stratum-node-core 0.1.0-alpha.4

Zero-I/O core types for Stratum pod nodes: did:nostr principals, typed identifiers, a strict NIP-98 signed-request verifier and bootstrap claim bodies
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
//! Wire shapes of applications, installations, grants and jobs: the
//! administrator's application routes and the member's tenant routes.
//!
//! Identifiers are 32 lower-case hex digits drawn by the controller from
//! the operating system's generator; this crate does no I/O, so callers
//! build them with `from_bytes`. States serialise as their lower-case
//! `snake_case` names.
//!
//! Request types deny unknown members and serialise in declaration order,
//! so a client signs exactly the bytes it sends. Every `POST` body carries
//! an `operation_id`, which the node binds to the action, the target, the
//! generation and the body's SHA-256, as Step 3a's member routes do.
//! Response types ignore members they do not name, so a newer node stays
//! readable by an older client.

use std::fmt;
use std::str::FromStr;

use serde::{Deserialize, Deserializer, Serialize, Serializer};

use crate::did::DidNostr;
use crate::encoding;
use crate::grant::OfferedGrant;
use crate::id::{OperationId, ParseIdError, Sha256Digest, UnixTime};
use crate::manifest::{ContainerPath, ImageId, Manifest, ParseNameError, WorkspaceMode};
use crate::members::Enforcement;

/// Defines a 16-byte identifier written as 32 lower-case hex digits.
macro_rules! hex16_id {
    ($(#[$doc:meta])* $name:ident) => {
        $(#[$doc])*
        #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
        pub struct $name([u8; 16]);

        impl $name {
            /// Wraps raw bytes, normally 16 bytes from the operating
            /// system's generator.
            pub const fn from_bytes(bytes: [u8; 16]) -> Self {
                Self(bytes)
            }

            /// Returns the raw bytes.
            pub const fn as_bytes(&self) -> &[u8; 16] {
                &self.0
            }

            /// Returns the 32 lower-case hex digits.
            pub fn to_hex(&self) -> String {
                hex::encode(self.0)
            }
        }

        impl From<[u8; 16]> for $name {
            fn from(bytes: [u8; 16]) -> Self {
                Self(bytes)
            }
        }

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

        impl fmt::Debug for $name {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                write!(f, concat!(stringify!($name), "({})"), self.to_hex())
            }
        }

        impl FromStr for $name {
            type Err = ParseIdError;

            /// Parses exactly 32 lower-case hex digits.
            fn from_str(text: &str) -> Result<Self, Self::Err> {
                encoding::decode_lower_hex::<16>(text)
                    .map(Self)
                    .ok_or(ParseIdError::InvalidHex { expected: 32 })
            }
        }

        impl Serialize for $name {
            fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
                serializer.serialize_str(&self.to_hex())
            }
        }

        impl<'de> Deserialize<'de> for $name {
            fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
                let text = String::deserialize(deserializer)?;
                text.parse().map_err(serde::de::Error::custom)
            }
        }
    };
}

hex16_id!(
    /// The identifier of an approved application.
    ///
    /// # Examples
    ///
    /// ```
    /// use stratum_node_core::ApplicationId;
    ///
    /// # fn main() -> Result<(), stratum_node_core::ParseIdError> {
    /// let id = ApplicationId::from_bytes([0xab; 16]);
    /// assert_eq!(id.to_string(), "ab".repeat(16));
    /// assert_eq!(id.to_string().parse::<ApplicationId>()?, id);
    /// assert!("AB".repeat(16).parse::<ApplicationId>().is_err());
    /// # Ok(())
    /// # }
    /// ```
    ApplicationId
);

hex16_id!(
    /// The identifier of an installation: one member's use of one
    /// application, with its own key. It is a single lower-case segment, so
    /// it fits the tenant route grammar and the report's resource name.
    ///
    /// # Examples
    ///
    /// ```
    /// use stratum_node_core::InstallationId;
    ///
    /// let id = InstallationId::from_bytes([1; 16]);
    /// assert_eq!(id.to_hex(), "01".repeat(16));
    /// ```
    InstallationId
);

