stratum-node-cli 0.1.0-alpha.3

The `stratum` client for Stratum pod nodes: operator key files, bootstrap, config, backup, invitations and members over the loopback API; join, pod access and export for tenants through the gate
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
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
//! `stratum member suspend|resume|archive|remove|show`: the administrator's
//! commands for stopping a member, ending a membership and reading one
//! member, on the loopback API.

use std::thread;
use std::time::{Duration, Instant};

use serde_json::{json, Value as Json};
use stratum_node_core::{
    ArchiveResponse, DidNostr, Enforcement, MemberActionRequest, MemberState, MemberView,
    NostrSecretKey, OperationId, RemovalArchive, RemoveRequest, RemoveResponse, ResumeResponse,
    SuspendResponse, UnixTime,
};

use crate::client::{Client, REQUEST_TIMEOUT};
use crate::error::CliError;
use crate::exit;
use crate::output::sanitize;
use crate::session::{operation_id, readyz, to_body, Confirmation, Session};

/// The members route; each member is `MEMBERS/<pk>`.
const MEMBERS: &str = "/api/v1/members";

/// The default for `member suspend --wait`: longer than the node's 310
/// second fallback, after which a suspension is `enforced` even if the gate
/// never polled.
///
/// # Examples
///
/// ```
/// use stratum_node_cli::DEFAULT_ENFORCEMENT_WAIT;
///
/// assert!(DEFAULT_ENFORCEMENT_WAIT.as_secs() > 310);
/// ```
pub const DEFAULT_ENFORCEMENT_WAIT: Duration = Duration::from_secs(330);

/// The pause between reads of the member while waiting for enforcement.
const ENFORCEMENT_POLL_INTERVAL: Duration = Duration::from_secs(2);

/// The least time one read inside the wait is allowed, so that the last
/// read, made when the wait has all but run out, can still be answered. A
/// wait therefore ends at most this long after its limit.
const MIN_WAIT_READ: Duration = Duration::from_secs(1);

/// The time allowed for an archive request. The node pauses writes, waits
/// for the gate to drain, then compresses and encrypts the pod, as for a
/// backup, so this is the backup's allowance.
const ARCHIVE_TIMEOUT: Duration = Duration::from_secs(15 * 60);

/// What `remove` prints about grants other members hold for the key.
const GRANTS_NOTICE: &str = "other members' ACLs that name this key are not changed: the node \
     cannot read them. If this key is admitted again, it regains whatever access those ACLs still \
     give it; members withdraw such grants themselves";

/// What `remove --no-archive` prints about the waiver.
const WAIVER_NOTICE: &str = "this removes the member WITHOUT an archive of their pod: the waiver \
     is part of the signed request, and the node records who waived it";

/// Options for [`Session::member_suspend`].
///
/// # Examples
///
/// ```
/// use std::time::Duration;
/// use stratum_node_cli::{Confirmation, SuspendOptions, DEFAULT_ENFORCEMENT_WAIT};
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let options = SuspendOptions {
///     member: "did:nostr:79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798".parse()?,
///     operation_id: None,
///     confirmation: Confirmation::Assumed,
///     wait: Some(DEFAULT_ENFORCEMENT_WAIT),
/// };
/// assert_eq!(options.wait, Some(Duration::from_secs(330)));
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone)]
pub struct SuspendOptions {
    /// The member to suspend (`<did>`).
    pub member: DidNostr,
    /// The operation ID; random when `None`.
    pub operation_id: Option<String>,
    /// Whether to ask first.
    pub confirmation: Confirmation,
    /// `--wait [seconds]`: after suspending, read the member until its
    /// suspension is `enforced`, for at most this long. `None` returns at
    /// once.
    pub wait: Option<Duration>,
}

