nowity 1.8.0 → 1.10.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.
@@ -37,6 +37,13 @@ exports.NowitySyncServer = void 0;
37
37
  const http = __importStar(require("http"));
38
38
  const ws_1 = require("ws");
39
39
  const protocol_1 = require("../core/protocol");
40
+ /**
41
+ * Pongs a socket gets per {@link PING_WINDOW_MS}. A client sends a burst of a
42
+ * few after each welcome and one every 30 s; anything beyond is not clock sync,
43
+ * and is answered with silence rather than with work done out of turn.
44
+ */
45
+ const PINGS_PER_WINDOW = 10;
46
+ const PING_WINDOW_MS = 10000;
40
47
  /** Largest context a connection may set, serialised. It is stored per socket. */
41
48
  const MAX_CONTEXT_BYTES = 4096;
42
49
  /** WebSocket front end for {@link SyncEngine}. */
@@ -57,6 +64,12 @@ class NowitySyncServer {
57
64
  /** Pings sent since the socket last proved it is alive. */
58
65
  this.missed = new WeakMap();
59
66
  this.heartbeatTimer = null;
67
+ /** When this socket's last hello arrived, for the clock in the welcome. */
68
+ this.helloAt = new WeakMap();
69
+ /** Sockets that get timing (see {@link NowitySyncServerOptions.timing}). */
70
+ this.timed = new WeakSet();
71
+ /** Pongs sent in the current window, per socket. */
72
+ this.pings = new WeakMap();
60
73
  this.opts = opts;
61
74
  this.onError = opts.onError ?? ((err) => console.error("[nowity/ws]", err));
62
75
  }
