1use std::collections::BTreeMap;
14
15use schemars::JsonSchema;
16use serde::{Deserialize, Serialize};
17use serde_json::Value;
18
19pub const NON_FINITE: &str = "$__zk2_private_non_finite";
24
25pub const DATETIME: &str = "$__toml_private_datetime";
28
29fn annotations<'de, D: serde::Deserializer<'de>>(
33 d: D,
34) -> Result<BTreeMap<String, Value>, D::Error> {
35 let raw = BTreeMap::<String, toml::Value>::deserialize(d)?;
36 Ok(raw.into_iter().map(|(k, v)| (k, from_toml(v))).collect())
37}
38
39fn from_toml(v: toml::Value) -> Value {
40 match v {
41 toml::Value::String(s) => Value::String(s),
42 toml::Value::Integer(i) => Value::from(i),
43 toml::Value::Float(f) => serde_json::Number::from_f64(f).map_or_else(
44 || {
45 Value::Object(
46 [(NON_FINITE.to_owned(), Value::String(f.to_string()))]
47 .into_iter()
48 .collect(),
49 )
50 },
51 Value::Number,
52 ),
53 toml::Value::Boolean(b) => Value::Bool(b),
54 toml::Value::Datetime(dt) => Value::Object(
55 [(DATETIME.to_owned(), Value::String(dt.to_string()))]
56 .into_iter()
57 .collect(),
58 ),
59 toml::Value::Array(a) => Value::Array(a.into_iter().map(from_toml).collect()),
60 toml::Value::Table(t) => {
61 Value::Object(t.into_iter().map(|(k, v)| (k, from_toml(v))).collect())
62 }
63 }
64}
65
66#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema)]
68#[serde(deny_unknown_fields)]
69pub struct ContractFile {
70 pub interface: InterfaceSection,
71 #[serde(default)]
72 pub defaults: Option<DefaultsSection>,
73 #[serde(default)]
74 pub schemas: SchemasSection,
75 #[serde(default)]
76 pub resources: BTreeMap<String, ResourceSpec>,
77 #[serde(default)]
78 pub requires: BTreeMap<String, Requirement>,
79}
80
81#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema)]
83#[serde(deny_unknown_fields)]
84pub struct InterfaceSection {
85 pub name: String,
87 #[schemars(range(max = 4_294_967_295_u32))]
88 pub major: u32,
89 #[serde(default)]
91 #[schemars(range(max = 4_294_967_295_u32))]
92 pub minor: Option<u32>,
93 #[serde(default)]
95 pub summary: Option<String>,
96 #[serde(default)]
98 pub uses: Vec<String>,
99}
100
101#[derive(Debug, Clone, Default, Deserialize, Serialize, JsonSchema)]
103#[serde(deny_unknown_fields)]
104pub struct SchemasSection {
105 #[serde(default)]
107 pub protobuf: Vec<String>,
108 #[serde(default)]
111 pub proto_include: Option<Vec<String>>,
112 #[serde(default)]
114 pub jsonschema: Vec<String>,
115 #[serde(default)]
118 pub packed: Vec<String>,
119}
120
121#[derive(Debug, Clone, Default, Deserialize, Serialize, JsonSchema)]
123#[serde(deny_unknown_fields)]
124pub struct DefaultsBlock {
125 #[serde(default, deserialize_with = "annotations")]
126 pub annotations: BTreeMap<String, Value>,
127 pub encoding: Option<Encoding>,
128 pub attachment_encoding: Option<Encoding>,
129 pub reliability: Option<Reliability>,
130 pub congestion: Option<Congestion>,
131 pub priority: Option<Priority>,
132 pub express: Option<bool>,
133 pub history: Option<History>,
134 pub idempotent: Option<bool>,
135 pub fanout: Option<Fanout>,
136 pub serving: Option<Serving>,
137 pub replies: Option<Replies>,
138 pub timeout_ms: Option<u64>,
139}
140
141#[derive(Debug, Clone, Default, Deserialize, Serialize, JsonSchema)]
143#[serde(deny_unknown_fields)]
144pub struct DefaultsSection {
145 #[serde(default, deserialize_with = "annotations")]
146 pub annotations: BTreeMap<String, Value>,
147 pub encoding: Option<Encoding>,
148 pub attachment_encoding: Option<Encoding>,
149 pub reliability: Option<Reliability>,
150 pub congestion: Option<Congestion>,
151 pub priority: Option<Priority>,
152 pub express: Option<bool>,
153 pub history: Option<History>,
154 pub idempotent: Option<bool>,
155 pub fanout: Option<Fanout>,
156 pub serving: Option<Serving>,
157 pub replies: Option<Replies>,
158 pub timeout_ms: Option<u64>,
159 pub stream: Option<DefaultsBlock>,
160 pub state: Option<DefaultsBlock>,
161 pub event: Option<DefaultsBlock>,
162 pub operation: Option<DefaultsBlock>,
163}
164
165impl DefaultsSection {
166 #[must_use]
168 pub fn base(&self) -> DefaultsBlock {
169 DefaultsBlock {
170 annotations: self.annotations.clone(),
171 encoding: self.encoding,
172 attachment_encoding: self.attachment_encoding,
173 reliability: self.reliability,
174 congestion: self.congestion,
175 priority: self.priority,
176 express: self.express,
177 history: self.history.clone(),
178 idempotent: self.idempotent,
179 fanout: self.fanout,
180 serving: self.serving,
181 replies: self.replies,
182 timeout_ms: self.timeout_ms,
183 }
184 }
185 #[must_use]
186 pub fn for_kind(&self, kind: Kind) -> Option<&DefaultsBlock> {
187 match kind {
188 Kind::Stream => self.stream.as_ref(),
189 Kind::State => self.state.as_ref(),
190 Kind::Event => self.event.as_ref(),
191 Kind::Operation => self.operation.as_ref(),
192 }
193 }
194}
195
196#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema)]
199#[serde(deny_unknown_fields)]
200pub struct ResourceSpec {
201 pub kind: Kind,
202 #[serde(default)]
203 pub doc: Option<String>,
204 #[serde(default)]
205 pub params: BTreeMap<String, ParamType>,
206 #[serde(default)]
207 pub cardinality: Option<Cardinality>,
208 #[serde(default)]
209 pub epoch: Option<String>,
210 #[serde(default)]
211 pub optional: bool,
212 #[serde(default)]
213 pub gate: Option<Gate>,
214 #[serde(default)]
215 pub deprecated: Option<Deprecated>,
216 #[serde(default, deserialize_with = "annotations")]
217 pub annotations: BTreeMap<String, Value>,
218 #[serde(default, rename = "type")]
220 pub type_: Option<TypeRef>,
221 #[serde(default)]
222 pub attachment: Option<TypeRef>,
223 #[serde(default)]
224 pub encoding: Option<Encoding>,
225 #[serde(default)]
226 pub attachment_encoding: Option<Encoding>,
227 #[serde(default)]
228 pub explicit: Option<bool>,
229 #[serde(default)]
230 pub reliability: Option<Reliability>,
231 #[serde(default)]
232 pub congestion: Option<Congestion>,
233 #[serde(default)]
234 pub priority: Option<Priority>,
235 #[serde(default)]
236 pub express: Option<bool>,
237 #[serde(default)]
238 pub history: Option<History>,
239 #[serde(default)]
242 pub frame: Option<FrameSpec>,
243 #[serde(default)]
244 pub rate: Option<String>,
245 #[serde(default)]
246 pub retention: Option<String>,
247 #[serde(default)]
249 pub request: Option<TypeRef>,
250 #[serde(default)]
251 pub response: Option<TypeRef>,
252 #[serde(default)]
253 pub error: Option<TypeRef>,
254 #[serde(default)]
255 pub idempotent: Option<bool>,
256 #[serde(default)]
257 pub fanout: Option<Fanout>,
258 #[serde(default)]
259 pub serving: Option<Serving>,
260 #[serde(default)]
261 pub replies: Option<Replies>,
262 #[serde(default)]
263 pub summary: Option<TypeRef>,
264 #[serde(default)]
265 pub timeout_ms: Option<u64>,
266}
267
268#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema)]
270#[serde(deny_unknown_fields)]
271pub struct Requirement {
272 pub interface: String,
274 #[serde(default)]
276 pub resources: Option<Vec<String>>,
277 #[serde(default)]
278 pub cardinality: Option<RequireCardinality>,
279 #[serde(default)]
280 pub optional: bool,
281 #[serde(default)]
282 pub doc: Option<String>,
283 #[serde(default, deserialize_with = "annotations")]
284 pub annotations: BTreeMap<String, Value>,
285}
286
287#[derive(
288 Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Deserialize, Serialize, JsonSchema,
289)]
290#[serde(rename_all = "lowercase")]
291pub enum Kind {
292 Stream,
293 State,
294 Event,
295 Operation,
296}
297
298impl Kind {
299 #[must_use]
300 pub fn as_str(self) -> &'static str {
301 match self {
302 Self::Stream => "stream",
303 Self::State => "state",
304 Self::Event => "event",
305 Self::Operation => "operation",
306 }
307 }
308}
309
310#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
311#[serde(rename_all = "lowercase")]
312pub enum ParamType {
313 String,
314 Uint,
315 Path,
316}
317
318#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
319#[serde(rename_all = "lowercase")]
320pub enum Encoding {
321 Json,
322 Cbor,
323}
324
325#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
326#[serde(rename_all = "snake_case")]
327pub enum Reliability {
328 BestEffort,
329 Reliable,
330}
331
332#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
333#[serde(rename_all = "lowercase")]
334pub enum Congestion {
335 Drop,
336 Block,
337}
338
339#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
341#[serde(rename_all = "snake_case")]
342pub enum Priority {
343 RealTime,
344 InteractiveHigh,
345 InteractiveLow,
346 DataHigh,
347 Data,
348 DataLow,
349 Background,
350}
351
352#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
353#[serde(rename_all = "lowercase")]
354pub enum Fanout {
355 Forbidden,
356 Allowed,
357}
358
359#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
360#[serde(rename_all = "lowercase")]
361pub enum Serving {
362 Exclusive,
363 Replicated,
364}
365
366#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
367#[serde(rename_all = "lowercase")]
368pub enum Replies {
369 One,
370 Many,
371}
372
373#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
374#[serde(rename_all = "lowercase")]
375pub enum RequireCardinality {
376 One,
377 Many,
378}
379
380#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
384#[serde(untagged)]
385pub enum TypeRef {
386 Named(String),
387 Raw(RawType),
388}
389
390#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
391#[serde(deny_unknown_fields)]
392pub struct RawType {
393 pub raw: String,
394 #[serde(default)]
395 pub media_param: Option<String>,
396}
397
398#[derive(Debug, Clone, Copy, PartialEq, Eq)]
406pub enum Cardinality {
407 Count(u64),
409 Unbounded,
411}
412
413impl Cardinality {
414 pub const UNBOUNDED: &'static str = "unbounded";
416
417 #[must_use]
419 pub fn value(self) -> u64 {
420 match self {
421 Self::Count(n) => n,
422 Self::Unbounded => crate::budget::NO_CEILING,
423 }
424 }
425}
426
427impl Serialize for Cardinality {
428 fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
429 match self {
430 Self::Count(n) => s.serialize_u64(*n),
431 Self::Unbounded => s.serialize_str(Self::UNBOUNDED),
432 }
433 }
434}
435
436impl<'de> Deserialize<'de> for Cardinality {
437 fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
438 struct V;
439 impl serde::de::Visitor<'_> for V {
440 type Value = Cardinality;
441 fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
442 f.write_str("a number, the most members one instance will hold, or \"unbounded\"")
443 }
444 fn visit_u64<E: serde::de::Error>(self, n: u64) -> Result<Cardinality, E> {
445 Ok(Cardinality::Count(n))
446 }
447 fn visit_i64<E: serde::de::Error>(self, n: i64) -> Result<Cardinality, E> {
448 u64::try_from(n)
449 .map(Cardinality::Count)
450 .map_err(|_| E::invalid_value(serde::de::Unexpected::Signed(n), &self))
451 }
452 fn visit_str<E: serde::de::Error>(self, s: &str) -> Result<Cardinality, E> {
453 if s == Cardinality::UNBOUNDED {
454 Ok(Cardinality::Unbounded)
455 } else {
456 Err(E::invalid_value(serde::de::Unexpected::Str(s), &self))
457 }
458 }
459 }
460 d.deserialize_any(V)
461 }
462}
463
464impl JsonSchema for Cardinality {
465 fn schema_name() -> std::borrow::Cow<'static, str> {
466 "Cardinality".into()
467 }
468
469 fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
472 schemars::json_schema!({
473 "description": "A templated resource's `cardinality`: a number, the most members \
474 one instance will hold, or `\"unbounded\"`, which is 4294967295 \
475 (core §2.2).",
476 "anyOf": [
477 {"type": "integer", "format": "uint64", "minimum": 0},
478 {"type": "string", "enum": ["unbounded"]}
479 ]
480 })
481 }
482}
483
484#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
486#[serde(untagged)]
487pub enum Gate {
488 One(String),
489 All(Vec<String>),
490}
491
492impl Gate {
493 #[must_use]
494 pub fn items(&self) -> Vec<&str> {
495 match self {
496 Self::One(s) => vec![s.as_str()],
497 Self::All(v) => v.iter().map(String::as_str).collect(),
498 }
499 }
500}
501
502#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
504#[serde(untagged)]
505pub enum History {
506 Flag(bool),
507 Params(HistoryParams),
508}
509
510#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
511#[serde(deny_unknown_fields)]
512pub struct HistoryParams {
513 #[schemars(range(max = 4_294_967_295_u32))]
514 pub depth: u32,
515 #[serde(default)]
516 pub miss_detection_ms: Option<u64>,
517}
518
519#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
523#[serde(deny_unknown_fields)]
524pub struct FrameSpec {
525 #[serde(default)]
527 pub records: Option<u64>,
528 #[serde(default)]
531 pub step_ms: Option<u64>,
532 #[serde(default)]
535 pub jitter_ms: Option<u64>,
536 #[serde(default)]
539 pub keyframe_every: Option<u64>,
540 #[serde(default)]
542 pub deadband: BTreeMap<String, DeadbandSpec>,
543}
544
545#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
548#[serde(deny_unknown_fields)]
549pub struct DeadbandSpec {
550 pub delta: String,
552 pub max_records: u64,
554}
555
556#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
557#[serde(deny_unknown_fields)]
558pub struct Deprecated {
559 #[schemars(range(max = 4_294_967_295_u32))]
560 pub since: u32,
561 #[serde(default)]
562 pub replaced_by: Option<String>,
563 #[serde(default)]
564 pub reason: Option<String>,
565}