~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0
1011 lines · 35.8 KB Raw History
//! The CLI: each method the server serves as a command, `pds <group> <command>
//! [flags]`, calling the server at `PDS_URL` over XRPC (`spec/COMMANDS.md`);
//! the routes no lexicon makes a command of (`OWN`): the admin's reads,
//! `pds admin logs` and `pds admin stats`, calling `/xrpc/_logs` and
//! `/xrpc/_stats`, the account's OAuth routes, the group `oauth`, and its
//! passkey routes, the group `passkey`; and `pds xrpc`, any call by its
//! name (`xrpc`).
//!
//! Exit statuses: 0 for the method's answer, 1 for an error it answers, 2 for
//! a usage error (no call made), 3 for a server that cannot be reached.

#![forbid(unsafe_code)]

mod xrpc;

use pds_lexicon::{Arg, JSON, Kind, Method, Type};
use serde_json::{Map, Value as Json, json};
use std::io::{Read, Write};
use std::sync::LazyLock;

const USAGE: u8 = 2;
const UNREACHABLE: u8 = 3;

/// Why a command stopped short of its method's answer.
enum Stop {
    /// A usage error, saying what was wrong.
    Usage(String),
    /// The server could not be reached, and why.
    Unreachable(String),
}

/// Run the CLI with its arguments (without the program's name); answers its exit status.
pub fn run(args: &[String]) -> i32 {
    let code = match command(args) {
        Ok(code) => code,
        Err(Stop::Usage(why)) => {
            eprintln!("pds: {why}");
            USAGE
        }
        Err(Stop::Unreachable(why)) => {
            eprintln!("pds: {why}");
            UNREACHABLE
        }
    };
    i32::from(code)
}

fn is_help(a: &str) -> bool {
    a == "--help" || a == "-h"
}

fn usage<T>(why: impl Into<String>) -> Result<T, Stop> {
    Err(Stop::Usage(why.into()))
}

fn command(args: &[String]) -> Result<u8, Stop> {
    let Some(group) = args.first() else {
        print!("{}", top_help());
        return Ok(0);
    };
    if is_help(group) {
        print!("{}", top_help());
        return Ok(0);
    }
    if group == xrpc::COMMAND {
        return xrpc::run(&args[1..]);
    }
    if !groups().contains(&group.as_str()) {
        return usage(format!("no group {group}; `pds --help` lists them"));
    }
    let Some(name) = args.get(1) else {
        return usage(format!(
            "pds {group} needs a command\n\n{}",
            group_help(group)
        ));
    };
    if is_help(name) {
        print!("{}", group_help(group));
        return Ok(0);
    }
    if let Some(r) = OWN.iter().find(|r| r.group == group && r.command == name) {
        let flags: Vec<&Arg> = r.args.iter().collect();
        let Some(args) = parse_flags(r.group, r.command, &flags, &args[2..])? else {
            print!("{}", help(r.group, r.command, Some(r.description), &flags));
            return Ok(0);
        };
        return call_own(r, args);
    }
    let Some(m) = pds_lexicon::by_command(group, name) else {
        return usage(format!(
            "pds {group} has no command {name}; `pds {group} --help` lists them"
        ));
    };
    let Some(args) = parse(m, &args[2..])? else {
        print!("{}", command_help(m));
        return Ok(0);
    };
    call(m, args)
}

/// The group of the admin's reads, after the commands of
/// `com.atproto.admin`'s methods.
const ADMIN: &str = "admin";

/// The group of the account's OAuth routes, after every other lexicon's.
const OAUTH: &str = "oauth";

/// The group of the account's passkey routes, after `oauth`.
const PASSKEY: &str = "passkey";

/// Every group, in the order listed: the lexicons', then `oauth`, then `passkey`.
fn groups() -> Vec<&'static str> {
    let mut groups = pds_lexicon::groups();
    groups.push(OAUTH);
    groups.push(PASSKEY);
    groups
}

/// A command of no lexicon's (`spec/COMMANDS.md`, "The admin's reads",
/// "The account's OAuth sessions" and "The account's passkeys"): its group
/// and name, its route, whether it is a `POST` of its flags as JSON rather
/// than a `GET` with them as the query, its description and its flags.
struct Own {
    group: &'static str,
    command: &'static str,
    route: &'static str,
    post: bool,
    description: &'static str,
    args: Vec<Arg>,
}

