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

johnandersen777.bsky.social/vuln-notif

0
0
main
1290 lines · 40.6 KB Raw History
//! PDS transport facade and publisher.
//!
//! [`Publisher`] owns the session manager and the retry/rate-limit loops; the
//! [`PdsApi`] seam keeps raw XRPC responses (status, headers, body and bytes)
//! so a `429`, a `401`, a `404` and a server-side `too large` are decisions the
//! publisher makes, not exceptions some typed helper already swallowed.

pub mod error;
pub mod governor;
pub mod session;

use std::collections::HashMap;
use std::fmt;
use std::sync::Arc;
use std::time::{Duration, Instant};

use async_trait::async_trait;
use serde_json::{Value, json};

use atproto_client::client::{AppPasswordAuth, Auth, CallLimits, DpopBody, xrpc_call_with_limits};
use atproto_client::reqwest::header::{HeaderMap, HeaderValue};
use atproto_client::reqwest::{Client, Method};
use atproto_identity::resolve::{HickoryDnsResolver, resolve_did_document, resolve_subject};
use atproto_identity::url::build_url;

pub use error::{PdsError, PdsErrorKind};
pub use governor::RateGovernor;
pub use session::Session;

use crate::constants::{
    BLOB_MIME, MAX_ATTEMPTS, MAX_RATE_LIMIT_ATTEMPTS, PDS_WRITE_CREATE, PDS_WRITE_DELETE,
    PDS_WRITE_PUT, RECORD_TARGET, RETRY_DELAYS,
};
use crate::db::model::CveRow;
use crate::log::{Level, Logger};
use crate::publish::{PublishOutcome, RecordRef};
use crate::records::{PreparedRow, cbor_bytes, sanitize_rkey};
use crate::time::{RealTime, Time};

use error::{classify_at, log_rate_limited, rate_limit_delay_from_headers};

/// Raw XRPC response preserving status, headers, body, and bytes.
#[derive(Debug, Clone, Default)]
pub struct XrpcResponse {
    pub status: u16,
    pub headers: HashMap<String, String>,
    pub body: Value,
    pub bytes: Vec<u8>,
}

impl XrpcResponse {
    /// Body as text for the classifier: the raw bytes when present, else the
    /// JSON rendering. Never logged.
    pub fn text(&self) -> String {
        if !self.bytes.is_empty() {
            String::from_utf8_lossy(&self.bytes).into_owned()
        } else if !self.body.is_null() {
            self.body.to_string()
        } else {
            String::new()
        }
    }
}

/// One page of `com.atproto.repo.listRecords`. The cursor is opaque to the
/// caller: pass it back to fetch the next page, `None` means the end.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct RecordPage {
    pub records: Vec<RecordItem>,
    pub cursor: Option<String>,
}

/// One record returned by `listRecords`.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct RecordItem {
    pub uri: String,
    pub cid: String,
    pub value: Value,
}

/// Low-level PDS transport seam (app-password + raw XRPC calls).
///
/// Session methods return the raw response as well: `createSession` answers
/// `429` with rate-limit headers that a typed helper would discard. Every
/// repository method takes the access JWT the caller resolved through
/// [`SessionManager`](session::SessionManager), so the fake used in tests sees
/// exactly which credential each retry used.
#[async_trait]
pub trait PdsApi: Send + Sync {
    async fn create_session(&self, handle: &str, password: &str) -> anyhow::Result<XrpcResponse>;
    async fn refresh_session(&self, refresh_jwt: &str) -> anyhow::Result<XrpcResponse>;
    async fn get_record(
        &self,
        repo: &str,
        collection: &str,
        rkey: &str,
        access_jwt: &str,
    ) -> anyhow::Result<XrpcResponse>;
    async fn create_record(
        &self,
        repo: &str,
        collection: &str,
        rkey: &str,
        record: &Value,
        access_jwt: &str,
    ) -> anyhow::Result<XrpcResponse>;
    async fn put_record(
        &self,
        repo: &str,
        collection: &str,
        rkey: &str,
        record: &Value,
        access_jwt: &str,
    ) -> anyhow::Result<XrpcResponse>;
    async fn apply_writes(
        &self,
        repo: &str,
        writes: &[Value],
        access_jwt: &str,
    ) -> anyhow::Result<XrpcResponse>;
    /// One page of records. Defaulted so existing transports (and fakes) keep
    /// compiling; a transport without the endpoint reports `unsupported`.
    async fn list_records(
        &self,
        _repo: &str,
        _collection: &str,
        _cursor: Option<&str>,
        _limit: Option<usize>,
        _access_jwt: &str,
    ) -> anyhow::Result<XrpcResponse> {
        Err(unsupported("listRecords"))
    }
    /// Delete one record. Defaulted so existing transports keep compiling.
    async fn delete_record(
        &self,
        _repo: &str,
        _collection: &str,
        _rkey: &str,
        _access_jwt: &str,
    ) -> anyhow::Result<XrpcResponse> {
        Err(unsupported("deleteRecord"))
    }
    async fn upload_blob(
        &self,
        bytes: &[u8],
        mime_type: &str,
        access_jwt: &str,
    ) -> anyhow::Result<XrpcResponse>;
}

