//! The bulk migration of a sealed table's open rows (sealing plan §7 step 3,
//! lane L9), run by a vault DEVICE: the Mac importer for bulk (Q21). The
//! object never holds a key that opens a row; the device seals, the object
//! keeps what it is handed.
//!
//! Unlike the day-to-day [`super::sweep`], which seals the open rows a copy
//! already holds, this reads the object's rows of one table itself, page by
//! page (`GET /v1/sync?tables=
`), so the device needs no copy of it.
//!
//! **A clear row stays until its sealed twin is verified.** Each batch of at
//! most [`BATCH`] open rows goes in three steps:
//!
//! 1. `seal_stage`: the twins are kept BESIDE the clear rows, which the
//! object does not touch.
//! 2. `GET /v1/seal/twins`: the device reads each twin back as stored, opens
//! it with its own key, and holds it to the clear row it read (every
//! column equal) and its blind tokens to the ones it makes again. A twin
//! that does not open, or opens to anything else, is never committed; the
//! row stays clear and is reported by name.
//! 3. `seal_commit` of the verified twins only: each takes its row's place
//! while the row is still at the version the device read.
//!
//! **Resumable, and safe against a racing edit, by construction.** The pass
//! cursor (`since`) is kept only when a pass has read to the object's end. A
//! run cut anywhere reads that pass again: rows it sealed now carry a seal and
//! are skipped, the rest are sealed. A row edited after it was read is left
//! `version_moved` by the object, and its edit gives it a version past this
//! pass's end, so the next pass reads it again and seals what it holds now.
//! Passes repeat until one finds nothing open to seal, then `seal_purge`
//! takes the table's sealed columns out of the act log's earlier args.
use std::collections::BTreeSet;
use serde_json::{json, Map, Value};
use cotton_core::definitions::seal::SealSpec;
use cotton_core::seal::row as stored_row;
use super::{guard_act, Sealer, KEEP_OPEN, SEAL_KEY_TABLE};
use crate::transport::object::ObjectRefusal;
/// Rows one stage and one commit carry (`SEAL_BATCH` in
/// apps/business/src/seal_migration.ts).
pub const BATCH: usize = 500;
/// Blind tokens one stage carries at most, a stage of one row exempt (`BLIND_PER_CALL` in
/// apps/business/src/seal.ts, LIVE CPU 4: a call writing more is refused 413 `too_large`). A batch of rows whose
/// words make many tokens (prompts, session titles) goes in as many stages as that takes.
pub const STAGE_TOKENS: usize = 2_000;
/// Passes over one table before the run stops and says so: a table whose
/// rows are edited faster than they are sealed is not chased for ever.
pub const MAX_PASSES: usize = 8;
/// One page of a sync of one table, as the object serves it.
#[derive(Debug, Clone, Default)]
pub struct Page {
/// `{table, id, version, data, deleted?}` per row.
pub rows: Vec,
/// The next page of the same pass, when there is one.
pub next: Option,
/// The version the pass reached: the next pass's `since` once `next` is none.
pub version: i64,
}
/// What the migration asks of the object. The Mac implements it over HTTPS
/// (`crates/cotton-mac/src/seal_migrate.rs`); tests over a fake object.
pub trait MigrateLine {
/// `GET /v1/sync?since=&tables=`, or the page `cursor` names.
fn page(&mut self, table: &str, since: i64, cursor: Option<&str>) -> Result;
/// `POST /v1/act { act, args }`, answering the act's reply.
fn act(&mut self, act: &str, args: Value) -> Result;
/// `GET /v1/seal/twins?table=&twins=,…`: the twins as stored.
fn twins(&mut self, table: &str, twins: &[String]) -> Result, ObjectRefusal>;
}
/// Where each table's migration got to, kept by the device across runs (the
/// Mac keeps it in `importer.db`).
pub trait Progress {
/// The `since` of the next pass over `table`: 0 the first time.
fn since(&self, table: &str) -> Result;
/// A pass read `table` to the object's end at `version`.
fn keep(&mut self, table: &str, version: i64) -> Result<(), String>;
}
/// What a run over one table did.
#[derive(Debug, Default, Clone, PartialEq)]
pub struct Migrated {
pub table: String,
/// Rows sealed in this run.
pub sealed: usize,
/// Open rows the person keeps open for good (Q3), left as they are.
pub kept_open: usize,
/// Rows the object left, by id and code (`version_moved`, `no_such_record`, …).
pub left: Vec<(String, String)>,
/// Twins the device did not verify, by id and why; their rows stay clear.
pub unverified: Vec<(String, String)>,
/// Passes read.
pub passes: usize,
/// Earlier acts `seal_purge` scrubbed, once a pass found nothing open.
pub purged: Option,
/// Whether the last pass found nothing left open to seal (never while a
/// twin went unverified: that pass is read again by the next run).
pub done: bool,
}
/// An open row read from the object: what is sealed and what it is held to.
struct Open {
id: String,
version: i64,
plain: Map,
}
/// Read every `seal_key` row the object holds into the sealer, so it seals
/// under each table's current version (a run never seals before it has).
pub fn learn_keys(sealer: &Sealer, line: &mut dyn MigrateLine) -> Result<(), String> {
let mut cursor: Option = None;
loop {
let page = line.page(SEAL_KEY_TABLE, 0, cursor.as_deref()).map_err(|refusal| format!("the object's seal keys could not be read: {}", refusal.message))?;
for row in &page.rows {
if row.get("table").and_then(Value::as_str) != Some(SEAL_KEY_TABLE) || row.get("deleted") == Some(&Value::Bool(true)) {
continue;
}
if let (Some(id), Some(data)) = (row.get("id").and_then(Value::as_str), row.get("data").and_then(Value::as_object)) {
sealer.learn(id, data);
}
}
match page.next {
Some(next) => cursor = Some(next),
None => break,
}
}
sealer.learned_all();
Ok(())
}
/// Migrate `table`'s open rows, resuming from `progress`. A refusal with no
/// answer or a lost sign-in stops the run (`Err`); the next run resumes.
pub fn migrate(sealer: &Sealer, table: &str, spec: &SealSpec, line: &mut dyn MigrateLine, progress: &mut dyn Progress) -> Result {
if !sealer.has_learned() {
return Err(format!("{}: the object's seal keys are not read yet (learn_keys first)", super::SEAL_KEY_MISSING));
}
let mut run = Migrated { table: table.to_string(), ..Migrated::default() };
// A row that does not open, or whose twin does not hold, is reported and left as it is; it never holds the purge
// back for every other row (LOCK TABLES 2): the run purges once nothing but such rows is left, and says it is not
// done, so the binary exits non-zero.
let mut purge = false;
while run.passes < MAX_PASSES {
run.passes += 1;
let failed_before = run.unverified.len();
let mut skipped = 0usize;
let since = progress.since(table)?;
let mut cursor: Option = None;
let mut batch: Vec = Vec::new();
let mut tried = 0usize;
let mut kept_open = 0usize;
loop {
let page = line.page(table, since, cursor.as_deref()).map_err(|refusal| format!("{table} could not be read: {}", refusal.message))?;
for row in &page.rows {
match open_row(sealer, table, spec, row) {
Some(Ok(open)) => batch.push(open),
Some(Err(Skip::KeptOpen)) => kept_open += 1,
Some(Err(Skip::DoesNotOpen(id, why))) => {
skipped += 1;
run.unverified.push((id, why));
}
None => {}
}
if batch.len() == BATCH {
tried += batch.len();
flush(sealer, table, spec, line, std::mem::take(&mut batch), &mut run)?;
}
}
match page.next {
Some(next) => cursor = Some(next),
None => {
tried += batch.len();
flush(sealer, table, spec, line, std::mem::take(&mut batch), &mut run)?;
// Only a pass read to the end, every twin of it verified, moves the
// cursor: a run cut short, or a row whose twin did not hold, is read again.
if run.unverified.is_empty() {
progress.keep(table, page.version)?;
}
break;
}
}
}
run.kept_open = run.kept_open.max(kept_open);
// The rows this pass tried whose twin did not hold: sealed by no later pass of this run either.
let failed = run.unverified.len() - failed_before - skipped;
// A failed row is read again by each pass (the cursor stays): said once.
let mut seen = BTreeSet::new();
run.unverified.retain(|(id, _)| seen.insert(id.clone()));
if tried <= failed {
run.done = run.unverified.is_empty();
purge = true;
break;
}
}
if purge {
let reply = line.act("seal_purge", json!({"table": table})).map_err(|refusal| format!("{table}'s act log could not be purged: {}", refusal.message))?;
run.purged = reply.get("scrubbed").and_then(Value::as_u64);
}
Ok(run)
}
/// Why a served row is not sealed by this run.
enum Skip {
/// The person keeps it open for good (Q3).
KeptOpen,
/// Sealed with a column left in the clear, and its seal does not open here: reported, never guessed at.
DoesNotOpen(String, String),
}
/// The columns `spec` seals that a sealed row still holds in the clear beside its seal (not null): it was sealed
/// under a wider clear list than the table's now (LOCK TABLES 1).
pub fn clear_left(spec: &SealSpec, data: &Map) -> Vec {
// The seal's own fields, the object's arrival patches (folded in by any device seal) and the keep-open mark are no
// column; any other key `spec` does not keep clear is plaintext beside the seal.
data.iter()
.filter(|(k, v)| !v.is_null() && spec.seals(k) && !stored_row::RESERVED.contains(&k.as_str()) && k.as_str() != cotton_core::seal::arrival::ARRIVAL_PATCHES && k.as_str() != KEEP_OPEN)
.map(|(k, _)| k.clone())
.collect()
}
/// A served row of `table` the run should seal: `Some(Ok)`, open and not
/// kept open, or sealed with a column of `spec` left in the clear (opened
/// here, so it is sealed again whole); `Some(Err)`, kept open (Q3), or such
/// a row that does not open; `None`, sealed as `spec` says, deleted, or
/// another table's.
fn open_row(sealer: &Sealer, table: &str, spec: &SealSpec, row: &Value) -> Option> {
if row.get("table").and_then(Value::as_str) != Some(table) || row.get("deleted") == Some(&Value::Bool(true)) {
return None;
}
let data = row.get("data").and_then(Value::as_object)?;
if stored_row::is_sealed(data) {
if clear_left(spec, data).is_empty() {
return None;
}
let id = row.get("id").and_then(Value::as_str)?.to_string();
let version = row.get("version").and_then(Value::as_i64)?;
return Some(match sealer.open(table, &id, data) {
Ok(plain) => Ok(Open { id, version, plain }),
Err(error) => Err(Skip::DoesNotOpen(id, format!("sealed with columns left in the clear, and its seal does not open ({})", error.code()))),
});
}
if data.get(KEEP_OPEN) == Some(&Value::Bool(true)) {
return Some(Err(Skip::KeptOpen));
}
let id = row.get("id").and_then(Value::as_str)?.to_string();
let version = row.get("version").and_then(Value::as_i64)?;
Some(Ok(Open { id, version, plain: data.clone() }))
}
/// Stage, verify and commit one batch.
fn flush(sealer: &Sealer, table: &str, spec: &SealSpec, line: &mut dyn MigrateLine, batch: Vec, run: &mut Migrated) -> Result<(), String> {
if batch.is_empty() {
return Ok(());
}
let mut rows = Vec::with_capacity(batch.len());
let mut tokens: std::collections::BTreeMap> = std::collections::BTreeMap::new();
for open in &batch {
let mut plain = open.plain.clone();
plain.remove(KEEP_OPEN);
let sealed = sealer.seal(table, &open.id, spec, &plain, None).map_err(|error| format!("{table} {}: {error}", open.id))?;
let row = json!({"id": open.id, "expect_version": open.version, "data": sealed.data, "blind": sealed.blind});
// The guard every device act passes: no sealed column leaves in the clear.
let spec_of = |name: &str| (name == table).then(|| spec.clone());
guard_act(spec_of, "seal", &json!({"table": table, "data": row["data"]}))?;
tokens.insert(open.id.clone(), sealed.blind.into_iter().collect());
rows.push(row);
}
for stage in stages(rows) {
land(sealer, table, line, &batch, stage, &tokens, run)?;
}
Ok(())
}
/// `rows` cut into stages of at most [`STAGE_TOKENS`] blind tokens; a row over it alone goes alone.
pub fn stages(rows: Vec) -> Vec> {
let mut out: Vec> = Vec::new();
let mut tokens = 0usize;
for row in rows {
let weight = row.get("blind").and_then(Value::as_array).map_or(0, Vec::len);
match out.last_mut() {
Some(stage) if tokens + weight <= STAGE_TOKENS => stage.push(row),
_ => {
out.push(vec![row]);
tokens = 0;
}
}
tokens += weight;
}
out
}
/// Stage, verify and commit one stage of `batch`'s rows.
fn land(sealer: &Sealer, table: &str, line: &mut dyn MigrateLine, batch: &[Open], rows: Vec, tokens: &std::collections::BTreeMap>, run: &mut Migrated) -> Result<(), String> {
let staged = line.act("seal_stage", json!({"table": table, "rows": rows})).map_err(|refusal| format!("{table}: the stage was refused ({}: {})", refusal.code, refusal.message))?;
run.left.extend(left_of(&staged));
let staged: Vec<(String, String)> = staged
.get("staged")
.and_then(Value::as_array)
.map(|list| list.iter().filter_map(|s| Some((s.get("id")?.as_str()?.to_string(), s.get("twin")?.as_str()?.to_string()))).collect())
.unwrap_or_default();
if staged.is_empty() {
return Ok(());
}
let names: Vec = staged.iter().map(|(_, twin)| twin.clone()).collect();
let served = line.twins(table, &names).map_err(|refusal| format!("{table}: the twins could not be read back ({})", refusal.message))?;
let mut verified = Vec::new();
for (id, twin) in &staged {
let open = batch.iter().find(|o| &o.id == id);
let held = served.iter().find(|t| t.get("twin").and_then(Value::as_str) == Some(twin.as_str()));
match (open, held) {
(Some(open), Some(held)) => match verify(sealer, table, open, held, &tokens[id]) {
Ok(()) => verified.push(twin.clone()),
Err(why) => run.unverified.push((id.clone(), why)),
},
(_, None) => run.unverified.push((id.clone(), "the object did not hand the twin back".into())),
(None, _) => run.unverified.push((id.clone(), "the object staged a row this run did not send".into())),
}
}
if verified.is_empty() {
return Ok(());
}
let committed = line.act("seal_commit", json!({"table": table, "twins": verified})).map_err(|refusal| format!("{table}: the commit was refused ({}: {})", refusal.code, refusal.message))?;
run.sealed += committed.get("sealed").and_then(Value::as_array).map_or(0, Vec::len);
run.left.extend(left_of(&committed));
Ok(())
}
/// A twin as the object stored it holds to the clear row it was made from:
/// the same row and version, it opens under this device's key to every
/// column the clear row held (no more, no less, a missing column equal to
/// null), and it carries the same blind tokens.
fn verify(sealer: &Sealer, table: &str, open: &Open, held: &Value, tokens: &BTreeSet) -> Result<(), String> {
if held.get("id").and_then(Value::as_str) != Some(open.id.as_str()) {
return Err("the twin names another row".into());
}
if held.get("expect_version").and_then(Value::as_i64) != Some(open.version) {
return Err("the twin was staged at another version".into());
}
let data = held.get("data").and_then(Value::as_object).ok_or("the twin holds no data")?;
if !stored_row::is_sealed(data) {
return Err("the twin is not sealed".into());
}
let opened = sealer.open(table, &open.id, data).map_err(|error| format!("the twin does not open ({})", error.code()))?;
let mut want = open.plain.clone();
want.remove(KEEP_OPEN);
let mut got = opened;
got.remove(KEEP_OPEN);
if unnulled(&got) != unnulled(&want) {
let differ: Vec<&String> = want.keys().chain(got.keys()).filter(|k| want.get(*k).unwrap_or(&Value::Null) != got.get(*k).unwrap_or(&Value::Null)).collect::>().into_iter().collect();
return Err(format!("the twin opens to other values in {}", differ.iter().map(|k| k.as_str()).collect::>().join(", ")));
}
let served: BTreeSet = held.get("blind").and_then(Value::as_array).map(|list| list.iter().filter_map(|t| t.as_str().map(str::to_string)).collect()).unwrap_or_default();
if &served != tokens {
return Err("the twin's blind tokens are not the row's".into());
}
Ok(())
}
fn unnulled(row: &Map) -> Map {
row.iter().filter(|(_, v)| !v.is_null()).map(|(k, v)| (k.clone(), v.clone())).collect()
}
fn left_of(reply: &Value) -> Vec<(String, String)> {
reply
.get("left")
.and_then(Value::as_array)
.map(|list| list.iter().filter_map(|l| Some((l.get("id")?.as_str()?.to_string(), l.get("code")?.as_str()?.to_string()))).collect())
.unwrap_or_default()
}
#[cfg(test)]
#[path = "migrate_tests.rs"]
mod tests;