static OWN: LazyLock<[Own; 9]> = LazyLock::new(|| {
    let arg = |name: &str, ty: Type, required: bool, description: &str, schema: Json| Arg {
        name: name.into(),
        ty,
        required,
        description: Some(description.into()),
        def: schema.clone(),
        schema,
    };
    let string = || json!({ "type": "string" });
    let get = |group, command, route, description| Own {
        group,
        command,
        route,
        post: false,
        description,
        args: vec![],
    };
    let post = |group, command, route, description, flag: Arg| Own {
        group,
        command,
        route,
        post: true,
        description,
        args: vec![flag],
    };
    let id = |description: &str| arg("id", Type::String, true, description, string());
    [
        Own {
            args: vec![
                arg(
                    "trace",
                    Type::String,
                    false,
                    "Lines of this trace id.",
                    string(),
                ),
                arg("msg", Type::String, false, "Lines of this msg.", string()),
                arg(
                    "method",
                    Type::String,
                    false,
                    "Lines of this route, as com.atproto.repo.createRecord or /oauth/token.",
                    string(),
                ),
                arg(
                    "level",
                    Type::String,
                    false,
                    "Lines at this level or above: debug, info, warn or error.",
                    json!({ "type": "string", "enum": ["debug", "info", "warn", "error"] }),
                ),
                arg(
                    "minMs",
                    Type::Integer,
                    false,
                    "Lines with an ms of this many milliseconds or more.",
                    json!({ "type": "integer", "minimum": 0 }),
                ),
                arg(
                    "limit",
                    Type::Integer,
                    false,
                    "How many, the last of those matched: 1 to 500, 100 if not given.",
                    json!({ "type": "integer", "minimum": 1, "maximum": 500 }),
                ),
            ],
            ..get(
                ADMIN,
                "logs",
                "_logs",
                "As the admin, the lines the server logged and kept in PDS_LOG_DIR, oldest first: the last of those of a trace, a message, a route, a level and above, or a time. Needs the admin's Basic auth.",
            )
        },
        get(
            ADMIN,
            "stats",
            "_stats",
            "As the admin, what the server counted since it started: its requests by route and status with their mean times, the requests it made, its syncs, its accounts and its firehose. Needs the admin's Basic auth.",
        ),
        get(
            OAUTH,
            "sessions",
            "_oauthSessions",
            "The OAuth sessions of your account, the apps you signed in to, newest first: each with its id, client, issuer (atproto or mcp), scope, and when it started, was last refreshed and ends. Needs your account's password session.",
        ),
        post(
            OAUTH,
            "revoke-session",
            "_oauthRevokeSession",
            "End one of your account's OAuth sessions by its id, as oauth_sessions lists it: the app is signed out at once. Needs your account's password session.",
            id("The session's id, as `pds oauth sessions` lists it."),
        ),
        get(
            OAUTH,
            "devices",
            "_oauthDevices",
            "The browsers your account is signed in on through the OAuth sign-in page, newest sign-in first: each with its id, when it signed in, and its user agent and IP address. Needs your account's password session.",
        ),
        post(
            OAUTH,
            "revoke-device",
            "_oauthRevokeDevice",
            "Sign your account out of one browser by its id, as oauth_devices lists it. Its apps' sessions stay: end those with oauth_revoke_session. Needs your account's password session.",
            id("The browser's id, as `pds oauth devices` lists it."),
        ),
        get(
            PASSKEY,
            "list",
            "_passkeyList",
            "The passkeys of your account, newest first: each with its id, name, when it was added and last signed in, and whether it is backed up. Needs your account's password session.",
        ),
        post(
            PASSKEY,
            "add",
            "_passkeyAdd",
            "A link to open in a browser within 15 minutes, which adds a passkey of this name to your account: it then signs in on the OAuth sign-in page with no password. A new link ends the last. Needs your account's password session.",
            arg(
                "name",
                Type::String,
                true,
                "The passkey's name, 1 to 64 characters, as `pds passkey list` will list it.",
                json!({ "type": "string", "minLength": 1, "maxLength": 64 }),
            ),
        ),
        post(
            PASSKEY,
            "remove",
            "_passkeyRemove",
            "Remove one of your account's passkeys by its id, as passkey_list lists it: it no longer signs in. Needs your account's password session.",
            id("The passkey's id, as `pds passkey list` lists it."),
        ),
    ]
});

