~ knotless Search/
↑↓ move↵ open⇧↵ all results

chadtmiller.com/hud

A remote MCP server that shows atproto records as interactive UI inside MCP Apps hosts

0
0
1379 lines · 54.3 KB Raw History
//! Calling a service's XRPC queries: the AppView's feeds and the like,
//! whatever a lexicon says a query takes and answers. A query is named by
//! its NSID, which must resolve to a lexicon whose main def is a `query`
//! (never a procedure: HUD only reads); it is sent to a service named by a
//! DID and the fragment of one of its document's services
//! (`did:web:api.bsky.app#bsky_appview`). Its params are checked against
//! the lexicon before the call, and its answer after, with the `atproto`
//! crate's lexicon validation: a service is someone else's server, and an
//! answer that is not what its lexicon says is refused.
//!
//! Calls are made as no one (`Caller::Public`), so only public data is had,
//! or, for a signed-in account, through its own PDS (`Caller::Account`),
//! which signs the call for the service (`atproto-proxy`); the rest of the
//! path is the same. The query tool and views' query joins ask alike
//! (`ask`), through an `Asker`: HUD as a caller (`As`), or a test's own.
//!
//! HUD keeps each answer a while, for whoever asked alone (`Asking`): 20 s
//! asked as no one, 8 s as an account, which forgets its own the moment it
//! writes through HUD (`Hud::wrote`); and asks a service once for all who
//! ask the same at once (`cache::Shared`). A view or query join that needs
//! what is there now says `fresh`, and is asked each time and kept by no one.

use crate::Hud;
use crate::blobs;
use crate::lexicon::{full_ref, refs_in};
use crate::oauth::Account;
use crate::tools::Refusal;
use crate::uri::AtUri;
use atproto::lexicon::Lexicons;
use futures::future::{BoxFuture, join_all};
use serde_json::{Map, Value};
use std::collections::{BTreeSet, VecDeque};
use std::sync::Arc;
use std::time::Duration;
use url::Url;

/// How long a service has to answer.
const WAIT: Duration = Duration::from_secs(10);
/// The most of an answer read.
const MAX: usize = 5 * 1024 * 1024;
/// The most lexicon documents gathered to check one query.
const DOCS_MAX: usize = 80;
/// How deep `describe_method` follows refs, and the most defs it gives.
const DESCRIBED_DEPTH: usize = 3;
const DESCRIBED_MAX: usize = 60;
/// The name a query's output schema is checked under, in its own document.
const OUTPUT_DEF: &str = "hudOutput";
/// How long an answer asked as no one is kept.
const KEPT_PUBLIC: Duration = Duration::from_secs(20);
/// How long an answer asked as an account is kept for it.
const KEPT_ACCOUNT: Duration = Duration::from_secs(8);

/// Who a query is made as: no one, for public data; or a signed-in
/// account, through its own PDS.
#[derive(Clone, Copy, Debug)]
pub enum Caller<'a> {
    Public,
    Account(&'a Account),
}

/// A service: a DID, and the fragment of the service in its document.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Service {
    pub did: String,
    pub fragment: String,
}

impl Service {
    /// `did:…#fragment`, or why it is not one.
    pub fn parse(s: &str) -> Result<Service, String> {
        let bad = || {
            format!(
                "Not a service: {s} (a DID with its service's #fragment, as did:web:api.bsky.app#bsky_appview)"
            )
        };
        let (did, fragment) = s.trim().split_once('#').ok_or_else(bad)?;
        let fragment_ok = (1..=64).contains(&fragment.len())
            && fragment
                .bytes()
                .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-');
        if !atproto::syntax::is_did(did) || !fragment_ok {
            return Err(bad());
        }
        Ok(Service {
            did: did.to_string(),
            fragment: fragment.to_string(),
        })
    }

    pub fn name(&self) -> String {
        format!("{}#{}", self.did, self.fragment)
    }
}

/// What a kept answer was asked as: who asked (an account's DID, none for
/// no one), the service, the method and its params by name, so the same
/// params given in another order are the same (an array's in its order).
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct Asking {
    pub viewer: Option<String>,
    pub service: String,
    pub method: String,
    pub pairs: Vec<(String, String)>,
}

impl Asking {
    fn new(caller: Caller, service: &Service, method: &str, pairs: &[(String, String)]) -> Asking {
        let mut pairs = pairs.to_vec();
        pairs.sort_by(|(a, _), (b, _)| a.cmp(b));
        let viewer = match caller {
            Caller::Public => None,
            Caller::Account(a) => Some(a.did.clone()),
        };
        Asking {
            viewer,
            service: service.name(),
            method: method.to_string(),
            pairs,
        }
    }
}

/// The endpoint a DID document gives the service whose id ends in
/// `#fragment`, if it is a URL the server may call.
pub fn endpoint(doc: &Value, service: &Service, allow_private: bool) -> Result<String, String> {
    let named = service.name();
    let found = atproto::did::service(doc, &format!("#{}", service.fragment))
        .ok_or_else(|| format!("{} names no service #{}", service.did, service.fragment))?;
    let url = Url::parse(&found).map_err(|_| format!("{named} has no usable endpoint"))?;
    let plain = url.username().is_empty()
        && url.password().is_none()
        && url.query().is_none()
        && url.fragment().is_none();
    if !plain {
        return Err(format!("{named} has no usable endpoint"));
    }
    crate::net::check_url(&url, allow_private)
        .map_err(|why| format!("{named} cannot be called: {why}"))?;
    Ok(url.as_str().trim_end_matches('/').to_string())
}

/// A lexicon document's main def, if it is a query; else why the method
/// cannot be called.
pub fn query_def<'a>(method: &str, doc: &'a Value) -> Result<&'a Value, String> {
    let main = &doc["defs"]["main"];
    match main["type"].as_str() {
        Some("query") => Ok(main),
        Some(other) => Err(format!(
            "{method} is a {other}, not a query: HUD only reads"
        )),
        None => Err(format!("{method} is not a method")),
    }
}

/// The problems with params given a query: names it does not take, then
/// the first value its lexicon refuses.
pub fn params_problems(
    lexicons: &Lexicons,
    method: &str,
    def: &Value,
    params: &Map<String, Value>,
) -> Vec<String> {
    let taken = def["parameters"]["properties"].as_object();
    let mut out: Vec<String> = params
        .keys()
        .filter(|k| taken.is_none_or(|t| !t.contains_key(k.as_str())))
        .map(|k| format!("params.{k} is not a parameter of {method}"))
        .collect();
    if let Err(e) = lexicons.validate_params(method, params) {
        out.push(e.to_string());
    }
    out
}

