fix(memory): bound automation dispatch tokens

This commit is contained in:
m4air
2026-09-19 16:22:22 -07:00
parent 52952623db
commit a5762e19cf
2 changed files with 32 additions and 0 deletions
@@ -0,0 +1,16 @@
import { describe, expect, it } from 'vitest'
import {
createAutomationDispatchToken,
getAutomationDispatchTokenCountForTests,
MAX_AUTOMATION_DISPATCH_TOKENS
} from './dispatch-tokens'
describe('automation dispatch tokens', () => {
it('bounds distinct token churn', () => {
for (let index = 0; index < MAX_AUTOMATION_DISPATCH_TOKENS + 4; index += 1) {
createAutomationDispatchToken(`automation-${index}`, `run-${index}`)
}
expect(getAutomationDispatchTokenCountForTests()).toBe(MAX_AUTOMATION_DISPATCH_TOKENS)
})
})
+16
View File
@@ -1,6 +1,7 @@
import { randomUUID } from 'node:crypto'
const DISPATCH_TOKEN_TTL_MS = 30 * 60_000
export const MAX_AUTOMATION_DISPATCH_TOKENS = 1024
type DispatchTokenRecord = {
automationId: string
@@ -20,6 +21,16 @@ function pruneExpiredDispatchTokens(now = Date.now()): void {
}
}
function trimDispatchTokens(): void {
while (dispatchTokens.size > MAX_AUTOMATION_DISPATCH_TOKENS) {
const oldestEvictable = [...dispatchTokens].find(([, record]) => !record.inFlight)
if (!oldestEvictable) {
return
}
dispatchTokens.delete(oldestEvictable[0])
}
}
export function createAutomationDispatchToken(automationId: string, runId: string): string {
pruneExpiredDispatchTokens()
const token = randomUUID()
@@ -29,9 +40,14 @@ export function createAutomationDispatchToken(automationId: string, runId: strin
expiresAt: Date.now() + DISPATCH_TOKEN_TTL_MS,
inFlight: false
})
trimDispatchTokens()
return token
}
export function getAutomationDispatchTokenCountForTests(): number {
return dispatchTokens.size
}
export function beginAutomationDispatchTokenUse(args: {
automationId: string
runId: string