@ultimat3/realtime 31.48.0 → 31.50.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.
package/src/fanout.ts CHANGED
@@ -69,17 +69,34 @@ export interface InProcessTransportOptions {
69
69
  class InProcessSet implements TransportSet {
70
70
  readonly #keys = new Map<string, Map<string, TransportSetEntry>>();
71
71
  readonly #clock: Clock;
72
+ #prunedAt = 0;
72
73
 
73
74
  constructor(clock: Clock) {
74
75
  this.#clock = clock;
75
76
  }
76
77
 
77
78
  async put(key: string, member: string, value: string, ttlMs: number): Promise<void> {
79
+ const now = this.#clock.now().getTime();
80
+ if (now >= this.#prunedAt + ttlMs) this.#prune(now);
78
81
  const bucket = this.#keys.get(key) ?? new Map<string, TransportSetEntry>();
79
- bucket.set(member, { member, value, expiresAt: this.#clock.now().getTime() + ttlMs });
82
+ bucket.set(member, { member, value, expiresAt: now + ttlMs });
80
83
  this.#keys.set(key, bucket);
81
84
  }
82
85
 
86
+ /**
87
+ * Expiry on the store's own clock, as the KV's server does it (`nats-kv.ts`). Read-time expiry
88
+ * alone kept every key nobody reads again — a forgotten room's sweep lease, which must outlive
89
+ * the room by one TTL so a follower reads its last roster — for the life of the process. A full
90
+ * pass at most once per TTL, the interval `sweepAll` already walks every room on.
91
+ */
92
+ #prune(now: number): void {
93
+ this.#prunedAt = now;
94
+ for (const [key, bucket] of this.#keys) {
95
+ for (const entry of bucket.values()) if (entry.expiresAt <= now) bucket.delete(entry.member);
96
+ if (bucket.size === 0) this.#keys.delete(key);
97
+ }
98
+ }
99
+
83
100
  async touch(key: string, member: string, ttlMs: number): Promise<boolean> {
84
101
  const entry = this.#keys.get(key)?.get(member);
85
102
  if (!entry || entry.expiresAt <= this.#clock.now().getTime()) return false;
@@ -104,18 +121,24 @@ class InProcessSet implements TransportSet {
104
121
  }
105
122
  return live;
106
123
  }
124
+
125
+ get size(): number {
126
+ return this.#keys.size;
127
+ }
107
128
  }
108
129
 
109
130
  /** Single-node default: `x dev`, tests, and small deployments that have not earned a bus yet. */
110
131
  export class InProcessTransport implements Transport {
111
132
  readonly name = 'in-process';
112
133
  readonly shared: TransportSet;
134
+ readonly #set: InProcessSet;
113
135
  readonly #handlers = new Map<string, Set<TransportHandler>>();
114
136
  readonly #onError: (error: unknown, subject: string) => void;
115
137
  #closed = false;
116
138
 
117
139
  constructor(options: InProcessTransportOptions = {}) {
118
- this.shared = new InProcessSet(options.clock ?? systemClock);
140
+ this.#set = new InProcessSet(options.clock ?? systemClock);
141
+ this.shared = this.#set;
119
142
  this.#onError = options.onError ?? (() => undefined);
120
143
  }
121
144
 
@@ -168,5 +191,12 @@ export class InProcessTransport implements Transport {
168
191
  }
169
192
  }
170
193
 
194
+ /**
195
+ * Keys `transport.shared` holds, emptied ones included: the in-process read a leak test needs. A
196
+ * module function, never a member — no caller of the public class has a use for it.
197
+ */
198
+ export const inProcessKeyCount = (transport: InProcessTransport): number =>
199
+ transport.shared instanceof InProcessSet ? transport.shared.size : 0;
200
+
171
201
  // The production bus lives in `nats-transport.ts`: it needs a socket, a codec and a JetStream
172
202
  // client, none of which belong in the file that defines what a transport *is*.
package/src/index.ts CHANGED
@@ -118,7 +118,7 @@ export {
118
118
  pageOutbox,
119
119
  } from './page-outbox';
120
120
  export { resetPageRealtime } from './page-reset';
121
- export { hasPageSocket, type SyncTarget } from './page-store';
121
+ export { hasPageSocket, hasSyncTarget, type SyncTarget } from './page-store';
122
122
  export { pollEvery, type QueryPoll } from './query-poll';
123
123
  export { installRealtime, type RealtimeInstall } from './reactivity';
124
124
  export {
@@ -128,7 +128,7 @@ export function closePageSockets(): void {
128
128
  }
129
129
 
130
130
  /** Where `hasPageSocket` lives, re-exported for the callers that reach it from here. */
131
- export { hasPageSocket } from './page-store';
131
+ export { hasPageSocket, hasSyncTarget } from './page-store';
132
132
 
133
133
  function hostFor(scope: string | null, buildId: string): SocketHost {
134
134
  const workerUrl =
package/src/page-store.ts CHANGED
@@ -9,6 +9,7 @@ import type { queryClientMethodFor } from '@ultimat3/query/client';
9
9
  import type { LiveClient } from './client';
10
10
  import { RealtimeUninstalledError } from './page-errors';
11
11
  import type { RecordStore } from './record-store';
12
+ import { pageSyncTarget } from './sync-meta';
12
13
 
13
14
  /** Where the page's one socket dials. Resolved on the server and handed to the island bootstrap. */
14
15
  export interface SyncTarget {
@@ -239,6 +240,16 @@ export function hasPageSocket(): boolean {
239
240
  return peekPageRealtime()?.socket !== undefined;
240
241
  }
241
242
 
243
+ /**
244
+ * Whether a live hook on this page could reach a sync node: a target `installRealtime` was given,
245
+ * or the document's `<meta name="ultimate-sync">`. Unlike `hasPageSocket` it is answered before any
246
+ * hook ran, and asking opens nothing — so an island can choose `useChannel` or its static
247
+ * fallback instead of meeting `X_SYNC_UNCONFIGURED`. `false` on a server render.
248
+ */
249
+ export function hasSyncTarget(): boolean {
250
+ return peekPageRealtime()?.sync !== undefined || pageSyncTarget() !== undefined;
251
+ }
252
+
242
253
  /** The page's record store, from its installed runtime. */
243
254
  export function pageStore(hook = 'pageStore'): RecordStore {
244
255
  return installedPage(hook).store;
@@ -6,8 +6,9 @@
6
6
  // policy is dropped, never sent. That is the rule from the live-query pipeline, implemented once.
7
7
  // A *denial* only — a gate that could not reach a decision raises, because "denied" and "the
8
8
  // database is down" are different facts and one of them has to page someone.
9
+ // Both gates decide in the SUBSCRIBER's context: `ctx.actor` is who asked, as it is over HTTP.
9
10
 
10
- import type { Actor, Ctx } from '@ultimat3/core';
11
+ import { type Actor, anonymousActor, type Ctx, ctxOf } from '@ultimat3/core';
11
12
  import { guardQuery, QueryDeniedError, type QueryPolicy, type QuerySubject } from '@ultimat3/query';
12
13
  import type { JsonValue, LiveRow } from './json';
13
14
 
@@ -60,5 +61,39 @@ function subjectOf(
60
61
  input: unknown,
61
62
  row: unknown,
62
63
  ): QuerySubject {
63
- return { actor, input, row, ctx: options.ctx, query: options.query };
64
+ // Anonymous is the anonymous actor, as over HTTP — never the node's own, which may be a system one.
65
+ const ctx =
66
+ actor === null ? subscriberContext(options.ctx, anonymousActor()) : ctxFor(options.ctx, actor);
67
+ return { actor, input, row, ctx, query: options.query };
68
+ }
69
+
70
+ /**
71
+ * Keyed by the actor OBJECT a socket holds — a re-auth puts a new one there — so no other actor
72
+ * can be answered from it; a row gate runs per subscriber per row, and `ctxOf` builds services.
73
+ */
74
+ const contexts = new WeakMap<Ctx, WeakMap<Actor, Ctx>>();
75
+
76
+ function ctxFor(node: Ctx, actor: Actor): Ctx {
77
+ let byActor = contexts.get(node);
78
+ if (byActor === undefined) {
79
+ byActor = new WeakMap();
80
+ contexts.set(node, byActor);
81
+ }
82
+ const known = byActor.get(actor);
83
+ if (known !== undefined) return known;
84
+ const made = subscriberContext(node, actor);
85
+ byActor.set(actor, made);
86
+ return made;
87
+ }
88
+
89
+ /** The node's context, re-made for one subscriber: same deploy, role and clock, their actor. */
90
+ export function subscriberContext(node: Ctx, actor: Actor): Ctx {
91
+ return ctxOf({
92
+ actor,
93
+ role: node.role,
94
+ buildId: node.buildId,
95
+ clock: node.clock,
96
+ locale: node.locale,
97
+ tz: node.tz,
98
+ });
64
99
  }
package/src/server.ts CHANGED
@@ -65,11 +65,16 @@ export {
65
65
  DeviceOfflineError,
66
66
  DeviceRequestTimeoutError,
67
67
  } from './device-errors';
68
+ export {
69
+ DEVICE_NODE_LOST,
70
+ type DeviceCloseHandler,
71
+ type DeviceInfo,
72
+ type DeviceOpenHandler,
73
+ } from './device-hooks';
68
74
  export {
69
75
  DEVICE_FRAME_QUEUE_MAX,
70
76
  DEVICE_REQUESTS_OUTSTANDING_MAX,
71
77
  type DeviceFrameHandler,
72
- type DeviceInfo,
73
78
  type DeviceWs,
74
79
  } from './device-host';
75
80
  export {
@@ -78,6 +83,7 @@ export {
78
83
  DEFAULT_DEVICE_REQUEST_DEADLINE_MS,
79
84
  DEFAULT_DEVICE_SOCKETS_PER_ACTOR,
80
85
  DEVICE_AUTH_DEADLINE_MS,
86
+ DEVICE_DISCONNECT_DEADLINE_MS,
81
87
  DEVICE_MAX_PENDING_UPGRADES,
82
88
  type DeviceAttachment,
83
89
  type DeviceAttachOptions,
@@ -95,7 +101,7 @@ export type {
95
101
  DeviceUpgradeTarget,
96
102
  DeviceWsData,
97
103
  } from './device-upgrade';
98
- export { DEVICE_FRAME_MAX_BYTES } from './device-wire';
104
+ export { DEVICE_CLOSE_REASON_MAX_BYTES, DEVICE_FRAME_MAX_BYTES } from './device-wire';
99
105
  export { RealtimeTopologyError } from './errors';
100
106
  export {
101
107
  InProcessTransport,
package/src/socket.ts CHANGED
@@ -10,15 +10,14 @@
10
10
  import {
11
11
  type Actor,
12
12
  type Clock,
13
- type Counter,
14
- counter,
15
13
  finiteOption,
16
14
  logger,
17
15
  recordConnection,
18
16
  systemClock,
19
17
  uuidV7,
20
18
  } from '@ultimat3/core';
21
- import { GapRepairs } from './channel-gaps';
19
+ import { channelFramesDropped, GapRepairs } from './channel-gaps';
20
+ import type { Audience } from './channel-tenant';
22
21
  import type { ChannelRecordsFrame } from './channel-wire';
23
22
  import { CLOSE } from './close-codes';
24
23
  import { DropWindow } from './socket-drops';
@@ -79,23 +78,6 @@ import {
79
78
  DEFAULT_MAX_FRAMES_PER_SECOND,
80
79
  } from './socket-defaults';
81
80
 
82
- /**
83
- * Channel frames this process dropped under backpressure. A dropped `records` frame is now marked
84
- * and REPAIRED — the socket is sent `replay-gap` once it drains and re-reads the channel's catch-up
85
- * query (`channel_replay_gaps_total` counts those) — while a dropped `events` frame is ephemeral
86
- * by definition and is only counted. The two series side by side are the whole delivery story.
87
- *
88
- * Declared here rather than in `@ultimat3/core`'s `runtime-metrics.ts` because that file is the
89
- * series EVERY Ultimate process emits and the deploy chart scales on; this one exists only where
90
- * channels do. **No attributes**: a topic is client-chosen (`topic()` admits any
91
- * `[A-Za-z0-9_-]+` segment), so a per-topic label is an unbounded series count one socket can mint
92
- * — the topic goes in the log line, where cardinality is somebody else's index.
93
- */
94
- const channelFramesDropped: Counter = counter('channel_frames_dropped_total', {
95
- unit: '{frame}',
96
- description: 'Channel frames dropped by socket backpressure',
97
- });
98
-
99
81
  export function actorIdOf(actor: Actor | null): string | null {
100
82
  return actor === null ? null : actor.id;
101
83
  }
@@ -428,12 +410,14 @@ export class SocketRegistry {
428
410
 
429
411
  /**
430
412
  * A `records` delivery. An owed `replay-gap` goes out first; a socket that then drops the frame is
431
- * marked for the next one. `deliver`'s twin, because only a records stream can be repaired.
413
+ * marked for the next one. `deliver`'s twin, because only a records stream can be repaired. A
414
+ * member `to` does not admit is sent `to.withheld` instead (`channel-tenant.ts`).
432
415
  */
433
- deliverRecords(topic: string, epoch: string, frame: ChannelRecordsFrame): number {
416
+ deliverRecords(topic: string, epoch: string, frame: ChannelRecordsFrame, to?: Audience): number {
434
417
  const members = this.#byTopic.get(topic);
435
418
  if (!members) return 0;
436
419
  const text = encode(frame);
420
+ const other = to === undefined ? text : encode(to.withheld);
437
421
  let sent = 0;
438
422
  let dropped = 0;
439
423
  for (const socket of members) {
@@ -442,7 +426,7 @@ export class SocketRegistry {
442
426
  continue;
443
427
  }
444
428
  this.gapRepairs.repair(socket, topic);
445
- if (socket.sendEncoded(text)) {
429
+ if (socket.sendEncoded(to === undefined || to.admits(socket.actor) ? text : other)) {
446
430
  sent += 1;
447
431
  continue;
448
432
  }
@@ -2,7 +2,7 @@
2
2
  // so the node itself stays testable with no server: this file is the only place realtime calls
3
3
  // `Bun.serve`, and the only thing in the package that knows a port exists.
4
4
 
5
- import { finiteOption, markListening, onShutdown } from '@ultimat3/core';
5
+ import { finiteOption, markListening, onShutdown, sharedPortOption } from '@ultimat3/core';
6
6
  import type { SyncNode } from './sync-node';
7
7
 
8
8
  export interface ListenOptions {
@@ -45,6 +45,8 @@ export function listenSyncNode(node: SyncNode, options: ListenOptions = {}): Syn
45
45
  // Spread, not `hostname: options.hostname` — Bun reads an explicit `undefined` as a request
46
46
  // and not as an absence, and the default it applies to a missing key is the one we want.
47
47
  ...(options.hostname === undefined ? {} : { hostname: options.hostname }),
48
+ // A supervised child on Linux shares the port with its siblings; anything else binds alone.
49
+ ...sharedPortOption(process.env),
48
50
  fetch: node.fetch,
49
51
  websocket: node.websocket,
50
52
  });