/// Make every at-uri param of a query (one its lexicon declares `format:
/// at-uri`, or an array of them) whose authority is a handle name the
/// handle's DID instead, as `resolve` finds it: services take DIDs, people
/// write handles (`at://bnb.im/app.bsky.feed.post/…`, from a bsky.app
/// link). A handle that does not resolve is the error, naming it.
pub async fn handles_to_dids<F, Fut>(
    def: &Value,
    params: &mut Map<String, Value>,
    resolve: F,
) -> Result<(), String>
where
    F: Fn(String) -> Fut,
    Fut: Future<Output = Result<String, String>>,
{
    for v in declared(def, params, "at-uri") {
        let Some(rest) = v.as_str().and_then(|s| s.strip_prefix("at://")) else {
            continue;
        };
        let (authority, path) = rest.split_at(rest.find(['/', '?', '#']).unwrap_or(rest.len()));
        let handle = authority.to_ascii_lowercase();
        if atproto::syntax::is_did(authority) || !atproto::syntax::is_handle(&handle) {
            continue;
        }
        let did = resolve(handle).await?;
        *v = Value::String(format!("at://{did}{path}"));
    }
    Ok(())
}

/// Make every at-identifier param of a query (`format: at-identifier`, or
/// an array of them) that is a handle, with or without a leading `@`, the
/// handle's DID instead, as `resolve` finds it. A handle that does not
/// resolve is the error, naming it.
pub async fn identifiers_to_dids<F, Fut>(
    def: &Value,
    params: &mut Map<String, Value>,
    resolve: F,
) -> Result<(), String>
where
    F: Fn(String) -> Fut,
    Fut: Future<Output = Result<String, String>>,
{
    for v in declared(def, params, "at-identifier") {
        let Some(given) = v.as_str() else {
            continue;
        };
        let given = given.trim();
        let handle = given
            .strip_prefix('@')
            .unwrap_or(given)
            .to_ascii_lowercase();
        if atproto::syntax::is_did(given) || !atproto::syntax::is_handle(&handle) {
            continue;
        }
        *v = Value::String(resolve(handle).await?);
    }
    Ok(())
}

/// The string values of the params a query's lexicon declares of
/// `format`, alone or as an array's items.
fn declared<'a>(
    def: &Value,
    params: &'a mut Map<String, Value>,
    format: &str,
) -> Vec<&'a mut Value> {
    let Some(declared) = def["parameters"]["properties"].as_object() else {
        return Vec::new();
    };
    let is = |p: &Value| p["format"] == format;
    let mut out = Vec::new();
    for (name, value) in params.iter_mut() {
        let Some(p) = declared.get(name) else {
            continue;
        };
        match value {
            Value::String(_) if is(p) => out.push(value),
            Value::Array(items) if p["type"] == "array" && is(&p["items"]) => {
                out.extend(items.iter_mut())
            }
            _ => {}
        }
    }
    out
}

/// Params as a query string's pairs: an array as its name repeated.
pub fn query_pairs(params: &Map<String, Value>) -> Vec<(String, String)> {
    let text = |v: &Value| match v {
        Value::String(s) => Some(s.clone()),
        Value::Null => None,
        other => Some(other.to_string()),
    };
    params
        .iter()
        .flat_map(|(k, v)| match v {
            Value::Array(items) => items
                .iter()
                .filter_map(|i| text(i).map(|t| (k.clone(), t)))
                .collect::<Vec<_>>(),
            v => text(v).map(|t| (k.clone(), t)).into_iter().collect(),
        })
        .collect()
}

/// A method's own lexicon among `docs`, as `lexicon_docs` gathers them.
pub fn own_doc<'a>(method: &str, docs: &'a [Arc<Value>]) -> Result<&'a Arc<Value>, String> {
    docs.iter()
        .find(|d| d["id"] == method)
        .ok_or_else(|| format!("No lexicon for {method}"))
}

/// A query's documents, its own given its output schema as a def of its
/// own when the schema is an object, so the validator can check an answer
/// against it.
pub fn lexicons_for(method: &str, docs: &[Arc<Value>]) -> Lexicons {
    Lexicons::new(docs.iter().map(|d| {
        let mut d = (**d).clone();
        if d["id"] == method {
            let schema = d["defs"]["main"]["output"]["schema"].clone();
            if schema["type"] == "object"
                && let Some(defs) = d["defs"].as_object_mut()
            {
                defs.insert(OUTPUT_DEF.into(), schema);
            }
        }
        d
    }))
}

/// Why a service's answer is not what its query's lexicon says, if it is
/// not. An answer with fields the lexicon does not name is allowed, as
/// atproto allows.
pub fn output_problem(
    lexicons: &Lexicons,
    method: &str,
    def: &Value,
    answer: &Value,
) -> Option<String> {
    let schema = &def["output"]["schema"];
    let reference = match schema["type"].as_str() {
        Some("object") => format!("{method}#{OUTPUT_DEF}"),
        Some("ref") => full_ref(method, schema["ref"].as_str()?),
        // No schema, or one (a union) the validator takes only within an object.
        _ => return None,
    };
    lexicons.validate(&reference, answer).err().map(|e| {
        let path = e
            .path
            .replacen("object", "response", 1)
            .replacen("record", "response", 1);
        format!("{path} {}", e.message)
    })
}

/// Whether a query's answer is one anyone could have had, so that its
/// images may go through the image CDN: one asked as no one, or of the
/// Bluesky AppView, whose answers to an account show public records alone.
/// Any other service asked as the account may answer what only it may read.
pub fn visibility(caller: Caller, service: &Service) -> blobs::Visibility {
    match caller {
        Caller::Public => blobs::Visibility::Public,
        Caller::Account(_) => account_answer(service),
    }
}

/// What a service's answer to the signed-in account is.
pub(crate) fn account_answer(service: &Service) -> blobs::Visibility {
    match service.name() == crate::interactions::APPVIEW {
        true => blobs::Visibility::Public,
        false => blobs::Visibility::Private,
    }
}

/// Point blob refs in an answer at where they are served (`blobs::rewrite`,
/// as `visibility` says), where the repository holding them is known: a
/// record (`record` or `value`) beside the `uri` naming it, as AppView
/// views give one. Others are left as they are.
pub fn rewrite_response(v: &mut Value, urls: blobs::Urls, visibility: blobs::Visibility) {
    match v {
        Value::Object(o) => {
            let did = o
                .get("uri")
                .and_then(Value::as_str)
                .and_then(|u| AtUri::parse(u).ok())
                .map(|u| u.authority)
                .filter(|a| atproto::syntax::is_did(a));
            for (k, child) in o.iter_mut() {
                if let Some(did) = &did
                    && matches!(k.as_str(), "record" | "value")
                {
                    blobs::rewrite(child, urls, did, visibility);
                }
                rewrite_response(child, urls, visibility);
            }
        }
        Value::Array(items) => items
            .iter_mut()
            .for_each(|i| rewrite_response(i, urls, visibility)),
        _ => {}
    }
}