hex16_id!(
    /// The identifier of a job: one installation's work for one period.
    ///
    /// # Examples
    ///
    /// ```
    /// use stratum_node_core::JobId;
    ///
    /// assert!("0".repeat(31).parse::<JobId>().is_err());
    /// ```
    JobId
);

/// Defines a fieldless enum with one wire name per variant, and its
/// `ALL`, `as_str`, `Display`, `FromStr` and string serde.
macro_rules! named_enum {
    ($(#[$doc:meta])* $name:ident { $($(#[$vdoc:meta])* $variant:ident => $text:literal,)+ }) => {
        $(#[$doc])*
        #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
        #[non_exhaustive]
        pub enum $name {
            $($(#[$vdoc])* $variant,)+
        }

        impl $name {
            /// Every value, in declaration order.
            pub const ALL: &'static [Self] = &[$(Self::$variant,)+];

            /// Returns the wire name.
            pub fn as_str(self) -> &'static str {
                match self {
                    $(Self::$variant => $text,)+
                }
            }
        }

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

        impl FromStr for $name {
            type Err = ParseNameError;

            /// Parses a wire name, exactly and case-sensitively.
            fn from_str(text: &str) -> Result<Self, Self::Err> {
                Self::ALL
                    .iter()
                    .copied()
                    .find(|value| value.as_str() == text)
                    .ok_or(ParseNameError)
            }
        }

        impl Serialize for $name {
            fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
                serializer.serialize_str(self.as_str())
            }
        }

        impl<'de> Deserialize<'de> for $name {
            fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
                let text = String::deserialize(deserializer)?;
                text.parse().map_err(|_| {
                    serde::de::Error::custom(concat!("not a known ", stringify!($name)))
                })
            }
        }
    };
}

named_enum!(
    /// An application's state. `disabled` is terminal.
    ///
    /// # Examples
    ///
    /// ```
    /// use stratum_node_core::ApplicationState;
    ///
    /// # fn main() -> Result<(), serde_json::Error> {
    /// assert_eq!(serde_json::to_string(&ApplicationState::Approved)?, "\"approved\"");
    /// assert!(ApplicationState::Disabled.is_terminal());
    /// # Ok(())
    /// # }
    /// ```
    ApplicationState {
        /// New installations may be made.
        Approved => "approved",
        /// No new installations; existing ones keep running.
        Withdrawn => "withdrawn",
        /// Emergency stop: every installation's key is disabled for the
        /// reason `application` and every live lease revoked.
        Disabled => "disabled",
    }
);

impl ApplicationState {
    /// Returns `true` for `disabled`.
    pub fn is_terminal(self) -> bool {
        matches!(self, Self::Disabled)
    }
}

named_enum!(
    /// An installation's state. `withdrawn` and `removed` are terminal.
    ///
    /// # Examples
    ///
    /// ```
    /// use stratum_node_core::InstallationState;
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// assert_eq!("pending_consent".parse::<InstallationState>()?, InstallationState::PendingConsent);
    /// assert!(InstallationState::Removed.is_terminal());
    /// # Ok(())
    /// # }
    /// ```
    InstallationState {
        /// Made, with its key; waiting for the member's consent.
        PendingConsent => "pending_consent",
        /// Consented: its key is enabled and jobs run.
        Active => "active",
        /// Withdrawn by the member.
        Withdrawn => "withdrawn",
        /// The member was removed.
        Removed => "removed",
    }
);

impl InstallationState {
    /// Returns `true` for `withdrawn` and `removed`.
    pub fn is_terminal(self) -> bool {
        matches!(self, Self::Withdrawn | Self::Removed)
    }
}

named_enum!(
    /// The node's record of a grant, per installation and container: what
    /// the member's client has told it, signed, at a point in time. It is
    /// not an observation of the pod's ACLs.
    ///
    /// # Examples
    ///
    /// ```
    /// use stratum_node_core::GrantState;
    ///
    /// assert_eq!(GrantState::CleanupReported.as_str(), "cleanup_reported");
    /// ```
    GrantState {
        /// Offered at installation.
        Offered => "offered",
        /// The member's consent named it.
        Consented => "consented",
        /// Withdrawn; the member's client has not yet reported the cleanup.
        Withdrawn => "withdrawn",
        /// The member's client reported removing it and reading the ACL
        /// back.
        CleanupReported => "cleanup_reported",
    }
);

named_enum!(
    /// A job's state.
    ///
    /// # Examples
    ///
    /// ```
    /// use stratum_node_core::JobState;
    ///
    /// assert!(JobState::Succeeded.is_terminal());
    /// assert!(!JobState::Running.is_terminal());
    /// assert_eq!(JobState::ALL.len(), 7);
    /// ```
    JobState {
        /// Waiting for a lease, perhaps until `next_eligible_at`.
        Pending => "pending",
        /// An attempt holds a current lease.
        Running => "running",
        /// The job reported `created` or `existing`.
        Succeeded => "succeeded",
        /// Out of attempts, or a final refusal.
        Failed => "failed",
        /// Its lease was revoked, or it was cancelled while pending.
        Cancelled => "cancelled",
        /// The job reported `conflict`.
        Conflict => "conflict",
        /// A later period ran instead.
        Skipped => "skipped",
    }
);

impl JobState {
    /// Returns `true` for every state but `pending` and `running`.
    pub fn is_terminal(self) -> bool {
        !matches!(self, Self::Pending | Self::Running)
    }
}

named_enum!(
    /// A lease's state. Only `claimed` and `started` are current.
    ///
    /// # Examples
    ///
    /// ```
    /// use stratum_node_core::LeaseState;
    ///
    /// assert!(LeaseState::Claimed.is_current());
    /// assert!(!LeaseState::Ended.is_current());
    /// ```
    LeaseState {
        /// Claimed; the container may not have started.
        Claimed => "claimed",
        /// The container runs with its limits verified and the signing
        /// window open.
        Started => "started",
        /// Ended by a result, or by the container exiting without one.
        Ended => "ended",
        /// Revoked by withdrawal, suspension, application disable or
        /// removal.
        Revoked => "revoked",
        /// Its deadline passed, or a restore expired it.
        Expired => "expired",
    }
);

impl LeaseState {
    /// Returns `true` for `claimed` and `started`.
    pub fn is_current(self) -> bool {
        matches!(self, Self::Claimed | Self::Started)
    }
}

named_enum!(
    /// A reason an application key is disabled. A key is enabled when it
    /// has none and is not destroyed.
    ///
    /// # Examples
    ///
    /// ```
    /// use stratum_node_core::KeyReason;
    ///
    /// # fn main() -> Result<(), serde_json::Error> {
    /// let reasons = vec![KeyReason::Suspension, KeyReason::Restore];
    /// assert_eq!(serde_json::to_string(&reasons)?, r#"["suspension","restore"]"#);
    /// # Ok(())
    /// # }
    /// ```
    KeyReason {
        /// The owner is suspended.
        Suspension => "suspension",
        /// The application was disabled.
        Application => "application",
        /// The installation was withdrawn.
        Withdrawal => "withdrawal",
        /// The keystore was restored; the owner's `resume` removes it.
        Restore => "restore",
    }
);

named_enum!(
    /// The state of an installation's key as the node wants it: `enabled`
    /// when it has no disable reason, else `disabled`, or `destroyed`.
    ///
    /// # Examples
    ///
    /// ```
    /// use stratum_node_core::KeyStatus;
    ///
    /// assert_eq!(KeyStatus::Enabled.to_string(), "enabled");
    /// ```
    KeyStatus {
        /// No disable reason.
        Enabled => "enabled",
        /// At least one disable reason.
        Disabled => "disabled",
        /// Destroyed at the signer, or marked for destruction.
        Destroyed => "destroyed",
    }
);

named_enum!(
    /// Whether the signer is known to refuse the keys an enforcement covers.
    ///
    /// # Examples
    ///
    /// ```
    /// use stratum_node_core::KeysPart;
    ///
    /// assert_eq!(KeysPart::Disabling.as_str(), "disabling");
    /// ```
    KeysPart {
        /// A disable is committed and not yet confirmed at the current key
        /// revision with no window open. An unreachable signer leaves it
        /// here.
        Disabling => "disabling",
        /// Every key is confirmed disabled with no window open.
        Disabled => "disabled",
    }
);

named_enum!(
    /// Whether the work an enforcement covers is known to have stopped.
    ///
    /// # Examples
    ///
    /// ```
    /// use stratum_node_core::WorkPart;
    ///
    /// assert_eq!(WorkPart::Stopped.as_str(), "stopped");
    /// ```
    WorkPart {
        /// A container may still run, or a create's outcome is unknown. An
        /// unreachable runner leaves it here.
        Stopping => "stopping",
        /// Every container is shown stopped and no create of unknown
        /// outcome remains.
        Stopped => "stopped",
    }
);

/// The parts of one enforcement (a suspension, a withdrawal or an
/// application disable): the authorisation at the gate and the proxy, the
/// keys at the signer and the work at the runner. None of it is stored; it
/// is recomputed for each answer.
///
/// # Examples
///
/// ```
/// use stratum_node_core::{Enforcement, EnforcementParts, KeysPart, WorkPart};
///
/// # fn main() -> Result<(), serde_json::Error> {
/// let parts = EnforcementParts {
///     authorisation: Enforcement::Enforced,
///     keys: KeysPart::Disabling,
///     work: WorkPart::Stopped,
/// };
/// assert_eq!(
///     serde_json::to_string(&parts)?,
///     r#"{"authorisation":"enforced","keys":"disabling","work":"stopped"}"#,
/// );
/// assert!(!parts.is_complete());
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct EnforcementParts {
    /// The gate and the proxy: `enforced` once both apply the revision, or
    /// their 310 s fallback has run out.
    pub authorisation: Enforcement,
    /// The signer.
    pub keys: KeysPart,
    /// The runner.
    pub work: WorkPart,
}

impl EnforcementParts {
    /// Returns `true` when every part is done: `enforced`, `disabled`,
    /// `stopped`.
    pub fn is_complete(&self) -> bool {
        self.authorisation == Enforcement::Enforced
            && self.keys == KeysPart::Disabled
            && self.work == WorkPart::Stopped
    }
}

named_enum!(
    /// What a job's last attempt came to: the five results a job reports;
    /// `limits_not_applied` when the runner could not verify the
    /// container's limits and killed it; and `limit_above_ceiling` when the
    /// job was never launched because its application's manifest asks for
    /// a limit above a ceiling lowered since the approval.
    ///
    /// # Examples
    ///
    /// ```
    /// use stratum_node_core::JobOutcome;
    ///
    /// assert_eq!(JobOutcome::InsufficientStorage.as_str(), "insufficient_storage");
    /// assert!(!JobOutcome::LimitsNotApplied.is_reportable());
    /// assert!(!JobOutcome::LimitAboveCeiling.is_reportable());
    /// ```
    JobOutcome {
        /// The job created its result.
        Created => "created",
        /// The period's result already existed and names this installation
        /// and period.
        Existing => "existing",
        /// A resource at the result path does not match.
        Conflict => "conflict",
        /// The pod refused the write with 507.
        InsufficientStorage => "insufficient_storage",
        /// The pod server refused with an empty 403: the grant is missing or
        /// narrower than the manifest.
        NotGranted => "not_granted",
        /// The runner killed the container because its cgroup limits were
        /// missing or different.
        LimitsNotApplied => "limits_not_applied",
        /// The controller failed the job without launching it: its
        /// application's manifest asks for a limit above the node's
        /// current ceiling (the ceiling was lowered after the approval).
        LimitAboveCeiling => "limit_above_ceiling",
    }
);

impl JobOutcome {
    /// Returns `true` for the outcomes a job may report itself, every one
    /// but `limits_not_applied` and `limit_above_ceiling`, which only the
    /// controller records.
    pub fn is_reportable(self) -> bool {
        !matches!(self, Self::LimitsNotApplied | Self::LimitAboveCeiling)
    }
}

named_enum!(
    /// A workspace slot's state (Step 3b-3; 3b-2 never reports a slot).
    ///
    /// # Examples
    ///
    /// ```
    /// use stratum_node_core::WorkspaceSlotState;
    ///
    /// assert_eq!(WorkspaceSlotState::WipePending.as_str(), "wipe_pending");
    /// ```
    WorkspaceSlotState {
        /// Unassigned and empty.
        Free => "free",
        /// Reserved at consent, before the runner wrote its marker.
        Reserved => "reserved",
        /// Assigned to an owner and generation.
        Assigned => "assigned",
        /// The owner's pod data is purged; the slot waits for a wipe.
        WipePending => "wipe_pending",
        /// A marker or emptiness mismatch; the administrator resolves it.
        Quarantined => "quarantined",
    }
);

/// A member's workspace slot as the administrator sees it: its state and
/// usable size, never its contents. Always `null` in Step 3b-2.
///
/// # Examples
///
/// ```
/// use stratum_node_core::{WorkspaceSlotState, WorkspaceView};
///
/// # fn main() -> Result<(), serde_json::Error> {
/// let view = WorkspaceView { slot: "slot-1".to_owned(), state: WorkspaceSlotState::Assigned, usable_bytes: Some(1024) };
/// assert_eq!(serde_json::to_string(&view)?, r#"{"slot":"slot-1","state":"assigned","usable_bytes":1024}"#);
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct WorkspaceView {
    /// The slot's name.
    pub slot: String,
    /// The slot's state.
    pub state: WorkspaceSlotState,
    /// The usable size measured when it was first assigned, in bytes.
    pub usable_bytes: Option<u64>,
}

/// A workspace given at consent: the slot and its usable size (Step 3b-3;
/// always `null` in 3b-2).
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct WorkspaceGrant {
    /// The slot's name.
    pub slot: String,
    /// The usable size, in bytes.
    pub usable_bytes: u64,
}

/// An installation's jobs counted by state.
///
/// # Examples
///
/// ```
/// use stratum_node_core::{JobCounts, JobState};
///
/// let mut counts = JobCounts::default();
/// counts.add(JobState::Succeeded, 2);
/// counts.add(JobState::Pending, 1);
/// assert_eq!(counts.get(JobState::Succeeded), 2);
/// assert_eq!(counts.total(), 3);
/// ```
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct JobCounts {
    /// `pending` jobs.
    pub pending: u64,
    /// `running` jobs.
    pub running: u64,
    /// `succeeded` jobs.
    pub succeeded: u64,
    /// `failed` jobs.
    pub failed: u64,
    /// `cancelled` jobs.
    pub cancelled: u64,
    /// `conflict` jobs.
    pub conflict: u64,
    /// `skipped` jobs.
    pub skipped: u64,
}

impl JobCounts {
    fn slot(&mut self, state: JobState) -> &mut u64 {
        match state {
            JobState::Pending => &mut self.pending,
            JobState::Running => &mut self.running,
            JobState::Succeeded => &mut self.succeeded,
            JobState::Failed => &mut self.failed,
            JobState::Cancelled => &mut self.cancelled,
            JobState::Conflict => &mut self.conflict,
            JobState::Skipped => &mut self.skipped,
        }
    }

    /// Adds `count` jobs in `state`, saturating.
    pub fn add(&mut self, state: JobState, count: u64) {
        let slot = self.slot(state);
        *slot = slot.saturating_add(count);
    }

    /// Returns the count of jobs in `state`.
    pub fn get(&self, state: JobState) -> u64 {
        let mut copy = *self;
        *copy.slot(state)
    }

    /// Returns the count of every job, saturating.
    pub fn total(&self) -> u64 {
        JobState::ALL
            .iter()
            .fold(0u64, |sum, state| sum.saturating_add(self.get(*state)))
    }
}

/// The body of `POST /api/v1/applications`: the manifest to approve.
///
/// The manifest is carried as JSON and validated by the node with
/// [`ValidManifest::from_value`](crate::ValidManifest::from_value), so a
/// refusal names the member and rule that failed (400 `invalid` with
/// `error.field`).
///
/// # Examples
///
/// ```
/// use stratum_node_core::ApproveApplicationRequest;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let body = ApproveApplicationRequest { operation_id: "app-1".parse()?, manifest: serde_json::json!({"name":"x"}) };
/// assert_eq!(serde_json::to_string(&body)?, r#"{"operation_id":"app-1","manifest":{"name":"x"}}"#);
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ApproveApplicationRequest {
    /// The administrator's operation ID.
    pub operation_id: OperationId,
    /// The manifest, as JSON.
    pub manifest: serde_json::Value,
}

/// The answer to `POST /api/v1/applications`.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct ApproveApplicationResponse {
    /// The new application.
    pub application: ApplicationId,
    /// `approved`.
    pub state: ApplicationState,
    /// The image ID the runner reported present.
    pub image_id: ImageId,
}

