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
//
// Copyright (c) 2017, 2020 ADLINK Technology Inc.
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License 2.0 which is available at
// http://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0
// which is available at https://www.apache.org/licenses/LICENSE-2.0.
//
// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
//

//! A Unique Hybrid Logical Clock.
//!
//! This library is an implementation of an
//! [Hybrid Logical Clock (HLC)](https://cse.buffalo.edu/tech-reports/2014-04.pdf)
//! associated to a unique identifier.
//! Thus, it is able to generate timestamps that are unique across a distributed system,
//! without the need of a centralized time source.
//!
//! # Quick Start
//!
//! ```
//! use uhlc::HLC;
//!
//! // create an HLC with a generated random ID and relying on SystemTime::now()
//! let hlc = HLC::default();
//!
//! // generate timestamps
//! let ts1 = hlc.new_timestamp();
//! let ts2 = hlc.new_timestamp();
//! assert!(ts2 > ts1);
//!
//! // update the HLC with a timestamp incoming from another HLC
//! // (typically remote, but not in this example...)
//! let hlc2 = HLC::default();
//! let other_ts = hlc2.new_timestamp();
//!
//! if ! hlc.update_with_timestamp(&other_ts).is_ok() {
//!     println!(r#"The incoming timestamp would make this HLC
//!              to drift too much. You should refuse it!"#);
//! }
//!
//! let ts3 = hlc.new_timestamp();
//! assert!(ts3 > ts2);
//! assert!(ts3 > other_ts);
//! ```

#![doc(
    html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk.png",
    html_favicon_url = "https://www.rust-lang.org/favicon.ico",
    html_root_url = "https://atolab.github.io/uhlc-rs/"
)]
#![cfg_attr(not(feature = "std"), no_std)]
extern crate alloc;

use alloc::{format, string::String};
use core::cmp;
use core::time::Duration;

#[cfg(feature = "std")]
use {
    lazy_static::lazy_static,
    std::env::var,
    std::sync::Mutex,
    std::time::{SystemTime, UNIX_EPOCH},
};

#[cfg(not(feature = "std"))]
use spin::Mutex; // No_std-friendly alternative to std::sync::Mutex

mod id;
pub use id::*;

mod ntp64;
pub use ntp64::*;

mod timestamp;
pub use timestamp::*;

/// The size of counter part in [`NTP64`] (in bits)
pub const CSIZE: u8 = 4u8;
// Bit-mask of the counter part within the 64 bits time
const CMASK: u64 = (1u64 << CSIZE) - 1u64;
// Bit-mask of the logical clock part within the 64 bits time
const LMASK: u64 = !CMASK;

// HLC Delta in milliseconds: maximum accepted drift for an external timestamp.
// I.e.: if an incoming timestamp has a time > now() + delta, then the HLC is not updated.
const DEFAULT_DELTA_MS: u64 = 500;
#[cfg(feature = "std")]
lazy_static! {
    static ref DELTA_MS: u64 = match var("UHLC_MAX_DELTA_MS") {
        Ok(s) => s.parse().unwrap_or_else(|e| panic!(
            "Error parsing environment variable ${{UHLC_MAX_DELTA_MS}}={} : {}",
            s, e
        )),
        Err(std::env::VarError::NotPresent) => DEFAULT_DELTA_MS,
        Err(e) => panic!(
            "Error parsing environment variable ${{UHLC_MAX_DELTA_MS}}: {}",
            e
        ),
    };
}
#[cfg(not(feature = "std"))]
static DELTA_MS: &u64 = &DEFAULT_DELTA_MS; // Environment variables do not make sense in no_std environment

///
/// The builder of [`HLC`].
///
/// # Examples
///
/// ```
/// use std::{convert::TryFrom, time::Duration};
/// use uhlc::{HLCBuilder, ID};
///
/// let default_hlc = HLCBuilder::new().build();
/// println!("{}", default_hlc.new_timestamp());
///
/// let custom_hlc = HLCBuilder::new()
///    .with_id(ID::try_from([0x01, 0x02, 0x03]).unwrap())
///    .with_max_delta(Duration::from_secs(1))
///    .build();
/// println!("{}", custom_hlc.new_timestamp());
pub struct HLCBuilder {
    hlc: HLC,
}

