Diffinery

homeflare/celldpublic

307 lines · 10.7 KBRaw History
1// Copyright 2026 Deno Land Inc. Apache-2.0 license.
2
3//! Immutable alarm publications and the retirement frontier, without I/O.
4//!
5//! A committed installation owns one key for its entire lifetime. Cleanup
6//! only deletes identities below a proved SQLite frontier, so an unresolved
7//! old DELETE cannot name a later installation. LIST, rather than successful
8//! callbacks, supplies the cleanup inventory after a lost response or restart.
9use super::Ms;
10use std::collections::{BTreeMap, HashMap};
11
12/// A SQLite writer epoch and its persistent, non-repeating alarm sequence.
13/// A publication always belongs to a positive ownership epoch. A listed
14/// migration seed uses zero and is older than every real installation.
15#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
16pub struct PublicationId {
17 pub epoch: u64,
18 pub sequence: u64,
19}
20
21impl std::fmt::Display for PublicationId {
22 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
23 write!(f, "{:016x}-{:016x}", self.epoch, self.sequence)
24 }
25}
26
27impl PublicationId {
28 pub fn parse(value: &str) -> Option<Self> {
29 let (epoch, sequence) = value.split_once('-')?;
30 if epoch.len() != 16 || sequence.len() != 16 {
31 return None;
32 }
33 let id = Self {
34 epoch: u64::from_str_radix(epoch, 16).ok()?,
35 sequence: u64::from_str_radix(sequence, 16).ok()?,
36 };
37 (id.epoch > 0 && id.to_string() == value).then_some(id)
38 }
39}
40
41/// The write position and publication identity sampled from one committed
42/// SQLite connection. A mailbox must carry this value, not sample it again.
43#[derive(Clone, Copy, Debug, PartialEq, Eq)]
44pub struct AlarmSource {
45 pub id: PublicationId,
46 pub position: u64,
47}
48
49#[derive(Clone, Copy, Debug, PartialEq, Eq)]
50pub struct AlarmSnapshot {
51 at_ms: Option<Ms>,
52 source: Option<AlarmSource>,
53}
54
55impl AlarmSnapshot {
56 pub fn without_wake(at_ms: Option<Ms>) -> Self {
57 Self {
58 at_ms,
59 source: None,
60 }
61 }
62
63 pub fn committed(at_ms: Option<Ms>, source: AlarmSource) -> Self {
64 Self {
65 at_ms,
66 source: Some(source),
67 }
68 }
69
70 pub fn at_ms(self) -> Option<Ms> {
71 self.at_ms
72 }
73
74 pub fn source(self) -> Option<AlarmSource> {
75 self.source
76 }
77
78 /// Other SQLite writes can advance a position without installing an alarm.
79 pub fn same_installation(self, other: Self) -> bool {
80 self.at_ms == other.at_ms && self.source.map(|s| s.id) == other.source.map(|s| s.id)
81 }
82}
83
84#[derive(Clone, Debug, PartialEq, Eq)]
85pub struct Publication {
86 pub key: String,
87 pub alarm: AlarmSnapshot,
88}
89
90/// A projection of durable SQLite truth. The executor must prove replication,
91/// ownership, and replacement publication before it writes this certificate.
92/// A stale certificate is conservative: it protects every later identity,
93/// including an installation whose PUT is still in progress.
94#[derive(Clone, Copy, Debug, PartialEq, Eq)]
95pub struct Retirement {
96 pub id: PublicationId,
97 pub at_ms: Option<Ms>,
98}
99
100impl Retirement {
101 pub fn retires(self, candidate: PublicationId) -> bool {
102 candidate < self.id || (candidate == self.id && self.at_ms.is_none())
103 }
104}
105
106/// A bounded cache of confirmed publications. Recent keys allow eager cleanup
107/// even when observations coalesce. LIST remains the complete inventory after
108/// overflow, cancellation, lost responses, or restart; no arm waits for DELETE.
109#[derive(Default)]
110pub struct WakeCore {
111 confirmed: HashMap<String, BTreeMap<PublicationId, AlarmSnapshot>>,
112}
113
114impl WakeCore {
115 pub fn new() -> Self {
116 Self::default()
117 }
118
119 pub fn publication(&self, cell: &str, alarm: AlarmSnapshot) -> Option<Publication> {
120 let due_ms = alarm.at_ms?;
121 let source = alarm.source?;
122 if due_ms < 0 || source.id.epoch == 0 || self.covered(cell, alarm) {
123 return None;
124 }
125 Some(Publication {
126 key: entry_key(due_ms, cell, source.id),
127 alarm,
128 })
129 }
130
131 /// A completion never replaces a newer installation's cache entry.
132 pub fn confirm(&mut self, cell: &str, alarm: AlarmSnapshot) {
133 let Some(source) = alarm.source else { return };
134 if alarm.at_ms.is_some() {
135 // A stalled durability proof must not accumulate an unbounded
136 // queue. Retain the newest identities, including current coverage.
137 const RECENT_PUBLICATIONS: usize = 32;
138 let recent = self.confirmed.entry(cell.to_string()).or_default();
139 recent.insert(source.id, alarm);
140 while recent.len() > RECENT_PUBLICATIONS {
141 recent.pop_first();
142 }
143 }
144 }
145
146 pub fn covered(&self, cell: &str, alarm: AlarmSnapshot) -> bool {
147 alarm.at_ms.is_some()
148 && alarm.source.is_some()
149 && self
150 .confirmed
151 .get(cell)
152 .and_then(|recent| recent.last_key_value())
153 .is_some_and(|(_, confirmed)| confirmed.same_installation(alarm))
154 }
155
156 /// Drain only identities below the proven frontier. Forgetting a candidate
157 /// before its DELETE finishes is safe because the collector can rediscover it.
158 pub fn take_retired(&mut self, cell: &str, retirement: Retirement) -> Vec<String> {
159 let mut keys = Vec::new();
160 if let Some(recent) = self.confirmed.get_mut(cell) {
161 recent.retain(|id, alarm| {
162 if retirement.retires(*id) {
163 keys.push(entry_key(alarm.at_ms.unwrap(), cell, *id));
164 false
165 } else {
166 true
167 }
168 });
169 }
170 keys
171 }
172
173 pub fn forget(&mut self, cell: &str) {
174 self.confirmed.remove(cell);
175 }
176}
177
178/// Civil date from days since 1970-01-01 (Howard Hinnant's algorithm).
179pub(crate) fn civil_from_days(z: i64) -> (i64, u32, u32) {
180 let z = z + 719_468;
181 let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
182 let doe = z - era * 146_097;
183 let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
184 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
185 let mp = (5 * doy + 2) / 153;
186 let d = (doy - (153 * mp + 2) / 5 + 1) as u32;
187 let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
188 (yoe + era * 400 + i64::from(m <= 2), m, d)
189}
190
191/// The time bucket a due timestamp falls in: minute precision, UTC,
192/// lexicographically ordered so the waker LISTs due buckets in order.
193fn minute_bucket(due_ms: i64) -> String {
194 let mins = due_ms.div_euclid(60_000);
195 let (y, mo, d) = civil_from_days(mins.div_euclid(1440));
196 let m = mins.rem_euclid(1440);
197 format!("{y:04}-{mo:02}-{d:02}T{:02}:{:02}", m / 60, m % 60)
198}
199
200fn days_from_civil(y: i64, m: u32, d: u32) -> i64 {
201 let y = y - i64::from(m <= 2);
202 let era = if y >= 0 { y } else { y - 399 } / 400;
203 let yoe = y - era * 400;
204 let mp = i64::from(if m > 2 { m - 3 } else { m + 9 });
205 let doy = (153 * mp + 2) / 5 + i64::from(d) - 1;
206 era * 146_097 + yoe * 365 + yoe / 4 - yoe / 100 + doy - 719_468
207}
208
209/// The due-minute floor a `YYYY-MM-DDTHH:MM` bucket names, in ms.
210fn parse_minute(minute: &str) -> Option<i64> {
211 if minute.len() != 16 {
212 return None;
213 }
214 let y: i64 = minute.get(0..4)?.parse().ok()?;
215 let mo: u32 = minute.get(5..7)?.parse().ok()?;
216 let d: u32 = minute.get(8..10)?.parse().ok()?;
217 let h: i64 = minute.get(11..13)?.parse().ok()?;
218 let mi: i64 = minute.get(14..16)?.parse().ok()?;
219 if minute.get(4..5)? != "-"
220 || minute.get(7..8)? != "-"
221 || minute.get(10..11)? != "T"
222 || minute.get(13..14)? != ":"
223 || !(1..=12).contains(&mo)
224 || !(1..=31).contains(&d)
225 || !(0..24).contains(&h)
226 || !(0..60).contains(&mi)
227 {
228 return None;
229 }
230 let ms = (days_from_civil(y, mo, d) * 1440 + h * 60 + mi) * 60_000;
231 (minute_bucket(ms) == minute).then_some(ms)
232}
233
234pub const ENTRY_PREFIX: &str = "wake/entries/";
235
236pub fn entry_key(due_ms: i64, cell: &str, id: PublicationId) -> String {
237 format!("{ENTRY_PREFIX}{}/{cell}/{id}", minute_bucket(due_ms))
238}
239
240/// An offline inventory hint, never an alarm installation. Its distinct name
241/// cannot collide with a writer or be removed by a legacy minute-key DELETE.
242pub fn migration_seed_key(cell: &str) -> String {
243 format!("{ENTRY_PREFIX}1970-01-01T00:00/{cell}/migration")
244}
245
246#[derive(Debug, Clone, PartialEq, Eq)]
247pub struct ListedEntry {
248 pub minute_ms: i64,
249 pub cell: String,
250 pub id: PublicationId,
251}
252
253/// Reject malformed identities and scopes before they can reach ownership.
254pub fn parse_entry_key(key: &str) -> Option<ListedEntry> {
255 let rest = key.strip_prefix(ENTRY_PREFIX)?;
256 let mut parts = rest.split('/');
257 let minute = parts.next()?;
258 let cell = parts.next()?;
259 let identity = parts.next()?;
260 let id = if identity == "migration" && minute == "1970-01-01T00:00" {
261 PublicationId {
262 epoch: 0,
263 sequence: 0,
264 }
265 } else {
266 PublicationId::parse(identity)?
267 };
268 if parts.next().is_some() || !crate::cell::valid_cell_scope(cell) {
269 return None;
270 }
271 Some(ListedEntry {
272 minute_ms: parse_minute(minute)?,
273 cell: cell.to_string(),
274 id,
275 })
276}
277
278pub fn parse_minute_prefix(prefix: &str) -> Option<i64> {
279 parse_minute(prefix.strip_prefix(ENTRY_PREFIX)?.trim_end_matches('/'))
280}
281
282/// May this node take the singleton waker-role lease — because it already holds
283/// it, or the current holder's lease has expired? An exactly-expired lease MUST
284/// be claimable (`<=`, not `<`): the waker is a SINGLE role, so a claim that
285/// stalls on the boundary leaves every evicted cell's alarm unwoken until
286/// some other node happens to reclaim.
287pub fn waker_may_claim(held_by_us: bool, expires_ms: Ms, now_ms: Ms) -> bool {
288 held_by_us || expires_ms <= now_ms
289}
290
291/// The elected waker's decision for one due entry once it has read the
292/// cell's owner record: does this node need to send the `Fleet` hint?
293///
294/// A live owner fires its own alarms. A resident cell fires from the owner's
295/// timer, and a dormant one wakes from the owner's own due scan, which sends
296/// it an `Owned` hint. The elected waker's hint is for everything else: a
297/// cell nobody owns, a cell whose owner's lease has run out, and a cell this
298/// node owns itself. Hinting a live owner's cell risks nothing (the core never
299/// steals), but it costs the elected node an activation permit and an owner
300/// read per entry, for the whole fleet's due set, every tick.
301pub fn elected_hint_needed(owner: Option<&str>, node: &str, owner_live: bool) -> bool {
302 match owner {
303 None => true,
304 Some(owner) if owner == node => true,
305 Some(_) => !owner_live,
306 }
307}