diff --git a/agentic/run-log-client/__tests__/realtime.test.ts b/agentic/run-log-client/__tests__/realtime.test.ts index 2559f464aa..5d8efc8c44 100644 --- a/agentic/run-log-client/__tests__/realtime.test.ts +++ b/agentic/run-log-client/__tests__/realtime.test.ts @@ -59,6 +59,10 @@ describe('the realtime wakeup', () => { expect(changedSubscriptionDocument(names)).not.toMatch(/entry|seq/); }); + it('only selects fields supplied by the realtime payload', () => { + expect(changedSubscriptionDocument(names)).not.toContain('timestamp'); + }); + it('resolves the next wait when a change arrives', async () => { const ws = fakeWs(); const wakeup = createRealtimeWakeup({ client: ws, names }); diff --git a/agentic/run-log-client/src/realtime.ts b/agentic/run-log-client/src/realtime.ts index eafcf14b10..7015e1f365 100644 --- a/agentic/run-log-client/src/realtime.ts +++ b/agentic/run-log-client/src/realtime.ts @@ -53,7 +53,6 @@ subscription RunEventChanged { ${field} { event ${names.event} { __typename } - timestamp } }`; diff --git a/graphile/graphile-bulk-mutations/src/plugins/BulkDeletePlugin.ts b/graphile/graphile-bulk-mutations/src/plugins/BulkDeletePlugin.ts index 4731702283..fe653d53d8 100644 --- a/graphile/graphile-bulk-mutations/src/plugins/BulkDeletePlugin.ts +++ b/graphile/graphile-bulk-mutations/src/plugins/BulkDeletePlugin.ts @@ -194,7 +194,7 @@ export const BulkDeletePlugin: GraphileConfig.Plugin = { // Use RETURNING instead of RETURNING * // For delete, we capture PKs before rows are gone const text = `DELETE FROM ${compiledFrom}\nWHERE ${whereStr}\nRETURNING ${pkReturning}`; - const mutationResult = await pgClient.query(text, values); + const mutationResult = await pgClient.query({ text, values }); const affectedCount = mutationResult.rowCount ?? 0; // For delete, rows no longer exist so we can't do a diff --git a/graphile/graphile-bulk-mutations/src/plugins/BulkInsertPlugin.ts b/graphile/graphile-bulk-mutations/src/plugins/BulkInsertPlugin.ts index 6b128024a1..57b2569326 100644 --- a/graphile/graphile-bulk-mutations/src/plugins/BulkInsertPlugin.ts +++ b/graphile/graphile-bulk-mutations/src/plugins/BulkInsertPlugin.ts @@ -6,6 +6,7 @@ import type { GraphQLInputType, GraphQLOutputType } from 'graphql'; import type { NestedRelationInfo } from '../utils/relations'; import { discoverNestedRelations } from '../utils/relations'; +import { selectReturningRecords } from '../utils/returning'; import type { ColumnSpec } from '../utils/sql-builder'; import { buildBulkInsertSQL } from '../utils/sql-builder'; @@ -200,10 +201,10 @@ export const BulkInsertPlugin: GraphileConfig.Plugin = { const allPkRows: Record[] = []; for (const batch of batches) { - const result = await pgClient.query( - batch.text, - batch.values - ); + const result = await pgClient.query({ + text: batch.text, + values: batch.values + }); totalAffected += result.rowCount ?? 0; if (result.rows) { allPkRows.push(...result.rows); @@ -259,10 +260,10 @@ export const BulkInsertPlugin: GraphileConfig.Plugin = { ); for (const batch of childBatches) { - const result = await pgClient.query( - batch.text, - batch.values - ); + const result = await pgClient.query({ + text: batch.text, + values: batch.values + }); totalAffected += result.rowCount ?? 0; } } @@ -270,24 +271,9 @@ export const BulkInsertPlugin: GraphileConfig.Plugin = { } // Follow-up SELECT using PKs to respect column-level grants - let returning: unknown[] = []; - if (allPkRows.length > 0) { - const pkConditions = allPkRows.map((pkRow, rowIdx) => { - return pkColumns.map((col, colIdx) => { - const paramIdx = rowIdx * pkColumns.length + colIdx + 1; - return `"${col}" = $${paramIdx}`; - }).join(' AND '); - }); - const whereClause = pkConditions.map((c) => `(${c})`).join(' OR '); - const selectParams = allPkRows.flatMap((pkRow) => - pkColumns.map((col) => pkRow[col]) - ); - const selectResult = await pgClient.query( - `SELECT * FROM ${compiledFrom} WHERE ${whereClause}`, - selectParams - ); - returning = selectResult.rows || []; - } + const returning = await selectReturningRecords( + pgClient, resource.from, resource.codec, pkColumns, allPkRows + ); return { affectedCount: totalAffected, diff --git a/graphile/graphile-bulk-mutations/src/plugins/BulkTypesPlugin.ts b/graphile/graphile-bulk-mutations/src/plugins/BulkTypesPlugin.ts index 18717fe73e..bd45149f0e 100644 --- a/graphile/graphile-bulk-mutations/src/plugins/BulkTypesPlugin.ts +++ b/graphile/graphile-bulk-mutations/src/plugins/BulkTypesPlugin.ts @@ -1,10 +1,11 @@ import '../augmentations'; -import { pgSelectFromRecords } from '@dataplan/pg'; import { access } from 'grafast'; import type { GraphileConfig } from 'graphile-config'; import type { GraphQLInputType, GraphQLOutputType } from 'graphql'; +import { pgSelectReturningRecords } from '../utils/returning'; + const version = '0.1.0'; /** @@ -469,12 +470,9 @@ export const BulkTypesPlugin: GraphileConfig.Plugin = { const filterTypeName = `${typeName}Filter`; const filterType = build.getTypeByName(filterTypeName) as GraphQLInputType | undefined; // Fall back to PostGraphile's built-in condition type - const conditionTypeName = inflection.conditionType( - typeName + const whereType = filterType || ( + build.getTypeByName(inflection.conditionType(typeName)) as GraphQLInputType | undefined ); - const conditionType = - build.getTypeByName(conditionTypeName) as GraphQLInputType | undefined; - const whereType = filterType || conditionType; return { description: 'Condition to select which rows to update.', @@ -513,12 +511,9 @@ export const BulkTypesPlugin: GraphileConfig.Plugin = { () => { const filterTypeName = `${typeName}Filter`; const filterType = build.getTypeByName(filterTypeName) as GraphQLInputType | undefined; - const conditionTypeName = inflection.conditionType( - typeName + const whereType = filterType || ( + build.getTypeByName(inflection.conditionType(typeName)) as GraphQLInputType | undefined ); - const conditionType = - build.getTypeByName(conditionTypeName) as GraphQLInputType | undefined; - const whereType = filterType || conditionType; return { description: 'Condition to select which rows to delete.', @@ -589,7 +584,7 @@ export const BulkTypesPlugin: GraphileConfig.Plugin = { $parent, 'returning' ) as any; - return pgSelectFromRecords( + return pgSelectReturningRecords( payloadResource, $records ); diff --git a/graphile/graphile-bulk-mutations/src/plugins/BulkUpdatePlugin.ts b/graphile/graphile-bulk-mutations/src/plugins/BulkUpdatePlugin.ts index 8ef1170067..be94368e36 100644 --- a/graphile/graphile-bulk-mutations/src/plugins/BulkUpdatePlugin.ts +++ b/graphile/graphile-bulk-mutations/src/plugins/BulkUpdatePlugin.ts @@ -4,6 +4,8 @@ import { sideEffectWithPgClient } from '@dataplan/pg'; import type { GraphileConfig } from 'graphile-config'; import type { GraphQLInputType, GraphQLOutputType } from 'graphql'; +import { selectReturningRecords } from '../utils/returning'; + const version = '0.1.0'; /** @@ -212,29 +214,13 @@ export const BulkUpdatePlugin: GraphileConfig.Plugin = { // Use RETURNING instead of RETURNING * const text = `UPDATE ${compiledFrom}\nSET ${setClauses.join(', ')}\nWHERE ${whereStr}\nRETURNING ${pkReturning}`; - const mutationResult = await pgClient.query(text, values); + const mutationResult = await pgClient.query({ text, values }); const affectedCount = mutationResult.rowCount ?? 0; // Follow-up SELECT using PKs to respect column-level grants - let returning: unknown[] = []; - if (mutationResult.rows && mutationResult.rows.length > 0) { - const pkRows: Record[] = mutationResult.rows; - const pkConditions = pkRows.map((pkRow, rowIdx) => { - return pkColumns.map((col, colIdx) => { - const paramIdx = rowIdx * pkColumns.length + colIdx + 1; - return `"${col}" = $${paramIdx}`; - }).join(' AND '); - }); - const selectWhere = pkConditions.map((c) => `(${c})`).join(' OR '); - const selectParams = pkRows.flatMap((pkRow) => - pkColumns.map((col) => pkRow[col]) - ); - const selectResult = await pgClient.query( - `SELECT * FROM ${compiledFrom} WHERE ${selectWhere}`, - selectParams - ); - returning = selectResult.rows || []; - } + const returning = await selectReturningRecords( + pgClient, resource.from, resource.codec, pkColumns, mutationResult.rows || [] + ); return { affectedCount, diff --git a/graphile/graphile-bulk-mutations/src/plugins/BulkUpsertPlugin.ts b/graphile/graphile-bulk-mutations/src/plugins/BulkUpsertPlugin.ts index 4b261c7562..63b1231a1e 100644 --- a/graphile/graphile-bulk-mutations/src/plugins/BulkUpsertPlugin.ts +++ b/graphile/graphile-bulk-mutations/src/plugins/BulkUpsertPlugin.ts @@ -4,6 +4,8 @@ import { sideEffectWithPgClient } from '@dataplan/pg'; import type { GraphileConfig } from 'graphile-config'; import type { GraphQLInputType, GraphQLOutputType } from 'graphql'; +import { selectReturningRecords } from '../utils/returning'; + import type { ColumnSpec } from '../utils/sql-builder'; import { buildBulkInsertSQL } from '../utils/sql-builder'; @@ -177,10 +179,10 @@ export const BulkUpsertPlugin: GraphileConfig.Plugin = { const allPkRows: Record[] = []; for (const batch of batches) { - const result = await pgClient.query( - batch.text, - batch.values - ); + const result = await pgClient.query({ + text: batch.text, + values: batch.values + }); totalAffected += result.rowCount ?? 0; if (result.rows) { allPkRows.push(...result.rows); @@ -188,24 +190,9 @@ export const BulkUpsertPlugin: GraphileConfig.Plugin = { } // Follow-up SELECT using PKs to respect column-level grants - let returning: unknown[] = []; - if (allPkRows.length > 0) { - const pkConditions = allPkRows.map((pkRow, rowIdx) => { - return pkColumns.map((col, colIdx) => { - const paramIdx = rowIdx * pkColumns.length + colIdx + 1; - return `"${col}" = $${paramIdx}`; - }).join(' AND '); - }); - const whereClause = pkConditions.map((c) => `(${c})`).join(' OR '); - const selectParams = allPkRows.flatMap((pkRow) => - pkColumns.map((col) => pkRow[col]) - ); - const selectResult = await pgClient.query( - `SELECT * FROM ${compiledFrom} WHERE ${whereClause}`, - selectParams - ); - returning = selectResult.rows || []; - } + const returning = await selectReturningRecords( + pgClient, resource.from, resource.codec, pkColumns, allPkRows + ); return { affectedCount: totalAffected, diff --git a/graphile/graphile-bulk-mutations/src/utils/returning.ts b/graphile/graphile-bulk-mutations/src/utils/returning.ts new file mode 100644 index 0000000000..67b5696396 --- /dev/null +++ b/graphile/graphile-bulk-mutations/src/utils/returning.ts @@ -0,0 +1,83 @@ +import type { PgClient, PgCodec, PgResource } from '@dataplan/pg'; +import { pgSelect, TYPES } from '@dataplan/pg'; +import type { Step } from 'grafast'; +import { lambda } from 'grafast'; +import sql from 'pg-sql2'; +import type { SQL, SQLRawValue } from 'pg-sql2'; + +function returningAttributes(codec: PgCodec) { + return Object.entries(codec.attributes).filter(([, attribute]) => !attribute.expression && !attribute.via); +} + +function jsonRecordValue(codec: PgCodec, value: SQL): SQL { + while (codec.domainOfCodec) codec = codec.domainOfCodec; + return sql.isEquivalent(codec.sqlType, TYPES.json.sqlType) || sql.isEquivalent(codec.sqlType, TYPES.jsonb.sqlType) + ? sql`(${value})::json` + : sql`to_json(${value})`; +} + +export async function selectReturningRecords( + pgClient: PgClient, + from: SQL, + codec: PgCodec, + pkColumns: readonly string[], + pkRows: Record[] +): Promise { + if (pkRows.length === 0) return []; + + const alias = sql.identifier('__bulk_returning'); + const attributes = returningAttributes(codec); + const columns = attributes.map(([name, attribute], index) => { + const column = sql`${alias}.${sql.identifier(name)}`; + const encoded = attribute.codec.castFromPg + ? attribute.codec.castFromPg(column, !!attribute.notNull) + : sql`${column}::text`; + return sql`${encoded} AS ${sql.identifier(String(index))}`; + }); + const conditions = pkRows.map((row) => sql`(${sql.join( + pkColumns.map((column) => sql`${alias}.${sql.identifier(column)} = ${sql.value(row[column] as SQLRawValue)}`), + ' AND ' + )})`); + const result = await pgClient.query>(sql.compile(sql` + SELECT ${sql.join(columns, ', ')} + FROM ${from} AS ${alias} + WHERE ${sql.join(conditions, ' OR ')} + `)); + return result.rows.map((row) => Object.fromEntries(attributes.map(([name, attribute], index) => [ + name, + row[index] == null ? null : attribute.codec.fromPg(row[index]) + ]))); +} + +export function pgSelectReturningRecords(resource: PgResource, $records: Step) { + const attributes = returningAttributes(resource.codec); + const $encoded = lambda($records, (records: Record[]) => records.map((record) => + attributes.map(([name, attribute]) => { + const value = record[name]; + const encoded = value == null ? null : attribute.codec.toPg(value); + return encoded == null ? null : String(encoded); + }) + ), true); + const alias = sql.identifier('__bulk_records'); + const row = sql`${alias}."value"`; + const fields = sql.identifier('__bulk_attributes'); + const entries = attributes.map(([name, attribute], index) => sql`( + ${sql.literal(name)}, + ${jsonRecordValue(attribute.codec, sql`${row}->>${sql.literal(index)}`)} + )`); + return pgSelect({ + resource, + identifiers: [], + args: [{ step: $encoded, pgCodec: TYPES.json }], + from: (records) => sql`json_populate_recordset( + NULL::${resource.codec.sqlType}, + ( + SELECT coalesce(json_agg(( + SELECT json_object_agg(${fields}."key", ${fields}."value") + FROM (VALUES ${sql.join(entries, ', ')}) AS ${fields}("key", "value") + )), '[]'::json) + FROM json_array_elements(${records.placeholder}) AS ${alias}("value") + ) + )` + }); +} diff --git a/graphile/graphile-cache/__tests__/create-instance.test.ts b/graphile/graphile-cache/__tests__/create-instance.test.ts new file mode 100644 index 0000000000..6ea997c1e5 --- /dev/null +++ b/graphile/graphile-cache/__tests__/create-instance.test.ts @@ -0,0 +1,65 @@ +import { RealtimeManager } from 'graphile-realtime-subscriptions'; +import { postgraphile } from 'postgraphile'; + +import { createGraphileInstance } from '../src/create-instance'; + +jest.mock('postgraphile', () => ({ postgraphile: jest.fn() })); +jest.mock('graphile-realtime-subscriptions', () => ({ RealtimeManager: jest.fn() })); + +const release = jest.fn(); +const start = jest.fn(); +const stop = jest.fn(); +const pool = { query: jest.fn() }; +const pgSubscriber = {}; +const preset = { pgServices: [{ adaptorSettings: { pool }, pgSubscriber }] } as any; + +beforeEach(() => { + jest.clearAllMocks(); + release.mockResolvedValue(undefined); + start.mockResolvedValue(undefined); + (postgraphile as jest.Mock).mockImplementation((resolvedPreset) => ({ + createServ: () => ({ addTo: jest.fn(), ready: jest.fn() }), + getSchema: async () => ({}), + getResolvedPreset: () => resolvedPreset, + release + })); + (RealtimeManager as jest.Mock).mockImplementation(() => ({ start, stop })); +}); + +it('passes the registered physical schema to the manager', async () => { + const entry = await createGraphileInstance({ preset, cacheKey: 'tenant', enableRealtime: true, realtimeSchema: 'rt_tenant_123' }); + expect(RealtimeManager).toHaveBeenCalledWith(expect.objectContaining({ schema: 'rt_tenant_123', pool, pgSubscriber })); + expect(start).toHaveBeenCalledTimes(1); + expect(entry.realtimeManager).toEqual({ start, stop }); +}); + +it.each([ + { enableRealtime: true }, + { enableRealtime: false, realtimeSchema: 'rt_tenant_123' } +])('does not start a manager without an enabled installed module: %j', async (options) => { + const entry = await createGraphileInstance({ preset, cacheKey: 'tenant', ...options }); + expect(RealtimeManager).not.toHaveBeenCalled(); + expect(entry.realtimeManager).toBeUndefined(); +}); + +it('propagates startup failures and releases the graphile instance', async () => { + const error = new Error('listener startup failed'); + start.mockRejectedValue(error); + await expect(createGraphileInstance({ preset, cacheKey: 'tenant', enableRealtime: true, realtimeSchema: 'rt_tenant_123' })).rejects.toBe(error); + expect(release).toHaveBeenCalledTimes(1); +}); + +it('preserves both startup and cleanup failures', async () => { + const error = new Error('listener startup failed'); + const cleanup = new Error('release failed'); + start.mockRejectedValue(error); + release.mockRejectedValue(cleanup); + await expect(createGraphileInstance({ preset, cacheKey: 'tenant', enableRealtime: true, realtimeSchema: 'rt_tenant_123' })) + .rejects.toMatchObject({ errors: [error, cleanup] }); +}); + +it('fails closed if an installed realtime module has no subscriber service', async () => { + await expect(createGraphileInstance({ preset: { pgServices: [] }, cacheKey: 'tenant', enableRealtime: true, realtimeSchema: 'rt_tenant_123' })) + .rejects.toThrow('no pgSubscriber'); + expect(release).toHaveBeenCalledTimes(1); +}); diff --git a/graphile/graphile-cache/src/create-instance.ts b/graphile/graphile-cache/src/create-instance.ts index acdd87bc32..5bb540038a 100644 --- a/graphile/graphile-cache/src/create-instance.ts +++ b/graphile/graphile-cache/src/create-instance.ts @@ -19,6 +19,7 @@ interface GraphileInstanceOptions { * pgServices (managed by pg-cache) rather than passed separately. */ enableRealtime?: boolean; + realtimeSchema?: string; } /** @@ -44,7 +45,7 @@ interface GraphileInstanceOptions { export const createGraphileInstance = async ( opts: GraphileInstanceOptions ): Promise => { - const { preset, cacheKey, enableRealtime = false } = opts; + const { preset, cacheKey, enableRealtime = false, realtimeSchema } = opts; const heapBefore = process.memoryUsage().heapUsed; const pgl = postgraphile(preset); @@ -70,7 +71,7 @@ export const createGraphileInstance = async ( heapBytes, }; - if (enableRealtime) { + if (enableRealtime && realtimeSchema) { try { // Extract PgSubscriber and pool from the resolved preset's pgServices. // The pool is the same instance managed by pg-cache (via getPgPool) @@ -81,15 +82,15 @@ export const createGraphileInstance = async ( const pool = pgService?.adaptorSettings?.pool ?? null; if (!pgSubscriber) { - log.warn(`PostGraphile[${cacheKey}] has no pgSubscriber — RealtimeManager will not be started`); + throw new Error(`PostGraphile[${cacheKey}] has no pgSubscriber for realtime`); } else if (!pool) { - log.warn(`PostGraphile[${cacheKey}] has no pool in pgService — RealtimeManager will not be started`); + throw new Error(`PostGraphile[${cacheKey}] has no pool in pgService for realtime`); } else { const manager = new RealtimeManager({ pgSubscriber, pool, nodeId: `graphile-cache:${cacheKey}`, - schema: 'realtime_public', + schema: realtimeSchema, }); await manager.start(); @@ -97,7 +98,12 @@ export const createGraphileInstance = async ( log.info(`RealtimeManager started for PostGraphile[${cacheKey}]`); } } catch (err) { - log.error(`Failed to start RealtimeManager for PostGraphile[${cacheKey}]:`, err); + try { + await pgl.release(); + } catch (cleanupError) { + throw new AggregateError([err, cleanupError], `Realtime startup and cleanup failed for PostGraphile[${cacheKey}]`); + } + throw err; } } diff --git a/graphile/graphile-realtime-subscriptions/README.md b/graphile/graphile-realtime-subscriptions/README.md index b546a5067c..cac392cbf2 100644 --- a/graphile/graphile-realtime-subscriptions/README.md +++ b/graphile/graphile-realtime-subscriptions/README.md @@ -25,11 +25,23 @@ const preset = { ## How It Works 1. A row is inserted/updated/deleted on a `@realtime`-tagged table -2. The `emit_change` trigger fires `pg_notify('realtime:{schema}.{table}', TG_OP)` +2. The `emit_change` trigger notifies `realtime:` plus the lowercase MD5 of `:` (41 bytes total). The length prefix keeps dotted identifiers unambiguous. Trigger generation, subscription plans and durable dispatch use this same encoding; deploy both server and database changes together. 3. PostGraphile's `pgSubscriber` receives the NOTIFY 4. The subscription re-queries the source table with RLS enforced 5. The client receives `{ event, row }` where `row` reflects the current state +### Authorization + +INSERT and UPDATE emit no frame when the RLS-scoped row lookup is null, including metadata-only selections. An `ids` filter never grants access. + +Multi-row notifications are split into individual row events before authorization, so an invisible row cannot suppress visible rows later in the batch. + +The throttle counts only individually authorized, matching rows, not NOTIFY batches. Invisible rows and IDs excluded by the subscription consume no budget. When the visible-row limit is exceeded, one overflow frame is emitted per rate window, with no row or row ID. Its event is the operation of the visible row that caused overflow. + +DELETE is delivered only for IDs previously seen as visible by that same subscription. An invisible UPDATE clears that history. History retains at most 10,000 recently visible IDs; eviction conservatively suppresses subsequent DELETE events for forgotten IDs. + +Triggers send byte-bounded ID chunks instead of unscoped INVALIDATE markers. Ephemeral small-row JSON notifications are reduced to IDs and reauthorized in the same way; their embedded row data is never trusted for delivery. Producer and server changes require coordinated deployment; legacy INVALIDATE payloads are rejected as malformed. + ## Subscription Modes ### Phase 3a (current) diff --git a/graphile/graphile-realtime-subscriptions/__tests__/authorization.test.ts b/graphile/graphile-realtime-subscriptions/__tests__/authorization.test.ts new file mode 100644 index 0000000000..728fa00e0b --- /dev/null +++ b/graphile/graphile-realtime-subscriptions/__tests__/authorization.test.ts @@ -0,0 +1,219 @@ +import { type ExecutionResult, GraphQLError, parse } from 'graphql'; + +import { filterMapIterator, flatMapIterator } from '../src/async-iterator'; +import { SubscriptionDelivery } from '../src/delivery'; +import { createGatedSubscriber, type ParsedPayload } from '../src/event-gate'; +import { filterInaccessibleEvents, realtimeResponseNames } from '../src/subscription-filter'; +import { SubscriptionVisibility } from '../src/visibility'; + +const payload = (event: string, id = 'id'): ParsedPayload => ({ event, rowIds: [id], overflow: false }); + +describe('visible-row throttling', () => { + beforeEach(() => { jest.spyOn(Date, 'now').mockReturnValue(1000); }); + afterEach(() => { jest.restoreAllMocks(); }); + + it('delivers 50 owner rows and one id-less overflow for 61 visible changes', () => { + const state = new SubscriptionDelivery(50); + const delivered = Array.from({ length: 61 }, (_, i) => state.project(payload('INSERT', String(i)), true)).filter(Boolean); + expect(delivered).toHaveLength(51); + expect(delivered.slice(0, 50)).toEqual(Array.from({ length: 50 }, (_, i) => payload('INSERT', String(i)))); + expect(delivered[50]).toEqual({ event: 'INSERT', rowIds: [], overflow: true }); + }); + + it('does not spend any budget or emit overflow for invisible changes', () => { + const state = new SubscriptionDelivery(2); + for (let i = 0; i < 61; i++) expect(state.project(payload('INSERT', String(i)), false)).toBeNull(); + expect(state.project(payload('INSERT', 'a'), true)).toEqual(payload('INSERT', 'a')); + expect(state.project(payload('INSERT', 'b'), true)).toEqual(payload('INSERT', 'b')); + }); + + it('counts only visible rows in mixed batches and keeps subscription budgets independent', () => { + const a = new SubscriptionDelivery(1), b = new SubscriptionDelivery(1); + expect(a.project(payload('UPDATE', 'private'), false)).toBeNull(); + expect(a.project(payload('UPDATE', 'shared'), true)).toEqual(payload('UPDATE', 'shared')); + expect(a.project(payload('UPDATE', 'private'), false)).toBeNull(); + expect(a.project(payload('UPDATE', 'next'), true)).toEqual({ event: 'UPDATE', rowIds: [], overflow: true }); + expect(b.project(payload('UPDATE', 'next'), true)).toEqual(payload('UPDATE', 'next')); + }); + + it('resets the visible budget and overflow flag in the next window', () => { + const state = new SubscriptionDelivery(1); + state.project(payload('INSERT'), true); + expect(state.project(payload('INSERT'), true)?.overflow).toBe(true); + expect(state.project(payload('INSERT'), true)).toBeNull(); + jest.mocked(Date.now).mockReturnValue(2001); + expect(state.project(payload('INSERT'), true)).toEqual(payload('INSERT')); + expect(state.project(payload('INSERT'), true)?.overflow).toBe(true); + }); + + it('uses observed visibility for DELETE and does not charge empty input', () => { + const state = new SubscriptionDelivery(2); + expect(state.project({ event: 'UPDATE', rowIds: [], overflow: false }, true)).toBeNull(); + expect(state.project(payload('DELETE'), false)).toBeNull(); + expect(state.project(payload('INSERT'), true)).toEqual(payload('INSERT')); + expect(state.project(payload('DELETE'), false)).toEqual(payload('DELETE')); + }); + + it('rejects an unexpanded batch before charging any row', () => { + const state = new SubscriptionDelivery(1); + expect(() => state.project({ event: 'UPDATE', rowIds: ['a', 'b'], overflow: false }, true)).toThrow('single-row'); + expect(state.project(payload('UPDATE'), true)).toEqual(payload('UPDATE')); + }); +}); + +describe('per-row batch authorization', () => { + it('rejects an unexpanded batch rather than silently authorizing only its first row', () => { + const state = new SubscriptionVisibility(); + expect(() => state.allow({ event: 'UPDATE', rowIds: ['a', 'b'], overflow: false }, true)).toThrow('single-row events'); + expect(state.allow(payload('DELETE', 'a'), false)).toBe(false); + }); + it.each(['INSERT', 'UPDATE', 'DELETE'])('splits every %s batch before applying visibility', async event => { + const state = new SubscriptionVisibility(); + if (event === 'DELETE') state.allow(payload('INSERT', 'visible'), true); + const gate = createGatedSubscriber({ async *subscribe() { yield `${event}:hidden,visible`; } }, {}); + const accepted = []; + for await (const row of await gate.subscribe('topic')) { + expect(row.rowIds).toHaveLength(1); + if (state.allow(row, row.rowIds[0] === 'visible')) accepted.push(row); + } + expect(accepted).toEqual([payload(event, 'visible')]); + }); + it('does not yield buffered rows after cancellation', async () => { + let closed = false; + async function* source() { try { yield [1, 2, 3]; } finally { closed = true; } } + const expanded = flatMapIterator(source(), values => values); + expect(await expanded.next()).toEqual({ done: false, value: 1 }); + await expanded.return(); + expect(closed).toBe(true); + expect(await expanded.next()).toEqual({ done: true, value: undefined }); + }); +}); + +describe('per-subscription visibility', () => { + it.each(['INSERT', 'UPDATE'])('drops invisible %s and subsequent DELETE', event => { + const state = new SubscriptionVisibility(); + expect(state.allow(payload(event), false)).toBe(false); + expect(state.allow(payload('DELETE'), false)).toBe(false); + }); + it.each(['INSERT', 'UPDATE'])('remembers a visible %s for DELETE, then forgets it', event => { + const state = new SubscriptionVisibility(); + expect(state.allow(payload(event), true)).toBe(true); + expect(state.allow(payload('DELETE'), false)).toBe(true); + expect(state.allow(payload('DELETE'), false)).toBe(false); + }); + it('forgets rows when they move out of visibility', () => { + const state = new SubscriptionVisibility(); + expect(state.allow(payload('INSERT'), true)).toBe(true); + expect(state.allow(payload('UPDATE'), false)).toBe(false); + expect(state.allow(payload('DELETE'), false)).toBe(false); + }); + it('does not share history between subscriptions', () => { + const original = new SubscriptionVisibility(); + const fresh = new SubscriptionVisibility(); + expect(original.allow(payload('INSERT'), true)).toBe(true); + expect(fresh.allow(payload('DELETE'), false)).toBe(false); + expect(original.allow(payload('DELETE'), false)).toBe(true); + }); + it('drops unscoped or empty signals even when passed a visible row', () => { + const state = new SubscriptionVisibility(); + expect(state.allow({ event: 'INVALIDATE', rowIds: [], overflow: true }, true)).toBe(false); + expect(state.allow({ event: 'UPDATE', rowIds: [], overflow: false }, true)).toBe(false); + }); + it('bounds remembered IDs by conservatively forgetting the oldest', () => { + const state = new SubscriptionVisibility(); + for (let i = 0; i <= 10_000; i++) state.allow(payload('INSERT', String(i)), true); + expect(state.allow(payload('DELETE', '0'), false)).toBe(false); + expect(state.allow(payload('DELETE', '10000'), false)).toBe(true); + }); +}); + +describe('subscription result filtering', () => { + async function* source(...values: any[]) { yield* values; } + async function collect(values: AsyncIterable) { + const results = []; + for await (const value of values) results.push(value); + return results; + } + it('drops the entire null-root result, not only its metadata', async () => { + const allowed = { data: { change: { event: 'INSERT', rowId: 'visible' } } }; + expect(await collect(filterInaccessibleEvents(source({ data: { change: null } }, allowed), ['change']))).toEqual([allowed]); + }); + it('handles an empty source without emitting a frame', async () => { + expect(await collect(filterInaccessibleEvents(source(), ['change']))).toEqual([]); + }); + it('filters pre-serialized root data but preserves incremental patches', async () => { + const patch = { path: ['change', 'note'], data: 'text' }; + const allowed = { data: '{"change":{"event":"INSERT"}}' }; + expect(await collect(filterInaccessibleEvents(source({ data: '{"change":null}' }, patch, allowed), ['change']))).toEqual([patch, allowed]); + }); + it('preserves GraphQL errors and results outside the realtime field', async () => { + const error: ExecutionResult = { data: { change: null }, errors: [new GraphQLError('RLS query failed')] }; + const unrelated: ExecutionResult = { data: { elsewhere: null } }; + expect(await collect(filterInaccessibleEvents(source(error, unrelated), ['change']))).toEqual([error, unrelated]); + }); + it('does not hide source failures', async () => { + const error = new Error('LISTEN failed'); + const broken = { [Symbol.asyncIterator]() { return { next: () => Promise.reject(error) }; } }; + await expect(filterInaccessibleEvents(broken, ['change']).next()).rejects.toBe(error); + }); + it('closes the source on a transform failure', async () => { + let closed = false; + async function* watched() { try { yield 'bad'; } finally { closed = true; } } + const error = new Error('malformed notification'); + await expect(filterMapIterator(watched(), () => { throw error; }).next()).rejects.toBe(error); + expect(closed).toBe(true); + }); + it('cancels an idle next immediately instead of queuing return behind it', async () => { + let finish!: (value: IteratorResult) => void; + const iterator = { + [Symbol.asyncIterator]() { return this; }, + next: () => new Promise>(resolve => { finish = resolve; }), + return: jest.fn(async (): Promise> => { finish({ done: true, value: undefined }); return { done: true, value: undefined }; }) + }; + const filtered = filterMapIterator(iterator, value => value); + const pending = filtered.next(); + await filtered.return!(); + expect(iterator.return).toHaveBeenCalledTimes(1); + expect(await pending).toEqual({ done: true, value: undefined }); + }); + it('propagates throw and closes a source that has no throw method', async () => { + const close = jest.fn(async (): Promise> => ({ done: true, value: undefined })); + const iterator = { [Symbol.asyncIterator]() { return this; }, next: close, return: close }; + const error = new Error('cancel'); + await expect(filterMapIterator(iterator, value => value).throw!(error)).rejects.toBe(error); + expect(close).toHaveBeenCalledTimes(1); + }); + it('resolves aliased roots through fragments and selects the requested operation', () => { + const document = parse(`subscription Watch { ...Root } + fragment Root on Subscription { ... on Subscription { change: onNoteChanged { event } } } + query Other { __typename }`); + const fields = new Set(['onNoteChanged']); + expect(realtimeResponseNames(document, 'Watch', fields)).toEqual(['change']); + expect(realtimeResponseNames(document, 'Other', fields)).toEqual([]); + expect(realtimeResponseNames(document, undefined, fields)).toEqual([]); + expect(realtimeResponseNames(document, 'Watch', new Set())).toEqual([]); + }); + + it.each(['@skip(if: true)', '@include(if: false)'])('ignores excluded aliases when filtering inaccessible events: %s', async directive => { + const document = parse(`subscription { change: onNoteChanged { event } skipped: onNoteChanged ${directive} { event } }`); + const names = realtimeResponseNames(document, undefined, new Set(['onNoteChanged'])); + expect(names).toEqual(['change']); + const allowed = { data: { change: { event: 'INSERT' } } }; + expect(await collect(filterInaccessibleEvents(source({ data: { change: null } }, allowed), names))).toEqual([allowed]); + }); + + it('honors variable values and defaults on fields, spreads and inline fragments', () => { + const document = parse(`subscription Watch($skip: Boolean! = true, $include: Boolean! = false) { + excluded: onNoteChanged @skip(if: $skip) { event } + ...Root @include(if: $include) + ... on Subscription @skip(if: $skip) { inline: onNoteChanged { event } } + ...Root + } + fragment Root on Subscription { change: onNoteChanged @include(if: true) { event } }`); + const fields = new Set(['onNoteChanged']); + expect(realtimeResponseNames(document, 'Watch', fields)).toEqual(['change']); + expect(realtimeResponseNames(document, 'Watch', fields, { skip: false, include: true })).toEqual(['excluded', 'change', 'inline']); + const skipped = parse('subscription { onNoteChanged @include(if: false) { event } }'); + expect(realtimeResponseNames(skipped, undefined, fields)).toEqual([]); + }); +}); diff --git a/graphile/graphile-realtime-subscriptions/__tests__/channel.test.ts b/graphile/graphile-realtime-subscriptions/__tests__/channel.test.ts new file mode 100644 index 0000000000..cb0a120f3e --- /dev/null +++ b/graphile/graphile-realtime-subscriptions/__tests__/channel.test.ts @@ -0,0 +1,22 @@ +import { realtimeChannel } from '../src/channel'; + +it.each([ + ['app_public', 'projects', '82e4cc86e360dca4f9342e08ca91489d'], + ['inventory_public', 'items', 'e66af24f0e368ab1c28a95c1cd4fd830'], + ['schemä.測', 'table.名', '6e2395ccd5e544e252ecbf660f313099'], + ['', '', '9a1c7ee2c7ce38d4bbbaf29ab9f2ac1e'] +])('encodes %j and %j identically to the SQL emitter', (schema, table, hash) => { + expect(realtimeChannel(schema, table)).toBe(`realtime:${hash}`); +}); + +it('bounds the channel even for maximum-size identifiers', () => { + const schema = 's'.repeat(63); + const table = 't'.repeat(63); + expect(Buffer.byteLength(realtimeChannel(schema, table))).toBe(41); + expect(realtimeChannel(schema, table)).toBe(realtimeChannel(schema, table)); +}); + +it('keeps qualified names with ambiguous delimiters distinct', () => { + expect(realtimeChannel('a.b', 'c')).toBe('realtime:a5507cd532dbd2308bb9ab5b425ff691'); + expect(realtimeChannel('a', 'b.c')).toBe('realtime:46e0a8e356179c0a3e4ed16727af894e'); +}); diff --git a/graphile/graphile-realtime-subscriptions/__tests__/cursor-tracker.test.ts b/graphile/graphile-realtime-subscriptions/__tests__/cursor-tracker.test.ts index 05a3c9b50a..77041d161f 100644 --- a/graphile/graphile-realtime-subscriptions/__tests__/cursor-tracker.test.ts +++ b/graphile/graphile-realtime-subscriptions/__tests__/cursor-tracker.test.ts @@ -32,7 +32,14 @@ import type { ChangeLogEntry,Queryable } from '../src/types'; function createMockPool(queryResult: { rows: any[] } = { rows: [] }): jest.Mocked { return { - query: jest.fn().mockResolvedValue(queryResult), + query: jest.fn().mockImplementation(async (sql: string) => { + if (sql.includes('runtime_sources')) return { rows: [{ runtime_sources: { + source_schema: 'app_public', source_table: 'projects', + fanout_function: 'fanout_projects', cleanup_function: 'cleanup_projects', + } }] }; + if (sql.includes('fanout_projects')) return { rows: queryResult.rows.map(row => ({ entry: row.drain_changes })) }; + return sql.includes('drain_changes') ? queryResult : { rows: [] }; + }), }; } @@ -58,7 +65,7 @@ describe('CursorTracker defaults', () => { expect(DEFAULT_POLL_INTERVAL_MS).toBe(5000); expect(DEFAULT_HEARTBEAT_INTERVAL_MS).toBe(30000); expect(DEFAULT_BATCH_LIMIT).toBe(500); - expect(DEFAULT_SCHEMA).toBe('realtime_public'); + expect(DEFAULT_SCHEMA).toBe('realtime_private'); }); it('generates a nodeId when not provided', () => { @@ -163,6 +170,60 @@ describe('CursorTracker.stop()', () => { jest.useRealTimers(); }); + it('does not clean up a tracker that never started', async () => { + const pool = createMockPool(); + await new CursorTracker({ pool }).stop(); + expect(pool.query).not.toHaveBeenCalled(); + }); + + it.each(['cleanup_projects', 'cleanup_ephemeral'])('retries pending shutdown after %s fails', async cleanup => { + const pool = createMockPool(); + const query = pool.query.getMockImplementation()!; + const tracker = new CursorTracker({ pool }); + await tracker.start(); + pool.query.mockImplementation((sql, values) => sql.includes(cleanup) ? Promise.reject(new Error('cleanup failed')) : query(sql, values)); + await expect(tracker.stop()).rejects.toThrow('cleanup failed'); + expect(tracker.isRunning).toBe(false); + expect(jest.getTimerCount()).toBe(0); + pool.query.mockImplementation(query).mockClear(); + await tracker.stop(); + expect(pool.query).toHaveBeenLastCalledWith(expect.stringContaining('cleanup_ephemeral'), [tracker.nodeId]); + pool.query.mockClear(); + await tracker.stop(); + expect(pool.query).not.toHaveBeenCalled(); + }); + + it('retries pending cleanup after startup and its cleanup both fail', async () => { + const pool = createMockPool(); + const query = pool.query.getMockImplementation()!; + pool.query.mockImplementation((sql, values) => sql.includes('drain_changes') || sql.includes('cleanup_projects') ? Promise.reject(new Error('startup or cleanup failed')) : query(sql, values)); + const tracker = new CursorTracker({ pool }); + await expect(tracker.start()).rejects.toBeInstanceOf(AggregateError); + expect(tracker.isRunning).toBe(false); + expect(jest.getTimerCount()).toBe(0); + pool.query.mockImplementation(query).mockClear(); + await tracker.stop(); + expect(pool.query).toHaveBeenLastCalledWith(expect.stringContaining('cleanup_ephemeral'), [tracker.nodeId]); + }); + + it('cleans up once before concurrent restarts after a failed shutdown', async () => { + const pool = createMockPool(); + const query = pool.query.getMockImplementation()!; + const tracker = new CursorTracker({ pool }); + await tracker.start(); + pool.query.mockImplementation((sql, values) => sql.includes('cleanup_projects') ? Promise.reject(new Error('cleanup failed')) : query(sql, values)); + await expect(tracker.stop()).rejects.toThrow('cleanup failed'); + pool.query.mockImplementation(query).mockClear(); + await Promise.all([tracker.start(), tracker.start()]); + const calls = pool.query.mock.calls.map(([sql]) => sql); + expect(calls.filter(sql => sql.includes('touch_listener'))).toHaveLength(1); + expect(jest.getTimerCount()).toBe(2); + expect(calls.findIndex(sql => sql.includes('cleanup_ephemeral'))).toBeGreaterThanOrEqual(0); + expect(calls.findIndex(sql => sql.includes('cleanup_ephemeral'))).toBeLessThan(calls.findIndex(sql => sql.includes('touch_listener'))); + expect(tracker.isRunning).toBe(true); + await tracker.stop(); + }); + it('calls cleanup_ephemeral on stop', async () => { const mockPool = createMockPool(); const tracker = new CursorTracker({ @@ -280,6 +341,38 @@ describe('CursorTracker.drain()', () => { expect(onChanges).toHaveBeenCalledWith([entry]); }); + it.each([false, true])('does not advance when onChanges fails (async: %s), and retries', async asynchronous => { + const entry = createChangeLogEntry(); + const pool = createMockPool({ rows: [{ drain_changes: entry }] }); + const failure = new Error('dispatch failed'); + const onChanges = jest.fn().mockImplementationOnce(() => { + if (asynchronous) return Promise.reject(failure); + throw failure; + }).mockImplementationOnce(() => { + expect(pool.query.mock.calls.some(([sql]) => sql.includes('advance_cursor'))).toBe(false); + }); + const tracker = new CursorTracker({ pool, onChanges }); + await expect(tracker.drain()).rejects.toBe(failure); + expect(pool.query.mock.calls.some(([sql]) => sql.includes('advance_cursor'))).toBe(false); + await expect(tracker.drain()).resolves.toEqual([entry]); + expect(onChanges).toHaveBeenCalledTimes(2); + expect(pool.query).toHaveBeenLastCalledWith(expect.stringContaining('advance_cursor'), [tracker.nodeId, entry.occurred_at]); + }); + + it('waits for asynchronous dispatch before advancing', async () => { + const entry = createChangeLogEntry(); + const pool = createMockPool({ rows: [{ drain_changes: entry }] }); + let complete!: () => void; + const onChanges = jest.fn(() => new Promise(resolve => { complete = resolve; })); + const tracker = new CursorTracker({ pool, onChanges }); + const pending = tracker.drain(); + while (!onChanges.mock.calls.length) await Promise.resolve(); + expect(pool.query.mock.calls.some(([sql]) => sql.includes('advance_cursor'))).toBe(false); + complete(); + await expect(pending).resolves.toEqual([entry]); + expect(pool.query).toHaveBeenLastCalledWith(expect.stringContaining('advance_cursor'), [tracker.nodeId, entry.occurred_at]); + }); + it('does not call onChanges when no entries', async () => { const onChanges = jest.fn(); @@ -292,7 +385,7 @@ describe('CursorTracker.drain()', () => { expect(onChanges).not.toHaveBeenCalled(); }); - it('returns empty array on error and calls onError', async () => { + it('propagates drain failures to the caller', async () => { const failingPool: Queryable = { query: jest.fn().mockRejectedValue(new Error('connection lost')), }; @@ -303,12 +396,8 @@ describe('CursorTracker.drain()', () => { onError, }); - const result = await tracker.drain(); - - expect(result).toEqual([]); - expect(onError).toHaveBeenCalledWith(expect.objectContaining({ - message: 'connection lost', - })); + await expect(tracker.drain()).rejects.toThrow('connection lost'); + expect(onError).not.toHaveBeenCalled(); }); it('prevents concurrent drains', async () => { @@ -334,6 +423,44 @@ describe('CursorTracker.drain()', () => { resolveQuery!(); await drain1; }); + + it('advances the cursor only after successful source fanout, preserving timestamp precision', async () => { + const entry = createChangeLogEntry({ occurred_at: '2026-11-20T12:00:00.123456+00:00' }); + const pool = createMockPool({ rows: [{ drain_changes: entry }] }); + const tracker = new CursorTracker({ pool, nodeId: 'node' }); + await tracker.drain(); + expect(pool.query).toHaveBeenLastCalledWith(expect.stringContaining('advance_cursor'), ['node', entry.occurred_at]); + const calls = pool.query.mock.calls.map(([sql]) => sql); + expect(calls.findIndex(sql => sql.includes('fanout_projects'))).toBeLessThan(calls.findIndex(sql => sql.includes('advance_cursor'))); + }); + + it('does not advance or dispatch when a source fanout fails', async () => { + const entry = createChangeLogEntry(); + const pool = createMockPool({ rows: [{ drain_changes: entry }] }); + const query = pool.query.getMockImplementation()!; + pool.query.mockImplementation((sql, values) => sql.includes('fanout_projects') ? Promise.reject(new Error('fanout failed')) : query(sql, values)); + const onChanges = jest.fn(); + const tracker = new CursorTracker({ pool, onChanges }); + await expect(tracker.drain()).rejects.toThrow('fanout failed'); + expect(pool.query.mock.calls.some(([sql]) => sql.includes('advance_cursor'))).toBe(false); + expect(onChanges).not.toHaveBeenCalled(); + }); + + it('advances past unmatched pending changes without dispatching them', async () => { + const pool = createMockPool({ rows: [{ drain_changes: createChangeLogEntry({ source_table: 'unregistered' }) }] }); + const onChanges = jest.fn(); + await expect(new CursorTracker({ pool, onChanges }).drain()).resolves.toEqual([]); + expect(pool.query.mock.calls.some(([sql]) => sql.includes('advance_cursor'))).toBe(true); + expect(onChanges).not.toHaveBeenCalled(); + }); + + it('preserves the listener when per-source cleanup fails', async () => { + const pool = createMockPool(); + const query = pool.query.getMockImplementation()!; + pool.query.mockImplementation((sql, values) => sql.includes('cleanup_projects') ? Promise.reject(new Error('source cleanup failed')) : query(sql, values)); + await expect(new CursorTracker({ pool }).cleanupEphemeral()).rejects.toThrow('source cleanup failed'); + expect(pool.query.mock.calls.some(([sql]) => sql.includes('cleanup_ephemeral'))).toBe(false); + }); }); describe('CursorTracker periodic polling', () => { @@ -416,7 +543,7 @@ describe('CursorTracker schema quoting', () => { await tracker.drain(); expect(mockPool.query).toHaveBeenCalledWith( - expect.stringContaining('realtime_public'), + expect.stringContaining('realtime_private'), expect.any(Array), ); }); @@ -447,7 +574,7 @@ describe('CursorTracker error handling', () => { jest.useRealTimers(); }); - it('touch_listener error calls onError without throwing', async () => { + it('propagates touch_listener failures', async () => { const failingPool: Queryable = { query: jest.fn().mockRejectedValue(new Error('touch failed')), }; @@ -458,14 +585,11 @@ describe('CursorTracker error handling', () => { onError, }); - await tracker.touchListener(); - - expect(onError).toHaveBeenCalledWith(expect.objectContaining({ - message: 'touch failed', - })); + await expect(tracker.touchListener()).rejects.toThrow('touch failed'); + expect(onError).not.toHaveBeenCalled(); }); - it('cleanup_ephemeral error calls onError without throwing', async () => { + it('propagates cleanup_ephemeral failures', async () => { const failingPool: Queryable = { query: jest.fn().mockRejectedValue(new Error('cleanup failed')), }; @@ -476,11 +600,8 @@ describe('CursorTracker error handling', () => { onError, }); - await tracker.cleanupEphemeral(); - - expect(onError).toHaveBeenCalledWith(expect.objectContaining({ - message: 'cleanup failed', - })); + await expect(tracker.cleanupEphemeral()).rejects.toThrow('cleanup failed'); + expect(onError).not.toHaveBeenCalled(); }); it('wraps non-Error objects in Error', async () => { @@ -494,9 +615,38 @@ describe('CursorTracker error handling', () => { onError, }); - await tracker.drain(); + await expect(tracker.drain()).rejects.toThrow('string error'); + expect(onError).not.toHaveBeenCalled(); + }); + + it('rejects failed initial drain, cleans registration, and leaves no timers', async () => { + const pool = createMockPool(); + pool.query.mockResolvedValueOnce({ rows: [] }).mockRejectedValueOnce(new Error('initial drain failed')); + const tracker = new CursorTracker({ pool, schema: 'physical_rt' }); + await expect(tracker.start()).rejects.toThrow('initial drain failed'); + expect(pool.query).toHaveBeenLastCalledWith('SELECT physical_rt.cleanup_ephemeral($1)', [tracker.nodeId]); + expect(tracker.isRunning).toBe(false); + expect(jest.getTimerCount()).toBe(0); + }); + + it('rejects failed registration without installing timers', async () => { + const pool = createMockPool(); + pool.query.mockRejectedValueOnce(new Error('registration failed')); + const tracker = new CursorTracker({ pool }); + await expect(tracker.start()).rejects.toThrow('registration failed'); + expect(pool.query).toHaveBeenCalledTimes(1); + expect(tracker.isRunning).toBe(false); + expect(jest.getTimerCount()).toBe(0); + }); - expect(onError).toHaveBeenCalledWith(expect.any(Error)); - expect(onError.mock.calls[0][0].message).toBe('string error'); + it('preserves a startup failure when registration cleanup also fails', async () => { + const pool = createMockPool(); + const error = new Error('drain failed'); + const cleanup = new Error('cleanup failed'); + pool.query.mockResolvedValueOnce({ rows: [] }).mockRejectedValueOnce(error).mockRejectedValueOnce(cleanup); + const tracker = new CursorTracker({ pool }); + await expect(tracker.start()).rejects.toMatchObject({ errors: [error, cleanup] }); + expect(tracker.isRunning).toBe(false); + expect(jest.getTimerCount()).toBe(0); }); }); diff --git a/graphile/graphile-realtime-subscriptions/__tests__/plugin.test.ts b/graphile/graphile-realtime-subscriptions/__tests__/plugin.test.ts index 7f6669bbf5..1348d9c715 100644 --- a/graphile/graphile-realtime-subscriptions/__tests__/plugin.test.ts +++ b/graphile/graphile-realtime-subscriptions/__tests__/plugin.test.ts @@ -5,11 +5,11 @@ * - Table discovery via @realtime smart tag * - Subscription field generation (onXxxChanged) * - Payload type generation (XxxSubscriptionPayload) with rowId and overflow fields - * - NOTIFY channel naming (realtime:{schema}.{table}) + * - Bounded NOTIFY channel naming * - Tables without @realtime tag are excluded * - Empty registry produces no fields * - Multiple realtime tables produce multiple fields - * - NOTIFY payload parsing (TG_OP:id1,id2,... and INVALIDATE) + * - NOTIFY payload parsing (TG_OP:id1,id2,... and ephemeral JSON) * - Per-subscriber event throttling with configurable limit * - Sparse set subscriptions (ids: [UUID!]) with row ID intersection filtering * - RLS-aware rowId masking in payload resolvers @@ -38,6 +38,8 @@ jest.mock('grafast', () => ({ object: mockObject, constant: mockConstant, lambda: mockLambda, + sideEffect: jest.fn((input: any, fn: Function) => fn(input)), + inhibitIf: jest.fn((input: any, hidden: boolean) => hidden ? null : input), })); let capturedFactory: Function | null = null; @@ -54,6 +56,7 @@ jest.mock('graphile-utils', () => ({ })); import type { EventGateOptions } from '../src/event-gate'; +import { SubscriptionDelivery } from '../src/delivery'; import { createGatedSubscriber, createRealtimeSubscriptionsPlugin, @@ -136,15 +139,20 @@ describe('parseNotifyPayload', () => { }); }); - it('parses INVALIDATE as overflow', () => { - const result = parseNotifyPayload('INVALIDATE'); - expect(result).toEqual({ - event: 'INVALIDATE', - rowIds: [], - overflow: true, + it('rejects the legacy id-less INVALIDATE marker', () => { + expect(() => parseNotifyPayload('INVALIDATE')).toThrow(MalformedNotifyPayloadError); + }); + + it('extracts only ids from ephemeral rows, never their embedded data', () => { + expect(parseNotifyPayload(JSON.stringify({ op: 'INSERT', rows: [{ id: 'a', title: 'private' }] }))).toEqual({ + event: 'INSERT', rowIds: ['a'], overflow: false, }); }); + it.each(['{', '{"op":"INSERT","rows":[]}', '{"op":"INSERT","rows":[{}]}'])('rejects malformed ephemeral input %s without echoing row data', raw => { + expect(() => parseNotifyPayload(raw)).toThrow(MalformedNotifyPayloadError); + }); + // A payload this cannot read means emit_change and this plugin have // diverged. Inventing an event name for it hides a deployment fault behind // data the client acts on, so every unreadable shape is a hard failure. @@ -259,7 +267,7 @@ describe('createRealtimeSubscriptionsPlugin', () => { const result = capturedFactory!(build); - expect(result.typeDefs).toBe(''); + expect(result.typeDefs).toEqual([]); expect(result.plans).toEqual({}); }); @@ -272,7 +280,7 @@ describe('createRealtimeSubscriptionsPlugin', () => { const result = capturedFactory!(build); - expect(result.typeDefs).toBe(''); + expect(result.typeDefs).toEqual([]); expect(result.plans).toEqual({}); }); @@ -282,7 +290,7 @@ describe('createRealtimeSubscriptionsPlugin', () => { const build = createMockBuild({}); const result = capturedFactory!(build); - expect(result.typeDefs).toBe(''); + expect(result.typeDefs).toEqual([]); expect(result.plans).toEqual({}); }); @@ -336,7 +344,7 @@ describe('createRealtimeSubscriptionsPlugin', () => { expect(result.typeDefs).toContain('documents: Documents'); expect(result.typeDefs).toContain('rowId: UUID'); expect(result.typeDefs).toContain('overflow: Boolean!'); - expect(result.typeDefs).toContain('masked when RLS denies access'); + expect(result.typeDefs).toContain('visible to this subscription'); }); it('extends Subscription type', () => { @@ -354,7 +362,7 @@ describe('createRealtimeSubscriptionsPlugin', () => { }); describe('NOTIFY channel naming', () => { - it('uses realtime:{schema}.{table} format', () => { + it('uses the bounded deterministic channel format', () => { createRealtimeSubscriptionsPlugin(); const codec = createMockCodec('projects', { @@ -374,7 +382,7 @@ describe('createRealtimeSubscriptionsPlugin', () => { const mockArgs = { getRaw: jest.fn(() => 'test-id') }; result.plans['Subscription']['onProjectsChanged'].subscribePlan(null, mockArgs); - expect(mockConstant).toHaveBeenCalledWith('realtime:app_public.projects'); + expect(mockConstant).toHaveBeenCalledWith('realtime:82e4cc86e360dca4f9342e08ca91489d'); }); it('handles different schema names', () => { @@ -393,7 +401,7 @@ describe('createRealtimeSubscriptionsPlugin', () => { const mockArgs = { getRaw: jest.fn(() => 'test-id') }; result.plans['Subscription']['onItemsChanged'].subscribePlan(null, mockArgs); - expect(mockConstant).toHaveBeenCalledWith('realtime:inventory_public.items'); + expect(mockConstant).toHaveBeenCalledWith('realtime:e66af24f0e368ab1c28a95c1cd4fd830'); }); }); @@ -430,19 +438,20 @@ describe('createRealtimeSubscriptionsPlugin', () => { expect(mockListen).toHaveBeenCalled(); }); - it('plan function returns event as-is', () => { + it('plan function authorizes the row before exposing metadata', () => { createRealtimeSubscriptionsPlugin(); const codec = createMockCodec('tasks', { realtime: true }); - const build = createMockBuild({ - tasks: createMockResource('tasks', codec), - }); - - const result = capturedFactory!(build); - const mockEvent = { get: jest.fn() }; - - const planResult = result.plans['Subscription']['onTasksChanged'].plan(mockEvent); - expect(planResult).toBe(mockEvent); + const row = { id: 'row-uuid' }; + const resource = { ...createMockResource('tasks', codec), get: jest.fn(() => row) }; + const result = capturedFactory!(createMockBuild({ tasks: resource })); + const parsed = { event: 'INSERT', rowIds: ['row-uuid'], overflow: false }; + const visibility = new SubscriptionDelivery(50); + const mockEvent = { get: (key: string) => ({ parsed, visibility }[key]) }; + expect(result.plans['Subscription']['onTasksChanged'].plan(mockEvent)).toEqual({ parsed, row }); + expect(resource.get).toHaveBeenCalledWith({ id: 'row-uuid' }); + resource.get.mockReturnValue(null); + expect(result.plans['Subscription']['onTasksChanged'].plan(mockEvent)).toEqual({ parsed: null, row: null }); }); it('generates payload type plans with event, row, rowId, and overflow resolvers', () => { @@ -479,7 +488,7 @@ describe('createRealtimeSubscriptionsPlugin', () => { expect(mockParent.get).toHaveBeenCalledWith('parsed'); }); - it('payload row resolver uses parsed rowId for full collection mode', () => { + it('payload row resolver reuses the authorized row', () => { createRealtimeSubscriptionsPlugin(); const codec = createMockCodec('tasks', { realtime: true }); @@ -495,11 +504,9 @@ describe('createRealtimeSubscriptionsPlugin', () => { const mockParent = { get: jest.fn(() => ({ event: 'INSERT', rowIds: ['row-uuid'], overflow: false })) }; result.plans['TasksSubscriptionPayload'].tasks(mockParent); - // The gate already narrowed rowIds to the subscription's ids, so the - // resolver reads nothing but 'parsed'. - expect(mockParent.get).toHaveBeenCalledWith('parsed'); + expect(mockParent.get).toHaveBeenCalledWith('row'); expect(mockParent.get).not.toHaveBeenCalledWith('subscribedIds'); - expect(mockResource.get).toHaveBeenCalled(); + expect(mockResource.get).not.toHaveBeenCalled(); }); }); @@ -554,27 +561,25 @@ describe('createRealtimeSubscriptionsPlugin', () => { it('yields nothing at all for an unsubscribed row', async () => { const gated = createGatedSubscriber(subscriberEmitting('UPDATE:id-x,id-y'), { ids: ['id-a', 'id-b'], - threshold: 50, }); await expect(collect(gated)).resolves.toEqual([]); }); - it('narrows rowIds to the subscribed set so no consumer re-intersects', async () => { + it('narrows to the subscribed IDs and authorizes each row independently', async () => { const gated = createGatedSubscriber(subscriberEmitting('UPDATE:id-x,id-b,id-a'), { ids: ['id-a', 'id-b'], - threshold: 50, }); await expect(collect(gated)).resolves.toEqual([ - { event: 'UPDATE', rowIds: ['id-b', 'id-a'], overflow: false }, + { event: 'UPDATE', rowIds: ['id-b'], overflow: false }, + { event: 'UPDATE', rowIds: ['id-a'], overflow: false }, ]); }); it('passes every event through in full collection mode', async () => { const gated = createGatedSubscriber(subscriberEmitting('INSERT:id-x', 'DELETE:id-y'), { ids: null, - threshold: 50, }); await expect(collect(gated)).resolves.toEqual([ @@ -583,32 +588,29 @@ describe('createRealtimeSubscriptionsPlugin', () => { ]); }); - it('delivers INVALIDATE regardless of the sparse set', async () => { - const gated = createGatedSubscriber(subscriberEmitting('INVALIDATE'), { - ids: ['id-a'], - threshold: 50, - }); - - await expect(collect(gated)).resolves.toEqual([ - { event: 'INVALIDATE', rowIds: [], overflow: true }, - ]); + it('rejects id-less legacy notifications even for a sparse set', async () => { + const gated = createGatedSubscriber(subscriberEmitting('INVALIDATE'), { ids: ['id-a'] }); + await expect(collect(gated)).rejects.toThrow(MalformedNotifyPayloadError); }); - it('collapses a burst to one INVALIDATE and then yields nothing', async () => { - const gated = createGatedSubscriber( - subscriberEmitting('INSERT:a', 'INSERT:b', 'INSERT:c', 'INSERT:d'), - { ids: null, threshold: 2 } - ); + it('does not consume a rate budget before rows can be authorized', async () => { + const gated = createGatedSubscriber(subscriberEmitting('UPDATE:a,b,c', 'UPDATE:d'), { ids: null }); + await expect(collect(gated)).resolves.toEqual(['a', 'b', 'c', 'd'].map(id => ({ + event: 'UPDATE', rowIds: [id], overflow: false, + }))); + }); + it('does not charge the row budget for IDs excluded by the subscription', async () => { + const gated = createGatedSubscriber(subscriberEmitting('UPDATE:excluded', 'UPDATE:a'), { + ids: ['a'], + }); await expect(collect(gated)).resolves.toEqual([ - { event: 'INSERT', rowIds: ['a'], overflow: false }, - { event: 'INSERT', rowIds: ['b'], overflow: false }, - { event: 'INVALIDATE', rowIds: [], overflow: true }, + { event: 'UPDATE', rowIds: ['a'], overflow: false }, ]); }); - it('throttles each subscription independently', async () => { - const opts: EventGateOptions = { ids: null, threshold: 1 }; + it('keeps sparse gating independent for each subscription', async () => { + const opts: EventGateOptions = { ids: null }; const noisy = createGatedSubscriber(subscriberEmitting('INSERT:a', 'INSERT:b'), opts); await collect(noisy); @@ -621,7 +623,6 @@ describe('createRealtimeSubscriptionsPlugin', () => { it('surfaces a malformed payload instead of emitting an event for it', async () => { const gated = createGatedSubscriber(subscriberEmitting('TRUNCATE:a'), { ids: null, - threshold: 50, }); await expect(collect(gated)).rejects.toThrow(MalformedNotifyPayloadError); @@ -642,16 +643,15 @@ describe('createRealtimeSubscriptionsPlugin', () => { expect(mockArgs.getRaw).toHaveBeenCalledWith('ids'); - // 'parsed' is the whole payload now — nothing downstream needs the ids. const listenCallback = mockListen.mock.calls[mockListen.mock.calls.length - 1][2]; listenCallback({ event: 'INSERT', rowIds: ['id-a'], overflow: false }); const objectArg = mockObject.mock.calls[mockObject.mock.calls.length - 1][0]; - expect(Object.keys(objectArg)).toEqual(['parsed']); + expect(Object.keys(objectArg)).toEqual(['parsed', 'visibility']); }); }); describe('RLS-aware event delivery', () => { - it('rowId doc comment mentions RLS masking', () => { + it('rowId documentation describes authorized delivery', () => { createRealtimeSubscriptionsPlugin(); const codec = createMockCodec('items', { realtime: true }); @@ -660,7 +660,7 @@ describe('createRealtimeSubscriptionsPlugin', () => { }); const result = capturedFactory!(build); - expect(result.typeDefs).toContain('masked when RLS denies access'); + expect(result.typeDefs).toContain('visible to this subscription'); }); it('type defs include sparse set ids argument', () => { diff --git a/graphile/graphile-realtime-subscriptions/__tests__/realtime-manager.test.ts b/graphile/graphile-realtime-subscriptions/__tests__/realtime-manager.test.ts index c0d10650e0..0a613f301c 100644 --- a/graphile/graphile-realtime-subscriptions/__tests__/realtime-manager.test.ts +++ b/graphile/graphile-realtime-subscriptions/__tests__/realtime-manager.test.ts @@ -98,12 +98,12 @@ describe('entryToNotifyPayload', () => { describe('entryToChannel', () => { it('builds channel from source_schema and source_table', () => { const entry = makeEntry({ source_schema: 'public', source_table: 'contact' }); - expect(entryToChannel(entry)).toBe('realtime:public.contact'); + expect(entryToChannel(entry)).toBe('realtime:9db2575819580f0b822621ba62a1976e'); }); it('handles custom schema names', () => { const entry = makeEntry({ source_schema: 'tenant_42', source_table: 'invoice' }); - expect(entryToChannel(entry)).toBe('realtime:tenant_42.invoice'); + expect(entryToChannel(entry)).toBe('realtime:6b8caecbaac87c42d4553ef6ea8709fb'); }); }); @@ -190,11 +190,39 @@ describe('RealtimeManager', () => { await manager.stop(); // should be no-op }); + it('retries pending tracker cleanup after a failed shutdown', async () => { + const manager = createManager(); + await manager.start(); + const query = mockPool.query.getMockImplementation()!; + mockPool.query.mockImplementation((sql, values) => sql.includes('cleanup_ephemeral') ? Promise.reject(new Error('cleanup failed')) : query(sql, values)); + await expect(manager.stop()).rejects.toThrow('cleanup failed'); + expect(manager.isRunning).toBe(false); + mockPool.query.mockImplementation(query).mockClear(); + await manager.stop(); + expect(mockPool.query).toHaveBeenLastCalledWith(expect.stringContaining('cleanup_ephemeral'), [manager.nodeId]); + mockPool.query.mockClear(); + await manager.stop(); + expect(mockPool.query).not.toHaveBeenCalled(); + }); + + it('retries pending cleanup after startup and its cleanup both fail', async () => { + const manager = createManager(); + mockPool.query.mockImplementation(async sql => { + if (sql.includes('drain_changes') || sql.includes('cleanup_ephemeral')) throw new Error('startup or cleanup failed'); + return { rows: [] }; + }); + await expect(manager.start()).rejects.toBeInstanceOf(AggregateError); + expect(manager.isRunning).toBe(false); + mockPool.query.mockResolvedValue({ rows: [] }).mockClear(); + await manager.stop(); + expect(mockPool.query).toHaveBeenLastCalledWith(expect.stringContaining('cleanup_ephemeral'), [manager.nodeId]); + }); + describe('event dispatching', () => { it('emits cursor-tracked events on PgSubscriber eventEmitter', async () => { const emitted: { channel: string; payload: string }[] = []; - mockSubscriber.eventEmitter.on('realtime:public.contact', (payload: string) => { - emitted.push({ channel: 'realtime:public.contact', payload }); + mockSubscriber.eventEmitter.on('realtime:9db2575819580f0b822621ba62a1976e', (payload: string) => { + emitted.push({ channel: 'realtime:9db2575819580f0b822621ba62a1976e', payload }); }); // Mock drain_changes to return entries @@ -203,10 +231,15 @@ describe('RealtimeManager', () => { makeEntry({ operation: 'UPDATE', payload_after: { id: 'row-b' } }), ]; - mockPool.query.mockImplementation(async (sql: string) => { - if (typeof sql === 'string' && sql.includes('drain_changes')) { - return { rows: entries.map((e) => ({ drain_changes: e })) }; - } + mockPool.query.mockImplementation(async (sql: string, values?: unknown[]) => { + if (sql.includes('drain_changes')) return { rows: entries.map(entry => ({ drain_changes: entry })) }; + if (sql.includes('runtime_sources')) return { rows: entries + .filter((entry, i) => entries.findIndex(other => other.source_schema === entry.source_schema && other.source_table === entry.source_table) === i) + .map(entry => ({ runtime_sources: { + source_schema: entry.source_schema, source_table: entry.source_table, + fanout_function: 'source_fanout', cleanup_function: 'source_cleanup', + } })) }; + if (sql.includes('source_fanout')) return { rows: JSON.parse(values![1] as string).map((entry: ChangeLogEntry) => ({ entry })) }; return { rows: [] }; }); @@ -223,7 +256,7 @@ describe('RealtimeManager', () => { it('handles DELETE events with payload_before', async () => { const emitted: string[] = []; - mockSubscriber.eventEmitter.on('realtime:public.contact', (payload: string) => { + mockSubscriber.eventEmitter.on('realtime:9db2575819580f0b822621ba62a1976e', (payload: string) => { emitted.push(payload); }); @@ -235,10 +268,15 @@ describe('RealtimeManager', () => { }), ]; - mockPool.query.mockImplementation(async (sql: string) => { - if (typeof sql === 'string' && sql.includes('drain_changes')) { - return { rows: entries.map((e) => ({ drain_changes: e })) }; - } + mockPool.query.mockImplementation(async (sql: string, values?: unknown[]) => { + if (sql.includes('drain_changes')) return { rows: entries.map(entry => ({ drain_changes: entry })) }; + if (sql.includes('runtime_sources')) return { rows: entries + .filter((entry, i) => entries.findIndex(other => other.source_schema === entry.source_schema && other.source_table === entry.source_table) === i) + .map(entry => ({ runtime_sources: { + source_schema: entry.source_schema, source_table: entry.source_table, + fanout_function: 'source_fanout', cleanup_function: 'source_cleanup', + } })) }; + if (sql.includes('source_fanout')) return { rows: JSON.parse(values![1] as string).map((entry: ChangeLogEntry) => ({ entry })) }; return { rows: [] }; }); @@ -254,8 +292,8 @@ describe('RealtimeManager', () => { it('dispatches to correct channels for different tables', async () => { const contactEvents: string[] = []; const invoiceEvents: string[] = []; - mockSubscriber.eventEmitter.on('realtime:public.contact', (p: string) => contactEvents.push(p)); - mockSubscriber.eventEmitter.on('realtime:billing.invoice', (p: string) => invoiceEvents.push(p)); + mockSubscriber.eventEmitter.on('realtime:9db2575819580f0b822621ba62a1976e', (p: string) => contactEvents.push(p)); + mockSubscriber.eventEmitter.on('realtime:2e0654a46337baffc614fed360153337', (p: string) => invoiceEvents.push(p)); const entries: ChangeLogEntry[] = [ makeEntry({ @@ -272,10 +310,15 @@ describe('RealtimeManager', () => { }), ]; - mockPool.query.mockImplementation(async (sql: string) => { - if (typeof sql === 'string' && sql.includes('drain_changes')) { - return { rows: entries.map((e) => ({ drain_changes: e })) }; - } + mockPool.query.mockImplementation(async (sql: string, values?: unknown[]) => { + if (sql.includes('drain_changes')) return { rows: entries.map(entry => ({ drain_changes: entry })) }; + if (sql.includes('runtime_sources')) return { rows: entries + .filter((entry, i) => entries.findIndex(other => other.source_schema === entry.source_schema && other.source_table === entry.source_table) === i) + .map(entry => ({ runtime_sources: { + source_schema: entry.source_schema, source_table: entry.source_table, + fanout_function: 'source_fanout', cleanup_function: 'source_cleanup', + } })) }; + if (sql.includes('source_fanout')) return { rows: JSON.parse(values![1] as string).map((entry: ChangeLogEntry) => ({ entry })) }; return { rows: [] }; }); @@ -290,7 +333,7 @@ describe('RealtimeManager', () => { }); describe('error handling', () => { - it('calls onError when drain fails', async () => { + it('propagates an initial drain failure and resets its started state', async () => { const errors: Error[] = []; mockPool.query.mockImplementation(async (sql: string) => { @@ -301,10 +344,14 @@ describe('RealtimeManager', () => { }); const manager = createManager({ onError: (err: Error) => errors.push(err) }); - await manager.start(); + await expect(manager.start()).rejects.toThrow('drain failed'); + expect(manager.isRunning).toBe(false); + expect(errors).toEqual([]); + expect(jest.getTimerCount()).toBe(0); - expect(errors).toHaveLength(1); - expect(errors[0].message).toBe('drain failed'); + mockPool.query.mockResolvedValue({ rows: [] }); + await manager.start(); + expect(manager.isRunning).toBe(true); await manager.stop(); }); @@ -314,10 +361,15 @@ describe('RealtimeManager', () => { makeEntry({ operation: 'INSERT', payload_after: { id: 'row-x' } }), ]; - mockPool.query.mockImplementation(async (sql: string) => { - if (typeof sql === 'string' && sql.includes('drain_changes')) { - return { rows: entries.map((e) => ({ drain_changes: e })) }; - } + mockPool.query.mockImplementation(async (sql: string, values?: unknown[]) => { + if (sql.includes('drain_changes')) return { rows: entries.map(entry => ({ drain_changes: entry })) }; + if (sql.includes('runtime_sources')) return { rows: entries + .filter((entry, i) => entries.findIndex(other => other.source_schema === entry.source_schema && other.source_table === entry.source_table) === i) + .map(entry => ({ runtime_sources: { + source_schema: entry.source_schema, source_table: entry.source_table, + fanout_function: 'source_fanout', cleanup_function: 'source_cleanup', + } })) }; + if (sql.includes('source_fanout')) return { rows: JSON.parse(values![1] as string).map((entry: ChangeLogEntry) => ({ entry })) }; return { rows: [] }; }); diff --git a/graphile/graphile-realtime-subscriptions/package.json b/graphile/graphile-realtime-subscriptions/package.json index 3f38936e09..8ec5778c61 100644 --- a/graphile/graphile-realtime-subscriptions/package.json +++ b/graphile/graphile-realtime-subscriptions/package.json @@ -44,7 +44,7 @@ "@pgsql/quotes": "^18.2.4" }, "peerDependencies": { - "grafast": "^1.1.1", + "grafast": "^1.1.2", "graphile-build": "^5.1.1", "graphile-build-pg": "^5.1.3", "graphile-config": "^1.1.0", diff --git a/graphile/graphile-realtime-subscriptions/src/async-iterator.ts b/graphile/graphile-realtime-subscriptions/src/async-iterator.ts new file mode 100644 index 0000000000..46ae86a47e --- /dev/null +++ b/graphile/graphile-realtime-subscriptions/src/async-iterator.ts @@ -0,0 +1,48 @@ +export function filterMapIterator(source: AsyncIterable, transform: (value: T) => U | null): AsyncGenerator { + return flatMapIterator(source, value => { + const result = transform(value); + return result === null ? [] : [result]; + }); +} + +export function flatMapIterator(source: AsyncIterable, transform: (value: T) => readonly U[]): AsyncGenerator { + const iterator = source[Symbol.asyncIterator](); + let closed = false; + let pending: readonly U[] = []; + let index = 0; + return { + [Symbol.asyncIterator]() { return this; }, + async [Symbol.asyncDispose]() { await this.return(); }, + async next() { + try { + while (!closed) { + if (index < pending.length) return { done: false, value: pending[index++] }; + const result = await iterator.next(); + if (closed || result.done) break; + pending = transform(result.value); + index = 0; + } + closed = true; + return { done: true, value: undefined }; + } catch (error) { + closed = true; + await iterator.return?.(); + throw error; + } + }, + async return() { + if (!closed) { + closed = true; + await iterator.return?.(); + } + return { done: true, value: undefined }; + }, + async throw(error: unknown) { + if (!closed) { + closed = true; + await iterator.return?.(); + } + throw error; + } + }; +} diff --git a/graphile/graphile-realtime-subscriptions/src/channel.ts b/graphile/graphile-realtime-subscriptions/src/channel.ts new file mode 100644 index 0000000000..dbed375eba --- /dev/null +++ b/graphile/graphile-realtime-subscriptions/src/channel.ts @@ -0,0 +1,6 @@ +import { createHash } from 'crypto'; + +export function realtimeChannel(schema: string, table: string): string { + const key = `${Buffer.byteLength(schema, 'utf8')}:${schema}${table}`; + return `realtime:${createHash('md5').update(key, 'utf8').digest('hex')}`; +} diff --git a/graphile/graphile-realtime-subscriptions/src/cursor-tracker.ts b/graphile/graphile-realtime-subscriptions/src/cursor-tracker.ts index ab1f1204b9..e81396d9d6 100644 --- a/graphile/graphile-realtime-subscriptions/src/cursor-tracker.ts +++ b/graphile/graphile-realtime-subscriptions/src/cursor-tracker.ts @@ -28,7 +28,14 @@ const log = new Logger('cursor-tracker'); const DEFAULT_POLL_INTERVAL_MS = 5000; const DEFAULT_HEARTBEAT_INTERVAL_MS = 30000; const DEFAULT_BATCH_LIMIT = 500; -const DEFAULT_SCHEMA = 'realtime_public'; +const DEFAULT_SCHEMA = 'realtime_private'; + +interface RuntimeSource { + source_schema: string; + source_table: string; + fanout_function: string; + cleanup_function: string; +} export class CursorTracker { readonly nodeId: string; @@ -44,6 +51,7 @@ export class CursorTracker { private pollTimer: ReturnType | null = null; private heartbeatTimer: ReturnType | null = null; private running = false; + private cleanupPending = false; private draining = false; constructor(options: CursorTrackerOptions) { @@ -65,22 +73,36 @@ export class CursorTracker { log.info(`Starting cursor tracker: node=${this.nodeId}, schema=${this.schema}`); - await this.touchListener(); - - // Initial drain immediately after registration - await this.drain(); + let registered = false; + try { + if (this.cleanupPending) await this.cleanupEphemeral(); + await this.touchListener(); + registered = true; + this.cleanupPending = true; + await this.drain(); + } catch (error) { + this.running = false; + if (registered) { + try { + await this.cleanupEphemeral(); + } catch (cleanupError) { + throw new AggregateError([error, cleanupError], `Cursor startup and cleanup failed for node=${this.nodeId}`); + } + } + throw error; + } this.pollTimer = setInterval(() => { - void this.drain(); + void this.drain().catch(this.onError); }, this.pollIntervalMs); this.heartbeatTimer = setInterval(() => { - void this.touchListener(); + void this.touchListener().catch(this.onError); }, this.heartbeatIntervalMs); } async stop(): Promise { - if (!this.running) return; + if (!this.running && !this.cleanupPending) return; this.running = false; log.info(`Stopping cursor tracker: node=${this.nodeId}`); @@ -104,21 +126,35 @@ export class CursorTracker { try { const sql = `SELECT * FROM ${this.quoteIdent(this.schema)}.drain_changes($1, $2)`; - const result = await this.pool.query<{ drain_changes: ChangeLogEntry }>( + const result = await this.pool.query<{ drain_changes: Omit }>( sql, [this.nodeId, this.batchLimit], ); - const entries = result.rows.map((row) => row.drain_changes); - - if (entries.length > 0) { - log.info(`Drained ${entries.length} change(s) for node=${this.nodeId}`); - this.onChanges(entries); + const pending = result.rows.map((row) => row.drain_changes); + const entries: ChangeLogEntry[] = []; + if (pending.length > 0) { + for (const source of await this.runtimeSources()) { + const changes = pending.filter(change => change.source_schema === source.source_schema && change.source_table === source.source_table); + if (changes.length === 0) continue; + const fanout = await this.pool.query<{ entry: ChangeLogEntry }>( + `SELECT ${this.quoteIdent(this.schema)}.${this.quoteIdent(source.fanout_function)}($1, $2) AS entry`, + [this.nodeId, JSON.stringify(changes)], + ); + entries.push(...fanout.rows.map(row => row.entry)); + } + if (entries.length > 0) { + log.info(`Drained ${entries.length} change(s) for node=${this.nodeId}`); + await this.onChanges(entries); + } + await this.pool.query( + `SELECT ${this.quoteIdent(this.schema)}.advance_cursor($1, $2)`, + [this.nodeId, pending[pending.length - 1].occurred_at], + ); } return entries; } catch (err) { - this.onError(err instanceof Error ? err : new Error(String(err))); - return []; + throw err instanceof Error ? err : new Error(String(err)); } finally { this.draining = false; } @@ -129,20 +165,34 @@ export class CursorTracker { const sql = `SELECT ${this.quoteIdent(this.schema)}.touch_listener($1)`; await this.pool.query(sql, [this.nodeId]); } catch (err) { - this.onError(err instanceof Error ? err : new Error(String(err))); + throw err instanceof Error ? err : new Error(String(err)); } } async cleanupEphemeral(): Promise { try { + for (const source of await this.runtimeSources()) { + await this.pool.query( + `SELECT ${this.quoteIdent(this.schema)}.${this.quoteIdent(source.cleanup_function)}($1)`, + [this.nodeId], + ); + } const sql = `SELECT ${this.quoteIdent(this.schema)}.cleanup_ephemeral($1)`; await this.pool.query(sql, [this.nodeId]); + this.cleanupPending = false; log.info(`Cleaned up ephemeral subscriptions for node=${this.nodeId}`); } catch (err) { - this.onError(err instanceof Error ? err : new Error(String(err))); + throw err instanceof Error ? err : new Error(String(err)); } } + private async runtimeSources(): Promise { + const result = await this.pool.query<{ runtime_sources: RuntimeSource }>( + `SELECT * FROM ${this.quoteIdent(this.schema)}.runtime_sources()`, + ); + return result.rows.map(row => row.runtime_sources); + } + get isRunning(): boolean { return this.running; } diff --git a/graphile/graphile-realtime-subscriptions/src/delivery.ts b/graphile/graphile-realtime-subscriptions/src/delivery.ts new file mode 100644 index 0000000000..78a153b2e3 --- /dev/null +++ b/graphile/graphile-realtime-subscriptions/src/delivery.ts @@ -0,0 +1,19 @@ +import { EventThrottle, type ParsedPayload } from './event-gate'; +import { SubscriptionVisibility } from './visibility'; + +export class SubscriptionDelivery { + private readonly visibility = new SubscriptionVisibility(); + private readonly throttle: EventThrottle; + + constructor(threshold: number) { + this.throttle = new EventThrottle(threshold); + } + + project(payload: ParsedPayload, rowVisible: boolean): ParsedPayload | null { + if (!this.visibility.allow(payload, rowVisible)) return null; + const action = this.throttle.check(); + if (action === 'drop') return null; + if (action === 'overflow') return { event: payload.event, rowIds: [], overflow: true }; + return payload; + } +} diff --git a/graphile/graphile-realtime-subscriptions/src/event-gate.ts b/graphile/graphile-realtime-subscriptions/src/event-gate.ts index b1747173a5..9a1080b36a 100644 --- a/graphile/graphile-realtime-subscriptions/src/event-gate.ts +++ b/graphile/graphile-realtime-subscriptions/src/event-gate.ts @@ -1,22 +1,16 @@ /** * The gate between PostgreSQL's NOTIFY stream and a GraphQL subscription. * - * Everything that can decide "this event should not reach the client" lives - * here, upstream of grafast, because grafast's `listen` maps each event to a - * step and offers no way to suppress one. Deciding downstream forced the - * plugin to represent "dropped" as a null payload, which the field resolvers - * then had to coalesce (`p?.event ?? 'UNKNOWN'`) — so a filtered event still - * reached the client, carrying an invented event name. Filtering here means - * the stream only ever yields events that should exist, and every resolver - * downstream is total. - * - * The gate also owns parsing and the overflow throttle, so a payload the - * trigger and the plugin disagree about fails loudly instead of arriving as + * Parsing and ID filtering happen before Grafast plans each event. + * The plugin authorizes each row before applying its visible-row throttle. + * A payload the trigger and the plugin disagree about fails loudly instead of arriving as * an `UNKNOWN`-shaped record. */ import type { GrafastSubscriber } from 'grafast'; +import { flatMapIterator } from './async-iterator'; + /** Operations `emit_change` is allowed to report. */ const KNOWN_OPERATIONS = new Set(['INSERT', 'UPDATE', 'DELETE']); @@ -24,8 +18,8 @@ export interface ParsedPayload { event: string; /** * Row ids being reported. Already narrowed to the subscription's `ids` when - * it supplied any, so no consumer needs to re-intersect. Empty for - * INVALIDATE. + * it supplied any, so no consumer needs to re-intersect. Empty only for + * an authorized overflow produced after row lookup. */ rowIds: string[]; overflow: boolean; @@ -34,8 +28,8 @@ export interface ParsedPayload { export class MalformedNotifyPayloadError extends Error { constructor(raw: string, reason: string) { super( - `Malformed realtime NOTIFY payload ${JSON.stringify(raw)}: ${reason}. ` + - 'Expected "INVALIDATE" or ":[,...]" ' + + `Malformed realtime NOTIFY payload ${JSON.stringify(raw.startsWith('{') ? '[ephemeral rows]' : raw)}: ${reason}. ` + + 'Expected ":[,...]" or ephemeral row JSON ' + 'as emitted by the emit_change trigger.' ); this.name = 'MalformedNotifyPayloadError'; @@ -44,15 +38,22 @@ export class MalformedNotifyPayloadError extends Error { /** * Parse the NOTIFY payload from `emit_change`. - * Format: `"TG_OP:id1,id2,..."` or `"INVALIDATE"`. + * Format: `"TG_OP:id1,id2,..."` or ephemeral `{"op":"TG_OP","rows":[{"id":"uuid"}]}`. * * Throws on anything else: a payload this cannot read means the trigger and * this plugin have diverged, and inventing an event name for it hides a * deployment fault behind data the client will act on. */ export function parseNotifyPayload(raw: string): ParsedPayload { - if (raw === 'INVALIDATE') { - return { event: 'INVALIDATE', rowIds: [], overflow: true }; + if (raw.startsWith('{')) { + let value: any; + try { value = JSON.parse(raw); } + catch { throw new MalformedNotifyPayloadError(raw, 'invalid ephemeral JSON'); } + if (!KNOWN_OPERATIONS.has(value?.op) || !Array.isArray(value.rows) || value.rows.length === 0 || + value.rows.some((row: any) => !row || typeof row.id !== 'string' || row.id.length === 0)) { + throw new MalformedNotifyPayloadError(raw, 'ephemeral payload requires an operation and row ids'); + } + return { event: value.op, rowIds: value.rows.map((row: { id: string }) => row.id), overflow: false }; } const colonIdx = raw.indexOf(':'); @@ -67,7 +68,7 @@ export function parseNotifyPayload(raw: string): ParsedPayload { const idsPart = raw.substring(colonIdx + 1); const rowIds = idsPart.length > 0 ? idsPart.split(',') : []; - if (rowIds.length === 0) { + if (rowIds.length === 0 || rowIds.some(id => id.length === 0)) { throw new MalformedNotifyPayloadError(raw, `${event} carries no row ids`); } @@ -117,29 +118,16 @@ export class EventThrottle { export interface EventGateOptions { /** Sparse-set subscription: deliver only events touching these row ids. */ ids?: readonly string[] | null; - /** Events per second before the gate collapses the stream to one INVALIDATE. */ - threshold: number; } /** * Apply the gate to one raw NOTIFY payload. * - * Returns the payload to deliver, or `null` meaning *do not emit* — a decision - * only this layer is allowed to make, because only this layer can act on it. + * Returns the payload to authorize, or `null` meaning *do not emit*. */ -function gate(raw: string, ids: readonly string[] | null, throttle: EventThrottle): ParsedPayload | null { +function gate(raw: string, ids: readonly string[] | null): ParsedPayload | null { const parsed = parseNotifyPayload(raw); - // An INVALIDATE is the overflow signal itself; throttling it would drop the - // one event telling the client to refetch. - if (parsed.overflow) return parsed; - - const action = throttle.check(); - if (action === 'drop') return null; - if (action === 'overflow') { - return { event: 'INVALIDATE', rowIds: [], overflow: true }; - } - if (!ids || ids.length === 0) return parsed; const matched = parsed.rowIds.filter(rowId => ids.includes(rowId)); @@ -151,24 +139,23 @@ function gate(raw: string, ids: readonly string[] | null, throttle: EventThrottl /** * Wrap a `GrafastSubscriber` so its stream yields parsed, gated payloads. * - * Built per subscription (the throttle and `ids` are per-subscriber state), so - * one noisy client can no longer throttle every other subscriber to the same - * table — which a single build-time throttle instance did. + * Built per subscription so each sparse ID set is independent. Row visibility + * and rate accounting are applied by the event plan, after its scoped lookup. */ export function createGatedSubscriber( inner: GrafastSubscriber>, - { ids, threshold }: EventGateOptions + { ids }: EventGateOptions ): GrafastSubscriber> { const subscribedIds = ids && ids.length > 0 ? ids : null; - const throttle = new EventThrottle(threshold); return { - async *subscribe(topic: string) { + async subscribe(topic: string) { const source = await inner.subscribe(topic); - for await (const raw of source) { - const payload = gate(String(raw), subscribedIds, throttle); - if (payload !== null) yield payload; - } + return flatMapIterator(source, raw => { + const payload = gate(String(raw), subscribedIds); + if (!payload) return []; + return payload.rowIds.map(id => ({ ...payload, rowIds: [id] })); + }); } // Deliberately no release(): `inner` is the shared pgSubscriber from the // request context and is not ours to tear down. Ending iteration returns diff --git a/graphile/graphile-realtime-subscriptions/src/index.ts b/graphile/graphile-realtime-subscriptions/src/index.ts index d0fdf741ca..374da94f35 100644 --- a/graphile/graphile-realtime-subscriptions/src/index.ts +++ b/graphile/graphile-realtime-subscriptions/src/index.ts @@ -17,6 +17,7 @@ * ``` */ +export { realtimeChannel } from './channel'; export { CursorTracker } from './cursor-tracker'; export { createRealtimeSubscriptionsPlugin, RealtimeSubscriptionsPlugin } from './plugin'; export { RealtimeSubscriptionsPreset } from './preset'; diff --git a/graphile/graphile-realtime-subscriptions/src/plugin.ts b/graphile/graphile-realtime-subscriptions/src/plugin.ts index a013d778b4..5066c836c3 100644 --- a/graphile/graphile-realtime-subscriptions/src/plugin.ts +++ b/graphile/graphile-realtime-subscriptions/src/plugin.ts @@ -11,15 +11,14 @@ * * NOTIFY payload format (from emit_change trigger): * - Normal: "INSERT:uuid1,uuid2,..." or "UPDATE:uuid1" or "DELETE:uuid1" - * - Overflow: "INVALIDATE" (when a single statement affects > 50 rows) + * - Ephemeral small batches: JSON with op and rows (only their IDs are used) * * Event flow: * 1. A row is inserted/updated/deleted - * 2. The emit_change trigger fires pg_notify with TG_OP:row_ids or INVALIDATE + * 2. The emit_change trigger fires byte-bounded pg_notify payloads * 3. PostGraphile's pgSubscriber receives the NOTIFY - * 4. The gate (see event-gate.ts) parses, throttles and filters it — a - * payload this subscription should not see never becomes an event - * 5. The plugin fetches the changed row(s) + * 4. The gate (see event-gate.ts) parses, filters IDs and splits each row + * 5. The plugin authorizes the row before counting it against the throttle * 6. The client receives { event, row, rowId, overflow } * * Cursor tracking (at-least-once delivery): @@ -32,29 +31,29 @@ * This enables at-least-once semantics by tracking cursor position. * * Overflow protection: - * - Database-side: statements affecting > 50 rows send INVALIDATE - * - Plugin-side: per-subscription throttle (default 50 events/second/table) - * drops individual events and sends a single INVALIDATE when exceeded + * - Database-side: large statements send byte-bounded ID chunks + * - Plugin-side: per-subscription throttle (default 50 visible rows/second) + * sends one id-less overflow frame when exceeded * * Security / RLS enforcement: * - Row data is always fetched via resource.get() which runs through the * authenticated user's connection with their JWT role and pgSettings applied. - * - For INSERT/UPDATE events, if RLS denies access (resource.get returns null), - * the rowId is masked (set to null) to prevent metadata leaks. - * - For DELETE events, row is naturally null (the row no longer exists). - * - For INVALIDATE (overflow), the client should refetch via a normal query - * which is also RLS-gated. - * - When ids are provided, only events for those specific rows are delivered, - * preventing cross-tenant event leaks. + * - Invisible INSERT/UPDATE events are inhibited and removed from the stream. + * - DELETE is delivered only for IDs this subscription previously saw as visible. + * - Invisible rows cannot consume the throttle budget or cause overflow. */ import { Logger } from '@pgpmjs/logger'; -import { constant, context as grafastContext, lambda,listen, object } from 'grafast'; +import { constant, context as grafastContext, inhibitIf, lambda, listen, object, sideEffect } from 'grafast'; import type { GraphileConfig } from 'graphile-config'; import { extendSchema } from 'graphile-utils'; +import type { GraphQLSchema } from 'graphql'; +import { realtimeChannel } from './channel'; +import { SubscriptionDelivery } from './delivery'; import type { ParsedPayload } from './event-gate'; import { createGatedSubscriber } from './event-gate'; +import { filterInaccessibleEvents, realtimeResponseNames } from './subscription-filter'; import type { RealtimeSubscriptionsPluginOptions } from './types'; const log = new Logger('graphile-realtime-subscriptions'); @@ -93,7 +92,7 @@ function discoverRealtimeTables(build: any): RealtimeTableInfo[] { const pgSchema = codec.extensions?.pg?.schemaName ?? 'public'; const pgTable = codec.extensions?.pg?.name ?? codec.name; - const notifyChannel = `realtime:${pgSchema}.${pgTable}`; + const notifyChannel = realtimeChannel(pgSchema, pgTable); result.push({ resource: r, @@ -123,11 +122,11 @@ function buildTypeDefs(tables: RealtimeTableInfo[]): string { .map(({ payloadTypeName, typeName, rowFieldName }) => `"""Payload delivered when a ${typeName} row changes."""\n` + `type ${payloadTypeName} {\n` + - ` """The DML operation: INSERT, UPDATE, DELETE, or INVALIDATE."""\n` + + ` """The DML operation: INSERT, UPDATE, or DELETE, including the visible change that caused overflow."""\n` + ` event: String!\n` + - ` """The current state of the row (null for DELETE, INVALIDATE, or if RLS denies access)."""\n` + + ` """The current state of the authorized row (null for DELETE or overflow)."""\n` + ` ${rowFieldName}: ${typeName}\n` + - ` """The ID of the changed row (null for INVALIDATE, or masked when RLS denies access)."""\n` + + ` """The ID of a change visible to this subscription."""\n` + ` rowId: UUID\n` + ` """True when too many changes occurred and the client should refetch."""\n` + ` overflow: Boolean!\n` + @@ -154,7 +153,7 @@ function requirePayload(payload: unknown): ParsedPayload { /** * The row this event reports. `rowIds` is already narrowed to the - * subscription's `ids`, so the first entry is the one to surface; INVALIDATE + * subscription's `ids`, so the first entry is the one to surface; overflow * carries none, which is a genuine absence rather than a suppressed error. */ function reportedRowId(payload: ParsedPayload): string | null { @@ -175,19 +174,26 @@ function buildPlans( const $pgSubscriber = (grafastContext() as any).get('pgSubscriber'); const $topic = constant(notifyChannel); const $ids = args.getRaw('ids'); + const $visibility = lambda([$pgSubscriber, $ids], () => new SubscriptionDelivery(overflowThreshold)); - // Parsing, throttling and sparse-set filtering all happen in the gate, - // built once per subscription, so the stream below yields only events - // that should reach this client — every step after it is total. const $subscriber = lambda([$pgSubscriber, $ids], (pair: unknown) => { const [pgSubscriber, ids] = pair as readonly [any, string[] | null | undefined]; - return createGatedSubscriber(pgSubscriber, { ids, threshold: overflowThreshold }); + return createGatedSubscriber(pgSubscriber, { ids }); }); - return listen($subscriber, $topic, ($payload: any) => object({ parsed: $payload })); + return listen($subscriber, $topic, ($payload: any) => object({ parsed: $payload, visibility: $visibility })); }, plan($event: any) { - return $event; + const $parsed = $event.get('parsed'); + const $rowId = lambda($parsed, (p: unknown) => reportedRowId(requirePayload(p))); + const $row = resource.get({ id: $rowId }); + const $projected = sideEffect([$parsed, $row, $event.get('visibility')], ([payload, row, delivery]: any) => + delivery.project(requirePayload(payload), row != null)); + const $hidden = lambda($projected, (payload: unknown) => payload == null); + const $reportedRowId = lambda($projected, (payload: ParsedPayload | null) => + payload && !payload.overflow ? reportedRowId(payload) : null); + const $reportedRow = resource.get({ id: $reportedRowId }); + return object({ parsed: inhibitIf($projected, $hidden), row: $reportedRow }); }, }; @@ -202,11 +208,7 @@ function buildPlans( return lambda($parent.get('parsed'), (p: unknown) => requirePayload(p).overflow); }, [rowFieldName]($parent: any) { - const $rowId = lambda($parent.get('parsed'), (p: unknown) => - reportedRowId(requirePayload(p)), - ); - - return resource.get({ id: $rowId }); + return $parent.get('row'); }, }; } @@ -219,14 +221,15 @@ export function createRealtimeSubscriptionsPlugin( options: RealtimeSubscriptionsPluginOptions = {}, ): GraphileConfig.Plugin { const overflowThreshold = options.overflowThreshold ?? DEFAULT_OVERFLOW_THRESHOLD; + const fieldsBySchema = new WeakMap>(); - return extendSchema( + const plugin = extendSchema( (build) => { const tables = discoverRealtimeTables(build); if (tables.length === 0) { log.info('No tables with @realtime tag found — skipping subscription generation'); - return { typeDefs: '', plans: {} }; + return { typeDefs: [], plans: {} }; } log.info(`Generating subscription fields for ${tables.length} realtime table(s)`); @@ -239,6 +242,23 @@ export function createRealtimeSubscriptionsPlugin( }, 'RealtimeSubscriptionsPlugin', ); + plugin.schema!.hooks!.finalize = (schema, build) => { + fieldsBySchema.set(schema, new Set(discoverRealtimeTables(build).map(table => table.fieldName))); + return schema; + }; + plugin.grafast = { + middleware: { + async subscribe(next, { args }) { + const result = await next(); + const fields = fieldsBySchema.get(args.schema); + if (!fields) throw new Error('Realtime authorization metadata is missing for this schema.'); + if (!fields.size || !(Symbol.asyncIterator in result)) return result; + const names = realtimeResponseNames(args.document, args.operationName, fields, args.variableValues); + return names.length ? filterInaccessibleEvents(result, names) : result; + } + } + }; + return plugin; } export { createRealtimeSubscriptionsPlugin as RealtimeSubscriptionsPlugin }; diff --git a/graphile/graphile-realtime-subscriptions/src/realtime-manager.ts b/graphile/graphile-realtime-subscriptions/src/realtime-manager.ts index 58bcf11926..18c36bffe4 100644 --- a/graphile/graphile-realtime-subscriptions/src/realtime-manager.ts +++ b/graphile/graphile-realtime-subscriptions/src/realtime-manager.ts @@ -25,6 +25,7 @@ import { Logger } from '@pgpmjs/logger'; +import { realtimeChannel } from './channel'; import { CursorTracker } from './cursor-tracker'; import type { ChangeLogEntry, @@ -61,10 +62,10 @@ function entryToNotifyPayload(entry: ChangeLogEntry): string { /** * Build the NOTIFY channel name for a change_log entry. - * Matches the channel format used by emit_change: "realtime:{schema}.{table}" + * Matches the bounded channel used by emit_change and subscription plans. */ function entryToChannel(entry: ChangeLogEntry): string { - return `realtime:${entry.source_schema}.${entry.source_table}`; + return realtimeChannel(entry.source_schema, entry.source_table); } export class RealtimeManager { @@ -103,11 +104,15 @@ export class RealtimeManager { this.started = true; log.info(`Starting RealtimeManager: node=${this.nodeId}`); - await this.cursorTracker.start(); + try { + await this.cursorTracker.start(); + } catch (error) { + this.started = false; + throw error; + } } async stop(): Promise { - if (!this.started) return; this.started = false; log.info(`Stopping RealtimeManager: node=${this.nodeId}`); diff --git a/graphile/graphile-realtime-subscriptions/src/subscription-filter.ts b/graphile/graphile-realtime-subscriptions/src/subscription-filter.ts new file mode 100644 index 0000000000..9d0989eba2 --- /dev/null +++ b/graphile/graphile-realtime-subscriptions/src/subscription-filter.ts @@ -0,0 +1,42 @@ +import { type DocumentNode, getDirectiveValues, getOperationAST, GraphQLIncludeDirective, GraphQLSkipDirective, Kind, type SelectionSetNode, valueFromASTUntyped } from 'graphql'; + +import { filterMapIterator } from './async-iterator'; + +export function realtimeResponseNames(document: DocumentNode, operationName: string | null | undefined, fields: ReadonlySet, variableValues: Record = {}): string[] { + const operation = getOperationAST(document, operationName); + if (operation?.operation !== 'subscription') return []; + const variables = Object.fromEntries((operation.variableDefinitions ?? []) + .filter(definition => definition.defaultValue) + .map(definition => [definition.variable.name.value, valueFromASTUntyped(definition.defaultValue!)])); + Object.assign(variables, variableValues); + const names = new Set(); + const visited = new Set(); + function visit(selectionSet: SelectionSetNode) { + for (const selection of selectionSet.selections) { + if (getDirectiveValues(GraphQLSkipDirective, selection, variables)?.if === true || + getDirectiveValues(GraphQLIncludeDirective, selection, variables)?.if === false) continue; + if (selection.kind === Kind.FIELD) { + if (fields.has(selection.name.value)) names.add(selection.alias?.value ?? selection.name.value); + } else if (selection.kind === Kind.INLINE_FRAGMENT) { + visit(selection.selectionSet); + } else if (!visited.has(selection.name.value)) { + visited.add(selection.name.value); + const fragment = document.definitions.find(definition => + definition.kind === Kind.FRAGMENT_DEFINITION && definition.name.value === selection.name.value); + if (fragment?.kind === Kind.FRAGMENT_DEFINITION) visit(fragment.selectionSet); + } + } + } + visit(operation.selectionSet); + return [...names]; +} + +export function filterInaccessibleEvents(source: AsyncIterable, names: readonly string[]): AsyncGenerator { + return filterMapIterator(source, result => { + const { data, errors } = result; + if ('path' in result) return result; + const root = typeof data === 'string' ? JSON.parse(data) : data; + return !errors?.length && root && typeof root === 'object' && names.length > 0 && + names.every(name => (root as Record)[name] === null) ? null : result; + }); +} diff --git a/graphile/graphile-realtime-subscriptions/src/types.ts b/graphile/graphile-realtime-subscriptions/src/types.ts index bbf220ba4d..ac4e059f34 100644 --- a/graphile/graphile-realtime-subscriptions/src/types.ts +++ b/graphile/graphile-realtime-subscriptions/src/types.ts @@ -3,10 +3,9 @@ */ export interface RealtimeSubscriptionsPluginOptions { /** - * Maximum number of events per table per second before switching to - * overflow (INVALIDATE) mode. When exceeded, the subscription sends - * a single { event: 'INVALIDATE', overflow: true } instead of - * individual row events, signaling the client to refetch. + * Maximum number of authorized row events per subscription per second. + * When exceeded, sends one overflow frame without a row or row ID, + * preserving the triggering operation and signaling the client to refetch. * * Default: 50 */ @@ -56,10 +55,10 @@ export interface CursorTrackerOptions { nodeId?: string; /** - * The realtime_public schema name where drain_changes(), + * The private realtime schema name where drain_changes(), * touch_listener(), and cleanup_ephemeral() live. * - * Default: 'realtime_public' + * Default: 'realtime_private' */ schema?: string; @@ -131,10 +130,10 @@ export interface RealtimeManagerOptions { nodeId?: string; /** - * The realtime_public schema name where drain_changes(), + * The private realtime schema name where drain_changes(), * touch_listener(), and cleanup_ephemeral() live. * - * Default: 'realtime_public' + * Default: 'realtime_private' */ schema?: string; diff --git a/graphile/graphile-realtime-subscriptions/src/visibility.ts b/graphile/graphile-realtime-subscriptions/src/visibility.ts new file mode 100644 index 0000000000..b1a021f26a --- /dev/null +++ b/graphile/graphile-realtime-subscriptions/src/visibility.ts @@ -0,0 +1,23 @@ +import type { ParsedPayload } from './event-gate'; + +const MAX_VISIBLE_IDS = 10_000; + +export class SubscriptionVisibility { + private readonly visibleIds = new Set(); + + allow(payload: ParsedPayload, rowVisible: boolean): boolean { + if (!payload.overflow && payload.rowIds.length > 1) { + throw new Error('Realtime visibility requires single-row events.'); + } + const id = payload.rowIds[0]; + if (payload.overflow || !id) return false; + if (payload.event === 'DELETE') return this.visibleIds.delete(id); + this.visibleIds.delete(id); + if (!rowVisible) return false; + this.visibleIds.add(id); + if (this.visibleIds.size > MAX_VISIBLE_IDS) { + this.visibleIds.delete(this.visibleIds.values().next().value!); + } + return true; + } +} diff --git a/graphile/graphile-realtime-test/README.md b/graphile/graphile-realtime-test/README.md index a040b75e24..ab59e4ea50 100644 --- a/graphile/graphile-realtime-test/README.md +++ b/graphile/graphile-realtime-test/README.md @@ -91,7 +91,7 @@ Fires a DML NOTIFY with the standard payload format. ### `notifyInvalidate(client, schema, table)` -Fires an INVALIDATE (overflow) NOTIFY. +Fires a legacy INVALIDATE NOTIFY for protocol rejection tests. Valid overflow is produced only after a batch of visible row IDs exceeds the subscriber's throttle limit. ### `buildPayload(operation, rowIds)` diff --git a/graphile/graphile-realtime-test/__tests__/realtime-websocket.integration.test.ts b/graphile/graphile-realtime-test/__tests__/realtime-websocket.integration.test.ts index 8652424a19..e20c133bf7 100644 --- a/graphile/graphile-realtime-test/__tests__/realtime-websocket.integration.test.ts +++ b/graphile/graphile-realtime-test/__tests__/realtime-websocket.integration.test.ts @@ -29,6 +29,16 @@ describe('realtime WebSocket E2E (real graphql-ws over ws)', () => { let ctx: GetConnectionsResult; let wsClient: ReturnType; + async function createRows(ids: string[]) { + await ctx.db.query('INSERT INTO realtime_test.items (id, name) SELECT id, id::text FROM unnest($1::uuid[]) AS rows(id)', [ids]); + await ctx.db.publish(); + } + + async function received(events: unknown[], count: number) { + for (let i = 0; i < 200 && events.length < count; i++) await delay(25); + expect(events).toHaveLength(count); + } + beforeAll(async () => { ctx = await getConnections( { @@ -48,6 +58,9 @@ describe('realtime WebSocket E2E (real graphql-ws over ws)', () => { } }, 15000); + beforeEach(async () => { await ctx.pg.beforeEach(); await ctx.db.beforeEach(); }); + afterEach(async () => { await ctx.db.afterEach(); await ctx.pg.afterEach(); }); + // ─── Direct grafast.subscribe sanity check ───────────────────────────── it('(sanity) direct grafastSubscribe works with this setup', async () => { @@ -73,6 +86,7 @@ describe('realtime WebSocket E2E (real graphql-ws over ws)', () => { it('establishes a WebSocket connection and receives INSERT events', async () => { const testId = randomUUID(); + await createRows([testId]); const eventPromise = ctx.ws.nextEvent<{ onItemChanged: { event: string; rowId: string; overflow: boolean }; @@ -89,6 +103,7 @@ describe('realtime WebSocket E2E (real graphql-ws over ws)', () => { await delay(300); await ctx.notifyChange('items', 'INSERT', [testId]); + await ctx.pg.publish(); const data = await eventPromise; expect(data).toBeDefined(); @@ -100,51 +115,50 @@ describe('realtime WebSocket E2E (real graphql-ws over ws)', () => { // ─── Multiple DML operations ────────────────────────────────────────── it('delivers UPDATE and DELETE events over WebSocket', async () => { - // UPDATE - const updateId = randomUUID(); - const updatePromise = ctx.ws.nextEvent<{ - onItemChanged: { event: string; overflow: boolean }; - }>( - wsClient, - `subscription { onItemChanged { event overflow } }`, + const id = randomUUID(); + await createRows([id]); + const { events, unsubscribe } = ctx.ws.collectEvents<{ onItemChanged: { event: string; rowId: string; overflow: boolean } }>( + wsClient, 'subscription { onItemChanged { event rowId overflow item { name } } }' ); - await delay(300); - await ctx.notifyChange('items', 'UPDATE', [updateId]); - const updateData = await updatePromise; - expect(updateData.onItemChanged.event).toBe('UPDATE'); - expect(updateData.onItemChanged.overflow).toBe(false); - - // DELETE - const deleteId = randomUUID(); - const deletePromise = ctx.ws.nextEvent<{ - onItemChanged: { event: string; overflow: boolean }; - }>( - wsClient, - `subscription { onItemChanged { event overflow } }`, - ); - await delay(300); - await ctx.notifyChange('items', 'DELETE', [deleteId]); - const deleteData = await deletePromise; - expect(deleteData.onItemChanged.event).toBe('DELETE'); - expect(deleteData.onItemChanged.overflow).toBe(false); + try { + await delay(300); + await ctx.notifyChange('items', 'UPDATE', [id]); + await ctx.pg.publish(); + await received(events, 1); + await ctx.db.query('DELETE FROM realtime_test.items WHERE id = $1', [id]); + await ctx.db.publish(); + await ctx.notifyChange('items', 'DELETE', [id]); + await ctx.pg.publish(); + await received(events, 2); + expect(events).toEqual([ + { onItemChanged: { event: 'UPDATE', rowId: id, overflow: false, item: { name: id } } }, + { onItemChanged: { event: 'DELETE', rowId: id, overflow: false, item: null } } + ]); + } finally { + unsubscribe(); + } }, 15000); - // ─── INVALIDATE (overflow) ──────────────────────────────────────────── + // ─── Authorized overflow ───────────────────────────────────────────── - it('delivers INVALIDATE (overflow) events via WebSocket', async () => { - const eventPromise = ctx.ws.nextEvent<{ - onItemChanged: { event: string; overflow: boolean }; - }>( - wsClient, - `subscription { onItemChanged { event overflow } }`, + it('delivers 50 visible events and one id-less overflow for a 61-row batch', async () => { + const ids = Array.from({ length: 61 }, () => randomUUID()); + await createRows(ids); + const { events, unsubscribe } = ctx.ws.collectEvents<{ onItemChanged: { event: string; rowId: string | null; overflow: boolean } }>( + wsClient, 'subscription { onItemChanged { event rowId overflow item { name } } }' ); - - await delay(300); - await ctx.notifyInvalidate('items'); - - const data = await eventPromise; - expect(data.onItemChanged.event).toBe('INVALIDATE'); - expect(data.onItemChanged.overflow).toBe(true); + try { + await delay(300); + await ctx.notifyChange('items', 'INSERT', ids); + await ctx.pg.publish(); + await received(events, 51); + expect(events.slice(0, 50)).toEqual(ids.slice(0, 50).map(id => ({ + onItemChanged: { event: 'INSERT', rowId: id, overflow: false, item: { name: id } } + }))); + expect(events[50]).toEqual({ onItemChanged: { event: 'INSERT', rowId: null, overflow: true, item: null } }); + } finally { + unsubscribe(); + } }, 15000); // ─── Sparse set filtering ──────────────────────────────────────────── @@ -152,6 +166,7 @@ describe('realtime WebSocket E2E (real graphql-ws over ws)', () => { it('filters events by ids argument (sparse set) over WebSocket', async () => { const watchedId = randomUUID(); const unwatchedId = randomUUID(); + await createRows([watchedId, unwatchedId]); const { events, unsubscribe } = ctx.ws.collectEvents<{ onItemChanged: { event: string; rowId: string | null; overflow: boolean }; @@ -170,9 +185,11 @@ describe('realtime WebSocket E2E (real graphql-ws over ws)', () => { await delay(300); await ctx.notifyChange('items', 'UPDATE', [unwatchedId]); + await ctx.pg.publish(); await delay(200); await ctx.notifyChange('items', 'INSERT', [watchedId]); + await ctx.pg.publish(); await delay(500); unsubscribe(); @@ -190,6 +207,7 @@ describe('realtime WebSocket E2E (real graphql-ws over ws)', () => { it('delivers events to multiple concurrent WebSocket subscribers', async () => { const testId = randomUUID(); + await createRows([testId]); const promise1 = ctx.ws.nextEvent<{ onItemChanged: { event: string }; @@ -208,6 +226,7 @@ describe('realtime WebSocket E2E (real graphql-ws over ws)', () => { await delay(300); await ctx.notifyChange('items', 'INSERT', [testId]); + await ctx.pg.publish(); const [data1, data2] = await Promise.all([promise1, promise2]); @@ -221,6 +240,7 @@ describe('realtime WebSocket E2E (real graphql-ws over ws)', () => { it('handles raw NOTIFY payloads via WebSocket', async () => { const testId = randomUUID(); + await createRows([testId]); const eventPromise = ctx.ws.nextEvent<{ onItemChanged: { event: string; rowId: string; overflow: boolean }; @@ -236,10 +256,12 @@ describe('realtime WebSocket E2E (real graphql-ws over ws)', () => { ); await delay(300); - await ctx.notify('items', `DELETE:${testId}`); + await ctx.notify('items', `UPDATE:${testId}`); + await ctx.pg.publish(); const data = await eventPromise; - expect(data.onItemChanged.event).toBe('DELETE'); + expect(data.onItemChanged.event).toBe('UPDATE'); + expect(data.onItemChanged.rowId).toBe(testId); expect(data.onItemChanged.overflow).toBe(false); }, 15000); }); diff --git a/graphile/graphile-realtime-test/__tests__/realtime.integration.test.ts b/graphile/graphile-realtime-test/__tests__/realtime.integration.test.ts index c721b9aff9..41c5d8a431 100644 --- a/graphile/graphile-realtime-test/__tests__/realtime.integration.test.ts +++ b/graphile/graphile-realtime-test/__tests__/realtime.integration.test.ts @@ -6,7 +6,7 @@ * - Smart tag injection generates subscription fields * - grafast.subscribe() returns an async iterator * - pg_notify payloads flow through to subscription events - * - INVALIDATE (overflow) payloads are handled correctly + * - Authorized row batches produce events and id-less overflow * - Sparse set filtering (ids argument) works */ @@ -94,6 +94,11 @@ describe('notify helpers', () => { describe('subscription event flow', () => { let ctx: RealtimeTestContext; + async function createRows(ids: string[]) { + await ctx.db.query('INSERT INTO realtime_test.items (id, name) SELECT id, id::text FROM unnest($1::uuid[]) AS rows(id)', [ids]); + await ctx.db.publish(); + } + beforeAll(async () => { ctx = await createRealtimeTestContext( { @@ -110,6 +115,9 @@ describe('subscription event flow', () => { if (ctx) await ctx.teardown(); }); + beforeEach(async () => { await ctx.pg.beforeEach(); await ctx.db.beforeEach(); }); + afterEach(async () => { await ctx.db.afterEach(); await ctx.pg.afterEach(); }); + it('subscribe() returns an async iterator (not an error result)', async () => { const result = await ctx.subscribe(` subscription { @@ -129,6 +137,8 @@ describe('subscription event flow', () => { }); it('delivers INSERT event via pg_notify', async () => { + const testId = randomUUID(); + await createRows([testId]); const iterator = (await ctx.subscribe(` subscription { onItemChanged { @@ -142,8 +152,8 @@ describe('subscription event flow', () => { // Small delay to let the pgSubscriber establish the LISTEN await new Promise((r) => setTimeout(r, 100)); - const testId = randomUUID(); await ctx.notifyChange('items', 'INSERT', [testId]); + await ctx.pg.publish(); const event = await waitForEvent(iterator, 5000); expect(event.data).toBeDefined(); @@ -155,33 +165,42 @@ describe('subscription event flow', () => { await iterator.return?.(); }); - it('delivers INVALIDATE (overflow) event', async () => { + it('delivers 50 visible events and one id-less overflow for a 61-row batch', async () => { + const ids = Array.from({ length: 61 }, () => randomUUID()); + await createRows(ids); const iterator = (await ctx.subscribe(` subscription { onItemChanged { event + rowId overflow + item { name } } } `)) as AsyncIterableIterator; await new Promise((r) => setTimeout(r, 100)); - await ctx.notifyInvalidate('items'); - - const event = await waitForEvent(iterator, 5000); - expect(event.data).toBeDefined(); - - const payload = (event.data as any).onItemChanged; - expect(payload.event).toBe('INVALIDATE'); - expect(payload.overflow).toBe(true); - - await iterator.return?.(); + try { + await ctx.notifyChange('items', 'INSERT', ids); + await ctx.pg.publish(); + for (const id of ids.slice(0, 50)) { + const event = await waitForEvent(iterator, 5000); + expect(event.errors).toBeUndefined(); + expect((event.data as any).onItemChanged).toEqual({ event: 'INSERT', rowId: id, overflow: false, item: { name: id } }); + } + const event = await waitForEvent(iterator, 5000); + expect(event.errors).toBeUndefined(); + expect((event.data as any).onItemChanged).toEqual({ event: 'INSERT', rowId: null, overflow: true, item: null }); + } finally { + await iterator.return?.(); + } }); it('sparse set: delivers only matching row IDs', async () => { const watchedId = randomUUID(); const unwatchedId = randomUUID(); + await createRows([watchedId, unwatchedId]); const iterator = (await ctx.subscribe( `subscription($ids: [UUID!]) { @@ -198,9 +217,11 @@ describe('subscription event flow', () => { // Fire a NOTIFY for the unwatched ID — should be filtered out await ctx.notifyChange('items', 'UPDATE', [unwatchedId]); + await ctx.pg.publish(); // Fire a NOTIFY for the watched ID — should be delivered await ctx.notifyChange('items', 'UPDATE', [watchedId]); + await ctx.pg.publish(); const event = await waitForEvent(iterator, 5000); expect(event.data).toBeDefined(); diff --git a/graphile/graphile-realtime-test/src/context.ts b/graphile/graphile-realtime-test/src/context.ts index b7a8fe2919..8fd43549ea 100644 --- a/graphile/graphile-realtime-test/src/context.ts +++ b/graphile/graphile-realtime-test/src/context.ts @@ -90,7 +90,7 @@ export interface RealtimeTestContext { ): Promise; /** - * Fire an INVALIDATE (overflow) NOTIFY. + * Fire a legacy INVALIDATE NOTIFY for protocol rejection tests. */ notifyInvalidate(table: string, schema?: string): Promise; diff --git a/graphile/graphile-realtime-test/src/notify.ts b/graphile/graphile-realtime-test/src/notify.ts index 3eb5a47ea0..55f30e9fcb 100644 --- a/graphile/graphile-realtime-test/src/notify.ts +++ b/graphile/graphile-realtime-test/src/notify.ts @@ -1,10 +1,11 @@ +import { realtimeChannel } from 'graphile-realtime-subscriptions'; import type { Client } from 'pg'; /** * Fire a pg_notify on the realtime channel for a given schema.table. * * The channel format matches what emit_change uses: - * `realtime:.
` + * `realtime:` plus the hash of the length-framed schema and table names. * * @param client - A pg Client (or PoolClient) to run the NOTIFY on * @param schema - The PostgreSQL schema name (e.g. 'public') @@ -17,7 +18,7 @@ export async function notify( table: string, payload: string ): Promise { - const channel = `realtime:${schema}.${table}`; + const channel = realtimeChannel(schema, table); await client.query(`SELECT pg_notify($1, $2)`, [channel, payload]); } @@ -39,7 +40,7 @@ export function buildPayload( } /** - * Build an INVALIDATE (overflow) payload. + * Build a legacy INVALIDATE payload for protocol rejection tests. */ export function buildInvalidatePayload(): string { return 'INVALIDATE'; @@ -65,7 +66,7 @@ export async function notifyChange( } /** - * Convenience: fire an INVALIDATE NOTIFY for a table. + * Fire a legacy INVALIDATE NOTIFY for protocol rejection tests. */ export async function notifyInvalidate( client: Client, diff --git a/graphile/graphile-realtime-test/src/subscribe.ts b/graphile/graphile-realtime-test/src/subscribe.ts index 89de892993..cc40a0eb65 100644 --- a/graphile/graphile-realtime-test/src/subscribe.ts +++ b/graphile/graphile-realtime-test/src/subscribe.ts @@ -1,4 +1,4 @@ -import { subscribe as grafastSubscribe } from 'grafast'; +import { hookArgs,subscribe as grafastSubscribe } from 'grafast'; import type { GraphileConfig } from 'graphile-config'; import type { DocumentNode, ExecutionResult,GraphQLSchema } from 'graphql'; import { parse } from 'graphql'; @@ -37,13 +37,16 @@ export async function subscribe( const document = typeof opts.query === 'string' ? parse(opts.query) : opts.query; - const result = await grafastSubscribe({ + const args = { schema: opts.schema, document, variableValues: opts.variables ?? undefined, - contextValue: opts.contextValue ?? {}, + contextValue: {}, resolvedPreset: opts.resolvedPreset, - }); + }; + await hookArgs(args); + Object.assign(args.contextValue, opts.contextValue); + const result = await grafastSubscribe(args); return result as AsyncIterableIterator | ExecutionResult; } diff --git a/graphile/graphile-realtime-test/src/ws-server.ts b/graphile/graphile-realtime-test/src/ws-server.ts index 238d59d1ff..52f36cae7d 100644 --- a/graphile/graphile-realtime-test/src/ws-server.ts +++ b/graphile/graphile-realtime-test/src/ws-server.ts @@ -1,13 +1,14 @@ import { createServer, type Server as HttpServer } from 'node:http'; import type { AddressInfo } from 'node:net'; -import { subscribe as grafastSubscribe } from 'grafast'; import type { GraphileConfig } from 'graphile-config'; import type { ExecutionResult, GraphQLSchema } from 'graphql'; import { type Client as GqlWsClient,createClient } from 'graphql-ws'; import { useServer } from 'graphql-ws/use/ws'; import { WebSocket,WebSocketServer } from 'ws'; +import { subscribe as subscribeHelper } from './subscribe.js'; + export interface WsTestServerInput { schema: GraphQLSchema; resolvedPreset: GraphileConfig.ResolvedPreset; @@ -65,10 +66,10 @@ export async function createWsTestServer( } } - const result = await grafastSubscribe({ + const result = await subscribeHelper({ schema: args.schema, - document: args.document, - variableValues: args.variableValues as + query: args.document, + variables: args.variableValues as | Record | undefined, contextValue, diff --git a/graphql/codegen/src/__tests__/codegen/__snapshots__/subscription-hooks.test.ts.snap b/graphql/codegen/src/__tests__/codegen/__snapshots__/subscription-hooks.test.ts.snap index d252ab1d4a..40169769e7 100644 --- a/graphql/codegen/src/__tests__/codegen/__snapshots__/subscription-hooks.test.ts.snap +++ b/graphql/codegen/src/__tests__/codegen/__snapshots__/subscription-hooks.test.ts.snap @@ -62,7 +62,7 @@ import type { SubscriptionEvent, SubscriptionFieldMeta, Unsubscribe } from "../. import type { Contact } from "../../orm/input-types"; import { contactKeys } from "../query-keys"; export type { SubscriptionEvent, Unsubscribe } from "../../orm/client"; -const SUBSCRIPTION_DOCUMENT = "subscription OnContactChanged {\\n onContactChanged {\\n event\\n contact { __typename }\\n timestamp\\n }\\n}"; +const SUBSCRIPTION_DOCUMENT = "subscription OnContactChanged {\\n onContactChanged {\\n event\\n contact { __typename }\\n }\\n}"; const FIELD_META: SubscriptionFieldMeta = { fieldName: "onContactChanged", tableName: "contact", @@ -129,7 +129,7 @@ import type { SubscriptionEvent, SubscriptionFieldMeta, Unsubscribe } from "../. import type { Project } from "../../orm/input-types"; import { projectKeys } from "../query-keys"; export type { SubscriptionEvent, Unsubscribe } from "../../orm/client"; -const SUBSCRIPTION_DOCUMENT = "subscription OnProjectChanged {\\n onProjectChanged {\\n event\\n project { __typename }\\n timestamp\\n }\\n}"; +const SUBSCRIPTION_DOCUMENT = "subscription OnProjectChanged {\\n onProjectChanged {\\n event\\n project { __typename }\\n }\\n}"; const FIELD_META: SubscriptionFieldMeta = { fieldName: "onProjectChanged", tableName: "project", diff --git a/graphql/codegen/src/__tests__/codegen/realtime-plugin.graphql b/graphql/codegen/src/__tests__/codegen/realtime-plugin.graphql new file mode 100644 index 0000000000..2cd27d328d --- /dev/null +++ b/graphql/codegen/src/__tests__/codegen/realtime-plugin.graphql @@ -0,0 +1,316 @@ +# Captured from the real routed server with RealtimeSubscriptionsPreset; reduced to notes and its subscription. +type Query { + """Reads and enables pagination through a set of `Note`.""" + notes( + """Only read the first `n` values of the set.""" + first: Int + + """Only read the last `n` values of the set.""" + last: Int + + """ + Skip the first `n` values from our `after` cursor, an alternative to cursor + based pagination. May not be used with `last`. + """ + offset: Int + + """Read all values in the set before (above) this cursor.""" + before: Cursor + + """Read all values in the set after (below) this cursor.""" + after: Cursor + + """ + A filter to be used in determining which values should be returned by the collection. + """ + where: NoteFilter + + """The method to use when ordering `Note`.""" + orderBy: [NoteOrderBy!] = [PRIMARY_KEY_ASC] + ): NoteConnection +} + +"""A connection to a list of `Note` values.""" +type NoteConnection { + """A list of `Note` objects.""" + nodes: [Note]! + + """ + A list of edges which contains the `Note` and cursor to aid in pagination. + """ + edges: [NoteEdge]! + + """Information to aid in pagination.""" + pageInfo: PageInfo! + + """The count of *all* `Note` you could get from the connection.""" + totalCount: Int! +} + +type Note { + id: UUID! + title: String! +} + +""" +A universally unique identifier as defined by [RFC 4122](https://tools.ietf.org/html/rfc4122). +""" +scalar UUID + +"""A `Note` edge in the connection.""" +type NoteEdge { + """A cursor for use in pagination.""" + cursor: Cursor + + """The `Note` at the end of the edge.""" + node: Note +} + +"""A location in a connection that can be used for resuming pagination.""" +scalar Cursor + +"""Information about pagination in a connection.""" +type PageInfo { + """When paginating forwards, are there more items?""" + hasNextPage: Boolean! + + """When paginating backwards, are there more items?""" + hasPreviousPage: Boolean! + + """When paginating backwards, the cursor to continue.""" + startCursor: Cursor + + """When paginating forwards, the cursor to continue.""" + endCursor: Cursor +} + +""" +A filter to be used against `Note` object types. All fields are combined with a logical ‘and.’ +""" +input NoteFilter { + """Filter by the object’s `id` field.""" + id: UUIDFilter + + """Filter by the object’s `title` field.""" + title: StringFilter + + """Checks for all expressions in this list.""" + and: [NoteFilter!] + + """Checks for any expressions in this list.""" + or: [NoteFilter!] + + """Negates the expression.""" + not: NoteFilter +} + +""" +A filter to be used against UUID fields. All fields are combined with a logical ‘and.’ +""" +input UUIDFilter { + """ + Is null (if `true` is specified) or is not null (if `false` is specified). + """ + isNull: Boolean + + """Equal to the specified value.""" + equalTo: UUID + + """Not equal to the specified value.""" + notEqualTo: UUID + + """ + Not equal to the specified value, treating null like an ordinary value. + """ + distinctFrom: UUID + + """Equal to the specified value, treating null like an ordinary value.""" + notDistinctFrom: UUID + + """Included in the specified list.""" + in: [UUID!] + + """Not included in the specified list.""" + notIn: [UUID!] + + """Less than the specified value.""" + lessThan: UUID + + """Less than or equal to the specified value.""" + lessThanOrEqualTo: UUID + + """Greater than the specified value.""" + greaterThan: UUID + + """Greater than or equal to the specified value.""" + greaterThanOrEqualTo: UUID +} + +""" +A filter to be used against String fields. All fields are combined with a logical ‘and.’ +""" +input StringFilter { + """ + Is null (if `true` is specified) or is not null (if `false` is specified). + """ + isNull: Boolean + + """Equal to the specified value.""" + equalTo: String + + """Not equal to the specified value.""" + notEqualTo: String + + """ + Not equal to the specified value, treating null like an ordinary value. + """ + distinctFrom: String + + """Equal to the specified value, treating null like an ordinary value.""" + notDistinctFrom: String + + """Included in the specified list.""" + in: [String!] + + """Not included in the specified list.""" + notIn: [String!] + + """Less than the specified value.""" + lessThan: String + + """Less than or equal to the specified value.""" + lessThanOrEqualTo: String + + """Greater than the specified value.""" + greaterThan: String + + """Greater than or equal to the specified value.""" + greaterThanOrEqualTo: String + + """Contains the specified string (case-sensitive).""" + includes: String + + """Does not contain the specified string (case-sensitive).""" + notIncludes: String + + """Contains the specified string (case-insensitive).""" + includesInsensitive: String + + """Does not contain the specified string (case-insensitive).""" + notIncludesInsensitive: String + + """Starts with the specified string (case-sensitive).""" + startsWith: String + + """Does not start with the specified string (case-sensitive).""" + notStartsWith: String + + """Starts with the specified string (case-insensitive).""" + startsWithInsensitive: String + + """Does not start with the specified string (case-insensitive).""" + notStartsWithInsensitive: String + + """Ends with the specified string (case-sensitive).""" + endsWith: String + + """Does not end with the specified string (case-sensitive).""" + notEndsWith: String + + """Ends with the specified string (case-insensitive).""" + endsWithInsensitive: String + + """Does not end with the specified string (case-insensitive).""" + notEndsWithInsensitive: String + + """ + Matches the specified pattern (case-sensitive). An underscore (_) matches any single character; a percent sign (%) matches any sequence of zero or more characters. + """ + like: String + + """ + Does not match the specified pattern (case-sensitive). An underscore (_) matches any single character; a percent sign (%) matches any sequence of zero or more characters. + """ + notLike: String + + """ + Matches the specified pattern (case-insensitive). An underscore (_) matches any single character; a percent sign (%) matches any sequence of zero or more characters. + """ + likeInsensitive: String + + """ + Does not match the specified pattern (case-insensitive). An underscore (_) matches any single character; a percent sign (%) matches any sequence of zero or more characters. + """ + notLikeInsensitive: String + + """Equal to the specified value (case-insensitive).""" + equalToInsensitive: String + + """Not equal to the specified value (case-insensitive).""" + notEqualToInsensitive: String + + """ + Not equal to the specified value, treating null like an ordinary value (case-insensitive). + """ + distinctFromInsensitive: String + + """ + Equal to the specified value, treating null like an ordinary value (case-insensitive). + """ + notDistinctFromInsensitive: String + + """Included in the specified list (case-insensitive).""" + inInsensitive: [String!] + + """Not included in the specified list (case-insensitive).""" + notInInsensitive: [String!] + + """Less than the specified value (case-insensitive).""" + lessThanInsensitive: String + + """Less than or equal to the specified value (case-insensitive).""" + lessThanOrEqualToInsensitive: String + + """Greater than the specified value (case-insensitive).""" + greaterThanInsensitive: String + + """Greater than or equal to the specified value (case-insensitive).""" + greaterThanOrEqualToInsensitive: String +} + +"""Methods to use when ordering `Note`.""" +enum NoteOrderBy { + NATURAL + PRIMARY_KEY_ASC + PRIMARY_KEY_DESC + ID_ASC + ID_DESC + TITLE_ASC + TITLE_DESC +} + +type Subscription { + """ + Subscribe to changes on this table. Pass ids to watch specific rows, or no args for the full collection. + """ + onNoteChanged(ids: [UUID!]): NoteSubscriptionPayload +} + +"""Payload delivered when a Note row changes.""" +type NoteSubscriptionPayload { + """The DML operation: INSERT, UPDATE, DELETE, or INVALIDATE.""" + event: String! + + """ + The current state of the row (null for DELETE, INVALIDATE, or if RLS denies access). + """ + note: Note + + """ + The ID of the changed row (null for INVALIDATE, or masked when RLS denies access). + """ + rowId: UUID + + """True when too many changes occurred and the client should refetch.""" + overflow: Boolean! +} diff --git a/graphql/codegen/src/__tests__/codegen/realtime-schema.test.ts b/graphql/codegen/src/__tests__/codegen/realtime-schema.test.ts new file mode 100644 index 0000000000..1e4f66c473 --- /dev/null +++ b/graphql/codegen/src/__tests__/codegen/realtime-schema.test.ts @@ -0,0 +1,97 @@ +import { readFileSync } from 'node:fs'; +import { createServer, type Server } from 'node:http'; +import type { AddressInfo } from 'node:net'; +import path from 'node:path'; + +import { buildSchema, graphql, parse, validate } from 'graphql'; +import ts from 'typescript'; + +import { generate } from '../../core/codegen'; +import { inferTablesFromIntrospection } from '../../core/introspect/infer-tables'; +import { EndpointSchemaSource } from '../../core/introspect/source/endpoint'; +import { FileSchemaSource } from '../../core/introspect/source/file'; +import { getConfigOptions } from '../../types/config'; +import type { IntrospectionQueryResponse } from '../../types/introspection'; + +const fixture = path.join(__dirname, 'realtime-plugin.graphql'); +const schema = buildSchema(readFileSync(fixture, 'utf8')); + +function generateSubscriptions(introspection: IntrospectionQueryResponse) { + return generate({ + tables: inferTablesFromIntrospection(introspection), + config: getConfigOptions({ reactQuery: true }), + }).files.filter((file) => file.path.startsWith('subscriptions/')); +} + +describe('codegen from the realtime plugin schema', () => { + let server: Server; + let endpoint: string; + + beforeAll(async () => { + server = createServer(async (req, res) => { + let body = ''; + for await (const chunk of req) body += chunk; + const { query, variables } = JSON.parse(body); + const result = await graphql({ schema, source: query, variableValues: variables }); + res.setHeader('Content-Type', 'application/json'); + res.end(JSON.stringify(result)); + }); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + endpoint = `http://127.0.0.1:${(server.address() as AddressInfo).port}/graphql`; + }); + afterAll(async () => { + await new Promise((resolve, reject) => server.close((error) => error ? reject(error) : resolve())); + }); + + it('captures the public signal: no description tag, but a subscription and payload', () => { + expect(schema.getType('Note')?.description).toBeUndefined(); + expect(schema.getSubscriptionType()?.getFields().onNoteChanged).toBeDefined(); + const payload = schema.getType('NoteSubscriptionPayload') as import('graphql').GraphQLObjectType; + expect(Object.keys(payload.getFields())).toEqual(['event', 'note', 'rowId', 'overflow']); + }); + + it.each(['endpoint', 'schema file'])('generates a validating subscription from %s introspection', async (source) => { + const result = await (source === 'endpoint' + ? new EndpointSchemaSource({ endpoint }) + : new FileSchemaSource({ schemaPath: fixture })).fetch(); + const tables = inferTablesFromIntrospection(result.introspection); + expect(tables.find((table) => table.name === 'Note')?.smartTags).toEqual({ '@realtime': true }); + expect(inferTablesFromIntrospection(result.introspection, { comments: false })[0].smartTags).toEqual({ '@realtime': true }); + const files = generateSubscriptions(result.introspection); + const hook = files.find((file) => file.path === 'subscriptions/useNoteSubscription.ts'); + expect(hook).toBeDefined(); + const ast = ts.createSourceFile('hook.ts', hook!.content, ts.ScriptTarget.Latest, true); + let document: string | undefined; + for (const statement of ast.statements) { + if (!ts.isVariableStatement(statement)) continue; + for (const declaration of statement.declarationList.declarations) { + if (declaration.name.getText(ast) === 'SUBSCRIPTION_DOCUMENT' && declaration.initializer && ts.isStringLiteral(declaration.initializer)) { + document = declaration.initializer.text; + } + } + } + expect(document).toBeDefined(); + expect(document).not.toContain('timestamp'); + expect(validate(schema, parse(document!))).toEqual([]); + }); + + it('does not generate subscriptions when none are advertised', async () => { + const { introspection } = await new FileSchemaSource({ schemaPath: fixture }).fetch(); + introspection.__schema.subscriptionType = null; + expect(generateSubscriptions(introspection)).toEqual([]); + }); + + it.each(['event', 'note'])('does not infer realtime for a similarly named field with the wrong %s payload', async (name) => { + const { introspection } = await new FileSchemaSource({ schemaPath: fixture }).fetch(); + const payload = introspection.__schema.types.find((type) => type.name === 'NoteSubscriptionPayload'); + payload!.fields = payload!.fields!.filter((field) => field.name !== name); + expect(generateSubscriptions(introspection)).toEqual([]); + }); + + it('preserves description tags when recovering realtime metadata', async () => { + const { introspection } = await new FileSchemaSource({ schemaPath: fixture }).fetch(); + introspection.__schema.types.find((type) => type.name === 'Note')!.description = '@realtime insert\n@custom value'; + const table = inferTablesFromIntrospection(introspection)[0]; + expect(table.smartTags).toMatchObject({ '@realtime': 'insert', '@custom': 'value' }); + }); +}); diff --git a/graphql/codegen/src/core/codegen/orm/client.ts b/graphql/codegen/src/core/codegen/orm/client.ts index 6caca4cff6..a06c16e05a 100644 --- a/graphql/codegen/src/core/codegen/orm/client.ts +++ b/graphql/codegen/src/core/codegen/orm/client.ts @@ -110,7 +110,6 @@ export interface SubscriptionEvent { operation: SubscriptionOperation; data: T | null; previousValues?: Partial; - timestamp: string; } export interface SubscriptionFieldMeta { diff --git a/graphql/codegen/src/core/codegen/subscriptions.ts b/graphql/codegen/src/core/codegen/subscriptions.ts index 6c2c593a6d..499a53db08 100644 --- a/graphql/codegen/src/core/codegen/subscriptions.ts +++ b/graphql/codegen/src/core/codegen/subscriptions.ts @@ -101,7 +101,6 @@ export function generateSubscriptionHook( ${subscriptionFieldName} { event ${singularName} { __typename } - timestamp } }`; const docDecl = constDecl( diff --git a/graphql/codegen/src/core/codegen/templates/orm-realtime.ts b/graphql/codegen/src/core/codegen/templates/orm-realtime.ts index 38f6b94faa..36cc06ca54 100644 --- a/graphql/codegen/src/core/codegen/templates/orm-realtime.ts +++ b/graphql/codegen/src/core/codegen/templates/orm-realtime.ts @@ -74,8 +74,6 @@ export interface SubscriptionEvent { data: T | null; /** Previous field values (populated on UPDATE when available) */ previousValues?: Partial; - /** Server-side timestamp of when the change occurred */ - timestamp: string; } /** @@ -205,8 +203,6 @@ export class RealtimeManager { previousValues: payload.previousValues as | Partial | undefined, - timestamp: - (payload.timestamp as string) ?? new Date().toISOString(), }; options.onEvent(event); }, diff --git a/graphql/query/__tests__/realtime-inference.test.ts b/graphql/query/__tests__/realtime-inference.test.ts new file mode 100644 index 0000000000..5dd08a9e56 --- /dev/null +++ b/graphql/query/__tests__/realtime-inference.test.ts @@ -0,0 +1,48 @@ +import { buildSchema, introspectionFromSchema } from 'graphql'; + +import { inferTablesFromIntrospection } from '../src/introspect/infer-tables'; +import type { IntrospectionQueryResponse } from '../src/types/introspection'; + +function realtimeTag(payload = 'NoteChangedPayload', event = 'String!', row = 'Note', args = '') { + const schema = buildSchema(` + scalar UUID + type Note { id: UUID!, title: String } + type NoteConnection { nodes: [Note!]! } + type Query { notes: NoteConnection! } + type NoteChangedPayload { event: ${event}, note: ${row} } + type Subscription { onNoteChanged${args}: ${payload} } + `); + const tables = inferTablesFromIntrospection(introspectionFromSchema(schema) as unknown as IntrospectionQueryResponse); + expect(tables).toHaveLength(1); + return tables[0].smartTags?.['@realtime']; +} + +describe('realtime subscription inference', () => { + it.each(['NoteChangedPayload', 'NoteChangedPayload!'])('accepts a singular payload: %s', payload => { + expect(realtimeTag(payload)).toBe(true); + }); + + it.each(['[NoteChangedPayload]', '[NoteChangedPayload!]!', '[[NoteChangedPayload!]!]!'])('rejects a list payload: %s', payload => { + expect(realtimeTag(payload)).toBeUndefined(); + }); + + it.each(['[String]', '[String!]!'])('rejects a list event: %s', event => { + expect(realtimeTag('NoteChangedPayload', event)).toBeUndefined(); + }); + + it.each(['[Note]', '[Note!]!', '[[Note!]!]!'])('rejects a list row: %s', row => { + expect(realtimeTag('NoteChangedPayload', 'String!', row)).toBeUndefined(); + }); + + it('accepts a non-null singular row', () => { + expect(realtimeTag('NoteChangedPayload!', 'String!', 'Note!')).toBe(true); + }); + + it.each(['(scope: String!)', '(ids: [UUID!]!)'])('rejects an unsupplied required argument: %s', args => { + expect(realtimeTag('NoteChangedPayload', 'String!', 'Note', args)).toBeUndefined(); + }); + + it.each(['(scope: String)', '(scope: String! = "default")', '(ids: [UUID!])'])('accepts optional or defaulted arguments: %s', args => { + expect(realtimeTag('NoteChangedPayload', 'String!', 'Note', args)).toBe(true); + }); +}); diff --git a/graphql/query/src/introspect/infer-tables.ts b/graphql/query/src/introspect/infer-tables.ts index b0ee0f599a..e164f4bf23 100644 --- a/graphql/query/src/introspect/infer-tables.ts +++ b/graphql/query/src/introspect/infer-tables.ts @@ -142,6 +142,9 @@ export function inferTablesFromIntrospection( const mutationFields = mutationType ? getTypeFields(typeMap.get(mutationType.name)) : []; + const subscriptionFields = schema.subscriptionType + ? getTypeFields(typeMap.get(schema.subscriptionType.name)) + : []; // Step 1: Build Table for each inferred entity const tables: Table[] = []; @@ -162,6 +165,24 @@ export function inferTablesFromIntrospection( commentsEnabled, ); + const subscription = subscriptionFields.find( + (field) => field.name === `on${entityName}Changed`, + ); + if (subscription && !isList(subscription.type) && !subscription.args.some( + argument => isNonNull(argument.type) && argument.defaultValue == null, + )) { + const payload = getTypeFields(typeMap.get(getBaseTypeName(subscription.type))); + const hasEvent = payload.some( + (field) => field.name === 'event' && !isList(field.type) && getBaseTypeName(field.type) === 'String', + ); + const hasRow = payload.some( + (field) => field.name === lcFirst(entityName) && !isList(field.type) && getBaseTypeName(field.type) === entityName, + ); + if (hasEvent && hasRow) { + table.smartTags = { '@realtime': true, ...table.smartTags }; + } + } + // Only include tables that have at least one real operation if (hasRealOperation) { tables.push(table); diff --git a/graphql/server-test/__fixtures__/seed/websocket-rls.sql b/graphql/server-test/__fixtures__/seed/websocket-rls.sql new file mode 100644 index 0000000000..0f43629fc9 --- /dev/null +++ b/graphql/server-test/__fixtures__/seed/websocket-rls.sql @@ -0,0 +1,137 @@ +CREATE TABLE "simple-pets-public".realtime_users (id uuid PRIMARY KEY, name text NOT NULL); +INSERT INTO "simple-pets-public".realtime_users VALUES + ('bbbbbbbb-0000-4000-8000-000000000002', 'Alice'), + ('bbbbbbbb-0000-4000-8000-000000000003', 'Bob'), + ('bbbbbbbb-0000-4000-8000-000000000004', 'Charlie'); +ALTER TABLE "simple-pets-auth-private".sessions ADD FOREIGN KEY (user_id) + REFERENCES "simple-pets-public".realtime_users(id); + +CREATE TABLE "simple-pets-public".rls_notes ( + id uuid PRIMARY KEY, + owner_id uuid NOT NULL REFERENCES "simple-pets-public".realtime_users(id), + title text NOT NULL DEFAULT 'private contents', + shared boolean NOT NULL DEFAULT false +); +COMMENT ON TABLE "simple-pets-public".rls_notes IS E'@realtime'; +ALTER TABLE "simple-pets-public".rls_notes ENABLE ROW LEVEL SECURITY; +GRANT SELECT, INSERT, UPDATE, DELETE ON "simple-pets-public".rls_notes TO authenticated; +CREATE POLICY read_notes ON "simple-pets-public".rls_notes FOR SELECT TO authenticated + USING (shared OR owner_id = nullif(current_setting('jwt.claims.user_id', true), '')::uuid); +CREATE POLICY create_notes ON "simple-pets-public".rls_notes FOR INSERT TO authenticated + WITH CHECK (owner_id = nullif(current_setting('jwt.claims.user_id', true), '')::uuid); +CREATE POLICY update_notes ON "simple-pets-public".rls_notes FOR UPDATE TO authenticated + USING (owner_id = nullif(current_setting('jwt.claims.user_id', true), '')::uuid) + WITH CHECK (owner_id = nullif(current_setting('jwt.claims.user_id', true), '')::uuid); +CREATE POLICY delete_notes ON "simple-pets-public".rls_notes FOR DELETE TO authenticated + USING (owner_id = nullif(current_setting('jwt.claims.user_id', true), '')::uuid); + +CREATE FUNCTION "simple-pets-private".notify_rls_note() RETURNS trigger AS $$ +BEGIN + PERFORM pg_notify('realtime:' || md5(octet_length(TG_TABLE_SCHEMA)::text || ':' || TG_TABLE_SCHEMA || TG_TABLE_NAME), + TG_OP || ':' || string_agg(id::text, ',' ORDER BY id)) + FROM changed_rows HAVING count(*) > 0; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; +CREATE TRIGGER notify_rls_note_insert AFTER INSERT ON "simple-pets-public".rls_notes + REFERENCING NEW TABLE AS changed_rows FOR EACH STATEMENT EXECUTE FUNCTION "simple-pets-private".notify_rls_note(); +CREATE TRIGGER notify_rls_note_update AFTER UPDATE ON "simple-pets-public".rls_notes + REFERENCING NEW TABLE AS changed_rows FOR EACH STATEMENT EXECUTE FUNCTION "simple-pets-private".notify_rls_note(); +CREATE TRIGGER notify_rls_note_delete AFTER DELETE ON "simple-pets-public".rls_notes + REFERENCING OLD TABLE AS changed_rows FOR EACH STATEMENT EXECUTE FUNCTION "simple-pets-private".notify_rls_note(); + +CREATE FUNCTION "simple-pets-public".bulk_write_rls_notes(note_ids uuid[], operation text) +RETURNS boolean AS $$ +BEGIN + IF operation = 'UPDATE' THEN + UPDATE "simple-pets-public".rls_notes AS n SET title = n.title || '!' WHERE n.id = ANY(note_ids); + ELSIF operation = 'DELETE' THEN + DELETE FROM "simple-pets-public".rls_notes WHERE id = ANY(note_ids); + ELSE + RAISE EXCEPTION 'Unknown test operation'; + END IF; + RETURN true; +END; +$$ LANGUAGE plpgsql VOLATILE; +GRANT EXECUTE ON FUNCTION "simple-pets-public".bulk_write_rls_notes(uuid[], text) TO authenticated; + +CREATE FUNCTION "simple-pets-public".write_rls_note(note_id uuid, operation text, shared boolean DEFAULT NULL) +RETURNS uuid AS $$ +BEGIN + IF operation = 'INSERT' THEN + INSERT INTO "simple-pets-public".rls_notes (id, owner_id, shared) + VALUES (note_id, current_setting('jwt.claims.user_id')::uuid, coalesce(shared, false)); + ELSIF operation = 'UPDATE' THEN + UPDATE "simple-pets-public".rls_notes AS n SET title = n.title || '!', shared = coalesce(write_rls_note.shared, n.shared) + WHERE n.id = note_id; + ELSIF operation = 'DELETE' THEN + DELETE FROM "simple-pets-public".rls_notes WHERE id = note_id; + ELSE + RAISE EXCEPTION 'Unknown test operation'; + END IF; + RETURN note_id; +END; +$$ LANGUAGE plpgsql VOLATILE; +GRANT EXECUTE ON FUNCTION "simple-pets-public".write_rls_note(uuid, text, boolean) TO authenticated; + +CREATE FUNCTION "simple-pets-public".rls_note_visible(note_id uuid) RETURNS boolean AS $$ + SELECT EXISTS (SELECT FROM "simple-pets-public".rls_notes WHERE id = note_id); +$$ LANGUAGE sql STABLE; +GRANT EXECUTE ON FUNCTION "simple-pets-public".rls_note_visible(uuid) TO authenticated; + +CREATE FUNCTION "simple-pets-public".bulk_create_rls_notes(note_ids uuid[], shared_ids uuid[]) +RETURNS uuid[] AS $$ + WITH added AS ( + INSERT INTO "simple-pets-public".rls_notes (id, owner_id, shared) + SELECT id, current_setting('jwt.claims.user_id')::uuid, id = ANY(shared_ids) + FROM unnest(note_ids) AS n(id) + RETURNING id + ) SELECT array_agg(id ORDER BY id) FROM added; +$$ LANGUAGE sql VOLATILE; +GRANT EXECUTE ON FUNCTION "simple-pets-public".bulk_create_rls_notes(uuid[], uuid[]) TO authenticated; + +UPDATE routing_public.database_settings SET max_concurrent_requests = 8, max_request_bytes = 16384 +WHERE database_id = '80a2eaaf-f77e-4bfe-8506-df929ef1b8d9'; + +CREATE TABLE "simple-pets-public".long_realtime_notification_lifecycle_notes ( + id uuid PRIMARY KEY, + owner_id uuid NOT NULL, + title text NOT NULL DEFAULT 'long channel contents' +); +COMMENT ON TABLE "simple-pets-public".long_realtime_notification_lifecycle_notes IS E'@realtime'; +ALTER TABLE "simple-pets-public".long_realtime_notification_lifecycle_notes ENABLE ROW LEVEL SECURITY; +GRANT SELECT, INSERT, UPDATE, DELETE ON "simple-pets-public".long_realtime_notification_lifecycle_notes TO authenticated; +CREATE POLICY own_long_notes ON "simple-pets-public".long_realtime_notification_lifecycle_notes TO authenticated + USING (owner_id = nullif(current_setting('jwt.claims.user_id', true), '')::uuid) + WITH CHECK (owner_id = nullif(current_setting('jwt.claims.user_id', true), '')::uuid); + +CREATE FUNCTION "simple-pets-private".notify_long_realtime_note() RETURNS trigger AS $$ +BEGIN + PERFORM pg_notify('realtime:' || md5(octet_length(TG_TABLE_SCHEMA)::text || ':' || TG_TABLE_SCHEMA || TG_TABLE_NAME), + TG_OP || ':' || string_agg(id::text, ',' ORDER BY id)) FROM changed_rows HAVING count(*) > 0; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; +CREATE TRIGGER long_note_insert AFTER INSERT ON "simple-pets-public".long_realtime_notification_lifecycle_notes + REFERENCING NEW TABLE AS changed_rows FOR EACH STATEMENT EXECUTE FUNCTION "simple-pets-private".notify_long_realtime_note(); +CREATE TRIGGER long_note_update AFTER UPDATE ON "simple-pets-public".long_realtime_notification_lifecycle_notes + REFERENCING NEW TABLE AS changed_rows FOR EACH STATEMENT EXECUTE FUNCTION "simple-pets-private".notify_long_realtime_note(); +CREATE TRIGGER long_note_delete AFTER DELETE ON "simple-pets-public".long_realtime_notification_lifecycle_notes + REFERENCING OLD TABLE AS changed_rows FOR EACH STATEMENT EXECUTE FUNCTION "simple-pets-private".notify_long_realtime_note(); + +CREATE FUNCTION "simple-pets-public".write_long_realtime_note(note_id uuid, operation text) RETURNS uuid AS $$ +BEGIN + IF operation = 'INSERT' THEN + INSERT INTO "simple-pets-public".long_realtime_notification_lifecycle_notes (id, owner_id) + VALUES (note_id, current_setting('jwt.claims.user_id')::uuid); + ELSIF operation = 'UPDATE' THEN + UPDATE "simple-pets-public".long_realtime_notification_lifecycle_notes SET title = title || '!' WHERE id = note_id; + ELSIF operation = 'DELETE' THEN + DELETE FROM "simple-pets-public".long_realtime_notification_lifecycle_notes WHERE id = note_id; + ELSE + RAISE EXCEPTION 'Unknown test operation'; + END IF; + RETURN note_id; +END; +$$ LANGUAGE plpgsql VOLATILE; +GRANT EXECUTE ON FUNCTION "simple-pets-public".write_long_realtime_note(uuid, text) TO authenticated; diff --git a/graphql/server-test/__fixtures__/seed/websocket.sql b/graphql/server-test/__fixtures__/seed/websocket.sql new file mode 100644 index 0000000000..019238726c --- /dev/null +++ b/graphql/server-test/__fixtures__/seed/websocket.sql @@ -0,0 +1,31 @@ +CREATE SCHEMA "simple-pets-auth-private"; +COMMENT ON TABLE "simple-pets-pets-public".animals IS E'@realtime'; +GRANT USAGE ON SCHEMA "simple-pets-auth-private" TO authenticated, anonymous; +CREATE TABLE "simple-pets-auth-private".sessions ( + id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + user_id uuid NOT NULL, + token text NOT NULL UNIQUE DEFAULT gen_random_uuid()::text, + expires_at timestamptz NOT NULL DEFAULT now() + interval '1 hour' +); +CREATE FUNCTION "simple-pets-public".issue_session(actor uuid) RETURNS text AS $$ + INSERT INTO "simple-pets-auth-private".sessions (user_id) VALUES (actor) RETURNING token; +$$ LANGUAGE sql VOLATILE; +GRANT INSERT, SELECT ON "simple-pets-auth-private".sessions TO anonymous, authenticated; +GRANT EXECUTE ON FUNCTION "simple-pets-public".issue_session(uuid) TO anonymous, authenticated; +CREATE FUNCTION "simple-pets-auth-private".authenticate(credential text) +RETURNS TABLE (id uuid, user_id uuid) AS $$ + SELECT s.id, s.user_id FROM "simple-pets-auth-private".sessions s + WHERE s.token = credential AND s.expires_at > now(); +$$ LANGUAGE sql STABLE; +GRANT EXECUTE ON FUNCTION "simple-pets-auth-private".authenticate(text) TO anonymous, authenticated; + +SET session_replication_role TO replica; +INSERT INTO metaschema_public.schema (id, database_id, name, schema_name, is_public) +VALUES ('6dba0001-0000-4000-8000-000000000001', '80a2eaaf-f77e-4bfe-8506-df929ef1b8d9', 'auth_private', 'simple-pets-auth-private', false); +INSERT INTO metaschema_public.function (id, database_id, schema_id, name) +VALUES ('6dba0002-0000-4000-8000-000000000001', '80a2eaaf-f77e-4bfe-8506-df929ef1b8d9', '6dba0001-0000-4000-8000-000000000001', 'authenticate'); +INSERT INTO routing_public.rls_settings (database_id, authenticate_schema_id, authenticate_function_id, authenticate_strict_function_id) +VALUES ('80a2eaaf-f77e-4bfe-8506-df929ef1b8d9', '6dba0001-0000-4000-8000-000000000001', '6dba0002-0000-4000-8000-000000000001', '6dba0002-0000-4000-8000-000000000001'); +INSERT INTO routing_public.database_settings (database_id, enable_realtime, max_concurrent_requests, max_queue_wait_ms, max_request_bytes) +VALUES ('80a2eaaf-f77e-4bfe-8506-df929ef1b8d9', true, 2, 0, 1024); +SET session_replication_role TO DEFAULT; diff --git a/graphql/server-test/__tests__/websocket-rls.integration.test.ts b/graphql/server-test/__tests__/websocket-rls.integration.test.ts new file mode 100644 index 0000000000..8752d93aa7 --- /dev/null +++ b/graphql/server-test/__tests__/websocket-rls.integration.test.ts @@ -0,0 +1,375 @@ +import { randomUUID } from 'crypto'; +import { graphileCache } from 'graphile-cache'; +import { type Client,createClient } from 'graphql-ws'; +import path from 'path'; +import type { PgTestClient } from 'pgsql-test/test-client'; +import type supertest from 'supertest'; +import WebSocket from 'ws'; + +import { getConnections, seed } from '../src'; +import type { ServerInfo } from '../src/types'; + +jest.setTimeout(60000); + +const HOST = 'app.test.constructive.io'; +const ALICE = 'bbbbbbbb-0000-4000-8000-000000000002'; +const BOB = 'bbbbbbbb-0000-4000-8000-000000000003'; +const CHARLIE = 'bbbbbbbb-0000-4000-8000-000000000004'; +const shared = path.join(__dirname, '../../../__fixtures__/seed'); +const pause = (ms: number) => new Promise(resolve => setTimeout(resolve, ms)); +const document = `subscription($ids: [UUID!]) { + onRlsNoteChanged(ids: $ids) { event rowId overflow rlsNote { id title } } +}`; + +interface Stream { client: Client; frames: any[]; errors: unknown[]; stop: () => void } + +describe('RLS-gated public tenant WebSocket events', () => { + let pg: PgTestClient; + let db: PgTestClient; + let server: ServerInfo; + let request: supertest.Agent; + let teardown: () => Promise; + let alice: string; + let bob: string; + let charlie: string; + let streams: Stream[] = []; + + async function http(token: string | undefined, query: string, variables = {}) { + const req = request.post('/graphql').set('Host', HOST); + if (token) req.set('Authorization', `Bearer ${token}`); + const response = await req.send({ query, variables }); + expect(response.status).toBe(200); + expect(response.body.errors).toBeUndefined(); + return response.body.data; + } + + async function write(id: string, operation: string, shared?: boolean) { + const result = await http(alice, `mutation($id: UUID!, $op: String!, $shared: Boolean) { + writeRlsNote(input: {noteId: $id, operation: $op, shared: $shared}) { result } + }`, { id, op: operation, shared }); + expect(result.writeRlsNote.result).toBe(id); + } + + async function visible(token: string, id: string, expected: boolean) { + expect((await http(token, 'query($id: UUID!) { rlsNoteVisible(noteId: $id) }', { id })).rlsNoteVisible).toBe(expected); + } + + async function bulkCreate(token: string, ids: string[], sharedIds: string[] = []) { + const result = await http(token, `mutation($ids: [UUID]!, $shared: [UUID]!) { + bulkCreateRlsNotes(input: {noteIds: $ids, sharedIds: $shared}) { result } + }`, { ids, shared: sharedIds }); + expect(result.bulkCreateRlsNotes.result).toEqual([...ids].sort()); + } + + async function overflow(stream: Stream) { + for (let i = 0; i < 100 && !payloads(stream).some(payload => payload.overflow); i++) await pause(20); + expect(stream.errors).toEqual([]); + expect(stream.frames.flatMap(frame => frame.errors ?? [])).toEqual([]); + expect(payloads(stream).filter(payload => payload.overflow)).toEqual([ + { event: 'INSERT', rowId: null, overflow: true, rlsNote: null } + ]); + } + + function open(token: string, ids?: string[], query = document, client?: Client) { + class Socket extends WebSocket { + constructor(address: string, protocols: string[]) { super(address, protocols, { headers: { Host: HOST } }); } + } + const stream: Stream = { + client: client ?? createClient({ + url: server.graphqlUrl.replace('http:', 'ws:'), webSocketImpl: Socket, + connectionParams: { Authorization: `Bearer ${token}` }, retryAttempts: 0 + }), frames: [], errors: [], stop: () => {} + }; + stream.stop = stream.client.subscribe({ query, variables: { ids } }, { + next: value => stream.frames.push(value), error: error => stream.errors.push(error), complete: () => {} + }); + streams.push(stream); + return stream; + } + + async function delivered(stream: Stream, id: string, event: string) { + for (let i = 0; i < 100; i++) { + expect(stream.errors).toEqual([]); + expect(stream.frames.flatMap(frame => frame.errors ?? [])).toEqual([]); + if (payloads(stream).some(payload => payload.rowId === id && payload.event === event)) return; + await pause(20); + } + throw new Error(`Missing ${event} for ${id}: ${JSON.stringify(stream.frames)}`); + } + + function payloads(stream: Stream): any[] { + return stream.frames.flatMap(frame => Object.values(frame.data ?? {}).filter(value => value && typeof value === 'object')); + } + + async function ready(...watchers: Stream[]) { + const id = randomUUID(); + await write(id, 'INSERT', true); + for (let i = 0; i < 50; i++) { + await write(id, 'UPDATE'); + await pause(30); + if (watchers.every(stream => payloads(stream).some(payload => payload.rowId === id))) break; + } + for (const stream of watchers) await delivered(stream, id, 'UPDATE'); + await pause(100); + for (const stream of streams) stream.frames.length = 0; + } + + async function silent(stream: Stream) { + await pause(300); + expect(stream.errors).toEqual([]); + expect(stream.frames).toEqual([]); + } + + beforeAll(async () => { + ({ pg, db, server, request, teardown } = await getConnections({ + schemas: ['simple-pets-public', 'simple-pets-pets-public'], + server: { useRouting: true, api: { isPublic: true, metaSchemas: [ + 'catalog_private', 'routing_public', 'apps_public', 'metaschema_public', 'metaschema_modules_public' + ] } } + }, [seed.pgpm(path.join(shared, '../..')), seed.sqlfile([ + path.join(shared, 'app-schemas/simple-pets/schema.sql'), path.join(shared, 'scoped/test-data.sql'), + path.join(__dirname, '../__fixtures__/seed/websocket.sql'), + path.join(__dirname, '../__fixtures__/seed/websocket-rls.sql') + ])])); + alice = (await http(undefined, `mutation { issueSession(input: {actor: "${ALICE}"}) { result } }`)).issueSession.result; + bob = (await http(undefined, `mutation { issueSession(input: {actor: "${BOB}"}) { result } }`)).issueSession.result; + charlie = (await http(undefined, `mutation { issueSession(input: {actor: "${CHARLIE}"}) { result } }`)).issueSession.result; + expect(alice).not.toBe(bob); + }); + beforeEach(async () => { await pg.beforeEach(); await db.beforeEach(); }); + afterEach(async () => { + for (const stream of streams) stream.stop(); + await Promise.all([...new Set(streams.map(stream => stream.client))].map(client => client.dispose())); + streams = []; + await db.afterEach(); await pg.afterEach(); + }); + afterAll(async () => { + // PgServices own their shared LISTEN sessions independently of PostGraphile. + const services = new Set([...graphileCache.values()].flatMap( + (entry): readonly { release?: () => void | Promise }[] => entry.pgl.getResolvedPreset().pgServices ?? [] + )); + for (const service of services) await service.release?.(); + await teardown?.(); + }); + + it('delivers long realtime channel INSERT, UPDATE and DELETE over the authenticated tenant socket', async () => { + const longWrite = async (id: string, operation: string) => { + const result = await http(alice, `mutation($id: UUID!, $op: String!) { + writeLongRealtimeNote(input: {noteId: $id, operation: $op}) { result } + }`, { id, op: operation }); + expect(result.writeLongRealtimeNote.result).toBe(id); + }; + const probe = randomUUID(); + await longWrite(probe, 'INSERT'); + const stream = open(alice, undefined, `subscription { + onLongRealtimeNotificationLifecycleNoteChanged { + event rowId longRealtimeNotificationLifecycleNote { id title } + } + }`); + for (let i = 0; i < 50 && payloads(stream).length === 0; i++) { + await longWrite(probe, 'UPDATE'); + await pause(30); + } + await delivered(stream, probe, 'UPDATE'); + const id = randomUUID(); + for (const operation of ['INSERT', 'UPDATE', 'DELETE']) { + await longWrite(id, operation); + await delivered(stream, id, operation); + } + const events = payloads(stream).filter(payload => payload.rowId === id); + expect(events.map(payload => payload.event)).toEqual(['INSERT', 'UPDATE', 'DELETE']); + expect(events[0].longRealtimeNotificationLifecycleNote).toMatchObject({ id, title: 'long channel contents' }); + expect(events[2].longRealtimeNotificationLifecycleNote).toBeNull(); + }); + + it.each(['@skip(if: true)', '@include(if: false)'])('does not disclose a private change alongside an excluded alias: %s', async directive => { + const a = open(alice); + const b = open(bob, undefined, `subscription { + active: onRlsNoteChanged { event rowId overflow rlsNote { id title } } + excluded: onRlsNoteChanged ${directive} { event rowId } + }`); + await ready(a, b); + const id = randomUUID(); + await write(id, 'INSERT'); + await delivered(a, id, 'INSERT'); + await visible(alice, id, true); + await visible(bob, id, false); + await silent(b); + }); + + it.each(['INSERT', 'UPDATE', 'DELETE'])('suppresses every frame for a private %s, not just the row object', async operation => { + const a = open(alice); + const b = open(bob); + await ready(a, b); + const id = randomUUID(); + await write(id, 'INSERT'); + await delivered(a, id, 'INSERT'); + await visible(alice, id, true); + await visible(bob, id, false); + if (operation !== 'INSERT') { + await pause(100); + a.frames.length = b.frames.length = 0; + await write(id, operation); + await delivered(a, id, operation); + } + await silent(b); + }); + + it('does not turn an exact-ID metadata-only subscription into an oracle', async () => { + const id = randomUUID(); + await write(id, 'INSERT'); + const filtered = open(bob, [id], 'subscription($ids: [UUID!]) { secret: onRlsNoteChanged(ids: $ids) { event rowId } }'); + const canary = open(bob, undefined, document, filtered.client); + const a = open(alice); + await ready(a, canary); + await visible(bob, id, false); + await write(id, 'UPDATE'); + await delivered(a, id, 'UPDATE'); + await silent(filtered); + }); + + it.each(['UPDATE', 'DELETE'])('authorizes each row of a mixed-visibility bulk %s with an invisible ID first', async operation => { + const [privateId, ...sharedIds] = [randomUUID(), randomUUID(), randomUUID()].sort(); + const owner = open(alice); + const observer = open(bob); + const filtered = open(bob, [privateId, sharedIds[1]], + 'subscription($ids: [UUID!]) { change: onRlsNoteChanged(ids: $ids) { event rowId } }', observer.client); + await ready(owner, observer); + await write(privateId, 'INSERT'); + await delivered(owner, privateId, 'INSERT'); + for (const id of sharedIds) { + await write(id, 'INSERT', true); + await delivered(owner, id, 'INSERT'); + await delivered(observer, id, 'INSERT'); + } + await delivered(filtered, sharedIds[1], 'INSERT'); + await visible(bob, privateId, false); + for (const id of sharedIds) await visible(bob, id, true); + await pause(100); + for (const stream of streams) stream.frames.length = 0; + const ids = [privateId, ...sharedIds]; + const result = await http(alice, 'mutation($ids: [UUID]!, $op: String!) { bulkWriteRlsNotes(input: {noteIds: $ids, operation: $op}) { result } }', { ids, op: operation }); + expect(result.bulkWriteRlsNotes.result).toBe(true); + await Promise.all([ + ...ids.map(id => delivered(owner, id, operation)), + ...sharedIds.map(id => delivered(observer, id, operation)), + delivered(filtered, sharedIds[1], operation) + ]); + await pause(100); + for (const [stream, expectedIds] of [[owner, ids], [observer, sharedIds], [filtered, [sharedIds[1]]]] as const) { + expect(stream.errors).toEqual([]); + expect(stream.frames.flatMap(frame => frame.errors ?? [])).toEqual([]); + expect(payloads(stream).map(payload => payload.rowId).sort()).toEqual([...expectedIds].sort()); + expect(payloads(stream).map(payload => payload.event)).toEqual(expectedIds.map(() => operation)); + } + for (const payload of payloads(observer)) { + if (operation === 'DELETE') expect(payload.rlsNote).toBeNull(); + else expect(payload.rlsNote).toMatchObject({ id: payload.rowId }); + } + }); + + it('forgets visibility when an UPDATE moves the row out of scope, including later DELETE', async () => { + const a = open(alice); + const b = open(bob); + await ready(a, b); + const id = randomUUID(); + await write(id, 'INSERT', true); + await delivered(a, id, 'INSERT'); await delivered(b, id, 'INSERT'); + await visible(bob, id, true); + a.frames.length = b.frames.length = 0; + await write(id, 'UPDATE', false); + await delivered(a, id, 'UPDATE'); + await visible(bob, id, false); + await write(id, 'DELETE'); + await delivered(a, id, 'DELETE'); + await silent(b); + }); + + it('keeps DELETE visibility history per subscription, even for the same authenticated user', async () => { + const original = open(alice); + await ready(original); + const id = randomUUID(); + await write(id, 'INSERT'); + await delivered(original, id, 'INSERT'); + const fresh = open(alice, undefined, document, original.client); + expect(fresh.client).toBe(original.client); + await ready(original, fresh); + await visible(alice, id, true); + await write(id, 'DELETE'); + await delivered(original, id, 'DELETE'); + await silent(fresh); + }); + + it('delivers 50 visible events and one id-less overflow for an owner bulk insert of 61 rows', async () => { + const owner = open(alice); + const observer = open(charlie); + await ready(owner, observer); + await pause(1100); + const ids = Array.from({ length: 61 }, () => randomUUID()).sort(); + await bulkCreate(alice, ids); + await overflow(owner); + const events = payloads(owner).filter(payload => !payload.overflow); + expect(events).toHaveLength(50); + expect(events.map(payload => payload.rowId)).toEqual(ids.slice(0, 50)); + expect(events.every(payload => payload.rlsNote.id === payload.rowId)).toBe(true); + await silent(observer); + }); + + it('does not send a third user any frame for another user bulk inserting 61 private rows', async () => { + const writer = open(bob); + const observer = open(charlie); + await ready(writer, observer); + await pause(1100); + const ids = Array.from({ length: 61 }, () => randomUUID()).sort(); + await bulkCreate(bob, ids); + await delivered(writer, ids[0], 'INSERT'); + await visible(charlie, ids[0], false); + await silent(observer); + }); + + it('counts only visible rows in a mixed batch with 61 invisible IDs first', async () => { + const owner = open(alice); + const observer = open(bob); + await ready(owner, observer); + await pause(1100); + const ids = Array.from({ length: 64 }, () => randomUUID()).sort(); + const sharedIds = ids.slice(61); + await bulkCreate(alice, ids, sharedIds); + for (const id of sharedIds) await delivered(observer, id, 'INSERT'); + await overflow(owner); + await pause(100); + expect(payloads(observer).map(payload => payload.rowId)).toEqual(sharedIds); + expect(payloads(observer).some(payload => payload.overflow)).toBe(false); + }); + + it('authorizes metadata-only selections, including an aliased subscription field', async () => { + const owner = open(alice); + const observer = open(bob, undefined, 'subscription { change: onRlsNoteChanged { event rowId } }'); + await ready(owner, observer); + const id = randomUUID(); + await write(id, 'INSERT'); + await delivered(owner, id, 'INSERT'); + await silent(observer); + }); + + it.each(['rlsNote { id }', '__typename'])('suppresses hidden frames when selecting only %s', async selection => { + const owner = open(alice); + const observer = open(bob, undefined, `subscription { onRlsNoteChanged { ${selection} } }`); + await ready(owner); + const canary = randomUUID(); + await write(canary, 'INSERT', true); + for (let i = 0; i < 50 && observer.frames.length === 0; i++) { + await write(canary, 'UPDATE'); + await pause(30); + } + expect(observer.errors).toEqual([]); + expect(observer.frames.flatMap(frame => frame.errors ?? [])).toEqual([]); + expect(observer.frames.length).toBeGreaterThan(0); + await pause(100); + owner.frames.length = observer.frames.length = 0; + const id = randomUUID(); + await write(id, 'INSERT'); + await delivered(owner, id, 'INSERT'); + await silent(observer); + }); +}); diff --git a/graphql/server-test/__tests__/websocket.integration.test.ts b/graphql/server-test/__tests__/websocket.integration.test.ts new file mode 100644 index 0000000000..dd59e43324 --- /dev/null +++ b/graphql/server-test/__tests__/websocket.integration.test.ts @@ -0,0 +1,311 @@ +import { requestProtectionLoader } from '@constructive-io/express-context'; +import { context, lambda } from 'grafast'; +import { makeExtendSchemaPlugin } from 'graphile-utils'; +import { createClient } from 'graphql-ws'; +import path from 'path'; +import type { PgTestClient } from 'pgsql-test/test-client'; +import type supertest from 'supertest'; +import WebSocket from 'ws'; + +import { getConnections, seed } from '../src'; +import type { ServerInfo } from '../src/types'; + +jest.setTimeout(60000); + +const HOST = 'app.test.constructive.io'; +const ACTOR = 'bbbbbbbb-0000-4000-8000-000000000002'; +const DATABASE = '80a2eaaf-f77e-4bfe-8506-df929ef1b8d9'; +const shared = path.join(__dirname, '../../../__fixtures__/seed'); +let releasePulse: () => void; +const probe = makeExtendSchemaPlugin({ + typeDefs: 'extend type Subscription { identity: String! pulse: Int! }', + plans: { + Subscription: { + pulse: { + subscribePlan() { + return lambda(context(), async function* () { + yield 0; + await new Promise((resolve) => { releasePulse = resolve; }); + yield 1; + }); + }, + plan: ($event) => $event + }, + identity: { + subscribePlan() { + return lambda(context(), async function* (ctx) { + yield JSON.stringify((ctx as { pgSettings: Record }).pgSettings); + }); + }, + plan: ($event) => $event + } + } + } +}); + +describe('public tenant WebSocket subscriptions', () => { + let pg: PgTestClient; + let db: PgTestClient; + let server: ServerInfo; + let request: supertest.Agent; + let teardown: () => Promise; + let token: string; + + beforeAll(async () => { + ({ pg, db, server, request, teardown } = await getConnections({ + schemas: ['simple-pets-public', 'simple-pets-pets-public'], + graphile: { preset: { plugins: [probe] } }, + server: { useRouting: true, api: { isPublic: true, metaSchemas: [ + 'catalog_private', 'routing_public', 'apps_public', 'metaschema_public', 'metaschema_modules_public' + ] } } + }, [ + seed.pgpm(path.join(shared, '../..')), + seed.sqlfile([ + path.join(shared, 'app-schemas/simple-pets/schema.sql'), + path.join(shared, 'scoped/test-data.sql'), + path.join(__dirname, '../__fixtures__/seed/websocket.sql') + ]) + ])); + const response = await request.post('/graphql').set('Host', HOST).send({ + query: 'mutation($actor: UUID!) { issueSession(input: {actor: $actor}) { result } }', + variables: { actor: ACTOR } + }); + expect(response.body.errors).toBeUndefined(); + token = response.body.data.issueSession.result; + expect(typeof token).toBe('string'); + }); + afterAll(async () => { await teardown?.(); }); + beforeEach(async () => { await pg.beforeEach(); await db.beforeEach(); }); + afterEach(async () => { await db.afterEach(); await pg.afterEach(); }); + + function socketClient(params?: Record, headers: Record = {}, host = HOST) { + class Socket extends WebSocket { + constructor(address: string, protocols: string[]) { + super(address, protocols, { headers: { Host: host, ...headers } }); + } + } + return createClient({ + url: server.graphqlUrl.replace('http:', 'ws:'), + webSocketImpl: Socket, + connectionParams: params, + retryAttempts: 0, + connectionAckWaitTimeout: 3000 + }); + } + + async function subscribe(params?: Record, headers: Record = {}, query = 'subscription { identity }', host = HOST): Promise { + const client = socketClient(params, headers, host); + let unsubscribe = () => {}; + try { + return await new Promise((resolve, reject) => { + const timeout = setTimeout(() => reject(new Error('No WebSocket result')), 5000); + unsubscribe = client.subscribe({ query }, { + next: (value) => { clearTimeout(timeout); resolve(value); }, + error: (error) => { clearTimeout(timeout); reject(error); }, + complete: () => { clearTimeout(timeout); } + }); + }); + } finally { + unsubscribe(); + await client.dispose(); + } + } + + it('delivers a real subscription using connectionParams-only authentication and tenant pgSettings', async () => { + const result = await subscribe({ Authorization: `Bearer ${token}` }); + expect(result.errors).toBeUndefined(); + expect(JSON.parse(result.data.identity)).toMatchObject({ + role: 'authenticated', + 'jwt.claims.user_id': ACTOR, + 'jwt.claims.database_id': DATABASE, + 'jwt.claims.api_id': '6c9997a4-591b-4cb3-9313-4ef45d6f134e' + }); + }); + + it('accepts a bearer header without connection parameters', async () => { + const result = await subscribe(undefined, { Authorization: `Bearer ${token}` }); + expect(JSON.parse(result.data.identity)['jwt.claims.user_id']).toBe(ACTOR); + }); + + it.each([ + { query: `subscription { identity } #${'é'.repeat(600)}` }, + { query: 'subscription { identity }', variables: { value: 'é'.repeat(600) } } + ])('refuses oversized subscription payloads in UTF-8 bytes: %#', async (payload) => { + expect(JSON.stringify(payload).length).toBeLessThan(1024); + expect(Buffer.byteLength(JSON.stringify(payload))).toBeGreaterThan(1024); + const client = socketClient({ Authorization: `Bearer ${token}` }); + try { + const result = await new Promise((resolve) => { + client.subscribe(payload, { + next: resolve, + error: resolve, + complete: () => resolve('unexpected completion') + }); + }); + expect(result).toEqual(expect.arrayContaining([ + expect.objectContaining({ extensions: expect.objectContaining({ code: 'REQUEST_TOO_LARGE' }) }) + ])); + } finally { + await client.dispose(); + } + }); + + it('rechecks payload bytes after refreshing protection on an existing socket', async () => { + const saved = await pg.one('SELECT max_request_bytes FROM routing_public.database_settings WHERE database_id = $1', [DATABASE]); + const client = socketClient({ Authorization: `Bearer ${token}` }); + const frames: any[] = []; + const failures: unknown[] = []; + let first!: () => void; + let complete!: () => void; + const started = new Promise(resolve => { first = resolve; }); + const finished = new Promise(resolve => { complete = resolve; }); + let stop = () => {}; + try { + await pg.query('UPDATE routing_public.database_settings SET max_request_bytes = 8192 WHERE database_id = $1', [DATABASE]); + await pg.publish(); + requestProtectionLoader.invalidate(DATABASE); + stop = client.subscribe({ query: 'subscription { pulse }' }, { + next: value => { frames.push(value); first(); }, + error: error => { failures.push(error); first(); complete(); }, + complete + }); + await started; + expect(failures).toEqual([]); + expect(frames[0].data.pulse).toBe(0); + await pg.query('UPDATE routing_public.database_settings SET max_request_bytes = 1024 WHERE database_id = $1', [DATABASE]); + await pg.publish(); + requestProtectionLoader.invalidate(DATABASE); + const payload = { query: `subscription { identity } #${'a'.repeat(2048)}` }; + const bytes = Buffer.byteLength(JSON.stringify(payload)); + expect(bytes).toBeGreaterThan(1024); + expect(bytes).toBeLessThan(8192); + const result = await new Promise(resolve => { + client.subscribe(payload, { next: resolve, error: resolve, complete: () => resolve('unexpected completion') }); + }); + expect(result).toEqual(expect.arrayContaining([ + expect.objectContaining({ extensions: expect.objectContaining({ code: 'REQUEST_TOO_LARGE' }) }) + ])); + releasePulse(); + await finished; + expect(failures).toEqual([]); + expect(frames.flatMap(frame => frame.errors ?? [])).toEqual([]); + expect(frames.map(frame => frame.data.pulse)).toEqual([0, 1]); + } finally { + releasePulse?.(); + stop(); + await client.dispose(); + await pg.query('UPDATE routing_public.database_settings SET max_request_bytes = $1 WHERE database_id = $2', [saved.max_request_bytes, DATABASE]); + await pg.publish(); + requestProtectionLoader.invalidate(DATABASE); + } + }); + + it('refuses upgrades before the handshake when open sockets exhaust the shared HTTP budget', async () => { + const sockets: WebSocket[] = []; + try { + for (let i = 0; i < 2; i++) { + await new Promise((resolve, reject) => { + const socket = new WebSocket(server.graphqlUrl.replace('http:', 'ws:'), 'graphql-transport-ws', { headers: { Host: HOST } }); + sockets.push(socket); + socket.once('open', () => socket.send(JSON.stringify({ type: 'connection_init', payload: { Authorization: `Bearer ${token}` } }))); + socket.once('message', data => { + if (JSON.parse(data.toString()).type === 'connection_ack') resolve(); + else reject(new Error('Expected connection_ack')); + }); + socket.once('error', reject); + }); + } + const status = await new Promise((resolve, reject) => { + const socket = new WebSocket(server.graphqlUrl.replace('http:', 'ws:'), 'graphql-transport-ws', { headers: { Host: HOST } }); + socket.on('error', () => {}); + socket.once('unexpected-response', (_req, response) => { + response.resume(); + socket.terminate(); + resolve(response.statusCode); + }); + socket.once('open', () => { socket.close(); reject(new Error('Upgrade bypassed admission')); }); + }); + expect(status).toBe(429); + const refused = await request.post('/graphql').set('Host', HOST).send({ query: '{ __typename }' }); + expect(refused.status).toBe(429); + expect(refused.body.errors[0].extensions.code).toBe('CONCURRENCY_LIMIT_REACHED'); + await new Promise(resolve => { + sockets[0].once('close', resolve); + sockets[0].close(); + }); + } finally { + await Promise.all(sockets.map((socket) => new Promise((resolve) => { + if (socket.readyState === WebSocket.CLOSED) return resolve(); + socket.once('close', resolve); + if (socket.readyState === WebSocket.CONNECTING) socket.terminate(); + else socket.close(); + }))); + } + const accepted = await request.post('/graphql').set('Host', HOST).send({ query: '{ __typename }' }); + expect(accepted.status).toBe(200); + expect(accepted.body.errors).toBeUndefined(); + }); + + it('keeps another subscription alive when an operation has malformed GraphQL', async () => { + const client = socketClient({ Authorization: `Bearer ${token}` }); + const values: number[] = []; + let first: () => void; + const started = new Promise((resolve) => { first = resolve; }); + let stop = () => {}; + try { + const finished = new Promise((resolve, reject) => { + stop = client.subscribe({ query: 'subscription { pulse }' }, { + next: (result) => { values.push(result.data.pulse as number); first(); }, + error: reject, + complete: resolve + }); + }); + await started; + const malformed = await new Promise((resolve) => { + client.subscribe({ query: 'subscription {' }, { + next: resolve, + error: resolve, + complete: () => resolve('unexpected completion') + }); + }); + expect(malformed).toEqual(expect.arrayContaining([ + expect.objectContaining({ message: expect.stringContaining('Syntax Error') }) + ])); + releasePulse(); + await finished; + expect(values).toEqual([0, 1]); + } finally { + releasePulse?.(); + stop(); + await client.dispose(); + } + }); + + it.each([undefined, { Authorization: 'Bearer garbage' }])('refuses missing or invalid bearer credentials: %j', async (params) => { + await expect(subscribe(params)).rejects.toEqual(expect.arrayContaining([ + expect.objectContaining({ extensions: expect.objectContaining({ code: 'UNAUTHENTICATED' }) }) + ])); + }); + + it('does not fall back to a valid handshake bearer when connectionParams are invalid', async () => { + await expect(subscribe({ Authorization: 'Bearer garbage' }, { Authorization: `Bearer ${token}` })).rejects.toEqual(expect.arrayContaining([ + expect.objectContaining({ extensions: expect.objectContaining({ code: 'UNAUTHENTICATED' }) }) + ])); + }); + + it('does not use ambient session cookies as WebSocket credentials', async () => { + await expect(subscribe(undefined, { Cookie: `constructive_session=${token}` })).rejects.toEqual(expect.arrayContaining([ + expect.objectContaining({ extensions: expect.objectContaining({ code: 'UNAUTHENTICATED' }) }) + ])); + }); + + it('refuses mutations on the subscription-only transport', async () => { + await expect(subscribe({ Authorization: `Bearer ${token}` }, {}, 'mutation { issueSession(input: {actor: "' + ACTOR + '"}) { result } }')).rejects.toEqual(expect.arrayContaining([ + expect.objectContaining({ message: 'WebSocket transport only accepts subscriptions' }) + ])); + }); + + it('does not route unknown hosts to another tenant', async () => { + await expect(subscribe({ Authorization: `Bearer ${token}` }, {}, 'subscription { identity }', 'absent.test.constructive.io')).rejects.toMatchObject({ message: expect.stringMatching(/404/) }); + }); +}); diff --git a/graphql/server-test/package.json b/graphql/server-test/package.json index 575ba37e81..417aa2df61 100644 --- a/graphql/server-test/package.json +++ b/graphql/server-test/package.json @@ -25,7 +25,7 @@ "build": "makage build", "build:dev": "makage build --dev", "lint": "eslint . --fix", - "test": "jest", + "test": "node --experimental-vm-modules ../../node_modules/jest/bin/jest.js", "test:watch": "jest --watch" }, "devDependencies": { @@ -39,14 +39,19 @@ "@types/express": "^5.0.6", "@types/pg": "^8.20.4", "@types/supertest": "^7.2.1", + "@types/ws": "^8.18.1", "agentic-server": "workspace:^", "appstash": "^0.8.0", "gql-ast": "workspace:^", + "grafast": "1.1.2", "graphile-cache": "workspace:^", "graphile-llm": "workspace:^", + "graphile-utils": "5.0.3", + "graphql-ws": "^6.0.8", "inquirerer": "^4.9.4", "makage": "^0.8.0", - "nested-obj": "^0.2.3" + "nested-obj": "^0.2.3", + "ws": "^8.21.3" }, "dependencies": { "@constructive-io/express-context": "workspace:^", diff --git a/graphql/server/src/middleware/__tests__/admission-control.test.ts b/graphql/server/src/middleware/__tests__/admission-control.test.ts index dad024358d..e4a15b10a6 100644 --- a/graphql/server/src/middleware/__tests__/admission-control.test.ts +++ b/graphql/server/src/middleware/__tests__/admission-control.test.ts @@ -6,6 +6,10 @@ import type { NextFunction, Request, Response } from 'express'; import { installRefusalRecorder } from '../../refusals/recorder'; import { createAdmissionControlMiddleware } from '../admission-control'; +jest.mock('../websocket', () => ({ + isWebSocketUpgrade: (req: Request) => req.headers.upgrade === 'websocket' +})); + const protection = (overrides: Partial): RequestProtection => ({ ...DEFAULT_REQUEST_PROTECTION, ...overrides @@ -75,6 +79,27 @@ const send = ( }; describe('createAdmissionControlMiddleware', () => { + it('holds a shared concurrency slot until an upgraded socket closes', async () => { + const middleware = createAdmissionControlMiddleware({ trustedProxyHops: 0 }); + const bounds = protection({ maxConcurrentRequests: 1, maxQueueWaitMs: 0 }); + const req = fakeReq({ protection: bounds }); + req.headers.upgrade = 'websocket'; + const socket = Object.assign(new EventEmitter(), { remoteAddress: '10.0.0.1' }); + Object.assign(req, { socket }); + const upgrade = send(middleware, req); + await upgrade.done; + expect(upgrade.next).toHaveBeenCalledTimes(1); + upgrade.res.emit('close'); + const refused = send(middleware, fakeReq({ protection: bounds })); + await refused.done; + expect(refused.res.captured.status).toBe(429); + socket.emit('close'); + const accepted = send(middleware, fakeReq({ protection: bounds })); + await accepted.done; + expect(accepted.next).toHaveBeenCalledTimes(1); + accepted.res.emit('finish'); + }); + it('admits a request under both bounds', async () => { const middleware = createAdmissionControlMiddleware({ trustedProxyHops: 0 }); const { next, res, done } = send(middleware, fakeReq()); diff --git a/graphql/server/src/middleware/admission-control.ts b/graphql/server/src/middleware/admission-control.ts index 31e89fc7ef..97ce013f56 100644 --- a/graphql/server/src/middleware/admission-control.ts +++ b/graphql/server/src/middleware/admission-control.ts @@ -14,6 +14,7 @@ import type { NextFunction, Request, RequestHandler, Response } from 'express'; import { respondWithGraphQLError } from '../errors/graphql-response'; import { recordRefusal } from '../refusals/recorder'; import { resolveProxyHops } from './client-ip'; +import { isWebSocketUpgrade } from './websocket'; const log = new Logger('admission'); @@ -112,7 +113,9 @@ export const createAdmissionControlMiddleware = ( // attached only after `acquire` resolves misses a hang-up during it. const gone = new AbortController(); const onClose = () => gone.abort(); - res.once('close', onClose); + // An upgraded socket holds one slot for its entire lifetime. + const lifetime = isWebSocketUpgrade(req) ? req.socket : res; + lifetime.once('close', onClose); let lease: AdmissionLease; try { @@ -122,11 +125,11 @@ export const createAdmissionControlMiddleware = ( signal: gone.signal }); } catch (e) { - res.off('close', onClose); + lifetime.off('close', onClose); next(e); return; } - res.off('close', onClose); + lifetime.off('close', onClose); if (gone.signal.aborted) { lease.release(); @@ -162,7 +165,7 @@ export const createAdmissionControlMiddleware = ( // until the process restarts, and a client that retries on abort would // drain the tenant's budget one leaked slot at a time. `release` is // idempotent, so both listeners can fire. - res.on('close', () => lease.release()); + lifetime.on('close', () => lease.release()); res.on('finish', () => lease.release()); next(); }; diff --git a/graphql/server/src/middleware/api.ts b/graphql/server/src/middleware/api.ts index e186bfbc24..62bba4b384 100644 --- a/graphql/server/src/middleware/api.ts +++ b/graphql/server/src/middleware/api.ts @@ -98,6 +98,7 @@ interface RoutingHeaders { interface ResolvedModuleSettings { rlsModule?: RlsModule; + realtimeModule?: { schemaName: string }; authSettings?: AuthSettings; corsOrigins?: string[]; databaseSettings?: DatabaseSettings; @@ -146,6 +147,9 @@ const resolveModuleSettings = async ( return { rlsModule, + realtimeModule: databaseSettings?.enableRealtime + ? await registry.resolve<{ schemaName: string }>('realtimeModule', ctx) + : undefined, authSettings, corsOrigins, databaseSettings, @@ -234,6 +238,7 @@ const toApiStructure = (row: ApiRow, opts: ApiOptions, settings: ResolvedModuleS roleName: requireApiRole('role_name', row.role_name, row.api_id), schema: row.schemas || [], rlsModule: settings.rlsModule, + realtimeModule: settings.realtimeModule, domains: [], databaseId: row.database_id, isPublic: row.is_public, @@ -373,6 +378,7 @@ const resolveScopedRoute = async (ctx: ResolveContext): Promise { return authType?.toLowerCase() === 'bearer' && authToken ? authToken : undefined; }; -export const createAuthenticateMiddleware = ( +export const authenticateRequest = async ( + req: Request, opts: PgpmOptions -): RequestHandler => { - return async ( - req: Request, - res: Response, - next: NextFunction - ): Promise => { - const api = req.api; - log.info(`[auth] middleware called, api=${api ? 'present' : 'missing'}`); - if (!api) { - res.status(500).send('Missing API info'); - return; - } - - const pool = api.tenantPool; - const rlsModule = api.rlsModule; - - log.info( - `[auth] rlsModule=${rlsModule ? 'present' : 'missing'}, ` + +): Promise<{ error: ConstructiveError; status?: number } | undefined> => { + const api = req.api; + log.info(`[auth] middleware called, api=${api ? 'present' : 'missing'}`); + if (!api) { + throw new Error('Missing API info'); + } + + const pool = api.tenantPool; + const rlsModule = api.rlsModule; + + log.info( + `[auth] rlsModule=${rlsModule ? 'present' : 'missing'}, ` + `authenticate=${rlsModule?.authenticate ?? 'none'}, ` + `authenticateStrict=${rlsModule?.authenticateStrict ?? 'none'}, ` + `privateSchema=${rlsModule?.privateSchema?.schemaName ?? 'none'}` - ); + ); - if ( - opts.server?.strictAuth && + if ( + opts.server?.strictAuth && !(rlsModule?.authenticateStrict && rlsModule.privateSchema?.schemaName) - ) { - log.error(`[auth] strictAuth is on but API ${api.apiId ?? 'unknown'} has no authenticateStrict; refusing`); - respondWithError(req, res, errors.STRICT_AUTH_UNAVAILABLE(), { status: 503 }); - return; - } - - if (!rlsModule) { - log.info('[auth] No RLS module configured, skipping auth'); - return next(); - } - - const authFn = opts.server?.strictAuth - ? rlsModule.authenticateStrict - : rlsModule.authenticate; + ) { + log.error(`[auth] strictAuth is on but API ${api.apiId ?? 'unknown'} has no authenticateStrict; refusing`); + return { error: errors.STRICT_AUTH_UNAVAILABLE(), status: 503 }; + } + + if (!rlsModule) { + log.info('[auth] No RLS module configured, skipping auth'); + return; + } + + const authFn = opts.server?.strictAuth + ? rlsModule.authenticateStrict + : rlsModule.authenticate; + + log.info( + `[auth] strictAuth=${opts.server?.strictAuth ?? false}, authFn=${authFn ?? 'none'}` + ); + + if (authFn && rlsModule.privateSchema.schemaName) { + const { authorization = '' } = req.headers; + const [authType] = authorization.split(' '); + const bearerToken = getBearerToken(req); + let token: any = {}; log.info( - `[auth] strictAuth=${opts.server?.strictAuth ?? false}, authFn=${authFn ?? 'none'}` + `[auth] authorization header present=${!!authorization}, ` + + `authType=${authType ?? 'none'}, hasToken=${!!bearerToken}` ); - if (authFn && rlsModule.privateSchema.schemaName) { - const { authorization = '' } = req.headers; - const [authType] = authorization.split(' '); - const bearerToken = getBearerToken(req); - let token: any = {}; + // Resolve the credential: prefer Bearer header, fall back to session cookie + const cookieToken = parseCookieToken(req, SESSION_COOKIE_NAME); + const effectiveToken = bearerToken ?? cookieToken; + const tokenSource = bearerToken ? 'bearer' : (cookieToken ? 'cookie' : 'none'); - log.info( - `[auth] authorization header present=${!!authorization}, ` + - `authType=${authType ?? 'none'}, hasToken=${!!bearerToken}` - ); + if (effectiveToken) { + log.info(`[auth] Processing ${tokenSource} authentication`); + const context: Record = { + 'jwt.claims.ip_address': req.clientIp, + }; - // Resolve the credential: prefer Bearer header, fall back to session cookie - const cookieToken = parseCookieToken(req, SESSION_COOKIE_NAME); - const effectiveToken = bearerToken ?? cookieToken; - const tokenSource = bearerToken ? 'bearer' : (cookieToken ? 'cookie' : 'none'); + if (req.get('origin')) { + context['jwt.claims.origin'] = req.get('origin'); + } + if (req.get('User-Agent')) { + context['jwt.claims.user_agent'] = req.get('User-Agent'); + } - if (effectiveToken) { - log.info(`[auth] Processing ${tokenSource} authentication`); - const context: Record = { - 'jwt.claims.ip_address': req.clientIp, - }; + const authQuery = `SELECT * FROM "${rlsModule.privateSchema.schemaName}"."${authFn}"($1)`; + log.info(`[auth] Executing auth query: ${authQuery}`); - if (req.get('origin')) { - context['jwt.claims.origin'] = req.get('origin'); - } - if (req.get('User-Agent')) { - context['jwt.claims.user_agent'] = req.get('User-Agent'); - } + try { + const result = await pgQueryContext({ + client: pool, + context, + query: authQuery, + variables: [effectiveToken], + }); + + log.info(`[auth] Query result: rowCount=${result?.rowCount}`); - const authQuery = `SELECT * FROM "${rlsModule.privateSchema.schemaName}"."${authFn}"($1)`; - log.info(`[auth] Executing auth query: ${authQuery}`); - - try { - const result = await pgQueryContext({ - client: pool, - context, - query: authQuery, - variables: [effectiveToken], - }); - - log.info(`[auth] Query result: rowCount=${result?.rowCount}`); - - if (result?.rowCount === 0) { - log.info('[auth] No rows returned, returning UNAUTHENTICATED'); - respondWithError(req, res, errors.UNAUTHENTICATED()); - return; - } - - token = result.rows[0]; - log.info(`[auth] Auth success: role=${token.role}, user_id=${token.user_id}`); - } catch (e: any) { - log.error('[auth] Auth error:', e.message); - respondWithError( - req, - res, - errors.INTERNAL_FAILURE({ - details: isDev() ? e.message : 'authentication failed', - }) - ); - return; + if (result?.rowCount === 0) { + log.info('[auth] No rows returned, returning UNAUTHENTICATED'); + return { error: errors.UNAUTHENTICATED() }; } - } else { - log.info('[auth] No credential provided (no bearer token or session cookie), using anonymous auth'); - } - req.token = token; + token = result.rows[0]; + log.info(`[auth] Auth success: role=${token.role}, user_id=${token.user_id}`); + } catch (e: any) { + log.error('[auth] Auth error:', e.message); + return { error: errors.INTERNAL_FAILURE({ + details: isDev() ? e.message : 'authentication failed', + }) }; + } } else { - log.info( - `[auth] Skipping auth: authFn=${authFn ?? 'none'}, ` + - `privateSchema=${rlsModule.privateSchema?.schemaName ?? 'none'}` - ); + log.info('[auth] No credential provided (no bearer token or session cookie), using anonymous auth'); } - // Read device token cookie for trusted device tracking - const deviceToken = parseCookieToken(req, DEVICE_TOKEN_COOKIE_NAME); - if (deviceToken) { - req.deviceToken = deviceToken; - log.info('[auth] Device token cookie present'); - } + req.token = token; + } else { + log.info( + `[auth] Skipping auth: authFn=${authFn ?? 'none'}, ` + + `privateSchema=${rlsModule.privateSchema?.schemaName ?? 'none'}` + ); + } + // Read device token cookie for trusted device tracking + const deviceToken = parseCookieToken(req, DEVICE_TOKEN_COOKIE_NAME); + if (deviceToken) { + req.deviceToken = deviceToken; + log.info('[auth] Device token cookie present'); + } + +}; + +export const createAuthenticateMiddleware = (opts: PgpmOptions): RequestHandler => { + return async (req: Request, res: Response, next: NextFunction): Promise => { + if (!req.api) { + res.status(500).send('Missing API info'); + return; + } + const failure = await authenticateRequest(req, opts); + if (failure) { + respondWithError(req, res, failure.error, { status: failure.status }); + return; + } next(); }; }; diff --git a/graphql/server/src/middleware/graphile.ts b/graphql/server/src/middleware/graphile.ts index 206441952e..7c8a2610ef 100644 --- a/graphql/server/src/middleware/graphile.ts +++ b/graphql/server/src/middleware/graphile.ts @@ -19,6 +19,8 @@ import { createConstructivePreset, createGrafastCacheLimitsPreset } from 'graphile-settings'; +import { getOperationAST, GraphQLError, parse } from 'graphql'; +import type { IncomingMessage } from 'http'; import { isGraphqlObservabilityEnabled } from '../diagnostics/observability'; import errorPage404Message from '../errors/404-message'; @@ -30,12 +32,14 @@ import { createErrorEventsPlugin } from '../plugins/error-events-plugin'; import { OwnerHandoffPlugin } from '../plugins/owner-handoff-plugin'; import { RequestProtectionPlugin } from '../plugins/request-protection-plugin'; import { WebauthnPlugin } from '../plugins/webauthn-plugin'; +import { recordRefusal } from '../refusals/recorder'; import type { ApiOptions, DatabaseSettings } from '../types'; import { getApiConfig, isApiError } from './api'; import { generationOf } from './cache-generation'; import { formatError } from './format-error'; import { makeIntrospectionWiring } from './graphile-introspection'; import { observeGraphileBuild } from './observability/graphile-build-stats'; +import { authenticatedWebSocketRequest, forwardWebSocketUpgrade } from './websocket'; // ============================================================================= // Single-Flight Pattern: In-Flight Tracking @@ -93,7 +97,8 @@ const buildPreset = ( apiId?: string, compute?: ComputeConfig, webauthn?: boolean, - platform?: boolean + platform?: boolean, + serverOptions: ConstructiveOptions = {} ): GraphileConfig.Preset => { const introspection = makeIntrospectionWiring(pool, schemas, graphileOptions, introspectionRole); const configuredPreset = graphileOptions?.preset ?? {}; @@ -118,6 +123,45 @@ const buildPreset = ( RequestProtectionPlugin, CaptchaPlugin, createErrorEventsPlugin(pool), + { + name: 'WebSocketSubscriptionOnlyPlugin', + version: '0.0.0', + grafserv: { + middleware: { + async onSubscribe(next, event) { + const req = (event.ctx.extra as { request: Request }).request; + const limit = (req.requestProtection ?? DEFAULT_REQUEST_PROTECTION).maxRequestBytes; + const bytes = Buffer.byteLength(JSON.stringify(event.message.payload), 'utf8'); + if (bytes > limit) { + recordRefusal(req, 'request_too_large'); + const error = errors.REQUEST_TOO_LARGE({ bytes, limit }); + return [new GraphQLError(error.message, { extensions: error.toExtensions() })]; + } + let operation; + try { + operation = getOperationAST(parse(event.message.payload.query), event.message.payload.operationName); + } catch (error) { + if (error instanceof GraphQLError) return [error]; + throw error; + } + if (operation?.operation !== 'subscription') { + return [new GraphQLError('WebSocket transport only accepts subscriptions')]; + } + const result = await next(); + if (result && !Array.isArray(result)) { + const refreshed = (result as { requestContext?: { ws?: { request?: Request } } }).requestContext?.ws?.request; + const refreshedLimit = (refreshed?.requestProtection ?? DEFAULT_REQUEST_PROTECTION).maxRequestBytes; + if (refreshed && bytes > refreshedLimit) { + recordRefusal(refreshed, 'request_too_large'); + const error = errors.REQUEST_TOO_LARGE({ bytes, limit: refreshedLimit }); + return [new GraphQLError(error.message, { extensions: error.toExtensions() })]; + } + } + return result; + } + } + } + }, // Only when the tenant provisioned the WebAuthn module; the policy // itself is read per request from `req.api.webauthnSettings`. ...(webauthn ? [WebauthnPlugin] : []), @@ -151,6 +195,7 @@ const buildPreset = ( pgScopedIntrospection: introspection.pgScopedIntrospection }, grafserv: { + websockets: databaseSettings?.enableRealtime === true, graphqlPath: '/graphql', graphiqlPath: '/graphiql', graphiql: true, @@ -159,9 +204,13 @@ const buildPreset = ( }, grafast: { explain: graphileOptions?.explain === true, - context: (requestContext: Partial) => { + context: async (requestContext: Partial) => { // In grafserv/express/v4, the request is available at requestContext.expressv4.req - const req = (requestContext as { expressv4?: { req?: Request } })?.expressv4?.req; + const ws = (requestContext as { ws?: { request: IncomingMessage; normalizedConnectionParams?: Record } }).ws; + const req = ws + ? await authenticatedWebSocketRequest(ws.request, ws.normalizedConnectionParams, serverOptions) + : (requestContext as { expressv4?: { req?: Request } })?.expressv4?.req; + if (ws && req) ws.request = req; const context: Record = {}; // Timeouts travel with the transaction as GUCs, so they bound the work @@ -420,7 +469,8 @@ export const graphile = (opts: ConstructiveOptions): RequestHandler => { api.apiId, compute, Boolean(api.webauthnSettings), - platform?.platform + platform?.platform, + opts ); const instance = await observeGraphileBuild( { @@ -431,6 +481,7 @@ export const graphile = (opts: ConstructiveOptions): RequestHandler => { () => createGraphileInstance({ preset, cacheKey: key, + realtimeSchema: api.realtimeModule?.schemaName, enableRealtime: api.databaseSettings?.enableRealtime }), { enabled: observabilityEnabled } @@ -525,6 +576,7 @@ export const graphile = (opts: ConstructiveOptions): RequestHandler => { api = resolved; continue; } + if (forwardWebSocketUpgrade(req, res, instance)) return; return instance.handler(req, res, next); } } catch (e: any) { diff --git a/graphql/server/src/middleware/websocket.ts b/graphql/server/src/middleware/websocket.ts new file mode 100644 index 0000000000..feac691186 --- /dev/null +++ b/graphql/server/src/middleware/websocket.ts @@ -0,0 +1,78 @@ +import { buildContext, createDefaultRegistry, DEFAULT_REQUEST_PROTECTION } from '@constructive-io/express-context'; +import type { ConstructiveOptions } from '@constructive-io/graphql-types'; +import type { Express, Request, Response } from 'express'; +import { SafeError } from 'grafast'; +import type { GraphileCacheEntry } from 'graphile-cache'; +import { IncomingMessage, ServerResponse } from 'http'; +import type { Socket } from 'net'; +import type { Duplex } from 'stream'; + +import { authenticateRequest, getBearerToken } from './auth'; + +const upgrades = new WeakMap(); +const loaders = createDefaultRegistry(); + +export const isWebSocketUpgrade = (req: IncomingMessage): boolean => upgrades.has(req); + +export function routeWebSocketUpgrade(app: Express, req: IncomingMessage, socket: Duplex, head: Buffer): void { + if (req.url?.split('?')[0] !== '/graphql') { + socket.end('HTTP/1.1 404 Not Found\r\nConnection: close\r\n\r\n'); + return; + } + upgrades.set(req, { socket, head }); + const res = new ServerResponse(req); + res.assignSocket(socket as Socket); + res.once('finish', () => socket.end()); + socket.once('error', () => socket.destroy()); + app(req, res); +} + +export function forwardWebSocketUpgrade(req: Request, res: Response, instance: GraphileCacheEntry): boolean { + const upgrade = upgrades.get(req); + if (!upgrade) return false; + upgrades.delete(req); + const { socket, head } = upgrade; + if (!instance.httpServer.listenerCount('upgrade')) { + res.status(404).end(); + return true; + } + res.detachSocket(socket as Socket); + instance.httpServer.emit('upgrade', req, socket, head); + return true; +} + +export async function authenticatedWebSocketRequest( + request: IncomingMessage, + params: Record | undefined, + opts: ConstructiveOptions +): Promise { + const req = Object.create(request) as Request; + req.headers = { ...request.headers }; + req.token = undefined; + const requiresAuth = req.api?.isPublic !== false && !!req.api?.rlsModule; + delete req.headers.cookie; + const authorizations = Object.entries(params ?? {}).filter(([key]) => key.toLowerCase() === 'authorization'); + if (authorizations.length) { + if (authorizations.length !== 1 || typeof authorizations[0][1] !== 'string') { + throw new SafeError('Invalid authorization', { code: 'UNAUTHENTICATED' }); + } + req.headers.authorization = authorizations[0][1]; + } + if (!getBearerToken(req) && requiresAuth) { + throw new SafeError('Authentication required', { code: 'UNAUTHENTICATED' }); + } + const failure = await authenticateRequest(req, opts); + if (failure) { + throw new SafeError(failure.error.message, failure.error.toExtensions()); + } + if (!req.token && requiresAuth) { + throw new SafeError('Authentication required', { code: 'UNAUTHENTICATED' }); + } + req.constructive = buildContext(req, { pg: opts.pg, loaders }); + const standing = await req.constructive?.useModule('standing'); + if (standing && (!standing.exists || standing.suspended)) { + throw new SafeError('Access suspended', { code: 'ACCESS_SUSPENDED' }); + } + req.requestProtection = await req.constructive?.useModule('requestProtection') ?? DEFAULT_REQUEST_PROTECTION; + return req; +} diff --git a/graphql/server/src/plugins/request-protection-plugin.ts b/graphql/server/src/plugins/request-protection-plugin.ts index 3225e6bcbf..b2fac31b4c 100644 --- a/graphql/server/src/plugins/request-protection-plugin.ts +++ b/graphql/server/src/plugins/request-protection-plugin.ts @@ -30,7 +30,10 @@ export const documentRefusalReason = (err: unknown): RefusalReason | undefined = */ const getExpressRequest = ( requestContext: Partial | undefined -): Request | undefined => (requestContext as { expressv4?: { req?: Request } })?.expressv4?.req; +): Request | undefined => { + const ctx = requestContext as { expressv4?: { req?: Request }; ws?: { request?: Request } }; + return ctx?.expressv4?.req ?? ctx?.ws?.request; +}; /** * Check the operation against the tenant's bounds. Returns the refusal as a diff --git a/graphql/server/src/server.ts b/graphql/server/src/server.ts index 124d6cf1a3..1734c03989 100644 --- a/graphql/server/src/server.ts +++ b/graphql/server/src/server.ts @@ -13,6 +13,7 @@ import { closeAllCaches,graphileCache } from 'graphile-cache'; import type { Server as HttpServer } from 'http'; import { Notification, Pool, PoolClient } from 'pg'; import { getPgPool } from 'pg-cache'; +import type { Duplex } from 'stream'; import { createAgenticRouter } from './agentic'; import { closeDebugDatabasePools } from './diagnostics/debug-db-snapshot'; @@ -42,6 +43,7 @@ import { localObservabilityOnly } from './middleware/observability/guard'; import { createRequestLogger } from './middleware/observability/request-logger'; import { createRequestProtectionMiddleware } from './middleware/request-protection'; import { createStandingMiddleware } from './middleware/standing'; +import { isWebSocketUpgrade, routeWebSocketUpgrade } from './middleware/websocket'; import { createPlatformRefusalRecorder, installRefusalRecorder } from './refusals/recorder'; const log = new Logger('server'); @@ -89,6 +91,7 @@ class Server { private shuttingDown = false; private closed = false; private httpServer: HttpServer | null = null; + private webSockets = new Set(); private debugSampler: DebugSamplerHandle | null = null; private refusalRecorder: RefusalRecorder | null = null; @@ -168,7 +171,7 @@ class Server { app.use(corsForRoutedApi); app.use(api); app.use(corsForRoutedApi); - app.use(authenticate); + app.use((req, res, next) => isWebSocketUpgrade(req) ? next() : authenticate(req, res, next)); app.use(createContextMiddleware({ pg: effectiveOpts.pg, loaders: createDefaultRegistry() @@ -186,6 +189,10 @@ class Server { // sit in the budget for the life of the stream. The other lanes need // their own bound sized for streaming, not this one. app.use('/graphql', createAdmissionControlMiddleware()); + const graphileMiddleware = graphile(effectiveOpts); + app.use((req, res, next) => isWebSocketUpgrade(req) + ? graphileMiddleware(req, res, next) + : next()); // CSRF protection for cookie-authenticated requests // Skip CSRF for Bearer token auth (not vulnerable to CSRF) and anonymous requests @@ -227,7 +234,7 @@ class Server { // REST function invocation routes (POST /fn/:alias, GET /fn/invocations/:id) app.use(createFnRouter()); - app.use(graphile(effectiveOpts)); + app.use(graphileMiddleware); app.use(createFlushMiddleware(effectiveOpts)); // Error handling - MUST be LAST @@ -250,6 +257,12 @@ class Server { log.info(`listening at http://${server?.host}:${server?.port}`) ); + httpServer.on('upgrade', (req, socket, head) => { + this.webSockets.add(socket); + socket.once('close', () => this.webSockets.delete(socket)); + routeWebSocketUpgrade(this.app, req, socket, head); + }); + httpServer.on('error', (err: NodeJS.ErrnoException) => { if (err.code === 'EADDRINUSE') { this.error(`Port ${server?.port ?? 'unknown'} is already in use`, err); @@ -409,6 +422,7 @@ class Server { this.debugSampler = null; } if (this.httpServer?.listening) { + for (const socket of this.webSockets) socket.destroy(); await new Promise((resolve) => this.httpServer!.close(() => resolve())); } await closeDebugDatabasePools(); diff --git a/graphql/test/__tests__/graphile-test.bulk-client.test.ts b/graphql/test/__tests__/graphile-test.bulk-client.test.ts new file mode 100644 index 0000000000..04c0511f98 --- /dev/null +++ b/graphql/test/__tests__/graphile-test.bulk-client.test.ts @@ -0,0 +1,147 @@ +import { readFileSync } from 'fs'; +import { execute } from 'grafast'; +import { makeSchema } from 'graphile-build'; +import { createConstructivePreset, makePgService } from 'graphile-settings'; +import type { GraphQLQueryFnObj } from 'graphile-test'; +import type { GraphQLInputObjectType } from 'graphql'; +import { getNamedType, parse } from 'graphql'; +import { join } from 'path'; +import { getWithPgClientFromPgService } from 'postgraphile/@dataplan/pg'; +import { getConnections, seed } from 'pgsql-test'; +import type { PgTestClient } from 'pgsql-test/test-client'; + +let pg: PgTestClient; +let db: PgTestClient; +let query: GraphQLQueryFnObj; +let teardown: () => Promise; +let service: ReturnType; +let withPgClient: Awaited>; + +const returning = 'id name quantity createdAt localTime day metadata labels state history position { x label } optionalAt'; + +function expectTypedRow(row: any) { + expect(row.createdAt).toMatch(/^2026-11-20[T ]12:34:56\.123456(?:Z|\+00(?::?00)?)$/); + expect(row.localTime).toMatch(/^2026-11-20[T ]12:34:56\.654321$/); + expect(row.day).toBe('2026-11-20'); + expect(row.metadata).toEqual({ nested: [1, null, { enabled: true }], text: 'commas,quotes"and\\slashes' }); + expect(row.labels).toEqual(['comma,value', 'quote"value', 'back\\slash', '', null]); + expect(row.state).toBe('QUEUED'); + expect(row.history).toEqual(['QUEUED', 'IN_PROGRESS']); + expect(row.position).toEqual({ x: 7, label: 'nested,record' }); + expect(row.optionalAt).toBeNull(); +} + +beforeEach(async () => { + const connections = await getConnections({}, [seed.sqlfile([join(__dirname, '../sql/bulk-client.sql')])]); + ({ pg, db, teardown } = connections); + await pg.beforeEach(); await db.beforeEach(); + service = makePgService({ pool: connections.manager.getPool(pg.config), schemas: ['bulk_test'] }); + const { schema, resolvedPreset } = await makeSchema({ + extends: [createConstructivePreset({ enableBulk: true })], + pgServices: [service] + }); + // Bulk callbacks must receive the production PgClient facade. + withPgClient = await getWithPgClientFromPgService(service); + query = async ({ query: document }) => execute({ + schema, resolvedPreset, + document: typeof document === 'string' ? parse(document) : document, + contextValue: { pgSettings: { role: 'postgres' }, withPgClient } + }) as Promise; +}); +afterEach(async () => { + await db.afterEach(); await pg.afterEach(); + await service.release?.(); + await teardown?.(); +}); + +it.each([ + ['bulkCreateItems', 'values: [{name: "Client A", quantity: 1}, {name: "Client B", quantity: 2}]', 2], + ['bulkUpsertItems', 'values: [{name: "Widget A", quantity: 7}, {name: "Client C", quantity: 8}], onConflict: {constraint: ITEMS_NAME_KEY}', 2], + ['bulkUpdateItems', 'where: {name: {equalTo: "Widget A"}}, patch: {quantity: 9}', 1] +])('%s executes through the real PgClient and returns affected rows', async (field, input, count) => { + const result = await query({ query: `mutation { ${field}(input: {${input}}) { affectedCount returning { ${returning} } } }` }); + expect(result.errors).toBeUndefined(); + expect(result.data[field].affectedCount).toBe(count); + expect(result.data[field].returning).toHaveLength(count as number); + for (const row of result.data[field].returning) { + expect(row.id).toEqual(expect.any(Number)); + expect(row).toMatchObject({ name: expect.any(String), quantity: expect.any(Number) }); + expectTypedRow(row); + } +}); + +it('returns null typed columns without confusing them with empty values', async () => { + const result = await query({ query: `mutation { bulkCreateItems(input: {values: [{name: "Nulls", metadata: null, labels: null, state: null, history: null, position: null}]}) { returning { metadata labels state history position { x label } optionalAt } } }` }); + expect(result.errors).toBeUndefined(); + expect(result.data.bulkCreateItems.returning).toEqual([{ metadata: null, labels: null, state: null, history: null, position: null, optionalAt: null }]); +}); + +it('returns no records when a bulk update matches no rows', async () => { + const result = await query({ query: `mutation { bulkUpdateItems(input: {where: {name: {equalTo: "Absent"}}, patch: {quantity: 1}}) { affectedCount returning { ${returning} } } }` }); + expect(result.errors).toBeUndefined(); + expect(result.data.bulkUpdateItems).toEqual({ affectedCount: 0, returning: [] }); +}); + +it('omits an unsupported physical column before timestamps without shifting returning values', async () => { + const shape = await query({ query: '{ __type(name: "Item") { fields { name } } }' }); + expect(shape.errors).toBeUndefined(); + expect(shape.data.__type.fields.map((field: any) => field.name)).not.toContain('unsupportedValue'); + const result = await query({ query: `mutation { bulkCreateItems(input: {values: [{name: "Unsupported"}]}) { returning { ${returning} } } }` }); + expect(result.errors).toBeUndefined(); + expect(result.data.bulkCreateItems.returning).toHaveLength(1); + expectTypedRow(result.data.bulkCreateItems.returning[0]); +}); + +it('returns non-casting codec attributes without including unsupported physical slots', async () => { + const result = await query({ query: 'mutation { bulkCreatePlainItems(input: {values: [{quantity: 12}]}) { returning { id quantity state } } }' }); + expect(result.errors).toBeUndefined(); + expect(result.data.bulkCreatePlainItems.returning).toEqual([{ id: expect.any(Number), quantity: 12, state: 'QUEUED' }]); +}); + +it('preserves the primary-key-only returning contract for deleted rows', async () => { + const result = await query({ query: 'mutation { bulkDeleteItems(input: {where: {name: {equalTo: "Widget A"}}}) { affectedCount returning { id } } }' }); + expect(result.errors).toBeUndefined(); + expect(result.data.bulkDeleteItems).toEqual({ affectedCount: 1, returning: [{ id: expect.any(Number) }] }); +}); + +it.each([ + ['bulkCreateItems', 'values: [{name: "Computed", quantity: 4}]', 'Computed:4'], + ['bulkUpsertItems', 'values: [{name: "Widget A", quantity: 6}], onConflict: {constraint: ITEMS_NAME_KEY}', 'Widget A:6'], + ['bulkUpdateItems', 'where: {name: {equalTo: "Widget A"}}, patch: {quantity: 8}', 'Widget A:8'] +])('%s resolves overloaded computed-column functions using the table row type', async (field, input, label) => { + const shape = await query({ query: '{ __type(name: "Item") { fields { name } } }' }); + expect(shape.data.__type.fields.map((field: any) => field.name)).toContain('label'); + await withPgClient({ role: 'postgres' }, (client) => client.query({ + text: readFileSync(join(__dirname, '../sql/bulk-client-overload.sql'), 'utf8') + })); + const result = await query({ query: `mutation { ${field}(input: {${input}}) { returning { ${returning} label } } }` }); + expect(result.errors).toBeUndefined(); + expect(result.data[field].returning).toHaveLength(1); + expect(result.data[field].returning[0].label).toBe(label); + expectTypedRow(result.data[field].returning[0]); +}); + +it('an empty bulk insert does not issue an empty query', async () => { + const result = await query({ query: 'mutation { bulkCreateItems(input: {values: []}) { affectedCount returning { id } } }' }); + expect(result.errors).toBeUndefined(); + expect(result.data.bulkCreateItems).toEqual({ affectedCount: 0, returning: [] }); +}); + +it('reports the real database constraint error rather than an invalid query call', async () => { + const result = await query({ query: 'mutation { bulkCreateItems(input: {values: [{name: "Widget A"}]}) { affectedCount } }' }); + expect(result.errors).toHaveLength(1); + expect(result.errors[0].message).toMatch(/duplicate key value violates unique constraint/); +}); + +it.each([true, false])('builds full-preset bulk update/delete inputs with connection filtering %s', async (enableConnectionFilter) => { + const { schema } = await makeSchema({ + extends: [createConstructivePreset({ enableBulk: true, enableConnectionFilter })], + pgServices: [service] + }); + const fields = schema.getMutationType()!.getFields(); + for (const name of ['bulkUpdateItems', 'bulkDeleteItems']) { + expect(fields[name]).toBeDefined(); + const input = getNamedType(fields[name].args[0].type) as GraphQLInputObjectType; + expect(String(input.getFields().where.type)).toBe(enableConnectionFilter ? 'ItemFilter!' : 'ItemCondition!'); + } +}); diff --git a/graphql/test/__tests__/graphile-test.realtime-empty.test.ts b/graphql/test/__tests__/graphile-test.realtime-empty.test.ts new file mode 100644 index 0000000000..5aa2c11165 --- /dev/null +++ b/graphql/test/__tests__/graphile-test.realtime-empty.test.ts @@ -0,0 +1,38 @@ +import { createConstructivePreset } from 'graphile-settings'; +import { getConnections } from 'graphile-test'; +import { parse } from 'graphql'; +import { join } from 'path'; +import { seed } from 'pgsql-test'; + +let connections: Awaited>; + +beforeAll(async () => { + connections = await getConnections( + { + useRoot: true, + schemas: ['app_public'], + authRole: 'postgres', + preset: { extends: [createConstructivePreset({ enableRealtime: true })] } + }, + [seed.sqlfile([join(__dirname, '../sql/test.sql')])] + ); +}); + +beforeEach(async () => { + await connections.pg.beforeEach(); + await connections.db.beforeEach(); +}); + +afterEach(async () => { + await connections.db.afterEach(); + await connections.pg.afterEach(); +}); + +afterAll(async () => connections.teardown()); + +it('builds a realtime-enabled API with no realtime-tagged tables', async () => { + const result = await connections.query(parse('{ __schema { queryType { name } subscriptionType { name } } }')); + expect(result).toEqual({ + data: { __schema: { queryType: { name: 'Query' }, subscriptionType: null } } + }); +}); diff --git a/graphql/test/sql/bulk-client-overload.sql b/graphql/test/sql/bulk-client-overload.sql new file mode 100644 index 0000000000..1fce42f4e1 --- /dev/null +++ b/graphql/test/sql/bulk-client-overload.sql @@ -0,0 +1,2 @@ +CREATE FUNCTION bulk_test.items_label(item bulk_test.plain_items) RETURNS text + LANGUAGE sql STABLE AS $$ SELECT 'plain:' || item.quantity::text $$; diff --git a/graphql/test/sql/bulk-client.sql b/graphql/test/sql/bulk-client.sql new file mode 100644 index 0000000000..b76cf139b7 --- /dev/null +++ b/graphql/test/sql/bulk-client.sql @@ -0,0 +1,31 @@ +CREATE SCHEMA bulk_test; +CREATE TYPE bulk_test.item_state AS ENUM ('queued', 'in progress'); +CREATE TYPE bulk_test.item_position AS (x integer, label text); +CREATE TABLE bulk_test.items ( + id serial PRIMARY KEY, + name text NOT NULL UNIQUE, + quantity int NOT NULL DEFAULT 0, + unsupported_value pg_lsn DEFAULT '0/16B6C50', + created_at timestamptz NOT NULL DEFAULT '2026-11-20 12:34:56.123456+00', + local_time timestamp NOT NULL DEFAULT '2026-11-20 12:34:56.654321', + day date NOT NULL DEFAULT '2026-11-20', + metadata jsonb DEFAULT '{"nested": [1, null, {"enabled": true}], "text": "commas,quotes\"and\\slashes"}', + labels text[] DEFAULT ARRAY['comma,value', 'quote"value', E'back\\slash', '', NULL], + state bulk_test.item_state DEFAULT 'queued', + history bulk_test.item_state[] DEFAULT ARRAY['queued', 'in progress']::bulk_test.item_state[], + position bulk_test.item_position DEFAULT ROW(7, 'nested,record')::bulk_test.item_position, + optional_at timestamptz +); +COMMENT ON TABLE bulk_test.items IS E'@behavior +bulkInsert +bulkUpsert +bulkUpdate +bulkDelete'; +INSERT INTO bulk_test.items (name, quantity) VALUES ('Widget A', 100); + +CREATE TABLE bulk_test.plain_items ( + id serial PRIMARY KEY, + unsupported_value pg_lsn DEFAULT '0/16B6C50', + quantity integer NOT NULL DEFAULT 11, + state bulk_test.item_state NOT NULL DEFAULT 'queued' +); +COMMENT ON TABLE bulk_test.plain_items IS E'@behavior +bulkInsert'; + +CREATE FUNCTION bulk_test.items_label(item bulk_test.items) RETURNS text + LANGUAGE sql STABLE AS $$ SELECT item.name || ':' || item.quantity::text $$; diff --git a/packages/express-context/__tests__/loaders/realtime.test.ts b/packages/express-context/__tests__/loaders/realtime.test.ts new file mode 100644 index 0000000000..687c601c78 --- /dev/null +++ b/packages/express-context/__tests__/loaders/realtime.test.ts @@ -0,0 +1,46 @@ +import type { Pool } from 'pg'; + +import { realtimeLoader } from '../../src/loaders/realtime'; +import type { LoaderContext } from '../../src/loaders/types'; + +const query = jest.fn(); +const ctx = (databaseId = 'db-a'): LoaderContext => ({ + databaseId, + routingPool: {} as Pool, + tenantPool: { query } as unknown as Pool +}); + +beforeEach(() => { + realtimeLoader.invalidate(); + query.mockReset(); +}); + +it('discovers and caches the physical schema through the tenant-keyed login reader', async () => { + query.mockResolvedValue({ rows: [{ runtime_schema: 'tenant_a_realtime_12' }] }); + await expect(realtimeLoader.resolve(ctx())).resolves.toEqual({ schemaName: 'tenant_a_realtime_12' }); + await realtimeLoader.resolve(ctx()); + expect(query).toHaveBeenCalledTimes(1); + expect(query).toHaveBeenCalledWith(expect.stringContaining('function_resolution.realtime_module_registrations($1)'), ['db-a']); + query.mockResolvedValue({ rows: [{ runtime_schema: 'tenant_b_realtime_19' }] }); + await expect(realtimeLoader.resolve(ctx('db-b'))).resolves.toEqual({ schemaName: 'tenant_b_realtime_19' }); +}); + +it('returns undefined only when the module is absent', async () => { + query.mockResolvedValue({ rows: [] }); + await expect(realtimeLoader.resolve(ctx())).resolves.toBeUndefined(); +}); + +it.each([[{ runtime_schema: null }], [{ runtime_schema: 'a' }, { runtime_schema: 'b' }]])('rejects malformed registrations: %j', async (...rows) => { + query.mockResolvedValue({ rows }); + await expect(realtimeLoader.resolve(ctx())).rejects.toThrow('Invalid realtime module registration'); +}); + +it('propagates lookup failures instead of treating them as an absent module', async () => { + query.mockRejectedValue(new Error('reader unavailable')); + await expect(realtimeLoader.resolve(ctx())).rejects.toThrow('reader unavailable'); +}); + +it('refuses unkeyed discovery', async () => { + await expect(realtimeLoader.resolve(ctx(''))).rejects.toThrow('context carries no databaseId'); + expect(query).not.toHaveBeenCalled(); +}); diff --git a/packages/express-context/src/loaders/index.ts b/packages/express-context/src/loaders/index.ts index 662beceb61..f0ddf1a068 100644 --- a/packages/express-context/src/loaders/index.ts +++ b/packages/express-context/src/loaders/index.ts @@ -61,6 +61,7 @@ export { llmLoader } from './llm'; export { PLATFORM_DATABASE_SQL, platformLoader } from './platform'; export { pubkeyLoader } from './pubkey'; export { requestProtectionLoader } from './request-protection'; +export { realtimeLoader } from './realtime'; export { rlsLoader } from './rls'; export { DATABASE_STANDING_SQL, DATABASE_STANDING_TTL_MS, standingLoader } from './standing'; export { webauthnLoader } from './webauthn'; @@ -82,6 +83,7 @@ import { platformLoader } from './platform'; import { pubkeyLoader } from './pubkey'; import { createLoaderRegistry } from './registry'; import { requestProtectionLoader } from './request-protection'; +import { realtimeLoader } from './realtime'; import { rlsLoader } from './rls'; import { standingLoader } from './standing'; import { webauthnLoader } from './webauthn'; @@ -89,6 +91,7 @@ import { webauthnLoader } from './webauthn'; export function createDefaultRegistry() { const registry = createLoaderRegistry(); registry.register(rlsLoader); + registry.register(realtimeLoader); registry.register(corsLoader); registry.register(databaseSettingsLoader); registry.register(pubkeyLoader); diff --git a/packages/express-context/src/loaders/realtime.ts b/packages/express-context/src/loaders/realtime.ts new file mode 100644 index 0000000000..8bb6e26c0c --- /dev/null +++ b/packages/express-context/src/loaders/realtime.ts @@ -0,0 +1,19 @@ +import { createModuleLoader } from './create-loader'; +import { requireDatabaseId } from './types'; + +export const realtimeLoader = createModuleLoader<{ schemaName: string }>({ + name: 'realtimeModule', + ttlMs: 60_000, + async resolve(ctx) { + requireDatabaseId(ctx.databaseId, 'realtimeModule'); + const { rows } = await ctx.tenantPool.query<{ runtime_schema: string | null }>( + 'SELECT runtime_schema FROM function_resolution.realtime_module_registrations($1)', + [ctx.databaseId] + ); + if (rows.length === 0) return undefined; + if (rows.length !== 1 || !rows[0].runtime_schema) { + throw new Error(`Invalid realtime module registration for database ${ctx.databaseId}`); + } + return { schemaName: rows[0].runtime_schema }; + } +}); diff --git a/packages/express-context/src/types.ts b/packages/express-context/src/types.ts index a6443b3461..9e59381334 100644 --- a/packages/express-context/src/types.ts +++ b/packages/express-context/src/types.ts @@ -142,6 +142,7 @@ export interface ApiStructure { roleName: string; schema: string[]; rlsModule?: RlsModule; + realtimeModule?: { schemaName: string }; domains?: string[]; databaseId?: string; isPublic?: boolean; @@ -284,6 +285,7 @@ export interface PlatformDatabase { */ export interface BuiltinModuleMap { rlsModule: RlsModule; + realtimeModule: { schemaName: string }; corsOrigins: string[]; databaseSettings: DatabaseSettings; authSettings: AuthSettings; diff --git a/pgpm.json b/pgpm.json index 1494cf1e2e..b45171df6f 100644 --- a/pgpm.json +++ b/pgpm.json @@ -8,7 +8,7 @@ "@constructive-db/routing": "8.9.0", "@constructive-db/routing-platform": "7.8.0", "@pgpm/database-jobs": "0.47.7", - "@pgpm/function-resolution": "0.47.10", + "@pgpm/function-resolution": "0.47.11", "@pgpm/inflection-db": "0.47.7", "@pgpm/jwt-claims": "0.47.7", "@pgpm/metaschema-modules": "0.47.10", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index b63df525e0..8912fbba7e 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -2378,6 +2378,9 @@ importers: '@types/supertest': specifier: ^7.2.1 version: 7.2.1 + '@types/ws': + specifier: ^8.18.1 + version: 8.18.1 agentic-server: specifier: workspace:^ version: link:../../agentic/agentic-server/dist @@ -2387,12 +2390,21 @@ importers: gql-ast: specifier: workspace:^ version: link:../gql-ast/dist + grafast: + specifier: 1.1.2 + version: 1.1.2(graphql@16.13.0) graphile-cache: specifier: workspace:^ version: link:../../graphile/graphile-cache/dist graphile-llm: specifier: workspace:^ version: link:../../graphile/graphile-llm/dist + graphile-utils: + specifier: 5.0.3 + version: 5.0.3(@dataplan/pg@1.1.1(@dataplan/json@1.0.1(grafast@1.1.2(graphql@16.13.0)))(grafast@1.1.2(graphql@16.13.0))(graphile-config@1.1.0)(graphql@16.13.0)(pg-sql2@5.0.1)(pg@8.21.0))(grafast@1.1.2(graphql@16.13.0))(graphile-build-pg@5.1.3(@dataplan/pg@1.1.1(@dataplan/json@1.0.1(grafast@1.1.2(graphql@16.13.0)))(grafast@1.1.2(graphql@16.13.0))(graphile-config@1.1.0)(graphql@16.13.0)(pg-sql2@5.0.1)(pg@8.21.0))(grafast@1.1.2(graphql@16.13.0))(graphile-build@5.1.1(grafast@1.1.2(graphql@16.13.0))(graphile-config@1.1.0)(graphql@16.13.0))(graphile-config@1.1.0)(graphql@16.13.0)(pg-sql2@5.0.1)(pg@8.21.0)(tamedevil@0.1.1))(graphile-build@5.1.1(grafast@1.1.2(graphql@16.13.0))(graphile-config@1.1.0)(graphql@16.13.0))(graphile-config@1.1.0)(graphql@16.13.0)(tamedevil@0.1.1) + graphql-ws: + specifier: ^6.0.8 + version: 6.0.8(graphql@16.13.0)(ws@8.21.3) inquirerer: specifier: ^4.9.4 version: 4.9.4 @@ -2402,6 +2414,9 @@ importers: nested-obj: specifier: ^0.2.3 version: 0.2.3 + ws: + specifier: ^8.21.3 + version: 8.21.3 publishDirectory: dist graphql/test: