tower-rs / tower-http

HTTP specific Tower utilities.
680 stars 159 forks source link

Add propagate_extensions middleware #425

Open bassmanitram opened 10 months ago

bassmanitram commented 10 months ago

(See issue #423 )

This middleware is intended to be used as a way of sharing state between "pre service" layers/filters etc and those that run "post service", particularly when the service itself is unaware of that state.

This is in fact, almost a verbatim copy of propagate_header, replacing the Header semantics with those required by http::Extensions.

For ease of implementation it removes the state from the request before the inner service is invoked, and inserts the state into the response when the response is ready.

It does not concern itself with the initial insert of the state into the request since that is covered by an existing middleware, and may also be achieved by other means in one of the "pre service" components.

Because Extensions are managed by type, both the layer and the underlying service have to be generic over the type of the user's state object - and that type has to be cloneable as well as Send and Sync. In order to keep the compiler happy, both the service and the layer have a phantom data field. I am not 100% sure that this is necessary, but it does seem to be one of the few safe code instances where it probably is.