@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/CLAUDE.md +2 -1
- package/README.md +6 -3
- package/package.json +5 -5
- package/src/channel-authz.ts +2 -13
- package/src/channel-decl.ts +11 -2
- package/src/channel-gaps.ts +19 -1
- package/src/channel-logs.ts +28 -5
- package/src/channel-records.ts +6 -3
- package/src/channel-ref.ts +6 -3
- package/src/channel-render.ts +2 -2
- package/src/channel-ring.ts +7 -0
- package/src/channel-tenant.ts +43 -4
- package/src/channel.ts +8 -1
- package/src/client-channels.ts +3 -1
- package/src/device-bus.ts +67 -12
- package/src/device-errors.ts +19 -4
- package/src/device-hooks.ts +141 -0
- package/src/device-host.ts +54 -16
- package/src/device-ledger.ts +153 -0
- package/src/device-socket.ts +56 -1
- package/src/device-wire.ts +25 -1
- package/src/fanout.ts +32 -2
- package/src/index.ts +1 -1
- package/src/page-socket.ts +1 -1
- package/src/page-store.ts +11 -0
- package/src/policy-gate.ts +37 -2
- package/src/server.ts +8 -2
- package/src/socket.ts +7 -23
- package/src/sync-listen.ts +3 -1
package/CLAUDE.md
CHANGED
|
@@ -172,7 +172,8 @@ A rule marked `†` has its full text in [`docs/history/realtime-rules.md`](../.
|
|
|
172
172
|
- **A channel is a DECLARATION, no primitive** (docs/history/primitive-factories.md):
|
|
173
173
|
`channel(name, { params, policy, catchUp, records?, events? })`, deny by default; `policy`
|
|
174
174
|
REQUIRED (`X_CHANNEL_DECLARATION_INVALID`; public: `allow('public')`). Presence: `events`.
|
|
175
|
-
- **A
|
|
175
|
+
- **A `$tenantColumn` param is the subscriber's org; elsewhere a tenanted row reaches only its
|
|
176
|
+
tenant** (`channel-tenant.ts`). †
|
|
176
177
|
- **A guard that FAILS on re-auth SUSPENDS the seat** (`guardFailures`): kept, silent until a pass.
|
|
177
178
|
A `null` actor on a `row` channel and a tenancy refusal are DENIALS.
|
|
178
179
|
- **A seat is decided for the actor ON the socket when the guard resolves** (`#settle`); a denied
|
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
|
|
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.
|
|
3
|
+
"version": "31.50.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.
|
|
56
|
-
"@ultimat3/entity": "31.
|
|
57
|
-
"@ultimat3/policy": "31.
|
|
58
|
-
"@ultimat3/query": "31.
|
|
55
|
+
"@ultimat3/core": "31.50.0",
|
|
56
|
+
"@ultimat3/entity": "31.50.0",
|
|
57
|
+
"@ultimat3/policy": "31.50.0",
|
|
58
|
+
"@ultimat3/query": "31.50.0",
|
|
59
59
|
"nats": "2.29.3"
|
|
60
60
|
}
|
|
61
61
|
}
|
package/src/channel-authz.ts
CHANGED
|
@@ -2,11 +2,12 @@
|
|
|
2
2
|
// with the params as input and the row the channel's own loader answered. Through
|
|
3
3
|
// `@ultimat3/query`'s `guardQuery`, the package's one authz seam — the call `policy-gate.ts` makes.
|
|
4
4
|
|
|
5
|
-
import { type Actor, type Ctx,
|
|
5
|
+
import { type Actor, type Ctx, runWithContext } from '@ultimat3/core';
|
|
6
6
|
import { guardQuery, QueryDeniedError } from '@ultimat3/query';
|
|
7
7
|
import type { Channel } from './channel-decl';
|
|
8
8
|
import { assertChannelTenant } from './channel-tenant';
|
|
9
9
|
import { isTenancyDenial, TopicForbiddenError } from './errors';
|
|
10
|
+
import { subscriberContext } from './policy-gate';
|
|
10
11
|
|
|
11
12
|
/**
|
|
12
13
|
* A denial is `X_TOPIC_FORBIDDEN`. A loader or a rule that RAISED is not a denial and leaves as it
|
|
@@ -74,15 +75,3 @@ function decide(
|
|
|
74
75
|
});
|
|
75
76
|
}
|
|
76
77
|
}
|
|
77
|
-
|
|
78
|
-
/** The node's context, re-made for one subscriber: same deploy, role and clock, their actor. */
|
|
79
|
-
function subscriberContext(node: Ctx, actor: Actor): Ctx {
|
|
80
|
-
return ctxOf({
|
|
81
|
-
actor,
|
|
82
|
-
role: node.role,
|
|
83
|
-
buildId: node.buildId,
|
|
84
|
-
clock: node.clock,
|
|
85
|
-
locale: node.locale,
|
|
86
|
-
tz: node.tz,
|
|
87
|
-
});
|
|
88
|
-
}
|
package/src/channel-decl.ts
CHANGED
|
@@ -72,8 +72,8 @@ export interface ChannelServerInit {
|
|
|
72
72
|
* Evaluated on subscribe: the params are the input, and `row` is what the loader below answered
|
|
73
73
|
* (`null` without one). REQUIRED, as on an `action` and a `query`: it was optional, and an omitted
|
|
74
74
|
* one let any socket — anonymous included — join with any param and receive every committed row.
|
|
75
|
-
* A public channel says so with `allow('public')`. Records are NOT gated per row
|
|
76
|
-
* params are
|
|
75
|
+
* A public channel says so with `allow('public')`. Records are NOT gated per row by the policy —
|
|
76
|
+
* the topic's params are its scope; only a row's TENANT is checked per member (`rowTenant`).
|
|
77
77
|
*/
|
|
78
78
|
readonly policy: QueryPolicy;
|
|
79
79
|
/**
|
|
@@ -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) {
|
package/src/channel-gaps.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
// The repair half of a dropped `records` frame: the per-socket mark is `SyncSocket.gaps`, and this
|
|
2
2
|
// is what answers it — one `replay-gap` per (socket, topic), sent once the socket takes frames
|
|
3
|
-
// again, counted in `channel_replay_gaps_total` beside `channel_frames_dropped_total
|
|
3
|
+
// again, counted in `channel_replay_gaps_total` beside `channel_frames_dropped_total` (declared
|
|
4
|
+
// here too; `socket.ts` counts the drops).
|
|
4
5
|
|
|
5
6
|
import { type Counter, counter } from '@ultimat3/core';
|
|
6
7
|
import type { ReplayGapFrame } from './channel-wire';
|
|
@@ -16,6 +17,23 @@ const channelReplayGaps: Counter = counter('channel_replay_gaps_total', {
|
|
|
16
17
|
description: 'replay-gap frames delivered to a socket that lost a channel records frame',
|
|
17
18
|
});
|
|
18
19
|
|
|
20
|
+
/**
|
|
21
|
+
* Channel frames this process dropped under backpressure. A dropped `records` frame is now marked
|
|
22
|
+
* and REPAIRED — the socket is sent `replay-gap` once it drains and re-reads the channel's catch-up
|
|
23
|
+
* query (`channel_replay_gaps_total` counts those) — while a dropped `events` frame is ephemeral
|
|
24
|
+
* by definition and is only counted. The two series side by side are the whole delivery story.
|
|
25
|
+
*
|
|
26
|
+
* Declared here rather than in `@ultimat3/core`'s `runtime-metrics.ts` because that file is the
|
|
27
|
+
* series EVERY Ultimate process emits and the deploy chart scales on; this one exists only where
|
|
28
|
+
* channels do. **No attributes**: a topic is client-chosen (`topic()` admits any
|
|
29
|
+
* `[A-Za-z0-9_-]+` segment), so a per-topic label is an unbounded series count one socket can mint
|
|
30
|
+
* — the topic goes in the log line, where cardinality is somebody else's index.
|
|
31
|
+
*/
|
|
32
|
+
export const channelFramesDropped: Counter = counter('channel_frames_dropped_total', {
|
|
33
|
+
unit: '{frame}',
|
|
34
|
+
description: 'Channel frames dropped by socket backpressure',
|
|
35
|
+
});
|
|
36
|
+
|
|
19
37
|
export class GapRepairs {
|
|
20
38
|
#announced = 0;
|
|
21
39
|
|
package/src/channel-logs.ts
CHANGED
|
@@ -7,7 +7,8 @@ import type { ChangeEvent } from './changefeed';
|
|
|
7
7
|
import type { Channel } from './channel-decl';
|
|
8
8
|
import { carriesTable, updatesFor } from './channel-records';
|
|
9
9
|
import { renderRecords } from './channel-render';
|
|
10
|
-
import { ChannelRing } from './channel-ring';
|
|
10
|
+
import { ChannelRing, type RecordsEntry } from './channel-ring';
|
|
11
|
+
import { type Audience, admitsTenant, rowTenant } from './channel-tenant';
|
|
11
12
|
import type { ChannelSince, ReplayGapFrame } from './channel-wire';
|
|
12
13
|
import type { SocketRegistry, SyncSocket } from './socket';
|
|
13
14
|
import { PROTOCOL_VERSION } from './sync-protocol';
|
|
@@ -79,9 +80,19 @@ export class ChannelLogs {
|
|
|
79
80
|
frames += this.#reopen(update.topic, open.target);
|
|
80
81
|
continue;
|
|
81
82
|
}
|
|
82
|
-
const
|
|
83
|
-
const
|
|
84
|
-
|
|
83
|
+
const tenant = rowTenant(update.channel, change.table, update.row);
|
|
84
|
+
const write = change.write ?? undefined;
|
|
85
|
+
const entry = open.ring.append(update.adopt, update.remove, write, tenant);
|
|
86
|
+
const epoch = open.ring.epoch;
|
|
87
|
+
const frame = renderRecords(update.topic, epoch, entry);
|
|
88
|
+
const audience: Audience | undefined =
|
|
89
|
+
tenant === undefined
|
|
90
|
+
? undefined
|
|
91
|
+
: {
|
|
92
|
+
admits: (actor) => admitsTenant(actor, tenant),
|
|
93
|
+
withheld: renderRecords(update.topic, epoch, withheld(entry)),
|
|
94
|
+
};
|
|
95
|
+
frames += this.#sockets.deliverRecords(update.topic, epoch, frame, audience);
|
|
85
96
|
}
|
|
86
97
|
return frames;
|
|
87
98
|
}
|
|
@@ -127,6 +138,9 @@ export class ChannelLogs {
|
|
|
127
138
|
* A `since` that is already CURRENT is answered too: the frame AT its cursor, carrying nothing.
|
|
128
139
|
* Sent nothing, the client had no frame to leave `joining` on — a channel that was up to date
|
|
129
140
|
* read as never joined. The seq is one it already holds, so its cursor does not move.
|
|
141
|
+
*
|
|
142
|
+
* A replayed entry holding another tenant's rows (`RecordsEntry.tenant`) is sent as its seq alone,
|
|
143
|
+
* exactly as the live frame was: a later joiner is never shown what a live member was not.
|
|
130
144
|
*/
|
|
131
145
|
resume(socket: SyncSocket, topic: string, since: ChannelSince | undefined, fresh: boolean): void {
|
|
132
146
|
const open = this.#byTopic.get(topic);
|
|
@@ -146,10 +160,19 @@ export class ChannelLogs {
|
|
|
146
160
|
}
|
|
147
161
|
const answer = entries.length > 0 ? entries : [{ seq: open.ring.seq, adopt: [], remove: [] }];
|
|
148
162
|
for (const entry of answer) {
|
|
149
|
-
|
|
163
|
+
const shown = admitsTenant(socket.actor, entry.tenant) ? entry : withheld(entry);
|
|
164
|
+
if (!socket.send(renderRecords(topic, open.ring.epoch, shown))) {
|
|
150
165
|
socket.gaps.set(topic, open.ring.epoch);
|
|
151
166
|
return;
|
|
152
167
|
}
|
|
153
168
|
}
|
|
154
169
|
}
|
|
155
170
|
}
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* One entry as a member outside its tenant receives it: the seq, so the cursor stays contiguous and
|
|
174
|
+
* no `replay-gap` is owed, and nothing else — no row, no key, and no write id to match an echo on.
|
|
175
|
+
*/
|
|
176
|
+
function withheld(entry: RecordsEntry): RecordsEntry {
|
|
177
|
+
return { seq: entry.seq, adopt: [], remove: [] };
|
|
178
|
+
}
|
package/src/channel-records.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// A committed change → the record updates each declared channel owes its subscribers. Pure: no
|
|
2
|
-
// socket, no seq, no policy — `ChannelHub` does those per node and per socket. The only
|
|
3
|
-
// of "which channel carries this row" lives here, so a write never names a channel
|
|
2
|
+
// socket, no seq, no policy, no tenant — `ChannelHub` does those per node and per socket. The only
|
|
3
|
+
// derivation of "which channel carries this row" lives here, so a write never names a channel.
|
|
4
4
|
|
|
5
5
|
import { type Counter, counter, logger } from '@ultimat3/core';
|
|
6
6
|
import type { Row } from '@ultimat3/core/page';
|
|
@@ -9,7 +9,10 @@ import type { ChangeEvent } from './changefeed';
|
|
|
9
9
|
import type { Channel, Topic } from './channel-decl';
|
|
10
10
|
import type { RecordPart } from './channel-ring';
|
|
11
11
|
|
|
12
|
-
/**
|
|
12
|
+
/**
|
|
13
|
+
* One topic's share of one change. `row` is the image it came from: no policy re-decides it, but
|
|
14
|
+
* its tenant decides which of the topic's members are shown it (`rowTenant`, `channel-tenant.ts`).
|
|
15
|
+
*/
|
|
13
16
|
export interface TopicUpdate {
|
|
14
17
|
readonly channel: Channel;
|
|
15
18
|
readonly topic: Topic;
|
package/src/channel-ref.ts
CHANGED
|
@@ -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
|
|
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
|
|
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
|
}
|
package/src/channel-render.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
// One ring entry → the `records` frame
|
|
2
|
-
//
|
|
1
|
+
// One ring entry → the `records` frame its topic's members receive. The same frame for all of them,
|
|
2
|
+
// but for an entry holding another tenant's rows (`RecordsEntry.tenant`): that member gets its seq.
|
|
3
3
|
|
|
4
4
|
import type { Row } from '@ultimat3/core/page';
|
|
5
5
|
import type { RecordsEntry } from './channel-ring';
|
package/src/channel-ring.ts
CHANGED
|
@@ -12,6 +12,11 @@ export interface RecordsEntry {
|
|
|
12
12
|
readonly remove: readonly { readonly type: string; readonly key: string }[];
|
|
13
13
|
/** The write that produced the change (`ChangeEvent.write`), kept so a replay still names it. */
|
|
14
14
|
readonly write?: string;
|
|
15
|
+
/**
|
|
16
|
+
* Present when the rows are one tenant's on a topic that is not that tenant's (`rowTenant`): only
|
|
17
|
+
* its members are shown them, live or replayed. `null`: the row named no tenant — nobody is.
|
|
18
|
+
*/
|
|
19
|
+
readonly tenant?: string | null;
|
|
15
20
|
}
|
|
16
21
|
|
|
17
22
|
export interface RecordPart {
|
|
@@ -48,6 +53,7 @@ export class ChannelRing {
|
|
|
48
53
|
adopt: readonly RecordPart[],
|
|
49
54
|
remove: RecordsEntry['remove'],
|
|
50
55
|
write?: string,
|
|
56
|
+
tenant?: string | null,
|
|
51
57
|
): RecordsEntry {
|
|
52
58
|
this.#seq += 1;
|
|
53
59
|
const entry: RecordsEntry = {
|
|
@@ -55,6 +61,7 @@ export class ChannelRing {
|
|
|
55
61
|
adopt,
|
|
56
62
|
remove,
|
|
57
63
|
...(write === undefined ? {} : { write }),
|
|
64
|
+
...(tenant === undefined ? {} : { tenant }),
|
|
58
65
|
};
|
|
59
66
|
this.#entries.push(entry);
|
|
60
67
|
if (this.#entries.length > this.#capacity) this.#entries.shift();
|
package/src/channel-tenant.ts
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
|
-
// The tenant half of a channel
|
|
2
|
-
//
|
|
3
|
-
//
|
|
1
|
+
// The tenant half of a channel: a param that names a records entity's tenant column must be the
|
|
2
|
+
// subscriber's own org, decided at subscribe by `@ultimat3/entity`'s own guard (`assertScoped`); a
|
|
3
|
+
// tenanted row on a topic NOT keyed by its tenant column reaches only that tenant's members.
|
|
4
4
|
|
|
5
5
|
import { type Actor, type Ctx, isUltimateError, runWithContext } from '@ultimat3/core';
|
|
6
6
|
import { assertScoped, type QueryPlan } from '@ultimat3/entity';
|
|
7
|
-
import { tenantColumnOfTable } from './change-tenant';
|
|
7
|
+
import { tenantColumnOfTable, tenantIn } from './change-tenant';
|
|
8
8
|
import type { Channel } from './channel-decl';
|
|
9
|
+
import type { ChannelRecordsFrame } from './channel-wire';
|
|
9
10
|
import { isTenancyDenial, TopicForbiddenError } from './errors';
|
|
10
11
|
|
|
11
12
|
/**
|
|
@@ -53,3 +54,41 @@ export function assertChannelTenant(
|
|
|
53
54
|
}
|
|
54
55
|
}
|
|
55
56
|
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Who may read one change's rows on `channel`: `undefined` for everyone on the topic — an untenanted
|
|
60
|
+
* table, or a channel keyed by the tenant column, whose subscribe already proved the tenant
|
|
61
|
+
* (`assertChannelTenant`) — else the tenant `row` names, `null` when it names none (no member).
|
|
62
|
+
*
|
|
63
|
+
* A topic keyed by `roomId` carries every org's rows that name that room, and its policy decided a
|
|
64
|
+
* permission, not a tenant: `can('message:read')` admitted org A to org B's room. The subscribe
|
|
65
|
+
* cannot decide this (the rows are not known yet), so delivery and ring replay do, per row.
|
|
66
|
+
*/
|
|
67
|
+
export function rowTenant(
|
|
68
|
+
channel: Channel,
|
|
69
|
+
table: string,
|
|
70
|
+
row: Readonly<Record<string, unknown>>,
|
|
71
|
+
): string | null | undefined {
|
|
72
|
+
const column = tenantColumnOfTable(table);
|
|
73
|
+
if (column === null || channel.params.includes(column)) return undefined;
|
|
74
|
+
return tenantIn(column, row);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* `assertScoped`'s verdict for a plan naming `tenant`, without a context to run it in: the actor's
|
|
79
|
+
* own org, and nothing else. A `crossTenant()` scope is never open around a delivery — it is a
|
|
80
|
+
* change, not a call — so there is no proof of one to honour here.
|
|
81
|
+
*/
|
|
82
|
+
export function admitsTenant(actor: Actor | null, tenant: string | null | undefined): boolean {
|
|
83
|
+
if (tenant === undefined) return true;
|
|
84
|
+
return tenant !== null && actor !== null && actor.orgId !== undefined && actor.orgId === tenant;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* A records frame's audience when it carries one tenant's rows (`rowTenant`): a member `admits`
|
|
89
|
+
* takes gets the frame, every other member `withheld` — the same seq, carrying nothing.
|
|
90
|
+
*/
|
|
91
|
+
export interface Audience {
|
|
92
|
+
readonly admits: (actor: Actor | null) => boolean;
|
|
93
|
+
readonly withheld: ChannelRecordsFrame;
|
|
94
|
+
}
|
package/src/channel.ts
CHANGED
|
@@ -449,7 +449,14 @@ export class ChannelHub {
|
|
|
449
449
|
bridge.sub ??= this.#transport.subscribe(channelSubject(name), (payload) => {
|
|
450
450
|
this.#sockets.deliver(name, decode(payload));
|
|
451
451
|
});
|
|
452
|
-
|
|
452
|
+
const opening = bridge.sub;
|
|
453
|
+
try {
|
|
454
|
+
await opening;
|
|
455
|
+
} catch (error) {
|
|
456
|
+
// Forgotten once answered: kept, it refused every later subscriber while any seat held it.
|
|
457
|
+
if (bridge.sub === opening) bridge.sub = null;
|
|
458
|
+
throw error;
|
|
459
|
+
}
|
|
453
460
|
// The hub shut down while the transport was answering. `close()` either never saw this bridge
|
|
454
461
|
// or saw it with nothing to close, so this is the last reference to the subscription: it closes
|
|
455
462
|
// here or never. The entry goes with it, so a second post-close subscribe opens and closes its
|
package/src/client-channels.ts
CHANGED
|
@@ -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
|
-
|
|
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(
|
|
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(
|
|
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
|
-
|
|
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);
|
package/src/device-errors.ts
CHANGED
|
@@ -26,13 +26,28 @@ export class DeviceOfflineError extends RealtimeError {
|
|
|
26
26
|
}
|
|
27
27
|
}
|
|
28
28
|
|
|
29
|
-
/**
|
|
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: {
|
|
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:
|
|
35
|
-
|
|
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
|
}
|