openadr 0.8.0

OpenADR 3.1 in Rust: VTN server, VEN runtime, typed client and an open conformance suite
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
//! The six addressable objects, their request bodies, and the pieces they share.
//!
//! Every object follows the same shape as the specification's `allOf` composition: VTN-provisioned
//! metadata (`id`, timestamps, `objectType`) plus the client-provided request body, which is a
//! separate type so that a `POST` body cannot even name a field the client is not allowed to set.
//!
//! That split is how two requirements are met by construction rather than by a check.
//! `[Def §Object Metadata]` — the VTN populates `id`, `createdDateTime`, `modificationDateTime` and
//! `objectType` on creation — is the response type's business, and every response type carries all
//! four. `[Def §POST and PUT]` — the VTN ignores those fields on the way in — needs no ignoring:
//! the request types have no such members, so there is nothing for a client to send and nothing for
//! a handler to remember to drop.

use crate::std_shim::{String, Vec};
use core::{cmp::Ordering, fmt, str::FromStr};
use serde::{Deserialize, Serialize};

use super::{
    ids::{ClientId, ClientName, ObjectId, ProgramName, ResourceName, Target, VenName},
    time::{Duration, StartTime, Timestamp},
    values::{PayloadType, ReadingType, Unit, ValuesMap},
};

/// The kinds of object addressable through the API (`objectTypes`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum ObjectType {
    /// A demand-response programme or tariff.
    Program,
    /// A demand-response event.
    Event,
    /// A report submitted by a VEN.
    Report,
    /// A webhook subscription.
    Subscription,
    /// A virtual end node.
    Ven,
    /// A device or system behind a VEN.
    Resource,
}

impl ObjectType {
    /// The wire spelling.
    pub const fn as_str(self) -> &'static str {
        match self {
            ObjectType::Program => "PROGRAM",
            ObjectType::Event => "EVENT",
            ObjectType::Report => "REPORT",
            ObjectType::Subscription => "SUBSCRIPTION",
            ObjectType::Ven => "VEN",
            ObjectType::Resource => "RESOURCE",
        }
    }

    /// The collection path segment, e.g. `programs`.
    pub const fn collection(self) -> &'static str {
        match self {
            ObjectType::Program => "programs",
            ObjectType::Event => "events",
            ObjectType::Report => "reports",
            ObjectType::Subscription => "subscriptions",
            ObjectType::Ven => "vens",
            ObjectType::Resource => "resources",
        }
    }

    /// Every variant, for iteration.
    pub const ALL: [ObjectType; 6] = [
        ObjectType::Program,
        ObjectType::Event,
        ObjectType::Report,
        ObjectType::Subscription,
        ObjectType::Ven,
        ObjectType::Resource,
    ];

    /// Every object type a write to this one may announce, its cascade included.
    ///
    /// Deleting a programme takes its events, their reports, and the subscriptions scoped to it —
    /// and each of those removals is announced, because nothing in OpenADR can say afterwards that
    /// an object went away. So a VTN working out who to tell about a write to *this* type has to
    /// consider subscribers watching any of *these*.
    ///
    /// Always contains `self`, which a test asserts: a type missing from its own list would mean a
    /// write announcing nothing, silently, on the one path where silence is the failure.
    pub const fn announces(self) -> &'static [ObjectType] {
        match self {
            ObjectType::Program => &[
                ObjectType::Program,
                ObjectType::Event,
                ObjectType::Report,
                ObjectType::Subscription,
            ],
            ObjectType::Event => &[ObjectType::Event, ObjectType::Report],
            ObjectType::Ven => &[ObjectType::Ven, ObjectType::Resource],
            ObjectType::Report => &[ObjectType::Report],
            ObjectType::Subscription => &[ObjectType::Subscription],
            ObjectType::Resource => &[ObjectType::Resource],
        }
    }
}

impl fmt::Display for ObjectType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

impl FromStr for ObjectType {
    type Err = UnknownObjectType;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "PROGRAM" => Ok(ObjectType::Program),
            "EVENT" => Ok(ObjectType::Event),
            "REPORT" => Ok(ObjectType::Report),
            "SUBSCRIPTION" => Ok(ObjectType::Subscription),
            "VEN" => Ok(ObjectType::Ven),
            "RESOURCE" => Ok(ObjectType::Resource),
            _ => Err(UnknownObjectType),
        }
    }
}

