Skip to main content

feldera_types/transport/
clock.rs

1use std::cmp::max;
2use std::fmt::{self, Display, Formatter};
3use std::str::FromStr;
4
5use chrono::FixedOffset;
6use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
7use utoipa::ToSchema;
8
9use crate::{
10    duration::{ConfigDuration, LegacyUnit},
11    duration_setting,
12};
13
14duration_setting!(
15    duration_clock_resolution,
16    "clock_resolution",
17    LegacyUnit::Micros
18);
19
20/// Fixed timezone offset for the pipeline clock.
21///
22/// Parsed from an ISO-8601 UTC offset string such as `"+05:30"` or
23/// `"-08:00"` and serialized back to the same form.  Wraps
24/// [`chrono::FixedOffset`], which accepts offsets strictly between -24 and
25/// +24 hours.
26#[derive(Clone, Copy, Debug, PartialEq, Eq)]
27pub struct ClockTimezoneOffset(FixedOffset);
28
29impl ClockTimezoneOffset {
30    /// The offset in milliseconds east of UTC.
31    pub fn offset_ms(&self) -> i64 {
32        i64::from(self.0.local_minus_utc()) * 1_000
33    }
34}
35
36impl FromStr for ClockTimezoneOffset {
37    type Err = String;
38
39    fn from_str(s: &str) -> Result<Self, Self::Err> {
40        FixedOffset::from_str(s).map(Self).map_err(|e| {
41            format!(
42                "invalid timezone offset {s:?} (expected a UTC offset such as \"+05:30\" or \"-08:00\"): {e}"
43            )
44        })
45    }
46}
47
48impl Display for ClockTimezoneOffset {
49    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
50        write!(f, "{}", self.0)
51    }
52}
53
54impl Serialize for ClockTimezoneOffset {
55    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
56        serializer.collect_str(self)
57    }
58}
59
60impl<'de> Deserialize<'de> for ClockTimezoneOffset {
61    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
62        let s = String::deserialize(deserializer)?;
63        s.parse().map_err(de::Error::custom)
64    }
65}
66
67fn is_zero(value: &i64) -> bool {
68    *value == 0
69}
70
71/// The default as the OpenAPI schema shows it.
72fn default_clock_resolution() -> String {
73    crate::config::DEFAULT_CLOCK_RESOLUTION.to_string()
74}
75
76#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize, ToSchema)]
77pub struct ClockConfig {
78    /// How often the clock ticks, for example `1s`. Unset selects the
79    /// default, `DEFAULT_CLOCK_RESOLUTION`.
80    #[serde(
81        default,
82        alias = "clock_resolution_usecs",
83        deserialize_with = "duration_clock_resolution",
84        skip_serializing_if = "Option::is_none"
85    )]
86    #[schema(value_type = Option<String>, default = default_clock_resolution)]
87    pub clock_resolution: Option<ConfigDuration>,
88
89    /// Constant offset added to every emitted `NOW()` value, in milliseconds
90    /// east of UTC.  Populated from the `clock_timezone_offset` pipeline
91    /// property; 0 means UTC.
92    #[serde(default, skip_serializing_if = "is_zero")]
93    pub timezone_offset_ms: i64,
94
95    /// Target value for `NOW()` at the worker's first emitted tick, in
96    /// milliseconds since the Unix epoch.
97    ///
98    /// Populated verbatim from `DevTweaks::now_offset` at endpoint
99    /// construction; the wall-clock delta is computed inside the
100    /// connector's worker task from a single `SystemTime::now()`
101    /// reading, so there is no drift between config construction and
102    /// the first emitted tick.  `None` means no shift is applied.
103    #[serde(default, skip_serializing_if = "Option::is_none")]
104    pub now_offset_ms: Option<i64>,
105
106    /// If `true`, the clock does not advance on wall-clock cadence.
107    /// `NOW()` is held at its current value and only advances when an
108    /// external caller invokes the pipeline's `POST /clock/advance`
109    /// endpoint.  Populated from `DevTweaks::now_http_driven`.
110    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
111    pub http_driven: bool,
112}
113
114impl ClockConfig {
115    /// The resolution in effect: `clock_resolution`, or
116    /// [`DEFAULT_CLOCK_RESOLUTION`](crate::config::DEFAULT_CLOCK_RESOLUTION)
117    /// when unset.
118    pub fn clock_resolution(&self) -> ConfigDuration {
119        self.clock_resolution
120            .unwrap_or(crate::config::DEFAULT_CLOCK_RESOLUTION)
121    }
122
123    pub fn clock_resolution_ms(&self) -> u64 {
124        // Rounds to the nearest millisecond, saturating past what a `u64`
125        // holds, and refuses a 0 clock resolution.
126        let millis = (self.clock_resolution().as_micros() + 500) / 1_000;
127        max(u64::try_from(millis).unwrap_or(u64::MAX), 1)
128    }
129}
130
131/// Body of `POST /clock/advance`.
132///
133/// `delta_ms` is unsigned; negative values fail JSON deserialization.
134/// `Some(0)` reads the current `NOW()` without moving it or rounding
135/// it; `Some(n)` advances by `n` ms; `None` (`null` or omitted)
136/// advances by one `clock_resolution`.  Non-zero values round up to
137/// the next `clock_resolution` boundary, so a sub-resolution delta
138/// still moves the clock by one full tick.
139#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
140pub struct ClockAdvanceRequest {
141    #[serde(default)]
142    pub delta_ms: Option<u64>,
143}
144
145/// Response of `POST /clock/advance`: the new `NOW()` value as both
146/// milliseconds since epoch (signed; pre-1970 anchors yield negative
147/// values) and an RFC 3339 string.
148#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
149pub struct ClockAdvanceResponse {
150    pub now_ms: i64,
151    pub now: String,
152}
153
154#[cfg(test)]
155mod test {
156    use super::{ClockConfig, ClockTimezoneOffset};
157    use crate::config::DEFAULT_CLOCK_RESOLUTION;
158    use crate::duration::ConfigDuration;
159
160    /// An explicit `null` under one key still counts as writing that key, so
161    /// it plus a value under the other is a duplicate, as the SQL compiler
162    /// reports it.
163    #[test]
164    fn a_null_and_the_other_spelling_are_a_duplicate() {
165        for json in [
166            r#"{"clock_resolution": null, "clock_resolution_usecs": 5}"#,
167            r#"{"clock_resolution": "1s", "clock_resolution_usecs": null}"#,
168        ] {
169            let error = serde_json::from_str::<ClockConfig>(json)
170                .unwrap_err()
171                .to_string();
172            assert!(error.contains("duplicate field"), "{json}: {error}");
173        }
174    }
175
176    /// The clock ticks in whole milliseconds: the resolution rounds to the
177    /// nearest one, halves up, and never to zero.
178    #[test]
179    fn clock_resolution_rounds_to_whole_milliseconds() {
180        for (resolution, millis) in [
181            ("1s", 1_000),
182            ("1499us", 1),
183            ("1500us", 2),
184            ("400us", 1),
185            ("0", 1),
186            // Past what a `u64` of microseconds holds: the resolution saturates
187            // rather than wrapping to a millisecond.
188            ("18446744073709551616us", 18_446_744_073_709_552),
189            ("18446744073709551615us", 18_446_744_073_709_552),
190            ("18446744073709551615s", u64::MAX),
191        ] {
192            let config: ClockConfig =
193                serde_json::from_value(serde_json::json!({"clock_resolution": resolution}))
194                    .unwrap();
195            assert_eq!(config.clock_resolution_ms(), millis, "{resolution}");
196        }
197    }
198
199    /// The clock resolution reads back from both spellings. They reach one
200    /// field, so writing both is rejected as a duplicate.
201    #[test]
202    fn clock_resolution_accepts_both_spellings() {
203        for (json, expected) in [
204            (r#"{}"#, DEFAULT_CLOCK_RESOLUTION),
205            (
206                r#"{"clock_resolution": "250ms"}"#,
207                ConfigDuration::from_millis(250),
208            ),
209            (
210                r#"{"clock_resolution_usecs": 100000}"#,
211                ConfigDuration::from_millis(100),
212            ),
213        ] {
214            let config: ClockConfig = serde_json::from_str(json).unwrap();
215            assert_eq!(config.clock_resolution(), expected, "parsing {json}");
216        }
217
218        // Both spellings reach one field, so writing both is a duplicate.
219        let error = serde_json::from_str::<ClockConfig>(
220            r#"{"clock_resolution": "250ms", "clock_resolution_usecs": 100000}"#,
221        )
222        .unwrap_err()
223        .to_string();
224        assert!(
225            error.contains("duplicate field `clock_resolution`"),
226            "{error}"
227        );
228    }
229
230    #[test]
231    fn timezone_offset_parses_and_round_trips() {
232        const MINUTE_MS: i64 = 60_000;
233        for (input, expected_ms) in [
234            ("+05:30", (5 * 60 + 30) * MINUTE_MS),
235            ("-08:00", -8 * 60 * MINUTE_MS),
236            ("+00:00", 0),
237            ("+14:00", 14 * 60 * MINUTE_MS),
238        ] {
239            let offset: ClockTimezoneOffset =
240                serde_json::from_value(serde_json::json!(input)).unwrap();
241            assert_eq!(offset.offset_ms(), expected_ms, "input {input}");
242            assert_eq!(
243                serde_json::to_value(offset).unwrap(),
244                serde_json::json!(input),
245                "round trip of {input}"
246            );
247        }
248    }
249
250    /// Configurations written before the offset existed must read back
251    /// with no offset.
252    #[test]
253    fn clock_config_without_offset_defaults_to_zero() {
254        let config: super::ClockConfig =
255            serde_json::from_value(serde_json::json!({"clock_resolution_usecs": 1_000_000}))
256                .unwrap();
257        assert_eq!(config.timezone_offset_ms, 0);
258
259        let runtime_config: crate::config::RuntimeConfig =
260            serde_json::from_value(serde_json::json!({"workers": 4})).unwrap();
261        assert_eq!(runtime_config.clock_timezone_offset, None);
262    }
263
264    #[test]
265    fn timezone_offset_rejects_invalid_input() {
266        // Missing sign, garbage, out of chrono's (-24h, +24h) range, and
267        // non-string JSON must all fail deserialization.
268        for input in [
269            serde_json::json!("05:30"),
270            serde_json::json!("banana"),
271            serde_json::json!("+27:00"),
272            serde_json::json!(330),
273        ] {
274            assert!(
275                serde_json::from_value::<ClockTimezoneOffset>(input.clone()).is_err(),
276                "input {input} should be rejected"
277            );
278        }
279    }
280}