chadtmiller.com/monolith
An atproto PDS
0
0
Scale: memory bounded by a cache, start time independent of the accounts, repositories and the firehose streamed from disk
.cargo/config.tomlnew+7−0
| @@ -0,0 +1,7 @@ | ||
# jemalloc, the `pds` binary's allocator (crates/pds/src/main.rs), is built to | ||
# give memory back to the system as soon as it is freed: freed pages are kept | ||
# for no time at all. The server's resident memory is what spec/STORE.md's | ||
# bounds count, and a default build keeps what a large write freed for ten | ||
# seconds. `_RJEM_MALLOC_CONF` in the server's environment still overrides it. | ||
[env] | ||
JEMALLOC_SYS_WITH_MALLOC_CONF = "dirty_decay_ms:0,muzzy_decay_ms:0" | ||
crates/pds/src/main.rs+52−1
| @@ -2,6 +2,14 @@ | ||
| ||
#![forbid(unsafe_code)] | ||
| ||
/// jemalloc rather than the system's allocator, built to keep freed pages | ||
/// for no time at all (`.cargo/config.toml`): the server's resident memory | ||
/// is what `spec/STORE.md`'s "Scale" bounds, and the system's allocators | ||
/// keep what a large write freed resident, each in its own way. So memory | ||
/// follows what is in use, the same on Linux and macOS. | ||
#[global_allocator] | ||
static ALLOCATOR: tikv_jemallocator::Jemalloc = tikv_jemallocator::Jemalloc; | ||
| ||
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\ | ||
| @@ -10,13 +18,26 @@ const SERVE_HELP: &str = "Usage: pds serve\n\n\ | ||
by PDS_LOG_LEVEL, PDS_METRICS_PORT and the OTEL_* variables. SIGTERM or\n\ | ||
SIGINT shuts it down.\n"; | ||
| ||
/// No transparent huge pages for this process, where the system gives them | ||
/// to every process (Linux, set to `always`): with them a thread's stack, | ||
/// and each region the allocator maps, is resident 2 MiB at a time however | ||
/// little of it is used, and the server's resident memory follows its | ||
/// threads, not what it holds. A system that refuses is left as it is. | ||
fn small_pages() { | ||
#[cfg(target_os = "linux")] | ||
let _ = rustix::thread::disable_transparent_huge_pages(true); | ||
} | ||
| ||
fn main() { | ||
let args: Vec<String> = std::env::args().skip(1).collect(); | ||
if args.first().map(String::as_str) != Some("serve") { | ||
std::process::exit(pds_cli::run(&args)); | ||
} | ||
match args.get(1).map(String::as_str) { | ||
None => pds_server::run(), | ||
None => { | ||
small_pages(); | ||
pds_server::run() | ||
} | ||
Some("--help" | "-h") => print!("{SERVE_HELP}"), | ||
Some(a) => { | ||
eprint!("pds: pds serve takes no argument {a:?}\n\n{SERVE_HELP}"); | ||
| @@ -24,3 +45,33 @@ fn main() { | ||
} | ||
} | ||
} | ||
| ||
#[cfg(test)] | ||
mod tests { | ||
/// The server's memory is in the system's small pages. | ||
#[cfg(target_os = "linux")] | ||
#[test] | ||
fn no_huge_pages() { | ||
super::small_pages(); | ||
assert_eq!( | ||
rustix::thread::transparent_huge_pages_are_disabled(), | ||
Ok(true) | ||
); | ||
} | ||
| ||
/// The build is given the allocator's options, as `.cargo/config.toml` | ||
/// sets them for jemalloc's build and this crate's alike: a build | ||
/// without them keeps freed pages resident for seconds, past | ||
/// `spec/STORE.md`'s memory bound. What the allocator then does with | ||
/// them is the scale run's to hold (`harness/compare.mjs --scale`). | ||
#[test] | ||
fn the_allocator_keeps_no_freed_pages() { | ||
let built = option_env!("JEMALLOC_SYS_WITH_MALLOC_CONF").unwrap_or(""); | ||
for option in ["dirty_decay_ms:0", "muzzy_decay_ms:0"] { | ||
assert!( | ||
built.split(',').any(|o| o == option), | ||
"jemalloc built with {built:?}, without {option}" | ||
); | ||
} | ||
} | ||
} | ||
crates/pds/Cargo.toml+4−0
| @@ -5,5 +5,9 @@ edition.workspace = true | ||
publish.workspace = true | ||
| ||
[dependencies] | ||
tikv-jemallocator.workspace = true | ||
pds-cli.workspace = true | ||
pds-server.workspace = true | ||
| ||
[target.'cfg(target_os = "linux")'.dependencies] | ||
rustix.workspace = true | ||
crates/pds-repo/src/edit.rsnew+638−0
638 lines changed: not loaded until asked for.
crates/pds-repo/src/full.rsnew+919−0
919 lines changed: not loaded until asked for.
crates/pds-repo/src/lib.rs+601−680
1281 lines changed: not loaded until asked for.
crates/pds-server/src/lifecycle/tests.rs+4−4
| @@ -93,7 +93,7 @@ impl Env { | ||
fn events(&self) -> Vec<Json> { | ||
self.s | ||
.events | ||
.get(0, u64::MAX - 1, self.s.events.drops()) | ||
.get(&self.s, 0, u64::MAX - 1, self.s.events.drops()) | ||
.iter() | ||
.map(|f| decoded(f)) | ||
.collect() | ||
| @@ -1501,7 +1501,7 @@ async fn deleting_an_account() { | ||
); | ||
} | ||
let events_before: Vec<Json> = e.events(); | ||
let n = e.s.events.len(); | ||
let n = e.s.events.len(&e.s); | ||
// An Authorization header is ignored; the token in lower case is taken. | ||
assert_eq!( | ||
call_raw( | ||
| @@ -1705,7 +1705,7 @@ async fn the_firehose_across_a_deletion() { | ||
.unwrap(); | ||
let of = |drops: u64| -> Vec<String> { | ||
e.s.events | ||
.get(0, u64::MAX - 1, drops) | ||
.get(&e.s, 0, u64::MAX - 1, drops) | ||
.iter() | ||
.map(|f| brief(&decoded(f))) | ||
.filter(|b| b.contains(&did)) | ||
| @@ -1775,7 +1775,7 @@ async fn a_deletion_cut_short() { | ||
); | ||
let deletions = s | ||
.events | ||
.get(0, u64::MAX - 1, s.events.drops()) | ||
.get(&s, 0, u64::MAX - 1, s.events.drops()) | ||
.iter() | ||
.map(|f| decoded(f)) | ||
.filter(|ev| ev["status"] == json!("deleted")) | ||
crates/pds-server/src/oauth/page.rs+1−3
| @@ -285,9 +285,7 @@ fn account_json(svc: &Service, a: &Account) -> Json { | ||
out["email"] = json!(e); | ||
} | ||
let profile = crate::read(&a.store) | ||
.repo | ||
.records | ||
.get("app.bsky.actor.profile/self") | ||
.record("app.bsky.actor.profile/self") | ||
.map(|r| pds_repo::data::to_json(&r.value)); | ||
if let Some(p) = profile { | ||
if let Some(n) = p["displayName"].as_str() { | ||
crates/pds-server/src/ops/metrics.rs+5−4
| @@ -139,10 +139,11 @@ impl Metrics { | ||
.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>(); | ||
// Every generation's log not yet folded away, and the checkpoints: | ||
// of an account not loaded, as its files' sizes are, which loads none. | ||
let log_bytes = svc.log.log_bytes() | ||
+ svc.log.checkpoint_bytes() | ||
+ all.iter().map(|a| a.store.log_bytes()).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}"); | ||
crates/pds-server/src/space_credentials/tests.rs+1−5
| @@ -640,11 +640,7 @@ async fn credential_requests_are_refused_in_order() { | ||
assert_eq!(get, Err("400 InvalidRequest".into())); | ||
// 2. A credentialKid that is no P-256 key, before the token. | ||
let signing = crate::plc::did_key( | ||
s.account(&w.alice.0) | ||
.unwrap() | ||
.store | ||
.read() | ||
.unwrap() | ||
crate::read(&s.account(&w.alice.0).unwrap().store) | ||
.repo | ||
.verifying_key(), | ||
); | ||
crates/pds-server/src/blobs.rs+88−32
| @@ -39,8 +39,8 @@ use axum::extract::{Extension, State as AxState}; | ||
use axum::http::{HeaderMap, HeaderValue, Method, header}; | ||
use axum::response::Response; | ||
use http_body::{Frame, SizeHint}; | ||
use pds_repo::data::{V, cid_string, valid_cid_string}; | ||
use pds_repo::{Change, Op, OpResult, Repo}; | ||
use pds_repo::data::{V, cid_string, from_json, valid_cid_string}; | ||
use pds_repo::{Change, Op, OpResult}; | ||
use serde_json::{Map, Value as Json, json}; | ||
use sha2::{Digest, Sha256}; | ||
use std::collections::{BTreeMap, BTreeSet, HashMap}; | ||
| @@ -49,7 +49,7 @@ use std::io::{self, Read, Seek, SeekFrom, Write}; | ||
use std::ops::Bound::{Excluded, Unbounded}; | ||
use std::path::{Path, PathBuf}; | ||
use std::pin::Pin; | ||
use std::sync::{Arc, OnceLock}; | ||
use std::sync::{Arc, LazyLock, OnceLock}; | ||
use std::task::{Context, Poll}; | ||
| ||
/// The largest body `uploadBlob` takes, as `describeServer` answers it. | ||
| @@ -239,6 +239,28 @@ impl Blobs { | ||
(self.now, self.ttl) = (now, ttl); | ||
} | ||
| ||
/// Whether nothing of it is in flight: no upload moving into place, no | ||
/// file doomed and not yet removed. | ||
pub(crate) fn settled(&self) -> bool { | ||
self.placing.is_empty() && self.doomed.is_empty() | ||
} | ||
| ||
/// About the bytes it holds in memory. | ||
pub(crate) fn cost(&self) -> u64 { | ||
let refs: usize = self | ||
.records | ||
.iter() | ||
.map(|(p, (r, c))| { | ||
p.len() + r.len() + c.iter().map(|x| x.len() + 24).sum::<usize>() + 96 | ||
}) | ||
.sum(); | ||
(self.held.len() * 160 | ||
+ self.refs.len() * 96 | ||
+ self.space_refs.len() * 96 | ||
+ self.takedowns.len() * 128 | ||
+ refs) as u64 | ||
} | ||
| ||
/// Whether some record references `cid`, public or in a space repo. | ||
fn referenced(&self, cid: &str) -> bool { | ||
self.refs.contains_key(cid) || self.space_refs.contains_key(cid) | ||
| @@ -390,19 +412,20 @@ impl Blobs { | ||
/// deleted references what it holds now. A blob no record references any | ||
/// more is no longer held, and its file is doomed. What it changed is | ||
/// kept, to `undo` should the commit not reach the log. | ||
pub(crate) fn committed(&mut self, repo: &Repo, c: &Change) { | ||
pub(crate) fn committed(&mut self, c: &Change) { | ||
let mut undo = Undo { | ||
bytes: self.bytes, | ||
doomed: self.doomed.len(), | ||
..Default::default() | ||
}; | ||
let mut delta: BTreeMap<String, i64> = BTreeMap::new(); | ||
let written: BTreeMap<&String, Vec<String>> = c | ||
.puts | ||
.iter() | ||
.map(|(p, j)| (p, from_json(j).map(|v| cids_in(&v)).unwrap_or_default())) | ||
.collect(); | ||
for path in c.puts.iter().map(|(p, _)| p).chain(&c.dels) { | ||
let now = repo | ||
.records | ||
.get(path) | ||
.map(|r| cids_in(&r.value)) | ||
.unwrap_or_default(); | ||
let now = written.get(path).cloned().unwrap_or_default(); | ||
let before = self.records.remove(path); | ||
undo.records.push((path.clone(), before.clone())); | ||
let before = before.map(|(_, cids)| cids).unwrap_or_default(); | ||
| @@ -588,7 +611,8 @@ 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. An upload no | ||
/// every other file in `dir` goes, as no entry holds it, but an upload | ||
/// of this process's on its way in (`temp_prefix`). 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. | ||
| @@ -624,7 +648,7 @@ impl Blobs { | ||
if !e | ||
.file_name() | ||
.to_str() | ||
.is_some_and(|n| self.held.contains_key(n)) | ||
.is_some_and(|n| self.held.contains_key(n) || n.starts_with(temp_prefix())) | ||
{ | ||
std::fs::remove_file(e.path()) | ||
.map_err(|why| format!("{}: {why}", e.path().display()))?; | ||
| @@ -647,28 +671,35 @@ impl Blobs { | ||
.map(|(cid, h)| (cid.as_str(), h, self.takedowns.get(cid).map(String::as_str))) | ||
} | ||
| ||
/// Each record with blob refs: its path, the rev that last wrote it, and | ||
/// the CIDs it references: what a checkpoint keeps of them. | ||
pub(crate) fn record_list(&self) -> Vec<(&str, &str, &[String])> { | ||
let mut out: Vec<(&str, &str, &[String])> = self | ||
.records | ||
.iter() | ||
.map(|(p, (r, c))| (p.as_str(), r.as_str(), c.as_slice())) | ||
.collect(); | ||
out.sort_unstable(); | ||
out | ||
} | ||
| ||
/// 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`). | ||
/// those held, each with its takedown, and the records with blob refs, | ||
/// each with the rev that last wrote it and what it references. The | ||
/// space repos' references are counted as each is restored (`space_repo`). | ||
pub(crate) fn restore( | ||
repo: &Repo, | ||
records: Vec<(String, String, Vec<String>)>, | ||
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); | ||
for (path, rev, cids) in records { | ||
if cids.is_empty() { | ||
continue; | ||
return Err(format!("record {path} kept with no blob refs")); | ||
} | ||
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)); | ||
b.records.insert(path, (rev, cids)); | ||
} | ||
for (cid, h, takedown) in held { | ||
if !b.refs.contains_key(&cid) { | ||
| @@ -718,12 +749,19 @@ pub(crate) fn apply( | ||
} | ||
} | ||
let Store { | ||
repo, blobs, wal, .. | ||
repo, | ||
blobs, | ||
disk, | ||
ctx, | ||
wal, | ||
.. | ||
} = st; | ||
let results = repo.apply_checked(ops, swap_commit, || blobs.check(&refs))?; | ||
let results = repo.apply_checked(&disk.source(&ctx.blocks), 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); | ||
blobs.committed(c); | ||
} | ||
Ok(results) | ||
} | ||
| @@ -745,9 +783,15 @@ pub(crate) fn forget(svc: &Service, account: &Account, doomed: Vec<String>) { | ||
} | ||
| ||
/// Log as gone every upload held past its time with no record referencing | ||
/// it, and remove its file, for every account. | ||
/// it, and remove its file, for every account whose store is held: one not | ||
/// held has its swept when next loaded and written. | ||
pub(crate) fn sweep(svc: &Service) { | ||
let accounts: Vec<Arc<Account>> = read(&svc.directory).by_did.values().cloned().collect(); | ||
let accounts: Vec<Arc<Account>> = read(&svc.directory) | ||
.by_did | ||
.values() | ||
.filter(|a| a.store.is_loaded()) | ||
.cloned() | ||
.collect(); | ||
let (now, ttl) = (svc.limits.clock.now(), svc.config.blob_ttl); | ||
for a in accounts { | ||
let (wal, n, gone) = { | ||
| @@ -874,6 +918,16 @@ async fn drain(body: &mut Body, mut limit: u64) { | ||
} | ||
} | ||
| ||
/// How the names of this process's uploads on their way in begin, in an | ||
/// account's blob directory: a store loaded while one comes in, its | ||
/// account's first request or one since it was let go, removes the files a | ||
/// process before left there (`recover`, `log::open_repo`), not this one's. | ||
pub(crate) fn temp_prefix() -> &'static str { | ||
static PREFIX: LazyLock<String> = | ||
LazyLock::new(|| format!(".tmp-{}-", hex::encode(rand::random::<[u8; 6]>()))); | ||
&PREFIX | ||
} | ||
| ||
/// An upload's bytes on their way in, removed unless they are moved into place. | ||
struct Temp { | ||
path: PathBuf, | ||
| @@ -888,7 +942,11 @@ impl Temp { | ||
pds_store::sync_dir(parent)?; | ||
} | ||
} | ||
let path = dir.join(format!(".tmp-{}", hex::encode(rand::random::<[u8; 12]>()))); | ||
let path = dir.join(format!( | ||
"{}{}", | ||
temp_prefix(), | ||
hex::encode(rand::random::<[u8; 12]>()) | ||
)); | ||
let file = pds_store::open_private( | ||
&path, | ||
OpenOptions::new().create_new(true).read(true).write(true), | ||
| @@ -2284,9 +2342,7 @@ mod tests { | ||
get_error(&s, &did, &raw_cid(b"never"), None).await, | ||
"InvalidRequest" | ||
); | ||
let record = repo_of(&s, &did, |r| { | ||
cid_string(&r.records.values().next().unwrap().cid) | ||
}); | ||
let record = cid_string(&records_of(&s, &did)[0].1.cid); | ||
assert_eq!(get_error(&s, &did, &record, None).await, "InvalidRequest"); | ||
let bob = s.account("bob.test").unwrap().did.clone(); | ||
assert_eq!(get_error(&s, &bob, &cid, None).await, "InvalidRequest"); | ||
crates/pds-server/src/cache.rsnew+985−0
985 lines changed: not loaded until asked for.
crates/pds-server/src/checkpoint.rs+2254−1214
A large diff, not shown.
crates/pds-server/src/compact.rs+93−9
| @@ -25,8 +25,11 @@ use std::collections::HashMap; | ||
/// How long past its expiry a session is kept on disk. | ||
pub(crate) const MARGIN: u64 = 60 * 60; | ||
| ||
/// How many entries go in one frame of a checkpoint. | ||
const FRAME_ENTRIES: usize = 1000; | ||
/// How many entries go in one frame of a checkpoint: few, so that a start, | ||
/// which parses a frame whole before it replays it, holds little of it at | ||
/// once, and what it keeps of each account is not left spread among the | ||
/// pages a large frame's parse took (`spec/STORE.md`, "Memory"). | ||
const FRAME_ENTRIES: usize = 32; | ||
| ||
/// The kind of the service checkpoint's first entry. | ||
pub(crate) const HEADER: &str = "checkpoint"; | ||
| @@ -38,26 +41,58 @@ pub(crate) fn checkpoint( | ||
frames: Vec<Vec<Json>>, | ||
generation: u64, | ||
last: u64, | ||
ceiling: Option<u64>, | ||
now: u64, | ||
keep: impl Fn(u64, &[u8]) -> bool, | ||
) -> Result<Vec<u8>, String> { | ||
let (folded, seq) = fold(frames, now.saturating_sub(MARGIN), now, keep)?; | ||
let mut out = pds_store::frame(&[ | ||
json!({ "t": HEADER, "generation": generation, "lastSeq": seq.max(last) }), | ||
]); | ||
let (folded, seq, reserved) = fold(frames, now.saturating_sub(MARGIN), now, keep)?; | ||
let mut header = json!({ "t": HEADER, "generation": generation, "lastSeq": seq.max(last) }); | ||
if let Some(c) = reserved.max(ceiling) { | ||
header["ceiling"] = json!(c); | ||
} | ||
let mut out = pds_store::frame(&[header]); | ||
for f in &folded { | ||
out.extend(pds_store::frame(f)); | ||
} | ||
Ok(out) | ||
} | ||
| ||
/// A service checkpoint read: its generation, the last seq it names, and its frames after the first. | ||
/// A service checkpoint read: its generation, the last seq it names, the | ||
/// greatest seq reserved (`events::SEQS`), if any was, and its frames after | ||
/// the first. | ||
pub(crate) struct Read { | ||
pub generation: u64, | ||
pub last_seq: u64, | ||
pub ceiling: Option<u64>, | ||
pub frames: Vec<Vec<Json>>, | ||
} | ||
| ||
/// A service checkpoint's first frame: its generation, the last seq it | ||
/// names, the greatest seq reserved, if any was, and where its frames after | ||
/// the first begin. | ||
pub(crate) struct Header { | ||
pub generation: u64, | ||
pub last_seq: u64, | ||
pub ceiling: Option<u64>, | ||
pub body: usize, | ||
} | ||
| ||
/// Read a service checkpoint's header: the rest, its frames, are replayed | ||
/// as they are parsed, and must reach its end. | ||
pub(crate) fn header(bytes: &[u8]) -> Result<Header, String> { | ||
let first = bytes.get(..4).map_or(0, |n| { | ||
u32::from_le_bytes(n.try_into().expect("4 bytes")) as usize | ||
}); | ||
let body = (12 + first).min(bytes.len()); | ||
let r = read(&bytes[..body])?; | ||
Ok(Header { | ||
generation: r.generation, | ||
last_seq: r.last_seq, | ||
ceiling: r.ceiling, | ||
body, | ||
}) | ||
} | ||
| ||
/// Read a service checkpoint, which must be whole. | ||
pub(crate) fn read(bytes: &[u8]) -> Result<Read, String> { | ||
let (mut frames, good) = pds_store::scan(bytes); | ||
| @@ -75,24 +110,41 @@ pub(crate) fn read(bytes: &[u8]) -> Result<Read, String> { | ||
"a checkpoint header with no generation or lastSeq: {h}" | ||
)); | ||
}; | ||
let ceiling = match h.get("ceiling") { | ||
None => None, | ||
Some(c) => Some( | ||
c.as_u64() | ||
.ok_or_else(|| format!("a checkpoint header whose ceiling is not a number: {h}"))?, | ||
), | ||
}; | ||
Ok(Read { | ||
generation, | ||
last_seq, | ||
ceiling, | ||
frames, | ||
}) | ||
} | ||
| ||
/// What `fold` answers: the frames kept, the greatest seq of the events | ||
/// they hold, and of the seqs reserved, if any were. | ||
type Folded = (Vec<Vec<Json>>, u64, Option<u64>); | ||
| ||
/// What `frames` hold now, as entries, without sessions that expired before | ||
/// `before`, nor anything of the accounts deleted but their deletions whose | ||
/// events `keep` keeps, nor single-use values and revocations whose `until` | ||
/// is not after `now`, nor the events `keep` drops; and the greatest seq of | ||
/// the events they hold. | ||
/// the events they hold, and of the seqs reserved, if any were. Each | ||
/// account's handle is the last its marks gave it, and the marks kept are | ||
/// those standing (`cache`). | ||
fn fold( | ||
frames: Vec<Vec<Json>>, | ||
before: u64, | ||
now: u64, | ||
keep: impl Fn(u64, &[u8]) -> bool, | ||
) -> Result<(Vec<Vec<Json>>, u64), String> { | ||
) -> Result<Folded, String> { | ||
let mut handles: HashMap<String, String> = HashMap::new(); | ||
let mut marked: std::collections::BTreeSet<String> = std::collections::BTreeSet::new(); | ||
let mut ceiling: Option<u64> = None; | ||
let mut accounts = Vec::new(); | ||
let mut mails: HashMap<String, Mail> = HashMap::new(); | ||
let mut held = Vec::new(); | ||
| @@ -133,9 +185,31 @@ fn fold( | ||
if let Some(did) = lifecycle.replay(&e, is_account)? { | ||
accounts.retain(|a| a["did"] != did.as_str()); | ||
mails.remove(&did); | ||
handles.remove(&did); | ||
marked.remove(&did); | ||
gone.insert(did); | ||
} | ||
} | ||
Some(crate::cache::DIR) => { | ||
let did = e["did"] | ||
.as_str() | ||
.ok_or_else(|| format!("a mark with no did: {e}"))? | ||
.to_string(); | ||
if let Some(h) = e["handle"].as_str() { | ||
handles.insert(did.clone(), h.to_string()); | ||
} | ||
if e["eager"].as_bool() == Some(true) { | ||
marked.insert(did); | ||
} else { | ||
marked.remove(&did); | ||
} | ||
} | ||
Some(crate::events::SEQS) => { | ||
let upto = e["upto"] | ||
.as_u64() | ||
.ok_or_else(|| format!("seqs with no upto: {e}"))?; | ||
ceiling = Some(ceiling.unwrap_or(0).max(upto)); | ||
} | ||
Some(crate::preferences::ENTRY) => { | ||
let did = e["did"] | ||
.as_str() | ||
| @@ -173,6 +247,9 @@ fn fold( | ||
let m = &mails[&did]; | ||
a["email"] = json!(m.email); | ||
a["password"] = json!(m.password); | ||
if let Some(h) = handles.get(&did) { | ||
a["handle"] = json!(h); | ||
} | ||
entries.push(a); | ||
mailed.extend(m.entries(&did)); | ||
} | ||
| @@ -192,12 +269,19 @@ fn fold( | ||
.into_iter() | ||
.filter(|e| e["did"].as_str().is_some_and(|did| mails.contains_key(did))), | ||
); | ||
entries.extend( | ||
marked | ||
.iter() | ||
.filter(|did| mails.contains_key(*did)) | ||
.map(|did| crate::cache::dir_entry(did, None, true)), | ||
); | ||
Ok(( | ||
entries | ||
.chunks(FRAME_ENTRIES) | ||
.map(<[Json]>::to_vec) | ||
.collect(), | ||
lifecycle.last_seq(), | ||
ceiling, | ||
)) | ||
} | ||
| ||
crates/pds-server/src/events.rs+462−71
533 lines changed: not loaded until asked for.
crates/pds-server/src/federation.rs+15−16
| @@ -98,16 +98,18 @@ fn get_blocks( | ||
.get("cids") | ||
.and_then(Json::as_array) | ||
.map_or(&[][..], Vec::as_slice); | ||
s.with_repo(shown, required(p, "did")?, not_found, |_, r| { | ||
s.with_store(shown, required(p, "did")?, not_found, |_, st| { | ||
// A CID that is not a SHA-256 one of DAG-CBOR or raw names no block of a repository. | ||
let parsed: Option<Vec<Vec<u8>>> = cids | ||
.iter() | ||
.map(|c| c.as_str().and_then(parse_cid)) | ||
.collect(); | ||
parsed.and_then(|c| r.blocks_car(&c)).map_or_else( | ||
|| invalid("Could not find all requested blocks"), | ||
|car| Ok(Resp::Car(car)), | ||
) | ||
parsed | ||
.and_then(|c| st.repo.blocks_car(&st.source(), &c)) | ||
.map_or_else( | ||
|| invalid("Could not find all requested blocks"), | ||
|car| Ok(Resp::Car(car)), | ||
) | ||
}) | ||
} | ||
| ||
| @@ -119,8 +121,8 @@ fn get_record( | ||
p: &Map<String, Json>, | ||
) -> Result<Resp, XrpcError> { | ||
let path = format!("{}/{}", required(p, "collection")?, required(p, "rkey")?); | ||
s.with_repo(shown, required(p, "did")?, not_found, |_, r| { | ||
Ok(Resp::Car(r.proof_car(&path))) | ||
s.with_store(shown, required(p, "did")?, not_found, |_, st| { | ||
Ok(Resp::Car(st.repo.proof_car(&st.source(), &path))) | ||
}) | ||
} | ||
| ||
| @@ -213,6 +215,7 @@ mod tests { | ||
}; | ||
match answer(s, &call).await { | ||
Ok(Resp::Car(b)) => Ok(b), | ||
Ok(Resp::CarStream(c)) => Ok(c.bytes().unwrap()), | ||
Ok(Resp::Json(j) | Resp::Headed(j, _)) => panic!("{nsid} answered JSON: {j}"), | ||
Ok(Resp::Nothing) => panic!("{nsid} answered nothing"), | ||
Ok(Resp::Blob(_)) => panic!("{nsid} answered a blob"), | ||
| @@ -658,15 +661,11 @@ mod tests { | ||
let (bob, _) = create(&s, "bob").await; | ||
fill(&s, &alice, &ta, "a.b.c", "k", 60).await; | ||
fill(&s, &alice, &ta, "x.y.z", "r", 20).await; | ||
let (head, records) = repo_of(&s, &alice, |r| { | ||
( | ||
r.head.clone(), | ||
r.records | ||
.iter() | ||
.map(|(k, v)| (k.clone(), v.cid.clone())) | ||
.collect::<Vec<_>>(), | ||
) | ||
}); | ||
let head = repo_of(&s, &alice, |r| r.head.clone()); | ||
let records: Vec<(String, Vec<u8>)> = records_of(&s, &alice) | ||
.into_iter() | ||
.map(|(k, v)| (k, v.cid)) | ||
.collect(); | ||
assert!( | ||
records | ||
.iter() | ||
crates/pds-server/src/identity.rs+67−20
crates/pds-server/src/lib.rs+97−16
crates/pds-server/src/lifecycle.rs+24−9
crates/pds-server/src/limits.rs+3−3
crates/pds-server/src/log.rs+579−338
917 lines changed: not loaded until asked for.
crates/pds-server/src/mcp.rs+6−1
crates/pds-server/src/ops.rs+7−3
crates/pds-server/src/read_after_write.rs+18−13
crates/pds-server/src/repo.rs+45−39
crates/pds-server/src/server.rs+17−21
crates/pds-server/src/sessions.rs+73−9
crates/pds-server/src/space_notify.rs+33−11
crates/pds-server/src/store.rs+26−54
crates/pds-server/src/sync.rs+136−8
crates/pds-server/src/validation.rs+23−16
crates/pds-store/src/generations.rs+245−72
crates/pds-store/src/lib.rs+143−12
crates/pds-store/src/table.rsnew+809−0
809 lines changed: not loaded until asked for.