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

Spaces as the November 13 alpha has them

Merged chadtmiller.com asked to merge into main from chadtmiller.com/monolith:spaces-alpha-20261113
crates/pds-cli/src/lib.rs+9−5
@@ -284,7 +284,7 @@ static ENCODING: LazyLock<Arg> = LazyLock::new(|| Arg {
});
/// The one type a method's raw body may be, as `importSpaceMeta`'s
/// `application/octet-stream`; None for one of any type, as `uploadBlob`'s `*/*`.
/// `application/vnd.dasl.star`; None for one of any type, as `uploadBlob`'s `*/*`.
fn fixed_encoding(m: &Method) -> Option<&str> {
m.input
.as_deref()
@@ -832,12 +832,16 @@ mod tests {
assert!(flags("com.atproto.sync.getBlob", &["--encoding", "a/b"]).is_err());
}
/// `import-space-meta` takes its body from standard input as its one
/// type, `application/octet-stream`: it has no `--encoding`, nor any other flag.
/// `import-space-meta` and the space's `import-repo` take their body from
/// standard input as their one type, `application/vnd.dasl.star`: they
/// have no `--encoding`, nor any other flag.
#[test]
fn space_meta_commands() {
let import = pds_lexicon::method("com.atproto.space.importSpaceMeta").unwrap();
assert_eq!(fixed_encoding(import), Some("application/octet-stream"));
assert_eq!(fixed_encoding(import), Some("application/vnd.dasl.star"));
let repo = pds_lexicon::method("com.atproto.space.importRepo").unwrap();
assert_eq!(fixed_encoding(repo), Some("application/vnd.dasl.star"));
assert!(command_help(repo).contains("It takes no flags."));
assert_eq!(
fixed_encoding(pds_lexicon::method("com.atproto.repo.uploadBlob").unwrap()),
None
@@ -851,7 +855,7 @@ mod tests {
assert!(
flags(
"com.atproto.space.importSpaceMeta",
&["--encoding", "application/octet-stream"]
&["--encoding", "application/vnd.dasl.star"]
)
.is_err()
);
crates/pds-lexicon/src/lib.rs+11−9
@@ -213,9 +213,8 @@ const ADDITIVE: &[&str] = &[
"app.bsky.notification.registerPush",
"com.atproto.space.createSpace",
"com.atproto.space.createRecord",
"com.atproto.space.getSpaceCredential",
"com.atproto.space.notifyWrite",
"com.atproto.space.registerNotify",
"com.atproto.space.authorizeSpaceSync",
"com.atproto.space.notifyRepoUpdate",
];
/// `createRecord` as `create_record` (with `_`) or `create-record` (with `-`).
@@ -870,7 +869,7 @@ mod tests {
(Some("server_delete_session"), None, None)
);
let tools: Vec<String> = methods().iter().filter_map(Method::tool).collect();
assert_eq!(tools.len(), 81, "{tools:?}");
assert_eq!(tools.len(), 79, "{tools:?}");
// The methods of a move are tools, but `importRepo`, whose input is a CAR file.
for t in [
"repo_list_missing_blobs",
@@ -890,8 +889,10 @@ mod tests {
);
assert!(tools.contains(&"space_list_blobs".to_string()));
assert!(
tools.contains(&"space_notify_write".to_string())
&& tools.contains(&"space_list_repos".to_string())
tools.contains(&"space_notify_repo_update".to_string())
&& tools.contains(&"space_list_writers".to_string())
&& tools.contains(&"space_authorize_space_sync".to_string())
&& tools.contains(&"space_notify_credentials_revoked".to_string())
);
assert!(
tools.contains(&"sync_list_repos".to_string())
@@ -899,7 +900,8 @@ mod tests {
);
assert!(
tools.contains(&"space_create_space".to_string())
&& tools.contains(&"memberspace_put_member".to_string())
&& tools.contains(&"memberspace_put_members".to_string())
&& tools.contains(&"memberspace_remove_members".to_string())
);
// uploadBlob's input and getBlob's answer are bytes: neither has a tool, both a command;
// nor have importRepo's CAR file, a space meta archive's export and import, a space
@@ -1017,7 +1019,7 @@ mod tests {
method("com.atproto.sync.getRepo").unwrap().input_schema()["required"],
json!([])
);
let n = method("com.atproto.space.notifyWrite")
let n = method("com.atproto.space.notifyRepoUpdate")
.unwrap()
.input_schema();
assert!(n["properties"]["data"].get("type").is_none());
@@ -1040,7 +1042,7 @@ mod tests {
"com.atproto.repo.applyWrites",
"com.atproto.space.deleteRecord",
"com.atproto.space.clearRecords",
"com.atproto.memberspace.putMember",
"com.atproto.memberspace.putMembers",
"com.atproto.server.deleteSession",
"com.atproto.identity.updateHandle",
"app.bsky.actor.putPreferences",
crates/pds-server/src/checkpoint/before.rs+83−144
@@ -1,27 +1,19 @@
//! A table of the version before, which the last release wrote: it has no
//! `H`, its `S` says version 2 and holds the table's generation, the last
//! `seq` and the greatest seq let go, and each space repo whole: its
//! space's URI, its rev and `data`, its records, `[path, DRISL bytes]`,
//! the rev that last wrote each, `[path, rev]`, and its operation log,
//! each operation's rev, collection, rkey, and CID after and before it.
//! The rest of its `S`, and its other sections, are as this version's.
//! `seq` and the greatest seq let go. The rest of its `S`, and its other
//! sections, are as this version's, but for what it holds of spaces.
//!
//! It is read whole, once, by the fold that makes a table of this version
//! of it (`load`): its space repos become the entries of their sections,
//! each checked as a load of the version before checked it.
//! It is read once, by the fold that makes a table of this version of it
//! (`load`). Of spaces it keeps nothing: its space repos, held whole in
//! its `S`, the spaces it is the authority of and its notifications are
//! let go, unread but for what its space repos' records reference of
//! blobs, which is counted until the log's mark (`unmarked`).
use super::spaces::{self, Entries, Meta, op_key, op_value, ref_key, space_key};
use super::{
Small, VERSION, as_bytes, as_link, as_list, as_pair, as_text, as_uint, fields, int, key, map,
or_none, text,
};
use super::unmarked::Unmarked;
use super::{Small, VERSION, as_uint, map};
use crate::blobs::cids_in;
use crate::space_repo::Op;
use pds_repo::data::{V, cid_of, cid_string, decode};
use pds_repo::data::{V, decode};
use pds_repo::valid_tid;
use pds_space::LtHash;
use pds_space::lthash::element;
use std::collections::BTreeMap;
/// The version a table of the version before says it is.
const BEFORE: i64 = 2;
@@ -53,144 +45,91 @@ pub(super) fn generation(bytes: &[u8]) -> Result<u64, String> {
as_uint(take(&mut state(bytes)?, "generation")?, "generation")
}
/// Read an `S` value of the version before, of the account `did`: the
/// state, and the entries of the space repos' sections, by key.
pub(super) fn read(bytes: &[u8], did: &str) -> Result<(Small, Entries), String> {
/// Read an `S` value of the version before, of the account `did`: its
/// state, unmarked, with no spaces state.
pub(super) fn read(bytes: &[u8], did: &str) -> Result<Small, String> {
let mut m = state(bytes)?;
let mut number = |k: &str| as_uint(take(&mut m, k)?, k);
let header = (number("generation")?, number("lastSeq")?, number("letGo")?);
let mut rows = BTreeMap::new();
let mut counted: BTreeMap<String, u64> = BTreeMap::new();
let mut kept = Vec::new();
for x in as_list(take(&mut m, "spaces")?, "spaces")? {
kept.push(space(x, &mut rows, &mut counted)?);
}
let counted = counted
.into_iter()
.map(|(cid, n)| V::Arr(vec![text(&cid), int(n)]));
m.push(("version".into(), V::Int(VERSION)));
m.push(("spaces".into(), V::Arr(kept)));
m.push(("spaceRefs".into(), V::Arr(counted.collect())));
Ok((Small::of(V::Map(m), header, did)?, rows))
}
/// A space repo as the version before kept it: its entries of this
/// version's sections go into `rows`, each of its records' blob references
/// is counted in `counted`, and what this version's `S` keeps of it is
/// answered. Its records must make its `data`, each have one rev, no later
/// than the repo's, and its operations be in order.
fn space(v: V, rows: &mut Entries, counted: &mut BTreeMap<String, u64>) -> Result<V, String> {
let [space, rev, data, records, written, ops] = fields(
v,
["space", "rev", "data", "records", "written", "ops"],
"a space",
)?;
let space = as_text(space, "a space's space")?;
let what = |x: &str| format!("space {space}'s {x}");
let rev = as_text(rev, &what("rev"))?;
let mut revs: BTreeMap<String, String> = BTreeMap::new();
for x in as_list(written, &what("written"))? {
let (path, r) = as_pair(x, &what("written"))?;
let (path, r) = (
as_text(path, &what("written's path"))?,
as_text(r, &what("written's rev"))?,
);
if revs.last_key_value().is_some_and(|(l, _)| *l >= path) || !valid_tid(&r) || r > rev {
return Err(what("written out of order, or of a bad rev"));
let mut spaces = None;
for k in ["spaces", "authority", "notify", "spaceRefs"] {
if let Ok(v) = take(&mut m, k)
&& k == "spaces"
{
spaces = Some(v);
}
revs.insert(path, r);
}
let mut hash = LtHash::new();
let mut held = 0u64;
let mut last: Option<String> = None;
for x in as_list(records, &what("records"))? {
let (path, bytes) = as_pair(x, &what("record"))?;
let (path, bytes) = (
as_text(path, &what("record's path"))?,
as_bytes(bytes, &what("record's bytes"))?,
);
if last.as_ref().is_some_and(|l| *l >= path) {
return Err(what("records out of order"));
}
let value = decode(&bytes).map_err(|e| what(&format!("record {path}: {e}")))?;
let Some(written) = revs.remove(&path) else {
return Err(what("records, not one rev for each"));
};
let meta = Meta {
cid: cid_of(0x71, &bytes),
rev: written,
refs: cids_in(&value),
};
hash.add(&element(&path, &cid_string(&meta.cid)));
for cid in &meta.refs {
*counted.entry(cid.clone()).or_default() += 1;
rows.insert(
key(spaces::REFS, &ref_key(&space, cid, &path)),
meta.rev.clone().into_bytes(),
);
let empty = || V::Arr(Vec::new());
m.push(("version".into(), V::Int(VERSION)));
m.push(("spaces".into(), empty()));
m.push(("authority".into(), empty()));
m.push((
"notify".into(),
map([
("queue", empty()),
("registrations", empty()),
("notices", empty()),
]),
));
m.push(("spaceRefs".into(), empty()));
let mut small = Small::of(V::Map(m), header, did)?;
let mut unmarked = Unmarked::default();
for (space, rev, records) in spaces.map(space_repos).into_iter().flatten() {
if let Some(rev) = rev.filter(|r| valid_tid(r)) {
small.tids.after(&rev);
}
let k = space_key(&space, path.as_bytes());
rows.insert(key(spaces::RECORDS, &k), meta.encode());
rows.insert(key(spaces::VALUES, &k), bytes);
held += 1;
last = Some(path);
}
if !revs.is_empty() {
return Err(what("written, not one record for each"));
}
let data = as_bytes(data, &what("data"))?;
if hash.digest()[..] != data[..] {
return Err(what("records, which do not make its data"));
}
let mut logged = 0u64;
let mut before: Option<(String, usize)> = None;
for x in as_list(ops, &what("ops"))? {
let [op_rev, collection, rkey, cid, prev] = fields(
x,
["rev", "collection", "rkey", "cid", "prev"],
&what("operation"),
)?;
let op_rev = as_text(op_rev, &what("operation's rev"))?;
if !valid_tid(&op_rev) || op_rev > rev || before.as_ref().is_some_and(|(r, _)| *r > op_rev)
{
return Err(what("operations out of order, or of a bad rev"));
for (path, bytes) in records {
let cids = decode(&bytes).map(|v| cids_in(&v)).unwrap_or_default();
unmarked.kept(&space, &path, cids, &mut small.blobs);
}
let index = match &before {
Some((r, i)) if *r == op_rev => i + 1,
_ => 0,
};
let link = |v: V| or_none(v, |l| as_link(l, &what("operation's cid")));
let o = Op {
path: format!(
"{}/{}",
as_text(collection, &what("operation's collection"))?,
as_text(rkey, &what("operation's rkey"))?
),
cid: link(cid)?,
prev: link(prev)?,
rev: op_rev.clone(),
index,
};
rows.insert(
key(spaces::OPS, &op_key(&space, &o.rev, o.index)),
op_value(&o),
);
before = Some((op_rev, index));
logged += 1;
}
Ok(map([
("space", text(&space)),
("rev", text(&rev)),
("data", V::Bytes(data)),
("hash", V::Bytes(hash.state().to_vec())),
("records", int(held)),
("ops", int(logged)),
]))
small.unmarked = Some(unmarked);
Ok(small)
}
/// A space repo its `spaces` holds whole, as far as it reads: its space's
/// URI, its rev, and each record's path and DRISL bytes.
type Whole = (String, Option<String>, Vec<(String, Vec<u8>)>);
/// Each space repo its `spaces` holds whole (`Whole`).
fn space_repos(spaces: V) -> Vec<Whole> {
let V::Arr(repos) = spaces else {
return Vec::new();
};
let get = |m: &[(String, V)], k: &str| m.iter().find(|(n, _)| n == k).map(|(_, v)| v.clone());
repos
.into_iter()
.filter_map(|r| {
let V::Map(m) = r else { return None };
let Some(V::Str(space)) = get(&m, "space") else {
return None;
};
let rev = match get(&m, "rev") {
Some(V::Str(rev)) => Some(rev),
_ => None,
};
let records = match get(&m, "records") {
Some(V::Arr(records)) => records
.into_iter()
.filter_map(|x| match x {
V::Arr(p) => match <[V; 2]>::try_from(p) {
Ok([V::Str(path), V::Bytes(bytes)]) => Some((path, bytes)),
_ => None,
},
_ => None,
})
.collect(),
_ => Vec::new(),
};
Some((space, rev, records))
})
.collect()
}
#[cfg(test)]
pub(crate) mod tests {
use super::super::{header_value, read_header};
use super::super::spaces::{self, Meta, space_key};
use super::super::{as_text, fields, header_value, int, key, read_header, text};
use super::*;
use pds_repo::data::encode;
use pds_store::table::{BLOCK, BlockCache, Table, TableWriter, Version};
crates/pds-server/src/checkpoint/spaces.rs+14−25
@@ -458,20 +458,14 @@ impl SpaceMem {
// ---- Reading: memtable, then table ---------------------------------------------------
/// The table's entries of these sections, or what stands for them: none,
/// a table, read from its file opened if given, or the entries themselves,
/// by key, as a table of the version before is made into (`before`).
/// The table's entries of these sections, if it has one, read from its
/// file opened if given.
#[derive(Clone, Copy)]
pub(crate) enum Old<'a> {
None,
Table(&'a Table, Option<&'a File>),
Rows(&'a Entries),
}
/// Entries of a table held in memory, by key: those a table of the version
/// before is made into (`before`).
pub(crate) type Entries = BTreeMap<Vec<u8>, Vec<u8>>;
/// What the memtable keeps of a section, in the order a scan reads it.
type MemRows<'a, M> = Peekable<Box<dyn Iterator<Item = (&'a Vec<u8>, &'a M)> + 'a>>;
@@ -490,7 +484,6 @@ impl<'a> Old<'a> {
tests::READS.with(|n| n.set(n.get() + 1));
t.get_in(k, *file, cache).map_err(|e| e.to_string())
}
Old::Rows(rows) => Ok(rows.get(k).cloned()),
}
}
@@ -510,21 +503,6 @@ impl<'a> Old<'a> {
r.map_err(|e| e.to_string())
}))
}
Old::Rows(rows) => {
let own = |(k, v): (&Vec<u8>, &Vec<u8>)| Ok((k.clone(), v.clone()));
if reverse {
Box::new(
rows.range::<[u8], _>((Bound::Unbounded, Bound::Excluded(from)))
.rev()
.map(own),
)
} else {
Box::new(
rows.range::<[u8], _>((Bound::Included(from), Bound::Unbounded))
.map(own),
)
}
}
}
}
}
@@ -1065,7 +1043,17 @@ pub(crate) mod tests {
meta.encode(),
);
}
let dir = crate::testing::scratch("spaces-voids");
std::fs::create_dir_all(&dir).unwrap();
let file = dir.join("table");
let mut w =
pds_store::table::TableWriter::new(File::create(&file).unwrap(), table.len() as u64);
for (k, v) in &table {
w.add(k, v).unwrap();
}
w.finish().unwrap();
let cache = BlockCache::new(1 << 20);
let table = Table::open(&file, &cache).unwrap();
let pos = Pos {
generation: 3,
offset: 0,
@@ -1088,7 +1076,7 @@ pub(crate) mod tests {
let view = |mem: &'_ SpaceMem| -> Vec<String> {
let v = View {
mem,
old: Old::Rows(&table),
old: Old::Table(&table, None),
cache: &cache,
};
let all = rows(v, a, false);
@@ -1137,6 +1125,7 @@ pub(crate) mod tests {
assert!(mem.voids.is_empty() && mem.records.is_empty());
assert_eq!(mem.cost(), 0);
assert_eq!(view(&mem), ["a.b/1", "keep.it/1", "keep.it/2", "z.z/1"]);
let _ = std::fs::remove_dir_all(&dir);
}
/// What an entry's value holds is read back as it was written.
crates/pds-server/src/checkpoint/unmarked.rsnew+195−0
@@ -0,0 +1,195 @@
//! Spaces state this server does not carry: spaces are an alpha, and none
//! of an earlier version's is kept (`spec/STORE.md`, "Upgrades").
//!
//! An account's spaces state is this version's where it is **marked**: in
//! a table that does not say it is unmarked, and in its log from the mark
//! on, `{"t":"spaces","v":1}` (`MARK`), which begins every account's log
//! (`log::new_repo`) and which a store found unmarked appends as it loads
//! (`log::open_repo`). A log with no table, after a table that says it is
//! unmarked, or after a table of the format `before` reads, is
//! unmarked until its mark. There each entry of spaces state (`of_spaces`),
//! whatever it holds, is let go as it is replayed: nothing is made of it,
//! and nothing of it is refused. Only what the space repos' records
//! reference of blobs is counted (`Unmarked`), as those references held
//! blobs then, so that every other entry replays as it was written; at the
//! mark they go, as a drop's do (`Small::mark`): a blob only they held is
//! no longer held. A fold of an unmarked log writes a table that says so,
//! with what it counted, and the log after it goes on from there.
use crate::blobs::{Blobs, cids_in};
use crate::space_repo;
use pds_repo::data::from_json;
use pds_repo::{Tids, valid_tid};
use serde_json::{Value as Json, json};
use std::collections::BTreeMap;
/// The kind of the mark's entry.
pub(crate) const MARK: &str = "spaces";
/// The mark's version, the only one this server knows.
pub(crate) const MARK_VERSION: u64 = 1;
/// The mark's entry.
pub(crate) fn mark() -> Json {
json!({ "t": MARK, "v": MARK_VERSION })
}
/// Whether an entry of the kind `t` is of spaces state: of the space repos,
/// the spaces an account is the authority of or its notifications, or of a
/// kind this server does not know named as theirs are, `space…` or
/// `notify…`. Not the mark.
pub(crate) fn of_spaces(t: &str) -> bool {
t != MARK
&& (t.starts_with("space")
|| t.starts_with("notify")
|| crate::space_authority::ENTRIES.contains(&t)
|| crate::space_notify::ENTRIES.contains(&t))
}
/// What an unmarked account's space repos hold of blob references: by
/// space, then path, the CIDs each record references, for those that
/// reference any. Its blobs count them (`Blobs::space_counted`).
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(crate) struct Unmarked {
records: BTreeMap<String, BTreeMap<String, Vec<String>>>,
}
impl Unmarked {
/// The record at `path` of the space repo `space` now references `cids`,
/// none if it is deleted: what that changes is counted in `delta`.
fn set(
&mut self,
space: &str,
path: &str,
cids: Vec<String>,
delta: &mut BTreeMap<String, i64>,
) {
let repo = self.records.entry(space.to_string()).or_default();
let before = if cids.is_empty() {
repo.remove(path)
} else {
repo.insert(path.to_string(), cids.clone())
}
.unwrap_or_default();
if repo.is_empty() {
self.records.remove(space);
}
for cid in before.iter().filter(|c| !cids.contains(c)) {
*delta.entry(cid.clone()).or_default() -= 1;
}
for cid in cids.iter().filter(|c| !before.contains(c)) {
*delta.entry(cid.clone()).or_default() += 1;
}
}
/// Every record of the space repo `space` gone: counted in `delta`.
fn empty(&mut self, space: &str, delta: &mut BTreeMap<String, i64>) {
for cid in self
.records
.remove(space)
.into_iter()
.flat_map(|r| r.into_values().flatten())
{
*delta.entry(cid).or_default() -= 1;
}
}
/// A record of a space repo a table `before` reads keeps whole, at
/// `path` of `space`, referencing `cids`: counted in `blobs`.
pub(super) fn kept(&mut self, space: &str, path: &str, cids: Vec<String>, blobs: &mut Blobs) {
let mut delta = BTreeMap::new();
self.set(space, path, cids, &mut delta);
blobs.space_counted(delta);
}
/// Replay an entry of spaces state before the mark (`of_spaces`): of a
/// space repo's commit, import or drop, what it changes of its records'
/// blob references, counted in `blobs`, and its rev, after which
/// `tids` makes revs; of any other kind, nothing. Whatever of it does
/// not read as this version writes it is passed over.
pub(crate) fn replay(&mut self, e: &Json, blobs: &mut Blobs, tids: &mut Tids) {
let Some(space) = e["space"].as_str() else {
return;
};
let t = e["t"].as_str().unwrap_or_default();
if ![space_repo::ENTRY, space_repo::IMPORT, space_repo::DROP].contains(&t) {
return;
}
if let Some(rev) = e["rev"].as_str().filter(|r| valid_tid(r)) {
tids.after(rev);
}
let list = |k: &str| e[k].as_array().map(Vec::as_slice).unwrap_or_default();
// Each `[path, value]` of a list, and the CIDs its value references.
let records = |k: &str| {
list(k)
.iter()
.filter_map(|p| match p.as_array().map(Vec::as_slice) {
Some([Json::String(path), value]) => Some((
path.clone(),
from_json(value).map(|v| cids_in(&v)).unwrap_or_default(),
)),
_ => None,
})
};
let mut delta = BTreeMap::new();
match t {
space_repo::ENTRY => {
// A `clearRecords` that names the prefixes of the records it keeps.
if let Some(kept) = e["kept"].as_array() {
let kept: Vec<&str> = kept.iter().filter_map(Json::as_str).collect();
let gone: Vec<String> = self
.records
.get(space)
.into_iter()
.flat_map(BTreeMap::keys)
.filter(|p| !kept.iter().any(|k| p.starts_with(k)))
.cloned()
.collect();
for path in gone {
self.set(space, &path, Vec::new(), &mut delta);
}
}
for path in list("dels").iter().filter_map(Json::as_str) {
self.set(space, path, Vec::new(), &mut delta);
}
for (path, cids) in records("puts") {
self.set(space, &path, cids, &mut delta);
}
}
space_repo::IMPORT => {
self.empty(space, &mut delta);
for (path, cids) in records("records") {
self.set(space, &path, cids, &mut delta);
}
}
_ => self.empty(space, &mut delta),
}
blobs.space_counted(delta);
}
/// As a table's state keeps it: each record that references blobs, its
/// space, path and CIDs, in order.
pub(super) fn saved(&self) -> impl Iterator<Item = (&str, &str, &[String])> {
self.records.iter().flat_map(|(space, repo)| {
repo.iter()
.map(move |(path, cids)| (space.as_str(), path.as_str(), cids.as_slice()))
})
}
/// Restore a record `saved` gave, in its order.
pub(super) fn restore(
&mut self,
space: String,
path: String,
cids: Vec<String>,
) -> Result<(), String> {
let last = self
.records
.last_key_value()
.and_then(|(s, repo)| Some((s.as_str(), repo.last_key_value()?.0.as_str())));
if cids.is_empty() || last.is_some_and(|l| l >= (space.as_str(), path.as_str())) {
return Err("unmarked records out of order, or with no blob refs".into());
}
self.records.entry(space).or_default().insert(path, cids);
Ok(())
}
}
crates/pds-server/src/space_credentials/tests.rs+213−127
@@ -248,19 +248,28 @@ pub(crate) async fn delegation_token(
Ok(got["token"].as_str().unwrap().to_string())
}
/// A credential from `authorizeSpaceSync` with this body.
pub(crate) async fn credential(s: &Shared, body: Json) -> Result<String, String> {
let got = http(
authorized(s, body)
.await
.map(|got| got["credential"].as_str().unwrap().to_string())
}
/// `authorizeSpaceSync`'s answer to this body.
pub(crate) async fn authorized(s: &Shared, body: Json) -> Result<Json, String> {
http(
s,
Method::POST,
"com.atproto.space.getSpaceCredential",
AUTHORIZE,
&[],
&HeaderMap::new(),
&body.to_string(),
)
.await?;
Ok(got["credential"].as_str().unwrap().to_string())
.await
}
const AUTHORIZE: &str = "com.atproto.space.authorizeSpaceSync";
async fn verify(
s: &Service,
headers: &HeaderMap,
@@ -268,7 +277,7 @@ async fn verify(
) -> Result<SpaceCredential, String> {
let method = Method::GET;
let call = Call {
nsid: "com.atproto.space.listRepos",
nsid: "com.atproto.space.listWriters",
method: &method,
params: &[],
body: b"",
@@ -530,12 +539,18 @@ async fn credentials_are_issued_and_verified() {
let s = &w.s;
let c = client(1);
let token = delegation_token(s, &w.alice.1, &w.space).await.unwrap();
let cred = credential(
let got = authorized(
s,
json!({ "space": w.space, "credentialKid": c.kid, "delegationToken": token }),
json!({ "space": w.space, "credentialKey": c.kid, "delegationToken": token }),
)
.await
.unwrap();
// No `spaceRev` while the space's writer set is empty.
assert_eq!(
got.as_object().unwrap().keys().collect::<Vec<_>>(),
["credential"]
);
let cred = got["credential"].as_str().unwrap().to_string();
let (header, payload, sig) = parts(&cred);
assert_eq!(
header,
@@ -594,6 +609,27 @@ async fn credentials_are_issued_and_verified() {
let _ = std::fs::remove_dir_all(&w.dir);
}
/// `body` with `extra`'s members added.
fn merged(mut body: Json, extra: &Json) -> Json {
for (k, v) in extra.as_object().unwrap() {
body[k] = v.clone();
}
body
}
/// Create a space of the account `token` is a session of, under `policy`.
async fn make_space(s: &Shared, token: &str, skey: &str, policy: Json) -> String {
let body = json!({ "spaceType": "com.example.forum", "skey": skey, "policy": policy });
call(s, "com.atproto.space.createSpace", Some(token), body)
.await
.unwrap()["space"]
.as_str()
.unwrap()
.to_string()
}
/// Each refusal of `authorizeSpaceSync`, in the order the spec gives them,
/// each before the next (`spec/SPACES-CREDENTIALS.md`, "authorizeSpaceSync").
#[tokio::test]
async fn credential_requests_are_refused_in_order() {
let w = world("cred-refused").await;
@@ -601,14 +637,22 @@ async fn credential_requests_are_refused_in_order() {
let kid = client(1).kid;
let ask = |body: Json| credential(s, body);
let elsewhere = "at://did:plc:nowhere/space/com.example.forum/main";
// 1. The lexicon, the HTTP method and the body.
let notify = json!({ "endpoint": "https://syncer.example", "token": "t" });
// 1. The lexicon, `notify` too, the HTTP method and the body.
let with_notify = |n: Json| json!({ "space": w.space, "credentialKey": kid, "notify": n });
for body in [
json!({ "credentialKid": kid }),
json!({ "credentialKey": kid }),
json!({ "space": w.space }),
json!({ "space": "at://did:plc:x/space/forum/k", "credentialKid": kid }),
json!({ "space": w.space, "credentialKid": 1 }),
json!({ "space": w.space, "credentialKid": kid, "delegationToken": 1 }),
json!({ "space": w.space, "credentialKid": kid, "clientAttestation": false }),
json!({ "space": "at://did:plc:x/space/forum/k", "credentialKey": kid }),
json!({ "space": w.space, "credentialKey": 1 }),
json!({ "space": w.space, "credentialKey": kid, "delegationToken": 1 }),
json!({ "space": w.space, "credentialKey": kid, "clientAttestation": false }),
with_notify(json!("https://syncer.example")),
with_notify(json!({ "endpoint": "https://syncer.example" })),
with_notify(json!({ "token": "t" })),
with_notify(json!({ "endpoint": "not a uri", "token": "t" })),
with_notify(json!({ "endpoint": "https://syncer.example", "token": "x".repeat(513) })),
with_notify(json!({ "endpoint": "https://syncer.example", "token": 7 })),
] {
assert_eq!(
ask(body.clone()).await,
@@ -616,29 +660,29 @@ async fn credential_requests_are_refused_in_order() {
"{body}"
);
}
// A token of 512 bytes, or none, and other members, pass it.
for n in [
json!({ "endpoint": "https://syncer.example", "token": "x".repeat(512) }),
json!({ "endpoint": "https://syncer.example", "token": "" }),
json!({ "endpoint": "https://syncer.example", "token": "t", "other": 1 }),
] {
assert_eq!(ask(with_notify(n)).await, Err("400 SpaceNotFound".into()));
}
assert_eq!(
http(
s,
Method::POST,
"com.atproto.space.getSpaceCredential",
&[],
&HeaderMap::new(),
"x"
)
.await,
http(s, Method::POST, AUTHORIZE, &[], &HeaderMap::new(), "x").await,
Err("400 InvalidRequest".into())
);
let get = http(
s,
Method::GET,
"com.atproto.space.getSpaceCredential",
&[("space", &w.space), ("credentialKid", &kid)],
AUTHORIZE,
&[("space", &w.space), ("credentialKey", &kid)],
&HeaderMap::new(),
"",
)
.await;
assert_eq!(get, Err("400 InvalidRequest".into()));
// 2. A credentialKid that is no P-256 key, before the token.
// 2. A credentialKey that is no P-256 key, before the authority.
let signing = crate::plc::did_key(
crate::read(&s.account(&w.alice.0).unwrap().store)
.repo
@@ -650,93 +694,146 @@ async fn credential_requests_are_refused_in_order() {
"nonsense",
"",
"did:plc:abc",
] {
for space in [w.space.as_str(), elsewhere] {
assert_eq!(
ask(json!({ "space": space, "credentialKey": bad, "delegationToken": "x" })).await,
Err("400 InvalidRequest".into()),
"{bad}"
);
}
}
// 3. The authority an account here, before the token, the attestation
// and `notify`, none of which is read.
let elsewhere_token = delegation_token(s, &w.bob.1, elsewhere).await.unwrap();
let base = |space: &str| json!({ "space": space, "credentialKey": kid });
for extra in [
json!({}),
json!({ "delegationToken": "x.y.z" }),
json!({ "clientAttestation": "x" }),
json!({ "delegationToken": elsewhere_token }),
json!({ "notify": notify }),
] {
assert_eq!(
ask(json!({ "space": w.space, "credentialKid": bad, "delegationToken": "x" })).await,
Err("400 InvalidRequest".into()),
"{bad}"
ask(merged(base(elsewhere), &extra)).await,
Err("400 SpaceNotFound".into()),
"{extra}"
);
}
// 4. A space deleted, before the token: one presented for it is not
// spent, and is taken once the space is created again.
let personal = json!({ "$type": "com.atproto.personalspace.policy" });
let gone = make_space(s, &w.alice.1, "gone", personal.clone()).await;
call(
s,
"com.atproto.space.deleteSpace",
Some(&w.alice.1),
json!({ "space": gone }),
)
.await
.unwrap();
let for_gone = delegation_token(s, &w.alice.1, &gone).await.unwrap();
for extra in [
json!({}),
json!({ "delegationToken": "x.y.z" }),
json!({ "clientAttestation": "x" }),
json!({ "delegationToken": for_gone }),
json!({ "notify": notify }),
] {
assert_eq!(
ask(merged(base(&gone), &extra)).await,
Err("400 SpaceDeleted".into()),
"{extra}"
);
}
// 3. The delegation token, before whether the space is here.
make_space(s, &w.alice.1, "gone", personal).await;
ask(merged(base(&gone), &json!({ "delegationToken": for_gone })))
.await
.unwrap();
// 5. The token, before the attestation; 6. the attestation, before
// whether the space was created. An empty one, of either, is as none.
let never = format!("at://{}/space/com.example.forum/never", w.alice.0);
assert_eq!(
ask(json!({ "space": elsewhere, "credentialKid": kid, "delegationToken": "x.y.z" })).await,
ask(merged(
base(&never),
&json!({ "delegationToken": "x.y.z", "clientAttestation": "x" })
))
.await,
Err("400 InvalidDelegationToken".into())
);
// 4. The space's authority, before the attestation.
assert_eq!(
ask(json!({ "space": elsewhere, "credentialKid": kid })).await,
Err("400 SpaceNotFound".into())
);
for bad in ["x", "a.b.c", "https://app.example/client.json"] {
for space in [&w.space, &never] {
assert_eq!(
ask(merged(base(space), &json!({ "clientAttestation": bad }))).await,
Err("400 InvalidClientAttestation".into()),
"{bad}"
);
}
}
assert_eq!(
ask(json!({ "space": elsewhere, "credentialKid": kid, "clientAttestation": "x" })).await,
ask(merged(
base(&w.space),
&json!({ "clientAttestation": "", "delegationToken": "" })
))
.await,
Err("400 SpaceNotFound".into())
);
let elsewhere_token = delegation_token(s, &w.bob.1, elsewhere).await.unwrap();
// 7. A space never created; a token verified is spent all the same.
let for_never = delegation_token(s, &w.alice.1, &never).await.unwrap();
assert_eq!(
ask(
json!({ "space": elsewhere, "credentialKid": kid, "delegationToken": elsewhere_token })
)
ask(merged(
base(&never),
&json!({ "delegationToken": for_never })
))
.await,
Err("400 SpaceNotFound".into())
);
// 5. The attestation; an empty one, and an empty token, are as none.
for bad in ["x", "a.b.c", "https://app.example/client.json"] {
assert_eq!(
ask(json!({ "space": w.space, "credentialKid": kid, "clientAttestation": bad })).await,
Err("400 InvalidClientAttestation".into()),
"{bad}"
);
}
assert_eq!(ask(json!({ "space": w.space, "credentialKid": kid, "clientAttestation": "", "delegationToken": "" })).await, Err("400 SpaceNotFound".into()));
// 7. The user perimeter: no token, or a user the space refuses.
assert_eq!(
ask(json!({ "space": w.space, "credentialKid": kid })).await,
Err("400 SpaceNotFound".into())
ask(merged(
base(&never),
&json!({ "delegationToken": for_never })
))
.await,
Err("400 InvalidDelegationToken".into())
);
assert_eq!(ask(base(&never)).await, Err("400 SpaceNotFound".into()));
// 8. The user perimeter: no token, or a user the space refuses.
assert_eq!(ask(base(&w.space)).await, Err("400 SpaceNotFound".into()));
let bobs = delegation_token(s, &w.bob.1, &w.space).await.unwrap();
assert_eq!(
ask(json!({ "space": w.space, "credentialKid": kid, "delegationToken": bobs })).await,
ask(merged(base(&w.space), &json!({ "delegationToken": bobs }))).await,
Err("400 SpaceNotFound".into())
);
// A token refused there was spent all the same.
assert_eq!(
ask(json!({ "space": w.space, "credentialKid": kid, "delegationToken": bobs })).await,
ask(merged(base(&w.space), &json!({ "delegationToken": bobs }))).await,
Err("400 InvalidDelegationToken".into())
);
// Replays, and a token for another space, which is spent too.
let alices = delegation_token(s, &w.alice.1, &w.space).await.unwrap();
ask(json!({ "space": w.space, "credentialKid": kid, "delegationToken": alices }))
.await
.unwrap();
let with_alices = |space: &str, t: &str| merged(base(space), &json!({ "delegationToken": t }));
ask(with_alices(&w.space, &alices)).await.unwrap();
assert_eq!(
ask(json!({ "space": w.space, "credentialKid": kid, "delegationToken": alices })).await,
ask(with_alices(&w.space, &alices)).await,
Err("400 InvalidDelegationToken".into())
);
let other = format!("at://{}/space/com.example.forum/other", w.alice.0);
let alices = delegation_token(s, &w.alice.1, &w.space).await.unwrap();
assert_eq!(
ask(json!({ "space": other, "credentialKid": kid, "delegationToken": alices })).await,
ask(with_alices(&other, &alices)).await,
Err("400 InvalidDelegationToken".into())
);
assert_eq!(
ask(json!({ "space": w.space, "credentialKid": kid, "delegationToken": alices })).await,
ask(with_alices(&w.space, &alices)).await,
Err("400 InvalidDelegationToken".into())
);
// No Authorization is read.
let headers = headers_of(&[("authorization", "Bearer nonsense")]);
let alices = delegation_token(s, &w.alice.1, &w.space).await.unwrap();
let body =
json!({ "space": w.space, "credentialKid": kid, "delegationToken": alices }).to_string();
http(
s,
Method::POST,
"com.atproto.space.getSpaceCredential",
&[],
&headers,
&body,
)
.await
.unwrap();
let body = with_alices(&w.space, &alices).to_string();
http(s, Method::POST, AUTHORIZE, &[], &headers, &body)
.await
.unwrap();
let _ = std::fs::remove_dir_all(&w.dir);
}
@@ -752,7 +849,7 @@ async fn delegation_tokens_each_with_one_thing_wrong() {
let trade = |token: String| {
credential(
s,
json!({ "space": w.space, "credentialKid": kid, "delegationToken": token }),
json!({ "space": w.space, "credentialKey": kid, "delegationToken": token }),
)
};
let mut count = 0;
@@ -1299,7 +1396,7 @@ async fn revocations_take_service_auth() {
&with(
&payload,
"lxm",
json!("com.atproto.space.getSpaceCredential"),
json!("com.atproto.space.authorizeSpaceSync"),
),
)),
"401 BadJwtLexiconMethod",
@@ -1465,7 +1562,7 @@ async fn revocations_and_spent_tokens_survive_a_restart() {
let w = world("cred-restart").await;
let c = client(1);
let token = delegation_token(&w.s, &w.alice.1, &w.space).await.unwrap();
let ask = json!({ "space": w.space, "credentialKid": c.kid, "delegationToken": token });
let ask = json!({ "space": w.space, "credentialKey": c.kid, "delegationToken": token });
let cred = credential(&w.s, ask.clone()).await.unwrap();
let jti = parts(&cred).1["jti"].as_str().unwrap().to_string();
let auth = format!("Bearer {}", service_auth_token(&w.s, &w.alice.0, &w.bob.0));
@@ -1629,9 +1726,10 @@ async fn delegation_tokens_are_refused_to_an_account_not_active() {
let _ = std::fs::remove_dir_all(&w.dir);
}
/// `getSpaceCredential` of a space whose authority is deactivated or taken
/// down: refused at step 4, whatever the user and the attestation, after
/// the key and the token are checked; a token taken at step 3 is spent.
/// `authorizeSpaceSync` of a space whose authority is deactivated or taken
/// down: refused at step 3, after the input and the key, whatever the
/// space, the token, the attestation and `notify`, none of which is read:
/// a token presented then is not spent.
#[tokio::test]
async fn credentials_are_refused_for_an_authority_not_active() {
let w = world("cred-authority-state").await;
@@ -1640,63 +1738,55 @@ async fn credentials_are_refused_for_an_authority_not_active() {
let kid = client(1).kid;
let ask = |body: Json| credential(s, body);
// Tokens made while every account is active: the authority's and another user's.
let mut tokens = Vec::new();
for _ in 0..4 {
tokens.push(delegation_token(s, t, &w.space).await.unwrap());
tokens.push(delegation_token(s, &w.bob.1, &w.space).await.unwrap());
}
let refused = |state: &'static str, alices: String, bobs: String| {
let (kid, space) = (kid.clone(), w.space.clone());
let alices = delegation_token(s, t, &w.space).await.unwrap();
let bobs = delegation_token(s, &w.bob.1, &w.space).await.unwrap();
let base = |space: &str| json!({ "space": space, "credentialKey": kid });
let refused = |state: &'static str| {
let (alices, bobs, space) = (alices.clone(), bobs.clone(), w.space.clone());
async move {
let space = space.as_str();
// 2. A credentialKid that is no key, and 3. a token that is no JWT, first.
assert_eq!(ask(json!({ "space": space, "credentialKid": "nonsense", "delegationToken": alices })).await, Err("400 InvalidRequest".into()));
// 2. A credentialKey that is no key, first.
assert_eq!(
ask(json!({ "space": space, "credentialKid": kid, "delegationToken": "x.y.z" }))
.await,
Err("400 InvalidDelegationToken".into())
);
// 4. The authority's state, before the attestation and the perimeter.
assert_eq!(
ask(json!({ "space": space, "credentialKid": kid })).await,
Err(state.into())
);
assert_eq!(
ask(json!({ "space": space, "credentialKid": kid, "clientAttestation": "x" }))
.await,
Err(state.into())
ask(json!({ "space": space, "credentialKey": "nonsense", "delegationToken": alices })).await,
Err("400 InvalidRequest".into())
);
// 3. The authority's state, before all else.
let other = format!("at://{alice}/space/com.example.forum/none");
assert_eq!(
ask(json!({ "space": other, "credentialKid": kid })).await,
Err(state.into())
);
for token in [&alices, &bobs] {
assert_eq!(ask(json!({ "space": space, "credentialKid": kid, "delegationToken": token, "clientAttestation": "x" })).await, Err(state.into()));
// Verified at step 3, it was spent all the same.
assert_eq!(ask(base(&other)).await, Err(state.into()));
for extra in [
json!({}),
json!({ "delegationToken": "x.y.z" }),
json!({ "clientAttestation": "x" }),
json!({ "delegationToken": alices }),
json!({ "delegationToken": bobs, "clientAttestation": "x" }),
json!({ "notify": { "endpoint": "https://syncer.example", "token": "t" } }),
] {
assert_eq!(
ask(json!({ "space": space, "credentialKid": kid, "delegationToken": token }))
.await,
Err("400 InvalidDelegationToken".into())
ask(merged(base(space), &extra)).await,
Err(state.into()),
"{extra}"
);
}
}
};
let mut next = || (tokens.pop().unwrap(), tokens.pop().unwrap());
deactivate(s, t, true).await;
let (b, a) = next();
refused("400 RepoDeactivated", a, b).await;
refused("400 RepoDeactivated").await;
take_down(s, alice, true).await;
let (b, a) = next();
refused("400 RepoTakendown", a, b).await;
refused("400 RepoTakendown").await;
take_down(s, alice, false).await;
let (b, a) = next();
refused("400 RepoDeactivated", a, b).await;
refused("400 RepoDeactivated").await;
deactivate(s, t, false).await;
let (_, a) = next();
ask(json!({ "space": w.space, "credentialKid": kid, "delegationToken": a }))
.await
.unwrap();
// Neither token was spent.
ask(merged(
base(&w.space),
&json!({ "delegationToken": alices }),
))
.await
.unwrap();
assert_eq!(
ask(merged(base(&w.space), &json!({ "delegationToken": bobs }))).await,
Err("400 SpaceNotFound".into())
);
let _ = std::fs::remove_dir_all(&w.dir);
}
@@ -1710,12 +1800,8 @@ fn the_methods_are_tools() {
"space_get_delegation_token",
false,
),
(
"com.atproto.space.getSpaceCredential",
"space_get_space_credential",
false,
),
(NOTIFY, "space_notify_credential_revoked", true),
(AUTHORIZE, "space_authorize_space_sync", false),
(NOTIFY, "space_notify_credentials_revoked", true),
] {
let m = pds_lexicon::method(nsid).unwrap();
assert_eq!(m.tool().as_deref(), Some(tool));
crates/pds-server/src/space_notify/tests.rs+932−499
1431 lines changed: not loaded until asked for.
crates/pds-server/src/cache.rs+1−1
@@ -42,7 +42,7 @@
//!
//! **A start** loads no account but those marked in the service log
//! (`Eager`): an account whose handle change is in flight, that has write
//! notifications or deletion notices to send, or, with blobs in a bucket,
//! notifications or notices to syncers to send, or, with blobs in a bucket,
//! an upload on its way or objects to delete (`blobstore`). Each is marked,
//! durably, before the entry that needs it reaches its own log, and
//! unmarked, with the handle it has then, once nothing needs it. So the
crates/pds-server/src/checkpoint.rs+261−78
@@ -36,8 +36,9 @@
//! bucket the objects it may keep of blobs not held (`blobstore`), the
//! records taken down, each space repo's rev and `data`, the lanes of
//! its LtHash and the counts of its records and operations, the spaces
//! it is the authority of (as `exportSpaceMeta`'s archives), and its
//! write notifications;
//! it is the authority of (as `exportSpaceMeta`'s archives), its write
//! notifications, and while the log after it is unmarked, the blob
//! references of the space records it let go (`unmarked`);
//! - `V`, keyed as `R`: that record's bytes.
//!
//! **The log after it** is replayed as the store loads, one frame at a time,
@@ -67,9 +68,14 @@
//! A log of a server before the tree was changed in place has commits that
//! name only their records: the first load folds it, read whole in memory
//! (`pds_repo::full`), into a table, once. A table of the version before
//! keeps its space repos whole in its `S` and has no `H` (`before`): the
//! first load folds it, with the log after it, into a table of this
//! version, once.
//! has no `H` (`before`): the first load folds it, with the log after it,
//! into a table of this version, once.
//!
//! **Spaces state is this version's alone** (`unmarked`): what a log holds
//! of spaces before its mark, or a table of the format `before` reads, is
//! let go, but for what its space records reference of blobs until the
//! mark; a table written meanwhile says so, in its `S`, with what it
//! counted.
use crate::blobs::{Blobs, Held};
use crate::cache::unrecoverable;
@@ -93,9 +99,13 @@ use std::io::{self, Write};
use std::os::unix::fs::FileExt;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, PoisonError, Weak};
use unmarked::Unmarked;
mod before;
pub(crate) mod spaces;
mod unmarked;
pub(crate) use unmarked::mark;
#[cfg(test)]
pub(crate) use before::tests::downgrade;
@@ -200,9 +210,13 @@ pub(crate) struct Small {
/// window when its log was compacted, `0` if none was: the firehose
/// tells a subscriber that missed it so, though nothing else holds it.
pub let_go: u64,
/// Until its spaces state is this version's, at its mark: the blob
/// references of the space records it let go (`unmarked`).
pub unmarked: Option<Unmarked>,
}
impl Small {
/// The state before any of a log with no table: unmarked.
pub(crate) fn new() -> Small {
Small {
generation: 0,
@@ -218,6 +232,22 @@ impl Small {
pending: None,
last_seq: 0,
let_go: 0,
unmarked: Some(Unmarked::default()),
}
}
/// Its spaces state this version's from here on: the blob references
/// of the space records it let go go too, as a drop's do, and a blob
/// only they held is no longer held (`unmarked`).
pub(crate) fn mark(&mut self) {
if self.unmarked.take().is_some() {
let delta = self
.blobs
.space_ref_list()
.into_iter()
.map(|(cid, n)| (cid.to_string(), -i64::from(n)))
.collect();
self.blobs.space_counted(delta);
}
}
@@ -225,7 +255,8 @@ impl Small {
!self.head.is_empty()
}
/// Replay one entry of the log but a commit's or an event's.
/// Replay one entry of the log but a commit's or an event's, or a space
/// repo's while its spaces state is this version's.
fn replay(&mut self, e: &Json, holds: impl Fn(&str) -> bool) -> Result<(), String> {
let text = |k: &str| {
e[k].as_str()
@@ -268,6 +299,17 @@ impl Small {
}
};
}
Some(unmarked::MARK) => {
if e["v"] != unmarked::MARK_VERSION {
return Err(format!("a mark of spaces of no known version: {e}"));
}
self.mark();
}
Some(t) if unmarked::of_spaces(t) && self.unmarked.is_some() => {
if let Some(u) = &mut self.unmarked {
u.replay(e, &mut self.blobs, &mut self.tids);
}
}
Some(t) if crate::space_authority::ENTRIES.contains(&t) => self.authority.replay(e)?,
Some(t) if space_notify::ENTRIES.contains(&t) => self.notify.replay(e)?,
t => return Err(format!("a log entry of no known type: {t:?}")),
@@ -275,8 +317,8 @@ impl Small {
Ok(())
}
/// The `S` value of a table: write notifications and registrations
/// settled at `now_ms` left out.
/// The `S` value of a table: write notifications past their horizon at
/// `now_ms` left out.
fn encode(&self, did: &str, now_ms: u64) -> Vec<u8> {
let spaces = self.spaces.saved().map(|r| {
map([
@@ -303,26 +345,35 @@ impl Small {
("until", int(p.at.until)),
])
});
let registered = n.registered.iter().flat_map(|(space, services)| {
services
.iter()
.filter(|(_, r)| r.expires > now_ms)
.map(move |(service, r)| {
map([
("space", text(space)),
("service", text(service)),
("expires", int(r.expires)),
("kid", or_null(r.kid.as_deref(), text)),
])
})
// Every registration, lapsed ones too: one ends only when dropped.
let registrations = n.registered.iter().flat_map(|(space, pairs)| {
pairs.iter().map(move |((endpoint, token), r)| {
map([
("space", text(space)),
("endpoint", text(endpoint)),
("token", text(token)),
("expires", int(r.expires)),
("noticed", V::Bool(r.noticed)),
])
})
});
let owed = n.owed.iter().map(|((space, service), at)| {
let notices = n.notices.iter().map(|((space, (endpoint, token)), x)| {
let (update, space_rev, lapse) = match &x.owed {
space_notify::Owed::Deleted => ("deleted", V::Null, V::Null),
space_notify::Owed::Expired { space_rev, lapse } => {
("expired", text(space_rev), int(*lapse))
}
};
map([
("space", text(space)),
("service", text(service)),
("n", int(at.n.into())),
("due", int(at.due)),
("until", int(at.until)),
("endpoint", text(endpoint)),
("token", text(token)),
("update", text(update)),
("spaceRev", space_rev),
("lapse", lapse),
("n", int(x.at.n.into())),
("due", int(x.at.due)),
("until", int(x.at.until)),
])
});
let mut state = map([
@@ -419,17 +470,30 @@ impl Small {
"notify",
map([
("queue", V::Arr(queue.collect())),
("registered", V::Arr(registered.collect())),
("owed", V::Arr(owed.collect())),
("registrations", V::Arr(registrations.collect())),
("notices", V::Arr(notices.collect())),
]),
),
]);
// With blobs in a bucket, the objects it may keep of blobs not held.
if let (V::Map(m), Some(objects)) = (&mut state, self.blobs.objects_list()) {
m.push((
"objects".into(),
V::Arr(objects.into_iter().map(text).collect()),
));
if let V::Map(m) = &mut state {
// With blobs in a bucket, the objects it may keep of blobs not held.
if let Some(objects) = self.blobs.objects_list() {
m.push((
"objects".into(),
V::Arr(objects.into_iter().map(text).collect()),
));
}
// Unmarked: the blob references of the space records let go.
if let Some(u) = &self.unmarked {
let records = u.saved().map(|(space, path, cids)| {
V::Arr(vec![
text(space),
text(path),
V::Arr(cids.iter().map(|c| text(c)).collect()),
])
});
m.push(("unmarked".into(), V::Arr(records.collect())));
}
}
encode(&state)
}
@@ -451,19 +515,38 @@ impl Small {
(generation, last_seq, let_go): (u64, u64, u64),
did: &str,
) -> Result<Small, String> {
let objects = match &mut state {
let mut optional = |k: &str| match &mut state {
V::Map(m) => m
.iter()
.position(|(k, _)| k == "objects")
.position(|(n, _)| n == k)
.map(|i| m.swap_remove(i).1),
_ => None,
};
let (objects, unmarked) = (optional("objects"), optional("unmarked"));
let objects = or_none(objects.unwrap_or(V::Null), |v| {
as_list(v, "objects")?
.into_iter()
.map(|c| as_text(c, "an object"))
.collect::<Result<Vec<_>, _>>()
})?;
let unmarked = or_none(unmarked.unwrap_or(V::Null), |v| {
let mut u = Unmarked::default();
for x in as_list(v, "unmarked")? {
let [space, path, cids] = as_list(x, "an unmarked record")?
.try_into()
.map_err(|_| "an unmarked record not three")?;
let cids = as_list(cids, "an unmarked record's blob refs")?
.into_iter()
.map(|c| as_text(c, "a blob ref"))
.collect::<Result<Vec<_>, _>>()?;
u.restore(
as_text(space, "an unmarked record's space")?,
as_text(path, "an unmarked record's path")?,
cids,
)?;
}
Ok(u)
})?;
let [
version,
state_did,
@@ -620,6 +703,7 @@ impl Small {
s.authority.restore(did, &space, archive.as_deref())?;
}
s.notify = read_notify(notify)?;
s.unmarked = unmarked;
Ok(s)
}
}
@@ -679,14 +763,6 @@ fn as_uint(v: V, what: &str) -> Result<u64, String> {
}
}
fn as_link(v: V, what: &str) -> Result<Vec<u8>, String> {
if let V::Link(l) = v {
Ok(l)
} else {
Err(format!("{what} is not a link"))
}
}
fn as_bytes(v: V, what: &str) -> Result<Vec<u8>, String> {
if let V::Bytes(b) = v {
Ok(b)
@@ -730,8 +806,11 @@ fn ascending<K: PartialOrd>(keys: impl IntoIterator<Item = K>) -> bool {
true
}
/// The notifications' state (`space_notify::Kept`), as `Small::encode`
/// writes it.
fn read_notify(v: V) -> Result<Kept, String> {
let [queue, registered, owed] = fields(v, ["queue", "registered", "owed"], "notify")?;
let [queue, registrations, notices] =
fields(v, ["queue", "registrations", "notices"], "notify")?;
let schedule = |n: V, due: V, until: V, what: &str| -> Result<Schedule, String> {
let n =
u32::try_from(as_uint(n, what)?).map_err(|_| format!("{what}: an attempt too many"))?;
@@ -764,39 +843,73 @@ fn read_notify(v: V) -> Result<Kept, String> {
};
kept.queue.insert(space, p);
}
let mut last: Option<(String, String)> = None;
for x in as_list(registered, "notify's registered")? {
let [space, service, expires, kid] =
fields(x, ["space", "service", "expires", "kid"], "a registration")?;
let mut last: Option<(String, String, String)> = None;
for x in as_list(registrations, "notify's registrations")? {
let [space, endpoint, token, expires, noticed] = fields(
x,
["space", "endpoint", "token", "expires", "noticed"],
"a registration",
)?;
let key = (
as_text(space, "a registration's space")?,
as_text(service, "a registration's service")?,
as_text(endpoint, "a registration's endpoint")?,
as_text(token, "a registration's token")?,
);
if last.as_ref().is_some_and(|l| *l >= key) {
return Err("notify's registered out of order".into());
return Err("notify's registrations out of order".into());
}
last = Some(key.clone());
let V::Bool(noticed) = noticed else {
return Err("a registration's noticed is not a boolean".into());
};
let r = space_notify::Registration {
expires: as_uint(expires, "a registration's expiry")?,
kid: or_none(kid, |k| as_text(k, "a registration's kid"))?,
noticed,
};
kept.register(key.0, key.1, r);
kept.register(key.0, (key.1, key.2), r);
}
for x in as_list(owed, "notify's owed")? {
let [space, service, n, due, until] = fields(
for x in as_list(notices, "notify's notices")? {
let [
space,
endpoint,
token,
update,
space_rev,
lapse,
n,
due,
until,
] = fields(
x,
["space", "service", "n", "due", "until"],
"a notice owed",
[
"space", "endpoint", "token", "update", "spaceRev", "lapse", "n", "due", "until",
],
"a notice",
)?;
let key = (
as_text(space, "a notice's space")?,
as_text(service, "a notice's service")?,
(
as_text(endpoint, "a notice's endpoint")?,
as_text(token, "a notice's token")?,
),
);
if kept.owed.last_key_value().is_some_and(|(l, _)| *l >= key) {
return Err("notify's owed out of order".into());
if kept
.notices
.last_key_value()
.is_some_and(|(l, _)| *l >= key)
{
return Err("notify's notices out of order".into());
}
kept.owed
.insert(key, schedule(n, due, until, "a notice owed")?);
let owed = match as_text(update, "a notice's update")?.as_str() {
"deleted" => space_notify::Owed::Deleted,
"expired" => space_notify::Owed::Expired {
space_rev: as_text(space_rev, "a notice's spaceRev")?,
lapse: as_uint(lapse, "a notice's lapse")?,
},
u => return Err(format!("a notice of no known kind {u}")),
};
let at = schedule(n, due, until, "a notice")?;
kept.notices.insert(key, space_notify::Notice { owed, at });
}
Ok(kept)
}
@@ -1117,7 +1230,9 @@ impl Memtable {
},
);
}
Some(space_repo::ENTRY | space_repo::IMPORT | space_repo::DROP) => {
Some(space_repo::ENTRY | space_repo::IMPORT | space_repo::DROP)
if small.unmarked.is_none() =>
{
small.spaces.replay(
e,
pos,
@@ -1233,7 +1348,11 @@ fn skim<'a>(
let (Some(space), Some(rev)) = (field("space"), field("rev")) else {
continue;
};
let (space, rev): (String, String) = (parse(space)?, parse(rev)?);
// One not of this version's, before its log's mark
// (`unmarked`), is passed over where it does not read.
let (Ok(space), Ok(rev)) = (parse::<String>(space), parse::<String>(rev)) else {
continue;
};
if let Some(ops) = field("ops")
&& !f(Raw::Space(
SPACE_OPS,
@@ -1250,7 +1369,10 @@ fn skim<'a>(
"records"
};
let records = field(records).unwrap_or("[]");
for (path, value) in parse::<Vec<(String, &RawValue)>>(records)? {
let Ok(records) = parse::<Vec<(String, &RawValue)>>(records) else {
continue;
};
for (path, value) in records {
let name = spaces::record_name(&space, &rev, &path);
if !f(Raw::Space(SPACE_RECORD, name, RECORD, value.get()))? {
return Ok(());
@@ -2238,9 +2360,6 @@ impl Fold for AccountFold {
Some(p) => Some(Table::open(p, &cache).map_err(|e| e.to_string())?),
None => None,
};
// A table of the version before keeps its space repos whole in its
// state: they are made the entries of their sections, held here.
let mut before: Option<spaces::Entries> = None;
let mut small = match &table {
Some(t) => {
let state = t
@@ -2249,19 +2368,14 @@ impl Fold for AccountFold {
.ok_or("a checkpoint with no state")?;
match t.get(b"H", &cache).map_err(|e| e.to_string())? {
Some(h) => Small::decode(&state, &h, &self.did)?,
None => {
let (small, rows) = before::read(&state, &self.did)?;
before = Some(rows);
small
}
None => before::read(&state, &self.did)?,
}
}
None => Small::new(),
};
let spaces_old = match (&before, &table) {
(Some(rows), _) => Old::Rows(rows),
(None, Some(t)) => Old::Table(t, None),
(None, None) => Old::None,
let spaces_old = match &table {
Some(t) => Old::Table(t, None),
None => Old::None,
};
let layout = Layout::new(
logs.first()
@@ -2318,7 +2432,6 @@ impl Fold for AccountFold {
let mut w = TableWriter::new(
io::BufWriter::new(out),
table.as_ref().map_or(0, |t| t.len())
+ before.as_ref().map_or(0, |rows| rows.len() as u64)
+ (mem.blocks.len() + mem.paths.len() + mem.events.len() * 2) as u64
+ spaces::entries(&mem.spaces)
+ 2,
@@ -2619,7 +2732,9 @@ fn legacy_fold(
small.tids.after(&c.rev);
small.head = c.head_bytes.clone();
}
Some(space_repo::ENTRY | space_repo::IMPORT | space_repo::DROP) => {
Some(space_repo::ENTRY | space_repo::IMPORT | space_repo::DROP)
if small.unmarked.is_none() =>
{
let pos = Pos {
generation: first + i as u64,
offset,
@@ -3166,4 +3281,72 @@ mod tests {
}
let _ = std::fs::remove_dir_all(&dir);
}
/// The notifications' part of a table: written and read back whole,
/// lapsed registrations and kept notices too.
#[test]
fn notify_state_round_trips() {
use super::{Small, read_notify};
use crate::space_notify::{Kept, Notice, Owed, Registration, Schedule};
use pds_repo::data::V;
let m = "at://did:plc:alicealicealicealicealic/space/com.example.forum/m".to_string();
let q = "at://did:plc:elsewhereelsewhereelsewhe/space/com.example.forum/q";
let at = Schedule {
n: 1,
due: 10,
until: 20,
};
let mut k = Kept::default();
k.queue.insert(
q.to_string(),
crate::space_notify::Pending {
rev: "3jzfcijpj2z2a".into(),
data: vec![1; 32],
at,
},
);
let pair = |e: &str, t: &str| (e.to_string(), t.to_string());
k.register(
m.clone(),
pair("https://a.example", "a"),
Registration {
expires: 5,
noticed: true,
},
);
k.register(
m.clone(),
pair("https://b.example/", ""),
Registration {
expires: 9,
noticed: false,
},
);
k.notices.insert(
(m.clone(), pair("https://a.example", "a")),
Notice {
owed: Owed::Expired {
space_rev: "3jzfcijpj2z2b".into(),
lapse: 5,
},
at,
},
);
k.notices.insert(
(m.clone(), pair("https://c.example", "c")),
Notice {
owed: Owed::Deleted,
at,
},
);
let mut small = Small::new();
small.notify = k.clone();
let state =
pds_repo::data::decode(&small.encode("did:plc:alicealicealicealicealic", 0)).unwrap();
let V::Map(fields) = state else {
panic!("a state that is no map")
};
let notify = fields.into_iter().find(|(k, _)| k == "notify").unwrap().1;
assert_eq!(read_notify(notify).unwrap(), k);
}
}
crates/pds-server/src/federation.rs+1−1
@@ -227,7 +227,7 @@ mod tests {
Ok(Resp::Nothing) => panic!("{nsid} answered nothing"),
Ok(Resp::Blob(_)) => panic!("{nsid} answered a blob"),
Ok(Resp::Upstream(_)) => panic!("{nsid} was forwarded"),
Ok(Resp::Octets(_) | Resp::Archive(..)) => panic!("{nsid} answered an archive"),
Ok(Resp::Star(_) | Resp::Archive(..)) => panic!("{nsid} answered an archive"),
Err(e) => Err(e.name.to_string()),
}
}
crates/pds-server/src/lib.rs+13−12
@@ -19,7 +19,7 @@
//! revocations), `space_authority` (the spaces each account is the
//! authority of, with who their policies authorize in `space_authz`) and
//! `space_notify` (write notifications, the writer set, syncers'
//! registrations and deletion notices); the firehose is `events`, the MCP
//! registrations, and the updates and notices sent them); the firehose is `events`, the MCP
//! endpoint `mcp`, the PLC directory `plc`, requests to URLs others name,
//! with SSRF protection, `outbound`, OAuth's authorization server `oauth`,
//! with the account's own routes for its OAuth sessions and devices in
@@ -338,7 +338,7 @@ pub(crate) struct Store {
/// The spaces it is the authority of (`spec/SPACES-POLICIES.md`), kept in the same log.
pub authority: space_authority::Authority,
/// Its write notifications waiting to be sent again, and the
/// registrations and deletion notices of its spaces (`space_notify`).
/// registrations of its spaces and the notices owed them (`space_notify`).
pub notify: space_notify::Kept,
/// Its checkpoint's table, and where in its log what the log changed is
/// (`checkpoint`): its tree's blocks and paths, and its events.
@@ -400,7 +400,7 @@ pub(crate) struct Service {
handle_resolver: identity::resolve::Resolver,
/// Each account's preferences.
prefs: preferences::Preferences,
/// Write notifications and deletion notices being sent, and when next.
/// Write notifications and notices to syncers being sent, and when next.
space_notify: space_notify::Notify,
}
@@ -573,6 +573,10 @@ impl Shown {
}
}
/// The media type of a STAR archive (`spec/SPACES.md`), as a space repo's
/// and a space meta archive are sent and taken.
const STAR_TYPE: &str = "application/vnd.dasl.star";
enum Resp {
Json(Json),
Car(Vec<u8>),
@@ -585,8 +589,8 @@ enum Resp {
Upstream(proxy::Upstream),
/// A JSON answer with headers of its own.
Headed(Json, Vec<(&'static str, String)>),
/// Bytes as `application/octet-stream`, as a space meta archive.
Octets(Vec<u8>),
/// A STAR archive, as a space meta archive (`STAR_TYPE`).
Star(Vec<u8>),
/// A space repo's archive, read as it is sent (`space_repo::Archive`),
/// with headers of its own, as its commit's MAC.
Archive(space_repo::Archive, Vec<(&'static str, String)>),
@@ -1001,12 +1005,9 @@ fn respond(answer: Result<Resp, XrpcError>, charged: Option<&limits::Charged>) -
.into_response(),
headers,
),
Ok(Resp::Octets(b)) => (
StatusCode::OK,
[(header::CONTENT_TYPE, "application/octet-stream")],
b,
)
.into_response(),
Ok(Resp::Star(b)) => {
(StatusCode::OK, [(header::CONTENT_TYPE, STAR_TYPE)], b).into_response()
}
Ok(Resp::Archive(a, headers)) => with_headers(a.response(), headers),
Err(e) => (
StatusCode::from_u16(e.status).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR),
@@ -1590,7 +1591,7 @@ mod testing {
match answer(s, &call).await {
Ok(Resp::Json(j) | Resp::Headed(j, _)) => Ok(j),
Ok(Resp::Car(_) | Resp::CarStream(_)) => Err("a CAR file".into()),
Ok(Resp::Octets(_) | Resp::Archive(..)) => Err("bytes".into()),
Ok(Resp::Star(_) | Resp::Archive(..)) => Err("bytes".into()),
Ok(Resp::Nothing) => Ok(Json::Null),
Ok(Resp::Blob(_)) => Err("a blob".into()),
// A service's answer: its JSON, or for an error, its name.
crates/pds-server/src/limits.rs+7−9
crates/pds-server/src/log.rs+263−39
crates/pds-server/src/mcp.rs+2−2
crates/pds-server/src/outbound.rs+2−2
crates/pds-server/src/scopes.rs+6−8
crates/pds-server/src/space_authority.rs+803−315
A large diff, not shown.
crates/pds-server/src/space_authz.rs+418−284
702 lines changed: not loaded until asked for.
crates/pds-server/src/space_credentials.rs+105−37
crates/pds-server/src/space_notify.rs+795−428
1223 lines changed: not loaded until asked for.
crates/pds-server/src/space_repo.rs+588−577
1165 lines changed: not loaded until asked for.
crates/pds-server/src/store.rs+10−3
crates/pds-space/src/commit.rs+2−97
crates/pds-space/src/key.rs+68−20
crates/pds-space/src/lib.rs+9−5
crates/pds-space/src/mac.rsnew+328−0
crates/pds-space/src/sf.rs+68−7
crates/pds-space/src/signature.rs+10−12
crates/pds-space/src/star.rs+9−7
crates/pds-space/tests/vectors.rs+134−51
docs/guide/operating.md+3−1
harness/checks/email.mjs+2−1
harness/checks/firehose.mjs+7−1
harness/checks/limits.mjs+7−7
harness/checks/oauth-scopes.mjs+7−5
harness/checks/scale.mjs+1−1
harness/checks/store.mjs+10−3
harness/checks/upgrade.mjs+13−12
harness/spaces/lib/spec.mjs+131−53
harness/spaces/compare.mjs+5−2
harness/spaces/credentials.mjs+98−71
harness/spaces/export.mjs+100−62
harness/spaces/package-lock.json+1578−2077
A large diff, not shown.
harness/spaces/package.json+49−47
harness/spaces/policies.mjs+310−206
516 lines changed: not loaded until asked for.
harness/spaces/repo.mjs+149−89
harness/spaces/ssrf.mjs+92−38
harness/spaces/sync.mjs+457−291
748 lines changed: not loaded until asked for.
harness/spaces/vectors.mjs+158−95
spec/interop/spaces/http-signature.json+94−42
spec/interop/spaces/kem.json+24−6
spec/interop/spaces/mac.json+308−90
spec/interop/spaces/README.md+8−6
spec/interop/spaces/repo-star.json+154−38
spec/lexicons/com/atproto/managedspace/policy.json+3−3
spec/lexicons/com/atproto/memberspace/defs.jsonnew+22−0
spec/lexicons/com/atproto/memberspace/listMembers.json+11−23
spec/lexicons/com/atproto/memberspace/member.json+3−5
spec/lexicons/com/atproto/memberspace/policy.json+7−7
spec/lexicons/com/atproto/memberspace/putMember.jsondeleted+0−49
spec/lexicons/com/atproto/memberspace/putMembers.jsonnew+43−0
spec/lexicons/com/atproto/memberspace/removeMember.jsondeleted+0−41
spec/lexicons/com/atproto/memberspace/removeMembers.jsonnew+43−0
spec/lexicons/com/atproto/personalspace/policy.json+1−1
spec/lexicons/com/atproto/space/applyWrites.json+6−11
spec/lexicons/com/atproto/space/authorizeSpaceSync.jsonnew+109−0
spec/lexicons/com/atproto/space/clearRecords.json+3−5
spec/lexicons/com/atproto/space/createRecord.json+7−14
spec/lexicons/com/atproto/space/createSpace.json+9−13
spec/lexicons/com/atproto/space/defs.json+54−8
spec/lexicons/com/atproto/space/deleteRecord.json+5−9
spec/lexicons/com/atproto/space/deleteSpace.json+3−4
spec/lexicons/com/atproto/space/exportSpaceMeta.json+4−5
spec/lexicons/com/atproto/space/getBlob.json+4−7
spec/lexicons/com/atproto/space/getDelegationToken.json+3−5
spec/lexicons/com/atproto/space/getLatestCommit.json+6−9
spec/lexicons/com/atproto/space/getRecord.json+7−11
spec/lexicons/com/atproto/space/getRepo.json+6−8
spec/lexicons/com/atproto/space/getSpace.json+7−9
spec/lexicons/com/atproto/space/getSpaceCredential.jsondeleted+0−84
spec/lexicons/com/atproto/space/importRepo.json+11−3
spec/lexicons/com/atproto/space/importSpaceMeta.json+8−5
spec/lexicons/com/atproto/space/listBlobs.json+3−10
spec/lexicons/com/atproto/space/listRecords.json+10−16
spec/lexicons/com/atproto/space/listRepoOps.json+20−24
spec/lexicons/com/atproto/space/listRepos.jsondeleted+0−91
spec/lexicons/com/atproto/space/listSpaces.json+30−14
spec/lexicons/com/atproto/space/listWriters.jsonnew+66−0
spec/lexicons/com/atproto/space/notifyCredentialRevoked.json → spec/lexicons/com/atproto/space/notifyCredentialsRevoked.jsonrenamed+4−5
spec/lexicons/com/atproto/space/notifyRepoUpdate.jsonnew+43−0
spec/lexicons/com/atproto/space/notifyWrite.jsondeleted+0−57
spec/lexicons/com/atproto/space/policy.json+2−2
spec/lexicons/com/atproto/space/putRecord.json+7−14
spec/lexicons/com/atproto/space/registerNotify.jsondeleted+0−49
spec/lexicons/com/atproto/space/removeWriter.json+6−8
spec/lexicons/com/atproto/space/unregisterNotify.jsondeleted+0−29
spec/lexicons/com/atproto/space/updateSpace.json+5−7
spec/spaces/lexicons/com/atproto/managedspace/checkAccess.jsonnew+44−0
spec/spaces/lexicons/com/atproto/managedspace/checkUserAccess.jsondeleted+0−48
spec/spaces/lexicons/com/atproto/space/confirmRegistration.jsonnew+44−0
spec/spaces/lexicons/com/atproto/space/notifySpaceDeleted.jsondeleted+0−24
spec/spaces/lexicons/com/atproto/space/notifySpaceUpdate.jsonnew+53−0
spec/spaces/proposal.md+197−130
spec/spaces/README.md+13−12
spec/COMMANDS.md+5−5
spec/LIFECYCLE.md+3−3
spec/LIMITS.md+15−13
spec/PDS.md+7−8
spec/SPACES-CREDENTIALS.md+138−83
spec/SPACES-EXPORT.md+88−58
spec/SPACES-POLICIES.md+296−223
519 lines changed: not loaded until asked for.
spec/SPACES-REPO.md+126−66
spec/SPACES-SYNC.md+388−263
651 lines changed: not loaded until asked for.
spec/SPACES.md+170−94
spec/STORE.md+10−7