nowity 1.9.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.
Files changed (38) hide show
  1. package/README.md +124 -16
  2. package/dist/client/clock.d.ts +98 -0
  3. package/dist/client/clock.d.ts.map +1 -0
  4. package/dist/client/clock.js +154 -0
  5. package/dist/client/devtools.d.ts +64 -1
  6. package/dist/client/devtools.d.ts.map +1 -1
  7. package/dist/client/devtools.js +134 -22
  8. package/dist/client/nowity-client.d.ts +38 -0
  9. package/dist/client/nowity-client.d.ts.map +1 -1
  10. package/dist/client/nowity-client.js +93 -3
  11. package/dist/client.d.ts +3 -0
  12. package/dist/client.d.ts.map +1 -1
  13. package/dist/client.js +4 -1
  14. package/dist/core/protocol.d.ts +70 -2
  15. package/dist/core/protocol.d.ts.map +1 -1
  16. package/dist/core/types.d.ts +13 -0
  17. package/dist/core/types.d.ts.map +1 -1
  18. package/dist/devtools.d.ts +14 -1
  19. package/dist/devtools.d.ts.map +1 -1
  20. package/dist/devtools.js +64 -18
  21. package/dist/server/api/configure.d.ts +5 -1
  22. package/dist/server/api/configure.d.ts.map +1 -1
  23. package/dist/server/api/configure.js +2 -0
  24. package/dist/server/change-source/change-source.d.ts +23 -5
  25. package/dist/server/change-source/change-source.d.ts.map +1 -1
  26. package/dist/server/change-source/outbox-change-source.d.ts +47 -12
  27. package/dist/server/change-source/outbox-change-source.d.ts.map +1 -1
  28. package/dist/server/change-source/outbox-change-source.js +154 -65
  29. package/dist/server/change-source/pg-snapshot.d.ts +25 -0
  30. package/dist/server/change-source/pg-snapshot.d.ts.map +1 -0
  31. package/dist/server/change-source/pg-snapshot.js +43 -0
  32. package/dist/server/sync-engine.d.ts +119 -0
  33. package/dist/server/sync-engine.d.ts.map +1 -1
  34. package/dist/server/sync-engine.js +445 -117
  35. package/dist/server/ws-server.d.ts +28 -0
  36. package/dist/server/ws-server.d.ts.map +1 -1
  37. package/dist/server/ws-server.js +112 -6
  38. 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
@@ -35,6 +69,11 @@ class EngineSession {
35
69
  this.connectionId = (0, node_crypto_1.randomUUID)();
36
70
  /** What the client last said it is looking at (`setContext`). */
37
71
  this.context = null;
72
+ /**
73
+ * Send this connection where its changes spent their time (`TxTiming`).
74
+ * Set by the socket front end from its `timing` option; off by default.
75
+ */
76
+ this.timing = false;
38
77
  }
39
78
  }
40
79
  exports.EngineSession = EngineSession;
@@ -91,10 +130,27 @@ class SyncEngine {
91
130
  * application transactions they covered. Without it a regression
92
131
  * here looks like nothing at all until the process is under load.
93
132
  */
94
- this.stats = { batches: 0, transactions: 0, snapshots: 0, candidates: 0, evaluations: 0, fanOutMs: 0 };
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
+ };
95
148
  this.opts = opts;
96
149
  this.permissionTables = new Set(opts.permissionTables ?? []);
97
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));
98
154
  this.onError = opts.onError ?? ((err) => console.error("[nowity/engine]", err));