fn top_help() -> String {
    let mut out = String::from(
        "pds: an atproto PDS, and a command for each of its methods.\n\n\
         Usage:\n  \
         pds serve                       run the server, configured by its environment\n  \
         pds <group> <command> [flags]   call a method of the server at PDS_URL, with the token PDS_TOKEN if set\n  \
         pds <group> --help              list a group's commands\n  \
         pds <group> <command> --help    list a command's flags\n  \
         pds xrpc <kind> <name> [args]   call any method or route of the server by its name; `pds xrpc --help` says how\n\n\
         Groups:\n",
    );
    for g in groups() {
        out.push_str(&format!("  {g}\n"));
        for (name, description) in listed(g) {
            out.push_str(&format!("    {name:<20} {description}\n"));
        }
    }
    out
}

/// A group's commands, each with its description: its methods', then its
/// commands of no lexicon's (`OWN`).
fn listed(group: &str) -> Vec<(String, &'static str)> {
    let methods = pds_lexicon::methods()
        .iter()
        .filter(|m| m.group == group)
        .filter_map(|m| Some((m.command()?, m.description.as_deref().unwrap_or(""))));
    let own = OWN
        .iter()
        .filter(|r| r.group == group)
        .map(|r| (r.command.to_string(), r.description));
    methods.chain(own).collect()
}

fn group_help(group: &str) -> String {
    let mut out = format!("Usage: pds {group} <command> [flags]\n\nCommands:\n");
    for (name, description) in listed(group) {
        out.push_str(&format!("  {name:<20} {description}\n"));
    }
    out
}

/// `--encoding`, the `Content-Type` of a command whose method takes its body
/// as it is, of any type (`uploadBlob`), which it reads from standard input.
static ENCODING: LazyLock<Arg> = LazyLock::new(|| Arg {
    name: "encoding".into(),
    ty: Type::String,
    required: true,
    description: Some("The Content-Type of the body, which is standard input.".into()),
    schema: json!({ "type": "string" }),
    def: json!({ "type": "string" }),
});

/// The one type a method's raw body may be, as `importSpaceMeta`'s
/// `application/vnd.dasl.star`; None for one of any type, as `uploadBlob`'s `*/*`.
fn fixed_encoding(m: &Method) -> Option<&str> {
    m.input
        .as_deref()
        .filter(|i| m.raw_input() && !i.contains('*'))
}

/// A command's flags: its method's arguments, and `--encoding` for one whose body is standard input of any type.
fn flags_of(m: &Method) -> impl Iterator<Item = &Arg> {
    m.args
        .iter()
        .chain((m.raw_input() && fixed_encoding(m).is_none()).then(|| &*ENCODING))
}

fn command_help(m: &Method) -> String {
    let flags: Vec<&Arg> = flags_of(m).collect();
    help(
        &m.group,
        &m.command().unwrap_or_default(),
        m.description.as_deref(),
        &flags,
    )
}

/// A command's help: its usage, its description, and its flags.
fn help(group: &str, command: &str, description: Option<&str>, flags: &[&Arg]) -> String {
    let mut out = format!("Usage: pds {group} {command} [flags]\n");
    if let Some(d) = description {
        out.push_str(&format!("\n{d}\n"));
    }
    if flags.is_empty() {
        out.push_str("\nIt takes no flags.\n");
        return out;
    }
    out.push_str("\nFlags:\n");
    for a in flags {
        let flag = format!("--{} {}", a.flag(), a.ty.placeholder());
        let mut about = String::new();
        if a.needed() {
            about.push_str("(required) ");
        }
        about.push_str(a.description.as_deref().unwrap_or(""));
        if a.names_account() {
            let left_out = "Left out with PDS_TOKEN set, the token's account's DID.";
            about.push_str(&if about.is_empty() {
                left_out.to_string()
            } else {
                format!(" {left_out}")
            });
        }
        out.push_str(&format!("  {flag:<32} {}\n", about.trim_end()));
    }
    out.push_str("\nA <json> flag takes JSON; given `-`, it reads the JSON from standard input.\n");
    out
}

/// A command's flags as its method's arguments, or None if they ask for help.
fn parse(m: &Method, flags: &[String]) -> Result<Option<Map<String, Json>>, Stop> {
    let args: Vec<&Arg> = flags_of(m).collect();
    parse_flags(&m.group, &m.command().unwrap_or_default(), &args, flags)
}