/// The string was not one of the six object types.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[error("unknown object type")]
pub struct UnknownObjectType;

/// Metadata the VTN provisions on every addressable object.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ObjectMetadata {
    /// VTN-assigned identifier.
    pub id: ObjectId,
    /// When the VTN created the object.
    pub created_date_time: Timestamp,
    /// When the VTN last modified the object.
    pub modification_date_time: Timestamp,
    /// Discriminator.
    pub object_type: ObjectType,
}

// ---------------------------------------------------------------------------
// Interval scaffolding
// ---------------------------------------------------------------------------

/// The temporal aspects of an interval, or the defaults for an event's intervals.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct IntervalPeriod {
    /// Start of the interval, or `0001-01-01` for "now".
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub start: Option<StartTime>,
    /// Length of the interval, or `P9999Y` for "no end".
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub duration: Option<Duration>,
    /// Maximum offset a client may apply to `start`, in either direction.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub randomize_start: Option<Duration>,
}

impl IntervalPeriod {
    /// An interval period with an absolute start and a duration.
    pub fn new(start: StartTime, duration: Duration) -> Self {
        Self {
            start: Some(start),
            duration: Some(duration),
            randomize_start: None,
        }
    }

    /// Apply a maximum start randomization.
    pub fn with_randomize_start(mut self, d: Duration) -> Self {
        self.randomize_start = Some(d);
        self
    }
}

/// A temporal window and the values that apply during it.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Interval {
    /// Client-assigned identifier, used to correlate report intervals with event intervals.
    ///
    /// Not a sequence number: the specification is explicit that it need not ascend.
    pub id: i32,
    /// Overrides the containing object's `intervalPeriod`, if present.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub interval_period: Option<IntervalPeriod>,
    /// The payloads that apply during this interval.
    pub payloads: Vec<ValuesMap>,
}

impl Interval {
    /// An interval carrying payloads and inheriting its timing from its parent.
    pub fn new(id: i32, payloads: Vec<ValuesMap>) -> Self {
        Self {
            id,
            interval_period: None,
            payloads,
        }
    }

    /// Give this interval its own timing.
    pub fn with_period(mut self, period: IntervalPeriod) -> Self {
        self.interval_period = Some(period);
        self
    }
}

// ---------------------------------------------------------------------------
// Descriptors
// ---------------------------------------------------------------------------

/// Context needed to interpret event payload values.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct EventPayloadDescriptor {
    /// Discriminator; always `EVENT_PAYLOAD_DESCRIPTOR`.
    #[serde(default = "event_payload_descriptor_tag")]
    pub object_type: String,
    /// The payload type this descriptor describes.
    pub payload_type: PayloadType,
    /// Unit of measure.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub units: Option<Unit>,
    /// ISO 4217 currency, for price payloads.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub currency: Option<String>,
}

fn event_payload_descriptor_tag() -> String {
    "EVENT_PAYLOAD_DESCRIPTOR".into()
}

impl EventPayloadDescriptor {
    /// A descriptor for a payload type.
    pub fn new(payload_type: PayloadType) -> Self {
        Self {
            object_type: event_payload_descriptor_tag(),
            payload_type,
            units: None,
            currency: None,
        }
    }

    /// Set the unit of measure.
    pub fn with_units(mut self, units: Unit) -> Self {
        self.units = Some(units);
        self
    }

    /// Set the currency.
    pub fn with_currency(mut self, currency: impl Into<String>) -> Self {
        self.currency = Some(currency.into());
        self
    }
}

/// Context needed to interpret report payload values.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ReportPayloadDescriptor {
    /// Discriminator; always `REPORT_PAYLOAD_DESCRIPTOR`.
    #[serde(default = "report_payload_descriptor_tag")]
    pub object_type: String,
    /// The payload type this descriptor describes.
    pub payload_type: PayloadType,
    /// How the value was obtained, e.g. [`ReadingType::DirectRead`].
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reading_type: Option<ReadingType>,
    /// Unit of measure.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub units: Option<Unit>,
    /// Quantified accuracy of the values.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub accuracy: Option<f32>,
    /// Confidence in the values, 0..=100.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub confidence: Option<u8>,
}

