graphile-realtime-subscriptions 1.13.0 → 1.13.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/esm/event-gate.js CHANGED
@@ -1,40 +1,44 @@
1
1
  /**
2
2
  * The gate between PostgreSQL's NOTIFY stream and a GraphQL subscription.
3
3
  *
4
- * Everything that can decide "this event should not reach the client" lives
5
- * here, upstream of grafast, because grafast's `listen` maps each event to a
6
- * step and offers no way to suppress one. Deciding downstream forced the
7
- * plugin to represent "dropped" as a null payload, which the field resolvers
8
- * then had to coalesce (`p?.event ?? 'UNKNOWN'`) — so a filtered event still
9
- * reached the client, carrying an invented event name. Filtering here means
10
- * the stream only ever yields events that should exist, and every resolver
11
- * downstream is total.
12
- *
13
- * The gate also owns parsing and the overflow throttle, so a payload the
14
- * trigger and the plugin disagree about fails loudly instead of arriving as
4
+ * Parsing and ID filtering happen before Grafast plans each event.
5
+ * The plugin authorizes each row before applying its visible-row throttle.
6
+ * A payload the trigger and the plugin disagree about fails loudly instead of arriving as
15
7
  * an `UNKNOWN`-shaped record.
16
8
  */
9
+ import { flatMapIterator } from './async-iterator';
17
10
  /** Operations `emit_change` is allowed to report. */
18
11
  const KNOWN_OPERATIONS = new Set(['INSERT', 'UPDATE', 'DELETE']);
