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

Take the better parts of both implementations

Merged chadtmiller.com asked to merge into main from chadtmiller.com/monolith:best-of-both
crates/pds-lexicon/src/lib.rs+226−3
@@ -1,7 +1,10 @@
//! The methods the server serves, read from their lexicons in `spec/lexicons`,
//! and the MCP tool and CLI command each one is (`spec/COMMANDS.md`).
//! the MCP tool and CLI command each one is (`spec/COMMANDS.md`), and how a
//! call's parameters and input are checked against its lexicon.
use pds_repo::data::{valid_at_identifier, valid_cid_string, valid_did, valid_handle, valid_nsid, valid_rkey};
use serde_json::{Map, Value as Json, json};
use std::collections::HashMap;
use std::sync::LazyLock;
include!(concat!(env!("OUT_DIR"), "/lexicons.rs"));
@@ -53,6 +56,8 @@ pub struct Arg {
pub description: Option<String>,
/// The JSON Schema of its value in the method's MCP tool's `inputSchema`.
pub schema: Json,
/// Its lexicon definition.
pub def: Json,
}
impl Arg {
@@ -87,6 +92,8 @@ pub struct Method {
pub args: Vec<Arg>,
/// The encoding of its answer, if it has one.
pub output: Option<String>,
/// The `params` or input schema the arguments are the properties of.
schema: Json,
}
impl Method {
@@ -172,9 +179,19 @@ pub fn groups() -> Vec<&'static str> {
gs
}
/// Every lexicon, by its id.
static DOCS: LazyLock<HashMap<String, Json>> = LazyLock::new(|| {
LEXICONS
.iter()
.map(|t| {
let doc: Json = serde_json::from_str(t).expect("lexicon JSON");
(doc["id"].as_str().expect("lexicon id").to_string(), doc)
})
.collect()
});
fn load() -> Vec<Method> {
let mut methods: Vec<Method> =
LEXICONS.iter().filter_map(|t| read_method(&serde_json::from_str(t).expect("lexicon JSON"))).collect();
let mut methods: Vec<Method> = DOCS.values().filter_map(read_method).collect();
methods.sort_by(|a, b| a.nsid.cmp(&b.nsid));
for (i, m) in methods.iter().enumerate() {
if methods[..i].iter().any(|o| o.group == m.group && o.name == m.name) {
@@ -200,6 +217,7 @@ fn read_method(doc: &Json) -> Option<Method> {
Kind::Procedure => main["input"]["schema"].clone(),
_ => main["parameters"].clone(),
};
let object = if object.is_null() { json!({ "type": "params", "properties": {} }) } else { object };
let required: Vec<&str> = object["required"].as_array().map(|r| r.iter().filter_map(Json::as_str).collect()).unwrap_or_default();
let nullable: Vec<&str> = object["nullable"].as_array().map(|r| r.iter().filter_map(Json::as_str).collect()).unwrap_or_default();
let args = object["properties"]
@@ -215,6 +233,7 @@ fn read_method(doc: &Json) -> Option<Method> {
required: required.contains(&n.as_str()),
description: p["description"].as_str().map(str::to_string),
schema: schema_of(p, ty, nullable.contains(&n.as_str())),
def: p.clone(),
}
})
.collect()
@@ -228,9 +247,180 @@ fn read_method(doc: &Json) -> Option<Method> {
description: main["description"].as_str().map(str::to_string),
args,
output: main["output"]["encoding"].as_str().map(str::to_string),
schema: object,
})
}
impl Method {
/// A query's parameters, from a URL's pairs: each typed as its lexicon
/// says, defaults filled in, then checked. The first of a repeated
/// parameter that is not an array counts; pairs it does not take are passed over.
pub fn parse_params<'a>(&self, pairs: impl IntoIterator<Item = (&'a str, &'a str)>) -> Result<Map<String, Json>, Invalid> {
let mut out = Map::new();
for (k, v) in pairs {
let Some(arg) = self.arg(k) else { continue };
let array = arg.ty == Type::Array;
let ty = if array { arg.def["items"]["type"].as_str() } else { arg.def["type"].as_str() };
let typed = match ty {
Some("integer") => v.parse::<i64>().map(Json::from).map_err(|_| Invalid(format!("Params/{k} must be an integer")))?,
Some("boolean") => match v {
"true" => Json::Bool(true),
"false" => Json::Bool(false),
_ => return Err(Invalid(format!("Params/{k} must be a boolean"))),
},
_ => Json::String(v.to_string()),
};
match out.entry(k).or_insert_with(|| if array { Json::Array(vec![]) } else { typed.clone() }) {
Json::Array(items) if array => items.push(typed),
_ => {}
}
}
for arg in &self.args {
if let (false, Some(d)) = (out.contains_key(&arg.name), arg.def.get("default")) {
out.insert(arg.name.clone(), d.clone());
}
}
let value = Json::Object(out);
validate(&self.nsid, &self.schema, &value, "Params")?;
let Json::Object(out) = value else { unreachable!("built as an object") };
Ok(out)
}
/// Check a procedure's input against its lexicon.
pub fn check_input(&self, input: &Json) -> Result<(), Invalid> {
validate(&self.nsid, &self.schema, input, "Input")
}
}
/// Why a value does not match its lexicon.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Invalid(pub String);
/// The definition a reference made in lexicon `nsid` names (`#name` there,
/// `id` for its main, or `id#name`), and the lexicon it is in.
fn resolve<'a>(nsid: &'a str, r: &'a str) -> Option<(&'static Json, &'a str)> {
let (id, name) = match r.split_once('#') {
Some(("", name)) => (nsid, name),
Some((id, name)) => (id, name),
None => (r, "main"),
};
Some((DOCS.get(id)?["defs"].get(name)?, id))
}
/// A union's ref in full, as a `$type` names it.
fn full_ref(nsid: &str, r: &str) -> String {
match r.split_once('#') {
Some(("", name)) => format!("{nsid}#{name}"),
_ => r.to_string(),
}
}
/// Whether a string is in a lexicon string format, as `atproto/lexicon.md` lists them.
fn in_format(format: &str, s: &str) -> bool {
match format {
"at-identifier" => valid_at_identifier(s),
"did" => valid_did(s),
"handle" => valid_handle(s),
"nsid" => valid_nsid(s),
"record-key" => valid_rkey(s),
"tid" => pds_repo::valid_tid(s),
"cid" => valid_cid_string(s),
"at-uri" => s.starts_with("at://"),
"uri" => s.contains(':'),
_ => true,
}
}
/// Check `value`, at `path`, against the definition `def` in lexicon `nsid`.
pub fn validate(nsid: &str, def: &Json, value: &Json, path: &str) -> Result<(), Invalid> {
let bad = |what: &str| Err(Invalid(format!("{path} must be {what}")));
let strings = |k: &str| def[k].as_array().into_iter().flatten().filter_map(Json::as_str);
match def["type"].as_str().unwrap_or("unknown") {
"object" | "params" => {
let Some(obj) = value.as_object() else { return bad("an object") };
let nullable = |k: &str| strings("nullable").any(|n| n == k);
for r in strings("required") {
match obj.get(r) {
Some(Json::Null) if nullable(r) => {}
None | Some(Json::Null) => return Err(Invalid(format!("{path} must have the property \"{r}\""))),
_ => {}
}
}
for (k, pdef) in def["properties"].as_object().into_iter().flatten() {
match obj.get(k) {
None => {}
Some(Json::Null) if nullable(k) => {}
Some(v) => validate(nsid, pdef, v, &format!("{path}/{k}"))?,
}
}
Ok(())
}
"string" => {
let Some(s) = value.as_str() else { return bad("a string") };
if def["maxLength"].as_u64().is_some_and(|m| s.len() as u64 > m) {
return bad(&format!("no longer than {} characters", def["maxLength"]));
}
if def["minLength"].as_u64().is_some_and(|m| (s.len() as u64) < m) {
return bad(&format!("no shorter than {} characters", def["minLength"]));
}
if let Some(e) = def["enum"].as_array().filter(|e| !e.contains(value)) {
return bad(&format!("one of {}", Json::Array(e.clone())));
}
match def["format"].as_str() {
Some(f) if !in_format(f, s) => bad(&format!("a valid {f}")),
_ => Ok(()),
}
}
"integer" => {
let Some(n) = value.as_i64() else { return bad("an integer") };
if def["minimum"].as_i64().is_some_and(|m| n < m) || def["maximum"].as_i64().is_some_and(|m| n > m) {
return bad(&format!("in the range {}..={}", def["minimum"], def["maximum"]));
}
Ok(())
}
"boolean" if value.is_boolean() => Ok(()),
"boolean" => bad("a boolean"),
"array" => {
let Some(items) = value.as_array() else { return bad("an array") };
if def["maxLength"].as_u64().is_some_and(|m| items.len() as u64 > m) {
return bad(&format!("no more than {} elements", def["maxLength"]));
}
for (i, v) in items.iter().enumerate() {
validate(nsid, &def["items"], v, &format!("{path}/{i}"))?;
}
Ok(())
}
"ref" => {
let r = def["ref"].as_str().unwrap_or_default();
let (target, id) = resolve(nsid, r).ok_or_else(|| Invalid(format!("{path}: no lexicon defines {r}")))?;
validate(id, target, value, path)
}
"union" => {
let Some(t) = value.get("$type").and_then(Json::as_str) else {
return bad("an object which includes the \"$type\" property");
};
let t = t.strip_suffix("#main").unwrap_or(t);
match strings("refs").find(|r| full_ref(nsid, r) == t) {
Some(r) => {
let (target, id) = resolve(nsid, r).ok_or_else(|| Invalid(format!("{path}: no lexicon defines {r}")))?;
validate(id, target, value, path)
}
None if def["closed"].as_bool() == Some(true) => {
bad(&format!("an object of type {}", strings("refs").map(|r| full_ref(nsid, r)).collect::<Vec<_>>().join(", ")))
}
None => Ok(()),
}
}
"unknown" | "blob" if value.is_object() => Ok(()),
"unknown" | "blob" => bad("an object"),
"cid-link" if value.get("$link").and_then(Json::as_str).is_some_and(valid_cid_string) => Ok(()),
"cid-link" => bad("a CID link"),
"bytes" if value.get("$bytes").is_some_and(Json::is_string) => Ok(()),
"bytes" => bad("bytes"),
_ => Ok(()),
}
}
fn type_of(p: &Json) -> Type {
match p["type"].as_str() {
Some("string") => Type::String,
@@ -340,4 +530,37 @@ mod tests {
}
assert_eq!(hints("com.atproto.sync.subscribeRepos"), None);
}
#[test]
fn params_are_typed_and_checked() {
let m = method("com.atproto.repo.listRecords").unwrap();
let p = m.parse_params([("repo", "alice.test"), ("collection", "com.example.note"), ("reverse", "true"), ("x", "y")]).unwrap();
assert_eq!(p, json!({ "repo": "alice.test", "collection": "com.example.note", "reverse": true, "limit": 50 }).as_object().unwrap().clone());
let list = |extra: (&'static str, &'static str)| m.parse_params([("repo", "alice.test"), ("collection", "com.example.note"), extra]);
assert_eq!(list(("limit", "+5")).unwrap()["limit"], 5);
for bad in [("limit", "0"), ("limit", "101"), ("limit", "x"), ("reverse", "yes"), ("collection", "not an nsid")] {
assert!(m.parse_params([("repo", "alice.test"), bad, ("collection", "com.example.note")]).is_err(), "{bad:?}");
}
assert!(m.parse_params([("repo", "alice.test")]).is_err());
let get_repo = method("com.atproto.sync.getRepo").unwrap();
assert!(get_repo.parse_params([("did", "did:plc:abc"), ("since", "notarev")]).is_err());
assert!(get_repo.parse_params([("did", "did:plc:abc"), ("since", "3jzfcijpj2z2a")]).is_ok());
}
#[test]
fn input_is_checked() {
let m = method("com.atproto.repo.applyWrites").unwrap();
let write = |t: &str, rkey: &str| json!({ "repo": "alice.test", "writes": [{ "$type": t, "collection": "com.example.note", "rkey": rkey }] });
m.check_input(&write("com.atproto.repo.applyWrites#delete", "a")).unwrap();
assert!(m.check_input(&write("com.atproto.repo.applyWrites#delete", "a b")).is_err());
assert!(m.check_input(&write("com.atproto.repo.applyWrites#nope", "a")).is_err());
assert!(m.check_input(&write("com.atproto.repo.applyWrites#create", "a")).is_err(), "a create needs its value");
let put = method("com.atproto.repo.putRecord").unwrap();
let body = json!({ "repo": "alice.test", "collection": "com.example.note", "rkey": "a", "record": {}, "swapRecord": null });
put.check_input(&body).unwrap();
let del = method("com.atproto.repo.deleteRecord").unwrap();
assert!(del.check_input(&json!({ "repo": "alice.test", "collection": "com.example.note", "rkey": "a", "swapRecord": null })).is_err());
assert!(put.check_input(&json!({ "repo": "alice.test", "collection": "com.example.note", "rkey": "a", "record": 5 })).is_err());
assert!(put.check_input(&json!({ "repo": "alice.test", "collection": "com.example.note", "rkey": "x".repeat(513), "record": {} })).is_err());
}
}
crates/pds-lexicon/Cargo.toml+1−0
@@ -5,4 +5,5 @@ edition.workspace = true
publish.workspace = true
[dependencies]
pds-repo.workspace = true
serde_json.workspace = true
crates/pds-repo/src/data.rs+116−0
@@ -89,6 +89,30 @@ pub fn parse_cid(s: &str) -> Option<Vec<u8>> {
}
}
/// Whether `s` is a CID as text: version 0 in base58, or version 1 in base32
/// whose multihash is as long as it says.
pub fn valid_cid_string(s: &str) -> bool {
const B58: &[u8] = b"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
if s.len() == 46 && s.starts_with("Qm") {
return s.bytes().all(|c| B58.contains(&c));
}
fn varint(rest: &mut &[u8]) -> Option<u64> {
let mut n = 0;
for i in 0..9 {
let (&b, tail) = rest.split_first()?;
*rest = tail;
n |= u64::from(b & 0x7f) << (7 * i);
if b < 0x80 {
return Some(n);
}
}
None
}
let Some(bytes) = s.strip_prefix('b').and_then(base32_decode) else { return false };
let rest = &mut bytes.as_slice();
matches!((varint(rest), varint(rest), varint(rest), varint(rest)), (Some(1), Some(_), Some(_), Some(len)) if rest.len() as u64 == len)
}
// ---- DAG-CBOR --------------------------------------------------------------
fn head(out: &mut Vec<u8>, major: u8, n: u64) {
@@ -159,6 +183,57 @@ fn enc(v: &V, out: &mut Vec<u8>) {
}
}
/// Decode one DAG-CBOR value that is all of `data`: what `encode` writes.
pub fn decode(data: &[u8]) -> Result<V, String> {
let mut pos = 0;
let v = dec(data, &mut pos, 0)?;
if pos == data.len() { Ok(v) } else { Err("bytes after the value".into()) }
}
fn take<'a>(data: &'a [u8], pos: &mut usize, n: usize) -> Result<&'a [u8], String> {
let s = data.get(*pos..pos.saturating_add(n)).ok_or("the value is cut short")?;
*pos += n;
Ok(s)
}
fn dec(d: &[u8], pos: &mut usize, depth: usize) -> Result<V, String> {
if depth > 128 {
return Err("nested too deep".into());
}
let first = take(d, pos, 1)?[0];
let (major, info) = (first >> 5, first & 31);
let n = match info {
0..=23 => u64::from(info),
24..=27 => take(d, pos, 1 << (info - 24))?.iter().fold(0, |n, &b| (n << 8) | u64::from(b)),
_ => return Err(format!("unsupported CBOR head {first:#x}")),
};
let int = || i64::try_from(n).map_err(|_| "integer out of range".to_string());
let len = || usize::try_from(n).map_err(|_| "length out of range".to_string());
Ok(match (major, n) {
(0, _) => V::Int(int()?),
(1, _) => V::Int(-1 - int()?),
(2, _) => V::Bytes(take(d, pos, len()?)?.to_vec()),
(3, _) => V::Str(String::from_utf8(take(d, pos, len()?)?.to_vec()).map_err(|_| "a string that is not UTF-8")?),
(4, _) => V::Arr((0..n).map(|_| dec(d, pos, depth + 1)).collect::<Result<_, _>>()?),
(5, _) => {
let mut m = Vec::new();
for _ in 0..n {
let V::Str(k) = dec(d, pos, depth + 1)? else { return Err("a map key that is not a string".into()) };
m.push((k, dec(d, pos, depth + 1)?));
}
V::Map(m)
}
(6, 42) => match dec(d, pos, depth + 1)? {
V::Bytes(b) if b.first() == Some(&0) => V::Link(b[1..].to_vec()),
_ => return Err("a link that is not a CID".into()),
},
(7, 20) => V::Bool(false),
(7, 21) => V::Bool(true),
(7, 22) => V::Null,
_ => return Err(format!("unsupported CBOR head {first:#x}")),
})
}
// ---- JSON <-> values -------------------------------------------------------
/// Convert JSON to the data model, rejecting what the model does not allow.
@@ -258,6 +333,35 @@ pub fn valid_rkey(s: &str) -> bool {
&& s.bytes().all(|c| c.is_ascii_alphanumeric() || b".-_:~".contains(&c))
}
/// Whether `s` is a DID: `did:`, a lowercase method, then its identifier (`atproto/did.md`).
pub fn valid_did(s: &str) -> bool {
let Some((method, id)) = s.strip_prefix("did:").and_then(|r| r.split_once(':')) else { return false };
s.len() <= 2048
&& !method.is_empty()
&& method.bytes().all(|c| c.is_ascii_lowercase())
&& !id.is_empty()
&& id.bytes().all(|c| c.is_ascii_alphanumeric() || b"._:%-".contains(&c))
&& !id.ends_with([':', '%'])
}
/// Whether `s` is a handle: a hostname of two or more labels whose last does
/// not start with a digit (`atproto/handle.md`).
pub fn valid_handle(s: &str) -> bool {
let label = |l: &str| {
let b = l.as_bytes();
(1..=63).contains(&b.len())
&& b[0].is_ascii_alphanumeric()
&& b[b.len() - 1].is_ascii_alphanumeric()
&& b.iter().all(|c| c.is_ascii_alphanumeric() || *c == b'-')
};
s.len() <= 253 && s.split('.').count() >= 2 && s.split('.').all(label) && !s.rsplit('.').next().is_some_and(|l| l.starts_with(|c: char| c.is_ascii_digit()))
}
/// Whether `s` is an at-identifier: a DID or a handle.
pub fn valid_at_identifier(s: &str) -> bool {
valid_did(s) || valid_handle(s)
}
#[cfg(test)]
mod tests {
use super::*;
@@ -272,9 +376,21 @@ mod tests {
assert_eq!(B64.encode(&cbor), f["cbor_base64"].as_str().unwrap().trim_end_matches('='));
assert_eq!(cid_string(&cid_of(0x71, &cbor)), f["cid"].as_str().unwrap());
assert_eq!(to_json(&v), f["json"]);
assert_eq!(encode(&decode(&cbor).unwrap()), cbor);
}
}
#[test]
fn syntax() {
assert!(valid_did("did:plc:aaaaaaaaaaaaaaaaaaaaaaaa") && valid_did("did:web:example.com"));
assert!(!valid_did("did:PLC:abc") && !valid_did("did:plc:") && !valid_did("plc:abc") && !valid_did("did:plc:abc:"));
assert!(valid_handle("alice.test") && valid_handle("a.b-c.example"));
assert!(!valid_handle("alice") && !valid_handle("alice.3com") && !valid_handle("-a.test") && !valid_handle("a..test"));
let cid = cid_string(&cid_of(0x71, b"x"));
assert!(valid_cid_string(&cid) && valid_cid_string("QmYwAPJzv5CZsnA625s3Xf2nemtYgPpHdWEz79ojWnPbdG"));
assert!(!valid_cid_string(&cid[..cid.len() - 2]) && !valid_cid_string("bafy") && !valid_cid_string("not a cid"));
}
#[test]
fn invalid() {
let text = std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/../../spec/interop/data-model/data-model-invalid.json")).unwrap();
crates/pds-repo/src/lib.rs+95−98
@@ -12,14 +12,15 @@ use sha2::{Digest, Sha256};
use std::collections::{BTreeMap, HashMap, HashSet};
use std::time::{SystemTime, UNIX_EPOCH};
pub struct ApiErr {
pub status: u16,
pub name: &'static str,
pub message: String,
}
pub fn err<T>(status: u16, name: &'static str, message: impl Into<String>) -> Result<T, ApiErr> {
Err(ApiErr { status, name, message: message.into() })
/// Why the repository refused writes.
#[derive(Debug, PartialEq, Eq)]
pub enum Refused {
/// `swapCommit` named a commit other than the latest.
StaleCommit,
/// A create of a record that exists, by path.
Exists(String),
/// An update or delete of a record that does not exist, by path.
Missing(String),
}
const TID_CHARS: &[u8; 32] = b"234567abcdefghijklmnopqrstuvwxyz";
@@ -41,7 +42,7 @@ impl Tids {
}
pub fn next(&mut self) -> String {
let micros = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_micros() as u64;
let micros = SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default().as_micros() as u64;
let t = ((micros << 10) | self.clock).max(self.last + 1);
self.last = t;
(0..13).rev().map(|i| TID_CHARS[((t >> (i * 5)) & 31) as usize] as char).collect()
@@ -88,7 +89,8 @@ pub struct Change {
pub since: Option<String>,
pub prev_data: Option<Vec<u8>>,
pub ops: Vec<EvOp>,
/// The tree blocks the event carries besides the commit.
/// The blocks the event carries besides the commit: tree nodes, then the
/// records the ops wrote, each in CID order.
pub blocks: Vec<Block>,
/// The CIDs of the blocks, records and tree nodes, that the repository
/// holds after this commit and did not before.
@@ -99,10 +101,10 @@ pub struct Repo {
pub did: String,
key: SigningKey,
pub records: BTreeMap<String, Record>,
/// Empty until the first commit.
pub rev: String,
pub head: Vec<u8>,
head_bytes: Vec<u8>,
blocks: Vec<Block>,
tree: mst::Node,
pub tids: Tids,
pub change: Option<Change>,
@@ -112,42 +114,46 @@ pub struct Repo {
}
impl Repo {
/// A repository with no commit yet: `init` makes its first, or `load`
/// and `finish_load` replay its log.
pub fn new(did: String, key: SigningKey) -> Self {
let mut r = Repo {
Repo {
did,
key,
records: BTreeMap::new(),
rev: String::new(),
head: vec![],
head_bytes: vec![],
blocks: vec![],
tree: mst::build_tree(&[]),
tids: Tids::new(),
change: None,
held: HashMap::new(),
};
r.commit();
r
}
}
/// The first commit of a new repository: the empty tree.
pub fn init(&mut self) -> Change {
self.commit(vec![])
}
pub fn head_string(&self) -> String {
cid_string(&self.head)
}
/// Rebuild the tree and sign a new commit over it.
fn commit(&mut self) {
let entries: Vec<(Vec<u8>, Vec<u8>)> =
self.records.iter().map(|(k, r)| (k.as_bytes().to_vec(), r.cid.clone())).collect();
let old: HashSet<Vec<u8>> = self.blocks.iter().map(|b| b.0.clone()).collect();
/// The tree's `(key, record cid)` pairs, in key order.
fn entries(&self) -> Vec<(Vec<u8>, Vec<u8>)> {
self.records.iter().map(|(k, r)| (k.as_bytes().to_vec(), r.cid.clone())).collect()
}
/// Rebuild the tree and sign a new commit over it, for these ops.
fn commit(&mut self, ops: Vec<EvOp>) -> Change {
let tree = mst::build_tree(&self.entries());
let first = self.rev.is_empty();
let tree = mst::build_tree(&entries);
let root = tree.cid.clone();
let blocks: Vec<Block> = tree.nodes().into_iter().map(|n| (n.cid.clone(), n.bytes.clone())).collect();
let fresh = blocks.iter().filter(|b| !old.contains(&b.0)).cloned().collect();
let rev = self.tids.next();
let mut held = HashMap::with_capacity(blocks.len() + self.records.len());
let nodes = tree.nodes();
let mut held = HashMap::with_capacity(nodes.len() + self.records.len());
let mut added = Vec::new();
for cid in blocks.iter().map(|b| &b.0).chain(self.records.values().map(|r| &r.cid)) {
for cid in nodes.iter().map(|n| &n.cid).chain(self.records.values().map(|r| &r.cid)) {
if held.contains_key(cid) {
continue;
}
@@ -160,11 +166,20 @@ impl Repo {
};
held.insert(cid.clone(), since);
}
let before = (!first).then_some(&self.tree);
let mut blocks: Vec<Block> = mst::event_nodes(before, &tree, ops.iter().map(|o| o.path.as_bytes()))
.into_iter()
.map(|n| (n.cid.clone(), n.bytes.clone()))
.collect();
let mut records: Vec<Block> = ops.iter().filter_map(|o| o.block.clone()).collect();
records.sort();
records.dedup_by(|a, b| a.0 == b.0);
blocks.extend(records);
let unsigned = |sig: Option<Vec<u8>>| {
let mut m = vec![
("did".to_string(), V::Str(self.did.clone())),
("version".to_string(), V::Int(3)),
("data".to_string(), V::Link(root.clone())),
("data".to_string(), V::Link(tree.cid.clone())),
("rev".to_string(), V::Str(rev.clone())),
("prev".to_string(), V::Null),
];
@@ -174,30 +189,32 @@ impl Repo {
V::Map(m)
};
let hash = Sha256::digest(encode(&unsigned(None)));
let sig: k256::ecdsa::Signature = self.key.sign_prehash(&hash).expect("signing");
let sig: k256::ecdsa::Signature = self.key.sign_prehash(&hash).expect("signing a 32-byte digest");
let sig = sig.normalize_s().unwrap_or(sig);
let bytes = encode(&unsigned(Some(sig.to_bytes().to_vec())));
self.head = cid_of(0x71, &bytes);
self.change = Some(Change {
drop(nodes);
let change = Change {
rev: rev.clone(),
head_bytes: bytes.clone(),
since: (!first).then(|| self.rev.clone()),
prev_data: (!first).then(|| self.tree.cid.clone()),
blocks: fresh,
ops,
blocks,
added,
..Default::default()
});
};
self.head = cid_of(0x71, &bytes);
self.held = held;
self.head_bytes = bytes;
self.blocks = blocks;
self.tree = tree;
self.rev = rev;
change
}
/// Replay a logged change to the records; `finish_load` then rebuilds the tree.
pub fn load(&mut self, c: &Change) -> Result<(), String> {
for (path, j) in &c.puts {
self.records.insert(path.clone(), make_record(from_json(j)?));
self.records.insert(path.clone(), make_record(from_json(j).map_err(|e| format!("record {path}: {e}"))?));
}
for path in &c.dels {
self.records.remove(path);
@@ -210,17 +227,28 @@ impl Repo {
Ok(())
}
pub fn finish_load(&mut self) {
let entries: Vec<(Vec<u8>, Vec<u8>)> =
self.records.iter().map(|(k, r)| (k.as_bytes().to_vec(), r.cid.clone())).collect();
self.tree = mst::build_tree(&entries);
self.blocks = self.tree.nodes().into_iter().map(|n| (n.cid.clone(), n.bytes.clone())).collect();
/// Rebuild the tree from the replayed records, and check it is the one the
/// latest commit signed.
pub fn finish_load(&mut self) -> Result<(), String> {
self.tree = mst::build_tree(&self.entries());
let commit = decode(&self.head_bytes).map_err(|e| format!("the latest commit: {e}"))?;
let field = |k: &str| match &commit {
V::Map(m) => m.iter().find(|(n, _)| n == k).map(|(_, v)| v),
_ => None,
};
if field("data") != Some(&V::Link(self.tree.cid.clone())) {
return Err(format!("the records make the tree {}, which the latest commit does not sign", cid_string(&self.tree.cid)));
}
if field("rev") != Some(&V::Str(self.rev.clone())) {
return Err(format!("the latest commit is not rev {}", self.rev));
}
let current: HashSet<&[u8]> =
self.blocks.iter().map(|b| b.0.as_slice()).chain(self.records.values().map(|r| r.cid.as_slice())).collect();
self.tree.nodes().into_iter().map(|n| n.cid.as_slice()).chain(self.records.values().map(|r| r.cid.as_slice())).collect();
self.held.retain(|cid, _| current.contains(cid.as_slice()));
self.head = cid_of(0x71, &self.head_bytes);
self.tids.after(&self.rev);
self.change = None;
Ok(())
}
pub fn uri(&self, collection: &str, rkey: &str) -> String {
@@ -228,61 +256,31 @@ impl Repo {
}
/// Apply writes as one commit, all or nothing.
pub fn apply(&mut self, ops: Vec<Op>, swap_commit: Option<&str>) -> Result<Vec<OpResult>, ApiErr> {
if let Some(s) = swap_commit {
if s != self.head_string() {
return err(400, "InvalidSwap", "Commit was at a different CID");
}
pub fn apply(&mut self, ops: Vec<Op>, swap_commit: Option<&str>) -> Result<Vec<OpResult>, Refused> {
if swap_commit.is_some_and(|s| s != self.head_string()) {
return Err(Refused::StaleCommit);
}
let mut originals: BTreeMap<String, Option<Record>> = BTreeMap::new();
let mut results = Vec::new();
let mut evops = Vec::new();
let mut failure = None;
for op in ops {
let r = self.apply_one(op, &mut originals, &mut evops);
match r {
match self.apply_one(op, &mut originals, &mut evops) {
Ok(x) => results.push(x),
Err(e) => {
failure = Some(e);
break;
}
}
}
if let Some(e) = failure {
for (k, old) in originals {
match old {
Some(r) => self.records.insert(k, r),
None => self.records.remove(&k),
};
}
return Err(e);
}
self.commit();
let puts = originals.keys().filter_map(|k| self.records.get(k).map(|r| (k.clone(), to_json(&r.value)))).collect();
let dels = originals.keys().filter(|k| !self.records.contains_key(*k)).cloned().collect();
let mut context = Vec::new();
for o in &evops {
self.tree.context(o.path.as_bytes(), &mut context);
}
if let Some(c) = &mut self.change {
c.puts = puts;
c.dels = dels;
c.ops = evops;
let mut have: HashSet<Vec<u8>> = c.blocks.iter().map(|b| b.0.clone()).collect();
for n in context {
if have.insert(n.cid.clone()) {
c.blocks.push((n.cid.clone(), n.bytes.clone()));
}
}
// Every record an op wrote travels with the diff.
for o in &c.ops {
if let Some((cid, bytes)) = &o.block {
if have.insert(cid.clone()) {
c.blocks.push((cid.clone(), bytes.clone()));
for (k, old) in originals {
match old {
Some(r) => self.records.insert(k, r),
None => self.records.remove(&k),
};
}
return Err(e);
}
}
}
let mut change = self.commit(evops);
change.puts = originals.keys().filter_map(|k| self.records.get(k).map(|r| (k.clone(), to_json(&r.value)))).collect();
change.dels = originals.keys().filter(|k| !self.records.contains_key(*k)).cloned().collect();
self.change = Some(change);
Ok(results)
}
@@ -291,18 +289,18 @@ impl Repo {
op: Op,
originals: &mut BTreeMap<String, Option<Record>>,
evops: &mut Vec<EvOp>,
) -> Result<OpResult, ApiErr> {
) -> Result<OpResult, Refused> {
let prev_of = |o: &Option<Record>| o.as_ref().map(|r| r.cid.clone());
match op {
Op::Create { collection, rkey, value } => {
let rkey = rkey.unwrap_or_else(|| self.tids.next());
let path = format!("{collection}/{rkey}");
if self.records.contains_key(&path) {
return err(500, "InternalServerError", "Internal Server Error");
return Err(Refused::Exists(path));
}
let rec = make_record(value);
let cid = cid_string(&rec.cid);
originals.entry(path.clone()).or_insert(None);
let prev = originals[&path].as_ref().map(|r| r.cid.clone());
let prev = prev_of(originals.entry(path.clone()).or_insert(None));
evops.push(EvOp { action: "create", path: path.clone(), cid: Some(rec.cid.clone()), prev, block: Some((rec.cid.clone(), rec.bytes.clone())) });
self.records.insert(path, rec);
Ok(OpResult::Create { uri: self.uri(&collection, &rkey), cid })
@@ -310,24 +308,23 @@ impl Repo {
Op::Update { collection, rkey, value } => {
let path = format!("{collection}/{rkey}");
if !self.records.contains_key(&path) {
return err(500, "InternalServerError", "Internal Server Error");
return Err(Refused::Missing(path));
}
let rec = make_record(value);
let cid = cid_string(&rec.cid);
let block = Some((rec.cid.clone(), rec.bytes.clone()));
evops.push(EvOp { action: "update", path: path.clone(), cid: Some(rec.cid.clone()), prev: None, block });
let rec_cid = rec.cid.clone();
let old = self.records.insert(path.clone(), rec);
originals.entry(path.clone()).or_insert(old);
evops.last_mut().unwrap().prev = originals[&path].as_ref().map(|r| r.cid.clone());
let prev = prev_of(originals.entry(path.clone()).or_insert(old));
evops.push(EvOp { action: "update", path, cid: Some(rec_cid), prev, block });
Ok(OpResult::Update { uri: self.uri(&collection, &rkey), cid })
}
Op::Delete { collection, rkey } => {
let path = format!("{collection}/{rkey}");
let Some(old) = self.records.remove(&path) else {
return err(500, "InternalServerError", "Internal Server Error");
return Err(Refused::Missing(path));
};
originals.entry(path.clone()).or_insert(Some(old));
let prev = originals[&path].as_ref().map(|r| r.cid.clone());
let prev = prev_of(originals.entry(path.clone()).or_insert(Some(old)));
evops.push(EvOp { action: "delete", path, cid: None, prev, block: None });
Ok(OpResult::Delete)
}
@@ -337,7 +334,7 @@ impl Repo {
/// The whole repository as a CAR file.
pub fn car(&self) -> Vec<u8> {
let mut blocks: Vec<(&[u8], &[u8])> = vec![(&self.head, &self.head_bytes)];
blocks.extend(self.blocks.iter().map(|(c, d)| (c.as_slice(), d.as_slice())));
blocks.extend(self.tree.nodes().into_iter().map(|n| (n.cid.as_slice(), n.bytes.as_slice())));
blocks.extend(self.records.values().map(|r| (r.cid.as_slice(), r.bytes.as_slice())));
car_file(&self.head, blocks)
}
@@ -351,7 +348,7 @@ impl Repo {
if self.rev.as_str() > since {
blocks.push((&self.head, &self.head_bytes));
}
blocks.extend(self.blocks.iter().filter(|(c, _)| after(c)).map(|(c, d)| (c.as_slice(), d.as_slice())));
blocks.extend(self.tree.nodes().into_iter().filter(|n| after(&n.cid)).map(|n| (n.cid.as_slice(), n.bytes.as_slice())));
let mut seen = HashSet::new();
blocks.extend(
self.records
crates/pds-repo/src/mst.rs+45−0
@@ -2,6 +2,7 @@
use crate::data::{V, cid_of, encode};
use sha2::{Digest, Sha256};
use std::collections::HashSet;
pub type Block = (Vec<u8>, Vec<u8>);
@@ -90,6 +91,20 @@ impl Node {
}
}
/// The tree nodes a commit's `#commit` event carries, in CID order: those of
/// `after` that `before` lacks (all of them for a first commit, which has no
/// `before`), and the context of each key the commit wrote.
pub fn event_nodes<'a, 'k>(before: Option<&Node>, after: &'a Node, keys: impl IntoIterator<Item = &'k [u8]>) -> Vec<&'a Node> {
let old: HashSet<&[u8]> = before.map(|b| b.nodes().into_iter().map(|n| n.cid.as_slice()).collect()).unwrap_or_default();
let mut out: Vec<&Node> = after.nodes().into_iter().filter(|n| !old.contains(n.cid.as_slice())).collect();
for k in keys {
after.context(k, &mut out);
}
out.sort_by(|a, b| a.cid.cmp(&b.cid));
out.dedup_by(|a, b| a.cid == b.cid);
out
}
/// Build the tree for sorted `(key, record cid)` pairs. Returns its root; an
/// empty repository is a single empty node.
pub fn build_tree(entries: &[(Vec<u8>, Vec<u8>)]) -> Node {
@@ -149,4 +164,34 @@ mod tests {
assert_eq!(depth(c["key"].as_str().unwrap().as_bytes()), c["height"].as_u64().unwrap() as usize, "{}", c["key"]);
}
}
/// The fixtures' trees, before and after each commit, and every block a
/// proof of its ops needs among the nodes its event carries.
#[test]
fn commit_proofs() {
use crate::data::{cid_string, parse_cid};
let text = std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/../../spec/interop/firehose/commit-proof-fixtures.json")).unwrap();
let cases: Vec<serde_json::Value> = serde_json::from_str(&text).unwrap();
assert!(!cases.is_empty());
for c in cases {
let leaf = parse_cid(c["leafValue"].as_str().unwrap()).unwrap();
let strs = |k: &str| c[k].as_array().unwrap().iter().map(|v| v.as_str().unwrap().to_string()).collect::<Vec<_>>();
let (keys, adds, dels) = (strs("keys"), strs("adds"), strs("dels"));
let tree = |ks: Vec<&String>| {
let mut e: Vec<(Vec<u8>, Vec<u8>)> = ks.into_iter().map(|k| (k.as_bytes().to_vec(), leaf.clone())).collect();
e.sort();
build_tree(&e)
};
let before = tree(keys.iter().collect());
let after = tree(keys.iter().filter(|k| !dels.contains(k)).chain(&adds).collect());
assert_eq!(cid_string(&before.cid), c["rootBeforeCommit"], "{}", c["comment"]);
assert_eq!(cid_string(&after.cid), c["rootAfterCommit"], "{}", c["comment"]);
let carried = event_nodes(Some(&before), &after, adds.iter().chain(&dels).map(|k| k.as_bytes()));
assert!(carried.windows(2).all(|w| w[0].cid < w[1].cid), "{}: in CID order", c["comment"]);
let carried: HashSet<String> = carried.iter().map(|n| cid_string(&n.cid)).collect();
for b in strs("blocksInProof") {
assert!(carried.contains(&b), "{}: {b} missing from the event", c["comment"]);
}
}
}
}
crates/pds-server/src/events.rs+9−8
@@ -1,19 +1,19 @@
//! The firehose: `com.atproto.sync.subscribeRepos` events and the WebSocket that serves them.
use pds_repo::data::*;
use pds_repo::{Change, car_file};
use crate::Shared;
use axum::body::Bytes;
use axum::extract::ws::rejection::WebSocketUpgradeRejection;
use axum::extract::ws::{Message, WebSocket, WebSocketUpgrade};
use axum::extract::{Query, State};
use axum::extract::ws::rejection::WebSocketUpgradeRejection;
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
use std::sync::Arc;
use pds_repo::data::*;
use pds_repo::{Change, car_file};
use std::time::{SystemTime, UNIX_EPOCH};
/// The current time as an atproto datetime, in UTC to the millisecond.
pub fn timestamp() -> String {
let ms = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_millis() as i64;
let ms = SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default().as_millis() as i64;
let (days, rem) = (ms.div_euclid(86_400_000), ms.rem_euclid(86_400_000));
// Civil date from days since 1970-01-01.
let z = days + 719_468;
@@ -130,7 +130,7 @@ pub async fn subscribe(
/// as it reaches the disk.
async fn stream(st: Shared, cursor: Option<Result<u64, std::num::ParseIntError>>, mut socket: WebSocket) {
let start = {
let s = st.lock().unwrap();
let s = st.read().await;
let rx = s.published.subscribe();
let last = *rx.borrow();
match cursor {
@@ -146,10 +146,11 @@ async fn stream(st: Shared, cursor: Option<Result<u64, std::num::ParseIntError>>
};
loop {
let upto = *rx.borrow_and_update();
let batch: Vec<Arc<Vec<u8>>> = st.lock().unwrap().events[pos..upto].to_vec();
// Shared with the server's copy: a send copies no frame.
let batch: Vec<Bytes> = st.read().await.events.get(pos..upto).map_or_else(Vec::new, <[Bytes]>::to_vec);
pos = upto;
for frame in batch {
if socket.send(Message::Binary(frame.to_vec().into())).await.is_err() {
if socket.send(Message::Binary(frame)).await.is_err() {
return;
}
}
crates/pds-server/src/lib.rs+381−311
692 lines changed: not loaded until asked for.
crates/pds-server/src/mcp.rs+19−21
@@ -3,7 +3,7 @@
//! `tools/call`. Each method with a JSON answer is a tool (`spec/COMMANDS.md`),
//! called through the same handling as XRPC.
use crate::{Resp, Shared, bearer, locked, serve};
use crate::{Call, Resp, Shared, answer, bearer};
use axum::body::Bytes;
use axum::extract::State;
use axum::http::{HeaderMap, HeaderValue, Method, StatusCode, header};
@@ -238,29 +238,27 @@ async fn call_tool(st: &Shared, name: &str, arguments: Option<&Json>, token: Opt
Some(Json::Object(a)) => a.clone(),
Some(_) => return Err(rpc_err(StatusCode::OK, INVALID_PARAMS, "arguments must be an object")),
};
let result = locked(st, |s| {
for a in m.args.iter().filter(|a| a.names_account()) {
args.entry(a.name.clone()).or_insert_with(|| json!(s.did));
}
match m.kind {
Kind::Query => {
let mut params = Vec::new();
for (k, v) in &args {
match v {
Json::Null => {}
Json::Array(items) => params.extend(items.iter().map(|i| (k.clone(), param_text(i)))),
v => params.push((k.clone(), param_text(v))),
}
}
serve(s, &m.nsid, &Method::GET, &params, &[], token)
let did = st.read().await.did.clone();
for a in m.args.iter().filter(|a| a.names_account()) {
args.entry(a.name.clone()).or_insert_with(|| json!(did));
}
let (method, mut params, mut body) = (if m.kind == Kind::Query { Method::GET } else { Method::POST }, Vec::new(), String::new());
if m.kind == Kind::Query {
for (k, v) in &args {
match v {
Json::Null => {}
Json::Array(items) => params.extend(items.iter().map(|i| (k.clone(), param_text(i)))),
v => params.push((k.clone(), param_text(v))),
}
_ => serve(s, &m.nsid, &Method::POST, &[], Json::Object(args).to_string().as_bytes(), token),
}
})
.await;
let (content, is_error) = match result {
} else {
body = Json::Object(args).to_string();
}
let call = Call { nsid: &m.nsid, method: &method, params: &params, body: body.as_bytes(), bearer: token.as_deref() };
let (content, is_error) = match answer(st, &call).await {
Ok(Resp::Json(j)) => (j, false),
Ok(Resp::Car(_)) => unreachable!("a tool's method answers JSON"),
// No method with a tool answers anything but JSON.
Ok(Resp::Car(_)) => (json!({ "error": "InternalServerError", "message": "a tool's method answered a CAR file" }), true),
Err(e) => (json!({ "error": e.name, "message": e.message }), true),
};
Ok(json!({
crates/pds-store/src/lib.rs+12−3
@@ -57,8 +57,10 @@ pub struct Wal {
file: File,
/// Frames handed to the operating system.
written: AtomicU64,
/// Frames known to be on disk.
/// Frames known to be on disk; the lock is held through each fsync.
synced: Mutex<u64>,
/// The same count, to read without waiting for an fsync in progress.
durable: AtomicU64,
}
impl Wal {
@@ -78,7 +80,7 @@ impl Wal {
if !existed {
File::open(dir)?.sync_all()?;
}
Ok((Wal { file, written: AtomicU64::new(0), synced: Mutex::new(0) }, frames))
Ok((Wal { file, written: AtomicU64::new(0), synced: Mutex::new(0), durable: AtomicU64::new(0) }, frames))
}
/// Hand a frame to the operating system. Callers must serialise this.
@@ -96,10 +98,16 @@ impl Wal {
self.written.load(Ordering::SeqCst)
}
/// Whether frame `seq` is known to be on disk already.
pub fn is_durable(&self, seq: u64) -> bool {
self.durable.load(Ordering::SeqCst) >= seq
}
/// Return once frame `seq` is on disk. Waiters that queue behind one fsync
/// find their frame covered by it.
pub fn wait(&self, seq: u64) {
let mut synced = self.synced.lock().unwrap();
// A failed fsync aborts, so nothing can panic holding the lock.
let mut synced = self.synced.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
if *synced >= seq {
return;
}
@@ -108,5 +116,6 @@ impl Wal {
std::process::abort();
}
*synced = target;
self.durable.store(target, Ordering::SeqCst);
}
}
harness/compare.mjs+133−20
@@ -204,11 +204,26 @@ await waitReady(server, cand.url)
/// through the method's MCP tool or CLI command instead, answered in the same
/// form.
async function xrpc(side, nsid, request = {}) {
if (COMMANDS && side === cand && chance(0.4)) {
const via = chance(0.5) ? await viaTool(nsid, request) : await viaCommand(nsid, request)
if (via) return via
}
return xrpcHttp(side, nsid, request)
let res
if (COMMANDS && side === cand && chance(0.4)) res = chance(0.5) ? await viaTool(nsid, request) : await viaCommand(nsid, request)
res ??= await xrpcHttp(side, nsid, request)
noteKeys(nsid, request.body, res)
return res
}
const WRITES = ['com.atproto.repo.createRecord', 'com.atproto.repo.putRecord', 'com.atproto.repo.deleteRecord', 'com.atproto.repo.applyWrites']
/// The keys, as `collection/rkey`, that writes named since the last
/// repository check, whether or not they landed, and the record CIDs they
/// answered: what `getRepo since` may have taken out of the tree and put
/// back, or written again.
const written = { keys: new Set(), records: new Set() }
function noteKeys(nsid, body, res) {
if (!WRITES.includes(nsid) || !body || typeof body !== 'object') return
const add = (c, k) => typeof c === 'string' && typeof k === 'string' && written.keys.add(`${c}/${k}`)
const tail = (uri) => (typeof uri === 'string' ? uri.split('/').pop() : undefined)
if (nsid.endsWith('applyWrites')) (Array.isArray(body.writes) ? body.writes : []).forEach((w, i) => add(w?.collection, w?.rkey ?? tail(res?.body?.results?.[i]?.uri)))
else add(body.collection, body.rkey ?? tail(res?.body?.uri))
for (const r of [res?.body, ...(Array.isArray(res?.body?.results) ? res.body.results : [])]) if (typeof r?.cid === 'string') written.records.add(r.cid)
}
async function xrpcHttp(side, nsid, { params, body, token, raw, method } = {}) {
@@ -745,8 +760,8 @@ const NOBODY = 'did:plc:aaaaaaaaaaaaaaaaaaaaaaaa'
/// Requests at the edges of what SLICE.md settles, 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; a method called with the other HTTP method; and
/// writes with `validate` set.
/// of a DID no one holds; arguments their lexicon refuses; a method called
/// with the other HTTP method; and writes with `validate` set.
async function oddRequests() {
const collection = pick(COLLECTIONS)
const bad = chance(0.5)
@@ -758,7 +773,7 @@ async function oddRequests() {
}
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) {
if (r < 0.6 && chance(0.5)) {
const [nsid, params] = pick([
['com.atproto.repo.describeRepo', { repo: NOBODY }],
['com.atproto.sync.getLatestCommit', { did: NOBODY }],
@@ -766,6 +781,28 @@ async function oddRequests() {
])
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)
@@ -1120,6 +1157,43 @@ let lastRev = ''
/// Each side's rev at the last repository check, for `getRepo` with `since`.
const revs = { reference: null, server: null }
/// The CIDs of the MST nodes a write of `key` can change, in a tree whose
/// blocks are `blocks` (by CID string), from `root`, and the record CID at
/// `key` if the tree holds it. They are the nodes a search for it passes
/// through and, where it is found, the edges of the subtrees beside it,
/// which deleting it merges and putting it back splits again.
function search(blocks, root, key) {
const path = []
let cid = root
while (cid && blocks.has(cid)) {
path.push(cid)
const node = cborDecode(blocks.get(cid))
let prev = ''
let next = node.l ? node.l.toString() : null
for (const e of node.e) {
const k = prev.slice(0, e.p) + Buffer.from(e.k).toString('latin1')
prev = k
if (key === k) {
const edge = (c, last) => {
for (; c && blocks.has(c); ) {
path.push(c)
const n = cborDecode(blocks.get(c))
const t = last ? (n.e.length ? n.e.at(-1).t : n.l) : n.l
c = t ? t.toString() : null
}
}
edge(next, true)
edge(e.t ? e.t.toString() : null, false)
return { path, value: e.v.toString() }
}
if (key < k) break
next = e.t ? e.t.toString() : null
}
cid = next
}
return { path, value: null }
}
async function checkRepos() {
const [a, b] = await Promise.all([ref, cand].map((side) => xrpc(side, 'com.atproto.sync.getRepo', { params: { did: side.did }, raw: true })))
if (a.status !== 200) throw new Error(`reference getRepo: ${JSON.stringify(a.body)}`)
@@ -1144,9 +1218,20 @@ async function checkRepos() {
if (latest.status !== 200 || latest.body.cid !== ours.root.toString() || latest.body.rev !== ourCommit.rev) {
await differ('com.atproto.sync.getLatestCommit', {}, { cid: ours.root.toString(), rev: ourCommit.rev }, latest.body)
}
if (revs.server && chance(0.3)) await checkSince(theirCommit.rev, ourCommit.rev, theirs.root.toString(), ours.root.toString())
// The current tree's blocks, the same on both sides: their roots are equal.
const tree = new Set()
theirs.blocks.forEach((_, cid) => { if (!cid.equals(theirs.root)) tree.add(cid.toString()) })
const current = { data: theirCommit.data.toString(), blocks: new Map() }
theirs.blocks.forEach((bytes, cid) => current.blocks.set(cid.toString(), bytes))
if (revs.server && chance(0.3)) await checkSince(theirCommit.rev, ourCommit.rev, theirs.root.toString(), ours.root.toString(), tree, current)
revs.reference = theirCommit.rev
revs.server = ourCommit.rev
revs.tree = tree
revs.blocks = new Map()
theirs.blocks.forEach((bytes, cid) => revs.blocks.set(cid.toString(), bytes))
revs.data = theirCommit.data.toString()
written.keys.clear()
written.records.clear()
count('repository check', Boolean(verified))
if (FIREHOSE) {
await checkFirehose()
@@ -1155,10 +1240,13 @@ async function checkRepos() {
}
/// `getRepo` with `since`: a CAR whose root is the latest commit, holding the
/// blocks of the commits after that rev, none if it is the latest. Each side
/// has its own revs, and its own commit blocks, so the two are compared by
/// the records their blocks hold, which are the same records.
async function checkSince(theirHead, ourHead, theirRoot, ourRoot) {
/// blocks of the current tree written after that rev, none if it is the
/// latest. Which blocks were written since depends on the order a side made
/// its commits in, which writes sent at once may change, so each side is held
/// to what does not: every block of the current tree that the tree at the
/// last check lacked must be there; nothing outside the current tree; and
/// nothing that stayed in it untouched by every write since.
async function checkSince(theirHead, ourHead, theirRoot, ourRoot, tree, current) {
const r = rand()
const which = r < 0.25 ? 'latest' : r < 0.35 ? 'bad' : 'last'
const since = which === 'latest' ? { reference: theirHead, server: ourHead } : which === 'bad' ? { reference: 'notarev', server: 'notarev' } : { ...revs }
@@ -1171,12 +1259,9 @@ async function checkSince(theirHead, ourHead, theirRoot, ourRoot) {
}
const read = async (bytes) => {
const car = await readCarWithRoot(bytes)
const recs = []
car.blocks.forEach((data, cid) => {
const v = cborDecode(data)
if (v && typeof v.$type === 'string') recs.push(cid.toString())
})
return { root: car.root.toString(), blocks: car.blocks.size, records: recs.sort() }
const held = new Set()
car.blocks.forEach((_, cid) => { if (!cid.equals(car.root)) held.add(cid.toString()) })
return { root: car.root.toString(), blocks: car.blocks.size, held }
}
let theirsSince, oursSince
try {
@@ -1188,7 +1273,35 @@ async function checkSince(theirHead, ourHead, theirRoot, ourRoot) {
if (oursSince.root !== ourRoot) await differ('com.atproto.sync.getRepo', request, `the latest commit, ${ourRoot}, as root`, oursSince.root)
if (theirsSince.root !== theirRoot) throw new Error(`the reference's getRepo since has root ${theirsSince.root}, not ${theirRoot}`)
if (which === 'latest' && oursSince.blocks !== 0) await differ('com.atproto.sync.getRepo', request, 'no blocks', `${oursSince.blocks} blocks`)
if (!isDeepStrictEqual(theirsSince.records, oursSince.records)) await differ('com.atproto.sync.getRepo', request, { records: theirsSince.records }, { records: oursSince.records }, 'the records written since')
if (which === 'last') {
const need = [...tree].filter((c) => !revs.tree.has(c))
// A block in both trees may be there only if a write since touched it: a
// node on the path of a key written since, that key's record, or a record
// a write since answered, which another key may hold too. Only such a
// block can have been taken out and put back, or written again.
const blocks = new Map(current.blocks)
revs.blocks.forEach((bytes, cid) => blocks.has(cid) || blocks.set(cid, bytes))
const touched = new Set(written.records)
for (const key of written.keys) {
for (const root of [current.data, revs.data]) {
const { path, value } = search(blocks, root, key)
path.forEach((c) => touched.add(c))
if (value) touched.add(value)
}
}
const judge = (s) => ({
missing: need.filter((c) => !s.held.has(c)),
outside: [...s.held].filter((c) => !tree.has(c)),
unchanged: [...s.held].filter((c) => revs.tree.has(c) && tree.has(c) && !touched.has(c)),
})
const [t, o] = [judge(theirsSince), judge(oursSince)]
// The reference holds to the rule too, which checks the rule.
if (t.missing.length || t.outside.length || t.unchanged.length) {
const show = (c) => ({ cid: c, block: cborDecode(blocks.get(c)), holders: [...records].filter(([, v]) => v === c).map(([k]) => k) })
throw new Error(`the reference's getRepo since breaks the rule it is held to: ${JSON.stringify({ ...t, unchanged: t.unchanged.map(show), keys: [...written.keys], records: [...written.records] }, (_, v) => (v instanceof Uint8Array ? Buffer.from(v).toString('latin1') : v?.['/'] ?? (v?.toString && v.asCID ? v.toString() : v)))}`)
}
if (o.missing.length || o.outside.length || o.unchanged.length) await differ('com.atproto.sync.getRepo', request, 'every block the current tree gained since that rev; none outside it; none that stayed, untouched by any write since', o)
}
count('getRepo since', true)
}
spec/COMMANDS.md+2−1
@@ -14,7 +14,8 @@ still holds.
The server and the CLI are one program, `pds`:
- `pds serve` runs the server, configured by the environment as `SLICE.md`
says.
says. When it cannot start, as when its data does not recover, it exits 1
with why on standard error.
- `pds <group> <command> [flags]` calls a method of a running server, and
`pds`, `pds --help` and `pds <group> --help` list the groups and commands,
each with its lexicon's description.
spec/SLICE.md+23−8
Cargo.lock+1−0