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(
327 tx: &mut dyn LedgerTx,
328 spec: &Spec<'_>,
329 record: &mut CollectionRecord,
330 rows: &[Row],
331) -> Result<(), ReplicaError> {
332 let now = spec.env.now_ms();
333 let mut current: Vec<(&Row, String)> = rows
334 .iter()
335 .map(|row| check_row(row).map(|digest| (row, digest)))
336 .collect::<Result<_, _>>()?;
337 current.sort_unstable_by(|a, b| a.0.key.cmp(&b.0.key));
338 if let Some(pair) = current
339 .windows(2)
340 .find(|pair| pair[0].0.key == pair[1].0.key)
341 {
342 return Err(ReplicaError::InvalidRow {
343 key: pair[0].0.key.chars().take(64).collect(),
344 reason: "the key appears twice in the list".to_string(),
345 });
346 }
347 let ledger = tx.entries(spec.name)?;
349 let mut upserts: Vec<(&Row, &String)> = Vec::new();
350 let mut deletes: Vec<&LedgerEntry> = Vec::new();
351 let mut held = ledger.iter().peekable();
352 for (row, digest) in ¤t {
353 while let Some(entry) = held.next_if(|entry| entry.key < row.key) {
354 if !entry.deleted {
355 deletes.push(entry);
356 }
357 }
358 let unchanged = held
359 .next_if(|entry| entry.key == row.key)
360 .is_some_and(|entry| !entry.deleted && &entry.digest == digest);
361 if !unchanged {
362 upserts.push((row, digest));
363 }
364 }
365 deletes.extend(held.filter(|entry| !entry.deleted));
366 for (row, digest) in upserts {
367 let version = assign_version(tx, spec, record)?;
368 tx.put_entry(
369 spec.name,
370 &LedgerEntry {
371 key: row.key.clone(),
372 digest: digest.clone(),
373 version,
374 deleted: false,
375 changed_at: now,
376 },
377 )?;
378 }
379 for entry in deletes {
380 let version = assign_version(tx, spec, record)?;
381 tx.put_entry(
382 spec.name,
383 &LedgerEntry {
384 key: entry.key.clone(),
385 digest: entry.digest.clone(),
386 version,
387 deleted: true,
388 changed_at: now,
389 },
390 )?;
391 }
392 prune(tx, spec, record, now)?;
393 record.dirty = false;
394 record.reconciled_at = now;
395 Ok(())
396}
397
398pub(crate) fn touch(
399 tx: &mut dyn LedgerTx,
400 spec: &Spec<'_>,
401 record: &mut CollectionRecord,
402 row: &Row,
403) -> Result<(), ReplicaError> {
404 let digest = check_row(row)?;
405 let now = spec.env.now_ms();
406 record_row(tx, spec, record, row, digest, now)?;
407 prune(tx, spec, record, now)
408}
409
410pub(crate) fn remove(
411 tx: &mut dyn LedgerTx,
412 spec: &Spec<'_>,
413 record: &mut CollectionRecord,
414 key: &str,
415) -> Result<(), ReplicaError> {
416 validate_key(key).map_err(|reason| ReplicaError::InvalidRow {
417 key: key.chars().take(64).collect(),
418 reason,
419 })?;
420 let now = spec.env.now_ms();
421 record_delete(tx, spec, record, key, now)?;
422 prune(tx, spec, record, now)
423}
424
425pub(crate) type Load<'l> = dyn FnMut(Option<&[String]>) -> Result<Vec<Row>, ReplicaError> + 'l;
428
429enum Plan {
431 NothingNew,
432 Changes(Vec<LedgerEntry>),
433 FullCopy {
434 version: u64,
435 entries: Vec<LedgerEntry>,
436 },
437}
438
439fn full_copy(
440 tx: &mut dyn LedgerTx,
441 spec: &Spec<'_>,
442 after: Option<&str>,
443 version: u64,
444 fetch: usize,
445) -> Result<Plan, ReplicaError> {
446 Ok(Plan::FullCopy {
447 version,
448 entries: tx.live_after(spec.name, after, fetch)?,
449 })
450}
451
452fn plan(
453 tx: &mut dyn LedgerTx,
454 spec: &Spec<'_>,
455 record: &mut CollectionRecord,
456 request: &PullRequest,
457) -> Result<Plan, ReplicaError> {
458 let fetch = request.effective_limit() + 1;
460 if request.epoch != record.epoch {
461 return full_copy(tx, spec, None, record.version, fetch);
463 }
464 if request.version > record.version {
465 rotate_now(tx, spec, record)?;
468 return full_copy(tx, spec, None, record.version, fetch);
469 }
470 if let Some(resume) = &request.resume {
471 if request.version >= record.floor {
481 return full_copy(tx, spec, Some(resume), request.version, fetch);
482 }
483 return full_copy(tx, spec, None, record.version, fetch);
484 }
485 if request.version < record.floor {
486 return full_copy(tx, spec, None, record.version, fetch);
488 }
489 if request.version == record.version {
490 return Ok(Plan::NothingNew);
491 }
492 Ok(Plan::Changes(tx.changes_after(
493 spec.name,
494 request.version,
495 fetch,
496 )?))
497}
498
499fn heal(
503 tx: &mut dyn LedgerTx,
504 spec: &Spec<'_>,
505 record: &mut CollectionRecord,
506 wanted: &[LedgerEntry],
507 loaded: &BTreeMap<String, Row>,
508) -> Result<bool, ReplicaError> {
509 let now = spec.env.now_ms();
510 let mut changed = false;
511 for entry in wanted.iter().filter(|entry| !entry.deleted) {
512 match loaded.get(&entry.key) {
513 None => changed |= record_delete(tx, spec, record, &entry.key, now)?,
514 Some(row) => {
515 let digest = check_row(row)?;
516 if digest != entry.digest {
517 changed |= record_row(tx, spec, record, row, digest, now)?;
518 }
519 }
520 }
521 }
522 Ok(changed)
523}
524
525pub(crate) fn check_request(spec: &Spec<'_>, request: &PullRequest) -> Result<(), ReplicaError> {
528 if !spec.schemas.contains(&request.schema) {
529 return Err(ReplicaError::SchemaUnsupported {
530 capability: spec.name.to_string(),
531 schema: request.schema,
532 });
533 }
534 request.validate().map_err(ReplicaError::InvalidRequest)
535}
536
537pub(crate) fn answer(
540 tx: &mut dyn LedgerTx,
541 spec: &Spec<'_>,
542 record: &mut CollectionRecord,
543 request: &PullRequest,
544 load: &mut Load<'_>,
545) -> Result<PullReply, ReplicaError> {
546 check_request(spec, request)?;
547 if record.dirty {
548 let rows = load(None)?;
550 reconcile(tx, spec, record, &rows)?;
551 }
552 let limit = request.effective_limit();
553 let mut whole_copy = false;
554 let mut heals = 0;
555 loop {
556 let plan = if whole_copy {
557 full_copy(tx, spec, None, record.version, limit + 1)?
558 } else {
559 plan(tx, spec, record, request)?
560 };
561 let wanted = match &plan {
562 Plan::NothingNew => {
563 return Ok(PullReply::NothingNew {
564 epoch: record.epoch.clone(),
565 version: record.version,
566 })
567 }
568 Plan::Changes(entries) | Plan::FullCopy { entries, .. } => entries,
569 };
570 let window = &wanted[..wanted.len().min(limit)];
571 let keys: Vec<String> = window
572 .iter()
573 .filter(|entry| !entry.deleted)
574 .map(|entry| entry.key.clone())
575 .collect();
576 let loaded: BTreeMap<String, Row> = if keys.is_empty() {
577 BTreeMap::new()
578 } else {
579 let wanted_keys: BTreeSet<&str> = keys.iter().map(String::as_str).collect();
580 load(Some(&keys))?
581 .into_iter()
582 .filter(|row| wanted_keys.contains(row.key.as_str()))
583 .map(|row| (row.key.clone(), row))
584 .collect()
585 };
586 if heals < 2 && heal(tx, spec, record, window, &loaded)? {
589 heals += 1;
590 continue;
591 }
592 match build(record, request, plan, limit, &loaded) {
593 Some(reply) => return Ok(reply),
594 None if !whole_copy => whole_copy = true,
595 None => {
596 return Err(ReplicaError::Store(
597 "a full copy could not be built".to_string(),
598 ))
599 }
600 }
601 }
602}
603
604fn build(
608 record: &CollectionRecord,
609 request: &PullRequest,
610 plan: Plan,
611 limit: usize,
612 loaded: &BTreeMap<String, Row>,
613) -> Option<PullReply> {
614 match plan {
615 Plan::NothingNew => Some(PullReply::NothingNew {
616 epoch: record.epoch.clone(),
617 version: record.version,
618 }),
619 Plan::Changes(entries) => {
620 let mut taken: Vec<&LedgerEntry> = Vec::new();
621 let mut bytes = 0;
622 let mut more = false;
623 for entry in &entries {
624 if taken.len() == limit {
625 more = true;
626 break;
627 }
628 let size = match (entry.deleted, loaded.get(&entry.key)) {
629 (true, _) => encoded_delete_bytes(&entry.key),
630 (false, Some(row)) => encoded_row_bytes(row),
631 (false, None) => 0,
634 };
635 if !taken.is_empty() && bytes + size > MAX_REPLY_ROW_BYTES {
636 more = true;
637 break;
638 }
639 bytes += size;
640 taken.push(entry);
641 }
642 let version = if more {
643 let exact = taken
651 .iter()
652 .zip(request.version + 1..)
653 .take_while(|(entry, expected)| entry.version == *expected)
654 .count();
655 if exact == 0 {
656 return None;
657 }
658 taken.truncate(exact);
659 request.version + exact as u64
660 } else {
661 record.version
664 };
665 let mut upserts = Vec::new();
666 let mut deletes = Vec::new();
667 for entry in taken {
668 match (entry.deleted, loaded.get(&entry.key)) {
669 (true, _) => deletes.push(entry.key.clone()),
670 (false, Some(row)) => upserts.push(row.clone()),
671 (false, None) => {}
672 }
673 }
674 Some(PullReply::Changes {
675 epoch: record.epoch.clone(),
676 version,
677 upserts,
678 deletes,
679 more,
680 })
681 }
682 Plan::FullCopy { version, entries } => {
683 let mut rows = Vec::new();
684 let mut bytes = 0;
685 let mut last_key: Option<&str> = None;
686 let mut more = false;
687 for (index, entry) in entries.iter().enumerate() {
688 if index == limit {
689 more = true;
690 break;
691 }
692 let Some(row) = loaded.get(&entry.key) else {
693 last_key = Some(&entry.key);
694 continue;
695 };
696 let size = encoded_row_bytes(row);
697 if index > 0 && bytes + size > MAX_REPLY_ROW_BYTES {
698 more = true;
699 break;
700 }
701 rows.push(row.clone());
702 bytes += size;
703 last_key = Some(&entry.key);
704 }
705 Some(PullReply::FullCopy {
706 epoch: record.epoch.clone(),
707 version,
708 rows,
709 next: if more {
710 last_key.map(str::to_string)
711 } else {
712 None
713 },
714 head: (record.version > version).then_some(record.version),
717 })
718 }
719 }
720}