From 42805227d51ede7f549591994d62d16b2ea19ff8 Mon Sep 17 00:00:00 2001 From: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Tue, 17 Nov 2026 09:11:36 +0000 Subject: [PATCH 1/5] feat: cap per-org GitOps requests with configurable RPM Co-Authored-By: Roshan Manjaly --- .env.example | 5 ++ README.md | 4 + docs/guides/commands.md | 6 ++ docs/guides/configuration.md | 40 ++++++++- docs/guides/troubleshooting.md | 14 ++++ improvements.md | 9 ++ src/api.ts | 10 ++- src/call.ts | 4 +- src/check-cmd.ts | 7 +- src/cleanup.ts | 8 +- src/config.ts | 5 +- src/interactive.ts | 7 +- src/org-pin.ts | 6 +- src/promotion-gate.ts | 2 + src/push.ts | 5 +- src/rate-limit.ts | 81 ++++++++++++++++++ src/rollback-cmd.ts | 6 +- src/setup.ts | 43 +++++----- src/sim.ts | 2 + src/vapi-client.ts | 5 +- src/vapi-fetch.ts | 33 ++++++++ tests/check-run.test.ts | 3 +- tests/org-pin.test.ts | 3 +- tests/rate-limit.test.ts | 135 ++++++++++++++++++++++++++++++ tests/sim-run.test.ts | 3 +- tests/user-agent-coverage.test.ts | 19 +++++ 26 files changed, 422 insertions(+), 43 deletions(-) create mode 100644 src/rate-limit.ts create mode 100644 src/vapi-fetch.ts create mode 100644 tests/rate-limit.test.ts 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..0470b93 100644 --- a/README.md +++ b/README.md @@ -203,6 +203,10 @@ 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. + | Command | What it does | | --- | --- | | `npm run setup` | Connect an org: create `.env.` and `resources//` | diff --git a/docs/guides/commands.md b/docs/guides/commands.md index 299b12f..0696654 100644 --- a/docs/guides/commands.md +++ b/docs/guides/commands.md @@ -7,6 +7,12 @@ 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 asks for the org folder before +validating the key so its client ceiling applies to validation too. + | 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..0bbc8ac 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 max GitOps RPM for this org: a positive integer. This is a GitOps client limit, not a Vapi org limit; defaults to `maxGitopsRpm` in the committed org settings file, or 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` | Optional `maxGitopsRpm` (default 100) and 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-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,40 @@ 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 + +Set the committed client-side ceiling per org in +`resources//.vapi-org.json`: + +```json +{ "orgId": "your-org-id", "maxGitopsRpm": 100 } +``` + +A file containing only `maxGitopsRpm` is also valid before the org is pinned; +pinning preserves this setting and any other existing fields. This is a +**GitOps client limit, not a Vapi org limit**. The Vapi org API limit is +per minute (200 requests per minute by default). Keep max GitOps RPM below +your org's API limit; the default is 100 RPM. Allow additional headroom +for other clients and processes. +All Vapi requests for an org +share a token bucket in a process, including probes, reads, writes and retries. +The bucket refills at `maxGitopsRpm / 60` tokens per second, with burst +capacity `max(1, ceil(maxGitopsRpm / 60))`. It starts full, so a short burst +can exceed the average rate slightly; it does not reserve the whole org quota. +Separate orgs have separate buckets; separate +processes do not coordinate. Existing write gaps and retry backoff still apply. + +Resolution: shell/CI `VAPI_MAX_GITOPS_RPM`, then `.env.` (with the +usual fallback env files), then committed `maxGitopsRpm`, then 100. +Values must be positive integers. An invalid configured value stops the +command before requests, naming its source even when another setting overrides +it. No API keys are printed. + +On a 429, GitOps warns once per org per process that max GitOps RPM +(`maxGitopsRpm` / `VAPI_MAX_GITOPS_RPM`) may be too high. It links to the +org-level API rate limit in the dashboard matching that org's API base URL: +[EU](https://dashboard.eu.vapi.ai/settings/organization) for +`api.eu.vapi.ai`, otherwise +[US](https://dashboard.vapi.ai/settings/organization). +Lower the client ceiling if necessary; retries retain their existing backoff. 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..f28f7c5 100644 --- a/improvements.md +++ b/improvements.md @@ -2076,3 +2076,12 @@ 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 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 backoff and write gaps retained. This is a GitOps client limit, not a Vapi org limit. diff --git a/src/api.ts b/src/api.ts index 6ea7e20..9125bd5 100644 --- a/src/api.ts +++ b/src/api.ts @@ -1,4 +1,7 @@ +import { limitedVapiFetch } from "./vapi-fetch.ts"; +import { orgLimiter } from "./rate-limit.ts"; import { + MAX_GITOPS_RPM, BASE_DIR, DRY_RUN, VAPI_BASE_URL, @@ -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(), @@ -147,7 +151,7 @@ export async function vapiRequest( for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) { await throttle(); - const response = await fetch(url, { + const response = await limitedVapiFetch(orgLimiter(BASE_DIR, VAPI_ENV, MAX_GITOPS_RPM), url, { method, headers: { "Content-Type": "application/json", @@ -193,7 +197,7 @@ 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 response = await limitedVapiFetch(orgLimiter(BASE_DIR, VAPI_ENV, MAX_GITOPS_RPM), url, { method: "GET", headers: { Authorization: `Bearer ${VAPI_TOKEN}`, @@ -244,7 +248,7 @@ export async function vapiDelete(endpoint: string): Promise { for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) { await throttle(); - const response = await fetch(url, { + const response = await limitedVapiFetch(orgLimiter(BASE_DIR, VAPI_ENV, MAX_GITOPS_RPM), url, { method: "DELETE", headers: { Authorization: `Bearer ${VAPI_TOKEN}`, diff --git a/src/call.ts b/src/call.ts index 21304cb..ba552a4 100644 --- a/src/call.ts +++ b/src/call.ts @@ -1,3 +1,5 @@ +import { limitedVapiFetch } from "./vapi-fetch.ts"; +import { orgLimiter } from "./rate-limit.ts"; import { missingApiKeyMessage, resolveOrgApiKey } from "./api-key.ts"; import { execSync } from "child_process"; import { existsSync, readFileSync } from "fs"; @@ -360,7 +362,7 @@ async function createCall( console.log(`📞 Creating call...`); - const response = await fetch(url, { + const response = await limitedVapiFetch(orgLimiter(BASE_DIR, config.env), url, { method: "POST", headers: { "Content-Type": "application/json", diff --git a/src/check-cmd.ts b/src/check-cmd.ts index 494194d..8191e68 100644 --- a/src/check-cmd.ts +++ b/src/check-cmd.ts @@ -1,3 +1,4 @@ +import { orgLimiter } from "./rate-limit.ts"; // CLI entry: `npm run check -- |--all [options]` // // Builds each check target's inline simulation-run payload from the files @@ -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) { + orgLimiter(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,7 @@ 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: orgLimiter(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 +394,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/cleanup.ts b/src/cleanup.ts index c988b2a..a9f350b 100644 --- a/src/cleanup.ts +++ b/src/cleanup.ts @@ -1,6 +1,10 @@ +import { limitedVapiFetch } from "./vapi-fetch.ts"; +import { orgLimiter } from "./rate-limit.ts"; import { resolve } from "path"; import { fileURLToPath } from "url"; import { + BASE_DIR, + MAX_GITOPS_RPM, loadIgnorePatterns, matchesIgnore, VAPI_BASE_URL, @@ -31,7 +35,7 @@ function isRecord(value: unknown): value is Record { async function vapiGet(endpoint: string, debug = false): Promise { await orgPinGuard(); await sleep(REQUEST_DELAY_MS); - const response = await fetch(`${VAPI_BASE_URL}${endpoint}`, { + const response = await limitedVapiFetch(orgLimiter(BASE_DIR, VAPI_ENV, MAX_GITOPS_RPM), `${VAPI_BASE_URL}${endpoint}`, { headers: { Authorization: `Bearer ${VAPI_TOKEN}`, "User-Agent": userAgentGet(), @@ -73,7 +77,7 @@ 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 response = await limitedVapiFetch(orgLimiter(BASE_DIR, VAPI_ENV, MAX_GITOPS_RPM), `${VAPI_BASE_URL}${endpoint}`, { method: "DELETE", headers: { Authorization: `Bearer ${VAPI_TOKEN}`, diff --git a/src/config.ts b/src/config.ts index 7ee5460..2ee2efa 100644 --- a/src/config.ts +++ b/src/config.ts @@ -1,3 +1,4 @@ +import { maxGitopsRpmRead } from "./rate-limit.ts"; import { missingApiKeyMessage, resolveOrgApiKey } from "./api-key.ts"; import { existsSync, readFileSync } from "fs"; import { basename, dirname, join, relative, resolve } from "path"; @@ -211,7 +212,7 @@ function loadEnvFile(env: string, baseDir: string): Record { if (fileVars[key] === undefined) fileVars[key] = value; // Only set if not already defined (env vars take precedence) - if (process.env[key] === undefined) { + if (key !== "VAPI_MAX_GITOPS_RPM" && process.env[key] === undefined) { process.env[key] = value; } } @@ -247,6 +248,8 @@ export const { // .env.. See resolveOrgApiKey. const SHELL_ENV = { ...process.env }; +export const MAX_GITOPS_RPM = maxGitopsRpmRead(BASE_DIR, VAPI_ENV, SHELL_ENV); + const ENV_FILE_VARS = loadEnvFile(VAPI_ENV, BASE_DIR); const API_KEY = resolveOrgApiKey(VAPI_ENV, SHELL_ENV, ENV_FILE_VARS); diff --git a/src/interactive.ts b/src/interactive.ts index 67eb822..2df106a 100644 --- a/src/interactive.ts +++ b/src/interactive.ts @@ -1,3 +1,5 @@ +import { limitedVapiFetch } from "./vapi-fetch.ts"; +import { orgLimiter } from "./rate-limit.ts"; import { missingApiKeyMessage, resolveOrgApiKey } from "./api-key.ts"; import { confirm, select } from "@inquirer/prompts"; import { execSync } from "child_process"; @@ -223,8 +225,9 @@ async function apiGet( token: string, baseUrl: string, endpoint: string, + org: string, ): Promise { - const response = await fetch(`${baseUrl}${endpoint}`, { + const response = await limitedVapiFetch(orgLimiter(BASE_DIR, org), `${baseUrl}${endpoint}`, { method: "GET", headers: { Authorization: `Bearer ${token}`, @@ -497,7 +500,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..4f509cc 100644 --- a/src/org-pin.ts +++ b/src/org-pin.ts @@ -162,9 +162,11 @@ 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..7810a73 100644 --- a/src/promotion-gate.ts +++ b/src/promotion-gate.ts @@ -1,3 +1,4 @@ +import { orgLimiter } from "./rate-limit.ts"; // The promotion check gate: `orgs..check: ` in promotion.yml // names a vapi-checks.yml check that must pass in that org before any // transition promotes out of it. The gate runs the same check as the PR @@ -151,6 +152,7 @@ export async function promotionGateRun( const results = await checkRunAll({ jobs, connectionFor: () => ({ + limiter: orgLimiter(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..5f05430 100644 --- a/src/push.ts +++ b/src/push.ts @@ -1,9 +1,12 @@ +import { limitedVapiFetch } from "./vapi-fetch.ts"; +import { orgLimiter } from "./rate-limit.ts"; import { select } from "@inquirer/prompts"; import { relative, resolve } from "path"; import { fileURLToPath } from "url"; import { getDryRunCounts, VapiApiError, vapiRequest } from "./api.ts"; import { canonicalizeForHash, type VapiResource } from "./canonical.ts"; import { + MAX_GITOPS_RPM, ALLOW_NEW_FILES, APPLY_FILTER, BASE_DIR, @@ -351,7 +354,7 @@ async function upsertResourceWithStateRecovery(options: { const resourceType = RESOURCE_LABEL_TO_TYPE[resourceLabel]; if (resourceType) { if (platformPayloadForSnapshot === undefined) { - const platformResponse = await fetch( + const platformResponse = await limitedVapiFetch(orgLimiter(BASE_DIR, VAPI_ENV, MAX_GITOPS_RPM), `${VAPI_BASE_URL}${updateEndpoint}`, { method: "GET", diff --git a/src/rate-limit.ts b/src/rate-limit.ts new file mode 100644 index 0000000..a9a0bc3 --- /dev/null +++ b/src/rate-limit.ts @@ -0,0 +1,81 @@ +import { existsSync, readFileSync } from "node:fs"; +import { join, resolve } from "node:path"; + +export const DEFAULT_MAX_GITOPS_RPM = 100; + +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 Error(`❌ 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 = process.env): number { + 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`); + } + let fileValue: number | undefined; + for (const name of [`.env.${org}`, `.env.${org}.local`, ".env.local"]) { + const path = join(rootDir, name); + if (!existsSync(path)) continue; + for (const line of readFileSync(path, "utf8").split("\n")) { + const match = /^\s*VAPI_MAX_GITOPS_RPM\s*=\s*(.*?)\s*$/.exec(line); + if (match) { + const number = positive(match[1]!.replace(/^(["'])(.*)\1$/, "$2"), `${name} VAPI_MAX_GITOPS_RPM`); + fileValue ??= number; + } + } + } + return env.VAPI_MAX_GITOPS_RPM === undefined ? fileValue ?? value : positive(env.VAPI_MAX_GITOPS_RPM, "environment VAPI_MAX_GITOPS_RPM"); +} + +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))) { + positive(rpm, "token bucket"); + this.capacity = Math.max(1, Math.ceil(rpm / 60)); + 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 orgLimiter(rootDir: string, org: string, rpm = maxGitopsRpmRead(rootDir, org)): TokenBucket { + const key = `${resolve(rootDir)}\0${org}`; + let limiter = buckets.get(key); + if (!limiter) { + limiter = new TokenBucket(rpm); + buckets.set(key, limiter); + } + return limiter; +} diff --git a/src/rollback-cmd.ts b/src/rollback-cmd.ts index 193c6f3..3a40460 100644 --- a/src/rollback-cmd.ts +++ b/src/rollback-cmd.ts @@ -1,3 +1,5 @@ +import { limitedVapiFetch } from "./vapi-fetch.ts"; +import { orgLimiter } from "./rate-limit.ts"; // CLI entry: `npm run rollback -- --to ` | // `npm run rollback -- --list` // @@ -147,7 +149,7 @@ 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: orgLimiter(BASE_DIR, cfg.env), token: cfg.token, baseUrl: cfg.baseUrl, userAgent: userAgentGet(), vapiClient: vapiClientGet() }, keySource: cfg.source, }); if (outcome.kind === "unverified") @@ -205,7 +207,7 @@ async function main(): Promise { process.stdout.write( ` 🔁 ${entry.resourceType}/${entry.resourceId} ... `, ); - const response = await fetch(`${cfg.baseUrl}${endpoint}/${uuid}`, { + const response = await limitedVapiFetch(orgLimiter(BASE_DIR, cfg.env), `${cfg.baseUrl}${endpoint}/${uuid}`, { method: "PATCH", headers: { Authorization: `Bearer ${cfg.token}`, diff --git a/src/setup.ts b/src/setup.ts index 0050ad1..9427a6b 100644 --- a/src/setup.ts +++ b/src/setup.ts @@ -1,3 +1,5 @@ +import { limitedVapiFetch } from "./vapi-fetch.ts"; +import { orgLimiter } from "./rate-limit.ts"; import { confirm, input, password, select } from "@inquirer/prompts"; import { execSync } from "child_process"; import { existsSync, readdirSync, readFileSync } from "fs"; @@ -33,6 +35,7 @@ const VAPI_REGIONS: Record = { us: "https://api.vapi.ai", eu: "https://api.eu.vapi.ai", }; +let requestOrg = "setup"; 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 +97,7 @@ const c = { // ───────────────────────────────────────────────────────────────────────────── async function apiGet(token: string, endpoint: string): Promise { - const response = await fetch(`${vapiBaseUrl}${endpoint}`, { + const response = await limitedVapiFetch(orgLimiter(BASE_DIR, requestOrg), `${vapiBaseUrl}${endpoint}`, { method: "GET", headers: { Authorization: `Bearer ${token}`, @@ -410,6 +413,8 @@ function fail(message: string): never { async function runDirectSetup(options: DirectSetupOptions): Promise { const { slug, region, resources } = options; + requestOrg = slug; + orgLimiter(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`); @@ -583,8 +588,22 @@ async function main(): Promise { ); console.log(""); - // ── Step 1: API key + region ──────────────────────────────────────── + // ── Step 1: Folder slug, API key + region ──────────────────────────────────────── + const rawSlug = await input({ + message: "Folder name for this org (e.g. my-org, my-org-prod)", + validate: (value) => { + const slug = slugify(value); + return slug && SLUG_RE.test(slug) ? true : "Must be lowercase alphanumeric with hyphens (e.g. my-org-name)"; + }, + transformer: (value) => { + const slug = slugify(value); + return slug && slug !== value ? `${value} → ${c.dim(slug)}` : value; + }, + }); + const slug = slugify(rawSlug); + requestOrg = slug; + orgLimiter(BASE_DIR, slug); let trimmedKey = ""; // eslint-disable-next-line no-constant-condition @@ -649,26 +668,6 @@ async function main(): Promise { // "retry" or failed switch → loop back to password prompt } - // ── Step 2: Folder slug ─────────────────────────────────────────────── - - const rawSlug = await input({ - message: "Folder name for this org (e.g. my-org, my-org-prod)", - validate: (value) => { - const slug = slugify(value); - if (!slug || !SLUG_RE.test(slug)) { - return "Must be lowercase alphanumeric with hyphens (e.g. my-org-name)"; - } - return true; - }, - transformer: (value) => { - const slug = slugify(value); - if (slug && slug !== value) return `${value} → ${c.dim(slug)}`; - return value; - }, - }); - - const slug = slugify(rawSlug); - // Check if org already exists locally const resourceDir = join(BASE_DIR, "resources", slug); const stateFile = join(BASE_DIR, `.vapi-state.${slug}.json`); diff --git a/src/sim.ts b/src/sim.ts index f376cd3..4252d33 100644 --- a/src/sim.ts +++ b/src/sim.ts @@ -1,3 +1,4 @@ +import { orgLimiter } from "./rate-limit.ts"; // Simulation runner — wraps `POST /eval/simulation/run`. // // Designed to be importable from `sim-cmd.ts` and from tests without @@ -237,6 +238,7 @@ const ITEM_PAGE_SIZE = 1000; function connectionFor(cfg: SimEnv): VapiConnection { return { + limiter: orgLimiter(BASE_DIR, cfg.env), token: cfg.token, baseUrl: cfg.baseUrl, userAgent: userAgentGet("sim"), diff --git a/src/vapi-client.ts b/src/vapi-client.ts index f1e76be..ff5d664 100644 --- a/src/vapi-client.ts +++ b/src/vapi-client.ts @@ -1,3 +1,5 @@ +import { limitedVapiFetch } from "./vapi-fetch.ts"; +import type { TokenBucket } from "./rate-limit.ts"; // Config-free HTTP client for the Vapi API. // // api.ts is the engine's client, but it imports config.ts, which parses @@ -7,6 +9,7 @@ // policy from here, so both clients fail and retry the same way. export interface VapiConnection { + limiter: TokenBucket; token: string; baseUrl: string; userAgent: string; @@ -83,7 +86,7 @@ export async function vapiFetchJson( const sleep = options.sleep ?? sleepDefault; for (let attempt = 0; ; attempt++) { - const response = await fetch(`${connection.baseUrl}${endpoint}`, { + const response = await limitedVapiFetch(connection.limiter, `${connection.baseUrl}${endpoint}`, { method, headers: { Authorization: `Bearer ${connection.token}`, diff --git a/src/vapi-fetch.ts b/src/vapi-fetch.ts new file mode 100644 index 0000000..f76c796 --- /dev/null +++ b/src/vapi-fetch.ts @@ -0,0 +1,33 @@ +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(); + const response = await fetch(url, { + ...init, + headers: { + "User-Agent": userAgentGet(), + "x-vapi-client": vapiClientGet(), + ...init.headers, + }, + }); + if (response.status === 429 && !warned.has(limiter)) { + warned.add(limiter); + console.warn( + `⚠️ max GitOps RPM (maxGitopsRpm / VAPI_MAX_GITOPS_RPM) may be configured too high. This is a GitOps client limit, not a Vapi org limit. Compare it with your org-level API rate limit in requests per minute (200 by default): ${orgSettingsUrl(url)}`, + ); + } + return response; +} diff --git a/tests/check-run.test.ts b/tests/check-run.test.ts index 0186d57..6d121e8 100644 --- a/tests/check-run.test.ts +++ b/tests/check-run.test.ts @@ -1,3 +1,4 @@ +import { TokenBucket } from "../src/rate-limit.ts"; import assert from "node:assert/strict"; import { createServer } from "node:http"; import type { AddressInfo } from "node:net"; @@ -229,7 +230,7 @@ function runArgs( token: "t", baseUrl: stub.baseUrl, userAgent: "vapi-gitops-check/test", - vapiClient: "gitops/test; command=check", + limiter: new TokenBucket(100), vapiClient: "gitops/test; command=check", }), deadline: DEADLINE_FAR(), pollIntervalMs: 1, diff --git a/tests/org-pin.test.ts b/tests/org-pin.test.ts index c58ec41..27f532d 100644 --- a/tests/org-pin.test.ts +++ b/tests/org-pin.test.ts @@ -1,3 +1,4 @@ +import { TokenBucket } from "../src/rate-limit.ts"; import assert from "node:assert/strict"; import { spawn } from "node:child_process"; import { @@ -34,7 +35,7 @@ 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..3f33f06 --- /dev/null +++ b/tests/rate-limit.test.ts @@ -0,0 +1,135 @@ +import assert from "node:assert/strict"; +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 { maxGitopsRpmRead, orgLimiter, TokenBucket } from "../src/rate-limit.ts"; +import { orgPinCheck } from "../src/org-pin.ts"; +import { orgSettingsUrl } from "../src/vapi-fetch.ts"; +import { vapiFetchJson } from "../src/vapi-client.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, 5); + await Promise.all(Array.from({ length: 10 }, () => 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(30, () => now, async (ms) => { now += ms; }); + assert.equal(limiter.capacity, 1); + await Promise.all(Array.from({ length: 3 }, () => limiter.acquire())); + assert.equal(now, 4000); + 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, 2); + await Promise.all(Array.from({ length: 102 }, () => 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("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.throws(() => maxGitopsRpmRead(root, "acme", { VAPI_MAX_GITOPS_RPM: "5" }), /❌.*resources\/acme\/\.vapi-org.json/); + } + 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", { VAPI_MAX_GITOPS_RPM: "5" }), /❌.*\.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); + 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]!, /max GitOps RPM.*maxGitopsRpm \/ VAPI_MAX_GITOPS_RPM.*https:\/\/dashboard.vapi.ai\/settings\/organization/); + assert.match(warnings[0]!, /requests per minute \(200 by default\)/); + } finally { + console.warn = warn; + await new Promise((resolve) => server.close(() => resolve())); + } +}); diff --git a/tests/sim-run.test.ts b/tests/sim-run.test.ts index 71c858e..866fa34 100644 --- a/tests/sim-run.test.ts +++ b/tests/sim-run.test.ts @@ -1,3 +1,4 @@ +import { TokenBucket } from "../src/rate-limit.ts"; import assert from "node:assert/strict"; import { createServer, type IncomingMessage } from "node:http"; import type { AddressInfo } from "node:net"; @@ -359,7 +360,7 @@ 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..19a4287 100644 --- a/tests/user-agent-coverage.test.ts +++ b/tests/user-agent-coverage.test.ts @@ -55,9 +55,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 +70,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 +86,23 @@ 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: 9 }, () => vapiGet("/assistant"))); + assert.equal(times.length, 10); + assert.ok(times[9]! - times[0]! >= 850, "requests beyond the initial burst must wait for tokens"); + assert.ok(times[9]! - times[8]! >= 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(")); +}); From 5d880c4435dc4f54282d9e75f51c23215100d70a Mon Sep 17 00:00:00 2001 From: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Tue, 17 Nov 2026 09:13:25 +0000 Subject: [PATCH 2/5] fix: preserve setup flow and report invalid GitOps limits cleanly Co-Authored-By: Roshan Manjaly --- docs/guides/commands.md | 5 +- improvements.md | 1 + src/api.ts | 65 ++++++---- src/call.ts | 28 +++-- src/check-cmd.ts | 14 ++- src/cleanup.ts | 42 ++++--- src/config.ts | 16 ++- src/interactive.ts | 24 ++-- src/org-pin.ts | 10 +- src/promotion-gate.ts | 7 +- src/push.ts | 9 +- src/rate-limit.ts | 68 ++++++++-- src/rollback-cmd.ts | 35 ++++-- src/setup.ts | 85 +++++++------ src/sim.ts | 13 +- src/vapi-client.ts | 24 ++-- tests/check-run.test.ts | 14 ++- tests/org-pin.test.ts | 138 +++++++++++++++++---- tests/rate-limit.test.ts | 199 ++++++++++++++++++++++++++---- tests/sim-run.test.ts | 10 +- tests/user-agent-coverage.test.ts | 23 +++- 21 files changed, 606 insertions(+), 224 deletions(-) diff --git a/docs/guides/commands.md b/docs/guides/commands.md index 0696654..453e71b 100644 --- a/docs/guides/commands.md +++ b/docs/guides/commands.md @@ -10,8 +10,9 @@ 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 asks for the org folder before -validating the key so its client ceiling applies to validation too. +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. | Command | Usage | What it does | | --- | --- | --- | diff --git a/improvements.md b/improvements.md index f28f7c5..7ac9a2a 100644 --- a/improvements.md +++ b/improvements.md @@ -2085,3 +2085,4 @@ dependency check, as `check-payload.ts` already does. - **Current mitigation:** Committed `maxGitopsRpm` (default 100), overridden by `VAPI_MAX_GITOPS_RPM`; invalid 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 backoff and write gaps retained. 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. diff --git a/src/api.ts b/src/api.ts index 9125bd5..9a4d605 100644 --- a/src/api.ts +++ b/src/api.ts @@ -1,15 +1,14 @@ -import { limitedVapiFetch } from "./vapi-fetch.ts"; -import { orgLimiter } from "./rate-limit.ts"; import { - MAX_GITOPS_RPM, 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 { @@ -19,6 +18,7 @@ import { shouldRetry, VapiApiError, } from "./vapi-client.ts"; +import { limitedVapiFetch } from "./vapi-fetch.ts"; // ───────────────────────────────────────────────────────────────────────────── // Dry-run accounting @@ -75,7 +75,6 @@ export function orgPinGuard(): Promise { return orgPinChecked; } - export function getDryRunCounts(): { POST: number; PATCH: number; @@ -151,16 +150,20 @@ export async function vapiRequest( for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) { await throttle(); - const response = await limitedVapiFetch(orgLimiter(BASE_DIR, VAPI_ENV, MAX_GITOPS_RPM), url, { - method, - headers: { - "Content-Type": "application/json", - Authorization: `Bearer ${VAPI_TOKEN}`, - "User-Agent": userAgentGet(), - "x-vapi-client": vapiClientGet(), + const response = await limitedVapiFetch( + orgLimiter(BASE_DIR, VAPI_ENV, MAX_GITOPS_RPM), + url, + { + method, + headers: { + "Content-Type": "application/json", + Authorization: `Bearer ${VAPI_TOKEN}`, + "User-Agent": userAgentGet(), + "x-vapi-client": vapiClientGet(), + }, + body: JSON.stringify(body), }, - body: JSON.stringify(body), - }); + ); if (response.ok) { return response.json() as Promise; @@ -197,14 +200,18 @@ export async function vapiGet(endpoint: string): Promise { const url = `${VAPI_BASE_URL}${endpoint}`; for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) { - const response = await limitedVapiFetch(orgLimiter(BASE_DIR, VAPI_ENV, MAX_GITOPS_RPM), url, { - method: "GET", - headers: { - Authorization: `Bearer ${VAPI_TOKEN}`, - "User-Agent": userAgentGet(), - "x-vapi-client": vapiClientGet(), + const response = await limitedVapiFetch( + orgLimiter(BASE_DIR, VAPI_ENV, MAX_GITOPS_RPM), + url, + { + method: "GET", + headers: { + Authorization: `Bearer ${VAPI_TOKEN}`, + "User-Agent": userAgentGet(), + "x-vapi-client": vapiClientGet(), + }, }, - }); + ); if (response.ok) { return response.json() as Promise; @@ -248,14 +255,18 @@ export async function vapiDelete(endpoint: string): Promise { for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) { await throttle(); - const response = await limitedVapiFetch(orgLimiter(BASE_DIR, VAPI_ENV, MAX_GITOPS_RPM), url, { - method: "DELETE", - headers: { - Authorization: `Bearer ${VAPI_TOKEN}`, - "User-Agent": userAgentGet(), - "x-vapi-client": vapiClientGet(), + const response = await limitedVapiFetch( + orgLimiter(BASE_DIR, VAPI_ENV, MAX_GITOPS_RPM), + url, + { + method: "DELETE", + headers: { + Authorization: `Bearer ${VAPI_TOKEN}`, + "User-Agent": userAgentGet(), + "x-vapi-client": vapiClientGet(), + }, }, - }); + ); if (response.ok) { return; diff --git a/src/call.ts b/src/call.ts index ba552a4..7a820b1 100644 --- a/src/call.ts +++ b/src/call.ts @@ -1,14 +1,14 @@ -import { limitedVapiFetch } from "./vapi-fetch.ts"; -import { orgLimiter } from "./rate-limit.ts"; -import { missingApiKeyMessage, resolveOrgApiKey } from "./api-key.ts"; import { execSync } from "child_process"; import { existsSync, readFileSync } from "fs"; import { createRequire } from "module"; import { dirname, join, resolve } from "path"; import * as readline from "readline"; import { fileURLToPath } from "url"; +import { missingApiKeyMessage, resolveOrgApiKey } from "./api-key.ts"; +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); @@ -362,16 +362,20 @@ async function createCall( console.log(`📞 Creating call...`); - const response = await limitedVapiFetch(orgLimiter(BASE_DIR, config.env), url, { - method: "POST", - headers: { - "Content-Type": "application/json", - Authorization: `Bearer ${config.token}`, - "User-Agent": userAgentGet(), - "x-vapi-client": vapiClientGet(), + const response = await limitedVapiFetch( + orgLimiterOrExit(BASE_DIR, config.env), + url, + { + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: `Bearer ${config.token}`, + "User-Agent": userAgentGet(), + "x-vapi-client": vapiClientGet(), + }, + body: JSON.stringify(body), }, - body: JSON.stringify(body), - }); + ); if (!response.ok) { const errorText = await response.text(); diff --git a/src/check-cmd.ts b/src/check-cmd.ts index 8191e68..c65945d 100644 --- a/src/check-cmd.ts +++ b/src/check-cmd.ts @@ -1,4 +1,4 @@ -import { orgLimiter } from "./rate-limit.ts"; +import { orgLimiterOrExit } from "./rate-limit.ts"; // CLI entry: `npm run check -- |--all [options]` // // Builds each check target's inline simulation-run payload from the files @@ -22,7 +22,7 @@ import type { CheckReportSkipped } from "./check-report.ts"; import { checkReportJson, checkReportMarkdown } from "./check-report.ts"; import type { CheckTargetResult } from "./check-run.ts"; import { checkRunAll, outcomeState } from "./check-run.ts"; -import { checkAffectedBy, changedFilesRead } from "./check-select.ts"; +import { changedFilesRead, checkAffectedBy } from "./check-select.ts"; import type { CommitStatus, GitHubStatusEnv } from "./check-status.ts"; import { AGGREGATE_CONTEXT, @@ -189,7 +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) { - orgLimiter(root, runOrg); + orgLimiterOrExit(root, runOrg); const baseUrl = checks.find( (check) => check.runOrg === runOrg && check.baseUrl, )?.baseUrl; @@ -296,7 +296,13 @@ async function liveRun( const vapiClient = vapiClientGet("check"); const vapi = (job: CheckJob): VapiConnection => { const connection = connections.get(job.check.runOrg)!; - return { limiter: orgLimiter(root, job.check.runOrg), 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); diff --git a/src/cleanup.ts b/src/cleanup.ts index a9f350b..83ff673 100644 --- a/src/cleanup.ts +++ b/src/cleanup.ts @@ -1,22 +1,22 @@ -import { limitedVapiFetch } from "./vapi-fetch.ts"; -import { orgLimiter } from "./rate-limit.ts"; import { resolve } from "path"; import { fileURLToPath } from "url"; +import { orgPinGuard } from "./api.ts"; import { BASE_DIR, - MAX_GITOPS_RPM, loadIgnorePatterns, + MAX_GITOPS_RPM, matchesIgnore, 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 @@ -35,13 +35,17 @@ function isRecord(value: unknown): value is Record { async function vapiGet(endpoint: string, debug = false): Promise { await orgPinGuard(); await sleep(REQUEST_DELAY_MS); - const response = await limitedVapiFetch(orgLimiter(BASE_DIR, VAPI_ENV, MAX_GITOPS_RPM), `${VAPI_BASE_URL}${endpoint}`, { - headers: { - Authorization: `Bearer ${VAPI_TOKEN}`, - "User-Agent": userAgentGet(), - "x-vapi-client": vapiClientGet(), + const response = await limitedVapiFetch( + orgLimiter(BASE_DIR, VAPI_ENV, MAX_GITOPS_RPM), + `${VAPI_BASE_URL}${endpoint}`, + { + headers: { + Authorization: `Bearer ${VAPI_TOKEN}`, + "User-Agent": userAgentGet(), + "x-vapi-client": vapiClientGet(), + }, }, - }); + ); if (!response.ok) { throw new Error(`GET ${endpoint} failed: ${response.status}`); } @@ -77,14 +81,18 @@ async function vapiGet(endpoint: string, debug = false): Promise { async function vapiDelete(endpoint: string): Promise { await orgPinGuard(); await sleep(REQUEST_DELAY_MS); - const response = await limitedVapiFetch(orgLimiter(BASE_DIR, VAPI_ENV, MAX_GITOPS_RPM), `${VAPI_BASE_URL}${endpoint}`, { - method: "DELETE", - headers: { - Authorization: `Bearer ${VAPI_TOKEN}`, - "User-Agent": userAgentGet(), - "x-vapi-client": vapiClientGet(), + const response = await limitedVapiFetch( + orgLimiter(BASE_DIR, VAPI_ENV, MAX_GITOPS_RPM), + `${VAPI_BASE_URL}${endpoint}`, + { + method: "DELETE", + headers: { + Authorization: `Bearer ${VAPI_TOKEN}`, + "User-Agent": userAgentGet(), + "x-vapi-client": vapiClientGet(), + }, }, - }); + ); if (!response.ok && response.status !== 404) { throw new Error(`DELETE ${endpoint} failed: ${response.status}`); } diff --git a/src/config.ts b/src/config.ts index 2ee2efa..48a5ff2 100644 --- a/src/config.ts +++ b/src/config.ts @@ -1,14 +1,14 @@ -import { maxGitopsRpmRead } from "./rate-limit.ts"; -import { missingApiKeyMessage, resolveOrgApiKey } from "./api-key.ts"; import { existsSync, readFileSync } from "fs"; import { basename, dirname, join, relative, resolve } from "path"; import { fileURLToPath } from "url"; -import type { Environment, ResourceType } from "./types.ts"; +import { missingApiKeyMessage, resolveOrgApiKey } from "./api-key.ts"; +import { maxGitopsRpmRead } from "./rate-limit.ts"; import { ignorePatternsRead, matchesIgnore as matchesIgnorePatterns, } from "./resource-parse.ts"; import { resolveResourceTypes, VALID_TYPE_ARGS } from "./resource-type-args.ts"; +import type { Environment, ResourceType } from "./types.ts"; // ───────────────────────────────────────────────────────────────────────────── // CLI Argument Parsing @@ -53,7 +53,6 @@ function parseEnvironment(): Environment { return envArg; } - function parseFlags(): { forceDelete: boolean; bootstrapSync: boolean; @@ -248,7 +247,14 @@ export const { // .env.. See resolveOrgApiKey. const SHELL_ENV = { ...process.env }; -export const MAX_GITOPS_RPM = maxGitopsRpmRead(BASE_DIR, VAPI_ENV, SHELL_ENV); +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/interactive.ts b/src/interactive.ts index 2df106a..4e5716b 100644 --- a/src/interactive.ts +++ b/src/interactive.ts @@ -1,17 +1,17 @@ -import { limitedVapiFetch } from "./vapi-fetch.ts"; -import { orgLimiter } from "./rate-limit.ts"; -import { missingApiKeyMessage, resolveOrgApiKey } from "./api-key.ts"; import { confirm, select } from "@inquirer/prompts"; import { execSync } from "child_process"; import { existsSync, readdirSync, readFileSync, statSync } from "fs"; import { dirname, extname, join, relative } from "path"; import { fileURLToPath } from "url"; +import { missingApiKeyMessage, resolveOrgApiKey } from "./api-key.ts"; +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 @@ -227,14 +227,18 @@ async function apiGet( endpoint: string, org: string, ): Promise { - const response = await limitedVapiFetch(orgLimiter(BASE_DIR, org), `${baseUrl}${endpoint}`, { - method: "GET", - headers: { - Authorization: `Bearer ${token}`, - "User-Agent": userAgentGet(), - "x-vapi-client": vapiClientGet(), + const response = await limitedVapiFetch( + orgLimiterOrExit(BASE_DIR, org), + `${baseUrl}${endpoint}`, + { + method: "GET", + headers: { + Authorization: `Bearer ${token}`, + "User-Agent": userAgentGet(), + "x-vapi-client": vapiClientGet(), + }, }, - }); + ); if (!response.ok) { const text = await response.text(); throw new Error(`API GET ${endpoint} failed (${response.status}): ${text}`); diff --git a/src/org-pin.ts b/src/org-pin.ts index 4f509cc..c2ceb2d 100644 --- a/src/org-pin.ts +++ b/src/org-pin.ts @@ -18,8 +18,8 @@ import { existsSync, readFileSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { orgApiKeyVar } from "./api-key.ts"; import { - type VapiConnection, VapiApiError, + type VapiConnection, vapiFetchJson, } from "./vapi-client.ts"; @@ -138,7 +138,9 @@ export interface OrgPinCheckArgs { * key belongs to another org, or to an empty org while the folder is pinned * to one that had resources. */ -export async function orgPinCheck(args: OrgPinCheckArgs): Promise { +export async function orgPinCheck( + args: OrgPinCheckArgs, +): Promise { const { rootDir, org, connection, keySource } = args; // Set only by tests/no-vapi-api.ts: tests that stub fetch count requests. if (process.env.VAPI_GITOPS_ORG_PIN === "off") return { kind: "unpinned" }; @@ -163,7 +165,9 @@ export async function orgPinCheck(args: OrgPinCheckArgs): Promise ); if (!folderExists) return { kind: "unpinned" }; const path = orgPinPath(rootDir, org); - const settings = existsSync(path) ? JSON.parse(readFileSync(path, "utf8")) : {}; + const settings = existsSync(path) + ? JSON.parse(readFileSync(path, "utf8")) + : {}; writeFileSync( path, `${JSON.stringify({ ...settings, orgId: keyOrg.orgId }, null, 2)}\n`, diff --git a/src/promotion-gate.ts b/src/promotion-gate.ts index 7810a73..4809b73 100644 --- a/src/promotion-gate.ts +++ b/src/promotion-gate.ts @@ -1,12 +1,13 @@ -import { orgLimiter } from "./rate-limit.ts"; +import { orgLimiterOrExit } from "./rate-limit.ts"; + // The promotion check gate: `orgs..check: ` in promotion.yml // names a vapi-checks.yml check that must pass in that org before any // transition promotes out of it. The gate runs the same check as the PR // workflow, built from the source org's files at the promoted commit. +import { checkJobsBuild } from "./check-build.ts"; import type { CheckDefinition } from "./check-config.ts"; import { CHECKS_CONFIG_FILE, checksConfigLoad } from "./check-config.ts"; -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"; @@ -152,7 +153,7 @@ export async function promotionGateRun( const results = await checkRunAll({ jobs, connectionFor: () => ({ - limiter: orgLimiter(rootDir, check.runOrg), + 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 5f05430..f9b53eb 100644 --- a/src/push.ts +++ b/src/push.ts @@ -1,12 +1,9 @@ -import { limitedVapiFetch } from "./vapi-fetch.ts"; -import { orgLimiter } from "./rate-limit.ts"; import { select } from "@inquirer/prompts"; import { relative, resolve } from "path"; import { fileURLToPath } from "url"; import { getDryRunCounts, VapiApiError, vapiRequest } from "./api.ts"; import { canonicalizeForHash, type VapiResource } from "./canonical.ts"; import { - MAX_GITOPS_RPM, ALLOW_NEW_FILES, APPLY_FILTER, BASE_DIR, @@ -14,6 +11,7 @@ import { DRY_RUN, FORCE_DELETE, loadIgnorePatterns, + MAX_GITOPS_RPM, OVERWRITE_DRIFT, RESOURCES_DIR, removeExcludedKeys, @@ -31,6 +29,7 @@ import { checkDriftForUpdate, type DriftCheckResult } from "./drift.ts"; import { deleteBaseline, writeBaseline } from "./hash-store.ts"; import { assertStateMigrated } from "./migrate-hash-store.ts"; import { detectOrphanYamls, formatGateMessage } from "./new-file-gate.ts"; +import { orgLimiter } from "./rate-limit.ts"; import { formatRecanonicalizeReport, recanonicalizeStateKeys, @@ -45,6 +44,7 @@ import { validateResources, } from "./validate.ts"; import { validateReferences } from "./validate-refs.ts"; +import { limitedVapiFetch } from "./vapi-fetch.ts"; import { changedFieldPaths, versionActorResolve, @@ -354,7 +354,8 @@ async function upsertResourceWithStateRecovery(options: { const resourceType = RESOURCE_LABEL_TO_TYPE[resourceLabel]; if (resourceType) { if (platformPayloadForSnapshot === undefined) { - const platformResponse = await limitedVapiFetch(orgLimiter(BASE_DIR, VAPI_ENV, MAX_GITOPS_RPM), + const platformResponse = await limitedVapiFetch( + orgLimiter(BASE_DIR, VAPI_ENV, MAX_GITOPS_RPM), `${VAPI_BASE_URL}${updateEndpoint}`, { method: "GET", diff --git a/src/rate-limit.ts b/src/rate-limit.ts index a9a0bc3..571bf25 100644 --- a/src/rate-limit.ts +++ b/src/rate-limit.ts @@ -3,16 +3,27 @@ import { join, resolve } from "node:path"; 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; + typeof value === "number" + ? value + : typeof value === "string" && value.trim() + ? Number(value) + : NaN; if (!Number.isInteger(number) || number <= 0) - throw new Error(`❌ Invalid max GitOps RPM in ${source}: expected a positive integer (a GitOps client limit, not a Vapi org limit).`); + 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 = process.env): number { +export function maxGitopsRpmRead( + rootDir: string, + org: string, + env: NodeJS.ProcessEnv = process.env, +): number { const pin = join(rootDir, "resources", org, ".vapi-org.json"); let value = DEFAULT_MAX_GITOPS_RPM; if (existsSync(pin)) { @@ -21,9 +32,15 @@ export function maxGitopsRpmRead(rootDir: string, org: string, env: NodeJS.Proce 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.`); + 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`); + if (parsed && Object.hasOwn(parsed, "maxGitopsRpm")) + value = positive( + parsed.maxGitopsRpm, + `resources/${org}/.vapi-org.json maxGitopsRpm`, + ); } let fileValue: number | undefined; for (const name of [`.env.${org}`, `.env.${org}.local`, ".env.local"]) { @@ -32,12 +49,17 @@ export function maxGitopsRpmRead(rootDir: string, org: string, env: NodeJS.Proce for (const line of readFileSync(path, "utf8").split("\n")) { const match = /^\s*VAPI_MAX_GITOPS_RPM\s*=\s*(.*?)\s*$/.exec(line); if (match) { - const number = positive(match[1]!.replace(/^(["'])(.*)\1$/, "$2"), `${name} VAPI_MAX_GITOPS_RPM`); + const number = positive( + match[1]!.replace(/^(["'])(.*)\1$/, "$2"), + `${name} VAPI_MAX_GITOPS_RPM`, + ); fileValue ??= number; } } } - return env.VAPI_MAX_GITOPS_RPM === undefined ? fileValue ?? value : positive(env.VAPI_MAX_GITOPS_RPM, "environment VAPI_MAX_GITOPS_RPM"); + return env.VAPI_MAX_GITOPS_RPM === undefined + ? (fileValue ?? value) + : positive(env.VAPI_MAX_GITOPS_RPM, "environment VAPI_MAX_GITOPS_RPM"); } export class TokenBucket { @@ -45,7 +67,12 @@ export class TokenBucket { 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))) { + constructor( + readonly rpm: number, + private now = () => performance.now(), + private sleep = (ms: number) => + new Promise((resolve) => setTimeout(resolve, ms)), + ) { positive(rpm, "token bucket"); this.capacity = Math.max(1, Math.ceil(rpm / 60)); this.tokens = this.capacity; @@ -55,13 +82,16 @@ export class TokenBucket { 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.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); + await this.sleep(((1 - this.tokens) * 60_000) / this.rpm); } }); this.queue = next.catch(() => {}); @@ -70,7 +100,21 @@ export class TokenBucket { } const buckets = new Map(); -export function orgLimiter(rootDir: string, org: string, rpm = maxGitopsRpmRead(rootDir, org)): TokenBucket { +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 = maxGitopsRpmRead(rootDir, org), +): TokenBucket { const key = `${resolve(rootDir)}\0${org}`; let limiter = buckets.get(key); if (!limiter) { diff --git a/src/rollback-cmd.ts b/src/rollback-cmd.ts index 3a40460..db88909 100644 --- a/src/rollback-cmd.ts +++ b/src/rollback-cmd.ts @@ -1,5 +1,6 @@ +import { orgLimiterOrExit } from "./rate-limit.ts"; import { limitedVapiFetch } from "./vapi-fetch.ts"; -import { orgLimiter } from "./rate-limit.ts"; + // CLI entry: `npm run rollback -- --to ` | // `npm run rollback -- --list` // @@ -10,10 +11,10 @@ import { orgLimiter } from "./rate-limit.ts"; // Self-contained (does not import config.ts) so it can run in isolation // without triggering the global CLI parser. -import { missingApiKeyMessage, resolveOrgApiKey } from "./api-key.ts"; import { existsSync, readFileSync } from "fs"; import { dirname, join } from "path"; import { fileURLToPath } from "url"; +import { missingApiKeyMessage, resolveOrgApiKey } from "./api-key.ts"; import { ORG_PIN_FILE, OrgPinMismatchError, orgPinCheck } from "./org-pin.ts"; import { listSnapshotTimestamps, loadSnapshot } from "./snapshot.ts"; import { userAgentGet, vapiClientGet } from "./user-agent.ts"; @@ -149,7 +150,13 @@ async function main(): Promise { const outcome = await orgPinCheck({ rootDir: BASE_DIR, org: args.env, - connection: { limiter: orgLimiter(BASE_DIR, cfg.env), 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") @@ -207,16 +214,20 @@ async function main(): Promise { process.stdout.write( ` 🔁 ${entry.resourceType}/${entry.resourceId} ... `, ); - const response = await limitedVapiFetch(orgLimiter(BASE_DIR, cfg.env), `${cfg.baseUrl}${endpoint}/${uuid}`, { - method: "PATCH", - headers: { - Authorization: `Bearer ${cfg.token}`, - "Content-Type": "application/json", - "User-Agent": userAgentGet(), - "x-vapi-client": vapiClientGet(), + const response = await limitedVapiFetch( + orgLimiterOrExit(BASE_DIR, cfg.env), + `${cfg.baseUrl}${endpoint}/${uuid}`, + { + method: "PATCH", + headers: { + Authorization: `Bearer ${cfg.token}`, + "Content-Type": "application/json", + "User-Agent": userAgentGet(), + "x-vapi-client": vapiClientGet(), + }, + body: JSON.stringify(entry.payload.platform), }, - body: JSON.stringify(entry.payload.platform), - }); + ); if (!response.ok) { const text = await response.text(); console.log(`❌ ${response.status}`); diff --git a/src/setup.ts b/src/setup.ts index 9427a6b..90056a4 100644 --- a/src/setup.ts +++ b/src/setup.ts @@ -1,5 +1,3 @@ -import { limitedVapiFetch } from "./vapi-fetch.ts"; -import { orgLimiter } from "./rate-limit.ts"; import { confirm, input, password, select } from "@inquirer/prompts"; import { execSync } from "child_process"; import { existsSync, readdirSync, readFileSync } from "fs"; @@ -14,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 { @@ -24,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 @@ -35,7 +39,8 @@ const VAPI_REGIONS: Record = { us: "https://api.vapi.ai", eu: "https://api.eu.vapi.ai", }; -let requestOrg = "setup"; +let requestOrg: string | undefined; +const validationLimiter = new TokenBucket(DEFAULT_MAX_GITOPS_RPM); 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; @@ -97,14 +102,18 @@ const c = { // ───────────────────────────────────────────────────────────────────────────── async function apiGet(token: string, endpoint: string): Promise { - const response = await limitedVapiFetch(orgLimiter(BASE_DIR, requestOrg), `${vapiBaseUrl}${endpoint}`, { - method: "GET", - headers: { - Authorization: `Bearer ${token}`, - "User-Agent": userAgentGet(), - "x-vapi-client": vapiClientGet(), + const response = await limitedVapiFetch( + requestOrg ? orgLimiterOrExit(BASE_DIR, requestOrg) : validationLimiter, + `${vapiBaseUrl}${endpoint}`, + { + method: "GET", + headers: { + Authorization: `Bearer ${token}`, + "User-Agent": userAgentGet(), + "x-vapi-client": vapiClientGet(), + }, }, - }); + ); if (!response.ok) { const text = await response.text(); @@ -414,12 +423,14 @@ function fail(message: string): never { async function runDirectSetup(options: DirectSetupOptions): Promise { const { slug, region, resources } = options; requestOrg = slug; - orgLimiter(BASE_DIR, 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`); - console.log(c.bold(`\n Vapi GitOps — non-interactive setup for "${slug}"\n`)); + console.log( + c.bold(`\n Vapi GitOps — non-interactive setup for "${slug}"\n`), + ); // Never clobber an org that already has local state. Re-running setup is // a destructive operation in the wizard (it deletes and re-pulls), and an @@ -452,7 +463,9 @@ async function runDirectSetup(options: DirectSetupOptions): Promise { // Setup writes the key into .env. and downloads that org, so a key // that may belong to another org is a hard stop here, not a warning. if (resolved.warning) { - fail(`${resolved.warning}\n Setup stopped before writing .env.${slug} or downloading anything.`); + fail( + `${resolved.warning}\n Setup stopped before writing .env.${slug} or downloading anything.`, + ); } const otherOrg = orgWithKey(slug, resolved.token); if (otherOrg) { @@ -572,7 +585,9 @@ async function main(): Promise { // so explain the non-interactive path instead. if (!process.stdin.isTTY) { console.error( - c.red("\n ✗ The setup wizard needs an interactive terminal (stdin is not a TTY).\n"), + c.red( + "\n ✗ The setup wizard needs an interactive terminal (stdin is not a TTY).\n", + ), ); console.error(SETUP_USAGE); process.exit(1); @@ -588,22 +603,8 @@ async function main(): Promise { ); console.log(""); - // ── Step 1: Folder slug, API key + region ──────────────────────────────────────── + // ── Step 1: API key + region ──────────────────────────────────────── - const rawSlug = await input({ - message: "Folder name for this org (e.g. my-org, my-org-prod)", - validate: (value) => { - const slug = slugify(value); - return slug && SLUG_RE.test(slug) ? true : "Must be lowercase alphanumeric with hyphens (e.g. my-org-name)"; - }, - transformer: (value) => { - const slug = slugify(value); - return slug && slug !== value ? `${value} → ${c.dim(slug)}` : value; - }, - }); - const slug = slugify(rawSlug); - requestOrg = slug; - orgLimiter(BASE_DIR, slug); let trimmedKey = ""; // eslint-disable-next-line no-constant-condition @@ -668,6 +669,25 @@ async function main(): Promise { // "retry" or failed switch → loop back to password prompt } + // ── Step 2: Folder slug ─────────────────────────────────────────────── + + const rawSlug = await input({ + message: "Folder name for this org (e.g. my-org, my-org-prod)", + validate: (value) => { + const slug = slugify(value); + return slug && SLUG_RE.test(slug) + ? true + : "Must be lowercase alphanumeric with hyphens (e.g. my-org-name)"; + }, + transformer: (value) => { + const slug = slugify(value); + return slug && slug !== value ? `${value} → ${c.dim(slug)}` : value; + }, + }); + const slug = slugify(rawSlug); + requestOrg = slug; + orgLimiterOrExit(BASE_DIR, slug); + // Check if org already exists locally const resourceDir = join(BASE_DIR, "resources", slug); const stateFile = join(BASE_DIR, `.vapi-state.${slug}.json`); @@ -815,12 +835,7 @@ async function main(): Promise { console.log(c.bold(" Downloading...\n")); - invokePull( - slug, - downloadAll ? "all" : selectedIds, - trimmedKey, - vapiBaseUrl, - ); + invokePull(slug, downloadAll ? "all" : selectedIds, trimmedKey, vapiBaseUrl); // ── Done ────────────────────────────────────────────────────────────── diff --git a/src/sim.ts b/src/sim.ts index 4252d33..d64ff4f 100644 --- a/src/sim.ts +++ b/src/sim.ts @@ -1,28 +1,29 @@ -import { orgLimiter } from "./rate-limit.ts"; +import { orgLimiterOrExit } from "./rate-limit.ts"; + // Simulation runner — wraps `POST /eval/simulation/run`. // // Designed to be importable from `sim-cmd.ts` and from tests without // triggering the CLI argument parser in `config.ts`. Env-loading is inlined // here (rather than importing from `config.ts`) for the same reason. -import { missingApiKeyMessage, resolveOrgApiKey } from "./api-key.ts"; import { existsSync, readFileSync } from "fs"; import { dirname, join } from "path"; import { fileURLToPath } from "url"; +import { missingApiKeyMessage, resolveOrgApiKey } from "./api-key.ts"; import { - simRunItemTerminal, - simRunVerdict, type SimRun, type SimRunItem, type SimRunItemCounts, type SimRunVerdict, + simRunItemTerminal, + simRunVerdict, } from "./sim-result.ts"; import type { StateFile } from "./types.ts"; import { userAgentGet, vapiClientGet } from "./user-agent.ts"; import { VapiApiError, - vapiFetchJson, type VapiConnection, + vapiFetchJson, } from "./vapi-client.ts"; const __dirname = dirname(fileURLToPath(import.meta.url)); @@ -238,7 +239,7 @@ const ITEM_PAGE_SIZE = 1000; function connectionFor(cfg: SimEnv): VapiConnection { return { - limiter: orgLimiter(BASE_DIR, cfg.env), + limiter: orgLimiterOrExit(BASE_DIR, cfg.env), token: cfg.token, baseUrl: cfg.baseUrl, userAgent: userAgentGet("sim"), diff --git a/src/vapi-client.ts b/src/vapi-client.ts index ff5d664..ed77bfa 100644 --- a/src/vapi-client.ts +++ b/src/vapi-client.ts @@ -1,5 +1,5 @@ -import { limitedVapiFetch } from "./vapi-fetch.ts"; import type { TokenBucket } from "./rate-limit.ts"; +import { limitedVapiFetch } from "./vapi-fetch.ts"; // Config-free HTTP client for the Vapi API. // // api.ts is the engine's client, but it imports config.ts, which parses @@ -86,16 +86,20 @@ export async function vapiFetchJson( const sleep = options.sleep ?? sleepDefault; for (let attempt = 0; ; attempt++) { - const response = await limitedVapiFetch(connection.limiter, `${connection.baseUrl}${endpoint}`, { - method, - headers: { - Authorization: `Bearer ${connection.token}`, - "Content-Type": "application/json", - "User-Agent": connection.userAgent, - "x-vapi-client": connection.vapiClient, + const response = await limitedVapiFetch( + connection.limiter, + `${connection.baseUrl}${endpoint}`, + { + method, + headers: { + Authorization: `Bearer ${connection.token}`, + "Content-Type": "application/json", + "User-Agent": connection.userAgent, + "x-vapi-client": connection.vapiClient, + }, + ...(body === undefined ? {} : { body: JSON.stringify(body) }), }, - ...(body === undefined ? {} : { body: JSON.stringify(body) }), - }); + ); if (response.ok) { const text = await response.text(); return (text ? JSON.parse(text) : null) as T; diff --git a/tests/check-run.test.ts b/tests/check-run.test.ts index 6d121e8..da87bf1 100644 --- a/tests/check-run.test.ts +++ b/tests/check-run.test.ts @@ -1,4 +1,3 @@ -import { TokenBucket } from "../src/rate-limit.ts"; import assert from "node:assert/strict"; import { createServer } from "node:http"; import type { AddressInfo } from "node:net"; @@ -9,12 +8,20 @@ import { MOCK_MARKER } from "../src/check-mocks.ts"; import type { CheckRunBody } from "../src/check-payload.ts"; import type { CheckRunArgs, CheckTargetResult } from "../src/check-run.ts"; import { checkRunAll, MIN_START_MS } from "../src/check-run.ts"; +import { TokenBucket } from "../src/rate-limit.ts"; // checkRunAll against a stateful stub of the simulations API. The target // assistant's name picks the stub's behaviour for that run. type Behaviour = - "pass" | "fail" | "skipped" | "hang" | "slow" | "unmocked" | "402" | "502"; + | "pass" + | "fail" + | "skipped" + | "hang" + | "slow" + | "unmocked" + | "402" + | "502"; interface StubRun { id: string; @@ -230,7 +237,8 @@ function runArgs( token: "t", baseUrl: stub.baseUrl, userAgent: "vapi-gitops-check/test", - limiter: new TokenBucket(100), vapiClient: "gitops/test; command=check", + limiter: new TokenBucket(100), + vapiClient: "gitops/test; command=check", }), deadline: DEADLINE_FAR(), pollIntervalMs: 1, diff --git a/tests/org-pin.test.ts b/tests/org-pin.test.ts index 27f532d..feb996d 100644 --- a/tests/org-pin.test.ts +++ b/tests/org-pin.test.ts @@ -1,4 +1,3 @@ -import { TokenBucket } from "../src/rate-limit.ts"; import assert from "node:assert/strict"; import { spawn } from "node:child_process"; import { @@ -25,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 @@ -35,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", limiter: new TokenBucket(100), 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. @@ -63,13 +69,24 @@ function orgDir(options: { folder: boolean; pin?: string }): string { } const serverError = new VapiApiError("GET", "/tool", 503, "unavailable", ""); -const unauthorized = new VapiApiError("GET", "/assistant", 401, "Unauthorized", ""); +const unauthorized = new VapiApiError( + "GET", + "/assistant", + 401, + "Unauthorized", + "", +); // ── Finding the key's org ──────────────────────────────────────────────── test("keyOrgFetch reads orgId from the first resource listed", async () => { - const { probeFetch, seen } = probes({ "/assistant": [{ id: "a1", orgId: "org-a" }] }); - assert.deepEqual(await keyOrgFetch(CONNECTION, probeFetch), { kind: "found", orgId: "org-a" }); + const { probeFetch, seen } = probes({ + "/assistant": [{ id: "a1", orgId: "org-a" }], + }); + assert.deepEqual(await keyOrgFetch(CONNECTION, probeFetch), { + kind: "found", + orgId: "org-a", + }); assert.deepEqual(seen, ["/assistant?limit=1"]); }); @@ -77,12 +94,17 @@ test("keyOrgFetch moves on from empty lists and reads { results } pages", async const { probeFetch, seen } = probes({ "/structured-output": { results: [{ id: "s1", orgId: "org-a" }] }, }); - assert.deepEqual(await keyOrgFetch(CONNECTION, probeFetch), { kind: "found", orgId: "org-a" }); + assert.deepEqual(await keyOrgFetch(CONNECTION, probeFetch), { + kind: "found", + orgId: "org-a", + }); assert.equal(seen.length, 6); }); test("keyOrgFetch reports an org that lists nothing as empty", async () => { - assert.deepEqual(await keyOrgFetch(CONNECTION, probes({}).probeFetch), { kind: "empty" }); + assert.deepEqual(await keyOrgFetch(CONNECTION, probes({}).probeFetch), { + kind: "empty", + }); }); test("keyOrgFetch reports unknown when a probe fails and none finds an org", async () => { @@ -94,7 +116,9 @@ test("keyOrgFetch reports unknown when a probe fails and none finds an org", asy test("keyOrgFetch stops at a rejected key", async () => { const { probeFetch, seen } = probes({ "/assistant": unauthorized }); - assert.deepEqual(await keyOrgFetch(CONNECTION, probeFetch), { kind: "unknown" }); + assert.deepEqual(await keyOrgFetch(CONNECTION, probeFetch), { + kind: "unknown", + }); assert.deepEqual(seen, ["/assistant?limit=1"]); }); @@ -104,7 +128,13 @@ test("orgPinCheck pins an unpinned folder to the key's org", async () => { const root = orgDir({ folder: true }); try { const { probeFetch } = probes({ "/assistant": [{ orgId: "org-a" }] }); - const outcome = await orgPinCheck({ rootDir: root, org: "acme", connection: CONNECTION, keySource: SOURCE, probeFetch }); + const outcome = await orgPinCheck({ + rootDir: root, + org: "acme", + connection: CONNECTION, + keySource: SOURCE, + probeFetch, + }); assert.deepEqual(outcome, { kind: "pinned", orgId: "org-a" }); assert.equal( readFileSync(join(root, "resources", "acme", ORG_PIN_FILE), "utf8"), @@ -119,7 +149,13 @@ test("orgPinCheck makes no request for an org with no folder and no pin", async const root = orgDir({ folder: false }); try { const { probeFetch, seen } = probes({ "/assistant": [{ orgId: "org-a" }] }); - const outcome = await orgPinCheck({ rootDir: root, org: "acme", connection: CONNECTION, keySource: SOURCE, probeFetch }); + const outcome = await orgPinCheck({ + rootDir: root, + org: "acme", + connection: CONNECTION, + keySource: SOURCE, + probeFetch, + }); assert.deepEqual(outcome, { kind: "unpinned" }); assert.deepEqual(seen, []); assert.equal(existsSync(join(root, "resources")), false); @@ -133,7 +169,13 @@ test("orgPinCheck passes a key for the pinned org", async () => { try { const { probeFetch } = probes({ "/assistant": [{ orgId: "org-a" }] }); assert.deepEqual( - await orgPinCheck({ rootDir: root, org: "acme", connection: CONNECTION, keySource: SOURCE, probeFetch }), + await orgPinCheck({ + rootDir: root, + org: "acme", + connection: CONNECTION, + keySource: SOURCE, + probeFetch, + }), { kind: "match" }, ); } finally { @@ -146,12 +188,21 @@ test("orgPinCheck refuses a key for another org, naming both orgs and the source try { const { probeFetch } = probes({ "/assistant": [{ orgId: "org-b" }] }); await assert.rejects( - orgPinCheck({ rootDir: root, org: "acme", connection: CONNECTION, keySource: SOURCE, probeFetch }), + orgPinCheck({ + rootDir: root, + org: "acme", + connection: CONNECTION, + keySource: SOURCE, + probeFetch, + }), (error: Error) => { assert.ok(error instanceof OrgPinMismatchError); assert.match(error.message, /belongs to Vapi org org-b/); assert.match(error.message, /pinned to org org-a/); - assert.match(error.message, /VAPI_PRIVATE_API_KEY_ACME environment variable/); + assert.match( + error.message, + /VAPI_PRIVATE_API_KEY_ACME environment variable/, + ); assert.doesNotMatch(error.message, /test-token-not-used/); return true; }, @@ -165,7 +216,13 @@ test("orgPinCheck refuses a key whose org is empty when the folder is pinned", a const root = orgDir({ folder: true, pin: '{"orgId":"org-a"}' }); try { await assert.rejects( - orgPinCheck({ rootDir: root, org: "acme", connection: CONNECTION, keySource: SOURCE, probeFetch: probes({}).probeFetch }), + orgPinCheck({ + rootDir: root, + org: "acme", + connection: CONNECTION, + keySource: SOURCE, + probeFetch: probes({}).probeFetch, + }), /belongs to an org with no resources/, ); } finally { @@ -178,7 +235,13 @@ test("orgPinCheck can't verify when the probes fail, and says so", async () => { try { const { probeFetch } = probes({ "/assistant": serverError }); assert.deepEqual( - await orgPinCheck({ rootDir: root, org: "acme", connection: CONNECTION, keySource: SOURCE, probeFetch }), + await orgPinCheck({ + rootDir: root, + org: "acme", + connection: CONNECTION, + keySource: SOURCE, + probeFetch, + }), { kind: "unverified" }, ); } finally { @@ -189,7 +252,10 @@ test("orgPinCheck can't verify when the probes fail, and says so", async () => { test("orgPinRead names the file when the pin is corrupt", () => { const root = orgDir({ folder: true, pin: "{not json" }); try { - assert.throws(() => orgPinRead(root, "acme"), /resources\/acme\/\.vapi-org\.json/); + assert.throws( + () => orgPinRead(root, "acme"), + /resources\/acme\/\.vapi-org\.json/, + ); } finally { rmSync(root, { recursive: true, force: true }); } @@ -212,20 +278,38 @@ test("pull stops before listing anything when the key belongs to another org", a cpSync(join(REPO, "package.json"), join(dir, "package.json")); symlinkSync(join(REPO, "node_modules"), join(dir, "node_modules"), "dir"); mkdirSync(join(dir, "resources", "acme"), { recursive: true }); - writeFileSync(join(dir, "resources", "acme", ORG_PIN_FILE), '{"orgId":"org-a"}\n'); - writeFileSync(join(dir, ".env.acme"), "VAPI_PRIVATE_API_KEY=wrong-org-key\n"); - const env: NodeJS.ProcessEnv = { ...process.env, VAPI_BASE_URL: `http://127.0.0.1:${port}` }; + writeFileSync( + join(dir, "resources", "acme", ORG_PIN_FILE), + '{"orgId":"org-a"}\n', + ); + writeFileSync( + join(dir, ".env.acme"), + "VAPI_PRIVATE_API_KEY=wrong-org-key\n", + ); + const env: NodeJS.ProcessEnv = { + ...process.env, + VAPI_BASE_URL: `http://127.0.0.1:${port}`, + }; delete env.VAPI_GITOPS_ORG_PIN; // Async spawn: the stub server runs in this process. - const result = await new Promise<{ code: number | null; output: string }>((resolve) => { - const child = spawn(process.execPath, ["--import", "tsx", "src/pull.ts", "acme"], { cwd: dir, env }); - let output = ""; - child.stdout.on("data", (chunk) => (output += chunk)); - child.stderr.on("data", (chunk) => (output += chunk)); - child.on("close", (code) => resolve({ code, output })); - }); + const result = await new Promise<{ code: number | null; output: string }>( + (resolve) => { + const child = spawn( + process.execPath, + ["--import", "tsx", "src/pull.ts", "acme"], + { cwd: dir, env }, + ); + let output = ""; + child.stdout.on("data", (chunk) => (output += chunk)); + child.stderr.on("data", (chunk) => (output += chunk)); + child.on("close", (code) => resolve({ code, output })); + }, + ); assert.equal(result.code, 1); - assert.match(result.output, /belongs to Vapi org org-b, but resources\/acme\/ is pinned to org org-a/); + assert.match( + result.output, + /belongs to Vapi org org-b, but resources\/acme\/ is pinned to org org-a/, + ); assert.doesNotMatch(result.output, /wrong-org-key/); // Only the probe went out: no listing, no writes. assert.deepEqual(seen, ["/assistant?limit=1"]); diff --git a/tests/rate-limit.test.ts b/tests/rate-limit.test.ts index 3f33f06..ba5458f 100644 --- a/tests/rate-limit.test.ts +++ b/tests/rate-limit.test.ts @@ -1,19 +1,38 @@ import assert from "node:assert/strict"; -import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +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 { maxGitopsRpmRead, orgLimiter, TokenBucket } from "../src/rate-limit.ts"; +import { fileURLToPath } from "node:url"; import { orgPinCheck } from "../src/org-pin.ts"; -import { orgSettingsUrl } from "../src/vapi-fetch.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; }); + const limiter = new TokenBucket( + 300, + () => now, + async (ms) => { + waits.push(ms); + now += ms; + }, + ); assert.equal(limiter.capacity, 5); await Promise.all(Array.from({ length: 10 }, () => limiter.acquire())); assert.deepEqual(waits, [200, 200, 200, 200, 200]); @@ -24,7 +43,13 @@ test("token bucket allows a burst, then sustains the configured rate", async () test("low RPM and concurrent requests sustain the cap", async () => { let now = 0; - const limiter = new TokenBucket(30, () => now, async (ms) => { now += ms; }); + const limiter = new TokenBucket( + 30, + () => now, + async (ms) => { + now += ms; + }, + ); assert.equal(limiter.capacity, 1); await Promise.all(Array.from({ length: 3 }, () => limiter.acquire())); assert.equal(now, 4000); @@ -34,7 +59,13 @@ test("low RPM and concurrent requests sustain the cap", async () => { 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; }); + const limiter = new TokenBucket( + 100, + () => now, + async (ms) => { + now += ms; + }, + ); assert.equal(limiter.capacity, 2); await Promise.all(Array.from({ length: 102 }, () => limiter.acquire())); assert.equal(now, 60_000); @@ -59,21 +90,38 @@ test("max GitOps RPM resolves defaults, committed settings and environment prece 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); + 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.throws(() => maxGitopsRpmRead(root, "acme", { VAPI_MAX_GITOPS_RPM: "5" }), /❌.*resources\/acme\/\.vapi-org.json/); + assert.throws( + () => maxGitopsRpmRead(root, "acme", { VAPI_MAX_GITOPS_RPM: "5" }), + /❌.*resources\/acme\/\.vapi-org.json/, + ); } 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/); + 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", { VAPI_MAX_GITOPS_RPM: "5" }), /❌.*\.env.acme/); + assert.throws( + () => maxGitopsRpmRead(root, "acme", { VAPI_MAX_GITOPS_RPM: "5" }), + /❌.*\.env.acme/, + ); } writeFileSync(pin, "{"); - assert.throws(() => maxGitopsRpmRead(root, "acme", {}), /Restore it from git/); - } finally { rmSync(root, { recursive: true, force: true }); } + 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 () => { @@ -81,17 +129,32 @@ test("pinning a settings-only file preserves all existing fields", async () => { 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 } })); + 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" }, + 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" }); + 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; @@ -100,9 +163,18 @@ test("pinning a settings-only file preserves all existing fields", async () => { }); 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"); + 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 () => { @@ -111,25 +183,102 @@ test("429 responses warn once per org and retries consume tokens", async () => { const warnings: string[] = []; const server = createServer((_req, res) => { requests++; - res.writeHead(requests % 2 ? 429 : 200, { "Content-Type": "application/json" }); + 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); - limiter.acquire = async () => { tokens++; }; + limiter.acquire = async () => { + tokens++; + }; const warn = console.warn; - console.warn = (message: string) => { warnings.push(message); }; + 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 () => {} }); + 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]!, /max GitOps RPM.*maxGitopsRpm \/ VAPI_MAX_GITOPS_RPM.*https:\/\/dashboard.vapi.ai\/settings\/organization/); + assert.match( + warnings[0]!, + /max GitOps RPM.*maxGitopsRpm \/ VAPI_MAX_GITOPS_RPM.*https:\/\/dashboard.vapi.ai\/settings\/organization/, + ); assert.match(warnings[0]!, /requests per minute \(200 by default\)/); } 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 }); + } +}); diff --git a/tests/sim-run.test.ts b/tests/sim-run.test.ts index 866fa34..1d1faba 100644 --- a/tests/sim-run.test.ts +++ b/tests/sim-run.test.ts @@ -1,8 +1,8 @@ -import { TokenBucket } from "../src/rate-limit.ts"; 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 @@ -360,7 +360,13 @@ test("simRunItemsFetch: pages until totalItems and dedupes overlapping pages", a ], async (baseUrl) => { const items = await simRunItemsFetch( - { token: "t", baseUrl, userAgent: "test", limiter: new TokenBucket(100), 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 19a4287..719f3ad 100644 --- a/tests/user-agent-coverage.test.ts +++ b/tests/user-agent-coverage.test.ts @@ -77,7 +77,9 @@ test("api.ts requests carry the command's User-Agent", async () => { delete process.env.GITHUB_ACTIONS; try { const { vapiGet } = await import("../src/api.ts"); - const { userAgentGet, vapiClientGet } = await import("../src/user-agent.ts"); + const { userAgentGet, vapiClientGet } = await import( + "../src/user-agent.ts" + ); await vapiGet("/assistant"); assert.deepEqual(seen, [userAgentGet()]); assert.match(seen[0] ?? "", /^vapi-gitops-apply\/[^ ]+$/); @@ -88,8 +90,14 @@ test("api.ts requests carry the command's User-Agent", async () => { ); await Promise.all(Array.from({ length: 9 }, () => vapiGet("/assistant"))); assert.equal(times.length, 10); - assert.ok(times[9]! - times[0]! >= 850, "requests beyond the initial burst must wait for tokens"); - assert.ok(times[9]! - times[8]! >= 140, "sustained requests must be spaced by the cap"); + assert.ok( + times[9]! - times[0]! >= 850, + "requests beyond the initial burst must wait for tokens", + ); + assert.ok( + times[9]! - times[8]! >= 140, + "sustained requests must be spaced by the cap", + ); } finally { await new Promise((resolve) => server.close(() => resolve())); } @@ -100,9 +108,14 @@ test("every Vapi fetch uses the shared limiter and warning path", () => { 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`); + 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(")); + assert.ok( + shared.indexOf("await limiter.acquire()") < shared.indexOf("await fetch("), + ); }); From ee602b3e8355a56b251b8cc522ec0abeb6f2e83c Mon Sep 17 00:00:00 2001 From: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Tue, 17 Nov 2026 09:23:17 +0000 Subject: [PATCH 3/5] fix: share org env parsing and clarify rate limit warnings Co-Authored-By: Roshan Manjaly --- docs/guides/configuration.md | 53 ++++++------- improvements.md | 2 +- src/api.ts | 62 +++++++-------- src/call.ts | 25 +++--- src/check-cmd.ts | 4 +- src/cleanup.ts | 42 +++++----- src/config.ts | 51 +++--------- src/env-file.ts | 15 ++++ src/interactive.ts | 22 +++-- src/org-pin.ts | 6 +- src/promotion-gate.ts | 5 +- src/push.ts | 9 ++- src/rate-limit.ts | 25 +++--- src/rollback-cmd.ts | 31 ++++---- src/setup.ts | 58 ++++++++------ src/sim.ts | 11 ++- src/vapi-client.ts | 28 +++---- src/vapi-fetch.ts | 2 +- tests/check-run.test.ts | 11 +-- tests/org-pin.test.ts | 128 ++++++------------------------ tests/rate-limit.test.ts | 45 ++++++++++- tests/user-agent-coverage.test.ts | 4 +- 22 files changed, 276 insertions(+), 363 deletions(-) create mode 100644 src/env-file.ts diff --git a/docs/guides/configuration.md b/docs/guides/configuration.md index 0bbc8ac..f60a50f 100644 --- a/docs/guides/configuration.md +++ b/docs/guides/configuration.md @@ -8,7 +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 max GitOps RPM for this org: a positive integer. This is a GitOps client limit, not a Vapi org limit; defaults to `maxGitopsRpm` in the committed org settings file, or 100. | +| `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. | @@ -50,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` | Optional `maxGitopsRpm` (default 100) and 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 @@ -63,37 +63,32 @@ Set these in GitHub under **Settings → Secrets and variables → Actions**. ## max GitOps RPM -Set the committed client-side ceiling per org in -`resources//.vapi-org.json`: +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 } ``` -A file containing only `maxGitopsRpm` is also valid before the org is pinned; -pinning preserves this setting and any other existing fields. This is a -**GitOps client limit, not a Vapi org limit**. The Vapi org API limit is -per minute (200 requests per minute by default). Keep max GitOps RPM below -your org's API limit; the default is 100 RPM. Allow additional headroom -for other clients and processes. -All Vapi requests for an org -share a token bucket in a process, including probes, reads, writes and retries. -The bucket refills at `maxGitopsRpm / 60` tokens per second, with burst -capacity `max(1, ceil(maxGitopsRpm / 60))`. It starts full, so a short burst -can exceed the average rate slightly; it does not reserve the whole org quota. -Separate orgs have separate buckets; separate -processes do not coordinate. Existing write gaps and retry backoff still apply. - -Resolution: shell/CI `VAPI_MAX_GITOPS_RPM`, then `.env.` (with the -usual fallback env files), then committed `maxGitopsRpm`, then 100. -Values must be positive integers. An invalid configured value stops the -command before requests, naming its source even when another setting overrides -it. No API keys are printed. - -On a 429, GitOps warns once per org per process that max GitOps RPM -(`maxGitopsRpm` / `VAPI_MAX_GITOPS_RPM`) may be too high. It links to the -org-level API rate limit in the dashboard matching that org's API base URL: -[EU](https://dashboard.eu.vapi.ai/settings/organization) for +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 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. + +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). -Lower the client ceiling if necessary; retries retain their existing backoff. +Existing retry backoff and write gaps still apply. + +Each org shares one token bucket per process. It refills at +`maxGitopsRpm / 60` tokens per second, with a small burst capacity of +`max(1, ceil(maxGitopsRpm / 60))`. Separate processes do not coordinate, +so their combined traffic can exceed the client ceiling. diff --git a/improvements.md b/improvements.md index 7ac9a2a..f06bf8a 100644 --- a/improvements.md +++ b/improvements.md @@ -2085,4 +2085,4 @@ dependency check, as `check-payload.ts` already does. - **Current mitigation:** Committed `maxGitopsRpm` (default 100), overridden by `VAPI_MAX_GITOPS_RPM`; invalid 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 backoff and write gaps retained. 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. +- **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 9a4d605..c01b436 100644 --- a/src/api.ts +++ b/src/api.ts @@ -75,6 +75,7 @@ export function orgPinGuard(): Promise { return orgPinChecked; } + export function getDryRunCounts(): { POST: number; PATCH: number; @@ -150,20 +151,17 @@ export async function vapiRequest( for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) { await throttle(); - const response = await limitedVapiFetch( - orgLimiter(BASE_DIR, VAPI_ENV, MAX_GITOPS_RPM), - url, - { - method, - headers: { - "Content-Type": "application/json", - Authorization: `Bearer ${VAPI_TOKEN}`, - "User-Agent": userAgentGet(), - "x-vapi-client": vapiClientGet(), - }, - body: JSON.stringify(body), + const limiter = orgLimiter(BASE_DIR, VAPI_ENV, MAX_GITOPS_RPM); + const response = await limitedVapiFetch(limiter, url, { + method, + headers: { + "Content-Type": "application/json", + Authorization: `Bearer ${VAPI_TOKEN}`, + "User-Agent": userAgentGet(), + "x-vapi-client": vapiClientGet(), }, - ); + body: JSON.stringify(body), + }); if (response.ok) { return response.json() as Promise; @@ -200,18 +198,15 @@ export async function vapiGet(endpoint: string): Promise { const url = `${VAPI_BASE_URL}${endpoint}`; for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) { - const response = await limitedVapiFetch( - orgLimiter(BASE_DIR, VAPI_ENV, MAX_GITOPS_RPM), - url, - { - method: "GET", - headers: { - Authorization: `Bearer ${VAPI_TOKEN}`, - "User-Agent": userAgentGet(), - "x-vapi-client": vapiClientGet(), - }, + const limiter = orgLimiter(BASE_DIR, VAPI_ENV, MAX_GITOPS_RPM); + const response = await limitedVapiFetch(limiter, url, { + method: "GET", + headers: { + Authorization: `Bearer ${VAPI_TOKEN}`, + "User-Agent": userAgentGet(), + "x-vapi-client": vapiClientGet(), }, - ); + }); if (response.ok) { return response.json() as Promise; @@ -255,18 +250,15 @@ export async function vapiDelete(endpoint: string): Promise { for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) { await throttle(); - const response = await limitedVapiFetch( - orgLimiter(BASE_DIR, VAPI_ENV, MAX_GITOPS_RPM), - url, - { - method: "DELETE", - headers: { - Authorization: `Bearer ${VAPI_TOKEN}`, - "User-Agent": userAgentGet(), - "x-vapi-client": vapiClientGet(), - }, + const limiter = orgLimiter(BASE_DIR, VAPI_ENV, MAX_GITOPS_RPM); + const response = await limitedVapiFetch(limiter, url, { + method: "DELETE", + headers: { + Authorization: `Bearer ${VAPI_TOKEN}`, + "User-Agent": userAgentGet(), + "x-vapi-client": vapiClientGet(), }, - ); + }); if (response.ok) { return; diff --git a/src/call.ts b/src/call.ts index 7a820b1..cb7ee5a 100644 --- a/src/call.ts +++ b/src/call.ts @@ -1,10 +1,10 @@ +import { missingApiKeyMessage, resolveOrgApiKey } from "./api-key.ts"; import { execSync } from "child_process"; import { existsSync, readFileSync } from "fs"; import { createRequire } from "module"; import { dirname, join, resolve } from "path"; import * as readline from "readline"; import { fileURLToPath } from "url"; -import { missingApiKeyMessage, resolveOrgApiKey } from "./api-key.ts"; import { orgLimiterOrExit } from "./rate-limit.ts"; import type { Environment, StateFile } from "./types.ts"; import { userAgentGet, vapiClientGet } from "./user-agent.ts"; @@ -362,20 +362,17 @@ async function createCall( console.log(`📞 Creating call...`); - const response = await limitedVapiFetch( - orgLimiterOrExit(BASE_DIR, config.env), - url, - { - method: "POST", - headers: { - "Content-Type": "application/json", - Authorization: `Bearer ${config.token}`, - "User-Agent": userAgentGet(), - "x-vapi-client": vapiClientGet(), - }, - body: JSON.stringify(body), + const limiter = orgLimiterOrExit(BASE_DIR, config.env); + const response = await limitedVapiFetch(limiter, url, { + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: `Bearer ${config.token}`, + "User-Agent": userAgentGet(), + "x-vapi-client": vapiClientGet(), }, - ); + body: JSON.stringify(body), + }); if (!response.ok) { const errorText = await response.text(); diff --git a/src/check-cmd.ts b/src/check-cmd.ts index c65945d..ef99431 100644 --- a/src/check-cmd.ts +++ b/src/check-cmd.ts @@ -1,4 +1,3 @@ -import { orgLimiterOrExit } from "./rate-limit.ts"; // CLI entry: `npm run check -- |--all [options]` // // Builds each check target's inline simulation-run payload from the files @@ -22,7 +21,7 @@ import type { CheckReportSkipped } from "./check-report.ts"; import { checkReportJson, checkReportMarkdown } from "./check-report.ts"; import type { CheckTargetResult } from "./check-run.ts"; import { checkRunAll, outcomeState } from "./check-run.ts"; -import { changedFilesRead, checkAffectedBy } from "./check-select.ts"; +import { checkAffectedBy, changedFilesRead } from "./check-select.ts"; import type { CommitStatus, GitHubStatusEnv } from "./check-status.ts"; import { AGGREGATE_CONTEXT, @@ -33,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"; diff --git a/src/cleanup.ts b/src/cleanup.ts index 83ff673..2a16e9c 100644 --- a/src/cleanup.ts +++ b/src/cleanup.ts @@ -1,15 +1,15 @@ import { resolve } from "path"; import { fileURLToPath } from "url"; -import { orgPinGuard } from "./api.ts"; import { BASE_DIR, loadIgnorePatterns, - MAX_GITOPS_RPM, 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"; @@ -35,17 +35,15 @@ function isRecord(value: unknown): value is Record { async function vapiGet(endpoint: string, debug = false): Promise { await orgPinGuard(); await sleep(REQUEST_DELAY_MS); - const response = await limitedVapiFetch( - orgLimiter(BASE_DIR, VAPI_ENV, MAX_GITOPS_RPM), - `${VAPI_BASE_URL}${endpoint}`, - { - headers: { - Authorization: `Bearer ${VAPI_TOKEN}`, - "User-Agent": userAgentGet(), - "x-vapi-client": vapiClientGet(), - }, + 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(), + "x-vapi-client": vapiClientGet(), }, - ); + }); if (!response.ok) { throw new Error(`GET ${endpoint} failed: ${response.status}`); } @@ -81,18 +79,16 @@ async function vapiGet(endpoint: string, debug = false): Promise { async function vapiDelete(endpoint: string): Promise { await orgPinGuard(); await sleep(REQUEST_DELAY_MS); - const response = await limitedVapiFetch( - orgLimiter(BASE_DIR, VAPI_ENV, MAX_GITOPS_RPM), - `${VAPI_BASE_URL}${endpoint}`, - { - method: "DELETE", - headers: { - Authorization: `Bearer ${VAPI_TOKEN}`, - "User-Agent": userAgentGet(), - "x-vapi-client": vapiClientGet(), - }, + 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}`, + "User-Agent": userAgentGet(), + "x-vapi-client": vapiClientGet(), }, - ); + }); if (!response.ok && response.status !== 404) { throw new Error(`DELETE ${endpoint} failed: ${response.status}`); } diff --git a/src/config.ts b/src/config.ts index 48a5ff2..e559366 100644 --- a/src/config.ts +++ b/src/config.ts @@ -1,14 +1,14 @@ -import { existsSync, readFileSync } from "fs"; -import { basename, dirname, join, relative, resolve } from "path"; -import { fileURLToPath } from "url"; import { missingApiKeyMessage, resolveOrgApiKey } from "./api-key.ts"; +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, } from "./resource-parse.ts"; import { resolveResourceTypes, VALID_TYPE_ARGS } from "./resource-type-args.ts"; -import type { Environment, ResourceType } from "./types.ts"; // ───────────────────────────────────────────────────────────────────────────── // CLI Argument Parsing @@ -53,6 +53,7 @@ function parseEnvironment(): Environment { return envArg; } + function parseFlags(): { forceDelete: boolean; bootstrapSync: boolean; @@ -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 (key !== "VAPI_MAX_GITOPS_RPM" && 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,7 @@ 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 { 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 4e5716b..ff82688 100644 --- a/src/interactive.ts +++ b/src/interactive.ts @@ -1,9 +1,9 @@ +import { missingApiKeyMessage, resolveOrgApiKey } from "./api-key.ts"; import { confirm, select } from "@inquirer/prompts"; import { execSync } from "child_process"; import { existsSync, readdirSync, readFileSync, statSync } from "fs"; import { dirname, extname, join, relative } from "path"; import { fileURLToPath } from "url"; -import { missingApiKeyMessage, resolveOrgApiKey } from "./api-key.ts"; 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 @@ -227,18 +227,16 @@ async function apiGet( endpoint: string, org: string, ): Promise { - const response = await limitedVapiFetch( - orgLimiterOrExit(BASE_DIR, org), - `${baseUrl}${endpoint}`, - { - method: "GET", - headers: { - Authorization: `Bearer ${token}`, - "User-Agent": userAgentGet(), - "x-vapi-client": vapiClientGet(), - }, + const limiter = orgLimiterOrExit(BASE_DIR, org); + const url = `${baseUrl}${endpoint}`; + const response = await limitedVapiFetch(limiter, url, { + method: "GET", + headers: { + Authorization: `Bearer ${token}`, + "User-Agent": userAgentGet(), + "x-vapi-client": vapiClientGet(), }, - ); + }); if (!response.ok) { const text = await response.text(); throw new Error(`API GET ${endpoint} failed (${response.status}): ${text}`); diff --git a/src/org-pin.ts b/src/org-pin.ts index c2ceb2d..73d204b 100644 --- a/src/org-pin.ts +++ b/src/org-pin.ts @@ -18,8 +18,8 @@ import { existsSync, readFileSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { orgApiKeyVar } from "./api-key.ts"; import { - VapiApiError, type VapiConnection, + VapiApiError, vapiFetchJson, } from "./vapi-client.ts"; @@ -138,9 +138,7 @@ export interface OrgPinCheckArgs { * key belongs to another org, or to an empty org while the folder is pinned * to one that had resources. */ -export async function orgPinCheck( - args: OrgPinCheckArgs, -): Promise { +export async function orgPinCheck(args: OrgPinCheckArgs): Promise { const { rootDir, org, connection, keySource } = args; // Set only by tests/no-vapi-api.ts: tests that stub fetch count requests. if (process.env.VAPI_GITOPS_ORG_PIN === "off") return { kind: "unpinned" }; diff --git a/src/promotion-gate.ts b/src/promotion-gate.ts index 4809b73..2a9b5bc 100644 --- a/src/promotion-gate.ts +++ b/src/promotion-gate.ts @@ -1,16 +1,15 @@ -import { orgLimiterOrExit } from "./rate-limit.ts"; - // The promotion check gate: `orgs..check: ` in promotion.yml // names a vapi-checks.yml check that must pass in that org before any // transition promotes out of it. The gate runs the same check as the PR // workflow, built from the source org's files at the promoted commit. -import { checkJobsBuild } from "./check-build.ts"; import type { CheckDefinition } from "./check-config.ts"; import { CHECKS_CONFIG_FILE, checksConfigLoad } from "./check-config.ts"; +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"; diff --git a/src/push.ts b/src/push.ts index f9b53eb..2678186 100644 --- a/src/push.ts +++ b/src/push.ts @@ -11,12 +11,12 @@ import { DRY_RUN, FORCE_DELETE, loadIgnorePatterns, - MAX_GITOPS_RPM, OVERWRITE_DRIFT, RESOURCES_DIR, removeExcludedKeys, STATE_FILE_PATH, STRICT_VALIDATION, + MAX_GITOPS_RPM, VAPI_BASE_URL, VAPI_ENV, } from "./config.ts"; @@ -29,7 +29,6 @@ import { checkDriftForUpdate, type DriftCheckResult } from "./drift.ts"; import { deleteBaseline, writeBaseline } from "./hash-store.ts"; import { assertStateMigrated } from "./migrate-hash-store.ts"; import { detectOrphanYamls, formatGateMessage } from "./new-file-gate.ts"; -import { orgLimiter } from "./rate-limit.ts"; import { formatRecanonicalizeReport, recanonicalizeStateKeys, @@ -44,7 +43,6 @@ import { validateResources, } from "./validate.ts"; import { validateReferences } from "./validate-refs.ts"; -import { limitedVapiFetch } from "./vapi-fetch.ts"; import { changedFieldPaths, versionActorResolve, @@ -96,6 +94,8 @@ import type { ResourceType, StateFile, } from "./types.ts"; +import { orgLimiter } from "./rate-limit.ts"; +import { limitedVapiFetch } from "./vapi-fetch.ts"; // ───────────────────────────────────────────────────────────────────────────── // Error Formatting @@ -354,8 +354,9 @@ async function upsertResourceWithStateRecovery(options: { const resourceType = RESOURCE_LABEL_TO_TYPE[resourceLabel]; if (resourceType) { if (platformPayloadForSnapshot === undefined) { + const limiter = orgLimiter(BASE_DIR, VAPI_ENV, MAX_GITOPS_RPM); const platformResponse = await limitedVapiFetch( - orgLimiter(BASE_DIR, VAPI_ENV, MAX_GITOPS_RPM), + limiter, `${VAPI_BASE_URL}${updateEndpoint}`, { method: "GET", diff --git a/src/rate-limit.ts b/src/rate-limit.ts index 571bf25..77c7038 100644 --- a/src/rate-limit.ts +++ b/src/rate-limit.ts @@ -1,5 +1,6 @@ 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; @@ -22,7 +23,7 @@ function positive(value: unknown, source: string): number { export function maxGitopsRpmRead( rootDir: string, org: string, - env: NodeJS.ProcessEnv = process.env, + env: NodeJS.ProcessEnv = shellEnvironment, ): number { const pin = join(rootDir, "resources", org, ".vapi-org.json"); let value = DEFAULT_MAX_GITOPS_RPM; @@ -43,18 +44,13 @@ export function maxGitopsRpmRead( ); } let fileValue: number | undefined; - for (const name of [`.env.${org}`, `.env.${org}.local`, ".env.local"]) { - const path = join(rootDir, name); - if (!existsSync(path)) continue; - for (const line of readFileSync(path, "utf8").split("\n")) { - const match = /^\s*VAPI_MAX_GITOPS_RPM\s*=\s*(.*?)\s*$/.exec(line); - if (match) { - const number = positive( - match[1]!.replace(/^(["'])(.*)\1$/, "$2"), - `${name} VAPI_MAX_GITOPS_RPM`, - ); - fileValue ??= number; - } + for (const { name, values } of orgEnvFilesRead(rootDir, org)) { + if (values.VAPI_MAX_GITOPS_RPM !== undefined) { + const number = positive( + values.VAPI_MAX_GITOPS_RPM, + `${name} VAPI_MAX_GITOPS_RPM`, + ); + fileValue ??= number; } } return env.VAPI_MAX_GITOPS_RPM === undefined @@ -72,6 +68,7 @@ export class TokenBucket { 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.ceil(rpm / 60)); @@ -118,7 +115,7 @@ export function orgLimiter( const key = `${resolve(rootDir)}\0${org}`; let limiter = buckets.get(key); if (!limiter) { - limiter = new TokenBucket(rpm); + limiter = new TokenBucket(rpm, undefined, undefined, org); buckets.set(key, limiter); } return limiter; diff --git a/src/rollback-cmd.ts b/src/rollback-cmd.ts index db88909..8c46524 100644 --- a/src/rollback-cmd.ts +++ b/src/rollback-cmd.ts @@ -1,6 +1,3 @@ -import { orgLimiterOrExit } from "./rate-limit.ts"; -import { limitedVapiFetch } from "./vapi-fetch.ts"; - // CLI entry: `npm run rollback -- --to ` | // `npm run rollback -- --list` // @@ -11,13 +8,15 @@ import { limitedVapiFetch } from "./vapi-fetch.ts"; // Self-contained (does not import config.ts) so it can run in isolation // without triggering the global CLI parser. +import { missingApiKeyMessage, resolveOrgApiKey } from "./api-key.ts"; import { existsSync, readFileSync } from "fs"; import { dirname, join } from "path"; import { fileURLToPath } from "url"; -import { missingApiKeyMessage, resolveOrgApiKey } from "./api-key.ts"; 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, ".."); @@ -214,20 +213,18 @@ async function main(): Promise { process.stdout.write( ` 🔁 ${entry.resourceType}/${entry.resourceId} ... `, ); - const response = await limitedVapiFetch( - orgLimiterOrExit(BASE_DIR, cfg.env), - `${cfg.baseUrl}${endpoint}/${uuid}`, - { - method: "PATCH", - headers: { - Authorization: `Bearer ${cfg.token}`, - "Content-Type": "application/json", - "User-Agent": userAgentGet(), - "x-vapi-client": vapiClientGet(), - }, - body: JSON.stringify(entry.payload.platform), + 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}`, + "Content-Type": "application/json", + "User-Agent": userAgentGet(), + "x-vapi-client": vapiClientGet(), }, - ); + body: JSON.stringify(entry.payload.platform), + }); if (!response.ok) { const text = await response.text(); console.log(`❌ ${response.status}`); diff --git a/src/setup.ts b/src/setup.ts index 90056a4..10facee 100644 --- a/src/setup.ts +++ b/src/setup.ts @@ -40,7 +40,12 @@ const VAPI_REGIONS: Record = { eu: "https://api.eu.vapi.ai", }; let requestOrg: string | undefined; -const validationLimiter = new TokenBucket(DEFAULT_MAX_GITOPS_RPM); +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; @@ -102,18 +107,17 @@ const c = { // ───────────────────────────────────────────────────────────────────────────── async function apiGet(token: string, endpoint: string): Promise { - const response = await limitedVapiFetch( - requestOrg ? orgLimiterOrExit(BASE_DIR, requestOrg) : validationLimiter, - `${vapiBaseUrl}${endpoint}`, - { - method: "GET", - headers: { - Authorization: `Bearer ${token}`, - "User-Agent": userAgentGet(), - "x-vapi-client": vapiClientGet(), - }, + const limiter = requestOrg + ? orgLimiterOrExit(BASE_DIR, requestOrg) + : validationLimiter; + const response = await limitedVapiFetch(limiter, `${vapiBaseUrl}${endpoint}`, { + method: "GET", + headers: { + Authorization: `Bearer ${token}`, + "User-Agent": userAgentGet(), + "x-vapi-client": vapiClientGet(), }, - ); + }); if (!response.ok) { const text = await response.text(); @@ -428,9 +432,7 @@ async function runDirectSetup(options: DirectSetupOptions): Promise { const resourceDir = join(BASE_DIR, "resources", slug); const stateFile = join(BASE_DIR, `.vapi-state.${slug}.json`); - console.log( - c.bold(`\n Vapi GitOps — non-interactive setup for "${slug}"\n`), - ); + console.log(c.bold(`\n Vapi GitOps — non-interactive setup for "${slug}"\n`)); // Never clobber an org that already has local state. Re-running setup is // a destructive operation in the wizard (it deletes and re-pulls), and an @@ -463,9 +465,7 @@ async function runDirectSetup(options: DirectSetupOptions): Promise { // Setup writes the key into .env. and downloads that org, so a key // that may belong to another org is a hard stop here, not a warning. if (resolved.warning) { - fail( - `${resolved.warning}\n Setup stopped before writing .env.${slug} or downloading anything.`, - ); + fail(`${resolved.warning}\n Setup stopped before writing .env.${slug} or downloading anything.`); } const otherOrg = orgWithKey(slug, resolved.token); if (otherOrg) { @@ -585,9 +585,7 @@ async function main(): Promise { // so explain the non-interactive path instead. if (!process.stdin.isTTY) { console.error( - c.red( - "\n ✗ The setup wizard needs an interactive terminal (stdin is not a TTY).\n", - ), + c.red("\n ✗ The setup wizard needs an interactive terminal (stdin is not a TTY).\n"), ); console.error(SETUP_USAGE); process.exit(1); @@ -675,15 +673,18 @@ async function main(): Promise { message: "Folder name for this org (e.g. my-org, my-org-prod)", validate: (value) => { const slug = slugify(value); - return slug && SLUG_RE.test(slug) - ? true - : "Must be lowercase alphanumeric with hyphens (e.g. my-org-name)"; + if (!slug || !SLUG_RE.test(slug)) { + return "Must be lowercase alphanumeric with hyphens (e.g. my-org-name)"; + } + return true; }, transformer: (value) => { const slug = slugify(value); - return slug && slug !== value ? `${value} → ${c.dim(slug)}` : value; + if (slug && slug !== value) return `${value} → ${c.dim(slug)}`; + return value; }, }); + const slug = slugify(rawSlug); requestOrg = slug; orgLimiterOrExit(BASE_DIR, slug); @@ -835,7 +836,12 @@ async function main(): Promise { console.log(c.bold(" Downloading...\n")); - invokePull(slug, downloadAll ? "all" : selectedIds, trimmedKey, vapiBaseUrl); + invokePull( + slug, + downloadAll ? "all" : selectedIds, + trimmedKey, + vapiBaseUrl, + ); // ── Done ────────────────────────────────────────────────────────────── diff --git a/src/sim.ts b/src/sim.ts index d64ff4f..6184555 100644 --- a/src/sim.ts +++ b/src/sim.ts @@ -1,29 +1,28 @@ -import { orgLimiterOrExit } from "./rate-limit.ts"; - // Simulation runner — wraps `POST /eval/simulation/run`. // // Designed to be importable from `sim-cmd.ts` and from tests without // triggering the CLI argument parser in `config.ts`. Env-loading is inlined // here (rather than importing from `config.ts`) for the same reason. +import { missingApiKeyMessage, resolveOrgApiKey } from "./api-key.ts"; import { existsSync, readFileSync } from "fs"; import { dirname, join } from "path"; import { fileURLToPath } from "url"; -import { missingApiKeyMessage, resolveOrgApiKey } from "./api-key.ts"; +import { orgLimiterOrExit } from "./rate-limit.ts"; import { + simRunItemTerminal, + simRunVerdict, type SimRun, type SimRunItem, type SimRunItemCounts, type SimRunVerdict, - simRunItemTerminal, - simRunVerdict, } from "./sim-result.ts"; import type { StateFile } from "./types.ts"; import { userAgentGet, vapiClientGet } from "./user-agent.ts"; import { VapiApiError, - type VapiConnection, vapiFetchJson, + type VapiConnection, } from "./vapi-client.ts"; const __dirname = dirname(fileURLToPath(import.meta.url)); diff --git a/src/vapi-client.ts b/src/vapi-client.ts index ed77bfa..259a6a9 100644 --- a/src/vapi-client.ts +++ b/src/vapi-client.ts @@ -1,5 +1,3 @@ -import type { TokenBucket } from "./rate-limit.ts"; -import { limitedVapiFetch } from "./vapi-fetch.ts"; // Config-free HTTP client for the Vapi API. // // api.ts is the engine's client, but it imports config.ts, which parses @@ -8,6 +6,9 @@ import { limitedVapiFetch } from "./vapi-fetch.ts"; // 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; @@ -86,20 +87,17 @@ export async function vapiFetchJson( const sleep = options.sleep ?? sleepDefault; for (let attempt = 0; ; attempt++) { - const response = await limitedVapiFetch( - connection.limiter, - `${connection.baseUrl}${endpoint}`, - { - method, - headers: { - Authorization: `Bearer ${connection.token}`, - "Content-Type": "application/json", - "User-Agent": connection.userAgent, - "x-vapi-client": connection.vapiClient, - }, - ...(body === undefined ? {} : { body: JSON.stringify(body) }), + const url = `${connection.baseUrl}${endpoint}`; + const response = await limitedVapiFetch(connection.limiter, url, { + method, + headers: { + Authorization: `Bearer ${connection.token}`, + "Content-Type": "application/json", + "User-Agent": connection.userAgent, + "x-vapi-client": connection.vapiClient, }, - ); + ...(body === undefined ? {} : { body: JSON.stringify(body) }), + }); if (response.ok) { const text = await response.text(); return (text ? JSON.parse(text) : null) as T; diff --git a/src/vapi-fetch.ts b/src/vapi-fetch.ts index f76c796..85833d0 100644 --- a/src/vapi-fetch.ts +++ b/src/vapi-fetch.ts @@ -26,7 +26,7 @@ export async function limitedVapiFetch( if (response.status === 429 && !warned.has(limiter)) { warned.add(limiter); console.warn( - `⚠️ max GitOps RPM (maxGitopsRpm / VAPI_MAX_GITOPS_RPM) may be configured too high. This is a GitOps client limit, not a Vapi org limit. Compare it with your org-level API rate limit in requests per minute (200 by default): ${orgSettingsUrl(url)}`, + `⚠️ 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/check-run.test.ts b/tests/check-run.test.ts index da87bf1..feef884 100644 --- a/tests/check-run.test.ts +++ b/tests/check-run.test.ts @@ -2,26 +2,19 @@ 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"; import type { CheckRunBody } from "../src/check-payload.ts"; import type { CheckRunArgs, CheckTargetResult } from "../src/check-run.ts"; import { checkRunAll, MIN_START_MS } from "../src/check-run.ts"; -import { TokenBucket } from "../src/rate-limit.ts"; // checkRunAll against a stateful stub of the simulations API. The target // assistant's name picks the stub's behaviour for that run. type Behaviour = - | "pass" - | "fail" - | "skipped" - | "hang" - | "slow" - | "unmocked" - | "402" - | "502"; + "pass" | "fail" | "skipped" | "hang" | "slow" | "unmocked" | "402" | "502"; interface StubRun { id: string; diff --git a/tests/org-pin.test.ts b/tests/org-pin.test.ts index feb996d..3f364e8 100644 --- a/tests/org-pin.test.ts +++ b/tests/org-pin.test.ts @@ -69,24 +69,13 @@ function orgDir(options: { folder: boolean; pin?: string }): string { } const serverError = new VapiApiError("GET", "/tool", 503, "unavailable", ""); -const unauthorized = new VapiApiError( - "GET", - "/assistant", - 401, - "Unauthorized", - "", -); +const unauthorized = new VapiApiError("GET", "/assistant", 401, "Unauthorized", ""); // ── Finding the key's org ──────────────────────────────────────────────── test("keyOrgFetch reads orgId from the first resource listed", async () => { - const { probeFetch, seen } = probes({ - "/assistant": [{ id: "a1", orgId: "org-a" }], - }); - assert.deepEqual(await keyOrgFetch(CONNECTION, probeFetch), { - kind: "found", - orgId: "org-a", - }); + const { probeFetch, seen } = probes({ "/assistant": [{ id: "a1", orgId: "org-a" }] }); + assert.deepEqual(await keyOrgFetch(CONNECTION, probeFetch), { kind: "found", orgId: "org-a" }); assert.deepEqual(seen, ["/assistant?limit=1"]); }); @@ -94,17 +83,12 @@ test("keyOrgFetch moves on from empty lists and reads { results } pages", async const { probeFetch, seen } = probes({ "/structured-output": { results: [{ id: "s1", orgId: "org-a" }] }, }); - assert.deepEqual(await keyOrgFetch(CONNECTION, probeFetch), { - kind: "found", - orgId: "org-a", - }); + assert.deepEqual(await keyOrgFetch(CONNECTION, probeFetch), { kind: "found", orgId: "org-a" }); assert.equal(seen.length, 6); }); test("keyOrgFetch reports an org that lists nothing as empty", async () => { - assert.deepEqual(await keyOrgFetch(CONNECTION, probes({}).probeFetch), { - kind: "empty", - }); + assert.deepEqual(await keyOrgFetch(CONNECTION, probes({}).probeFetch), { kind: "empty" }); }); test("keyOrgFetch reports unknown when a probe fails and none finds an org", async () => { @@ -116,9 +100,7 @@ test("keyOrgFetch reports unknown when a probe fails and none finds an org", asy test("keyOrgFetch stops at a rejected key", async () => { const { probeFetch, seen } = probes({ "/assistant": unauthorized }); - assert.deepEqual(await keyOrgFetch(CONNECTION, probeFetch), { - kind: "unknown", - }); + assert.deepEqual(await keyOrgFetch(CONNECTION, probeFetch), { kind: "unknown" }); assert.deepEqual(seen, ["/assistant?limit=1"]); }); @@ -128,13 +110,7 @@ test("orgPinCheck pins an unpinned folder to the key's org", async () => { const root = orgDir({ folder: true }); try { const { probeFetch } = probes({ "/assistant": [{ orgId: "org-a" }] }); - const outcome = await orgPinCheck({ - rootDir: root, - org: "acme", - connection: CONNECTION, - keySource: SOURCE, - probeFetch, - }); + const outcome = await orgPinCheck({ rootDir: root, org: "acme", connection: CONNECTION, keySource: SOURCE, probeFetch }); assert.deepEqual(outcome, { kind: "pinned", orgId: "org-a" }); assert.equal( readFileSync(join(root, "resources", "acme", ORG_PIN_FILE), "utf8"), @@ -149,13 +125,7 @@ test("orgPinCheck makes no request for an org with no folder and no pin", async const root = orgDir({ folder: false }); try { const { probeFetch, seen } = probes({ "/assistant": [{ orgId: "org-a" }] }); - const outcome = await orgPinCheck({ - rootDir: root, - org: "acme", - connection: CONNECTION, - keySource: SOURCE, - probeFetch, - }); + const outcome = await orgPinCheck({ rootDir: root, org: "acme", connection: CONNECTION, keySource: SOURCE, probeFetch }); assert.deepEqual(outcome, { kind: "unpinned" }); assert.deepEqual(seen, []); assert.equal(existsSync(join(root, "resources")), false); @@ -169,13 +139,7 @@ test("orgPinCheck passes a key for the pinned org", async () => { try { const { probeFetch } = probes({ "/assistant": [{ orgId: "org-a" }] }); assert.deepEqual( - await orgPinCheck({ - rootDir: root, - org: "acme", - connection: CONNECTION, - keySource: SOURCE, - probeFetch, - }), + await orgPinCheck({ rootDir: root, org: "acme", connection: CONNECTION, keySource: SOURCE, probeFetch }), { kind: "match" }, ); } finally { @@ -188,21 +152,12 @@ test("orgPinCheck refuses a key for another org, naming both orgs and the source try { const { probeFetch } = probes({ "/assistant": [{ orgId: "org-b" }] }); await assert.rejects( - orgPinCheck({ - rootDir: root, - org: "acme", - connection: CONNECTION, - keySource: SOURCE, - probeFetch, - }), + orgPinCheck({ rootDir: root, org: "acme", connection: CONNECTION, keySource: SOURCE, probeFetch }), (error: Error) => { assert.ok(error instanceof OrgPinMismatchError); assert.match(error.message, /belongs to Vapi org org-b/); assert.match(error.message, /pinned to org org-a/); - assert.match( - error.message, - /VAPI_PRIVATE_API_KEY_ACME environment variable/, - ); + assert.match(error.message, /VAPI_PRIVATE_API_KEY_ACME environment variable/); assert.doesNotMatch(error.message, /test-token-not-used/); return true; }, @@ -216,13 +171,7 @@ test("orgPinCheck refuses a key whose org is empty when the folder is pinned", a const root = orgDir({ folder: true, pin: '{"orgId":"org-a"}' }); try { await assert.rejects( - orgPinCheck({ - rootDir: root, - org: "acme", - connection: CONNECTION, - keySource: SOURCE, - probeFetch: probes({}).probeFetch, - }), + orgPinCheck({ rootDir: root, org: "acme", connection: CONNECTION, keySource: SOURCE, probeFetch: probes({}).probeFetch }), /belongs to an org with no resources/, ); } finally { @@ -235,13 +184,7 @@ test("orgPinCheck can't verify when the probes fail, and says so", async () => { try { const { probeFetch } = probes({ "/assistant": serverError }); assert.deepEqual( - await orgPinCheck({ - rootDir: root, - org: "acme", - connection: CONNECTION, - keySource: SOURCE, - probeFetch, - }), + await orgPinCheck({ rootDir: root, org: "acme", connection: CONNECTION, keySource: SOURCE, probeFetch }), { kind: "unverified" }, ); } finally { @@ -252,10 +195,7 @@ test("orgPinCheck can't verify when the probes fail, and says so", async () => { test("orgPinRead names the file when the pin is corrupt", () => { const root = orgDir({ folder: true, pin: "{not json" }); try { - assert.throws( - () => orgPinRead(root, "acme"), - /resources\/acme\/\.vapi-org\.json/, - ); + assert.throws(() => orgPinRead(root, "acme"), /resources\/acme\/\.vapi-org\.json/); } finally { rmSync(root, { recursive: true, force: true }); } @@ -278,38 +218,20 @@ test("pull stops before listing anything when the key belongs to another org", a cpSync(join(REPO, "package.json"), join(dir, "package.json")); symlinkSync(join(REPO, "node_modules"), join(dir, "node_modules"), "dir"); mkdirSync(join(dir, "resources", "acme"), { recursive: true }); - writeFileSync( - join(dir, "resources", "acme", ORG_PIN_FILE), - '{"orgId":"org-a"}\n', - ); - writeFileSync( - join(dir, ".env.acme"), - "VAPI_PRIVATE_API_KEY=wrong-org-key\n", - ); - const env: NodeJS.ProcessEnv = { - ...process.env, - VAPI_BASE_URL: `http://127.0.0.1:${port}`, - }; + writeFileSync(join(dir, "resources", "acme", ORG_PIN_FILE), '{"orgId":"org-a"}\n'); + writeFileSync(join(dir, ".env.acme"), "VAPI_PRIVATE_API_KEY=wrong-org-key\n"); + const env: NodeJS.ProcessEnv = { ...process.env, VAPI_BASE_URL: `http://127.0.0.1:${port}` }; delete env.VAPI_GITOPS_ORG_PIN; // Async spawn: the stub server runs in this process. - const result = await new Promise<{ code: number | null; output: string }>( - (resolve) => { - const child = spawn( - process.execPath, - ["--import", "tsx", "src/pull.ts", "acme"], - { cwd: dir, env }, - ); - let output = ""; - child.stdout.on("data", (chunk) => (output += chunk)); - child.stderr.on("data", (chunk) => (output += chunk)); - child.on("close", (code) => resolve({ code, output })); - }, - ); + const result = await new Promise<{ code: number | null; output: string }>((resolve) => { + const child = spawn(process.execPath, ["--import", "tsx", "src/pull.ts", "acme"], { cwd: dir, env }); + let output = ""; + child.stdout.on("data", (chunk) => (output += chunk)); + child.stderr.on("data", (chunk) => (output += chunk)); + child.on("close", (code) => resolve({ code, output })); + }); assert.equal(result.code, 1); - assert.match( - result.output, - /belongs to Vapi org org-b, but resources\/acme\/ is pinned to org org-a/, - ); + assert.match(result.output, /belongs to Vapi org org-b, but resources\/acme\/ is pinned to org org-a/); assert.doesNotMatch(result.output, /wrong-org-key/); // Only the probe went out: no listing, no writes. assert.deepEqual(seen, ["/assistant?limit=1"]); diff --git a/tests/rate-limit.test.ts b/tests/rate-limit.test.ts index ba5458f..ac1bef7 100644 --- a/tests/rate-limit.test.ts +++ b/tests/rate-limit.test.ts @@ -190,7 +190,7 @@ test("429 responses warn once per org and retries consume tokens", async () => { }); await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); const { port } = server.address() as AddressInfo; - const limiter = new TokenBucket(2); + const limiter = new TokenBucket(2, undefined, undefined, "acme"); limiter.acquire = async () => { tokens++; }; @@ -215,9 +215,17 @@ test("429 responses warn once per org and retries consume tokens", async () => { assert.equal(warnings.length, 1); assert.match( warnings[0]!, - /max GitOps RPM.*maxGitopsRpm \/ VAPI_MAX_GITOPS_RPM.*https:\/\/dashboard.vapi.ai\/settings\/organization/, + /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/, ); - assert.match(warnings[0]!, /requests per minute \(200 by default\)/); } finally { console.warn = warn; await new Promise((resolve) => server.close(() => resolve())); @@ -282,3 +290,34 @@ test("invalid committed RPM exits config-free callers without a stack", () => { 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 # invalid even with an override\n", + ); + assert.throws( + () => maxGitopsRpmRead(root, "acme", { VAPI_MAX_GITOPS_RPM: "60" }), + /\.env.acme VAPI_MAX_GITOPS_RPM/, + ); + } finally { + rmSync(root, { recursive: true, force: true }); + } +}); diff --git a/tests/user-agent-coverage.test.ts b/tests/user-agent-coverage.test.ts index 719f3ad..ce17202 100644 --- a/tests/user-agent-coverage.test.ts +++ b/tests/user-agent-coverage.test.ts @@ -77,9 +77,7 @@ test("api.ts requests carry the command's User-Agent", async () => { delete process.env.GITHUB_ACTIONS; try { const { vapiGet } = await import("../src/api.ts"); - const { userAgentGet, vapiClientGet } = await import( - "../src/user-agent.ts" - ); + const { userAgentGet, vapiClientGet } = await import("../src/user-agent.ts"); await vapiGet("/assistant"); assert.deepEqual(seen, [userAgentGet()]); assert.match(seen[0] ?? "", /^vapi-gitops-apply\/[^ ]+$/); From 24e1fd1d1ec3c1732ba505b5aa9d792df6030b43 Mon Sep 17 00:00:00 2001 From: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Tue, 17 Nov 2026 09:46:58 +0000 Subject: [PATCH 4/5] fix(api): pace writes only with the org RPM limiter Co-Authored-By: Roshan Manjaly --- README.md | 4 ++- docs/guides/commands.md | 3 ++- docs/guides/configuration.md | 3 ++- improvements.md | 11 +++++++- src/api.ts | 18 ------------- src/cleanup.ts | 8 ------ tests/api-write-pacing.test.ts | 49 ++++++++++++++++++++++++++++++++++ 7 files changed, 66 insertions(+), 30 deletions(-) create mode 100644 tests/api-write-pacing.test.ts diff --git a/README.md b/README.md index 0470b93..f8702e6 100644 --- a/README.md +++ b/README.md @@ -206,6 +206,8 @@ More detail: [How the engine works](docs/guides/how-it-works.md). 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. | Command | What it does | | --- | --- | @@ -213,7 +215,7 @@ client ceiling (default 100), configured by `maxGitopsRpm` in the committed | `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 453e71b..87331ef 100644 --- a/docs/guides/commands.md +++ b/docs/guides/commands.md @@ -12,7 +12,8 @@ Every command that contacts Vapi observes the per-org 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. +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 | | --- | --- | --- | diff --git a/docs/guides/configuration.md b/docs/guides/configuration.md index f60a50f..54a54c4 100644 --- a/docs/guides/configuration.md +++ b/docs/guides/configuration.md @@ -86,7 +86,8 @@ On a 429, the warning names the org and effective RPM, suggests lowering rate limit: [EU](https://dashboard.eu.vapi.ai/settings/organization) for `api.eu.vapi.ai`, otherwise [US](https://dashboard.vapi.ai/settings/organization). -Existing retry backoff and write gaps still apply. +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 diff --git a/improvements.md b/improvements.md index f06bf8a..94429f5 100644 --- a/improvements.md +++ b/improvements.md @@ -2084,5 +2084,14 @@ dependency check, as `check-payload.ts` already does. - **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 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 backoff and write gaps retained. This is a GitOps client limit, not a Vapi org limit. +- **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. + +## 2026-11-17 — One client request pacing policy [RESOLVED 2026-11-17] (#95) + +- **Problem:** Fixed request sleeps added a second pacing policy on top of max GitOps RPM. +- **Current behavior:** [API writes](src/api.ts) and [cleanup reads/deletes](src/cleanup.ts) now use only the shared per-org token bucket. +- **Risk:** A configured burst can still trigger the platform's org rate limit. +- **Current mitigation:** Keep max GitOps RPM below the org quota; existing 429/5xx retry backoff is unchanged. +- **Possible fix:** No additional pacing layer is needed. +- **Status:** Implemented with stub-server coverage for burst writes and sustained limiter spacing. diff --git a/src/api.ts b/src/api.ts index c01b436..b0bc07c 100644 --- a/src/api.ts +++ b/src/api.ts @@ -107,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, @@ -150,7 +134,6 @@ export async function vapiRequest( } for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) { - await throttle(); const limiter = orgLimiter(BASE_DIR, VAPI_ENV, MAX_GITOPS_RPM); const response = await limitedVapiFetch(limiter, url, { method, @@ -249,7 +232,6 @@ export async function vapiDelete(endpoint: string): Promise { } for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) { - await throttle(); const limiter = orgLimiter(BASE_DIR, VAPI_ENV, MAX_GITOPS_RPM); const response = await limitedVapiFetch(limiter, url, { method: "DELETE", diff --git a/src/cleanup.ts b/src/cleanup.ts index 2a16e9c..27de54e 100644 --- a/src/cleanup.ts +++ b/src/cleanup.ts @@ -22,19 +22,12 @@ 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 limiter = orgLimiter(BASE_DIR, VAPI_ENV, MAX_GITOPS_RPM); const url = `${VAPI_BASE_URL}${endpoint}`; const response = await limitedVapiFetch(limiter, url, { @@ -78,7 +71,6 @@ async function vapiGet(endpoint: string, debug = false): Promise { async function vapiDelete(endpoint: string): Promise { await orgPinGuard(); - await sleep(REQUEST_DELAY_MS); const limiter = orgLimiter(BASE_DIR, VAPI_ENV, MAX_GITOPS_RPM); const url = `${VAPI_BASE_URL}${endpoint}`; const response = await limitedVapiFetch(limiter, url, { diff --git a/tests/api-write-pacing.test.ts b/tests/api-write-pacing.test.ts new file mode 100644 index 0000000..410fa4e --- /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 < 8; 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), + ["POST", "PATCH", "DELETE", "POST", "PATCH", "DELETE", "POST", "PATCH"], + ); + 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[7]!.time - seen[0]!.time >= 500, + "writes beyond the five-token burst must wait for the limiter", + ); + assert.ok( + seen[7]!.time - seen[6]!.time >= 140, + "sustained writes must be spaced by the configured refill rate", + ); + } finally { + await new Promise((resolve) => server.close(() => resolve())); + } +}); From 7ea332dddd68084f01a4cf4c515d3017fcb5fd25 Mon Sep 17 00:00:00 2001 From: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Tue, 17 Nov 2026 19:45:04 +0000 Subject: [PATCH 5/5] fix(rate-limit): honor cancellation and harden request configuration Co-Authored-By: Roshan Manjaly --- README.md | 3 +- docs/guides/configuration.md | 9 ++-- improvements.md | 11 +--- src/check-run.ts | 2 + src/rate-limit.ts | 34 ++++++------ src/sim.ts | 2 +- src/vapi-client.ts | 2 + src/vapi-fetch.ts | 11 ++-- tests/api-write-pacing.test.ts | 10 ++-- tests/check-run.test.ts | 45 ++++++++++++++++ tests/config-api-key.test.ts | 49 +++++++++++++++++ tests/env-file.test.ts | 32 ++++++++++++ tests/rate-limit.test.ts | 87 +++++++++++++++++++++++++------ tests/user-agent-coverage.test.ts | 18 ++++--- tests/vapi-fetch.test.ts | 63 ++++++++++++++++++++++ 15 files changed, 316 insertions(+), 62 deletions(-) create mode 100644 tests/env-file.test.ts create mode 100644 tests/vapi-fetch.test.ts diff --git a/README.md b/README.md index f8702e6..8b8b257 100644 --- a/README.md +++ b/README.md @@ -207,7 +207,8 @@ Vapi requests use a per-org [max GitOps RPM](docs/guides/configuration.md#max-gi 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. +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 | | --- | --- | diff --git a/docs/guides/configuration.md b/docs/guides/configuration.md index 54a54c4..e1ddf32 100644 --- a/docs/guides/configuration.md +++ b/docs/guides/configuration.md @@ -73,13 +73,14 @@ org limit. Set it in the committed `resources//.vapi-org.json`: 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 setting stops the command and names its source. +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. +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 @@ -91,5 +92,7 @@ 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, ceil(maxGitopsRpm / 60))`. Separate processes do not coordinate, +`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/improvements.md b/improvements.md index 94429f5..971fb21 100644 --- a/improvements.md +++ b/improvements.md @@ -2082,16 +2082,7 @@ dependency check, as `check-payload.ts` already does. - **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 settings stop requests. A 429 warns with the org's region-specific dashboard link. +- **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. - -## 2026-11-17 — One client request pacing policy [RESOLVED 2026-11-17] (#95) - -- **Problem:** Fixed request sleeps added a second pacing policy on top of max GitOps RPM. -- **Current behavior:** [API writes](src/api.ts) and [cleanup reads/deletes](src/cleanup.ts) now use only the shared per-org token bucket. -- **Risk:** A configured burst can still trigger the platform's org rate limit. -- **Current mitigation:** Keep max GitOps RPM below the org quota; existing 429/5xx retry backoff is unchanged. -- **Possible fix:** No additional pacing layer is needed. -- **Status:** Implemented with stub-server coverage for burst writes and sustained limiter spacing. 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/rate-limit.ts b/src/rate-limit.ts index 77c7038..b823336 100644 --- a/src/rate-limit.ts +++ b/src/rate-limit.ts @@ -25,6 +25,15 @@ export function maxGitopsRpmRead( 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)) { @@ -43,19 +52,7 @@ export function maxGitopsRpmRead( `resources/${org}/.vapi-org.json maxGitopsRpm`, ); } - let fileValue: number | undefined; - for (const { name, values } of orgEnvFilesRead(rootDir, org)) { - if (values.VAPI_MAX_GITOPS_RPM !== undefined) { - const number = positive( - values.VAPI_MAX_GITOPS_RPM, - `${name} VAPI_MAX_GITOPS_RPM`, - ); - fileValue ??= number; - } - } - return env.VAPI_MAX_GITOPS_RPM === undefined - ? (fileValue ?? value) - : positive(env.VAPI_MAX_GITOPS_RPM, "environment VAPI_MAX_GITOPS_RPM"); + return value; } export class TokenBucket { @@ -71,7 +68,7 @@ export class TokenBucket { readonly org = "unknown", ) { positive(rpm, "token bucket"); - this.capacity = Math.max(1, Math.ceil(rpm / 60)); + this.capacity = Math.max(1, Math.min(20, Math.floor(rpm / 5))); this.tokens = this.capacity; this.updated = now(); } @@ -110,12 +107,17 @@ export function orgLimiterOrExit(rootDir: string, org: string): TokenBucket { export function orgLimiter( rootDir: string, org: string, - rpm = maxGitopsRpmRead(rootDir, org), + rpm?: number, ): TokenBucket { const key = `${resolve(rootDir)}\0${org}`; let limiter = buckets.get(key); if (!limiter) { - limiter = new TokenBucket(rpm, undefined, undefined, org); + limiter = new TokenBucket( + rpm ?? maxGitopsRpmRead(rootDir, org), + undefined, + undefined, + org, + ); buckets.set(key, limiter); } return limiter; diff --git a/src/sim.ts b/src/sim.ts index 6184555..f085759 100644 --- a/src/sim.ts +++ b/src/sim.ts @@ -348,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 259a6a9..31c6a1b 100644 --- a/src/vapi-client.ts +++ b/src/vapi-client.ts @@ -24,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; @@ -90,6 +91,7 @@ export async function vapiFetchJson( 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 index 85833d0..4389112 100644 --- a/src/vapi-fetch.ts +++ b/src/vapi-fetch.ts @@ -15,13 +15,14 @@ export async function limitedVapiFetch( 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: { - "User-Agent": userAgentGet(), - "x-vapi-client": vapiClientGet(), - ...init.headers, - }, + headers, }); if (response.status === 429 && !warned.has(limiter)) { warned.add(limiter); diff --git a/tests/api-write-pacing.test.ts b/tests/api-write-pacing.test.ts index 410fa4e..8c8b4a4 100644 --- a/tests/api-write-pacing.test.ts +++ b/tests/api-write-pacing.test.ts @@ -23,24 +23,24 @@ test("API writes use the limiter burst and sustained rate without another gap", process.env.VAPI_MAX_GITOPS_RPM = "300"; try { const { vapiRequest, vapiDelete } = await import("../src/api.ts"); - for (let i = 0; i < 8; i++) { + 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), - ["POST", "PATCH", "DELETE", "POST", "PATCH", "DELETE", "POST", "PATCH"], + 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[7]!.time - seen[0]!.time >= 500, - "writes beyond the five-token burst must wait for the limiter", + seen[22]!.time - seen[0]!.time >= 500, + "writes beyond the twenty-token burst must wait for the limiter", ); assert.ok( - seen[7]!.time - seen[6]!.time >= 140, + seen[22]!.time - seen[21]!.time >= 140, "sustained writes must be spaced by the configured refill rate", ); } finally { diff --git a/tests/check-run.test.ts b/tests/check-run.test.ts index feef884..0b3dde2 100644 --- a/tests/check-run.test.ts +++ b/tests/check-run.test.ts @@ -339,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/rate-limit.test.ts b/tests/rate-limit.test.ts index ac1bef7..c6e403b 100644 --- a/tests/rate-limit.test.ts +++ b/tests/rate-limit.test.ts @@ -33,8 +33,8 @@ test("token bucket allows a burst, then sustains the configured rate", async () now += ms; }, ); - assert.equal(limiter.capacity, 5); - await Promise.all(Array.from({ length: 10 }, () => limiter.acquire())); + 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())); @@ -44,7 +44,7 @@ test("token bucket allows a burst, then sustains the configured rate", async () test("low RPM and concurrent requests sustain the cap", async () => { let now = 0; const limiter = new TokenBucket( - 30, + 1, () => now, async (ms) => { now += ms; @@ -52,7 +52,7 @@ test("low RPM and concurrent requests sustain the cap", async () => { ); assert.equal(limiter.capacity, 1); await Promise.all(Array.from({ length: 3 }, () => limiter.acquire())); - assert.equal(now, 4000); + assert.equal(now, 120000); assert.throws(() => new TokenBucket(Infinity), /positive integer/); assert.throws(() => new TokenBucket(1.5), /positive integer/); }); @@ -66,8 +66,8 @@ test("default RPM has only a small burst across a minute", async () => { now += ms; }, ); - assert.equal(limiter.capacity, 2); - await Promise.all(Array.from({ length: 102 }, () => limiter.acquire())); + assert.equal(limiter.capacity, 20); + await Promise.all(Array.from({ length: 120 }, () => limiter.acquire())); assert.equal(now, 60_000); }); @@ -79,6 +79,59 @@ test("process registry shares an org but isolates other orgs", async () => { 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"); @@ -96,10 +149,16 @@ test("max GitOps RPM resolves defaults, committed settings and environment prece ); 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", { VAPI_MAX_GITOPS_RPM: "5" }), + () => 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"]) { @@ -109,11 +168,9 @@ test("max GitOps RPM resolves defaults, committed settings and environment prece /❌.*environment VAPI_MAX_GITOPS_RPM/, ); writeFileSync(join(root, ".env.acme"), `VAPI_MAX_GITOPS_RPM=${value}\n`); - assert.throws( - () => maxGitopsRpmRead(root, "acme", { VAPI_MAX_GITOPS_RPM: "5" }), - /❌.*\.env.acme/, - ); + assert.throws(() => maxGitopsRpmRead(root, "acme", {}), /❌.*\.env.acme/); } + rmSync(join(root, ".env.acme")); writeFileSync(pin, "{"); assert.throws( () => maxGitopsRpmRead(root, "acme", {}), @@ -311,11 +368,11 @@ test("shared env parsing handles exports, comments and org file precedence", () ); writeFileSync( join(root, ".env.acme"), - "export VAPI_MAX_GITOPS_RPM=invalid # invalid even with an override\n", + "export VAPI_MAX_GITOPS_RPM=invalid # ignored when overridden\n", ); - assert.throws( - () => maxGitopsRpmRead(root, "acme", { VAPI_MAX_GITOPS_RPM: "60" }), - /\.env.acme VAPI_MAX_GITOPS_RPM/, + assert.equal( + maxGitopsRpmRead(root, "acme", { VAPI_MAX_GITOPS_RPM: "60" }), + 60, ); } finally { rmSync(root, { recursive: true, force: true }); diff --git a/tests/user-agent-coverage.test.ts b/tests/user-agent-coverage.test.ts index ce17202..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})`); @@ -86,14 +92,14 @@ 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: 9 }, () => vapiGet("/assistant"))); - assert.equal(times.length, 10); + await Promise.all(Array.from({ length: 24 }, () => vapiGet("/assistant"))); + assert.equal(times.length, 25); assert.ok( - times[9]! - times[0]! >= 850, + times[24]! - times[0]! >= 850, "requests beyond the initial burst must wait for tokens", ); assert.ok( - times[9]! - times[8]! >= 140, + times[24]! - times[23]! >= 140, "sustained requests must be spaced by the cap", ); } finally { 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" }, + ); +});