@dammers/use-signalr-core 0.4.0 → 0.5.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 +56 -17
- package/dist/calls.d.ts +19 -7
- package/dist/calls.js +43 -24
- package/dist/config.d.ts +1 -1
- package/dist/connection-manager.d.ts +2 -2
- package/dist/connection-manager.js +33 -9
- package/dist/context.d.ts +1 -1
- package/dist/hub-entry.d.ts +1 -1
- package/dist/index.d.ts +14 -11
- package/dist/index.js +6 -5
- package/dist/retry.js +10 -3
- package/dist/session.d.ts +27 -0
- package/dist/session.js +76 -0
- package/dist/status-store.d.ts +1 -1
- package/dist/types.d.ts +7 -7
- package/package.json +17 -3
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# @dammers/use-signalr-core
|
|
2
2
|
|
|
3
|
-
Framework-free connection lifecycle, contracts, and retry logic for [SignalR](https://learn.microsoft.com/aspnet/core/signalr)
|
|
3
|
+
Framework-free connection lifecycle, contracts, and retry logic for [SignalR](https://learn.microsoft.com/aspnet/core/signalr). Core owns all connection behavior. Every adapter in this repository is a thin reactive layer on top of it.
|
|
4
4
|
|
|
5
5
|
[](https://www.npmjs.com/package/@dammers/use-signalr-core)
|
|
6
6
|

|
|
@@ -8,9 +8,17 @@ Framework-free connection lifecycle, contracts, and retry logic for [SignalR](ht
|
|
|
8
8
|
|
|
9
9
|
## Who needs this
|
|
10
10
|
|
|
11
|
-
Adapter authors
|
|
11
|
+
Adapter authors. This package has no provider, no hooks, and no reactive layer.
|
|
12
12
|
|
|
13
|
-
|
|
13
|
+
If you build an application, install an adapter instead of core. Core is a dependency of every adapter:
|
|
14
|
+
|
|
15
|
+
- [`@dammers/use-signalr-react`](https://github.com/DammersCode/use-signalr/blob/main/packages/react/README.md)
|
|
16
|
+
- [`@dammers/use-signalr-solid`](https://github.com/DammersCode/use-signalr/blob/main/packages/solid/README.md)
|
|
17
|
+
- [`@dammers/use-signalr-svelte`](https://github.com/DammersCode/use-signalr/blob/main/packages/svelte/README.md)
|
|
18
|
+
- [`@dammers/use-signalr-angular`](https://github.com/DammersCode/use-signalr/blob/main/packages/angular/README.md)
|
|
19
|
+
- [`@dammers/use-signalr-vue`](https://github.com/DammersCode/use-signalr/blob/main/packages/vue/README.md)
|
|
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)
|
|
14
22
|
|
|
15
23
|
## Install
|
|
16
24
|
|
|
@@ -18,27 +26,58 @@ Building an app? Install `@dammers/use-signalr-react` or `@dammers/use-signalr-s
|
|
|
18
26
|
npm i @dammers/use-signalr-core @microsoft/signalr
|
|
19
27
|
```
|
|
20
28
|
|
|
21
|
-
|
|
29
|
+
Core requires `@microsoft/signalr` ≥ 8.
|
|
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:
|
|
22
49
|
|
|
23
|
-
|
|
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. |
|
|
24
55
|
|
|
25
|
-
|
|
26
|
-
| ---------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
27
|
-
| `createConnectionManager(deps)` | Owns one provider generation's `HubConnection`s: build, start with retry, lazy ref-counted start/stop, reconnect fan-out. No framework dependency — driven by callbacks. |
|
|
28
|
-
| `createInvoker(deps, hub, method, getOptions, onAbort)` | Builds the request/response call function behind an invoke hook: waits for connection, retries idempotent failures, rethrows business errors. |
|
|
29
|
-
| `createSender(getConnection, hub, method)` | Builds the fire-and-forget call function behind a send hook: drops if not connected. |
|
|
30
|
-
| `createTeardownSender(deps, hub, method, getOptions)` | Builds the reliable teardown call function: survives disposal, queues while connecting, holds a lazy hub open until flushed. |
|
|
31
|
-
| `event<Args>()` / `method<Args, Return?>()` | Contract markers used inside `hubs.<path>.events` / `.methods` to declare what a hub pushes and what it accepts. |
|
|
32
|
-
| `hubKeys(config)`, `resolveHubConfig(config, hubConfig)` | Resolve per-hub config against global defaults. |
|
|
33
|
-
| `isRetriableConnectError`, `isRetriableInvokeError`, `resolveBackoff`, `DEFAULT_BACKOFF`, `sleep`, `InvokeError` | Retry/backoff building blocks and the error type thrown once an invoke's attempts are exhausted. |
|
|
56
|
+
Call `start` only from a client-only lifecycle hook. `createSignalRSession` does no I/O when you construct it.
|
|
34
57
|
|
|
35
|
-
|
|
58
|
+
## Call helpers
|
|
36
59
|
|
|
37
|
-
An adapter
|
|
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`.
|
|
38
75
|
|
|
39
76
|
## More
|
|
40
77
|
|
|
41
|
-
|
|
78
|
+
[ARCHITECTURE.md](https://github.com/DammersCode/use-signalr/blob/main/ARCHITECTURE.md) has the full new-adapter checklist, the core/adapter split, and the naming conventions.
|
|
79
|
+
|
|
80
|
+
Shared concepts (the contract, per-hub configuration, invoke retry, send versus invoke versus teardown) live in the [root README](https://github.com/DammersCode/use-signalr#readme).
|
|
42
81
|
|
|
43
82
|
## License
|
|
44
83
|
|
package/dist/calls.d.ts
CHANGED
|
@@ -1,5 +1,16 @@
|
|
|
1
1
|
import type { HubConnection } from "@microsoft/signalr";
|
|
2
|
-
import type { HubString, InvokeOptions, TeardownOptions, MethodArgs, MethodName, MethodReturn, SignalRContract } from "./types";
|
|
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
|
+
*/
|
|
8
|
+
export interface AbortScope {
|
|
9
|
+
track: (ac: AbortController) => void;
|
|
10
|
+
untrack: (ac: AbortController) => void;
|
|
11
|
+
abortAll: () => void;
|
|
12
|
+
}
|
|
13
|
+
export declare function createAbortScope(): AbortScope;
|
|
3
14
|
export interface CallTarget<T extends SignalRContract> {
|
|
4
15
|
waitForConnection: (hub: keyof T & HubString, timeoutMs: number) => Promise<HubConnection>;
|
|
5
16
|
getConnection: (hub: keyof T & HubString) => HubConnection | null;
|
|
@@ -9,20 +20,21 @@ export interface CallTarget<T extends SignalRContract> {
|
|
|
9
20
|
* called at CALL time (not build time), so the adapter can pass a ref/latest
|
|
10
21
|
* accessor and preserve latest-options semantics. `setAbort` is called once
|
|
11
22
|
* per invocation with the new controller, so the adapter's unmount/cleanup
|
|
12
|
-
* handler can abort the in-flight call.
|
|
23
|
+
* handler can abort the in-flight call. `clearAbort` runs when that call
|
|
24
|
+
* settles, so adapters can retain only active controllers.
|
|
13
25
|
*/
|
|
14
|
-
export declare function createInvoker<T extends SignalRContract, H extends keyof T & HubString, M extends MethodName<T, H>>(target: CallTarget<T>, hub: H, method: M, getOptions: () => InvokeOptions | undefined, setAbort: (ac: AbortController) => void): (...args: MethodArgs<T, H, M>) => Promise<MethodReturn<T, H, M>>;
|
|
26
|
+
export declare function createInvoker<T extends SignalRContract, H extends keyof T & HubString, M extends MethodName<T, H>>(target: CallTarget<T>, hub: H, method: M, getOptions: () => InvokeOptions | undefined, setAbort: (ac: AbortController) => void, clearAbort?: (ac: AbortController) => void): (...args: MethodArgs<T, H, M>) => Promise<MethodReturn<T, H, M>>;
|
|
15
27
|
/**
|
|
16
28
|
* Builds the stable fire-and-forget sender for `useSignalRSend`. Reads the
|
|
17
|
-
* connection at call time and never depends on
|
|
18
|
-
* is safe to capture in
|
|
29
|
+
* connection at call time and never depends on the adapter's tracked state,
|
|
30
|
+
* so it is safe to capture in a teardown handler.
|
|
19
31
|
*/
|
|
20
32
|
export declare function createSender<T extends SignalRContract, H extends keyof T & HubString, M extends MethodName<T, H>>(getConnection: (hub: H) => HubConnection | null, hub: H, method: M): (...args: MethodArgs<T, H, M>) => Promise<boolean>;
|
|
21
33
|
/**
|
|
22
34
|
* Builds the stable RELIABLE teardown sender for `useSignalRTeardown`. Runs
|
|
23
35
|
* detached from the caller's lifecycle: it acquires the hub itself, waits
|
|
24
|
-
* for a connection, sends, then releases — independent of the
|
|
25
|
-
* that created it having already
|
|
36
|
+
* for a connection, sends, then releases — independent of the consumer
|
|
37
|
+
* that created it having already torn down.
|
|
26
38
|
*/
|
|
27
39
|
export declare function createTeardownSender<T extends SignalRContract, H extends keyof T & HubString, M extends MethodName<T, H>>(deps: {
|
|
28
40
|
acquire: (hub: H) => void;
|
package/dist/calls.js
CHANGED
|
@@ -1,15 +1,27 @@
|
|
|
1
1
|
import { HubConnectionState } from "@microsoft/signalr";
|
|
2
|
-
import { DEFAULT_BACKOFF, InvokeError, isRetriableInvokeError, resolveBackoff, sleep, } from "./retry";
|
|
2
|
+
import { DEFAULT_BACKOFF, InvokeError, isRetriableInvokeError, resolveBackoff, sleep, } from "./retry.js";
|
|
3
3
|
const DEFAULT_TIMEOUT = 10000;
|
|
4
4
|
const DEFAULT_TEARDOWN_TIMEOUT = 10000;
|
|
5
|
+
export function createAbortScope() {
|
|
6
|
+
const active = new Set();
|
|
7
|
+
return {
|
|
8
|
+
track: (ac) => active.add(ac),
|
|
9
|
+
untrack: (ac) => active.delete(ac),
|
|
10
|
+
abortAll: () => {
|
|
11
|
+
active.forEach((ac) => ac.abort());
|
|
12
|
+
active.clear();
|
|
13
|
+
},
|
|
14
|
+
};
|
|
15
|
+
}
|
|
5
16
|
/**
|
|
6
17
|
* Builds the stable invoke function for `useSignalRInvoke`. `getOptions` is
|
|
7
18
|
* called at CALL time (not build time), so the adapter can pass a ref/latest
|
|
8
19
|
* accessor and preserve latest-options semantics. `setAbort` is called once
|
|
9
20
|
* per invocation with the new controller, so the adapter's unmount/cleanup
|
|
10
|
-
* handler can abort the in-flight call.
|
|
21
|
+
* handler can abort the in-flight call. `clearAbort` runs when that call
|
|
22
|
+
* settles, so adapters can retain only active controllers.
|
|
11
23
|
*/
|
|
12
|
-
export function createInvoker(target, hub, method, getOptions, setAbort) {
|
|
24
|
+
export function createInvoker(target, hub, method, getOptions, setAbort, clearAbort) {
|
|
13
25
|
const { waitForConnection, getConnection } = target;
|
|
14
26
|
return async (...args) => {
|
|
15
27
|
const o = getOptions();
|
|
@@ -17,32 +29,39 @@ export function createInvoker(target, hub, method, getOptions, setAbort) {
|
|
|
17
29
|
const retries = o?.retries ?? 0;
|
|
18
30
|
const ac = new AbortController();
|
|
19
31
|
setAbort(ac);
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
32
|
+
try {
|
|
33
|
+
let attempt = 0;
|
|
34
|
+
for (;;) {
|
|
35
|
+
try {
|
|
36
|
+
const connection = await waitForConnection(hub, timeout);
|
|
37
|
+
return await connection.invoke(method, ...args);
|
|
38
|
+
}
|
|
39
|
+
catch (error) {
|
|
40
|
+
if (ac.signal.aborted)
|
|
41
|
+
throw error; // abort wins: never reclassify or retry
|
|
42
|
+
const conn = getConnection(hub);
|
|
43
|
+
const forced = o?.isRetriable?.(error);
|
|
44
|
+
const retriable = forced ?? (conn ? isRetriableInvokeError(error, conn) : true);
|
|
45
|
+
if (!retriable || attempt >= retries) {
|
|
46
|
+
// No retries: rethrow the raw error, so callers see the original.
|
|
47
|
+
if (retries === 0)
|
|
48
|
+
throw error;
|
|
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;
|
|
35
53
|
}
|
|
36
|
-
await sleep(resolveBackoff(o?.backoff ?? DEFAULT_BACKOFF, attempt), ac.signal);
|
|
37
|
-
attempt += 1;
|
|
38
54
|
}
|
|
39
55
|
}
|
|
56
|
+
finally {
|
|
57
|
+
clearAbort?.(ac);
|
|
58
|
+
}
|
|
40
59
|
};
|
|
41
60
|
}
|
|
42
61
|
/**
|
|
43
62
|
* Builds the stable fire-and-forget sender for `useSignalRSend`. Reads the
|
|
44
|
-
* connection at call time and never depends on
|
|
45
|
-
* is safe to capture in
|
|
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.
|
|
46
65
|
*/
|
|
47
66
|
export function createSender(getConnection, hub, method) {
|
|
48
67
|
return (...args) => {
|
|
@@ -57,8 +76,8 @@ export function createSender(getConnection, hub, method) {
|
|
|
57
76
|
/**
|
|
58
77
|
* Builds the stable RELIABLE teardown sender for `useSignalRTeardown`. Runs
|
|
59
78
|
* detached from the caller's lifecycle: it acquires the hub itself, waits
|
|
60
|
-
* for a connection, sends, then releases — independent of the
|
|
61
|
-
* that created it having already
|
|
79
|
+
* for a connection, sends, then releases — independent of the consumer
|
|
80
|
+
* that created it having already torn down.
|
|
62
81
|
*/
|
|
63
82
|
export function createTeardownSender(deps, hub, method, getOptions) {
|
|
64
83
|
const { acquire, release, waitForConnection } = deps;
|
package/dist/config.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { HubDef, HubString, ResolvedHubConfig, SignalRClientConfig } from "./types";
|
|
1
|
+
import type { HubDef, HubString, ResolvedHubConfig, SignalRClientConfig } from "./types.js";
|
|
2
2
|
/** Typed `Object.keys`. Narrows the keys to the declared hubs. */
|
|
3
3
|
export declare function hubKeys<H extends Record<HubString, HubDef>>(config: SignalRClientConfig<H>): Array<keyof H & HubString>;
|
|
4
4
|
/** Merge a hub's per-hub config over the global defaults. */
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { HubConnection } from "@microsoft/signalr";
|
|
2
|
-
import type { HubConnectionStatus, HubString, ResolvedHubConfig } from "./types";
|
|
2
|
+
import type { HubConnectionStatus, HubString, ResolvedHubConfig } from "./types.js";
|
|
3
3
|
export interface ConnectionManagerDeps<Hub extends HubString> {
|
|
4
4
|
baseUrl: string;
|
|
5
5
|
hubs: Hub[];
|
|
@@ -28,6 +28,6 @@ export interface ConnectionManager<Hub extends HubString> {
|
|
|
28
28
|
/**
|
|
29
29
|
* Owns the HubConnection lifecycle for one provider generation: building,
|
|
30
30
|
* starting with retry, lazy ref-counted start/stop, and reconnect fan-out.
|
|
31
|
-
*
|
|
31
|
+
* Framework-neutral — driven by the adapter's lifecycle hook and context callbacks.
|
|
32
32
|
*/
|
|
33
33
|
export declare function createConnectionManager<Hub extends HubString>(deps: ConnectionManagerDeps<Hub>): ConnectionManager<Hub>;
|
|
@@ -1,15 +1,16 @@
|
|
|
1
1
|
import { HubConnectionBuilder, HubConnectionState } from "@microsoft/signalr";
|
|
2
|
-
import { isRetriableConnectError } from "./config";
|
|
2
|
+
import { isRetriableConnectError } from "./config.js";
|
|
3
3
|
const CONNECT_RETRY_BASE_MS = 2500;
|
|
4
4
|
function noop() { }
|
|
5
5
|
/**
|
|
6
6
|
* Owns the HubConnection lifecycle for one provider generation: building,
|
|
7
7
|
* starting with retry, lazy ref-counted start/stop, and reconnect fan-out.
|
|
8
|
-
*
|
|
8
|
+
* Framework-neutral — driven by the adapter's lifecycle hook and context callbacks.
|
|
9
9
|
*/
|
|
10
10
|
export function createConnectionManager(deps) {
|
|
11
11
|
const { baseUrl, hubs, resolve, getAccessToken, refCounts, stopTimers, reconnectListeners, onStatus, onError, isCurrent, } = deps;
|
|
12
12
|
const built = new Map();
|
|
13
|
+
const retryTimers = new Set();
|
|
13
14
|
let disposing = false;
|
|
14
15
|
const setStatus = (hub, status) => {
|
|
15
16
|
const e = built.get(hub);
|
|
@@ -17,6 +18,11 @@ export function createConnectionManager(deps) {
|
|
|
17
18
|
e.status = status;
|
|
18
19
|
onStatus(hub, status);
|
|
19
20
|
};
|
|
21
|
+
// stop() stays fire-and-forget so the public API remains synchronous, but a
|
|
22
|
+
// rejection must surface instead of becoming an unhandled rejection.
|
|
23
|
+
const stopConnection = (hub, connection) => {
|
|
24
|
+
void connection.stop().catch((err) => onError(hub, err));
|
|
25
|
+
};
|
|
20
26
|
const clearStopTimer = (hub) => {
|
|
21
27
|
const id = stopTimers.get(hub);
|
|
22
28
|
if (id !== undefined) {
|
|
@@ -47,6 +53,7 @@ export function createConnectionManager(deps) {
|
|
|
47
53
|
applyReconnect(builder, rc.reconnect);
|
|
48
54
|
const conn = builder.build();
|
|
49
55
|
// Pre-bind declared client events, so a server push never hits zero handlers.
|
|
56
|
+
// Tests must count `.on` deltas: this adds one call per declared event.
|
|
50
57
|
for (const ev of rc.events)
|
|
51
58
|
conn.on(ev, noop);
|
|
52
59
|
let resolveReady;
|
|
@@ -63,6 +70,9 @@ export function createConnectionManager(deps) {
|
|
|
63
70
|
built.set(hub, entry);
|
|
64
71
|
// Attach lifecycle handlers ONCE — SignalR has no removal API.
|
|
65
72
|
conn.onclose((err) => {
|
|
73
|
+
// A stale generation's late callback must never overwrite the live one's status.
|
|
74
|
+
if (!isCurrent())
|
|
75
|
+
return;
|
|
66
76
|
// A deliberate stop() (logout, rebuild, lazy stop) leaves err undefined: stay silent.
|
|
67
77
|
if (disposing || err === undefined) {
|
|
68
78
|
setStatus(hub, "disconnected");
|
|
@@ -71,10 +81,15 @@ export function createConnectionManager(deps) {
|
|
|
71
81
|
setStatus(hub, "disconnected");
|
|
72
82
|
onError(hub, err);
|
|
73
83
|
});
|
|
74
|
-
conn.onreconnecting(() =>
|
|
84
|
+
conn.onreconnecting(() => {
|
|
85
|
+
if (isCurrent())
|
|
86
|
+
setStatus(hub, "reconnecting");
|
|
87
|
+
});
|
|
75
88
|
conn.onreconnected(() => {
|
|
76
89
|
entry.resolveReady();
|
|
77
|
-
if (!
|
|
90
|
+
if (!isCurrent())
|
|
91
|
+
return;
|
|
92
|
+
if (!disposing) {
|
|
78
93
|
onStatus(hub, "reconnected");
|
|
79
94
|
reconnectListeners.get(hub)?.forEach((cb) => cb());
|
|
80
95
|
}
|
|
@@ -103,7 +118,11 @@ export function createConnectionManager(deps) {
|
|
|
103
118
|
}
|
|
104
119
|
retries += 1;
|
|
105
120
|
setStatus(hub, "disconnected");
|
|
106
|
-
setTimeout(
|
|
121
|
+
const id = setTimeout(() => {
|
|
122
|
+
retryTimers.delete(id);
|
|
123
|
+
void start();
|
|
124
|
+
}, CONNECT_RETRY_BASE_MS * retries);
|
|
125
|
+
retryTimers.add(id);
|
|
107
126
|
}
|
|
108
127
|
};
|
|
109
128
|
void start();
|
|
@@ -124,7 +143,7 @@ export function createConnectionManager(deps) {
|
|
|
124
143
|
e.stopping = true;
|
|
125
144
|
built.delete(hub);
|
|
126
145
|
setStatus(hub, "disconnected");
|
|
127
|
-
|
|
146
|
+
stopConnection(hub, e.connection);
|
|
128
147
|
};
|
|
129
148
|
if (graceMs <= 0)
|
|
130
149
|
queueMicrotask(stopNow);
|
|
@@ -165,11 +184,14 @@ export function createConnectionManager(deps) {
|
|
|
165
184
|
if (entry?.connection.state === HubConnectionState.Connected) {
|
|
166
185
|
return entry.connection;
|
|
167
186
|
}
|
|
168
|
-
|
|
187
|
+
let timeoutId;
|
|
188
|
+
const timeout = new Promise((res) => {
|
|
189
|
+
timeoutId = setTimeout(() => res("timeout"), deadline - Date.now());
|
|
190
|
+
});
|
|
169
191
|
const result = await Promise.race([
|
|
170
192
|
entry?.ready.then(() => "ready") ?? timeout,
|
|
171
193
|
timeout,
|
|
172
|
-
]);
|
|
194
|
+
]).finally(() => clearTimeout(timeoutId));
|
|
173
195
|
if (result === "timeout")
|
|
174
196
|
break;
|
|
175
197
|
}
|
|
@@ -179,7 +201,9 @@ export function createConnectionManager(deps) {
|
|
|
179
201
|
disposing = true;
|
|
180
202
|
stopTimers.forEach((id) => clearTimeout(id));
|
|
181
203
|
stopTimers.clear();
|
|
182
|
-
|
|
204
|
+
retryTimers.forEach((id) => clearTimeout(id));
|
|
205
|
+
retryTimers.clear();
|
|
206
|
+
built.forEach((e, hub) => stopConnection(hub, e.connection));
|
|
183
207
|
// refCounts are kept across rebuilds on purpose.
|
|
184
208
|
};
|
|
185
209
|
return { reconcile, getConnection, waitForConnection, dispose };
|
package/dist/context.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { HubConnection } from "@microsoft/signalr";
|
|
2
|
-
import type { HubConnectionStatus, HubString, SignalRContract } from "./types";
|
|
2
|
+
import type { HubConnectionStatus, HubString, SignalRContract } from "./types.js";
|
|
3
3
|
export interface SignalRProviderPropsBase<TChildren> {
|
|
4
4
|
children: TChildren;
|
|
5
5
|
/** Base URL of the SignalR server. Connections rebuild when this changes. */
|
package/dist/hub-entry.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { HubConnection } from "@microsoft/signalr";
|
|
2
|
-
import type { HubConnectionStatus } from "./types";
|
|
2
|
+
import type { HubConnectionStatus } from "./types.js";
|
|
3
3
|
/** Live state for one hub connection, owned by the connection manager. */
|
|
4
4
|
export interface HubEntry {
|
|
5
5
|
connection: HubConnection;
|
package/dist/index.d.ts
CHANGED
|
@@ -1,11 +1,14 @@
|
|
|
1
|
-
export { event, method } from "./types";
|
|
2
|
-
export type { HubString, HubContract, SignalRContract, EventDef, MethodDef, HubDef, InferContract, EventName, MethodName, EventArgs, MethodArgs, MethodReturn, HubConnectionStatus, ReconnectConfig, PerHubConfig, SignalRClientConfig, ResolvedHubConfig, InvokeOptions, TeardownOptions, } from "./types";
|
|
3
|
-
export { hubKeys, resolveHubConfig, isRetriableConnectError } from "./config";
|
|
4
|
-
export { DEFAULT_BACKOFF, InvokeError, isRetriableInvokeError, resolveBackoff, sleep, } from "./retry";
|
|
5
|
-
export type { HubEntry } from "./hub-entry";
|
|
6
|
-
export { createConnectionManager } from "./connection-manager";
|
|
7
|
-
export type { ConnectionManager, ConnectionManagerDeps } from "./connection-manager";
|
|
8
|
-
export type { StatusStore } from "./status-store";
|
|
9
|
-
export type { SignalRProviderPropsBase, SignalRContextValueBase } from "./context";
|
|
10
|
-
export { createInvoker, createSender, createTeardownSender } from "./calls";
|
|
11
|
-
export type {
|
|
1
|
+
export { event, method } from "./types.js";
|
|
2
|
+
export type { HubString, HubContract, SignalRContract, EventDef, MethodDef, HubDef, InferContract, EventName, MethodName, EventArgs, MethodArgs, MethodReturn, HubConnectionStatus, ReconnectConfig, PerHubConfig, SignalRClientConfig, ResolvedHubConfig, InvokeOptions, TeardownOptions, } from "./types.js";
|
|
3
|
+
export { hubKeys, resolveHubConfig, isRetriableConnectError } from "./config.js";
|
|
4
|
+
export { DEFAULT_BACKOFF, InvokeError, isRetriableInvokeError, resolveBackoff, sleep, } from "./retry.js";
|
|
5
|
+
export type { HubEntry } from "./hub-entry.js";
|
|
6
|
+
export { createConnectionManager } from "./connection-manager.js";
|
|
7
|
+
export type { ConnectionManager, ConnectionManagerDeps } from "./connection-manager.js";
|
|
8
|
+
export type { StatusStore } from "./status-store.js";
|
|
9
|
+
export type { SignalRProviderPropsBase, SignalRContextValueBase } from "./context.js";
|
|
10
|
+
export { createAbortScope, createInvoker, createSender, createTeardownSender, } from "./calls.js";
|
|
11
|
+
export type { AbortScope } from "./calls.js";
|
|
12
|
+
export type { CallTarget } from "./calls.js";
|
|
13
|
+
export { createSignalRSession } from "./session.js";
|
|
14
|
+
export type { SignalRSession, SignalRSessionDeps } from "./session.js";
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
export { event, method } from "./types";
|
|
2
|
-
export { hubKeys, resolveHubConfig, isRetriableConnectError } from "./config";
|
|
3
|
-
export { DEFAULT_BACKOFF, InvokeError, isRetriableInvokeError, resolveBackoff, sleep, } from "./retry";
|
|
4
|
-
export { createConnectionManager } from "./connection-manager";
|
|
5
|
-
export { createInvoker, createSender, createTeardownSender } from "./calls";
|
|
1
|
+
export { event, method } from "./types.js";
|
|
2
|
+
export { hubKeys, resolveHubConfig, isRetriableConnectError } from "./config.js";
|
|
3
|
+
export { DEFAULT_BACKOFF, InvokeError, isRetriableInvokeError, resolveBackoff, sleep, } from "./retry.js";
|
|
4
|
+
export { createConnectionManager } from "./connection-manager.js";
|
|
5
|
+
export { createAbortScope, createInvoker, createSender, createTeardownSender, } from "./calls.js";
|
|
6
|
+
export { createSignalRSession } from "./session.js";
|
package/dist/retry.js
CHANGED
|
@@ -51,11 +51,18 @@ export function resolveBackoff(backoff, attempt) {
|
|
|
51
51
|
}
|
|
52
52
|
/** setTimeout wrapped as a cancellable promise. */
|
|
53
53
|
export function sleep(ms, signal) {
|
|
54
|
+
// An already-aborted signal never fires "abort", so check before listening.
|
|
55
|
+
if (signal?.aborted)
|
|
56
|
+
return Promise.reject(new AbortError("aborted"));
|
|
54
57
|
return new Promise((resolve, reject) => {
|
|
55
|
-
const
|
|
56
|
-
signal?.addEventListener("abort", () => {
|
|
58
|
+
const onAbort = () => {
|
|
57
59
|
clearTimeout(t);
|
|
58
60
|
reject(new AbortError("aborted"));
|
|
59
|
-
}
|
|
61
|
+
};
|
|
62
|
+
const t = setTimeout(() => {
|
|
63
|
+
signal?.removeEventListener("abort", onAbort);
|
|
64
|
+
resolve();
|
|
65
|
+
}, ms);
|
|
66
|
+
signal?.addEventListener("abort", onAbort);
|
|
60
67
|
});
|
|
61
68
|
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import type { StatusStore } from "./status-store.js";
|
|
2
|
+
import type { HubConnectionStatus, HubString, ResolvedHubConfig, SignalRContract } from "./types.js";
|
|
3
|
+
import type { SignalRContextValueBase } from "./context.js";
|
|
4
|
+
export interface SignalRSessionDeps<T extends SignalRContract, TStore extends StatusStore<keyof T & HubString> = StatusStore<keyof T & HubString>> {
|
|
5
|
+
hubs: Array<keyof T & HubString>;
|
|
6
|
+
resolve: (hub: keyof T & HubString) => ResolvedHubConfig;
|
|
7
|
+
statusStore: TStore;
|
|
8
|
+
/** Read at call time so token rotation never rebuilds the connection. */
|
|
9
|
+
getAccessToken: () => string | Promise<string>;
|
|
10
|
+
onStatusChange?: (hub: keyof T & HubString, status: HubConnectionStatus) => void;
|
|
11
|
+
onError?: (hub: keyof T & HubString, error: unknown) => void;
|
|
12
|
+
}
|
|
13
|
+
export interface SignalRSession<T extends SignalRContract, TStore extends StatusStore<keyof T & HubString> = StatusStore<keyof T & HubString>> {
|
|
14
|
+
/** Build/replace the live manager generation for this baseUrl. Disposes the previous one. */
|
|
15
|
+
start: (baseUrl: string) => void;
|
|
16
|
+
/** Dispose the live generation and mark every hub disconnected. Idempotent. */
|
|
17
|
+
stop: () => void;
|
|
18
|
+
/** The value an adapter puts into its framework context. Stable identity. */
|
|
19
|
+
context: SignalRContextValueBase<T, TStore>;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Owns the adapter-facing half of a provider: the manager generation, lazy
|
|
23
|
+
* ref-counts, reconnect listeners, and the context value built on top of
|
|
24
|
+
* them. Framework adapters own only reactive translation, context
|
|
25
|
+
* propagation, and lifecycle binding — everything else lives here.
|
|
26
|
+
*/
|
|
27
|
+
export declare function createSignalRSession<T extends SignalRContract, TStore extends StatusStore<keyof T & HubString> = StatusStore<keyof T & HubString>>(deps: SignalRSessionDeps<T, TStore>): SignalRSession<T, TStore>;
|
package/dist/session.js
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { createConnectionManager } from "./connection-manager.js";
|
|
2
|
+
/**
|
|
3
|
+
* Owns the adapter-facing half of a provider: the manager generation, lazy
|
|
4
|
+
* ref-counts, reconnect listeners, and the context value built on top of
|
|
5
|
+
* them. Framework adapters own only reactive translation, context
|
|
6
|
+
* propagation, and lifecycle binding — everything else lives here.
|
|
7
|
+
*/
|
|
8
|
+
export function createSignalRSession(deps) {
|
|
9
|
+
const { hubs, resolve, statusStore, getAccessToken, onStatusChange, onError } = deps;
|
|
10
|
+
// Lazy ref-counts, pending stop timers, and reconnect listeners persist
|
|
11
|
+
// across rebuilds. The live manager is swapped per generation.
|
|
12
|
+
const refCounts = new Map();
|
|
13
|
+
const stopTimers = new Map();
|
|
14
|
+
const reconnectListeners = new Map();
|
|
15
|
+
let current = null;
|
|
16
|
+
const start = (baseUrl) => {
|
|
17
|
+
current?.dispose();
|
|
18
|
+
current = null;
|
|
19
|
+
const manager = createConnectionManager({
|
|
20
|
+
baseUrl,
|
|
21
|
+
hubs,
|
|
22
|
+
resolve,
|
|
23
|
+
getAccessToken: () => getAccessToken(),
|
|
24
|
+
refCounts,
|
|
25
|
+
stopTimers,
|
|
26
|
+
reconnectListeners,
|
|
27
|
+
onStatus: (hub, status) => {
|
|
28
|
+
statusStore.set(hub, status);
|
|
29
|
+
onStatusChange?.(hub, status);
|
|
30
|
+
},
|
|
31
|
+
onError: (hub, err) => onError?.(hub, err),
|
|
32
|
+
isCurrent: () => current === manager,
|
|
33
|
+
});
|
|
34
|
+
current = manager;
|
|
35
|
+
manager.reconcile(); // build eager hubs plus already-referenced lazy hubs
|
|
36
|
+
};
|
|
37
|
+
const stop = () => {
|
|
38
|
+
// Notify synchronous adapter stores while the live connections are still
|
|
39
|
+
// available, so they can detach event handlers deterministically.
|
|
40
|
+
hubs.forEach((h) => statusStore.set(h, "disconnected"));
|
|
41
|
+
current?.dispose();
|
|
42
|
+
current = null;
|
|
43
|
+
};
|
|
44
|
+
const context = {
|
|
45
|
+
getConnection: (hub) => current?.getConnection(hub) ?? null,
|
|
46
|
+
isHubConnected: (hub) => statusStore.get(hub) === "connected",
|
|
47
|
+
getStatus: (hub) => statusStore.get(hub),
|
|
48
|
+
statusStore,
|
|
49
|
+
waitForConnection: (hub, timeoutMs) => {
|
|
50
|
+
if (!current) {
|
|
51
|
+
return Promise.reject(new Error(`SignalR not connected: ${String(hub)}`));
|
|
52
|
+
}
|
|
53
|
+
return current.waitForConnection(hub, timeoutMs);
|
|
54
|
+
},
|
|
55
|
+
acquire: (hub) => {
|
|
56
|
+
const next = (refCounts.get(hub) ?? 0) + 1;
|
|
57
|
+
refCounts.set(hub, next);
|
|
58
|
+
if (next === 1)
|
|
59
|
+
current?.reconcile();
|
|
60
|
+
},
|
|
61
|
+
release: (hub) => {
|
|
62
|
+
const next = Math.max(0, (refCounts.get(hub) ?? 0) - 1);
|
|
63
|
+
refCounts.set(hub, next);
|
|
64
|
+
if (next === 0)
|
|
65
|
+
current?.reconcile();
|
|
66
|
+
},
|
|
67
|
+
registerReconnect: (hub, cb) => {
|
|
68
|
+
let set = reconnectListeners.get(hub);
|
|
69
|
+
if (!set)
|
|
70
|
+
reconnectListeners.set(hub, (set = new Set()));
|
|
71
|
+
set.add(cb);
|
|
72
|
+
return () => set.delete(cb);
|
|
73
|
+
},
|
|
74
|
+
};
|
|
75
|
+
return { start, stop, context };
|
|
76
|
+
}
|
package/dist/status-store.d.ts
CHANGED
package/dist/types.d.ts
CHANGED
|
@@ -56,7 +56,7 @@ type Methods<T, H extends keyof T> = NonNullable<T[H] extends {
|
|
|
56
56
|
export type EventName<T, H extends keyof T> = keyof Events<T, H> & string;
|
|
57
57
|
export type MethodName<T, H extends keyof T> = keyof Methods<T, H> & string;
|
|
58
58
|
export type EventArgs<T, H extends keyof T, E extends EventName<T, H>> = Events<T, H>[E] extends (...args: infer A) => any ? A : never;
|
|
59
|
-
export type MethodArgs<T, H extends keyof T, M extends MethodName<T, H>> = Methods<T, H>[M] extends (...args: infer A) => any ? A :
|
|
59
|
+
export type MethodArgs<T, H extends keyof T, M extends MethodName<T, H>> = Methods<T, H>[M] extends (...args: infer A) => any ? A : never;
|
|
60
60
|
export type MethodReturn<T, H extends keyof T, M extends MethodName<T, H>> = Methods<T, H>[M] extends (...args: any[]) => Promise<infer R> ? R : unknown;
|
|
61
61
|
export type HubConnectionStatus = "disconnected" | "connecting" | "connected" | "reconnecting"
|
|
62
62
|
/** Transient: fires once after a successful reconnect (not on the first connect). */
|
|
@@ -125,12 +125,12 @@ export interface InvokeOptions {
|
|
|
125
125
|
* the default rule. */
|
|
126
126
|
isRetriable?: (error: unknown) => boolean | undefined;
|
|
127
127
|
/**
|
|
128
|
-
* Keeps an in-flight call alive when the calling
|
|
129
|
-
* Default false: in-flight invokes are aborted on
|
|
130
|
-
* correct for query-like reads. Set true for a method invoked in
|
|
131
|
-
* cleanup, so it still reaches the server. The detached call
|
|
132
|
-
*
|
|
133
|
-
* connecting-race and lazy-hub case, use `useSignalRTeardown` instead.
|
|
128
|
+
* Keeps an in-flight call alive when the calling consumer tears down.
|
|
129
|
+
* Default false: in-flight invokes are aborted on teardown, which is
|
|
130
|
+
* correct for query-like reads. Set true for a method invoked in a
|
|
131
|
+
* cleanup handler, so it still reaches the server. The detached call
|
|
132
|
+
* survives teardown, but a still-pending retry loop is NOT cancelled. For
|
|
133
|
+
* the connecting-race and lazy-hub case, use `useSignalRTeardown` instead.
|
|
134
134
|
*/
|
|
135
135
|
keepAliveOnUnmount?: boolean;
|
|
136
136
|
}
|
package/package.json
CHANGED
|
@@ -1,12 +1,25 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dammers/use-signalr-core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.0",
|
|
4
4
|
"description": "Framework-free typed multi-hub SignalR core: connection lifecycle, contracts, retry.",
|
|
5
5
|
"author": "Dammers",
|
|
6
6
|
"license": "MIT",
|
|
7
|
-
"repository":
|
|
8
|
-
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/DammersCode/use-signalr.git",
|
|
10
|
+
"directory": "packages/core"
|
|
11
|
+
},
|
|
12
|
+
"homepage": "https://github.com/DammersCode/use-signalr/tree/main/packages/core#readme",
|
|
9
13
|
"bugs": "https://github.com/DammersCode/use-signalr/issues",
|
|
14
|
+
"keywords": [
|
|
15
|
+
"signalr",
|
|
16
|
+
"typescript",
|
|
17
|
+
"realtime",
|
|
18
|
+
"websocket"
|
|
19
|
+
],
|
|
20
|
+
"engines": {
|
|
21
|
+
"node": ">=18"
|
|
22
|
+
},
|
|
10
23
|
"type": "module",
|
|
11
24
|
"sideEffects": false,
|
|
12
25
|
"main": "./dist/index.js",
|
|
@@ -24,6 +37,7 @@
|
|
|
24
37
|
"access": "public"
|
|
25
38
|
},
|
|
26
39
|
"scripts": {
|
|
40
|
+
"prebuild": "node -e \"require('fs').rmSync('dist',{recursive:true,force:true})\"",
|
|
27
41
|
"build": "tsc -p tsconfig.build.json",
|
|
28
42
|
"typecheck": "tsc --noEmit",
|
|
29
43
|
"test": "vitest run"
|