diff options
52 files changed, 3237 insertions, 213 deletions
diff --git a/CHANGELOG.md b/CHANGELOG.md index d5c6ac5..ff27c0c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,22 @@ it from the release before ([`docs/operations.md`](docs/operations.md), ## Unreleased +* A swarm holding a store can hold it in a document of its own kind, a set of events, + instead of in the Automerge document: `--store-document PATH`, beside `--store-root` + or `--store-id`, names the set's file, and such a node syncs with nodes on a set and + no others. There are no changes, writers, epochs or remakes in it: events are passed + on by their names, nodes catch up by ranges of names and their fingerprints, and a + node that starts with nothing asks members for the root, or the checkpoint + `--store-checkpoint` names, by its name. What a checkpoint forgot is kept for + `--store-keeps-forgotten` (30 days). A swarm on Automerge moves to it node by node, + each node for a while of both kinds (`--store-both`): it syncs with nodes of either, + and carries between them ([`docs/operations.md`](docs/operations.md), + [Moving to sets of events](docs/operations.md#moving-to-sets-of-events)) + ([`docs/document.md`](docs/document.md), + [A set of events](docs/document.md#a-set-of-events); + [`src/federation/store/set.rs`](src/federation/store/set.rs), + [`src/swarm/set.rs`](src/swarm/set.rs)). + * Wire version 53, spoken beside 52, so a swarm upgrades node by node: what is the document's of a message (a SYNC's body and what vouches for it, where a STATUS says the sender stands, what a BLOB request asks for in bulk) goes as bytes the wire carries diff --git a/docs/development.md b/docs/development.md index 0e98af2..7a8f7e6 100644 --- a/docs/development.md +++ b/docs/development.md @@ -144,6 +144,15 @@ tag's nodes log this tree's as such, so their operators know to upgrade. scripts/wire-check v0.0.1 ``` +`scripts/sets-check` runs a federation of this tree on this host, over libp2p on +loopback, and moves it from Automerge documents to sets of events as its operators +would ([`operations.md`](operations.md), +[Moving to sets of events](operations.md#moving-to-sets-of-events)): three nodes of +two parties on the document, each started again of both kinds, then on its set alone, +then all at once from their sets' files, and a fourth joining with the store's ID +alone. After each start a value written through the party's client at one node is +read at every node, with all that was written before, and no node logs an error. + A change to the wire format is a new version (`wire::VERSION`) beside the ones the build speaks already: the messages of the version before keep their types, frozen, and are encoded and decoded in `transport/wire.rs` beside the newest's, and `golden_bytes` keeps diff --git a/docs/document.md b/docs/document.md index 17dca62..07d3420 100644 --- a/docs/document.md +++ b/docs/document.md @@ -336,6 +336,14 @@ upgrades node by node. A node that speaks 52 alone says no kind, and is of the k there was then; nodes of different kinds refuse each other in the handshake, saying so, and sync nothing. +What another kind says goes in the same two messages (`SyncBody::Kind`, +`HeadsSummary::Kind`): a SYNC's body is one of Automerge's, or another kind's bytes; a +STATUS's stamp is Automerge's heads, or another kind's bytes after a byte no Automerge +stamp begins with. Version 52 says neither. What a SYNC and a STATUS say beside, that +the sender is ready, when it sent, whose tree a push is along, whom it reaches, is for +every kind; the epoch, a body taken as delivered, heads announced and what vouches for +changes are Automerge's, and a node of another kind says one epoch and leaves the rest. + ### As merged state without a history would give it To see that what is asked isn't Automerge's in other words: @@ -626,7 +634,10 @@ among nodes that don't trust each other, no cut by time holds. ## A set of events -Not built: a kind, `events`, for a swarm holding a store ([`store.md`](store.md)). The +A kind, `events`, for a swarm holding a store ([`store.md`](store.md)): built. A node +is of it where its operator says so ([As built](#as-built), below), and a swarm on +Automerge moves to it node by node +([From an Automerge document to this](#from-an-automerge-document-to-this)). The store asks nothing of what carries its events, and what makes an Automerge document carry them is most of what a swarm holding a store has to get right ([On Automerge](store.md#on-automerge)): the changes that may write an event, the @@ -656,7 +667,9 @@ held; and where the fold takes it at its history, which every node judges alike. the fold refuses there is held by nobody. One whose history takes it and that the node itself refuses or doesn't read (a node's own: what it took before, its operator's drops, where it stopped) is held and passed on all the same, as the document holds it -today: so that what one node doesn't read still reaches the nodes that do. +today: so that what one node doesn't read still reaches the nodes that do. A node that +stopped holds back what comes after, as it can't tell which of it will be taken, and +passes that on alike, until it takes again: then it holds of it what it took. What builds on such an event, the node can't judge: it holds no history to judge it at. Where nodes took different ones of two versions that changed the same, or an @@ -721,6 +734,34 @@ What the store promises ([What is promised](store.md#what-is-promised)) it promi now; "nothing underneath adds an event or takes one away" is then true by what the document is, not by what is put again. +### As built + +A node holds its store in a set of events where it is given `--store-document`, the +set's file, beside `--store-root` or `--store-id`. It then says `events` for its kind +in its handshakes, and syncs with nodes that say so and no others. + +* **The set** ([`federation/store/set.rs`](../src/federation/store/set.rs)): the store, + and beside it what the store lets go of and the node still gives; the members' + entries ([`entry.rs`](../src/federation/store/entry.rs)); its names, kept as it + changes; its file, written where it changed, every five seconds and as the node + stops. +* **Passing on** ([`federation/store/passing.rs`](../src/federation/store/passing.rs), + [`swarm/set.rs`](../src/swarm/set.rs)): where the node stands goes in its STATUSes, + the checkpoint's and the heads' digest with the fingerprint of all its names; the + rest in SYNCs' bodies: ranges ([`document/ranges.rs`](../src/document/ranges.rs)), + heads, the names it wants, events and entries. What it took goes on to its other + neighbours at once. Nothing is kept of a peer between messages. +* **Starting**: from the file; without one, from the root, where given and no + checkpoint is pinned; else with nothing, asking the members it reaches for the + checkpoint named by the store's ID or by `--store-checkpoint`, and for the events + that one keeps, each taken as what its name says. +* **The node's own entry** is what `swarm::members` writes of a member, put as the + node's next entry; its other writes of protocol data are refused. What reads + members, the policy and the swarm's ID of a document reads them of the set + (`Holding::entries`). +* **The document the node holds beside** is an Automerge document with nothing in it: + nothing syncs it, remakes it or writes to it, and the API's `/store` holds nothing. + ### From an Automerge document to this A store is its root and its events, whatever carries them: a node of this kind reads @@ -729,8 +770,22 @@ without a new federation and without a vote, by **a node of both kinds for a whi release whose node can hold the store in both at once, a member of both, and takes into each what the other holds, as it puts events again today. Operators move their nodes one at a time; once none is of the old kind, the next release drops it for a swarm -holding a store. From the release that has this kind, no swarm holding a store is -started on Automerge: one that runs there runs on, until it has moved. +holding a store. + +Built: a node given `--store-both` beside `--store-document` holds its store in the +Automerge document and in a set ([`swarm/set.rs`](../src/swarm/set.rs), +`Holding::of_both`). It takes handshakes of either kind and says to each peer the kind +that peer holds; passes the Automerge document on to the ones and its set to the +others; puts into the document what its set took of peers on sets, and passes on to +them what its set took of the document; and writes its entry in both. Its set, without +a file yet, is made of the store as the node reads it of its document, so it begins +where the document does, a checkpoint a remake left among it. Nodes on the document +alone and nodes on a set alone take none of each other's handshakes: what goes between +them goes through the nodes of both +([`operations.md`](operations.md), [Moving to sets of events](operations.md#moving-to-sets-of-events)). + +Not built: that no swarm holding a store is started on Automerge any more. One that +runs there runs on, until it has moved. ## What others do diff --git a/docs/guides/federation/README.md b/docs/guides/federation/README.md index 104a04c..c9b0205 100644 --- a/docs/guides/federation/README.md +++ b/docs/guides/federation/README.md @@ -28,9 +28,9 @@ by them, in its words. * [`voting-by-itself.md`](voting-by-itself.md): a node voting and proposing for its party by its operator's rules: its key, its record, following, proposing checkpoints. * [`refusals-and-drops.md`](refusals-and-drops.md): what a node refuses and what of it - is its own, the store file, dropping events and taking them back. -* [`remakes.md`](remakes.md): compactions only, the electorate, the snapshot, putting - again after a switch, two epochs for one, and rejoining. + is its own, what is kept across restarts, dropping events and taking them back. +* [`remakes.md`](remakes.md): in the Automerge document, compactions only, the electorate, + the snapshot, putting again after a switch, two epochs for one, and rejoining. * [`upgrades.md`](upgrades.md): upgrading the nodes of a federated swarm, what the federation's number and its revision say, and moving to a later revision. * [`watching.md`](watching.md): what a node's API and its log say that needs an operator diff --git a/docs/guides/federation/building-on-the-api.md b/docs/guides/federation/building-on-the-api.md index 45394ed..1f01954 100644 --- a/docs/guides/federation/building-on-the-api.md +++ b/docs/guides/federation/building-on-the-api.md @@ -91,5 +91,6 @@ already: a write is an event every node keeps until a checkpoint leaves it out. ## Not through the store API -A node of a federated swarm refuses writes through the store API (`/store`): the document -takes events and each node's own protocol data only. +A node of a federated swarm refuses writes through the store API (`/store`), which holds +nothing of the store where it is a set of events: a federation takes events and each +node's own protocol data only. diff --git a/docs/guides/federation/checkpoints.md b/docs/guides/federation/checkpoints.md index 072fc80..12d08a9 100644 --- a/docs/guides/federation/checkpoints.md +++ b/docs/guides/federation/checkpoints.md @@ -114,10 +114,15 @@ Votes and proposals aren't signed again: their version is behind. ## Nodes that weren't there -A node reads its store at every start from its document's checkpoint, or from the one -its operator pins (`--store-checkpoint`), which it finds in its document. Until a remake -leaves out what a checkpoint forgot, the document holds what came before, and a node -that was away builds the checkpoint from it as any. After such a remake, a node away -across it, or joining, takes the checkpoint only where its operator pins it: ask a node -you trust for it (`checkpoint` in `GET /events`) +A node that was away across a move builds the checkpoint itself, as any: the others keep +what the checkpoint forgot for a while (`--store-keeps-forgotten`, 30 days unless +given), and give it what it lacks. A node away for longer, or joining, starts from the +checkpoint only where its operator pins it (`--store-checkpoint`), with nothing of the +store yet: ask a node you trust for it (`checkpoint` in `GET /events`) ([`running-a-node.md`](running-a-node.md), [Joining](running-a-node.md#joining)). + +A node keeping its store in the Automerge document reads it at every start from its +document's checkpoint, or from the one its operator pins, which it finds in its +document. Until a remake leaves out what a checkpoint forgot, the document holds what +came before, and a node that was away builds the checkpoint from it; after such a +remake, it takes the checkpoint only where its operator pins it. diff --git a/docs/guides/federation/forking-and-following.md b/docs/guides/federation/forking-and-following.md index 63b7c40..441f4f9 100644 --- a/docs/guides/federation/forking-and-following.md +++ b/docs/guides/federation/forking-and-following.md @@ -48,7 +48,7 @@ go. The rules are the design's ([`federation.md`](../../federation.md), `--at 4a1d 9e30` names the heads for the others. The fork is named by its root's ID, the SHA-256 of its root (the file's first line), which nobody can steer. 4. **Start it**: a node carries one swarm, so the founders start the fork's nodes with - files of their own (state, document, store file), from the root + files of their own (state, the set of events), from the root (`--store-root fork-root`), or by its ID through one of them (`--store-id`), each with its party (`--store-party`). 5. **Begin a record there**: a fork is a store of its own, and a party that never voted diff --git a/docs/guides/federation/getting-started.md b/docs/guides/federation/getting-started.md index 33f9181..8b7e5f3 100644 --- a/docs/guides/federation/getting-started.md +++ b/docs/guides/federation/getting-started.md @@ -107,11 +107,12 @@ Keep it: a party that loses its record casts nothing on the current version ## Starting -tv's node starts the federation from the root: +tv's node starts the federation from the root, and holds it in a set of events, kept in +a file (`--store-document`): ```sh -continuum --store-root root --store-party tv --store-file store.json \ - --state-file state.json --document-file document --node-key-file node.key \ +continuum --store-root root --store-party tv --store-document events \ + --state-file state.json --node-key-file node.key \ --htpasswd htpasswd --mycelium-enable curl -s -u tv:secret localhost:3000/events # {"checkpoint":"6d1e…","heads":["6d1e…"],"party":"tv","store":"6d1e…","taken":0, @@ -122,15 +123,21 @@ lass's node joins it by its ID, through tv's node, one of whose addresses it is (`addresses` in `GET /admin/stats` there): ```sh -continuum --store-id 6d1e… --store-party lass --store-file store.json \ - --seeds mycelium:… --state-file state.json --document-file document \ +continuum --store-id 6d1e… --store-party lass --store-document events \ + --seeds mycelium:… --state-file state.json \ --node-key-file node.key --htpasswd htpasswd --mycelium-enable ``` -Nodes sync with the nodes the parties list, and with no others: both are in the first -version. A party lists another node of its own by itself, without a vote +It asks tv's node for the root by its ID, and for everything after. Nodes sync with the +nodes the parties list, and with no others: both are in the first version. A party lists +another node of its own by itself, without a vote ([`common-changes.md`](common-changes.md#what-a-party-does-by-itself)). +A federation that keeps its store in the Automerge document (`--document-file`, +`--store-file`, no `--store-document`) goes on so, and moves to sets of events node by +node ([`operations.md`](../../operations.md), +[Moving to sets of events](../../operations.md#moving-to-sets-of-events)). + ## Writing and reading tv writes in its namespace, through its node: @@ -209,8 +216,8 @@ continuum-party --node http://lass:secret@localhost:3000 --key lass.key \ Once a node holds both votes, it writes the version, and every node takes it: `continuum-party status` says version 1. makefu's node, started with -`--store-id 6d1e… --store-party makefu` and a seed, is a member now: the others sync -with it, and makefu writes in its namespace as tv did. +`--store-id 6d1e… --store-party makefu --store-document events` and a seed, is a member +now: the others sync with it, and makefu writes in its namespace as tv did. ## What next diff --git a/docs/guides/federation/promises.md b/docs/guides/federation/promises.md index 733c713..c6ba2eb 100644 --- a/docs/guides/federation/promises.md +++ b/docs/guides/federation/promises.md @@ -40,8 +40,9 @@ to whom. A party whose machine is taken over whole is the adversary from then on * **Good votes**: a party may vote badly; a `true` binds it while its proposal can pass, and only other parties' nays free it: parties that never vote hold it there. * **Delivery**: what a party's nodes withhold reaches nobody through them. -* **Speed and uptime**: a party that floods the store, or keeps remakes from committing, - makes nodes slow or runs them out of memory, never wrong. The others fork away from it. +* **Speed and uptime**: a party that floods the store, or, where it is kept in the + Automerge document, keeps remakes from committing, makes nodes slow or runs them out of + memory, never wrong. The others fork away from it. * **One swarm where keys voted twice**: each node keeps the version it took, and nodes part, until their operators choose ([`when-things-go-wrong.md`](when-things-go-wrong.md)). @@ -59,7 +60,7 @@ to whom. A party whose machine is taken over whole is the adversary from then on ([`keys.md`](keys.md), [`proposing-and-voting.md`](proposing-and-voting.md)); vote from one client; back only what you mean to, as a `true` binds. * **An operator**: give your node seeds you trust, pin checkpoints you got from nodes you - trust, and keep its store file ([`running-a-node.md`](running-a-node.md)). + trust, and keep the file of its set ([`running-a-node.md`](running-a-node.md)). * **An application**: read from a node you trust, as what it answers is its word; check the events yourself where that matters ([`writing-and-reading.md`](writing-and-reading.md), diff --git a/docs/guides/federation/refusals-and-drops.md b/docs/guides/federation/refusals-and-drops.md index 1d29df1..40f37de 100644 --- a/docs/guides/federation/refusals-and-drops.md +++ b/docs/guides/federation/refusals-and-drops.md @@ -26,17 +26,21 @@ curl -s -u tv:secret localhost:3000/events/refused or larger than it allows), `judged` (refused at its history), `builtOn` (built on `on`, refused), `notAbove` (not above the checkpoint's heads, as a move refuses it). -A change of another node that a node refuses doesn't take its events with it: the store -takes them as from anywhere (`Took events a refused change carried`), and the node puts -them again. - ## Kept across restarts -A node reads its store anew from its document at every start; what it refused of its -own, and what it dropped, it keeps in its store file (`--store-file`), written whenever -it changes. Without the file, a restart may take what it refused; a file that doesn't -read stops the node from starting; one it can't write it logs (`Couldn't write the store -file`). +What a node refused of its own, and what it dropped, is in its set's file +(`--store-document`) with the events, written where the set changed, every five seconds +and as the node stops; started again, the node goes on from it. Without the file, the +node joins anew, and may take what it refused; a file that doesn't read stops the node +from starting; one it can't write it logs (`Couldn't write the store's document`). + +A node keeping its store in the Automerge document reads it anew from that document at +every start, and keeps what it refused of its own and what it dropped in its store file +(`--store-file`), written whenever it changes: without it, a restart may take what it +refused, and one that doesn't read stops the node from starting (`Couldn't write the +store file`, where it can't write it). A change of another node that such a node refuses +doesn't take its events with it: the store takes them as from anywhere (`Took events a +refused change carried`), and the node puts them again. ## Dropping @@ -57,7 +61,8 @@ events from whoever brings them, and any version event naming a version among th whoever wrote it anew; it writes none itself, though it holds the votes passing it, and keeps so across restarts. Not what its checkpoint keeps or holds by ID: every event after it builds on that. A move to a checkpoint is undone -only by a checkpoint its operator pins (`--store-checkpoint`). +only by starting from a checkpoint its operator pins (`--store-checkpoint`), anew +([`running-a-node.md`](running-a-node.md), [Joining](running-a-node.md#joining)). ## Taking back diff --git a/docs/guides/federation/remakes.md b/docs/guides/federation/remakes.md index 05c27ab..5897ba4 100644 --- a/docs/guides/federation/remakes.md +++ b/docs/guides/federation/remakes.md @@ -1,5 +1,12 @@ # Remakes under a federation +A node holding its store in a set of events (`--store-document`) has nothing to remake: +it holds no changes, no writers and no epochs, and what it holds shrinks by the +federation's checkpoints alone ([`checkpoints.md`](checkpoints.md)). This guide is for a +federation that keeps its store in the Automerge document, until it moved +([`operations.md`](../../operations.md), +[Moving to sets of events](../../operations.md#moving-to-sets-of-events)). + A remake moves a swarm to a new document, for Automerge's sake only: the store needs none, and its events stay what they are. A federated swarm takes compactions only. How a remake runs is as in any swarm ([`remakes.md`](../../remakes.md)); this guide says what is diff --git a/docs/guides/federation/running-a-node.md b/docs/guides/federation/running-a-node.md index 27ee3a0..2392578 100644 --- a/docs/guides/federation/running-a-node.md +++ b/docs/guides/federation/running-a-node.md @@ -1,29 +1,37 @@ # Running a node of a federation -A node of a federated swarm runs as any continuum node: its node key, its state and -document files, its transports, a supervisor ([`operations.md`](../../operations.md)). -This guide says what is otherwise: the options of a swarm holding a store, who syncs, -what its API lets in, and joining. +A node of a federated swarm runs as any continuum node: its node key, its state file, +its transports, a supervisor ([`operations.md`](../../operations.md)). This guide says +what is otherwise: the options of a swarm holding a store, who syncs, what its API lets +in, and joining. + +A node holds its store in a set of events, kept in a file (`--store-document`), which +this guide describes; or in the Automerge document any swarm syncs, as federations +started before sets did, and do until they move +([In the Automerge document](#in-the-automerge-document), below). Nodes of the one and +nodes of the other don't sync with each other. ## Its options * `--store-root FILE` starts the swarm from its root, or goes on with it: the file the founders made (`continuum-party root`), the root on its first line and, for a fork, - the events the root keeps, a line each. The node builds the changes founding the - swarm from it, as every node given the file builds them, and is ready at once. -* `--store-id ID` joins the swarm by its ID, the root's SHA-256, through `--seeds`. - Joining with an empty document, the node takes as its root that store's genesis change - only. + the events the root keeps, a line each. The node begins its set from it, as every + node given the file does, and is ready at once. +* `--store-id ID` joins the swarm by its ID, the root's SHA-256, through `--seeds` + ([Joining](#joining), below). * `--store-party NAME`, which both need: the party the node is of, named in its entry and its handshakes. It is a member once that party's node list names it ([Who syncs](#who-syncs)). -* `--store-file PATH`: what is the node's own, written whenever it changes: the events - it refused by what it took before (of two versions changing one, the second it judged) - and those its operator had it drop. A node reads its store anew from its document - whenever it starts: without the file, it may then take what it refused. Keep it beside - the document file; one that doesn't read stops the node from starting. -* `--store-checkpoint ID`: a checkpoint the node reads its store from whenever it starts, - instead of from the document's checkpoint, by its ID ([Joining](#joining), below). +* `--store-document PATH`: the file of the node's set of events, written where the set + changed, every five seconds and as the node stops: the store's events, what the node + refused by what it took before (of two versions changing one, the second it judged), + what its operator had it drop, and the members' entries. Started again, the node goes + on from it. One that doesn't read, or is of another store, stops the node from + starting. +* `--store-checkpoint ID`: the checkpoint a node joining with nothing begins its set + from, instead of the root, by its ID ([Joining](#joining), below). +* `--store-keeps-forgotten DURATION` (30 days unless given): for how long the node keeps + what a checkpoint its store moved to forgot, for nodes still before that checkpoint. * `--store-neighbour-parties NAME,…`: parties among whose members, with its own party's, the node keeps some of its neighbours. * `--store-vote-key PATH` and the options with it: the node votes and proposes for its @@ -37,10 +45,11 @@ node refuses to start with them. ## Its files Beside those of every node ([`lifecycle.md`](../../lifecycle.md), -[What the files are for](../../lifecycle.md#what-the-files-are-for)), the store file. Back -up the node key, as every node's: its node ID is what its party lists, and a new key is a -new node, which the party lists anew. The document file and the store file go together: -the store file says what the node refuses of what the document holds. +[What the files are for](../../lifecycle.md#what-the-files-are-for)), the file of its +set, and no document file: the document a swarm syncs otherwise stays empty. Back up the +node key, as every node's: its node ID is what its party lists, and a new key is a new +node, which the party lists anew. Back up the set's file too: a node without it joins +anew, and may then take what it refused. ## Who syncs @@ -90,50 +99,83 @@ alone, so that a party listing many nodes can't be all of a node's neighbours. (whether it takes a `true` a party is about to cast); and its operator's: `POST /admin/events/drop`, `/admin/events/allow`, `/admin/events/vote`, `/admin/events/fork`. Each answers `404` while the node holds no store. -* **The store API** (`/store`) reads the document, where events are bytes at - `_continuum/events/<ID>`; what counts is read at `GET /events/counts`. A write through - it is refused (`403`): the document takes events and each node's own protocol data - only. +* **The store API** (`/store`) holds nothing: events are read at `GET /events/{id}`, + what counts at `GET /events/counts`. A write through it is refused (`403`): the set + takes events and each node's own entry only. So is a remake (`/admin/remakes`, `400`: + `this node's document is a set of events: there is nothing to remake`). ## Joining -A node with an empty document joins by the store's ID (`--store-id`) through a member -(`--seeds`), and holds its store once it has read the document: `GET /events` answers -then. It learns of other members as it syncs, and needs none of its seeds once it has: -they may go away. Before a checkpoint passed, it reads from the root: of two versions -changing one, which keys voting twice wrote, it takes the first it judges, as any node, -and reports the other (`own` in `GET /events/refused`), for you to choose +A node with nothing of the store joins by its ID (`--store-id`) through a member +(`--seeds`): it asks the members it reaches for the root by its ID, takes what hashes to +it, and holds its store then (`Begun the store's set from what peers gave by name`): +`GET /events` answers. Everything after it catches up on as it syncs. It learns of other +members so, and needs none of its seeds once it has: they may go away. Before a +checkpoint passed, it reads from the root: of two versions changing one, which keys +voting twice wrote, it takes the first it judges, as any node, and reports the other +(`own` in `GET /events/refused`), for you to choose ([`when-things-go-wrong.md`](when-things-go-wrong.md)). Once the store moved to a checkpoint, a node joining starts from that checkpoint, which its operator pins by its ID (`--store-checkpoint`): ask a node you trust for it -(`checkpoint` in `GET /events`). The node finds it in its document, built from what the -document holds as any node builds it, and holds no store until then (`The pinned -checkpoint isn't in the document (yet)`). It takes no epoch whose snapshot holds a -checkpoint it neither builds nor has pinned: from the root, it would take what was grown -anew from it since, by keys of versions long replaced. +(`checkpoint` in `GET /events`). The node asks the members it reaches for the checkpoint +by that ID, and for the events it keeps, and holds no store until it has them all. From +the root, it would take what was grown anew from it since, by keys of versions long +replaced. The pin counts only while the node has no file of its set: with one, it goes on +from there. -A node that was away across a move to a checkpoint builds that checkpoint from its -document, which holds what came before until a remake leaves it out; after such a remake, -it takes the checkpoint only where its operator pins it. Pin it, and restart the node. +A node that was away across a move to a checkpoint builds that checkpoint itself, from +what the others keep of what the checkpoint forgot (`--store-keeps-forgotten`). Away for +longer than they keep it, it stays before the checkpoint, and the others refuse what it +writes: start it anew, without its set's file and with the checkpoint pinned. It then +holds none of what it refused of its own or dropped +([`refusals-and-drops.md`](refusals-and-drops.md)). ## What it writes by itself * **A version that passed**, as soon as it holds the votes passing it (`Writing a version that passed`): any node may write it, and the same version written by several is one. -* **Events its document lacks**, that its store would take and that it has: after a - remake, a rejoin, or a change of another node it refused (`Put again events the - document lacked`). * **Merge events**, under a revision with them, where its party lists it and its store holds more heads than an event may name (64): signed with its node key, a random wait after there first were (`Merged heads beyond what an event may name`). They count for nothing, and gather the heads apart, so that what is written after builds on them all. -* **Its own protocol data**: its entry, its acks of remakes, and the remakes it - coordinates. Remakes are compactions only, acked by the members - ([`remakes.md`](../../remakes.md)). +* **Its own entry**: where it is reached, its party, and what else a member says of + itself, signed with its node key and counted, the latest taken. It refuses events as every node does, and some by what it took before: of two versions changing the one it reads, the second it judged (`Refused an event its history takes, by what this node took before: kept so`). `GET /events/refused` lists them apart (`own`): tell its party, which decides what the node keeps. + +## In the Automerge document + +A federation started before sets of events keeps its store in the document every swarm +syncs: its nodes run without `--store-document`, and move there node by node, through +`--store-both` ([`operations.md`](../../operations.md), +[Moving to sets of events](../../operations.md#moving-to-sets-of-events)). Until then, +what is otherwise at such a node: + +* **Its options and files**: `--document-file`, as any node's, and `--store-file PATH`, + what is the node's own, written whenever it changes: the events it refused by what it + took before, and those its operator had it drop. The node reads its store anew from + its document whenever it starts: without the store file, it may then take what it + refused. The two go together; a store file that doesn't read stops the node from + starting. +* **Starting and joining**: given the root, the node builds the changes founding the + swarm from it; joining with an empty document, it takes as its root that store's + genesis change only, and holds its store once it has read the document. A pinned + checkpoint (`--store-checkpoint`) it finds in its document, built from what the + document holds, at every start, and holds no store until then (`The pinned checkpoint + isn't in the document (yet)`). +* **A node that was away** across a move to a checkpoint builds it from its document, + which holds what came before until a remake leaves it out; after such a remake, it + takes the checkpoint only where its operator pins it. Pin it, and restart the node. +* **The store API** (`/store`) reads the document, where events are bytes at + `_continuum/events/<ID>`; a write through it is refused (`403`): the document takes + events and each node's own protocol data only. +* **What it writes by itself** besides: events its document lacks, that its store would + take and that it has, after a remake, a rejoin, or a change of another node it refused + (`Put again events the document lacked`); and its acks of remakes, and the remakes it + coordinates. Remakes are compactions only, acked by the members + ([`remakes.md`](remakes.md)). diff --git a/docs/guides/federation/upgrades.md b/docs/guides/federation/upgrades.md index 92cedc4..4cec3af 100644 --- a/docs/guides/federation/upgrades.md +++ b/docs/guides/federation/upgrades.md @@ -12,10 +12,10 @@ A node of a federated swarm upgrades as any node does restarted with its files, and a release's version says how: a patch or a minor release one node at a time, a major one every node close together. Nodes write each other the newest wire version both speak; where two releases share none, a major one, upgraded nodes and -the others don't talk, and the swarm is split until all are upgraded. A remake needs the -same Automerge on every node, and one with another rejoins instead of switching. Before -1.0.0, the first part of the version that isn't 0 counts as the major one (`0.2.0` after -`0.1.1` is a flag day). +the others don't talk, and the swarm is split until all are upgraded. Where the store is +kept in the Automerge document, a remake needs the same Automerge on every node, and one +with another rejoins instead of switching. Before 1.0.0, the first part of the version +that isn't 0 counts as the major one (`0.2.0` after `0.1.1` is a flag day). Nobody runs every node of a federated swarm: each party's operators upgrade its nodes. A patch or minor release each party takes when it likes; for a major one, agree on when, diff --git a/docs/guides/federation/watching.md b/docs/guides/federation/watching.md index a60b1ab..f3e8ccb 100644 --- a/docs/guides/federation/watching.md +++ b/docs/guides/federation/watching.md @@ -107,10 +107,12 @@ At warn or error: takes events again` once its operator had it drop that event; * `This node isn't a member of its store, as it reads now: its party doesn't list it, and members don't sync with it`; -* `The pinned checkpoint isn't in the document (yet): holding no store until it is`; +* `The pinned checkpoint isn't in the document (yet): holding no store until it is`, at + a node keeping its store in the Automerge document; * `The document's root is no store's: not reading it`, `Reading the store from the document failed`; -* `Couldn't write the store file: a restart may take what this node refused`: a full or +* `Couldn't write the store's document: a restart goes on from what the file holds`, + `Couldn't write the store file: a restart may take what this node refused`: a full or read-only disk; * `Couldn't vote by itself`, `Voting by itself, without its party's record: votes none`; * `Couldn't put what it signed for its party: put again later`, `Couldn't write a version diff --git a/docs/guides/federation/when-things-go-wrong.md b/docs/guides/federation/when-things-go-wrong.md index 8326f72..5bd7f62 100644 --- a/docs/guides/federation/when-things-go-wrong.md +++ b/docs/guides/federation/when-things-go-wrong.md @@ -11,7 +11,7 @@ rules are the design's ([`federation.md`](../../federation.md), Two versions changing one are written only where keys voted twice: a party's `true` and `false` on one proposal, each shown to some, or its `true` on two. Each node takes the first it judges and refuses the other, with everything built on it, and keeps so across -restarts (`--store-file`); its log says so (`Refused an event its history takes, by what +restarts; its log says so (`Refused an event its history takes, by what this node took before: kept so`), `continuum-party status` says so, and `GET /events/refused` lists it under `own`: @@ -61,7 +61,8 @@ curl -u tv:secret -X POST -H 'Content-Type: application/json' \ The node refuses what it dropped from then on, from whoever brings it, and writes no version naming what it dropped, until it is allowed again. A node drops only what it took after its checkpoint: a version that moved it to a checkpoint it undoes only by -taking a checkpoint its operator pins (`--store-checkpoint`). +starting from a checkpoint its operator pins (`--store-checkpoint`), anew, without its +set's file ([`running-a-node.md`](running-a-node.md), [Joining](running-a-node.md#joining)). The parties answer keys that voted twice by forking, without the party that voted twice (`continuum-party fork remove lass`) or with its keys named anew (`fork keys lass @@ -75,7 +76,7 @@ record. A node stops at a version event writing a version that passed on the version it reads, which its continuum doesn't read: of a later federation, using what a later continuum takes, or none at all. It takes nothing and refuses nothing from then on, and votes -nothing by itself or by hand; what is put through it, it still writes into the document +nothing by itself or by hand; what is put through it, it holds back and passes on (`stopped` when put). Its log says so (`The store stopped at an event this continuum can't judge`), and `GET /events` names the event, why, and how many it holds back: @@ -94,7 +95,7 @@ makes a version none ([`proposing-and-voting.md`](proposing-and-voting.md), Upgrade the node to a continuum that reads it: restarted, it reads its store anew and takes it. Where none does (two thirds passed a proposal that is no version), have the node drop that event: it goes on under the version before, refuses the event and any writing -that version, and keeps so (`--store-file`): +that version, and keeps so across restarts: ```sh curl -u tv:secret -X POST -H 'Content-Type: application/json' \ @@ -102,11 +103,12 @@ curl -u tv:secret -X POST -H 'Content-Type: application/json' \ # {"dropped":["9a1e…"]} ``` -Allowed again (`/admin/events/allow`), it stops there once more. A node that stopped -keeps none of it in its store file: restarted, it stops there again. What it holds back -it leaves out of nothing, as it can't tell which will be taken: it puts it again where its -document lacks it, and a remake keeps it, so a remake while nodes are stopped loses none -of what was put since. +Allowed again (`/admin/events/allow`), it stops there once more. What a node holds back, +it leaves out of nothing, as it can't tell which will be taken: it passes it on to the +other nodes, which take it where they read that version, and keeps it in its set's file; +restarted, it stops there again. A node keeping its store in the Automerge document puts +what it holds back again where its document lacks it, and a remake keeps it, so a remake +while nodes are stopped loses none of what was put since. ## A node doing less than it should @@ -119,8 +121,8 @@ of what was put since. (`continuum-party nodes --add`), through any member. * **An event waits** (`waiting` when put): the node lacks an event it builds on. It takes it once that one arrives. -* **It doesn't start**: its store file doesn't read, or an option of a swarm that isn't - federated is set ([`running-a-node.md`](running-a-node.md), +* **It doesn't start**: the file of its set doesn't read, or an option of a swarm that + isn't federated is set ([`running-a-node.md`](running-a-node.md), [Its options](running-a-node.md#its-options)). * **A write is refused**: [`writing-and-reading.md`](writing-and-reading.md), [Why a write is refused](writing-and-reading.md#why-a-write-is-refused). diff --git a/docs/operations.md b/docs/operations.md index e99a914..b12af28 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -155,6 +155,40 @@ A node upgrades by restarting with its files. What to know: (`automerge` in `--version`), and a release changing it says so in the change log. * **The dashboard** reloads by itself once its node serves another version of it. +## Moving to sets of events + +A swarm holding a store keeps it in the Automerge document, or in a document of the +store's own kind, a set of events ([`document.md`](document.md), +[A set of events](document.md#a-set-of-events)): no changes, writers, epochs or remakes, +and nothing to compact but by the federation's checkpoints. A running swarm moves there +node by node, the federation as it is: its root, its events and its votes are the same. + +Nodes on the document alone and nodes on a set alone don't sync with each other. Nodes +of both kinds do with either, and carry between them, so move every node through that: + +1. **Every node on a release that has sets** (`--version` says wire versions up to 53 + at least), one at a time, as any upgrade. +2. **Every node of both kinds**, one at a time: start it again with `--store-document + PATH`, a new file, and `--store-both`, everything else as it was, its + `--document-file` and `--store-file` among it. It goes on with its document, makes + its set of the store it reads there, and keeps it in the file. +3. **Every node on its set alone**, one at a time, once all are of both: start it + again without `--store-both`, `--document-file` and `--store-file`. It goes on from + the set's file. + +Between the steps, the swarm works as ever: an event put on any node reaches every +node. Within a step, it works as long as the nodes of both kinds reach each other and +every other node reaches one of them; `GET /events` on each node shows whether its +store holds what the others' hold (`heads`). + +A node that joins later is given `--store-id`, `--store-document` and seeds: with +nothing of the store, it asks the members it reaches for the root by its name, or, with +`--store-checkpoint`, for that checkpoint. + +Don't remake while nodes are of both kinds: a node of both follows a remake as any node +on the document, but that it then carries on between the two is not something a test +covers. + ## Behind a reverse proxy The HTTP API speaks plain HTTP on `127.0.0.1:3000`; a reverse proxy in front adds TLS. diff --git a/docs/store.md b/docs/store.md index f1e7586..a72164c 100644 --- a/docs/store.md +++ b/docs/store.md @@ -249,6 +249,11 @@ The store's first home is a swarm's document, which continuum's sync, transports and remakes carry. A swarm holds a store from its genesis change, or not at all, and its document holds nothing but the store and continuum's protocol data. +Its other home is a document of its own kind, a set of events, where a node is given +`--store-document` ([`document.md`](document.md), [A set of events](document.md#a-set-of-events)): +there the store's events are the document, and what this section says of changes, +writers, putting again and remakes isn't. + ### What the document holds | Where | What | diff --git a/scripts/sets-check b/scripts/sets-check new file mode 100755 index 0000000..8deb7fe --- /dev/null +++ b/scripts/sets-check @@ -0,0 +1,219 @@ +#!/bin/sh +# Runs a federation of this tree's continuum on this host, over libp2p on loopback, and +# moves it from Automerge documents to sets of events node by node, as its operators +# would (docs/operations.md: Moving to sets of events), through the nodes' API and the +# party's client all along: +# +# * a and b of tv, c of lass, each holding the store in its Automerge document; +# * each started again of both kinds (--store-document, --store-both); +# * each started again on its set alone; +# * all stopped, and started from their sets' files; +# * d, which tv lists then, joining with nothing but the store's ID. +# +# After each start, a value written at one node is read at every other, and what was +# written before is still read. No node logs an error. +# +# scripts/sets-check +# +# Built with CONTINUUM_FEATURES (`most` unless given; libp2p and federation among +# them). The nodes listen from CONTINUUM_SETS_CHECK_PORT on (47700 unless given), eight +# ports. + +set -eu + +cd "$(git rev-parse --show-toplevel)" + +features=${CONTINUUM_FEATURES:-most} +port=${CONTINUUM_SETS_CHECK_PORT:-47700} +say() { echo "sets-check: $*" >&2; } + +work=$(mktemp -d) +failed=false +clean() { + for pid in "$work"/*/pid; do + [ -f "$pid" ] && kill "$(cat "$pid")" 2>/dev/null || true + done + wait 2>/dev/null || true + if $failed; then + for log in "$work"/*/log; do + [ -f "$log" ] || continue + say "the last of $(basename "$(dirname "$log")")'s log:" + tail -n 25 "$log" >&2 + done + fi + rm -rf "$work" +} +trap clean EXIT +trap 'exit 130' INT TERM +fail() { + failed=true + say "$*" + exit 1 +} + +say "building this tree (features $features)" +cargo build -q --features "$features" --bin continuum --bin continuum-party +bin=${CARGO_TARGET_DIR:-$(pwd)/target}/debug +node=$bin/continuum +party=$bin/continuum-party + +number() { # NAME: a 0, b 1, c 2, d 3 + case $1 in a) echo 0 ;; b) echo 1 ;; c) echo 2 ;; d) echo 3 ;; esac +} +http() { echo $((port + $(number "$1"))); } +p2p() { echo $((port + 4 + $(number "$1"))); } +seed() { echo "libp2p:/ip4/127.0.0.1/tcp/$(p2p "$1")"; } +party_of() { + case $1 in c) echo lass ;; *) echo tv ;; esac +} + +# Keys of the parties, and of the nodes, whose IDs the first version names. +for name in tv lass; do + ssh-keygen -q -t ed25519 -N '' -f "$work/$name.key" +done +for name in a b c d; do + mkdir "$work/$name" + "$node" node-id --create "$work/$name/node.key" >"$work/$name/id" 2>/dev/null +done +id_of() { tail -n 1 "$work/$1/id"; } +"$party" found --name sets-check "tv=$work/tv.key.pub" "lass=$work/lass.key.pub" \ + --nodes "tv=$(id_of a),$(id_of b)" --nodes "lass=$(id_of c)" >"$work/first.json" +"$party" root "$work/first.json" >"$work/root" +# The store's ID: the SHA-256 of the root, the file's first line. +store=$(printf '%s' "$(head -n 1 "$work/root")" | sha256sum | cut -d' ' -f1) +# Each party's record of its votes, which its client writes by. +for name in tv lass; do + "$party" --record "$work/$name.record" init "$name" --root "$work/root" >/dev/null +done +say "the federation $store: a and b of tv, c of lass" + +start() { # NAME [OPTION...]: the node, with what every start of it has + name=$1 + shift + (cd "$work/$name" && exec "$node" --bind-addr "127.0.0.1:$(http "$name")" \ + --user-header X-User --node-key-file node.key --state-file state.json \ + --libp2p-enable --libp2p-listen "/ip4/127.0.0.1/tcp/$(p2p "$name")" \ + --store-party "$(party_of "$name")" "$@" >>log 2>&1) & + echo $! >"$work/$name/pid" +} +stop() { # NAME + kill "$(cat "$work/$1/pid")" 2>/dev/null || true + wait "$(cat "$work/$1/pid")" 2>/dev/null || true + rm -f "$work/$1/pid" +} +# Whether the command $2... succeeds within $1 seconds, tried every second. +within() { + seconds=$1 + shift + while ! "$@" >/dev/null 2>&1; do + seconds=$((seconds - 1)) + [ "$seconds" -gt 0 ] || return 1 + sleep 1 + done +} +ready() { curl -sf "http://127.0.0.1:$(http "$1")/ready"; } +# The party's client at a node, as that node's party: it logs in by the party's key. +client() { # NAME COMMAND... + name=$1 + shift + "$party" --node "http://127.0.0.1:$(http "$name")" \ + --key "$work/$(party_of "$name").key" \ + --record "$work/$(party_of "$name").record" "$@" +} +reads() { # NAME PATH VALUE: whether the node reads the value there + [ "$(client "$1" read "$2" 2>/dev/null)" = "$3" ] +} +written="" +# Writes a value at NAME, as its party, and waits until every node of $nodes reads it, +# and everything written before. +write_and_read() { # NAME KEY + path="home/$(party_of "$1")/$2" + within 30 client "$1" write "$path" "\"$2\"" || { + client "$1" write "$path" "\"$2\"" >&2 || true + fail "$1 takes no write at $path" + } + written="$written $path=$2" + for at in $nodes; do + for pair in $written; do + within 60 reads "$at" "${pair%%=*}" "\"${pair##*=}\"" || + fail "$at doesn't read ${pair%%=*} (written at $1)" + done + done + say "written at $1, read at$(printf ' %s' $nodes): $path" +} +kind() { # NAME: the kinds the node says it holds, as its log has them + grep -c "as a set of events\|Going on with the store's document\|Begun the store's set" \ + "$work/$1/log" || true +} + +# On the Automerge document: a from the root, b and c by the store's ID. +automerge() { # NAME + case $1 in + a) start a --store-root "$work/root" --store-file store.json --document-file document ;; + *) start "$1" --store-id "$store" --store-file store.json --document-file document \ + --seeds "$(seed a)" ;; + esac +} +nodes="a b c" +for name in $nodes; do + automerge "$name" + within 60 ready "$name" || fail "$name isn't ready on its Automerge document" +done +write_and_read a first +write_and_read c second + +# Of both kinds, one at a time, everything else as it was. +for name in $nodes; do + stop "$name" + case $name in + a) start a --store-root "$work/root" --store-file store.json --document-file document \ + --store-document set.events --store-both ;; + *) start "$name" --store-id "$store" --store-file store.json --document-file document \ + --seeds "$(seed a)" --store-document set.events --store-both ;; + esac + within 60 ready "$name" || fail "$name isn't ready of both kinds" + write_and_read "$name" "both-$name" +done +for name in $nodes; do + within 30 test -s "$work/$name/set.events" || fail "$name wrote no file of its set" +done + +# On its set alone, one at a time, from the set's file. +alone() { # NAME + case $1 in + a) start a --store-id "$store" --store-document set.events --seeds "$(seed b)" ;; + *) start "$1" --store-id "$store" --store-document set.events --seeds "$(seed a)" ;; + esac +} +for name in $nodes; do + stop "$name" + alone "$name" + within 60 ready "$name" || fail "$name isn't ready on its set alone" + write_and_read "$name" "set-$name" +done + +# All down, and up again from their sets' files. +for name in $nodes; do + stop "$name" +done +for name in $nodes; do + alone "$name" +done +for name in $nodes; do + within 60 ready "$name" || fail "$name isn't ready again" +done +write_and_read b again + +# A node tv lists then, with nothing but the store's ID. +client a nodes --add "$(id_of d)" >/dev/null 2>&1 || fail "tv doesn't list d" +start d --store-id "$store" --store-document set.events --seeds "$(seed a)" +within 60 ready d || fail "d isn't ready: it didn't begin its set from what members gave" +nodes="a b c d" +write_and_read d joined + +if grep -l ' ERROR \|panicked' "$work"/*/log >/dev/null 2>&1; then + failed=true + grep -h ' ERROR \|panicked' "$work"/*/log | head -n 10 >&2 + fail "a node logged an error" +fi +say "moved to sets of events, node by node: every write read everywhere, at every step" diff --git a/src/api/cors.rs b/src/api/cors.rs index 287daf1..6ead19f 100644 --- a/src/api/cors.rs +++ b/src/api/cors.rs @@ -50,8 +50,10 @@ async fn allowed(state: &AppState, origin: &str) -> bool { return true; } let replica = state.doc.read().await; - members::members(&replica.doc).iter().any(|member| { - members::dashboard(&replica.doc, member) + let entries = state.entries(); + let listed = &crate::document::view::members_of(&entries, &replica.doc); + members::members(listed).iter().any(|member| { + members::dashboard(listed, member) .and_then(|url| origin_of(&url)) .is_some_and(|theirs| theirs == origin) }) diff --git a/src/api/dashboard/mod.rs b/src/api/dashboard/mod.rs index f5a91ac..5d74df4 100644 --- a/src/api/dashboard/mod.rs +++ b/src/api/dashboard/mod.rs @@ -354,6 +354,8 @@ async fn build(state: &AppState, graph: &Graph) -> JsonValue { let peers = serde_json::to_value(&list).unwrap_or_default(); let (aliases, dashboards, remakes) = { let replica = state.doc.read().await; + let entries = state.entries(); + let listed = &crate::document::view::members_of(&entries, &replica.doc); // The remakes of our epoch, with who voted: the map shows them. let remakes = crate::remake::current( &state.remake, @@ -362,11 +364,11 @@ async fn build(state: &AppState, graph: &Graph) -> JsonValue { state.clock.now_millis(), state.timing.dormant_after.as_millis() as u64, ); - let dashboards: std::collections::HashMap<String, String> = members::members(&replica.doc) + let dashboards: std::collections::HashMap<String, String> = members::members(listed) .into_iter() - .filter_map(|pk| members::dashboard(&replica.doc, &pk).map(|url| (pk, url))) + .filter_map(|pk| members::dashboard(listed, &pk).map(|url| (pk, url))) .collect(); - (members::aliases(&replica.doc), dashboards, remakes) + (members::aliases(listed), dashboards, remakes) }; let local = state.local_id(); let intended: Map<String, JsonValue> = graph diff --git a/src/api/events.rs b/src/api/events.rs index 1c4b826..3fece6e 100644 --- a/src/api/events.rs +++ b/src/api/events.rs @@ -235,7 +235,11 @@ async fn heard(state: &AppState) -> std::collections::HashMap<String, u64> { /// checkpoint, what its parties signed that moving there /// refuses (`beside`, `signed_beside`). async fn counts(State(state): State<AppState>) -> Response { - let aliases = crate::swarm::members::aliases(&state.doc.read().await.doc); + let entries = state.entries(); + let aliases = crate::swarm::members::aliases(&crate::document::view::members_of( + &entries, + &state.doc.read().await.doc, + )); let heard = heard(&state).await; with_store(&state, |store| { let read = store.state(); diff --git a/src/api/login.rs b/src/api/login.rs index e442ea2..09c68df 100644 --- a/src/api/login.rs +++ b/src/api/login.rs @@ -115,10 +115,12 @@ pub(crate) async fn bearer( let now = state.clock.now_millis().as_u64(); let verified = { let replica = state.doc.read().await; - let verified = token::verify(&replica.doc, &text, &swarm, now); + let entries = state.entries(); + let listed = &crate::document::view::members_of(&entries, &replica.doc); + let verified = token::verify(listed, &text, &swarm, now); #[cfg(feature = "federation")] let verified = - verified.and_then(|claims| token::issued_here(&replica.doc, state.local_id(), claims)); + verified.and_then(|claims| token::issued_here(listed, state.local_id(), claims)); verified } .and_then(|claims| { @@ -559,17 +561,17 @@ async fn credentials_end( /// sessions. async fn refused_now(state: &AppState, who: &Credentials) -> Option<token::Refused> { let replica = state.doc.read().await; + let entries = state.entries(); + let listed = &crate::document::view::members_of(&entries, &replica.doc); match who { - Credentials::Token(claims) => { - token::still_taken(&replica.doc, claims).err().or_else(|| { - state - .ended_sessions - .lock_or_recover() - .contains_key(&claims.session) - .then_some(token::Refused::Ended) - }) - } - Credentials::User(user) => token::user_taken(&replica.doc, user).err(), + Credentials::Token(claims) => token::still_taken(listed, claims).err().or_else(|| { + state + .ended_sessions + .lock_or_recover() + .contains_key(&claims.session) + .then_some(token::Refused::Ended) + }), + Credentials::User(user) => token::user_taken(listed, user).err(), } } diff --git a/src/api/peers.rs b/src/api/peers.rs index 586c32d..ed7d97f 100644 --- a/src/api/peers.rs +++ b/src/api/peers.rs @@ -171,7 +171,11 @@ pub(crate) async fn peer_list(state: &AppState) -> PeerListResponse { let now = Instant::now(); let local_epoch = state.local_epoch(); - let mut aliases = crate::swarm::members::aliases(&state.doc.read().await.doc); + let entries = state.entries(); + let mut aliases = crate::swarm::members::aliases(&crate::document::view::members_of( + &entries, + &state.doc.read().await.doc, + )); let names = crate::swarm::reach::names(&state).await; let named = |keys: Vec<u64>| -> Vec<String> { let mut named: Vec<String> = keys diff --git a/src/api/stats.rs b/src/api/stats.rs index a5fe0d8..651d6ba 100644 --- a/src/api/stats.rs +++ b/src/api/stats.rs @@ -308,13 +308,11 @@ pub(crate) async fn collect(state: &AppState, list: &PeerListResponse) -> StatsR let (heads, tier, remakes) = { let replica = state.doc.read().await; + let entries = state.entries(); + let listed = &crate::document::view::members_of(&entries, &replica.doc); let heads = replica.heads().len(); let remakes = crate::remake::summary(&state.remake, &replica.doc, replica.epoch); - ( - heads, - members::tier(&replica.doc, state.local_id()), - remakes, - ) + (heads, members::tier(listed, state.local_id()), remakes) }; let now_ms = state.clock.now_millis(); let saved = state.stats.saved_size(); diff --git a/src/config/mod.rs b/src/config/mod.rs index efc190d..e68b60c 100644 --- a/src/config/mod.rs +++ b/src/config/mod.rs @@ -216,6 +216,30 @@ 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. Without the file yet, the node begins it from the root where it is given one (store-root) and pins no checkpoint; else it joins with nothing, and gathers of the members it reaches what its set begins from, by name: the root, or the checkpoint store-checkpoint names. Can't be combined with store-file, which the file stands for.", + ), + #[cfg(feature = "federation")] + option( + "store-both", + Kind::Flag, + "BOOL", + Some("false"), + "With store-document: hold the store in the Automerge document too, and sync with nodes of either kind, taking into each what the other holds: an event that comes by one goes on by the other, and the node's entry is in both. For moving a running swarm to sets of events node by node (docs/document.md, From an Automerge document to this): a node is started with it, on the document it has, and without it once no node it reaches holds the Automerge document alone. Without the set's file yet, the set begins from the store as the node reads it of its document.", + ), + #[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 +833,17 @@ 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)] + pub(crate) store_both: bool, + #[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 +1105,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 +1371,8 @@ 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-both", self.store_both), ("store-party", self.store_party.is_some()), ("store-readers", !self.store_readers.is_empty()), ( @@ -1355,6 +1396,14 @@ impl Settings { return Ok(()); } }; + if self.store_document.is_some() && self.store_file.is_some() && !self.store_both { + bail!("store-document holds what store-file would: unset store-file"); + } + if self.store_both && self.store_document.is_none() { + bail!( + "store-both: set store-document, the file of the set of events the node holds beside its Automerge document" + ); + } 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 +1531,10 @@ 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-both", self.store_both), + #[cfg(feature = "federation")] ("store-party", self.store_party.is_some()), #[cfg(feature = "federation")] ("store-readers", !self.store_readers.is_empty()), @@ -1564,7 +1617,7 @@ fn command() -> Command { with_options(::config::arguments::with_print_config(command), OPTIONS) } -/// `continuum node-id FILE`: the node ID of the key in `FILE` (`Loaded::node_id`). +/// `continuum node-id FILE`: the node ID of the key in `FILE` (`asked_node_id`). const NODE_ID: &str = "node-id"; /// The configuration, and where each value set came from (absent: default). @@ -1575,9 +1628,6 @@ pub(crate) struct Loaded { pub(crate) files: Vec<PathBuf>, /// `--print-config`: print [`Loaded::report`] and exit. pub(crate) print_only: bool, - /// `node-id FILE [--create]`: print the node ID of the key `FILE` holds, made there - /// with `--create` where there is none, and exit. - pub(crate) node_id: Option<(PathBuf, bool)>, } impl Loaded { @@ -1647,22 +1697,30 @@ pub(crate) fn load() -> Result<Loaded> { ::config::arguments::refuse_gone(std::env::args().skip(1), &SCHEMA)?; let matches = command().get_matches(); let print_only = ::config::arguments::prints_config(&matches); - let node_id = matches.subcommand_matches(NODE_ID).map(|sub| { - let file = sub.get_one::<String>("file").expect("required"); - (PathBuf::from(file), sub.get_flag("create")) - }); - if print_only || node_id.is_some() { - // Logs go to stdout too: the report or the node ID goes there alone (the report - // says where each value came from anyway). + if print_only { + // Logs go to stdout too: the report goes there alone (it says where each value + // came from anyway). let _ = crate::logging::set_filter("off"); } let (merged, files) = merged(&matches, &SCHEMA, &[])?; let mut loaded = resolve(merged, files)?; loaded.print_only = print_only; - loaded.node_id = node_id; Ok(loaded) } +/// `node-id FILE [--create]`, where the command line asks for it: the file whose key's +/// node ID to print, made there with `--create` where there is none. Asked before +/// the configuration is read: it needs none of a node's, which a party's founders +/// don't have yet as they ask for their nodes' IDs. +pub(crate) fn asked_node_id() -> Option<(PathBuf, bool)> { + let matches = command().get_matches(); + let sub = matches.subcommand_matches(NODE_ID)?; + let file = sub.get_one::<String>("file").expect("required"); + // Logs go to stdout too: the node ID goes there alone. + let _ = crate::logging::set_filter("off"); + Some((PathBuf::from(file), sub.get_flag("create"))) +} + /// HyParView's active view, where `neighbours` isn't set: the paper's, for swarms of up /// to about 10 000 members (its fanout of 4, plus one). const HYPARVIEW_NEIGHBOURS: usize = 5; @@ -1768,7 +1826,6 @@ fn resolve(merged: Layer, files: Vec<PathBuf>) -> Result<Loaded> { .collect(), files, print_only: false, - node_id: None, }) } diff --git a/src/document/passing.rs b/src/document/passing.rs index 0b9a3dd..dc116e3 100644 --- a/src/document/passing.rs +++ b/src/document/passing.rs @@ -194,6 +194,7 @@ pub(crate) fn carried_bytes(body: &SyncBody) -> Option<usize> { SyncBody::Message(payload) | SyncBody::Deflated(payload) => Some(payload.0.len()), SyncBody::Changes { changes, .. } => Some(changes.iter().map(|change| change.len()).sum()), SyncBody::Delta(_) => None, + SyncBody::Kind(bytes) => Some(bytes.len()), } } diff --git a/src/document/view.rs b/src/document/view.rs index 018e8c0..8df88b3 100644 --- a/src/document/view.rs +++ b/src/document/view.rs @@ -116,3 +116,346 @@ pub(crate) fn delete_path( ) -> Result<(), StoreError> { doc.delete_path(path, prune) } + +/// A document that is a tree of JSON and nothing else: maps of maps, down to values. For +/// a kind that keeps what the node reads at paths otherwise (a set of events its +/// members' entries), and hands it over so; and for what writes there through `Write`, +/// which then looks at what the tree holds after. +#[derive(Clone, Debug, PartialEq)] +#[cfg_attr(not(feature = "federation"), allow(dead_code))] +pub(crate) struct Tree(pub(crate) JsonValue); + +#[cfg_attr(not(feature = "federation"), allow(dead_code))] +impl Default for Tree { + fn default() -> Self { + Self::new() + } +} + +impl Tree { + /// A tree holding nothing. + pub(crate) fn new() -> Self { + Tree(JsonValue::Object(serde_json::Map::new())) + } + + /// The value at `path`: through maps alone. + fn at(&self, path: &[String]) -> Result<Option<&JsonValue>, StoreError> { + let mut value = &self.0; + for key in path { + match value { + JsonValue::Object(map) => match map.get(key) { + Some(inner) => value = inner, + None => return Ok(None), + }, + _ => return Err(StoreError::Conflict), + } + } + Ok(Some(value)) + } +} + +impl Read for Tree { + fn read_path(&self, path: &[String]) -> Result<Option<JsonValue>, StoreError> { + Ok(self.at(path)?.cloned()) + } + + fn read_plain(&self, path: &[String]) -> Result<Option<JsonValue>, StoreError> { + self.read_path(path) + } + + fn read_typed(&self, path: &[String]) -> Result<Option<JsonValue>, StoreError> { + self.read_path(path) + } + + fn keys_at(&self, path: &[String]) -> Result<Option<Vec<String>>, StoreError> { + Ok(match self.at(path) { + Ok(Some(JsonValue::Object(map))) => Some(map.keys().cloned().collect()), + _ => None, + }) + } +} + +impl Write for Tree { + fn write_path(&mut self, path: &[String], value: &JsonValue) -> Result<(), StoreError> { + let mut at = &mut self.0; + for key in path { + if at.is_null() { + *at = JsonValue::Object(serde_json::Map::new()); + } + let JsonValue::Object(map) = at else { + return Err(StoreError::Conflict); + }; + at = map.entry(key.clone()).or_insert(JsonValue::Null); + } + *at = value.clone(); + Ok(()) + } + + fn delete_path(&mut self, path: &[String], prune: bool) -> Result<(), StoreError> { + let Some((last, above)) = path.split_last() else { + return Err(StoreError::NotFound); + }; + let mut at = &mut self.0; + for key in above { + match at { + JsonValue::Object(map) => match map.get_mut(key) { + Some(inner) => at = inner, + None => return Err(StoreError::NotFound), + }, + _ => return Err(StoreError::Conflict), + } + } + let JsonValue::Object(map) = at else { + return Err(StoreError::Conflict); + }; + if map.remove(last).is_none() { + return Err(StoreError::NotFound); + } + // The maps left empty above it, from the deepest up, the root never. + if prune { + for depth in (1..path.len()).rev() { + let Ok(Some(JsonValue::Object(map))) = self.at(&path[..depth]) else { + break; + }; + if !map.is_empty() { + break; + } + self.delete_path(&path[..depth], false)?; + } + } + Ok(()) + } +} + +/// Where the node reads its members, the policy and the swarm's ID: of what its +/// document keeps apart and hands over as a tree (`AppState::entries`), where it does, +/// over the document it holds. A node holding its store in a set of events alone reads +/// the tree, the document beside being empty; one holding it in both reads the members +/// of both. +pub(crate) fn members_of<'a>(entries: &'a Option<Tree>, doc: &'a dyn Read) -> Listed<'a> { + Listed { + over: entries.as_ref(), + under: doc, + } +} + +/// A tree over a document (`members_of`): at a path, what the tree holds there, else +/// what the document does; where both hold maps, the two as one, the tree's values over +/// the document's. +pub(crate) struct Listed<'a> { + over: Option<&'a Tree>, + under: &'a dyn Read, +} + +/// `over` on `under`: maps as one, key by key; anything else, `over`. +fn laid(over: JsonValue, under: JsonValue) -> JsonValue { + match (over, under) { + (JsonValue::Object(mut over), JsonValue::Object(under)) => { + for (key, below) in under { + let merged = match over.remove(&key) { + Some(above) => laid(above, below), + None => below, + }; + over.insert(key, merged); + } + JsonValue::Object(over) + } + (over, _) => over, + } +} + +impl Listed<'_> { + fn read( + &self, + path: &[String], + under: impl FnOnce(&dyn Read) -> Result<Option<JsonValue>, StoreError>, + ) -> Result<Option<JsonValue>, StoreError> { + let Some(over) = self.over else { + return under(self.under); + }; + // The tree first: where it holds a value that is no map, the document isn't + // asked, nor is what it holds on the way in the way. + match over.read_path(path) { + Ok(Some(above)) if !above.is_object() => Ok(Some(above)), + Ok(above) => match (above, under(self.under)) { + (Some(above), Ok(Some(below))) => Ok(Some(laid(above, below))), + (Some(above), _) => Ok(Some(above)), + (None, below) => below, + }, + Err(_) => under(self.under), + } + } +} + +impl Read for Listed<'_> { + fn read_path(&self, path: &[String]) -> Result<Option<JsonValue>, StoreError> { + self.read(path, |doc| doc.read_path(path)) + } + + fn read_plain(&self, path: &[String]) -> Result<Option<JsonValue>, StoreError> { + self.read(path, |doc| doc.read_plain(path)) + } + + fn read_typed(&self, path: &[String]) -> Result<Option<JsonValue>, StoreError> { + self.read(path, |doc| doc.read_typed(path)) + } + + fn keys_at(&self, path: &[String]) -> Result<Option<Vec<String>>, StoreError> { + let below = self.under.keys_at(path); + let Some(over) = self.over else { + return below; + }; + match (over.keys_at(path)?, below) { + (Some(mut above), Ok(Some(below))) => { + for key in below { + if !above.contains(&key) { + above.push(key); + } + } + Ok(Some(above)) + } + (Some(above), _) => Ok(Some(above)), + (None, below) => below, + } + } +} + +#[cfg(test)] +mod tree_tests { + use serde_json::json; + + use super::*; + + fn path(keys: &[&str]) -> Vec<String> { + keys.iter().map(|key| (*key).to_owned()).collect() + } + + #[test] + fn a_tree_reads_what_was_written() { + let mut tree = Tree::new(); + tree.write_path(&path(&["a", "b", "c"]), &json!(1)).unwrap(); + tree.write_path(&path(&["a", "d"]), &json!({"e": [1, 2]})) + .unwrap(); + assert_eq!( + tree.read_path(&path(&["a", "b", "c"])).unwrap(), + Some(json!(1)) + ); + assert_eq!( + tree.read_plain(&path(&["a", "d", "e"])).unwrap(), + Some(json!([1, 2])) + ); + assert_eq!( + tree.read_typed(&[]).unwrap(), + Some(json!({"a": {"b": {"c": 1}, "d": {"e": [1, 2]}}})) + ); + assert_eq!(tree.read_path(&path(&["a", "x"])).unwrap(), None); + assert_eq!(tree.read_path(&path(&["x", "y"])).unwrap(), None); + let mut keys = tree.keys_at(&path(&["a"])).unwrap().expect("a map"); + keys.sort(); + assert_eq!(keys, path(&["b", "d"])); + assert_eq!(tree.keys_at(&path(&["a", "b", "c"])).unwrap(), None); + assert_eq!(tree.keys_at(&path(&["x"])).unwrap(), None); + // Through a value that is no map: a conflict, as in any document. + assert!(matches!( + tree.read_path(&path(&["a", "b", "c", "z"])), + Err(StoreError::Conflict) + )); + assert!(matches!( + tree.write_path(&path(&["a", "b", "c", "z"]), &json!(1)), + Err(StoreError::Conflict) + )); + // Written over, it reads as the new value. + tree.write_path(&path(&["a", "b"]), &json!("v")).unwrap(); + assert_eq!( + tree.read_path(&path(&["a", "b"])).unwrap(), + Some(json!("v")) + ); + } + + #[test] + fn a_tree_deletes_and_prunes() { + let mut tree = Tree::new(); + tree.write_path(&path(&["a", "b", "c"]), &json!(1)).unwrap(); + tree.write_path(&path(&["a", "d"]), &json!(2)).unwrap(); + assert!(matches!( + tree.delete_path(&path(&["a", "x"]), false), + Err(StoreError::NotFound) + )); + tree.delete_path(&path(&["a", "b", "c"]), false).unwrap(); + assert_eq!(tree.read_path(&path(&["a", "b"])).unwrap(), Some(json!({}))); + tree.write_path(&path(&["a", "b", "c"]), &json!(1)).unwrap(); + tree.delete_path(&path(&["a", "b", "c"]), true).unwrap(); + // The map left empty went; the one that holds something stays. + assert_eq!( + tree.read_path(&path(&["a"])).unwrap(), + Some(json!({"d": 2})) + ); + tree.delete_path(&path(&["a", "d"]), true).unwrap(); + assert_eq!(tree.read_path(&[]).unwrap(), Some(json!({}))); + } + + #[test] + fn a_tree_over_a_document_reads_as_both() { + let mut under = Tree::new(); + under + .write_path(&path(&["m", "a"]), &json!({"alias": "a", "tier": 1})) + .unwrap(); + under + .write_path(&path(&["m", "b"]), &json!({"alias": "b"})) + .unwrap(); + under + .write_path(&path(&["only", "under"]), &json!(1)) + .unwrap(); + let mut over = Tree::new(); + over.write_path(&path(&["m", "a"]), &json!({"alias": "A"})) + .unwrap(); + over.write_path(&path(&["m", "c"]), &json!({"alias": "c"})) + .unwrap(); + over.write_path(&path(&["policy"]), &json!("p")).unwrap(); + let entries = Some(over); + let listed = members_of(&entries, &under); + // Keys of both; a map of both as one, the tree's values over the document's. + let mut keys = listed.keys_at(&path(&["m"])).unwrap().expect("a map"); + keys.sort(); + assert_eq!(keys, path(&["a", "b", "c"])); + assert_eq!( + listed.read_path(&path(&["m", "a"])).unwrap(), + Some(json!({"alias": "A", "tier": 1})) + ); + assert_eq!( + listed.read_path(&path(&["m", "a", "alias"])).unwrap(), + Some(json!("A")) + ); + assert_eq!( + listed.read_path(&path(&["m", "b", "alias"])).unwrap(), + Some(json!("b")) + ); + assert_eq!( + listed.read_plain(&path(&["m", "c", "alias"])).unwrap(), + Some(json!("c")) + ); + assert_eq!( + listed.read_typed(&path(&["policy"])).unwrap(), + Some(json!("p")) + ); + assert_eq!( + listed.read_path(&path(&["only", "under"])).unwrap(), + Some(json!(1)) + ); + assert_eq!(listed.read_path(&path(&["nowhere"])).unwrap(), None); + // No tree: the document as it is. + let none = None; + let listed = members_of(&none, &under); + assert_eq!( + listed.read_path(&path(&["m", "a", "alias"])).unwrap(), + Some(json!("a")) + ); + assert_eq!( + listed + .keys_at(&path(&["m"])) + .unwrap() + .map(|keys| keys.len()), + Some(2) + ); + } +} diff --git a/src/federation/held.rs b/src/federation/held.rs index ec3738f..39d6102 100644 --- a/src/federation/held.rs +++ b/src/federation/held.rs @@ -34,6 +34,7 @@ use super::event::{self, Does, Event, Signed}; use super::fold::Federation; use super::revision::Feature; use super::store::memory::{Built, Offered, Store}; +use super::store::set::Set; use super::store::{Fold, Id, Refused}; use super::version::Version; use super::vote::{self, Act, Rules, Seen}; @@ -110,6 +111,18 @@ 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, + /// Whether the node holds the store in the document a swarm syncs otherwise too + /// (`of_both`): a node of both kinds, by which a running swarm moves to sets. + both: bool, + /// For how long a set made of the store read from the document keeps what a + /// checkpoint forgot (`of_both`). + keeps_forgotten: Duration, // A std mutex: never held while waiting for the document. inner: Mutex<Inner>, } @@ -123,10 +136,64 @@ pub(crate) struct Voter { pub(crate) rules: Rules, } +/// A set of events as a node starts with it: held, from its file or begun from the +/// root; or still to be gathered of its peers, where the node was given neither. +pub(crate) enum Begun { + Set(Box<Set<Federation>>), + Start(super::store::passing::Start<Federation>), +} + +/// What carries the store: a document it is read from, or a set of events, which is +/// the store's own document (`store::set`). +enum Carried { + Store(Box<Store<Federation>>), + Set(Box<Set<Federation>>), +} + +impl std::ops::Deref for Carried { + type Target = Store<Federation>; + + fn deref(&self) -> &Store<Federation> { + match self { + Carried::Store(store) => store, + Carried::Set(set) => set.store(), + } + } +} + +impl Carried { + fn offer(&mut self, bytes: Vec<u8>) -> Offered { + match self { + Carried::Store(store) => store.offer(bytes), + Carried::Set(set) => set.offer(bytes, Instant::now()), + } + } + + fn drop_taken(&mut self, ids: &[Id]) -> Result<Vec<Id>, Refused> { + match self { + Carried::Store(store) => store.drop_taken(ids), + Carried::Set(set) => set.drop_taken(ids, Instant::now()), + } + } + + fn allow(&mut self, ids: &[Id]) { + match self { + Carried::Store(store) => store.allow(ids), + Carried::Set(set) => set.allow(ids, Instant::now()), + } + } +} + #[derive(Default)] struct Inner { /// None until a document holding a store holds its root. - store: Option<Store<Federation>>, + store: Option<Carried>, + /// A set of events to be, where the node started with nothing of its store and + /// gathers what its set begins from of its peers (`store::passing::Start`). + starting: Option<super::store::passing::Start<Federation>>, + /// What the set took of the document, to be passed on to the peers that hold sets + /// (`unpassed`): a node of both kinds takes into each what the other holds. + unpassed: Vec<Id>, /// The document read from (`Replica::epoch_seq`), and its events read. epoch_seq: Option<u32>, read: HashSet<Id>, @@ -219,6 +286,11 @@ impl Holding { near: Vec::new(), members: RwLock::default(), voter: None, + of_a_set: false, + both: false, + keeps_forgotten: Duration::ZERO, + document: None, + written: Mutex::default(), inner: Mutex::new(Inner { kept, ..Inner::default() @@ -322,7 +394,13 @@ impl Holding { match started { Ok(store) => { info!(store = %id, refused = own.len(), dropped = dropped.len(), "Reading the store from the document"); - inner.store = Some(store.refusing(&own, &dropped, &writes)); + let store = store.refusing(&own, &dropped, &writes); + // A node of both kinds: the store in a set too, from here on. + inner.store = Some(if self.of_a_set { + Carried::Set(Box::new(Set::new(store, self.keeps_forgotten))) + } else { + Carried::Store(Box::new(store)) + }); } Err(why) => { if inner.none.replace(id) != Some(id) { @@ -337,7 +415,13 @@ impl Holding { for (id, bytes) in unread.events { inner.read.insert(id); match store.offer(bytes) { - Offered::Taken(ids) => taken += ids.len(), + Offered::Taken(ids) => { + taken += ids.len(); + // To pass on, where a set carries the store too (`unpassed`). + if self.of_a_set { + inner.unpassed.extend(ids); + } + } Offered::Refused(why) => { refused += 1; info!(event = %id, why = ?why, "The store refuses an event the document holds"); @@ -491,6 +575,10 @@ impl Holding { /// what its store's checkpoint keeps, then what it took after it, then what it holds /// back, stopped (`Store::held_back`). pub(crate) fn lacking(&self, doc: &impl ReadDoc) -> Vec<(Id, Vec<u8>)> { + // A set of events alone is the store's own document: it lacks none of it. + if self.of_a_set && !self.both { + return Vec::new(); + } let mut held: HashSet<Id> = events::ids(doc).into_iter().collect(); let mut inner = self.inner.lock_or_recover(); inner.left.retain(|(id, _)| !held.contains(id)); @@ -968,7 +1056,210 @@ impl Holding { /// `f` of the store, where the node holds one. pub(crate) fn with<T>(&self, f: impl FnOnce(&Store<Federation>) -> T) -> Option<T> { - self.inner.lock_or_recover().store.as_ref().map(f) + self.inner.lock_or_recover().store.as_deref().map(f) + } + + /// Itself, its store carried by `set`: the store's own document, read from no + /// other (`store::set`). + pub(crate) fn carrying(mut self, set: Set<Federation>) -> Self { + self.of_a_set = true; + { + let mut inner = self.inner.lock_or_recover(); + inner.store = Some(Carried::Set(Box::new(set))); + self.settle(&mut inner); + } + self + } + + /// Itself, its store to be carried by a set of events it has nothing of yet: what + /// `start` gathers of its peers (`swarm::set`). + pub(crate) fn awaiting(mut self, start: super::store::passing::Start<Federation>) -> Self { + self.of_a_set = true; + self.inner.lock_or_recover().starting = Some(start); + self + } + + /// What the set took of the document since last asked, in the order taken. + pub(crate) fn unpassed(&self) -> Vec<Id> { + std::mem::take(&mut self.inner.lock_or_recover().unpassed) + } + + /// The names a node that started with nothing asks a peer for, to begin its set + /// from; none, once it holds one. + pub(crate) fn start_wants(&self) -> Vec<crate::document::ranges::Name> { + self.inner + .lock_or_recover() + .starting + .as_ref() + .map(|start| start.wants()) + .unwrap_or_default() + } + + /// Takes what a peer sent a node that started with nothing. Whether it holds its + /// set by it. + pub(crate) fn start_take(&self, units: Vec<super::store::passing::Unit>) -> bool { + let mut inner = self.inner.lock_or_recover(); + let Some(set) = inner.starting.as_mut().and_then(|start| start.take(units)) else { + return false; + }; + info!(store = %set.store().id(), "Begun the store's set from what peers gave by name"); + inner.starting = None; + inner.store = Some(Carried::Set(Box::new(set))); + self.settle(&mut inner); + true + } + + /// The store the node holds, or is to hold once it has gathered its set: by its ID. + pub(crate) fn store_id(&self) -> Option<Id> { + let inner = self.inner.lock_or_recover(); + inner + .store + .as_ref() + .map(|store| store.id()) + .or_else(|| inner.starting.as_ref().map(|start| start.store())) + } + + /// Itself, its store carried by the set `begun`, held or to be, and kept in the + /// file at `path`; itself, where the node is given no set and holds none. + pub(crate) fn carrying_if( + self, + begun: Option<Begun>, + path: Option<PathBuf>, + files: Arc<Files>, + ) -> Self { + let holding = match begun { + Some(Begun::Set(set)) => self.carrying(*set), + Some(Begun::Start(start)) => self.awaiting(start), + None => self, + }; + match path { + // A set held, to be gathered, or to be made of the store read from the + // document (`of_both`). + Some(path) if holding.of_a_set => holding.kept_in(path, files), + _ => holding, + } + } + + /// 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 { + self.kinds()[0] + } + + /// Whether a set of events carries the store, and nothing else does. + pub(crate) fn of_a_set(&self) -> bool { + self.of_a_set && !self.both + } + + /// Whether the node holds a set of events, alone or beside the Automerge document. + pub(crate) fn has_a_set(&self) -> bool { + self.of_a_set + } + + /// [`of_both`](Self::of_both), where `both`. + pub(crate) fn of_both_if(self, both: bool, keeps: Duration) -> Self { + if both { self.of_both(keeps) } else { self } + } + + /// Itself, holding its store in the Automerge document and in a set of events: the + /// set it is given (`carrying`), or, given none, one made of the store as it is + /// first read from the document, keeping what a checkpoint forgot for `keeps`. + pub(crate) fn of_both(mut self, keeps: Duration) -> Self { + self.both = true; + self.of_a_set = true; + self.keeps_forgotten = keeps; + self + } + + /// The kinds of document the node holds its store in, which it says in + /// handshakes: the one it says first, first. + pub(crate) fn kinds(&self) -> &'static [&'static str] { + match (self.of_a_set, self.both) { + (true, true) => &[crate::document::KIND, super::store::set::KIND], + (true, false) => &[super::store::set::KIND], + (false, _) => &[crate::document::KIND], + } + } + + /// What `f` makes of the set of events carrying the store, where one does. + pub(crate) fn with_set<T>(&self, f: impl FnOnce(&Set<Federation>) -> T) -> Option<T> { + match &self.inner.lock_or_recover().store { + Some(Carried::Set(set)) => Some(f(set)), + _ => None, + } + } + + /// What the node reads of its document at paths, where a set of events carries the + /// store: what a document holding a store has there. The members' entries, each at + /// `_continuum/members/<node ID>`, which a set keeps apart; the policy of a swarm + /// holding a store; and the swarm's ID, the store's. + pub(crate) fn entries(&self) -> Option<crate::document::view::Tree> { + use crate::document::view::{Tree, Write}; + self.with_set(|set| { + let mut tree = Tree::new(); + // Into a tree of maps alone: nothing is in the way of any of it. + let _ = tree.write_path( + &crate::access::policy::path(), + &events::policy(Federation::NAME), + ); + let _ = tree.write_path( + &meta::path(&[meta::SWARM]), + &serde_json::Value::String(set.store().id().to_string()), + ); + for entry in set.entries() { + if let Some(value) = entry.value() { + let path = [ + meta::ROOT.to_owned(), + meta::MEMBERS.to_owned(), + entry.node(), + ]; + let _ = tree.write_path(&path, &serde_json::Value::Object(value)); + } + } + tree + }) + } + + /// Has `f` change the set of events carrying the store, where one does, and + /// settles what the node keeps of its store by it: its members, as it reads now. + pub(crate) fn change_set<T>(&self, f: impl FnOnce(&mut Set<Federation>) -> T) -> Option<T> { + let mut inner = self.inner.lock_or_recover(); + let Some(Carried::Set(set)) = inner.store.as_mut() else { + return None; + }; + let out = f(set); + self.settle(&mut inner); + Some(out) } /// What a remake's snapshot holds of the store: as this node reads it anew from @@ -1111,6 +1402,16 @@ pub(crate) async fn run_worker(state: crate::state::AppState) { error!(error = %error, "Reading the store from the document failed"); (false, false, false, Vec::new(), Vec::new()) }); + // What the set took of the document goes on to the peers that hold sets, and + // the node's entry in the document is its entry in the set: a node of both + // kinds takes into each what the other holds. + if state.holding.has_a_set() && !state.of_a_set() { + let unpassed = state.holding.unpassed(); + if !unpassed.is_empty() { + crate::swarm::set::wrote(&state, unpassed).await; + } + crate::swarm::set::mirror_entry(&state).await; + } for bytes in signed { if let Err(error) = write(&state, None, bytes).await { warn!(error = %error, "Couldn't put what it signed for its party: put again later"); @@ -1194,7 +1495,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.holding.has_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"); + } + } + } } } } @@ -1228,6 +1540,18 @@ pub(crate) async fn write( bytes: Vec<u8>, ) -> Result<(), store::StoreError> { let id = Id::of(&bytes); + // Into a set of events it goes as the store takes it, where it didn't yet; and is + // passed on, as written. + if state.of_a_set() { + let holding = Arc::clone(&state.holding); + let _ = tokio::task::spawn_blocking(move || holding.offer(bytes)).await; + // What the set gives: taken, or held back by a store that stopped. + let held = state.holding.with_set(|set| set.get(&id).is_some()); + if held == Some(true) { + crate::swarm::set::wrote(state, vec![id]).await; + } + return Ok(()); + } state .mutate_doc_for( user, @@ -1245,7 +1569,14 @@ pub(crate) async fn write( }, ) .await - .map(|_| ()) + .map(|_| ())?; + // A node of both kinds: on to the peers that hold sets, too (`swarm::set`). + if state.holding.has_a_set() + && state.holding.with(|store| store.get(&id).is_some()) == Some(true) + { + crate::swarm::set::wrote(state, vec![id]).await; + } + Ok(()) } async fn put_again(state: &crate::state::AppState) { @@ -2686,4 +3017,103 @@ mod tests { LATER, ); } + + #[test] + fn a_store_carried_by_a_set_is_the_nodes_store() { + use crate::federation::store::passing; + + let (tv, lass) = (Party::new("tv", 1), Party::new("lass", 2)); + let first = Spec::first(&[&tv, &lass], &[]); + let root = first.root(); + let set = |root: &[u8]| { + Set::new( + Store::<Federation>::new(root.to_vec(), Vec::new()).expect("a root"), + Duration::from_secs(60), + ) + }; + let holding = Holding::default().carrying(set(&root)); + assert_eq!(holding.kind(), crate::federation::store::set::KIND); + assert_eq!(Holding::default().kind(), crate::document::KIND); + assert!(holding.tells_members()); + // Offered as to any store; and what another's set holds comes by passing on. + let write = tv.write(&[Id::of(&root)], "home/tv/a", harness::str("1")); + assert!(matches!( + holding.offer(write.clone()), + Some(Offered::Taken(_)) + )); + assert_eq!(holding.with(|store| store.taken().len()), Some(1)); + let other = Holding::default().carrying(set(&root)); + let stamp = holding.with_set(passing::stamp).expect("a set"); + let mut to_other = vec![passing::Message::Stamp(stamp)]; + let mut to_holding = Vec::new(); + for _ in 0..10 { + for message in std::mem::take(&mut to_other) { + let (replies, _) = other + .change_set(|set| passing::receive(set, message, Instant::now())) + .expect("a set"); + to_holding.extend(replies); + } + for message in std::mem::take(&mut to_holding) { + let (replies, _) = holding + .change_set(|set| passing::receive(set, message, Instant::now())) + .expect("a set"); + to_other.extend(replies); + } + } + assert_eq!( + other.with(|store| store.taken().to_vec()), + Some(vec![Id::of(&write)]) + ); + // A store read from a document has no set. + assert!(Holding::default().with_set(|_| ()).is_none()); + } + + #[test] + fn a_sets_entries_read_as_a_documents_members() { + use crate::federation::store::entry::Entry; + use crate::identity::NodeKey; + + let key = NodeKey::from_seed([7; 32]); + let tv = Party::new("tv", 1); + let first = Spec::first(&[&tv], &[]); + let root = first.root(); + let listed = tv.nodes(&[Id::of(&root)], &[key.id()]); + let mut set = Set::new( + Store::<Federation>::new(root.clone(), Vec::new()).expect("a root"), + Duration::from_secs(60), + ); + assert!(matches!( + set.offer(listed, Instant::now()), + Offered::Taken(_) + )); + let entry = Entry::new( + &Id::of(&root), + &key, + 1, + &serde_json::json!({"party": "tv", "addresses": ["a"], "alias": "seven"}), + ); + assert_eq!( + set.put_entry(entry), + crate::federation::store::set::Put::Taken + ); + let holding = Holding::default().carrying(set); + let tree = holding.entries().expect("a set"); + assert_eq!(crate::swarm::members::members(&tree), vec![key.id()]); + assert_eq!( + crate::swarm::members::party(&tree, &key.id()), + Some("tv".to_owned()) + ); + assert!(holding.member(&key.id(), Some("tv")) == Some(true)); + // And the rest a document holding a store has for the node to read: the + // policy, by which a node takes no token another issued, and the swarm's ID. + assert!(matches!( + crate::access::policy::of(&tree), + crate::access::policy::Policy::Store(_) + )); + assert_eq!( + crate::document::view::read_path(&tree, &meta::path(&[meta::SWARM])).unwrap(), + Some(serde_json::Value::String(Id::of(&root).to_string())) + ); + assert!(Holding::default().entries().is_none()); + } } diff --git a/src/federation/store/memory.rs b/src/federation/store/memory.rs index 8f099be..6f4ee5d 100644 --- a/src/federation/store/memory.rs +++ b/src/federation/store/memory.rs @@ -332,6 +332,14 @@ impl<F: Fold> Store<F> { .map(|(id, why)| (id, why.as_str(), self.held_back.len())) } + /// The events the store holds back, stopped, in the order offered: the one it stopped + /// at, and those offered since. None while it isn't stopped. + pub(crate) fn holds_back(&self) -> impl ExactSizeIterator<Item = (Id, &[u8])> { + self.held_back + .iter() + .map(|(id, event)| (*id, event.bytes.as_slice())) + } + /// What the store holds back, stopped (`Fold::stops`): the events offered since, and /// those waiting for events it doesn't hold, as it can't tell which will be taken; each /// after those of its dependencies among them, by ID otherwise. Nothing while it isn't diff --git a/src/federation/store/passing.rs b/src/federation/store/passing.rs index 5a6e2af..88e66a4 100644 --- a/src/federation/store/passing.rs +++ b/src/federation/store/passing.rs @@ -15,12 +15,15 @@ //! the store, or put as an entry; and for what the store then waits on and doesn't //! hold, the node asks in turn, back to what both hold. -use std::time::Instant; +use std::collections::BTreeMap; +use std::time::{Duration, Instant}; use serde::{Deserialize, Serialize}; use super::entry::Entry; +use super::Refused; +use super::memory::Store; use super::set::{Put, Set}; use super::{Fold, Id}; use crate::document::ranges::{self, Name}; @@ -45,6 +48,9 @@ pub(crate) struct Stamp { pub(crate) enum Unit { Event(#[serde(with = "serde_bytes")] Vec<u8>), Entry(#[serde(with = "serde_bytes")] Vec<u8>), + /// The checkpoint the sender's store holds, a root among them: for a node that + /// starts with nothing but its name (`Start`). + Checkpoint(#[serde(with = "serde_bytes")] Vec<u8>), } /// What one node says to another of its set. @@ -62,6 +68,100 @@ pub(crate) enum Message { Units(Vec<Unit>), } +/// A set to be: what a node that starts with nothing gathers of its peers, to begin +/// its store's set from (`docs/document.md`, A set of events, Passing on). It knows its +/// store by its ID, and where it starts by a name: the store's root, which is the +/// store's ID, or a checkpoint its operator pins. It asks for the checkpoint of that +/// name, then for the events that one keeps; each is what its name says, or not +/// taken. +pub(crate) struct Start<F: Fold> { + store: Id, + at: Id, + keeps_forgotten: Duration, + /// The checkpoint named `at`, once it came, and the events it keeps, by name. + checkpoint: Option<(Vec<u8>, Vec<Id>)>, + kept: BTreeMap<Id, Vec<u8>>, + fold: std::marker::PhantomData<F>, +} + +impl<F: Fold> Start<F> { + /// A set of the store `store` to be, starting at the checkpoint named `at`. + pub(crate) fn new(store: Id, at: Id, keeps_forgotten: Duration) -> Self { + Self { + store, + at, + keeps_forgotten, + checkpoint: None, + kept: BTreeMap::new(), + fold: std::marker::PhantomData, + } + } + + /// The store it is to hold. + pub(crate) fn store(&self) -> Id { + self.store + } + + /// The names it asks a peer for now. + pub(crate) fn wants(&self) -> Vec<Name> { + match &self.checkpoint { + None => vec![self.at.0], + Some((_, keeps)) => keeps + .iter() + .filter(|id| !self.kept.contains_key(id)) + .map(|id| id.0) + .take(NAMES) + .collect(), + } + } + + /// Takes what a peer sent of what it asked for. The set, once it has all it + /// begins from; a checkpoint that is none of the fold's, or that the store doesn't + /// begin from, is let go of, to be asked for again. + pub(crate) fn take(&mut self, units: Vec<Unit>) -> Option<Set<F>> { + for unit in units { + match unit { + Unit::Checkpoint(bytes) + if self.checkpoint.is_none() && Id::of(&bytes) == self.at => + { + if let Some((_, keeps)) = F::parts(&bytes) { + self.checkpoint = Some((bytes, keeps)); + } + } + Unit::Event(bytes) if bytes.len() <= F::LARGEST => { + let id = Id::of(&bytes); + let kept = self + .checkpoint + .as_ref() + .is_some_and(|(_, keeps)| keeps.contains(&id)); + if kept { + self.kept.insert(id, bytes); + } + } + _ => {} + } + } + let (checkpoint, keeps) = self.checkpoint.as_ref()?; + if keeps.iter().any(|id| !self.kept.contains_key(id)) { + return None; + } + let kept: Vec<Vec<u8>> = self.kept.values().cloned().collect(); + let store: Result<Store<F>, Refused> = if self.at == self.store { + Store::new(checkpoint.clone(), kept) + } else { + Store::pinned(self.store, checkpoint.clone(), kept) + }; + match store { + Ok(store) => Some(Set::new(store, self.keeps_forgotten)), + Err(_) => { + self.checkpoint = None; + self.kept.clear(); + None + } + } + } +} + /// What a node took of a message. #[derive(Debug, Default, PartialEq, Eq)] pub(crate) struct Took { @@ -85,8 +185,13 @@ pub(crate) fn stamp<F: Fold>(set: &Set<F>) -> Stamp { } } -/// The unit named `name`, where `set` holds it. +/// The unit named `name`, where `set` holds it: an event, an entry, or the checkpoint +/// its store holds. pub(crate) fn unit<F: Fold>(set: &Set<F>, name: &Name) -> Option<Unit> { + let checkpoint = set.store().checkpoint(); + if Id::of(checkpoint).0 == *name { + return Some(Unit::Checkpoint(checkpoint.to_vec())); + } set.get(&Id(*name)) .map(|bytes| Unit::Event(bytes.to_vec())) .or_else(|| { @@ -130,7 +235,9 @@ pub(crate) fn receive<F: Fold>( continue; }; let size = match &unit { - Unit::Event(bytes) | Unit::Entry(bytes) => bytes.len(), + Unit::Event(bytes) | Unit::Entry(bytes) | Unit::Checkpoint(bytes) => { + bytes.len() + } }; // What doesn't fit, the peer asks for again. if bytes + size > BYTES && !units.is_empty() { @@ -152,6 +259,8 @@ pub(crate) fn receive<F: Fold>( match unit { Unit::Event(bytes) => events.push(bytes), Unit::Entry(bytes) => entries.push(bytes), + // A node holding a set built its checkpoint itself. + Unit::Checkpoint(_) => {} } } took.events = set.offer_all(events, now); @@ -375,7 +484,7 @@ mod tests { let sizes: Vec<usize> = units .iter() .map(|unit| match unit { - Unit::Event(bytes) | Unit::Entry(bytes) => bytes.len(), + Unit::Event(bytes) | Unit::Entry(bytes) | Unit::Checkpoint(bytes) => bytes.len(), }) .collect(); assert!(sizes.iter().sum::<usize>() <= BYTES); @@ -430,4 +539,66 @@ mod tests { ); } } + + #[test] + fn a_node_with_nothing_begins_its_set_from_what_peers_give_by_name() { + // A store that moved to a checkpoint, which keeps an event. + let mut ahead = set(); + let now = Instant::now(); + let root = ahead.store().id(); + let first = testfold::put(&[root], "a", "1"); + let first_id = Id::of(&first); + let second = testfold::put(&[first_id], "a", "2"); + let second_id = Id::of(&second); + let lock = testfold::lock(&[second_id], "b"); + let lock_id = Id::of(&lock); + let cut = testfold::cut(&[lock_id], 1, &[lock_id]); + for event in [first, second, lock, cut.clone()] { + assert!(matches!(ahead.offer(event, now), Offered::Taken(_))); + } + let pinned = Id::of(ahead.store().checkpoint()); + assert_ne!(pinned, root); + + // From the root: the checkpoint named by the store's ID, were it still held. + let mut from_root = Start::<TestFold>::new(root, root, KEEPS); + assert_eq!(from_root.wants(), vec![root.0]); + assert_eq!(unit(&ahead, &root.0), None); + let fresh = set(); + let Some(Unit::Checkpoint(bytes)) = unit(&fresh, &root.0) else { + panic!("no root"); + }; + let begun = from_root + .take(vec![Unit::Checkpoint(bytes)]) + .expect("a set, the root keeping nothing"); + assert_eq!(begun.store().id(), root); + + // From a checkpoint its operator pins: that, then what it keeps. + let mut start = Start::<TestFold>::new(root, pinned, KEEPS); + assert_eq!(start.wants(), vec![pinned.0]); + // What isn't what its name says isn't taken. + assert!( + start + .take(vec![Unit::Checkpoint(b"another".to_vec())]) + .is_none() + ); + assert_eq!(start.wants(), vec![pinned.0]); + let checkpoint = unit(&ahead, &pinned.0).expect("its checkpoint"); + assert!(matches!(checkpoint, Unit::Checkpoint(_))); + assert!(start.take(vec![checkpoint]).is_none()); + let wanted = start.wants(); + assert!(!wanted.is_empty() && !wanted.contains(&pinned.0)); + let kept: Vec<Unit> = wanted + .iter() + .map(|name| unit(&ahead, name).expect("kept")) + .collect(); + let begun = start.take(kept).expect("a set"); + assert_eq!(begun.store().id(), root); + assert_eq!(begun.store().checkpoint(), ahead.store().checkpoint()); + // And it goes on as any set: what the other holds after the checkpoint comes. + let mut sets = [ahead, begun]; + let mut rng = Rng::new(9); + settle(&mut sets, &mut rng, now); + assert!(sets[1].store().get(&Id::of(&cut)).is_some()); + assert_eq!(sets[1].store().taken(), sets[0].store().taken()); + } } diff --git a/src/federation/store/set.rs b/src/federation/store/set.rs index b033927..d0dbe18 100644 --- a/src/federation/store/set.rs +++ b/src/federation/store/set.rs @@ -9,6 +9,8 @@ //! oldest going first: whoever mints events can mint these; //! * what a move to a checkpoint forgot, for as long as the node's operator says: a node //! still before the checkpoint builds it from them. +//! * what the store holds back, stopped at an event it can't judge (`Fold::stops`): the +//! node can't tell which of it will be taken, and a node that judges it takes it. //! //! And each member's entry (`entry`): its node's newest, and none of a node the store //! doesn't name a member as it reads now. @@ -123,6 +125,9 @@ pub(crate) struct Set<F: Fold> { /// The unjudged among them, the oldest first, and their bytes in all. unjudged: VecDeque<Id>, unjudged_bytes: usize, + /// What the store holds back, stopped, by ID: where among what it holds back + /// (`Store::holds_back`). + held_back: BTreeMap<Id, usize>, /// For how long what a checkpoint forgot is kept. keeps_forgotten: Duration, /// Who carries the store, as it reads now (`Fold::members`). @@ -157,6 +162,7 @@ impl<F: Fold> Set<F> { beside: BTreeMap::new(), unjudged: VecDeque::new(), unjudged_bytes: 0, + held_back: BTreeMap::new(), keeps_forgotten, members, entries: BTreeMap::new(), @@ -245,12 +251,13 @@ impl<F: Fold> Set<F> { /// document keeps as far as it gives it to others. pub(crate) fn offer(&mut self, bytes: Vec<u8>, now: Instant) -> Offered { let offered = self.store.offer(bytes); - self.settle(now); + let _ = self.settle(now); offered } /// Offers events to the store, at `now`, as `offer` does each: those the store took - /// by them, in the order taken. + /// by them, in the order taken, and those it holds back since, stopped: what the + /// document gives to others by them. pub(crate) fn offer_all( &mut self, events: impl IntoIterator<Item = Vec<u8>>, @@ -262,7 +269,7 @@ impl<F: Fold> Set<F> { taken.extend(ids); } } - self.settle(now); + taken.extend(self.settle(now)); taken } @@ -289,7 +296,7 @@ impl<F: Fold> Set<F> { /// holds them on, for others. pub(crate) fn drop_taken(&mut self, ids: &[Id], now: Instant) -> Result<Vec<Id>, Refused> { let dropped = self.store.drop_taken(ids); - self.settle(now); + let _ = self.settle(now); dropped } @@ -317,11 +324,12 @@ impl<F: Fold> Set<F> { self.store.offer(bytes); } } - self.settle(now); + let _ = self.settle(now); } - /// Takes in what the store let go of. - fn settle(&mut self, now: Instant) { + /// Takes in what the store let go of, and what it holds back, stopped: the events it + /// holds back since last asked, in the order offered. + fn settle(&mut self, now: Instant) -> Vec<Id> { let took = self.store.took(); let gone = self.store.let_go(); // Who is a member is the fold's to say of the store's state, and costs what @@ -376,8 +384,42 @@ impl<F: Fold> Set<F> { } !held }); + let held_back = self.hold_back(); #[cfg(test)] self.check(); + held_back + } + + /// Follows what the store holds back, stopped: its names among those the document + /// gives, and those held back since last asked, in the order offered. + fn hold_back(&mut self) -> Vec<Id> { + let holds = self.store.holds_back().len(); + // The store holds back more, after what it held back: the common case. + let more = holds >= self.held_back.len() + && self.held_back.len().checked_sub(1).is_none_or(|last| { + self.store + .holds_back() + .nth(last) + .is_some_and(|(id, _)| self.held_back.get(&id) == Some(&last)) + }); + let from = if more { self.held_back.len() } else { 0 }; + if !more { + // It takes again, and may have stopped anew: what it held back, it took, + // refused, or holds back again. + for id in std::mem::take(&mut self.held_back).into_keys() { + if self.store.get(&id).is_none() && !self.beside.contains_key(&id) { + self.names.remove(&id.0); + } + } + } + let mut since = Vec::new(); + for (at, (id, _)) in self.store.holds_back().enumerate().skip(from) { + self.held_back.insert(id, at); + if self.names.insert(id.0) { + since.push(id); + } + } + since } /// Whether the store refuses `id` as the node's own, or for building on such: what @@ -423,12 +465,16 @@ impl<F: Fold> Set<F> { self.beside.len() != before } - /// The bytes of an event the document gives to others: one its store holds, or one - /// held beside it. + /// The bytes of an event the document gives to others: one its store holds, one + /// held beside it, or one the store holds back. pub(crate) fn get(&self, id: &Id) -> Option<&[u8]> { self.store .get(id) .or_else(|| self.beside.get(id).map(|(bytes, _)| bytes.as_slice())) + .or_else(|| { + let at = *self.held_back.get(id)?; + self.store.holds_back().nth(at).map(|(_, bytes)| bytes) + }) } /// Why the document holds `id` beside its store, where it does. @@ -436,7 +482,8 @@ impl<F: Fold> Set<F> { self.beside.get(id).map(|(_, why)| *why) } - /// The document as bytes, at `now`: what its file holds. All it holds but what waits + /// The document as bytes, at `now`: what its file holds, what its store holds back + /// among it. All it holds but what waits /// for what it builds on, which comes again; and what its node refuses of its own, /// which a store read anew is told before anything is offered to it. pub(crate) fn save(&self, now: Instant) -> Vec<u8> { @@ -451,6 +498,12 @@ impl<F: Fold> Set<F> { .iter() .filter_map(|id| self.store.get(id)) .map(|bytes| bytes.to_vec().into()) + // What the store holds back, after: offered again, it stops there again. + .chain( + self.store + .holds_back() + .map(|(_, bytes)| bytes.to_vec().into()), + ) .collect(), own: own.iter().map(|id| id.0).collect(), dropped: dropped.iter().map(|id| id.0).collect(), @@ -521,7 +574,7 @@ impl<F: Fold> Set<F> { for event in saved.taken { set.store.offer(event.into_vec()); } - set.settle(now); + let _ = set.settle(now); for (bytes, why) in saved.beside { let bytes = bytes.into_vec(); let id = Id::of(&bytes); @@ -543,7 +596,7 @@ impl<F: Fold> Set<F> { set.names.insert(id.0); set.beside.insert(id, (bytes, why)); } - set.settle(now); + let _ = set.settle(now); set.expire(now); for entry in saved.entries { if let Some(entry) = Entry::decode(&entry) { @@ -595,6 +648,7 @@ impl<F: Fold> Set<F> { .map(|id| id.0) .chain(self.store.kept().iter().map(|bytes| Id::of(bytes).0)) .chain(self.beside.keys().map(|id| id.0)) + .chain(self.held_back.keys().map(|id| id.0)) .chain(self.entries.values().map(Entry::name)) .collect() } @@ -998,4 +1052,48 @@ mod tests { assert!(!set.wants(&waiting[WAITS + 4].0)); assert_eq!(set.store().lacks().len(), WAITS); } + + /// What a store that stopped holds back, the document gives to others, as the node + /// can't tell which of it will be taken; its file keeps it; and once the store takes + /// again, the document gives what the store took of it and no more. + #[test] + fn what_a_stopped_store_holds_back_is_given_to_others() { + let mut set = set(); + let now = Instant::now(); + let root = set.store().id(); + let mark = taken(set.offer(testfold::put(&[root], "mark", "1"), now)); + let new = testfold::era(&[mark], 1, "new"); + let at = Id::of(&new); + let later = testfold::put(&[mark], "b", "1"); + let junk = testfold::junk(&[mark]); + let (later_id, junk_id) = (Id::of(&later), Id::of(&junk)); + // Held back, and given: by name, to catch up by, and as what was taken by them. + assert_eq!( + set.offer_all([new.clone(), later.clone(), junk.clone()], now), + vec![at, later_id, junk_id] + ); + assert!(set.store().stopped().is_some()); + for (id, bytes) in [(at, &new), (later_id, &later), (junk_id, &junk)] { + assert_eq!(set.get(&id), Some(bytes.as_slice())); + assert!(set.names().contains(&id.0)); + assert!(!set.wants(&id.0)); + } + // Offered again, nothing is given anew. + assert!(set.offer_all([later.clone()], now).is_empty()); + // Its file keeps what it holds back: read, the store stops there again. + let mut read = Set::<TestFold>::load(&set.save(now), KEEPS, now).expect("it reads"); + assert_eq!(read.store().stopped().map(|(id, _, _)| *id), Some(at)); + assert_eq!(read.named(), set.named()); + assert_eq!(read.get(&later_id), Some(later.as_slice())); + // Its operator has it drop the event it stopped at: what it held back is taken, + // or refused, and what is refused at its history is given no more. + read.drop_taken(&[at], now).expect("dropped"); + assert!(read.store().stopped().is_none()); + assert_eq!(read.store().taken(), &[mark, later_id]); + assert_eq!(read.get(&junk_id), None); + assert!(!read.names().contains(&junk_id.0)); + // What it dropped is the node's own, which others may take. + assert_eq!(read.beside(&at), Some(Beside::Own)); + assert!(read.names().contains(&at.0)); + } } @@ -81,16 +81,16 @@ fn voter(args: &config::Settings) -> Result<Option<federation::held::Voter>> { pub async fn run() -> Result<()> { logging::init(); - let config = config::load()?; - if let Some((file, create)) = &config.node_id { + if let Some((file, create)) = config::asked_node_id() { let new = !file.exists(); - let key = identity::NodeKey::load(file, *create)?; + let key = identity::NodeKey::load(&file, create)?; if new { eprintln!("a new node key in {}: a new node", file.display()); } println!("{}", key.id()); return Ok(()); } + let config = config::load()?; if config.print_only { println!( "{}", @@ -221,11 +221,37 @@ 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)) => store.set( + path, + &files, + args.store_checkpoint + .as_deref() + .and_then(federation::store::Id::from_hex), + args.store_keeps_forgotten, + args.store_both, + )?, + _ => None, + }; #[cfg(feature = "federation")] let starting = match &store { - Some(store) => { + Some(store) if set.is_none() || args.store_both => { 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 +398,9 @@ pub async fn run() -> Result<()> { args.store_party.clone(), )? .near(args.store_neighbour_parties.clone()) - .voting(voter(args)?), + .voting(voter(args)?) + .of_both_if(args.store_both, args.store_keeps_forgotten) + .carrying_if(set, args.store_document.clone(), Arc::clone(&files)), strict_keys: args .strict_keys .iter() @@ -394,7 +422,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 +520,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/remake/api.rs b/src/remake/api.rs index 9ccd582..7590c2e 100644 --- a/src/remake/api.rs +++ b/src/remake/api.rs @@ -386,6 +386,16 @@ async fn start_kind<H: Host>( None, ); }; + // A set of events has nothing to remake (`docs/document.md`, A set of events): no + // changes, writers or epochs, and it is bounded by the store's checkpoints. + #[cfg(feature = "federation")] + if host.holding().of_a_set() { + return error_response( + StatusCode::BAD_REQUEST, + "this node's document is a set of events: there is nothing to remake".to_owned(), + None, + ); + } // A swarm holding a store takes compactions only (`docs/store.md`, Remakes): every // node builds a compaction's snapshot itself from the base. #[cfg(feature = "federation")] diff --git a/src/simtest/holding.rs b/src/simtest/holding.rs index 16158b1..8f601dd 100644 --- a/src/simtest/holding.rs +++ b/src/simtest/holding.rs @@ -1726,3 +1726,681 @@ async fn store_attack_31() { ) .await; } + +/// A store carried by a set of events on `root`, for a node of `party`. +fn of_a_set(party: &str, root: &[u8]) -> Holding { + use crate::federation::store::set::Set; + holding(party).carrying(Set::new( + Store::<Federation>::new(root.to_vec(), Vec::new()).expect("a root"), + Duration::from_secs(600), + )) +} + +/// How many members' entries `node`'s set holds. +fn entries(node: &AppState) -> usize { + node.holding + .with_set(|set| set.entries().count()) + .unwrap_or(0) +} + +/// Where `node`'s set stands. +fn stands(node: &AppState) -> Option<crate::federation::store::passing::Stamp> { + node.holding + .with_set(crate::federation::store::passing::stamp) +} + +/// tv lists a and b, lass lists c: each node's store is carried by a set of events, +/// its own document, and nothing is in the Automerge document it holds. Each registers, +/// and its entry reaches the others; events put on a and on c reach all three; and they +/// come to stand alike. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_swarm_of_sets_passes_entries_and_events_on() { + let sim = Sim::with_identity(91); + let (tv, lass, _) = three(); + let (_, root, id) = federation(&[(&tv, &["a", "b"]), (&lass, &["c"])]); + let nodes: Vec<AppState> = [("a", "tv"), ("b", "tv"), ("c", "lass")] + .into_iter() + .map(|(name, party)| { + let seeds: Vec<&str> = if name == "a" { Vec::new() } else { vec!["a"] }; + let root = root.clone(); + sim.start_with( + name, + &seeds, + Start::FromDocument(Origin::Root), + move |config| { + config.store = Some(id); + config.holding = of_a_set(party, &root); + }, + ) + }) + .collect(); + let members: Vec<&AppState> = nodes.iter().collect(); + let members = &members; + sim.wait_ready(members, SOON).await; + for node in members.iter() { + assert_eq!(node.kinds(), [crate::federation::store::set::KIND]); + assert!(node.holding.tells_members()); + } + sim.wait_until("each holds the three entries", SOON, move || async move { + members.iter().all(|node| entries(node) == 3) + }) + .await; + + let on_a = tv.write(&[id], "home/tv/x", s("1")); + let on_c = lass.write(&[id], "home/lass/y", s("2")); + let ids = [Id::of(&on_a), Id::of(&on_c)]; + put(members[0], &[&on_a]).await; + put(members[2], &[&on_c]).await; + sim.wait_until("a, b and c hold both events", SOON, move || async move { + members.iter().all(|node| holds(node, &ids)) + }) + .await; + sim.wait_until("they stand alike", SOON, move || async move { + let first = stands(members[0]); + first.is_some() && members.iter().all(|node| stands(node) == first) + }) + .await; + for node in members.iter() { + assert_eq!(read(node, |store| store.state().values().len()), Some(2)); + // Nothing went into the document it holds beside. + assert!(node.doc.read().await.heads().is_empty()); + } +} + +/// On sets of events, a version of a federation this continuum doesn't know passes, and +/// a version event writes it: every node stops there. What is put through one of them +/// meanwhile, it holds back and passes on, as it can't tell what will be taken: the +/// others hold it back too. Their operators have them drop that event: they take again, +/// all alike. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_stopped_node_of_a_set_passes_on_what_it_holds_back() { + let sim = Sim::with_identity(99); + let (tv, lass, makefu) = three(); + let (first, root, id) = federation(&[(&tv, &["a"]), (&lass, &["b"]), (&makefu, &["c"])]); + let nodes: Vec<AppState> = [("a", "tv"), ("b", "lass"), ("c", "makefu")] + .into_iter() + .map(|(name, party)| { + let seeds: Vec<&str> = if name == "a" { Vec::new() } else { vec!["a"] }; + let root = root.clone(); + sim.start_with( + name, + &seeds, + Start::FromDocument(Origin::Root), + move |config| { + config.store = Some(id); + config.holding = of_a_set(party, &root); + }, + ) + }) + .collect(); + let members: Vec<&AppState> = nodes.iter().collect(); + let all = &members; + sim.wait_ready(all, SOON).await; + sim.wait_until("each holds the three entries", SOON, move || async move { + all.iter().all(|node| entries(node) == 3) + }) + .await; + + let on = first.hash(); + let text = String::from_utf8(first.after(on).json().bytes()) + .expect("UTF-8") + .replace(r#""federation":1"#, r#""federation":2"#); + let unknown = crate::federation::jcs::read(text.as_bytes()).expect("JCS"); + let hash = Id::of(&unknown.bytes()); + let proposal = tv.propose(&[id], &unknown); + let votes = [&tv, &lass].map(|party| party.vote(&[Id::of(&proposal)], on, hash, true)); + let written = harness::version_event(&[Id::of(&votes[0]), Id::of(&votes[1])], hash); + let at = Id::of(&written); + put(all[0], &[&proposal, &votes[0], &votes[1], &written]).await; + sim.wait_until("every node stopped there", LONG, move || async move { + all.iter().all(|node| stopped(node) == Some(at)) + }) + .await; + + let meanwhile = tv.write(&[id], "home/tv/a", s("1")); + put(all[0], &[&meanwhile]).await; + let meanwhile = Id::of(&meanwhile); + sim.wait_until("every node holds it back", LONG, move || async move { + all.iter() + .all(|node| holds_back(node, &[at, meanwhile], false)) + }) + .await; + + for node in all.iter() { + let dropped = node.holding.drop_taken(&[at]).expect("a store"); + assert_eq!(dropped, Ok(vec![at])); + } + sim.wait_until("every node takes again", LONG, move || async move { + all.iter() + .all(|node| stopped(node).is_none() && holds(node, &[meanwhile])) + }) + .await; + let read: Vec<Option<Counts>> = all.iter().map(|node| counts(node)).collect(); + assert!(read.iter().all(|counts| counts == &read[0]), "{read:?}"); +} + +/// 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(held::Begun::Set(Box::new(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; +} + +/// a and b hold the store and a write; c is given the store's ID alone, and nothing of +/// the store: it asks the members it reaches for the root by its name, begins its set +/// from it, and catches up as any node behind. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_node_of_a_set_joins_with_nothing_but_the_stores_id() { + use crate::federation::store::passing; + + let sim = Sim::with_identity(94); + 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; + let write = tv.write(&[id], "home/tv/x", s("1")); + let ids = [Id::of(&write)]; + put(&a, &[&write]).await; + + let c = sim.start_with( + "c", + &["a"], + Start::FromDocument(Origin::Root), + move |config| { + config.store = Some(id); + config.holding = holding("lass").carrying_if( + Some(held::Begun::Start(passing::Start::new( + id, + id, + Duration::from_secs(600), + ))), + None, + Arc::new(Files::default()), + ); + }, + ); + assert_eq!(c.kinds(), [crate::federation::store::set::KIND]); + assert!(read(&c, |_| ()).is_none()); + sim.wait_ready(&[&c], SOON).await; + let (all, ids) = (&[&a, &b, &c], &ids); + sim.wait_until( + "c holds the store, the write and the entries", + SOON, + move || async move { holds(all[2], ids) && all.iter().all(|node| entries(node) == 3) }, + ) + .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) + }) + .await; +} + +/// d is of lass, which doesn't list it: given the store's ID, it reaches a, which takes +/// none of its handshakes and gives it nothing, neither the root nor an event. It never +/// holds the store. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_node_no_party_lists_gets_nothing_of_a_set() { + use crate::federation::store::passing; + + let sim = Sim::with_identity(95); + 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; + let write = tv.write(&[id], "home/tv/x", s("1")); + put(&a, &[&write]).await; + let pair = &[&a, &b]; + sim.wait_until( + "a and b hold each other's entries", + SOON, + move || async move { pair.iter().all(|node| entries(node) == 2) }, + ) + .await; + + let d = sim.start_with( + "d", + &["a"], + Start::FromDocument(Origin::Root), + move |config| { + config.store = Some(id); + config.holding = holding("lass").carrying_if( + Some(held::Begun::Start(passing::Start::new( + id, + id, + Duration::from_secs(600), + ))), + None, + Arc::new(Files::default()), + ); + }, + ); + // Long enough for it to have joined, were it let in. + tokio::time::sleep(Duration::from_secs(4)).await; + assert!(!d.is_ready().await); + assert!(read(&d, |_| ()).is_none()); + assert!(!d.holding.start_wants().is_empty()); + // And a holds no entry of it. + assert_eq!(entries(&a), 2); +} + +/// A node away while the others moved to a checkpoint: a and b forgot what came before +/// it, and keep it a while beside their stores; c, back, gets that of them, builds the +/// checkpoint itself, and reads what they read, what came after it too. d, with nothing +/// and the checkpoint pinned, begins from it by its name. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_node_of_a_set_away_across_a_move_builds_the_checkpoint_itself() { + use crate::federation::store::passing; + + let sim = Sim::with_identity(96); + let parties = three(); + let (tv, lass, makefu) = &parties; + let (first, root, id) = federation(&[(tv, &["a"]), (lass, &["b"]), (makefu, &["c", "d"])]); + let a = start_on_a_set(&sim, "a", "tv", id, a_set(&root), None, false); + let b = start_on_a_set(&sim, "b", "lass", id, a_set(&root), None, false); + let c = start_on_a_set(&sim, "c", "makefu", id, a_set(&root), None, false); + let all = &[&a, &b, &c]; + sim.wait_ready(all, SOON).await; + sim.wait_until("each holds the three entries", SOON, move || async move { + all.iter().all(|node| entries(node) == 3) + }) + .await; + + sim.net.take_down("c"); + let gone = tv.write(&[id], "home/tv/a", s("0")); + let head = tv.write(&[Id::of(&gone)], "home/tv/a", s("1")); + let (next, [proposal, tv_yes, lass_yes]) = checkpoint_at(&parties, &first, &[Id::of(&head)]); + put(&a, &[&gone, &head, &proposal, &tv_yes]).await; + put(&b, &[&lass_yes]).await; + let passed = next.hash(); + sim.wait_until( + "a and b moved to the checkpoint", + LONG, + move || async move { + all[..2] + .iter() + .all(|node| current(node) == Some(passed) && checkpoint(node) != Some(id)) + }, + ) + .await; + let after = tv.write(&[Id::of(&head)], "home/tv/b", s("2")); + put(&a, &[&after]).await; + let moved = checkpoint(&a).expect("a store"); + assert_eq!(checkpoint(&b), Some(moved)); + let gone = Id::of(&gone); + // The store forgot it; the set keeps it a while, for whoever is still before. + assert_eq!(read(&a, |store| store.get(&gone).is_some()), Some(false)); + assert_eq!( + a.holding.with_set(|set| set.get(&gone).is_some()), + Some(true) + ); + + sim.net.bring_up("c"); + let after = Id::of(&after); + sim.wait_until( + "c moved there, and holds what came after", + LONG, + move || async move { + checkpoint(all[2]) == Some(moved) && holds(all[2], &[after]) && holds(all[1], &[after]) + }, + ) + .await; + assert_eq!(counts(&c), counts(&a)); + + let d = sim.start_with( + "d", + &["a"], + Start::FromDocument(Origin::Root), + move |config| { + config.store = Some(id); + config.holding = holding("makefu").carrying_if( + Some(held::Begun::Start(passing::Start::new( + id, + moved, + Duration::from_secs(600), + ))), + None, + Arc::new(Files::default()), + ); + }, + ); + sim.wait_ready(&[&d], SOON).await; + let d = &d; + sim.wait_until( + "d began from the pinned checkpoint, and caught up", + LONG, + move || async move { checkpoint(d) == Some(moved) && holds(d, &[after]) }, + ) + .await; + assert_eq!(counts(d), counts(&a)); +} + +/// A swarm on its way from Automerge documents to sets of events: a and b hold the +/// store in the Automerge document, e in a set, and m in both. a and e take none of +/// each other's handshakes; m takes both, saying to each the kind it holds. An event +/// put on a reaches e through m, and one put on e reaches a and b: m takes into each +/// what the other holds. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_node_of_both_kinds_carries_events_between_them() { + let sim = Sim::with_identity(97); + let (tv, lass, makefu) = three(); + let (_, root, id) = federation(&[(&tv, &["a", "b"]), (&lass, &["m"]), (&makefu, &["e"])]); + let start = |name: &'static str, seeds: &'static [&'static str], holding: Holding| { + let root = root.clone(); + sim.start_with( + name, + seeds, + Start::FromDocument(Origin::Root), + move |config| { + of_the_store(config, id, Some(&root), holding); + }, + ) + }; + let a = start("a", &[], holding("tv")); + let b = start("b", &["a"], holding("tv")); + let m = start( + "m", + &["a"], + holding("lass").of_both(Duration::from_secs(600)), + ); + assert_eq!(m.kinds().len(), 2); + let e = { + let seeds = ["m"]; + let root = root.clone(); + sim.start_with( + "e", + &seeds, + Start::FromDocument(Origin::Root), + move |config| { + config.store = Some(id); + config.holding = holding("makefu").carrying_if( + Some(held::Begun::Set(Box::new(a_set(&root)))), + None, + Arc::new(Files::default()), + ); + }, + ) + }; + let all = &[&a, &b, &m, &e]; + sim.wait_ready(all, SOON).await; + sim.wait_until( + "m holds a set, and its entry and e's in it", + LONG, + move || async move { entries(all[2]) == 2 && entries(all[3]) == 2 }, + ) + .await; + + let on_a = tv.write(&[id], "home/tv/x", s("1")); + let on_e = makefu.write(&[id], "home/makefu/y", s("2")); + let ids = [Id::of(&on_a), Id::of(&on_e)]; + put(&a, &[&on_a]).await; + put(&e, &[&on_e]).await; + let ids = &ids; + sim.wait_until("all four hold both events", LONG, move || async move { + all.iter().all(|node| holds(node, ids)) + }) + .await; + for node in all.iter() { + assert_eq!(read(node, |store| store.state().values().len()), Some(2)); + } + // e's event is in the Automerge document, which m put it in; a's isn't in e's, which + // holds nothing. + assert!(events::ids(&a.doc.read().await.doc).contains(&ids[1])); + assert!(e.doc.read().await.heads().is_empty()); +} + +/// A swarm moves from Automerge documents to sets of events, node by node, as its +/// operators are told to: a and b on the document; then each of both kinds, started +/// again on its document with a file for its set; then each on its set alone, started +/// again from that file. What was put before is held throughout, and what is put at +/// each step reaches the other node. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_swarm_moves_to_sets_node_by_node() { + use crate::federation::store::set::Set; + + let sim = Sim::with_identity(98); + let (tv, lass, _) = three(); + let (_, root, id) = federation(&[(&tv, &["a"]), (&lass, &["b"])]); + let dir = crate::files::scratch_dir("move-to-sets"); + let keeps = Duration::from_secs(600); + let nodes = started( + &sim, + &root, + vec![("a", holding("tv")), ("b", holding("lass"))], + ) + .await; + let (mut a, mut b) = (nodes[0].clone(), nodes[1].clone()); + let x = tv.write(&[id], "home/tv/x", s("1")); + put(&a, &[&x]).await; + let mut ids = vec![Id::of(&x)]; + { + let (pair, ids) = (&[&a, &b], &ids); + sim.wait_until("both hold x", LONG, move || async move { + pair.iter().all(|node| holds(node, ids)) + }) + .await; + } + + // Each of both kinds, on the document it has. + for (name, party, seeds) in [("a", "tv", [""; 0].as_slice()), ("b", "lass", &["a"])] { + let node = if name == "a" { &a } else { &b }; + let doc = node.doc.read().await.doc.clone(); + let path = dir.join(format!("{name}.events")); + let party = party.to_owned(); + let again = sim.restart_with( + name, + seeds, + Start::FromDocument(Origin::Root), + move |config| { + config.store = Some(id); + config.initial_doc = doc; + config.holding = holding(&party).of_both(keeps).carrying_if( + None, + Some(path), + Arc::new(Files::default()), + ); + }, + ); + sim.wait_ready(&[&again], SOON).await; + { + let (again, ids) = (&again, &ids); + sim.wait_until("it made its set, holding what it held", LONG, move || async move { + again.holding.with_set(|_| ()).is_some() && holds(again, ids) + }) + .await; + } + if name == "a" { + a = again; + } else { + b = again; + } + } + let y = lass.write(&[ids[0]], "home/lass/y", s("2")); + put(&b, &[&y]).await; + ids.push(Id::of(&y)); + { + let (pair, ids) = (&[&a, &b], &ids); + sim.wait_until( + "both hold y, and each other's entry in their sets", + LONG, + move || async move { + pair.iter() + .all(|node| holds(node, ids) && entries(node) == 2) + }, + ) + .await; + } + + // Each on its set alone, from the set's file. + for (name, party, seeds) in [("a", "tv", [""; 0].as_slice()), ("b", "lass", &["a"])] { + let node = if name == "a" { &a } else { &b }; + node.holding.save().expect("the set written"); + let path = dir.join(format!("{name}.events")); + let bytes = std::fs::read(&path).expect("the set's file"); + let set = Set::<Federation>::load(&bytes, keeps, std::time::Instant::now()).expect("a set"); + let party = party.to_owned(); + let again = sim.restart_with( + name, + seeds, + Start::FromDocument(Origin::Root), + move |config| { + config.store = Some(id); + config.holding = holding(&party).carrying_if( + Some(held::Begun::Set(Box::new(set))), + Some(path), + Arc::new(Files::default()), + ); + }, + ); + assert_eq!(again.kinds(), [crate::federation::store::set::KIND]); + assert!(holds(&again, &ids), "what the file held"); + sim.wait_ready(&[&again], SOON).await; + let z = tv.write( + &[*ids.last().expect("some")], + &format!("home/tv/{name}"), + s("3"), + ); + put(&again, &[&z]).await; + ids.push(Id::of(&z)); + if name == "a" { + a = again; + } else { + b = again; + } + let (pair, ids) = (&[&a, &b], &ids); + sim.wait_until( + "both hold what was put on the one started again", + LONG, + move || async move { pair.iter().all(|node| holds(node, ids)) }, + ) + .await; + } + assert!(a.doc.read().await.heads().is_empty()); + assert_eq!(read(&a, |store| store.state().values().len()), Some(4)); + let pair = &[&a, &b]; + sim.wait_until("they stand alike", LONG, move || async move { + stands(pair[0]).is_some() && stands(pair[0]) == stands(pair[1]) + }) + .await; +} diff --git a/src/state/mod.rs b/src/state/mod.rs index 604f6ae..c3bb4e8 100644 --- a/src/state/mod.rs +++ b/src/state/mod.rs @@ -50,6 +50,10 @@ use crate::swarm::throughput::ThroughputTable; use crate::transport; use crate::transport::firewall::Firewall; +/// Why a write is refused where a set of events carries the node's store. +#[cfg(feature = "federation")] +const NOT_A_SETS: &str = "this node's document is a set of events: what is written to it is events, and of its members' entries the node's own"; + #[derive(Debug, Clone, PartialEq, Eq)] pub(crate) enum NodeLifecycle { // TODO maybe rename discovered_swarm_id to swarm_id if that doesn't impair readability. @@ -377,6 +381,44 @@ impl AppState { *self.closing.borrow() } + /// The kinds of document this node holds, which it says in handshakes: more than + /// one where it holds its store in both (`Holding::kinds`). + pub(crate) fn kinds(&self) -> &'static [&'static str] { + #[cfg(feature = "federation")] + { + self.holding.kinds() + } + #[cfg(not(feature = "federation"))] + { + &[crate::document::KIND] + } + } + + /// Whether this node's document is a set of events (`federation::store::set`): + /// the Automerge document it holds is empty then, and nothing passes it on. + pub(crate) fn of_a_set(&self) -> bool { + #[cfg(feature = "federation")] + { + self.holding.of_a_set() + } + #[cfg(not(feature = "federation"))] + { + false + } + } + + /// What the node reads of a document at paths (its members, the policy, the swarm's + /// ID), where this node's document keeps + /// them apart (a set of events, `Holding::entries`): none, where they are in the + /// document it holds. + pub(crate) fn entries(&self) -> Option<crate::document::view::Tree> { + #[cfg(feature = "federation")] + if self.holding.has_a_set() { + return self.holding.entries(); + } + None + } + pub(crate) fn local_id(&self) -> &str { self.transport.local_id() } @@ -602,6 +644,10 @@ impl AppState { T: Send + 'static, E: From<StoreError> + Send + 'static, { + #[cfg(feature = "federation")] + if self.of_a_set() { + return self.mutate_set(f).await; + } self.mutate_doc_as(None, Sign::Protocol, false, move |write| f(write)) .await .map(|(out, _)| out) @@ -620,6 +666,10 @@ impl AppState { T: Send + 'static, E: From<StoreError> + Send + 'static, { + #[cfg(feature = "federation")] + if self.of_a_set() { + return self.mutate_set(f).await; + } self.mutate_doc_as(user, sign, true, move |write| f(write)) .await .map(|(out, _)| out) @@ -639,9 +689,64 @@ impl AppState { T: Send + 'static, E: From<StoreError> + Send + 'static, { + #[cfg(feature = "federation")] + if self.of_a_set() { + return Err(E::from(StoreError::Refused(NOT_A_SETS.to_owned()))); + } self.mutate_doc_as(user, sign, true, f).await } + /// A write where a set of events carries this node's store (`federation::store:: + /// set`): to the members' entries as a document has them (`Holding::entries`), of + /// which the node writes its own alone. What its own reads as after is put as its + /// next entry, signed, and passed on (`swarm::set`). + #[cfg(feature = "federation")] + async fn mutate_set<T, E>(&self, f: impl FnOnce(&mut dyn Write) -> Result<T, E>) -> Result<T, E> + where + E: From<StoreError>, + { + use crate::document::view::Read; + use crate::federation::store::entry::Entry; + use crate::federation::store::set::Put; + + let refused = || E::from(StoreError::Refused(NOT_A_SETS.to_owned())); + let own = crate::swarm::members::member_path(self.local_id()); + let before = self.holding.entries().unwrap_or_default(); + let mut after = before.clone(); + let out = f(&mut after)?; + let was = before.read_path(&own).map_err(E::from)?; + let is = after.read_path(&own).map_err(E::from)?; + // Nothing but its own entry, which it doesn't take away. + let (mut rest_before, mut rest_after) = (before, after); + let _ = rest_before.delete_path(&own, true); + let _ = rest_after.delete_path(&own, true); + if rest_before != rest_after { + return Err(refused()); + } + let Some(is) = is else { + return if was.is_some() { + Err(refused()) + } else { + Ok(out) + }; + }; + if Some(&is) == was.as_ref() { + return Ok(out); + } + let Some(key) = self.node_key.clone() else { + return Err(refused()); + }; + let node = self.local_id().to_owned(); + let put = self.holding.change_set(|set| { + let count = set.entry(&node).map_or(1, |entry| entry.count() + 1); + set.put_entry(Entry::new(&set.store().id(), &key, count, &is)) + }); + if put == Some(Put::Taken) { + crate::swarm::set::registered(self).await; + } + Ok(out) + } + /// [`mutate_doc_for`](Self::mutate_doc_for); with `registering_first`, after this /// node's registration if the policy needs it first. While writes are held /// (`writes_held`), after they no longer are. diff --git a/src/state/peer.rs b/src/state/peer.rs index 721a754..356736a 100644 --- a/src/state/peer.rs +++ b/src/state/peer.rs @@ -92,6 +92,9 @@ pub(crate) struct PeerState { /// The party its handshakes name, in a swarm holding a store (`swarm::peer::members`). #[cfg(feature = "federation")] pub(crate) party: Option<String>, + /// The kind of document its handshakes say it holds, of those this node holds: what + /// this node says to it in turn, and passes on to it (`swarm::peer::inbound`). + pub(crate) kind: Option<&'static str>, pub(crate) hello_state: HelloState, /// Wait between unanswered HELLOs; reset whenever a new handshake starts. pub(crate) hello_backoff: Backoff, @@ -339,6 +342,7 @@ impl PeerState { tree_writer: None, left: false, hello_attempts: 0, + kind: None, last_hello_at: None, unreachable_since: None, incidents: Incidents::default(), diff --git a/src/swarm/bootstrap.rs b/src/swarm/bootstrap.rs index 7626d53..45c86e6 100644 --- a/src/swarm/bootstrap.rs +++ b/src/swarm/bootstrap.rs @@ -39,6 +39,11 @@ const BOOTSTRAP_REPORT: Duration = Duration::from_secs(300); /// Retrying seeds that didn't resolve: first after this, doubling up to the maximum. const RESOLVE_RETRY: Duration = Duration::from_secs(5); const RESOLVE_RETRY_MAX: Duration = Duration::from_secs(300); +/// A seed that resolved, and whose HELLO failed, is said HELLO again this soon, a few +/// times (`HELLO_SOON`): what a node speaks is mostly known a moment after it proved +/// where it is, and a HELLO in a version that can't say this node's kind didn't go. +const HELLO_AGAIN: Duration = Duration::from_millis(250); +const HELLO_SOON: u32 = 4; /// How this node starts. #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -52,6 +57,27 @@ pub(crate) enum Start { } pub(crate) async fn bootstrap(state: &AppState, seeds: &[String], start: Start) -> Result<()> { + // A set of events is its store's document, and the store's ID its swarm's: it + // starts on what it holds, with nothing in the document the node holds beside. + // Holding nothing of it yet, it first gathers what the set begins from of the + // members it reaches through its seeds (`swarm::set::ask_to_start`). + #[cfg(feature = "federation")] + if state.of_a_set() { + if let Some(store) = state.holding.store_id() { + state.set_expected_swarm_id(store.to_string()).await?; + } + if state.holding.with(|_| ()).is_none() { + reach_seeds(state, seeds).await; + let mut closing = state.closing.subscribe(); + while state.holding.with(|_| ()).is_none() { + crate::swarm::set::ask_to_start(state).await; + tokio::select! { + () = tokio::time::sleep(std::time::Duration::from_secs(1)) => {} + _ = closing.wait_for(|closing| *closing) => return Ok(()), + } + } + } + } if let Start::FromDocument(origin) = start { let Some(swarm_id) = state.swarm_id().await else { bail!("starting on a document without a swarm ID"); @@ -314,6 +340,68 @@ 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, where the node is given it and pins no checkpoint; else + /// to be gathered of its peers, from the checkpoint `pin` names, or the root, by its + /// name; of `both` kinds, none without a file. What a checkpoint forgot is kept for + /// `keeps`. + pub(crate) fn set( + &self, + path: &Path, + files: &Files, + pin: Option<crate::federation::store::Id>, + keeps: std::time::Duration, + both: bool, + ) -> Result<Option<crate::federation::held::Begun>> { + use crate::federation::fold::Federation; + use crate::federation::held::Begun; + use crate::federation::store::{memory::Store, passing::Start, 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 anew, 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(Some(Begun::Set(Box::new(set)))); + } + // A node of both kinds makes its set of the store as it reads it of its + // document (`Holding::of_both`). + if both { + return Ok(None); + } + match (&self.root, pin) { + (Some((root, kept)), None) => { + 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(Some(Begun::Set(Box::new(Set::new(store, keeps))))) + } + (_, pin) => { + let at = pin.unwrap_or(self.id); + info!(swarm_id = %self.id, from = %at, "Joining the swarm holding the store with nothing of it: its set begins from what members give by that name"); + Ok(Some(Begun::Start(Start::new(self.id, at, keeps)))) + } + } + } + /// The swarm's ID: the root's, in hex. pub(crate) fn swarm_id(&self) -> String { self.id.to_string() @@ -512,7 +600,7 @@ fn load_backup(path: &Path, files: &Files) -> Result<Document> { async fn reach_seeds(state: &AppState, seeds: &[String]) { let mut unresolved = seeds.to_vec(); let mut failing = HashSet::new(); - resolve_seeds(state, &mut unresolved, &mut failing).await; + let mut unsaid = resolve_seeds(state, &mut unresolved, &mut failing).await; if unresolved.is_empty() { return; } @@ -520,13 +608,18 @@ async fn reach_seeds(state: &AppState, seeds: &[String]) { let mut closing = state.closing.subscribe(); tokio::spawn(async move { let mut retry = RESOLVE_RETRY; + let mut soon = 0; while !unresolved.is_empty() { tokio::select! { - () = tokio::time::sleep(retry) => {} + () = tokio::time::sleep(if unsaid && soon < HELLO_SOON { HELLO_AGAIN } else { retry }) => {} _ = closing.wait_for(|closing| *closing) => return, } - resolve_seeds(&state, &mut unresolved, &mut failing).await; - retry = (retry * 2).min(RESOLVE_RETRY_MAX); + if unsaid && soon < HELLO_SOON { + soon += 1; + } else { + retry = (retry * 2).min(RESOLVE_RETRY_MAX); + } + unsaid = resolve_seeds(&state, &mut unresolved, &mut failing).await; } }); } @@ -535,7 +628,9 @@ async fn resolve_seeds( state: &AppState, unresolved: &mut Vec<String>, failing: &mut HashSet<String>, -) { +) -> bool { + // Whether a seed resolved and its HELLO failed. + let mut unsaid = false; let mut still = Vec::new(); for seed in unresolved.drain(..) { match state.transport.resolve_seed(&seed).await { @@ -549,6 +644,19 @@ async fn resolve_seeds( crate::swarm::roots::seed_found(state, &peer); if let Err(error) = send_hello_once(state, &peer).await { warn!(peer = %peer, error = %format!("{error:#}"), "Initial HELLO failed; will retry"); + // Again with the seeds that don't resolve yet: nothing else says + // HELLO again to a node that is no neighbour (`peer::worker`). + if let Some(peer_state) = state.get_peer_state(&peer).await { + let mut peer_state = peer_state.lock().await; + if matches!( + peer_state.hello_state, + crate::state::HelloState::AwaitingReply { .. } + ) { + peer_state.hello_state = crate::state::HelloState::NotSent; + } + } + unsaid = true; + still.push(seed); } } Err(error) => { @@ -562,6 +670,7 @@ async fn resolve_seeds( } } *unresolved = still; + unsaid } /// Why the node is still joining, for the log. @@ -631,6 +740,66 @@ 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); + use crate::federation::held::Begun; + let set_of = |start: &StoreStart, pin| match start.set(&path, &files, pin, keeps, false) { + Ok(Some(Begun::Set(set))) => Some(*set), + Ok(Some(Begun::Start(_)) | None) => None, + Err(error) => panic!("{error:#}"), + }; + // No file: from the root, where given and no checkpoint is pinned; else to be + // gathered of peers. + assert!(set_of(&joining, None).is_none()); + assert!(set_of(&store, Some(Id::of(b"a checkpoint"))).is_none()); + let mut set = set_of(&store, None).expect("from the root"); + 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 = set_of(start, None).expect("from the file"); + 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, None, keeps, false).is_err()); + std::fs::write(&path, b"something else").unwrap(); + assert!(store.set(&path, &files, None, keeps, false).is_err()); + // A node of both kinds: the file, where there is one; else none here. + std::fs::remove_file(&path).unwrap(); + assert!( + store + .set(&path, &files, None, keeps, true) + .unwrap() + .is_none() + ); + } + /// 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] diff --git a/src/swarm/members.rs b/src/swarm/members.rs index eac4d55..5a54593 100644 --- a/src/swarm/members.rs +++ b/src/swarm/members.rs @@ -368,14 +368,16 @@ pub(crate) async fn ensure_registered(state: &AppState) { shortest, ) = { let replica = state.doc.read().await; + let entries = state.entries(); + let listed = &crate::document::view::members_of(&entries, &replica.doc); ( - registered(&replica.doc, &local), - alias(&replica.doc, &local), - dashboard(&replica.doc, &local), - addresses(&replica.doc, &local), - millis_at(&replica.doc, &alive_path(&local)), - millis_at(&replica.doc, &window_path(&local)), - shortest_window(&replica.doc, state.electorate_window), + registered(listed, &local), + alias(listed, &local), + dashboard(listed, &local), + addresses(listed, &local), + millis_at(listed, &alive_path(&local)), + millis_at(listed, &window_path(&local)), + shortest_window(listed, state.electorate_window), ) }; let wanted = state.alias.clone(); @@ -454,7 +456,11 @@ pub(crate) async fn ensure_registered(state: &AppState) { // The party it is of, as configured. #[cfg(feature = "federation")] if let Some(ours) = state.holding.party() { - let recorded = party(&state.doc.read().await.doc, &local); + let entries = state.entries(); + let recorded = party( + &crate::document::view::members_of(&entries, &state.doc.read().await.doc), + &local, + ); if recorded.as_deref() != Some(ours) { let (path, value) = (party_path(&local), json!(ours)); match state diff --git a/src/swarm/mod.rs b/src/swarm/mod.rs index 6c0a242..1637130 100644 --- a/src/swarm/mod.rs +++ b/src/swarm/mod.rs @@ -19,6 +19,8 @@ pub(crate) mod refusals; pub(crate) mod relay; pub(crate) mod roots; pub(crate) mod rtt; +#[cfg(feature = "federation")] +pub(crate) mod set; pub(crate) mod skew; pub(crate) mod source; pub(crate) mod speaking; diff --git a/src/swarm/peer/handshake.rs b/src/swarm/peer/handshake.rs index 2e5a315..fc0a31b 100644 --- a/src/swarm/peer/handshake.rs +++ b/src/swarm/peer/handshake.rs @@ -144,7 +144,7 @@ async fn transmit_hello(state: &AppState, peer: &str) -> Result<()> { .await .map(|root| root.0.to_vec()), party: party(state), - kind: crate::document::KIND.to_owned(), + kind: kind_to(state, peer).await.to_owned(), }), ) .await; @@ -180,6 +180,20 @@ async fn say_what_we_speak(state: &AppState, peer: &str) { } } +/// The kind of document this node says to `peer` it holds: the one the peer's +/// handshakes said, of those this node holds; where the peer said none yet, and this +/// node holds more than one, each in turn, HELLO by HELLO, until one is answered. +async fn kind_to(state: &AppState, peer: &str) -> &'static str { + let kinds = state.kinds(); + let Some(peer_state) = state.get_peer_state(peer).await else { + return kinds[0]; + }; + let peer_state = peer_state.lock().await; + peer_state + .kind + .unwrap_or(kinds[peer_state.hello_attempts as usize % kinds.len()]) +} + pub(super) async fn ensure_handshake(state: &AppState, peer: &str) { if let Err(error) = send_hello_once(state, peer).await { warn!(peer = %peer, error = %format!("{error:#}"), "HELLO failed; will retry"); @@ -255,7 +269,7 @@ pub(super) async fn send_hello_reply( .await .map(|root| root.0.to_vec()), party: party(state), - kind: crate::document::KIND.to_owned(), + kind: kind_to(state, peer).await.to_owned(), }; debug!(to = %peer, ready, "Sending HELLO_REPLY"); diff --git a/src/swarm/peer/inbound.rs b/src/swarm/peer/inbound.rs index a558ded..b6c486d 100644 --- a/src/swarm/peer/inbound.rs +++ b/src/swarm/peer/inbound.rs @@ -114,12 +114,22 @@ pub(crate) async fn handle_message( ParsedMessage::HelloReply(reply) => Some(&reply.kind), _ => None, }; - if let Some(theirs) = kind.filter(|kind| *kind != crate::document::KIND) { - anyhow::bail!( - "{peer} holds a document of another kind ({theirs}; this node's is {}): they sync \ - nothing; a release that knows the kind does", - crate::document::KIND - ); + if let Some(theirs) = kind { + let Some(held) = state.kinds().iter().find(|held| *held == theirs) else { + anyhow::bail!( + "{peer} holds a document of another kind ({theirs}; this node's is {}): they \ + sync nothing; a release that knows the kind does", + state.kinds().join(" and ") + ); + }; + // Of the kinds this node holds, the one the peer holds: what it is told in + // turn, and passed on. + state + .get_or_create_peer_state(&peer) + .await + .lock() + .await + .kind = Some(held); } // The root its document starts from: another than ours, of our epoch, is another @@ -218,6 +228,18 @@ pub(crate) async fn handle_message( .map_err(|error| anyhow!("Failed to notify sync worker: {error}"))?; } transport::ParsedMessage::Sync(envelope) => { + // Of a set of events: this node's set's to take, where it holds one + // (`swarm::set`); and of an Automerge document nothing, where it holds a set + // alone. + #[cfg(feature = "federation")] + if state.of_a_set() || matches!(envelope.body, transport::SyncBody::Kind(_)) { + if let transport::SyncBody::Kind(body) = envelope.body + && state.holding.has_a_set() + { + crate::swarm::set::received(state, &peer, body).await; + } + return Ok(()); + } if reactivated { ensure_handshake(state, &peer).await; } @@ -251,6 +273,8 @@ pub(crate) async fn handle_message( crate::swarm::blob::handle(state, &peer, blob).await; } transport::ParsedMessage::Status(remote) => { + #[cfg(feature = "federation")] + let remote = crate::swarm::set::heard_status(state, &peer, remote); // An announcement is no keepalive; it is answered only if we lack some of the // heads it announced (`relay::lacks`), so the announcer learns what we have // that it lacks while we pull. Having all of them, we are as far or further, @@ -290,6 +314,8 @@ pub(crate) async fn handle_message( } } transport::ParsedMessage::StatusReply(remote) => { + #[cfg(feature = "federation")] + let remote = crate::swarm::set::heard_status(state, &peer, remote); // An answer to our slow round's announcement: a tree missed. let announced = peer_state.lock().await.slow_announced_at.take(); if let Some(at) = announced { diff --git a/src/swarm/peer/keepalive.rs b/src/swarm/peer/keepalive.rs index 72ab033..bbcc6e3 100644 --- a/src/swarm/peer/keepalive.rs +++ b/src/swarm/peer/keepalive.rs @@ -182,10 +182,21 @@ pub(crate) async fn local_status(state: &AppState, peer: &str) -> transport::Sta let stamp = state.stamp.borrow(); (stamp.summary(), stamp.epoch, stamp.epoch_seq) }; - let syncs_with_you = match state.get_peer_state(peer).await { - Some(peer_state) => peer_state.lock().await.syncs_on(epoch), - None => false, + let (syncs_with_you, _of_a_set) = match state.get_peer_state(peer).await { + Some(peer_state) => { + let peer_state = peer_state.lock().await; + ( + peer_state.syncs_on(epoch), + peer_state + .kind + .is_some_and(|kind| kind != crate::document::KIND), + ) + } + None => (false, false), }; + // To a peer that holds a set of events, where this node's stands (`swarm::set`). + #[cfg(feature = "federation")] + let heads = crate::swarm::set::stamp(state, _of_a_set).unwrap_or(heads); let (reaches, round_trips) = crate::swarm::reach::published_with_round_trips(state); transport::Status { heads, diff --git a/src/swarm/reach.rs b/src/swarm/reach.rs index 760bcb5..20961ad 100644 --- a/src/swarm/reach.rs +++ b/src/swarm/reach.rs @@ -196,7 +196,9 @@ pub(crate) fn of(said: Option<&(Instant, Vec<u64>)>) -> Option<Vec<u64>> { /// The members of our member list by pair key, to name what neighbours say they reach. pub(crate) async fn names(state: &AppState) -> HashMap<u64, String> { let replica = state.doc.read().await; - members::members(&replica.doc) + let entries = state.entries(); + let listed = &crate::document::view::members_of(&entries, &replica.doc); + members::members(listed) .into_iter() .map(|member| (topology::pair_key(&member), member)) .collect() diff --git a/src/swarm/set.rs b/src/swarm/set.rs new file mode 100644 index 0000000..54a48fe --- /dev/null +++ b/src/swarm/set.rs @@ -0,0 +1,278 @@ +//! Passing a set of events on between nodes (`docs/document.md`, A set of events): the +//! swarm's side of `federation::store::passing`, for a node whose store a set carries +//! (`Holding::carrying`). +//! +//! * Where the node stands goes in its STATUSes, keepalives and their replies, as +//! another kind's stamp (`HeadsSummary::Kind`); a peer's is given to the set, and what +//! the set says back goes to that peer. +//! * Everything else the set says goes as a SYNC's body (`SyncBody::Kind`). +//! * What the set took of a peer, or of this node's own, goes on at once to the node's +//! other neighbours, as units: a neighbour that has them takes them for held. +//! +//! Nothing is kept of a peer between messages, and a message lost is nothing to repair: +//! the next keepalive says where the node stands again. + +use std::time::Instant; + +use tracing::debug; + +use crate::federation::store::Id; +use crate::federation::store::passing::{self, Message, Took, Unit}; +use crate::state::AppState; +use crate::swarm::topology; +use crate::transport::{self, HeadsSummary, ParsedMessage, SyncBody}; + +/// Whether `peer` holds a set of events, as its handshakes said: what a node of both +/// kinds passes its set on to. A node that holds a set alone takes handshakes of no +/// other. +pub(crate) async fn holds_a_set(state: &AppState, peer: &str) -> bool { + match state.get_peer_state(peer).await { + Some(peer_state) => { + peer_state.lock().await.kind == Some(crate::federation::store::set::KIND) + } + None => false, + } +} + +/// Where this node's set stands, as its STATUSes say it to a peer that holds one +/// (`to_a_set`); none, where the node holds no set, or the peer doesn't. +pub(crate) fn stamp(state: &AppState, to_a_set: bool) -> Option<HeadsSummary> { + if !state.holding.has_a_set() || !(to_a_set || state.holding.of_a_set()) { + return None; + } + // A node still gathering what its set begins from stands nowhere yet. + let stamp = state + .holding + .with_set(|set| rmp_serde::to_vec(&passing::stamp(set)).expect("a stamp encodes")) + .unwrap_or_default(); + Some(HeadsSummary::Kind(stamp)) +} + +/// What a STATUS of `peer` says, where a set carries this node's store: where the +/// peer's set stands is given to this node's, off the caller's task; and the status is +/// handed on saying this node's own stamp, so that what compares stamps for an +/// Automerge document's sake finds nothing to do. +pub(crate) fn heard_status( + state: &AppState, + peer: &str, + mut remote: transport::Status, +) -> transport::Status { + // A peer that says where a set stands holds one. + let of_a_set = matches!(remote.heads, HeadsSummary::Kind(_)); + let Some(ours) = stamp(state, of_a_set) else { + return remote; + }; + if !of_a_set && !state.holding.of_a_set() { + return remote; + } + if let HeadsSummary::Kind(bytes) = std::mem::replace(&mut remote.heads, ours) + && let Ok(stamp) = rmp_serde::from_slice::<passing::Stamp>(&bytes) + { + let (state, peer) = (state.clone(), peer.to_owned()); + tokio::spawn(async move { + handle(&state, &peer, Message::Stamp(stamp)).await; + }); + } + remote +} + +/// What a SYNC of `peer` carries of its set, where a set carries this node's store. +pub(crate) async fn received(state: &AppState, peer: &str, body: Vec<u8>) { + let message = match rmp_serde::from_slice::<Message>(&body) { + Ok(message) => message, + Err(error) => { + debug!(peer = %peer, error = %error, "What a peer says of its set doesn't read"); + return; + } + }; + // Started with nothing: what was asked for, to begin the set from (`ask_to_start`). + if !state.holding.start_wants().is_empty() { + if let Message::Units(units) = message { + let holding = std::sync::Arc::clone(&state.holding); + let begun = tokio::task::spawn_blocking(move || holding.start_take(units)) + .await + .unwrap_or(false); + if begun { + state.notify_store_changed(); + state.topology_changed.notify_one(); + } else { + ask(state, peer).await; + } + } + return; + } + handle(state, peer, message).await; +} + +/// Asks `peer` for what this node's set begins from, where the node started with +/// nothing and still gathers it. +async fn ask(state: &AppState, peer: &str) { + let wants = state.holding.start_wants(); + if !wants.is_empty() { + send(state, peer, &Message::Wants(wants)).await; + } +} + +/// Asks every peer whose handshake this node took for what its set begins from, where +/// the node started with nothing and still gathers it. +pub(crate) async fn ask_to_start(state: &AppState) { + if state.holding.start_wants().is_empty() { + return; + } + for (peer, peer_state) in state.peers_snapshot().await { + let established = + peer_state.lock().await.hello_state == crate::state::HelloState::Established; + if established { + ask(state, &peer).await; + } + } +} + +/// Gives `message` of `peer` to this node's set, sends the peer what the set says back, +/// and passes on what it took. +async fn handle(state: &AppState, peer: &str, message: Message) { + let holding = std::sync::Arc::clone(&state.holding); + // Taking events judges them: off the tasks that read messages. + let made = tokio::task::spawn_blocking(move || { + holding.change_set(|set| passing::receive(set, message, Instant::now())) + }) + .await; + let Ok(Some((replies, took))) = made else { + return; + }; + for reply in replies { + send(state, peer, &reply).await; + } + pass_on(state, Some(peer), took).await; +} + +/// Sends `peer` what this node's set says. +async fn send(state: &AppState, peer: &str, message: &Message) { + let (epoch, epoch_seq) = state.epoch_stamp(); + let envelope = transport::SyncEnvelope { + epoch: transport::EpochTag::of(epoch), + epoch_seq, + body: SyncBody::Kind(rmp_serde::to_vec(message).expect("a message encodes")), + ready: state.is_ready().await && !state.is_closing(), + writer: None, + delivered: false, + sent: state.clock.now_millis(), + signatures: serde_bytes::ByteBuf::new(), + }; + if let Err(error) = state + .transport + .send_message(peer, &ParsedMessage::Sync(envelope)) + .await + { + debug!(peer = %peer, error = %format!("{error:#}"), "Saying of our set failed"); + } +} + +/// Passes on what this node's set took, of `from` or of the node's own: to its other +/// neighbours, as units; and tells what waits on the store, or on who is a member. +async fn pass_on(state: &AppState, from: Option<&str>, took: Took) { + if took.is_empty() { + return; + } + state.notify_store_changed(); + // Entries are where members are reached, and events may change who is one. + state.topology_changed.notify_one(); + let names = took + .events + .iter() + .map(|id| id.0) + .chain(entry_names(state, &took.entries)); + let units: Vec<Unit> = state + .holding + .with_set(|set| names.filter_map(|name| passing::unit(set, &name)).collect()) + .unwrap_or_default(); + if units.is_empty() { + return; + } + let message = Message::Units(units); + for peer in state.active_peers_on_local_epoch().await { + if Some(peer.as_str()) != from + && topology::is_neighbour(state, &peer) + && holds_a_set(state, &peer).await + { + send(state, &peer, &message).await; + } + } +} + +/// The names of the entries this node's set holds of `nodes`. +fn entry_names(state: &AppState, nodes: &[String]) -> Vec<[u8; 32]> { + state + .holding + .with_set(|set| { + nodes + .iter() + .filter_map(|node| set.entry(node).map(|entry| entry.name())) + .collect() + }) + .unwrap_or_default() +} + +/// Passes on events this node's set took of the node itself (the API, its own votes): +/// `taken`, by their names. +pub(crate) async fn wrote(state: &AppState, taken: Vec<Id>) { + pass_on( + state, + None, + Took { + events: taken, + entries: Vec::new(), + }, + ) + .await; +} + +/// Passes on this node's own entry, which its set just took. +pub(crate) async fn registered(state: &AppState) { + pass_on( + state, + None, + Took { + events: Vec::new(), + entries: vec![state.local_id().to_owned()], + }, + ) + .await; +} + +/// On a node of both kinds, puts its entry as the document it holds has it as its entry +/// in the set, where the two differ, and passes it on: what the node says of itself, +/// it says to the peers of either kind. +pub(crate) async fn mirror_entry(state: &AppState) { + use crate::federation::store::entry::Entry; + use crate::federation::store::set::Put; + + if !state.holding.has_a_set() || state.holding.of_a_set() { + return; + } + let Some(key) = state.node_key.clone() else { + return; + }; + let node = state.local_id().to_owned(); + let own = crate::swarm::members::member_path(&node); + let written = crate::document::view::read_path(&state.doc.read().await.doc, &own); + let Ok(Some(serde_json::Value::Object(written))) = written else { + return; + }; + let put = state.holding.change_set(|set| { + let held = set.entry(&node); + if held.and_then(|entry| entry.value()).as_ref() == Some(&written) { + return None; + } + let count = held.map_or(1, |entry| entry.count() + 1); + Some(set.put_entry(Entry::new( + &set.store().id(), + &key, + count, + &serde_json::Value::Object(written), + ))) + }); + if put.flatten() == Some(Put::Taken) { + registered(state).await; + } +} diff --git a/src/swarm/stability.rs b/src/swarm/stability.rs index 8163e06..c163778 100644 --- a/src/swarm/stability.rs +++ b/src/swarm/stability.rs @@ -178,7 +178,11 @@ pub(crate) async fn tick(state: &AppState) { return; } let local = state.local_id().to_owned(); - let current = members::tier(&state.doc.read().await.doc, &local); + let entries = state.entries(); + let current = members::tier( + &crate::document::view::members_of(&entries, &state.doc.read().await.doc), + &local, + ); let desired = { let mut stability = lock(state); diff --git a/src/swarm/state_file.rs b/src/swarm/state_file.rs index 415fb1a..51b00cc 100644 --- a/src/swarm/state_file.rs +++ b/src/swarm/state_file.rs @@ -133,8 +133,9 @@ pub(crate) async fn update(state: &AppState, now: bool) { let seeds = { let replica = state.doc.read().await; + let entries = state.entries(); seeds( - &replica.doc, + &crate::document::view::members_of(&entries, &replica.doc), state.local_id(), state.electorate_window, state.clock.now_millis().as_u64(), @@ -185,7 +186,12 @@ pub(crate) async fn update(state: &AppState, now: bool) { /// Where to rejoin through: the addresses of members alive within the electorate /// window, stable ones first, of at most `MAX_SEEDS` members, sorted. Changes only when /// members join, leave, move or change tier, so the file rarely does. -fn seeds(doc: &crate::document::Document, me: &str, window: Duration, now: u64) -> Vec<String> { +fn seeds( + doc: &dyn crate::document::view::Read, + me: &str, + window: Duration, + now: u64, +) -> Vec<String> { let (mut stable, transient): (Vec<String>, Vec<String>) = members::electorate(doc, now, window) .into_iter() .filter(|pk| pk != me) diff --git a/src/swarm/sync.rs b/src/swarm/sync.rs index 65a02ea..3939377 100644 --- a/src/swarm/sync.rs +++ b/src/swarm/sync.rs @@ -63,6 +63,13 @@ async fn deliver_sync_to_peer(state: &AppState, peer: &str) -> Result<()> { } } + // A set of events is passed on otherwise (`swarm::set`): with a peer that holds + // one, and of the Automerge document a node holds beside one alone, no sync. + #[cfg(feature = "federation")] + if state.of_a_set() || crate::swarm::set::holds_a_set(state, peer).await { + return Ok(()); + } + let we_ready = state.is_ready().await; let validated_swarm = { @@ -405,6 +412,9 @@ pub(crate) async fn handle_sync( // Changes pushed along a tree (`SyncBody::Changes`): their heads and bytes, made // into the Automerge message that would have brought them (`Received::pushed`). let (payload, deflated, pushed) = match envelope.body { + // Of a document of another kind: none this node holds, which a peer holding + // one isn't let near (`peer::inbound`). + transport::SyncBody::Kind(_) => return Ok(()), transport::SyncBody::Message(payload) => (payload, false, None), transport::SyncBody::Deflated(payload) => (payload, true, None), transport::SyncBody::Changes { heads, changes } => { diff --git a/src/swarm/topology/mod.rs b/src/swarm/topology/mod.rs index df9a27e..1f99cd8 100644 --- a/src/swarm/topology/mod.rs +++ b/src/swarm/topology/mod.rs @@ -382,7 +382,7 @@ pub(crate) fn with_recorded( #[cfg(feature = "federation")] fn of_the_store( state: &AppState, - doc: &crate::document::Document, + doc: &dyn crate::document::view::Read, listed: Vec<String>, ) -> Vec<String> { if !state.holding.tells_members() { @@ -411,11 +411,13 @@ async fn nearby(state: &AppState, inputs: &Inputs<'_>) -> BTreeSet<String> { } let group: BTreeMap<String, BTreeSet<String>> = { let replica = state.doc.read().await; + let entries = state.entries(); + let listed = &crate::document::view::members_of(&entries, &replica.doc); inputs .transports .iter() .filter(|(member, _)| { - members::party(&replica.doc, member) + members::party(listed, member) .is_some_and(|party| parties.contains(&party.as_str())) }) .map(|(member, transports)| (member.clone(), transports.clone())) @@ -738,32 +740,31 @@ pub(crate) async fn refresh(state: &AppState) -> Option<NeighbourChange> { } let (current, stable, transports, alive, k, recorded) = { let replica = state.doc.read().await; - members::apply(state, &replica.doc); + let entries = state.entries(); + let listed = &crate::document::view::members_of(&entries, &replica.doc); + members::apply(state, listed); let k = swarm_neighbours(&replica.doc, state.neighbours_k); switch_ways(state, swarm_ways(&replica.doc, state.configured_ways)); - let current = members::members(&replica.doc); + let current = members::members(listed); #[cfg(feature = "federation")] - let current = of_the_store(state, &replica.doc, current); + let current = of_the_store(state, listed, current); // Those that said they are alive within the electorate window. - let alive: BTreeSet<String> = members::electorate( - &replica.doc, - state.clock.now_millis().0, - state.electorate_window, - ) - .into_iter() - .collect(); + let alive: BTreeSet<String> = + members::electorate(listed, state.clock.now_millis().0, state.electorate_window) + .into_iter() + .collect(); let stable: BTreeSet<String> = current .iter() - .filter(|m| members::tier(&replica.doc, m) == members::Tier::Stable) + .filter(|m| members::tier(listed, m) == members::Tier::Stable) .cloned() .collect(); let transports: BTreeMap<String, BTreeSet<String>> = current .iter() - .map(|m| (m.clone(), schemes(&members::addresses(&replica.doc, m)))) + .map(|m| (m.clone(), schemes(&members::addresses(listed, m)))) .collect(); let recorded: BTreeMap<String, members::RecordedLinks> = current .iter() - .map(|m| (m.clone(), members::links(&replica.doc, m))) + .map(|m| (m.clone(), members::links(listed, m))) .filter(|(_, links)| *links != members::RecordedLinks::default()) .collect(); (current, stable, transports, alive, k, recorded) diff --git a/src/swarm/working_links.rs b/src/swarm/working_links.rs index b384919..ca3a22b 100644 --- a/src/swarm/working_links.rs +++ b/src/swarm/working_links.rs @@ -182,11 +182,13 @@ pub(crate) async fn check(state: &AppState) { // would leave none. let (recorded, links) = { let replica = state.doc.read().await; - let recorded = members::links(&replica.doc, &me); + let entries = state.entries(); + let listed = &crate::document::view::members_of(&entries, &replica.doc); + let recorded = members::links(listed, &me); let mut links = links; links.unreached.retain(|member| { recorded.unreached.contains(member) - || !members::links(&replica.doc, member).unreached.contains(&me) + || !members::links(listed, member).unreached.contains(&me) }); (recorded, links) }; diff --git a/src/transport/mod.rs b/src/transport/mod.rs index 61abe9c..4189890 100644 --- a/src/transport/mod.rs +++ b/src/transport/mod.rs @@ -114,6 +114,9 @@ pub(crate) enum HeadsSummary { /// of starting the sync over to find out what it lacks. sample: Vec<ChangeHash>, }, + /// Where a document of another kind than Automerge's stands, as that kind's bytes + /// (`docs/document.md`, Passing on): neither heads nor a digest of any. + Kind(Vec<u8>), } /// Where the next sample starts (`HeadsSummary::of`). @@ -144,6 +147,7 @@ impl HeadsSummary { match self { Self::Heads(heads) => digest_of(heads), Self::Digest { digest, .. } => *digest, + Self::Kind(bytes) => Sha256::digest(bytes).into(), } } @@ -151,7 +155,7 @@ impl HeadsSummary { pub(crate) fn heads(&self) -> Option<&[ChangeHash]> { match self { Self::Heads(heads) => Some(heads), - Self::Digest { .. } => None, + Self::Digest { .. } | Self::Kind(_) => None, } } @@ -160,6 +164,7 @@ impl HeadsSummary { match self { Self::Heads(heads) => heads, Self::Digest { sample, .. } => sample, + Self::Kind(_) => &[], } } } @@ -845,6 +850,9 @@ pub(crate) enum SyncBody { /// Instead of a message too large to send in one piece: fetch these changes as a /// blob (`BlobId::Delta`), then sync on. Delta(DeltaSpec), + /// What a document of another kind than Automerge's says, as that kind's bytes + /// (`docs/document.md`, Passing on). + Kind(#[serde(with = "serde_bytes")] Vec<u8>), } /// The changes in the history of `to` but not of `from`: what a peer at `from` lacks of @@ -934,6 +942,10 @@ impl std::fmt::Debug for SyncBody { ) .finish(), Self::Delta(spec) => f.debug_tuple("Delta").field(spec).finish(), + Self::Kind(bytes) => f + .debug_tuple("Kind") + .field(&format!("{} bytes", bytes.len())) + .finish(), } } } diff --git a/src/transport/traffic.rs b/src/transport/traffic.rs index 33903ca..01bba65 100644 --- a/src/transport/traffic.rs +++ b/src/transport/traffic.rs @@ -225,7 +225,10 @@ fn related(peer: &str, message: &ParsedMessage) -> Option<String> { SyncBody::Delta(spec) => { format!("blob {}", crate::transport::BlobId::Delta(spec.id())) } - SyncBody::Message(_) | SyncBody::Deflated(_) | SyncBody::Changes { .. } => { + SyncBody::Message(_) + | SyncBody::Deflated(_) + | SyncBody::Changes { .. } + | SyncBody::Kind(_) => { return None; } }, diff --git a/src/transport/wire.rs b/src/transport/wire.rs index 79532fb..dda052b 100644 --- a/src/transport/wire.rs +++ b/src/transport/wire.rs @@ -89,6 +89,9 @@ pub(crate) enum WireError { #[error("wire format version {0} (we speak version {VERSION})")] Version(u8), + #[error("a document of another kind than Automerge's, which wire version {0} doesn't say")] + OtherKind(u8), + #[error("unknown message kind {0}")] UnknownKind(u8), @@ -139,6 +142,9 @@ pub(crate) fn encode_in(message: &ParsedMessage, version: u8) -> Result<Vec<u8>, if !(OLDEST..=VERSION).contains(&version) && !proof { return Err(WireError::Version(version)); } + if version < KINDS && of_another_kind(message) { + return Err(WireError::OtherKind(version)); + } let mut payload = vec![version, tag(message.kind())]; // From `KINDS` on, what is a document's kind's goes as bytes (`kinds`); before, as // the messages' own types have it, which are Automerge's. @@ -173,6 +179,24 @@ pub(crate) fn encode_in(message: &ParsedMessage, version: u8) -> Result<Vec<u8>, Ok(payload) } +/// Whether `message` carries what a document of another kind than Automerge's says, +/// which only the versions from `KINDS` on carry. +fn of_another_kind(message: &ParsedMessage) -> bool { + match message { + // A handshake in a version that says no kind is taken for an Automerge + // document's: one of another kind waits for a version that says it. + ParsedMessage::Hello(hello) => hello.kind != crate::document::KIND, + ParsedMessage::HelloReply(reply) => reply.kind != crate::document::KIND, + ParsedMessage::Sync(envelope) => { + matches!(envelope.body, crate::transport::SyncBody::Kind(_)) + } + ParsedMessage::Status(status) | ParsedMessage::StatusReply(status) => { + matches!(status.heads, crate::transport::HeadsSummary::Kind(_)) + } + _ => false, + } +} + /// The payload of `message`, in the newest wire version. #[cfg(test)] pub(crate) fn encode(message: &ParsedMessage) -> Result<Vec<u8>, WireError> { @@ -256,6 +280,10 @@ mod kinds { round_trips: Option<Vec<u8>>, } + /// What the stamp of a document of another kind than Automerge's begins with: an + /// Automerge stamp is a MessagePack array, which begins otherwise. + const OTHER_STAMP: u8 = 0; + /// Where an Automerge document stands, as its bytes have it. struct StampOut<'a>(&'a HeadsSummary); @@ -338,7 +366,11 @@ mod kinds { )? } ParsedMessage::Status(status) | ParsedMessage::StatusReply(status) => { - let stamp = rmp_serde::to_vec(&StampOut(&status.heads))?; + let stamp = match &status.heads { + // Another kind's, after a byte that begins no Automerge stamp. + HeadsSummary::Kind(bytes) => [&[OTHER_STAMP], bytes.as_slice()].concat(), + heads => rmp_serde::to_vec(&StampOut(heads))?, + }; rmp_serde::encode::write( payload, &StatusOut { @@ -437,7 +469,10 @@ mod kinds { /// The STATUS, or the STATUS_REPLY, in `body`. pub(super) fn status(body: &[u8]) -> Result<Status, WireError> { let status: StatusIn = rmp_serde::from_slice(body)?; - let StampIn(heads) = rmp_serde::from_slice(&status.stamp)?; + let heads = match status.stamp.split_first() { + Some((&OTHER_STAMP, bytes)) => HeadsSummary::Kind(bytes.to_vec()), + _ => rmp_serde::from_slice::<StampIn>(&status.stamp)?.0, + }; Ok(Status { heads, epoch: status.epoch, @@ -784,6 +819,11 @@ pub(crate) mod codec { heads.iter().map(|head| Bytes::new(&head.0)).collect(), Bytes::new(&[]), ), + HeadsSummary::Kind(_) => { + return Err(serde::ser::Error::custom( + "where a document of another kind stands, which heads don't say", + )); + } HeadsSummary::Digest { digest, sample } => ( sample.iter().map(|head| Bytes::new(&head.0)).collect(), Bytes::new(digest), @@ -1202,7 +1242,16 @@ mod tests { other => panic!("{other:?}"), }; assert_eq!(read(&hello("another"), KINDS), "another"); - assert_eq!(read(&hello("another"), KINDS - 1), crate::document::KIND); + // The version before says no kind, and one read in it is Automerge's: a + // handshake of another kind doesn't go in it. + assert_eq!( + read(&hello(crate::document::KIND), KINDS - 1), + crate::document::KIND + ); + assert!(matches!( + encode_in(&hello("another"), KINDS - 1), + Err(WireError::OtherKind(_)) + )); assert_eq!( read(&hello(crate::document::KIND), VERSION), crate::document::KIND @@ -1497,6 +1546,70 @@ mod tests { /// The exact bytes of the messages that carry what is a document's kind's, from /// `KINDS` on (`kinds`). If this fails after a change to a message type or a codec, /// the change is a new wire format: bump `VERSION` and take the new bytes. + /// What a document of another kind than Automerge's says goes where Automerge's + /// does, from the version that carries a kind's bytes on; the version before + /// doesn't say it. + #[test] + fn another_kinds_bytes_go_in_sync_and_status() { + let epoch = Epoch { + generation: 0, + id: [0; 32], + }; + let status = ParsedMessage::Status(Status { + heads: HeadsSummary::Kind(vec![0xaa; 4]), + epoch, + epoch_seq: 0, + ready: true, + syncs_with_you: true, + leaving: false, + announcing: false, + reaches: None, + round_trips: None, + }); + let sync = ParsedMessage::Sync(crate::transport::SyncEnvelope { + epoch: crate::transport::EpochTag::of(epoch), + epoch_seq: 0, + body: crate::transport::SyncBody::Kind(vec![5, 6]), + ready: true, + writer: None, + delivered: false, + sent: crate::clock::UnixMillis(8), + signatures: serde_bytes::ByteBuf::new(), + }); + let status_bytes = encode_in(&status, KINDS).unwrap(); + let sync_bytes = encode_in(&sync, KINDS).unwrap(); + assert_eq!( + hex(&status_bytes), + "350399c40500aaaaaaaa9200c420000000000000000000000000000000000000000000000000000000000000000000c3c3c2c2c0c0" + ); + assert_eq!( + hex(&sync_bytes), + "3502979200c408000000000000000000c40c9281a44b696e64c4020506c2c3c008c400" + ); + let ParsedMessage::Status(read) = decode(&status_bytes).unwrap() else { + panic!("no status"); + }; + assert!(matches!(read.heads, HeadsSummary::Kind(bytes) if bytes == vec![0xaa; 4])); + let ParsedMessage::Sync(read) = decode(&sync_bytes).unwrap() else { + panic!("no sync"); + }; + assert!( + matches!(read.body, crate::transport::SyncBody::Kind(bytes) if bytes == vec![5, 6]) + ); + assert!(!read.delivered); + // Two stamps of another kind are the same where their bytes are. + assert_eq!(HeadsSummary::Kind(vec![1]), HeadsSummary::Kind(vec![1])); + assert_ne!(HeadsSummary::Kind(vec![1]), HeadsSummary::Kind(vec![2])); + assert!(matches!( + encode_in(&status, 52), + Err(WireError::OtherKind(52)) + )); + assert!(matches!( + encode_in(&sync, 52), + Err(WireError::OtherKind(52)) + )); + } + #[test] fn golden_bytes_of_kinds() { let epoch = Epoch { |
