~ 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
1581 lines · 58.1 KB Raw History
//! Canvases in their owners' own spaces, with `HUD_SPACES=on`:
//! `SpaceStore`, a `Store` that keeps a canvas no one but its owner is in
//! in a personal space on the owner's PDS,
//! `at://<owner>/space/place.hud.workspace/<id>`: its info as a
//! `place.hud.canvas` record keyed `self`, each tile as a
//! `place.hud.tile` record keyed by its id (`schemas/`). The
//! server's files (`FileStore`) keep the rest: every person's index, the
//! canvases shared with others, and those of the people whose PDS or
//! sign-in does not allow spaces.
//!
//! Where a person's canvases go is decided once per sign-in (`person`,
//! asked on each use of theirs): in spaces if their PDS says it serves the
//! spaces alpha (`describeServer`'s `spacesAlpha`), their sign-in was
//! granted HUD's space permission (`config::SPACE_SCOPE`), and a first
//! call, listing their workspace spaces, works; else in the server's files,
//! the reason kept and told (`storage`). One decided for want of an answer
//! is decided again a minute later. Decided for spaces, those spaces are
//! read whole (`listRecords`, every page) into memory, which then holds
//! each canvas kept in a space as last written; and each canvas of theirs
//! that is in a file, theirs alone, moves in when the engine writes it
//! whole, as it does each then: its file put aside as `<id>.json.moved`.
//!
//! A change is written as it is made, but a tile's places and widths
//! (`order`, `width`, `stack`), a second after its last; a canvas's writes
//! one at a time. Tiles read from records from before columns (`x`, `y`,
//! `w`, `h`) are made columns as read and written so at once. A failed write
//! is logged, and tried again with the canvas's next change; three failures
//! in a row put the person's canvases back in the server's files, as memory
//! holds them, for the rest of their sign-in. A canvas shared with anyone
//! goes back to a file too, its space deleted; deleting a canvas deletes
//! its space, or failing that, its records.

use super::store::{Change, FileStore, Fut, Index, Store};
use super::{
    CANVAS_RECORD, CanvasInfo, MAX_TILES, Member, Role, TILE_RECORD, Tile, checked_id,
    checked_name, migrated,
};
use crate::Hud;
use crate::oauth::Reach;
use crate::space::{self, Failure, SpaceRecord};
use serde_json::{Value, json};
use std::collections::hash_map::Entry;
use std::collections::{BTreeSet, HashMap};
use std::sync::{Arc, Mutex, MutexGuard, PoisonError, Weak};
use std::time::Duration;
use tokio::time::Instant;

/// The space type of a canvas (`schemas/place.hud.workspace.json`).
pub const SPACE_TYPE: &str = "place.hud.workspace";
/// A canvas's info, in its owner's repo in its space.
pub const CANVAS: &str = CANVAS_RECORD;
/// A tile, in its author's repo in its canvas's space.
pub const TILE: &str = TILE_RECORD;
/// The key of a canvas's info record.
const SELF: &str = "self";
/// How long after a tile's last change of place or width it is written.
const SETTLE: Duration = Duration::from_secs(1);
/// The failed writes in a row that put a person's canvases back in files.
const FAILURES_MAX: u32 = 3;
/// How long until a decision made for want of an answer is made again.
const RETRY: Duration = Duration::from_secs(60);
/// The longest `flush` waits for the writes waiting.
const FLUSH_MAX: Duration = Duration::from_secs(15);
/// Why a canvas shared with others is in a file.
const SHARED: &str = "a canvas shared with others stays on this HUD server";
/// Why a person's canvases are in files when their sign-in lacks the
/// permission.
const SIGN_IN_AGAIN: &str = "sign in again to keep your canvases in your own PDS: your sign-in does not allow HUD's workspace spaces";

/// Whether a granted scope allows HUD to keep canvases in the account's
/// spaces: a `space:` permission of the workspace type (or any) that
/// manages their making, as `config::SPACE_SCOPE` asks, the PDS writing it
/// out again with the account's DID and the type's collections.
pub fn grants(scope: &str) -> bool {
    scope.split_whitespace().any(|token| {
        let Some(rest) = token.strip_prefix("space:") else {
            return false;
        };
        let (kind, params) = rest.split_once('?').unwrap_or((rest, ""));
        (kind == SPACE_TYPE || kind == "*") && params.split('&').any(|p| p == "manage=create")
    })
}

/// Where a person's canvases go.
#[derive(Clone, Debug, PartialEq)]
enum Choice {
    Space,
    /// The server's files: why, and whether to decide again in a while.
    File {
        reason: String,
        again: bool,
    },
}

/// What was decided for a person, for which sign-in (`Reach::key`).
struct Person {
    key: Option<String>,
    choice: Choice,
    /// Failed writes in a row.
    failures: u32,
    decided: Instant,
}

/// A canvas kept in a space, as last written: its space, info and tiles,
/// and the records still to write (`self` its info) or delete there.
struct Kept {
    uri: String,
    info: CanvasInfo,
    tiles: Vec<Tile>,
    unput: BTreeSet<String>,
    undeleted: BTreeSet<String>,
}

#[derive(Default)]
struct State {
    people: HashMap<String, Person>,
    /// The canvases in spaces, by id.
    kept: HashMap<String, Kept>,
    /// The spaces of canvases that went back to files when their owner's
    /// writes failed, by canvas id: deleted with the canvas.
    left: HashMap<String, String>,
    /// Spaces to delete, by their authority, whose deletion failed: tried
    /// again at its next decision.
    doomed: HashMap<String, BTreeSet<String>>,
    /// Each canvas's writes, one at a time.
    lanes: HashMap<String, Arc<tokio::sync::Mutex<()>>>,
    /// Each person's decisions, one at a time.
    deciding: HashMap<String, Arc<tokio::sync::Mutex<()>>>,
    /// Tiles placed, by canvas and tile: when to write each, or
    /// none while it is written.
    waiting: HashMap<(String, String), Option<Instant>>,
}

/// Canvases in their owners' spaces where they can be, in the server's
/// files where not.
pub struct SpaceStore {
    inner: Arc<Inner>,
}

struct Inner {
    hud: Weak<Hud>,
    files: FileStore,
    state: Mutex<State>,
    /// Wakes the writes waiting, to write them now.
    hurry: tokio::sync::Notify,
}

impl SpaceStore {
    /// The store of the server `hud`, with `files` for what is not in a
    /// space.
    pub fn new(hud: Weak<Hud>, files: FileStore) -> SpaceStore {
        SpaceStore {
            inner: Arc::new(Inner {
                hud,
                files,
                state: Mutex::new(State::default()),
                hurry: tokio::sync::Notify::new(),
            }),
        }
    }
}

