#![warn(missing_docs)]
pub mod digest;
mod ledger;
#[cfg(feature = "sqlite")]
mod sqlite;
pub mod store;
pub mod wire;
use std::fmt;
use std::hash::{BuildHasher, Hasher};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Mutex, PoisonError};
use std::time::{SystemTime, UNIX_EPOCH};
use serde_json::Value;
use sha2::{Digest, Sha256};
pub use ledger::{
Head, Horizon, ROTATION_MIN_INTERVAL_MS, TOMBSTONE_MAX_AGE_MS, TOMBSTONE_MAX_COUNT,
};
pub use store::{CollectionRecord, LedgerEntry, LedgerStore, LedgerTx, MemoryLedger, Pruned};
pub use wire::{
Announce, AnnounceReply, HeadsData, PullReply, PullRequest, PushedHead, Row, SyncAnswer,
SyncEntry, SyncErrorCode, SyncReply, SyncRequest, WindowDays, WindowedAnnounce,
WindowedPullRequest, WindowedSyncEntry, WindowedSyncRequest,
};
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ReplicaError {
Config(String),
InvalidRow {
key: String,
reason: String,
},
InvalidRequest(String),
SchemaUnsupported {
capability: String,
schema: u32,
},
Load(String),
Store(String),
}
impl fmt::Display for ReplicaError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ReplicaError::Config(reason) => write!(f, "replica_config_invalid: {reason}"),
ReplicaError::InvalidRow { key, reason } => {
write!(f, "replica_row_invalid: row '{key}': {reason}")
}
ReplicaError::InvalidRequest(reason) => {
write!(f, "replica_request_invalid: {reason}")
}
ReplicaError::SchemaUnsupported { capability, schema } => write!(
f,
"{} schema {schema} is not served by {capability}",
wire::SCHEMA_UNSUPPORTED_PREFIX
),
ReplicaError::Load(reason) => write!(f, "replica_load_failed: {reason}"),
ReplicaError::Store(reason) => write!(f, "replica_store_failed: {reason}"),
}
}
}
impl std::error::Error for ReplicaError {}
pub trait Environment: Sync {
fn now_ms(&self) -> u64;
fn new_epoch(&self) -> String;
}
#[derive(Debug, Clone, Copy, Default)]
pub struct SystemEnvironment;
impl Environment for SystemEnvironment {
fn now_ms(&self) -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|elapsed| u64::try_from(elapsed.as_millis()).unwrap_or(u64::MAX))
.unwrap_or(0)
}
fn new_epoch(&self) -> String {
random_epoch()
}
}
fn random_epoch() -> String {
static COUNTER: AtomicU64 = AtomicU64::new(0);
let mut hasher = std::collections::hash_map::RandomState::new().build_hasher();
hasher.write_u64(COUNTER.fetch_add(1, Ordering::Relaxed));
let mut sha = Sha256::new();
sha.update(hasher.finish().to_le_bytes());
sha.update(
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|elapsed| elapsed.as_nanos())
.unwrap_or(0)
.to_le_bytes(),
);
sha.update(std::process::id().to_le_bytes());
let hash = sha.finalize();
const ALPHABET: &[u8; 36] = b"abcdefghijklmnopqrstuvwxyz0123456789";
hash.iter()
.take(8)
.map(|byte| char::from(ALPHABET[usize::from(*byte) % ALPHABET.len()]))
.collect()
}
pub trait Announcer {
fn invoke(&self, capability: &str, payload: Value) -> Result<Value, String>;
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AnnounceOutcome {
Accepted(Head),
Rotated(Head),
RotationDeferred(Head),
Failed {
error: String,
first: bool,
},
}
#[derive(Debug, Clone, PartialEq)]
pub struct Answered {
pub reply: PullReply,
pub head_moved: bool,
}
pub struct Collection {
name: &'static str,
table_prefix: &'static str,
schemas: &'static [u32],
env: &'static dyn Environment,
horizon: Horizon,
announce_failing: AtomicBool,
handed_out: Mutex<Vec<(String, u64)>>,
}
const HANDED_OUT_EPOCHS: usize = 16;
impl fmt::Debug for Collection {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Collection")
.field("name", &self.name)
.field("table_prefix", &self.table_prefix)
.field("schemas", &self.schemas)
.field("horizon", &self.horizon)
.finish()
}
}
impl Collection {
pub const fn new(
pull_capability: &'static str,
table_prefix: &'static str,
schemas: &'static [u32],
) -> Self {
Self {
name: pull_capability,
table_prefix,
schemas,
env: &SystemEnvironment,
horizon: Horizon::DEFAULT,
announce_failing: AtomicBool::new(false),
handed_out: Mutex::new(Vec::new()),
}
}
pub const fn with_environment(mut self, env: &'static dyn Environment) -> Self {
self.env = env;
self
}
pub const fn with_tombstone_horizon(mut self, max_age_ms: u64, max_count: u64) -> Self {
self.horizon = Horizon {
max_age_ms,
max_count,
};
self
}
pub fn name(&self) -> &'static str {
self.name
}
pub fn schemas(&self) -> &'static [u32] {
self.schemas
}
fn spec(&self) -> ledger::Spec<'_> {
ledger::Spec {
name: self.name,
schemas: self.schemas,
env: self.env,
horizon: self.horizon,
}
}
fn check(&self) -> Result<(), ReplicaError> {
let segments: Vec<&str> = self.name.split('.').collect();
let segment_ok = |segment: &&str| {
let mut chars = segment.chars();
chars.next().is_some_and(|c| c.is_ascii_lowercase())
&& chars
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-' || c == '_')
};
if segments.len() < 3
|| segments.last() != Some(&"pull")
|| !segments.iter().all(segment_ok)
{
return Err(ReplicaError::Config(format!(
"'{}' is not a pull capability '<app>.<collection>.pull'",
self.name
)));
}
if self.name.starts_with("core.") {
return Err(ReplicaError::Config(format!(
"'{}' is in the reserved 'core.' namespace",
self.name
)));
}
if self.table_prefix.len() > 48
|| self.table_prefix.starts_with(|c: char| c.is_ascii_digit())
|| !self
.table_prefix
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b == b'_')
{
return Err(ReplicaError::Config(format!(
"table prefix '{}' must be [A-Za-z_][A-Za-z0-9_]{{0,47}} or empty",
self.table_prefix
)));
}
if self.horizon.max_count == 0 {
return Err(ReplicaError::Config(
"the tombstone horizon must keep at least one tombstone".to_string(),
));
}
Ok(())
}
fn handed_out(&self, epoch: &str) -> Option<u64> {
let marks = self
.handed_out
.lock()
.unwrap_or_else(PoisonError::into_inner);
marks.iter().find(|(e, _)| e == epoch).map(|(_, v)| *v)
}
fn note_handed_out(&self, epoch: &str, version: u64) {
let mut marks = self
.handed_out
.lock()
.unwrap_or_else(PoisonError::into_inner);
let mark = match marks.iter().position(|(e, _)| e == epoch) {
Some(index) => marks.remove(index).1.max(version),
None => version,
};
marks.insert(0, (epoch.to_string(), mark));
marks.truncate(HANDED_OUT_EPOCHS);
}
fn went_back(&self, record: &CollectionRecord) -> bool {
self.handed_out(&record.epoch)
.is_some_and(|mark| mark > record.version)
}
fn with_record<S, R>(
&self,
store: &S,
mut work: impl FnMut(
&mut dyn LedgerTx,
&ledger::Spec<'_>,
&mut CollectionRecord,
bool,
) -> Result<R, ReplicaError>,
) -> Result<R, ReplicaError>
where
S: LedgerStore + ?Sized,
{
self.check()?;
let spec = self.spec();
let mut out = None;
store.write(self.table_prefix, &mut |tx| {
let mut record = ledger::open(tx, &spec)?;
let before = record.clone();
let went_back = self.went_back(&record);
let rotated = ledger::begin(tx, &spec, &mut record, went_back)?;
let result = work(tx, &spec, &mut record, rotated)?;
if record != before {
tx.put_record(spec.name, &record)?;
}
out = Some(result);
Ok(())
})?;
out.ok_or_else(|| ReplicaError::Store("the store did not run the ledger work".to_string()))
}
fn read_settled<S: LedgerStore + ?Sized>(
&self,
store: &S,
) -> Result<Option<CollectionRecord>, ReplicaError> {
self.check()?;
let record = store.read_record(self.table_prefix, self.name)?;
Ok(record
.filter(|record| !self.went_back(record) && ledger::nothing_due(&self.spec(), record)))
}
pub fn ensure<S: LedgerStore + ?Sized>(&self, store: &S) -> Result<(), ReplicaError> {
self.check()?;
store.ensure(self.table_prefix)
}
pub fn reconcile<S: LedgerStore + ?Sized>(
&self,
store: &S,
rows: &[Row],
) -> Result<Option<u64>, ReplicaError> {
self.with_record(store, |tx, spec, record, _| {
let before = Head::from(&*record);
ledger::reconcile(tx, spec, record, rows)?;
Ok((Head::from(&*record) != before).then_some(record.version))
})
}
pub fn touch<S: LedgerStore + ?Sized>(
&self,
store: &S,
row: &Row,
) -> Result<u64, ReplicaError> {
self.with_record(store, |tx, spec, record, _| {
ledger::touch(tx, spec, record, row)?;
Ok(record.version)
})
}
pub fn remove<S: LedgerStore + ?Sized>(
&self,
store: &S,
key: &str,
) -> Result<u64, ReplicaError> {
self.with_record(store, |tx, spec, record, _| {
ledger::remove(tx, spec, record, key)?;
Ok(record.version)
})
}
pub fn mark_dirty<S: LedgerStore + ?Sized>(&self, store: &S) -> Result<(), ReplicaError> {
self.with_record(store, |_tx, _spec, record, _| {
record.dirty = true;
Ok(())
})
}
pub fn reset<S: LedgerStore + ?Sized>(&self, store: &S) -> Result<bool, ReplicaError> {
self.with_record(store, |tx, spec, record, rotated| {
let rotated = rotated || ledger::request_rotation(tx, spec, record)?;
record.dirty = true;
Ok(rotated)
})
}
pub fn head<S: LedgerStore + ?Sized>(&self, store: &S) -> Result<Head, ReplicaError> {
if let Some(record) = self.read_settled(store)? {
return Ok(Head::from(&record));
}
self.with_record(store, |_tx, _spec, record, _| Ok(Head::from(&*record)))
}
pub fn answer<S, L>(
&self,
store: &S,
request: &PullRequest,
mut load: L,
) -> Result<Answered, ReplicaError>
where
S: LedgerStore + ?Sized,
L: FnMut(&S, Option<&[String]>) -> Result<Vec<Row>, String>,
{
ledger::check_request(&self.spec(), request)?;
if request.resume.is_none() {
if let Some(record) = self.read_settled(store)? {
if !record.dirty
&& record.epoch == request.epoch
&& record.version == request.version
{
self.note_handed_out(&record.epoch, record.version);
return Ok(Answered {
reply: PullReply::NothingNew {
epoch: record.epoch,
version: record.version,
},
head_moved: false,
});
}
}
}
let (answered, head) = self.with_record(store, |tx, spec, record, rotated| {
let before = Head::from(&*record);
let mut load_rows =
|keys: Option<&[String]>| load(store, keys).map_err(ReplicaError::Load);
let reply = ledger::answer(tx, spec, record, request, &mut load_rows)?;
let head = Head::from(&*record);
Ok((
Answered {
reply,
head_moved: rotated || head != before,
},
head,
))
})?;
self.note_handed_out(&head.epoch, head.version);
Ok(answered)
}
pub fn pull<S, L>(&self, store: &S, request: &Value, load: L) -> Result<Value, String>
where
S: LedgerStore + ?Sized,
L: FnMut(&S, Option<&[String]>) -> Result<Vec<Row>, String>,
{
let request: PullRequest = serde_json::from_value(request.clone())
.map_err(|error| ReplicaError::InvalidRequest(error.to_string()).to_string())?;
let answered = self
.answer(store, &request, load)
.map_err(|error| error.to_string())?;
serde_json::to_value(&answered.reply)
.map_err(|error| ReplicaError::Store(error.to_string()).to_string())
}
pub fn announce<S: LedgerStore + ?Sized>(
&self,
store: &S,
bus: &dyn Announcer,
) -> AnnounceOutcome {
let outcome = self.announce_inner(store, bus);
if outcome.is_ok() {
self.announce_failing.store(false, Ordering::Relaxed);
}
outcome.unwrap_or_else(|error| AnnounceOutcome::Failed {
error,
first: !self.announce_failing.swap(true, Ordering::Relaxed),
})
}
fn announce_inner<S: LedgerStore + ?Sized>(
&self,
store: &S,
bus: &dyn Announcer,
) -> Result<AnnounceOutcome, String> {
let head = self.head(store).map_err(|error| error.to_string())?;
if send_announce(self.name, &head, bus)? == AnnounceReply::Ok {
self.note_handed_out(&head.epoch, head.version);
return Ok(AnnounceOutcome::Accepted(head));
}
self.note_handed_out(&head.epoch, head.version.saturating_add(1));
let new_head = self
.with_record(store, |tx, spec, record, rotated| {
if !rotated && record.epoch == head.epoch {
ledger::rotate_now(tx, spec, record)?;
}
Ok(Head::from(&*record))
})
.map_err(|error| error.to_string())?;
match send_announce(self.name, &new_head, bus)? {
AnnounceReply::Ok => {
self.note_handed_out(&new_head.epoch, new_head.version);
Ok(AnnounceOutcome::Rotated(new_head))
}
AnnounceReply::Rotate => Ok(AnnounceOutcome::RotationDeferred(new_head)),
}
}
pub fn description(&self) -> String {
let schemas = self
.schemas
.iter()
.map(u32::to_string)
.collect::<Vec<_>>()
.join(", ");
format!(
"Replicated collection served by node-app-replica (Phase 3 contract). Request \
{{\"e\":<epoch held, \"\" for none>,\"v\":<version held>,\"s\":<schema>,\"l\":<row limit, \
at most 500>,\"a\":<resume key, optional>}}. Reply {{\"e\",\"v\"}} when nothing is new; \
{{\"e\",\"v\",\"u\":[[key,value,ord?,part?]...],\"x\":[key...],\"m\":1?}} with the \
changes since v; or {{\"e\",\"v\",\"f\":1,\"u\":[...],\"n\":<next key>?}}, a full copy in \
key order. Schemas served: {schemas}. Called by the node (core.replica.sync), not by devices."
)
}
}
fn send_announce(
capability: &str,
head: &Head,
bus: &dyn Announcer,
) -> Result<AnnounceReply, String> {
let payload = Announce {
capability: capability.to_string(),
epoch: head.epoch.clone(),
version: head.version,
};
let payload = serde_json::to_value(&payload).map_err(|error| error.to_string())?;
let reply = bus.invoke(wire::ANNOUNCE_CAPABILITY, payload)?;
serde_json::from_value(reply).map_err(|error| format!("unexpected announce reply: {error}"))
}