diff --git a/graphql/env/README.md b/graphql/env/README.md index a147cbd9b5..f651d7d967 100644 --- a/graphql/env/README.md +++ b/graphql/env/README.md @@ -91,6 +91,18 @@ PostgreSQL extensions or change the API's exposed schemas. Each cache limit must be a safe integer of at least `2`. When omitted, Grafast's upstream default for that cache remains in effect. +### Schema Build Limits +- `GRAPHILE_BUILD_CONCURRENCY` - Handler builds that may run at once in the process (default `2`, at least `1`) +- `GRAPHILE_BUILD_QUEUE_MAX` - Builds that may wait for a slot (default `64`; `0` refuses at once while every slot is busy) +- `GRAPHILE_BUILD_QUEUE_WAIT_MS` - How long a build may wait for a slot (default `30000`; `0` never waits) + +A request whose API has no cached handler waits for a build slot. When the +queue is full or the wait expires, the request is refused with HTTP 503, a +`Retry-After` header (the queue wait in seconds, at most 60) and the +`SCHEMA_BUILD_UNAVAILABLE` error code, so clients and load balancers can retry. A build that cannot reach the database is +answered the same way. Invalid values fail option resolution with the variable +name. + ### Grafast Explain - `GRAPHILE_EXPLAIN` - Allow clients to request Grafast plan/SQL output via the `x-graphql-explain` header (off unless set) diff --git a/graphql/env/__tests__/build-limits.test.ts b/graphql/env/__tests__/build-limits.test.ts new file mode 100644 index 0000000000..93715f4b2e --- /dev/null +++ b/graphql/env/__tests__/build-limits.test.ts @@ -0,0 +1,119 @@ +import * as fs from 'fs'; +import * as os from 'os'; +import * as path from 'path'; + +import { normalizeGraphileBuildLimits } from '../src/build-limits'; +import { getGraphQLEnvVars } from '../src/env'; +import { getEnvOptions } from '../src/merge'; + +describe('Graphile build-limit configuration', () => { + it('leaves the bounds to the server defaults when nothing is configured', () => { + expect(getEnvOptions({}, process.cwd(), {}).graphile?.buildLimits).toBeUndefined(); + }); + + it('normalizes a partial configuration into an immutable copy', () => { + const input = { concurrency: 4, queueWaitMs: 0 }; + const normalized = normalizeGraphileBuildLimits(input); + input.concurrency = 8; + + expect(normalized).toEqual({ concurrency: 4, queueWaitMs: 0 }); + expect(Object.isFrozen(normalized)).toBe(true); + }); + + it.each([0, -1, 1.5, Number.MAX_SAFE_INTEGER + 1, Infinity, NaN])( + 'rejects a concurrency of %s', + (value) => { + expect(() => normalizeGraphileBuildLimits({ concurrency: value })).toThrow( + 'graphile.buildLimits.concurrency must be a safe integer of at least 1' + ); + } + ); + + it('accepts zero for the queue bounds and rejects waits setTimeout cannot honour', () => { + expect(normalizeGraphileBuildLimits({ queueMax: 0, queueWaitMs: 0 })).toEqual({ + queueMax: 0, + queueWaitMs: 0 + }); + expect(normalizeGraphileBuildLimits({ queueWaitMs: 2_147_483_647 })).toEqual({ + queueWaitMs: 2_147_483_647 + }); + expect(() => normalizeGraphileBuildLimits({ queueWaitMs: 2_147_483_648 })).toThrow( + 'graphile.buildLimits.queueWaitMs must be an integer from 0 to 2147483647' + ); + expect(() => normalizeGraphileBuildLimits({ queueMax: -1 })).toThrow( + 'graphile.buildLimits.queueMax must be a safe integer of at least 0' + ); + }); + + it('rejects malformed objects and unknown settings', () => { + expect(() => normalizeGraphileBuildLimits([] as unknown as {})).toThrow( + 'graphile.buildLimits must be an object' + ); + expect(() => normalizeGraphileBuildLimits(null as unknown as {})).toThrow( + 'graphile.buildLimits must be an object' + ); + expect(() => + normalizeGraphileBuildLimits({ maxConcurrency: 4 } as unknown as {}) + ).toThrow("graphile.buildLimits contains unsupported setting 'maxConcurrency'"); + }); + + it('maps all three environment variables', () => { + expect( + getGraphQLEnvVars({ + GRAPHILE_BUILD_CONCURRENCY: '3', + GRAPHILE_BUILD_QUEUE_MAX: '0', + GRAPHILE_BUILD_QUEUE_WAIT_MS: '15000' + }).graphile?.buildLimits + ).toEqual({ concurrency: 3, queueMax: 0, queueWaitMs: 15_000 }); + }); + + it.each(['', '0', '-1', '1.5', 'two'])( + 'rejects an invalid GRAPHILE_BUILD_CONCURRENCY %p', + (value) => { + expect(() => getGraphQLEnvVars({ GRAPHILE_BUILD_CONCURRENCY: value })).toThrow( + 'GRAPHILE_BUILD_CONCURRENCY must be a safe integer of at least 1' + ); + } + ); + + it('rejects an out-of-range GRAPHILE_BUILD_QUEUE_WAIT_MS', () => { + expect(() => getGraphQLEnvVars({ GRAPHILE_BUILD_QUEUE_WAIT_MS: '2147483648' })).toThrow( + 'GRAPHILE_BUILD_QUEUE_WAIT_MS must be an integer from 0 to 2147483647' + ); + }); + + it('keeps the environment silent when no limit is set', () => { + expect(getGraphQLEnvVars({}).graphile?.buildLimits).toBeUndefined(); + }); + + it('merges config, environment and overrides before validating', () => { + const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'graphile-build-limits-')); + try { + fs.writeFileSync( + path.join(tempDir, 'pgpm.json'), + JSON.stringify({ graphile: { buildLimits: { concurrency: 4, queueMax: 16 } } }) + ); + + const options = getEnvOptions( + { graphile: { buildLimits: { queueWaitMs: 5_000 } } }, + tempDir, + { GRAPHILE_BUILD_QUEUE_MAX: '8' } + ); + + expect(options.graphile?.buildLimits).toEqual({ + concurrency: 4, + queueMax: 8, + queueWaitMs: 5_000 + }); + expect(Object.isFrozen(options.graphile?.buildLimits)).toBe(true); + } finally { + fs.rmSync(tempDir, { recursive: true, force: true }); + } + }); + + it('rejects an invalid runtime override during final validation', () => { + expect(() => + getEnvOptions({ graphile: { buildLimits: { concurrency: 0 } } }, process.cwd(), {}) + ).toThrow('graphile.buildLimits.concurrency must be a safe integer of at least 1'); + }); +}); diff --git a/graphql/env/src/build-limits.ts b/graphql/env/src/build-limits.ts new file mode 100644 index 0000000000..aab4f3ec98 --- /dev/null +++ b/graphql/env/src/build-limits.ts @@ -0,0 +1,72 @@ +import type { GraphileBuildLimits } from '@constructive-io/graphql-types'; +import { parseEnvNumber } from '12factor-env'; + +type BuildLimitKey = keyof GraphileBuildLimits; + +interface Bound { + min: number; + /** Inclusive upper bound; absent means any safe integer. */ + max?: number; + env: string; +} + +const BOUNDS: Record = { + concurrency: { min: 1, env: 'GRAPHILE_BUILD_CONCURRENCY' }, + queueMax: { min: 0, env: 'GRAPHILE_BUILD_QUEUE_MAX' }, + // setTimeout fires at once for longer delays, so a larger wait never waits. + queueWaitMs: { min: 0, max: 2_147_483_647, env: 'GRAPHILE_BUILD_QUEUE_WAIT_MS' } +}; + +const KEYS = Object.keys(BOUNDS) as BuildLimitKey[]; + +const assertBuildLimit = (key: BuildLimitKey, value: unknown, label: string): number => { + const { min, max } = BOUNDS[key]; + if ( + !Number.isSafeInteger(value) || + (value as number) < min || + (max !== undefined && (value as number) > max) + ) { + throw new Error( + max === undefined + ? `${label} must be a safe integer of at least ${min}` + : `${label} must be an integer from ${min} to ${max}` + ); + } + return value as number; +}; + +/** Build limits set through `GRAPHILE_BUILD_*`; absent when none is set. */ +export const getBuildLimitsEnv = ( + env: NodeJS.ProcessEnv +): GraphileBuildLimits | undefined => { + const limits: GraphileBuildLimits = {}; + for (const key of KEYS) { + const { env: name } = BOUNDS[key]; + const raw = env[name]; + if (raw !== undefined) limits[key] = assertBuildLimit(key, parseEnvNumber(raw), name); + } + return Object.keys(limits).length > 0 ? limits : undefined; +}; + +/** Validate every configuration source before the bounds reach the server. */ +export const normalizeGraphileBuildLimits = ( + limits: GraphileBuildLimits | undefined +): Readonly | undefined => { + if (limits === undefined) return undefined; + if (typeof limits !== 'object' || limits === null || Array.isArray(limits)) { + throw new Error('graphile.buildLimits must be an object'); + } + for (const key of Object.keys(limits)) { + if (!(KEYS as string[]).includes(key)) { + throw new Error(`graphile.buildLimits contains unsupported setting '${key}'`); + } + } + const normalized: GraphileBuildLimits = {}; + for (const key of KEYS) { + const value = limits[key]; + if (value !== undefined) { + normalized[key] = assertBuildLimit(key, value, `graphile.buildLimits.${key}`); + } + } + return Object.freeze(normalized); +}; diff --git a/graphql/env/src/env.ts b/graphql/env/src/env.ts index 27b51523ed..0b6e97cde2 100644 --- a/graphql/env/src/env.ts +++ b/graphql/env/src/env.ts @@ -1,6 +1,7 @@ import { ConstructiveOptions } from '@constructive-io/graphql-types'; import { parseEnvBoolean, parseEnvNumber } from '12factor-env'; +import { getBuildLimitsEnv } from './build-limits'; import { normalizeGrafastCacheLimits, parseGrafastCacheLimitEnv @@ -12,6 +13,7 @@ import { getScopedIntrospectionEnv } from './scoped-introspection'; */ export const getGraphQLEnvVars = (env: NodeJS.ProcessEnv = process.env): Partial => { const scopedIntrospection = getScopedIntrospectionEnv(env); + const buildLimits = getBuildLimitsEnv(env); const { GRAPHILE_SCHEMA, GRAPHILE_EXPLAIN, @@ -90,6 +92,7 @@ export const getGraphQLEnvVars = (env: NodeJS.ProcessEnv = process.env): Partial ) }) }), + ...(buildLimits !== undefined && { buildLimits }), ...(GRAPHILE_EXPLAIN && { explain: parseEnvBoolean(GRAPHILE_EXPLAIN) }), ...(graphiql !== undefined && { graphiql }), ...(GRAPHILE_SCHEMA && { diff --git a/graphql/env/src/index.ts b/graphql/env/src/index.ts index 1cde42a418..2079b4e0fd 100644 --- a/graphql/env/src/index.ts +++ b/graphql/env/src/index.ts @@ -1,4 +1,5 @@ // Export Constructive-specific env functions +export { normalizeGraphileBuildLimits } from './build-limits'; export { getGraphQLEnvVars } from './env'; export { normalizeGrafastCacheLimits } from './grafast-cache-limits'; export { getConstructiveEnvOptions,getEnvOptions } from './merge'; diff --git a/graphql/env/src/merge.ts b/graphql/env/src/merge.ts index fcf155461e..45da75cd07 100644 --- a/graphql/env/src/merge.ts +++ b/graphql/env/src/merge.ts @@ -2,6 +2,7 @@ import { constructiveGraphqlDefaults,ConstructiveOptions } from '@constructive-i import { getEnvOptions as getPgpmEnvOptions, loadConfigSync, replaceArrays } from '@pgpmjs/env'; import deepmerge from 'deepmerge'; +import { normalizeGraphileBuildLimits } from './build-limits'; import { getGraphQLEnvVars } from './env'; import { normalizeGrafastCacheLimits } from './grafast-cache-limits'; @@ -59,6 +60,10 @@ export const getEnvOptions = ( if (grafastCache !== undefined && options.graphile) { options.graphile = { ...options.graphile, grafastCache }; } + const buildLimits = normalizeGraphileBuildLimits(options.graphile?.buildLimits); + if (buildLimits !== undefined && options.graphile) { + options.graphile = { ...options.graphile, buildLimits }; + } return options; }; diff --git a/graphql/server-test/__tests__/build-limits.integration.test.ts b/graphql/server-test/__tests__/build-limits.integration.test.ts new file mode 100644 index 0000000000..4dda141843 --- /dev/null +++ b/graphql/server-test/__tests__/build-limits.integration.test.ts @@ -0,0 +1,154 @@ +/** + * Bounded cold handler builds over real HTTP: a request whose build cannot get + * a slot reaches the client as a retryable 503 with `Retry-After`, not as a 200 + * carrying a masked error, and the same request is served once a slot is free. + * + * Run tests: + * pnpm test -- --testPathPattern=build-limits.integration + */ + +// A test-only gate in front of the real handler build: the first build holds +// the only slot at the gate until the test releases it, so the overlap the +// test asserts on does not depend on timing. +let mockGate: Promise | undefined; +let mockBuildStarted: (() => void) | undefined; + +jest.mock('graphile-cache', () => { + const actual = jest.requireActual('graphile-cache'); + return { + ...actual, + createGraphileInstance: async (...args: Parameters) => { + mockBuildStarted?.(); + if (mockGate) await mockGate; + return actual.createGraphileInstance(...args); + } + }; +}); + +import path from 'path'; +import type { PgTestClient } from 'pgsql-test'; +import type supertest from 'supertest'; + +import { getConnections, seed } from '../src'; + +jest.setTimeout(120000); + +const sharedSeedRoot = path.join(__dirname, '..', '..', '..', '__fixtures__', 'seed'); +const shared = (...segments: string[]) => path.join(sharedSeedRoot, ...segments); +const pgpmWorkspace = path.join(sharedSeedRoot, '..', '..'); +const databaseId = '80a2eaaf-f77e-4bfe-8506-df929ef1b8d9'; +const metaSchemas = [ + 'catalog_private', + 'routing_public', + 'apps_public', + 'metaschema_public', + 'metaschema_modules_public' +]; + +// Each schema set is a service of its own, so each one needs its own build. +const schemaSets = [ + ['simple-pets-public'], + ['simple-pets-pets-public'], + ['simple-pets-public', 'simple-pets-pets-public'] +]; + +describe('bounded cold handler builds', () => { + let releaseGate: (() => void) | undefined; + let request: supertest.Agent; + let pg: PgTestClient; + let db: PgTestClient; + let teardown: () => Promise; + + const post = (schemata: string[]) => + request + .post('/graphql') + .set('X-Database-Id', databaseId) + .set('X-Schemata', schemata.join(',')) + .send({ query: '{ __typename }' }); + + beforeAll(async () => { + ({ request, pg, db, teardown } = await getConnections( + { + schemas: schemaSets[2], + authRole: 'anonymous', + // One build at a time and no queue: a build that finds the slot taken + // is refused at once. + graphile: { buildLimits: { concurrency: 1, queueMax: 0, queueWaitMs: 2_000 } }, + server: { + useRouting: true, + api: { isPublic: false, metaSchemas } + } + }, + [ + seed.pgpm(pgpmWorkspace), + seed.sqlfile([ + shared('app-schemas', 'simple-pets', 'schema.sql'), + shared('scoped', 'test-data.sql'), + shared('app-schemas', 'simple-pets', 'test-data.sql') + ]) + ] + )); + }); + + beforeEach(async () => { + await pg.beforeEach(); + await db.beforeEach(); + }); + + afterEach(async () => { + // Never leave a build waiting at the gate, whatever the test did. + releaseGate?.(); + releaseGate = undefined; + mockGate = undefined; + mockBuildStarted = undefined; + await db.afterEach(); + await pg.afterEach(); + }); + + afterAll(async () => { + await teardown(); + }); + + it('refuses builds while the only slot is taken and serves them once it is free', async () => { + mockGate = new Promise((resolve) => { + releaseGate = resolve; + }); + const firstBuildStarted = new Promise((resolve) => { + mockBuildStarted = resolve; + }); + + // `then` sends the request; the first build takes the slot and waits at the gate. + const first = post(schemaSets[0]).then((res) => res); + try { + await firstBuildStarted; + mockBuildStarted = undefined; + + const refused = await Promise.all(schemaSets.slice(1).map((schemata) => post(schemata))); + for (const res of refused) { + expect(res.status).toBe(503); + expect(res.headers['retry-after']).toBe('2'); + expect(res.body.errors).toHaveLength(1); + expect(res.body.errors[0].extensions.code).toBe('SCHEMA_BUILD_UNAVAILABLE'); + expect(res.body.data).toBeUndefined(); + } + } finally { + // Open the gate however the checks went, so the first build never stays + // blocked, and let its request finish before the suite cleans up. + mockGate = undefined; + releaseGate?.(); + releaseGate = undefined; + await first.catch((): undefined => undefined); + } + + const served = await first; + expect(served.status).toBe(200); + expect(served.body).toEqual({ data: { __typename: 'Query' } }); + + // The slot is free again: the refused services are built and served on retry. + for (const schemata of schemaSets.slice(1)) { + const retry = await post(schemata); + expect(retry.status).toBe(200); + expect(retry.body).toEqual({ data: { __typename: 'Query' } }); + } + }); +}); diff --git a/graphql/server/src/diagnostics/debug-memory-snapshot.ts b/graphql/server/src/diagnostics/debug-memory-snapshot.ts index 0000c9840a..1c1490e325 100644 --- a/graphql/server/src/diagnostics/debug-memory-snapshot.ts +++ b/graphql/server/src/diagnostics/debug-memory-snapshot.ts @@ -4,7 +4,7 @@ import v8 from 'node:v8'; import { SVC_CACHE_TTL_MS,svcCache } from '@pgpmjs/server-utils'; import { getCacheStats } from 'graphile-cache'; -import { getInFlightCount, getInFlightKeys } from '../middleware/graphile'; +import { getBuildSlotStats, getInFlightCount, getInFlightKeys } from '../middleware/graphile'; import { getGraphileBuildStats } from '../middleware/observability/graphile-build-stats'; import { getRefusalRecorderStats } from '../refusals/recorder'; @@ -55,6 +55,8 @@ export interface DebugMemorySnapshot { count: number; keys: string[]; }; + /** Handler builds holding a build slot, and builds waiting for one. */ + buildSlots: ReturnType; graphileBuilds: ReturnType; /** In-memory refusal counter + flusher state; null when no recorder is installed. */ refusals: ReturnType; @@ -121,6 +123,7 @@ export const getDebugMemorySnapshot = (): DebugMemorySnapshot => { count: getInFlightCount(), keys: getInFlightKeys(), }, + buildSlots: getBuildSlotStats(), graphileBuilds: getGraphileBuildStats(), refusals: getRefusalRecorderStats(), uptimeMinutes: process.uptime() / 60, diff --git a/graphql/server/src/errors/__tests__/database-availability.test.ts b/graphql/server/src/errors/__tests__/database-availability.test.ts new file mode 100644 index 0000000000..1ce41c9384 --- /dev/null +++ b/graphql/server/src/errors/__tests__/database-availability.test.ts @@ -0,0 +1,65 @@ +import { isDatabaseUnavailableError } from '../database-availability'; + +const withCode = (code: string, message = `failed with ${code}`) => + Object.assign(new Error(message), { code }); + +describe('isDatabaseUnavailableError', () => { + it.each([ + '08000', // connection_exception + '08001', // sqlclient_unable_to_establish_sqlconnection + '08006', // connection_failure + '53300', // too_many_connections + '57P01', // admin_shutdown + '57P02', // crash_shutdown + '57P03' // cannot_connect_now + ])('treats SQLSTATE %s as unavailable', (code) => { + expect(isDatabaseUnavailableError(withCode(code))).toBe(true); + }); + + it.each(['EAI_AGAIN', 'ECONNREFUSED', 'ECONNRESET', 'ETIMEDOUT', 'EPIPE', 'EHOSTUNREACH', 'ENETUNREACH'])( + 'treats socket error %s as unavailable', + (code) => { + expect(isDatabaseUnavailableError(withCode(code))).toBe(true); + } + ); + + it.each([ + 'timeout exceeded when trying to connect', + 'Connection terminated unexpectedly', + 'Connection terminated due to connection timeout', + 'Client has encountered a connection error and is not queryable' + ])('treats the node-postgres message "%s" as unavailable', (message) => { + expect(isDatabaseUnavailableError(new Error(message))).toBe(true); + }); + + it('follows causes and aggregate members', () => { + const refused = withCode('ECONNREFUSED'); + expect(isDatabaseUnavailableError(new Error('introspection failed', { cause: refused }))).toBe(true); + expect( + isDatabaseUnavailableError(new AggregateError([new Error('first address'), refused], 'connect failed')) + ).toBe(true); + }); + + it.each([ + ['an undefined table', withCode('42P01')], + ['a permission error', withCode('42501')], + ['a cancelled statement', withCode('57014')], + ['a plain error', new Error('boom')], + ['an unknown host', withCode('ENOTFOUND')], + ['a near-miss code', withCode('0800')] + ])('does not treat %s as unavailable', (_label, error) => { + expect(isDatabaseUnavailableError(error)).toBe(false); + }); + + it('ignores values that are not errors', () => { + expect(isDatabaseUnavailableError(undefined)).toBe(false); + expect(isDatabaseUnavailableError('ECONNREFUSED')).toBe(false); + expect(isDatabaseUnavailableError({ code: 'ECONNREFUSED', message: 'refused' })).toBe(false); + }); + + it('stops following a cause chain that loops', () => { + const looping = new Error('wrapper') as Error & { cause?: unknown }; + looping.cause = looping; + expect(isDatabaseUnavailableError(looping)).toBe(false); + }); +}); diff --git a/graphql/server/src/errors/database-availability.ts b/graphql/server/src/errors/database-availability.ts new file mode 100644 index 0000000000..fb169404f1 --- /dev/null +++ b/graphql/server/src/errors/database-availability.ts @@ -0,0 +1,59 @@ +/** + * Whether an error means PostgreSQL could not be reached, or ended the + * connection, rather than rejecting the work itself. Such a failure clears + * without any change to the request (a restart, a failover, a saturated pool), + * so it is reported as retryable instead of as an internal error. + * + * @module errors/database-availability + */ + +/** SQLSTATEs outside class 08 (connection exception) that mean the same. */ +const UNAVAILABLE_SQLSTATES = new Set([ + '53300', // too_many_connections + '57P01', // admin_shutdown + '57P02', // crash_shutdown + '57P03' // cannot_connect_now +]); + +/** Socket-level failures reported by Node, and a temporary DNS failure. */ +const UNAVAILABLE_SOCKET_CODES = new Set([ + 'EAI_AGAIN', + 'ECONNREFUSED', + 'ECONNRESET', + 'ETIMEDOUT', + 'EPIPE', + 'EHOSTUNREACH', + 'ENETUNREACH' +]); + +/** node-postgres reports these without a SQLSTATE or socket code. */ +const UNAVAILABLE_MESSAGES = [ + // pg-pool: no connection became free within connectionTimeoutMillis + 'timeout exceeded when trying to connect', + // pg: the socket closed under an open connection + 'Connection terminated unexpectedly', + // pg: connecting took longer than connectionTimeoutMillis + 'Connection terminated due to connection timeout', + // pg: a query on a client whose connection already failed + 'Client has encountered a connection error and is not queryable' +]; + +/** How far to follow `cause` and `AggregateError` members. */ +const MAX_DEPTH = 5; + +export const isDatabaseUnavailableError = (error: unknown, depth = 0): boolean => { + if (depth > MAX_DEPTH || !(error instanceof Error)) return false; + const code = (error as { code?: unknown }).code; + if (typeof code === 'string') { + if (code.startsWith('08') && code.length === 5) return true; + if (UNAVAILABLE_SQLSTATES.has(code) || UNAVAILABLE_SOCKET_CODES.has(code)) return true; + } + if (UNAVAILABLE_MESSAGES.some((message) => error.message.includes(message))) return true; + if ( + error instanceof AggregateError && + error.errors.some((member) => isDatabaseUnavailableError(member, depth + 1)) + ) { + return true; + } + return isDatabaseUnavailableError(error.cause, depth + 1); +}; diff --git a/graphql/server/src/middleware/__tests__/graphile-build-limits.test.ts b/graphql/server/src/middleware/__tests__/graphile-build-limits.test.ts new file mode 100644 index 0000000000..5c6c5592d7 --- /dev/null +++ b/graphql/server/src/middleware/__tests__/graphile-build-limits.test.ts @@ -0,0 +1,379 @@ +const mockCacheGet = jest.fn(); +const mockCacheGraphileInstance = jest.fn(); +const mockCreateGraphileInstance = jest.fn(); +const mockMakeIntrospectionWiring = jest.fn(); + +jest.mock('graphile-cache', () => ({ + cacheGraphileInstance: mockCacheGraphileInstance, + createGraphileInstance: mockCreateGraphileInstance, + disposeUncachedEntry: jest.requireActual('graphile-cache').disposeUncachedEntry, + graphileCache: { + get: mockCacheGet, + delete: jest.fn(), + clear: jest.fn() + } +})); + +jest.mock('@pgpmjs/server-utils', () => ({ + svcCache: { delete: jest.fn(), clear: jest.fn() } +})); + +jest.mock('graphile-settings', () => ({ + createConstructivePreset: jest.fn(() => ({})), + createGrafastCacheLimitsPreset: jest.fn(() => ({})) +})); + +jest.mock('../graphile-introspection', () => ({ + makeIntrospectionWiring: mockMakeIntrospectionWiring +})); + +const mockGetApiConfig = jest.fn(); +jest.mock('../api', () => ({ + getApiConfig: mockGetApiConfig, + isApiError: (result: { errorHtml?: unknown } | null | undefined) => + !!result && typeof result.errorHtml === 'string' +})); + +import type { GraphileBuildLimits } from '@constructive-io/graphql-types'; +import { Logger } from '@pgpmjs/logger'; +import type { Request, Response } from 'express'; + +import { clearGenerations, evictServiceKey } from '../cache-generation'; +import { clearInFlightMap, getBuildSlotStats, getInFlightCount, graphile } from '../graphile'; + +const api = () => ({ + tenantPool: {}, + anonRole: 'anonymous', + roleName: 'authenticated', + schema: ['app_public'], + databaseId: 'database-id' +}); + +const makeRequest = (key: string): Request => + ({ + requestId: `request-${key}`, + svc_key: key, + api: api(), + get: jest.fn((): undefined => undefined) + }) as unknown as Request; + +interface Captured { + status?: number; + headers: Record; + body?: { errors: Array<{ message: string; extensions: Record }> }; +} + +/** A response that records what was sent. */ +class FakeResponse { + headersSent = false; + captured: Captured = { headers: {} }; + + status(code: number): this { + this.captured.status = code; + return this; + } + + set(headers: Record): this { + Object.assign(this.captured.headers, headers); + return this; + } + + json(body: Captured['body']): this { + this.captured.body = body; + return this; + } +} + +const makeResponse = (): { res: Response; captured: Captured } => { + const fake = new FakeResponse(); + return { res: fake as unknown as Response, captured: fake.captured }; +}; + +/** A handler build that finishes only when the test says so. */ +interface GatedBuild { + key: string; + handler: jest.Mock; + finish: () => void; + fail: (error: unknown) => void; +} + +/** Every handler build waits on its own gate, recorded in start order. */ +const gateBuilds = (): GatedBuild[] => { + const started: GatedBuild[] = []; + mockCreateGraphileInstance.mockImplementation(({ cacheKey }: { cacheKey: string }) => { + const handler = jest.fn(); + return new Promise((resolve, reject) => { + started.push({ + key: cacheKey, + handler, + finish: () => resolve({ handler }), + fail: reject + }); + }); + }); + return started; +}; + +/** Let every promise continuation that is ready run. */ +const settle = () => new Promise((resolve) => setImmediate(resolve)); + +const middlewareWith = (buildLimits?: GraphileBuildLimits) => + graphile({ graphile: buildLimits ? { buildLimits } : {} } as any); + +const expectRefused = (captured: Captured, retryAfter: string) => { + expect(captured.status).toBe(503); + expect(captured.headers['Retry-After']).toBe(retryAfter); + expect(captured.body?.errors).toHaveLength(1); + expect(captured.body?.errors[0].message).toBe( + "This API's schema cannot be prepared right now. Please retry in a moment." + ); + expect(captured.body?.errors[0].extensions).toEqual( + expect.objectContaining({ code: 'SCHEMA_BUILD_UNAVAILABLE' }) + ); +}; + +describe('graphile handler build limits', () => { + let logSpies: jest.SpyInstance[]; + + beforeEach(() => { + clearInFlightMap(); + clearGenerations(); + mockCacheGet.mockReset().mockReturnValue(undefined); + mockCacheGraphileInstance.mockReset().mockResolvedValue(undefined); + mockCreateGraphileInstance.mockReset(); + mockMakeIntrospectionWiring.mockReset().mockReturnValue({ presets: [], pgService: {} }); + mockGetApiConfig.mockReset(); + logSpies = (['info', 'warn', 'error'] as const).map((level) => + jest.spyOn(Logger.prototype, level).mockImplementation(() => undefined) + ); + }); + + afterEach(() => { + for (const spy of logSpies) spy.mockRestore(); + // A test that leaves a build holding a slot would starve the next one. + expect(getBuildSlotStats()).toEqual({ active: 0, queued: 0 }); + }); + + it('runs two builds at once by default and starts queued builds in arrival order', async () => { + const builds = gateBuilds(); + const middleware = middlewareWith(); + const next = jest.fn(); + const requests = ['a', 'b', 'c', 'd'].map((key) => + middleware(makeRequest(key), makeResponse().res, next) + ); + await settle(); + + expect(builds.map((build) => build.key)).toEqual(['a', 'b']); + expect(getBuildSlotStats()).toEqual({ active: 2, queued: 2 }); + expect(getInFlightCount()).toBe(4); + + builds[1].finish(); + await settle(); + expect(builds.map((build) => build.key)).toEqual(['a', 'b', 'c']); + expect(getBuildSlotStats()).toEqual({ active: 2, queued: 1 }); + + builds[0].finish(); + await settle(); + expect(builds.map((build) => build.key)).toEqual(['a', 'b', 'c', 'd']); + expect(getBuildSlotStats()).toEqual({ active: 2, queued: 0 }); + + builds[2].finish(); + builds[3].finish(); + await Promise.all(requests); + + for (const build of builds) expect(build.handler).toHaveBeenCalledTimes(1); + expect(next).not.toHaveBeenCalled(); + expect(getInFlightCount()).toBe(0); + }); + + it('fills each unset bound from the defaults', async () => { + const builds = gateBuilds(); + const middleware = middlewareWith({ concurrency: undefined, queueMax: 0 }); + const next = jest.fn(); + const running = ['a', 'b'].map((key) => middleware(makeRequest(key), makeResponse().res, next)); + const refused = makeResponse(); + await middleware(makeRequest('c'), refused.res, next); + await settle(); + + expect(builds.map((build) => build.key)).toEqual(['a', 'b']); + expectRefused(refused.captured, '30'); + + for (const build of builds) build.finish(); + await Promise.all(running); + expect(next).not.toHaveBeenCalled(); + }); + + it('shares one slot among requests coalesced on the same build', async () => { + const builds = gateBuilds(); + const middleware = middlewareWith({ concurrency: 1, queueMax: 0 }); + const next = jest.fn(); + const first = middleware(makeRequest('a'), makeResponse().res, next); + const second = middleware(makeRequest('a'), makeResponse().res, next); + await settle(); + + expect(builds).toHaveLength(1); + expect(getBuildSlotStats()).toEqual({ active: 1, queued: 0 }); + + builds[0].finish(); + await Promise.all([first, second]); + expect(builds[0].handler).toHaveBeenCalledTimes(2); + expect(next).not.toHaveBeenCalled(); + }); + + it('refuses a build with 503 and Retry-After when the queue is full', async () => { + const builds = gateBuilds(); + const middleware = middlewareWith({ concurrency: 1, queueMax: 1, queueWaitMs: 4_500 }); + const next = jest.fn(); + const running = middleware(makeRequest('a'), makeResponse().res, next); + const queued = middleware(makeRequest('b'), makeResponse().res, next); + const refused = makeResponse(); + await middleware(makeRequest('c'), refused.res, next); + await settle(); + + expectRefused(refused.captured, '5'); + expect(builds.map((build) => build.key)).toEqual(['a']); + expect(getBuildSlotStats()).toEqual({ active: 1, queued: 1 }); + // The refused build left no in-flight entry behind, so a retry builds again. + expect(getInFlightCount()).toBe(2); + + builds[0].finish(); + await settle(); + builds[1].finish(); + await Promise.all([running, queued]); + expect(next).not.toHaveBeenCalled(); + }); + + it('caps Retry-After at a minute however long the configured wait', async () => { + const builds = gateBuilds(); + const middleware = middlewareWith({ concurrency: 1, queueMax: 0, queueWaitMs: 2_147_483_647 }); + const next = jest.fn(); + const running = middleware(makeRequest('a'), makeResponse().res, next); + const refused = makeResponse(); + await middleware(makeRequest('b'), refused.res, next); + await settle(); + + expectRefused(refused.captured, '60'); + + builds[0].finish(); + await running; + expect(next).not.toHaveBeenCalled(); + }); + + it('refuses a build that waits longer than queueWaitMs', async () => { + const builds = gateBuilds(); + const middleware = middlewareWith({ concurrency: 1, queueMax: 4, queueWaitMs: 20 }); + const next = jest.fn(); + const running = middleware(makeRequest('a'), makeResponse().res, next); + const timedOut = makeResponse(); + await middleware(makeRequest('b'), timedOut.res, next); + await settle(); + + expectRefused(timedOut.captured, '1'); + expect(builds.map((build) => build.key)).toEqual(['a']); + + builds[0].finish(); + await running; + expect(next).not.toHaveBeenCalled(); + }); + + it('answers every coalesced request with 503 when the build cannot reach the database', async () => { + const builds = gateBuilds(); + const middleware = middlewareWith(); + const next = jest.fn(); + const responses = [makeResponse(), makeResponse()]; + const requests = responses.map(({ res }) => middleware(makeRequest('a'), res, next)); + await settle(); + + const refused = Object.assign(new Error('connect ECONNREFUSED 127.0.0.1:5432'), { + code: 'ECONNREFUSED' + }); + builds[0].fail(refused); + await Promise.all(requests); + + for (const { captured } of responses) expectRefused(captured, '30'); + // The waiter did not start a second build against the same database. + expect(builds).toHaveLength(1); + expect(next).not.toHaveBeenCalled(); + expect(getInFlightCount()).toBe(0); + }); + + it('starts one retry build for requests coalesced on a failed build, even while it waits for a slot', async () => { + const builds = gateBuilds(); + const middleware = middlewareWith({ concurrency: 1, queueMax: 4 }); + const next = jest.fn(); + const failed = makeResponse(); + const first = middleware(makeRequest('a'), failed.res, next); + const waiters = [1, 2, 3].map(() => middleware(makeRequest('a'), makeResponse().res, next)); + // Queued behind 'a', so the slot 'a' frees goes to 'b' and the retry has to wait. + const other = middleware(makeRequest('b'), makeResponse().res, next); + await settle(); + expect(builds.map((build) => build.key)).toEqual(['a']); + + builds[0].fail(new Error('permission denied for schema tenant_private')); + await first; + await settle(); + expect(failed.captured.body?.errors[0].extensions).toEqual( + expect.objectContaining({ code: 'INTERNAL_FAILURE' }) + ); + // One retry for the three coalesced requests, registered while it waits. + expect(builds.map((build) => build.key)).toEqual(['a', 'b']); + expect(getBuildSlotStats()).toEqual({ active: 1, queued: 1 }); + expect(getInFlightCount()).toBe(2); + + builds[1].finish(); + await settle(); + expect(builds.map((build) => build.key)).toEqual(['a', 'b', 'a']); + builds[2].finish(); + await Promise.all([...waiters, other]); + expect(builds[2].handler).toHaveBeenCalledTimes(3); + expect(next).not.toHaveBeenCalled(); + }); + + it('keeps masking other build failures and frees their slot', async () => { + const builds = gateBuilds(); + const middleware = middlewareWith({ concurrency: 1, queueMax: 0 }); + const next = jest.fn(); + const failed = makeResponse(); + const request = middleware(makeRequest('a'), failed.res, next); + await settle(); + builds[0].fail(new Error('permission denied for schema tenant_private')); + await request; + + expect(failed.captured.status).toBe(200); + expect(failed.captured.headers).toEqual({}); + expect(failed.captured.body?.errors[0].extensions).toEqual( + expect.objectContaining({ code: 'INTERNAL_FAILURE' }) + ); + + const later = middleware(makeRequest('b'), makeResponse().res, next); + await settle(); + expect(builds.map((build) => build.key)).toEqual(['a', 'b']); + builds[1].finish(); + await later; + expect(builds[1].handler).toHaveBeenCalledTimes(1); + }); + + it('skips a queued build whose service changed while it waited', async () => { + const builds = gateBuilds(); + mockGetApiConfig.mockImplementation(async () => api()); + const middleware = middlewareWith({ concurrency: 1, queueMax: 4 }); + const next = jest.fn(); + const running = middleware(makeRequest('a'), makeResponse().res, next); + const waiting = middleware(makeRequest('b'), makeResponse().res, next); + await settle(); + expect(getBuildSlotStats()).toEqual({ active: 1, queued: 1 }); + + evictServiceKey('b'); + builds[0].finish(); + await settle(); + + // The request resolved its service again and the next build is for that + // resolution: nothing was built for the service as it was before. + expect(mockGetApiConfig).toHaveBeenCalledTimes(1); + expect(builds.map((build) => build.key)).toEqual(['a', 'b']); + builds[1].finish(); + await Promise.all([running, waiting]); + expect(builds[1].handler).toHaveBeenCalledTimes(1); + expect(next).not.toHaveBeenCalled(); + }); +}); diff --git a/graphql/server/src/middleware/graphile.ts b/graphql/server/src/middleware/graphile.ts index 4a20640833..9b2e15ecd6 100644 --- a/graphql/server/src/middleware/graphile.ts +++ b/graphql/server/src/middleware/graphile.ts @@ -2,8 +2,13 @@ import './types'; // for Request type import { ConstructiveError, errors, format } from '@constructive-io/errors'; import type { ComputeConfig } from '@constructive-io/express-context'; -import { DEFAULT_REQUEST_PROTECTION, protectionPgSettings } from '@constructive-io/express-context'; -import type { ConstructiveOptions } from '@constructive-io/graphql-types'; +import { + ConcurrencyLimiter, + DEFAULT_REQUEST_PROTECTION, + protectionPgSettings +} from '@constructive-io/express-context'; +import type { ConstructiveOptions, GraphileBuildLimits } from '@constructive-io/graphql-types'; +import { graphileBuildLimitDefaults } from '@constructive-io/graphql-types'; import { Logger } from '@pgpmjs/logger'; import { parse as parseAcceptLanguage } from 'accept-language-parser'; import type { NextFunction, Request, RequestHandler, Response } from 'express'; @@ -27,6 +32,7 @@ import type { IncomingMessage } from 'http'; import { isGraphqlObservabilityEnabled } from '../diagnostics/observability'; import errorPage404Message from '../errors/404-message'; import { HandlerCreationError } from '../errors/api-errors'; +import { isDatabaseUnavailableError } from '../errors/database-availability'; import { respondWithGraphQLError } from '../errors/graphql-response'; import { AuthCookiePlugin } from '../plugins/auth-cookie-plugin'; import { CaptchaPlugin } from '../plugins/captcha-plugin'; @@ -77,6 +83,41 @@ export function clearInFlightMap(): void { creating.clear(); } +// ============================================================================= +// Build Slots: bounded concurrent handler builds +// ============================================================================= + +/** + * Bounds distinct handler builds across the process. Coalesced requests share + * one build and one slot. Every build introspects through the served pool, so + * one process-wide key bounds what that pool has to absorb. + */ +const buildSlots = new ConcurrencyLimiter(); +const BUILD_SLOTS = 'graphile-build'; + +/** + * Returns how many handler builds hold a slot and how many wait for one. + * Useful for monitoring and debugging. + */ +export function getBuildSlotStats(): { active: number; queued: number } { + return { active: buildSlots.activeFor(BUILD_SLOTS), queued: buildSlots.queuedFor(BUILD_SLOTS) }; +} + +/** A retryable refusal: the build could not start, or the database was unreachable. */ +const isBuildUnavailable = (error: unknown): error is ConstructiveError => + error instanceof ConstructiveError && error.code === 'SCHEMA_BUILD_UNAVAILABLE'; + +/** + * Seconds for a `Retry-After` header: the configured wait, from one second to + * a minute. By the end of the wait every queued build has started or been + * refused, so the queue has turned over. The ceiling keeps a long configured + * wait from asking clients to stay away for hours; admission control's queue + * wait, and so its `Retry-After`, has the same ceiling. + */ +const MAX_RETRY_AFTER_SECONDS = 60; +const retryAfterSeconds = (ms: number): string => + String(Math.min(Math.max(Math.ceil(ms / 1000), 1), MAX_RETRY_AFTER_SECONDS)); + const log = new Logger('graphile'); const reqLabel = (req: Request): string => (req.requestId ? `[${req.requestId}]` : '[req]'); @@ -415,6 +456,12 @@ const MAX_SERVICE_RESOLUTIONS = 3; export const graphile = (opts: ConstructiveOptions): RequestHandler => { const observabilityEnabled = isGraphqlObservabilityEnabled(opts.server?.host); + const configuredLimits = opts.graphile?.buildLimits; + const buildLimits: Required = { + concurrency: configuredLimits?.concurrency ?? graphileBuildLimitDefaults.concurrency, + queueMax: configuredLimits?.queueMax ?? graphileBuildLimitDefaults.queueMax, + queueWaitMs: configuredLimits?.queueWaitMs ?? graphileBuildLimitDefaults.queueWaitMs + }; /** A cached, coalesced or newly built handler for one resolution of the service. */ const handlerFor = async ( @@ -454,6 +501,9 @@ export const graphile = (opts: ConstructiveOptions): RequestHandler => { } catch (error) { // The service this waiter resolved is gone too: resolve it again. if (error instanceof ServiceInvalidatedError) throw error; + // Retrying a build that could not start, or could not reach the + // database, only adds load to what refused it: answer every waiter. + if (isBuildUnavailable(error)) throw error; log.warn(`${label} Coalesced request failed for PostGraphile[${key}], retrying`, error); // Fall through to Phase C to retry creation } @@ -483,10 +533,8 @@ export const graphile = (opts: ConstructiveOptions): RequestHandler => { const pool = api.tenantPool; - // Register the creation promise before any asynchronous preset work so - // concurrent requests coalesce while optional plugin modules load. const startedUnder = generationOf(key); - const creationPromise = (async () => { + const buildHandler = async (): Promise => { const compute = api.apiId ? await req.constructive?.useModule('compute') : undefined; const platform = api.databaseId ? await req.constructive?.useModule('platform') : undefined; const preset = buildPreset( @@ -532,6 +580,40 @@ export const graphile = (opts: ConstructiveOptions): RequestHandler => { // has been released, so coalesced waiters must not be handed it. await cacheGraphileInstance(key, instance); return instance; + }; + + // Register the creation promise before any asynchronous preset work so + // concurrent requests coalesce while optional plugin modules load. + const creationPromise = (async () => { + const slot = await buildSlots.acquire(BUILD_SLOTS, { + limit: buildLimits.concurrency, + queueLimit: buildLimits.queueMax, + queueWaitMs: buildLimits.queueWaitMs + }); + if (!slot.granted) { + log.warn( + `${label} PostGraphile[${key}] build refused: ${slot.refusal} after ${slot.queuedMs}ms ` + + `(concurrency=${buildLimits.concurrency} queueMax=${buildLimits.queueMax})` + ); + throw errors.SCHEMA_BUILD_UNAVAILABLE(); + } + try { + // The service changed while this build waited for a slot: the handler + // would be discarded at admission, so the requests resolve it again now. + if (generationOf(key) !== startedUnder) throw new ServiceInvalidatedError(key); + return await buildHandler(); + } catch (error) { + // The database was unreachable or dropped the connection: nothing about + // the request has to change for a later attempt to succeed, so every + // request waiting on this build is told to retry instead of rebuilding. + if (isDatabaseUnavailableError(error)) { + log.error(`${label} PostGraphile[${key}] build could not reach the database:`, error); + throw errors.SCHEMA_BUILD_UNAVAILABLE(); + } + throw error; + } finally { + slot.release(); + } })(); creating.set(key, creationPromise); @@ -540,7 +622,7 @@ export const graphile = (opts: ConstructiveOptions): RequestHandler => { log.info(`${label} Cached PostGraphile v5 handler key=${key} databaseId=${databaseLabel}`); return instance; } catch (error) { - if (error instanceof ServiceInvalidatedError) throw error; + if (error instanceof ServiceInvalidatedError || isBuildUnavailable(error)) throw error; log.error(`${label} Failed to create PostGraphile[${key}]:`, error); const cause = error instanceof Error ? error.message : String(error); throw handlerFailure(cause, { cacheKey: key, cause }); @@ -604,6 +686,15 @@ export const graphile = (opts: ConstructiveOptions): RequestHandler => { return instance.handler(req, res, next); } } catch (error) { + // As with admission control, a 200 would hide a refusal that clients, + // proxies and load balancers have to act on: answer 503 with a retry hint. + if (isBuildUnavailable(error) && !res.headersSent) { + respondWithGraphQLError(res, error, { + status: 503, + headers: { 'Retry-After': retryAfterSeconds(buildLimits.queueWaitMs) } + }); + return; + } const errorId = logInternalError(error, `${label} PostGraphile middleware error`); if (!res.headersSent) { respondWithGraphQLError( diff --git a/graphql/types/src/graphile.ts b/graphql/types/src/graphile.ts index 90bbf84e3d..114aa8c2e6 100644 --- a/graphql/types/src/graphile.ts +++ b/graphql/types/src/graphile.ts @@ -53,6 +53,37 @@ export interface GrafastCacheLimits { operationOperationPlansCacheMaxLength?: number; } +/** + * Process-wide bounds on cold PostGraphile handler builds. + * + * A build introspects the database and constructs a schema. When many APIs go + * cold at once (a restart, a flush, more active APIs than the handler cache + * holds), unbounded builds run in parallel and compete with requests for the + * same small connection pool until connection attempts time out. Builds beyond + * `concurrency` wait in arrival order; a build that finds the queue full, or + * waits longer than `queueWaitMs`, is refused with a retryable 503. + */ +export interface GraphileBuildLimits { + /** Handler builds that may run at once in this process. */ + concurrency?: number; + /** Builds that may wait for a slot. `0` refuses at once while every slot is busy. */ + queueMax?: number; + /** How long a build may wait for a slot, in milliseconds. `0` never waits. */ + queueWaitMs?: number; +} + +/** + * Default build bounds. Two concurrent builds leave most of the default + * five-connection pool to requests, the queue absorbs a cold start of a few + * dozen APIs, and a build that cannot start within 30 seconds is refused with + * a retryable 503 instead of waiting out the client's timeout. + */ +export const graphileBuildLimitDefaults: Readonly> = Object.freeze({ + concurrency: 2, + queueMax: 64, + queueWaitMs: 30_000 +}); + /** * PostGraphile/Graphile v5 configuration */ @@ -65,6 +96,11 @@ export interface GraphileOptions { preset?: Partial; /** Explicit per-schema Grafast cache bounds used for tenant-density control. */ grafastCache?: GrafastCacheLimits; + /** + * Bounds on concurrent cold handler builds; see {@link GraphileBuildLimits}. + * Unset keys use {@link graphileBuildLimitDefaults}. + */ + buildLimits?: GraphileBuildLimits; /** * Allow clients to request Grafast plan/SQL output with the * `x-graphql-explain` header. Off unless set. diff --git a/graphql/types/src/index.ts b/graphql/types/src/index.ts index db2333a7b7..01e97a7434 100644 --- a/graphql/types/src/index.ts +++ b/graphql/types/src/index.ts @@ -3,6 +3,8 @@ export { apiDefaults, ApiOptions, GrafastCacheLimits, + graphileBuildLimitDefaults, + GraphileBuildLimits, graphileDefaults, graphileFeatureDefaults, GraphileFeatureOptions, diff --git a/packages/errors/src/registry.ts b/packages/errors/src/registry.ts index 189368cdb8..40f9a0bfbb 100644 --- a/packages/errors/src/registry.ts +++ b/packages/errors/src/registry.ts @@ -646,6 +646,12 @@ export const registry = { message: 'Too many requests are in flight for this API. Please retry in a moment.', positional: ['limit', 'waitedMs'] }), + SCHEMA_BUILD_UNAVAILABLE: defineError({ + code: 'SCHEMA_BUILD_UNAVAILABLE', + class: 'public', + http: 503, + message: "This API's schema cannot be prepared right now. Please retry in a moment." + }), INTROSPECTION_DISABLED: defineError({ code: 'INTROSPECTION_DISABLED', class: 'public',