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

Split the spec, harness and server by area

Merged chadtmiller.com asked to merge into main from chadtmiller.com/monolith:split
.knotless/review.md+1−1
@@ -1,6 +1,6 @@
This repository builds a PDS from specifications: agents build `crates/` from `spec/`, and `harness/` checks it against the reference PDS. Check that:
- Every change in behaviour is in `spec/` (`SLICE.md`, `COMMANDS.md` or a lexicon) as well as in the code, and the README says what is built, not how it came to be built.
- Every change in behaviour is in `spec/` (`PDS.md` or the page of its area beside it, `COMMANDS.md` or a lexicon) as well as in the code, and the README says what is built, not how it came to be built.
- A harness change makes a check stricter or fixes it, and never loosens one so that a server passes. A new check says what it compares, and with what.
- Server code takes nothing from the reference PDS's or an SDK's source, and adds no atproto or MCP crates.
- Each conformance check excused in `harness/conformance.yaml` gives a reason that the suite's source supports.
crates/pds-server/src/events.rs+1−1
@@ -1,4 +1,4 @@
//! The firehose: `com.atproto.sync.subscribeRepos` events and the WebSocket that serves them.
//! The firehose: `com.atproto.sync.subscribeRepos` events and the WebSocket that serves them, as `spec/SYNC.md` says.
use crate::Shared;
use axum::body::Bytes;
crates/pds-server/src/lib.rs+59−624
683 lines changed: not loaded until asked for.
crates/pds-server/src/log.rsnew+280−0
@@ -0,0 +1,280 @@
//! What the server keeps: its state, as entries in the log in its data
//! directory, replayed when it starts again, as `spec/DURABILITY.md` says.
use crate::{Server, events};
use axum::body::Bytes;
use pds_repo::*;
use pds_store::Wal;
use serde_json::{Value as Json, json};
use std::path::Path as FsPath;
use std::sync::Arc;
impl Server {
/// Start from the log in `dir`: replay it, or begin a new one.
pub(crate) fn open(dir: &FsPath, did: String, handle: String, password: String, key: k256::ecdsa::SigningKey) -> Result<Server, String> {
let (wal, frames) = Wal::open(dir).map_err(|e| format!("the log: {e}"))?;
let mut s = Server {
did: did.clone(),
handle,
password,
repo: Repo::new(did, key),
owner_tokens: vec![],
wal: Arc::new(wal),
pending: vec![],
events: vec![],
published: tokio::sync::watch::channel(0).0,
};
let mut have_commit = false;
for e in frames.iter().flatten() {
have_commit |= s.replay(e)?;
}
if have_commit {
s.repo.finish_load()?;
} else {
// A new directory: its first commit is the empty repository.
let c = s.repo.init();
s.pending.push(commit_entry(&c));
for frame in events::initial_events(&s.did, &s.handle, &c) {
let seq = s.next_seq();
s.add_event(seq, frame);
}
let seq = s.wal.append(&s.pending);
s.wal.wait(seq);
s.pending.clear();
}
let n = s.events.len();
s.published.send_replace(n);
Ok(s)
}
pub(crate) fn next_seq(&self) -> u64 {
self.events.len() as u64 + 1
}
/// Add an event to the stream and to the entries the request in hand logs.
pub(crate) fn add_event(&mut self, seq: u64, frame: Vec<u8>) {
self.pending.push(json!({ "t": "event", "seq": seq, "frame": hex::encode(&frame) }));
self.events.push(Bytes::from(frame));
}
/// Apply one logged entry; true if it was a commit.
fn replay(&mut self, e: &Json) -> Result<bool, String> {
let text = |k: &str| e[k].as_str().map(str::to_string).ok_or_else(|| format!("a log entry with no {k}: {e}"));
let hex = |x: &Json| x.as_str().and_then(|h| hex::decode(h).ok()).ok_or_else(|| format!("a log entry with {x} for hex"));
let list = |k: &str| e[k].as_array().ok_or_else(|| format!("a commit with no {k}"));
match e["t"].as_str() {
Some("session") => self.owner_tokens.push(text("token")?),
Some("event") => {
if e["seq"].as_u64() != Some(self.next_seq()) {
return Err(format!("event {} where event {} was due", e["seq"], self.next_seq()));
}
self.events.push(Bytes::from(hex(&e["frame"])?));
}
Some("commit") => {
let path = |p: &Json| p.as_str().map(str::to_string).ok_or_else(|| format!("a commit with {p} for a path"));
let c = Change {
rev: text("rev")?,
head_bytes: hex(&e["head"])?,
puts: list("puts")?.iter().map(|p| Ok((path(&p[0])?, p[1].clone()))).collect::<Result<_, String>>()?,
dels: list("dels")?.iter().map(path).collect::<Result<_, _>>()?,
added: match e.get("added") {
Some(a) => a.as_array().ok_or("a commit whose added is not a list")?.iter().map(hex).collect::<Result<_, _>>()?,
None => vec![],
},
..Default::default()
};
self.repo.load(&c)?;
return Ok(true);
}
t => return Err(format!("a log entry of no known type: {t:?}")),
}
Ok(false)
}
}
pub(crate) fn commit_entry(c: &Change) -> Json {
json!({
"t": "commit", "rev": c.rev, "head": hex::encode(&c.head_bytes),
"puts": c.puts.iter().map(|(k, v)| json!([k, v])).collect::<Vec<_>>(), "dels": c.dels,
"added": c.added.iter().map(hex::encode).collect::<Vec<_>>(),
})
}
#[cfg(test)]
mod tests {
use crate::Server;
use crate::testing::*;
use pds_store::{self as store, Wal};
use serde_json::{Value as Json, json};
use std::path::Path as FsPath;
type State = (Vec<u8>, String, Vec<String>, Vec<Vec<u8>>);
/// Everything a restart must carry over, as one comparable value.
fn state(s: &Server) -> State {
(s.repo.car(), s.repo.rev.clone(), s.owner_tokens.clone(), s.events.iter().map(|e| e.to_vec()).collect())
}
/// Run a script of requests; after each, the log's length and the state.
fn script(dir: &FsPath) -> Vec<(usize, State)> {
let mut s = open(dir);
let log = || std::fs::metadata(dir.join(store::LOG_NAME)).unwrap().len() as usize;
let mut steps = Vec::new();
let mut snap = |s: &Server| {
steps.push((log(), state(s)));
};
snap(&s);
let owner = session(&mut s);
snap(&s);
let rec = |t: &str, n: i64| json!({ "$type": t, "n": n, "b": { "$bytes": "AQID" } });
let w = |c: &str, k: &str, n: i64| json!({ "repo": DID, "collection": "a.b.c", "rkey": k, "record": rec(c, n) });
call(&mut s, "com.atproto.repo.putRecord", Some(&owner), w("a.b.c", "one", 1)).unwrap();
snap(&s);
call(&mut s, "com.atproto.repo.putRecord", Some(&owner), w("a.b.c", "two", 2)).unwrap();
snap(&s);
call(&mut s, "com.atproto.repo.applyWrites", Some(&owner), json!({ "repo": DID, "writes": [
{ "$type": "com.atproto.repo.applyWrites#create", "collection": "a.b.c", "rkey": "three", "value": rec("a.b.c", 3) },
{ "$type": "com.atproto.repo.applyWrites#update", "collection": "a.b.c", "rkey": "one", "value": rec("a.b.c", 4) },
{ "$type": "com.atproto.repo.applyWrites#delete", "collection": "a.b.c", "rkey": "two" } ] })).unwrap();
snap(&s);
call(&mut s, "com.atproto.repo.deleteRecord", Some(&owner), json!({ "repo": DID, "collection": "a.b.c", "rkey": "three" })).unwrap();
snap(&s);
// A refused write changes nothing and logs nothing.
assert!(call(&mut s, "com.atproto.repo.applyWrites", Some("forged"), json!({ "repo": DID, "writes": [] })).is_err());
snap(&s);
let n = steps.len();
assert_eq!(steps[n - 1].0, steps[n - 2].0);
steps
}
#[test]
fn restart_resumes() {
let dir = scratch("resume");
let steps = script(&dir);
let s = open(&dir);
let last = steps.last().unwrap();
assert_eq!(state(&s), last.1);
// Four events open the stream; each of the four commits adds one.
assert_eq!(s.events.len(), 4 + 4);
assert_eq!(*s.published.borrow(), s.events.len());
drop(s);
let mut s = open(&dir);
let before = s.repo.rev.clone();
let t = s.owner_tokens[0].clone();
call(&mut s, "com.atproto.repo.putRecord", Some(&t), json!({ "repo": DID, "collection": "a.b.c", "rkey": "x", "record": { "n": 1 } })).unwrap();
assert!(s.repo.rev > before);
let _ = std::fs::remove_dir_all(&dir);
}
/// A log whose frames are intact but whose entries are not what the
/// server wrote is refused with a reason, not a panic.
#[test]
fn bad_entries_are_refused() {
let dir = scratch("bad-src");
script(&dir);
let (frames, _) = store::scan(&std::fs::read(dir.join(store::LOG_NAME)).unwrap());
let work = scratch("bad-work");
let reopen = |frames: &[Vec<Json>]| {
let _ = std::fs::remove_dir_all(&work);
std::fs::create_dir_all(&work).unwrap();
std::fs::write(work.join(store::LOG_NAME), frames.iter().flat_map(|f| store::frame(f)).collect::<Vec<u8>>()).unwrap();
try_open(&work).err()
};
assert_eq!(reopen(&frames), None);
let mut tampered = frames.clone();
// A record the latest commit did not sign.
let last = tampered.iter_mut().rev().find_map(|f| f.iter_mut().find(|e| e["t"] == "commit" && !e["puts"].as_array().unwrap().is_empty())).unwrap();
last["puts"][0][1]["n"] = json!(99);
assert!(reopen(&tampered).unwrap().contains("does not sign"));
for (at, bad) in [(1, json!({ "t": "nonsense" })), (1, json!({ "t": "session" })), (2, json!({ "t": "commit", "rev": "x" }))] {
let mut broken = frames.clone();
broken[at].push(bad.clone());
assert!(reopen(&broken).is_some(), "{bad}");
}
let _ = std::fs::remove_dir_all(&dir);
let _ = std::fs::remove_dir_all(&work);
}
/// Cut the log at every byte of each frame (and flip a byte in each): recovery
/// must give the state before that frame or after it, and keep working.
#[test]
fn torn_writes_recover_to_before_or_after() {
let dir = scratch("torn-src");
let steps = script(&dir);
let log = std::fs::read(dir.join(store::LOG_NAME)).unwrap();
let work = scratch("torn-work");
let key = |t: &(usize, State)| t.1.clone();
let mut cuts = 0;
for w in steps.windows(2).skip(1) {
let (from, to) = (w[0].0, w[1].0);
for cut in from..=to {
let _ = std::fs::remove_dir_all(&work);
std::fs::create_dir_all(&work).unwrap();
std::fs::write(work.join(store::LOG_NAME), &log[..cut]).unwrap();
let s = open(&work);
let got = state(&s);
let want = if cut == to { key(&w[1]) } else { key(&w[0]) };
assert_eq!(got, want, "cut at {cut} of frame {from}..{to}");
cuts += 1;
// After recovery the log must take new writes and replay them.
if cut % 7 == 0 || cut == to {
let mut s = s;
let tok = s.owner_tokens.first().cloned();
if let Some(t) = tok {
call(&mut s, "com.atproto.repo.putRecord", Some(&t), json!({ "repo": DID, "collection": "a.b.c", "rkey": "after", "record": { "n": 9 } })).unwrap();
let again = open(&work);
assert_eq!(state(&again), state(&s), "cut at {cut}");
}
}
}
// A damaged byte anywhere in the last frame drops that frame.
{
for at in (from..to).step_by(5) {
let mut bad = log[..to].to_vec();
bad[at] ^= 0x55;
let _ = std::fs::remove_dir_all(&work);
std::fs::create_dir_all(&work).unwrap();
std::fs::write(work.join(store::LOG_NAME), &bad).unwrap();
assert_eq!(state(&open(&work)), key(&w[0]), "flip at {at} of frame {from}..{to}");
}
}
}
assert!(cuts > 500);
let _ = std::fs::remove_dir_all(&dir);
let _ = std::fs::remove_dir_all(&work);
}
#[test]
fn torn_first_commit_starts_fresh() {
let dir = scratch("torn-first");
let steps = script(&dir);
let log = std::fs::read(dir.join(store::LOG_NAME)).unwrap();
for cut in 0..=steps[0].0 {
let work = scratch("torn-first-work");
std::fs::create_dir_all(&work).unwrap();
std::fs::write(work.join(store::LOG_NAME), &log[..cut]).unwrap();
let s = open(&work);
assert_eq!(s.repo.records.len(), 0);
assert!(!s.repo.rev.is_empty());
let again = open(&work);
assert_eq!(state(&again), state(&s));
let _ = std::fs::remove_dir_all(&work);
}
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn wal_group_commit_covers_all_waiters() {
let dir = scratch("wal");
let (wal, _) = Wal::open(&dir).unwrap();
let a = wal.append(&[json!({ "t": "session", "token": "a" })]);
let b = wal.append(&[json!({ "t": "session", "token": "b" })]);
assert!(!wal.is_durable(a));
wal.wait(b);
assert!(wal.is_durable(a) && wal.is_durable(b));
wal.wait(a);
let (frames, _) = store::scan(&std::fs::read(dir.join(store::LOG_NAME)).unwrap());
assert_eq!(frames.len(), 2);
let _ = std::fs::remove_dir_all(&dir);
}
}
crates/pds-server/src/repo.rsnew+266−0
@@ -0,0 +1,266 @@
//! The repository's records: the `com.atproto.repo` methods, as
//! `spec/REPO.md` says.
use crate::{Call, Handler, Resp, Server, XrpcError, commit_meta, err, internal, invalid, opt, required};
use pds_repo::data::*;
use pds_repo::*;
use serde_json::{Map, Value as Json, json};
pub(crate) fn handler(nsid: &str) -> Option<Handler> {
Some(match nsid {
"com.atproto.repo.getRecord" => Handler::Query(get_record),
"com.atproto.repo.listRecords" => Handler::Query(list_records),
"com.atproto.repo.describeRepo" => Handler::Query(describe_repo),
"com.atproto.repo.createRecord" => Handler::Procedure { owner: true, f: create_record },
"com.atproto.repo.putRecord" => Handler::Procedure { owner: true, f: put_record },
"com.atproto.repo.deleteRecord" => Handler::Procedure { owner: true, f: delete_record },
"com.atproto.repo.applyWrites" => Handler::Procedure { owner: true, f: apply_writes },
_ => return None,
})
}
fn check_repo(s: &Server, repo: &str) -> Result<(), XrpcError> {
if repo == s.handle || repo == s.did { Ok(()) } else { invalid("Could not find repo") }
}
fn record_json(s: &Server, collection: &str, rkey: &str, r: &Record) -> Json {
json!({ "uri": s.repo.uri(collection, rkey), "cid": cid_string(&r.cid), "value": to_json(&r.value) })
}
fn get_record(s: &Server, _: &Call, p: &Map<String, Json>) -> Result<Resp, XrpcError> {
check_repo(s, required(p, "repo")?)?;
let (collection, rkey) = (required(p, "collection")?, required(p, "rkey")?);
match s.repo.records.get(&format!("{collection}/{rkey}")) {
Some(r) if opt(p, "cid").is_none_or(|c| c == cid_string(&r.cid)) => Ok(Resp::Json(record_json(s, collection, rkey, r))),
_ => err(400, "RecordNotFound", format!("Could not locate record: {}", s.repo.uri(collection, rkey))),
}
}
/// A page of a collection: newest (greatest key) first unless `reverse`, read
/// from the range of the collection's keys after the cursor.
fn list_records(s: &Server, _: &Call, p: &Map<String, Json>) -> Result<Resp, XrpcError> {
use std::ops::Bound::{Excluded, Included};
check_repo(s, required(p, "repo")?)?;
let collection = required(p, "collection")?;
let limit = p.get("limit").and_then(Json::as_u64).unwrap_or(50) as usize;
let reverse = p.get("reverse").and_then(Json::as_bool) == Some(true);
// Every key of the collection, and only those, is at least `lo` and less
// than `hi`, as '0' follows '/'; so is the collection's key `lo` + a cursor.
let (lo, hi) = (format!("{collection}/"), format!("{collection}0"));
let range = match (opt(p, "cursor"), reverse) {
(None, _) => (Included(lo.clone()), Excluded(hi)),
(Some(c), false) => (Included(lo.clone()), Excluded(format!("{lo}{c}"))),
(Some(c), true) => (Excluded(format!("{lo}{c}")), Excluded(hi)),
};
let keyed = s.repo.records.range(range).map(|(k, r)| (&k[lo.len()..], r));
let page: Vec<(&str, &Record)> = if reverse { keyed.take(limit).collect() } else { keyed.rev().take(limit).collect() };
let records: Vec<Json> = page.iter().map(|(rk, r)| record_json(s, collection, rk, r)).collect();
let mut out = json!({ "records": records });
if let Some((rk, _)) = page.last() {
out["cursor"] = json!(rk);
}
Ok(Resp::Json(out))
}
fn describe_repo(s: &Server, _: &Call, p: &Map<String, Json>) -> Result<Resp, XrpcError> {
let repo = required(p, "repo")?;
if repo != s.handle && repo != s.did {
return err(400, "RepoNotFound", format!("Could not find repo: {repo}"));
}
let mut cols: Vec<&str> = s.repo.records.keys().filter_map(|k| k.split('/').next()).collect();
cols.dedup();
Ok(Resp::Json(json!({
"handle": s.handle, "did": s.did,
"didDoc": { "id": s.did, "alsoKnownAs": [format!("at://{}", s.handle)] },
"collections": cols, "handleIsCorrect": true
})))
}
// ---- Writes -----------------------------------------------------------
/// A record as input, in the data model and an object.
fn record_value(b: &Map<String, Json>, field: &str) -> Result<V, XrpcError> {
let Some(j) = b.get(field) else { return invalid(format!("Input/{field} is required")) };
match from_json(j) {
Ok(v @ V::Map(_)) => Ok(v),
Ok(_) => invalid("record must be an object"),
Err(e) => invalid(e),
}
}
/// A record whose `$type` is its collection, given it if it has none. The
/// reference checks this after the write's `repo`, not with its input.
fn typed(v: V, collection: &str) -> Result<V, XrpcError> {
let V::Map(mut m) = v else { return invalid("record must be an object") };
match m.iter().find(|(k, _)| k == "$type") {
Some((_, V::Str(t))) if t == collection => Ok(V::Map(m)),
Some((_, V::Str(_))) => invalid("$type does not match collection"),
None => {
m.push(("$type".into(), V::Str(collection.into())));
Ok(V::Map(m))
}
_ => invalid("$type must be a string"),
}
}
/// The `validationStatus` a write answers, as its `validate` asks: `unknown`
/// by default, none with `false`. `true` is refused, as the server knows no
/// lexicon for any record type.
fn validation_status(b: &Map<String, Json>) -> Result<Option<&'static str>, XrpcError> {
match b.get("validate") {
None => Ok(Some("unknown")),
Some(Json::Bool(false)) => Ok(None),
Some(_) => invalid("Lexicon not found"),
}
}
/// A write's answer, with its `validationStatus` if it has one.
fn with_status(mut answer: Json, status: Option<&str>) -> Json {
if let Some(v) = status {
answer["validationStatus"] = json!(v);
}
answer
}
/// A write's `repo`, checked once its input is: `403 AccountNotFound` unless it names the account.
fn check_account(s: &Server, repo: &str) -> Result<(), XrpcError> {
if repo == s.handle || repo == s.did { Ok(()) } else { err(403, "AccountNotFound", "Could not find account") }
}
/// The record one write created or updated.
fn written(results: Vec<OpResult>) -> Result<(String, String), XrpcError> {
match results.into_iter().next() {
Some(OpResult::Create { uri, cid } | OpResult::Update { uri, cid }) => Ok((uri, cid)),
_ => internal(),
}
}
fn create_record(s: &mut Server, b: &Map<String, Json>) -> Result<Resp, XrpcError> {
let (repo, collection, rkey) = (required(b, "repo")?, required(b, "collection")?, opt(b, "rkey"));
let status = validation_status(b)?;
let value = record_value(b, "record")?;
check_account(s, repo)?;
let value = typed(value, collection)?;
let op = Op::Create { collection: collection.into(), rkey: rkey.map(Into::into), value };
let (uri, cid) = written(s.repo.apply(vec![op], opt(b, "swapCommit"))?)?;
Ok(Resp::Json(with_status(json!({ "uri": uri, "cid": cid, "commit": commit_meta(s) }), status)))
}
fn put_record(s: &mut Server, b: &Map<String, Json>) -> Result<Resp, XrpcError> {
let (repo, collection, rkey) = (required(b, "repo")?, required(b, "collection")?, required(b, "rkey")?);
let status = validation_status(b)?;
let value = record_value(b, "record")?;
check_account(s, repo)?;
let value = typed(value, collection)?;
let existing = s.repo.records.get(&format!("{collection}/{rkey}")).map(|r| cid_string(&r.cid));
if existing.is_some() && existing.as_deref() == Some(cid_string(&make_record(value.clone()).cid).as_str()) {
// Writing what is already there makes no commit.
let uri = s.repo.uri(collection, rkey);
return Ok(Resp::Json(with_status(json!({ "uri": uri, "cid": existing }), status)));
}
// `swapRecord: null` asks that there be no record.
match b.get("swapRecord") {
None => {}
Some(Json::Null) if existing.is_none() => {}
Some(Json::String(c)) if existing.as_deref() == Some(c.as_str()) => {}
Some(_) => return err(400, "InvalidSwap", "Record was at a different CID"),
}
let op = if existing.is_some() {
Op::Update { collection: collection.into(), rkey: rkey.into(), value }
} else {
Op::Create { collection: collection.into(), rkey: Some(rkey.into()), value }
};
let (uri, cid) = written(s.repo.apply(vec![op], opt(b, "swapCommit"))?)?;
Ok(Resp::Json(with_status(json!({ "uri": uri, "cid": cid, "commit": commit_meta(s) }), status)))
}
fn delete_record(s: &mut Server, b: &Map<String, Json>) -> Result<Resp, XrpcError> {
let (repo, collection, rkey) = (required(b, "repo")?, required(b, "collection")?, required(b, "rkey")?);
check_account(s, repo)?;
let existing = s.repo.records.get(&format!("{collection}/{rkey}")).map(|r| cid_string(&r.cid));
if existing.is_none() {
return Ok(Resp::Json(json!({})));
}
if opt(b, "swapRecord").is_some_and(|c| existing.as_deref() != Some(c)) {
return err(400, "InvalidSwap", "Record was at a different CID");
}
s.repo.apply(vec![Op::Delete { collection: collection.into(), rkey: rkey.into() }], opt(b, "swapCommit"))?;
Ok(Resp::Json(json!({ "commit": commit_meta(s) })))
}
fn apply_writes(s: &mut Server, b: &Map<String, Json>) -> Result<Resp, XrpcError> {
let repo = required(b, "repo")?;
let status = validation_status(b)?;
let Some(Json::Array(writes)) = b.get("writes") else { return invalid("Input/writes must be an array") };
let mut ops = Vec::with_capacity(writes.len());
for w in writes {
let Json::Object(w) = w else { return invalid("invalid write") };
let collection = required(w, "collection")?.to_string();
ops.push(match opt(w, "$type") {
Some("com.atproto.repo.applyWrites#create") => {
Op::Create { collection, rkey: opt(w, "rkey").map(Into::into), value: record_value(w, "value")? }
}
Some("com.atproto.repo.applyWrites#update") => {
Op::Update { collection, rkey: required(w, "rkey")?.into(), value: record_value(w, "value")? }
}
Some("com.atproto.repo.applyWrites#delete") => Op::Delete { collection, rkey: required(w, "rkey")?.into() },
_ => return invalid("unknown write type"),
});
}
check_account(s, repo)?;
for op in &mut ops {
if let Op::Create { collection, value, .. } | Op::Update { collection, value, .. } = op {
*value = typed(std::mem::replace(value, V::Null), collection)?;
}
}
let results: Vec<Json> = s
.repo
.apply(ops, opt(b, "swapCommit"))?
.into_iter()
.map(|r| match r {
OpResult::Create { uri, cid } => {
with_status(json!({ "$type": "com.atproto.repo.applyWrites#createResult", "uri": uri, "cid": cid }), status)
}
OpResult::Update { uri, cid } => {
with_status(json!({ "$type": "com.atproto.repo.applyWrites#updateResult", "uri": uri, "cid": cid }), status)
}
OpResult::Delete => json!({ "$type": "com.atproto.repo.applyWrites#deleteResult" }),
})
.collect();
Ok(Resp::Json(json!({ "commit": commit_meta(s), "results": results })))
}
#[cfg(test)]
mod tests {
use crate::testing::*;
use serde_json::json;
/// listRecords pages through its collection alone, both ways.
#[test]
fn list_records_pages_a_collection() {
let dir = scratch("list");
let mut s = open(&dir);
let owner = session(&mut s);
for c in ["a.b.c", "a.b.cd", "a.b.c.d", "a.b.b"] {
for k in ["-x", "1", "m", "z~"] {
call(&mut s, "com.atproto.repo.putRecord", Some(&owner), json!({ "repo": DID, "collection": c, "rkey": k, "record": {} })).unwrap();
}
}
let mut list = |reverse: bool, cursor: Option<&str>| {
let mut p = vec![("repo".to_string(), DID.to_string()), ("collection".into(), "a.b.c".into()), ("limit".into(), "3".into())];
p.extend(reverse.then(|| ("reverse".to_string(), "true".to_string())));
p.extend(cursor.map(|c| ("cursor".to_string(), c.to_string())));
let got = call_with(&mut s, "com.atproto.repo.listRecords", None, &p, json!({})).unwrap();
let keys: Vec<String> = got["records"].as_array().unwrap().iter().map(|r| r["uri"].as_str().unwrap().rsplit('/').next().unwrap().to_string()).collect();
(keys, got["cursor"].as_str().map(str::to_string))
};
assert_eq!(list(false, None), (vec!["z~".into(), "m".into(), "1".into()], Some("1".into())));
assert_eq!(list(false, Some("1")), (vec!["-x".into()], Some("-x".into())));
assert_eq!(list(false, Some("-x")), (vec![], None));
assert_eq!(list(true, None), (vec!["-x".into(), "1".into(), "m".into()], Some("m".into())));
assert_eq!(list(true, Some("m")), (vec!["z~".into()], Some("z~".into())));
assert_eq!(list(true, Some("")), (vec!["-x".into(), "1".into(), "m".into()], Some("m".into())));
assert_eq!(list(false, Some("")).0, Vec::<String>::new());
let _ = std::fs::remove_dir_all(&dir);
}
}
crates/pds-server/src/server.rsnew+67−0
@@ -0,0 +1,67 @@
//! The server and its sessions: `describeServer`, `createSession` and
//! `getSession`, as `spec/PDS.md` says.
use crate::{Auth, Call, Handler, Resp, Server, XrpcError, auth, err, invalid_token, required};
use serde_json::{Map, Value as Json, json};
pub(crate) fn handler(nsid: &str) -> Option<Handler> {
Some(match nsid {
"com.atproto.server.describeServer" => Handler::Query(describe_server),
"com.atproto.server.getSession" => Handler::Query(get_session),
"com.atproto.server.createSession" => Handler::Procedure { owner: false, f: create_session },
_ => return None,
})
}
fn describe_server(s: &Server, _: &Call, _: &Map<String, Json>) -> Result<Resp, XrpcError> {
Ok(Resp::Json(json!({
"did": s.did, "availableUserDomains": [], "inviteCodeRequired": false
})))
}
fn get_session(s: &Server, call: &Call, _: &Map<String, Json>) -> Result<Resp, XrpcError> {
match auth(s, call.bearer) {
Auth::Owner => Ok(Resp::Json(json!({ "handle": s.handle, "did": s.did, "active": true }))),
Auth::None => err(401, "AuthMissing", "Authentication Required"),
Auth::Invalid => invalid_token(),
}
}
fn token(prefix: &str) -> String {
let b: [u8; 24] = rand::random();
format!("{prefix}.{}", hex::encode(b))
}
fn create_session(s: &mut Server, b: &Map<String, Json>) -> Result<Resp, XrpcError> {
let (id, pw) = (required(b, "identifier")?, required(b, "password")?);
if (id != s.handle && id != s.did) || pw != s.password {
return err(401, "AuthenticationRequired", "Invalid identifier or password");
}
let access = token("owner");
s.owner_tokens.push(access.clone());
s.pending.push(json!({ "t": "session", "token": access }));
Ok(Resp::Json(json!({
"accessJwt": access, "refreshJwt": token("refresh"), "handle": s.handle, "did": s.did,
"didDoc": { "id": s.did }, "active": true
})))
}
#[cfg(test)]
mod tests {
use crate::Server;
use crate::testing::*;
use serde_json::json;
#[test]
fn get_session_answers_by_token() {
let dir = scratch("session");
let mut s = open(&dir);
let get = |s: &mut Server, t: Option<&str>| call(s, "com.atproto.server.getSession", t, json!({}));
assert_eq!(get(&mut s, None), Err("AuthMissing".into()));
assert_eq!(get(&mut s, Some("forged")), Err("InvalidToken".into()));
let sess = call(&mut s, "com.atproto.server.createSession", None, json!({ "identifier": DID, "password": "pw" })).unwrap();
let got = get(&mut s, sess["accessJwt"].as_str()).unwrap();
assert_eq!(got, json!({ "handle": "h.test", "did": DID, "active": true }));
let _ = std::fs::remove_dir_all(&dir);
}
}
crates/pds-server/src/sync.rsnew+73−0
@@ -0,0 +1,73 @@
//! The repository whole: `getRepo` and `getLatestCommit`, as `spec/SYNC.md`
//! says. The firehose, `subscribeRepos`, is in `events`.
use crate::{Call, Handler, Resp, Server, XrpcError, commit_meta, err, opt, required};
use serde_json::{Map, Value as Json};
pub(crate) fn handler(nsid: &str) -> Option<Handler> {
Some(match nsid {
"com.atproto.sync.getRepo" => Handler::Query(get_repo),
"com.atproto.sync.getLatestCommit" => Handler::Query(get_latest_commit),
_ => return None,
})
}
fn check_did(s: &Server, did: &str) -> Result<(), XrpcError> {
if did == s.did { Ok(()) } else { err(400, "RepoNotFound", "Could not find repo") }
}
fn get_repo(s: &Server, _: &Call, p: &Map<String, Json>) -> Result<Resp, XrpcError> {
check_did(s, required(p, "did")?)?;
Ok(Resp::Car(match opt(p, "since") {
None => s.repo.car(),
Some(since) => s.repo.car_since(since),
}))
}
fn get_latest_commit(s: &Server, _: &Call, p: &Map<String, Json>) -> Result<Resp, XrpcError> {
check_did(s, required(p, "did")?)?;
Ok(Resp::Json(commit_meta(s)))
}
#[cfg(test)]
mod tests {
use crate::testing::*;
use pds_repo::data::*;
use pds_repo::*;
use serde_json::json;
/// `getRepo since` answers the same after a restart, which rebuilds when
/// each block was added from the log.
#[test]
fn since_survives_restart() {
let dir = scratch("since");
let mut s = open(&dir);
let owner = session(&mut s);
let mut revs = vec![s.repo.rev.clone()];
for (k, n) in [("one", 1), ("two", 2), ("one", 3), ("three", 1)] {
let body = json!({ "repo": DID, "collection": "a.b.c", "rkey": k, "record": { "n": n } });
call(&mut s, "com.atproto.repo.putRecord", Some(&owner), body).unwrap();
revs.push(s.repo.rev.clone());
}
call(&mut s, "com.atproto.repo.deleteRecord", Some(&owner), json!({ "repo": DID, "collection": "a.b.c", "rkey": "two" })).unwrap();
revs.push(s.repo.rev.clone());
let before: Vec<Vec<u8>> = revs.iter().map(|r| s.repo.car_since(r)).collect();
// At the latest rev, the CAR is its header alone.
let latest = before.last().unwrap();
assert_eq!(latest, &car_file(&s.repo.head, std::iter::empty()));
// A record's block is among them from the commit that last made the
// repository hold it: `three` holds again what `one` first held.
let holds = |car: &[u8], n: i64| {
let r = make_record(from_json(&json!({ "n": n, "$type": "a.b.c" })).unwrap());
car.windows(r.bytes.len()).any(|w| w == r.bytes.as_slice())
};
assert!(holds(&before[3], 1) && !holds(&before[3], 2) && !holds(&before[3], 3));
assert!(!holds(&before[4], 1));
assert!(holds(&before[0], 1) && holds(&before[0], 3) && !holds(&before[0], 2));
drop(s);
let s = open(&dir);
let after: Vec<Vec<u8>> = revs.iter().map(|r| s.repo.car_since(r)).collect();
assert_eq!(before, after);
let _ = std::fs::remove_dir_all(&dir);
}
}
harness/checks/commands.mjsnew+73−0
@@ -0,0 +1,73 @@
// The MCP tools and CLI commands themselves, against the lexicons
// (spec/COMMANDS.md). The calls through them are lib/via.mjs's.
import { isDeepStrictEqual } from 'node:util'
import { cand } from '../lib/processes.mjs'
import { count, differ } from '../lib/report.mjs'
import { ACCOUNT_ARGS, METHODS, MCP_VERSION, mcpRpc, runCli } from '../lib/via.mjs'
/// What a lexicon type is as JSON Schema, by spec/COMMANDS.md: the `type`
/// expected, or undefined for none.
function schemaType(t) {
if (['string', 'integer', 'boolean', 'array'].includes(t)) return t
if (['object', 'ref', 'union'].includes(t)) return 'object'
return undefined
}
/// The tools and commands, as spec/COMMANDS.md derives them from the
/// lexicons: `server/discover`, the tool list and each tool's schema, the
/// CLI's help at each level, and usage errors for what it does not take.
export async function checkCommands() {
const d = await mcpRpc('server/discover', {}, undefined, 'DiscoverResult')
if (d.failed || d.message.error) await differ('MCP server/discover', {}, 'a DiscoverResult', d)
if (!d.message.result.supportedVersions?.includes(MCP_VERSION) || !d.message.result.capabilities?.tools) await differ('MCP server/discover', {}, `supportedVersions with ${MCP_VERSION}, and the tools capability`, d.message.result)
const want = Object.values(METHODS).filter((m) => m.tool)
for (const token of [undefined, cand.token]) {
const r = await mcpRpc('tools/list', {}, token, 'ListToolsResult')
if (r.failed || r.message.error) await differ('MCP tools/list', { token: token ? 'the account\'s' : 'none' }, 'a ListToolsResult', r)
const tools = r.message.result.tools
const names = tools.map((t) => t.name).sort()
if (!isDeepStrictEqual(names, want.map((m) => m.tool).sort())) await differ('MCP tools/list', { token: token ? 'the account\'s' : 'none' }, want.map((m) => m.tool).sort(), names, 'a tool for every method with a JSON answer')
for (const m of want) {
const t = tools.find((t) => t.name === m.tool)
const s = t.inputSchema ?? {}
const props = s.properties ?? {}
const fail = (why, got) => differ(`tool ${m.tool}`, { method: m.nsid }, why, got)
if (t.description !== m.description) await fail(`the lexicon's description: ${m.description}`, t.description)
if (s.type !== 'object' || !isDeepStrictEqual(Object.keys(props).sort(), Object.keys(m.props).sort())) await fail(`an object schema with the lexicon's properties: ${Object.keys(m.props).sort()}`, s)
const required = m.required.filter((k) => !ACCOUNT_ARGS.includes(k)).sort()
if (!isDeepStrictEqual([...(s.required ?? [])].sort(), required)) await fail(`required ${required}`, s.required ?? [])
for (const [k, lexProp] of Object.entries(m.props)) {
const type = schemaType(lexProp.type)
const want = m.nullable.includes(k) ? [type, 'null'] : type
if (!isDeepStrictEqual(props[k]?.type, want)) await fail(`${k} of type ${JSON.stringify(want) ?? 'any'}, as its lexicon type ${lexProp.type}${m.nullable.includes(k) ? ', nullable' : ''}`, props[k])
for (const c of ['minimum', 'maximum', 'maxLength', 'enum']) if (lexProp[c] !== undefined && !isDeepStrictEqual(props[k]?.[c], lexProp[c])) await fail(`${k} with ${c} ${JSON.stringify(lexProp[c])}`, props[k])
}
const destructive = ['com.atproto.repo.deleteRecord', 'com.atproto.repo.putRecord', 'com.atproto.repo.applyWrites'].includes(m.nsid)
const hints = m.kind === 'query' ? { readOnlyHint: true } : { readOnlyHint: false, destructiveHint: destructive }
for (const [h, v] of Object.entries(hints)) if (t.annotations?.[h] !== v) await fail(`${h}: ${v}`, t.annotations ?? null)
}
}
const unknown = await mcpRpc('tools/call', { name: 'no_such_tool', arguments: {} }, cand.token, 'CallToolResult')
if (unknown.message?.error?.code !== -32602) await differ('MCP tools/call', { name: 'no_such_tool' }, 'the protocol error -32602', unknown.message ?? unknown)
const malformed = await mcpRpc('tools/call', { name: METHODS['com.atproto.repo.getRecord'].tool, arguments: 'not an object' }, cand.token, 'CallToolResult')
if (malformed.message?.error?.code !== -32602) await differ('MCP tools/call', { arguments: 'not an object' }, 'the protocol error -32602', malformed.message ?? malformed)
count('tool list and schemas', true)
const cli = Object.values(METHODS).filter((m) => m.command)
const top = await runCli(['--help'])
for (const g of new Set(cli.map((m) => m.group))) {
if (top.code !== 0 || !top.stdout.toString().includes(g)) await differ('pds --help', {}, `exit 0, listing the group ${g}`, { code: top.code, stdout: top.stdout.toString().slice(0, 500) })
const h = await runCli([g, '--help'])
for (const m of cli.filter((m) => m.group === g)) {
if (h.code !== 0 || !h.stdout.toString().includes(m.command)) await differ(`pds ${g} --help`, {}, `exit 0, listing ${m.command}`, { code: h.code, stdout: h.stdout.toString().slice(0, 500) })
const c = await runCli([g, m.command, '--help'])
for (const p of Object.keys(m.props)) if (c.code !== 0 || !c.stdout.toString().includes(m.flag(p))) await differ(`pds ${g} ${m.command} --help`, {}, `exit 0, listing ${m.flag(p)}`, { code: c.code, stdout: c.stdout.toString().slice(0, 500) })
const bad = await runCli([g, m.command, '--no-such-flag', 'x'])
if (bad.code !== 2) await differ(`pds ${g} ${m.command} --no-such-flag x`, {}, 'a usage error: exit 2', { code: bad.code, stdout: bad.stdout.toString().slice(0, 300) })
}
const none = await runCli([g, 'no-such-command'])
if (none.code !== 2) await differ(`pds ${g} no-such-command`, {}, 'a usage error: exit 2', { code: none.code })
}
count('command help and usage', true)
}
harness/checks/crashes.mjsnew+60−0
@@ -0,0 +1,60 @@
// Crashes: the server killed with SIGKILL and started again on its data
// (spec/DURABILITY.md).
import { FIREHOSE } from '../lib/args.mjs'
import { COLLECTIONS, RKEYS, below, goodRecord, pick, rand } from '../lib/random.mjs'
import { HANDLE, cand, ref, server, wait, waitReady } from '../lib/processes.mjs'
import { differ } from '../lib/report.mjs'
import { nextBatch, noteCommit, noteWrite, records } from '../lib/state.mjs'
import { xrpc } from '../lib/xrpc.mjs'
import { resubscribe } from './firehose.mjs'
import { syncHeads } from './records.mjs'
import { checkRepos } from './repository.mjs'
export const crashes = { count: 0, inFlight: 0, landed: 0, restartMs: [] }
/// Kill the server with SIGKILL, sometimes with a put on its way, and start
/// it again on the same data. Every write it answered must still be there,
/// and what it was killed during must have happened entirely or not at all.
export async function crash() {
const op = rand() < 0.6 ? inFlightPut() : null
if (op) await wait(below(8))
await server.kill()
crashes.count += 1
server.start()
crashes.restartMs.push(await waitReady(server, cand.url))
if (FIREHOSE) resubscribe()
if (op) {
crashes.inFlight += 1
// A request that had not reached the process before it died may reach
// the new one, so whether it landed is known only once it is answered.
op.answer = await op.sent
await op.settle()
}
await syncHeads()
await checkRepos()
}
/// An account's put on its way.
function inFlightPut() {
const collection = pick(COLLECTIONS)
const key = pick(RKEYS)
const body = { repo: HANDLE, collection, rkey: key, record: { ...goodRecord(collection), batch: nextBatch() } }
const before = records.get(`${collection}/${key}`) ?? null
return {
sent: xrpc(cand, 'com.atproto.repo.putRecord', { body, token: cand.token }),
async settle() {
const got = await xrpc(cand, 'com.atproto.repo.getRecord', { params: { repo: HANDLE, collection, rkey: key } })
const nowCid = got.status === 200 ? got.body.cid : null
if (nowCid === before) return
// It landed, so make it on the reference too; the repository check
// then says whether it landed whole.
crashes.landed += 1
const a = await xrpc(ref, 'com.atproto.repo.putRecord', { body, token: ref.token })
if (a.status >= 400) await differ('a write the process was killed during', body, 'nothing, or the whole write', got.body, 'the reference refuses it')
if (a.body.cid !== nowCid) await differ('a write the process was killed during', body, { cid: a.body.cid }, { cid: nowCid }, 'it landed only in part')
noteWrite(collection, key, a)
noteCommit(ref, a)
},
}
}
harness/checks/firehose.mjsnew+212−0
@@ -0,0 +1,212 @@
// The firehose: each side's subscribeRepos, every event checked as a
// consumer would and the server's held to the reference's (spec/SYNC.md).
import { isDeepStrictEqual } from 'node:util'
import { readCarWithRoot, verifyProofs, verifyCommitSig, MST, MemoryBlockstore } from '@atproto/repo'
import { cborDecode, cborDecodeMulti } from '@atproto/common'
import { getKey } from '@atproto/identity'
import { chance, pick } from '../lib/random.mjs'
import { cand, ref, wait } from '../lib/processes.mjs'
import { count, differ } from '../lib/report.mjs'
import { xrpc } from '../lib/xrpc.mjs'
/// A subscription to the server's `subscribeRepos`, adding every event it
/// sends to `events`.
function subscribe(side, cursor, events = []) {
const url = `${side.url.replace(/^http/, 'ws')}/xrpc/com.atproto.sync.subscribeRepos${cursor === undefined ? '' : `?cursor=${cursor}`}`
const ws = new WebSocket(url)
ws.binaryType = 'arraybuffer'
const sub = { ws, events, open: true }
ws.onmessage = (m) => {
try {
const [header, body] = cborDecodeMulti(new Uint8Array(m.data))
events.push({ header, body })
} catch (err) {
events.push({ header: { op: -1 }, body: { error: 'Undecodable', message: String(err) } })
}
}
sub.closed = new Promise((ok) => (ws.onclose = () => ((sub.open = false), ok())))
ws.onerror = () => {}
return sub
}
/// What the harness has seen of each side's firehose: every event, how many
/// it has checked, the last seq, and the rev and tree root its last commit
/// or sync event left.
const firehose = { reference: null, server: null, checks: 0 }
export async function startFirehose() {
for (const side of [ref, cand]) {
const described = await xrpc(side, 'com.atproto.repo.describeRepo', { params: { repo: side.did } })
const key = side === cand ? cand.key : getKey(described.body.didDoc)
firehose[side.name] = { side, key, events: [], seen: 0, lastSeq: 0, chain: null }
firehose[side.name].sub = subscribe(side, 0, firehose[side.name].events)
}
}
/// After a restart, carry on from the last event received.
export function resubscribe() {
const f = firehose.server
const last = f.events.findLast((e) => e.body.seq !== undefined)?.body.seq
f.sub = subscribe(cand, last ?? 0, f.events)
}
const kind = (e) => (e.header.op === -1 ? `error ${e.body.error}` : e.header.t)
// Each side gives a record created without a key a TID of its own; no key
// the harness chooses has a TID's shape.
const sameKey = (path) => path.replace(/\/[234567a-z]{13}$/, '/<tid>')
const opKey = (op) => `${op.action} ${sameKey(op.path)} ${op.cid?.toString() ?? '-'} ${op.prev?.toString() ?? '-'}`
function describeEvent(e) {
const b = e.body
return {
type: kind(e),
seq: b.seq,
rev: b.rev,
since: b.since,
prevData: b.prevData?.toString(),
commit: b.commit?.toString(),
ops: b.ops?.map(opKey),
...(e.header.op === -1 ? { error: b.error, message: b.message } : {}),
}
}
/// Check one event on its own terms: what the sync spec says a consumer
/// checks, and that it continues the chain of events before it. The
/// reference's events are checked too, which checks the checks.
async function checkEvent(f, e) {
const { header, body } = e
const did = f.side.did
const fail = (why) => differ(`the ${f.side.name}'s firehose`, { event: kind(e), seq: body.seq }, why, describeEvent(e))
if (header.op === -1) return fail('no error frame')
if (!(body.seq > f.lastSeq)) return fail(`a seq after ${f.lastSeq}`)
f.lastSeq = body.seq
if (header.t === '#identity' || header.t === '#account') {
if (body.did !== did) return fail(`the account's did`)
return
}
if (header.t !== '#commit' && header.t !== '#sync') return fail('a #commit, #sync, #identity or #account event')
if ((body.repo ?? body.did) !== did) return fail(`the account's did`)
let car
try {
car = await readCarWithRoot(body.blocks)
} catch (err) {
return fail(`blocks that are a CAR file (${err.message})`)
}
let commit
try {
commit = cborDecode(car.blocks.get(car.root))
} catch {
return fail('blocks holding the commit they name as root')
}
if (header.t === '#commit' && body.commit?.toString() !== car.root.toString()) return fail('a commit that is the root of its blocks')
if (commit.did !== did || commit.rev !== body.rev || commit.version !== 3) return fail(`a version 3 commit with the event's did and rev`)
if (!(await verifyCommitSig(commit, f.key))) return fail(`a commit signed with the account's key`)
const prev = f.chain
if (header.t === '#sync') {
if (prev && !(body.rev >= prev.rev)) return fail(`a rev not before ${prev.rev}`)
f.chain = { rev: body.rev, data: commit.data.toString() }
return
}
if (prev && !(body.rev > prev.rev)) return fail(`a rev after ${prev.rev}`)
if (body.rebase || body.tooBig) return fail('rebase and tooBig false')
if ((body.since ?? null) !== (prev?.rev ?? null)) return fail(`since ${prev?.rev ?? null}`)
if (prev) {
if (body.prevData?.toString() !== prev.data) return fail(`prevData ${prev.data}`)
// Undo the ops on the tree in the event's blocks: the root must be the
// previous commit's, so the event alone shows what changed.
try {
let mst = MST.load(new MemoryBlockstore(car.blocks), commit.data)
for (const op of [...body.ops].reverse()) {
if (op.action === 'create') mst = await mst.delete(op.path)
else if (op.action === 'update') mst = await mst.update(op.path, op.prev)
else if (op.action === 'delete') mst = await mst.add(op.path, op.prev)
else return fail('ops that are create, update or delete')
}
const root = (await mst.getPointer()).toString()
if (root !== prev.data) return fail(`ops that undo to the previous tree, ${prev.data}, not ${root}`)
} catch (err) {
return fail(`blocks that let the ops be undone (${err.message})`)
}
const claims = body.ops.map((op) => {
const [collection, rkey] = op.path.split('/')
return { collection, rkey, cid: op.action === 'delete' ? null : op.cid }
})
try {
await verifyProofs(body.blocks, claims, did, f.key)
} catch (err) {
return fail(`blocks that prove every op (${err.message})`)
}
}
f.chain = { rev: body.rev, data: commit.data.toString() }
}
/// Both firehoses caught up with their latest commits, each new event
/// checked, and the same writes on both sides since the last check.
export async function checkFirehose() {
const first = firehose.checks++ === 0
const fresh = {}
for (const side of [ref, cand]) {
const f = firehose[side.name]
const latest = await xrpc(side, 'com.atproto.sync.getLatestCommit', { params: { did: side.did } })
const has = () => f.events.some((e) => e.header.t === '#commit' && e.body.commit?.toString() === latest.body.cid)
const started = Date.now()
while (!has() && Date.now() - started < 3000) await wait(20)
if (!has()) await differ(`the ${side.name}'s firehose`, {}, `an event for the latest commit, ${latest.body.cid}, within 3s`, f.events.slice(-3).map(describeEvent))
fresh[side.name] = f.events.slice(f.seen)
f.seen = f.events.length
for (const e of fresh[side.name]) await checkEvent(f, e)
}
if (first) {
// A new account's first events.
const [a, b] = [fresh.reference.map(kind), fresh.server.map(kind)]
if (!isDeepStrictEqual(a, b)) await differ('the firehose', { from: 'the start' }, a, b, 'the events a new account starts with')
return
}
// Writes sent at once may be committed in either order.
const commits = (events) => events.filter((e) => e.header.t === '#commit').map((e) => e.body.ops.map(opKey).sort().join(' | ')).sort()
const [a, b] = [commits(fresh.reference), commits(fresh.server)]
if (!isDeepStrictEqual(a, b)) await differ('the firehose', { since: 'the last check' }, a, b, 'the commits since the last check, by their ops')
const others = (events) => events.filter((e) => e.header.t !== '#commit').map(kind)
if (!isDeepStrictEqual(others(fresh.reference), others(fresh.server))) await differ('the firehose', { since: 'the last check' }, others(fresh.reference), others(fresh.server), 'events other than commits')
count('firehose check', true)
}
/// A new subscription from a cursor must replay exactly the events after it,
/// and one from the future must be refused as the reference refuses it.
export async function checkReplay() {
const all = firehose.server.events
const from = chance(0.2) ? 0 : pick(all).body.seq
const line = (e) => `${e.body.seq} ${kind(e)} ${e.body.commit ?? ''}`
const want = all.filter((e) => e.body.seq > from).map(line)
const replay = subscribe(cand, from)
const started = Date.now()
while (replay.events.length < want.length && Date.now() - started < 3000) await wait(20)
await wait(50)
replay.ws.close()
const got = replay.events.map(line)
if (!isDeepStrictEqual(got, want)) await differ('subscribeRepos from a cursor', { cursor: from }, want, got)
count('firehose replay', true)
const future = firehose.server.lastSeq + 1000
const answers = {}
for (const side of [ref, cand]) {
const sub = subscribe(side, future)
const t = Date.now()
while (sub.open && Date.now() - t < 2000) await wait(20)
sub.ws.close()
answers[side.name] = { events: sub.events.map(kind), closed: !sub.open }
}
if (!isDeepStrictEqual(answers.reference, answers.server)) await differ('subscribeRepos from a cursor in the future', { cursor: future }, answers.reference, answers.server)
// A cursor that is not an integer is refused as the reference refuses it.
const odd = {}
for (const side of [ref, cand]) {
const sub = subscribe(side, 'abc')
const t = Date.now()
while (sub.open && Date.now() - t < 2000) await wait(20)
sub.ws.close()
odd[side.name] = { events: sub.events.map(kind), closed: !sub.open }
}
if (!isDeepStrictEqual(odd.reference, odd.server)) await differ('subscribeRepos from a cursor that is not an integer', { cursor: 'abc' }, odd.reference, odd.server)
}
harness/checks/odd.mjsnew+89−0
@@ -0,0 +1,89 @@
// Odd requests: those at the edges of what the spec settles, across the
// methods, each held to the reference.
import { isDeepStrictEqual } from 'node:util'
import { COLLECTIONS, RKEYS, chance, goodRecord, pick, rand, record } from '../lib/random.mjs'
import { HANDLE, PASSWORD, cand, ref } from '../lib/processes.mjs'
import { count, differ } from '../lib/report.mjs'
import { cids, exists, nextBatch, noteCommit, records } from '../lib/state.mjs'
import { both, normalize, xrpcHttp } from '../lib/xrpc.mjs'
/// A DID no server here holds.
const NOBODY = 'did:plc:aaaaaaaaaaaaaaaaaaaaaaaa'
/// Requests at the edges of what spec/PDS.md and its pages settle, each held to the
/// reference: writes with no token or one never given out, whatever their
/// input; a write to another repository; the sync methods and describeRepo
/// of a DID no one holds; arguments their lexicon refuses; a method called
/// with the other HTTP method; and writes with `validate` set.
export async function oddRequests() {
const collection = pick(COLLECTIONS)
const bad = chance(0.5)
const writeBody = () => ({ repo: HANDLE, collection: bad ? 'not an nsid' : collection, rkey: pick(RKEYS), record: record(collection, cids) })
const r = rand()
if (r < 0.2) {
const nsid = pick(['com.atproto.repo.createRecord', 'com.atproto.repo.putRecord', 'com.atproto.repo.deleteRecord'])
return void (await both(`write with no token${bad ? ', bad input' : ''}`, nsid, { body: writeBody() }))
}
if (r < 0.3) return void (await both('write with a token never given out, bad input', 'com.atproto.repo.createRecord', { body: { ...writeBody(), collection: 'not an nsid' }, token: 'never-given-out' }))
if (r < 0.45) return void (await both('write to another repository', 'com.atproto.repo.createRecord', { body: { ...writeBody(), collection, repo: NOBODY }, token: 'owner' }))
if (r < 0.6 && chance(0.5)) {
const [nsid, params] = pick([
['com.atproto.repo.describeRepo', { repo: NOBODY }],
['com.atproto.sync.getLatestCommit', { did: NOBODY }],
['com.atproto.sync.getRepo', { did: NOBODY }],
])
return void (await both('a repository no one holds', nsid, { params }))
}
if (r < 0.6) {
// Arguments of the wrong syntax or type, which the method's lexicon
// refuses. Over HTTP only: a command parses its flags first, as
// COMMANDS.md says, and a value such as `reverse: maybe` is no flag.
const k = pick(RKEYS)
const [nsid, request] = pick([
['com.atproto.repo.createRecord', { body: { repo: HANDLE, collection, record: goodRecord(collection), validate: null }, token: 'owner' }],
['com.atproto.repo.listRecords', { params: { repo: HANDLE, collection, reverse: 'maybe' } }],
['com.atproto.repo.createRecord', { body: { repo: 'not a did', collection, record: goodRecord(collection) }, token: 'owner' }],
['com.atproto.repo.describeRepo', { params: { repo: 'not a did' } }],
['com.atproto.sync.getLatestCommit', { params: { did: 'not a did' } }],
['com.atproto.repo.getRecord', { params: { repo: HANDLE, collection, rkey: k, cid: 'not a cid' } }],
['com.atproto.repo.createRecord', { body: { repo: HANDLE, collection, record: goodRecord(collection), swapCommit: 'not a cid' }, token: 'owner' }],
['com.atproto.repo.putRecord', { body: { repo: HANDLE, collection, rkey: k, record: goodRecord(collection), swapRecord: 'not a cid' }, token: 'owner' }],
['com.atproto.sync.getRepo', { params: { did: NOBODY, since: 'notarev' } }],
['com.atproto.server.createSession', { body: { identifier: HANDLE, password: PASSWORD, authFactorToken: 5 } }],
])
const [a, b] = await Promise.all([ref, cand].map((side) => xrpcHttp(side, nsid, { ...request, token: request.token === 'owner' ? side.token : undefined })))
const [na, nb] = [normalize(ref, a), normalize(cand, b)]
if (!isDeepStrictEqual(na, nb)) await differ(nsid, request, na, nb, 'arguments the lexicon refuses')
return count('arguments the lexicon refuses', a.status < 400)
}
if (r < 0.75) {
// The other HTTP method: a procedure by GET, a query by POST.
const [nsid, request] = chance(0.5)
? ['com.atproto.repo.createRecord', { method: 'GET' }]
: ['com.atproto.repo.getRecord', { method: 'POST', body: {}, params: { repo: HANDLE, collection, rkey: pick(RKEYS) } }]
const [a, b] = await Promise.all([ref, cand].map((side) => xrpcHttp(side, nsid, { ...request, token: side.token })))
const [na, nb] = [normalize(ref, a), normalize(cand, b)]
if (!isDeepStrictEqual(na, nb)) await differ(nsid, { by: request.method }, na, nb, 'called with the other HTTP method')
return count('the other HTTP method', false)
}
// validate: true is refused for want of a lexicon; false writes, with no validationStatus.
const validate = chance(0.5)
const key = pick(RKEYS)
const value = { ...goodRecord(collection), batch: nextBatch() }
const [nsid, body] = pick([
['com.atproto.repo.createRecord', { repo: HANDLE, collection, rkey: key, record: value, validate }],
['com.atproto.repo.putRecord', { repo: HANDLE, collection, rkey: key, record: value, validate }],
['com.atproto.repo.applyWrites', { repo: HANDLE, validate, writes: [{ $type: `com.atproto.repo.applyWrites#${exists(collection, key) ? 'update' : 'create'}`, collection, rkey: key, value }] }],
])
const [a, b] = await both(`validate: ${validate}`, nsid, { body, token: 'owner' })
if (a.status < 400) {
const cid = a.body.cid ?? a.body.results?.[0]?.cid
if (cid) {
records.set(`${collection}/${key}`, cid)
cids.push(cid)
}
}
noteCommit(ref, a)
noteCommit(cand, b)
}
harness/checks/records.mjsnew+248−0
harness/checks/repository.mjsnew+166−0
harness/checks/session.mjsnew+48−0
harness/lib/args.mjsnew+21−0
harness/lib/processes.mjsnew+112−0
harness/lib/random.mjsnew+52−0
harness/lib/report.mjsnew+25−0
harness/lib/state.mjsnew+43−0
harness/lib/via.mjsnew+217−0
harness/lib/xrpc.mjsnew+78−0
harness/compare.mjs+28−1357
1385 lines changed: not loaded until asked for.
spec/COMMANDS.md+3−3
spec/DURABILITY.mdnew+29−0
spec/PDS.mdnew+101−0
spec/REPO.mdnew+50−0
spec/SLICE.mddeleted+0−211
spec/SYNC.mdnew+70−0
AGENTS.md+15−9
README.md+4−4