Skip to main content

sew_proto/
id.rs

1//! Time-sortable 64-bit ids.
2//!
3//! Layout, high bit to low bit: `0` | 42 bits ms since the Sew epoch | 10 bits node | 11 bits
4//! sequence. Ids run `1 ..= i64::MAX`; `0` is never valid. JSON form is a decimal string.
5
6use std::borrow::Cow;
7use std::fmt;
8use std::str::FromStr;
9use std::sync::Mutex;
10
11use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
12use serde::{Deserialize, Deserializer, Serialize, Serializer};
13
14pub use crate::clock::{Clock, SystemClock};
15use crate::time::Timestamp;
16
17/// The Sew epoch, 2026-01-01T00:00:00Z, in Unix milliseconds.
18pub const SEW_EPOCH_MS: u64 = 1_767_225_600_000;
19/// Bits holding milliseconds since the Sew epoch.
20pub const TIMESTAMP_BITS: u32 = 42;
21/// Bits holding the node number.
22pub const NODE_BITS: u32 = 10;
23/// Bits holding the per-millisecond sequence.
24pub const SEQUENCE_BITS: u32 = 11;
25/// Highest node number.
26pub const MAX_NODE: u16 = 1023;
27/// Highest sequence number within one millisecond.
28pub const MAX_SEQUENCE: u16 = 2047;
29/// Longest the generator waits for a clock that moved backward before it panics.
30pub const CLOCK_REGRESSION_MAX_WAIT_MS: u64 = 5_000;
31/// Largest millisecond offset the 42-bit field holds.
32pub const MAX_MS_SINCE_EPOCH: u64 = (1 << TIMESTAMP_BITS) - 1;
33
34const REGRESSION_STEP_MS: u64 = 100;
35
36/// A Sew entity id. Invariant: `1 ..= i64::MAX`.
37#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
38pub struct Id(u64);
39
40/// Space id (same [`Id`] type; the alias is for reading only).
41pub type SpaceId = Id;
42/// Channel id.
43pub type ChannelId = Id;
44/// Message id.
45pub type MessageId = Id;
46/// Member id.
47pub type MemberId = Id;
48/// Role id. `@everyone`'s role id equals its space id.
49pub type RoleId = Id;
50/// Category id.
51pub type CategoryId = Id;
52/// Job id.
53pub type JobId = Id;
54
55impl Id {
56    /// Wraps a raw value. `None` for `0` or values above `i64::MAX`.
57    pub const fn new(v: u64) -> Option<Id> {
58        if v == 0 || v > i64::MAX as u64 {
59            None
60        } else {
61            Some(Id(v))
62        }
63    }
64
65    /// Wraps a constant. Panics (a compile error in const context) when the value is invalid.
66    pub const fn new_const(v: u64) -> Id {
67        match Id::new(v) {
68            Some(id) => id,
69            None => panic!("sew id: constant out of range"),
70        }
71    }
72
73    /// The raw value.
74    pub const fn get(self) -> u64 {
75        self.0
76    }
77
78    /// Converts from a Postgres `bigint`. `None` for values below 1.
79    pub const fn from_i64(v: i64) -> Option<Id> {
80        if v < 1 { None } else { Some(Id(v as u64)) }
81    }
82
83    /// Converts to a Postgres `bigint`. Always positive.
84    pub const fn to_i64(self) -> i64 {
85        self.0 as i64
86    }
87
88    /// Builds an id from its parts. `None` if a part is out of range or the result is `0`.
89    pub const fn from_parts(ms_since_epoch: u64, node: NodeId, seq: u16) -> Option<Id> {
90        if ms_since_epoch > MAX_MS_SINCE_EPOCH || seq > MAX_SEQUENCE {
91            return None;
92        }
93        Id::new(
94            (ms_since_epoch << (NODE_BITS + SEQUENCE_BITS))
95                | ((node.0 as u64) << SEQUENCE_BITS)
96                | seq as u64,
97        )
98    }
99
100    /// Milliseconds since the Sew epoch.
101    pub const fn ms_since_epoch(self) -> u64 {
102        self.0 >> (NODE_BITS + SEQUENCE_BITS)
103    }
104
105    /// The node that made this id.
106    pub const fn node(self) -> NodeId {
107        NodeId(((self.0 >> SEQUENCE_BITS) & MAX_NODE as u64) as u16)
108    }
109
110    /// The sequence within its millisecond.
111    pub const fn sequence(self) -> u16 {
112        (self.0 & MAX_SEQUENCE as u64) as u16
113    }
114
115    /// The smallest id that can exist at `t` (for time-based cursors). Times before the epoch
116    /// give `Id(1)`; times past the id range give the largest id.
117    pub fn min_for_time(t: Timestamp) -> Id {
118        let ms = clamp_ms(t);
119        match Id::from_parts(ms, NodeId(0), 0) {
120            Some(id) => id,
121            None => Id(1),
122        }
123    }
124
125    /// The largest id that can exist at `t`.
126    pub fn max_for_time(t: Timestamp) -> Id {
127        let ms = clamp_ms(t);
128        match Id::from_parts(ms, NodeId(MAX_NODE), MAX_SEQUENCE) {
129            Some(id) => id,
130            None => Id(i64::MAX as u64),
131        }
132    }
133}
134
135fn clamp_ms(t: Timestamp) -> u64 {
136    let unix = t.unix_ms();
137    let since = unix.saturating_sub(SEW_EPOCH_MS as i64);
138    if since <= 0 {
139        0
140    } else {
141        (since as u64).min(MAX_MS_SINCE_EPOCH)
142    }
143}
144
145/// The ms-precision UTC time an id was made.
146pub fn id_to_time(id: Id) -> Timestamp {
147    Timestamp::from_unix_ms_saturating(SEW_EPOCH_MS + id.ms_since_epoch())
148}
149
150/// Error parsing an [`Id`].
151#[derive(Debug, Clone, PartialEq, Eq)]
152pub struct IdParseError(String);
153
154impl fmt::Display for IdParseError {
155    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
156        write!(
157            f,
158            "invalid id {:?}: expected a decimal string [1-9][0-9]{{0,18}} no larger than {}",
159            self.0,
160            i64::MAX
161        )
162    }
163}
164
165impl std::error::Error for IdParseError {}
166
167/// Parses the strict decimal form: `[1-9][0-9]{0,18}`, at most `i64::MAX`.
168pub(crate) fn parse_id_str(s: &str) -> Option<Id> {
169    let b = s.as_bytes();
170    if b.is_empty() || b.len() > 19 || b[0] == b'0' || !b.iter().all(u8::is_ascii_digit) {
171        return None;
172    }
173    s.parse::<u64>().ok().and_then(Id::new)
174}
175
176impl FromStr for Id {
177    type Err = IdParseError;
178
179    fn from_str(s: &str) -> Result<Self, Self::Err> {
180        parse_id_str(s).ok_or_else(|| IdParseError(s.to_owned()))
181    }
182}
183
184impl fmt::Display for Id {
185    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
186        fmt::Display::fmt(&self.0, f)
187    }
188}
189
190impl Serialize for Id {
191    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
192        serializer.collect_str(self)
193    }
194}
195
196impl<'de> Deserialize<'de> for Id {
197    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
198        struct V;
199        impl serde::de::Visitor<'_> for V {
200            type Value = Id;
201            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
202                f.write_str("an id as a decimal string")
203            }
204            fn visit_str<E: serde::de::Error>(self, s: &str) -> Result<Id, E> {
205                s.parse().map_err(E::custom)
206            }
207        }
208        deserializer.deserialize_str(V)
209    }
210}
211
212impl JsonSchema for Id {
213    fn inline_schema() -> bool {
214        true
215    }
216
217    fn schema_name() -> Cow<'static, str> {
218        "Id".into()
219    }
220
221    fn json_schema(_: &mut SchemaGenerator) -> Schema {
222        json_schema!({
223            "type": "string",
224            "pattern": "^[1-9][0-9]{0,18}$",
225            "description": "A Sew id: a decimal string of a 64-bit time-sortable id (1 to 9223372036854775807)."
226        })
227    }
228}
229
230/// A node number, `0 ..= 1023`. A single-node install uses [`NodeId::SINGLE`].
231#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
232pub struct NodeId(u16);
233
234impl NodeId {
235    /// Node 0, used by every single-node install.
236    pub const SINGLE: NodeId = NodeId(0);
237
238    /// `None` for values above 1023.
239    pub const fn new(n: u16) -> Option<NodeId> {
240        if n > MAX_NODE { None } else { Some(NodeId(n)) }
241    }
242
243    /// The raw value.
244    pub const fn get(self) -> u16 {
245        self.0
246    }
247}
248
249#[derive(Debug)]
250struct GenState {
251    last_ms: u64,
252    seq: u16,
253    issued: bool,
254}
255
256/// The clock reads behind the last issued id ([`IdGenerator::try_next`]).
257#[derive(Debug, Clone, Copy, PartialEq, Eq)]
258pub struct ClockBehind {
259    /// How far the clock reads behind the last issued id's millisecond.
260    pub behind_ms: u64,
261}
262
263impl fmt::Display for ClockBehind {
264    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
265        write!(
266            f,
267            "sew id: the clock reads {} ms behind the last issued id",
268            self.behind_ms
269        )
270    }
271}
272
273impl std::error::Error for ClockBehind {}
274
275/// Makes unique, strictly increasing ids for one node.
276///
277/// - Same millisecond: the sequence goes up. After 2,048 ids in one millisecond it yields
278///   through [`Clock::sleep_ms`]`(0)` until the clock shows a later millisecond.
279/// - Clock behind the last id: [`IdGenerator::next`] waits in steps of at most 100 ms and, after
280///   5,000 ms of waiting, panics with `sew id: clock moved backward`; [`IdGenerator::try_next`]
281///   returns [`ClockBehind`] at once. Neither ever emits a duplicate or smaller id.
282/// - Clock outside the id range (before the Sew epoch or past 42 bits): it panics with
283///   `sew id: clock outside id range`.
284#[derive(Debug)]
285pub struct IdGenerator<C: Clock = SystemClock> {
286    node: NodeId,
287    state: Mutex<GenState>,
288    clock: C,
289}
290
291impl IdGenerator<SystemClock> {
292    /// A generator on the system clock.
293    pub fn new(node: NodeId) -> Self {
294        IdGenerator::with_clock(node, SystemClock)
295    }
296}
297
298impl<C: Clock> IdGenerator<C> {
299    /// A generator on the given clock.
300    pub fn with_clock(node: NodeId, clock: C) -> Self {
301        IdGenerator {
302            node,
303            state: Mutex::new(GenState {
304                last_ms: 0,
305                seq: 0,
306                issued: false,
307            }),
308            clock,
309        }
310    }
311
312    /// The clock this generator reads.
313    pub fn clock(&self) -> &C {
314        &self.clock
315    }
316
317    /// The next id.
318    ///
319    /// # Panics
320    ///
321    /// When the clock stays behind the last id for 5 s, or reads outside the id range.
322    pub fn next(&self) -> Id {
323        // A panic while holding the lock only happens on the fatal paths below; a poisoned
324        // state is still consistent (it holds the last issued id).
325        let mut st = self.state.lock().unwrap_or_else(|e| e.into_inner());
326        let mut waited: u64 = 0;
327        loop {
328            let gap = match self.issue(&mut st) {
329                Ok(id) => return id,
330                Err(ClockBehind { behind_ms }) => behind_ms,
331            };
332            // The clock moved backward.
333            if waited >= CLOCK_REGRESSION_MAX_WAIT_MS {
334                panic!(
335                    "sew id: clock moved backward by {gap} ms and did not recover within {CLOCK_REGRESSION_MAX_WAIT_MS} ms"
336                );
337            }
338            let step = gap
339                .min(REGRESSION_STEP_MS)
340                .min(CLOCK_REGRESSION_MAX_WAIT_MS - waited);
341            self.clock.sleep_ms(step);
342            waited += step;
343        }
344    }
345
346    /// The next id without waiting for a clock that moved backward: [`ClockBehind`] at once,
347    /// with the gap to the last issued id. A caller that must not block
348    /// (a server request thread) refuses the work and retries later instead. The state is
349    /// unchanged by a refusal, so ids stay unique and increasing. Same-millisecond overflow
350    /// still yields (through [`Clock::sleep_ms`]`(0)`) until the next millisecond.
351    ///
352    /// # Panics
353    ///
354    /// When the clock reads outside the id range.
355    pub fn try_next(&self) -> Result<Id, ClockBehind> {
356        let mut st = self.state.lock().unwrap_or_else(|e| e.into_inner());
357        self.issue(&mut st)
358    }
359
360    /// One attempt: an id, or the gap when the clock reads behind the last id.
361    fn issue(&self, st: &mut GenState) -> Result<Id, ClockBehind> {
362        loop {
363            let ms = self.ms_since_epoch_now();
364            if !st.issued || ms > st.last_ms {
365                st.last_ms = ms;
366                st.seq = 0;
367                st.issued = true;
368                if ms == 0 && self.node.0 == 0 {
369                    // Id 0 is invalid; skip sequence 0 at the epoch millisecond.
370                    st.seq = 1;
371                }
372                break;
373            }
374            if ms == st.last_ms {
375                if st.seq < MAX_SEQUENCE {
376                    st.seq += 1;
377                    break;
378                }
379                self.clock.sleep_ms(0);
380                continue;
381            }
382            return Err(ClockBehind {
383                behind_ms: st.last_ms - ms,
384            });
385        }
386        match Id::from_parts(st.last_ms, self.node, st.seq) {
387            Some(id) => Ok(id),
388            None => panic!("sew id: clock outside id range"),
389        }
390    }
391
392    fn ms_since_epoch_now(&self) -> u64 {
393        let now = self.clock.now_unix_ms();
394        if now < SEW_EPOCH_MS || now - SEW_EPOCH_MS > MAX_MS_SINCE_EPOCH {
395            panic!("sew id: clock outside id range (unix ms {now})");
396        }
397        now - SEW_EPOCH_MS
398    }
399}
400
401/// A comma-separated list of 1–100 distinct ids, as in `GET /api/v1/messages?ids=1,2,3`.
402#[derive(Debug, Clone, PartialEq, Eq, Hash)]
403pub struct IdList(Vec<Id>);
404
405/// Error parsing an [`IdList`].
406#[derive(Debug, Clone, PartialEq, Eq)]
407pub struct IdListError(String);
408
409impl fmt::Display for IdListError {
410    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
411        write!(f, "invalid id list: {}", self.0)
412    }
413}
414
415impl std::error::Error for IdListError {}
416
417impl IdList {
418    /// Builds a list, checking the 1–100 length and uniqueness rules.
419    pub fn new(ids: Vec<Id>) -> Result<Self, IdListError> {
420        if ids.is_empty() {
421            return Err(IdListError("empty".into()));
422        }
423        if ids.len() > crate::limits::IDS_PER_QUERY_MAX {
424            return Err(IdListError(format!(
425                "{} ids; at most {}",
426                ids.len(),
427                crate::limits::IDS_PER_QUERY_MAX
428            )));
429        }
430        let mut seen = std::collections::HashSet::with_capacity(ids.len());
431        for id in &ids {
432            if !seen.insert(*id) {
433                return Err(IdListError(format!("duplicate id {id}")));
434            }
435        }
436        Ok(IdList(ids))
437    }
438
439    /// The ids in request order.
440    pub fn ids(&self) -> &[Id] {
441        &self.0
442    }
443
444    /// Consumes the list.
445    pub fn into_vec(self) -> Vec<Id> {
446        self.0
447    }
448}
449
450impl FromStr for IdList {
451    type Err = IdListError;
452
453    fn from_str(s: &str) -> Result<Self, Self::Err> {
454        if s.is_empty() {
455            return Err(IdListError("empty".into()));
456        }
457        let mut ids = Vec::new();
458        for part in s.split(',') {
459            let id = parse_id_str(part).ok_or_else(|| IdListError(format!("bad id {part:?}")))?;
460            ids.push(id);
461        }
462        IdList::new(ids)
463    }
464}
465
466impl fmt::Display for IdList {
467    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
468        for (i, id) in self.0.iter().enumerate() {
469            if i > 0 {
470                f.write_str(",")?;
471            }
472            fmt::Display::fmt(id, f)?;
473        }
474        Ok(())
475    }
476}
477
478impl Serialize for IdList {
479    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
480        serializer.collect_str(self)
481    }
482}
483
484impl<'de> Deserialize<'de> for IdList {
485    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
486        let s = Cow::<'de, str>::deserialize(deserializer)?;
487        s.parse().map_err(serde::de::Error::custom)
488    }
489}
490
491impl JsonSchema for IdList {
492    fn inline_schema() -> bool {
493        true
494    }
495
496    fn schema_name() -> Cow<'static, str> {
497        "IdList".into()
498    }
499
500    fn json_schema(_: &mut SchemaGenerator) -> Schema {
501        json_schema!({
502            "type": "string",
503            "pattern": "^[1-9][0-9]{0,18}(,[1-9][0-9]{0,18}){0,99}$",
504            "description": "1 to 100 distinct ids, comma-separated."
505        })
506    }
507}