1#![warn(missing_docs)]
13
14use std::fmt;
15use std::ops::Deref;
16use std::str::FromStr;
17use std::sync::Arc;
18use std::time::Duration;
19
20use anyhow::bail;
21use mz_ore::now::{AsEpochMillis, NowFn};
22use serde::{Deserialize, Serialize};
23
24pub mod client;
25pub mod instances;
26pub mod metrics;
27pub mod params;
28
29#[derive(Clone)]
35pub struct WallclockLagFn<T>(Arc<dyn Fn(T) -> Duration + Send + Sync>);
36
37impl<T: AsEpochMillis> WallclockLagFn<T> {
38 pub fn new(now: NowFn) -> Self {
40 let inner = Arc::new(move |time: T| {
41 let time_ms = time.as_epoch_millis();
42 let lag_ms = now().saturating_sub(time_ms);
43 let lag_s = lag_ms.div_ceil(1000);
44 Duration::from_secs(lag_s)
45 });
46 Self(inner)
47 }
48}
49
50impl<T> Deref for WallclockLagFn<T> {
51 type Target = dyn Fn(T) -> Duration + Send + Sync;
52
53 fn deref(&self) -> &Self::Target {
54 &(*self.0)
55 }
56}
57
58#[derive(
60 Clone,
61 Copy,
62 Debug,
63 Eq,
64 PartialEq,
65 Ord,
66 PartialOrd,
67 Hash,
68 Serialize,
69 Deserialize
70)]
71pub enum ReplicaId {
72 User(u64),
74 System(u64),
76}
77
78impl ReplicaId {
79 pub fn inner_id(&self) -> u64 {
81 match self {
82 ReplicaId::User(id) => *id,
83 ReplicaId::System(id) => *id,
84 }
85 }
86
87 pub fn is_user(&self) -> bool {
89 matches!(self, Self::User(_))
90 }
91
92 pub fn is_system(&self) -> bool {
94 matches!(self, Self::System(_))
95 }
96}
97
98impl fmt::Display for ReplicaId {
99 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
100 match self {
101 Self::User(id) => write!(f, "u{}", id),
102 Self::System(id) => write!(f, "s{}", id),
103 }
104 }
105}
106
107impl FromStr for ReplicaId {
108 type Err = anyhow::Error;
109
110 fn from_str(s: &str) -> Result<Self, Self::Err> {
111 let first = s.chars().next();
112 let rest = s.get(1..);
113 if let (Some(prefix), Some(num)) = (first, rest) {
114 let id = num.parse()?;
115 match prefix {
116 'u' => return Ok(Self::User(id)),
117 's' => return Ok(Self::System(id)),
118 _ => (),
119 }
120 }
121
122 bail!("invalid replica ID: {}", s);
123 }
124}