/// An AppView video view's type.
const VIDEO_VIEW: &str = "app.bsky.embed.video#view";

/// Point every video an answer shows (`app.bsky.embed.video#view`) at the
/// proxy, beside its HLS playlist: a `url` of its blob, in the repository
/// of the post that holds it, the nearest `author.did` around it (a
/// `postView`'s, or a quoted `viewRecord`'s). A video whose post's author
/// is not known, or whose `cid` is not one, is left as it is.
pub fn video_urls(v: &mut Value, origin: &str) {
    walk_videos(v, origin, None);
}

fn walk_videos(v: &mut Value, origin: &str, did: Option<&str>) {
    match v {
        Value::Object(o) => {
            let own = o
                .get("author")
                .and_then(|a| a.get("did"))
                .and_then(Value::as_str)
                .filter(|d| atproto::syntax::is_did(d))
                .map(str::to_string);
            let did = own.as_deref().or(did);
            if o.get("$type").and_then(Value::as_str) == Some(VIDEO_VIEW)
                && let Some(did) = did
                && let Some(cid) = o
                    .get("cid")
                    .and_then(Value::as_str)
                    .filter(|c| atproto::Cid::parse(c).is_ok())
            {
                let url = blobs::url(origin, did, cid);
                o.insert("url".into(), Value::String(url));
                return;
            }
            o.values_mut().for_each(|c| walk_videos(c, origin, did));
        }
        Value::Array(items) => items.iter_mut().for_each(|i| walk_videos(i, origin, did)),
        _ => {}
    }
}

/// The NSIDs the refs of `v`, written in the document `nsid`, name.
fn ref_nsids(nsid: &str, v: &Value) -> Vec<String> {
    let mut refs = Vec::new();
    refs_in(v, &mut refs);
    refs.into_iter()
        .filter_map(|r| {
            let full = full_ref(nsid, r);
            full.split_once('#').map(|(n, _)| n.to_string())
        })
        .collect()
}

impl Hud {
    /// The lexicon documents a method's values may need: its own and those
    /// its defs ref, in turn, up to `DOCS_MAX`.
    pub async fn lexicon_docs(&self, method: &str) -> Vec<Arc<Value>> {
        let mut seen: BTreeSet<String> = BTreeSet::from([method.to_string()]);
        let mut level = vec![method.to_string()];
        let mut docs = Vec::new();
        while !level.is_empty() && docs.len() < DOCS_MAX {
            let found = join_all(level.iter().map(|n| self.lexicon_doc(n))).await;
            let mut next = Vec::new();
            for (nsid, doc) in level.iter().zip(found) {
                let Some(doc) = doc else { continue };
                for r in ref_nsids(nsid, &doc["defs"]) {
                    if seen.len() < DOCS_MAX && seen.insert(r.clone()) {
                        next.push(r);
                    }
                }
                docs.push(doc);
            }
            level = next;
        }
        docs
    }

    /// The defs a query's parameters and output ref, followed up to three
    /// levels deep, at most 60, by `nsid#name`.
    pub async fn described_defs(&self, method: &str, def: &Value) -> Map<String, Value> {
        let mut out = Map::new();
        let mut queue: VecDeque<(String, usize)> = VecDeque::new();
        let mut seen = BTreeSet::new();
        let push = |queue: &mut VecDeque<(String, usize)>,
                    seen: &mut BTreeSet<String>,
                    nsid: &str,
                    v: &Value,
                    depth: usize| {
            let mut refs = Vec::new();
            refs_in(v, &mut refs);
            for r in refs {
                let full = full_ref(nsid, r);
                if seen.insert(full.clone()) {
                    queue.push_back((full, depth));
                }
            }
        };
        push(&mut queue, &mut seen, method, &def["parameters"], 1);
        push(&mut queue, &mut seen, method, &def["output"], 1);
        while let Some((full, depth)) = queue.pop_front() {
            if out.len() >= DESCRIBED_MAX {
                break;
            }
            // `full_ref` always writes `nsid#name`.
            let (nsid, name) = full.split_once('#').unwrap_or((&full, "main"));
            let Some(doc) = self.lexicon_doc(nsid).await else {
                continue;
            };
            let Some(found) = doc["defs"].get(name) else {
                continue;
            };
            if depth < DESCRIBED_DEPTH {
                push(&mut queue, &mut seen, nsid, found, depth + 1);
            }
            out.insert(full.clone(), found.clone());
        }
        out
    }

    /// The endpoint of a service, from its DID's document.
    pub async fn service_endpoint(&self, service: &Service) -> Result<String, String> {
        let doc = self.did_doc(&service.did).await?;
        endpoint(&doc, service, self.net.allow_private())
    }

    /// Call a query of `service` at `endpoint` as `caller`, its answer a
    /// JSON object, or why there is none, in one line naming no more of
    /// the service's own words than its error's name. A service HUD does
    /// not ask to call as the account (`scope::calls`) is called as no one.
    /// Made as no one and refused for want of an account (`AuthMissing`,
    /// `AuthenticationRequired`), with sign-in on, it asks for sign-in,
    /// unless the account was the caller.
    pub async fn call_query(
        &self,
        caller: Caller<'_>,
        endpoint: &str,
        service: &Service,
        method: &str,
        pairs: &[(String, String)],
    ) -> Result<Value, Refusal> {
        let mut url = Url::parse(&format!("{endpoint}/xrpc/{method}"))
            .map_err(|_| format!("{endpoint} is not a usable endpoint"))?;
        url.query_pairs_mut().extend_pairs(pairs);
        let host = url.host_str().unwrap_or(endpoint).to_string();
        // As the account where HUD asks to call this service as it; else as
        // no one, public data alone, as signed out (`declined`, where the
        // account was the caller).
        let asked = self.oauth.as_ref().map(|o| o.scope.as_str());
        let (account, declined) = match caller {
            Caller::Account(a)
                if asked.is_some_and(|s| crate::scope::calls(s, &service.name())) =>
            {
                (Some(a), false)
            }
            Caller::Account(_) => (None, true),
            Caller::Public => (None, false),
        };
        let got = match account {
            None => self
                .net
                .fetch_json(&url, WAIT, MAX)
                .await
                .map_err(|why| format!("Could not call {method} on {host}: {why}"))?,
            Some(a) => {
                self.pds_call(a, method, pairs, None, Some(&service.name()))
                    .await?
            }
        };
        if got.status != 200 {
            let error = crate::pds::error_name(&got.body);
            let wants_account = matches!(
                error.as_deref(),
                Some("AuthMissing" | "AuthenticationRequired")
            );
            return Err(match (account, error.as_deref()) {
                (None, _) if wants_account && declined => format!(
                    "{method} needs an account, and HUD does not call {} as you",
                    service.name()
                )
                .into(),
                (None, _) if wants_account && self.oauth.is_some() => Refusal::SignIn,
                (Some(a), Some("ScopeMissingError")) => {
                    let aud = service.name().replace('#', "%23");
                    self.scope_refused(a, &format!("rpc:{method}?aud={aud}"))
                        .await
                }
                (_, Some(e)) => format!("{host} refused {method}: {e} ({})", got.status).into(),
                (_, None) => format!("{host} refused {method} ({})", got.status).into(),
            });
        }
        match serde_json::from_slice(&got.body) {
            Ok(v @ Value::Object(_)) => Ok(v),
            _ => Err(format!("{host} answered {method} with something that is not JSON").into()),
        }
    }

