Warp filter setting a `tokio::task::LocalKey`

Hi there,

I'm writing a logging framework which has the notion of a "context key" which represents a single process across multiple services. In Java world I would set a thread local capturing that context key at the boundary.

I understand there is an analog in Rust's threads, and Tokio seems to have an analog in tokio::task::LocalKey (tokio::task::LocalKey - Rust).

What I'm struggling to do is demystify Warp's filters sufficiently so that I can plug in a filter to an existing filter chain that sets this value. The thing I'm stumbling over is the callback nature of LocalKey which needs to be provided the future inside of the task_local! call site.

My current filter chain looks something like: warp::post().and(warp::path("something")).and(clone_state()).and(my_authentication()).and(second_filter()) etc. where my_authentication filter extracts the user object and explicitly passes it to the final handler.

This is fine, and I could have another filter which extracts the context key and adds that to the handler's signature and then have my handler call MY_TASK_LOCAL.scope(context_key, async move { actual_handler()}) but that gets messy fast.

What I'd like to do is write a filter which in essence does MY_TASK_LOCAL.scope(context_key, async move { filter_chain.continue() }), or some such thing so that the handler itself gets executed within the "scope" of MY_TASK_LOCAL set by the higher up filter.

Is this possible with Warp filters?

Thanks!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.