kasl_server/backup.rs
1//! `kasl-server backup` and `restore`: the installation's data as one file.
2//!
3//! An operator running this on their own hardware owns the consequences of
4//! losing it, so taking a copy has to be something they can do without knowing
5//! PostgreSQL. `pg_dump` is the better tool for someone who already has a
6//! backup regime; this is for everyone else, and it does two things `pg_dump`
7//! cannot:
8//!
9//! * **It knows the schema version.** A dump carries the migration it was
10//! taken at, and a restore refuses a file from a newer server rather than
11//! loading rows into tables whose columns have since changed. The failure
12//! mode being avoided is not an error - it is a restore that appears to work
13//! and quietly drops what the older schema has no place for.
14//! * **It is the same binary.** No `postgres-client` package on the host, no
15//! version skew between a client and the server it dumps.
16//!
17//! JSON Lines rather than SQL: each line is a table's worth of rows, so a file
18//! can be read by anything, checked by eye, and streamed without holding the
19//! installation in memory.
20
21use anyhow::{Context, Result, bail};
22use serde::{Deserialize, Serialize};
23use sqlx::{PgPool, Row, postgres::PgRow};
24use std::io::{BufRead, Write};
25
26/// Tables in the order they must be written and loaded.
27///
28/// Parents first: every foreign key points at a table earlier in this list, so
29/// a restore that walks it in order never inserts a row whose owner is missing.
30/// `_sqlx_migrations` is deliberately absent - the schema is applied by the
31/// server, not carried in the file.
32///
33/// `users` and `departments` are the exception no ordering can solve: a person
34/// belongs to a department and a department names its manager, so each points
35/// at the other. See [`DEFERRED_COLUMNS`].
36///
37/// Kept honest by `every_table_in_the_schema_is_carried` in the integration
38/// tests, which compares this list against `information_schema` rather than
39/// against a second hand-written list. A list checked only by eye is a list
40/// that grows a hole the day somebody adds a table and reads the file they are
41/// working in: that is exactly how `calendar_days` shipped in v0.21 absent
42/// from here, so a backup of an installation's production calendar restored as
43/// an installation with no calendar at all - a full header, a plausible row
44/// count, and the norms silently wrong on every holiday.
45pub const TABLES: [&str; 14] = [
46 "users",
47 "departments",
48 "agents",
49 "sessions",
50 "workdays",
51 "pauses",
52 "tasks",
53 "tags",
54 "task_tags",
55 "reports",
56 "audit_log",
57 // The production calendar. Not derivable from anything else in the file:
58 // it is an act of a government somebody typed in by hand (ADR 0017).
59 "calendar_days",
60 // What the server noticed and what people decided about it. `fired_at` and
61 // an acknowledgement are the two facts a sweep cannot reconstruct, which
62 // is the same reason they are stored at all.
63 "alerts",
64 // What the server said outward and whether it arrived. Names destinations
65 // by label only - their addresses live in the environment, not here, so a
66 // backup file carries no credential to post as anybody (ADR 0019).
67 "webhook_deliveries",
68];
69
70/// Columns held back on insert and written once every table is loaded.
71///
72/// The one cycle in this schema: `users.department_id` points at a department,
73/// and `departments.manager_id` points back at a user. Whichever goes in first
74/// has a column referring to a row that does not exist yet, so that column
75/// waits - the row is inserted without it and updated at the end.
76///
77/// The alternative, making the constraints `DEFERRABLE`, would loosen them for
78/// every ordinary write in the product to serve one command that runs rarely.
79const DEFERRED_COLUMNS: [(&str, &str); 2] = [("users", "department_id"), ("departments", "manager_id")];
80
81/// Tables the restore replaces wholesale but never empties from the file.
82///
83/// `settings` is one row created by a migration. Deleting it and inserting the
84/// backup's copy would work, but leaving the row alone and updating it keeps
85/// the `CHECK (singleton)` constraint honest at every moment.
86pub const SETTINGS: &str = "settings";
87
88/// What the file says about itself, on its first line.
89#[derive(Debug, Serialize, Deserialize)]
90pub struct Header {
91 /// Always `kasl-server-backup`, so a file fed to the wrong tool says so.
92 pub format: String,
93 /// The migration the source database was at. The restore's gate.
94 pub schema_version: i64,
95 /// The version that wrote it - for a human reading the file, not a check.
96 pub server_version: String,
97 pub taken_at: chrono::DateTime<chrono::Utc>,
98}
99
100/// The marker every backup starts with.
101const FORMAT: &str = "kasl-server-backup";
102
103/// One table's rows.
104#[derive(Debug, Serialize, Deserialize)]
105struct Chunk {
106 table: String,
107 rows: Vec<serde_json::Value>,
108}
109
110/// Writes the whole installation to `out`.
111///
112/// Rows are read a table at a time and written as they come, so the file is
113/// produced without the installation ever being resident in memory.
114pub async fn dump(pool: &PgPool, schema_version: i64, out: &mut impl Write) -> Result<Summary> {
115 let header = Header {
116 format: FORMAT.to_string(),
117 schema_version,
118 server_version: env!("CARGO_PKG_VERSION").to_string(),
119 taken_at: chrono::Utc::now(),
120 };
121 writeln!(out, "{}", serde_json::to_string(&header)?)?;
122
123 let mut summary = Summary::default();
124
125 for table in TABLES.into_iter().chain([SETTINGS]) {
126 // `row_to_json` hands the whole row over as JSON, so this module does
127 // not need a struct per table - and a column added by a later
128 // migration travels without anything here being edited.
129 // `AssertSqlSafe` on a name from `TABLES`, a constant in this file.
130 let rows: Vec<serde_json::Value> = sqlx::query(sqlx::AssertSqlSafe(format!("SELECT row_to_json(t) AS row FROM {table} AS t")))
131 .fetch_all(pool)
132 .await
133 .with_context(|| format!("failed to read {table}"))?
134 .into_iter()
135 .map(|row: PgRow| row.get::<serde_json::Value, _>("row"))
136 .collect();
137
138 summary.rows += rows.len();
139 summary.tables += 1;
140 writeln!(
141 out,
142 "{}",
143 serde_json::to_string(&Chunk {
144 table: table.to_string(),
145 rows,
146 })?
147 )?;
148 }
149
150 out.flush()?;
151 Ok(summary)
152}
153
154/// What a backup or restore moved.
155#[derive(Debug, Default, PartialEq, Eq)]
156pub struct Summary {
157 pub tables: usize,
158 pub rows: usize,
159}
160
161/// Reads a backup into an empty installation.
162///
163/// Refuses rather than merges: a restore into a database with data in it would
164/// have to decide what wins, and every answer to that is wrong for somebody.
165/// The operator empties the database - or points at a fresh one - and the
166/// intent is theirs rather than inferred.
167pub async fn load(pool: &PgPool, schema_version: i64, input: impl BufRead) -> Result<Summary> {
168 let mut lines = input.lines();
169
170 let header: Header = {
171 let first = lines.next().context("the backup is empty")??;
172 serde_json::from_str(&first).context("the first line is not a kasl-server backup header")?
173 };
174
175 if header.format != FORMAT {
176 bail!("this is not a kasl-server backup (format: {})", header.format);
177 }
178
179 // The gate this module exists for. A dump from a newer server may contain
180 // columns this schema has no home for; loading it would drop them silently
181 // and look like a success.
182 if header.schema_version > schema_version {
183 bail!(
184 "the backup is from a newer server (schema {} against this server's {}); upgrade kasl-server before restoring",
185 header.schema_version,
186 schema_version
187 );
188 }
189
190 ensure_empty(pool).await?;
191
192 let mut summary = Summary::default();
193 // One transaction: a restore that stopped halfway would leave an
194 // installation whose rows reference owners that were never loaded.
195 let mut tx = pool.begin().await?;
196
197 // What the cycle forced us to leave out, to be written once every row it
198 // could point at exists: (table, column, row id, value).
199 let mut deferred: Vec<(&'static str, &'static str, serde_json::Value, serde_json::Value)> = Vec::new();
200
201 for line in lines {
202 let line = line?;
203 if line.trim().is_empty() {
204 continue;
205 }
206 let chunk: Chunk = serde_json::from_str(&line).context("a line of the backup could not be read")?;
207
208 summary.tables += 1;
209 for row in &chunk.rows {
210 let held = insert(&mut tx, &chunk.table, row).await?;
211 deferred.extend(held);
212 summary.rows += 1;
213 }
214 }
215
216 for (table, column, id, value) in deferred {
217 // Both names come from `DEFERRED_COLUMNS`, constants in this file.
218 sqlx::query(sqlx::AssertSqlSafe(format!(
219 "UPDATE {table} SET {column} = ($1::text)::uuid WHERE id = ($2::text)::uuid"
220 )))
221 .bind(value.as_str().unwrap_or_default())
222 .bind(id.as_str().unwrap_or_default())
223 .execute(&mut *tx)
224 .await
225 .with_context(|| format!("failed to restore {table}.{column}"))?;
226 }
227
228 tx.commit().await?;
229 Ok(summary)
230}
231
232/// The one table name in this module that does not come from its own source.
233///
234/// A restore reads names out of a file, and a file can say anything. Matching
235/// against the known list turns that name back into a constant before it
236/// reaches a statement - the check is that the name *is* one of ours, not that
237/// it looks harmless.
238fn known_table(name: &str) -> Result<&'static str> {
239 TABLES
240 .into_iter()
241 .chain([SETTINGS])
242 .find(|table| *table == name)
243 .with_context(|| format!("the backup names a table this server does not have: {name}"))
244}
245
246/// Inserts one row given as a JSON object.
247///
248/// `json_populate_record` turns the object back into a row of the table's own
249/// type, so the column list lives in the database rather than being repeated
250/// here for every table.
251/// One value held back until the rest of the restore has caught up.
252type Deferred = (&'static str, &'static str, serde_json::Value, serde_json::Value);
253
254async fn insert(tx: &mut sqlx::Transaction<'_, sqlx::Postgres>, table: &str, row: &serde_json::Value) -> Result<Vec<Deferred>> {
255 let table = known_table(table)?;
256
257 // Take out the column that points into the cycle, if this table has one
258 // and this row actually uses it. A null needs nothing held back.
259 let mut held = Vec::new();
260 let mut row = row.clone();
261 for (owner, column) in DEFERRED_COLUMNS {
262 if owner != table {
263 continue;
264 }
265 let Some(object) = row.as_object_mut() else { continue };
266 match object.get(column) {
267 Some(serde_json::Value::Null) | None => {}
268 Some(value) => {
269 let value = value.clone();
270 let id = object.get("id").cloned().unwrap_or(serde_json::Value::Null);
271 object.insert(column.to_string(), serde_json::Value::Null);
272 held.push((owner, column, id, value));
273 }
274 }
275 }
276 let row = &row;
277
278 if table == SETTINGS {
279 // The singleton row already exists, put there by the migration.
280 // `coalesce` on `demo`: a backup taken before the column existed has
281 // no key for it, `json_populate_record` reads that as NULL, and a
282 // restore of a perfectly good older file must not fail on the
283 // column it could not have known about.
284 sqlx::query(sqlx::AssertSqlSafe(format!(
285 "UPDATE {SETTINGS} SET privacy_level = (r).privacy_level,
286 demo = coalesce((r).demo, false),
287 updated_at = (r).updated_at
288 FROM (SELECT json_populate_record(NULL::{SETTINGS}, $1::json) AS r) AS s
289 WHERE singleton"
290 )))
291 .bind(row)
292 .execute(&mut **tx)
293 .await
294 .with_context(|| format!("failed to restore {table}"))?;
295 return Ok(held);
296 }
297
298 sqlx::query(sqlx::AssertSqlSafe(format!(
299 "INSERT INTO {table} SELECT * FROM json_populate_record(NULL::{table}, $1::json)"
300 )))
301 .bind(row)
302 .execute(&mut **tx)
303 .await
304 .with_context(|| format!("failed to restore a row of {table}"))?;
305 Ok(held)
306}
307
308/// Refuses to restore over an installation that already holds people.
309///
310/// `users` alone: everything else hangs off it, and an operator who has
311/// started a server but never signed anyone in should not have to empty a
312/// database to restore into it.
313async fn ensure_empty(pool: &PgPool) -> Result<()> {
314 let users: i64 = sqlx::query_scalar("SELECT count(*) FROM users").fetch_one(pool).await?;
315 if users > 0 {
316 bail!("this database already holds {users} accounts; restore into an empty one");
317 }
318 Ok(())
319}
320
321#[cfg(test)]
322mod tests {
323 use super::*;
324
325 #[test]
326 fn a_backup_names_itself_and_its_schema() {
327 // The header is the whole contract with a future restore: a file that
328 // did not say which schema it came from could only be loaded on faith.
329 let header = Header {
330 format: FORMAT.to_string(),
331 schema_version: 20260826000001,
332 server_version: "0.14.0".to_string(),
333 taken_at: chrono::Utc::now(),
334 };
335 let json = serde_json::to_string(&header).unwrap();
336 let read: Header = serde_json::from_str(&json).unwrap();
337
338 assert_eq!(read.format, FORMAT);
339 assert_eq!(read.schema_version, 20260826000001);
340 }
341
342 #[test]
343 fn parents_come_before_their_children() {
344 // The restore inserts in this order, so a table must never appear
345 // before one it points at. Checked as a property rather than by eye:
346 // a table added in the wrong place fails here instead of failing a
347 // customer's restore with a foreign key violation.
348 let position = |table: &str| TABLES.iter().position(|t| *t == table).unwrap_or_else(|| panic!("{table} is not in TABLES"));
349
350 for (child, parent) in [
351 ("alerts", "users"),
352 ("agents", "users"),
353 ("sessions", "users"),
354 ("workdays", "users"),
355 ("pauses", "workdays"),
356 ("tasks", "users"),
357 ("tags", "users"),
358 ("task_tags", "tasks"),
359 ("task_tags", "tags"),
360 ("reports", "users"),
361 ("departments", "users"),
362 ] {
363 assert!(position(parent) < position(child), "{parent} must be restored before {child}");
364 }
365 }
366
367 #[test]
368 fn a_table_name_from_a_file_has_to_be_one_of_ours() {
369 // The only name in this module that does not come from its own source
370 // arrives inside a backup, and a file can say anything. Every table
371 // reaches a statement only after being matched back to a constant.
372 assert_eq!(known_table("users").unwrap(), "users");
373 assert_eq!(known_table(SETTINGS).unwrap(), SETTINGS);
374
375 for hostile in ["users; DROP TABLE users", "pg_shadow", "_sqlx_migrations", "users --", ""] {
376 let error = known_table(hostile).unwrap_err();
377 assert!(error.to_string().contains("does not have"), "`{hostile}` must be refused by name, got: {error}");
378 }
379 }
380
381 #[test]
382 fn every_table_is_listed_once() {
383 let mut seen = TABLES.to_vec();
384 seen.sort_unstable();
385 let count = seen.len();
386 seen.dedup();
387 assert_eq!(seen.len(), count, "a table listed twice would be restored twice");
388 assert!(!TABLES.contains(&SETTINGS), "settings is updated, not inserted, so it must not be in TABLES");
389 assert!(
390 !TABLES.contains(&"_sqlx_migrations"),
391 "the schema is applied by the server, not carried in a backup"
392 );
393 }
394}