chadtmiller.com/monolith
An atproto PDS
0
0
A start reads no account: each is loaded on its first use
.knotless/workflows/store-bench.yml+6−4
| @@ -2,9 +2,11 @@ | ||
# it: the server's logs beside SQLite under the same commits, a log | ||
# replayed, and the server's start and memory by the number of accounts in | ||
# its service log. Its log is the tables, for bench/store/RESULTS.md. On a | ||
# pull that changes the benchmark, so that what it measures on the runner is | ||
# read with the change; and on main when the owner asks. It fails only if | ||
# the benchmark cannot build or run, never for a number. | ||
# pull that changes the benchmark, or the formats it writes itself: a log's | ||
# frames (crates/pds-store), an account's commit frames and the service | ||
# log's entries (the server's log.rs, compact.rs and store.rs), so that a | ||
# change to those says so here; and on main when the owner asks. It fails | ||
# only if the benchmark cannot build or run, never for a number. | ||
# | ||
# Node, the pages' packages and both builds are kept between runs. | ||
image: rust:1.98 | ||
| @@ -12,7 +14,7 @@ runners: [runner.knotless.dev] | ||
on: | ||
pull: | ||
base: [refs/heads/main] | ||
paths: [bench/store/**, .knotless/workflows/store-bench.yml] | ||
paths: [bench/store/**, .knotless/workflows/store-bench.yml, crates/pds-store/**, crates/pds-server/src/log.rs, crates/pds-server/src/compact.rs, crates/pds-server/src/store.rs] | ||
asked: {refs: [refs/heads/main]} | ||
cache: [target, bench/store/target, /usr/local/cargo/registry, /usr/local/rustup, /opt/node, web/node_modules] | ||
steps: | ||
bench/store/README.md+17−9
| @@ -69,15 +69,23 @@ log takes. | ||
on every account: the server (`target/release/pds`, with the scale run's | ||
`PDS_CACHE_BYTES`, 16 MiB) is started on an empty data directory, once | ||
unmeasured and then three times, the slowest the empty start; the | ||
accounts' entries are written | ||
into its service log as the server writes them, none with a repository; it | ||
is started on that log; one invite code is made, a write to the service log | ||
that makes its compaction due, and its resident memory sampled until the | ||
checkpoint is in place; then it is started on the checkpoint. The table has | ||
each start's time until `describeServer` answers, beside the bound | ||
`spec/STORE.md` gives a start (twice the empty start and 250 ms); the | ||
resident memory idle, and the most while compacting, beside the bound it | ||
gives memory (the empty start's, 32 MiB, the cache and 4 KiB an account). | ||
accounts' entries are written into its service log as the server writes | ||
them, none with a repository; it is started on that log; one invite code | ||
is made, a write to the service log that makes its compaction due, and its | ||
resident memory sampled until the checkpoint is in place; then it is | ||
started on the checkpoint. The table has: | ||
| ||
- the start on that log, all of it replayed. The server compacts its | ||
service log long before it is that long, so no server starts on one: | ||
this is what replaying one costs, and is held to no bound; | ||
- the start on the checkpoint, as a server that holds those accounts | ||
starts, until `describeServer` answers, beside the bound `spec/STORE.md` | ||
gives a start (twice the empty start and 250 ms), and its resident | ||
memory then; | ||
- how long the compaction took, and the most resident memory while it | ||
ran, beside the bound `spec/STORE.md` gives memory (the empty start's, | ||
32 MiB, the cache and 4 KiB an account). | ||
| ||
A figure over its bound is in bold. | ||
| ||
## Reading the results | ||
bench/store/RESULTS.md+81−78
| @@ -8,9 +8,9 @@ machine's numbers compare only with its own. | ||
The `store-bench` workflow's run on `runner.knotless.dev`, in the image | ||
`rust:1.98`. | ||
| ||
- Linux 6.8.0-146-generic x86_64, 12 cores, load 2.38; its files on the | ||
- Linux 6.8.0-146-generic x86_64, 12 cores, load 5.93; its files on the | ||
run's overlay over the runner's disk. Every sync is `fsync`. | ||
- cargo 1.98.1; node v24.22.1; the repository at `cb07f18`. | ||
- cargo 1.98.1; node v24.22.1; the repository at `66cde9b`. | ||
| ||
### Writes | ||
| ||
| @@ -18,64 +18,68 @@ The `store-bench` workflow's run on `runner.knotless.dev`, in the image | ||
| ||
| layout | per s | p50 ms | p99 ms | log syncs | ms per sync | | ||
|---|--:|--:|--:|--:|--:| | ||
| a log for each account (the server's) | 696 | 19.2 | 60.2 | 1447 | 19.64 | | ||
| one log for all | 618 | 16.4 | 156.5 | 292 | 8.19 | | ||
| SQLite for each account | 605 | 20.9 | 77.5 | | | | ||
| one SQLite for all | 107 | 10.5 | 1474.7 | | | | ||
| a log for each account (the server's) | 734 | 18.8 | 41.8 | 1444 | 18.64 | | ||
| one log for all | 787 | 16.4 | 56.1 | 236 | 7.95 | | ||
| SQLite for each account | 657 | 19.5 | 66.7 | | | | ||
| one SQLite for all | 106 | 113.4 | 696.1 | | | | ||
| ||
1500 commits from 4 writers over 40 accounts, each on disk (fsync) before it is answered. | ||
| ||
| layout | per s | p50 ms | p99 ms | log syncs | ms per sync | | ||
|---|--:|--:|--:|--:|--:| | ||
| a log for each account (the server's) | 205 | 18.5 | 37.0 | 1498 | 18.86 | | ||
| one log for all | 253 | 16.2 | 27.7 | 695 | 8.46 | | ||
| SQLite for each account | 189 | 19.3 | 46.5 | | | | ||
| one SQLite for all | 111 | 8.4 | 701.3 | | | | ||
| a log for each account (the server's) | 204 | 18.5 | 38.7 | 1500 | 18.70 | | ||
| one log for all | 218 | 16.1 | 43.3 | 750 | 9.14 | | ||
| SQLite for each account | 194 | 18.8 | 41.1 | | | | ||
| one SQLite for all | 112 | 33.0 | 70.3 | | | | ||
| ||
- Syncs of different files go on side by side here: sixteen writers make | ||
1447 syncs of 20 ms each in two seconds. So a log for each account is as | ||
fast as one log for all from 16 writers, and a fifth slower from 4, where | ||
one log's writers still share syncs. One log for all would buy little | ||
where the server is deployed; what it buys on the Mac is `F_FULLFSYNC`'s | ||
cost. | ||
1444 syncs of 19 ms each in two seconds. So a log for each account and | ||
one log for all are within a tenth of each other from 16 writers, either | ||
ahead from run to run (696 against 618 the run before this), and one log | ||
is a tenth to a fifth ahead from 4, where its writers still share syncs. | ||
One log for all would buy little where the server is deployed; what it | ||
buys on the Mac is `F_FULLFSYNC`'s cost. | ||
- SQLite for each account is a tenth or so behind the logs, never ahead. | ||
One SQLite for all is the slowest layout, at a sixth of the logs' rate | ||
from 16 writers, its p99 over a second. | ||
One SQLite for all is the slowest layout, at a seventh of the logs' rate | ||
from 16 writers. | ||
| ||
### A log replayed | ||
| ||
| log MiB | frames | replay ms | MiB per s | | ||
|--:|--:|--:|--:| | ||
| 64 | 6599 | 66 | 966 | | ||
| 512 | 52777 | 531 | 963 | | ||
| 64 | 6599 | 69 | 924 | | ||
| 512 | 52777 | 531 | 964 | | ||
| ||
### The service log by the number of accounts | ||
| ||
| accounts | email and password | service log MiB | start on the log ms | start on the checkpoint ms | start bound ms | idle RSS MiB | compaction ms | peak RSS compacting MiB | RSS bound MiB | | ||
| accounts | email and password | service log MiB | that log replayed at a start ms | start on the checkpoint ms | start bound ms | idle RSS MiB | compaction ms | peak RSS compacting MiB | RSS bound MiB | | ||
|--:|---|--:|--:|--:|--:|--:|--:|--:|--:| | ||
| 10000 | no | 7.1 | **413** | **383** | 314 | 32.3 | 191 | **103.6** | 103.2 | | ||
| 10000 | yes | 8.6 | **727** | **725** | 307 | 37.0 | 229 | **113.7** | 103.2 | | ||
| 30000 | no | 21.4 | **1129** | **1119** | 361 | 65.3 | 553 | **280.4** | 181.3 | | ||
| 30000 | yes | 25.8 | **4251** | **4204** | 313 | 80.5 | 615 | **312.9** | 181.3 | | ||
| 100000 | no | 71.4 | **3694** | **3602** | 310 | 172.6 | 1628 | **900.5** | 454.7 | | ||
| 100000 | yes | 85.9 | **115145** | **118117** | 310 | 219.0 | 1898 | **1008.2** | 454.8 | | ||
| ||
As on the Mac, below, which says why: over both bounds from 10000 | ||
accounts, and two minutes to start with 100000 that have emails. | ||
| 10000 | no | 7.1 | 104 | 27 | 307 | 16.9 | 243 | 33.0 | 103.8 | | ||
| 10000 | yes | 8.6 | 118 | 30 | 310 | 16.7 | 254 | 37.9 | 103.2 | | ||
| 30000 | no | 21.4 | 194 | 25 | 305 | 16.8 | 491 | 66.0 | 181.8 | | ||
| 30000 | yes | 25.8 | 224 | 26 | 306 | 16.9 | 568 | 84.1 | 181.6 | | ||
| 100000 | no | 71.4 | 572 | 30 | 305 | 17.6 | 1668 | 173.3 | 455.0 | | ||
| 100000 | yes | 85.9 | 673 | 28 | 312 | 17.7 | 1905 | 224.3 | 454.9 | | ||
| ||
A start on the checkpoint, and the memory it leaves, do not follow the | ||
accounts. The compaction here is of a log that holds every account, which | ||
this part writes and no server is left with: its time and memory follow | ||
that log. | ||
| ||
## Apple M1 Pro, macOS | ||
| ||
`just store-bench 10000 30000 100000 500000`. | ||
| ||
- Darwin 25.5.0 arm64, 8 cores, 32 GiB; APFS on the internal SSD | ||
(`/dev/disk3s5`). Every sync is `F_FULLFSYNC`, a flush through the | ||
drive's cache. | ||
- cargo 1.99.1; node v24.22.1; the repository at `bbbecb5`, the benchmark | ||
as it was added. | ||
- The machine was not alone: its load was 34 as the run began, from other | ||
work. The write part, run three more times that day under loads of 14 to | ||
37, gave 16 writers 423 to 465 commits per second on a log for each | ||
account, 887 to 1341 on one log for all, 216 to 227 on SQLite for each | ||
account and 178 to 197 on one SQLite for all: the order never changed, | ||
and one log for all is the row the load moves most. | ||
- cargo 1.99.1; node v24.22.1; the repository at `66cde9b`. | ||
- The machine was not alone: its load was 23 as the run began, from other | ||
work. Over five runs of the write part under loads of 14 to 37, 16 | ||
writers made 423 to 476 commits per second on a log for each account, | ||
569 to 1341 on one log for all, 209 to 227 on SQLite for each account and | ||
178 to 197 on one SQLite for all: the order never changed, and one log | ||
for all is the row the load moves most. | ||
| ||
### Writes | ||
| ||
| @@ -83,66 +87,65 @@ accounts, and two minutes to start with 100000 that have emails. | ||
| ||
| layout | per s | p50 ms | p99 ms | log syncs | ms per sync | | ||
|---|--:|--:|--:|--:|--:| | ||
| a log for each account (the server's) | 476 | 28.5 | 130.7 | 1450 | 22.45 | | ||
| one log for all | 569 | 19.9 | 169.8 | 516 | 4.87 | | ||
| SQLite for each account | 209 | 69.1 | 206.6 | | | | ||
| one SQLite for all | 192 | 64.2 | 361.5 | | | | ||
| SQLite for each account, fsync without F_FULLFSYNC | 3130 | 3.0 | 50.2 | | | | ||
| one SQLite for all, fsync without F_FULLFSYNC | 4826 | 2.2 | 12.7 | | | | ||
| a log for each account (the server's) | 423 | 32.6 | 107.5 | 1463 | 23.46 | | ||
| one log for all | 990 | 14.0 | 47.7 | 219 | 6.69 | | ||
| SQLite for each account | 221 | 66.3 | 181.1 | | | | ||
| one SQLite for all | 182 | 72.6 | 297.5 | | | | ||
| SQLite for each account, fsync without F_FULLFSYNC | 3075 | 4.4 | 25.1 | | | | ||
| one SQLite for all, fsync without F_FULLFSYNC | 4489 | 2.4 | 10.6 | | | | ||
| ||
1500 commits from 4 writers over 40 accounts, each on disk (F_FULLFSYNC) before it is answered. | ||
| ||
| layout | per s | p50 ms | p99 ms | log syncs | ms per sync | | ||
|---|--:|--:|--:|--:|--:| | ||
| a log for each account (the server's) | 229 | 16.6 | 35.9 | 1499 | 14.37 | | ||
| one log for all | 409 | 9.1 | 22.8 | 714 | 5.08 | | ||
| SQLite for each account | 222 | 18.0 | 35.1 | | | | ||
| one SQLite for all | 188 | 18.0 | 86.0 | | | | ||
| SQLite for each account, fsync without F_FULLFSYNC | 4592 | 0.7 | 5.5 | | | | ||
| one SQLite for all, fsync without F_FULLFSYNC | 5906 | 0.5 | 4.5 | | | | ||
| a log for each account (the server's) | 251 | 14.9 | 28.8 | 1498 | 13.79 | | ||
| one log for all | 451 | 9.0 | 18.9 | 701 | 4.68 | | ||
| SQLite for each account | 225 | 17.5 | 34.8 | | | | ||
| one SQLite for all | 190 | 19.3 | 69.4 | | | | ||
| SQLite for each account, fsync without F_FULLFSYNC | 4855 | 0.7 | 2.5 | | | | ||
| one SQLite for all, fsync without F_FULLFSYNC | 4825 | 0.6 | 5.7 | | | | ||
| ||
- At the same durability SQLite is no faster than the server's logs: level | ||
with them from 4 writers, half their rate from 16. Its rows without | ||
`F_FULLFSYNC` are what it does on macOS by default, and what the PDS | ||
benchmark's SQLite servers' write numbers are paid with | ||
(`../RESULTS.md`, "Durability differs"). | ||
- A log for each account is a sync for each account's commits: 1450 syncs | ||
for 1500 commits, each 22 ms as sixteen wait on the one drive, where one | ||
log for all made 516 of 5 ms. `F_FULLFSYNC` flushes the whole drive, so | ||
syncs of different files queue behind each other here; whether they do | ||
on Linux is what the runner's section says. | ||
- A log for each account is a sync for each account's commits: 1463 syncs | ||
for 1500 commits, each 23 ms as sixteen wait on the one drive, where one | ||
log for all made 219 of 7 ms. `F_FULLFSYNC` flushes the whole drive, so | ||
syncs of different files queue behind each other here; on Linux they do | ||
not, as the runner's section says. | ||
| ||
### A log replayed | ||
| ||
| log MiB | frames | replay ms | MiB per s | | ||
|--:|--:|--:|--:| | ||
| 64 | 6599 | 60 | 1064 | | ||
| 512 | 52777 | 480 | 1066 | | ||
| 64 | 6599 | 75 | 851 | | ||
| 512 | 52777 | 610 | 840 | | ||
| ||
A log may grow to its checkpoint's size before it is compacted, so an | ||
account whose table is half a gibibyte may take half a second of replay | ||
alone on its first request after a start, of the second `spec/STORE.md` | ||
gives it. | ||
account whose table is half a gibibyte may take over half a second of | ||
replay alone on its first request after a start, of the second | ||
`spec/STORE.md` gives it. | ||
| ||
### The service log by the number of accounts | ||
| ||
| accounts | email and password | service log MiB | start on the log ms | start on the checkpoint ms | start bound ms | idle RSS MiB | compaction ms | peak RSS compacting MiB | RSS bound MiB | | ||
| accounts | email and password | service log MiB | that log replayed at a start ms | start on the checkpoint ms | start bound ms | idle RSS MiB | compaction ms | peak RSS compacting MiB | RSS bound MiB | | ||
|--:|---|--:|--:|--:|--:|--:|--:|--:|--:| | ||
| 10000 | no | 7.1 | **293** | 289 | 292 | 35.0 | 94 | **108.3** | 105.2 | | ||
| 10000 | yes | 8.6 | **462** | **458** | 298 | 39.8 | 110 | **119.5** | 105.2 | | ||
| 30000 | no | 21.4 | **839** | **903** | 291 | 69.2 | 307 | **286.6** | 183.4 | | ||
| 30000 | yes | 25.8 | **3435** | **3457** | 298 | 84.3 | 361 | **309.3** | 183.4 | | ||
| 100000 | no | 71.4 | **4380** | **5120** | 303 | 128.1 | 1830 | **812.5** | 456.8 | | ||
| 100000 | yes | 85.9 | **74972** | **43015** | 316 | 162.0 | 996 | **949.8** | 456.8 | | ||
| ||
- The start grows with the accounts, about 27 µs each on a quiet machine | ||
(2680 ms for 100000): a sample of that start has four fifths of its time | ||
deriving each account's public key from its signing key as its entry is | ||
read. | ||
- With emails it grows with their square: each account's email is compared | ||
with every one before it. | ||
- Compacting the service log holds all of it in memory as parsed JSON, | ||
about 7 KiB an account for these accounts, over the memory bound from | ||
10000 accounts. | ||
- The scale run (`spec/STORE.md`, "How it is checked") makes 2000 accounts | ||
without passwords, and sees none of this. | ||
| 10000 | no | 7.1 | 65 | 22 | 296 | 18.9 | 153 | 35.3 | 105.6 | | ||
| 10000 | yes | 8.6 | 70 | 20 | 350 | 18.9 | 162 | 40.3 | 105.6 | | ||
| 30000 | no | 21.4 | 149 | 22 | 303 | 19.1 | 433 | 69.5 | 183.7 | | ||
| 30000 | yes | 25.8 | 182 | 24 | 299 | 19.1 | 517 | 84.5 | 183.8 | | ||
| 100000 | no | 71.4 | 453 | 26 | 297 | 19.7 | 1501 | 175.0 | 457.2 | | ||
| 100000 | yes | 85.9 | 491 | 25 | 305 | 19.9 | 1619 | 225.3 | 457.2 | | ||
| 500000 | no | 357.6 | 4764 | 32 | 295 | 23.8 | 7833 | 750.3 | 2019.7 | | ||
| 500000 | yes | 430.9 | 2597 | 36 | 296 | 24.4 | 8753 | 1000.2 | 2019.7 | | ||
| ||
- A start on the checkpoint is 20 to 36 ms from 10000 accounts to 500000, | ||
and leaves 19 to 24 MiB resident: neither follows the accounts. | ||
- Replaying a log goes at 75 to 170 MiB a second with the accounts' entries | ||
noted, so the service log is compacted at 8 MiB, whatever its | ||
checkpoint's size. | ||
- The compaction timed is of a log that holds every account, which this | ||
part writes and no server is left with: what it holds follows that log, | ||
about 2 KiB an account in it. | ||
bench/store/service.mjs+9−6
| @@ -173,10 +173,11 @@ async function measure(n, emails) { | ||
closeSync(fd) | ||
const logBytes = statSync(log).size | ||
| ||
// Started on the log. | ||
// Started on that log, all of it replayed: a log no server is left with | ||
// once it is past what it compacts at, so this is what replaying one | ||
// costs, not a start it is held to. | ||
const first = await start() | ||
await sleep(300) | ||
const idle = rss(first.proc.pid) | ||
| ||
// One write to the service log makes its compaction due: its memory is | ||
// sampled until the checkpoint is in place and the log it covers gone. | ||
| @@ -187,7 +188,7 @@ async function measure(n, emails) { | ||
}) | ||
if (!res.ok) throw new Error(`createInviteCode: ${res.status} ${await res.text()}`) | ||
const at = performance.now() | ||
let peak = idle | ||
let peak = rss(first.proc.pid) | ||
let folded = null | ||
while (performance.now() - at < 300_000) { | ||
peak = Math.max(peak, rss(first.proc.pid)) | ||
| @@ -199,8 +200,10 @@ async function measure(n, emails) { | ||
} | ||
await stop(first.proc) | ||
| ||
// Started on the checkpoint. | ||
// Started on the checkpoint, as a server that holds these accounts starts. | ||
const second = await start() | ||
await sleep(300) | ||
const idle = rss(second.proc.pid) | ||
await stop(second.proc) | ||
closeSync(out) | ||
rmSync(dir, { recursive: true, force: true }) | ||
| @@ -210,10 +213,10 @@ async function measure(n, emails) { | ||
const startBound = 2 * t0 + START_SLACK | ||
const rssBound = r0 + REQUEST_SLACK + CACHE_BYTES + PER_ACCOUNT * n | ||
const over = (x, bound, text) => (x > bound ? `**${text}**` : text) | ||
console.log(`| ${n} | ${emails ? 'yes' : 'no'} | ${MiB(logBytes)} | ${over(first.ms, startBound, ms(first.ms))} | ${over(second.ms, startBound, ms(second.ms))} | ${ms(startBound)} | ${MiB(idle)} | ${ms(folded)} | ${over(peak, rssBound, MiB(peak))} | ${MiB(rssBound)} |`) | ||
console.log(`| ${n} | ${emails ? 'yes' : 'no'} | ${MiB(logBytes)} | ${ms(first.ms)} | ${over(second.ms, startBound, ms(second.ms))} | ${ms(startBound)} | ${MiB(idle)} | ${ms(folded)} | ${over(peak, rssBound, MiB(peak))} | ${MiB(rssBound)} |`) | ||
} | ||
| ||
console.log('| accounts | email and password | service log MiB | start on the log ms | start on the checkpoint ms | start bound ms | idle RSS MiB | compaction ms | peak RSS compacting MiB | RSS bound MiB |') | ||
console.log('| accounts | email and password | service log MiB | that log replayed at a start ms | start on the checkpoint ms | start bound ms | idle RSS MiB | compaction ms | peak RSS compacting MiB | RSS bound MiB |') | ||
console.log('|--:|---|--:|--:|--:|--:|--:|--:|--:|--:|') | ||
for (const n of COUNTS) { | ||
for (const emails of [false, true]) await measure(n, emails) | ||
crates/pds-server/src/lifecycle/tests.rs+3−1
| @@ -1722,7 +1722,8 @@ async fn the_firehose_across_a_deletion() { | ||
| ||
/// A deletion's entry, cut at every byte: the account is there with | ||
/// everything it had, or gone with nothing of it served, its handle and | ||
/// email free, and its deletion on the firehose. | ||
/// email free, its deletion on the firehose, and its files gone once the | ||
/// directories of no account are swept. | ||
#[tokio::test] | ||
async fn a_deletion_cut_short() { | ||
let e = Env::new("life-cut").await; | ||
| @@ -1766,6 +1767,7 @@ async fn a_deletion_cut_short() { | ||
) | ||
.unwrap(); | ||
let s = open(&work, &e.plc); | ||
s.sweep_repos(); | ||
let gone = s.account(&did).is_none(); | ||
assert_eq!(gone, cut == after.len(), "cut at {cut}"); | ||
assert_eq!( | ||
crates/pds-server/src/migration/tests.rs+83−0
| @@ -1006,3 +1006,86 @@ async fn imports_need_free_space() { | ||
m.new.limits.disk.set_free(None); | ||
assert_eq!(import(&m.new, &token, &car).await, Ok(Json::Null)); | ||
} | ||
| ||
/// The DIDs `listRepos` lists. | ||
async fn repos(s: &Shared) -> Vec<String> { | ||
let listed = post(s, "com.atproto.sync.listRepos", None, Json::Null) | ||
.await | ||
.unwrap(); | ||
listed["repos"] | ||
.as_array() | ||
.unwrap() | ||
.iter() | ||
.map(|r| r["did"].as_str().unwrap().to_string()) | ||
.collect() | ||
} | ||
| ||
/// An account deleted that moves here again with its DID is one account | ||
/// again, listed once: whether its row before was in the table or its | ||
/// deletion is, across a compaction and a start that loads none. | ||
#[tokio::test] | ||
async fn an_account_deleted_moves_here_again() { | ||
let sink = scratch("migration-again-mail"); | ||
std::fs::create_dir_all(&sink).unwrap(); | ||
let configure = { | ||
let sink = sink.clone(); | ||
move |c: &mut crate::Config| { | ||
c.hostname = "new.test".into(); | ||
c.public_url = "http://new.test".into(); | ||
c.rotation_key = SigningKey::from_slice(&[7u8; 32]).unwrap(); | ||
c.mailer = crate::email::Mailer::sink(&sink); | ||
} | ||
}; | ||
let mut m = Move::start("migration-again", configure.clone()).await; | ||
m.dirs.push(sink.clone()); | ||
let delete = |token: String| { | ||
let (new, did, sink) = (m.new.clone(), m.did.clone(), sink.clone()); | ||
async move { | ||
call( | ||
&new, | ||
"com.atproto.server.requestAccountDelete", | ||
Some(&token), | ||
Json::Null, | ||
) | ||
.await | ||
.unwrap(); | ||
let body = json!({ "did": did, "password": "mover-pw", "token": crate::email::testing::last_token(&sink) }); | ||
call(&new, "com.atproto.server.deleteAccount", None, body) | ||
.await | ||
.unwrap(); | ||
} | ||
}; | ||
// Made, its row in the table; deleted and made again, both in the log. | ||
let token = m.moved().await; | ||
assert_eq!(repos(&m.new).await, [m.did.clone()]); | ||
m.new.log.compact().unwrap(); | ||
delete(token).await; | ||
assert_eq!(repos(&m.new).await, Vec::<String>::new()); | ||
let token = m.moved().await; | ||
assert_eq!(repos(&m.new).await, [m.did.clone()]); | ||
let session = post(&m.new, SESSION, Some(&token), Json::Null) | ||
.await | ||
.unwrap(); | ||
assert_eq!(session["handle"], json!("mover.test")); | ||
// The table covers the deletion and the making again. | ||
m.new.log.compact().unwrap(); | ||
assert_eq!(repos(&m.new).await, [m.did.clone()]); | ||
// Deleted and made again once more, and a start that loads none. | ||
delete(token).await; | ||
m.moved().await; | ||
assert_eq!(repos(&m.new).await, [m.did.clone()]); | ||
let (dir, plc) = (m.dirs[1].clone(), m.plc.url.clone()); | ||
drop(std::mem::replace(&mut m.new, m.old.clone())); | ||
for compacted in [false, true] { | ||
let new = open_with(&dir, &plc, |c| { | ||
configure(c); | ||
c.load_all = false; | ||
}); | ||
if compacted { | ||
new.log.compact().unwrap(); | ||
} | ||
assert_eq!(repos(&new).await, [m.did.clone()], "compacted: {compacted}"); | ||
let found = new.account("mover.test").map(|a| a.did.clone()); | ||
assert_eq!(found, Some(m.did.clone()), "compacted: {compacted}"); | ||
} | ||
} | ||
crates/pds-server/src/ops/metrics.rs+16−11
| @@ -128,22 +128,27 @@ impl Metrics { | ||
| ||
/// The exposition, with the gauges read from `svc` now. | ||
fn render(&self, svc: &Shared) -> String { | ||
let (accounts, all) = { | ||
// As `listRepos` lists them: the count the directory keeps. The | ||
// accounts' files are found by DID, of an account loaded or not. | ||
let (accounts, dids) = { | ||
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<_>>()) | ||
(d.count(), d.dids()) | ||
}; | ||
// Every generation's log not yet folded away, and the checkpoints: | ||
// of an account not loaded, as its files' sizes are, which loads none. | ||
// of an account or a store 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>(); | ||
+ dids | ||
.iter() | ||
.map(|did| { | ||
let loaded = read(&svc.directory).by_did.get(did).cloned(); | ||
match loaded { | ||
Some(a) => a.store.log_bytes(), | ||
None => crate::directory::files_bytes(&svc.dir, did), | ||
} | ||
}) | ||
.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/cache.rs+61−32
| @@ -1,15 +1,18 @@ | ||
//! What the server holds in memory of its accounts (`spec/STORE.md`, | ||
//! "Scale"), within `PDS_CACHE_BYTES`. | ||
//! | ||
//! **Always held**, for each account: its DID, handle, keys, state, mail | ||
//! and DID document (`Account`), a few KiB. **Held while used**: its store | ||
//! (`Store`), loaded from its checkpoint and log on its first use, a read or | ||
//! a write (`Slot`), and let go when it has not been used for `IDLE`, or | ||
//! when the stores held count more than the cache's share of | ||
//! `PDS_CACHE_BYTES`, least recently used first. A store is let go only with | ||
//! nothing of it in flight: no write waiting for its log to be on disk, no | ||
//! compaction of its log, no upload moving into place. Everything it holds | ||
//! is on disk by then, so letting it go is dropping it. | ||
//! **Held once used**, for each account: its DID, handle, keys, state, mail | ||
//! and DID document (`Account`), with its sessions, app passwords and | ||
//! preferences, a few KiB, made of its row of the service checkpoint and | ||
//! its entries of the service log on its first use (`directory`), and held | ||
//! from then on. **Held while used**: its store (`Store`), loaded from its | ||
//! checkpoint and log on its first use, a read or a write (`Slot`), and let | ||
//! go when it has not been used for `IDLE`, or when the stores held count | ||
//! more than the cache's share of `PDS_CACHE_BYTES`, least recently used | ||
//! first. A store is let go only with nothing of it in flight: no write | ||
//! waiting for its log to be on disk, no compaction of its log, no upload | ||
//! moving into place. Everything it holds is on disk by then, so letting it | ||
//! go is dropping it. | ||
//! | ||
//! **A start** loads no account but those marked in the service log | ||
//! (`Eager`): an account whose handle change is in flight, that has write | ||
| @@ -50,8 +53,9 @@ pub(crate) struct Ctx { | ||
pub events: Arc<Firehose>, | ||
pub eager: Arc<Eager>, | ||
pub cache: Cache, | ||
/// The blocks of the stores' tables and logs read from disk, shared. | ||
pub blocks: pds_store::table::BlockCache, | ||
/// The blocks of the stores' tables and logs read from disk, and of | ||
/// the service checkpoint's (`directory`), shared. | ||
pub blocks: Arc<pds_store::table::BlockCache>, | ||
/// While the server starts: a store loaded then with no commit gets | ||
/// its first from the start, once it knows where seqs go on from. | ||
pub starting: std::sync::atomic::AtomicBool, | ||
| @@ -273,11 +277,49 @@ pub(crate) fn sweep_every(svc: &crate::Shared) { | ||
| ||
// ---- An account's slot ------------------------------------------------------------- | ||
| ||
/// An account's signing key, made on first use. Making one derives its | ||
/// public key, which is most of what making an account of its entries | ||
/// would cost, and many an account is loaded to answer what signs nothing: | ||
/// until then it is the secret alone, checked to be one. | ||
pub(crate) struct Key { | ||
secret: k256::SecretKey, | ||
made: std::sync::OnceLock<SigningKey>, | ||
} | ||
| ||
impl Key { | ||
/// The key of these bytes, if they are one: as `SigningKey::from_slice` | ||
/// takes them. | ||
pub fn from_slice(bytes: &[u8]) -> Option<Key> { | ||
let secret = k256::SecretKey::from_slice(bytes).ok()?; | ||
Some(Key { | ||
secret, | ||
made: std::sync::OnceLock::new(), | ||
}) | ||
} | ||
| ||
/// A key made already. | ||
pub fn made(key: SigningKey) -> Key { | ||
Key { | ||
secret: k256::SecretKey::from(&key), | ||
made: std::sync::OnceLock::from(key), | ||
} | ||
} | ||
| ||
pub fn get(&self) -> &SigningKey { | ||
self.made.get_or_init(|| SigningKey::from(&self.secret)) | ||
} | ||
| ||
/// The secret's bytes, as an account's entry keeps them. | ||
pub fn to_bytes(&self) -> k256::FieldBytes { | ||
self.secret.to_bytes() | ||
} | ||
} | ||
| ||
/// An account's store: loaded on first use, let go when the cache needs | ||
/// the room or it is idle. | ||
pub(crate) struct Slot { | ||
account: Weak<Account>, | ||
key: SigningKey, | ||
key: Key, | ||
ctx: Arc<Ctx>, | ||
store: RwLock<Option<Box<Store>>>, | ||
/// When it was last used (`clock`). | ||
| @@ -341,12 +383,7 @@ pub(crate) fn unrecoverable(dir: &std::path::Path, why: &str) -> ! { | ||
| ||
impl Slot { | ||
/// The slot of `account`, signing with `key`, holding `store` if given. | ||
pub fn new( | ||
account: Weak<Account>, | ||
key: SigningKey, | ||
ctx: Arc<Ctx>, | ||
store: Option<Store>, | ||
) -> Slot { | ||
pub fn new(account: Weak<Account>, key: Key, ctx: Arc<Ctx>, store: Option<Store>) -> Slot { | ||
let slot = Slot { | ||
account, | ||
key, | ||
| @@ -366,7 +403,7 @@ impl Slot { | ||
fn compacted(&self, st: &Store) { | ||
let fold = crate::checkpoint::AccountFold { | ||
did: st.repo.did.clone(), | ||
key: self.key.clone(), | ||
key: self.key.get().clone(), | ||
window: self.ctx.window, | ||
account: self.account.clone(), | ||
}; | ||
| @@ -426,18 +463,10 @@ impl Slot { | ||
if let Some(st) = g.as_deref() { | ||
return st.wal.log_bytes() + st.wal.checkpoint_bytes(); | ||
} | ||
let Some(a) = self.account.upgrade() else { | ||
return 0; | ||
}; | ||
let layout = crate::store::account_layout(&self.ctx.dir, &a.did); | ||
let size = |p: std::path::PathBuf| std::fs::metadata(p).map_or(0, |m| m.len()); | ||
let logs: u64 = layout | ||
.generations() | ||
.unwrap_or_default() | ||
.into_iter() | ||
.map(|g| size(layout.log(g))) | ||
.sum(); | ||
logs + size(layout.checkpoint()) | ||
match self.account.upgrade() { | ||
Some(a) => crate::directory::files_bytes(&self.ctx.dir, &a.did), | ||
None => 0, | ||
} | ||
} | ||
| ||
/// Load its store if it is not held: an error if the data directory | ||
| @@ -473,7 +502,7 @@ impl Slot { | ||
fn open(&self) -> Result<Store, String> { | ||
let a = self.account.upgrade().ok_or("an account no longer held")?; | ||
let c = &self.ctx; | ||
let mut r = crate::log::open_repo(c, &a.did, &self.key)?; | ||
let mut r = crate::log::open_repo(c, &a.did, self.key.get())?; | ||
self.compacted(&r.store); | ||
if r.fresh && !c.starting.load(Ordering::SeqCst) { | ||
// With no events if it was made deactivated, moving here. | ||
crates/pds-server/src/checkpoint.rs+2−1
| @@ -1867,7 +1867,8 @@ fn table_events(t: &Table, cache: &BlockCache, out: &mut BTreeMap<u64, u64>) -> | ||
/// log is left open and nothing is kept in memory. For the firehose, which | ||
/// finds the events before a start in every account's files before it sends | ||
/// one, each then read through its store. The caller sees that the store is | ||
/// not loaded meanwhile (`cache::Slot::events`). | ||
/// not loaded meanwhile (`cache::Slot::events`, or of an account not loaded, | ||
/// `events::Firehose::find_old`). | ||
pub(crate) fn events_on_disk(ctx: &crate::cache::Ctx, did: &str) -> Result<EventsOnDisk, String> { | ||
let layout = crate::store::account_layout(&ctx.dir, did); | ||
let mut out: BTreeMap<u64, u64> = BTreeMap::new(); | ||
crates/pds-server/src/compact.rs+1174−222
1396 lines changed: not loaded until asked for.
crates/pds-server/src/directory.rsnew+1542−0
1542 lines changed: not loaded until asked for.
crates/pds-server/src/email.rs+24−38
| @@ -16,7 +16,7 @@ use crate::server::{password, password_length, valid_email}; | ||
use crate::sessions::{self, Token}; | ||
use crate::{ | ||
Account, Handler, Resp, Service, Shared, XrpcError, durable, err, internal, invalid, | ||
invalid_token, opt, read, required, write, | ||
invalid_token, opt, required, write, | ||
}; | ||
use lettre::message::{Mailbox, Message, header::ContentType}; | ||
use lettre::transport::smtp::authentication::Credentials; | ||
| @@ -166,6 +166,11 @@ impl Mail { | ||
self.tokens.get(&p).map(|i| i.token.as_str()) | ||
} | ||
| ||
/// Its password reset token, if it has one. | ||
pub(crate) fn reset_token(&self) -> Option<&str> { | ||
self.token(Purpose::ResetPassword) | ||
} | ||
| ||
/// Whether `given` is the account's token of `p`: `InvalidToken` if it is | ||
/// not, in any case, then `ExpiredToken` if it is past its 15 minutes at `now`. | ||
pub fn check(&self, p: Purpose, given: &str, now: u64) -> Result<(), XrpcError> { | ||
| @@ -183,7 +188,7 @@ impl Mail { | ||
} | ||
| ||
/// Make the change an entry says, as it is logged and as it is replayed. | ||
fn apply(&mut self, e: &Json) -> Result<(), String> { | ||
pub(crate) fn apply(&mut self, e: &Json) -> Result<(), String> { | ||
let text = |k: &str| { | ||
e[k].as_str() | ||
.ok_or_else(|| format!("an entry with no {k}: {e}")) | ||
| @@ -271,30 +276,9 @@ impl Mail { | ||
} | ||
} | ||
| ||
/// Replay an entry of `accounts.log` of the kinds in `ENTRIES`, given every | ||
/// account's `Mail` by DID. | ||
pub(crate) fn replay(mails: &mut HashMap<String, Mail>, e: &Json) -> Result<(), String> { | ||
let Some(did) = e["did"].as_str() else { | ||
return Err(format!("an entry with no did: {e}")); | ||
}; | ||
if e["t"] == "updateEmail" | ||
&& mails.iter().any(|(d, m)| { | ||
d != did && m.email.is_some() && m.email.as_deref() == e["email"].as_str() | ||
}) | ||
{ | ||
return Err(format!("an email changed to another account's: {e}")); | ||
} | ||
let Some(m) = mails.get_mut(did) else { | ||
return Err(format!( | ||
"a {} entry of {did:?}, which no account has", | ||
e["t"] | ||
)); | ||
}; | ||
m.apply(e) | ||
} | ||
| ||
/// Which account each password reset token is of, as `resetPassword` is | ||
/// given the token alone. It holds each account's current one. | ||
/// Which account, of those loaded, each password reset token is of, as | ||
/// `resetPassword` is given the token alone. It holds each one's current | ||
/// one; an account not loaded is found by the hints (`directory`). | ||
#[derive(Default)] | ||
pub(crate) struct Resets(Mutex<HashMap<String, String>>); | ||
| ||
| @@ -303,13 +287,18 @@ impl Resets { | ||
self.0.lock().unwrap_or_else(PoisonError::into_inner) | ||
} | ||
| ||
/// Note an account's reset token, as recovered. | ||
/// Note the reset token of an account loaded, if it has one. | ||
pub fn note(&self, did: &str, m: &Mail) { | ||
if let Some(t) = m.token(Purpose::ResetPassword) { | ||
self.lock().insert(t.to_string(), did.to_string()); | ||
} | ||
} | ||
| ||
/// The account, of those loaded, whose reset token this is. | ||
pub fn of(&self, token: &str) -> Option<String> { | ||
self.lock().get(token).cloned() | ||
} | ||
| ||
/// Forget a deleted account's token. | ||
pub fn forget(&self, did: &str) { | ||
self.lock().retain(|_, d| d != did); | ||
| @@ -777,6 +766,9 @@ async fn update_email(s: Shared, t: Token, b: Map<String, Json>) -> Result<Resp, | ||
let Some(old) = m.email.clone() else { | ||
return Ok(Resp::Nothing); | ||
}; | ||
// An account not loaded that may have the email is loaded | ||
// first: then those loaded say whether it is taken. | ||
s.load_hinted(crate::compact::EMAIL, &email); | ||
let mut d = write(&s.directory); | ||
if d.emails.get(&email).is_some_and(|other| other != did) | ||
|| d.claimed_emails.contains(&email) | ||
| @@ -811,14 +803,9 @@ async fn update_email(s: Shared, t: Token, b: Map<String, Json>) -> Result<Resp, | ||
async fn request_password_reset(s: Shared, b: Map<String, Json>) -> Result<Resp, XrpcError> { | ||
let email = required(&b, "email")?.to_lowercase(); | ||
let not_found = || invalid("account not found"); | ||
let a = { | ||
let d = read(&s.directory); | ||
d.emails | ||
.get(&email) | ||
.and_then(|did| d.by_did.get(did)) | ||
.cloned() | ||
let Some(a) = s.by_email(&email) else { | ||
return not_found(); | ||
}; | ||
let Some(a) = a else { return not_found() }; | ||
let out = { | ||
let mut m = lock(&a.mail); | ||
// Its email may have changed since it was looked up. | ||
| @@ -840,12 +827,10 @@ async fn reset_password(s: Shared, b: Map<String, Json>) -> Result<Resp, XrpcErr | ||
return invalid("Password too long"); | ||
} | ||
let token = token.to_ascii_uppercase(); | ||
let Some(did) = s.resets.lock().get(&token).cloned() else { | ||
return invalid_token(); | ||
}; | ||
let Some(a) = s.account(&did) else { | ||
let Some(a) = s.by_reset(&token) else { | ||
return invalid_token(); | ||
}; | ||
let did = a.did.clone(); | ||
let now = s.sessions.now(); | ||
lock(&a.mail).check(Purpose::ResetPassword, &token, now)?; | ||
// Hashed on the hash threads with no lock held; the token is checked | ||
| @@ -989,6 +974,7 @@ pub(crate) mod testing { | ||
mod tests { | ||
use super::testing::*; | ||
use super::*; | ||
use crate::read; | ||
use crate::testing::*; | ||
use std::path::PathBuf; | ||
use std::sync::atomic::Ordering; | ||
crates/pds-server/src/events.rs+30−10
crates/pds-server/src/federation.rs+34−23
crates/pds-server/src/identity.rs+3−0
crates/pds-server/src/lib.rs+28−46
crates/pds-server/src/lifecycle.rs+24−46
crates/pds-server/src/log.rs+506−194
700 lines changed: not loaded until asked for.