Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
38 commits
Select commit Hold shift + click to select a range
4c5c675
fix(graphql-server): route tenant WebSocket upgrades with bearer auth
pyramation Nov 20, 2026
b171a5b
fix(codegen): infer realtime subscriptions from schema fields
pyramation Nov 20, 2026
979f41e
fix(server): isolate malformed websocket subscription errors
pyramation Nov 20, 2026
03540c7
fix(server): apply admission budgets to websocket upgrades
pyramation Nov 20, 2026
9bc5fc2
fix(server): enforce websocket subscription payload byte limits
pyramation Nov 20, 2026
6d7d198
fix(realtime): discover physical module schemas and fail startup with…
pyramation Nov 20, 2026
1fee4bf
fix(realtime): dispatch private static runtime helpers
pyramation Nov 20, 2026
3dfc24c
fix(realtime): type pending changes before subscriber fanout
pyramation Nov 20, 2026
849a621
fix: contribute no SDL when realtime has no tagged tables
pyramation Nov 20, 2026
94dd670
fix(realtime): authorize frames before exposing row metadata
pyramation Nov 20, 2026
4347905
fix(realtime): authorize every row in notification batches
pyramation Nov 20, 2026
c1c8221
fix(realtime): throttle individual matching row events
pyramation Nov 20, 2026
b2deb08
fix(realtime): share bounded database notification channels
pyramation Nov 20, 2026
67a0b98
fix(bulk): call the Graphile PgClient query options API
pyramation Nov 20, 2026
449013b
fix(bulk): lazily resolve condition inputs with connection filtering
pyramation Nov 21, 2026
5062758
fix(bulk): decode returning records with their PostgreSQL codec
pyramation Nov 21, 2026
d6200ed
fix(bulk): project returning rows in codec attribute order
pyramation Nov 21, 2026
233a5e6
fix(bulk): preserve composite type for computed returning fields
pyramation Nov 21, 2026
762a9f9
fix: throttle realtime rows only after subscriber authorization
pyramation Nov 21, 2026
579fd69
docs: describe authorization-scoped realtime overflow
pyramation Nov 21, 2026
ca82451
test(server): seed the realtime registration reader for websocket fix…
pyramation Nov 21, 2026
494668b
fix(realtime): await dispatch before advancing the durable cursor
pyramation Nov 21, 2026
7e41c7f
fix(realtime): require grafast with the inhibition API
pyramation Nov 21, 2026
bd87dd5
test(realtime): align notification fixtures with authorized chunk del…
pyramation Nov 21, 2026
76c2396
fix(query): reject list-shaped realtime subscriptions
pyramation Nov 21, 2026
06d0f0e
fix(realtime): honor selection directives when filtering hidden events
pyramation Nov 21, 2026
301c66c
fix(query): reject realtime subscriptions with required arguments
pyramation Nov 21, 2026
0103dc0
test(realtime): use a rejecting iterator for source failures
pyramation Nov 21, 2026
97ac9f6
test(graphql): use the managed Graphile fixture factory
pyramation Nov 21, 2026
07e1e2e
test(server): enable VM modules for native websocket integration
pyramation Nov 21, 2026
58686c7
fix(server): enforce refreshed websocket payload limits
pyramation Nov 21, 2026
3a443e3
test(realtime): isolate subscription histories on one socket
pyramation Nov 21, 2026
5d0a6ef
test(server): initialize admission sockets and handle closed cleanup
pyramation Nov 21, 2026
2befba6
style(realtime): sort authorization imports
pyramation Nov 21, 2026
68398ab
test(server): preserve deployed readers during fixture bootstrap
pyramation Nov 21, 2026
dc4e413
style(server): sort websocket protection imports
pyramation Nov 21, 2026
5dfa9f0
test(server): use the published realtime registration reader
pyramation Nov 21, 2026
2eec574
fix(realtime): retry failed listener cleanup
pyramation Nov 21, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions agentic/run-log-client/__tests__/realtime.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 });
Expand Down
1 change: 0 additions & 1 deletion agentic/run-log-client/src/realtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,6 @@ subscription RunEventChanged {
${field} {
event
${names.event} { __typename }
timestamp
}
}`;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,7 @@ export const BulkDeletePlugin: GraphileConfig.Plugin = {
// Use RETURNING <pk_columns> 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
Expand Down
38 changes: 12 additions & 26 deletions graphile/graphile-bulk-mutations/src/plugins/BulkInsertPlugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand Down Expand Up @@ -200,10 +201,10 @@ export const BulkInsertPlugin: GraphileConfig.Plugin = {
const allPkRows: Record<string, unknown>[] = [];

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);
Expand Down Expand Up @@ -259,35 +260,20 @@ 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;
}
}
}
}

// 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,
Expand Down
19 changes: 7 additions & 12 deletions graphile/graphile-bulk-mutations/src/plugins/BulkTypesPlugin.ts
Original file line number Diff line number Diff line change
@@ -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';

/**
Expand Down Expand Up @@ -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.',
Expand Down Expand Up @@ -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.',
Expand Down Expand Up @@ -589,7 +584,7 @@ export const BulkTypesPlugin: GraphileConfig.Plugin = {
$parent,
'returning'
) as any;
return pgSelectFromRecords(
return pgSelectReturningRecords(
payloadResource,
$records
);
Expand Down
26 changes: 6 additions & 20 deletions graphile/graphile-bulk-mutations/src/plugins/BulkUpdatePlugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';

/**
Expand Down Expand Up @@ -212,29 +214,13 @@ export const BulkUpdatePlugin: GraphileConfig.Plugin = {

// Use RETURNING <pk_columns> 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<string, unknown>[] = 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,
Expand Down
31 changes: 9 additions & 22 deletions graphile/graphile-bulk-mutations/src/plugins/BulkUpsertPlugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand Down Expand Up @@ -177,35 +179,20 @@ export const BulkUpsertPlugin: GraphileConfig.Plugin = {
const allPkRows: Record<string, unknown>[] = [];

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);
}
}

// 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,
Expand Down
83 changes: 83 additions & 0 deletions graphile/graphile-bulk-mutations/src/utils/returning.ts
Original file line number Diff line number Diff line change
@@ -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<string, unknown>[]
): Promise<unknown[]> {
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<Record<string, string | null>>(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<string, unknown>[]) => 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")
)
)`
});
}
65 changes: 65 additions & 0 deletions graphile/graphile-cache/__tests__/create-instance.test.ts
Original file line number Diff line number Diff line change
@@ -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);
});
Loading
Loading