/// Handle/DID to PDS endpoint resolution seam.
#[async_trait]
pub trait PdsResolver: Send + Sync {
    async fn resolve_handle(&self, handle: &str) -> anyhow::Result<String>;
    async fn resolve_pds(&self, did: &str) -> anyhow::Result<String>;
}

#[derive(Clone)]
pub struct PublisherConfig {
    pub pds_url: String,
    pub handle: String,
    pub app_password: String,
    pub collection: String,
    pub timeout_secs: f64,
    pub governor: Arc<RateGovernor>,
}

impl fmt::Debug for PublisherConfig {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("PublisherConfig")
            .field("pds_url", &self.pds_url)
            .field("handle", &self.handle)
            .field("app_password", &"<redacted>")
            .field("collection", &self.collection)
            .field("timeout_secs", &self.timeout_secs)
            .finish()
    }
}

/// Real PDS transport: raw XRPC calls with the status and headers intact.
struct RealPdsApi {
    pds_url: String,
    timeout: Duration,
    http: Client,
}

impl RealPdsApi {
    fn new(pds_url: String, timeout_secs: f64) -> anyhow::Result<Self> {
        let http = Client::builder().build()?;
        let timeout = Duration::from_secs_f64(if timeout_secs > 0.0 {
            timeout_secs
        } else {
            60.0
        });
        Ok(Self {
            pds_url,
            timeout,
            http,
        })
    }

    fn limits(&self) -> CallLimits {
        CallLimits::with_timeout(self.timeout)
    }

    fn app_auth(access_jwt: &str) -> Auth {
        Auth::AppPassword(AppPasswordAuth {
            access_token: access_jwt.to_owned(),
        })
    }

    async fn call(
        &self,
        method: Method,
        nsid: &str,
        params: &[(&str, &str)],
        body: Option<&Value>,
        auth: &Auth,
        headers: &HeaderMap,
    ) -> anyhow::Result<XrpcResponse> {
        let url = build_url(
            &self.pds_url,
            &format!("/xrpc/{nsid}"),
            params.iter().copied(),
        )?;
        let dpop_body = body.map(DpopBody::Json);
        let response = xrpc_call_with_limits(
            &self.http,
            auth,
            method,
            url.as_str(),
            dpop_body,
            headers,
            self.limits(),
        )
        .await?;
        Ok(convert_response(response))
    }
}

fn convert_response(response: atproto_client::client::XrpcResponse) -> XrpcResponse {
    let headers = response
        .headers
        .iter()
        .map(|(name, value)| {
            (
                name.as_str().to_owned(),
                String::from_utf8_lossy(value.as_bytes()).into_owned(),
            )
        })
        .collect();
    XrpcResponse {
        status: response.status.as_u16(),
        headers,
        body: response.body.unwrap_or(Value::Null),
        bytes: response.bytes.to_vec(),
    }
}

#[async_trait]
impl PdsApi for RealPdsApi {
    async fn create_session(&self, handle: &str, password: &str) -> anyhow::Result<XrpcResponse> {
        let body = json!({ "identifier": handle, "password": password });
        self.call(
            Method::POST,
            "com.atproto.server.createSession",
            &[],
            Some(&body),
            &Auth::None,
            &HeaderMap::new(),
        )
        .await
    }

    async fn refresh_session(&self, refresh_jwt: &str) -> anyhow::Result<XrpcResponse> {
        let mut headers = HeaderMap::new();
        headers.insert(
            atproto_client::reqwest::header::AUTHORIZATION,
            HeaderValue::from_str(&format!("Bearer {refresh_jwt}"))?,
        );
        self.call(
            Method::POST,
            "com.atproto.server.refreshSession",
            &[],
            None,
            &Auth::None,
            &headers,
        )
        .await
    }

    async fn get_record(
        &self,
        repo: &str,
        collection: &str,
        rkey: &str,
        access_jwt: &str,
    ) -> anyhow::Result<XrpcResponse> {
        self.call(
            Method::GET,
            "com.atproto.repo.getRecord",
            &[("repo", repo), ("collection", collection), ("rkey", rkey)],
            None,
            &Self::app_auth(access_jwt),
            &HeaderMap::new(),
        )
        .await
    }

