@ultimat3/realtime 31.49.0 → 31.51.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/README.md CHANGED
@@ -959,10 +959,11 @@ made it — a key already queued collapses as always, and nothing queued is ever
959
959
 
960
960
  ## Device sockets
961
961
 
962
- `deviceSocket({ path, resolveToken, onFrame, maxSocketsPerActor?, heartbeatMs?, allowedOrigins? })`
962
+ `deviceSocket({ path, resolveToken, onFrame, onOpen?, onClose?, maxSocketsPerActor?, heartbeatMs?, allowedOrigins? })`
963
963
  — a declared socket for a non-browser client, from `./server`. A factory over `route`: the value is
964
964
  a websocket mount plus `request(ctx, deviceId, frame, { deadlineMs })`, which reaches one connected
965
- device from any process over the bus, scoped to `ctx.actor.orgId`. `deviceAgent({ url, token,
965
+ device from any process over the bus, scoped to `ctx.actor.orgId`, and `disconnect(ctx, deviceId,
966
+ reason)`, which closes one from any process. `deviceAgent({ url, token,
966
967
  onRequest })` is the Bun client. Every rule (credential, caps, frame limit, beat, drain, codes):
967
968
  [wiki/Realtime.md#device-sockets](../../wiki/Realtime.md#device-sockets).
968
969
 
@@ -970,7 +971,9 @@ onRequest })` is the Bun client. Every rule (credential, caps, frame limit, beat
970
971
  |---|---|
971
972
  | `device-socket.ts` | the declaration, its screen, the registry, `request()` and `attach()` |
972
973
  | `device-upgrade.ts` | the upgrade decision: origin, bearer token under a deadline, expiry, cap |
973
- | `device-host.ts` | the sockets one node holds: frames, the lane, the sweep, the drain |
974
+ | `device-host.ts` | the sockets one node holds: frames, the lane, the sweep, the drain, a `disconnect()` |
975
+ | `device-hooks.ts` | `onOpen` / `onClose`, beside the socket path, one lane per socket |
976
+ | `device-ledger.ts` | the open sockets in the bus's shared set, so a dead node's still close |
974
977
  | `device-bus.ts` | where a device is and how a request reaches it and comes back |
975
978
  | `device-wire.ts` | both hops' frames and the frame limit |
976
979
  | `device-agent.ts` | the device's half, on Bun |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ultimat3/realtime",
3
- "version": "31.49.0",
3
+ "version": "31.51.0",
4
4
  "description": "Three-tier realtime: channels, live queries, local-first sync — one protocol, one mutator shape",
5
5
  "keywords": [
6
6
  "ultimate",
@@ -52,10 +52,10 @@
52
52
  "test": "bun test"
53
53
  },
54
54
  "dependencies": {
55
- "@ultimat3/core": "31.49.0",
56
- "@ultimat3/entity": "31.49.0",
57
- "@ultimat3/policy": "31.49.0",
58
- "@ultimat3/query": "31.49.0",
55
+ "@ultimat3/core": "31.51.0",
56
+ "@ultimat3/entity": "31.51.0",
57
+ "@ultimat3/policy": "31.51.0",
58
+ "@ultimat3/query": "31.51.0",
59
59
  "nats": "2.29.3"
60
60
  }
61
61
  }
@@ -142,6 +142,15 @@ export function channel<K extends string>(
142
142
  );
143
143
  }
144
144
  assertCatchUpPolicy(name, catchUpReadOf(ref), policy);
