Skip to main content

boson_backend_postgres/
bootstrap.rs

1//! Bootstrap helper — register `PostgreSQL` backend on the global [`QueueRouter`](boson_core::QueueRouter).
2
3use std::sync::Arc;
4
5use boson_core::{QueueBackend, QueueRouter};
6use uuid::Uuid;
7
8use crate::PostgresQueueBackend;
9
10const DEFAULT_POSTGRES_URL: &str = "postgres://boson:bench@127.0.0.1:5433/boson_bench";
11
12/// Resolve postgres URL from env (test preferred, then bench, then default).
13#[must_use]
14pub fn postgres_test_url() -> String {
15    std::env::var("BOSON_TEST_POSTGRES_URL")
16        .or_else(|_| std::env::var("BOSON_BENCH_POSTGRES_URL"))
17        .unwrap_or_else(|_| DEFAULT_POSTGRES_URL.to_string())
18}
19
20/// Install a new [`PostgresQueueBackend`] as the process-global default backend.
21///
22/// # Errors
23///
24/// Propagates errors from [`PostgresQueueBackend::connect`].
25pub async fn install_default_postgres_backend(url: &str) -> boson_core::Result<Arc<PostgresQueueBackend>> {
26    let backend = Arc::new(PostgresQueueBackend::connect(url).await?);
27    let dyn_backend: Arc<dyn QueueBackend> = Arc::clone(&backend) as Arc<dyn QueueBackend>;
28    QueueRouter::set_global(QueueRouter::with_default(dyn_backend));
29    Ok(backend)
30}
31
32/// Install postgres backend with an isolated schema for test sessions.
33///
34/// # Errors
35///
36/// Propagates errors from [`PostgresQueueBackend::connect_isolated`].
37pub async fn install_isolated_postgres_backend(
38    url: &str,
39) -> boson_core::Result<(Arc<PostgresQueueBackend>, String)> {
40    let schema = format!("boson_{}", Uuid::new_v4().simple());
41    let backend = Arc::new(PostgresQueueBackend::connect_isolated(url, &schema).await?);
42    Ok((backend, schema))
43}