/// The flags `pds <group> <command>` was given, as the arguments `args`
/// names, or None if they ask for help.
fn parse_flags(
    group: &str,
    command: &str,
    args: &[&Arg],
    flags: &[String],
) -> Result<Option<Map<String, Json>>, Stop> {
    let mut values = Map::new();
    let mut stdin_read = false;
    let mut i = 0;
    while i < flags.len() {
        let a = &flags[i];
        i += 1;
        if is_help(a) {
            return Ok(None);
        }
        let Some(flag) = a.strip_prefix("--") else {
            return usage(format!("unexpected argument {a:?}: flags are --name value"));
        };
        let (name, inline) = match flag.split_once('=') {
            Some((n, v)) => (n, Some(v.to_string())),
            None => (flag, None),
        };
        let Some(arg) = args.iter().find(|x| x.flag() == name) else {
            return usage(format!("pds {group} {command} takes no flag --{name}"));
        };
        if values.contains_key(&arg.name) {
            return usage(format!("--{name} is given twice"));
        }
        let text = match inline {
            Some(v) => Some(v),
            None if arg.ty == Type::Boolean => match flags.get(i).map(String::as_str) {
                Some(v @ ("true" | "false")) => {
                    i += 1;
                    Some(v.to_string())
                }
                _ => None,
            },
            None => match flags.get(i) {
                Some(v) => {
                    i += 1;
                    Some(v.clone())
                }
                None => return usage(format!("--{name} needs a value")),
            },
        };
        let value = value(arg, text, &mut stdin_read)?;
        values.insert(arg.name.clone(), value);
    }
    let missing: Vec<String> = args
        .iter()
        .filter(|a| a.needed() && !values.contains_key(&a.name))
        .map(|a| format!("--{}", a.flag()))
        .collect();
    if !missing.is_empty() {
        return usage(format!(
            "pds {group} {command} needs {}",
            missing.join(", ")
        ));
    }
    Ok(Some(values))
}

/// A flag's value, from its text (None for a bare boolean flag).
fn value(arg: &Arg, text: Option<String>, stdin_read: &mut bool) -> Result<Json, Stop> {
    let flag = arg.flag();
    let Some(text) = text else {
        return Ok(Json::Bool(true));
    };
    match arg.ty {
        Type::String => Ok(Json::String(text)),
        Type::Integer => match text.parse::<i64>() {
            Ok(n)
                if text
                    .trim_start_matches('-')
                    .bytes()
                    .all(|b| b.is_ascii_digit()) =>
            {
                Ok(json!(n))
            }
            _ => usage(format!("--{flag} takes an integer, not {text:?}")),
        },
        Type::Boolean => match text.as_str() {
            "true" => Ok(Json::Bool(true)),
            "false" => Ok(Json::Bool(false)),
            _ => usage(format!("--{flag} takes true or false, not {text:?}")),
        },
        Type::Array | Type::Object | Type::Unknown => {
            let text = if text == "-" {
                if *stdin_read {
                    return usage("only one flag can read standard input");
                }
                *stdin_read = true;
                let mut s = String::new();
                if let Err(e) = std::io::stdin().read_to_string(&mut s) {
                    return usage(format!("--{flag}: cannot read standard input: {e}"));
                }
                s
            } else {
                text
            };
            match serde_json::from_str::<Json>(&text) {
                Ok(Json::Null) => usage(format!("--{flag} cannot be null")),
                Ok(v) => Ok(v),
                Err(e) => usage(format!("--{flag} takes JSON: {e}")),
            }
        }
    }
}

/// A query parameter's text, as XRPC takes it.
fn param_text(v: &Json) -> String {
    match v {
        Json::String(s) => s.clone(),
        other => other.to_string(),
    }
}

struct Server {
    url: String,
    token: Option<String>,
    /// The admin's password, sent as `Basic` auth when there is no token.
    admin: Option<String>,
    http: reqwest::blocking::Client,
}

impl Server {
    /// The server `PDS_URL` names, called with `PDS_TOKEN` if set, else
    /// with the admin's password if `PDS_ADMIN_PASSWORD` is set.
    fn from_env() -> Result<Server, Stop> {
        let Ok(url) = std::env::var("PDS_URL") else {
            return Err(Stop::Unreachable(
                "PDS_URL is not set: it is the server's URL".into(),
            ));
        };
        let http = reqwest::blocking::Client::builder()
            .no_proxy()
            .build()
            .map_err(|e| Stop::Unreachable(e.to_string()))?;
        Ok(Server {
            url: url.trim_end_matches('/').to_string(),
            token: std::env::var("PDS_TOKEN").ok().filter(|t| !t.is_empty()),
            admin: std::env::var("PDS_ADMIN_PASSWORD").ok(),
            http,
        })
    }

