1use 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
17pub const SEW_EPOCH_MS: u64 = 1_767_225_600_000;
19pub const TIMESTAMP_BITS: u32 = 42;
21pub const NODE_BITS: u32 = 10;
23pub const SEQUENCE_BITS: u32 = 11;
25pub const MAX_NODE: u16 = 1023;
27pub const MAX_SEQUENCE: u16 = 2047;
29pub const CLOCK_REGRESSION_MAX_WAIT_MS: u64 = 5_000;
31pub const MAX_MS_SINCE_EPOCH: u64 = (1 << TIMESTAMP_BITS) - 1;
33
34const REGRESSION_STEP_MS: u64 = 100;
35
36#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
38pub struct Id(u64);
39
40pub type SpaceId = Id;
42pub type ChannelId = Id;
44pub type MessageId = Id;
46pub type MemberId = Id;
48pub type RoleId = Id;
50pub type CategoryId = Id;
52pub type JobId = Id;
54
55impl Id {
56 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 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 pub const fn get(self) -> u64 {
75 self.0
76 }
77
78 pub const fn from_i64(v: i64) -> Option<Id> {
80 if v < 1 { None } else { Some(Id(v as u64)) }
81 }
82
83 pub const fn to_i64(self) -> i64 {
85 self.0 as i64
86 }
87
88 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 pub const fn ms_since_epoch(self) -> u64 {
102 self.0 >> (NODE_BITS + SEQUENCE_BITS)
103 }
104
105 pub const fn node(self) -> NodeId {
107 NodeId(((self.0 >> SEQUENCE_BITS) & MAX_NODE as u64) as u16)
108 }
109
110 pub const fn sequence(self) -> u16 {
112 (self.0 & MAX_SEQUENCE as u64) as u16
113 }
114
115 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 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
145pub fn id_to_time(id: Id) -> Timestamp {
147 Timestamp::from_unix_ms_saturating(SEW_EPOCH_MS + id.ms_since_epoch())
148}
149
150#[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
167pub(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#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
232pub struct NodeId(u16);
233
234impl NodeId {
235 pub const SINGLE: NodeId = NodeId(0);
237
238 pub const fn new(n: u16) -> Option<NodeId> {
240 if n > MAX_NODE { None } else { Some(NodeId(n)) }
241 }
242
243 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
258pub struct ClockBehind {
259 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#[derive(Debug)]
285pub struct IdGenerator<C: Clock = SystemClock> {
286 node: NodeId,
287 state: Mutex<GenState>,
288 clock: C,
289}
290
291impl IdGenerator<SystemClock> {
292 pub fn new(node: NodeId) -> Self {
294 IdGenerator::with_clock(node, SystemClock)
295 }
296}
297
298impl<C: Clock> IdGenerator<C> {
299 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 pub fn clock(&self) -> &C {
314 &self.clock
315 }
316
317 pub fn next(&self) -> Id {
323 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 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 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 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 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#[derive(Debug, Clone, PartialEq, Eq, Hash)]
403pub struct IdList(Vec<Id>);
404
405#[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 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 pub fn ids(&self) -> &[Id] {
441 &self.0
442 }
443
444 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}