armour-core 0.1.0

Core types for armour ecosystem
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
use std::{
    cell::Cell,
    fmt::Debug,
    marker::PhantomData,
    str::FromStr,
    sync::atomic::{AtomicU8, Ordering},
    time::{Duration, SystemTime},
};

#[cfg(feature = "bytemuck")]
use bytemuck::{Pod, TransparentWrapper, Zeroable};
use rapira::{Rapira, RapiraError};
use rend::u64_be;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout};

use crate::{
    IdStr, Typ,
    enc::IdHasher,
    error::ArmourError,
    get_type::GetType,
    key_part::{KeyPart, MILLISECOND_BITS},
    key_type::KeyType,
    num_ops::g8bits,
};

type Result<T, E = ArmourError> = core::result::Result<T, E>;

/// different from the unix timestamp epoch in milliseconds
///
/// 2023-04-09 0:00:00 UTC
const TS_DIFF: u64 = 0x187_6350_0000;

const TS_BITS: u32 = 40;
const TS_MAX: u64 = (1 << TS_BITS) - 1;
// 64 - 40 = 24
const TS_SHIFT: u32 = u64::BITS - TS_BITS;

// 2^8 = 256
pub(crate) const SHARD_BITS: u32 = 8;
// 255
pub const SHARD_ID_MAX: u64 = (1 << SHARD_BITS) - 1;

/// 16 bits
const SEQ_BITS: u32 = u64::BITS - TS_BITS - SHARD_BITS;
/// 65_535 max sequence
const SEQ_MAX: u64 = (1 << SEQ_BITS) - 1;

// 2^3 = 8
const SHARD_INST_BITS: u32 = 3;
// 7
pub const SHARD_INSTANCE_ID_MAX: u64 = (1 << SHARD_INST_BITS) - 1;
// 5 + 16 = 21
const SHARD_INSTANCE_SHIFT: u32 = SHARD_THREAD_BITS + SEQ_BITS;

// 2^5 = 32
pub const SHARD_THREAD_BITS: u32 = 5;
// 31
pub const SHARD_THREAD_ID_MAX: u64 = (1 << SHARD_THREAD_BITS) - 1;

#[derive(Debug, Clone, Copy)]
struct SeqForMs {
    /// timestamp in milliseconds
    ts: u64,
    seq: u64,
    count: u64,
}

impl SeqForMs {
    #[cfg(feature = "std")]
    #[inline]
    fn with_ts_and_rand_seq(ts: u64) -> Self {
        use rand::{RngExt, rng};

        let seq = rng().random_range(0..=SEQ_MAX);

        SeqForMs { ts, seq, count: 0 }
    }

    #[cold]
    fn wait_inc(self, ts: u64, duration: Duration) -> Self {
        tracing::info!(?duration, "wait_inc");
        let nanos = duration.subsec_nanos() % 1_000_000;
        let wait_nanos = 1_000_000 - nanos;
        std::thread::sleep(Duration::from_nanos(wait_nanos as u64));

        SeqForMs::with_ts_and_rand_seq(ts + 1)
    }

    #[inline]
    fn increment(mut self, ts: u64, duration: Duration) -> Self {
        if self.count == SEQ_MAX {
            self.wait_inc(ts, duration)
        } else {
            if self.seq == SEQ_MAX {
                self.seq = 0;
            } else {
                self.seq += 1;
            }
            self.count += 1;
            self
        }
    }
}

static THREAD_SEQ: AtomicU8 = AtomicU8::new(0);

thread_local! {
    static SEQ_CHECK: Cell<SeqForMs> = Cell::new(SeqForMs::with_ts_and_rand_seq(0));
    static THREAD_ID: Cell<u8> = Cell::new(THREAD_SEQ.fetch_add(1, Ordering::Relaxed));
}