    /// Call a method: a query with `args` as its parameters, a procedure with
    /// them as its JSON input, or with `raw`, a type and bytes, as its body.
    fn send(
        &self,
        m: &Method,
        args: &Map<String, Json>,
        raw: Option<(String, Vec<u8>)>,
    ) -> Result<reqwest::blocking::Response, Stop> {
        let url = format!("{}/xrpc/{}", self.url, m.nsid);
        let req = match (m.kind, raw) {
            (Kind::Procedure, Some((encoding, body))) => self
                .http
                .post(&url)
                .header("content-type", encoding)
                .body(body),
            // A procedure that takes no input is sent none.
            (Kind::Procedure, None) if m.input.is_none() && args.is_empty() => self.http.post(&url),
            (Kind::Procedure, None) => self
                .http
                .post(&url)
                .header("content-type", JSON)
                .body(Json::Object(args.clone()).to_string()),
            _ => return self.get(&url, args),
        };
        self.with_auth(req)
    }

    /// `GET` of `url`, with `args` as its query's parameters.
    fn get(
        &self,
        url: &str,
        args: &Map<String, Json>,
    ) -> Result<reqwest::blocking::Response, Stop> {
        let mut params = Vec::new();
        for (k, v) in args {
            match v {
                Json::Array(items) => {
                    params.extend(items.iter().map(|i| (k.as_str(), param_text(i))))
                }
                v => params.push((k.as_str(), param_text(v))),
            }
        }
        self.with_auth(self.http.get(url).query(&params))
    }

    /// Send `req` with the token, or else the admin's `Basic` auth.
    fn with_auth(
        &self,
        req: reqwest::blocking::RequestBuilder,
    ) -> Result<reqwest::blocking::Response, Stop> {
        self.sent(self.authorized(req))
    }

    /// `req` with the token, or else the admin's `Basic` auth, if either is set.
    fn authorized(
        &self,
        req: reqwest::blocking::RequestBuilder,
    ) -> reqwest::blocking::RequestBuilder {
        if let Some(t) = &self.token {
            req.bearer_auth(t)
        } else if let Some(password) = &self.admin {
            req.basic_auth("admin", Some(password))
        } else {
            req
        }
    }

    /// Send `req`, its answer or why the server could not be reached.
    fn sent(
        &self,
        req: reqwest::blocking::RequestBuilder,
    ) -> Result<reqwest::blocking::Response, Stop> {
        req.send()
            .map_err(|e| Stop::Unreachable(format!("cannot reach {}: {e}", self.url)))
    }

    /// The token's account's DID, as `getSession` answers it; None for a
    /// token it does not answer for.
    fn account(&self) -> Result<Option<String>, Stop> {
        let get_session =
            pds_lexicon::method("com.atproto.server.getSession").expect("getSession's lexicon");
        let (status, body) = answer(self.send(get_session, &Map::new(), None)?, &self.url)?;
        Ok(body["did"]
            .as_str()
            .filter(|_| status == 200)
            .map(str::to_string))
    }
}

/// A JSON answer's status and body.
fn answer(res: reqwest::blocking::Response, url: &str) -> Result<(u16, Json), Stop> {
    let status = res.status().as_u16();
    let bytes = res
        .bytes()
        .map_err(|e| Stop::Unreachable(format!("cannot read the answer of {url}: {e}")))?;
    Ok((
        status,
        serde_json::from_slice(&bytes)
            .unwrap_or_else(|_| Json::String(String::from_utf8_lossy(&bytes).into_owned())),
    ))
}

fn print_line(v: &Json) {
    let mut out = std::io::stdout().lock();
    let _ = writeln!(out, "{v}");
}

/// Print an error the server answered, as `{status, error, message}`.
fn print_error(status: u16, body: &Json) -> u8 {
    let reason = reqwest::StatusCode::from_u16(status)
        .ok()
        .and_then(|s| s.canonical_reason())
        .unwrap_or("Error");
    let error = body["error"].as_str().unwrap_or(reason);
    let message = match (&body["message"], body) {
        (Json::String(m), _) => m.clone(),
        (_, Json::String(text)) => text.clone(),
        _ => reason.to_string(),
    };
    print_line(&json!({ "status": status, "error": error, "message": message }));
    1
}