/// A canvas from its owner's records in its space: its info (`self`) and
/// tiles, oldest first, the newest 200 of them; and the keys of those from
/// before columns, made columns as read, to write again. None without its
/// info.
fn canvas_of(
    id: &str,
    did: &str,
    handle: Option<&str>,
    records: &[SpaceRecord],
) -> Option<(CanvasInfo, Vec<Tile>, BTreeSet<String>)> {
    let me = records
        .iter()
        .find(|r| r.collection == CANVAS && r.rkey == SELF)?;
    let text = |k: &str| me.value.get(k)?.as_str().map(str::to_string);
    let info = CanvasInfo {
        id: id.to_string(),
        name: checked_name(&text("name")?).ok()?,
        owner: did.to_string(),
        members: vec![Member {
            did: did.to_string(),
            handle: handle.map(str::to_string),
            role: Role::Owner,
            joined: true,
            invited_by: None,
        }],
        created_at: text("createdAt")?,
        updated_at: text("updatedAt")?,
    };
    let kept: Vec<&SpaceRecord> = records.iter().filter(|r| r.collection == TILE).collect();
    let mut values: Vec<Value> = kept.iter().map(|r| r.value.clone()).collect();
    let moved: BTreeSet<String> = if migrated(&mut values) {
        kept.iter()
            .zip(&values)
            .filter(|(r, v)| r.value != **v)
            .map(|(r, _)| r.rkey.clone())
            .collect()
    } else {
        BTreeSet::new()
    };
    let mut tiles: Vec<Tile> = kept
        .iter()
        .zip(&values)
        .filter_map(|(r, v)| Tile::from_record(&r.rkey, v, did))
        .collect();
    tiles.sort_by(|a, b| (&a.at, &a.id).cmp(&(&b.at, &b.id)));
    if tiles.len() > MAX_TILES {
        tiles.drain(..tiles.len() - MAX_TILES);
    }
    let moved = moved
        .into_iter()
        .filter(|k| tiles.iter().any(|t| &t.id == k))
        .collect();
    Some((info, tiles, moved))
}

/// A record checked against its lexicon, as every record HUD writes is.
fn checked(collection: &str, record: Value) -> Result<Value, Failure> {
    let doc = crate::lexicon::bundled(collection)
        .ok_or_else(|| Failure::Failed(format!("{collection} has no lexicon")))?;
    crate::writes::checked_record(collection, Some(&record), &[doc]).map_err(Failure::Failed)
}

/// The record of a canvas in a space keyed `rkey`: its info (`self`) or a
/// tile on it.
fn record_of(k: &Kept, rkey: &str) -> Option<Value> {
    match rkey {
        SELF => Some(k.info.record()),
        tid => k.tiles.iter().find(|t| t.id == tid).map(Tile::record),
    }
}

/// Whether `new` is `old` placed (its order, width or stack), and nothing
/// else.
fn placed_only(old: &Tile, new: &Tile) -> bool {
    old.id == new.id
        && old.tool == new.tool
        && old.title == new.title
        && old.by == new.by
        && old.author == new.author
        && old.at == new.at
        && old.arguments == new.arguments
        && old.from == new.from
}

/// The canvas a change is of.
fn info_of<'a>(change: &Change<'a>) -> &'a CanvasInfo {
    match change {
        Change::Info { info, .. } | Change::Tiles { info, .. } | Change::Deleted(info) => info,
    }
}

/// Where a change to a canvas goes: its file, into its space, out of its
/// space (as it was there), or to its space.
enum Way {
    File,
    In,
    Out(Box<Kept>),
    Sync,
}

/// What a waiting tile's write does next.
enum Next {
    Wait(Instant),
    Write,
    Done,
}

