@ultimat3/realtime 31.18.1 → 31.20.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 +6 -4
- package/README.md +6 -2
- package/package.json +5 -5
- package/src/nats-transport.ts +17 -3
- package/src/sync-auth.ts +13 -5
- package/src/sync-upgrade.ts +13 -8
- package/src/transport-env.ts +4 -1
package/CLAUDE.md
CHANGED
|
@@ -123,7 +123,8 @@ A rule marked `†` has its full text in [`docs/history/realtime-rules.md`](../.
|
|
|
123
123
|
`X_TRANSPORT_UNAVAILABLE`; `'publish'` dials in background. Never `waitOnFirstConnect`
|
|
124
124
|
(retries forever). A publish with no live connection is refused.
|
|
125
125
|
- **`nats` is imported only by `nats-lib-client.ts`**; its reconnect re-subscribes. GIVEN UP
|
|
126
|
-
(`onClosed`), `NatsTransport` re-dials on backoff and re-binds
|
|
126
|
+
(`onClosed`), `NatsTransport` re-dials on backoff and re-binds; the backoff wait is armed on
|
|
127
|
+
its `scheduler` option, so a test fires it by hand (`ManualScheduler`) and never sleeps.
|
|
127
128
|
- **Nothing leaves `NatsTransport` uncoded** — `#translating` wraps `publish`/`subscribe` refusals
|
|
128
129
|
as `X_TRANSPORT_UNAVAILABLE`. `#ensure` reuses a mid-reconnect client on purpose;
|
|
129
130
|
`Transport.onReconnect(listener)` (required) announces each recovery.
|
|
@@ -148,12 +149,13 @@ A rule marked `†` has its full text in [`docs/history/realtime-rules.md`](../.
|
|
|
148
149
|
- Presence lives in `transport.shared`; the sync node is `PresenceRegistry`'s only caller, and
|
|
149
150
|
**one node per topic sweeps**. Detail: `docs/history/realtime-agent-notes.md`.
|
|
150
151
|
- **A socket's actor comes from `syncNode({ authenticate })` only**, run before
|
|
151
|
-
`server.upgrade`. `null`
|
|
152
|
-
`X_SOCKET_AUTH_UNAVAILABLE`. Absent = anonymous, and `start()` warns. The actor lives only in the
|
|
152
|
+
`server.upgrade`. `null` or a thrown session refusal (`isSessionRefusal`) = 401
|
|
153
|
+
`X_SOCKET_UNAUTHENTICATED`; any other throw = 503 `X_SOCKET_AUTH_UNAVAILABLE`. Absent = anonymous, and `start()` warns. The actor lives only in the
|
|
153
154
|
`GrantBook`.
|
|
154
155
|
- **The grant is recorded BEFORE `server.upgrade`**; `onUngranted` is REQUIRED on `UpgradeDeps`. †
|
|
155
156
|
- **A grant expires; a socket does not**: expired grants are re-decided on an interval
|
|
156
|
-
(`hub.onActorChange`, `registry.reauthorize`). No `refresh` = close `1008`; one that raises retries
|
|
157
|
+
(`hub.onActorChange`, `registry.reauthorize`). No `refresh` = close `1008`; one that raises retries,
|
|
158
|
+
except a session refusal, which closes `1008` like `null`.
|
|
157
159
|
- **Inbound frames run in a lane, never the socket**: `subscribe` is `sub:<sid>` or `topic:<name>`,
|
|
158
160
|
everything else unlaned (`frame-lanes.ts`); a lane exists only while work is queued.
|
|
159
161
|
- **A dropped `records` frame is counted AND repaired**: per-node `seq`/`epoch` per channel; a refused
|
package/README.md
CHANGED
|
@@ -347,7 +347,8 @@ const options: Pick<SyncNodeOptions, 'authenticate'> = {
|
|
|
347
347
|
|---|---|
|
|
348
348
|
| a `SyncGrant` | upgrades, and the socket carries `grant.actor` |
|
|
349
349
|
| `null` | **401** `X_SOCKET_UNAUTHENTICATED` — a decision, and the client's own condition |
|
|
350
|
-
| a
|
|
350
|
+
| a thrown session refusal (`X_UNAUTHENTICATED`, `X_SESSION_EXPIRED`: core's `isSessionRefusal`) | the same as `null` — what `@ultimat3/auth`'s `authenticate()` throws for a signed-out, expired or forged cookie |
|
|
351
|
+
| any other throw | **503** `X_SOCKET_AUTH_UNAVAILABLE` — a failure, reported, and the client is told to retry |
|
|
351
352
|
| the option is absent | upgrades **anonymous**, and `start()` warns: every policy on that node is being asked about `null` |
|
|
352
353
|
|
|
353
354
|
`expiresAt` is the half a long-lived socket needs: the node re-decides an expired grant on an
|
|
@@ -355,7 +356,8 @@ interval (`reauthenticateIntervalMs`, 30s), calling `refresh` and then `hub.onAc
|
|
|
355
356
|
`registry.reauthorize` — so a revoked role drops the topics and subscriptions it no longer covers,
|
|
356
357
|
and survivors are re-snapshotted under the new authority. No `refresh`, and an expired grant closes
|
|
357
358
|
the socket with `1008`; the client re-dials with a fresh credential. A `refresh` that *raises* keeps
|
|
358
|
-
the socket and retries next pass — a token service timing out is not a revocation.
|
|
359
|
+
the socket and retries next pass — a token service timing out is not a revocation. A raised session
|
|
360
|
+
refusal is the exception: it IS a revocation, and closes the socket with `1008` like `null` does.
|
|
359
361
|
|
|
360
362
|
**Without `authenticate` this node is single-tenant.** Every actor is `null`, so
|
|
361
363
|
`hub.guard('org.*.feed', ({ actor }) => actor?.orgId === …)` denies everyone and the only guard that
|
|
@@ -874,6 +876,8 @@ made it — a key already queued collapses as always, and nothing queued is ever
|
|
|
874
876
|
asserts the KV bucket when `shared` is first read instead of at the dial, so a publisher needs no
|
|
875
877
|
JetStream. The first dial is ONE attempt of the library's — `waitOnFirstConnect` is not set,
|
|
876
878
|
because under it nats@2.29.3 retries a failed first dial forever and the promise never settles.
|
|
879
|
+
`scheduler` (a `Scheduler`, default `timeoutScheduler`) arms the re-dial loop's backoff wait: a
|
|
880
|
+
test hands a manual one and fires each wait itself, so no test of the loop sleeps.
|
|
877
881
|
- **`NatsTransport` runs on the official `nats` client** — `nats@2.29.3`, pinned exact, admitted at
|
|
878
882
|
this transport seam and nowhere else
|
|
879
883
|
([`docs/idea/18-build-vs-wrap.md`](../../docs/idea/18-build-vs-wrap.md)). The package reaches it
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ultimat3/realtime",
|
|
3
|
-
"version": "31.
|
|
3
|
+
"version": "31.20.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.20.0",
|
|
56
|
+
"@ultimat3/entity": "31.20.0",
|
|
57
|
+
"@ultimat3/policy": "31.20.0",
|
|
58
|
+
"@ultimat3/query": "31.20.0",
|
|
59
59
|
"nats": "2.29.3"
|
|
60
60
|
}
|
|
61
61
|
}
|
package/src/nats-transport.ts
CHANGED
|
@@ -26,7 +26,14 @@ import { NatsKvSet } from './nats-kv';
|
|
|
26
26
|
import { openNatsClient } from './nats-open';
|
|
27
27
|
import { NatsReports } from './nats-reports';
|
|
28
28
|
import { NatsSubscriptions } from './nats-subscriptions';
|
|
29
|
-
import {
|
|
29
|
+
import {
|
|
30
|
+
defaultBackoff,
|
|
31
|
+
policyDelay,
|
|
32
|
+
type ReconnectBackoff,
|
|
33
|
+
type Rng,
|
|
34
|
+
type Scheduler,
|
|
35
|
+
timeoutScheduler,
|
|
36
|
+
} from './thundering-herd';
|
|
30
37
|
|
|
31
38
|
const encoder = new TextEncoder();
|
|
32
39
|
const decoder = new TextDecoder();
|
|
@@ -43,6 +50,11 @@ export interface NatsTransportOptions {
|
|
|
43
50
|
/** A failing subscriber, or a connection lost in the background, must not break the process. */
|
|
44
51
|
readonly onError?: (error: unknown, subject: string) => void;
|
|
45
52
|
readonly rng?: Rng;
|
|
53
|
+
/**
|
|
54
|
+
* Arms the re-dial loop's backoff wait. Default `timeoutScheduler` (`setTimeout`); a test hands
|
|
55
|
+
* a manual one and fires the wait itself, so a backoff is a delay it names, not one it sleeps.
|
|
56
|
+
*/
|
|
57
|
+
readonly scheduler?: Scheduler;
|
|
46
58
|
/** Injected so the whole transport — reconnect included — runs in a test with no network. */
|
|
47
59
|
readonly connect?: NatsConnect;
|
|
48
60
|
/**
|
|
@@ -73,6 +85,7 @@ export class NatsTransport implements Transport {
|
|
|
73
85
|
readonly #backoff: ReconnectBackoff;
|
|
74
86
|
readonly #attempts: number;
|
|
75
87
|
readonly #rng: Rng;
|
|
88
|
+
readonly #schedule: Scheduler;
|
|
76
89
|
#client: NatsClient | undefined;
|
|
77
90
|
#dialing: Promise<NatsClient> | undefined;
|
|
78
91
|
#retries = 0;
|
|
@@ -112,6 +125,7 @@ export class NatsTransport implements Transport {
|
|
|
112
125
|
options.maxReconnectAttempts ?? DEFAULT_ATTEMPTS,
|
|
113
126
|
);
|
|
114
127
|
this.#rng = options.rng ?? Math.random;
|
|
128
|
+
this.#schedule = options.scheduler ?? timeoutScheduler;
|
|
115
129
|
this.#dialTimeoutMs = finiteOption(
|
|
116
130
|
'createNatsTransport',
|
|
117
131
|
'dialTimeoutMs',
|
|
@@ -402,11 +416,11 @@ export class NatsTransport implements Transport {
|
|
|
402
416
|
#pause(ms: number): Promise<void> {
|
|
403
417
|
return new Promise((resolve) => {
|
|
404
418
|
const done = (): void => {
|
|
405
|
-
|
|
419
|
+
cancel();
|
|
406
420
|
this.#wakeRedial = undefined;
|
|
407
421
|
resolve();
|
|
408
422
|
};
|
|
409
|
-
const
|
|
423
|
+
const cancel = this.#schedule(done, ms);
|
|
410
424
|
this.#wakeRedial = done;
|
|
411
425
|
});
|
|
412
426
|
}
|
package/src/sync-auth.ts
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
// holds it, and the pass that re-decides one whose window has closed.
|
|
4
4
|
|
|
5
5
|
import type { Actor, Clock } from '@ultimat3/core';
|
|
6
|
-
import { finiteOption } from '@ultimat3/core';
|
|
6
|
+
import { finiteOption, isSessionRefusal } from '@ultimat3/core';
|
|
7
7
|
import { GrantRefreshTimeoutError } from './errors';
|
|
8
8
|
import { type Scheduler, timeoutScheduler } from './thundering-herd';
|
|
9
9
|
|
|
@@ -38,7 +38,9 @@ export interface SyncGrant {
|
|
|
38
38
|
* refused credential never costs a websocket. `null` is a decision (nobody may open this socket);
|
|
39
39
|
* a throw is a failure (nothing was decided) — the node answers those differently, because reading
|
|
40
40
|
* an auth backend timeout as a denial is the same class of bug as reading a dead pool as a row
|
|
41
|
-
* policy refusing a row.
|
|
41
|
+
* policy refusing a row. One throw IS a decision: a session refusal (`isSessionRefusal`, core's
|
|
42
|
+
* one list — `X_UNAUTHENTICATED`, `X_SESSION_EXPIRED`), which `@ultimat3/auth`'s `authenticate()`
|
|
43
|
+
* raises for a revoked, expired or forged cookie. It is answered exactly as `null` is.
|
|
42
44
|
*/
|
|
43
45
|
export type SyncAuthenticator = (request: Request) => Promise<SyncGrant | null>;
|
|
44
46
|
|
|
@@ -109,6 +111,9 @@ export interface GrantSweepResult {
|
|
|
109
111
|
* the one it would be responding to. It stays expired, so the next pass retries it — and every
|
|
110
112
|
* failure is reported, because a socket that cannot be re-decided is not a socket anyone should
|
|
111
113
|
* discover from a graph of connection counts.
|
|
114
|
+
*
|
|
115
|
+
* Except a session refusal, which is a denial that happens to arrive as a throw: read as a failure,
|
|
116
|
+
* a socket opened with a cookie that was then signed out kept streaming under its actor.
|
|
112
117
|
*/
|
|
113
118
|
export async function sweepGrants(deps: GrantSweepDeps): Promise<GrantSweepResult> {
|
|
114
119
|
const now = deps.clock.now().getTime();
|
|
@@ -127,9 +132,12 @@ export async function sweepGrants(deps: GrantSweepDeps): Promise<GrantSweepResul
|
|
|
127
132
|
try {
|
|
128
133
|
next = grant.refresh ? await within(grant.refresh(), socketId, deadlineMs, schedule) : null;
|
|
129
134
|
} catch (error) {
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
135
|
+
if (!isSessionRefusal(error)) {
|
|
136
|
+
failed += 1;
|
|
137
|
+
deps.onRefreshFailed?.(socketId, error);
|
|
138
|
+
continue;
|
|
139
|
+
}
|
|
140
|
+
next = null;
|
|
133
141
|
}
|
|
134
142
|
// Asked again, because `refresh` is the app's and awaiting it is awaiting a token service: the
|
|
135
143
|
// socket may have closed meanwhile (its grant deleted) or been re-granted. Written back
|
package/src/sync-upgrade.ts
CHANGED
|
@@ -8,6 +8,7 @@ import {
|
|
|
8
8
|
healthBody,
|
|
9
9
|
healthPeerListed,
|
|
10
10
|
healthzPayload,
|
|
11
|
+
isSessionRefusal,
|
|
11
12
|
readyzPayload,
|
|
12
13
|
reportError,
|
|
13
14
|
} from '@ultimat3/core';
|
|
@@ -171,14 +172,18 @@ async function answerUpgrade(
|
|
|
171
172
|
try {
|
|
172
173
|
grant = await deps.authenticate(request);
|
|
173
174
|
} catch (error) {
|
|
174
|
-
// A
|
|
175
|
-
//
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
175
|
+
// A session refusal IS a denial that arrived as a throw (`sync-auth.ts`): answered 503, the
|
|
176
|
+
// client re-dials with the same dead cookie forever. It falls through to the `null` branch.
|
|
177
|
+
if (!isSessionRefusal(error)) {
|
|
178
|
+
// A failure is not a denial. The token service timing out must not read to a client as
|
|
179
|
+
// "you may not connect" — it is told to come back, and this node is the one that pages.
|
|
180
|
+
reportError(error, { source: 'realtime', scope: { operation: 'sync.authenticate' } });
|
|
181
|
+
refund();
|
|
182
|
+
return wireErrorResponse(
|
|
183
|
+
503,
|
|
184
|
+
new SocketAuthUnavailableError({ detail: 'see the node log for the cause' }),
|
|
185
|
+
);
|
|
186
|
+
}
|
|
182
187
|
}
|
|
183
188
|
// The decision, made before a socket exists: an upgrade is the cheapest thing to refuse and the
|
|
184
189
|
// most expensive thing to take back.
|
package/src/transport-env.ts
CHANGED
|
@@ -11,7 +11,7 @@ import { InProcessTransport } from './fanout';
|
|
|
11
11
|
import type { NatsConnect } from './nats-client';
|
|
12
12
|
import { assertBucket } from './nats-jetstream';
|
|
13
13
|
import { NatsTransport } from './nats-transport';
|
|
14
|
-
import type { ReconnectBackoff } from './thundering-herd';
|
|
14
|
+
import type { ReconnectBackoff, Scheduler } from './thundering-herd';
|
|
15
15
|
|
|
16
16
|
/**
|
|
17
17
|
* The keys read here, and nothing else. Named once so docs and tests cannot drift from the code.
|
|
@@ -94,6 +94,8 @@ export interface SelectTransportOptions {
|
|
|
94
94
|
readonly connectWithinMs?: number | undefined;
|
|
95
95
|
/** The dial's retry curve; the transport's own default when unset. */
|
|
96
96
|
readonly backoff?: ReconnectBackoff | undefined;
|
|
97
|
+
/** Arms the dial loop's backoff wait (`NatsTransportOptions.scheduler`); `setTimeout` when unset. */
|
|
98
|
+
readonly scheduler?: Scheduler | undefined;
|
|
97
99
|
/** Where the transport's background failures go; its own logger line when unset. */
|
|
98
100
|
readonly onError?: ((error: unknown, subject: string) => void) | undefined;
|
|
99
101
|
}
|
|
@@ -154,6 +156,7 @@ export function selectTransport(
|
|
|
154
156
|
...(options.clock === undefined ? {} : { clock: options.clock }),
|
|
155
157
|
...(options.connect === undefined ? {} : { connect: options.connect }),
|
|
156
158
|
...(options.backoff === undefined ? {} : { backoff: options.backoff }),
|
|
159
|
+
...(options.scheduler === undefined ? {} : { scheduler: options.scheduler }),
|
|
157
160
|
...(options.onError === undefined ? {} : { onError: options.onError }),
|
|
158
161
|
});
|
|
159
162
|
const withinMs = finiteOption(
|