Skip to content
Merged
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
50 changes: 50 additions & 0 deletions graphql/server/src/middleware/__tests__/format-error.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,56 @@ describe('formatError', () => {
expect(result.extensions?.errorId).toBeUndefined();
});

/** What node-postgres hands over for `errors.raise_error(code, context, class)`. */
const raisedByDatabase = (code: string, context: Record<string, unknown>, errorClass?: string) => {
const pgError = Object.assign(new Error(code), {
code: 'P0001',
detail: JSON.stringify({ code, context, ...(errorClass ? { class: errorClass } : {}) }),
});
return new GraphQLError(pgError.message, { path: ['confirmUpload'], originalError: pgError });
};

it('passes a public database code the registry does not know through unchanged', () => {
const result = formatError(raisedByDatabase('CODE_NO_REGISTRY_KNOWS', { id: 'abc' }, 'public')) as {
message: string;
extensions?: Record<string, unknown>;
};

expect(result.message).toBe('CODE_NO_REGISTRY_KNOWS');
expect(result.extensions).toEqual({
code: 'CODE_NO_REGISTRY_KNOWS',
class: 'public',
context: { id: 'abc' },
});
});

it('passes an internal database code the registry does not know through with an errorId', () => {
const result = formatError(raisedByDatabase('CODE_NO_REGISTRY_KNOWS', { id: 'abc' }, 'internal')) as {
message: string;
extensions?: Record<string, unknown>;
};

expect(result.message).toBe('CODE_NO_REGISTRY_KNOWS');
expect(result.extensions).toMatchObject({
code: 'CODE_NO_REGISTRY_KNOWS',
class: 'internal',
context: { id: 'abc' },
});
expect(result.extensions?.errorId).toMatch(/^[0-9a-f]{16}$/);
});

it('treats an unknown database code that names no class as internal', () => {
const result = formatError(raisedByDatabase('CODE_NO_REGISTRY_KNOWS', {})) as {
message: string;
extensions?: Record<string, unknown>;
};

expect(result.message).toBe('CODE_NO_REGISTRY_KNOWS');
expect(result.extensions?.code).toBe('CODE_NO_REGISTRY_KNOWS');
expect(result.extensions?.class).toBe('internal');
expect(result.extensions?.errorId).toMatch(/^[0-9a-f]{16}$/);
});

