stratum-node-core 0.1.0-alpha.3

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
//! Wire shapes of the administrator's member routes added in Step 3a:
//! suspend, resume, archive, remove and the single-member view.
//!
//! Request types deny unknown members, as the controller's other request
//! bodies do, and serialise their members in declaration order, so a client
//! signs exactly the bytes it sends. 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::admission::MemberState;
use crate::did::DidNostr;
use crate::id::{EventId, OperationId, UnixTime};

/// Whether the gate is known to enforce one suspension.
///
/// Enforcement belongs to one suspension, named by key, generation and
/// suspension number. It is `enforcing` until the gate is known to hold a
/// directory revision that lists the suspension, or until the gate's lease
/// must have run out; then it is `enforced`. It is never stored.
///
/// The text form is `"enforcing"` or `"enforced"`.
///
/// # Examples
///
/// ```
/// use stratum_node_core::Enforcement;
///
/// # fn main() -> Result<(), serde_json::Error> {
/// assert_eq!(serde_json::to_string(&Enforcement::Enforced)?, "\"enforced\"");
/// assert_eq!(serde_json::from_str::<Enforcement>("\"enforcing\"")?, Enforcement::Enforcing);
/// assert_eq!(Enforcement::Enforcing.to_string(), "enforcing");
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
#[non_exhaustive]
pub enum Enforcement {
    /// The suspension is committed, and the gate is not yet known to apply
    /// it.
    Enforcing,
    /// The gate admits no new signed request by or to the member. Requests
    /// admitted earlier may still be running.
    Enforced,
}

impl Enforcement {
    /// Returns the lowercase name.
    ///
    /// # Examples
    ///
    /// ```
    /// use stratum_node_core::Enforcement;
    ///
    /// assert_eq!(Enforcement::Enforced.as_str(), "enforced");
    /// ```
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Enforcing => "enforcing",
            Self::Enforced => "enforced",
        }
    }
}

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

/// The body of `POST /api/v1/members/{pk}/suspend`, `…/resume` and
/// `…/archive`: the node it is addressed to and the operation ID.
///
/// The operation ID is bound by the node to the action, the member, the
/// member's generation and the SHA-256 of this body; a resend returns the
/// stored response, and any other reuse is 409 `conflict`.
///
/// # Examples
///
/// ```
/// use stratum_node_core::{DidNostr, MemberActionRequest};
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let node = DidNostr::from_hex(&"79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798")?;
/// let body = MemberActionRequest { node, operation_id: "suspend-1".parse()? };
/// let bytes = serde_json::to_vec(&body)?;
/// assert!(bytes.starts_with(b"{\"node\":\"did:nostr:"));
/// assert_eq!(serde_json::from_slice::<MemberActionRequest>(&bytes)?, body);
/// assert!(serde_json::from_str::<MemberActionRequest>(
///     r#"{"node":"did:nostr:79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798","operation_id":"x","extra":1}"#
/// ).is_err());
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct MemberActionRequest {
    /// The node the request is addressed to.
    pub node: DidNostr,
    /// The administrator's operation ID.
    pub operation_id: OperationId,
}

/// The body of `POST /api/v1/members/{pk}/remove`.
///
/// `require_archive` defaults to `true` when the member is absent. Setting
/// it to `false` is the administrator's recorded decision to remove
/// without an archive; it is part of the signed body, and the node audits
/// who waived it. The client always writes the member, so the signed bytes
/// say which was chosen.
///
/// # Examples
///
/// ```
/// use stratum_node_core::RemoveRequest;
///
/// # fn main() -> Result<(), serde_json::Error> {
/// let node = "did:nostr:79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798";
/// let defaulted: RemoveRequest =
///     serde_json::from_str(&format!(r#"{{"node":"{node}","operation_id":"rm-1"}}"#))?;
/// assert!(defaulted.require_archive);
///
/// let waived: RemoveRequest = serde_json::from_str(&format!(
///     r#"{{"node":"{node}","operation_id":"rm-1","require_archive":false}}"#
/// ))?;
/// assert!(!waived.require_archive);
/// assert!(serde_json::to_string(&waived)?.ends_with(r#""require_archive":false}"#));
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct RemoveRequest {
    /// The node the request is addressed to.
    pub node: DidNostr,
    /// The administrator's operation ID.
    pub operation_id: OperationId,
    /// Whether an archive taken in the current suspension is required.
    #[serde(default = "default_require_archive")]
    pub require_archive: bool,
}

fn default_require_archive() -> bool {
    true
}

