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