@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.
@@ -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;