fn report_payload_descriptor_tag() -> String {
    "REPORT_PAYLOAD_DESCRIPTOR".into()
}

impl ReportPayloadDescriptor {
    /// A descriptor for a payload type.
    pub fn new(payload_type: PayloadType) -> Self {
        Self {
            object_type: report_payload_descriptor_tag(),
            payload_type,
            reading_type: None,
            units: None,
            accuracy: None,
            confidence: None,
        }
    }
}

/// A payload descriptor of either flavour, discriminated by `objectType`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "objectType")]
pub enum PayloadDescriptor {
    /// Describes event payloads.
    #[serde(rename = "EVENT_PAYLOAD_DESCRIPTOR")]
    Event(EventPayloadDescriptor),
    /// Describes report payloads.
    #[serde(rename = "REPORT_PAYLOAD_DESCRIPTOR")]
    Report(ReportPayloadDescriptor),
}

/// Which intervals a report should carry relative to the event's intervals.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum ReportIntervals {
    /// Mirror the event's intervals exactly.
    #[default]
    Intervals,
    /// The VEN may subdivide event intervals.
    SubIntervals,
    /// The VEN chooses its own intervals.
    OpenIntervals,
}

/// A request from the VTN for a VEN to produce reports.
///
/// The `-1` sentinels are the specification's, kept verbatim so that a round trip is lossless;
/// [`crate::core::ReportSchedule`] interprets them.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ReportDescriptor {
    /// The payload type being requested.
    pub payload_type: PayloadType,
    /// How the value should be obtained.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reading_type: Option<ReadingType>,
    /// Unit of measure.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub units: Option<Unit>,
    /// Restrict the report to matching resources.
    #[serde(
        default,
        skip_serializing_if = "Vec::is_empty",
        deserialize_with = "super::null_as_default"
    )]
    pub targets: Vec<Target>,
    /// Aggregate all targeted resources into one series instead of reporting each.
    #[serde(default)]
    pub aggregate: bool,
    /// Interval at which to generate a report; `-1` means "at the end of the last interval".
    #[serde(default = "minus_one")]
    pub start_interval: i32,
    /// Number of intervals per report; `-1` means "all".
    #[serde(default = "minus_one")]
    pub num_intervals: i32,
    /// `true` reports intervals preceding `startInterval`, `false` those following (a forecast).
    #[serde(default = "bool_true")]
    pub historical: bool,
    /// Intervals between reports; `-1` means "same as numIntervals", `0` means ad hoc.
    #[serde(default = "minus_one")]
    pub frequency: i32,
    /// How many reports to produce; `-1` repeats indefinitely.
    #[serde(default = "one")]
    pub repeat: i32,
    /// Whether the VEN may subdivide or replace the event's intervals.
    #[serde(default)]
    pub report_intervals: ReportIntervals,
}

const fn minus_one() -> i32 {
    -1
}
const fn one() -> i32 {
    1
}
const fn bool_true() -> bool {
    true
}

impl ReportDescriptor {
    /// A descriptor with every schema default in place.
    pub fn new(payload_type: PayloadType) -> Self {
        Self {
            payload_type,
            reading_type: None,
            units: None,
            targets: Vec::new(),
            aggregate: false,
            start_interval: -1,
            num_intervals: -1,
            historical: true,
            frequency: -1,
            repeat: 1,
            report_intervals: ReportIntervals::default(),
        }
    }

    /// Whether the VEN decides when to report (`frequency == 0`).
    pub fn is_ad_hoc(&self) -> bool {
        self.frequency == 0
    }

    /// Whether reporting repeats without end (`repeat == -1`).
    pub fn repeats_forever(&self) -> bool {
        self.repeat < 0
    }
}

// ---------------------------------------------------------------------------
// Program
// ---------------------------------------------------------------------------

/// A link to a human- or machine-readable description of a programme.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ProgramDescription {
    /// The URL.
    #[serde(rename = "URL")]
    pub url: String,
}

