Skip to content

Never stop coding. Free MIT AI gateway: one endpoint, 375 providers (150+ free), 1,400+ models Kimi, Claude, GPT, Gemini, GLM, DeepSeek, MiniMax. Works with Claude Code, Codex, Cursor, OpenCode, Cline & Copilot. Quota-aware auto-fallback, RTK+Caveman compression saves 15-95% tokens, MCP/A2A, Desktop/PWA. Built by 900+ contributors

feat(quota): reconcile key allowedQuotas when pool allocations saved as exclusive (Phase C3)

diegosouzapw6a14c3128045
diff --git a/src/app/api/quota/pools/[id]/route.ts b/src/app/api/quota/pools/[id]/route.ts
index 239f1835f3..2cdaa69983 100644
--- a/src/app/api/quota/pools/[id]/route.ts
+++ b/src/app/api/quota/pools/[id]/route.ts
@@ -17,6 +17,7 @@ import { requireManagementAuth } from "@/lib/api/requireManagementAuth";
import { PoolUpdateSchema } from "@/shared/schemas/quota";
import { getPool, updatePool, deletePool } from "@/lib/localDb";
import { logAuditEvent, getAuditRequestContext } from "@/lib/compliance/index";
+import { reconcilePoolExclusivity } from "@/lib/quota/quotaKey";
export const dynamic = "force-dynamic";
@@ -51,11 +52,35 @@ export async function PATCH(request: Request, { params }: RouteParams): Promise<
return NextResponse.json(buildErrorBody(400, parsed.error.message), { status: 400 });
}
+ // Capture prev allocations BEFORE the update so we know which keys are leaving.
+ // Only needed when `exclusive` is explicitly present in the request body.
+ const exclusivePresent = body !== null && typeof body === "object" && "exclusive" in body;
+ const prevApiKeyIds: string[] = [];
+ if (exclusivePresent) {
+ const existingPool = getPool(id);
+ if (existingPool) {
+ for (const alloc of existingPool.allocations) {
+ prevApiKeyIds.push(alloc.apiKeyId);
+ }
+ }
+ }
+
const pool = updatePool(id, parsed.data);
if (!pool) {
return NextResponse.json(buildErrorBody(404, "Pool not found"), { status: 404 });
}
+ // Reconcile allowedQuotas on API keys when exclusive flag is explicitly set.
+ if (exclusivePresent) {
+ const nextApiKeyIds = (parsed.data.allocations ?? []).map((a) => a.apiKeyId);
+ await reconcilePoolExclusivity(
+ id,
+ prevApiKeyIds,
+ nextApiKeyIds,
+ parsed.data.exclusive ?? false,
+ );
+ }
+
const ctx = getAuditRequestContext(request);
logAuditEvent({
action: "quota.pool.updated",
diff --git a/src/lib/quota/quotaKey.ts b/src/lib/quota/quotaKey.ts
index 90dc715736..8c581c3e08 100644
--- a/src/lib/quota/quotaKey.ts
+++ b/src/lib/quota/quotaKey.ts
@@ -2,12 +2,14 @@
* quota/quotaKey.ts — Resolve which connections and providers an API key may
* use, based on its `allowedQuotas` pool-ID list.
*
- * This is a pure read-side helper; it does NOT mutate any state. Later tasks
- * (A3/A4) use the returned scope to enforce request-time restrictions.
+ * Also exports `reconcilePoolExclusivity` (Phase C3) which keeps each API
+ * key's `allowedQuotas` in sync when a pool's allocations are saved with the
+ * `exclusive` flag.
*/
import { getPool } from "@/lib/db/quotaPools";
import { getProviderConnectionById } from "@/lib/db/providers";
+import { getApiKeyById, updateApiKeyPermissions } from "@/lib/db/apiKeys";
import { quotaPoolSlug } from "./quotaModelNaming";
// ---------------------------------------------------------------------------
@@ -87,3 +89,63 @@ export async function resolveQuotaKeyScope(
poolSlugs: Array.from(poolSlugSet),
};
}
+
+// ---------------------------------------------------------------------------
+// Phase C3 — Exclusivity reconciliation
+// ---------------------------------------------------------------------------
+
+/**
+ * Reconcile each affected API key's `allowedQuotas` when a pool's allocations
+ * are saved with an `exclusive` flag.
+ *
+ * Rules:
+ * - `exclusive === true` → keys in `nextApiKeyIds` get `poolId` ADDED to their
+ * `allowedQuotas`; keys that were in `prevApiKeyIds` but are no longer in
+ * `nextApiKeyIds` get `poolId` REMOVED.
+ * - `exclusive === false` → `poolId` is REMOVED from ALL keys in the union of
+ * `prevApiKeyIds` and `nextApiKeyIds`.
+ *
+ * Only writes when the set actually changed (avoids needless DB round-trips).
+ * Missing keys are silently skipped — this function never throws.
+ */
+export async function reconcilePoolExclusivity(
+ poolId: string,
+ prevApiKeyIds: string[],
+ nextApiKeyIds: string[],
+ exclusive: boolean,
+): Promise<void> {
+ const affectedIds = new Set([...prevApiKeyIds, ...nextApiKeyIds]);
+
+ for (const keyId of affectedIds) {
+ try {
+ const keyRow = await getApiKeyById(keyId);
+ if (!keyRow) continue;
+
+ const currentQuotas: string[] = Array.isArray(
+ (keyRow as Record<string, unknown>).allowedQuotas,
+ )
+ ? ((keyRow as Record<string, unknown>).allowedQuotas as string[])
+ : [];
+
+ let nextQuotas: string[];
+
+ if (exclusive && nextApiKeyIds.includes(keyId)) {
+ // Key is in the new allocation AND pool is exclusive → ensure poolId present.
+ if (currentQuotas.includes(poolId)) {
+ continue; // no change needed
+ }
+ nextQuotas = [...currentQuotas, poolId];
+ } else {
+ // Pool is non-exclusive OR key was removed → ensure poolId absent.
+ if (!currentQuotas.includes(poolId)) {
+ continue; // no change needed
+ }
+ nextQuotas = currentQuotas.filter((q) => q !== poolId);
+ }
+
+ await updateApiKeyPermissions(keyId, { allowedQuotas: nextQuotas });
+ } catch {
+ // Defensive: a single key failure must never abort reconciliation for others.
+ }
+ }
+}
diff --git a/src/shared/schemas/quota.ts b/src/shared/schemas/quota.ts
index 8631cac623..97f70da67d 100644
--- a/src/shared/schemas/quota.ts
+++ b/src/shared/schemas/quota.ts
@@ -11,6 +11,7 @@ export type PoolCreate = z.infer<typeof PoolCreateSchema>;
export const PoolUpdateSchema = z.object({
name: z.string().min(1).max(120).optional(),
allocations: z.array(PoolAllocationSchema).optional(),
+ exclusive: z.boolean().optional(),
});
export type PoolUpdate = z.infer<typeof PoolUpdateSchema>;
diff --git a/tests/unit/quota-exclusivity-reconcile.test.ts b/tests/unit/quota-exclusivity-reconcile.test.ts
new file mode 100644
index 0000000000..89ef35e2b3
--- /dev/null
+++ b/tests/unit/quota-exclusivity-reconcile.test.ts
@@ -0,0 +1,217 @@
+/**
+ * tests/unit/quota-exclusivity-reconcile.test.ts
+ *
+ * TDD coverage for reconcilePoolExclusivity (Phase C3):
+ *
+ * - Adding a key as exclusive → poolId added to its allowedQuotas
+ * - Transferring exclusivity between keys → prev key loses poolId, next gains it
+ * - Turning off exclusive → all keys lose poolId
+ * - Idempotency: calling twice with same args makes no extra change
+ * - Missing / unknown key → skipped defensively (never throws)
+ * - Absent exclusive param on PATCH → no reconciliation (skip test at unit level)
+ */
+
+import test from "node:test";
+import assert from "node:assert/strict";
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+
+const TEST_DATA_DIR = fs.mkdtempSync(
+ path.join(os.tmpdir(), "omniroute-quota-exclusivity-"),
+);
+process.env.DATA_DIR = TEST_DATA_DIR;
+process.env.API_KEY_SECRET =
+ process.env.API_KEY_SECRET || "exclusivity-reconcile-test-secret";
+
+const core = await import("../../src/lib/db/core.ts");
+const apiKeysDb = await import("../../src/lib/db/apiKeys.ts");
+const poolsDb = await import("../../src/lib/db/quotaPools.ts");
+const { reconcilePoolExclusivity } = await import(
+ "../../src/lib/quota/quotaKey.ts"
+);
+
+// ---------------------------------------------------------------------------
+// Test lifecycle helpers
+// ---------------------------------------------------------------------------
+
+async function resetStorage() {
+ core.resetDbInstance();
+ apiKeysDb.resetApiKeyState();
+
+ for (let attempt = 0; attempt < 10; attempt++) {
+ try {
+ if (fs.existsSync(TEST_DATA_DIR)) {
+ fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
+ }
+ break;
+ } catch (error: unknown) {
+ const err = error as NodeJS.ErrnoException;
+ if ((err?.code === "EBUSY" || err?.code === "EPERM") && attempt < 9) {
+ await new Promise((resolve) => setTimeout(resolve, 50 * (attempt + 1)));
+ } else {
+ throw error;
+ }
+ }
+ }
+
+ fs.mkdirSync(TEST_DATA_DIR, { recursive: true });
+}
+
+/** Helper: get the current allowedQuotas for a key by id. */
+async function getAllowedQuotas(keyId: string): Promise<string[]> {
+ const row = await apiKeysDb.getApiKeyById(keyId);
+ if (!row) return [];
+ return Array.isArray((row as Record<string, unknown>).allowedQuotas)
+ ? ((row as Record<string, unknown>).allowedQuotas as string[])
+ : [];
+}
+
+test.beforeEach(async () => {
+ await resetStorage();
+});
+
+test.after(async () => {
+ core.resetDbInstance();
+ apiKeysDb.resetApiKeyState();
+ fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
+});
+
+// ---------------------------------------------------------------------------
+// Core scenarios
+// ---------------------------------------------------------------------------
+
+test("reconcilePoolExclusivity: exclusive=true adds poolId to allocated key, leaves other key unchanged", async () => {
+ const pool = poolsDb.createPool({ connectionId: "conn-excl-1", name: "Excl Pool A" });
+ const keyA = await apiKeysDb.createApiKey("Key A", "machine-excl-a");
+ const keyB = await apiKeysDb.createApiKey("Key B", "machine-excl-b");
+
+ // keyA gets allocated exclusively; keyB is not in next allocation
+ await reconcilePoolExclusivity(pool.id, [], [keyA.id], true);
+
+ apiKeysDb.clearApiKeyCaches();
+
+ const quotasA = await getAllowedQuotas(keyA.id);
+ const quotasB = await getAllowedQuotas(keyB.id);
+
+ assert.ok(quotasA.includes(pool.id), "keyA should have poolId in allowedQuotas");
+ assert.deepEqual(quotasB, [], "keyB should remain untouched");
+});
+
+test("reconcilePoolExclusivity: transferring exclusivity — prev key loses poolId, next key gains it", async () => {
+ const pool = poolsDb.createPool({ connectionId: "conn-excl-2", name: "Excl Pool B" });
+ const keyA = await apiKeysDb.createApiKey("Key A2", "machine-excl-a2");
+ const keyB = await apiKeysDb.createApiKey("Key B2", "machine-excl-b2");
+
+ // First, keyA is exclusively allocated
+ await apiKeysDb.updateApiKeyPermissions(keyA.id, { allowedQuotas: [pool.id] });
+ apiKeysDb.clearApiKeyCaches();
+
+ // Now transfer: prev=[keyA], next=[keyB], exclusive=true
+ await reconcilePoolExclusivity(pool.id, [keyA.id], [keyB.id], true);
+ apiKeysDb.clearApiKeyCaches();
+
+ const quotasA = await getAllowedQuotas(keyA.id);
+ const quotasB = await getAllowedQuotas(keyB.id);
+
+ assert.ok(!quotasA.includes(pool.id), "keyA should no longer have poolId");
+ assert.ok(quotasB.includes(pool.id), "keyB should now have poolId");
+});
+
+test("reconcilePoolExclusivity: exclusive=false removes poolId from all prev+next keys", async () => {
+ const pool = poolsDb.createPool({ connectionId: "conn-excl-3", name: "Excl Pool C" });
+ const keyB = await apiKeysDb.createApiKey("Key B3", "machine-excl-b3");
+
+ // Give keyB the poolId first
+ await apiKeysDb.updateApiKeyPermissions(keyB.id, { allowedQuotas: [pool.id] });
+ apiKeysDb.clearApiKeyCaches();
+
+ // Turn off exclusive: prev=[keyB], next=[keyB], exclusive=false
+ await reconcilePoolExclusivity(pool.id, [keyB.id], [keyB.id], false);
+ apiKeysDb.clearApiKeyCaches();
+
+ const quotasB = await getAllowedQuotas(keyB.id);
+ assert.ok(!quotasB.includes(pool.id), "keyB should no longer have poolId after exclusive=false");
+});
+
+test("reconcilePoolExclusivity: idempotent — calling twice with same args does not duplicate or change anything", async () => {
+ const pool = poolsDb.createPool({ connectionId: "conn-excl-4", name: "Excl Pool D" });
+ const keyA = await apiKeysDb.createApiKey("Key A4", "machine-excl-a4");
+
+ // First call
+ await reconcilePoolExclusivity(pool.id, [], [keyA.id], true);
+ apiKeysDb.clearApiKeyCaches();
+
+ const quotasAfterFirst = await getAllowedQuotas(keyA.id);
+ assert.ok(quotasAfterFirst.includes(pool.id), "poolId should be present after first call");
+ assert.equal(
+ quotasAfterFirst.filter((q) => q === pool.id).length,
+ 1,
+ "poolId should appear exactly once",
+ );
+
+ // Second call — idempotent
+ await reconcilePoolExclusivity(pool.id, [], [keyA.id], true);
+ apiKeysDb.clearApiKeyCaches();
+
+ const quotasAfterSecond = await getAllowedQuotas(keyA.id);
+ assert.deepEqual(
+ quotasAfterSecond,
+ quotasAfterFirst,
+ "allowedQuotas should be unchanged after second call",
+ );
+ assert.equal(
+ quotasAfterSecond.filter((q) => q === pool.id).length,
+ 1,
+ "poolId should still appear exactly once",
+ );
+});
+
+test("reconcilePoolExclusivity: idempotent removal — calling exclusive=false twice is safe", async () => {
+ const pool = poolsDb.createPool({ connectionId: "conn-excl-5", name: "Excl Pool E" });
+ const keyA = await apiKeysDb.createApiKey("Key A5", "machine-excl-a5");
+
+ await apiKeysDb.updateApiKeyPermissions(keyA.id, { allowedQuotas: [pool.id] });
+ apiKeysDb.clearApiKeyCaches();
+
+ await reconcilePoolExclusivity(pool.id, [keyA.id], [keyA.id], false);
+ apiKeysDb.clearApiKeyCaches();
+
+ const quotasAfterFirst = await getAllowedQuotas(keyA.id);
+ assert.ok(!quotasAfterFirst.includes(pool.id), "poolId removed after first exclusive=false");
+
+ // Second call — should not throw, should be a no-op
+ await reconcilePoolExclusivity(pool.id, [keyA.id], [keyA.id], false);
+ apiKeysDb.clearApiKeyCaches();
+
+ const quotasAfterSecond = await getAllowedQuotas(keyA.id);
+ assert.deepEqual(quotasAfterSecond, [], "still empty after second exclusive=false call");
+});
+
+test("reconcilePoolExclusivity: missing/unknown keyId is skipped defensively (no throw)", async () => {
+ const pool = poolsDb.createPool({ connectionId: "conn-excl-6", name: "Excl Pool F" });
+
+ // ghost-key does not exist in the DB; must not throw
+ await assert.doesNotReject(
+ () => reconcilePoolExclusivity(pool.id, [], ["ghost-key-id-that-does-not-exist"], true),
+ "should not throw for unknown key IDs",
+ );
+});
+
+test("reconcilePoolExclusivity: exclusive=true preserves other poolIds already in allowedQuotas", async () => {
+ const pool1 = poolsDb.createPool({ connectionId: "conn-excl-7a", name: "Excl Pool G1" });
+ const pool2 = poolsDb.createPool({ connectionId: "conn-excl-7b", name: "Excl Pool G2" });
+ const keyA = await apiKeysDb.createApiKey("Key A7", "machine-excl-a7");
+
+ // Pre-seed keyA with pool1 already
+ await apiKeysDb.updateApiKeyPermissions(keyA.id, { allowedQuotas: [pool1.id] });
+ apiKeysDb.clearApiKeyCaches();
+
+ // Reconcile pool2 exclusively for keyA
+ await reconcilePoolExclusivity(pool2.id, [], [keyA.id], true);
+ apiKeysDb.clearApiKeyCaches();
+
+ const quotas = await getAllowedQuotas(keyA.id);
+ assert.ok(quotas.includes(pool1.id), "pool1 should still be present");
+ assert.ok(quotas.includes(pool2.id), "pool2 should be added");
+});