//! The ladder, and the fresh line it now is. //! //! ## One rung, and it issues the flat DDL //! //! The database is disposable while the product is in development. There are //! no migrations: [`MIGRATIONS`] holds exactly one entry, at //! [`SCHEMA_VERSION`], and its statements are //! [`crate::schema::ddl::SCHEMA_DDL`], the one flat DDL of a fresh file. A //! shape change edits that file, bumps `schema::ddl::SCHEMA_VERSION`, //! re-records `tests/fixtures/schema-snapshot.json` and adds a SHAPE line to //! the shape ledger. Nothing climbs. //! //! ## Household files move in place before initialization //! //! [`migration_plan`] refuses a file stamped below [`SCHEMA_VERSION`] (and //! above 0) with [`StoreError::Refused`], and so does every runner that asks //! it. At startup, every household file moves in place to the current shape: //! `startup_schema::prepare` calls `shape_move::move_to_current`; on the //! phone, `dev_heal.rs` performs the move. This initializer accepts an empty //! file (version 0) or a file already at the current stamp; a file stamped //! above this build is refused. //! //! ## Retired names are still a list //! //! [`RETIRED_TABLES`] names every table an earlier rung of the old ladder //! dropped. None of them is in a fresh file, but an op naming one can still //! arrive, and two readers treat it as silence rather than a rejection: the //! fold skips it (`skipped_retired`), and the server accepts and discards it. //! A queued one is never dropped on this phone (QUEUE BAD OP 7): it is sent //! like any other change. An unknown table that is NOT retired still rejects: a named list, never //! a catch-all. use crate::driver::Driver; use crate::error::{Result, StoreError}; /// One rung of the ladder. /// /// No `PartialEq`: nothing needs one, and a derived equality over a field that /// later holds a function pointer would be a comparison that is sometimes /// wrong, which is worse than none. #[derive(Debug, Clone, Copy)] pub struct Migration { /// The version this step brings a file TO. pub version: u32, /// The step's SQL, issued in order. pub statements: &'static [&'static str], } impl Migration { pub const fn at(version: u32, statements: &'static [&'static str]) -> Migration { Migration { version, statements, } } } /// The ladder: one rung, at [`crate::schema::ddl::SCHEMA_VERSION`], issuing /// [`crate::schema::ddl::SCHEMA_DDL`]. See the module header; a shape change /// edits the DDL and the version, never this list. pub const MIGRATIONS: &[Migration] = &[Migration::at( crate::schema::ddl::SCHEMA_VERSION, crate::schema::ddl::SCHEMA_DDL, )]; /// The version a file this build creates is stamped with, derived from the /// one rung, which reads it from `schema::ddl::SCHEMA_VERSION`. pub const SCHEMA_VERSION: u32 = MIGRATIONS[MIGRATIONS.len() - 1].version; /// **THE TWO DECLARATIONS OF THIS NUMBER AGREE, AND THE COMPILER SAYS SO.** /// /// `schema::ddl::SCHEMA_VERSION` is a literal and this one is derived from the /// ladder, and `ddl.rs` has said "it is held equal to `migrate::SCHEMA_VERSION`" /// since the two existed — by nothing but that sentence. A rung that bumped one /// and not the other therefore compiled, shipped, and split the build in half: /// `cotton-store` stamped a new file at the derived number while /// `cotton-server`'s open gate compared it against the literal, so the server /// refused a file its own client had just written, with the pre-cutover restore /// advice. Run #157 of PR #941: "stamped schema 29 and this build reads 28". /// /// A `const` assertion rather than a test, because this cannot be a thing /// somebody remembers to run: it fails the compile of every crate in the /// workspace, in the same second the mismatch is written. const _: () = assert!( crate::schema::ddl::SCHEMA_VERSION == SCHEMA_VERSION, "schema::ddl::SCHEMA_VERSION and migrate::SCHEMA_VERSION disagree — bump the literal in ddl.rs to the ladder's last rung" ); /// The statements that build a fresh file: the one rung's, which are /// [`crate::schema::ddl::SCHEMA_DDL`]. [`crate::create`] issues them in phases /// rather than list order. pub fn schema_statements() -> &'static [&'static str] { MIGRATIONS[0].statements } /// Every table the old ladder retired, flat. None of them is in a fresh file; /// the list survives because an op naming one can still arrive, and the fold, /// the outbox and the server treat such an op as silence (see the module /// header). A name is retired or it is not. pub const RETIRED_TABLES: &[&str] = &[ "cotton_scopes", "cotton_call_buckets", "cotton_call_members", "cotton_call_nodes", "cotton_call_stats", "cotton_calls", "cotton_collection_members", "cotton_document_grants", "cotton_msg_otp_buckets", // The one SYSTEM table the old ladder retired (version 11). The fold and // the outbox will never meet it, because an op is a write to the LIFE and // `_ops` was the protocol's own bookkeeping. "_ops", // Version 14 — the Code tool. A machine IS a device (version 13), and an // account is a row that survives a logout, so both readings fold onto rows // that already exist. Cotton note "The Code tool — why a Mac holds the sessions". "cotton_machines", "cotton_account_usage", // Version 23 — the launch folded into the session. `cotton_sessions` is // the one object now, and a row here has nothing left to be. // Cotton note "The Code tool — why a Mac holds the sessions". "cotton_session_launches", // Version 33 — the walkthrough became a note and the verification run // became nothing. Both families, children included. "cotton_run_cases", "cotton_run_screens", "cotton_walkthrough_runs", "cotton_walkthrough_screens", "cotton_walkthrough_shares", "cotton_walkthroughs", // Schema 139 — money is one row per move or expectation. The old sides // and aliases have been carried into those rows before their tables go. "cotton_money_aliases", "cotton_money_transaction_lines", // Schema 144 — the home-screen widgets left the phone, and the rows that // said which widget stood where went with them. "cotton_widgets", ]; /// Is this table one the old ladder retired? Reads [`RETIRED_TABLES`]. pub fn is_retired_table(table: &str) -> bool { RETIRED_TABLES.contains(&table) } /// What `migrate_store` would do to this file, without doing any of it. #[derive(Debug, Clone, PartialEq, Eq)] pub struct MigrationPlan { /// The version stamped in the file now. 0 for a file with no schema at all. pub from: u32, /// Where it will end up — always [`SCHEMA_VERSION`]. pub to: u32, /// The versions that will be applied, in order. Empty when it is current. pub pending: Vec, } /// What one run did. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct MigrationOutcome { pub from: u32, pub to: u32, } /// One step, reported before it runs and again after. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct MigrationStep { /// The schema version this step brings the file to. pub version: u32, /// 1-based position in `pending` — "Step {index} of {total}". pub index: usize, pub total: usize, /// How long the step took. `None` on the event fired BEFORE it runs — which /// is the event a screen exists for, since the step blocks from start to /// finish. pub took_ms: Option, } /// The version stamped in the file. 0 for a file with no schema at all. pub fn current_version(db: &Driver) -> Result { let row = db.get("PRAGMA user_version", &[])?; row.and_then(|row| row.int("user_version")) .and_then(|value| u32::try_from(value).ok()) .ok_or_else(|| StoreError::refused("cotton-store: invalid or missing schema version")) } /// Read what a migration WOULD do. Pure: one `PRAGMA user_version`, no write. /// /// Asked before anything a person can see is opened. Three answers: /// /// - a file with no schema (version 0) plans the one rung; /// - a file stamped below [`SCHEMA_VERSION`] is REFUSED with /// [`StoreError::Refused`]: startup must first move it in place through /// `startup_schema::prepare` → `shape_move::move_to_current` (or /// `dev_heal.rs` on the phone); /// - a file at [`SCHEMA_VERSION`] plans nothing; any other nonzero stamp refuses. pub fn migration_plan(db: &Driver) -> Result { let from = current_version(db)?; if from != 0 && from != SCHEMA_VERSION { return Err(StoreError::refused(format!( "cotton-store: this file is stamped schema {from} and does not match this build at {SCHEMA_VERSION}; an older file predates the fresh start; it is carried, never climbed. A file stamped from {} up crosses in place first (`shape_move`); an older one is refused.", crate::shape_move::LEDGER_BASE ))); } if from == 0 && !crate::create::schema_objects(db)?.is_empty() { return Err(StoreError::refused("cotton-store: an unstamped database already has a schema; initialization only accepts an empty file")); } Ok(MigrationPlan { from, to: SCHEMA_VERSION, pending: MIGRATIONS .iter() .filter(|migration| migration.version > from) .map(|migration| migration.version) .collect(), }) } /// Create the baseline and its version stamp in one transaction. pub fn run_migration(db: &Driver, migration: &Migration) -> Result<()> { db.transaction(|db| { for statement in migration.statements { db.exec(statement)?; } db.exec(&format!("PRAGMA user_version = {}", migration.version)) }) } /// Bring `db` up to [`SCHEMA_VERSION`], one step at a time. /// /// Idempotent: an already-current file is a no-op. Each step commits its own /// `user_version`, so an interrupted run leaves the file at the last WHOLE /// version rather than half-way into the next, and a second call re-plans from /// there. That is what makes a retry safe with no bookkeeping of its own. pub fn migrate_store(db: &Driver) -> Result { migrate_reporting(db, &mut |_| {}) } /// [`migrate_store`], reporting each step before and after it runs. /// /// The same list through the same [`run_migration`]: a migrator that forked for /// a progress screen would be the worst possible place to break "one /// implementation of who wins". The callback is where a UI hands the thread /// back — on the phone that is what lets a frame paint before a step that will /// block for seconds. /// /// A failure arrives as [`StoreError::Migration`] naming the version and the /// file's version AFTER the rollback — the two numbers a retry and a failure /// screen both depend on. pub fn migrate_reporting( db: &Driver, on_step: &mut dyn FnMut(MigrationStep), ) -> Result { let plan = migration_plan(db)?; let total = plan.pending.len(); for (position, migration) in MIGRATIONS .iter() .filter(|migration| migration.version > plan.from) .enumerate() { let index = position + 1; on_step(MigrationStep { version: migration.version, index, total, took_ms: None, }); let started = std::time::Instant::now(); if let Err(cause) = run_migration(db, migration) { // `current_version` again rather than the step before: the // transaction rolled back, so this reads what the file actually // says, which is the number the next attempt depends on. return Err(StoreError::Migration { version: migration.version, from: current_version(db)?, to: SCHEMA_VERSION, source: Box::new(cause), }); } on_step(MigrationStep { version: migration.version, index, total, took_ms: Some(started.elapsed().as_millis()), }); } Ok(MigrationOutcome { from: plan.from, to: current_version(db)?, }) } /// What migrating a REPLICA did. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct ReplicaMigration { pub from: u32, pub to: u32, /// Queued ops dropped because the schema no longer has their table. pub dropped_from_outbox: usize, /// The pull cursor was rewound and the whole server log will be folded /// again. pub replayed: bool, } /// Initialize or validate a replica against the same baseline as the store. pub fn migrate_replica(db: &Driver) -> Result { migrate_replica_reporting(db, &mut |_| {}) } /// Report baseline creation; there are no upgrade replays or retired-op sweeps. pub fn migrate_replica_reporting( db: &Driver, on_step: &mut dyn FnMut(MigrationStep), ) -> Result { let outcome = migrate_reporting(db, on_step)?; Ok(ReplicaMigration { from: outcome.from, to: outcome.to, dropped_from_outbox: 0, replayed: false, }) }