/// - 64bit id [--timestamp(40)--|--shard_id(8)--|--seq_id(16)--]
/// - 40 bit - timestamp (in milliseconds) started from 2023-04-09 0:00:00 UTC, 34 years available (from 2023 to 2057)
/// - 8 bit - shard_id ([datacenter_id / instance_id] with thread_id), 256 values
/// - 16 bit - random sequence id (unique for thread / per thread), 65_536 values
/// - Blowfish for encryption
/// - ZBASE32 for encoding into 13 length string (example: "ifs1gp9dw8hdw")
/// - create ~ 50ns (~ 21k in 1ms or 21m in 1s) in 1 thread
///
/// Notes:
/// - checks timestamp and shard_id when deserialized from string
/// - Fuid is not inlined for InlineArray
#[derive(Hash, IntoBytes, FromBytes, Immutable, KnownLayout)]
#[cfg_attr(
    feature = "rkyv",
    derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)
)]
#[cfg_attr(feature = "bytemuck", derive(TransparentWrapper))]
#[cfg_attr(feature = "bytemuck", transparent(u64_be))]
#[cfg_attr(feature = "bitcode", derive(bitcode::Encode, bitcode::Decode))]
#[repr(transparent)]
pub struct Fuid<H>(pub u64_be, PhantomData<H>);

#[cfg(feature = "bytemuck")]
unsafe impl<T> Zeroable for Fuid<T> {}
#[cfg(feature = "bytemuck")]
unsafe impl<T: 'static> Pod for Fuid<T> {}

impl<T> Clone for Fuid<T> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<T> Copy for Fuid<T> {}

impl<H> Fuid<H> {
    pub fn from_thread() -> Self {
        let thread_id = THREAD_ID.get();
        Self::with_shard(thread_id as u64)
    }

    /// - 3 bit - instance id (datacenter id / shard id) (max 7)
    /// - 5 bit - thread id (max 31)
    /// - instance_id (datacenter) < 8 and thread_id (worker) < 32
    #[cfg(feature = "std")]
    #[inline]
    pub fn with_inst_thread(instance_id: u64, thread_id: u64) -> Self {
        assert!(instance_id <= SHARD_INSTANCE_ID_MAX);
        assert!(thread_id <= SHARD_THREAD_ID_MAX);

        let shard_id = (instance_id << SHARD_THREAD_BITS) | thread_id;
        Self::with_shard(shard_id)
    }

    /// Create a new Fuid.
    /// - shard_id < 256
    #[cfg(feature = "std")]
    pub fn with_shard(shard_id: u64) -> Self {
        assert!(shard_id <= SHARD_ID_MAX);

        let now = SystemTime::now();
        // in ms
        #[allow(clippy::unwrap_used)]
        let duration = now.duration_since(SystemTime::UNIX_EPOCH).unwrap();
        let timestamp = duration.as_millis() as u64;

        let new_epoch_ts = timestamp - TS_DIFF;

        let id = new_epoch_ts << TS_SHIFT;

        let id = id | (shard_id << SEQ_BITS);

        let mut seq_check = SEQ_CHECK.get();

        if seq_check.ts == timestamp {
            seq_check = seq_check.increment(timestamp, duration);
        } else {
            seq_check = SeqForMs::with_ts_and_rand_seq(timestamp);
        }
        SEQ_CHECK.set(seq_check);

        let id = id | seq_check.seq;

        Self(u64_be::from_native(id), PhantomData)
    }

    /// unix timestamp in milliseconds
    #[inline]
    pub fn timestamp(&self) -> u64 {
        let ts = self.0.to_native() >> TS_SHIFT;
        ts + TS_DIFF
    }

    pub fn date(&self) -> time::OffsetDateTime {
        let ts = self.timestamp();
        let ts = ts as i128;
        let ts = ts * 1_000_000;
        let dt = time::OffsetDateTime::from_unix_timestamp_nanos(ts);
        dt.expect("invalid timestamp")
    }

    /// get LE u64
    #[inline]
    pub fn get(&self) -> u64 {
        self.0.to_native()
    }

    #[inline]
    pub fn to_be_bytes(self) -> [u8; 8] {
        zerocopy::transmute!(self)
    }

    #[inline]
    pub fn from_be_bytes(bytes: [u8; 8]) -> Self {
        zerocopy::transmute!(bytes)
    }

    /// to BE bytes
    #[inline]
    pub fn to_bytes(self) -> [u8; 8] {
        zerocopy::transmute!(self)
    }

    /// from BE bytes
    #[inline]
    pub fn from_bytes(bytes: [u8; 8]) -> Self {
        zerocopy::transmute!(bytes)
    }

