Files

420 lines
18 KiB
TypeScript

// @vitest-environment node
import { beforeEach, describe, expect, it, vi } from "vitest";
type Marker = {
requestHash: string;
responseStatus: number;
responseBody: unknown;
responseHeaders: Record<string, string> | null;
expiresAt: Date | null;
};
const mocks = vi.hoisted(() => ({
getTenant: vi.fn(),
getOrPersistTenantSubscription: vi.fn(),
getAllSubscriptionProducts: vi.fn(),
getAllSubscriptionProductsStrict: vi.fn(),
addTenantSubscriptionProduct: vi.fn(),
getUser: vi.fn(),
createEvent: vi.fn(),
createIdempotentTenantEvent: vi.fn(),
clearTenantSubscriptionCache: vi.fn(),
completeSelfServiceCheckout: vi.fn(),
loggerError: vi.fn(),
dbTransaction: vi.fn(),
executeRaw: vi.fn(),
upsertTenantSubscription: vi.fn(),
markers: new Map<string, Marker>(),
events: new Set<string>(),
subscriptionWrites: [] as unknown[],
transactionClients: [] as unknown[],
transactionOpen: false,
failCommitOnce: false,
failMarkerUpdateOnce: false,
}));
vi.mock("../../db/tenants.db.server", () => ({ getTenant: mocks.getTenant }));
vi.mock("../../db/tenantSubscriptions.db.server", () => ({ getOrPersistTenantSubscription: mocks.getOrPersistTenantSubscription }));
vi.mock("../../db/subscriptionProducts.db.server", () => ({
getAllSubscriptionProducts: mocks.getAllSubscriptionProducts,
getAllSubscriptionProductsStrict: mocks.getAllSubscriptionProductsStrict,
}));
vi.mock("../../db/subscriptions/tenantSubscriptionProducts.db.server", () => ({
addTenantSubscriptionProduct: mocks.addTenantSubscriptionProduct,
}));
vi.mock("../../db/users.db.server", () => ({ getUser: mocks.getUser }));
vi.mock("../../../modules/events/services/.server/EventsService", () => ({
default: {
create: mocks.createEvent,
createIdempotentTenantEvent: mocks.createIdempotentTenantEvent,
},
}));
vi.mock("~/application/pricing/currencies", () => ({
default: [{ value: "EUR", default: true }],
}));
vi.mock("~/utils/logger.server", () => ({
createScopedLogger: () => ({ info: vi.fn(), debug: vi.fn(), warn: vi.fn(), error: mocks.loggerError }),
}));
vi.mock("~/utils/db.server", () => ({ db: { $transaction: mocks.dbTransaction } }));
vi.mock("~/utils/db/appConfiguration.db.server", () => ({ getAppConfiguration: vi.fn() }));
vi.mock("./subscriptionService", () => ({
cancelTenantSubscription: vi.fn(),
clearAllSubscriptionsCache: vi.fn(),
clearTenantSubscriptionCache: mocks.clearTenantSubscriptionCache,
getActiveTenantSubscriptions: vi.fn(),
}));
vi.mock("~/services/billing/self-service-checkout.server", () => ({ completeSelfServiceCheckout: mocks.completeSelfServiceCheckout }));
vi.mock("../../api/.server/TenantTypesApi", () => ({ TenantTypesApi: { setTenantTypes: vi.fn() } }));
import { autosubscribeToTrialOrFreePlan } from "./pricingService";
const IDEMPOTENCY_KEY = "d7077797-054b-497a-b1ce-8e4f36257a96";
const IDEMPOTENCY_SCOPE = "tenant-bootstrap/workspace-trial-autosubscribe-v1";
function markerStorageKey({ partitionKey, scope, key }: { partitionKey: string; scope: string; key: string }): string {
return `${partitionKey}:${scope}:${key}`;
}
function expectedMarkerKey(): string {
return markerStorageKey({ partitionKey: "tenant:tenant_1", scope: IDEMPOTENCY_SCOPE, key: IDEMPOTENCY_KEY });
}
function idempotencyClient() {
return {
$executeRaw: mocks.executeRaw,
tenantSubscription: {
upsert: mocks.upsertTenantSubscription,
},
idempotencyKey: {
findUnique: vi.fn(
async ({ where }: { where: { idempotency_key_partition_scope_key: { partitionKey: string; scope: string; key: string } } }) =>
mocks.markers.get(markerStorageKey(where.idempotency_key_partition_scope_key)) ?? null
),
create: vi.fn(async ({ data }: { data: Marker & { partitionKey: string; scope: string; key: string } }) => {
const storageKey = markerStorageKey(data);
if (mocks.markers.has(storageKey)) throw Object.assign(new Error("duplicate marker"), { code: "P2002" });
const marker: Marker = {
requestHash: data.requestHash,
responseStatus: data.responseStatus,
responseBody: data.responseBody ?? null,
responseHeaders: data.responseHeaders ?? null,
expiresAt: data.expiresAt ?? null,
};
mocks.markers.set(storageKey, marker);
return marker;
}),
update: vi.fn(
async ({
where,
data,
}: {
where: { idempotency_key_partition_scope_key: { partitionKey: string; scope: string; key: string } };
data: Partial<Marker>;
}) => {
if (mocks.failMarkerUpdateOnce) {
mocks.failMarkerUpdateOnce = false;
throw new Error("marker update failed");
}
const storageKey = markerStorageKey(where.idempotency_key_partition_scope_key);
const existing = mocks.markers.get(storageKey);
if (!existing) throw new Error("marker missing");
const marker = { ...existing, ...data };
mocks.markers.set(storageKey, marker);
return marker;
}
),
deleteMany: vi.fn(async ({ where }: { where: { partitionKey: string; scope: string; key: string } }) => {
mocks.markers.delete(markerStorageKey(where));
return { count: 1 };
}),
},
};
}
function args(overrides: Record<string, unknown> = {}) {
return {
request: new Request("https://app.example.test/new-account"),
t: (key: string) => key,
tenantId: "tenant_1",
userId: "user_1",
throwOnFailure: true,
idempotencyKey: IDEMPOTENCY_KEY,
...overrides,
};
}
describe("autosubscribeToTrialOrFreePlan post-commit idempotency", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.markers.clear();
mocks.events.clear();
mocks.subscriptionWrites.length = 0;
mocks.transactionClients.length = 0;
mocks.transactionOpen = false;
mocks.failCommitOnce = false;
mocks.failMarkerUpdateOnce = false;
mocks.getTenant.mockResolvedValue({ id: "tenant_1", name: "Acme", slug: "acme" });
mocks.getOrPersistTenantSubscription.mockImplementation(async () => {
expect(mocks.transactionOpen).toBe(false);
return { id: "subscription_1" };
});
const catalog = [
{
id: "product_1",
title: "Pro",
prices: [
{
id: "price_1",
currency: "EUR",
price: 10,
trialDays: 14,
subscriptionProductId: "product_1",
subscriptionProduct: { title: "Pro" },
},
],
},
];
mocks.getAllSubscriptionProducts.mockResolvedValue(catalog);
mocks.getAllSubscriptionProductsStrict.mockResolvedValue(catalog);
mocks.getUser.mockResolvedValue({ id: "user_1", email: "owner@example.test" });
mocks.executeRaw.mockResolvedValue(1);
mocks.upsertTenantSubscription.mockImplementation(async () => {
expect(mocks.transactionOpen).toBe(true);
return { id: "subscription_1" };
});
mocks.addTenantSubscriptionProduct.mockImplementation(async (input, options) => {
expect(mocks.transactionOpen).toBe(true);
mocks.subscriptionWrites.push({ input, options });
return { id: "tenant_product_1" };
});
mocks.clearTenantSubscriptionCache.mockImplementation(() => {
expect(mocks.transactionOpen).toBe(false);
});
mocks.createIdempotentTenantEvent.mockImplementation(async ({ idempotencyKey }: { idempotencyKey: string }) => {
expect(mocks.transactionOpen).toBe(false);
mocks.events.add(idempotencyKey);
});
mocks.dbTransaction.mockImplementation(async (callback: (tx: ReturnType<typeof idempotencyClient>) => Promise<unknown>) => {
const markerSnapshot = new Map(mocks.markers);
const writeCount = mocks.subscriptionWrites.length;
const tx = idempotencyClient();
mocks.transactionClients.push(tx);
mocks.transactionOpen = true;
try {
const result = await callback(tx);
if (mocks.failCommitOnce) {
mocks.failCommitOnce = false;
throw new Error("transaction commit failed");
}
mocks.transactionOpen = false;
return result;
} catch (error) {
mocks.markers.clear();
for (const [key, marker] of markerSnapshot) mocks.markers.set(key, marker);
mocks.subscriptionWrites.splice(writeCount);
mocks.transactionOpen = false;
throw error;
}
});
});
it("commits the local trial marker before cache and event dispatch and never calls a billing gateway", async () => {
await expect(autosubscribeToTrialOrFreePlan(args() as never)).resolves.toBeUndefined();
expect(mocks.addTenantSubscriptionProduct).toHaveBeenCalledWith(
expect.objectContaining({
tenantSubscriptionId: "subscription_1",
subscriptionProductId: "product_1",
billingProviderSubscriptionId: null,
fromCheckoutSessionId: null,
}),
{
invalidateCache: false,
client: mocks.transactionClients[0],
}
);
expect(mocks.markers.get(expectedMarkerKey())?.responseStatus).toBe(201);
expect(mocks.clearTenantSubscriptionCache).toHaveBeenCalledWith("tenant_1");
expect(mocks.createIdempotentTenantEvent).toHaveBeenCalledWith(
expect.objectContaining({
event: "subscription.subscribed",
idempotencyKey: `tenant-bootstrap:tenant_1:${IDEMPOTENCY_KEY}:trial-subscribed`,
})
);
expect(mocks.executeRaw).toHaveBeenCalledOnce();
expect(mocks.upsertTenantSubscription).toHaveBeenCalledWith({
where: { tenantId: "tenant_1" },
create: { tenantId: "tenant_1", billingProviderCustomerId: "" },
update: {},
select: { id: true },
});
expect(mocks.getOrPersistTenantSubscription).not.toHaveBeenCalled();
expect(mocks.completeSelfServiceCheckout).not.toHaveBeenCalled();
});
it("replays without a duplicate subscription while safely retrying cache invalidation and the idempotent event", async () => {
await autosubscribeToTrialOrFreePlan(args() as never);
await autosubscribeToTrialOrFreePlan(args() as never);
expect(mocks.subscriptionWrites).toHaveLength(1);
expect(mocks.addTenantSubscriptionProduct).toHaveBeenCalledOnce();
expect(mocks.clearTenantSubscriptionCache).toHaveBeenCalledTimes(2);
expect(mocks.createIdempotentTenantEvent).toHaveBeenCalledTimes(2);
expect(mocks.createIdempotentTenantEvent.mock.calls.map(([input]) => input.idempotencyKey)).toEqual([
`tenant-bootstrap:tenant_1:${IDEMPOTENCY_KEY}:trial-subscribed`,
`tenant-bootstrap:tenant_1:${IDEMPOTENCY_KEY}:trial-subscribed`,
]);
expect(mocks.events.size).toBe(1);
});
it("serializes parallel retries to one subscription product and one event identity", async () => {
await Promise.all([autosubscribeToTrialOrFreePlan(args() as never), autosubscribeToTrialOrFreePlan(args() as never)]);
expect(mocks.addTenantSubscriptionProduct).toHaveBeenCalledOnce();
expect(mocks.subscriptionWrites).toHaveLength(1);
expect(mocks.events).toEqual(new Set([`tenant-bootstrap:tenant_1:${IDEMPOTENCY_KEY}:trial-subscribed`]));
expect(mocks.executeRaw).toHaveBeenCalledTimes(2);
});
it("fails closed when the strict bootstrap catalog read fails", async () => {
const error = new Error("subscription catalog unavailable");
mocks.getAllSubscriptionProductsStrict.mockRejectedValueOnce(error);
await expect(autosubscribeToTrialOrFreePlan(args() as never)).rejects.toBe(error);
expect(mocks.dbTransaction).toHaveBeenCalledOnce();
expect(mocks.getAllSubscriptionProducts).not.toHaveBeenCalled();
expect(mocks.addTenantSubscriptionProduct).not.toHaveBeenCalled();
expect(mocks.createIdempotentTenantEvent).not.toHaveBeenCalled();
expect(mocks.markers.size).toBe(0);
});
it("rolls back the local write when marker completion fails and retries cleanly", async () => {
mocks.failMarkerUpdateOnce = true;
await expect(autosubscribeToTrialOrFreePlan(args() as never)).rejects.toThrow("marker update failed");
expect(mocks.subscriptionWrites).toHaveLength(0);
expect(mocks.markers.has(expectedMarkerKey())).toBe(false);
expect(mocks.clearTenantSubscriptionCache).not.toHaveBeenCalled();
expect(mocks.createIdempotentTenantEvent).not.toHaveBeenCalled();
await expect(autosubscribeToTrialOrFreePlan(args() as never)).resolves.toBeUndefined();
expect(mocks.subscriptionWrites).toHaveLength(1);
expect(mocks.createIdempotentTenantEvent).toHaveBeenCalledOnce();
});
it("does not dispatch cache or event effects when the marker transaction commit fails", async () => {
mocks.failCommitOnce = true;
await expect(autosubscribeToTrialOrFreePlan(args() as never)).rejects.toThrow("transaction commit failed");
expect(mocks.subscriptionWrites).toHaveLength(0);
expect(mocks.markers.has(expectedMarkerKey())).toBe(false);
expect(mocks.clearTenantSubscriptionCache).not.toHaveBeenCalled();
expect(mocks.createIdempotentTenantEvent).not.toHaveBeenCalled();
await autosubscribeToTrialOrFreePlan(args() as never);
expect(mocks.subscriptionWrites).toHaveLength(1);
expect(mocks.createIdempotentTenantEvent).toHaveBeenCalledOnce();
});
it("keeps a committed local trial and retries only the idempotent event after event commit failure", async () => {
mocks.createIdempotentTenantEvent.mockRejectedValueOnce(new Error("event commit failed"));
await expect(autosubscribeToTrialOrFreePlan(args() as never)).rejects.toThrow("event commit failed");
expect(mocks.subscriptionWrites).toHaveLength(1);
expect(mocks.markers.get(expectedMarkerKey())?.responseStatus).toBe(201);
await autosubscribeToTrialOrFreePlan(args() as never);
expect(mocks.subscriptionWrites).toHaveLength(1);
expect(mocks.addTenantSubscriptionProduct).toHaveBeenCalledOnce();
expect(mocks.clearTenantSubscriptionCache).toHaveBeenCalledTimes(2);
expect(mocks.createIdempotentTenantEvent).toHaveBeenCalledTimes(2);
});
it("reuses the committed locale-invariant event payload when the catalog changes before a retry", async () => {
mocks.createIdempotentTenantEvent.mockRejectedValueOnce(new Error("event commit failed"));
await expect(autosubscribeToTrialOrFreePlan(args({ t: (key: string) => `de:${key}` }) as never)).rejects.toThrow("event commit failed");
mocks.getAllSubscriptionProductsStrict.mockResolvedValueOnce([
{
id: "product_2",
title: "Business",
prices: [
{
id: "price_2",
currency: "EUR",
price: 20,
trialDays: 7,
subscriptionProductId: "product_2",
subscriptionProduct: { title: "Business" },
},
],
},
]);
mocks.getTenant.mockResolvedValueOnce({ id: "tenant_1", name: "Renamed", slug: "renamed" });
mocks.getUser.mockResolvedValueOnce({ id: "user_1", email: "changed@example.test" });
await autosubscribeToTrialOrFreePlan(args({ t: (key: string) => `en:${key}` }) as never);
expect(mocks.subscriptionWrites).toHaveLength(1);
expect(mocks.getAllSubscriptionProductsStrict).toHaveBeenCalledOnce();
expect(mocks.getTenant).toHaveBeenCalledOnce();
expect(mocks.getUser).toHaveBeenCalledOnce();
expect(mocks.createIdempotentTenantEvent).toHaveBeenCalledTimes(2);
const eventPayloads = mocks.createIdempotentTenantEvent.mock.calls.map(([input]) => input.data);
expect(eventPayloads).toEqual([
{
user: { id: "user_1", email: "owner@example.test" },
tenant: { id: "tenant_1", name: "Acme", slug: "acme" },
subscription: { product: { id: "product_1", title: "Pro" } },
},
{
user: { id: "user_1", email: "owner@example.test" },
tenant: { id: "tenant_1", name: "Acme", slug: "acme" },
subscription: { product: { id: "product_1", title: "Pro" } },
},
]);
});
it("fails closed when a committed trial marker contains an invalid event projection", async () => {
await autosubscribeToTrialOrFreePlan(args() as never);
const marker = mocks.markers.get(expectedMarkerKey());
expect(marker).toBeDefined();
if (marker) {
marker.responseBody = {
state: "subscribed",
subscriptionProductId: "product_1",
subscriptionPriceId: "price_1",
eventData: { tenant: { id: "tenant_other" } },
};
}
await expect(autosubscribeToTrialOrFreePlan(args() as never)).rejects.toThrow("Workspace trial idempotency marker is invalid");
expect(mocks.subscriptionWrites).toHaveLength(1);
});
it("keeps legacy callers fail-soft while allowing workspace creation to fail closed", async () => {
mocks.addTenantSubscriptionProduct.mockRejectedValue(new Error("subscription write failed"));
await expect(autosubscribeToTrialOrFreePlan(args({ idempotencyKey: undefined, throwOnFailure: false }) as never)).resolves.toBeUndefined();
await expect(autosubscribeToTrialOrFreePlan(args({ idempotencyKey: undefined }) as never)).rejects.toThrow("subscription write failed");
expect(mocks.loggerError).toHaveBeenCalledTimes(2);
expect(JSON.stringify(mocks.loggerError.mock.calls)).not.toContain("subscription write failed");
expect(mocks.createEvent).not.toHaveBeenCalled();
expect(mocks.completeSelfServiceCheckout).not.toHaveBeenCalled();
});
it("does not complete a marker when RLS cannot see the committed tenant", async () => {
mocks.getTenant.mockResolvedValue(null);
await expect(autosubscribeToTrialOrFreePlan(args({ throwOnFailure: false }) as never)).resolves.toBeUndefined();
await expect(autosubscribeToTrialOrFreePlan(args() as never)).rejects.toThrow("Tenant unavailable for auto-subscribe");
expect(mocks.getOrPersistTenantSubscription).not.toHaveBeenCalled();
expect(mocks.markers.size).toBe(0);
});
});