coven_database/commit_task.rs
1//! A commit scope that follows a task onto the blocking threads its database
2//! calls run on.
3
4use sqlive::CommitScope;
5use std::future::Future;
6
7tokio::task_local! {
8 static TASK: CommitScope;
9}
10
11/// Run `work` with its database calls' commits attributed to `scope`. The
12/// scope's future holds `work` once and polls it; an `async fn` here would
13/// hold a second, moved copy beside it. Calls started from other tasks,
14/// including tasks `work` spawns, are outside the scope.
15pub fn in_commit_scope<F: Future>(scope: CommitScope, work: F) -> impl Future<Output = F::Output> {
16 TASK.scope(scope, work)
17}
18
19/// Bind a database call to the scope of the task starting it, before it runs
20/// on a blocking thread: commits it makes report that scope.
21pub(crate) fn bind<R>(
22 run: impl FnOnce() -> R + Send + 'static,
23) -> impl FnOnce() -> R + Send + 'static {
24 let scope = TASK.try_with(|scope| *scope).ok();
25 #[cfg(any(test, feature = "test-utils"))]
26 let run = coven_foundation::test_work::bind(run);
27 move || sqlive::enter(scope, run)
28}