Skip to main content

boson_runtime/
global.rs

1//! Process-wide default Boson instance for macro-generated `send_with` helpers.
2//!
3//! Generated task handles call [`default`] internally. Install the runtime once at application
4//! boot with [`configure`] after [`crate::BosonBuilder::build`] or [`crate::BosonBuilder::build_manual`].
5
6use std::sync::RwLock;
7
8use super::Boson;
9
10static DEFAULT_BOSON: RwLock<Option<Boson>> = std::sync::RwLock::new(None);
11
12/// Install the process-wide default [`Boson`] instance.
13///
14/// Required before calling macro-generated `<TaskName>::send_with`. Typically called once after
15/// building the runtime:
16///
17/// ```rust,no_run
18/// # use std::sync::Arc;
19/// # use boson_backend_mem::MemQueueBackend;
20/// # use boson_core::JsonExecutionContextFactory;
21/// # use boson_runtime::{configure, Boson};
22/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
23/// let boson = Boson::builder()
24///     .queue_backend(Arc::new(MemQueueBackend::new()))
25///     .execution_context_factory(JsonExecutionContextFactory)
26///     .auto_registry()
27///     .build()?;
28/// configure(boson);
29/// # Ok(())
30/// # }
31/// ```
32///
33/// # Panics
34///
35/// Panics if the internal lock is poisoned.
36pub fn configure(boson: Boson) {
37    let mut guard = DEFAULT_BOSON.write().unwrap();
38    *guard = Some(boson);
39}
40
41/// Return the configured default [`Boson`] instance, if any.
42///
43/// Used by macro-generated `send_with` helpers. Returns `None` when [`configure`] has not been
44/// called.
45///
46/// # Panics
47///
48/// Panics if the internal lock is poisoned.
49pub fn default() -> Option<Boson> {
50    let guard = DEFAULT_BOSON.read().unwrap();
51    guard.clone()
52}
53