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 in **any process** that calls macro-generated `<TaskName>::send_with` — including
15/// Mode 2 enqueue-only hosts that use [`BosonBuilder::without_worker`](crate::BosonBuilder::without_worker).
16/// Not required when you only call [`Boson::enqueue`](crate::Boson::enqueue) on a held handle.
17///
18/// Getting started:
19/// [Mode 1](https://docs.rs/uf-boson/latest/boson/index.html#mode-1--embedded-one-binary) /
20/// [Mode 2](https://docs.rs/uf-boson/latest/boson/index.html#mode-2--remote-worker-two-binaries).
21///
22/// ```rust,no_run
23/// # use std::sync::Arc;
24/// # use boson_backend_mem::MemQueueBackend;
25/// # use boson_core::JsonExecutionContextFactory;
26/// # use boson_runtime::{configure, Boson};
27/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
28/// let boson = Boson::builder()
29///     .queue_backend(Arc::new(MemQueueBackend::new()))
30///     .execution_context_factory(JsonExecutionContextFactory)
31///     .auto_registry()
32///     .build()?;
33/// configure(boson);
34/// # Ok(())
35/// # }
36/// ```
37///
38/// # Panics
39///
40/// Panics if the internal lock is poisoned.
41pub fn configure(boson: Boson) {
42    let mut guard = DEFAULT_BOSON.write().unwrap();
43    *guard = Some(boson);
44}
45
46/// Return the configured default [`Boson`] instance, if any.
47///
48/// Used by macro-generated `send_with` helpers. Returns `None` when [`configure`] has not been
49/// called.
50///
51/// # Panics
52///
53/// Panics if the internal lock is poisoned.
54pub fn default() -> Option<Boson> {
55    let guard = DEFAULT_BOSON.read().unwrap();
56    guard.clone()
57}