~ 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
509 lines · 20.0 KB Raw History
//! Where canvases are kept: the `Store` trait, which the engine asks for
//! what it holds and tells of each change; and `FileStore`, the server's
//! own files. A backend is told each change with the canvas whole as it now
//! is and the change itself, so one that writes whole files and one that
//! writes a record per tile (a space on the person's PDS, `SpaceStore`)
//! both have what they need.
//!
//! `FileStore` keeps, under its directory (`<HUD_DATA_DIR>/canvas/`), each
//! canvas as `<id>.json` (its info and tiles), and each person's index as
//! `by-did/<sha256 of the DID>.json` (the canvases they own or are a member
//! of, those open as tabs, in order, and the one they last opened), rebuilt
//! from the canvases at start if that directory is missing. A canvas from
//! before there were many, `<sha256 of the DID>.json`, is moved into the
//! person's first canvas and kept aside as `<…>.json.moved`; so is a canvas
//! moved into a space, `<id>.json.moved`. A canvas's tiles from before
//! columns (`x`, `y`, `w`, `h`) are made columns as it is read
//! (`super::migrated`), and written back at start. A person's whole
//! deletion (`forget`) deletes their index, their canvas from before and
//! every file of a canvas they own, put aside or not. Each file mode 0600,
//! written whole.

use super::{CanvasInfo, Tile, migrated};
use crate::oauth::store::write_private;
use atproto::jose;
use serde_json::{Value, json};
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::pin::Pin;

/// What a backend's methods answer.
pub type Fut<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;

/// A person's index: the canvases they own or are a member of, those open
/// as tabs, in order (none in an index from before tabs), and the one they
/// last opened.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Index {
    pub canvases: Vec<String>,
    pub open: Option<Vec<String>>,
    pub current: Option<String>,
}

/// A change to a canvas, with the canvas as it now is.
pub enum Change<'a> {
    /// Made, renamed, or its members changed.
    Info {
        info: &'a CanvasInfo,
        tiles: &'a [Tile],
    },
    /// Tiles added or changed (`changed`), each by its author, and taken
    /// off (`gone`: each id, and who wrote it), by one change.
    Tiles {
        info: &'a CanvasInfo,
        tiles: &'a [Tile],
        changed: Vec<&'a Tile>,
        gone: Vec<(&'a str, &'a str)>,
    },
    /// The canvas deleted.
    Deleted(&'a CanvasInfo),
}

/// Where canvases are kept.
pub trait Store: Send + Sync {
    /// Every canvas kept: its info, and how many tiles it has. Read once,
    /// at start.
    fn canvases(&self) -> Fut<'_, Vec<(CanvasInfo, usize)>>;
    /// A canvas's tiles, oldest first.
    fn tiles<'a>(&'a self, info: &'a CanvasInfo) -> Fut<'a, Result<Vec<Tile>, String>>;
    /// Keep a change.
    fn write<'a>(&'a self, change: Change<'a>) -> Fut<'a, Result<(), String>>;
    /// A person's index, if they have one.
    fn index<'a>(&'a self, did: &'a str) -> Fut<'a, Option<Index>>;
    /// Keep a person's index.
    fn put_index<'a>(&'a self, did: &'a str, index: &'a Index) -> Fut<'a, Result<(), String>>;
    /// A person's one canvas from before there were many, its tiles, if it
    /// is still to be moved.
    fn legacy<'a>(&'a self, did: &'a str) -> Fut<'a, Option<Vec<Tile>>>;
    /// Put a person's canvas from before aside, once moved.
    fn retire_legacy<'a>(&'a self, did: &'a str) -> Fut<'a, ()>;
    /// A person's canvases kept elsewhere than at start, as the store
    /// decides where theirs go, once per sign-in: none when that was
    /// decided already. Asked on each use of theirs; it answers at once
    /// once decided.
    fn person<'a>(&'a self, _did: &'a str) -> Fut<'a, Option<Vec<(CanvasInfo, usize)>>> {
        Box::pin(async { None })
    }
    /// Whether a canvas is kept elsewhere than it belongs: written whole
    /// again, it moves there.
    fn misplaced(&self, _info: &CanvasInfo) -> bool {
        false
    }
    /// Where a canvas is kept, as its pages and tools are told:
    /// `{ kind: "space", uri }`, or `{ kind: "file", reason? }`, the reason
    /// it is not in a space where spaces are on.
    fn storage(&self, _info: &CanvasInfo) -> Value {
        json!({ "kind": "file" })
    }
    /// Write what waits to be written, as the server stops.
    fn flush(&self) -> Fut<'_, ()> {
        Box::pin(async {})
    }
    /// Delete what is kept of a person's past their canvases, once each
    /// was deleted or left: their index, their canvas from before there
    /// were many, any file of a canvas they own still kept (put aside
    /// too), and where spaces are on, every workspace space of theirs
    /// left. Every failure, in a line each.
    fn forget<'a>(&'a self, did: &'a str) -> Fut<'a, Result<(), Vec<String>>>;
}

