rings_core/dht/entry/retention.rs
1//! Retention and admission of DHT entries.
2//!
3//! State: every entry carries `expires_at_ms : Option<u128>`, the instant after which it must
4//! no longer be served or replicated. The origin stamps it at the operation boundary; every
5//! receiver bounds it at admission. Both bounds are a property of the entry kind: a data topic
6//! is refreshed by its publishers, while a relay inbox must outlive the absence of the peer it
7//! is kept for (see the `inbox` module).
8//!
9//! Laws:
10//! - Stamping: `stamped(now)` maps an absent bound to `now + kind.default_lifetime_ms()` and
11//! preserves a present one, so a forwarded operation keeps the origin's bound.
12//! - Join: the bound of a join is the `max` of the bounds, with `None < Some(_)`. `max` is
13//! idempotent, commutative, and associative, so the product of the payload lattice and the
14//! bound lattice is again a join-semilattice.
15//! - Removal: a tombstone leaves the carrier's bound unchanged. Retention is refreshed by what
16//! is held (adds and overwrites), never by a removal: once the bound elapses, a data carrier
17//! serves no element, and only its remove side stays until it is stable (see Liveness).
18//! - Liveness: `is_live_at(now) ⟺ expires_at_ms = Some(t) ∧ (now < t ∨ now < stable(x))`,
19//! where `stable(x) = max({τ(k)} ∪ {τ(register)}) + H + σ` over the removes and the register
20//! a data carrier holds (see Element horizon), and is absent for a relay inbox. A carrier
21//! that expired with an unstable remove would take the remove with it before its horizon, and
22//! a replica whose carrier other writes keep alive would then serve the removed payload back;
23//! the register counts because an overwrite drops every remove below it. Past `t`, the
24//! projection empties the element side (`retired_at`), so a live-by-`stable` carrier serves
25//! only its removes and register. An unstamped value is not live, so a stored value that
26//! predates retention is retired on its next read.
27//! - Admission: a value is admissible at `now` in overlay `n` iff it is live, its bound is at
28//! most `now + kind.max_lifetime_ms() + TS_OFFSET_TOLERANCE_MS`, every version it carries has
29//! a logical time at most `now + TS_OFFSET_TOLERANCE_MS`, every payload is at most
30//! `ENTRY_PAYLOAD_MAX_BYTES`, and its kind's witness holds (a relay inbox admits only held
31//! messages addressed to its recipient, attested by their holder and verified as of the hold
32//! instant inside `n`; see the `inbox` module). Admission is a predicate on the
33//! peer-supplied delta, never on the receiver's join result, so locally derived versions (an
34//! overwrite floor bumped by one step) are never mistaken for a peer clock running ahead.
35//!
36//! # Element horizon
37//!
38//! The carrier bound joins by `max`, so a data carrier that other writers keep refreshing never
39//! expires, and neither would its elements or its tombstones. A tombstone may be dropped only
40//! once no carrier anywhere can still hold an add it covers as live; otherwise a stale replica
41//! resurrects the add. Acknowledgements cannot establish that (replica sets move with churn,
42//! and fetch caches are carriers that never acknowledge), and a reset floor stamped by one
43//! owner establishes it only by erasing every concurrent add that owner never received (#867).
44//! The stability used here is a clock horizon instead (#872):
45//!
46//! ```text
47//! τ(d) = d.version.logical_time_ms the dot's issue time
48//! H = kind.element_horizon_ms() Data: max_lifetime_ms, no single write asks longer
49//! σ = TS_OFFSET_TOLERANCE_MS assumed bound on pairwise clock skew
50//!
51//! retire_t(x) = x ∖ { add (v, d) | t ≥ τ(d) + H }
52//! ∖ { remove (e, r) | t ≥ τ(r) + H + σ }
53//! ∖ { register F | t ≥ τ(F) + H + σ }
54//!
55//! retired_at(x, t) = retire_t(x) if t < x.expires_at_ms
56//! retire_t(x) with no elements otherwise
57//! ```
58//!
59//! `retired_at` is applied at the local clock `t` on every read of a stored or cached carrier
60//! and to every value written to storage or to the fetch cache. So every data element lives
61//! until the earlier of `τ(d) + H` and its carrier's retention bound, the latest bound any write
62//! it was joined with requested (a plain append requests `default_lifetime_ms`, 10 minutes).
63//! Writing it again issues a fresh dot and a fresh bound: a sole writer must rewrite a value
64//! within the default lifetime, and every writer within `H`, even while other writes keep the
65//! carrier alive.
66//!
67//! Laws, for `t` any node's clock and `x, y` carriers of one data topic:
68//! - Homomorphism: `retire_t(x ⊔ y) = retire_t(x) ⊔ retire_t(y)`. Every filter is a threshold
69//! on `τ`, the leading component of the dot order, so each drops a down-set of dots; `max`
70//! per payload (and on the register) commutes with dropping a down-set; and a dropped remove
71//! or register only ever covered or floored adds that are dropped too (`d ≤ r ⇒ τ(d) ≤ τ(r)`
72//! and `H ≤ H + σ`), so no join pairs a surviving add with a dropped remove or floor that
73//! shadowed it. Retirement therefore commutes with every replication path, and replicas stay
74//! join-compatible. The bound-elapsed step of `retired_at` is carrier-level, like deleting an
75//! expired carrier, and is not a homomorphism; it only narrows that deletion.
76//! - Composition: `retire_t ∘ retire_s = retire_max(s, t)`; in particular `retire_t` is
77//! idempotent.
78//! - No loss: no live add is lost. An add leaves a carrier only by a remove covering it, a user
79//! `Overwrite` register above it, the `max_data_len` cap, its own horizon, its carrier's
80//! retention bound, or storage byte-budget eviction of its element side:
81//! `∀ a. t < τ(a) + H ∧ ¬covered(a) ∧ ¬(a.version < register(⨆ᵢ xᵢ)) ∧ a ∈ ⋃ᵢ xᵢ
82//! ⇒ a ∈ retire_t(⨆ᵢ xᵢ)`, cap aside.
83//! - No resurrection: a remove `(e, r)` or a register leaves the replicas that hold it only at a
84//! clock `t_p ≥ τ(r) + H + σ`, whether by this projection, by an overwrite above it (whose
85//! register then holds the carrier at least as long), or with its carrier (which stays live
86//! while it holds either, see Liveness); an ack-gated hand-off deletes the sender's copy only
87//! once the receiver has joined it, so it moves rather than drops. Every clock then reads
88//! `t_q ≥ t_p − σ ≥ τ(r) + H ≥ τ(d) + H` for every add `d ≤ r` it shadowed, including the
89//! dropping node's own clock should it step back by up to `σ`, so every carrier has already
90//! retired those adds and none can serve them back. Eviction keeps it too: the remove side
91//! lives in a removal store that refuses and never evicts (#920, `chord::carrier_store`), so
92//! the byte budget of the data store drops element sides only.
93//! - Bound (#921): a data carrier holds at most `max_data_len` elements and at most
94//! `DATA_TOMBSTONE_MAX_LEN` unstable removes. The remove bound refuses, it never truncates:
95//! a delta carrying more is inadmissible, and a join or operation whose result would hold
96//! more is refused and changes nothing, since a truncated remove could still cover an add
97//! inside its horizon somewhere. A refusal drops no remove a replica holds, so it keeps No
98//! resurrection; replicas that refuse each other's deltas converge once the union fits. A
99//! sync delta is no stronger than a writer: each of its removes either covers an add a
100//! `Tombstone` could cover, with a dot at most `σ` later, or covers nothing and costs what an
101//! `Extend` and `Tombstone` of a fresh value cost (removal-stability paper, Lemma 4).
102//!
103//! A relay inbox has no dot horizon: it has no reset floor and its tombstones are capped. Its
104//! elements retire by the hold horizon instead: a held message retires `MAX_RELAY_INBOX_TTL_MS`
105//! after its signed hold instant, however long newer holds keep its carrier (#907; see the
106//! `inbox` module).
107//!
108//! Size: the payload predicate is element-intrinsic, so filtering by it commutes with union
109//! and the carrier stays a lattice; together with the count cap `kind.max_data_len()` and the
110//! remove bound it bounds a data carrier at `DATA_CARRIER_WIRE_MAX` encoded bytes. A byte budget
111//! over the whole carrier is deliberately not used: "the newest payloads that fit" depends on
112//! the sizes of payloads a replica may already have dropped, so it is not a lattice morphism
113//! and replicas would diverge.
114
115use bytes::Bytes;
116
117use super::Entry;
118use super::EntryCrdt;
119use super::EntryDot;
120use super::EntryKind;
121use super::EntryOperation;
122use super::EntryVersion;
123use super::TombstoneBound;
124use crate::consts::DEFAULT_RELAY_INBOX_TTL_MS;
125use crate::consts::DEFAULT_TTL_MS;
126use crate::consts::ENTRY_PAYLOAD_MAX_BYTES;
127use crate::consts::MAX_RELAY_INBOX_TTL_MS;
128use crate::consts::MAX_TTL_MS;
129use crate::consts::TS_OFFSET_TOLERANCE_MS;
130use crate::error::Error;
131use crate::error::Result;
132
133impl EntryKind {
134 /// Retention stamped at the operation boundary when the origin left it absent.
135 pub const fn default_lifetime_ms(self) -> u64 {
136 match self {
137 EntryKind::Data => DEFAULT_TTL_MS,
138 EntryKind::RelayMessage => DEFAULT_RELAY_INBOX_TTL_MS,
139 }
140 }
141
142 /// The longest retention a receiver admits for this kind.
143 pub const fn max_lifetime_ms(self) -> u64 {
144 match self {
145 EntryKind::Data => MAX_TTL_MS,
146 EntryKind::RelayMessage => MAX_RELAY_INBOX_TTL_MS,
147 }
148 }
149
150 /// The dot horizon `H`: how long after its dot's issue time an add of this kind may be held
151 /// anywhere, or `None` for a kind whose elements retire otherwise.
152 ///
153 /// A data element lives at most the longest retention one write may request, so writing a
154 /// value again (which issues a fresh dot) is what keeps it. A relay element has no dot
155 /// horizon: it retires by its signed hold instant instead, the hold horizon
156 /// `inbox::RELAY_HOLD_HORIZON_MS`, which a rewrite under a fresh dot cannot extend.
157 pub const fn element_horizon_ms(self) -> Option<u64> {
158 match self {
159 EntryKind::Data => Some(self.max_lifetime_ms()),
160 EntryKind::RelayMessage => None,
161 }
162 }
163}
164
165/// The retention law of a kind with an element horizon: when an add retires, when a remove (and
166/// the register) retires, and what holds an expired carrier live.
167///
168/// The production law is [`ElementRetention::of`]. The horizons are crate-visible so a model can
169/// check a deliberately broken law and witness that it fails.
170#[derive(Clone, Copy, Debug, PartialEq, Eq)]
171pub(crate) struct ElementRetention {
172 /// `H`: an add retires at `τ(d) + H`.
173 pub(crate) add_horizon_ms: u128,
174 /// `H + σ`: a remove, and the register, retire at `τ + H + σ`.
175 pub(crate) remove_horizon_ms: u128,
176}
177
178impl ElementRetention {
179 /// The production law of `kind`, or `None` for a kind without an element horizon.
180 pub(crate) fn of(kind: EntryKind) -> Option<Self> {
181 let horizon_ms = u128::from(kind.element_horizon_ms()?);
182 Some(Self {
183 add_horizon_ms: horizon_ms,
184 remove_horizon_ms: horizon_ms.saturating_add(TS_OFFSET_TOLERANCE_MS),
185 })
186 }
187
188 /// Whether the add `dot` is past the horizon at `now_ms`: `t ≥ τ(d) + H`.
189 fn retires_add(self, dot: &EntryDot, now_ms: u128) -> bool {
190 now_ms
191 >= dot
192 .version
193 .logical_time_ms
194 .saturating_add(self.add_horizon_ms)
195 }
196
197 /// The instant a remove or register at `version` becomes stable, i.e. every add it covers
198 /// or floors is retired on every clock within the skew tolerance: `τ + H + σ`.
199 pub(super) fn stable_at(self, version: &EntryVersion) -> u128 {
200 version
201 .logical_time_ms
202 .saturating_add(self.remove_horizon_ms)
203 }
204
205 /// Whether a remove or register at `version` is stable at `now_ms`: `t ≥ τ + H + σ`.
206 fn retires_remove(self, version: &EntryVersion, now_ms: u128) -> bool {
207 now_ms >= self.stable_at(version)
208 }
209}
210
211/// Whether one element is within the per-element size bound.
212fn payload_within_bound(value: &Bytes) -> bool {
213 value.len() <= ENTRY_PAYLOAD_MAX_BYTES
214}
215
216impl Entry {
217 /// Stamp the retention bound when the origin left it absent.
218 pub(super) fn ensure_lifetime_from(mut self, now_ms: u128) -> Self {
219 if self.expires_at_ms.is_none() {
220 self.expires_at_ms =
221 Some(now_ms.saturating_add(u128::from(self.kind.default_lifetime_ms())));
222 }
223 self
224 }
225
226 /// The retention bound of a join: the later of the two bounds.
227 pub(super) fn joined_lifetime(&self, other: &Self) -> Option<u128> {
228 self.expires_at_ms.max(other.expires_at_ms)
229 }
230
231 /// The element-horizon projection at the local clock `now_ms` (see the module
232 /// documentation): `retire_t`, then, once the retention bound has elapsed, the carrier's
233 /// elements dropped so that only its remove side outlives the bound.
234 ///
235 /// Pre: `self` is normalized ([`Self::try_into_storage_entry`]), as every stored value, join
236 /// result and operation result is; the projection is then a pure filter.
237 /// Post: for a relay carrier, every element past the hold horizon dropped
238 /// (`holds_retired_at`) and nothing else; for a data carrier, normalized, and
239 /// identity, without copying or hashing, when nothing has crossed a threshold. The retention
240 /// bound is unchanged.
241 pub fn retired_at(self, now_ms: u128) -> Self {
242 let retention = ElementRetention::of(self.kind);
243 let entry = self.retired_under(retention, now_ms);
244 match entry.kind {
245 EntryKind::Data => entry,
246 EntryKind::RelayMessage => entry.holds_retired_at(now_ms),
247 }
248 }
249
250 /// What a read serves at `now_ms`: the projection [`Self::retired_at`] when it is live
251 /// ([`Self::is_live_at`]), else `None`.
252 ///
253 /// Pre: `self` is normalized.
254 pub(crate) fn live_at(self, now_ms: u128) -> Option<Self> {
255 let projected = self.retired_at(now_ms);
256 projected.is_live_at(now_ms).then_some(projected)
257 }
258
259 /// [`Self::retired_at`] under the retention law `retention`.
260 pub(super) fn retired_under(self, retention: Option<ElementRetention>, now_ms: u128) -> Self {
261 let Some(retention) = retention else {
262 return self;
263 };
264 let bound_elapsed = !self.bound_live_at(now_ms);
265 let entry = self.horizon_retired_under(retention, now_ms);
266 match bound_elapsed && !entry.data.is_empty() {
267 true => entry.without_elements(),
268 false => entry,
269 }
270 }
271
272 /// This entry with its element side emptied and its remove side, register and bound kept.
273 fn without_elements(self) -> Self {
274 let proofs = self
275 .crdt
276 .proofs
277 .into_iter()
278 .filter(|proof| !proof.key.is_element_add())
279 .collect();
280 Self {
281 data: Vec::new(),
282 crdt: EntryCrdt {
283 dots: Vec::new(),
284 co_dots: Vec::new(),
285 proofs,
286 ..self.crdt
287 },
288 ..self
289 }
290 }
291
292 /// `retire_t` alone under `retention`: every add past `τ + H` and every remove and register
293 /// past `τ + H + σ` is dropped. This is the join homomorphism of the module documentation;
294 /// the bound-elapsed projection of [`Self::retired_at`] is not.
295 ///
296 /// Pre: `self` is normalized. Retiring a remove or the register never uncovers an element,
297 /// since every element either covered is retired first, so the filters need no
298 /// renormalization and compute no digest.
299 pub(super) fn horizon_retired_under(self, retention: ElementRetention, now_ms: u128) -> Self {
300 let retires_add = |dot: &EntryDot| retention.retires_add(dot, now_ms);
301 let retires_remove = |version: &EntryVersion| retention.retires_remove(version, now_ms);
302 let crossed = self.crdt.dots.iter().any(retires_add)
303 || self.crdt.co_dots.iter().any(|(_, dot)| retires_add(dot))
304 || self
305 .crdt
306 .tombstones
307 .iter()
308 .any(|tombstone| retires_remove(&tombstone.dot.version))
309 || self.crdt.register.as_ref().is_some_and(retires_remove)
310 || self.crdt.co_registers.iter().any(retires_remove);
311 if !crossed {
312 return self;
313 }
314 let mut data = Vec::with_capacity(self.data.len());
315 let mut dots = Vec::with_capacity(self.crdt.dots.len());
316 let mut remapped = Vec::with_capacity(self.crdt.dots.len());
317 for (value, dot) in self.data.into_iter().zip(self.crdt.dots) {
318 if retires_add(&dot) {
319 remapped.push(None);
320 } else {
321 remapped.push(u32::try_from(data.len()).ok());
322 data.push(value);
323 dots.push(dot);
324 }
325 }
326 let co_dots = self
327 .crdt
328 .co_dots
329 .into_iter()
330 .filter_map(|(index, dot)| {
331 (!retires_add(&dot))
332 .then(|| {
333 remapped
334 .get(usize::try_from(index).ok()?)
335 .copied()
336 .flatten()
337 })
338 .flatten()
339 .map(|new_index| (new_index, dot))
340 })
341 .collect::<Vec<_>>();
342 let mut surviving_floors = self
343 .crdt
344 .register
345 .into_iter()
346 .chain(self.crdt.co_registers)
347 .filter(|version| !retires_remove(version))
348 .collect::<Vec<_>>();
349 surviving_floors.sort();
350 let register = surviving_floors.pop();
351 let tombstones = self
352 .crdt
353 .tombstones
354 .into_iter()
355 .filter(|tombstone| !retires_remove(&tombstone.dot.version))
356 .collect::<Vec<_>>();
357 let proofs = if self.crdt.proofs.is_empty() {
358 Vec::new()
359 } else {
360 let mut surviving_adds = std::collections::BTreeMap::new();
361 for (index, value) in data.iter().enumerate() {
362 let digest = super::ElementDigest(crate::ecc::keccak256(value.as_ref()));
363 if let Some(dot) = dots.get(index) {
364 if !dot.version.actor.is_default() {
365 surviving_adds.insert((digest, dot.version.actor), *dot);
366 }
367 }
368 for &(co_idx, dot) in &co_dots {
369 if co_idx as usize == index && !dot.version.actor.is_default() {
370 surviving_adds.insert((digest, dot.version.actor), dot);
371 }
372 }
373 }
374 self.crdt
375 .proofs
376 .into_iter()
377 .filter(|proof| match proof.key {
378 super::provenance::DataProofKey::Register(_) => register
379 .into_iter()
380 .chain(surviving_floors.iter().copied())
381 .any(|floor| proof.matches_register(floor)),
382 super::provenance::DataProofKey::Add(digest, actor) => surviving_adds
383 .get(&(digest, actor))
384 .is_some_and(|dot| proof.matches_add(digest, *dot)),
385 super::provenance::DataProofKey::Remove(_, _) => tombstones
386 .iter()
387 .any(|t| proof.matches_remove(t.element, t.dot)),
388 })
389 .collect()
390 };
391 Self {
392 data,
393 crdt: EntryCrdt {
394 register,
395 dots,
396 co_dots,
397 co_registers: surviving_floors,
398 proofs,
399 tombstones,
400 },
401 ..self
402 }
403 }
404
405 /// Whether the retention bound itself has not elapsed at `now_ms`: exactly when this carrier
406 /// answers a lookup as found. A carrier held live past its bound by an unstable remove or
407 /// register serves no element, and answering it as found would shadow a replica that still
408 /// holds data; it answers as absent, and its remove side still spreads by join on hand-off
409 /// and repair.
410 pub(crate) fn bound_live_at(&self, now_ms: u128) -> bool {
411 self.expires_at_ms
412 .is_some_and(|expires_at_ms| now_ms < expires_at_ms)
413 }
414
415 /// Whether this entry may still be served or replicated at `now_ms`: its retention bound
416 /// has not elapsed, or it still holds a remove or register that is not yet stable (see the
417 /// module documentation).
418 ///
419 /// Post: `false` for an unstamped entry, so a legacy stored value without a bound is
420 /// retired on its next read.
421 pub fn is_live_at(&self, now_ms: u128) -> bool {
422 self.is_live_under(ElementRetention::of(self.kind), now_ms)
423 }
424
425 /// [`Self::is_live_at`] under the retention law `retention`.
426 pub(super) fn is_live_under(&self, retention: Option<ElementRetention>, now_ms: u128) -> bool {
427 self.expires_at_ms.is_some()
428 && (self.bound_live_at(now_ms)
429 || retention
430 .and_then(|retention| self.removes_stable_under(retention))
431 .is_some_and(|stable_at_ms| now_ms < stable_at_ms))
432 }
433
434 /// The instant every remove and the register this entry holds are stable,
435 /// `max({τ(k)} ∪ {τ(register)}) + H + σ`, or `None` when it holds neither.
436 ///
437 /// The register counts because an overwrite drops every remove below it: were it not to
438 /// hold the carrier, an overwrite would collapse an unstable remove into a carrier that
439 /// expires at its own bound, and a stale replica could serve the removed payload back.
440 fn removes_stable_under(&self, retention: ElementRetention) -> Option<u128> {
441 self.crdt
442 .tombstones
443 .iter()
444 .map(|tombstone| tombstone.dot.version)
445 .chain(self.crdt.register)
446 .chain(self.crdt.co_registers.iter().copied())
447 .map(|version| retention.stable_at(&version))
448 .max()
449 }
450
451 /// Admission law for a delta supplied by a peer (see the module documentation): the value
452 /// admitted and normalized for storage, as the proof [`AdmittedEntry`].
453 ///
454 /// Pre: `now_ms` is the receiver's clock, `network_id` its overlay, and `self` is the
455 /// peer-supplied value, not a join result.
456 /// Post: `Ok` implies the entry is live, its bound and every version it carries are within
457 /// the receiver's tolerance of `now_ms`, every payload is within the size bound, and the
458 /// kind's witness holds. The version bound keeps a peer-supplied hybrid clock from pinning
459 /// a key: an accepted floor can exceed the receiver's clock only by the message skew
460 /// tolerance, so honest writers issued after that tolerance elapses dominate it again.
461 pub(crate) fn validate_admissible_at(
462 self,
463 now_ms: u128,
464 network_id: u32,
465 ) -> Result<AdmittedEntry> {
466 self.check_admissible_at(now_ms, network_id)?;
467 self.try_into_storage_entry().map(AdmittedEntry)
468 }
469
470 /// The admission law of [`Self::validate_admissible_at`] as a check on a borrowed value,
471 /// for a path that joins the value at once and so needs no proof.
472 pub(crate) fn check_admissible_at(&self, now_ms: u128, network_id: u32) -> Result<()> {
473 self.validate_bounds_at(now_ms)?;
474 match self.kind {
475 EntryKind::Data => self.validate_data_proofs(now_ms, network_id),
476 EntryKind::RelayMessage => self.validate_inbox_witness(now_ms, network_id),
477 }
478 }
479
480 /// The kind-independent part of the admission law: liveness, retention bound, version
481 /// clocks, payload sizes, and the tombstone bound.
482 pub(crate) fn validate_bounds_at(&self, now_ms: u128) -> Result<()> {
483 if !self.is_live_at(now_ms) {
484 return Err(Error::EntryNotLive);
485 }
486 let lifetime_bound = now_ms
487 .saturating_add(u128::from(self.kind.max_lifetime_ms()))
488 .saturating_add(TS_OFFSET_TOLERANCE_MS);
489 if self.expires_at_ms > Some(lifetime_bound) {
490 return Err(Error::EntryLifetimeExceedsMax);
491 }
492 let clock_bound = now_ms.saturating_add(TS_OFFSET_TOLERANCE_MS);
493 if self
494 .versions()
495 .any(|version| version.logical_time_ms > clock_bound)
496 {
497 return Err(Error::EntryVersionAheadOfClock);
498 }
499 if !self.data.iter().all(payload_within_bound) {
500 return Err(Error::EntryPayloadExceedsMax);
501 }
502 self.check_tombstone_bound()
503 }
504
505 /// The tombstone law of a carrier under a refusing bound (#921; removal-stability paper,
506 /// Law 5): `Ok` iff it holds at most the bound's removes. Checked on a peer-supplied delta at
507 /// admission, and on the result of every join and operation before it is stored, so a store
508 /// never holds a data carrier past
509 /// [`DATA_TOMBSTONE_MAX_LEN`](crate::consts::DATA_TOMBSTONE_MAX_LEN) and a refused write changes
510 /// nothing; a truncating bound is enforced by materialization instead.
511 pub(crate) fn check_tombstone_bound(&self) -> Result<()> {
512 let count = self.crdt.tombstones.len();
513 match self.kind.tombstone_bound() {
514 TombstoneBound::Refuse(bound) if count > bound => {
515 Err(Error::EntryTombstonesExceedMax { count, bound })
516 }
517 TombstoneBound::Refuse(_) | TombstoneBound::Truncate(_) => Ok(()),
518 }
519 }
520}
521
522impl EntryOperation {
523 /// Admission law for the delta this operation carries.
524 pub fn validate_admissible_at(&self, now_ms: u128, network_id: u32) -> Result<()> {
525 self.entry().check_admissible_at(now_ms, network_id)
526 }
527}
528
529/// A replicated value that passed the admission law at a receiver's clock and is normalized
530/// for storage ([`Entry::try_into_storage_entry`]): the proof a storage join of a value that
531/// did not come from local storage takes. Constructed only by [`Entry::validate_admissible_at`],
532/// or by [`AdmittedEntry::stored`] for a value this node itself stores.
533#[derive(Clone, Debug, PartialEq, Eq)]
534pub(crate) struct AdmittedEntry(Entry);
535
536impl AdmittedEntry {
537 /// A value read from this node's own storage: admitted when it was written (a peer's value
538 /// through [`Entry::validate_admissible_at`], a local one by the operation that produced it,
539 /// which admission must not judge, as its derived versions may run ahead of the clock) and
540 /// normalized, as every stored value is. Admitted by construction, so it is not judged
541 /// again.
542 ///
543 /// Pre: `entry` was read from this node's storage.
544 pub(crate) fn stored(entry: Entry) -> Self {
545 Self(entry)
546 }
547
548 /// The kind of the admitted value, which names its storage namespace.
549 pub(crate) const fn kind(&self) -> EntryKind {
550 self.0.kind
551 }
552
553 /// The admitted value, owned.
554 pub(crate) fn into_entry(self) -> Entry {
555 self.0
556 }
557}