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(
26    url: &str,
27) -> boson_core::Result<Arc<PostgresQueueBackend>> {
28    let backend = Arc::new(PostgresQueueBackend::connect(url).await?);
29    let dyn_backend: Arc<dyn QueueBackend> = Arc::clone(&backend) as Arc<dyn QueueBackend>;
30    QueueRouter::set_global(QueueRouter::with_default(dyn_backend));
31    Ok(backend)
32}
33
34/// Install postgres backend with an isolated schema for test sessions.
35///
36/// # Errors
37///
38/// Propagates errors from [`PostgresQueueBackend::connect_isolated`].
39pub async fn install_isolated_postgres_backend(
40    url: &str,
41) -> boson_core::Result<(Arc<PostgresQueueBackend>, String)> {
42    let schema = format!("boson_{}", Uuid::new_v4().simple());
43    let backend = Arc::new(PostgresQueueBackend::connect_isolated(url, &schema).await?);
44    Ok((backend, schema))
45}