/** * Unit test for `admin.slots.createSlot`'s post-create cleanup. * * `staleSlotsCleanup` used to be called fire-and-forget. In workerd the * mutation could return (and the isolate be frozen) before the cleanup ran. * Because the cleanup is an incremental 20-slot window, a skipped run leaves * `skuIds` on the slot that fell out of the window permanently. These tests pin * the awaited behaviour and the existing "cleanup failure must not fail slot * creation" contract. */ import { slotsRouter } from '@/src/trpc/apis/admin-apis/apis/slots' import { createSlotWithRelations, staleSlotsCleanup } from '@/src/dbService' import { createSlotsCacheFile } from '@/src/lib/cloud_cache' jest.mock('@/src/dbService', () => ({ createSlotWithRelations: jest.fn(async () => ({ slot: { id: 1 }, message: 'Slot created', })), staleSlotsCleanup: jest.fn(async () => 1), })) jest.mock('@/src/lib/cloud_cache', () => ({ createSlotsCacheFile: jest.fn(async () => 1), })) const mockedCleanup = staleSlotsCleanup as jest.MockedFunction const mockedCreate = createSlotWithRelations as jest.MockedFunction const mockedCache = createSlotsCacheFile as jest.MockedFunction const input = { deliveryTime: new Date(Date.now() + 3_600_000).toISOString(), freezeTime: new Date(Date.now() + 1_800_000).toISOString(), } const ctx = { staffUser: { id: 3, regionId: 1 } } /** tRPC stores the resolver on the procedure's `_def`; call it with a fake ctx. */ const resolveCreateSlot = () => (slotsRouter.createSlot as any)._def.resolver const drainMicrotasks = () => new Promise((resolve) => setImmediate(resolve)) describe('admin.slots.createSlot cleanup', () => { beforeEach(() => { jest.clearAllMocks() }) it('awaits staleSlotsCleanup before resolving', async () => { let release!: () => void const work = new Promise((resolve) => { release = () => resolve(1) }) mockedCleanup.mockReturnValueOnce(work) const run = resolveCreateSlot()({ input, ctx }) let settled = false run.then(() => { settled = true }) await drainMicrotasks() expect(mockedCreate).toHaveBeenCalledTimes(1) expect(mockedCache).toHaveBeenCalledTimes(1) expect(mockedCleanup).toHaveBeenCalledTimes(1) // Cleanup must stay inside the caller's region; a global window would let // region A clear region B's slots. expect(mockedCleanup).toHaveBeenCalledWith(ctx.staffUser.regionId) expect(settled).toBe(false) release() await run expect(settled).toBe(true) }) it('swallows a cleanup rejection so slot creation still succeeds', async () => { mockedCleanup.mockRejectedValueOnce(new Error('cleanup failed')) const result = await resolveCreateSlot()({ input, ctx }) expect(result).toEqual(expect.objectContaining({ message: 'Slot created' })) expect(mockedCleanup).toHaveBeenCalledTimes(1) expect(mockedCleanup).toHaveBeenCalledWith(ctx.staffUser.regionId) }) })