@owlmeans/client-socket 0.1.18-rc.5 → 0.1.18-rc.50
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 +22 -16
- package/agent-meta/manifest.json +2 -2
- package/agent-meta/skills/client-socket/SKILL.md +173 -8
- package/build/consts.d.ts +8 -0
- package/build/consts.d.ts.map +1 -0
- package/build/consts.js +17 -0
- package/build/consts.js.map +1 -0
- package/build/consts.local.d.ts +3 -0
- package/build/consts.local.d.ts.map +1 -0
- package/build/consts.local.js +2 -0
- package/build/consts.local.js.map +1 -0
- package/build/helper/types.d.ts +22 -0
- package/build/helper/types.d.ts.map +1 -0
- package/build/helper/types.js +2 -0
- package/build/helper/types.js.map +1 -0
- package/build/helper.d.ts +8 -4
- package/build/helper.d.ts.map +1 -1
- package/build/helper.js +79 -49
- package/build/helper.js.map +1 -1
- package/build/hooks.d.ts +18 -0
- package/build/hooks.d.ts.map +1 -0
- package/build/hooks.js +66 -0
- package/build/hooks.js.map +1 -0
- package/build/index.d.ts +4 -0
- package/build/index.d.ts.map +1 -1
- package/build/index.js +3 -0
- package/build/index.js.map +1 -1
- package/build/status.d.ts +30 -0
- package/build/status.d.ts.map +1 -0
- package/build/status.js +151 -0
- package/build/status.js.map +1 -0
- package/build/types.d.ts +75 -0
- package/build/types.d.ts.map +1 -1
- package/build/utils/connection.d.ts +12 -3
- package/build/utils/connection.d.ts.map +1 -1
- package/build/utils/connection.js +264 -28
- package/build/utils/connection.js.map +1 -1
- package/build/utils/consts.local.d.ts +6 -0
- package/build/utils/consts.local.d.ts.map +1 -0
- package/build/utils/consts.local.js +6 -0
- package/build/utils/consts.local.js.map +1 -0
- package/build/utils/index.d.ts +1 -0
- package/build/utils/index.d.ts.map +1 -1
- package/build/utils/types.d.ts +31 -0
- package/build/utils/types.d.ts.map +1 -0
- package/build/utils/types.js +2 -0
- package/build/utils/types.js.map +1 -0
- package/package.json +15 -11
- package/src/consts.local.ts +3 -0
- package/src/consts.ts +20 -0
- package/src/helper/types.ts +20 -0
- package/src/helper.ts +95 -53
- package/src/hooks.ts +75 -0
- package/src/index.ts +4 -0
- package/src/status.ts +162 -0
- package/src/types.ts +84 -1
- package/src/utils/connection.ts +256 -33
- package/src/utils/consts.local.ts +5 -0
- package/src/utils/index.ts +1 -0
- package/src/utils/types.ts +33 -0
- package/tests/context.ts +20 -0
- package/tests/reconnect.spec.ts +372 -0
- package/tests/tsconfig.json +12 -0
- package/tsconfig.json +1 -1
- package/build/.gitkeep +0 -0
package/src/helper.ts
CHANGED
|
@@ -1,68 +1,110 @@
|
|
|
1
|
-
import type
|
|
1
|
+
import { type ClientEntrypoint, clientRequestHelper } from '@owlmeans/client-entrypoint'
|
|
2
2
|
import type { AbstractRequest } from '@owlmeans/entrypoint'
|
|
3
|
-
import {
|
|
4
|
-
import { EntrypointOutcome } from '@owlmeans/entrypoint'
|
|
5
|
-
import type { Connection } from '@owlmeans/socket'
|
|
6
|
-
import { SocketInitializationError } from '@owlmeans/socket'
|
|
3
|
+
import { type Connection, SocketConnectionError } from '@owlmeans/socket'
|
|
7
4
|
import { makeConnection } from './utils/connection.js'
|
|
8
5
|
import { assertContext } from '@owlmeans/context'
|
|
9
|
-
import type { Config, Context } from './types.js'
|
|
10
|
-
import {
|
|
11
|
-
import {
|
|
12
|
-
import {
|
|
13
|
-
import {
|
|
6
|
+
import type { Config, Context, ConnectOptions, ReconnectPolicy, SocketStatusServiceAppend, WsOptions } from './types.js'
|
|
7
|
+
import type { SocketClientHelper } from './helper/types.js'
|
|
8
|
+
import { makeApiCallHelper } from '@owlmeans/client-entrypoint/utils'
|
|
9
|
+
import { createIdOfLength } from '@owlmeans/basic-ids'
|
|
10
|
+
import { DEFAULT_RECONNECT_POLICY, SOCKET_STATUS } from './consts.js'
|
|
14
11
|
|
|
15
|
-
export const
|
|
16
|
-
const
|
|
17
|
-
|
|
18
|
-
|
|
12
|
+
export const createSocketClientHelper = (): SocketClientHelper => {
|
|
13
|
+
const resolvePolicy = (
|
|
14
|
+
ctx: Context, options?: ConnectOptions
|
|
15
|
+
): { policy: ReconnectPolicy, retry: boolean } => {
|
|
16
|
+
const requested = options?.reconnect !== undefined ? options.reconnect : ctx.cfg.socket?.reconnect
|
|
17
|
+
const retry = requested !== false
|
|
18
|
+
const overrides = requested === false || requested == null ? {} : requested
|
|
19
|
+
return { policy: { ...DEFAULT_RECONNECT_POLICY, ...overrides }, retry }
|
|
20
|
+
}
|
|
19
21
|
|
|
20
|
-
|
|
21
|
-
|
|
22
|
+
const openRawSocket = async (url: string): Promise<WebSocket> => {
|
|
23
|
+
const socket = new WebSocket(url)
|
|
24
|
+
return await new Promise<WebSocket>((resolve, reject) => {
|
|
25
|
+
const cleanup = () => {
|
|
26
|
+
socket.removeEventListener('open', onOpen)
|
|
27
|
+
socket.removeEventListener('error', onFail)
|
|
28
|
+
socket.removeEventListener('close', onFail)
|
|
29
|
+
}
|
|
30
|
+
const onOpen = () => { cleanup(); resolve(socket) }
|
|
31
|
+
const onFail = () => { cleanup(); reject(new SocketConnectionError('handshake')) }
|
|
32
|
+
socket.addEventListener('open', onOpen)
|
|
33
|
+
socket.addEventListener('error', onFail)
|
|
34
|
+
socket.addEventListener('close', onFail)
|
|
35
|
+
})
|
|
22
36
|
}
|
|
23
|
-
const socket = new WebSocket(url)
|
|
24
37
|
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
}, 30_000)
|
|
38
|
+
const establish = async (
|
|
39
|
+
ctx: Context, policy: ReconnectPolicy, retry: boolean, open: () => Promise<WebSocket>
|
|
40
|
+
): Promise<Connection> => {
|
|
41
|
+
const statusId = createIdOfLength(8)
|
|
42
|
+
const status = ctx.hasService(SOCKET_STATUS)
|
|
43
|
+
? (ctx as unknown as SocketStatusServiceAppend).socketStatus() : null
|
|
32
44
|
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
45
|
+
let opened = false
|
|
46
|
+
let lost = false
|
|
47
|
+
const managed = makeConnection({
|
|
48
|
+
policy, retry, open, onStatus: state => {
|
|
49
|
+
lost = state === 'lost'
|
|
50
|
+
status?.report(statusId, state, state === 'online' ? undefined : revive)
|
|
51
|
+
}
|
|
52
|
+
})
|
|
53
|
+
const { connection, ready } = managed
|
|
37
54
|
|
|
38
|
-
|
|
55
|
+
const baseClose = connection.close
|
|
56
|
+
connection.close = async () => {
|
|
57
|
+
await baseClose()
|
|
58
|
+
status?.release(statusId)
|
|
39
59
|
}
|
|
40
|
-
})
|
|
41
|
-
}
|
|
42
60
|
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
[module]
|
|
48
|
-
)
|
|
49
|
-
const connection = useValue<Connection>(async () => {
|
|
50
|
-
const _request = provideRequest(mod.getAlias(), mod.getPath())
|
|
51
|
-
Object.assign(_request, request)
|
|
52
|
-
return await ws(mod, _request)
|
|
53
|
-
}, [
|
|
54
|
-
mod.getAlias(),
|
|
55
|
-
request?.query?.[AUTH_QUERY],
|
|
56
|
-
request?.params ? JSON.stringify(request.params) : undefined
|
|
57
|
-
])
|
|
58
|
-
|
|
59
|
-
useEffect(() => {
|
|
60
|
-
if (connection != null) {
|
|
61
|
-
return () => {
|
|
62
|
-
void connection.close()
|
|
61
|
+
const revive = () => {
|
|
62
|
+
if (opened || !lost) {
|
|
63
|
+
managed.revive()
|
|
64
|
+
return
|
|
63
65
|
}
|
|
66
|
+
// Never opened, so `ws()` already rejected and nobody holds this connection to hand a revived
|
|
67
|
+
// socket to: drop it for good and leave re-dialing to its owner (`useWs` does, on `onRetry`).
|
|
68
|
+
void baseClose()
|
|
69
|
+
status?.release(statusId)
|
|
64
70
|
}
|
|
65
|
-
}, [connection])
|
|
66
71
|
|
|
67
|
-
|
|
72
|
+
// A rejection leaves this id reporting `'lost'` rather than releasing it — there is no
|
|
73
|
+
// `Connection` to hand back for a caller to close, and the aggregate is what puts
|
|
74
|
+
// `SocketReloadDialog` up. It is released by `revive` above, on the next `retry()`.
|
|
75
|
+
await ready
|
|
76
|
+
opened = true
|
|
77
|
+
|
|
78
|
+
return connection
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
const connect = async (
|
|
82
|
+
address: () => Promise<string> | string, ctx: Context, options?: ConnectOptions
|
|
83
|
+
): Promise<Connection> => {
|
|
84
|
+
const { policy, retry } = resolvePolicy(ctx, options)
|
|
85
|
+
return await establish(ctx, policy, retry, async () => openRawSocket(await address()))
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const ws = async (
|
|
89
|
+
module: ClientEntrypoint<string>, request?: AbstractRequest<{ token?: string }>, options?: WsOptions
|
|
90
|
+
): Promise<Connection> => {
|
|
91
|
+
const ctx = assertContext<Config, Context>(module.ctx as Context, 'client-ws')
|
|
92
|
+
request = request ?? clientRequestHelper.provideRequest(module.alias, module.path())
|
|
93
|
+
const { policy, retry } = resolvePolicy(ctx, options)
|
|
94
|
+
|
|
95
|
+
return await establish(ctx, policy, retry, async () => {
|
|
96
|
+
await options?.beforeConnect?.(request!)
|
|
97
|
+
const url = await makeApiCallHelper({ ref: module }).entrypointUrl(request)
|
|
98
|
+
return await openRawSocket(url)
|
|
99
|
+
})
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
return { connect, ws }
|
|
68
103
|
}
|
|
104
|
+
|
|
105
|
+
export const socketClientHelper = createSocketClientHelper()
|
|
106
|
+
|
|
107
|
+
/** @deprecated compat:factory-refactor — use `socketClientHelper.ws(…)` */
|
|
108
|
+
export const ws = (
|
|
109
|
+
module: ClientEntrypoint<string>, request?: AbstractRequest<{ token?: string }>, options?: WsOptions
|
|
110
|
+
): Promise<Connection> => socketClientHelper.ws(module, request, options)
|
package/src/hooks.ts
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { type ClientEntrypoint, clientRequestHelper } from '@owlmeans/client-entrypoint'
|
|
2
|
+
import type { AbstractRequest } from '@owlmeans/entrypoint'
|
|
3
|
+
import type { Connection } from '@owlmeans/socket'
|
|
4
|
+
import type { EntrypointReference } from '@owlmeans/context'
|
|
5
|
+
import type { SocketStatusServiceAppend, WsOptions } from './types.js'
|
|
6
|
+
import { useContext, useValue } from '@owlmeans/client'
|
|
7
|
+
import { AUTH_QUERY } from '@owlmeans/auth'
|
|
8
|
+
import { useEffect, useMemo, useState } from 'react'
|
|
9
|
+
import { SOCKET_STATUS } from './consts.js'
|
|
10
|
+
import { socketClientHelper } from './helper.js'
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Open a socket through a declared entrypoint protocol.
|
|
14
|
+
*
|
|
15
|
+
* String aliases remain an adapter input for dynamically addressed integrations, while
|
|
16
|
+
* application callers pass their immutable protocol declaration and receive its bound client
|
|
17
|
+
* entrypoint here at the transport boundary.
|
|
18
|
+
*
|
|
19
|
+
* Re-opens on its own after a network drop (see `ws()`). `null` until the first attempt opens,
|
|
20
|
+
* and again once the retry budget elapses without one ever opening — dialed afresh on the next
|
|
21
|
+
* `SocketStatusService.retry()`. A screen that must tell those two apart reads
|
|
22
|
+
* `useSocketStatus()` (from `./status.js`) alongside this.
|
|
23
|
+
*/
|
|
24
|
+
export const useWs = (
|
|
25
|
+
module: EntrypointReference | string, request?: Partial<AbstractRequest<any>>, options?: WsOptions
|
|
26
|
+
): Connection | null => {
|
|
27
|
+
const ctx = useContext()
|
|
28
|
+
const mod = useMemo(
|
|
29
|
+
() => ctx.entrypoint<ClientEntrypoint>(module),
|
|
30
|
+
[module]
|
|
31
|
+
)
|
|
32
|
+
const [failed, setFailed] = useState(false)
|
|
33
|
+
const [dial, setDial] = useState(0)
|
|
34
|
+
const connection = useValue<Connection | null>(async (cancel) => {
|
|
35
|
+
const _request = clientRequestHelper.provideRequest(mod.alias, mod.path())
|
|
36
|
+
Object.assign(_request, request)
|
|
37
|
+
try {
|
|
38
|
+
const conn = await socketClientHelper.ws(mod, _request, options)
|
|
39
|
+
if (cancel?.current) {
|
|
40
|
+
// The component unmounted while the handshake (or its retries) were still in flight —
|
|
41
|
+
// there is no `useEffect` cleanup coming for this value, so close it here instead of
|
|
42
|
+
// leaving a live socket and its retry timers attached to nothing.
|
|
43
|
+
void conn.close()
|
|
44
|
+
return null
|
|
45
|
+
}
|
|
46
|
+
return conn
|
|
47
|
+
} catch {
|
|
48
|
+
if (!cancel?.current) setFailed(true)
|
|
49
|
+
return null
|
|
50
|
+
}
|
|
51
|
+
}, [
|
|
52
|
+
mod.alias,
|
|
53
|
+
request?.query?.[AUTH_QUERY],
|
|
54
|
+
request?.params ? JSON.stringify(request.params) : undefined,
|
|
55
|
+
dial
|
|
56
|
+
])
|
|
57
|
+
|
|
58
|
+
useEffect(() => {
|
|
59
|
+
if (!failed || !ctx.hasService(SOCKET_STATUS)) return
|
|
60
|
+
return (ctx as unknown as SocketStatusServiceAppend).socketStatus().onRetry(() => {
|
|
61
|
+
setFailed(false)
|
|
62
|
+
setDial(n => n + 1)
|
|
63
|
+
})
|
|
64
|
+
}, [failed])
|
|
65
|
+
|
|
66
|
+
useEffect(() => {
|
|
67
|
+
if (connection != null) {
|
|
68
|
+
return () => {
|
|
69
|
+
void connection.close()
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
}, [connection])
|
|
73
|
+
|
|
74
|
+
return connection
|
|
75
|
+
}
|
package/src/index.ts
CHANGED
package/src/status.ts
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
import { createService } from '@owlmeans/context'
|
|
2
|
+
import { useContext } from '@owlmeans/client'
|
|
3
|
+
import { useCallback, useEffect, useState } from 'react'
|
|
4
|
+
import type {
|
|
5
|
+
Config, Context, SocketConnectionState, SocketStatusService, SocketStatusServiceAppend
|
|
6
|
+
} from './types.js'
|
|
7
|
+
import { RANK } from './consts.local.js'
|
|
8
|
+
import { SOCKET_STATUS } from './consts.js'
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Aggregates the coarse health of every `ws()`/`useWs()` connection an app has open into one
|
|
12
|
+
* worst-of-all state. A page with several sockets (thinking stream, file watch, notifications…)
|
|
13
|
+
* still shows one dialog, not one per socket — so the aggregate, not any single connection, is
|
|
14
|
+
* what a UI like `SocketReloadDialog` reads.
|
|
15
|
+
*/
|
|
16
|
+
export const createSocketStatusService = (alias: string = SOCKET_STATUS): SocketStatusService => {
|
|
17
|
+
const states = new Map<string, SocketConnectionState>()
|
|
18
|
+
const revivers = new Map<string, () => void>()
|
|
19
|
+
const listeners = new Set<(state: SocketConnectionState) => void>()
|
|
20
|
+
const retryListeners = new Set<() => void>()
|
|
21
|
+
let current: SocketConnectionState = 'online'
|
|
22
|
+
|
|
23
|
+
const recompute = () => {
|
|
24
|
+
let worst: SocketConnectionState = 'online'
|
|
25
|
+
for (const state of states.values()) {
|
|
26
|
+
if (RANK[state] > RANK[worst]) worst = state
|
|
27
|
+
}
|
|
28
|
+
if (worst !== current) {
|
|
29
|
+
current = worst
|
|
30
|
+
listeners.forEach(listener => listener(current))
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// Connections still retrying are nudged too, so one whose older budget is about to run out does
|
|
35
|
+
// not report `'lost'` right after its lost siblings were revived.
|
|
36
|
+
const retry = (): boolean => {
|
|
37
|
+
const pending = [...states].filter(([, state]) => state !== 'online')
|
|
38
|
+
pending.forEach(([id]) => revivers.get(id)?.())
|
|
39
|
+
if (!pending.some(([, state]) => state === 'lost')) return false
|
|
40
|
+
retryListeners.forEach(listener => listener())
|
|
41
|
+
return true
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// A backgrounded tab is where sockets die unnoticed (throttled timers, a sleeping machine), so
|
|
45
|
+
// the moment it is looked at again is the moment to retry — before anyone reaches for a button.
|
|
46
|
+
const watchActivation = () => {
|
|
47
|
+
if (typeof document === 'undefined' || typeof window === 'undefined') return
|
|
48
|
+
document.addEventListener('visibilitychange', () => {
|
|
49
|
+
if (document.visibilityState === 'visible') retry()
|
|
50
|
+
})
|
|
51
|
+
window.addEventListener('focus', () => { retry() })
|
|
52
|
+
window.addEventListener('online', () => { retry() })
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
return createService<SocketStatusService>(alias, {
|
|
56
|
+
report: (id, state, revive) => {
|
|
57
|
+
states.set(id, state)
|
|
58
|
+
if (revive != null) revivers.set(id, revive)
|
|
59
|
+
else revivers.delete(id)
|
|
60
|
+
recompute()
|
|
61
|
+
},
|
|
62
|
+
release: (id) => { states.delete(id); revivers.delete(id); recompute() },
|
|
63
|
+
state: () => current,
|
|
64
|
+
subscribe: listener => {
|
|
65
|
+
listeners.add(listener)
|
|
66
|
+
return () => { listeners.delete(listener) }
|
|
67
|
+
},
|
|
68
|
+
retry,
|
|
69
|
+
onRetry: listener => {
|
|
70
|
+
retryListeners.add(listener)
|
|
71
|
+
return () => { retryListeners.delete(listener) }
|
|
72
|
+
},
|
|
73
|
+
}, service => async () => {
|
|
74
|
+
watchActivation()
|
|
75
|
+
service.initialized = true
|
|
76
|
+
})
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Register the shared socket-status aggregator. Idempotent, and cheap enough for a host package
|
|
81
|
+
* (`@owlmeans/web-panel`) to call unconditionally on every context: every `ws()`/`useWs()`
|
|
82
|
+
* connection reports itself here if — and only if — the context carries this service, so an app
|
|
83
|
+
* that never calls this behaves exactly as it did before reconnect support existed.
|
|
84
|
+
*/
|
|
85
|
+
export const appendSocketStatus = <C extends Config = Config, T extends Context<C> = Context<C>>(
|
|
86
|
+
ctx: T, alias: string = SOCKET_STATUS
|
|
87
|
+
): T & SocketStatusServiceAppend => {
|
|
88
|
+
const _ctx = ctx as T & SocketStatusServiceAppend
|
|
89
|
+
if (!ctx.hasService(alias)) {
|
|
90
|
+
ctx.registerService(createSocketStatusService(alias))
|
|
91
|
+
}
|
|
92
|
+
_ctx.socketStatus = () => ctx.service(alias)
|
|
93
|
+
return _ctx
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
const readSocketStatusService = (
|
|
97
|
+
ctx: Context & Partial<SocketStatusServiceAppend>
|
|
98
|
+
): SocketStatusService | null => {
|
|
99
|
+
try {
|
|
100
|
+
return typeof ctx.hasService === 'function' && ctx.hasService(SOCKET_STATUS)
|
|
101
|
+
? ctx.socketStatus?.() ?? null : null
|
|
102
|
+
} catch {
|
|
103
|
+
// Registered but not yet run through the context's OWN `init()` — a component that renders
|
|
104
|
+
// as a sibling of the router (as `SocketReloadDialog` does) mounts before that finishes,
|
|
105
|
+
// since `context.configure().init()` runs from the router's effect, not before React's
|
|
106
|
+
// first commit. Treat it as "not ready yet" rather than crash the render.
|
|
107
|
+
return null
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** The status service once the context can hand it out; `null` while it cannot, or never will. */
|
|
112
|
+
const useStatusService = (): SocketStatusService | null => {
|
|
113
|
+
const ctx = useContext() as unknown as Context & Partial<SocketStatusServiceAppend>
|
|
114
|
+
const [service, setService] = useState<SocketStatusService | null>(() => readSocketStatusService(ctx))
|
|
115
|
+
|
|
116
|
+
useEffect(() => {
|
|
117
|
+
if (service != null) return
|
|
118
|
+
let cancelled = false
|
|
119
|
+
void ctx.waitForInitialized?.().then(() => { if (!cancelled) setService(readSocketStatusService(ctx)) })
|
|
120
|
+
return () => { cancelled = true }
|
|
121
|
+
}, [ctx, service])
|
|
122
|
+
|
|
123
|
+
return service
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* The worst state across every live `ws()`/`useWs()` connection, or `'online'` if the app never
|
|
128
|
+
* registered the status service (`appendSocketStatus`) or has not finished initializing yet.
|
|
129
|
+
*/
|
|
130
|
+
export const useSocketStatus = (): SocketConnectionState => {
|
|
131
|
+
const service = useStatusService()
|
|
132
|
+
const [state, setState] = useState<SocketConnectionState>(() => service?.state() ?? 'online')
|
|
133
|
+
|
|
134
|
+
useEffect(() => {
|
|
135
|
+
if (service == null) return
|
|
136
|
+
setState(service.state())
|
|
137
|
+
return service.subscribe(setState)
|
|
138
|
+
}, [service])
|
|
139
|
+
|
|
140
|
+
return state
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* `retry` revives every lost connection now (`SocketStatusService.retry()`); `retrying` is true
|
|
145
|
+
* from any retry — this one, or the service's own on tab activation — until the aggregate settles
|
|
146
|
+
* back on `'online'` or `'lost'`.
|
|
147
|
+
*/
|
|
148
|
+
export const useSocketRetry = (): { retry: () => void, retrying: boolean } => {
|
|
149
|
+
const service = useStatusService()
|
|
150
|
+
const [retrying, setRetrying] = useState(false)
|
|
151
|
+
|
|
152
|
+
useEffect(() => {
|
|
153
|
+
if (service == null) return
|
|
154
|
+
const stopRetry = service.onRetry(() => setRetrying(service.state() === 'reconnecting'))
|
|
155
|
+
const stopState = service.subscribe(state => { if (state !== 'reconnecting') setRetrying(false) })
|
|
156
|
+
return () => { stopRetry(); stopState() }
|
|
157
|
+
}, [service])
|
|
158
|
+
|
|
159
|
+
const retry = useCallback(() => { service?.retry() }, [service])
|
|
160
|
+
|
|
161
|
+
return { retry, retrying }
|
|
162
|
+
}
|
package/src/types.ts
CHANGED
|
@@ -1,7 +1,90 @@
|
|
|
1
1
|
|
|
2
2
|
import type { ClientConfig } from '@owlmeans/client-context'
|
|
3
3
|
import type { ClientContext } from '@owlmeans/client'
|
|
4
|
+
import type { AbstractRequest } from '@owlmeans/entrypoint'
|
|
5
|
+
import type { InitializedService } from '@owlmeans/context'
|
|
4
6
|
|
|
5
|
-
export interface Config extends ClientConfig {
|
|
7
|
+
export interface Config extends ClientConfig {
|
|
8
|
+
socket?: SocketClientSettings
|
|
9
|
+
}
|
|
6
10
|
|
|
7
11
|
export interface Context<C extends Config = Config> extends ClientContext<C> { }
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* How aggressively a dropped socket is retried, and when the carrier gives up on it.
|
|
15
|
+
*
|
|
16
|
+
* The delay grows geometrically from `minDelay` to `maxDelay` (±`jitter`, a fraction of the
|
|
17
|
+
* computed delay) and stays there. `budget` is measured from the connection's FIRST failed
|
|
18
|
+
* attempt in an outage — a socket that opens and drops again right away does not get a fresh
|
|
19
|
+
* budget — and `stableAfter` is how long a reopened socket must stay up before the attempt
|
|
20
|
+
* counter and the outage clock reset, so a flapping link is never read as "recovered" between
|
|
21
|
+
* two drops a second apart.
|
|
22
|
+
*/
|
|
23
|
+
export interface ReconnectPolicy {
|
|
24
|
+
/** First retry delay, in ms. Default 200. */
|
|
25
|
+
minDelay: number
|
|
26
|
+
/** Delay ceiling, in ms — the backoff never grows past this. Default 3000. */
|
|
27
|
+
maxDelay: number
|
|
28
|
+
/** Geometric growth factor applied to the delay after every failed attempt. Default 2. */
|
|
29
|
+
factor: number
|
|
30
|
+
/** Randomization applied to each computed delay, as a fraction of it. Default 0.1 (±10%). */
|
|
31
|
+
jitter: number
|
|
32
|
+
/** Total time, in ms, the carrier keeps retrying before it reports the socket lost. Default
|
|
33
|
+
* 600000 (10 minutes). */
|
|
34
|
+
budget: number
|
|
35
|
+
/** Retry window, in ms, of an outage restarted on a lost socket by `SocketStatusService.retry()`
|
|
36
|
+
* (a "Try again" press, the tab coming back) — short, so a retry that cannot succeed reports
|
|
37
|
+
* `'lost'` again while someone is still looking. Default 15000. */
|
|
38
|
+
reviveBudget: number
|
|
39
|
+
/** How long a reopened socket must stay open before the attempt count and the outage clock
|
|
40
|
+
* reset, in ms. Default 10000. */
|
|
41
|
+
stableAfter: number
|
|
42
|
+
/** Heartbeat ping interval, in ms. Default 30000. */
|
|
43
|
+
heartbeat: number
|
|
44
|
+
/** How long to wait for ANY inbound frame after a ping before treating the socket as dead and
|
|
45
|
+
* forcing it closed, in ms. Default 10000. */
|
|
46
|
+
pongTimeout: number
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export interface SocketClientSettings {
|
|
50
|
+
/** `false` disables reconnection outright — a dropped socket is reported gone and stays gone,
|
|
51
|
+
* the pre-reconnect-support behaviour. Anything else merges over the defaults. */
|
|
52
|
+
reconnect?: false | Partial<ReconnectPolicy>
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export interface ConnectOptions {
|
|
56
|
+
reconnect?: false | Partial<ReconnectPolicy>
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export interface WsOptions extends ConnectOptions {
|
|
60
|
+
/**
|
|
61
|
+
* Run before every connection attempt, the first one included, given the request that will be
|
|
62
|
+
* turned into the socket URL — where a caller refreshes a token or other query/param value
|
|
63
|
+
* that may have changed since the previous attempt.
|
|
64
|
+
*/
|
|
65
|
+
beforeConnect?: (request: AbstractRequest<any>) => void | Promise<void>
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** The coarse health of a socket connection — the worst of everything a status service tracks. */
|
|
69
|
+
export type SocketConnectionState = 'online' | 'reconnecting' | 'lost'
|
|
70
|
+
|
|
71
|
+
export interface SocketStatusService extends InitializedService {
|
|
72
|
+
/** Record this connection's current state under `id` — call again to update it. `revive` is
|
|
73
|
+
* how `retry()` brings it back (`'lost'`) or hurries it (`'reconnecting'`); every report
|
|
74
|
+
* replaces the previous one. */
|
|
75
|
+
report: (id: string, state: SocketConnectionState, revive?: () => void) => void
|
|
76
|
+
/** Stop tracking `id` (the connection closed on purpose). */
|
|
77
|
+
release: (id: string) => void
|
|
78
|
+
/** The worst state across every tracked connection; `'online'` when none are tracked. */
|
|
79
|
+
state: () => SocketConnectionState
|
|
80
|
+
subscribe: (listener: (state: SocketConnectionState) => void) => () => void
|
|
81
|
+
/** Revive every `'lost'` connection and hurry every `'reconnecting'` one, then tell `onRetry`
|
|
82
|
+
* listeners. `false` (and no listener call) when nothing was lost. Also fires by itself when a
|
|
83
|
+
* browser tab becomes visible, its window gains focus, or the network comes back online. */
|
|
84
|
+
retry: () => boolean
|
|
85
|
+
onRetry: (listener: () => void) => () => void
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export interface SocketStatusServiceAppend {
|
|
89
|
+
socketStatus: () => SocketStatusService
|
|
90
|
+
}
|