    /// Forget the answers kept for `did`, as it wrote: what it reads next
    /// shows what it wrote.
    pub(crate) fn wrote(&self, did: &str) {
        self.answers.forget(&|k| k.viewer.as_deref() == Some(did));
    }
}

/// What a query is asked through: the lexicons, handles and calls it needs.
pub trait Asker: Sync {
    /// The lexicon documents a method's values may need, its own among
    /// them where it has one.
    fn docs<'a>(&'a self, method: &'a str) -> BoxFuture<'a, Vec<Arc<Value>>>;
    /// The DID a handle names, or why none.
    fn handle_did(&self, handle: String) -> BoxFuture<'_, Result<String, String>>;
    /// The call: its answer, a JSON object, and the host that gave it;
    /// `fresh`, asked now, never an answer kept.
    fn call<'a>(
        &'a self,
        service: &'a Service,
        method: &'a str,
        pairs: Vec<(String, String)>,
        fresh: bool,
    ) -> BoxFuture<'a, Result<(Value, String), Refusal>>;
    /// Point an answer's blobs and videos at the proxy.
    fn rewrite(&self, service: &Service, answer: &mut Value);
}

/// A query's answer, as asked, and the host that gave it.
#[derive(Debug)]
pub struct Asked {
    pub response: Value,
    pub host: String,
}

/// Ask a query as the query tool does: its at-uri params naming a handle
/// made the handle's DID (`params`, as sent), the params checked against
/// its lexicon, the call, and the answer checked against the lexicon, its
/// blobs and videos pointed at the proxy. An answer kept a while will do.
pub async fn ask<A: Asker + ?Sized>(
    asker: &A,
    service: &Service,
    method: &str,
    params: &mut Map<String, Value>,
) -> Result<Asked, Refusal> {
    let docs = asker.docs(method).await;
    ask_with(asker, &docs, service, method, params, false).await
}

/// `ask`, with the lexicon documents `asker.docs` gave for `method`;
/// `fresh`, asked now.
pub async fn ask_with<A: Asker + ?Sized>(
    asker: &A,
    docs: &[Arc<Value>],
    service: &Service,
    method: &str,
    params: &mut Map<String, Value>,
    fresh: bool,
) -> Result<Asked, Refusal> {
    let ready = ready(asker, docs, method, params).await?;
    ready.ask(asker, service, params, fresh).await
}

/// A query ready to call: its params as `ready` left them, and what its
/// answer is checked against.
pub struct Ready<'d> {
    method: &'d str,
    def: &'d Value,
    lexicons: Lexicons,
}

/// `ask`'s first half, before the call: `params`' at-uris naming a handle
/// made the handle's DID, then checked against `method`'s lexicon among
/// `docs`. What a query's scope holds of its params is known from here on.
pub async fn ready<'d, A: Asker + ?Sized>(
    asker: &A,
    docs: &'d [Arc<Value>],
    method: &'d str,
    params: &mut Map<String, Value>,
) -> Result<Ready<'d>, Refusal> {
    let doc = own_doc(method, docs)?;
    let def = query_def(method, doc)?;
    handles_to_dids(def, params, |h| asker.handle_did(h)).await?;
    let lexicons = lexicons_for(method, docs);
    let problems = params_problems(&lexicons, method, def, params);
    if !problems.is_empty() {
        return Err(format!("Invalid params for {method}: {}", problems.join("; ")).into());
    }
    Ok(Ready {
        method,
        def,
        lexicons,
    })
}

impl Ready<'_> {
    /// `ask`'s second half: the call with `params` as `ready` left them
    /// (`fresh`, asked now), its answer checked against the lexicon, its
    /// blobs and videos pointed at the proxy.
    pub async fn ask<A: Asker + ?Sized>(
        &self,
        asker: &A,
        service: &Service,
        params: &Map<String, Value>,
        fresh: bool,
    ) -> Result<Asked, Refusal> {
        let (method, def) = (self.method, self.def);
        let pairs = query_pairs(params);
        let (mut response, host) = asker.call(service, method, pairs, fresh).await?;
        if let Some(problem) = output_problem(&self.lexicons, method, def, &response) {
            return Err(format!("The service's answer does not match {method}: {problem}").into());
        }
        asker.rewrite(service, &mut response);
        Ok(Asked { response, host })
    }
}

/// HUD asking as `caller`: no one, or a signed-in account through its PDS.
pub struct As<'a> {
    pub hud: &'a Hud,
    pub caller: Caller<'a>,
}

impl As<'_> {
    /// The call itself, to the service, its answer and the host that gave it.
    async fn upstream(
        &self,
        service: &Service,
        method: &str,
        pairs: &[(String, String)],
    ) -> Result<(Value, String), Refusal> {
        let endpoint = self.hud.service_endpoint(service).await?;
        let host = Url::parse(&endpoint)
            .ok()
            .and_then(|u| u.host_str().map(str::to_string));
        let answer = self
            .hud
            .call_query(self.caller, &endpoint, service, method, pairs)
            .await?;
        Ok((answer, host.unwrap_or(endpoint)))
    }
}