    async fn create_record(
        &self,
        repo: &str,
        collection: &str,
        rkey: &str,
        record: &Value,
        access_jwt: &str,
    ) -> anyhow::Result<XrpcResponse> {
        let body = json!({
            "repo": repo,
            "collection": collection,
            "rkey": rkey,
            "record": record,
        });
        self.call(
            Method::POST,
            "com.atproto.repo.createRecord",
            &[],
            Some(&body),
            &Self::app_auth(access_jwt),
            &HeaderMap::new(),
        )
        .await
    }

    async fn put_record(
        &self,
        repo: &str,
        collection: &str,
        rkey: &str,
        record: &Value,
        access_jwt: &str,
    ) -> anyhow::Result<XrpcResponse> {
        let body = json!({
            "repo": repo,
            "collection": collection,
            "rkey": rkey,
            "record": record,
        });
        self.call(
            Method::POST,
            "com.atproto.repo.putRecord",
            &[],
            Some(&body),
            &Self::app_auth(access_jwt),
            &HeaderMap::new(),
        )
        .await
    }

    async fn apply_writes(
        &self,
        repo: &str,
        writes: &[Value],
        access_jwt: &str,
    ) -> anyhow::Result<XrpcResponse> {
        let body = json!({ "repo": repo, "writes": writes });
        self.call(
            Method::POST,
            "com.atproto.repo.applyWrites",
            &[],
            Some(&body),
            &Self::app_auth(access_jwt),
            &HeaderMap::new(),
        )
        .await
    }

    async fn list_records(
        &self,
        repo: &str,
        collection: &str,
        cursor: Option<&str>,
        limit: Option<usize>,
        access_jwt: &str,
    ) -> anyhow::Result<XrpcResponse> {
        let limit = limit.map(|value| value.to_string());
        let mut params = vec![("repo", repo), ("collection", collection)];
        if let Some(cursor) = cursor {
            params.push(("cursor", cursor));
        }
        if let Some(limit) = limit.as_deref() {
            params.push(("limit", limit));
        }
        self.call(
            Method::GET,
            "com.atproto.repo.listRecords",
            &params,
            None,
            &Self::app_auth(access_jwt),
            &HeaderMap::new(),
        )
        .await
    }

    async fn delete_record(
        &self,
        repo: &str,
        collection: &str,
        rkey: &str,
        access_jwt: &str,
    ) -> anyhow::Result<XrpcResponse> {
        let body = json!({
            "repo": repo,
            "collection": collection,
            "rkey": rkey,
        });
        self.call(
            Method::POST,
            "com.atproto.repo.deleteRecord",
            &[],
            Some(&body),
            &Self::app_auth(access_jwt),
            &HeaderMap::new(),
        )
        .await
    }

    async fn upload_blob(
        &self,
        bytes: &[u8],
        mime_type: &str,
        access_jwt: &str,
    ) -> anyhow::Result<XrpcResponse> {
        let url = build_url(
            &self.pds_url,
            "/xrpc/com.atproto.repo.uploadBlob",
            std::iter::empty::<(&str, &str)>(),
        )?;
        let response = xrpc_call_with_limits(
            &self.http,
            &Self::app_auth(access_jwt),
            Method::POST,
            url.as_str(),
            Some(DpopBody::Bytes {
                content_type: mime_type,
                data: bytes.to_vec(),
            }),
            &HeaderMap::new(),
            self.limits(),
        )
        .await?;
        Ok(convert_response(response))
    }
}

/// Repository writer facade (mirrors the reference publisher surface).
pub struct Publisher {
    config: PublisherConfig,
    api: Arc<dyn PdsApi>,
    sessions: session::SessionManager,
    logger: Logger,
    time: Arc<dyn Time>,
}

impl Publisher {
    /// Build the real transport from `config.timeout_secs`.
    pub fn new(config: PublisherConfig) -> anyhow::Result<Self> {
        let api: Arc<dyn PdsApi> = Arc::new(RealPdsApi::new(
            config.pds_url.clone(),
            config.timeout_secs,
        )?);
        Self::with_api(config, api, Logger::stderr(Level::Info), Arc::new(RealTime))
    }

    /// Inject a transport, logger and clock (tests, or a runtime fake).
    pub fn with_api(
        config: PublisherConfig,
        api: Arc<dyn PdsApi>,
        logger: Logger,
        time: Arc<dyn Time>,
    ) -> anyhow::Result<Self> {
        let sessions = session::SessionManager::new(
            api.clone(),
            config.handle.clone(),
            config.app_password.clone(),
            config.governor.clone(),
            logger.clone(),
            time.clone(),
        );
        Ok(Self {
            config,
            api,
            sessions,
            logger,
            time,
        })
    }

    pub async fn login(&self) -> anyhow::Result<()> {
        self.sessions.login().await.map(|_| ())
    }

