1#![warn(missing_docs)]
40
41pub mod digest;
42mod ledger;
43#[cfg(feature = "sqlite")]
44mod sqlite;
45pub mod store;
46pub mod wire;
47
48use std::fmt;
49use std::hash::{BuildHasher, Hasher};
50use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
51use std::sync::{Mutex, PoisonError};
52use std::time::{SystemTime, UNIX_EPOCH};
53
54use serde_json::Value;
55use sha2::{Digest, Sha256};
56
57pub use ledger::{
58 Head, Horizon, ROTATION_MIN_INTERVAL_MS, TOMBSTONE_MAX_AGE_MS, TOMBSTONE_MAX_COUNT,
59};
60pub use store::{CollectionRecord, LedgerEntry, LedgerStore, LedgerTx, MemoryLedger, Pruned};
61pub use wire::{
62 Announce, AnnounceReply, HeadsData, PullReply, PullRequest, PushedHead, Row, SyncAnswer,
63 SyncEntry, SyncErrorCode, SyncReply, SyncRequest, WindowDays, WindowedAnnounce,
64 WindowedPullRequest, WindowedSyncEntry, WindowedSyncRequest,
65};
66
67#[derive(Debug, Clone, PartialEq, Eq)]
70pub enum ReplicaError {
71 Config(String),
73 InvalidRow {
75 key: String,
77 reason: String,
79 },
80 InvalidRequest(String),
82 SchemaUnsupported {
84 capability: String,
86 schema: u32,
88 },
89 Load(String),
91 Store(String),
93}
94
95impl fmt::Display for ReplicaError {
96 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
97 match self {
98 ReplicaError::Config(reason) => write!(f, "replica_config_invalid: {reason}"),
99 ReplicaError::InvalidRow { key, reason } => {
100 write!(f, "replica_row_invalid: row '{key}': {reason}")
101 }
102 ReplicaError::InvalidRequest(reason) => {
103 write!(f, "replica_request_invalid: {reason}")
104 }
105 ReplicaError::SchemaUnsupported { capability, schema } => write!(
106 f,
107 "{} schema {schema} is not served by {capability}",
108 wire::SCHEMA_UNSUPPORTED_PREFIX
109 ),
110 ReplicaError::Load(reason) => write!(f, "replica_load_failed: {reason}"),
111 ReplicaError::Store(reason) => write!(f, "replica_store_failed: {reason}"),
112 }
113 }
114}
115
116impl std::error::Error for ReplicaError {}
117
118pub trait Environment: Sync {
120 fn now_ms(&self) -> u64;
122 fn new_epoch(&self) -> String;
125}
126
127#[derive(Debug, Clone, Copy, Default)]
129pub struct SystemEnvironment;
130
131impl Environment for SystemEnvironment {
132 fn now_ms(&self) -> u64 {
133 SystemTime::now()
134 .duration_since(UNIX_EPOCH)
135 .map(|elapsed| u64::try_from(elapsed.as_millis()).unwrap_or(u64::MAX))
136 .unwrap_or(0)
137 }
138
139 fn new_epoch(&self) -> String {
140 random_epoch()
141 }
142}
143
144fn random_epoch() -> String {
149 static COUNTER: AtomicU64 = AtomicU64::new(0);
150 let mut hasher = std::collections::hash_map::RandomState::new().build_hasher();
151 hasher.write_u64(COUNTER.fetch_add(1, Ordering::Relaxed));
152 let mut sha = Sha256::new();
153 sha.update(hasher.finish().to_le_bytes());
154 sha.update(
155 SystemTime::now()
156 .duration_since(UNIX_EPOCH)
157 .map(|elapsed| elapsed.as_nanos())
158 .unwrap_or(0)
159 .to_le_bytes(),
160 );
161 sha.update(std::process::id().to_le_bytes());
162 let hash = sha.finalize();
163 const ALPHABET: &[u8; 36] = b"abcdefghijklmnopqrstuvwxyz0123456789";
164 hash.iter()
165 .take(8)
166 .map(|byte| char::from(ALPHABET[usize::from(*byte) % ALPHABET.len()]))
167 .collect()
168}
169
170pub trait Announcer {
173 fn invoke(&self, capability: &str, payload: Value) -> Result<Value, String>;
176}
177
178#[derive(Debug, Clone, PartialEq, Eq)]
185pub enum AnnounceOutcome {
186 Accepted(Head),
188 Rotated(Head),
191 RotationDeferred(Head),
195 Failed {
198 error: String,
200 first: bool,
202 },
203}
204
205#[derive(Debug, Clone, PartialEq)]
209pub struct Answered {
210 pub reply: PullReply,
212 pub head_moved: bool,
214}
215
216pub struct Collection {
219 name: &'static str,
220 table_prefix: &'static str,
221 schemas: &'static [u32],
222 env: &'static dyn Environment,
223 horizon: Horizon,
224 announce_failing: AtomicBool,
225 handed_out: Mutex<Vec<(String, u64)>>,
230}
231
232const HANDED_OUT_EPOCHS: usize = 16;
235
236impl fmt::Debug for Collection {
237 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
238 f.debug_struct("Collection")
239 .field("name", &self.name)
240 .field("table_prefix", &self.table_prefix)
241 .field("schemas", &self.schemas)
242 .field("horizon", &self.horizon)
243 .finish()
244 }
245}
246
247impl Collection {
248 pub const fn new(
253 pull_capability: &'static str,
254 table_prefix: &'static str,
255 schemas: &'static [u32],
256 ) -> Self {
257 Self {
258 name: pull_capability,
259 table_prefix,
260 schemas,
261 env: &SystemEnvironment,
262 horizon: Horizon::DEFAULT,
263 announce_failing: AtomicBool::new(false),
264 handed_out: Mutex::new(Vec::new()),
265 }
266 }
267
268 pub const fn with_environment(mut self, env: &'static dyn Environment) -> Self {
270 self.env = env;
271 self
272 }
273
274 pub const fn with_tombstone_horizon(mut self, max_age_ms: u64, max_count: u64) -> Self {
276 self.horizon = Horizon {
277 max_age_ms,
278 max_count,
279 };
280 self
281 }
282
283 pub fn name(&self) -> &'static str {
285 self.name
286 }
287
288 pub fn schemas(&self) -> &'static [u32] {
290 self.schemas
291 }
292
293 fn spec(&self) -> ledger::Spec<'_> {
294 ledger::Spec {
295 name: self.name,
296 schemas: self.schemas,
297 env: self.env,
298 horizon: self.horizon,
299 }
300 }
301
302 fn check(&self) -> Result<(), ReplicaError> {
303 let segments: Vec<&str> = self.name.split('.').collect();
304 let segment_ok = |segment: &&str| {
305 let mut chars = segment.chars();
306 chars.next().is_some_and(|c| c.is_ascii_lowercase())
307 && chars
308 .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-' || c == '_')
309 };
310 if segments.len() < 3
311 || segments.last() != Some(&"pull")
312 || !segments.iter().all(segment_ok)
313 {
314 return Err(ReplicaError::Config(format!(
315 "'{}' is not a pull capability '<app>.<collection>.pull'",
316 self.name
317 )));
318 }
319 if self.name.starts_with("core.") {
320 return Err(ReplicaError::Config(format!(
321 "'{}' is in the reserved 'core.' namespace",
322 self.name
323 )));
324 }
325 if self.table_prefix.len() > 48
328 || self.table_prefix.starts_with(|c: char| c.is_ascii_digit())
329 || !self
330 .table_prefix
331 .bytes()
332 .all(|b| b.is_ascii_alphanumeric() || b == b'_')
333 {
334 return Err(ReplicaError::Config(format!(
335 "table prefix '{}' must be [A-Za-z_][A-Za-z0-9_]{{0,47}} or empty",
336 self.table_prefix
337 )));
338 }
339 if self.horizon.max_count == 0 {
340 return Err(ReplicaError::Config(
341 "the tombstone horizon must keep at least one tombstone".to_string(),
342 ));
343 }
344 Ok(())
345 }
346
347 fn handed_out(&self, epoch: &str) -> Option<u64> {
349 let marks = self
350 .handed_out
351 .lock()
352 .unwrap_or_else(PoisonError::into_inner);
353 marks.iter().find(|(e, _)| e == epoch).map(|(_, v)| *v)
354 }
355
356 fn note_handed_out(&self, epoch: &str, version: u64) {
359 let mut marks = self
360 .handed_out
361 .lock()
362 .unwrap_or_else(PoisonError::into_inner);
363 let mark = match marks.iter().position(|(e, _)| e == epoch) {
364 Some(index) => marks.remove(index).1.max(version),
365 None => version,
366 };
367 marks.insert(0, (epoch.to_string(), mark));
368 marks.truncate(HANDED_OUT_EPOCHS);
369 }
370
371 fn went_back(&self, record: &CollectionRecord) -> bool {
374 self.handed_out(&record.epoch)
375 .is_some_and(|mark| mark > record.version)
376 }
377
378 fn with_record<S, R>(
383 &self,
384 store: &S,
385 mut work: impl FnMut(
386 &mut dyn LedgerTx,
387 &ledger::Spec<'_>,
388 &mut CollectionRecord,
389 bool,
390 ) -> Result<R, ReplicaError>,
391 ) -> Result<R, ReplicaError>
392 where
393 S: LedgerStore + ?Sized,
394 {
395 self.check()?;
396 let spec = self.spec();
397 let mut out = None;
398 store.write(self.table_prefix, &mut |tx| {
399 let mut record = ledger::open(tx, &spec)?;
400 let before = record.clone();
401 let went_back = self.went_back(&record);
402 let rotated = ledger::begin(tx, &spec, &mut record, went_back)?;
403 let result = work(tx, &spec, &mut record, rotated)?;
404 if record != before {
405 tx.put_record(spec.name, &record)?;
406 }
407 out = Some(result);
408 Ok(())
409 })?;
410 out.ok_or_else(|| ReplicaError::Store("the store did not run the ledger work".to_string()))
411 }
412
413 fn read_settled<S: LedgerStore + ?Sized>(
417 &self,
418 store: &S,
419 ) -> Result<Option<CollectionRecord>, ReplicaError> {
420 self.check()?;
421 let record = store.read_record(self.table_prefix, self.name)?;
422 Ok(record
423 .filter(|record| !self.went_back(record) && ledger::nothing_due(&self.spec(), record)))
424 }
425
426 pub fn ensure<S: LedgerStore + ?Sized>(&self, store: &S) -> Result<(), ReplicaError> {
429 self.check()?;
430 store.ensure(self.table_prefix)
431 }
432
433 pub fn reconcile<S: LedgerStore + ?Sized>(
437 &self,
438 store: &S,
439 rows: &[Row],
440 ) -> Result<Option<u64>, ReplicaError> {
441 self.with_record(store, |tx, spec, record, _| {
442 let before = Head::from(&*record);
443 ledger::reconcile(tx, spec, record, rows)?;
444 Ok((Head::from(&*record) != before).then_some(record.version))
445 })
446 }
447
448 pub fn touch<S: LedgerStore + ?Sized>(
450 &self,
451 store: &S,
452 row: &Row,
453 ) -> Result<u64, ReplicaError> {
454 self.with_record(store, |tx, spec, record, _| {
455 ledger::touch(tx, spec, record, row)?;
456 Ok(record.version)
457 })
458 }
459
460 pub fn remove<S: LedgerStore + ?Sized>(
462 &self,
463 store: &S,
464 key: &str,
465 ) -> Result<u64, ReplicaError> {
466 self.with_record(store, |tx, spec, record, _| {
467 ledger::remove(tx, spec, record, key)?;
468 Ok(record.version)
469 })
470 }
471
472 pub fn mark_dirty<S: LedgerStore + ?Sized>(&self, store: &S) -> Result<(), ReplicaError> {
474 self.with_record(store, |_tx, _spec, record, _| {
475 record.dirty = true;
476 Ok(())
477 })
478 }
479
480 pub fn reset<S: LedgerStore + ?Sized>(&self, store: &S) -> Result<bool, ReplicaError> {
490 self.with_record(store, |tx, spec, record, rotated| {
491 let rotated = rotated || ledger::request_rotation(tx, spec, record)?;
492 record.dirty = true;
493 Ok(rotated)
494 })
495 }
496
497 pub fn head<S: LedgerStore + ?Sized>(&self, store: &S) -> Result<Head, ReplicaError> {
501 if let Some(record) = self.read_settled(store)? {
502 return Ok(Head::from(&record));
503 }
504 self.with_record(store, |_tx, _spec, record, _| Ok(Head::from(&*record)))
505 }
506
507 pub fn answer<S, L>(
512 &self,
513 store: &S,
514 request: &PullRequest,
515 mut load: L,
516 ) -> Result<Answered, ReplicaError>
517 where
518 S: LedgerStore + ?Sized,
519 L: FnMut(&S, Option<&[String]>) -> Result<Vec<Row>, String>,
520 {
521 ledger::check_request(&self.spec(), request)?;
522 if request.resume.is_none() {
524 if let Some(record) = self.read_settled(store)? {
525 if !record.dirty
526 && record.epoch == request.epoch
527 && record.version == request.version
528 {
529 self.note_handed_out(&record.epoch, record.version);
530 return Ok(Answered {
531 reply: PullReply::NothingNew {
532 epoch: record.epoch,
533 version: record.version,
534 },
535 head_moved: false,
536 });
537 }
538 }
539 }
540 let (answered, head) = self.with_record(store, |tx, spec, record, rotated| {
541 let before = Head::from(&*record);
542 let mut load_rows =
543 |keys: Option<&[String]>| load(store, keys).map_err(ReplicaError::Load);
544 let reply = ledger::answer(tx, spec, record, request, &mut load_rows)?;
545 let head = Head::from(&*record);
546 Ok((
547 Answered {
548 reply,
549 head_moved: rotated || head != before,
550 },
551 head,
552 ))
553 })?;
554 self.note_handed_out(&head.epoch, head.version);
557 Ok(answered)
558 }
559
560 pub fn pull<S, L>(&self, store: &S, request: &Value, load: L) -> Result<Value, String>
568 where
569 S: LedgerStore + ?Sized,
570 L: FnMut(&S, Option<&[String]>) -> Result<Vec<Row>, String>,
571 {
572 let request: PullRequest = serde_json::from_value(request.clone())
573 .map_err(|error| ReplicaError::InvalidRequest(error.to_string()).to_string())?;
574 let answered = self
575 .answer(store, &request, load)
576 .map_err(|error| error.to_string())?;
577 serde_json::to_value(&answered.reply)
578 .map_err(|error| ReplicaError::Store(error.to_string()).to_string())
579 }
580
581 pub fn announce<S: LedgerStore + ?Sized>(
585 &self,
586 store: &S,
587 bus: &dyn Announcer,
588 ) -> AnnounceOutcome {
589 let outcome = self.announce_inner(store, bus);
590 if outcome.is_ok() {
591 self.announce_failing.store(false, Ordering::Relaxed);
592 }
593 outcome.unwrap_or_else(|error| AnnounceOutcome::Failed {
594 error,
595 first: !self.announce_failing.swap(true, Ordering::Relaxed),
596 })
597 }
598
599 fn announce_inner<S: LedgerStore + ?Sized>(
600 &self,
601 store: &S,
602 bus: &dyn Announcer,
603 ) -> Result<AnnounceOutcome, String> {
604 let head = self.head(store).map_err(|error| error.to_string())?;
605 if send_announce(self.name, &head, bus)? == AnnounceReply::Ok {
606 self.note_handed_out(&head.epoch, head.version);
607 return Ok(AnnounceOutcome::Accepted(head));
608 }
609 self.note_handed_out(&head.epoch, head.version.saturating_add(1));
615 let new_head = self
616 .with_record(store, |tx, spec, record, rotated| {
617 if !rotated && record.epoch == head.epoch {
618 ledger::rotate_now(tx, spec, record)?;
619 }
620 Ok(Head::from(&*record))
621 })
622 .map_err(|error| error.to_string())?;
623 match send_announce(self.name, &new_head, bus)? {
624 AnnounceReply::Ok => {
625 self.note_handed_out(&new_head.epoch, new_head.version);
626 Ok(AnnounceOutcome::Rotated(new_head))
627 }
628 AnnounceReply::Rotate => Ok(AnnounceOutcome::RotationDeferred(new_head)),
631 }
632 }
633
634 pub fn description(&self) -> String {
636 let schemas = self
637 .schemas
638 .iter()
639 .map(u32::to_string)
640 .collect::<Vec<_>>()
641 .join(", ");
642 format!(
643 "Replicated collection served by node-app-replica (Phase 3 contract). Request \
644 {{\"e\":<epoch held, \"\" for none>,\"v\":<version held>,\"s\":<schema>,\"l\":<row limit, \
645 at most 500>,\"a\":<resume key, optional>}}. Reply {{\"e\",\"v\"}} when nothing is new; \
646 {{\"e\",\"v\",\"u\":[[key,value,ord?,part?]...],\"x\":[key...],\"m\":1?}} with the \
647 changes since v; or {{\"e\",\"v\",\"f\":1,\"u\":[...],\"n\":<next key>?}}, a full copy in \
648 key order. Schemas served: {schemas}. Called by the node (core.replica.sync), not by devices."
649 )
650 }
651}
652
653fn send_announce(
654 capability: &str,
655 head: &Head,
656 bus: &dyn Announcer,
657) -> Result<AnnounceReply, String> {
658 let payload = Announce {
659 capability: capability.to_string(),
660 epoch: head.epoch.clone(),
661 version: head.version,
662 };
663 let payload = serde_json::to_value(&payload).map_err(|error| error.to_string())?;
664 let reply = bus.invoke(wire::ANNOUNCE_CAPABILITY, payload)?;
665 serde_json::from_value(reply).map_err(|error| format!("unexpected announce reply: {error}"))
666}