impl HLCBuilder {
    ///
    /// Constructs a new HLCBuilder for the creation of an [`HLC`], with the following default configuration:
    ///  * a random u128 as HLC identifier.
    ///   Can be changed calling [`Self::with_id()`].
    ///  * [`system_time_clock()`] as physical clock (i.e. the ).
    ///   Can be changed calling [`Self::with_clock()`].
    ///  * 500 millisecond as maximum delta (i.e. the maximum accepted drift for an external timestamp).
    ///   Can be changed calling [`Self::with_max_delta()`].
    ///
    pub fn new() -> HLCBuilder {
        HLCBuilder::default()
    }

    ///
    /// Configure a specific identifier for the HLC to be created.
    ///
    /// **NOTE: the identifier must be unique in the system.**
    ///
    pub fn with_id(mut self, id: ID) -> HLCBuilder {
        self.hlc.id = id;
        self
    }

    ///
    /// Configure a specific physical clock for the HLC to be created.
    ///
    /// The `clock` parameter must be a function returning a new physical time (as an [`NTP64`] at each call.
    /// The time returned by this clock doesn't need to be monotonic: when the HLC generates a new timestamp from this time,
    /// it first checks if this time is greater than the previously generated timestamp. If not, the new timestamp it the previous one +1.
    ///
    pub fn with_clock(mut self, clock: fn() -> NTP64) -> HLCBuilder {
        self.hlc.clock = clock;
        self
    }

    ///
    /// Configure the maximum delta accepted by an HLC when updating it's logical clock calling [`HLC::update_with_timestamp()`].
    ///
    pub fn with_max_delta(mut self, delta: Duration) -> HLCBuilder {
        self.hlc.delta = delta.into();
        self
    }

    pub fn build(self) -> HLC {
        self.hlc
    }
}

impl Default for HLCBuilder {
    fn default() -> Self {
        HLCBuilder {
            hlc: HLC {
                id: ID::rand(),
                #[cfg(feature = "std")]
                clock: system_time_clock,
                #[cfg(not(feature = "std"))]
                clock: zero_clock,
                delta: NTP64::from(Duration::from_millis(*DELTA_MS)),
                last_time: Default::default(),
            },
        }
    }
}

/// An Hybric Logical Clock generating [`Timestamp`]s
pub struct HLC {
    id: ID,
    clock: fn() -> NTP64,
    delta: NTP64,
    last_time: Mutex<NTP64>,
}

#[cfg(feature = "std")]
macro_rules! lock {
    ($var:expr) => {
        match $var.try_lock() {
            Ok(guard) => guard,
            Err(_) => $var.lock().unwrap(),
        }
    };
}

#[cfg(not(feature = "std"))]
macro_rules! lock {
    ($var:expr) => {
        $var.lock()
    };
}

impl HLC {
    /// Generate a new [`Timestamp`].
    ///
    /// This timestamp is unique in the system and is always greater
    /// than the latest timestamp generated by the HLC and than the
    /// latest incoming timestamp that was used to update this [`HLC`]
    /// (using [`HLC::update_with_timestamp()`]).
    ///
    /// # Examples
    ///
    /// ```
    /// use uhlc::HLC;
    ///
    /// let hlc = HLC::default();
    /// let ts1 =  hlc.new_timestamp();
    /// let ts2 =  hlc.new_timestamp();
    /// assert!(ts2 > ts1);
    /// ```
    pub fn new_timestamp(&self) -> Timestamp {
        let mut now = (self.clock)();
        now.0 &= LMASK;
        let mut last_time = lock!(self.last_time);
        if now.0 > (last_time.0 & LMASK) {
            *last_time = now
        } else {
            *last_time += 1;
        }
        Timestamp::new(*last_time, self.id)
    }

    /// Returns the HLC [`ID`].
    ///
    /// This ID is the specific identifier for this HLC instance.
    ///
    pub fn get_id(&self) -> &ID {
        &self.id
    }

