stratum_node_cli/lifecycle.rs
1//! `stratum member suspend|resume|archive|remove|show`: the administrator's
2//! commands for stopping a member, ending a membership and reading one
3//! member, on the loopback API.
4
5use std::thread;
6use std::time::{Duration, Instant};
7
8use serde_json::{json, Value as Json};
9use stratum_node_core::{
10 ArchiveResponse, DidNostr, Enforcement, MemberActionRequest, MemberState, MemberView,
11 NostrSecretKey, OperationId, RemovalArchive, RemoveRequest, RemoveResponse, ResumeResponse,
12 SuspendResponse, UnixTime,
13};
14
15use crate::client::{Client, REQUEST_TIMEOUT};
16use crate::error::CliError;
17use crate::exit;
18use crate::output::sanitize;
19use crate::session::{operation_id, readyz, to_body, Confirmation, Session};
20
21/// The members route; each member is `MEMBERS/<pk>`.
22const MEMBERS: &str = "/api/v1/members";
23
24/// The default for `member suspend --wait`: longer than the node's 310
25/// second fallback, after which a suspension is `enforced` even if the gate
26/// never polled.
27///
28/// # Examples
29///
30/// ```
31/// use stratum_node_cli::DEFAULT_ENFORCEMENT_WAIT;
32///
33/// assert!(DEFAULT_ENFORCEMENT_WAIT.as_secs() > 310);
34/// ```
35pub const DEFAULT_ENFORCEMENT_WAIT: Duration = Duration::from_secs(330);
36
37/// The pause between reads of the member while waiting for enforcement.
38const ENFORCEMENT_POLL_INTERVAL: Duration = Duration::from_secs(2);
39
40/// The least time one read inside the wait is allowed, so that the last
41/// read, made when the wait has all but run out, can still be answered. A
42/// wait therefore ends at most this long after its limit.
43const MIN_WAIT_READ: Duration = Duration::from_secs(1);
44
45/// The time allowed for an archive request. The node pauses writes, waits
46/// for the gate to drain, then compresses and encrypts the pod, as for a
47/// backup, so this is the backup's allowance.
48const ARCHIVE_TIMEOUT: Duration = Duration::from_secs(15 * 60);
49
50/// What `remove` prints about grants other members hold for the key.
51const GRANTS_NOTICE: &str = "other members' ACLs that name this key are not changed: the node \
52 cannot read them. If this key is admitted again, it regains whatever access those ACLs still \
53 give it; members withdraw such grants themselves";
54
55/// What `remove --no-archive` prints about the waiver.
56const WAIVER_NOTICE: &str = "this removes the member WITHOUT an archive of their pod: the waiver \
57 is part of the signed request, and the node records who waived it";
58
59/// Options for [`Session::member_suspend`].
60///
61/// # Examples
62///
63/// ```
64/// use std::time::Duration;
65/// use stratum_node_cli::{Confirmation, SuspendOptions, DEFAULT_ENFORCEMENT_WAIT};
66///
67/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
68/// let options = SuspendOptions {
69/// member: "did:nostr:79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798".parse()?,
70/// operation_id: None,
71/// confirmation: Confirmation::Assumed,
72/// wait: Some(DEFAULT_ENFORCEMENT_WAIT),
73/// };
74/// assert_eq!(options.wait, Some(Duration::from_secs(330)));
75/// # Ok(())
76/// # }
77/// ```
78#[derive(Debug, Clone)]
79pub struct SuspendOptions {
80 /// The member to suspend (`<did>`).
81 pub member: DidNostr,
82 /// The operation ID; random when `None`.
83 pub operation_id: Option<String>,
84 /// Whether to ask first.
85 pub confirmation: Confirmation,
86 /// `--wait [seconds]`: after suspending, read the member until its
87 /// suspension is `enforced`, for at most this long. `None` returns at
88 /// once.
89 pub wait: Option<Duration>,
90}
91
92/// Options for [`Session::member_remove`].
93///
94/// # Examples
95///
96/// ```
97/// use stratum_node_cli::{Confirmation, RemoveOptions};
98///
99/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
100/// // `stratum member remove <did> --no-archive --yes`: a recorded waiver.
101/// let options = RemoveOptions {
102/// member: "did:nostr:79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798".parse()?,
103/// operation_id: Some("rm-2026-12-04".to_owned()),
104/// confirmation: Confirmation::Assumed,
105/// require_archive: false,
106/// };
107/// assert!(!options.require_archive);
108/// # Ok(())
109/// # }
110/// ```
111#[derive(Debug, Clone)]
112pub struct RemoveOptions {
113 /// The member to remove (`<did>`).
114 pub member: DidNostr,
115 /// The operation ID; random when `None`.
116 pub operation_id: Option<String>,
117 /// Whether to ask first.
118 pub confirmation: Confirmation,
119 /// Whether the node must hold an archive taken during the member's
120 /// current suspension (`true` unless `--no-archive`). `false` is a
121 /// recorded waiver.
122 pub require_archive: bool,
123}
124
125/// One administrator member action on the loopback API.
126#[derive(Debug, Clone, Copy, PartialEq, Eq)]
127enum Action {
128 Suspend,
129 Resume,
130 Archive,
131 Remove { require_archive: bool },
132}
133
134impl Action {
135 /// The last segment of the route.
136 fn segment(self) -> &'static str {
137 match self {
138 Self::Suspend => "suspend",
139 Self::Resume => "resume",
140 Self::Archive => "archive",
141 Self::Remove { .. } => "remove",
142 }
143 }
144
145 /// The flags a retry must repeat so that its body is identical.
146 fn retry_flags(self) -> &'static str {
147 match self {
148 Self::Remove {
149 require_archive: false,
150 } => " --no-archive",
151 _ => "",
152 }
153 }
154}
155
156/// A signed action, sent: the operation ID and the parsed answer.
157struct Sent<T> {
158 operation_id: OperationId,
159 answer: T,
160}
161
162impl Session {
163 /// `stratum member suspend <did> [--wait[=<seconds>]] [--yes]`: moves a
164 /// `provisioned` or `active` member to `suspended`. Asks first. Signed.
165 ///
166 /// Sends `POST /api/v1/members/<pk>/suspend` with
167 /// `{"node", "operation_id"}`. The node changes the member's state and
168 /// publishes a new directory revision in one step; no member key and no
169 /// pod write is involved. The answer reports the suspension number and
170 /// whether the suspension is `enforcing` (the gate may still admit new
171 /// requests) or `enforced` (it admits none).
172 ///
173 /// With [`SuspendOptions::wait`], the member is then read with
174 /// `GET /api/v1/members/<pk>` at once, and every two seconds after that
175 /// until enforcement is `enforced`; the enforcement printed is the
176 /// read's, never the answer's. A resend of the same operation returns
177 /// the answer stored when the suspension committed, which may say
178 /// `enforced` for a member resumed since, so only the read is current.
179 /// Each read is allowed only the time left in the wait (at least one
180 /// second), so the wait ends within about a second of its limit.
181 ///
182 /// # Errors
183 ///
184 /// [`CliError::NotConfirmed`]; [`CliError::Refused`] when the answer is
185 /// not `suspended`, or when the member is not, or stops being,
186 /// suspended under that suspension; [`CliError::TimedOut`] when the
187 /// wait runs out while still `enforcing`, or while a read is
188 /// unanswered; and key, transport, protocol and server errors
189 /// (`conflict` from a state that cannot be suspended).
190 ///
191 /// # Examples
192 ///
193 /// ```no_run
194 /// use std::time::Duration;
195 /// use stratum_node_cli::{Confirmation, Output, OutputFormat, Session, SuspendOptions};
196 ///
197 /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
198 /// let session = Session::new(
199 /// "http://127.0.0.1:7460".parse()?,
200 /// Some("operator.nsec".into()),
201 /// Output::new(OutputFormat::Human),
202 /// );
203 /// session.member_suspend(&SuspendOptions {
204 /// member: "did:nostr:79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798".parse()?,
205 /// operation_id: None,
206 /// confirmation: Confirmation::Assumed,
207 /// wait: Some(Duration::from_secs(60)),
208 /// })?;
209 /// # Ok(())
210 /// # }
211 /// ```
212 pub fn member_suspend(&self, options: &SuspendOptions) -> Result<u8, CliError> {
213 let member = options.member;
214 let question = format!(
215 "suspend member {member}? Every signed request by them, and every signed request to \
216 their pod, will be refused until they are resumed"
217 );
218 let sent = self.send_action::<SuspendResponse>(
219 &member,
220 Action::Suspend,
221 options.operation_id.as_deref(),
222 options.confirmation,
223 &question,
224 )?;
225 let answer = sent.answer;
226 if answer.state != MemberState::Suspended {
227 return Err(unexpected_state(&member, "suspend", answer.state));
228 }
229 let mut enforcement = answer.enforcement;
230 let mut waited = None;
231 if let Some(limit) = options.wait {
232 // Always read: on a resend the answer is the stored one, and
233 // its enforcement may belong to a suspension since resumed.
234 let started = Instant::now();
235 if enforcement != Enforcement::Enforced {
236 self.output().note(&format!(
237 "suspension {} is enforcing; waiting up to {} s for it to be enforced",
238 answer.suspension,
239 limit.as_secs()
240 ))?;
241 }
242 enforcement = self.wait_enforced(&member, answer.suspension, limit)?;
243 waited = Some(started.elapsed().as_secs());
244 }
245 self.output().json(&json!({
246 "operation_id": sent.operation_id.as_str(),
247 "did": member,
248 "state": answer.state,
249 "suspension": answer.suspension,
250 "directory_rev": answer.directory_rev,
251 "enforcement": enforcement,
252 "waited_secs": waited,
253 }))?;
254 self.output().line(&format!(
255 "{member}: suspended (suspension {})",
256 answer.suspension
257 ))?;
258 self.output()
259 .line(&format!("directory revision: {}", answer.directory_rev))?;
260 self.output().line(&format!(
261 "enforcement: {}",
262 describe_enforcement(enforcement)
263 ))?;
264 Ok(exit::OK)
265 }
266
267 /// `stratum member resume <did> [--yes]`: returns a `suspended` member
268 /// to the state it had, `provisioned` or `active`. Asks first. Signed.
269 ///
270 /// Sends `POST /api/v1/members/<pk>/resume` with
271 /// `{"node", "operation_id"}`. Resuming ends the suspension and
272 /// discards any archive taken during it.
273 ///
274 /// # Errors
275 ///
276 /// [`CliError::NotConfirmed`], [`CliError::Refused`] when the answer is
277 /// neither `provisioned` nor `active`, and key, transport, protocol and
278 /// server errors (`conflict` for a member that is not suspended).
279 ///
280 /// # Examples
281 ///
282 /// ```no_run
283 /// use stratum_node_cli::{Confirmation, Output, OutputFormat, Session};
284 /// use stratum_node_core::DidNostr;
285 ///
286 /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
287 /// let session = Session::new(
288 /// "http://127.0.0.1:7460".parse()?,
289 /// Some("operator.nsec".into()),
290 /// Output::new(OutputFormat::Human),
291 /// );
292 /// let member: DidNostr =
293 /// "did:nostr:79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798".parse()?;
294 /// session.member_resume(&member, None, Confirmation::Prompt)?;
295 /// # Ok(())
296 /// # }
297 /// ```
298 pub fn member_resume(
299 &self,
300 member: &DidNostr,
301 operation_id_arg: Option<&str>,
302 confirmation: Confirmation,
303 ) -> Result<u8, CliError> {
304 let question = format!(
305 "resume member {member}? Their access, and access to their pod, works again; an \
306 archive taken during this suspension no longer counts for removal"
307 );
308 let sent = self.send_action::<ResumeResponse>(
309 member,
310 Action::Resume,
311 operation_id_arg,
312 confirmation,
313 &question,
314 )?;
315 let state = sent.answer.state;
316 if !matches!(state, MemberState::Provisioned | MemberState::Active) {
317 return Err(unexpected_state(member, "resume", state));
318 }
319 self.output().json(&json!({
320 "operation_id": sent.operation_id.as_str(),
321 "did": member,
322 "state": state,
323 }))?;
324 self.output()
325 .line(&format!("{member}: resumed, now {state}"))?;
326 Ok(exit::OK)
327 }
328
329 /// `stratum member archive <did> [--yes]`: has the node take an
330 /// encrypted archive of a suspended member's pod data. Asks first.
331 /// Signed.
332 ///
333 /// Sends `POST /api/v1/members/<pk>/archive` with
334 /// `{"node", "operation_id"}`, allowing up to 15 minutes for the answer.
335 /// The node refuses unless the member is `suspended` and that
336 /// suspension is `enforced`, and while a backup or another archive
337 /// runs. It pauses writes at the gate for every tenant while it reads
338 /// the pod data, as a backup does. The archive is encrypted to the
339 /// backup recipients and signed by the node; its reference is the
340 /// manifest's event ID, which `remove` and `stratumd purge` name.
341 ///
342 /// # Errors
343 ///
344 /// [`CliError::NotConfirmed`] and key, transport, protocol and server
345 /// errors (`conflict` for a member that is not suspended or not yet
346 /// enforced, or while a backup runs; `gate_unavailable` when the gate
347 /// could not be paused).
348 ///
349 /// # Examples
350 ///
351 /// ```no_run
352 /// use stratum_node_cli::{Confirmation, Output, OutputFormat, Session};
353 /// use stratum_node_core::DidNostr;
354 ///
355 /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
356 /// let session = Session::new(
357 /// "http://127.0.0.1:7460".parse()?,
358 /// Some("operator.nsec".into()),
359 /// Output::new(OutputFormat::Human),
360 /// );
361 /// let member: DidNostr =
362 /// "did:nostr:79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798".parse()?;
363 /// session.member_archive(&member, Some("archive-1"), Confirmation::Assumed)?;
364 /// # Ok(())
365 /// # }
366 /// ```
367 pub fn member_archive(
368 &self,
369 member: &DidNostr,
370 operation_id_arg: Option<&str>,
371 confirmation: Confirmation,
372 ) -> Result<u8, CliError> {
373 let question = format!(
374 "archive the pod of suspended member {member}? Writes to every pod pause while the \
375 node reads it"
376 );
377 let sent = self.send_action::<ArchiveResponse>(
378 member,
379 Action::Archive,
380 operation_id_arg,
381 confirmation,
382 &question,
383 )?;
384 let answer = sent.answer;
385 self.output().json(&json!({
386 "operation_id": sent.operation_id.as_str(),
387 "did": member,
388 "directory": answer.directory,
389 "entries": answer.entries,
390 "bytes": answer.bytes,
391 "manifest": answer.manifest,
392 }))?;
393 self.output().line(&format!("{member}: archived"))?;
394 self.output()
395 .line(&format!("directory: {}", sanitize(&answer.directory)))?;
396 self.output().line(&format!(
397 "entries: {} ({} bytes unpacked)",
398 answer.entries, answer.bytes
399 ))?;
400 self.output()
401 .line(&format!("archive reference: {}", answer.manifest))?;
402 Ok(exit::OK)
403 }
404
405 /// `stratum member remove <did> [--no-archive] [--yes]`: ends a
406 /// `suspended` member's membership. Asks first. Signed.
407 ///
408 /// Sends `POST /api/v1/members/<pk>/remove` with
409 /// `{"node", "operation_id", "require_archive"}`; `require_archive` is
410 /// always written, `true` unless `--no-archive`. The member's slot is
411 /// freed and their pod is unreachable at once; the data stays on disk
412 /// until the operator purges it, no earlier than the `purge_not_before`
413 /// the answer gives. `--no-archive` waives the archive: the prompt and
414 /// the output say so, and the node records who waived it.
415 ///
416 /// Other members' ACLs that name the key are not touched; the output
417 /// says that the key regains that access if it is admitted again.
418 ///
419 /// # Errors
420 ///
421 /// [`CliError::NotConfirmed`], [`CliError::Refused`] when the answer is
422 /// not `removed`, or records a waiver for a request that required an
423 /// archive, or an archive for one that waived it, and
424 /// key, transport, protocol and server errors (`archive_required`, and
425 /// `conflict` for a member that is not suspended).
426 ///
427 /// # Examples
428 ///
429 /// ```no_run
430 /// use stratum_node_cli::{Confirmation, Output, OutputFormat, RemoveOptions, Session};
431 ///
432 /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
433 /// let session = Session::new(
434 /// "http://127.0.0.1:7460".parse()?,
435 /// Some("operator.nsec".into()),
436 /// Output::new(OutputFormat::Human),
437 /// );
438 /// session.member_remove(&RemoveOptions {
439 /// member: "did:nostr:79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798".parse()?,
440 /// operation_id: None,
441 /// confirmation: Confirmation::Prompt,
442 /// require_archive: true,
443 /// })?;
444 /// # Ok(())
445 /// # }
446 /// ```
447 pub fn member_remove(&self, options: &RemoveOptions) -> Result<u8, CliError> {
448 let member = options.member;
449 let question = if options.require_archive {
450 format!(
451 "remove suspended member {member}? Their slot is freed and their pod becomes \
452 unreachable; the node requires an archive from this suspension"
453 )
454 } else {
455 format!(
456 "remove suspended member {member} WITHOUT an archive? Their slot is freed and \
457 their pod becomes unreachable; the waiver is signed and recorded"
458 )
459 };
460 if !options.require_archive {
461 self.output().note(WAIVER_NOTICE)?;
462 }
463 let sent = self.send_action::<RemoveResponse>(
464 &member,
465 Action::Remove {
466 require_archive: options.require_archive,
467 },
468 options.operation_id.as_deref(),
469 options.confirmation,
470 &question,
471 )?;
472 let answer = sent.answer;
473 if answer.state != MemberState::Removed {
474 return Err(unexpected_state(&member, "remove", answer.state));
475 }
476 match (options.require_archive, answer.archive) {
477 (true, RemovalArchive::Archive(_)) | (false, RemovalArchive::Waived) => {}
478 (false, other) => {
479 return Err(CliError::Refused(format!(
480 "the node removed {member} citing archive {other}, but this request waived \
481 the archive"
482 )));
483 }
484 (true, other) => {
485 return Err(CliError::Refused(format!(
486 "the node removed {member} recording archive `{other}`, but this request \
487 required an archive"
488 )));
489 }
490 }
491 let archive_line = match answer.archive {
492 RemovalArchive::Archive(id) => format!("archive: {id}"),
493 _ => format!("archive: waived ({WAIVER_NOTICE})"),
494 };
495 self.output().json(&json!({
496 "operation_id": sent.operation_id.as_str(),
497 "did": member,
498 "state": answer.state,
499 "purge_not_before": answer.purge_not_before,
500 "archive": answer.archive,
501 "archive_waived": answer.archive == RemovalArchive::Waived,
502 "grants_notice": GRANTS_NOTICE,
503 }))?;
504 self.output().line(&format!("{member}: removed"))?;
505 self.output().line(&archive_line)?;
506 self.output().line(&format!(
507 "purge not before: {} (unix time); the pod data stays on disk until the operator \
508 runs `stratumd purge --member {member}`",
509 answer.purge_not_before
510 ))?;
511 self.output().line(&format!("note: {GRANTS_NOTICE}"))?;
512 Ok(exit::OK)
513 }
514
515 /// `stratum member show <did>`: reads one member as it is now. Signed.
516 ///
517 /// Sends `GET /api/v1/members/<pk>`, which takes no operation ID and is
518 /// never stored, so its enforcement is current. Prints the state,
519 /// generation, suspension number, the times of each step, enforcement,
520 /// whether the pod is over quota, the last measurement (size, when, how
521 /// long it took), `purge_not_before` and the archive reference. Under
522 /// `--json`, prints the node's answer.
523 ///
524 /// # Errors
525 ///
526 /// [`CliError::Refused`] when the answer names another member, and key,
527 /// transport, protocol and server errors (`not_found` for a key the
528 /// node has never admitted).
529 ///
530 /// # Examples
531 ///
532 /// ```no_run
533 /// use stratum_node_cli::{Output, OutputFormat, Session};
534 /// use stratum_node_core::DidNostr;
535 ///
536 /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
537 /// let session = Session::new(
538 /// "http://127.0.0.1:7460".parse()?,
539 /// Some("operator.nsec".into()),
540 /// Output::new(OutputFormat::Human),
541 /// );
542 /// let member: DidNostr =
543 /// "did:nostr:79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798".parse()?;
544 /// let _exit_code = session.member_show(&member)?;
545 /// # Ok(())
546 /// # }
547 /// ```
548 pub fn member_show(&self, member: &DidNostr) -> Result<u8, CliError> {
549 let key = self.key()?;
550 let client = self.client()?;
551 let (view, raw) = read_member(&client, &key, member)?;
552 self.output().json(&raw)?;
553 for line in describe_view(&view) {
554 self.output().line(&line)?;
555 }
556 Ok(exit::OK)
557 }
558
559 /// Signs and sends one member action, in the order every administrator
560 /// action follows: operation ID, key, `/readyz`, confirmation, the
561 /// retry note, then the request. Without confirmation nothing is sent.
562 fn send_action<T: serde::de::DeserializeOwned>(
563 &self,
564 member: &DidNostr,
565 action: Action,
566 operation_id_arg: Option<&str>,
567 confirmation: Confirmation,
568 question: &str,
569 ) -> Result<Sent<T>, CliError> {
570 let operation_id = operation_id(operation_id_arg)?;
571 let key = self.key()?;
572 let client = self.client()?;
573 let ready = readyz(&client)?;
574 if !self.confirmed(question, confirmation)? {
575 return Err(CliError::NotConfirmed);
576 }
577 self.output().note(&format!(
578 "operation id: {operation_id} (to retry after a lost response, pass --operation-id \
579 {operation_id}{}: the retry must send the same request)",
580 action.retry_flags()
581 ))?;
582 let body = action_body(action, ready.node_did, &operation_id)?;
583 let path = format!("{MEMBERS}/{}/{}", member.to_hex(), action.segment());
584 let response = if action == Action::Archive {
585 client.post_with_timeout(&path, &body, &key, ARCHIVE_TIMEOUT)?
586 } else {
587 client.post(&path, &body, Some(&key))?
588 };
589 let (answer, _raw): (T, Json) = response.into_json()?;
590 Ok(Sent {
591 operation_id,
592 answer,
593 })
594 }
595
596 /// Reads the member until the suspension numbered `suspension` is
597 /// `enforced`, for at most `limit`. The first read is made at once;
598 /// each read is allowed only the time left, but at least
599 /// [`MIN_WAIT_READ`].
600 fn wait_enforced(
601 &self,
602 member: &DidNostr,
603 suspension: u64,
604 limit: Duration,
605 ) -> Result<Enforcement, CliError> {
606 let key = self.key()?;
607 let client = self.client()?;
608 let deadline = Instant::now() + limit;
609 let still_enforcing = || {
610 CliError::TimedOut(format!(
611 "suspension {suspension} of {member} is still enforcing after {} s: the gate has \
612 not yet confirmed it; `stratum member show {member}` reports when it is enforced",
613 limit.as_secs()
614 ))
615 };
616 loop {
617 let allowed = deadline
618 .saturating_duration_since(Instant::now())
619 .clamp(MIN_WAIT_READ, REQUEST_TIMEOUT);
620 let view = match read_member_within(&client, &key, member, allowed) {
621 Ok((view, _raw)) => view,
622 // The read was cut off by the wait's own limit: the wait ran
623 // out, which is not the node being unreachable.
624 Err(CliError::Unreachable { .. }) if Instant::now() >= deadline => {
625 return Err(still_enforcing())
626 }
627 Err(err) => return Err(err),
628 };
629 if view.state != MemberState::Suspended || view.suspension != suspension {
630 return Err(CliError::Refused(format!(
631 "{member} is now {} (suspension {}), so suspension {suspension} will not be \
632 enforced",
633 view.state, view.suspension
634 )));
635 }
636 match view.enforcement {
637 Some(Enforcement::Enforced) => return Ok(Enforcement::Enforced),
638 Some(_) => {}
639 None => {
640 return Err(CliError::Protocol(format!(
641 "the node reports {member} as suspended with no enforcement"
642 )))
643 }
644 }
645 let now = Instant::now();
646 if now >= deadline {
647 return Err(still_enforcing());
648 }
649 thread::sleep(ENFORCEMENT_POLL_INTERVAL.min(deadline - now));
650 }
651 }
652}
653
654/// Serialises the body of `action`: core's request types, so the client
655/// and the node share one definition. The same operation ID and flags give
656/// the same bytes, which a resend must send.
657fn action_body(
658 action: Action,
659 node: DidNostr,
660 operation_id: &OperationId,
661) -> Result<Vec<u8>, CliError> {
662 match action {
663 Action::Remove { require_archive } => to_body(&RemoveRequest {
664 node,
665 operation_id: operation_id.clone(),
666 require_archive,
667 }),
668 Action::Suspend | Action::Resume | Action::Archive => to_body(&MemberActionRequest {
669 node,
670 operation_id: operation_id.clone(),
671 }),
672 }
673}
674
675/// `GET /api/v1/members/<pk>`, checked to name `member`.
676fn read_member(
677 client: &Client,
678 key: &NostrSecretKey,
679 member: &DidNostr,
680) -> Result<(MemberView, Json), CliError> {
681 read_member_within(client, key, member, REQUEST_TIMEOUT)
682}
683
684/// As [`read_member`], allowing `timeout` for the exchange.
685fn read_member_within(
686 client: &Client,
687 key: &NostrSecretKey,
688 member: &DidNostr,
689 timeout: Duration,
690) -> Result<(MemberView, Json), CliError> {
691 let path = format!("{MEMBERS}/{}", member.to_hex());
692 let (view, raw): (MemberView, Json) = client
693 .get_with_timeout(&path, Some(key), timeout)?
694 .into_json()?;
695 if view.did != *member {
696 return Err(CliError::Refused(format!(
697 "asked for {member}, the node answered with {}",
698 view.did
699 )));
700 }
701 Ok((view, raw))
702}
703
704/// The error for an answer in a state the action cannot produce.
705fn unexpected_state(member: &DidNostr, action: &str, state: MemberState) -> CliError {
706 CliError::Refused(format!(
707 "the node reports {member} as {state} after {action}"
708 ))
709}
710
711/// Explains an enforcement value.
712fn describe_enforcement(enforcement: Enforcement) -> String {
713 match enforcement {
714 Enforcement::Enforced => "enforced: the gate admits no new signed request by or to \
715 this member (requests already admitted may still finish)"
716 .to_owned(),
717 other => format!(
718 "{}: the gate may still admit new requests until it takes the new directory, or \
719 310 s have passed; pass --wait, or run `stratum member show`",
720 other.as_str()
721 ),
722 }
723}
724
725/// Formats an optional time.
726fn time(value: Option<UnixTime>) -> String {
727 value.map_or_else(|| "-".to_owned(), |t| t.to_string())
728}
729
730/// The human lines of `member show`.
731fn describe_view(view: &MemberView) -> Vec<String> {
732 let measurement = match (view.pod_bytes, view.measured_at, view.measurement_ms) {
733 (Some(bytes), Some(at), Some(ms)) => {
734 format!("{bytes} bytes, measured at {at} (unix time) in {ms} ms")
735 }
736 (Some(bytes), at, ms) => format!(
737 "{bytes} bytes, measured at {} in {} ms",
738 time(at),
739 ms.map_or_else(|| "-".to_owned(), |ms| ms.to_string())
740 ),
741 _ => "not measured yet".to_owned(),
742 };
743 vec![
744 format!("member: {}", view.did),
745 format!("state: {}", view.state),
746 format!("generation: {}", view.generation),
747 format!("suspension: {}", view.suspension),
748 format!(
749 "enforcement: {}",
750 view.enforcement.map_or("-", Enforcement::as_str)
751 ),
752 format!("over quota: {}", if view.over_quota { "yes" } else { "no" }),
753 format!("pod size: {measurement}"),
754 format!("reserved at: {}", view.reserved_at),
755 format!("provisioned at: {}", time(view.provisioned_at)),
756 format!("activated at: {}", time(view.activated_at)),
757 format!("suspended at: {}", time(view.suspended_at)),
758 format!("cancelled at: {}", time(view.cancelled_at)),
759 format!("removed at: {}", time(view.removed_at)),
760 format!("purge not before: {}", time(view.purge_not_before)),
761 format!(
762 "archive: {}",
763 view.archive
764 .map_or_else(|| "-".to_owned(), |id| id.to_hex())
765 ),
766 ]
767}
768
769#[cfg(test)]
770mod tests {
771 use super::*;
772
773 fn node() -> DidNostr {
774 DidNostr::from_hex("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798")
775 .expect("key")
776 }
777
778 #[test]
779 fn e3a_25_the_same_operation_and_flags_give_the_same_bytes() {
780 let id: OperationId = "rm-1".parse().expect("id");
781 let first = action_body(
782 Action::Remove {
783 require_archive: false,
784 },
785 node(),
786 &id,
787 )
788 .expect("body");
789 let again = action_body(
790 Action::Remove {
791 require_archive: false,
792 },
793 node(),
794 &id,
795 )
796 .expect("body");
797 assert_eq!(first, again);
798 let required = action_body(
799 Action::Remove {
800 require_archive: true,
801 },
802 node(),
803 &id,
804 )
805 .expect("body");
806 assert_ne!(first, required);
807 assert!(String::from_utf8(required)
808 .expect("utf8")
809 .ends_with(r#""require_archive":true}"#));
810 let suspend = action_body(Action::Suspend, node(), &id).expect("body");
811 assert_eq!(
812 String::from_utf8(suspend).expect("utf8"),
813 format!(r#"{{"node":"{}","operation_id":"rm-1"}}"#, node())
814 );
815 }
816
817 #[test]
818 fn retries_repeat_the_waiver_flag() {
819 assert_eq!(
820 Action::Remove {
821 require_archive: false
822 }
823 .retry_flags(),
824 " --no-archive"
825 );
826 assert_eq!(
827 Action::Remove {
828 require_archive: true
829 }
830 .retry_flags(),
831 ""
832 );
833 assert_eq!(Action::Suspend.retry_flags(), "");
834 }
835}