/// Options for [`Session::member_remove`].
///
/// # Examples
///
/// ```
/// use stratum_node_cli::{Confirmation, RemoveOptions};
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// // `stratum member remove <did> --no-archive --yes`: a recorded waiver.
/// let options = RemoveOptions {
///     member: "did:nostr:79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798".parse()?,
///     operation_id: Some("rm-2026-12-04".to_owned()),
///     confirmation: Confirmation::Assumed,
///     require_archive: false,
/// };
/// assert!(!options.require_archive);
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone)]
pub struct RemoveOptions {
    /// The member to remove (`<did>`).
    pub member: DidNostr,
    /// The operation ID; random when `None`.
    pub operation_id: Option<String>,
    /// Whether to ask first.
    pub confirmation: Confirmation,
    /// Whether the node must hold an archive taken during the member's
    /// current suspension (`true` unless `--no-archive`). `false` is a
    /// recorded waiver.
    pub require_archive: bool,
}

/// One administrator member action on the loopback API.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Action {
    Suspend,
    Resume,
    Archive,
    Remove { require_archive: bool },
}

impl Action {
    /// The last segment of the route.
    fn segment(self) -> &'static str {
        match self {
            Self::Suspend => "suspend",
            Self::Resume => "resume",
            Self::Archive => "archive",
            Self::Remove { .. } => "remove",
        }
    }

    /// The flags a retry must repeat so that its body is identical.
    fn retry_flags(self) -> &'static str {
        match self {
            Self::Remove {
                require_archive: false,
            } => " --no-archive",
            _ => "",
        }
    }
}

/// A signed action, sent: the operation ID and the parsed answer.
struct Sent<T> {
    operation_id: OperationId,
    answer: T,
}

impl Session {
    /// `stratum member suspend <did> [--wait[=<seconds>]] [--yes]`: moves a
    /// `provisioned` or `active` member to `suspended`. Asks first. Signed.
    ///
    /// Sends `POST /api/v1/members/<pk>/suspend` with
    /// `{"node", "operation_id"}`. The node changes the member's state and
    /// publishes a new directory revision in one step; no member key and no
    /// pod write is involved. The answer reports the suspension number and
    /// whether the suspension is `enforcing` (the gate may still admit new
    /// requests) or `enforced` (it admits none).
    ///
    /// With [`SuspendOptions::wait`], the member is then read with
    /// `GET /api/v1/members/<pk>` at once, and every two seconds after that
    /// until enforcement is `enforced`; the enforcement printed is the
    /// read's, never the answer's. A resend of the same operation returns
    /// the answer stored when the suspension committed, which may say
    /// `enforced` for a member resumed since, so only the read is current.
    /// Each read is allowed only the time left in the wait (at least one
    /// second), so the wait ends within about a second of its limit.
    ///
    /// # Errors
    ///
    /// [`CliError::NotConfirmed`]; [`CliError::Refused`] when the answer is
    /// not `suspended`, or when the member is not, or stops being,
    /// suspended under that suspension; [`CliError::TimedOut`] when the
    /// wait runs out while still `enforcing`, or while a read is
    /// unanswered; and key, transport, protocol and server errors
    /// (`conflict` from a state that cannot be suspended).
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use std::time::Duration;
    /// use stratum_node_cli::{Confirmation, Output, OutputFormat, Session, SuspendOptions};
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let session = Session::new(
    ///     "http://127.0.0.1:7460".parse()?,
    ///     Some("operator.nsec".into()),
    ///     Output::new(OutputFormat::Human),
    /// );
    /// session.member_suspend(&SuspendOptions {
    ///     member: "did:nostr:79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798".parse()?,
    ///     operation_id: None,
    ///     confirmation: Confirmation::Assumed,
    ///     wait: Some(Duration::from_secs(60)),
    /// })?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn member_suspend(&self, options: &SuspendOptions) -> Result<u8, CliError> {
        let member = options.member;
        let question = format!(
            "suspend member {member}? Every signed request by them, and every signed request to \
             their pod, will be refused until they are resumed"
        );
        let sent = self.send_action::<SuspendResponse>(
            &member,
            Action::Suspend,
            options.operation_id.as_deref(),
            options.confirmation,
            &question,
        )?;
        let answer = sent.answer;
        if answer.state != MemberState::Suspended {
            return Err(unexpected_state(&member, "suspend", answer.state));
        }
        let mut enforcement = answer.enforcement;
        let mut waited = None;
        if let Some(limit) = options.wait {
            // Always read: on a resend the answer is the stored one, and
            // its enforcement may belong to a suspension since resumed.
            let started = Instant::now();
            if enforcement != Enforcement::Enforced {
                self.output().note(&format!(
                    "suspension {} is enforcing; waiting up to {} s for it to be enforced",
                    answer.suspension,
                    limit.as_secs()
                ))?;
            }
            enforcement = self.wait_enforced(&member, answer.suspension, limit)?;
            waited = Some(started.elapsed().as_secs());
        }
        self.output().json(&json!({
            "operation_id": sent.operation_id.as_str(),
            "did": member,
            "state": answer.state,
            "suspension": answer.suspension,
            "directory_rev": answer.directory_rev,
            "enforcement": enforcement,
            "waited_secs": waited,
        }))?;
        self.output().line(&format!(
            "{member}: suspended (suspension {})",
            answer.suspension
        ))?;
        self.output()
            .line(&format!("directory revision: {}", answer.directory_rev))?;
        self.output().line(&format!(
            "enforcement: {}",
            describe_enforcement(enforcement)
        ))?;
        Ok(exit::OK)
    }