/// The body of `POST /api/v1/applications/{id}/withdraw`, `…/approve` and
/// `…/disable`.
///
/// # Examples
///
/// ```
/// use stratum_node_core::ApplicationActionRequest;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let body: ApplicationActionRequest = serde_json::from_str(r#"{"operation_id":"d-1"}"#)?;
/// assert_eq!(body.operation_id.as_str(), "d-1");
/// assert!(serde_json::from_str::<ApplicationActionRequest>(r#"{"operation_id":"d-1","x":1}"#).is_err());
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ApplicationActionRequest {
    /// The administrator's operation ID.
    pub operation_id: OperationId,
}

/// The answer to an application transition.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct ApplicationStateResponse {
    /// The application's state after the transition.
    pub state: ApplicationState,
}

/// One application in `GET /api/v1/applications`.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct ApplicationView {
    /// The application.
    pub application: ApplicationId,
    /// Its state.
    pub state: ApplicationState,
    /// The approved manifest.
    pub manifest: Manifest,
    /// The approved image ID (also in the manifest).
    pub image_id: ImageId,
    /// When it was approved.
    pub approved_at: UnixTime,
    /// How many installations it has, in any state.
    pub installations: u64,
}

/// The answer to `GET /api/v1/applications`.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct ApplicationList {
    /// Every application, newest approval first.
    pub applications: Vec<ApplicationView>,
}