it.each(['production', 'development', 'test', undefined])(
'formats errors identically when NODE_ENV is %s',
async (env) => {
Expand Down
16 changes: 14 additions & 2 deletions packages/errors/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@ service or client without pulling in pgpm.
- **`errors.*` factory** — type-safe throwable builders derived from the
registry, e.g. `throw errors.MODULE_NOT_FOUND({ name })`.
- **`classify(code)`** — `public` or `internal`; unknown codes are `internal`
(fail safe) so transports never leak unregistered errors.
(fail safe). This is the fallback only: `parse()` trusts the class the
producer sent (`DETAIL.class`, `extensions.class`) before the registry.
- **`httpStatusFor(code)`** — the canonical code → HTTP status mapping, so no
transport keeps its own table. Unregistered codes answer `500` *and are
reported*, never silently.
Expand Down Expand Up @@ -47,7 +48,10 @@ throw errors.ACCOUNT_EXISTS();
- **Curated** (`src/registry.ts`) — refined, typed-context entries for the codes
that matter most (public auth/limit copy, native PostgreSQL constraint codes,
pgpm CLI codes). These override the generated entries.
- Unregistered codes still `parse()` and are classified `internal` (masked).
- Unregistered codes still `parse()`. One the database raised with an explicit
class keeps that class, so the GraphQL server passes it through with its
code, class and context; without a class it is `internal`. Either way it has
no registry copy and no HTTP status (`500`, reported).

## HTTP status

Expand Down Expand Up @@ -93,6 +97,14 @@ class from each canonical `errors.raise_error('CODE', context, 'class')` call
database is the source of truth for classification, so an explicit class is trusted
directly; codes without one (e.g. single-arg calls relying on the helper default, or
legacy `RAISE EXCEPTION`) fall back to a name-based heuristic.

A generator often hands the code to a raise helper instead of spelling it at the
raise (`wrong_status_code := 'FILE_STATUS_INVALID'` at the caller,
`raise_error(wrong_status_code, …, 'internal')` in the helper). The audit resolves
those too: it finds the parameters that reach a raise, then collects the codes
passed to them by name, as a parameter default, as a jsonb `'error_code'`, or as
the prefix of `raise_error(prefix || '_SUFFIX', …)`. A code built any other way at
runtime is still invisible to it.
`generate-registry.py` reads that snapshot and, when a
`constructive-io/dashboard` checkout is found (via `DASHBOARD_DIR` or a sibling
`../dashboard`), seeds public copy from its error catalogs. Re-run both whenever
Expand Down
99 changes: 99 additions & 0 deletions packages/errors/__tests__/storage-refusals.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
import { readFileSync } from 'fs';
import { join } from 'path';

import {
errors,
format,
httpStatusFor,
resetUnmappedStatusReports,
setUnmappedStatusReporter,
toError
} from '../src';

const inventory: Record<string, unknown> = JSON.parse(
readFileSync(join(__dirname, '../scripts/db-error-inventory.json'), 'utf-8')
);

/** The shape errors.raise_error gives node-postgres: P0001 with the payload in DETAIL. */
const raised = (code: string, context: Record<string, unknown>, errorClass: 'public' | 'internal') =>
Object.assign(new Error(code), {
code: 'P0001',
detail: JSON.stringify({ code, context, class: errorClass })
});

const reported: string[] = [];

beforeEach(() => {
reported.length = 0;
resetUnmappedStatusReports();
setUnmappedStatusReporter(code => reported.push(code));
});

afterAll(() => {
setUnmappedStatusReporter(null);
});

const fileId = '6f1c2f0e-0000-4000-8000-000000000001';

describe('file and secret refusals raised by the database', () => {
it('answers a write about a file row that is gone as a 404', () => {
const err = toError(raised('FILE_NOT_FOUND', { file_id: fileId }, 'internal'));

expect(inventory.FILE_NOT_FOUND).toBeDefined();
expect(err).toMatchObject({
code: 'FILE_NOT_FOUND',
errorClass: 'internal',
http: 404,
context: { file_id: fileId }
});
expect(err.message).toBe('File not found.');
expect(reported).toEqual([]);
});

it('keeps a write about a file in the wrong status internal, as the database raises it', () => {
const err = toError(raised('FILE_STATUS_INVALID', { file_id: fileId }, 'internal'));

expect(inventory.FILE_STATUS_INVALID).toBeDefined();
expect(err).toMatchObject({
code: 'FILE_STATUS_INVALID',
errorClass: 'internal',
http: 500,
context: { file_id: fileId }
});
expect(err.message).toBe('File status invalid.');
expect(reported).toEqual([]);
});

it('answers deleting a secret that does not exist as a public 404', () => {
const err = toError(raised('SECRET_NOT_FOUND', {}, 'public'));

expect(inventory.SECRET_NOT_FOUND).toBeDefined();
expect(err).toMatchObject({ code: 'SECRET_NOT_FOUND', errorClass: 'public', http: 404 });
expect(err.message).toBe('Secret not found.');
expect(reported).toEqual([]);
});
});

describe('FILE_NOT_FOUND on the local filesystem', () => {
it('still names the path and the kind of file', () => {
const err = errors.FILE_NOT_FOUND({ filePath: 'pgpm.json', type: 'configuration' });

expect(err).toMatchObject({ code: 'FILE_NOT_FOUND', errorClass: 'internal', http: 404 });
expect(err.message).toBe('configuration file not found: pgpm.json');
expect(format('FILE_NOT_FOUND', { filePath: 'a.sql' })).toBe('File not found: a.sql');
});
});

describe('codes a generator hands to a raise helper instead of spelling at the raise', () => {
it.each([
['RESOURCE_CPU_CAP_EXCEEDED', 400],
['RESOURCE_MEMORY_CAP_EXCEEDED', 400],
['RESOURCE_STORAGE_TOTAL_CAP_EXCEEDED', 400],
['EXECUTION_DEADLINE_EXCEEDS_RETENTION', 400],
['PROCESS_EXTRACTION_INSERT_ON_FILES_TABLE', 400]
])('registers %s as a public %i', (code, status) => {
expect(inventory[code]).toBeDefined();
expect(httpStatusFor(code)).toEqual({ status, mapped: true });
expect(toError(raised(code, {}, 'public'))).toMatchObject({ code, errorClass: 'public', http: status });
});
});
Loading
Loading