145
+ // Rows are replayed after a gap by the catch-up read; a ref that names none can carry events only.
146
+ // By the read declared, never its name: a declared query's name is stamped at boot, after this.
147
+ if ((init.records ?? []).length > 0 && catchUpReadOf(ref) === undefined) {
148
+ refuseChannel(
149
+ name,
150
+ 'carries records and names no catchUp read, so a client that misses a frame could never be brought back up to date',
151
+ `channelRef('${name}', { params: [/* … */], catchUp: rowsQuery }) // catchUp: the query that re-reads these rows — or drop records from channel() for an events-only channel`,
152
+ );
153
+ }
145
154
  const records = (init.records ?? []).map((entity) => {
146
155
  const projection = projectionFor(name, entity);
147
156
  for (const param of ref.params) {
@@ -34,8 +34,10 @@ export interface ChannelRefInit<K extends string> {
34
34
  /**
35
35
  * The read a client re-runs on `replay-gap` or a new epoch — a query, by name. Read on every
36
36
  * access, never at declaration: `registerQueries()` stamps a declared query's name at boot.
37
+ * Omitted on an events-only channel: with no `records` nothing is replayed, so a gap restarts
38
+ * the cursor and reads nothing — and `channel(ref, { records })` refuses a ref without one.
37
39
  */
38
- readonly catchUp: CatchUpRead;
40
+ readonly catchUp?: CatchUpRead | undefined;
39
41
  }
40
42
 
41
43
  /**
@@ -53,6 +55,7 @@ export interface ChannelHandle<K extends string = string> {
53
55
  readonly kind: 'channel-ref';
54
56
  readonly name: string;
55
57
  readonly params: readonly K[];
58
+ /** The catch-up query's name; `''` for an events-only ref, which reads nothing on a gap. */
56
59
  readonly catchUp: string;
57
60
  /** The topic for one set of params — the one spelling both halves use. */
58
61
  topic(params: ChannelParams<K>): Topic;
@@ -94,10 +97,10 @@ export function channelRef<const K extends string>(
94
97
  name,
95
98
  params: init.params,
96
99
  get catchUp(): string {
97
- return init.catchUp.name;
100
+ return init.catchUp?.name ?? '';
98
101
  },
99
102
  topic: topicOf,
100
103
  });
101
- READS.set(ref, init.catchUp);
104
+ if (init.catchUp !== undefined) READS.set(ref, init.catchUp);
102
105
  return ref;
103
106
  }
@@ -356,7 +356,9 @@ export class ChannelBook {
356
356
  // in the same notification as the read's rows (`#drain`). One whose echo comes AFTER the read
357
357
  // answered (replication slower than the read) is waited for (#778): the read lands once the
358
358
  // writes in flight over its types are answered or echoed, bounded by the store's server wait.
359
- this.#deps.catchUp(entry.catchUp, entry.params).then(
359
+ // An events-only channel names no read: nothing is replayed, so the gap answers with nothing.
360
+ const { catchUp } = this.#deps;
361
+ (entry.catchUp === '' ? Promise.resolve(undefined) : catchUp(entry.catchUp, entry.params)).then(
360
362
  (answered) => {
361
363
  if (this.#byTopic.get(entry.topic) !== entry) return;
362
364
  let landed = false;
package/src/device-bus.ts CHANGED
@@ -7,6 +7,7 @@ import { type Clock, logger, systemClock } from '@ultimat3/core';
7
7
  import { DeviceOfflineError, DeviceRequestTimeoutError } from './device-errors';
8
8
  import {
9
9
  type BusClaim,
10
+ type BusDisconnect,
10
11
  type BusMessage,
11
12
  type BusReply,
12
13
  type BusRequest,
@@ -23,6 +24,8 @@ export interface DeviceBusHandlers {
23
24
  onRequest(request: BusRequest): void;
24
25
  /** A newer socket for a device opened on `claim.node`. */
25
26
  onClaim(claim: BusClaim): void;
27
+ /** Close the device's socket, if this node holds it; answer through `reply`. */
28
+ onDisconnect(order: BusDisconnect): void;
26
29
  }
27
30
 
28
31
  export interface DeviceBusOptions {
@@ -164,6 +167,56 @@ export class DeviceBus {
164
167
  deviceId: string,
165
168
  frame: JsonValue,
166
169
  deadlineMs: number,
170
+ ): Promise<JsonValue> {
171
+ return await this.#ask(tenant, deviceId, deadlineMs, 'request', (id) => ({
172
+ kind: 'request',
173
+ id,
174
+ from: this.#options.nodeId,
175
+ tenant,
176
+ deviceId,
177
+ deadlineMs,
178
+ frame,
179
+ }));
180
+ }
181
+
182
+ /**
183
+ * The device's socket closed by the node holding it, with `reason`. `true` once the holder
184
+ * closed it; `false` when no node holds one under this tenant — the same answer for a device of
185
+ * another tenant. A holder that never answers is `X_DEVICE_REQUEST_TIMEOUT`.
186
+ */
187
+ async disconnect(
188
+ tenant: string,
189
+ deviceId: string,
190
+ reason: string,
191
+ deadlineMs: number,
192
+ ): Promise<boolean> {
193
+ try {
194
+ await this.#ask(tenant, deviceId, deadlineMs, 'disconnect', (id) => ({
195
+ kind: 'disconnect',
196
+ id,
197
+ from: this.#options.nodeId,
198
+ tenant,
199
+ deviceId,
200
+ reason,
201
+ }));
202
+ return true;
203
+ } catch (error) {
204
+ if (error instanceof DeviceOfflineError) return false;
205
+ throw error;
206
+ }
207
+ }
208
+
209
+ /**
210
+ * One message to the node holding a device, and its reply. Located first, so a device nobody
211
+ * holds is `X_DEVICE_OFFLINE` at once; a holder that finds no socket says so, and one that never
212
+ * answers is `X_DEVICE_REQUEST_TIMEOUT` with its pending entry gone.
213
+ */
214
+ async #ask(
215
+ tenant: string,
216
+ deviceId: string,
217
+ deadlineMs: number,
218
+ operation: 'request' | 'disconnect',
219
+ message: (id: string) => BusRequest | BusDisconnect,
167
220
  ): Promise<JsonValue> {
168
221
  const holder = await this.#locate(tenant, deviceId);
169
222
  if (holder === null) {
@@ -177,21 +230,19 @@ export class DeviceBus {
177
230
  const answer = new Promise<JsonValue>((resolve, reject) => {
178
231
  const cancel = this.#options.schedule(() => {
179
232
  if (!this.#pending.delete(id)) return;
180
- reject(new DeviceRequestTimeoutError({ path: this.#options.path, deviceId, deadlineMs }));
233
+ reject(
234
+ new DeviceRequestTimeoutError({
235
+ path: this.#options.path,
236
+ deviceId,
237
+ deadlineMs,
238
+ operation,
239
+ }),
240
+ );
181
241
  }, deadlineMs);
182
242
  this.#pending.set(id, { deviceId, resolve, reject, cancel });
183
243
  });
184
- const request: BusRequest = {
185
- kind: 'request',
186
- id,
187
- from: this.#options.nodeId,
188
- tenant,
189
- deviceId,
190
- deadlineMs,
191
- frame,
192
- };
193
244
  try {
194
- await this.#options.transport.publish(this.#nodeSubject(holder), JSON.stringify(request));
245
+ await this.#options.transport.publish(this.#nodeSubject(holder), JSON.stringify(message(id)));
195
246
  } catch (error) {
196
247
  const pending = this.#pending.get(id);
197
248
  this.#pending.delete(id);
@@ -234,7 +285,11 @@ export class DeviceBus {
234
285
  return;
235
286
  }
236
287
  if (message.kind === 'request') handlers?.onRequest(message);
237
- else if (message.kind === 'claim') handlers?.onClaim(message);
288
+ // This node's own claim: `open` already closed the socket it replaced, and a claim that lands
289
+ // after a newer socket opened here would close that one instead.
290
+ else if (message.kind === 'claim') {
291
+ if (message.node !== this.#options.nodeId) handlers?.onClaim(message);
292
+ } else if (message.kind === 'disconnect') handlers?.onDisconnect(message);
238
293
  else {
239
294
  const pending = this.#pending.get(message.id);
240
295
  if (pending !== undefined) this.#settle(message.id, pending, message);
@@ -26,13 +26,28 @@ export class DeviceOfflineError extends RealtimeError {
26
26
  }
27
27
  }
28
28
 
29
- /** The device took the request frame and sent no `response` carrying its id before the deadline. */
29
+ /**
30
+ * The device took the request frame and sent no `response` carrying its id before the deadline —
31
+ * or, for a `disconnect()`, the node registered as holding it never said it closed the socket.
32
+ */
30
33
  export class DeviceRequestTimeoutError extends RealtimeError {
31
- constructor(args: { path: string; deviceId: string; deadlineMs: number }) {
34
+ constructor(args: {
35
+ path: string;
36
+ deviceId: string;
37
+ deadlineMs: number;
38
+ operation?: 'request' | 'disconnect' | undefined;
39
+ }) {
40
+ const id = idArg(args.deviceId);
32
41
  super({
33
42
  code: 'X_DEVICE_REQUEST_TIMEOUT',
34
- cause: `device ${JSON.stringify(args.deviceId)} on deviceSocket("${args.path}") did not answer within ${args.deadlineMs}ms`,
35
- fix: `deviceLink.request(ctx, '${idArg(args.deviceId)}', frame, { deadlineMs: ${Math.min(args.deadlineMs * 2, DEVICE_MAX_DEADLINE_MS)} }) # or answer every request with { type: 'response', id, frame } on the device`,
43
+ cause:
44
+ args.operation === 'disconnect'
45
+ ? `the node holding device ${JSON.stringify(args.deviceId)} on deviceSocket("${args.path}") did not confirm the disconnect within ${args.deadlineMs}ms`
46
+ : `device ${JSON.stringify(args.deviceId)} on deviceSocket("${args.path}") did not answer within ${args.deadlineMs}ms`,
47
+ fix:
48
+ args.operation === 'disconnect'
49
+ ? `x doctor --json # then retry deviceLink.disconnect(ctx, '${id}', reason); a node that died holding it closes on its own within three beats`
50
+ : `deviceLink.request(ctx, '${id}', frame, { deadlineMs: ${Math.min(args.deadlineMs * 2, DEVICE_MAX_DEADLINE_MS)} }) # or answer every request with { type: 'response', id, frame } on the device`,
36
51
  });
37
52
  }
38
53
  }
@@ -0,0 +1,141 @@
1
+ // `onOpen` and `onClose` of a device socket, run beside the socket and never in its path: each in
2
+ // a per-socket lane (a close never overtakes its open), as the device's actor, a throw reported and
3
+ // nothing more. With `onClose` declared each socket is also on the ledger, so a node that dies
4
+ // holding sockets still yields their close events, from whichever node leads the next pass.
5
+
6
+ import type { Actor, Ctx } from '@ultimat3/core';
7
+ import { ctxOf, reportError, runWithContext } from '@ultimat3/core';
8
+ import { actorOfRecord, type DeviceLedger, type DeviceRecord, recordActor } from './device-ledger';
9
+ import type { DeviceWsData } from './device-upgrade';
10
+
11
+ /** Who a socket belongs to — what `onFrame`, `onOpen` and `onClose` read. */
12
+ export interface DeviceInfo {
13
+ readonly deviceId: string;
14
+ readonly socketId: string;
15
+ readonly tenant: string;
16
+ }
17
+
18
+ export type DeviceOpenHandler = (input: {
19
+ readonly device: DeviceInfo;
20
+ readonly ctx: Ctx;
21
+ }) => Promise<void> | void;
22
+
23
+ export type DeviceCloseHandler = (input: {
24
+ readonly device: DeviceInfo;
25
+ readonly ctx: Ctx;
26
+ /**
27
+ * Why it closed: the node's own reason (`replaced`, `no beat`, `grant expired`, `drain`, the one
28
+ * `disconnect()` was given, …), `disconnected` when the device or its network ended it, and
29
+ * `node lost` when the node holding it stopped beating — then `ctx.actor` carries the actor's
30
+ * kind, id and org only, since roles and facts never leave the node that resolved them.
31
+ */
32
+ readonly reason: string;
33
+ }) => Promise<void> | void;
34
+
35
+ /** The close reason of a socket whose node died with it. */
36
+ export const DEVICE_NODE_LOST = 'node lost';
37
+
38
+ export interface DeviceHooksOptions {
39
+ readonly onOpen?: DeviceOpenHandler | undefined;
40
+ readonly onClose?: DeviceCloseHandler | undefined;
41
+ /** Present exactly when `onClose` is: an app that never reads a close pays no bus write. */
42
+ readonly ledger: DeviceLedger | null;
43
+ }
44
+
45
+ const infoOf = (data: DeviceWsData): DeviceInfo => ({
46
+ deviceId: data.grant.deviceId,
47
+ socketId: data.socketId,
48
+ tenant: data.tenant,
49
+ });
50
+
51
+ export class DeviceHooks {
52
+ readonly #options: DeviceHooksOptions;
53
+ readonly #lanes = new Map<string, Promise<void>>();
54
+
55
+ constructor(options: DeviceHooksOptions) {
56
+ this.#options = options;
57
+ }
58
+
59
+ /** Lanes still running: what a leak test reads. */
60
+ get pending(): number {
61
+ return this.#lanes.size;
62
+ }
63
+
64
+ opened(data: DeviceWsData): void {
65
+ const { ledger } = this.#options;
66
+ const record = { ...infoOf(data), actor: recordActor(data.grant.actor) };
67
+ this.#queue(data.socketId, async () => {
68
+ if (ledger !== null) await this.#guard(ledger.opened(record), 'device.ledger');
69
+ await this.#open(infoOf(data), data.grant.actor);
70
+ });
71
+ }
72
+
73
+ closed(data: DeviceWsData, reason: string): void {
74
+ const { ledger } = this.#options;
75
+ this.#queue(data.socketId, async () => {
76
+ if (ledger !== null) await this.#guard(ledger.closed(data.socketId), 'device.ledger');
77
+ await this.#close(infoOf(data), data.grant.actor, reason);
78
+ });
79
+ }
80
+
81
+ /**
82
+ * The beat's pass: each held socket's record kept, and written again (an `onOpen` with it) when
83
+ * it was gone; then, on the leading node, a close for each socket a dead node took with it.
84
+ */
85
+ async sweep(held: () => readonly DeviceWsData[], holds: (socketId: string) => boolean) {
86
+ const { ledger } = this.#options;
87
+ if (ledger === null) return;
88
+ await Promise.all(
89
+ held().map(async (data) => {
90
+ if (await ledger.keep(data.socketId)) return;
91
+ if (holds(data.socketId)) this.opened(data);
92
+ }),
93
+ );
94
+ for (const record of await ledger.reap()) this.#lost(record);
95
+ }
96
+
97
+ #lost(record: DeviceRecord): void {
98
+ const { socketId, deviceId, tenant } = record;
99
+ this.#queue(socketId, () =>
100
+ this.#close({ deviceId, socketId, tenant }, actorOfRecord(record.actor), DEVICE_NODE_LOST),
101
+ );
102
+ }
103
+
104
+ async #open(device: DeviceInfo, actor: Actor): Promise<void> {
105
+ const { onOpen } = this.#options;
106
+ if (onOpen === undefined) return;
107
+ const ctx = ctxOf({ actor });
108
+ await this.#guard(
109
+ (async () => await runWithContext(ctx, () => onOpen({ device, ctx })))(),
110
+ 'device.on_open',
111
+ );
112
+ }
113
+
114
+ async #close(device: DeviceInfo, actor: Actor, reason: string): Promise<void> {
115
+ const { onClose } = this.#options;
116
+ if (onClose === undefined) return;
117
+ const ctx = ctxOf({ actor });
118
+ await this.#guard(
119
+ (async () => await runWithContext(ctx, () => onClose({ device, ctx, reason })))(),
120
+ 'device.on_close',
121
+ );
122
+ }
123
+
124
+ /** Appended to the socket's lane; the lane is forgotten once nothing is queued behind it. */
125
+ #queue(socketId: string, work: () => Promise<void>): void {
126
+ const lane = (this.#lanes.get(socketId) ?? Promise.resolve()).then(work);
127
+ this.#lanes.set(socketId, lane);
128
+ void lane.then(() => {
129
+ if (this.#lanes.get(socketId) === lane) this.#lanes.delete(socketId);
130
+ });
131
+ }
132
+
133
+ /** A hook or a bus write that fails is reported; the lane, and the socket, go on. */
134
+ async #guard(work: Promise<void>, operation: string): Promise<void> {
135
+ try {
136
+ await work;
137
+ } catch (error) {
138
+ reportError(error, { source: 'realtime', scope: { operation } });
139
+ }
140
+ }
141
+ }
@@ -7,9 +7,11 @@ import { ctxOf, isUltimateError, reportError, runWithContext } from '@ultimat3/c
7
7
  import { CLOSE } from './close-codes';
