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

johnandersen777.bsky.social/atlibs-identlink

ident.link agent-of walk with grants over CAR-verified sync.getRecord: Rust crate identlink, wasm, JS

1 collaborator
0
0
main
79 lines · 3.0 KB Raw History
use chrono::{DateTime, Utc};
use identlink::{market_contract_held, walk, Ancestor, DidDoc, Error, Io, Options, StrongRef};
use serde::Deserialize;
use serde_json::Value;

struct Mem {
    v: Value,
}

fn entry<'a>(map: &'a Value, key: &str) -> Result<Option<&'a Value>, Error> {
    match map.get(key) {
        None | Some(Value::Null) => Ok(None),
        Some(Value::String(s)) if s == "error" => Err(format!("{key}: error").into()),
        Some(v) => Ok(Some(v)),
    }
}

impl Io for Mem {
    async fn resolve_did(&self, did: &str) -> Result<Option<DidDoc>, Error> {
        Ok(entry(&self.v["dids"], did)?.map(DidDoc::deserialize).transpose()?)
    }

    async fn get_record(&self, repo: &str, collection: &str, rkey: &str) -> Result<Option<Value>, Error> {
        if entry(&self.v["dids"], repo)?.is_none() {
            return Ok(None);
        }
        Ok(entry(&self.v["records"], &format!("at://{repo}/{collection}/{rkey}"))?.cloned())
    }

    async fn contract_held(&self, contract: &StrongRef, authorities: &[String]) -> Result<bool, Error> {
        let repo = contract.uri.strip_prefix("at://").and_then(|r| r.split('/').next());
        Ok(entry(&self.v["held"], &contract.uri)? == Some(&Value::Bool(true)) && authorities.iter().any(|a| Some(a.as_str()) == repo))
    }

    fn now(&self) -> DateTime<Utc> {
        self.v["now"].as_str().unwrap().parse().unwrap()
    }
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct Want {
    ancestors: Vec<Ancestor>,
    roots: Vec<String>,
    truncated: bool,
    expires_at: Option<DateTime<Utc>>,
    #[serde(default)]
    errors: usize,
}

#[test]
fn vectors() {
    let v: Value = serde_json::from_str(include_str!("../vectors.json")).unwrap();
    let io = Mem { v: v.clone() };
    for case in v["cases"].as_array().unwrap() {
        let name = case["name"].as_str().unwrap();
        let options = Options::deserialize(&case["options"]).unwrap();
        let want = Want::deserialize(&case["want"]).unwrap();
        let got = futures::executor::block_on(walk(&io, case["agent"].as_str().unwrap(), options));
        assert_eq!(got.ancestors, want.ancestors, "{name}: ancestors");
        assert_eq!(got.roots, want.roots, "{name}: roots");
        assert_eq!(got.truncated, want.truncated, "{name}: truncated");
        assert_eq!(got.expires_at, want.expires_at, "{name}: expiresAt");
        assert_eq!(got.errors.len(), want.errors, "{name}: errors {:?}", got.errors);
    }
}

#[test]
fn market() {
    let v: Value = serde_json::from_str(include_str!("../vectors.json")).unwrap();
    let io = Mem { v: v.clone() };
    for case in v["market"].as_array().unwrap() {
        let contract = StrongRef::deserialize(&case["contract"]).unwrap();
        let authorities = Vec::<String>::deserialize(&case["authorities"]).unwrap();
        let got = futures::executor::block_on(market_contract_held(&io, &contract, &authorities));
        let got = got.map(Value::Bool).unwrap_or_else(|_| Value::from("error"));
        assert_eq!(got, case["want"], "{}", case["name"]);
    }
}