camel_api/transaction.rs
1//! Provider-neutral transaction port for `transacted { datasource }` blocks.
2//!
3//! This module is the `camel-api` half of the sql-transactions capability: it
4//! defines the object-safe [`TransactionManager`] / [`TransactionSession`]
5//! surface, the [`TransactionState`] lifecycle machine, the
6//! [`TransactionOutcome`] finalization result, and the typed
7//! [`TransactionError`] family. The port is implemented by the sql component
8//! (slice 2) and resolved by datasource name from a `camel-core` registry;
9//! `camel-api` carries no driver or SQL value model.
10//!
11//! The surface is deliberately final for slice 2: lazy begin, the rollback-only
12//! flag, finalization outcomes, and `#[non_exhaustive]` error/outcome types are
13//! all present here, so adding execution and registry wiring needs no signature
14//! change. Sessions are `'static` trait objects so the implementing crate can
15//! downcast to its concrete session for statement execution.
16//!
17//! The [`join`] submodule carries the runtime join channels (a `task_local!`
18//! block-session cell and the baked join scope) that bind a joined sql step to
19//! the block session it must run inside.
20
21pub mod join;
22
23use std::any::Any;
24use std::future::Future;
25use std::pin::Pin;
26use std::sync::Arc;
27use std::time::Duration;
28
29use thiserror::Error;
30
31/// Lifecycle state of a [`TransactionSession`].
32///
33/// The session tracks the state explicitly rather than inferring it from the
34/// borrow of a guard: `Fresh → Active → Finalizing → Done | Detached`.
35/// `Fresh` means no `BEGIN` has been sent yet (begin is lazy, per the
36/// sql-transactions requirement "Lazy begin and block-owned commit/rollback"),
37/// `Finalizing` covers an in-flight `COMMIT`/`ROLLBACK`, and `Detached` records
38/// a connection that was discarded instead of returned to the pool (requirement
39/// "Uncertain finalization detaches the connection").
40#[derive(Debug, Clone, Copy, PartialEq, Eq)]
41#[non_exhaustive]
42pub enum TransactionState {
43 /// No statement has been sent on the session yet; `BEGIN` is lazy.
44 Fresh,
45 /// `BEGIN` was acknowledged and the session accepts joined work.
46 Active,
47 /// A `COMMIT` or `ROLLBACK` is in flight; no new joined work is admitted.
48 Finalizing,
49 /// Finalization completed and the session holds no transaction.
50 Done,
51 /// The backing connection was discarded; the session is unusable.
52 Detached,
53}
54
55/// Result of finalizing a [`TransactionSession`].
56///
57/// Returned by [`TransactionSession::commit`] and
58/// [`TransactionSession::rollback`]; `#[non_exhaustive]` so slice 2 can add
59/// outcomes without breaking implementors. [`TransactionOutcome::Detached`] is
60/// the observable counterpart of a connection that was dropped rather than
61/// returned to the pool (requirement "Uncertain finalization detaches the
62/// connection").
63#[derive(Debug, Clone, Copy, PartialEq, Eq)]
64#[non_exhaustive]
65pub enum TransactionOutcome {
66 /// `COMMIT` was acknowledged by the database.
67 Committed,
68 /// `ROLLBACK` was acknowledged by the database.
69 RolledBack,
70 /// Finalization could not be acknowledged and the connection was discarded.
71 Detached,
72}
73
74/// Typed transaction failures for load-time validation and runtime finalization.
75///
76/// Every variant names the offender (step or statement) and, where one exists,
77/// the datasource, so operators can discriminate programmatically. The variants
78/// map one-to-one onto the sql-transactions requirements named in each doc
79/// comment. `#[non_exhaustive]` lets slice 2 grow the family without a breaking
80/// change.
81#[derive(Debug, Clone, PartialEq, Eq, Error)]
82#[non_exhaustive]
83pub enum TransactionError {
84 /// No [`TransactionManager`] is registered for the block datasource.
85 ///
86 /// Serves the requirement "Load-time validation is fail-closed and typed"
87 /// (unknown datasource with no registered TransactionManager) and the
88 /// requirement "TransactionManager port and registry resolution"
89 /// (fail closed, named error).
90 #[error("no TransactionManager for datasource '{datasource}'")]
91 ManagerMissing {
92 /// Datasource named by the transacted block.
93 datasource: String,
94 },
95
96 /// A parallel split reaches a joined sql step inside the block.
97 ///
98 /// Serves the requirement "Load-time validation is fail-closed and typed".
99 #[error(
100 "parallel split step '{step}' inside a transacted block on datasource '{datasource}' \
101 cannot join the transaction"
102 )]
103 ParallelInBlock {
104 /// The split step that escapes the transaction scope.
105 step: String,
106 /// Datasource of the enclosing transacted block.
107 datasource: String,
108 },
109
110 /// A multicast reaches a joined sql step inside the block.
111 ///
112 /// Serves the requirement "Load-time validation is fail-closed and typed".
113 #[error(
114 "multicast step '{step}' inside a transacted block on datasource '{datasource}' \
115 cannot join the transaction"
116 )]
117 MulticastInBlock {
118 /// The multicast step that escapes the transaction scope.
119 step: String,
120 /// Datasource of the enclosing transacted block.
121 datasource: String,
122 },
123
124 /// A wire tap reaches a joined sql step inside the block.
125 ///
126 /// Serves the requirement "Load-time validation is fail-closed and typed".
127 #[error(
128 "wireTap step '{step}' inside a transacted block on datasource '{datasource}' \
129 cannot join the transaction"
130 )]
131 WireTapInBlock {
132 /// The wire-tap step that escapes the transaction scope.
133 step: String,
134 /// Datasource of the enclosing transacted block.
135 datasource: String,
136 },
137
138 /// An asynchronous producer handoff reaches a joined sql step inside the block.
139 ///
140 /// Serves the requirement "Load-time validation is fail-closed and typed".
141 #[error(
142 "async handoff at step '{step}' inside a transacted block on datasource '{datasource}' \
143 cannot join the transaction"
144 )]
145 AsyncInBlock {
146 /// The step whose producer scheme hands the exchange to another task.
147 step: String,
148 /// Datasource of the enclosing transacted block.
149 datasource: String,
150 },
151
152 /// A `seda:` handoff reaches a joined sql step inside the block.
153 ///
154 /// Serves the requirement "Load-time validation is fail-closed and typed".
155 #[error(
156 "seda handoff at step '{step}' inside a transacted block on datasource '{datasource}' \
157 cannot join the transaction"
158 )]
159 SedaInBlock {
160 /// The step that hands the exchange to a seda queue.
161 step: String,
162 /// Datasource of the enclosing transacted block.
163 datasource: String,
164 },
165
166 /// A sql step produces a `StreamList` anywhere inside the block.
167 ///
168 /// Rejected unconditionally (no consumer step needs to be present); serves
169 /// the requirement "Load-time validation is fail-closed and typed".
170 #[error(
171 "sql step '{step}' uses outputType=StreamList inside a transacted block \
172 on datasource '{datasource}'"
173 )]
174 StreamListInBlock {
175 /// The sql step producing the stream.
176 step: String,
177 /// Datasource of the enclosing transacted block.
178 datasource: String,
179 },
180
181 /// A sql step inside the block targets a different datasource.
182 ///
183 /// Serves the requirement "Load-time validation is fail-closed and typed"
184 /// (no 2PC across datasources).
185 #[error(
186 "sql step '{step}' targets datasource '{step_datasource}' but the transacted block \
187 is on datasource '{block_datasource}' (no two-phase commit)"
188 )]
189 ForeignDatasource {
190 /// The sql step on the foreign datasource.
191 step: String,
192 /// Datasource of the enclosing transacted block.
193 block_datasource: String,
194 /// Datasource the offending sql step targets.
195 step_datasource: String,
196 },
197
198 /// A sql step inside the block has no named datasource.
199 ///
200 /// Inline `db_url` cannot join a block-owned transaction; serves the
201 /// requirement "Load-time validation is fail-closed and typed".
202 #[error(
203 "sql step '{step}' inside a transacted block has no named datasource \
204 (inline db_url cannot join the block transaction)"
205 )]
206 UnnamedDatasource {
207 /// The sql step missing the `datasource` parameter.
208 step: String,
209 },
210
211 /// A `transacted` block is nested inside another one.
212 ///
213 /// Serves the requirement "Load-time validation is fail-closed and typed".
214 #[error("transacted block on datasource '{inner}' is nested inside another transacted block")]
215 NestedBlock {
216 /// Datasource of the inner (nested) block.
217 inner: String,
218 },
219
220 /// Joined SQL was refused because the session is aborted.
221 ///
222 /// Serves the requirement "Handled joined DB errors are rollback-only":
223 /// after the database aborted the transaction, no further statement may run.
224 #[error("transaction session on datasource '{datasource}' was aborted")]
225 SessionAborted {
226 /// Datasource of the aborted session.
227 datasource: String,
228 },
229
230 /// The block body returned `Ok` after a joined DB error was handled.
231 ///
232 /// Serves the requirement "Handled joined DB errors are rollback-only":
233 /// the server may have aborted the transaction, so a commit path must never
234 /// report `Committed`.
235 #[error(
236 "transacted block on datasource '{datasource}' handled a joined database error; \
237 the session is rollback-only"
238 )]
239 AbortedByHandledError {
240 /// Datasource of the rollback-only session.
241 datasource: String,
242 },
243
244 /// A `COMMIT` acknowledgment was lost or unreadable.
245 ///
246 /// Serves the requirement "Cancellation cutoff": an unacknowledged `COMMIT`
247 /// is reported as uncertain and never as a rollback.
248 #[error(
249 "commit on datasource '{datasource}' is uncertain: the database did not acknowledge it"
250 )]
251 CommitUncertain {
252 /// Datasource whose commit is uncertain.
253 datasource: String,
254 },
255
256 /// The database rejected the `COMMIT`.
257 ///
258 /// Serves the requirement "Cancellation cutoff": a rejected `COMMIT` is a
259 /// typed failure, never a reported rollback.
260 #[error("commit on datasource '{datasource}' failed: {reason}")]
261 CommitFailed {
262 /// Datasource whose commit failed.
263 datasource: String,
264 /// Driver-reported failure detail.
265 reason: String,
266 },
267
268 /// A `ROLLBACK` could not be acknowledged.
269 ///
270 /// Serves the requirement "Uncertain finalization detaches the connection":
271 /// the connection is discarded and the outcome is `Detached`.
272 #[error(
273 "rollback on datasource '{datasource}' is uncertain: the database did not acknowledge it"
274 )]
275 RollbackUncertain {
276 /// Datasource whose rollback is uncertain.
277 datasource: String,
278 },
279
280 /// Connection acquisition exhausted the pool within the acquire deadline.
281 ///
282 /// Serves the requirement "Pool exhaustion is bounded and named".
283 #[error(
284 "no connection available for datasource '{datasource}' after waiting {waited_ms} ms \
285 (max_connections={max_connections})"
286 )]
287 PoolExhausted {
288 /// Datasource whose pool is exhausted.
289 datasource: String,
290 /// Configured pool size at the time of the failure.
291 max_connections: u32,
292 /// Time spent waiting for a connection.
293 waited_ms: u64,
294 },
295
296 /// Block execution exceeded its deadline.
297 ///
298 /// Serves the requirement "Block timeout".
299 #[error("transacted block on datasource '{datasource}' timed out after {elapsed_ms} ms")]
300 Timeout {
301 /// Datasource of the timed-out block.
302 datasource: String,
303 /// Time elapsed before the deadline fired.
304 elapsed_ms: u64,
305 },
306
307 /// The session's single execution slot is already held.
308 ///
309 /// Serves the requirement "Busy block session" (at most one concurrent join
310 /// per session).
311 #[error("transaction session on datasource '{datasource}' is busy")]
312 Busy {
313 /// Datasource of the busy session.
314 datasource: String,
315 },
316
317 /// A baked join has no transaction session to join at runtime.
318 ///
319 /// Serves the requirement "Join semantics for sql steps on the block
320 /// datasource"; the step must fail rather than auto-commit.
321 #[error("joined sql step on datasource '{datasource}' has no transaction session")]
322 JoinSessionMissing {
323 /// Datasource the step expected to join.
324 datasource: String,
325 },
326
327 /// A baked join resolved to a different transaction scope at runtime.
328 ///
329 /// Serves the requirement "Join semantics for sql steps on the block
330 /// datasource"; scope membership is lexical, so a mismatch is a hard error.
331 #[error(
332 "transaction join scope mismatch on datasource '{datasource}': \
333 expected scope {expected_scope}, found scope {found_scope}"
334 )]
335 JoinScopeMismatch {
336 /// Datasource the step expected to join.
337 datasource: String,
338 /// Scope id baked at load time.
339 expected_scope: u64,
340 /// Scope id of the session actually found at runtime.
341 found_scope: u64,
342 },
343
344 /// A joined sql step's SQL comes from a runtime source (header/body/file).
345 ///
346 /// Serves the requirement "Join semantics for sql steps on the block
347 /// datasource": a joined step's SQL is static, route-configured text.
348 #[error("joined sql step '{step}' uses a runtime SQL source")]
349 RuntimeSqlInJoinedStep {
350 /// The step whose SQL is not statically known.
351 step: String,
352 },
353
354 /// A joined sql step issues a transaction-control or implicit-commit statement.
355 ///
356 /// Serves the requirement "Join semantics for sql steps on the block
357 /// datasource" (`BEGIN`/`COMMIT`/`ROLLBACK`/`SAVEPOINT` and equivalents
358 /// inside a joined step are rejected at load).
359 #[error("joined sql step '{step}' issues transaction-control statement '{statement}'")]
360 TransactionControlSql {
361 /// The offending sql step.
362 step: String,
363 /// The statement text that was rejected.
364 statement: String,
365 },
366
367 /// The loader cannot prove the transaction semantics of a URL scheme.
368 ///
369 /// Serves the requirement "Join semantics for sql steps on the block
370 /// datasource": dialect identity comes from the URL scheme, so an
371 /// unrecognized scheme fails closed.
372 #[error("cannot prove transaction semantics for URL scheme '{scheme}'")]
373 DialectUnprovable {
374 /// URL scheme whose dialect could not be resolved.
375 scheme: String,
376 },
377
378 /// The resolved dialect does not support joined transactions in v1.
379 ///
380 /// Serves the requirement "Join semantics for sql steps on the block
381 /// datasource": joined steps are PostgreSQL-only in v1.
382 #[error(
383 "dialect '{dialect}' on datasource '{datasource}' does not support joined transactions"
384 )]
385 UnsupportedJoinDialect {
386 /// Resolved dialect name (e.g. `mysql`, `sqlite`).
387 dialect: String,
388 /// Datasource of the offending block.
389 datasource: String,
390 },
391
392 /// An in-block dynamic routing target was rejected at load.
393 ///
394 /// Serves the requirement "Join semantics for sql steps on the block
395 /// datasource": a step whose destination is computed from the exchange
396 /// (recipient list, routing slip, dynamic router) cannot prove block
397 /// membership statically, so a transacted block containing one is
398 /// rejected at load.
399 #[error(
400 "dynamic routing target at step '{step}' inside a transacted block \
401 cannot prove transaction membership"
402 )]
403 DynamicTargetUnprovable {
404 /// The dynamic-routing step inside the block.
405 step: String,
406 },
407}
408
409/// Boxed future resolving to a new [`TransactionSession`].
410///
411/// Hand-typed like [`crate::datasource::GetPoolFuture`] so the trait stays
412/// object safe without an `async_trait` dependency.
413pub type OpenSessionFuture<'a> = Pin<
414 Box<dyn Future<Output = Result<Arc<dyn TransactionSession>, TransactionError>> + Send + 'a>,
415>;
416
417/// Boxed future for the lazy `BEGIN` of a [`TransactionSession`].
418pub type BeginFuture<'a> = Pin<Box<dyn Future<Output = Result<(), TransactionError>> + Send + 'a>>;
419
420/// Boxed future for finalizing a [`TransactionSession`].
421///
422/// Resolves to the observed [`TransactionOutcome`] so the caller can
423/// distinguish an acknowledged commit/rollback from a detached connection.
424pub type FinalizeFuture<'a> =
425 Pin<Box<dyn Future<Output = Result<TransactionOutcome, TransactionError>> + Send + 'a>>;
426
427/// Provider-neutral factory for transaction sessions on one datasource.
428///
429/// Implemented by the sql component (slice 2) and resolved by datasource
430/// name from the `camel-core` registry. `camel-api` never sees a driver or a
431/// SQL value model: slice 2 keeps statement execution in its own extension
432/// trait over the concrete session type.
433///
434/// `Send + Sync + 'static` lets the registry hold the manager in an `Arc` and
435/// share it across workers. [`TransactionManager::open_session`] returns a
436/// boxed future so the trait object is object safe. The [`Any`] supertrait
437/// lets boot-time registration tests recover the concrete manager from the
438/// registry by trait-object upcast, exactly like [`TransactionSession`]; it is
439/// auto-implemented, so implementors carry no extra burden.
440pub trait TransactionManager: Any + Send + Sync + 'static {
441 /// Datasource name this manager serves.
442 ///
443 /// The registry keys managers by this name, and load validation reports it
444 /// in every typed error.
445 fn datasource(&self) -> &str;
446
447 /// Open a session on this manager's datasource.
448 ///
449 /// Opening borrows a pooled connection but SHALL NOT send `BEGIN`: begin is
450 /// lazy and driven by [`TransactionSession::begin`] at the first joined sql
451 /// step. Registry resolution failures surface as
452 /// [`TransactionError::ManagerMissing`] before this method is reached.
453 fn open_session(&self) -> OpenSessionFuture<'_>;
454
455 /// Bound for connection acquisition, normally the datasource
456 /// `acquire_timeout`.
457 ///
458 /// Slice 2 compares this deadline with the block timeout and reports the
459 /// deadline that elapses first (requirement "Pool exhaustion is bounded and
460 /// named", "Block timeout").
461 fn acquire_deadline(&self) -> Duration;
462}
463
464/// One block-owned transaction on one datasource.
465///
466/// A session owns (or guards) its pooled connection for the whole block, so
467/// every joined sql step on the block datasource shares one transaction
468/// (requirement "Join semantics for sql steps on the block datasource"). The
469/// session is `'static` so the implementing crate can downcast the trait object
470/// to its concrete type for statement execution without `camel-api` gaining a
471/// SQL value model.
472///
473/// The [`Any`] supertrait makes that downcast a trait-object upcast: an
474/// `Arc<dyn TransactionSession>` coerces to `Arc<dyn Any + Send + Sync>` and
475/// [`Arc::downcast`](std::sync::Arc::downcast) recovers the concrete session
476/// type. `Any` is auto-implemented, so implementors carry no extra burden.
477pub trait TransactionSession: Any + Send + Sync + 'static {
478 /// Datasource this session runs on.
479 fn datasource(&self) -> &str;
480
481 /// Current lifecycle state.
482 ///
483 /// Slice 2 relies on the explicit machine (`Fresh → Active → Finalizing →
484 /// Done | Detached`) rather than inferring state from a borrow.
485 fn state(&self) -> TransactionState;
486
487 /// Send the lazy `BEGIN`.
488 ///
489 /// Called at the first joined sql step, not when the session opens.
490 /// Precondition `Clean`; `Ok(())` if already `Open` (idempotent);
491 /// `Err(SessionAborted)` otherwise. A begin that arrives while the
492 /// session's execution slot is held is rejected with the typed `Busy`
493 /// error. The owner SHALL call `begin` only
494 /// from the `Clean` state or to observe an already-open session, and
495 /// admission hygiene must have been acknowledged before the first
496 /// `BEGIN` (requirement "Lazy begin and block-owned commit/rollback").
497 fn begin(&self) -> BeginFuture<'_>;
498
499 /// Mark the session rollback-only.
500 ///
501 /// Slice 2 calls this before returning a joined database error to the
502 /// pipeline (requirement "Handled joined DB errors are rollback-only"), so a
503 /// handled error can never commit a server-aborted transaction.
504 fn set_rollback_only(&self);
505
506 /// Whether the session has been marked rollback-only.
507 fn is_rollback_only(&self) -> bool;
508
509 /// Commit the block's transaction.
510 ///
511 /// Returns the observed [`TransactionOutcome`]; slice 2 relies on the
512 /// outcome (not just `Ok`) to distinguish an acknowledged commit from a
513 /// detached connection (requirement "Cancellation cutoff", "Uncertain
514 /// finalization detaches the connection").
515 ///
516 /// Precondition `Active`. Otherwise no SQL is sent and the call returns
517 /// `Err(SessionAborted)`. The owner SHALL call `commit` only when
518 /// `state() == Active`.
519 fn commit(&self) -> FinalizeFuture<'_>;
520
521 /// End the block without committing. Total over every lifecycle state; the
522 /// implementation selects the action from its private phase:
523 /// - nothing begun (`Fresh`, BEGIN never sent): no SQL, connection returned
524 /// clean, `Ok(RolledBack)` (nothing was begun, so nothing is durable);
525 /// - BEGIN sent but unacknowledged (`Fresh`): no SQL, detach,
526 /// `Err(RollbackUncertain)`;
527 /// - `Active`: ROLLBACK within the finalize grace; acknowledged →
528 /// `Ok(RolledBack)`, else detach + `Err(RollbackUncertain)`;
529 /// - `Detached`, or a defensive `Finalizing`/`Done` entry: no SQL,
530 /// `Err(RollbackUncertain)` (`error!` log for the defensive entry).
531 fn rollback(&self) -> FinalizeFuture<'_>;
532}
533
534#[cfg(test)]
535mod tests {
536 use std::any::Any;
537 use std::sync::Arc;
538 use std::sync::atomic::{AtomicBool, Ordering};
539
540 use super::*;
541
542 /// Minimal concrete port implementation used by the port tests.
543 ///
544 /// Every method resolves without I/O: the tests exercise the trait-object
545 /// surface (upcast/downcast) and the doc contract, not execution.
546 pub(super) struct StubSession {
547 datasource: String,
548 state: TransactionState,
549 rollback_only: AtomicBool,
550 }
551
552 impl StubSession {
553 pub(super) fn new(datasource: &str) -> Self {
554 Self {
555 datasource: datasource.to_owned(),
556 state: TransactionState::Active,
557 rollback_only: AtomicBool::new(false),
558 }
559 }
560 }
561
562 impl TransactionSession for StubSession {
563 fn datasource(&self) -> &str {
564 &self.datasource
565 }
566
567 fn state(&self) -> TransactionState {
568 self.state
569 }
570
571 fn begin(&self) -> BeginFuture<'_> {
572 Box::pin(std::future::ready(Ok(())))
573 }
574
575 fn set_rollback_only(&self) {
576 self.rollback_only.store(true, Ordering::Relaxed);
577 }
578
579 fn is_rollback_only(&self) -> bool {
580 self.rollback_only.load(Ordering::Relaxed)
581 }
582
583 fn commit(&self) -> FinalizeFuture<'_> {
584 Box::pin(std::future::ready(Ok(TransactionOutcome::Committed)))
585 }
586
587 fn rollback(&self) -> FinalizeFuture<'_> {
588 Box::pin(std::future::ready(Ok(TransactionOutcome::RolledBack)))
589 }
590 }
591
592 // Compile-time proof that both port traits are usable as trait objects.
593 #[test]
594 fn port_traits_are_object_safe() {
595 fn _assert(_m: &dyn TransactionManager, _s: &dyn TransactionSession) {}
596 }
597
598 #[test]
599 fn session_port_upcasts_to_any_and_downcasts() {
600 let concrete = Arc::new(StubSession::new("pg"));
601 let port: Arc<dyn TransactionSession> = concrete.clone();
602
603 // The `Any` supertrait makes the erase explicit: a trait-object upcast
604 // to `dyn Any`, no wrapper and no per-implementor method.
605 let erased: Arc<dyn Any + Send + Sync> = port;
606
607 let restored = Arc::downcast::<StubSession>(erased)
608 .expect("the session trait object must downcast to its concrete type");
609 assert_eq!(restored.datasource(), "pg");
610 assert!(
611 Arc::ptr_eq(&concrete, &restored),
612 "downcast must recover the same allocation, not a copy"
613 );
614 }
615
616 #[test]
617 fn rollback_doc_carries_total_contract() {
618 // Source-text assertion: the 604d contract is docs-only, so the review
619 // gate is the doc text itself. Only the production half of the file is
620 // searched: the phrases below also appear as literals in this test's
621 // own arrays, so a whole-file read would pass with every `///` doc
622 // stripped. `///` / `//!` markers are removed line-wise and whitespace
623 // is normalised so the test tracks prose, not the exact doc wrapping.
624 let source =
625 std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/src/transaction.rs"))
626 .expect("camel-api source tree is present at test time");
627 let production = source
628 .split("#[cfg(test)]")
629 .next()
630 .unwrap_or("")
631 .lines()
632 .map(|line| {
633 let line = line.trim();
634 line.strip_prefix("///")
635 .or_else(|| line.strip_prefix("//!"))
636 .unwrap_or(line)
637 })
638 .collect::<Vec<_>>()
639 .join(" ");
640 let production = production.split_whitespace().collect::<Vec<_>>().join(" ");
641 assert!(
642 !production.is_empty(),
643 "the production half of transaction.rs must be non-empty"
644 );
645
646 for phrase in [
647 "Total over every lifecycle state",
648 "nothing begun (`Fresh`, BEGIN never sent)",
649 "BEGIN sent but unacknowledged",
650 "`Active`: ROLLBACK within the finalize grace",
651 "`Detached`, or a defensive `Finalizing`/`Done` entry",
652 "`error!` log for the defensive entry",
653 ] {
654 assert!(
655 production.contains(phrase),
656 "rollback doc must carry the total-rollback contract phrase: {phrase}"
657 );
658 }
659
660 for phrase in [
661 "Precondition `Active`. Otherwise no SQL is sent and the call returns `Err(SessionAborted)`.",
662 "The owner SHALL call `commit` only when `state() == Active`.",
663 ] {
664 assert!(
665 production.contains(phrase),
666 "commit doc must carry the precondition phrase: {phrase}"
667 );
668 }
669
670 // The 604d contract replaces the pre-604d prose; a retained copy would
671 // mean the replacement was an append and the port would carry two
672 // contradictory rollback contracts.
673 assert!(
674 !production.contains("Roll back the block's transaction."),
675 "the pre-604d rollback doc must be replaced, not kept alongside the new contract"
676 );
677 }
678
679 #[test]
680 fn transaction_error_display_names_offender_and_datasource() {
681 let manager_missing = TransactionError::ManagerMissing {
682 datasource: "pg".into(),
683 };
684 let rendered = manager_missing.to_string();
685 assert!(
686 rendered.contains("pg") && rendered.contains("TransactionManager"),
687 "manager-missing display must name the datasource and the missing port: {rendered}"
688 );
689
690 let foreign = TransactionError::ForeignDatasource {
691 step: "s1".into(),
692 block_datasource: "pg".into(),
693 step_datasource: "audit".into(),
694 };
695 let rendered = foreign.to_string();
696 assert!(
697 rendered.contains("s1") && rendered.contains("pg") && rendered.contains("audit"),
698 "foreign-datasource display must name the step and both datasources: {rendered}"
699 );
700
701 let stream_list = TransactionError::StreamListInBlock {
702 step: "s2".into(),
703 datasource: "pg".into(),
704 };
705 let rendered = stream_list.to_string();
706 assert!(
707 rendered.contains("s2") && rendered.contains("pg"),
708 "stream-list display must name the step and the datasource: {rendered}"
709 );
710 }
711
712 #[test]
713 #[allow(clippy::match_single_binding)]
714 fn non_exhaustive_enums_accept_catch_all() {
715 // `#[non_exhaustive]` keeps downstream crates from writing an exhaustive
716 // match, so a catch-all arm alone must compile for both enums.
717 let state = TransactionState::Fresh;
718 let outcome = TransactionOutcome::Committed;
719
720 let state_label = match state {
721 _ => "state",
722 };
723 let outcome_label = match outcome {
724 _ => "outcome",
725 };
726
727 assert_eq!(state_label, "state");
728 assert_eq!(outcome_label, "outcome");
729 }
730}