Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

A separate directory

The users’ database becomes the directory: users, sessions, tenants, memberships and the place of each tenant or user. Your data is on PostgreSQL servers: each with one database for many tenants, or one database for each. Rules: spec 15. When to use it: the wiki.

use std::collections::HashMap;
use std::sync::Arc;
use auth_chad::Store;
use auth_chad::axum::{At, Auth, FirstParty, PlaceBy, Placement, Service, run_places};
use serde::{Deserialize, Serialize};

#[derive(Clone, Serialize, Deserialize)]
struct Place {
    server: String,     // a name, for example "db2"
    database: String,   // no password here: it belongs to the process's configuration
}

struct Databases {
    servers: HashMap<String, String>,   // name → connection string, from environment variables
}

impl Databases {
    fn from_env() -> Self {
        let names = std::env::var("DB_SERVERS").unwrap_or_default();   // "db1,db2"
        let url = |name: &str| std::env::var(format!("DB_{}_URL", name.to_uppercase())).ok();
        Self { servers: names.split(',').filter_map(|n| Some((n.to_owned(), url(n)?))).collect() }
    }
}

async fn create_database(url: &str, name: &str) -> bool {
    let _ = (url, name);   // CREATE DATABASE if it is missing, then your migrations
    true
}

async fn drop_database(url: &str, name: &str) -> bool {
    let _ = (url, name);   // DROP DATABASE IF EXISTS
    true
}

impl Placement for Databases {
    type Place = Place;
    const BY: Option<PlaceBy> = Some(PlaceBy::Tenant);

    async fn choose(&self, owner: [u8; 16]) -> Option<Place> {
        let mut names: Vec<&String> = self.servers.keys().collect();
        names.sort();
        let server = names.get(usize::from(owner[0]) % names.len().max(1))?;   // or: where there is room
        let database = format!("tenant_{}", owner.iter().map(|b| format!("{b:02x}")).collect::<String>());
        Some(Place { server: (*server).clone(), database })
    }

    async fn provision(&self, _owner: [u8; 16], place: &Place, _id: [u8; 16]) -> bool {
        let Some(url) = self.servers.get(&place.server) else { return false };
        create_database(url, &place.database).await   // safe to repeat
    }

    async fn remove(&self, _owner: [u8; 16], place: &Place, _id: [u8; 16]) -> bool {
        let Some(url) = self.servers.get(&place.server) else { return false };
        drop_database(url, &place.database).await
    }
}

fn setup<S: Store + 'static>(auth: Auth<S>) -> Arc<impl Service> {
    Arc::new(auth.with_places(Databases::from_env()))
}

async fn after_signup<A: Service>(auth: &A) {
    run_places(auth).await.ok();   // sooner than the next run of the worker
}

async fn notes(who: FirstParty, at: At<Place>) -> String {
    format!("{} uses {} on {}", who.0.tenant(), at.place.database, at.place.server)
}
  • Tables: places are an optional feature (Feature::Places, and Feature::Tenants to place by tenant). Migrate with them and call auth.check_tables() at start.
  • By tenant or by user: BY decides. Never both.
  • One database for many tenants: give them the same database, and give your tables a tenant column.
  • A new tenant or user gets its place in the same commit, in the state creating. Until provision answers true, At gives 503 not_ready with Retry-After.
  • The worker runs provision and remove (load-balancer). Work that fails runs again after its lease of 5 minutes.
  • Moving: place::begin_move (requests get 503 moving), copy the data, then place::finish_move with the new place. The generation grows.
  • Removing: place::remove. Requests get 404 at once, and remove runs until it answers true.
  • Waiting too long: place::in_states(store, PlaceState::Creating).
  • Connections: a PostgreSQL connection is for one database. With a database for each tenant, keep a small pool for each active one.
  • After a restore of the directory: auth-chad after-restore postgres prints the SQL that ends every session.