interplane.Get Omega
Read in your language

synapse

A component of the AienOS ecosystem.

Brought by drakestapleton

branch main Branches Tags History

synapse / crates / synapse-coord / src / board / cursor.rs

722 lines · 27763 bytes Raw Blame History
1//! Subscriptions, cursors, `read_since`, `deliver` and `ack`.
2//!
3//! A tag receives (a) every event addressed to it (`to` lists the tag), found through
4//! `inbox/<tag>.idx` and flagged `addressed`, and (b) every event on a topic or thread it
5//! subscribed to, found through `topics/<topic>.idx` and the thread keys of `journal.idx`.
6//! `to` sets addressing, not visibility: an event addressed to other tags is still seen
7//! (unflagged) by the subscribers of its thread or topic. Nobody receives a thread or topic
8//! they did not follow unless it is addressed to them. A tag never receives its own posts.
9//! Nothing is found by scanning journal bodies.
10//!
11//! The durable cursor `cursors/<tag>.json` holds `acked` (highest id the agent confirmed)
12//! and the advisory `cursors/<tag>.delivered` marker holds the highest id handed out
13//! (written without fsync: losing it only re-delivers). Reading from `acked` after a crash
14//! returns every unprocessed event again (at-least-once, stable ids); reading from
15//! `delivered` returns only what was never handed out.
16//!
17//! Every durable cursor write sets `cursors/<tag>.unsynced` before its rename and removes
18//! it only after the directory sync succeeded (under the tag lock). A delivery that finds
19//! the cursor already there (a retry of a first delivery whose sync failed, or any write a
20//! crash cut before its sync) flushes `cursors/` while that marker is set, before it
21//! reports the batch; with nothing pending it needs no directory sync.
22
23use super::frame::{as_string, as_u64, compact, j_list, key_hash, num_u64, str_list, H_THREAD};
24use super::journal::{
25 create_marker, ensure_dir, fcntl_lock, fsync_dir, inbox_file, read_ids_after, topic_file,
26 FileLock, Snapshot,
27};
28use super::{
29 validate_name, validate_tag, Board, BoardError, Event, Me, MAX_READ_LIMIT, MAX_SUBSCRIPTIONS,
30 PROTOCOL,
31};
32use crate::json::{self, J};
33use std::collections::BTreeMap;
34use std::path::PathBuf;
35use std::sync::Mutex;
36
37const MAX_CURSOR_BYTES: u64 = 4096;
38const MAX_SUBS_BYTES: u64 = 64 * 1024;
39static TAG_LOCKS: Mutex<()> = Mutex::new(());
40
41/// One subscription.
42#[derive(Clone, Debug, PartialEq, Eq)]
43pub enum Sub {
44 Topic(String),
45 Thread(String),
46}
47
48/// A tag's subscriptions.
49#[derive(Clone, Debug, Default, PartialEq, Eq)]
50pub struct Subscriptions {
51 pub topics: Vec<String>,
52 pub threads: Vec<String>,
53}
54
55/// A tag's durable cursor.
56#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
57pub struct Cursor {
58 pub delivered: u64,
59 pub acked: u64,
60 pub expired: bool,
61 /// False when the tag has never read (the cursor then starts at the board's base).
62 pub exists: bool,
63}
64
65/// Where a cursor-driven read starts.
66#[derive(Clone, Copy, Debug, PartialEq, Eq)]
67pub enum Resume {
68 /// After `delivered`: only events never handed out.
69 Delivered,
70 /// After `acked`: everything not yet confirmed (use after a restart).
71 Acked,
72}
73
74/// One event of a batch, with whether it was addressed to the reader.
75#[derive(Clone, Debug, PartialEq, Eq)]
76pub struct Delivered {
77 pub event: Event,
78 pub addressed: bool,
79}
80
81/// A read result. `events` holds addressed events first, then subscribed ones, each in id
82/// order. Every matching id `<= through` is in this batch or an earlier one; the next read
83/// continues after `through`.
84#[derive(Clone, Debug, Default, PartialEq, Eq)]
85pub struct ReadBatch {
86 pub events: Vec<Delivered>,
87 pub after: u64,
88 pub through: u64,
89 pub base: u64,
90 pub last: u64,
91 /// A table entry in flight (a concurrent post) was not read; it is not committed yet.
92 pub torn_entry: Option<u64>,
93 /// True when the batch was cut by `limit`: read again after `through`.
94 pub more: bool,
95}
96
97struct TagLock(#[allow(dead_code)] FileLock);
98
99impl Board {
100 fn tag_lock(&self, tag: &str) -> Result<TagLock, BoardError> {
101 let d = ensure_dir(self.root(), "cursors")?;
102 Ok(TagLock(fcntl_lock(
103 self.root(),
104 &d.join(format!("{tag}.lock")),
105 &TAG_LOCKS,
106 )?))
107 }
108
109 fn cursor_path(&self, tag: &str) -> PathBuf {
110 self.root().join("cursors").join(format!("{tag}.json"))
111 }
112
113 fn subs_path(&self, tag: &str) -> PathBuf {
114 self.root().join("subs").join(format!("{tag}.json"))
115 }
116
117 /// The tag's cursor (a missing file is a fresh cursor, `exists: false`).
118 pub fn cursor(&self, tag: &str) -> Result<Cursor, BoardError> {
119 validate_tag(tag)?;
120 let p = self.cursor_path(tag);
121 crate::record::check_real_parents(self.root(), &p)?;
122 let Some(b) = crate::record::read_bounded(&p, MAX_CURSOR_BYTES)? else {
123 return Ok(Cursor::default());
124 };
125 let bad = |r: &str| BoardError::BadCursor {
126 path: p.clone(),
127 reason: r.into(),
128 };
129 let j = json::parse(&b).ok_or_else(|| bad("not JSON"))?;
130 if as_string(j.get("v")).as_deref() != Some(PROTOCOL)
131 || as_string(j.get("tag")).as_deref() != Some(tag)
132 {
133 return Err(bad("not this tag's aien-board/1 cursor"));
134 }
135 let c = Cursor {
136 delivered: as_u64(j.get("delivered")).ok_or_else(|| bad("delivered is not an id"))?,
137 acked: as_u64(j.get("acked")).ok_or_else(|| bad("acked is not an id"))?,
138 expired: match j.get("expired") {
139 Some(J::True) => true,
140 Some(J::False) => false,
141 _ => return Err(bad("expired is not a boolean")),
142 },
143 exists: true,
144 };
145 if c.acked > c.delivered {
146 return Err(bad("acked is beyond delivered"));
147 }
148 let (_, last) = self.bounds()?;
149 if c.delivered > last {
150 return Err(bad("delivered is beyond the last committed event"));
151 }
152 let mut c = c;
153 if let Some(h) = self.read_delivered_hint(tag, last)? {
154 c.delivered = c.delivered.max(h);
155 }
156 Ok(c)
157 }
158
159 fn delivered_path(&self, tag: &str) -> PathBuf {
160 self.root().join("cursors").join(format!("{tag}.delivered"))
161 }
162
163 /// The advisory `delivered` marker (`cursors/<tag>.delivered`, decimal id). It is written
164 /// without fsync on every delivery: losing it on power loss only re-delivers events
165 /// after `acked` (at least once, as after any crash). Unparseable or out-of-range
166 /// contents are ignored; a planted link or FIFO is refused like every board file.
167 fn read_delivered_hint(&self, tag: &str, last: u64) -> Result<Option<u64>, BoardError> {
168 let p = self.delivered_path(tag);
169 crate::record::check_real_parents(self.root(), &p)?;
170 let Some(b) = crate::record::read_bounded(&p, 64)? else {
171 return Ok(None);
172 };
173 Ok(std::str::from_utf8(&b)
174 .ok()
175 .and_then(|s| s.trim().parse::<u64>().ok())
176 .filter(|h| *h <= last))
177 }
178
179 fn write_delivered_hint(&self, tag: &str, id: u64) -> Result<(), BoardError> {
180 let p = self.delivered_path(tag);
181 crate::record::check_real_parents(self.root(), &p)?;
182 crate::record::check_replaceable(&p)?;
183 let mut tmp = p.as_os_str().to_owned();
184 tmp.push(format!(".tmp{}", std::process::id()));
185 let tmp = PathBuf::from(tmp);
186 let mut f = crate::record::create_temp(&tmp)?;
187 std::io::Write::write_all(&mut f, format!("{id}\n").as_bytes())
188 .map_err(super::io_err(&tmp))?;
189 drop(f);
190 std::fs::rename(&tmp, &p).map_err(super::io_err(&p))?;
191 Ok(())
192 }
193
194 fn write_cursor(&self, tag: &str, c: &Cursor) -> Result<(), BoardError> {
195 let mut o = J::obj();
196 o.set("v", J::str(PROTOCOL));
197 o.set("tag", J::str(tag));
198 o.set("delivered", num_u64(c.delivered));
199 o.set("acked", num_u64(c.acked));
200 o.set("expired", if c.expired { J::True } else { J::False });
201 let mut data = compact(&o);
202 data.push(b'\n');
203 // Mark before the rename, clear after the directory sync (see the module docs): a
204 // failed sync or a crash in between leaves the obligation for the next delivery.
205 let m = self.unsynced_path(tag);
206 crate::record::check_real_parents(self.root(), &m)?;
207 create_marker(&m)?;
208 crate::durable_write(self.root(), &self.cursor_path(tag), &data)?;
209 // Best effort: a leftover marker only costs the next delivery one directory sync.
210 let _ = std::fs::remove_file(&m);
211 Ok(())
212 }
213
214 /// `cursors/<tag>.unsynced`: a durable write of this tag's cursor may have been renamed
215 /// into place without a successful directory sync.
216 fn unsynced_path(&self, tag: &str) -> PathBuf {
217 self.root().join("cursors").join(format!("{tag}.unsynced"))
218 }
219
220 /// Discharge a cursor publication an earlier write left unsynced (caller holds the tag
221 /// lock): flush `cursors/` and drop the marker. A failure (of the flush or of the marker
222 /// lookup itself; only `NotFound` means nothing is owed) is returned, the marker kept.
223 fn flush_unsynced_cursor(&self, tag: &str) -> Result<(), BoardError> {
224 let m = self.unsynced_path(tag);
225 crate::record::check_real_parents(self.root(), &m)?;
226 if !super::journal::marker_present(&m)? {
227 return Ok(());
228 }
229 self.sync_cursor_dir()?;
230 let _ = std::fs::remove_file(&m);
231 Ok(())
232 }
233
234 /// The tag's subscriptions (empty when it never subscribed).
235 pub fn subscriptions_of(&self, tag: &str) -> Result<Subscriptions, BoardError> {
236 validate_tag(tag)?;
237 let p = self.subs_path(tag);
238 crate::record::check_real_parents(self.root(), &p)?;
239 let Some(b) = crate::record::read_bounded(&p, MAX_SUBS_BYTES)? else {
240 return Ok(Subscriptions::default());
241 };
242 let bad = |r: &str| BoardError::Corrupt {
243 path: p.clone(),
244 offset: 0,
245 reason: r.into(),
246 };
247 let j = json::parse(&b).ok_or_else(|| bad("not JSON"))?;
248 if as_string(j.get("v")).as_deref() != Some(PROTOCOL)
249 || as_string(j.get("tag")).as_deref() != Some(tag)
250 {
251 return Err(bad("not this tag's aien-board/1 subscriptions"));
252 }
253 let s = Subscriptions {
254 topics: str_list(j.get("topics")).ok_or_else(|| bad("bad topics"))?,
255 threads: str_list(j.get("threads")).ok_or_else(|| bad("bad threads"))?,
256 };
257 if s.topics.len() + s.threads.len() > MAX_SUBSCRIPTIONS {
258 return Err(BoardError::TooManySubscriptions {
259 limit: MAX_SUBSCRIPTIONS,
260 });
261 }
262 for t in &s.topics {
263 validate_name("topic", t)?;
264 }
265 for t in &s.threads {
266 validate_name("thread", t)?;
267 }
268 Ok(s)
269 }
270
271 fn change_subs(&self, me: &Me, sub: &Sub, add: bool) -> Result<Subscriptions, BoardError> {
272 self.check_binding(me)?;
273 let (field, name) = match sub {
274 Sub::Topic(t) => ("topic", t),
275 Sub::Thread(t) => ("thread", t),
276 };
277 validate_name(field, name)?;
278 let _l = self.tag_lock(&me.tag)?;
279 ensure_dir(self.root(), "subs")?;
280 let mut s = self.subscriptions_of(&me.tag)?;
281 let list = match sub {
282 Sub::Topic(_) => &mut s.topics,
283 Sub::Thread(_) => &mut s.threads,
284 };
285 let had = list.contains(name);
286 if add && !had {
287 list.push(name.clone());
288 } else if !add && had {
289 list.retain(|x| x != name);
290 } else {
291 // Already applied: flush `subs/` before reporting it (see `ack`), since an
292 // earlier change may have been renamed in without a successful sync.
293 fsync_dir(&self.root().join("subs"))?;
294 return Ok(s);
295 }
296 if s.topics.len() + s.threads.len() > MAX_SUBSCRIPTIONS {
297 return Err(BoardError::TooManySubscriptions {
298 limit: MAX_SUBSCRIPTIONS,
299 });
300 }
301 let mut o = J::obj();
302 o.set("v", J::str(PROTOCOL));
303 o.set("tag", J::str(&me.tag));
304 o.set("topics", j_list(&s.topics));
305 o.set("threads", j_list(&s.threads));
306 let mut data = compact(&o);
307 data.push(b'\n');
308 crate::durable_write(self.root(), &self.subs_path(&me.tag), &data)?;
309 Ok(s)
310 }
311
312 /// The subscriptions of the tag this session holds.
313 pub fn subscriptions(&self, session: &str) -> Result<Subscriptions, BoardError> {
314 let me = self.whoami(session)?;
315 self.subscriptions_of(&me.tag)
316 }
317
318 pub fn subscribe(&self, session: &str, sub: &Sub) -> Result<Subscriptions, BoardError> {
319 let me = self.whoami(session)?;
320 self.change_subs(&me, sub, true)
321 }
322
323 pub fn unsubscribe(&self, session: &str, sub: &Sub) -> Result<Subscriptions, BoardError> {
324 let me = self.whoami(session)?;
325 self.change_subs(&me, sub, false)
326 }
327
328 /// Events for `tag` after `after` (at most `limit`): addressed first, then subscribed.
329 /// Pure read: no cursor moves.
330 pub fn read_since(
331 &self,
332 session: &str,
333 after: u64,
334 limit: usize,
335 ) -> Result<ReadBatch, BoardError> {
336 let me = &self.whoami(session)?;
337 let subs = self.subscriptions_of(&me.tag)?;
338 self.read_for(&me.tag, &subs, after, limit, false)
339 }
340
341 /// Only the events addressed to `me` after `after` (an inbox index read). Pure read.
342 pub fn read_mine(
343 &self,
344 session: &str,
345 after: u64,
346 limit: usize,
347 ) -> Result<ReadBatch, BoardError> {
348 let me = &self.whoami(session)?;
349 self.read_for(&me.tag, &Subscriptions::default(), after, limit, true)
350 }
351
352 /// Operator view: unread (after the tag's `acked`) events addressed to `tag`. Needs no
353 /// session and moves nothing.
354 pub fn inbox(&self, tag: &str, limit: usize) -> Result<ReadBatch, BoardError> {
355 validate_tag(tag)?;
356 let after = self.start_after(tag, Resume::Acked)?;
357 self.read_for(tag, &Subscriptions::default(), after, limit, true)
358 }
359
360 /// Operator view (`board read --all`): every event after `after`, ignoring
361 /// subscriptions and audience. Exists for the human CLI only.
362 pub fn read_all(&self, after: Option<u64>, limit: usize) -> Result<ReadBatch, BoardError> {
363 self.with_retry(|| {
364 let snap = Snapshot::take(self)?;
365 let after = check_after(&snap, after.unwrap_or(snap.base.saturating_sub(1)))?;
366 let limit = limit.clamp(1, MAX_READ_LIMIT);
367 let mut b = batch(&snap, after);
368 let mut id = after + 1;
369 while id <= snap.last && b.events.len() < limit {
370 b.events.push(Delivered {
371 event: snap.get(id)?,
372 addressed: false,
373 });
374 id += 1;
375 }
376 b.through = id - 1;
377 b.more = b.through < snap.last;
378 Ok(b)
379 })
380 }
381
382 pub(crate) fn start_after(&self, tag: &str, from: Resume) -> Result<u64, BoardError> {
383 let c = self.cursor(tag)?;
384 let (base, _) = self.bounds()?;
385 if c.expired {
386 return Err(BoardError::CursorExpired {
387 tag: tag.into(),
388 base,
389 });
390 }
391 if !c.exists {
392 return Ok(base.saturating_sub(1));
393 }
394 Ok(match from {
395 Resume::Delivered => c.delivered,
396 Resume::Acked => c.acked,
397 })
398 }
399
400 /// Cursor-driven read: from `delivered` or `acked`, then advance `delivered` to
401 /// `through`. A tag that never read starts at the board's base.
402 pub fn deliver(
403 &self,
404 session: &str,
405 limit: usize,
406 from: Resume,
407 ) -> Result<ReadBatch, BoardError> {
408 let me = &self.whoami(session)?;
409 let after = self.start_after(&me.tag, from)?;
410 let subs = self.subscriptions_of(&me.tag)?;
411 let b = self.read_for(&me.tag, &subs, after, limit, false)?;
412 let _l = self.tag_lock(&me.tag)?;
413 let mut c = self.cursor(&me.tag)?;
414 if c.expired {
415 return Err(BoardError::CursorExpired {
416 tag: me.tag.clone(),
417 base: b.base,
418 });
419 }
420 if !c.exists {
421 // First read: create the durable cursor once.
422 c.acked = after;
423 c.delivered = after;
424 self.write_cursor(&me.tag, &c)?;
425 } else {
426 // Already there, but not necessarily durable: a first delivery (or any cursor
427 // write) may have renamed it into place and then failed, or died before, its
428 // directory sync. Discharge that before reporting the batch.
429 self.flush_unsynced_cursor(&me.tag)?;
430 }
431 if b.through > c.delivered {
432 self.write_delivered_hint(&me.tag, b.through)?;
433 }
434 Ok(b)
435 }
436
437 /// Confirm processing through `id`. Idempotent at or below the cursor (a no-op that
438 /// never moves it backwards); refuses ids beyond the last committed event.
439 pub fn ack(&self, session: &str, id: u64) -> Result<Cursor, BoardError> {
440 let me = &self.whoami(session)?;
441 let (base, last) = self.bounds()?;
442 let _l = self.tag_lock(&me.tag)?;
443 let mut c = self.cursor(&me.tag)?;
444 if c.expired {
445 return Err(BoardError::CursorExpired {
446 tag: me.tag.clone(),
447 base,
448 });
449 }
450 if id > last {
451 return Err(BoardError::AckBeyondCommitted { id, last });
452 }
453 if c.exists && id <= c.acked {
454 // Already applied, but not necessarily durable: an earlier ack may have renamed
455 // this cursor into place and then failed (or died before) the directory sync.
456 // Sync it again before reporting the cursor, so a retry is never a durable
457 // success over a rename a power loss could still undo.
458 self.sync_cursor_dir()?;
459 return Ok(c);
460 }
461 c.acked = id;
462 c.delivered = c.delivered.max(id);
463 c.exists = true;
464 self.write_cursor(&me.tag, &c)?;
465 Ok(c)
466 }
467
468 /// The highest id this session's tag confirmed (the board's `base - 1` when it never
469 /// acked).
470 pub fn acked(&self, session: &str) -> Result<u64, BoardError> {
471 let me = self.whoami(session)?;
472 let c = self.cursor(&me.tag)?;
473 if c.exists {
474 return Ok(c.acked);
475 }
476 let (base, _) = self.bounds()?;
477 Ok(base.saturating_sub(1))
478 }
479
480 /// One event by id, only when it is visible to this session's tag: addressed to it,
481 /// or on a thread or topic it subscribed to, and not its own post. `None` otherwise
482 /// (also for ids compacted away or never committed).
483 pub fn get(&self, session: &str, id: u64) -> Result<Option<Event>, BoardError> {
484 let me = self.whoami(session)?;
485 let subs = self.subscriptions_of(&me.tag)?;
486 self.with_retry(|| {
487 let snap = Snapshot::take(self)?;
488 if id == 0 || id < snap.base || id > snap.last {
489 return Ok(None);
490 }
491 let ev = snap.get(id)?;
492 let visible = ev.from_tag != me.tag
493 && (ev.to.iter().any(|t| t == &me.tag)
494 || subs.topics.contains(&ev.topic)
495 || subs.threads.contains(&ev.thread));
496 Ok(visible.then_some(ev))
497 })
498 }
499
500 /// Accept the gap of an expired cursor: it restarts at the board's base, explicitly.
501 pub fn accept_gap(&self, session: &str) -> Result<Cursor, BoardError> {
502 let me = &self.whoami(session)?;
503 let (base, _) = self.bounds()?;
504 let _l = self.tag_lock(&me.tag)?;
505 let mut c = self.cursor(&me.tag)?;
506 let start = base.saturating_sub(1);
507 c.acked = c.acked.max(start);
508 c.delivered = c.delivered.max(c.acked);
509 c.expired = false;
510 c.exists = true;
511 self.write_cursor(&me.tag, &c)?;
512 Ok(c)
513 }
514
515 /// Every cursor on the board. Compaction decides from this list whether it would drop
516 /// events a reader has not acknowledged, so the enumeration is complete or it fails:
517 /// only an absent `cursors/` directory means "no cursors"; a directory that cannot be
518 /// listed (permission, I/O) or an entry that cannot be read is an error, never an
519 /// empty or shortened list.
520 pub(crate) fn all_cursors(&self) -> Result<Vec<(String, Cursor)>, BoardError> {
521 let dir = self.root().join("cursors");
522 let rd = match std::fs::read_dir(&dir) {
523 Ok(rd) => rd,
524 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
525 Err(e) => return Err(super::io_err(&dir)(e)),
526 };
527 let mut tags: Vec<String> = Vec::new();
528 for ent in rd {
529 let ent = ent.map_err(super::io_err(&dir))?;
530 // Only `<valid tag>.json` is a cursor (`cursor_path`); temp files and foreign
531 // names are not cursors and are skipped.
532 if let Some(t) = ent
533 .file_name()
534 .to_str()
535 .and_then(|n| n.strip_suffix(".json"))
536 .filter(|t| validate_tag(t).is_ok())
537 {
538 tags.push(t.to_string());
539 }
540 }
541 tags.sort();
542 tags.into_iter()
543 .map(|t| self.cursor(&t).map(|c| (t, c)))
544 .collect()
545 }
546
547 pub(crate) fn expire_cursors(&self, tags: &[String]) -> Result<(), BoardError> {
548 for t in tags {
549 let _l = self.tag_lock(t)?;
550 let mut c = self.cursor(t)?;
551 c.expired = true;
552 self.write_cursor(t, &c)?;
553 }
554 Ok(())
555 }
556
557 /// Flush `cursors/` (absent: nothing to flush). Every cursor visible in it is then
558 /// durable, including one an earlier ack, first read or expiration renamed into place
559 /// before its own directory sync failed or the process died.
560 pub(crate) fn sync_cursor_dir(&self) -> Result<(), BoardError> {
561 let d = self.root().join("cursors");
562 match std::fs::symlink_metadata(&d) {
563 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
564 // Present, or a lookup error: the sync itself must succeed (an error is returned).
565 _ => fsync_dir(&d),
566 }
567 }
568
569 fn with_retry<T>(&self, mut f: impl FnMut() -> Result<T, BoardError>) -> Result<T, BoardError> {
570 // First reader of a new kernel boot before any writer: the derived files may have
571 // lost unsynced writes, so rebuild them (under the writer lock) before reading.
572 if super::journal::needs_boot_rebuild(self.root())? {
573 self.recover()?;
574 }
575 let mut tries = 0;
576 loop {
577 match f() {
578 Err(BoardError::IndexMismatch { .. }) if tries < 3 => {
579 tries += 1;
580 std::thread::sleep(std::time::Duration::from_millis(5 << tries));
581 }
582 // Still mismatched after the backoff: no compaction is in flight, one died
583 // between its renames. Run writer recovery (it rebuilds journal.idx from the
584 // journal under the lock and never cuts a committed event), then read again.
585 Err(BoardError::IndexMismatch { .. }) if tries == 3 => {
586 tries += 1;
587 self.recover()?;
588 }
589 r => return r,
590 }
591 }
592 }
593
594 fn read_for(
595 &self,
596 tag: &str,
597 subs: &Subscriptions,
598 after: u64,
599 limit: usize,
600 mine_only: bool,
601 ) -> Result<ReadBatch, BoardError> {
602 self.with_retry(|| self.read_once(tag, subs, after, limit, mine_only))
603 }
604
605 fn read_once(
606 &self,
607 tag: &str,
608 subs: &Subscriptions,
609 after: u64,
610 limit: usize,
611 mine_only: bool,
612 ) -> Result<ReadBatch, BoardError> {
613 let snap = Snapshot::take(self)?;
614 let after = check_after(&snap, after)?;
615 let limit = limit.clamp(1, MAX_READ_LIMIT);
616 let mut b = batch(&snap, after);
617 if snap.last == 0 || after >= snap.last {
618 return Ok(b);
619 }
620 let maxe = self.limits().max_events;
621 // id -> addressed. Each source contributes its lowest `limit` ids above `after`,
622 // so the lowest `limit` of the union are exact.
623 let mut cand: BTreeMap<u64, bool> = BTreeMap::new();
624 let mut cut = false;
625 let (ids, more) =
626 read_ids_after(&inbox_file(self.root(), tag), after, snap.last, limit, maxe)?;
627 cut |= more;
628 for id in ids {
629 cand.insert(id, true);
630 }
631 if !mine_only {
632 for t in &subs.topics {
633 let (ids, more) =
634 read_ids_after(&topic_file(self.root(), t), after, snap.last, limit, maxe)?;
635 cut |= more;
636 for id in ids {
637 cand.entry(id).or_insert(false);
638 }
639 }
640 if !subs.threads.is_empty() {
641 let hs: Vec<u64> = subs
642 .threads
643 .iter()
644 .map(|t| key_hash(H_THREAD, t.as_bytes()))
645 .collect();
646 let mut hits = 0usize;
647 snap.scan(after + 1, |e| {
648 if hs.contains(&e.thread_h) {
649 if hits == limit {
650 cut = true;
651 return Ok(false);
652 }
653 hits += 1;
654 cand.entry(e.id).or_insert(false);
655 }
656 Ok(true)
657 })?;
658 }
659 }
660 let cut = cut || cand.len() > limit;
661 let chosen: Vec<(u64, bool)> = cand.into_iter().take(limit).collect();
662 b.more = cut;
663 b.through = if cut {
664 chosen.last().map(|c| c.0).unwrap_or(after)
665 } else {
666 snap.last
667 };
668 let mut addressed = Vec::new();
669 let mut subscribed = Vec::new();
670 for (id, _) in chosen {
671 let ev = snap.get(id)?;
672 if ev.from_tag == tag {
673 continue;
674 }
675 if ev.to.iter().any(|t| t == tag) {
676 addressed.push(Delivered {
677 event: ev,
678 addressed: true,
679 });
680 } else if !mine_only
681 && (subs.topics.contains(&ev.topic) || subs.threads.contains(&ev.thread))
682 {
683 subscribed.push(Delivered {
684 event: ev,
685 addressed: false,
686 });
687 }
688 // Anything else is a hash collision: not for this reader, and not a gap.
689 }
690 addressed.extend(subscribed);
691 b.events = addressed;
692 Ok(b)
693 }
694}
695
696fn check_after(snap: &Snapshot, after: u64) -> Result<u64, BoardError> {
697 if after > snap.last {
698 return Err(BoardError::CursorAhead {
699 after,
700 last: snap.last,
701 });
702 }
703 if snap.base > 0 && after + 1 < snap.base {
704 return Err(BoardError::Compacted {
705 after,
706 base: snap.base,
707 });
708 }
709 Ok(after)
710}
711
712fn batch(snap: &Snapshot, after: u64) -> ReadBatch {
713 ReadBatch {
714 events: Vec::new(),
715 after,
716 through: after,
717 base: snap.base,
718 last: snap.last,
719 torn_entry: snap.torn_entry,
720 more: false,
721 }
722}