Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -150,20 +150,23 @@ describe('admitByBudget', () => {
expect(mocks.getHandle).not.toHaveBeenCalled()
})

it('counts a live lease-lapsed unit as running and defers it without starting a run', async () => {
mocks.countRunningUnits.mockResolvedValue({})
mocks.describe.mockResolvedValue(executionStatus('RUNNING'))
const live = sessionizeUnit('event-1', true)
const fresh = sessionizeUnit('event-2')

expect(await admitByBudget([live, fresh])).toEqual({
admitted: [],
deferred: [live, fresh],
})
expect(mocks.getHandle).toHaveBeenCalledWith(syncRunWorkflowId(live))
expect(mocks.getHandle).toHaveBeenCalledTimes(1)
expect(mocks.start).not.toHaveBeenCalled()
})
it.each(['RUNNING', 'PAUSED'])(
'counts a lease-lapsed unit whose workflow is %s as running and defers it without starting a run',
async (statusName) => {
mocks.countRunningUnits.mockResolvedValue({})
mocks.describe.mockResolvedValue(executionStatus(statusName))
const live = sessionizeUnit('event-1', true)
const fresh = sessionizeUnit('event-2')

expect(await admitByBudget([live, fresh])).toEqual({
admitted: [],
deferred: [live, fresh],
})
expect(mocks.getHandle).toHaveBeenCalledWith(syncRunWorkflowId(live))
expect(mocks.getHandle).toHaveBeenCalledTimes(1)
expect(mocks.start).not.toHaveBeenCalled()
},
)

