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,805 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.SyncEngine = exports.ClientIdTaken = exports.EngineSession = void 0;
|
|
4
|
+
const node_crypto_1 = require("node:crypto");
|
|
5
|
+
const errors_1 = require("../api/errors");
|
|
6
|
+
const diff_1 = require("../core/diff");
|
|
7
|
+
const protocol_1 = require("../core/protocol");
|
|
8
|
+
const types_1 = require("../core/types");
|
|
9
|
+
const invalidation_index_1 = require("./invalidation-index");
|
|
10
|
+
const evaluate_1 = require("./evaluate");
|
|
11
|
+
const mutator_1 = require("./mutator");
|
|
12
|
+
/** Server-side handle for one connected client. */
|
|
13
|
+
class EngineSession {
|
|
14
|
+
constructor(info, send) {
|
|
15
|
+
this.info = info;
|
|
16
|
+
this.send = send;
|
|
17
|
+
this.subs = new Map();
|
|
18
|
+
/**
|
|
19
|
+
* This connection's claim on its client id, once the handshake has made it.
|
|
20
|
+
*
|
|
21
|
+
* Null until then, which is why a session opened without a handshake — the
|
|
22
|
+
* performance harness does exactly that — is not subject to the check.
|
|
23
|
+
*/
|
|
24
|
+
this.token = null;
|
|
25
|
+
/** Highest `lastMutationId` already communicated to this client. */
|
|
26
|
+
this.lastSentMutationId = -1;
|
|
27
|
+
/** Serialises this client's mutations; they must be applied in order. */
|
|
28
|
+
this.mutationChain = Promise.resolve();
|
|
29
|
+
this.closed = false;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
exports.EngineSession = EngineSession;
|
|
33
|
+
/**
|
|
34
|
+
* "Somebody else is this client now."
|
|
35
|
+
*
|
|
36
|
+
* A refusal of the connection, not of the write, and the difference decides
|
|
37
|
+
* whether the mutation id may be burned.
|
|
38
|
+
*/
|
|
39
|
+
class ClientIdTaken extends Error {
|
|
40
|
+
constructor(message) {
|
|
41
|
+
super(message);
|
|
42
|
+
this.nowity = "client-id-taken";
|
|
43
|
+
this.name = "ClientIdTaken";
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
exports.ClientIdTaken = ClientIdTaken;
|
|
47
|
+
/**
|
|
48
|
+
* The sync engine: turns change events into per-subscription patches.
|
|
49
|
+
*
|
|
50
|
+
* Everything that touches subscription state runs on one serialised task queue —
|
|
51
|
+
* change batches, new subscriptions, teardown. That is not just for tidiness, it
|
|
52
|
+
* is what closes the snapshot/stream hole (§6, test 9): a subscription's initial
|
|
53
|
+
* snapshot can only be read while the stream is quiesced at a known cursor, and
|
|
54
|
+
* the cursor's meaning ("every transaction up to here had already finished") then
|
|
55
|
+
* guarantees the snapshot contains everything the stream will not replay.
|
|
56
|
+
*/
|
|
57
|
+
class SyncEngine {
|
|
58
|
+
constructor(opts) {
|
|
59
|
+
this.sessions = new Set();
|
|
60
|
+
/**
|
|
61
|
+
* Which subscriptions a change can reach.
|
|
62
|
+
*
|
|
63
|
+
* The engine never walks every subscription of every session any more; it
|
|
64
|
+
* asks this instead, and walks the answer.
|
|
65
|
+
*/
|
|
66
|
+
this.index = new invalidation_index_1.InvalidationIndex();
|
|
67
|
+
/**
|
|
68
|
+
* scope → subscriptions in it, for the permission path.
|
|
69
|
+
*
|
|
70
|
+
* A scope invalidation is not a row change and cannot be looked up by value:
|
|
71
|
+
* the whole point is that nothing in the *data* moved.
|
|
72
|
+
*/
|
|
73
|
+
this.byScope = new Map();
|
|
74
|
+
this.tasks = Promise.resolve();
|
|
75
|
+
this.started = false;
|
|
76
|
+
/**
|
|
77
|
+
* What the fan-out actually cost, for anyone measuring it.
|
|
78
|
+
*
|
|
79
|
+
* `evaluations` is the number the whole design turns on: how many times a
|
|
80
|
+
* live query had to be run against the database. Without it a regression
|
|
81
|
+
* here looks like nothing at all until the process is under load.
|
|
82
|
+
*/
|
|
83
|
+
this.stats = { batches: 0, candidates: 0, evaluations: 0, fanOutMs: 0 };
|
|
84
|
+
this.opts = opts;
|
|
85
|
+
this.permissionTables = new Set(opts.permissionTables ?? []);
|
|
86
|
+
this.narrow = opts.narrowInvalidation ?? true;
|
|
87
|
+
this.onError = opts.onError ?? ((err) => console.error("[nowity/engine]", err));
|
|
88
|
+
}
|
|
89
|
+
// ------------------------------------------------------------------ lifecycle
|
|
90
|
+
async start() {
|
|
91
|
+
if (this.started)
|
|
92
|
+
return;
|
|
93
|
+
this.started = true;
|
|
94
|
+
const from = await this.opts.snapshots.withSnapshot((snap) => this.opts.source.startPosition(snap));
|
|
95
|
+
await this.opts.source.start(from, (batch) => this.run(() => this.timedBatch(batch)));
|
|
96
|
+
}
|
|
97
|
+
async stop() {
|
|
98
|
+
if (!this.started)
|
|
99
|
+
return;
|
|
100
|
+
this.started = false;
|
|
101
|
+
await this.opts.source.stop();
|
|
102
|
+
await this.tasks.catch(() => undefined);
|
|
103
|
+
}
|
|
104
|
+
/** Wait until every queued task (and the change stream) has settled. */
|
|
105
|
+
async settle() {
|
|
106
|
+
await this.opts.source.drain();
|
|
107
|
+
await this.run(async () => undefined);
|
|
108
|
+
}
|
|
109
|
+
/** Serialised execution of everything that reads or writes subscription state. */
|
|
110
|
+
run(fn) {
|
|
111
|
+
// `tasks` is always a settled-or-caught promise, so the chain cannot be
|
|
112
|
+
// broken by one failing task.
|
|
113
|
+
const next = this.tasks.then(fn);
|
|
114
|
+
this.tasks = next.catch(() => undefined);
|
|
115
|
+
return next;
|
|
116
|
+
}
|
|
117
|
+
// ------------------------------------------------------------------- sessions
|
|
118
|
+
openSession(info, send) {
|
|
119
|
+
// Two connections cannot share one mutation sequence, and the way they
|
|
120
|
+
// fail if they do is the worst kind: the second client's mutation 1 is
|
|
121
|
+
// indistinguishable from a replay of the first client's, so it is
|
|
122
|
+
// acknowledged and never applied. Nothing here can tell that apart after
|
|
123
|
+
// the fact, but it can say that the situation has arisen.
|
|
124
|
+
for (const other of this.sessions) {
|
|
125
|
+
if (other.closed || other.info.clientId !== info.clientId)
|
|
126
|
+
continue;
|
|
127
|
+
this.onError(new Error(`Two open connections claim the client id "${info.clientId}". ` +
|
|
128
|
+
`Mutation numbering is per client, so one of them will have ` +
|
|
129
|
+
`writes acknowledged and dropped as replays. Each tab needs ` +
|
|
130
|
+
`its own id — which is why the browser keeps it in ` +
|
|
131
|
+
`sessionStorage rather than localStorage. ` +
|
|
132
|
+
`This check sees only this process's connections; a collision ` +
|
|
133
|
+
`spread across two sync processes surfaces as a rejected ` +
|
|
134
|
+
`out-of-order mutation instead.`));
|
|
135
|
+
break;
|
|
136
|
+
}
|
|
137
|
+
const session = new EngineSession(info, send);
|
|
138
|
+
this.sessions.add(session);
|
|
139
|
+
return session;
|
|
140
|
+
}
|
|
141
|
+
async closeSession(session) {
|
|
142
|
+
session.closed = true;
|
|
143
|
+
await this.run(async () => {
|
|
144
|
+
for (const sub of session.subs.values())
|
|
145
|
+
this.forget(sub);
|
|
146
|
+
session.subs.clear();
|
|
147
|
+
this.sessions.delete(session);
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
async welcome(session) {
|
|
151
|
+
await this.claimClientId(session);
|
|
152
|
+
const lastMutationId = await this.opts.snapshots.withSnapshot((snap) => this.readLastMutationId(snap, session.info.clientId));
|
|
153
|
+
session.send({
|
|
154
|
+
t: "welcome",
|
|
155
|
+
v: protocol_1.PROTOCOL_VERSION,
|
|
156
|
+
lastMutationId,
|
|
157
|
+
...(this.opts.api ? { api: this.opts.api } : {}),
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* Take ownership of the client id for this connection.
|
|
162
|
+
*
|
|
163
|
+
* The newest connection wins, which is what a reconnect needs: the socket
|
|
164
|
+
* that just arrived is the one the user is looking at. A connection that has
|
|
165
|
+
* been superseded finds out at its next write, and finds out loudly instead
|
|
166
|
+
* of having it silently dropped.
|
|
167
|
+
*/
|
|
168
|
+
async claimClientId(session) {
|
|
169
|
+
const token = (0, node_crypto_1.randomUUID)();
|
|
170
|
+
await this.opts.writes.withWrite(async (w) => {
|
|
171
|
+
await w.query(`INSERT INTO nowity_client (client_id, session_token)
|
|
172
|
+
VALUES ($1, $2)
|
|
173
|
+
ON CONFLICT (client_id) DO UPDATE
|
|
174
|
+
SET session_token = EXCLUDED.session_token, updated_at = now()`, [session.info.clientId, token]);
|
|
175
|
+
});
|
|
176
|
+
session.token = token;
|
|
177
|
+
}
|
|
178
|
+
// -------------------------------------------------------------- subscriptions
|
|
179
|
+
async subscribe(session, subId, queryName, args) {
|
|
180
|
+
const def = this.opts.queries.get(queryName);
|
|
181
|
+
await this.run(async () => {
|
|
182
|
+
if (session.closed)
|
|
183
|
+
return;
|
|
184
|
+
await this.opts.snapshots.withSnapshot(async (snap) => {
|
|
185
|
+
const ctx = { db: snap, session: session.info };
|
|
186
|
+
const scope = def.scope ? def.scope(args, ctx) : null;
|
|
187
|
+
const epoch = scope ? await this.readEpoch(snap, scope) : 0;
|
|
188
|
+
const allowed = def.authorize ? await def.authorize(args, ctx) : true;
|
|
189
|
+
const lastMutationId = await this.readLastMutationId(snap, session.info.clientId);
|
|
190
|
+
const sub = {
|
|
191
|
+
subId,
|
|
192
|
+
def,
|
|
193
|
+
args,
|
|
194
|
+
scope,
|
|
195
|
+
epoch,
|
|
196
|
+
prev: (0, evaluate_1.emptyOutput)(),
|
|
197
|
+
session,
|
|
198
|
+
denied: false,
|
|
199
|
+
tables: def.tracksReads ? null : new Set(def.tables),
|
|
200
|
+
// A hand-written definition declares tables and nothing
|
|
201
|
+
// finer, so it watches those whole. Only an execution that
|
|
202
|
+
// reported its own reads can narrow to rows.
|
|
203
|
+
keys: def.tracksReads ? null : wholeTables(def.tables),
|
|
204
|
+
entity: def.entity,
|
|
205
|
+
};
|
|
206
|
+
let output = null;
|
|
207
|
+
if (allowed) {
|
|
208
|
+
try {
|
|
209
|
+
output = await this.evaluate(def, args, session, snap);
|
|
210
|
+
}
|
|
211
|
+
catch (err) {
|
|
212
|
+
// A refusal is an answer, not a failure: it becomes a
|
|
213
|
+
// denied subscription that keeps watching for the day the
|
|
214
|
+
// answer changes.
|
|
215
|
+
if (!(0, errors_1.isForbidden)(err))
|
|
216
|
+
throw err;
|
|
217
|
+
this.rememberRefusedReads(sub, err);
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
if (output === null) {
|
|
221
|
+
sub.denied = true;
|
|
222
|
+
session.subs.set(subId, sub);
|
|
223
|
+
this.register(sub);
|
|
224
|
+
session.send({
|
|
225
|
+
t: "tx",
|
|
226
|
+
position: "",
|
|
227
|
+
lastMutationId,
|
|
228
|
+
patches: [],
|
|
229
|
+
revoked: [{ subId, reason: "not-authorized", epoch }],
|
|
230
|
+
});
|
|
231
|
+
return;
|
|
232
|
+
}
|
|
233
|
+
this.absorb(sub, output);
|
|
234
|
+
session.subs.set(subId, sub);
|
|
235
|
+
this.register(sub);
|
|
236
|
+
session.lastSentMutationId = Math.max(session.lastSentMutationId, lastMutationId);
|
|
237
|
+
session.send({
|
|
238
|
+
t: "snapshot",
|
|
239
|
+
lastMutationId,
|
|
240
|
+
...this.toSnapshot(sub, output, "initial"),
|
|
241
|
+
});
|
|
242
|
+
});
|
|
243
|
+
});
|
|
244
|
+
}
|
|
245
|
+
async unsubscribe(session, subId) {
|
|
246
|
+
await this.run(async () => {
|
|
247
|
+
const sub = session.subs.get(subId);
|
|
248
|
+
if (!sub)
|
|
249
|
+
return;
|
|
250
|
+
session.subs.delete(subId);
|
|
251
|
+
this.forget(sub);
|
|
252
|
+
});
|
|
253
|
+
}
|
|
254
|
+
// ------------------------------------------------------------------ bookkeeping
|
|
255
|
+
/**
|
|
256
|
+
* File a subscription under what it reads, and under its scope.
|
|
257
|
+
*
|
|
258
|
+
* Idempotent: `add` replaces any previous placement, which is what makes it
|
|
259
|
+
* safe to call again every time a re-execution reports a different read set.
|
|
260
|
+
*/
|
|
261
|
+
register(sub) {
|
|
262
|
+
this.index.add(sub, this.filedKeys(sub));
|
|
263
|
+
if (sub.scope === null)
|
|
264
|
+
return;
|
|
265
|
+
let set = this.byScope.get(sub.scope);
|
|
266
|
+
if (!set)
|
|
267
|
+
this.byScope.set(sub.scope, (set = new Set()));
|
|
268
|
+
set.add(sub);
|
|
269
|
+
}
|
|
270
|
+
/**
|
|
271
|
+
* What the subscription is filed under, once the kill switch has had its say.
|
|
272
|
+
*
|
|
273
|
+
* Dropping to table granularity here rather than at extraction time keeps
|
|
274
|
+
* the two paths one path: the keys are still derived, still tested, and the
|
|
275
|
+
* switch only decides how much of them the index is allowed to use.
|
|
276
|
+
*/
|
|
277
|
+
filedKeys(sub) {
|
|
278
|
+
if (sub.keys === null)
|
|
279
|
+
return null;
|
|
280
|
+
if (this.narrow)
|
|
281
|
+
return sub.keys;
|
|
282
|
+
return wholeTables([...sub.keys.keys()]);
|
|
283
|
+
}
|
|
284
|
+
forget(sub) {
|
|
285
|
+
this.index.remove(sub);
|
|
286
|
+
if (sub.scope === null)
|
|
287
|
+
return;
|
|
288
|
+
const set = this.byScope.get(sub.scope);
|
|
289
|
+
if (!set)
|
|
290
|
+
return;
|
|
291
|
+
set.delete(sub);
|
|
292
|
+
if (set.size === 0)
|
|
293
|
+
this.byScope.delete(sub.scope);
|
|
294
|
+
}
|
|
295
|
+
// ------------------------------------------------------------------ change fan-out
|
|
296
|
+
/** `handleBatch`, with the one number worth watching taken around it. */
|
|
297
|
+
async timedBatch(batch) {
|
|
298
|
+
const started = process.hrtime.bigint();
|
|
299
|
+
try {
|
|
300
|
+
await this.handleBatch(batch);
|
|
301
|
+
}
|
|
302
|
+
finally {
|
|
303
|
+
this.stats.fanOutMs += Number(process.hrtime.bigint() - started) / 1e6;
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
async handleBatch(batch) {
|
|
307
|
+
const invalidatedScopes = new Set();
|
|
308
|
+
let revalidateEverything = false;
|
|
309
|
+
for (const event of batch.events) {
|
|
310
|
+
// A permission-table change is an invalidation. It is never turned
|
|
311
|
+
// into a patch — but the table is still watched like any other,
|
|
312
|
+
// because a query may legitimately *select* from it (a member list),
|
|
313
|
+
// and such a query carries its own permission check.
|
|
314
|
+
if (!this.permissionTables.has(event.table))
|
|
315
|
+
continue;
|
|
316
|
+
const scopes = this.opts.scopeOfChange?.(event) ?? null;
|
|
317
|
+
if (scopes === null) {
|
|
318
|
+
revalidateEverything = true;
|
|
319
|
+
}
|
|
320
|
+
else if (Array.isArray(scopes)) {
|
|
321
|
+
for (const scope of scopes)
|
|
322
|
+
invalidatedScopes.add(scope);
|
|
323
|
+
}
|
|
324
|
+
else {
|
|
325
|
+
invalidatedScopes.add(scopes);
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
// Bump epochs before opening the read snapshot, so recomputation and the
|
|
329
|
+
// epoch stamped on its result cannot disagree.
|
|
330
|
+
for (const scope of invalidatedScopes) {
|
|
331
|
+
await this.bumpEpoch(scope, batch.position);
|
|
332
|
+
}
|
|
333
|
+
if (this.sessions.size === 0)
|
|
334
|
+
return;
|
|
335
|
+
const candidates = this.candidatesFor(batch, invalidatedScopes, revalidateEverything);
|
|
336
|
+
this.stats.batches += 1;
|
|
337
|
+
this.stats.candidates += candidates.size;
|
|
338
|
+
const bySession = new Map();
|
|
339
|
+
for (const sub of candidates) {
|
|
340
|
+
if (sub.session.closed)
|
|
341
|
+
continue;
|
|
342
|
+
const list = bySession.get(sub.session);
|
|
343
|
+
if (list)
|
|
344
|
+
list.push(sub);
|
|
345
|
+
else
|
|
346
|
+
bySession.set(sub.session, [sub]);
|
|
347
|
+
}
|
|
348
|
+
// Sessions with nothing to recompute may still have a mutation watermark
|
|
349
|
+
// to hear about, and the two sets are usually disjoint: the client that
|
|
350
|
+
// wrote is rarely the one whose subscription the write changed.
|
|
351
|
+
const interested = new Set(bySession.keys());
|
|
352
|
+
for (const session of this.writersIn(batch))
|
|
353
|
+
interested.add(session);
|
|
354
|
+
// The common case in an application of any size: a change nobody has a
|
|
355
|
+
// stake in. Opening a snapshot to establish that would make the floor
|
|
356
|
+
// cost of a write grow with the number of connections, which is the
|
|
357
|
+
// shape this whole change exists to get rid of.
|
|
358
|
+
if (interested.size === 0)
|
|
359
|
+
return;
|
|
360
|
+
const outgoing = [];
|
|
361
|
+
await this.opts.snapshots.withSnapshot(async (snap) => {
|
|
362
|
+
const epochCache = new Map();
|
|
363
|
+
const mutationIds = await this.readLastMutationIds(snap, [...interested].map((s) => s.info.clientId));
|
|
364
|
+
for (const session of interested) {
|
|
365
|
+
if (session.closed)
|
|
366
|
+
continue;
|
|
367
|
+
const patches = [];
|
|
368
|
+
const snapshots = [];
|
|
369
|
+
const revoked = [];
|
|
370
|
+
for (const sub of bySession.get(session) ?? []) {
|
|
371
|
+
// A subscription torn down while this batch was in flight is
|
|
372
|
+
// still in the set the index handed over.
|
|
373
|
+
if (session.subs.get(sub.subId) !== sub)
|
|
374
|
+
continue;
|
|
375
|
+
const invalidated = revalidateEverything ||
|
|
376
|
+
(sub.scope !== null && invalidatedScopes.has(sub.scope));
|
|
377
|
+
// A query that reports its own read set needs no scopes and no
|
|
378
|
+
// separate authorize pass: the permission table it consulted is
|
|
379
|
+
// in that read set, so a change to it wakes the subscription up
|
|
380
|
+
// the same way a change to the data does — including when the
|
|
381
|
+
// subscription is currently denied, which is what makes
|
|
382
|
+
// *gaining* access work.
|
|
383
|
+
if (sub.def.tracksReads) {
|
|
384
|
+
try {
|
|
385
|
+
await this.refreshTracked(sub, snap, patches, snapshots, revoked);
|
|
386
|
+
}
|
|
387
|
+
catch (err) {
|
|
388
|
+
this.onError(err);
|
|
389
|
+
session.send({
|
|
390
|
+
t: "error",
|
|
391
|
+
subId: sub.subId,
|
|
392
|
+
code: "query-failed",
|
|
393
|
+
message: err.message,
|
|
394
|
+
});
|
|
395
|
+
}
|
|
396
|
+
continue;
|
|
397
|
+
}
|
|
398
|
+
// A denied subscription is woken only by an invalidation. No
|
|
399
|
+
// data event may produce anything for it, no matter that its
|
|
400
|
+
// socket subscribed before the rights were taken away.
|
|
401
|
+
if (!invalidated && sub.denied)
|
|
402
|
+
continue;
|
|
403
|
+
try {
|
|
404
|
+
if (invalidated) {
|
|
405
|
+
await this.reauthorizeAndResnapshot(sub, snap, epochCache, snapshots, revoked);
|
|
406
|
+
}
|
|
407
|
+
else {
|
|
408
|
+
const patch = await this.patchFor(sub, snap);
|
|
409
|
+
if (patch)
|
|
410
|
+
patches.push(patch);
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
catch (err) {
|
|
414
|
+
this.onError(err);
|
|
415
|
+
session.send({
|
|
416
|
+
t: "error",
|
|
417
|
+
subId: sub.subId,
|
|
418
|
+
code: "query-failed",
|
|
419
|
+
message: err.message,
|
|
420
|
+
});
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
const lastMutationId = mutationIds.get(session.info.clientId) ?? 0;
|
|
424
|
+
const mutationNews = lastMutationId > session.lastSentMutationId;
|
|
425
|
+
if (patches.length || snapshots.length || revoked.length || mutationNews) {
|
|
426
|
+
session.lastSentMutationId = Math.max(session.lastSentMutationId, lastMutationId);
|
|
427
|
+
outgoing.push({
|
|
428
|
+
session,
|
|
429
|
+
message: {
|
|
430
|
+
t: "tx",
|
|
431
|
+
position: batch.position,
|
|
432
|
+
lastMutationId,
|
|
433
|
+
patches,
|
|
434
|
+
...(snapshots.length ? { snapshots } : {}),
|
|
435
|
+
...(revoked.length ? { revoked } : {}),
|
|
436
|
+
},
|
|
437
|
+
});
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
});
|
|
441
|
+
for (const { session, message } of outgoing) {
|
|
442
|
+
if (!session.closed)
|
|
443
|
+
session.send(message);
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
/**
|
|
447
|
+
* Sessions whose mutation watermark this batch may have moved.
|
|
448
|
+
*
|
|
449
|
+
* A client's `last_mutation_id` only advances when one of its own mutations
|
|
450
|
+
* commits, and a mutation that wrote nothing produces no batch at all — so
|
|
451
|
+
* when the source stamps its events, the clients named in a batch are the
|
|
452
|
+
* only ones with news in it. A source that cannot attribute writes gets the
|
|
453
|
+
* honest answer, which is every session.
|
|
454
|
+
*/
|
|
455
|
+
writersIn(batch) {
|
|
456
|
+
if (!this.opts.source.attributesWrites)
|
|
457
|
+
return this.sessions;
|
|
458
|
+
const writers = new Set();
|
|
459
|
+
for (const event of batch.events) {
|
|
460
|
+
if (event.clientId !== null)
|
|
461
|
+
writers.add(event.clientId);
|
|
462
|
+
}
|
|
463
|
+
if (writers.size === 0)
|
|
464
|
+
return [];
|
|
465
|
+
const found = [];
|
|
466
|
+
for (const session of this.sessions) {
|
|
467
|
+
if (!session.closed && writers.has(session.info.clientId))
|
|
468
|
+
found.push(session);
|
|
469
|
+
}
|
|
470
|
+
return found;
|
|
471
|
+
}
|
|
472
|
+
/**
|
|
473
|
+
* The subscriptions this batch could have changed the answer for.
|
|
474
|
+
*
|
|
475
|
+
* Everything else is skipped without touching the database, which is the
|
|
476
|
+
* whole difference between a cost that grows with the number of changes and
|
|
477
|
+
* one that grows with the number of changes times the number of watchers.
|
|
478
|
+
*/
|
|
479
|
+
candidatesFor(batch, invalidatedScopes, revalidateEverything) {
|
|
480
|
+
const candidates = new Set();
|
|
481
|
+
// "Cannot tell which scope" is rare and deliberately blunt: correctness
|
|
482
|
+
// is not negotiable, and an unrecognisable permission change is exactly
|
|
483
|
+
// when guessing is least affordable.
|
|
484
|
+
if (revalidateEverything) {
|
|
485
|
+
for (const session of this.sessions) {
|
|
486
|
+
for (const sub of session.subs.values())
|
|
487
|
+
candidates.add(sub);
|
|
488
|
+
}
|
|
489
|
+
return candidates;
|
|
490
|
+
}
|
|
491
|
+
this.index.collect(batch.events, candidates);
|
|
492
|
+
for (const scope of invalidatedScopes) {
|
|
493
|
+
const subs = this.byScope.get(scope);
|
|
494
|
+
if (subs)
|
|
495
|
+
for (const sub of subs)
|
|
496
|
+
candidates.add(sub);
|
|
497
|
+
}
|
|
498
|
+
return candidates;
|
|
499
|
+
}
|
|
500
|
+
/**
|
|
501
|
+
* Take an execution's read set and entity, and make them the subscription's.
|
|
502
|
+
*
|
|
503
|
+
* The read set is re-derived on every execution rather than accumulated,
|
|
504
|
+
* because a query can legitimately ask a different question each time — a
|
|
505
|
+
* method that branches, or a list whose window moved. Accumulating would
|
|
506
|
+
* leave the subscription filed under rows it no longer looks at, and the
|
|
507
|
+
* index would fill up with entries nothing can ever remove.
|
|
508
|
+
*/
|
|
509
|
+
absorb(sub, output) {
|
|
510
|
+
sub.prev = output;
|
|
511
|
+
if (output.tables) {
|
|
512
|
+
sub.tables = new Set([...output.tables, ...sub.def.tables]);
|
|
513
|
+
sub.keys = narrowing(output.keys, sub.tables, sub.def.tables);
|
|
514
|
+
this.index.add(sub, this.filedKeys(sub));
|
|
515
|
+
}
|
|
516
|
+
if (output.entity)
|
|
517
|
+
sub.entity = output.entity;
|
|
518
|
+
}
|
|
519
|
+
rememberRefusedReads(sub, err) {
|
|
520
|
+
if (!err.tables)
|
|
521
|
+
return;
|
|
522
|
+
sub.tables = new Set([...err.tables, ...sub.def.tables]);
|
|
523
|
+
sub.keys = narrowing(err.keys, sub.tables, sub.def.tables);
|
|
524
|
+
this.index.add(sub, this.filedKeys(sub));
|
|
525
|
+
}
|
|
526
|
+
/**
|
|
527
|
+
* One pass over a read-set-tracking subscription, in whichever direction it
|
|
528
|
+
* moved: granted, revoked, or merely changed.
|
|
529
|
+
*/
|
|
530
|
+
async refreshTracked(sub, snap, patches, snapshots, revoked) {
|
|
531
|
+
let output;
|
|
532
|
+
try {
|
|
533
|
+
output = await this.evaluate(sub.def, sub.args, sub.session, snap);
|
|
534
|
+
}
|
|
535
|
+
catch (err) {
|
|
536
|
+
if (!(0, errors_1.isForbidden)(err))
|
|
537
|
+
throw err;
|
|
538
|
+
this.rememberRefusedReads(sub, err);
|
|
539
|
+
if (!sub.denied) {
|
|
540
|
+
sub.denied = true;
|
|
541
|
+
sub.prev = (0, evaluate_1.emptyOutput)();
|
|
542
|
+
revoked.push({
|
|
543
|
+
subId: sub.subId,
|
|
544
|
+
reason: "permission-revoked",
|
|
545
|
+
epoch: sub.epoch,
|
|
546
|
+
});
|
|
547
|
+
}
|
|
548
|
+
return;
|
|
549
|
+
}
|
|
550
|
+
const wasDenied = sub.denied;
|
|
551
|
+
sub.denied = false;
|
|
552
|
+
if (wasDenied) {
|
|
553
|
+
// Recompute and replace, never diff: the client threw its copy away
|
|
554
|
+
// when it was revoked, so there is nothing to diff against.
|
|
555
|
+
this.absorb(sub, output);
|
|
556
|
+
snapshots.push(this.toSnapshot(sub, output, "permission-change"));
|
|
557
|
+
return;
|
|
558
|
+
}
|
|
559
|
+
const patch = this.diffInto(sub, output);
|
|
560
|
+
if (patch)
|
|
561
|
+
patches.push(patch);
|
|
562
|
+
}
|
|
563
|
+
async reauthorizeAndResnapshot(sub, snap, epochCache, snapshots, revoked) {
|
|
564
|
+
const ctx = { db: snap, session: sub.session.info };
|
|
565
|
+
const epoch = sub.scope ? await this.readEpoch(snap, sub.scope, epochCache) : 0;
|
|
566
|
+
sub.epoch = epoch;
|
|
567
|
+
if (sub.def.authorize && !(await sub.def.authorize(sub.args, ctx))) {
|
|
568
|
+
if (!sub.denied) {
|
|
569
|
+
sub.denied = true;
|
|
570
|
+
sub.prev = (0, evaluate_1.emptyOutput)();
|
|
571
|
+
revoked.push({ subId: sub.subId, reason: "permission-revoked", epoch });
|
|
572
|
+
}
|
|
573
|
+
return;
|
|
574
|
+
}
|
|
575
|
+
sub.denied = false;
|
|
576
|
+
// Not a diff: the whole subscription is recomputed and replaced. Working
|
|
577
|
+
// out which individual entities a user just lost is exactly the kind of
|
|
578
|
+
// complexity §2 tells us not to buy.
|
|
579
|
+
const output = await this.evaluate(sub.def, sub.args, sub.session, snap);
|
|
580
|
+
this.absorb(sub, output);
|
|
581
|
+
snapshots.push(this.toSnapshot(sub, output, "permission-change"));
|
|
582
|
+
}
|
|
583
|
+
async patchFor(sub, snap) {
|
|
584
|
+
return this.diffInto(sub, await this.evaluate(sub.def, sub.args, sub.session, snap));
|
|
585
|
+
}
|
|
586
|
+
/** Diff a fresh output against the subscription's previous one and adopt it. */
|
|
587
|
+
diffInto(sub, next) {
|
|
588
|
+
const diff = (0, diff_1.diffRowSets)(sub.prev.index, next.index);
|
|
589
|
+
const idsChanged = !sameIds(sub.prev.ids, next.ids);
|
|
590
|
+
const extraUpsert = {};
|
|
591
|
+
const extraRemove = {};
|
|
592
|
+
let extraChanged = false;
|
|
593
|
+
const entities = new Set([...sub.prev.extra.keys(), ...next.extra.keys()]);
|
|
594
|
+
for (const entity of entities) {
|
|
595
|
+
const extraDiff = (0, diff_1.diffRowSets)(sub.prev.extra.get(entity) ?? new Map(), next.extra.get(entity) ?? new Map());
|
|
596
|
+
if ((0, types_1.isEmptyDiff)(extraDiff))
|
|
597
|
+
continue;
|
|
598
|
+
extraChanged = true;
|
|
599
|
+
if (extraDiff.upsert.length)
|
|
600
|
+
extraUpsert[entity] = extraDiff.upsert;
|
|
601
|
+
if (extraDiff.remove.length)
|
|
602
|
+
extraRemove[entity] = extraDiff.remove;
|
|
603
|
+
}
|
|
604
|
+
this.absorb(sub, next);
|
|
605
|
+
if ((0, types_1.isEmptyDiff)(diff) && !idsChanged && !extraChanged)
|
|
606
|
+
return null;
|
|
607
|
+
return {
|
|
608
|
+
subId: sub.subId,
|
|
609
|
+
entity: sub.entity,
|
|
610
|
+
epoch: sub.epoch,
|
|
611
|
+
...(idsChanged ? { ids: next.ids } : {}),
|
|
612
|
+
upsert: diff.upsert,
|
|
613
|
+
remove: diff.remove,
|
|
614
|
+
...(Object.keys(extraUpsert).length ? { extraUpsert } : {}),
|
|
615
|
+
...(Object.keys(extraRemove).length ? { extraRemove } : {}),
|
|
616
|
+
};
|
|
617
|
+
}
|
|
618
|
+
evaluate(def, args, session, snap) {
|
|
619
|
+
this.stats.evaluations += 1;
|
|
620
|
+
return (0, evaluate_1.evaluateQuery)(def, args, session.info, snap);
|
|
621
|
+
}
|
|
622
|
+
toSnapshot(sub, output, reason) {
|
|
623
|
+
return {
|
|
624
|
+
subId: sub.subId,
|
|
625
|
+
entity: sub.entity,
|
|
626
|
+
...(output.single ? { single: true } : {}),
|
|
627
|
+
...(output.order ? { order: output.order } : {}),
|
|
628
|
+
...(output.filter ? { filter: output.filter } : {}),
|
|
629
|
+
ids: output.ids,
|
|
630
|
+
...(0, evaluate_1.outputRows)(output),
|
|
631
|
+
scope: sub.scope,
|
|
632
|
+
epoch: sub.epoch,
|
|
633
|
+
reason,
|
|
634
|
+
};
|
|
635
|
+
}
|
|
636
|
+
// ------------------------------------------------------------------- mutations
|
|
637
|
+
/** Queue a mutation; mutations of one client are applied in order. */
|
|
638
|
+
mutate(session, mutationId, name, args) {
|
|
639
|
+
const result = session.mutationChain.then(() => this.executeMutation(session, mutationId, name, args));
|
|
640
|
+
session.mutationChain = result.catch(() => undefined);
|
|
641
|
+
return result;
|
|
642
|
+
}
|
|
643
|
+
async executeMutation(session, mutationId, name, args) {
|
|
644
|
+
const clientId = session.info.clientId;
|
|
645
|
+
try {
|
|
646
|
+
const def = this.opts.mutators.get(name);
|
|
647
|
+
const outcome = await this.opts.writes.withWrite(async (w) => {
|
|
648
|
+
await w.query(`INSERT INTO nowity_client (client_id) VALUES ($1) ON CONFLICT DO NOTHING`, [clientId]);
|
|
649
|
+
const { rows } = await w.query(`SELECT last_mutation_id::text AS last, session_token FROM nowity_client
|
|
650
|
+
WHERE client_id = $1 FOR UPDATE`, [clientId]);
|
|
651
|
+
const last = Number(rows[0].last);
|
|
652
|
+
const owner = rows[0].session_token;
|
|
653
|
+
// Another connection has claimed this id since. Numbering is per
|
|
654
|
+
// client, so carrying on would mean each of them taking the
|
|
655
|
+
// other's mutations for replays of its own — the failure this
|
|
656
|
+
// check exists to stop being silent.
|
|
657
|
+
if (session.token !== null && owner !== null && owner !== session.token) {
|
|
658
|
+
throw new ClientIdTaken(`The client id "${clientId}" has been claimed by another ` +
|
|
659
|
+
`connection, so this one may no longer write. Mutation ` +
|
|
660
|
+
`numbering is per client and each connection needs an id of ` +
|
|
661
|
+
`its own; the browser keeps one per tab in sessionStorage.`);
|
|
662
|
+
}
|
|
663
|
+
// Idempotency: a mutation resent after a reconnect must not be
|
|
664
|
+
// applied twice.
|
|
665
|
+
if (mutationId <= last)
|
|
666
|
+
return { ok: true, lastMutationId: last };
|
|
667
|
+
if (mutationId !== last + 1) {
|
|
668
|
+
// The one place a client id shared by two connections is
|
|
669
|
+
// caught for certain. `openSession` reports the collision
|
|
670
|
+
// when both are on this process, but with several sync
|
|
671
|
+
// processes on one database neither can see the other's
|
|
672
|
+
// sessions — and this check can, because the sequence they
|
|
673
|
+
// are both writing to is in the database.
|
|
674
|
+
throw new mutator_1.MutationRejected(`Out of order mutation ${mutationId} for client "${clientId}", ` +
|
|
675
|
+
`expected ${last + 1}. Either a mutation was lost before it ` +
|
|
676
|
+
`reached the server, or two connections are using this client ` +
|
|
677
|
+
`id — mutation numbering is per client, and each connection ` +
|
|
678
|
+
`needs an id of its own.`);
|
|
679
|
+
}
|
|
680
|
+
// Stamp the transaction so the capture trigger can attribute the
|
|
681
|
+
// resulting change events to this client and mutation.
|
|
682
|
+
await w.query(`SELECT set_config('nowity.client_id', $1, true),
|
|
683
|
+
set_config('nowity.mutation_id', $2, true)`, [clientId, String(mutationId)]);
|
|
684
|
+
await def.server(args, {
|
|
685
|
+
db: w,
|
|
686
|
+
session: session.info,
|
|
687
|
+
mutationId,
|
|
688
|
+
});
|
|
689
|
+
await w.query(`UPDATE nowity_client SET last_mutation_id = $2, updated_at = now()
|
|
690
|
+
WHERE client_id = $1`, [clientId, mutationId]);
|
|
691
|
+
return { ok: true, lastMutationId: mutationId };
|
|
692
|
+
});
|
|
693
|
+
return outcome;
|
|
694
|
+
}
|
|
695
|
+
catch (err) {
|
|
696
|
+
// A refused mutation is a normal outcome of the write path, not an
|
|
697
|
+
// engine failure; only unexpected errors are worth reporting.
|
|
698
|
+
if (!(err instanceof mutator_1.MutationRejected))
|
|
699
|
+
this.onError(err);
|
|
700
|
+
// A superseded connection is the one case where the id must *not* be
|
|
701
|
+
// burned. The write was refused because of who asked, not because of
|
|
702
|
+
// what it asked for, and the connection that now owns the id will
|
|
703
|
+
// resend it with the same number — burning it here would turn that
|
|
704
|
+
// resend into an acknowledged no-op, which is the very write loss
|
|
705
|
+
// this check exists to prevent.
|
|
706
|
+
if (err instanceof ClientIdTaken) {
|
|
707
|
+
return { ok: false, error: err.message, lastMutationId: mutationId - 1 };
|
|
708
|
+
}
|
|
709
|
+
// The write is rolled back, but the mutation id is burned in its own
|
|
710
|
+
// transaction. Otherwise the client would keep a rejected mutation in
|
|
711
|
+
// its pending queue forever and never converge.
|
|
712
|
+
await this.opts.writes
|
|
713
|
+
.withWrite(async (w) => {
|
|
714
|
+
await w.query(`INSERT INTO nowity_client (client_id, last_mutation_id)
|
|
715
|
+
VALUES ($1, $2)
|
|
716
|
+
ON CONFLICT (client_id) DO UPDATE
|
|
717
|
+
SET last_mutation_id = GREATEST(nowity_client.last_mutation_id, $2),
|
|
718
|
+
updated_at = now()`, [clientId, mutationId]);
|
|
719
|
+
})
|
|
720
|
+
.catch((bookkeepingErr) => this.onError(bookkeepingErr));
|
|
721
|
+
return {
|
|
722
|
+
ok: false,
|
|
723
|
+
error: err.message,
|
|
724
|
+
lastMutationId: mutationId,
|
|
725
|
+
};
|
|
726
|
+
}
|
|
727
|
+
}
|
|
728
|
+
// ------------------------------------------------------------------ epoch store
|
|
729
|
+
/**
|
|
730
|
+
* Move a scope's epoch on, once per change rather than once per reader.
|
|
731
|
+
*
|
|
732
|
+
* `position` is what makes several sync processes agree: they all hand over
|
|
733
|
+
* the same batch position, the first one through does the increment and the
|
|
734
|
+
* rest read the value it wrote. Without it, one permission change would cost
|
|
735
|
+
* a write per node on a single very hot row.
|
|
736
|
+
*/
|
|
737
|
+
async bumpEpoch(scope, position) {
|
|
738
|
+
await this.opts.writes.withWrite(async (w) => {
|
|
739
|
+
await w.query(`SELECT nowity_bump_epoch($1, $2)`, [scope, position]);
|
|
740
|
+
});
|
|
741
|
+
}
|
|
742
|
+
async readEpoch(snap, scope, cache) {
|
|
743
|
+
const cached = cache?.get(scope);
|
|
744
|
+
if (cached !== undefined)
|
|
745
|
+
return cached;
|
|
746
|
+
const { rows } = await snap.query(`SELECT version::text AS version FROM nowity_scope_epoch WHERE scope = $1`, [scope]);
|
|
747
|
+
const epoch = rows.length ? Number(rows[0].version) : 0;
|
|
748
|
+
cache?.set(scope, epoch);
|
|
749
|
+
return epoch;
|
|
750
|
+
}
|
|
751
|
+
async readLastMutationId(snap, clientId) {
|
|
752
|
+
const { rows } = await snap.query(`SELECT last_mutation_id::text AS last FROM nowity_client WHERE client_id = $1`, [clientId]);
|
|
753
|
+
return rows.length ? Number(rows[0].last) : 0;
|
|
754
|
+
}
|
|
755
|
+
async readLastMutationIds(snap, clientIds) {
|
|
756
|
+
const out = new Map();
|
|
757
|
+
if (clientIds.length === 0)
|
|
758
|
+
return out;
|
|
759
|
+
// Explicit placeholders rather than `= ANY($1::text[])`: array parameters
|
|
760
|
+
// are not portable across the adapters this can run on (pg vs Prisma raw).
|
|
761
|
+
const placeholders = clientIds.map((_, index) => `$${index + 1}`).join(", ");
|
|
762
|
+
const { rows } = await snap.query(`SELECT client_id, last_mutation_id::text AS last
|
|
763
|
+
FROM nowity_client WHERE client_id IN (${placeholders})`, clientIds);
|
|
764
|
+
for (const row of rows)
|
|
765
|
+
out.set(row.client_id, Number(row.last));
|
|
766
|
+
return out;
|
|
767
|
+
}
|
|
768
|
+
}
|
|
769
|
+
exports.SyncEngine = SyncEngine;
|
|
770
|
+
/** A read set that names tables and nothing finer. */
|
|
771
|
+
function wholeTables(tables) {
|
|
772
|
+
const keys = new Map();
|
|
773
|
+
for (const table of tables)
|
|
774
|
+
keys.set(table, types_1.ANY_ROWS);
|
|
775
|
+
return keys;
|
|
776
|
+
}
|
|
777
|
+
/**
|
|
778
|
+
* Combine what an execution read with how far it could be narrowed.
|
|
779
|
+
*
|
|
780
|
+
* `tables` is the authority on *which* tables matter — it is derived by a
|
|
781
|
+
* separate walk that over-approximates on purpose — and the keys only ever
|
|
782
|
+
* refine an entry that is already there. A table the keys know nothing about
|
|
783
|
+
* stays whole, so the two walks disagreeing can cost a recomputation and never
|
|
784
|
+
* a missed one. Declared tables stay whole too: `@query({ tables })` names a
|
|
785
|
+
* table, never a row.
|
|
786
|
+
*/
|
|
787
|
+
function narrowing(keys, tables, declared) {
|
|
788
|
+
const out = wholeTables([...tables]);
|
|
789
|
+
if (keys) {
|
|
790
|
+
for (const [table, tableKeys] of keys)
|
|
791
|
+
out.set(table, tableKeys);
|
|
792
|
+
}
|
|
793
|
+
for (const table of declared)
|
|
794
|
+
out.set(table, types_1.ANY_ROWS);
|
|
795
|
+
return out;
|
|
796
|
+
}
|
|
797
|
+
function sameIds(a, b) {
|
|
798
|
+
if (a.length !== b.length)
|
|
799
|
+
return false;
|
|
800
|
+
for (let i = 0; i < a.length; i += 1) {
|
|
801
|
+
if (a[i] !== b[i])
|
|
802
|
+
return false;
|
|
803
|
+
}
|
|
804
|
+
return true;
|
|
805
|
+
}
|