s2_kit/types/mod.rs
1//! The S2 JSON data model: 36 messages and 41 component types.
2//!
3//! Types common to every control type are in [`common`]; the rest are grouped by the
4//! control type they belong to ([`pebc`], [`ppbc`], [`ombc`], [`frbc`], [`ddbc`]). The
5//! scalar types the whole model rests on — [`Id`], [`Timestamp`], [`Duration`] — are
6//! re-exported here.
7//!
8//! The model is **wire-faithful**, warts included: `DDBC.OperationMode` really does
9//! capitalise its `Id` field, `DDBC.ActuatorDescription` really does spell it
10//! `supported_commodites`, and `ControlType` really does say `NOT_CONTROLABLE`. Each is
11//! carried by a `#[serde(rename)]` so the bytes are right while the Rust identifier is
12//! not also wrong, and each is listed as errata.
13//!
14//! What the types do **not** do is judge. A factor of 1.3 and a 289-element forecast are
15//! both representable, because a proxy has to be able to carry a message it would refuse
16//! to send, and because `INVALID_CONTENT` is a reception status the standard wants sent —
17//! which requires having decoded the message first. [`crate::validate`] is what judges;
18//! the builders are what refuse.
19
20pub mod common;
21pub mod ddbc;
22pub mod frbc;
23pub mod id;
24pub mod ombc;
25pub mod pebc;
26pub mod ppbc;
27pub mod time;
28
29pub use common::*;
30pub use id::{Id, InvalidId};
31pub use time::{Duration, InvalidTimestamp, TimeOutOfRange, Timestamp};
32
33use alloc::borrow::{Cow, ToOwned};
34use alloc::string::String;
35use serde::{Deserialize, Serialize};
36
37/// An S2 JSON version string as it appears on the wire.
38///
39/// S2 negotiates versions by **exact string match**: `S2C §Versioning of JSON Schema
40/// files` says "the exact version string **must** be used (e.g. `v1.0.0`)". No semver
41/// range is involved, and none should be inferred — `s2energy` parses the peer's string
42/// as a `VersionReq`, which accepts strings the peer never offered.
43///
44/// The complication is that the deployed ecosystem negotiates `"0.0.2-beta"` — the tag
45/// that predates S2 JSON v1.0.0 — while the schemas are tagged `v1.0.0`. Both are
46/// supported; [`WireProfile`] is what a version string means for the wire.
47///
48/// Every version this crate speaks is an associated constant of this type, in both
49/// spellings, so naming one costs nothing and mentions it once:
50///
51/// ```
52/// use s2_kit::{ProtocolVersion, WireProfile};
53///
54/// // What an S2 JSON handshake writes, and what S2 Connect writes (erratum E25).
55/// assert_eq!(ProtocolVersion::V1_0_0.as_str(), "1.0.0");
56/// assert_eq!(ProtocolVersion::V1_0_0_CONNECT.as_str(), "v1.0.0");
57///
58/// // Same version either way.
59/// assert!(ProtocolVersion::V1_0_0.matches(&ProtocolVersion::V1_0_0_CONNECT));
60///
61/// // And a profile hands out both without allocating.
62/// assert_eq!(WireProfile::V0_0_2Beta.version(), ProtocolVersion::V0_0_2_BETA);
63/// ```
64#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
65#[serde(transparent)]
66pub struct ProtocolVersion(Cow<'static, str>);
67
68impl ProtocolVersion {
69 /// S2 JSON v1.0.0, the current tag, as an S2 JSON handshake spells it.
70 pub const V1_0_0: Self = Self::from_static("1.0.0");
71 /// S2 JSON v0.0.2-beta, what every deployed implementation still negotiates.
72 pub const V0_0_2_BETA: Self = Self::from_static("0.0.2-beta");
73 /// S2 JSON v1.0.0 as **S2 Connect** spells it, with the `v` (erratum E25).
74 pub const V1_0_0_CONNECT: Self = Self::from_static("v1.0.0");
75 /// S2 JSON v0.0.2-beta as **S2 Connect** spells it, with the `v` (erratum E25).
76 pub const V0_0_2_BETA_CONNECT: Self = Self::from_static("v0.0.2-beta");
77
78 /// Wrap a version string exactly as it will appear on the wire.
79 #[must_use]
80 pub fn new(s: impl Into<String>) -> Self {
81 Self(Cow::Owned(s.into()))
82 }
83
84 /// Wrap a `'static` version string without allocating. `const`, and what the
85 /// associated constants above are built from.
86 #[must_use]
87 pub const fn from_static(s: &'static str) -> Self {
88 Self(Cow::Borrowed(s))
89 }
90
91 /// The string.
92 #[must_use]
93 pub fn as_str(&self) -> &str {
94 &self.0
95 }
96
97 /// The version without the optional `v` the two specifications disagree about.
98 ///
99 /// `S2C` requires `v1.0.0`, every S2 JSON handshake writes `1.0.0`, and
100 /// `s2energy-connection`'s examples write `v1`. This crate transmits one spelling and
101 /// understands both (erratum E25).
102 #[must_use]
103 pub fn canonical(&self) -> &str {
104 self.0.strip_prefix('v').unwrap_or(&self.0)
105 }
106
107 /// Whether two version strings name the same version.
108 ///
109 /// Exact match on the canonical form — **not** a semver range, which is how
110 /// `s2energy` accepts versions the peer never offered (D5). The leading `v` is the
111 /// only latitude.
112 #[must_use]
113 pub fn matches(&self, other: &Self) -> bool {
114 self.canonical() == other.canonical()
115 }
116
117 /// Which wire shape this version string selects, if this crate knows it.
118 #[must_use]
119 pub fn wire_profile(&self) -> Option<WireProfile> {
120 match self.canonical() {
121 "1.0.0" => Some(WireProfile::V1_0_0),
122 "0.0.2-beta" => Some(WireProfile::V0_0_2Beta),
123 _ => None,
124 }
125 }
126
127 /// Whether this crate can speak this version.
128 #[must_use]
129 pub fn is_supported(&self) -> bool {
130 self.wire_profile().is_some()
131 }
132}
133
134impl From<&str> for ProtocolVersion {
135 fn from(s: &str) -> Self {
136 Self(Cow::Owned(s.to_owned()))
137 }
138}
139
140impl From<String> for ProtocolVersion {
141 fn from(s: String) -> Self {
142 Self(Cow::Owned(s))
143 }
144}
145
146impl core::fmt::Display for ProtocolVersion {
147 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
148 f.write_str(&self.0)
149 }
150}
151
152impl core::fmt::Debug for ProtocolVersion {
153 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
154 write!(f, "ProtocolVersion({:?})", self.0)
155 }
156}
157
158/// A shape of the S2 JSON wire.
159///
160/// The two tagged versions of S2 JSON differ in exactly one place. Content-diffing them
161/// (ignoring `$id`) shows:
162///
163/// | | `v0.0.2-beta` | `v1.0.0` |
164/// |---|---|---|
165/// | `DDBC.SystemDescription` | required `present_demand_rate` | field absent |
166/// | `DDBC.PresentDemandStatus` | does not exist | a message |
167/// | everything else | identical | identical |
168///
169/// So one enum and one `Option` carry the whole difference, and the codec enforces it
170/// per negotiated version.
171#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
172#[non_exhaustive]
173pub enum WireProfile {
174 /// S2 JSON v1.0.0.
175 #[default]
176 V1_0_0,
177 /// S2 JSON v0.0.2-beta — what the deployed ecosystem still negotiates.
178 V0_0_2Beta,
179}
180
181impl WireProfile {
182 /// Every profile this crate speaks, most preferred first — the default offer.
183 pub const ALL: [Self; 2] = [Self::V1_0_0, Self::V0_0_2Beta];
184
185 /// The version string this crate offers for the profile **in an S2 JSON handshake**.
186 ///
187 /// No `v`, which is what every deployed implementation negotiates;
188 /// [`connect_version_str`](Self::connect_version_str) is the other spelling.
189 #[must_use]
190 pub const fn version_str(self) -> &'static str {
191 match self {
192 Self::V1_0_0 => "1.0.0",
193 Self::V0_0_2Beta => "0.0.2-beta",
194 }
195 }
196
197 /// The version string this crate offers for the profile **over S2 Connect**.
198 ///
199 /// With the `v`, which `S2C §Versioning of JSON Schema files` requires. Only what goes
200 /// out: [`ProtocolVersion::matches`] understands either spelling (E25).
201 #[must_use]
202 pub const fn connect_version_str(self) -> &'static str {
203 match self {
204 Self::V1_0_0 => "v1.0.0",
205 Self::V0_0_2Beta => "v0.0.2-beta",
206 }
207 }
208
209 /// The version string, as a [`ProtocolVersion`]. Allocation-free.
210 #[must_use]
211 pub const fn version(self) -> ProtocolVersion {
212 match self {
213 Self::V1_0_0 => ProtocolVersion::V1_0_0,
214 Self::V0_0_2Beta => ProtocolVersion::V0_0_2_BETA,
215 }
216 }
217
218 /// The S2 Connect version string, as a [`ProtocolVersion`]. Allocation-free.
219 #[must_use]
220 pub const fn connect_version(self) -> ProtocolVersion {
221 match self {
222 Self::V1_0_0 => ProtocolVersion::V1_0_0_CONNECT,
223 Self::V0_0_2Beta => ProtocolVersion::V0_0_2_BETA_CONNECT,
224 }
225 }
226
227 /// Whether `DDBC.SystemDescription` must carry `present_demand_rate`.
228 #[must_use]
229 pub const fn ddbc_system_description_carries_demand_rate(self) -> bool {
230 matches!(self, Self::V0_0_2Beta)
231 }
232
233 /// Every profile this crate speaks, most recent first.
234 #[must_use]
235 pub const fn all() -> &'static [Self] {
236 &[Self::V1_0_0, Self::V0_0_2Beta]
237 }
238}
239
240impl core::fmt::Display for WireProfile {
241 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
242 f.write_str(self.version_str())
243 }
244}
245
246#[cfg(test)]
247mod tests {
248 use super::*;
249
250 #[test]
251 fn the_constants_are_the_strings_the_two_specifications_write() {
252 // Both spellings are values rather than loose `&str`s: naming a version is the
253 // commonest thing a consumer does, and it should mention the version once.
254 assert_eq!(ProtocolVersion::V1_0_0.as_str(), "1.0.0");
255 assert_eq!(ProtocolVersion::V1_0_0_CONNECT.as_str(), "v1.0.0");
256 assert_eq!(ProtocolVersion::V0_0_2_BETA.as_str(), "0.0.2-beta");
257 assert_eq!(ProtocolVersion::V0_0_2_BETA_CONNECT.as_str(), "v0.0.2-beta");
258
259 // The `v` is the only latitude, so the two spellings are the same version.
260 assert!(ProtocolVersion::V1_0_0.matches(&ProtocolVersion::V1_0_0_CONNECT));
261 assert!(ProtocolVersion::V0_0_2_BETA.matches(&ProtocolVersion::V0_0_2_BETA_CONNECT));
262 assert!(!ProtocolVersion::V1_0_0.matches(&ProtocolVersion::V0_0_2_BETA));
263
264 // And they are exactly what the profiles hand out, without allocating.
265 for profile in WireProfile::all() {
266 assert_eq!(profile.version().as_str(), profile.version_str());
267 assert_eq!(
268 profile.connect_version().as_str(),
269 profile.connect_version_str()
270 );
271 }
272
273 // `#[serde(transparent)]` over a `Cow` is still a bare JSON string.
274 assert_eq!(
275 serde_json::to_string(&ProtocolVersion::V0_0_2_BETA).unwrap(),
276 "\"0.0.2-beta\""
277 );
278 assert_eq!(
279 serde_json::from_str::<ProtocolVersion>("\"v1.0.0\"").unwrap(),
280 ProtocolVersion::V1_0_0_CONNECT
281 );
282 }
283
284 #[test]
285 fn version_strings_map_to_profiles_exactly() {
286 for (s, expected) in [
287 ("1.0.0", Some(WireProfile::V1_0_0)),
288 ("v1.0.0", Some(WireProfile::V1_0_0)),
289 ("0.0.2-beta", Some(WireProfile::V0_0_2Beta)),
290 ("v0.0.2-beta", Some(WireProfile::V0_0_2Beta)),
291 // Not a range match: 1.0.1 is not 1.0.0, and we do not guess.
292 ("1.0.1", None),
293 ("1.1", None),
294 ("", None),
295 ("latest", None),
296 ] {
297 assert_eq!(ProtocolVersion::new(s).wire_profile(), expected, "{s:?}");
298 }
299 }
300
301 #[test]
302 fn the_two_specifications_spell_one_version_two_ways_and_both_are_understood() {
303 // `S2C §Versioning of JSON Schema files` requires `v1.0.0`; every S2 JSON
304 // handshake in the wild writes `1.0.0`. Exact matching on either side means the
305 // two do not interoperate, which is erratum E25.
306 let connect = ProtocolVersion::new("v1.0.0");
307 let handshake = ProtocolVersion::new("1.0.0");
308 assert!(connect.matches(&handshake));
309 assert!(handshake.matches(&connect));
310 assert_eq!(connect.canonical(), "1.0.0");
311 assert_eq!(handshake.canonical(), "1.0.0");
312 // The string on the wire is untouched: matching is tolerant, transmission is not.
313 assert_eq!(connect.as_str(), "v1.0.0");
314 assert_eq!(handshake.as_str(), "1.0.0");
315
316 // And each specification gets the spelling it asks for.
317 assert_eq!(WireProfile::V1_0_0.version_str(), "1.0.0");
318 assert_eq!(WireProfile::V1_0_0.connect_version_str(), "v1.0.0");
319 assert_eq!(WireProfile::V0_0_2Beta.version_str(), "0.0.2-beta");
320 assert_eq!(WireProfile::V0_0_2Beta.connect_version_str(), "v0.0.2-beta");
321 for profile in WireProfile::all() {
322 assert!(profile.version().matches(&profile.connect_version()));
323 assert_eq!(profile.connect_version().wire_profile(), Some(*profile));
324 }
325 }
326
327 #[test]
328 fn tolerating_the_prefix_is_not_tolerating_a_range() {
329 // The one latitude taken is the `v`. Everything else is still an exact match —
330 // `s2energy` parsing the peer's string as a `VersionReq` is what makes it accept
331 // versions the peer never offered (D5), and `v1` is the API major version, not a
332 // schema version at all.
333 for s in [
334 "1.0",
335 "1",
336 "v1",
337 "1.0.1",
338 "^1.0.0",
339 "1.0.0-rc1",
340 "vv1.0.0",
341 "",
342 ] {
343 assert_eq!(ProtocolVersion::new(s).wire_profile(), None, "{s:?}");
344 assert!(
345 !ProtocolVersion::new(s).matches(&ProtocolVersion::new("1.0.0")),
346 "{s:?} must not match 1.0.0"
347 );
348 }
349 }
350
351 #[test]
352 fn only_the_beta_profile_carries_the_ddbc_demand_rate() {
353 assert!(WireProfile::V0_0_2Beta.ddbc_system_description_carries_demand_rate());
354 assert!(!WireProfile::V1_0_0.ddbc_system_description_carries_demand_rate());
355 }
356}