    /// Returns the HLC delta as [`NTP64`].
    ///
    /// The maximum delta accepted by an HLC when updating it's logical clock calling [`HLC::update_with_timestamp()`].
    ///
    pub fn get_delta(&self) -> &NTP64 {
        &self.delta
    }

    /// Update this [`HLC`] with a [`Timestamp`].
    ///
    /// Typically, this timestamp should have been generated by another HLC.
    /// If the timestamp exceeds the current time of this HLC by more than the configured maximum delta
    /// (see [`HLCBuilder::with_max_delta()`]) an [`Err`] is returned.
    ///
    /// # Examples
    ///
    /// ```
    /// use uhlc::HLC;
    ///
    /// let hlc1 = HLC::default();
    ///
    /// // update the HLC with a timestamp incoming from another HLC
    /// // (typically remote, but not in this example...)
    /// let hlc2 = HLC::default();
    /// let other_ts = hlc2.new_timestamp();
    /// if ! hlc1.update_with_timestamp(&other_ts).is_ok() {
    ///     println!(r#"The incoming timestamp would make this HLC
    ///              to drift too much. You should refuse it!"#);
    /// }
    ///
    /// let ts = hlc1.new_timestamp();
    /// assert!(ts > other_ts);
    /// ```
    pub fn update_with_timestamp(&self, timestamp: &Timestamp) -> Result<(), String> {
        let mut now = (self.clock)();
        now.0 &= LMASK;
        let msg_time = timestamp.get_time();
        if *msg_time > now && *msg_time - now > self.delta {
            let err_msg = format!(
                "incoming timestamp from {} exceeding delta {}ms is rejected: {} vs. now: {}",
                timestamp.get_id(),
                self.delta.to_duration().as_millis(),
                msg_time,
                now
            );
            #[cfg(feature = "std")]
            log::warn!("{}", err_msg);
            #[cfg(feature = "defmt")]
            defmt::warn!("{}", err_msg);
            Err(err_msg)
        } else {
            let mut last_time = lock!(self.last_time);
            let max_time = cmp::max(cmp::max(now, *msg_time), *last_time);
            if max_time == now {
                *last_time = now;
            } else if max_time == *msg_time {
                *last_time = *msg_time + 1;
            } else {
                *last_time += 1;
            }
            Ok(())
        }
    }
}

impl Default for HLC {
    /// Create a new [`HLC`] with a random u128 ID and using
    /// [`system_time_clock()`] as physical clock.
    /// This is equivalent to `HLCBuilder::default().build()`
    fn default() -> Self {
        HLCBuilder::default().build()
    }
}

/// A physical clock relying on std::time::SystemTime::now().
///
/// It returns a NTP64 relative to std::time::UNIX_EPOCH (1st Jan 1970).
/// That's the default clock used by an [`HLC`] if [`HLCBuilder::with_clock()`] is not called.
///
#[inline]
#[cfg(feature = "std")]
pub fn system_time_clock() -> NTP64 {
    NTP64::from(SystemTime::now().duration_since(UNIX_EPOCH).unwrap())
}

/// A dummy clock that returns a NTP64 initialized with the value 0.
/// Suitable to use in no_std environments where std::time::{SystemTime, UNIX_EPOCH} are not available.
/// If the feature `std` is disabled, that's the default clock used by an [`HLC`] if [`HLCBuilder::with_clock()`] is not called.
/// Notice that this means that the [`HLC`] will use incremental timestamps starting from 0.
#[inline]
pub fn zero_clock() -> NTP64 {
    NTP64(0)
}

#[cfg(test)]
mod tests {
    use crate::*;
    use async_std::sync::Arc;
    use async_std::task;
    use core::convert::TryFrom;
    use core::time::Duration;
    use futures::join;

    fn is_sorted(vec: &[Timestamp]) -> bool {
        let mut it = vec.iter();
        let mut ts = it.next().unwrap();
        for next in it {
            if next <= ts {
                return false;
            };
            ts = next;
        }
        true
    }

