// @vitest-environment node import { beforeEach, describe, expect, it, vi } from "vitest"; import { getRlsExecutionContext, runWithRlsContext, runWithRlsTransaction } from "@hivegrid/db/rls-context.server"; const mocks = vi.hoisted(() => ({ createOwnedTenantWithShkDefaults: vi.fn(), getUser: vi.fn(), getUserInfo: vi.fn(), createIdempotentTenantEvent: vi.fn(), autosubscribeToTrialOrFreePlan: vi.fn(), postCommitWarn: vi.fn(), })); vi.mock("~/locale/i18next.server", () => ({ getTranslations: vi.fn(async () => ({ t: (key: string) => key })), })); vi.mock("~/domain/tenant-bootstrap/tenantBootstrapService.server", () => ({ createOwnedTenantWithShkDefaults: mocks.createOwnedTenantWithShkDefaults, })); vi.mock("~/utils/db/users.db.server", () => ({ getUser: mocks.getUser })); vi.mock("~/utils/session.server", () => ({ getUserInfo: mocks.getUserInfo })); vi.mock("~/modules/events/services/.server/EventsService", () => ({ default: { createIdempotentTenantEvent: mocks.createIdempotentTenantEvent }, })); vi.mock("~/utils/services/.server/pricingService", () => ({ autosubscribeToTrialOrFreePlan: mocks.autosubscribeToTrialOrFreePlan, })); vi.mock("~/utils/logger.server", () => ({ createScopedLogger: vi.fn(() => ({ warn: mocks.postCommitWarn })), })); vi.mock("~/utils/app/CanonicalUrlUtils", () => ({ appPath: ({ tenantSlug, path }: { tenantSlug: string; path: string }) => `/app/${tenantSlug}/${path}`, })); import { TenantsApi } from "./TenantsApi"; const CREATION_REQUEST_KEY = "d7077797-054b-497a-b1ce-8e4f36257a96"; const ACCOUNT_EVENT_IDEMPOTENCY_KEY = `tenant-bootstrap:tenant_1:${CREATION_REQUEST_KEY}:account-created`; describe("TenantsApi.create RLS provisioning", () => { beforeEach(() => { vi.clearAllMocks(); mocks.getUserInfo.mockResolvedValue({ userId: "user_1" }); const user = { id: "user_1", email: "owner@example.test", firstName: "Ada", lastName: "Lovelace", locale: "de", createdAt: new Date("2026-07-15T08:00:00.000Z"), defaultTenantId: null, }; mocks.getUser.mockResolvedValue(user); mocks.createOwnedTenantWithShkDefaults.mockImplementation(async () => { expect(getRlsExecutionContext()).toMatchObject({ userId: "user_1" }); return { tenant: { id: "tenant_1", name: "Acme", slug: "acme" }, user: { ...user, defaultTenantId: "tenant_1" }, replayed: false, }; }); mocks.autosubscribeToTrialOrFreePlan.mockImplementation(async () => { expect(getRlsExecutionContext()).toMatchObject({ userId: "user_1", tenantId: "tenant_1" }); expect(getRlsExecutionContext()?.transaction).toBeUndefined(); }); mocks.createIdempotentTenantEvent.mockImplementation(async () => { expect(getRlsExecutionContext()).toMatchObject({ userId: "user_1", tenantId: "tenant_1" }); expect(getRlsExecutionContext()?.transaction).toBeUndefined(); }); }); it("runs replay-safe post-commit work outside any bootstrap or marker transaction", async () => { const request = new Request("https://admin.example.test/accounts", { method: "POST" }); const result = await runWithRlsContext({ userId: "user_1" }, () => TenantsApi.create({ request, name: "Acme", slug: "acme", creationRequestKey: CREATION_REQUEST_KEY }) ); expect(mocks.createOwnedTenantWithShkDefaults).toHaveBeenCalledWith({ user: expect.objectContaining({ id: "user_1", email: "owner@example.test" }), name: "Acme", slug: "acme", creationRequestKey: CREATION_REQUEST_KEY, t: expect.any(Function), }); expect(mocks.autosubscribeToTrialOrFreePlan).toHaveBeenCalledWith( expect.objectContaining({ tenantId: "tenant_1", userId: "user_1", throwOnFailure: true, idempotencyKey: CREATION_REQUEST_KEY, }) ); expect(mocks.createIdempotentTenantEvent).toHaveBeenCalledWith( expect.objectContaining({ event: "account.created", tenantId: "tenant_1", userId: "user_1", idempotencyKey: ACCOUNT_EVENT_IDEMPOTENCY_KEY, }) ); expect(mocks.autosubscribeToTrialOrFreePlan.mock.invocationCallOrder[0]).toBeGreaterThan( mocks.createOwnedTenantWithShkDefaults.mock.invocationCallOrder[0] ); expect(mocks.createIdempotentTenantEvent.mock.invocationCallOrder[0]).toBeGreaterThan( mocks.createOwnedTenantWithShkDefaults.mock.invocationCallOrder[0] ); expect(result).toMatchObject({ redirectTo: "/app/acme/dashboard", tenant: { id: "tenant_1" }, user: { id: "user_1" } }); expect(getRlsExecutionContext()).toBeNull(); }); it("does not run post-commit work when the atomic owner bootstrap fails", async () => { mocks.createOwnedTenantWithShkDefaults.mockRejectedValueOnce(new Error("bootstrap failed")); const request = new Request("https://admin.example.test/accounts", { method: "POST" }); await expect( runWithRlsContext({ userId: "user_1" }, () => TenantsApi.create({ request, name: "Acme", slug: "acme", creationRequestKey: CREATION_REQUEST_KEY }) ) ).rejects.toThrow("bootstrap failed"); expect(mocks.autosubscribeToTrialOrFreePlan).not.toHaveBeenCalled(); expect(mocks.createIdempotentTenantEvent).not.toHaveBeenCalled(); }); it("isolates post-commit work from a previously-bound tenant", async () => { const request = new Request("https://old.example.test/new-account", { method: "POST" }); await runWithRlsContext({ userId: "user_1", tenantId: "tenant_old" }, async () => { await TenantsApi.create({ request, name: "Acme", slug: "acme", creationRequestKey: CREATION_REQUEST_KEY }); expect(getRlsExecutionContext()).toMatchObject({ userId: "user_1", tenantId: "tenant_old" }); }); expect(mocks.autosubscribeToTrialOrFreePlan).toHaveBeenCalledOnce(); expect(mocks.createIdempotentTenantEvent).toHaveBeenCalledOnce(); }); it("drops an inherited transaction before dispatching post-commit work", async () => { const request = new Request("https://app.example.test/new-account", { method: "POST" }); const oldTransaction = {}; await runWithRlsContext({ userId: "user_1" }, () => runWithRlsTransaction(oldTransaction, () => TenantsApi.create({ request, name: "Acme", slug: "acme", creationRequestKey: CREATION_REQUEST_KEY }) ) ); expect(mocks.autosubscribeToTrialOrFreePlan).toHaveBeenCalledOnce(); expect(mocks.createIdempotentTenantEvent).toHaveBeenCalledOnce(); }); it("replays both intrinsically idempotent steps with their original stable keys after response loss", async () => { const request = new Request("https://app.example.test/new-account", { method: "POST" }); await runWithRlsContext({ userId: "user_1" }, () => TenantsApi.create({ request, name: "Acme", slug: "acme", creationRequestKey: CREATION_REQUEST_KEY }) ); const user = await mocks.getUser(); mocks.createOwnedTenantWithShkDefaults.mockResolvedValueOnce({ tenant: { id: "tenant_1", name: "Acme", slug: "acme" }, user: { ...user, defaultTenantId: "tenant_1" }, replayed: true, }); const replay = await runWithRlsContext({ userId: "user_1" }, () => TenantsApi.create({ request, name: "Acme", slug: "acme", creationRequestKey: CREATION_REQUEST_KEY }) ); expect(replay.replayed).toBe(true); expect(mocks.autosubscribeToTrialOrFreePlan).toHaveBeenCalledTimes(2); expect(mocks.autosubscribeToTrialOrFreePlan.mock.calls.map(([args]) => args.idempotencyKey)).toEqual([ CREATION_REQUEST_KEY, CREATION_REQUEST_KEY, ]); expect(mocks.createIdempotentTenantEvent).toHaveBeenCalledTimes(2); expect(mocks.createIdempotentTenantEvent.mock.calls.map(([args]) => args.idempotencyKey)).toEqual([ ACCOUNT_EVENT_IDEMPOTENCY_KEY, ACCOUNT_EVENT_IDEMPOTENCY_KEY, ]); }); it("propagates a replayable post-commit failure and completes it on an exact retry", async () => { const request = new Request("https://app.example.test/new-account", { method: "POST" }); mocks.autosubscribeToTrialOrFreePlan.mockRejectedValueOnce(new Error("billing unavailable")); await expect( runWithRlsContext({ userId: "user_1" }, () => TenantsApi.create({ request, name: "Acme", slug: "acme", creationRequestKey: CREATION_REQUEST_KEY }) ) ).rejects.toThrow("billing unavailable"); expect(mocks.createIdempotentTenantEvent).not.toHaveBeenCalled(); expect(mocks.postCommitWarn).toHaveBeenCalledWith( expect.objectContaining({ op: "workspace.postcommit.trial-autosubscribe", tenantId: "tenant_1" }), expect.stringContaining("Workspace creation committed") ); const user = await mocks.getUser(); mocks.createOwnedTenantWithShkDefaults.mockResolvedValueOnce({ tenant: { id: "tenant_1", name: "Acme", slug: "acme" }, user: { ...user, defaultTenantId: "tenant_1" }, replayed: true, }); await runWithRlsContext({ userId: "user_1" }, () => TenantsApi.create({ request, name: "Acme", slug: "acme", creationRequestKey: CREATION_REQUEST_KEY }) ); expect(mocks.autosubscribeToTrialOrFreePlan).toHaveBeenCalledTimes(2); expect(mocks.createIdempotentTenantEvent).toHaveBeenCalledOnce(); }); });