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