/// One application in the member's catalogue.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct CatalogueEntry {
    /// The application.
    pub application: ApplicationId,
    /// Its manifest.
    pub manifest: Manifest,
}

/// The answer to `GET /api/v1/catalogue`: the `approved` applications.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Catalogue {
    /// The approved applications.
    pub applications: Vec<CatalogueEntry>,
}

/// The body of `POST /api/v1/installations`.
///
/// `workspace` absent means `none`; the client always writes it, so the
/// signed bytes say which was chosen.
///
/// # Examples
///
/// ```
/// use stratum_node_core::{ApplicationId, CreateInstallationRequest, WorkspaceMode};
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let app = ApplicationId::from_bytes([7; 16]);
/// let body: CreateInstallationRequest = serde_json::from_str(&format!(
///     r#"{{"operation_id":"i-1","application":"{app}","schedule_secs":3600}}"#
/// ))?;
/// assert_eq!(body.workspace, WorkspaceMode::None);
/// assert!(serde_json::to_string(&body)?.ends_with(r#""schedule_secs":3600,"workspace":"none"}"#));
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CreateInstallationRequest {
    /// The member's operation ID.
    pub operation_id: OperationId,
    /// The application to install.
    pub application: ApplicationId,
    /// 0 (manual only) or 300 to 604 800.
    pub schedule_secs: u64,
    /// The workspace asked for; no more than the manifest allows.
    #[serde(default)]
    pub workspace: WorkspaceMode,
}