/// The answer to `POST /api/v1/members/{pk}/suspend`.
///
/// The stored response is what was true when the suspension committed: a
/// resend returns it unchanged, so its `enforcement` is historical. Read
/// [`MemberView`] for the current value.
///
/// # Examples
///
/// ```
/// use stratum_node_core::{Enforcement, MemberState, SuspendResponse};
///
/// # fn main() -> Result<(), serde_json::Error> {
/// let answer = SuspendResponse {
///     state: MemberState::Suspended,
///     enforcement: Enforcement::Enforcing,
///     directory_rev: 12,
///     suspension: 1,
/// };
/// assert_eq!(
///     serde_json::to_string(&answer)?,
///     r#"{"state":"suspended","enforcement":"enforcing","directory_rev":12,"suspension":1}"#,
/// );
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct SuspendResponse {
    /// The member's state, `suspended`.
    pub state: MemberState,
    /// Enforcement when the response was built.
    pub enforcement: Enforcement,
    /// The directory revision that first lists this suspension.
    pub directory_rev: u64,
    /// The suspension number within the member's generation.
    pub suspension: u64,
}

/// The answer to `POST /api/v1/members/{pk}/resume`: the state the member
/// returned to, `provisioned` or `active`.
///
/// # Examples
///
/// ```
/// use stratum_node_core::{MemberState, ResumeResponse};
///
/// # fn main() -> Result<(), serde_json::Error> {
/// let answer: ResumeResponse = serde_json::from_str(r#"{"state":"active"}"#)?;
/// assert_eq!(answer.state, MemberState::Active);
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct ResumeResponse {
    /// The state the member returned to.
    pub state: MemberState,
}

/// The answer to `POST /api/v1/members/{pk}/archive`.
///
/// `manifest` is the archive's reference: the event ID of the signed
/// manifest beside the encrypted archive. `remove` and `purge` name an
/// archive by this reference.
///
/// # Examples
///
/// ```
/// use stratum_node_core::{ArchiveResponse, EventId};
///
/// # fn main() -> Result<(), serde_json::Error> {
/// let answer = ArchiveResponse {
///     directory: "archive-20261204T120000Z".to_owned(),
///     entries: 4,
///     bytes: 812,
///     manifest: EventId::from_bytes([0xab; 32]),
/// };
/// let text = serde_json::to_string(&answer)?;
/// assert!(text.contains(&format!("\"manifest\":\"{}\"", "ab".repeat(32))));
/// assert_eq!(serde_json::from_str::<ArchiveResponse>(&text)?, answer);
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct ArchiveResponse {
    /// The name of the directory holding the archive and its manifest.
    pub directory: String,
    /// The number of entries in the archive.
    pub entries: u64,
    /// The unpacked size of the archived pod data, in bytes.
    pub bytes: u64,
    /// The archive's reference: the signed manifest's event ID.
    pub manifest: EventId,
}

/// What a removal recorded about the archive: the reference of the archive
/// taken in the removed member's last suspension, or the administrator's
/// waiver.
///
/// On the wire it is the archive reference (the manifest's event ID, 64
/// lowercase hex digits) or the string `"waived"`. The two cannot be
/// confused: an event ID is never `"waived"`.
///
/// # Examples
///
/// ```
/// use stratum_node_core::{EventId, RemovalArchive};
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let waived: RemovalArchive = "waived".parse()?;
/// assert_eq!(waived, RemovalArchive::Waived);
///
/// let id = EventId::from_bytes([1; 32]);
/// let archived: RemovalArchive = id.to_hex().parse()?;
/// assert_eq!(archived, RemovalArchive::Archive(id));
/// assert_eq!(serde_json::to_string(&waived)?, "\"waived\"");
/// assert!("WAIVED".parse::<RemovalArchive>().is_err());
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum RemovalArchive {
    /// An archive was taken in the member's current generation and
    /// suspension; this is its manifest's event ID.
    Archive(EventId),
    /// The administrator removed the member without an archive.
    Waived,
}

/// The text form of [`RemovalArchive::Waived`].
const WAIVED: &str = "waived";

impl fmt::Display for RemovalArchive {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Archive(id) => f.write_str(&id.to_hex()),
            Self::Waived => f.write_str(WAIVED),
        }
    }
}

impl FromStr for RemovalArchive {
    type Err = ParseRemovalArchiveError;

    /// Parses `"waived"` or an event ID in lowercase hex, exactly.
    fn from_str(text: &str) -> Result<Self, Self::Err> {
        if text == WAIVED {
            return Ok(Self::Waived);
        }
        text.parse()
            .map(Self::Archive)
            .map_err(|_| ParseRemovalArchiveError)
    }
}

