graphile-realtime-subscriptions 1.12.0 → 1.13.1
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/README.md +17 -4
- package/async-iterator.d.ts +2 -0
- package/async-iterator.js +54 -0
- package/channel.d.ts +1 -0
- package/channel.js +8 -0
- package/cursor-tracker.d.ts +3 -1
- package/cursor-tracker.js +52 -15
- package/delivery.d.ts +7 -0
- package/delivery.js +23 -0
- package/esm/async-iterator.d.ts +2 -0
- package/esm/async-iterator.js +50 -0
- package/esm/channel.d.ts +1 -0
- package/esm/channel.js +5 -0
- package/esm/cursor-tracker.d.ts +3 -1
- package/esm/cursor-tracker.js +52 -15
- package/esm/delivery.d.ts +7 -0
- package/esm/delivery.js +19 -0
- package/esm/event-gate.d.ts +9 -20
- package/esm/event-gate.js +33 -41
- package/esm/index.d.ts +1 -0
- package/esm/index.js +1 -0
- package/esm/plugin.d.ts +10 -15
- package/esm/plugin.js +53 -31
- package/esm/realtime-manager.d.ts +1 -1
- package/esm/realtime-manager.js +10 -5
- package/esm/subscription-filter.d.ts +6 -0
- package/esm/subscription-filter.js +45 -0
- package/esm/types.d.ts +7 -8
- package/esm/visibility.d.ts +5 -0
- package/esm/visibility.js +22 -0
- package/event-gate.d.ts +9 -20
- package/event-gate.js +33 -41
- package/index.d.ts +1 -0
- package/index.js +3 -1
- package/package.json +4 -4
- package/plugin.d.ts +10 -15
- package/plugin.js +52 -30
- package/realtime-manager.d.ts +1 -1
- package/realtime-manager.js +10 -5
- package/subscription-filter.d.ts +6 -0
- package/subscription-filter.js +49 -0
- package/types.d.ts +7 -8
- package/visibility.d.ts +5 -0
- package/visibility.js +26 -0
package/README.md
CHANGED
|
@@ -25,11 +25,23 @@ const preset = {
|
|
|
25
25
|
## How It Works
|
|
26
26
|
|
|
27
27
|
1. A row is inserted/updated/deleted on a `@realtime`-tagged table
|
|
28
|
-
2. The `emit_change` trigger
|
|
28
|
+
2. The `emit_change` trigger notifies `realtime:` plus the lowercase MD5 of `<UTF-8 schema byte length>:<schema><table>` (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.
|
|
29
29
|
3. PostGraphile's `pgSubscriber` receives the NOTIFY
|
|
30
30
|
4. The subscription re-queries the source table with RLS enforced
|
|
31
31
|
5. The client receives `{ event, row }` where `row` reflects the current state
|
|
32
32
|
|
|
33
|
+
### Authorization
|
|
34
|
+
|
|
35
|
+
INSERT and UPDATE emit no frame when the RLS-scoped row lookup is null, including metadata-only selections. An `ids` filter never grants access.
|
|
36
|
+
|
|
37
|
+
Multi-row notifications are split into individual row events before authorization, so an invisible row cannot suppress visible rows later in the batch.
|
|
38
|
+
|
|
39
|
+
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.
|
|
40
|
+
|
|
41
|
+
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.
|
|
42
|
+
|
|
43
|
+
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.
|
|
44
|
+
|
|
33
45
|
## Subscription Modes
|
|
34
46
|
|
|
35
47
|
### Phase 3a (current)
|
|
@@ -96,9 +108,10 @@ Install skills for AI coding agents:
|
|
|
96
108
|
# All platform skills (security, blueprints, codegen, billing, etc.)
|
|
97
109
|
npx skills add constructive-io/constructive-skills
|
|
98
110
|
|
|
99
|
-
# Individual repo skills (pgpm, testing, CLI, search, etc.)
|
|
100
|
-
npx skills add
|
|
101
|
-
npx skills add
|
|
111
|
+
# Individual repo skills (pgpm, safegres, testing, CLI, search, etc.)
|
|
112
|
+
npx skills add constructive-io/constructive --skill pgpm
|
|
113
|
+
npx skills add constructive-io/constructive --skill safegres
|
|
114
|
+
npx skills add constructive-io/constructive --skill constructive-testing
|
|
102
115
|
```
|
|
103
116
|
|
|
104
117
|
## Credits
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
export declare function filterMapIterator<T, U>(source: AsyncIterable<T>, transform: (value: T) => U | null): AsyncGenerator<U, void, void>;
|
|
2
|
+
export declare function flatMapIterator<T, U>(source: AsyncIterable<T>, transform: (value: T) => readonly U[]): AsyncGenerator<U, void, void>;
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.filterMapIterator = filterMapIterator;
|
|
4
|
+
exports.flatMapIterator = flatMapIterator;
|
|
5
|
+
function filterMapIterator(source, transform) {
|
|
6
|
+
return flatMapIterator(source, value => {
|
|
7
|
+
const result = transform(value);
|
|
8
|
+
return result === null ? [] : [result];
|
|
9
|
+
});
|
|
10
|
+
}
|
|
11
|
+
function flatMapIterator(source, transform) {
|
|
12
|
+
const iterator = source[Symbol.asyncIterator]();
|
|
13
|
+
let closed = false;
|
|
14
|
+
let pending = [];
|
|
15
|
+
let index = 0;
|
|
16
|
+
return {
|
|
17
|
+
[Symbol.asyncIterator]() { return this; },
|
|
18
|
+
async [Symbol.asyncDispose]() { await this.return(); },
|
|
19
|
+
async next() {
|
|
20
|
+
try {
|
|
21
|
+
while (!closed) {
|
|
22
|
+
if (index < pending.length)
|
|
23
|
+
return { done: false, value: pending[index++] };
|
|
24
|
+
const result = await iterator.next();
|
|
25
|
+
if (closed || result.done)
|
|
26
|
+
break;
|
|
27
|
+
pending = transform(result.value);
|
|
28
|
+
index = 0;
|
|
29
|
+
}
|
|
30
|
+
closed = true;
|
|
31
|
+
return { done: true, value: undefined };
|
|
32
|
+
}
|
|
33
|
+
catch (error) {
|
|
34
|
+
closed = true;
|
|
35
|
+
await iterator.return?.();
|
|
36
|
+
throw error;
|
|
37
|
+
}
|
|
38
|
+
},
|
|
39
|
+
async return() {
|
|
40
|
+
if (!closed) {
|
|
41
|
+
closed = true;
|
|
42
|
+
await iterator.return?.();
|
|
43
|
+
}
|
|
44
|
+
return { done: true, value: undefined };
|
|
45
|
+
},
|
|
46
|
+
async throw(error) {
|
|
47
|
+
if (!closed) {
|
|
48
|
+
closed = true;
|
|
49
|
+
await iterator.return?.();
|
|
50
|
+
}
|
|
51
|
+
throw error;
|
|
52
|
+
}
|
|
53
|
+
};
|
|
54
|
+
}
|
package/channel.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function realtimeChannel(schema: string, table: string): string;
|
package/channel.js
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.realtimeChannel = realtimeChannel;
|
|
4
|
+
const crypto_1 = require("crypto");
|
|
5
|
+
function realtimeChannel(schema, table) {
|
|
6
|
+
const key = `${Buffer.byteLength(schema, 'utf8')}:${schema}${table}`;
|
|
7
|
+
return `realtime:${(0, crypto_1.createHash)('md5').update(key, 'utf8').digest('hex')}`;
|
|
8
|
+
}
|
package/cursor-tracker.d.ts
CHANGED
|
@@ -16,7 +16,7 @@ import type { ChangeLogEntry, CursorTrackerOptions } from './types';
|
|
|
16
16
|
declare const DEFAULT_POLL_INTERVAL_MS = 5000;
|
|
17
17
|
declare const DEFAULT_HEARTBEAT_INTERVAL_MS = 30000;
|
|
18
18
|
declare const DEFAULT_BATCH_LIMIT = 500;
|
|
19
|
-
declare const DEFAULT_SCHEMA = "
|
|
19
|
+
declare const DEFAULT_SCHEMA = "realtime_private";
|
|
20
20
|
export declare class CursorTracker {
|
|
21
21
|
readonly nodeId: string;
|
|
22
22
|
private readonly schema;
|
|
@@ -29,6 +29,7 @@ export declare class CursorTracker {
|
|
|
29
29
|
private pollTimer;
|
|
30
30
|
private heartbeatTimer;
|
|
31
31
|
private running;
|
|
32
|
+
private cleanupPending;
|
|
32
33
|
private draining;
|
|
33
34
|
constructor(options: CursorTrackerOptions);
|
|
34
35
|
start(): Promise<void>;
|
|
@@ -36,6 +37,7 @@ export declare class CursorTracker {
|
|
|
36
37
|
drain(): Promise<ChangeLogEntry[]>;
|
|
37
38
|
touchListener(): Promise<void>;
|
|
38
39
|
cleanupEphemeral(): Promise<void>;
|
|
40
|
+
private runtimeSources;
|
|
39
41
|
get isRunning(): boolean;
|
|
40
42
|
private quoteIdent;
|
|
41
43
|
}
|
package/cursor-tracker.js
CHANGED
|
@@ -25,7 +25,7 @@ const DEFAULT_HEARTBEAT_INTERVAL_MS = 30000;
|
|
|
25
25
|
exports.DEFAULT_HEARTBEAT_INTERVAL_MS = DEFAULT_HEARTBEAT_INTERVAL_MS;
|
|
26
26
|
const DEFAULT_BATCH_LIMIT = 500;
|
|
27
27
|
exports.DEFAULT_BATCH_LIMIT = DEFAULT_BATCH_LIMIT;
|
|
28
|
-
const DEFAULT_SCHEMA = '
|
|
28
|
+
const DEFAULT_SCHEMA = 'realtime_private';
|
|
29
29
|
exports.DEFAULT_SCHEMA = DEFAULT_SCHEMA;
|
|
30
30
|
class CursorTracker {
|
|
31
31
|
nodeId;
|
|
@@ -39,6 +39,7 @@ class CursorTracker {
|
|
|
39
39
|
pollTimer = null;
|
|
40
40
|
heartbeatTimer = null;
|
|
41
41
|
running = false;
|
|
42
|
+
cleanupPending = false;
|
|
42
43
|
draining = false;
|
|
43
44
|
constructor(options) {
|
|
44
45
|
this.nodeId = options.nodeId ?? (0, crypto_1.randomUUID)();
|
|
@@ -57,18 +58,36 @@ class CursorTracker {
|
|
|
57
58
|
return;
|
|
58
59
|
this.running = true;
|
|
59
60
|
log.info(`Starting cursor tracker: node=${this.nodeId}, schema=${this.schema}`);
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
61
|
+
let registered = false;
|
|
62
|
+
try {
|
|
63
|
+
if (this.cleanupPending)
|
|
64
|
+
await this.cleanupEphemeral();
|
|
65
|
+
await this.touchListener();
|
|
66
|
+
registered = true;
|
|
67
|
+
this.cleanupPending = true;
|
|
68
|
+
await this.drain();
|
|
69
|
+
}
|
|
70
|
+
catch (error) {
|
|
71
|
+
this.running = false;
|
|
72
|
+
if (registered) {
|
|
73
|
+
try {
|
|
74
|
+
await this.cleanupEphemeral();
|
|
75
|
+
}
|
|
76
|
+
catch (cleanupError) {
|
|
77
|
+
throw new AggregateError([error, cleanupError], `Cursor startup and cleanup failed for node=${this.nodeId}`);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
throw error;
|
|
81
|
+
}
|
|
63
82
|
this.pollTimer = setInterval(() => {
|
|
64
|
-
void this.drain();
|
|
83
|
+
void this.drain().catch(this.onError);
|
|
65
84
|
}, this.pollIntervalMs);
|
|
66
85
|
this.heartbeatTimer = setInterval(() => {
|
|
67
|
-
void this.touchListener();
|
|
86
|
+
void this.touchListener().catch(this.onError);
|
|
68
87
|
}, this.heartbeatIntervalMs);
|
|
69
88
|
}
|
|
70
89
|
async stop() {
|
|
71
|
-
if (!this.running)
|
|
90
|
+
if (!this.running && !this.cleanupPending)
|
|
72
91
|
return;
|
|
73
92
|
this.running = false;
|
|
74
93
|
log.info(`Stopping cursor tracker: node=${this.nodeId}`);
|
|
@@ -89,16 +108,26 @@ class CursorTracker {
|
|
|
89
108
|
try {
|
|
90
109
|
const sql = `SELECT * FROM ${this.quoteIdent(this.schema)}.drain_changes($1, $2)`;
|
|
91
110
|
const result = await this.pool.query(sql, [this.nodeId, this.batchLimit]);
|
|
92
|
-
const
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
this.
|
|
111
|
+
const pending = result.rows.map((row) => row.drain_changes);
|
|
112
|
+
const entries = [];
|
|
113
|
+
if (pending.length > 0) {
|
|
114
|
+
for (const source of await this.runtimeSources()) {
|
|
115
|
+
const changes = pending.filter(change => change.source_schema === source.source_schema && change.source_table === source.source_table);
|
|
116
|
+
if (changes.length === 0)
|
|
117
|
+
continue;
|
|
118
|
+
const fanout = await this.pool.query(`SELECT ${this.quoteIdent(this.schema)}.${this.quoteIdent(source.fanout_function)}($1, $2) AS entry`, [this.nodeId, JSON.stringify(changes)]);
|
|
119
|
+
entries.push(...fanout.rows.map(row => row.entry));
|
|
120
|
+
}
|
|
121
|
+
if (entries.length > 0) {
|
|
122
|
+
log.info(`Drained ${entries.length} change(s) for node=${this.nodeId}`);
|
|
123
|
+
await this.onChanges(entries);
|
|
124
|
+
}
|
|
125
|
+
await this.pool.query(`SELECT ${this.quoteIdent(this.schema)}.advance_cursor($1, $2)`, [this.nodeId, pending[pending.length - 1].occurred_at]);
|
|
96
126
|
}
|
|
97
127
|
return entries;
|
|
98
128
|
}
|
|
99
129
|
catch (err) {
|
|
100
|
-
|
|
101
|
-
return [];
|
|
130
|
+
throw err instanceof Error ? err : new Error(String(err));
|
|
102
131
|
}
|
|
103
132
|
finally {
|
|
104
133
|
this.draining = false;
|
|
@@ -110,19 +139,27 @@ class CursorTracker {
|
|
|
110
139
|
await this.pool.query(sql, [this.nodeId]);
|
|
111
140
|
}
|
|
112
141
|
catch (err) {
|
|
113
|
-
|
|
142
|
+
throw err instanceof Error ? err : new Error(String(err));
|
|
114
143
|
}
|
|
115
144
|
}
|
|
116
145
|
async cleanupEphemeral() {
|
|
117
146
|
try {
|
|
147
|
+
for (const source of await this.runtimeSources()) {
|
|
148
|
+
await this.pool.query(`SELECT ${this.quoteIdent(this.schema)}.${this.quoteIdent(source.cleanup_function)}($1)`, [this.nodeId]);
|
|
149
|
+
}
|
|
118
150
|
const sql = `SELECT ${this.quoteIdent(this.schema)}.cleanup_ephemeral($1)`;
|
|
119
151
|
await this.pool.query(sql, [this.nodeId]);
|
|
152
|
+
this.cleanupPending = false;
|
|
120
153
|
log.info(`Cleaned up ephemeral subscriptions for node=${this.nodeId}`);
|
|
121
154
|
}
|
|
122
155
|
catch (err) {
|
|
123
|
-
|
|
156
|
+
throw err instanceof Error ? err : new Error(String(err));
|
|
124
157
|
}
|
|
125
158
|
}
|
|
159
|
+
async runtimeSources() {
|
|
160
|
+
const result = await this.pool.query(`SELECT * FROM ${this.quoteIdent(this.schema)}.runtime_sources()`);
|
|
161
|
+
return result.rows.map(row => row.runtime_sources);
|
|
162
|
+
}
|
|
126
163
|
get isRunning() {
|
|
127
164
|
return this.running;
|
|
128
165
|
}
|
package/delivery.d.ts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { type ParsedPayload } from './event-gate';
|
|
2
|
+
export declare class SubscriptionDelivery {
|
|
3
|
+
private readonly visibility;
|
|
4
|
+
private readonly throttle;
|
|
5
|
+
constructor(threshold: number);
|
|
6
|
+
project(payload: ParsedPayload, rowVisible: boolean): ParsedPayload | null;
|
|
7
|
+
}
|
package/delivery.js
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.SubscriptionDelivery = void 0;
|
|
4
|
+
const event_gate_1 = require("./event-gate");
|
|
5
|
+
const visibility_1 = require("./visibility");
|
|
6
|
+
class SubscriptionDelivery {
|
|
7
|
+
visibility = new visibility_1.SubscriptionVisibility();
|
|
8
|
+
throttle;
|
|
9
|
+
constructor(threshold) {
|
|
10
|
+
this.throttle = new event_gate_1.EventThrottle(threshold);
|
|
11
|
+
}
|
|
12
|
+
project(payload, rowVisible) {
|
|
13
|
+
if (!this.visibility.allow(payload, rowVisible))
|
|
14
|
+
return null;
|
|
15
|
+
const action = this.throttle.check();
|
|
16
|
+
if (action === 'drop')
|
|
17
|
+
return null;
|
|
18
|
+
if (action === 'overflow')
|
|
19
|
+
return { event: payload.event, rowIds: [], overflow: true };
|
|
20
|
+
return payload;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
exports.SubscriptionDelivery = SubscriptionDelivery;
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
export declare function filterMapIterator<T, U>(source: AsyncIterable<T>, transform: (value: T) => U | null): AsyncGenerator<U, void, void>;
|
|
2
|
+
export declare function flatMapIterator<T, U>(source: AsyncIterable<T>, transform: (value: T) => readonly U[]): AsyncGenerator<U, void, void>;
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
export function filterMapIterator(source, transform) {
|
|
2
|
+
return flatMapIterator(source, value => {
|
|
3
|
+
const result = transform(value);
|
|
4
|
+
return result === null ? [] : [result];
|
|
5
|
+
});
|
|
6
|
+
}
|
|
7
|
+
export function flatMapIterator(source, transform) {
|
|
8
|
+
const iterator = source[Symbol.asyncIterator]();
|
|
9
|
+
let closed = false;
|
|
10
|
+
let pending = [];
|
|
11
|
+
let index = 0;
|
|
12
|
+
return {
|
|
13
|
+
[Symbol.asyncIterator]() { return this; },
|
|
14
|
+
async [Symbol.asyncDispose]() { await this.return(); },
|
|
15
|
+
async next() {
|
|
16
|
+
try {
|
|
17
|
+
while (!closed) {
|
|
18
|
+
if (index < pending.length)
|
|
19
|
+
return { done: false, value: pending[index++] };
|
|
20
|
+
const result = await iterator.next();
|
|
21
|
+
if (closed || result.done)
|
|
22
|
+
break;
|
|
23
|
+
pending = transform(result.value);
|
|
24
|
+
index = 0;
|
|
25
|
+
}
|
|
26
|
+
closed = true;
|
|
27
|
+
return { done: true, value: undefined };
|
|
28
|
+
}
|
|
29
|
+
catch (error) {
|
|
30
|
+
closed = true;
|
|
31
|
+
await iterator.return?.();
|
|
32
|
+
throw error;
|
|
33
|
+
}
|
|
34
|
+
},
|
|
35
|
+
async return() {
|
|
36
|
+
if (!closed) {
|
|
37
|
+
closed = true;
|
|
38
|
+
await iterator.return?.();
|
|
39
|
+
}
|
|
40
|
+
return { done: true, value: undefined };
|
|
41
|
+
},
|
|
42
|
+
async throw(error) {
|
|
43
|
+
if (!closed) {
|
|
44
|
+
closed = true;
|
|
45
|
+
await iterator.return?.();
|
|
46
|
+
}
|
|
47
|
+
throw error;
|
|
48
|
+
}
|
|
49
|
+
};
|
|
50
|
+
}
|
package/esm/channel.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function realtimeChannel(schema: string, table: string): string;
|
package/esm/channel.js
ADDED
package/esm/cursor-tracker.d.ts
CHANGED
|
@@ -16,7 +16,7 @@ import type { ChangeLogEntry, CursorTrackerOptions } from './types';
|
|
|
16
16
|
declare const DEFAULT_POLL_INTERVAL_MS = 5000;
|
|
17
17
|
declare const DEFAULT_HEARTBEAT_INTERVAL_MS = 30000;
|
|
18
18
|
declare const DEFAULT_BATCH_LIMIT = 500;
|
|
19
|
-
declare const DEFAULT_SCHEMA = "
|
|
19
|
+
declare const DEFAULT_SCHEMA = "realtime_private";
|
|
20
20
|
export declare class CursorTracker {
|
|
21
21
|
readonly nodeId: string;
|
|
22
22
|
private readonly schema;
|
|
@@ -29,6 +29,7 @@ export declare class CursorTracker {
|
|
|
29
29
|
private pollTimer;
|
|
30
30
|
private heartbeatTimer;
|
|
31
31
|
private running;
|
|
32
|
+
private cleanupPending;
|
|
32
33
|
private draining;
|
|
33
34
|
constructor(options: CursorTrackerOptions);
|
|
34
35
|
start(): Promise<void>;
|
|
@@ -36,6 +37,7 @@ export declare class CursorTracker {
|
|
|
36
37
|
drain(): Promise<ChangeLogEntry[]>;
|
|
37
38
|
touchListener(): Promise<void>;
|
|
38
39
|
cleanupEphemeral(): Promise<void>;
|
|
40
|
+
private runtimeSources;
|
|
39
41
|
get isRunning(): boolean;
|
|
40
42
|
private quoteIdent;
|
|
41
43
|
}
|
package/esm/cursor-tracker.js
CHANGED
|
@@ -19,7 +19,7 @@ const log = new Logger('cursor-tracker');
|
|
|
19
19
|
const DEFAULT_POLL_INTERVAL_MS = 5000;
|
|
20
20
|
const DEFAULT_HEARTBEAT_INTERVAL_MS = 30000;
|
|
21
21
|
const DEFAULT_BATCH_LIMIT = 500;
|
|
22
|
-
const DEFAULT_SCHEMA = '
|
|
22
|
+
const DEFAULT_SCHEMA = 'realtime_private';
|
|
23
23
|
export class CursorTracker {
|
|
24
24
|
nodeId;
|
|
25
25
|
schema;
|
|
@@ -32,6 +32,7 @@ export class CursorTracker {
|
|
|
32
32
|
pollTimer = null;
|
|
33
33
|
heartbeatTimer = null;
|
|
34
34
|
running = false;
|
|
35
|
+
cleanupPending = false;
|
|
35
36
|
draining = false;
|
|
36
37
|
constructor(options) {
|
|
37
38
|
this.nodeId = options.nodeId ?? randomUUID();
|
|
@@ -50,18 +51,36 @@ export class CursorTracker {
|
|
|
50
51
|
return;
|
|
51
52
|
this.running = true;
|
|
52
53
|
log.info(`Starting cursor tracker: node=${this.nodeId}, schema=${this.schema}`);
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
54
|
+
let registered = false;
|
|
55
|
+
try {
|
|
56
|
+
if (this.cleanupPending)
|
|
57
|
+
await this.cleanupEphemeral();
|
|
58
|
+
await this.touchListener();
|
|
59
|
+
registered = true;
|
|
60
|
+
this.cleanupPending = true;
|
|
61
|
+
await this.drain();
|
|
62
|
+
}
|
|
63
|
+
catch (error) {
|
|
64
|
+
this.running = false;
|
|
65
|
+
if (registered) {
|
|
66
|
+
try {
|
|
67
|
+
await this.cleanupEphemeral();
|
|
68
|
+
}
|
|
69
|
+
catch (cleanupError) {
|
|
70
|
+
throw new AggregateError([error, cleanupError], `Cursor startup and cleanup failed for node=${this.nodeId}`);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
throw error;
|
|
74
|
+
}
|
|
56
75
|
this.pollTimer = setInterval(() => {
|
|
57
|
-
void this.drain();
|
|
76
|
+
void this.drain().catch(this.onError);
|
|
58
77
|
}, this.pollIntervalMs);
|
|
59
78
|
this.heartbeatTimer = setInterval(() => {
|
|
60
|
-
void this.touchListener();
|
|
79
|
+
void this.touchListener().catch(this.onError);
|
|
61
80
|
}, this.heartbeatIntervalMs);
|
|
62
81
|
}
|
|
63
82
|
async stop() {
|
|
64
|
-
if (!this.running)
|
|
83
|
+
if (!this.running && !this.cleanupPending)
|
|
65
84
|
return;
|
|
66
85
|
this.running = false;
|
|
67
86
|
log.info(`Stopping cursor tracker: node=${this.nodeId}`);
|
|
@@ -82,16 +101,26 @@ export class CursorTracker {
|
|
|
82
101
|
try {
|
|
83
102
|
const sql = `SELECT * FROM ${this.quoteIdent(this.schema)}.drain_changes($1, $2)`;
|
|
84
103
|
const result = await this.pool.query(sql, [this.nodeId, this.batchLimit]);
|
|
85
|
-
const
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
this.
|
|
104
|
+
const pending = result.rows.map((row) => row.drain_changes);
|
|
105
|
+
const entries = [];
|
|
106
|
+
if (pending.length > 0) {
|
|
107
|
+
for (const source of await this.runtimeSources()) {
|
|
108
|
+
const changes = pending.filter(change => change.source_schema === source.source_schema && change.source_table === source.source_table);
|
|
109
|
+
if (changes.length === 0)
|
|
110
|
+
continue;
|
|
111
|
+
const fanout = await this.pool.query(`SELECT ${this.quoteIdent(this.schema)}.${this.quoteIdent(source.fanout_function)}($1, $2) AS entry`, [this.nodeId, JSON.stringify(changes)]);
|
|
112
|
+
entries.push(...fanout.rows.map(row => row.entry));
|
|
113
|
+
}
|
|
114
|
+
if (entries.length > 0) {
|
|
115
|
+
log.info(`Drained ${entries.length} change(s) for node=${this.nodeId}`);
|
|
116
|
+
await this.onChanges(entries);
|
|
117
|
+
}
|
|
118
|
+
await this.pool.query(`SELECT ${this.quoteIdent(this.schema)}.advance_cursor($1, $2)`, [this.nodeId, pending[pending.length - 1].occurred_at]);
|
|
89
119
|
}
|
|
90
120
|
return entries;
|
|
91
121
|
}
|
|
92
122
|
catch (err) {
|
|
93
|
-
|
|
94
|
-
return [];
|
|
123
|
+
throw err instanceof Error ? err : new Error(String(err));
|
|
95
124
|
}
|
|
96
125
|
finally {
|
|
97
126
|
this.draining = false;
|
|
@@ -103,19 +132,27 @@ export class CursorTracker {
|
|
|
103
132
|
await this.pool.query(sql, [this.nodeId]);
|
|
104
133
|
}
|
|
105
134
|
catch (err) {
|
|
106
|
-
|
|
135
|
+
throw err instanceof Error ? err : new Error(String(err));
|
|
107
136
|
}
|
|
108
137
|
}
|
|
109
138
|
async cleanupEphemeral() {
|
|
110
139
|
try {
|
|
140
|
+
for (const source of await this.runtimeSources()) {
|
|
141
|
+
await this.pool.query(`SELECT ${this.quoteIdent(this.schema)}.${this.quoteIdent(source.cleanup_function)}($1)`, [this.nodeId]);
|
|
142
|
+
}
|
|
111
143
|
const sql = `SELECT ${this.quoteIdent(this.schema)}.cleanup_ephemeral($1)`;
|
|
112
144
|
await this.pool.query(sql, [this.nodeId]);
|
|
145
|
+
this.cleanupPending = false;
|
|
113
146
|
log.info(`Cleaned up ephemeral subscriptions for node=${this.nodeId}`);
|
|
114
147
|
}
|
|
115
148
|
catch (err) {
|
|
116
|
-
|
|
149
|
+
throw err instanceof Error ? err : new Error(String(err));
|
|
117
150
|
}
|
|
118
151
|
}
|
|
152
|
+
async runtimeSources() {
|
|
153
|
+
const result = await this.pool.query(`SELECT * FROM ${this.quoteIdent(this.schema)}.runtime_sources()`);
|
|
154
|
+
return result.rows.map(row => row.runtime_sources);
|
|
155
|
+
}
|
|
119
156
|
get isRunning() {
|
|
120
157
|
return this.running;
|
|
121
158
|
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { type ParsedPayload } from './event-gate';
|
|
2
|
+
export declare class SubscriptionDelivery {
|
|
3
|
+
private readonly visibility;
|
|
4
|
+
private readonly throttle;
|
|
5
|
+
constructor(threshold: number);
|
|
6
|
+
project(payload: ParsedPayload, rowVisible: boolean): ParsedPayload | null;
|
|
7
|
+
}
|
package/esm/delivery.js
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { EventThrottle } from './event-gate';
|
|
2
|
+
import { SubscriptionVisibility } from './visibility';
|
|
3
|
+
export class SubscriptionDelivery {
|
|
4
|
+
visibility = new SubscriptionVisibility();
|
|
5
|
+
throttle;
|
|
6
|
+
constructor(threshold) {
|
|
7
|
+
this.throttle = new EventThrottle(threshold);
|
|
8
|
+
}
|
|
9
|
+
project(payload, rowVisible) {
|
|
10
|
+
if (!this.visibility.allow(payload, rowVisible))
|
|
11
|
+
return null;
|
|
12
|
+
const action = this.throttle.check();
|
|
13
|
+
if (action === 'drop')
|
|
14
|
+
return null;
|
|
15
|
+
if (action === 'overflow')
|
|
16
|
+
return { event: payload.event, rowIds: [], overflow: true };
|
|
17
|
+
return payload;
|
|
18
|
+
}
|
|
19
|
+
}
|
package/esm/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
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
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
|
-
*
|
|
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 `"
|
|
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
|
|
67
|
-
*
|
|
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
|
|
59
|
+
export declare function createGatedSubscriber(inner: GrafastSubscriber<Record<string, string>>, { ids }: EventGateOptions): GrafastSubscriber<Record<string, ParsedPayload>>;
|