|
| 1 | +/** |
| 2 | + * @vitest-environment node |
| 3 | + */ |
| 4 | + |
| 5 | +import { usageLog } from '@sim/db/schema' |
| 6 | +import { dbChainMockFns, queueTableRows, resetDbChainMock } from '@sim/testing' |
| 7 | +import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest' |
| 8 | + |
| 9 | +const { mockRecordUsage, mockTerminateById, mockThresholdBilling } = vi.hoisted(() => ({ |
| 10 | + mockRecordUsage: vi.fn(), |
| 11 | + mockTerminateById: vi.fn(), |
| 12 | + mockThresholdBilling: vi.fn(), |
| 13 | +})) |
| 14 | + |
| 15 | +vi.mock('@/lib/billing/core/usage-log', async (importOriginal) => { |
| 16 | + const original = await importOriginal<typeof import('@/lib/billing/core/usage-log')>() |
| 17 | + return { ...original, recordUsage: mockRecordUsage } |
| 18 | +}) |
| 19 | +vi.mock('@/lib/billing/threshold-billing', () => ({ |
| 20 | + checkAndBillPayerOverageThreshold: mockThresholdBilling, |
| 21 | +})) |
| 22 | +vi.mock('@/lib/core/config/env-flags', () => ({ |
| 23 | + getCostMultiplier: vi.fn(() => 1), |
| 24 | + isBillingEnabled: false, |
| 25 | +})) |
| 26 | +vi.mock('@/lib/execution/remote-sandbox/provider', () => ({ |
| 27 | + getSandboxProvider: vi.fn(() => ({ terminateById: mockTerminateById })), |
| 28 | +})) |
| 29 | + |
| 30 | +import { createSandboxPricingSnapshot } from '@/lib/billing/sandbox-pricing' |
| 31 | +import { |
| 32 | + SANDBOX_USAGE_OUTBOX_EVENT_TYPE, |
| 33 | + type SandboxUsageOutboxPayloadV1, |
| 34 | + sandboxUsageOutboxHandlers, |
| 35 | +} from '@/lib/billing/sandbox-usage-outbox' |
| 36 | +import type { OutboxEventContext } from '@/lib/core/outbox/service' |
| 37 | + |
| 38 | +const context: OutboxEventContext = { |
| 39 | + eventId: 'event-1', |
| 40 | + eventType: SANDBOX_USAGE_OUTBOX_EVENT_TYPE, |
| 41 | + attempts: 0, |
| 42 | + maxAttempts: 10, |
| 43 | + signal: new AbortController().signal, |
| 44 | + checkpointPayload: vi.fn(), |
| 45 | +} |
| 46 | + |
| 47 | +function payload(overrides: Partial<SandboxUsageOutboxPayloadV1> = {}) { |
| 48 | + const base: SandboxUsageOutboxPayloadV1 = { |
| 49 | + version: 1, |
| 50 | + provider: 'e2b', |
| 51 | + providerSandboxId: 'sandbox-1', |
| 52 | + sandboxKind: 'code', |
| 53 | + providerRequestedAt: '2026-08-27T12:00:00.000Z', |
| 54 | + providerReadyAt: '2026-08-27T12:00:01.000Z', |
| 55 | + providerExpiresAt: '2026-08-27T12:05:00.000Z', |
| 56 | + terminationRequestedAt: '2026-08-27T12:00:10.000Z', |
| 57 | + terminatedAt: '2026-08-27T12:00:10.000Z', |
| 58 | + outcome: 'success', |
| 59 | + cleanupStatus: 'terminated', |
| 60 | + workspaceId: 'workspace-1', |
| 61 | + workflowId: 'workflow-1', |
| 62 | + executionId: 'execution-1', |
| 63 | + billingAttribution: { |
| 64 | + actorUserId: 'user-1', |
| 65 | + workspaceId: 'workspace-1', |
| 66 | + organizationId: null, |
| 67 | + billedAccountUserId: 'user-1', |
| 68 | + billingEntity: { type: 'user', id: 'user-1' }, |
| 69 | + billingPeriod: { |
| 70 | + start: '2026-08-01T00:00:00.000Z', |
| 71 | + end: '2026-09-01T00:00:00.000Z', |
| 72 | + }, |
| 73 | + payerSubscription: null, |
| 74 | + }, |
| 75 | + pricing: createSandboxPricingSnapshot('e2b', 1), |
| 76 | + } |
| 77 | + return { ...base, ...overrides } |
| 78 | +} |
| 79 | + |
| 80 | +async function runHandler(value: SandboxUsageOutboxPayloadV1): Promise<void> { |
| 81 | + await sandboxUsageOutboxHandlers[SANDBOX_USAGE_OUTBOX_EVENT_TYPE](value, context) |
| 82 | +} |
| 83 | + |
| 84 | +afterAll(resetDbChainMock) |
| 85 | + |
| 86 | +describe('sandbox usage outbox finalizer', () => { |
| 87 | + beforeEach(() => { |
| 88 | + vi.clearAllMocks() |
| 89 | + resetDbChainMock() |
| 90 | + queueTableRows(usageLog, [{ cost: '0.02' }]) |
| 91 | + mockRecordUsage.mockResolvedValue(undefined) |
| 92 | + mockTerminateById.mockResolvedValue('terminated') |
| 93 | + }) |
| 94 | + |
| 95 | + it('records an attributed Code sandbox ledger event and refreshes execution cost', async () => { |
| 96 | + await runHandler(payload()) |
| 97 | + |
| 98 | + expect(mockRecordUsage).toHaveBeenCalledWith( |
| 99 | + expect.objectContaining({ |
| 100 | + userId: 'user-1', |
| 101 | + workspaceId: 'workspace-1', |
| 102 | + workflowId: 'workflow-1', |
| 103 | + executionId: 'execution-1', |
| 104 | + tx: expect.anything(), |
| 105 | + entries: [ |
| 106 | + expect.objectContaining({ |
| 107 | + category: 'tool', |
| 108 | + source: 'workflow', |
| 109 | + description: 'Code sandbox', |
| 110 | + sourceReference: 'sandbox:e2b:sandbox-1', |
| 111 | + }), |
| 112 | + ], |
| 113 | + }) |
| 114 | + ) |
| 115 | + expect(dbChainMockFns.execute).toHaveBeenCalledOnce() |
| 116 | + expect(dbChainMockFns.update).toHaveBeenCalled() |
| 117 | + }) |
| 118 | + |
| 119 | + it('terminates and checkpoints a sandbox whose terminal timestamp is missing', async () => { |
| 120 | + await runHandler( |
| 121 | + payload({ |
| 122 | + terminationRequestedAt: undefined, |
| 123 | + terminatedAt: undefined, |
| 124 | + outcome: undefined, |
| 125 | + cleanupStatus: 'active', |
| 126 | + }) |
| 127 | + ) |
| 128 | + |
| 129 | + expect(mockTerminateById).toHaveBeenCalledWith('sandbox-1') |
| 130 | + expect(context.checkpointPayload).toHaveBeenCalledWith( |
| 131 | + expect.objectContaining({ cleanupStatus: 'terminated', terminatedAt: expect.any(String) }) |
| 132 | + ) |
| 133 | + expect(mockRecordUsage).toHaveBeenCalledOnce() |
| 134 | + }) |
| 135 | + |
| 136 | + it('propagates transient provider failures so the generic outbox retries', async () => { |
| 137 | + mockTerminateById.mockRejectedValueOnce(new Error('provider unavailable')) |
| 138 | + |
| 139 | + await expect( |
| 140 | + runHandler(payload({ terminatedAt: undefined, cleanupStatus: 'pending_reconciliation' })) |
| 141 | + ).rejects.toThrow('provider unavailable') |
| 142 | + expect(mockRecordUsage).not.toHaveBeenCalled() |
| 143 | + }) |
| 144 | + |
| 145 | + it('uses the same ledger event key when finalization is replayed', async () => { |
| 146 | + await runHandler(payload()) |
| 147 | + await runHandler(payload()) |
| 148 | + |
| 149 | + const firstEventKey = mockRecordUsage.mock.calls[0][0].entries[0].eventKey |
| 150 | + const secondEventKey = mockRecordUsage.mock.calls[1][0].entries[0].eventKey |
| 151 | + expect(firstEventKey).toBe(secondEventKey) |
| 152 | + }) |
| 153 | +}) |
0 commit comments