//! The fold's guard on a serving fact that re-keys the serving Mac. use std::collections::BTreeMap; use rusqlite::types::Value as SqlValue; use serde_json::{json, Value}; use super::*; use crate::test_support::{seeded_file, WORKSPACE}; /// Epoch 1, served by `device:mac` under `author-1` with relay key `relay-1`. fn served() -> Driver { let db = seeded_file("device:mac"); db.run( "INSERT INTO cotton_serving_machine \ (id, workspace_id, epoch, device_credential_id, author_id, relay_key, since) \ VALUES ('s-1', ?, 1, 'device:mac', 'author-1', 'relay-1', '2026-10-03T00:00:00.000Z')", &[SqlValue::Text(WORKSPACE.to_string())], ) .expect("the serving fact"); db } fn succession(change: impl FnOnce(&mut BTreeMap)) -> BTreeMap { let mut fields: BTreeMap = [ ("workspace_id", json!(WORKSPACE)), ("epoch", json!(2)), ("device_credential_id", json!("device:mac-new")), ("author_id", json!("author-1")), ("relay_key", json!("relay-1")), ("backup_access_key_id", Value::Null), ("start_positions", json!({"positions": {}, "skipped": [], SUCCEEDS: "device:mac"})), ] .into_iter() .map(|(key, value)| (key.to_string(), value)) .collect(); change(&mut fields); fields } /// RULE: A serving fact that re-keys the serving Mac changes nothing but the key — the next epoch, the key the epoch before it names, the same relay key, no backup access key of its own, written by a serving author of the epoch before — and anything else parks as a conflict on every device; a fact that names no succession is not judged here. #[test] fn a_succession_fact_changes_nothing_but_the_key() { let db = served(); assert_eq!(refusal(&db, &succession(|_| {}), "author-1").unwrap(), None); let refused = |fields: BTreeMap, author: &str| { let reason = refusal(&db, &fields, author).unwrap(); assert!(reason.as_deref().is_some_and(|reason| reason.starts_with("conflict:")), "{fields:?} by {author}: {reason:?}"); }; refused(succession(|fields| { fields.insert("relay_key".into(), json!("relay-2")); }), "author-1"); refused(succession(|fields| { fields.insert("relay_key".into(), Value::Null); }), "author-1"); refused(succession(|fields| { fields.insert("backup_access_key_id".into(), json!("AKIA-NEW")); }), "author-1"); refused( succession(|fields| { fields.insert("start_positions".into(), json!({SUCCEEDS: "device:mini"})); }), "author-1", ); refused(succession(|fields| { fields.insert("device_credential_id".into(), json!("device:mac")); }), "author-1"); refused(succession(|_| {}), "author-of-another-machine"); // An epoch this file has not heard of the fact before: it waits. let ahead = succession(|fields| { fields.insert("epoch".into(), json!(3)); }); let waits = refusal(&db, &ahead, "author-1").unwrap().expect("waits"); assert!(!waits.starts_with("conflict:"), "{waits}"); // A take-over is judged elsewhere. let takeover = succession(|fields| { fields.insert("start_positions".into(), json!({"positions": {}, "skipped": []})); }); assert_eq!(refusal(&db, &takeover, "anyone").unwrap(), None); }