@dammers/use-signalr-core 0.5.0 → 1.1.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 +18 -67
- package/dist/calls.d.ts +50 -35
- package/dist/calls.js +85 -72
- package/dist/config.d.ts +8 -7
- package/dist/config.js +71 -17
- package/dist/connection-manager.d.ts +15 -13
- package/dist/connection-manager.js +187 -108
- package/dist/context.d.ts +44 -19
- package/dist/errors.d.ts +9 -0
- package/dist/errors.js +16 -0
- package/dist/hub-entry.d.ts +2 -5
- package/dist/index.d.ts +5 -10
- package/dist/index.js +1 -3
- package/dist/retry.d.ts +3 -29
- package/dist/retry.js +5 -31
- package/dist/session.d.ts +31 -14
- package/dist/session.js +210 -30
- package/dist/status-store.d.ts +3 -1
- package/dist/timers.d.ts +2 -0
- package/dist/timers.js +2 -0
- package/dist/types.d.ts +109 -48
- package/package.json +9 -7
package/README.md
CHANGED
|
@@ -1,84 +1,35 @@
|
|
|
1
1
|
# @dammers/use-signalr-core
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The framework-free core of [use-signalr](https://use-signalr.vercel.app): connection lifecycle, the hub contract, recovery, and call helpers for typed [SignalR](https://learn.microsoft.com/aspnet/core/signalr).
|
|
4
4
|
|
|
5
5
|
[](https://www.npmjs.com/package/@dammers/use-signalr-core)
|
|
6
|
-
](./LICENSE)
|
|
6
|
+
[](https://github.com/DammersCode/use-signalr/blob/main/LICENSE)
|
|
8
7
|
|
|
9
|
-
|
|
8
|
+
This package is for adapter authors. To use SignalR in an app, install the adapter for your framework:
|
|
10
9
|
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
- [`@dammers/use-signalr-preact`](https://github.com/DammersCode/use-signalr/blob/main/packages/preact/README.md)
|
|
21
|
-
- [`@dammers/use-signalr-lit`](https://github.com/DammersCode/use-signalr/blob/main/packages/lit/README.md)
|
|
10
|
+
| Package | Framework |
|
|
11
|
+
| --- | --- |
|
|
12
|
+
| [`@dammers/use-signalr-react`](https://use-signalr.vercel.app/docs/react) | React |
|
|
13
|
+
| [`@dammers/use-signalr-vue`](https://use-signalr.vercel.app/docs/vue) | Vue |
|
|
14
|
+
| [`@dammers/use-signalr-angular`](https://use-signalr.vercel.app/docs/angular) | Angular |
|
|
15
|
+
| [`@dammers/use-signalr-svelte`](https://use-signalr.vercel.app/docs/svelte) | Svelte |
|
|
16
|
+
| [`@dammers/use-signalr-preact`](https://use-signalr.vercel.app/docs/preact) | Preact |
|
|
17
|
+
| [`@dammers/use-signalr-solid`](https://use-signalr.vercel.app/docs/solid) | Solid |
|
|
18
|
+
| [`@dammers/use-signalr-lit`](https://use-signalr.vercel.app/docs/lit) | Lit |
|
|
22
19
|
|
|
23
20
|
## Install
|
|
24
21
|
|
|
25
22
|
```bash
|
|
26
|
-
npm
|
|
23
|
+
npm install @dammers/use-signalr-core @microsoft/signalr
|
|
27
24
|
```
|
|
28
25
|
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
## The adapter entry point
|
|
32
|
-
|
|
33
|
-
`createSignalRSession(deps)` is the one call an adapter builds its provider around. It owns the connection generation, lazy ref counts, grace periods, reconnect fan-out, and the context value.
|
|
34
|
-
|
|
35
|
-
```ts
|
|
36
|
-
import { createSignalRSession } from "@dammers/use-signalr-core";
|
|
37
|
-
|
|
38
|
-
const session = createSignalRSession({
|
|
39
|
-
hubs, // the hub paths from the config
|
|
40
|
-
resolve, // (hub) => ResolvedHubConfig
|
|
41
|
-
statusStore, // the adapter's own reactive StatusStore
|
|
42
|
-
getAccessToken, // read at call time, so token rotation causes no rebuild
|
|
43
|
-
onStatusChange, // optional
|
|
44
|
-
onError, // optional
|
|
45
|
-
});
|
|
46
|
-
```
|
|
47
|
-
|
|
48
|
-
The session returns three members:
|
|
49
|
-
|
|
50
|
-
| Member | What it does |
|
|
51
|
-
| --- | --- |
|
|
52
|
-
| `start(baseUrl)` | Builds the live connection generation and disposes the previous one. |
|
|
53
|
-
| `stop()` | Disposes the live generation and marks every hub disconnected. Idempotent. |
|
|
54
|
-
| `context` | The value the adapter puts into its framework context. Stable identity. |
|
|
55
|
-
|
|
56
|
-
Call `start` only from a client-only lifecycle hook. `createSignalRSession` does no I/O when you construct it.
|
|
57
|
-
|
|
58
|
-
## Call helpers
|
|
59
|
-
|
|
60
|
-
An adapter maps its invoke, send, and teardown surface onto these three factories. Do not reimplement their semantics.
|
|
61
|
-
|
|
62
|
-
| Helper | What it does |
|
|
63
|
-
| --- | --- |
|
|
64
|
-
| `createInvoker(target, hub, method, getOptions, setAbort, clearAbort?)` | Request/response call: waits for a connection, retries retriable failures, rethrows business errors. |
|
|
65
|
-
| `createSender(getConnection, hub, method)` | Fire-and-forget call. Drops the call when the hub is not connected. |
|
|
66
|
-
| `createTeardownSender(deps, hub, method, getOptions)` | Reliable cleanup call: survives disposal, queues while connecting, and holds a lazy hub open until it flushes. |
|
|
67
|
-
|
|
68
|
-
`createAbortScope()` tracks every in-flight invoke `AbortController` for one consumer. Pass its `track` and `untrack` as `setAbort` and `clearAbort`. Call `abortAll` from the adapter's cleanup to abort all in-flight calls at once.
|
|
69
|
-
|
|
70
|
-
## Also exported
|
|
71
|
-
|
|
72
|
-
`event<Args>()` and `method<Args, Return?>()` declare a hub contract. `hubKeys(config)` and `resolveHubConfig(config, hubConfig)` resolve per-hub configuration against the global defaults. `isRetriableConnectError`, `isRetriableInvokeError`, `resolveBackoff`, `DEFAULT_BACKOFF`, `sleep`, and `InvokeError` are the retry building blocks.
|
|
73
|
-
|
|
74
|
-
The contract and configuration types ship with the package: `HubString`, `HubContract`, `SignalRContract`, `EventDef`, `MethodDef`, `HubDef`, `InferContract`, `EventName`, `MethodName`, `EventArgs`, `MethodArgs`, `MethodReturn`, `HubConnectionStatus`, `ReconnectConfig`, `PerHubConfig`, `SignalRClientConfig`, `ResolvedHubConfig`, `InvokeOptions`, `TeardownOptions`, `StatusStore`, `SignalRSession`, `SignalRSessionDeps`, `SignalRProviderPropsBase`, `SignalRContextValueBase`, `ConnectionManager`, `ConnectionManagerDeps`, `HubEntry`, `CallTarget`, `AbortScope`.
|
|
75
|
-
|
|
76
|
-
## More
|
|
26
|
+
It needs `@microsoft/signalr` ^8 || ^9 || ^10 || ^11 and Node 20.19 or later. It has no runtime dependencies.
|
|
77
27
|
|
|
78
|
-
|
|
28
|
+
## Documentation
|
|
79
29
|
|
|
80
|
-
|
|
30
|
+
- [Build an adapter](https://use-signalr.vercel.app/docs/core/build-an-adapter)
|
|
31
|
+
- [API reference](https://use-signalr.vercel.app/docs/core/reference/api)
|
|
81
32
|
|
|
82
33
|
## License
|
|
83
34
|
|
|
84
|
-
MIT © [DammersCode](https://github.com/DammersCode)
|
|
35
|
+
[MIT](https://github.com/DammersCode/use-signalr/blob/main/LICENSE) © [DammersCode](https://github.com/DammersCode)
|
package/dist/calls.d.ts
CHANGED
|
@@ -1,43 +1,58 @@
|
|
|
1
1
|
import type { HubConnection } from "@microsoft/signalr";
|
|
2
2
|
import type { HubString, InvokeOptions, TeardownOptions, MethodArgs, MethodName, MethodReturn, SignalRContract } from "./types.js";
|
|
3
|
-
/**
|
|
4
|
-
* Tracks every in-flight invocation of one consumer, so its cleanup aborts
|
|
5
|
-
* ALL of them — not just the most recent. Adapters pass `track`/`untrack`
|
|
6
|
-
* straight to `createInvoker` and call `abortAll` from their teardown hook.
|
|
7
|
-
*/
|
|
3
|
+
/** One shared signal for all in-flight calls of a consumer. `abort` cancels them and starts a fresh signal. */
|
|
8
4
|
export interface AbortScope {
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
5
|
+
/** Returns the current signal. Pass it as `getSignal`. */
|
|
6
|
+
signal: () => AbortSignal;
|
|
7
|
+
/** Aborts the current signal with an `AbortError`, and starts a fresh signal. */
|
|
8
|
+
abort: () => void;
|
|
12
9
|
}
|
|
13
10
|
export declare function createAbortScope(): AbortScope;
|
|
11
|
+
/** The members of the context that the invoker needs. */
|
|
14
12
|
export interface CallTarget<T extends SignalRContract> {
|
|
15
|
-
|
|
13
|
+
/** Resolves when the hub is connected. */
|
|
14
|
+
waitForConnection: (hub: keyof T & HubString, timeoutMs: number, signal?: AbortSignal) => Promise<HubConnection>;
|
|
15
|
+
/** The live `HubConnection` of the hub, or `null` when none exists. */
|
|
16
16
|
getConnection: (hub: keyof T & HubString) => HubConnection | null;
|
|
17
|
+
/** With `keepAliveOnUnmount`, a call holds a lazy hub with `acquire` and `release` until it settles. Pass both or neither. */
|
|
18
|
+
acquire?: (hub: keyof T & HubString) => void;
|
|
19
|
+
/** Lowers the count that `acquire` raised. */
|
|
20
|
+
release?: (hub: keyof T & HubString) => void;
|
|
17
21
|
}
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
*/
|
|
26
|
-
|
|
27
|
-
/**
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
*/
|
|
39
|
-
export declare function createTeardownSender<T extends SignalRContract, H extends keyof T & HubString, M extends MethodName<T, H>>(
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
22
|
+
export interface InvokerOptions<T extends SignalRContract, H extends keyof T & HubString, M extends MethodName<T, H>> {
|
|
23
|
+
/** The object that provides `waitForConnection` and `getConnection`. Pass the session context. */
|
|
24
|
+
target: CallTarget<T>;
|
|
25
|
+
/** The hub path. */
|
|
26
|
+
hub: H;
|
|
27
|
+
/** The method name. */
|
|
28
|
+
method: M;
|
|
29
|
+
/** Called at call time. Returns the `InvokeOptions` for this call. */
|
|
30
|
+
getOptions: () => InvokeOptions | undefined;
|
|
31
|
+
/** Called at call time. Aborting the returned signal aborts a call that still waits. A call that is already sent finishes. */
|
|
32
|
+
getSignal?: () => AbortSignal | undefined;
|
|
33
|
+
}
|
|
34
|
+
/** Builds the stable invoke function for one hub method. */
|
|
35
|
+
export declare function createInvoker<T extends SignalRContract, H extends keyof T & HubString, M extends MethodName<T, H>>({ target, hub, method, getOptions, getSignal, }: InvokerOptions<T, H, M>): (...args: MethodArgs<T, H, M>) => Promise<MethodReturn<T, H, M>>;
|
|
36
|
+
/** Fire-and-forget sender. It reads the connection at call time, so a teardown handler can capture it. */
|
|
37
|
+
export declare function createSender<T extends SignalRContract, H extends keyof T & HubString, M extends MethodName<T, H>>({ getConnection, hub, method, }: {
|
|
38
|
+
getConnection: (hub: H) => HubConnection | null;
|
|
39
|
+
hub: H;
|
|
40
|
+
method: M;
|
|
41
|
+
}): (...args: MethodArgs<T, H, M>) => Promise<boolean>;
|
|
42
|
+
/** Teardown sender. It acquires the hub itself, so it still works after its consumer is gone. */
|
|
43
|
+
export declare function createTeardownSender<T extends SignalRContract, H extends keyof T & HubString, M extends MethodName<T, H>>({ target: { acquire, release, waitForConnection, beginSend }, hub, method, getOptions, }: {
|
|
44
|
+
target: {
|
|
45
|
+
acquire: (hub: H) => void;
|
|
46
|
+
release: (hub: H) => void;
|
|
47
|
+
waitForConnection: (hub: H, timeoutMs: number, signal?: AbortSignal) => Promise<HubConnection>;
|
|
48
|
+
/** Tells the session that a send is pending, so `stop()` can let it finish. Pass the one from the session context. */
|
|
49
|
+
beginSend?: (hub: H) => {
|
|
50
|
+
signal: AbortSignal;
|
|
51
|
+
use: (connection: HubConnection) => void;
|
|
52
|
+
end: () => void;
|
|
53
|
+
};
|
|
54
|
+
};
|
|
55
|
+
hub: H;
|
|
56
|
+
method: M;
|
|
57
|
+
getOptions: () => TeardownOptions | undefined;
|
|
58
|
+
}): (...args: MethodArgs<T, H, M>) => Promise<boolean>;
|
package/dist/calls.js
CHANGED
|
@@ -1,101 +1,114 @@
|
|
|
1
1
|
import { HubConnectionState } from "@microsoft/signalr";
|
|
2
|
-
import {
|
|
2
|
+
import { isFinalWaitError } from "./errors.js";
|
|
3
|
+
import { MAX_TIMER_MS } from "./timers.js";
|
|
4
|
+
import { DEFAULT_BACKOFF, isRetriableInvokeError, resolveBackoff, sleep, } from "./retry.js";
|
|
3
5
|
const DEFAULT_TIMEOUT = 10000;
|
|
4
6
|
const DEFAULT_TEARDOWN_TIMEOUT = 10000;
|
|
5
7
|
export function createAbortScope() {
|
|
6
|
-
|
|
8
|
+
let controller = new AbortController();
|
|
7
9
|
return {
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
10
|
+
signal: () => controller.signal,
|
|
11
|
+
abort: () => {
|
|
12
|
+
const stale = controller;
|
|
13
|
+
controller = new AbortController();
|
|
14
|
+
stale.abort(new DOMException("The consumer unmounted, so the call was aborted.", "AbortError"));
|
|
13
15
|
},
|
|
14
16
|
};
|
|
15
17
|
}
|
|
16
|
-
/**
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
* per invocation with the new controller, so the adapter's unmount/cleanup
|
|
21
|
-
* handler can abort the in-flight call. `clearAbort` runs when that call
|
|
22
|
-
* settles, so adapters can retain only active controllers.
|
|
23
|
-
*/
|
|
24
|
-
export function createInvoker(target, hub, method, getOptions, setAbort, clearAbort) {
|
|
25
|
-
const { waitForConnection, getConnection } = target;
|
|
26
|
-
return async (...args) => {
|
|
27
|
-
const o = getOptions();
|
|
18
|
+
/** Builds the stable invoke function for one hub method. */
|
|
19
|
+
export function createInvoker({ target, hub, method, getOptions, getSignal, }) {
|
|
20
|
+
const { waitForConnection, getConnection, acquire, release } = target;
|
|
21
|
+
const attempts = async (o, args) => {
|
|
28
22
|
const timeout = o?.timeout ?? DEFAULT_TIMEOUT;
|
|
29
23
|
const retries = o?.retries ?? 0;
|
|
30
|
-
const
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
throw new InvokeError(`SignalR invoke ${hub}/${String(method)} failed after ${attempt + 1} attempts`, error, attempt + 1, retriable);
|
|
50
|
-
}
|
|
51
|
-
await sleep(resolveBackoff(o?.backoff ?? DEFAULT_BACKOFF, attempt), ac.signal);
|
|
52
|
-
attempt += 1;
|
|
53
|
-
}
|
|
24
|
+
const signal = getSignal?.() ?? new AbortController().signal;
|
|
25
|
+
let attempt = 0;
|
|
26
|
+
for (;;) {
|
|
27
|
+
try {
|
|
28
|
+
const connection = await waitForConnection(hub, timeout, signal);
|
|
29
|
+
signal.throwIfAborted();
|
|
30
|
+
return await connection.invoke(method, ...args);
|
|
31
|
+
}
|
|
32
|
+
catch (error) {
|
|
33
|
+
if (signal.aborted)
|
|
34
|
+
throw error; // abort wins: never reclassify or retry
|
|
35
|
+
const conn = getConnection(hub);
|
|
36
|
+
const forced = o?.isRetriable?.(error);
|
|
37
|
+
const retriable = forced ??
|
|
38
|
+
(isFinalWaitError(error) ? false : conn ? isRetriableInvokeError(error, conn) : true);
|
|
39
|
+
if (!retriable || attempt >= retries)
|
|
40
|
+
throw error;
|
|
41
|
+
await sleep(resolveBackoff(o?.backoff ?? DEFAULT_BACKOFF, attempt), signal);
|
|
42
|
+
attempt += 1;
|
|
54
43
|
}
|
|
55
44
|
}
|
|
45
|
+
};
|
|
46
|
+
return async (...args) => {
|
|
47
|
+
const o = getOptions();
|
|
48
|
+
const holdsHub = o?.keepAliveOnUnmount === true && acquire && release;
|
|
49
|
+
if (holdsHub)
|
|
50
|
+
acquire(hub);
|
|
51
|
+
try {
|
|
52
|
+
return await attempts(o, args);
|
|
53
|
+
}
|
|
56
54
|
finally {
|
|
57
|
-
|
|
55
|
+
if (holdsHub)
|
|
56
|
+
release(hub);
|
|
58
57
|
}
|
|
59
58
|
};
|
|
60
59
|
}
|
|
61
|
-
/**
|
|
62
|
-
|
|
63
|
-
* connection at call time and never depends on the adapter's tracked state,
|
|
64
|
-
* so it is safe to capture in a teardown handler.
|
|
65
|
-
*/
|
|
66
|
-
export function createSender(getConnection, hub, method) {
|
|
60
|
+
/** Fire-and-forget sender. It reads the connection at call time, so a teardown handler can capture it. */
|
|
61
|
+
export function createSender({ getConnection, hub, method, }) {
|
|
67
62
|
return (...args) => {
|
|
68
63
|
const connection = getConnection(hub);
|
|
69
64
|
if (!connection || connection.state !== HubConnectionState.Connected) {
|
|
70
65
|
return Promise.resolve(false); // dropped: not connected
|
|
71
66
|
}
|
|
72
67
|
// send() is variadic and untyped; args are enforced at the call site.
|
|
73
|
-
return connection.send(method, ...args).then(() => true);
|
|
68
|
+
return connection.send(method, ...args).then(() => true, () => false);
|
|
74
69
|
};
|
|
75
70
|
}
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
71
|
+
function ignoreErrors(fn) {
|
|
72
|
+
try {
|
|
73
|
+
fn();
|
|
74
|
+
}
|
|
75
|
+
catch {
|
|
76
|
+
// Nothing is left to report to.
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
/** Teardown sender. It acquires the hub itself, so it still works after its consumer is gone. */
|
|
80
|
+
export function createTeardownSender({ target: { acquire, release, waitForConnection, beginSend }, hub, method, getOptions, }) {
|
|
84
81
|
return (...args) => {
|
|
85
82
|
const timeout = getOptions()?.timeout ?? DEFAULT_TEARDOWN_TIMEOUT;
|
|
83
|
+
const inFlight = beginSend?.(hub); // registered before any await, so a later stop() sees it
|
|
86
84
|
acquire(hub); // hold the hub open past our own unmount, until flushed
|
|
87
|
-
return
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
}
|
|
99
|
-
|
|
85
|
+
return new Promise((resolve) => {
|
|
86
|
+
let finished = false;
|
|
87
|
+
const finish = (sent) => {
|
|
88
|
+
if (finished)
|
|
89
|
+
return;
|
|
90
|
+
finished = true;
|
|
91
|
+
clearTimeout(timer);
|
|
92
|
+
resolve(sent);
|
|
93
|
+
// A failing cleanup must not leave the call pending or throw from a timer.
|
|
94
|
+
ignoreErrors(() => release(hub));
|
|
95
|
+
ignoreErrors(() => inFlight?.end());
|
|
96
|
+
};
|
|
97
|
+
// The timeout also covers the send, so a stuck send cannot hold a stopped connection open.
|
|
98
|
+
const timer = Number.isFinite(timeout)
|
|
99
|
+
? setTimeout(() => finish(false), Math.min(timeout, MAX_TIMER_MS))
|
|
100
|
+
: undefined;
|
|
101
|
+
void (async () => {
|
|
102
|
+
try {
|
|
103
|
+
const connection = await waitForConnection(hub, timeout, inFlight?.signal);
|
|
104
|
+
inFlight?.use(connection);
|
|
105
|
+
await connection.send(method, ...args);
|
|
106
|
+
finish(true);
|
|
107
|
+
}
|
|
108
|
+
catch {
|
|
109
|
+
finish(false); // never connected in time, the session stopped, or the send failed: best-effort
|
|
110
|
+
}
|
|
111
|
+
})();
|
|
112
|
+
});
|
|
100
113
|
};
|
|
101
114
|
}
|
package/dist/config.d.ts
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { IHubProtocol } from "@microsoft/signalr";
|
|
2
|
+
import type { HubDef, HttpOptions, HubString, ResolvedHubConfig, SignalRClientConfig } from "./types.js";
|
|
2
3
|
/** Typed `Object.keys`. Narrows the keys to the declared hubs. */
|
|
3
4
|
export declare function hubKeys<H extends Record<HubString, HubDef>>(config: SignalRClientConfig<H>): Array<keyof H & HubString>;
|
|
5
|
+
/** Join the base URL and a hub path without a double slash. */
|
|
6
|
+
export declare function joinHubUrl(baseUrl: string, hub: HubString): string;
|
|
7
|
+
/** Throws when a binary protocol meets a transport that only has Server-Sent Events. */
|
|
8
|
+
export declare function assertProtocolFitsTransport(hub: string, protocol: IHubProtocol, httpOptions: HttpOptions): void;
|
|
4
9
|
/** Merge a hub's per-hub config over the global defaults. */
|
|
5
|
-
export declare function resolveHubConfig<H extends Record<HubString, HubDef>>(config: SignalRClientConfig<H>,
|
|
6
|
-
/**
|
|
7
|
-
* Checks whether a FIRST-CONNECT failure is worth a retry. Permanent
|
|
8
|
-
* negotiate failures (auth, wrong path, bad request) are not — a retry just
|
|
9
|
-
* hammers the server. Network, transient, and 5xx failures are worth a retry.
|
|
10
|
-
*/
|
|
10
|
+
export declare function resolveHubConfig<H extends Record<HubString, HubDef>>(config: SignalRClientConfig<H>, hub: keyof H & HubString): ResolvedHubConfig;
|
|
11
|
+
/** True for network, timeout, and 5xx failures. Auth, wrong-path, and bad-request negotiate failures are permanent. */
|
|
11
12
|
export declare function isRetriableConnectError(err: unknown): boolean;
|
package/dist/config.js
CHANGED
|
@@ -1,32 +1,86 @@
|
|
|
1
|
-
import { HttpError, LogLevel } from "@microsoft/signalr";
|
|
1
|
+
import { HttpError, HttpTransportType, LogLevel, TransferFormat } from "@microsoft/signalr";
|
|
2
2
|
/** Typed `Object.keys`. Narrows the keys to the declared hubs. */
|
|
3
3
|
export function hubKeys(config) {
|
|
4
4
|
return Object.keys(config.hubs);
|
|
5
5
|
}
|
|
6
|
+
function mergeHttpOptions(global = {}, perHub = {}) {
|
|
7
|
+
const merged = { ...global, ...perHub };
|
|
8
|
+
if (global.headers && perHub.headers) {
|
|
9
|
+
merged.headers = { ...global.headers, ...perHub.headers };
|
|
10
|
+
}
|
|
11
|
+
return merged;
|
|
12
|
+
}
|
|
13
|
+
/** Join the base URL and a hub path without a double slash. */
|
|
14
|
+
export function joinHubUrl(baseUrl, hub) {
|
|
15
|
+
return `${baseUrl.replace(/\/+$/, "")}${hub}`;
|
|
16
|
+
}
|
|
17
|
+
/** Throws when a binary protocol meets a transport that only has Server-Sent Events. */
|
|
18
|
+
export function assertProtocolFitsTransport(hub, protocol, httpOptions) {
|
|
19
|
+
if (protocol.transferFormat === TransferFormat.Binary &&
|
|
20
|
+
httpOptions.transport === HttpTransportType.ServerSentEvents) {
|
|
21
|
+
throw new Error(`Hub "${hub}": the "${protocol.name}" protocol sends binary data. ` +
|
|
22
|
+
"Server-Sent Events cannot carry binary data. " +
|
|
23
|
+
"Use WebSockets or LongPolling in httpOptions.transport, or use a text protocol.");
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
/** Throws when skipNegotiation is on and the transport is not WebSockets only. */
|
|
27
|
+
function assertSkipNegotiationFitsTransport(hub, httpOptions) {
|
|
28
|
+
if (httpOptions.skipNegotiation && httpOptions.transport !== HttpTransportType.WebSockets) {
|
|
29
|
+
throw new Error(`Hub "${hub}": skipNegotiation needs httpOptions.transport = HttpTransportType.WebSockets.`);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
const REMOVED_KEYS = {
|
|
33
|
+
transport: "Move it into httpOptions.",
|
|
34
|
+
skipNegotiation: "Move it into httpOptions.",
|
|
35
|
+
maxConnectRetries: "The library retries a failed hub until the hub stops. Delete the option.",
|
|
36
|
+
};
|
|
37
|
+
function assertNoRemovedKeys(where, options) {
|
|
38
|
+
if (!options)
|
|
39
|
+
return;
|
|
40
|
+
for (const [key, advice] of Object.entries(REMOVED_KEYS)) {
|
|
41
|
+
if (key in options)
|
|
42
|
+
throw new Error(`${where}: the "${key}" option does not exist. ${advice}`);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
6
45
|
/** Merge a hub's per-hub config over the global defaults. */
|
|
7
|
-
export function resolveHubConfig(config,
|
|
46
|
+
export function resolveHubConfig(config, hub) {
|
|
47
|
+
const perHub = config.hubs[hub];
|
|
48
|
+
assertNoRemovedKeys("SignalR config", config);
|
|
49
|
+
assertNoRemovedKeys(`Hub "${hub}"`, perHub);
|
|
50
|
+
const httpOptions = mergeHttpOptions(config.httpOptions, perHub?.httpOptions);
|
|
51
|
+
assertSkipNegotiationFitsTransport(hub, httpOptions);
|
|
52
|
+
const hubProtocol = perHub?.hubProtocol ?? config.hubProtocol;
|
|
53
|
+
if (hubProtocol && typeof hubProtocol !== "function") {
|
|
54
|
+
assertProtocolFitsTransport(hub, hubProtocol, httpOptions);
|
|
55
|
+
}
|
|
56
|
+
const configureBuilders = [];
|
|
57
|
+
if (config.configureBuilder)
|
|
58
|
+
configureBuilders.push(config.configureBuilder);
|
|
59
|
+
if (perHub?.configureBuilder)
|
|
60
|
+
configureBuilders.push(perHub.configureBuilder);
|
|
8
61
|
return {
|
|
9
62
|
lazy: perHub?.lazy ?? config.lazy ?? false,
|
|
10
63
|
graceMs: perHub?.graceMs ?? 0,
|
|
11
64
|
reconnect: perHub?.reconnect ?? config.reconnect ?? true,
|
|
12
|
-
maxConnectRetries: perHub?.maxConnectRetries ?? config.maxConnectRetries ?? 2,
|
|
13
65
|
logLevel: perHub?.logLevel ?? config.logLevel ?? LogLevel.Information,
|
|
14
|
-
|
|
15
|
-
|
|
66
|
+
httpOptions,
|
|
67
|
+
hubProtocol,
|
|
68
|
+
configureBuilders,
|
|
16
69
|
events: Object.keys(perHub?.events ?? {}),
|
|
17
70
|
};
|
|
18
71
|
}
|
|
19
|
-
/**
|
|
20
|
-
* Checks whether a FIRST-CONNECT failure is worth a retry. Permanent
|
|
21
|
-
* negotiate failures (auth, wrong path, bad request) are not — a retry just
|
|
22
|
-
* hammers the server. Network, transient, and 5xx failures are worth a retry.
|
|
23
|
-
*/
|
|
72
|
+
/** True for network, timeout, and 5xx failures. Auth, wrong-path, and bad-request negotiate failures are permanent. */
|
|
24
73
|
export function isRetriableConnectError(err) {
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
74
|
+
const s = err instanceof HttpError ? err.statusCode : negotiateStatusCode(err);
|
|
75
|
+
// 0 (network), 408, 429, 5xx, timeouts, and unknown errors are transient.
|
|
76
|
+
return !(s === 400 || s === 401 || s === 403 || s === 404);
|
|
77
|
+
}
|
|
78
|
+
// SignalR wraps negotiate HttpErrors and keeps only their message.
|
|
79
|
+
function negotiateStatusCode(err) {
|
|
80
|
+
if (!(err instanceof Error) || !("errorType" in err))
|
|
81
|
+
return undefined;
|
|
82
|
+
if (err.errorType !== "FailedToNegotiateWithServerError")
|
|
83
|
+
return undefined;
|
|
84
|
+
const code = /Status code '(\d{3})'/.exec(err.message)?.[1];
|
|
85
|
+
return code === undefined ? undefined : Number(code);
|
|
32
86
|
}
|
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import type { HubConnection } from "@microsoft/signalr";
|
|
2
|
-
import type { HubConnectionStatus, HubString, ResolvedHubConfig } from "./types.js";
|
|
2
|
+
import type { HubConnectionStatus, SignalRErrorInfo, HubString, ResolvedHubConfig } from "./types.js";
|
|
3
|
+
/** Runs a user callback. A throw or a rejection goes to onError. A failure of onError is dropped. */
|
|
4
|
+
export declare function runUserCallback<Hub extends HubString>(hub: Hub, callback: () => unknown, onError: (hub: Hub, error: unknown) => unknown): void;
|
|
3
5
|
export interface ConnectionManagerDeps<Hub extends HubString> {
|
|
4
6
|
baseUrl: string;
|
|
5
7
|
hubs: Hub[];
|
|
@@ -11,23 +13,23 @@ export interface ConnectionManagerDeps<Hub extends HubString> {
|
|
|
11
13
|
/** Pending lazy-stop timers, shared across rebuilds. */
|
|
12
14
|
stopTimers: Map<Hub, ReturnType<typeof setTimeout>>;
|
|
13
15
|
reconnectListeners: Map<Hub, Set<() => void>>;
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
/**
|
|
16
|
+
/** Hubs that connected before, shared across rebuilds. A later connect of one runs the reconnect listeners. */
|
|
17
|
+
connectedBefore: Set<Hub>;
|
|
18
|
+
/** Delivers a server push to the session's handler registry. */
|
|
19
|
+
dispatch: (hub: Hub, event: string, args: unknown[]) => void;
|
|
20
|
+
/** `error` is set when the status is "disconnected" after a failure. */
|
|
21
|
+
onStatus: (hub: Hub, status: HubConnectionStatus, error?: unknown) => void;
|
|
22
|
+
/** Reports once per outage: the first failed attempt of a retriable outage, or a non-retriable error. */
|
|
23
|
+
onError: (hub: Hub, error: unknown, info: SignalRErrorInfo) => void;
|
|
24
|
+
/** True while this manager is the live one. Guards stale rebuilds. */
|
|
17
25
|
isCurrent: () => boolean;
|
|
18
26
|
}
|
|
19
27
|
export interface ConnectionManager<Hub extends HubString> {
|
|
20
28
|
/** Builds/starts desired hubs and stops undesired ones. Safe to call repeatedly. */
|
|
21
29
|
reconcile: () => void;
|
|
22
30
|
getConnection: (hub: Hub) => HubConnection | null;
|
|
23
|
-
/**
|
|
24
|
-
|
|
25
|
-
/** Stops all connections and cancels timers. */
|
|
26
|
-
dispose: () => void;
|
|
31
|
+
/** Stops all connections and cancels timers. A connected hub in `keep` stays open and is returned, so the caller closes it. */
|
|
32
|
+
dispose: (keep?: ReadonlySet<Hub>) => Map<Hub, HubConnection>;
|
|
27
33
|
}
|
|
28
|
-
/**
|
|
29
|
-
* Owns the HubConnection lifecycle for one provider generation: building,
|
|
30
|
-
* starting with retry, lazy ref-counted start/stop, and reconnect fan-out.
|
|
31
|
-
* Framework-neutral — driven by the adapter's lifecycle hook and context callbacks.
|
|
32
|
-
*/
|
|
34
|
+
/** Owns the hub connections of one provider: build, start with recovery, lazy ref-counted stop. */
|
|
33
35
|
export declare function createConnectionManager<Hub extends HubString>(deps: ConnectionManagerDeps<Hub>): ConnectionManager<Hub>;
|