diff --git a/server/src/__tests__/skill-package-storage-throttle.test.ts b/server/src/__tests__/skill-package-storage-throttle.test.ts new file mode 100644 index 00000000000..d5cedb98a16 --- /dev/null +++ b/server/src/__tests__/skill-package-storage-throttle.test.ts @@ -0,0 +1,154 @@ +import { randomUUID } from "node:crypto"; +import { promises as fs } from "node:fs"; +import { createServer, type IncomingMessage, type ServerResponse } from "node:http"; +import type { AddressInfo } from "node:net"; +import os from "node:os"; +import path from "node:path"; +import express from "express"; +import request from "supertest"; +import { eq } from "drizzle-orm"; +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; +import { companies, companySkillRepositorySnapshots as snapshots, createDb } from "@paperclipai/db"; +import type { CompanySkillVersionFileInventoryEntry } from "@paperclipai/shared"; +import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js"; +import { errorHandler } from "../middleware/error-handler.js"; +import { skillPackageStore } from "../services/skill-package-store.js"; +import { createS3StorageProvider } from "../storage/s3-provider.js"; +import { createStorageService } from "../storage/service.js"; + +const captureExceptionMock = vi.hoisted(() => vi.fn()); +vi.mock("../sentry.js", () => ({ captureException: captureExceptionMock })); +vi.mock("../telemetry.js", () => ({ getTelemetryClient: () => null })); + +const SLOW_DOWN = ` +SlowDownPlease reduce your request rate.req-503`; + +const objects = new Map(); +const puts: Array<{ key: string; contentMd5: string | undefined }> = []; +let throttledPuts = 0; + +function respond(req: IncomingMessage, res: ServerResponse, body: Buffer) { + const key = decodeURIComponent((req.url ?? "").split("?")[0]!.replace(/^\/bucket\//, "")); + if (req.method === "PUT") { + puts.push({ key, contentMd5: req.headers["content-md5"] as string | undefined }); + if (throttledPuts > 0) { + throttledPuts--; + res.writeHead(503, { "content-type": "application/xml" }); + res.end(SLOW_DOWN); + return; + } + objects.set(key, body); + res.writeHead(200, { etag: '"saved"' }); + res.end(); + return; + } + if (req.method === "GET" || req.method === "HEAD") { + const object = objects.get(key); + if (!object) { + res.writeHead(404, { "content-type": "application/xml" }); + res.end("NoSuchKey"); + return; + } + res.writeHead(200, { "content-length": object.length, etag: '"saved"' }); + res.end(req.method === "GET" ? object : undefined); + return; + } + res.writeHead(204); + res.end(); +} + +const server = createServer((req, res) => { + const chunks: Buffer[] = []; + req.on("data", chunk => chunks.push(chunk as Buffer)); + req.on("end", () => respond(req, res, Buffer.concat(chunks))); +}); + +const files: CompanySkillVersionFileInventoryEntry[] = [ + { path: "skills/one/SKILL.md", kind: "skill", content: "---\nname: one\ndescription: Test one\n---\nUse it.\n" }, +]; + +const support = await getEmbeddedPostgresTestSupport(); +describe.skipIf(!support.supported)("skill package uploads under storage request-rate limits", () => { + let database: Awaited>; + let db: ReturnType; + let home: string; + let storage: ReturnType; + const savedEnv = { ...process.env }; + + beforeAll(async () => { + await new Promise(resolve => server.listen(0, "127.0.0.1", resolve)); + const endpoint = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; + process.env.AWS_ACCESS_KEY_ID = "fixture-access-key"; + process.env.AWS_SECRET_ACCESS_KEY = "fixture-secret-key"; + delete process.env.AWS_SESSION_TOKEN; + delete process.env.AWS_PROFILE; + home = await fs.mkdtemp(path.join(os.tmpdir(), "skill-package-throttle-")); + process.env.PAPERCLIP_HOME = home; + database = await startEmbeddedPostgresTestDatabase("skill-package-throttle-"); + db = createDb(database.connectionString, { maxConnections: 2 }); + storage = createStorageService(createS3StorageProvider({ bucket: "bucket", region: "us-east-1", endpoint, forcePathStyle: true })); + }); + + beforeEach(() => { + objects.clear(); + puts.length = 0; + throttledPuts = 0; + captureExceptionMock.mockReset(); + vi.spyOn(Math, "random").mockReturnValue(0); + }); + afterEach(() => vi.restoreAllMocks()); + + afterAll(async () => { + process.env = savedEnv; + server.closeAllConnections(); + await new Promise(resolve => server.close(() => resolve())); + await db?.$client.end({ timeout: 1 }); + await database?.cleanup(); + if (home) await fs.rm(home, { recursive: true, force: true }); + }); + + async function company() { + const id = randomUUID(); + await db.insert(companies).values({ id, name: "Throttle test", issuePrefix: `T${id.slice(0, 6)}` }); + return id; + } + + it("resends the archive after a transient SlowDown and publishes the package", async () => { + const companyId = await company(); + throttledPuts = 1; + + const id = await skillPackageStore(db, storage).prepare(companyId, files); + + const [row] = await db.select().from(snapshots).where(eq(snapshots.id, id)); + expect(row!.storage?.archiveKey).toBeTruthy(); + const archivePuts = puts.filter(put => put.key.endsWith("files.tar.gz")); + expect(archivePuts).toHaveLength(2); + expect(archivePuts.every(put => put.contentMd5)).toBe(true); + }); + + it("answers persistent throttling with 503 and lets the same caller retry at once", async () => { + const companyId = await company(); + throttledPuts = Number.POSITIVE_INFINITY; + const store = skillPackageStore(db, storage); + const app = express(); + app.post("/prepare", async (_req, res) => { res.json({ id: await store.prepare(companyId, files) }); }); + app.use(errorHandler); + + const throttled = await request(app).post("/prepare"); + + expect(throttled.status).toBe(503); + expect(throttled.headers["retry-after"]).toBe("30"); + expect(throttled.body).toEqual({ + error: "File storage is temporarily unavailable or is limiting requests. Try again in a moment.", + code: "storage_unavailable", + }); + expect(captureExceptionMock).not.toHaveBeenCalled(); + + throttledPuts = 0; + const retried = await request(app).post("/prepare"); + + expect(retried.status).toBe(200); + const [row] = await db.select().from(snapshots).where(eq(snapshots.id, retried.body.id)); + expect(row!.storage).not.toBeNull(); + }); +}); diff --git a/server/src/__tests__/storage-unavailable-error-handler.test.ts b/server/src/__tests__/storage-unavailable-error-handler.test.ts new file mode 100644 index 00000000000..809143a6df3 --- /dev/null +++ b/server/src/__tests__/storage-unavailable-error-handler.test.ts @@ -0,0 +1,45 @@ +import express from "express"; +import request from "supertest"; +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { errorHandler } from "../middleware/error-handler.js"; +import { recordStorageFailure } from "../storage/failure-diagnostics.js"; + +const captureExceptionMock = vi.hoisted(() => vi.fn()); +vi.mock("../sentry.js", () => ({ captureException: captureExceptionMock })); +vi.mock("../telemetry.js", () => ({ getTelemetryClient: () => null })); + +function createApp(error: unknown) { + const app = express(); + app.post("/work", async () => { throw error; }); + app.use(errorHandler); + return app; +} + +function storageFailure(error: Error, errorCode: string, httpStatus: number | null) { + recordStorageFailure(error, { provider: "s3", operation: "read_object_body", errorCode, httpStatus, requestId: null, attempts: 3 }); + return error; +} + +describe("storage failures in the error handler", () => { + beforeEach(() => captureExceptionMock.mockReset()); + + it("answers a storage connection reset with 503, not as a client abort", async () => { + const reset = storageFailure(Object.assign(new Error("aborted"), { code: "ECONNRESET" }), "ECONNRESET", null); + + const res = await request(createApp(reset)).post("/work"); + + expect(res.status).toBe(503); + expect(res.headers["retry-after"]).toBe("30"); + expect(res.body.code).toBe("storage_unavailable"); + expect(captureExceptionMock).not.toHaveBeenCalled(); + }); + + it("still reports a storage credential rejection as a server fault", async () => { + const rejected = storageFailure(Object.assign(new Error("expired"), { name: "ExpiredToken" }), "ExpiredToken", 400); + + const res = await request(createApp(rejected)).post("/work"); + + expect(res.status).toBe(500); + expect(captureExceptionMock).toHaveBeenCalledTimes(1); + }); +}); diff --git a/server/src/middleware/error-handler.ts b/server/src/middleware/error-handler.ts index 758c3b26c67..a58bd7eba1e 100644 --- a/server/src/middleware/error-handler.ts +++ b/server/src/middleware/error-handler.ts @@ -24,6 +24,7 @@ import { isOpenRouterCatalogUnavailable } from "../services/openrouter-models.js import { ENVIRONMENT_PROVIDER_UNAVAILABLE_CODE, readTransientSandboxCreationRefusal } from "../services/environment-provider-unavailable-error.js"; import { isEndedDbPoolError } from "../database-retry.js"; import { ToolGatewayHttpError } from "../services/tool-gateway.js"; +import { isStorageCredentialRejection, isStorageUnavailableError, recordedStorageFailureDiagnostics, STORAGE_TEMPORARILY_UNAVAILABLE_MESSAGE, STORAGE_UNAVAILABLE_CODE } from "../storage/storage-unavailable.js"; export interface ErrorContext { error: { @@ -299,7 +300,8 @@ export function errorHandler( // answer, so skip the error sinks and just close out the response. if ( rootError.message === "aborted" && - (rootError as NodeJS.ErrnoException).code === "ECONNRESET" + (rootError as NodeJS.ErrnoException).code === "ECONNRESET" && + !isStorageUnavailableError(rootError) ) { if (!res.headersSent) res.status(499); res.end(); @@ -355,6 +357,18 @@ export function errorHandler( return; } + if (isStorageUnavailableError(rootError) && !isStorageCredentialRejection(rootError)) { + logger.warn({ method: req.method, route: req.route?.path, storageFailure: recordedStorageFailureDiagnostics(rootError) }, + "File storage was unavailable for a request"); + if (!res.headersSent) { + res.set("Retry-After", "30"); + res.status(503).json({ error: STORAGE_TEMPORARILY_UNAVAILABLE_MESSAGE, code: STORAGE_UNAVAILABLE_CODE }); + } else { + res.end(); + } + return; + } + const reportableError = sanitizeSecretSensitiveError(req, rootError); attachErrorContext( req, diff --git a/server/src/services/skill-package-store.ts b/server/src/services/skill-package-store.ts index 11c14f3765b..56b3cdaf104 100644 --- a/server/src/services/skill-package-store.ts +++ b/server/src/services/skill-package-store.ts @@ -514,7 +514,7 @@ export function skillPackageStore(db: Db, suppliedStorage?: StorageService, cach try { const archive = await writeSkillPackageArchive(archivePath, files, signal); await backend.putFile({ companyId, namespace: "skill-packages", objectKey: upload.archiveKey, originalFilename: "files.tar.gz", - contentType: "application/gzip", body: createReadStream(archivePath), byteSize: archive.bytes, sha256: archive.sha256, signal }); + contentType: "application/gzip", body: createReadStream(archivePath), byteSize: archive.bytes, sha256: archive.sha256, sourceFile: archivePath, signal }); await backend.putFile({ companyId, namespace: "skill-packages", objectKey: upload.manifestKey, originalFilename: "manifest.json", contentType: "application/json", body: manifestBuffer, signal }); const receipt: SkillPackageStorageReceipt = { format: "tar-gzip-v1", provider: backend.provider, ...(!restore ? { durable: true } : {}), diff --git a/server/src/storage/storage-unavailable.ts b/server/src/storage/storage-unavailable.ts index 111cc0649fc..ac87eaa3e71 100644 --- a/server/src/storage/storage-unavailable.ts +++ b/server/src/storage/storage-unavailable.ts @@ -9,6 +9,8 @@ export const STORAGE_UNAVAILABLE_WAIT_RETRY_REASON = "storage_unavailable_wait"; export const STORAGE_UNAVAILABLE_MESSAGE = "File storage was unavailable, so this attempt stopped before it could save its work. Paperclip will retry automatically when storage is back."; +export const STORAGE_TEMPORARILY_UNAVAILABLE_MESSAGE = "File storage is temporarily unavailable or is limiting requests. Try again in a moment."; + export const STORAGE_CREDENTIALS_REJECTED_MESSAGE = "File storage rejected Paperclip's storage credentials (they may have expired or been rotated), so this attempt stopped before it could save its work. Paperclip will retry automatically when valid credentials are available."; /** For a storage failure that no storage wait owns, such as a run whose native @@ -64,6 +66,10 @@ function recordedStorageFailure(error: unknown) { return null; } +export function recordedStorageFailureDiagnostics(error: unknown) { + return recordedStorageFailure(error)?.diagnostics ?? null; +} + export function isStorageCredentialRejection(error: unknown): boolean { const recorded = recordedStorageFailure(error); return recorded !== null && isCredentialRejectionCode(recorded.diagnostics.errorCode, recorded.diagnostics.httpStatus);