chadtmiller.com/monolith
An atproto PDS
0
0
getBlob's request line names its blob and the bytes it sent
.changeset/getblob-log.mdnew+7−0
| @@ -0,0 +1,7 @@ | ||
--- | ||
default: minor | ||
--- | ||
| ||
# getBlob's log line names the blob and the bytes sent | ||
| ||
The `request` line of a `com.atproto.sync.getBlob` answered `200`, or `500` when the store failed to read the blob, has `repo` and `cid`, the account's DID and the blob's CID; one answered `200` has `bytes` too, the bytes of the blob the server handed to the connection: the blob's size when it was sent whole, fewer when the client left first or the store's read failed partway. `did` stays the account whose token the request carried. `pds admin logs --method com.atproto.sync.getBlob` shows which blobs are fetched, and which fetches were cut short. | ||
.changeset/lettre-0-11-24.md+1−1
| @@ -4,4 +4,4 @@ default: patch | ||
| ||
# Email sending takes lettre 0.11.24's fixes | ||
| ||
The server sends email with lettre 0.11.24, which fixes two advisories in 0.11.23. RUSTSEC-2026-0564: a CR or LF in a display name made formatting a message panic. RUSTSEC-2026-0565: an SMTP server could make the client buffer a never-ending reply until memory ran out. | ||
The server sends email with lettre 0.11.24, which fixes four advisories in 0.11.23. RUSTSEC-2026-0564: a CR or LF in a display name made formatting a message panic. RUSTSEC-2026-0565: an SMTP server could make the client buffer a never-ending reply until memory ran out. RUSTSEC-2026-0560: a man-in-the-middle could slip replies of its own in after `STARTTLS`. RUSTSEC-2026-0561: a message with bare line endings could end early and smuggle SMTP commands after it. | ||
crates/pds-server/src/ops/trace.rs+4−1
| @@ -207,13 +207,15 @@ impl Settings { | ||
// ------------------------------------------------------------ context | ||
| ||
/// A request's trace context: its trace, its own span, the span it is the | ||
/// child of, whether it is sampled, and the account its token is of. | ||
/// child of, whether it is sampled, the account its token is of, and of a | ||
/// `getBlob` the blob it serves, by its account's DID and its CID. | ||
pub(crate) struct Ctx { | ||
pub trace_id: [u8; 16], | ||
pub span_id: [u8; 8], | ||
parent: Option<[u8; 8]>, | ||
pub sampled: bool, | ||
pub did: OnceLock<String>, | ||
pub blob: OnceLock<(String, String)>, | ||
} | ||
| ||
tokio::task_local! { | ||
| @@ -273,6 +275,7 @@ impl Ctx { | ||
parent, | ||
sampled, | ||
did: OnceLock::new(), | ||
blob: OnceLock::new(), | ||
} | ||
} | ||
| ||
crates/pds-server/src/blobs.rs+1−0
| @@ -1763,6 +1763,7 @@ fn get_blob( | ||
let Some(h) = st.blobs.served(cid).filter(|_| !st.blobs.taken_down(cid)) else { | ||
return invalid("Blob not found"); | ||
}; | ||
crate::ops::serving_blob(&a.did, cid); | ||
serve(s, &a.did, cid, h) | ||
} | ||
| ||
crates/pds-server/src/ops.rs+21−4
| @@ -650,6 +650,14 @@ pub(crate) fn verified(did: &str) { | ||
} | ||
} | ||
| ||
/// The blob the `getBlob` being answered serves, of the account `did`: its | ||
/// request line names it (`spec/OPERATIONS.md`, "Events"). | ||
pub(crate) fn serving_blob(did: &str, cid: &str) { | ||
if let Some(ctx) = trace::current() { | ||
let _ = ctx.blob.set((did.to_string(), cid.to_string())); | ||
} | ||
} | ||
| ||
/// Wait on `f`, a wait on writes reaching the disk, as a span `fsync` of | ||
/// the request being answered. | ||
pub(crate) async fn fsync<T>(f: impl Future<Output = T>) -> T { | ||
| @@ -762,7 +770,7 @@ impl Seen { | ||
|| status == StatusCode::NO_CONTENT | ||
|| status == StatusCode::NOT_MODIFIED; | ||
if bodiless || res.body().is_end_stream() { | ||
self.done(status.as_u16()); | ||
self.done(status.as_u16(), 0); | ||
return res; | ||
} | ||
let exact = res.body().size_hint().exact(); | ||
| @@ -777,16 +785,25 @@ impl Seen { | ||
}) | ||
} | ||
| ||
/// The answer is whole: its line, metrics and span. | ||
fn done(self, status: u16) { | ||
/// The answer is whole, `sent` bytes of its body handed on: its line, | ||
/// metrics and span. | ||
fn done(self, status: u16, sent: u64) { | ||
let o = ops(); | ||
let secs = self.started.elapsed().as_secs_f64(); | ||
let blob = self | ||
.ctx | ||
.blob | ||
.get() | ||
.filter(|_| status == 200 || status == 500); | ||
let fields = [ | ||
("method", json!(self.route)), | ||
("status", json!(status)), | ||
("ms", json!(secs * 1000.0)), | ||
("trace_id", json!(hex::encode(self.ctx.trace_id))), | ||
("did", json!(self.ctx.did.get())), | ||
("repo", json!(blob.map(|(did, _)| did))), | ||
("cid", json!(blob.map(|(_, cid)| cid))), | ||
("bytes", json!(blob.filter(|_| status == 200).map(|_| sent))), | ||
]; | ||
line( | ||
if status >= 500 { | ||
| @@ -828,7 +845,7 @@ struct Logged { | ||
impl Logged { | ||
fn done(&mut self) { | ||
if let Some(seen) = self.seen.take() { | ||
seen.done(self.status); | ||
seen.done(self.status, self.sent); | ||
} | ||
} | ||
} | ||
harness/checks/blobstore.mjs+35−1
| @@ -129,6 +129,40 @@ export async function failedRead(acct) { | ||
await compareGetBlob('getBlob once the store reads again', (side) => ({ did: didOf(side, acct), cid })) | ||
} | ||
| ||
/// getBlob, on the server alone, of a blob a record references of 2 bytes | ||
/// or more, while the store sends the head of its read and half its bytes | ||
/// and drops the connection, which the reference is not compared on: | ||
/// `200` with the blob's `Content-Length`, the answer ending short of it | ||
/// (spec/BLOBS.md, "The objects"). Its `request` line's `bytes`, fewer than | ||
/// the size, is checked with the rest of the log (checks/logging.mjs). | ||
export async function cutRead(acct) { | ||
const m = model(acct) | ||
const cids = referencedCids(m).filter((c) => !m.takedowns.has(c) && (m.stored.get(c)?.size ?? 0) >= 2) | ||
if (!cids.length) return | ||
const cid = pick(cids) | ||
const size = m.stored.get(cid).size | ||
const url = new URL(`${cand.url}/xrpc/com.atproto.sync.getBlob`) | ||
url.searchParams.set('did', didOf(cand, acct)) | ||
url.searchParams.set('cid', cid) | ||
s3.fail({ bucket: BUCKETS.server, op: 'GetObject', mode: 'cut' }) | ||
const got = { status: 0, 'content-length': null, read: 0, ended: 'whole' } | ||
try { | ||
const res = await fetch(url, { headers: { 'accept-encoding': 'identity' } }) | ||
Object.assign(got, { status: res.status, 'content-length': res.headers.get('content-length') }) | ||
try { | ||
for await (const chunk of res.body ?? []) got.read += chunk.byteLength | ||
} catch { | ||
got.ended = 'short' | ||
} | ||
} catch (err) { | ||
got.ended = `request failed: ${err.message}` | ||
} | ||
s3.clearFailures() | ||
const ok = got.status === 200 && got['content-length'] === String(size) && got.ended === 'short' && got.read < size | ||
if (!ok) await differ('getBlob, the store cutting its read short', { cid, size }, { status: 200, 'content-length': String(size), ended: 'short', read: `fewer than ${size}` }, got, SPEC) | ||
count('getBlob, the store cutting its read short', ok) | ||
} | ||
| ||
/// getBlob of a blob a record references whose object something other | ||
/// than the server deleted, on both sides, as a backup brought back finds | ||
/// one (spec/DURABILITY.md); then the objects put back. | ||
| @@ -337,4 +371,4 @@ export async function blobstoreCounted() { | ||
} | ||
| ||
/// The steps a run with --s3 adds, by weight. | ||
export const S3_STEPS = [[failedUpload, 3], [failedRead, 2], [objectGone, 1], [failedDelete, 2], [reuploadAtOnce, 2], [uploadDuringDelete, 2]] | ||
export const S3_STEPS = [[failedUpload, 3], [failedRead, 2], [cutRead, 1], [objectGone, 1], [failedDelete, 2], [reuploadAtOnce, 2], [uploadDuringDelete, 2]] | ||
harness/checks/logging.mjs+33−2
| @@ -25,6 +25,7 @@ const AUTHED = new Set([ | ||
'com.atproto.server.createAppPassword', 'com.atproto.server.listAppPasswords', 'com.atproto.server.revokeAppPassword', | ||
'com.atproto.server.getAccountInviteCodes', 'com.atproto.identity.updateHandle', 'com.atproto.identity.getRecommendedDidCredentials', | ||
]) | ||
const GET_BLOB = 'com.atproto.sync.getBlob' | ||
| ||
/// The server failing spec/OPERATIONS.md. | ||
export const broke = (what, detail, want, got) => differ(`the server's ${what}`, detail, want, got, 'spec/OPERATIONS.md') | ||
| @@ -81,6 +82,11 @@ async function checkLines(lives) { | ||
if (typeof obj.ms !== 'number' || !(obj.ms >= 0) || !Number.isFinite(obj.ms)) await bad('`ms`, a number of 0 or more') | ||
if (typeof obj.trace_id !== 'string' || !TRACE_ID.test(obj.trace_id)) await bad('`trace_id`, 32 lowercase hex digits, not all 0') | ||
if ('did' in obj && (typeof obj.did !== 'string' || !obj.did.startsWith('did:'))) await bad('`did` a DID, when there is one') | ||
if (obj.method === GET_BLOB) { | ||
if ('repo' in obj && (typeof obj.repo !== 'string' || !obj.repo.startsWith('did:') || typeof obj.cid !== 'string' || !obj.cid)) await bad('`repo` a DID and `cid` a CID, together') | ||
if ('cid' in obj && !('repo' in obj)) await bad('`cid` only with `repo`') | ||
if ('bytes' in obj && (!int(obj.bytes) || obj.bytes < 0 || !('repo' in obj) || obj.status !== 200)) await bad('`bytes`, a number of 0 or more, with `repo` and `cid`, of a 200') | ||
} else if (['repo', 'cid', 'bytes'].some((k) => k in obj)) await bad('no `repo`, `cid` or `bytes` but of getBlob') | ||
if (obj.level !== (obj.status >= 500 ? 'error' : 'info')) await bad('`level` info, or error for a status of 500 or more') | ||
} else if (obj.msg === 'start') { | ||
if (obj.level !== 'info' || typeof obj.version !== 'string' || !obj.version || obj.port !== Number(life.env.PDS_PORT)) await bad(`level info, a \`version\`, and \`port\` ${life.env.PDS_PORT}`) | ||
| @@ -138,9 +144,15 @@ async function checkRequests(lives) { | ||
if (!rec.status || !rec.traceId || rec.ended === null) continue | ||
const life = lives[rec.life] | ||
const level = rec.status >= 500 ? 'error' : 'info' | ||
// A body cut short once the server it came from was signalled to stop, | ||
// as when it was killed, may have no line: the server writes one as the | ||
// body ends, and a server killed writes nothing more. | ||
const stopped = life.signalled ?? life.ended | ||
if (rec.short && stopped != null && rec.ended >= stopped) continue | ||
// The request may have reached the next start, if the one it was sent | ||
// to was killed first. | ||
if (!writes(life, level) || (lives[rec.life + 1] && !writes(lives[rec.life + 1], level))) continue | ||
// to was killed first: then its answer came after that one exited. | ||
const next = life.ended !== null && rec.ended > life.ended ? lives[rec.life + 1] : undefined | ||
if (!writes(life, level) || (next && !writes(next, level))) continue | ||
const request = { method: rec.method, path: rec.path, traceparent: `00-${rec.traceId}-${rec.spanId}-${rec.sampled ? '01' : '00'}`, status: rec.status } | ||
const lines = byTrace.get(rec.traceId) ?? [] | ||
if (lines.length !== 1) await broke('log', request, 'one `request` line with the request\'s trace id', lines.length ? lines : 'none') | ||
| @@ -150,11 +162,30 @@ async function checkRequests(lives) { | ||
if (line.ms > took + 20) await broke('log', request, `\`ms\` no more than the ${took.toFixed(1)} ms the harness waited for the whole answer`, line) | ||
const did = rec.status < 300 && AUTHED.has(rec.route) ? tokenDids.get(rec.token) : undefined | ||
if (did && line.did !== did) await broke('log', request, { did }, line) | ||
if (rec.route === GET_BLOB) await blobFields(rec, request, line) | ||
checked += 1 | ||
} | ||
count('log lines of the harness\'s requests', checked > 0) | ||
} | ||
| ||
/// A getBlob's `repo`, `cid` and `bytes`: of the blob it asked for, when | ||
/// answered 200 or 500, and of a 200 the bytes the harness read, or, of an | ||
/// answer that ended short, at least those and fewer than it said it had | ||
/// (spec/OPERATIONS.md, "Events"). | ||
async function blobFields(rec, request, line) { | ||
const got = { repo: line.repo, cid: line.cid, bytes: line.bytes } | ||
const want = {} | ||
if (rec.status === 200 || rec.status === 500) Object.assign(want, { repo: rec.params.did, cid: rec.params.cid }) | ||
if (rec.status === 200) { | ||
if (rec.bytes === undefined) want.bytes = Number.isInteger(line.bytes) ? line.bytes : 'a number' | ||
else if (rec.short) { | ||
if (!(line.bytes >= rec.bytes && line.bytes < rec.length)) await broke('log', request, `\`bytes\` no fewer than the ${rec.bytes} the harness read of an answer that ended short, and fewer than its Content-Length ${rec.length}`, got) | ||
want.bytes = line.bytes | ||
} else want.bytes = rec.bytes | ||
} | ||
if (got.repo !== want.repo || got.cid !== want.cid || got.bytes !== want.bytes) await broke('log', request, want, got) | ||
} | ||
| ||
/// Nothing on standard error, but from a start that exited 1 | ||
/// (spec/OPERATIONS.md, "The log"). | ||
async function checkStderr(lives) { | ||
harness/lib/observe.mjs+31−11
| @@ -18,11 +18,14 @@ const realNow = performance.now.bind(performance) | ||
export const now = () => performance.timeOrigin + realNow() | ||
| ||
/// Each request the harness sent the server, in order: `{n, life, traceId, | ||
/// spanId, sampled, method, path, route, status, started, ended, token, | ||
/// commit, did}`. `life` is the server process it went to (`server.lives`), | ||
/// `status` 0 until it is answered, or for good if it never was; `token` | ||
/// the bearer token it carried; `commit` whether its JSON answer says a | ||
/// commit was made, and `did` the DID it names. | ||
/// spanId, sampled, method, path, route, params, status, started, ended, | ||
/// token, commit, did}`, and of a fetch, once its body is read, `bytes`, | ||
/// how many it read, `length`, its `Content-Length` if any, and `short`, | ||
/// true if the body failed before it ended. `life` is the server process it | ||
/// went to (`server.lives`), `params` its query, `status` 0 until it is | ||
/// answered, or for good if it never was; `token` the bearer token it | ||
/// carried; `commit` whether its JSON answer says a commit was made, and | ||
/// `did` the DID it names. | ||
export const sent = [] | ||
| ||
/// Every secret the run handled: passwords, tokens, invite codes, keys, | ||
| @@ -70,7 +73,7 @@ export function begin(method, url, headers, body) { | ||
if (text !== null && /x-www-form-urlencoded/i.test(type)) noteFields(new URLSearchParams(text)) | ||
else if (typeof body === 'string' || (text !== null && /json/.test(type))) noteText(text) | ||
const rec = { | ||
n, life: lifeOf(), ...ctx, method: (method ?? 'GET').toUpperCase(), path: u.pathname, route: routeOf(u.pathname), | ||
n, life: lifeOf(), ...ctx, method: (method ?? 'GET').toUpperCase(), path: u.pathname, route: routeOf(u.pathname), params: Object.fromEntries(u.searchParams), | ||
status: 0, started: now(), ended: null, token: /^Bearer (\S+)$/.exec(auth ?? '')?.[1] ?? null, commit: false, did: null, | ||
} | ||
sent.push(rec) | ||
| @@ -137,15 +140,32 @@ export function watch(serverUrl, life) { | ||
noteSetCookies(res.headers.getSetCookie()) | ||
if (res.redirected) noteUrl(res.url) | ||
const type = res.headers.get('content-type') ?? '' | ||
const copy = res.clone() | ||
rec.read = copy | ||
.arrayBuffer() | ||
.then((buf) => end(rec, res.status, /json|event-stream|text/.test(type) && buf.byteLength < 1 << 22 ? Buffer.from(buf).toString('utf8') : '')) | ||
.catch(() => (rec.ended = now())) | ||
const length = res.headers.get('content-length') | ||
if (length !== null) rec.length = Number(length) | ||
rec.read = readCounted(res.clone(), rec).then((buf) => end(rec, res.status, buf && /json|event-stream|text/.test(type) && buf.byteLength < 1 << 22 ? buf.toString('utf8') : '')) | ||
harness/lib/observe.mjsline 145ResolvedA failed body read now reaches Addressed in b74b63a: a short body that ended once its server was signalled to stop owes no line, and is skipped (checks/logging.mjs, checkRequests). harness/lib/observe.mjsline 145Still unaddressed: a failed read reaches | ||
return res | ||
} | ||
} | ||
| ||
/// The body of `res`, read whole, its bytes counted on `rec` as they come; | ||
/// null, with `rec.short`, if it failed before it ended. | ||
async function readCounted(res, rec) { | ||
rec.bytes = 0 | ||
if (!res.body) return Buffer.alloc(0) | ||
const chunks = [] | ||
try { | ||
for await (const chunk of res.body) { | ||
chunks.push(chunk) | ||
rec.bytes += chunk.byteLength | ||
} | ||
} catch { | ||
rec.short = true | ||
rec.ended = now() | ||
return null | ||
} | ||
return Buffer.concat(chunks) | ||
} | ||
| ||
/// Every answer read whole. | ||
export const settled = () => Promise.all(sent.map((r) => r.read).filter(Boolean)) | ||
| ||
harness/lib/s3.mjs+22−7
| @@ -23,6 +23,16 @@ const WRITES = ['PutObject', 'CopyObject', 'CompleteMultipartUpload'] | ||
/// A response that is never sent: what an operation stores under | ||
/// `'store-then-hang'` it answers to nobody. | ||
const UNANSWERED = { writeHead() {}, end() {}, setHeader() {} } | ||
/// A response that sends its head and the first half of its body's bytes, | ||
/// then drops the connection: what `'cut'` answers. | ||
const cutShort = (res) => ({ | ||
setHeader: (k, v) => res.setHeader(k, v), | ||
writeHead: (...args) => res.writeHead(...args), | ||
end(data) { | ||
const b = data == null ? Buffer.alloc(0) : Buffer.from(data) | ||
res.write(b.subarray(0, Math.floor(b.length / 2)), () => res.socket?.destroy()) | ||
}, | ||
}) | ||
| ||
const XMLNS = 'http://s3.amazonaws.com/doc/2006-03-01/' | ||
const EMPTY_SHA256 = 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855' | ||
| @@ -77,7 +87,7 @@ class S3Error extends Error { | ||
/// bucket, key, path, status, ms, signed}`, `path` the request target as | ||
/// sent; `status` and `ms` are set once it is answered and stay null for | ||
/// one that never is. Besides: `code`, the S3 error code it was answered | ||
/// with; `fault`, `'status'`, `'hang'`, `'store-then-hang'` or `'reset'` when `fail` made it | ||
/// with; `fault`, `'status'`, `'hang'`, `'store-then-hang'`, `'reset'` or `'cut'` when `fail` made it | ||
/// fail; `payload`, its `x-amz-content-sha256`; `encoding`, its | ||
/// `Content-Encoding`; `checksum`, the `x-amz-checksum-*` checked and where | ||
/// it came (`'crc32 header'`, `'crc32 trailer'`); `error`, the stack of an | ||
| @@ -137,6 +147,7 @@ export async function startS3({ accessKeyId, secretAccessKey, region = 'us-east- | ||
(f) => f.count < f.times && (f.bucket == null || f.bucket === rec.bucket) && (f.key == null || f.key === rec.key) && (f.op == null || [f.op].flat().includes(rec.op)), | ||
) | ||
let storeThenHang = false | ||
let cut = false | ||
if (rule) { | ||
rule.count += 1 | ||
if (rule.mode === 'reset') { | ||
| @@ -150,6 +161,9 @@ export async function startS3({ accessKeyId, secretAccessKey, region = 'us-east- | ||
if (rule.mode === 'store-then-hang') { | ||
rec.fault = 'store-then-hang' | ||
storeThenHang = true | ||
} else if (rule.mode === 'cut') { | ||
rec.fault = 'cut' | ||
cut = true | ||
} else if (rule.mode.delayMs) { | ||
rec.fault = 'delay' | ||
await new Promise((ok) => setTimeout(ok, rule.mode.delayMs)) | ||
| @@ -178,7 +192,7 @@ export async function startS3({ accessKeyId, secretAccessKey, region = 'us-east- | ||
} | ||
return | ||
} | ||
await OPS[rec.op](req, res, target, body) | ||
await OPS[rec.op](req, cut ? cutShort(res) : res, target, body) | ||
} catch (err) { | ||
if (!(err instanceof S3Error)) { | ||
rec.error = String(err.stack) | ||
| @@ -606,12 +620,13 @@ export async function startS3({ accessKeyId, secretAccessKey, region = 'us-east- | ||
/// the request handled as ever, that long after it came; `'hang'`, | ||
/// read the request and never answer; `'store-then-hang'`, for a request | ||
/// that writes an object (`WRITES`), store it as if it succeeded and never | ||
/// answer, and for any other `'hang'`; or `'reset'`, destroy the | ||
/// connection at once. Answers the rule, whose `count` is how many it has | ||
/// failed. | ||
/// answer, and for any other `'hang'`; `'reset'`, destroy the | ||
/// connection at once; or `'cut'`, answer as ever but send only the head | ||
/// and the first half of the body's bytes, then destroy the connection. | ||
/// Answers the rule, whose `count` is how many it has failed. | ||
s3.fail = ({ bucket, key, op, times = Infinity, mode }) => { | ||
if (!['hang', 'store-then-hang', 'reset'].includes(mode) && !(Number.isInteger(mode?.status) && mode.status >= 300) && !(Number.isInteger(mode?.delayMs) && mode.delayMs > 0)) | ||
throw new Error(`fail: mode ${JSON.stringify(mode)}: not 'hang', 'store-then-hang', 'reset', {status, code} or {delayMs}`) | ||
if (!['hang', 'store-then-hang', 'reset', 'cut'].includes(mode) && !(Number.isInteger(mode?.status) && mode.status >= 300) && !(Number.isInteger(mode?.delayMs) && mode.delayMs > 0)) | ||
throw new Error(`fail: mode ${JSON.stringify(mode)}: not 'hang', 'store-then-hang', 'reset', 'cut', {status, code} or {delayMs}`) | ||
const rule = { bucket, key, op, times, mode, count: 0 } | ||
failures.push(rule) | ||
return rule | ||
spec/BLOBS.md+7−0
| @@ -440,6 +440,13 @@ have it fail, the same way on both sides, and compare the answers | ||
- `getBlob` of a blob a record references while the store fails its | ||
reads, the same ways, and again once it reads; and a `blobstore failure` | ||
line of `op` `get`. | ||
- `getBlob` of such a blob, of 2 bytes or more, on the server alone, while | ||
the store answers its read with the object's headers and the first half | ||
of its bytes and then closes the connection (the reference is not | ||
compared on a failure after the first byte): `200` with the blob's | ||
`Content-Length`, and the answer ending short of it ("The objects", | ||
above); its `request` line's `bytes` fewer than the blob's size | ||
(`OPERATIONS.md`, "Events"). | ||
- `getBlob` of such a blob whose object the harness deleted from both | ||
buckets, as a backup brought back finds one, and again once it is put | ||
back. | ||