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

Blobs kept in an S3-compatible bucket, by the reference's variables

Merged chadtmiller.com asked to merge into main from chadtmiller.com/monolith:s3-blobstore
crates/pds-server/src/ops/trace.rs+30−9
@@ -379,7 +379,8 @@ pub(crate) fn server_span(
/// Where the server sends a request of its own: the PLC directory, a
/// crawler, a service it forwards to or reads from (the AppView, those
/// `atproto-proxy` names), a `did:web` document, a client's metadata or
/// keys (OAuth's, or an attesting client's), or a space's notification.
/// keys (OAuth's, or an attesting client's), a space's notification, a
/// permission set's record, or the bucket blobs are kept in.
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum Target {
Plc,
@@ -389,6 +390,7 @@ pub(crate) enum Target {
Client,
Space,
Lexicon,
Blobstore,
}
impl Target {
@@ -401,6 +403,7 @@ impl Target {
Target::Client => "client",
Target::Space => "space",
Target::Lexicon => "lexicon",
Target::Blobstore => "blobstore",
}
}
@@ -414,10 +417,21 @@ impl Target {
Target::Client => ("client failure", Level::Debug),
Target::Space => ("space notification failure", Level::Debug),
Target::Lexicon => ("lexicon failure", Level::Debug),
Target::Blobstore => ("blobstore failure", Level::Warn),
}
}
}
/// What a request to the bucket does, as its failure line names it: `put`,
/// `get` or `delete`.
fn blobstore_op(m: &Method) -> &'static str {
match *m {
Method::PUT => "put",
Method::DELETE => "delete",
_ => "get",
}
}
/// Send a request of the server's own to `target`, as `execute` does.
pub(crate) async fn send(
target: Target,
@@ -504,18 +518,25 @@ impl Outgoing {
);
if let Some(why) = &error {
let (msg, level) = target.failure();
// Only a directory's paths name a DID, and nothing else of a URL is logged.
let did = (target == Target::Plc)
.then(|| {
self.url
.path_segments()
.and_then(|mut s| s.find(|p| p.starts_with("did:")).map(str::to_string))
})
.flatten();
// Only a directory's paths, and the bucket's keys, name a DID,
// and nothing else of a URL is logged.
let segments = || self.url.path_segments().into_iter().flatten();
let did = match target {
Target::Plc => segments()
.find(|p| p.starts_with("did:"))
.map(str::to_string),
Target::Blobstore => segments()
.map(|p| percent_encoding::percent_decode_str(p).decode_utf8_lossy())
.find(|p| p.starts_with("did:"))
.map(|p| p.into_owned()),
_ => None,
};
let op = (target == Target::Blobstore).then(|| blobstore_op(&self.method));
line(
level,
msg,
&[
("op", json!(op)),
("error", json!(why)),
("status", json!(status)),
("did", json!(did)),
crates/pds-server/src/blobs.rs+419−112
531 lines changed: not loaded until asked for.
crates/pds-server/src/blobstore.rsnew+1490−0
1490 lines changed: not loaded until asked for.
crates/pds-server/src/cache.rs+15−7
@@ -12,11 +12,13 @@
//! 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, or that has
//! write notifications or deletion notices to send. Each is marked, durably,
//! before the entry that needs it reaches its own log, and unmarked, with
//! the handle it has then, once nothing needs it. So the service log holds
//! each account's handle but while a mark says to look in its own log.
//! (`Eager`): an account whose handle change is in flight, that has write
//! notifications or deletion notices to send, or, with blobs in a bucket,
//! an upload on its way or objects to delete (`blobstore`). Each is marked,
//! durably, before the entry that needs it reaches its own log, and
//! unmarked, with the handle it has then, once nothing needs it. So the
//! service log holds each account's handle but while a mark says to look in
//! its own log.
use crate::events::Firehose;
use crate::{Account, Locked, Store};
@@ -53,6 +55,9 @@ pub(crate) struct Ctx {
/// 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,
/// The bucket blobs are kept in, if they are not kept in the data
/// directory (`blobstore`).
pub bucket: Option<Arc<crate::blobstore::Bucket>>,
}
fn lock<T>(m: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
@@ -145,9 +150,12 @@ impl Eager {
}
impl Store {
/// Whether a start must load it: a handle change in flight, or sends due.
/// Whether a start must load it: a handle change in flight, sends due,
/// or with blobs in a bucket, an upload on its way or a stray.
pub(crate) fn needs_start(&self) -> bool {
self.pending.is_some() || self.notify.next_due().is_some()
self.pending.is_some()
|| self.notify.next_due().is_some()
|| (self.ctx.bucket.is_some() && self.blobs.objects_unsettled())
}
/// Whether nothing of it is in flight, so that it may be let go.
crates/pds-server/src/checkpoint.rs+30−7
@@ -18,9 +18,10 @@
//! DID, the table's generation, the latest commit's block, the counts of
//! records and blocks of its tree, the last TID, the last `seq`, the
//! handle and a change in flight, the blobs held with their takedowns and
//! the records' blob refs, the records taken down, the space repos whole,
//! the spaces it is the authority of (as `exportSpaceMeta`'s archives),
//! and its write notifications.
//! the records' blob refs, with blobs in a bucket the objects it may keep
//! of blobs not held (`blobstore`), the records taken down, the space
//! repos whole, the spaces it is the authority of (as `exportSpaceMeta`'s
//! archives), and its write notifications.
//!
//! **The log after it** is replayed as the store loads, one frame at a time,
//! into a `Memtable`: each block, path and event the log changed, and where
@@ -297,7 +298,7 @@ impl Small {
("until", int(at.until)),
])
});
encode(&map([
let mut state = map([
("version", V::Int(VERSION)),
("did", text(did)),
("generation", int(generation)),
@@ -388,12 +389,34 @@ impl Small {
("owed", V::Arr(owed.collect())),
]),
),
]))
]);
// With blobs in a bucket, the objects it may keep of blobs not held.
if let (V::Map(m), Some(objects)) = (&mut state, self.blobs.objects_list()) {
m.push((
"objects".into(),
V::Arr(objects.into_iter().map(text).collect()),
));
}
encode(&state)
}
/// Read an `S` value: everything checked, as `encode` writes it, and
/// that it is of the account `did`.
fn decode(bytes: &[u8], did: &str) -> Result<Small, String> {
let mut state = decode(bytes).map_err(|e| format!("the state: {e}"))?;
let objects = match &mut state {
V::Map(m) => m
.iter()
.position(|(k, _)| k == "objects")
.map(|i| m.swap_remove(i).1),
_ => None,
};
let objects = or_none(objects.unwrap_or(V::Null), |v| {
as_list(v, "objects")?
.into_iter()
.map(|c| as_text(c, "an object"))
.collect::<Result<Vec<_>, _>>()
})?;
let [
version,
state_did,
@@ -412,7 +435,7 @@ impl Small {
authority,
notify,
] = fields(
decode(bytes).map_err(|e| format!("the state: {e}"))?,
state,
[
"version",
"did",
@@ -493,7 +516,7 @@ impl Small {
if !ascending(records.iter().map(|(p, _, _)| p.as_str())) {
return Err("blob refs out of order".into());
}
s.blobs = Blobs::restore(records, held)?;
s.blobs = Blobs::restore(records, held, objects)?;
let mut last: Option<String> = None;
for x in as_list(takedowns, "takedowns")? {
let [path, r] = fields(x, ["path", "ref"], "a takedown")?;
crates/pds-server/src/compact.rs+10−3
@@ -8,9 +8,11 @@
//! log holds in the backfill window; each deletion whose event is in the
//! window, of whose account nothing else is kept; OAuth's entries with only
//! each session's latest refresh and what each device's last entries leave;
//! the single-use values still held; and each account's preferences as last
//! put. So however often sessions, password or OAuth, are refreshed, and
//! devices signed in, the service log holds no more than what is kept.
//! the single-use values still held; each account's preferences as last
//! put; and with blobs in a bucket, the objects of deleted accounts not yet
//! deleted (`blobstore`). So however often sessions, password or OAuth, are
//! refreshed, and devices signed in, the service log holds no more than what
//! is kept.
//!
//! The fold reads the logs, not memory, so that it is exactly what replay
//! would make of them. It leaves out sessions that expired more than
@@ -157,6 +159,9 @@ fn fold(
let mut prefs_at: HashMap<String, usize> = HashMap::new();
let (mut oauth, mut spent) = (Vec::new(), Vec::new());
let mut gone = std::collections::HashSet::new();
// Deleted accounts' objects in a bucket not yet deleted, kept apart from
// what the fold drops of the accounts deleted.
let mut doomed = crate::blobstore::Doomed::default();
for e in frames.into_iter().flatten() {
match e["t"].as_str() {
Some("account") => {
@@ -237,6 +242,7 @@ fn fold(
held.push(e);
}
}
Some(t) if crate::blobstore::ENTRIES.contains(&t) => doomed.replay(&e)?,
t => return Err(format!("a log entry of no known type: {t:?}")),
}
}
@@ -275,6 +281,7 @@ fn fold(
.filter(|did| mails.contains_key(*did))
.map(|did| crate::cache::dir_entry(did, None, true)),
);
entries.extend(doomed.entries());
Ok((
entries
.chunks(FRAME_ENTRIES)
crates/pds-server/src/lib.rs+15−7
@@ -7,7 +7,8 @@
//! passwords), `email` (the account's email, the tokens mailed for it, and
//! the mailer), `repo` (records), `sync` (the repository whole),
//! `federation` (what a relay reads, and the crawlers the server tells),
//! `identity` (handles), `blobs`, `invites`, `lifecycle` (deactivating,
//! `identity` (handles), `blobs` (kept in the data directory, or in a
//! bucket, `blobstore`), `invites`, `lifecycle` (deactivating,
//! taking down and deleting accounts, and what each state does to every
//! method), `proxy` (requests for other services, service tokens) with
//! `read_after_write` and `preferences`, `space_repo` (each account's space
@@ -31,6 +32,7 @@
#![forbid(unsafe_code)]
mod blobs;
mod blobstore;
mod cache;
mod checkpoint;
mod compact;
@@ -143,6 +145,9 @@ pub(crate) struct Config {
/// the data directory before serving: the tests' way; the server's own
/// loads each on first use.
pub load_all: bool,
/// The bucket blobs are kept in, if they are not kept in the data
/// directory (`spec/BLOBS.md`).
pub blobstore: Option<blobstore::Settings>,
}
impl Config {
@@ -205,6 +210,7 @@ impl Config {
log_floor: store::FLOOR,
cache_bytes: limits::env_u64("PDS_CACHE_BYTES", 256 << 20)?,
load_all: false,
blobstore: blobstore::Settings::from_env()?,
})
}
}
@@ -682,10 +688,10 @@ pub fn run() {
}),
};
let config = Config::from_env().unwrap_or_else(|e| fail(e));
ops::start(
ops::Settings::from_env(port).unwrap_or_else(|e| fail(e)),
port,
);
let settings = ops::Settings::from_env(port).unwrap_or_else(|e| fail(e));
// Where the data directory keeps its blobs, before anything is written.
blobstore::check_dir(FsPath::new(&dir), config.blobstore.is_some()).unwrap_or_else(|e| fail(e));
ops::start(settings, port);
let unclean = ops::unclean(FsPath::new(&dir));
let svc = Arc::new(
Service::open(FsPath::new(&dir), config)
@@ -703,6 +709,7 @@ pub fn run() {
// Handle changes in flight when the server stopped are settled while it serves.
identity::settle_unfinished(&svc);
blobs::sweep_every(&svc);
blobstore::delete_every(&svc);
cache::sweep_every(&svc);
// Notifications kept when the server stopped are sent again when due.
space_notify::start(&svc);
@@ -941,7 +948,7 @@ async fn serve(svc: &Shared, call: &Call<'_>) -> Result<Resp, XrpcError> {
limits::charge(svc, call, None, None)?;
}
shown.durable().await?;
out
blobs::read_object(svc, out).await
}
Handler::Lookup(f) => {
let p = params(call, m)?;
@@ -1014,7 +1021,7 @@ async fn serve(svc: &Shared, call: &Call<'_>) -> Result<Resp, XrpcError> {
.unwrap_or_else(|_| internal())
}
// A method that checks its call in its own order pays the limits itself (`limits::guard`).
Handler::Call(f) => f(svc, call, m).await,
Handler::Call(f) => blobs::read_object(svc, f(svc, call, m).await).await,
}
}
@@ -1331,6 +1338,7 @@ mod testing {
log_floor: crate::store::FLOOR,
cache_bytes: 256 << 20,
load_all: true,
blobstore: None,
}
}
crates/pds-server/src/lifecycle.rs+23−5
@@ -848,7 +848,7 @@ async fn delete_account(s: Shared, b: Map<String, Json>) -> Result<Resp, XrpcErr
return refuse();
}
let now = s.sessions.now();
let (n, landing) = {
let (n, landing, objects) = {
let m = email::lock(&a.mail);
// A password reset meanwhile makes it wrong.
if m.password != stored {
@@ -860,6 +860,10 @@ async fn delete_account(s: Shared, b: Map<String, Json>) -> Result<Resp, XrpcErr
let synced = durable(s.log.clone(), n).await;
s.events.land(landing);
synced?;
// Its objects in a bucket go once its deletion is on disk.
if let Some(bucket) = &s.ctx.bucket {
bucket.doom(&a.did, objects);
}
// Its files go once its deletion is on disk; a restart removes any left.
let dir = s.dir.join("repos").join(&a.did);
let removed = tokio::task::spawn_blocking(move || match std::fs::remove_dir_all(&dir) {
@@ -877,8 +881,14 @@ async fn delete_account(s: Shared, b: Map<String, Json>) -> Result<Resp, XrpcErr
/// Delete an account, with its mail held: logged, in one entry with its
/// deletion's event and the places of its events, dropped from the
/// firehose; then it is no account, its handle and email free, its sessions,
/// app passwords and tokens gone. Answers the frame and the event to land.
fn remove(s: &Service, a: &Account, m: &email::Mail) -> Result<(u64, Landing), XrpcError> {
/// app passwords and tokens gone. With blobs in a bucket, the objects it may
/// keep are named in the same frame, to delete (`blobstore`). Answers the
/// frame, the event to land, and those objects.
fn remove(
s: &Service,
a: &Account,
m: &email::Mail,
) -> Result<(u64, Landing, Vec<String>), XrpcError> {
let st = write(&a.store);
not_deleted(a)?;
// OAuth's lock, taken before the state's, is held throughout: no OAuth
@@ -901,7 +911,15 @@ fn remove(s: &Service, a: &Account, m: &email::Mail) -> Result<(u64, Landing), X
.or_else(email::not_logged)?;
let frame = events::account_event(&a.did, seq, &events::timestamp(), Some("deleted"));
let entry = json!({ "t": "deleted", "did": a.did, "gaps": runs(&seqs), "seq": seq, "frame": hex::encode(&frame) });
let n = match s.log.append(&[entry]) {
let objects = match &s.ctx.bucket {
Some(_) => st.blobs.kept_list(),
None => Vec::new(),
};
let mut entries = vec![entry];
if !objects.is_empty() {
entries.push(crate::blobstore::doomed_entry(&a.did, &objects));
}
let n = match s.log.append(&entries) {
Ok(n) => n,
Err(e) => {
s.events.fail(seq, 1);
@@ -922,7 +940,7 @@ fn remove(s: &Service, a: &Account, m: &email::Mail) -> Result<(u64, Landing), X
{
d.emails.remove(e);
}
Ok((n, Landing { seq, frames: vec![frame.into()] }))
Ok((n, Landing { seq, frames: vec![frame.into()] }, objects))
})?;
s.sessions.forget(&a.did);
s.resets.forget(&a.did);
crates/pds-server/src/log.rs+39−5
@@ -12,8 +12,9 @@
//! and their uses (`invites::ENTRIES`), the single-use values the spaces
//! took (`single_use`), the spaces' credentials revoked here
//! (`space_credentials`), each account's state and its events
//! (`lifecycle::ENTRIES`), and each account's preferences as last put
//! (`preferences::ENTRY`);
//! (`lifecycle::ENTRIES`), each account's preferences as last put
//! (`preferences::ENTRY`), and with blobs in a bucket, the objects of
//! deleted accounts not yet deleted (`blobstore::ENTRIES`);
//! - `jwt.key`, the secret its tokens are signed with, and `oauth.key`, the
//! one OAuth seals its tokens, nonces and cookies with;
//! - each account's own log, `repos/<did>/repo.<g>.log` from its checkpoint
@@ -27,7 +28,8 @@
//! records it publishes and the repo it drops (`space_repo::DROP`); and its
//! 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`).
//! - `repos/<did>/blobs/<cid>`, the bytes of each blob it holds (`blobs`),
//! or with blobs in a bucket, none, and the mark `blobstore` (`blobstore`).
//!
//! Each log is compacted into its checkpoint, generation by generation
//! (`store`, `pds_store`). A start reads each checkpoint and replays the
@@ -307,7 +309,9 @@ pub(crate) fn handle_entry(handle: &str, cid: &str) -> Json {
/// Append `commit`'s entry, if given, and `entries`, with the events
/// numbered from `seq`, the commit's change kept in the store's memtable:
/// the events to land once the log is on disk, or, if the append failed,
/// none of them, their numbers left unused.
/// none of them, their numbers left unused. With blobs in a bucket, a
/// commit that stops the account holding a blob has it marked for a start
/// to load first, so that the blob's object is deleted (`blobstore`).
fn append_events(
events: &Firehose,
st: &mut Store,
@@ -316,6 +320,13 @@ fn append_events(
frames: Vec<Vec<u8>>,
commit: Option<&Change>,
) -> io::Result<Landing> {
if st.ctx.bucket.is_some()
&& st.blobs.dooms()
&& let Err(e) = st.ctx.eager.mark(&st.repo.did)
{
events.fail(seq, frames.len());
return Err(e);
}
let now = crate::events::now_ms();
let times: Vec<u64> = frames
.iter()
@@ -448,7 +459,16 @@ pub(crate) fn open_repo(ctx: &Arc<Ctx>, did: &str, key: &SigningKey) -> Result<R
disk,
mut small,
} = crate::checkpoint::load(ctx, did, key)?;
small.blobs.recover(&blob_dir(dir, did))?;
match &ctx.bucket {
None => small.blobs.recover(&blob_dir(dir, did))?,
Some(bucket) => {
small.blobs.recover_kept();
// An upload the server stopped during, or an object not yet deleted.
if small.blobs.strays().next().is_some() {
bucket.wake(did);
}
}
}
let fresh = repo.rev.is_empty();
Ok(Recovered {
store: Store {
@@ -593,6 +613,8 @@ impl Service {
// a deleted account's.
let mut lifecycle = crate::lifecycle::Replayed::default();
let prefs = crate::preferences::Preferences::default();
// Deleted accounts' objects in a bucket not yet deleted.
let mut doomed = crate::blobstore::Doomed::default();
let mut apply = |e: &Json| -> Result<(), String> {
let at = |why: String| format!("{ACCOUNTS_LOG}: {why}");
match e["t"].as_str() {
@@ -671,6 +693,9 @@ impl Service {
marked.remove(did);
}
}
Some(t) if crate::blobstore::ENTRIES.contains(&t) => {
doomed.replay(e).map_err(at)?
}
Some(crate::events::SEQS) => {
let upto = e["upto"]
.as_u64()
@@ -767,6 +792,14 @@ impl Service {
));
let eager = Arc::new(crate::cache::Eager::new(log.clone(), marked));
let files = Files::new(OPEN_LOGS);
let bucket = match config.blobstore.clone() {
Some(s) => {
let b = crate::blobstore::Bucket::new(s)?;
b.doomed(doomed);
Some(Arc::new(b))
}
None => None,
};
let ctx = Arc::new(Ctx {
dir: dir.to_path_buf(),
files: files.clone(),
@@ -779,6 +812,7 @@ impl Service {
cache: crate::cache::Cache::new(config.cache_bytes / 2),
blocks: pds_store::table::BlockCache::new(config.cache_bytes / 4),
starting: std::sync::atomic::AtomicBool::new(true),
bucket,
});
let limits = crate::limits::Limits::new(dir, &config);
sessions.prune(sessions.now());
crates/pds-server/src/ops.rs+1−5
@@ -236,11 +236,7 @@ pub(crate) fn failed_for(level: Level, msg: &str, did: &str, why: impl std::fmt:
/// checkpoint, or the single log of the layout before generations, and no
/// mark of a shutdown.
pub(crate) fn unclean(dir: &Path) -> bool {
let layout = crate::store::service_layout(dir);
let data = layout.generations().is_ok_and(|g| !g.is_empty())
|| layout.checkpoint().exists()
|| dir.join(crate::store::LEGACY_SERVICE).exists();
data && !dir.join(CLEAN).exists()
crate::store::holds_data(dir) && !dir.join(CLEAN).exists()
}
/// The data is read: say so if the last server did not shut down, and take
crates/pds-server/src/space_authority.rs+3−1
@@ -694,7 +694,9 @@ async fn change<T>(
let mut st = write(&a.store);
let out = f(&mut st, &mut frame)?;
if !frame.entries.is_empty() {
if let Err(e) = st.wal.append(&frame.entries) {
if let Err(e) =
crate::blobstore::mark_for(&st).and_then(|()| st.wal.append(&frame.entries))
{
crate::ops::failed_for(
crate::ops::Level::Error,
"a change to spaces failed",
crates/pds-server/src/space_repo.rs+5−3
@@ -990,7 +990,7 @@ async fn write(svc: &Shared, call: &Call<'_>, m: &'static Method) -> Result<Resp
// The blobs its records reference are on disk before it is.
st.blobs
.sync_before(&st.wal, c.puts.iter().flat_map(|(_, r)| cids_in(&r.value)));
match st.wal.append(&[entry]) {
match crate::blobstore::mark_for(st).and_then(|()| st.wal.append(&[entry])) {
Ok(_) => {
st.spaces.land(c, &mut st.blobs);
(Ok(answer), Some(commit))
@@ -1707,7 +1707,7 @@ fn get_blob(
{
return err(400, "BlobNotFound", format!("Blob not found: {cid}"));
}
st.blobs.serve_space(&s.dir, &a.did, cid)
st.blobs.serve_space(s, &a.did, cid)
}
/// The CIDs the repo's records reference, each once, in ascending order,
@@ -1816,7 +1816,9 @@ async fn import_repo(svc: &Shared, call: &Call<'_>) -> Result<Resp, XrpcError> {
&st.wal,
import.records.iter().flat_map(|(_, r)| cids_in(&r.value)),
);
if let Err(e) = st.wal.append(&[import.entry(&commit.data)]) {
if let Err(e) = crate::blobstore::mark_for(st)
.and_then(|()| st.wal.append(&[import.entry(&commit.data)]))
{
// Nothing of it reached the log: nothing of it stays.
crate::ops::failed_for(
crate::ops::Level::Error,
crates/pds-server/src/store.rs+11−1
harness/checks/backup.mjs+9−1
harness/checks/blobs.mjs+65−20
harness/checks/blobstore.mjsnew+339−0
harness/checks/crashes.mjs+7−1
harness/checks/lifecycle.mjs+2−1
harness/checks/operations.mjs+15−2
harness/lib/adapters/spec-pds.mjs+1−1
harness/lib/args.mjs+9−1
harness/lib/env.mjs+16−2
harness/lib/processes.mjs+13−4
harness/lib/s3.mjsnew+900−0
900 lines changed: not loaded until asked for.
harness/compare.mjs+15−2
harness/gates.mjs+6−2
spec/BLOBS.md+138−2
spec/DURABILITY.md+28−11
spec/LIMITS.md+2−1
spec/OPERATIONS.md+5−3
spec/PDS.md+2−1
spec/STORE.md+3−1
README.md+15−4