impl Serialize for RemovalArchive {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.collect_str(self)
    }
}

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

/// The text is neither `"waived"` nor an event ID in lowercase hex.
///
/// # Examples
///
/// ```
/// use stratum_node_core::{ParseRemovalArchiveError, RemovalArchive};
///
/// assert_eq!("Waived".parse::<RemovalArchive>(), Err(ParseRemovalArchiveError));
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, thiserror::Error)]
#[error("removal archive is neither \"waived\" nor an archive reference")]
pub struct ParseRemovalArchiveError;

/// The answer to `POST /api/v1/members/{pk}/remove`.
///
/// # Examples
///
/// ```
/// use stratum_node_core::{MemberState, RemovalArchive, RemoveResponse, UnixTime};
///
/// # fn main() -> Result<(), serde_json::Error> {
/// let answer = RemoveResponse {
///     state: MemberState::Removed,
///     purge_not_before: UnixTime::from_secs(1_767_225_600),
///     archive: RemovalArchive::Waived,
/// };
/// assert_eq!(
///     serde_json::to_string(&answer)?,
///     r#"{"state":"removed","purge_not_before":1767225600,"archive":"waived"}"#,
/// );
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct RemoveResponse {
    /// The member's state, `removed`.
    pub state: MemberState,
    /// The earliest time `purge` may delete the member's pod data.
    pub purge_not_before: UnixTime,
    /// The archive the removal relied on, or the waiver.
    pub archive: RemovalArchive,
}

/// The answer to `GET /api/v1/members/{pk}`: one member as it is now.
///
/// This route takes no operation ID and its answer is never stored, so
/// `enforcement` is current. Times are Unix seconds; a time is `null` when
/// the event has not happened in the current generation.
///
/// # Examples
///
/// ```
/// use stratum_node_core::{DidNostr, Enforcement, MemberState, MemberView, UnixTime};
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let did = DidNostr::from_hex("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798")?;
/// let view = MemberView {
///     did,
///     state: MemberState::Suspended,
///     generation: 1,
///     suspension: 2,
///     reserved_at: UnixTime::from_secs(1_700_000_000),
///     provisioned_at: Some(UnixTime::from_secs(1_700_000_010)),
///     activated_at: Some(UnixTime::from_secs(1_700_000_020)),
///     suspended_at: Some(UnixTime::from_secs(1_700_000_900)),
///     cancelled_at: None,
///     removed_at: None,
///     enforcement: Some(Enforcement::Enforced),
///     over_quota: false,
///     pod_bytes: Some(4096),
///     measured_at: Some(UnixTime::from_secs(1_700_000_600)),
///     measurement_ms: Some(12),
///     purge_not_before: None,
///     archive: None,
/// };
/// let text = serde_json::to_string(&view)?;
/// assert_eq!(serde_json::from_str::<MemberView>(&text)?, view);
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct MemberView {
    /// The member's identity.
    pub did: DidNostr,
    /// The membership state.
    pub state: MemberState,
    /// The generation: 1 for the first admission, raised by one on each
    /// re-admission.
    pub generation: u64,
    /// The number of suspensions within this generation.
    pub suspension: u64,
    /// When the current generation's slot was reserved.
    pub reserved_at: UnixTime,
    /// When the pod server created the pod, in this generation.
    pub provisioned_at: Option<UnixTime>,
    /// When the owner confirmed the pod, in this generation.
    pub activated_at: Option<UnixTime>,
    /// When the current suspension began; `null` unless `suspended`.
    pub suspended_at: Option<UnixTime>,
    /// When the administrator cancelled the membership, if they did.
    pub cancelled_at: Option<UnixTime>,
    /// When the administrator removed the member, if they did.
    pub removed_at: Option<UnixTime>,
    /// Enforcement of the current suspension; `null` unless `suspended`.
    pub enforcement: Option<Enforcement>,
    /// Whether the gate refuses `PUT` to this member's pod with 507.
    pub over_quota: bool,
    /// The pod's size in bytes at the last measurement for this
    /// generation, if one has completed.
    pub pod_bytes: Option<u64>,
    /// When the last measurement completed.
    pub measured_at: Option<UnixTime>,
    /// How long the last measurement took, in milliseconds.
    pub measurement_ms: Option<u64>,
    /// The earliest time `purge` may delete the pod data; set when the
    /// member is `removed` or `cancelled`.
    pub purge_not_before: Option<UnixTime>,
    /// The reference of the archive taken in the current suspension, if
    /// any.
    pub archive: Option<EventId>,
}