/// Client-provided programme description.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ProgramRequest {
    /// Short name, unique to the VTN.
    pub program_name: ProgramName,
    /// The temporal span of the programme, which may be years long.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub interval_period: Option<IntervalPeriod>,
    /// Links to descriptions.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub program_descriptions: Option<Vec<ProgramDescription>>,
    /// Descriptors giving payloads their context.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub payload_descriptors: Option<Vec<PayloadDescriptor>>,
    /// Programme attributes, e.g. `RETAILER_NAME` (3.1 replaced the flat fields with these).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub attributes: Option<Vec<ValuesMap>>,
    /// Targets that gate which VENs may read this programme.
    #[serde(
        default,
        skip_serializing_if = "Vec::is_empty",
        deserialize_with = "super::null_as_default"
    )]
    pub targets: Vec<Target>,
}

impl ProgramRequest {
    /// A programme with only its required field set.
    pub fn new(program_name: ProgramName) -> Self {
        Self {
            program_name,
            interval_period: None,
            program_descriptions: None,
            payload_descriptors: None,
            attributes: None,
            targets: Vec::new(),
        }
    }

    /// Set the targets.
    pub fn with_targets(mut self, targets: Vec<Target>) -> Self {
        self.targets = targets;
        self
    }
}

/// Server-provided programme.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Program {
    /// VTN-assigned identifier.
    pub id: ObjectId,
    /// Creation time.
    pub created_date_time: Timestamp,
    /// Last modification time.
    pub modification_date_time: Timestamp,
    /// Discriminator; always [`ObjectType::Program`].
    #[serde(default = "program_type")]
    pub object_type: ObjectType,
    /// The client-provided content.
    #[serde(flatten)]
    pub content: ProgramRequest,
}

fn program_type() -> ObjectType {
    ObjectType::Program
}

// ---------------------------------------------------------------------------
// Event
// ---------------------------------------------------------------------------

/// Relative priority of an event; a lower number is a higher priority.
///
/// `None` means unprioritised, which sorts *after* every explicit priority so that an event with a
/// stated priority always wins on a timeline.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(transparent)]
pub struct Priority(pub Option<u32>);

impl Priority {
    /// The highest priority the schema allows.
    pub const MAX: Priority = Priority(Some(0));
    /// No stated priority.
    pub const UNSPECIFIED: Priority = Priority(None);

    /// A stated priority.
    pub const fn new(value: u32) -> Self {
        Priority(Some(value))
    }

    /// The numeric value, if stated.
    pub const fn value(self) -> Option<u32> {
        self.0
    }
}

impl Ord for Priority {
    fn cmp(&self, other: &Self) -> Ordering {
        // Ordering is "most important first": Some(0) < Some(1) < None.
        match (self.0, other.0) {
            (Some(a), Some(b)) => a.cmp(&b),
            (Some(_), None) => Ordering::Less,
            (None, Some(_)) => Ordering::Greater,
            (None, None) => Ordering::Equal,
        }
    }
}

impl PartialOrd for Priority {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

/// Client-provided event.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct EventRequest {
    /// The programme this event belongs to.
    #[serde(rename = "programID")]
    pub program_id: ObjectId,
    /// Free-form name for debugging and user interfaces.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub event_name: Option<String>,
    /// Overall event duration; may extend or truncate the intervals (User Guide §7.3).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub duration: Option<Duration>,
    /// Relative priority.
    #[serde(default, skip_serializing_if = "Priority::is_unspecified")]
    pub priority: Priority,
    /// Targets that gate which VENs may read this event.
    #[serde(
        default,
        skip_serializing_if = "Vec::is_empty",
        deserialize_with = "super::null_as_default"
    )]
    pub targets: Vec<Target>,
    /// Reports requested from VENs.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub report_descriptors: Option<Vec<ReportDescriptor>>,
    /// Descriptors giving payloads their context.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub payload_descriptors: Option<Vec<EventPayloadDescriptor>>,
    /// Default timing for the intervals below.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub interval_period: Option<IntervalPeriod>,
    /// The intervals. Absent for a "report-only" event.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub intervals: Option<Vec<Interval>>,
}

impl Priority {
    fn is_unspecified(&self) -> bool {
        self.0.is_none()
    }
}

impl EventRequest {
    /// An event with only its required field set.
    pub fn new(program_id: ObjectId) -> Self {
        Self {
            program_id,
            event_name: None,
            duration: None,
            priority: Priority::UNSPECIFIED,
            targets: Vec::new(),
            report_descriptors: None,
            payload_descriptors: None,
            interval_period: None,
            intervals: None,
        }
    }