it('admits an orphan whose workflow finished into a free slot', async () => {
mocks.countRunningUnits.mockResolvedValue({})
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
WorkflowIdReusePolicy,
WorkflowNotFoundError,
} from '@crowd/temporal'
import type { WorkflowExecutionStatusName } from '@crowd/temporal'

import { svc } from '../main'
import { applyRunCaps, releaseOrphan } from '../runCap'
Expand All @@ -25,6 +26,7 @@ const HEARTBEAT_TTL_SECONDS = 300
const DEFAULT_RUN_ESTIMATE = 50
const BUDGET_PROBE_CONCURRENCY = 10
const CHANNEL_LABEL_MAX_LENGTH = 80
const LIVE_RUN_STATUSES: WorkflowExecutionStatusName[] = ['RUNNING', 'PAUSED']

export async function claimDue(limit: number): Promise<IClaimedUnit[]> {
return claimDueUnits(dbStoreQx(svc.postgres.writer), limit)
Expand Down Expand Up @@ -88,7 +90,7 @@ async function findLiveLapsedUnitIds(lapsedUnits: IClaimedUnit[]): Promise<Set<s
async function isRunLive(unit: IClaimedUnit): Promise<boolean> {
try {
const { status } = await svc.temporal.workflow.getHandle(syncRunWorkflowId(unit)).describe()
return status.name === 'RUNNING'
return LIVE_RUN_STATUSES.includes(status.name)
} catch (err) {
if (err instanceof WorkflowNotFoundError) {
return false
Expand Down
184 changes: 184 additions & 0 deletions services/libs/connectors/src/pool/tokenPool.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,184 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'

import type { Logger } from '@crowd/logging'
import type { RedisClient } from '@crowd/redis'

import { createHttpClient } from '../http/client'
import {
ConnectorCodeError,
ConnectorError,
ProviderAuthError,
ProviderUnavailableError,
RateLimitError,
} from '../http/errors'
import { MINT_RETRY_DELAY_MS, type TokenMinter, createTokenPool } from './tokenPool'

const PLATFORM = 'example'
const ENTRIES_KEY = `connectors:pool:${PLATFORM}:entries`

function createFakeRedis(): RedisClient {
const hashes = new Map<string, Map<string, string>>()
const sortedSets = new Map<string, Map<string, number>>()
const hash = (key: string) => hashes.get(key) ?? hashes.set(key, new Map()).get(key)!
const sortedSet = (key: string) => sortedSets.get(key) ?? sortedSets.set(key, new Map()).get(key)!

const fake = {
hGetAll: async (key: string) => Object.fromEntries(hash(key)),
hSet: async (key: string, values: Record<string, string>) => {
Object.entries(values).forEach(([field, value]) => hash(key).set(field, value))
},
hIncrBy: async (key: string, field: string, by: number) => {
hash(key).set(field, String(Number(hash(key).get(field) ?? 0) + by))
},
zRange: async (key: string) =>
[...sortedSet(key).entries()].sort((a, b) => a[1] - b[1]).map(([member]) => member),
zAdd: async (key: string, { score, value }: { score: number; value: string }) => {
sortedSet(key).set(value, score)
},
eval: async (
_script: string,
{ keys, arguments: args }: { keys: string[]; arguments: string[] },
) => {
const [entryId, rawUpdate] = args
const current = hash(keys[0]).get(entryId)
if (!current) {
return 0
}
const state = JSON.parse(current) as Record<string, unknown>
for (const [field, value] of Object.entries(
JSON.parse(rawUpdate) as Record<string, unknown>,
)) {
if (value === null) {
delete state[field]
} else {
state[field] = value
}
}
hash(keys[0]).set(entryId, JSON.stringify(state))
return 1
},
}
return fake as unknown as RedisClient
}

async function poolWithEntries(entries: Record<string, object>, mintToken: TokenMinter) {
const redis = createFakeRedis()
await redis.hSet(
ENTRIES_KEY,
Object.fromEntries(Object.entries(entries).map(([id, state]) => [id, JSON.stringify(state)])),
)
for (const [index, id] of Object.keys(entries).entries()) {
await redis.zAdd(`connectors:pool:${PLATFORM}:lru`, { score: index, value: id })
}
return createTokenPool(redis, PLATFORM, { mintToken })
}

function minterFailingWith(failures: Record<string, ConnectorError>): TokenMinter {
return vi.fn(async (entryId: string) => {
if (failures[entryId]) {
throw failures[entryId]
}
return { token: `minted-${entryId}`, expiresAt: new Date(Date.now() + 3_600_000).toISOString() }
})
}

describe('token pool acquire', () => {
const NOW = new Date('2026-11-26T10:00:00.000Z')
const at = (offsetMs: number) => new Date(NOW.getTime() + offsetMs)
const exhaustedUntil = (resumeAt: Date) =>
new RateLimitError('token pool exhausted', { resumeAt })
const retryMintAt = (resumeAt: Date) =>
new RateLimitError('token pool has no usable token, waiting to retry a failed mint', {
resumeAt,
})
const empty = new ProviderAuthError('token pool empty')

beforeEach(() => {
vi.useFakeTimers({ now: NOW, toFake: ['Date'] })
})

afterEach(() => {
vi.useRealTimers()
})

it.each<[string, Record<string, object>, Record<string, ConnectorError>, ConnectorError]>([
[
'a transient sign-in failure of the only entry waits for the mint retry delay',
{ only: {} },
{ only: new ProviderUnavailableError('sign-in page down') },
retryMintAt(at(MINT_RETRY_DELAY_MS)),
],
[
'a rate-limited mint that may retry sooner still waits for the mint retry delay',
{ only: {} },
{ only: new RateLimitError('slow down', { resumeAt: at(120_000) }) },
retryMintAt(at(MINT_RETRY_DELAY_MS)),
],
[
'a rate-limited mint that must wait longer passes that time on',
{ only: {} },
{ only: new RateLimitError('slow down', { resumeAt: at(900_000) }) },
retryMintAt(at(900_000)),
],
[
'a parked entry decides the wait even when it frees up after the mint retry',
{ parked: { parkedUntil: at(900_000).toISOString() }, failing: {} },
{ failing: new ProviderUnavailableError('sign-in page down') },
exhaustedUntil(at(900_000)),
],
[
'one quarantined and one transiently failing entry waits for the mint retry delay',
{ broken: { quarantined: true }, failing: {} },
{ failing: new RateLimitError('slow down') },
retryMintAt(at(MINT_RETRY_DELAY_MS)),
],
[
'a rejected sign-in quarantines the entry and leaves the pool empty',
{ only: {} },
{ only: new ProviderAuthError('bad password') },
empty,
],
[
'a mint failure of any other class leaves the pool empty',
{ only: {} },
{ only: new ConnectorCodeError('minter bug') },
empty,
],
])('%s', async (_name, entries, failures, expected) => {
const pool = await poolWithEntries(entries, minterFailingWith(failures))

const error = (await pool.acquire().catch((err: unknown) => err)) as ConnectorError

expect(error).toBeInstanceOf(expected.constructor)
expect([error.message, error.options?.resumeAt]).toEqual([
expected.message,
expected.options?.resumeAt,
])
})

it('makes a request mint once and fail without retrying when the only mint fails transiently', async () => {
const mint = minterFailingWith({ only: new ProviderUnavailableError('sign-in page down') })
const pool = await poolWithEntries({ only: {} }, mint)
const http = createHttpClient({
acquireToken: () => pool.acquire('only'),
parkToken: pool.park,
invalidateToken: pool.invalidate,
log: { info: vi.fn(), warn: vi.fn() } as unknown as Logger,
})

await expect(http.request({ url: 'https://example.test/items' })).rejects.toMatchObject({
errorClass: 'provider.rate_limit',
options: { resumeAt: at(MINT_RETRY_DELAY_MS) },
})
expect(mint).toHaveBeenCalledTimes(1)
})

it('borrows the next entry when one installation fails to mint, and quarantines nothing', async () => {
const mint = minterFailingWith({ first: new ProviderUnavailableError('github 502') })
const pool = await poolWithEntries({ first: {}, second: {} }, mint)

await expect(pool.acquire('first')).resolves.toEqual({ id: 'second', value: 'minted-second' })
await expect(pool.acquire('first')).resolves.toEqual({ id: 'second', value: 'minted-second' })
expect(mint).toHaveBeenCalledTimes(3)
})
})
52 changes: 39 additions & 13 deletions services/libs/connectors/src/pool/tokenPool.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import { ConnectorError, ProviderAuthError, RateLimitError } from '../http/error

export const PROBE_STALENESS_MS = 90_000
const TOKEN_EXPIRY_MARGIN_MS = 120_000
export const MINT_RETRY_DELAY_MS = 300_000
const TRANSIENT_MINT_ERROR_CLASSES = new Set(['provider.unavailable', 'provider.rate_limit'])

export interface BudgetSnapshot {
limit: number
Expand Down Expand Up @@ -45,6 +47,11 @@ interface IEntryState {

type EntryStateUpdate = { [K in keyof IEntryState]?: IEntryState[K] | null }

interface ITokenResolution {
token: string | null
mintRetryAt?: Date
}

// atomic get-merge-set per entry; JSON null in the update deletes the field
const MERGE_ENTRY_STATE_SCRIPT = `
local json = redis.call('HGET', KEYS[1], ARGV[1])
Expand Down Expand Up @@ -167,20 +174,20 @@ export function createTokenPool(
entryId: string,
state: IEntryState,
nowMs: number,
): Promise<string | null> {
): Promise<ITokenResolution> {
const cached = usableToken(state, nowMs)
if (cached) {
return cached
return { token: cached }
}
const mint = options?.mintToken
if (!mint) {
return null
return { token: null }
}
try {
const { token, expiresAt } = await mint(entryId)
await updateState(entryId, { token, tokenExpiresAtMs: new Date(expiresAt).getTime() })
log?.info({ event: 'pool_token_minted', entryId, expiresAt }, 'pool token minted')
return token
return { token }
} catch (err) {
if (err instanceof ConnectorError) {
if (err.errorClass === 'provider.auth' || err.errorClass === 'provider.contract') {
Expand All @@ -194,13 +201,21 @@ export function createTokenPool(
},
'pool entry quarantined on mint failure',
)
return null
return { token: null }
}
log?.warn(
{ event: 'pool_mint_failed', entryId, errorClass: err.errorClass, errMsg: err.message },
'token mint failed, skipping entry',
)
return null
if (!TRANSIENT_MINT_ERROR_CLASSES.has(err.errorClass)) {
return { token: null }
}
return {
token: null,
mintRetryAt: new Date(
Math.max(err.options?.resumeAt?.getTime() ?? 0, Date.now() + MINT_RETRY_DELAY_MS),
),
}
}
throw err
}
Expand Down Expand Up @@ -266,6 +281,7 @@ export function createTokenPool(
: lruOrder
const probe = options?.probeBudget
let earliestBudgetResetAt: Date | null = null
let earliestMintRetryAt: Date | null = null
for (const id of ordered) {
const state = states.get(id)
if (!state) {
Expand All @@ -279,10 +295,12 @@ export function createTokenPool(
logSkip(id, 'parked', { parkedUntil: state.parkedUntil })
continue
}
const token = await ensureUsableToken(id, state, nowMs)
if (!token) {
const resolution = await ensureUsableToken(id, state, nowMs)
if (!resolution.token) {
earliestMintRetryAt = earliestDate([earliestMintRetryAt, resolution.mintRetryAt ?? null])
continue
}
const token = resolution.token
if (probe) {
const bucket = await loadBucket(probe, id, token, nowMs)
if (bucket && bucket.remaining <= 0) {
Expand All @@ -301,14 +319,15 @@ export function createTokenPool(
logAcquired(id, preferredEntryId)
return { id, value: token }
}
const parkedResumeAt = earliestParkedUntil(states, nowMs)
const resumeAt =
parkedResumeAt && earliestBudgetResetAt
? new Date(Math.min(parkedResumeAt.getTime(), earliestBudgetResetAt.getTime()))
: (parkedResumeAt ?? earliestBudgetResetAt)
const resumeAt = earliestDate([earliestParkedUntil(states, nowMs), earliestBudgetResetAt])
if (resumeAt) {
throw new RateLimitError('token pool exhausted', { resumeAt })
}
if (earliestMintRetryAt) {
throw new RateLimitError('token pool has no usable token, waiting to retry a failed mint', {
resumeAt: earliestMintRetryAt,
})
}
throw new ProviderAuthError('token pool empty')
},

Expand Down Expand Up @@ -374,3 +393,10 @@ export function createTokenPool(
},
}
}

function earliestDate(dates: (Date | null)[]): Date | null {
return dates.reduce<Date | null>(
(earliest, date) => (date && (!earliest || date < earliest) ? date : earliest),
null,
)
}
Loading
Loading