    /// to BE u64
    #[inline]
    pub fn to_u64(self) -> u64 {
        zerocopy::transmute!(self)
    }

    /// from BE u64
    #[inline]
    pub fn from_u64(bytes: u64) -> Self {
        zerocopy::transmute!(bytes)
    }

    #[inline]
    pub fn to_le_bytes(self) -> [u8; 8] {
        self.0.to_native().to_le_bytes()
    }

    #[inline]
    pub fn instance_id(&self) -> u64 {
        let ts = self.0.to_native() >> SHARD_INSTANCE_SHIFT;
        ts & SHARD_INSTANCE_ID_MAX
    }

    #[inline]
    pub fn thread_id(&self) -> u64 {
        let ts = self.0.to_native() >> SEQ_BITS;
        ts & SHARD_THREAD_ID_MAX
    }

    #[inline]
    pub fn shard_id(&self) -> u64 {
        let ts = self.0.to_native() >> SEQ_BITS;
        ts & SHARD_ID_MAX
    }

    #[inline]
    fn seq(&self) -> u64 {
        let ts = self.0.to_native();
        ts & SEQ_MAX
    }

    /// id: {id:#x}; {id:#b}; {dt}-{instance_id}-{thread_id}-{seq}
    #[cfg(feature = "std")]
    pub fn format<W>(&self, w: &mut W) -> core::result::Result<(), core::fmt::Error>
    where
        W: std::fmt::Write,
    {
        let id = self.0.to_native();
        let dt = self.date();
        let instance_id = self.instance_id();
        let thread_id = self.thread_id();
        let seq = self.seq();
        write!(
            w,
            "id: {id:#x}; {id:#b}; {dt}-{instance_id}-{thread_id}-{seq}"
        )
    }

    /// return prefix for date [--timestamp(5)--|0x00(1)|0x0000(2)]
    /// ms - unix timestamp in milliseconds
    pub fn date_prefix(ms: u64) -> [u8; 8] {
        let ts = (ms - TS_DIFF) << TS_SHIFT;
        ts.to_be_bytes()
    }

    pub fn check(&self) -> core::result::Result<(), ArmourError> {
        let ts = self.0.to_native() >> TS_SHIFT;
        if ts > TS_MAX {
            return Err(ArmourError::IdDecodeError);
        }
        Ok(())
    }

    /// only for iterator with excluded bounds
    pub fn increment(mut self) -> Self {
        self.0 += 1;
        self
    }

    /// group_id for this Fuid (12 days one group)
    #[inline]
    pub fn group_id(&self) -> u32 {
        g8bits(self.0.to_native(), MILLISECOND_BITS)
    }
}

impl<H: IdHasher> Fuid<H> {
    pub fn ser(self) -> IdStr {
        let u: u64 = zerocopy::transmute!(self);
        H::ser(u)
    }

    pub fn deser(id: &str) -> Result<Self> {
        let id = H::deser(id)?;
        Ok(zerocopy::transmute!(id))
    }
}

impl Fuid<()> {
    pub fn ser(self) -> IdStr {
        let u: [u8; 8] = zerocopy::transmute!(self);
        crate::enc::encode(&u)
    }

    pub fn deser(id: &str) -> Result<Self> {
        let id = crate::enc::decode(id)?;
        Ok(zerocopy::transmute!(id))
    }
}

impl<T> PartialOrd for Fuid<T> {
    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl<T> Ord for Fuid<T> {
    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
        self.0.cmp(&other.0)
    }
}

impl<T> PartialEq for Fuid<T> {
    fn eq(&self, other: &Self) -> bool {
        self.0 == other.0
    }
}

impl<T> Eq for Fuid<T> {}

impl<T> PartialEq<[u8; 8]> for Fuid<T> {
    fn eq(&self, other: &[u8; 8]) -> bool {
        let bytes: &[u8; 8] = zerocopy::transmute_ref!(self);
        bytes == other
    }
}

impl<T> PartialEq<Fuid<T>> for [u8; 8] {
    fn eq(&self, other: &Fuid<T>) -> bool {
        let bytes: &[u8; 8] = zerocopy::transmute_ref!(other);
        bytes == self
    }
}