    /// Set the intervals.
    pub fn with_intervals(mut self, intervals: Vec<Interval>) -> Self {
        self.intervals = Some(intervals);
        self
    }

    /// Set the default interval period.
    pub fn with_interval_period(mut self, period: IntervalPeriod) -> Self {
        self.interval_period = Some(period);
        self
    }

    /// Set the targets.
    pub fn with_targets(mut self, targets: Vec<Target>) -> Self {
        self.targets = targets;
        self
    }

    /// Set the priority.
    pub fn with_priority(mut self, priority: Priority) -> Self {
        self.priority = priority;
        self
    }
}

/// Server-provided event.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Event {
    /// VTN-assigned identifier.
    pub id: ObjectId,
    /// Creation time.
    pub created_date_time: Timestamp,
    /// Last modification time.
    pub modification_date_time: Timestamp,
    /// Discriminator; always [`ObjectType::Event`].
    #[serde(default = "event_type")]
    pub object_type: ObjectType,
    /// The client-provided content.
    #[serde(flatten)]
    pub content: EventRequest,
}

fn event_type() -> ObjectType {
    ObjectType::Event
}

// ---------------------------------------------------------------------------
// Report
// ---------------------------------------------------------------------------

/// Report data for one resource.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ReportResource {
    /// The resource, or [`ResourceName::AGGREGATED`] for an aggregate series.
    pub resource_name: ResourceName,
    /// Default timing for the intervals below.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub interval_period: Option<IntervalPeriod>,
    /// The reported intervals.
    pub intervals: Vec<Interval>,
}

/// Client-provided report.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ReportRequest {
    /// The event this report answers.
    #[serde(rename = "eventID")]
    pub event_id: ObjectId,
    /// Name of the reporting client.
    pub client_name: ClientName,
    /// Free-form name for debugging and user interfaces.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub report_name: Option<String>,
    /// Descriptors giving payloads their context.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub payload_descriptors: Option<Vec<ReportPayloadDescriptor>>,
    /// Per-resource data.
    pub resources: Vec<ReportResource>,
}

impl ReportRequest {
    /// A report with its required fields set.
    pub fn new(
        event_id: ObjectId,
        client_name: ClientName,
        resources: Vec<ReportResource>,
    ) -> Self {
        Self {
            event_id,
            client_name,
            report_name: None,
            payload_descriptors: None,
            resources,
        }
    }
}

/// Server-provided report.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Report {
    /// VTN-assigned identifier.
    pub id: ObjectId,
    /// Creation time.
    pub created_date_time: Timestamp,
    /// Last modification time.
    pub modification_date_time: Timestamp,
    /// Discriminator; always [`ObjectType::Report`].
    #[serde(default = "report_type")]
    pub object_type: ObjectType,
    /// Identity of the client that created the report; stamped by the VTN.
    #[serde(rename = "clientID", default, skip_serializing_if = "Option::is_none")]
    pub client_id: Option<ClientId>,
    /// The client-provided content.
    #[serde(flatten)]
    pub content: ReportRequest,
}

fn report_type() -> ObjectType {
    ObjectType::Report
}

// ---------------------------------------------------------------------------
// Subscription
// ---------------------------------------------------------------------------

/// An operation on an object that can trigger a notification.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum Operation {
    /// The object was read.
    ///
    /// Only webhooks can carry this; the messaging-protocol bindings deliberately omit it.
    Read,
    /// The object was created.
    Create,
    /// The object was updated.
    Update,
    /// The object was deleted.
    Delete,
}

impl Operation {
    /// The lowercase spelling used in MQTT topic paths.
    pub const fn topic_segment(self) -> &'static str {
        match self {
            Operation::Read => "read",
            Operation::Create => "create",
            Operation::Update => "update",
            Operation::Delete => "delete",
        }
    }
}

impl fmt::Display for Operation {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Operation::Read => "READ",
            Operation::Create => "CREATE",
            Operation::Update => "UPDATE",
            Operation::Delete => "DELETE",
        })
    }
}

/// One `(objects, operations) -> callback` rule of a subscription.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ObjectOperation {
    /// Object types to watch.
    pub objects: Vec<ObjectType>,
    /// Operations to watch.
    pub operations: Vec<Operation>,
    /// Where to POST the notification. Required, and required to be HTTPS.
    pub callback_url: String,
    /// Token the VTN presents to the callback so the receiver can authenticate it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub bearer_token: Option<String>,
}