    /// getRecord only: found, missing (error `None`), and hard errors.
    pub async fn check_row(&self, row: &CveRow) -> anyhow::Result<PublishOutcome> {
        let mut outcome = PublishOutcome {
            cve_id: Some(row.id.clone()),
            ..PublishOutcome::default()
        };
        outcome.get_ops = 1;
        let rkey = sanitize_rkey(&row.id);
        let call = RepoCall::Get {
            repo: self.repo(),
            collection: self.collection(),
            rkey: &rkey,
        };
        let result = self
            .request(&call, 0, "getRecord", Some(&row.id), None)
            .await?;
        merge_outcome(&mut outcome, result.outcome);
        match result.error {
            None => {
                outcome.found = true;
                if let Some(response) = &result.response {
                    outcome.uri = body_field(&response.body, "uri");
                    outcome.cid = body_field(&response.body, "cid");
                }
            }
            Some(error) if error.kind == PdsErrorKind::NotFound => {}
            Some(error) => outcome.error = Some(format!("getRecord: {error}")),
        }
        Ok(outcome)
    }

    /// createRecord for one prepared row (no getRecord).
    pub async fn create_row(&self, prepared: &PreparedRow) -> anyhow::Result<PublishOutcome> {
        let mut outcome = PublishOutcome {
            cve_id: Some(prepared.cve_id.clone()),
            ..PublishOutcome::default()
        };
        outcome.create_ops = 1;
        let rkey = sanitize_rkey(&prepared.cve_id);
        let call = RepoCall::Create {
            repo: self.repo(),
            collection: self.collection(),
            rkey: &rkey,
            record: &prepared.record,
        };
        let result = self
            .request(
                &call,
                PDS_WRITE_CREATE as u64,
                "createRecord",
                Some(&prepared.cve_id),
                None,
            )
            .await?;
        merge_outcome(&mut outcome, result.outcome);
        match result.error {
            None => {
                outcome.created = true;
                if let Some(response) = &result.response {
                    outcome.uri = body_field(&response.body, "uri");
                    outcome.cid = body_field(&response.body, "cid");
                }
                outcome.record_bytes = prepared.record_bytes;
            }
            Some(error) if error.kind == PdsErrorKind::AlreadyExists => outcome.found = true,
            Some(error) if error.kind == PdsErrorKind::TooLarge => {
                outcome.skipped = true;
                outcome.error = Some(error.to_string());
            }
            Some(error) => outcome.error = Some(format!("createRecord: {error}")),
        }
        Ok(outcome)
    }

    /// Upload the full-CVE blob, then create the pointer record.
    pub async fn create_large_row(&self, prepared: &PreparedRow) -> anyhow::Result<PublishOutcome> {
        let Some(blob) = prepared.blob.as_deref() else {
            return Ok(PublishOutcome {
                cve_id: Some(prepared.cve_id.clone()),
                error: Some("missing blob payload".to_owned()),
                ..PublishOutcome::default()
            });
        };
        let mut outcome = PublishOutcome {
            cve_id: Some(prepared.cve_id.clone()),
            oversized: true,
            blob_ops: 1,
            blob_bytes: blob.len() as u64,
            ..PublishOutcome::default()
        };

        let upload = RepoCall::Upload {
            bytes: blob,
            mime: BLOB_MIME,
        };
        let uploaded = self
            .request(&upload, 0, "uploadBlob", Some(&prepared.cve_id), None)
            .await?;
        merge_outcome(&mut outcome, uploaded.outcome);
        if let Some(error) = uploaded.error {
            outcome.skipped = false;
            outcome.error = Some(format!("uploadBlob: {error}"));
            return Ok(outcome);
        }

        let blob_ref = normalize_blob_ref(
            uploaded
                .response
                .as_ref()
                .and_then(|response| response.body.get("blob"))
                .unwrap_or(&Value::Null),
            BLOB_MIME,
            blob.len(),
        );
        outcome.blob_cid = blob_ref
            .get("ref")
            .and_then(|reference| reference.get("$link"))
            .and_then(Value::as_str)
            .map(str::to_owned);

        let mut record = prepared.record.clone();
        if let Value::Object(map) = &mut record {
            map.insert("dataBlob".to_owned(), blob_ref);
        }
        match cbor_bytes(&record) {
            Ok(bytes) => {
                outcome.record_bytes = bytes.len() as u64;
                if bytes.len() > RECORD_TARGET {
                    outcome.error =
                        Some(format!("compact record too large: {} bytes", bytes.len()));
                    return Ok(outcome);
                }
            }
            Err(error) => {
                outcome.error = Some(format!("encode compact record: {error}"));
                return Ok(outcome);
            }
        }

        outcome.create_ops = 1;
        let rkey = sanitize_rkey(&prepared.cve_id);
        let call = RepoCall::Create {
            repo: self.repo(),
            collection: self.collection(),
            rkey: &rkey,
            record: &record,
        };
        let result = self
            .request(
                &call,
                PDS_WRITE_CREATE as u64,
                "createRecord",
                Some(&prepared.cve_id),
                None,
            )
            .await?;
        merge_outcome(&mut outcome, result.outcome);
        match result.error {
            None => {
                outcome.created = true;
                if let Some(response) = &result.response {
                    outcome.uri = body_field(&response.body, "uri");
                    outcome.cid = body_field(&response.body, "cid");
                }
            }
            Some(error) if error.kind == PdsErrorKind::AlreadyExists => outcome.found = true,
            Some(error) => outcome.error = Some(format!("createRecord: {error}")),
        }
        Ok(outcome)
    }

