Skip to content

Add SetTaskLocal service + layer #821

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

Draft
wants to merge 3 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
Add a test
… and make it pass in a stupid way.
  • Loading branch information
jplatte committed Apr 23, 2025
commit 743ae1f81e99cbc89694f5aa9ab75e3e0e8babf3
8 changes: 7 additions & 1 deletion tower/src/task_local.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,12 @@ where
}

fn call(&mut self, req: R) -> Self::Future {
self.key.scope(self.value.clone(), self.inner.call(req))
// This is not great. I don't want to clone the value twice.
// Probably need to introduce a custom Future that delays calling
// inner.call until the local-key is set?
let fut = self
.key
.sync_scope(self.value.clone(), || self.inner.call(req));
self.key.scope(self.value.clone(), fut)
}
}
36 changes: 36 additions & 0 deletions tower/tests/task_local.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
#![cfg(all(feature = "task-local", feature = "util"))]

use futures::pin_mut;
use tower::{util::ServiceExt, Service as _};
use tower_test::{assert_request_eq, mock};

mod support;

tokio::task_local! {
static NUM: i32;
}

#[tokio::test]
async fn set_task_local() {
let _t = support::trace_init();

let (service, handle) = mock::pair();
pin_mut!(handle);

let mut client = service
.map_request(|()| {
assert_eq!(NUM.get(), 9000);
})
.map_response(|()| {
assert_eq!(NUM.get(), 9000);
})
.set_task_local(&NUM, 9000);

// allow a request through
handle.allow(1);

let ready = client.ready().await.unwrap();
let fut = ready.call(());
assert_request_eq!(handle, ()).send_response(());
fut.await.unwrap();
}