aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authortv <tv@krebsco.de>2026-11-30 14:55:03 +0000
committertv <tv@krebsco.de>2026-11-30 14:55:03 +0000
commit8017b0e69f0350c2a35629ae71d511ddf7a3aa9c (patch)
tree494d282a79985a19d2194717fa7a7e7a4bba52e1
parent8e97bcfa65e92da21df912cc5e19cf18027b82b8 (diff)
A node of a swarm holding a store, on a set of events (--store-document)
With store-root or store-id, store-document names the file of the store's own document, a set of events: the node holds its store there and nothing in the Automerge document, syncs with nodes holding a set and no others, and goes on from the file when started again. Without a file yet it begins from the root (StoreStart::set); joining by the ID alone needs a file. What a checkpoint forgot is kept for store-keeps-forgotten (30 days). The file stands for store-file, and no checkpoint is pinned. The set is written to its file where it changed, every five seconds with the store's worker and as the node stops (Holding::save), what a checkpoint forgot longer ago let go of first. Simulations: a node behind catches up; a node goes on from its file.
-rw-r--r--src/config/mod.rs41
-rw-r--r--src/federation/held.rs64
-rw-r--r--src/lib.rs33
-rw-r--r--src/simtest/holding.rs122
-rw-r--r--src/swarm/bootstrap.rs91
5 files changed, 348 insertions, 3 deletions
diff --git a/src/config/mod.rs b/src/config/mod.rs
index efc190d..9c82673 100644
--- a/src/config/mod.rs
+++ b/src/config/mod.rs
@@ -216,6 +216,22 @@ pub(crate) const OPTIONS: &[OptionSpec] = &[
),
#[cfg(feature = "federation")]
option(
+ "store-document",
+ Kind::Text,
+ "PATH",
+ None,
+ "With store-root or store-id: hold the store in a document of its own kind, a set of events (docs/document.md), kept in this file, instead of in the Automerge document a swarm syncs otherwise. The node then syncs with nodes holding such a set, and with no others: a swarm is of one kind. The file holds the store's events, what the node refused of its own and what its operator had it drop, and its members' entries; started again, the node goes on from it. Can't be combined with store-file, which the file stands for, nor with store-checkpoint.",
+ ),
+ #[cfg(feature = "federation")]
+ option(
+ "store-keeps-forgotten",
+ Kind::Duration,
+ "DURATION",
+ Some("30d"),
+ "With store-document: for how long the node keeps what a checkpoint its store moved to forgot, for nodes still before that checkpoint, which build it from that. A node behind for longer starts from a checkpoint its operator pins.",
+ ),
+ #[cfg(feature = "federation")]
+ option(
"store-checkpoint",
Kind::Text,
"ID",
@@ -809,6 +825,14 @@ pub(crate) struct Settings {
#[cfg(feature = "federation")]
pub(crate) store_checkpoint: Option<String>,
#[cfg(feature = "federation")]
+ pub(crate) store_document: Option<PathBuf>,
+ #[cfg(feature = "federation")]
+ #[serde(
+ default = "default_store_keeps_forgotten",
+ with = "crate::units::duration_option"
+ )]
+ pub(crate) store_keeps_forgotten: Duration,
+ #[cfg(feature = "federation")]
pub(crate) store_party: Option<String>,
#[cfg(feature = "federation")]
#[serde(default)]
@@ -1070,6 +1094,10 @@ fn default_neighbours() -> usize {
fn default_electorate_window() -> Duration {
Duration::from_secs(7 * 24 * 3600)
}
+#[cfg(feature = "federation")]
+fn default_store_keeps_forgotten() -> Duration {
+ Duration::from_secs(30 * 24 * 3600)
+}
fn default_clock_skew_warn() -> Duration {
Duration::from_secs(2)
}
@@ -1332,6 +1360,7 @@ impl Settings {
let of_a_store = [
("store-file", self.store_file.is_some()),
("store-checkpoint", self.store_checkpoint.is_some()),
+ ("store-document", self.store_document.is_some()),
("store-party", self.store_party.is_some()),
("store-readers", !self.store_readers.is_empty()),
(
@@ -1355,6 +1384,16 @@ impl Settings {
return Ok(());
}
};
+ if self.store_document.is_some() {
+ if self.store_file.is_some() {
+ bail!("store-document holds what store-file would: unset store-file");
+ }
+ if self.store_checkpoint.is_some() {
+ bail!(
+ "store-document: a set of events starts from its root or from its file, from no pinned checkpoint: unset store-checkpoint"
+ );
+ }
+ }
match &self.store_party {
None => bail!(
"{store}: set store-party, the party this node is of: in a swarm holding a store, nodes sync with the nodes its parties list, each as its party's"
@@ -1482,6 +1521,8 @@ impl Settings {
#[cfg(feature = "federation")]
("store-checkpoint", self.store_checkpoint.is_some()),
#[cfg(feature = "federation")]
+ ("store-document", self.store_document.is_some()),
+ #[cfg(feature = "federation")]
("store-party", self.store_party.is_some()),
#[cfg(feature = "federation")]
("store-readers", !self.store_readers.is_empty()),
diff --git a/src/federation/held.rs b/src/federation/held.rs
index cd53727..fd43062 100644
--- a/src/federation/held.rs
+++ b/src/federation/held.rs
@@ -111,6 +111,10 @@ pub(crate) struct Holding {
members: RwLock<Option<BTreeSet<(String, String)>>>,
/// What it votes for its party with, if it votes by itself.
voter: Option<Voter>,
+ /// Where the set of events carrying the store is kept (`--store-document`), if it
+ /// is; and how it stood as it was last written there.
+ document: Option<(PathBuf, Arc<Files>)>,
+ written: Mutex<Option<super::store::passing::Stamp>>,
/// Whether a set of events carries the store (`carrying`), from the node's start on.
of_a_set: bool,
// A std mutex: never held while waiting for the document.
@@ -264,6 +268,8 @@ impl Holding {
members: RwLock::default(),
voter: None,
of_a_set: false,
+ document: None,
+ written: Mutex::default(),
inner: Mutex::new(Inner {
kept,
..Inner::default()
@@ -1034,6 +1040,51 @@ impl Holding {
self
}
+ /// Itself, its store carried by `set` and kept in the file at `path`, where the node
+ /// is given a set.
+ pub(crate) fn carrying_if(
+ self,
+ set: Option<Set<Federation>>,
+ path: Option<PathBuf>,
+ files: Arc<Files>,
+ ) -> Self {
+ match (set, path) {
+ (Some(set), Some(path)) => self.carrying(set).kept_in(path, files),
+ (Some(set), None) => self.carrying(set),
+ (None, _) => self,
+ }
+ }
+
+ /// Itself, keeping the set of events that carries its store in the file at `path`.
+ pub(crate) fn kept_in(mut self, path: PathBuf, files: Arc<Files>) -> Self {
+ self.document = Some((path, files));
+ self
+ }
+
+ /// Lets go of what a checkpoint forgot longer ago than the set keeps it, and
+ /// writes the set to its file where it changed since it was last written.
+ /// Whether it wrote.
+ pub(crate) fn save(&self) -> std::io::Result<bool> {
+ let Some((path, files)) = &self.document else {
+ return Ok(false);
+ };
+ let now = Instant::now();
+ self.change_set(|set| set.expire(now));
+ let mut written = self.written.lock_or_recover();
+ let Some((stands, bytes)) = self
+ .with_set(|set| {
+ let stands = super::store::passing::stamp(set);
+ (Some(stands) != *written).then(|| (stands, set.save(now)))
+ })
+ .flatten()
+ else {
+ return Ok(false);
+ };
+ files.write_atomic(FileKind::Store, path, &bytes)?;
+ *written = Some(stands);
+ Ok(true)
+ }
+
/// The kind of the document that carries the store: a set of events, or the
/// document the node holds, which the store is read from.
pub(crate) fn kind(&self) -> &'static str {
@@ -1314,7 +1365,18 @@ pub(crate) async fn run_worker(state: crate::state::AppState) {
}
}
}
- _ = looks.tick() => look = true,
+ _ = looks.tick() => {
+ look = true;
+ // A set of events to its file, where it changed (`Holding::save`).
+ if state.of_a_set() {
+ let holding = Arc::clone(&state.holding);
+ if let Ok(Err(error)) =
+ tokio::task::spawn_blocking(move || holding.save()).await
+ {
+ error!(error = %error, "Couldn't write the store's document: a restart goes on from what the file holds");
+ }
+ }
+ }
}
}
}
diff --git a/src/lib.rs b/src/lib.rs
index da106b9..8b56399 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -221,11 +221,29 @@ pub async fn run() -> Result<()> {
#[cfg(feature = "federation")]
let store =
bootstrap::StoreStart::of(args.store_root.as_deref(), args.store_id.as_deref(), &files)?;
+ // Its store's own document, a set of events (`--store-document`): from its file,
+ // or from the root.
+ #[cfg(feature = "federation")]
+ let set = match (&store, &args.store_document) {
+ (Some(store), Some(path)) => Some(store.set(path, &files, args.store_keeps_forgotten)?),
+ _ => None,
+ };
#[cfg(feature = "federation")]
let starting = match &store {
- Some(store) => {
+ Some(store) if set.is_none() => {
store.starting(starting, remembered.as_ref().map(|r| r.swarm_id.as_str()))?
}
+ // A set is the store's document: the one a swarm syncs otherwise stays empty.
+ Some(store) => {
+ let swarm_id = store.swarm_id();
+ if let Some(remembered) = remembered.as_ref().filter(|r| r.swarm_id != swarm_id) {
+ anyhow::bail!(
+ "The state file remembers swarm {}, not the store's ({swarm_id}): give the store's state file, or another",
+ remembered.swarm_id
+ );
+ }
+ None
+ }
None => starting,
};
let (
@@ -372,7 +390,8 @@ pub async fn run() -> Result<()> {
args.store_party.clone(),
)?
.near(args.store_neighbour_parties.clone())
- .voting(voter(args)?),
+ .voting(voter(args)?)
+ .carrying_if(set, args.store_document.clone(), Arc::clone(&files)),
strict_keys: args
.strict_keys
.iter()
@@ -394,7 +413,13 @@ pub async fn run() -> Result<()> {
// Join the remembered swarm and no other; HELLOs claim it. A document to start on
// names its swarm itself (checked against the remembered one above).
+ #[cfg(feature = "federation")]
+ let of_a_set = state.of_a_set();
+ #[cfg(not(feature = "federation"))]
+ let of_a_set = false;
let start = match starting_swarm {
+ // A set of events is what the node starts on: its store's swarm (`bootstrap`).
+ _ if of_a_set => bootstrap::Start::FromDocument(bootstrap::Origin::Root),
Some((swarm_id, origin)) => {
state.set_expected_swarm_id(swarm_id).await?;
bootstrap::Start::FromDocument(origin)
@@ -486,6 +511,10 @@ pub async fn run() -> Result<()> {
swarm::state_file::update(&state, true).await;
swarm::document_file::flush(&state).await;
swarm::document_file::close(&state).await;
+ #[cfg(feature = "federation")]
+ if let Err(error) = state.holding.save() {
+ tracing::error!(error = %error, "Couldn't write the store's document as the node stops");
+ }
Ok(())
}
diff --git a/src/simtest/holding.rs b/src/simtest/holding.rs
index 4a8098b..6da7a90 100644
--- a/src/simtest/holding.rs
+++ b/src/simtest/holding.rs
@@ -1806,3 +1806,125 @@ async fn a_swarm_of_sets_passes_entries_and_events_on() {
assert!(node.doc.read().await.heads().is_empty());
}
}
+
+/// Starts `name`, of `party`, on a set of events `set`, kept in the file at `path` where
+/// given: the first of them with no seed, the others seeded by `a`.
+fn start_on_a_set(
+ sim: &Sim,
+ name: &str,
+ party: &str,
+ id: Id,
+ set: crate::federation::store::set::Set<Federation>,
+ path: Option<std::path::PathBuf>,
+ restart: bool,
+) -> AppState {
+ let seeds: Vec<&str> = if name == "a" { Vec::new() } else { vec!["a"] };
+ let party = party.to_owned();
+ let adjust = move |config: &mut NodeConfig| {
+ config.store = Some(id);
+ config.holding = holding(&party).carrying_if(Some(set), path, Arc::new(Files::default()));
+ };
+ if restart {
+ sim.restart_with(name, &seeds, Start::FromDocument(Origin::Root), adjust)
+ } else {
+ sim.start_with(name, &seeds, Start::FromDocument(Origin::Root), adjust)
+ }
+}
+
+/// A set of events begun from `root`.
+fn a_set(root: &[u8]) -> crate::federation::store::set::Set<Federation> {
+ crate::federation::store::set::Set::new(
+ Store::<Federation>::new(root.to_vec(), Vec::new()).expect("a root"),
+ Duration::from_secs(600),
+ )
+}
+
+/// a and b hold events; c, of another party, starts later from the root alone, and
+/// catches up: it comes to hold what they hold, and to stand as they do.
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn a_node_of_a_set_that_is_behind_catches_up() {
+ let sim = Sim::with_identity(92);
+ let (tv, lass, _) = three();
+ let (_, root, id) = federation(&[(&tv, &["a", "b"]), (&lass, &["c"])]);
+ let a = start_on_a_set(&sim, "a", "tv", id, a_set(&root), None, false);
+ let b = start_on_a_set(&sim, "b", "tv", id, a_set(&root), None, false);
+ sim.wait_ready(&[&a, &b], SOON).await;
+ // A chain of writes, each on the one before.
+ let mut on = id;
+ let mut ids = Vec::new();
+ for n in 0..30 {
+ let write = tv.write(&[on], "home/tv/x", s(&n.to_string()));
+ on = Id::of(&write);
+ ids.push(on);
+ put(&a, &[&write]).await;
+ }
+ let (first, ids) = (&[&a, &b], &ids);
+ sim.wait_until("a and b hold the writes", SOON, move || async move {
+ first.iter().all(|node| holds(node, ids))
+ })
+ .await;
+
+ let c = start_on_a_set(&sim, "c", "lass", id, a_set(&root), None, false);
+ let all = &[&a, &b, &c];
+ sim.wait_until("c holds them too", SOON, move || async move {
+ holds(all[2], ids)
+ })
+ .await;
+ sim.wait_until("all stand alike", SOON, move || async move {
+ let first = stands(all[0]);
+ first.is_some() && all.iter().all(|node| stands(node) == first) && entries(all[2]) == 3
+ })
+ .await;
+}
+
+/// A node keeps its set in a file, written as the set changes; started again on what
+/// the file holds, it holds what it held, the others' entries among it, before it hears
+/// of anyone.
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn a_node_of_a_set_goes_on_from_its_file() {
+ let sim = Sim::with_identity(93);
+ let (tv, _, _) = three();
+ let (_, root, id) = federation(&[(&tv, &["a", "b"])]);
+ let dir = crate::files::scratch_dir("set-file");
+ let path = dir.join("b.events");
+ let a = start_on_a_set(&sim, "a", "tv", id, a_set(&root), None, false);
+ let b = start_on_a_set(&sim, "b", "tv", id, a_set(&root), Some(path.clone()), false);
+ sim.wait_ready(&[&a, &b], SOON).await;
+ let write = tv.write(&[id], "home/tv/x", s("1"));
+ let ids = [Id::of(&write)];
+ put(&a, &[&write]).await;
+ let (nodes, ids) = (&[&a, &b], &ids);
+ sim.wait_until(
+ "both hold the write and both entries",
+ SOON,
+ move || async move {
+ nodes
+ .iter()
+ .all(|node| holds(node, ids) && entries(node) == 2)
+ },
+ )
+ .await;
+ assert!(b.holding.save().expect("written") || path.exists());
+
+ let bytes = std::fs::read(&path).expect("the set's file");
+ let set = crate::federation::store::set::Set::<Federation>::load(
+ &bytes,
+ Duration::from_secs(600),
+ std::time::Instant::now(),
+ )
+ .expect("a set");
+ let b = start_on_a_set(&sim, "b", "tv", id, set, Some(path), true);
+ // What the file held, at once.
+ assert!(holds(&b, ids));
+ assert_eq!(entries(&b), 2);
+ // And it goes on: a write put on it reaches a.
+ sim.wait_ready(&[&b], SOON).await;
+ let next = tv.write(&[ids[0]], "home/tv/x", s("2"));
+ let next_id = [Id::of(&next)];
+ put(&b, &[&next]).await;
+ let (a, next_id) = (&a, &next_id);
+ sim.wait_until("a holds what b wrote after", SOON, move || async move {
+ holds(a, next_id)
+ })
+ .await;
+}
diff --git a/src/swarm/bootstrap.rs b/src/swarm/bootstrap.rs
index 24da958..9d29c5b 100644
--- a/src/swarm/bootstrap.rs
+++ b/src/swarm/bootstrap.rs
@@ -322,6 +322,53 @@ impl StoreStart {
}))
}
+ /// The store's own document, a set of events (`--store-document`), kept in the file
+ /// at `path`: as the file has it, where there is one, which must be this store's;
+ /// else begun from the root, which the node must be given then. What a checkpoint
+ /// forgot is kept for `keeps`.
+ pub(crate) fn set(
+ &self,
+ path: &Path,
+ files: &Files,
+ keeps: std::time::Duration,
+ ) -> Result<crate::federation::store::set::Set<crate::federation::fold::Federation>> {
+ use crate::federation::fold::Federation;
+ use crate::federation::store::{memory::Store, set::Set};
+ let now = std::time::Instant::now();
+ let held = files
+ .read(FileKind::Store, path)
+ .with_context(|| format!("Reading the store's document {}", path.display()))?;
+ if let Some(bytes) = held {
+ let set = Set::<Federation>::load(&bytes, keeps, now).map_err(|refused| {
+ anyhow::anyhow!(
+ "The store's document {} doesn't read ({}): move it away only knowing the node then starts from the root, and may take what it refused",
+ path.display(),
+ refused.0
+ )
+ })?;
+ if set.store().id() != self.id {
+ bail!(
+ "The store's document {} is of store {}, not {}",
+ path.display(),
+ set.store().id(),
+ self.id
+ );
+ }
+ info!(swarm_id = %self.id, path = %path.display(), "Going on with the store's document");
+ return Ok(set);
+ }
+ let Some((root, kept)) = &self.root else {
+ bail!(
+ "store-document {} doesn't exist, and store-id names no root to begin it from: give the store's root (store-root)",
+ path.display()
+ );
+ };
+ let store = Store::<Federation>::new(root.clone(), kept.clone())
+ .map_err(|refused| anyhow::anyhow!("The store's root is none: {}", refused.0))?;
+ info!(swarm_id = %self.id, "Starting the swarm holding the store from its root, as a set of events (--store-document)");
+ Ok(Set::new(store, keeps))
+ }
+
/// The swarm's ID: the root's, in hex.
pub(crate) fn swarm_id(&self) -> String {
self.id.to_string()
@@ -651,6 +698,50 @@ mod tests {
assert!(joining.starting(None, None).unwrap().is_none());
}
+ #[cfg(feature = "federation")]
+ #[test]
+ fn a_stores_document_is_begun_from_the_root_or_gone_on_with() {
+ use crate::federation::harness::{self, Party, Spec};
+ use crate::federation::store::memory::Offered;
+ use std::time::{Duration, Instant};
+
+ let tv = Party::new("tv", 1);
+ let root = Spec::first(&[&tv], &[]).root();
+ let id = Id::of(&root);
+ let store = StoreStart {
+ id,
+ root: Some((root.clone(), Vec::new())),
+ };
+ let joining = StoreStart { id, root: None };
+ let dir = crate::files::scratch_dir("store-document");
+ let path = dir.join("store.events");
+ let files = Files::default();
+ let keeps = Duration::from_secs(60);
+ // No file: from the root, which joining by the ID alone doesn't give.
+ assert!(joining.set(&path, &files, keeps).is_err());
+ let mut set = store.set(&path, &files, keeps).unwrap();
+ let write = tv.write(&[id], "home/tv/a", harness::str("1"));
+ assert!(matches!(
+ set.offer(write.clone(), Instant::now()),
+ Offered::Taken(_)
+ ));
+ std::fs::write(&path, set.save(Instant::now())).unwrap();
+ // A file: gone on with, the root given or not.
+ for start in [&store, &joining] {
+ let read = start.set(&path, &files, keeps).unwrap();
+ assert_eq!(read.store().taken(), &[Id::of(&write)]);
+ }
+ // Of another store, or no document: refused.
+ let other_root = Spec::first(&[&Party::new("lass", 2)], &[]).root();
+ let other = StoreStart {
+ id: Id::of(&other_root),
+ root: Some((other_root, Vec::new())),
+ };
+ assert!(other.set(&path, &files, keeps).is_err());
+ std::fs::write(&path, b"something else").unwrap();
+ assert!(store.set(&path, &files, keeps).is_err());
+ }
+
/// A fork's root, and the event it keeps on a line of its own: the swarm starts from
/// the changes founding it. Without that event: no store's root.
#[test]