    /// Idempotent putRecord for index/software/release records.
    pub async fn put_record(
        &self,
        collection: &str,
        rkey: &str,
        record: Value,
    ) -> anyhow::Result<PublishOutcome> {
        let mut outcome = PublishOutcome {
            cve_id: Some(rkey.to_owned()),
            ..PublishOutcome::default()
        };
        outcome.create_ops = 1;
        let call = RepoCall::Put {
            repo: self.repo(),
            collection,
            rkey,
            record: &record,
        };
        let result = self
            .request(&call, PDS_WRITE_PUT as u64, "putRecord", Some(rkey), None)
            .await?;
        merge_outcome(&mut outcome, result.outcome);
        match result.error {
            None => {
                outcome.created = true;
                if let Some(response) = &result.response {
                    outcome.uri = body_field(&response.body, "uri");
                    outcome.cid = body_field(&response.body, "cid");
                }
                outcome.record_bytes = cbor_bytes(&record)
                    .map(|bytes| bytes.len() as u64)
                    .unwrap_or(0);
            }
            Some(error) => outcome.error = Some(format!("putRecord: {error}")),
        }
        Ok(outcome)
    }

    /// One page of `listRecords`; a read, so it reserves no write points.
    pub async fn list_records(
        &self,
        collection: &str,
        cursor: Option<&str>,
        limit: Option<usize>,
    ) -> anyhow::Result<RecordPage> {
        let call = RepoCall::List {
            repo: self.repo(),
            collection,
            cursor,
            limit,
        };
        let result = self.request(&call, 0, "listRecords", None, None).await?;
        if let Some(error) = result.error {
            return Err(error.into());
        }
        let response = result
            .response
            .ok_or_else(|| anyhow::anyhow!("listRecords returned no response"))?;
        Ok(parse_record_page(&response.body))
    }

    /// Upload artifact bytes as a blob and return the normalized blob ref.
    ///
    /// Blob uploads are charged zero write points.
    pub async fn upload_blob(&self, bytes: &[u8], mime_type: &str) -> anyhow::Result<Value> {
        let call = RepoCall::Upload {
            bytes,
            mime: mime_type,
        };
        let result = self.request(&call, 0, "uploadBlob", None, None).await?;
        if let Some(error) = result.error {
            return Err(error.into());
        }
        let response = result
            .response
            .ok_or_else(|| anyhow::anyhow!("uploadBlob returned no response"))?;
        Ok(normalize_blob_ref(
            response.body.get("blob").unwrap_or(&Value::Null),
            mime_type,
            bytes.len(),
        ))
    }

    /// Delete one record. A missing record is not an error: `found` stays
    /// false and `error` stays `None`.
    pub async fn delete_record(
        &self,
        collection: &str,
        rkey: &str,
    ) -> anyhow::Result<PublishOutcome> {
        let mut outcome = PublishOutcome {
            cve_id: Some(rkey.to_owned()),
            ..PublishOutcome::default()
        };
        let call = RepoCall::Delete {
            repo: self.repo(),
            collection,
            rkey,
        };
        let result = self
            .request(
                &call,
                PDS_WRITE_DELETE as u64,
                "deleteRecord",
                Some(rkey),
                None,
            )
            .await?;
        merge_outcome(&mut outcome, result.outcome);
        match result.error {
            None => {
                outcome.found = true;
                outcome.uri = Some(format!("at://{}/{collection}/{rkey}", self.repo()));
                outcome.cid = result
                    .response
                    .as_ref()
                    .and_then(|response| response.body.get("commit"))
                    .and_then(|commit| commit.get("cid"))
                    .and_then(Value::as_str)
                    .map(str::to_owned);
            }
            Some(error) if error.kind == PdsErrorKind::NotFound => {}
            Some(error) => outcome.error = Some(format!("deleteRecord: {error}")),
        }
        Ok(outcome)
    }

