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