import { describe, expect, it, vi } from "vitest"; import { STORAGE_BYTES_PER_GB } from "@hivegrid/entitlements"; import { assertTenantStorageReservation, resolveTenantStorageCapacity, resolveTenantStorageUsage, TenantStorageCapacityError, withTenantStorageWriteReservation, } from "./storage-capacity.server"; const now = new Date("2026-07-30T12:00:00.000Z"); function subscription(overrides: Record = {}) { return { status: "active", planCode: "starter", seatQuantity: 8, officeSeatQuantity: 3, fieldSeatQuantity: 6, storageAddOnCodes: ["storage_100gb"], trialEndsAt: null, frozenAt: null, cancelledAt: null, products: [ { createdAt: new Date("2026-07-01T00:00:00.000Z"), cancelledAt: null, endsAt: null, currentPeriodStart: null, planCode: "starter", seatQuantity: 9, officeSeatQuantity: 3, fieldSeatQuantity: 6, storageAddOnCodes: ["storage_100gb"], quantity: 9, subscriptionProduct: { code: "starter", lagoPlanCode: "starter", kind: "base_plan" }, }, ], ...overrides, }; } describe("tenant storage capacity", () => { it("resolves the active commercial plan, role seats, and storage add-ons", async () => { const client = { tenantSubscription: { findUnique: vi.fn().mockResolvedValue(subscription()) }, }; await expect(resolveTenantStorageCapacity("tenant_1", client, now)).resolves.toEqual({ available: true, capacity: { planCode: "starter", includedStorageGb: 100, additionalSeatStorageGb: 20, addOnStorageGb: 100, totalStorageGb: 220, totalStorageBytes: 220 * STORAGE_BYTES_PER_GB, }, }); }); it("fails closed for frozen billing and missing active base products", async () => { const frozenClient = { tenantSubscription: { findUnique: vi.fn().mockResolvedValue(subscription({ status: "frozen", frozenAt: now })) }, }; await expect(resolveTenantStorageCapacity("tenant_1", frozenClient, now)).resolves.toMatchObject({ available: false, reason: "billing_read_only", }); const missingPlanClient = { tenantSubscription: { findUnique: vi.fn().mockResolvedValue(subscription({ products: [] })) }, }; await expect(resolveTenantStorageCapacity("tenant_1", missingPlanClient, now)).resolves.toMatchObject({ available: false, reason: "plan_unknown", }); }); it("counts stored files and in-progress reservations under the tenant lock", async () => { const tx = { $executeRaw: vi.fn().mockResolvedValue(1), $queryRaw: vi.fn().mockResolvedValue([{ storedBytes: 50n, reservedBytes: 25n }]), tenantSubscription: { findUnique: vi.fn().mockResolvedValue(subscription()) }, }; await expect(assertTenantStorageReservation(tx as never, "tenant_1", 100, now)).resolves.toMatchObject({ storedBytes: 50, reservedBytes: 25, requestedBytes: 100, }); expect(tx.$executeRaw).toHaveBeenCalledOnce(); }); it("projects stored and in-progress bytes without taking the reservation lock", async () => { const tx = { $executeRaw: vi.fn(), $queryRaw: vi.fn().mockResolvedValue([{ storedBytes: 50n, reservedBytes: 25n }]), tenantSubscription: { findUnique: vi.fn().mockResolvedValue(subscription()) }, }; await expect(resolveTenantStorageUsage(tx as never, "tenant_1", now)).resolves.toMatchObject({ available: true, storedBytes: 50, reservedBytes: 25, remainingBytes: 220 * STORAGE_BYTES_PER_GB - 75, }); expect(tx.$executeRaw).not.toHaveBeenCalled(); }); it("rejects reservations that exceed the paid capacity", async () => { const tx = { $executeRaw: vi.fn().mockResolvedValue(1), $queryRaw: vi.fn().mockResolvedValue([{ storedBytes: BigInt(99 * STORAGE_BYTES_PER_GB), reservedBytes: 0n }]), tenantSubscription: { findUnique: vi.fn().mockResolvedValue( subscription({ officeSeatQuantity: 2, fieldSeatQuantity: 5, storageAddOnCodes: [], products: [ { ...subscription().products[0], officeSeatQuantity: 2, fieldSeatQuantity: 5, storageAddOnCodes: [], }, ], }) ), }, }; await expect(assertTenantStorageReservation(tx as never, "tenant_1", 2 * STORAGE_BYTES_PER_GB, now)).rejects.toMatchObject({ code: "STORAGE_QUOTA_EXCEEDED", }); }); it("persists a tenant-wide reservation before upload and swaps it for the File commit under the same lock", async () => { let reservationStatus = "in_progress"; const events: string[] = []; const tx = { $executeRaw: vi.fn().mockImplementation(async () => { events.push("lock"); return 1; }), $queryRaw: vi.fn().mockResolvedValue([{ storedBytes: 50n, reservedBytes: 25n }]), tenantSubscription: { findUnique: vi.fn().mockResolvedValue(subscription()) }, file: { findFirst: vi.fn().mockResolvedValue({ id: "file_1" }) }, fileUpload: { create: vi.fn().mockImplementation(async ({ data }) => { events.push("reservation"); return { id: data.id, tenantId: data.tenantId, targetFileId: data.targetFileId, totalSizeBytes: data.totalSizeBytes }; }), findFirst: vi.fn().mockImplementation(async () => ({ id: "reservation_1", status: reservationStatus })), updateMany: vi.fn().mockImplementation(async ({ data }) => { reservationStatus = data.status; events.push(`reservation:${data.status}`); return { count: 1 }; }), }, }; await expect( withTenantStorageWriteReservation({ reservation: { reservationId: "reservation_1", tenantId: "tenant_1", actorUserId: "user_1", targetFileId: "file_1", originalFilename: "invoice.pdf", mimeType: "application/pdf", sizeBytes: 100, now, }, runTransaction: async (operation) => operation(tx as never), upload: async () => { events.push("upload"); return { key: "files/file_1" }; }, commit: async (_commitTx, stored) => { events.push(`commit:${stored.key}`); return "committed"; }, rollbackUpload: vi.fn(), }) ).resolves.toBe("committed"); expect(events).toEqual(["lock", "reservation", "upload", "lock", "commit:files/file_1", "reservation:completed"]); expect(tx.fileUpload.create).toHaveBeenCalledWith({ data: expect.objectContaining({ status: "in_progress", targetFileId: "file_1", totalSizeBytes: 100, expiresAt: new Date("9999-12-31T23:59:59.999Z"), }), select: { id: true, tenantId: true, targetFileId: true, totalSizeBytes: true }, }); expect(tx.file.findFirst).toHaveBeenCalledWith({ where: { id: "file_1", tenantId: "tenant_1", sizeBytes: 100 }, select: { id: true }, }); }); it("deletes a failed object before cancelling its paid-capacity reservation", async () => { let reservationStatus = "in_progress"; const events: string[] = []; const tx = { $executeRaw: vi.fn().mockResolvedValue(1), $queryRaw: vi.fn().mockResolvedValue([{ storedBytes: 0n, reservedBytes: 0n }]), tenantSubscription: { findUnique: vi.fn().mockResolvedValue(subscription()) }, file: { findFirst: vi.fn() }, fileUpload: { create: vi.fn().mockResolvedValue({ id: "reservation_1", tenantId: "tenant_1", targetFileId: "file_1", totalSizeBytes: 100 }), findFirst: vi.fn().mockImplementation(async () => ({ id: "reservation_1", status: reservationStatus })), updateMany: vi.fn().mockImplementation(async ({ data }) => { reservationStatus = data.status; events.push(`reservation:${data.status}`); return { count: 1 }; }), }, }; await expect( withTenantStorageWriteReservation({ reservation: { reservationId: "reservation_1", tenantId: "tenant_1", actorUserId: "user_1", targetFileId: "file_1", originalFilename: "invoice.pdf", mimeType: "application/pdf", sizeBytes: 100, now, }, runTransaction: async (operation) => operation(tx as never), upload: async () => ({ key: "files/file_1" }), commit: async () => { throw new Error("database write failed"); }, rollbackUpload: async () => { events.push("object:deleted"); }, }) ).rejects.toThrow("database write failed"); expect(events).toEqual(["object:deleted", "reservation:cancelled"]); expect(reservationStatus).toBe("cancelled"); }); it("rejects a commit that did not persist the exact reserved File row", async () => { let reservationStatus = "in_progress"; const rollbackUpload = vi.fn().mockResolvedValue(undefined); const tx = { $executeRaw: vi.fn().mockResolvedValue(1), $queryRaw: vi.fn().mockResolvedValue([{ storedBytes: 0n, reservedBytes: 0n }]), tenantSubscription: { findUnique: vi.fn().mockResolvedValue(subscription()) }, file: { findFirst: vi.fn().mockResolvedValue(null) }, fileUpload: { create: vi.fn().mockResolvedValue({ id: "reservation_1", tenantId: "tenant_1", targetFileId: "file_1", totalSizeBytes: 100 }), findFirst: vi.fn().mockImplementation(async () => ({ id: "reservation_1", status: reservationStatus })), updateMany: vi.fn().mockImplementation(async ({ data }) => { reservationStatus = data.status; return { count: 1 }; }), }, }; await expect( withTenantStorageWriteReservation({ reservation: { reservationId: "reservation_1", tenantId: "tenant_1", actorUserId: "user_1", targetFileId: "file_1", originalFilename: "invoice.pdf", mimeType: "application/pdf", sizeBytes: 100, now, }, runTransaction: async (operation) => operation(tx as never), upload: async () => ({ key: "files/file_1" }), commit: async () => "callback-returned-without-file", rollbackUpload, }) ).rejects.toMatchObject({ code: "STORAGE_RESERVATION_INVALID" }); expect(rollbackUpload).toHaveBeenCalledWith({ key: "files/file_1" }); expect(reservationStatus).toBe("cancelled"); }); it("keeps an undeletable object charged through a durable in-progress reservation", async () => { let reservationStatus = "in_progress"; const tx = { $executeRaw: vi.fn().mockResolvedValue(1), $queryRaw: vi.fn().mockResolvedValue([{ storedBytes: 0n, reservedBytes: 0n }]), tenantSubscription: { findUnique: vi.fn().mockResolvedValue(subscription()) }, file: { findFirst: vi.fn() }, fileUpload: { create: vi.fn().mockImplementation(async ({ data }) => ({ id: data.id, tenantId: data.tenantId, targetFileId: data.targetFileId, totalSizeBytes: data.totalSizeBytes, })), findFirst: vi.fn().mockImplementation(async () => ({ id: "reservation_1", status: reservationStatus })), updateMany: vi.fn().mockImplementation(async ({ data }) => { reservationStatus = data.status; return { count: 1 }; }), }, }; await expect( withTenantStorageWriteReservation({ reservation: { reservationId: "reservation_1", tenantId: "tenant_1", actorUserId: "user_1", targetFileId: "file_1", originalFilename: "invoice.pdf", mimeType: "application/pdf", sizeBytes: 100, now, }, runTransaction: async (operation) => operation(tx as never), upload: async () => ({ key: "files/file_1" }), commit: async () => { throw new Error("database write failed"); }, rollbackUpload: async () => { throw new Error("object delete failed"); }, }) ).rejects.toMatchObject({ message: "Storage write and rollback both failed", errors: [expect.objectContaining({ message: "database write failed" }), expect.objectContaining({ message: "object delete failed" })], }); expect(reservationStatus).toBe("in_progress"); expect(tx.fileUpload.updateMany).not.toHaveBeenCalled(); expect(tx.fileUpload.create).toHaveBeenCalledWith( expect.objectContaining({ data: expect.objectContaining({ expiresAt: new Date("9999-12-31T23:59:59.999Z") }), }) ); }); });