use crate::std_shim::{String, ToString, Vec, format};
use serde_json::Value as Json;
pub const PRESERVED_PREFIX: &str = "x-openadr-preserved-";
pub trait WireAdapter: core::fmt::Debug + Send + Sync {
fn name(&self) -> &'static str;
fn inbound(&self, _body: &mut Json) {}
fn outbound(&self, _body: &mut Json) {}
}
#[derive(Debug, Clone, Copy, Default)]
pub struct Canonical;
impl WireAdapter for Canonical {
fn name(&self) -> &'static str {
"canonical"
}
}
#[derive(Debug, Clone, Copy, Default)]
pub struct Fluvius;
impl Fluvius {
const FREQUENCY: &'static str = "frequency";
const REQUIRED: &'static str = "required";
fn preserved_key(field: &str) -> String {
format!("{PRESERVED_PREFIX}{field}")
}
fn for_each_report_descriptor(body: &mut Json, f: impl Fn(&mut serde_json::Map<String, Json>)) {
fn walk(v: &mut Json, f: &(impl Fn(&mut serde_json::Map<String, Json>) + ?Sized)) {
match v {
Json::Array(items) => items.iter_mut().for_each(|i| walk(i, f)),
Json::Object(map) => {
if let Some(Json::Array(descriptors)) = map.get_mut("reportDescriptors") {
for d in descriptors {
if let Json::Object(d) = d {
f(d);
}
}
}
for (_, child) in map.iter_mut() {
walk(child, f);
}
}
_ => {}
}
}
walk(body, &f);
}
}
impl WireAdapter for Fluvius {
fn name(&self) -> &'static str {
"fluvius-netflex"
}
fn inbound(&self, body: &mut Json) {
Self::for_each_report_descriptor(body, |d| {
if let Some(Json::String(s)) = d.get(Self::FREQUENCY) {
let preserved = Json::String(s.clone());
d.remove(Self::FREQUENCY);
d.insert(Self::preserved_key(Self::FREQUENCY), preserved);
}
if let Some(flag) = d.remove(Self::REQUIRED) {
d.insert(Self::preserved_key(Self::REQUIRED), flag);
}
});
}
fn outbound(&self, body: &mut Json) {
Self::for_each_report_descriptor(body, |d| {
for field in [Self::FREQUENCY, Self::REQUIRED] {
if let Some(v) = d.remove(&Self::preserved_key(field)) {
d.insert(field.to_string(), v);
}
}
});
}
}
#[derive(Debug, Default)]
pub struct AdapterChain {
adapters: Vec<crate::std_shim::Box<dyn WireAdapter>>,
}
impl AdapterChain {
pub fn new() -> Self {
Self::default()
}
pub fn with(mut self, adapter: impl WireAdapter + 'static) -> Self {
self.adapters.push(crate::std_shim::Box::new(adapter));
self
}
pub fn is_empty(&self) -> bool {
self.adapters.is_empty()
}
pub fn names(&self) -> impl Iterator<Item = &'static str> {
self.adapters.iter().map(|a| a.name())
}
pub fn inbound(&self, body: &mut Json) {
for a in self.adapters.iter().rev() {
a.inbound(body);
}
}
pub fn outbound(&self, body: &mut Json) {
for a in &self.adapters {
a.outbound(body);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::model::ReportDescriptor;
fn fluvius_event() -> Json {
serde_json::json!({
"id": "event-2026-02-11-bat-001",
"programID": "tflex-da-batteries",
"targets": ["BATTERY-001"],
"reportDescriptors": [
{ "payloadType": "EVENT_STATUS", "required": true },
{ "payloadType": "COMPLIANCE_STATUS", "required": true, "frequency": "PT15M" }
]
})
}
#[test]
fn fluvius_event_does_not_parse_canonically() {
let d = &fluvius_event()["reportDescriptors"][1];
assert!(
serde_json::from_value::<ReportDescriptor>(d.clone()).is_err(),
"a string frequency must not parse as the schema's integer"
);
}
#[test]
fn fluvius_adapter_makes_it_parse_without_inventing_semantics() {
let mut body = fluvius_event();
Fluvius.inbound(&mut body);
let d: ReportDescriptor =
serde_json::from_value(body["reportDescriptors"][1].clone()).unwrap();
assert_eq!(d.frequency, -1);
assert_eq!(d.payload_type.as_str(), "COMPLIANCE_STATUS");
}
#[test]
fn deviations_survive_a_round_trip() {
let original = fluvius_event();
let mut body = original.clone();
Fluvius.inbound(&mut body);
Fluvius.outbound(&mut body);
assert_eq!(body, original);
}
#[test]
fn a_chain_of_two_undoes_itself_in_reverse() {
#[derive(Debug)]
struct Wrap(&'static str, &'static str);
impl WireAdapter for Wrap {
fn name(&self) -> &'static str {
self.0
}
fn outbound(&self, body: &mut Json) {
if let Some(Json::String(s)) = body.get_mut("v") {
*s = format!("{}({s})", self.1);
}
}
fn inbound(&self, body: &mut Json) {
if let Some(Json::String(s)) = body.get_mut("v") {
let open = format!("{}(", self.1);
if let Some(inner) = s.strip_prefix(&open).and_then(|r| r.strip_suffix(')')) {
*s = inner.to_string();
}
}
}
}
let chain = AdapterChain::new()
.with(Wrap("a", "A"))
.with(Wrap("b", "B"));
assert_eq!(chain.names().collect::<Vec<_>>(), vec!["a", "b"]);
let mut wire = serde_json::json!({ "v": "x" });
chain.outbound(&mut wire);
assert_eq!(wire["v"], "B(A(x))");
chain.inbound(&mut wire);
assert_eq!(wire["v"], "x", "the chain did not undo itself");
}
#[test]
fn adapter_reaches_descriptors_nested_in_a_notification() {
let mut body = serde_json::json!({
"objectType": "EVENT",
"operation": "CREATE",
"object": fluvius_event(),
});
Fluvius.inbound(&mut body);
assert!(
body["object"]["reportDescriptors"][1]
.get("x-openadr-preserved-frequency")
.is_some()
);
}
#[test]
fn chain_applies_and_unapplies_symmetrically() {
let chain = AdapterChain::new().with(Fluvius);
let original = fluvius_event();
let mut body = original.clone();
chain.inbound(&mut body);
chain.outbound(&mut body);
assert_eq!(body, original);
}
}