nowity 1.10.0 → 1.11.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 +65 -15
- package/dist/core/types.d.ts +7 -0
- package/dist/core/types.d.ts.map +1 -1
- package/dist/server/api/configure.d.ts +5 -1
- package/dist/server/api/configure.d.ts.map +1 -1
- package/dist/server/api/configure.js +2 -0
- package/dist/server/change-source/change-source.d.ts +23 -5
- package/dist/server/change-source/change-source.d.ts.map +1 -1
- package/dist/server/change-source/outbox-change-source.d.ts +46 -12
- package/dist/server/change-source/outbox-change-source.d.ts.map +1 -1
- package/dist/server/change-source/outbox-change-source.js +153 -65
- package/dist/server/change-source/pg-snapshot.d.ts +25 -0
- package/dist/server/change-source/pg-snapshot.d.ts.map +1 -0
- package/dist/server/change-source/pg-snapshot.js +43 -0
- package/dist/server/sync-engine.d.ts +110 -0
- package/dist/server/sync-engine.d.ts.map +1 -1
- package/dist/server/sync-engine.js +409 -111
- package/dist/server/ws-server.d.ts +8 -0
- package/dist/server/ws-server.d.ts.map +1 -1
- package/dist/server/ws-server.js +32 -5
- package/package.json +1 -1
|
@@ -1,14 +1,44 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.SyncEngine = exports.ClientIdTaken = exports.EngineSession = void 0;
|
|
3
|
+
exports.SyncEngine = exports.ClientIdTaken = exports.EngineSession = exports.DEFAULT_FAN_OUT_MIN_PER_SNAPSHOT = exports.DEFAULT_FAN_OUT_CONCURRENCY = void 0;
|
|
4
4
|
const node_crypto_1 = require("node:crypto");
|
|
5
5
|
const errors_1 = require("../api/errors");
|
|
6
6
|
const diff_1 = require("../core/diff");
|
|
7
7
|
const protocol_1 = require("../core/protocol");
|
|
8
8
|
const types_1 = require("../core/types");
|
|
9
9
|
const invalidation_index_1 = require("./invalidation-index");
|
|
10
|
+
const pg_snapshot_1 = require("./change-source/pg-snapshot");
|
|
10
11
|
const evaluate_1 = require("./evaluate");
|
|
11
12
|
const mutator_1 = require("./mutator");
|
|
13
|
+
/** See {@link SyncEngineOptions.fanOut}. */
|
|
14
|
+
exports.DEFAULT_FAN_OUT_CONCURRENCY = 4;
|
|
15
|
+
exports.DEFAULT_FAN_OUT_MIN_PER_SNAPSHOT = 8;
|
|
16
|
+
/**
|
|
17
|
+
* One holder at a time, in the order they asked.
|
|
18
|
+
*
|
|
19
|
+
* Both things that recompute a session's existing subscriptions and send the
|
|
20
|
+
* result — a batch and a mutation's own recomputation — hold its session's
|
|
21
|
+
* lock from before they open their snapshot until the message is out. (A
|
|
22
|
+
* subscribe creates a subscription rather than recomputing one; it is ordered
|
|
23
|
+
* against batches by the engine's queue and against acks by
|
|
24
|
+
* `EngineSession.subscribing`.) That keeps
|
|
25
|
+
* a subscription's diffs in order, and makes every recomputation of a session
|
|
26
|
+
* read in a snapshot newer than the one before it, so nothing ever moves a
|
|
27
|
+
* client back in time. A holder may wait for a connection, but nobody waits for
|
|
28
|
+
* a lock while holding a connection, which is what keeps it free of deadlocks.
|
|
29
|
+
*/
|
|
30
|
+
class SessionLock {
|
|
31
|
+
constructor() {
|
|
32
|
+
this.tail = Promise.resolve();
|
|
33
|
+
}
|
|
34
|
+
acquire() {
|
|
35
|
+
let release;
|
|
36
|
+
const held = new Promise((resolve) => (release = resolve));
|
|
37
|
+
const previous = this.tail;
|
|
38
|
+
this.tail = previous.then(() => held);
|
|
39
|
+
return previous.then(() => release);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
12
42
|
/** Server-side handle for one connected client. */
|
|
13
43
|
class EngineSession {
|
|
14
44
|
constructor(info, send) {
|
|
@@ -26,6 +56,10 @@ class EngineSession {
|
|
|
26
56
|
this.lastSentMutationId = -1;
|
|
27
57
|
/** Serialises this client's mutations; they must be applied in order. */
|
|
28
58
|
this.mutationChain = Promise.resolve();
|
|
59
|
+
/** See {@link SessionLock}. */
|
|
60
|
+
this.lock = new SessionLock();
|
|
61
|
+
/** Subscribes of this session being evaluated right now. */
|
|
62
|
+
this.subscribing = 0;
|
|
29
63
|
this.closed = false;
|
|
30
64
|
/**
|
|
31
65
|
* This socket, as presence records it. Not the client id: a client id
|
|
@@ -96,10 +130,27 @@ class SyncEngine {
|
|
|
96
130
|
* application transactions they covered. Without it a regression
|
|
97
131
|
* here looks like nothing at all until the process is under load.
|
|
98
132
|
*/
|
|
99
|
-
this.stats = {
|
|
133
|
+
this.stats = {
|
|
134
|
+
batches: 0,
|
|
135
|
+
transactions: 0,
|
|
136
|
+
snapshots: 0,
|
|
137
|
+
candidates: 0,
|
|
138
|
+
evaluations: 0,
|
|
139
|
+
fanOutMs: 0,
|
|
140
|
+
/** Mutations whose result went out with the writer's recomputed data. */
|
|
141
|
+
acks: 0,
|
|
142
|
+
/** Snapshots and recomputations those took (not in the totals above). */
|
|
143
|
+
ackSnapshots: 0,
|
|
144
|
+
ackEvaluations: 0,
|
|
145
|
+
/** Recomputations a batch skipped because the writer's ack had them already. */
|
|
146
|
+
skipped: 0,
|
|
147
|
+
};
|
|
100
148
|
this.opts = opts;
|
|
101
149
|
this.permissionTables = new Set(opts.permissionTables ?? []);
|
|
102
150
|
this.narrow = opts.narrowInvalidation ?? true;
|
|
151
|
+
this.ackWithState = opts.ackWithState !== false && opts.source.ownWrites !== undefined;
|
|
152
|
+
this.fanOutConcurrency = Math.max(1, Math.floor(opts.fanOut?.concurrency ?? exports.DEFAULT_FAN_OUT_CONCURRENCY));
|
|
153
|
+
this.fanOutMinPerSnapshot = Math.max(1, Math.floor(opts.fanOut?.minPerSnapshot ?? exports.DEFAULT_FAN_OUT_MIN_PER_SNAPSHOT));
|
|
103
154
|
this.onError = opts.onError ?? ((err) => console.error("[nowity/engine]", err));
|
|
104
155
|
opts.derived?.onChange(() => {
|
|
105
156
|
this.run(async () => this.pushDerived()).catch((err) => this.onError(err));
|
|
@@ -223,6 +274,22 @@ class SyncEngine {
|
|
|
223
274
|
async subscribe(session, subId, queryName, args) {
|
|
224
275
|
const def = this.opts.queries.get(queryName);
|
|
225
276
|
await this.run(async () => {
|
|
277
|
+
if (session.closed)
|
|
278
|
+
return;
|
|
279
|
+
// Not under the session lock: a slow query would hold the writer's
|
|
280
|
+
// ack behind it. A mutation's ack skips the session while this
|
|
281
|
+
// runs instead (see ackWithData).
|
|
282
|
+
session.subscribing += 1;
|
|
283
|
+
try {
|
|
284
|
+
await this.subscribeNow(session, subId, def, args);
|
|
285
|
+
}
|
|
286
|
+
finally {
|
|
287
|
+
session.subscribing -= 1;
|
|
288
|
+
}
|
|
289
|
+
});
|
|
290
|
+
}
|
|
291
|
+
async subscribeNow(session, subId, def, args) {
|
|
292
|
+
{
|
|
226
293
|
if (session.closed)
|
|
227
294
|
return;
|
|
228
295
|
await this.opts.snapshots.withSnapshot(async (snap) => {
|
|
@@ -248,6 +315,7 @@ class SyncEngine {
|
|
|
248
315
|
entity: def.entity,
|
|
249
316
|
filterColumns: null,
|
|
250
317
|
mutatorsSent: "[]",
|
|
318
|
+
mark: null,
|
|
251
319
|
};
|
|
252
320
|
let output = null;
|
|
253
321
|
if (allowed) {
|
|
@@ -286,7 +354,7 @@ class SyncEngine {
|
|
|
286
354
|
...this.toSnapshot(sub, output, "initial"),
|
|
287
355
|
});
|
|
288
356
|
});
|
|
289
|
-
}
|
|
357
|
+
}
|
|
290
358
|
}
|
|
291
359
|
async unsubscribe(session, subId) {
|
|
292
360
|
await this.run(async () => {
|
|
@@ -405,105 +473,166 @@ class SyncEngine {
|
|
|
405
473
|
// shape this whole change exists to get rid of.
|
|
406
474
|
if (interested.size === 0)
|
|
407
475
|
return;
|
|
408
|
-
const
|
|
409
|
-
|
|
410
|
-
await
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
catch (err) {
|
|
464
|
-
this.onError(err);
|
|
465
|
-
session.send({
|
|
466
|
-
t: "error",
|
|
467
|
-
subId: sub.subId,
|
|
468
|
-
code: "query-failed",
|
|
469
|
-
message: err.message,
|
|
470
|
-
});
|
|
471
|
-
}
|
|
476
|
+
const groups = this.partition([...interested], bySession);
|
|
477
|
+
const ctx = { batch, readAt, fanOutAt, invalidatedScopes, revalidateEverything, bySession };
|
|
478
|
+
const settled = await Promise.allSettled(groups.map((group) => this.fanOutGroup(group, ctx)));
|
|
479
|
+
// Every group has released its locks by now; the first failure fails
|
|
480
|
+
// the batch, and the source delivers it again — the groups that made
|
|
481
|
+
// it diff to nothing the second time.
|
|
482
|
+
for (const result of settled) {
|
|
483
|
+
if (result.status === "rejected")
|
|
484
|
+
throw result.reason;
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
/**
|
|
488
|
+
* Sessions in groups of roughly equal work, one snapshot per group.
|
|
489
|
+
*
|
|
490
|
+
* A session is never split: everything it is sent for one batch comes from
|
|
491
|
+
* one snapshot. Groups only appear when there is enough work to pay for
|
|
492
|
+
* the extra connection.
|
|
493
|
+
*/
|
|
494
|
+
partition(sessions, bySession) {
|
|
495
|
+
const open = sessions.filter((session) => !session.closed);
|
|
496
|
+
const work = (session) => bySession.get(session)?.length ?? 0;
|
|
497
|
+
const total = open.reduce((sum, session) => sum + work(session), 0);
|
|
498
|
+
const count = Math.min(this.fanOutConcurrency, open.length, Math.max(1, Math.ceil(total / this.fanOutMinPerSnapshot)));
|
|
499
|
+
if (count <= 1)
|
|
500
|
+
return open.length ? [open] : [];
|
|
501
|
+
const groups = Array.from({ length: count }, () => ({ load: 0, sessions: [] }));
|
|
502
|
+
for (const session of [...open].sort((a, b) => work(b) - work(a))) {
|
|
503
|
+
let lightest = groups[0];
|
|
504
|
+
for (const group of groups)
|
|
505
|
+
if (group.load < lightest.load)
|
|
506
|
+
lightest = group;
|
|
507
|
+
lightest.sessions.push(session);
|
|
508
|
+
// A session with no recomputation still costs its watermark read.
|
|
509
|
+
lightest.load += Math.max(1, work(session));
|
|
510
|
+
}
|
|
511
|
+
return groups.map((group) => group.sessions).filter((group) => group.length > 0);
|
|
512
|
+
}
|
|
513
|
+
async fanOutGroup(sessions, ctx) {
|
|
514
|
+
const releases = [];
|
|
515
|
+
try {
|
|
516
|
+
// Locks first, then the snapshot: see SessionLock. The groups of
|
|
517
|
+
// one batch hold disjoint sessions, so taking them one by one
|
|
518
|
+
// cannot deadlock.
|
|
519
|
+
for (const session of sessions)
|
|
520
|
+
releases.push(await session.lock.acquire());
|
|
521
|
+
const outgoing = [];
|
|
522
|
+
this.stats.snapshots += 1;
|
|
523
|
+
await this.opts.snapshots.withSnapshot(async (snap) => {
|
|
524
|
+
const epochCache = new Map();
|
|
525
|
+
const live = sessions.filter((session) => !session.closed);
|
|
526
|
+
const mutationIds = await this.readLastMutationIds(snap, live.map((s) => s.info.clientId));
|
|
527
|
+
for (const session of live) {
|
|
528
|
+
const message = await this.fanOutSession(session, snap, epochCache, mutationIds, ctx);
|
|
529
|
+
if (message)
|
|
530
|
+
outgoing.push({ session, message });
|
|
472
531
|
}
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
532
|
+
});
|
|
533
|
+
for (const { session, message } of outgoing) {
|
|
534
|
+
if (!session.closed)
|
|
535
|
+
session.send(message);
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
finally {
|
|
539
|
+
for (const release of releases)
|
|
540
|
+
release();
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
/** What one session is sent for a batch, if anything. */
|
|
544
|
+
async fanOutSession(session, snap, epochCache, mutationIds, ctx) {
|
|
545
|
+
const { batch, bySession, invalidatedScopes, revalidateEverything } = ctx;
|
|
546
|
+
const patches = [];
|
|
547
|
+
const snapshots = [];
|
|
548
|
+
const revoked = [];
|
|
549
|
+
const mutators = [];
|
|
550
|
+
for (const sub of bySession.get(session) ?? []) {
|
|
551
|
+
// A subscription torn down while this batch was in flight is
|
|
552
|
+
// still in the set the index handed over.
|
|
553
|
+
if (session.subs.get(sub.subId) !== sub)
|
|
554
|
+
continue;
|
|
555
|
+
const invalidated = revalidateEverything ||
|
|
556
|
+
(sub.scope !== null && invalidatedScopes.has(sub.scope));
|
|
557
|
+
// Recomputed for the writer's own mutation in a snapshot that
|
|
558
|
+
// already saw every transaction of this batch: the answer cannot
|
|
559
|
+
// have moved since, and recomputing would only diff to nothing.
|
|
560
|
+
// Never for an invalidation, which the data alone does not show.
|
|
561
|
+
if (!invalidated && sub.mark !== null && (0, pg_snapshot_1.seesAll)(sub.mark, batch.xids)) {
|
|
562
|
+
this.stats.skipped += 1;
|
|
563
|
+
continue;
|
|
564
|
+
}
|
|
565
|
+
sub.mark = null;
|
|
566
|
+
// A query that reports its own read set needs no scopes and no
|
|
567
|
+
// separate authorize pass: the permission table it consulted is
|
|
568
|
+
// in that read set, so a change to it wakes the subscription up
|
|
569
|
+
// the same way a change to the data does — including when the
|
|
570
|
+
// subscription is currently denied, which is what makes
|
|
571
|
+
// *gaining* access work.
|
|
572
|
+
if (sub.def.tracksReads) {
|
|
573
|
+
try {
|
|
574
|
+
await this.refreshTracked(sub, snap, patches, snapshots, revoked);
|
|
482
575
|
}
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
if (patches.length || snapshots.length || revoked.length || mutators.length || mutationNews) {
|
|
486
|
-
session.lastSentMutationId = Math.max(session.lastSentMutationId, lastMutationId);
|
|
487
|
-
outgoing.push({
|
|
488
|
-
session,
|
|
489
|
-
message: {
|
|
490
|
-
t: "tx",
|
|
491
|
-
position: batch.position,
|
|
492
|
-
lastMutationId,
|
|
493
|
-
...(session.timing ? { timing: txTiming(batch, session, readAt, fanOutAt) } : {}),
|
|
494
|
-
patches,
|
|
495
|
-
...(snapshots.length ? { snapshots } : {}),
|
|
496
|
-
...(revoked.length ? { revoked } : {}),
|
|
497
|
-
...(mutators.length ? { mutators } : {}),
|
|
498
|
-
},
|
|
499
|
-
});
|
|
576
|
+
catch (err) {
|
|
577
|
+
this.reportQueryFailure(sub, err);
|
|
500
578
|
}
|
|
579
|
+
continue;
|
|
501
580
|
}
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
581
|
+
// A denied subscription is woken only by an invalidation. No
|
|
582
|
+
// data event may produce anything for it, no matter that its
|
|
583
|
+
// socket subscribed before the rights were taken away.
|
|
584
|
+
if (!invalidated && sub.denied)
|
|
585
|
+
continue;
|
|
586
|
+
try {
|
|
587
|
+
if (invalidated) {
|
|
588
|
+
await this.reauthorizeAndResnapshot(sub, snap, epochCache, snapshots, revoked);
|
|
589
|
+
}
|
|
590
|
+
else {
|
|
591
|
+
const patch = await this.patchFor(sub, snap);
|
|
592
|
+
if (patch)
|
|
593
|
+
patches.push(patch);
|
|
594
|
+
}
|
|
595
|
+
}
|
|
596
|
+
catch (err) {
|
|
597
|
+
this.reportQueryFailure(sub, err);
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
// A recomputation can change what a subscription read, and with
|
|
601
|
+
// it which derived mutators apply. Snapshots carry their own.
|
|
602
|
+
const resnapshotted = new Set(snapshots.map((snapshot) => snapshot.subId));
|
|
603
|
+
for (const sub of bySession.get(session) ?? []) {
|
|
604
|
+
if (session.subs.get(sub.subId) !== sub || resnapshotted.has(sub.subId))
|
|
605
|
+
continue;
|
|
606
|
+
const changed = this.changedMutators(sub);
|
|
607
|
+
if (changed)
|
|
608
|
+
mutators.push({ subId: sub.subId, mutators: changed });
|
|
506
609
|
}
|
|
610
|
+
// Never lower than what the client was already told: a mutation's own
|
|
611
|
+
// recomputation may have confirmed it before this batch got here.
|
|
612
|
+
const lastMutationId = Math.max(mutationIds.get(session.info.clientId) ?? 0, session.lastSentMutationId, 0);
|
|
613
|
+
const mutationNews = lastMutationId > session.lastSentMutationId;
|
|
614
|
+
if (!(patches.length || snapshots.length || revoked.length || mutators.length || mutationNews))
|
|
615
|
+
return null;
|
|
616
|
+
session.lastSentMutationId = lastMutationId;
|
|
617
|
+
return {
|
|
618
|
+
t: "tx",
|
|
619
|
+
position: batch.position,
|
|
620
|
+
lastMutationId,
|
|
621
|
+
...(session.timing ? { timing: txTiming(batch, session, ctx.readAt, ctx.fanOutAt) } : {}),
|
|
622
|
+
patches,
|
|
623
|
+
...(snapshots.length ? { snapshots } : {}),
|
|
624
|
+
...(revoked.length ? { revoked } : {}),
|
|
625
|
+
...(mutators.length ? { mutators } : {}),
|
|
626
|
+
};
|
|
627
|
+
}
|
|
628
|
+
reportQueryFailure(sub, err) {
|
|
629
|
+
this.onError(err);
|
|
630
|
+
sub.session.send({
|
|
631
|
+
t: "error",
|
|
632
|
+
subId: sub.subId,
|
|
633
|
+
code: "query-failed",
|
|
634
|
+
message: err.message,
|
|
635
|
+
});
|
|
507
636
|
}
|
|
508
637
|
/**
|
|
509
638
|
* Sessions whose mutation watermark this batch may have moved.
|
|
@@ -590,15 +719,23 @@ class SyncEngine {
|
|
|
590
719
|
* One pass over a read-set-tracking subscription, in whichever direction it
|
|
591
720
|
* moved: granted, revoked, or merely changed.
|
|
592
721
|
*/
|
|
593
|
-
async refreshTracked(sub, snap, patches, snapshots, revoked) {
|
|
722
|
+
async refreshTracked(sub, snap, patches, snapshots, revoked, counted = true) {
|
|
594
723
|
let output;
|
|
595
724
|
try {
|
|
596
|
-
output = await this.evaluate(sub.def, sub.args, sub.session, snap);
|
|
725
|
+
output = await this.evaluate(sub.def, sub.args, sub.session, snap, counted);
|
|
597
726
|
}
|
|
598
727
|
catch (err) {
|
|
599
728
|
if (!(0, errors_1.isForbidden)(err))
|
|
600
729
|
throw err;
|
|
601
|
-
this.
|
|
730
|
+
this.applyTracked(sub, { forbidden: err }, patches, snapshots, revoked);
|
|
731
|
+
return;
|
|
732
|
+
}
|
|
733
|
+
this.applyTracked(sub, { output }, patches, snapshots, revoked);
|
|
734
|
+
}
|
|
735
|
+
/** The second half of {@link refreshTracked}: adopt an evaluation's outcome. */
|
|
736
|
+
applyTracked(sub, outcome, patches, snapshots, revoked) {
|
|
737
|
+
if ("forbidden" in outcome) {
|
|
738
|
+
this.rememberRefusedReads(sub, outcome.forbidden);
|
|
602
739
|
if (!sub.denied) {
|
|
603
740
|
sub.denied = true;
|
|
604
741
|
sub.prev = (0, evaluate_1.emptyOutput)();
|
|
@@ -610,6 +747,7 @@ class SyncEngine {
|
|
|
610
747
|
}
|
|
611
748
|
return;
|
|
612
749
|
}
|
|
750
|
+
const { output } = outcome;
|
|
613
751
|
const wasDenied = sub.denied;
|
|
614
752
|
sub.denied = false;
|
|
615
753
|
if (wasDenied) {
|
|
@@ -678,8 +816,9 @@ class SyncEngine {
|
|
|
678
816
|
...(Object.keys(extraRemove).length ? { extraRemove } : {}),
|
|
679
817
|
};
|
|
680
818
|
}
|
|
681
|
-
evaluate(def, args, session, snap) {
|
|
682
|
-
|
|
819
|
+
evaluate(def, args, session, snap, counted = true) {
|
|
820
|
+
if (counted)
|
|
821
|
+
this.stats.evaluations += 1;
|
|
683
822
|
return (0, evaluate_1.evaluateQuery)(def, args, session.info, snap);
|
|
684
823
|
}
|
|
685
824
|
toSnapshot(sub, output, reason) {
|
|
@@ -754,10 +893,24 @@ class SyncEngine {
|
|
|
754
893
|
const startedAt = Date.now();
|
|
755
894
|
try {
|
|
756
895
|
const def = this.opts.mutators.get(name);
|
|
896
|
+
const ownWrites = this.ackWithState ? this.opts.source.ownWrites : undefined;
|
|
897
|
+
let written = null;
|
|
757
898
|
const outcome = await this.opts.writes.withWrite(async (w) => {
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
899
|
+
// One round trip for what used to be three: the row is created
|
|
900
|
+
// if missing and locked either way (the conflict branch takes
|
|
901
|
+
// the same row lock `FOR UPDATE` would), and the transaction is
|
|
902
|
+
// stamped so the capture trigger can attribute the resulting
|
|
903
|
+
// change events to this client and mutation. Stamping before
|
|
904
|
+
// the checks below is harmless: a refusal rolls it back.
|
|
905
|
+
const { rows } = await w.query(`WITH c AS (
|
|
906
|
+
INSERT INTO nowity.nowity_client AS c (client_id) VALUES ($1)
|
|
907
|
+
ON CONFLICT (client_id) DO UPDATE SET client_id = c.client_id
|
|
908
|
+
RETURNING last_mutation_id, session_token
|
|
909
|
+
)
|
|
910
|
+
SELECT c.last_mutation_id::text AS last, c.session_token,
|
|
911
|
+
set_config('nowity.client_id', $1, true) AS stamped_client,
|
|
912
|
+
set_config('nowity.mutation_id', $2, true) AS stamped_mutation
|
|
913
|
+
FROM c`, [clientId, String(mutationId)]);
|
|
761
914
|
const last = Number(rows[0].last);
|
|
762
915
|
const owner = rows[0].session_token;
|
|
763
916
|
// Another connection has claimed this id since. Numbering is per
|
|
@@ -787,18 +940,32 @@ class SyncEngine {
|
|
|
787
940
|
`id — mutation numbering is per client, and each connection ` +
|
|
788
941
|
`needs an id of its own.`);
|
|
789
942
|
}
|
|
790
|
-
// Stamp the transaction so the capture trigger can attribute the
|
|
791
|
-
// resulting change events to this client and mutation.
|
|
792
|
-
await w.query(`SELECT set_config('nowity.client_id', $1, true),
|
|
793
|
-
set_config('nowity.mutation_id', $2, true)`, [clientId, String(mutationId)]);
|
|
794
943
|
const value = await def.server(args, {
|
|
795
944
|
db: w,
|
|
796
945
|
session: session.info,
|
|
797
946
|
mutationId,
|
|
798
947
|
afterCommit: (fn) => committed.push(fn),
|
|
799
948
|
});
|
|
800
|
-
|
|
801
|
-
|
|
949
|
+
if (ownWrites) {
|
|
950
|
+
// The watermark and what this transaction wrote, in one
|
|
951
|
+
// statement: the capture trigger has put every change of it
|
|
952
|
+
// in the outbox already, under this transaction's xid.
|
|
953
|
+
const { rows: done } = await w.query(`WITH u AS (
|
|
954
|
+
UPDATE nowity.nowity_client SET last_mutation_id = $2, updated_at = now()
|
|
955
|
+
WHERE client_id = $1
|
|
956
|
+
RETURNING 1
|
|
957
|
+
)
|
|
958
|
+
SELECT pg_current_xact_id()::text AS xid, ${ownWrites.sql} AS writes,
|
|
959
|
+
(SELECT count(*) FROM u)::int AS updated`, [clientId, mutationId]);
|
|
960
|
+
written = {
|
|
961
|
+
xid: String(done[0].xid),
|
|
962
|
+
events: ownWrites.parse(done[0].writes, clientId, mutationId),
|
|
963
|
+
};
|
|
964
|
+
}
|
|
965
|
+
else {
|
|
966
|
+
await w.query(`UPDATE nowity.nowity_client SET last_mutation_id = $2, updated_at = now()
|
|
967
|
+
WHERE client_id = $1`, [clientId, mutationId]);
|
|
968
|
+
}
|
|
802
969
|
return { ok: true, lastMutationId: mutationId, value };
|
|
803
970
|
});
|
|
804
971
|
// A replay committed nothing; a commit time would be fiction.
|
|
@@ -812,6 +979,11 @@ class SyncEngine {
|
|
|
812
979
|
}
|
|
813
980
|
}
|
|
814
981
|
const { replayed: _replayed, ...rest } = outcome;
|
|
982
|
+
if (written !== null && committedAt !== undefined) {
|
|
983
|
+
await this.ackWithData(session, mutationId, written, committedAt).catch((err) =>
|
|
984
|
+
// The stream delivers it anyway; this only costs the latency.
|
|
985
|
+
this.onError(err));
|
|
986
|
+
}
|
|
815
987
|
return { ...rest, startedAt, ...(committedAt !== undefined ? { committedAt } : {}) };
|
|
816
988
|
}
|
|
817
989
|
catch (err) {
|
|
@@ -848,6 +1020,121 @@ class SyncEngine {
|
|
|
848
1020
|
};
|
|
849
1021
|
}
|
|
850
1022
|
}
|
|
1023
|
+
/**
|
|
1024
|
+
* The writer's subscriptions this mutation can have changed, recomputed
|
|
1025
|
+
* now and sent as one `tx` with its `lastMutationId` — before the result
|
|
1026
|
+
* (see {@link SyncEngineOptions.ackWithState}).
|
|
1027
|
+
*
|
|
1028
|
+
* Read in a snapshot opened after the commit, under the session's lock, so
|
|
1029
|
+
* it is newer than anything the session was sent before and older than
|
|
1030
|
+
* anything it is sent after. Each recomputed subscription remembers that
|
|
1031
|
+
* snapshot: the batch that later carries this transaction finds it already
|
|
1032
|
+
* seen and skips the subscription, and anything committed after it is in
|
|
1033
|
+
* a later batch, which recomputes as usual.
|
|
1034
|
+
*
|
|
1035
|
+
* All or nothing. The `lastMutationId` tells the client to drop its
|
|
1036
|
+
* optimistic copy of the mutation, so it may only go out when every
|
|
1037
|
+
* subscription the write can reach is in the same message; a write to a
|
|
1038
|
+
* permission table is left to the stream, whose invalidation path the
|
|
1039
|
+
* data-only recomputation here does not replace.
|
|
1040
|
+
*/
|
|
1041
|
+
async ackWithData(session, mutationId, written, committedAt) {
|
|
1042
|
+
if (session.closed)
|
|
1043
|
+
return;
|
|
1044
|
+
if (written.events.some((event) => this.permissionTables.has(event.table)))
|
|
1045
|
+
return;
|
|
1046
|
+
const release = await session.lock.acquire();
|
|
1047
|
+
try {
|
|
1048
|
+
// A subscribe being evaluated may have read before the commit and
|
|
1049
|
+
// register after this looked, and the lastMutationId below would
|
|
1050
|
+
// then confirm the mutation to a client one of whose subscriptions
|
|
1051
|
+
// does not show it. The stream sends that one; a subscribe that
|
|
1052
|
+
// starts from here on reads after the commit anyway.
|
|
1053
|
+
if (session.closed || session.subscribing > 0)
|
|
1054
|
+
return;
|
|
1055
|
+
const fanOutAt = Date.now();
|
|
1056
|
+
const reached = new Set();
|
|
1057
|
+
if (written.events.length)
|
|
1058
|
+
this.index.collect(written.events, reached);
|
|
1059
|
+
const subs = [...reached].filter((sub) => sub.session === session &&
|
|
1060
|
+
session.subs.get(sub.subId) === sub &&
|
|
1061
|
+
// Data never wakes a denied hand-written subscription; only an
|
|
1062
|
+
// invalidation does, and none comes from here.
|
|
1063
|
+
(sub.def.tracksReads || !sub.denied));
|
|
1064
|
+
const patches = [];
|
|
1065
|
+
const snapshots = [];
|
|
1066
|
+
const revoked = [];
|
|
1067
|
+
const mutators = [];
|
|
1068
|
+
if (subs.length) {
|
|
1069
|
+
this.stats.ackSnapshots += 1;
|
|
1070
|
+
const { mark, outcomes } = await this.opts.snapshots.withSnapshot(async (snap) => {
|
|
1071
|
+
const { rows } = await snap.query(`SELECT pg_current_snapshot()::text AS snap`);
|
|
1072
|
+
const outcomes = [];
|
|
1073
|
+
for (const sub of subs) {
|
|
1074
|
+
this.stats.ackEvaluations += 1;
|
|
1075
|
+
try {
|
|
1076
|
+
outcomes.push({ output: await this.evaluate(sub.def, sub.args, sub.session, snap, false) });
|
|
1077
|
+
}
|
|
1078
|
+
catch (err) {
|
|
1079
|
+
if (sub.def.tracksReads && (0, errors_1.isForbidden)(err))
|
|
1080
|
+
outcomes.push({ forbidden: err });
|
|
1081
|
+
else
|
|
1082
|
+
outcomes.push({ failed: err });
|
|
1083
|
+
}
|
|
1084
|
+
}
|
|
1085
|
+
return { mark: (0, pg_snapshot_1.parseSnapshot)(rows[0].snap), outcomes };
|
|
1086
|
+
});
|
|
1087
|
+
subs.forEach((sub, index) => {
|
|
1088
|
+
const outcome = outcomes[index];
|
|
1089
|
+
if (session.subs.get(sub.subId) !== sub)
|
|
1090
|
+
return;
|
|
1091
|
+
if ("failed" in outcome) {
|
|
1092
|
+
// As the stream would: the client hears about the query,
|
|
1093
|
+
// the rest of the message goes out.
|
|
1094
|
+
this.reportQueryFailure(sub, outcome.failed);
|
|
1095
|
+
return;
|
|
1096
|
+
}
|
|
1097
|
+
if (sub.def.tracksReads) {
|
|
1098
|
+
this.applyTracked(sub, outcome, patches, snapshots, revoked);
|
|
1099
|
+
}
|
|
1100
|
+
else if ("output" in outcome) {
|
|
1101
|
+
const patch = this.diffInto(sub, outcome.output);
|
|
1102
|
+
if (patch)
|
|
1103
|
+
patches.push(patch);
|
|
1104
|
+
}
|
|
1105
|
+
sub.mark = mark;
|
|
1106
|
+
});
|
|
1107
|
+
const resnapshotted = new Set(snapshots.map((snapshot) => snapshot.subId));
|
|
1108
|
+
for (const sub of subs) {
|
|
1109
|
+
if (resnapshotted.has(sub.subId))
|
|
1110
|
+
continue;
|
|
1111
|
+
const changed = this.changedMutators(sub);
|
|
1112
|
+
if (changed)
|
|
1113
|
+
mutators.push({ subId: sub.subId, mutators: changed });
|
|
1114
|
+
}
|
|
1115
|
+
}
|
|
1116
|
+
if (session.closed)
|
|
1117
|
+
return;
|
|
1118
|
+
const lastMutationId = Math.max(mutationId, session.lastSentMutationId);
|
|
1119
|
+
session.lastSentMutationId = lastMutationId;
|
|
1120
|
+
this.stats.acks += 1;
|
|
1121
|
+
session.send({
|
|
1122
|
+
t: "tx",
|
|
1123
|
+
position: written.xid,
|
|
1124
|
+
lastMutationId,
|
|
1125
|
+
...(session.timing
|
|
1126
|
+
? { timing: ackTiming(written.events, committedAt, fanOutAt) }
|
|
1127
|
+
: {}),
|
|
1128
|
+
patches,
|
|
1129
|
+
...(snapshots.length ? { snapshots } : {}),
|
|
1130
|
+
...(revoked.length ? { revoked } : {}),
|
|
1131
|
+
...(mutators.length ? { mutators } : {}),
|
|
1132
|
+
});
|
|
1133
|
+
}
|
|
1134
|
+
finally {
|
|
1135
|
+
release();
|
|
1136
|
+
}
|
|
1137
|
+
}
|
|
851
1138
|
// ------------------------------------------------------------------ epoch store
|
|
852
1139
|
/**
|
|
853
1140
|
* Move a scope's epoch on, once per change rather than once per reader.
|
|
@@ -940,3 +1227,14 @@ function txTiming(batch, session, readAt, fanOutAt) {
|
|
|
940
1227
|
}
|
|
941
1228
|
return { ...(writtenAt !== undefined ? { writtenAt } : {}), readAt, fanOutAt, sentAt: fanOutAt };
|
|
942
1229
|
}
|
|
1230
|
+
/** {@link TxTiming} of a mutation's own data: read from its transaction, not the stream. */
|
|
1231
|
+
function ackTiming(events, committedAt, fanOutAt) {
|
|
1232
|
+
let writtenAt;
|
|
1233
|
+
for (const event of events) {
|
|
1234
|
+
if (event.writtenAt === undefined)
|
|
1235
|
+
continue;
|
|
1236
|
+
if (writtenAt === undefined || event.writtenAt < writtenAt)
|
|
1237
|
+
writtenAt = event.writtenAt;
|
|
1238
|
+
}
|
|
1239
|
+
return { ...(writtenAt !== undefined ? { writtenAt } : {}), readAt: committedAt, fanOutAt, sentAt: fanOutAt };
|
|
1240
|
+
}
|
|
@@ -70,6 +70,14 @@ export declare class NowitySyncServer {
|
|
|
70
70
|
* processed before the session exists.
|
|
71
71
|
*/
|
|
72
72
|
private readonly chains;
|
|
73
|
+
/**
|
|
74
|
+
* Where a socket's mutations wait: behind the last `hello` (the session
|
|
75
|
+
* they are written under) and the mutations before them, not behind
|
|
76
|
+
* subscribes. A subscribe can take as long as its query; a move should not.
|
|
77
|
+
*/
|
|
78
|
+
private readonly mutationChains;
|
|
79
|
+
/** Settles once the socket's last `hello` has been handled. */
|
|
80
|
+
private readonly helloBarriers;
|
|
73
81
|
/** Registered on a borrowed server, and removed again on close. */
|
|
74
82
|
private upgradeHandler;
|
|
75
83
|
/** Pings sent since the socket last proved it is alive. */
|