use std::path::PathBuf;
use std::process::ExitCode;
use std::time::Duration;
use clap::{Args, Parser, Subcommand};
use stratum_node_cli::{
exit, parse_duration, ApplyOptions, CanonicalOrigin, CliError, Confirmation, ConnectAddress,
ExportOptions, GateTarget, InviteOptions, JoinOptions, LoopbackUrl, Output, OutputFormat,
PutOptions, Session, SetupOptions, WriteCondition, DEFAULT_URL,
};
use stratum_node_core::{DidNostr, InvitationId};
const EXIT_CODES: &str = "\
Exit codes:
0 success; for `status`, the node is ready
1 local failure (key, token or resume file, clock, output)
2 the node could not be reached
3 status: the node is unconfigured
4 status: the node is degraded
5 the node's response does not follow the API contract
6 previewed but not applied: no confirmation (pass --yes)
7 a local check refused the node's answer (claim body, backup manifest,
admission notice, join probe)
8 join: the pod was not provisioned within --wait-secs (rerun to continue)
9 export: written, but entries changed, vanished or were skipped
10 bad_request 11 unauthorized 12 forbidden
13 not_found 14 conflict 15 payload_too_large
16 unsupported_media_type 17 invalid (also an invalid preview)
18 too_many_challenges 19 backup_refused 20 internal
21 unknown server error code 22 request_timeout
23 capacity_exhausted 24 invitation_refused 25 invitations_disabled
26 gate_unavailable 27 too_many_requests 28 misdirected_request
29 method_not_allowed 30 insufficient_storage 31 precondition_failed
32 bad_gateway 33 gateway_timeout
64 invalid command line
Server errors are printed as `code: message`.";
#[derive(Debug, Parser)]
#[command(name = "stratum", version, after_help = EXIT_CODES)]
struct Cli {
#[arg(long, global = true, env = "STRATUM_URL", default_value = DEFAULT_URL)]
url: LoopbackUrl,
#[arg(long, global = true, env = "STRATUM_KEY_FILE", value_name = "FILE")]
key_file: Option<PathBuf>,
#[arg(long, global = true)]
json: bool,
#[command(subcommand)]
command: Command,
}
#[derive(Debug, Subcommand)]
enum Command {
Key {
#[command(subcommand)]
command: KeyCommand,
},
Status,
Config {
#[command(subcommand)]
command: ConfigCommand,
},
Setup(SetupArgs),
SignChallenge {
#[arg(long, value_name = "FILE")]
claim_body_file: PathBuf,
#[arg(long, value_name = "DID")]
expect_node: DidNostr,
},
Audit {
#[command(subcommand)]
command: AuditCommand,
},
Backup {
#[arg(long, value_name = "ID")]
operation_id: Option<String>,
#[arg(long, value_name = "DID")]
expect_node: Option<DidNostr>,
},
Invite {
#[command(subcommand)]
command: InviteCommand,
},
Member {
#[command(subcommand)]
command: MemberCommand,
},
Join(JoinArgs),
Pod {
#[command(subcommand)]
command: PodCommand,
},
Export(ExportArgs),
}
#[derive(Debug, Subcommand)]
enum InviteCommand {
Create {
did: DidNostr,
#[arg(long, value_name = "DURATION", value_parser = parse_duration)]
expires_in: Option<Duration>,
#[arg(long, value_name = "HOST:PORT")]
connect: Option<ConnectAddress>,
#[arg(long, value_name = "ID")]
operation_id: Option<String>,
#[arg(long, value_name = "DID")]
expect_node: Option<DidNostr>,
},
List,
Revoke {
invitation: InvitationId,
#[arg(long, value_name = "ID")]
operation_id: Option<String>,
},
}
#[derive(Debug, Subcommand)]
enum MemberCommand {
List,
Repair(MemberArgs),
Cancel(MemberArgs),
}
#[derive(Debug, Args)]
struct MemberArgs {
did: DidNostr,
#[arg(long, value_name = "ID")]
operation_id: Option<String>,
#[arg(long, short = 'y')]
yes: bool,
}
#[derive(Debug, Args)]
struct GateArgs {
#[arg(long, env = "STRATUM_ORIGIN", value_name = "ORIGIN")]
origin: CanonicalOrigin,
#[arg(long, env = "STRATUM_CONNECT", value_name = "HOST:PORT")]
connect: Option<ConnectAddress>,
}
impl GateArgs {
fn target(self) -> Result<GateTarget, CliError> {
GateTarget::new(self.origin, self.connect)
}
}
#[derive(Debug, Args)]
struct JoinArgs {
#[arg(long, value_name = "ID")]
invitation: InvitationId,
#[arg(long, value_name = "DID")]
node: DidNostr,
#[command(flatten)]
gate: GateArgs,
#[arg(long, value_name = "SECONDS", default_value_t = 120)]
wait_secs: u64,
#[arg(long, short = 'y')]
yes: bool,
}
#[derive(Debug, Subcommand)]
enum PodCommand {
Ls {
#[arg(default_value = "")]
path: String,
#[command(flatten)]
gate: GateArgs,
},
Get {
path: String,
#[arg(short = 'o', long = "output", value_name = "FILE")]
output: Option<PathBuf>,
#[command(flatten)]
gate: GateArgs,
},
Put(PutArgs),
Rm(RmArgs),
Acl {
#[command(subcommand)]
command: AclCommand,
},
}
#[derive(Debug, Args)]
struct RmArgs {
path: String,
#[command(flatten)]
gate: GateArgs,
#[arg(long, short = 'y')]
yes: bool,
}
#[derive(Debug, Subcommand)]
enum AclCommand {
Get {
#[arg(default_value = "")]
path: String,
#[arg(short = 'o', long = "output", value_name = "FILE")]
output: Option<PathBuf>,
#[command(flatten)]
gate: GateArgs,
},
Put(PutArgs),
}
#[derive(Debug, Args)]
struct PutArgs {
path: String,
file: PathBuf,
#[arg(long, value_name = "TYPE")]
content_type: Option<String>,
#[arg(long, value_name = "ETAG", conflicts_with = "create_only")]
if_match: Option<String>,
#[arg(long)]
create_only: bool,
#[command(flatten)]
gate: GateArgs,
}
impl PutArgs {
fn into_parts(self) -> (PutOptions, GateArgs) {
let condition = match (self.if_match, self.create_only) {
(Some(etag), _) => WriteCondition::IfMatch(etag),
(None, true) => WriteCondition::CreateOnly,
(None, false) => WriteCondition::Always,
};
(
PutOptions {
path: self.path,
file: self.file,
content_type: self.content_type,
condition,
},
self.gate,
)
}
}
#[derive(Debug, Args)]
struct ExportArgs {
#[arg(short = 'o', long = "output", value_name = "ARCHIVE")]
output: PathBuf,
#[arg(long)]
force: bool,
#[command(flatten)]
gate: GateArgs,
}
#[derive(Debug, Subcommand)]
enum KeyCommand {
Generate {
#[arg(long, value_name = "FILE")]
out: PathBuf,
},
Show,
}
#[derive(Debug, Subcommand)]
enum ConfigCommand {
Schema,
Show,
Preview(PreviewArgs),
Apply(ApplyArgs),
}
#[derive(Debug, Subcommand)]
enum AuditCommand {
Checkpoint,
}
#[derive(Debug, Args)]
struct ChangeArgs {
#[arg(long = "set", value_name = "PATH=VALUE")]
sets: Vec<String>,
#[arg(long, value_name = "N")]
base_revision: Option<u64>,
}
#[derive(Debug, Args)]
struct PreviewArgs {
#[command(flatten)]
changes: ChangeArgs,
}
#[derive(Debug, Args)]
struct ApplyArgs {
#[command(flatten)]
changes: ChangeArgs,
#[arg(long, value_name = "ID")]
operation_id: Option<String>,
#[arg(long, short = 'y')]
yes: bool,
}
#[derive(Debug, Args)]
struct SetupArgs {
#[arg(long, value_name = "FILE")]
token_file: PathBuf,
#[arg(long = "set", value_name = "PATH=VALUE")]
sets: Vec<String>,
#[arg(long, value_name = "DID")]
expect_node: Option<DidNostr>,
#[arg(long)]
show_text: bool,
#[arg(long, value_name = "FILE")]
resume_file: Option<PathBuf>,
#[arg(long, short = 'y')]
yes: bool,
}
trait YesFlag {
fn yes(&self) -> bool;
fn confirmation(&self) -> Confirmation {
if self.yes() {
Confirmation::Assumed
} else {
Confirmation::Prompt
}
}
}
impl YesFlag for ApplyArgs {
fn yes(&self) -> bool {
self.yes
}
}
impl YesFlag for SetupArgs {
fn yes(&self) -> bool {
self.yes
}
}
impl YesFlag for MemberArgs {
fn yes(&self) -> bool {
self.yes
}
}
impl YesFlag for JoinArgs {
fn yes(&self) -> bool {
self.yes
}
}
impl YesFlag for RmArgs {
fn yes(&self) -> bool {
self.yes
}
}
fn main() -> ExitCode {
let cli = match Cli::try_parse() {
Ok(cli) => cli,
Err(err) => {
let code = if err.use_stderr() {
exit::USAGE
} else {
exit::OK
};
let _printed = err.print();
return ExitCode::from(code);
}
};
let output = Output::new(if cli.json {
OutputFormat::Json
} else {
OutputFormat::Human
});
let session = Session::new(cli.url, cli.key_file, output);
let result = match cli.command {
Command::Key {
command: KeyCommand::Generate { out },
} => session.key_generate(&out),
Command::Key {
command: KeyCommand::Show,
} => session.key_show(),
Command::Status => session.status(),
Command::Config { command } => match command {
ConfigCommand::Schema => session.config_schema(),
ConfigCommand::Show => session.config_show(),
ConfigCommand::Preview(args) => {
session.config_preview(&args.changes.sets, args.changes.base_revision)
}
ConfigCommand::Apply(args) => session.config_apply(&ApplyOptions {
confirmation: args.confirmation(),
sets: args.changes.sets,
base_revision: args.changes.base_revision,
operation_id: args.operation_id,
}),
},
Command::Setup(args) => session.setup(&SetupOptions {
confirmation: args.confirmation(),
token_file: args.token_file,
sets: args.sets,
resume_file: args.resume_file,
expect_node: args.expect_node,
show_text: args.show_text,
}),
Command::SignChallenge {
claim_body_file,
expect_node,
} => session.sign_challenge(&claim_body_file, &expect_node),
Command::Audit {
command: AuditCommand::Checkpoint,
} => session.audit_checkpoint(),
Command::Backup {
operation_id,
expect_node,
} => session.backup(operation_id.as_deref(), expect_node.as_ref()),
Command::Invite { command } => run_invite(&session, command),
Command::Member { command } => run_member(&session, command),
Command::Join(args) => {
let confirmation = args.confirmation();
args.gate.target().and_then(|target| {
session.join(
&target,
&JoinOptions {
invitation: args.invitation,
node: args.node,
wait: Duration::from_secs(args.wait_secs),
confirmation,
},
)
})
}
Command::Pod { command } => run_pod(&session, command),
Command::Export(args) => args.gate.target().and_then(|target| {
session.export(
&target,
&ExportOptions {
output: args.output,
force: args.force,
},
)
}),
};
match result {
Ok(code) => ExitCode::from(code),
Err(err) => {
output.error(&err);
ExitCode::from(err.exit_code())
}
}
}
fn run_invite(session: &Session, command: InviteCommand) -> Result<u8, CliError> {
match command {
InviteCommand::Create {
did,
expires_in,
connect,
operation_id,
expect_node,
} => session.invite_create(&InviteOptions {
subject: did,
expires_in,
operation_id,
expect_node,
gate: connect,
}),
InviteCommand::List => session.invite_list(),
InviteCommand::Revoke {
invitation,
operation_id,
} => session.invite_revoke(&invitation, operation_id.as_deref()),
}
}
fn run_member(session: &Session, command: MemberCommand) -> Result<u8, CliError> {
match command {
MemberCommand::List => session.member_list(),
MemberCommand::Repair(args) => {
session.member_repair(&args.did, args.operation_id.as_deref(), args.confirmation())
}
MemberCommand::Cancel(args) => {
session.member_cancel(&args.did, args.operation_id.as_deref(), args.confirmation())
}
}
}
fn run_pod(session: &Session, command: PodCommand) -> Result<u8, CliError> {
match command {
PodCommand::Ls { path, gate } => session.pod_ls(&gate.target()?, &path),
PodCommand::Get { path, output, gate } => {
session.pod_get(&gate.target()?, &path, output.as_deref())
}
PodCommand::Put(args) => {
let (options, gate) = args.into_parts();
session.pod_put(&gate.target()?, &options)
}
PodCommand::Rm(args) => {
let confirmation = args.confirmation();
session.pod_rm(&args.gate.target()?, &args.path, confirmation)
}
PodCommand::Acl {
command: AclCommand::Get { path, output, gate },
} => session.pod_acl_get(&gate.target()?, &path, output.as_deref()),
PodCommand::Acl {
command: AclCommand::Put(args),
} => {
let (options, gate) = args.into_parts();
session.pod_acl_put(&gate.target()?, &options)
}
}
}