chadtmiller.com/monolith
An atproto PDS
0
0
After a shutdown, the firehose's first message comes within a second
crates/pds-server/src/events/index.rsnew+285−0
| @@ -0,0 +1,285 @@ | ||
//! The firehose's index: `events.index` in the data directory, which a | ||
//! shutdown leaves of the events in the backfill window that the accounts' | ||
//! logs hold, so that the start after it finds them without reading every | ||
//! account's files (`Firehose::write_index`, `Firehose::find_old`). | ||
//! | ||
//! The file is frames (`pds_store`). The first holds the header alone, | ||
//! `{"t": "events", "version", "ceiling", "made", "gone", "window", | ||
//! "events"}`: the greatest seq reserved in the service log when it was | ||
//! written, the greatest seq an event is known to have had, the greatest of | ||
//! an event let go as out of the window, the window in milliseconds, and | ||
//! how many events follow. Each frame after it holds up to `FRAME` of them, | ||
//! in order of seq, each `[seq, time, account]`: when it was made, in | ||
//! milliseconds since the epoch, and its account's DID where the file first | ||
//! names it, from then on how many DIDs the file named before that one. | ||
//! Neither the events' frames, which their accounts' stores hold, nor the | ||
//! service log's own events are in it. | ||
//! | ||
//! It is written whole to `events.index.tmp`, made durable, and renamed | ||
//! over the one before. Nothing is written to it as events are made: it is | ||
//! true until the next event is numbered, and a start takes it only if its | ||
//! ceiling is the one the start read from the service log, which the first | ||
//! event a run numbers reserves past (`Firehose::reserve`). One of another | ||
//! version, of a shorter window than the start's, cut short, or failing a | ||
//! check is as none. | ||
| ||
use crate::store::EVENTS_INDEX; | ||
use serde_json::{Value as Json, json}; | ||
use std::collections::HashMap; | ||
use std::collections::hash_map::Entry; | ||
use std::io::{self, Write}; | ||
use std::path::{Path, PathBuf}; | ||
use std::sync::Arc; | ||
| ||
/// What the header's `t` is. | ||
const HEADER: &str = "events"; | ||
| ||
/// The version of the format written, and the only one read. | ||
const VERSION: u64 = 1; | ||
| ||
/// The most events in a frame. | ||
const FRAME: usize = 4096; | ||
| ||
/// What an index holds. | ||
#[derive(Debug, PartialEq)] | ||
pub(super) struct Index { | ||
/// The greatest seq reserved in the service log when it was written. | ||
pub ceiling: u64, | ||
/// The greatest seq an event is known to have had. | ||
pub made: u64, | ||
/// The greatest seq of an event let go as out of the window. | ||
pub gone: u64, | ||
/// The backfill window it was written with, in milliseconds. | ||
pub window: u64, | ||
/// Each event's seq, its account and when it was made, in order of seq. | ||
pub events: Vec<(u64, Arc<str>, u64)>, | ||
} | ||
| ||
/// The index being written. | ||
fn tmp(dir: &Path) -> PathBuf { | ||
dir.join(format!("{EVENTS_INDEX}.tmp")) | ||
} | ||
| ||
/// An event's account, as its entry names it: its DID, or how many DIDs | ||
/// were named before it. | ||
enum Account<'a> { | ||
First(&'a str), | ||
Again(u64), | ||
} | ||
| ||
impl serde::Serialize for Account<'_> { | ||
fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> { | ||
match self { | ||
Account::First(did) => s.serialize_str(did), | ||
Account::Again(n) => s.serialize_u64(*n), | ||
} | ||
} | ||
} | ||
| ||
/// Leave `index` in `dir`, in place of the one before, durable. | ||
pub(super) fn write(dir: &Path, index: &Index) -> io::Result<()> { | ||
use serde::ser::{SerializeSeq, Serializer}; | ||
let tmp = tmp(dir); | ||
let file = pds_store::open_private( | ||
&tmp, | ||
std::fs::OpenOptions::new() | ||
.create(true) | ||
.truncate(true) | ||
.write(true), | ||
)?; | ||
let mut out = io::BufWriter::new(&file); | ||
out.write_all(&pds_store::frame(&[json!({ | ||
"t": HEADER, "version": VERSION, "ceiling": index.ceiling, "made": index.made, | ||
"gone": index.gone, "window": index.window, "events": index.events.len(), | ||
})]))?; | ||
// Each DID named so far, and how many were named before it. | ||
let mut named: HashMap<&str, u64> = HashMap::new(); | ||
for events in index.events.chunks(FRAME) { | ||
let frame = pds_store::frame_of(events.len() * 32, |out| { | ||
let mut s = serde_json::Serializer::new(out); | ||
let mut entries = s | ||
.serialize_seq(Some(events.len())) | ||
.expect("a frame serializes"); | ||
for (seq, did, at) in events { | ||
let did: &str = did; | ||
let before = named.len() as u64; | ||
let account = match named.entry(did) { | ||
Entry::Occupied(n) => Account::Again(*n.get()), | ||
Entry::Vacant(n) => { | ||
n.insert(before); | ||
Account::First(did) | ||
} | ||
}; | ||
entries | ||
.serialize_element(&(seq, at, account)) | ||
.expect("an event serializes"); | ||
} | ||
entries.end().expect("a frame serializes"); | ||
}); | ||
out.write_all(&frame)?; | ||
} | ||
out.flush()?; | ||
drop(out); | ||
file.sync_all()?; | ||
std::fs::rename(&tmp, dir.join(EVENTS_INDEX))?; | ||
pds_store::sync_dir(dir) | ||
} | ||
| ||
/// The header of an index a start may take, its ceiling `ceiling` and its | ||
/// window no shorter than `window`, with no event yet, and how many follow. | ||
fn header(entries: &[Json], ceiling: u64, window: u64) -> Option<(Index, u64)> { | ||
let [h] = entries else { | ||
return None; | ||
}; | ||
let n = |k: &str| h[k].as_u64(); | ||
if h["t"] != HEADER || n("version")? != VERSION { | ||
return None; | ||
} | ||
let index = Index { | ||
ceiling: n("ceiling")?, | ||
made: n("made")?, | ||
gone: n("gone")?, | ||
window: n("window")?, | ||
events: Vec::new(), | ||
}; | ||
(index.ceiling == ceiling && index.window >= window).then_some((index, n("events")?)) | ||
} | ||
| ||
/// An event as its entry has it, `dids` the DIDs named so far. | ||
fn event(e: &Json, dids: &mut Vec<Arc<str>>) -> Option<(u64, Arc<str>, u64)> { | ||
let [seq, at, account] = e.as_array()?.as_slice() else { | ||
return None; | ||
}; | ||
let did = match account { | ||
Json::String(did) => { | ||
dids.push(Arc::from(did.as_str())); | ||
dids.last()?.clone() | ||
} | ||
n => dids.get(usize::try_from(n.as_u64()?).ok()?)?.clone(), | ||
}; | ||
Some((seq.as_u64()?, did, at.as_u64()?)) | ||
} | ||
| ||
/// The index in `dir`, if it is whole and one a start may take: of this | ||
/// version, its ceiling `ceiling`, its window no shorter than `window`, and | ||
/// its events in order, none past the last it says was made. What a write | ||
/// cut short left beside it is removed. | ||
pub(super) fn read(dir: &Path, ceiling: u64, window: u64) -> Option<Index> { | ||
let _ = std::fs::remove_file(tmp(dir)); | ||
let mut index: Option<Index> = None; | ||
let mut count = 0; | ||
let mut dids: Vec<Arc<str>> = Vec::new(); | ||
let read = pds_store::scan_file(&dir.join(EVENTS_INDEX), |_, _, entries| { | ||
let Some(index) = &mut index else { | ||
let (found, events) = header(&entries, ceiling, window).ok_or_else(String::new)?; | ||
(index, count) = (Some(found), events); | ||
return Ok(()); | ||
}; | ||
for e in &entries { | ||
let e = event(e, &mut dids).ok_or_else(String::new)?; | ||
if e.0 > index.made || index.events.last().is_some_and(|last| last.0 >= e.0) { | ||
return Err(String::new()); | ||
} | ||
index.events.push(e); | ||
} | ||
Ok(()) | ||
}); | ||
match read { | ||
Ok(Ok((whole, size))) if whole == size => { | ||
index.filter(|index| index.events.len() as u64 == count) | ||
} | ||
_ => None, | ||
} | ||
} | ||
| ||
#[cfg(test)] | ||
mod tests { | ||
use super::*; | ||
| ||
fn index(events: usize) -> Index { | ||
let did = |n: usize| -> Arc<str> { Arc::from(format!("did:plc:{}", n % 7).as_str()) }; | ||
Index { | ||
ceiling: 9000, | ||
made: 2 * events as u64 + 5, | ||
gone: 3, | ||
window: 1000, | ||
events: (0..events) | ||
.map(|n| (2 * n as u64 + 4, did(n * n), 1_700_000_000_000 + n as u64)) | ||
.collect(), | ||
} | ||
} | ||
| ||
/// An index is read as it was written, the one before replaced; and by | ||
/// no start that read another ceiling, or keeps a longer window. | ||
#[test] | ||
fn read_as_written() { | ||
let dir = crate::testing::scratch("events-index"); | ||
std::fs::create_dir_all(&dir).unwrap(); | ||
assert_eq!(read(&dir, 9000, 1000), None); | ||
for events in [3, 0, FRAME, 2 * FRAME + 1] { | ||
let index = index(events); | ||
write(&dir, &index).unwrap(); | ||
assert!(!tmp(&dir).exists()); | ||
assert_eq!(read(&dir, 9000, 1000).as_ref(), Some(&index)); | ||
assert_eq!(read(&dir, 9000, 999).as_ref(), Some(&index)); | ||
assert_eq!(read(&dir, 9000, 1001), None); | ||
assert_eq!(read(&dir, 9001, 1000), None); | ||
assert_eq!(read(&dir, 8999, 1000), None); | ||
} | ||
// An account's events share its DID, as read. | ||
write(&dir, &index(20)).unwrap(); | ||
let events = read(&dir, 9000, 1000).unwrap().events; | ||
assert!(Arc::ptr_eq(&events[0].1, &events[7].1)); | ||
let _ = std::fs::remove_dir_all(&dir); | ||
} | ||
| ||
/// An index cut short at any byte, with a byte changed, with more after | ||
/// it, or whose events are not as its header says, is as none; and what | ||
/// a write cut short left beside it is removed. | ||
#[test] | ||
fn checked_as_read() { | ||
let dir = crate::testing::scratch("events-index-cut"); | ||
std::fs::create_dir_all(&dir).unwrap(); | ||
let index = index(FRAME + 9); | ||
write(&dir, &index).unwrap(); | ||
let path = dir.join(EVENTS_INDEX); | ||
let whole = std::fs::read(&path).unwrap(); | ||
let frames = pds_store::scan(&whole).0; | ||
assert_eq!(frames.len(), 3); | ||
let put = |bytes: &[u8]| std::fs::write(&path, bytes).unwrap(); | ||
let cuts = (0..400).chain((400..whole.len()).step_by(127)); | ||
for cut in cuts.chain(whole.len() - 40..whole.len()) { | ||
put(&whole[..cut]); | ||
assert_eq!(read(&dir, 9000, 1000), None, "cut at {cut}"); | ||
} | ||
for at in (0..whole.len()).step_by(997) { | ||
let mut bytes = whole.clone(); | ||
bytes[at] ^= 1; | ||
put(&bytes); | ||
assert_eq!(read(&dir, 9000, 1000), None, "changed at {at}"); | ||
} | ||
put(&[&whole[..], b"more"].concat()); | ||
assert_eq!(read(&dir, 9000, 1000), None); | ||
// Whole frames, but not the events the header counts, or not in order. | ||
let bytes = |frames: &[&Vec<Json>]| -> Vec<u8> { | ||
frames.iter().flat_map(|f| pds_store::frame(f)).collect() | ||
}; | ||
put(&bytes(&[&frames[0], &frames[1]])); | ||
assert_eq!(read(&dir, 9000, 1000), None); | ||
put(&bytes(&[&frames[0], &frames[1], &frames[2], &frames[2]])); | ||
assert_eq!(read(&dir, 9000, 1000), None); | ||
let mut swapped = frames[2].clone(); | ||
swapped.swap(3, 4); | ||
put(&bytes(&[&frames[0], &frames[1], &swapped])); | ||
assert_eq!(read(&dir, 9000, 1000), None); | ||
let mut versioned = frames[0].clone(); | ||
versioned[0]["version"] = json!(VERSION + 1); | ||
put(&bytes(&[&versioned, &frames[1], &frames[2]])); | ||
assert_eq!(read(&dir, 9000, 1000), None); | ||
put(&whole); | ||
std::fs::write(tmp(&dir), &whole[..whole.len() / 2]).unwrap(); | ||
assert_eq!(read(&dir, 9000, 1000), Some(index)); | ||
assert!(!tmp(&dir).exists()); | ||
let _ = std::fs::remove_dir_all(&dir); | ||
} | ||
} | ||
crates/pds-server/src/events.rs+1367−23
1390 lines changed: not loaded until asked for.
crates/pds-server/src/lib.rs+3−0
| @@ -746,6 +746,9 @@ pub fn run() { | ||
identity::settle_unfinished(&svc); | ||
// Directories of no account go while it serves. | ||
directory::sweep_once(&svc); | ||
// The firehose's events made before the start are taken from the | ||
// index a shutdown left of them, if it holds, while it serves. | ||
events::find_indexed_soon(&svc); | ||
blobs::sweep_every(&svc); | ||
blobstore::delete_every(&svc); | ||
cache::sweep_every(&svc); | ||
crates/pds-server/src/lifecycle.rs+5−1
| @@ -640,6 +640,7 @@ fn change(s: &Service, a: &Account, c: Change) -> Result<(u64, Landing), XrpcErr | ||
Landing { | ||
seq, | ||
frames: frames.into_iter().map(Into::into).collect(), | ||
times: Vec::new(), | ||
}, | ||
)) | ||
}) | ||
| @@ -684,6 +685,7 @@ async fn announce(s: &Shared, did: &str) -> Result<(), XrpcError> { | ||
Landing { | ||
seq, | ||
frames: vec![frame.into()], | ||
times: Vec::new(), | ||
}, | ||
) | ||
}; | ||
| @@ -719,6 +721,7 @@ pub(crate) async fn tell( | ||
Landing { | ||
seq, | ||
frames: vec![frame.into()], | ||
times: Vec::new(), | ||
}, | ||
) | ||
}; | ||
| @@ -975,7 +978,8 @@ fn remove( | ||
s.ctx.eager.forget(&a.did); | ||
state.deleted = true; | ||
d.remove(a, m.email.as_deref(), at.generation); | ||
Ok((n, Landing { seq, frames: vec![frame.into()] }, objects)) | ||
let landing = Landing { seq, frames: vec![frame.into()], times: Vec::new() }; | ||
Ok((n, landing, objects)) | ||
})?; | ||
s.sessions.forget(&a.did); | ||
s.resets.forget(&a.did); | ||
crates/pds-server/src/log.rs+16−1
| @@ -29,7 +29,13 @@ | ||
//! write notifications waiting to be sent again, and the registrations and | ||
//! deletion notices of its spaces (`space_notify::ENTRIES`); | ||
//! - `repos/<did>/blobs/<cid>`, the bytes of each blob it holds (`blobs`), | ||
//! or with blobs in a bucket, none, and the mark `blobstore` (`blobstore`). | ||
//! or with blobs in a bucket, none, and the mark `blobstore` (`blobstore`); | ||
//! - `events.index`, which a shutdown leaves: of each firehose event in the | ||
//! backfill window that an account's log holds, its seq, account and time, | ||
//! so that the start after it finds them without reading the accounts' | ||
//! logs (`events::index`). It holds nothing the logs do not: a start | ||
//! reads the logs instead, on first need, where an event was numbered | ||
//! after the index was left, as before a kill, or where it is cut short. | ||
//! | ||
//! Each log is compacted into its checkpoint, generation by generation | ||
//! (`store`, `pds_store`). A start reads the service checkpoint's summary | ||
| @@ -366,6 +372,7 @@ fn append_events( | ||
Ok(Landing { | ||
seq, | ||
frames: frames.into_iter().map(Bytes::from).collect(), | ||
times, | ||
}) | ||
} | ||
| ||
| @@ -907,6 +914,14 @@ impl Service { | ||
.raise(last) | ||
.map_err(|e| format!("{ACCOUNTS_LOG}: {e}"))?; | ||
} | ||
// With no account, no store holds an event made before this start: | ||
// the firehose has them all, and a shutdown may leave its index. | ||
{ | ||
let d = crate::read(&svc.directory); | ||
if d.count() == 0 && d.dids().is_empty() { | ||
svc.events.none_before(); | ||
} | ||
} | ||
// An account whose repository has no commit yet gets its first, | ||
// with no events if it was made deactivated, moving here. | ||
for a in &loading { | ||
crates/pds-server/src/ops.rs+22−12
| @@ -293,8 +293,9 @@ pub(crate) fn signals() -> impl Future<Output = &'static str> { | ||
} | ||
| ||
/// Shut down, the server having stopped taking connections and its requests | ||
/// finished: close the firehose's subscriptions, sync what is written, | ||
/// export the spans held, leave the mark of a shutdown, say so, and exit 0. | ||
/// finished: close the firehose's subscriptions, sync what is written and | ||
/// leave the firehose's index (`settle`), export the spans held, leave the | ||
/// mark of a shutdown, say so, and exit 0. | ||
pub(crate) async fn shutdown(svc: &Shared, signal: &'static str) -> ! { | ||
svc.events.close(); | ||
for _ in 0..40 { | ||
| @@ -304,16 +305,7 @@ pub(crate) async fn shutdown(svc: &Shared, signal: &'static str) -> ! { | ||
tokio::time::sleep(Duration::from_millis(25)).await; | ||
} | ||
let s = svc.clone(); | ||
let synced = tokio::task::spawn_blocking(move || -> std::io::Result<()> { | ||
s.log.wait(s.log.written())?; | ||
let accounts: Vec<_> = crate::read(&s.directory).by_did.values().cloned().collect(); | ||
// A store not held has nothing written that is not on disk. | ||
for wal in accounts.iter().filter_map(|a| a.store.loaded_wal()) { | ||
wal.wait(wal.written())?; | ||
} | ||
Ok(()) | ||
}) | ||
.await; | ||
let synced = tokio::task::spawn_blocking(move || settle(&s)).await; | ||
if let Some(e) = &ops().exporter { | ||
e.flush(Instant::now() + FLUSH).await; | ||
} | ||
| @@ -340,6 +332,24 @@ pub(crate) async fn shutdown(svc: &Shared, signal: &'static str) -> ! { | ||
std::process::exit(0); | ||
} | ||
| ||
/// What a shutdown leaves on disk: no event is numbered from now on, what | ||
/// is written is made durable, and then the firehose's events in the window | ||
/// are indexed for the next start (`events::Firehose::write_index`), if | ||
/// every one numbered had reached its log before the logs were synced. | ||
pub(crate) fn settle(s: &crate::Service) -> std::io::Result<()> { | ||
let landed = s.events.seal(); | ||
s.log.wait(s.log.written())?; | ||
let accounts: Vec<_> = crate::read(&s.directory).by_did.values().cloned().collect(); | ||
// A store not held has nothing written that is not on disk. | ||
for wal in accounts.iter().filter_map(|a| a.store.loaded_wal()) { | ||
wal.wait(wal.written())?; | ||
} | ||
if landed && let Err(e) = s.events.write_index(&s.dir) { | ||
failed("writing the firehose's index", e); | ||
} | ||
Ok(()) | ||
} | ||
| ||
// ------------------------------------------------------------ requests | ||
| ||
/// The trace context of the request being answered, if any, for what is | ||
crates/pds-server/src/store.rs+16−5
| @@ -7,8 +7,11 @@ | ||
//! checkpoint `accounts.checkpoint`; for each account, in `repos/<did>/`, | ||
//! its log `repo.<g>.log`, its checkpoint `repo.checkpoint`, and `blobs/`, | ||
//! or with blobs in a bucket, none, and the mark `blobstore` (`blobstore`); | ||
//! and `lock`, which the process using the directory holds (`hold`). | ||
//! While a checkpoint is written, `<checkpoint>.tmp` is beside it. | ||
//! `lock`, which the process using the directory holds (`hold`); and | ||
//! `events.index`, which a shutdown leaves of the firehose's events in the | ||
//! backfill window, each one's seq, account and time (`events::index`). | ||
//! While a checkpoint is written, `<checkpoint>.tmp` is beside it, and | ||
//! `events.index.tmp` beside the index. | ||
//! Generations are decimal from 0. A log is frames (`pds_store`), each one | ||
//! write's whole effect, and may end with a **seal**, `[{"t":"seal"}]`: the | ||
//! log is closed, the next generation follows. | ||
| @@ -68,9 +71,13 @@ | ||
//! have left frames the system had not written out. Only the firehose, | ||
//! finding where the events before the start are, reads accounts' files | ||
//! without that (`checkpoint::events_on_disk`); each event is sent as its | ||
//! store, loaded, reads it. A service checkpoint of the format before a | ||
//! table, a log whose first frame names its generation, is folded alone | ||
//! into a table of the same generation before the service log starts | ||
//! store, loaded, reads it. It reads none of them where the last server | ||
//! shut down and left `events.index`, and no event has been numbered since: | ||
//! the index names the greatest seq reserved in the service log as it was | ||
//! written, and a start takes it only if that is the one it reads there | ||
//! (`events::Firehose::find_old`). A service checkpoint of the format | ||
//! before a table, a log whose first frame names its generation, is folded | ||
//! alone into a table of the same generation before the service log starts | ||
//! (`compact::convert`). | ||
//! | ||
//! **Seqs** are never given twice: each event keeps the seq it was written | ||
| @@ -119,6 +126,10 @@ pub(crate) fn holds_data(dir: &Path) -> bool { | ||
/// The file a process holds a data directory by. | ||
const LOCK: &str = "lock"; | ||
| ||
/// The firehose's index of the events in the window, which a shutdown | ||
/// leaves in the data directory (`events::index`). | ||
pub(crate) const EVENTS_INDEX: &str = "events.index"; | ||
| ||
/// Hold the data directory `dir`, made if it is missing, for as long as the | ||
/// file answered is open: `pds serve` and `pds migrate-blobs` each hold it | ||
/// while they run (`spec/COMMANDS.md`). Refused if another process holds | ||
docs/guide/comparing.md+3−2
| @@ -156,8 +156,9 @@ repository and streams it back and replays the firehose, then holds 100000 | ||
accounts, finds one in 50 of them by DID, handle, email and session, and | ||
refreshes 10000 sessions several times over, stays within its base, the | ||
cache and 4 KiB an account; and it starts as fast with all of that as on an | ||
empty data directory. Making the accounts is most of its time, some | ||
minutes. | ||
empty data directory; and after a shutdown and a start, the firehose's | ||
first message from a cursor comes within a second. Making the accounts is | ||
most of its time, some minutes. | ||
| ||
`--upgrade` starts the server alone on the data directories the last | ||
release wrote, in `harness/upgrade/`, one shut down and one killed, and | ||
harness/checks/scale.mjs+83−4
| @@ -85,10 +85,11 @@ async function holdPeak(what, peak) { | ||
console.error(` ${what}: peak ${MiB(peak)}, bound ${MiB(bound())}`) | ||
} | ||
| ||
/// Kill the server and start it again; its start held to the rule, and its | ||
/// memory just started to the idle bound. Answers the start's time. | ||
async function restart(what) { | ||
await server.kill() | ||
/// Stop the server, killed or with the signal given, and start it again; | ||
/// its start held to the rule, and its memory just started to the idle | ||
/// bound. Answers the start's time. | ||
async function restart(what, signal = 'SIGKILL') { | ||
await server.stop(signal) | ||
server.start() | ||
const ms = await waitReady(server, cand.url) | ||
await wait(300) | ||
| @@ -283,6 +284,50 @@ function replay() { | ||
}) | ||
} | ||
| ||
/// How long the firehose's first message is waited for before it is given | ||
/// up: long, so that a failure says how late it was. | ||
const FIRST_PATIENCE = 600_000 | ||
| ||
/// The first message of the firehose from `cursor`: how long it took from | ||
/// asking, and its seq; no time if none came in `FIRST_PATIENCE`. | ||
function firstMessage(cursor) { | ||
return new Promise((done) => { | ||
const at = Date.now() | ||
const ws = new WebSocket(`${cand.url.replace(/^http/, 'ws')}/xrpc/com.atproto.sync.subscribeRepos?cursor=${cursor}`) | ||
ws.binaryType = 'arraybuffer' | ||
const give = (answer) => { | ||
clearTimeout(late) | ||
ws.close() | ||
done(answer) | ||
} | ||
const late = setTimeout(() => give({ ms: null }), FIRST_PATIENCE) | ||
ws.onmessage = (m) => give({ ms: Date.now() - at, seq: cborDecodeMulti(new Uint8Array(m.data))[1]?.seq }) | ||
ws.onerror = () => {} | ||
}) | ||
} | ||
| ||
/// The seq of the first event `write` makes: a subscription with no cursor | ||
/// is open before it, and its first message is that event's. Answered once | ||
/// the write is answered too: the event may come first, and what follows | ||
/// may kill the server. | ||
function seqOf(write) { | ||
return new Promise((done, failed) => { | ||
const ws = new WebSocket(`${cand.url.replace(/^http/, 'ws')}/xrpc/com.atproto.sync.subscribeRepos`) | ||
ws.binaryType = 'arraybuffer' | ||
let written | ||
ws.onopen = () => { | ||
written = write() | ||
written.catch(failed) | ||
} | ||
ws.onmessage = (m) => { | ||
ws.close() | ||
const seq = cborDecodeMulti(new Uint8Array(m.data))[1]?.seq | ||
written.then(() => done(seq), failed) | ||
} | ||
ws.onerror = () => failed(new Error('no live subscription')) | ||
}) | ||
} | ||
| ||
/// The run: what spec/STORE.md's "How it is checked" says of it. | ||
export async function scaleRun() { | ||
// The base: just started on an empty data directory. | ||
| @@ -349,5 +394,39 @@ export async function scaleRun() { | ||
await holdPeak(`${WITH_PASSWORDS} accounts' sessions each refreshed ${REFRESHES} times`, (await sampled(refreshAll)).peak) | ||
await restart(`with ${MOST} accounts, sessions refreshed`) | ||
await holdPeak(`one account in ${ONE_IN} of ${MOST} found again`, (await sampled(() => findSome('sessions refreshed and a start'))).peak) | ||
| ||
// The firehose after a start that follows a shutdown, the first thing | ||
// asked of it: its first message within a second, from the first event | ||
// ever made and from the last, a commit made just before the shutdown. | ||
// Before the shutdown the firehose is asked from 0 once, as a relay asks | ||
// it: after a kill, which this start followed, that may wait. | ||
const afterKill = await firstMessage(0) | ||
console.error(` the firehose from 0, after a kill and a start with ${MOST} accounts: its first message ${afterKill.ms === null ? `not in ${FIRST_PATIENCE / 1000} s` : `in ${afterKill.ms} ms`}`) | ||
if (afterKill.seq !== events.seqs[0]) await fail(cand, 'the firehose from 0, after a kill and a start', { accounts: state.accounts.length }, `the event of seq ${events.seqs[0]}`, afterKill) | ||
const writer = state.accounts[1] | ||
const write = (text) => async () => { | ||
const res = await xrpcHttp(cand, 'com.atproto.repo.createRecord', { body: { repo: writer.did, collection: 'com.example.scale', record: { $type: 'com.example.scale', text } }, token: writer.token }) | ||
if (res.status !== 200) await fail(cand, `createRecord, ${text}`, { did: writer.did }, 'the record', res.body) | ||
} | ||
const last = await seqOf(write('the last before a shutdown')) | ||
await restart(`with ${MOST} accounts, after a shutdown`, 'SIGTERM') | ||
for (const [what, cursor, seq] of [['0', 0, events.seqs[0]], ['the seq before the last commit', last - 1, last]]) { | ||
const first = await firstMessage(cursor) | ||
console.error(` the firehose from ${what}, after a shutdown and a start with ${MOST} accounts: its first message ${first.ms === null ? `not in ${FIRST_PATIENCE / 1000} s` : `in ${first.ms} ms`}`) | ||
if (first.ms === null || first.ms > COLD_MS || first.seq !== seq) { | ||
await fail(cand, `the firehose from ${what}, after a shutdown and a start`, { accounts: state.accounts.length, cursor }, `its first message within ${COLD_MS} ms, the event of seq ${seq}`, { ms: first.ms, seq: first.seq }) | ||
} | ||
} | ||
count('firehose after a shutdown', true) | ||
| ||
// What the shutdown left of the firehose must not outlive a write: a | ||
// record written since, then a kill and a start, and the firehose from | ||
// the seq before that record's commit is sent it, however long it takes. | ||
const later = await seqOf(write('after the shutdown, before a kill')) | ||
await restart(`with ${MOST} accounts, after a write and a kill`) | ||
const sent = await firstMessage(later - 1) | ||
console.error(` the firehose from the seq before a commit made after the shutdown, after a kill: its first message ${sent.ms === null ? `not in ${FIRST_PATIENCE / 1000} s` : `in ${sent.ms} ms`}`) | ||
if (sent.seq !== later) await fail(cand, 'the firehose after a shutdown, a start, a write and a kill', { accounts: state.accounts.length, cursor: later - 1 }, `the event of seq ${later}`, sent) | ||
count('firehose after a kill', true) | ||
return { r0: state.r0, t0, accounts: state.accounts.length, repo: repo.bytes.length, events: events.bytes } | ||
} | ||
spec/DURABILITY.md+7−3
| @@ -44,9 +44,13 @@ server may choose how it lays its data out. | ||
nothing of itself, and below `PDS_MIN_FREE_BYTES` of free space a write | ||
is `507 InsufficientStorage` before it starts (`LIMITS.md`). | ||
- Data the server cannot recover is never served. Entries that do not parse, | ||
past a last write cut short (which recovery drops), or a rebuilt tree that | ||
is not the one the head commit names, make `pds serve` exit 1, with | ||
`pds: cannot recover <dir>: ` and why on standard error. | ||
past a last write cut short (which recovery drops), a rebuilt tree that | ||
is not the one the head commit names, or two accounts kept with one | ||
handle or one email, make `pds serve` exit 1, with | ||
`pds: cannot recover <dir>: ` and why on standard error: as it starts, | ||
for what it reads then, and for what is one account's, which it reads on | ||
that account's first use (`STORE.md`, "Scale"), when it reads it. Nothing | ||
of that account is answered first. | ||
- All of this holds at every moment, whatever the server is doing in the | ||
background to keep its data small (`STORE.md`), and on a data directory | ||
the previous version of the server wrote. | ||
spec/STORE.md+21−1
| @@ -169,6 +169,14 @@ given, not the accounts or their data. | ||
to send them does not grow with the size of the answer, a `getRepo` of | ||
any size within the memory bound. A subscriber that reads slowly is sent | ||
the events as it reads them, not buffered ahead of it. | ||
- **The firehose after a start.** After a start that follows a shutdown | ||
(`SIGTERM`), a `subscribeRepos` with a cursor is sent its first message | ||
within 1 second of asking, the first subscription after the start too, | ||
whatever the number of accounts. After a kill or a power cut, the first | ||
such subscription may wait while the server reads its accounts' files | ||
for the events made before; the events it is sent are the same. A | ||
server shut down before it was ever asked that, on a start that followed | ||
a kill, is as one killed. | ||
| ||
## Upgrades | ||
| ||
| @@ -280,7 +288,19 @@ empty start's time and its resident memory then the base, and then: | ||
sessions is written several times over and compacted as it is, within | ||
the memory bound throughout; starts the server again, within the | ||
starting bound and the idle memory; and looks for the same accounts | ||
again, each session by its last refresh's token. | ||
again, each session by its last refresh's token; | ||
- asks for the firehose from cursor `0`, as a relay would, on that start, | ||
which followed a kill: its first message, however long it takes, must be | ||
the first event ever made. Then it writes a record to one account, with | ||
a subscription open to learn its commit's `seq`; shuts the server down | ||
with `SIGTERM` and starts it again, within the starting bound and the | ||
idle memory; and, the first request it is sent, asks for the firehose | ||
from cursor `0`, then from the `seq` before that commit's: each one's | ||
first message must come within a second, and be the first event ever | ||
made, and that commit. Then it writes another record, kills the server | ||
and starts it, and asks for the firehose from the `seq` before that | ||
record's commit: it must be sent that commit, however long it takes, so | ||
that what a shutdown left of the firehose does not outlive a write. | ||
| ||
`node compare.mjs --upgrade ...` is a run of its own, of the server alone, | ||
against `harness/upgrade/`: what the previous version made, with | ||