impl Inner {
    fn lock(&self) -> MutexGuard<'_, State> {
        self.state.lock().unwrap_or_else(PoisonError::into_inner)
    }

    fn lane(&self, id: &str) -> Arc<tokio::sync::Mutex<()>> {
        self.lock().lanes.entry(id.to_string()).or_default().clone()
    }

    async fn reach(&self, hud: &Hud, did: &str) -> Option<Reach> {
        hud.oauth.as_ref()?.reach(did, grants).await
    }

    /// Whether a canvas belongs in a space: its owner's go there, and no
    /// one else is in it.
    fn belongs(st: &State, info: &CanvasInfo) -> bool {
        let space = st
            .people
            .get(&info.owner)
            .is_some_and(|p| p.choice == Choice::Space);
        space && info.members.iter().all(|m| m.did == info.owner)
    }

    /// Decide where a person's canvases go, unless that was decided for
    /// their sign-in already: those found in their spaces.
    async fn decide(&self, did: &str) -> Option<Vec<(CanvasInfo, usize)>> {
        let hud = self.hud.upgrade()?;
        let gate = self
            .lock()
            .deciding
            .entry(did.to_string())
            .or_default()
            .clone();
        let _one = gate.lock().await;
        let reach = self.reach(&hud, did).await;
        let key = reach.as_ref().map(|r| r.key.clone());
        if let Some(p) = self.lock().people.get(did) {
            let again = matches!(p.choice, Choice::File { again: true, .. })
                && p.decided.elapsed() >= RETRY;
            if p.key == key && !again {
                return None;
            }
        }
        let (choice, loaded) = match &reach {
            None => (
                Choice::File {
                    reason: "no sign-in of yours reaches your PDS".into(),
                    again: false,
                },
                Vec::new(),
            ),
            Some(r) => match self.choose(&hud, r).await {
                Ok(loaded) => (Choice::Space, loaded),
                Err((reason, again)) => (Choice::File { reason, again }, Vec::new()),
            },
        };
        match &choice {
            Choice::Space => tracing::info!(did, "canvases kept in their spaces"),
            Choice::File { reason, .. } => tracing::info!(did, reason, "canvases kept in files"),
        }
        let handle = reach.as_ref().and_then(|r| r.account.handle.clone());
        let mut found = Vec::new();
        let mut columned = Vec::new();
        {
            let mut st = self.lock();
            let space = choice == Choice::Space;
            st.people.insert(
                did.to_string(),
                Person {
                    key,
                    choice,
                    failures: 0,
                    decided: Instant::now(),
                },
            );
            if !space {
                self.to_files(&mut st, did);
                return Some(found);
            }
            for (uri, id, records) in loaded {
                if let Some(k) = st.kept.get(&id) {
                    found.push((k.info.clone(), k.tiles.len()));
                    continue;
                }
                // A canvas with a file of its own was put back there since:
                // the file is the newer, and moves in again.
                if self.files.has(&id) {
                    continue;
                }
                match canvas_of(&id, did, handle.as_deref(), &records) {
                    Some((info, tiles, moved)) => {
                        found.push((info.clone(), tiles.len()));
                        st.left.remove(&id);
                        if !moved.is_empty() {
                            columned.push(id.clone());
                        }
                        st.kept.insert(
                            id,
                            Kept {
                                uri,
                                info,
                                tiles,
                                unput: moved,
                                undeleted: BTreeSet::new(),
                            },
                        );
                    }
                    None => tracing::warn!(did, space = uri, "a workspace space with no canvas"),
                }
            }
        }
        // Tiles from before columns, made columns as read, written so.
        for id in columned {
            let lane = self.lane(&id);
            let _lane = lane.lock().await;
            match self.sync(&id).await {
                Ok(()) => tracing::info!(canvas = id, "a canvas in a space made columns"),
                Err(why) => {
                    tracing::warn!(canvas = id, why, "a canvas made columns was not written")
                }
            }
        }
        Some(found)
    }

    /// Whether a person's canvases can go in spaces, through `r`: each of
    /// their workspace spaces' URI, canvas id and records; else why not,
    /// and whether to ask again in a while.
    async fn choose(
        &self,
        hud: &Hud,
        r: &Reach,
    ) -> Result<Vec<(String, String, Vec<SpaceRecord>)>, (String, bool)> {
        let did = r.account.did.as_str();
        match hud.spaces_alpha(&r.pds).await {
            Err(why) => return Err((format!("your PDS could not be reached: {why}"), true)),
            Ok(false) => return Err(("your PDS does not offer spaces".into(), false)),
            Ok(true) => {}
        }
        if !grants(&r.scope) {
            return Err((SIGN_IN_AGAIN.into(), false));
        }
        let refused = |f: Failure| {
            let again = f.transient();
            match f {
                Failure::ScopeMissing => (SIGN_IN_AGAIN.to_string(), again),
                f => (f.line(), again),
            }
        };
        let listed = hud
            .spaces_of(&r.account, SPACE_TYPE)
            .await
            .map_err(refused)?;
        let doomed = self.lock().doomed.get(did).cloned().unwrap_or_default();
        let mut out = Vec::new();
        for uri in listed {
            let Ok(s) = atproto::space::SpaceRef::parse(&uri) else {
                continue;
            };
            let ours = s.authority == did
                && s.kind == SPACE_TYPE
                && checked_id(&s.skey).is_ok_and(|id| id == s.skey);
            if !ours {
                continue;
            }
            if doomed.contains(&uri) {
                if hud.delete_space(&r.account, &uri).await.is_ok() {
                    // Its entry is there: `doomed` was read from it.
                    let mut st = self.lock();
                    st.doomed.get_mut(did).into_iter().for_each(|d| {
                        d.remove(&uri);
                    });
                }
                continue;
            }
            let records = hud.space_records(&r.account, &uri).await.map_err(refused)?;
            out.push((uri, s.skey, records));
        }
        Ok(out)
    }

    /// A person's canvases in spaces put in files, as memory holds them;
    /// their spaces left as they are.
    fn to_files(&self, st: &mut State, did: &str) {
        let moved: Vec<(String, Kept)> = st.kept.extract_if(|_, k| k.info.owner == did).collect();
        for (id, k) in moved {
            if let Err(e) = self.files.put(&k.info, &k.tiles) {
                tracing::error!(canvas = id, error = %e, "could not keep a canvas");
            }
            st.waiting.retain(|(c, _), _| *c != id);
            st.left.insert(id, k.uri);
        }
    }

    /// A write that failed: counted, and the third in a row puts the
    /// person's canvases back in files, their pages told. The failure in
    /// one line.
    fn failed(&self, hud: &Hud, did: &str, f: &Failure) -> String {
        let line = f.line();
        {
            let mut st = self.lock();
            let Some(p) = st.people.get_mut(did).filter(|p| p.choice == Choice::Space) else {
                return line;
            };
            p.failures += 1;
            let failures = p.failures;
            tracing::warn!(did, failures, why = line, "a write to a space failed");
            if p.failures < FAILURES_MAX {
                return line;
            }
            p.choice = Choice::File {
                reason: format!(
                    "writing to your PDS failed {FAILURES_MAX} times in a row ({line}); sign in again to try again"
                ),
                again: false,
            };
            self.to_files(&mut st, did);
        }
        tracing::warn!(did, "canvases back in files");
        hud.canvases.workspace_changed(did);
        line
    }

    fn succeeded(&self, did: &str) {
        let mut st = self.lock();
        st.people
            .get_mut(did)
            .into_iter()
            .for_each(|p| p.failures = 0);
    }

    /// Keep a change, its canvas's lane held but for tiles' places alone.
    async fn write(self: &Arc<Self>, change: Change<'_>) -> Result<(), String> {
        let info = info_of(&change);
        let change = match change {
            Change::Tiles {
                info,
                tiles,
                changed,
                gone,
            } => {
                let changed: Vec<&Tile> = changed
                    .into_iter()
                    .filter(|t| !self.placed(info, t))
                    .collect();
                if changed.is_empty() && gone.is_empty() {
                    return Ok(());
                }
                Change::Tiles {
                    info,
                    tiles,
                    changed,
                    gone,
                }
            }
            other => other,
        };
        let lane = self.lane(&info.id);
        let _lane = lane.lock().await;
        let tiles = match &change {
            Change::Deleted(info) => return self.delete(info).await,
            Change::Info { tiles, .. } | Change::Tiles { tiles, .. } => *tiles,
        };
        // Where it goes, decided at once: a canvas in its space noted; one
        // that is to leave it (a canvas shared now) kept in its file and
        // taken out, its space then deleted (its owner's canvases in
        // spaces are always theirs to keep there: `to_files` empties them).
        let way = {
            let mut st = self.lock();
            let belongs = Self::belongs(&st, info);
            let State { kept, waiting, .. } = &mut *st;
            match kept.entry(info.id.clone()) {
                Entry::Occupied(mut k) if belongs => {
                    Self::note(k.get_mut(), waiting, &change);
                    Way::Sync
                }
                Entry::Occupied(k) => {
                    self.files.put(info, tiles)?;
                    waiting.retain(|(c, _), _| *c != info.id);
                    Way::Out(Box::new(k.remove()))
                }
                Entry::Vacant(_) if belongs => Way::In,
                Entry::Vacant(_) => Way::File,
            }
        };
        match way {
            Way::File => self.files.put(info, tiles),
            Way::In => self.move_in(info, tiles).await,
            Way::Out(k) => {
                self.drop_space(&info.owner, &k).await;
                Ok(())
            }
            Way::Sync => self.sync(&info.id).await,
        }
    }

    /// A tile of a canvas in a space placed and nothing else: noted, its
    /// write put off until a second after its last such change. False for
    /// any other change.
    fn placed(self: &Arc<Self>, info: &CanvasInfo, tile: &Tile) -> bool {
        let mut st = self.lock();
        if !Self::belongs(&st, info) {
            return false;
        }
        let State { kept, waiting, .. } = &mut *st;
        let Some(old) = kept
            .get_mut(&info.id)
            .and_then(|k| k.tiles.iter_mut().find(|t| t.id == tile.id))
        else {
            return false;
        };
        if !placed_only(old, tile) {
            return false;
        }
        *old = tile.clone();
        let due = Instant::now() + SETTLE;
        let key = (info.id.clone(), tile.id.clone());
        match waiting.entry(key.clone()) {
            Entry::Occupied(mut e) => {
                e.insert(Some(due));
            }
            Entry::Vacant(e) => {
                e.insert(Some(due));
                crate::telemetry::spawn(self.clone().settle_tile(key));
            }
        }
        true
    }

    /// A change to a canvas in a space, `k`, noted: what is to be written.
    fn note(
        k: &mut Kept,
        waiting: &mut HashMap<(String, String), Option<Instant>>,
        change: &Change<'_>,
    ) {
        let id = &k.info.id;
        match change {
            Change::Tiles { changed, gone, .. } => {
                for tile in changed {
                    match k.tiles.iter_mut().find(|t| t.id == tile.id) {
                        Some(old) => *old = (*tile).clone(),
                        None => k.tiles.push((*tile).clone()),
                    }
                    k.unput.insert(tile.id.clone());
                    waiting.remove(&(id.clone(), tile.id.clone()));
                }
                for (tid, _) in gone {
                    k.tiles.retain(|t| t.id != *tid);
                    k.unput.remove(*tid);
                    k.undeleted.insert(tid.to_string());
                    waiting.remove(&(id.clone(), tid.to_string()));
                }
            }
            // Its info (a canvas deleted is never noted).
            _ => {
                k.info = info_of(change).clone();
                k.unput.insert(SELF.into());
            }
        }
    }

    /// Write what a canvas in a space has still to write, its lane held:
    /// stopped at the first failure, which stays to be tried again.
    async fn sync(&self, id: &str) -> Result<(), String> {
        let Some(hud) = self.hud.upgrade() else {
            return Ok(());
        };
        // What it has to write: its info, its tiles still on it, and the
        // tiles taken off.
        let pending = {
            let st = self.lock();
            st.kept.get(id).map(|k| {
                let puts: Vec<String> = k
                    .unput
                    .iter()
                    .filter(|r| *r == SELF || k.tiles.iter().any(|t| &t.id == *r))
                    .cloned()
                    .collect();
                let deletes: Vec<String> = k.undeleted.iter().cloned().collect();
                (k.info.owner.clone(), k.uri.clone(), puts, deletes)
            })
        };
        let Some((did, uri, puts, deletes)) =
            pending.filter(|(_, _, puts, deletes)| !puts.is_empty() || !deletes.is_empty())
        else {
            return Ok(());
        };
        let Some(r) = self.reach(&hud, &did).await else {
            return Err(self.failed(&hud, &did, &Failure::SignedOut));
        };
        for rkey in puts {
            // Its canvas gone from its space since: no more of it written.
            let record = self.lock().kept.get(id).and_then(|k| record_of(k, &rkey));
            let Some(record) = record else {
                return Ok(());
            };
            let collection = if rkey == SELF { CANVAS } else { TILE };
            if let Err(f) = put(&hud, &r, &uri, collection, &rkey, record).await {
                return Err(self.failed(&hud, &did, &f));
            }
            if let Some(k) = self.lock().kept.get_mut(id) {
                k.unput.remove(&rkey);
            }
        }
        for rkey in deletes {
            match hud.delete_space_record(&r.account, &uri, TILE, &rkey).await {
                Ok(()) => {
                    if let Some(k) = self.lock().kept.get_mut(id) {
                        k.undeleted.remove(&rkey);
                    }
                }
                Err(f) => return Err(self.failed(&hud, &did, &f)),
            }
        }
        self.succeeded(&did);
        Ok(())
    }

    /// Move a canvas of a person whose canvases go in spaces into its
    /// space, its lane held: its file kept first, put aside once the space
    /// holds it whole.
    async fn move_in(&self, info: &CanvasInfo, tiles: &[Tile]) -> Result<(), String> {
        self.files.put(info, tiles)?;
        let Some(hud) = self.hud.upgrade() else {
            return Ok(());
        };
        let did = &info.owner;
        let Some(r) = self.reach(&hud, did).await else {
            return Err(self.failed(&hud, did, &Failure::SignedOut));
        };
        let uri = space::uri(did, SPACE_TYPE, &info.id);
        let moved = async {
            hud.create_space(&r.account, SPACE_TYPE, &info.id).await?;
            put(&hud, &r, &uri, CANVAS, SELF, info.record()).await?;
            for t in tiles {
                put(&hud, &r, &uri, TILE, &t.id, t.record()).await?;
            }
            Ok::<(), Failure>(())
        };
        if let Err(f) = moved.await {
            return Err(self.failed(&hud, did, &f));
        }
        if let Err(e) = self.files.put_aside(&info.id) {
            tracing::warn!(canvas = info.id, error = %e, "could not put a moved canvas's file aside");
        }
        {
            let mut st = self.lock();
            st.left.remove(&info.id);
            st.kept.insert(
                info.id.clone(),
                Kept {
                    uri: uri.clone(),
                    info: info.clone(),
                    tiles: tiles.to_vec(),
                    unput: BTreeSet::new(),
                    undeleted: BTreeSet::new(),
                },
            );
        }
        self.succeeded(did);
        let id = &info.id;
        tracing::info!(canvas = id, space = uri, "a canvas moved into its space");
        Ok(())
    }

    /// Delete a canvas, its lane held: its file, and its space if it had
    /// one.
    async fn delete(&self, info: &CanvasInfo) -> Result<(), String> {
        let (kept, left) = {
            let mut st = self.lock();
            st.waiting.retain(|(c, _), _| *c != info.id);
            (st.kept.remove(&info.id), st.left.remove(&info.id))
        };
        let file = self.files.write(Change::Deleted(info)).await;
        match (kept, left) {
            (Some(k), _) => self.drop_space(&info.owner, &k).await,
            (None, Some(uri)) => self.doom(&info.owner, &uri),
            (None, None) => {}
        }
        file
    }

    /// Delete a canvas's space; failing that, as a grant without deleting
    /// spaces does, its records. What could not be deleted is tried again
    /// at the owner's next decision.
    async fn drop_space(&self, did: &str, k: &Kept) {
        let Some(hud) = self.hud.upgrade() else {
            return;
        };
        let Some(r) = self.reach(&hud, did).await else {
            return self.doom(did, &k.uri);
        };
        match hud.delete_space(&r.account, &k.uri).await {
            Ok(()) => tracing::info!(space = k.uri, "a canvas's space deleted"),
            Err(f) if f.transient() => {
                let why = f.line();
                tracing::warn!(space = k.uri, why, "a canvas's space was not deleted");
                self.doom(did, &k.uri);
            }
            Err(_) => {
                let mut records = vec![(CANVAS, SELF.to_string())];
                records.extend(k.tiles.iter().map(|t| (TILE, t.id.clone())));
                for (collection, rkey) in records {
                    let gone = hud
                        .delete_space_record(&r.account, &k.uri, collection, &rkey)
                        .await;
                    if let Err(f) = gone {
                        let why = f.line();
                        tracing::warn!(space = k.uri, why, "a canvas's records were not deleted");
                        return self.doom(did, &k.uri);
                    }
                }
            }
        }
    }

    fn doom(&self, did: &str, uri: &str) {
        self.lock()
            .doomed
            .entry(did.to_string())
            .or_default()
            .insert(uri.to_string());
    }

    /// What is kept of a person's past their canvases deleted: their
    /// files (`FileStore::forget`), what memory holds of theirs, and every
    /// workspace space of theirs their sign-in reaches, each deleted, or
    /// failing that, as a grant without deleting spaces does, emptied of
    /// its records. Every failure, in a line each.
    async fn forget(&self, did: &str) -> Result<(), Vec<String>> {
        let mut failed = self.files.forget(did).await.err().unwrap_or_default();
        {
            let mut st = self.lock();
            let theirs =
                |uri: &str| atproto::space::SpaceRef::parse(uri).is_ok_and(|s| s.authority == did);
            let ids: Vec<String> = st
                .kept
                .iter()
                .filter(|(_, k)| k.info.owner == did)
                .map(|(id, _)| id.clone())
                .collect();
            for id in &ids {
                st.kept.remove(id);
                st.waiting.retain(|(c, _), _| c != id);
            }
            st.left.retain(|_, uri| !theirs(uri));
            st.doomed.remove(did);
            st.people.remove(did);
        }
        let hud = self.hud.upgrade();
        let reach = match &hud {
            Some(hud) => self.reach(hud, did).await.filter(|r| grants(&r.scope)),
            None => None,
        };
        if let (Some(hud), Some(r)) = (hud, reach) {
            let listed = match hud.spaces_alpha(&r.pds).await {
                Ok(false) => Ok(Vec::new()),
                Ok(true) => hud
                    .spaces_of(&r.account, SPACE_TYPE)
                    .await
                    .map_err(|f| f.line()),
                Err(why) => Err(format!("your PDS could not be reached: {why}")),
            };
            match listed {
                Err(why) => failed.push(format!("your workspace spaces were not listed: {why}")),
                Ok(listed) => {
                    for uri in listed {
                        let ours = atproto::space::SpaceRef::parse(&uri)
                            .is_ok_and(|s| s.authority == did && s.kind == SPACE_TYPE);
                        if !ours {
                            continue;
                        }
                        if let Err(f) = Self::delete_whole(&hud, &r, &uri).await {
                            failed.push(format!("{uri} was not deleted: {}", f.line()));
                        }
                    }
                }
            }
        }
        if failed.is_empty() {
            Ok(())
        } else {
            Err(failed)
        }
    }

    /// Delete a space of `r`'s; failing that for want of permission, its
    /// records in it.
    async fn delete_whole(hud: &Hud, r: &Reach, uri: &str) -> Result<(), Failure> {
        match hud.delete_space(&r.account, uri).await {
            Err(f) if !f.transient() => {
                for rec in hud.space_records(&r.account, uri).await? {
                    hud.delete_space_record(&r.account, uri, &rec.collection, &rec.rkey)
                        .await?;
                }
                tracing::info!(space = uri, "a space emptied, as it was not deleted");
                Ok(())
            }
            done => done,
        }
    }

    /// Write a placed tile once its last such change is a second
    /// old, and again if it changes so while written.
    async fn settle_tile(self: Arc<Self>, key: (String, String)) {
        loop {
            let next = match self.lock().waiting.get(&key) {
                Some(Some(due)) if Instant::now() < *due => Next::Wait(*due),
                Some(Some(_)) => Next::Write,
                _ => Next::Done,
            };
            match next {
                Next::Done => return,
                Next::Wait(due) => {
                    tokio::select! {
                        () = tokio::time::sleep_until(due) => {}
                        () = self.hurry.notified() => {}
                    }
                    continue;
                }
                Next::Write => {}
            }
            let lane = self.lane(&key.0);
            let _lane = lane.lock().await;
            let next = {
                let mut st = self.lock();
                match st.waiting.get(&key) {
                    Some(Some(due)) if Instant::now() < *due => Next::Wait(*due),
                    Some(Some(_)) => {
                        st.waiting.insert(key.clone(), None);
                        st.kept.get_mut(&key.0).into_iter().for_each(|k| {
                            k.unput.insert(key.1.clone());
                        });
                        Next::Write
                    }
                    _ => Next::Done,
                }
            };
            match next {
                Next::Wait(_) => continue,
                Next::Done => {
                    self.lock().waiting.remove(&key);
                    return;
                }
                Next::Write => {}
            }
            if let Err(why) = self.sync(&key.0).await {
                tracing::warn!(canvas = key.0, why, "a tile's place was not written");
            }
            let mut st = self.lock();
            if let Some(None) = st.waiting.get(&key) {
                st.waiting.remove(&key);
                return;
            }
        }
    }

    /// Write every tile waiting now, and wait for them, a while at most.
    async fn flush(&self) {
        let until = Instant::now() + FLUSH_MAX;
        while Instant::now() < until {
            {
                let mut st = self.lock();
                if st.waiting.is_empty() {
                    return;
                }
                let now = Instant::now();
                for due in st.waiting.values_mut().flatten() {
                    *due = now;
                }
            }
            self.hurry.notify_waiters();
            tokio::time::sleep(Duration::from_millis(10)).await;
        }
        tracing::warn!("tiles' places left unwritten");
    }
}