/// The answer to `POST /api/v1/installations`.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct CreateInstallationResponse {
    /// The new installation.
    pub installation: InstallationId,
    /// The installation's application key, as `did:nostr:` text.
    pub app_did: DidNostr,
    /// The offered grant: combined Turtle and hash, and each container's.
    pub grant: OfferedGrant,
    /// `pending_consent`.
    pub state: InstallationState,
}

/// The body of `POST /api/v1/installations/{id}/consent`.
///
/// `read_back` must be `true`: the client states that it read every
/// container's ACL back and found the offered authorisation.
///
/// # Examples
///
/// ```
/// use stratum_node_core::{ConsentRequest, Sha256Digest};
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let body = ConsentRequest { operation_id: "c-1".parse()?, grant_sha256: Sha256Digest::of(b"t"), read_back: true };
/// let text = serde_json::to_string(&body)?;
/// assert!(text.starts_with(r#"{"operation_id":"c-1","grant_sha256":""#));
/// assert!(text.ends_with(r#","read_back":true}"#));
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ConsentRequest {
    /// The member's operation ID.
    pub operation_id: OperationId,
    /// The offered grant's combined hash.
    pub grant_sha256: Sha256Digest,
    /// Always `true`.
    pub read_back: bool,
}

/// The answer to `POST /api/v1/installations/{id}/consent`.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct ConsentResponse {
    /// `active`.
    pub state: InstallationState,
    /// The workspace given; always `null` in Step 3b-2.
    pub workspace: Option<WorkspaceGrant>,
}