8
8
  import type { DeviceBus, DeviceBusHandlers } from './device-bus';
9
9
  import { DeviceFrameTooLargeError } from './device-errors';
10
+ import type { DeviceHooks, DeviceInfo } from './device-hooks';
10
11
  import type { DeviceWsData } from './device-upgrade';
11
12
  import {
12
13
  type BusClaim,
14
+ type BusDisconnect,
13
15
  type BusRequest,
14
16
  bytesOverLimit,
15
17
  DEVICE_FRAME_MAX_BYTES,
@@ -28,13 +30,6 @@ export interface DeviceWs {
28
30
  close(code?: number, reason?: string): void;
29
31
  }
30
32
 
31
- /** Who sent a frame — what `onFrame` reads alongside it. */
32
- export interface DeviceInfo {
33
- readonly deviceId: string;
34
- readonly socketId: string;
35
- readonly tenant: string;
36
- }
37
-
38
33
  export type DeviceFrameHandler = (input: {
39
34
  readonly frame: JsonValue;
40
35
  readonly device: DeviceInfo;
@@ -57,6 +52,8 @@ interface Held {
57
52
  queued: number;
58
53
  /** Request id → the requesting node and when this node stops waiting for the device. */
59
54
  readonly requests: Map<string, { readonly from: string; readonly until: number }>;
55
+ /** Why this node closed it, set by the first close this node makes; `null` until then. */
56
+ reason: string | null;
60
57
  }
61
58
 
62
59
  export interface DeviceHostOptions {
@@ -68,8 +65,13 @@ export interface DeviceHostOptions {
68
65
  readonly clock: Clock;
69
66
  readonly rng: Rng;
70
67
  readonly schedule: Scheduler;
68
+ /** `onOpen`/`onClose`, run beside the socket path. Absent: no hook, no ledger. */
69
+ readonly hooks?: DeviceHooks | undefined;
71
70
  }
72
71
 
72
+ /** The close reason of a socket this node did not close: the device, or its network, did. */
73
+ const PEER_CLOSED = 'disconnected';
74
+
73
75
  /** A device's key on this node: tenant and id together, never one without the other. */
74
76
  const deviceKey = (tenant: string, deviceId: string): string => JSON.stringify([tenant, deviceId]);
75
77
 
@@ -91,14 +93,17 @@ export class DeviceHost implements DeviceBusHandlers {
91
93
  const key = deviceKey(tenant, grant.deviceId);
92
94
  // One socket per device: the newest wins here and, through the claim, on every other node.
93
95
  const previous = this.#byDevice.get(key);
94
- if (previous !== undefined) this.#held.get(previous)?.ws.close(CLOSE.policy, 'replaced');
96
+ const replaced = previous === undefined ? undefined : this.#held.get(previous);
97
+ if (replaced !== undefined) this.#shut(replaced, CLOSE.policy, 'replaced');
95
98
  this.#held.set(socketId, {
96
99
  ws,
97
100
  lastSeen: this.#options.clock.monotonic(),
98
101
  lane: Promise.resolve(),
99
102
  queued: 0,
100
103
  requests: new Map(),
104
+ reason: null,
101
105
  });
106
+ this.#options.hooks?.opened(ws.data);
102
107
  this.#byDevice.set(key, socketId);
103
108
  this.#send(ws, {
104
109
  type: 'hello',
@@ -115,18 +120,18 @@ export class DeviceHost implements DeviceBusHandlers {
115
120
  const held = this.#held.get(ws.data.socketId);
116
121
  if (held === undefined) return;
117
122
  if (typeof message !== 'string') {
118
- ws.close(1003, 'text frames only');
123
+ this.#shut(held, 1003, 'text frames only');
119
124
  return;
120
125
  }
121
126
  // Bun's `maxPayloadLength` refuses first; this is the same limit for a host that applied none.
122
127
  if (bytesOverLimit(message) !== null) {
123
- ws.close(1009, 'X_DEVICE_FRAME_TOO_LARGE');
128
+ this.#shut(held, 1009, 'X_DEVICE_FRAME_TOO_LARGE');
124
129
  return;
125
130
  }
126
131
  held.lastSeen = this.#options.clock.monotonic();
127
132
  const frame = decodeDeviceFrame(message);
128
133
  if (frame === undefined) {
129
- ws.close(CLOSE.policy, 'X_PROTOCOL_VERSION');
134
+ this.#shut(held, CLOSE.policy, 'X_PROTOCOL_VERSION');
130
135
  return;
131
136
  }
132
137
  if (frame.type === 'response') {
@@ -146,6 +151,7 @@ export class DeviceHost implements DeviceBusHandlers {
146
151
  this.#options.principals.release(socketId);
147
152
  if (held === undefined) return;
148
153
  this.#held.delete(socketId);
154
+ this.#options.hooks?.closed(ws.data, held.reason ?? PEER_CLOSED);
149
155
  for (const [id, asked] of held.requests)
150
156
  this.#offline(asked.from, id, 'the device disconnected');
151
157
  const key = deviceKey(tenant, grant.deviceId);
@@ -180,7 +186,23 @@ export class DeviceHost implements DeviceBusHandlers {
180
186
  onClaim(claim: BusClaim): void {
181
187
  const socketId = this.#byDevice.get(deviceKey(claim.tenant, claim.deviceId));
182
188
  if (socketId === undefined || socketId === claim.socketId) return;
183
- this.#held.get(socketId)?.ws.close(CLOSE.policy, 'replaced');
189
+ const held = this.#held.get(socketId);
190
+ if (held !== undefined) this.#shut(held, CLOSE.policy, 'replaced');
191
+ }
192
+
193
+ /** `disconnect()` from any node: the device's socket here closed with the caller's reason. */
194
+ onDisconnect(order: BusDisconnect): void {
195
+ const socketId = this.#byDevice.get(deviceKey(order.tenant, order.deviceId));
196
+ const held = socketId === undefined ? undefined : this.#held.get(socketId);
197
+ if (held === undefined) {
198
+ this.#offline(order.from, order.id, 'no socket for it on the node it was registered on');
199
+ return;
200
+ }
201
+ this.#shut(held, CLOSE.policy, order.reason);
202
+ this.#background(
203
+ this.#options.bus.reply(order.from, { kind: 'response', id: order.id, frame: true }),
204
+ 'device.reply',
205
+ );
184
206
  }
185
207
 
186
208
  /** One pass: silent and expired sockets closed, live ones re-registered, stale requests forgotten. */
@@ -191,11 +213,11 @@ export class DeviceHost implements DeviceBusHandlers {
191
213
  for (const held of this.#held.values()) {
192
214
  const { grant, tenant, socketId } = held.ws.data;
193
215
  if (now - held.lastSeen > silentAfter) {
194
- held.ws.close(CLOSE.idle, 'no beat');
216
+ this.#shut(held, CLOSE.idle, 'no beat');
195
217
  continue;
196
218
  }
197
219
  if (grant.expiresAt !== undefined && !(grant.expiresAt > wall)) {
198
- held.ws.close(CLOSE.policy, 'grant expired');
220
+ this.#shut(held, CLOSE.policy, 'grant expired');
199
221
  continue;
200
222
  }
201
223
  for (const [id, asked] of held.requests) if (asked.until <= now) held.requests.delete(id);
@@ -204,6 +226,16 @@ export class DeviceHost implements DeviceBusHandlers {
204
226
  'device.refresh',
205
227
  );
206
228
  }
229
+ const { hooks } = this.#options;
230
+ if (hooks !== undefined) {
231
+ this.#background(
232
+ hooks.sweep(
233
+ () => [...this.#held.values()].map((entry) => entry.ws.data),
234
+ (socketId) => this.#held.has(socketId),
235
+ ),
236
+ 'device.ledger',
237
+ );
238
+ }
207
239
  }
208
240
 
209
241
  /** Every socket told when to come back (slots across `spreadMs`), then the grace, then closed. */
@@ -221,12 +253,18 @@ export class DeviceHost implements DeviceBusHandlers {
221
253
  await new Promise<void>((resolve) => this.#options.schedule(resolve, options.graceMs));
222
254
  }
223
255
  // Closed, not removed: each `close` callback releases its slot, its requests and its entry.
224
- for (const entry of [...this.#held.values()]) entry.ws.close(CLOSE.goingAway, 'drain');
256
+ for (const entry of [...this.#held.values()]) this.#shut(entry, CLOSE.goingAway, 'drain');
257
+ }
258
+
259
+ /** Every close this node makes: the first reason is the one `onClose` reads. */
260
+ #shut(held: Held, code: number, reason: string): void {
261
+ held.reason ??= reason;
262
+ held.ws.close(code, reason);
225
263
  }
226
264
 
227
265
  #enqueue(held: Held, frame: JsonValue): void {
228
266
  if (held.queued >= DEVICE_FRAME_QUEUE_MAX) {
229
- held.ws.close(CLOSE.policy, 'X_FRAME_RATE_LIMIT');
267
+ this.#shut(held, CLOSE.policy, 'X_FRAME_RATE_LIMIT');
230
268
  return;
231
269
  }
232
270
  held.queued += 1;
@@ -0,0 +1,153 @@
1
+ // The open device sockets of one declaration, fleet-wide, in the bus's shared set: what turns a node
2
+ // that died holding sockets into close events. A holder writes one record per socket and keeps it on
3
+ // its beat; one serving node per pass (the lowest live id, presence's election) reads every record
4
+ // and takes the ones whose node stopped beating — each dropped before it is handed back.
5
+
6
+ import {
7
+ type Actor,
8
+ type ActorKind,
9
+ agentActor,
10
+ anonymousActor,
11
+ isActorKind,
12
+ isJsonObject,
13
+ serviceActor,
14
+ userActor,
15
+ } from '@ultimat3/core';
16
+ import { parseJson } from './device-wire';
17
+ import type { Transport } from './fanout';
18
+
19
+ /** A node is live while its roster entry is: three beats, the device registration's own window. */
20
+ const ROSTER_BEATS = 3;
21
+ /**
22
+ * A record outlives its holder's roster entry many times over, so a dead node's sockets are still
23
+ * on the bus when a survivor (or the node's own replacement) leads a pass. Refreshed every beat.
24
+ */
25
+ const RECORD_BEATS = 20;
26
+
27
+ /** Who a socket acted as, as far as another node can rebuild it: identity, never roles or facts. */
28
+ export interface DeviceRecordActor {
29
+ readonly kind: ActorKind;
30
+ readonly id: string;
31
+ readonly orgId?: string | undefined;
32
+ }
33
+
34
+ export interface DeviceRecord {
35
+ readonly socketId: string;
36
+ readonly node: string;
37
+ readonly tenant: string;
38
+ readonly deviceId: string;
39
+ readonly actor: DeviceRecordActor;
40
+ }
41
+
42
+ export interface DeviceLedgerOptions {
43
+ readonly transport: Transport;
44
+ readonly path: string;
45
+ readonly nodeId: string;
46
+ readonly heartbeatMs: number;
47
+ }
48
+
49
+ export const recordActor = (actor: Actor): DeviceRecordActor =>
50
+ actor.orgId === undefined
51
+ ? { kind: actor.kind, id: actor.id }
52
+ : { kind: actor.kind, id: actor.id, orgId: actor.orgId };
53
+
54
+ /** The actor a record names, rebuilt with no role, scope, permission or fact it never carried. */
55
+ export function actorOfRecord(actor: DeviceRecordActor): Actor {
56
+ const init = { id: actor.id, orgId: actor.orgId };
57
+ if (actor.kind === 'service') return serviceActor(init);
58
+ if (actor.kind === 'agent') return agentActor(init);
59
+ if (actor.kind === 'anonymous') return anonymousActor();
60
+ return userActor(init);
61
+ }
62
+
63
+ const isText = (value: unknown): value is string => typeof value === 'string';
64
+
65
+ function parseRecord(socketId: string, value: string): DeviceRecord | undefined {
66
+ const raw = parseJson(value);
67
+ if (!isJsonObject(raw)) return undefined;
68
+ const { node, tenant, deviceId, actor } = raw;
69
+ if (!isText(node) || !isText(tenant) || !isText(deviceId) || !isJsonObject(actor)) {
70
+ return undefined;
71
+ }
72
+ const { kind, id, orgId } = actor;
73
+ if (!isActorKind(kind) || !isText(id) || (orgId !== undefined && !isText(orgId))) {
74
+ return undefined;
75
+ }
76
+ return {
77
+ socketId,
78
+ node,
79
+ tenant,
80
+ deviceId,
81
+ actor: orgId === undefined ? { kind, id } : { kind, id, orgId },
82
+ };
83
+ }
84
+
85
+ export class DeviceLedger {
86
+ readonly #options: DeviceLedgerOptions;
87
+ readonly #recordsKey: string;
88
+ readonly #rosterKey: string;
89
+
90
+ constructor(options: DeviceLedgerOptions) {
91
+ this.#options = options;
92
+ this.#recordsKey = `device.open.${JSON.stringify(options.path)}`;
93
+ this.#rosterKey = `device.nodes.${JSON.stringify(options.path)}`;
94
+ }
95
+
96
+ /** On the roster before the first socket: a record whose node is absent from it is reaped. */
97
+ async join(): Promise<void> {
98
+ await this.#options.transport.shared.put(
99
+ this.#rosterKey,
100
+ this.#options.nodeId,
101
+ '',
102
+ this.#options.heartbeatMs * ROSTER_BEATS,
103
+ );
104
+ }
105
+
106
+ async opened(record: Omit<DeviceRecord, 'node'>): Promise<void> {
107
+ const { socketId, tenant, deviceId, actor } = record;
108
+ await this.#options.transport.shared.put(
109
+ this.#recordsKey,
110
+ socketId,
111
+ JSON.stringify({ node: this.#options.nodeId, tenant, deviceId, actor }),
112
+ this.#recordTtl(),
113
+ );
114
+ }
115
+
116
+ /** `false` when the record was gone — reaped, or lost with the bus: the caller writes it again. */
117
+ async keep(socketId: string): Promise<boolean> {
118
+ return await this.#options.transport.shared.touch(
119
+ this.#recordsKey,
120
+ socketId,
121
+ this.#recordTtl(),
122
+ );
123
+ }
124
+
125
+ async closed(socketId: string): Promise<void> {
126
+ await this.#options.transport.shared.drop(this.#recordsKey, socketId);
127
+ }
128
+
129
+ /**
130
+ * One pass: this node's roster entry renewed, and — when it leads — every record whose node is
131
+ * off the roster, dropped and returned. Two nodes that disagree on the leader both reap; that is
132
+ * a second close event for a socket already gone, never a socket left without one.
133
+ */
134
+ async reap(): Promise<readonly DeviceRecord[]> {
135
+ await this.join();
136
+ const roster = await this.#options.transport.shared.entries(this.#rosterKey);
137
+ const live = new Set(roster.map((entry) => entry.member));
138
+ const leader = [...live, this.#options.nodeId].sort()[0];
139
+ if (leader !== this.#options.nodeId) return [];
140
+ const orphans: DeviceRecord[] = [];
141
+ for (const entry of await this.#options.transport.shared.entries(this.#recordsKey)) {
142
+ const record = parseRecord(entry.member, entry.value);
143
+ if (record === undefined || live.has(record.node)) continue;
144
+ await this.#options.transport.shared.drop(this.#recordsKey, entry.member);
145
+ orphans.push(record);
146
+ }
147
+ return orphans;
148
+ }
149
+
150
+ #recordTtl(): number {
151
+ return this.#options.heartbeatMs * RECORD_BEATS;
152
+ }
153
+ }
@@ -12,14 +12,21 @@ import {
12
12
  DeviceFrameTooLargeError,
13
13
  DeviceOfflineError,
14
14
  } from './device-errors';
15
+ import { type DeviceCloseHandler, DeviceHooks, type DeviceOpenHandler } from './device-hooks';
15
16
  import { type DeviceFrameHandler, DeviceHost, type DeviceWs } from './device-host';
17
+ import { DeviceLedger } from './device-ledger';
16
18
  import {
17
19
  answerDeviceUpgrade,
18
20
  type DeviceTokenResolver,
19
21
  type DeviceUpgradeTarget,
20
22
  tenantOf,
21
23
  } from './device-upgrade';
22
- import { bytesOverLimit, DEVICE_FRAME_MAX_BYTES } from './device-wire';
24
+ import {
25
+ bytesOverLimit,
26
+ DEVICE_CLOSE_REASON_MAX_BYTES,
27
+ DEVICE_FRAME_MAX_BYTES,
28
+ isCloseReason,
29
+ } from './device-wire';
23
30
  import type { Transport } from './fanout';
24
31
  import type { JsonValue } from './json';
25
32
  import { PrincipalSockets } from './principal-sockets';
@@ -28,6 +35,8 @@ import { AcceptBudget, type Rng, type Scheduler, timeoutScheduler } from './thun
28
35
  export const DEFAULT_DEVICE_HEARTBEAT_MS = 15_000;
29
36
  export const DEFAULT_DEVICE_SOCKETS_PER_ACTOR = 10;
30
37
  export const DEFAULT_DEVICE_REQUEST_DEADLINE_MS = 30_000;
38
+ /** How long `disconnect()` waits for the holding node to say it closed the socket. */
39
+ export const DEVICE_DISCONNECT_DEADLINE_MS = 5_000;
31
40
  /** How long `resolveToken` may hold an upgrade before it is answered 503. */
32
41
  export const DEVICE_AUTH_DEADLINE_MS = 5_000;
33
42
  /** Upgrades parked in `resolveToken` at once, per declaration per node; past it, shed. */
@@ -45,6 +54,14 @@ export interface DeviceSocketOptions {
45
54
  readonly path: string;
46
55
  readonly resolveToken: DeviceTokenResolver;
47
56
  readonly onFrame: DeviceFrameHandler;
57
+ /** A socket opened. Runs beside the socket, never in its path: a throw is reported, nothing else. */
58
+ readonly onOpen?: DeviceOpenHandler | undefined;
59
+ /**
60
+ * A socket closed — at least once per socket, with its reason, on the node that held it; or, when
61
+ * that node died, on whichever serving node leads the next beat (`reason: 'node lost'`). Runs
62
+ * after its `onOpen` settles, beside the socket path, a throw reported and nothing else.
63
+ */
64
+ readonly onClose?: DeviceCloseHandler | undefined;
48
65
  readonly maxSocketsPerActor?: number | undefined;
49
66
  /** How often a device must send a frame (a `{ type: 'beat' }` is free); silent for two, it is closed. */
50
67
  readonly heartbeatMs?: number | undefined;
@@ -94,6 +111,14 @@ export interface DeviceSocket {
94
111
  frame: JsonValue,
95
112
  options?: DeviceRequestOptions,
96
113
  ): Promise<JsonValue>;
114
+ /**
115
+ * Close one device's socket from any role, on whichever node holds it, with `reason` (what the
116
+ * device's close frame and `onClose` read). `true` once it is closed; `false` when no socket is
117
+ * open for it under the caller's tenant — the same answer for another tenant's device.
118
+ * `deviceSocket()` always sets it; optional only so a `DeviceSocket` of an app's own (a test's
119
+ * fake) still compiles. Required waits on `next`.
120
+ */
121
+ disconnect?(ctx: { readonly actor: Actor }, deviceId: string, reason: string): Promise<boolean>;
97
122
  attach(options: DeviceAttachOptions): Promise<DeviceAttachment>;
98
123
  /** Sockets this process holds for this declaration. */
99
124
  readonly connected: number;
@@ -284,6 +309,29 @@ export function deviceSocket(options: DeviceSocketOptions): DeviceSocket {
284
309
  }
285
310
  return await bus.request(tenantOf(ctx.actor), deviceId, frame, deadlineMs);
286
311
  },
312
+ async disconnect(ctx, deviceId, reason) {
313
+ if (!isCloseReason(reason)) {
314
+ throw invalid(
315
+ path,
316
+ `disconnect's reason must be 1 to ${DEVICE_CLOSE_REASON_MAX_BYTES} UTF-8 bytes, a websocket close frame's room`,
317
+ `deviceLink.disconnect(ctx, deviceId, 'revoked')`,
318
+ );
319
+ }
320
+ if (bus === null) {
321
+ throw new DeviceOfflineError({
322
+ path,
323
+ deviceId,
324
+ reason:
325
+ 'this process never attached the declaration to a bus (the boot attaches every declared deviceSocket)',
326
+ });
327
+ }
328
+ return await bus.disconnect(
329
+ tenantOf(ctx.actor),
330
+ deviceId,
331
+ reason,
332
+ DEVICE_DISCONNECT_DEADLINE_MS,
333
+ );
334
+ },
287
335
  async attach(attachOptions) {
288
336
  if (bus !== null) {
289
337
  throw invalid(
@@ -309,6 +357,10 @@ export function deviceSocket(options: DeviceSocketOptions): DeviceSocket {
309
357
  clock,
310
358
  newId,
311
359
  });
360
+ const ledger =
361
+ attachOptions.serve && options.onClose !== undefined
362
+ ? new DeviceLedger({ transport: attachOptions.transport, path, nodeId, heartbeatMs })
363
+ : null;
312
364
  const ownHost = attachOptions.serve
313
365
  ? new DeviceHost({
314
366
  path,
@@ -319,8 +371,11 @@ export function deviceSocket(options: DeviceSocketOptions): DeviceSocket {
319
371
  clock,
320
372
  rng,
321
373
  schedule,
374
+ hooks: new DeviceHooks({ onOpen: options.onOpen, onClose: options.onClose, ledger }),
322
375
  })
323
376
  : null;
377
+ // On the roster before the first socket, so no leader reaps this node's records as a dead one's.
378
+ await ledger?.join();
324
379
  await ownBus.start(ownHost);
325
380
  bus = ownBus;
326
381
  host = ownHost;
@@ -123,7 +123,26 @@ export interface BusClaim {
123
123
  readonly socketId: string;
124
124
  }
125
125
 
126
- export type BusMessage = BusRequest | BusReply | BusClaim;
126
+ /** `disconnect()` on its way to the node that holds the device: close it, with this reason. */
127
+ export interface BusDisconnect {
128
+ readonly kind: 'disconnect';
129
+ readonly id: string;
130
+ readonly from: string;
131
+ readonly tenant: string;
132
+ readonly deviceId: string;
133
+ readonly reason: string;
134
+ }
135
+
136
+ /** The longest close reason, in UTF-8 bytes: what a websocket close frame has room for. */
137
+ export const DEVICE_CLOSE_REASON_MAX_BYTES = 123;
138
+
139
+ /** A close reason a websocket can carry: some text, and no more than its close frame holds. */
140
+ export const isCloseReason = (value: unknown): value is string =>
141
+ typeof value === 'string' &&
142
+ value.length > 0 &&
143
+ encoder.encode(value).length <= DEVICE_CLOSE_REASON_MAX_BYTES;
144
+
145
+ export type BusMessage = BusRequest | BusReply | BusClaim | BusDisconnect;
127
146
 
128
147
  const isText = (value: unknown): value is string => typeof value === 'string';
129
148
 
@@ -146,6 +165,11 @@ export function decodeBusMessage(text: string): BusMessage | undefined {
146
165
  if (kind === 'offline' && isId(id) && isText(raw['reason'])) {
147
166
  return { kind, id, reason: raw['reason'] };
148
167
  }
168
+ if (kind === 'disconnect') {
169
+ const { from, reason } = raw;
170
+ if (!isId(id) || !isId(from) || !isText(tenant) || !isText(deviceId)) return undefined;
171
+ return isCloseReason(reason) ? { kind, id, from, tenant, deviceId, reason } : undefined;
172
+ }
149
173
  if (kind === 'claim') {
150
174
  const { node, socketId } = raw;
151
175
  if (!isText(tenant) || !isText(deviceId) || !isId(node) || !isText(socketId)) return undefined;
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;
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,