@@ -171,7 +184,10 @@ class NowitySyncServer {
171
184
  const authenticated = new Promise((resolve) => (settleAuth = resolve));
172
185
  // Anything from the peer proves it is there, not only a pong.
173
186
  socket.on("pong", () => this.missed.set(socket, 0));
187
+ let authed = false;
174
188
  socket.on("message", (data) => {
189
+ // First, before parsing: every later step is the server's time, not the wire's.
190
+ const receivedAt = Date.now();
175
191
  this.missed.set(socket, 0);
176
192
  let message;
177
193
  try {
@@ -181,10 +197,18 @@ class NowitySyncServer {
181
197
  this.onError(err);
182
198
  return;
183
199
  }
200
+ if (message.t === "ping") {
201
+ // Answered now, not in turn: behind a slow mutation in the
202
+ // chain it would measure the mutation instead of the wire.
203
+ if (authed && typeof message.id === "number" && typeof message.t0 === "number" && this.allowPing(socket, receivedAt)) {
204
+ this.sendTo(socket, { t: "pong", id: message.id, t0: message.t0, t1: receivedAt, t2: Date.now() });
205
+ }
206
+ return;
207
+ }
184
208
  const previous = this.chains.get(socket) ?? Promise.resolve();
185
209
  const next = previous
186
210
  .then(() => authenticated)
187
- .then((auth) => (auth ? this.handleMessage(socket, auth, message) : undefined));
211
+ .then((auth) => (auth ? this.handleMessage(socket, auth, message, receivedAt) : undefined));
188
212
  this.chains.set(socket, next.catch((err) => this.onError(err)));
189
213
  });
190
214
  socket.on("close", () => {
@@ -206,11 +230,12 @@ class NowitySyncServer {
206
230
  this.onError(err);
207
231
  auth = null;
208
232
  }
233
+ authed = auth !== null;
209
234
  settleAuth(auth ?? null);
210
235
  if (!auth)
211
236
  socket.close(4401, "unauthorized");
212
237
  }
213
- async handleMessage(socket, auth, message) {
238
+ async handleMessage(socket, auth, message, receivedAt) {
214
239
  try {
215
240
  if (message.t === "hello") {
216
241
  if (message.v !== protocol_1.PROTOCOL_VERSION) {
@@ -233,7 +258,14 @@ class NowitySyncServer {
233
258
  if (existing)
234
259
  await this.opts.engine.closeSession(existing);
235
260
  const context = validContext(message.context) ? (message.context ?? null) : null;
261
+ const timing = await this.timingFor(info);
262
+ if (timing)
263
+ this.timed.add(socket);
264
+ else
265
+ this.timed.delete(socket);
266
+ this.helloAt.set(socket, receivedAt);
236
267
  const session = this.opts.engine.openSession(info, (msg) => this.sendTo(socket, msg), context);
268
+ session.timing = timing;
237
269
  this.sessions.set(socket, session);
238
270
  // The socket may have closed while the previous session was
239
271
  // being closed above. Its close handler has run already and
@@ -293,6 +325,14 @@ class NowitySyncServer {
293
325
  }
294
326
  case "mutate": {
295
327
  const outcome = await this.opts.engine.mutate(session, message.mutationId, message.name, message.args);
328
+ const timing = this.timed.has(socket)
329
+ ? {
330
+ receivedAt,
331
+ startedAt: outcome.startedAt ?? receivedAt,
332
+ ...(outcome.committedAt !== undefined ? { committedAt: outcome.committedAt } : {}),
333
+ sentAt: 0,
334
+ }
335
+ : undefined;
296
336
  this.sendTo(socket, {
297
337
  t: "mutation-result",
298
338
  mutationId: message.mutationId,
@@ -300,6 +340,7 @@ class NowitySyncServer {
300
340
  ...(outcome.error ? { error: outcome.error } : {}),
301
341
  ...(outcome.value !== undefined ? { value: outcome.value } : {}),
302
342
  lastMutationId: outcome.lastMutationId,
343
+ ...(timing ? { timing } : {}),
303
344
  });
304
345
  break;
305
346
  }
@@ -314,9 +355,47 @@ class NowitySyncServer {
314
355
  });
315
356
  }
316
357
  }
358
+ allowPing(socket, now) {
359
+ let window = this.pings.get(socket);
360
+ if (!window || now - window.since >= PING_WINDOW_MS) {
361
+ window = { since: now, count: 0 };
362
+ this.pings.set(socket, window);
363
+ }
364
+ window.count += 1;
365
+ return window.count <= PINGS_PER_WINDOW;
366
+ }
367
+ async timingFor(info) {
368
+ const timing = this.opts.timing;
369
+ if (typeof timing !== "function")
370
+ return timing === true;
371
+ try {
372
+ return (await timing(info)) === true;
373
+ }
374
+ catch (err) {
375
+ this.onError(err);
376
+ return false;
377
+ }
378
+ }
317
379
  sendTo(socket, message) {
318
380
  if (socket.readyState !== socket.OPEN)
319
381
  return;
382
+ // Stamped as late as possible: the time it leaves is what the client's
383
+ // clock sync and the panel's axis are measured against.
384
+ switch (message.t) {
385
+ case "welcome": {
386
+ const receivedAt = this.helloAt.get(socket);
387
+ if (receivedAt !== undefined)
388
+ message.clock = { receivedAt, sentAt: Date.now() };
389
+ if (this.timed.has(socket))
390
+ message.timing = true;
391
+ break;
392
+ }
393
+ case "mutation-result":
394
+ case "tx":
395
+ if (message.timing)
396
+ message.timing.sentAt = Date.now();
397
+ break;
398
+ }
320
399
  socket.send(JSON.stringify(message));
321
400
  }
322
401
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nowity",
3
- "version": "1.8.0",
3
+ "version": "1.10.0",
4
4
  "description": "Realtime object model over PostgreSQL: logical change stream, query-scoped subscriptions, MobX identity map",
5
5
  "main": "dist/index.js",
6
6
  "scripts": {
@@ -60,6 +60,10 @@
60
60
  "./client": {
61
61
  "types": "./dist/client.d.ts",
62
62
  "default": "./dist/client.js"
63
+ },
64
+ "./devtools": {
65
+ "types": "./dist/devtools.d.ts",
66
+ "default": "./dist/devtools.js"
63
67
  }
64
68
  },
65
69
  "peerDependenciesMeta": {