/// The body of `POST /api/v1/installations/{id}/run`.
///
/// # Examples
///
/// ```
/// use stratum_node_core::RunRequest;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let body = RunRequest { operation_id: "r-1".parse()?, period: 12 };
/// assert_eq!(serde_json::to_string(&body)?, r#"{"operation_id":"r-1","period":12}"#);
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct RunRequest {
    /// The member's operation ID.
    pub operation_id: OperationId,
    /// The period to run.
    pub period: u64,
}

/// The answer to `POST /api/v1/installations/{id}/run`: the period's job,
/// new or existing.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct RunResponse {
    /// The job.
    pub job: JobId,
    /// Its state.
    pub state: JobState,
}

/// The body of `POST /api/v1/installations/{id}/withdraw` and `…/resume`.
///
/// # Examples
///
/// ```
/// use stratum_node_core::InstallationActionRequest;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let body = InstallationActionRequest { operation_id: "w-1".parse()? };
/// assert_eq!(serde_json::to_string(&body)?, r#"{"operation_id":"w-1"}"#);
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct InstallationActionRequest {
    /// The member's operation ID.
    pub operation_id: OperationId,
}

/// The answer to `POST /api/v1/installations/{id}/withdraw`.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct WithdrawResponse {
    /// `withdrawn`.
    pub state: InstallationState,
    /// `enforcing` when the answer is built.
    pub authorisation: Enforcement,
    /// The containers whose grant cleanup the client must still report.
    pub cleanup_pending: Vec<ContainerPath>,
}