/// Canvases in the server's own files.
pub struct FileStore {
    dir: PathBuf,
}

impl FileStore {
    pub fn new(dir: PathBuf) -> FileStore {
        FileStore { dir }
    }

    fn canvas_path(&self, id: &str) -> PathBuf {
        self.dir.join(format!("{id}.json"))
    }

    fn index_path(&self, did: &str) -> PathBuf {
        self.dir
            .join("by-did")
            .join(format!("{}.json", jose::sha256(did)))
    }

    fn legacy_path(&self, did: &str) -> PathBuf {
        self.dir.join(format!("{}.json", jose::sha256(did)))
    }

    fn keep(&self, path: &Path, doc: &Value) -> Result<(), String> {
        write_private(path, doc.to_string().as_bytes())
            .map_err(|e| format!("{}: {e}", path.display()))
    }

    /// Keep a canvas whole in its file.
    pub fn put(&self, info: &CanvasInfo, tiles: &[Tile]) -> Result<(), String> {
        let mut doc = info.to_json();
        doc["tiles"] = tiles.iter().map(Tile::to_json).collect();
        self.keep(&self.canvas_path(&info.id), &doc)
    }

    /// A canvas file read: its info and tiles, and whether its tiles were
    /// kept as made before, brought up to date as read (`migrated`).
    fn read(&self, path: &Path) -> Option<(CanvasInfo, Vec<Tile>, bool)> {
        let mut v: Value = serde_json::from_slice(&std::fs::read(path).ok()?).ok()?;
        let info = CanvasInfo::from_json(&v)?;
        let moved = migrated(v["tiles"].as_array_mut()?);
        let tiles = v["tiles"]
            .as_array()?
            .iter()
            .map(|t| Tile::from_json(t, &info.owner))
            .collect::<Option<Vec<_>>>()?;
        Some((info, tiles, moved))
    }

    /// Put a canvas's file aside, once it is kept elsewhere: `<id>.json`
    /// becomes `<id>.json.moved`, which nothing reads.
    pub fn put_aside(&self, id: &str) -> Result<(), String> {
        let from = self.canvas_path(id);
        match std::fs::rename(&from, from.with_extension("json.moved")) {
            Err(e) if e.kind() != std::io::ErrorKind::NotFound => {
                Err(format!("{}: {e}", from.display()))
            }
            _ => Ok(()),
        }
    }

    /// Whether a canvas has a file of its own.
    pub fn has(&self, id: &str) -> bool {
        self.canvas_path(id).exists()
    }
}

/// Whether a file's stem is a canvas's id.
fn is_canvas_file(path: &Path) -> Option<&str> {
    let stem = path.file_name()?.to_str()?.strip_suffix(".json")?;
    super::checked_id(stem).is_ok().then_some(stem)
}

