stratum_node_core/members.rs
1//! Wire shapes of the administrator's member routes added in Step 3a:
2//! suspend, resume, archive, remove and the single-member view.
3//!
4//! Request types deny unknown members, as the controller's other request
5//! bodies do, and serialise their members in declaration order, so a client
6//! signs exactly the bytes it sends. Response types ignore members they do
7//! not name, so a newer node stays readable by an older client.
8
9use std::fmt;
10use std::str::FromStr;
11
12use serde::{Deserialize, Deserializer, Serialize, Serializer};
13
14use crate::admission::MemberState;
15use crate::did::DidNostr;
16use crate::id::{EventId, OperationId, UnixTime};
17use crate::installations::{KeysPart, WorkPart, WorkspaceView};
18
19/// Whether the gate is known to enforce one suspension.
20///
21/// Enforcement belongs to one suspension, named by key, generation and
22/// suspension number. It is `enforcing` until the gate is known to hold a
23/// directory revision that lists the suspension, or until the gate's lease
24/// must have run out; then it is `enforced`. It is never stored.
25///
26/// The text form is `"enforcing"` or `"enforced"`.
27///
28/// # Examples
29///
30/// ```
31/// use stratum_node_core::Enforcement;
32///
33/// # fn main() -> Result<(), serde_json::Error> {
34/// assert_eq!(serde_json::to_string(&Enforcement::Enforced)?, "\"enforced\"");
35/// assert_eq!(serde_json::from_str::<Enforcement>("\"enforcing\"")?, Enforcement::Enforcing);
36/// assert_eq!(Enforcement::Enforcing.to_string(), "enforcing");
37/// # Ok(())
38/// # }
39/// ```
40#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
41#[serde(rename_all = "lowercase")]
42#[non_exhaustive]
43pub enum Enforcement {
44 /// The suspension is committed, and the gate is not yet known to apply
45 /// it.
46 Enforcing,
47 /// The gate admits no new signed request by or to the member. Requests
48 /// admitted earlier may still be running.
49 Enforced,
50}
51
52impl Enforcement {
53 /// Returns the lowercase name.
54 ///
55 /// # Examples
56 ///
57 /// ```
58 /// use stratum_node_core::Enforcement;
59 ///
60 /// assert_eq!(Enforcement::Enforced.as_str(), "enforced");
61 /// ```
62 pub fn as_str(self) -> &'static str {
63 match self {
64 Self::Enforcing => "enforcing",
65 Self::Enforced => "enforced",
66 }
67 }
68}
69
70impl fmt::Display for Enforcement {
71 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
72 f.write_str(self.as_str())
73 }
74}
75
76/// The body of `POST /api/v1/members/{pk}/suspend`, `…/resume` and
77/// `…/archive`: the node it is addressed to and the operation ID.
78///
79/// The operation ID is bound by the node to the action, the member, the
80/// member's generation and the SHA-256 of this body; a resend returns the
81/// stored response, and any other reuse is 409 `conflict`.
82///
83/// # Examples
84///
85/// ```
86/// use stratum_node_core::{DidNostr, MemberActionRequest};
87///
88/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
89/// let node = DidNostr::from_hex(&"79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798")?;
90/// let body = MemberActionRequest { node, operation_id: "suspend-1".parse()? };
91/// let bytes = serde_json::to_vec(&body)?;
92/// assert!(bytes.starts_with(b"{\"node\":\"did:nostr:"));
93/// assert_eq!(serde_json::from_slice::<MemberActionRequest>(&bytes)?, body);
94/// assert!(serde_json::from_str::<MemberActionRequest>(
95/// r#"{"node":"did:nostr:79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798","operation_id":"x","extra":1}"#
96/// ).is_err());
97/// # Ok(())
98/// # }
99/// ```
100#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
101#[serde(deny_unknown_fields)]
102pub struct MemberActionRequest {
103 /// The node the request is addressed to.
104 pub node: DidNostr,
105 /// The administrator's operation ID.
106 pub operation_id: OperationId,
107}
108
109/// The body of `POST /api/v1/members/{pk}/remove`.
110///
111/// `require_archive` defaults to `true` when the member is absent. Setting
112/// it to `false` is the administrator's recorded decision to remove
113/// without an archive; it is part of the signed body, and the node audits
114/// who waived it. The client always writes the member, so the signed bytes
115/// say which was chosen.
116///
117/// # Examples
118///
119/// ```
120/// use stratum_node_core::RemoveRequest;
121///
122/// # fn main() -> Result<(), serde_json::Error> {
123/// let node = "did:nostr:79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798";
124/// let defaulted: RemoveRequest =
125/// serde_json::from_str(&format!(r#"{{"node":"{node}","operation_id":"rm-1"}}"#))?;
126/// assert!(defaulted.require_archive);
127///
128/// let waived: RemoveRequest = serde_json::from_str(&format!(
129/// r#"{{"node":"{node}","operation_id":"rm-1","require_archive":false}}"#
130/// ))?;
131/// assert!(!waived.require_archive);
132/// assert!(serde_json::to_string(&waived)?.ends_with(r#""require_archive":false}"#));
133/// # Ok(())
134/// # }
135/// ```
136#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
137#[serde(deny_unknown_fields)]
138pub struct RemoveRequest {
139 /// The node the request is addressed to.
140 pub node: DidNostr,
141 /// The administrator's operation ID.
142 pub operation_id: OperationId,
143 /// Whether an archive taken in the current suspension is required.
144 #[serde(default = "default_require_archive")]
145 pub require_archive: bool,
146}
147
148fn default_require_archive() -> bool {
149 true
150}
151
152/// The answer to `POST /api/v1/members/{pk}/suspend`.
153///
154/// The stored response is what was true when the suspension committed: a
155/// resend returns it unchanged, so its `enforcement` is historical. Read
156/// [`MemberView`] for the current value.
157///
158/// # Examples
159///
160/// ```
161/// use stratum_node_core::{Enforcement, MemberState, SuspendResponse};
162///
163/// # fn main() -> Result<(), serde_json::Error> {
164/// let answer = SuspendResponse {
165/// state: MemberState::Suspended,
166/// enforcement: Enforcement::Enforcing,
167/// directory_rev: 12,
168/// suspension: 1,
169/// };
170/// assert_eq!(
171/// serde_json::to_string(&answer)?,
172/// r#"{"state":"suspended","enforcement":"enforcing","directory_rev":12,"suspension":1}"#,
173/// );
174/// # Ok(())
175/// # }
176/// ```
177#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
178pub struct SuspendResponse {
179 /// The member's state, `suspended`.
180 pub state: MemberState,
181 /// Enforcement when the response was built.
182 pub enforcement: Enforcement,
183 /// The directory revision that first lists this suspension.
184 pub directory_rev: u64,
185 /// The suspension number within the member's generation.
186 pub suspension: u64,
187}
188
189/// The answer to `POST /api/v1/members/{pk}/resume`: the state the member
190/// returned to, `provisioned` or `active`.
191///
192/// # Examples
193///
194/// ```
195/// use stratum_node_core::{MemberState, ResumeResponse};
196///
197/// # fn main() -> Result<(), serde_json::Error> {
198/// let answer: ResumeResponse = serde_json::from_str(r#"{"state":"active"}"#)?;
199/// assert_eq!(answer.state, MemberState::Active);
200/// # Ok(())
201/// # }
202/// ```
203#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
204pub struct ResumeResponse {
205 /// The state the member returned to.
206 pub state: MemberState,
207}
208
209/// The answer to `POST /api/v1/members/{pk}/archive`.
210///
211/// `manifest` is the archive's reference: the event ID of the signed
212/// manifest beside the encrypted archive. `remove` and `purge` name an
213/// archive by this reference.
214///
215/// # Examples
216///
217/// ```
218/// use stratum_node_core::{ArchiveResponse, EventId};
219///
220/// # fn main() -> Result<(), serde_json::Error> {
221/// let answer = ArchiveResponse {
222/// directory: "archive-20261204T120000Z".to_owned(),
223/// entries: 4,
224/// bytes: 812,
225/// manifest: EventId::from_bytes([0xab; 32]),
226/// };
227/// let text = serde_json::to_string(&answer)?;
228/// assert!(text.contains(&format!("\"manifest\":\"{}\"", "ab".repeat(32))));
229/// assert_eq!(serde_json::from_str::<ArchiveResponse>(&text)?, answer);
230/// # Ok(())
231/// # }
232/// ```
233#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
234pub struct ArchiveResponse {
235 /// The name of the directory holding the archive and its manifest.
236 pub directory: String,
237 /// The number of entries in the archive.
238 pub entries: u64,
239 /// The unpacked size of the archived pod data, in bytes.
240 pub bytes: u64,
241 /// The archive's reference: the signed manifest's event ID.
242 pub manifest: EventId,
243}
244
245/// What a removal recorded about the archive: the reference of the archive
246/// taken in the removed member's last suspension, or the administrator's
247/// waiver.
248///
249/// On the wire it is the archive reference (the manifest's event ID, 64
250/// lowercase hex digits) or the string `"waived"`. The two cannot be
251/// confused: an event ID is never `"waived"`.
252///
253/// # Examples
254///
255/// ```
256/// use stratum_node_core::{EventId, RemovalArchive};
257///
258/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
259/// let waived: RemovalArchive = "waived".parse()?;
260/// assert_eq!(waived, RemovalArchive::Waived);
261///
262/// let id = EventId::from_bytes([1; 32]);
263/// let archived: RemovalArchive = id.to_hex().parse()?;
264/// assert_eq!(archived, RemovalArchive::Archive(id));
265/// assert_eq!(serde_json::to_string(&waived)?, "\"waived\"");
266/// assert!("WAIVED".parse::<RemovalArchive>().is_err());
267/// # Ok(())
268/// # }
269/// ```
270#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
271#[non_exhaustive]
272pub enum RemovalArchive {
273 /// An archive was taken in the member's current generation and
274 /// suspension; this is its manifest's event ID.
275 Archive(EventId),
276 /// The administrator removed the member without an archive.
277 Waived,
278}
279
280/// The text form of [`RemovalArchive::Waived`].
281const WAIVED: &str = "waived";
282
283impl fmt::Display for RemovalArchive {
284 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
285 match self {
286 Self::Archive(id) => f.write_str(&id.to_hex()),
287 Self::Waived => f.write_str(WAIVED),
288 }
289 }
290}
291
292impl FromStr for RemovalArchive {
293 type Err = ParseRemovalArchiveError;
294
295 /// Parses `"waived"` or an event ID in lowercase hex, exactly.
296 fn from_str(text: &str) -> Result<Self, Self::Err> {
297 if text == WAIVED {
298 return Ok(Self::Waived);
299 }
300 text.parse()
301 .map(Self::Archive)
302 .map_err(|_| ParseRemovalArchiveError)
303 }
304}
305
306impl Serialize for RemovalArchive {
307 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
308 serializer.collect_str(self)
309 }
310}
311
312impl<'de> Deserialize<'de> for RemovalArchive {
313 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
314 let text = String::deserialize(deserializer)?;
315 text.parse().map_err(serde::de::Error::custom)
316 }
317}
318
319/// The text is neither `"waived"` nor an event ID in lowercase hex.
320///
321/// # Examples
322///
323/// ```
324/// use stratum_node_core::{ParseRemovalArchiveError, RemovalArchive};
325///
326/// assert_eq!("Waived".parse::<RemovalArchive>(), Err(ParseRemovalArchiveError));
327/// ```
328#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, thiserror::Error)]
329#[error("removal archive is neither \"waived\" nor an archive reference")]
330pub struct ParseRemovalArchiveError;
331
332/// The answer to `POST /api/v1/members/{pk}/remove`.
333///
334/// # Examples
335///
336/// ```
337/// use stratum_node_core::{MemberState, RemovalArchive, RemoveResponse, UnixTime};
338///
339/// # fn main() -> Result<(), serde_json::Error> {
340/// let answer = RemoveResponse {
341/// state: MemberState::Removed,
342/// purge_not_before: UnixTime::from_secs(1_767_225_600),
343/// archive: RemovalArchive::Waived,
344/// };
345/// assert_eq!(
346/// serde_json::to_string(&answer)?,
347/// r#"{"state":"removed","purge_not_before":1767225600,"archive":"waived"}"#,
348/// );
349/// # Ok(())
350/// # }
351/// ```
352#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
353pub struct RemoveResponse {
354 /// The member's state, `removed`.
355 pub state: MemberState,
356 /// The earliest time `purge` may delete the member's pod data.
357 pub purge_not_before: UnixTime,
358 /// The archive the removal relied on, or the waiver.
359 pub archive: RemovalArchive,
360}
361
362/// The answer to `GET /api/v1/members/{pk}`: one member as it is now.
363///
364/// This route takes no operation ID and its answer is never stored, so
365/// `enforcement` is current. Times are Unix seconds; a time is `null` when
366/// the event has not happened in the current generation. Step 3b adds the
367/// suspension's three enforcement parts and the workspace; a client reading
368/// an older node sees them `null`.
369///
370/// # Examples
371///
372/// ```
373/// use stratum_node_core::{DidNostr, Enforcement, KeysPart, MemberState, MemberView, UnixTime, WorkPart};
374///
375/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
376/// let did = DidNostr::from_hex("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798")?;
377/// let view = MemberView {
378/// did,
379/// state: MemberState::Suspended,
380/// generation: 1,
381/// suspension: 2,
382/// reserved_at: UnixTime::from_secs(1_700_000_000),
383/// provisioned_at: Some(UnixTime::from_secs(1_700_000_010)),
384/// activated_at: Some(UnixTime::from_secs(1_700_000_020)),
385/// suspended_at: Some(UnixTime::from_secs(1_700_000_900)),
386/// cancelled_at: None,
387/// removed_at: None,
388/// enforcement: Some(Enforcement::Enforced),
389/// over_quota: false,
390/// pod_bytes: Some(4096),
391/// measured_at: Some(UnixTime::from_secs(1_700_000_600)),
392/// measurement_ms: Some(12),
393/// purge_not_before: None,
394/// archive: None,
395/// authorisation: Some(Enforcement::Enforced),
396/// keys: Some(KeysPart::Disabled),
397/// work: Some(WorkPart::Stopping),
398/// workspace: None,
399/// };
400/// let text = serde_json::to_string(&view)?;
401/// assert_eq!(serde_json::from_str::<MemberView>(&text)?, view);
402/// # Ok(())
403/// # }
404/// ```
405#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
406pub struct MemberView {
407 /// The member's identity.
408 pub did: DidNostr,
409 /// The membership state.
410 pub state: MemberState,
411 /// The generation: 1 for the first admission, raised by one on each
412 /// re-admission.
413 pub generation: u64,
414 /// The number of suspensions within this generation.
415 pub suspension: u64,
416 /// When the current generation's slot was reserved.
417 pub reserved_at: UnixTime,
418 /// When the pod server created the pod, in this generation.
419 pub provisioned_at: Option<UnixTime>,
420 /// When the owner confirmed the pod, in this generation.
421 pub activated_at: Option<UnixTime>,
422 /// When the current suspension began; `null` unless `suspended`.
423 pub suspended_at: Option<UnixTime>,
424 /// When the administrator cancelled the membership, if they did.
425 pub cancelled_at: Option<UnixTime>,
426 /// When the administrator removed the member, if they did.
427 pub removed_at: Option<UnixTime>,
428 /// Enforcement of the current suspension; `null` unless `suspended`.
429 pub enforcement: Option<Enforcement>,
430 /// Whether the gate refuses `PUT` to this member's pod with 507.
431 pub over_quota: bool,
432 /// The pod's size in bytes at the last measurement for this
433 /// generation, if one has completed.
434 pub pod_bytes: Option<u64>,
435 /// When the last measurement completed.
436 pub measured_at: Option<UnixTime>,
437 /// How long the last measurement took, in milliseconds.
438 pub measurement_ms: Option<u64>,
439 /// The earliest time `purge` may delete the pod data; set when the
440 /// member is `removed` or `cancelled`.
441 pub purge_not_before: Option<UnixTime>,
442 /// The reference of the archive taken in the current suspension, if
443 /// any.
444 pub archive: Option<EventId>,
445 /// The current suspension's authorisation part: `enforced` once the
446 /// gate and the proxy apply it, or their fallback has run out; `null`
447 /// unless `suspended`.
448 pub authorisation: Option<Enforcement>,
449 /// The current suspension's keys part (the signer); `null` unless
450 /// `suspended`.
451 pub keys: Option<KeysPart>,
452 /// The current suspension's work part (the runner); `null` unless
453 /// `suspended`.
454 pub work: Option<WorkPart>,
455 /// The member's workspace slot; always `null` in Step 3b-2.
456 pub workspace: Option<WorkspaceView>,
457}