diff --git a/.env.example b/.env.example index 0d6ac91..3b5b19a 100644 --- a/.env.example +++ b/.env.example @@ -25,3 +25,8 @@ VAPI_PRIVATE_API_KEY=your-vapi-private-key-here # Set to the EU endpoint for EU-region orgs. # VAPI_BASE_URL=https://api.vapi.ai # VAPI_BASE_URL=https://api.eu.vapi.ai + +# Optional max GitOps RPM: client-side ceiling, NOT a Vapi org rate limit. +# Overrides resources//.vapi-org.json maxGitopsRpm (default 100). +# Must be a positive integer; shell/CI takes precedence over this file. +# VAPI_MAX_GITOPS_RPM=100 diff --git a/README.md b/README.md index 9984b3d..8b8b257 100644 --- a/README.md +++ b/README.md @@ -203,13 +203,20 @@ More detail: [How the engine works](docs/guides/how-it-works.md). ## Commands +Vapi requests use a per-org [max GitOps RPM](docs/guides/configuration.md#max-gitops-rpm) +client ceiling (default 100), configured by `maxGitopsRpm` in the committed +`.vapi-org.json` or overridden by `VAPI_MAX_GITOPS_RPM`. This is not a Vapi org limit. +Reads and writes use the same limiter, without an extra write delay; retry +backoff still applies. The burst capacity is capped at 20 requests (20 at the +default 100 RPM), allowing up to 120 requests in a minute at the default. + | Command | What it does | | --- | --- | | `npm run setup` | Connect an org: create `.env.` and `resources//` | | `npm run validate -- ` | Check resource files offline before deploying | | `npm run apply -- ` | Deploy: pull, merge, then push (the default) | | `npm run pull -- ` | Sync platform changes down without overwriting local edits | -| `npm run push -- ` | Push without pulling first (prefer `apply`) | +| `npm run push -- ` | Push without pulling first (prefer `apply`); paced by max GitOps RPM | | `npm run rollback -- ` | Restore a pre-deploy snapshot | | `npm run cleanup -- ` | Find, and optionally delete, platform resources with no file | | `npm run audit -- ` | Report drift between files, state and the platform | diff --git a/docs/guides/commands.md b/docs/guides/commands.md index 299b12f..87331ef 100644 --- a/docs/guides/commands.md +++ b/docs/guides/commands.md @@ -7,6 +7,14 @@ The other commands are direct only. +Every command that contacts Vapi observes the per-org +[max GitOps RPM](configuration.md#max-gitops-rpm) client ceiling (default 100). +Set committed `maxGitopsRpm` or override with `VAPI_MAX_GITOPS_RPM`; this does +not change the Vapi org API rate limit. Setup validates the key and region +using the default client ceiling before asking for the org folder; subsequent +requests use that org’s configured ceiling. Reads and writes share this +limiter without an additional write delay; retry backoff still applies. + | Command | Usage | What it does | | --- | --- | --- | | `npm run setup` | `npm run setup [-- ]` | Connect an org: creates `.env.` and `resources//`. | diff --git a/docs/guides/configuration.md b/docs/guides/configuration.md index cffbc5d..e1ddf32 100644 --- a/docs/guides/configuration.md +++ b/docs/guides/configuration.md @@ -8,6 +8,7 @@ gitignored: never commit them. | Variable | Required | Description | | --- | --- | --- | | `VAPI_PRIVATE_API_KEY` | ✅ | The org's private API key, from [Private API Keys](https://dashboard.vapi.ai/org/api-keys). The older name `VAPI_TOKEN` is also accepted. | +| `VAPI_MAX_GITOPS_RPM` | | Override the org’s GitOps client request ceiling, in requests per minute. Positive integer; defaults to `maxGitopsRpm`, then 100. | | `VAPI_BASE_URL` | | API base URL. Defaults to `https://api.vapi.ai`; EU orgs use `https://api.eu.vapi.ai` (`npm run setup -- --region eu` sets it). | | `VAPI_CREDENTIAL_`, `VAPI_PHONE_NUMBER_` | | Generated by `setup` and `pull` inside a marked block: the org's credential and phone-number IDs, by name. Values you set outside the block are kept and take precedence. | @@ -49,7 +50,7 @@ Set these in GitHub under **Settings → Secrets and variables → Actions**. | --- | --- | | `promotion.yml` | Promotion pipelines between orgs. Start from `promotion.example.yml`. | | `vapi-checks.yml` | PR checks. Start from `vapi-checks.example.yml`. | -| `resources//.vapi-org.json` | The Vapi org ID the folder belongs to. Written by the first command that can see the key's org, then checked by every command before any request: a key for another org stops the command. If a folder genuinely moves to another org, delete the file in a reviewed commit. | +| `resources//.vapi-org.json` | The Vapi org ID and optional `maxGitopsRpm` client ceiling (default 100). Written by the first command that can see the key's org, then checked by every command before any request: a key for another org stops the command. If a folder genuinely moves to another org, delete the file in a reviewed commit. | | `resources//.vapi-ignore` | Platform resources this repo shouldn't manage, as glob patterns. See `resources/.vapi-ignore.example` and [YAML conventions](../learnings/yaml-conventions.md). | ## Other environment variables @@ -59,3 +60,39 @@ Set these in GitHub under **Settings → Secrets and variables → Actions**. | `CI=true` | Suppresses interactive warnings, such as the one `pull --force` prints. Set automatically by most CI systems. | | `VAPI_CALL_DEBUG=1` | Makes `npm run call` log message types it would otherwise ignore. | | `VAPI_GITOPS_ROOT` | Overrides the repository root that `npm run promote` and `npm run check` read from. Mainly for tests. | + +## max GitOps RPM + +max GitOps RPM caps the requests this client sends for an org, including +reads, writes, probes and retries. It is a GitOps client limit, not a Vapi +org limit. Set it in the committed `resources//.vapi-org.json`: + +```json +{ "orgId": "your-org-id", "maxGitopsRpm": 100 } +``` + +The default is 100 requests per minute, below Vapi's default org API limit +of 200 RPM. Leave headroom for other clients. Values must be positive +integers; an invalid winning setting stops the command and names its source. +A settings-only file is valid before pinning, which preserves existing fields. + +Precedence is shell/CI `VAPI_MAX_GITOPS_RPM`, then `.env.`, +`.env..local` and `.env.local` (first file wins), then committed +`maxGitopsRpm`, then 100. Quoted values, `export` prefixes and inline +comments work the same way in the env files for every command. Only the +winning value is validated; each org's limiter is configured once per process. + +On a 429, the warning names the org and effective RPM, suggests lowering +`maxGitopsRpm` or setting `VAPI_MAX_GITOPS_RPM`, and links to the org API +rate limit: [EU](https://dashboard.eu.vapi.ai/settings/organization) for +`api.eu.vapi.ai`, otherwise +[US](https://dashboard.vapi.ai/settings/organization). +Reads and writes use this limiter equally, with no extra write delay. +Existing retry backoff still applies. + +Each org shares one token bucket per process. It refills at +`maxGitopsRpm / 60` tokens per second, with a small burst capacity of +`max(1, min(20, floor(maxGitopsRpm / 5)))` (20 requests at the default). +The default allows up to 120 requests in a minute including the initial burst, +below the default 200 RPM org limit. Separate processes do not coordinate, +so their combined traffic can exceed the client ceiling. diff --git a/docs/guides/troubleshooting.md b/docs/guides/troubleshooting.md index a167999..34a2d32 100644 --- a/docs/guides/troubleshooting.md +++ b/docs/guides/troubleshooting.md @@ -125,3 +125,17 @@ have. Build `.ts` resources from files in the repository instead. A folder under `resources/` that isn't a valid org name (lowercase letters, digits and hyphens) fails too. Rename it, or move it out of `resources/`. + +## 429: max GitOps RPM may be too high + +GitOps warns once per org per process on a Vapi 429. Lower `maxGitopsRpm` +in `resources//.vapi-org.json`, or its `VAPI_MAX_GITOPS_RPM` override. +This is a GitOps client limit, not a Vapi org limit. Other clients and other +GitOps processes can also use the org's API quota. + +The warning links to your org-level API rate limit at +https://dashboard.eu.vapi.ai/settings/organization when the org uses +`api.eu.vapi.ai`, otherwise https://dashboard.vapi.ai/settings/organization. +Existing retry/backoff remains in effect; the client ceiling does not +guarantee that the server will never rate-limit you. See +[configuration](configuration.md#max-gitops-rpm) for precedence and burst behavior. diff --git a/improvements.md b/improvements.md index ef4ca0e..971fb21 100644 --- a/improvements.md +++ b/improvements.md @@ -2076,3 +2076,13 @@ dependency check, as `check-payload.ts` already does. `AGENTS.md`. Don't conflate that with drift detection. - **Renaming `npm run eval` to disambiguate from `npm run sim`.** Backwards-incompatible script change; raise as a separate issue. + +## 2026-11-17 — Per-org max GitOps RPM + +- **Problem:** Independent request paths could burst without a shared client ceiling. +- **Current behavior:** [rate-limit.ts](src/rate-limit.ts) shares a token bucket per org; [vapi-fetch.ts](src/vapi-fetch.ts) routes every Vapi fetch through it, including retries. +- **Risk:** Multiple processes or other clients may still exhaust the platform quota. +- **Current mitigation:** Committed `maxGitopsRpm` (default 100), overridden by `VAPI_MAX_GITOPS_RPM`; invalid winning settings stop requests. A 429 warns with the org's region-specific dashboard link. +- **Possible fix:** Coordinate budgets across processes if deployments need a global client ceiling. +- **Status:** Implemented; existing retry backoff retained; reads and writes paced only by the shared limiter. This is a GitOps client limit, not a Vapi org limit. +- **Review hardening:** Invalid limits exit cleanly without a stack trace. The setup wizard keeps key/region validation first, using the default client ceiling until the folder is selected. Shared env parsing supports exports and comments without leaking one org’s override to another; 429 advice names the org and effective RPM. diff --git a/src/api.ts b/src/api.ts index 6ea7e20..b0bc07c 100644 --- a/src/api.ts +++ b/src/api.ts @@ -1,12 +1,14 @@ import { BASE_DIR, DRY_RUN, + MAX_GITOPS_RPM, VAPI_BASE_URL, VAPI_ENV, VAPI_TOKEN, VAPI_TOKEN_SOURCE, } from "./config.ts"; import { ORG_PIN_FILE, OrgPinMismatchError, orgPinCheck } from "./org-pin.ts"; +import { orgLimiter } from "./rate-limit.ts"; import type { VapiResponse } from "./types.ts"; import { userAgentGet, vapiClientGet } from "./user-agent.ts"; import { @@ -16,6 +18,7 @@ import { shouldRetry, VapiApiError, } from "./vapi-client.ts"; +import { limitedVapiFetch } from "./vapi-fetch.ts"; // ───────────────────────────────────────────────────────────────────────────── // Dry-run accounting @@ -45,6 +48,7 @@ export function orgPinGuard(): Promise { rootDir: BASE_DIR, org: VAPI_ENV, connection: { + limiter: orgLimiter(BASE_DIR, VAPI_ENV, MAX_GITOPS_RPM), token: VAPI_TOKEN ?? "", baseUrl: VAPI_BASE_URL, userAgent: userAgentGet(), @@ -103,26 +107,10 @@ function formatBodyPreview(body: Record): string { // existing importers and `instanceof` checks see one class. export { VapiApiError }; -// Minimum gap between writes, to stay under rate limits. Reads skip it: a pull -// is a handful of list requests, and a 700ms gap before each one was most of a -// pull's run time. A 429 on a read is still retried with backoff. -const REQUEST_DELAY_MS = 700; - -let lastRequestTime = 0; - async function sleep(ms: number): Promise { return new Promise((resolve) => setTimeout(resolve, ms)); } -async function throttle(): Promise { - const now = Date.now(); - const timeSinceLastRequest = now - lastRequestTime; - if (timeSinceLastRequest < REQUEST_DELAY_MS) { - await sleep(REQUEST_DELAY_MS - timeSinceLastRequest); - } - lastRequestTime = Date.now(); -} - export async function vapiRequest( method: "POST" | "PATCH", endpoint: string, @@ -146,8 +134,8 @@ export async function vapiRequest( } for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) { - await throttle(); - const response = await fetch(url, { + const limiter = orgLimiter(BASE_DIR, VAPI_ENV, MAX_GITOPS_RPM); + const response = await limitedVapiFetch(limiter, url, { method, headers: { "Content-Type": "application/json", @@ -193,7 +181,8 @@ export async function vapiGet(endpoint: string): Promise { const url = `${VAPI_BASE_URL}${endpoint}`; for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) { - const response = await fetch(url, { + const limiter = orgLimiter(BASE_DIR, VAPI_ENV, MAX_GITOPS_RPM); + const response = await limitedVapiFetch(limiter, url, { method: "GET", headers: { Authorization: `Bearer ${VAPI_TOKEN}`, @@ -243,8 +232,8 @@ export async function vapiDelete(endpoint: string): Promise { } for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) { - await throttle(); - const response = await fetch(url, { + const limiter = orgLimiter(BASE_DIR, VAPI_ENV, MAX_GITOPS_RPM); + const response = await limitedVapiFetch(limiter, url, { method: "DELETE", headers: { Authorization: `Bearer ${VAPI_TOKEN}`, diff --git a/src/call.ts b/src/call.ts index 21304cb..cb7ee5a 100644 --- a/src/call.ts +++ b/src/call.ts @@ -5,8 +5,10 @@ import { createRequire } from "module"; import { dirname, join, resolve } from "path"; import * as readline from "readline"; import { fileURLToPath } from "url"; +import { orgLimiterOrExit } from "./rate-limit.ts"; import type { Environment, StateFile } from "./types.ts"; import { userAgentGet, vapiClientGet } from "./user-agent.ts"; +import { limitedVapiFetch } from "./vapi-fetch.ts"; const require = createRequire(import.meta.url); @@ -360,7 +362,8 @@ async function createCall( console.log(`📞 Creating call...`); - const response = await fetch(url, { + const limiter = orgLimiterOrExit(BASE_DIR, config.env); + const response = await limitedVapiFetch(limiter, url, { method: "POST", headers: { "Content-Type": "application/json", diff --git a/src/check-cmd.ts b/src/check-cmd.ts index 494194d..ef99431 100644 --- a/src/check-cmd.ts +++ b/src/check-cmd.ts @@ -32,6 +32,7 @@ import { } from "./check-status.ts"; import type { OrgConnection } from "./org-connection.ts"; import { childRun, connectionLoad, tokensParse } from "./org-connection.ts"; +import { orgLimiterOrExit } from "./rate-limit.ts"; import { userAgentGet, vapiClientGet } from "./user-agent.ts"; import type { VapiConnection } from "./vapi-client.ts"; @@ -188,6 +189,7 @@ function connectionsLoad( const envKey = process.env.VAPI_PRIVATE_API_KEY ?? process.env.VAPI_TOKEN; const connections = new Map(); for (const runOrg of runOrgs) { + orgLimiterOrExit(root, runOrg); const baseUrl = checks.find( (check) => check.runOrg === runOrg && check.baseUrl, )?.baseUrl; @@ -277,6 +279,7 @@ function reportWrite( } async function liveRun( + root: string, parsed: CheckArgs, jobs: CheckJob[], connections: Map, @@ -293,7 +296,13 @@ async function liveRun( const vapiClient = vapiClientGet("check"); const vapi = (job: CheckJob): VapiConnection => { const connection = connections.get(job.check.runOrg)!; - return { token: connection.token, baseUrl: connection.baseUrl!, userAgent, vapiClient }; + return { + limiter: orgLimiterOrExit(root, job.check.runOrg), + token: connection.token, + baseUrl: connection.baseUrl!, + userAgent, + vapiClient, + }; }; const post = async (status: CommitStatus) => { if (statusEnv) await commitStatusPost(statusEnv, status); @@ -391,7 +400,7 @@ async function checksRun( mockNotices: [], durationMs: 0, })) - : await liveRun(parsed, jobs, connections, statusEnv); + : await liveRun(root, parsed, jobs, connections, statusEnv); reportWrite(root, parsed, results, skipped); return { code: exitCode(results), results }; } diff --git a/src/check-run.ts b/src/check-run.ts index 5280fa1..862172e 100644 --- a/src/check-run.ts +++ b/src/check-run.ts @@ -84,6 +84,8 @@ export function mockNoticesCollect(items: SimRunItem[]): string[] { } function errorReason(error: unknown): string { + if (error instanceof Error && error.name === "AbortError") + return "not started: interrupted"; if (error instanceof VapiApiError && error.statusCode === 402) return `billing: the run org can't start simulations (402: ${error.apiMessage})`; return error instanceof Error ? error.message : String(error); diff --git a/src/cleanup.ts b/src/cleanup.ts index c988b2a..27de54e 100644 --- a/src/cleanup.ts +++ b/src/cleanup.ts @@ -1,37 +1,36 @@ import { resolve } from "path"; import { fileURLToPath } from "url"; import { + BASE_DIR, loadIgnorePatterns, matchesIgnore, + MAX_GITOPS_RPM, VAPI_BASE_URL, VAPI_ENV, VAPI_TOKEN, } from "./config.ts"; import { orgPinGuard } from "./api.ts"; +import { orgLimiter } from "./rate-limit.ts"; import { FOLDER_MAP } from "./resource-parse.ts"; import { slugify } from "./slug-utils.ts"; import { loadState } from "./state.ts"; import type { ResourceType } from "./types.ts"; import { userAgentGet, vapiClientGet } from "./user-agent.ts"; +import { limitedVapiFetch } from "./vapi-fetch.ts"; // ───────────────────────────────────────────────────────────────────────────── // Dangerous Sync - Delete everything NOT in state file // ───────────────────────────────────────────────────────────────────────────── -const REQUEST_DELAY_MS = 700; - -async function sleep(ms: number): Promise { - return new Promise((resolve) => setTimeout(resolve, ms)); -} - function isRecord(value: unknown): value is Record { return value !== null && typeof value === "object" && !Array.isArray(value); } async function vapiGet(endpoint: string, debug = false): Promise { await orgPinGuard(); - await sleep(REQUEST_DELAY_MS); - const response = await fetch(`${VAPI_BASE_URL}${endpoint}`, { + const limiter = orgLimiter(BASE_DIR, VAPI_ENV, MAX_GITOPS_RPM); + const url = `${VAPI_BASE_URL}${endpoint}`; + const response = await limitedVapiFetch(limiter, url, { headers: { Authorization: `Bearer ${VAPI_TOKEN}`, "User-Agent": userAgentGet(), @@ -72,8 +71,9 @@ async function vapiGet(endpoint: string, debug = false): Promise { async function vapiDelete(endpoint: string): Promise { await orgPinGuard(); - await sleep(REQUEST_DELAY_MS); - const response = await fetch(`${VAPI_BASE_URL}${endpoint}`, { + const limiter = orgLimiter(BASE_DIR, VAPI_ENV, MAX_GITOPS_RPM); + const url = `${VAPI_BASE_URL}${endpoint}`; + const response = await limitedVapiFetch(limiter, url, { method: "DELETE", headers: { Authorization: `Bearer ${VAPI_TOKEN}`, diff --git a/src/config.ts b/src/config.ts index 7ee5460..e559366 100644 --- a/src/config.ts +++ b/src/config.ts @@ -1,8 +1,9 @@ import { missingApiKeyMessage, resolveOrgApiKey } from "./api-key.ts"; -import { existsSync, readFileSync } from "fs"; -import { basename, dirname, join, relative, resolve } from "path"; +import { dirname, join, relative, resolve } from "path"; import { fileURLToPath } from "url"; import type { Environment, ResourceType } from "./types.ts"; +import { orgEnvFilesRead, shellEnvironment } from "./env-file.ts"; +import { maxGitopsRpmRead } from "./rate-limit.ts"; import { ignorePatternsRead, matchesIgnore as matchesIgnorePatterns, @@ -182,41 +183,13 @@ function parseFlags(): { // a key from .env. apart from one that was exported in the shell. function loadEnvFile(env: string, baseDir: string): Record { const fileVars: Record = {}; - const envFiles = [ - join(baseDir, `.env.${env}`), // e.g. .env.my-org - join(baseDir, `.env.${env}.local`), // e.g. .env.my-org.local (local overrides) - join(baseDir, ".env.local"), // .env.local (always loaded last) - ]; - - for (const envFile of envFiles) { - if (existsSync(envFile)) { - const content = readFileSync(envFile, "utf-8"); - for (const line of content.split("\n")) { - const trimmed = line.trim(); - if (!trimmed || trimmed.startsWith("#")) continue; - - const eqIndex = trimmed.indexOf("="); - if (eqIndex === -1) continue; - - const key = trimmed.slice(0, eqIndex).trim(); - let value = trimmed.slice(eqIndex + 1).trim(); - - // Remove quotes if present - if ( - (value.startsWith('"') && value.endsWith('"')) || - (value.startsWith("'") && value.endsWith("'")) - ) { - value = value.slice(1, -1); - } - - if (fileVars[key] === undefined) fileVars[key] = value; - // Only set if not already defined (env vars take precedence) - if (process.env[key] === undefined) { - process.env[key] = value; - } - } - console.log(`📁 Loaded env file: ${basename(envFile)}`); + for (const { name, values } of orgEnvFilesRead(baseDir, env)) { + for (const [key, value] of Object.entries(values)) { + if (value === undefined) continue; + if (fileVars[key] === undefined) fileVars[key] = value; + if (process.env[key] === undefined) process.env[key] = value; } + console.log(`📁 Loaded env file: ${name}`); } return fileVars; } @@ -245,7 +218,16 @@ export const { // merged in, so an exported key still beats a key in the .env file: // VAPI_PRIVATE_API_KEY_, then VAPI_PRIVATE_API_KEY / VAPI_TOKEN, then // .env.. See resolveOrgApiKey. -const SHELL_ENV = { ...process.env }; +const SHELL_ENV = shellEnvironment; + +export const MAX_GITOPS_RPM = (() => { + try { + return maxGitopsRpmRead(BASE_DIR, VAPI_ENV, SHELL_ENV); + } catch (error) { + console.error(error instanceof Error ? error.message : String(error)); + process.exit(1); + } +})(); const ENV_FILE_VARS = loadEnvFile(VAPI_ENV, BASE_DIR); const API_KEY = resolveOrgApiKey(VAPI_ENV, SHELL_ENV, ENV_FILE_VARS); diff --git a/src/env-file.ts b/src/env-file.ts new file mode 100644 index 0000000..2d051a5 --- /dev/null +++ b/src/env-file.ts @@ -0,0 +1,15 @@ +import { existsSync, readFileSync } from "node:fs"; +import { join } from "node:path"; +import { parseEnv } from "node:util"; + +// Keep shell overrides separate from values merged into process.env later. +export const shellEnvironment = { ...process.env }; + +export function orgEnvFilesRead(rootDir: string, org: string) { + return [`.env.${org}`, `.env.${org}.local`, ".env.local"] + .filter((name) => existsSync(join(rootDir, name))) + .map((name) => ({ + name, + values: parseEnv(readFileSync(join(rootDir, name), "utf8")), + })); +} diff --git a/src/interactive.ts b/src/interactive.ts index 67eb822..ff82688 100644 --- a/src/interactive.ts +++ b/src/interactive.ts @@ -4,12 +4,14 @@ import { execSync } from "child_process"; import { existsSync, readdirSync, readFileSync, statSync } from "fs"; import { dirname, extname, join, relative } from "path"; import { fileURLToPath } from "url"; +import { orgLimiterOrExit } from "./rate-limit.ts"; import searchableCheckbox, { BACK_SENTINEL } from "./searchableCheckbox.js"; // slug-utils is config-free (no config.ts side effects) — safe to import in // the launcher, which runs before any org/token is selected. import { isBackupCopyFile } from "./slug-utils.ts"; import type { StateFile } from "./types.ts"; import { userAgentGet, vapiClientGet } from "./user-agent.ts"; +import { limitedVapiFetch } from "./vapi-fetch.ts"; // ───────────────────────────────────────────────────────────────────────────── // Constants @@ -223,8 +225,11 @@ async function apiGet( token: string, baseUrl: string, endpoint: string, + org: string, ): Promise { - const response = await fetch(`${baseUrl}${endpoint}`, { + const limiter = orgLimiterOrExit(BASE_DIR, org); + const url = `${baseUrl}${endpoint}`; + const response = await limitedVapiFetch(limiter, url, { method: "GET", headers: { Authorization: `Bearer ${token}`, @@ -497,7 +502,7 @@ export async function runInteractivePull(): Promise { snapshots = await Promise.all( RESOURCE_TYPES.map(async (type): Promise => { try { - const data = await apiGet(token, baseUrl, type.endpoint); + const data = await apiGet(token, baseUrl, type.endpoint, slug); return { key: type.key, label: type.label, diff --git a/src/org-pin.ts b/src/org-pin.ts index 6ed9935..73d204b 100644 --- a/src/org-pin.ts +++ b/src/org-pin.ts @@ -162,9 +162,13 @@ export async function orgPinCheck(args: OrgPinCheckArgs): Promise ` Stopped before reading or changing anything.\n${fix}`, ); if (!folderExists) return { kind: "unpinned" }; + const path = orgPinPath(rootDir, org); + const settings = existsSync(path) + ? JSON.parse(readFileSync(path, "utf8")) + : {}; writeFileSync( - orgPinPath(rootDir, org), - `${JSON.stringify({ orgId: keyOrg.orgId }, null, 2)}\n`, + path, + `${JSON.stringify({ ...settings, orgId: keyOrg.orgId }, null, 2)}\n`, ); return { kind: "pinned", orgId: keyOrg.orgId }; } diff --git a/src/promotion-gate.ts b/src/promotion-gate.ts index 22e42c2..2a9b5bc 100644 --- a/src/promotion-gate.ts +++ b/src/promotion-gate.ts @@ -9,6 +9,7 @@ import { checkJobsBuild } from "./check-build.ts"; import type { CheckOutcome, CheckTargetResult } from "./check-run.ts"; import { checkRunAll, MAX_CONCURRENT, MIN_START_MS } from "./check-run.ts"; import type { OrgConnection } from "./org-connection.ts"; +import { orgLimiterOrExit } from "./rate-limit.ts"; import type { PromotionConfig } from "./promotion.ts"; import { userAgentGet, vapiClientGet } from "./user-agent.ts"; @@ -151,6 +152,7 @@ export async function promotionGateRun( const results = await checkRunAll({ jobs, connectionFor: () => ({ + limiter: orgLimiterOrExit(rootDir, check.runOrg), token: connection.token, baseUrl: connection.baseUrl ?? DEFAULT_BASE_URL, // Gate runs are counted apart from PR check runs. diff --git a/src/push.ts b/src/push.ts index c22f41d..2678186 100644 --- a/src/push.ts +++ b/src/push.ts @@ -16,6 +16,7 @@ import { removeExcludedKeys, STATE_FILE_PATH, STRICT_VALIDATION, + MAX_GITOPS_RPM, VAPI_BASE_URL, VAPI_ENV, } from "./config.ts"; @@ -93,6 +94,8 @@ import type { ResourceType, StateFile, } from "./types.ts"; +import { orgLimiter } from "./rate-limit.ts"; +import { limitedVapiFetch } from "./vapi-fetch.ts"; // ───────────────────────────────────────────────────────────────────────────── // Error Formatting @@ -351,7 +354,9 @@ async function upsertResourceWithStateRecovery(options: { const resourceType = RESOURCE_LABEL_TO_TYPE[resourceLabel]; if (resourceType) { if (platformPayloadForSnapshot === undefined) { - const platformResponse = await fetch( + const limiter = orgLimiter(BASE_DIR, VAPI_ENV, MAX_GITOPS_RPM); + const platformResponse = await limitedVapiFetch( + limiter, `${VAPI_BASE_URL}${updateEndpoint}`, { method: "GET", diff --git a/src/rate-limit.ts b/src/rate-limit.ts new file mode 100644 index 0000000..b823336 --- /dev/null +++ b/src/rate-limit.ts @@ -0,0 +1,124 @@ +import { existsSync, readFileSync } from "node:fs"; +import { join, resolve } from "node:path"; +import { orgEnvFilesRead, shellEnvironment } from "./env-file.ts"; + +export const DEFAULT_MAX_GITOPS_RPM = 100; + +export class InvalidMaxGitopsRpmError extends Error {} + +function positive(value: unknown, source: string): number { + const number = + typeof value === "number" + ? value + : typeof value === "string" && value.trim() + ? Number(value) + : NaN; + if (!Number.isInteger(number) || number <= 0) + throw new InvalidMaxGitopsRpmError( + `❌ Invalid max GitOps RPM in ${source}: expected a positive integer (a GitOps client limit, not a Vapi org limit).`, + ); + return number; +} + +export function maxGitopsRpmRead( + rootDir: string, + org: string, + env: NodeJS.ProcessEnv = shellEnvironment, +): number { + if (env.VAPI_MAX_GITOPS_RPM !== undefined) + return positive(env.VAPI_MAX_GITOPS_RPM, "environment VAPI_MAX_GITOPS_RPM"); + for (const { name, values } of orgEnvFilesRead(rootDir, org)) { + if (values.VAPI_MAX_GITOPS_RPM !== undefined) + return positive( + values.VAPI_MAX_GITOPS_RPM, + `${name} VAPI_MAX_GITOPS_RPM`, + ); + } + const pin = join(rootDir, "resources", org, ".vapi-org.json"); + let value = DEFAULT_MAX_GITOPS_RPM; + if (existsSync(pin)) { + let parsed; + try { + parsed = JSON.parse(readFileSync(pin, "utf8")); + } catch (error) { + const reason = error instanceof Error ? error.message : String(error); + throw new Error( + `Can't read resources/${org}/.vapi-org.json: ${reason}. Restore it from git.`, + ); + } + if (parsed && Object.hasOwn(parsed, "maxGitopsRpm")) + value = positive( + parsed.maxGitopsRpm, + `resources/${org}/.vapi-org.json maxGitopsRpm`, + ); + } + return value; +} + +export class TokenBucket { + private tokens: number; + readonly capacity: number; + private updated: number; + private queue = Promise.resolve(); + constructor( + readonly rpm: number, + private now = () => performance.now(), + private sleep = (ms: number) => + new Promise((resolve) => setTimeout(resolve, ms)), + readonly org = "unknown", + ) { + positive(rpm, "token bucket"); + this.capacity = Math.max(1, Math.min(20, Math.floor(rpm / 5))); + this.tokens = this.capacity; + this.updated = now(); + } + acquire(): Promise { + const next = this.queue.then(async () => { + for (;;) { + const now = this.now(); + this.tokens = Math.min( + this.capacity, + this.tokens + (Math.max(0, now - this.updated) * this.rpm) / 60_000, + ); + this.updated = now; + if (this.tokens + 1e-9 >= 1) { + this.tokens -= 1; + return; + } + await this.sleep(((1 - this.tokens) * 60_000) / this.rpm); + } + }); + this.queue = next.catch(() => {}); + return next; + } +} + +const buckets = new Map(); +export function orgLimiterOrExit(rootDir: string, org: string): TokenBucket { + try { + return orgLimiter(rootDir, org); + } catch (error) { + if (!(error instanceof InvalidMaxGitopsRpmError)) throw error; + console.error(error.message); + process.exit(1); + } +} + +export function orgLimiter( + rootDir: string, + org: string, + rpm?: number, +): TokenBucket { + const key = `${resolve(rootDir)}\0${org}`; + let limiter = buckets.get(key); + if (!limiter) { + limiter = new TokenBucket( + rpm ?? maxGitopsRpmRead(rootDir, org), + undefined, + undefined, + org, + ); + buckets.set(key, limiter); + } + return limiter; +} diff --git a/src/rollback-cmd.ts b/src/rollback-cmd.ts index 193c6f3..8c46524 100644 --- a/src/rollback-cmd.ts +++ b/src/rollback-cmd.ts @@ -13,8 +13,10 @@ import { existsSync, readFileSync } from "fs"; import { dirname, join } from "path"; import { fileURLToPath } from "url"; import { ORG_PIN_FILE, OrgPinMismatchError, orgPinCheck } from "./org-pin.ts"; +import { orgLimiterOrExit } from "./rate-limit.ts"; import { listSnapshotTimestamps, loadSnapshot } from "./snapshot.ts"; import { userAgentGet, vapiClientGet } from "./user-agent.ts"; +import { limitedVapiFetch } from "./vapi-fetch.ts"; const __dirname = dirname(fileURLToPath(import.meta.url)); const BASE_DIR = join(__dirname, ".."); @@ -147,7 +149,13 @@ async function main(): Promise { const outcome = await orgPinCheck({ rootDir: BASE_DIR, org: args.env, - connection: { token: cfg.token, baseUrl: cfg.baseUrl, userAgent: userAgentGet(), vapiClient: vapiClientGet() }, + connection: { + limiter: orgLimiterOrExit(BASE_DIR, cfg.env), + token: cfg.token, + baseUrl: cfg.baseUrl, + userAgent: userAgentGet(), + vapiClient: vapiClientGet(), + }, keySource: cfg.source, }); if (outcome.kind === "unverified") @@ -205,7 +213,9 @@ async function main(): Promise { process.stdout.write( ` 🔁 ${entry.resourceType}/${entry.resourceId} ... `, ); - const response = await fetch(`${cfg.baseUrl}${endpoint}/${uuid}`, { + const limiter = orgLimiterOrExit(BASE_DIR, cfg.env); + const url = `${cfg.baseUrl}${endpoint}/${uuid}`; + const response = await limitedVapiFetch(limiter, url, { method: "PATCH", headers: { Authorization: `Bearer ${cfg.token}`, diff --git a/src/setup.ts b/src/setup.ts index 0050ad1..10facee 100644 --- a/src/setup.ts +++ b/src/setup.ts @@ -12,6 +12,11 @@ import { resolveOrgApiKey, } from "./api-key.ts"; import { updateEnvConnection } from "./bindings.ts"; +import { + DEFAULT_MAX_GITOPS_RPM, + orgLimiterOrExit, + TokenBucket, +} from "./rate-limit.ts"; import { typeArgFor } from "./resource-type-args.ts"; import searchableCheckbox, { BACK_SENTINEL } from "./searchableCheckbox.js"; import { @@ -22,6 +27,7 @@ import { } from "./setup-args.ts"; import { slugify } from "./slug-utils.ts"; import { userAgentGet, vapiClientGet } from "./user-agent.ts"; +import { limitedVapiFetch } from "./vapi-fetch.ts"; // ───────────────────────────────────────────────────────────────────────────── // Constants @@ -33,6 +39,13 @@ const VAPI_REGIONS: Record = { us: "https://api.vapi.ai", eu: "https://api.eu.vapi.ai", }; +let requestOrg: string | undefined; +const validationLimiter = new TokenBucket( + DEFAULT_MAX_GITOPS_RPM, + undefined, + undefined, + "setup (folder not selected)", +); let vapiBaseUrl = VAPI_REGIONS.us!; const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; @@ -94,7 +107,10 @@ const c = { // ───────────────────────────────────────────────────────────────────────────── async function apiGet(token: string, endpoint: string): Promise { - const response = await fetch(`${vapiBaseUrl}${endpoint}`, { + const limiter = requestOrg + ? orgLimiterOrExit(BASE_DIR, requestOrg) + : validationLimiter; + const response = await limitedVapiFetch(limiter, `${vapiBaseUrl}${endpoint}`, { method: "GET", headers: { Authorization: `Bearer ${token}`, @@ -410,6 +426,8 @@ function fail(message: string): never { async function runDirectSetup(options: DirectSetupOptions): Promise { const { slug, region, resources } = options; + requestOrg = slug; + orgLimiterOrExit(BASE_DIR, slug); const envPath = join(BASE_DIR, `.env.${slug}`); const resourceDir = join(BASE_DIR, "resources", slug); const stateFile = join(BASE_DIR, `.vapi-state.${slug}.json`); @@ -668,6 +686,8 @@ async function main(): Promise { }); const slug = slugify(rawSlug); + requestOrg = slug; + orgLimiterOrExit(BASE_DIR, slug); // Check if org already exists locally const resourceDir = join(BASE_DIR, "resources", slug); diff --git a/src/sim.ts b/src/sim.ts index f376cd3..f085759 100644 --- a/src/sim.ts +++ b/src/sim.ts @@ -8,6 +8,7 @@ import { missingApiKeyMessage, resolveOrgApiKey } from "./api-key.ts"; import { existsSync, readFileSync } from "fs"; import { dirname, join } from "path"; import { fileURLToPath } from "url"; +import { orgLimiterOrExit } from "./rate-limit.ts"; import { simRunItemTerminal, simRunVerdict, @@ -237,6 +238,7 @@ const ITEM_PAGE_SIZE = 1000; function connectionFor(cfg: SimEnv): VapiConnection { return { + limiter: orgLimiterOrExit(BASE_DIR, cfg.env), token: cfg.token, baseUrl: cfg.baseUrl, userAgent: userAgentGet("sim"), @@ -346,7 +348,7 @@ export async function simRunExecute( "POST", "/eval/simulation/run", body, - { retry: "rate-limit-only" }, + { retry: "rate-limit-only", signal: options.signal }, ); const runId = created?.id; if (!runId) { diff --git a/src/vapi-client.ts b/src/vapi-client.ts index f1e76be..31c6a1b 100644 --- a/src/vapi-client.ts +++ b/src/vapi-client.ts @@ -6,7 +6,11 @@ // runner) uses this client instead. api.ts imports the error class and retry // policy from here, so both clients fail and retry the same way. +import type { TokenBucket } from "./rate-limit.ts"; +import { limitedVapiFetch } from "./vapi-fetch.ts"; + export interface VapiConnection { + limiter: TokenBucket; token: string; baseUrl: string; userAgent: string; @@ -20,6 +24,7 @@ export interface VapiConnection { export type VapiRetryPolicy = "transient" | "rate-limit-only" | "none"; export interface VapiFetchOptions { + signal?: AbortSignal; retry?: VapiRetryPolicy; maxRetries?: number; initialDelayMs?: number; @@ -83,8 +88,10 @@ export async function vapiFetchJson( const sleep = options.sleep ?? sleepDefault; for (let attempt = 0; ; attempt++) { - const response = await fetch(`${connection.baseUrl}${endpoint}`, { + const url = `${connection.baseUrl}${endpoint}`; + const response = await limitedVapiFetch(connection.limiter, url, { method, + signal: options.signal, headers: { Authorization: `Bearer ${connection.token}`, "Content-Type": "application/json", diff --git a/src/vapi-fetch.ts b/src/vapi-fetch.ts new file mode 100644 index 0000000..4389112 --- /dev/null +++ b/src/vapi-fetch.ts @@ -0,0 +1,34 @@ +import type { TokenBucket } from "./rate-limit.ts"; +import { userAgentGet, vapiClientGet } from "./user-agent.ts"; + +export function orgSettingsUrl(baseUrl: string): string { + return new URL(baseUrl).hostname === "api.eu.vapi.ai" + ? "https://dashboard.eu.vapi.ai/settings/organization" + : "https://dashboard.vapi.ai/settings/organization"; +} + +const warned = new WeakSet(); + +export async function limitedVapiFetch( + limiter: TokenBucket, + url: string, + init: RequestInit = {}, +): Promise { + await limiter.acquire(); + init.signal?.throwIfAborted(); + const headers = new Headers(init.headers); + if (!headers.has("User-Agent")) headers.set("User-Agent", userAgentGet()); + if (!headers.has("x-vapi-client")) + headers.set("x-vapi-client", vapiClientGet()); + const response = await fetch(url, { + ...init, + headers, + }); + if (response.status === 429 && !warned.has(limiter)) { + warned.add(limiter); + console.warn( + `⚠️ Vapi returned 429 (rate limited) for org ${limiter.org}. maxGitopsRpm is ${limiter.rpm} requests per minute, which may be higher than your org's API rate limit (200 RPM by default). Check it at ${orgSettingsUrl(url)}, then lower maxGitopsRpm in resources/${limiter.org}/.vapi-org.json or set VAPI_MAX_GITOPS_RPM. This is a GitOps client limit, not a Vapi org limit.`, + ); + } + return response; +} diff --git a/tests/api-write-pacing.test.ts b/tests/api-write-pacing.test.ts new file mode 100644 index 0000000..8c8b4a4 --- /dev/null +++ b/tests/api-write-pacing.test.ts @@ -0,0 +1,49 @@ +import assert from "node:assert/strict"; +import { createServer } from "node:http"; +import type { AddressInfo } from "node:net"; +import test from "node:test"; + +test("API writes use the limiter burst and sustained rate without another gap", async () => { + const seen: Array<{ method: string; time: number }> = []; + const server = createServer((req, res) => { + seen.push({ method: req.method!, time: performance.now() }); + if (req.method === "DELETE") { + res.writeHead(204); + res.end(); + } else { + res.writeHead(200, { "Content-Type": "application/json" }); + res.end('{"id":"stub-resource"}'); + } + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const { port } = server.address() as AddressInfo; + process.argv = ["node", "src/push.ts", "write-pacing-test"]; + process.env.VAPI_TOKEN = "test-token-not-used"; + process.env.VAPI_BASE_URL = `http://127.0.0.1:${port}`; + process.env.VAPI_MAX_GITOPS_RPM = "300"; + try { + const { vapiRequest, vapiDelete } = await import("../src/api.ts"); + for (let i = 0; i < 23; i++) { + if (i % 3 === 2) await vapiDelete("/assistant/stub-resource"); + else await vapiRequest(i % 3 === 0 ? "POST" : "PATCH", "/assistant", {}); + } + assert.deepEqual( + seen.map(({ method }) => method), + Array.from({ length: 23 }, (_, i) => ["POST", "PATCH", "DELETE"][i % 3]), + ); + assert.ok( + seen[2]!.time - seen[0]!.time < 1000, + "writes within the limiter burst must not wait for a second pacing policy", + ); + assert.ok( + seen[22]!.time - seen[0]!.time >= 500, + "writes beyond the twenty-token burst must wait for the limiter", + ); + assert.ok( + seen[22]!.time - seen[21]!.time >= 140, + "sustained writes must be spaced by the configured refill rate", + ); + } finally { + await new Promise((resolve) => server.close(() => resolve())); + } +}); diff --git a/tests/check-run.test.ts b/tests/check-run.test.ts index 0186d57..0b3dde2 100644 --- a/tests/check-run.test.ts +++ b/tests/check-run.test.ts @@ -2,6 +2,7 @@ import assert from "node:assert/strict"; import { createServer } from "node:http"; import type { AddressInfo } from "node:net"; import test from "node:test"; +import { TokenBucket } from "../src/rate-limit.ts"; import type { CheckJob } from "../src/check-build.ts"; import { checksConfigParse } from "../src/check-config.ts"; import { MOCK_MARKER } from "../src/check-mocks.ts"; @@ -229,6 +230,7 @@ function runArgs( token: "t", baseUrl: stub.baseUrl, userAgent: "vapi-gitops-check/test", + limiter: new TokenBucket(100), vapiClient: "gitops/test; command=check", }), deadline: DEADLINE_FAR(), @@ -337,6 +339,51 @@ test("an abort (SIGINT/SIGTERM) cancels in-flight runs and doesn't start new one }); }); +test("a create aborted in the one-RPM limiter queue never sends a POST", async () => { + await withStub(async (stub) => { + let now = 0; + let entered!: () => void; + let release!: () => void; + const waiting = new Promise((resolve) => { + entered = resolve; + }); + const gate = new Promise((resolve) => { + release = resolve; + }); + const limiter = new TokenBucket( + 1, + () => now, + async (ms) => { + entered(); + await gate; + now += ms; + }, + ); + await limiter.acquire(); + const controller = new AbortController(); + const pending = checkRunAll( + runArgs(stub, [job("pass")], { + signal: controller.signal, + connectionFor: () => ({ + token: "unused", + baseUrl: stub.baseUrl, + userAgent: "test", + vapiClient: "test", + limiter, + }), + }), + ); + await waiting; + controller.abort(); + release(); + const [result] = await pending; + assert.equal(result!.outcome, "incomplete"); + assert.equal(result!.reason, "not started: interrupted"); + assert.deepEqual(stub.requests, []); + assert.equal(now, 60000); + }); +}); + test("runs that can't fit in the remaining budget aren't started", async () => { await withStub(async (stub) => { const [result] = await checkRunAll( diff --git a/tests/config-api-key.test.ts b/tests/config-api-key.test.ts index 05d5368..13e94ba 100644 --- a/tests/config-api-key.test.ts +++ b/tests/config-api-key.test.ts @@ -4,6 +4,7 @@ import { cpSync, mkdirSync, mkdtempSync, + readFileSync, rmSync, symlinkSync, writeFileSync, @@ -69,3 +70,51 @@ test("a key only in .env. is used quietly", () => { assert.doesNotMatch(`${run.stdout}${run.stderr}`, /Using the API key|different key/); assert.equal(run.code, 0); }); + +test("existing example-style env files preserve API keys and base URLs", () => { + const dir = mkdtempSync(join(tmpdir(), "vapi-env-compat-")); + try { + cpSync(join(REPO, "src"), join(dir, "src"), { recursive: true }); + cpSync(join(REPO, "package.json"), join(dir, "package.json")); + symlinkSync(join(REPO, "node_modules"), join(dir, "node_modules"), "dir"); + const env = { ...process.env }; + for (const name of [ + "VAPI_PRIVATE_API_KEY", + "VAPI_PRIVATE_API_KEY_ACME_PROD", + "VAPI_TOKEN", + "VAPI_BASE_URL", + "VAPI_MAX_GITOPS_RPM", + ]) + delete env[name]; + const example = readFileSync(join(REPO, ".env.example"), "utf8"); + for (const quote of ["", "'", '"']) { + writeFileSync( + join(dir, ".env.acme-prod"), + example + .replace( + "your-vapi-private-key-here", + `${quote}fixture-private-key${quote}`, + ) + .replace( + "# VAPI_BASE_URL=https://api.eu.vapi.ai", + `VAPI_BASE_URL=${quote}https://api.eu.vapi.ai${quote}`, + ), + ); + const result = spawnSync( + process.execPath, + [ + "--import", + "tsx", + "--input-type=module", + "-e", + 'process.argv = ["node", "config-test", "acme-prod"]; const config = await import("./src/config.ts"); const assert = await import("node:assert/strict"); assert.equal(config.VAPI_TOKEN, "fixture-private-key"); assert.equal(config.VAPI_BASE_URL, "https://api.eu.vapi.ai"); console.log("config values match");', + ], + { cwd: dir, encoding: "utf8", env, timeout: 30000 }, + ); + assert.equal(result.status, 0, result.stderr); + assert.match(result.stdout, /config values match/); + } + } finally { + rmSync(dir, { recursive: true, force: true }); + } +}); diff --git a/tests/env-file.test.ts b/tests/env-file.test.ts new file mode 100644 index 0000000..c038852 --- /dev/null +++ b/tests/env-file.test.ts @@ -0,0 +1,32 @@ +import assert from "node:assert/strict"; +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import test from "node:test"; +import { orgEnvFilesRead } from "../src/env-file.ts"; + +test("shared env parser supports comments, exports, quoted lines and duplicate assignments", () => { + const root = mkdtempSync(join(tmpdir(), "env-parser-")); + try { + for (const [input, expected] of [ + ["KEY=value # note", "value"], + ["KEY=value#fragment", "value"], + ['KEY="value" # note', "value"], + ["export KEY=value", "value"], + ['KEY="line1\\nline2"', "line1\nline2"], + ['KEY="line1\nline2"', "line1\nline2"], + ["KEY=`value`", "value"], + ["KEY=first\nKEY=last", "last"], + ["KEY='value#fragment'", "value#fragment"], + ]) { + writeFileSync(join(root, ".env.acme"), input!); + assert.equal( + orgEnvFilesRead(root, "acme")[0]!.values.KEY, + expected, + input, + ); + } + } finally { + rmSync(root, { recursive: true, force: true }); + } +}); diff --git a/tests/org-pin.test.ts b/tests/org-pin.test.ts index c58ec41..3f364e8 100644 --- a/tests/org-pin.test.ts +++ b/tests/org-pin.test.ts @@ -24,6 +24,7 @@ import { orgPinCheck, orgPinRead, } from "../src/org-pin.ts"; +import { TokenBucket } from "../src/rate-limit.ts"; import { VapiApiError } from "../src/vapi-client.ts"; // Nothing used to tie resources// to a Vapi org, so a key for the wrong @@ -34,7 +35,13 @@ import { VapiApiError } from "../src/vapi-client.ts"; delete process.env.VAPI_GITOPS_ORG_PIN; const REPO = fileURLToPath(new URL("..", import.meta.url)); -const CONNECTION = { token: "test-token-not-used", baseUrl: "http://stub", userAgent: "test", vapiClient: "test" }; +const CONNECTION = { + token: "test-token-not-used", + baseUrl: "http://stub", + userAgent: "test", + limiter: new TokenBucket(100), + vapiClient: "test", +}; const SOURCE = "the VAPI_PRIVATE_API_KEY_ACME environment variable"; // A probe stub: endpoint (without the query) → response or error. diff --git a/tests/rate-limit.test.ts b/tests/rate-limit.test.ts new file mode 100644 index 0000000..c6e403b --- /dev/null +++ b/tests/rate-limit.test.ts @@ -0,0 +1,380 @@ +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + writeFileSync, +} from "node:fs"; +import { createServer } from "node:http"; +import type { AddressInfo } from "node:net"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import test from "node:test"; +import { fileURLToPath } from "node:url"; +import { orgPinCheck } from "../src/org-pin.ts"; +import { + maxGitopsRpmRead, + orgLimiter, + TokenBucket, +} from "../src/rate-limit.ts"; +import { vapiFetchJson } from "../src/vapi-client.ts"; +import { orgSettingsUrl } from "../src/vapi-fetch.ts"; + +test("token bucket allows a burst, then sustains the configured rate", async () => { + let now = 0; + const waits: number[] = []; + const limiter = new TokenBucket( + 300, + () => now, + async (ms) => { + waits.push(ms); + now += ms; + }, + ); + assert.equal(limiter.capacity, 20); + await Promise.all(Array.from({ length: 25 }, () => limiter.acquire())); + assert.deepEqual(waits, [200, 200, 200, 200, 200]); + now += 10_000; + await Promise.all(Array.from({ length: 5 }, () => limiter.acquire())); + assert.equal(waits.length, 5); +}); + +test("low RPM and concurrent requests sustain the cap", async () => { + let now = 0; + const limiter = new TokenBucket( + 1, + () => now, + async (ms) => { + now += ms; + }, + ); + assert.equal(limiter.capacity, 1); + await Promise.all(Array.from({ length: 3 }, () => limiter.acquire())); + assert.equal(now, 120000); + assert.throws(() => new TokenBucket(Infinity), /positive integer/); + assert.throws(() => new TokenBucket(1.5), /positive integer/); +}); + +test("default RPM has only a small burst across a minute", async () => { + let now = 0; + const limiter = new TokenBucket( + 100, + () => now, + async (ms) => { + now += ms; + }, + ); + assert.equal(limiter.capacity, 20); + await Promise.all(Array.from({ length: 120 }, () => limiter.acquire())); + assert.equal(now, 60_000); +}); + +test("process registry shares an org but isolates other orgs", async () => { + const a = orgLimiter("/registry-test", "a", 5); + assert.equal(orgLimiter("/registry-test", "a", 5), a); + const b = orgLimiter("/registry-test", "b", 5); + assert.notEqual(a, b); + await Promise.all([a.acquire(), b.acquire()]); +}); + +test("org limiter cache does not re-read changed configuration", () => { + const root = mkdtempSync(join(tmpdir(), "rpm-cache-")); + const folder = join(root, "resources", "acme"); + mkdirSync(folder, { recursive: true }); + const pin = join(folder, ".vapi-org.json"); + try { + writeFileSync(pin, '{"maxGitopsRpm":75}'); + const first = orgLimiter(root, "acme"); + writeFileSync(pin, "{"); + writeFileSync(join(root, ".env.acme"), "VAPI_MAX_GITOPS_RPM=invalid"); + assert.equal(orgLimiter(root, "acme"), first); + assert.equal(first.rpm, 75); + } finally { + rmSync(root, { recursive: true, force: true }); + } +}); + +test("only the winning RPM source is validated", () => { + const root = mkdtempSync(join(tmpdir(), "rpm-winner-")); + const folder = join(root, "resources", "acme"); + mkdirSync(folder, { recursive: true }); + try { + writeFileSync(join(folder, ".vapi-org.json"), '{"maxGitopsRpm":0}'); + writeFileSync(join(root, ".env.acme"), "VAPI_MAX_GITOPS_RPM=90"); + writeFileSync(join(root, ".env.acme.local"), "VAPI_MAX_GITOPS_RPM=invalid"); + assert.equal(maxGitopsRpmRead(root, "acme", {}), 90); + writeFileSync(join(root, ".env.acme"), "VAPI_MAX_GITOPS_RPM=invalid"); + assert.equal( + maxGitopsRpmRead(root, "acme", { VAPI_MAX_GITOPS_RPM: "80" }), + 80, + ); + assert.throws( + () => maxGitopsRpmRead(root, "acme", {}), + /\.env.acme VAPI_MAX_GITOPS_RPM/, + ); + } finally { + rmSync(root, { recursive: true, force: true }); + } +}); + +test("burst capacity is floored, bounded below by one and capped at twenty", () => { + for (const [rpm, capacity] of [ + [1, 1], + [9, 1], + [10, 2], + [99, 19], + [100, 20], + [1000, 20], + ]) { + assert.equal(new TokenBucket(rpm!).capacity, capacity); + } +}); + +test("max GitOps RPM resolves defaults, committed settings and environment precedence", () => { + const root = mkdtempSync(join(tmpdir(), "rpm-config-")); + const folder = join(root, "resources", "acme"); + mkdirSync(folder, { recursive: true }); + const pin = join(folder, ".vapi-org.json"); + try { + assert.equal(maxGitopsRpmRead(root, "acme", {}), 100); + writeFileSync(pin, JSON.stringify({ maxGitopsRpm: 12 })); + assert.equal(maxGitopsRpmRead(root, "acme", {}), 12); + writeFileSync(join(root, ".env.acme"), "VAPI_MAX_GITOPS_RPM='8'\n"); + assert.equal(maxGitopsRpmRead(root, "acme", {}), 8); + assert.equal( + maxGitopsRpmRead(root, "acme", { VAPI_MAX_GITOPS_RPM: "5" }), + 5, + ); + for (const value of [0, -1, 1.5, "bad", "", null, true, "Infinity"]) { + writeFileSync(pin, JSON.stringify({ maxGitopsRpm: value })); + assert.equal( + maxGitopsRpmRead(root, "acme", { VAPI_MAX_GITOPS_RPM: "5" }), + 5, + ); + rmSync(join(root, ".env.acme")); + assert.throws( + () => maxGitopsRpmRead(root, "acme", {}), + /❌.*resources\/acme\/\.vapi-org.json/, + ); + writeFileSync(join(root, ".env.acme"), "VAPI_MAX_GITOPS_RPM=8\n"); + } + writeFileSync(pin, "{}"); + for (const value of ["0", "-1", "1.5", "bad", "", "Infinity"]) { + writeFileSync(join(root, ".env.acme"), "VAPI_MAX_GITOPS_RPM=8\n"); + assert.throws( + () => maxGitopsRpmRead(root, "acme", { VAPI_MAX_GITOPS_RPM: value }), + /❌.*environment VAPI_MAX_GITOPS_RPM/, + ); + writeFileSync(join(root, ".env.acme"), `VAPI_MAX_GITOPS_RPM=${value}\n`); + assert.throws(() => maxGitopsRpmRead(root, "acme", {}), /❌.*\.env.acme/); + } + rmSync(join(root, ".env.acme")); + writeFileSync(pin, "{"); + assert.throws( + () => maxGitopsRpmRead(root, "acme", {}), + /Restore it from git/, + ); + } finally { + rmSync(root, { recursive: true, force: true }); + } +}); + +test("pinning a settings-only file preserves all existing fields", async () => { + const root = mkdtempSync(join(tmpdir(), "rpm-pin-")); + const folder = join(root, "resources", "acme"); + mkdirSync(folder, { recursive: true }); + const path = join(folder, ".vapi-org.json"); + writeFileSync( + path, + JSON.stringify({ maxGitopsRpm: 5, extra: { keep: true } }), + ); + const prior = process.env.VAPI_GITOPS_ORG_PIN; + delete process.env.VAPI_GITOPS_ORG_PIN; + try { + const outcome = await orgPinCheck({ + rootDir: root, + org: "acme", + keySource: "test", + connection: { + token: "unused", + baseUrl: "http://stub", + userAgent: "test", + limiter: new TokenBucket(100), + vapiClient: "test", + }, + probeFetch: async () => [{ orgId: "org-acme" }], + }); + assert.equal(outcome.kind, "pinned"); + assert.deepEqual(JSON.parse(readFileSync(path, "utf8")), { + maxGitopsRpm: 5, + extra: { keep: true }, + orgId: "org-acme", + }); + } finally { + if (prior === undefined) delete process.env.VAPI_GITOPS_ORG_PIN; + else process.env.VAPI_GITOPS_ORG_PIN = prior; + rmSync(root, { recursive: true, force: true }); + } +}); + +test("429 advice selects only the matching region dashboard", () => { + assert.equal( + orgSettingsUrl("https://api.eu.vapi.ai/assistant"), + "https://dashboard.eu.vapi.ai/settings/organization", + ); + assert.equal( + orgSettingsUrl("https://api.vapi.ai/assistant"), + "https://dashboard.vapi.ai/settings/organization", + ); + assert.equal( + orgSettingsUrl("http://localhost:123"), + "https://dashboard.vapi.ai/settings/organization", + ); +}); + +test("429 responses warn once per org and retries consume tokens", async () => { + let requests = 0; + let tokens = 0; + const warnings: string[] = []; + const server = createServer((_req, res) => { + requests++; + res.writeHead(requests % 2 ? 429 : 200, { + "Content-Type": "application/json", + }); + res.end("{}"); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const { port } = server.address() as AddressInfo; + const limiter = new TokenBucket(2, undefined, undefined, "acme"); + limiter.acquire = async () => { + tokens++; + }; + const warn = console.warn; + console.warn = (message: string) => { + warnings.push(message); + }; + try { + const connection = { + token: "unused", + baseUrl: `http://127.0.0.1:${port}`, + userAgent: "test", + vapiClient: "test", + limiter, + }; + for (let i = 0; i < 2; i++) + await vapiFetchJson(connection, "GET", "/assistant", undefined, { + sleep: async () => {}, + }); + assert.equal(requests, 4); + assert.equal(tokens, 4); + assert.equal(warnings.length, 1); + assert.match( + warnings[0]!, + /Vapi returned 429 \(rate limited\) for org acme\. maxGitopsRpm is 2 requests per minute/, + ); + assert.match(warnings[0]!, /200 RPM by default/); + assert.match( + warnings[0]!, + /https:\/\/dashboard.vapi.ai\/settings\/organization/, + ); + assert.match( + warnings[0]!, + /resources\/acme\/\.vapi-org.json or set VAPI_MAX_GITOPS_RPM/, + ); + } finally { + console.warn = warn; + await new Promise((resolve) => server.close(() => resolve())); + } +}); + +test("invalid RPM exits a command cleanly before any request", () => { + const root = fileURLToPath(new URL("..", import.meta.url)); + for (const script of ["src/pull-cmd.ts", "src/setup.ts"]) { + const result = spawnSync( + process.execPath, + ["--import", "tsx", script, "invalid-rpm-test"], + { + cwd: root, + env: { + ...process.env, + VAPI_MAX_GITOPS_RPM: "invalid", + VAPI_PRIVATE_API_KEY: "unused", + }, + encoding: "utf8", + }, + ); + assert.equal(result.status, 1, result.stderr); + assert.match( + result.stderr, + /❌ Invalid max GitOps RPM in environment VAPI_MAX_GITOPS_RPM/, + ); + assert.doesNotMatch(result.stderr, /\n\s+at |Error:|node:internal/); + } +}); + +test("invalid committed RPM exits config-free callers without a stack", () => { + const root = mkdtempSync(join(tmpdir(), "rpm-exit-")); + mkdirSync(join(root, "resources", "acme"), { recursive: true }); + writeFileSync( + join(root, "resources", "acme", ".vapi-org.json"), + JSON.stringify({ maxGitopsRpm: 0 }), + ); + try { + const module = new URL("../src/rate-limit.ts", import.meta.url).href; + const result = spawnSync( + process.execPath, + [ + "--import", + "tsx", + "--input-type=module", + "-e", + `import { orgLimiterOrExit } from ${JSON.stringify(module)}; orgLimiterOrExit(${JSON.stringify(root)}, "acme");`, + ], + { + cwd: fileURLToPath(new URL("..", import.meta.url)), + encoding: "utf8", + }, + ); + assert.equal(result.status, 1, result.stderr); + assert.match( + result.stderr, + /❌ Invalid max GitOps RPM in resources\/acme\/\.vapi-org.json/, + ); + assert.doesNotMatch(result.stderr, /\n\s+at |Error:|node:internal/); + } finally { + rmSync(root, { recursive: true, force: true }); + } +}); + +test("shared env parsing handles exports, comments and org file precedence", () => { + const root = mkdtempSync(join(tmpdir(), "rpm-env-")); + try { + writeFileSync( + join(root, ".env.acme"), + 'export VAPI_MAX_GITOPS_RPM = "90" # client ceiling\n', + ); + writeFileSync( + join(root, ".env.acme.local"), + "VAPI_MAX_GITOPS_RPM=80 # fallback\n", + ); + writeFileSync(join(root, ".env.local"), "VAPI_MAX_GITOPS_RPM=70\n"); + assert.equal(maxGitopsRpmRead(root, "acme", {}), 90); + assert.equal(maxGitopsRpmRead(root, "other", {}), 70); + assert.equal( + maxGitopsRpmRead(root, "acme", { VAPI_MAX_GITOPS_RPM: "60" }), + 60, + ); + writeFileSync( + join(root, ".env.acme"), + "export VAPI_MAX_GITOPS_RPM=invalid # ignored when overridden\n", + ); + assert.equal( + maxGitopsRpmRead(root, "acme", { VAPI_MAX_GITOPS_RPM: "60" }), + 60, + ); + } finally { + rmSync(root, { recursive: true, force: true }); + } +}); diff --git a/tests/sim-run.test.ts b/tests/sim-run.test.ts index 71c858e..1d1faba 100644 --- a/tests/sim-run.test.ts +++ b/tests/sim-run.test.ts @@ -2,6 +2,7 @@ import assert from "node:assert/strict"; import { createServer, type IncomingMessage } from "node:http"; import type { AddressInfo } from "node:net"; import test from "node:test"; +import { TokenBucket } from "../src/rate-limit.ts"; import { runSimulation, simRunItemsFetch } from "../src/sim.ts"; // runSimulation against a local stub of the simulations API. Each stub @@ -359,7 +360,13 @@ test("simRunItemsFetch: pages until totalItems and dedupes overlapping pages", a ], async (baseUrl) => { const items = await simRunItemsFetch( - { token: "t", baseUrl, userAgent: "test", vapiClient: "test" }, + { + token: "t", + baseUrl, + userAgent: "test", + limiter: new TokenBucket(100), + vapiClient: "test", + }, "run-1", ); assert.equal(items.length, 1002); diff --git a/tests/user-agent-coverage.test.ts b/tests/user-agent-coverage.test.ts index 72ea69d..4d6917f 100644 --- a/tests/user-agent-coverage.test.ts +++ b/tests/user-agent-coverage.test.ts @@ -26,7 +26,10 @@ test("every fetch in src/ sets the User-Agent", () => { .split(/\bfetch\(/) .slice(1) .forEach((rest, i) => { - const call = rest.slice(0, rest.indexOf(");") + 2); + const call = + file === "vapi-fetch.ts" + ? readFileSync(join(SRC, file), "utf8") + : rest.slice(0, rest.indexOf(");") + 2); if (!call.includes('"User-Agent"')) missing.push(`${file} (fetch #${i + 1})`); }); @@ -44,7 +47,10 @@ test("every Vapi fetch in src/ sets x-vapi-client", () => { .split(/\bfetch\(/) .slice(1) .forEach((rest, i) => { - const call = rest.slice(0, rest.indexOf(");") + 2); + const call = + file === "vapi-fetch.ts" + ? readFileSync(join(SRC, file), "utf8") + : rest.slice(0, rest.indexOf(");") + 2); const github = call.includes('"X-GitHub-Api-Version"'); if (!github && !call.includes('"x-vapi-client"')) missing.push(`${file} (fetch #${i + 1})`); @@ -55,9 +61,11 @@ test("every Vapi fetch in src/ sets x-vapi-client", () => { test("api.ts requests carry the command's User-Agent", async () => { const seen: Array = []; + const times: number[] = []; const seenClient: Array = []; const server = createServer((req, res) => { seen.push(req.headers["user-agent"]); + times.push(performance.now()); seenClient.push(req.headers["x-vapi-client"]); res.writeHead(200, { "Content-Type": "application/json" }); res.end("[]"); @@ -68,6 +76,7 @@ test("api.ts requests carry the command's User-Agent", async () => { process.argv = ["node", "src/push.ts", "ua-test-org"]; process.env.VAPI_TOKEN = "test-token-not-used"; process.env.VAPI_BASE_URL = `http://127.0.0.1:${port}`; + process.env.VAPI_MAX_GITOPS_RPM = "300"; process.env.npm_lifecycle_event = "apply"; delete process.env.VAPI_GITOPS_COMMAND; delete process.env.CI; @@ -83,7 +92,34 @@ test("api.ts requests carry the command's User-Agent", async () => { String(seenClient[0]), /^gitops\/[^;]+; command=apply; run=[0-9a-f-]{36}$/, ); + await Promise.all(Array.from({ length: 24 }, () => vapiGet("/assistant"))); + assert.equal(times.length, 25); + assert.ok( + times[24]! - times[0]! >= 850, + "requests beyond the initial burst must wait for tokens", + ); + assert.ok( + times[24]! - times[23]! >= 140, + "sustained requests must be spaced by the cap", + ); } finally { await new Promise((resolve) => server.close(() => resolve())); } }); + +test("every Vapi fetch uses the shared limiter and warning path", () => { + const files = readdirSync(SRC, { recursive: true, encoding: "utf8" }); + for (const file of files.filter((f) => f.endsWith(".ts"))) { + const source = readFileSync(join(SRC, file), "utf8"); + if (/\bfetch\s*\(/.test(source)) + assert.ok( + ["vapi-fetch.ts", "check-status.ts"].includes(file), + `${file} must use limitedVapiFetch`, + ); + } + const shared = readFileSync(join(SRC, "vapi-fetch.ts"), "utf8"); + assert.match(shared, /await limiter\.acquire\(\)/); + assert.ok( + shared.indexOf("await limiter.acquire()") < shared.indexOf("await fetch("), + ); +}); diff --git a/tests/vapi-fetch.test.ts b/tests/vapi-fetch.test.ts new file mode 100644 index 0000000..4d13b4d --- /dev/null +++ b/tests/vapi-fetch.test.ts @@ -0,0 +1,63 @@ +import assert from "node:assert/strict"; +import { createServer } from "node:http"; +import type { AddressInfo } from "node:net"; +import test from "node:test"; +import { TokenBucket } from "../src/rate-limit.ts"; +import { limitedVapiFetch } from "../src/vapi-fetch.ts"; +import { userAgentGet, vapiClientGet } from "../src/user-agent.ts"; + +test("Headers objects and header arrays preserve authorization and caller client headers", async () => { + const seen: Array> = []; + const server = createServer((req, res) => { + seen.push(req.headers); + res.end("{}"); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const { port } = server.address() as AddressInfo; + try { + for (const headers of [ + new Headers({ Authorization: "Bearer object" }), + [["Authorization", "Bearer array"]], + new Headers({ + Authorization: "Bearer custom", + "User-Agent": "caller-agent", + "x-vapi-client": "caller-client", + }), + [ + ["Authorization", "Bearer custom-array"], + ["User-Agent", "array-agent"], + ["x-vapi-client", "array-client"], + ], + ] as Array>) { + const response = await limitedVapiFetch( + new TokenBucket(100), + `http://127.0.0.1:${port}`, + { headers }, + ); + await response.text(); + } + assert.deepEqual( + seen.map((headers) => headers.authorization), + ["Bearer object", "Bearer array", "Bearer custom", "Bearer custom-array"], + ); + assert.deepEqual( + seen.map((headers) => headers["user-agent"]), + [userAgentGet(), userAgentGet(), "caller-agent", "array-agent"], + ); + assert.deepEqual( + seen.map((headers) => headers["x-vapi-client"]), + [vapiClientGet(), vapiClientGet(), "caller-client", "array-client"], + ); + } finally { + await new Promise((resolve) => server.close(() => resolve())); + } +}); + +test("an already aborted request never reaches fetch", async () => { + await assert.rejects( + limitedVapiFetch(new TokenBucket(100), "http://127.0.0.1:1", { + signal: AbortSignal.abort(), + }), + { name: "AbortError" }, + ); +});