impl Asker for As<'_> {
    fn docs<'a>(&'a self, method: &'a str) -> BoxFuture<'a, Vec<Arc<Value>>> {
        Box::pin(self.hud.lexicon_docs(method))
    }

    fn handle_did(&self, handle: String) -> BoxFuture<'_, Result<String, String>> {
        Box::pin(async move { self.hud.handle_did(&handle).await })
    }

    /// The answer kept for whoever asked, else the call's, made once for
    /// all who ask the same at once and kept as `Asking` says.
    fn call<'a>(
        &'a self,
        service: &'a Service,
        method: &'a str,
        pairs: Vec<(String, String)>,
        fresh: bool,
    ) -> BoxFuture<'a, Result<(Value, String), Refusal>> {
        Box::pin(async move {
            let asked = self.upstream(service, method, &pairs);
            if fresh {
                return asked.await;
            }
            let kept = match self.caller {
                Caller::Public => KEPT_PUBLIC,
                Caller::Account(_) => KEPT_ACCOUNT,
            };
            let key = Asking::new(self.caller, service, method, &pairs);
            self.hud.answers.get_or(key, kept, asked).await
        })
    }

    fn rewrite(&self, service: &Service, answer: &mut Value) {
        let config = &self.hud.config;
        rewrite_response(answer, config.blob_urls(), visibility(self.caller, service));
        video_urls(answer, &config.public_origin);
    }
}

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

    /// Every bundled lexicon, as a query's checks would gather them.
    fn bundled() -> (Vec<Arc<Value>>, Lexicons) {
        let docs: Vec<Arc<Value>> = crate::lexicon::all_bundled().cloned().collect();
        let lex = lexicons_for("app.bsky.feed.getFeed", &docs);
        (docs, lex)
    }

    fn doc(nsid: &str) -> Arc<Value> {
        crate::lexicon::bundled(nsid).unwrap()
    }

    #[test]
    fn only_queries() {
        assert!(query_def("app.bsky.feed.getFeed", &doc("app.bsky.feed.getFeed")).is_ok());
        assert_eq!(
            query_def("app.bsky.feed.post", &doc("app.bsky.feed.post"))
                .err()
                .as_deref(),
            Some("app.bsky.feed.post is a record, not a query: HUD only reads")
        );
        let procedure = json!({ "defs": { "main": { "type": "procedure" } } });
        assert_eq!(
            query_def("com.atproto.repo.createRecord", &procedure)
                .err()
                .as_deref(),
            Some("com.atproto.repo.createRecord is a procedure, not a query: HUD only reads")
        );
        assert!(query_def("x.y.z", &json!({ "defs": {} })).is_err());
    }

    #[test]
    fn params() {
        let (_, lex) = bundled();
        let getfeed = doc("app.bsky.feed.getFeed");
        let def = query_def("app.bsky.feed.getFeed", &getfeed).unwrap();
        let p =
            |v: Value| params_problems(&lex, "app.bsky.feed.getFeed", def, v.as_object().unwrap());
        let feed = "at://did:plc:z72i7hdynmk6r22z27h6tvur/app.bsky.feed.generator/whats-hot";
        assert!(p(json!({ "feed": feed, "limit": 10, "cursor": "c" })).is_empty());
        assert_eq!(
            p(json!({ "limit": 10 })),
            ["params must have the property \"feed\""]
        );
        assert_eq!(p(json!({ "feed": feed, "limit": "ten" })).len(), 1);
        assert_eq!(p(json!({ "feed": feed, "limit": 1000 })).len(), 1);
        assert_eq!(
            p(json!({ "feed": feed, "colour": "red" })),
            ["params.colour is not a parameter of app.bsky.feed.getFeed"]
        );
        assert_eq!(
            query_pairs(
                json!({ "feed": feed, "limit": 10, "uris": ["a", "b"], "x": null })
                    .as_object()
                    .unwrap()
            ),
            [
                ("feed".to_string(), feed.to_string()),
                ("limit".into(), "10".into()),
                ("uris".into(), "a".into()),
                ("uris".into(), "b".into()),
            ]
        );
    }

    #[test]
    fn outputs() {
        let (_, lex) = bundled();
        let getfeed = doc("app.bsky.feed.getFeed");
        let def = query_def("app.bsky.feed.getFeed", &getfeed).unwrap();
        let check = |v: Value| output_problem(&lex, "app.bsky.feed.getFeed", def, &v);
        assert_eq!(check(json!({ "feed": [], "cursor": "c" })), None);
        assert_eq!(
            check(json!({ "feed": [], "somethingNew": 1 })),
            None,
            "extra fields are allowed"
        );
        assert!(
            check(json!({ "feed": "not an array" }))
                .unwrap()
                .starts_with("response.feed")
        );
        assert!(check(json!({ "cursor": "c" })).unwrap().contains("feed"));
        // A post view missing its author is refused.
        let cid = atproto::Cid::of_cbor(b"a post").to_string();
        let bad = json!({ "feed": [{ "post": { "uri": "at://did:plc:a/app.bsky.feed.post/1", "cid": cid,
                                           "record": {}, "indexedAt": "2026-11-14T00:00:00.000Z" } }] });
        assert!(check(bad).unwrap().contains("author"));
    }

    #[test]
    fn services() {
        let s = Service::parse("did:web:api.bsky.app#bsky_appview").unwrap();
        assert_eq!(
            (s.did.as_str(), s.fragment.as_str()),
            ("did:web:api.bsky.app", "bsky_appview")
        );
        assert_eq!(s.name(), "did:web:api.bsky.app#bsky_appview");
        for bad in [
            "did:web:api.bsky.app",
            "api.bsky.app#bsky_appview",
            "did:web:api.bsky.app#",
            "did:web:x#a b",
        ] {
            assert!(Service::parse(bad).is_err(), "{bad}");
        }
        let doc = json!({ "id": "did:web:api.bsky.app", "service": [
            { "id": "#bsky_notif", "type": "BskyNotificationService", "serviceEndpoint": "https://api.bsky.app" },
            { "id": "#bsky_appview", "type": "BskyAppView", "serviceEndpoint": "https://api.bsky.app/" },
            { "id": "#private", "type": "X", "serviceEndpoint": "https://10.0.0.1" },
        ] });
        assert_eq!(
            endpoint(&doc, &s, false).as_deref(),
            Ok("https://api.bsky.app")
        );
        let missing = Service::parse("did:web:api.bsky.app#bsky_chat").unwrap();
        assert_eq!(
            endpoint(&doc, &missing, false).err().as_deref(),
            Some("did:web:api.bsky.app names no service #bsky_chat")
        );
        let private = Service::parse("did:web:api.bsky.app#private").unwrap();
        assert!(endpoint(&doc, &private, false).is_err());
        for (fragment, at) in [
            ("unparsed", "not a url"),
            ("dressed", "https://u@api.example"),
        ] {
            let doc =
                json!({ "service": [{ "id": format!("#{fragment}"), "serviceEndpoint": at }] });
            let s = Service::parse(&format!("did:web:api.example#{fragment}")).unwrap();
            assert_eq!(
                endpoint(&doc, &s, false),
                Err(format!(
                    "did:web:api.example#{fragment} has no usable endpoint"
                ))
            );
        }
    }

    #[test]
    fn response_blobs() {
        let cid = "bafkreibme22gw2h7y2h7tg2fhqotaqjucnbc24deqo72b6mkl2egezxhvy";
        let blob = json!({ "$type": "blob", "ref": { "$link": cid }, "mimeType": "image/jpeg", "size": 10 });
        let mut v = json!({ "feed": [{ "post": { "uri": "at://did:plc:a/app.bsky.feed.post/1",
            "record": { "embed": { "images": [{ "image": blob }] } } } }],
            "loose": { "image": blob } });
        let public = blobs::Visibility::Public;
        rewrite_response(&mut v, blobs::Urls::proxy("https://hud.example"), public);
        assert_eq!(
            v["feed"][0]["post"]["record"]["embed"]["images"][0]["image"]["url"],
            format!("https://hud.example/blob/did:plc:a/{cid}")
        );
        assert!(
            v["loose"]["image"].get("url").is_none(),
            "no repository known"
        );
        // With a CDN, a public answer's images go through it; a private
        // answer's stay on the proxy.
        let urls = blobs::Urls {
            origin: "https://hud.example",
            cdn: Some("https://cdn.example/img"),
        };
        let image =
            |v: &Value| v["feed"][0]["post"]["record"]["embed"]["images"][0]["image"].clone();
        let mut seen = v.clone();
        rewrite_response(&mut seen, urls, public);
        assert_eq!(
            image(&seen)["url"],
            format!("https://cdn.example/img/feed_fullsize/plain/did:plc:a/{cid}@jpeg")
        );
        let mut kept = v.clone();
        rewrite_response(&mut kept, urls, blobs::Visibility::Private);
        assert_eq!(image(&kept), image(&v));
        // Which answers are public: any asked as no one, and the AppView's.
        let appview = Service::parse(crate::interactions::APPVIEW).unwrap();
        let chat = Service::parse("did:web:api.bsky.chat#bsky_chat").unwrap();
        assert_eq!(visibility(Caller::Public, &chat), public);
        assert_eq!(account_answer(&appview), public);
        assert_eq!(account_answer(&chat), blobs::Visibility::Private);
    }

    #[test]
    fn video_views_get_urls() {
        const C1: &str = "bafkreibme22gw2h7y2h7tg2fhqotaqjucnbc24deqo72b6mkl2egezxhvy";
        const C2: &str = "bafyreie5737gdxlw5i64vzichcalba3z2v5n6icifvx5xytvske7mr3hpm";
        let video = |cid: &str| {
            json!({ "$type": "app.bsky.embed.video#view", "cid": cid,
                    "playlist": format!("https://video.bsky.app/watch/x/{cid}/playlist.m3u8") })
        };
        let o = "https://hud.example";
        let mut answer = json!({ "feed": [
            // A post's own video, by its author.
            { "post": { "uri": "at://did:plc:a/app.bsky.feed.post/1", "author": { "did": "did:plc:a" },
                        "embed": video(C1) } },
            // A quote of a post with a video: the quoted author's.
            { "post": { "author": { "did": "did:plc:a" }, "embed": {
                "$type": "app.bsky.embed.record#view",
                "record": { "$type": "app.bsky.embed.record#viewRecord", "author": { "did": "did:plc:q" },
                            "embeds": [video(C2)] } } } },
            // Media with a quote: the media the outer post's, the quote's
            // its own.
            { "post": { "author": { "did": "did:plc:a" }, "embed": {
                "$type": "app.bsky.embed.recordWithMedia#view",
                "media": video(C1),
                "record": { "record": { "author": { "did": "did:plc:q" }, "embeds": [video(C2)] } } } } },
            // No author known, or no CID: left alone.
            { "embed": video(C1) },
            { "post": { "author": { "did": "did:plc:a" }, "embed": video("not a cid") } },
        ] });
        video_urls(&mut answer, o);
        let url = |did: &str, cid: &str| json!(format!("{o}/blob/{did}/{cid}"));
        let f = &answer["feed"];
        assert_eq!(f[0]["post"]["embed"]["url"], url("did:plc:a", C1));
        assert_eq!(
            f[1]["post"]["embed"]["record"]["embeds"][0]["url"],
            url("did:plc:q", C2)
        );
        assert_eq!(f[2]["post"]["embed"]["media"]["url"], url("did:plc:a", C1));
        assert_eq!(
            f[2]["post"]["embed"]["record"]["record"]["embeds"][0]["url"],
            url("did:plc:q", C2)
        );
        assert!(f[3]["embed"].get("url").is_none());
        assert!(f[4]["post"]["embed"].get("url").is_none());
    }

    #[tokio::test]
    async fn handles_in_at_uris_become_dids() {
        let def = json!({ "parameters": { "type": "params", "properties": {
            "uri": { "type": "string", "format": "at-uri" },
            "uris": { "type": "array", "items": { "type": "string", "format": "at-uri" } },
            "actor": { "type": "string", "format": "at-identifier" },
        } } });
        let fake = |h: String| async move {
            match h.as_str() {
                "bnb.im" => Ok("did:plc:bnb".to_string()),
                _ => Err(format!("The handle {h} does not resolve to a DID")),
            }
        };
        let mut params = json!({
            "uri": "at://BNB.im/app.bsky.feed.post/3mwvwapoefs26",
            "uris": ["at://bnb.im/app.bsky.feed.post/1", "at://did:plc:x/app.bsky.feed.post/2",
                     "https://bsky.app/profile/bnb.im"],
            "actor": "bnb.im",
            "other": "at://bnb.im/app.bsky.feed.post/1",
        })
        .as_object()
        .unwrap()
        .clone();
        handles_to_dids(&def, &mut params, fake).await.unwrap();
        assert_eq!(
            params["uri"],
            "at://did:plc:bnb/app.bsky.feed.post/3mwvwapoefs26"
        );
        assert_eq!(
            params["uris"],
            json!([
                "at://did:plc:bnb/app.bsky.feed.post/1",
                "at://did:plc:x/app.bsky.feed.post/2",
                "https://bsky.app/profile/bnb.im"
            ])
        );
        // Not declared an at-uri: left as given.
        assert_eq!(params["actor"], "bnb.im");
        assert_eq!(params["other"], "at://bnb.im/app.bsky.feed.post/1");
        // A handle that does not resolve: the error, naming it.
        let mut bad = json!({ "uri": "at://nobody.example/app.bsky.feed.post/1" })
            .as_object()
            .unwrap()
            .clone();
        assert_eq!(
            handles_to_dids(&def, &mut bad, fake).await,
            Err("The handle nobody.example does not resolve to a DID".to_string())
        );
    }

    #[test]
    fn outputs_with_no_schema_are_not_checked() {
        let (_, lex) = bundled();
        let def = json!({ "type": "query", "output": { "encoding": "application/json" } });
        assert_eq!(
            output_problem(&lex, "com.example.q", &def, &json!({ "x": 1 })),
            None
        );
    }

    #[tokio::test]
    async fn identifiers_named_by_handles_become_dids() {
        let def = json!({ "parameters": { "type": "params", "properties": {
            "actor": { "type": "string", "format": "at-identifier" },
            "other": { "type": "string", "format": "at-identifier" },
            "actors": { "type": "array", "items": { "type": "string", "format": "at-identifier" } },
        } } });
        let fake = |h: String| async move {
            match h.as_str() {
                "alice.test" => Ok("did:plc:alice".to_string()),
                _ => Err(format!("The handle {h} does not resolve to a DID")),
            }
        };
        let mut params = json!({ "actor": " @Alice.Test ", "other": 5,
                                 "actors": [5, "did:plc:bob", "not a handle!", "alice.test"] })
        .as_object()
        .unwrap()
        .clone();
        identifiers_to_dids(&def, &mut params, fake).await.unwrap();
        assert_eq!(
            Value::Object(params),
            json!({ "actor": "did:plc:alice", "other": 5,
                    "actors": [5, "did:plc:bob", "not a handle!", "did:plc:alice"] })
        );
        // A method with no params has none to make.
        let mut params = json!({ "actor": "alice.test" })
            .as_object()
            .unwrap()
            .clone();
        identifiers_to_dids(&json!({ "type": "query" }), &mut params, fake)
            .await
            .unwrap();
        assert_eq!(params["actor"], "alice.test");
        // One that does not resolve is the error.
        let mut params = json!({ "actor": "bob.test" }).as_object().unwrap().clone();
        assert_eq!(
            identifiers_to_dids(&def, &mut params, fake).await,
            Err("The handle bob.test does not resolve to a DID".into())
        );
    }

    const SERVICE: &str = "did:plc:serviceserviceserviceser";

    /// A service, its PLC directory and a handle resolver, as one fake.
    async fn service(
        axum::extract::Path(path): axum::extract::Path<String>,
        axum::extract::State(url): axum::extract::State<String>,
    ) -> axum::response::Response {
        use axum::http::StatusCode;
        use axum::response::IntoResponse;
        match path.as_str() {
            SERVICE => axum::Json(json!({ "id": SERVICE, "service": [
                { "id": "#svc", "type": "X", "serviceEndpoint": url }] }))
            .into_response(),
            "com.atproto.identity.resolveHandle" => {
                axum::Json(json!({ "did": "did:plc:alice" })).into_response()
            }
            "app.bsky.feed.getFeed" => axum::Json(json!({ "feed": [] })).into_response(),
            "com.example.auth" => {
                (StatusCode::UNAUTHORIZED, r#"{"error":"AuthMissing"}"#).into_response()
            }
            "com.example.required" => (
                StatusCode::UNAUTHORIZED,
                r#"{"error":"AuthenticationRequired"}"#,
            )
                .into_response(),
            "com.example.down" => StatusCode::INTERNAL_SERVER_ERROR.into_response(),
            _ => "not json".into_response(),
        }
    }

    /// A server whose PLC directory, handle resolver and service are the
    /// fake, sign-in on as `oauth` says, no lexicon resolving; and the
    /// fake's URL.
    async fn served(oauth: bool) -> (Arc<Hud>, String) {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let url = format!("http://{}", listener.local_addr().unwrap());
        let app = axum::Router::new()
            .route("/xrpc/{path}", axum::routing::get(service))
            .route("/{path}", axum::routing::get(service))
            .with_state(url.clone());
        tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
        let mut hud = crate::tests::hud_with(&url, |c| {
            c.oauth = oauth;
            c.handle_resolver = Some(url.clone());
        });
        let no_dns = crate::net::tests::fake_net(true, |_, _| crate::net::tests::Reply::NoSuchName);
        Arc::get_mut(&mut hud).unwrap().net = no_dns.await;
        (hud, url)
    }

    #[tokio::test]
    async fn queries_asked_and_refused_in_a_line() {
        let (hud, url) = served(false).await;
        let svc = Service::parse(&format!("{SERVICE}#svc")).unwrap();
        let public = As {
            hud: &hud,
            caller: Caller::Public,
        };
        // A handle in an at-uri made its DID; the host that answered.
        let mut params = json!({ "feed": "at://alice.test/app.bsky.feed.generator/x" })
            .as_object()
            .unwrap()
            .clone();
        let asked = ask(&public, &svc, "app.bsky.feed.getFeed", &mut params)
            .await
            .unwrap();
        assert_eq!(
            (asked.response, asked.host.as_str()),
            (json!({ "feed": [] }), "127.0.0.1")
        );
        assert_eq!(
            params["feed"],
            "at://did:plc:alice/app.bsky.feed.generator/x"
        );
        assert_eq!(
            ask(&public, &svc, "com.example.nothing", &mut Map::new())
                .await
                .unwrap_err(),
            Refusal::Error("No lexicon for com.example.nothing".into())
        );
        let call = |endpoint: &str, method: &'static str| {
            let (hud, endpoint, svc) = (hud.clone(), endpoint.to_string(), svc.clone());
            async move {
                hud.call_query(Caller::Public, &endpoint, &svc, method, &[])
                    .await
                    .unwrap_err()
            }
        };
        let error = |e: &str| Refusal::Error(e.into());
        assert_eq!(
            call(&url, "com.example.auth").await,
            error("127.0.0.1 refused com.example.auth: AuthMissing (401)")
        );
        assert_eq!(
            call(&url, "com.example.down").await,
            error("127.0.0.1 refused com.example.down (500)")
        );
        assert_eq!(
            call(&url, "com.example.text").await,
            error("127.0.0.1 answered com.example.text with something that is not JSON")
        );
        assert_eq!(
            call("http://127.0.0.1:1", "com.example.text").await,
            error("Could not call com.example.text on 127.0.0.1: could not connect")
        );
        assert_eq!(
            call("nowhere", "com.example.text").await,
            error("nowhere is not a usable endpoint")
        );
        // With sign-in on, a query refused for want of an account asks for it.
        let (signing, url) = served(true).await;
        assert_eq!(
            signing
                .call_query(Caller::Public, &url, &svc, "com.example.auth", &[])
                .await,
            Err(Refusal::SignIn)
        );
        assert_eq!(
            signing
                .call_query(Caller::Public, &url, &svc, "com.example.required", &[])
                .await,
            Err(Refusal::SignIn)
        );
    }

    #[tokio::test]
    async fn described_defs_found_and_bounded() {
        let (hud, _) = served(false).await;
        let refs = |refs: Vec<String>| {
            let props: Map<String, Value> = refs
                .into_iter()
                .enumerate()
                .map(|(i, r)| (format!("p{i:03}"), json!({ "type": "ref", "ref": r })))
                .collect();
            json!({ "parameters": { "type": "params", "properties": props } })
        };
        // Those that resolve, alone.
        let def = refs(vec![
            "com.atproto.repo.strongRef".into(),
            "com.atproto.repo.strongRef#nothere".into(),
            "com.example.none#x".into(),
        ]);
        let found = hud.described_defs("com.example.q", &def).await;
        assert_eq!(
            found.keys().collect::<Vec<_>>(),
            ["com.atproto.repo.strongRef#main"]
        );
        // At most 60.
        let many: Vec<String> = crate::lexicon::all_bundled()
            .flat_map(|d| {
                let id = d["id"].as_str().unwrap().to_string();
                let names: Vec<String> = d["defs"].as_object().unwrap().keys().cloned().collect();
                names.into_iter().map(move |k| format!("{id}#{k}"))
            })
            .take(70)
            .collect();
        assert_eq!(
            hud.described_defs("com.example.q", &refs(many)).await.len(),
            DESCRIBED_MAX
        );
    }

    #[tokio::test]
    async fn queries_as_the_account_name_the_scope_they_lack() {
        let lacking = || async {
            (
                axum::http::StatusCode::FORBIDDEN,
                r#"{"error":"ScopeMissingError"}"#,
            )
        };
        let app = axum::Router::new().route("/xrpc/{method}", axum::routing::get(lacking));
        let pds = crate::tests::serve(app).await;
        let (hud, account) = crate::tests::signed_in("http://127.0.0.1:1", &pds);
        // A service HUD asks to call as the account (`scope::calls`).
        let svc = Service::parse(crate::interactions::APPVIEW).unwrap();
        assert_eq!(
            hud.call_query(Caller::Account(&account), &pds, &svc, "com.example.q", &[])
                .await,
            Err(Refusal::Error(
                "Your sign-in does not allow rpc:com.example.q?aud=did:web:api.bsky.app%23bsky_appview"
                    .into()
            ))
        );
    }

    #[tokio::test]
    async fn queries_of_a_service_not_called_as_the_account_say_so() {
        let wanting = || async {
            (
                axum::http::StatusCode::UNAUTHORIZED,
                r#"{"error":"AuthMissing"}"#,
            )
        };
        let app = axum::Router::new().route("/xrpc/{method}", axum::routing::get(wanting));
        let endpoint = crate::tests::serve(app).await;
        let (hud, account) = crate::tests::signed_in("http://127.0.0.1:1", &endpoint);
        // A service HUD doesn't ask to call as the account: called as no
        // one, and wanting an account, it says HUD won't call it as you.
        let svc = Service::parse("did:web:api.example#svc").unwrap();
        assert_eq!(
            hud.call_query(Caller::Account(&account), &endpoint, &svc, "com.example.q", &[])
                .await,
            Err(Refusal::Error(
                "com.example.q needs an account, and HUD does not call did:web:api.example#svc as you"
                    .into()
            ))
        );
    }

    /// Answers kept a while for whoever asked alone, each asked once for
    /// all asking it at once; an error never kept; a fresh ask asked anew
    /// and kept for no one; an account's write forgets its own.
    #[tokio::test]
    async fn answers_kept_for_whoever_asked() {
        type Counts = Arc<std::sync::Mutex<std::collections::HashMap<String, u64>>>;
        async fn answer(
            axum::extract::Path(path): axum::extract::Path<String>,
            axum::extract::State((url, counts)): axum::extract::State<(String, Counts)>,
        ) -> axum::response::Response {
            use axum::response::IntoResponse;
            let n = {
                let mut counts = counts.lock().unwrap();
                let n = counts.entry(path.clone()).or_default();
                *n += 1;
                *n
            };
            match path.as_str() {
                SERVICE => axum::Json(json!({ "id": SERVICE, "service": [
                    { "id": "#svc", "type": "X", "serviceEndpoint": url }] }))
                .into_response(),
                "com.example.down" => axum::http::StatusCode::INTERNAL_SERVER_ERROR.into_response(),
                _ => {
                    tokio::time::sleep(Duration::from_millis(50)).await;
                    axum::Json(json!({ "n": n })).into_response()
                }
            }
        }
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let url = format!("http://{}", listener.local_addr().unwrap());
        let counts = Counts::default();
        let app = axum::Router::new()
            .route("/xrpc/{path}", axum::routing::get(answer))
            .route("/{path}", axum::routing::get(answer))
            .with_state((url.clone(), counts.clone()));
        tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
        let (hud, alice) = crate::tests::signed_in(&url, &url);
        let auth = hud.oauth.as_ref().unwrap();
        let bob = "did:plc:bobbobbobbobbobbobbobbob";
        let bob = auth
            .account(&auth.signed_in_offline_at(bob, Some("bob.test"), false, &url))
            .unwrap();
        let svc = Service::parse(&format!("{SERVICE}#svc")).unwrap();
        let ask = async |caller: Caller<'_>, method: &str, given: &[(&str, &str)], fresh: bool| {
            let pairs = given.iter().map(|(k, v)| (k.to_string(), v.to_string()));
            let asker = As { hud: &hud, caller };
            let asked = asker.call(&svc, method, pairs.collect(), fresh).await;
            asked.map(|(v, _)| v["n"].as_u64().unwrap())
        };
        let q = [("limit", "2"), ("actor", "a")];
        let (public, alice, bob) = (
            Caller::Public,
            Caller::Account(&alice),
            Caller::Account(&bob),
        );
        // Asked as no one, kept; the same params in another order alike.
        assert_eq!(ask(public, "com.example.q", &q, false).await, Ok(1));
        let swapped = [("actor", "a"), ("limit", "2")];
        assert_eq!(ask(public, "com.example.q", &swapped, false).await, Ok(1));
        // Each account asks for itself.
        assert_eq!(ask(alice, "com.example.q", &q, false).await, Ok(2));
        assert_eq!(ask(alice, "com.example.q", &q, false).await, Ok(2));
        assert_eq!(ask(bob, "com.example.q", &q, false).await, Ok(3));
        // Fresh: asked anew, and kept for no one.
        assert_eq!(ask(public, "com.example.q", &q, true).await, Ok(4));
        assert_eq!(ask(public, "com.example.q", &q, false).await, Ok(1));
        // Alice's write forgets hers alone.
        hud.wrote(crate::tests::ALICE);
        assert_eq!(ask(alice, "com.example.q", &q, false).await, Ok(5));
        assert_eq!(ask(bob, "com.example.q", &q, false).await, Ok(3));
        assert_eq!(ask(public, "com.example.q", &q, false).await, Ok(1));
        // Three asking at once: one call.
        let three = (0..3).map(|_| ask(public, "com.example.slow", &[], false));
        let three = futures::future::join_all(three).await;
        assert_eq!(three, [Ok(1), Ok(1), Ok(1)]);
        // An error is not kept.
        for _ in 0..2 {
            let down = ask(public, "com.example.down", &[], false).await;
            assert!(matches!(down, Err(Refusal::Error(e)) if e.ends_with("(500)")));
        }
        let counts = counts.lock().unwrap();
        assert_eq!(
            (counts["com.example.slow"], counts["com.example.down"]),
            (1, 2)
        );
    }
}