From 0cd95b422456209feeb18ee52f8d80e4cf387c66 Mon Sep 17 00:00:00 2001 From: Rui Chen Date: Fri, 9 Oct 2026 12:18:36 -0400 Subject: [PATCH] fix(upload): let storage pace the block body instead of buffering it The block PUT route read its body through h3's `getRequestWebStream`, which enqueues every `data` event into a ReadableStream that has no `pull` and never pauses the request. When the client sends faster than the storage adapter consumes (lib-storage reads one part, then waits for UploadPart), the rest of the block piles up in process memory. Concurrent uploads multiply it. Hand the Node request stream to `uploadPart` instead, so the adapter's reads pace the client through TCP flow control. `uploadPart` now takes a `Readable`, which also drops the web-stream round trip. tests/proxy-backpressure.test.ts mounts the real upload route on an in-process h3 app, stalls the storage adapter and asserts that less than 64 MiB of a 512 MiB block is read off the socket meanwhile. Before this change the route reads the whole 512 MiB. Refs #274 Signed-off-by: Rui Chen --- lib/storage.ts | 8 +- .../devstoreaccount1/upload/[uploadId].put.ts | 12 +- tests/cleanup-lifecycle.test.ts | 7 +- tests/eager-merge.test.ts | 7 +- tests/proxy-backpressure.test.ts | 113 ++++++++++++++++++ 5 files changed, 120 insertions(+), 27 deletions(-) create mode 100644 tests/proxy-backpressure.test.ts diff --git a/lib/storage.ts b/lib/storage.ts index e56d0f3d..7355be2e 100644 --- a/lib/storage.ts +++ b/lib/storage.ts @@ -1,6 +1,5 @@ /* eslint-disable ts/method-signature-style */ import type { Kysely } from 'kysely' -import type { ReadableStream } from 'node:stream/web' import type { Database, StorageLocation } from './db' import type { Env } from './schemas' import { randomUUID } from 'node:crypto' @@ -326,7 +325,7 @@ export class Storage { return Promise.all(this.mergeStreamPromises) } - async uploadPart(uploadId: number, partIndex: number, stream: ReadableStream) { + async uploadPart(uploadId: number, partIndex: number, stream: Readable) { const upload = await this.db .selectFrom('uploads') .where('id', '=', uploadId) @@ -342,10 +341,7 @@ export class Storage { .where('id', '=', uploadId) .execute() - await this.adapter.uploadStream( - `${upload.folderName}/parts/${partIndex}`, - Readable.fromWeb(stream), - ) + await this.adapter.uploadStream(`${upload.folderName}/parts/${partIndex}`, stream) await this.db .updateTable('uploads') diff --git a/routes/devstoreaccount1/upload/[uploadId].put.ts b/routes/devstoreaccount1/upload/[uploadId].put.ts index 58b35018..ebe3ac9c 100644 --- a/routes/devstoreaccount1/upload/[uploadId].put.ts +++ b/routes/devstoreaccount1/upload/[uploadId].put.ts @@ -1,9 +1,7 @@ -import type { ReadableStream } from 'node:stream/web' import { Buffer } from 'node:buffer' import { randomUUID } from 'node:crypto' import { z } from 'zod' -import { logger } from '~/lib/logger' import { getStorage } from '~/lib/storage' @@ -37,14 +35,10 @@ export default defineEventHandler(async (event) => { const { uploadId } = parsedPathParams.data - const stream = getRequestWebStream(event) - if (!stream) { - logger.debug('Upload: Request body is not a stream') - throw createError({ statusCode: 400, statusMessage: 'Request body must be a stream' }) - } - + // Not h3's `getRequestWebStream`: it enqueues every `data` event and never pauses the + // request, so a body arriving faster than storage consumes it is buffered in full. const storage = await getStorage() - await storage.uploadPart(uploadId, chunkIndex, stream as ReadableStream) + await storage.uploadPart(uploadId, chunkIndex, event.node.req) // prevent random EOF error with in tonistiigi/go-actions-cache caused by missing request id setHeader(event, 'x-ms-request-id', randomUUID()) diff --git a/tests/cleanup-lifecycle.test.ts b/tests/cleanup-lifecycle.test.ts index c35f48c4..73dba28c 100644 --- a/tests/cleanup-lifecycle.test.ts +++ b/tests/cleanup-lifecycle.test.ts @@ -1,4 +1,3 @@ -import type { ReadableStream as NodeReadableStream } from 'node:stream/web' import { randomUUID } from 'node:crypto' import { Readable } from 'node:stream' @@ -95,11 +94,7 @@ describe('cleanup lifecycle', () => { scope: 'refs/heads/main', repoId: '123', }) - await storage.uploadPart( - upload!.id, - 0, - Readable.toWeb(Readable.from('payload')) as NodeReadableStream, - ) + await storage.uploadPart(upload!.id, 0, Readable.from('payload')) const deleteFolder = vi .spyOn(storage.adapter, 'deleteFolder') .mockRejectedValue(new Error('no')) diff --git a/tests/eager-merge.test.ts b/tests/eager-merge.test.ts index 5f37bb02..64cf33af 100644 --- a/tests/eager-merge.test.ts +++ b/tests/eager-merge.test.ts @@ -1,4 +1,3 @@ -import type { ReadableStream as NodeReadableStream } from 'node:stream/web' import { randomUUID } from 'node:crypto' import { Readable } from 'node:stream' @@ -13,11 +12,7 @@ async function uploadParts(storage: Storage, parts: Buffer[]) { const key = randomUUID() const upload = await storage.createUpload({ key, ...scope }) for (const [index, part] of parts.entries()) - await storage.uploadPart( - upload!.id, - index, - Readable.toWeb(Readable.from(part)) as NodeReadableStream, - ) + await storage.uploadPart(upload!.id, index, Readable.from(part)) await storage.completeUpload({ key, ...scope }) const db = await getDatabase() return db diff --git a/tests/proxy-backpressure.test.ts b/tests/proxy-backpressure.test.ts new file mode 100644 index 00000000..1bef7ce8 --- /dev/null +++ b/tests/proxy-backpressure.test.ts @@ -0,0 +1,113 @@ +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 { setTimeout as sleep } from 'node:timers/promises' + +import * as h3 from 'h3' +import { afterAll, afterEach, beforeAll, describe, expect, test, vi } from 'vitest' +import { getStorage } from '~/lib/storage' + +const MiB = 1024 * 1024 +const ENTRY_BYTES = 512 * MiB +const CHUNK_BYTES = 64 * 1024 +// Stream highWaterMarks are KiBs and loopback socket buffers a few MiB. Holding +// more than this means the route is queueing the body in process memory instead +// of letting TCP flow control pace the faster side. +const MAX_BUFFERED_BYTES = 64 * MiB + +// The real route handler on an in-process h3 app, so the test process is the +// server process and its socket and storage calls are observable. +const router = h3.createRouter({ preemptive: true }) // as Nitro: an `undefined` return ends the response +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: route modules call Nitro auto-imports (`defineEventHandler`, + // …) at evaluation time, so they can only load after the stubs above. + const { default: upload } = await import('~/routes/devstoreaccount1/upload/[uploadId].put') + router.put('/upload/:uploadId', upload) + server.listen(0) + await once(server, 'listening') +}) + +afterEach(() => { + vi.restoreAllMocks() + server.closeAllConnections() +}) + +afterAll(async () => { + vi.unstubAllGlobals() + server.close() + await once(server, 'close') +}) + +/** Resolves once `read()` has not changed for `quietMs`, i.e. the pipe has stalled or finished. */ +async function settled(read: () => number, quietMs = 500, timeoutMs = 20_000) { + const deadline = Date.now() + timeoutMs + let last = read() + let quietSince = Date.now() + while (Date.now() < deadline && Date.now() - quietSince < quietMs) { + await sleep(50) + if (read() === last) continue + last = read() + quietSince = Date.now() + } + return last +} + +describe('proxy routes apply backpressure', () => { + test('upload does not buffer a block body that storage is not reading yet', async () => { + const storage = await getStorage() + const created = await storage.createUpload({ + key: `backpressure-${randomUUID()}`, + version: 'v1', + scope: 'refs/heads/main', + repoId: '123', + }) + if (!created) throw new Error('createUpload returned nothing') + + // Storage that stalls (an S3 UploadPart in flight) and drains only when released. + const { promise: storageStalled, resolve: releaseStorage } = Promise.withResolvers() + vi.spyOn(storage.adapter, 'uploadStream').mockImplementation(async (_name, stream) => { + await storageStalled + for await (const _chunk of stream); + }) + + const { port } = server.address() as AddressInfo + const serverSide = once(server, 'request') as Promise<[IncomingMessage, ServerResponse]> + const req = http.request(`http://localhost:${port}/upload/${created.id}`, { + method: 'PUT', + headers: { 'content-length': ENTRY_BYTES }, + }) + const response = once(req, 'response') as Promise<[IncomingMessage]> + const chunk = Buffer.alloc(CHUNK_BYTES) + let sent = 0 + const sendAll = (async () => { + while (sent < ENTRY_BYTES) { + sent += CHUNK_BYTES + if (!req.write(chunk)) await once(req, 'drain') + } + req.end() + })() + + await settled(() => sent) + const sentWhileStalled = sent + const [serverReq] = await serverSide + const readWhileStalled = serverReq.socket.bytesRead + + releaseStorage() + await sendAll + const [res] = await response + res.resume() + expect(res.statusCode).toBe(201) + expect + .soft(readWhileStalled, 'bytes read off the socket while storage was stalled') + .toBeLessThan(MAX_BUFFERED_BYTES) + expect + .soft(sentWhileStalled, 'bytes the client got out while storage was stalled') + .toBeLessThan(MAX_BUFFERED_BYTES) + }, 60_000) +})