chadtmiller.com/monolith
An atproto PDS
0
0
Blobstore connections kept 90 s; a request failed on its way sent again
.changeset/blobstore-connections.mdnew+7−0
| @@ -0,0 +1,7 @@ | ||
--- | ||
default: patch | ||
--- | ||
| ||
# Blobs in a bucket are read and stored over kept connections | ||
| ||
With `PDS_BLOBSTORE_S3_BUCKET` set, the server keeps a connection to the store open for up to 90 seconds between requests, instead of 2, so most `getBlob`s and uploads no longer open a connection and do a TLS handshake first. A request that fails before any answer, as when the store closes an idle connection just as the request is sent, is sent once more over a new connection, within the same timeout. | ||
crates/pds-server/src/blobstore.rs+33−19
| @@ -504,7 +504,10 @@ impl Drop for Turn<'_> { | ||
/// The bucket, and the deletes it is owed. | ||
pub(crate) struct Bucket { | ||
s: Settings, | ||
/// Keeps a connection unused for up to 90 seconds. | ||
http: reqwest::Client, | ||
/// Keeps none: what a request that failed on its way is sent again with. | ||
fresh: reqwest::Client, | ||
/// Each object's turn while some upload or delete waits on it or holds it. | ||
turns: Mutex<Turns>, | ||
/// The accounts whose strays the deleter is to look at. | ||
| @@ -516,18 +519,20 @@ pub(crate) struct Bucket { | ||
| ||
impl Bucket { | ||
pub(crate) fn new(s: Settings) -> Result<Bucket, String> { | ||
let http = reqwest::Client::builder() | ||
.no_proxy() | ||
.redirect(reqwest::redirect::Policy::none()) | ||
.connect_timeout(s.request_timeout.min(Duration::from_secs(5))) | ||
// A store may close a connection it holds idle (Node's HTTP | ||
// server does after 5 seconds) just as a request goes out on it. | ||
.pool_idle_timeout(Duration::from_secs(2)) | ||
.build() | ||
.map_err(|e| format!("an HTTP client: {e}"))?; | ||
let builder = || { | ||
reqwest::Client::builder() | ||
.no_proxy() | ||
.redirect(reqwest::redirect::Policy::none()) | ||
.connect_timeout(s.request_timeout.min(Duration::from_secs(5))) | ||
}; | ||
let built = | ||
|b: reqwest::ClientBuilder| b.build().map_err(|e| format!("an HTTP client: {e}")); | ||
let http = built(builder().pool_idle_timeout(Duration::from_secs(90)))?; | ||
let fresh = built(builder().pool_max_idle_per_host(0))?; | ||
Ok(Bucket { | ||
s, | ||
http, | ||
fresh, | ||
turns: Mutex::default(), | ||
due: Mutex::default(), | ||
doomed: Mutex::default(), | ||
| @@ -535,6 +540,22 @@ impl Bucket { | ||
}) | ||
} | ||
| ||
/// Send `req` over a connection an earlier request left open, if one is; | ||
/// one that fails on its way, as when the store closes that connection | ||
/// just as it goes out, once more over a connection of its own. Every | ||
/// request to the store may be made twice to the same effect | ||
/// (`spec/BLOBS.md`, "Requests to the store"). | ||
async fn send(&self, req: reqwest::Request) -> reqwest::Result<reqwest::Response> { | ||
let again = req.try_clone(); | ||
match crate::ops::execute(Target::Blobstore, &self.http, req).await { | ||
Err(e) if !e.is_connect() && !e.is_timeout() => match again { | ||
Some(req) => crate::ops::execute(Target::Blobstore, &self.fresh, req).await, | ||
None => Err(e), | ||
}, | ||
sent => sent, | ||
} | ||
} | ||
| ||
/// Wait for the turn of `did`'s object `cid`. | ||
pub(crate) async fn turn(&self, did: &str, cid: &str) -> Turn<'_> { | ||
let key = (did.to_string(), cid.to_string()); | ||
| @@ -683,7 +704,7 @@ impl Bucket { | ||
wait: Duration, | ||
) -> Result<reqwest::StatusCode, String> { | ||
let sent = tokio::time::timeout(wait, async { | ||
let res = crate::ops::execute(Target::Blobstore, &self.http, req).await?; | ||
let res = self.send(req).await?; | ||
let status = res.status(); | ||
let _ = res.bytes().await; | ||
Ok::<_, reqwest::Error>(status) | ||
| @@ -743,9 +764,7 @@ impl Bucket { | ||
}; | ||
let wait = self.s.request_timeout; | ||
let first = tokio::time::timeout(wait, async { | ||
let mut res = crate::ops::execute(Target::Blobstore, &self.http, req) | ||
.await | ||
.map_err(|_| None)?; | ||
let mut res = self.send(req).await.map_err(|_| None)?; | ||
if res.status() != reqwest::StatusCode::OK { | ||
return Err(None); | ||
} | ||
| @@ -812,12 +831,7 @@ impl Bucket { | ||
.inspect_err(|why| failure("get", did, why))?; | ||
let wait = self.s.request_timeout; | ||
let late = || format!("no answer within {} ms", wait.as_millis()); | ||
let mut res = match tokio::time::timeout( | ||
wait, | ||
crate::ops::execute(Target::Blobstore, &self.http, req), | ||
) | ||
.await | ||
{ | ||
let mut res = match tokio::time::timeout(wait, self.send(req)).await { | ||
Ok(Ok(res)) => res, | ||
Ok(Err(e)) => return Err(e.to_string()), | ||
Err(_) => return Err(late()), | ||
harness/checks/blobstore.mjs+36−1
| @@ -23,6 +23,7 @@ import { compareGetBlob, hold, landed, model, plainBody, rawCid, referenceAgain, | ||
| ||
const UPLOAD = 'com.atproto.repo.uploadBlob' | ||
const SPEC = 'spec/BLOBS.md, "Where blobs are kept"' | ||
const STORE_REQUESTS = 'spec/BLOBS.md, "Requests to the store"' | ||
/// How long the server has to bring its bucket to what it holds. | ||
const WITHIN_MS = 60_000 | ||
| ||
| @@ -243,6 +244,40 @@ export async function uploadDuringDelete(acct) { | ||
await referenceAgain(acct, m, cid, 'on its way as the blob stopped being held', 'uploaded as it stopped being held') | ||
} | ||
| ||
/// getBlob of a blob a record references while the store resets the | ||
/// connection of each side's first read of it, once: sent again over a | ||
/// connection of its own, it is read back whole, on both sides alike | ||
/// (spec/BLOBS.md, "Requests to the store"). | ||
export async function resetOnce(acct) { | ||
const cid = await referencedBlob(acct) | ||
if (!cid) return | ||
const rules = [BUCKETS.reference, BUCKETS.server].map((bucket) => s3.fail({ bucket, op: READS, mode: 'reset', times: 1 })) | ||
const a = await compareGetBlob('getBlob, the store resetting its first read once', (side) => ({ did: didOf(side, acct), cid })) | ||
s3.clearFailures() | ||
if (rules.some((r) => r.count !== 1) || a.status !== 200) await differ('getBlob, the store resetting its first read once', { cid }, { reset: [1, 1], status: 200 }, { reset: rules.map((r) => r.count), status: a.status }, STORE_REQUESTS) | ||
} | ||
| ||
/// Two getBlobs of the server's 3 s apart, past the 2 s a client might keep | ||
/// a connection and within the 5 s the store keeps one: the second read | ||
/// goes over the connection the first left open (spec/BLOBS.md, "Requests | ||
/// to the store"). | ||
export async function keptConnection(acct) { | ||
const cid = await referencedBlob(acct) | ||
if (!cid) return | ||
const key = serverKey(acct, cid) | ||
const read = async () => { | ||
const got = await xrpc(cand, 'com.atproto.sync.getBlob', { params: { did: didOf(cand, acct), cid }, raw: true }) | ||
if (got.status !== 200) await differ('getBlob, for the store\'s connections', { cid }, 200, got.status, STORE_REQUESTS) | ||
return s3.requests.findLast((r) => r.bucket === BUCKETS.server && r.op === 'GetObject' && r.key === key) | ||
} | ||
const first = await read() | ||
await wait(3000) | ||
const second = await read() | ||
const kept = Boolean(first && second && second !== first && second.connection === first.connection) | ||
if (!kept) await differ('the server\'s reads from the store, 3 s apart', { cid }, 'the second over the connection the first left open', { first: first?.connection ?? 'no read', second: second && second !== first ? second.connection : 'no read' }, STORE_REQUESTS) | ||
count('a connection to the store kept between reads', true) | ||
} | ||
| ||
/// A blob a record of the account references, not taken down: one it has, | ||
/// or one made. | ||
async function referencedBlob(acct) { | ||
| @@ -371,4 +406,4 @@ export async function blobstoreCounted() { | ||
} | ||
| ||
/// The steps a run with --s3 adds, by weight. | ||
export const S3_STEPS = [[failedUpload, 3], [failedRead, 2], [cutRead, 1], [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], [resetOnce, 1], [keptConnection, 1]] | ||
harness/lib/s3.mjs+6−3
| @@ -84,8 +84,9 @@ class S3Error extends Error { | ||
/// Answers `{url, makeBucket, objects, remove, requests, rejected, fail, | ||
/// put, clearFailures, close}`: | ||
/// - `requests`, every request in the order it came, `{at, method, op, | ||
/// 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 | ||
/// bucket, key, path, status, ms, signed, connection}`, `path` the request | ||
/// target as sent, `connection` the number of the connection it came on, | ||
/// from 1 in the order they were made; `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'`, `'reset'` or `'cut'` when `fail` made it | ||
/// fail; `payload`, its `x-amz-content-sha256`; `encoding`, its | ||
| @@ -110,6 +111,7 @@ export async function startS3({ accessKeyId, secretAccessKey, region = 'us-east- | ||
const uploads = new Map() | ||
const failures = [] | ||
const sockets = new Set() | ||
let connections = 0 | ||
let served = 0 | ||
let uploadsMade = 0 | ||
const s3 = { requests: [], rejected: [] } | ||
| @@ -123,6 +125,7 @@ export async function startS3({ accessKeyId, secretAccessKey, region = 'us-east- | ||
}) | ||
}) | ||
server.on('connection', (c) => { | ||
c.number = ++connections | ||
sockets.add(c) | ||
c.on('close', () => sockets.delete(c)) | ||
}) | ||
| @@ -130,7 +133,7 @@ export async function startS3({ accessKeyId, secretAccessKey, region = 'us-east- | ||
async function handle(req, res) { | ||
const started = performance.now() | ||
const requestId = (++served).toString(16).toUpperCase().padStart(16, '0') | ||
const rec = { at: Date.now(), method: req.method, op: 'Unknown', bucket: null, key: null, path: req.url, status: null, ms: null, signed: false } | ||
const rec = { at: Date.now(), method: req.method, op: 'Unknown', bucket: null, key: null, path: req.url, status: null, ms: null, signed: false, connection: req.socket.number } | ||
s3.requests.push(rec) | ||
res.setHeader('x-amz-request-id', requestId) | ||
res.setHeader('x-amz-id-2', requestId) | ||
spec/BLOBS.md+20−0
| @@ -264,6 +264,21 @@ store's certificate is verified. They are the operator's, to a store the | ||
operator names, often on a private address, so SSRF protection (`PROXY.md`) | ||
does not apply to them. | ||
| ||
A request goes over a connection an earlier one left open, if the store | ||
keeps one open; the server keeps one unused for up to 90 seconds. Every | ||
request the server makes of the store may be made twice to the same effect | ||
(a `PUT` of the same bytes to the same key, a `GET`, a `DELETE`), so one | ||
that fails on its way, the connection closed before any answer came, as | ||
when the store closes a connection it held idle just as the request is | ||
sent, is sent once more over a connection of its own, within the same | ||
time limit. Only a request that fails so twice, or one the store answers | ||
and then fails, fails as "The objects" says below. | ||
| ||
*Note:* a store across a network, as R2 is from a server outside | ||
Cloudflare, takes tens of milliseconds and a TLS handshake to open a | ||
connection: a server that kept none between requests paid that on most | ||
`getBlob`s and uploads. | ||
| ||
### The objects | ||
| ||
Each blob an account holds is one object, keyed `blocks/<did>/<cid>`, its | ||
| @@ -450,6 +465,11 @@ have it fail, the same way on both sides, and compare the answers | ||
- `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. | ||
- `getBlob` of such a blob while the store resets the connection of each | ||
side's first read of it, once: on both sides `200`, the blob whole. | ||
- On the server alone, two `getBlob`s of such a blob 3 s apart, the store | ||
keeping a connection open 5 s: the second read goes over the connection | ||
the first left open. | ||
- A record deleted, the last to reference a blob, while the store fails | ||
the server's deletes (the reference's go on): both answer alike, and the | ||
server logs a `blobstore failure` of `op` `delete`. | ||