tsoracle-core 2.3.0

Sync algorithm core for tsoracle: window allocator, 46/18-bit timestamp packing, monotonicity invariants, and the shared cluster peer type.
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
//
//  ░▀█▀░█▀▀░█▀█░█▀▄░█▀█░█▀▀░█░░░█▀▀
//  ░░█░░▀▀█░█░█░█▀▄░█▀█░█░░░█░░░█▀▀
//  ░░▀░░▀▀▀░▀▀▀░▀░▀░▀░▀░▀▀▀░▀▀▀░▀▀▀
//
//  tsoracle — Distributed Timestamp Oracle
//  https://www.tsoracle.rs
//
//  Copyright (c) 2026 Prisma Risk
//
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//
//      https://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
//

//! A consensus peer and the tsoracle service endpoint it advertises.

use core::fmt;
use core::str::FromStr;

/// Error returned when a string fails the [`PeerEndpoint`] contract.
#[derive(Clone, Debug, thiserror::Error, PartialEq, Eq)]
pub enum PeerEndpointError {
    /// The endpoint was an empty string. `PeerEndpoint` carries no "absent"
    /// semantics; callers that need optionality wrap it in `Option`.
    #[error("peer endpoint must not be empty")]
    Empty,
    /// The endpoint begins with `http://` or `https://`. The TLS client
    /// silently drops scheme-bearing leader hints to refuse a transport
    /// downgrade, so a scheme-bearing endpoint makes its owner unreachable
    /// via redirect.
    #[error("peer endpoint {endpoint:?} must be scheme-less host:port, not a http(s):// URL")]
    SchemeBearing { endpoint: String },
    /// The endpoint has no `:port` suffix. A bare host is technically a valid
    /// authority but is never an intentional production value — the consensus
    /// drivers always advertise an explicit port.
    #[error("peer endpoint {endpoint:?} must include an explicit :port")]
    MissingPort { endpoint: String },
    /// The host portion before `:port` is empty (e.g. `":50051"`).
    #[error("peer endpoint {endpoint:?} has an empty host")]
    EmptyHost { endpoint: String },
    /// The port portion is empty, non-numeric, or outside `1..=65535`.
    #[error("peer endpoint {endpoint:?} has an invalid port: {reason}")]
    InvalidPort {
        endpoint: String,
        reason: &'static str,
    },
}

/// A scheme-less `host:port` advertising the tsoracle service address of a
/// peer node.
///
/// **Contract (enforced at construction):**
///
/// * No `http://` / `https://` prefix. The TLS client silently drops
///   scheme-bearing leader hints (`rejects_plaintext_hint`) to refuse a
///   transport downgrade, so a scheme-bearing endpoint would make its owner
///   unreachable via follower redirect — a silent prod trap. (See
///   `tsoracle_server::fence::endpoint_is_scheme_less` for the historical
///   runtime guard this newtype subsumes.)
/// * Non-empty.
/// * Includes an explicit `:port` with a numeric port in `1..=65535`.
/// * Bracketed IPv6 supported (`[::1]:50051`).
///
/// Consumers that need to dial this endpoint prepend `http://` / `https://`
/// at dial time based on their TLS configuration (see e.g.
/// `tsoracle_client::channel_pool`); the endpoint itself is transport-agnostic.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct PeerEndpoint(String);

impl PeerEndpoint {
    /// Borrow the underlying `host:port` string.
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Consume self, returning the underlying `String`.
    pub fn into_inner(self) -> String {
        self.0
    }
}

impl TryFrom<String> for PeerEndpoint {
    type Error = PeerEndpointError;

    fn try_from(endpoint: String) -> Result<Self, Self::Error> {
        if endpoint.is_empty() {
            return Err(PeerEndpointError::Empty);
        }
        // ASCII-lowercase only, matching the client's `normalize_uri`. An
        // uppercase variant would already fail to parse downstream.
        if endpoint.starts_with("http://") || endpoint.starts_with("https://") {
            return Err(PeerEndpointError::SchemeBearing { endpoint });
        }
        // `rsplit_once(':')` splits on the LAST colon, which is the port
        // separator for both `host:port` and the bracketed-IPv6 form
        // `[::1]:50051` (host=`[::1]`, port=`50051`). `split_once(':')` would
        // break IPv6 by splitting at the first colon inside the address.
        let (host, port_str) = match endpoint.rsplit_once(':') {
            Some(pair) => pair,
            None => return Err(PeerEndpointError::MissingPort { endpoint }),
        };
        if host.is_empty() {
            return Err(PeerEndpointError::EmptyHost { endpoint });
        }
        // `u16::from_str` rejects empty, non-numeric, and `> 65535`. Port 0
        // parses cleanly but is reserved per RFC 6335; reject it explicitly.
        let port = port_str
            .parse::<u16>()
            .map_err(|_| PeerEndpointError::InvalidPort {
                endpoint: endpoint.clone(),
                reason: "must be a base-10 number in 1..=65535",
            })?;
        if port == 0 {
            return Err(PeerEndpointError::InvalidPort {
                endpoint,
                reason: "port 0 is reserved",
            });
        }
        Ok(PeerEndpoint(endpoint))
    }
}

