Skip to content

feature: expose redirect policy through extension #583

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 29 additions & 2 deletions tower-http/src/follow_redirect/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,7 @@ impl<ReqBody, ResBody, S, P> Service<Request<ReqBody>> for FollowRedirect<S, P>
where
S: Service<Request<ReqBody>, Response = Response<ResBody>> + Clone,
ReqBody: Body + Default,
P: Policy<ReqBody, S::Error> + Clone,
P: Policy<ReqBody, S::Error> + Clone + Send + Sync + 'static,
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This would be considered breaking changes, since some types might not fit the bounds.

Can we insert a custom extension without the need to change this layer?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure what you mean by layer ? the tower middleware Layer ?

The extra constraints come from the signature of http::extensions::Extensions

pub fn insert<T: Clone + Send + Sync + 'static>(&mut self, val: T) -> Option<T> 

Copy link
Author

@unusual-thoughts unusual-thoughts Jun 12, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One way to avoid the breaking change would be something like:

trait MaybeAddExtension {
    fn add_policy_ext<ResBody>(&self, _res: &mut Response<ResBody>) {}
}

impl<T> MaybeAddExtension for T
where
    T: Clone + Send + Sync + 'static,
{
    fn add_policy_ext<ResBody>(&self, res: &mut Response<ResBody>) {
        res.extensions_mut().insert(FollowedPolicy(self.clone()));
    }
}

and then we can have

-    P: Policy<ReqBody, S::Error> + Clone,
+    P: Policy<ReqBody, S::Error> + Clone + MaybeAddExtension,

         res.extensions_mut().insert(RequestUri(this.uri.clone()));
+        this.policy.add_policy_ext(&mut res);

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You'd still be adding a bound where there wasn't one before, it would be exactly the same breaking change. The problem is somebody could have implemented a custom policy that's not Send or not Sync, and passed that to with_policy. The change to this line would then result in FollowRedirect<_, CustomPolicy> no longer implementing Service.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

oh you're right, somehow I mistakenly thought that the default empty implementation would be generated for non-Sync/Send policies.
So is the only way to avoid the breaking change to define a second layer variant that adds the extension?

{
type Response = Response<ResBody>;
type Error = S::Error;
Expand Down Expand Up @@ -250,14 +250,16 @@ impl<S, ReqBody, ResBody, P> Future for ResponseFuture<S, ReqBody, P>
where
S: Service<Request<ReqBody>, Response = Response<ResBody>> + Clone,
ReqBody: Body + Default,
P: Policy<ReqBody, S::Error>,
P: Policy<ReqBody, S::Error> + Clone + Send + Sync + 'static,
{
type Output = Result<Response<ResBody>, S::Error>;

fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let mut this = self.project();
let mut res = ready!(this.future.as_mut().poll(cx)?);
res.extensions_mut().insert(RequestUri(this.uri.clone()));
res.extensions_mut()
.insert(FollowedPolicy(this.policy.clone()));

let drop_payload_headers = |headers: &mut HeaderMap| {
for header in &[
Expand Down Expand Up @@ -342,6 +344,11 @@ where
#[derive(Clone)]
pub struct RequestUri(pub Uri);

/// Response [`Extensions`][http::Extensions] value that contains the redirect [`Policy`] that
/// was run before the last request of the redirect chain by a [`FollowRedirect`] middleware.
#[derive(Clone)]
pub struct FollowedPolicy<P>(pub P);

#[derive(Debug)]
enum BodyRepr<B> {
Some(B),
Expand Down Expand Up @@ -423,6 +430,12 @@ mod tests {
res.extensions().get::<RequestUri>().unwrap().0,
"http://example.com/0"
);
assert!(res
.extensions()
.get::<FollowedPolicy<Action>>()
.unwrap()
.0
.is_follow());
}

#[tokio::test]
Expand All @@ -441,6 +454,12 @@ mod tests {
res.extensions().get::<RequestUri>().unwrap().0,
"http://example.com/42"
);
assert!(res
.extensions()
.get::<FollowedPolicy<Action>>()
.unwrap()
.0
.is_stop());
}

#[tokio::test]
Expand All @@ -459,6 +478,14 @@ mod tests {
res.extensions().get::<RequestUri>().unwrap().0,
"http://example.com/32"
);
assert_eq!(
res.extensions()
.get::<FollowedPolicy<Limited>>()
.unwrap()
.0
.remaining,
0
);
}

/// A server with an endpoint `GET /{n}` which redirects to `/{n-1}` unless `n` equals zero,
Expand Down
2 changes: 1 addition & 1 deletion tower-http/src/follow_redirect/policy/limited.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use super::{Action, Attempt, Policy};
/// A redirection [`Policy`] that limits the number of successive redirections.
#[derive(Clone, Copy, Debug)]
pub struct Limited {
remaining: usize,
pub(crate) remaining: usize,
}

impl Limited {
Expand Down
Loading