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::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#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
48#[serde(transparent)]
49pub struct ProtocolVersion(String);
50
51impl ProtocolVersion {
52 /// S2 JSON v1.0.0, the current tag.
53 pub const V1_0_0: &'static str = "1.0.0";
54 /// S2 JSON v0.0.2-beta, what every deployed implementation still negotiates.
55 pub const V0_0_2_BETA: &'static str = "0.0.2-beta";
56
57 /// Wrap a version string exactly as it will appear on the wire.
58 #[must_use]
59 pub fn new(s: impl Into<String>) -> Self {
60 Self(s.into())
61 }
62
63 /// The string.
64 #[must_use]
65 pub fn as_str(&self) -> &str {
66 &self.0
67 }
68
69 /// The version without the optional `v` the two specifications disagree about.
70 ///
71 /// `S2C` requires `v1.0.0`, every S2 JSON handshake writes `1.0.0`, and
72 /// `s2energy-connection`'s examples write `v1`. This crate transmits one spelling and
73 /// understands both (erratum E25).
74 #[must_use]
75 pub fn canonical(&self) -> &str {
76 self.0.strip_prefix('v').unwrap_or(&self.0)
77 }
78
79 /// Whether two version strings name the same version.
80 ///
81 /// Exact match on the canonical form — **not** a semver range, which is how
82 /// `s2energy` accepts versions the peer never offered (D5). The leading `v` is the
83 /// only latitude.
84 #[must_use]
85 pub fn matches(&self, other: &Self) -> bool {
86 self.canonical() == other.canonical()
87 }
88
89 /// Which wire shape this version string selects, if this crate knows it.
90 #[must_use]
91 pub fn wire_profile(&self) -> Option<WireProfile> {
92 match self.canonical() {
93 "1.0.0" => Some(WireProfile::V1_0_0),
94 "0.0.2-beta" => Some(WireProfile::V0_0_2Beta),
95 _ => None,
96 }
97 }
98
99 /// Whether this crate can speak this version.
100 #[must_use]
101 pub fn is_supported(&self) -> bool {
102 self.wire_profile().is_some()
103 }
104}
105
106impl From<&str> for ProtocolVersion {
107 fn from(s: &str) -> Self {
108 Self(s.to_owned())
109 }
110}
111
112impl From<String> for ProtocolVersion {
113 fn from(s: String) -> Self {
114 Self(s)
115 }
116}
117
118impl core::fmt::Display for ProtocolVersion {
119 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
120 f.write_str(&self.0)
121 }
122}
123
124impl core::fmt::Debug for ProtocolVersion {
125 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
126 write!(f, "ProtocolVersion({:?})", self.0)
127 }
128}
129
130/// A shape of the S2 JSON wire.
131///
132/// The two tagged versions of S2 JSON differ in exactly one place. Content-diffing them
133/// (ignoring `$id`) shows:
134///
135/// | | `v0.0.2-beta` | `v1.0.0` |
136/// |---|---|---|
137/// | `DDBC.SystemDescription` | required `present_demand_rate` | field absent |
138/// | `DDBC.PresentDemandStatus` | does not exist | a message |
139/// | everything else | identical | identical |
140///
141/// So one enum and one `Option` carry the whole difference, and the codec enforces it
142/// per negotiated version.
143#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
144#[non_exhaustive]
145pub enum WireProfile {
146 /// S2 JSON v1.0.0.
147 #[default]
148 V1_0_0,
149 /// S2 JSON v0.0.2-beta — what the deployed ecosystem still negotiates.
150 V0_0_2Beta,
151}
152
153impl WireProfile {
154 /// The version string this crate offers for the profile **in an S2 JSON handshake**.
155 ///
156 /// No `v`, which is what every deployed implementation negotiates;
157 /// [`connect_version_str`](Self::connect_version_str) is the other spelling.
158 #[must_use]
159 pub const fn version_str(self) -> &'static str {
160 match self {
161 Self::V1_0_0 => ProtocolVersion::V1_0_0,
162 Self::V0_0_2Beta => ProtocolVersion::V0_0_2_BETA,
163 }
164 }
165
166 /// The version string this crate offers for the profile **over S2 Connect**.
167 ///
168 /// With the `v`, which `S2C §Versioning of JSON Schema files` requires. Only what goes
169 /// out: [`ProtocolVersion::matches`] understands either spelling (E25).
170 #[must_use]
171 pub const fn connect_version_str(self) -> &'static str {
172 match self {
173 Self::V1_0_0 => "v1.0.0",
174 Self::V0_0_2Beta => "v0.0.2-beta",
175 }
176 }
177
178 /// The version string, as a [`ProtocolVersion`].
179 #[must_use]
180 pub fn version(self) -> ProtocolVersion {
181 ProtocolVersion::new(self.version_str())
182 }
183
184 /// The S2 Connect version string, as a [`ProtocolVersion`].
185 #[must_use]
186 pub fn connect_version(self) -> ProtocolVersion {
187 ProtocolVersion::new(self.connect_version_str())
188 }
189
190 /// Whether `DDBC.SystemDescription` must carry `present_demand_rate`.
191 #[must_use]
192 pub const fn ddbc_system_description_carries_demand_rate(self) -> bool {
193 matches!(self, Self::V0_0_2Beta)
194 }
195
196 /// Every profile this crate speaks, most recent first.
197 #[must_use]
198 pub const fn all() -> &'static [Self] {
199 &[Self::V1_0_0, Self::V0_0_2Beta]
200 }
201}
202
203impl core::fmt::Display for WireProfile {
204 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
205 f.write_str(self.version_str())
206 }
207}
208
209#[cfg(test)]
210mod tests {
211 use super::*;
212
213 #[test]
214 fn version_strings_map_to_profiles_exactly() {
215 for (s, expected) in [
216 ("1.0.0", Some(WireProfile::V1_0_0)),
217 ("v1.0.0", Some(WireProfile::V1_0_0)),
218 ("0.0.2-beta", Some(WireProfile::V0_0_2Beta)),
219 ("v0.0.2-beta", Some(WireProfile::V0_0_2Beta)),
220 // Not a range match: 1.0.1 is not 1.0.0, and we do not guess.
221 ("1.0.1", None),
222 ("1.1", None),
223 ("", None),
224 ("latest", None),
225 ] {
226 assert_eq!(ProtocolVersion::new(s).wire_profile(), expected, "{s:?}");
227 }
228 }
229
230 #[test]
231 fn the_two_specifications_spell_one_version_two_ways_and_both_are_understood() {
232 // `S2C §Versioning of JSON Schema files` requires `v1.0.0`; every S2 JSON
233 // handshake in the wild writes `1.0.0`. Exact matching on either side means the
234 // two do not interoperate, which is erratum E25.
235 let connect = ProtocolVersion::new("v1.0.0");
236 let handshake = ProtocolVersion::new("1.0.0");
237 assert!(connect.matches(&handshake));
238 assert!(handshake.matches(&connect));
239 assert_eq!(connect.canonical(), "1.0.0");
240 assert_eq!(handshake.canonical(), "1.0.0");
241 // The string on the wire is untouched: matching is tolerant, transmission is not.
242 assert_eq!(connect.as_str(), "v1.0.0");
243 assert_eq!(handshake.as_str(), "1.0.0");
244
245 // And each specification gets the spelling it asks for.
246 assert_eq!(WireProfile::V1_0_0.version_str(), "1.0.0");
247 assert_eq!(WireProfile::V1_0_0.connect_version_str(), "v1.0.0");
248 assert_eq!(WireProfile::V0_0_2Beta.version_str(), "0.0.2-beta");
249 assert_eq!(WireProfile::V0_0_2Beta.connect_version_str(), "v0.0.2-beta");
250 for profile in WireProfile::all() {
251 assert!(profile.version().matches(&profile.connect_version()));
252 assert_eq!(profile.connect_version().wire_profile(), Some(*profile));
253 }
254 }
255
256 #[test]
257 fn tolerating_the_prefix_is_not_tolerating_a_range() {
258 // The one latitude taken is the `v`. Everything else is still an exact match —
259 // `s2energy` parsing the peer's string as a `VersionReq` is what makes it accept
260 // versions the peer never offered (D5), and `v1` is the API major version, not a
261 // schema version at all.
262 for s in [
263 "1.0",
264 "1",
265 "v1",
266 "1.0.1",
267 "^1.0.0",
268 "1.0.0-rc1",
269 "vv1.0.0",
270 "",
271 ] {
272 assert_eq!(ProtocolVersion::new(s).wire_profile(), None, "{s:?}");
273 assert!(
274 !ProtocolVersion::new(s).matches(&ProtocolVersion::new("1.0.0")),
275 "{s:?} must not match 1.0.0"
276 );
277 }
278 }
279
280 #[test]
281 fn only_the_beta_profile_carries_the_ddbc_demand_rate() {
282 assert!(WireProfile::V0_0_2Beta.ddbc_system_description_carries_demand_rate());
283 assert!(!WireProfile::V1_0_0.ddbc_system_description_carries_demand_rate());
284 }
285}