Files
puter/src/backend/testUtil.ts
T
Filip KujundžićandDaniel Salazar 2d12dcc99f Reorganize AI drivers and harden request handling (#4614)
* Move the AI drivers into drivers/ai

The seven drivers/ai-* folders and the AI-only helpers in drivers/util
become one tree:

  drivers/ai/interfaces/<interface>/            the Puter-facing drivers
  drivers/ai/providers/<vendor>/<interface>/    vendor adapters, catalogs, tests
  drivers/ai/protocols/openaiCompatible/        the shared OpenAI wire protocol
  drivers/ai/shared/                            helpers several interfaces use

Files are moved and their relative imports rewritten; no implementation
changes. Driver names, aliases, interfaces, config keys, model ids and
usage keys are unchanged.

The chat catalog registration test scanned providers/*/ next to itself.
It now scans providers/*/chat/ and fails if the scan finds no catalog, so
a wrong directory can't pass it.

General helpers that non-AI code also uses stay in drivers/util: file
input, data URIs, upstream errors, stream piping, CRUD limits.

* Document the AI driver layout

doc/ai-drivers.md explains what interfaces, providers, protocols and
shared each own, the import rules between them, where a new file goes,
and the steps for adding a provider or an AI interface. It also lists
the three places that don't follow the layout yet.

doc/architecture.md and AGENTS.md link to it.

* Move catalogPrice into ai/shared

Chat providers and the Cloudflare and xAI image catalogs all parse vendor
prices with catalogPrice, so it lives in shared/ instead of the chat
interface's pricing helpers. The image catalogs no longer import from
the chat interface.

* Move the Textract and Mistral OCR calls into provider classes

OCRDriver held both vendors' clients, request building, response
normalizing and metering. That now lives in TextractOcrProvider
(providers/awsTextract/ocr) and MistralOcrProvider (providers/mistral/ocr),
both implementing IOcrProvider. The driver keeps the provider catalog,
model resolution, auth and credit gates, and input resolution.

The page estimate, document detection and credit hold both providers use
are in interfaces/ocr/common.ts.

No behavior change: same validation order, error messages, usage keys,
holds and charges.

* Move the ElevenLabs voice changer into a provider class

VoiceChangerDriver built the ElevenLabs request, measured the converted
audio and metered it, and imported the output formats from the ElevenLabs
text-to-speech provider. That code is now in providers/elevenlabs:

  outputFormats.ts                         formats both speech interfaces use
  speechToSpeech/ElevenLabsSpeechToSpeechProvider.ts
  speechToSpeech/measuredOutput.ts         WAV, Opus and byte-rate timing
  speechToSpeech/costs.ts

The driver keeps provider resolution, test mode and the auth check. With
one provider it holds the class directly; there is no provider interface.

No behavior change: same validation order, error messages, usage keys,
holds and charges.

* Move the AI billing helpers the realtime relay uses below the driver layer

OpenAIRealtimeRelayService is a service, and it imported the cost factor,
the provider key reader and a transcription price from drivers/ai. Those
now live in src/backend/util, which both layers can import:

  util/aiCostFactor.ts    withAiCostFactor, withAiCreditHold and the
                          request cost helpers, unchanged
  util/aiProviderKey.ts   readProviderKey, cut from providerRegistry.ts
  util/aiPrices.ts        the gpt-transcribe per-second price, read by the
                          OpenAI speech-to-text cost table and the relay

withStreamedAiCharge returns a DriverStreamResult, so it stays in the
driver layer as drivers/ai/shared/streamedAiCharge.ts with its tests.

MeteringService is untouched. No prices or billing behavior change.

* Remove the aiUserIdentifier alias

shared/aiUserIdentifier.ts re-exported upstreamUserIdentifier under a
second name, and only its own test imported it. The alias is gone; its
tests, which cover truncation and actor shapes the other file didn't,
replace the four cases in upstreamIdentifier.test.ts.

* Move the AI test helpers into the AI tree

drivers/integrationTestUtil.ts held helpers for AI provider tests, but a
store test and the realtime relay test imported from it too.

  drivers/ai/shared/integrationTestUtil.ts   the provider test helpers
  testEnv.ts                                 optionalEnv and skipUnlessEnv,
                                             for any env-gated suite
  testUtil.ts                                withAiCostFactorHook, next to
                                             the server it hooks

No test under services/ or stores/ imports from the driver layer's AI
code now. The typecheck baseline entry for the moved file is renamed, not
regenerated.

* Split the tool and compaction helpers by dialect

FunctionCalling.js and compaction.js each held Puter-facing parsing next
to OpenAI and Anthropic request shapes. Each dialect now owns its mapping:

  interfaces/chat/utils     normalize_tools_object, readCompaction and the
                            other dialect-neutral checks
  protocols/openaiCompatible/openaiParams.ts
                            toolsToWire (was make_openai_tools) and
                            toOpenAiContextManagement
  providers/claude/chat/contextManagement.ts
                            toAnthropicContextManagement

toolsToWire takes the dialect as its second argument, like the other
mappers in that module, and takes an array; every caller already guarded
the empty case.

make_claude_tools is removed. Nothing but its tests called it: the Claude
provider uses claudeToolPolicy directly. The three cases only those tests
had are added to the claudeToolPolicy tests. The chat interface helpers no
longer import from providers/claude.

* Remove the unused ImageProvider base class

Every image provider implements IImageProvider directly; nothing extended
or imported the abstract class in interfaces/image/ImageProvider.ts.

The guide's import rules now say that only an interface's driver file
imports providers, which holds since the tool helpers stopped importing
the Claude policy.

* Rerun Replicate predictions an output safety checker rejects

Some community models check the generated image and fail the
prediction with "Try running it again" for a share of seeds, whatever
the prompt. adirik/realvisxl-v3.0-turbo failed 5 of 24 runs of "a small
red cube on a white table" that way.

A prediction that fails with that message is now run again, up to two
more times, inside the same deadline and credit hold. A request that
pins a seed is not rerun, because the same seed is rejected again.
Only the prediction that succeeds is metered, as before.

* Answer malformed AI requests with a 400 where they enter

A value that used to end in an unclassified error, in a request or in
an upstream answer, now gets a classified one before provider code runs
on it. A value a driver or provider ignored or refused before is
handled as it was.

Every driver:
- shared/scalarOptions.ts answers 400 for a value that cannot be
  converted to text, such as { "toString": null }, in the options a
  driver reads as text, a number or a flag. The chat, video, text to
  speech, speech to text, voice changer and OCR drivers call it first.
- An unknown provider name that is not text gets the same 400 as any
  other unknown name.

Chat requests:
- A falsy `tools` means no tools on every provider.
- A tool call id or a content block type that cannot be converted to
  text is a 400.
- A tool result that is an object is sent as its JSON, like the content
  of a `tool` message.
- `include` that is not an array is a 400.
- `anthropicBetas` that is not a list of names is dropped.
- Gemini's native route answers 400 when no user or assistant message
  is left to send.
- The prompt estimate reads a compaction block whose content is not a
  string.

Image, video, speech and OCR requests:
- The image driver checks `input_image_mime_type` with `quality` and
  `resolution`.
- The video driver answers 400 for a model that is not a string.
- The voice changer answers 400 for an `output_format` that is not a
  string.
- Mistral OCR answers 400 when the SDK refuses the options before
  sending them, as Mistral chat does.

Upstream answers to chat:
- A choice without a message is the existing 400 bad_response, which
  still falls back.
- A usage count that is not a number is reported as zero in the cost
  event, as pricing already skips it.

* Fuzz the AI drivers with seeded requests and upstream answers

Two seeded suites send malformed input through the real drivers and
providers. The vendors are played at the HTTP boundary, so each
provider's request and response code runs.

- ChatCompletionDriver.fuzz.test.ts covers the 17 chat providers that
  have a static catalog. Requests with a few values changed must
  resolve or reject below 500 without marking a route unhealthy.
  Valid requests against wrong statuses, bodies of the wrong shape and
  broken event streams must end with an answer or a classified error.
  A stream only has to end; the error line it carries is not checked.
- mediaDrivers.fuzz.test.ts covers the image, video, speech and OCR
  drivers, called as a user with unlimited metering so a request gets
  past file input and the credit hold. Every vendor refuses the
  request, and every call must end with a classified error.

shared/fuzzTestUtil.ts holds the seeded random source, the hostile JSON
values, the mutation, and the stand-in for fetch, undici and axios. An
SDK that calls https.request itself fails the suite. PUTER_FUZZ_CASES
raises the case count for a longer run. doc/ai-drivers.md describes the
suites.

* Restore the CODEOWNERS default owner and wildcard patterns

The default owner line read `- @Salazareo`, which only matches a file
named `-`, so files without a specific owner had none. Three patterns
had their `*` escaped, which GitHub rejects as invalid, so their lines
assigned no owner.

---------

Co-authored-by: Daniel Salazar <daniel.salazar@puter.com>
2026-11-14 00:23:04 -07:00

600 lines
21 KiB
TypeScript

import bcrypt from 'bcrypt';
import { mkdtempSync, rmSync } from 'node:fs';
import { ServerResponse, type IncomingMessage } from 'node:http';
import { createServer } from 'node:net';
import type { AddressInfo } from 'node:net';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { v4 as uuidv4 } from 'uuid';
import { deepMerge } from '../../tools/lib/configMigration.mjs';
import { makeActor } from './core/actor';
import type { Actor } from './core/actor';
import { runWithContext } from './core/context';
import { PuterServer } from './server';
import { IConfig } from './types';
import { puterClients } from './clients';
import type { EventClient } from './clients/event/EventClient';
import {
PostgresDatabaseClient,
type PostgresPool,
} from './clients/database/PostgresDatabaseClient';
import { SqliteDatabaseClient } from './clients/database/SqliteDatabaseClient';
import type { PoolConfig } from 'pg';
import { ADMIN_GROUP_UID } from './services/selfhosted/DefaultUserService';
import { FULL_API_ACCESS } from './services/permission/consts';
import { WORKER_SUBDOMAIN_PREFIX } from './stores/subdomain/SubdomainStore.js';
import { generateDefaultFsentries } from './util/userProvisioning';
export const POSTGRES_TEST_MIGRATIONS_PATH =
'src/backend/clients/database/migrations/postgres';
type PgMockPostgresHarness = {
client: PostgresDatabaseClient;
createClient: () => PostgresDatabaseClient;
destroy: () => void;
};
const usesPgMockPostgres = (config: IConfig): boolean => {
const database = config.database;
if (database?.engine !== 'postgres' || database.inMemory !== true) {
return false;
}
return !(
database.connectionString ||
database.url ||
database.host ||
database.port ||
database.user ||
database.password ||
database.database ||
database.replica
);
};
export const createPgMockPostgresDatabaseClient = async (
config: IConfig,
): Promise<PgMockPostgresHarness> => {
const [{ PostgresMock }, { Pool }] = await Promise.all([
import('pgmock'),
import('pg'),
]);
const mock = await PostgresMock.create();
const pgMockConfig = mock.getNodePostgresConfig();
const createPgMockStream = pgMockConfig.stream;
const poolFactory = (poolConfig: PoolConfig): PostgresPool =>
new Pool({
...poolConfig,
database: 'postgres',
...pgMockConfig,
stream: () => {
const stream = createPgMockStream();
stream.ref = () => stream;
stream.unref = () => stream;
return stream;
},
}) as unknown as PostgresPool;
const createClient = () => new PostgresDatabaseClient(config, poolFactory);
return {
client: createClient(),
createClient,
destroy: () => mock.destroy(),
};
};
/**
* When `PUTER_TEST_DB_ENGINE=postgres` is set, `setupTestServer` swaps its
* default sqlite test database for an in-memory Postgres backed by pgmock (with
* the bundled Postgres migrations applied on boot). Tests that explicitly
* override `database` still win — the env var only affects the implicit default
* used by callers that don't pass any DB overrides.
*
* Recognized values: `postgres` → pgmock. Anything else (including unset) → the
* original sqlite-in-memory default.
*/
const testDatabaseDefault = (): IConfig['database'] => {
const engine = (process.env.PUTER_TEST_DB_ENGINE ?? '').toLowerCase();
if (engine === 'postgres') {
return {
engine: 'postgres',
inMemory: true,
migrationPaths: [POSTGRES_TEST_MIGRATIONS_PATH],
};
}
return { engine: 'sqlite', inMemory: true };
};
export type SetupTestServerOptions = {
/**
* Listen on a real HTTP port so external clients (puter.js runners,
* workerd, browsers) can connect. Default: in-process only, no listener.
*/
listen?: boolean;
};
/**
* Grab a free port by binding to 0 and releasing it. Done up-front (rather than
* letting the server listen on 0) so the port is known while building config —
* `origin` / `api_base_url` consumers like LocalWorkerService read it at
* construction time.
*/
export const allocateEphemeralPort = (): Promise<number> =>
new Promise((resolve, reject) => {
const probe = createServer();
probe.unref();
probe.on('error', reject);
probe.listen(0, '127.0.0.1', () => {
const { port } = probe.address() as AddressInfo;
probe.close(() => resolve(port));
});
});
// The JSON module's payload lives on `.default` — merging the namespace
// itself would bury every value under a stray `default` key.
const loadDefaultConfig = async (): Promise<IConfig> => {
const { default: defaultConfig } = await import(
'../../config.default.json',
{
with: {
type: 'json',
},
}
);
return defaultConfig as unknown as IConfig;
};
export const setupTestServer = async (
configOverrides?: IConfig,
options?: SetupTestServerOptions,
): Promise<PuterServer> => {
const defaultConfig = await loadDefaultConfig();
// merge default config with overrides and test defaults
const config = deepMerge(
deepMerge(defaultConfig, {
extensions: [],
port: 0,
database: testDatabaseDefault(),
dynamo: { inMemory: true, bootstrapTables: true },
redis: { useMock: true },
// Suites run system jobs themselves, not on the poll timer.
jobs: { enabled: false },
// The health loop's timed `SELECT 1` would land in tests that
// count queries.
server_health: { disabled_checks: ['database-liveness'] },
s3: { localConfig: { inMemory: true } },
no_default_user: true,
no_devwatch: true,
no_browser_launch: true,
import_ts_extensions: true,
}),
configOverrides ?? {},
) as IConfig;
// Ollama auto-discovers unless disabled, probing localhost on every boot
// and logging the failure after the test may have finished.
config.providers ??= {};
config.providers.ollama ??= { enabled: false };
if (options?.listen) {
if (!config.port) config.port = await allocateEphemeralPort();
// Derive from `domain` so the advertised origins match the host
// the subdomain gates expect (`api.<domain>` for API routes).
const host = config.domain ?? '127.0.0.1';
config.origin ??= `http://${host}:${config.port}`;
config.api_base_url ??= config.domain
? `http://api.${config.domain}:${config.port}`
: config.origin;
}
let pgMockClient: PgMockPostgresHarness | undefined;
if (usesPgMockPostgres(config)) {
const database = config.database;
if (!database) {
throw new Error('Postgres test database config is missing');
}
database.migrationPaths ??= [POSTGRES_TEST_MIGRATIONS_PATH];
pgMockClient = await createPgMockPostgresDatabaseClient(config);
}
const server = new PuterServer(
config,
pgMockClient ? { ...puterClients, db: pgMockClient.client } : undefined,
);
if (pgMockClient) {
const originalShutdown = server.shutdown.bind(server);
let destroyPgMock: (() => void) | undefined = pgMockClient.destroy;
server.shutdown = async () => {
try {
await originalShutdown();
} finally {
destroyPgMock?.();
destroyPgMock = undefined;
}
};
}
try {
await server.start(!options?.listen);
} catch (e) {
// Stops whatever boot already started; also destroys the pgmock.
try {
await server.shutdown();
} catch {
// the start error is the one worth reporting
}
throw e;
}
return server;
};
const PORT_ATTEMPTS = 3;
/**
* `allocateEphemeralPort` releases the port before boot listens on it, and
* another process can take it in between, so boot again on a fresh one.
*/
const bootOnFreshPort = async <T>(
boot: (port: number) => Promise<T>,
): Promise<T> => {
for (let attempt = 1; ; attempt++) {
const port = await allocateEphemeralPort();
try {
return await boot(port);
} catch (e) {
const inUse =
(e as NodeJS.ErrnoException | undefined)?.code === 'EADDRINUSE';
if (!inUse || attempt >= PORT_ATTEMPTS) throw e;
}
}
};
export type TestUserCredentials = {
username: string;
password: string;
token: string;
/**
* Full-access access token (what the dashboard's "API Token" flow mints).
* The `/puterai/*` wire routes reject bare session tokens
* (`noUserSession`), so suites exercising them authenticate with this.
*/
apiToken: string;
/**
* User-scoped worker session token (what deploying a worker with no app
* binding mints — `kind='worker'` session row). Never treated as a root
* token: suites use it to prove worker credentials pass the `noUserSession`
* gates.
*/
workerToken: string;
};
/**
* Seed a user with a known password directly through the stores (same steps as
* DefaultUserService's admin bootstrap: bcrypt-hashed password, home directory
* tree, optional admin-group membership) and mint a session token the same way
* `POST /login` does.
*/
export const createTestUser = async (
server: PuterServer,
opts: { username: string; password: string; admin?: boolean },
): Promise<TestUserCredentials> => {
const passwordHash = await bcrypt.hash(opts.password, 8);
const created = await server.stores.user.create({
username: opts.username,
uuid: uuidv4(),
password: passwordHash,
email: null,
requires_email_confirmation: false,
});
// Driver permissions no longer come from here (see
// `default_user_permissions`), but group-issued ACL grants do, and a
// verified signup is a member of the default user group.
const { default_user_group } = await loadDefaultConfig();
if (default_user_group) {
await server.stores.group.addUsers(default_user_group, [opts.username]);
}
if (opts.admin) {
await server.stores.group.addUsers(ADMIN_GROUP_UID, [opts.username]);
}
await generateDefaultFsentries(
server.clients.db,
server.stores.user,
created,
);
const user = (await server.stores.user.getById(created.id)) ?? created;
const { token } = await server.services.auth.createSessionToken(user, {
user_agent: 'puter-test-env',
});
// Mint the delegated credential the same way the dashboard's
// "API Token" flow does (POST /auth/create-access-token with the
// full-api-access sentinel).
const apiToken = await server.services.auth.createAccessToken(
makeActor({ user }),
[[FULL_API_ACCESS]],
{ label: 'puter-test-env' },
);
// Mint a user-scoped worker token the same way deploying an app-less
// worker does (WorkerDriver falls back to createWorkerSessionToken). The
// token only lives as long as its worker row, so seed one.
const workerName = `test-env-worker-${user.id}`;
const workerRow = await server.stores.subdomain.create({
userId: user.id,
subdomain: `${WORKER_SUBDOMAIN_PREFIX}${workerName}`,
});
const { token: workerToken } =
await server.services.auth.createWorkerSessionToken(
makeActor({ user }),
user,
workerName,
{},
{ workerUid: workerRow.uuid },
);
return {
username: opts.username,
password: opts.password,
token,
apiToken,
workerToken,
};
};
export type PuterTestEnv = {
/**
* Root origin (`http://puter.localhost:<port>`) — GUI and root-only routes
* like `POST /login` live here.
*/
origin: string;
/**
* API origin (`http://api.puter.localhost:<port>`) — what puter.js clients
* use as their APIOrigin. Routes gated on the `api` subdomain (e.g.
* `/whoami`) only match this host.
*/
apiOrigin: string;
/**
* Seeded accounts: an admin and two regular (non-privileged) users. `other`
* exists so suites can exercise cross-user flows (permission grants, access
* denials) without creating users on the fly.
*/
users: {
admin: TestUserCredentials;
user: TestUserCredentials;
other: TestUserCredentials;
};
server: PuterServer;
shutdown: () => Promise<void>;
};
export const TEST_ADMIN_CREDENTIALS = {
username: 'admin',
password: 'puter-test-admin-password',
};
export const TEST_USER_CREDENTIALS = {
username: 'testuser',
password: 'puter-test-user-password',
};
export const TEST_OTHER_USER_CREDENTIALS = {
username: 'otheruser',
password: 'puter-test-other-password',
};
/**
* Boot an in-memory Puter server on a real ephemeral port with deterministic
* credentials, for client test runners (puter.js on node, browsers, workerd).
* Clients can authenticate with the pre-minted tokens or via a real `POST
* /login` using the fixed passwords — no stdout scraping.
*/
export const setupPuterTestEnv = async (
configOverrides?: IConfig,
): Promise<PuterTestEnv> => {
// Real hostnames rather than 127.0.0.1: API routes are gated on the
// `api` subdomain, and `*.localhost` resolves to loopback on modern
// platforms (and in browsers).
const domain = 'puter.localhost';
// Unlike unit-test servers (extensions: []), the client env loads the
// real extensions — clients depend on endpoints that live there
// (e.g. /whoami). Resolved from this module so cwd doesn't matter.
const extensionsDir = fileURLToPath(
new URL('../../extensions', import.meta.url),
);
const { server, origin, apiOrigin } = await bootOnFreshPort(
async (port) => {
const origin = `http://${domain}:${port}`;
const apiOrigin = `http://api.${domain}:${port}`;
const server = await setupTestServer(
deepMerge(
{
port,
domain,
origin,
api_base_url: apiOrigin,
// The browser runner serves its fixture page from the
// API origin so the SDK runs same-origin, which makes
// that origin this env's GUI. A browser overrides any
// `Origin` header a test sets, so without this the
// credential routes behind `guiOriginGate` (/login,
// /signup, /session/sync-cookie) 403 in the browser
// while passing everywhere else.
allow_gui_origins: [apiOrigin],
extensions: [extensionsDir],
},
configOverrides ?? {},
) as IConfig,
{ listen: true },
);
return { server, origin, apiOrigin };
},
);
try {
const admin = await createTestUser(server, {
...TEST_ADMIN_CREDENTIALS,
admin: true,
});
const user = await createTestUser(server, TEST_USER_CREDENTIALS);
const other = await createTestUser(server, TEST_OTHER_USER_CREDENTIALS);
return {
origin,
apiOrigin,
users: { admin, user, other },
server,
shutdown: () => server.shutdown(),
};
} catch (e) {
await server.shutdown().catch(() => {});
throw e;
}
};
/**
* `controller` with each handler run inside a request scope of its own, as the
* router runs it — for tests that call handlers directly. The scope carries the
* request's actor.
*/
export const inRequestScope = <T extends object>(controller: T): T =>
new Proxy(controller, {
get(target, prop) {
const value = Reflect.get(target, prop, target);
if (typeof value !== 'function') return value;
return (...args: unknown[]) =>
runWithContext(
{
actor: (args[0] as { actor?: Actor } | undefined)
?.actor,
},
() => value.apply(target, args),
);
},
});
/** Adds a replica that, for `queries`, is empty, a copy from now, or current. */
export const lagReadReplica = async (
server: PuterServer,
queries: RegExp,
{ mode = 'missing' }: { mode?: 'missing' | 'frozen' | 'current' } = {},
) => {
type Read = (sql: string, params?: unknown[]) => Promise<unknown[]>;
const db = server.clients.db as unknown as Record<string, unknown> & {
read: Read;
};
let frozen: SqliteDatabaseClient | null = null;
let frozenDir: string | null = null;
if (mode === 'frozen') {
frozenDir = mkdtempSync(join(tmpdir(), 'puter-replica-'));
const path = join(frozenDir, 'replica.sqlite');
await server.clients.db.write('VACUUM INTO ?', [path]);
frozen = new SqliteDatabaseClient({
port: 0,
extensions: [],
database: { engine: 'sqlite', path },
} as IConfig);
await frozen.onServerStart();
}
const names = ['read', 'pread', 'hasReadReplica'];
const own = names.map((name) => Object.getOwnPropertyDescriptor(db, name));
const read = db.read.bind(db);
let primaryReads = 0;
db.hasReadReplica = () => true;
db.read = async (sql: string, params: unknown[] = []) => {
if (mode === 'current' || !queries.test(sql)) return read(sql, params);
return frozen ? frozen.read(sql, params) : [];
};
db.pread = async (sql: string, params: unknown[] = []) => {
if (queries.test(sql)) primaryReads++;
return read(sql, params);
};
return {
primaryReads: () => primaryReads,
catchUp: () => {
names.forEach((name, i) => {
const descriptor = own[i];
if (descriptor) Object.defineProperty(db, name, descriptor);
else delete db[name];
});
frozen?.onServerShutdown();
if (frozenDir) rmSync(frozenDir, { recursive: true, force: true });
},
};
};
/** Runs `fn` with every AI driver's cost factor hooked to `factor`. */
export const withAiCostFactorHook = async <T>(
events: EventClient,
factor: number,
fn: () => Promise<T>,
): Promise<T> => {
const hook = (_key: string, event: { factor: number }) => {
event.factor = factor;
};
events.on('ai.cost.factor.*', hook);
try {
return await fn();
} finally {
events.off('ai.cost.factor.*', hook);
}
};
/**
* The most `close` listeners the backend may leave on one response. Request
* tracing adds up to five of its own, and Node warns past ten.
*/
export const RESPONSE_CLOSE_LISTENER_BUDGET = 5;
/**
* Records the most `close` listeners each server response held at once. The
* hook is process-wide, so call `restore` when done.
*/
export const trackResponseCloseListeners = () => {
const peaks = new Map<ServerResponse, number>();
const proto = ServerResponse.prototype as unknown as Record<
string,
(
this: ServerResponse,
event: string | symbol,
listener: unknown,
) => unknown
>;
const methods = ['on', 'addListener', 'prependListener'];
const own = methods.map((m) => Object.getOwnPropertyDescriptor(proto, m));
for (const method of methods) {
const original = proto[method]!;
proto[method] = function (event, listener) {
const result = original.call(this, event, listener);
if (event === 'close') {
const count = this.listenerCount('close');
peaks.set(this, Math.max(peaks.get(this) ?? 0, count));
}
return result;
};
}
return {
/** The highest count on any response to a request `match` accepts. */
peak: (match: (req: IncomingMessage) => boolean): number =>
Math.max(
0,
...[...peaks]
.filter(([res]) => match(res.req))
.map(([, count]) => count),
),
restore: () => {
methods.forEach((method, i) => {
const descriptor = own[i];
if (descriptor)
Object.defineProperty(proto, method, descriptor);
else delete proto[method];
});
},
};
};