@rebasepro/server 0.34.1 → 0.34.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.es.js CHANGED
@@ -6331,7 +6331,8 @@ var SOCKET_OPT_IN_PARAM = "rebase_caps";
6331
6331
  var SOCKET_OPT_INS = [
6332
6332
  "heartbeat",
6333
6333
  "channel_seq",
6334
- "cancel_sql"
6334
+ "cancel_sql",
6335
+ "ping"
6335
6336
  ];
6336
6337
  /**
6337
6338
  * The query parameter naming the group a socket belongs to. A platform that
@@ -6342,6 +6343,19 @@ var SOCKET_AFFINITY_PARAM = "affinity";
6342
6343
  /** Slack on top of two heartbeat intervals before a silent socket is given up on. */
6343
6344
  var HEARTBEAT_GRACE_MS = 5e3;
6344
6345
  /**
6346
+ * How long a socket has to answer the `ping` sent when the page wakes, in ms,
6347
+ * before it is given up on. Long enough for a phone's radio to come back.
6348
+ */
6349
+ var WAKE_PROBE_TIMEOUT_MS = 1e4;
6350
+ /** The code and reason of a `close` event, read without trusting its shape. */
6351
+ function closeEventDetails(event) {
6352
+ if (typeof event !== "object" || event === null) return {};
6353
+ return {
6354
+ code: "code" in event && typeof event.code === "number" ? event.code : void 0,
6355
+ reason: "reason" in event && typeof event.reason === "string" && event.reason !== "" ? event.reason : void 0
6356
+ };
6357
+ }
6358
+ /**
6345
6359
  * `url` with the opt-ins named on it, and `affinity` when there is one.
6346
6360
  * Appended rather than rebuilt through `URL`, which would rewrite the address
6347
6361
  * the caller gave (a bare origin gains a `/`).
@@ -6544,7 +6558,16 @@ var RebaseWebSocketClient = class {
6544
6558
  serverClientId;
6545
6559
  /** When the current socket last delivered anything, heartbeats included. */
6546
6560
  lastFrameAt = 0;
6561
+ /** When the current socket opened, for the `disconnect` event. */
6562
+ socketOpenedAt = 0;
6547
6563
  livenessTimer = null;
6564
+ /** The current wake probe: when it was sent, and when it must have been answered by. */
6565
+ wakeProbe = null;
6566
+ /**
6567
+ * Why this client is about to close the current socket itself, read by its
6568
+ * close handler so the `disconnect` event names the cause.
6569
+ */
6570
+ closingFor = null;
6548
6571
  /** Give up on the current socket as though it had closed. Set per socket. */
6549
6572
  dropSocket = null;
6550
6573
  /** Whether the server agreed, in its `hello`, to `name` for this socket. */
