mirror of
https://github.com/tdurieux/anonymous_github.git
synced 2026-12-02 09:03:37 +01:00
fix: do not log a visitor who stops a cached download as a 500
The shared cache sends blobs with pipeline(stream, res). When the client goes away, pipeline rejects with ERR_STREAM_PREMATURE_CLOSE. The response is destroyed but req.aborted is false (the POST body was read), so isResponseCancellation did not match and handleError logged a code-less Error with httpStatus 500. Watch the response and the source before piping. If the response closed unfinished before the source failed, rethrow as response_cancelled, which handleError already skips. A source that errors or closes without ending still surfaces as a fault. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
a4f65e7d30
commit
1b20ffc2f0
3 files changed
+138
-6
No files matched your search
@@ -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);
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user