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,28 +1,57 @@
1
1
  "use strict";
2
- /**
3
- * What a browser's Nowity client did, for a developer to look at — the Network
4
- * tab of the socket.
5
- *
6
- * Off unless asked for (`devtools` option or {@link NowityClient.enableDevtools}):
7
- * a client without a recorder does not measure, serialise or allocate anything
8
- * for it. With one, every subscribe, mutation and connection event becomes a
9
- * record in a ring buffer of the last `limit` entries, kept only in this page's
10
- * memory. Nothing here is sent anywhere.
11
- *
12
- * Arguments are masked on the way in, not on the way out: a record never holds a
13
- * value the allowlist did not let through, so neither the panel nor an export can
14
- * leak what the recorder never kept. Payloads (rows, mutation results) are not
15
- * kept at all — only their size.
16
- *
17
- * Times are `performance.now()` — milliseconds since the page's navigation
18
- * started — so the summary reads as the page's own startup: when the socket
19
- * opened, when the server welcomed it, when the first data arrived.
20
- */
21
2
  Object.defineProperty(exports, "__esModule", { value: true });
22
3
  exports.NowityDevtools = exports.MASKED = exports.DEFAULT_ALLOWED_KEYS = exports.UPDATE_LIMIT = exports.DEFAULT_LIMIT = void 0;
4
+ exports.mutationPhases = mutationPhases;
23
5
  exports.maskArgs = maskArgs;
24
6
  exports.byteSize = byteSize;
25
7
  exports.jsonBytes = jsonBytes;
8
+ /** Records waiting for the data that includes them, at most. */
9
+ const AWAITING_DATA_LIMIT = 100;
10
+ /**
11
+ * How long after its answer a mutation still waits for its data. A mutation
12
+ * that wrote nothing tracked gets no push of its own, and without a limit the
13
+ * next unrelated one — whose `lastMutationId` covers it too — would be shown as
14
+ * its push.
15
+ */
16
+ const AWAITING_DATA_MS = 10000;
17
+ /**
18
+ * The steps of one mutation on one axis, the server's clock: sent → received →
19
+ * started → committed → answered, then written → read → fan-out → pushed →
20
+ * data. A client time is converted with the offset the record was stamped
21
+ * with, so a later change of the estimate does not tear one record apart.
22
+ * Sorted by time; empty before the clock is synced. Pure, for tests and panel.
23
+ */
24
+ function mutationPhases(record) {
25
+ if (record.type !== "mutation" || record.serverTs === null)
26
+ return [];
27
+ const offset = record.serverTs - record.ts;
28
+ const sent = record.serverTs;
29
+ const uncertainty = record.uncertaintyMs;
30
+ const out = [];
31
+ const client = (name, ts) => {
32
+ if (ts === null || ts === undefined)
33
+ return;
34
+ out.push({ name, clock: "client", serverTs: ts + offset, offsetMs: round(ts + offset - sent), uncertaintyMs: uncertainty });
35
+ };
36
+ const server = (name, ts, clock = "server") => {
37
+ if (ts === undefined || !Number.isFinite(ts))
38
+ return;
39
+ out.push({ name, clock, serverTs: ts, offsetMs: round(ts - sent), uncertaintyMs: null });
40
+ };
41
+ client("sent", record.ts);
42
+ const timing = record.meta.server;
43
+ server("received", timing?.receivedAt);
44
+ server("started", timing?.startedAt);
45
+ server("committed", timing?.committedAt);
46
+ client("answered", record.durationMs === null ? null : record.ts + record.durationMs);
47
+ const push = record.meta.push;
48
+ server("written", push?.writtenAt, "database");
49
+ server("read", push?.readAt);
50
+ server("fanOut", push?.fanOutAt);
51
+ server("pushed", push?.sentAt);
52
+ client("data", record.meta.dataAt);
53
+ return out.sort((a, b) => a.serverTs - b.serverTs);
54
+ }
26
55
  exports.DEFAULT_LIMIT = 500;
27
56
  /** Updates kept per subscription; the count goes on. */
28
57
  exports.UPDATE_LIMIT = 50;