@@ -6721,7 +6744,9 @@ var RebaseWebSocketClient = class {
6721
6744
  window.addEventListener("online", this.onlineListener);
6722
6745
  if (typeof document !== "undefined" && typeof document.addEventListener === "function") {
6723
6746
  this.visibilityListener = () => {
6724
- if (document.visibilityState === "visible") this.retryNow("Tab is visible again");
6747
+ if (document.visibilityState !== "visible") return;
6748
+ this.retryNow("Tab is visible again");
6749
+ this.probeAfterWake();
6725
6750
  };
6726
6751
  document.addEventListener("visibilitychange", this.visibilityListener);
6727
6752
  }
@@ -6923,6 +6948,8 @@ var RebaseWebSocketClient = class {
6923
6948
  this.hadConnection = true;
6924
6949
  this.isConnected = true;
6925
6950
  this.gaveUp = false;
6951
+ this.socketOpenedAt = Date.now();
6952
+ this.lastFrameAt = this.socketOpenedAt;
6926
6953
  if (!this.outageReported) this.setState("connected");
6927
6954
  this.refusedSession = null;
6928
6955
  if (this.getAuthToken && !this.isAuthenticated) {
@@ -6941,6 +6968,7 @@ var RebaseWebSocketClient = class {
6941
6968
  if (!(token && this.noteSessionRefused(token, error))) {
6942
6969
  this.connectionDebug("WebSocket connected, not signed in yet:", error?.message || error);
6943
6970
  if (token && this.ws === socket && !this.refusedSession) {
6971
+ this.closingFor = "client";
6944
6972
  socket.close(4e3, "Could not authenticate; reconnecting");
6945
6973
  return;
6946
6974
  }
@@ -6967,8 +6995,17 @@ var RebaseWebSocketClient = class {
6967
6995
  console.error("Error parsing WebSocket message:", error);
6968
6996
  }
6969
6997
  };
6970
- const onClosed = () => {
6998
+ const onClosed = (event, cause) => {
6971
6999
  this.connectionDebug("Disconnected from PostgreSQL backend");
7000
+ const now = Date.now();
7001
+ const info = {
7002
+ ...closeEventDetails(event),
7003
+ cause: cause ?? this.closingFor ?? "server",
7004
+ openForMs: this.socketOpenedAt ? now - this.socketOpenedAt : 0,
7005
+ silentForMs: this.lastFrameAt ? now - this.lastFrameAt : 0
7006
+ };
7007
+ this.closingFor = null;
7008
+ this.socketOpenedAt = 0;
6972
7009
  this.stopLivenessWatch();
6973
7010
  this.forgetServerOptIns();
6974
7011
  if (this.ws === socket) this.ws = null;
@@ -6976,7 +7013,7 @@ var RebaseWebSocketClient = class {
6976
7013
  this.isAuthenticated = false;
6977
7014
  this.authPromise = null;
6978
7015
  this.suspendSubscribeWatchdogs();
6979
- this.emit("disconnect");
7016
+ this.emit("disconnect", info);
6980
7017
  for (const [reqId, request] of this.pendingRequests.entries()) {
6981
7018
  this.pendingRequests.delete(reqId);
6982
7019
  if (reqId.startsWith("auth_")) request.reject(/* @__PURE__ */ new Error("Connection closed during authentication"));
@@ -6986,16 +7023,16 @@ var RebaseWebSocketClient = class {
6986
7023
  this.attemptReconnect();
6987
7024
  };
6988
7025
  this.ws.onclose = onClosed;
6989
- this.dropSocket = () => {
7026
+ this.dropSocket = (cause) => {
6990
7027
  if (this.ws !== socket) return;
6991
7028
  socket.onclose = null;
6992
7029
  socket.onmessage = null;
6993
7030
  socket.onerror = null;
6994
7031
  socket.onopen = null;
6995
7032
  try {
6996
- socket.close();
7033
+ socket.close(4003, cause === "probe" ? "No answer to a ping after waking" : "Two heartbeats missed");
6997
7034
  } catch {}
6998
- onClosed();
7035
+ onClosed(void 0, cause);
6999
7036
  };
7000
7037
  this.ws.onerror = (error) => {
7001
7038
  console.error("WebSocket error:", error);
@@ -7018,25 +7055,72 @@ var RebaseWebSocketClient = class {
7018
7055
  /**
7019
7056
  * Redial when two heartbeats in a row have not arrived. Anything the
7020
7057
  * server sends counts as a beat, so a busy socket is never judged on them.
7058
+ *
7059
+ * Never on a silence the page caused. A phone that locked, a tab the
7060
+ * browser froze or a laptop that slept runs no timers and reads no frames,
7061
+ * and on waking this interval used to fire before the frames waiting on
7062
+ * the socket were read: it saw a minute of silence and tore down a socket
7063
+ * that was fine, and every app on it saw a disconnect. A tick that comes
7064
+ * far later than it was due is a wake: the socket is asked (`ping`, which
7065
+ * a server that offers it answers at once) and given
7066
+ * {@link WAKE_PROBE_TIMEOUT_MS} to say anything — or, from a server that
7067
+ * does not offer `ping`, a whole deadline from now.
7021
7068
  */
7022
7069
  watchLiveness(heartbeatMs) {
7023
7070
  this.stopLivenessWatch();
7024
7071
  const deadline = 2 * heartbeatMs + Math.min(HEARTBEAT_GRACE_MS, heartbeatMs);
7072
+ const period = Math.max(250, Math.floor(heartbeatMs / 2));
7025
7073
  this.lastFrameAt = Date.now();
7074
+ let lastTick = Date.now();
7026
7075
  this.livenessTimer = setInterval(() => {
7027
- const silentFor = Date.now() - this.lastFrameAt;
7076
+ const now = Date.now();
7077
+ const late = now - lastTick > 2 * period + 1e3;
7078
+ lastTick = now;
7079
+ if (late) {
7080
+ this.probeAfterWake();
7081
+ return;
7082
+ }
7083
+ const probe = this.wakeProbe;
7084
+ if (probe) if (this.lastFrameAt >= probe.sentAt) this.wakeProbe = null;
7085
+ else if (now > probe.deadline) {
7086
+ console.warn(`[Rebase] Realtime: no answer ${Math.round((now - probe.sentAt) / 1e3)} s after waking. Reconnecting.`);
7087
+ this.stopLivenessWatch();
7088
+ this.dropSocket?.("probe");
7089
+ return;
7090
+ } else return;
7091
+ const silentFor = now - this.lastFrameAt;
7028
7092
  if (silentFor <= deadline) return;
7029
7093
  console.warn(`[Rebase] Realtime: nothing from the server for ${Math.round(silentFor / 1e3)} s, two missed heartbeats. Reconnecting.`);
7030
7094
  this.stopLivenessWatch();
7031
- this.dropSocket?.();
7032
- }, Math.max(250, Math.floor(heartbeatMs / 2)));
7095
+ this.dropSocket?.("heartbeat");
7096
+ }, period);
7033
7097
  unref(this.livenessTimer);
7034
7098
  }
7099
+ /**
7100
+ * The page has just woken (a late liveness tick, or the tab shown again):
7101
+ * ask an open socket whether it is still there instead of judging it on
7102
+ * the silence of the sleep. Does nothing while no heartbeats are watched.
7103
+ */
7104
+ probeAfterWake() {
7105
+ if (!this.livenessTimer || !this.ws || !this.isConnected) return;
7106
+ const now = Date.now();
7107
+ if (this.wakeProbe && now <= this.wakeProbe.deadline) return;
7108
+ if (this.serverOptIns.has("ping")) try {
7109
+ this.ws.send(JSON.stringify({ type: "ping" }));
7110
+ this.wakeProbe = {
7111
+ sentAt: now,
7112
+ deadline: now + WAKE_PROBE_TIMEOUT_MS
7113
+ };
7114
+ return;
7115
+ } catch {}
7116
+ this.lastFrameAt = now;
7117
+ }
7035
7118
  stopLivenessWatch() {
7036
7119
  if (this.livenessTimer) {
7037
7120
  clearInterval(this.livenessTimer);
7038
7121
  this.livenessTimer = null;
7039
7122
  }
7123
+ this.wakeProbe = null;
7040
7124
  }
7041
7125
  forgetServerOptIns() {
7042
7126
  this.serverOptIns = /* @__PURE__ */ new Set();
@@ -10484,6 +10568,21 @@ function createRoutedRealtimeService(opts) {
10484
10568
  setClientOptIns(clientId, optIns) {
10485
10569
  for (const p of all()) p.setClientOptIns?.(clientId, optIns);
10486
10570
  },
10571
+ describeClient(clientId) {
10572
+ const described = {
10573
+ channels: [],
10574
+ framesOut: 0,
10575
+ bytesOut: 0
10576
+ };
10577
+ for (const p of all()) {
10578
+ const one = p.describeClient?.(clientId);
10579
+ if (!one) continue;
10580
+ described.channels.push(...one.channels);
10581
+ described.framesOut += one.framesOut;
10582
+ described.bytesOut += one.bytesOut;
10583
+ }
10584
+ return described;
10585
+ },
10487
10586
  async rescopeClient(clientId, authContext) {
10488
10587
  await Promise.all(all().map((p) => p.rescopeClient?.(clientId, authContext)));
10489
10588
  },
@@ -10546,6 +10645,7 @@ function createRoutedRealtimeService(opts) {
10546
10645
  const source = p.counts?.();
10547
10646
  if (!source) continue;
10548
10647
  counts.sockets = Math.max(counts.sockets, source.sockets);
10648
+ counts.socketTotals ??= source.socketTotals;
10549
10649
  counts.channels += source.channels;
10550
10650
  counts.busFramesSkipped += source.busFramesSkipped;
10551
10651
  for (const [kind, frames] of Object.entries(source.busFramesPublished)) counts.busFramesPublished[kind] = (counts.busFramesPublished[kind] ?? 0) + frames;
@@ -35431,6 +35531,14 @@ var REALTIME_SOCKETS_METRIC = "rebase_realtime_sockets";
35431
35531
  var REALTIME_CHANNELS_METRIC = "rebase_realtime_channels";
35432
35532
  var REALTIME_BUS_PUBLISHED_METRIC = "rebase_realtime_bus_frames_published_total";
35433
35533
  var REALTIME_BUS_SKIPPED_METRIC = "rebase_realtime_bus_frames_skipped_total";
35534
+ var REALTIME_OPENS_METRIC = "rebase_realtime_socket_opens_total";
35535
+ var REALTIME_CLOSES_METRIC = "rebase_realtime_socket_closes_total";
35536
+ var REALTIME_CLOSE_CODES_METRIC = "rebase_realtime_socket_close_codes_total";
35537
+ var REALTIME_FRAMES_IN_METRIC = "rebase_realtime_frames_in_total";
35538
+ var REALTIME_BYTES_IN_METRIC = "rebase_realtime_bytes_in_total";
35539
+ var REALTIME_FRAMES_OUT_METRIC = "rebase_realtime_frames_out_total";
35540
+ var REALTIME_BYTES_OUT_METRIC = "rebase_realtime_bytes_out_total";
35541
+ var REALTIME_REFUSED_METRIC = "rebase_realtime_frames_refused_total";
35434
35542
  /**
35435
35543
  * Report `provider`'s counts in `registry` at each render. A deployment with no
35436
35544
  * realtime, or a provider that keeps no counts, emits none of these series.
@@ -35444,6 +35552,16 @@ function recordRealtimeCounts(registry, provider) {
35444
35552
  registry.setGauge(REALTIME_CHANNELS_METRIC, counts.channels);
35445
35553
  for (const [kind, frames] of Object.entries(counts.busFramesPublished)) registry.setCounter(REALTIME_BUS_PUBLISHED_METRIC, frames, { kind });
35446
35554
  registry.setCounter(REALTIME_BUS_SKIPPED_METRIC, counts.busFramesSkipped);
35555
+ const sockets = counts.socketTotals;
35556
+ if (!sockets) return;
35557
+ registry.setCounter(REALTIME_OPENS_METRIC, sockets.opened);
35558
+ for (const [closedBy, n] of Object.entries(sockets.closedBy)) registry.setCounter(REALTIME_CLOSES_METRIC, n, { closed_by: closedBy });
35559
+ for (const [code, n] of Object.entries(sockets.closeCodes)) registry.setCounter(REALTIME_CLOSE_CODES_METRIC, n, { code });
35560
+ registry.setCounter(REALTIME_FRAMES_IN_METRIC, sockets.framesIn);
35561
+ registry.setCounter(REALTIME_BYTES_IN_METRIC, sockets.bytesIn);
35562
+ registry.setCounter(REALTIME_FRAMES_OUT_METRIC, sockets.framesOut);
35563
+ registry.setCounter(REALTIME_BYTES_OUT_METRIC, sockets.bytesOut);
35564
+ for (const [code, n] of Object.entries(sockets.refused)) registry.setCounter(REALTIME_REFUSED_METRIC, n, { code });
35447
35565
  });
35448
35566
  }
35449
35567
  //#endregion