|
| 1 | +/** |
| 2 | + * @vitest-environment node |
| 3 | + */ |
| 4 | +import { describe, expect, it, vi } from 'vitest' |
| 5 | +import { |
| 6 | + getExecutionRedisBudgetKeys, |
| 7 | + reserveExecutionRedisBytes, |
| 8 | +} from '@/lib/execution/redis-budget.server' |
| 9 | + |
| 10 | +function countOccurrences(haystack: string, needle: string): number { |
| 11 | + return haystack.split(needle).length - 1 |
| 12 | +} |
| 13 | + |
| 14 | +async function captureReserveScript(userId?: string): Promise<string> { |
| 15 | + let script = '' |
| 16 | + const redis = { |
| 17 | + eval: vi.fn(async (source: string) => { |
| 18 | + script = source |
| 19 | + return [1, 'ok', 0, 0] |
| 20 | + }), |
| 21 | + } |
| 22 | + |
| 23 | + await reserveExecutionRedisBytes(redis as never, { |
| 24 | + executionId: 'exec-1', |
| 25 | + userId, |
| 26 | + category: 'event_buffer', |
| 27 | + operation: 'write_events', |
| 28 | + bytes: 128, |
| 29 | + }) |
| 30 | + |
| 31 | + return script |
| 32 | +} |
| 33 | + |
| 34 | +describe('reserveExecutionRedisBytes', () => { |
| 35 | + it('scopes the reservation to the execution, and to the user when one is known', () => { |
| 36 | + expect( |
| 37 | + getExecutionRedisBudgetKeys({ |
| 38 | + executionId: 'exec-1', |
| 39 | + category: 'event_buffer', |
| 40 | + operation: 'write_events', |
| 41 | + bytes: 1, |
| 42 | + }) |
| 43 | + ).toEqual(['execution:redis-budget:execution:exec-1']) |
| 44 | + |
| 45 | + expect( |
| 46 | + getExecutionRedisBudgetKeys({ |
| 47 | + executionId: 'exec-1', |
| 48 | + userId: 'user-1', |
| 49 | + category: 'event_buffer', |
| 50 | + operation: 'write_events', |
| 51 | + bytes: 1, |
| 52 | + }) |
| 53 | + ).toEqual(['execution:redis-budget:execution:exec-1', 'execution:redis-budget:user:user-1']) |
| 54 | + }) |
| 55 | + |
| 56 | + /** |
| 57 | + * A user key aggregates across every execution that user runs, so extending |
| 58 | + * its TTL on each write keeps it alive indefinitely while the per-execution |
| 59 | + * data it accounts for expires underneath it. The window must be fixed. |
| 60 | + */ |
| 61 | + it('never extends an existing user budget window', async () => { |
| 62 | + const script = await captureReserveScript('user-1') |
| 63 | + |
| 64 | + const userKeyExpires = countOccurrences(script, "redis.call('EXPIRE', KEYS[2]") |
| 65 | + const userKeyTtlGuards = countOccurrences(script, "redis.call('TTL', KEYS[2]) < 0") |
| 66 | + expect(userKeyExpires).toBeGreaterThan(0) |
| 67 | + expect(userKeyTtlGuards).toBe(userKeyExpires) |
| 68 | + }) |
| 69 | + |
| 70 | + it('keeps sliding the execution budget window, which expires with its own data', async () => { |
| 71 | + const script = await captureReserveScript('user-1') |
| 72 | + |
| 73 | + expect(countOccurrences(script, "redis.call('TTL', KEYS[1]) < 0")).toBe(0) |
| 74 | + expect(countOccurrences(script, "redis.call('EXPIRE', KEYS[1]")).toBeGreaterThan(0) |
| 75 | + }) |
| 76 | +}) |
0 commit comments