chadtmiller.com/hud
A remote MCP server that shows atproto records as interactive UI inside MCP Apps hosts
place.hud.hudkit 0.5.0 Latest 5 packages
0
0
//! The lexicon of a record type, for drawing its records' fields. The
//! common ones are bundled (`lexicons/`, embedded at compile time); any
//! other is resolved as atproto publishes them: the NSID's authority (its
//! segments but the last, reversed) names a DID in its `_lexicon` TXT
//! record, and that DID's repository holds the document as the record
//! `com.atproto.lexicon.schema/<nsid>`. The defs of other NSIDs the record
//! refers to are resolved one level deep, the same way.
//!
//! What resolves is kept a day, what is answered not to (no `_lexicon`
//! record, no schema record) an hour: in memory, and as a file under
//! `<HUD_CACHE_DIR>/lexicons/`, read when memory has nothing, so a restart
//! refetches nothing still fresh. One that had no answer on the way (none
//! in time, a server that cannot answer now) is kept nowhere, so the next
//! to ask resolves it again (`net`). A lexicon is anyone's text: it goes
//! to the view, read into its drawing (`ui`), never a tool's `content`.
use crate::Hud;
use crate::net::did_of_txt;
use serde_json::{Map, Value, json};
use std::collections::{BTreeSet, HashMap};
use std::path::PathBuf;
use std::sync::{Arc, LazyLock};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
include!(concat!(env!("OUT_DIR"), "/bundled.rs"));
/// How long a resolved lexicon is kept.
const KEEP: Duration = Duration::from_secs(24 * 3600);
/// How long a lexicon answered not to resolve is kept as not resolving.
const KEEP_MISSING: Duration = Duration::from_secs(3600);
/// How long resolving one lexicon over the network has, all its steps.
const RESOLVE_WAIT: Duration = Duration::from_secs(8);
/// How long the schema record's read has.
const RECORD_WAIT: Duration = Duration::from_secs(5);
/// The most of a schema record read.
const RECORD_MAX: usize = 1024 * 1024;
/// The most refs to other NSIDs resolved for one lexicon.
const REFS_MAX: usize = 50;
/// The schema records' collection.
const SCHEMA: &str = "com.atproto.lexicon.schema";
/// The bundled lexicons, parsed on first use.
static PARSED: LazyLock<HashMap<&'static str, Arc<Value>>> = LazyLock::new(|| {
BUNDLED
.iter()
.map(|(nsid, text)| {
// A bundled lexicon that is not JSON names itself as it fails.
let doc: Value = serde_json::from_str(text).expect(nsid);
(*nsid, Arc::new(doc))
})
.collect()
});
/// The bundled lexicon of `nsid`, if there is one.
pub fn bundled(nsid: &str) -> Option<Arc<Value>> {
PARSED.get(nsid).cloned()
}
/// Every bundled lexicon document.
pub fn all_bundled() -> impl Iterator<Item = &'static Arc<Value>> {
PARSED.values()
}
/// An NSID's authority: its segments but the last, reversed
/// (`social.grain.gallery` is `grain.social`'s).
pub fn authority(nsid: &str) -> String {
let mut segments: Vec<&str> = nsid.split('.').collect();
segments.pop();
segments.reverse();
segments.join(".")
}
/// Whether `doc` is a lexicon document of `nsid`: version 1, its id, defs.
pub(crate) fn is_document(doc: &Value, nsid: &str) -> bool {
doc.get("lexicon") == Some(&json!(1))
&& doc.get("id").and_then(Value::as_str) == Some(nsid)
&& doc.get("defs").is_some_and(Value::is_object)
}
/// The lexicon document of `nsid` a `getRecord` answer holds, if it is one.
fn schema_of(nsid: &str, body: &[u8]) -> Option<Value> {
let answer: Value = serde_json::from_slice(body).ok()?;
let mut doc = answer.get("value")?.clone();
doc.as_object_mut()?.remove("$type");
is_document(&doc, nsid).then_some(doc)
}
/// A ref written in `doc` (of `nsid`), as `nsid#def`: `#def` is local,
/// and a ref with no `#` is to `#main`.
pub(crate) fn full_ref(nsid: &str, r: &str) -> String {
match r.split_once('#') {
Some(("", def)) => format!("{nsid}#{def}"),
Some((other, def)) => format!("{other}#{def}"),
None => format!("{r}#main"),
}
}
/// The refs to other NSIDs' defs that `doc`'s main def reaches: through
/// `ref`s, `union`s' refs and array items, following its own defs (which
/// the view reads from the document) but none of another's.
pub fn external_refs(doc: &Value) -> BTreeSet<String> {
let nsid = doc.get("id").and_then(Value::as_str).unwrap_or_default();
let defs = doc.get("defs").and_then(Value::as_object);
let mut seen_local = BTreeSet::from(["main".to_string()]);
let mut pending: Vec<&Value> = defs.and_then(|d| d.get("main")).into_iter().collect();
let mut out = BTreeSet::new();
while let Some(def) = pending.pop() {
let mut refs = Vec::new();
refs_in(def, &mut refs);
for r in refs {
let full = full_ref(nsid, r);
let (of, name) = full.split_once('#').unwrap_or((&full, "main"));
if of == nsid {
if seen_local.insert(name.to_string())
&& let Some(d) = defs.and_then(|d| d.get(name))
{
pending.push(d);
}
} else if atproto::syntax::is_nsid(of) && out.len() < REFS_MAX {
out.insert(full.clone());
}
}
}
out
}
/// The refs a schema value names, at any depth: a `ref`'s and a `union`'s.
pub(crate) fn refs_in<'a>(v: &'a Value, out: &mut Vec<&'a str>) {
match v {
Value::Object(o) => {
match o.get("type").and_then(Value::as_str) {
Some("ref") => out.extend(o.get("ref").and_then(Value::as_str)),
Some("union") => out.extend(
o.get("refs")
.and_then(Value::as_array)
.into_iter()
.flatten()
.filter_map(Value::as_str),
),
_ => {}
}
o.values().for_each(|c| refs_in(c, out));
}
Value::Array(items) => items.iter().for_each(|c| refs_in(c, out)),
_ => {}
}
}
fn now_secs() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_or(0, |d| d.as_secs())
}
impl Hud {
/// The lexicon of a collection as the view takes it, `{nsid, doc,
/// refs}`; null if it does not resolve.
pub async fn lexicon(&self, nsid: &str) -> Value {
let Some(doc) = self.lexicon_doc(nsid).await else {
return Value::Null;
};
let wanted = external_refs(&doc);
let resolved = futures::future::join_all(wanted.iter().map(|r| async move {
let (of, def) = r.split_once('#')?;
let doc = self.lexicon_doc(of).await?;
Some((r.clone(), doc.get("defs")?.get(def)?.clone()))
}))
.await;
let refs: Map<String, Value> = resolved.into_iter().flatten().collect();
json!({ "nsid": nsid, "doc": *doc, "refs": refs })
}
/// A lexicon document: an operator's app's (`operator`), bundled,
/// kept, or resolved now.
pub async fn lexicon_doc(&self, nsid: &str) -> Option<Arc<Value>> {
if let Some(doc) = crate::view::views().lexicon(nsid).or_else(|| bundled(nsid)) {
return Some(doc);
}
if !atproto::syntax::is_nsid(nsid) {
return None;
}
if let Some(kept) = self.lexicons.get(&nsid.to_string()) {
return kept;
}
if let Some((doc, left)) = self.read_kept(nsid).await {
self.lexicons.put(nsid.to_string(), doc.clone(), left);
return doc;
}
// Kept only if answered: with no answer on the way, the next ask
// resolves it again.
let Ok(Ok(found)) = tokio::time::timeout(RESOLVE_WAIT, self.resolve_lexicon(nsid)).await
else {
return None;
};
let doc = found.map(Arc::new);
let keep = if doc.is_some() { KEEP } else { KEEP_MISSING };
self.lexicons.put(nsid.to_string(), doc.clone(), keep);
self.write_kept(nsid, doc.as_deref()).await;
doc
}
/// Resolve a lexicon over the network, as the module says: it, or none
/// if the answers on the way say there is none; else why not now: its
/// DNS record or its PDS had no answer, or its publisher's PDS cannot
/// be found (which `did_doc` keeps, or not, as it was answered).
async fn resolve_lexicon(&self, nsid: &str) -> Result<Option<Value>, String> {
let records = self
.net
.txt(&format!("_lexicon.{}", authority(nsid)))
.await?;
let Some(did) = did_of_txt(&records) else {
return Ok(None);
};
let pds = self.pds(&did).await?;
// A PDS's URL as `pds` gives it, checked, with no query or
// fragment: a path after it always parses.
let mut url = url::Url::parse(&format!("{pds}/xrpc/com.atproto.repo.getRecord"))
.expect("a checked PDS URL takes a path");
url.query_pairs_mut()
.append_pair("repo", &did)
.append_pair("collection", SCHEMA)
.append_pair("rkey", nsid);
match self.net.fetch(&url, RECORD_WAIT, RECORD_MAX).await {
Ok(got) if got.unavailable() => Err(format!("{pds} answered {}", got.status)),
Ok(got) if got.status == 200 => Ok(schema_of(nsid, &got.body)),
Ok(_) => Ok(None),
Err(f) if f.answered => Ok(None),
Err(f) => Err(f.why),
}
}
/// The directory lexicons are kept in.
fn kept_dir(&self) -> PathBuf {
self.config.cache_dir.join("lexicons")
}
/// A lexicon kept on disk, if still fresh: it (or none, kept as not
/// resolving), and how long it stays fresh.
async fn read_kept(&self, nsid: &str) -> Option<(Option<Arc<Value>>, Duration)> {
let text = tokio::fs::read(self.kept_dir().join(format!("{nsid}.json")))
.await
.ok()?;
let kept: Value = serde_json::from_slice(&text).ok()?;
let at = kept.get("fetchedAt")?.as_u64()?;
let doc = kept
.get("doc")
.filter(|d| is_document(d, nsid))
.cloned()
.map(Arc::new);
let ttl = if doc.is_some() { KEEP } else { KEEP_MISSING };
let age = Duration::from_secs(now_secs().saturating_sub(at));
let left = ttl.checked_sub(age).filter(|l| !l.is_zero())?;
Some((doc, left))
}
/// Keep a lexicon on disk, written whole to a scratch file and renamed
/// over the old, so a reader never sees half of one. A failure is
/// logged and otherwise ignored: the disk cache only saves fetches.
async fn write_kept(&self, nsid: &str, doc: Option<&Value>) {
let dir = self.kept_dir();
let path = dir.join(format!("{nsid}.json"));
let kept = json!({ "nsid": nsid, "fetchedAt": now_secs(), "doc": doc });
let scratch = path.with_extension(format!(
"json.{}.{:x}",
std::process::id(),
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_or(0, |d| d.subsec_nanos())
));
let write = async {
tokio::fs::create_dir_all(&dir).await?;
tokio::fs::write(&scratch, kept.to_string()).await?;
tokio::fs::rename(&scratch, &path).await
};
if let Err(e) = write.await {
let _ = tokio::fs::remove_file(&scratch).await;
tracing::warn!(nsid, error = %e, "could not keep a lexicon on disk");
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::net::tests::{Reply, fake_net, txt};
use axum::extract::Query;
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
use std::collections::HashMap;
const PUBLISHER: &str = "did:plc:publisherpublisherpublis";
const CLOSED: &str = "did:plc:closedclosedclosedclosed";
#[test]
fn refs_followed_once_and_only_to_nsids() {
let doc = json!({ "lexicon": 1, "id": "com.example.a", "defs": {
"main": { "type": "object", "properties": {
"x": { "type": "ref", "ref": "#local" },
"y": { "type": "ref", "ref": "#local" },
"z": { "type": "ref", "ref": "#missing" },
"w": { "type": "union", "refs": ["not an nsid#x", "com.example.b"] },
} },
"local": { "type": "ref", "ref": "com.example.c#def" },
} });
assert_eq!(
external_refs(&doc),
BTreeSet::from([
"com.example.b#main".to_string(),
"com.example.c#def".to_string()
])
);
}
/// A schema record's `getRecord` answer: the document of `nsid`,
/// whose main def refers to `refs`, and a def `def`.
fn schema(nsid: &str, refs: &[&str]) -> Value {
let props: Map<String, Value> = refs
.iter()
.map(|r| (r.to_string(), json!({ "type": "ref", "ref": r })))
.collect();
json!({ "uri": format!("at://{PUBLISHER}/{SCHEMA}/{nsid}"), "value": {
"$type": SCHEMA, "lexicon": 1, "id": nsid, "defs": {
"main": { "type": "object", "properties": props },
"def": { "type": "string" },
} } })
}
/// The publisher's PLC directory and PDS, as one fake.
async fn publisher(
axum::extract::Path(path): axum::extract::Path<String>,
Query(q): Query<HashMap<String, String>>,
axum::extract::State(url): axum::extract::State<String>,
) -> Response {
let pds = |did: &str, at: &str| {
axum::Json(json!({ "id": did, "service": [{ "id": "#atproto_pds",
"type": "AtprotoPersonalDataServer", "serviceEndpoint": at }] }))
.into_response()
};
match path.as_str() {
PUBLISHER => pds(PUBLISHER, &url),
CLOSED => pds(CLOSED, "http://127.0.0.1:1"),
_ => match q["rkey"].as_str() {
"com.example.thing" => axum::Json(schema(
"com.example.thing",
&["com.example.other#def", "com.example.gone#def"],
))
.into_response(),
"com.example.other" => axum::Json(schema("com.example.other", &[])).into_response(),
"com.example.wrong" => axum::Json(schema("com.example.other", &[])).into_response(),
"com.example.big" => " ".repeat(RECORD_MAX + 1).into_response(),
"com.example.busy" => StatusCode::SERVICE_UNAVAILABLE.into_response(),
_ => (StatusCode::BAD_REQUEST, r#"{"error":"RecordNotFound"}"#).into_response(),
},
}
}
/// A server resolving lexicons through a fake DNS and the fake
/// publisher, keeping them under `cache_dir`.
async fn resolving(cache_dir: PathBuf) -> Arc<Hud> {
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(publisher))
.route("/{path}", axum::routing::get(publisher))
.with_state(url.clone());
tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
let mut hud = crate::tests::hud_with(&url, |c| c.cache_dir = cache_dir);
Arc::get_mut(&mut hud).unwrap().net = fake_net(true, |name, _| match name {
"_lexicon.example.com" => Reply::Records(vec![txt(name, &format!("did={PUBLISHER}"))]),
"_lexicon.closed.com" => Reply::Records(vec![txt(name, &format!("did={CLOSED}"))]),
"_lexicon.example.org" => Reply::Fail,
_ => Reply::NoSuchName,
})
.await;
hud
}
#[tokio::test]
async fn lexicons_resolved_kept_and_refused() {
let dir = std::env::temp_dir().join(format!("hud-lexicon-{}", atproto::jose::random(6)));
let hud = resolving(dir.clone()).await;
// Resolved, with the defs it refers to that resolve.
let thing = hud.lexicon("com.example.thing").await;
assert_eq!(thing["doc"]["id"], "com.example.thing");
assert!(thing["doc"].get("$type").is_none());
assert_eq!(
thing["refs"],
json!({ "com.example.other#def": { "type": "string" } })
);
assert_eq!(hud.lexicon("not an nsid").await, Value::Null);
// None: a record that is another's, too large, missing; a domain
// with no record; a DNS or PDS with no answer.
for nsid in [
"com.example.wrong",
"com.example.big",
"com.example.gone",
"com.example.busy",
"net.example.thing",
"org.example.thing",
"com.closed.thing",
] {
assert_eq!(hud.lexicon(nsid).await, Value::Null, "{nsid}");
}
// On disk, only those answered: a restart reads them, asking nothing.
let kept = |nsid: &str| dir.join("lexicons").join(format!("{nsid}.json")).exists();
assert!(kept("com.example.thing") && kept("com.example.gone"));
assert!(
!kept("com.example.busy") && !kept("org.example.thing") && !kept("com.closed.thing")
);
let again = resolving(dir.clone()).await;
let fresh = |hud: &Arc<Hud>| hud.lexicons.held().entries;
assert!(again.lexicon_doc("com.example.thing").await.is_some());
assert!(again.lexicon_doc("com.example.gone").await.is_none());
assert_eq!(fresh(&again), 2);
// One kept long ago is resolved again.
std::fs::write(
dir.join("lexicons").join("com.example.other.json"),
json!({ "nsid": "com.example.other", "fetchedAt": 0, "doc": null }).to_string(),
)
.unwrap();
assert!(again.lexicon_doc("com.example.other").await.is_some());
// A disk that keeps nothing only saves nothing.
let file = dir.join("a-file");
std::fs::write(&file, "").unwrap();
let diskless = resolving(file).await;
assert!(diskless.lexicon_doc("com.example.thing").await.is_some());
}
#[test]
fn authorities() {
assert_eq!(authority("social.grain.gallery"), "grain.social");
assert_eq!(authority("app.bsky.feed.post"), "feed.bsky.app");
assert_eq!(authority("com.example.record"), "example.com");
}
#[test]
fn bundled_are_documents() {
assert!(!BUNDLED.is_empty());
for (nsid, _) in BUNDLED {
assert!(is_document(&bundled(nsid).unwrap(), nsid), "{nsid}");
}
}
#[test]
fn refs_one_level() {
let refs = external_refs(&bundled("app.bsky.feed.post").unwrap());
// Through the post's own #replyRef, to strongRef; its embed union;
// its facets' items.
for r in [
"com.atproto.repo.strongRef#main",
"app.bsky.embed.images#main",
"app.bsky.richtext.facet#main",
] {
assert!(refs.contains(r), "{r} in {refs:?}");
}
assert!(refs.iter().all(|r| !r.starts_with("app.bsky.feed.post#")));
let photo = external_refs(&bundled("social.grain.photo").unwrap());
assert_eq!(
photo,
BTreeSet::from(["social.grain.defs#aspectRatio".to_string()])
);
}
}