1use std::collections::{BTreeMap, BTreeSet};
5
6use crate::digest::digest_and_value_len;
7use crate::store::{CollectionRecord, LedgerEntry, LedgerTx};
8use crate::wire::{
9 encoded_delete_bytes, encoded_row_bytes, is_epoch, validate_key, value_within_depth, PullReply,
10 PullRequest, Row, MAX_PART_BYTES, MAX_REPLY_ROW_BYTES, MAX_SAFE_INTEGER, MAX_VALUE_BYTES,
11 VALUE_TOO_DEEP,
12};
13use crate::{Environment, ReplicaError};
14
15#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17pub struct Horizon {
18 pub max_age_ms: u64,
20 pub max_count: u64,
22}
23
24pub const TOMBSTONE_MAX_AGE_MS: u64 = 30 * 24 * 60 * 60 * 1000;
26pub const TOMBSTONE_MAX_COUNT: u64 = 5_000;
28pub const ROTATION_MIN_INTERVAL_MS: u64 = 60_000;
34
35impl Horizon {
36 pub const DEFAULT: Horizon = Horizon {
38 max_age_ms: TOMBSTONE_MAX_AGE_MS,
39 max_count: TOMBSTONE_MAX_COUNT,
40 };
41}
42
43pub(crate) struct Spec<'a> {
45 pub name: &'a str,
46 pub schemas: &'a [u32],
47 pub env: &'a dyn Environment,
48 pub horizon: Horizon,
49}
50
51#[derive(Debug, Clone, PartialEq, Eq)]
53pub struct Head {
54 pub epoch: String,
56 pub version: u64,
58}
59
60impl From<&CollectionRecord> for Head {
61 fn from(record: &CollectionRecord) -> Self {
62 Head {
63 epoch: record.epoch.clone(),
64 version: record.version,
65 }
66 }
67}
68
69pub(crate) fn check_row(row: &Row) -> Result<String, ReplicaError> {
71 let invalid = |reason: String| ReplicaError::InvalidRow {
72 key: row.key.chars().take(64).collect(),
73 reason,
74 };
75 validate_key(&row.key).map_err(invalid)?;
76 if !value_within_depth(&row.value) {
77 return Err(invalid(VALUE_TOO_DEEP.to_string()));
78 }
79 let (digest, value_bytes) = digest_and_value_len(row);
80 if value_bytes > MAX_VALUE_BYTES {
81 return Err(invalid(format!(
82 "value is {value_bytes} bytes encoded; at most {MAX_VALUE_BYTES} are allowed"
83 )));
84 }
85 if row.ord.unsigned_abs() > MAX_SAFE_INTEGER {
86 return Err(invalid("ord must be within ±(2^53 - 1)".to_string()));
87 }
88 if row.part.len() > MAX_PART_BYTES {
89 return Err(invalid(format!(
90 "part is {} bytes; at most {MAX_PART_BYTES} are allowed",
91 row.part.len()
92 )));
93 }
94 Ok(digest)
95}
96
97fn new_epoch(spec: &Spec<'_>, previous: Option<&str>) -> Result<String, ReplicaError> {
98 for _ in 0..4 {
99 let epoch = spec.env.new_epoch();
100 if !is_epoch(&epoch) {
101 return Err(ReplicaError::Store(
102 "the environment produced an epoch outside [a-z0-9]{1,16}".to_string(),
103 ));
104 }
105 if previous != Some(epoch.as_str()) {
106 return Ok(epoch);
107 }
108 }
109 Err(ReplicaError::Store(
110 "the environment keeps producing the current epoch".to_string(),
111 ))
112}
113
114fn assign_version(
119 tx: &mut dyn LedgerTx,
120 spec: &Spec<'_>,
121 record: &mut CollectionRecord,
122) -> Result<u64, ReplicaError> {
123 if record.rotate_owed {
124 rotate_now(tx, spec, record)?;
125 }
126 if record.version >= MAX_SAFE_INTEGER {
127 return Err(ReplicaError::Store(format!(
128 "version of {} would pass 2^53 - 1",
129 record.epoch
130 )));
131 }
132 record.version += 1;
133 Ok(record.version)
134}
135
136pub(crate) fn open(
139 tx: &mut dyn LedgerTx,
140 spec: &Spec<'_>,
141) -> Result<CollectionRecord, ReplicaError> {
142 if let Some(record) = tx.record(spec.name)? {
143 return Ok(record);
144 }
145 let record = CollectionRecord {
146 epoch: new_epoch(spec, None)?,
147 version: 0,
148 floor: 0,
149 dirty: true,
150 rotated_at: spec.env.now_ms(),
151 reconciled_at: 0,
152 rotate_owed: false,
153 };
154 tx.put_record(spec.name, &record)?;
155 Ok(record)
156}
157
158fn rotation_allowed(spec: &Spec<'_>, record: &CollectionRecord) -> bool {
161 let since = spec.env.now_ms().checked_sub(record.rotated_at);
162 record.rotated_at == 0 || since.map_or(true, |since| since >= ROTATION_MIN_INTERVAL_MS)
163}
164
165pub(crate) fn request_rotation(
171 tx: &mut dyn LedgerTx,
172 spec: &Spec<'_>,
173 record: &mut CollectionRecord,
174) -> Result<bool, ReplicaError> {
175 if rotation_allowed(spec, record) {
176 rotate_now(tx, spec, record)?;
177 return Ok(true);
178 }
179 record.rotate_owed = true;
180 Ok(false)
181}
182
183pub(crate) fn begin(
189 tx: &mut dyn LedgerTx,
190 spec: &Spec<'_>,
191 record: &mut CollectionRecord,
192 went_back: bool,
193) -> Result<bool, ReplicaError> {
194 if went_back || (record.rotate_owed && rotation_allowed(spec, record)) {
195 rotate_now(tx, spec, record)?;
196 return Ok(true);
197 }
198 Ok(false)
199}
200
201pub(crate) fn nothing_due(spec: &Spec<'_>, record: &CollectionRecord) -> bool {
204 !(record.rotate_owed && rotation_allowed(spec, record))
205}
206
207pub(crate) fn rotate_now(
220 tx: &mut dyn LedgerTx,
221 spec: &Spec<'_>,
222 record: &mut CollectionRecord,
223) -> Result<(), ReplicaError> {
224 let now = spec.env.now_ms();
225 let mut version = 0;
226 for mut entry in tx.entries(spec.name)? {
227 if entry.deleted {
228 tx.delete_entry(spec.name, &entry.key)?;
229 continue;
230 }
231 version += 1;
232 entry.version = version;
233 entry.changed_at = now;
234 tx.put_entry(spec.name, &entry)?;
235 }
236 record.epoch = new_epoch(spec, Some(&record.epoch))?;
237 record.version = version;
238 record.floor = 0;
239 record.rotated_at = now;
240 record.rotate_owed = false;
241 Ok(())
242}
243
244fn record_row(
246 tx: &mut dyn LedgerTx,
247 spec: &Spec<'_>,
248 record: &mut CollectionRecord,
249 row: &Row,
250 digest: String,
251 now: u64,
252) -> Result<bool, ReplicaError> {
253 if let Some(entry) = tx.entry(spec.name, &row.key)? {
254 if !entry.deleted && entry.digest == digest {
255 return Ok(false);
256 }
257 }
258 let version = assign_version(tx, spec, record)?;
259 tx.put_entry(
260 spec.name,
261 &LedgerEntry {
262 key: row.key.clone(),
263 digest,
264 version,
265 deleted: false,
266 changed_at: now,
267 },
268 )?;
269 Ok(true)
270}
271
272fn record_delete(
274 tx: &mut dyn LedgerTx,
275 spec: &Spec<'_>,
276 record: &mut CollectionRecord,
277 key: &str,
278 now: u64,
279) -> Result<bool, ReplicaError> {
280 let Some(entry) = tx.entry(spec.name, key)? else {
281 return Ok(false);
282 };
283 if entry.deleted {
284 return Ok(false);
285 }
286 let version = assign_version(tx, spec, record)?;
287 tx.put_entry(
288 spec.name,
289 &LedgerEntry {
290 key: key.to_string(),
291 digest: entry.digest,
292 version,
293 deleted: true,
294 changed_at: now,
295 },
296 )?;
297 Ok(true)
298}
299
300fn prune(
304 tx: &mut dyn LedgerTx,
305 spec: &Spec<'_>,
306 record: &mut CollectionRecord,
307 now: u64,
308) -> Result<(), ReplicaError> {
309 let pruned = tx.prune_tombstones(
310 spec.name,
311 now.saturating_sub(spec.horizon.max_age_ms),
312 spec.horizon.max_count,
313 )?;
314 if let Some(highest) = pruned.highest {
315 record.floor = record.floor.max(highest);
316 }
317 if pruned.over_keep {
318 request_rotation(tx, spec, record)?;
319 }
320 Ok(())
321}
322
323pub(crate) fn reconcile(
330 tx: &mut dyn LedgerTx,
331 spec: &Spec<'_>,
332 record: &mut CollectionRecord,
333 rows: &[Row],
334) -> Result<(), ReplicaError> {
335 let now = spec.env.now_ms();
336 let start = record.clone();
337 let mut current: Vec<(&Row, String)> = rows
338 .iter()
339 .map(|row| check_row(row).map(|digest| (row, digest)))
340 .collect::<Result<_, _>>()?;
341 current.sort_unstable_by(|a, b| a.0.key.cmp(&b.0.key));
342 if let Some(pair) = current
343 .windows(2)
344 .find(|pair| pair[0].0.key == pair[1].0.key)
345 {
346 return Err(ReplicaError::InvalidRow {
347 key: pair[0].0.key.chars().take(64).collect(),
348 reason: "the key appears twice in the list".to_string(),
349 });
350 }
351 let ledger = tx.entries(spec.name)?;
353 let mut upserts: Vec<(&Row, &String)> = Vec::new();
354 let mut deletes: Vec<&LedgerEntry> = Vec::new();
355 let mut held = ledger.iter().peekable();
356 for (row, digest) in ¤t {
357 while let Some(entry) = held.next_if(|entry| entry.key < row.key) {
358 if !entry.deleted {
359 deletes.push(entry);
360 }
361 }
362 let unchanged = held
363 .next_if(|entry| entry.key == row.key)
364 .is_some_and(|entry| !entry.deleted && &entry.digest == digest);
365 if !unchanged {
366 upserts.push((row, digest));
367 }
368 }
369 deletes.extend(held.filter(|entry| !entry.deleted));
370 for (row, digest) in upserts {
371 let version = assign_version(tx, spec, record)?;
372 tx.put_entry(
373 spec.name,
374 &LedgerEntry {
375 key: row.key.clone(),
376 digest: digest.clone(),
377 version,
378 deleted: false,
379 changed_at: now,
380 },
381 )?;
382 }
383 for entry in deletes {
384 let version = assign_version(tx, spec, record)?;
385 tx.put_entry(
386 spec.name,
387 &LedgerEntry {
388 key: entry.key.clone(),
389 digest: entry.digest.clone(),
390 version,
391 deleted: true,
392 changed_at: now,
393 },
394 )?;
395 }
396 prune(tx, spec, record, now)?;
397 record.dirty = false;
398 if *record != start {
400 record.reconciled_at = now;
401 }
402 Ok(())
403}
404
405pub(crate) fn touch(
406 tx: &mut dyn LedgerTx,
407 spec: &Spec<'_>,
408 record: &mut CollectionRecord,
409 row: &Row,
410) -> Result<(), ReplicaError> {
411 let digest = check_row(row)?;
412 let now = spec.env.now_ms();
413 record_row(tx, spec, record, row, digest, now)?;
414 prune(tx, spec, record, now)
415}
416
417pub(crate) fn remove(
418 tx: &mut dyn LedgerTx,
419 spec: &Spec<'_>,
420 record: &mut CollectionRecord,
421 key: &str,
422) -> Result<(), ReplicaError> {
423 validate_key(key).map_err(|reason| ReplicaError::InvalidRow {
424 key: key.chars().take(64).collect(),
425 reason,
426 })?;
427 let now = spec.env.now_ms();
428 record_delete(tx, spec, record, key, now)?;
429 prune(tx, spec, record, now)
430}
431
432pub(crate) type Load<'l> = dyn FnMut(Option<&[String]>) -> Result<Vec<Row>, ReplicaError> + 'l;
435
436enum Plan {
438 NothingNew,
439 Changes(Vec<LedgerEntry>),
440 FullCopy {
441 version: u64,
442 entries: Vec<LedgerEntry>,
443 },
444}
445
446fn full_copy(
447 tx: &mut dyn LedgerTx,
448 spec: &Spec<'_>,
449 after: Option<&str>,
450 version: u64,
451 fetch: usize,
452) -> Result<Plan, ReplicaError> {
453 Ok(Plan::FullCopy {
454 version,
455 entries: tx.live_after(spec.name, after, fetch)?,
456 })
457}
458
459fn plan(
460 tx: &mut dyn LedgerTx,
461 spec: &Spec<'_>,
462 record: &mut CollectionRecord,
463 request: &PullRequest,
464) -> Result<Plan, ReplicaError> {
465 let fetch = request.effective_limit() + 1;
467 if request.epoch != record.epoch {
468 return full_copy(tx, spec, None, record.version, fetch);
470 }
471 if request.version > record.version {
472 rotate_now(tx, spec, record)?;
475 return full_copy(tx, spec, None, record.version, fetch);
476 }
477 if let Some(resume) = &request.resume {
478 if request.version >= record.floor {
488 return full_copy(tx, spec, Some(resume), request.version, fetch);
489 }
490 return full_copy(tx, spec, None, record.version, fetch);
491 }
492 if request.version < record.floor {
493 return full_copy(tx, spec, None, record.version, fetch);
495 }
496 if request.version == record.version {
497 return Ok(Plan::NothingNew);
498 }
499 Ok(Plan::Changes(tx.changes_after(
500 spec.name,
501 request.version,
502 fetch,
503 )?))
504}
505
506fn heal(
510 tx: &mut dyn LedgerTx,
511 spec: &Spec<'_>,
512 record: &mut CollectionRecord,
513 wanted: &[LedgerEntry],
514 loaded: &BTreeMap<String, Row>,
515) -> Result<bool, ReplicaError> {
516 let now = spec.env.now_ms();
517 let mut changed = false;
518 for entry in wanted.iter().filter(|entry| !entry.deleted) {
519 match loaded.get(&entry.key) {
520 None => changed |= record_delete(tx, spec, record, &entry.key, now)?,
521 Some(row) => {
522 let digest = check_row(row)?;
523 if digest != entry.digest {
524 changed |= record_row(tx, spec, record, row, digest, now)?;
525 }
526 }
527 }
528 }
529 Ok(changed)
530}
531
532pub(crate) fn check_request(spec: &Spec<'_>, request: &PullRequest) -> Result<(), ReplicaError> {
535 if !spec.schemas.contains(&request.schema) {
536 return Err(ReplicaError::SchemaUnsupported {
537 capability: spec.name.to_string(),
538 schema: request.schema,
539 });
540 }
541 request.validate().map_err(ReplicaError::InvalidRequest)
542}
543
544pub(crate) fn answer(
547 tx: &mut dyn LedgerTx,
548 spec: &Spec<'_>,
549 record: &mut CollectionRecord,
550 request: &PullRequest,
551 load: &mut Load<'_>,
552) -> Result<PullReply, ReplicaError> {
553 check_request(spec, request)?;
554 if record.dirty {
555 let rows = load(None)?;
557 reconcile(tx, spec, record, &rows)?;
558 }
559 let limit = request.effective_limit();
560 let mut whole_copy = false;
561 let mut heals = 0;
562 loop {
563 let plan = if whole_copy {
564 full_copy(tx, spec, None, record.version, limit + 1)?
565 } else {
566 plan(tx, spec, record, request)?
567 };
568 let wanted = match &plan {
569 Plan::NothingNew => {
570 return Ok(PullReply::NothingNew {
571 epoch: record.epoch.clone(),
572 version: record.version,
573 })
574 }
575 Plan::Changes(entries) | Plan::FullCopy { entries, .. } => entries,
576 };
577 let window = &wanted[..wanted.len().min(limit)];
578 let keys: Vec<String> = window
579 .iter()
580 .filter(|entry| !entry.deleted)
581 .map(|entry| entry.key.clone())
582 .collect();
583 let loaded: BTreeMap<String, Row> = if keys.is_empty() {
584 BTreeMap::new()
585 } else {
586 let wanted_keys: BTreeSet<&str> = keys.iter().map(String::as_str).collect();
587 load(Some(&keys))?
588 .into_iter()
589 .filter(|row| wanted_keys.contains(row.key.as_str()))
590 .map(|row| (row.key.clone(), row))
591 .collect()
592 };
593 if heals < 2 && heal(tx, spec, record, window, &loaded)? {
596 heals += 1;
597 continue;
598 }
599 match build(record, request, plan, limit, &loaded) {
600 Some(reply) => return Ok(reply),
601 None if !whole_copy => whole_copy = true,
602 None => {
603 return Err(ReplicaError::Store(
604 "a full copy could not be built".to_string(),
605 ))
606 }
607 }
608 }
609}
610
611fn build(
615 record: &CollectionRecord,
616 request: &PullRequest,
617 plan: Plan,
618 limit: usize,
619 loaded: &BTreeMap<String, Row>,
620) -> Option<PullReply> {
621 match plan {
622 Plan::NothingNew => Some(PullReply::NothingNew {
623 epoch: record.epoch.clone(),
624 version: record.version,
625 }),
626 Plan::Changes(entries) => {
627 let mut taken: Vec<&LedgerEntry> = Vec::new();
628 let mut bytes = 0;
629 let mut more = false;
630 for entry in &entries {
631 if taken.len() == limit {
632 more = true;
633 break;
634 }
635 let size = match (entry.deleted, loaded.get(&entry.key)) {
636 (true, _) => encoded_delete_bytes(&entry.key),
637 (false, Some(row)) => encoded_row_bytes(row),
638 (false, None) => 0,
641 };
642 if !taken.is_empty() && bytes + size > MAX_REPLY_ROW_BYTES {
643 more = true;
644 break;
645 }
646 bytes += size;
647 taken.push(entry);
648 }
649 let version = if more {
650 let exact = taken
658 .iter()
659 .zip(request.version + 1..)
660 .take_while(|(entry, expected)| entry.version == *expected)
661 .count();
662 if exact == 0 {
663 return None;
664 }
665 taken.truncate(exact);
666 request.version + exact as u64
667 } else {
668 record.version
671 };
672 let mut upserts = Vec::new();
673 let mut deletes = Vec::new();
674 for entry in taken {
675 match (entry.deleted, loaded.get(&entry.key)) {
676 (true, _) => deletes.push(entry.key.clone()),
677 (false, Some(row)) => upserts.push(row.clone()),
678 (false, None) => {}
679 }
680 }
681 Some(PullReply::Changes {
682 epoch: record.epoch.clone(),
683 version,
684 upserts,
685 deletes,
686 more,
687 })
688 }
689 Plan::FullCopy { version, entries } => {
690 let mut rows = Vec::new();
691 let mut bytes = 0;
692 let mut last_key: Option<&str> = None;
693 let mut more = false;
694 for (index, entry) in entries.iter().enumerate() {
695 if index == limit {
696 more = true;
697 break;
698 }
699 let Some(row) = loaded.get(&entry.key) else {
700 last_key = Some(&entry.key);
701 continue;
702 };
703 let size = encoded_row_bytes(row);
704 if index > 0 && bytes + size > MAX_REPLY_ROW_BYTES {
705 more = true;
706 break;
707 }
708 rows.push(row.clone());
709 bytes += size;
710 last_key = Some(&entry.key);
711 }
712 Some(PullReply::FullCopy {
713 epoch: record.epoch.clone(),
714 version,
715 rows,
716 next: if more {
717 last_key.map(str::to_string)
718 } else {
719 None
720 },
721 head: (record.version > version).then_some(record.version),
724 })
725 }
726 }
727}