    /// `stratum member resume <did> [--yes]`: returns a `suspended` member
    /// to the state it had, `provisioned` or `active`. Asks first. Signed.
    ///
    /// Sends `POST /api/v1/members/<pk>/resume` with
    /// `{"node", "operation_id"}`. Resuming ends the suspension and
    /// discards any archive taken during it.
    ///
    /// # Errors
    ///
    /// [`CliError::NotConfirmed`], [`CliError::Refused`] when the answer is
    /// neither `provisioned` nor `active`, and key, transport, protocol and
    /// server errors (`conflict` for a member that is not suspended).
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use stratum_node_cli::{Confirmation, Output, OutputFormat, Session};
    /// use stratum_node_core::DidNostr;
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let session = Session::new(
    ///     "http://127.0.0.1:7460".parse()?,
    ///     Some("operator.nsec".into()),
    ///     Output::new(OutputFormat::Human),
    /// );
    /// let member: DidNostr =
    ///     "did:nostr:79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798".parse()?;
    /// session.member_resume(&member, None, Confirmation::Prompt)?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn member_resume(
        &self,
        member: &DidNostr,
        operation_id_arg: Option<&str>,
        confirmation: Confirmation,
    ) -> Result<u8, CliError> {
        let question = format!(
            "resume member {member}? Their access, and access to their pod, works again; an \
             archive taken during this suspension no longer counts for removal"
        );
        let sent = self.send_action::<ResumeResponse>(
            member,
            Action::Resume,
            operation_id_arg,
            confirmation,
            &question,
        )?;
        let state = sent.answer.state;
        if !matches!(state, MemberState::Provisioned | MemberState::Active) {
            return Err(unexpected_state(member, "resume", state));
        }
        self.output().json(&json!({
            "operation_id": sent.operation_id.as_str(),
            "did": member,
            "state": state,
        }))?;
        self.output()
            .line(&format!("{member}: resumed, now {state}"))?;
        Ok(exit::OK)
    }

