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

pds migrate-blobs moves blobs between the data directory and a bucket

Merged chadtmiller.com asked to merge into main from chadtmiller.com/monolith:migrate-blobs
crates/pds/src/main.rs+34−4
@@ -1,4 +1,5 @@
//! `pds`: `pds serve` runs the server; anything else is the CLI, calling a running one.
//! `pds`: `pds serve` runs the server, `pds migrate-blobs` moves its blobs
//! while it is stopped; anything else is the CLI, calling a running one.
#![forbid(unsafe_code)]
@@ -19,6 +20,15 @@ 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";
const MIGRATE_HELP: &str = "Usage: pds migrate-blobs --to bucket|disk\n\n\
Move the data directory's blobs into the bucket PDS_BLOBSTORE_S3_BUCKET\n\
names (--to bucket), or out of it into the data directory (--to disk),\n\
with no server running on it. It is given the environment pds serve is,\n\
with the bucket's variables set either way. Killed or stopped, run it\n\
again: with the same --to it carries on, with the other it moves them\n\
back. Done, it prints {\"moved\":<blobs>,\"bytes\":<bytes>}; then start pds\n\
serve with the environment of where they are.\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
@@ -31,10 +41,15 @@ fn small_pages() {
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.first().map(String::as_str) {
Some("serve") => serve(&args[1..]),
Some("migrate-blobs") => migrate_blobs(&args[1..]),
_ => std::process::exit(pds_cli::run(&args)),
}
match args.get(1).map(String::as_str) {
}
fn serve(args: &[String]) {
match args.first().map(String::as_str) {
None => {
small_pages();
pds_server::run()
@@ -47,6 +62,21 @@ fn main() {
}
}
fn migrate_blobs(args: &[String]) {
let to = match args {
[h] if h == "--help" || h == "-h" => return print!("{MIGRATE_HELP}"),
[flag, to] if flag == "--to" => pds_server::Place::named(to),
_ => None,
};
let Some(to) = to else {
eprint!(
"pds: pds migrate-blobs takes --to bucket or --to disk, not {args:?}\n\n{MIGRATE_HELP}"
);
std::process::exit(2);
};
pds_server::migrate_blobs(to)
}
#[cfg(test)]
mod tests {
/// The server's memory is in the system's small pages.
crates/pds-server/src/blobs.rs+98−4
@@ -37,7 +37,10 @@
//! may keep (`kept`): `blobPut` before an upload puts one, `blobDeleted`
//! once one is deleted. Those of blobs no longer held are deleted by the
//! deleter (`blobstore`), which a write that stops holding a blob, an
//! upload, and `sweep` wake, where they would remove its file.
//! upload, and `sweep` wake, where they would remove its file. A move of
//! the blobs into the bucket (`migrate_blobs`) logs `blobPut` for each blob
//! held before it puts their objects, and a move out of it
//! `blobObjectsDeleted` once it has deleted every object the store may keep.
use crate::{
Account, Call, Handler, Resp, Service, Shared, Shown, Store, XrpcError, err, internal, invalid,
@@ -70,11 +73,22 @@ const UPLOAD: &str = "com.atproto.repo.uploadBlob";
const PUT: &str = "blobPut";
/// The entry of an object the bucket answered the delete of.
const DELETED: &str = "blobDeleted";
/// The entry of every object the bucket may keep deleted, by a move of the
/// blobs out of it.
const OBJECTS_DELETED: &str = "blobObjectsDeleted";
/// The kinds of entry an account's log has of its blobs: an upload, one no
/// longer held, a takedown or its lifting (`spec/LIFECYCLE.md`), and with
/// blobs in a bucket, an object it may keep and one deleted (`blobstore`).
pub(crate) const ENTRIES: &[&str] = &["blob", "blobGone", "takedownBlob", PUT, DELETED];
/// blobs in a bucket, an object it may keep and one deleted (`blobstore`),
/// and every one deleted (`migrate_blobs`).
pub(crate) const ENTRIES: &[&str] = &[
"blob",
"blobGone",
"takedownBlob",
PUT,
DELETED,
OBJECTS_DELETED,
];
/// How often uploads held past their time are logged as gone, and their files removed.
const SWEEP_EVERY: std::time::Duration = std::time::Duration::from_secs(30);
@@ -153,7 +167,8 @@ pub(crate) struct Blobs {
takedowns: BTreeMap<String, String>,
/// With blobs in a bucket, the CIDs whose objects it may keep: each blob
/// held, and those of the others not known to be deleted, its strays.
/// Empty with blobs in the data directory.
/// Empty with blobs in the data directory, but while a move of them
/// into the bucket, or out of it, is unfinished (`migrate_blobs`).
kept: BTreeSet<String>,
}
@@ -319,6 +334,69 @@ impl Blobs {
self.kept.remove(cid);
}
/// The blobs it holds at `now`, with uploads held for `ttl`, each with
/// its size, in order of CID.
pub(crate) fn holding(&self, now: u64, ttl: u64) -> Vec<(String, u64)> {
self.held
.iter()
.filter(|(cid, h)| self.referenced(cid) || h.at.saturating_add(ttl) > now)
.map(|(cid, h)| (cid.clone(), h.size))
.collect()
}
/// The CIDs of every object a bucket may keep, and of every blob held:
/// those a move out of the bucket deletes.
pub(crate) fn objects(&self) -> Vec<String> {
let mut all: BTreeSet<&String> = self.kept.iter().collect();
all.extend(self.held.keys());
all.into_iter().cloned().collect()
}
/// Log, in `wal`, that a bucket may keep the objects of `cids`, those no
/// entry names yet, before a move puts them: the frame to wait on, if
/// one was appended.
pub(crate) fn note_kept(
&mut self,
wal: &pds_store::Wal,
cids: &[String],
) -> io::Result<Option<u64>> {
let new: Vec<&String> = cids.iter().filter(|c| !self.kept.contains(*c)).collect();
if new.is_empty() {
return Ok(None);
}
let n = wal.append(&new.iter().map(|c| put_entry(c)).collect::<Vec<_>>())?;
self.kept.extend(new.into_iter().cloned());
Ok(Some(n))
}
/// Log, in `wal`, that the strays `cids` are deleted, as the deleter
/// does: the frame to wait on, if one was appended.
pub(crate) fn strays_deleted(
&mut self,
wal: &pds_store::Wal,
cids: &[String],
) -> io::Result<Option<u64>> {
if cids.is_empty() {
return Ok(None);
}
let n = wal.append(&cids.iter().map(|c| deleted_entry(c)).collect::<Vec<_>>())?;
for c in cids {
self.kept.remove(c);
}
Ok(Some(n))
}
/// Log, in `wal`, that a move out of the bucket deleted every object it
/// may keep: the frame to wait on, if one was appended.
pub(crate) fn objects_deleted(&mut self, wal: &pds_store::Wal) -> io::Result<Option<u64>> {
if self.kept.is_empty() {
return Ok(None);
}
let n = wal.append(&[json!({ "t": OBJECTS_DELETED })])?;
self.kept.clear();
Ok(Some(n))
}
/// Whether an upload is on its way, or a stray waits to be deleted.
pub(crate) fn objects_unsettled(&self) -> bool {
!self.placing.is_empty() || self.strays().next().is_some()
@@ -638,6 +716,10 @@ impl Blobs {
/// Replay an entry of the kinds in `ENTRIES`.
pub(crate) fn replay(&mut self, e: &Json) -> Result<(), String> {
if e["t"] == OBJECTS_DELETED {
self.kept.clear();
return Ok(());
}
let Some(cid) = e["cid"].as_str() else {
return Err(format!("a blob entry with no cid: {e}"));
};
@@ -1110,6 +1192,18 @@ impl Drop for Temp {
}
}
/// Make `bytes` `cid`'s file in `dir`, in place of any there, synced, as a
/// move into the data directory writes it (`migrate_blobs`): the directory
/// is synced once each of its files is.
pub(crate) fn write_synced(dir: &Path, cid: &str, bytes: &[u8]) -> io::Result<()> {
let mut t = Temp::create(dir)?;
t.file.write_all(bytes)?;
t.file.sync_all()?;
std::fs::rename(&t.path, dir.join(cid))?;
t.placed = true;
Ok(())
}
/// The type a body's first bytes show, of those `spec/BLOBS.md` lists.
fn sniff(head: &[u8], body: &mut (impl Read + Seek)) -> Option<&'static str> {
let at = |from: usize, want: &[u8]| head.get(from..from + want.len()) == Some(want);
crates/pds-server/src/blobstore.rs+531−268
799 lines changed: not loaded until asked for.
crates/pds-server/src/lib.rs+91−28
@@ -8,7 +8,8 @@
//! the mailer), `repo` (records), `sync` (the repository whole),
//! `federation` (what a relay reads, and the crawlers the server tells),
//! `identity` (handles), `blobs` (kept in the data directory, or in a
//! bucket, `blobstore`), `invites`, `lifecycle` (deactivating,
//! bucket, `blobstore`, and moved from one to the other by `pds
//! migrate-blobs`, `migrate_blobs`), `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
@@ -46,6 +47,7 @@ mod lifecycle;
mod limits;
mod log;
mod mcp;
mod migrate_blobs;
mod oauth;
mod ops;
mod outbound;
@@ -68,6 +70,8 @@ mod store;
mod sync;
mod validation;
pub use blobstore::Place;
use axum::{
Router,
body::{Body, Bytes},
@@ -81,7 +85,7 @@ use pds_repo::{Refused, Repo};
use pds_store::Wal;
use serde_json::{Map, Value as Json, json};
use std::collections::{HashMap, HashSet};
use std::path::{Path as FsPath, PathBuf};
use std::path::PathBuf;
use std::pin::Pin;
use std::sync::{Arc, Mutex, OnceLock, PoisonError, RwLock, RwLockReadGuard, RwLockWriteGuard};
@@ -664,38 +668,71 @@ fn handler(nsid: &str) -> Option<Handler> {
AREAS.iter().find_map(|area| area(nsid))
}
/// What `pds serve` is given by its environment, as `spec/PDS.md` says.
struct Environment {
port: u16,
dir: PathBuf,
address: std::net::IpAddr,
config: Config,
ops: ops::Settings,
}
impl Environment {
/// Read from the environment: why not, if a variable is missing or
/// does not parse.
fn read() -> Result<Environment, String> {
let var = |n: &str| std::env::var(n).map_err(|_| format!("{n} is not set"));
let port = var("PDS_PORT")?
.parse::<u16>()
.map_err(|_| "PDS_PORT is not a port".to_string())?;
let dir = PathBuf::from(var("PDS_DATA_DIR")?);
let address = match std::env::var("PDS_BIND_ADDRESS")
.ok()
.filter(|a| !a.is_empty())
{
None => std::net::IpAddr::from([127, 0, 0, 1]),
Some(a) => a
.parse()
.map_err(|_| format!("PDS_BIND_ADDRESS is {a:?}, not an IPv4 or IPv6 address"))?,
};
let config = Config::from_env()?;
let ops = ops::Settings::from_env(port)?;
Ok(Environment {
port,
dir,
address,
config,
ops,
})
}
}
/// Say why the process cannot go on, on standard error, and exit 1.
fn fail(why: String) -> ! {
eprintln!("pds: {why}");
std::process::exit(1);
}
/// Run the server, configured by the environment as `spec/PDS.md` says,
/// until a SIGTERM or SIGINT shuts it down (`spec/OPERATIONS.md`).
pub fn run() {
let fail = |why: String| -> ! {
eprintln!("pds: {why}");
std::process::exit(1);
};
let var = |n: &str| std::env::var(n).unwrap_or_else(|_| fail(format!("{n} is not set")));
let port = var("PDS_PORT")
.parse::<u16>()
.unwrap_or_else(|_| fail("PDS_PORT is not a port".into()));
let dir = var("PDS_DATA_DIR");
let address = match std::env::var("PDS_BIND_ADDRESS")
.ok()
.filter(|a| !a.is_empty())
{
None => std::net::IpAddr::from([127, 0, 0, 1]),
Some(a) => a.parse().unwrap_or_else(|_| {
fail(format!(
"PDS_BIND_ADDRESS is {a:?}, not an IPv4 or IPv6 address"
))
}),
};
let config = Config::from_env().unwrap_or_else(|e| fail(e));
let settings = ops::Settings::from_env(port).unwrap_or_else(|e| fail(e));
let Environment {
port,
dir,
address,
config,
ops: settings,
} = Environment::read().unwrap_or_else(|e| fail(e));
// The data directory is this process's alone while it runs, before
// anything is written (`spec/COMMANDS.md`).
let _held = store::hold(&dir).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));
blobstore::check_dir(&dir, config.blobstore.is_some()).unwrap_or_else(|e| fail(e));
ops::start(settings, port);
let unclean = ops::unclean(FsPath::new(&dir));
let unclean = ops::unclean(&dir);
let svc = Arc::new(
Service::open(FsPath::new(&dir), config)
.unwrap_or_else(|e| fail(format!("cannot recover {dir}: {e}"))),
Service::open(&dir, config)
.unwrap_or_else(|e| fail(format!("cannot recover {}: {e}", dir.display()))),
);
ops::recovered(&svc, unclean).unwrap_or_else(|e| fail(e));
let app = router(svc.clone());
@@ -718,6 +755,31 @@ pub fn run() {
})
}
/// `pds migrate-blobs --to <to>`: move the data directory's blobs into the
/// bucket or out of it, given the environment `pds serve` is, as
/// `spec/BLOBS.md`'s "Moving them" says (`migrate_blobs`); print what it
/// moved and exit 0, or say why not and exit 1.
pub fn migrate_blobs(to: Place) -> ! {
let env = Environment::read().unwrap_or_else(|e| fail(e));
if env.config.blobstore.is_none() {
fail("PDS_BLOBSTORE_S3_BUCKET is not set: it names the bucket the blobs are moved into, or out of".into());
}
let _held = store::hold(&env.dir).unwrap_or_else(|e| fail(e));
let moved = tokio::runtime::Runtime::new()
.unwrap()
.block_on(migrate_blobs::run(&env.dir, env.config, to))
.unwrap_or_else(|e| fail(e));
use std::io::Write;
let mut out = std::io::stdout();
let _ = writeln!(
out,
"{{\"moved\":{},\"bytes\":{}}}",
moved.blobs, moved.bytes
)
.and_then(|()| out.flush());
std::process::exit(0);
}
/// The server's routes. Every path under `/xrpc/` is a method, served or
/// forwarded. Each answers browsers as `cors` says.
fn router(svc: Shared) -> Router {
@@ -1200,6 +1262,7 @@ fn commit_meta(r: &Repo) -> Json {
mod testing {
use super::*;
use axum::body::Bytes;
use std::path::Path as FsPath;
/// A PLC directory, at the URL answered, which takes a genesis operation
/// only if its signature and DID are as `atproto/did-plc.md` says, and
crates/pds-server/src/migrate_blobs.rsnew+560−0
560 lines changed: not loaded until asked for.
crates/pds-server/src/store.rs+46−1
@@ -6,7 +6,8 @@
//! **Files.** In `PDS_DATA_DIR`: the service log, `accounts.<g>.log`, and its
//! 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`).
//! 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.
//! 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
@@ -95,6 +96,35 @@ pub(crate) fn holds_data(dir: &Path) -> bool {
|| dir.join(LEGACY_SERVICE).exists()
}
/// The file a process holds a data directory by.
const LOCK: &str = "lock";
/// 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
/// it; the system lets it go when the process ends, however it ends.
pub(crate) fn hold(dir: &Path) -> Result<std::fs::File, String> {
pds_store::make_dirs(dir).map_err(|e| format!("{}: {e}", dir.display()))?;
let lock = dir.join(LOCK);
let at = |e: io::Error| format!("{}: {e}", lock.display());
let f = pds_store::open_private(
&lock,
std::fs::OpenOptions::new()
.create(true)
.truncate(false)
.write(true),
)
.map_err(at)?;
match rustix::fs::flock(&f, rustix::fs::FlockOperation::NonBlockingLockExclusive) {
Ok(()) => Ok(f),
Err(rustix::io::Errno::WOULDBLOCK) => Err(format!(
"{} is held by another process: a pds serve, or a pds migrate-blobs, runs on it",
dir.display()
)),
Err(e) => Err(at(e.into())),
}
}
/// When a log is compacted: past its checkpoint's size or `log_floor`, or
/// once its generation began more than twice the window ago.
pub(crate) fn policy(c: &Config) -> Policy {
@@ -381,3 +411,18 @@ pub(crate) fn read_checkpoint(layout: &Layout) -> Result<Option<Vec<u8>>, String
let p = layout.checkpoint();
read_if(&p).map_err(|e| format!("{}: {e}", p.display()))
}
#[cfg(test)]
mod tests {
/// A data directory is held by one at a time, until it lets it go.
#[test]
fn a_data_directory_is_held_by_one_at_a_time() {
let dir = crate::testing::scratch("held");
let held = super::hold(&dir).unwrap();
let refused = super::hold(&dir).unwrap_err();
assert!(refused.contains("held by another process"), "{refused}");
drop(held);
drop(super::hold(&dir).unwrap());
let _ = std::fs::remove_dir_all(&dir);
}
}
harness/checks/migrate.mjsnew+228−0
@@ -0,0 +1,228 @@
// Moving blobs between the data directory and a bucket (spec/BLOBS.md,
// "Moving them"), a run of its own, --migrate: the server keeps its blobs on
// disk, then is moved into a bucket of the S3 store the harness runs
// (lib/s3.mjs), then back, each move killed at random moments and run again,
// one turned back halfway, one stopped by an object gone. The reference keeps
// its blobs on disk throughout, and after each move every account's blobs
// must read as the reference's; the server's bucket and data directory are
// held to what each place holds. And: the data directory is held by one
// process at a time (spec/COMMANDS.md, "One binary").
import { spawn } from 'node:child_process'
import { isDeepStrictEqual } from 'node:util'
import { command, STEPS_GIVEN } from '../lib/args.mjs'
import { below, chance, pick } from '../lib/random.mjs'
import { cand, freePort, s3, server, waitReady } from '../lib/processes.mjs'
import { count, differ, run } from '../lib/report.mjs'
import { BUCKETS, S3_KEYS, S3_TIMEOUT_MS } from '../lib/s3.mjs'
import { accounts, didOf } from '../lib/state.mjs'
import { createFirstAccounts } from './accounts.mjs'
import { blobRecord, blobsSurvive, compareGetBlob, getBlob, listBlobs, model, referencedCids, uploadBlob } from './blobs.mjs'
import { bucketHolds, dataDirHoldsNoBlobs } from './blobstore.mjs'
const SPEC = 'spec/BLOBS.md, "Moving them"'
/// The blob steps of each phase, unless --steps says.
const PHASE_STEPS = STEPS_GIVEN ?? 60
const STEPS = [[uploadBlob, 4], [blobRecord, 6], [getBlob, 3], [listBlobs, 2]]
/// The bucket's variables, which the command is given whichever way it
/// moves, and the server only while its blobs are in the bucket.
const BUCKET_ENV = () => ({
PDS_BLOBSTORE_S3_BUCKET: BUCKETS.server,
PDS_BLOBSTORE_S3_ENDPOINT: s3.url,
PDS_BLOBSTORE_S3_FORCE_PATH_STYLE: 'true',
PDS_BLOBSTORE_S3_ACCESS_KEY_ID: S3_KEYS.accessKeyId,
PDS_BLOBSTORE_S3_SECRET_ACCESS_KEY: S3_KEYS.secretAccessKey,
PDS_BLOBSTORE_S3_UPLOAD_TIMEOUT_MS: String(S3_TIMEOUT_MS),
PDS_BLOBSTORE_S3_REQUEST_TIMEOUT_MS: String(S3_TIMEOUT_MS),
})
/// The server's environment for blobs kept `where`.
function serveEnv(where) {
for (const k of Object.keys(BUCKET_ENV())) delete server.env[k]
if (where === 'bucket') Object.assign(server.env, BUCKET_ENV())
return { ...process.env, ...server.env }
}
/// `pds <args>` with `env`, killed after `killAfter` ms if given, counted
/// from when `armed()` first holds (polled every few ms; at once without
/// it): its exit, standard output and standard error.
function pds(args, env, killAfter, armed = () => true) {
return new Promise((ok) => {
const p = spawn(command[0], args, { env, stdio: ['ignore', 'pipe', 'pipe'] })
const out = []
const err = []
p.stdout.on('data', (d) => out.push(d))
p.stderr.on('data', (d) => err.push(d))
let timer = null
const poll = killAfter === undefined ? null : setInterval(() => {
if (!armed()) return
clearInterval(poll)
timer = setTimeout(() => p.kill('SIGKILL'), killAfter)
}, 2)
p.on('exit', (code, signal) => {
clearInterval(poll)
clearTimeout(timer)
ok({ code, signal, stdout: Buffer.concat(out).toString('utf8'), stderr: Buffer.concat(err).toString('utf8') })
})
})
}
const migrateEnv = () => ({ ...process.env, ...server.env, ...BUCKET_ENV() })
/// The blobs the harness knows the accounts hold, and their bytes.
function held() {
let n = 0
let bytes = 0
for (const acct of accounts) for (const s of acct.blobs?.stored.values() ?? []) (n += 1), (bytes += s.size)
return { moved: n, bytes }
}
/// A `pds serve` on the data directory, apart from the run's server: it
/// must exit 1, with why on standard error, before it serves.
async function serveRefused(where, why, spec = SPEC) {
const port = await freePort()
const env = { ...serveEnv(where), PDS_PORT: String(port), PDS_METRICS_PORT: '' }
const r = await pds(['serve'], env, 20_000)
serveEnv(where)
if (r.code !== 1 || !r.stderr.trim() || r.stdout.trim()) await differ(`pds serve ${why}`, { blobs: where }, 'exit 1, with why on standard error and nothing on standard output', { code: r.code, signal: r.signal, stdout: r.stdout.slice(0, 300), stderr: r.stderr.slice(0, 300) }, spec)
count(`pds serve ${why}, refused`, false)
}
/// `pds migrate-blobs --to <to>`, killed now and then, run again until it
/// finishes. The store answers each request 100 ms late, and a kill lands
/// at a random moment within 600 ms of its first request of the run: after
/// the move has marked the data directory (spec/BLOBS.md, "Moving them", 4
/// before 5), while it copies, switches or cleans up. With `back`, the
/// first time it is killed the move is turned back: moved where the blobs
/// were, served from there, then moved on.
async function moveTo(to, { kills = 3, back } = {}) {
let killed = 0
for (let attempt = 0; ; attempt++) {
if (attempt > 40) throw new Error(`pds migrate-blobs --to ${to} did not finish in 40 runs`)
const kill = killed < kills && chance(0.8) ? below(600) : undefined
s3.fail({ bucket: BUCKETS.server, mode: { delayMs: 100 } })
const from = s3.requests.length
const r = await pds(['migrate-blobs', '--to', to], migrateEnv(), kill, () => s3.requests.slice(from).some((q) => q.bucket === BUCKETS.server))
s3.clearFailures()
if (r.signal === 'SIGKILL') {
killed += 1
// Unfinished, the data directory is not served, whichever way.
if (killed === 1) await serveRefused(pick(['bucket', 'disk']), 'on a data directory whose blobs are moving')
if (back && killed === 1) {
harness/checks/migrate.mjsline 112

The turn-back (back) and the first-kill serveRefused run only if the first attempt is killed. A run whose first attempt isn't killed (a 20% draw, or the move finishing before the kill) passes without checking either, and nothing says so. Counting those checks as ran or skipped, or failing when back was asked for and never ran, would keep a lucky seed from skipping them.

await moveTo(back, { kills: 1 })
await serves(back, `moved back to ${back} after a move to ${to} was killed`)
await server.stop('SIGTERM', 15_000)
}
continue
}
if (r.code !== 0) await differ(`pds migrate-blobs --to ${to}`, { attempt: attempt + 1, killed }, 'exit 0', { code: r.code, stdout: r.stdout.slice(0, 300), stderr: r.stderr.slice(0, 500) }, SPEC)
let line
try {
line = JSON.parse(r.stdout.trim())
} catch {
await differ(`pds migrate-blobs --to ${to}`, { attempt: attempt + 1 }, 'one line of JSON on standard output', r.stdout.slice(0, 300), SPEC)
}
if (!isDeepStrictEqual(line, held())) await differ(`pds migrate-blobs --to ${to}`, { attempt: attempt + 1, killed }, held(), line, SPEC)
return count(`pds migrate-blobs --to ${to}, killed ${killed} times first`, true)
}
}
/// `pds migrate-blobs --to <where>` on a data directory that keeps its
/// blobs there already: nothing moved.
async function nothingToMove(where) {
const r = await pds(['migrate-blobs', '--to', where], migrateEnv(), 60_000)
if (r.code !== 0 || r.stdout.trim() !== '{"moved":0,"bytes":0}') await differ(`pds migrate-blobs --to ${where}, its blobs there already`, {}, { code: 0, stdout: '{"moved":0,"bytes":0}' }, { code: r.code, signal: r.signal, stdout: r.stdout.slice(0, 300), stderr: r.stderr.slice(0, 300) }, SPEC)
count(`pds migrate-blobs --to ${where}, its blobs there already`, true)
}
/// The server started with its blobs `where`, and every account's blobs
/// read as the reference's: every blob a record references, listBlobs, and
/// a record referencing an upload no record had (checks/blobs.mjs).
async function serves(where, when) {
serveEnv(where)
server.start()
await waitReady(server, cand.url)
for (const acct of accounts) for (const cid of referencedCids(model(acct))) await compareGetBlob(`getBlob, ${when}`, (side) => ({ did: didOf(side, acct), cid }))
await blobsSurvive()
if (where === 'bucket') {
await bucketHolds(when)
await dataDirHoldsNoBlobs(when)
} else {
const left = [...s3.objects(BUCKETS.server).keys()].filter((k) => k.startsWith('blocks/'))
if (left.length) await differ(`the bucket, ${when}`, { bucket: BUCKETS.server }, 'no object of the accounts\' blobs', left.slice(0, 10), SPEC)
count(`the bucket holds no blob, ${when}`, true)
}
}
/// Random blob steps, compared as in any run.
async function blobSteps(n) {
const total = STEPS.reduce((s, [, w]) => s + w, 0)
for (let i = 0; i < n; i++, run.step++) {
let r = below(total)
for (const [fn, w] of STEPS) if ((r -= w) < 0) {
await fn(pick(accounts))
break
}
}
}
/// The data directory held by the running server: a second `pds serve` on
/// it, and `pds migrate-blobs`, are refused.
async function heldByServer(where) {
await serveRefused(where, 'beside a running server on its data directory', 'spec/COMMANDS.md, "One binary"')
const r = await pds(['migrate-blobs', '--to', where === 'bucket' ? 'disk' : 'bucket'], migrateEnv(), 20_000)
if (r.code !== 1 || !r.stderr.trim()) await differ('pds migrate-blobs beside a running server on its data directory', {}, 'exit 1, with why on standard error', { code: r.code, signal: r.signal, stdout: r.stdout.slice(0, 300), stderr: r.stderr.slice(0, 300) }, 'spec/COMMANDS.md, "One binary"')
count('pds migrate-blobs beside a running server, refused', false)
}
/// Arguments that do not parse: usage errors, exit 2, with nothing moved.
async function usage() {
for (const args of [['migrate-blobs'], ['migrate-blobs', '--to', 'cloud']]) {
const r = await pds(args, migrateEnv(), 20_000)
if (r.code !== 2) await differ(`pds ${args.join(' ')}`, {}, 'a usage error: exit 2', { code: r.code, stderr: r.stderr.slice(0, 300) }, SPEC)
count(`pds ${args.join(' ')}, a usage error`, false)
}
}
/// A move into the data directory stopped by a blob whose object is gone:
/// exit 1 naming it, the data directory not served either way; then the
/// object back, and the move run again to its end.
async function stoppedByObjectGone() {
const holders = accounts.filter((a) => a.blobs?.stored.size)
if (!holders.length) return
const acct = pick(holders)
const cid = pick([...acct.blobs.stored.keys()])
const key = `blocks/${didOf(cand, acct)}/${cid}`
const saved = s3.objects(BUCKETS.server).get(key)
if (!saved) return differ('the server\'s bucket before a move', { cid }, `an object ${key}`, 'none', SPEC)
s3.remove(BUCKETS.server, key)
const r = await pds(['migrate-blobs', '--to', 'disk'], migrateEnv(), 60_000)
if (r.code !== 1 || !r.stderr.includes(cid) || !r.stderr.includes(didOf(cand, acct))) await differ('pds migrate-blobs --to disk, a blob\'s object gone', { cid }, 'exit 1, naming the DID and CID on standard error', { code: r.code, signal: r.signal, stderr: r.stderr.slice(0, 500) }, SPEC)
count('pds migrate-blobs, stopped by an object gone', false)
await serveRefused('disk', 'after a move stopped by an object gone')
await serveRefused('bucket', 'after a move stopped by an object gone')
s3.put(BUCKETS.server, key, saved.bytes, saved.contentType)
}
/// The run: blobs on disk; moved into the bucket, the first move turned
/// back halfway; blobs in the bucket; a move out stopped by an object gone,
/// then moved out; blobs on disk again. Each place served between moves.
export async function migrateRun() {
await createFirstAccounts()
await blobSteps(PHASE_STEPS)
await heldByServer('disk')
await server.stop('SIGTERM', 15_000)
await usage()
await nothingToMove('disk')
await moveTo('bucket', { back: 'disk' })
await nothingToMove('bucket')
await serves('bucket', 'moved into the bucket')
await blobSteps(PHASE_STEPS)
await heldByServer('bucket')
await server.stop('SIGTERM', 15_000)
await stoppedByObjectGone()
await moveTo('disk')
await serves('disk', 'moved into the data directory')
await blobSteps(PHASE_STEPS / 2)
}
harness/lib/args.mjs+9−3
@@ -1,6 +1,6 @@
// compare.mjs's arguments.
const usage = 'usage: node harness/compare.mjs [--steps N] [--seed N] [--check-every N] [--crash-every N] [--firehose] [--commands] [--s3] [--limits | --invites | --lifecycle | --store | --scale | --pages | --upgrade | --upgrade-write] [--only name,...] [--impl name] [--area name --result file.json] [--tally file.json] -- <server command...>'
const usage = 'usage: node harness/compare.mjs [--steps N] [--seed N] [--check-every N] [--crash-every N] [--firehose] [--commands] [--s3] [--limits | --invites | --lifecycle | --store | --scale | --pages | --upgrade | --upgrade-write | --migrate] [--only name,...] [--impl name] [--area name --result file.json] [--tally file.json] -- <server command...>'
const dash = process.argv.indexOf('--')
const opts = process.argv.slice(2, dash === -1 ? undefined : dash)
/// The command that starts the server.
@@ -14,6 +14,8 @@ const str = (name, fallback) => {
return i === -1 ? fallback : opts[i + 1]
}
export const STEPS = opt('--steps', 400)
/// `--steps` when it is given, for runs whose own default differs.
export const STEPS_GIVEN = opt('--steps', undefined)
export const SEED = opt('--seed', 1)
export const CHECK_EVERY = opt('--check-every', 10)
/// The implementation the server is, by its adapter's name in
@@ -68,7 +70,11 @@ export const PAGES_STEPS = opt('--steps', 30)
/// previous version.
export const UPGRADE = opts.includes('--upgrade')
export const UPGRADE_WRITE = opts.includes('--upgrade-write')
if (LIMITS + INVITES + LIFECYCLE + STORE + SCALE + PAGES + UPGRADE + UPGRADE_WRITE > 1) {
/// A run of its own: the server's blobs moved from its data directory into
/// a bucket of the S3 store the harness runs and back, by `pds
/// migrate-blobs` killed as it goes (spec/BLOBS.md, "Moving them").
export const MIGRATE = opts.includes('--migrate')
if (LIMITS + INVITES + LIFECYCLE + STORE + SCALE + PAGES + UPGRADE + UPGRADE_WRITE + MIGRATE > 1 || (MIGRATE && IMPL !== 'spec-pds')) {
console.error(usage)
process.exit(2)
}
@@ -76,7 +82,7 @@ if (LIMITS + INVITES + LIFECYCLE + STORE + SCALE + PAGES + UPGRADE + UPGRADE_WRI
/// for each side, held to spec/BLOBS.md, "Where blobs are kept": with the
/// random steps (and --crash-every, --firehose), or --lifecycle.
export const S3 = opts.includes('--s3')
if (S3 && (LIMITS || INVITES || STORE || SCALE || PAGES || UPGRADE || UPGRADE_WRITE || AREA || IMPL !== 'spec-pds')) {
if (S3 && (LIMITS || INVITES || STORE || SCALE || PAGES || UPGRADE || UPGRADE_WRITE || MIGRATE || AREA || IMPL !== 'spec-pds')) {
console.error(usage)
process.exit(2)
}
harness/lib/processes.mjs+4−3
@@ -8,7 +8,7 @@ import { chmodSync, mkdtempSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { TestNetworkNoAppView } from '@atproto/dev-env'
import { BACKFILL_MS, CACHE_BYTES, IMPL, INVITES, LIFECYCLE, LIMITS, S3, command } from './args.mjs'
import { BACKFILL_MS, CACHE_BYTES, IMPL, INVITES, LIFECYCLE, LIMITS, MIGRATE, S3, command } from './args.mjs'
import { ADAPTERS } from './adapters/index.mjs'
import { startCrawlers } from './crawlers.mjs'
import { startClientWeb } from './clients.mjs'
@@ -62,8 +62,9 @@ export async function start() {
const appView = await startAppView()
const bsky = { bskyAppViewUrl: appView.url, bskyAppViewDid: appView.did, bskyAppViewCdnUrlPattern: CDN_PATTERN }
// With --s3, both sides keep their blobs in buckets of the store here, a
// bucket each (spec/BLOBS.md, "Where blobs are kept").
if (S3) {
// bucket each (spec/BLOBS.md, "Where blobs are kept"); with --migrate, the
// server's are moved into its bucket and out again, the reference's on disk.
if (S3 || MIGRATE) {
s3 = await startS3(S3_KEYS)
for (const b of Object.values(BUCKETS)) s3.makeBucket(b)
}
harness/compare.mjs+12−1
@@ -58,6 +58,9 @@
// (lib/s3.mjs), with the random steps or --lifecycle: the store fails as
// steps ask, for both alike, and the server's bucket and data directory
// are held to spec/BLOBS.md, "Where blobs are kept".
// --migrate is a run of its own: the server's blobs moved from its data
// directory into a bucket and back by `pds migrate-blobs`, killed as it
// goes, and every blob read as the reference's after each move.
// --impl names another implementation's adapter (lib/adapters/), which
// starts that server itself, given as much of this setup as it can take;
// spec-pds's is the default, the command after `--` with this environment.
@@ -75,7 +78,7 @@
// accounts and their repositories, and the report. Each area's checks are in
// checks/.
import { AREA, CHECK_EVERY, COMMANDS, CRASH_EVERY, FIREHOSE, INVITES, LIFECYCLE, LIMITS, ONLY, PAGES, S3, SCALE, SEED, STEPS, STORE, UPGRADE, UPGRADE_WRITE } from './lib/args.mjs'
import { AREA, CHECK_EVERY, COMMANDS, CRASH_EVERY, FIREHOSE, INVITES, LIFECYCLE, LIMITS, MIGRATE, ONLY, PAGES, S3, SCALE, SEED, STEPS, STORE, UPGRADE, UPGRADE_WRITE } from './lib/args.mjs'
import { below, pick } from './lib/random.mjs'
import { shutdown, start } from './lib/processes.mjs'
import { counts, run } from './lib/report.mjs'
@@ -110,6 +113,7 @@ import { scaleRun } from './checks/scale.mjs'
import { pagesRun } from './checks/pages.mjs'
import { upgradeRun, upgradeWrite } from './checks/upgrade.mjs'
import { S3_STEPS, blobstoreCounted, bucketHolds, dataDirHoldsNoBlobs } from './checks/blobstore.mjs'
import { migrateRun } from './checks/migrate.mjs'
import { areaRun } from './lib/areas.mjs'
await start()
@@ -164,6 +168,13 @@ if (UPGRADE) {
for (const [kind, { ok, error }] of Object.entries(counts).sort()) console.error(` ${kind.padEnd(56)} ${String(ok).padStart(5)} ok ${String(error).padStart(5)} refused`)
await shutdown(0)
}
if (MIGRATE) {
await migrateRun()
await checkOperations()
console.error(`\nall migration checks agree (seed ${SEED}), ${accounts.length} accounts`)
for (const [kind, { ok, error }] of Object.entries(counts).sort()) console.error(` ${kind.padEnd(72)} ${String(ok).padStart(5)} ok ${String(error).padStart(5)} refused`)
await shutdown(0)
}
if (FIREHOSE) await startFirehose()
await noCrawlsYet()
await createFirstAccounts()
harness/gates.mjs+1−0
@@ -75,6 +75,7 @@ const SUITES = {
run(15, 'compare.mjs', '--upgrade'),
run(150, 'compare.mjs', '--steps', 400, '--seed', 61, '--crash-every', 25, '--s3'),
run(120, 'compare.mjs', '--lifecycle', '--steps', 12, '--s3'),
run(120, 'compare.mjs', '--migrate', '--seed', 71),
],
// Nightly: the server killed while it writes, every 15 steps, over long
// runs: plain, with the firehose, and with the firehose through the MCP
spec/BLOBS.md+88−5
@@ -238,11 +238,11 @@ as `LIMITS.md` says of its variables. An empty variable is as if unset.
A data directory keeps its blobs where its first start put them: started
again with the bucket set when it kept them in itself, or unset when it kept
them in a bucket, `pds serve` exits 1 before it serves, with why on
standard error. Nothing moves blobs from one to the other. Which bucket, and
the endpoint, may change between starts, as when a store's objects are
copied to another: the server reads no object at its start, so a start
takes no longer with a bucket, and a bucket it cannot reach shows only
when a request needs it.
standard error. `pds migrate-blobs` moves them from one to the other
(below). Which bucket, and the endpoint, may change between starts, as when
a store's objects are copied to another: the server reads no object at its
start, so a start takes no longer with a bucket, and a bucket it cannot
reach shows only when a request needs it.
### Requests to the store
@@ -298,6 +298,60 @@ whose object the store may have kept while the server holds nothing of it
than the server; and, after a power cut, an object whose upload the server
had not yet made durable (`DURABILITY.md`).
### Moving them
`pds migrate-blobs --to bucket` moves a data directory's blobs from it into
the bucket, and `pds migrate-blobs --to disk` from the bucket into it. It is
given the environment `pds serve` is, with the bucket's variables set either
way, as the bucket is where the blobs go or come from, and runs with no
server on the data directory (`COMMANDS.md`, "One binary"). The reference
has no such command: its operator stops it, copies the files into the
bucket, or the objects out of it, and starts it with the other variables.
1. It checks the environment as `pds serve` does, and exits 1 on what
`pds serve` would, before it writes anything to standard output. A
`--to` other than `bucket` or `disk`, or none, is a usage error: exit
status 2.
2. A data directory a server, or another `pds migrate-blobs`, holds is
refused: exit 1, with why on standard error, and nothing changed.
3. A data directory that keeps its blobs where `--to` says, with no move
unfinished, is left as it is: it prints `{"moved":0,"bytes":0}` and
exits 0.
4. Otherwise it first marks the data directory, durably, as moving its
blobs. From then until it finishes, `pds serve` on it exits 1 before it
serves, with why on standard error, naming the command to run.
5. It copies each blob every account holds, referenced or not, taken down
or not, to the other place: into the bucket, the object
`blocks/<did>/<cid>` with the file's bytes; into the data directory,
the object's bytes as the file, synced. Each blob's bytes must be its
CID's, read where they are kept: a blob whose bytes are missing there,
or are not its CID's, stops it, exit 1, with each such blob (DID and
CID) on standard error, the data directory still moving. A store that
fails a request, as `pds serve` would count a failure, stops it the
same way, with why.
6. With every blob copied, it makes the data directory keep its blobs
where `--to` says, durably, and then deletes what is left where they
were: into the bucket, the blobs' files; into the data directory, the
blobs' objects, and those the server still owed a delete of (`The
objects`, above). The objects of a deleted account the server owed are
deleted either way.
7. Then it marks the move finished, prints one line,
`{"moved":<blobs>,"bytes":<bytes>}`: the blobs the accounts hold, every
one now where `--to` says, and the sum of their sizes; and exits 0.
Killed at any moment, or stopped by a failure, the command is run again:
with the same `--to` it carries on and finishes, copying again what it
had; with the other `--to`, it moves the blobs back where they were, as a
move that way. Either way, once it has finished, `pds serve` with the
environment of the place it moved them to holds every blob it held
before, each read answering as it did; the data directory, with the
bucket, holds none of their bytes; and the bucket, with the data
directory, holds none of the objects of the accounts it holds, as `The
objects` says.
The server is down while the command runs, for as long as copying every
blob takes.
## Durability
Blobs are kept with everything else in `PDS_DATA_DIR`, or in the bucket
@@ -403,6 +457,35 @@ blob an account holds, and `pds_outbound_requests_total` of target
`blobstore` must count at least each upload the store kept since the
server started (`OPERATIONS.md`).
`node compare.mjs --migrate ...` is a run of its own
(`harness/checks/migrate.mjs`), with the S3 store `--s3` runs. The server
starts with its blobs on disk, the reference with its own on disk
throughout. Blob steps of the run (uploads, records with blob refs,
`getBlob`, `listBlobs`) are compared, then, the server stopped:
- `pds serve`, and `pds migrate-blobs`, beside the running server must
exit 1 (`COMMANDS.md`); `migrate-blobs` with no `--to`, or another, is a
usage error; `--to disk` on a data directory keeping its blobs there
prints `{"moved":0,"bytes":0}`.
- `--to bucket`, with the store answering each request 100 ms late, is
killed at a random moment within 600 ms of the store's first request of
each run, and run again until it finishes. The first
time it is killed, `pds serve` must refuse the data directory, and the
move is turned back: `--to disk`, killed too, to its end, the server
started on disk and every blob read as the reference's, and the bucket
holding no object of the accounts' blobs; then `--to bucket` again.
Each finished run must print the count and bytes of the blobs the
harness knows the accounts hold, and `--to bucket` then
`{"moved":0,"bytes":0}`.
- Started with the bucket: every blob a record references read as the
reference's, `listBlobs` and a record referencing an upload compared,
and the bucket and data directory held as `--s3` holds them. More blob
steps, then the same refusals beside it.
- One object deleted, `--to disk` must exit 1 naming its DID and CID, and
`pds serve` refuse the data directory either way; the object put back,
`--to disk` killed and run again to its end, then served as on disk, the
bucket holding no object of the accounts' blobs, and more blob steps.
Not compared, as no client could rely on them: the other headers of
`getBlob` (`Cache-Control`, `Vary`, CORS), compression of its answer, a
`Range` request (the reference ignores it), `HEAD`, a `Content-Encoding` on
spec/COMMANDS.md+7−0
README.md+7−1