impl Store for FileStore {
    fn canvases(&self) -> Fut<'_, Vec<(CanvasInfo, usize)>> {
        Box::pin(async move {
            let mut out = Vec::new();
            for entry in std::fs::read_dir(&self.dir).into_iter().flatten().flatten() {
                let path = entry.path();
                if is_canvas_file(&path).is_none() {
                    continue;
                }
                match self.read(&path) {
                    Some((info, tiles, moved)) => {
                        if moved {
                            match self.put(&info, &tiles) {
                                Ok(()) => {
                                    tracing::info!(canvas = info.id, "a canvas brought up to date")
                                }
                                Err(e) => {
                                    tracing::error!(canvas = info.id, error = %e, "could not keep a canvas brought up to date")
                                }
                            }
                        }
                        out.push((info, tiles.len()))
                    }
                    None => tracing::warn!(path = %path.display(), "not a canvas; left as it is"),
                }
            }
            // The indexes, rebuilt from the canvases where there are none.
            if !self.dir.join("by-did").exists() && !out.is_empty() {
                let mut by: BTreeMap<&str, Vec<String>> = BTreeMap::new();
                for (info, _) in &out {
                    for m in &info.members {
                        by.entry(&m.did).or_default().push(info.id.clone());
                    }
                }
                for (did, canvases) in by {
                    let index = Index {
                        canvases,
                        open: None,
                        current: None,
                    };
                    if let Err(e) = self.put_index(did, &index).await {
                        tracing::error!(error = %e, "could not rebuild a canvas index");
                    }
                }
            }
            out
        })
    }

    fn tiles<'a>(&'a self, info: &'a CanvasInfo) -> Fut<'a, Result<Vec<Tile>, String>> {
        Box::pin(async move {
            let path = self.canvas_path(&info.id);
            if !path.exists() {
                return Ok(Vec::new());
            }
            self.read(&path)
                .map(|(_, tiles, _)| tiles)
                .ok_or_else(|| format!("{} is not a canvas", path.display()))
        })
    }

    fn write<'a>(&'a self, change: Change<'a>) -> Fut<'a, Result<(), String>> {
        Box::pin(async move {
            match change {
                Change::Info { info, tiles } | Change::Tiles { info, tiles, .. } => {
                    self.put(info, tiles)
                }
                Change::Deleted(info) => match std::fs::remove_file(self.canvas_path(&info.id)) {
                    Err(e) if e.kind() != std::io::ErrorKind::NotFound => Err(e.to_string()),
                    _ => Ok(()),
                },
            }
        })
    }

    fn index<'a>(&'a self, did: &'a str) -> Fut<'a, Option<Index>> {
        Box::pin(async move {
            let v: Value =
                serde_json::from_slice(&std::fs::read(self.index_path(did)).ok()?).ok()?;
            if v["did"] != did {
                return None;
            }
            Some(Index {
                canvases: v["canvases"]
                    .as_array()?
                    .iter()
                    .filter_map(|c| c.as_str().map(str::to_string))
                    .collect(),
                open: v["open"].as_array().map(|open| {
                    open.iter()
                        .filter_map(|c| c.as_str().map(str::to_string))
                        .collect()
                }),
                current: v["current"].as_str().map(str::to_string),
            })
        })
    }

    fn put_index<'a>(&'a self, did: &'a str, index: &'a Index) -> Fut<'a, Result<(), String>> {
        Box::pin(async move {
            self.keep(
                &self.index_path(did),
                &json!({ "did": did, "canvases": index.canvases, "open": index.open,
                         "current": index.current }),
            )
        })
    }

    fn legacy<'a>(&'a self, did: &'a str) -> Fut<'a, Option<Vec<Tile>>> {
        Box::pin(async move {
            let v: Value =
                serde_json::from_slice(&std::fs::read(self.legacy_path(did)).ok()?).ok()?;
            if v["did"] != did {
                return None;
            }
            let mut tiles = v["tiles"].as_array()?.clone();
            migrated(&mut tiles);
            tiles.iter().map(|t| Tile::from_json(t, did)).collect()
        })
    }

    fn retire_legacy<'a>(&'a self, did: &'a str) -> Fut<'a, ()> {
        Box::pin(async move {
            let from = self.legacy_path(did);
            let to = from.with_extension("json.moved");
            if let Err(e) = std::fs::rename(&from, &to) {
                tracing::warn!(error = %e, "could not put a moved canvas aside");
            }
        })
    }

    fn forget<'a>(&'a self, did: &'a str) -> Fut<'a, Result<(), Vec<String>>> {
        Box::pin(async move {
            let mut paths = vec![self.index_path(did), self.legacy_path(did)];
            paths.push(paths[1].with_extension("json.moved"));
            // A canvas of theirs kept, or put aside, which nothing else
            // deletes: one moved into a space, or whose deletion failed.
            for entry in std::fs::read_dir(&self.dir).into_iter().flatten().flatten() {
                let path = entry.path();
                // A name that is not text is no canvas's: it matches no id.
                let name = entry.file_name();
                let name = name.to_string_lossy();
                let stem = name
                    .strip_suffix(".json.moved")
                    .or_else(|| name.strip_suffix(".json"));
                if !stem.is_some_and(|s| super::checked_id(s).is_ok_and(|id| id == s)) {
                    continue;
                }
                let owner = std::fs::read(&path)
                    .ok()
                    .and_then(|b| serde_json::from_slice::<Value>(&b).ok())
                    .and_then(|v| CanvasInfo::from_json(&v))
                    .map(|info| info.owner);
                if owner.as_deref() == Some(did) {
                    paths.push(path);
                }
            }
            let failed: Vec<String> = paths
                .iter()
                .filter_map(|path| match std::fs::remove_file(path) {
                    Err(e) if e.kind() != std::io::ErrorKind::NotFound => {
                        Some(format!("{}: {e}", path.display()))
                    }
                    _ => None,
                })
                .collect();
            if failed.is_empty() {
                Ok(())
            } else {
                Err(failed)
            }
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::canvas::{Member, Role};

    const ALICE: &str = "did:plc:alice";

    fn dir() -> PathBuf {
        let d = std::env::temp_dir().join(format!("hud-canvas-store-{}", jose::random(6)));
        std::fs::create_dir_all(&d).unwrap();
        d
    }

    fn info(id: &str) -> CanvasInfo {
        CanvasInfo {
            id: id.into(),
            name: "Coast trip".into(),
            owner: ALICE.into(),
            members: vec![Member {
                did: ALICE.into(),
                handle: None,
                role: Role::Owner,
                joined: true,
                invited_by: None,
            }],
            created_at: "2026-11-14T00:00:00.000Z".into(),
            updated_at: "2026-11-14T00:00:00.000Z".into(),
        }
    }

    /// A canvas's file as kept, with `tiles`.
    fn file(info: &CanvasInfo, tiles: Value) -> String {
        let mut doc = info.to_json();
        doc["tiles"] = tiles;
        doc.to_string()
    }

    #[tokio::test]
    async fn forgetting_says_what_it_could_not_delete() {
        let d = dir();
        let store = FileStore::new(d.clone());
        // Where a person's index goes, a directory.
        let index = store.index_path(ALICE);
        std::fs::create_dir_all(index.join("x")).unwrap();
        let why = store.forget(ALICE).await.unwrap_err();
        assert_eq!(why.len(), 1, "{why:?}");
        assert!(
            why[0].starts_with(&format!("{}: ", index.display())),
            "{why:?}"
        );
        std::fs::remove_dir_all(&d).unwrap();
    }

    #[tokio::test]
    async fn what_cannot_be_read_or_written_is_left_as_it_is() {
        let d = dir();
        let store = FileStore::new(d.clone());
        // A file with a tile HUD does not make: not a canvas.
        let odd = info("00000000000a");
        std::fs::write(
            d.join("00000000000a.json"),
            file(&odd, json!([{ "id": "nope" }])),
        )
        .unwrap();
        // Nor is one whose tiles are not a list.
        std::fs::write(
            d.join("00000000000e.json"),
            file(&info("00000000000e"), json!({})),
        )
        .unwrap();
        // A canvas from before columns kept under another id's name, where
        // its own file cannot be written: a directory is in its place.
        let old = info("00000000000c");
        let tile = json!({ "id": "000000000001", "tool": "describe_repo",
            "arguments": { "actor": "alice.test" }, "title": "alice.test", "x": 0.0, "y": 0.0,
            "w": 420.0, "h": 560.0, "by": "agent", "at": "2026-11-14T00:00:00.000Z" });
        std::fs::write(
            d.join("00000000000b.json"),
            file(&old, json!([tile.clone()])),
        )
        .unwrap();
        std::fs::create_dir_all(d.join("00000000000c.json").join("x")).unwrap();
        // Another from before columns, written back up to date.
        let mended = info("00000000000f");
        let path = d.join("00000000000f.json");
        std::fs::write(&path, file(&mended, json!([tile]))).unwrap();
        // The indexes cannot be rebuilt: where they go leads nowhere.
        std::os::unix::fs::symlink(d.join("nowhere"), d.join("by-did")).unwrap();
        // The canvas read, brought up to date in memory; the rest left.
        let mut found = store.canvases().await;
        found.sort_by(|a, b| a.0.id.cmp(&b.0.id));
        assert_eq!(found, vec![(old.clone(), 1), (mended, 1)]);
        let kept: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
        assert_eq!(kept["tiles"][0]["order"], "1");
        assert!(store.index(ALICE).await.is_none());
        assert_eq!(
            store.tiles(&odd).await,
            Err(format!(
                "{} is not a canvas",
                d.join("00000000000a.json").display()
            ))
        );
        let kept = store.put(&old, &[]).unwrap_err();
        assert!(kept.contains("00000000000c.json"), "{kept}");
        // A canvas with no file has no tiles.
        assert_eq!(store.tiles(&info("00000000000d")).await, Ok(Vec::new()));
        // Put aside where the place it goes is taken: refused, the file kept.
        std::fs::create_dir_all(d.join("00000000000a.json.moved").join("x")).unwrap();
        assert!(store.put_aside("00000000000a").is_err());
        assert!(store.has("00000000000a"));
        std::fs::remove_dir_all(&d).unwrap();
    }

    #[tokio::test]
    async fn another_persons_files_are_not_theirs() {
        let d = dir();
        let store = FileStore::new(d.clone());
        // An index and a canvas from before, each another DID's under
        // Alice's name.
        let index = Index {
            canvases: vec!["00000000000a".into()],
            open: None,
            current: None,
        };
        store.put_index("did:plc:bob", &index).await.unwrap();
        std::fs::rename(store.index_path("did:plc:bob"), store.index_path(ALICE)).unwrap();
        assert_eq!(store.index(ALICE).await, None);
        let whose = json!({ "did": ALICE, "canvases": {} });
        std::fs::write(store.index_path(ALICE), whose.to_string()).unwrap();
        assert_eq!(store.index(ALICE).await, None);
        let legacy = store.legacy_path(ALICE);
        std::fs::write(
            &legacy,
            json!({ "did": "did:plc:bob", "tiles": [] }).to_string(),
        )
        .unwrap();
        assert_eq!(store.legacy(ALICE).await, None);
        // Put aside where the place it goes is taken: left where it is.
        std::fs::create_dir_all(legacy.with_extension("json.moved").join("x")).unwrap();
        store.retire_legacy(ALICE).await;
        assert!(legacy.exists());
        // Files are where canvases belong, and nothing waits to be written.
        let mine = info("00000000000e");
        store.put(&mine, &[]).unwrap();
        assert!(!store.misplaced(&mine));
        let before = std::fs::read(d.join("00000000000e.json")).unwrap();
        store.flush().await;
        assert_eq!(std::fs::read(d.join("00000000000e.json")).unwrap(), before);
        std::fs::remove_dir_all(&d).unwrap();
    }
}