slave-framework 0.9.1

Runtime for slave apps (a Laravel-inspired Rust framework for MCP-first apps): server lifecycle, config, logging, a Toasty database (PostgreSQL), and OpenID Connect sign-in
Documentation
//! The application's [Toasty](https://github.com/tokio-rs/toasty) database.
//!
//! Models are Rust structs with `#[derive(toasty::Model)]`; this module opens
//! the connection pool they run on, on PostgreSQL. Configure it with
//! `DATABASE_URL` (default [`DEFAULT_URL`]). Several processes and machines
//! can share the database.
//!
//! Schema changes are Toasty migrations: generated from the models by the
//! app's `migrate` binary (built on `toasty-cli`) and applied by it.

use toasty::{Db, ModelSet};

use crate::Result;

/// Transaction isolation levels, for [`toasty::TransactionBuilder::isolation`].
/// `Serializable` transactions may fail with a serialization failure under
/// contention; retry them ([`SERIALIZABLE_ATTEMPTS`]).
pub use toasty_core::driver::operation::IsolationLevel;

/// How many times to run a `Serializable` transaction that keeps failing
/// with a serialization failure before giving up.
pub const SERIALIZABLE_ATTEMPTS: usize = 5;

/// Environment variable holding the database URL.
pub const URL_ENV: &str = "DATABASE_URL";

/// The database used when `DATABASE_URL` is not set: a local PostgreSQL.
pub const DEFAULT_URL: &str = "postgresql://localhost:5432/postgres";

/// Where to connect.
#[derive(Debug, Clone)]
pub struct DatabaseConfig {
    /// A Toasty connection URL, e.g. `postgresql://user:pass@host:5432/app`.
    pub url: String,
}

impl DatabaseConfig {
    /// Reads `DATABASE_URL`, falling back to [`DEFAULT_URL`].
    pub fn from_env() -> Self {
        Self {
            url: crate::env::var_or(URL_ENV, DEFAULT_URL),
        }
    }
}

/// Opens a pooled handle to the database for `models`. Cheap to clone: clones
/// share the pool.
pub async fn connect(models: ModelSet, config: &DatabaseConfig) -> Result<Db> {
    Ok(Db::builder().models(models).connect(&config.url).await?)
}