    /// `stratum member archive <did> [--yes]`: has the node take an
    /// encrypted archive of a suspended member's pod data. Asks first.
    /// Signed.
    ///
    /// Sends `POST /api/v1/members/<pk>/archive` with
    /// `{"node", "operation_id"}`, allowing up to 15 minutes for the answer.
    /// The node refuses unless the member is `suspended` and that
    /// suspension is `enforced`, and while a backup or another archive
    /// runs. It pauses writes at the gate for every tenant while it reads
    /// the pod data, as a backup does. The archive is encrypted to the
    /// backup recipients and signed by the node; its reference is the
    /// manifest's event ID, which `remove` and `stratumd purge` name.
    ///
    /// # Errors
    ///
    /// [`CliError::NotConfirmed`] and key, transport, protocol and server
    /// errors (`conflict` for a member that is not suspended or not yet
    /// enforced, or while a backup runs; `gate_unavailable` when the gate
    /// could not be paused).
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use stratum_node_cli::{Confirmation, Output, OutputFormat, Session};
    /// use stratum_node_core::DidNostr;
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let session = Session::new(
    ///     "http://127.0.0.1:7460".parse()?,
    ///     Some("operator.nsec".into()),
    ///     Output::new(OutputFormat::Human),
    /// );
    /// let member: DidNostr =
    ///     "did:nostr:79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798".parse()?;
    /// session.member_archive(&member, Some("archive-1"), Confirmation::Assumed)?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn member_archive(
        &self,
        member: &DidNostr,
        operation_id_arg: Option<&str>,
        confirmation: Confirmation,
    ) -> Result<u8, CliError> {
        let question = format!(
            "archive the pod of suspended member {member}? Writes to every pod pause while the \
             node reads it"
        );
        let sent = self.send_action::<ArchiveResponse>(
            member,
            Action::Archive,
            operation_id_arg,
            confirmation,
            &question,
        )?;
        let answer = sent.answer;
        self.output().json(&json!({
            "operation_id": sent.operation_id.as_str(),
            "did": member,
            "directory": answer.directory,
            "entries": answer.entries,
            "bytes": answer.bytes,
            "manifest": answer.manifest,
        }))?;
        self.output().line(&format!("{member}: archived"))?;
        self.output()
            .line(&format!("directory: {}", sanitize(&answer.directory)))?;
        self.output().line(&format!(
            "entries: {} ({} bytes unpacked)",
            answer.entries, answer.bytes
        ))?;
        self.output()
            .line(&format!("archive reference: {}", answer.manifest))?;
        Ok(exit::OK)
    }

    /// `stratum member remove <did> [--no-archive] [--yes]`: ends a
    /// `suspended` member's membership. Asks first. Signed.
    ///
    /// Sends `POST /api/v1/members/<pk>/remove` with
    /// `{"node", "operation_id", "require_archive"}`; `require_archive` is
    /// always written, `true` unless `--no-archive`. The member's slot is
    /// freed and their pod is unreachable at once; the data stays on disk
    /// until the operator purges it, no earlier than the `purge_not_before`
    /// the answer gives. `--no-archive` waives the archive: the prompt and
    /// the output say so, and the node records who waived it.
    ///
    /// Other members' ACLs that name the key are not touched; the output
    /// says that the key regains that access if it is admitted again.
    ///
    /// # Errors
    ///
    /// [`CliError::NotConfirmed`], [`CliError::Refused`] when the answer is
    /// not `removed`, or records a waiver for a request that required an
    /// archive, or an archive for one that waived it, and
    /// key, transport, protocol and server errors (`archive_required`, and
    /// `conflict` for a member that is not suspended).
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use stratum_node_cli::{Confirmation, Output, OutputFormat, RemoveOptions, Session};
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let session = Session::new(
    ///     "http://127.0.0.1:7460".parse()?,
    ///     Some("operator.nsec".into()),
    ///     Output::new(OutputFormat::Human),
    /// );
    /// session.member_remove(&RemoveOptions {
    ///     member: "did:nostr:79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798".parse()?,
    ///     operation_id: None,
    ///     confirmation: Confirmation::Prompt,
    ///     require_archive: true,
    /// })?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn member_remove(&self, options: &RemoveOptions) -> Result<u8, CliError> {
        let member = options.member;
        let question = if options.require_archive {
            format!(
                "remove suspended member {member}? Their slot is freed and their pod becomes \
                 unreachable; the node requires an archive from this suspension"
            )
        } else {
            format!(
                "remove suspended member {member} WITHOUT an archive? Their slot is freed and \
                 their pod becomes unreachable; the waiver is signed and recorded"
            )
        };
        if !options.require_archive {
            self.output().note(WAIVER_NOTICE)?;
        }
        let sent = self.send_action::<RemoveResponse>(
            &member,
            Action::Remove {
                require_archive: options.require_archive,
            },
            options.operation_id.as_deref(),
            options.confirmation,
            &question,
        )?;
        let answer = sent.answer;
        if answer.state != MemberState::Removed {
            return Err(unexpected_state(&member, "remove", answer.state));
        }
        match (options.require_archive, answer.archive) {
            (true, RemovalArchive::Archive(_)) | (false, RemovalArchive::Waived) => {}
            (false, other) => {
                return Err(CliError::Refused(format!(
                    "the node removed {member} citing archive {other}, but this request waived \
                     the archive"
                )));
            }
            (true, other) => {
                return Err(CliError::Refused(format!(
                    "the node removed {member} recording archive `{other}`, but this request \
                     required an archive"
                )));
            }
        }
        let archive_line = match answer.archive {
            RemovalArchive::Archive(id) => format!("archive: {id}"),
            _ => format!("archive: waived ({WAIVER_NOTICE})"),
        };
        self.output().json(&json!({
            "operation_id": sent.operation_id.as_str(),
            "did": member,
            "state": answer.state,
            "purge_not_before": answer.purge_not_before,
            "archive": answer.archive,
            "archive_waived": answer.archive == RemovalArchive::Waived,
            "grants_notice": GRANTS_NOTICE,
        }))?;
        self.output().line(&format!("{member}: removed"))?;
        self.output().line(&archive_line)?;
        self.output().line(&format!(
            "purge not before: {} (unix time); the pod data stays on disk until the operator \
             runs `stratumd purge --member {member}`",
            answer.purge_not_before
        ))?;
        self.output().line(&format!("note: {GRANTS_NOTICE}"))?;
        Ok(exit::OK)
    }

