Skip to main content

lean_ctx_cloud/events/
hlc.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Hybrid logical clock of an engine (SPEC-ENGINE §3.3.2, C0 2.0
3//! `vectors/hlc.vectors.json`).
4
5use serde::{Deserialize, Serialize};
6
7/// A clock reading.
8#[derive(
9    Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize,
10)]
11pub struct Stamp {
12    pub wall_ms: u64,
13    pub counter: u16,
14}
15
16/// A counter above 65 535 moves the wall one millisecond on.
17fn bump(wall_ms: u64, counter: u32) -> Stamp {
18    match u16::try_from(counter) {
19        Ok(counter) => Stamp { wall_ms, counter },
20        Err(_) => Stamp {
21            wall_ms: wall_ms + 1,
22            counter: 0,
23        },
24    }
25}
26
27/// Stamp an own event: `wall = max(local, last.wall)`; `counter =
28/// last.counter + 1` if the wall did not move, else 0.
29pub fn send(last: Stamp, local_wall_ms: u64) -> Stamp {
30    let wall = local_wall_ms.max(last.wall_ms);
31    if wall == last.wall_ms {
32        bump(wall, u32::from(last.counter) + 1)
33    } else {
34        Stamp {
35            wall_ms: wall,
36            counter: 0,
37        }
38    }
39}
40
41/// Merge a received event's stamp into the clock.
42pub fn receive(last: Stamp, remote: Stamp, local_wall_ms: u64) -> Stamp {
43    let wall = local_wall_ms.max(last.wall_ms).max(remote.wall_ms);
44    let counter = match (wall == last.wall_ms, wall == remote.wall_ms) {
45        (true, true) => u32::from(last.counter.max(remote.counter)) + 1,
46        (true, false) => u32::from(last.counter) + 1,
47        (false, true) => u32::from(remote.counter) + 1,
48        (false, false) => 0,
49    };
50    bump(wall, counter)
51}
52
53/// The server's skew clamp: accepted iff `wall_ms ≤ now + 120 s` and
54/// `wall_ms ≥ place_created_at − 300 s` (else `hlc_skew`).
55pub fn server_accepts(wall_ms: u64, server_now_ms: u64, place_created_at_ms: u64) -> bool {
56    wall_ms <= server_now_ms + 120_000 && wall_ms >= place_created_at_ms.saturating_sub(300_000)
57}