    #[test]
    fn hlc_parallel() {
        use alloc::vec::Vec;
        task::block_on(async {
            let id0: ID = ID::try_from([0x01]).unwrap();
            let id1: ID = ID::try_from([0x02]).unwrap();
            let id2: ID = ID::try_from([0x03]).unwrap();
            let id3: ID = ID::try_from([0x04]).unwrap();
            let hlc0 = Arc::new(HLCBuilder::new().with_id(id0).build());
            let hlc1 = Arc::new(HLCBuilder::new().with_id(id1).build());
            let hlc2 = Arc::new(HLCBuilder::new().with_id(id2).build());
            let hlc3 = Arc::new(HLCBuilder::new().with_id(id3).build());

            // Make 4 tasks to generate 10000 timestamps each with distinct HLCs,
            // and also to update each other HLCs
            const NB_TIME: usize = 10000;
            let t0 = {
                let hlc0 = hlc0.clone();
                let hlc1 = hlc1.clone();
                task::spawn(async move {
                    let mut times: Vec<Timestamp> = Vec::with_capacity(10000);
                    for _ in 0..NB_TIME {
                        let ts = hlc0.new_timestamp();
                        assert!(hlc1.update_with_timestamp(&ts).is_ok());
                        times.push(ts)
                    }
                    times
                })
            };
            let t1 = {
                let hlc1 = hlc1.clone();
                let hlc2 = hlc2.clone();
                task::spawn(async move {
                    let mut times: Vec<Timestamp> = Vec::with_capacity(10000);
                    for _ in 0..NB_TIME {
                        let ts = hlc1.new_timestamp();
                        assert!(hlc2.update_with_timestamp(&ts).is_ok());
                        times.push(ts)
                    }
                    times
                })
            };
            let t2 = {
                let hlc2 = hlc3.clone();
                let hlc3 = hlc3.clone();
                task::spawn(async move {
                    let mut times: Vec<Timestamp> = Vec::with_capacity(10000);
                    for _ in 0..NB_TIME {
                        let ts = hlc2.new_timestamp();
                        assert!(hlc3.update_with_timestamp(&ts).is_ok());
                        times.push(ts)
                    }
                    times
                })
            };
            let t3 = {
                let hlc3 = hlc3.clone();
                let hlc0 = hlc0.clone();
                task::spawn(async move {
                    let mut times: Vec<Timestamp> = Vec::with_capacity(10000);
                    for _ in 0..NB_TIME {
                        let ts = hlc3.new_timestamp();
                        assert!(hlc0.update_with_timestamp(&ts).is_ok());
                        times.push(ts)
                    }
                    times
                })
            };
            let vecs = join!(t0, t1, t2, t3);

            // test that each timeseries is sorted (i.e. monotonic time)
            assert!(is_sorted(&vecs.0));
            assert!(is_sorted(&vecs.1));
            assert!(is_sorted(&vecs.2));
            assert!(is_sorted(&vecs.3));

            // test that there is no duplicate amongst all timestamps
            let mut all_times: Vec<Timestamp> = vecs
                .0
                .into_iter()
                .chain(vecs.1)
                .chain(vecs.2)
                .chain(vecs.3)
                .collect::<Vec<Timestamp>>();
            assert_eq!(NB_TIME * 4, all_times.len());
            all_times.sort();
            all_times.dedup();
            assert_eq!(NB_TIME * 4, all_times.len());
        });
    }

    #[test]
    fn hlc_update_with_timestamp() {
        let id: ID = ID::rand();
        let hlc = HLCBuilder::new().with_id(id).build();

        // Test that updating with an old Timestamp don't break the HLC
        let past_ts = Timestamp::new(Default::default(), id);
        let now_ts = hlc.new_timestamp();
        assert!(hlc.update_with_timestamp(&past_ts).is_ok());
        assert!(hlc.new_timestamp() > now_ts);

        // Test that updating with a Timestamp exceeding the delta is refused
        let now_ts = hlc.new_timestamp();
        let future_time = now_ts.get_time() + NTP64::from(Duration::from_millis(1000));
        let future_ts = Timestamp::new(future_time, id);
        assert!(hlc.update_with_timestamp(&future_ts).is_err())
    }
}