    /// `stratum member show <did>`: reads one member as it is now. Signed.
    ///
    /// Sends `GET /api/v1/members/<pk>`, which takes no operation ID and is
    /// never stored, so its enforcement is current. Prints the state,
    /// generation, suspension number, the times of each step, enforcement,
    /// whether the pod is over quota, the last measurement (size, when, how
    /// long it took), `purge_not_before` and the archive reference. Under
    /// `--json`, prints the node's answer.
    ///
    /// # Errors
    ///
    /// [`CliError::Refused`] when the answer names another member, and key,
    /// transport, protocol and server errors (`not_found` for a key the
    /// node has never admitted).
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use stratum_node_cli::{Output, OutputFormat, Session};
    /// use stratum_node_core::DidNostr;
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let session = Session::new(
    ///     "http://127.0.0.1:7460".parse()?,
    ///     Some("operator.nsec".into()),
    ///     Output::new(OutputFormat::Human),
    /// );
    /// let member: DidNostr =
    ///     "did:nostr:79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798".parse()?;
    /// let _exit_code = session.member_show(&member)?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn member_show(&self, member: &DidNostr) -> Result<u8, CliError> {
        let key = self.key()?;
        let client = self.client()?;
        let (view, raw) = read_member(&client, &key, member)?;
        self.output().json(&raw)?;
        for line in describe_view(&view) {
            self.output().line(&line)?;
        }
        Ok(exit::OK)
    }

    /// Signs and sends one member action, in the order every administrator
    /// action follows: operation ID, key, `/readyz`, confirmation, the
    /// retry note, then the request. Without confirmation nothing is sent.
    fn send_action<T: serde::de::DeserializeOwned>(
        &self,
        member: &DidNostr,
        action: Action,
        operation_id_arg: Option<&str>,
        confirmation: Confirmation,
        question: &str,
    ) -> Result<Sent<T>, CliError> {
        let operation_id = operation_id(operation_id_arg)?;
        let key = self.key()?;
        let client = self.client()?;
        let ready = readyz(&client)?;
        if !self.confirmed(question, confirmation)? {
            return Err(CliError::NotConfirmed);
        }
        self.output().note(&format!(
            "operation id: {operation_id} (to retry after a lost response, pass --operation-id \
             {operation_id}{}: the retry must send the same request)",
            action.retry_flags()
        ))?;
        let body = action_body(action, ready.node_did, &operation_id)?;
        let path = format!("{MEMBERS}/{}/{}", member.to_hex(), action.segment());
        let response = if action == Action::Archive {
            client.post_with_timeout(&path, &body, &key, ARCHIVE_TIMEOUT)?
        } else {
            client.post(&path, &body, Some(&key))?
        };
        let (answer, _raw): (T, Json) = response.into_json()?;
        Ok(Sent {
            operation_id,
            answer,
        })
    }

