⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.
TypeScript honoissue-managementissue-trackerjira-alternativekanbanlinear-alternativemcpproject-managementreactself-hostedtypescript
fix: verify uploads without holding pooled connections
Tin31a4f737b657
diff --git a/apps/api/src/storage/cleanup-queue.ts b/apps/api/src/storage/cleanup-queue.tsindex 6835591dd..7582060c3 100644--- a/apps/api/src/storage/cleanup-queue.ts+++ b/apps/api/src/storage/cleanup-queue.ts@@ -1,7 +1,10 @@-import { eq, sql } from "drizzle-orm";+import { randomUUID } from "node:crypto";+import { HTTPException } from "hono/http-exception";+import { and, eq, sql } from "drizzle-orm";import db from "../database";import {assetTable,+ jobLeaseTable,projectTable,storageCleanupTable,} from "../database/schema";@@ -13,10 +16,15 @@ export async function queueStorageCleanup() {const uniqueKeys = [...new Set(keys)];if (!uniqueKeys.length) return;- await tx- .insert(storageCleanupTable)- .values(uniqueKeys.map((objectKey) => ({ objectKey })))- .onConflictDoNothing();+ for (let offset = 0; offset < uniqueKeys.length; offset += 500)+ await tx+ .insert(storageCleanupTable)+ .values(+ uniqueKeys+ .slice(offset, offset + 500)+ .map((objectKey) => ({ objectKey })),+ )+ .onConflictDoNothing();}export async function retryStorageCleanup(): Promise<{ degraded: boolean }> {@@ -42,6 +50,10 @@ export async function retryStorageCleanup(): Promise<{ degraded: boolean }> {where: eq(storageCleanupTable.objectKey, item.objectKey),});if (!queued) return;+ const verification = await tx.query.jobLeaseTable.findFirst({+ where: eq(jobLeaseTable.name, `storage-verification:${item.objectKey}`),+ });+ if (verification && verification.expiresAt > new Date()) return;const [asset] = await tx.select({ id: assetTable.id }).from(assetTable)@@ -86,8 +98,7 @@ export async function retryStorageCleanup(): Promise<{ degraded: boolean }> {return { degraded };}-// Coordinate finalization and deletion of this object only. Verification runs-// inside this lock so a finalizer waiting behind cleanup sees the missing object.+// Serialize reference changes, verification leases and deletion for this object only.export async function withStorageObject<T>(objectKey: string,apply: (@@ -101,3 +112,55 @@ export async function withStorageObject<T>(return apply(tx);});}++// A durable lease protects the object while verification runs without a pooled connection.+export async function withVerifiedStorageObject<Verified, Result>(+ objectKey: string,+ verify: () => Promise<Verified>,+ apply: (+ tx: Parameters<Parameters<typeof db.transaction>[0]>[0],+ verified: Verified,+ ) => Promise<Result>,+): Promise<Result> {+ const name = `storage-verification:${objectKey}`;+ const owner = randomUUID();+ await withStorageObject(objectKey, async (tx) => {+ const current = await tx.query.jobLeaseTable.findFirst({+ where: eq(jobLeaseTable.name, name),+ });+ if (current && current.expiresAt > new Date())+ throw new HTTPException(503, {+ message: "Upload verification is already in progress.",+ });+ await tx+ .insert(jobLeaseTable)+ .values({ name, owner, expiresAt: new Date(Date.now() + 60_000) })+ .onConflictDoUpdate({+ target: jobLeaseTable.name,+ set: { owner, expiresAt: new Date(Date.now() + 60_000) },+ });+ });+ try {+ const verified = await verify();+ return await withStorageObject(objectKey, async (tx) => {+ const lease = await tx.query.jobLeaseTable.findFirst({+ where: eq(jobLeaseTable.name, name),+ });+ if (lease?.owner !== owner || lease.expiresAt <= new Date())+ throw new HTTPException(503, {+ message: "Upload verification expired; retry the upload.",+ });+ const result = await apply(tx, verified);+ await tx+ .delete(jobLeaseTable)+ .where(+ and(eq(jobLeaseTable.name, name), eq(jobLeaseTable.owner, owner)),+ );+ return result;+ });+ } finally {+ await db+ .delete(jobLeaseTable)+ .where(and(eq(jobLeaseTable.name, name), eq(jobLeaseTable.owner, owner)));+ }+}diff --git a/apps/api/src/task/index.ts b/apps/api/src/task/index.tsindex a9b1ce15c..daa2b5c5b 100644--- a/apps/api/src/task/index.ts+++ b/apps/api/src/task/index.ts@@ -1,4 +1,4 @@-import { withStorageObject } from "../storage/cleanup-queue";+import { withVerifiedStorageObject } from "../storage/cleanup-queue";import { eq } from "drizzle-orm";import { HTTPException } from "hono/http-exception";import { requireEntitlement } from "../billing/require-entitlement-middleware";@@ -1005,73 +1005,76 @@ const task = apiRouter<BaseVariables & { workspaceId: string }>()});}- const asset = await withStorageObject(normalizedKey, async (db) => {- let uploaded: Awaited<ReturnType<typeof verifyTaskAssetUpload>>;- try {- uploaded = await verifyTaskAssetUpload(normalizedKey, {- size,- contentType,- });- } catch (error) {- throw new HTTPException(- error instanceof InvalidUploadedAssetError ? 400 : 503,- {- message:- error instanceof InvalidUploadedAssetError- ? error.message- : "Unable to verify uploaded object.",- },- );- }-- const [existingAsset] = await db- .select({ id: assetTable.id })- .from(assetTable)- .where(eq(assetTable.objectKey, normalizedKey))- .limit(1);-- const [saved] = existingAsset- ? await db- .update(assetTable)- .set({- workspaceId: taskContext.workspaceId,- projectId: taskContext.projectId,- taskId: taskContext.taskId,- filename,- mimeType: uploaded.contentType,- size: uploaded.size,- kind: isImageContentType(uploaded.contentType)- ? "image"- : "attachment",- surface,- createdBy: userId || null,- })- .where(eq(assetTable.id, existingAsset.id))- .returning({- id: assetTable.id,- })- : await db- .insert(assetTable)- .values({- workspaceId: taskContext.workspaceId,- projectId: taskContext.projectId,- taskId: taskContext.taskId,- objectKey: normalizedKey,- filename,- mimeType: uploaded.contentType,- size: uploaded.size,- kind: isImageContentType(uploaded.contentType)- ? "image"- : "attachment",- surface,- createdBy: userId || null,- })- .returning({- id: assetTable.id,- });-- return saved;- });+ const asset = await withVerifiedStorageObject(+ normalizedKey,+ async () => {+ try {+ return await verifyTaskAssetUpload(normalizedKey, {+ size,+ contentType,+ });+ } catch (error) {+ throw new HTTPException(+ error instanceof InvalidUploadedAssetError ? 400 : 503,+ {+ message:+ error instanceof InvalidUploadedAssetError+ ? error.message+ : "Unable to verify uploaded object.",+ },+ );+ }+ },+ async (db, uploaded) => {+ const [existingAsset] = await db+ .select({ id: assetTable.id })+ .from(assetTable)+ .where(eq(assetTable.objectKey, normalizedKey))+ .limit(1);++ const [saved] = existingAsset+ ? await db+ .update(assetTable)+ .set({+ workspaceId: taskContext.workspaceId,+ projectId: taskContext.projectId,+ taskId: taskContext.taskId,+ filename,+ mimeType: uploaded.contentType,+ size: uploaded.size,+ kind: isImageContentType(uploaded.contentType)+ ? "image"+ : "attachment",+ surface,+ createdBy: userId || null,+ })+ .where(eq(assetTable.id, existingAsset.id))+ .returning({+ id: assetTable.id,+ })+ : await db+ .insert(assetTable)+ .values({+ workspaceId: taskContext.workspaceId,+ projectId: taskContext.projectId,+ taskId: taskContext.taskId,+ objectKey: normalizedKey,+ filename,+ mimeType: uploaded.contentType,+ size: uploaded.size,+ kind: isImageContentType(uploaded.contentType)+ ? "image"+ : "attachment",+ surface,+ createdBy: userId || null,+ })+ .returning({+ id: assetTable.id,+ });++ return saved;+ },+ );if (!asset) {throw new HTTPException(500, {diff --git a/tests/api-integration/project-storage-cleanup.test.ts b/tests/api-integration/project-storage-cleanup.test.tsindex c31d9361a..aa36cdd3e 100644--- a/tests/api-integration/project-storage-cleanup.test.ts+++ b/tests/api-integration/project-storage-cleanup.test.ts@@ -199,3 +199,79 @@ it("gives new objects a turn despite a full batch of permanent retries", async (}),).toBeUndefined();});++it("queues more than the PostgreSQL parameter limit without rolling back", async () => {+ const { queueStorageCleanup } =+ await import("../../apps/api/src/storage/cleanup-queue");+ await db.transaction((tx) =>+ queueStorageCleanup(+ tx,+ Array.from({ length: 66_000 }, (_, i) => `large-project-${i}`),+ ),+ );+ const { sql } = await import("drizzle-orm");+ const count = await db.execute(+ sql`select count(*)::integer as total from ${schema.storageCleanupTable}`,+ );+ expect(count.rows[0].total).toBe(66_000);+});++it("keeps the pool available and protects objects during slow verification", async () => {+ const { withVerifiedStorageObject } =+ await import("../../apps/api/src/storage/cleanup-queue");+ const { sql } = await import("drizzle-orm");+ let finish!: () => void;+ const wait = new Promise<void>((resolve) => {+ finish = resolve;+ });+ let started = 0;+ let allStarted!: () => void;+ const ready = new Promise<void>((resolve) => {+ allStarted = resolve;+ });+ const pending = Array.from({ length: 10 }, (_, i) =>+ withVerifiedStorageObject(+ `slow-${i}`,+ async () => {+ if (++started === 10) allStarted();+ await wait;+ return i;+ },+ async (_tx, value) => value,+ ),+ );+ try {+ await ready;+ expect((await db.execute(sql`select 1 as healthy`)).rows[0].healthy).toBe(+ 1,+ );+ await db.insert(schema.storageCleanupTable).values({ objectKey: "slow-0" });+ await retryStorageCleanup();+ expect(m.deleteS3Object).not.toHaveBeenCalled();+ expect(await db.query.storageCleanupTable.findMany()).toHaveLength(1);+ } finally {+ finish();+ await Promise.all(pending);+ }+ expect(await db.query.jobLeaseTable.findMany()).toHaveLength(0);+});++it("declines to finalize after a verification lease expires", async () => {+ const { withVerifiedStorageObject } =+ await import("../../apps/api/src/storage/cleanup-queue");+ const apply = vi.fn();+ await expect(+ withVerifiedStorageObject(+ "expired",+ async () => {+ await db+ .update(schema.jobLeaseTable)+ .set({ expiresAt: new Date(0) })+ .where(eq(schema.jobLeaseTable.name, "storage-verification:expired"));+ },+ apply,+ ),+ ).rejects.toThrow("expired");+ expect(apply).not.toHaveBeenCalled();+ expect(await db.query.jobLeaseTable.findMany()).toHaveLength(0);+});