diff --git a/src/core/cached-response.ts b/src/core/cached-response.ts index fe2a76d..28712d7 100644 --- a/src/core/cached-response.ts +++ b/src/core/cached-response.ts @@ -1,4 +1,5 @@ import { recordResponseFailure } from "./request-evidence"; +import { watchClientClose } from "./response-cancellation"; import { createGzip } from "zlib"; import { createHash } from "crypto"; import { Readable, PassThrough } from "stream"; @@ -53,12 +54,19 @@ async function sendCached(content: Readable, res: Response, // Install evidence before pipeline's listeners destroy the response. const localFailure = () => { if (!res.destroyed) recordResponseFailure(res, "unknown", "local_abort"); }; stream.once("error", localFailure); - if (record.encoding === "identity" && !res.req.acceptsEncodings("identity")) { - res.setHeader("Content-Encoding", "gzip"); res.removeHeader("Content-Length"); - const gzip = createGzip(); - gzip.once("error", localFailure); - await pipeline(stream, gzip, res); - } else await pipeline(stream, res); + const clientClosed = watchClientClose(res, stream); + try { + if (record.encoding === "identity" && !res.req.acceptsEncodings("identity")) { + res.setHeader("Content-Encoding", "gzip"); res.removeHeader("Content-Length"); + const gzip = createGzip(); + gzip.once("error", localFailure); + await pipeline(stream, gzip, res); + } else await pipeline(stream, res); + } catch (error) { + // A visitor who stops a download is not a server fault. + if (clientClosed()) throw Object.assign(new Error("response_cancelled"), { cause: error }); + throw error; + } return true; }; const decision = results.decision(key); diff --git a/src/core/response-cancellation.ts b/src/core/response-cancellation.ts index 5ec895e..3a4766e 100644 --- a/src/core/response-cancellation.ts +++ b/src/core/response-cancellation.ts @@ -14,3 +14,19 @@ export function isResponseCancellation(error: unknown, response?: { destroyed?: } return false; } + +/** + * pipeline() rejects with ERR_STREAM_PREMATURE_CLOSE both when the client goes + * away and when the source ends early. Call before piping; the returned check + * is true only when the response closed unfinished before the source failed. + */ +export function watchClientClose(response: { writableFinished?: boolean; once(event: "close", listener: () => void): unknown }, + source: { readableEnded?: boolean; once(event: "close" | "error", listener: () => void): unknown }): () => boolean { + let sourceFailed = false; + let clientClosed = false; + source.once("error", () => { sourceFailed = true; }); + // A source that closes without ending was cut short. + source.once("close", () => { if (!source.readableEnded) sourceFailed = true; }); + response.once("close", () => { if (!sourceFailed && !response.writableFinished) clientClosed = true; }); + return () => clientClosed; +} diff --git a/test/cached-response-cancellation.test.js b/test/cached-response-cancellation.test.js new file mode 100644 index 0000000..84f78e5 --- /dev/null +++ b/test/cached-response-cancellation.test.js @@ -0,0 +1,108 @@ +const { strict: assert } = require("node:assert"); +const { promises: fs } = require("node:fs"); +const http = require("node:http"); +const { tmpdir } = require("node:os"); +const { join } = require("node:path"); +const { PassThrough, Readable, Writable } = require("node:stream"); +const { pipeline } = require("node:stream/promises"); +const { setTimeout } = require("node:timers"); +const { createHash } = require("node:crypto"); +const express = require("express"); +require("ts-node/register/transpile-only"); +const config = require("../src/config").default; +const { sharedBlobCache, closeBlobCaches } = require("../src/core/blob-cache"); +const { watchClientClose, isResponseCancellation } = require("../src/core/response-cancellation"); +const streamer = require("../src/streamer/route").default; + +const body = Buffer.alloc(8 * 1024 * 1024, 7); +const sha = createHash("sha1").update(`blob ${body.length}\0`).update(body).digest("hex"); +const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); + +/** Collect the structured records a test run writes to stdout. */ +function captureLogs() { + const records = []; + const write = process.stdout.write; + process.stdout.write = function (chunk, ...rest) { + for (const line of String(chunk).split("\n")) { + try { const record = JSON.parse(line); if (record && record.severity) { records.push(record); continue; } } catch { /* not a record */ } + if (line) write.call(process.stdout, line + "\n"); + } + const callback = rest.find((arg) => typeof arg === "function"); + if (callback) callback(); + return true; + }; + return { records, restore: () => { process.stdout.write = write; } }; +} + +describe("cached response cancellation", function () { + this.timeout(15000); + let root, old; + beforeEach(async () => { + old = { ...config }; closeBlobCaches(); + root = await fs.mkdtemp(join(tmpdir(), "cached-cancel-")); + Object.assign(config, { STORAGE: "filesystem", FOLDER: root, SHARED_CACHE_ENABLED: true, + SHARED_CACHE_PATH: join(root, "cache"), SHARED_CACHE_BYTES: 64 * 1024 ** 2, + SHARED_CACHE_RESULT_BYTES: 32 * 1024 ** 2, SHARED_CACHE_MAX_FILE_BYTES: 16 * 1024 ** 2, + SHARED_CACHE_FREE_BYTES: 0, BILLING_ENABLED: false }); + }); + afterEach(async () => { + closeBlobCaches(); Object.assign(config, old); + await fs.rm(root, { recursive: true, force: true }); + }); + + it("does not log a client that stops a cached download as a server error", async () => { + const seeded = await sharedBlobCache().getOrFill(`git-${sha}`, async () => Readable.from([body]), async () => `git-${sha}`, body.length); + for await (const chunk of seeded) void chunk; + const app = express(); app.use(express.json()); app.use("/api", streamer); + const server = await new Promise((resolve) => { const s = app.listen(0, "127.0.0.1", () => resolve(s)); }); + const logs = captureLogs(); + try { + await new Promise((resolve) => { + const req = http.request({ host: "127.0.0.1", port: server.address().port, path: "/api", method: "POST", + headers: { "content-type": "application/json" } }, (res) => { + res.once("data", () => req.destroy()); + res.on("error", () => undefined); + res.on("close", resolve); + }); + req.on("error", resolve); + req.end(JSON.stringify({ token: "", repoFullName: "owner/repo", repoId: "anon", sha, size: body.length, + filePath: "video.bin", anonymizerOptions: { terms: [], filePath: "video.bin" } })); + }); + await wait(300); + } finally { + logs.restore(); + server.closeAllConnections(); + await new Promise((resolve) => server.close(resolve)); + } + const faults = logs.records.filter((record) => record.severity === "error" || record.severity === "warn"); + assert.deepEqual(faults, []); + }); + + it("names a client disconnect but keeps a source that ended early as a failure", async () => { + const attribute = async (closeFirst) => { + const source = new PassThrough(); + // The "late" response never acknowledges its write, like a slow socket. + const response = new Writable({ write(_chunk, _encoding, done) { if (closeFirst !== "late") done(); } }); + const clientClosed = watchClientClose(response, source); + const piping = pipeline(source, response); + source.write("partial"); + if (closeFirst === "late") source.end(); + await wait(5); + if (closeFirst !== "source") response.destroy(); + else source.destroy(); + const error = await piping.then(() => undefined, (failure) => failure); + return { error, clientClosed: clientClosed(), cancellation: isResponseCancellation(error, response) }; + }; + const client = await attribute("client"); + assert.equal(client.error.code, "ERR_STREAM_PREMATURE_CLOSE"); + assert.equal(client.clientClosed, true); + // The source was fully read but the response had not flushed yet. + const late = await attribute("late"); + assert.equal(late.error.code, "ERR_STREAM_PREMATURE_CLOSE"); + assert.equal(late.clientClosed, true); + const source = await attribute("source"); + assert.equal(source.error.code, "ERR_STREAM_PREMATURE_CLOSE"); + assert.equal(source.clientClosed, false); + assert.equal(source.cancellation, false); + }); +});