/// The body of `POST /api/v1/installations/{id}/cleanup`.
///
/// # Examples
///
/// ```
/// use stratum_node_core::CleanupRequest;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let body = CleanupRequest { operation_id: "x-1".parse()?, containers: vec!["reports/".parse()?], read_back: true };
/// assert_eq!(
///     serde_json::to_string(&body)?,
///     r#"{"operation_id":"x-1","containers":["reports/"],"read_back":true}"#,
/// );
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CleanupRequest {
    /// The member's operation ID.
    pub operation_id: OperationId,
    /// The containers now cleaned.
    pub containers: Vec<ContainerPath>,
    /// Always `true`: each ACL was read back without the authorisation.
    pub read_back: bool,
}

/// The answer to `POST /api/v1/installations/{id}/cleanup`.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct CleanupResponse {
    /// `cleanup_reported` when no container is pending, else `withdrawn`.
    pub grant: GrantState,
    /// The containers still pending.
    pub cleanup_pending: Vec<ContainerPath>,
}

/// The answer to `POST /api/v1/installations/{id}/resume`: the key's
/// state after the `restore` reason is removed.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct ResumeInstallationResponse {
    /// `enabled` when no other reason remains.
    pub keys: KeyStatus,
}

/// One installation as the member (`GET /api/v1/installations`,
/// `…/{id}`) and the administrator (`GET /api/v1/installations`) see it.
/// It never carries a result body.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct InstallationView {
    /// The installation.
    pub installation: InstallationId,
    /// Its application.
    pub application: ApplicationId,
    /// The member who owns it.
    pub owner: DidNostr,
    /// Its state.
    pub state: InstallationState,
    /// The owner's generation it was made in.
    pub generation: u64,
    /// Its schedule: 0, or 300 to 604 800.
    pub schedule_secs: u64,
    /// The workspace it asked for.
    pub workspace: WorkspaceMode,
    /// Its application key, once the signer returned it.
    pub app_did: Option<DidNostr>,
    /// When it was made.
    pub created_at: UnixTime,
    /// When consent made it `active`.
    pub activated_at: Option<UnixTime>,
    /// When it was withdrawn.
    pub withdrawn_at: Option<UnixTime>,
    /// Its key's disable reasons.
    pub key_reasons: Vec<KeyReason>,
    /// The grant's state: `withdrawn` while any container's cleanup is
    /// pending.
    pub grant: GrantState,
    /// The containers whose cleanup is pending.
    pub cleanup_pending: Vec<ContainerPath>,
    /// The enforcement of its withdrawal, or of the application's disable;
    /// `null` when neither applies.
    pub enforcement: Option<EnforcementParts>,
    /// Its jobs counted by state.
    pub jobs: JobCounts,
}

/// The answer to `GET /api/v1/installations`.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct InstallationList {
    /// The installations: the member's own, or every one for the
    /// administrator.
    pub installations: Vec<InstallationView>,
}

/// One job in `GET /api/v1/installations/{id}/jobs`.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct JobView {
    /// The job.
    pub job: JobId,
    /// Its period.
    pub period: u64,
    /// Its state.
    pub state: JobState,
    /// Attempts counted against the limit of three.
    pub attempts: u32,
    /// When it was made.
    pub created_at: UnixTime,
    /// When its next attempt may start, if it waits.
    pub next_eligible_at: Option<UnixTime>,
    /// What its last attempt came to.
    pub outcome: Option<JobOutcome>,
    /// The result resource's pod path.
    pub resource: Option<String>,
    /// The result resource's SHA-256.
    pub sha256: Option<Sha256Digest>,
    /// The result resource's length, in bytes.
    pub length: Option<u64>,
    /// The last attempt's exit code, when it exited without a result.
    pub exit_code: Option<i64>,
}

/// The answer to `GET /api/v1/installations/{id}/jobs`.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct JobList {
    /// The installation.
    pub installation: InstallationId,
    /// Its jobs, latest period first.
    pub jobs: Vec<JobView>,
}