nowity 1.10.0 → 1.12.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.
@@ -1,14 +1,45 @@
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
+ exports.describeNarrowing = describeNarrowing;
4
5
  const node_crypto_1 = require("node:crypto");
5
6
  const errors_1 = require("../api/errors");
6
7
  const diff_1 = require("../core/diff");
7
8
  const protocol_1 = require("../core/protocol");
8
9
  const types_1 = require("../core/types");
9
10
  const invalidation_index_1 = require("./invalidation-index");
11
+ const pg_snapshot_1 = require("./change-source/pg-snapshot");
10
12
  const evaluate_1 = require("./evaluate");
11
13
  const mutator_1 = require("./mutator");
14
+ /** See {@link SyncEngineOptions.fanOut}. */
15
+ exports.DEFAULT_FAN_OUT_CONCURRENCY = 4;
16
+ exports.DEFAULT_FAN_OUT_MIN_PER_SNAPSHOT = 8;
17
+ /**
18
+ * One holder at a time, in the order they asked.
19
+ *
20
+ * Both things that recompute a session's existing subscriptions and send the
21
+ * result — a batch and a mutation's own recomputation — hold its session's
22
+ * lock from before they open their snapshot until the message is out. (A
23
+ * subscribe creates a subscription rather than recomputing one; it is ordered
24
+ * against batches by the engine's queue and against acks by
25
+ * `EngineSession.subscribing`.) That keeps
26
+ * a subscription's diffs in order, and makes every recomputation of a session
27
+ * read in a snapshot newer than the one before it, so nothing ever moves a
28
+ * client back in time. A holder may wait for a connection, but nobody waits for
29
+ * a lock while holding a connection, which is what keeps it free of deadlocks.
30
+ */
31
+ class SessionLock {
32
+ constructor() {
33
+ this.tail = Promise.resolve();
34
+ }
35
+ acquire() {
36
+ let release;
37
+ const held = new Promise((resolve) => (release = resolve));
38
+ const previous = this.tail;
39
+ this.tail = previous.then(() => held);
40
+ return previous.then(() => release);
41
+ }
42
+ }
12
43
  /** Server-side handle for one connected client. */
