xs/store/mod.rs
1//! The event stream store.
2//!
3//! A [`Store`] is an append-only log of [`Frame`]s persisted to a directory on
4//! disk. Append events with [`Store::append`], replay and follow them with
5//! [`Store::read`], and stash payload bytes in the content-addressed store with
6//! the `cas_*` methods.
7//!
8//! ## Topics
9//!
10//! Every frame has a dot-delimited `topic` (for example `clip.add`). Topics form
11//! a hierarchy: a reader can ask for an exact topic, a prefix wildcard like
12//! `clip.*`, `*` for everything, or a comma-separated list of such patterns
13//! (`game.move.*,game.create`). See [`validate_topic`](crate::store::validate_topic)
14//! for the allowed characters and [`ReadOptions::topic`] for querying.
15//!
16//! ## Retention
17//!
18//! Each frame carries a [`TTL`] that controls how long it is kept: forever, for
19//! a fixed duration, only the last N per topic, or ephemeral (broadcast to live
20//! readers but never stored). A `time:` frame is indexed by its expiry and a
21//! background sweeper removes it within one sweep interval (the default, one
22//! second, is set with [`StoreOptions::ttl_sweep`]). Reads never return an
23//! expired frame, even one the sweeper has not reached yet.
24//!
25//! ## Durability
26//!
27//! Every append commits to the on-disk journal before it returns, so a process
28//! crash loses nothing. Only power loss or a kernel crash can lose the part of
29//! the journal not yet fsynced, and recovery then yields a stable prefix of the
30//! stream. An [`Fsync`] policy, set with [`Store::with_fsync`], decides when
31//! that fsync happens: after every append, on a timer (the default, one
32//! second), or never. [`Store::flush`] fsyncs on demand.
33
34mod fsync;
35pub use fsync::*;
36mod ttl;
37pub use ttl::*;
38
39#[cfg(test)]
40mod tests;
41
42use std::collections::{HashMap, HashSet};
43use std::ops::Bound;
44use std::path::PathBuf;
45use std::time::Duration;
46
47use tokio::sync::broadcast;
48use tokio::sync::mpsc::{self, UnboundedReceiver, UnboundedSender};
49
50use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
51use std::sync::{Arc, Mutex};
52
53use nu_protocol::engine::EngineState;
54use scru128::Scru128Id;
55
56use serde::{Deserialize, Deserializer, Serialize};
57
58use fjall::{
59 config::{BlockSizePolicy, HashRatioPolicy, RestartIntervalPolicy},
60 Database, Error as FjallError, Keyspace, KeyspaceCreateOptions, OwnedWriteBatch, PersistMode,
61};
62
63/// Error returned when opening a [`Store`].
64#[derive(Debug)]
65pub enum StoreError {
66 /// The store directory is already open in another process.
67 Locked,
68 /// An error from the underlying `fjall` database.
69 Other(FjallError),
70}
71
72impl std::fmt::Display for StoreError {
73 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
74 match self {
75 StoreError::Locked => write!(f, "Store is locked by another process"),
76 StoreError::Other(e) => write!(f, "{e}"),
77 }
78 }
79}
80
81impl std::error::Error for StoreError {}
82
83/// A single event in the stream.
84///
85/// A frame is metadata; the payload bytes (if any) live in the content-addressed
86/// store and are referenced by [`hash`](Frame::hash). Build one with the
87/// [`bon`](https://docs.rs/bon) builder, where the topic is the required
88/// starting argument:
89///
90/// ```
91/// use xs::{Frame, TTL};
92///
93/// let frame = Frame::builder("clip.add")
94/// .meta(serde_json::json!({ "source": "keyboard" }))
95/// .ttl(TTL::Last(100))
96/// .build();
97///
98/// assert_eq!(frame.topic, "clip.add");
99/// ```
100///
101/// The [`id`](Frame::id) is assigned by [`Store::append`] at write time, so the
102/// value you set on a builder is ignored when appending.
103#[derive(PartialEq, Eq, Serialize, Deserialize, Clone, Default, bon::Builder)]
104pub struct Frame {
105 /// Dot-delimited topic this frame belongs to (for example `clip.add`).
106 ///
107 /// Must satisfy [`validate_topic`]; [`Store::append`] rejects invalid topics.
108 #[builder(start_fn, into)]
109 pub topic: String,
110 /// Time-sortable identifier. Assigned by [`Store::append`]; any value set
111 /// before appending is overwritten.
112 #[builder(default)]
113 pub id: Scru128Id,
114 /// Integrity hash of the payload in the content-addressed store, if this
115 /// frame has one. Produce it with [`Store::cas_insert`].
116 pub hash: Option<ssri::Integrity>,
117 /// Arbitrary JSON metadata carried inline with the frame.
118 pub meta: Option<serde_json::Value>,
119 /// Retention policy for this frame. Defaults to [`TTL::Forever`] when unset.
120 pub ttl: Option<TTL>,
121}
122
123use std::fmt;
124
125impl fmt::Debug for Frame {
126 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
127 f.debug_struct("Frame")
128 .field("id", &format!("{id}", id = self.id))
129 .field("topic", &self.topic)
130 .field("hash", &self.hash.as_ref().map(|x| format!("{x}")))
131 .field("meta", &self.meta)
132 .field("ttl", &self.ttl)
133 .finish()
134 }
135}
136
137impl<'de> Deserialize<'de> for FollowOption {
138 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
139 where
140 D: Deserializer<'de>,
141 {
142 let s: String = Deserialize::deserialize(deserializer)?;
143 if s.is_empty() || s == "yes" {
144 Ok(FollowOption::On)
145 } else if let Ok(duration) = s.parse::<u64>() {
146 Ok(FollowOption::WithHeartbeat(Duration::from_millis(duration)))
147 } else {
148 match s.as_str() {
149 "true" => Ok(FollowOption::On),
150 "false" | "no" => Ok(FollowOption::Off),
151 _ => Err(serde::de::Error::custom("Invalid value for follow option")),
152 }
153 }
154 }
155}
156
157fn deserialize_bool<'de, D>(deserializer: D) -> Result<bool, D::Error>
158where
159 D: Deserializer<'de>,
160{
161 let s: String = Deserialize::deserialize(deserializer)?;
162 match s.as_str() {
163 "false" | "no" | "0" => Ok(false),
164 _ => Ok(true),
165 }
166}
167
168/// Options controlling a [`Store::read`] or [`Store::read_sync`] call.
169///
170/// Defaults replay every stored frame once, oldest first, then stop. Build a
171/// query with the [`bon`](https://docs.rs/bon) builder:
172///
173/// ```
174/// use xs::{ReadOptions, FollowOption};
175///
176/// // Replay history for one topic, then keep streaming new appends.
177/// let opts = ReadOptions::builder()
178/// .topic("clip.*".to_string())
179/// .follow(FollowOption::On)
180/// .build();
181/// ```
182#[derive(PartialEq, Deserialize, Clone, Debug, Default, bon::Builder)]
183pub struct ReadOptions {
184 /// Whether to keep streaming live appends after history is replayed.
185 /// Defaults to [`FollowOption::Off`].
186 #[serde(default)]
187 #[builder(default)]
188 pub follow: FollowOption,
189 /// Skip historical frames and emit only appends made after the read starts.
190 #[serde(default, deserialize_with = "deserialize_bool")]
191 #[builder(default)]
192 pub new: bool,
193 /// Start after this ID (exclusive).
194 #[serde(rename = "after")]
195 pub after: Option<Scru128Id>,
196 /// Start from this ID (inclusive).
197 pub from: Option<Scru128Id>,
198 /// Stop after emitting this many historical frames.
199 pub limit: Option<usize>,
200 /// Return the last N frames (most recent), in chronological order.
201 pub last: Option<usize>,
202 /// Restrict to one or more topic patterns, comma-separated. Each pattern
203 /// is an exact name, a `prefix.*` wildcard, or `*` for all, e.g.
204 /// `clip.add` or `game.move.*,game.create`. Commas are a safe separator
205 /// because [`validate_topic`] forbids them in topic names.
206 pub topic: Option<String>,
207}
208
209/// A single topic pattern: an exact topic name or a `prefix.*` wildcard.
210#[derive(Clone, Debug, PartialEq)]
211pub enum Pattern {
212 /// Matches the topic exactly.
213 Exact(String),
214 /// Matches any topic starting with this prefix. Stored with the trailing
215 /// dot, so `a.*` becomes `Prefix("a.")` and matches `a.b` but not `a`.
216 Prefix(String),
217}
218
219impl Pattern {
220 fn matches(&self, topic: &str) -> bool {
221 match self {
222 Pattern::Exact(t) => t == topic,
223 Pattern::Prefix(p) => topic.starts_with(p.as_str()),
224 }
225 }
226}
227
228/// A parsed topic filter: the value of [`ReadOptions::topic`] split on commas
229/// into individual [`Pattern`]s.
230///
231/// Note that synthetic control frames emitted by a following read --
232/// `xs.threshold` and heartbeat `xs.pulse` -- are delivered directly on the
233/// read channel and are never subject to this filter.
234#[derive(Clone, Debug, PartialEq)]
235pub enum TopicFilter {
236 /// Match every topic (no filter, or some element was `*`).
237 All,
238 /// Match topics satisfying at least one of these patterns.
239 Patterns(Vec<Pattern>),
240}
241
242impl TopicFilter {
243 /// Parse a comma-separated pattern list. Empty elements are ignored; an
244 /// empty or all-`*` spec yields [`TopicFilter::All`].
245 pub fn parse(spec: &str) -> TopicFilter {
246 let mut patterns = Vec::new();
247 for part in spec.split(',') {
248 let part = part.trim();
249 if part.is_empty() {
250 continue;
251 }
252 if part == "*" {
253 return TopicFilter::All;
254 }
255 if let Some(prefix) = part.strip_suffix(".*") {
256 patterns.push(Pattern::Prefix(format!("{prefix}.")));
257 } else {
258 patterns.push(Pattern::Exact(part.to_string()));
259 }
260 }
261 if patterns.is_empty() {
262 TopicFilter::All
263 } else {
264 TopicFilter::Patterns(patterns)
265 }
266 }
267
268 /// Parse an optional spec; `None` means no filter.
269 pub fn from_option(spec: Option<&str>) -> TopicFilter {
270 match spec {
271 Some(s) => TopicFilter::parse(s),
272 None => TopicFilter::All,
273 }
274 }
275
276 /// Does `topic` match this filter?
277 pub fn matches(&self, topic: &str) -> bool {
278 match self {
279 TopicFilter::All => true,
280 TopicFilter::Patterns(patterns) => patterns.iter().any(|p| p.matches(topic)),
281 }
282 }
283}
284
285/// K-way merge of per-pattern frame iterators, ordered by frame id, with
286/// dedupe when overlapping patterns yield the same frame from more than one
287/// iterator. Each input iterator must itself be sorted by id (ascending when
288/// `descending` is false, descending otherwise).
289struct MergeById<'a> {
290 iters: Vec<Box<dyn Iterator<Item = Frame> + 'a>>,
291 heap: std::collections::BinaryHeap<MergeEntry>,
292 descending: bool,
293 last_emitted: Option<Scru128Id>,
294}
295
296struct MergeEntry {
297 key: u128,
298 idx: usize,
299 frame: Frame,
300}
301
302impl PartialEq for MergeEntry {
303 fn eq(&self, other: &Self) -> bool {
304 self.key == other.key && self.idx == other.idx
305 }
306}
307impl Eq for MergeEntry {}
308impl PartialOrd for MergeEntry {
309 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
310 Some(self.cmp(other))
311 }
312}
313impl Ord for MergeEntry {
314 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
315 self.key.cmp(&other.key).then(self.idx.cmp(&other.idx))
316 }
317}
318
319/// BinaryHeap is a max-heap; for ascending merges flip the bits so the
320/// smallest id pops first.
321fn merge_key(id: &Scru128Id, descending: bool) -> u128 {
322 let raw = u128::from_be_bytes(id.to_bytes());
323 if descending {
324 raw
325 } else {
326 !raw
327 }
328}
329
330impl<'a> MergeById<'a> {
331 fn new(mut iters: Vec<Box<dyn Iterator<Item = Frame> + 'a>>, descending: bool) -> Self {
332 let mut heap = std::collections::BinaryHeap::with_capacity(iters.len());
333 for (idx, iter) in iters.iter_mut().enumerate() {
334 if let Some(frame) = iter.next() {
335 heap.push(MergeEntry {
336 key: merge_key(&frame.id, descending),
337 idx,
338 frame,
339 });
340 }
341 }
342 MergeById {
343 iters,
344 heap,
345 descending,
346 last_emitted: None,
347 }
348 }
349}
350
351impl Iterator for MergeById<'_> {
352 type Item = Frame;
353
354 fn next(&mut self) -> Option<Frame> {
355 loop {
356 let entry = self.heap.pop()?;
357 if let Some(frame) = self.iters[entry.idx].next() {
358 self.heap.push(MergeEntry {
359 key: merge_key(&frame.id, self.descending),
360 idx: entry.idx,
361 frame,
362 });
363 }
364 // Overlapping patterns can yield the same frame from more than
365 // one iterator; emit it once.
366 if self.last_emitted == Some(entry.frame.id) {
367 continue;
368 }
369 self.last_emitted = Some(entry.frame.id);
370 return Some(entry.frame);
371 }
372 }
373}
374
375impl ReadOptions {
376 /// Parse options from a URL query string (the form used by the HTTP API),
377 /// for example `follow=true&topic=clip.*&last=10`. `None` yields the
378 /// defaults.
379 pub fn from_query(query: Option<&str>) -> Result<Self, crate::error::Error> {
380 match query {
381 Some(q) => Ok(serde_urlencoded::from_str(q)?),
382 None => Ok(Self::default()),
383 }
384 }
385
386 /// Render these options back into a URL query string, the inverse of
387 /// [`from_query`](ReadOptions::from_query). Returns an empty string when no
388 /// options are set.
389 pub fn to_query_string(&self) -> String {
390 let mut params = Vec::new();
391
392 // Add follow parameter with heartbeat if specified
393 match self.follow {
394 FollowOption::Off => {}
395 FollowOption::On => params.push(("follow", "true".to_string())),
396 FollowOption::WithHeartbeat(duration) => {
397 params.push(("follow", duration.as_millis().to_string()));
398 }
399 }
400
401 // Add new if true
402 if self.new {
403 params.push(("new", "true".to_string()));
404 }
405
406 // Add after if present
407 if let Some(after) = self.after {
408 params.push(("after", after.to_string()));
409 }
410
411 // Add from if present
412 if let Some(from) = self.from {
413 params.push(("from", from.to_string()));
414 }
415
416 // Add limit if present
417 if let Some(limit) = self.limit {
418 params.push(("limit", limit.to_string()));
419 }
420
421 // Add last if present
422 if let Some(last) = self.last {
423 params.push(("last", last.to_string()));
424 }
425
426 if let Some(topic) = &self.topic {
427 params.push(("topic", topic.clone()));
428 }
429
430 // Return empty string if no params
431 if params.is_empty() {
432 String::new()
433 } else {
434 url::form_urlencoded::Serializer::new(String::new())
435 .extend_pairs(params)
436 .finish()
437 }
438 }
439}
440
441/// Whether a read keeps streaming after history is replayed.
442#[derive(Default, PartialEq, Clone, Debug)]
443pub enum FollowOption {
444 /// Stop once historical frames are exhausted.
445 #[default]
446 Off,
447 /// Replay history, then stream live appends indefinitely.
448 On,
449 /// Like [`On`](FollowOption::On), but also emit a periodic heartbeat frame
450 /// at the given interval so idle readers can detect a live connection.
451 WithHeartbeat(Duration),
452}
453
454#[derive(Debug)]
455enum GCTask {
456 CheckLastTTL {
457 topic: String,
458 keep: u32,
459 },
460 /// Remove every `time:` frame whose expiry has passed, up to
461 /// `MAX_SWEEP_PER_DRAIN`. Sent by the sweep tick.
462 Sweep,
463 Drain(tokio::sync::oneshot::Sender<()>),
464}
465
466/// A frame the gc worker is about to delete.
467enum Removal {
468 /// Only the id is known. The frame is fetched to learn its keys.
469 Id(Scru128Id),
470 /// An index hit that already carries every key the removal needs, so no
471 /// point read into `stream` is required. `expires_at` is `None` when the
472 /// frame has no `time:` ttl and so has no expiry index entry.
473 Indexed {
474 id: Scru128Id,
475 topic: String,
476 expires_at: Option<u64>,
477 },
478}
479
480impl Removal {
481 fn id(&self) -> Scru128Id {
482 match self {
483 Removal::Id(id) | Removal::Indexed { id, .. } => *id,
484 }
485 }
486}
487
488/// Where the next expiry sweep starts scanning. Everything below it has been
489/// swept, so the sweep steps over the tombstones earlier sweeps left instead
490/// of walking them again.
491///
492/// It only ever moves up to a key a sweep actually removed, and a sweep never
493/// looks past the frames that are due, so it can never come to rest above an
494/// entry that is still waiting for its expiry to pass. The one way an entry
495/// can appear below it is an index write, which
496/// [`note_indexed_expiry`](Store::note_indexed_expiry) moves it back for.
497#[derive(Clone, Copy, PartialEq, Eq, Debug)]
498struct SweepStart {
499 key: [u8; 24],
500 /// Whether `key` itself still has to be swept: false on the key a sweep
501 /// removed, true on one a later index write put back in play.
502 inclusive: bool,
503}
504
505impl SweepStart {
506 fn bound(&self) -> Bound<[u8; 24]> {
507 if self.inclusive {
508 Bound::Included(self.key)
509 } else {
510 Bound::Excluded(self.key)
511 }
512 }
513
514 /// Sort position, so two starts can be compared. An inclusive start sits
515 /// before an exclusive one on the same key: it covers one more entry.
516 fn rank(&self) -> ([u8; 24], u8) {
517 (self.key, u8::from(!self.inclusive))
518 }
519}
520
521/// Where a `last:n` trim scan of a topic starts. Below it the topic holds no
522/// live frame, only the tombstones of ones a trim or another removal path
523/// took, so a scan that starts here counts and trims exactly what a scan of
524/// the whole topic would.
525///
526/// A trim proves that of everything it removed. A scan that reaches the end of
527/// the topic without finding `keep` live frames proves it of everything under
528/// the oldest entry it saw, which is why the bound can be inclusive.
529///
530/// The one way a live frame can appear below it is an index write, which
531/// [`note_indexed_topic`](Store::note_indexed_topic) drops the floor for.
532#[derive(Clone, Copy, PartialEq, Eq, Debug)]
533struct TrimFloor {
534 id: Scru128Id,
535 /// Whether `id` itself is still on the topic and in scope for the scan.
536 inclusive: bool,
537}
538
539/// Options for opening a [`Store`]. Build one with the
540/// [`bon`](https://docs.rs/bon) builder; every field has a default.
541///
542/// ```
543/// use std::time::Duration;
544/// use xs::{Fsync, StoreOptions};
545///
546/// let options = StoreOptions::builder()
547/// .fsync(Fsync::Always)
548/// .ttl_sweep(Duration::from_millis(250))
549/// .build();
550/// assert_eq!(options.fsync, Fsync::Always);
551/// assert_eq!(StoreOptions::default().ttl_sweep, Duration::from_millis(1000));
552/// ```
553#[derive(Clone, Debug, PartialEq, Eq, bon::Builder)]
554pub struct StoreOptions {
555 /// When the journal is fsynced. See [`Fsync`].
556 #[builder(default)]
557 pub fsync: Fsync,
558 /// How often expired `time:` frames are swept from disk. Default 1000 ms.
559 /// Zero disables the sweeper; expired frames are then only hidden from
560 /// reads, never removed.
561 #[builder(default = Duration::from_millis(1000))]
562 pub ttl_sweep: Duration,
563}
564
565impl Default for StoreOptions {
566 fn default() -> Self {
567 StoreOptions::builder().build()
568 }
569}
570
571/// An append-only event stream backed by a directory on disk.
572///
573/// Open one with [`new`](Store::new). `Store` is cheaply [`Clone`]able: every
574/// clone shares the same underlying database, broadcast channel, and
575/// content-addressed store, so clone it freely across tasks and threads instead
576/// of wrapping it in an `Arc`.
577///
578/// See the [module docs](crate::store) for the topic and retention model.
579#[derive(Clone)]
580pub struct Store {
581 /// Directory backing this store (the path passed to [`new`](Store::new)).
582 pub path: PathBuf,
583 db: Database,
584 stream: Keyspace,
585 idx_topic: Keyspace,
586 /// `time:` frames keyed by expiry then id, valued by topic. The sweeper
587 /// range-scans it from [`sweep_start`](Store::sweep_start) up to now. See
588 /// [`idx_expiry_key`].
589 idx_expiry: Keyspace,
590 /// Where the next sweep resumes in `idx_expiry`; `None` is the start of
591 /// the index. In memory only: a reopened store sweeps from the start
592 /// again, which costs one walk of whatever tombstones outlived it and can
593 /// never skip a frame. See [`SweepStart`].
594 sweep_start: Arc<Mutex<Option<SweepStart>>>,
595 /// Per-topic `last:n` trim floor: every frame on the topic with an id at
596 /// or below it has been removed, so a trim scan stops there rather than
597 /// running on into the tombstones of the frames it trimmed last time. In
598 /// memory only, on the same reasoning as
599 /// [`sweep_start`](Store::sweep_start). See
600 /// [`last_overflow`](Store::last_overflow).
601 trim_floor: Arc<Mutex<HashMap<String, TrimFloor>>>,
602 broadcast_tx: broadcast::Sender<Frame>,
603 gc_tx: UnboundedSender<GCTask>,
604 /// Joins the background workers when the last caller-held clone drops.
605 /// Declared after `gc_tx` on purpose: fields drop in order, so the gc
606 /// channel closes before the join, and the gc worker can exit.
607 workers: Option<Arc<Workers>>,
608 append_lock: Arc<Mutex<()>>,
609 /// Runtime handle captured at [`new`](Store::new), used to spawn the follow
610 /// and heartbeat tasks from the now-sync [`read`](Store::read). `Handle` is
611 /// cheaply `Clone`, so every `Store` clone shares the same runtime.
612 rt: Option<tokio::runtime::Handle>,
613 /// Optional base engine the processors clone, set via [`with_base_engine`].
614 /// `None` falls back to `Engine::new()`. See
615 /// [`prepared_base`](crate::nu::prepared_base) and ADR 0007.
616 base_engine: Option<Arc<EngineState>>,
617 /// Fsync policy and dirty flag, shared by every clone and the fsync worker.
618 fsync: Arc<FsyncState>,
619 /// Counters about this store's own work, shared by every clone and by
620 /// the gc worker. See [`StoreStats`].
621 stats: Arc<StoreStats>,
622}
623
624/// Counters the store keeps about its own work, always on.
625///
626/// Relaxed atomics on paths that already touch the database, so the cost is
627/// noise next to the work being counted. Cumulative for the life of the
628/// process, with no way to reset: a caller wanting a rate subtracts two
629/// reads.
630#[derive(Debug, Default)]
631pub struct StoreStats {
632 /// Frames accepted by [`append`](Store::append), including ephemeral ones
633 /// that were broadcast but never stored.
634 pub appends: AtomicUsize,
635 /// Frames pulled from a keyspace iterator by a read. Larger than the
636 /// number returned whenever a read filters: the gap is wasted work.
637 pub frames_scanned: AtomicUsize,
638 /// Point reads into `stream`. A topic read does one per frame it returns,
639 /// so this over `frames_scanned` says how well the index is filtering.
640 pub stream_reads: AtomicUsize,
641 /// Frames removed by [`remove_many`](Store::remove_many).
642 pub removed_frames: AtomicUsize,
643 /// Batches committed by [`remove_many`](Store::remove_many). One per gc
644 /// drain that had anything to do.
645 pub remove_commits: AtomicUsize,
646 /// Times the gc worker drained its queue.
647 pub gc_drains: AtomicUsize,
648 /// Nanoseconds the gc worker spent inside a drain. Against `gc_drains`
649 /// this is the cost of retention, which is otherwise invisible.
650 pub gc_nanos: AtomicU64,
651}
652
653/// A serializable read of [`StoreStats`]. See its fields for what each counts.
654#[derive(Debug, Clone, serde::Serialize)]
655pub struct StoreStatsSnapshot {
656 pub appends: u64,
657 pub frames_scanned: u64,
658 pub stream_reads: u64,
659 pub removed_frames: u64,
660 pub remove_commits: u64,
661 pub gc_drains: u64,
662 pub gc_nanos: u64,
663}
664
665impl StoreStats {
666 fn snapshot(&self) -> StoreStatsSnapshot {
667 let n = |c: &AtomicUsize| c.load(Ordering::Relaxed) as u64;
668 StoreStatsSnapshot {
669 appends: n(&self.appends),
670 frames_scanned: n(&self.frames_scanned),
671 stream_reads: n(&self.stream_reads),
672 removed_frames: n(&self.removed_frames),
673 remove_commits: n(&self.remove_commits),
674 gc_drains: n(&self.gc_drains),
675 gc_nanos: self.gc_nanos.load(Ordering::Relaxed),
676 }
677 }
678}
679
680/// Cache hit rates for one keyspace, each `None` until that layer has been
681/// asked for something.
682#[derive(Debug, Clone, serde::Serialize)]
683pub struct KeyspaceRates {
684 pub block_cache_hit: Option<f64>,
685 pub data_block_cache_hit: Option<f64>,
686 pub index_block_cache_hit: Option<f64>,
687 pub filter_block_cache_hit: Option<f64>,
688 pub table_file_cache_hit: Option<f64>,
689 /// Share of filter lookups that saved a read. Only counted when the
690 /// filter reports a miss: a filter costs nothing on a hit, so this is
691 /// what it is worth, not how often it ran.
692 pub filter_efficiency: Option<f64>,
693}
694
695/// A rate is meaningless with no observations behind it.
696fn rate(observations: usize, value: f64) -> Option<f64> {
697 (observations > 0).then_some(value)
698}
699
700/// A point-in-time read of one keyspace's cache and filter counters.
701///
702/// Every rate is a fraction in `0.0..=1.0`, or `0.0` when nothing has been
703/// asked of that layer yet. The counters are cumulative since the process
704/// started; fjall has no way to reset them, so a caller comparing two reads
705/// should subtract.
706#[derive(Debug, Clone, serde::Serialize)]
707pub struct KeyspaceMetrics {
708 pub keyspace: &'static str,
709
710 /// Hit rates, or `null` where nothing has been asked of that layer yet.
711 /// fjall returns 1.0 for a rate with no observations, which reads as a
712 /// perfect cache on a store that has done no work.
713 pub rates: KeyspaceRates,
714
715 pub filter_queries: usize,
716 pub io_skipped_by_filter: usize,
717
718 /// Blocks asked for, and how many of those reached the filesystem.
719 pub block_loads: usize,
720 pub block_load_io: usize,
721 pub data_block_io: u64,
722 pub index_block_io: u64,
723 pub filter_block_io: u64,
724}
725
726impl KeyspaceMetrics {
727 fn read(keyspace: &'static str, ks: &Keyspace) -> Self {
728 // `Keyspace::metrics` hands back an `lsm_tree::Metrics`, a type fjall
729 // does not re-export, so the reference is never named.
730 let m = ks.metrics();
731 Self {
732 keyspace,
733 rates: KeyspaceRates {
734 block_cache_hit: rate(m.block_loads(), m.block_cache_hit_rate()),
735 data_block_cache_hit: rate(
736 m.data_block_load_count(),
737 m.data_block_cache_hit_rate(),
738 ),
739 index_block_cache_hit: rate(
740 m.index_block_load_count(),
741 m.index_block_cache_hit_rate(),
742 ),
743 filter_block_cache_hit: rate(
744 m.filter_block_load_count(),
745 m.filter_block_cache_hit_rate(),
746 ),
747 // No public count of table opens, so borrow the block loads:
748 // no block was loaded means no file was opened either.
749 table_file_cache_hit: rate(m.block_loads(), m.table_file_cache_hit_rate()),
750 filter_efficiency: rate(m.filter_queries(), m.filter_efficiency()),
751 },
752 filter_queries: m.filter_queries(),
753 io_skipped_by_filter: m.io_skipped_by_filter(),
754 block_loads: m.block_loads(),
755 block_load_io: m.block_load_io_count(),
756 data_block_io: m.data_block_io(),
757 index_block_io: m.index_block_io(),
758 filter_block_io: m.filter_block_io(),
759 }
760 }
761}
762
763/// Joins the background workers when the last caller-held `Store` drops.
764/// The gc worker's own clone carries `None`, so it never joins itself. The
765/// ticks stop first: the sweep tick holds a gc sender, and the gc worker
766/// only exits once every sender is gone. Once the joins return every worker
767/// has dropped its database handle, the database is closed, and the path
768/// can be reopened.
769struct Workers {
770 gc: Option<std::thread::JoinHandle<()>>,
771 fsync: Option<Tick>,
772 sweep: Option<Tick>,
773}
774
775impl Drop for Workers {
776 fn drop(&mut self) {
777 drop(self.fsync.take());
778 drop(self.sweep.take());
779 if let Some(handle) = self.gc.take() {
780 let _ = handle.join();
781 }
782 }
783}
784
785/// A thread that runs a closure every `interval` until dropped. Dropping it
786/// sets `stop`, unparks the thread, and joins it, so the join waits for at
787/// most one in-flight run of the closure.
788struct Tick {
789 stop: Arc<AtomicBool>,
790 handle: Option<std::thread::JoinHandle<()>>,
791}
792
793impl Tick {
794 fn spawn(interval: Duration, mut run: impl FnMut() + Send + 'static) -> Tick {
795 let stop = Arc::new(AtomicBool::new(false));
796 let handle = std::thread::spawn({
797 let stop = stop.clone();
798 move || loop {
799 // park_timeout may wake early; the flags checked by each
800 // closure make that harmless.
801 std::thread::park_timeout(interval);
802 if stop.load(Ordering::Acquire) {
803 break;
804 }
805 run();
806 }
807 });
808 Tick {
809 stop,
810 handle: Some(handle),
811 }
812 }
813}
814
815impl Drop for Tick {
816 fn drop(&mut self) {
817 self.stop.store(true, Ordering::Release);
818 if let Some(handle) = self.handle.take() {
819 handle.thread().unpark();
820 let _ = handle.join();
821 }
822 }
823}
824
825/// Shared fsync bookkeeping.
826struct FsyncState {
827 mode: Fsync,
828 /// Set after every commit under `interval`; the tick clears it.
829 dirty: AtomicBool,
830}
831
832impl Store {
833 /// Open the store at `path`, creating the directory layout if it does not
834 /// exist. Spawns a background worker that garbage-collects expired frames.
835 /// Uses the default [`Fsync`] policy; see [`with_fsync`](Store::with_fsync)
836 /// to choose one.
837 ///
838 /// # Errors
839 ///
840 /// Returns [`StoreError::Locked`] if another process already holds the
841 /// store open, or [`StoreError::Other`] for any other database error.
842 ///
843 /// ```no_run
844 /// use xs::Store;
845 ///
846 /// let store = Store::new("./clipboard-store".into())?;
847 /// # Ok::<(), xs::StoreError>(())
848 /// ```
849 pub fn new(path: PathBuf) -> Result<Store, StoreError> {
850 Store::open(path, StoreOptions::default())
851 }
852
853 /// Open the store at `path` with an explicit [`Fsync`] policy. Otherwise
854 /// the same as [`new`](Store::new).
855 ///
856 /// ```no_run
857 /// use xs::{Store, Fsync};
858 ///
859 /// let store = Store::with_fsync("./clipboard-store".into(), Fsync::Always)?;
860 /// # Ok::<(), xs::StoreError>(())
861 /// ```
862 pub fn with_fsync(path: PathBuf, fsync: Fsync) -> Result<Store, StoreError> {
863 Store::open(path, StoreOptions::builder().fsync(fsync).build())
864 }
865
866 /// Open the store at `path` with explicit [`StoreOptions`]. Otherwise the
867 /// same as [`new`](Store::new).
868 ///
869 /// ```no_run
870 /// use std::time::Duration;
871 /// use xs::{Store, StoreOptions};
872 ///
873 /// let options = StoreOptions::builder()
874 /// .ttl_sweep(Duration::from_millis(250))
875 /// .build();
876 /// let store = Store::open("./clipboard-store".into(), options)?;
877 /// # Ok::<(), xs::StoreError>(())
878 /// ```
879 pub fn open(path: PathBuf, options: StoreOptions) -> Result<Store, StoreError> {
880 let fsync = options.fsync;
881 let db = match Database::builder(path.join("fjall"))
882 .cache_size(32 * 1024 * 1024) // 32 MiB
883 // One worker cannot keep up: every append writes three keyspaces, each
884 // calls check_memtable_rotate, and all of them queue into the single
885 // shared channel that worker also has to drain. At 1, flushes starve --
886 // 1M appends put only 10.7% of their bytes into segments, and 1.0% with
887 // the sweeper also committing. See BUGS-FOUND.md.
888 .worker_threads(2)
889 .open()
890 {
891 Ok(db) => db,
892 Err(FjallError::Locked) => return Err(StoreError::Locked),
893 Err(e) => return Err(StoreError::Other(e)),
894 };
895
896 // Options for stream keyspace: point reads by frame ID
897 let stream_opts = || {
898 KeyspaceCreateOptions::default()
899 .max_memtable_size(8 * 1024 * 1024) // 8 MiB
900 .data_block_size_policy(BlockSizePolicy::all(16 * 1024)) // 16 KiB
901 .data_block_hash_ratio_policy(HashRatioPolicy::all(8.0))
902 .expect_point_read_hits(true)
903 };
904
905 // Options for idx_topic keyspace: prefix scans only
906 let idx_opts = || {
907 KeyspaceCreateOptions::default()
908 .max_memtable_size(8 * 1024 * 1024) // 8 MiB
909 .data_block_size_policy(BlockSizePolicy::all(16 * 1024)) // 16 KiB
910 .data_block_hash_ratio_policy(HashRatioPolicy::all(0.0)) // no point reads
911 .expect_point_read_hits(true)
912 };
913
914 // An idx_topic key is `<topic>\0<id>`, so one topic repeats across
915 // every entry it has. A restart point writes a key in full instead of
916 // against the one before it, so fewer of them is a smaller index, and
917 // nothing binary-searches inside these blocks to pay for it.
918 let idx_topic_opts =
919 || idx_opts().data_block_restart_interval_policy(RestartIntervalPolicy::all(32));
920
921 // An idx_expiry key is `<expiry><id>`: consecutive keys share a prefix
922 // only when frames expire in the same millisecond, so the same change
923 // buys much less. Left at the default.
924 let stream = db.keyspace("stream", stream_opts).unwrap();
925 let idx_topic = db.keyspace("idx_topic", idx_topic_opts).unwrap();
926 let idx_expiry = db.keyspace("idx_expiry", idx_opts).unwrap();
927
928 let (broadcast_tx, _) = broadcast::channel(FOLLOW_BUFFER);
929 let (gc_tx, gc_rx) = mpsc::unbounded_channel();
930
931 let fsync_state = Arc::new(FsyncState {
932 mode: fsync,
933 dirty: AtomicBool::new(false),
934 });
935
936 let mut store = Store {
937 path: path.clone(),
938 db,
939 stream,
940 idx_topic,
941 idx_expiry,
942 sweep_start: Arc::new(Mutex::new(None)),
943 trim_floor: Arc::new(Mutex::new(HashMap::new())),
944 broadcast_tx,
945 gc_tx,
946 workers: None,
947 append_lock: Arc::new(Mutex::new(())),
948 rt: tokio::runtime::Handle::try_current().ok(),
949 base_engine: None,
950 fsync: fsync_state,
951 stats: Arc::new(StoreStats::default()),
952 };
953
954 // Spawn the workers. The gc worker's clone is taken while `workers` is
955 // still `None`, so only callers' clones join them.
956 let gc = spawn_gc_worker(gc_rx, store.clone());
957 let fsync_tick = match fsync {
958 Fsync::Interval(interval) => Some(spawn_fsync_tick(
959 store.db.clone(),
960 store.fsync.clone(),
961 interval,
962 )),
963 Fsync::Always | Fsync::Never => None,
964 };
965 let sweep_tick = if options.ttl_sweep.is_zero() {
966 None
967 } else {
968 Some(spawn_sweep_tick(store.gc_tx.clone(), options.ttl_sweep))
969 };
970 store.workers = Some(Arc::new(Workers {
971 gc: Some(gc),
972 fsync: fsync_tick,
973 sweep: sweep_tick,
974 }));
975
976 Ok(store)
977 }
978
979 /// Counters about this store's own work: appends, how much a read
980 /// scanned against how much it returned, and what retention cost.
981 pub fn stats(&self) -> StoreStatsSnapshot {
982 self.stats.snapshot()
983 }
984
985 /// Cache and filter counters for each keyspace, for tuning
986 /// `cache_size`, `max_cached_files`, and the filter and pinning policies.
987 ///
988 /// Cumulative since the process started. See [`KeyspaceMetrics`].
989 pub fn metrics(&self) -> Vec<KeyspaceMetrics> {
990 vec![
991 KeyspaceMetrics::read("stream", &self.stream),
992 KeyspaceMetrics::read("idx_topic", &self.idx_topic),
993 KeyspaceMetrics::read("idx_expiry", &self.idx_expiry),
994 ]
995 }
996
997 /// The [`Fsync`] policy this store was opened with.
998 pub fn fsync(&self) -> Fsync {
999 self.fsync.mode
1000 }
1001
1002 /// Fsync the journal now, whatever the [`Fsync`] policy. Every append
1003 /// that has returned is durable once this returns. Use it before a
1004 /// planned shutdown, or in tests that reopen a store.
1005 pub fn flush(&self) -> Result<(), crate::error::Error> {
1006 // Clear before persisting: a write that lands during the persist sets
1007 // the flag again, so the next tick still covers it.
1008 self.fsync.dirty.store(false, Ordering::Release);
1009 self.db.persist(PersistMode::SyncAll)?;
1010 Ok(())
1011 }
1012
1013 /// Apply the [`Fsync`] policy after a committed batch: sync inline under
1014 /// `always`, mark the journal dirty for the tick under `interval`, and do
1015 /// nothing under `never`.
1016 fn after_commit(&self) -> Result<(), crate::error::Error> {
1017 match self.fsync.mode {
1018 Fsync::Always => self.db.persist(PersistMode::SyncAll)?,
1019 Fsync::Interval(_) => self.fsync.dirty.store(true, Ordering::Release),
1020 Fsync::Never => {}
1021 }
1022 Ok(())
1023 }
1024
1025 /// Set a base engine the processor engines clone.
1026 ///
1027 /// A program that embeds xs prepares an [`EngineState`] with its own
1028 /// commands, env, and consts;
1029 /// [`prepared_base`](crate::nu::prepared_base) clones it per spawn and adds
1030 /// the store commands, so the actor, service, and action processors get
1031 /// those commands. Shared across `Store` clones, so set it once, before the
1032 /// processors spawn. No base set: `Engine::new()`.
1033 pub fn with_base_engine(mut self, base: EngineState) -> Self {
1034 self.base_engine = Some(Arc::new(base));
1035 self
1036 }
1037
1038 /// The base engine an embedder attached via [`with_base_engine`], if any.
1039 pub fn base_engine(&self) -> Option<&EngineState> {
1040 self.base_engine.as_deref()
1041 }
1042
1043 /// Wait until the background garbage-collection worker has processed every
1044 /// task queued so far. Useful in tests to observe TTL eviction
1045 /// deterministically.
1046 pub async fn wait_for_gc(&self) {
1047 let (tx, rx) = tokio::sync::oneshot::channel();
1048 let _ = self.gc_tx.send(GCTask::Drain(tx));
1049 let _ = rx.await;
1050 }
1051
1052 /// Queue a sweep now, as the sweep tick would. Follow it with
1053 /// [`wait_for_gc`](Store::wait_for_gc) to observe the removals.
1054 #[cfg(test)]
1055 fn sweep(&self) {
1056 let _ = self.gc_tx.send(GCTask::Sweep);
1057 }
1058
1059 /// Number of entries in the expiry index.
1060 #[cfg(test)]
1061 fn idx_expiry_len(&self) -> usize {
1062 self.idx_expiry.len().unwrap()
1063 }
1064
1065 /// Read frames into an async channel according to `options`.
1066 ///
1067 /// By default this replays matching historical frames oldest-first and then
1068 /// closes the channel. With [`FollowOption::On`] it instead keeps the
1069 /// channel open and streams new appends as they arrive. When following, a
1070 /// single ephemeral `xs.threshold` frame is emitted to mark the boundary
1071 /// between replayed history and live events.
1072 ///
1073 /// The returned [`Receiver`](tokio::sync::mpsc::Receiver) is bounded;
1074 /// dropping it stops the read. For a blocking, non-async caller use
1075 /// [`read_sync`](Store::read_sync).
1076 ///
1077 /// ```no_run
1078 /// use xs::{Store, ReadOptions, FollowOption};
1079 ///
1080 /// # async fn run(store: Store) {
1081 /// let mut rx = store.read(ReadOptions::builder().follow(FollowOption::On).build());
1082 /// while let Some(frame) = rx.recv().await {
1083 /// if frame.topic == "xs.threshold" {
1084 /// // caught up to live; everything after this is new
1085 /// continue;
1086 /// }
1087 /// println!("{} {}", frame.id, frame.topic);
1088 /// }
1089 /// # }
1090 /// ```
1091 #[tracing::instrument(skip(self))]
1092 pub fn read(&self, options: ReadOptions) -> tokio::sync::mpsc::Receiver<Frame> {
1093 let (tx, rx) = tokio::sync::mpsc::channel(100);
1094
1095 let should_follow = matches!(
1096 options.follow,
1097 FollowOption::On | FollowOption::WithHeartbeat(_)
1098 );
1099
1100 // Only take broadcast subscription if following. We initate the subscription here to
1101 // ensure we don't miss any messages between historical processing and starting the
1102 // broadcast subscription.
1103 let broadcast_rx = if should_follow {
1104 Some(self.broadcast_tx.subscribe())
1105 } else {
1106 None
1107 };
1108
1109 // Only create done channel if we're doing historical processing
1110 let done_rx = if !options.new {
1111 let (done_tx, done_rx) = tokio::sync::oneshot::channel();
1112 let tx_clone = tx.clone();
1113 let store = self.clone();
1114 let options = options.clone();
1115 let should_follow_clone = should_follow;
1116
1117 // Spawn OS thread to handle historical events
1118 std::thread::spawn(move || {
1119 let mut last_id = None;
1120 let mut count = 0;
1121
1122 // Handle --last N: get the N most recent frames
1123 let filter = TopicFilter::from_option(options.topic.as_deref());
1124
1125 if let Some(last_n) = options.last {
1126 let iter = store.iter_for_filter_rev(filter);
1127
1128 // Collect last N frames (in reverse order), skipping expired
1129 let mut frames: Vec<Frame> = Vec::with_capacity(last_n);
1130 for frame in iter {
1131 if is_expired(&frame) {
1132 continue;
1133 }
1134 frames.push(frame);
1135 if frames.len() >= last_n {
1136 break;
1137 }
1138 }
1139
1140 // Reverse to chronological order and send
1141 for frame in frames.into_iter().rev() {
1142 last_id = Some(frame.id);
1143 count += 1;
1144 if tx_clone.blocking_send(frame).is_err() {
1145 return;
1146 }
1147 }
1148 } else {
1149 // Normal forward iteration
1150 // Determine start bound: from (inclusive) takes precedence over after (exclusive)
1151 let start_bound = options
1152 .from
1153 .map(|id| (id, true))
1154 .or_else(|| options.after.map(|id| (id, false)));
1155
1156 let iter = store.iter_for_filter(filter, start_bound);
1157
1158 for frame in iter {
1159 if is_expired(&frame) {
1160 continue;
1161 }
1162
1163 last_id = Some(frame.id);
1164
1165 if let Some(limit) = options.limit {
1166 if count >= limit {
1167 return; // Exit early if limit reached
1168 }
1169 }
1170
1171 if tx_clone.blocking_send(frame).is_err() {
1172 return;
1173 }
1174 count += 1;
1175 }
1176 }
1177
1178 // Send threshold message if following
1179 if should_follow_clone {
1180 let threshold = Frame::builder("xs.threshold")
1181 .id(scru128::new())
1182 .ttl(TTL::Ephemeral)
1183 .build();
1184 if tx_clone.blocking_send(threshold).is_err() {
1185 return;
1186 }
1187 }
1188
1189 // Signal completion with the last seen ID and count
1190 let _ = done_tx.send((last_id, count));
1191 });
1192
1193 Some(done_rx)
1194 } else {
1195 None
1196 };
1197
1198 // Handle broadcast subscription and heartbeat
1199 if let Some(broadcast_rx) = broadcast_rx {
1200 let handle = self
1201 .rt
1202 .clone()
1203 .expect("read() with follow needs a runtime handle");
1204
1205 {
1206 let tx = tx.clone();
1207 let limit = options.limit;
1208
1209 handle.spawn(async move {
1210 // If we have a done_rx, wait for historical processing
1211 let (last_id, mut count) = match done_rx {
1212 Some(done_rx) => match done_rx.await {
1213 Ok((id, count)) => (id, count),
1214 Err(_) => return, // Historical processing failed/cancelled
1215 },
1216 None => (None, 0),
1217 };
1218
1219 let filter = TopicFilter::from_option(options.topic.as_deref());
1220
1221 let mut broadcast_rx = broadcast_rx;
1222 loop {
1223 tokio::select! {
1224 _ = tx.closed() => break,
1225 r = broadcast_rx.recv() => match r {
1226 Ok(frame) => {
1227 // Filter by topic (any-match against the parsed patterns)
1228 if !filter.matches(&frame.topic) {
1229 continue;
1230 }
1231
1232 // Skip if we've already seen this frame during historical scan
1233 if let Some(last_scanned_id) = last_id {
1234 if frame.id <= last_scanned_id {
1235 continue;
1236 }
1237 }
1238
1239 if tx.send(frame).await.is_err() {
1240 break;
1241 }
1242
1243 if let Some(limit) = limit {
1244 count += 1;
1245 if count >= limit {
1246 break;
1247 }
1248 }
1249 }
1250 // The reader fell more than FOLLOW_BUFFER frames
1251 // behind and the channel overwrote what it had not
1252 // taken. Carrying on would hand it the frames after
1253 // the gap as though nothing were missing, and the
1254 // read channel carries frames only, so there is no
1255 // way to say otherwise in band. End the read instead:
1256 // a closed stream is a signal the reader cannot
1257 // mistake for a complete one. It resumes with
1258 // `after` set to the last id it received.
1259 Err(broadcast::error::RecvError::Lagged(skipped)) => {
1260 tracing::warn!(
1261 skipped,
1262 "follow fell behind the live buffer, ending the read"
1263 );
1264 break;
1265 }
1266 Err(broadcast::error::RecvError::Closed) => break,
1267 }
1268 }
1269 }
1270 });
1271 }
1272
1273 // Handle heartbeat if requested
1274 if let FollowOption::WithHeartbeat(duration) = options.follow {
1275 let heartbeat_tx = tx;
1276 handle.spawn(async move {
1277 loop {
1278 tokio::select! {
1279 _ = heartbeat_tx.closed() => break,
1280 _ = tokio::time::sleep(duration) => {
1281 let frame = Frame::builder("xs.pulse")
1282 .id(scru128::new())
1283 .ttl(TTL::Ephemeral)
1284 .build();
1285 if heartbeat_tx.send(frame).await.is_err() {
1286 break;
1287 }
1288 }
1289 }
1290 }
1291 });
1292 }
1293 }
1294
1295 rx
1296 }
1297
1298 /// Replay matching historical frames as a blocking iterator.
1299 ///
1300 /// This honours the `topic`, `from`, `after`, `limit`, and `last` parts of
1301 /// [`ReadOptions`] but ignores [`follow`](ReadOptions::follow): it never
1302 /// streams live appends. Use [`read`](Store::read) when you need to follow.
1303 ///
1304 /// The iterator is lazy: it reads a frame per `next`, so a caller that
1305 /// stops early only pays for what it pulled. The exception is `last`,
1306 /// which reads in reverse and buffers its N frames to return them in
1307 /// chronological order.
1308 ///
1309 /// ```no_run
1310 /// use xs::{Store, ReadOptions};
1311 ///
1312 /// # fn run(store: Store) {
1313 /// let opts = ReadOptions::builder().topic("clip.*".to_string()).last(10).build();
1314 /// for frame in store.read_sync(opts) {
1315 /// println!("{} {}", frame.id, frame.topic);
1316 /// }
1317 /// # }
1318 /// ```
1319 pub fn read_sync(&self, options: ReadOptions) -> impl Iterator<Item = Frame> + '_ {
1320 // Hide expired frames the sweeper has not reached yet
1321 let filter_expired = |frame: Frame| (!is_expired(&frame)).then_some(frame);
1322
1323 let filter = TopicFilter::from_option(options.topic.as_deref());
1324
1325 if let Some(last_n) = options.last {
1326 // Handle --last N: get the N most recent frames. This branch reads
1327 // in reverse and re-orders, so it has to collect, but it is bounded
1328 // by last_n.
1329 let iter = self.iter_for_filter_rev(filter);
1330
1331 // Collect last N frames (in reverse order), skipping expired
1332 let mut frames: Vec<Frame> = Vec::with_capacity(last_n);
1333 for frame in iter {
1334 if let Some(frame) = filter_expired(frame) {
1335 frames.push(frame);
1336 if frames.len() >= last_n {
1337 break;
1338 }
1339 }
1340 }
1341
1342 // Reverse to chronological order
1343 frames.reverse();
1344 Box::new(frames.into_iter()) as Box<dyn Iterator<Item = Frame> + '_>
1345 } else {
1346 // Normal forward iteration, streamed: the caller only pays for the
1347 // frames it pulls.
1348 let start_bound = options
1349 .from
1350 .map(|id| (id, true))
1351 .or_else(|| options.after.map(|id| (id, false)));
1352
1353 Box::new(
1354 self.iter_for_filter(filter, start_bound)
1355 .filter_map(filter_expired)
1356 .take(options.limit.unwrap_or(usize::MAX)),
1357 )
1358 }
1359 }
1360
1361 /// Returns the current module state as of a given point in the stream.
1362 ///
1363 /// Scans all frames up to (and including) `as_of` and returns a mapping of
1364 /// module name to CAS hash for the latest frame on each `xs.module.<name>`
1365 /// topic.
1366 /// Resolve the set of registered Nushell modules as of a given frame ID.
1367 ///
1368 /// Scans `xs.module.<name>` frames up to and including `as_of` and returns a
1369 /// map from module name to the content hash of its latest definition. Used
1370 /// by the scripting runtime; rarely needed when embedding the store
1371 /// directly.
1372 pub fn nu_modules_at(
1373 &self,
1374 as_of: &Scru128Id,
1375 ) -> std::collections::HashMap<String, ssri::Integrity> {
1376 let mut modules = std::collections::HashMap::new();
1377 let options = ReadOptions::builder().follow(FollowOption::Off).build();
1378 for frame in self.read_sync(options) {
1379 if frame.id > *as_of {
1380 break;
1381 }
1382 if let Some(hash) = frame.hash {
1383 if let Some(name) = frame.topic.strip_prefix("xs.module.") {
1384 if !name.is_empty() {
1385 modules.insert(name.to_string(), hash);
1386 }
1387 }
1388 }
1389 }
1390 modules
1391 }
1392
1393 /// Fetch a single frame by ID, or `None` if no such frame exists.
1394 pub fn get(&self, id: &Scru128Id) -> Option<Frame> {
1395 self.stats.stream_reads.fetch_add(1, Ordering::Relaxed);
1396 self.stream
1397 .get(id.to_bytes())
1398 .unwrap()
1399 .map(|value| deserialize_frame((id.as_bytes(), value)))
1400 }
1401
1402 /// Delete a frame and its topic index entries. Removing a frame that does
1403 /// not exist is a no-op and returns `Ok(())`.
1404 ///
1405 /// This removes the stream entry only; any payload bytes in the
1406 /// content-addressed store are left in place.
1407 #[tracing::instrument(skip(self), fields(id = %id.to_string()))]
1408 pub fn remove(&self, id: &Scru128Id) -> Result<(), crate::error::Error> {
1409 self.remove_many([Removal::Id(*id)])
1410 }
1411
1412 /// Delete every frame in `removals`, with their index entries, in one
1413 /// batch with one commit. A [`Removal::Id`] whose frame is already gone
1414 /// is skipped, and nothing is committed when none remain.
1415 fn remove_many(
1416 &self,
1417 removals: impl IntoIterator<Item = Removal>,
1418 ) -> Result<(), crate::error::Error> {
1419 let mut batch = self.db.batch();
1420 for removal in removals {
1421 match removal {
1422 Removal::Id(id) => {
1423 if let Some(frame) = self.get(&id) {
1424 self.remove_frame_keys(
1425 &mut batch,
1426 &frame.id,
1427 &frame.topic,
1428 expires_at(&frame),
1429 );
1430 }
1431 }
1432 Removal::Indexed {
1433 id,
1434 topic,
1435 expires_at,
1436 } => self.remove_frame_keys(&mut batch, &id, &topic, expires_at),
1437 }
1438 }
1439 if batch.is_empty() {
1440 return Ok(());
1441 }
1442 batch.commit()?;
1443 self.stats.remove_commits.fetch_add(1, Ordering::Relaxed);
1444 // No inline fsync in any mode. The tombstones reach disk with the next
1445 // append's sync or the next tick. If power loss brings a frame back,
1446 // its index entries come back with it, so it is trimmed or swept
1447 // again.
1448 if matches!(self.fsync.mode, Fsync::Interval(_)) {
1449 self.fsync.dirty.store(true, Ordering::Release);
1450 }
1451 Ok(())
1452 }
1453
1454 /// Queue the stream entry and index keys of a frame for removal on
1455 /// `batch`. `expires_at` is the frame's expiry index slot, `Some` only for
1456 /// a `time:` frame. The topic key is built without validation: the frame
1457 /// exists.
1458 fn remove_frame_keys(
1459 &self,
1460 batch: &mut OwnedWriteBatch,
1461 id: &Scru128Id,
1462 topic: &str,
1463 expires_at: Option<u64>,
1464 ) {
1465 self.stats.removed_frames.fetch_add(1, Ordering::Relaxed);
1466 let mut topic_key = idx_topic_key_prefix(topic);
1467 topic_key.extend(id.as_bytes());
1468 batch.remove(&self.stream, id.as_bytes());
1469 batch.remove(&self.idx_topic, topic_key);
1470 for prefix_key in idx_topic_prefix_keys(topic, id) {
1471 batch.remove(&self.idx_topic, prefix_key);
1472 }
1473 if let Some(expires_at) = expires_at {
1474 batch.remove(&self.idx_expiry, idx_expiry_key(expires_at, id));
1475 }
1476 }
1477
1478 /// The oldest `time:` frames whose expiry is at or before `now_ms`, at
1479 /// most `limit` of them, straight from the expiry index. A full `limit`
1480 /// means there may be more.
1481 ///
1482 /// The scan resumes at [`sweep_start`](Store::sweep_start) rather than at
1483 /// the start of the index. Everything below that point is the tombstones
1484 /// of frames earlier sweeps removed, and walking them again on every sweep
1485 /// is what made draining a backlog cost O(n^2/batch).
1486 fn expired_at(&self, now_ms: u64, limit: usize) -> Vec<Removal> {
1487 let last = idx_expiry_key(now_ms, &Scru128Id::from_bytes([0xff; 16]));
1488 let from = *self.sweep_start.lock().unwrap();
1489 // A clock that stepped backwards can leave the resume point above the
1490 // cut-off. Nothing below it is unswept, so there is nothing to do
1491 // until the clock catches up.
1492 if from.is_some_and(|start| start.key > last) {
1493 return Vec::new();
1494 }
1495 let start = from.map_or(Bound::Unbounded, |start| start.bound());
1496
1497 let mut removals = Vec::new();
1498 let mut swept = None;
1499 for guard in self
1500 .idx_expiry
1501 .range((start, Bound::Included(last)))
1502 .take(limit)
1503 {
1504 // Stop on a read error rather than skipping the entry: the resume
1505 // point may never pass an entry this sweep did not remove.
1506 let Ok((key, value)) = guard.into_inner() else {
1507 break;
1508 };
1509 let Ok(key) = <[u8; 24]>::try_from(key.as_ref()) else {
1510 break;
1511 };
1512 let (expires_at, id) = idx_expiry_parse_key(&key);
1513 removals.push(Removal::Indexed {
1514 id,
1515 topic: String::from_utf8_lossy(&value).into_owned(),
1516 expires_at: Some(expires_at),
1517 });
1518 swept = Some(key);
1519 }
1520
1521 if let Some(key) = swept {
1522 let mut start = self.sweep_start.lock().unwrap();
1523 // Only advance from the point this scan started at. An index write
1524 // that moved it back while the scan ran wins: the next sweep
1525 // covers this ground again, and covering it twice is cheap next to
1526 // leaving a frame behind.
1527 if *start == from {
1528 *start = Some(SweepStart {
1529 key,
1530 inclusive: false,
1531 });
1532 }
1533 }
1534 removals
1535 }
1536
1537 /// Ids on `topic` past the newest `keep`, oldest first, at most `limit` of
1538 /// them, ignoring frames already in `pending` so a batch drops exactly
1539 /// what applying its tasks one by one would. A full `limit` means there
1540 /// may be more.
1541 ///
1542 /// Two bounded scans, both floored at the topic's
1543 /// [`trim_floor`](Store::trim_floor), below which the topic holds nothing
1544 /// but the tombstones of frames an earlier trim removed:
1545 ///
1546 /// 1. backwards from the newest entry for the `keep`-th newest live id,
1547 /// the high-water mark everything older than which is overflow;
1548 /// 2. forwards from the floor for the ids to remove.
1549 ///
1550 /// Taking the removals in forward order is what keeps trimming a backlog
1551 /// linear. A truncated pass leaves the floor on the newest id it removed,
1552 /// so the next pass starts above its own tombstones instead of walking
1553 /// them to reach what it left.
1554 ///
1555 /// Both scans read index keys only. The expiry an `idx_topic` value now
1556 /// carries is for the read path: a trim counts entries, so a `time:` frame
1557 /// the sweeper has not reached yet still holds one of the `keep` slots,
1558 /// exactly as it did when those values were empty.
1559 fn last_overflow(
1560 &self,
1561 topic: &str,
1562 keep: u32,
1563 pending: &HashSet<Scru128Id>,
1564 limit: usize,
1565 ) -> Vec<Overflow> {
1566 let floor = self.trim_floor.lock().unwrap().get(topic).copied();
1567 // The floor is a bound on the id, so it is a bound on the key: both
1568 // scans open at it and never reach the tombstones below it. See
1569 // [`idx_topic_range`].
1570 let (low, top) = idx_topic_range(
1571 idx_topic_key_prefix(topic),
1572 floor.map(|floor| (floor.id, floor.inclusive)),
1573 );
1574
1575 // The keep-th newest live id. Everything below it is overflow; fewer
1576 // than keep live entries means there is nothing to trim.
1577 let high = if keep == 0 {
1578 top
1579 } else {
1580 let mut seen = 0;
1581 let mut hwm = None;
1582 let mut oldest = None;
1583 for guard in self.idx_topic.range((low.clone(), top)).rev() {
1584 // A read error is not the end of the topic: give up on this
1585 // pass rather than record a floor the scan never reached.
1586 let Ok(key) = guard.key() else {
1587 return Vec::new();
1588 };
1589 let id = idx_topic_frame_id_from_key(&key);
1590 oldest = Some(id);
1591 if pending.contains(&id) {
1592 continue;
1593 }
1594 seen += 1;
1595 if seen == keep {
1596 hwm = Some(key.to_vec());
1597 break;
1598 }
1599 }
1600 match hwm {
1601 Some(key) => Bound::Excluded(key),
1602 None => {
1603 // The scan reached the end of the topic without finding
1604 // `keep` live frames. Nothing to trim, but everything
1605 // below the oldest entry it saw is tombstone, so the next
1606 // scan can start there instead of walking it again.
1607 if let Some(id) = oldest {
1608 self.set_trim_floor(
1609 topic,
1610 floor,
1611 TrimFloor {
1612 id,
1613 inclusive: true,
1614 },
1615 );
1616 }
1617 return Vec::new();
1618 }
1619 }
1620 };
1621
1622 let mut overflow = Vec::new();
1623 let mut trimmed = None;
1624 for guard in self.idx_topic.range((low, high)) {
1625 // Take the value too: it carries the frame's expiry, so the removal
1626 // needs no point read into `stream` to learn its keys.
1627 let Ok((key, value)) = guard.into_inner() else {
1628 break;
1629 };
1630 let id = idx_topic_frame_id_from_key(&key);
1631 if !pending.contains(&id) {
1632 overflow.push(Overflow {
1633 id,
1634 expires_at: idx_topic_expiry_of(&value),
1635 });
1636 }
1637 // A pending id counts: this drain removes it too, so the floor may
1638 // pass it.
1639 trimmed = Some(id);
1640 if overflow.len() == limit {
1641 break;
1642 }
1643 }
1644
1645 if let Some(id) = trimmed {
1646 self.set_trim_floor(
1647 topic,
1648 floor,
1649 TrimFloor {
1650 id,
1651 inclusive: false,
1652 },
1653 );
1654 }
1655 overflow
1656 }
1657
1658 /// Move a topic's trim floor to `to`, unless something moved it since the
1659 /// scan read `from`. An index write that dropped it while the scan ran
1660 /// wins: the next trim covers the topic from further back, and covering
1661 /// ground twice is cheap next to leaving a frame behind.
1662 fn set_trim_floor(&self, topic: &str, from: Option<TrimFloor>, to: TrimFloor) {
1663 let mut floors = self.trim_floor.lock().unwrap();
1664 if floors.get(topic).copied() == from {
1665 floors.insert(topic.to_string(), to);
1666 }
1667 }
1668
1669 /// Note that a `time:` frame's expiry entry has been committed at `key`.
1670 ///
1671 /// A frame restored with an id from the past, or appended in the instant a
1672 /// sweep passed its slot, lands below the resume point, where no later
1673 /// sweep would look. Move the resume point back onto it.
1674 ///
1675 /// Must be called after the commit: called before, a sweep could run,
1676 /// find nothing at the key yet, and leave the resume point above it again.
1677 fn note_indexed_expiry(&self, key: [u8; 24]) {
1678 let mut start = self.sweep_start.lock().unwrap();
1679 // Already at the start of the index: nothing can be below it.
1680 let Some(current) = *start else { return };
1681 let candidate = SweepStart {
1682 key,
1683 inclusive: true,
1684 };
1685 if candidate.rank() < current.rank() {
1686 *start = Some(candidate);
1687 }
1688 }
1689
1690 /// Note that a frame's topic index entry has been committed. An id at or
1691 /// below the topic's trim floor is in ground a trim scan no longer covers,
1692 /// so drop the floor and let the next trim scan the topic whole.
1693 ///
1694 /// Called after the commit, as
1695 /// [`note_indexed_expiry`](Store::note_indexed_expiry) is, and for every
1696 /// frame: `last:n` counts what is on the topic, whatever ttl put it there.
1697 fn note_indexed_topic(&self, topic: &str, id: &Scru128Id) {
1698 let mut floors = self.trim_floor.lock().unwrap();
1699 if floors.is_empty() {
1700 return;
1701 }
1702 if floors.get(topic).is_some_and(|floor| *id <= floor.id) {
1703 floors.remove(topic);
1704 }
1705 }
1706
1707 /// Forget where the sweep and the `last:n` trims had got to, so each next
1708 /// scan starts from the beginning of its index again. Called when a
1709 /// removal batch fails to commit: its frames are still there, but the
1710 /// resume points have already moved as though they were gone.
1711 fn reset_gc_resume(&self) {
1712 *self.sweep_start.lock().unwrap() = None;
1713 self.trim_floor.lock().unwrap().clear();
1714 }
1715
1716 // --- Content-addressed store (CAS) ---
1717 //
1718 // Frame payloads live here, keyed by an integrity hash. The typical flow is
1719 // `cas_insert` to store bytes, stash the returned hash on a `Frame`, then
1720 // `cas_read` to retrieve them later. Each method has a `_sync` twin for
1721 // blocking callers; the streaming `cas_reader`/`cas_writer` variants avoid
1722 // buffering the whole payload in memory.
1723
1724 /// Open a streaming reader for the payload identified by `hash`.
1725 pub async fn cas_reader(&self, hash: ssri::Integrity) -> cacache::Result<cacache::Reader> {
1726 cacache::Reader::open_hash(&self.path.join("cacache"), hash).await
1727 }
1728
1729 /// Blocking variant of [`cas_reader`](Store::cas_reader).
1730 pub fn cas_reader_sync(&self, hash: ssri::Integrity) -> cacache::Result<cacache::SyncReader> {
1731 cacache::SyncReader::open_hash(self.path.join("cacache"), hash)
1732 }
1733
1734 /// Open a streaming writer; finish it to obtain the payload's integrity hash.
1735 pub async fn cas_writer(&self) -> cacache::Result<cacache::Writer> {
1736 cacache::WriteOpts::new()
1737 .open_hash(&self.path.join("cacache"))
1738 .await
1739 }
1740
1741 /// Blocking variant of [`cas_writer`](Store::cas_writer).
1742 pub fn cas_writer_sync(&self) -> cacache::Result<cacache::SyncWriter> {
1743 cacache::WriteOpts::new().open_hash_sync(self.path.join("cacache"))
1744 }
1745
1746 /// Store `content` and return its integrity hash, ready to attach to a
1747 /// [`Frame::hash`].
1748 pub async fn cas_insert(&self, content: impl AsRef<[u8]>) -> cacache::Result<ssri::Integrity> {
1749 cacache::write_hash(&self.path.join("cacache"), content).await
1750 }
1751
1752 /// Blocking variant of [`cas_insert`](Store::cas_insert).
1753 pub fn cas_insert_sync(&self, content: impl AsRef<[u8]>) -> cacache::Result<ssri::Integrity> {
1754 cacache::write_hash_sync(self.path.join("cacache"), content)
1755 }
1756
1757 /// Convenience wrapper over [`cas_insert`](Store::cas_insert) for a byte slice.
1758 pub async fn cas_insert_bytes(&self, bytes: &[u8]) -> cacache::Result<ssri::Integrity> {
1759 self.cas_insert(bytes).await
1760 }
1761
1762 /// Blocking variant of [`cas_insert_bytes`](Store::cas_insert_bytes).
1763 pub fn cas_insert_bytes_sync(&self, bytes: &[u8]) -> cacache::Result<ssri::Integrity> {
1764 self.cas_insert_sync(bytes)
1765 }
1766
1767 /// Read back the full payload for `hash` into a `Vec<u8>`.
1768 pub async fn cas_read(&self, hash: &ssri::Integrity) -> cacache::Result<Vec<u8>> {
1769 cacache::read_hash(&self.path.join("cacache"), hash).await
1770 }
1771
1772 /// Blocking variant of [`cas_read`](Store::cas_read).
1773 pub fn cas_read_sync(&self, hash: &ssri::Integrity) -> cacache::Result<Vec<u8>> {
1774 cacache::read_hash_sync(self.path.join("cacache"), hash)
1775 }
1776
1777 /// Persist a frame exactly as given, including its existing
1778 /// [`id`](Frame::id), without broadcasting it to live readers or scheduling
1779 /// TTL garbage collection.
1780 ///
1781 /// Most callers want [`append`](Store::append) instead, which assigns a
1782 /// fresh ID, handles ephemeral and `Last` retention, and notifies
1783 /// subscribers. Use `insert_frame` only when you are reconstructing a stream
1784 /// with predetermined IDs (for example when restoring a backup).
1785 #[tracing::instrument(skip(self))]
1786 pub fn insert_frame(&self, frame: &Frame) -> Result<(), crate::error::Error> {
1787 let encoded: Vec<u8> = serde_json::to_vec(&frame).unwrap();
1788
1789 // Get the index topic key (also validates topic)
1790 let topic_key = idx_topic_key_from_frame(frame)?;
1791
1792 // Get prefix index keys for hierarchical queries
1793 let prefix_keys = idx_topic_prefix_keys(&frame.topic, &frame.id);
1794
1795 // Every idx_topic entry for this frame carries the same expiry, so a
1796 // topic scan can drop an expired id without reading the frame.
1797 let idx_value = idx_topic_expiry_value(frame);
1798
1799 // The id may already be here under a different topic or ttl. This is
1800 // an upsert, so the stream row is replaced, but the index keys carry
1801 // the topic and the expiry, so the old ones would survive their frame
1802 // and answer for a topic it no longer has.
1803 let superseded = self.get(&frame.id);
1804
1805 let mut batch = self.db.batch();
1806 batch.insert(&self.stream, frame.id.as_bytes(), encoded);
1807 batch.insert(&self.idx_topic, topic_key.clone(), idx_value);
1808 for prefix_key in &prefix_keys {
1809 batch.insert(&self.idx_topic, prefix_key, idx_value);
1810 }
1811 // A time: frame is also indexed by its expiry, for the sweeper
1812 let expiry_key = expires_at(frame).map(|at| idx_expiry_key(at, &frame.id));
1813 if let Some(key) = expiry_key {
1814 batch.insert(&self.idx_expiry, key, frame.topic.as_bytes());
1815 }
1816
1817 if let Some(old) = superseded.as_ref().filter(|old| old.topic != frame.topic) {
1818 let mut old_key = idx_topic_key_prefix(&old.topic);
1819 old_key.extend(frame.id.as_bytes());
1820 // "a.b" and "a.c" share the prefix key "a.", so drop only the keys
1821 // the write above is not putting straight back: removing and
1822 // inserting one key in one batch has no defined winner.
1823 for key in std::iter::once(old_key).chain(idx_topic_prefix_keys(&old.topic, &frame.id))
1824 {
1825 if key != topic_key && !prefix_keys.contains(&key) {
1826 batch.remove(&self.idx_topic, key);
1827 }
1828 }
1829 }
1830 // A changed ttl moves the expiry entry, because the expiry is half of
1831 // its key. An unchanged one is the same key, already rewritten above
1832 // with whatever topic the frame now carries.
1833 if let Some(stale) = superseded
1834 .as_ref()
1835 .and_then(expires_at)
1836 .map(|at| idx_expiry_key(at, &frame.id))
1837 .filter(|stale| Some(*stale) != expiry_key)
1838 {
1839 batch.remove(&self.idx_expiry, stale);
1840 }
1841
1842 batch.commit()?;
1843 // Both gc scans resume where they last stopped, and an id from the
1844 // past can land behind them. Tell them, once the entries are there to
1845 // be found.
1846 if let Some(key) = expiry_key {
1847 self.note_indexed_expiry(key);
1848 }
1849 self.note_indexed_topic(&frame.topic, &frame.id);
1850 self.after_commit()
1851 }
1852
1853 /// Append a frame to the stream and return it with its freshly assigned
1854 /// [`id`](Frame::id).
1855 ///
1856 /// This is the primary write path. It:
1857 ///
1858 /// - assigns a new time-sortable ID (overwriting any ID on the input);
1859 /// - validates the topic (see [`validate_topic`]);
1860 /// - persists the frame, unless its [`TTL`] is [`TTL::Ephemeral`], in which
1861 /// case it is only broadcast to live readers;
1862 /// - schedules garbage collection for [`TTL::Last`] retention;
1863 /// - broadcasts the frame to everyone currently in a following
1864 /// [`read`](Store::read).
1865 ///
1866 /// Appends are serialized internally, so frames are assigned IDs and
1867 /// delivered to subscribers in a consistent order.
1868 ///
1869 /// # Errors
1870 ///
1871 /// Returns an error if the topic is invalid or the underlying write fails.
1872 ///
1873 /// ```no_run
1874 /// use xs::{Store, Frame, TTL};
1875 ///
1876 /// # async fn run(store: Store) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
1877 /// let hash = store.cas_insert("hello clipboard").await?;
1878 /// let frame = store.append(
1879 /// Frame::builder("clip.add").hash(hash).ttl(TTL::Last(100)).build(),
1880 /// )?;
1881 /// println!("appended {}", frame.id);
1882 /// # Ok(())
1883 /// # }
1884 /// ```
1885 pub fn append(&self, mut frame: Frame) -> Result<Frame, crate::error::Error> {
1886 // Serialize all appends to ensure ID generation, write, and broadcast
1887 // happen atomically. This guarantees subscribers receive frames in
1888 // scru128 ID order.
1889 let _guard = self.append_lock.lock().unwrap();
1890
1891 frame.id = scru128::new();
1892
1893 // Check for null byte in topic (in case we're not storing the frame)
1894 idx_topic_key_from_frame(&frame)?;
1895
1896 // only store the frame if it's not ephemeral
1897 if frame.ttl != Some(TTL::Ephemeral) {
1898 self.insert_frame(&frame)?;
1899
1900 // If this is a Last TTL, schedule a gc task
1901 if let Some(TTL::Last(n)) = frame.ttl {
1902 let _ = self.gc_tx.send(GCTask::CheckLastTTL {
1903 topic: frame.topic.clone(),
1904 keep: n,
1905 });
1906 }
1907 }
1908
1909 self.stats.appends.fetch_add(1, Ordering::Relaxed);
1910 let _ = self.broadcast_tx.send(frame.clone());
1911 Ok(frame)
1912 }
1913
1914 /// Iterate frames starting from a bound.
1915 /// `start` is `(id, inclusive)` where inclusive=true means >= and inclusive=false means >.
1916 fn iter_frames(
1917 &self,
1918 start: Option<(Scru128Id, bool)>,
1919 ) -> Box<dyn Iterator<Item = Frame> + '_> {
1920 let range = match start {
1921 Some((id, true)) => (Bound::Included(id.as_bytes().to_vec()), Bound::Unbounded),
1922 Some((id, false)) => (Bound::Excluded(id.as_bytes().to_vec()), Bound::Unbounded),
1923 None => (Bound::Unbounded, Bound::Unbounded),
1924 };
1925
1926 let scanned = self.stats.clone();
1927 Box::new(self.stream.range(range).filter_map(move |guard| {
1928 scanned.frames_scanned.fetch_add(1, Ordering::Relaxed);
1929 let (key, value) = guard.into_inner().ok()?;
1930 Some(deserialize_frame((key, value)))
1931 }))
1932 }
1933
1934 /// Iterate frames in reverse order (most recent first).
1935 fn iter_frames_rev(&self) -> Box<dyn Iterator<Item = Frame> + '_> {
1936 let scanned = self.stats.clone();
1937 Box::new(self.stream.iter().rev().filter_map(move |guard| {
1938 scanned.frames_scanned.fetch_add(1, Ordering::Relaxed);
1939 let (key, value) = guard.into_inner().ok()?;
1940 Some(deserialize_frame((key, value)))
1941 }))
1942 }
1943
1944 /// Iterate frames by topic in reverse order (most recent first).
1945 fn iter_frames_by_topic_rev(&self, topic: &str) -> Box<dyn Iterator<Item = Frame> + '_> {
1946 let prefix = idx_topic_key_prefix(topic);
1947 let now = now_ms();
1948 let scanned = self.stats.clone();
1949 Box::new(
1950 self.idx_topic
1951 .prefix(prefix)
1952 .rev()
1953 .filter_map(move |guard| {
1954 scanned.frames_scanned.fetch_add(1, Ordering::Relaxed);
1955 self.get(&idx_topic_hit_id(guard, now)?)
1956 }),
1957 )
1958 }
1959
1960 /// Iterate frames by topic prefix in reverse order (most recent first).
1961 fn iter_frames_by_topic_prefix_rev(
1962 &self,
1963 prefix: &str,
1964 ) -> Box<dyn Iterator<Item = Frame> + '_> {
1965 let mut index_prefix = Vec::with_capacity(prefix.len() + 1);
1966 index_prefix.extend(prefix.as_bytes());
1967 index_prefix.push(NULL_DELIMITER);
1968
1969 let now = now_ms();
1970 let scanned = self.stats.clone();
1971
1972 Box::new(
1973 self.idx_topic
1974 .prefix(index_prefix)
1975 .rev()
1976 .filter_map(move |guard| {
1977 scanned.frames_scanned.fetch_add(1, Ordering::Relaxed);
1978 self.get(&idx_topic_hit_id(guard, now)?)
1979 }),
1980 )
1981 }
1982
1983 /// Iterate frames on an exact topic, ascending by frame id, from `start`.
1984 fn iter_frames_by_topic(
1985 &self,
1986 topic: &str,
1987 start: Option<(Scru128Id, bool)>,
1988 ) -> Box<dyn Iterator<Item = Frame> + '_> {
1989 let range = idx_topic_range(idx_topic_key_prefix(topic), start);
1990 let now = now_ms();
1991 let scanned = self.stats.clone();
1992 Box::new(self.idx_topic.range(range).filter_map(move |guard| {
1993 scanned.frames_scanned.fetch_add(1, Ordering::Relaxed);
1994 self.get(&idx_topic_hit_id(guard, now)?)
1995 }))
1996 }
1997
1998 /// Iterate frames matching a topic prefix (for wildcard queries like "user.*").
1999 /// The prefix should include the trailing dot (e.g., "user." for "user.*").
2000 fn iter_frames_by_topic_prefix(
2001 &self,
2002 prefix: &str,
2003 start: Option<(Scru128Id, bool)>,
2004 ) -> Box<dyn Iterator<Item = Frame> + '_> {
2005 // Build index prefix: "user.\0" for scanning all "user.*" entries
2006 let mut index_prefix = Vec::with_capacity(prefix.len() + 1);
2007 index_prefix.extend(prefix.as_bytes());
2008 index_prefix.push(NULL_DELIMITER);
2009
2010 let range = idx_topic_range(index_prefix, start);
2011 let now = now_ms();
2012 let scanned = self.stats.clone();
2013
2014 Box::new(self.idx_topic.range(range).filter_map(move |guard| {
2015 scanned.frames_scanned.fetch_add(1, Ordering::Relaxed);
2016 self.get(&idx_topic_hit_id(guard, now)?)
2017 }))
2018 }
2019
2020 /// Forward iterator for a single pattern, using the topic index.
2021 fn iter_for_pattern(
2022 &self,
2023 pattern: Pattern,
2024 start: Option<(Scru128Id, bool)>,
2025 ) -> Box<dyn Iterator<Item = Frame> + '_> {
2026 match pattern {
2027 Pattern::Exact(topic) => self.iter_frames_by_topic(&topic, start),
2028 Pattern::Prefix(prefix) => self.iter_frames_by_topic_prefix(&prefix, start),
2029 }
2030 }
2031
2032 /// Reverse (most recent first) iterator for a single pattern.
2033 fn iter_for_pattern_rev(&self, pattern: Pattern) -> Box<dyn Iterator<Item = Frame> + '_> {
2034 match pattern {
2035 Pattern::Exact(topic) => self.iter_frames_by_topic_rev(&topic),
2036 Pattern::Prefix(prefix) => self.iter_frames_by_topic_prefix_rev(&prefix),
2037 }
2038 }
2039
2040 /// Forward iterator for a parsed topic filter, ascending by frame id.
2041 /// A single pattern uses the indexed path directly; multiple patterns
2042 /// are k-way merged with dedupe for overlapping patterns.
2043 fn iter_for_filter(
2044 &self,
2045 filter: TopicFilter,
2046 start: Option<(Scru128Id, bool)>,
2047 ) -> Box<dyn Iterator<Item = Frame> + '_> {
2048 match filter {
2049 TopicFilter::All => self.iter_frames(start),
2050 TopicFilter::Patterns(mut patterns) if patterns.len() == 1 => {
2051 self.iter_for_pattern(patterns.remove(0), start)
2052 }
2053 TopicFilter::Patterns(patterns) => {
2054 let iters = patterns
2055 .into_iter()
2056 .map(|p| self.iter_for_pattern(p, start))
2057 .collect();
2058 Box::new(MergeById::new(iters, false))
2059 }
2060 }
2061 }
2062
2063 /// Reverse variant of [`iter_for_filter`](Store::iter_for_filter),
2064 /// descending by frame id (most recent first).
2065 fn iter_for_filter_rev(&self, filter: TopicFilter) -> Box<dyn Iterator<Item = Frame> + '_> {
2066 match filter {
2067 TopicFilter::All => self.iter_frames_rev(),
2068 TopicFilter::Patterns(mut patterns) if patterns.len() == 1 => {
2069 self.iter_for_pattern_rev(patterns.remove(0))
2070 }
2071 TopicFilter::Patterns(patterns) => {
2072 let iters = patterns
2073 .into_iter()
2074 .map(|p| self.iter_for_pattern_rev(p))
2075 .collect();
2076 Box::new(MergeById::new(iters, true))
2077 }
2078 }
2079 }
2080}
2081
2082fn spawn_gc_worker(
2083 mut gc_rx: UnboundedReceiver<GCTask>,
2084 mut store: Store,
2085) -> std::thread::JoinHandle<()> {
2086 // The worker's own clone must not hold a live `gc_tx`, or the channel
2087 // never closes and the worker, the database, and the fsync worker outlive
2088 // every caller's handle. Give it a sender whose receiver is already gone.
2089 let (closed_tx, _) = mpsc::unbounded_channel();
2090 store.gc_tx = closed_tx;
2091
2092 // One drain per wake: take the task that woke us and whatever else is
2093 // queued, up to the cap, and apply every removal in one batch with one
2094 // commit. A Drain is answered after that commit, so every task queued
2095 // before it has been applied by the time its reply lands.
2096 const MAX_TASKS_PER_DRAIN: usize = 1024;
2097 // A sweep removes at most this many frames. When it fills the cap the
2098 // next drain starts with another sweep, without waiting for the tick.
2099 const MAX_SWEEP_PER_DRAIN: usize = 4096;
2100 // A last:n trim removes at most this many frames per topic per drain, and
2101 // is carried over the same way a full sweep is. Without a cap the first
2102 // trim of a topic with a backlog collects every id past `keep` at once.
2103 const MAX_TRIM_PER_DRAIN: usize = 4096;
2104
2105 std::thread::spawn(move || {
2106 // Tasks a full batch left unfinished, run first in the next drain.
2107 let mut carried: Vec<GCTask> = Vec::new();
2108 loop {
2109 if carried.is_empty() {
2110 match gc_rx.blocking_recv() {
2111 Some(task) => carried.push(task),
2112 None => break,
2113 }
2114 }
2115
2116 let drain_started = std::time::Instant::now();
2117
2118 // Ids in this drain, so a last:n scan and a sweep never count or
2119 // queue a frame twice.
2120 let mut pending = HashSet::new();
2121 let mut removals = Vec::new();
2122 let mut drains = Vec::new();
2123 let mut sweep_again = false;
2124 // Topics whose trim filled its cap, one entry each however many
2125 // tasks for them this drain took.
2126 let mut trim_again: HashMap<String, u32> = HashMap::new();
2127 // Topics this drain must trim, collapsed from however many tasks
2128 // asked. Scanned after the take loop so every Sweep has already
2129 // run: an expired frame is hidden from reads, so it must not hold
2130 // a keep slot.
2131 let mut trims: HashMap<String, u32> = HashMap::new();
2132 let mut taken = 0;
2133 while taken < MAX_TASKS_PER_DRAIN {
2134 let Some(task) = carried.pop().or_else(|| gc_rx.try_recv().ok()) else {
2135 break;
2136 };
2137 match task {
2138 GCTask::CheckLastTTL { topic, keep } => {
2139 // One scan per topic per drain, at the smallest keep
2140 // asked for. A second scan for the same topic filters
2141 // out everything the first collected, skips keep, and
2142 // walks the rest to return nothing.
2143 trims
2144 .entry(topic)
2145 .and_modify(|k| *k = (*k).min(keep))
2146 .or_insert(keep);
2147 }
2148 GCTask::Sweep => {
2149 let expired = store.expired_at(now_ms(), MAX_SWEEP_PER_DRAIN);
2150 sweep_again |= expired.len() == MAX_SWEEP_PER_DRAIN;
2151 for removal in expired {
2152 if pending.insert(removal.id()) {
2153 removals.push(removal);
2154 }
2155 }
2156 }
2157 GCTask::Drain(tx) => drains.push(tx),
2158 }
2159 taken += 1;
2160 }
2161
2162 // Now that every Sweep in this drain has run, so `pending` holds
2163 // the expired frames it is removing, trim each topic once.
2164 for (topic, keep) in trims {
2165 let overflow = store.last_overflow(&topic, keep, &pending, MAX_TRIM_PER_DRAIN);
2166 let again = overflow.len() == MAX_TRIM_PER_DRAIN;
2167 for frame in overflow {
2168 if pending.insert(frame.id) {
2169 removals.push(Removal::Indexed {
2170 id: frame.id,
2171 topic: topic.clone(),
2172 expires_at: frame.expires_at,
2173 });
2174 }
2175 }
2176 if again {
2177 trim_again.insert(topic, keep);
2178 }
2179 }
2180
2181 if let Err(e) = store.remove_many(removals) {
2182 tracing::error!("gc remove failed: {e}");
2183 // The batch did not land, so every frame this drain counted as
2184 // gone is still there, below resume points that have already
2185 // moved past it. Start both scans over.
2186 store.reset_gc_resume();
2187 }
2188 store.stats.gc_drains.fetch_add(1, Ordering::Relaxed);
2189 store
2190 .stats
2191 .gc_nanos
2192 .fetch_add(drain_started.elapsed().as_nanos() as u64, Ordering::Relaxed);
2193 for tx in drains {
2194 let _ = tx.send(());
2195 }
2196 carried.extend(
2197 trim_again
2198 .into_iter()
2199 .map(|(topic, keep)| GCTask::CheckLastTTL { topic, keep }),
2200 );
2201 if sweep_again {
2202 carried.push(GCTask::Sweep);
2203 }
2204 }
2205 })
2206}
2207
2208/// Fsync the journal every `interval` when something was written since the
2209/// last tick. No final persist is needed on stop: fjall syncs the journal
2210/// when the database closes.
2211fn spawn_fsync_tick(db: Database, state: Arc<FsyncState>, interval: Duration) -> Tick {
2212 Tick::spawn(interval, move || {
2213 if state.dirty.swap(false, Ordering::AcqRel) {
2214 if let Err(e) = db.persist(PersistMode::SyncAll) {
2215 tracing::error!("fsync failed: {e}");
2216 }
2217 }
2218 })
2219}
2220
2221/// Queue a [`GCTask::Sweep`] every `interval`. The gc worker does the scan
2222/// and the removals, so a slow sweep never blocks the tick.
2223fn spawn_sweep_tick(gc_tx: UnboundedSender<GCTask>, interval: Duration) -> Tick {
2224 Tick::spawn(interval, move || {
2225 let _ = gc_tx.send(GCTask::Sweep);
2226 })
2227}
2228
2229fn now_ms() -> u64 {
2230 std::time::SystemTime::now()
2231 .duration_since(std::time::UNIX_EPOCH)
2232 .unwrap()
2233 .as_millis() as u64
2234}
2235
2236/// When a `time:` frame expires, in ms since the epoch: its id's timestamp
2237/// plus its ttl. `None` for any other ttl.
2238fn expires_at(frame: &Frame) -> Option<u64> {
2239 match frame.ttl.as_ref() {
2240 Some(TTL::Time(ttl)) => Some(frame.id.timestamp().saturating_add(ttl.as_millis() as u64)),
2241 _ => None,
2242 }
2243}
2244
2245/// Has this frame's `time:` ttl passed? Matches the sweeper's cut-off, so a
2246/// frame is hidden from reads from the moment it becomes sweepable.
2247fn is_expired(frame: &Frame) -> bool {
2248 matches!(expires_at(frame), Some(at) if now_ms() >= at)
2249}
2250
2251/// Expiry index key: expiry in ms as big-endian u64, then the frame id. Sorts
2252/// by expiry, so a range scan up to now yields exactly the expired frames.
2253fn idx_expiry_key(expires_at: u64, id: &Scru128Id) -> [u8; 24] {
2254 let mut key = [0u8; 24];
2255 key[..8].copy_from_slice(&expires_at.to_be_bytes());
2256 key[8..].copy_from_slice(id.as_bytes());
2257 key
2258}
2259
2260fn idx_expiry_parse_key(key: &[u8]) -> (u64, Scru128Id) {
2261 let expires_at = u64::from_be_bytes(key[..8].try_into().unwrap());
2262 let id = Scru128Id::from_bytes(key[8..24].try_into().unwrap());
2263 (expires_at, id)
2264}
2265
2266/// Live frames held for a following read that has not taken them yet.
2267///
2268/// A reader that falls further behind than this has its read ended rather
2269/// than silently skipped: see the `Lagged` arm in [`read`](Store::read).
2270/// Raising it buys a slow reader more room before that happens, at a frame
2271/// of memory per slot per follower.
2272const FOLLOW_BUFFER: usize = 4096;
2273
2274const NULL_DELIMITER: u8 = 0;
2275const MAX_TOPIC_LENGTH: usize = 255;
2276
2277/// Validate a frame topic (per ADR 0001).
2278///
2279/// A topic must be non-empty and at most 255 bytes, start with an ASCII letter
2280/// or `_`, and contain only `a-z A-Z 0-9 _ - .`. It may not end with `.` or
2281/// contain consecutive dots. [`Store::append`] runs this automatically; call it
2282/// directly to validate user input before building a [`Frame`].
2283///
2284/// ```
2285/// use xs::store::validate_topic;
2286///
2287/// assert!(validate_topic("clip.add").is_ok());
2288/// assert!(validate_topic("clip.").is_err());
2289/// ```
2290pub fn validate_topic(topic: &str) -> Result<(), crate::error::Error> {
2291 if topic.is_empty() {
2292 return Err("Topic cannot be empty".to_string().into());
2293 }
2294 if topic.len() > MAX_TOPIC_LENGTH {
2295 return Err(format!("Topic exceeds max length of {MAX_TOPIC_LENGTH} bytes").into());
2296 }
2297 if topic.ends_with('.') {
2298 return Err("Topic cannot end with '.'".to_string().into());
2299 }
2300 if topic.contains("..") {
2301 return Err("Topic cannot contain consecutive dots".to_string().into());
2302 }
2303
2304 let bytes = topic.as_bytes();
2305 let first = bytes[0];
2306 if !first.is_ascii_alphabetic() && first != b'_' {
2307 return Err("Topic must start with a-z, A-Z, or _".to_string().into());
2308 }
2309
2310 for &b in bytes {
2311 if !b.is_ascii_alphanumeric() && b != b'_' && b != b'-' && b != b'.' {
2312 return Err(format!(
2313 "Topic contains invalid character: '{}'. Allowed: a-z A-Z 0-9 _ - .",
2314 b as char
2315 )
2316 .into());
2317 }
2318 }
2319
2320 Ok(())
2321}
2322
2323/// Validates a topic query (for --topic flag).
2324/// Accepts a comma-separated list of patterns; each element is an exact
2325/// topic, a `prefix.*` wildcard, or `*` (match all).
2326pub fn validate_topic_query(spec: &str) -> Result<(), crate::error::Error> {
2327 let mut seen = false;
2328 for part in spec.split(',') {
2329 let part = part.trim();
2330 if part.is_empty() {
2331 continue;
2332 }
2333 seen = true;
2334 validate_topic_pattern(part)?;
2335 }
2336 if !seen {
2337 return Err("Topic query cannot be empty".to_string().into());
2338 }
2339 Ok(())
2340}
2341
2342/// Validate a single topic pattern: "*", "prefix.*", or an exact topic.
2343fn validate_topic_pattern(topic: &str) -> Result<(), crate::error::Error> {
2344 if topic == "*" {
2345 return Ok(());
2346 }
2347 if let Some(prefix) = topic.strip_suffix(".*") {
2348 // Validate the prefix part (e.g., "user" in "user.*")
2349 // Prefix can be empty edge case: ".*" is not valid
2350 if prefix.is_empty() {
2351 return Err("Wildcard '.*' requires a prefix".to_string().into());
2352 }
2353 validate_topic(prefix)
2354 } else {
2355 validate_topic(topic)
2356 }
2357}
2358
2359/// Generate prefix index keys for hierarchical topic queries.
2360/// For topic "user.id1.messages", returns keys for prefixes "user." and "user.id1."
2361fn idx_topic_prefix_keys(topic: &str, frame_id: &scru128::Scru128Id) -> Vec<Vec<u8>> {
2362 let mut keys = Vec::new();
2363 let mut pos = 0;
2364 while let Some(dot_pos) = topic[pos..].find('.') {
2365 let prefix = &topic[..pos + dot_pos + 1]; // include the dot
2366 let mut key = Vec::with_capacity(prefix.len() + 1 + 16);
2367 key.extend(prefix.as_bytes());
2368 key.push(NULL_DELIMITER);
2369 key.extend(frame_id.as_bytes());
2370 keys.push(key);
2371 pos += dot_pos + 1;
2372 }
2373 keys
2374}
2375
2376/// An `idx_topic` value meaning "this frame has no `time:` ttl". Distinct from
2377/// the empty value an older store wrote, which means "unknown".
2378const IDX_TOPIC_NEVER: u64 = u64::MAX;
2379
2380/// One frame a `last:n` trim is going to remove, with everything
2381/// [`Store::remove_many`] needs to delete its keys. The topic is the one being
2382/// trimmed and the expiry came off the index entry, so no point read is needed.
2383#[derive(Debug, Clone, Copy)]
2384struct Overflow {
2385 id: Scru128Id,
2386 /// `Some` when the frame has a `time:` ttl and so an expiry index entry.
2387 /// `None` when it has none, or when the entry predates the index carrying
2388 /// one -- see [`idx_topic_expiry_of`].
2389 expires_at: Option<u64>,
2390}
2391
2392/// The expiry an `idx_topic` value carries, if it carries one.
2393///
2394/// `None` covers two cases the caller must treat alike: a frame with no `time:`
2395/// ttl, which has no expiry index entry to delete, and an entry written before
2396/// the index carried an expiry, whose frame may have one. Removing a key that
2397/// is not there is a no-op, so both are safe to treat as "nothing to delete" --
2398/// but the second leaves a stale expiry entry, which the sweeper drops on its
2399/// next pass when the point read finds no frame.
2400#[inline]
2401fn idx_topic_expiry_of(value: &[u8]) -> Option<u64> {
2402 match <[u8; 8]>::try_from(value) {
2403 Ok(bytes) => match u64::from_be_bytes(bytes) {
2404 IDX_TOPIC_NEVER => None,
2405 at => Some(at),
2406 },
2407 Err(_) => None,
2408 }
2409}
2410
2411/// The `idx_topic` value for a frame: its expiry in ms as a big-endian u64, or
2412/// [`IDX_TOPIC_NEVER`]. Every entry for the frame -- the exact topic key and
2413/// each prefix key -- gets the same eight bytes, so a topic scan can drop an
2414/// expired id without a point read into `stream`.
2415fn idx_topic_expiry_value(frame: &Frame) -> [u8; 8] {
2416 expires_at(frame).unwrap_or(IDX_TOPIC_NEVER).to_be_bytes()
2417}
2418
2419/// Has the frame behind this `idx_topic` value expired as of `now`? A value
2420/// that is not eight bytes -- an entry written before the index carried an
2421/// expiry -- reads as "unknown" and answers `false`, so the caller falls back
2422/// to reading the frame and letting [`is_expired`] decide. Both shapes can sit
2423/// in one index.
2424///
2425/// The arithmetic matches [`expires_at`] exactly, so this never hides a frame
2426/// [`is_expired`] would keep.
2427#[inline]
2428fn idx_topic_is_expired(value: &[u8], now: u64) -> bool {
2429 match <[u8; 8]>::try_from(value) {
2430 Ok(bytes) => {
2431 let expires_at = u64::from_be_bytes(bytes);
2432 expires_at != IDX_TOPIC_NEVER && now >= expires_at
2433 }
2434 Err(_) => false,
2435 }
2436}
2437
2438/// The frame id an `idx_topic` hit points at, or `None` to skip the hit
2439/// entirely.
2440///
2441/// The entry's value carries the frame's expiry, so an already expired id is
2442/// dropped here without the point read into `stream` that seeing its ttl would
2443/// otherwise take. `now` is sampled once when the iterator is built, which only
2444/// ever skips fewer frames than a fresh sample would: [`is_expired`] still runs
2445/// on everything that gets through, so the two never disagree about what is
2446/// visible.
2447#[inline]
2448fn idx_topic_hit_id(guard: fjall::Guard, now: u64) -> Option<Scru128Id> {
2449 let (key, value) = guard.into_inner().ok()?;
2450 if idx_topic_is_expired(&value, now) {
2451 return None;
2452 }
2453 Some(idx_topic_frame_id_from_key(&key))
2454}
2455
2456/// The `idx_topic` key range covering one index prefix, opening at `start`
2457/// when there is one.
2458///
2459/// Every key under a prefix is that prefix followed by the frame's 16 byte id,
2460/// and ids sort ascending, so a bound on the id is a bound on the key. Seeking
2461/// to it beats walking the topic from its first entry and discarding
2462/// everything below: on a topic holding 500k frames, reading `after` a recent
2463/// id touches a handful of index entries instead of all 500k.
2464///
2465/// The upper bound is the prefix plus all ones, the largest key the prefix can
2466/// hold. A topic never contains the NUL delimiter, so no other topic's keys
2467/// fall inside the range.
2468fn idx_topic_range(
2469 prefix: Vec<u8>,
2470 start: Option<(Scru128Id, bool)>,
2471) -> (Bound<Vec<u8>>, Bound<Vec<u8>>) {
2472 fn key_at(prefix: &[u8], id: &[u8; 16]) -> Vec<u8> {
2473 let mut key = Vec::with_capacity(prefix.len() + 16);
2474 key.extend_from_slice(prefix);
2475 key.extend_from_slice(id);
2476 key
2477 }
2478
2479 let hi = Bound::Included(key_at(&prefix, &[0xff; 16]));
2480 let lo = match start {
2481 Some((id, true)) => Bound::Included(key_at(&prefix, id.as_bytes())),
2482 Some((id, false)) => Bound::Excluded(key_at(&prefix, id.as_bytes())),
2483 // Shorter than every key it covers, so it sorts before all of them.
2484 None => Bound::Included(prefix),
2485 };
2486 (lo, hi)
2487}
2488
2489fn idx_topic_key_prefix(topic: &str) -> Vec<u8> {
2490 let mut v = Vec::with_capacity(topic.len() + 1); // topic bytes + delimiter
2491 v.extend(topic.as_bytes()); // topic string as UTF-8 bytes
2492 v.push(NULL_DELIMITER); // Delimiter for variable-sized keys
2493 v
2494}
2495
2496pub(crate) fn idx_topic_key_from_frame(frame: &Frame) -> Result<Vec<u8>, crate::error::Error> {
2497 validate_topic(&frame.topic)?;
2498 let mut v = idx_topic_key_prefix(&frame.topic);
2499 v.extend(frame.id.as_bytes());
2500 Ok(v)
2501}
2502
2503fn idx_topic_frame_id_from_key(key: &[u8]) -> Scru128Id {
2504 let frame_id_bytes = &key[key.len() - 16..];
2505 Scru128Id::from_bytes(frame_id_bytes.try_into().unwrap())
2506}
2507
2508fn deserialize_frame<B1: AsRef<[u8]> + std::fmt::Debug, B2: AsRef<[u8]>>(
2509 record: (B1, B2),
2510) -> Frame {
2511 serde_json::from_slice(record.1.as_ref()).unwrap_or_else(|e| {
2512 // Try to convert the key to a Scru128Id and print in a format that can be copied for deletion
2513 let key_bytes = record.0.as_ref();
2514 if key_bytes.len() == 16 {
2515 if let Ok(bytes) = key_bytes.try_into() {
2516 let id = Scru128Id::from_bytes(bytes);
2517 eprintln!("CORRUPTED_RECORD_ID: {id}");
2518 }
2519 }
2520 let key = std::str::from_utf8(record.0.as_ref()).unwrap();
2521 let value = std::str::from_utf8(record.1.as_ref()).unwrap();
2522 panic!("Failed to deserialize frame: {e} {key} {value}")
2523 })
2524}