impl ObjectOperation {
    /// Whether this rule matches an operation on an object type.
    pub fn matches(&self, object: ObjectType, operation: Operation) -> bool {
        self.objects.contains(&object) && self.operations.contains(&operation)
    }
}

/// Client-provided subscription.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SubscriptionRequest {
    /// Name of the subscribing client.
    pub client_name: ClientName,
    /// Restrict notifications to one programme.
    #[serde(rename = "programID", default, skip_serializing_if = "Option::is_none")]
    pub program_id: Option<ObjectId>,
    /// The rules.
    pub object_operations: Vec<ObjectOperation>,
    /// Restrict notifications to objects carrying these targets.
    #[serde(
        default,
        skip_serializing_if = "Vec::is_empty",
        deserialize_with = "super::null_as_default"
    )]
    pub targets: Vec<Target>,
}

/// Server-provided subscription.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Subscription {
    /// VTN-assigned identifier.
    pub id: ObjectId,
    /// Creation time.
    pub created_date_time: Timestamp,
    /// Last modification time.
    pub modification_date_time: Timestamp,
    /// Discriminator; always [`ObjectType::Subscription`].
    #[serde(default = "subscription_type")]
    pub object_type: ObjectType,
    /// Identity of the client that created the subscription; stamped by the VTN.
    #[serde(rename = "clientID")]
    pub client_id: ClientId,
    /// The client-provided content.
    #[serde(flatten)]
    pub content: SubscriptionRequest,
}

fn subscription_type() -> ObjectType {
    ObjectType::Subscription
}

// ---------------------------------------------------------------------------
// VEN and resource
// ---------------------------------------------------------------------------

/// A VEN as described by business logic, which may assign identity and targets.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BlVenRequest {
    /// The client this VEN object belongs to.
    #[serde(rename = "clientID")]
    pub client_id: ClientId,
    /// Name, unique within the VTN.
    pub ven_name: VenName,
    /// Targets granted to this VEN. Only business logic may write these.
    #[serde(
        default,
        skip_serializing_if = "Vec::is_empty",
        deserialize_with = "super::null_as_default"
    )]
    pub targets: Vec<Target>,
    /// Attributes describing the VEN.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub attributes: Option<Vec<ValuesMap>>,
}

/// A VEN as described by itself: no identity, no targets.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct VenVenRequest {
    /// Name, unique within the VTN.
    pub ven_name: VenName,
    /// Attributes describing the VEN.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub attributes: Option<Vec<ValuesMap>>,
}

/// A VEN request body, discriminated by `objectType`.
///
/// The discriminator is what stops a VEN from granting itself targets: `VEN_VEN_REQUEST` has no
/// `targets` member at all, so the privilege is unreachable rather than merely unauthorised.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "objectType")]
pub enum VenRequest {
    /// Written by business logic.
    #[serde(rename = "BL_VEN_REQUEST")]
    Bl(BlVenRequest),
    /// Written by the VEN itself.
    #[serde(rename = "VEN_VEN_REQUEST")]
    Ven(VenVenRequest),
}

impl VenRequest {
    /// The VEN name, whichever flavour this is.
    pub fn ven_name(&self) -> &VenName {
        match self {
            VenRequest::Bl(r) => &r.ven_name,
            VenRequest::Ven(r) => &r.ven_name,
        }
    }

    /// The attributes, whichever flavour this is.
    pub fn attributes(&self) -> Option<&Vec<ValuesMap>> {
        match self {
            VenRequest::Bl(r) => r.attributes.as_ref(),
            VenRequest::Ven(r) => r.attributes.as_ref(),
        }
    }
}

/// Server-provided VEN.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Ven {
    /// VTN-assigned identifier.
    pub id: ObjectId,
    /// Creation time.
    pub created_date_time: Timestamp,
    /// Last modification time.
    pub modification_date_time: Timestamp,
    /// Discriminator.
    ///
    /// The specification composes `ven` from `objectMetadata` + `BlVenRequest`, whose `objectType`
    /// enumerations contradict each other (`VEN` vs `BL_VEN_REQUEST`). Every implementation in the
    /// field emits `VEN`, which is also what the notification discriminator requires, so that is
    /// what we emit.
    #[serde(default = "ven_type")]
    pub object_type: ObjectType,
    /// The client this VEN belongs to.
    #[serde(rename = "clientID")]
    pub client_id: ClientId,
    /// Name, unique within the VTN.
    pub ven_name: VenName,
    /// Targets granted to this VEN.
    #[serde(
        default,
        skip_serializing_if = "Vec::is_empty",
        deserialize_with = "super::null_as_default"
    )]
    pub targets: Vec<Target>,
    /// Attributes describing the VEN.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub attributes: Option<Vec<ValuesMap>>,
}