@@ -158,6 +187,8 @@ class NowityDevtools {
158
187
  /** Re-sent subscribes waiting for their snapshot: subId → when. */
159
188
  this.resubscribedAt = new Map();
160
189
  this.mutations = new Map();
190
+ /** Answered mutations whose data has not arrived yet. */
191
+ this.awaitingData = new Map();
161
192
  this.connection = 0;
162
193
  this.connectAt = null;
163
194
  this.openedAt = null;
@@ -174,6 +205,13 @@ class NowityDevtools {
174
205
  this.opts = opts;
175
206
  this.limit = Math.max(1, opts.limit ?? exports.DEFAULT_LIMIT);
176
207
  this.now = opts.now ?? defaultNow;
208
+ this.clock = opts.clock ?? null;
209
+ // Records made before the first sample get their server time with it.
210
+ this.stopClock = this.clock ? this.clock.subscribe(() => this.backfill()) : null;
211
+ }
212
+ /** Stop following the clock. The records stay. */
213
+ dispose() {
214
+ this.stopClock?.();
177
215
  }
178
216
  // ------------------------------------------------------------------- reading
179
217
  /** Records, oldest first. A new array whenever {@link version} moves. */
@@ -197,6 +235,7 @@ class NowityDevtools {
197
235
  openSubscriptions: open,
198
236
  pendingSubscriptions: pending,
199
237
  pendingMutations: this.mutations.size,
238
+ clock: this.clock ? this.clock.state() : null,
200
239
  };
201
240
  }
202
241
  /** Listen for changes; batched to one call per microtask. Returns the unsubscribe. */
@@ -211,6 +250,7 @@ class NowityDevtools {
211
250
  this.list = [];
212
251
  this.subs.clear();
213
252
  this.mutations.clear();
253
+ this.awaitingData.clear();
214
254
  this.resubscribedAt.clear();
215
255
  this.changed();
216
256
  }
@@ -290,7 +330,7 @@ class NowityDevtools {
290
330
  const meta = { subId, args: this.mask(query, args), updateCount: 0, updateBytes: 0, updates: [] };
291
331
  if (hydrated)
292
332
  meta.hydrated = true;
293
- const record = { id: 0, type: "subscribe", name: query, ts, durationMs: null, bytes: null, status: "pending", meta };
333
+ const record = { id: 0, type: "subscribe", name: query, ts, serverTs: null, uncertaintyMs: null, durationMs: null, bytes: null, status: "pending", meta };
294
334
  this.subs.set(subId, record);
295
335
  this.add(record);
296
336
  }
@@ -365,7 +405,7 @@ class NowityDevtools {
365
405
  const meta = { mutationId, args: this.mask(name, args) };
366
406
  if (optimisticMs !== null)
367
407
  meta.optimisticMs = round(optimisticMs);
368
- const record = { id: 0, type: "mutation", name, ts: this.now(), durationMs: null, bytes, status: "pending", meta };
408
+ const record = { id: 0, type: "mutation", name, ts: this.now(), serverTs: null, uncertaintyMs: null, durationMs: null, bytes, status: "pending", meta };
369
409
  this.mutations.set(mutationId, record);
370
410
  this.add(record);
371
411
  }
@@ -376,7 +416,7 @@ class NowityDevtools {
376
416
  record.meta.resent = (record.meta.resent ?? 0) + 1;
377
417
  this.changed();
378
418
  }
