Skip to main content

stratum_node_core/
installations.rs

1//! Wire shapes of applications, installations, grants and jobs: the
2//! administrator's application routes and the member's tenant routes.
3//!
4//! Identifiers are 32 lower-case hex digits drawn by the controller from
5//! the operating system's generator; this crate does no I/O, so callers
6//! build them with `from_bytes`. States serialise as their lower-case
7//! `snake_case` names.
8//!
9//! Request types deny unknown members and serialise in declaration order,
10//! so a client signs exactly the bytes it sends. Every `POST` body carries
11//! an `operation_id`, which the node binds to the action, the target, the
12//! generation and the body's SHA-256, as Step 3a's member routes do.
13//! Response types ignore members they do not name, so a newer node stays
14//! readable by an older client.
15
16use std::fmt;
17use std::str::FromStr;
18
19use serde::{Deserialize, Deserializer, Serialize, Serializer};
20
21use crate::did::DidNostr;
22use crate::encoding;
23use crate::grant::OfferedGrant;
24use crate::id::{OperationId, ParseIdError, Sha256Digest, UnixTime};
25use crate::manifest::{ContainerPath, ImageId, Manifest, ParseNameError, WorkspaceMode};
26use crate::members::Enforcement;
27
28/// Defines a 16-byte identifier written as 32 lower-case hex digits.
29macro_rules! hex16_id {
30    ($(#[$doc:meta])* $name:ident) => {
31        $(#[$doc])*
32        #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
33        pub struct $name([u8; 16]);
34
35        impl $name {
36            /// Wraps raw bytes, normally 16 bytes from the operating
37            /// system's generator.
38            pub const fn from_bytes(bytes: [u8; 16]) -> Self {
39                Self(bytes)
40            }
41
42            /// Returns the raw bytes.
43            pub const fn as_bytes(&self) -> &[u8; 16] {
44                &self.0
45            }
46
47            /// Returns the 32 lower-case hex digits.
48            pub fn to_hex(&self) -> String {
49                hex::encode(self.0)
50            }
51        }
52
53        impl From<[u8; 16]> for $name {
54            fn from(bytes: [u8; 16]) -> Self {
55                Self(bytes)
56            }
57        }
58
59        impl fmt::Display for $name {
60            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
61                f.write_str(&self.to_hex())
62            }
63        }
64
65        impl fmt::Debug for $name {
66            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
67                write!(f, concat!(stringify!($name), "({})"), self.to_hex())
68            }
69        }
70
71        impl FromStr for $name {
72            type Err = ParseIdError;
73
74            /// Parses exactly 32 lower-case hex digits.
75            fn from_str(text: &str) -> Result<Self, Self::Err> {
76                encoding::decode_lower_hex::<16>(text)
77                    .map(Self)
78                    .ok_or(ParseIdError::InvalidHex { expected: 32 })
79            }
80        }
81
82        impl Serialize for $name {
83            fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
84                serializer.serialize_str(&self.to_hex())
85            }
86        }
87
88        impl<'de> Deserialize<'de> for $name {
89            fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
90                let text = String::deserialize(deserializer)?;
91                text.parse().map_err(serde::de::Error::custom)
92            }
93        }
94    };
95}
96
97hex16_id!(
98    /// The identifier of an approved application.
99    ///
100    /// # Examples
101    ///
102    /// ```
103    /// use stratum_node_core::ApplicationId;
104    ///
105    /// # fn main() -> Result<(), stratum_node_core::ParseIdError> {
106    /// let id = ApplicationId::from_bytes([0xab; 16]);
107    /// assert_eq!(id.to_string(), "ab".repeat(16));
108    /// assert_eq!(id.to_string().parse::<ApplicationId>()?, id);
109    /// assert!("AB".repeat(16).parse::<ApplicationId>().is_err());
110    /// # Ok(())
111    /// # }
112    /// ```
113    ApplicationId
114);
115
116hex16_id!(
117    /// The identifier of an installation: one member's use of one
118    /// application, with its own key. It is a single lower-case segment, so
119    /// it fits the tenant route grammar and the report's resource name.
120    ///
121    /// # Examples
122    ///
123    /// ```
124    /// use stratum_node_core::InstallationId;
125    ///
126    /// let id = InstallationId::from_bytes([1; 16]);
127    /// assert_eq!(id.to_hex(), "01".repeat(16));
128    /// ```
129    InstallationId
130);
131
132hex16_id!(
133    /// The identifier of a job: one installation's work for one period.
134    ///
135    /// # Examples
136    ///
137    /// ```
138    /// use stratum_node_core::JobId;
139    ///
140    /// assert!("0".repeat(31).parse::<JobId>().is_err());
141    /// ```
142    JobId
143);
144
145/// Defines a fieldless enum with one wire name per variant, and its
146/// `ALL`, `as_str`, `Display`, `FromStr` and string serde.
147macro_rules! named_enum {
148    ($(#[$doc:meta])* $name:ident { $($(#[$vdoc:meta])* $variant:ident => $text:literal,)+ }) => {
149        $(#[$doc])*
150        #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
151        #[non_exhaustive]
152        pub enum $name {
153            $($(#[$vdoc])* $variant,)+
154        }
155
156        impl $name {
157            /// Every value, in declaration order.
158            pub const ALL: &'static [Self] = &[$(Self::$variant,)+];
159
160            /// Returns the wire name.
161            pub fn as_str(self) -> &'static str {
162                match self {
163                    $(Self::$variant => $text,)+
164                }
165            }
166        }
167
168        impl fmt::Display for $name {
169            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
170                f.write_str(self.as_str())
171            }
172        }
173
174        impl FromStr for $name {
175            type Err = ParseNameError;
176
177            /// Parses a wire name, exactly and case-sensitively.
178            fn from_str(text: &str) -> Result<Self, Self::Err> {
179                Self::ALL
180                    .iter()
181                    .copied()
182                    .find(|value| value.as_str() == text)
183                    .ok_or(ParseNameError)
184            }
185        }
186
187        impl Serialize for $name {
188            fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
189                serializer.serialize_str(self.as_str())
190            }
191        }
192
193        impl<'de> Deserialize<'de> for $name {
194            fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
195                let text = String::deserialize(deserializer)?;
196                text.parse().map_err(|_| {
197                    serde::de::Error::custom(concat!("not a known ", stringify!($name)))
198                })
199            }
200        }
201    };
202}
203
204named_enum!(
205    /// An application's state. `disabled` is terminal.
206    ///
207    /// # Examples
208    ///
209    /// ```
210    /// use stratum_node_core::ApplicationState;
211    ///
212    /// # fn main() -> Result<(), serde_json::Error> {
213    /// assert_eq!(serde_json::to_string(&ApplicationState::Approved)?, "\"approved\"");
214    /// assert!(ApplicationState::Disabled.is_terminal());
215    /// # Ok(())
216    /// # }
217    /// ```
218    ApplicationState {
219        /// New installations may be made.
220        Approved => "approved",
221        /// No new installations; existing ones keep running.
222        Withdrawn => "withdrawn",
223        /// Emergency stop: every installation's key is disabled for the
224        /// reason `application` and every live lease revoked.
225        Disabled => "disabled",
226    }
227);
228
229impl ApplicationState {
230    /// Returns `true` for `disabled`.
231    pub fn is_terminal(self) -> bool {
232        matches!(self, Self::Disabled)
233    }
234}
235
236named_enum!(
237    /// An installation's state. `withdrawn` and `removed` are terminal.
238    ///
239    /// # Examples
240    ///
241    /// ```
242    /// use stratum_node_core::InstallationState;
243    ///
244    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
245    /// assert_eq!("pending_consent".parse::<InstallationState>()?, InstallationState::PendingConsent);
246    /// assert!(InstallationState::Removed.is_terminal());
247    /// # Ok(())
248    /// # }
249    /// ```
250    InstallationState {
251        /// Made, with its key; waiting for the member's consent.
252        PendingConsent => "pending_consent",
253        /// Consented: its key is enabled and jobs run.
254        Active => "active",
255        /// Withdrawn by the member.
256        Withdrawn => "withdrawn",
257        /// The member was removed.
258        Removed => "removed",
259    }
260);
261
262impl InstallationState {
263    /// Returns `true` for `withdrawn` and `removed`.
264    pub fn is_terminal(self) -> bool {
265        matches!(self, Self::Withdrawn | Self::Removed)
266    }
267}
268
269named_enum!(
270    /// The node's record of a grant, per installation and container: what
271    /// the member's client has told it, signed, at a point in time. It is
272    /// not an observation of the pod's ACLs.
273    ///
274    /// # Examples
275    ///
276    /// ```
277    /// use stratum_node_core::GrantState;
278    ///
279    /// assert_eq!(GrantState::CleanupReported.as_str(), "cleanup_reported");
280    /// ```
281    GrantState {
282        /// Offered at installation.
283        Offered => "offered",
284        /// The member's consent named it.
285        Consented => "consented",
286        /// Withdrawn; the member's client has not yet reported the cleanup.
287        Withdrawn => "withdrawn",
288        /// The member's client reported removing it and reading the ACL
289        /// back.
290        CleanupReported => "cleanup_reported",
291    }
292);
293
294named_enum!(
295    /// A job's state.
296    ///
297    /// # Examples
298    ///
299    /// ```
300    /// use stratum_node_core::JobState;
301    ///
302    /// assert!(JobState::Succeeded.is_terminal());
303    /// assert!(!JobState::Running.is_terminal());
304    /// assert_eq!(JobState::ALL.len(), 7);
305    /// ```
306    JobState {
307        /// Waiting for a lease, perhaps until `next_eligible_at`.
308        Pending => "pending",
309        /// An attempt holds a current lease.
310        Running => "running",
311        /// The job reported `created` or `existing`.
312        Succeeded => "succeeded",
313        /// Out of attempts, or a final refusal.
314        Failed => "failed",
315        /// Its lease was revoked, or it was cancelled while pending.
316        Cancelled => "cancelled",
317        /// The job reported `conflict`.
318        Conflict => "conflict",
319        /// A later period ran instead.
320        Skipped => "skipped",
321    }
322);
323
324impl JobState {
325    /// Returns `true` for every state but `pending` and `running`.
326    pub fn is_terminal(self) -> bool {
327        !matches!(self, Self::Pending | Self::Running)
328    }
329}
330
331named_enum!(
332    /// A lease's state. Only `claimed` and `started` are current.
333    ///
334    /// # Examples
335    ///
336    /// ```
337    /// use stratum_node_core::LeaseState;
338    ///
339    /// assert!(LeaseState::Claimed.is_current());
340    /// assert!(!LeaseState::Ended.is_current());
341    /// ```
342    LeaseState {
343        /// Claimed; the container may not have started.
344        Claimed => "claimed",
345        /// The container runs with its limits verified and the signing
346        /// window open.
347        Started => "started",
348        /// Ended by a result, or by the container exiting without one.
349        Ended => "ended",
350        /// Revoked by withdrawal, suspension, application disable or
351        /// removal.
352        Revoked => "revoked",
353        /// Its deadline passed, or a restore expired it.
354        Expired => "expired",
355    }
356);
357
358impl LeaseState {
359    /// Returns `true` for `claimed` and `started`.
360    pub fn is_current(self) -> bool {
361        matches!(self, Self::Claimed | Self::Started)
362    }
363}
364
365named_enum!(
366    /// A reason an application key is disabled. A key is enabled when it
367    /// has none and is not destroyed.
368    ///
369    /// # Examples
370    ///
371    /// ```
372    /// use stratum_node_core::KeyReason;
373    ///
374    /// # fn main() -> Result<(), serde_json::Error> {
375    /// let reasons = vec![KeyReason::Suspension, KeyReason::Restore];
376    /// assert_eq!(serde_json::to_string(&reasons)?, r#"["suspension","restore"]"#);
377    /// # Ok(())
378    /// # }
379    /// ```
380    KeyReason {
381        /// The owner is suspended.
382        Suspension => "suspension",
383        /// The application was disabled.
384        Application => "application",
385        /// The installation was withdrawn.
386        Withdrawal => "withdrawal",
387        /// The keystore was restored; the owner's `resume` removes it.
388        Restore => "restore",
389    }
390);
391
392named_enum!(
393    /// The state of an installation's key as the node wants it: `enabled`
394    /// when it has no disable reason, else `disabled`, or `destroyed`.
395    ///
396    /// # Examples
397    ///
398    /// ```
399    /// use stratum_node_core::KeyStatus;
400    ///
401    /// assert_eq!(KeyStatus::Enabled.to_string(), "enabled");
402    /// ```
403    KeyStatus {
404        /// No disable reason.
405        Enabled => "enabled",
406        /// At least one disable reason.
407        Disabled => "disabled",
408        /// Destroyed at the signer, or marked for destruction.
409        Destroyed => "destroyed",
410    }
411);
412
413named_enum!(
414    /// Whether the signer is known to refuse the keys an enforcement covers.
415    ///
416    /// # Examples
417    ///
418    /// ```
419    /// use stratum_node_core::KeysPart;
420    ///
421    /// assert_eq!(KeysPart::Disabling.as_str(), "disabling");
422    /// ```
423    KeysPart {
424        /// A disable is committed and not yet confirmed at the current key
425        /// revision with no window open. An unreachable signer leaves it
426        /// here.
427        Disabling => "disabling",
428        /// Every key is confirmed disabled with no window open.
429        Disabled => "disabled",
430    }
431);
432
433named_enum!(
434    /// Whether the work an enforcement covers is known to have stopped.
435    ///
436    /// # Examples
437    ///
438    /// ```
439    /// use stratum_node_core::WorkPart;
440    ///
441    /// assert_eq!(WorkPart::Stopped.as_str(), "stopped");
442    /// ```
443    WorkPart {
444        /// A container may still run, or a create's outcome is unknown. An
445        /// unreachable runner leaves it here.
446        Stopping => "stopping",
447        /// Every container is shown stopped and no create of unknown
448        /// outcome remains.
449        Stopped => "stopped",
450    }
451);
452
453/// The parts of one enforcement (a suspension, a withdrawal or an
454/// application disable): the authorisation at the gate and the proxy, the
455/// keys at the signer and the work at the runner. None of it is stored; it
456/// is recomputed for each answer.
457///
458/// # Examples
459///
460/// ```
461/// use stratum_node_core::{Enforcement, EnforcementParts, KeysPart, WorkPart};
462///
463/// # fn main() -> Result<(), serde_json::Error> {
464/// let parts = EnforcementParts {
465///     authorisation: Enforcement::Enforced,
466///     keys: KeysPart::Disabling,
467///     work: WorkPart::Stopped,
468/// };
469/// assert_eq!(
470///     serde_json::to_string(&parts)?,
471///     r#"{"authorisation":"enforced","keys":"disabling","work":"stopped"}"#,
472/// );
473/// assert!(!parts.is_complete());
474/// # Ok(())
475/// # }
476/// ```
477#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
478pub struct EnforcementParts {
479    /// The gate and the proxy: `enforced` once both apply the revision, or
480    /// their 310 s fallback has run out.
481    pub authorisation: Enforcement,
482    /// The signer.
483    pub keys: KeysPart,
484    /// The runner.
485    pub work: WorkPart,
486}
487
488impl EnforcementParts {
489    /// Returns `true` when every part is done: `enforced`, `disabled`,
490    /// `stopped`.
491    pub fn is_complete(&self) -> bool {
492        self.authorisation == Enforcement::Enforced
493            && self.keys == KeysPart::Disabled
494            && self.work == WorkPart::Stopped
495    }
496}
497
498named_enum!(
499    /// What a job's last attempt came to: the five results a job reports;
500    /// `limits_not_applied` when the runner could not verify the
501    /// container's limits and killed it; and `limit_above_ceiling` when the
502    /// job was never launched because its application's manifest asks for
503    /// a limit above a ceiling lowered since the approval.
504    ///
505    /// # Examples
506    ///
507    /// ```
508    /// use stratum_node_core::JobOutcome;
509    ///
510    /// assert_eq!(JobOutcome::InsufficientStorage.as_str(), "insufficient_storage");
511    /// assert!(!JobOutcome::LimitsNotApplied.is_reportable());
512    /// assert!(!JobOutcome::LimitAboveCeiling.is_reportable());
513    /// ```
514    JobOutcome {
515        /// The job created its result.
516        Created => "created",
517        /// The period's result already existed and names this installation
518        /// and period.
519        Existing => "existing",
520        /// A resource at the result path does not match.
521        Conflict => "conflict",
522        /// The pod refused the write with 507.
523        InsufficientStorage => "insufficient_storage",
524        /// The pod server refused with an empty 403: the grant is missing or
525        /// narrower than the manifest.
526        NotGranted => "not_granted",
527        /// The runner killed the container because its cgroup limits were
528        /// missing or different.
529        LimitsNotApplied => "limits_not_applied",
530        /// The controller failed the job without launching it: its
531        /// application's manifest asks for a limit above the node's
532        /// current ceiling (the ceiling was lowered after the approval).
533        LimitAboveCeiling => "limit_above_ceiling",
534    }
535);
536
537impl JobOutcome {
538    /// Returns `true` for the outcomes a job may report itself, every one
539    /// but `limits_not_applied` and `limit_above_ceiling`, which only the
540    /// controller records.
541    pub fn is_reportable(self) -> bool {
542        !matches!(self, Self::LimitsNotApplied | Self::LimitAboveCeiling)
543    }
544}
545
546named_enum!(
547    /// A workspace slot's state (Step 3b-3; 3b-2 never reports a slot).
548    ///
549    /// # Examples
550    ///
551    /// ```
552    /// use stratum_node_core::WorkspaceSlotState;
553    ///
554    /// assert_eq!(WorkspaceSlotState::WipePending.as_str(), "wipe_pending");
555    /// ```
556    WorkspaceSlotState {
557        /// Unassigned and empty.
558        Free => "free",
559        /// Reserved at consent, before the runner wrote its marker.
560        Reserved => "reserved",
561        /// Assigned to an owner and generation.
562        Assigned => "assigned",
563        /// The owner's pod data is purged; the slot waits for a wipe.
564        WipePending => "wipe_pending",
565        /// A marker or emptiness mismatch; the administrator resolves it.
566        Quarantined => "quarantined",
567    }
568);
569
570/// A member's workspace slot as the administrator sees it: its state and
571/// usable size, never its contents. Always `null` in Step 3b-2.
572///
573/// # Examples
574///
575/// ```
576/// use stratum_node_core::{WorkspaceSlotState, WorkspaceView};
577///
578/// # fn main() -> Result<(), serde_json::Error> {
579/// let view = WorkspaceView { slot: "slot-1".to_owned(), state: WorkspaceSlotState::Assigned, usable_bytes: Some(1024) };
580/// assert_eq!(serde_json::to_string(&view)?, r#"{"slot":"slot-1","state":"assigned","usable_bytes":1024}"#);
581/// # Ok(())
582/// # }
583/// ```
584#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
585pub struct WorkspaceView {
586    /// The slot's name.
587    pub slot: String,
588    /// The slot's state.
589    pub state: WorkspaceSlotState,
590    /// The usable size measured when it was first assigned, in bytes.
591    pub usable_bytes: Option<u64>,
592}
593
594/// A workspace given at consent: the slot and its usable size (Step 3b-3;
595/// always `null` in 3b-2).
596#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
597pub struct WorkspaceGrant {
598    /// The slot's name.
599    pub slot: String,
600    /// The usable size, in bytes.
601    pub usable_bytes: u64,
602}
603
604/// An installation's jobs counted by state.
605///
606/// # Examples
607///
608/// ```
609/// use stratum_node_core::{JobCounts, JobState};
610///
611/// let mut counts = JobCounts::default();
612/// counts.add(JobState::Succeeded, 2);
613/// counts.add(JobState::Pending, 1);
614/// assert_eq!(counts.get(JobState::Succeeded), 2);
615/// assert_eq!(counts.total(), 3);
616/// ```
617#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
618pub struct JobCounts {
619    /// `pending` jobs.
620    pub pending: u64,
621    /// `running` jobs.
622    pub running: u64,
623    /// `succeeded` jobs.
624    pub succeeded: u64,
625    /// `failed` jobs.
626    pub failed: u64,
627    /// `cancelled` jobs.
628    pub cancelled: u64,
629    /// `conflict` jobs.
630    pub conflict: u64,
631    /// `skipped` jobs.
632    pub skipped: u64,
633}
634
635impl JobCounts {
636    fn slot(&mut self, state: JobState) -> &mut u64 {
637        match state {
638            JobState::Pending => &mut self.pending,
639            JobState::Running => &mut self.running,
640            JobState::Succeeded => &mut self.succeeded,
641            JobState::Failed => &mut self.failed,
642            JobState::Cancelled => &mut self.cancelled,
643            JobState::Conflict => &mut self.conflict,
644            JobState::Skipped => &mut self.skipped,
645        }
646    }
647
648    /// Adds `count` jobs in `state`, saturating.
649    pub fn add(&mut self, state: JobState, count: u64) {
650        let slot = self.slot(state);
651        *slot = slot.saturating_add(count);
652    }
653
654    /// Returns the count of jobs in `state`.
655    pub fn get(&self, state: JobState) -> u64 {
656        let mut copy = *self;
657        *copy.slot(state)
658    }
659
660    /// Returns the count of every job, saturating.
661    pub fn total(&self) -> u64 {
662        JobState::ALL
663            .iter()
664            .fold(0u64, |sum, state| sum.saturating_add(self.get(*state)))
665    }
666}
667
668/// The body of `POST /api/v1/applications`: the manifest to approve.
669///
670/// The manifest is carried as JSON and validated by the node with
671/// [`ValidManifest::from_value`](crate::ValidManifest::from_value), so a
672/// refusal names the member and rule that failed (400 `invalid` with
673/// `error.field`).
674///
675/// # Examples
676///
677/// ```
678/// use stratum_node_core::ApproveApplicationRequest;
679///
680/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
681/// let body = ApproveApplicationRequest { operation_id: "app-1".parse()?, manifest: serde_json::json!({"name":"x"}) };
682/// assert_eq!(serde_json::to_string(&body)?, r#"{"operation_id":"app-1","manifest":{"name":"x"}}"#);
683/// # Ok(())
684/// # }
685/// ```
686#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
687#[serde(deny_unknown_fields)]
688pub struct ApproveApplicationRequest {
689    /// The administrator's operation ID.
690    pub operation_id: OperationId,
691    /// The manifest, as JSON.
692    pub manifest: serde_json::Value,
693}
694
695/// The answer to `POST /api/v1/applications`.
696#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
697pub struct ApproveApplicationResponse {
698    /// The new application.
699    pub application: ApplicationId,
700    /// `approved`.
701    pub state: ApplicationState,
702    /// The image ID the runner reported present.
703    pub image_id: ImageId,
704}
705
706/// The body of `POST /api/v1/applications/{id}/withdraw`, `…/approve` and
707/// `…/disable`.
708///
709/// # Examples
710///
711/// ```
712/// use stratum_node_core::ApplicationActionRequest;
713///
714/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
715/// let body: ApplicationActionRequest = serde_json::from_str(r#"{"operation_id":"d-1"}"#)?;
716/// assert_eq!(body.operation_id.as_str(), "d-1");
717/// assert!(serde_json::from_str::<ApplicationActionRequest>(r#"{"operation_id":"d-1","x":1}"#).is_err());
718/// # Ok(())
719/// # }
720/// ```
721#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
722#[serde(deny_unknown_fields)]
723pub struct ApplicationActionRequest {
724    /// The administrator's operation ID.
725    pub operation_id: OperationId,
726}
727
728/// The answer to an application transition.
729#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
730pub struct ApplicationStateResponse {
731    /// The application's state after the transition.
732    pub state: ApplicationState,
733}
734
735/// One application in `GET /api/v1/applications`.
736#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
737pub struct ApplicationView {
738    /// The application.
739    pub application: ApplicationId,
740    /// Its state.
741    pub state: ApplicationState,
742    /// The approved manifest.
743    pub manifest: Manifest,
744    /// The approved image ID (also in the manifest).
745    pub image_id: ImageId,
746    /// When it was approved.
747    pub approved_at: UnixTime,
748    /// How many installations it has, in any state.
749    pub installations: u64,
750}
751
752/// The answer to `GET /api/v1/applications`.
753#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
754pub struct ApplicationList {
755    /// Every application, newest approval first.
756    pub applications: Vec<ApplicationView>,
757}
758
759/// One application in the member's catalogue.
760#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
761pub struct CatalogueEntry {
762    /// The application.
763    pub application: ApplicationId,
764    /// Its manifest.
765    pub manifest: Manifest,
766}
767
768/// The answer to `GET /api/v1/catalogue`: the `approved` applications.
769#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
770pub struct Catalogue {
771    /// The approved applications.
772    pub applications: Vec<CatalogueEntry>,
773}
774
775/// The body of `POST /api/v1/installations`.
776///
777/// `workspace` absent means `none`; the client always writes it, so the
778/// signed bytes say which was chosen.
779///
780/// # Examples
781///
782/// ```
783/// use stratum_node_core::{ApplicationId, CreateInstallationRequest, WorkspaceMode};
784///
785/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
786/// let app = ApplicationId::from_bytes([7; 16]);
787/// let body: CreateInstallationRequest = serde_json::from_str(&format!(
788///     r#"{{"operation_id":"i-1","application":"{app}","schedule_secs":3600}}"#
789/// ))?;
790/// assert_eq!(body.workspace, WorkspaceMode::None);
791/// assert!(serde_json::to_string(&body)?.ends_with(r#""schedule_secs":3600,"workspace":"none"}"#));
792/// # Ok(())
793/// # }
794/// ```
795#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
796#[serde(deny_unknown_fields)]
797pub struct CreateInstallationRequest {
798    /// The member's operation ID.
799    pub operation_id: OperationId,
800    /// The application to install.
801    pub application: ApplicationId,
802    /// 0 (manual only) or 300 to 604 800.
803    pub schedule_secs: u64,
804    /// The workspace asked for; no more than the manifest allows.
805    #[serde(default)]
806    pub workspace: WorkspaceMode,
807}
808
809/// The answer to `POST /api/v1/installations`.
810#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
811pub struct CreateInstallationResponse {
812    /// The new installation.
813    pub installation: InstallationId,
814    /// The installation's application key, as `did:nostr:` text.
815    pub app_did: DidNostr,
816    /// The offered grant: combined Turtle and hash, and each container's.
817    pub grant: OfferedGrant,
818    /// `pending_consent`.
819    pub state: InstallationState,
820}
821
822/// The body of `POST /api/v1/installations/{id}/consent`.
823///
824/// `read_back` must be `true`: the client states that it read every
825/// container's ACL back and found the offered authorisation.
826///
827/// # Examples
828///
829/// ```
830/// use stratum_node_core::{ConsentRequest, Sha256Digest};
831///
832/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
833/// let body = ConsentRequest { operation_id: "c-1".parse()?, grant_sha256: Sha256Digest::of(b"t"), read_back: true };
834/// let text = serde_json::to_string(&body)?;
835/// assert!(text.starts_with(r#"{"operation_id":"c-1","grant_sha256":""#));
836/// assert!(text.ends_with(r#","read_back":true}"#));
837/// # Ok(())
838/// # }
839/// ```
840#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
841#[serde(deny_unknown_fields)]
842pub struct ConsentRequest {
843    /// The member's operation ID.
844    pub operation_id: OperationId,
845    /// The offered grant's combined hash.
846    pub grant_sha256: Sha256Digest,
847    /// Always `true`.
848    pub read_back: bool,
849}
850
851/// The answer to `POST /api/v1/installations/{id}/consent`.
852#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
853pub struct ConsentResponse {
854    /// `active`.
855    pub state: InstallationState,
856    /// The workspace given; always `null` in Step 3b-2.
857    pub workspace: Option<WorkspaceGrant>,
858}
859
860/// The body of `POST /api/v1/installations/{id}/run`.
861///
862/// # Examples
863///
864/// ```
865/// use stratum_node_core::RunRequest;
866///
867/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
868/// let body = RunRequest { operation_id: "r-1".parse()?, period: 12 };
869/// assert_eq!(serde_json::to_string(&body)?, r#"{"operation_id":"r-1","period":12}"#);
870/// # Ok(())
871/// # }
872/// ```
873#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
874#[serde(deny_unknown_fields)]
875pub struct RunRequest {
876    /// The member's operation ID.
877    pub operation_id: OperationId,
878    /// The period to run.
879    pub period: u64,
880}
881
882/// The answer to `POST /api/v1/installations/{id}/run`: the period's job,
883/// new or existing.
884#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
885pub struct RunResponse {
886    /// The job.
887    pub job: JobId,
888    /// Its state.
889    pub state: JobState,
890}
891
892/// The body of `POST /api/v1/installations/{id}/withdraw` and `…/resume`.
893///
894/// # Examples
895///
896/// ```
897/// use stratum_node_core::InstallationActionRequest;
898///
899/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
900/// let body = InstallationActionRequest { operation_id: "w-1".parse()? };
901/// assert_eq!(serde_json::to_string(&body)?, r#"{"operation_id":"w-1"}"#);
902/// # Ok(())
903/// # }
904/// ```
905#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
906#[serde(deny_unknown_fields)]
907pub struct InstallationActionRequest {
908    /// The member's operation ID.
909    pub operation_id: OperationId,
910}
911
912/// The answer to `POST /api/v1/installations/{id}/withdraw`.
913#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
914pub struct WithdrawResponse {
915    /// `withdrawn`.
916    pub state: InstallationState,
917    /// `enforcing` when the answer is built.
918    pub authorisation: Enforcement,
919    /// The containers whose grant cleanup the client must still report.
920    pub cleanup_pending: Vec<ContainerPath>,
921}
922
923/// The body of `POST /api/v1/installations/{id}/cleanup`.
924///
925/// # Examples
926///
927/// ```
928/// use stratum_node_core::CleanupRequest;
929///
930/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
931/// let body = CleanupRequest { operation_id: "x-1".parse()?, containers: vec!["reports/".parse()?], read_back: true };
932/// assert_eq!(
933///     serde_json::to_string(&body)?,
934///     r#"{"operation_id":"x-1","containers":["reports/"],"read_back":true}"#,
935/// );
936/// # Ok(())
937/// # }
938/// ```
939#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
940#[serde(deny_unknown_fields)]
941pub struct CleanupRequest {
942    /// The member's operation ID.
943    pub operation_id: OperationId,
944    /// The containers now cleaned.
945    pub containers: Vec<ContainerPath>,
946    /// Always `true`: each ACL was read back without the authorisation.
947    pub read_back: bool,
948}
949
950/// The answer to `POST /api/v1/installations/{id}/cleanup`.
951#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
952pub struct CleanupResponse {
953    /// `cleanup_reported` when no container is pending, else `withdrawn`.
954    pub grant: GrantState,
955    /// The containers still pending.
956    pub cleanup_pending: Vec<ContainerPath>,
957}
958
959/// The answer to `POST /api/v1/installations/{id}/resume`: the key's
960/// state after the `restore` reason is removed.
961#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
962pub struct ResumeInstallationResponse {
963    /// `enabled` when no other reason remains.
964    pub keys: KeyStatus,
965}
966
967/// One installation as the member (`GET /api/v1/installations`,
968/// `…/{id}`) and the administrator (`GET /api/v1/installations`) see it.
969/// It never carries a result body.
970#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
971pub struct InstallationView {
972    /// The installation.
973    pub installation: InstallationId,
974    /// Its application.
975    pub application: ApplicationId,
976    /// The member who owns it.
977    pub owner: DidNostr,
978    /// Its state.
979    pub state: InstallationState,
980    /// The owner's generation it was made in.
981    pub generation: u64,
982    /// Its schedule: 0, or 300 to 604 800.
983    pub schedule_secs: u64,
984    /// The workspace it asked for.
985    pub workspace: WorkspaceMode,
986    /// Its application key, once the signer returned it.
987    pub app_did: Option<DidNostr>,
988    /// When it was made.
989    pub created_at: UnixTime,
990    /// When consent made it `active`.
991    pub activated_at: Option<UnixTime>,
992    /// When it was withdrawn.
993    pub withdrawn_at: Option<UnixTime>,
994    /// Its key's disable reasons.
995    pub key_reasons: Vec<KeyReason>,
996    /// The grant's state: `withdrawn` while any container's cleanup is
997    /// pending.
998    pub grant: GrantState,
999    /// The containers whose cleanup is pending.
1000    pub cleanup_pending: Vec<ContainerPath>,
1001    /// The enforcement of its withdrawal, or of the application's disable;
1002    /// `null` when neither applies.
1003    pub enforcement: Option<EnforcementParts>,
1004    /// Its jobs counted by state.
1005    pub jobs: JobCounts,
1006}
1007
1008/// The answer to `GET /api/v1/installations`.
1009#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
1010pub struct InstallationList {
1011    /// The installations: the member's own, or every one for the
1012    /// administrator.
1013    pub installations: Vec<InstallationView>,
1014}
1015
1016/// One job in `GET /api/v1/installations/{id}/jobs`.
1017#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
1018pub struct JobView {
1019    /// The job.
1020    pub job: JobId,
1021    /// Its period.
1022    pub period: u64,
1023    /// Its state.
1024    pub state: JobState,
1025    /// Attempts counted against the limit of three.
1026    pub attempts: u32,
1027    /// When it was made.
1028    pub created_at: UnixTime,
1029    /// When its next attempt may start, if it waits.
1030    pub next_eligible_at: Option<UnixTime>,
1031    /// What its last attempt came to.
1032    pub outcome: Option<JobOutcome>,
1033    /// The result resource's pod path.
1034    pub resource: Option<String>,
1035    /// The result resource's SHA-256.
1036    pub sha256: Option<Sha256Digest>,
1037    /// The result resource's length, in bytes.
1038    pub length: Option<u64>,
1039    /// The last attempt's exit code, when it exited without a result.
1040    pub exit_code: Option<i64>,
1041}
1042
1043/// The answer to `GET /api/v1/installations/{id}/jobs`.
1044#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
1045pub struct JobList {
1046    /// The installation.
1047    pub installation: InstallationId,
1048    /// Its jobs, latest period first.
1049    pub jobs: Vec<JobView>,
1050}