    /// Reads the member until the suspension numbered `suspension` is
    /// `enforced`, for at most `limit`. The first read is made at once;
    /// each read is allowed only the time left, but at least
    /// [`MIN_WAIT_READ`].
    fn wait_enforced(
        &self,
        member: &DidNostr,
        suspension: u64,
        limit: Duration,
    ) -> Result<Enforcement, CliError> {
        let key = self.key()?;
        let client = self.client()?;
        let deadline = Instant::now() + limit;
        let still_enforcing = || {
            CliError::TimedOut(format!(
                "suspension {suspension} of {member} is still enforcing after {} s: the gate has \
                 not yet confirmed it; `stratum member show {member}` reports when it is enforced",
                limit.as_secs()
            ))
        };
        loop {
            let allowed = deadline
                .saturating_duration_since(Instant::now())
                .clamp(MIN_WAIT_READ, REQUEST_TIMEOUT);
            let view = match read_member_within(&client, &key, member, allowed) {
                Ok((view, _raw)) => view,
                // The read was cut off by the wait's own limit: the wait ran
                // out, which is not the node being unreachable.
                Err(CliError::Unreachable { .. }) if Instant::now() >= deadline => {
                    return Err(still_enforcing())
                }
                Err(err) => return Err(err),
            };
            if view.state != MemberState::Suspended || view.suspension != suspension {
                return Err(CliError::Refused(format!(
                    "{member} is now {} (suspension {}), so suspension {suspension} will not be \
                     enforced",
                    view.state, view.suspension
                )));
            }
            match view.enforcement {
                Some(Enforcement::Enforced) => return Ok(Enforcement::Enforced),
                Some(_) => {}
                None => {
                    return Err(CliError::Protocol(format!(
                        "the node reports {member} as suspended with no enforcement"
                    )))
                }
            }
            let now = Instant::now();
            if now >= deadline {
                return Err(still_enforcing());
            }
            thread::sleep(ENFORCEMENT_POLL_INTERVAL.min(deadline - now));
        }
    }
}

/// Serialises the body of `action`: core's request types, so the client
/// and the node share one definition. The same operation ID and flags give
/// the same bytes, which a resend must send.
fn action_body(
    action: Action,
    node: DidNostr,
    operation_id: &OperationId,
) -> Result<Vec<u8>, CliError> {
    match action {
        Action::Remove { require_archive } => to_body(&RemoveRequest {
            node,
            operation_id: operation_id.clone(),
            require_archive,
        }),
        Action::Suspend | Action::Resume | Action::Archive => to_body(&MemberActionRequest {
            node,
            operation_id: operation_id.clone(),
        }),
    }
}

/// `GET /api/v1/members/<pk>`, checked to name `member`.
fn read_member(
    client: &Client,
    key: &NostrSecretKey,
    member: &DidNostr,
) -> Result<(MemberView, Json), CliError> {
    read_member_within(client, key, member, REQUEST_TIMEOUT)
}

/// As [`read_member`], allowing `timeout` for the exchange.
fn read_member_within(
    client: &Client,
    key: &NostrSecretKey,
    member: &DidNostr,
    timeout: Duration,
) -> Result<(MemberView, Json), CliError> {
    let path = format!("{MEMBERS}/{}", member.to_hex());
    let (view, raw): (MemberView, Json) = client
        .get_with_timeout(&path, Some(key), timeout)?
        .into_json()?;
    if view.did != *member {
        return Err(CliError::Refused(format!(
            "asked for {member}, the node answered with {}",
            view.did
        )));
    }
    Ok((view, raw))
}