fn call(m: &Method, mut args: Map<String, Json>) -> Result<u8, Stop> {
    let token = std::env::var("PDS_TOKEN").ok().filter(|t| !t.is_empty());
    // A `repo` or `did` left out is the token's account's; with no token, it
    // is as required as the lexicon says.
    let left_out: Vec<&Arg> = m
        .args
        .iter()
        .filter(|a| a.names_account() && !args.contains_key(&a.name))
        .collect();
    if token.is_none() && !left_out.is_empty() {
        let missing: Vec<String> = left_out.iter().map(|a| format!("--{}", a.flag())).collect();
        return usage(format!(
            "pds {} {} needs {}, or PDS_TOKEN for its account's",
            m.group,
            m.command().unwrap_or_default(),
            missing.join(", ")
        ));
    }
    let server = Server::from_env()?;
    // A token getSession does not answer for leaves them out, for the method to answer it.
    if server.token.is_some()
        && !left_out.is_empty()
        && let Some(did) = server.account()?
    {
        for a in left_out {
            args.insert(a.name.clone(), json!(did));
        }
    }
    // A raw body is standard input, sent as its method's one type, or as `--encoding` says.
    let given = if m.raw_input() {
        args.remove("encoding")
    } else {
        None
    };
    let encoding = match (fixed_encoding(m), given) {
        (Some(fixed), _) => Some(fixed.to_string()),
        (None, Some(Json::String(encoding))) => Some(encoding),
        _ => None,
    };
    let raw = match encoding {
        Some(encoding) => {
            let mut body = Vec::new();
            if let Err(e) = std::io::stdin().read_to_end(&mut body) {
                return usage(format!("cannot read standard input: {e}"));
            }
            Some((encoding, body))
        }
        None => None,
    };
    let mut res = server.send(m, &args, raw)?;
    // A method that answers nothing prints `{}`.
    if res.status().is_success() && m.output.is_none() {
        print_line(&json!({}));
        return Ok(0);
    }
    if !res.status().is_success() || m.output.as_deref() == Some(JSON) {
        let (status, body) = answer(res, &server.url)?;
        if !(200..300).contains(&status) {
            return Ok(print_error(status, &body));
        }
        print_line(&body);
        return Ok(0);
    }
    // Bytes, as getRepo's and getBlob's: written as they come.
    let mut out = std::io::stdout().lock();
    res.copy_to(&mut out)
        .map_err(|e| Stop::Unreachable(format!("cannot read the answer of {}: {e}", server.url)))?;
    let _ = out.flush();
    Ok(0)
}

