chadtmiller.com/monolith
An atproto PDS
0
0
Operations and the log store: logs, health, metrics, traces, perf gate; bounded disk and start time
.knotless/workflows/gates.yml+14−6
| @@ -1,7 +1,9 @@ | ||
# The gates, as `just gates` runs them: the server's own tests, then every | ||
# harness run of the server against the reference PDS, several at once. On | ||
# every pull into main, so the merge queue waits on them, and on every push | ||
# to main. | ||
# The gates, as `just gates` runs them: the server's own tests, every | ||
# harness run of the server against the reference PDS, several at once, | ||
# and then the performance step, alone. On every pull into main, so the | ||
# merge queue waits on them, and on every push to main. The code gates | ||
# (cargo fmt, clippy, cargo deny, no unsafe code) are not among them: | ||
# `just code` runs them. | ||
# | ||
# Node, the harness's packages and the build are kept between runs. | ||
image: rust:1.98 | ||
| @@ -22,5 +24,11 @@ steps: | ||
run: cargo test | ||
- name: build | ||
run: cargo build --release -p pds | ||
- name: harness | ||
run: cd harness && PATH=/opt/node/bin:$PATH node gates.mjs compare commands | ||
- name: compare | ||
run: cd harness && PATH=/opt/node/bin:$PATH node gates.mjs compare | ||
- name: crash | ||
run: cd harness && PATH=/opt/node/bin:$PATH node gates.mjs crash | ||
- name: commands | ||
run: cd harness && PATH=/opt/node/bin:$PATH node gates.mjs commands | ||
- name: perf | ||
run: cd harness && PATH=/opt/node/bin:$PATH node gates.mjs perf | ||
crates/pds/src/main.rs+3−1
| @@ -4,7 +4,9 @@ const SERVE_HELP: &str = "Usage: pds serve\n\n\ | ||
Run the server, configured by its environment: PDS_PORT, PDS_DATA_DIR, PDS_HOSTNAME,\n\ | ||
PDS_PUBLIC_URL, PDS_HANDLE_DOMAINS, PDS_PLC_URL, PDS_PLC_ROTATION_KEY_HEX and,\n\ | ||
if set, PDS_RECOVERY_DID_KEY; PDS_EMAIL_SMTP_URL and PDS_EMAIL_FROM, both or\n\ | ||
neither; and PDS_DEV_MAIL_DIR, for development only.\n"; | ||
neither; PDS_DEV_MAIL_DIR, for development only; its log, metrics and traces\n\ | ||
by PDS_LOG_LEVEL, PDS_METRICS_PORT and the OTEL_* variables. SIGTERM or\n\ | ||
SIGINT shuts it down.\n"; | ||
| ||
fn main() { | ||
let args: Vec<String> = std::env::args().skip(1).collect(); | ||
crates/pds-repo/src/lib.rs+181−1
| @@ -52,10 +52,20 @@ impl Tids { | ||
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() | ||
tid_string(t) | ||
} | ||
| ||
/// The last TID made, or that `after` was given, as a string: every one | ||
/// made after it is later. | ||
pub fn last(&self) -> String { | ||
tid_string(self.last) | ||
} | ||
} | ||
| ||
fn tid_string(t: u64) -> String { | ||
(0..13).rev().map(|i| TID_CHARS[((t >> (i * 5)) & 31) as usize] as char).collect() | ||
} | ||
| ||
pub struct Record { | ||
pub cid: Vec<u8>, | ||
pub bytes: Vec<u8>, | ||
| @@ -382,6 +392,45 @@ impl Repo { | ||
Ok(()) | ||
} | ||
| ||
/// Every node of its tree, each once, children before parents. | ||
pub fn tree_nodes(&self) -> impl Iterator<Item = (&[u8], &[u8])> { | ||
self.tree.nodes().into_iter().map(|n| (n.cid.as_slice(), n.bytes.as_slice())) | ||
} | ||
| ||
/// Each block of its tree, MST node or record, each once, with the rev of | ||
/// the commit that added it: of a repository with a commit, loaded or made. | ||
pub fn block_revs(&self) -> impl Iterator<Item = (&[u8], &str)> { | ||
self.held.iter().map(|(cid, h)| (cid.as_slice(), h.rev.as_str())) | ||
} | ||
| ||
/// Begin loading from a checkpoint (`spec/STORE.md`): the latest commit, | ||
/// the records of its tree by path, the rev of the commit that added each | ||
/// block of the tree, the rev of the commit that last wrote each record, | ||
/// and the last TID made. The log's changes after it are then `load`ed, | ||
/// and `finish_load` rebuilds the tree and checks it against the latest | ||
/// commit, as for a log replayed from the start. | ||
pub fn load_checkpoint( | ||
&mut self, | ||
head_bytes: Vec<u8>, | ||
records: Vec<(String, Record)>, | ||
revs: HashMap<Vec<u8>, String>, | ||
written: HashMap<String, String>, | ||
tid: &str, | ||
) -> Result<(), String> { | ||
let rev = match decode(&head_bytes).map_err(|e| format!("the latest commit: {e}"))? { | ||
V::Map(m) => m.into_iter().find(|(k, _)| k == "rev").map(|(_, v)| v), | ||
_ => None, | ||
}; | ||
let Some(V::Str(rev)) = rev else { return Err("the latest commit has no rev".into()) }; | ||
self.records = records.into_iter().collect(); | ||
self.written = written; | ||
self.rev = rev; | ||
self.head_bytes = head_bytes; | ||
self.loaded = revs; | ||
self.tids.after(tid); | ||
Ok(()) | ||
} | ||
| ||
pub fn uri(&self, collection: &str, rkey: &str) -> String { | ||
format!("at://{}/{}/{}", self.did, collection, rkey) | ||
} | ||
| @@ -590,6 +639,64 @@ pub fn car_with_roots<'a>(roots: &[&[u8]], blocks: impl IntoIterator<Item = (&'a | ||
out | ||
} | ||
| ||
/// Read a CAR v1 file whole: its roots and its blocks, in order. Err for | ||
/// anything else: a header that is not exactly `{roots, version: 1}` with | ||
/// `roots` a list of links, a section cut short or empty, a CID not version 1 | ||
/// or whose multihash is not as long as it says, or bytes after the last | ||
/// section. Whether each CID is its block's hash is not checked. | ||
pub fn read_car(bytes: &[u8]) -> Result<(Vec<Vec<u8>>, Vec<Block>), String> { | ||
let mut pos = 0; | ||
let header = section(bytes, &mut pos).map_err(|e| format!("the CAR header: {e}"))?; | ||
let roots = match decode(header).map_err(|e| format!("the CAR header: {e}"))? { | ||
V::Map(m) if m.len() == 2 => { | ||
let get = |k: &str| m.iter().find(|(n, _)| n == k).map(|(_, v)| v); | ||
match (get("roots"), get("version")) { | ||
(Some(V::Arr(roots)), Some(V::Int(1))) => roots | ||
.iter() | ||
.map(|r| if let V::Link(l) = r { Ok(l.clone()) } else { Err("a CAR root that is no link".to_string()) }) | ||
.collect::<Result<Vec<_>, _>>()?, | ||
_ => return Err("a CAR header not of version 1 with a list of roots".into()), | ||
} | ||
} | ||
_ => return Err("a CAR header not exactly roots and version".into()), | ||
}; | ||
let mut blocks = Vec::new(); | ||
while pos < bytes.len() { | ||
let at = pos; | ||
let s = section(bytes, &mut pos).map_err(|e| format!("the CAR section at {at}: {e}"))?; | ||
let mut p = 0; | ||
let bad = || format!("the CAR section at {at}: a CID not of version 1, or cut short"); | ||
let [version, _codec, _hash, len] = [(); 4].map(|_| read_varint(s, &mut p)); | ||
let (Some(1), Some(_), Some(_), Some(len)) = (version, _codec, _hash, len) else { return Err(bad()) }; | ||
let end = p.checked_add(usize::try_from(len).map_err(|_| bad())?).filter(|e| *e <= s.len()).ok_or_else(bad)?; | ||
blocks.push((s[..end].to_vec(), s[end..].to_vec())); | ||
} | ||
Ok((roots, blocks)) | ||
} | ||
| ||
/// A varint-prefixed section of a CAR file, at `pos`, moving past it. | ||
fn section<'a>(bytes: &'a [u8], pos: &mut usize) -> Result<&'a [u8], String> { | ||
let n = read_varint(bytes, pos).ok_or("a length cut short")?; | ||
let n = usize::try_from(n).ok().filter(|n| *n > 0 && *n <= bytes.len() - *pos).ok_or("a length of nothing, or past the end")?; | ||
let s = &bytes[*pos..*pos + n]; | ||
*pos += n; | ||
Ok(s) | ||
} | ||
| ||
/// An unsigned LEB128 varint at `pos`, of at most 9 bytes, moving past it. | ||
fn read_varint(bytes: &[u8], pos: &mut usize) -> Option<u64> { | ||
let mut n = 0u64; | ||
for i in 0..9 { | ||
let b = *bytes.get(*pos)?; | ||
*pos += 1; | ||
n |= u64::from(b & 0x7f) << (7 * i); | ||
if b & 0x80 == 0 { | ||
return Some(n); | ||
} | ||
} | ||
None | ||
} | ||
| ||
pub fn make_record(value: V) -> Record { | ||
let bytes = encode(&value); | ||
Record { cid: cid_of(0x71, &bytes), bytes, value } | ||
| @@ -706,4 +813,77 @@ mod tests { | ||
assert_eq!(car, car_with_roots(&[], want)); | ||
} | ||
} | ||
| ||
/// A CAR file reads back as written; one cut short, with bytes after | ||
/// it, or with a header of another shape, does not. | ||
#[test] | ||
fn cars_read_back() { | ||
let mut r = repo(); | ||
create(&mut r, "one", text(3)).unwrap(); | ||
let car = r.car(); | ||
let (roots, blocks) = read_car(&car).unwrap(); | ||
assert_eq!(roots, vec![r.head.clone()]); | ||
let refs: Vec<(&[u8], &[u8])> = blocks.iter().map(|(c, d)| (c.as_slice(), d.as_slice())).collect(); | ||
assert_eq!(car_file(&r.head, refs), car); | ||
// Cut short, it is refused, or else cut at a section's end. | ||
for cut in 1..car.len() { | ||
assert!(read_car(&car[..cut]).map_or(true, |(_, b)| b.len() < blocks.len() && b[..] == blocks[..b.len()]), "{cut}"); | ||
} | ||
assert!(read_car(&[car.clone(), vec![0]].concat()).is_err()); | ||
let header = |v: V| { | ||
let h = encode(&v); | ||
let mut out = Vec::new(); | ||
varint(&mut out, h.len()); | ||
out.extend(h); | ||
out | ||
}; | ||
let roots = || ("roots".to_string(), V::Arr(vec![V::Link(r.head.clone())])); | ||
assert!(read_car(&header(V::Map(vec![roots(), ("version".into(), V::Int(2))]))).is_err()); | ||
assert!(read_car(&header(V::Map(vec![roots()]))).is_err()); | ||
assert!(read_car(&header(V::Map(vec![roots(), ("version".into(), V::Int(1)), ("x".into(), V::Null)]))).is_err()); | ||
assert_eq!(read_car(&header(V::Map(vec![roots(), ("version".into(), V::Int(1))]))).unwrap(), (vec![r.head.clone()], vec![])); | ||
} | ||
| ||
/// A repository loaded from what a checkpoint keeps of it, then the | ||
/// changes after it, is the repository replayed whole. | ||
#[test] | ||
fn loads_from_a_checkpoint() { | ||
let mut r = repo(); | ||
let mut revs = vec![r.rev.clone()]; | ||
for i in 0..30 { | ||
create(&mut r, &format!("k{i}"), text(i % 4 + 1)).unwrap(); | ||
revs.push(r.rev.clone()); | ||
} | ||
let del = Op::Delete { collection: "a.b.c".into(), rkey: "k3".into() }; | ||
r.apply(vec![del], None).unwrap(); | ||
r.change = None; | ||
let up = Op::Update { collection: "a.b.c".into(), rkey: "k4".into(), value: text(9) }; | ||
r.apply(vec![up], None).unwrap(); | ||
r.change = None; | ||
revs.push(r.rev.clone()); | ||
let mut c = Repo::new(r.did.clone(), r.key.clone()); | ||
let records = r.records.iter().map(|(p, x)| (p.clone(), Record { cid: x.cid.clone(), bytes: x.bytes.clone(), value: x.value.clone() })).collect(); | ||
let block_revs = r.block_revs().map(|(c, v)| (c.to_vec(), v.to_string())).collect(); | ||
c.load_checkpoint(r.head_bytes.clone(), records, block_revs, r.written.clone(), &r.tids.last()).unwrap(); | ||
// The changes after it, as the log replays them. | ||
let mut later = Vec::new(); | ||
for i in 0..3 { | ||
later.push(create(&mut r, &format!("n{i}"), text(i + 1)).unwrap()); | ||
revs.push(r.rev.clone()); | ||
} | ||
for ch in &later { | ||
c.load(ch).unwrap(); | ||
} | ||
c.finish_load().unwrap(); | ||
assert_eq!(c.car(), r.car()); | ||
assert_eq!((&c.head, &c.rev, &c.written), (&r.head, &r.rev, &r.written)); | ||
for since in &revs { | ||
assert_eq!(c.car_since(since), r.car_since(since), "since {since}"); | ||
} | ||
assert!(c.tids.last() >= r.rev); | ||
// A tree that is not the commit's is refused. | ||
let mut bad = Repo::new(r.did.clone(), r.key.clone()); | ||
bad.load_checkpoint(r.head_bytes.clone(), vec![], HashMap::new(), HashMap::new(), "2222222222222").unwrap(); | ||
assert!(bad.finish_load().is_err()); | ||
} | ||
} | ||
crates/pds-repo/src/mst.rs+88−1
| @@ -1,6 +1,6 @@ | ||
//! The Merkle Search Tree, rebuilt deterministically from the sorted key/value pairs. | ||
| ||
use crate::data::{V, cid_of, encode}; | ||
use crate::data::{V, cid_of, cid_string, decode, encode}; | ||
use sha2::{Digest, Sha256}; | ||
use std::collections::HashSet; | ||
| ||
| @@ -178,6 +178,63 @@ fn node(entries: &[(Vec<u8>, Vec<u8>)], depths: &[usize], level: usize) -> Optio | ||
Some(Box::new(Node { cid: cid_of(0x71, &bytes), bytes, left, entries: kids })) | ||
} | ||
| ||
/// The `(key, value cid)` entries of a tree read from its blocks, in key | ||
/// order, and the CIDs of the nodes it holds, each once. | ||
pub type Walked = (Vec<(Vec<u8>, Vec<u8>)>, Vec<Vec<u8>>); | ||
| ||
/// Walk the tree rooted at `root`, its nodes found by `block`: its entries in | ||
/// key order and its nodes. Err for a node `block` does not find, one that is | ||
/// not a tree node (a map of exactly `l` and `e`, each entry exactly `p`, | ||
/// `k`, `v` and `t`), or keys not in strictly ascending order. Whether the | ||
/// tree is the one its entries build is not checked: `build_tree` says. | ||
pub fn walk<'a>(root: &[u8], block: impl Fn(&[u8]) -> Option<&'a [u8]>) -> Result<Walked, String> { | ||
let mut out: Walked = (Vec::new(), Vec::new()); | ||
visit(root, &block, &mut out)?; | ||
Ok(out) | ||
} | ||
| ||
fn visit<'a>(cid: &[u8], block: &impl Fn(&[u8]) -> Option<&'a [u8]>, out: &mut Walked) -> Result<(), String> { | ||
let bad = |why: &str| format!("tree node {}: {why}", cid_string(cid)); | ||
let bytes = block(cid).ok_or_else(|| bad("missing"))?; | ||
out.1.push(cid.to_vec()); | ||
let V::Map(mut m) = decode(bytes).map_err(|e| bad(&e))? else { return Err(bad("not a map")) }; | ||
let link = |v: Option<V>| match v { | ||
Some(V::Null) => Ok(None), | ||
Some(V::Link(l)) => Ok(Some(l)), | ||
_ => Err(bad("a subtree that is no link or null")), | ||
}; | ||
let (l, e) = (take(&mut m, "l"), take(&mut m, "e")); | ||
let (Some(V::Arr(entries)), true) = (e, m.is_empty()) else { return Err(bad("not exactly l and a list e")) }; | ||
if let Some(l) = link(l)? { | ||
visit(&l, block, out)?; | ||
} | ||
let mut prev: Vec<u8> = Vec::new(); | ||
for e in entries { | ||
let V::Map(mut e) = e else { return Err(bad("an entry not a map")) }; | ||
let (p, k, v, t) = (take(&mut e, "p"), take(&mut e, "k"), take(&mut e, "v"), take(&mut e, "t")); | ||
let (Some(V::Int(p)), Some(V::Bytes(k)), Some(V::Link(v)), true) = (p, k, v, e.is_empty()) else { | ||
return Err(bad("an entry not exactly p, k, v and t")); | ||
}; | ||
let p = usize::try_from(p).ok().filter(|p| *p <= prev.len()).ok_or_else(|| bad("a prefix longer than the key before"))?; | ||
prev.truncate(p); | ||
prev.extend(k); | ||
if out.0.last().is_some_and(|(last, _)| *last >= prev) { | ||
return Err(bad("keys out of order")); | ||
} | ||
out.0.push((prev.clone(), v)); | ||
if let Some(t) = link(t)? { | ||
visit(&t, block, out)?; | ||
} | ||
} | ||
Ok(()) | ||
} | ||
| ||
/// A map's value of key `k`, taken out of it. | ||
fn take(m: &mut Vec<(String, V)>, k: &str) -> Option<V> { | ||
let i = m.iter().position(|(n, _)| n == k)?; | ||
Some(m.swap_remove(i).1) | ||
} | ||
| ||
#[cfg(test)] | ||
mod tests { | ||
use super::*; | ||
| @@ -220,4 +277,34 @@ mod tests { | ||
} | ||
} | ||
} | ||
| ||
/// A tree walked from its blocks answers its entries and every node; | ||
/// one missing a node, or with keys out of order, is refused. | ||
#[test] | ||
fn walks() { | ||
use std::collections::HashMap; | ||
for n in [0usize, 1, 40, 1000] { | ||
let mut entries: Vec<(Vec<u8>, Vec<u8>)> = (0..n).map(|i| (format!("a.b.c/k{i}").into_bytes(), cid_of(0x71, &i.to_le_bytes()))).collect(); | ||
entries.sort(); | ||
let tree = build_tree(&entries); | ||
let blocks: HashMap<Vec<u8>, Vec<u8>> = tree.nodes().into_iter().map(|x| (x.cid.clone(), x.bytes.clone())).collect(); | ||
let (got, nodes) = walk(&tree.cid, |c| blocks.get(c).map(Vec::as_slice)).unwrap(); | ||
assert_eq!(got, entries); | ||
let mut want: Vec<Vec<u8>> = blocks.keys().cloned().collect(); | ||
let mut nodes = nodes; | ||
want.sort(); | ||
nodes.sort(); | ||
assert_eq!(nodes, want); | ||
if n > 1 { | ||
let leaf = tree.nodes()[0].cid.clone(); | ||
assert!(walk(&tree.cid, |c| if *c == leaf[..] { None } else { blocks.get(c).map(Vec::as_slice) }).is_err()); | ||
} | ||
} | ||
// Two keys swapped in one node. | ||
let (a, b) = (b"a.b.c/2".to_vec(), b"a.b.c/1".to_vec()); | ||
let e = |k: &[u8]| V::Map(vec![("p".into(), V::Int(0)), ("k".into(), V::Bytes(k.to_vec())), ("v".into(), V::Link(cid_of(0x71, b"x"))), ("t".into(), V::Null)]); | ||
let bytes = encode(&V::Map(vec![("l".into(), V::Null), ("e".into(), V::Arr(vec![e(&a), e(&b)]))])); | ||
let cid = cid_of(0x71, &bytes); | ||
assert!(walk(&cid, |c| (*c == cid[..]).then_some(bytes.as_slice())).is_err()); | ||
} | ||
} | ||
crates/pds-server/src/lifecycle/tests.rs+8−10
| @@ -72,8 +72,7 @@ impl Env { | ||
| ||
/// Every event a subscription begun now replays: `$t` beside its body's fields. | ||
fn events(&self) -> Vec<Json> { | ||
let n = self.s.events.len(); | ||
self.s.events.get(0, n, self.s.events.drops()).iter().map(|f| decoded(f)).collect() | ||
self.s.events.get(0, u64::MAX - 1, self.s.events.drops()).iter().map(|f| decoded(f)).collect() | ||
} | ||
} | ||
| ||
| @@ -693,7 +692,8 @@ async fn deleting_an_account() { | ||
let before = e.events(); | ||
e.reopen(); | ||
assert_eq!(e.events(), before); | ||
assert_eq!(e.s.events.len(), n + 1); | ||
// Numbered on after every event given out, the deleted account's too. | ||
assert_eq!(*e.s.events.subscribe().borrow(), n as u64 + 1); | ||
assert!(e.s.account(&did).is_none()); | ||
// Its handle and email are free: a new account takes them. | ||
let again = json!({ "handle": "alice.test", "email": "alice@mail.com", "password": "pw" }); | ||
| @@ -715,8 +715,7 @@ async fn the_firehose_across_a_deletion() { | ||
let live = e.s.events.drops(); | ||
e.call(REQUEST_DELETE, Some(&token), Json::Null).await.unwrap(); | ||
e.call(DELETE, None, json!({ "did": did, "password": "alice-pw", "token": last_token(&e.sink) })).await.unwrap(); | ||
let n = e.s.events.len(); | ||
let of = |drops: u64| -> Vec<String> { e.s.events.get(0, n, drops).iter().map(|f| brief(&decoded(f))).filter(|b| b.contains(&did)).collect() }; | ||
let of = |drops: u64| -> Vec<String> { e.s.events.get(0, u64::MAX - 1, drops).iter().map(|f| brief(&decoded(f))).filter(|b| b.contains(&did)).collect() }; | ||
let all = of(live); | ||
assert_eq!(all.len(), 5); | ||
assert_eq!(all.last().unwrap(), &format!("account {did} false deleted")); | ||
| @@ -733,7 +732,7 @@ async fn a_deletion_cut_short() { | ||
create(&e.s, "bob").await; | ||
e.call("com.atproto.repo.putRecord", Some(&token), put(&did, "one", json!({ "n": 1 }))).await.unwrap(); | ||
e.call(REQUEST_DELETE, Some(&token), Json::Null).await.unwrap(); | ||
let log = e.dir.join(crate::log::ACCOUNTS_LOG); | ||
let log = crate::log::accounts_log(&e.dir); | ||
let before = std::fs::read(&log).unwrap(); | ||
let repo = std::fs::read(crate::log::repo_log(&e.dir, &did)).unwrap(); | ||
e.call(DELETE, None, json!({ "did": did, "password": "alice-pw", "token": last_token(&e.sink) })).await.unwrap(); | ||
| @@ -746,18 +745,17 @@ async fn a_deletion_cut_short() { | ||
for f in ["jwt.key"] { | ||
std::fs::copy(e.dir.join(f), work.join(f)).unwrap(); | ||
} | ||
std::fs::write(work.join(crate::log::ACCOUNTS_LOG), &after[..cut]).unwrap(); | ||
std::fs::write(crate::log::accounts_log(&work), &after[..cut]).unwrap(); | ||
std::fs::write(crate::log::repo_log(&work, &did), &repo).unwrap(); | ||
let bob = e.s.account("bob.test").unwrap().did.clone(); | ||
let bob_dir = e.dir.join("repos").join(&bob); | ||
std::fs::create_dir_all(work.join("repos").join(&bob)).unwrap(); | ||
std::fs::copy(bob_dir.join("repo.log"), work.join("repos").join(&bob).join("repo.log")).unwrap(); | ||
std::fs::copy(bob_dir.join("repo.0.log"), work.join("repos").join(&bob).join("repo.0.log")).unwrap(); | ||
let s = open(&work, &e.plc); | ||
let gone = s.account(&did).is_none(); | ||
assert_eq!(gone, cut == after.len(), "cut at {cut}"); | ||
assert_eq!(work.join("repos").join(&did).exists(), !gone, "cut at {cut}"); | ||
let n = s.events.len(); | ||
let deletions = s.events.get(0, n, s.events.drops()).iter().map(|f| decoded(f)).filter(|ev| ev["status"] == json!("deleted")).count(); | ||
let deletions = s.events.get(0, u64::MAX - 1, s.events.drops()).iter().map(|f| decoded(f)).filter(|ev| ev["status"] == json!("deleted")).count(); | ||
assert_eq!(deletions, usize::from(gone), "cut at {cut}"); | ||
let free = call(&s, "com.atproto.server.createAccount", None, json!({ "handle": "alice.test", "email": "alice@mail.com", "password": "pw" })).await; | ||
assert_eq!(free.is_ok(), gone, "cut at {cut}"); | ||
crates/pds-server/src/oauth/clients/fetch.rs+1−1
| @@ -97,7 +97,7 @@ impl Fetcher { | ||
None if url.scheme() != "https" => return Err(format!("{url} is not https")), | ||
None => url.to_string(), | ||
}; | ||
let got = outbound.fetch_limited(outbound.client().get(&target).header("accept", "application/json"), MAX_BODY, self.timeout).await?; | ||
let got = outbound.fetch_limited(crate::ops::Target::Client, outbound.client().get(&target).header("accept", "application/json"), MAX_BODY, self.timeout).await?; | ||
if got.status != 200 { | ||
return Err(format!("{url} answered {}", got.status)); | ||
} | ||
crates/pds-server/src/oauth/tests.rs+8−5
| @@ -1402,10 +1402,13 @@ pub(crate) fn kept(s: &Service) -> Kept { | ||
} | ||
| ||
/// What OAuth keeps, as it is held at `now`: the single-use values whose | ||
/// time has passed are forgotten, whenever they were held. A test that runs | ||
/// longer than a value is held compares what it kept so. | ||
/// time has passed are forgotten, whenever they were held, and what OAuth | ||
/// forgets by `now`, as a restart does. A test that runs longer than a value | ||
/// or a request is held compares what it kept so. | ||
pub(crate) fn held_at(k: &Kept, now: u64) -> Kept { | ||
(k.0.clone(), k.1.iter().filter(|(_, t)| **t > now).map(|(k, t)| (k.clone(), *t)).collect()) | ||
let mut oauth = k.0.clone(); | ||
oauth.forget(now); | ||
(oauth, k.1.iter().filter(|(_, t)| **t > now).map(|(k, t)| (k.clone(), *t)).collect()) | ||
} | ||
| ||
#[tokio::test] | ||
| @@ -1678,7 +1681,7 @@ async fn states_are_kept_as_digests() { | ||
let held = srv.svc.replay.snapshot(srv.now()); | ||
assert!(held.contains_key(&(STATE_NS.to_string(), digest))); | ||
assert!(held.keys().all(|(ns, _)| ["dpop", "pkce", STATE_NS].contains(&ns.as_str())), "{held:?}"); | ||
let log = String::from_utf8_lossy(&std::fs::read(dir.join(crate::log::ACCOUNTS_LOG)).unwrap()).into_owned(); | ||
let log = String::from_utf8_lossy(&std::fs::read(dir.join(crate::log::ACCOUNTS_LOG_FILE)).unwrap()).into_owned(); | ||
assert!(log.contains(r#""ns":"state","#) && !log.contains(r#""ns":"state "#)); | ||
// A state an older server kept, in the client's namespace, is still refused. | ||
let now = srv.now(); | ||
| @@ -1903,7 +1906,7 @@ async fn a_password_reset_ends_what_oauth_kept_of_the_account() { | ||
call(&srv.svc, "com.atproto.server.requestPasswordReset", None, json!({ "email": "alice@mail.com" })).await.unwrap(); | ||
let log_len = srv.svc.log.len(); | ||
call(&srv.svc, "com.atproto.server.resetPassword", None, json!({ "token": last_token(&sink), "password": "new-pw" })).await.unwrap(); | ||
let frames = pds_store::scan(&std::fs::read(dir.join(crate::log::ACCOUNTS_LOG)).unwrap()[log_len as usize..]).0; | ||
let frames = pds_store::scan(&std::fs::read(dir.join(crate::log::ACCOUNTS_LOG_FILE)).unwrap()[log_len as usize..]).0; | ||
assert_eq!(frames.len(), 1, "one frame"); | ||
let kinds: Vec<&str> = frames[0].iter().filter_map(|e| e["t"].as_str()).collect(); | ||
assert!(["password", "oauthEndRequest", "oauthEndSession", "oauthSignOut"].iter().all(|k| kinds.contains(k)), "{kinds:?}"); | ||
crates/pds-server/src/ops/metrics.rsnew+202−0
| @@ -0,0 +1,202 @@ | ||
//! The server's metrics, in Prometheus' text format, version 0.0.4, on | ||
//! `127.0.0.1:PDS_METRICS_PORT` (`spec/OPERATIONS.md`). Every label's | ||
//! values are bounded: the routes served, statuses, and the outbound targets. | ||
| ||
use super::trace::Target; | ||
use crate::{Shared, read}; | ||
use axum::body::Body; | ||
use axum::http::{Method, Response, StatusCode, header}; | ||
use std::collections::BTreeMap; | ||
use std::fmt::Write; | ||
use std::sync::{Mutex, PoisonError}; | ||
use std::time::Duration; | ||
| ||
const REQUEST_BUCKETS: &[f64] = &[0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0]; | ||
const FSYNC_BUCKETS: &[f64] = &[0.0001, 0.00025, 0.0005, 0.001, 0.0025, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 1.0]; | ||
| ||
struct Histogram { | ||
bounds: &'static [f64], | ||
/// Each bucket's own observations, not yet cumulative. | ||
counts: Vec<u64>, | ||
count: u64, | ||
sum: f64, | ||
} | ||
| ||
impl Histogram { | ||
fn new(bounds: &'static [f64]) -> Histogram { | ||
Histogram { bounds, counts: vec![0; bounds.len()], count: 0, sum: 0.0 } | ||
} | ||
| ||
fn observe(&mut self, v: f64) { | ||
if let Some(i) = self.bounds.iter().position(|b| v <= *b) { | ||
self.counts[i] += 1; | ||
} | ||
self.count += 1; | ||
self.sum += v; | ||
} | ||
| ||
/// Its samples, with `labels` before `le`, each `name_bucket`, `_sum`, `_count`. | ||
fn render(&self, out: &mut String, name: &str, labels: &str) { | ||
let sep = if labels.is_empty() { "" } else { "," }; | ||
let mut seen = 0; | ||
for (b, n) in self.bounds.iter().zip(&self.counts) { | ||
seen += n; | ||
let _ = writeln!(out, "{name}_bucket{{{labels}{sep}le=\"{b}\"}} {seen}"); | ||
} | ||
let _ = writeln!(out, "{name}_bucket{{{labels}{sep}le=\"+Inf\"}} {}", self.count); | ||
let braces = if labels.is_empty() { String::new() } else { format!("{{{labels}}}") }; | ||
let _ = writeln!(out, "{name}_sum{braces} {}", self.sum); | ||
let _ = writeln!(out, "{name}_count{braces} {}", self.count); | ||
} | ||
} | ||
| ||
struct Inner { | ||
requests: BTreeMap<(&'static str, u16), u64>, | ||
durations: BTreeMap<&'static str, Histogram>, | ||
limited: BTreeMap<&'static str, u64>, | ||
fsync: Histogram, | ||
outbound: BTreeMap<(&'static str, &'static str), u64>, | ||
outbound_durations: BTreeMap<&'static str, Histogram>, | ||
} | ||
| ||
/// The counters and histograms, from the start of the process. | ||
pub(super) struct Metrics(Mutex<Inner>); | ||
| ||
impl Default for Metrics { | ||
fn default() -> Metrics { | ||
Metrics(Mutex::new(Inner { | ||
requests: BTreeMap::new(), | ||
durations: BTreeMap::new(), | ||
limited: BTreeMap::new(), | ||
fsync: Histogram::new(FSYNC_BUCKETS), | ||
outbound: BTreeMap::new(), | ||
outbound_durations: BTreeMap::new(), | ||
})) | ||
} | ||
} | ||
| ||
impl Metrics { | ||
fn lock(&self) -> std::sync::MutexGuard<'_, Inner> { | ||
self.0.lock().unwrap_or_else(PoisonError::into_inner) | ||
} | ||
| ||
/// A request answered, on `route`, taking `secs`. | ||
pub fn request(&self, route: &'static str, status: u16, secs: f64) { | ||
let mut m = self.lock(); | ||
*m.requests.entry((route, status)).or_default() += 1; | ||
m.durations.entry(route).or_insert_with(|| Histogram::new(REQUEST_BUCKETS)).observe(secs); | ||
if status == 429 { | ||
*m.limited.entry(route).or_default() += 1; | ||
} | ||
} | ||
| ||
pub fn fsync(&self, d: Duration) { | ||
self.lock().fsync.observe(d.as_secs_f64()); | ||
} | ||
| ||
/// A request the server made, answered with a 2xx (`ok`) or not. | ||
pub fn outbound(&self, target: Target, ok: bool, secs: f64) { | ||
let mut m = self.lock(); | ||
*m.outbound.entry((target.label(), if ok { "ok" } else { "error" })).or_default() += 1; | ||
m.outbound_durations.entry(target.label()).or_insert_with(|| Histogram::new(REQUEST_BUCKETS)).observe(secs); | ||
} | ||
| ||
/// The exposition, with the gauges read from `svc` now. | ||
fn render(&self, svc: &Shared) -> String { | ||
let (accounts, all) = { | ||
let d = read(&svc.directory); | ||
// As `listRepos` lists them: in order, a deleted account passed over. | ||
let accounts = d.order.iter().filter(|did| !d.deleted.contains(*did)).take_while(|did| d.by_did.contains_key(*did)).count(); | ||
(accounts, d.by_did.values().cloned().collect::<Vec<_>>()) | ||
}; | ||
// Every generation's log not yet folded away, and the checkpoints. | ||
let bytes = |w: &pds_store::Wal| w.log_bytes() + w.checkpoint_bytes(); | ||
let log_bytes = bytes(&svc.log) + all.iter().map(|a| bytes(&read(&a.store).wal)).sum::<u64>(); | ||
let mut out = String::with_capacity(8192); | ||
let family = |out: &mut String, name: &str, ty: &str, help: &str| { | ||
let _ = writeln!(out, "# HELP {name} {help}\n# TYPE {name} {ty}"); | ||
}; | ||
let m = self.lock(); | ||
family(&mut out, "pds_requests_total", "counter", "Requests answered."); | ||
for ((route, status), n) in &m.requests { | ||
let _ = writeln!(out, "pds_requests_total{{method=\"{}\",status=\"{status}\"}} {n}", escape(route)); | ||
} | ||
family(&mut out, "pds_request_duration_seconds", "histogram", "Each request's time, from reading its head to its log line."); | ||
for (route, h) in &m.durations { | ||
h.render(&mut out, "pds_request_duration_seconds", &format!("method=\"{}\"", escape(route))); | ||
} | ||
family(&mut out, "pds_rate_limited_total", "counter", "Requests refused by a rate limit."); | ||
for (route, n) in &m.limited { | ||
let _ = writeln!(out, "pds_rate_limited_total{{method=\"{}\"}} {n}", escape(route)); | ||
} | ||
family(&mut out, "pds_firehose_seq", "gauge", "The seq of the firehose's last event."); | ||
let _ = writeln!(out, "pds_firehose_seq {}", svc.events.published()); | ||
family(&mut out, "pds_firehose_subscribers", "gauge", "subscribeRepos connections open."); | ||
let _ = writeln!(out, "pds_firehose_subscribers {}", svc.events.subscribers()); | ||
family(&mut out, "pds_accounts", "gauge", "The accounts the server holds."); | ||
let _ = writeln!(out, "pds_accounts {accounts}"); | ||
family(&mut out, "pds_log_bytes", "gauge", "The bytes of the logs the server keeps its state in."); | ||
let _ = writeln!(out, "pds_log_bytes {log_bytes}"); | ||
family(&mut out, "pds_fsync_duration_seconds", "histogram", "Each sync of written data to the disk."); | ||
m.fsync.render(&mut out, "pds_fsync_duration_seconds", ""); | ||
family(&mut out, "pds_outbound_requests_total", "counter", "Requests the server made."); | ||
for ((target, outcome), n) in &m.outbound { | ||
let _ = writeln!(out, "pds_outbound_requests_total{{target=\"{target}\",outcome=\"{outcome}\"}} {n}"); | ||
} | ||
family(&mut out, "pds_outbound_request_duration_seconds", "histogram", "Each request the server made, until its answer or failure."); | ||
for (target, h) in &m.outbound_durations { | ||
h.render(&mut out, "pds_outbound_request_duration_seconds", &format!("target=\"{target}\"")); | ||
} | ||
out | ||
} | ||
} | ||
| ||
fn escape(v: &str) -> String { | ||
v.replace('\\', "\\\\").replace('"', "\\\"").replace('\n', "\\n") | ||
} | ||
| ||
/// Serve `GET /metrics` on `listener`, and `404` to anything else. | ||
pub(super) async fn serve(listener: tokio::net::TcpListener, svc: Shared) { | ||
let app = axum::Router::new().fallback(move |method: Method, uri: axum::http::Uri| { | ||
let svc = svc.clone(); | ||
async move { | ||
let mut res = Response::new(Body::empty()); | ||
if method == Method::GET && uri.path() == "/metrics" { | ||
res = Response::new(Body::from(super::ops().metrics.render(&svc))); | ||
res.headers_mut().insert(header::CONTENT_TYPE, header::HeaderValue::from_static("text/plain; version=0.0.4; charset=utf-8")); | ||
} else { | ||
*res.status_mut() = StatusCode::NOT_FOUND; | ||
} | ||
res | ||
} | ||
}); | ||
let _ = axum::serve(listener, app).await; | ||
} | ||
| ||
#[cfg(test)] | ||
mod tests { | ||
use super::*; | ||
| ||
/// A histogram's buckets are cumulative, each bound as Prometheus reads | ||
/// it, then `+Inf`, `_sum` and `_count`. | ||
#[test] | ||
fn histograms() { | ||
let mut h = Histogram::new(FSYNC_BUCKETS); | ||
for v in [0.00005, 0.0003, 0.0003, 2.0] { | ||
h.observe(v); | ||
} | ||
let mut out = String::new(); | ||
h.render(&mut out, "x", ""); | ||
let lines: Vec<&str> = out.lines().collect(); | ||
assert_eq!(lines[0], "x_bucket{le=\"0.0001\"} 1"); | ||
assert_eq!(lines[2], "x_bucket{le=\"0.0005\"} 3"); | ||
assert_eq!(lines[11], "x_bucket{le=\"1\"} 3"); | ||
assert_eq!(lines[12], "x_bucket{le=\"+Inf\"} 4"); | ||
assert!((lines[13].strip_prefix("x_sum ").unwrap().parse::<f64>().unwrap() - 2.00065).abs() < 1e-9); | ||
assert_eq!(lines[14], "x_count 4"); | ||
let mut out = String::new(); | ||
Histogram::new(REQUEST_BUCKETS).render(&mut out, "y", "method=\"_health\""); | ||
assert!(out.starts_with("y_bucket{method=\"_health\",le=\"0.005\"} 0\n")); | ||
assert!(out.ends_with("y_sum{method=\"_health\"} 0\ny_count{method=\"_health\"} 0\n")); | ||
} | ||
} | ||
crates/pds-server/src/ops/trace.rsnew+668−0
668 lines changed: not loaded until asked for.
crates/pds-server/src/space_credentials/attestation.rs+1−1
| @@ -84,7 +84,7 @@ fn https(url: &str) -> Option<reqwest::Url> { | ||
/// none), at most `JSON_DOC_MAX` bytes, within `WAIT`. | ||
async fn fetch(out: &Outbound, url: reqwest::Url) -> Option<Map<String, Json>> { | ||
let request = out.client().get(url).header(reqwest::header::ACCEPT, "application/json"); | ||
let got = out.fetch_limited(request, outbound::JSON_DOC_MAX, outbound::WAIT).await.ok()?; | ||
let got = out.fetch_limited(crate::ops::Target::Client, request, outbound::JSON_DOC_MAX, outbound::WAIT).await.ok()?; | ||
if got.status != 200 { | ||
return None; | ||
} | ||
crates/pds-server/src/blobs.rs+142−20
| @@ -12,9 +12,16 @@ | ||
//! public record's do (`space_repo` counts them), but the public `getBlob` | ||
//! and `listBlobs` serve and list only blobs public records reference. | ||
//! | ||
//! An upload is written to a temporary file in that directory, synced, and | ||
//! renamed into place, and the directory synced, before its entry is logged: | ||
//! an entry always has its file. A write that removes a blob's last | ||
//! An upload is written to a temporary file in that directory and renamed | ||
//! into place before its entry is logged, and answered once both are handed | ||
//! to the operating system: an entry always has its file, and an answered | ||
//! upload survives the server being killed. Neither is synced then. The | ||
//! commit that first references a blob has its file and directory synced | ||
//! before the commit's frame is (`sync_before`, `Wal::sync_first`), in the | ||
//! group commit, so a referenced blob survives a power cut wherever its | ||
//! commit does; an upload no record references yet may not | ||
//! (`spec/DURABILITY.md`), and recovery drops one whose file did not. | ||
//! A write that removes a blob's last | ||
//! reference stops holding it at once, under the account's lock, but removes | ||
//! its file only once the write is on disk. If the server stops between the | ||
//! two, it starts again with the file held by no entry, and removes it, as it | ||
| @@ -23,7 +30,7 @@ | ||
//! uploaded: refused as a ref and counted against no quota at once, and | ||
//! logged as gone, its file removed, by `sweep`. | ||
| ||
use crate::{Account, Call, Handler, Resp, Service, Shared, Shown, Store, XrpcError, durable, err, internal, invalid, opt, read, required, write}; | ||
use crate::{Account, Call, Handler, Resp, Service, Shared, Shown, Store, XrpcError, err, internal, invalid, opt, read, required, write}; | ||
use axum::body::{Body, Bytes, HttpBody}; | ||
use axum::extract::{Extension, State as AxState}; | ||
use axum::http::{HeaderMap, HeaderValue, Method, header}; | ||
| @@ -108,6 +115,9 @@ pub(crate) struct Blobs { | ||
bytes: u64, | ||
/// Uploads moving their files into place, by CID: those files stay. | ||
placing: HashMap<String, u32>, | ||
/// The files of uploads not yet synced, by CID: synced before the frame | ||
/// of the commit that first references them. | ||
unsynced: HashMap<String, PathBuf>, | ||
/// Blobs the last write stopped holding, whose files go once it is on disk. | ||
doomed: Vec<String>, | ||
/// The last commit's changes, until it is in the log. | ||
| @@ -218,6 +228,16 @@ impl Blobs { | ||
self.refs.contains_key(cid) || self.space_refs.contains_key(cid) | ||
} | ||
| ||
/// Have the files of the uploads not yet synced among `cids` synced | ||
/// before `wal` next is: a commit referencing them is about to be logged | ||
/// in it. | ||
pub(crate) fn sync_before(&mut self, wal: &pds_store::Wal, cids: impl IntoIterator<Item = String>) { | ||
let paths: Vec<PathBuf> = cids.into_iter().filter_map(|c| self.unsynced.remove(&c)).collect(); | ||
if !paths.is_empty() { | ||
wal.sync_first(paths); | ||
} | ||
} | ||
| ||
/// Whether a blob held is unreferenced and past its time. | ||
fn expired(&self, cid: &str) -> bool { | ||
!self.referenced(cid) && self.held.get(cid).is_some_and(|h| h.at.saturating_add(self.ttl) <= self.now) | ||
| @@ -472,17 +492,29 @@ impl Blobs { | ||
} | ||
| ||
/// Once the log is replayed: every blob held has its file, whole, and | ||
/// every other file in `dir` goes, as no entry holds it. | ||
/// every other file in `dir` goes, as no entry holds it. An upload no | ||
/// record references was never synced: one whose file a power cut took | ||
/// is held no more, and the others are synced by the commit that first | ||
/// references them, as before. | ||
pub(crate) fn recover(&mut self, dir: &Path) -> Result<(), String> { | ||
self.doomed.clear(); | ||
self.undo = None; | ||
let mut lost = Vec::new(); | ||
for (cid, h) in &self.held { | ||
let p = dir.join(cid); | ||
match std::fs::metadata(&p) { | ||
Ok(m) if m.len() == h.size => {} | ||
_ => return Err(format!("{}: the file of a blob the log holds is missing or not whole", p.display())), | ||
let whole = std::fs::metadata(&p).is_ok_and(|m| m.len() == h.size); | ||
match (whole, self.referenced(cid)) { | ||
(_, true) if !whole => return Err(format!("{}: the file of a blob the log holds is missing or not whole", p.display())), | ||
(_, true) => {} | ||
(true, false) => { | ||
self.unsynced.insert(cid.clone(), p); | ||
} | ||
(false, false) => lost.push(cid.clone()), | ||
} | ||
} | ||
for cid in lost { | ||
self.set_held(&cid, None); | ||
} | ||
let Ok(entries) = std::fs::read_dir(dir) else { return Ok(()) }; | ||
for e in entries { | ||
let e = e.map_err(|e| format!("{}: {e}", dir.display()))?; | ||
| @@ -499,6 +531,42 @@ impl Blobs { | ||
std::mem::take(&mut self.doomed) | ||
} | ||
| ||
/// The blobs it holds, in ascending order of CID, each with its | ||
/// takedown's reference while it is down: what a checkpoint keeps. | ||
pub(crate) fn held_list(&self) -> impl Iterator<Item = (&str, &Held, Option<&str>)> { | ||
self.held.iter().map(|(cid, h)| (cid.as_str(), h, self.takedowns.get(cid).map(String::as_str))) | ||
} | ||
| ||
/// The blobs a checkpoint keeps, as replaying the log would leave them: | ||
/// those held, each with its takedown, and the references the records of | ||
/// `repo` make, each record's by the rev that last wrote it. The space | ||
/// repos' references are counted as each is restored (`space_repo`). | ||
pub(crate) fn restore(repo: &Repo, held: Vec<(String, Held, Option<String>)>) -> Result<Blobs, String> { | ||
let mut b = Blobs::default(); | ||
for (path, r) in &repo.records { | ||
let cids = cids_in(&r.value); | ||
if cids.is_empty() { | ||
continue; | ||
} | ||
let rev = repo.written.get(path).ok_or_else(|| format!("record {path} with no rev that wrote it"))?; | ||
for cid in &cids { | ||
*b.refs.entry(cid.clone()).or_default() += 1; | ||
} | ||
b.records.insert(path.clone(), (rev.clone(), cids)); | ||
} | ||
for (cid, h, takedown) in held { | ||
if !b.refs.contains_key(&cid) { | ||
b.unreferenced.insert((h.at, cid.clone())); | ||
} | ||
if let Some(t) = takedown { | ||
b.takedowns.insert(cid.clone(), t); | ||
} | ||
b.bytes += h.size; | ||
b.held.insert(cid, h); | ||
} | ||
Ok(b) | ||
} | ||
| ||
/// What a restart must carry over, as one comparable value. | ||
#[cfg(test)] | ||
pub(crate) fn snapshot(&self) -> String { | ||
| @@ -518,9 +586,10 @@ pub(crate) fn apply(st: &mut Store, ops: Vec<Op>, swap_commit: Option<&str>) -> | ||
refs_in(value, &mut refs); | ||
} | ||
} | ||
let Store { repo, blobs, .. } = st; | ||
let Store { repo, blobs, wal, .. } = st; | ||
let results = repo.apply_checked(ops, swap_commit, || blobs.check(&refs))?; | ||
if let Some(c) = &repo.change { | ||
blobs.sync_before(wal, refs.iter().map(|r| cid_string(&r.cid))); | ||
blobs.committed(repo, c); | ||
} | ||
Ok(results) | ||
| @@ -562,13 +631,13 @@ pub(crate) fn sweep(svc: &Service) { | ||
(st.wal.clone(), n, gone) | ||
} | ||
Err(e) => { | ||
eprintln!("pds: {}: logging uploads gone: {e}", a.did); | ||
crate::ops::failed_for(crate::ops::Level::Error, "logging uploads gone failed", &a.did, e); | ||
continue; | ||
} | ||
} | ||
}; | ||
if let Err(e) = wal.wait(n) { | ||
eprintln!("pds: {}: syncing uploads gone: {e}", a.did); | ||
crate::ops::failed_for(crate::ops::Level::Error, "syncing uploads gone failed", &a.did, e); | ||
continue; | ||
} | ||
forget(svc, &a, gone); | ||
| @@ -660,12 +729,16 @@ impl Temp { | ||
Ok(Temp { path, file, placed: false }) | ||
} | ||
| ||
/// Move the bytes to `to`, durably. | ||
/// Move the bytes to `to`, unsynced: the commit that first references | ||
/// them syncs them. Bytes of the same CID already there stay, as they | ||
/// may be synced and these not. | ||
fn place(mut self, to: &Path) -> io::Result<()> { | ||
self.file.sync_all()?; | ||
if to.exists() { | ||
return Ok(()); | ||
} | ||
std::fs::rename(&self.path, to)?; | ||
self.placed = true; | ||
pds_store::sync_dir(to.parent().unwrap_or(Path::new("."))) | ||
Ok(()) | ||
} | ||
} | ||
| ||
| @@ -782,8 +855,9 @@ async fn upload_blob(svc: Shared, call: &Call<'_>, headers: &HeaderMap, body: &m | ||
} | ||
| ||
/// Store an upload's bytes as its CID's, within the account's quota, and log | ||
/// it, unless a record references it already; return once that is on disk. | ||
/// Its file is put in place first, held by none until it is logged. | ||
/// it, unless a record references it already; return once that is handed to | ||
/// the operating system, unsynced. Its file is put in place first, held by | ||
/// none until it is logged. | ||
async fn store(svc: Shared, account: Arc<Account>, dir: PathBuf, tmp: Temp, cid: String, blob: Held) -> Result<(), XrpcError> { | ||
*write(&account.store).blobs.placing.entry(cid.clone()).or_default() += 1; | ||
let to = dir.join(&cid); | ||
| @@ -820,21 +894,23 @@ async fn store(svc: Shared, account: Arc<Account>, dir: PathBuf, tmp: Temp, cid: | ||
match st.wal.append(&entries) { | ||
Ok(n) => { | ||
st.blobs.uploaded(&cid, how, blob); | ||
if !st.blobs.referenced(&cid) { | ||
st.blobs.unsynced.insert(cid.clone(), dir.join(&cid)); | ||
} | ||
Ok(n) | ||
} | ||
Err(e) => { | ||
eprintln!("pds: {}: logging an upload: {e}", account.did); | ||
crate::ops::failed_for(crate::ops::Level::Error, "logging an upload failed", &account.did, e); | ||
internal() | ||
} | ||
} | ||
} | ||
}; | ||
(logged.map(|n| (st.wal.clone(), n)), logged_or_doomed(&st.blobs, &cid)) | ||
(logged, logged_or_doomed(&st.blobs, &cid)) | ||
}; | ||
// An upload not logged leaves no file a blob held does not have. | ||
forget(&svc, &account, doomed); | ||
let (wal, n) = logged?; | ||
durable(wal, n).await | ||
logged.map(|_| ()) | ||
} | ||
| ||
/// The CID, if the account does not hold it, as a file to remove. | ||
| @@ -1276,6 +1352,52 @@ mod tests { | ||
let _ = std::fs::remove_dir_all(&dir); | ||
} | ||
| ||
/// An upload is answered unsynced; the commit that first references it | ||
/// syncs its file before the commit's frame. A power cut is modelled as | ||
/// losing every file not synced: the referenced blob survives with its | ||
/// commit, the unreferenced upload is lost, and the server starts again, | ||
/// holding the one and not the other. | ||
#[tokio::test] | ||
async fn a_referenced_blob_survives_where_its_commit_does() { | ||
let plc = plc().await; | ||
let dir = scratch("blob-power-cut"); | ||
let s = open(&dir, &plc); | ||
let (did, token) = create(&s, "alice").await; | ||
let (kept, lost) = (plain(41), plain(42)); | ||
let (kc, lc) = (raw_cid(&kept), raw_cid(&lost)); | ||
for b in [&kept, &lost] { | ||
test_upload(&s, Some(&token), Some("text/plain"), b.clone(), false).await.unwrap(); | ||
} | ||
let account = s.account(&did).unwrap(); | ||
{ | ||
let st = read(&account.store); | ||
assert!(st.blobs.unsynced.contains_key(&kc) && st.blobs.unsynced.contains_key(&lc), "uploads are answered unsynced"); | ||
} | ||
put(&s, &token, &did, "a", json!({ "f": bref(&kc, "text/plain", kept.len() as i64) })).await.unwrap(); | ||
let wal = { | ||
let st = read(&account.store); | ||
assert!(!st.blobs.unsynced.contains_key(&kc), "the commit referencing it took it to sync"); | ||
assert!(st.blobs.unsynced.contains_key(&lc), "an unreferenced upload stays unsynced"); | ||
st.wal.clone() | ||
}; | ||
// The commit was answered: its frame is on disk, so the blob's file is. | ||
assert!(wal.is_durable(wal.written())); | ||
drop((wal, account)); | ||
drop(s); | ||
// The power cut: the file never synced is gone. | ||
std::fs::remove_file(blob_dir(&dir, &did).join(&lc)).unwrap(); | ||
let s = open(&dir, &plc); | ||
let (status, _, bytes) = get(&s, &did, &kc, None).await; | ||
assert_eq!((status, bytes), (200, kept.clone())); | ||
let r = json!({ "f": bref(&lc, "text/plain", lost.len() as i64) }); | ||
assert_eq!(put(&s, &token, &did, "b", r).await, Err("BlobNotFound".into())); | ||
// Uploaded again, it is held, and its next reference syncs it. | ||
test_upload(&s, Some(&token), Some("text/plain"), lost.clone(), false).await.unwrap(); | ||
put(&s, &token, &did, "b", json!({ "f": bref(&lc, "text/plain", lost.len() as i64) })).await.unwrap(); | ||
assert!(!read(&s.account(&did).unwrap().store).blobs.unsynced.contains_key(&lc)); | ||
let _ = std::fs::remove_dir_all(&dir); | ||
} | ||
| ||
/// A blob is held while some record references it, counted across | ||
/// creates, updates, deletes and applyWrites. | ||
#[tokio::test] | ||
crates/pds-server/src/checkpoint.rsnew+972−0
972 lines changed: not loaded until asked for.
crates/pds-server/src/compact.rs+148−80
crates/pds-server/src/email.rs+4−6
crates/pds-server/src/events.rs+289−144
433 lines changed: not loaded until asked for.
crates/pds-server/src/federation.rs+5−8
crates/pds-server/src/identity.rs+12−12
crates/pds-server/src/invites.rs+1−2
crates/pds-server/src/lib.rs+46−24
crates/pds-server/src/lifecycle.rs+51−41
crates/pds-server/src/limits.rs+44−19
crates/pds-server/src/log.rs+372−193
565 lines changed: not loaded until asked for.
crates/pds-server/src/oauth.rs+3−10
crates/pds-server/src/ops.rsnew+488−0
488 lines changed: not loaded until asked for.
crates/pds-server/src/outbound.rs+20−17
crates/pds-server/src/plc.rs+6−5
crates/pds-server/src/preferences.rs+1−2
crates/pds-server/src/proxy.rs+2−2
crates/pds-server/src/scopes.rs+4−1
crates/pds-server/src/server.rs+7−11
crates/pds-server/src/sessions.rs+3−6
crates/pds-server/src/single_use.rs+1−1
crates/pds-server/src/space_authority.rs+41−2
crates/pds-server/src/space_authz.rs+2−2
crates/pds-server/src/space_credentials.rs+1−2
crates/pds-server/src/space_notify.rs+7−7
crates/pds-server/src/space_repo.rs+92−5
crates/pds-server/src/store.rsnew+344−0
crates/pds-server/src/validation.rs+1−1
crates/pds-server/Cargo.toml+1−0
crates/pds-store/src/generations.rsnew+1202−0
1202 lines changed: not loaded until asked for.
crates/pds-store/src/lib.rs+250−47
harness/checks/blobs.mjs+35−18
harness/checks/crashes.mjs+14−7
harness/checks/federation.mjs+28−0
harness/checks/firehose.mjs+83−14
harness/checks/identity.mjs+12−3
harness/checks/lifecycle.mjs+14−4
harness/checks/limits.mjs+14−3
harness/checks/logging.mjsnew+186−0
harness/checks/oauth-clients.mjs+12−1
harness/checks/oauth.mjs+1−1
harness/checks/operations.mjsnew+609−0
609 lines changed: not loaded until asked for.
harness/checks/store.mjsnew+463−0
463 lines changed: not loaded until asked for.
harness/lib/args.mjs+9−3
harness/lib/env.mjs+4−2
harness/lib/mail.mjs+6−2
harness/lib/oauth.mjs+13−2
harness/lib/observe.mjsnew+289−0
harness/lib/otlp.mjsnew+200−0
harness/lib/processes.mjs+74−23
harness/lib/prometheus.mjsnew+67−0
harness/lib/services.mjs+4−0
harness/lib/xrpc.mjs+6−0
harness/code.mjsnew+29−0
harness/compare.mjs+25−4
harness/gates.mjs+58−34
harness/perf.mjsnew+229−0
spec/BLOBS.md+4−0
spec/DURABILITY.md+48−11
spec/FEDERATION.md+8−5
spec/LIMITS.md+8−9
spec/OPERATIONS.mdnew+405−0
405 lines changed: not loaded until asked for.