tower-rs / tower-http

HTTP specific Tower utilities.
680 stars 159 forks source link

A means to propagate state between the layers that run before the service function, and those that run after. #423

Open bassmanitram opened 11 months ago

bassmanitram commented 11 months ago

Feature Request

A middleware 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.

Motivation

The concrete motivation in my case is the "as lite-a-touch-as-possible" approach to wrapping AWS Lambda functions (eventually in any language, but initially in Rust) with layers that enforce our enterprise policy and aid in homogenizing the interface that the Lambda function is written to - specifically for AWS API Gateway API invocations.

These layers examine the request and need to set various state values that are then used by the layers that run after the Lambda function has returned. The problem is, of course, that the Lambda function consumes the request and produces a response.

The propagate_header middleware is addressing a very similar use case for headers.

Proposal

Effectively, copy the propagate_header middleware and change its semantics to be those of http::Request and Response extensions!

Alternatives

There are of course many ways that Layer developers might be able to propagate such state when necessary - but they all rely on the same need - to save the state off "somewhere" when invoking the request/response service and retrieve when the response is ready. This scheme of exploiting the request and response extensions mechanism within a propagation middleware is an extremely convenient way to achieve this in a generic fashion.

I am in the process of creating this middleware - see PR #425