    /// `applyWrites` for any mix of create/update/delete ops, charged per op.
    pub async fn apply_writes(&self, writes: Vec<Value>) -> anyhow::Result<PublishOutcome> {
        let mut outcome = PublishOutcome::default();
        let call = RepoCall::Apply {
            repo: self.repo(),
            writes: &writes,
        };
        let result = self
            .request(&call, apply_write_cost(&writes), "applyWrites", None, None)
            .await?;
        merge_outcome(&mut outcome, result.outcome);
        if let Some(error) = result.error {
            outcome.error = Some(format!("applyWrites: {error}"));
        }
        Ok(outcome)
    }

    /// Create rows atomically with applyWrites. `None` results mean the PDS
    /// omitted (or misaligned) `results`, so the caller must verify another
    /// way.
    pub async fn create_batch(
        &self,
        rows: &[PreparedRow],
    ) -> anyhow::Result<(PublishOutcome, Option<Vec<RecordRef>>)> {
        let mut outcome = PublishOutcome {
            create_ops: 1,
            ..PublishOutcome::default()
        };
        let writes: Vec<Value> = rows
            .iter()
            .map(|prepared| {
                json!({
                    "$type": "com.atproto.repo.applyWrites#create",
                    "collection": self.collection(),
                    "rkey": sanitize_rkey(&prepared.cve_id),
                    "value": prepared.record,
                })
            })
            .collect();
        let call = RepoCall::Apply {
            repo: self.repo(),
            writes: &writes,
        };
        let result = self
            .request(
                &call,
                PDS_WRITE_CREATE as u64 * writes.len() as u64,
                "applyWrites",
                None,
                None,
            )
            .await?;
        merge_outcome(&mut outcome, result.outcome);
        let Some(error) = result.error else {
            let refs = result
                .response
                .as_ref()
                .and_then(|response| response.body.get("results"))
                .and_then(|results| parse_results(results, writes.len()));
            return Ok((outcome, refs));
        };
        outcome.error = Some(format!("applyWrites: {error}"));
        Ok((outcome, None))
    }

    pub async fn close(&self) -> anyhow::Result<()> {
        Ok(())
    }

    pub fn repo(&self) -> &str {
        self.sessions.repo()
    }

    pub fn collection(&self) -> &str {
        &self.config.collection
    }

    pub fn login_calls(&self) -> u64 {
        self.sessions.login_calls()
    }

    async fn request(
        &self,
        call: &RepoCall<'_>,
        write_cost: u64,
        op: &str,
        cve: Option<&str>,
        slug: Option<&str>,
    ) -> anyhow::Result<AttemptResult> {
        let mut total = PublishOutcome::default();
        let mut rate_attempts = 0u32;
        loop {
            let mut part = self.attempt(call, write_cost, op, cve, slug).await?;
            let headers = std::mem::take(&mut part.headers);
            merge_outcome(&mut total, part.outcome);
            match part.error {
                None => {
                    return Ok(AttemptResult {
                        response: part.response,
                        outcome: total,
                        error: None,
                        headers,
                    });
                }
                Some(error) if error.kind == PdsErrorKind::RateLimited => {
                    rate_attempts += 1;
                    if rate_attempts >= MAX_RATE_LIMIT_ATTEMPTS {
                        return Ok(AttemptResult {
                            response: None,
                            outcome: total,
                            error: Some(error),
                            headers,
                        });
                    }
                    let delay =
                        rate_limit_delay_from_headers(&error, &headers, rate_attempts, &*self.time);
                    log_rate_limited(
                        &self.logger,
                        &error,
                        &headers,
                        op,
                        cve,
                        slug,
                        delay,
                        rate_attempts,
                    );
                    total.retries += 1;
                    self.config.governor.record_wait(delay);
                    self.time.sleep(Duration::from_secs_f64(delay)).await;
                }
                Some(error) => {
                    return Ok(AttemptResult {
                        response: None,
                        outcome: total,
                        error: Some(error),
                        headers,
                    });
                }
            }
        }
    }