13
44
  class EngineSession {
14
45
  constructor(info, send) {
@@ -26,6 +57,10 @@ class EngineSession {
26
57
  this.lastSentMutationId = -1;
27
58
  /** Serialises this client's mutations; they must be applied in order. */
28
59
  this.mutationChain = Promise.resolve();
60
+ /** See {@link SessionLock}. */
61
+ this.lock = new SessionLock();
62
+ /** Subscribes of this session being evaluated right now. */
63
+ this.subscribing = 0;
29
64
  this.closed = false;
30
65
  /**
31
66
  * This socket, as presence records it. Not the client id: a client id
@@ -40,6 +75,11 @@ class EngineSession {
40
75
  * Set by the socket front end from its `timing` option; off by default.
41
76
  */
42
77
  this.timing = false;
78
+ /**
79
+ * Send this connection each subscription's {@link SubNarrowing}. Set by
80
+ * the socket front end from its `narrowing` option; off by default.
81
+ */
82
+ this.narrowing = false;
43
83
  }
44
84
  }
45
85
  exports.EngineSession = EngineSession;
@@ -96,10 +136,27 @@ class SyncEngine {
96
136
  * application transactions they covered. Without it a regression
97
137
  * here looks like nothing at all until the process is under load.
98
138
  */
99
- this.stats = { batches: 0, transactions: 0, snapshots: 0, candidates: 0, evaluations: 0, fanOutMs: 0 };
139
+ this.stats = {
140
+ batches: 0,
141
+ transactions: 0,
142
+ snapshots: 0,
143
+ candidates: 0,
144
+ evaluations: 0,
145
+ fanOutMs: 0,
146
+ /** Mutations whose result went out with the writer's recomputed data. */
147
+ acks: 0,
148
+ /** Snapshots and recomputations those took (not in the totals above). */
149
+ ackSnapshots: 0,
150
+ ackEvaluations: 0,
151
+ /** Recomputations a batch skipped because the writer's ack had them already. */
152
+ skipped: 0,
153
+ };
100
154
  this.opts = opts;
101
155
  this.permissionTables = new Set(opts.permissionTables ?? []);
102
156
  this.narrow = opts.narrowInvalidation ?? true;
157
+ this.ackWithState = opts.ackWithState !== false && opts.source.ownWrites !== undefined;
158
+ this.fanOutConcurrency = Math.max(1, Math.floor(opts.fanOut?.concurrency ?? exports.DEFAULT_FAN_OUT_CONCURRENCY));
159
+ this.fanOutMinPerSnapshot = Math.max(1, Math.floor(opts.fanOut?.minPerSnapshot ?? exports.DEFAULT_FAN_OUT_MIN_PER_SNAPSHOT));
103
160
  this.onError = opts.onError ?? ((err) => console.error("[nowity/engine]", err));
104
161
  opts.derived?.onChange(() => {
105
162
  this.run(async () => this.pushDerived()).catch((err) => this.onError(err));
@@ -223,6 +280,22 @@ class SyncEngine {
223
280
  async subscribe(session, subId, queryName, args) {
224
281
  const def = this.opts.queries.get(queryName);
225
282
  await this.run(async () => {
283
+ if (session.closed)
284
+ return;
285
+ // Not under the session lock: a slow query would hold the writer's
286
+ // ack behind it. A mutation's ack skips the session while this
287
+ // runs instead (see ackWithData).
288
+ session.subscribing += 1;
289
+ try {
290
+ await this.subscribeNow(session, subId, def, args);
291
+ }
292
+ finally {
293
+ session.subscribing -= 1;
294
+ }
295
+ });
296
+ }
297
+ async subscribeNow(session, subId, def, args) {
298
+ {
226
299
  if (session.closed)
227
300
  return;
228
301
  await this.opts.snapshots.withSnapshot(async (snap) => {
@@ -248,6 +321,8 @@ class SyncEngine {
248
321
  entity: def.entity,
249
322
  filterColumns: null,
250
323
  mutatorsSent: "[]",
324
+ narrowingSent: "",
325
+ mark: null,
251
326
  };
252
327
  let output = null;
253
328
  if (allowed) {
@@ -273,6 +348,7 @@ class SyncEngine {
273
348
  lastMutationId,
274
349
  patches: [],
275
350
  revoked: [{ subId, reason: "not-authorized", epoch }],
351
+ ...this.narrowingUpdate(sub),
276
352
  });
277
353
  return;
278
354
  }
@@ -286,7 +362,7 @@ class SyncEngine {
286
362
  ...this.toSnapshot(sub, output, "initial"),
287
363
  });
288
364
  });
289
- });
365
+ }
290
366
  }
291
367
  async unsubscribe(session, subId) {
292
368
  await this.run(async () => {
@@ -405,105 +481,172 @@ class SyncEngine {
405
481
  // shape this whole change exists to get rid of.
406
482
  if (interested.size === 0)
407
483
  return;
408
- const outgoing = [];
409
- this.stats.snapshots += 1;
410
- await this.opts.snapshots.withSnapshot(async (snap) => {
411
- const epochCache = new Map();
412
- const mutationIds = await this.readLastMutationIds(snap, [...interested].map((s) => s.info.clientId));
413
- for (const session of interested) {
414
- if (session.closed)
415
- continue;
416
- const patches = [];
417
- const snapshots = [];
418
- const revoked = [];
419
- const mutators = [];
420
- for (const sub of bySession.get(session) ?? []) {
421
- // A subscription torn down while this batch was in flight is
422
- // still in the set the index handed over.
423
- if (session.subs.get(sub.subId) !== sub)
424
- continue;
425
- const invalidated = revalidateEverything ||
426
- (sub.scope !== null && invalidatedScopes.has(sub.scope));
427
- // A query that reports its own read set needs no scopes and no
428
- // separate authorize pass: the permission table it consulted is
429
- // in that read set, so a change to it wakes the subscription up
430
- // the same way a change to the data does — including when the
431
- // subscription is currently denied, which is what makes
432
- // *gaining* access work.
433
- if (sub.def.tracksReads) {
434
- try {
435
- await this.refreshTracked(sub, snap, patches, snapshots, revoked);
436
- }
437
- catch (err) {
438
- this.onError(err);
439
- session.send({
440
- t: "error",
441
- subId: sub.subId,
442
- code: "query-failed",
443
- message: err.message,
444
- });
445
- }
446
- continue;
447
- }
448
- // A denied subscription is woken only by an invalidation. No
449
- // data event may produce anything for it, no matter that its
450
- // socket subscribed before the rights were taken away.
451
- if (!invalidated && sub.denied)
452
- continue;
453
- try {
454
- if (invalidated) {
455
- await this.reauthorizeAndResnapshot(sub, snap, epochCache, snapshots, revoked);
456
- }
457
- else {
458
- const patch = await this.patchFor(sub, snap);
459
- if (patch)
460
- patches.push(patch);
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
- }
484
+ const groups = this.partition([...interested], bySession);
485
+ const ctx = { batch, readAt, fanOutAt, invalidatedScopes, revalidateEverything, bySession };
486
+ const settled = await Promise.allSettled(groups.map((group) => this.fanOutGroup(group, ctx)));
487
+ // Every group has released its locks by now; the first failure fails
488
+ // the batch, and the source delivers it again — the groups that made
489
+ // it diff to nothing the second time.
490
+ for (const result of settled) {
491
+ if (result.status === "rejected")
492
+ throw result.reason;
493
+ }
494
+ }
495
+ /**
496
+ * Sessions in groups of roughly equal work, one snapshot per group.
497
+ *
498
+ * A session is never split: everything it is sent for one batch comes from
499
+ * one snapshot. Groups only appear when there is enough work to pay for
500
+ * the extra connection.
501
+ */
502
+ partition(sessions, bySession) {
503
+ const open = sessions.filter((session) => !session.closed);
504
+ const work = (session) => bySession.get(session)?.length ?? 0;
505
+ const total = open.reduce((sum, session) => sum + work(session), 0);
506
+ const count = Math.min(this.fanOutConcurrency, open.length, Math.max(1, Math.ceil(total / this.fanOutMinPerSnapshot)));
507
+ if (count <= 1)
508
+ return open.length ? [open] : [];
509
+ const groups = Array.from({ length: count }, () => ({ load: 0, sessions: [] }));
510
+ for (const session of [...open].sort((a, b) => work(b) - work(a))) {
511
+ let lightest = groups[0];
512
+ for (const group of groups)
513
+ if (group.load < lightest.load)
514
+ lightest = group;
515
+ lightest.sessions.push(session);
516
+ // A session with no recomputation still costs its watermark read.
517
+ lightest.load += Math.max(1, work(session));
518
+ }
519
+ return groups.map((group) => group.sessions).filter((group) => group.length > 0);
520
+ }
521
+ async fanOutGroup(sessions, ctx) {
522
+ const releases = [];
523
+ try {
524
+ // Locks first, then the snapshot: see SessionLock. The groups of
525
+ // one batch hold disjoint sessions, so taking them one by one
526
+ // cannot deadlock.
527
+ for (const session of sessions)
528
+ releases.push(await session.lock.acquire());
529
+ const outgoing = [];
530
+ this.stats.snapshots += 1;
531
+ await this.opts.snapshots.withSnapshot(async (snap) => {
532
+ const epochCache = new Map();
533
+ const live = sessions.filter((session) => !session.closed);
534
+ const mutationIds = await this.readLastMutationIds(snap, live.map((s) => s.info.clientId));
535
+ for (const session of live) {
536
+ const message = await this.fanOutSession(session, snap, epochCache, mutationIds, ctx);
537
+ if (message)
538
+ outgoing.push({ session, message });
472
539
  }
473
- // A recomputation can change what a subscription read, and with
474
- // it which derived mutators apply. Snapshots carry their own.
475
- const resnapshotted = new Set(snapshots.map((snapshot) => snapshot.subId));
476
- for (const sub of bySession.get(session) ?? []) {
477
- if (session.subs.get(sub.subId) !== sub || resnapshotted.has(sub.subId))
478
- continue;
479
- const changed = this.changedMutators(sub);
480
- if (changed)
481
- mutators.push({ subId: sub.subId, mutators: changed });
540
+ });
541
+ for (const { session, message } of outgoing) {
542
+ if (!session.closed)
543
+ session.send(message);
544
+ }
545
+ }
546
+ finally {
547
+ for (const release of releases)
548
+ release();
549
+ }
550
+ }
551
+ /** What one session is sent for a batch, if anything. */
552
+ async fanOutSession(session, snap, epochCache, mutationIds, ctx) {
553
+ const { batch, bySession, invalidatedScopes, revalidateEverything } = ctx;
554
+ const patches = [];
555
+ const snapshots = [];
556
+ const revoked = [];
557
+ const mutators = [];
558
+ const narrowing = [];
559
+ for (const sub of bySession.get(session) ?? []) {
560
+ // A subscription torn down while this batch was in flight is
561
+ // still in the set the index handed over.
562
+ if (session.subs.get(sub.subId) !== sub)
563
+ continue;
564
+ const invalidated = revalidateEverything ||
565
+ (sub.scope !== null && invalidatedScopes.has(sub.scope));
566
+ // Recomputed for the writer's own mutation in a snapshot that
567
+ // already saw every transaction of this batch: the answer cannot
568
+ // have moved since, and recomputing would only diff to nothing.
569
+ // Never for an invalidation, which the data alone does not show.
570
+ if (!invalidated && sub.mark !== null && (0, pg_snapshot_1.seesAll)(sub.mark, batch.xids)) {
571
+ this.stats.skipped += 1;
572
+ continue;
573
+ }
574
+ sub.mark = null;
575
+ // A query that reports its own read set needs no scopes and no
576
+ // separate authorize pass: the permission table it consulted is
577
+ // in that read set, so a change to it wakes the subscription up
578
+ // the same way a change to the data does — including when the
579
+ // subscription is currently denied, which is what makes
580
+ // *gaining* access work.
581
+ if (sub.def.tracksReads) {
582
+ try {
583
+ await this.refreshTracked(sub, snap, patches, snapshots, revoked);
482
584
  }
483
- const lastMutationId = mutationIds.get(session.info.clientId) ?? 0;
484
- const mutationNews = lastMutationId > session.lastSentMutationId;
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
- });
585
+ catch (err) {
586
+ this.reportQueryFailure(sub, err);
500
587
  }
588
+ continue;
589
+ }
590
+ // A denied subscription is woken only by an invalidation. No
591
+ // data event may produce anything for it, no matter that its
592
+ // socket subscribed before the rights were taken away.
593
+ if (!invalidated && sub.denied)
594
+ continue;
595
+ try {
596
+ if (invalidated) {
597
+ await this.reauthorizeAndResnapshot(sub, snap, epochCache, snapshots, revoked);
598
+ }
599
+ else {
600
+ const patch = await this.patchFor(sub, snap);
601
+ if (patch)
602
+ patches.push(patch);
603
+ }
604
+ }
605
+ catch (err) {
606
+ this.reportQueryFailure(sub, err);
501
607
  }
502
- });
503
- for (const { session, message } of outgoing) {
504
- if (!session.closed)
505
- session.send(message);
506
608
  }
609
+ // A recomputation can change what a subscription read, and with
610
+ // it which derived mutators apply. Snapshots carry their own.
611
+ const resnapshotted = new Set(snapshots.map((snapshot) => snapshot.subId));
612
+ for (const sub of bySession.get(session) ?? []) {
613
+ if (session.subs.get(sub.subId) !== sub || resnapshotted.has(sub.subId))
614
+ continue;
615
+ const changed = this.changedMutators(sub);
616
+ if (changed)
617
+ mutators.push({ subId: sub.subId, mutators: changed });
618
+ const narrowed = this.changedNarrowing(sub);
619
+ if (narrowed)
620
+ narrowing.push({ subId: sub.subId, narrowing: narrowed });
621
+ }
622
+ // Never lower than what the client was already told: a mutation's own
623
+ // recomputation may have confirmed it before this batch got here.
624
+ const lastMutationId = Math.max(mutationIds.get(session.info.clientId) ?? 0, session.lastSentMutationId, 0);
625
+ const mutationNews = lastMutationId > session.lastSentMutationId;
626
+ if (!(patches.length || snapshots.length || revoked.length || mutators.length || narrowing.length || mutationNews)) {
627
+ return null;
628
+ }
629
+ session.lastSentMutationId = lastMutationId;
630
+ return {
631
+ t: "tx",
632
+ position: batch.position,
633
+ lastMutationId,
634
+ ...(session.timing ? { timing: txTiming(batch, session, ctx.readAt, ctx.fanOutAt) } : {}),
635
+ patches,
636
+ ...(snapshots.length ? { snapshots } : {}),
637
+ ...(revoked.length ? { revoked } : {}),
638
+ ...(mutators.length ? { mutators } : {}),
639
+ ...(narrowing.length ? { narrowing } : {}),
640
+ };
641
+ }
642
+ reportQueryFailure(sub, err) {
643
+ this.onError(err);
644
+ sub.session.send({
645
+ t: "error",
646
+ subId: sub.subId,
647
+ code: "query-failed",
648
+ message: err.message,
649
+ });
507
650
  }
508
651
  /**
509
652
  * Sessions whose mutation watermark this batch may have moved.
@@ -590,15 +733,23 @@ class SyncEngine {
590
733
  * One pass over a read-set-tracking subscription, in whichever direction it
591
734
  * moved: granted, revoked, or merely changed.
592
735
  */
593
- async refreshTracked(sub, snap, patches, snapshots, revoked) {
736
+ async refreshTracked(sub, snap, patches, snapshots, revoked, counted = true) {
594
737
  let output;
595
738
  try {
596
- output = await this.evaluate(sub.def, sub.args, sub.session, snap);
739
+ output = await this.evaluate(sub.def, sub.args, sub.session, snap, counted);
597
740
  }
598
741
  catch (err) {
599
742
  if (!(0, errors_1.isForbidden)(err))
600
743
  throw err;
601
- this.rememberRefusedReads(sub, err);
744
+ this.applyTracked(sub, { forbidden: err }, patches, snapshots, revoked);
745
+ return;
746
+ }
747
+ this.applyTracked(sub, { output }, patches, snapshots, revoked);
748
+ }
749
+ /** The second half of {@link refreshTracked}: adopt an evaluation's outcome. */
750
+ applyTracked(sub, outcome, patches, snapshots, revoked) {
751
+ if ("forbidden" in outcome) {
752
+ this.rememberRefusedReads(sub, outcome.forbidden);
602
753
  if (!sub.denied) {
603
754
  sub.denied = true;
604
755
  sub.prev = (0, evaluate_1.emptyOutput)();
@@ -610,6 +761,7 @@ class SyncEngine {
610
761
  }
611
762
  return;
612
763
  }
764
+ const { output } = outcome;
613
765
  const wasDenied = sub.denied;
614
766
  sub.denied = false;
615
767
  if (wasDenied) {
@@ -678,13 +830,15 @@ class SyncEngine {
678
830
  ...(Object.keys(extraRemove).length ? { extraRemove } : {}),
679
831
  };
680
832
  }
681
- evaluate(def, args, session, snap) {
682
- this.stats.evaluations += 1;
833
+ evaluate(def, args, session, snap, counted = true) {
834
+ if (counted)
835
+ this.stats.evaluations += 1;
683
836
  return (0, evaluate_1.evaluateQuery)(def, args, session.info, snap);
684
837
  }
685
838
  toSnapshot(sub, output, reason) {
686
839
  const mutators = this.derivedFor(sub);
687
840
  sub.mutatorsSent = JSON.stringify(mutators);
841
+ const narrowing = this.narrowingField(sub);
688
842
  return {
689
843
  subId: sub.subId,
690
844
  entity: sub.entity,
@@ -697,8 +851,34 @@ class SyncEngine {
697
851
  epoch: sub.epoch,
698
852
  reason,
699
853
  ...(mutators.length ? { mutators } : {}),
854
+ ...narrowing,
700
855
  };
701
856
  }
857
+ // ------------------------------------------------------------ narrowing
858
+ /** `{ narrowing }` for a message, and remembered as sent; empty off a narrowing connection. */
859
+ narrowingField(sub) {
860
+ if (!sub.session.narrowing)
861
+ return {};
862
+ const narrowing = describeNarrowing(sub.keys, this.narrow, sub.def.tables);
863
+ sub.narrowingSent = JSON.stringify(narrowing);
864
+ return { narrowing };
865
+ }
866
+ /** `{ narrowing: [update] }` for a `tx`, for a subscription that gets no snapshot. */
867
+ narrowingUpdate(sub) {
868
+ const { narrowing } = this.narrowingField(sub);
869
+ return narrowing ? { narrowing: [{ subId: sub.subId, narrowing }] } : {};
870
+ }
871
+ /** The narrowing if it differs from what the client was last sent, else null. */
872
+ changedNarrowing(sub) {
873
+ if (!sub.session.narrowing)
874
+ return null;
875
+ const narrowing = describeNarrowing(sub.keys, this.narrow, sub.def.tables);
876
+ const serialised = JSON.stringify(narrowing);
877
+ if (serialised === sub.narrowingSent)
878
+ return null;
879
+ sub.narrowingSent = serialised;
880
+ return narrowing;
881
+ }
702
882
  // ------------------------------------------------------------ derived mutators
703
883
  /** What the subscription should hold now. */
704
884
  derivedFor(sub) {
@@ -754,10 +934,24 @@ class SyncEngine {
754
934
  const startedAt = Date.now();
755
935
  try {
756
936
  const def = this.opts.mutators.get(name);
937
+ const ownWrites = this.ackWithState ? this.opts.source.ownWrites : undefined;
938
+ let written = null;
757
939
  const outcome = await this.opts.writes.withWrite(async (w) => {
758
- await w.query(`INSERT INTO nowity.nowity_client (client_id) VALUES ($1) ON CONFLICT DO NOTHING`, [clientId]);
759
- const { rows } = await w.query(`SELECT last_mutation_id::text AS last, session_token FROM nowity.nowity_client
760
- WHERE client_id = $1 FOR UPDATE`, [clientId]);
940
+ // One round trip for what used to be three: the row is created
941
+ // if missing and locked either way (the conflict branch takes
942
+ // the same row lock `FOR UPDATE` would), and the transaction is
943
+ // stamped so the capture trigger can attribute the resulting
944
+ // change events to this client and mutation. Stamping before
945
+ // the checks below is harmless: a refusal rolls it back.
946
+ const { rows } = await w.query(`WITH c AS (
947
+ INSERT INTO nowity.nowity_client AS c (client_id) VALUES ($1)
948
+ ON CONFLICT (client_id) DO UPDATE SET client_id = c.client_id
949
+ RETURNING last_mutation_id, session_token
950
+ )
951
+ SELECT c.last_mutation_id::text AS last, c.session_token,
952
+ set_config('nowity.client_id', $1, true) AS stamped_client,
953
+ set_config('nowity.mutation_id', $2, true) AS stamped_mutation
954
+ FROM c`, [clientId, String(mutationId)]);
761
955
  const last = Number(rows[0].last);
762
956
  const owner = rows[0].session_token;
763
957
  // Another connection has claimed this id since. Numbering is per
@@ -787,18 +981,32 @@ class SyncEngine {
787
981
  `id — mutation numbering is per client, and each connection ` +
788
982
  `needs an id of its own.`);
789
983
  }
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
984
  const value = await def.server(args, {
795
985
  db: w,
796
986
  session: session.info,
797
987
  mutationId,
798
988
  afterCommit: (fn) => committed.push(fn),
799
989
  });
800
- await w.query(`UPDATE nowity.nowity_client SET last_mutation_id = $2, updated_at = now()
801
- WHERE client_id = $1`, [clientId, mutationId]);
990
+ if (ownWrites) {
991
+ // The watermark and what this transaction wrote, in one
992
+ // statement: the capture trigger has put every change of it
993
+ // in the outbox already, under this transaction's xid.
994
+ const { rows: done } = await w.query(`WITH u AS (
995
+ UPDATE nowity.nowity_client SET last_mutation_id = $2, updated_at = now()
996
+ WHERE client_id = $1
997
+ RETURNING 1
998
+ )
999
+ SELECT pg_current_xact_id()::text AS xid, ${ownWrites.sql} AS writes,
1000
+ (SELECT count(*) FROM u)::int AS updated`, [clientId, mutationId]);
1001
+ written = {
1002
+ xid: String(done[0].xid),
1003
+ events: ownWrites.parse(done[0].writes, clientId, mutationId),
1004
+ };
1005
+ }
1006
+ else {
1007
+ await w.query(`UPDATE nowity.nowity_client SET last_mutation_id = $2, updated_at = now()
1008
+ WHERE client_id = $1`, [clientId, mutationId]);
1009
+ }
802
1010
  return { ok: true, lastMutationId: mutationId, value };
803
1011
  });
804
1012
  // A replay committed nothing; a commit time would be fiction.
@@ -812,6 +1020,11 @@ class SyncEngine {
812
1020
  }
813
1021
  }
814
1022
  const { replayed: _replayed, ...rest } = outcome;
1023
+ if (written !== null && committedAt !== undefined) {
1024
+ await this.ackWithData(session, mutationId, written, committedAt).catch((err) =>
1025
+ // The stream delivers it anyway; this only costs the latency.
1026
+ this.onError(err));
1027
+ }
815
1028
  return { ...rest, startedAt, ...(committedAt !== undefined ? { committedAt } : {}) };
816
1029
  }
817
1030
  catch (err) {
@@ -848,6 +1061,126 @@ class SyncEngine {
848
1061
  };
849
1062
  }
850
1063
  }
1064
+ /**
1065
+ * The writer's subscriptions this mutation can have changed, recomputed
1066
+ * now and sent as one `tx` with its `lastMutationId` — before the result
1067
+ * (see {@link SyncEngineOptions.ackWithState}).
1068
+ *
1069
+ * Read in a snapshot opened after the commit, under the session's lock, so
1070
+ * it is newer than anything the session was sent before and older than
1071
+ * anything it is sent after. Each recomputed subscription remembers that
1072
+ * snapshot: the batch that later carries this transaction finds it already
1073
+ * seen and skips the subscription, and anything committed after it is in
1074
+ * a later batch, which recomputes as usual.
1075
+ *
1076
+ * All or nothing. The `lastMutationId` tells the client to drop its
1077
+ * optimistic copy of the mutation, so it may only go out when every
1078
+ * subscription the write can reach is in the same message; a write to a
1079
+ * permission table is left to the stream, whose invalidation path the
1080
+ * data-only recomputation here does not replace.
1081
+ */
1082
+ async ackWithData(session, mutationId, written, committedAt) {
1083
+ if (session.closed)
1084
+ return;
1085
+ if (written.events.some((event) => this.permissionTables.has(event.table)))
1086
+ return;
1087
+ const release = await session.lock.acquire();
1088
+ try {
1089
+ // A subscribe being evaluated may have read before the commit and
1090
+ // register after this looked, and the lastMutationId below would
1091
+ // then confirm the mutation to a client one of whose subscriptions
1092
+ // does not show it. The stream sends that one; a subscribe that
1093
+ // starts from here on reads after the commit anyway.
1094
+ if (session.closed || session.subscribing > 0)
1095
+ return;
1096
+ const fanOutAt = Date.now();
1097
+ const reached = new Set();
1098
+ if (written.events.length)
1099
+ this.index.collect(written.events, reached);
1100
+ const subs = [...reached].filter((sub) => sub.session === session &&
1101
+ session.subs.get(sub.subId) === sub &&
1102
+ // Data never wakes a denied hand-written subscription; only an
1103
+ // invalidation does, and none comes from here.
1104
+ (sub.def.tracksReads || !sub.denied));
1105
+ const patches = [];
1106
+ const snapshots = [];
1107
+ const revoked = [];
1108
+ const mutators = [];
1109
+ const narrowing = [];
1110
+ if (subs.length) {
1111
+ this.stats.ackSnapshots += 1;
1112
+ const { mark, outcomes } = await this.opts.snapshots.withSnapshot(async (snap) => {
1113
+ const { rows } = await snap.query(`SELECT pg_current_snapshot()::text AS snap`);
1114
+ const outcomes = [];
1115
+ for (const sub of subs) {
1116
+ this.stats.ackEvaluations += 1;
1117
+ try {
1118
+ outcomes.push({ output: await this.evaluate(sub.def, sub.args, sub.session, snap, false) });
1119
+ }
1120
+ catch (err) {
1121
+ if (sub.def.tracksReads && (0, errors_1.isForbidden)(err))
1122
+ outcomes.push({ forbidden: err });
1123
+ else
1124
+ outcomes.push({ failed: err });
1125
+ }
1126
+ }
1127
+ return { mark: (0, pg_snapshot_1.parseSnapshot)(rows[0].snap), outcomes };
1128
+ });
1129
+ subs.forEach((sub, index) => {
1130
+ const outcome = outcomes[index];
1131
+ if (session.subs.get(sub.subId) !== sub)
1132
+ return;
1133
+ if ("failed" in outcome) {
1134
+ // As the stream would: the client hears about the query,
1135
+ // the rest of the message goes out.
1136
+ this.reportQueryFailure(sub, outcome.failed);
1137
+ return;
1138
+ }
1139
+ if (sub.def.tracksReads) {
1140
+ this.applyTracked(sub, outcome, patches, snapshots, revoked);
1141
+ }
1142
+ else if ("output" in outcome) {
1143
+ const patch = this.diffInto(sub, outcome.output);
1144
+ if (patch)
1145
+ patches.push(patch);
1146
+ }
1147
+ sub.mark = mark;
1148
+ });
1149
+ const resnapshotted = new Set(snapshots.map((snapshot) => snapshot.subId));
1150
+ for (const sub of subs) {
1151
+ if (resnapshotted.has(sub.subId))
1152
+ continue;
1153
+ const changed = this.changedMutators(sub);
1154
+ if (changed)
1155
+ mutators.push({ subId: sub.subId, mutators: changed });
1156
+ const narrowed = this.changedNarrowing(sub);
1157
+ if (narrowed)
1158
+ narrowing.push({ subId: sub.subId, narrowing: narrowed });
1159
+ }
1160
+ }
1161
+ if (session.closed)
1162
+ return;
1163
+ const lastMutationId = Math.max(mutationId, session.lastSentMutationId);
1164
+ session.lastSentMutationId = lastMutationId;
1165
+ this.stats.acks += 1;
1166
+ session.send({
1167
+ t: "tx",
1168
+ position: written.xid,
1169
+ lastMutationId,
1170
+ ...(session.timing
1171
+ ? { timing: ackTiming(written.events, committedAt, fanOutAt) }
1172
+ : {}),
1173
+ patches,
1174
+ ...(snapshots.length ? { snapshots } : {}),
1175
+ ...(revoked.length ? { revoked } : {}),
1176
+ ...(mutators.length ? { mutators } : {}),
1177
+ ...(narrowing.length ? { narrowing } : {}),
1178
+ });
1179
+ }
1180
+ finally {
1181
+ release();
1182
+ }
1183
+ }
851
1184
  // ------------------------------------------------------------------ epoch store
852
1185
  /**
853
1186
  * Move a scope's epoch on, once per change rather than once per reader.
@@ -917,6 +1250,26 @@ function narrowing(keys, tables, declared) {
917
1250
  out.set(table, types_1.ANY_ROWS);
918
1251
  return out;
919
1252
  }
1253
+ /**
1254
+ * What a developer panel is told about a subscription's read keys: tables,
1255
+ * column names and how many values — never a value, which is row data.
1256
+ * Tables sorted, so the same narrowing always serialises the same.
1257
+ */
1258
+ function describeNarrowing(keys, narrowed, declared = []) {
1259
+ if (keys === null)
1260
+ return { always: true, narrowed, tables: [] };
1261
+ const declaredSet = new Set(declared);
1262
+ const tables = [...keys.entries()]
1263
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
1264
+ .map(([table, tableKeys]) => {
1265
+ if (tableKeys === types_1.ANY_ROWS) {
1266
+ return declaredSet.has(table) ? { table, whole: true, declared: true } : { table, whole: true };
1267
+ }
1268
+ const columns = [...new Set(tableKeys.map((key) => key.column))].sort();
1269
+ return { table, whole: false, columns, keys: tableKeys.length };
1270
+ });
1271
+ return { always: false, narrowed, tables };
1272
+ }
920
1273
  function sameIds(a, b) {
921
1274
  if (a.length !== b.length)
922
1275
  return false;
@@ -940,3 +1293,14 @@ function txTiming(batch, session, readAt, fanOutAt) {
940
1293
  }
941
1294
  return { ...(writtenAt !== undefined ? { writtenAt } : {}), readAt, fanOutAt, sentAt: fanOutAt };
942
1295
  }
1296
+ /** {@link TxTiming} of a mutation's own data: read from its transaction, not the stream. */
1297
+ function ackTiming(events, committedAt, fanOutAt) {
1298
+ let writtenAt;
1299
+ for (const event of events) {
1300
+ if (event.writtenAt === undefined)
1301
+ continue;
1302
+ if (writtenAt === undefined || event.writtenAt < writtenAt)
1303
+ writtenAt = event.writtenAt;
1304
+ }
1305
+ return { ...(writtenAt !== undefined ? { writtenAt } : {}), readAt: committedAt, fanOutAt, sentAt: fanOutAt };
1306
+ }