impl<T> PartialEq<Fuid<T>> for Option<Fuid<T>> {
    fn eq(&self, other: &Fuid<T>) -> bool {
        match self {
            Some(id) => id == other,
            None => false,
        }
    }
}

impl<T> PartialEq<Option<Fuid<T>>> for Fuid<T> {
    fn eq(&self, other: &Option<Fuid<T>>) -> bool {
        match other {
            Some(id) => self == id,
            None => false,
        }
    }
}

impl<T> AsRef<Self> for Fuid<T> {
    fn as_ref(&self) -> &Self {
        self
    }
}

impl<T> AsRef<[u8; 8]> for Fuid<T> {
    fn as_ref(&self) -> &[u8; 8] {
        zerocopy::transmute_ref!(self)
    }
}

/// only check if non-zero, not check valid byte mask
impl<H> Rapira for Fuid<H> {
    const STATIC_SIZE: Option<usize> = Some(8);
    const MIN_SIZE: usize = 8;

    #[inline]
    fn size(&self) -> usize {
        8
    }

    #[inline]
    fn check_bytes(slice: &mut &[u8]) -> rapira::Result<()> {
        let bytes: &[u8] = slice.get(..8).ok_or(RapiraError::SliceLen)?;

        const ZERO_BYTES: [u8; 8] = [0u8; 8];

        if bytes == ZERO_BYTES {
            return Err(RapiraError::NonZero);
        }

        *slice = unsafe { slice.get_unchecked(8..) };
        Ok(())
    }

    #[inline]
    fn from_slice(slice: &mut &[u8]) -> rapira::Result<Self>
    where
        Self: Sized,
    {
        let bytes = <[u8; 8]>::from_slice(slice)?;
        let id = Self::from_bytes(bytes);
        Ok(id)
    }

    #[inline]
    fn convert_to_bytes(&self, slice: &mut [u8], cursor: &mut usize) {
        let bytes: &[u8; 8] = zerocopy::transmute_ref!(self);
        bytes.convert_to_bytes(slice, cursor);
    }
}

impl<H> GetType for Fuid<H> {
    const TYPE: Typ = Typ::Fuid;
}

impl<H> KeyPart for Fuid<H> {
    const TY: KeyType = KeyType::Fuid;
    const PREFIX_BITS: u32 = MILLISECOND_BITS;
}

impl<H: IdHasher> std::fmt::Display for Fuid<H> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.ser())
    }
}

impl std::fmt::Display for Fuid<()> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.ser())
    }
}

impl<H> Debug for Fuid<H> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let id = self.0.to_native();
        let id = format!("{id:#X}");
        f.debug_tuple("Fuid").field(&id).finish()
    }
}

impl<T: IdHasher> TryFrom<&str> for Fuid<T> {
    type Error = ArmourError;
    fn try_from(val: &str) -> Result<Self> {
        Self::deser(val)
    }
}

impl TryFrom<&str> for Fuid<()> {
    type Error = ArmourError;
    fn try_from(val: &str) -> Result<Self> {
        Self::deser(val)
    }
}

impl<T: IdHasher> FromStr for Fuid<T> {
    type Err = ArmourError;
    fn from_str(s: &str) -> Result<Self> {
        Self::deser(s)
    }
}

impl FromStr for Fuid<()> {
    type Err = ArmourError;
    fn from_str(s: &str) -> Result<Self> {
        Self::deser(s)
    }
}

#[cfg(feature = "std")]
impl<T: IdHasher> Serialize for Fuid<T> {
    fn serialize<S: Serializer>(&self, serializer: S) -> core::result::Result<S::Ok, S::Error> {
        let s = self.ser();
        serializer.serialize_str(&s)
    }
}

#[cfg(feature = "std")]
impl<'de, T: IdHasher> Deserialize<'de> for Fuid<T> {
    fn deserialize<D>(deserializer: D) -> core::result::Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        use serde::de::Error;

        let s: &str = Deserialize::deserialize(deserializer)?;
        let a = Fuid::<T>::deser(s).map_err(|err| {
            tracing::error!("id value error: {err}");
            D::Error::custom("id value error")
        })?;
        Ok(a)
    }
}

