Open source CapCut alternative.
TypeScript
fix(site): bound database connections and command polling [rebuild]
David Le5de3bd4194ec
diff --git a/site/package-lock.json b/site/package-lock.jsonindex 6fffd6dc..de26fe6c 100644--- a/site/package-lock.json+++ b/site/package-lock.json@@ -46,6 +46,7 @@"@tanstack/react-query": "^5.101.0","@types/mdx": "^2.0.13","@typesafe-ai/sdk": "0.6.0",+ "@vercel/functions": "^3.9.9","ai": "^7.0.14","better-auth": "1.6.11","better-call": "1.3.5",@@ -10669,6 +10670,182 @@"win32"]},+ "node_modules/@vercel/cli-config": {+ "version": "0.3.0",+ "resolved": "https://registry.npmjs.org/@vercel/cli-config/-/cli-config-0.3.0.tgz",+ "integrity": "sha512-kQLt5Pm8wKd7/imzDY9/9u0tf8OuRkAuXI+s7j057FSUrXapAmumJSKwDqnR4ZZqdWoUcNLlFAgVIAdiwcGTcw==",+ "license": "Apache-2.0",+ "dependencies": {+ "xdg-app-paths": "5",+ "zod": "4.1.11"+ }+ },+ "node_modules/@vercel/cli-config/node_modules/zod": {+ "version": "4.1.11",+ "resolved": "https://registry.npmjs.org/zod/-/zod-4.1.11.tgz",+ "integrity": "sha512-WPsqwxITS2tzx1bzhIKsEs19ABD5vmCVa4xBo2tq/SrV4RNZtfws1EnCWQXM6yh8bD08a1idvkB5MZSBiZsjwg==",+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/colinhacks"+ }+ },+ "node_modules/@vercel/cli-exec": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/@vercel/cli-exec/-/cli-exec-1.0.1.tgz",+ "integrity": "sha512-g9XerViJ/paZujufXYcu5XYI2vU2rtB4sgdpjUHde5RnOkdmpu0ngH46LCFGHoPXO/C+qDPSczIHIRN+8Q2YKQ==",+ "license": "Apache-2.0",+ "dependencies": {+ "execa": "5.1.1"+ },+ "engines": {+ "node": ">= 18"+ }+ },+ "node_modules/@vercel/cli-exec/node_modules/execa": {+ "version": "5.1.1",+ "resolved": "https://registry.npmjs.org/execa/-/execa-5.1.1.tgz",+ "integrity": "sha512-8uSpZZocAZRBAPIEINJj3Lo9HyGitllczc27Eh5YYojjMFMn8yHMDMaUHE2Jqfq05D/wucwI4JGURyXt1vchyg==",+ "license": "MIT",+ "dependencies": {+ "cross-spawn": "^7.0.3",+ "get-stream": "^6.0.0",+ "human-signals": "^2.1.0",+ "is-stream": "^2.0.0",+ "merge-stream": "^2.0.0",+ "npm-run-path": "^4.0.1",+ "onetime": "^5.1.2",+ "signal-exit": "^3.0.3",+ "strip-final-newline": "^2.0.0"+ },+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/sindresorhus/execa?sponsor=1"+ }+ },+ "node_modules/@vercel/cli-exec/node_modules/get-stream": {+ "version": "6.0.1",+ "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-6.0.1.tgz",+ "integrity": "sha512-ts6Wi+2j3jQjqi70w5AlN8DFnkSwC+MqmxEzdEALB2qXZYV3X/b1CTfgPLGJNMeAWxdPfU8FO1ms3NUfaHCPYg==",+ "license": "MIT",+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/@vercel/cli-exec/node_modules/human-signals": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/human-signals/-/human-signals-2.1.0.tgz",+ "integrity": "sha512-B4FFZ6q/T2jhhksgkbEW3HBvWIfDW85snkQgawt07S7J5QXTk6BkNV+0yAeZrM5QpMAdYlocGoljn0sJ/WQkFw==",+ "license": "Apache-2.0",+ "engines": {+ "node": ">=10.17.0"+ }+ },+ "node_modules/@vercel/cli-exec/node_modules/is-stream": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-2.0.1.tgz",+ "integrity": "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg==",+ "license": "MIT",+ "engines": {+ "node": ">=8"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/@vercel/cli-exec/node_modules/npm-run-path": {+ "version": "4.0.1",+ "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-4.0.1.tgz",+ "integrity": "sha512-S48WzZW777zhNIrn7gxOlISNAqi9ZC/uQFnRdbeIHhZhCA6UqpkOT8T1G7BvfdgP4Er8gF4sUbaS0i7QvIfCWw==",+ "license": "MIT",+ "dependencies": {+ "path-key": "^3.0.0"+ },+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/@vercel/cli-exec/node_modules/onetime": {+ "version": "5.1.2",+ "resolved": "https://registry.npmjs.org/onetime/-/onetime-5.1.2.tgz",+ "integrity": "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==",+ "license": "MIT",+ "dependencies": {+ "mimic-fn": "^2.1.0"+ },+ "engines": {+ "node": ">=6"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/@vercel/cli-exec/node_modules/signal-exit": {+ "version": "3.0.7",+ "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz",+ "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==",+ "license": "ISC"+ },+ "node_modules/@vercel/cli-exec/node_modules/strip-final-newline": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/strip-final-newline/-/strip-final-newline-2.0.0.tgz",+ "integrity": "sha512-BrpvfNAE3dcvq7ll3xVumzjKjZQ5tI1sEUIKr3Uoks0XUl45St3FlatVqef9prk4jRDzhW6WZg+3bk93y6pLjA==",+ "license": "MIT",+ "engines": {+ "node": ">=6"+ }+ },+ "node_modules/@vercel/functions": {+ "version": "3.9.9",+ "resolved": "https://registry.npmjs.org/@vercel/functions/-/functions-3.9.9.tgz",+ "integrity": "sha512-ocN/BNsIswReoyqfU1huilNyBM9tvY9kFXgYj0LlyPRATC1dt35gj2jN5hs9+Nag/CRyVQOX58L2FEhvL+0sSA==",+ "license": "Apache-2.0",+ "dependencies": {+ "@vercel/oidc": "3.8.9"+ },+ "engines": {+ "node": ">= 20"+ },+ "peerDependencies": {+ "@aws-sdk/credential-provider-web-identity": "*",+ "ws": ">=8"+ },+ "peerDependenciesMeta": {+ "@aws-sdk/credential-provider-web-identity": {+ "optional": true+ },+ "ws": {+ "optional": true+ }+ }+ },+ "node_modules/@vercel/functions/node_modules/@vercel/oidc": {+ "version": "3.8.9",+ "resolved": "https://registry.npmjs.org/@vercel/oidc/-/oidc-3.8.9.tgz",+ "integrity": "sha512-TcbdH3YtGS2KU98T99dN4sbf+E4vbJZsJTRN97wKQ7QWQ0BR7U02QX3KN4+5GHxBtKTj1c5CnvTTitc2ZRad0A==",+ "license": "Apache-2.0",+ "dependencies": {+ "@vercel/cli-config": "0.3.0",+ "@vercel/cli-exec": "1.0.1",+ "jose": "^5.9.6"+ },+ "engines": {+ "node": ">= 20"+ }+ },+ "node_modules/@vercel/functions/node_modules/jose": {+ "version": "5.10.0",+ "resolved": "https://registry.npmjs.org/jose/-/jose-5.10.0.tgz",+ "integrity": "sha512-s+3Al/p9g32Iq+oqXxkW//7jk2Vig6FF1CFqzVXoTUXt2qz89YWbL+OwS17NFYEvxC35n0FKeGO2LGYSxeM2Gg==",+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/panva"+ }+ },"node_modules/@vercel/oidc": {"version": "3.2.0","resolved": "https://registry.npmjs.org/@vercel/oidc/-/oidc-3.2.0.tgz",@@ -19043,6 +19220,15 @@"url": "https://github.com/chalk/chalk?sponsor=1"}},+ "node_modules/os-paths": {+ "version": "4.4.0",+ "resolved": "https://registry.npmjs.org/os-paths/-/os-paths-4.4.0.tgz",+ "integrity": "sha512-wrAwOeXp1RRMFfQY8Sy7VaGVmPocaLwSFOYCGKSyo8qmJ+/yaafCl5BCA1IQZWqFSRBrKDYFeR9d/VyQzfH/jg==",+ "license": "MIT",+ "engines": {+ "node": ">= 6.0"+ }+ },"node_modules/outvariant": {"version": "1.4.3","resolved": "https://registry.npmjs.org/outvariant/-/outvariant-1.4.3.tgz",@@ -23481,6 +23667,31 @@"url": "https://github.com/sponsors/sindresorhus"}},+ "node_modules/xdg-app-paths": {+ "version": "5.5.1",+ "resolved": "https://registry.npmjs.org/xdg-app-paths/-/xdg-app-paths-5.5.1.tgz",+ "integrity": "sha512-hI3flOB4PLZIy5prbtTpirobtPE2ZtZ52szO+2mM9Efp6ErM398La+C1lIpNWDfNoQk+6Lsi6nMcCwVB7pxeMQ==",+ "license": "MIT",+ "dependencies": {+ "os-paths": "^4.0.1",+ "xdg-portable": "^7.2.0"+ },+ "engines": {+ "node": ">= 6.0"+ }+ },+ "node_modules/xdg-portable": {+ "version": "7.3.0",+ "resolved": "https://registry.npmjs.org/xdg-portable/-/xdg-portable-7.3.0.tgz",+ "integrity": "sha512-sqMMuL1rc0FmMBOzCpd0yuy9trqF2yTTVe+E9ogwCSWQCdDEtQUwrZPT6AxqtsFGRNxycgncbP/xmOOSPw5ZUw==",+ "license": "MIT",+ "dependencies": {+ "os-paths": "^4.0.1"+ },+ "engines": {+ "node": ">= 6.0"+ }+ },"node_modules/xtend": {"version": "4.0.2","resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz",diff --git a/site/package.json b/site/package.jsonindex 94901e85..5dbc7e11 100644--- a/site/package.json+++ b/site/package.json@@ -85,6 +85,7 @@"@tanstack/react-query": "^5.101.0","@types/mdx": "^2.0.13","@typesafe-ai/sdk": "0.6.0",+ "@vercel/functions": "^3.9.9","ai": "^7.0.14","better-auth": "1.6.11","better-call": "1.3.5",diff --git a/site/src/cut/components/RequireSession.tsx b/site/src/cut/components/RequireSession.tsxindex 05bff1ad..b39e1be5 100644--- a/site/src/cut/components/RequireSession.tsx+++ b/site/src/cut/components/RequireSession.tsx@@ -1,5 +1,5 @@"use client";-import { bindChatRuntime, bindCutClip, bindCutJudge } from "@/cut/lib/chatRuntime";+import { bindChatRuntime, bindChatgptPolling, bindCutClip, bindCutJudge } from "@/cut/lib/chatRuntime";import { useEffect, type ReactNode } from "react";import { useEnvironment } from "@/cut/lib/environment";@@ -42,6 +42,7 @@ export function RequireSession({ children }: { children: ReactNode }) {useEffect(() => {if (!userId || !config.data) return;bindChatRuntime(config.data.settings.chatRuntime);+ bindChatgptPolling(config.data.settings.chatgptPolling);bindCutJudge(config.data.settings.cutJudge);bindCutClip(config.data.settings.cutClip);reportExposures(config.data);diff --git a/site/src/cut/lib/chatRuntime.ts b/site/src/cut/lib/chatRuntime.tsindex c05eb553..332fdd8b 100644--- a/site/src/cut/lib/chatRuntime.ts+++ b/site/src/cut/lib/chatRuntime.ts@@ -7,6 +7,13 @@ export function bindChatRuntime(value: unknown): void {}export function chatRuntime(): Settings["chatRuntime"] { return runtime; }+let polling: Settings["chatgptPolling"] = SETTINGS.chatgptPolling.default;+export function bindChatgptPolling(value: unknown): void {+ const parsed = SETTINGS.chatgptPolling.schema.safeParse(value);+ if (parsed.success) polling = parsed.data;+}+export function chatgptPolling(): Settings["chatgptPolling"] { return polling; }+let judge: Settings["cutJudge"] = SETTINGS.cutJudge.default;export function bindCutJudge(value: unknown): void {const parsed = SETTINGS.cutJudge.schema.safeParse(value);diff --git a/site/src/cut/lib/hostCommandPolling.test.ts b/site/src/cut/lib/hostCommandPolling.test.tsnew file mode 100644index 00000000..c80224d3--- /dev/null+++ b/site/src/cut/lib/hostCommandPolling.test.ts@@ -0,0 +1,64 @@+import { expect, test } from "bun:test";+import { hostCommandPoller } from "./hostCommandPolling";+import { SETTINGS } from "@/lib/config/registry";++const settings = () => SETTINGS.chatgptPolling.default;++test("failed polls back off, remain bounded, and reset after recovery", async () => {+ let status = 500;+ const poll = hostCommandPoller({+ claim: async () => new Response(null, { status }),+ run: async () => {}, settings, hidden: () => false,+ });+ expect(await poll()).toBe(2000);+ expect(await poll()).toBe(4000);+ expect(await poll()).toBe(8000);+ for (let i = 0; i < 8; i++) await poll();+ expect(await poll()).toBe(60000);+ status = 204;+ expect(await poll()).toBe(1000);+ status = 503;+ expect(await poll()).toBe(2000);+});++test("expired sessions and inaccessible projects stop the polling loop", async () => {+ for (const status of [401, 403, 404]) {+ const poll = hostCommandPoller({+ claim: async () => new Response(null, { status }),+ run: async () => { throw new Error("Must not run"); }, settings, hidden: () => true,+ });+ expect(await poll()).toBeNull();+ }+});++test("network failures and Retry-After delay the next attempt", async () => {+ let networkFailure = true;+ const poll = hostCommandPoller({+ claim: async () => {+ if (networkFailure) throw new TypeError("Offline");+ return new Response(null, { status: 429, headers: { "Retry-After": "120" } });+ },+ run: async () => {}, settings, hidden: () => true,+ });+ expect(await poll()).toBe(6000);+ networkFailure = false;+ expect(await poll()).toBe(120000);+});++test("the next claim waits for the current batch to finish", async () => {+ let finish!: () => void;+ const completed = new Promise<void>((resolve) => { finish = resolve; });+ let ran = false;+ let returned = false;+ const poll = hostCommandPoller({+ claim: async () => Response.json({ id: "job", spec: { commands: [], readOnly: true } }),+ run: async (job) => { expect(job.id).toBe("job"); ran = true; await completed; },+ settings, hidden: () => false,+ });+ const next = poll().then((delay) => { returned = true; return delay; });+ await new Promise((resolve) => setTimeout(resolve, 0));+ expect(ran).toBe(true);+ expect(returned).toBe(false);+ finish();+ expect(await next).toBe(0);+});diff --git a/site/src/cut/lib/hostCommandPolling.ts b/site/src/cut/lib/hostCommandPolling.tsnew file mode 100644index 00000000..ee554693--- /dev/null+++ b/site/src/cut/lib/hostCommandPolling.ts@@ -0,0 +1,38 @@+import type { Settings } from "@/lib/config/registry";+import type { CommandJobSpec } from "@/cut/lib/commandBatch";++type Claimed = { id: string; spec: CommandJobSpec };++/** Each completed poll returns its next delay; an expired session stops it. */+export function hostCommandPoller(options: {+ claim: () => Promise<Response>;+ run: (job: Claimed) => Promise<void>;+ settings: () => Settings["chatgptPolling"];+ hidden: () => boolean;+}) {+ let backoff = 0;+ return async (): Promise<number | null> => {+ const settings = options.settings();+ const cadence = options.hidden() ? settings.hiddenPollMs : settings.pollMs;+ let retryAfter = 0;+ try {+ const response = await options.claim();+ if ([401, 403, 404].includes(response.status)) return null;+ if (response.status === 200 || response.status === 204) {+ if (response.status === 200) await options.run(await response.json() as Claimed);+ backoff = 0;+ return response.status === 200 ? 0 : cadence;+ }+ const retry = response.headers.get("retry-after");+ if (retry) {+ const seconds = Number(retry);+ retryAfter = Number.isFinite(seconds) ? seconds * 1000 : Date.parse(retry) - Date.now();+ if (!Number.isFinite(retryAfter)) retryAfter = 0;+ }+ } catch {+ // Network failures use the same bounded cadence as server failures.+ }+ backoff = Math.min(settings.maxBackoffMs, Math.max(cadence, backoff) * 2);+ return Math.max(backoff, retryAfter);+ };+}diff --git a/site/src/cut/lib/hostCommands.ts b/site/src/cut/lib/hostCommands.tsindex 2e863e6b..e1393a2b 100644--- a/site/src/cut/lib/hostCommands.ts+++ b/site/src/cut/lib/hostCommands.ts@@ -1,6 +1,8 @@"use client";import { useEffect } from "react";+import { chatgptPolling } from "@/cut/lib/chatRuntime";+import { hostCommandPoller } from "@/cut/lib/hostCommandPolling";import { runAiTool } from "./aiTools";import { apiFetch } from "./backend";import { runCommandBatch, type CommandJobSpec } from "./commandBatch";@@ -17,8 +19,6 @@ import { serializeDoc, useEditor } from "./store";* ChatGPT. Each batch is one undo step here, so the user's own ⌘Z and* ChatGPT's undo agree on what a step is.*/-const POLL_MS = 1000;-const HIDDEN_POLL_MS = 3000;const HEARTBEAT_MS = 10_000;const snapshot = () => JSON.stringify(serializeDoc(useEditor.getState()));@@ -114,22 +114,16 @@ export function useHostCommands(projectId: string, enabled: boolean): void {const schedule = (ms: number) => {if (!signal.aborted) timer = window.setTimeout(tick, ms);};- const claim = async (): Promise<{ id: string; spec: CommandJobSpec } | null> => {- const res = await apiFetch(`/api/cut/projects/${projectId}/commands/claim`, { method: "POST", signal });- return res.status === 200 ? ((await res.json()) as { id: string; spec: CommandJobSpec }) : null;- };+ const poll = hostCommandPoller({+ claim: () => apiFetch(`/api/cut/projects/${projectId}/commands/claim`, { method: "POST", signal }),+ run: (job) => runClaimed(projectId, job.id, job.spec, signal),+ settings: chatgptPolling,+ hidden: () => document.hidden,+ });const tick = async () => {if (signal.aborted) return;- let claimed: { id: string; spec: CommandJobSpec } | null = null;- try {- claimed = await claim();- } catch {- // A failed poll is asked again on the next tick.- }- if (!claimed) return schedule(document.hidden ? HIDDEN_POLL_MS : POLL_MS);- await runClaimed(projectId, claimed.id, claimed.spec, signal);- // Another batch may be waiting behind this one.- schedule(0);+ const delay = await poll();+ if (delay !== null) schedule(delay);};schedule(0);return () => {diff --git a/site/src/lib/config/effective.ts b/site/src/lib/config/effective.tsindex b4f373ed..ed93e6ad 100644--- a/site/src/lib/config/effective.ts+++ b/site/src/lib/config/effective.ts@@ -6,7 +6,7 @@ import { variantSchema, type ExperimentVariant } from "@/lib/config/experiment";import type { SettingKey, Settings } from "@/lib/config/registry";import { resolveSettings } from "@/lib/config/resolve";import type { DonkeyAuthenticatedRequest } from "@/lib/donkey-api-auth";-import { prisma } from "@/lib/prisma";+import { configureDatabasePool, prisma } from "@/lib/prisma";// What one user's configuration is right now: overrides from su, plus the// variants of every running experiment they are assigned to. Assignment@@ -58,7 +58,9 @@ export async function contextFromRequest(request: DonkeyAuthenticatedRequest): Pexport async function readOverrides(): Promise<Record<string, unknown>> {const rows = await prisma.settingOverride.findMany({ select: { key: true, value: true } });- return Object.fromEntries(rows.map((row) => [row.key, row.value]));+ const overrides = Object.fromEntries(rows.map((row) => [row.key, row.value]));+ configureDatabasePool(overrides);+ return overrides;}export function parseVariants(raw: Prisma.JsonValue): ExperimentVariant[] {diff --git a/site/src/lib/config/registry.ts b/site/src/lib/config/registry.tsindex b38903f3..f82d25bb 100644--- a/site/src/lib/config/registry.ts+++ b/site/src/lib/config/registry.ts@@ -31,6 +31,17 @@ function validTimeZone(zone: string): boolean {}export const SETTINGS = defineSettings({+ databasePool: {+ schema: z.object({+ maxConnections: z.number().int().min(1).max(20),+ idleTimeoutMs: z.number().int().min(100).max(30000),+ connectionTimeoutMs: z.number().int().min(100).max(30000),+ }).strict(),+ default: { maxConnections: 3, idleTimeoutMs: 5000, connectionTimeoutMs: 5000 },+ public: false,+ title: "Database connection pool",+ description: "Connections per server instance, idle connection lifetime, and connection wait limit. Instances start with defaults and apply overrides whenever they read settings. Existing connections drain at their idle deadline.",+ },chatgptApp: {schema: z.object({enabled: z.boolean(),@@ -54,6 +65,17 @@ export const SETTINGS = defineSettings({title: "ChatGPT app",description: "Account linking, allowed OAuth callbacks, token lifetimes, preview polling, how long an edit call waits and how long the card's editor has to claim it, and how long the editor stays signed in inside the card. Enable after the OAuth tables are deployed.",},+ chatgptPolling: {+ schema: z.object({+ pollMs: z.number().int().min(500).max(3000),+ hiddenPollMs: z.number().int().min(1000).max(3000),+ maxBackoffMs: z.number().int().min(10000).max(300000),+ }).strict(),+ default: { pollMs: 1000, hiddenPollMs: 3000, maxBackoffMs: 60000 },+ public: true,+ title: "ChatGPT editor polling",+ description: "Command polling cadence and maximum failure backoff. Expired sessions stop polling until the editor opens again.",+ },cutPreviewJobs: {schema: z.object({ maxAttempts: z.number().int().min(1).max(10) }).strict(),default: { maxAttempts: 5 },diff --git a/site/src/lib/databasePool.test.ts b/site/src/lib/databasePool.test.tsnew file mode 100644index 00000000..6029d68e--- /dev/null+++ b/site/src/lib/databasePool.test.ts@@ -0,0 +1,95 @@+import { EventEmitter } from "node:events";+import { afterEach, describe, expect, test } from "bun:test";+import type { Pool, PoolConfig } from "pg";++import { SETTINGS } from "@/lib/config/registry";+import { applyDatabasePoolOverride, createDatabasePool } from "@/lib/databasePool";++// Exercise pg's real admission queue and idle timers without a database.+class ConnectedClient extends EventEmitter {+ _queryable = true;+ _ending = false;++ connect(callback: () => void): void { queueMicrotask(callback); }+ end(callback?: () => void): void { this._ending = true; callback?.(); }+ ref(): void {}+ unref(): void {}+}++const pools: Pool[] = [];+function createPool(): Pool {+ const pool = createDatabasePool({ Client: ConnectedClient } as unknown as PoolConfig);+ pools.push(pool);+ return pool;+}++afterEach(async () => {+ await Promise.all(pools.splice(0).map((pool) => pool.end()));+});++describe("database connection budget", () => {+ test("parallel requests queue at the per-instance cap and reuse released connections", async () => {+ const pool = createPool();+ const active = await Promise.all(Array.from({ length: SETTINGS.databasePool.default.maxConnections }, () => pool.connect()));+ const queued = pool.connect();+ expect(pool.totalCount).toBe(3);+ expect(pool.waitingCount).toBe(1);+ active[0].release();+ const reused = await queued;+ expect(reused).toBe(active[0]);+ expect(pool.totalCount).toBe(3);+ reused.release();+ active.slice(1).forEach((client) => client.release());+ });++ test("runtime overrides limit new work and bound its wait without interrupting active work", async () => {+ const pool = createPool();+ const active = await pool.connect();+ applyDatabasePoolOverride(pool, { maxConnections: 1, idleTimeoutMs: 100, connectionTimeoutMs: 100 });+ await expect(pool.connect()).rejects.toThrow("timeout exceeded when trying to connect");+ expect(pool.totalCount).toBe(1);+ expect(pool.waitingCount).toBe(0);+ active.release();+ const reused = await pool.connect();+ expect(reused).toBe(active);+ reused.release();+ await new Promise((resolve) => setTimeout(resolve, 150));+ expect(pool.totalCount).toBe(0);+ });++ test("resetting an override restores the defaults on the same pool", async () => {+ const pool = createPool();+ applyDatabasePoolOverride(pool, { maxConnections: 1, idleTimeoutMs: 100, connectionTimeoutMs: 100 });+ applyDatabasePoolOverride(pool, undefined);+ expect(pool.options.max).toBe(SETTINGS.databasePool.default.maxConnections);+ expect(pool.options.idleTimeoutMillis).toBe(SETTINGS.databasePool.default.idleTimeoutMs);+ expect(pool.options.connectionTimeoutMillis).toBe(SETTINGS.databasePool.default.connectionTimeoutMs);+ });++ test("Vercel keeps the request alive until idle connections close", async () => {+ const contextKey = Symbol.for("@vercel/request-context");+ const previousContext: unknown = Reflect.get(globalThis, contextKey);+ const previousUrl = process.env.VERCEL_URL;+ const previousRegion = process.env.VERCEL_REGION;+ const waits: Promise<unknown>[] = [];+ try {+ process.env.VERCEL_URL = "pool-test.vercel.app";+ process.env.VERCEL_REGION = "test";+ Reflect.set(globalThis, contextKey, { get: () => ({ waitUntil: (promise: Promise<unknown>) => waits.push(promise) }) });+ const pool = createPool();+ applyDatabasePoolOverride(pool, { maxConnections: 1, idleTimeoutMs: 100, connectionTimeoutMs: 100 });+ const client = await pool.connect();+ client.release();+ expect(waits).toHaveLength(1);+ await waits[0];+ expect(pool.totalCount).toBe(0);+ } finally {+ if (previousUrl === undefined) delete process.env.VERCEL_URL;+ else process.env.VERCEL_URL = previousUrl;+ if (previousRegion === undefined) delete process.env.VERCEL_REGION;+ else process.env.VERCEL_REGION = previousRegion;+ if (previousContext === undefined) Reflect.deleteProperty(globalThis, contextKey);+ else Reflect.set(globalThis, contextKey, previousContext);+ }+ });+});diff --git a/site/src/lib/databasePool.ts b/site/src/lib/databasePool.tsnew file mode 100644index 00000000..dfb4ea24--- /dev/null+++ b/site/src/lib/databasePool.ts@@ -0,0 +1,30 @@+import { attachDatabasePool } from "@vercel/functions";+import { Pool, type PoolConfig } from "pg";++import { SETTINGS } from "@/lib/config/registry";++export function createDatabasePool(config: PoolConfig): Pool {+ const settings = SETTINGS.databasePool.default;+ const pool = new Pool({+ ...config,+ max: settings.maxConnections,+ idleTimeoutMillis: settings.idleTimeoutMs,+ connectionTimeoutMillis: settings.connectionTimeoutMs,+ allowExitOnIdle: true,+ });+ attachDatabasePool(pool);+ return pool;+}++export function applyDatabasePoolOverride(pool: Pool, value: unknown): void {+ const parsed = SETTINGS.databasePool.schema.safeParse(value ?? SETTINGS.databasePool.default);+ if (!parsed.success) {+ console.error('[config] override for setting "databasePool" no longer parses; skipped');+ }+ const settings = parsed.success ? parsed.data : SETTINGS.databasePool.default;+ // Updating the pool keeps checked-out transactions alive. Existing idle+ // connections retain their deadline; new acquisitions use the new limits.+ pool.options.max = settings.maxConnections;+ pool.options.idleTimeoutMillis = settings.idleTimeoutMs;+ pool.options.connectionTimeoutMillis = settings.connectionTimeoutMs;+}diff --git a/site/src/lib/prisma.ts b/site/src/lib/prisma.tsindex 0a624eab..0f3dadf5 100644--- a/site/src/lib/prisma.ts+++ b/site/src/lib/prisma.ts@@ -1,9 +1,12 @@import { PrismaPg } from "@prisma/adapter-pg";+import type { Pool } from "pg";import { PrismaClient } from "@/generated/prisma/client";+import { applyDatabasePoolOverride, createDatabasePool } from "@/lib/databasePool";const globalForPrisma = globalThis as unknown as {prisma?: PrismaClient;+ databasePool?: Pool;};function createPrismaClient() {@@ -13,13 +16,18 @@ function createPrismaClient() {throw new Error("DATABASE_URL is not configured.");}- const adapter = new PrismaPg({ connectionString });+ const pool = globalForPrisma.databasePool ?? createDatabasePool({ connectionString });+ globalForPrisma.databasePool = pool;+ const adapter = new PrismaPg(pool, { disposeExternalPool: true });return new PrismaClient({ adapter });}export const prisma = globalForPrisma.prisma ?? createPrismaClient();+globalForPrisma.prisma = prisma;-if (process.env.NODE_ENV !== "production") {- globalForPrisma.prisma = prisma;+export function configureDatabasePool(overrides: Record<string, unknown>): void {+ if (globalForPrisma.databasePool) {+ applyDatabasePoolOverride(globalForPrisma.databasePool, overrides.databasePool);+ }}