    async fn attempt(
        &self,
        call: &RepoCall<'_>,
        write_cost: u64,
        op: &str,
        cve: Option<&str>,
        slug: Option<&str>,
    ) -> anyhow::Result<AttemptResult> {
        let mut outcome = PublishOutcome::default();
        let mut attempt = 1u32;
        while attempt <= MAX_ATTEMPTS {
            let (access_jwt, generation) = match self.sessions.snapshot().await {
                Some((session, generation)) => (session.access_jwt, generation),
                None => {
                    let session = self.sessions.login().await?;
                    (session.access_jwt, self.sessions.generation().await)
                }
            };

            if write_cost > 0 {
                self.config
                    .governor
                    .reserve_write(write_cost as f64, op, cve, slug)
                    .await?;
            }
            self.config.governor.request().await?;

            let started = Instant::now();
            let result = call.execute(&*self.api, &access_jwt).await;
            outcome.durations.push(started.elapsed().as_secs_f64());
            outcome.calls += 1;

            match result {
                Ok(response) => {
                    if session::is_success(response.status) {
                        return Ok(AttemptResult {
                            response: Some(response),
                            outcome,
                            error: None,
                            headers: HashMap::new(),
                        });
                    }
                    let error = classify_at(
                        Some(response.status),
                        &response.headers,
                        &response.text(),
                        None,
                        self.time.now_unix(),
                    );
                    match error.kind {
                        PdsErrorKind::Unauthorized if attempt < MAX_ATTEMPTS => {
                            let headers = response.headers.clone();
                            if let Err(login_error) =
                                self.sessions.reauth(&access_jwt, generation).await
                            {
                                return Ok(AttemptResult {
                                    response: None,
                                    outcome,
                                    error: Some(session::error_from_message(
                                        login_error.to_string(),
                                    )),
                                    headers,
                                });
                            }
                            outcome.retries += 1;
                            attempt += 1;
                            continue;
                        }
                        PdsErrorKind::TooLarge => {
                            outcome.skipped = true;
                            return Ok(AttemptResult {
                                response: None,
                                outcome,
                                error: Some(error),
                                headers: response.headers,
                            });
                        }
                        PdsErrorKind::Transient if attempt < MAX_ATTEMPTS => {
                            outcome.retries += 1;
                            let delay = RETRY_DELAYS[(attempt - 1) as usize];
                            self.time.sleep(Duration::from_secs_f64(delay)).await;
                            attempt += 1;
                            continue;
                        }
                        _ => {
                            return Ok(AttemptResult {
                                response: None,
                                outcome,
                                error: Some(error),
                                headers: response.headers,
                            });
                        }
                    }
                }
                Err(transport) => {
                    if attempt < MAX_ATTEMPTS {
                        outcome.retries += 1;
                        let delay = RETRY_DELAYS[(attempt - 1) as usize];
                        self.time.sleep(Duration::from_secs_f64(delay)).await;
                        attempt += 1;
                        continue;
                    }
                    let error = classify_at(
                        None,
                        &HashMap::new(),
                        "",
                        Some(&transport.to_string()),
                        self.time.now_unix(),
                    );
                    return Ok(AttemptResult {
                        response: None,
                        outcome,
                        error: Some(error),
                        headers: HashMap::new(),
                    });
                }
            }
        }
        Ok(AttemptResult {
            response: None,
            outcome,
            error: None,
            headers: HashMap::new(),
        })
    }
}

enum RepoCall<'a> {
    Get {
        repo: &'a str,
        collection: &'a str,
        rkey: &'a str,
    },
    Create {
        repo: &'a str,
        collection: &'a str,
        rkey: &'a str,
        record: &'a Value,
    },
    Put {
        repo: &'a str,
        collection: &'a str,
        rkey: &'a str,
        record: &'a Value,
    },
    Apply {
        repo: &'a str,
        writes: &'a [Value],
    },
    List {
        repo: &'a str,
        collection: &'a str,
        cursor: Option<&'a str>,
        limit: Option<usize>,
    },
    Delete {
        repo: &'a str,
        collection: &'a str,
        rkey: &'a str,
    },
    Upload {
        bytes: &'a [u8],
        mime: &'a str,
    },
}

impl RepoCall<'_> {
    async fn execute(&self, api: &dyn PdsApi, access_jwt: &str) -> anyhow::Result<XrpcResponse> {
        match self {
            RepoCall::Get {
                repo,
                collection,
                rkey,
            } => api.get_record(repo, collection, rkey, access_jwt).await,
            RepoCall::Create {
                repo,
                collection,
                rkey,
                record,
            } => {
                api.create_record(repo, collection, rkey, record, access_jwt)
                    .await
            }
            RepoCall::Put {
                repo,
                collection,
                rkey,
                record,
            } => {
                api.put_record(repo, collection, rkey, record, access_jwt)
                    .await
            }
            RepoCall::Apply { repo, writes } => api.apply_writes(repo, writes, access_jwt).await,
            RepoCall::List {
                repo,
                collection,
                cursor,
                limit,
            } => {
                api.list_records(repo, collection, *cursor, *limit, access_jwt)
                    .await
            }
            RepoCall::Delete {
                repo,
                collection,
                rkey,
            } => api.delete_record(repo, collection, rkey, access_jwt).await,
            RepoCall::Upload { bytes, mime } => api.upload_blob(bytes, mime, access_jwt).await,
        }
    }
}

struct AttemptResult {
    response: Option<XrpcResponse>,
    outcome: PublishOutcome,
    error: Option<PdsError>,
    headers: HashMap<String, String>,
}

