s2_kit/lib.rs
1//! The S2 energy flexibility standard in Rust.
2//!
3//! S2 — formally **EN 50491-12-2**, internationally IEC 63402-2-2 — is the European
4//! standard for communicating energy flexibility between a **Customer Energy Manager**
5//! (CEM) and a **Resource Manager** (RM). The RM describes *how* a device can behave; the
6//! CEM decides *why* it should. The standard's own image is a menu: the RM writes it, the
7//! CEM orders from it, and the RM may always refuse.
8//!
9//! This crate implements the two open specifications that make the standard usable over
10//! IP:
11//!
12//! * **S2 JSON v1.0.0** — the 36 messages and 41 component types, their encoding, and the
13//! protocol around them: control-type selection, reception statuses, revocation,
14//! validity windows, timers and instruction lifecycles.
15//! * **S2 Connect 1.0.0** — DNS-SD discovery, HMAC challenge–response pairing,
16//! access-token session initiation, the WebSocket transport and the reconnection rules.
17//!
18//! # Where to start
19//!
20//! | You are building | Start at |
21//! |---|---|
22//! | A device that offers flexibility | [`session::RmSession`] |
23//! | An energy manager that uses it | [`session::CemSession`] |
24//! | A proxy, analyzer or log reader | [`session::Analyzer`] |
25//! | Two devices that must find and trust each other | [`connect`] |
26//! | Something over a transport that is not WebSocket | [`session`], and drive it yourself |
27//!
28//! Longer guides, the full rule catalogue and the conformance statement are at
29//! <https://hupe1980.github.io/s2-kit>.
30//!
31//! ```
32//! use s2_kit::prelude::*;
33//!
34//! let details = ResourceManagerDetails::builder()
35//! .resource_id(Id::parse("battery-1")?)
36//! .roles(vec![Role { role: RoleType::EnergyStorage, commodity: Commodity::Electricity }])
37//! .instruction_processing_delay(Duration::from_millis(500))
38//! .available_control_types(vec![ControlType::FillRateBasedControl])
39//! .provides_forecast(false)
40//! .provides_power_measurement_types(vec![CommodityQuantity::ElectricPower3PhaseSymmetric])
41//! .build();
42//!
43//! let mut rm = RmSession::new(RmConfig::default(), details);
44//! rm.open(Timestamp::now());
45//!
46//! // Everything the session wants to say is waiting here; a driver writes it to a socket.
47//! let first = rm.poll_transmit().expect("the RM speaks first");
48//! assert!(first.text.contains(r#""message_type":"Handshake""#));
49//! # Ok::<(), Box<dyn std::error::Error>>(())
50//! ```
51//!
52//! # Design in one paragraph
53//!
54//! The protocol core is **sans-I/O**: no sockets, no clock, no tasks. Every engine takes
55//! `now` as a parameter and is driven by `handle_*` / `poll_*`, so a two-hour timer, a
56//! lost acknowledgement and a revoked constraint are all ordinary unit tests. Drivers —
57//! WebSocket, HTTPS, mDNS — are Cargo features that hang off the side. The data model is
58//! hand-written and *proven* against the standard's own JSON schemas in CI rather than
59//! generated from a modified copy of them, and the layer above it is a
60//! [rule-numbered semantic validator](validate) for everything JSON Schema cannot express.
61//!
62//! # Features
63//!
64//! | Feature | Enables |
65//! |---|---|
66//! | `std` *(default)* | The standard library. Without it the crate is `no_std + alloc`. |
67//! | `uuid` *(default)* | [`Id::generate`](types::Id::generate) and friends. |
68//! | `tokio` | [`io::Driver`], which pumps a session over any text transport. |
69//! | `connect-client` | Pairing and session initiation, with leaf-fingerprint capture and CA pinning. |
70//! | `connect-server` | An `axum` router for both APIs and the authorised WebSocket, TLS serving, a self-signed CA helper. |
71//! | `discovery` | DNS-SD advertise and browse of `_s2connect._tcp`. |
72//! | `tls-ring` *(default)* | `ring` as the bundled TLS cryptography; no `cmake` to cross-compile. |
73//! | `tls-aws-lc-rs` | `aws-lc-rs` instead: FIPS-certifiable, post-quantum. Exactly one is linked. |
74//! | `jiff` / `time` / `chrono` | [`Timestamp`] conversions, with the crate re-exported. |
75//! | `testing` | Fixtures, the two-engine harness, the in-memory pipe, and `.s2log` transcripts read as well as written. |
76//! | `schemars` | `JsonSchema` for this crate's own types, for the equivalence check. |
77//! | `tracing` | A span per session and an event per message from the drivers, keyed by `message_id`; never a payload. |
78//! | `cli` | The `s2-kit` command-line tool. |
79
80#![cfg_attr(not(feature = "std"), no_std)]
81#![cfg_attr(docsrs, feature(doc_cfg))]
82// Tests are allowed to panic: that is what a failing assertion is. The lints are on for
83// everything else, where a panic in a driver answering a peer is a crash.
84#![cfg_attr(
85 test,
86 allow(
87 clippy::unwrap_used,
88 clippy::expect_used,
89 clippy::panic,
90 clippy::indexing_slicing,
91 clippy::float_cmp,
92 )
93)]
94#![cfg_attr(doctest, doc = include_str!("../README.md"))]
95#![doc(html_logo_url = "https://s2standard.org/wp-content/uploads/2023/09/Logo-S2.svg")]
96
97extern crate alloc;
98
99#[cfg(feature = "std")]
100extern crate std;
101
102pub mod codec;
103pub mod message;
104pub mod model;
105pub mod schema;
106pub mod session;
107pub mod types;
108pub mod validate;
109
110pub mod connect;
111
112pub(crate) mod trace;
113
114// The website's guides, as doctests. Generated by `cargo xtask gen-site-examples`; it
115// exists so a snippet a reader copies out of a guide is a snippet that compiles. Only
116// rustdoc ever builds it.
117#[cfg(doctest)]
118mod site_doctests;
119
120#[cfg(feature = "tokio")]
121#[cfg_attr(docsrs, doc(cfg(feature = "tokio")))]
122pub mod io;
123
124#[cfg(feature = "testing")]
125#[cfg_attr(docsrs, doc(cfg(feature = "testing")))]
126pub mod testing;
127
128pub use codec::{DecodeError, DecodeOptions, Strictness, decode, decode_with, encode};
129pub use message::{Message, MessageKind};
130pub use types::{Duration, Id, ProtocolVersion, Timestamp, WireProfile};
131
132/// Everything a typical Resource Manager or Customer Energy Manager needs.
133pub mod prelude {
134 pub use crate::codec::{DecodeError, Strictness, decode, encode};
135 pub use crate::message::{Message, MessageKind};
136 pub use crate::session::{
137 CemConfig, CemEvent, CemSession, CloseReason, Instructed, Negotiation, RmConfig, RmEvent,
138 RmSession, SessionState,
139 };
140 pub use crate::types::common::*;
141 pub use crate::types::{
142 Duration, Id, ProtocolVersion, Timestamp, WireProfile, ddbc, frbc, ombc, pebc, ppbc,
143 };
144 pub use crate::validate::{Report, RuleId, Severity, Validate, Violation};
145}
146
147// The rule for this block: if a type from crate `X` is reachable from this crate's public
148// API, `X` is re-exported here under the feature that brings it in — so a caller names the
149// version this crate was built against instead of keeping a major in step by hand. A
150// drifted one otherwise reports `expected MaybeTlsStream<TcpStream>, found
151// MaybeTlsStream<TcpStream>`.
152#[cfg(feature = "chrono")]
153#[cfg_attr(docsrs, doc(cfg(feature = "chrono")))]
154pub use chrono;
155#[cfg(feature = "jiff")]
156#[cfg_attr(docsrs, doc(cfg(feature = "jiff")))]
157pub use jiff;
158#[cfg(feature = "time")]
159#[cfg_attr(docsrs, doc(cfg(feature = "time")))]
160pub use time;
161#[cfg(feature = "uuid")]
162#[cfg_attr(docsrs, doc(cfg(feature = "uuid")))]
163pub use uuid;
164
165// `WebSocket::connect` returns a
166// `WebSocket<MaybeTlsStream<TcpStream>>`; [`io::Dialled`] is its short spelling.
167#[cfg(feature = "tokio")]
168#[cfg_attr(docsrs, doc(cfg(feature = "tokio")))]
169pub use tokio;
170#[cfg(feature = "tokio")]
171#[cfg_attr(docsrs, doc(cfg(feature = "tokio")))]
172pub use tokio_tungstenite;
173
174// `CapturedIdentity::chain` carries `CertificateDer`s, `TlsClient::config` an
175// `Arc<ClientConfig>`, `default_provider` an `Arc<CryptoProvider>`.
176#[cfg(feature = "tokio")]
177#[cfg_attr(docsrs, doc(cfg(feature = "tokio")))]
178pub use rustls;
179
180// `connect::server`'s routers are `axum::Router`s, mounted in an application's own.
181#[cfg(feature = "connect-server")]
182#[cfg_attr(docsrs, doc(cfg(feature = "connect-server")))]
183pub use axum;
184
185// `Discovery::daemon` hands back the `mdns_sd::ServiceDaemon` it is driving.
186#[cfg(feature = "discovery")]
187#[cfg_attr(docsrs, doc(cfg(feature = "discovery")))]
188pub use mdns_sd;