camel_api/transaction/join.rs
1//! Runtime join channels that bind a joined sql step to its block session.
2//!
3//! A `transacted { datasource }` block owns exactly one
4//! [`TransactionSession`]; every joined sql step inside the block must run on
5//! that session rather than auto-commit on a fresh connection. The binding is
6//! carried in two task-local cells because the pipeline runs a step on the
7//! block's own task, while the load-compiled step cannot hold a runtime
8//! `Arc`:
9//!
10//! - [`BLOCK_SESSION`] holds the [`BlockSession`] a segment installs for its
11//! body task: the datasource, the scope id of the enclosing block, and the
12//! session trait object;
13//! - [`JOIN_SCOPE`] holds the scope id baked into a joined sql step at load
14//! time.
15//!
16//! A joined sql step reads both cells, compares its baked [`JoinScope`] with
17//! the block's scope id, and only then joins. Scope membership is lexical, so
18//! a mismatch is a hard error rather than a silent join into another block's
19//! transaction.
20//!
21//! The cells are task-local on purpose: sibling branches of a split would
22//! otherwise observe the same session, which the port forbids (at most one
23//! concurrent join per session). Nothing here knows about `sqlx` or the SQL
24//! value model; the session stays a [`TransactionSession`] trait object that
25//! the sql component downcasts to its concrete type.
26
27use std::fmt;
28use std::future::Future;
29use std::sync::Arc;
30
31use super::TransactionSession;
32
33tokio::task_local! {
34 /// Block session installed by the enclosing transacted segment.
35 ///
36 /// Present only for the body task of a transacted block; absent means the
37 /// step runs outside any block and must not join. Read it through
38 /// [`current_block_session`] or install it with [`BlockSession::enter`].
39 pub static BLOCK_SESSION: BlockSession;
40
41 /// Join scope id baked into the current sql step at load time.
42 ///
43 /// Baked per joined step, not per block: the step compares this id with
44 /// [`BlockSession::scope`] to prove it is joining its own block. Read it
45 /// through [`JoinScope::current`].
46 pub static JOIN_SCOPE: u64;
47}
48
49/// The datasource, scope id, and session of one running transacted block.
50///
51/// A segment builds one per block entry and installs it for the body task
52/// through [`BlockSession::enter`]; joined steps then read it with
53/// [`current_block_session`]. Cloning is cheap: the datasource is shared and
54/// the session is an `Arc` (the block keeps its own handle for commit or
55/// rollback).
56#[derive(Clone)]
57pub struct BlockSession {
58 datasource: Arc<str>,
59 scope: JoinScope,
60 session: Arc<dyn TransactionSession>,
61}
62
63impl BlockSession {
64 /// Build the binding for a block on `datasource` in scope `scope`.
65 ///
66 /// `session` is the block's owned session handle, the same allocation the
67 /// block later commits or rolls back.
68 #[must_use]
69 pub fn new(
70 datasource: impl Into<Arc<str>>,
71 scope: JoinScope,
72 session: Arc<dyn TransactionSession>,
73 ) -> Self {
74 Self {
75 datasource: datasource.into(),
76 scope,
77 session,
78 }
79 }
80
81 /// Datasource the block is transacted on.
82 #[must_use]
83 pub fn datasource(&self) -> &str {
84 &self.datasource
85 }
86
87 /// Scope id of the enclosing block.
88 ///
89 /// A joined step compares this with its own baked [`JoinScope`]; equality
90 /// proves the step belongs to this block.
91 #[must_use]
92 pub fn scope(&self) -> JoinScope {
93 self.scope
94 }
95
96 /// The block's transaction session.
97 ///
98 /// Returned as a clone of the shared handle; the caller must still go
99 /// through the port (lazy `begin`, rollback-only marking) and must not
100 /// finalize it.
101 #[must_use]
102 pub fn session(&self) -> Arc<dyn TransactionSession> {
103 Arc::clone(&self.session)
104 }
105
106 /// Install `self` as [`BLOCK_SESSION`] for the task that polls `fut`.
107 ///
108 /// The binding ends when `fut` completes or is dropped, so nested blocks
109 /// shadow and unwrap without touching the outer binding.
110 pub async fn enter<F: Future>(self, fut: F) -> F::Output {
111 BLOCK_SESSION.scope(self, fut).await
112 }
113}
114
115impl fmt::Debug for BlockSession {
116 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
117 f.debug_struct("BlockSession")
118 .field("datasource", &self.datasource)
119 .field("scope", &self.scope)
120 .field("state", &self.session.state())
121 .finish_non_exhaustive()
122 }
123}
124
125/// Block scope id, baked per joined sql step and compared at join time.
126///
127/// The id is opaque: the loader assigns one per transacted block, bakes it
128/// into every joined step of that block, and the segment uses the same id when
129/// it installs the [`BlockSession`]. A step whose baked id differs from the
130/// running block's id is a [`super::TransactionError::JoinScopeMismatch`].
131#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
132pub struct JoinScope(u64);
133
134impl JoinScope {
135 /// Wrap a loader-assigned scope id.
136 #[must_use]
137 pub const fn new(id: u64) -> Self {
138 Self(id)
139 }
140
141 /// The raw scope id (for the typed error fields, which carry `u64`).
142 #[must_use]
143 pub const fn get(self) -> u64 {
144 self.0
145 }
146
147 /// Install `self` as [`JOIN_SCOPE`] for the task that polls `fut`.
148 ///
149 /// Used by a joined sql step to bake its load-time scope for work it
150 /// spawns, and by tests; the runtime segment installs [`BLOCK_SESSION`],
151 /// not this cell.
152 pub async fn set<F: Future>(self, fut: F) -> F::Output {
153 JOIN_SCOPE.scope(self.0, fut).await
154 }
155
156 /// The scope id baked into the current task, if any.
157 ///
158 /// `None` means the current task carries no baked scope: the step is not a
159 /// joined step, so it must not join a transaction.
160 #[must_use]
161 pub fn current() -> Option<Self> {
162 JOIN_SCOPE.try_with(|scope| Self(*scope)).ok()
163 }
164
165 /// Whether the current task's baked scope equals `self`.
166 ///
167 /// Shorthand for the join-time comparison: an absent scope is never a
168 /// match, so a non-joined step fails closed.
169 #[must_use]
170 pub fn scope_is(self) -> bool {
171 Self::current() == Some(self)
172 }
173}
174
175/// The [`BlockSession`] installed for the current task, if any.
176///
177/// `None` means the current task runs outside a transacted block body; a
178/// joined step must then fail with
179/// [`super::TransactionError::JoinSessionMissing`] instead of auto-committing.
180#[must_use]
181pub fn current_block_session() -> Option<BlockSession> {
182 BLOCK_SESSION.try_with(BlockSession::clone).ok()
183}
184
185#[cfg(test)]
186mod tests {
187 use std::sync::Arc;
188
189 use super::*;
190 use crate::transaction::tests::StubSession;
191
192 fn session() -> Arc<dyn TransactionSession> {
193 Arc::new(StubSession::new("pg"))
194 }
195
196 #[tokio::test]
197 async fn join_task_local_scopes_isolate() {
198 let outer = BlockSession::new("pg", JoinScope::new(1), session());
199 let inner = BlockSession::new("pg", JoinScope::new(2), session());
200
201 assert!(
202 current_block_session().is_none(),
203 "no block session is installed outside a block body"
204 );
205
206 outer
207 .clone()
208 .enter(async {
209 let running = current_block_session().expect("outer scope installs the session");
210 assert_eq!(running.scope(), JoinScope::new(1));
211 assert_eq!(running.datasource(), "pg");
212
213 inner
214 .clone()
215 .enter(async {
216 let running =
217 current_block_session().expect("inner scope installs the session");
218 assert_eq!(
219 running.scope(),
220 JoinScope::new(2),
221 "inner scope shadows the outer one inside its own task"
222 );
223 })
224 .await;
225
226 let running =
227 current_block_session().expect("the outer binding survives the inner scope");
228 assert_eq!(
229 running.scope(),
230 JoinScope::new(1),
231 "the inner scope must not leak past its future"
232 );
233 })
234 .await;
235
236 assert!(
237 current_block_session().is_none(),
238 "the binding ends with the block body"
239 );
240
241 // A spawned task starts with no inherited cell: joining is lexical,
242 // never ambient across a producer handoff.
243 outer
244 .enter(async {
245 tokio::spawn(async {
246 assert!(
247 current_block_session().is_none(),
248 "a spawned task must not inherit a block session"
249 );
250 })
251 .await // allow-test-wait: join of the test-spawned finite task; purely in-memory
252 .expect("spawned task completes");
253 })
254 .await;
255 }
256
257 #[tokio::test]
258 async fn join_scope_set_and_compare() {
259 assert_eq!(
260 JoinScope::current(),
261 None,
262 "no scope is baked outside a joined step"
263 );
264 assert!(!JoinScope::new(3).scope_is(), "absent scope never matches");
265
266 JoinScope::new(3)
267 .set(async {
268 assert_eq!(JoinScope::current(), Some(JoinScope::new(3)));
269 assert!(JoinScope::new(3).scope_is());
270 assert!(!JoinScope::new(4).scope_is());
271 })
272 .await;
273
274 assert_eq!(
275 JoinScope::current(),
276 None,
277 "the baked scope ends with its future"
278 );
279 assert_eq!(JoinScope::new(9).get(), 9);
280 }
281}