19
12
  export class MalformedNotifyPayloadError extends Error {
20
13
  constructor(raw, reason) {
21
- super(`Malformed realtime NOTIFY payload ${JSON.stringify(raw)}: ${reason}. ` +
22
- 'Expected "INVALIDATE" or "<INSERT|UPDATE|DELETE>:<uuid>[,<uuid>...]" ' +
14
+ super(`Malformed realtime NOTIFY payload ${JSON.stringify(raw.startsWith('{') ? '[ephemeral rows]' : raw)}: ${reason}. ` +
15
+ 'Expected "<INSERT|UPDATE|DELETE>:<uuid>[,<uuid>...]" or ephemeral row JSON ' +
23
16
  'as emitted by the emit_change trigger.');
24
17
  this.name = 'MalformedNotifyPayloadError';
25
18
  }
26
19
  }
27
20
  /**
28
21
  * Parse the NOTIFY payload from `emit_change`.
29
- * Format: `"TG_OP:id1,id2,..."` or `"INVALIDATE"`.
22
+ * Format: `"TG_OP:id1,id2,..."` or ephemeral `{"op":"TG_OP","rows":[{"id":"uuid"}]}`.
30
23
  *
31
24
  * Throws on anything else: a payload this cannot read means the trigger and
32
25
  * this plugin have diverged, and inventing an event name for it hides a
33
26
  * deployment fault behind data the client will act on.
34
27
  */
35
28
  export function parseNotifyPayload(raw) {
36
- if (raw === 'INVALIDATE') {
37
- return { event: 'INVALIDATE', rowIds: [], overflow: true };
29
+ if (raw.startsWith('{')) {
30
+ let value;
31
+ try {
32
+ value = JSON.parse(raw);
33
+ }
34
+ catch {
35
+ throw new MalformedNotifyPayloadError(raw, 'invalid ephemeral JSON');
36
+ }
37
+ if (!KNOWN_OPERATIONS.has(value?.op) || !Array.isArray(value.rows) || value.rows.length === 0 ||
38
+ value.rows.some((row) => !row || typeof row.id !== 'string' || row.id.length === 0)) {
39
+ throw new MalformedNotifyPayloadError(raw, 'ephemeral payload requires an operation and row ids');
40
+ }
41
+ return { event: value.op, rowIds: value.rows.map((row) => row.id), overflow: false };
38
42
  }
39
43
  const colonIdx = raw.indexOf(':');
40
44
  if (colonIdx === -1) {
@@ -46,7 +50,7 @@ export function parseNotifyPayload(raw) {
46
50
  }
47
51
  const idsPart = raw.substring(colonIdx + 1);
48
52
  const rowIds = idsPart.length > 0 ? idsPart.split(',') : [];
49
- if (rowIds.length === 0) {
53
+ if (rowIds.length === 0 || rowIds.some(id => id.length === 0)) {
50
54
  throw new MalformedNotifyPayloadError(raw, `${event} carries no row ids`);
51
55
  }
52
56
  return { event, rowIds, overflow: false };
@@ -89,21 +93,10 @@ export class EventThrottle {
89
93
  /**
90
94
  * Apply the gate to one raw NOTIFY payload.
91
95
  *
92
- * Returns the payload to deliver, or `null` meaning *do not emit* — a decision
93
- * only this layer is allowed to make, because only this layer can act on it.
96
+ * Returns the payload to authorize, or `null` meaning *do not emit*.
94
97
  */
95
- function gate(raw, ids, throttle) {
98
+ function gate(raw, ids) {
96
99
  const parsed = parseNotifyPayload(raw);
97
- // An INVALIDATE is the overflow signal itself; throttling it would drop the
98
- // one event telling the client to refetch.
99
- if (parsed.overflow)
100
- return parsed;
101
- const action = throttle.check();
102
- if (action === 'drop')
103
- return null;
104
- if (action === 'overflow') {
105
- return { event: 'INVALIDATE', rowIds: [], overflow: true };
106
- }
107
100
  if (!ids || ids.length === 0)
108
101
  return parsed;
109
102
  const matched = parsed.rowIds.filter(rowId => ids.includes(rowId));
@@ -114,21 +107,20 @@ function gate(raw, ids, throttle) {
114
107
  /**
115
108
  * Wrap a `GrafastSubscriber` so its stream yields parsed, gated payloads.
116
109
  *
117
- * Built per subscription (the throttle and `ids` are per-subscriber state), so
118
- * one noisy client can no longer throttle every other subscriber to the same
119
- * table — which a single build-time throttle instance did.
110
+ * Built per subscription so each sparse ID set is independent. Row visibility
111
+ * and rate accounting are applied by the event plan, after its scoped lookup.
120
112
  */
121
- export function createGatedSubscriber(inner, { ids, threshold }) {
113
+ export function createGatedSubscriber(inner, { ids }) {
122
114
  const subscribedIds = ids && ids.length > 0 ? ids : null;
123
- const throttle = new EventThrottle(threshold);
124
115
  return {
125
- async *subscribe(topic) {
116
+ async subscribe(topic) {
126
117
  const source = await inner.subscribe(topic);
127
- for await (const raw of source) {
128
- const payload = gate(String(raw), subscribedIds, throttle);
129
- if (payload !== null)
130
- yield payload;
131
- }
118
+ return flatMapIterator(source, raw => {
119
+ const payload = gate(String(raw), subscribedIds);
120
+ if (!payload)
121
+ return [];
122
+ return payload.rowIds.map(id => ({ ...payload, rowIds: [id] }));
123
+ });
132
124
  }
133
125
  // Deliberately no release(): `inner` is the shared pgSubscriber from the
134
126
  // request context and is not ours to tear down. Ending iteration returns
package/esm/index.d.ts CHANGED
@@ -16,6 +16,7 @@
16
16
  * };
17
17
  * ```
18
18
  */
19
+ export { realtimeChannel } from './channel';
19
20
  export { CursorTracker } from './cursor-tracker';
20
21
  export { createRealtimeSubscriptionsPlugin, RealtimeSubscriptionsPlugin } from './plugin';
21
22
  export { RealtimeSubscriptionsPreset } from './preset';
package/esm/index.js CHANGED
@@ -16,6 +16,7 @@
16
16
  * };
17
17
  * ```
18
18
  */
19
+ export { realtimeChannel } from './channel';
19
20
  export { CursorTracker } from './cursor-tracker';
20
21
  export { createRealtimeSubscriptionsPlugin, RealtimeSubscriptionsPlugin } from './plugin';
21
22
  export { RealtimeSubscriptionsPreset } from './preset';
package/esm/plugin.d.ts CHANGED
@@ -11,15 +11,14 @@
11
11
  *
12
12
  * NOTIFY payload format (from emit_change trigger):
13
13
  * - Normal: "INSERT:uuid1,uuid2,..." or "UPDATE:uuid1" or "DELETE:uuid1"
14
- * - Overflow: "INVALIDATE" (when a single statement affects > 50 rows)
14
+ * - Ephemeral small batches: JSON with op and rows (only their IDs are used)
15
15
  *
16
16
  * Event flow:
17
17
  * 1. A row is inserted/updated/deleted
18
- * 2. The emit_change trigger fires pg_notify with TG_OP:row_ids or INVALIDATE
18
+ * 2. The emit_change trigger fires byte-bounded pg_notify payloads
19
19
  * 3. PostGraphile's pgSubscriber receives the NOTIFY
20
- * 4. The gate (see event-gate.ts) parses, throttles and filters it — a
21
- * payload this subscription should not see never becomes an event
22
- * 5. The plugin fetches the changed row(s)
20
+ * 4. The gate (see event-gate.ts) parses, filters IDs and splits each row
21
+ * 5. The plugin authorizes the row before counting it against the throttle
23
22
  * 6. The client receives { event, row, rowId, overflow }
24
23
  *
25
24
  * Cursor tracking (at-least-once delivery):
@@ -32,20 +31,16 @@
32
31
  * This enables at-least-once semantics by tracking cursor position.
33
32
  *
34
33
  * Overflow protection:
35
- * - Database-side: statements affecting > 50 rows send INVALIDATE
36
- * - Plugin-side: per-subscription throttle (default 50 events/second/table)
37
- * drops individual events and sends a single INVALIDATE when exceeded
34
+ * - Database-side: large statements send byte-bounded ID chunks
35
+ * - Plugin-side: per-subscription throttle (default 50 visible rows/second)
36
+ * sends one id-less overflow frame when exceeded
38
37
  *
39
38
  * Security / RLS enforcement:
40
39
  * - Row data is always fetched via resource.get() which runs through the
41
40
  * authenticated user's connection with their JWT role and pgSettings applied.
42
- * - For INSERT/UPDATE events, if RLS denies access (resource.get returns null),
43
- * the rowId is masked (set to null) to prevent metadata leaks.
44
- * - For DELETE events, row is naturally null (the row no longer exists).
45
- * - For INVALIDATE (overflow), the client should refetch via a normal query
46
- * which is also RLS-gated.
47
- * - When ids are provided, only events for those specific rows are delivered,
48
- * preventing cross-tenant event leaks.
41
+ * - Invisible INSERT/UPDATE events are inhibited and removed from the stream.
42
+ * - DELETE is delivered only for IDs this subscription previously saw as visible.
43
+ * - Invisible rows cannot consume the throttle budget or cause overflow.
49
44
  */
50
45
  import type { GraphileConfig } from 'graphile-config';
51
46
  import type { RealtimeSubscriptionsPluginOptions } from './types';
package/esm/plugin.js CHANGED
@@ -11,15 +11,14 @@
11
11
  *
12
12
  * NOTIFY payload format (from emit_change trigger):
13
13
  * - Normal: "INSERT:uuid1,uuid2,..." or "UPDATE:uuid1" or "DELETE:uuid1"
14
- * - Overflow: "INVALIDATE" (when a single statement affects > 50 rows)
14
+ * - Ephemeral small batches: JSON with op and rows (only their IDs are used)
15
15
  *
16
16
  * Event flow:
17
17
  * 1. A row is inserted/updated/deleted
18
- * 2. The emit_change trigger fires pg_notify with TG_OP:row_ids or INVALIDATE
18
+ * 2. The emit_change trigger fires byte-bounded pg_notify payloads
19
19
  * 3. PostGraphile's pgSubscriber receives the NOTIFY
20
- * 4. The gate (see event-gate.ts) parses, throttles and filters it — a
21
- * payload this subscription should not see never becomes an event
22
- * 5. The plugin fetches the changed row(s)
20
+ * 4. The gate (see event-gate.ts) parses, filters IDs and splits each row
21
+ * 5. The plugin authorizes the row before counting it against the throttle
23
22
  * 6. The client receives { event, row, rowId, overflow }
24
23
  *
25
24
  * Cursor tracking (at-least-once delivery):
@@ -32,25 +31,24 @@
32
31
  * This enables at-least-once semantics by tracking cursor position.
33
32
  *
34
33
  * Overflow protection:
35
- * - Database-side: statements affecting > 50 rows send INVALIDATE
36
- * - Plugin-side: per-subscription throttle (default 50 events/second/table)
37
- * drops individual events and sends a single INVALIDATE when exceeded
34
+ * - Database-side: large statements send byte-bounded ID chunks
35
+ * - Plugin-side: per-subscription throttle (default 50 visible rows/second)
36
+ * sends one id-less overflow frame when exceeded
38
37
  *
39
38
  * Security / RLS enforcement:
40
39
  * - Row data is always fetched via resource.get() which runs through the
41
40
  * authenticated user's connection with their JWT role and pgSettings applied.
42
- * - For INSERT/UPDATE events, if RLS denies access (resource.get returns null),
43
- * the rowId is masked (set to null) to prevent metadata leaks.
44
- * - For DELETE events, row is naturally null (the row no longer exists).
45
- * - For INVALIDATE (overflow), the client should refetch via a normal query
46
- * which is also RLS-gated.
47
- * - When ids are provided, only events for those specific rows are delivered,
48
- * preventing cross-tenant event leaks.
41
+ * - Invisible INSERT/UPDATE events are inhibited and removed from the stream.
42
+ * - DELETE is delivered only for IDs this subscription previously saw as visible.
43
+ * - Invisible rows cannot consume the throttle budget or cause overflow.
49
44
  */
50
45
  import { Logger } from '@pgpmjs/logger';
51
- import { constant, context as grafastContext, lambda, listen, object } from 'grafast';
46
+ import { constant, context as grafastContext, inhibitIf, lambda, listen, object, sideEffect } from 'grafast';
52
47
  import { extendSchema } from 'graphile-utils';
48
+ import { realtimeChannel } from './channel';
49
+ import { SubscriptionDelivery } from './delivery';
53
50
  import { createGatedSubscriber } from './event-gate';
51
+ import { filterInaccessibleEvents, realtimeResponseNames } from './subscription-filter';
54
52
  const log = new Logger('graphile-realtime-subscriptions');
55
53
  /** Default overflow threshold: events per second per table per subscriber */
56
54
  const DEFAULT_OVERFLOW_THRESHOLD = 50;
@@ -72,7 +70,7 @@ function discoverRealtimeTables(build) {
72
70
  const rowFieldName = typeName.charAt(0).toLowerCase() + typeName.slice(1);
73
71
  const pgSchema = codec.extensions?.pg?.schemaName ?? 'public';
74
72
  const pgTable = codec.extensions?.pg?.name ?? codec.name;
75
- const notifyChannel = `realtime:${pgSchema}.${pgTable}`;
73
+ const notifyChannel = realtimeChannel(pgSchema, pgTable);
76
74
  result.push({
77
75
  resource: r,
78
76
  typeName,
@@ -94,11 +92,11 @@ function buildTypeDefs(tables) {
94
92
  const payloadTypes = tables
95
93
  .map(({ payloadTypeName, typeName, rowFieldName }) => `"""Payload delivered when a ${typeName} row changes."""\n` +
96
94
  `type ${payloadTypeName} {\n` +
97
- ` """The DML operation: INSERT, UPDATE, DELETE, or INVALIDATE."""\n` +
95
+ ` """The DML operation: INSERT, UPDATE, or DELETE, including the visible change that caused overflow."""\n` +
98
96
  ` event: String!\n` +
99
- ` """The current state of the row (null for DELETE, INVALIDATE, or if RLS denies access)."""\n` +
97
+ ` """The current state of the authorized row (null for DELETE or overflow)."""\n` +
100
98
  ` ${rowFieldName}: ${typeName}\n` +
101
- ` """The ID of the changed row (null for INVALIDATE, or masked when RLS denies access)."""\n` +
99
+ ` """The ID of a change visible to this subscription."""\n` +
102
100
  ` rowId: UUID\n` +
103
101
  ` """True when too many changes occurred and the client should refetch."""\n` +
104
102
  ` overflow: Boolean!\n` +
@@ -119,7 +117,7 @@ function requirePayload(payload) {
119
117
  }
120
118
  /**
121
119
  * The row this event reports. `rowIds` is already narrowed to the
122
- * subscription's `ids`, so the first entry is the one to surface; INVALIDATE
120
+ * subscription's `ids`, so the first entry is the one to surface; overflow
123
121
  * carries none, which is a genuine absence rather than a suppressed error.
124
122
  */
125
123
  function reportedRowId(payload) {
@@ -136,17 +134,22 @@ function buildPlans(tables, overflowThreshold) {
136
134
  const $pgSubscriber = grafastContext().get('pgSubscriber');
137
135
  const $topic = constant(notifyChannel);
138
136
  const $ids = args.getRaw('ids');
139
- // Parsing, throttling and sparse-set filtering all happen in the gate,
140
- // built once per subscription, so the stream below yields only events
141
- // that should reach this client — every step after it is total.
137
+ const $visibility = lambda([$pgSubscriber, $ids], () => new SubscriptionDelivery(overflowThreshold));
142
138
  const $subscriber = lambda([$pgSubscriber, $ids], (pair) => {
143
139
  const [pgSubscriber, ids] = pair;
144
- return createGatedSubscriber(pgSubscriber, { ids, threshold: overflowThreshold });
140
+ return createGatedSubscriber(pgSubscriber, { ids });
145
141
  });
146
- return listen($subscriber, $topic, ($payload) => object({ parsed: $payload }));
142
+ return listen($subscriber, $topic, ($payload) => object({ parsed: $payload, visibility: $visibility }));
147
143
  },
148
144
  plan($event) {
149
- return $event;
145
+ const $parsed = $event.get('parsed');
146
+ const $rowId = lambda($parsed, (p) => reportedRowId(requirePayload(p)));
147
+ const $row = resource.get({ id: $rowId });
148
+ const $projected = sideEffect([$parsed, $row, $event.get('visibility')], ([payload, row, delivery]) => delivery.project(requirePayload(payload), row != null));
149
+ const $hidden = lambda($projected, (payload) => payload == null);
150
+ const $reportedRowId = lambda($projected, (payload) => payload && !payload.overflow ? reportedRowId(payload) : null);
151
+ const $reportedRow = resource.get({ id: $reportedRowId });
152
+ return object({ parsed: inhibitIf($projected, $hidden), row: $reportedRow });
150
153
  },
151
154
  };
152
155
  allPlans[payloadTypeName] = {
@@ -160,8 +163,7 @@ function buildPlans(tables, overflowThreshold) {
160
163
  return lambda($parent.get('parsed'), (p) => requirePayload(p).overflow);
161
164
  },
162
165
  [rowFieldName]($parent) {
163
- const $rowId = lambda($parent.get('parsed'), (p) => reportedRowId(requirePayload(p)));
164
- return resource.get({ id: $rowId });
166
+ return $parent.get('row');
165
167
  },
166
168
  };
167
169
  }
@@ -170,11 +172,12 @@ function buildPlans(tables, overflowThreshold) {
170
172
  }
171
173
  export function createRealtimeSubscriptionsPlugin(options = {}) {
172
174
  const overflowThreshold = options.overflowThreshold ?? DEFAULT_OVERFLOW_THRESHOLD;
173
- return extendSchema((build) => {
175
+ const fieldsBySchema = new WeakMap();
176
+ const plugin = extendSchema((build) => {
174
177
  const tables = discoverRealtimeTables(build);
175
178
  if (tables.length === 0) {
176
179
  log.info('No tables with @realtime tag found — skipping subscription generation');
177
- return { typeDefs: '', plans: {} };
180
+ return { typeDefs: [], plans: {} };
178
181
  }
179
182
  log.info(`Generating subscription fields for ${tables.length} realtime table(s)`);
180
183
  log.info(`Overflow threshold: ${overflowThreshold} events/second/table`);
@@ -182,6 +185,25 @@ export function createRealtimeSubscriptionsPlugin(options = {}) {
182
185
  const plans = buildPlans(tables, overflowThreshold);
183
186
  return { typeDefs, plans };
184
187
  }, 'RealtimeSubscriptionsPlugin');
188
+ plugin.schema.hooks.finalize = (schema, build) => {
189
+ fieldsBySchema.set(schema, new Set(discoverRealtimeTables(build).map(table => table.fieldName)));
190
+ return schema;
191
+ };
192
+ plugin.grafast = {
193
+ middleware: {
194
+ async subscribe(next, { args }) {
195
+ const result = await next();
196
+ const fields = fieldsBySchema.get(args.schema);
197
+ if (!fields)
198
+ throw new Error('Realtime authorization metadata is missing for this schema.');
199
+ if (!fields.size || !(Symbol.asyncIterator in result))
200
+ return result;
201
+ const names = realtimeResponseNames(args.document, args.operationName, fields, args.variableValues);
202
+ return names.length ? filterInaccessibleEvents(result, names) : result;
203
+ }
204
+ }
205
+ };
206
+ return plugin;
185
207
  }
186
208
  export { createRealtimeSubscriptionsPlugin as RealtimeSubscriptionsPlugin };
187
209
  // Re-export CursorTracker and RealtimeManager for convenience
@@ -38,7 +38,7 @@ declare function extractRowId(entry: ChangeLogEntry): string | null;
38
38
  declare function entryToNotifyPayload(entry: ChangeLogEntry): string;
39
39
  /**
40
40
  * Build the NOTIFY channel name for a change_log entry.
41
- * Matches the channel format used by emit_change: "realtime:{schema}.{table}"
41
+ * Matches the bounded channel used by emit_change and subscription plans.
42
42
  */
43
43
  declare function entryToChannel(entry: ChangeLogEntry): string;
44
44
  export declare class RealtimeManager {
@@ -23,6 +23,7 @@
23
23
  * 3. stop() → cleans up ephemeral subscriptions, removes listener node
24
24
  */
25
25
  import { Logger } from '@pgpmjs/logger';
26
+ import { realtimeChannel } from './channel';
26
27
  import { CursorTracker } from './cursor-tracker';
27
28
  const log = new Logger('realtime-manager');
28
29
  /**
@@ -51,10 +52,10 @@ function entryToNotifyPayload(entry) {
51
52
  }
52
53
  /**
53
54
  * Build the NOTIFY channel name for a change_log entry.
54
- * Matches the channel format used by emit_change: "realtime:{schema}.{table}"
55
+ * Matches the bounded channel used by emit_change and subscription plans.
55
56
  */
56
57
  function entryToChannel(entry) {
57
- return `realtime:${entry.source_schema}.${entry.source_table}`;
58
+ return realtimeChannel(entry.source_schema, entry.source_table);
58
59
  }
59
60
  export class RealtimeManager {
60
61
  cursorTracker;
@@ -87,11 +88,15 @@ export class RealtimeManager {
87
88
  return;
88
89
  this.started = true;
89
90
  log.info(`Starting RealtimeManager: node=${this.nodeId}`);
90
- await this.cursorTracker.start();
91
+ try {
92
+ await this.cursorTracker.start();
93
+ }
94
+ catch (error) {
95
+ this.started = false;
96
+ throw error;
97
+ }
91
98
  }
92
99
  async stop() {
93
- if (!this.started)
94
- return;
95
100
  this.started = false;
96
101
  log.info(`Stopping RealtimeManager: node=${this.nodeId}`);
97
102
  await this.cursorTracker.stop();
@@ -0,0 +1,6 @@
1
+ import { type DocumentNode } from 'graphql';
2
+ export declare function realtimeResponseNames(document: DocumentNode, operationName: string | null | undefined, fields: ReadonlySet<string>, variableValues?: Record<string, unknown>): string[];
3
+ export declare function filterInaccessibleEvents<T extends {
4
+ data?: unknown;
5
+ errors?: readonly unknown[];
6
+ }>(source: AsyncIterable<T>, names: readonly string[]): AsyncGenerator<T, void, void>;
@@ -0,0 +1,45 @@
1
+ import { getDirectiveValues, getOperationAST, GraphQLIncludeDirective, GraphQLSkipDirective, Kind, valueFromASTUntyped } from 'graphql';
2
+ import { filterMapIterator } from './async-iterator';
3
+ export function realtimeResponseNames(document, operationName, fields, variableValues = {}) {
4
+ const operation = getOperationAST(document, operationName);
5
+ if (operation?.operation !== 'subscription')
6
+ return [];
7
+ const variables = Object.fromEntries((operation.variableDefinitions ?? [])
8
+ .filter(definition => definition.defaultValue)
9
+ .map(definition => [definition.variable.name.value, valueFromASTUntyped(definition.defaultValue)]));
10
+ Object.assign(variables, variableValues);
11
+ const names = new Set();
12
+ const visited = new Set();
13
+ function visit(selectionSet) {
14
+ for (const selection of selectionSet.selections) {
15
+ if (getDirectiveValues(GraphQLSkipDirective, selection, variables)?.if === true ||
16
+ getDirectiveValues(GraphQLIncludeDirective, selection, variables)?.if === false)
17
+ continue;
18
+ if (selection.kind === Kind.FIELD) {
19
+ if (fields.has(selection.name.value))
20
+ names.add(selection.alias?.value ?? selection.name.value);
21
+ }
22
+ else if (selection.kind === Kind.INLINE_FRAGMENT) {
23
+ visit(selection.selectionSet);
24
+ }
25
+ else if (!visited.has(selection.name.value)) {
26
+ visited.add(selection.name.value);
27
+ const fragment = document.definitions.find(definition => definition.kind === Kind.FRAGMENT_DEFINITION && definition.name.value === selection.name.value);
28
+ if (fragment?.kind === Kind.FRAGMENT_DEFINITION)
29
+ visit(fragment.selectionSet);
30
+ }
31
+ }
32
+ }
33
+ visit(operation.selectionSet);
34
+ return [...names];
35
+ }
36
+ export function filterInaccessibleEvents(source, names) {
37
+ return filterMapIterator(source, result => {
38
+ const { data, errors } = result;
39
+ if ('path' in result)
40
+ return result;
41
+ const root = typeof data === 'string' ? JSON.parse(data) : data;
42
+ return !errors?.length && root && typeof root === 'object' && names.length > 0 &&
43
+ names.every(name => root[name] === null) ? null : result;
44
+ });
45
+ }
package/esm/types.d.ts CHANGED
@@ -3,10 +3,9 @@
3
3
  */
4
4
  export interface RealtimeSubscriptionsPluginOptions {
5
5
  /**
6
- * Maximum number of events per table per second before switching to
7
- * overflow (INVALIDATE) mode. When exceeded, the subscription sends
8
- * a single { event: 'INVALIDATE', overflow: true } instead of
9
- * individual row events, signaling the client to refetch.
6
+ * Maximum number of authorized row events per subscription per second.
7
+ * When exceeded, sends one overflow frame without a row or row ID,
8
+ * preserving the triggering operation and signaling the client to refetch.
10
9
  *
11
10
  * Default: 50
12
11
  */
@@ -51,10 +50,10 @@ export interface CursorTrackerOptions {
51
50
  */
52
51
  nodeId?: string;
53
52
  /**
54
- * The realtime_public schema name where drain_changes(),
53
+ * The private realtime schema name where drain_changes(),
55
54
  * touch_listener(), and cleanup_ephemeral() live.
56
55
  *
57
- * Default: 'realtime_public'
56
+ * Default: 'realtime_private'
58
57
  */
59
58
  schema?: string;
60
59
  /**
@@ -116,10 +115,10 @@ export interface RealtimeManagerOptions {
116
115
  */
117
116
  nodeId?: string;
118
117
  /**
119
- * The realtime_public schema name where drain_changes(),
118
+ * The private realtime schema name where drain_changes(),
120
119
  * touch_listener(), and cleanup_ephemeral() live.
121
120
  *
122
- * Default: 'realtime_public'
121
+ * Default: 'realtime_private'
123
122
  */
124
123
  schema?: string;
125
124
  /**
@@ -0,0 +1,5 @@
1
+ import type { ParsedPayload } from './event-gate';
2
+ export declare class SubscriptionVisibility {
3
+ private readonly visibleIds;
4
+ allow(payload: ParsedPayload, rowVisible: boolean): boolean;
5
+ }
@@ -0,0 +1,22 @@
1
+ const MAX_VISIBLE_IDS = 10_000;
2
+ export class SubscriptionVisibility {
3
+ visibleIds = new Set();
4
+ allow(payload, rowVisible) {
5
+ if (!payload.overflow && payload.rowIds.length > 1) {
6
+ throw new Error('Realtime visibility requires single-row events.');
7
+ }
8
+ const id = payload.rowIds[0];
9
+ if (payload.overflow || !id)
10
+ return false;
11
+ if (payload.event === 'DELETE')
12
+ return this.visibleIds.delete(id);
13
+ this.visibleIds.delete(id);
14
+ if (!rowVisible)
15
+ return false;
16
+ this.visibleIds.add(id);
17
+ if (this.visibleIds.size > MAX_VISIBLE_IDS) {
18
+ this.visibleIds.delete(this.visibleIds.values().next().value);
19
+ }
20
+ return true;
21
+ }
22
+ }
package/event-gate.d.ts CHANGED
@@ -1,17 +1,9 @@
1
1
  /**
2
2
  * The gate between PostgreSQL's NOTIFY stream and a GraphQL subscription.
3
3
  *
4
- * Everything that can decide "this event should not reach the client" lives
5
- * here, upstream of grafast, because grafast's `listen` maps each event to a
6
- * step and offers no way to suppress one. Deciding downstream forced the
7
- * plugin to represent "dropped" as a null payload, which the field resolvers
8
- * then had to coalesce (`p?.event ?? 'UNKNOWN'`) — so a filtered event still
9
- * reached the client, carrying an invented event name. Filtering here means
10
- * the stream only ever yields events that should exist, and every resolver
11
- * downstream is total.
12
- *
13
- * The gate also owns parsing and the overflow throttle, so a payload the
14
- * trigger and the plugin disagree about fails loudly instead of arriving as
4
+ * Parsing and ID filtering happen before Grafast plans each event.
5
+ * The plugin authorizes each row before applying its visible-row throttle.
6
+ * A payload the trigger and the plugin disagree about fails loudly instead of arriving as
15
7
  * an `UNKNOWN`-shaped record.
16
8
  */
17
9
  import type { GrafastSubscriber } from 'grafast';
@@ -19,8 +11,8 @@ export interface ParsedPayload {
19
11
  event: string;
20
12
  /**
21
13
  * Row ids being reported. Already narrowed to the subscription's `ids` when
22
- * it supplied any, so no consumer needs to re-intersect. Empty for
23
- * INVALIDATE.
14
+ * it supplied any, so no consumer needs to re-intersect. Empty only for
15
+ * an authorized overflow produced after row lookup.
24
16
  */
25
17
  rowIds: string[];
26
18
  overflow: boolean;
@@ -30,7 +22,7 @@ export declare class MalformedNotifyPayloadError extends Error {
30
22
  }
31
23
  /**
32
24
  * Parse the NOTIFY payload from `emit_change`.
33
- * Format: `"TG_OP:id1,id2,..."` or `"INVALIDATE"`.
25
+ * Format: `"TG_OP:id1,id2,..."` or ephemeral `{"op":"TG_OP","rows":[{"id":"uuid"}]}`.
34
26
  *
35
27
  * Throws on anything else: a payload this cannot read means the trigger and
36
28
  * this plugin have diverged, and inventing an event name for it hides a
@@ -57,14 +49,11 @@ export declare class EventThrottle {
57
49
  export interface EventGateOptions {
58
50
  /** Sparse-set subscription: deliver only events touching these row ids. */
59
51
  ids?: readonly string[] | null;
60
- /** Events per second before the gate collapses the stream to one INVALIDATE. */
61
- threshold: number;
62
52
  }
63
53
  /**
64
54
  * Wrap a `GrafastSubscriber` so its stream yields parsed, gated payloads.
65
55
  *
66
- * Built per subscription (the throttle and `ids` are per-subscriber state), so
67
- * one noisy client can no longer throttle every other subscriber to the same
68
- * table — which a single build-time throttle instance did.
56
+ * Built per subscription so each sparse ID set is independent. Row visibility
57
+ * and rate accounting are applied by the event plan, after its scoped lookup.
69
58
  */
70
- export declare function createGatedSubscriber(inner: GrafastSubscriber<Record<string, string>>, { ids, threshold }: EventGateOptions): GrafastSubscriber<Record<string, ParsedPayload>>;
59
+ export declare function createGatedSubscriber(inner: GrafastSubscriber<Record<string, string>>, { ids }: EventGateOptions): GrafastSubscriber<Record<string, ParsedPayload>>;