use chrono::{DateTime, Utc}; use futures::future::BoxFuture; use serde_json::Value; use crate::{is_did, market_contract_held, verify_record, DidDoc, Error, Io, StrongRef}; pub type ContractHeldFn = Box) -> BoxFuture<'static, Result> + Send + Sync>; pub struct HttpIo { pub client: reqwest::Client, pub plc: String, pub contract_held: Option, } impl Default for HttpIo { fn default() -> Self { #[cfg(not(target_arch = "wasm32"))] let client = reqwest::Client::builder() .timeout(std::time::Duration::from_secs(10)) .build() .expect("reqwest client"); #[cfg(target_arch = "wasm32")] let client = reqwest::Client::new(); Self { client, plc: "https://plc.directory".into(), contract_held: None } } } impl Io for HttpIo { async fn resolve_did(&self, did: &str) -> Result, Error> { if !is_did(did) { return Err(format!("not a DID: {did}").into()); } let url = if did.starts_with("did:plc:") { format!("{}/{did}", self.plc) } else if let Some(host) = did.strip_prefix("did:web:").filter(|h| !h.contains(':')) { format!("https://{}/.well-known/did.json", host.replace("%3A", ":")) } else { return Err(format!("unsupported DID: {did}").into()); }; let res = self.client.get(url).send().await?; if matches!(res.status().as_u16(), 404 | 410) { return Ok(None); } let doc: DidDoc = serde_json::from_slice(&res.error_for_status()?.bytes().await?)?; if doc.id != did { return Err(format!("the DID doc for {did} names {}", doc.id).into()); } Ok(Some(doc)) } async fn get_record(&self, repo: &str, collection: &str, rkey: &str) -> Result, Error> { let Some(doc) = self.resolve_did(repo).await? else { return Ok(None); }; let pds = doc.pds().ok_or_else(|| format!("{repo} has no PDS"))?; let res = self .client .get(format!("{}/xrpc/com.atproto.sync.getRecord", pds.trim_end_matches('/'))) .query(&[("did", repo), ("collection", collection), ("rkey", rkey)]) .send() .await?; let status = res.status(); let body = res.bytes().await?; if !status.is_success() { let error = serde_json::from_slice::(&body).ok().and_then(|v| v.get("error")?.as_str().map(String::from)); return match error.as_deref() { Some("RecordNotFound" | "RepoNotFound" | "RepoTakendown" | "RepoDeactivated" | "RepoSuspended") => Ok(None), e => Err(format!("sync.getRecord {status} {}", e.unwrap_or("")).into()), }; } verify_record(&body, &doc, repo, collection, rkey) } async fn contract_held(&self, contract: &StrongRef, authorities: &[String]) -> Result { match &self.contract_held { Some(f) => f(contract.clone(), authorities.to_vec()).await, None => market_contract_held(self, contract, authorities).await, } } fn now(&self) -> DateTime { std::time::SystemTime::now().into() } }