fn ven_type() -> ObjectType {
    ObjectType::Ven
}

/// A resource as described by business logic.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BlResourceRequest {
    /// Name, unique within its VEN.
    pub resource_name: ResourceName,
    /// The VEN this resource belongs to.
    #[serde(rename = "venID")]
    pub ven_id: ObjectId,
    /// The client that owns it.
    ///
    /// Required in 3.1.0 and removed in 3.1.1, because `venID` already determines it. Optional here
    /// so that a 3.1.0 peer's body parses and a 3.1.0 peer still receives the field it expects; the
    /// VTN derives ownership from `venID` either way.
    #[serde(rename = "clientID", default, skip_serializing_if = "Option::is_none")]
    pub client_id: Option<ClientId>,
    /// Targets granted to this resource. Only business logic may write these.
    #[serde(
        default,
        skip_serializing_if = "Vec::is_empty",
        deserialize_with = "super::null_as_default"
    )]
    pub targets: Vec<Target>,
    /// Attributes describing the resource.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub attributes: Option<Vec<ValuesMap>>,
}

/// A resource as described by its VEN: no targets, and no VEN it does not already belong to.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct VenResourceRequest {
    /// Name, unique within its VEN.
    pub resource_name: ResourceName,
    /// The VEN this resource belongs to.
    ///
    /// Required in 3.1.0 and removed in 3.1.1: a VEN's own resources belong to the VEN the token
    /// identifies, so the field could only ever restate it or contradict it. Optional here — a
    /// 3.1.0 peer may send it, and one that names a *different* VEN is refused rather than quietly
    /// redirected.
    #[serde(rename = "venID", default, skip_serializing_if = "Option::is_none")]
    pub ven_id: Option<ObjectId>,
    /// Attributes describing the resource.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub attributes: Option<Vec<ValuesMap>>,
}

/// A resource request body, discriminated by `objectType`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "objectType")]
pub enum ResourceRequest {
    /// Written by business logic.
    #[serde(rename = "BL_RESOURCE_REQUEST")]
    Bl(BlResourceRequest),
    /// Written by the owning VEN.
    #[serde(rename = "VEN_RESOURCE_REQUEST")]
    Ven(VenResourceRequest),
}

impl ResourceRequest {
    /// The resource name, whichever flavour this is.
    pub fn resource_name(&self) -> &ResourceName {
        match self {
            ResourceRequest::Bl(r) => &r.resource_name,
            ResourceRequest::Ven(r) => &r.resource_name,
        }
    }

    /// The attributes, whichever flavour this is.
    pub fn attributes(&self) -> Option<&Vec<ValuesMap>> {
        match self {
            ResourceRequest::Bl(r) => r.attributes.as_ref(),
            ResourceRequest::Ven(r) => r.attributes.as_ref(),
        }
    }
}

/// Server-provided resource.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Resource {
    /// VTN-assigned identifier.
    pub id: ObjectId,
    /// Creation time.
    pub created_date_time: Timestamp,
    /// Last modification time.
    pub modification_date_time: Timestamp,
    /// Discriminator; always [`ObjectType::Resource`] (see [`Ven::object_type`]).
    #[serde(default = "resource_type")]
    pub object_type: ObjectType,
    /// Name, unique within its VEN.
    pub resource_name: ResourceName,
    /// The VEN this resource belongs to.
    #[serde(rename = "venID")]
    pub ven_id: ObjectId,
    /// Targets granted to this resource.
    #[serde(
        default,
        skip_serializing_if = "Vec::is_empty",
        deserialize_with = "super::null_as_default"
    )]
    pub targets: Vec<Target>,
    /// Attributes describing the resource.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub attributes: Option<Vec<ValuesMap>>,
}

fn resource_type() -> ObjectType {
    ObjectType::Resource
}

