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

Faster gates; rules from the spec-only rebuilds; and scale (stacked, reviewed separately)

Merged chadtmiller.com asked to merge into main from chadtmiller.com/monolith:gatespeed
.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"
.knotless/workflows/gates.yml+13−2
@@ -18,13 +18,24 @@ steps:
with: {dir: harness}
- uses: chadtmiller.com/steps/npm-ci@1
with: {dir: harness/spaces}
# A step at a time, each under the runner's limit on one.
# A step at a time, each under the runner's limit on one. The tests'
# scratch directories are in memory where /dev/shm has room for them (they
# take 8 MB at most): the server's durability tests start it on its log
# cut at every byte, and each start syncs every log, which on a disk is
# most of the tests' time. The build's own temporary files stay on the
# disk.
- name: tools
run: rustup component add rustfmt clippy && (test -x /opt/cargo-deny/bin/cargo-deny || cargo install --locked --root /opt/cargo-deny cargo-deny)
- name: code
run: cd harness && PATH=/opt/cargo-deny/bin:/opt/node/bin:$PATH node gates.mjs code
- name: test
run: cargo test
run: |
cargo test --no-run
if [ -d /dev/shm ] && [ "$(df -Pk /dev/shm | awk 'NR==2 {print $4}')" -ge 49152 ]; then
export TMPDIR=/dev/shm
echo "the tests' scratch directories are in /dev/shm"
fi
cargo test
- name: build
run: cargo build --release -p pds
- name: compare
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+341−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"))
@@ -1792,3 +1792,340 @@ async fn a_deletion_cut_short() {
}
let _ = std::fs::remove_dir_all(&work);
}
/// The PLC directory cannot be read: `validDid` is `false`, the answer
/// `200`; an activation, by the owner or the admin, of an account or of a
/// DID no account has, is `502`, and a takedown lifted in the same call
/// stays lifted.
#[tokio::test]
async fn the_directory_down() {
let mut e = Env::new("life-plc-down").await;
let (did, token) = create(&e.s, "alice").await;
e.call(DEACTIVATE, Some(&token), json!({})).await.unwrap();
e.takedown(&did, true).await.unwrap();
let plc = std::mem::replace(&mut e.plc, "http://127.0.0.1:1".into());
e.reopen();
let got = e.call(CHECK, Some(&token), Json::Null).await.unwrap();
assert_eq!(
(&got["validDid"], &got["activated"]),
(&json!(false), &json!(false))
);
// The directory before the takedown.
assert_eq!(
e.call(ACTIVATE, Some(&token), Json::Null).await,
Err("UpstreamFailure".into())
);
let before = e.events().len();
let both = json!({ "subject": { "$type": REPO_REF, "did": did }, "takedown": { "applied": false }, "deactivated": { "applied": false } });
assert_eq!(e.admin(UPDATE, both).await, Err("UpstreamFailure".into()));
let state = e.admin_query(&[("did", &did)]).await.unwrap();
assert_eq!(
(&state["takedown"], &state["deactivated"]),
(&json!({ "applied": false }), &json!({ "applied": true }))
);
assert_eq!(
e.events()[before..].iter().map(brief).collect::<Vec<_>>(),
[format!("account {did} false deactivated")]
);
let nobody = json!({ "subject": { "$type": REPO_REF, "did": "did:plc:aaaaaaaaaaaaaaaaaaaaaaaa" }, "deactivated": { "applied": false } });
assert_eq!(e.admin(UPDATE, nobody).await, Err("UpstreamFailure".into()));
assert_eq!(e.events().len(), before + 1);
// Deactivating reads no directory.
e.call(DEACTIVATE, Some(&token), json!({})).await.unwrap();
// Up again, it is activated.
e.plc = plc;
e.reopen();
e.call(ACTIVATE, Some(&token), Json::Null).await.unwrap();
assert_eq!(
e.call(CHECK, Some(&token), Json::Null).await.unwrap()["validDid"],
json!(true)
);
}
/// A deleted account's activation, by its token or the admin: its token,
/// its body, then its DID document, whose rotation keys and endpoint are
/// looked at before its signing key, which is gone.
#[tokio::test]
async fn a_deleted_account_activated() {
let e = Env::new("life-deleted-activate").await;
let (did, token) = create(&e.s, "alice").await;
let app = app_session(&e, &token, "alice.test").await;
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 activate = json!({ "subject": { "$type": REPO_REF, "did": did }, "deactivated": { "applied": false } });
assert_eq!(
e.call(ACTIVATE, Some(&app), Json::Null).await,
Err("InvalidToken".into())
);
assert_eq!(
e.call(ACTIVATE, Some(&token), json!({})).await,
Err("InvalidRequest".into())
);
// Its document still names this server.
assert_eq!(
e.call(ACTIVATE, Some(&token), Json::Null).await,
Err("InternalServerError".into())
);
assert_eq!(
e.admin(UPDATE, activate.clone()).await,
Err("InternalServerError".into())
);
// Moved elsewhere.
let moved = reqwest::Client::new()
.put(format!("{}/{did}/data", e.plc))
.body("https://elsewhere.example")
.send()
.await
.unwrap();
assert!(moved.status().is_success());
assert_eq!(
e.call(ACTIVATE, Some(&token), Json::Null).await,
Err("InvalidRequest".into())
);
assert_eq!(
e.admin(UPDATE, activate).await,
Err("InvalidRequest".into())
);
}
/// A record's `uri` that names no record, of an account here, taken down
/// or not: `updateSubjectStatus` takes down nothing, `getSubjectStatus` is
/// `400 NotFound`; a handle as its authority is `500` to both.
#[tokio::test]
async fn uris_naming_no_record() {
let e = Env::new("life-uris").await;
let (did, token) = create(&e.s, "alice").await;
let rec = e
.call(
"com.atproto.repo.putRecord",
Some(&token),
put(&did, "one", json!({ "n": 1 })),
)
.await
.unwrap();
let strong = |uri: &str| json!({ "$type": STRONG_REF, "uri": uri, "cid": rec["cid"] });
for down in [false, true] {
e.takedown(&did, down).await.unwrap();
for uri in [format!("at://{did}"), format!("at://{did}/a.b.c")] {
let got = e
.admin(
UPDATE,
json!({ "subject": strong(&uri), "takedown": { "applied": true, "ref": "x" } }),
)
.await
.unwrap();
assert_eq!(got["subject"]["uri"], json!(uri));
assert_eq!(
e.admin_query(&[("uri", &uri)]).await,
Err("NotFound".into()),
"{uri}"
);
}
let status = e
.admin_query(&[("uri", rec["uri"].as_str().unwrap())])
.await
.unwrap();
assert_eq!(status["takedown"], json!({ "applied": false }));
}
for uri in [
"at://alice.test/a.b.c/one",
"at://nobody.test/a.b.c/one",
"at://alice.test",
] {
assert_eq!(
e.admin_query(&[("uri", uri)]).await,
Err("InternalServerError".into()),
"{uri}"
);
}
assert_eq!(
e.admin_query(&[("uri", "at://did:plc:aaaaaaaaaaaaaaaaaaaaaaaa/a.b.c/one")])
.await,
Err("NotFound".into())
);
}
/// The email methods, `getAccountInviteCodes` and the preferences, of an
/// account in each state: refused with the token, before the input, a
/// taken-down account `401 AccountTakedown` and a deleted one `403
/// AccountNotFound`, with no mail sent.
#[tokio::test]
async fn own_calls_by_state() {
let e = Env::new("life-own-rows").await;
let mut c = crate::Config {
mailer: crate::email::Mailer::sink(&e.sink),
..config(&e.plc)
};
c.proxy.appview = Some(crate::proxy::AppView {
url: "http://127.0.0.1:1".into(),
did: "did:web:appview.test".into(),
});
let dir = scratch("life-own-rows-app");
let s: Shared = Arc::new(Service::open(&dir, c).unwrap());
let (did, token) = create(&s, "alice").await;
let app = {
let pw = call(
&s,
"com.atproto.server.createAppPassword",
Some(&token),
json!({ "name": "app" }),
)
.await
.unwrap()["password"]
.clone();
tokens(
&call(
&s,
LOGIN,
None,
json!({ "identifier": "alice.test", "password": pw }),
)
.await
.unwrap(),
)
.0
};
/// A call: its method, its parameters and its input.
type Row<'a> = (&'a str, &'a [(String, String)], Json);
async fn rows(s: &Shared, token: &str) -> Vec<String> {
let none: &[(String, String)] = &[];
let bad = [("includeUsed".to_string(), "nope".to_string())];
let calls: Vec<Row> = vec![
(
"com.atproto.server.requestEmailConfirmation",
none,
Json::Null,
),
(
"com.atproto.server.confirmEmail",
none,
json!({ "email": 5 }),
),
("com.atproto.server.requestEmailUpdate", none, Json::Null),
(
"com.atproto.server.updateEmail",
none,
json!({ "email": 5 }),
),
("com.atproto.server.getAccountInviteCodes", none, Json::Null),
("com.atproto.server.getAccountInviteCodes", &bad, Json::Null),
("app.bsky.actor.getPreferences", none, Json::Null),
(
"app.bsky.actor.putPreferences",
none,
json!({ "preferences": 5 }),
),
(
"app.bsky.actor.putPreferences",
none,
json!({ "preferences": [] }),
),
];
let mut out = Vec::new();
for (nsid, p, b) in calls {
out.push(
call_with(s, nsid, Some(token), p, b)
.await
.map_or_else(|x| x, |_| "ok".to_string()),
);
}
out
}
let (inv, td, nf) = ("InvalidRequest", "AccountTakedown", "AccountNotFound");
assert_eq!(
rows(&s, &token).await,
["ok", inv, "ok", inv, "ok", inv, "ok", inv, "ok"]
);
call(&s, DEACTIVATE, Some(&token), json!({})).await.unwrap();
assert_eq!(
rows(&s, &token).await,
["ok", inv, "ok", inv, "NotFound", inv, "ok", inv, "ok"]
);
let mailed = sent(&e.sink).len();
let takedown = json!({ "subject": { "$type": REPO_REF, "did": did }, "takedown": { "applied": true, "ref": "r" } });
call_raw(
&s,
UPDATE,
Bearer::of(Some(&admin_header())),
&[],
&takedown.to_string(),
)
.await
.unwrap();
assert_eq!(
rows(&s, &token).await,
[td, td, td, td, td, inv, "ok", td, td]
);
// The token's own checks first.
for nsid in [
"com.atproto.server.requestEmailUpdate",
"com.atproto.server.getAccountInviteCodes",
] {
assert_eq!(
call(&s, nsid, Some(&app), Json::Null).await,
Err("InvalidToken".into()),
"{nsid}"
);
}
// A takendown session's token works for getPreferences alone.
let login =
json!({ "identifier": "alice.test", "password": "alice-pw", "allowTakendown": true });
let down = tokens(&call(&s, LOGIN, None, login).await.unwrap()).0;
assert_eq!(
call(&s, "app.bsky.actor.getPreferences", Some(&down), Json::Null).await,
Ok(json!({ "preferences": [] }))
);
for nsid in [
"app.bsky.actor.putPreferences",
"com.atproto.server.requestEmailConfirmation",
] {
assert_eq!(
call(&s, nsid, Some(&down), json!({ "preferences": [] })).await,
Err("InvalidToken".into()),
"{nsid}"
);
}
assert_eq!(sent(&e.sink).len(), mailed);
// Deleted.
let lift =
json!({ "subject": { "$type": REPO_REF, "did": did }, "takedown": { "applied": false } });
call_raw(
&s,
UPDATE,
Bearer::of(Some(&admin_header())),
&[],
&lift.to_string(),
)
.await
.unwrap();
call(&s, REQUEST_DELETE, Some(&token), Json::Null)
.await
.unwrap();
call(
&s,
DELETE,
None,
json!({ "did": did, "password": "alice-pw", "token": last_token(&e.sink) }),
)
.await
.unwrap();
let mailed = sent(&e.sink).len();
assert_eq!(
rows(&s, &token).await,
[nf, nf, nf, nf, nf, inv, "NotFound", nf, nf]
);
assert_eq!(
call(&s, "app.bsky.actor.getPreferences", Some(&down), Json::Null).await,
Err("NotFound".into())
);
assert_eq!(sent(&e.sink).len(), mailed);
let _ = std::fs::remove_dir_all(&dir);
}
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/scopes/tests.rs+56−0
@@ -275,6 +275,13 @@ fn refusals_name_the_missing_scope() {
names(Need::Blob("*/*"), "blob:*/*");
names(Need::Blob("a/b,c@d:e%f"), "blob:a/b,c@d:e%f");
names(Need::Blob("x/é\"#"), "blob:x/%C3%A9%22%23");
names(
Need::Rpc {
lxm: "chat.bsky.convo.listConvos",
aud: "did:plc:aaaaaaaaaaaaaaaaaaaaaaaa#a b",
},
"rpc:chat.bsky.convo.listConvos?aud=did:plc:aaaaaaaaaaaaaaaaaaaaaaaa%23a+b",
);
names(
Need::Account {
attr: "email",
@@ -672,6 +679,32 @@ async fn blob_uploads() {
)
.await;
assert_eq!(answer(&big).1, "PayloadTooLarge");
// Each byte of the header is its Latin-1 character, lowered, then UTF-8.
for (bytes, s) in [
(&b"image/p\xC9ng"[..], "blob:image/p%C3%A9ng"),
(&b"x/\xC3\x89"[..], "blob:x/%C3%A3%C2%89"),
(&b"\xC9/x"[..], "blob:%C3%A9/x"),
] {
let proof = c.proof("POST", "com.atproto.repo.uploadBlob", true);
let r = srv
.request("POST", "/xrpc/com.atproto.repo.uploadBlob")
.body(b"some bytes".to_vec())
.header(
"content-type",
reqwest::header::HeaderValue::from_bytes(bytes).unwrap(),
)
.header("authorization", format!("DPoP {}", c.access))
.header("dpop", proof);
let g = got(r).await;
if let Some(n) = g.header("dpop-nonce") {
c.app.nonce = Some(n);
}
if s.starts_with("blob:image/") {
ok(&g);
} else {
lacks(&g, s);
}
}
let _ = std::fs::remove_dir_all(&dir);
}
@@ -870,6 +903,29 @@ async fn reads() {
(g.status, g.error(), g.header("dpop-nonce")),
(401, "AuthenticationRequired".into(), None)
);
// A `DPoP` header that is not two words is a header of a bad form, first.
for (header, status, name) in [
("DPoP", 400, "InvalidToken"),
("DPoP a b", 400, "InvalidToken"),
("dpop abc", 401, "AuthenticationRequired"),
] {
let g = c
.send(
"POST",
"com.atproto.server.createAccount",
"",
Some("application/json"),
b"{}".to_vec(),
Some(header.into()),
None,
)
.await;
assert_eq!(
(g.status, g.error(), g.header("dpop-nonce")),
(status, name.into(), None),
"{header}"
);
}
let _ = std::fs::remove_dir_all(&dir);
}
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+102−33
@@ -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),
@@ -1000,7 +1058,20 @@ async fn upload_blob(
if media.is_empty() {
return invalid("Request encoding (Content-Type) required but not provided");
}
crate::scopes::may(call.bearer, &crate::scopes::Need::Blob(&media))?;
// What the scope needs reads each byte of the header as its Latin-1
// character, as the refusal names it (`spec/OAUTH-SCOPES.md`).
let raw = headers
.get(header::CONTENT_TYPE)
.map(|v| v.as_bytes())
.unwrap_or_default();
let latin1: String = raw
.split(|&b| b == b';')
.next()
.unwrap_or_default()
.iter()
.map(|&b| char::from(b))
.collect();
crate::scopes::may(call.bearer, &crate::scopes::Need::Blob(&latin1))?;
let too_large = || err(413, "PayloadTooLarge", "request entity too large");
let length = headers
.get(header::CONTENT_LENGTH)
@@ -2271,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
crates/pds-server/src/events.rs+462−71
533 lines changed: not loaded until asked for.
crates/pds-server/src/federation.rs+15−16
crates/pds-server/src/identity.rs+83−21
crates/pds-server/src/invites.rs+1−0
crates/pds-server/src/lib.rs+111−24
crates/pds-server/src/lifecycle.rs+140−58
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/preferences.rs+12−3
crates/pds-server/src/proxy.rs+32−0
crates/pds-server/src/read_after_write.rs+18−13
crates/pds-server/src/repo.rs+45−39
crates/pds-server/src/scopes.rs+23−1
crates/pds-server/src/server.rs+17−21
crates/pds-server/src/sessions.rs+73−9
crates/pds-server/src/space_authority.rs+6−5
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.
harness/checks/lifecycle.mjs+182−21
harness/checks/logging.mjs+32−2
harness/checks/oauth-scopes.mjs+47−1
harness/checks/operations.mjs+7−2
harness/checks/repository.mjs+19−2
harness/checks/scale.mjsnew+242−0
harness/lib/args.mjs+7−2
harness/lib/env.mjs+4−2
harness/lib/plc-proxy.mjs+12−5
harness/lib/processes.mjs+6−6
harness/compare.mjs+14−5
harness/gates.mjs+52−39
spec/EMAIL.md+3−1
spec/LIFECYCLE.md+129−52
spec/LIMITS.md+3−1
spec/OAUTH-SCOPES.md+26−6
spec/PDS.md+1−1
spec/PROXY.md+5−2
spec/STORE.md+62−10
Cargo.lock+32−0
Cargo.toml+8−4
Justfile+3−2
README.md+11−8