1pub mod v1;
7pub mod v2;
8mod base64url;
9
10pub use v2::*;
11
12use std::error::Error;
13use std::fmt;
14use std::time::{Duration, SystemTime, UNIX_EPOCH};
15
16pub const ORBIT_EPOCH_UNIX_MS: u64 = 1_767_225_600_000;
17pub const DEFAULT_CLOCK_ROLLBACK_TOLERANCE_MS: u64 = 5_000;
18
19#[derive(Clone, Copy, Debug, Eq, PartialEq)]
20pub enum OrbitErrorCode {
21 InvalidType,
22 InvalidNode,
23 InvalidSequence,
24 InvalidTimestamp,
25 InvalidDecimal,
26 InvalidBase64Url,
28 InvalidFormatVersion,
30 InvalidRegion,
32 InvalidTenant,
34 InvalidReserved,
36 ClockRollback,
37 SequenceExhausted,
38 NodeOwnershipLost,
39}
40
41impl OrbitErrorCode {
42 pub const fn as_str(self) -> &'static str {
44 match self {
45 Self::InvalidType => "INVALID_TYPE",
46 Self::InvalidNode => "INVALID_NODE",
47 Self::InvalidSequence => "INVALID_SEQUENCE",
48 Self::InvalidTimestamp => "INVALID_TIMESTAMP",
49 Self::InvalidDecimal => "INVALID_DECIMAL",
50 Self::InvalidBase64Url => "INVALID_BASE64URL",
51 Self::InvalidFormatVersion => "INVALID_FORMAT_VERSION",
52 Self::InvalidRegion => "INVALID_REGION",
53 Self::InvalidTenant => "INVALID_TENANT",
54 Self::InvalidReserved => "INVALID_RESERVED",
55 Self::ClockRollback => "CLOCK_ROLLBACK",
56 Self::SequenceExhausted => "SEQUENCE_EXHAUSTED",
57 Self::NodeOwnershipLost => "NODE_OWNERSHIP_LOST",
58 }
59 }
60}
61
62impl fmt::Display for OrbitErrorCode {
63 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
64 f.write_str(self.as_str())
65 }
66}
67
68#[derive(Clone, Debug, Eq, PartialEq)]
69pub struct OrbitError {
70 pub code: OrbitErrorCode,
71 message: String,
72}
73
74impl OrbitError {
75 pub fn new(code: OrbitErrorCode, message: impl Into<String>) -> Self {
76 Self { code, message: message.into() }
77 }
78}
79
80impl fmt::Display for OrbitError {
81 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
82 write!(f, "{}: {}", self.code, self.message)
83 }
84}
85
86impl Error for OrbitError {}
87
88pub trait OrbitClock: Send + Sync {
90 fn current_orbit_timestamp_ms(&self) -> i64;
91}
92
93impl<F> OrbitClock for F
94where
95 F: Fn() -> i64 + Send + Sync,
96{
97 fn current_orbit_timestamp_ms(&self) -> i64 {
98 self()
99 }
100}
101
102#[derive(Debug, Default)]
103pub struct SystemOrbitClock;
104
105impl OrbitClock for SystemOrbitClock {
106 fn current_orbit_timestamp_ms(&self) -> i64 {
107 let unix_ms = SystemTime::now()
108 .duration_since(UNIX_EPOCH)
109 .unwrap_or(Duration::ZERO)
110 .as_millis() as i128;
111 (unix_ms - i128::from(ORBIT_EPOCH_UNIX_MS)) as i64
112 }
113}
114
115#[derive(Clone, Copy, Debug, Eq, PartialEq)]
116pub enum SequenceExhaustedMode {
117 Wait,
118 Fail,
119}