fn merge_outcome(target: &mut PublishOutcome, part: PublishOutcome) {
    target.calls += part.calls;
    target.retries += part.retries;
    target.skipped = target.skipped || part.skipped;
    target.blob_ops += part.blob_ops;
    target.blob_bytes += part.blob_bytes;
    target.oversized = target.oversized || part.oversized;
    target.record_bytes = target.record_bytes.max(part.record_bytes);
    target.durations.extend(part.durations);
}

fn body_field(body: &Value, key: &str) -> Option<String> {
    body.get(key).and_then(Value::as_str).map(str::to_owned)
}

fn parse_record_page(body: &Value) -> RecordPage {
    let records = body
        .get("records")
        .and_then(Value::as_array)
        .map(|items| {
            items
                .iter()
                .map(|item| RecordItem {
                    uri: body_field(item, "uri").unwrap_or_default(),
                    cid: body_field(item, "cid").unwrap_or_default(),
                    value: item.get("value").cloned().unwrap_or(Value::Null),
                })
                .collect()
        })
        .unwrap_or_default();
    RecordPage {
        records,
        cursor: body_field(body, "cursor"),
    }
}

/// applyWrites point cost: create/update = 3, delete = 1, per record.
fn apply_write_cost(writes: &[Value]) -> u64 {
    writes
        .iter()
        .map(|write| match write.get("$type").and_then(Value::as_str) {
            Some(kind) if kind.ends_with("#delete") => PDS_WRITE_DELETE as u64,
            Some(kind) if kind.ends_with("#update") => PDS_WRITE_PUT as u64,
            Some(_) => PDS_WRITE_CREATE as u64,
            None if write.get("value").is_some() => PDS_WRITE_CREATE as u64,
            None => PDS_WRITE_DELETE as u64,
        })
        .sum()
}

fn unsupported(op: &str) -> anyhow::Error {
    anyhow::anyhow!("{op}: unsupported by this PDS transport")
}

/// Normalize an uploadBlob answer into the reference the record stores:
/// `$type: "blob"`, `ref.{$link}`, `mimeType`, `size`.
fn normalize_blob_ref(blob: &Value, mime_type: &str, size: usize) -> Value {
    let mut reference = blob.as_object().cloned().unwrap_or_default();
    reference
        .entry("$type")
        .or_insert_with(|| Value::String("blob".to_owned()));
    if let Some(Value::String(link)) = reference.get("ref").cloned() {
        reference.insert("ref".to_owned(), json!({ "$link": link }));
    }
    reference
        .entry("mimeType")
        .or_insert_with(|| Value::String(mime_type.to_owned()));
    reference.entry("size").or_insert_with(|| Value::from(size));
    Value::Object(reference)
}

fn parse_results(results: &Value, expected: usize) -> Option<Vec<RecordRef>> {
    let Value::Array(items) = results else {
        return None;
    };
    if items.len() != expected {
        return None;
    }
    let mut refs = Vec::with_capacity(items.len());
    for item in items {
        refs.push(RecordRef {
            uri: item.get("uri")?.as_str()?.to_owned(),
            cid: item.get("cid")?.as_str()?.to_owned(),
        });
    }
    Some(refs)
}

/// Resolve a handle (or DID) to its atproto PDS endpoint.
///
/// `plc_url` is a hostname or URL; the resolver wants only the hostname.
pub async fn resolve_pds_url(handle_or_did: &str, plc_url: &str) -> anyhow::Result<String> {
    let http = Client::builder()
        .timeout(Duration::from_secs(10))
        .redirect(atproto_client::reqwest::redirect::Policy::none())
        .build()?;
    let did = if handle_or_did.starts_with("did:") {
        handle_or_did.to_owned()
    } else {
        let dns = HickoryDnsResolver::create_resolver(&[]);
        resolve_subject(&http, &dns, handle_or_did).await?
    };
    if did.is_empty() {
        anyhow::bail!("could not resolve handle {handle_or_did:?}");
    }
    let plc_hostname = plc_hostname(plc_url);
    let document = resolve_did_document(&http, &plc_hostname, &did).await?;
    let endpoint = document
        .pds_endpoints()
        .into_iter()
        .next()
        .ok_or_else(|| anyhow::anyhow!("DID {did} has no atproto_pds service endpoint"))?;
    Ok(endpoint.trim_end_matches('/').to_owned())
}

fn plc_hostname(plc_url: &str) -> String {
    let trimmed = plc_url.trim_end_matches('/');
    if let Ok(url) = atproto_client::reqwest::Url::parse(trimmed)
        && let Some(host) = url.host_str()
    {
        return host.to_owned();
    }
    trimmed
        .trim_start_matches("https://")
        .trim_start_matches("http://")
        .trim_end_matches('/')
        .to_owned()
}