Skip to main content

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    /// The version string this crate offers for the profile **in an S2 JSON handshake**.
183    ///
184    /// No `v`, which is what every deployed implementation negotiates;
185    /// [`connect_version_str`](Self::connect_version_str) is the other spelling.
186    #[must_use]
187    pub const fn version_str(self) -> &'static str {
188        match self {
189            Self::V1_0_0 => "1.0.0",
190            Self::V0_0_2Beta => "0.0.2-beta",
191        }
192    }
193
194    /// The version string this crate offers for the profile **over S2 Connect**.
195    ///
196    /// With the `v`, which `S2C §Versioning of JSON Schema files` requires. Only what goes
197    /// out: [`ProtocolVersion::matches`] understands either spelling (E25).
198    #[must_use]
199    pub const fn connect_version_str(self) -> &'static str {
200        match self {
201            Self::V1_0_0 => "v1.0.0",
202            Self::V0_0_2Beta => "v0.0.2-beta",
203        }
204    }
205
206    /// The version string, as a [`ProtocolVersion`]. Allocation-free.
207    #[must_use]
208    pub const fn version(self) -> ProtocolVersion {
209        match self {
210            Self::V1_0_0 => ProtocolVersion::V1_0_0,
211            Self::V0_0_2Beta => ProtocolVersion::V0_0_2_BETA,
212        }
213    }
214
215    /// The S2 Connect version string, as a [`ProtocolVersion`]. Allocation-free.
216    #[must_use]
217    pub const fn connect_version(self) -> ProtocolVersion {
218        match self {
219            Self::V1_0_0 => ProtocolVersion::V1_0_0_CONNECT,
220            Self::V0_0_2Beta => ProtocolVersion::V0_0_2_BETA_CONNECT,
221        }
222    }
223
224    /// Whether `DDBC.SystemDescription` must carry `present_demand_rate`.
225    #[must_use]
226    pub const fn ddbc_system_description_carries_demand_rate(self) -> bool {
227        matches!(self, Self::V0_0_2Beta)
228    }
229
230    /// Every profile this crate speaks, most recent first.
231    #[must_use]
232    pub const fn all() -> &'static [Self] {
233        &[Self::V1_0_0, Self::V0_0_2Beta]
234    }
235}
236
237impl core::fmt::Display for WireProfile {
238    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
239        f.write_str(self.version_str())
240    }
241}
242
243#[cfg(test)]
244mod tests {
245    use super::*;
246
247    #[test]
248    fn the_constants_are_the_strings_the_two_specifications_write() {
249        // Both spellings are values rather than loose `&str`s: naming a version is the
250        // commonest thing a consumer does, and it should mention the version once.
251        assert_eq!(ProtocolVersion::V1_0_0.as_str(), "1.0.0");
252        assert_eq!(ProtocolVersion::V1_0_0_CONNECT.as_str(), "v1.0.0");
253        assert_eq!(ProtocolVersion::V0_0_2_BETA.as_str(), "0.0.2-beta");
254        assert_eq!(ProtocolVersion::V0_0_2_BETA_CONNECT.as_str(), "v0.0.2-beta");
255
256        // The `v` is the only latitude, so the two spellings are the same version.
257        assert!(ProtocolVersion::V1_0_0.matches(&ProtocolVersion::V1_0_0_CONNECT));
258        assert!(ProtocolVersion::V0_0_2_BETA.matches(&ProtocolVersion::V0_0_2_BETA_CONNECT));
259        assert!(!ProtocolVersion::V1_0_0.matches(&ProtocolVersion::V0_0_2_BETA));
260
261        // And they are exactly what the profiles hand out, without allocating.
262        for profile in WireProfile::all() {
263            assert_eq!(profile.version().as_str(), profile.version_str());
264            assert_eq!(
265                profile.connect_version().as_str(),
266                profile.connect_version_str()
267            );
268        }
269
270        // `#[serde(transparent)]` over a `Cow` is still a bare JSON string.
271        assert_eq!(
272            serde_json::to_string(&ProtocolVersion::V0_0_2_BETA).unwrap(),
273            "\"0.0.2-beta\""
274        );
275        assert_eq!(
276            serde_json::from_str::<ProtocolVersion>("\"v1.0.0\"").unwrap(),
277            ProtocolVersion::V1_0_0_CONNECT
278        );
279    }
280
281    #[test]
282    fn version_strings_map_to_profiles_exactly() {
283        for (s, expected) in [
284            ("1.0.0", Some(WireProfile::V1_0_0)),
285            ("v1.0.0", Some(WireProfile::V1_0_0)),
286            ("0.0.2-beta", Some(WireProfile::V0_0_2Beta)),
287            ("v0.0.2-beta", Some(WireProfile::V0_0_2Beta)),
288            // Not a range match: 1.0.1 is not 1.0.0, and we do not guess.
289            ("1.0.1", None),
290            ("1.1", None),
291            ("", None),
292            ("latest", None),
293        ] {
294            assert_eq!(ProtocolVersion::new(s).wire_profile(), expected, "{s:?}");
295        }
296    }
297
298    #[test]
299    fn the_two_specifications_spell_one_version_two_ways_and_both_are_understood() {
300        // `S2C §Versioning of JSON Schema files` requires `v1.0.0`; every S2 JSON
301        // handshake in the wild writes `1.0.0`. Exact matching on either side means the
302        // two do not interoperate, which is erratum E25.
303        let connect = ProtocolVersion::new("v1.0.0");
304        let handshake = ProtocolVersion::new("1.0.0");
305        assert!(connect.matches(&handshake));
306        assert!(handshake.matches(&connect));
307        assert_eq!(connect.canonical(), "1.0.0");
308        assert_eq!(handshake.canonical(), "1.0.0");
309        // The string on the wire is untouched: matching is tolerant, transmission is not.
310        assert_eq!(connect.as_str(), "v1.0.0");
311        assert_eq!(handshake.as_str(), "1.0.0");
312
313        // And each specification gets the spelling it asks for.
314        assert_eq!(WireProfile::V1_0_0.version_str(), "1.0.0");
315        assert_eq!(WireProfile::V1_0_0.connect_version_str(), "v1.0.0");
316        assert_eq!(WireProfile::V0_0_2Beta.version_str(), "0.0.2-beta");
317        assert_eq!(WireProfile::V0_0_2Beta.connect_version_str(), "v0.0.2-beta");
318        for profile in WireProfile::all() {
319            assert!(profile.version().matches(&profile.connect_version()));
320            assert_eq!(profile.connect_version().wire_profile(), Some(*profile));
321        }
322    }
323
324    #[test]
325    fn tolerating_the_prefix_is_not_tolerating_a_range() {
326        // The one latitude taken is the `v`. Everything else is still an exact match —
327        // `s2energy` parsing the peer's string as a `VersionReq` is what makes it accept
328        // versions the peer never offered (D5), and `v1` is the API major version, not a
329        // schema version at all.
330        for s in [
331            "1.0",
332            "1",
333            "v1",
334            "1.0.1",
335            "^1.0.0",
336            "1.0.0-rc1",
337            "vv1.0.0",
338            "",
339        ] {
340            assert_eq!(ProtocolVersion::new(s).wire_profile(), None, "{s:?}");
341            assert!(
342                !ProtocolVersion::new(s).matches(&ProtocolVersion::new("1.0.0")),
343                "{s:?} must not match 1.0.0"
344            );
345        }
346    }
347
348    #[test]
349    fn only_the_beta_profile_carries_the_ddbc_demand_rate() {
350        assert!(WireProfile::V0_0_2Beta.ddbc_system_description_carries_demand_rate());
351        assert!(!WireProfile::V1_0_0.ddbc_system_description_carries_demand_rate());
352    }
353}