#[cfg(test)]
mod tests {

    use super::*;
    use crate::std_shim::vec;

    #[test]
    fn every_object_type_announces_itself() {
        // A type missing from its own list would be a write that queues nothing, on the one path
        // where nothing is exactly what the failure looks like.
        for t in ObjectType::ALL {
            assert!(t.announces().contains(&t), "{t} does not announce itself");
        }
    }

    #[test]
    fn a_cascade_is_announced_by_the_type_that_causes_it() {
        // These mirror the foreign keys the storage layer declares. If a cascade is added there and
        // not here, the subscribers watching the cascaded type are silently left out of the sweep.
        assert!(ObjectType::Program.announces().contains(&ObjectType::Event));
        assert!(
            ObjectType::Program
                .announces()
                .contains(&ObjectType::Report)
        );
        assert!(
            ObjectType::Program
                .announces()
                .contains(&ObjectType::Subscription)
        );
        assert!(ObjectType::Event.announces().contains(&ObjectType::Report));
        assert!(ObjectType::Ven.announces().contains(&ObjectType::Resource));
    }

    #[test]
    fn priority_orders_most_important_first() {
        let mut ps = vec![Priority::UNSPECIFIED, Priority::new(10), Priority::new(0)];
        ps.sort();
        assert_eq!(
            ps,
            vec![Priority::new(0), Priority::new(10), Priority::UNSPECIFIED]
        );
    }

    #[test]
    fn ven_request_discriminator_gates_target_assignment() {
        let ven_written =
            r#"{"objectType":"VEN_VEN_REQUEST","venName":"ven-1","targets":["gold"]}"#;
        let parsed: VenRequest = serde_json::from_str(ven_written).unwrap();
        // `targets` simply does not exist on the VEN-written variant, so it is dropped.
        match parsed {
            VenRequest::Ven(v) => assert_eq!(v.ven_name.as_str(), "ven-1"),
            VenRequest::Bl(_) => panic!("wrong variant"),
        }

        let bl_written = r#"{"objectType":"BL_VEN_REQUEST","clientID":"c1","venName":"ven-1","targets":["gold"]}"#;
        match serde_json::from_str::<VenRequest>(bl_written).unwrap() {
            VenRequest::Bl(v) => assert_eq!(v.targets.len(), 1),
            VenRequest::Ven(_) => panic!("wrong variant"),
        }
    }

    #[test]
    fn missing_discriminator_is_an_error() {
        assert!(serde_json::from_str::<VenRequest>(r#"{"venName":"ven-1"}"#).is_err());
    }

    #[test]
    fn null_targets_deserialize_as_empty() {
        let e: EventRequest = serde_json::from_str(r#"{"programID":"p1","targets":null}"#).unwrap();
        assert!(e.targets.is_empty());
        // And are omitted on the way out rather than emitted as null.
        assert_eq!(serde_json::to_string(&e).unwrap(), r#"{"programID":"p1"}"#);
    }

    #[test]
    fn report_descriptor_defaults_match_the_schema() {
        let rd: ReportDescriptor = serde_json::from_str(r#"{"payloadType":"USAGE"}"#).unwrap();
        assert_eq!(rd.start_interval, -1);
        assert_eq!(rd.num_intervals, -1);
        assert!(rd.historical);
        assert_eq!(rd.frequency, -1);
        assert_eq!(rd.repeat, 1);
        assert!(!rd.aggregate);
        assert_eq!(rd.report_intervals, ReportIntervals::Intervals);
    }

    #[test]
    fn event_round_trips_with_metadata_flattened() {
        let json = r#"{
            "id":"e1",
            "createdDateTime":"2026-02-10T16:00:00Z",
            "modificationDateTime":"2026-02-10T16:00:00Z",
            "objectType":"EVENT",
            "programID":"p1",
            "eventName":"test",
            "intervals":[{"id":0,"payloads":[{"type":"PRICE","values":[0.17]}]}]
        }"#;
        let e: Event = serde_json::from_str(json).unwrap();
        assert_eq!(e.object_type, ObjectType::Event);
        assert_eq!(e.content.program_id.as_str(), "p1");
        let back: Event = serde_json::from_str(&serde_json::to_string(&e).unwrap()).unwrap();
        assert_eq!(e, back);
    }
}