99
155
  opts.derived?.onChange(() => {
100
156
  this.run(async () => this.pushDerived()).catch((err) => this.onError(err));
@@ -106,7 +162,11 @@ class SyncEngine {
106
162
  return;
107
163
  this.started = true;
108
164
  const from = await this.opts.snapshots.withSnapshot((snap) => this.opts.source.startPosition(snap));
109
- await this.opts.source.start(from, (batch) => this.run(() => this.timedBatch(batch)));
165
+ await this.opts.source.start(from, (batch) => {
166
+ // Taken before the queue: waiting behind other work is part of the push.
167
+ const readAt = Date.now();
168
+ return this.run(() => this.timedBatch(batch, readAt));
169
+ });
110
170
  }
111
171
  async stop() {
112
172
  if (!this.started)
@@ -214,6 +274,22 @@ class SyncEngine {
214
274
  async subscribe(session, subId, queryName, args) {
215
275
  const def = this.opts.queries.get(queryName);
216
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
+ {
217
293
  if (session.closed)
218
294
  return;
219
295
  await this.opts.snapshots.withSnapshot(async (snap) => {
@@ -239,6 +315,7 @@ class SyncEngine {
239
315
  entity: def.entity,
240
316
  filterColumns: null,
241
317
  mutatorsSent: "[]",
318
+ mark: null,
242
319
  };
243
320
  let output = null;
244
321
  if (allowed) {
@@ -277,7 +354,7 @@ class SyncEngine {
277
354
  ...this.toSnapshot(sub, output, "initial"),
278
355
  });
279
356
  });
280
- });
357
+ }
281
358
  }
282
359
  async unsubscribe(session, subId) {
283
360
  await this.run(async () => {
@@ -331,16 +408,17 @@ class SyncEngine {
331
408
  }
332
409
  // ------------------------------------------------------------------ change fan-out
333
410
  /** `handleBatch`, with the one number worth watching taken around it. */
334
- async timedBatch(batch) {
411
+ async timedBatch(batch, readAt = Date.now()) {
335
412
  const started = process.hrtime.bigint();
336
413
  try {
337
- await this.handleBatch(batch);
414
+ await this.handleBatch(batch, readAt);
338
415
  }
339
416
  finally {
340
417
  this.stats.fanOutMs += Number(process.hrtime.bigint() - started) / 1e6;
341
418
  }
342
419
  }
343
- async handleBatch(batch) {
420
+ async handleBatch(batch, readAt) {
421
+ const fanOutAt = Date.now();
344
422
  const invalidatedScopes = new Set();
345
423
  let revalidateEverything = false;
346
424
  for (const event of batch.events) {
@@ -395,104 +473,166 @@ class SyncEngine {
395
473
  // shape this whole change exists to get rid of.
396
474
  if (interested.size === 0)
397
475
  return;
398
- const outgoing = [];
399
- this.stats.snapshots += 1;
400
- await this.opts.snapshots.withSnapshot(async (snap) => {
401
- const epochCache = new Map();
402
- const mutationIds = await this.readLastMutationIds(snap, [...interested].map((s) => s.info.clientId));
403
- for (const session of interested) {
404
- if (session.closed)
405
- continue;
406
- const patches = [];
407
- const snapshots = [];
408
- const revoked = [];
409
- const mutators = [];
410
- for (const sub of bySession.get(session) ?? []) {
411
- // A subscription torn down while this batch was in flight is
412
- // still in the set the index handed over.
413
- if (session.subs.get(sub.subId) !== sub)
414
- continue;
415
- const invalidated = revalidateEverything ||
416
- (sub.scope !== null && invalidatedScopes.has(sub.scope));
417
- // A query that reports its own read set needs no scopes and no
418
- // separate authorize pass: the permission table it consulted is
419
- // in that read set, so a change to it wakes the subscription up
420
- // the same way a change to the data does — including when the
421
- // subscription is currently denied, which is what makes
422
- // *gaining* access work.
423
- if (sub.def.tracksReads) {
424
- try {
425
- await this.refreshTracked(sub, snap, patches, snapshots, revoked);
426
- }
427
- catch (err) {
428
- this.onError(err);
429
- session.send({
430
- t: "error",
431
- subId: sub.subId,
432
- code: "query-failed",
433
- message: err.message,
434
- });
435
- }
436
- continue;
437
- }
438
- // A denied subscription is woken only by an invalidation. No
439
- // data event may produce anything for it, no matter that its
440
- // socket subscribed before the rights were taken away.
441
- if (!invalidated && sub.denied)
442
- continue;
443
- try {
444
- if (invalidated) {
445
- await this.reauthorizeAndResnapshot(sub, snap, epochCache, snapshots, revoked);
446
- }
447
- else {
448
- const patch = await this.patchFor(sub, snap);
449
- if (patch)
450
- patches.push(patch);
451
- }
452
- }
453
- catch (err) {
454
- this.onError(err);
455
- session.send({
456
- t: "error",
457
- subId: sub.subId,
458
- code: "query-failed",
459
- message: err.message,
460
- });
461
- }
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 });
462
531
  }
463
- // A recomputation can change what a subscription read, and with
464
- // it which derived mutators apply. Snapshots carry their own.
465
- const resnapshotted = new Set(snapshots.map((snapshot) => snapshot.subId));
466
- for (const sub of bySession.get(session) ?? []) {
467
- if (session.subs.get(sub.subId) !== sub || resnapshotted.has(sub.subId))
468
- continue;
469
- const changed = this.changedMutators(sub);
470
- if (changed)
471
- mutators.push({ subId: sub.subId, mutators: changed });
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);
472
575
  }
473
- const lastMutationId = mutationIds.get(session.info.clientId) ?? 0;
474
- const mutationNews = lastMutationId > session.lastSentMutationId;
475
- if (patches.length || snapshots.length || revoked.length || mutators.length || mutationNews) {
476
- session.lastSentMutationId = Math.max(session.lastSentMutationId, lastMutationId);
477
- outgoing.push({
478
- session,
479
- message: {
480
- t: "tx",
481
- position: batch.position,
482
- lastMutationId,
483
- patches,
484
- ...(snapshots.length ? { snapshots } : {}),
485
- ...(revoked.length ? { revoked } : {}),
486
- ...(mutators.length ? { mutators } : {}),
487
- },
488
- });
576
+ catch (err) {
577
+ this.reportQueryFailure(sub, err);
489
578
  }
579
+ continue;
490
580
  }
491
- });
492
- for (const { session, message } of outgoing) {
493
- if (!session.closed)
494
- session.send(message);
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 });
495
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
+ });
496
636
  }
497
637
  /**
498
638
  * Sessions whose mutation watermark this batch may have moved.
@@ -579,15 +719,23 @@ class SyncEngine {
579
719
  * One pass over a read-set-tracking subscription, in whichever direction it
580
720
  * moved: granted, revoked, or merely changed.
581
721
  */
582
- async refreshTracked(sub, snap, patches, snapshots, revoked) {
722
+ async refreshTracked(sub, snap, patches, snapshots, revoked, counted = true) {
583
723
  let output;
584
724
  try {
585
- output = await this.evaluate(sub.def, sub.args, sub.session, snap);
725
+ output = await this.evaluate(sub.def, sub.args, sub.session, snap, counted);
586
726
  }
587
727
  catch (err) {
588
728
  if (!(0, errors_1.isForbidden)(err))
589
729
  throw err;
590
- this.rememberRefusedReads(sub, err);
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);
591
739
  if (!sub.denied) {
592
740
  sub.denied = true;
593
741
  sub.prev = (0, evaluate_1.emptyOutput)();
@@ -599,6 +747,7 @@ class SyncEngine {
599
747
  }
600
748
  return;
601
749
  }
750
+ const { output } = outcome;
602
751
  const wasDenied = sub.denied;
603
752
  sub.denied = false;
604
753
  if (wasDenied) {
@@ -667,8 +816,9 @@ class SyncEngine {
667
816
  ...(Object.keys(extraRemove).length ? { extraRemove } : {}),
668
817
  };
669
818
  }
670
- evaluate(def, args, session, snap) {
671
- this.stats.evaluations += 1;
819
+ evaluate(def, args, session, snap, counted = true) {
820
+ if (counted)
821
+ this.stats.evaluations += 1;
672
822
  return (0, evaluate_1.evaluateQuery)(def, args, session.info, snap);
673
823
  }
674
824
  toSnapshot(sub, output, reason) {
@@ -740,12 +890,27 @@ class SyncEngine {
740
890
  async executeMutation(session, mutationId, name, args) {
741
891
  const clientId = session.info.clientId;
742
892
  const committed = [];
893
+ const startedAt = Date.now();
743
894
  try {
744
895
  const def = this.opts.mutators.get(name);
896
+ const ownWrites = this.ackWithState ? this.opts.source.ownWrites : undefined;
897
+ let written = null;
745
898
  const outcome = await this.opts.writes.withWrite(async (w) => {
746
- await w.query(`INSERT INTO nowity.nowity_client (client_id) VALUES ($1) ON CONFLICT DO NOTHING`, [clientId]);
747
- const { rows } = await w.query(`SELECT last_mutation_id::text AS last, session_token FROM nowity.nowity_client
748
- WHERE client_id = $1 FOR UPDATE`, [clientId]);
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)]);
749
914
  const last = Number(rows[0].last);
750
915
  const owner = rows[0].session_token;
751
916
  // Another connection has claimed this id since. Numbering is per
@@ -761,7 +926,7 @@ class SyncEngine {
761
926
  // Idempotency: a mutation resent after a reconnect must not be
762
927
  // applied twice.
763
928
  if (mutationId <= last)
764
- return { ok: true, lastMutationId: last };
929
+ return { ok: true, lastMutationId: last, replayed: true };
765
930
  if (mutationId !== last + 1) {
766
931
  // The one place a client id shared by two connections is
767
932
  // caught for certain. `openSession` reports the collision
@@ -775,20 +940,36 @@ class SyncEngine {
775
940
  `id — mutation numbering is per client, and each connection ` +
776
941
  `needs an id of its own.`);
777
942
  }
778
- // Stamp the transaction so the capture trigger can attribute the
779
- // resulting change events to this client and mutation.
780
- await w.query(`SELECT set_config('nowity.client_id', $1, true),
781
- set_config('nowity.mutation_id', $2, true)`, [clientId, String(mutationId)]);
782
943
  const value = await def.server(args, {
783
944
  db: w,
784
945
  session: session.info,
785
946
  mutationId,
786
947
  afterCommit: (fn) => committed.push(fn),
787
948
  });
788
- await w.query(`UPDATE nowity.nowity_client SET last_mutation_id = $2, updated_at = now()
789
- WHERE client_id = $1`, [clientId, mutationId]);
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
+ }
790
969
  return { ok: true, lastMutationId: mutationId, value };
791
970
  });
971
+ // A replay committed nothing; a commit time would be fiction.
972
+ const committedAt = outcome.replayed ? undefined : Date.now();
792
973
  for (const fn of committed) {
793
974
  try {
794
975
  fn();
@@ -797,7 +978,13 @@ class SyncEngine {
797
978
  this.onError(err);
798
979
  }
799
980
  }
800
- return outcome;
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
+ }
987
+ return { ...rest, startedAt, ...(committedAt !== undefined ? { committedAt } : {}) };
801
988
  }
802
989
  catch (err) {
803
990
  // A refused mutation is a normal outcome of the write path, not an
@@ -811,7 +998,7 @@ class SyncEngine {
811
998
  // resend into an acknowledged no-op, which is the very write loss
812
999
  // this check exists to prevent.
813
1000
  if (err instanceof ClientIdTaken) {
814
- return { ok: false, error: err.message, lastMutationId: mutationId - 1 };
1001
+ return { ok: false, error: err.message, lastMutationId: mutationId - 1, startedAt };
815
1002
  }
816
1003
  // The write is rolled back, but the mutation id is burned in its own
817
1004
  // transaction. Otherwise the client would keep a rejected mutation in
@@ -829,9 +1016,125 @@ class SyncEngine {
829
1016
  ok: false,
830
1017
  error: err.message,
831
1018
  lastMutationId: mutationId,
1019
+ startedAt,
832
1020
  };
833
1021
  }
834
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
+ }
835
1138
  // ------------------------------------------------------------------ epoch store
836
1139
  /**
837
1140
  * Move a scope's epoch on, once per change rather than once per reader.
@@ -910,3 +1213,28 @@ function sameIds(a, b) {
910
1213
  }
911
1214
  return true;
912
1215
  }
1216
+ /**
1217
+ * The server's side of one push, for a connection that gets timing. `sentAt`
1218
+ * is stamped by the socket as the message leaves.
1219
+ */
1220
+ function txTiming(batch, session, readAt, fanOutAt) {
1221
+ let writtenAt;
1222
+ for (const event of batch.events) {
1223
+ if (event.writtenAt === undefined || event.clientId !== session.info.clientId)
1224
+ continue;
1225
+ if (writtenAt === undefined || event.writtenAt < writtenAt)
1226
+ writtenAt = event.writtenAt;
1227
+ }
1228
+ return { ...(writtenAt !== undefined ? { writtenAt } : {}), readAt, fanOutAt, sentAt: fanOutAt };
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
+ }