Skip to main content

object_log/
sequencer.rs

1//! The sequencing seam: offset assignment, the offset→location index, and
2//! retention. The engine owns storage + buffering; a `Sequencer` owns offsets.
3
4use crate::ObjectLogError;
5use serde::{Deserialize, Serialize};
6use std::collections::{HashMap, HashSet};
7use std::sync::Mutex;
8
9/// Opaque, engine-visible identifier for an independent offset stream (one dense,
10/// monotonic offset space). A Kafka broker maps `(topic, partition)` onto one of
11/// these; a WAL maps a shard. object-log treats it as an opaque key.
12#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
13pub struct PartitionKey(pub String);
14
15impl PartitionKey {
16    /// Borrow the key as a string slice.
17    pub fn as_str(&self) -> &str {
18        &self.0
19    }
20}
21
22/// Where a batch's bytes live inside its object. **Authored by the engine** (it
23/// owns object layout); the sequencer stores it in the index and returns it from
24/// [`Sequencer::lookup`].
25#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
26pub struct BatchLocation {
27    /// Key of the object holding the batch.
28    pub object_id: String,
29    /// Byte offset of the batch within the object.
30    pub byte_start: u32,
31    /// Byte length of the batch.
32    pub byte_len: u32,
33}
34
35/// One batch presented to [`Sequencer::commit`]. The engine fills `partition`,
36/// `record_count`, and `location` (all engine-visible); `meta` is forwarded
37/// **uninterpreted** — only the sequencer reads it.
38pub struct CommitBatch<'a, M> {
39    /// The offset stream this batch belongs to.
40    pub partition: PartitionKey,
41    /// Number of records in the batch (offsets advance by this).
42    pub record_count: i32,
43    /// Where the batch lives in its (already-durable) object.
44    pub location: BatchLocation,
45    /// Sequencer-private metadata (e.g. idempotent-producer identity). Opaque to
46    /// the engine.
47    pub meta: &'a M,
48    /// Fence epoch the caller believes owns this partition. [`ManifestSequencer`](crate::ManifestSequencer)
49    /// rejects the batch when the stored index epoch differs. Other sequencers
50    /// ignore it.
51    pub epoch: u64,
52}
53
54/// Per-batch result of [`Sequencer::commit`].
55#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
56pub enum CommitOutcome {
57    /// A fresh, contiguous offset range was assigned starting at `base_offset`.
58    Assigned {
59        /// First offset assigned to the batch.
60        base_offset: i64,
61        /// Number of records committed.
62        record_count: i32,
63    },
64    /// A retried batch was recognized as already committed (idempotent no-op);
65    /// the original `base_offset` is returned.
66    Duplicate {
67        /// The originally assigned first offset.
68        base_offset: i64,
69    },
70    /// This batch was not indexed. Other batches in the same call may already
71    /// be durable. The caller must rewrite this batch in a new data object
72    /// rather than reuse the offsets it expected.
73    Rejected {
74        /// Why the conditional update did not land.
75        reason: String,
76    },
77}
78
79/// An index entry resolving an offset range to its bytes.
80#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
81pub struct IndexEntry {
82    /// Where the batch's bytes live.
83    pub location: BatchLocation,
84    /// First offset in the batch.
85    pub base_offset: i64,
86    /// Number of records in the batch.
87    pub record_count: i32,
88}
89
90/// The linearization point: assigns offsets to durably-stored batches and owns
91/// the offset→location index.
92///
93/// **Synchronous on purpose** — a lin-point is a critical section, not async I/O.
94/// The engine calls it from its flush worker (a dedicated thread / blocking
95/// task), so a blocking implementation (a `Mutex`, a SQL transaction) is fine.
96///
97/// Contract: [`commit`](Sequencer::commit) is **atomic across the whole slice**
98/// (all supplied batches commit together or not at all), and the engine
99/// presents batches for any single [`PartitionKey`] in arrival order and never
100/// splits one partition across concurrent `commit` calls.
101pub trait Sequencer: Send + Sync {
102    /// Sequencer-private per-batch metadata, forwarded uninterpreted by the
103    /// engine. object-log's default sequencers use `()`; a Kafka coordinator uses
104    /// its producer-identity fields.
105    type Meta: Send + Sync;
106
107    /// Opt in to atomic commits containing already-durable batches from several
108    /// data objects, in creation order. Default preserves one-object calls for
109    /// custom sequencers that rely on that boundary.
110    fn supports_multi_object_commit(&self) -> bool {
111        false
112    }
113
114    /// Assign offsets to durably uploaded batches and persist the index.
115    /// By default these belong to one object; an opted-in implementation may
116    /// receive several objects in one ordered call.
117    /// Returns one [`CommitOutcome`] per input batch, in order.
118    ///
119    /// On `Err`, nothing from this call was indexed. A [`CommitOutcome::Rejected`]
120    /// batch was not indexed either; earlier batches in the same call may already
121    /// be durable when the sequencer commits one partition at a time.
122    fn commit(
123        &self,
124        batches: &[CommitBatch<'_, Self::Meta>],
125    ) -> Result<Vec<CommitOutcome>, ObjectLogError>;
126
127    /// Resolve `fetch_offset` to the ordered index entries covering it onward.
128    fn lookup(
129        &self,
130        partition: &PartitionKey,
131        fetch_offset: i64,
132    ) -> Result<Vec<IndexEntry>, ObjectLogError>;
133
134    /// The next offset to be assigned (index-only; no object reads).
135    fn high_watermark(&self, partition: &PartitionKey) -> Result<i64, ObjectLogError>;
136
137    /// The first readable offset (advances on [`truncate_before`](Sequencer::truncate_before)).
138    fn log_start_offset(&self, partition: &PartitionKey) -> Result<i64, ObjectLogError>;
139
140    /// Retention MECHANISM (not policy): drop index entries below `offset` and
141    /// return object ids that now have **no** live references from **any**
142    /// partition (objects are multiplexed and shared), for the engine to delete.
143    fn truncate_before(
144        &self,
145        partition: &PartitionKey,
146        offset: i64,
147    ) -> Result<Vec<String>, ObjectLogError>;
148
149    /// Move the stored fence epoch for `partition` from `expected` to `new_epoch`.
150    ///
151    /// The default succeeds without storing anything. [`ManifestSequencer`](crate::ManifestSequencer)
152    /// compares `expected` with the epoch in that partition's index and fails
153    /// when they differ. A missing index is not an error: the next commit records
154    /// its epoch.
155    fn fence_epoch(
156        &self,
157        partition: &PartitionKey,
158        expected: u64,
159        new_epoch: u64,
160    ) -> Result<(), ObjectLogError> {
161        let _ = (partition, expected, new_epoch);
162        Ok(())
163    }
164}
165
166/// Per-partition in-memory index state.
167#[derive(Default)]
168struct PartState {
169    next_offset: i64,
170    log_start: i64,
171    entries: Vec<IndexEntry>,
172}
173
174/// A single-node, in-memory [`Sequencer`] (`Meta = ()`): assigns dense offsets and
175/// keeps the offset→location index in memory.
176///
177/// The log *bytes* live durably in the `BlobStore`, but this index does not
178/// survive a restart — use it for tests and single-process work, or persist the
179/// index yourself for a crash-durable standalone log.
180#[derive(Default)]
181pub struct InMemorySequencer {
182    state: Mutex<HashMap<PartitionKey, PartState>>,
183}
184
185impl InMemorySequencer {
186    /// Create an empty sequencer.
187    pub fn new() -> Self {
188        Self::default()
189    }
190
191    /// Object ids referenced by any live index entry (for orphan reaping).
192    pub fn live_object_ids(&self) -> HashSet<String> {
193        let state = self.state.lock().expect("poisoned");
194        let mut live = HashSet::new();
195        for ps in state.values() {
196            for e in &ps.entries {
197                live.insert(e.location.object_id.clone());
198            }
199        }
200        live
201    }
202}
203
204impl Sequencer for InMemorySequencer {
205    type Meta = ();
206
207    fn supports_multi_object_commit(&self) -> bool {
208        true
209    }
210
211    fn commit(
212        &self,
213        batches: &[CommitBatch<'_, Self::Meta>],
214    ) -> Result<Vec<CommitOutcome>, ObjectLogError> {
215        let mut state = self.state.lock().expect("poisoned");
216        let mut outcomes = Vec::with_capacity(batches.len());
217        for cb in batches {
218            let ps = state.entry(cb.partition.clone()).or_default();
219            let base = ps.next_offset;
220            ps.entries.push(IndexEntry {
221                location: cb.location.clone(),
222                base_offset: base,
223                record_count: cb.record_count,
224            });
225            ps.next_offset = base + cb.record_count as i64;
226            outcomes.push(CommitOutcome::Assigned {
227                base_offset: base,
228                record_count: cb.record_count,
229            });
230        }
231        Ok(outcomes)
232    }
233
234    fn lookup(
235        &self,
236        partition: &PartitionKey,
237        fetch_offset: i64,
238    ) -> Result<Vec<IndexEntry>, ObjectLogError> {
239        let state = self.state.lock().expect("poisoned");
240        let Some(ps) = state.get(partition) else {
241            return Ok(Vec::new());
242        };
243        Ok(ps
244            .entries
245            .iter()
246            .filter(|e| e.base_offset + e.record_count as i64 > fetch_offset)
247            .cloned()
248            .collect())
249    }
250
251    fn high_watermark(&self, partition: &PartitionKey) -> Result<i64, ObjectLogError> {
252        Ok(self
253            .state
254            .lock()
255            .expect("poisoned")
256            .get(partition)
257            .map_or(0, |ps| ps.next_offset))
258    }
259
260    fn log_start_offset(&self, partition: &PartitionKey) -> Result<i64, ObjectLogError> {
261        Ok(self
262            .state
263            .lock()
264            .expect("poisoned")
265            .get(partition)
266            .map_or(0, |ps| ps.log_start))
267    }
268
269    fn truncate_before(
270        &self,
271        partition: &PartitionKey,
272        offset: i64,
273    ) -> Result<Vec<String>, ObjectLogError> {
274        let mut state = self.state.lock().expect("poisoned");
275        let mut dropped: Vec<String> = Vec::new();
276        match state.get_mut(partition) {
277            Some(ps) => {
278                for e in ps.entries.iter() {
279                    if e.base_offset + e.record_count as i64 <= offset {
280                        dropped.push(e.location.object_id.clone());
281                    }
282                }
283                ps.entries
284                    .retain(|e| e.base_offset + e.record_count as i64 > offset);
285                if offset > ps.log_start {
286                    ps.log_start = offset.min(ps.next_offset);
287                }
288            }
289            None => return Ok(Vec::new()),
290        }
291        // An object is reclaimable only when no entry in ANY partition references it.
292        let mut live: HashSet<String> = HashSet::new();
293        for ps in state.values() {
294            for e in &ps.entries {
295                live.insert(e.location.object_id.clone());
296            }
297        }
298        let mut dead: Vec<String> = Vec::new();
299        let mut seen: HashSet<String> = HashSet::new();
300        for oid in dropped {
301            if !live.contains(&oid) && seen.insert(oid.clone()) {
302                dead.push(oid);
303            }
304        }
305        Ok(dead)
306    }
307}