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};
const MEMBERS: &str = "/api/v1/members";
pub const DEFAULT_ENFORCEMENT_WAIT: Duration = Duration::from_secs(330);
const ENFORCEMENT_POLL_INTERVAL: Duration = Duration::from_secs(2);
const MIN_WAIT_READ: Duration = Duration::from_secs(1);
const ARCHIVE_TIMEOUT: Duration = Duration::from_secs(15 * 60);
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";
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";
#[derive(Debug, Clone)]
pub struct SuspendOptions {
pub member: DidNostr,
pub operation_id: Option<String>,
pub confirmation: Confirmation,
pub wait: Option<Duration>,
}
#[derive(Debug, Clone)]
pub struct RemoveOptions {
pub member: DidNostr,
pub operation_id: Option<String>,
pub confirmation: Confirmation,
pub require_archive: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Action {
Suspend,
Resume,
Archive,
Remove { require_archive: bool },
}
impl Action {
fn segment(self) -> &'static str {
match self {
Self::Suspend => "suspend",
Self::Resume => "resume",
Self::Archive => "archive",
Self::Remove { .. } => "remove",
}
}
fn retry_flags(self) -> &'static str {
match self {
Self::Remove {
require_archive: false,
} => " --no-archive",
_ => "",
}
}
}
struct Sent<T> {
operation_id: OperationId,
answer: T,
}
impl Session {
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 {
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)
}
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)
}
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)
}
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)
}
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)
}
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,
})
}
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,
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));
}
}
}
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(),
}),
}
}
fn read_member(
client: &Client,
key: &NostrSecretKey,
member: &DidNostr,
) -> Result<(MemberView, Json), CliError> {
read_member_within(client, key, member, REQUEST_TIMEOUT)
}
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))
}
fn unexpected_state(member: &DidNostr, action: &str, state: MemberState) -> CliError {
CliError::Refused(format!(
"the node reports {member} as {state} after {action}"
))
}
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()
),
}
}
fn time(value: Option<UnixTime>) -> String {
value.map_or_else(|| "-".to_owned(), |t| t.to_string())
}
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(), "");
}
}