//! Builder workflows: the boot-time seed and the lookups the web layer
//! resolves cookies and logins with. The control-database queries live in
//! [`crate::db::builder`]; the school-provisioning routes never come through
//! here — they speak to [`crate::tenant::Tenants`] directly.
use crate::database::Database;
use crate::db::builder;
use crate::domain::builder::{Builder, BuilderId, BuilderSession};
use crate::domain::user::{Password, Username};
use crate::error::AppError;
/// Idempotent startup seed: guarantee an account with this username in the
/// control database. Missing → created. Already present → nothing to do (the
/// stored password stays whatever it is — the seed never rewrites a
/// credential, so rotating `BUILDER_PASSWORD` in the environment does not
/// silently re-key a live account; delete the row to re-seed). There is no
/// role to promote here, so this cannot have
/// [`crate::service::user::ensure_admin`]'s create-then-promote hole.
pub async fn ensure(db: &Database, username: Username, password: Password) -> Result<(), AppError> {
if builder::find_by_username(db, username.as_str())
.await?
.is_some()
{
return Ok(());
}
let builder = Builder {
id: BuilderId::generate(),
password_hash: password.hash_async().await?,
username,
};
// A rival boot that seeded the same username between the read above and
// this insert loses the race silently — `create` reports "already there"
// instead of raising, so the second container of a fresh deployment boots
// instead of dying on a duplicate key. The winner's credential stands.
if builder::create(db, builder).await? {
// The account name stays out of the event: exported log records must
// name no person (see `telemetry`).
tracing::info!("seeded the builder account named by BUILDER_USERNAME");
}
Ok(())
}
/// The login lookup. Usernames are stored trimmed; callers trim the same way
/// so a padded attempt matches the canonical name.
pub async fn find_by_username(db: &Database, username: &str) -> Result