/// Put a record in the account's repo in a space, checked first.
async fn put(
    hud: &Hud,
    r: &Reach,
    uri: &str,
    collection: &str,
    rkey: &str,
    record: Value,
) -> Result<(), Failure> {
    let record = checked(collection, record)?;
    hud.put_space_record(&r.account, uri, collection, rkey, &record)
        .await
}

impl Store for SpaceStore {
    fn canvases(&self) -> Fut<'_, Vec<(CanvasInfo, usize)>> {
        self.inner.files.canvases()
    }

    fn tiles<'a>(&'a self, info: &'a CanvasInfo) -> Fut<'a, Result<Vec<Tile>, String>> {
        Box::pin(async move {
            if let Some(k) = self.inner.lock().kept.get(&info.id) {
                return Ok(k.tiles.clone());
            }
            self.inner.files.tiles(info).await
        })
    }

    fn write<'a>(&'a self, change: Change<'a>) -> Fut<'a, Result<(), String>> {
        Box::pin(self.inner.write(change))
    }

    fn index<'a>(&'a self, did: &'a str) -> Fut<'a, Option<Index>> {
        self.inner.files.index(did)
    }

    fn put_index<'a>(&'a self, did: &'a str, index: &'a Index) -> Fut<'a, Result<(), String>> {
        self.inner.files.put_index(did, index)
    }

    fn legacy<'a>(&'a self, did: &'a str) -> Fut<'a, Option<Vec<Tile>>> {
        self.inner.files.legacy(did)
    }

    fn retire_legacy<'a>(&'a self, did: &'a str) -> Fut<'a, ()> {
        self.inner.files.retire_legacy(did)
    }

    fn person<'a>(&'a self, did: &'a str) -> Fut<'a, Option<Vec<(CanvasInfo, usize)>>> {
        Box::pin(self.inner.decide(did))
    }

    fn misplaced(&self, info: &CanvasInfo) -> bool {
        let st = self.inner.lock();
        !st.kept.contains_key(&info.id) && Inner::belongs(&st, info)
    }

    fn storage(&self, info: &CanvasInfo) -> Value {
        let st = self.inner.lock();
        if let Some(k) = st.kept.get(&info.id) {
            return json!({ "kind": "space", "uri": k.uri });
        }
        let reason = if info.members.len() > 1 {
            Some(SHARED.to_string())
        } else {
            match st.people.get(&info.owner).map(|p| &p.choice) {
                Some(Choice::File { reason, .. }) => Some(reason.clone()),
                Some(Choice::Space) => {
                    Some("not in your PDS yet: it moves there with its next change".into())
                }
                None => None,
            }
        };
        match reason {
            Some(reason) => json!({ "kind": "file", "reason": reason }),
            None => json!({ "kind": "file" }),
        }
    }

    fn flush(&self) -> Fut<'_, ()> {
        Box::pin(self.inner.flush())
    }

    fn forget<'a>(&'a self, did: &'a str) -> Fut<'a, Result<(), Vec<String>>> {
        Box::pin(self.inner.forget(did))
    }
}

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

    fn tile(arguments: Value) -> Tile {
        Tile {
            id: "00000000000a".into(),
            tool: "query".into(),
            arguments,
            title: "For You".into(),
            order: 2.5,
            width: Width::TwoThirds,
            stack: Some("00000000000e".into()),
            by: By::Agent,
            author: "did:plc:alice".into(),
            at: "2026-11-14T12:00:00.000Z".into(),
            from: Some("00000000000f".into()),
        }
    }

    #[test]
    fn the_scope_asked_and_granted() {
        // The one string asked for, of HUD's workspace type.
        assert_eq!(
            crate::config::SPACE_SCOPE,
            format!("space:{SPACE_TYPE}?authority=*&manage=create&manage=update&manage=delete")
        );
        let asked = crate::scope::asked(crate::view::views(), true, true);
        assert!(!grants(&crate::scope::asked(
            crate::view::views(),
            true,
            false
        )));
        // Granted as asked, or written out again by the PDS with the DID
        // and the type's collections.
        assert!(grants(&asked));
        assert!(grants(
            "atproto space:place.hud.workspace?authority=*&collection=place.hud.canvas&collection=place.hud.tile&manage=create&manage=update&manage=delete"
        ));
        assert!(grants("atproto space:*?manage=create"));
        for scope in [
            "atproto transition:generic",
            "atproto space:place.hud.workspace",
            "atproto space:com.example.other?manage=create",
            "atproto space:place.hud.workspace.x?manage=create",
        ] {
            assert!(!grants(scope), "{scope}");
        }
    }

    #[test]
    fn records_as_their_lexicons_say() {
        // The lexicons: a space type of the two collections, and records.
        let decl = crate::lexicon::bundled(SPACE_TYPE).unwrap();
        let main = &decl["defs"]["main"];
        assert_eq!(
            (main["type"].as_str(), main["key"].as_str()),
            (Some("space"), Some("any"))
        );
        assert_eq!(main["collections"], json!([CANVAS, TILE]));
        assert!(main["name"].is_string() && main["description"].is_string());
        for nsid in [CANVAS, TILE] {
            let doc = crate::lexicon::bundled(nsid).unwrap();
            assert_eq!(doc["defs"]["main"]["type"], "record", "{nsid}");
        }
        // A tile's record: its place as text, checked, and read back as it was.
        let t = tile(
            json!({ "method": "app.bsky.feed.getFeed", "params": { "feed": "For You", "limit": 5 } }),
        );
        let record = checked(TILE, t.record()).unwrap();
        assert_eq!(
            (
                &record["order"],
                &record["width"],
                &record["stack"],
                &record["by"]
            ),
            (
                &json!("2.5"),
                &json!("two-thirds"),
                &json!("00000000000e"),
                &json!("agent")
            )
        );
        assert!(record.get("argumentsJson").is_none());
        let back = Tile::from_record(&t.id, &record, "did:plc:alice").unwrap();
        assert_eq!(back, t);
        // Arguments a record cannot hold go as JSON text.
        let odd = tile(json!({ "view": { "ratio": 1.5 }, "x": { "$bytes": "AA" } }));
        let record = checked(TILE, odd.record()).unwrap();
        assert!(record.get("arguments").is_none());
        assert_eq!(
            Tile::from_record(&odd.id, &record, "did:plc:alice")
                .unwrap()
                .arguments,
            odd.arguments
        );
        // What is not a tile HUD makes is left out.
        let mut bad = t.record();
        bad["tool"] = json!("create_record");
        assert!(Tile::from_record(&t.id, &bad, "did:plc:alice").is_none());
        assert!(Tile::from_record("self", &t.record(), "did:plc:alice").is_none());
        // A canvas's info, checked; and a canvas from its records, its
        // tiles oldest first.
        let info = CanvasInfo {
            id: "0123456789ab".into(),
            name: "Coast trip".into(),
            owner: "did:plc:alice".into(),
            members: vec![],
            created_at: "2026-11-14T00:00:00.000Z".into(),
            updated_at: "2026-11-14T00:00:00.000Z".into(),
        };
        let me = checked(CANVAS, info.record()).unwrap();
        let newer = Tile {
            id: "00000000000b".into(),
            at: "2026-11-14T13:00:00.000Z".into(),
            ..back.clone()
        };
        let records = [
            SpaceRecord {
                collection: TILE.into(),
                rkey: newer.id.clone(),
                value: newer.record(),
            },
            SpaceRecord {
                collection: TILE.into(),
                rkey: back.id.clone(),
                value: back.record(),
            },
            SpaceRecord {
                collection: CANVAS.into(),
                rkey: SELF.into(),
                value: me,
            },
        ];
        let (read, tiles, moved) =
            canvas_of(&info.id, &info.owner, Some("alice.test"), &records).unwrap();
        assert_eq!(read.name, "Coast trip");
        assert_eq!(read.members[0].role, Role::Owner);
        assert_eq!(read.members[0].handle.as_deref(), Some("alice.test"));
        assert_eq!(
            tiles.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
            ["00000000000a", "00000000000b"]
        );
        assert!(moved.is_empty());
        assert!(canvas_of(&info.id, &info.owner, None, &records[..2]).is_none());
    }

    #[test]
    fn records_from_before_columns_made_columns() {
        // Two tile records as HUD wrote them before columns.
        let old = |rkey: &str, x: i64, y: i64, w: i64| SpaceRecord {
            collection: TILE.into(),
            rkey: rkey.into(),
            value: json!({ "$type": TILE, "tool": "describe_repo", "arguments": { "actor": "me" },
                "title": rkey, "x": x, "y": y, "w": w, "h": 560, "by": "you",
                "createdAt": "2026-11-14T12:00:00.000Z" }),
        };
        let records = [
            old("00000000000a", 500, 0, 800),
            old("00000000000b", 0, 0, 600),
            SpaceRecord {
                collection: CANVAS.into(),
                rkey: SELF.into(),
                value: json!({ "$type": CANVAS, "name": "Old", "createdAt": "2026-11-14T00:00:00.000Z",
                    "updatedAt": "2026-11-14T00:00:00.000Z" }),
            },
        ];
        let (_, tiles, moved) = canvas_of("0123456789ab", "did:plc:alice", None, &records).unwrap();
        let placed: Vec<(&str, f64, Width, By)> = tiles
            .iter()
            .map(|t| (t.id.as_str(), t.order, t.width, t.by))
            .collect();
        assert_eq!(
            placed,
            [
                ("00000000000a", 2.0, Width::TwoThirds, By::Person),
                ("00000000000b", 1.0, Width::Half, By::Person)
            ]
        );
        // Both to write again, each now valid for the lexicon.
        assert_eq!(moved.len(), 2);
        for t in &tiles {
            checked(TILE, t.record()).unwrap();
        }
    }

    #[test]
    fn places_alone_wait() {
        let t = tile(json!({}));
        let moved = Tile {
            order: 99.0,
            width: Width::Full,
            stack: None,
            ..t.clone()
        };
        assert!(placed_only(&t, &moved));
        let retitled = Tile {
            title: "Other".into(),
            ..t.clone()
        };
        assert!(!placed_only(&t, &retitled));
    }

    #[test]
    fn the_newest_tiles_kept_and_records_with_no_lexicon_refused() {
        // More tiles than a canvas holds, from before columns: the newest
        // kept, and those alone written again.
        let records: Vec<SpaceRecord> = (0..=MAX_TILES)
            .map(|n| SpaceRecord {
                collection: TILE.into(),
                rkey: format!("{n:012x}"),
                value: json!({ "$type": TILE, "tool": "describe_repo", "arguments": {},
                    "title": "t", "x": n, "y": 0, "w": 420, "h": 560, "by": "agent",
                    "createdAt": format!("2026-11-14T12:{:02}:{:02}.000Z", n / 60, n % 60) }),
            })
            .chain([SpaceRecord {
                collection: CANVAS.into(),
                rkey: SELF.into(),
                value: json!({ "$type": CANVAS, "name": "Full", "createdAt": "2026-11-14T00:00:00.000Z",
                    "updatedAt": "2026-11-14T00:00:00.000Z" }),
            }])
            .collect();
        let (_, tiles, moved) = canvas_of(ID, ALICE, None, &records).unwrap();
        assert_eq!(tiles.len(), MAX_TILES);
        assert_eq!(tiles[0].id, format!("{:012x}", 1));
        assert_eq!(moved.len(), MAX_TILES);
        assert!(!moved.contains(&format!("{:012x}", 0)));
        assert_eq!(
            checked("com.example.nothing", json!({})),
            Err(Failure::Failed("com.example.nothing has no lexicon".into()))
        );
    }

    const ALICE: &str = "did:plc:alice";
    const ID: &str = "0123456789ab";

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

    /// A store whose server is gone, its files in `dir`.
    fn serverless(dir: &std::path::Path) -> Arc<Inner> {
        Arc::new(Inner {
            hud: Weak::new(),
            files: FileStore::new(dir.to_path_buf()),
            state: Mutex::new(State::default()),
            hurry: tokio::sync::Notify::new(),
        })
    }

    fn info() -> 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(),
        }
    }

    /// The canvas as kept in its space, its one tile written.
    fn in_space() -> Kept {
        Kept {
            uri: space::uri(ALICE, SPACE_TYPE, ID),
            info: info(),
            tiles: vec![tile(json!({}))],
            unput: BTreeSet::new(),
            undeleted: BTreeSet::new(),
        }
    }

    /// A server with its data in `dir`, spaces off.
    fn hud(dir: &std::path::Path) -> Arc<Hud> {
        Hud::new(crate::Config {
            port: 0,
            bind: "::".parse().unwrap(),
            public_origin: "https://hud.test".into(),
            cache_dir: dir.join("cache"),
            blob_cache_bytes: 0,
            cache_memory_bytes: 1 << 24,
            data_dir: dir.join("data"),
            oauth: false,
            oauth_scope: crate::scope::asked(crate::view::views(), true, false),
            oauth_include: None,
            workspace: true,
            sign_up_pds: crate::config::SIGN_UP_PDS.into(),
            client: Default::default(),
            operators: Vec::new(),
            logs: false,
            logs_keep: crate::logs::KEEP,
            spaces: false,
            plc_url: "http://127.0.0.1:9".into(),
            handle_resolver: None,
            allow_private: false,
            backlinks: crate::backlinks::Backlinks::None,
            favicons: None,
            image_cdn: None,
            relay: None,
        })
        .unwrap()
    }

    #[tokio::test]
    async fn a_place_waiting_for_a_canvas_gone_from_its_space_is_dropped() {
        let d = dir();
        let server = hud(&d);
        let inner = Arc::new(Inner {
            hud: Arc::downgrade(&server),
            files: FileStore::new(d.clone()),
            state: Mutex::new(State::default()),
            hurry: tokio::sync::Notify::new(),
        });
        let key = (ID.to_string(), "00000000000a".to_string());
        inner
            .lock()
            .waiting
            .insert(key.clone(), Some(Instant::now()));
        inner.clone().settle_tile(key).await;
        assert!(inner.lock().waiting.is_empty());
        assert!(inner.lock().people.is_empty());
        std::fs::remove_dir_all(&d).unwrap();
    }

    #[tokio::test(start_paused = true)]
    async fn places_written_once_settled() {
        let d = dir();
        let inner = serverless(&d);
        let key = (ID.to_string(), "00000000000a".to_string());
        inner.lock().kept.insert(ID.into(), in_space());
        let unput = |inner: &Inner| inner.lock().kept[ID].unput.contains(&key.1);
        let clear = |inner: &Inner| inner.lock().kept.get_mut(ID).unwrap().unput.clear();
        // Nothing waiting: nothing to write.
        inner.clone().settle_tile(key.clone()).await;
        assert!(!unput(&inner));
        // Waiting a second: then to be written.
        inner
            .lock()
            .waiting
            .insert(key.clone(), Some(Instant::now() + SETTLE));
        let start = Instant::now();
        inner.clone().settle_tile(key.clone()).await;
        assert!(start.elapsed() >= SETTLE);
        assert!(inner.lock().waiting.is_empty());
        assert!(unput(&inner));
        // Its canvas's lane busy with another write: placed again
        // meanwhile, it waits again; taken off meanwhile, it is not.
        clear(&inner);
        let lane = inner.lane(ID);
        let busy = lane.lock().await;
        inner
            .lock()
            .waiting
            .insert(key.clone(), Some(Instant::now()));
        let task = tokio::spawn(inner.clone().settle_tile(key.clone()));
        tokio::task::yield_now().await;
        inner
            .lock()
            .waiting
            .insert(key.clone(), Some(Instant::now() + SETTLE));
        let start = Instant::now();
        drop(busy);
        task.await.unwrap();
        assert!(start.elapsed() >= SETTLE);
        assert!(unput(&inner));
        clear(&inner);
        let busy = lane.lock().await;
        inner
            .lock()
            .waiting
            .insert(key.clone(), Some(Instant::now()));
        let task = tokio::spawn(inner.clone().settle_tile(key.clone()));
        tokio::task::yield_now().await;
        inner.lock().waiting.remove(&key);
        drop(busy);
        task.await.unwrap();
        assert!(!unput(&inner));
        // Flushed: what waits is written at once.
        inner
            .lock()
            .waiting
            .insert(key.clone(), Some(Instant::now() + SETTLE));
        let task = tokio::spawn(inner.clone().settle_tile(key.clone()));
        tokio::task::yield_now().await;
        let start = Instant::now();
        inner.flush().await;
        assert!(start.elapsed() < SETTLE);
        task.await.unwrap();
        assert!(unput(&inner));
        // What no write comes for is given up on, after a while.
        inner
            .lock()
            .waiting
            .insert(key.clone(), Some(Instant::now() + SETTLE));
        let start = Instant::now();
        inner.flush().await;
        assert!(start.elapsed() >= FLUSH_MAX);
        assert_eq!(inner.lock().waiting.len(), 1);
        std::fs::remove_dir_all(&d).unwrap();
    }

    #[tokio::test]
    async fn with_the_server_gone_canvases_stay_in_files() {
        let d = dir();
        let inner = serverless(&d);
        // Moved in: kept in its file, and no further.
        assert_eq!(inner.move_in(&info(), &in_space().tiles).await, Ok(()));
        assert!(inner.files.has(ID));
        assert!(inner.lock().kept.is_empty());
        // Its space not deleted, nor kept to delete later.
        inner.drop_space(ALICE, &in_space()).await;
        assert!(inner.lock().doomed.is_empty());
        // Put back in files where its file cannot be written: its space
        // remembered all the same, its places no longer waiting.
        std::fs::remove_file(d.join(format!("{ID}.json"))).unwrap();
        std::fs::create_dir_all(d.join(format!("{ID}.json")).join("x")).unwrap();
        let mut st = inner.lock();
        st.kept.insert(ID.into(), in_space());
        st.waiting
            .insert((ID.into(), "00000000000a".into()), Some(Instant::now()));
        inner.to_files(&mut st, ALICE);
        assert!(st.kept.is_empty() && st.waiting.is_empty());
        assert_eq!(st.left[ID], in_space().uri);
        drop(st);
        std::fs::remove_dir_all(&d).unwrap();
    }

    #[tokio::test]
    async fn where_each_canvas_is_said_to_be_kept() {
        let d = dir();
        let store = SpaceStore {
            inner: serverless(&d),
        };
        let info = info();
        // Its owner not yet seen: in a file, no more said.
        assert_eq!(store.storage(&info), json!({ "kind": "file" }));
        assert!(!store.misplaced(&info));
        // Theirs go in spaces: this one not yet.
        let person = |choice| Person {
            key: None,
            choice,
            failures: 0,
            decided: Instant::now(),
        };
        store
            .inner
            .lock()
            .people
            .insert(ALICE.into(), person(Choice::Space));
        assert_eq!(
            store.storage(&info),
            json!({ "kind": "file", "reason": "not in your PDS yet: it moves there with its next change" })
        );
        assert!(store.misplaced(&info));
        store.inner.lock().kept.insert(ID.into(), in_space());
        assert_eq!(
            store.storage(&info),
            json!({ "kind": "space", "uri": in_space().uri })
        );
        assert!(!store.misplaced(&info));
        // A canvas from before there were many, put aside once moved.
        let legacy = d.join(format!("{}.json", atproto::jose::sha256(ALICE)));
        std::fs::write(&legacy, "{}").unwrap();
        store.retire_legacy(ALICE).await;
        assert!(legacy.with_extension("json.moved").exists());
        // A failure of a person whose canvases are in files counts for
        // nothing.
        let hud = hud(&d);
        let file = Choice::File {
            reason: "your PDS does not offer spaces".into(),
            again: false,
        };
        store.inner.lock().people.insert(ALICE.into(), person(file));
        assert_eq!(
            store
                .inner
                .failed(&hud, ALICE, &Failure::Failed("timeout".into())),
            "your PDS could not be reached: timeout"
        );
        assert_eq!(store.inner.lock().people[ALICE].failures, 0);
        std::fs::remove_dir_all(&d).unwrap();
    }

    #[tokio::test]
    async fn forgotten_from_memory_with_the_server_gone() {
        let d = dir();
        let inner = serverless(&d);
        const BOB: &str = "did:plc:bob";
        let bobs = "0000000000bb";
        {
            let mut st = inner.lock();
            st.kept.insert(ID.into(), in_space());
            let mut his = in_space();
            his.info.owner = BOB.into();
            st.kept.insert(bobs.into(), his);
            st.waiting
                .insert((ID.into(), "00000000000a".into()), Some(Instant::now()));
            st.waiting
                .insert((bobs.into(), "00000000000a".into()), Some(Instant::now()));
            let left = |did: &str, id: &str| space::uri(did, SPACE_TYPE, id);
            st.left
                .insert("0000000000cc".into(), left(ALICE, "0000000000cc"));
            st.left
                .insert("0000000000dd".into(), left(BOB, "0000000000dd"));
            st.doomed
                .entry(ALICE.into())
                .or_default()
                .insert(in_space().uri);
            st.people.insert(
                ALICE.into(),
                Person {
                    key: None,
                    choice: Choice::Space,
                    failures: 0,
                    decided: Instant::now(),
                },
            );
        }
        // Nothing of hers kept in memory after; Bob's as it was.
        assert_eq!(inner.forget(ALICE).await, Ok(()));
        let st = inner.lock();
        let keys = |m: Vec<&String>| m.into_iter().cloned().collect::<Vec<_>>();
        assert_eq!(keys(st.kept.keys().collect()), [bobs]);
        assert_eq!(keys(st.left.keys().collect()), ["0000000000dd"]);
        assert_eq!(
            st.waiting
                .keys()
                .map(|(c, _)| c.as_str())
                .collect::<Vec<_>>(),
            [bobs]
        );
        assert!(st.doomed.is_empty() && st.people.is_empty());
        drop(st);
        std::fs::remove_dir_all(&d).unwrap();
    }
}