use std::fmt;
use std::future::Future;
use std::sync::Arc;
use super::TransactionSession;
tokio::task_local! {
pub static BLOCK_SESSION: BlockSession;
pub static JOIN_SCOPE: u64;
}
#[derive(Clone)]
pub struct BlockSession {
datasource: Arc<str>,
scope: JoinScope,
session: Arc<dyn TransactionSession>,
}
impl BlockSession {
#[must_use]
pub fn new(
datasource: impl Into<Arc<str>>,
scope: JoinScope,
session: Arc<dyn TransactionSession>,
) -> Self {
Self {
datasource: datasource.into(),
scope,
session,
}
}
#[must_use]
pub fn datasource(&self) -> &str {
&self.datasource
}
#[must_use]
pub fn scope(&self) -> JoinScope {
self.scope
}
#[must_use]
pub fn session(&self) -> Arc<dyn TransactionSession> {
Arc::clone(&self.session)
}
pub async fn enter<F: Future>(self, fut: F) -> F::Output {
BLOCK_SESSION.scope(self, fut).await
}
}
impl fmt::Debug for BlockSession {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("BlockSession")
.field("datasource", &self.datasource)
.field("scope", &self.scope)
.field("state", &self.session.state())
.finish_non_exhaustive()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct JoinScope(u64);
impl JoinScope {
#[must_use]
pub const fn new(id: u64) -> Self {
Self(id)
}
#[must_use]
pub const fn get(self) -> u64 {
self.0
}
pub async fn set<F: Future>(self, fut: F) -> F::Output {
JOIN_SCOPE.scope(self.0, fut).await
}
#[must_use]
pub fn current() -> Option<Self> {
JOIN_SCOPE.try_with(|scope| Self(*scope)).ok()
}
#[must_use]
pub fn scope_is(self) -> bool {
Self::current() == Some(self)
}
}
#[must_use]
pub fn current_block_session() -> Option<BlockSession> {
BLOCK_SESSION.try_with(BlockSession::clone).ok()
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use super::*;
use crate::transaction::tests::StubSession;
fn session() -> Arc<dyn TransactionSession> {
Arc::new(StubSession::new("pg"))
}
#[tokio::test]
async fn join_task_local_scopes_isolate() {
let outer = BlockSession::new("pg", JoinScope::new(1), session());
let inner = BlockSession::new("pg", JoinScope::new(2), session());
assert!(
current_block_session().is_none(),
"no block session is installed outside a block body"
);
outer
.clone()
.enter(async {
let running = current_block_session().expect("outer scope installs the session");
assert_eq!(running.scope(), JoinScope::new(1));
assert_eq!(running.datasource(), "pg");
inner
.clone()
.enter(async {
let running =
current_block_session().expect("inner scope installs the session");
assert_eq!(
running.scope(),
JoinScope::new(2),
"inner scope shadows the outer one inside its own task"
);
})
.await;
let running =
current_block_session().expect("the outer binding survives the inner scope");
assert_eq!(
running.scope(),
JoinScope::new(1),
"the inner scope must not leak past its future"
);
})
.await;
assert!(
current_block_session().is_none(),
"the binding ends with the block body"
);
outer
.enter(async {
tokio::spawn(async {
assert!(
current_block_session().is_none(),
"a spawned task must not inherit a block session"
);
})
.await .expect("spawned task completes");
})
.await;
}
#[tokio::test]
async fn join_scope_set_and_compare() {
assert_eq!(
JoinScope::current(),
None,
"no scope is baked outside a joined step"
);
assert!(!JoinScope::new(3).scope_is(), "absent scope never matches");
JoinScope::new(3)
.set(async {
assert_eq!(JoinScope::current(), Some(JoinScope::new(3)));
assert!(JoinScope::new(3).scope_is());
assert!(!JoinScope::new(4).scope_is());
})
.await;
assert_eq!(
JoinScope::current(),
None,
"the baked scope ends with its future"
);
assert_eq!(JoinScope::new(9).get(), 9);
}
}