Skip to content

src/quota.test.ts

51 lines · 1.7 KB · TypeScript
Raw
import assert from 'node:assert/strict'
import { test } from 'node:test'
import {
	adjustPoll,
	isPlanLimitError,
	nextUtcMidnight,
	quotaLevel,
	quotaWarning,
	readFetchQuota,
} from './quota.ts'

const usage = (current: number, limit = 80_000) => ({
	day: '2026-10-10',
	resources: [
		{ resource: 'job_runs_per_day', current: 1, limit: 10 },
		{ resource: 'outbound_fetches_per_day', current, limit },
	],
})

test('readFetchQuota picks outbound_fetches_per_day', () => {
	assert.deepEqual(readFetchQuota(usage(64_000)), { current: 64_000, limit: 80_000, percent: 80, day: '2026-10-10' })
	assert.equal(readFetchQuota({ resources: [] }), null)
	assert.equal(readFetchQuota(null), null)
})

test('quotaLevel thresholds', () => {
	assert.equal(quotaLevel(null), 'ok')
	assert.equal(quotaLevel(readFetchQuota(usage(10_000))), 'ok')
	assert.equal(quotaLevel(readFetchQuota(usage(64_000))), 'warn')
	assert.equal(quotaLevel(readFetchQuota(usage(76_000))), 'critical')
})

test('adjustPoll only raises', () => {
	assert.equal(adjustPoll(60, 'ok'), 60)
	assert.equal(adjustPoll(60, 'warn'), 300)
	assert.equal(adjustPoll(600, 'warn'), 600)
	assert.equal(adjustPoll(15, 'critical'), 900)
	assert.equal(adjustPoll(undefined, 'critical'), undefined)
})

test('quotaWarning is null when ok', () => {
	const q = readFetchQuota(usage(76_000))!
	assert.equal(quotaWarning(q, 'ok'), null)
	assert.match(quotaWarning(q, 'critical')!, /76,000 of 80,000/)
})

test('isPlanLimitError and reset time', () => {
	assert.equal(isPlanLimitError(new Error('Plan limit reached: outbound_fetches_per_day')), true)
	assert.equal(isPlanLimitError(new Error('timeout')), false)
	assert.equal(nextUtcMidnight(Date.parse('2026-10-10T22:20:00Z')).toISOString(), '2026-10-11T00:00:00.000Z')
})