diff --git a/README.md b/README.md index 9030701..960adf4 100644 --- a/README.md +++ b/README.md @@ -28,6 +28,18 @@ volumes: cache-data: ``` +## Resource limits + +All optional. + +| Variable | Default | Effect | +| ------------------------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | +| `STORAGE_S3_MAX_SOCKETS` | `50` | Sockets per S3 data pool, for `http://` and `https://` endpoints alike. Reads (GetObject) and writes (uploads, Merges) each get a pool this size. | +| `STORAGE_S3_CONTROL_MAX_SOCKETS` | `16` | Sockets for HEAD, LIST and DELETE requests (cache lookups, cleanup), kept apart from bulk transfers. | +| `STORAGE_S3_CONTROL_QUEUE_TIMEOUT_MS` | `5000` | How long a control request waits for a socket and connection before failing; `0` waits forever. | +| `MAX_CONCURRENT_MERGES` | `16` | Merges one process runs at once. Beyond it, restores stream the parts and a later download merges. | +| `DOWNLOAD_IDLE_TIMEOUT_MS` | `300000` | Closes a download whose client has not read a byte for this long; `0` disables. | + ## Documentation ๐Ÿ‘‰ ๐Ÿ‘ˆ diff --git a/lib/metrics.ts b/lib/metrics.ts index 012d35f..f1190da 100644 --- a/lib/metrics.ts +++ b/lib/metrics.ts @@ -1,5 +1,7 @@ +import type { Agent, ClientRequest } from 'node:http' +import { performance } from 'node:perf_hooks' import { sql } from 'kysely' -import { collectDefaultMetrics, Counter, Gauge, Registry } from 'prom-client' +import { collectDefaultMetrics, Counter, Gauge, Histogram, Registry } from 'prom-client' import { getDatabase } from './db' // Per-process registry. Correct for the shipped single-worker-per-container @@ -42,3 +44,251 @@ export const cacheStorageBytes = new Gauge({ cacheStorageBytes.set(Number(bytes)) }, }) + +const SECONDS_BUCKETS = [0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 30, 60] + +export const cacheLookupDurationSeconds = new Histogram({ + name: 'cache_lookup_duration_seconds', + help: 'Download-URL lookup handling time by result, including the storage existence check.', + labelNames: ['result'], + buckets: SECONDS_BUCKETS, + registers: [metricsRegistry], +}) + +export const cacheDownloadsTotal = new Counter({ + name: 'cache_downloads_total', + help: 'Proxied /download requests by outcome. client_gone: the client hung up before the body finished; idle_timeout: no bytes moved for DOWNLOAD_IDLE_TIMEOUT_MS.', + labelNames: ['result'], + registers: [metricsRegistry], +}) +for (const result of ['completed', 'client_gone', 'idle_timeout', 'not_found', 'error']) + cacheDownloadsTotal.inc({ result }, 0) + +export type MergeKind = 'stream' | 'compose' + +export const cacheMergesTotal = new Counter({ + name: 'cache_merges_total', + help: 'Finished Merges by kind (stream: parts piped through this process; compose: server-side copy) and result.', + labelNames: ['kind', 'result'], + registers: [metricsRegistry], +}) + +export const cacheMergesSkippedTotal = new Counter({ + name: 'cache_merges_skipped_total', + help: 'Merges not started because this process already runs MAX_CONCURRENT_MERGES; a later download retries them.', + registers: [metricsRegistry], +}) + +export const cacheMergeDurationSeconds = new Histogram({ + name: 'cache_merge_duration_seconds', + help: 'Wall time of finished Merges by kind and result.', + labelNames: ['kind', 'result'], + buckets: [1, 5, 15, 30, 60, 120, 300, 600, 1800, 3600], + registers: [metricsRegistry], +}) + +const mergeStartTimes = new Set<{ startedAt: number }>() + +export const cacheMergesInProgress = new Gauge({ + name: 'cache_merges_in_progress', + help: 'Merges running now in this process.', + registers: [metricsRegistry], + collect() { + cacheMergesInProgress.set(mergeStartTimes.size) + }, +}) + +export const cacheMergeOldestAgeSeconds = new Gauge({ + name: 'cache_merge_oldest_age_seconds', + help: 'Age of the longest-running in-progress Merge; 0 when none is running.', + registers: [metricsRegistry], + collect() { + let oldest = Infinity + for (const { startedAt } of mergeStartTimes) oldest = Math.min(oldest, startedAt) + cacheMergeOldestAgeSeconds.set(oldest === Infinity ? 0 : (performance.now() - oldest) / 1000) + }, +}) + +/** Call when a Merge starts; call the returned function exactly once when it settles. */ +export function trackMerge(kind: MergeKind) { + const entry = { startedAt: performance.now() } + mergeStartTimes.add(entry) + return (result: 'success' | 'failure') => { + if (!mergeStartTimes.delete(entry)) return + cacheMergesTotal.inc({ kind, result }) + cacheMergeDurationSeconds.observe( + { kind, result }, + (performance.now() - entry.startedAt) / 1000, + ) + } +} + +// Lease rows, computed at scrape time. Expired rows mean a holder died or stopped +// renewing; a growing active count with no finished Merges means Merges are stuck. +export const cacheLeases = new Gauge({ + name: 'cache_leases', + help: 'Merge and Storage Reader Lease rows by state (active: not yet expired).', + labelNames: ['type', 'state'], + registers: [metricsRegistry], + async collect() { + const db = await getDatabase() + const now = Date.now() + const count = (table: 'merge_leases' | 'storage_reader_leases') => + db + .selectFrom(table) + .select([ + sql`count(*)`.as('total'), + sql`coalesce(sum(case when ${sql.ref('expiresAt')} < ${now} then 1 else 0 end), 0)`.as( + 'expired', + ), + ]) + .executeTakeFirstOrThrow() + const [merge, reader] = await Promise.all([ + count('merge_leases'), + count('storage_reader_leases'), + ]) + for (const [type, row] of [ + ['merge', merge], + ['reader', reader], + ] as const) { + const expired = Number(row.expired) + cacheLeases.set({ type, state: 'expired' }, expired) + cacheLeases.set({ type, state: 'active' }, Number(row.total) - expired) + } + }, +}) + +// --- S3 client --------------------------------------------------------------- + +/** reads: GetObject bodies; writes: uploads and Merges; control: HEAD/LIST/DELETE. */ +export type S3Pool = 'reads' | 'writes' | 'control' + +const s3Agents: { pool: S3Pool; agent: Agent }[] = [] + +export const s3HttpSockets = new Gauge({ + name: 's3_http_sockets', + help: 'S3 agent sockets by pool and state (active: assigned to a request, idle: kept alive). Counts the agent view; a socket the remote end already closed still reads active until it is read or destroyed.', + labelNames: ['pool', 'state'], + registers: [metricsRegistry], + collect() { + const counts = new Map() + for (const { pool, agent } of s3Agents) { + const count = counts.get(pool) ?? { active: 0, idle: 0 } + for (const sockets of Object.values(agent.sockets)) count.active += sockets?.length ?? 0 + for (const sockets of Object.values(agent.freeSockets)) count.idle += sockets?.length ?? 0 + counts.set(pool, count) + } + for (const [pool, { active, idle }] of counts) { + s3HttpSockets.set({ pool, state: 'active' }, active) + s3HttpSockets.set({ pool, state: 'idle' }, idle) + } + }, +}) + +export const s3HttpQueuedRequests = new Gauge({ + name: 's3_http_queued_requests', + help: 'Live S3 requests waiting for a free agent socket, by pool (maxSockets reached). Sustained > 0 means pool starvation.', + labelNames: ['pool'], + registers: [metricsRegistry], + collect() { + const counts = new Map() + for (const { pool, agent } of s3Agents) { + let queued = counts.get(pool) ?? 0 + // Aborted requests stay in the queue until a socket frees; Node then skips them. + for (const requests of Object.values(agent.requests)) + queued += requests?.filter((req) => !req.destroyed).length ?? 0 + counts.set(pool, queued) + } + for (const [pool, queued] of counts) s3HttpQueuedRequests.set({ pool }, queued) + }, +}) + +export const s3HttpMaxSockets = new Gauge({ + name: 's3_http_max_sockets', + help: 'Configured S3 agent socket limit by pool (STORAGE_S3_MAX_SOCKETS, STORAGE_S3_CONTROL_MAX_SOCKETS).', + labelNames: ['pool'], + registers: [metricsRegistry], +}) + +export const s3SocketWaitSeconds = new Histogram({ + name: 's3_socket_wait_seconds', + help: 'Time an S3 request waited for an agent socket, by pool. Requests aborted while queued are not observed; pair with s3_http_queued_requests.', + labelNames: ['pool'], + buckets: [0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1, 5, 10, 30, 60], + registers: [metricsRegistry], +}) + +/** Exposes `agent`'s pool on /metrics and times how long each request waits for a socket. */ +export function instrumentS3Agent(pool: S3Pool, agent: Agent) { + s3Agents.push({ pool, agent }) + s3HttpMaxSockets.set({ pool }, agent.maxSockets) + // `addRequest` is where Node's Agent either hands out a socket or queues the + // request; it is undocumented but the hook every agent wrapper relies on. + const pooled = agent as Agent & { addRequest: (req: ClientRequest, options: unknown) => void } + const addRequest = pooled.addRequest.bind(agent) + pooled.addRequest = (req, options) => { + const queuedAt = performance.now() + req.once('socket', () => + s3SocketWaitSeconds.observe({ pool }, (performance.now() - queuedAt) / 1000), + ) + addRequest(req, options) + } +} + +export const s3RequestsTotal = new Counter({ + name: 's3_requests_total', + help: 'S3 commands by outcome (ok, not_found, aborted, timeout, network, error).', + labelNames: ['command', 'outcome'], + registers: [metricsRegistry], +}) + +export const s3RequestDurationSeconds = new Histogram({ + name: 's3_request_duration_seconds', + help: 'S3 command time until the response headers, including socket wait and SDK retries; excludes streaming a GetObject body.', + labelNames: ['command'], + buckets: SECONDS_BUCKETS, + registers: [metricsRegistry], +}) + +export const s3RequestRetriesTotal = new Counter({ + name: 's3_request_retries_total', + help: 'SDK retry attempts beyond the first, by command.', + labelNames: ['command'], + registers: [metricsRegistry], +}) + +const S3_NETWORK_ERROR_CODES: Record = { + ECONNRESET: true, + ECONNREFUSED: true, + EPIPE: true, + ENOTFOUND: true, + EAI_AGAIN: true, +} + +function s3Outcome(err: unknown) { + const { name, code, $metadata } = (err ?? {}) as { + name?: string + code?: string + $metadata?: { httpStatusCode?: number } + } + if (name === 'AbortError') return 'aborted' + // The SDK renames ECONNRESET/EPIPE to TimeoutError, so check the code first. + if (S3_NETWORK_ERROR_CODES[code ?? '']) return 'network' + if (name === 'TimeoutError' || name === 'RequestTimeout' || code === 'ETIMEDOUT') return 'timeout' + if (name === 'NotFound' || name === 'NoSuchKey' || $metadata?.httpStatusCode === 404) + return 'not_found' + return 'error' +} + +/** Records one S3 command: `err` is the thrown error, absent on success. */ +export function observeS3Request( + commandName: string, + startedAt: number, + attempts: number | undefined, + err?: unknown, +) { + const command = commandName.replace(/Command$/, '') + s3RequestDurationSeconds.observe({ command }, (performance.now() - startedAt) / 1000) + s3RequestsTotal.inc({ command, outcome: err === undefined ? 'ok' : s3Outcome(err) }) + if (attempts && attempts > 1) s3RequestRetriesTotal.inc({ command }, attempts - 1) +} diff --git a/lib/schemas.ts b/lib/schemas.ts index bbae5f5..493e5bd 100644 --- a/lib/schemas.ts +++ b/lib/schemas.ts @@ -5,6 +5,9 @@ export const envStorageDriverSchema = type.or( 'STORAGE_DRIVER': type.unit('s3'), 'STORAGE_S3_BUCKET': 'string', 'STORAGE_S3_SOCKET_TIMEOUT_MS': 'number.integer >= 0 = 10000', + 'STORAGE_S3_MAX_SOCKETS': 'number.integer >= 1 = 50', + 'STORAGE_S3_CONTROL_MAX_SOCKETS': 'number.integer >= 1 = 16', + 'STORAGE_S3_CONTROL_QUEUE_TIMEOUT_MS': 'number.integer >= 0 = 5000', 'AWS_REGION': "string = 'us-east-1'", 'AWS_ENDPOINT_URL?': 'string.url', 'AWS_ACCESS_KEY_ID?': 'string', @@ -84,6 +87,8 @@ export const envBaseSchema = type({ 'DEBUG?': 'unknown', 'ENABLE_DIRECT_DOWNLOADS': 'boolean = false', 'EAGER_MERGE': 'boolean = false', + 'MAX_CONCURRENT_MERGES': 'number.integer >= 1 = 16', + 'DOWNLOAD_IDLE_TIMEOUT_MS': 'number.integer >= 0 = 300000', 'BENCHMARK': 'boolean = false', 'SKIP_TOKEN_VALIDATION': 'boolean = false', 'MANAGEMENT_API_KEY?': 'string', diff --git a/lib/storage.ts b/lib/storage.ts index d40ce61..a03e5aa 100644 --- a/lib/storage.ts +++ b/lib/storage.ts @@ -1,14 +1,16 @@ /* eslint-disable ts/method-signature-style */ import type { ContainerClient } from '@azure/storage-blob' import type { Kysely } from 'kysely' +import type { Writable } from 'node:stream' import type { Database, StorageLocation } from './db' import type { Reservation } from './helpers' +import type { MergeKind, S3Pool } from './metrics' import type { Env } from './schemas' import { randomUUID } from 'node:crypto' -import { once } from 'node:events' import { createReadStream, createWriteStream } from 'node:fs' import fs from 'node:fs/promises' -import { Agent } from 'node:https' +import { Agent as HttpAgent } from 'node:http' +import { Agent as HttpsAgent } from 'node:https' import path from 'node:path' import { PassThrough, Readable } from 'node:stream' import { pipeline } from 'node:stream/promises' @@ -43,6 +45,7 @@ import { getDatabase, isUniqueViolation, retryOnLockConflict } from './db' import { env } from './env' import { generateNumberId, reservationHash } from './helpers' import { logger } from './logger' +import { cacheMergesSkippedTotal, instrumentS3Agent, observeS3Request, trackMerge } from './metrics' import { acquireMergeLease, createReaderLease, @@ -66,6 +69,23 @@ function escapeLikePattern(value: string) { .replaceAll('_', String.raw`\_`) } +/** + * Resolves once `stream` wants more data or is closed. A destroyed stream emits + * no 'drain', and no 'error' when destroyed without one, so waiting on 'drain' + * alone hangs forever once its reader is gone. + */ +function drainOrClose(stream: Writable) { + const { promise, resolve } = Promise.withResolvers() + const done = () => { + stream.off('drain', done) + stream.off('close', done) + resolve() + } + stream.on('drain', done) + stream.on('close', done) + return promise +} + export class ObjectNotFoundError extends Error { constructor(objectName: string) { super(`Object not found in storage: ${objectName}`) @@ -130,6 +150,7 @@ export class Storage { private db private mergeStreamPromises = new Set>() + private activeMerges = 0 adapter private constructor({ db, adapter }: { adapter: StorageAdapter; db: Kysely }) { @@ -198,16 +219,25 @@ export class Storage { ) { if (location.partsDeletedAt) throw new Error('No parts to feed') + // Either sink can be destroyed mid-download: the route destroys the response + // when the client hangs up, and a failed merge upload destroys the merger. + // Waiting on a destroyed sink's 'drain' would park the pump forever, pinning + // the current part's backend read and renewing the merge lease. Keep feeding + // whichever sink is still open, and stop reading once both are gone. + const sinks = [responseStream, mergerStream] for await (const chunk of this.streamParts(location)) { - // attach both drain listeners simultaneously to prevent a race condition where the second stream being faster hangs forever + // attach every drain wait before awaiting any, so a faster sink's 'drain' is never missed const drains = [] - if (!responseStream.write(chunk)) drains.push(once(responseStream, 'drain')) - if (!mergerStream.write(chunk)) drains.push(once(mergerStream, 'drain')) + for (const sink of sinks) { + if (sink.destroyed) continue + if (!sink.write(chunk) && !sink.destroyed) drains.push(drainOrClose(sink)) + } await Promise.all(drains) + // Leaving the loop makes `streamParts` destroy the current part stream. + if (sinks.every((sink) => sink.destroyed)) return } - responseStream.end() - mergerStream.end() + for (const sink of sinks) if (!sink.destroyed) sink.end() await globalThis.gc?.() } @@ -281,25 +311,45 @@ export class Storage { /** * Runs a Merge under a Merge Lease. `write` produces `${folderName}/merged`; * a lease-fenced transaction then marks the Merge complete. Returns false - * when another worker holds the lease. Writing straight to the final object - * is safe (ADR-0004). The returned promise never rejects: failures are logged - * and the merge state rolled back. + * when another worker holds the lease or this process already runs + * MAX_CONCURRENT_MERGES Merges; a skipped Merge is retried by a later + * download. Writing straight to the final object is safe (ADR-0004). The + * returned promise never rejects: failures are logged and the merge state + * rolled back. */ - private async startMerge(location: StorageLocation, write: () => Promise) { - const mergeToken = await acquireMergeLease(this.db, location.id) - if (!mergeToken) return false - - await this.db - .updateTable('storage_locations') - .set({ mergeStartedAt: Date.now() }) - .where('id', '=', location.id) - .execute() + private async startMerge(location: StorageLocation, kind: MergeKind, write: () => Promise) { + // Each Merge holds storage connections and buffers for its whole duration; + // unbounded, a burst of first restores or finalizes exhausts them. + if (this.activeMerges >= env.MAX_CONCURRENT_MERGES) { + cacheMergesSkippedTotal.inc() + return false + } + // Reserve the slot before the first await so concurrent callers cannot overshoot it. + this.activeMerges++ + let mergeToken: string | undefined + try { + mergeToken = await acquireMergeLease(this.db, location.id) + if (mergeToken) + await this.db + .updateTable('storage_locations') + .set({ mergeStartedAt: Date.now() }) + .where('id', '=', location.id) + .execute() + } catch (err) { + this.activeMerges-- + throw err + } + if (!mergeToken) { + this.activeMerges-- + return false + } const renewalTimer = setInterval(() => { void renewMergeLease(this.db, location.id, mergeToken) }, LEASE_RENEWAL_MS) renewalTimer.unref() + const finishMerge = trackMerge(kind) const mergePromise = write() .then(async () => { // The merged object is already written, so losing a deadlock here must @@ -321,8 +371,10 @@ export class Storage { .execute() }), ) + finishMerge('success') }) .catch(async (err) => { + finishMerge('failure') logger.error(`Merge failed for storage location ${location.id}`, { error: err }) await this.db .updateTable('storage_locations') @@ -341,6 +393,7 @@ export class Storage { }) .finally(async () => { clearInterval(renewalTimer) + this.activeMerges-- await releaseMergeLease(this.db, location.id, mergeToken) }) this.mergeStreamPromises.add(mergePromise) @@ -363,7 +416,7 @@ export class Storage { bytes <= compose.maxPartBytes && (index === partSizes.length - 1 || bytes >= compose.minPartBytes), ) - await this.startMerge(location, () => + await this.startMerge(location, composable ? 'compose' : 'stream', () => composable ? compose.run(location.folderName, location.partCount) : this.adapter.uploadStream( @@ -601,7 +654,7 @@ export class Storage { const responseStream = new PassThrough() const mergerStream = new PassThrough() - const merge = await this.startMerge(storageLocation, () => + const merge = await this.startMerge(storageLocation, 'stream', () => this.adapter .uploadStream(`${storageLocation.folderName}/merged`, mergerStream) .catch((err) => { @@ -877,25 +930,76 @@ function accumulateFolder( folders.set(folderName, existing) } +/** reads: GetObject; writes: uploads, multipart and part copies; control: HEAD, LIST, DELETE. */ +interface S3Clients { + reads: S3Client + writes: S3Client + control: S3Client +} + class S3Adapter implements StorageAdapter { static async fromEnv(env: Extract) { const bucket = env.STORAGE_S3_BUCKET - const agent = new Agent({ - keepAlive: true, - maxSockets: 50, - keepAliveMsecs: 1000, - }) - const s3 = new S3Client({ - forcePathStyle: true, - region: env.AWS_REGION, - requestHandler: new NodeHttpHandler({ - httpsAgent: agent, - socketTimeout: env.STORAGE_S3_SOCKET_TIMEOUT_MS, - }), - }) + // One socket pool per kind of work. A streaming Merge holds a part GetObject + // open (paused by backpressure) while it waits for a socket to upload the + // merged object; in one shared pool, as many concurrent Merges as sockets + // deadlock it, and the HeadObject of every cache lookup queues behind all + // bulk transfers. Write holders never wait on reads and control requests + // hold a socket only briefly, so no wait cycle can span pools. + const createClient = (pool: S3Pool, maxSockets: number, connectionTimeout?: number) => { + // Both protocols get the configured pool: NodeHttpHandler picks the agent by + // endpoint scheme, and an http:// endpoint (MinIO, RustFS, an in-cluster + // gateway) would otherwise fall back to the SDK's default agent and ignore + // the configured size. + const agentOptions = { keepAlive: true, maxSockets, keepAliveMsecs: 1000 } + const httpAgent = new HttpAgent(agentOptions) + const httpsAgent = new HttpsAgent(agentOptions) + instrumentS3Agent(pool, httpAgent) + instrumentS3Agent(pool, httpsAgent) + const client = new S3Client({ + forcePathStyle: true, + region: env.AWS_REGION, + requestHandler: new NodeHttpHandler({ + httpAgent, + httpsAgent, + socketTimeout: env.STORAGE_S3_SOCKET_TIMEOUT_MS, + connectionTimeout, + }), + }) + // `initialize` wraps the whole command (retries, socket wait, signing), so the + // duration is what callers wait for; a GetObject settles at response headers. + client.middlewareStack.add( + (next, context) => async (args) => { + const startedAt = performance.now() + try { + const result = await next(args) + const { $metadata } = result.output as { $metadata?: { attempts?: number } } + observeS3Request(context.commandName ?? 'unknown', startedAt, $metadata?.attempts) + return result + } catch (err) { + const { $metadata } = err as { $metadata?: { attempts?: number } } + observeS3Request(context.commandName ?? 'unknown', startedAt, $metadata?.attempts, err) + throw err + } + }, + { step: 'initialize', name: 'cacheServerMetrics' }, + ) + return client + } + const clients: S3Clients = { + reads: createClient('reads', env.STORAGE_S3_MAX_SOCKETS), + writes: createClient('writes', env.STORAGE_S3_MAX_SOCKETS), + // Bounds the wait for a socket plus the connect, so a starved lookup fails + // instead of hanging; cleared once a kept-alive socket is assigned. + control: createClient( + 'control', + env.STORAGE_S3_CONTROL_MAX_SOCKETS, + env.STORAGE_S3_CONTROL_QUEUE_TIMEOUT_MS, + ), + } try { - await s3.send( + await clients.control.send( new HeadBucketCommand({ Bucket: bucket, }), @@ -907,10 +1011,10 @@ class S3Adapter implements StorageAdapter { throw err } - return new S3Adapter({ s3, bucket }) + return new S3Adapter({ clients, bucket }) } - private s3 + private clients private bucket private keyPrefix = 'gh-actions-cache' @@ -922,12 +1026,14 @@ class S3Adapter implements StorageAdapter { run: async (folderName: string, partCount: number) => { const Bucket = this.bucket const Key = `${this.keyPrefix}/${folderName}/merged` - const { UploadId } = await this.s3.send(new CreateMultipartUploadCommand({ Bucket, Key })) + const { UploadId } = await this.clients.writes.send( + new CreateMultipartUploadCommand({ Bucket, Key }), + ) if (!UploadId) throw new Error('S3 did not return an UploadId') try { const Parts = [] for (let PartNumber = 1; PartNumber <= partCount; PartNumber++) { - const copy = await this.s3.send( + const copy = await this.clients.writes.send( new UploadPartCopyCommand({ Bucket, Key, @@ -938,11 +1044,11 @@ class S3Adapter implements StorageAdapter { ) Parts.push({ PartNumber, ETag: copy.CopyPartResult?.ETag }) } - await this.s3.send( + await this.clients.writes.send( new CompleteMultipartUploadCommand({ Bucket, Key, UploadId, MultipartUpload: { Parts } }), ) } catch (err) { - await this.s3 + await this.clients.writes .send(new AbortMultipartUploadCommand({ Bucket, Key, UploadId })) .catch(() => {}) throw err @@ -950,8 +1056,8 @@ class S3Adapter implements StorageAdapter { }, } - constructor({ bucket, s3 }: { s3: S3Client; bucket: string }) { - this.s3 = s3 + constructor({ bucket, clients }: { clients: S3Clients; bucket: string }) { + this.clients = clients this.bucket = bucket } @@ -959,7 +1065,7 @@ class S3Adapter implements StorageAdapter { let continuationToken: string | undefined do { - const response = await this.s3.send( + const response = await this.clients.control.send( new ListObjectsV2Command({ Bucket: this.bucket, Prefix: prefix, @@ -982,7 +1088,7 @@ class S3Adapter implements StorageAdapter { private async deleteByPrefix(prefix: string) { const deleted = { objects: 0, bytes: 0 } while (true) { - const listResponse = await this.s3.send( + const listResponse = await this.clients.control.send( new ListObjectsV2Command({ Bucket: this.bucket, Prefix: prefix }), ) if (!listResponse.Contents || listResponse.Contents.length === 0) break @@ -998,7 +1104,7 @@ class S3Adapter implements StorageAdapter { listResponse.Contents.filter((obj): obj is { Key: string } => !!obj.Key), 1000, ).map((chunkedObjects) => - this.s3.send( + this.clients.control.send( new DeleteObjectsCommand({ Bucket: this.bucket, Delete: { @@ -1024,7 +1130,7 @@ class S3Adapter implements StorageAdapter { async createDownloadStream(objectName: string, range?: RangeRequest): Promise { try { - const response = await this.s3.send( + const response = await this.clients.reads.send( new GetObjectCommand({ Bucket: this.bucket, Key: `${this.keyPrefix}/${objectName}`, @@ -1051,7 +1157,7 @@ class S3Adapter implements StorageAdapter { async objectExists(objectName: string) { try { - await this.s3.send( + await this.clients.control.send( new HeadObjectCommand({ Bucket: this.bucket, Key: `${this.keyPrefix}/${objectName}`, @@ -1079,7 +1185,7 @@ class S3Adapter implements StorageAdapter { async uploadStream(objectName: string, iterator: AsyncIterable) { await new S3Upload({ - client: this.s3, + client: this.clients.writes, params: { Bucket: this.bucket, Key: `${this.keyPrefix}/${objectName}`, @@ -1135,7 +1241,7 @@ class S3Adapter implements StorageAdapter { async createDownloadUrl(objectName: string, expiresAt: number) { return getSignedUrl( - this.s3, + this.clients.reads, new GetObjectCommand({ Bucket: this.bucket, Key: `${this.keyPrefix}/${objectName}`, diff --git a/routes/download/[locationId].ts b/routes/download/[locationId].ts index c31513c..eec603a 100644 --- a/routes/download/[locationId].ts +++ b/routes/download/[locationId].ts @@ -1,7 +1,9 @@ import type { RangeRequest } from '~/lib/storage' import { pipeline } from 'node:stream/promises' import { z } from 'zod' +import { env } from '~/lib/env' import { logger } from '~/lib/logger' +import { cacheDownloadsTotal } from '~/lib/metrics' import { getStorage, RangeNotSatisfiableError } from '~/lib/storage' const pathParamsSchema = z.object({ @@ -43,12 +45,16 @@ export default defineEventHandler(async (event) => { try { download = await storage.download(locationId, range) } catch (err) { - if (!(err instanceof RangeNotSatisfiableError)) throw err + if (!(err instanceof RangeNotSatisfiableError)) { + cacheDownloadsTotal.inc({ result: 'error' }) + throw err + } // An empty entry has no satisfiable range. The filesystem and GCS adapters raise // for any Range on one and Azure for any start past 0, while RustFS (S3) answers // `bytes=0-` with an empty 200. Ignore Range on empty entries (RFC 9110 ยง14.2) so // the response does not depend on the storage driver. if (err.size === 0) { + cacheDownloadsTotal.inc({ result: 'completed' }) setHeader(event, 'content-length', 0) return send(event) } @@ -56,11 +62,13 @@ export default defineEventHandler(async (event) => { if (err.size !== undefined) setHeader(event, 'content-range', `bytes */${err.size}`) return send(event) } - if (!download) + if (!download) { + cacheDownloadsTotal.inc({ result: 'not_found' }) throw createError({ statusCode: 404, message: 'Cache file not found', }) + } if (download.range && download.size !== undefined) { setResponseStatus(event, 206) @@ -77,19 +85,61 @@ export default defineEventHandler(async (event) => { // `sendStream` neither waits for `drain` nor notices client aborts; `pipeline` does both // and destroys the source, which releases its reader lease. `_handled` is an h3 v1 internal. event._handled = true + // The client can hang up while storage is still answering (a read queued behind + // a full socket pool). `pipeline` refuses an already-closed destination with + // ERR_STREAM_UNABLE_TO_PIPE without taking ownership of the source, so release + // the backend read here instead of leaving its socket and reader lease pinned. + const { res } = event.node + if (res.destroyed || res.closed) { + download.stream.destroy() + cacheDownloadsTotal.inc({ result: 'client_gone' }) + logger.debug(`Client aborted /download/${locationId} before storage answered`) + return + } + // The HTTP server has no idle timeout, so a client that stops reading but keeps + // the connection open would hold the backend read, its reader lease and, on a + // first restore, the Merge it paces forever. Bytes moving at any rate keep the + // download alive. + let idleTimer: NodeJS.Timeout | undefined + if (env.DOWNLOAD_IDLE_TIMEOUT_MS > 0) { + const body = download.stream + idleTimer = setTimeout(() => { + body.destroy( + Object.assign(new Error(`No bytes sent for ${env.DOWNLOAD_IDLE_TIMEOUT_MS} ms`), { + code: 'ERR_DOWNLOAD_IDLE_TIMEOUT', + }), + ) + }, env.DOWNLOAD_IDLE_TIMEOUT_MS) + idleTimer.unref() + body.on('data', () => idleTimer?.refresh()) + } try { - await pipeline(download.stream, event.node.res) + await pipeline(download.stream, res) + cacheDownloadsTotal.inc({ result: 'completed' }) } catch (err) { + // Every exit that did not finish the pipe must release the backend read: an + // unread body pins its storage connection and the reader lease it carries. + download.stream.destroy() + const { code } = err as NodeJS.ErrnoException + if (code === 'ERR_DOWNLOAD_IDLE_TIMEOUT') { + cacheDownloadsTotal.inc({ result: 'idle_timeout' }) + logger.warn(`Download /download/${locationId} closed: ${(err as Error).message}`) + return + } // Client went away mid-body. Expected on cancelled jobs and parallel runners. - if ((err as NodeJS.ErrnoException).code === 'ERR_STREAM_PREMATURE_CLOSE') { + if (code === 'ERR_STREAM_PREMATURE_CLOSE' || code === 'ERR_STREAM_UNABLE_TO_PIPE') { + cacheDownloadsTotal.inc({ result: 'client_gone' }) logger.debug(`Client aborted /download/${locationId}: ${(err as Error).message}`) return } + cacheDownloadsTotal.inc({ result: 'error' }) // Headers are out, so Nitro's error handler would crash with ERR_HTTP_HEADERS_SENT. - if (event.node.res.headersSent) { + if (res.headersSent) { logger.error(`Download stream failed for ${locationId}`, { error: err }) return } throw err + } finally { + clearTimeout(idleTimer) } }) diff --git a/routes/twirp/github.actions.results.api.v1.CacheService/GetCacheEntryDownloadURL.post.ts b/routes/twirp/github.actions.results.api.v1.CacheService/GetCacheEntryDownloadURL.post.ts index feb91d0..1c45cbf 100644 --- a/routes/twirp/github.actions.results.api.v1.CacheService/GetCacheEntryDownloadURL.post.ts +++ b/routes/twirp/github.actions.results.api.v1.CacheService/GetCacheEntryDownloadURL.post.ts @@ -1,6 +1,6 @@ import { map, pipe, prop, sortBy } from 'remeda' import { z } from 'zod' -import { cacheRequestsTotal } from '~/lib/metrics' +import { cacheLookupDurationSeconds, cacheRequestsTotal } from '~/lib/metrics' import { getCacheScope } from '~/lib/scope' import { getStorage } from '~/lib/storage' import { readTwirpRequest, sendTwirpResponse, TwirpMessage } from '~/lib/twirp' @@ -21,12 +21,20 @@ export default defineEventHandler(async (event) => { ) const storage = await getStorage() - const match = await storage.getCacheEntryWithDownloadUrl({ - keys: [key, ...(restore_keys ?? [])], - version, - scopes: pipe(scopes, sortBy([prop('Permission'), 'desc']), map(prop('Scope'))), - repoId, - }) + const lookupTimer = cacheLookupDurationSeconds.startTimer() + let match + try { + match = await storage.getCacheEntryWithDownloadUrl({ + keys: [key, ...(restore_keys ?? [])], + version, + scopes: pipe(scopes, sortBy([prop('Permission'), 'desc']), map(prop('Scope'))), + repoId, + }) + } catch (err) { + lookupTimer({ result: 'error' }) + throw err + } + lookupTimer({ result: match ? 'hit' : 'miss' }) cacheRequestsTotal.inc({ result: match ? 'hit' : 'miss' }) diff --git a/tests/download-client-gone.test.ts b/tests/download-client-gone.test.ts new file mode 100644 index 0000000..90d8aeb --- /dev/null +++ b/tests/download-client-gone.test.ts @@ -0,0 +1,158 @@ +import type { IncomingMessage, ServerResponse } from 'node:http' +import type { AddressInfo } from 'node:net' +import { Buffer } from 'node:buffer' +import { randomUUID } from 'node:crypto' +import { once } from 'node:events' +import http from 'node:http' +import { Readable } from 'node:stream' + +import * as h3 from 'h3' +import { afterAll, afterEach, beforeAll, describe, expect, test, vi } from 'vitest' +import { getDatabase } from '~/lib/db' +import { getStorage } from '~/lib/storage' + +/** + * A stand-in for the object store: answers every GET with an unending body, so + * a response only gives its socket back by being read to the end or destroyed. + */ +async function startOrigin() { + const server = http.createServer((_req, res) => { + res.writeHead(200, { 'content-type': 'application/octet-stream' }) + const chunk = Buffer.alloc(64 * 1024) + const pump = () => { + while (!res.destroyed && res.write(chunk)); + } + res.on('drain', pump) + pump() + }) + server.listen(0) + await once(server, 'listening') + const { port } = server.address() as AddressInfo + return { + url: `http://localhost:${port}`, + close: async () => { + server.closeAllConnections() + server.close() + await once(server, 'close') + }, + } +} + +// The real route on an in-process h3 app, as in proxy-backpressure.test.ts, so +// the storage it calls and the sockets it holds are observable here. +const router = h3.createRouter({ preemptive: true }) +const server = http.createServer(h3.toNodeListener(h3.createApp().use(router))) + +beforeAll(async () => { + for (const [name, value] of Object.entries(h3)) vi.stubGlobal(name, value) + // Not a static import: the route calls Nitro auto-imports at evaluation time, + // so it can only load after the stubs above. + const { default: download } = await import('~/routes/download/[locationId]') + router.get('/download/:locationId', download) + server.listen(0) + await once(server, 'listening') +}) + +afterEach(() => { + vi.restoreAllMocks() + server.closeAllConnections() +}) + +afterAll(async () => { + vi.unstubAllGlobals() + server.close() + await once(server, 'close') +}) + +async function createMergedEntry() { + const storage = await getStorage() + const db = await getDatabase() + const key = `client-gone-${randomUUID()}` + const entry = { key, version: 'v1', scope: 'refs/heads/main', repoId: '123' } + const upload = await storage.createUpload(entry) + await storage.uploadPart(upload.id, 0, Readable.from('payload')) + await storage.completeUpload(entry) + const { locationId } = await db + .selectFrom('cache_entries') + .where('key', '=', key) + .select('locationId') + .executeTakeFirstOrThrow() + // Merged, so download() goes straight to one read of the merged object. + await db + .updateTable('storage_locations') + .set({ mergedAt: Date.now() }) + .where('id', '=', locationId) + .execute() + return locationId +} + +/** + * A client can give up on /download while the storage read is still waiting + * for a socket in a saturated pool. The body then arrives for a response that + * is already closed, and `pipeline` rejects a closed destination + * (ERR_STREAM_UNABLE_TO_PIPE) before it takes ownership of the source. Unless + * the route destroys it, the body pins its backend socket and reader lease for + * the life of the process. + */ +describe('download for a client that left before storage answered', () => { + test('releases the backend socket and the reader lease', async () => { + const origin = await startOrigin() + const agent = new http.Agent({ keepAlive: true, maxSockets: 1 }) + const storage = await getStorage() + const db = await getDatabase() + const locationId = await createMergedEntry() + + const { promise: clientGone, resolve: markClientGone } = Promise.withResolvers() + const { promise: adapterSettled, resolve: markAdapterSettled } = Promise.withResolvers() + let body: IncomingMessage | undefined + vi.spyOn(storage.adapter, 'createDownloadStream').mockImplementation(async () => { + try { + await clientGone + const req = http.get(origin.url, { agent }) + const [res] = (await once(req, 'response')) as [IncomingMessage] + body = res + return { stream: res } + } finally { + markAdapterSettled() + } + }) + + try { + const { port } = server.address() as AddressInfo + const serverSide = once(server, 'request') as Promise<[IncomingMessage, ServerResponse]> + const req = http.get(`http://localhost:${port}/download/${locationId}`) + req.on('error', () => {}) + const [, serverRes] = await serverSide + req.destroy() + await once(serverRes, 'close') + markClientGone() + await adapterSettled + + expect(body).toBeDefined() + await vi.waitFor( + () => { + expect( + Object.values(agent.sockets).flat(), + 'sockets held for the gone client', + ).toHaveLength(0) + expect(body!.destroyed, 'backend body destroyed').toBe(true) + }, + { timeout: 5000, interval: 25 }, + ) + await vi.waitFor( + async () => { + const leases = await db + .selectFrom('storage_reader_leases') + .where('storageLocationId', '=', locationId) + .select('id') + .execute() + expect(leases, 'reader leases left behind').toHaveLength(0) + }, + { timeout: 5000, interval: 25 }, + ) + } finally { + agent.destroy() + await origin.close() + } + }, 20_000) +}) diff --git a/tests/download-merge-sink-gone.test.ts b/tests/download-merge-sink-gone.test.ts new file mode 100644 index 0000000..151fbd7 --- /dev/null +++ b/tests/download-merge-sink-gone.test.ts @@ -0,0 +1,158 @@ +import { Buffer } from 'node:buffer' +import { randomUUID } from 'node:crypto' +import { once } from 'node:events' +import { Readable } from 'node:stream' +import { setTimeout as sleep } from 'node:timers/promises' +import { afterEach, describe, expect, test, vi } from 'vitest' +import { getDatabase } from '~/lib/db' +import { getStorage } from '~/lib/storage' + +const PART_COUNT = 3 +const PART_BYTES = 1024 * 1024 + +async function createUnmergedEntry() { + const storage = await getStorage() + const db = await getDatabase() + const key = `merge-sink-gone-${randomUUID()}` + const entry = { key, version: 'v1', scope: 'refs/heads/main', repoId: '123' } + const upload = await storage.createUpload(entry) + if (!upload) throw new Error('createUpload returned nothing') + for (let i = 0; i < PART_COUNT; i++) + await storage.uploadPart(upload.id, i, Readable.from([Buffer.alloc(PART_BYTES, i)])) + await storage.completeUpload(entry) + return db + .selectFrom('cache_entries') + .where('key', '=', key) + .select('locationId') + .executeTakeFirstOrThrow() +} + +/** Records every part stream the download opens, so the test can see each one released. */ +async function trackPartStreams() { + const storage = await getStorage() + const original = storage.adapter.createDownloadStream.bind(storage.adapter) + const parts: Readable[] = [] + vi.spyOn(storage.adapter, 'createDownloadStream').mockImplementation(async (name, range) => { + const download = await original(name, range) + if (name.includes('/parts/')) parts.push(download.stream) + return download + }) + return parts +} + +/** Fails the background merge upload without reading it, as a broken S3 upload would. */ +async function failMergeUpload() { + const storage = await getStorage() + vi.spyOn(storage.adapter, 'uploadStream').mockRejectedValue(new Error('merge upload failed')) +} + +/** Reads one chunk, then hangs up the way the route does when the client leaves. */ +async function leaveAfterFirstChunk(stream: Readable) { + await once(stream, 'readable') + expect(stream.read()).not.toBeNull() + stream.destroy() +} + +async function settles(promise: Promise, timeoutMs = 5000) { + return Promise.race([promise.then(() => 'settled'), sleep(timeoutMs, 'still pending')]) +} + +async function locationState(locationId: string) { + const db = await getDatabase() + const { mergedAt } = await db + .selectFrom('storage_locations') + .where('id', '=', locationId) + .select('mergedAt') + .executeTakeFirstOrThrow() + const mergeLeases = await db + .selectFrom('merge_leases') + .where('storageLocationId', '=', locationId) + .select('token') + .execute() + return { mergedAt, mergeLeases } +} + +afterEach(() => { + vi.restoreAllMocks() +}) + +/** + * The first download of an unmerged entry tees its parts into the client + * response and the background merge upload. When one of them is destroyed + * (client hung up, merge upload failed), a pump waiting for 'drain' parks + * forever: a destroyed stream emits neither 'drain' nor 'error'. That holds the + * part's backend read (an S3 socket), starves the merge, and keeps renewing + * the merge lease for the life of the process. + */ +describe('first download of an unmerged entry', () => { + test('client leaving mid-stream still completes the merge and releases the parts', async () => { + const storage = await getStorage() + const { locationId } = await createUnmergedEntry() + const parts = await trackPartStreams() + + const download = await storage.download(locationId) + if (!download) throw new Error('download returned nothing') + const { stream } = download + await leaveAfterFirstChunk(stream) + + expect(await settles(storage.waitForOngoingMerges()), 'merge settled').toBe('settled') + const { mergedAt, mergeLeases } = await locationState(locationId) + expect(mergedAt, 'merge completed').not.toBeNull() + expect(mergeLeases, 'merge lease released').toHaveLength(0) + expect(parts).toHaveLength(PART_COUNT) + expect( + parts.filter((part) => !part.destroyed), + 'part streams left open', + ).toHaveLength(0) + }, 20_000) + + test('a failed merge upload still serves the whole entry to the client', async () => { + const storage = await getStorage() + const { locationId } = await createUnmergedEntry() + await failMergeUpload() + + const download = await storage.download(locationId) + if (!download) throw new Error('download returned nothing') + const { stream } = download + let received = 0 + const consumed = (async () => { + for await (const chunk of stream) received += (chunk as Buffer).length + })() + + expect(await settles(consumed), 'client download finished').toBe('settled') + expect(received).toBe(PART_COUNT * PART_BYTES) + expect(await settles(storage.waitForOngoingMerges()), 'merge settled').toBe('settled') + const { mergedAt, mergeLeases } = await locationState(locationId) + expect(mergedAt, 'failed merge not marked complete').toBeNull() + expect(mergeLeases, 'merge lease released').toHaveLength(0) + }, 20_000) + + test('client and merge both gone stops reading and destroys the part stream', async () => { + const storage = await getStorage() + const { locationId } = await createUnmergedEntry() + await failMergeUpload() + // An unending part: only being destroyed lets it go, as with a GetObject body. + const part = Readable.from( + (async function* () { + for (;;) { + await sleep(1) + yield Buffer.alloc(64 * 1024) + } + })(), + ) + vi.spyOn(storage.adapter, 'createDownloadStream').mockResolvedValue({ stream: part }) + + const download = await storage.download(locationId) + if (!download) throw new Error('download returned nothing') + const { stream } = download + await leaveAfterFirstChunk(stream) + + await vi.waitFor(() => expect(part.destroyed, 'part stream destroyed').toBe(true), { + timeout: 5000, + interval: 25, + }) + expect(await settles(storage.waitForOngoingMerges()), 'merge settled').toBe('settled') + const { mergeLeases } = await locationState(locationId) + expect(mergeLeases, 'merge lease released').toHaveLength(0) + }, 20_000) +}) diff --git a/tests/merge-concurrency.test.ts b/tests/merge-concurrency.test.ts new file mode 100644 index 0000000..66e6852 --- /dev/null +++ b/tests/merge-concurrency.test.ts @@ -0,0 +1,117 @@ +import { createHash, randomUUID } from 'node:crypto' +import { Readable } from 'node:stream' + +import { afterEach, describe, expect, test } from 'vitest' +import { getDatabase } from '~/lib/db' +import { env } from '~/lib/env' +import { cacheMergesSkippedTotal } from '~/lib/metrics' +import { Storage } from '~/lib/storage' + +const scope = { version: 'v1', scope: 'refs/heads/main', repoId: '123' } +const parts = [Buffer.alloc(256 * 1024, 'a'), Buffer.alloc(256 * 1024, 'b')] +const expected = createHash('sha256').update(Buffer.concat(parts)).digest('hex') + +async function uploadEntry(storage: Storage) { + const key = `merge-cap-${randomUUID()}` + const upload = await storage.createUpload({ key, ...scope }) + for (const [index, part] of parts.entries()) + await storage.uploadPart(upload.id, index, Readable.from(part)) + await storage.completeUpload({ key, ...scope }) + const db = await getDatabase() + return db + .selectFrom('cache_entries') + .innerJoin('storage_locations', 'storage_locations.id', 'cache_entries.locationId') + .where('cache_entries.key', '=', key) + .select(['storage_locations.id as locationId', 'folderName']) + .executeTakeFirstOrThrow() +} + +async function download(storage: Storage, locationId: string) { + const result = await storage.download(locationId) + if (!result) throw new Error(`location ${locationId} not found`) + return result.stream +} + +async function sha256(stream: Readable) { + const hash = createHash('sha256') + for await (const chunk of stream) hash.update(chunk) + return hash.digest('hex') +} + +async function mergeState(locationId: string) { + const db = await getDatabase() + return db + .selectFrom('storage_locations') + .where('id', '=', locationId) + .select(['mergedAt', 'mergeStartedAt']) + .executeTakeFirstOrThrow() +} + +describe('merge concurrency limit', () => { + const originalMaxMerges = env.MAX_CONCURRENT_MERGES + const originalEagerMerge = env.EAGER_MERGE + afterEach(() => { + env.MAX_CONCURRENT_MERGES = originalMaxMerges + env.EAGER_MERGE = originalEagerMerge + }) + + test('a first restore beyond the limit is served from parts without merging', async () => { + env.EAGER_MERGE = false + env.MAX_CONCURRENT_MERGES = 1 + const storage = await Storage.fromEnv() + const first = await uploadEntry(storage) + const second = await uploadEntry(storage) + + try { + // The first restore's Merge is paced by its unread stream, so it still + // holds the only slot when the second restore starts. + // `get()` hands out live value objects, so read the number right away. + const before = await cacheMergesSkippedTotal.get() + const skippedBefore = before.values[0]?.value ?? 0 + const firstStream = await download(storage, first.locationId) + const secondStream = await download(storage, second.locationId) + const after = await cacheMergesSkippedTotal.get() + expect((after.values[0]?.value ?? 0) - skippedBefore, 'merges skipped').toBe(1) + expect(await sha256(secondStream)).toBe(expected) + expect(await sha256(firstStream)).toBe(expected) + await storage.waitForOngoingMerges() + + expect(await mergeState(first.locationId)).not.toMatchObject({ mergedAt: null }) + expect(await mergeState(second.locationId)).toMatchObject({ mergedAt: null }) + + // With the slot free again, the next restore merges the skipped entry. + expect(await sha256(await download(storage, second.locationId))).toBe(expected) + await storage.waitForOngoingMerges() + expect(await mergeState(second.locationId)).not.toMatchObject({ mergedAt: null }) + } finally { + await storage.adapter.deleteFolder(first.folderName) + await storage.adapter.deleteFolder(second.folderName) + } + }) + + test('an eager merge beyond the limit leaves the entry to a later download', async () => { + env.EAGER_MERGE = false + env.MAX_CONCURRENT_MERGES = 1 + const storage = await Storage.fromEnv() + const busy = await uploadEntry(storage) + // An unread first restore keeps its Merge, and the only slot, busy. + const busyStream = await download(storage, busy.locationId) + + env.EAGER_MERGE = true + const eager = await uploadEntry(storage) + try { + // Upload completion awaits the Merge Lease, so a started Merge would have + // stamped mergeStartedAt by now. + expect(await mergeState(eager.locationId)).toEqual({ mergedAt: null, mergeStartedAt: null }) + + expect(await sha256(busyStream)).toBe(expected) + await storage.waitForOngoingMerges() + expect(await sha256(await download(storage, eager.locationId))).toBe(expected) + await storage.waitForOngoingMerges() + expect(await mergeState(eager.locationId)).not.toMatchObject({ mergedAt: null }) + } finally { + await storage.adapter.deleteFolder(busy.folderName) + await storage.adapter.deleteFolder(eager.folderName) + } + }) +}) diff --git a/tests/merge-socket-pool.test.ts b/tests/merge-socket-pool.test.ts new file mode 100644 index 0000000..2fc94cc --- /dev/null +++ b/tests/merge-socket-pool.test.ts @@ -0,0 +1,92 @@ +import type { Env } from '~/lib/schemas' +import { createHash, randomUUID } from 'node:crypto' +import { Readable } from 'node:stream' + +import { afterEach, describe, expect, test } from 'vitest' +import { getDatabase } from '~/lib/db' +import { env } from '~/lib/env' +import { Storage } from '~/lib/storage' + +const MiB = 1024 * 1024 +const POOL = 4 +const scope = { version: 'v1', scope: 'refs/heads/main', repoId: '123' } +const s3Env = env as Extract + +async function uploadEntry(storage: Storage, parts: Buffer[]) { + const key = `merge-pool-${randomUUID()}` + const upload = await storage.createUpload({ key, ...scope }) + for (const [index, part] of parts.entries()) + await storage.uploadPart(upload.id, index, Readable.from(part)) + await storage.completeUpload({ key, ...scope }) + const db = await getDatabase() + return db + .selectFrom('cache_entries') + .innerJoin('storage_locations', 'storage_locations.id', 'cache_entries.locationId') + .where('cache_entries.key', '=', key) + .select(['storage_locations.id as locationId', 'folderName']) + .executeTakeFirstOrThrow() +} + +async function sha256(stream: Readable) { + const hash = createHash('sha256') + for await (const chunk of stream) hash.update(chunk) + return hash.digest('hex') +} + +// A first restore merges its parts while it streams them: it holds a part +// GetObject open and needs another S3 socket to upload the merged object. With +// one shared pool, as many concurrent first restores as sockets each hold a GET +// and wait for an upload socket that never frees, so every restore and every +// later S3 call (lookup HEADs included) hangs. +describe.skipIf(process.env.VITEST_STORAGE_DRIVER !== 's3')('merges and the S3 socket pool', () => { + const originalMaxSockets = s3Env.STORAGE_S3_MAX_SOCKETS + const originalEagerMerge = env.EAGER_MERGE + afterEach(() => { + s3Env.STORAGE_S3_MAX_SOCKETS = originalMaxSockets + env.EAGER_MERGE = originalEagerMerge + }) + + // A deadlock never settles, so it fails as a test timeout. + test( + 'as many concurrent first restores as pool sockets complete and merge', + { timeout: 60_000 }, + async () => { + env.EAGER_MERGE = false + s3Env.STORAGE_S3_MAX_SOCKETS = POOL + const storage = await Storage.fromEnv() + + // Parts above lib-storage's 5 MiB part size, so each merge is a multipart upload. + const parts = [Buffer.alloc(6 * MiB, 'a'), Buffer.alloc(6 * MiB, 'b')] + const expected = createHash('sha256').update(Buffer.concat(parts)).digest('hex') + const entries = [] + for (let i = 0; i < POOL; i++) entries.push(await uploadEntry(storage, parts)) + + try { + const digests = await Promise.all( + entries.map(async ({ locationId }) => { + const download = await storage.download(locationId) + if (!download) throw new Error(`location ${locationId} not found`) + return sha256(download.stream) + }), + ) + expect(digests).toEqual(entries.map(() => expected)) + + await storage.waitForOngoingMerges() + const db = await getDatabase() + const merged = await db + .selectFrom('storage_locations') + .where( + 'id', + 'in', + entries.map((e) => e.locationId), + ) + .where('mergedAt', 'is not', null) + .select('id') + .execute() + expect(merged).toHaveLength(POOL) + } finally { + for (const { folderName } of entries) await storage.adapter.deleteFolder(folderName) + } + }, + ) +}) diff --git a/tests/metrics.test.ts b/tests/metrics.test.ts index b072108..9959203 100644 --- a/tests/metrics.test.ts +++ b/tests/metrics.test.ts @@ -71,5 +71,57 @@ describe('prometheus metrics', () => { // Scrape-time gauge: present and non-negative (collect() ran without throwing). expect(after).toContain('cache_storage_bytes') expect(readCounter(after, 'cache_storage_bytes')).toBeGreaterThanOrEqual(0) + + // Every series the dashboards read is exposed, with or without observations. + for (const name of [ + 'cache_lookup_duration_seconds', + 'cache_downloads_total', + 'cache_merges_total', + 'cache_merges_skipped_total', + 'cache_merge_duration_seconds', + 'cache_merges_in_progress', + 'cache_merge_oldest_age_seconds', + 'cache_leases', + 's3_http_sockets', + 's3_http_queued_requests', + 's3_http_max_sockets', + 's3_socket_wait_seconds', + 's3_requests_total', + 's3_request_duration_seconds', + 's3_request_retries_total', + ]) + expect(after, name).toMatch(new RegExp(`^# TYPE ${name} `, 'm')) + + for (const series of [ + 'cache_lookup_duration_seconds_count{result="hit"}', + 'cache_lookup_duration_seconds_count{result="miss"}', + 'cache_downloads_total{result="completed"}', + ]) + expect(readCounter(after, series), series).toBeGreaterThan(readCounter(before, series)) + expect(after).toContain('cache_downloads_total{result="idle_timeout"}') + expect(after).toContain('cache_leases{type="merge",state="active"}') + expect(after).toContain('cache_leases{type="reader",state="expired"}') + + // The first restore of an unmerged entry runs a streaming Merge in the background. + const merged = 'cache_merges_total{kind="stream",result="success"}' + await expect + .poll(async () => readCounter(await scrape(), merged), { timeout: 10_000 }) + .toBeGreaterThan(readCounter(before, merged)) + + if (process.env.VITEST_STORAGE_DRIVER === 's3') { + const headOk = 's3_requests_total{command="HeadObject",outcome="ok"}' + expect(readCounter(after, headOk)).toBeGreaterThan(readCounter(before, headOk)) + // Upload, restore and lookup each went through their own configured, + // instrumented pool (the test endpoint is http://, so this also proves the + // SDK's default agent is not used). + for (const pool of ['writes', 'reads', 'control']) { + const pooled = + readCounter(after, `s3_http_sockets{pool="${pool}",state="active"}`) + + readCounter(after, `s3_http_sockets{pool="${pool}",state="idle"}`) + expect(pooled, `${pool} sockets`).toBeGreaterThan(0) + } + expect(readCounter(after, 's3_http_max_sockets{pool="reads"}')).toBe(50) + expect(readCounter(after, 's3_http_max_sockets{pool="control"}')).toBe(16) + } }) }) diff --git a/tests/proxy-backpressure.test.ts b/tests/proxy-backpressure.test.ts index 9a7ff4f..72cff49 100644 --- a/tests/proxy-backpressure.test.ts +++ b/tests/proxy-backpressure.test.ts @@ -9,6 +9,8 @@ import { setTimeout as sleep } from 'node:timers/promises' import * as h3 from 'h3' import { afterAll, afterEach, beforeAll, describe, expect, test, vi } from 'vitest' +import { getDatabase } from '~/lib/db' +import { env } from '~/lib/env' import { getStorage } from '~/lib/storage' const MiB = 1024 * 1024 @@ -167,4 +169,112 @@ describe('proxy routes apply backpressure', () => { await vi.waitFor(() => expect(source.destroyed).toBe(true), { timeout: 5000, interval: 50 }) }, 20_000) + + describe('download idle timeout', () => { + const originalIdleTimeout = env.DOWNLOAD_IDLE_TIMEOUT_MS + beforeAll(() => { + env.DOWNLOAD_IDLE_TIMEOUT_MS = 500 + }) + afterAll(() => { + env.DOWNLOAD_IDLE_TIMEOUT_MS = originalIdleTimeout + }) + + test.each([ + { response: 'a whole entry', status: 200, range: undefined }, + { response: 'a Range', status: 206, range: { start: 0, end: ENTRY_BYTES - 1 } }, + ])( + 'releases the storage read of a client that stopped reading $response', + async ({ status, range }) => { + // Real timers and sockets on purpose: the stall comes from TCP flow control, + // which fake timers cannot drive. + let pulled = 0 + function* entry() { + while (pulled < ENTRY_BYTES) { + pulled += CHUNK_BYTES + yield Buffer.alloc(CHUNK_BYTES) + } + } + const source = Readable.from(entry(), { objectMode: false, highWaterMark: CHUNK_BYTES }) + const storage = await getStorage() + vi.spyOn(storage, 'download').mockResolvedValue({ + stream: source, + size: ENTRY_BYTES, + range, + }) + + const { port } = server.address() as AddressInfo + const serverSide = once(server, 'request') as Promise<[IncomingMessage, ServerResponse]> + const req = http.get(`http://localhost:${port}/download/${randomUUID()}`, { + headers: range ? { range: `bytes=${range.start}-${range.end}` } : {}, + }) + req.on('error', () => undefined) + const [res] = (await once(req, 'response')) as [IncomingMessage] + expect(res.statusCode).toBe(status) + res.once('data', () => res.pause()) // stops reading, keeps the connection open + const [, serverRes] = await serverSide + const serverClosed = once(serverRes, 'close') + + // Without an idle timeout neither ever happens: the pipe just stays parked. + await expect(once(source, 'close')).rejects.toMatchObject({ + code: 'ERR_DOWNLOAD_IDLE_TIMEOUT', + }) + await serverClosed + expect(pulled).toBeLessThan(ENTRY_BYTES) + req.destroy() + }, + 20_000, + ) + + test('a stalled first restore is closed and its Merge still completes', async () => { + const storage = await getStorage() + const db = await getDatabase() + const reservation = { + key: `idle-unmerged-${randomUUID()}`, + version: 'v1', + scope: 'refs/heads/main', + repoId: '123', + } + const upload = await storage.createUpload(reservation) + // Far more than loopback socket buffers hold, so the stalled client really blocks the tee. + for (let i = 0; i < 4; i++) + await storage.uploadPart(upload.id, i, Readable.from([Buffer.alloc(8 * MiB, i)])) + await storage.completeUpload(reservation) + const { locationId } = await db + .selectFrom('cache_entries') + .where('key', '=', reservation.key) + .select('locationId') + .executeTakeFirstOrThrow() + + const { port } = server.address() as AddressInfo + const serverSide = once(server, 'request') as Promise<[IncomingMessage, ServerResponse]> + const req = http.get(`http://localhost:${port}/download/${locationId}`) + req.on('error', () => undefined) + const [res] = (await once(req, 'response')) as [IncomingMessage] + expect(res.statusCode).toBe(200) + res.once('data', () => res.pause()) + const [, serverRes] = await serverSide + await once(serverRes, 'close') + req.destroy() + + // The pump keeps feeding the merge once the client's side of the tee is gone. + await storage.waitForOngoingMerges() + const location = await db + .selectFrom('storage_locations') + .where('id', '=', locationId) + .select('mergedAt') + .executeTakeFirstOrThrow() + expect(location.mergedAt).not.toBeNull() + await vi.waitFor( + async () => { + const leases = await db + .selectFrom('storage_reader_leases') + .where('storageLocationId', '=', locationId) + .select('id') + .execute() + expect(leases, 'reader leases left behind').toHaveLength(0) + }, + { timeout: 5000, interval: 50 }, + ) + }, 30_000) + }) }) diff --git a/tests/s3-socket-pool.test.ts b/tests/s3-socket-pool.test.ts new file mode 100644 index 0000000..d876f57 --- /dev/null +++ b/tests/s3-socket-pool.test.ts @@ -0,0 +1,59 @@ +import type { Env } from '~/lib/schemas' +import { randomUUID } from 'node:crypto' +import { Readable } from 'node:stream' +import { setTimeout as sleep } from 'node:timers/promises' + +import { afterEach, describe, expect, test } from 'vitest' +import { env } from '~/lib/env' +import { Storage } from '~/lib/storage' + +const s3Env = env as Extract + +// The test endpoint is http://, so this also covers the agent NodeHttpHandler +// picks for plain-http endpoints (MinIO, RustFS, in-cluster gateways). +describe.skipIf(process.env.VITEST_STORAGE_DRIVER !== 's3')('s3 socket pool', () => { + const originalMaxSockets = s3Env.STORAGE_S3_MAX_SOCKETS + afterEach(() => { + s3Env.STORAGE_S3_MAX_SOCKETS = originalMaxSockets + }) + + test('the configured pool size bounds the sockets used for an http endpoint', async () => { + s3Env.STORAGE_S3_MAX_SOCKETS = 1 + const storage = await Storage.fromEnv() + const folder = `socket-pool-${randomUUID()}` + await storage.adapter.uploadStream(`${folder}/a`, Readable.from([Buffer.from('a')])) + await storage.adapter.uploadStream(`${folder}/b`, Readable.from([Buffer.from('b')])) + + try { + // An unread body keeps its socket: the only one in the pool. + const held = await storage.adapter.createDownloadStream(`${folder}/a`) + const second = storage.adapter.createDownloadStream(`${folder}/b`) + const queued = await Promise.race([second.then(() => false), sleep(1000, true)]) + expect(queued, 'second GET queued for the only socket').toBe(true) + + held.stream.destroy() + const { stream } = await second + expect(Buffer.concat(await stream.toArray()).toString()).toBe('b') + } finally { + await storage.adapter.deleteFolder(folder) + } + }) + + test('a lookup HEAD does not queue behind held reads', async () => { + s3Env.STORAGE_S3_MAX_SOCKETS = 1 + const storage = await Storage.fromEnv() + const folder = `socket-pool-${randomUUID()}` + await storage.adapter.uploadStream(`${folder}/a`, Readable.from([Buffer.from('a')])) + + // A paused restore (or a Merge waiting to upload) keeps its GET socket. + const held = await storage.adapter.createDownloadStream(`${folder}/a`) + try { + const lookup = storage.adapter.objectExists(`${folder}/a`) + const answered = await Promise.race([lookup, sleep(1000, 'queued')]) + expect(answered, 'HeadObject answered while every data socket is held').toBe(true) + } finally { + held.stream.destroy() + await storage.adapter.deleteFolder(folder) + } + }) +}) diff --git a/tests/setup.ts b/tests/setup.ts index 5ca471e..8e8660a 100644 --- a/tests/setup.ts +++ b/tests/setup.ts @@ -44,6 +44,8 @@ const TESTING_ENV_BASE = { | 'ORPHANED_STORAGE_GRACE_PERIOD_HOURS' | 'ENABLE_DIRECT_DOWNLOADS' | 'EAGER_MERGE' + | 'MAX_CONCURRENT_MERGES' + | 'DOWNLOAD_IDLE_TIMEOUT_MS' | 'BENCHMARK' | 'SKIP_TOKEN_VALIDATION' | 'ACTIONS_TOKEN_ISSUER' @@ -85,6 +87,9 @@ const TESTING_ENV_BY_STORAGE_DRIVER = { AWS_REGION: 'us-east-1', STORAGE_S3_BUCKET: 'vitest', STORAGE_S3_SOCKET_TIMEOUT_MS: 10_000, + STORAGE_S3_MAX_SOCKETS: 50, + STORAGE_S3_CONTROL_MAX_SOCKETS: 16, + STORAGE_S3_CONTROL_QUEUE_TIMEOUT_MS: 5000, AWS_ACCESS_KEY_ID: 'rustfsadmin', AWS_SECRET_ACCESS_KEY: 'rustfsadmin', AWS_ENDPOINT_URL: 'http://localhost:9000',