Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions graphql/env/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
119 changes: 119 additions & 0 deletions graphql/env/__tests__/build-limits.test.ts
Original file line number Diff line number Diff line change
@@ -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');
});
});
72 changes: 72 additions & 0 deletions graphql/env/src/build-limits.ts
Original file line number Diff line number Diff line change
@@ -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<BuildLimitKey, Bound> = {
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<GraphileBuildLimits> | 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);
};
3 changes: 3 additions & 0 deletions graphql/env/src/env.ts
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -12,6 +13,7 @@ import { getScopedIntrospectionEnv } from './scoped-introspection';
*/
export const getGraphQLEnvVars = (env: NodeJS.ProcessEnv = process.env): Partial<ConstructiveOptions> => {
const scopedIntrospection = getScopedIntrospectionEnv(env);
const buildLimits = getBuildLimitsEnv(env);
const {
GRAPHILE_SCHEMA,
GRAPHILE_EXPLAIN,
Expand Down Expand Up @@ -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 && {
Expand Down
1 change: 1 addition & 0 deletions graphql/env/src/index.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand Down
5 changes: 5 additions & 0 deletions graphql/env/src/merge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand Down Expand Up @@ -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;
};

Expand Down
Loading
Loading