/// The error for an answer in a state the action cannot produce.
fn unexpected_state(member: &DidNostr, action: &str, state: MemberState) -> CliError {
    CliError::Refused(format!(
        "the node reports {member} as {state} after {action}"
    ))
}

/// Explains an enforcement value.
fn describe_enforcement(enforcement: Enforcement) -> String {
    match enforcement {
        Enforcement::Enforced => "enforced: the gate admits no new signed request by or to \
             this member (requests already admitted may still finish)"
            .to_owned(),
        other => format!(
            "{}: the gate may still admit new requests until it takes the new directory, or \
             310 s have passed; pass --wait, or run `stratum member show`",
            other.as_str()
        ),
    }
}

/// Formats an optional time.
fn time(value: Option<UnixTime>) -> String {
    value.map_or_else(|| "-".to_owned(), |t| t.to_string())
}

/// The human lines of `member show`.
fn describe_view(view: &MemberView) -> Vec<String> {
    let measurement = match (view.pod_bytes, view.measured_at, view.measurement_ms) {
        (Some(bytes), Some(at), Some(ms)) => {
            format!("{bytes} bytes, measured at {at} (unix time) in {ms} ms")
        }
        (Some(bytes), at, ms) => format!(
            "{bytes} bytes, measured at {} in {} ms",
            time(at),
            ms.map_or_else(|| "-".to_owned(), |ms| ms.to_string())
        ),
        _ => "not measured yet".to_owned(),
    };
    vec![
        format!("member: {}", view.did),
        format!("state: {}", view.state),
        format!("generation: {}", view.generation),
        format!("suspension: {}", view.suspension),
        format!(
            "enforcement: {}",
            view.enforcement.map_or("-", Enforcement::as_str)
        ),
        format!("over quota: {}", if view.over_quota { "yes" } else { "no" }),
        format!("pod size: {measurement}"),
        format!("reserved at: {}", view.reserved_at),
        format!("provisioned at: {}", time(view.provisioned_at)),
        format!("activated at: {}", time(view.activated_at)),
        format!("suspended at: {}", time(view.suspended_at)),
        format!("cancelled at: {}", time(view.cancelled_at)),
        format!("removed at: {}", time(view.removed_at)),
        format!("purge not before: {}", time(view.purge_not_before)),
        format!(
            "archive: {}",
            view.archive
                .map_or_else(|| "-".to_owned(), |id| id.to_hex())
        ),
    ]
}

#[cfg(test)]
mod tests {
    use super::*;

    fn node() -> DidNostr {
        DidNostr::from_hex("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798")
            .expect("key")
    }

    #[test]
    fn e3a_25_the_same_operation_and_flags_give_the_same_bytes() {
        let id: OperationId = "rm-1".parse().expect("id");
        let first = action_body(
            Action::Remove {
                require_archive: false,
            },
            node(),
            &id,
        )
        .expect("body");
        let again = action_body(
            Action::Remove {
                require_archive: false,
            },
            node(),
            &id,
        )
        .expect("body");
        assert_eq!(first, again);
        let required = action_body(
            Action::Remove {
                require_archive: true,
            },
            node(),
            &id,
        )
        .expect("body");
        assert_ne!(first, required);
        assert!(String::from_utf8(required)
            .expect("utf8")
            .ends_with(r#""require_archive":true}"#));
        let suspend = action_body(Action::Suspend, node(), &id).expect("body");
        assert_eq!(
            String::from_utf8(suspend).expect("utf8"),
            format!(r#"{{"node":"{}","operation_id":"rm-1"}}"#, node())
        );
    }

    #[test]
    fn retries_repeat_the_waiver_flag() {
        assert_eq!(
            Action::Remove {
                require_archive: false
            }
            .retry_flags(),
            " --no-archive"
        );
        assert_eq!(
            Action::Remove {
                require_archive: true
            }
            .retry_flags(),
            ""
        );
        assert_eq!(Action::Suspend.retry_flags(), "");
    }
}