Skip to main content

claviron_db/
config.rs

1use std::collections::HashMap;
2use std::path::PathBuf;
3use std::time::Duration;
4
5use claviron_helpers::de::{
6    deserialize_duration, deserialize_optional_duration,
7};
8use serde::Deserialize;
9
10/// Database composition from `db.yaml` or an enclosing runner's launch options.
11///
12/// Every section is optional here. What needs a connection says so where it
13/// looks for one: hosting asks for the connection `hosting:` names
14/// (`postgres.default` when unwritten) and refuses to boot without it.
15#[derive(Debug, Deserialize, Default, PartialEq)]
16#[serde(default)]
17pub struct DbFileConfig {
18    /// Which connection holds Claviron's hosting data (vhosts, aliases,
19    /// certificates), as `<backend>.<name>`: `postgres.default` when absent,
20    /// or e.g. `sqlite.hosting`.
21    pub hosting: Option<String>,
22    #[cfg(feature = "postgres")]
23    pub postgres: BackendConnections,
24    #[cfg(feature = "mysql")]
25    pub mysql: BackendConnections,
26    #[cfg(feature = "sqlite")]
27    pub sqlite: std::collections::HashMap<String, SqliteEntry>,
28}
29
30/// Map of named connections under a single backend (postgres or mysql).
31///
32/// The literal key `"default"` is conventionally the system default — for
33/// postgres it is required at boot, for mysql it is optional.
34#[derive(Debug, Deserialize, Default, PartialEq)]
35#[serde(transparent)]
36pub struct BackendConnections {
37    pub entries: HashMap<String, ConnectionEntry>,
38}
39
40impl BackendConnections {
41    pub fn default_entry(&self) -> Option<&ConnectionEntry> {
42        self.entries.get("default")
43    }
44
45    pub fn get(
46        &self,
47        name: &str,
48    ) -> Option<&ConnectionEntry> {
49        self.entries.get(name)
50    }
51
52    pub fn names(&self) -> impl Iterator<Item = &str> {
53        self.entries.keys().map(String::as_str)
54    }
55
56    pub fn is_empty(&self) -> bool {
57        self.entries.is_empty()
58    }
59}
60
61/// One named connection. Two ways to specify the transport:
62///
63/// - `url:` — a full connection URL (`postgres://…`, `mysql://…`).
64///   When present, structured fields are ignored. Handed straight to
65///   `sqlx::ConnectOptions::from_url(...)`.
66/// - `connect:` — nested map with structured fields (`host`, `port`,
67///   `database`, `username`, `password`, `socket`).
68///
69/// Two top-level fields rather than `#[serde(flatten)]` because
70/// serde-yaml silently drops flattened fields under certain shapes
71/// (the rest-map round-trip eats fields like `url:` when the inner
72/// struct has `#[serde(default)]`). Keep them explicit.
73///
74/// `pool:` is always required. claviron does not read process env at
75/// runtime; if a value must come from the deploy environment, use
76/// `${ENV_KEY}` substitution at the yaml layer: Congif expands it from the
77/// application's frozen configuration environment while preparing the file.
78#[derive(Debug, Deserialize, Clone, PartialEq)]
79pub struct ConnectionEntry {
80    #[serde(default)]
81    pub url: Option<url::Url>,
82    #[serde(default)]
83    pub connect: Option<ConnectInfo>,
84    pub pool: PoolConfig,
85}
86
87/// One named SQLite database: a file on this host, opened by every process
88/// of the fleet that uses it.
89///
90/// ```yaml
91/// sqlite:
92///   hosting:
93///     path: /var/lib/portico/hosting.db   # relative paths are cwd-relative
94///     busy_timeout: 5s                    # required: how long a writer waits for the lock
95///     create: true                        # create the file when missing; default false
96///     mmap_size: 16 MiB                   # optional read mapping ceiling; 0 disables it
97///     pool: { pool_size: 4, idle_size: 0, acquire_timeout: 10s, idle_timeout: 5m, max_lifetime: 30m }
98/// ```
99///
100/// The journal is always WAL: readers in every process go on while one
101/// writes, which is what several workers on one file need; the default
102/// rollback journal would block them for every write. SQLite's other
103/// settings, `synchronous` among them, are left at SQLite's own defaults
104/// unless an explicit connection option overrides them.
105#[derive(Debug, Deserialize, Clone, PartialEq)]
106#[serde(deny_unknown_fields)]
107pub struct SqliteEntry {
108    #[serde(default)]
109    pub mode: SqliteMode,
110    #[serde(default)]
111    pub path: PathBuf,
112    /// How long a statement waits for another process's write lock before
113    /// it fails with `SQLITE_BUSY`. Writers across processes take turns on
114    /// one lock; this is the operator's answer to how long a turn may take.
115    #[serde(deserialize_with = "deserialize_duration")]
116    pub busy_timeout: Duration,
117    /// Create the file when it does not exist. Off, a missing file is an
118    /// error at the first connection rather than a new empty database.
119    #[serde(default)]
120    pub create: bool,
121    /// Maximum bytes of the persistent database file to memory-map for reads.
122    /// Omission/null preserves SQLite's default; zero disables mapping.
123    /// Accepts a byte count or a size such as `16 MiB`. SQLite may cap this
124    /// value or disable mapping on platforms that do not support it.
125    #[serde(default, deserialize_with = "deserialize_optional_byte_size")]
126    pub mmap_size: Option<u64>,
127    pub pool: PoolConfig,
128}
129
130/// File databases persist across processes; memory databases belong to one pool.
131#[derive(Debug, Default, Deserialize, Clone, Copy, PartialEq, Eq)]
132#[serde(rename_all = "snake_case")]
133pub enum SqliteMode {
134    #[default]
135    File,
136    Memory,
137}
138
139fn deserialize_optional_byte_size<'de, D>(
140    deserializer: D
141) -> std::result::Result<Option<u64>, D::Error>
142where
143    D: serde::Deserializer<'de>,
144{
145    #[derive(Deserialize)]
146    #[serde(untagged)]
147    enum Size {
148        Bytes(u64),
149        Human(
150            #[serde(
151                deserialize_with = "claviron_helpers::de::deserialize_byte_size"
152            )]
153            u64,
154        ),
155    }
156
157    Ok(Option::<Size>::deserialize(deserializer)?.map(|size| match size {
158        Size::Bytes(bytes) | Size::Human(bytes) => bytes,
159    }))
160}
161
162#[derive(Debug, Deserialize, Clone, Default, PartialEq)]
163#[serde(default)]
164pub struct ConnectInfo {
165    pub socket: Option<PathBuf>,
166    pub host: String,     // default localhost
167    pub port: u16,        // default 3306 (mysql) / 5432 (postgres)
168    pub database: String, // no default
169    pub username: String, // no default
170    pub password: String, // default empty
171}
172
173#[derive(Debug, Deserialize, Clone, PartialEq)]
174pub struct PoolConfig {
175    pub pool_size: u32,
176    pub idle_size: u32,
177    #[serde(deserialize_with = "deserialize_duration")]
178    pub acquire_timeout: Duration,
179    #[serde(deserialize_with = "deserialize_duration")]
180    pub idle_timeout: Duration,
181    #[serde(deserialize_with = "deserialize_duration")]
182    pub max_lifetime: Duration,
183    /// How long a single statement may run before PostgreSQL cancels it.
184    ///
185    /// Carried as a connection option rather than issued as a `SET`, which
186    /// makes it the session default: it costs no round trip, and it survives
187    /// the `RESET ALL` a pooled connection is given when it is handed back.
188    ///
189    /// Absent leaves the server's own setting alone. Set it wherever a pool
190    /// serves something that must not be held up by one query — a request hot
191    /// path above all, where a runaway statement otherwise occupies a worker
192    /// until it finishes.
193    #[serde(default, deserialize_with = "deserialize_optional_duration")]
194    pub statement_timeout: Option<Duration>,
195}