impl TryFrom<&str> for PeerEndpoint {
    type Error = PeerEndpointError;
    fn try_from(s: &str) -> Result<Self, Self::Error> {
        Self::try_from(s.to_string())
    }
}

impl FromStr for PeerEndpoint {
    type Err = PeerEndpointError;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::try_from(s.to_string())
    }
}

impl fmt::Display for PeerEndpoint {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

impl AsRef<str> for PeerEndpoint {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

#[cfg(feature = "serde")]
impl serde::Serialize for PeerEndpoint {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(&self.0)
    }
}

#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for PeerEndpoint {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        // Re-validate on the way in: a wire-supplied or persisted endpoint
        // that violates the contract is rejected here, not silently observed
        // as a runtime trap downstream.
        let s = String::deserialize(deserializer)?;
        Self::try_from(s).map_err(serde::de::Error::custom)
    }
}

/// A known peer node and the network endpoint where its TSO service can be
/// reached for follower-redirect hints.
///
/// `node_id` is the consensus node identity (the OmniPaxos `NodeId`/pid or the
/// openraft `NodeId`). `endpoint` is the advertised tsoracle service address
/// surfaced via `LeaderState::Follower::leader_endpoint` when this peer is the
/// elected leader. This is the cross-backend shape consensus drivers share so
/// the `leader_endpoint` derivation reads the same regardless of the engine
/// underneath.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct TsoPeer {
    pub node_id: u64,
    pub endpoint: PeerEndpoint,
}

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

    // ---- TsoPeer struct shape (preserved from pre-newtype tests; updated
    // ---- to use contract-conforming endpoints instead of the http://...
    // ---- forms that were latent contract violations).

    #[test]
    fn carries_node_id_and_endpoint() {
        let peer = TsoPeer {
            node_id: 2,
            endpoint: PeerEndpoint::try_from("node-2:50051").unwrap(),
        };
        assert_eq!(peer.node_id, 2);
        assert_eq!(peer.endpoint.as_str(), "node-2:50051");
    }

    #[test]
    fn equality_is_by_node_id_and_endpoint() {
        let left = TsoPeer {
            node_id: 1,
            endpoint: PeerEndpoint::try_from("a:1").unwrap(),
        };
        let same = TsoPeer {
            node_id: 1,
            endpoint: PeerEndpoint::try_from("a:1").unwrap(),
        };
        let different_endpoint = TsoPeer {
            node_id: 1,
            endpoint: PeerEndpoint::try_from("b:1").unwrap(),
        };
        assert_eq!(left, same);
        assert_ne!(left, different_endpoint);
    }

    #[test]
    fn is_usable_as_a_hash_set_member() {
        use std::collections::HashSet;

        let mut peers = HashSet::new();
        peers.insert(TsoPeer {
            node_id: 1,
            endpoint: PeerEndpoint::try_from("a:1").unwrap(),
        });
        let duplicate = peers.insert(TsoPeer {
            node_id: 1,
            endpoint: PeerEndpoint::try_from("a:1").unwrap(),
        });
        assert!(!duplicate, "an equal peer must hash to the same bucket");
        assert_eq!(peers.len(), 1);
    }

    // ---- PeerEndpoint: accepted shapes

    #[test]
    fn accepts_basic_hostname_with_port() {
        let e = PeerEndpoint::try_from("node-1:50051").unwrap();
        assert_eq!(e.as_str(), "node-1:50051");
    }

    #[test]
    fn accepts_ipv4_with_port() {
        let e = PeerEndpoint::try_from("10.0.0.7:50551").unwrap();
        assert_eq!(e.as_str(), "10.0.0.7:50551");
    }

    #[test]
    fn accepts_ipv6_bracketed_with_port() {
        let e = PeerEndpoint::try_from("[::1]:50551").unwrap();
        assert_eq!(e.as_str(), "[::1]:50551");
    }

    #[test]
    fn accepts_fqdn_with_port() {
        let e = PeerEndpoint::try_from("leader.example.com:9000").unwrap();
        assert_eq!(e.as_str(), "leader.example.com:9000");
    }

    #[test]
    fn accepts_max_port() {
        let e = PeerEndpoint::try_from("h:65535").unwrap();
        assert_eq!(e.as_str(), "h:65535");
    }

    #[test]
    fn accepts_min_valid_port() {
        let e = PeerEndpoint::try_from("h:1").unwrap();
        assert_eq!(e.as_str(), "h:1");
    }

    // ---- PeerEndpoint: rejected shapes

    #[test]
    fn rejects_empty() {
        assert_eq!(PeerEndpoint::try_from(""), Err(PeerEndpointError::Empty),);
    }

    #[test]
    fn rejects_http_scheme() {
        let err = PeerEndpoint::try_from("http://node-1:50051").unwrap_err();
        assert!(
            matches!(err, PeerEndpointError::SchemeBearing { .. }),
            "expected SchemeBearing, got {err:?}",
        );
    }

    #[test]
    fn rejects_https_scheme() {
        let err = PeerEndpoint::try_from("https://node-1:50051").unwrap_err();
        assert!(
            matches!(err, PeerEndpointError::SchemeBearing { .. }),
            "expected SchemeBearing, got {err:?}",
        );
    }

    #[test]
    fn rejects_mem_scheme_via_missing_port() {
        // `mem://foo` is not http(s):// so it bypasses the scheme check, but
        // it has no numeric port — either the missing-port branch or the
        // invalid-port branch must reject it. Either is contract-correct;
        // both are acceptable.
        let err = PeerEndpoint::try_from("mem://foo").unwrap_err();
        assert!(
            matches!(
                err,
                PeerEndpointError::MissingPort { .. }
                    | PeerEndpointError::InvalidPort { .. }
                    | PeerEndpointError::EmptyHost { .. }
            ),
            "expected port-shape rejection, got {err:?}",
        );
    }

    #[test]
    fn rejects_bare_host_no_port() {
        let err = PeerEndpoint::try_from("node-1").unwrap_err();
        assert!(
            matches!(err, PeerEndpointError::MissingPort { .. }),
            "expected MissingPort, got {err:?}",
        );
    }

    #[test]
    fn rejects_empty_port() {
        let err = PeerEndpoint::try_from("node-1:").unwrap_err();
        assert!(
            matches!(err, PeerEndpointError::InvalidPort { .. }),
            "expected InvalidPort, got {err:?}",
        );
    }

    #[test]
    fn rejects_non_numeric_port() {
        let err = PeerEndpoint::try_from("node-1:abc").unwrap_err();
        assert!(
            matches!(err, PeerEndpointError::InvalidPort { .. }),
            "expected InvalidPort, got {err:?}",
        );
    }

    #[test]
    fn rejects_empty_host() {
        let err = PeerEndpoint::try_from(":50051").unwrap_err();
        assert!(
            matches!(err, PeerEndpointError::EmptyHost { .. }),
            "expected EmptyHost, got {err:?}",
        );
    }

    #[test]
    fn rejects_port_zero() {
        let err = PeerEndpoint::try_from("h:0").unwrap_err();
        assert!(
            matches!(err, PeerEndpointError::InvalidPort { .. }),
            "expected InvalidPort, got {err:?}",
        );
    }

    #[test]
    fn rejects_port_overflow() {
        let err = PeerEndpoint::try_from("h:65536").unwrap_err();
        assert!(
            matches!(err, PeerEndpointError::InvalidPort { .. }),
            "expected InvalidPort, got {err:?}",
        );
    }

    // ---- PeerEndpoint: API surface

    #[test]
    fn display_round_trips() {
        let e = PeerEndpoint::try_from("node-1:50051").unwrap();
        assert_eq!(format!("{e}"), "node-1:50051");
    }

    #[test]
    fn from_str_works() {
        let e: PeerEndpoint = "node-1:50051".parse().unwrap();
        assert_eq!(e.as_str(), "node-1:50051");
    }

    #[test]
    fn try_from_str_ref_works() {
        let e: PeerEndpoint = "node-1:50051".try_into().unwrap();
        assert_eq!(e.as_str(), "node-1:50051");
    }

    #[test]
    fn into_inner_returns_string() {
        let e = PeerEndpoint::try_from("node-1:50051").unwrap();
        assert_eq!(e.into_inner(), String::from("node-1:50051"));
    }

    // ---- PeerEndpoint: serde re-validates on deserialize

    #[cfg(feature = "serde")]
    #[test]
    fn serde_round_trip_preserves_value() {
        let e = PeerEndpoint::try_from("10.0.0.7:50551").unwrap();
        let json = serde_json::to_string(&e).unwrap();
        assert_eq!(json, "\"10.0.0.7:50551\"");
        let back: PeerEndpoint = serde_json::from_str(&json).unwrap();
        assert_eq!(back, e);
    }

    #[cfg(feature = "serde")]
    #[test]
    fn serde_rejects_scheme_bearing_input() {
        // A scheme-bearing endpoint that snuck onto the wire must NOT be
        // observable as a `PeerEndpoint` — re-validate on deserialize.
        let err = serde_json::from_str::<PeerEndpoint>("\"http://node-1:50051\"")
            .expect_err("deserialize must reject scheme-bearing input");
        let msg = err.to_string();
        assert!(
            msg.contains("scheme-less") || msg.contains("http"),
            "error should mention the scheme contract, got: {msg}",
        );
    }
}