tilo_actions/document_sync.rs
1//! Which records a device is sent when it joins a workspace, and which it asks
2//! for when it needs them.
3//!
4//! Most records are *eager*: a joining device is replayed them and follows
5//! their changes live. A record can instead be declared *on-demand* by its
6//! id: a joining device is not replayed it, and gets its history and its
7//! live changes only once it asks to open it. A big workspace keeps the
8//! documents nobody has open out of every join that way.
9//!
10//! A record that grows without end is kept as a *chain* of numbered parts
11//! instead, each a record of its own: `derived:part.<n>@<base>`. The part
12//! with the highest number a host holds is the chain's head, which takes the
13//! new writes and is replayed like an eager record; every earlier part is
14//! on-demand. A part's id is its base and its number, so two writers that
15//! both start part `n + 1` start the same record, and nothing has to decide
16//! which of them did.
17//!
18//! A record the platform splits into *chunks* keeps one of them — chunk `0`,
19//! the record itself — eager and declares the rest
20//! (`derived:chunk.<n>@<base>`, `n` from `1`) on-demand: the record's manifest
21//! says which chunks exist, and a device is sent the ones it opens. A write
22//! therefore moves only the chunk it changed to the devices holding it.
23//!
24//! The declaration is the record id itself, because every host can read the
25//! route a change travels on, sealed or not.
26//!
27//! A workspace can also send all of its records on demand: a public one,
28//! which anyone may walk into, replays a newcomer only its governance and its
29//! shared desktop, whatever its records' ids say. Its host decides that for
30//! the workspace and says so in the `Ready` that ends a device's replay; the
31//! device then asks for every record it opens, and takes one as new only once
32//! the host answered it holds none of it.
33//!
34//! A device that holds no part of a chain finds its head by opening the
35//! chain's *head* (`derived:head@<base>`, [`chain_head`]): a name for
36//! whichever part is the head, which holds nothing of its own. The host sends
37//! the head part's history in answer, and the device follows the chain from
38//! then on, each later head included: one round trip, whichever part the head
39//! is. Answered with nothing, the chain has no part yet.
40
41/// Role of a part of a chained record, in `derived:part.<n>@<base>`.
42const PART_ROLE: &str = "part.";
43/// Role of a chunk of a split record, in `derived:chunk.<n>@<base>`.
44const CHUNK_ROLE: &str = "chunk.";
45/// Role of a record declared on-demand, in `derived:on-demand@<base>`.
46const ON_DEMAND_ROLE: &str = "on-demand";
47/// Role of a chain's head, in `derived:head@<base>`.
48const HEAD_ROLE: &str = "head";
49
50/// How a record reaches the devices of a workspace.
51#[derive(Clone, Copy, Debug, PartialEq, Eq)]
52pub enum DocumentSync<'a> {
53 /// Replayed to every joining device and followed live.
54 Eager,
55 /// Sent to a device only once it opens the record.
56 OnDemand,
57 /// Part `index` of the chain `base`: eager while it is the chain's head,
58 /// on-demand once a later part exists.
59 Part {
60 /// The record the chain belongs to.
61 base: &'a str,
62 /// The part's number, from `0`.
63 index: u64,
64 },
65 /// Chunk `number` of the split record `base`, its `0` being the record
66 /// itself; always on-demand.
67 Chunk {
68 /// The record the chunk belongs to.
69 base: &'a str,
70 /// The chunk's number, from `1`.
71 number: u64,
72 },
73 /// The head of the chain `base`, whichever part that is: opened, it
74 /// sends that part and follows the chain. No document lives under it.
75 ChainHead {
76 /// The record the chain belongs to.
77 base: &'a str,
78 },
79}
80
81/// How `record` (a route's record id) is synced.
82#[must_use]
83pub fn document_sync(record: &str) -> DocumentSync<'_> {
84 let Some((role, base)) = record
85 .strip_prefix("derived:")
86 .and_then(|derived| derived.split_once('@'))
87 else {
88 return DocumentSync::Eager;
89 };
90 if role == ON_DEMAND_ROLE {
91 return DocumentSync::OnDemand;
92 }
93 if role == HEAD_ROLE {
94 return DocumentSync::ChainHead { base };
95 }
96 if let Some(index) = role.strip_prefix(PART_ROLE) {
97 return match numbered(index) {
98 Some(index) => DocumentSync::Part { base, index },
99 None => DocumentSync::Eager,
100 };
101 }
102 let Some(number) = role.strip_prefix(CHUNK_ROLE) else {
103 return DocumentSync::Eager;
104 };
105 // Chunks are numbered from `1`: chunk `0` is the record itself.
106 match numbered(number) {
107 Some(number) if number > 0 => DocumentSync::Chunk { base, number },
108 _ => DocumentSync::Eager,
109 }
110}
111
112/// The number a `part.`/`chunk.` role carries, when it is canonical: decimal
113/// digits and no leading zero, so one part or chunk has one id.
114fn numbered(index: &str) -> Option<u64> {
115 let canonical = !index.is_empty()
116 && index.bytes().all(|byte| byte.is_ascii_digit())
117 && (index == "0" || !index.starts_with('0'));
118 canonical
119 .then(|| {
120 tilo_failure::ignored!(
121 "a probe of the id's shape: only a number past u64 fails, and it names no part",
122 index.parse().ok()
123 )
124 })
125 .flatten()
126}
127
128/// The id of part `index` of the chained record `base`.
129#[must_use]
130pub fn document_part(base: &str, index: u64) -> String {
131 format!("derived:{PART_ROLE}{index}@{base}")
132}
133
134/// The id of the head of the chained record `base`: opening it sends the
135/// chain's newest part, whichever that is, and follows the chain.
136#[must_use]
137pub fn chain_head(base: &str) -> String {
138 format!("derived:{HEAD_ROLE}@{base}")
139}
140
141/// The id of chunk `number` of the split record `base` (`number` from `1`;
142/// chunk `0` is `base`).
143#[must_use]
144pub fn document_chunk(base: &str, number: u64) -> String {
145 format!("derived:{CHUNK_ROLE}{number}@{base}")
146}
147
148/// The id of `base` declared on-demand.
149#[must_use]
150pub fn on_demand_document(base: &str) -> String {
151 format!("derived:{ON_DEMAND_ROLE}@{base}")
152}
153
154#[cfg(test)]
155mod tests {
156 use super::*;
157
158 tilo_test_env::scenario! {
159 fn a_record_declares_how_it_syncs;
160
161 phase a_record_id_declares_how_it_syncs;
162 {
163 assert_eq!(document_sync("general"), DocumentSync::Eager);
164 assert_eq!(
165 document_sync("derived:default@tab:0000000000000000"),
166 DocumentSync::Eager
167 );
168 assert_eq!(
169 document_sync(&on_demand_document("uuid:1")),
170 DocumentSync::OnDemand
171 );
172 assert_eq!(
173 document_sync(&document_part("chat", 12)),
174 DocumentSync::Part {
175 base: "chat",
176 index: 12
177 }
178 );
179 assert_eq!(
180 document_sync(&document_part("", 0)),
181 DocumentSync::Part { base: "", index: 0 }
182 );
183 assert_eq!(
184 document_sync(&chain_head("chat")),
185 DocumentSync::ChainHead { base: "chat" }
186 );
187 // One part, one id: anything else is an ordinary record.
188 for other in [
189 "derived:part.01@chat",
190 "derived:part.@chat",
191 "derived:part.1x@chat",
192 "derived:part.-1@chat",
193 ] {
194 assert_eq!(document_sync(other), DocumentSync::Eager, "{other}");
195 }
196 }
197
198 phase a_chunk_is_a_numbered_record_sent_when_opened;
199 {
200 assert_eq!(
201 document_sync(&document_chunk("general", 3)),
202 DocumentSync::Chunk {
203 base: "general",
204 number: 3
205 }
206 );
207 // Chunk 0 is the record itself, which a join replays like any record.
208 for other in [
209 "general",
210 "derived:chunk.0@general",
211 "derived:chunk.01@general",
212 "derived:chunk.@general",
213 "derived:chunk.1x@general",
214 ] {
215 assert_eq!(document_sync(other), DocumentSync::Eager, "{other}");
216 }
217 }
218 }
219}