nowity 1.0.0
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 +751 -0
- package/dist/api/contract.d.ts +186 -0
- package/dist/api/contract.d.ts.map +1 -0
- package/dist/api/contract.js +251 -0
- package/dist/api/errors.d.ts +50 -0
- package/dist/api/errors.d.ts.map +1 -0
- package/dist/api/errors.js +50 -0
- package/dist/api/index.d.ts +13 -0
- package/dist/api/index.d.ts.map +1 -0
- package/dist/api/index.js +32 -0
- package/dist/client/confirmed-store.d.ts +33 -0
- package/dist/client/confirmed-store.d.ts.map +1 -0
- package/dist/client/confirmed-store.js +123 -0
- package/dist/client/connection.d.ts +102 -0
- package/dist/client/connection.d.ts.map +1 -0
- package/dist/client/connection.js +285 -0
- package/dist/client/list.d.ts +102 -0
- package/dist/client/list.d.ts.map +1 -0
- package/dist/client/list.js +257 -0
- package/dist/client/live-query.d.ts +153 -0
- package/dist/client/live-query.d.ts.map +1 -0
- package/dist/client/live-query.js +244 -0
- package/dist/client/nowity-client.d.ts +188 -0
- package/dist/client/nowity-client.d.ts.map +1 -0
- package/dist/client/nowity-client.js +580 -0
- package/dist/client/null-transport.d.ts +16 -0
- package/dist/client/null-transport.d.ts.map +1 -0
- package/dist/client/null-transport.js +17 -0
- package/dist/client/overlay.d.ts +44 -0
- package/dist/client/overlay.d.ts.map +1 -0
- package/dist/client/overlay.js +90 -0
- package/dist/client/query-source.d.ts +78 -0
- package/dist/client/query-source.d.ts.map +1 -0
- package/dist/client/query-source.js +57 -0
- package/dist/client/ssr-source.d.ts +70 -0
- package/dist/client/ssr-source.d.ts.map +1 -0
- package/dist/client/ssr-source.js +134 -0
- package/dist/client/transport.d.ts +19 -0
- package/dist/client/transport.d.ts.map +1 -0
- package/dist/client/transport.js +2 -0
- package/dist/client/ws-transport.d.ts +30 -0
- package/dist/client/ws-transport.d.ts.map +1 -0
- package/dist/client/ws-transport.js +89 -0
- package/dist/client.d.ts +47 -0
- package/dist/client.d.ts.map +1 -0
- package/dist/client.js +80 -0
- package/dist/core/diff.d.ts +14 -0
- package/dist/core/diff.d.ts.map +1 -0
- package/dist/core/diff.js +56 -0
- package/dist/core/normalize.d.ts +16 -0
- package/dist/core/normalize.d.ts.map +1 -0
- package/dist/core/normalize.js +67 -0
- package/dist/core/protocol.d.ts +215 -0
- package/dist/core/protocol.d.ts.map +1 -0
- package/dist/core/protocol.js +14 -0
- package/dist/core/ssr-bridge.d.ts +69 -0
- package/dist/core/ssr-bridge.d.ts.map +1 -0
- package/dist/core/ssr-bridge.js +40 -0
- package/dist/core/types.d.ts +96 -0
- package/dist/core/types.d.ts.map +1 -0
- package/dist/core/types.js +17 -0
- package/dist/index.d.ts +47 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +98 -0
- package/dist/ironbean/client.d.ts +7 -0
- package/dist/ironbean/client.d.ts.map +1 -0
- package/dist/ironbean/client.js +38 -0
- package/dist/ironbean/server.d.ts +42 -0
- package/dist/ironbean/server.d.ts.map +1 -0
- package/dist/ironbean/server.js +62 -0
- package/dist/ironbean/tokens.d.ts +26 -0
- package/dist/ironbean/tokens.d.ts.map +1 -0
- package/dist/ironbean/tokens.js +23 -0
- package/dist/next/config.d.ts +7 -0
- package/dist/next/config.d.ts.map +1 -0
- package/dist/next/config.js +77 -0
- package/dist/next/live.d.ts +69 -0
- package/dist/next/live.d.ts.map +1 -0
- package/dist/next/live.js +70 -0
- package/dist/next/serve.d.ts +44 -0
- package/dist/next/serve.d.ts.map +1 -0
- package/dist/next/serve.js +107 -0
- package/dist/next/server.d.ts +62 -0
- package/dist/next/server.d.ts.map +1 -0
- package/dist/next/server.js +127 -0
- package/dist/react/connection-context.d.ts +4 -0
- package/dist/react/connection-context.d.ts.map +1 -0
- package/dist/react/connection-context.js +28 -0
- package/dist/react/grid-list.d.ts +34 -0
- package/dist/react/grid-list.d.ts.map +1 -0
- package/dist/react/grid-list.js +62 -0
- package/dist/react/hydrate.d.ts +22 -0
- package/dist/react/hydrate.d.ts.map +1 -0
- package/dist/react/hydrate.js +18 -0
- package/dist/react/index.d.ts +35 -0
- package/dist/react/index.d.ts.map +1 -0
- package/dist/react/index.js +51 -0
- package/dist/react/list.d.ts +31 -0
- package/dist/react/list.d.ts.map +1 -0
- package/dist/react/list.js +35 -0
- package/dist/react/prerendered.d.ts +33 -0
- package/dist/react/prerendered.d.ts.map +1 -0
- package/dist/react/prerendered.js +165 -0
- package/dist/react/provider.d.ts +64 -0
- package/dist/react/provider.d.ts.map +1 -0
- package/dist/react/provider.js +130 -0
- package/dist/react/refusals.d.ts +31 -0
- package/dist/react/refusals.d.ts.map +1 -0
- package/dist/react/refusals.js +51 -0
- package/dist/react/restricted.d.ts +76 -0
- package/dist/react/restricted.d.ts.map +1 -0
- package/dist/react/restricted.js +126 -0
- package/dist/react/use-list.d.ts +42 -0
- package/dist/react/use-list.d.ts.map +1 -0
- package/dist/react/use-list.js +56 -0
- package/dist/react/use-query.d.ts +66 -0
- package/dist/react/use-query.d.ts.map +1 -0
- package/dist/react/use-query.js +126 -0
- package/dist/react/virtual.d.ts +60 -0
- package/dist/react/virtual.d.ts.map +1 -0
- package/dist/react/virtual.js +131 -0
- package/dist/server/api/auth.d.ts +37 -0
- package/dist/server/api/auth.d.ts.map +1 -0
- package/dist/server/api/auth.js +54 -0
- package/dist/server/api/bridge.d.ts +28 -0
- package/dist/server/api/bridge.d.ts.map +1 -0
- package/dist/server/api/bridge.js +330 -0
- package/dist/server/api/collector.d.ts +25 -0
- package/dist/server/api/collector.d.ts.map +1 -0
- package/dist/server/api/collector.js +184 -0
- package/dist/server/api/configure.d.ts +31 -0
- package/dist/server/api/configure.d.ts.map +1 -0
- package/dist/server/api/configure.js +67 -0
- package/dist/server/api/execution.d.ts +77 -0
- package/dist/server/api/execution.d.ts.map +1 -0
- package/dist/server/api/execution.js +97 -0
- package/dist/server/api/list.d.ts +141 -0
- package/dist/server/api/list.d.ts.map +1 -0
- package/dist/server/api/list.js +281 -0
- package/dist/server/api/prerender.d.ts +32 -0
- package/dist/server/api/prerender.d.ts.map +1 -0
- package/dist/server/api/prerender.js +69 -0
- package/dist/server/api/read-keys.d.ts +128 -0
- package/dist/server/api/read-keys.d.ts.map +1 -0
- package/dist/server/api/read-keys.js +464 -0
- package/dist/server/api/read-set.d.ts +103 -0
- package/dist/server/api/read-set.d.ts.map +1 -0
- package/dist/server/api/read-set.js +210 -0
- package/dist/server/api/runtime.d.ts +36 -0
- package/dist/server/api/runtime.d.ts.map +1 -0
- package/dist/server/api/runtime.js +49 -0
- package/dist/server/api/tracked-client.d.ts +6 -0
- package/dist/server/api/tracked-client.d.ts.map +1 -0
- package/dist/server/api/tracked-client.js +56 -0
- package/dist/server/change-source/change-source.d.ts +41 -0
- package/dist/server/change-source/change-source.d.ts.map +1 -0
- package/dist/server/change-source/change-source.js +2 -0
- package/dist/server/change-source/outbox-change-source.d.ts +106 -0
- package/dist/server/change-source/outbox-change-source.d.ts.map +1 -0
- package/dist/server/change-source/outbox-change-source.js +237 -0
- package/dist/server/change-source/wal-change-source.d.ts +85 -0
- package/dist/server/change-source/wal-change-source.d.ts.map +1 -0
- package/dist/server/change-source/wal-change-source.js +193 -0
- package/dist/server/db.d.ts +51 -0
- package/dist/server/db.d.ts.map +1 -0
- package/dist/server/db.js +53 -0
- package/dist/server/evaluate.d.ts +39 -0
- package/dist/server/evaluate.d.ts.map +1 -0
- package/dist/server/evaluate.js +61 -0
- package/dist/server/invalidation-index.d.ts +64 -0
- package/dist/server/invalidation-index.d.ts.map +1 -0
- package/dist/server/invalidation-index.js +0 -0
- package/dist/server/mutator.d.ts +59 -0
- package/dist/server/mutator.d.ts.map +1 -0
- package/dist/server/mutator.js +77 -0
- package/dist/server/query.d.ts +113 -0
- package/dist/server/query.d.ts.map +1 -0
- package/dist/server/query.js +35 -0
- package/dist/server/setup.d.ts +30 -0
- package/dist/server/setup.d.ts.map +1 -0
- package/dist/server/setup.js +107 -0
- package/dist/server/sql/setup.sql +215 -0
- package/dist/server/ssr.d.ts +29 -0
- package/dist/server/ssr.d.ts.map +1 -0
- package/dist/server/ssr.js +43 -0
- package/dist/server/sync-engine.d.ts +256 -0
- package/dist/server/sync-engine.d.ts.map +1 -0
- package/dist/server/sync-engine.js +805 -0
- package/dist/server/ws-server.d.ts +56 -0
- package/dist/server/ws-server.d.ts.map +1 -0
- package/dist/server/ws-server.js +241 -0
- package/package.json +81 -0
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.OutboxChangeSource = void 0;
|
|
4
|
+
const node_crypto_1 = require("node:crypto");
|
|
5
|
+
const normalize_1 = require("../../core/normalize");
|
|
6
|
+
const SELECT_COLUMNS = `seq::text AS seq, xid::text AS xid, tbl, op, pk, before, after, client_id, mutation_id::text AS mutation_id`;
|
|
7
|
+
/**
|
|
8
|
+
* Change source built on an outbox table filled by triggers, woken by
|
|
9
|
+
* LISTEN/NOTIFY.
|
|
10
|
+
*
|
|
11
|
+
* The interesting part is the read cursor. `seq` alone is not usable: sequence
|
|
12
|
+
* values are assigned before commit, so ordering by `seq` can walk past a row
|
|
13
|
+
* whose transaction commits later, and that row would then be filtered out by
|
|
14
|
+
* `seq > cursor` forever. Instead the reader only consumes rows whose `xid` is
|
|
15
|
+
* strictly below `pg_snapshot_xmin(pg_current_snapshot())` — the oldest
|
|
16
|
+
* transaction id still in flight. That set has two properties we need:
|
|
17
|
+
*
|
|
18
|
+
* - every transaction in it is committed (nothing below xmin can still be
|
|
19
|
+
* running), and no new row can ever appear with such an `xid`;
|
|
20
|
+
* - it grows as a *prefix* of the `xid` order, so a single `xid` cursor is a
|
|
21
|
+
* complete, gap-free bookmark.
|
|
22
|
+
*
|
|
23
|
+
* Cost of that guarantee: one long-running *write* transaction anywhere in the
|
|
24
|
+
* database stalls the stream until it finishes (read-only transactions do not,
|
|
25
|
+
* they never get an xid). For an application with short transactions this is
|
|
26
|
+
* fine; if it ever stops being fine, that is the moment to switch to the WAL
|
|
27
|
+
* source, which gets true commit ordering from the server.
|
|
28
|
+
*/
|
|
29
|
+
class OutboxChangeSource {
|
|
30
|
+
constructor(opts) {
|
|
31
|
+
this.name = "outbox";
|
|
32
|
+
/** The trigger stamps every row with the mutation that produced it. */
|
|
33
|
+
this.attributesWrites = true;
|
|
34
|
+
this.cursor = 0n;
|
|
35
|
+
/** Last cursor written to `nowity_consumer`; avoids a write per idle lap. */
|
|
36
|
+
this.publishedCursor = null;
|
|
37
|
+
this.handler = null;
|
|
38
|
+
this.listener = null;
|
|
39
|
+
this.timer = null;
|
|
40
|
+
this.pruneTimer = null;
|
|
41
|
+
this.running = false;
|
|
42
|
+
this.draining = null;
|
|
43
|
+
/** Monotonic "please take another lap" counter, see {@link drain}. */
|
|
44
|
+
this.requestSeq = 0;
|
|
45
|
+
this.servedSeq = 0;
|
|
46
|
+
this.pool = opts.pool;
|
|
47
|
+
this.channel = opts.channel ?? "nowity_change";
|
|
48
|
+
this.pollIntervalMs = opts.pollIntervalMs ?? 250;
|
|
49
|
+
this.batchSize = opts.batchSize ?? 500;
|
|
50
|
+
this.consumerId = opts.consumerId ?? `outbox-${(0, node_crypto_1.randomUUID)()}`;
|
|
51
|
+
this.pruneIntervalMs = opts.pruneIntervalMs ?? 0;
|
|
52
|
+
this.pruneStaleAfter = opts.pruneStaleAfter ?? "1 hour";
|
|
53
|
+
this.onError = opts.onError ?? ((err) => console.error("[nowity/outbox]", err));
|
|
54
|
+
}
|
|
55
|
+
async startPosition(snap) {
|
|
56
|
+
const { rows } = await snap.query(`SELECT pg_snapshot_xmin(pg_current_snapshot())::text AS xmin`);
|
|
57
|
+
// Transactions below xmin are committed *and* visible in this snapshot.
|
|
58
|
+
// Everything from xmin upwards may be missing from it, so replay starts
|
|
59
|
+
// there — hence the cursor is xmin - 1 ("last fully handled xid").
|
|
60
|
+
const xmin = BigInt(rows[0].xmin);
|
|
61
|
+
return (xmin - 1n).toString();
|
|
62
|
+
}
|
|
63
|
+
async start(from, handler) {
|
|
64
|
+
this.cursor = BigInt(from);
|
|
65
|
+
this.handler = handler;
|
|
66
|
+
this.running = true;
|
|
67
|
+
// Registered before the first read, so retention cannot delete rows this
|
|
68
|
+
// reader is about to want. A reader that appeared after a prune would
|
|
69
|
+
// not read a hole — it resumes from the transaction horizon — but it
|
|
70
|
+
// would silently miss what was deleted.
|
|
71
|
+
await this.publishCursor();
|
|
72
|
+
if (this.pruneIntervalMs > 0) {
|
|
73
|
+
this.pruneTimer = setInterval(() => {
|
|
74
|
+
this.prune().catch((err) => this.onError(err));
|
|
75
|
+
}, this.pruneIntervalMs);
|
|
76
|
+
if (typeof this.pruneTimer.unref === "function")
|
|
77
|
+
this.pruneTimer.unref();
|
|
78
|
+
}
|
|
79
|
+
this.listener = await this.pool.connect();
|
|
80
|
+
this.listener.on("notification", () => this.wake());
|
|
81
|
+
this.listener.on("error", (err) => this.onError(err));
|
|
82
|
+
await this.listener.query(`LISTEN ${this.channel}`);
|
|
83
|
+
this.timer = setInterval(() => this.wake(), this.pollIntervalMs);
|
|
84
|
+
if (typeof this.timer.unref === "function")
|
|
85
|
+
this.timer.unref();
|
|
86
|
+
await this.drain();
|
|
87
|
+
}
|
|
88
|
+
async stop() {
|
|
89
|
+
this.running = false;
|
|
90
|
+
if (this.timer)
|
|
91
|
+
clearInterval(this.timer);
|
|
92
|
+
this.timer = null;
|
|
93
|
+
if (this.pruneTimer)
|
|
94
|
+
clearInterval(this.pruneTimer);
|
|
95
|
+
this.pruneTimer = null;
|
|
96
|
+
await this.draining?.catch(() => undefined);
|
|
97
|
+
// A clean shutdown gives its watermark back immediately, rather than
|
|
98
|
+
// holding retention until it ages out.
|
|
99
|
+
await this.pool
|
|
100
|
+
.query(`SELECT nowity_consumer_forget($1)`, [this.consumerId])
|
|
101
|
+
.catch(() => undefined);
|
|
102
|
+
this.publishedCursor = null;
|
|
103
|
+
if (this.listener) {
|
|
104
|
+
await this.listener.query(`UNLISTEN ${this.channel}`).catch(() => undefined);
|
|
105
|
+
this.listener.removeAllListeners("notification");
|
|
106
|
+
this.listener.release();
|
|
107
|
+
this.listener = null;
|
|
108
|
+
}
|
|
109
|
+
this.handler = null;
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Read and dispatch everything currently eligible.
|
|
113
|
+
*
|
|
114
|
+
* Resolves only after a read that *started* after this call, so a test can
|
|
115
|
+
* write to the database, `await drain()`, and know the change has been
|
|
116
|
+
* handed to the engine. The `requestSeq`/`servedSeq` pair is what makes that
|
|
117
|
+
* true even when a read is already in flight: the running loop takes another
|
|
118
|
+
* lap instead of the caller silently piggybacking on a read that began too
|
|
119
|
+
* early.
|
|
120
|
+
*/
|
|
121
|
+
async drain() {
|
|
122
|
+
const mySeq = ++this.requestSeq;
|
|
123
|
+
while (this.servedSeq < mySeq) {
|
|
124
|
+
if (this.draining) {
|
|
125
|
+
await this.draining;
|
|
126
|
+
continue;
|
|
127
|
+
}
|
|
128
|
+
this.draining = this.drainLoop().finally(() => {
|
|
129
|
+
this.draining = null;
|
|
130
|
+
});
|
|
131
|
+
await this.draining;
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
wake() {
|
|
135
|
+
if (!this.running)
|
|
136
|
+
return;
|
|
137
|
+
this.drain().catch((err) => this.onError(err));
|
|
138
|
+
}
|
|
139
|
+
async drainLoop() {
|
|
140
|
+
// Claim every request made so far; a request arriving mid-loop bumps
|
|
141
|
+
// requestSeq again and gets its own lap.
|
|
142
|
+
const claimed = this.requestSeq;
|
|
143
|
+
try {
|
|
144
|
+
// eslint-disable-next-line no-constant-condition
|
|
145
|
+
while (true) {
|
|
146
|
+
const rows = await this.fetch();
|
|
147
|
+
if (rows.length === 0)
|
|
148
|
+
break;
|
|
149
|
+
for (const batch of groupByTransaction(rows)) {
|
|
150
|
+
if (!this.handler)
|
|
151
|
+
return;
|
|
152
|
+
await this.handler(batch);
|
|
153
|
+
this.cursor = BigInt(batch.position);
|
|
154
|
+
}
|
|
155
|
+
// Once per lap rather than once per transaction: the watermark
|
|
156
|
+
// only has to be behind-or-equal to be safe, and a write per
|
|
157
|
+
// change would double the cost of every change.
|
|
158
|
+
await this.publishCursor();
|
|
159
|
+
}
|
|
160
|
+
this.servedSeq = Math.max(this.servedSeq, claimed);
|
|
161
|
+
}
|
|
162
|
+
catch (err) {
|
|
163
|
+
// Do not mark the request served — the caller retries on the next lap.
|
|
164
|
+
throw err;
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
/** Tell retention where this reader is, when it has moved. */
|
|
168
|
+
async publishCursor() {
|
|
169
|
+
if (this.publishedCursor === this.cursor)
|
|
170
|
+
return;
|
|
171
|
+
await this.pool.query(`SELECT nowity_consumer_seen($1, $2)`, [
|
|
172
|
+
this.consumerId,
|
|
173
|
+
this.cursor.toString(),
|
|
174
|
+
]);
|
|
175
|
+
this.publishedCursor = this.cursor;
|
|
176
|
+
}
|
|
177
|
+
/**
|
|
178
|
+
* Delete what every live reader has passed. Returns how many rows went.
|
|
179
|
+
*
|
|
180
|
+
* Safe to run from every node at once: the bound is the slowest live
|
|
181
|
+
* consumer's cursor, so two nodes pruning concurrently delete the same rows
|
|
182
|
+
* rather than each other's.
|
|
183
|
+
*/
|
|
184
|
+
async prune() {
|
|
185
|
+
const { rows } = await this.pool.query(`SELECT nowity_prune_outbox($1::interval) AS deleted`, [
|
|
186
|
+
this.pruneStaleAfter,
|
|
187
|
+
]);
|
|
188
|
+
return Number(rows[0]?.deleted ?? 0);
|
|
189
|
+
}
|
|
190
|
+
async fetch() {
|
|
191
|
+
const { rows } = (await this.pool.query(`SELECT ${SELECT_COLUMNS}
|
|
192
|
+
FROM nowity_outbox
|
|
193
|
+
WHERE xid > $1::xid8
|
|
194
|
+
AND xid < pg_snapshot_xmin(pg_current_snapshot())
|
|
195
|
+
ORDER BY xid, seq
|
|
196
|
+
LIMIT $2`, [this.cursor.toString(), this.batchSize]));
|
|
197
|
+
if (rows.length < this.batchSize)
|
|
198
|
+
return rows;
|
|
199
|
+
// The limit may have cut a transaction in half; drop the trailing group
|
|
200
|
+
// so no batch is ever delivered incomplete.
|
|
201
|
+
const lastXid = rows[rows.length - 1].xid;
|
|
202
|
+
const trimmed = rows.filter((r) => r.xid !== lastXid);
|
|
203
|
+
if (trimmed.length > 0)
|
|
204
|
+
return trimmed;
|
|
205
|
+
// A single transaction larger than the batch size: fetch it whole.
|
|
206
|
+
const { rows: whole } = (await this.pool.query(`SELECT ${SELECT_COLUMNS}
|
|
207
|
+
FROM nowity_outbox
|
|
208
|
+
WHERE xid = $1::xid8
|
|
209
|
+
ORDER BY seq`, [lastXid]));
|
|
210
|
+
return whole;
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
exports.OutboxChangeSource = OutboxChangeSource;
|
|
214
|
+
function groupByTransaction(rows) {
|
|
215
|
+
const batches = [];
|
|
216
|
+
let current = null;
|
|
217
|
+
for (const row of rows) {
|
|
218
|
+
if (!current || current.xid !== row.xid) {
|
|
219
|
+
current = { position: row.xid, xid: row.xid, events: [] };
|
|
220
|
+
batches.push(current);
|
|
221
|
+
}
|
|
222
|
+
current.events.push({
|
|
223
|
+
table: row.tbl,
|
|
224
|
+
op: row.op,
|
|
225
|
+
pk: (0, normalize_1.normalizeRow)(row.pk ?? {}),
|
|
226
|
+
before: row.before ? (0, normalize_1.normalizeRow)(row.before) : null,
|
|
227
|
+
after: row.after ? (0, normalize_1.normalizeRow)(row.after) : null,
|
|
228
|
+
clientId: row.client_id,
|
|
229
|
+
mutationId: row.mutation_id === null ? null : Number(row.mutation_id),
|
|
230
|
+
// The capture trigger stores `to_jsonb(OLD)`, so the previous row is
|
|
231
|
+
// always whole here — a row leaving a live query's filter is visible
|
|
232
|
+
// without any per-table configuration.
|
|
233
|
+
beforeComplete: true,
|
|
234
|
+
});
|
|
235
|
+
}
|
|
236
|
+
return batches;
|
|
237
|
+
}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import type { Pool } from "pg";
|
|
2
|
+
import type { SnapshotContext } from "../db";
|
|
3
|
+
import type { BatchHandler, ChangeSource } from "./change-source";
|
|
4
|
+
export interface WalChangeSourceOptions {
|
|
5
|
+
/** Pool used only for slot management and bookkeeping. */
|
|
6
|
+
pool: Pool;
|
|
7
|
+
/** Connection string for the replication connection (needs REPLICATION). */
|
|
8
|
+
connectionString: string;
|
|
9
|
+
slotName?: string;
|
|
10
|
+
/** Primary key columns per table, used to build `pk` for inserts. */
|
|
11
|
+
primaryKeys?: Record<string, string[]>;
|
|
12
|
+
/** Tables never streamed. Nowity's own bookkeeping is always excluded. */
|
|
13
|
+
excludeTables?: string[];
|
|
14
|
+
onError?: (err: Error) => void;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Change source built on PostgreSQL logical replication + wal2json.
|
|
18
|
+
*
|
|
19
|
+
* Compared to {@link OutboxChangeSource} this one sees changes made *outside*
|
|
20
|
+
* the application — manual SQL, migrations, another service — which is its only
|
|
21
|
+
* real advantage, and the reason it exists behind the same interface rather than
|
|
22
|
+
* as the default. Two things it cannot give you:
|
|
23
|
+
*
|
|
24
|
+
* - **mutation attribution.** `set_config('nowity.client_id', …)` is not in the
|
|
25
|
+
* WAL, so `clientId`/`mutationId` are always null here. The client's echo
|
|
26
|
+
* handling does not depend on them (it rebases on `lastMutationId`), but
|
|
27
|
+
* server-side "who did this" logging does.
|
|
28
|
+
* - **carefree operations.** One slot feeds exactly one consumer, and while the
|
|
29
|
+
* consumer is down WAL accumulates on the primary until the disk fills. Any
|
|
30
|
+
* deployment using this source needs monitoring of
|
|
31
|
+
* `pg_replication_slots.confirmed_flush_lsn` and the retained WAL size, plus a
|
|
32
|
+
* plan for failover (a slot does not survive it before PG17 failover slots —
|
|
33
|
+
* expect a new slot and a full resnapshot of every client).
|
|
34
|
+
*/
|
|
35
|
+
export declare class WalChangeSource implements ChangeSource {
|
|
36
|
+
readonly name = "wal";
|
|
37
|
+
/** `set_config` is not in the WAL, so nothing here can say who wrote what. */
|
|
38
|
+
readonly attributesWrites = false;
|
|
39
|
+
private readonly opts;
|
|
40
|
+
private readonly slotName;
|
|
41
|
+
private readonly excluded;
|
|
42
|
+
private readonly onError;
|
|
43
|
+
private service;
|
|
44
|
+
private handler;
|
|
45
|
+
/**
|
|
46
|
+
* Tables whose `UPDATE`/`DELETE` puts the whole previous row into the WAL.
|
|
47
|
+
*
|
|
48
|
+
* Read once at start. A table switched to `REPLICA IDENTITY FULL` after the
|
|
49
|
+
* engine is running keeps being treated as if it had not been until the next
|
|
50
|
+
* restart — which costs invalidation precision, never correctness, and is
|
|
51
|
+
* the safe direction to be wrong in.
|
|
52
|
+
*/
|
|
53
|
+
private fullIdentity;
|
|
54
|
+
/** Serialises handler execution: `emit('data')` is not awaited by the lib. */
|
|
55
|
+
private queue;
|
|
56
|
+
private stopped;
|
|
57
|
+
constructor(opts: WalChangeSourceOptions);
|
|
58
|
+
/**
|
|
59
|
+
* Creates the replication slot if needed and returns the LSN to resume from.
|
|
60
|
+
*
|
|
61
|
+
* Order matters: the slot must exist *before* the caller's snapshot is read,
|
|
62
|
+
* because from that moment on the server retains WAL for us. Anything
|
|
63
|
+
* committed after this point is either visible in the snapshot (then the
|
|
64
|
+
* replayed change produces an empty diff) or not (then the replay is what
|
|
65
|
+
* delivers it). Neither case loses data.
|
|
66
|
+
*/
|
|
67
|
+
startPosition(snap: SnapshotContext): Promise<string>;
|
|
68
|
+
/**
|
|
69
|
+
* Which tables log their whole previous row.
|
|
70
|
+
*
|
|
71
|
+
* `relreplident` is `'f'` for `REPLICA IDENTITY FULL`, `'d'` for the primary
|
|
72
|
+
* key, `'i'` for a named index, `'n'` for nothing. Only the first gives a
|
|
73
|
+
* complete before-image, and only a complete before-image can show a row
|
|
74
|
+
* leaving a live query's filter.
|
|
75
|
+
*/
|
|
76
|
+
private loadReplicaIdentities;
|
|
77
|
+
private ensureSlot;
|
|
78
|
+
start(from: string, handler: BatchHandler): Promise<void>;
|
|
79
|
+
stop(): Promise<void>;
|
|
80
|
+
drain(): Promise<void>;
|
|
81
|
+
private enqueue;
|
|
82
|
+
private toBatch;
|
|
83
|
+
private pkOf;
|
|
84
|
+
}
|
|
85
|
+
//# sourceMappingURL=wal-change-source.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"wal-change-source.d.ts","sourceRoot":"","sources":["../../../src/server/change-source/wal-change-source.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,IAAI,CAAC;AAI/B,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,OAAO,CAAC;AAC7C,OAAO,KAAK,EAAE,YAAY,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAElE,MAAM,WAAW,sBAAsB;IACnC,0DAA0D;IAC1D,IAAI,EAAE,IAAI,CAAC;IACX,4EAA4E;IAC5E,gBAAgB,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,qEAAqE;IACrE,WAAW,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,EAAE,CAAC,CAAC;IACvC,0EAA0E;IAC1E,aAAa,CAAC,EAAE,MAAM,EAAE,CAAC;IACzB,OAAO,CAAC,EAAE,CAAC,GAAG,EAAE,KAAK,KAAK,IAAI,CAAC;CAClC;AAID;;;;;;;;;;;;;;;;;;GAkBG;AACH,qBAAa,eAAgB,YAAW,YAAY;IAChD,QAAQ,CAAC,IAAI,SAAS;IACtB,8EAA8E;IAC9E,QAAQ,CAAC,gBAAgB,SAAS;IAElC,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAyB;IAC9C,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAS;IAClC,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAc;IACvC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAuB;IAE/C,OAAO,CAAC,OAAO,CAA0C;IACzD,OAAO,CAAC,OAAO,CAA6B;IAC5C;;;;;;;OAOG;IACH,OAAO,CAAC,YAAY,CAAqB;IACzC,8EAA8E;IAC9E,OAAO,CAAC,KAAK,CAAoC;IACjD,OAAO,CAAC,OAAO,CAAS;gBAEZ,IAAI,EAAE,sBAAsB;IAOxC;;;;;;;;OAQG;IACG,aAAa,CAAC,IAAI,EAAE,eAAe,GAAG,OAAO,CAAC,MAAM,CAAC;IAU3D;;;;;;;OAOG;YACW,qBAAqB;YAUrB,UAAU;IAQlB,KAAK,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,YAAY,GAAG,OAAO,CAAC,IAAI,CAAC;IAgCzD,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC;IAQrB,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAO5B,OAAO,CAAC,OAAO;IAaf,OAAO,CAAC,OAAO;IAoCf,OAAO,CAAC,IAAI;CAUf"}
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.WalChangeSource = void 0;
|
|
4
|
+
const pg_logical_replication_1 = require("pg-logical-replication");
|
|
5
|
+
const normalize_1 = require("../../core/normalize");
|
|
6
|
+
const ALWAYS_EXCLUDED = ["nowity_outbox", "nowity_scope_epoch", "nowity_client"];
|
|
7
|
+
/**
|
|
8
|
+
* Change source built on PostgreSQL logical replication + wal2json.
|
|
9
|
+
*
|
|
10
|
+
* Compared to {@link OutboxChangeSource} this one sees changes made *outside*
|
|
11
|
+
* the application — manual SQL, migrations, another service — which is its only
|
|
12
|
+
* real advantage, and the reason it exists behind the same interface rather than
|
|
13
|
+
* as the default. Two things it cannot give you:
|
|
14
|
+
*
|
|
15
|
+
* - **mutation attribution.** `set_config('nowity.client_id', …)` is not in the
|
|
16
|
+
* WAL, so `clientId`/`mutationId` are always null here. The client's echo
|
|
17
|
+
* handling does not depend on them (it rebases on `lastMutationId`), but
|
|
18
|
+
* server-side "who did this" logging does.
|
|
19
|
+
* - **carefree operations.** One slot feeds exactly one consumer, and while the
|
|
20
|
+
* consumer is down WAL accumulates on the primary until the disk fills. Any
|
|
21
|
+
* deployment using this source needs monitoring of
|
|
22
|
+
* `pg_replication_slots.confirmed_flush_lsn` and the retained WAL size, plus a
|
|
23
|
+
* plan for failover (a slot does not survive it before PG17 failover slots —
|
|
24
|
+
* expect a new slot and a full resnapshot of every client).
|
|
25
|
+
*/
|
|
26
|
+
class WalChangeSource {
|
|
27
|
+
constructor(opts) {
|
|
28
|
+
this.name = "wal";
|
|
29
|
+
/** `set_config` is not in the WAL, so nothing here can say who wrote what. */
|
|
30
|
+
this.attributesWrites = false;
|
|
31
|
+
this.service = null;
|
|
32
|
+
this.handler = null;
|
|
33
|
+
/**
|
|
34
|
+
* Tables whose `UPDATE`/`DELETE` puts the whole previous row into the WAL.
|
|
35
|
+
*
|
|
36
|
+
* Read once at start. A table switched to `REPLICA IDENTITY FULL` after the
|
|
37
|
+
* engine is running keeps being treated as if it had not been until the next
|
|
38
|
+
* restart — which costs invalidation precision, never correctness, and is
|
|
39
|
+
* the safe direction to be wrong in.
|
|
40
|
+
*/
|
|
41
|
+
this.fullIdentity = new Set();
|
|
42
|
+
/** Serialises handler execution: `emit('data')` is not awaited by the lib. */
|
|
43
|
+
this.queue = Promise.resolve();
|
|
44
|
+
this.stopped = false;
|
|
45
|
+
this.opts = opts;
|
|
46
|
+
this.slotName = opts.slotName ?? "nowity_slot";
|
|
47
|
+
this.excluded = new Set([...ALWAYS_EXCLUDED, ...(opts.excludeTables ?? [])]);
|
|
48
|
+
this.onError = opts.onError ?? ((err) => console.error("[nowity/wal]", err));
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Creates the replication slot if needed and returns the LSN to resume from.
|
|
52
|
+
*
|
|
53
|
+
* Order matters: the slot must exist *before* the caller's snapshot is read,
|
|
54
|
+
* because from that moment on the server retains WAL for us. Anything
|
|
55
|
+
* committed after this point is either visible in the snapshot (then the
|
|
56
|
+
* replayed change produces an empty diff) or not (then the replay is what
|
|
57
|
+
* delivers it). Neither case loses data.
|
|
58
|
+
*/
|
|
59
|
+
async startPosition(snap) {
|
|
60
|
+
await this.ensureSlot();
|
|
61
|
+
const { rows } = await snap.query(`SELECT COALESCE(confirmed_flush_lsn, pg_current_wal_lsn())::text AS lsn
|
|
62
|
+
FROM pg_replication_slots WHERE slot_name = $1`, [this.slotName]);
|
|
63
|
+
return rows[0]?.lsn ?? "0/00000000";
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Which tables log their whole previous row.
|
|
67
|
+
*
|
|
68
|
+
* `relreplident` is `'f'` for `REPLICA IDENTITY FULL`, `'d'` for the primary
|
|
69
|
+
* key, `'i'` for a named index, `'n'` for nothing. Only the first gives a
|
|
70
|
+
* complete before-image, and only a complete before-image can show a row
|
|
71
|
+
* leaving a live query's filter.
|
|
72
|
+
*/
|
|
73
|
+
async loadReplicaIdentities() {
|
|
74
|
+
const { rows } = await this.opts.pool.query(`SELECT c.relname FROM pg_class c
|
|
75
|
+
JOIN pg_namespace n ON n.oid = c.relnamespace
|
|
76
|
+
WHERE c.relkind = 'r' AND c.relreplident = 'f'
|
|
77
|
+
AND n.nspname NOT IN ('pg_catalog', 'information_schema')`);
|
|
78
|
+
this.fullIdentity = new Set(rows.map((row) => row.relname));
|
|
79
|
+
}
|
|
80
|
+
async ensureSlot() {
|
|
81
|
+
await this.opts.pool.query(`SELECT pg_create_logical_replication_slot($1, 'wal2json')
|
|
82
|
+
WHERE NOT EXISTS (SELECT 1 FROM pg_replication_slots WHERE slot_name = $1)`, [this.slotName]);
|
|
83
|
+
}
|
|
84
|
+
async start(from, handler) {
|
|
85
|
+
this.handler = handler;
|
|
86
|
+
this.stopped = false;
|
|
87
|
+
await this.loadReplicaIdentities();
|
|
88
|
+
const service = new pg_logical_replication_1.LogicalReplicationService({ connectionString: this.opts.connectionString },
|
|
89
|
+
// Manual acknowledge: a change must not be marked as consumed before
|
|
90
|
+
// the engine has actually fanned it out.
|
|
91
|
+
{ acknowledge: { auto: false, timeoutSeconds: 0 } });
|
|
92
|
+
this.service = service;
|
|
93
|
+
const plugin = new pg_logical_replication_1.Wal2JsonPlugin({
|
|
94
|
+
includeXids: true,
|
|
95
|
+
includeLsn: true,
|
|
96
|
+
includeTimestamp: false,
|
|
97
|
+
includeTypes: false,
|
|
98
|
+
filterTables: [...this.excluded].map((t) => `*.${t}`).join(","),
|
|
99
|
+
});
|
|
100
|
+
service.on("error", (err) => this.onError(err));
|
|
101
|
+
service.on("data", (lsn, log) => {
|
|
102
|
+
this.enqueue(lsn, log);
|
|
103
|
+
});
|
|
104
|
+
// `subscribe` resolves only when the stream ends, so it is not awaited.
|
|
105
|
+
service.subscribe(plugin, this.slotName, from).catch((err) => {
|
|
106
|
+
if (!this.stopped)
|
|
107
|
+
this.onError(err);
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
async stop() {
|
|
111
|
+
this.stopped = true;
|
|
112
|
+
await this.queue.catch(() => undefined);
|
|
113
|
+
await this.service?.stop().catch(() => undefined);
|
|
114
|
+
this.service = null;
|
|
115
|
+
this.handler = null;
|
|
116
|
+
}
|
|
117
|
+
async drain() {
|
|
118
|
+
// Replication is push-based; there is nothing to poll. Waiting for the
|
|
119
|
+
// in-flight queue is the best "everything received so far is handled"
|
|
120
|
+
// this source can offer.
|
|
121
|
+
await this.queue.catch(() => undefined);
|
|
122
|
+
}
|
|
123
|
+
enqueue(lsn, log) {
|
|
124
|
+
this.queue = this.queue
|
|
125
|
+
.then(async () => {
|
|
126
|
+
if (this.stopped)
|
|
127
|
+
return;
|
|
128
|
+
const batch = this.toBatch(lsn, log);
|
|
129
|
+
if (batch.events.length > 0 && this.handler) {
|
|
130
|
+
await this.handler(batch);
|
|
131
|
+
}
|
|
132
|
+
await this.service?.acknowledge(lsn);
|
|
133
|
+
})
|
|
134
|
+
.catch((err) => this.onError(err));
|
|
135
|
+
}
|
|
136
|
+
toBatch(lsn, log) {
|
|
137
|
+
const xid = log.xid !== undefined ? String(log.xid) : lsn;
|
|
138
|
+
const events = [];
|
|
139
|
+
for (const change of log.change ?? []) {
|
|
140
|
+
if (change.kind !== "insert" && change.kind !== "update" && change.kind !== "delete") {
|
|
141
|
+
continue; // truncate / message: not a row change
|
|
142
|
+
}
|
|
143
|
+
if (this.excluded.has(change.table))
|
|
144
|
+
continue;
|
|
145
|
+
const columns = rowFromColumns(change.columnnames, change.columnvalues);
|
|
146
|
+
const oldRow = change.oldkeys
|
|
147
|
+
? rowFromColumns(change.oldkeys.keynames, change.oldkeys.keyvalues)
|
|
148
|
+
: null;
|
|
149
|
+
const after = change.kind === "delete" ? null : columns;
|
|
150
|
+
// `before` is whatever the table's replica identity puts in the WAL —
|
|
151
|
+
// by default just the key, everything only with REPLICA IDENTITY FULL
|
|
152
|
+
// (see `setReplicaIdentityFull`). For a delete it is all there is.
|
|
153
|
+
const before = change.kind === "insert" ? null : (oldRow ?? columns);
|
|
154
|
+
events.push({
|
|
155
|
+
table: change.table,
|
|
156
|
+
op: change.kind,
|
|
157
|
+
pk: this.pkOf(change.table, after ?? before ?? {}, oldRow),
|
|
158
|
+
before,
|
|
159
|
+
after,
|
|
160
|
+
clientId: null,
|
|
161
|
+
mutationId: null,
|
|
162
|
+
beforeComplete: this.fullIdentity.has(change.table),
|
|
163
|
+
});
|
|
164
|
+
}
|
|
165
|
+
return { position: log.nextlsn ?? lsn, xid, events };
|
|
166
|
+
}
|
|
167
|
+
pkOf(table, row, oldKeys) {
|
|
168
|
+
const configured = this.opts.primaryKeys?.[table];
|
|
169
|
+
if (configured) {
|
|
170
|
+
const pk = {};
|
|
171
|
+
for (const col of configured)
|
|
172
|
+
pk[col] = row[col] ?? oldKeys?.[col] ?? null;
|
|
173
|
+
return pk;
|
|
174
|
+
}
|
|
175
|
+
if (oldKeys)
|
|
176
|
+
return oldKeys;
|
|
177
|
+
return "id" in row ? { id: row.id } : {};
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
exports.WalChangeSource = WalChangeSource;
|
|
181
|
+
/**
|
|
182
|
+
* wal2json omits `columnnames`/`columnvalues` entirely for a delete (there is no
|
|
183
|
+
* new row), so both have to be treated as optional.
|
|
184
|
+
*/
|
|
185
|
+
function rowFromColumns(names, values) {
|
|
186
|
+
const row = {};
|
|
187
|
+
if (!names || !values)
|
|
188
|
+
return row;
|
|
189
|
+
names.forEach((name, i) => {
|
|
190
|
+
row[name] = (0, normalize_1.normalizeValue)(values[i]);
|
|
191
|
+
});
|
|
192
|
+
return row;
|
|
193
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import type { Pool } from "pg";
|
|
2
|
+
/** Anything that can run parameterised SQL. */
|
|
3
|
+
export interface Queryable {
|
|
4
|
+
query(text: string, values?: unknown[]): Promise<{
|
|
5
|
+
rows: any[];
|
|
6
|
+
}>;
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* A database connection pinned to one consistent read snapshot.
|
|
10
|
+
*
|
|
11
|
+
* Every re-evaluation of live queries for a single change batch happens inside
|
|
12
|
+
* one snapshot, which buys three things at once:
|
|
13
|
+
* - queries of different clients cannot disagree about the state of the world,
|
|
14
|
+
* - a query spanning several tables cannot observe a torn transaction,
|
|
15
|
+
* - `nowity_client.last_mutation_id` read from the same snapshot is exactly the
|
|
16
|
+
* watermark "these data include your mutations up to N".
|
|
17
|
+
*/
|
|
18
|
+
export interface SnapshotContext extends Queryable {
|
|
19
|
+
/**
|
|
20
|
+
* Adapter-specific handle bound to the same snapshot — a `PoolClient` for
|
|
21
|
+
* the pg adapter, a Prisma transaction client for the Prisma adapter.
|
|
22
|
+
* Query definitions cast this to whatever their adapter provides.
|
|
23
|
+
*/
|
|
24
|
+
readonly client: unknown;
|
|
25
|
+
}
|
|
26
|
+
export interface SnapshotRunner {
|
|
27
|
+
withSnapshot<T>(fn: (snap: SnapshotContext) => Promise<T>): Promise<T>;
|
|
28
|
+
}
|
|
29
|
+
/** Snapshot runner backed by a plain `pg` pool. */
|
|
30
|
+
export declare class PgSnapshotRunner implements SnapshotRunner {
|
|
31
|
+
private readonly pool;
|
|
32
|
+
constructor(pool: Pool);
|
|
33
|
+
withSnapshot<T>(fn: (snap: SnapshotContext) => Promise<T>): Promise<T>;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Snapshot runner backed by a Prisma interactive transaction, so query
|
|
37
|
+
* definitions can be written with the Prisma client while still sharing the
|
|
38
|
+
* engine's snapshot. `snap.client` is the Prisma transaction client.
|
|
39
|
+
*/
|
|
40
|
+
export declare class PrismaSnapshotRunner implements SnapshotRunner {
|
|
41
|
+
private readonly prisma;
|
|
42
|
+
private readonly timeoutMs;
|
|
43
|
+
constructor(prisma: {
|
|
44
|
+
$transaction<T>(fn: (tx: any) => Promise<T>, opts?: {
|
|
45
|
+
isolationLevel?: string;
|
|
46
|
+
timeout?: number;
|
|
47
|
+
}): Promise<T>;
|
|
48
|
+
}, timeoutMs?: number);
|
|
49
|
+
withSnapshot<T>(fn: (snap: SnapshotContext) => Promise<T>): Promise<T>;
|
|
50
|
+
}
|
|
51
|
+
//# sourceMappingURL=db.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"db.d.ts","sourceRoot":"","sources":["../../src/server/db.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAc,MAAM,IAAI,CAAC;AAE3C,+CAA+C;AAC/C,MAAM,WAAW,SAAS;IACtB,KAAK,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,OAAO,EAAE,GAAG,OAAO,CAAC;QAAE,IAAI,EAAE,GAAG,EAAE,CAAA;KAAE,CAAC,CAAC;CACrE;AAED;;;;;;;;;GASG;AACH,MAAM,WAAW,eAAgB,SAAQ,SAAS;IAC9C;;;;OAIG;IACH,QAAQ,CAAC,MAAM,EAAE,OAAO,CAAC;CAC5B;AAED,MAAM,WAAW,cAAc;IAC3B,YAAY,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,IAAI,EAAE,eAAe,KAAK,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;CAC1E;AAED,mDAAmD;AACnD,qBAAa,gBAAiB,YAAW,cAAc;IACvC,OAAO,CAAC,QAAQ,CAAC,IAAI;gBAAJ,IAAI,EAAE,IAAI;IAEjC,YAAY,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,IAAI,EAAE,eAAe,KAAK,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC;CAkB/E;AAED;;;;GAIG;AACH,qBAAa,oBAAqB,YAAW,cAAc;IAEnD,OAAO,CAAC,QAAQ,CAAC,MAAM;IAMvB,OAAO,CAAC,QAAQ,CAAC,SAAS;gBANT,MAAM,EAAE;QACrB,YAAY,CAAC,CAAC,EACV,EAAE,EAAE,CAAC,EAAE,EAAE,GAAG,KAAK,OAAO,CAAC,CAAC,CAAC,EAC3B,IAAI,CAAC,EAAE;YAAE,cAAc,CAAC,EAAE,MAAM,CAAC;YAAC,OAAO,CAAC,EAAE,MAAM,CAAA;SAAE,GACrD,OAAO,CAAC,CAAC,CAAC,CAAC;KACjB,EACgB,SAAS,SAAS;IAGjC,YAAY,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,IAAI,EAAE,eAAe,KAAK,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC;CAc/E"}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.PrismaSnapshotRunner = exports.PgSnapshotRunner = void 0;
|
|
4
|
+
/** Snapshot runner backed by a plain `pg` pool. */
|
|
5
|
+
class PgSnapshotRunner {
|
|
6
|
+
constructor(pool) {
|
|
7
|
+
this.pool = pool;
|
|
8
|
+
}
|
|
9
|
+
async withSnapshot(fn) {
|
|
10
|
+
const client = await this.pool.connect();
|
|
11
|
+
try {
|
|
12
|
+
await client.query("BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY");
|
|
13
|
+
const snap = {
|
|
14
|
+
client,
|
|
15
|
+
query: (text, values) => client.query(text, values),
|
|
16
|
+
};
|
|
17
|
+
const result = await fn(snap);
|
|
18
|
+
await client.query("COMMIT");
|
|
19
|
+
return result;
|
|
20
|
+
}
|
|
21
|
+
catch (err) {
|
|
22
|
+
await client.query("ROLLBACK").catch(() => undefined);
|
|
23
|
+
throw err;
|
|
24
|
+
}
|
|
25
|
+
finally {
|
|
26
|
+
client.release();
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
exports.PgSnapshotRunner = PgSnapshotRunner;
|
|
31
|
+
/**
|
|
32
|
+
* Snapshot runner backed by a Prisma interactive transaction, so query
|
|
33
|
+
* definitions can be written with the Prisma client while still sharing the
|
|
34
|
+
* engine's snapshot. `snap.client` is the Prisma transaction client.
|
|
35
|
+
*/
|
|
36
|
+
class PrismaSnapshotRunner {
|
|
37
|
+
constructor(prisma, timeoutMs = 15000) {
|
|
38
|
+
this.prisma = prisma;
|
|
39
|
+
this.timeoutMs = timeoutMs;
|
|
40
|
+
}
|
|
41
|
+
async withSnapshot(fn) {
|
|
42
|
+
return this.prisma.$transaction(async (tx) => {
|
|
43
|
+
const snap = {
|
|
44
|
+
client: tx,
|
|
45
|
+
query: async (text, values) => ({
|
|
46
|
+
rows: (await tx.$queryRawUnsafe(text, ...(values ?? []))),
|
|
47
|
+
}),
|
|
48
|
+
};
|
|
49
|
+
return fn(snap);
|
|
50
|
+
}, { isolationLevel: "RepeatableRead", timeout: this.timeoutMs });
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
exports.PrismaSnapshotRunner = PrismaSnapshotRunner;
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import type { OrderKey, RowFilter } from "../core/protocol";
|
|
2
|
+
import type { EntityId, ReadKeySet, Row } from "../core/types";
|
|
3
|
+
import type { SnapshotContext } from "./db";
|
|
4
|
+
import { type QueryDef, type SessionInfo } from "./query";
|
|
5
|
+
/** One evaluation of a live query, indexed for diffing and for transport. */
|
|
6
|
+
export interface QueryOutput {
|
|
7
|
+
index: Map<EntityId, Row>;
|
|
8
|
+
/** Ids of the primary entity, in the order the query returned them. */
|
|
9
|
+
ids: EntityId[];
|
|
10
|
+
/** Related entity sets, keyed by entity name. */
|
|
11
|
+
extra: Map<string, Map<EntityId, Row>>;
|
|
12
|
+
/** Tables this execution read, when it was able to record them. */
|
|
13
|
+
tables?: string[];
|
|
14
|
+
/** The same reads, narrowed to rows where the query said which ones. */
|
|
15
|
+
keys?: ReadKeySet;
|
|
16
|
+
/** Entity of the primary rows, when the execution derived it. */
|
|
17
|
+
entity?: string;
|
|
18
|
+
/** The query returned one row rather than a list. */
|
|
19
|
+
single?: boolean;
|
|
20
|
+
/** How the rows are ordered, when the execution could tell. */
|
|
21
|
+
order?: OrderKey[];
|
|
22
|
+
/** Which rows belong here, when the browser can decide it itself. */
|
|
23
|
+
filter?: RowFilter;
|
|
24
|
+
}
|
|
25
|
+
export declare function emptyOutput(): QueryOutput;
|
|
26
|
+
/**
|
|
27
|
+
* Run a query definition against one read snapshot and normalise its result.
|
|
28
|
+
*
|
|
29
|
+
* Shared by the sync engine (which diffs consecutive outputs) and by the
|
|
30
|
+
* server-side rendering path (which serialises a single output for hydration), so
|
|
31
|
+
* the two can never disagree about what a query returns.
|
|
32
|
+
*/
|
|
33
|
+
export declare function evaluateQuery(def: QueryDef, args: unknown, session: SessionInfo, snap: SnapshotContext): Promise<QueryOutput>;
|
|
34
|
+
/** Rows of an output as plain arrays, ready to be serialised. */
|
|
35
|
+
export declare function outputRows(output: QueryOutput): {
|
|
36
|
+
rows: Row[];
|
|
37
|
+
extra?: Record<string, Row[]>;
|
|
38
|
+
};
|
|
39
|
+
//# sourceMappingURL=evaluate.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"evaluate.d.ts","sourceRoot":"","sources":["../../src/server/evaluate.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC5D,OAAO,KAAK,EAAE,QAAQ,EAAE,UAAU,EAAE,GAAG,EAAE,MAAM,eAAe,CAAC;AAC/D,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,MAAM,CAAC;AAC5C,OAAO,EAAiB,KAAK,QAAQ,EAAE,KAAK,WAAW,EAAE,MAAM,SAAS,CAAC;AAEzE,6EAA6E;AAC7E,MAAM,WAAW,WAAW;IACxB,KAAK,EAAE,GAAG,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAC;IAC1B,uEAAuE;IACvE,GAAG,EAAE,QAAQ,EAAE,CAAC;IAChB,iDAAiD;IACjD,KAAK,EAAE,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAC,CAAC;IACvC,mEAAmE;IACnE,MAAM,CAAC,EAAE,MAAM,EAAE,CAAC;IAClB,wEAAwE;IACxE,IAAI,CAAC,EAAE,UAAU,CAAC;IAClB,iEAAiE;IACjE,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,qDAAqD;IACrD,MAAM,CAAC,EAAE,OAAO,CAAC;IACjB,+DAA+D;IAC/D,KAAK,CAAC,EAAE,QAAQ,EAAE,CAAC;IACnB,qEAAqE;IACrE,MAAM,CAAC,EAAE,SAAS,CAAC;CACtB;AAED,wBAAgB,WAAW,IAAI,WAAW,CAEzC;AAED;;;;;;GAMG;AACH,wBAAsB,aAAa,CAC/B,GAAG,EAAE,QAAQ,EACb,IAAI,EAAE,OAAO,EACb,OAAO,EAAE,WAAW,EACpB,IAAI,EAAE,eAAe,GACtB,OAAO,CAAC,WAAW,CAAC,CAmCtB;AAED,iEAAiE;AACjE,wBAAgB,UAAU,CAAC,MAAM,EAAE,WAAW,GAAG;IAAE,IAAI,EAAE,GAAG,EAAE,CAAC;IAAC,KAAK,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,EAAE,CAAC,CAAA;CAAE,CAS9F"}
|