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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
27pub struct ClockTimezoneOffset(FixedOffset);
28
29impl ClockTimezoneOffset {
30 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
71fn 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 #[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 #[serde(default, skip_serializing_if = "is_zero")]
93 pub timezone_offset_ms: i64,
94
95 #[serde(default, skip_serializing_if = "Option::is_none")]
104 pub now_offset_ms: Option<i64>,
105
106 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
111 pub http_driven: bool,
112}
113
114impl ClockConfig {
115 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 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#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
140pub struct ClockAdvanceRequest {
141 #[serde(default)]
142 pub delta_ms: Option<u64>,
143}
144
145#[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 #[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 #[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 ("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 #[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 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 #[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 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}