#[cfg(feature = "std")]
impl Serialize for Fuid<()> {
    fn serialize<S: Serializer>(&self, serializer: S) -> core::result::Result<S::Ok, S::Error> {
        let s = self.ser();
        serializer.serialize_str(&s)
    }
}

#[cfg(feature = "std")]
impl<'de> Deserialize<'de> for Fuid<()> {
    fn deserialize<D>(deserializer: D) -> core::result::Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        use serde::de::Error;

        let s: &str = Deserialize::deserialize(deserializer)?;
        let a = Fuid::<()>::deser(s).map_err(|err| {
            tracing::error!("id value error: {err}");
            D::Error::custom("id value error")
        })?;
        Ok(a)
    }
}

#[cfg(feature = "ts-rs")]
impl<H> ts_rs::TS for Fuid<H> {
    type WithoutGenerics = Fuid<()>;
    type OptionInnerType = Self;
    fn name(_: &ts_rs::Config) -> String {
        "Fuid".to_owned()
    }
    fn decl_concrete(c: &ts_rs::Config) -> String {
        format!("type Fuid = {};", Self::inline(c))
    }
    fn decl(c: &ts_rs::Config) -> String {
        let inline = <Fuid<()> as ::ts_rs::TS>::inline(c);
        format!("type Fuid = {inline};")
    }
    fn inline(_: &ts_rs::Config) -> String {
        "string".to_owned()
    }
    fn inline_flattened(c: &ts_rs::Config) -> String {
        panic!("{} cannot be flattened", Self::name(c))
    }
    fn output_path() -> Option<std::path::PathBuf> {
        Some(std::path::PathBuf::from("fuid.ts"))
    }
}

#[cfg(feature = "facet")]
unsafe impl<'facet, H: 'static> facet::Facet<'facet> for Fuid<H> {
    const SHAPE: &'static facet::Shape = &const {
        const VTABLE: facet::VTableDirect = facet::vtable_direct!(Fuid<()> =>
            Debug,
            Hash,
            PartialEq,
            PartialOrd,
            Ord,
        );

        facet::ShapeBuilder::for_sized::<Fuid<H>>("Fuid")
            .ty(facet::Type::User(facet::UserType::Struct(facet::StructType {
                repr: facet::Repr::transparent(),
                kind: facet::StructKind::TupleStruct,
                fields: &const {
                    [facet::FieldBuilder::new("0", facet::shape_of::<u64>, 0).build()]
                },
            })))
            .inner(<u64 as facet::Facet>::SHAPE)
            .def(facet::Def::Scalar)
            .vtable_direct(&VTABLE)
            .eq()
            .copy()
            .send()
            .sync()
            .build()
    };
}

#[cfg(feature = "fake")]
impl<H, T> fake::Dummy<T> for Fuid<H> {
    fn dummy_with_rng<R: rand::Rng + ?Sized>(_: &T, _: &mut R) -> Self {
        Fuid::from_thread()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::enc::Cipher;

    #[derive(Debug, PartialOrd, Ord, PartialEq, Eq, Clone, Copy, Hash)]
    pub struct Hasher;

    impl IdHasher for Hasher {
        const HASHER: Cipher = Cipher::new(
            "_mKbKGF2IrkGvIJvl97HuCgWjgt6QRZ7Ye8DHBQ2anvyi18BdMz8uN6Ej3YJApooY6qDu0obqq4",
        );
    }

    #[test]
    fn test_fuid_creation() {
        let fuid = Fuid::<Hasher>::with_inst_thread(1, 2);
        assert_eq!(fuid.instance_id(), 1);
        assert_eq!(fuid.thread_id(), 2);

        let fuid = Fuid::<Hasher>::with_shard(55);
        assert_eq!(fuid.shard_id(), 55);
    }

    #[test]
    fn test_fuid_ser_deser() {
        let fuid = Fuid::<Hasher>::with_shard(111);
        let id_str = fuid.ser();
        #[allow(clippy::unwrap_used)]
        let deserialized_fuid = Fuid::<Hasher>::deser(&id_str).unwrap();
        assert_eq!(fuid, deserialized_fuid);
    }
}