379
- onMutationResult(mutationId, ok, error) {
419
+ onMutationResult(mutationId, ok, error, timing) {
380
420
  const record = this.mutations.get(mutationId);
381
421
  if (!record)
382
422
  return;
@@ -385,8 +425,50 @@ class NowityDevtools {
385
425
  record.status = ok ? "ok" : "rejected";
386
426
  if (!ok && error)
387
427
  record.meta.code = shorten(error);
428
+ if (timing)
429
+ record.meta.server = { ...timing };
430
+ if (ok && record.meta.dataAt === undefined && record.meta.resent === undefined) {
431
+ this.awaitingData.set(mutationId, record);
432
+ if (this.awaitingData.size > AWAITING_DATA_LIMIT) {
433
+ const oldest = this.awaitingData.keys().next().value;
434
+ this.awaitingData.delete(oldest);
435
+ }
436
+ }
388
437
  this.changed();
389
438
  }
439
+ /**
440
+ * Data arrived that includes every mutation up to `lastMutationId` — the
441
+ * first such data is where a mutation's round ends. `timing` is the
442
+ * server's side of it, when the server sends timing.
443
+ */
444
+ onData(lastMutationId, timing) {
445
+ let touched = false;
446
+ const ts = round(this.now());
447
+ const reach = (record) => {
448
+ record.meta.dataAt = ts;
449
+ if (timing)
450
+ record.meta.push = { ...timing };
451
+ touched = true;
452
+ };
453
+ for (const [mutationId, record] of this.awaitingData) {
454
+ const answeredAt = record.ts + (record.durationMs ?? 0);
455
+ if (ts - answeredAt > AWAITING_DATA_MS) {
456
+ this.awaitingData.delete(mutationId);
457
+ continue;
458
+ }
459
+ if (mutationId > lastMutationId)
460
+ continue;
461
+ this.awaitingData.delete(mutationId);
462
+ reach(record);
463
+ }
464
+ // The data may overtake the answer; the answer then finds it there.
465
+ for (const [mutationId, record] of this.mutations) {
466
+ if (mutationId <= lastMutationId && record.meta.dataAt === undefined)
467
+ reach(record);
468
+ }
469
+ if (touched)
470
+ this.changed();
471
+ }
390
472
  /** Acknowledged by data after a reconnect, its own result lost with the old socket. */
391
473
  onMutationSettled(mutationId) {
392
474
  this.onMutationResult(mutationId, true, undefined);
@@ -396,6 +478,7 @@ class NowityDevtools {
396
478
  if (!record)
397
479
  return;
398
480
  this.mutations.delete(mutationId);
481
+ this.awaitingData.delete(mutationId);
399
482
  record.status = "lost";
400
483
  this.changed();
401
484
  }
@@ -409,6 +492,9 @@ class NowityDevtools {
409
492
  }
410
493
  }
411
494
  update(record, update) {
495
+ const serverTs = this.clock?.toServerTime(update.ts);
496
+ if (serverTs !== null && serverTs !== undefined)
497
+ update.serverTs = serverTs;
412
498
  const meta = record.meta;
413
499
  meta.updateCount = (meta.updateCount ?? 0) + 1;
414
500
  meta.updateBytes = (meta.updateBytes ?? 0) + (update.bytes ?? 0);
@@ -421,11 +507,37 @@ class NowityDevtools {
421
507
  add(fields) {
422
508
  const record = fields;
423
509
  record.id = ++this.seq;
510
+ this.stamp(record);
424
511
  this.list.push(record);
425
512
  if (this.list.length > this.limit)
426
513
  this.list.splice(0, this.list.length - this.limit);
427
514
  this.changed();
428
515
  }
516
+ /** `serverTs` / `uncertaintyMs` from the clock as it is now. */
517
+ stamp(record) {
518
+ const serverTs = this.clock?.toServerTime(record.ts) ?? null;
519
+ record.serverTs = serverTs;
520
+ record.uncertaintyMs = serverTs === null ? null : round(this.clock.uncertaintyMs ?? 0);
521
+ }
522
+ /** Give records from before the first clock sample their server time. */
523
+ backfill() {
524
+ const clock = this.clock;
525
+ if (!clock?.synced)
526
+ return;
527
+ for (const record of this.list) {
528
+ if (record.serverTs === null)
529
+ this.stamp(record);
530
+ for (const update of record.meta.updates ?? []) {
531
+ if (update.serverTs !== undefined)
532
+ continue;
533
+ const serverTs = clock.toServerTime(update.ts);
534
+ if (serverTs !== null)
535
+ update.serverTs = serverTs;
536
+ }
537
+ }
538
+ // The summary shows the clock, so a new sample is a change either way.
539
+ this.changed();
540
+ }
429
541
  changed() {
430
542
  this.rev += 1;
431
543
  // A record changed in place still has to look new to a reader comparing
@@ -2,6 +2,7 @@ import { observable } from "mobx";
2
2
  import { type DerivedMutator } from "../core/derived";
3
3
  import type { HydrationPayload, ServerMessage, ServerWelcome } from "../core/protocol";
4
4
  import type { EntityId } from "../core/types";
5
+ import { ServerClock, type ServerClockOptions } from "./clock";
5
6
  import { NowityDevtools, type DevtoolsOptions } from "./devtools";
6
7
  import { LiveQuery, type QueryDescriptor } from "./live-query";
7
8
  import { type LocalTx } from "./overlay";
@@ -146,7 +147,24 @@ export interface NowityClientOptions {
146
147
  * switches it on later.
147
148
  */
148
149
  devtools?: boolean | DevtoolsOptions;
150
+ /**
151
+ * Keep an estimate of the server's clock ({@link NowityClient.clock}).
152
+ *
153
+ * On by default: the welcome is the first sample, then a short burst of
154
+ * pings, then one every `intervalMs` (30 s) — a few dozen bytes. `false`
155
+ * turns the pings off; a server older than the clock sync gets none either
156
+ * way, and the clock then simply stays unsynced.
157
+ */
158
+ clock?: false | ClockSyncOptions;
149
159
  }
160
+ export interface ClockSyncOptions extends ServerClockOptions {
161
+ /** Between two pings once synced. Default 30 s. */
162
+ intervalMs?: number;
163
+ /** Pings right after each welcome, one after another. Default 3. */
164
+ burst?: number;
165
+ }
166
+ export declare const DEFAULT_CLOCK_INTERVAL_MS = 30000;
167
+ export declare const DEFAULT_CLOCK_BURST = 3;
150
168
  export type ConnectionStatus = "idle" | "connecting" | "connected" | "disconnected";
151
169
  /**
152
170
  * The client half of Nowity: a MobX object graph kept in sync with Postgres.
@@ -233,6 +251,20 @@ export declare class NowityClient {
233
251
  private context;
234
252
  /** See {@link enableDevtools}. `null` = nothing is measured. */
235
253
  private recorder;
254
+ /**
255
+ * The server's clock as this page estimates it: `offsetMs`, `rttMs`,
256
+ * `sampleCount`, `syncedAt` and `toServerTime(performance.now())`. Unsynced
257
+ * (`null`s) until the first welcome of a server that supports it.
258
+ */
259
+ readonly clock: ServerClock;
260
+ private readonly clockSync;
261
+ /** When the current hello left, on {@link clock}'s clock. */
262
+ private helloSentAt;
263
+ /** The ping waiting for its pong: id and when it left. One at a time. */
264
+ private ping;
265
+ private pingSeq;
266
+ private burstLeft;
267
+ private pingTimer;
236
268
  constructor(opts: NowityClientOptions);
237
269
  /**
238
270
  * Start recording subscribes, mutations and connection events for a
@@ -266,6 +298,12 @@ export declare class NowityClient {
266
298
  */
267
299
  setContext(context: Record<string, unknown> | null): void;
268
300
  private handleClose;
301
+ /** After a welcome: a burst of pings one after another, then one per interval. */
302
+ private startClockSync;
303
+ private stopClockSync;
304
+ private sendPing;
305
+ private schedulePing;
306
+ private handlePong;
269
307
  private send;
270
308
  /**
271
309
  * Forget every unconfirmed mutation: the connection they were bound to is
@@ -1 +1 @@
1
- {"version":3,"file":"nowity-client.d.ts","sourceRoot":"","sources":["../../src/client/nowity-client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAU,UAAU,EAAqD,MAAM,MAAM,CAAC;AAC7F,OAAO,EAIH,KAAK,cAAc,EACtB,MAAM,iBAAiB,CAAC;AACzB,OAAO,KAAK,EAER,gBAAgB,EAGhB,aAAa,EAEb,aAAa,EAIhB,MAAM,kBAAkB,CAAC;AAE1B,OAAO,KAAK,EAAE,QAAQ,EAAO,MAAM,eAAe,CAAC;AAEnD,OAAO,EAAE,cAAc,EAAuB,KAAK,eAAe,EAAE,MAAM,YAAY,CAAC;AACvF,OAAO,EACH,SAAS,EAET,KAAK,eAAe,EAEvB,MAAM,cAAc,CAAC;AACtB,OAAO,EAAW,KAAK,OAAO,EAAE,MAAM,WAAW,CAAC;AAClD,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAE7C,MAAM,WAAW,kBAAkB;IAC/B,MAAM,EAAE,MAAM,CAAC;IACf,gEAAgE;IAChE,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,mEAAmE;IACnE,UAAU,CAAC,EAAE,MAAM,CAAC;CACvB;AAED,MAAM,WAAW,gBAAgB;IAC7B,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,SAAS,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,kBAAkB,CAAC,CAAC;CAClD;AAED,MAAM,MAAM,gBAAgB,CAAC,CAAC,GAAG,GAAG,IAAI,oBAAoB,CAAC,CAAC,CAAC,GAAG,qBAAqB,CAAC;AAExF,MAAM,WAAW,oBAAoB,CAAC,CAAC,GAAG,GAAG;IACzC,IAAI,EAAE,MAAM,CAAC;IACb;;;;OA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AAM,EAAE,MAAM,GAAG,UAAU,CAAC,OAAO,UAAU,CAAC,GAAG,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAC;IASxE,uEAAuE;IACvE,MAAM,CAAC,CAAC,GAAG,GAAG,EAAE,UAAU,EAAE,MAAM,EAAE,EAAE,EAAE,QAAQ,GAAG,CAAC,GAAG,SAAS;IAIhE,uEAAuE;IACvE,OAAO,CAAC,MAAM,CAkCX;IAEH,+EAA+E;IAC/E,OAAO,CAAC,SAAS;IAiBjB,OAAO,CAAC,WAAW;IAkBnB,OAAO,CAAC,cAAc;IAmBtB,OAAO,CAAC,eAAe;IAiBvB,wFAAwF;IACxF,QAAQ,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,GAAG,SAAS;IAI5C,OAAO,CAAC,SAAS;IASjB,OAAO,CAAC,YAAY;IAMpB,8EAA8E;IAC9E,IAAI,oBAAoB,IAAI,MAAM,CAEjC;IAED,IAAI,WAAW,IAAI,OAAO,CAEzB;IAED,0EAA0E;IAC1E,aAAa,CAAC,OAAO,EAAE,aAAa,GAAG,IAAI;CAG9C;AAED;;;;;GAKG;AACH,wBAAgB,eAAe,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,GAAG,MAAM,CAEpE"}
@@ -1,10 +1,11 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.NowityClient = exports.ConnectionLostError = exports.StrictOptimisticError = void 0;
3
+ exports.NowityClient = exports.DEFAULT_CLOCK_BURST = exports.DEFAULT_CLOCK_INTERVAL_MS = exports.ConnectionLostError = exports.StrictOptimisticError = void 0;
4
4
  exports.subscriptionKey = subscriptionKey;
5
5
  const mobx_1 = require("mobx");
6
6
  const derived_1 = require("../core/derived");
7
7
  const protocol_1 = require("../core/protocol");
8
+ const clock_1 = require("./clock");
8
9
  const confirmed_store_1 = require("./confirmed-store");
9
10
  const devtools_1 = require("./devtools");
10
11
  const live_query_1 = require("./live-query");
@@ -35,6 +36,8 @@ class ConnectionLostError extends Error {
35
36
  }
36
37
  }
37
38
  exports.ConnectionLostError = ConnectionLostError;
39
+ exports.DEFAULT_CLOCK_INTERVAL_MS = 30000;
40
+ exports.DEFAULT_CLOCK_BURST = 3;
38
41
  /** Shared empty result, so a query with no local inserts allocates nothing. */
39
42
  const EMPTY_IDS = [];
40
43
  /**
@@ -117,6 +120,13 @@ class NowityClient {
117
120
  this.context = null;
118
121
  /** See {@link enableDevtools}. `null` = nothing is measured. */
119
122
  this.recorder = null;
123
+ /** When the current hello left, on {@link clock}'s clock. */
124
+ this.helloSentAt = null;
125
+ /** The ping waiting for its pong: id and when it left. One at a time. */
126
+ this.ping = null;
127
+ this.pingSeq = 0;
128
+ this.burstLeft = 0;
129
+ this.pingTimer = null;
120
130
  /** Rebuild the overlay from confirmed state plus pending mutations. */
121
131
  this.rebase = (0, mobx_1.action)(() => {
122
132
  this.pendingBox.set(this.pending.length > 0);
@@ -162,6 +172,15 @@ class NowityClient {
162
172
  this.context = opts.context ?? null;
163
173
  this.strictOptimistic = opts.strictOptimistic ?? strictFromEnv();
164
174
  this.optimisticOn = opts.optimistic ?? true;
175
+ const clockOpts = opts.clock === false ? {} : (opts.clock ?? {});
176
+ this.clock = new clock_1.ServerClock(clockOpts);
177
+ this.clockSync =
178
+ opts.clock === false
179
+ ? null
180
+ : {
181
+ intervalMs: clockOpts.intervalMs ?? exports.DEFAULT_CLOCK_INTERVAL_MS,
182
+ burst: Math.max(1, clockOpts.burst ?? exports.DEFAULT_CLOCK_BURST),
183
+ };
165
184
  for (const mutator of opts.mutators ?? []) {
166
185
  if (mutator.local === undefined && !mutator.pessimistic?.trim()) {
167
186
  throw new Error(`Client mutator "${mutator.name}" has neither local() nor a pessimistic reason.`);
@@ -182,11 +201,12 @@ class NowityClient {
182
201
  * subscriptions already open are not in it.
183
202
  */
184
203
  enableDevtools(options = {}) {
185
- this.recorder ?? (this.recorder = new devtools_1.NowityDevtools(options));
204
+ this.recorder ?? (this.recorder = new devtools_1.NowityDevtools({ clock: this.clock, ...options }));
186
205
  return this.recorder;
187
206
  }
188
207
  /** Stop recording and drop what was recorded. */
189
208
  disableDevtools() {
209
+ this.recorder?.dispose();
190
210
  this.recorder = null;
191
211
  }
192
212
  /** The running recorder, or `null` when devtools are off. */
@@ -220,6 +240,7 @@ class NowityClient {
220
240
  clearTimeout(this.reconnectTimer);
221
241
  this.reconnectTimer = null;
222
242
  this.opts.transport.close();
243
+ this.stopClockSync();
223
244
  (0, mobx_1.runInAction)(() => this.status.set("idle"));
224
245
  }
225
246
  /** Drop the connection as if the network died. For tests and for retry UX. */
@@ -232,6 +253,7 @@ class NowityClient {
232
253
  this.reconnectAttempt = 0;
233
254
  this.recorder?.onOpen();
234
255
  (0, mobx_1.runInAction)(() => this.status.set("connected"));
256
+ this.helloSentAt = this.clock.now();
235
257
  // The context rides on the hello: the server forgets it with the old
236
258
  // socket, and a new socket has to be told before it is recorded.
237
259
  this.send({
@@ -263,6 +285,7 @@ class NowityClient {
263
285
  this.recorder?.onClose(this.intentionalClose);
264
286
  this.connected = false;
265
287
  this.welcomed = false;
288
+ this.stopClockSync();
266
289
  (0, mobx_1.runInAction)(() => this.status.set(this.intentionalClose ? "idle" : "disconnected"));
267
290
  if (this.opts.onDisconnect === "drop")
268
291
  this.dropPending();
@@ -287,6 +310,57 @@ class NowityClient {
287
310
  this.connect();
288
311
  }, delay);
289
312
  }
313
+ // ------------------------------------------------------------------ clock sync
314
+ /** After a welcome: a burst of pings one after another, then one per interval. */
315
+ startClockSync() {
316
+ this.stopClockSync();
317
+ if (!this.clockSync)
318
+ return;
319
+ this.burstLeft = this.clockSync.burst;
320
+ this.sendPing();
321
+ }
322
+ stopClockSync() {
323
+ if (this.pingTimer)
324
+ clearTimeout(this.pingTimer);
325
+ this.pingTimer = null;
326
+ this.ping = null;
327
+ this.burstLeft = 0;
328
+ this.helloSentAt = null;
329
+ }
330
+ sendPing() {
331
+ if (!this.clockSync || !this.welcomed)
332
+ return;
333
+ if (this.pingTimer)
334
+ clearTimeout(this.pingTimer);
335
+ this.pingTimer = null;
336
+ // A ping whose pong never came (an older server, a lost frame) is
337
+ // given up: one outstanding at a time keeps the bookkeeping trivial.
338
+ const ping = { id: ++this.pingSeq, t0: this.clock.now() };
339
+ this.ping = ping;
340
+ this.opts.transport.send({ t: "ping", id: ping.id, t0: ping.t0 });
341
+ this.schedulePing(this.clockSync.intervalMs);
342
+ }
343
+ schedulePing(delayMs) {
344
+ if (this.pingTimer)
345
+ clearTimeout(this.pingTimer);
346
+ this.pingTimer = setTimeout(() => {
347
+ this.pingTimer = null;
348
+ this.sendPing();
349
+ }, delayMs);
350
+ // The clock must never hold a process open.
351
+ this.pingTimer.unref?.();
352
+ }
353
+ handlePong(message, receivedAt) {
354
+ const ping = this.ping;
355
+ if (!ping || ping.id !== message.id)
356
+ return;
357
+ this.ping = null;
358
+ this.clock.addSample(ping.t0, message.t1, message.t2, receivedAt);
359
+ if (this.burstLeft > 0)
360
+ this.burstLeft -= 1;
361
+ if (this.burstLeft > 0)
362
+ this.sendPing();
363
+ }
290
364
  send(message) {
291
365
  this.opts.transport.send(message);
292
366
  if (this.recorder && message.t === "hello")
@@ -464,13 +538,27 @@ class NowityClient {
464
538
  }
465
539
  // -------------------------------------------------------------------- messages
466
540
  handleMessage(message, raw) {
541
+ // First: the clock sample ends when the message arrives, not when it is applied.
542
+ const receivedAt = this.clock.now();
467
543
  try {
544
+ if (message.t === "pong") {
545
+ this.handlePong(message, receivedAt);
546
+ return;
547
+ }
468
548
  this.opts.onServerMessage?.(message);
549
+ if (message.t === "welcome" && message.clock && this.helloSentAt !== null) {
550
+ // The welcome is the first sample. A reconnect may follow a
551
+ // suspend, after which the old relation of the clocks proves
552
+ // nothing — the new samples replace whatever contradicts them.
553
+ this.clock.addSample(this.helloSentAt, message.clock.receivedAt, message.clock.sentAt, receivedAt);
554
+ }
469
555
  if (this.recorder)
470
556
  this.record(this.recorder, message, raw);
471
557
  switch (message.t) {
472
558
  case "welcome":
473
559
  this.handleWelcome(message);
560
+ if (message.clock)
561
+ this.startClockSync();
474
562
  break;
475
563
  case "snapshot":
476
564
  this.handleSnapshotMessage(message);
@@ -524,6 +612,7 @@ class NowityClient {
524
612
  break;
525
613
  case "snapshot":
526
614
  recorder.onSnapshot(message.subId, size(), message.reason === "permission-change");
615
+ recorder.onData(message.lastMutationId, undefined);
527
616
  break;
528
617
  case "tx":
529
618
  for (const revoked of message.revoked ?? []) {
@@ -534,9 +623,10 @@ class NowityClient {
534
623
  }
535
624
  for (const patch of message.patches)
536
625
  recorder.onPatch(patch.subId, (0, devtools_1.jsonBytes)(patch));
626
+ recorder.onData(message.lastMutationId, message.timing);
537
627
  break;
538
628
  case "mutation-result":
539
- recorder.onMutationResult(message.mutationId, message.ok, message.error);
629
+ recorder.onMutationResult(message.mutationId, message.ok, message.error, message.timing);
540
630
  break;
541
631
  case "error":
542
632
  if (message.subId)
package/dist/client.d.ts CHANGED
@@ -40,6 +40,9 @@ export type { QueryEntry, QueryError, QuerySource } from "./client/query-source"
40
40
  export { ConnectionLostError, StrictOptimisticError, type ClientMutatorDef, type OptimisticMutatorDef, type PessimisticMutatorDef, } from "./client/nowity-client";
41
41
  export type { Draft, EntityTx, LocalEntities, LocalTx } from "./client/overlay";
42
42
  export { WebSocketTransport, type WebSocketTransportOptions } from "./client/ws-transport";
43
+ export { ServerClock, clockSample, type ClockSample, type ClockState, type ServerClockOptions, } from "./client/clock";
44
+ export type { ClockSyncOptions } from "./client/nowity-client";
45
+ export type { MutationTiming, TxTiming } from "./core/protocol";
43
46
  /**
44
47
  * The recorder behind `client.enableDevtools()`; the panel that shows it is a
45
48
  * separate entry, `nowity/devtools`, loaded only where it is wanted.
@@ -1 +1 @@
1
- {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAGH,OAAO,EACH,GAAG,EACH,QAAQ,EACR,KAAK,EACL,IAAI,EAC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.
22
22
  */
23
23
  Object.defineProperty(exports, "__esModule", { value: true });
24
- exports.NowityClientToken = exports.configureNowityClient = exports.WebSocketTransport = exports.StrictOptimisticError = exports.ConnectionLostError = exports.currentConnection = exports.activeConnection = exports.NowityConnection = exports.Restricted = exports.useQuerySource = exports.SourceScope = exports.NowityProvider = exports.useService = exports.DEFAULT_PAGE_SIZE = exports.LiveList = exports.List = exports.GridList = exports.useList = exports.useQuerySuspense = exports.observer = exports.isRejected = exports.isForbidden = exports.Rejected = exports.Forbidden = exports.buildManifest = exports.countQuery = exports.pageQuery = exports.endpointName = exports.resetContracts = exports.resolveContracts = exports.contractOf = exports.knownContracts = exports.mutation = exports.list = exports.query = exports.contract = exports.api = void 0;
24
+ exports.NowityClientToken = exports.configureNowityClient = exports.clockSample = exports.ServerClock = exports.WebSocketTransport = exports.StrictOptimisticError = exports.ConnectionLostError = exports.currentConnection = exports.activeConnection = exports.NowityConnection = exports.Restricted = exports.useQuerySource = exports.SourceScope = exports.NowityProvider = exports.useService = exports.DEFAULT_PAGE_SIZE = exports.LiveList = exports.List = exports.GridList = exports.useList = exports.useQuerySuspense = exports.observer = exports.isRejected = exports.isForbidden = exports.Rejected = exports.Forbidden = exports.buildManifest = exports.countQuery = exports.pageQuery = exports.endpointName = exports.resetContracts = exports.resolveContracts = exports.contractOf = exports.knownContracts = exports.mutation = exports.list = exports.query = exports.contract = exports.api = void 0;
25
25
  // ------------------------------------------------------------------- contracts
26
26
  var contract_1 = require("./api/contract");
27
27
  Object.defineProperty(exports, "api", { enumerable: true, get: function () { return contract_1.api; } });
@@ -83,6 +83,9 @@ Object.defineProperty(exports, "ConnectionLostError", { enumerable: true, get: f
83
83
  Object.defineProperty(exports, "StrictOptimisticError", { enumerable: true, get: function () { return nowity_client_1.StrictOptimisticError; } });
84
84
  var ws_transport_1 = require("./client/ws-transport");
85
85
  Object.defineProperty(exports, "WebSocketTransport", { enumerable: true, get: function () { return ws_transport_1.WebSocketTransport; } });
86
+ var clock_1 = require("./client/clock");
87
+ Object.defineProperty(exports, "ServerClock", { enumerable: true, get: function () { return clock_1.ServerClock; } });
88
+ Object.defineProperty(exports, "clockSample", { enumerable: true, get: function () { return clock_1.clockSample; } });
86
89
  var client_1 = require("./ironbean/client");
87
90
  Object.defineProperty(exports, "configureNowityClient", { enumerable: true, get: function () { return client_1.configureNowityClient; } });
88
91
  var tokens_1 = require("./ironbean/tokens");