1use super::{
3 causal::{CausalPayload, CausalVersion},
4 causal_replica::{CausalReplica, CausalReplicaOptions, CausalSnapshot},
5 cluster::{AtomicJournalStore, JournalVersion},
6};
7use crate::LinkError;
8use serde_json::{json, Value};
9use std::collections::{BTreeMap, BTreeSet};
10
11fn invalid() -> LinkError {
12 LinkError::InvalidFormat("invalid causal batch state".into())
13}
14fn identity(value: &str) -> Result<u128, LinkError> {
15 if value.len() != 32
16 || !value
17 .bytes()
18 .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
19 {
20 return Err(invalid());
21 }
22 u128::from_str_radix(value, 16)
23 .ok()
24 .filter(|v| *v != 0)
25 .ok_or_else(invalid)
26}
27fn number(value: &Value) -> Result<u64, LinkError> {
28 let text = value.as_str().ok_or_else(invalid)?;
29 text.parse::<u64>()
30 .ok()
31 .filter(|v| v.to_string() == text)
32 .ok_or_else(invalid)
33}
34fn raw(value: &CausalVersion) -> Result<Value, LinkError> {
35 serde_json::from_str(&value.encode()?).map_err(|_| invalid())
36}
37fn range(token: u128, count: usize) -> Result<(), LinkError> {
38 token
39 .checked_add(count.saturating_sub(1) as u128)
40 .ok_or_else(invalid)?;
41 Ok(())
42}
43pub(super) fn validate_token(value: &str, count: usize) -> Result<u128, LinkError> {
44 let token = identity(value)?;
45 range(token, count)?;
46 Ok(token)
47}
48#[derive(Clone, Debug)]
49pub struct CausalBatchEdit {
50 pub address: u64,
51 pub observed: Vec<CausalVersion>,
52 pub payload: Option<CausalPayload>,
53}
54#[derive(Clone, Debug, PartialEq, Eq)]
55pub struct CausalBatchSnapshot {
56 pub generation: u64,
57 pub author: String,
58 pub last_counter: u64,
59 pub versions: Vec<CausalVersion>,
60}
61pub(super) fn normalize(edits: &[CausalBatchEdit]) -> Result<Vec<Value>, LinkError> {
62 if edits.len() > 64 {
63 return Err(invalid());
64 }
65 let mut previous = 0;
66 edits
67 .iter()
68 .map(|edit| {
69 if edit.address <= previous || edit.observed.len() > 64 {
70 return Err(invalid());
71 }
72 previous = edit.address;
73 let context = CausalVersion::merge(&edit.observed, &[])?;
74 let dummy = CausalVersion::advance(
75 edit.address,
76 "00000000000000000000000000000001",
77 0,
78 &[],
79 edit.payload.clone(),
80 )?;
81 Ok(json!([
82 edit.address.to_string(),
83 context.iter().map(raw).collect::<Result<Vec<_>, _>>()?,
84 raw(&dummy)?[4]
85 ]))
86 })
87 .collect()
88}
89fn parse_edits(value: &Value, author: &str) -> Result<Vec<CausalBatchEdit>, LinkError> {
90 let edits = value
91 .as_array()
92 .filter(|v| v.len() <= 64)
93 .ok_or_else(invalid)?;
94 edits
95 .iter()
96 .map(|value| {
97 let value = value
98 .as_array()
99 .filter(|v| v.len() == 3)
100 .ok_or_else(invalid)?;
101 let address = number(&value[0])?;
102 let observed = value[1]
103 .as_array()
104 .filter(|v| v.len() <= 64)
105 .ok_or_else(invalid)?
106 .iter()
107 .map(|v| CausalVersion::decode(&v.to_string()))
108 .collect::<Result<Vec<_>, _>>()?;
109 let dummy = CausalVersion::decode(
110 &json!([
111 "causal-version1",
112 value[0],
113 [author, "1"],
114 [[author, "1"]],
115 value[2]
116 ])
117 .to_string(),
118 )?;
119 Ok(CausalBatchEdit {
120 address,
121 observed,
122 payload: dummy.payload,
123 })
124 })
125 .collect()
126}
127struct StagingStore(JournalVersion);
128impl AtomicJournalStore for StagingStore {
129 fn supports_durable_flush(&self) -> bool {
130 true
131 }
132 fn read(&mut self, _: &[String]) -> Result<Vec<JournalVersion>, LinkError> {
133 Ok(vec![self.0.clone()])
134 }
135 fn compare_exchange(
136 &mut self,
137 _: &[String],
138 expected: &[JournalVersion],
139 updates: &[Option<Vec<String>>],
140 ) -> Result<bool, LinkError> {
141 self.0 = JournalVersion {
142 generation: expected[0].generation + 1,
143 entries: updates[0].clone().ok_or_else(invalid)?,
144 };
145 Ok(true)
146 }
147}
148struct Receipt {
149 request: Value,
150 versions: Vec<CausalVersion>,
151}
152struct Loaded {
153 expected: Vec<JournalVersion>,
154 owner: CausalReplica<StagingStore>,
155 snapshot: CausalSnapshot,
156 receipts: BTreeMap<String, Receipt>,
157}
158pub struct CausalBatch<S> {
161 store: S,
162 keys: Vec<String>,
163 author: String,
164 options: CausalReplicaOptions,
165}
166impl<S: AtomicJournalStore> CausalBatch<S> {
167 pub fn new(
168 store: S,
169 owner_key: &str,
170 receipt_key: &str,
171 author: &str,
172 options: CausalReplicaOptions,
173 ) -> Result<Self, LinkError> {
174 let owner = CausalReplica::new(store, owner_key, author, options)?;
175 if receipt_key.is_empty()
176 || receipt_key.len() > 128
177 || receipt_key == owner_key
178 || !receipt_key
179 .bytes()
180 .all(|b| b.is_ascii_alphanumeric() || b"_.-".contains(&b))
181 {
182 return Err(invalid());
183 }
184 Ok(Self {
185 store: owner.into_store(),
186 keys: vec![owner_key.into(), receipt_key.into()],
187 author: author.into(),
188 options,
189 })
190 }
191 pub fn into_store(self) -> S {
192 self.store
193 }
194 fn admit(&self, entries: &[String]) -> Result<(), LinkError> {
195 if entries.len() > self.options.max_entries {
196 return Err(invalid());
197 }
198 let mut bytes = 0usize;
199 for entry in entries {
200 bytes = bytes.checked_add(entry.len()).ok_or_else(invalid)?;
201 if entry.len() > 1_048_576 || bytes > self.options.max_bytes {
202 return Err(invalid());
203 }
204 let (mut depth, mut separators, mut quoted) = (0i32, 0usize, false);
205 for item in entry.bytes() {
206 if !(b' '..=b'~').contains(&item) || item == b'\\' {
207 return Err(invalid());
208 }
209 if item == b'"' {
210 quoted = !quoted;
211 continue;
212 }
213 if quoted {
214 continue;
215 }
216 match item {
217 b'{' | b'}' => return Err(invalid()),
218 b'[' => {
219 depth += 1;
220 if depth > 7 {
221 return Err(invalid());
222 }
223 }
224 b']' => {
225 depth -= 1;
226 if depth < 0 {
227 return Err(invalid());
228 }
229 }
230 b',' => {
231 separators += 1;
232 if separators > 32768 {
233 return Err(invalid());
234 }
235 }
236 _ => {}
237 }
238 }
239 if quoted || depth != 0 {
240 return Err(invalid());
241 }
242 }
243 Ok(())
244 }
245 fn load(&mut self) -> Result<Loaded, LinkError> {
246 let expected = self.store.read(&self.keys)?;
247 if expected.len() != 2 {
248 return Err(invalid());
249 }
250 for value in &expected {
251 self.admit(&value.entries)?;
252 }
253 let staging = StagingStore(JournalVersion {
254 generation: u64::from(expected[0].generation != 0),
255 entries: expected[0].entries.clone(),
256 });
257 let mut owner = CausalReplica::new(staging, &self.keys[0], &self.author, self.options)?;
258 let snapshot = owner.snapshot()?;
259 let mut writes = BTreeMap::new();
260 for text in expected[0].entries.iter().skip(1) {
261 let entry: Value = serde_json::from_str(text).map_err(|_| invalid())?;
262 if entry[0] == "causal-write1" {
263 let value = CausalVersion::decode(&entry[3].to_string())?;
264 let observed = entry[2]
265 .as_array()
266 .ok_or_else(invalid)?
267 .iter()
268 .map(|v| CausalVersion::decode(&v.to_string()))
269 .collect::<Result<Vec<_>, _>>()?;
270 let encoded = normalize(&[CausalBatchEdit {
271 address: value.address,
272 observed,
273 payload: value.payload.clone(),
274 }])?
275 .remove(0);
276 writes.insert(
277 entry[1].as_str().ok_or_else(invalid)?.to_owned(),
278 (encoded, value),
279 );
280 }
281 }
282 let mut receipts = BTreeMap::new();
283 let mut used = BTreeSet::new();
284 let metadata = &expected[1];
285 if metadata.generation == 0 {
286 if !metadata.entries.is_empty() {
287 return Err(invalid());
288 }
289 } else {
290 if expected[0].generation == 0
291 || metadata.entries.first()
292 != Some(&json!(["causal-batches1", self.keys[0], self.author]).to_string())
293 {
294 return Err(invalid());
295 }
296 for text in metadata.entries.iter().skip(1) {
297 let value: Value = serde_json::from_str(text).map_err(|_| invalid())?;
298 let canonical = value.to_string();
299 if canonical != *text {
300 return Err(invalid());
301 }
302 let entry = value
303 .as_array()
304 .filter(|v| v.len() == 5 && v[0] == "causal-batch1")
305 .ok_or_else(invalid)?;
306 let token = entry[1].as_str().ok_or_else(invalid)?;
307 let base = validate_token(token, 0)?;
308 let generation = number(&entry[2])?;
309 let start = number(&entry[3])?;
310 if receipts.contains_key(token) || start > snapshot.last_counter {
311 return Err(invalid());
312 }
313 let edits = parse_edits(&entry[4], &self.author)?;
314 let encoded = normalize(&edits)?;
315 range(base, edits.len())?;
316 if json!(encoded) != entry[4] {
317 return Err(invalid());
318 }
319 let versions = encoded
320 .iter()
321 .enumerate()
322 .map(|(index, edit)| {
323 let child = format!("{:032x}", base + index as u128);
324 let (prior, version) = writes.get(&child).ok_or_else(invalid)?;
325 if !used.insert(child)
326 || version.dot.counter
327 != start.checked_add(index as u64 + 1).ok_or_else(invalid)?
328 || prior != edit
329 {
330 return Err(invalid());
331 }
332 Ok(version.clone())
333 })
334 .collect::<Result<Vec<_>, _>>()?;
335 receipts.insert(
336 token.into(),
337 Receipt {
338 request: json!([generation.to_string(), encoded]),
339 versions,
340 },
341 );
342 }
343 }
344 Ok(Loaded {
345 expected,
346 owner,
347 snapshot,
348 receipts,
349 })
350 }
351 pub fn snapshot(&mut self) -> Result<CausalBatchSnapshot, LinkError> {
352 let loaded = self.load()?;
353 Ok(CausalBatchSnapshot {
354 generation: loaded.expected[0].generation,
355 author: loaded.snapshot.author,
356 last_counter: loaded.snapshot.last_counter,
357 versions: loaded.snapshot.versions,
358 })
359 }
360 pub fn write(
361 &mut self,
362 token: &str,
363 generation: u64,
364 edits: &[CausalBatchEdit],
365 ) -> Result<Vec<CausalVersion>, LinkError> {
366 let base = validate_token(token, 0)?;
367 let encoded = normalize(edits)?;
368 range(base, edits.len())?;
369 let request = json!([generation.to_string(), encoded]);
370 let mut loaded = self.load()?;
371 let receipt = loaded.receipts.get(token);
372 if let Some(receipt) = receipt {
373 if receipt.request != request {
374 return Err(invalid());
375 }
376 } else if loaded.expected[0].generation != generation {
377 return Err(LinkError::Transaction(
378 "conflict: stale causal batch base".into(),
379 ));
380 }
381 let mut result = Vec::with_capacity(edits.len());
382 for (index, edit) in edits.iter().enumerate() {
383 let value = loaded.owner.write(
384 &format!("{:032x}", base + index as u128),
385 edit.address,
386 &edit.observed,
387 edit.payload.clone(),
388 )?;
389 let counter = match receipt {
390 Some(receipt) => receipt.versions[index].dot.counter,
391 None => loaded
392 .snapshot
393 .last_counter
394 .checked_add(index as u64 + 1)
395 .ok_or_else(invalid)?,
396 };
397 if value.dot.counter != counter {
398 return Err(LinkError::InvalidFormat(
399 "causal batch child-token collision".into(),
400 ));
401 }
402 result.push(value);
403 }
404 if receipt.is_some() {
405 return Ok(result);
406 }
407 let mut owner_entries = loaded.owner.into_store().0.entries;
408 if owner_entries.is_empty() {
409 owner_entries.push(json!(["causal-replica1", self.author]).to_string());
410 }
411 let mut entries = loaded.expected[1].entries.clone();
412 if entries.is_empty() {
413 entries.push(json!(["causal-batches1", self.keys[0], self.author]).to_string());
414 }
415 entries.push(
416 json!([
417 "causal-batch1",
418 token,
419 generation.to_string(),
420 loaded.snapshot.last_counter.to_string(),
421 encoded
422 ])
423 .to_string(),
424 );
425 self.admit(&entries)?;
426 match self.store.compare_exchange(&self.keys, &loaded.expected, &[Some(owner_entries), Some(entries)]) {
427 Ok(true) => Ok(result),
428 Ok(false) => Err(LinkError::Transaction("conflict: causal batch state changed".into())),
429 Err(cause) => Err(LinkError::Transaction(format!("indeterminate causal batch publication; reread and retry original request: {cause}"))),
430 }
431 }
432}