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