/// Call one of the commands of no lexicon's: its JSON answer, printed as
/// the server sent it, one line (`_logs`' lines each as the server wrote
/// it); or its error, printed as a method's.
fn call_own(r: &Own, args: Map<String, Json>) -> Result<u8, Stop> {
    let server = Server::from_env()?;
    let url = format!("{}/xrpc/{}", server.url, r.route);
    let res = if r.post {
        let req = server
            .http
            .post(&url)
            .header("content-type", JSON)
            .body(Json::Object(args).to_string());
        server.with_auth(req)?
    } else {
        server.get(&url, &args)?
    };
    let status = res.status().as_u16();
    let text = res
        .text()
        .map_err(|e| Stop::Unreachable(format!("cannot read the answer of {}: {e}", server.url)))?;
    match serde_json::from_str::<Json>(&text) {
        Ok(_) if (200..300).contains(&status) => {
            let mut out = std::io::stdout().lock();
            let _ = writeln!(out, "{}", text.trim());
            Ok(0)
        }
        Ok(body) => Ok(print_error(status, &body)),
        Err(_) => Ok(print_error(status, &Json::String(text))),
    }
}

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

    fn flags(nsid: &str, argv: &[&str]) -> Result<Option<Map<String, Json>>, String> {
        let argv: Vec<String> = argv.iter().map(|a| a.to_string()).collect();
        parse(pds_lexicon::method(nsid).unwrap(), &argv).map_err(|e| match e {
            Stop::Usage(why) | Stop::Unreachable(why) => why,
        })
    }

    #[test]
    fn flag_values() {
        let list = "com.atproto.repo.listRecords";
        let got = flags(
            list,
            &["--collection", "a.b.c", "--limit", "5", "--reverse"],
        )
        .unwrap()
        .unwrap();
        assert_eq!(
            Json::Object(got),
            json!({ "collection": "a.b.c", "limit": 5, "reverse": true })
        );
        let got = flags(
            list,
            &[
                "--collection=a.b.c",
                "--reverse",
                "false",
                "--cursor",
                "--x",
            ],
        )
        .unwrap()
        .unwrap();
        assert_eq!(
            Json::Object(got),
            json!({ "collection": "a.b.c", "reverse": false, "cursor": "--x" })
        );
        let put = flags(
            "com.atproto.repo.putRecord",
            &[
                "--collection",
                "a.b.c",
                "--rkey",
                "-",
                "--record",
                r#"{"n":1}"#,
            ],
        )
        .unwrap()
        .unwrap();
        assert_eq!(
            Json::Object(put),
            json!({ "collection": "a.b.c", "rkey": "-", "record": { "n": 1 } })
        );
        assert_eq!(
            flags(list, &["--collection", "a.b.c", "--help"]).unwrap(),
            None
        );
    }

    #[test]
    fn usage_errors() {
        let list = "com.atproto.repo.listRecords";
        for argv in [
            &["--collection", "a.b.c", "--no-such-flag", "x"][..],
            &["--limit", "5"],
            &["--collection", "a.b.c", "--limit", "five"],
            &["--collection", "a.b.c", "--limit", "1.5"],
            &["--collection", "a.b.c", "--reverse=yes"],
            &["--collection", "a.b.c", "--collection", "d.e.f"],
            &["--collection"],
            &["a.b.c"],
        ] {
            assert!(flags(list, argv).is_err(), "{argv:?}");
        }
        let create = "com.atproto.repo.createRecord";
        assert!(flags(create, &["--collection", "a.b.c", "--record", "null"]).is_err());
        assert!(flags(create, &["--collection", "a.b.c", "--record", "{"]).is_err());
    }

    /// `upload-blob` takes its body from standard input, its type from
    /// `--encoding`, which it needs; `get-blob` takes its parameters.
    #[test]
    fn blob_commands() {
        let upload = "com.atproto.repo.uploadBlob";
        assert_eq!(
            Json::Object(
                flags(upload, &["--encoding", "image/png"])
                    .unwrap()
                    .unwrap()
            ),
            json!({ "encoding": "image/png" })
        );
        assert!(flags(upload, &[]).is_err());
        assert!(flags(upload, &["--encoding", "a/b", "--repo", "x"]).is_err());
        let help = command_help(pds_lexicon::method(upload).unwrap());
        assert!(help.contains("--encoding <string>"), "{help}");
        let got = flags(
            "com.atproto.sync.getBlob",
            &["--did", "did:plc:x", "--cid", "bafy"],
        )
        .unwrap()
        .unwrap();
        assert_eq!(
            Json::Object(got),
            json!({ "did": "did:plc:x", "cid": "bafy" })
        );
        assert!(flags("com.atproto.sync.getBlob", &["--encoding", "a/b"]).is_err());
    }

    /// `import-space-meta` and the space's `import-repo` take their body from
    /// standard input as their one type, `application/vnd.dasl.star`: they
    /// have no `--encoding`, nor any other flag.
    #[test]
    fn space_meta_commands() {
        let import = pds_lexicon::method("com.atproto.space.importSpaceMeta").unwrap();
        assert_eq!(fixed_encoding(import), Some("application/vnd.dasl.star"));
        let repo = pds_lexicon::method("com.atproto.space.importRepo").unwrap();
        assert_eq!(fixed_encoding(repo), Some("application/vnd.dasl.star"));
        assert!(command_help(repo).contains("It takes no flags."));
        assert_eq!(
            fixed_encoding(pds_lexicon::method("com.atproto.repo.uploadBlob").unwrap()),
            None
        );
        assert_eq!(
            flags("com.atproto.space.importSpaceMeta", &[])
                .unwrap()
                .unwrap(),
            Map::new()
        );
        assert!(
            flags(
                "com.atproto.space.importSpaceMeta",
                &["--encoding", "application/vnd.dasl.star"]
            )
            .is_err()
        );
        assert!(command_help(import).contains("It takes no flags."));
        let got = flags(
            "com.atproto.space.exportSpaceMeta",
            &["--space", "at://did:plc:x/space/a.b.c/k"],
        )
        .unwrap()
        .unwrap();
        assert_eq!(
            Json::Object(got),
            json!({ "space": "at://did:plc:x/space/a.b.c/k" })
        );
    }

    /// `import-repo` sends standard input as its one type, a CAR file
    /// (`spec/COMMANDS.md`): no `--encoding`, nor any other flag; and its
    /// method has no MCP tool.
    #[test]
    fn import_repo_command() {
        let import = pds_lexicon::method("com.atproto.repo.importRepo").unwrap();
        assert_eq!(import.command().as_deref(), Some("import-repo"));
        assert_eq!(fixed_encoding(import), Some("application/vnd.ipld.car"));
        assert_eq!(import.tool(), None);
        assert_eq!(
            flags("com.atproto.repo.importRepo", &[]).unwrap().unwrap(),
            Map::new()
        );
        assert!(flags("com.atproto.repo.importRepo", &["--encoding", "a/b"]).is_err());
        assert!(command_help(import).contains("It takes no flags."));
    }

    /// The admin's reads are commands of `admin`, after its methods', with
    /// the spec's descriptions and `logs`'s flags.
    #[test]
    fn admin_reads() {
        let names: Vec<String> = listed(ADMIN).into_iter().map(|(n, _)| n).collect();
        assert_eq!(&names[names.len() - 2..], ["logs", "stats"]);
        assert!(names.len() > 2);
        let help = group_help(ADMIN);
        assert!(help.contains("As the admin, what the server counted since it started"));
        let logs = &OWN[0];
        let flags: Vec<&Arg> = logs.args.iter().collect();
        let text = help_of(logs);
        for f in [
            "--trace", "--msg", "--method", "--level", "--min-ms", "--limit",
        ] {
            assert!(text.contains(f), "{f}");
        }
        let parse = |argv: &[&str]| {
            let argv: Vec<String> = argv.iter().map(|a| a.to_string()).collect();
            parse_flags(ADMIN, "logs", &flags, &argv)
        };
        assert_eq!(
            parse(&["--level", "info", "--min-ms", "5", "--limit=3"])
                .ok()
                .flatten()
                .map(Json::Object),
            Some(json!({ "level": "info", "minMs": 5, "limit": 3 }))
        );
        for bad in [
            &["--limit", "x"][..],
            &["--no-such-flag", "x"],
            &["--level"],
        ] {
            assert!(matches!(parse(bad), Err(Stop::Usage(_))), "{bad:?}");
        }
        assert!(help_of(&OWN[1]).contains("It takes no flags."));
    }

    /// The account's OAuth routes are the group `oauth`, listed after every
    /// lexicon's group, and its passkey routes the group `passkey`, after
    /// it, their commands in the spec's order; a change needs its flag, a
    /// list takes none.
    #[test]
    fn oauth_and_passkey_commands() {
        assert_eq!(groups()[groups().len() - 2..], [OAUTH, PASSKEY]);
        assert!(!pds_lexicon::groups().contains(&OAUTH));
        assert!(!pds_lexicon::groups().contains(&PASSKEY));
        let names = |g| -> Vec<String> { listed(g).into_iter().map(|(n, _)| n).collect() };
        assert_eq!(
            names(OAUTH),
            ["sessions", "revoke-session", "devices", "revoke-device"]
        );
        assert_eq!(names(PASSKEY), ["list", "add", "remove"]);
        assert!(top_help().trim_end().ends_with(OWN[8].description));
        for r in OWN
            .iter()
            .filter(|r| r.group == OAUTH || r.group == PASSKEY)
        {
            let flags: Vec<&Arg> = r.args.iter().collect();
            let parse = |argv: &[&str]| {
                let argv: Vec<String> = argv.iter().map(|a| a.to_string()).collect();
                parse_flags(r.group, r.command, &flags, &argv)
            };
            if r.post {
                let flag = if r.command == "add" { "name" } else { "id" };
                assert!(help_of(r).contains(&format!("--{flag}")));
                assert!(matches!(parse(&[]), Err(Stop::Usage(_))));
                assert_eq!(
                    parse(&[&format!("--{flag}"), "x"])
                        .ok()
                        .flatten()
                        .map(Json::Object),
                    Some(json!({ flag: "x" }))
                );
            } else {
                assert!(help_of(r).contains("It takes no flags."));
                assert!(matches!(parse(&["--id", "x"]), Err(Stop::Usage(_))));
            }
        }
    }

    fn help_of(r: &Own) -> String {
        let flags: Vec<&Arg> = r.args.iter().collect();
        help(r.group, r.command, Some(r.description), &flags)
    }
}