@linxin666/dsh-remote-bridge 0.0.0-stage → 0.4.8
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/LICENSE +202 -0
- package/README.i18n.yaml +6 -0
- package/README.md +277 -2
- package/README.zh.md +276 -0
- package/cordis.patch.yml +17 -0
- package/icon.svg +3 -0
- package/lib/client.js +1830 -0
- package/lib/client.js.map +1 -0
- package/lib/index.js +5789 -0
- package/lib/types/client/PairEntry.d.ts +16 -0
- package/lib/types/client/PairPanel.d.ts +55 -0
- package/lib/types/client/icons.d.ts +18 -0
- package/lib/types/client/index.d.ts +35 -0
- package/lib/types/client/locales.d.ts +42 -0
- package/lib/types/client/pair-token.d.ts +73 -0
- package/lib/types/client/semantic.d.ts +28 -0
- package/lib/types/core/approvals.d.ts +99 -0
- package/lib/types/core/connection.d.ts +170 -0
- package/lib/types/core/crypto.d.ts +48 -0
- package/lib/types/core/delta.d.ts +101 -0
- package/lib/types/core/devices.d.ts +72 -0
- package/lib/types/core/dsh-frames.d.ts +332 -0
- package/lib/types/core/envelope.d.ts +132 -0
- package/lib/types/core/extension.d.ts +144 -0
- package/lib/types/core/gateway-errors.d.ts +49 -0
- package/lib/types/core/hub.d.ts +127 -0
- package/lib/types/core/jobs.d.ts +204 -0
- package/lib/types/core/loopback.d.ts +35 -0
- package/lib/types/core/owner-peer.d.ts +49 -0
- package/lib/types/core/pairing.d.ts +61 -0
- package/lib/types/core/protocol.d.ts +319 -0
- package/lib/types/core/questions.d.ts +294 -0
- package/lib/types/core/session-meta.d.ts +105 -0
- package/lib/types/core/session-permissions.d.ts +134 -0
- package/lib/types/core/wire.d.ts +115 -0
- package/lib/types/core/ws-frames.d.ts +72 -0
- package/lib/types/host/dsh-home.d.ts +16 -0
- package/lib/types/host/pair-origin.d.ts +44 -0
- package/lib/types/host/routes.d.ts +27 -0
- package/lib/types/host/websocket.d.ts +111 -0
- package/lib/types/index.d.ts +55 -0
- package/lib/types/mount-once.d.ts +55 -0
- package/locale/en.json +6 -0
- package/locale/ru.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +93 -3
- package/src/client/PairEntry.tsx +151 -0
- package/src/client/PairPanel.tsx +183 -0
- package/src/client/icons.tsx +72 -0
- package/src/client/index.ts +81 -0
- package/src/client/locales.ts +72 -0
- package/src/client/pair-token.ts +104 -0
- package/src/client/panel.module.css +344 -0
- package/src/client/semantic.ts +37 -0
- package/src/core/approvals.ts +173 -0
- package/src/core/connection.ts +1906 -0
- package/src/core/crypto.ts +113 -0
- package/src/core/delta.ts +204 -0
- package/src/core/devices.ts +209 -0
- package/src/core/dsh-frames.ts +843 -0
- package/src/core/envelope.ts +219 -0
- package/src/core/extension.ts +197 -0
- package/src/core/gateway-errors.ts +92 -0
- package/src/core/hub.ts +310 -0
- package/src/core/jobs.ts +372 -0
- package/src/core/loopback.ts +60 -0
- package/src/core/owner-peer.ts +70 -0
- package/src/core/pairing.ts +113 -0
- package/src/core/protocol.ts +381 -0
- package/src/core/questions.ts +630 -0
- package/src/core/session-meta.ts +176 -0
- package/src/core/session-permissions.ts +266 -0
- package/src/core/wire.ts +159 -0
- package/src/core/ws-frames.ts +139 -0
- package/src/css-modules.d.ts +6 -0
- package/src/host/dsh-home.ts +42 -0
- package/src/host/pair-origin.ts +77 -0
- package/src/host/routes.ts +85 -0
- package/src/host/websocket.ts +359 -0
- package/src/index.ts +257 -0
- package/src/mount-once.ts +142 -0
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Protocol v1 frame envelope: the one JSON-object-per-text-frame codec both
|
|
3
|
+
* ends of the bridge speak. Shapes are frozen by the parent card and are not
|
|
4
|
+
* ours to extend:
|
|
5
|
+
*
|
|
6
|
+
* request {"t":"req","id":<uint>,"m":"<method>","p":{...}}
|
|
7
|
+
* response {"t":"res","id":<uint>,"ok":true,"r":{...}}
|
|
8
|
+
* {"t":"res","id":<uint>,"ok":false,"e":{"code":"<str>","msg":"<str>"}}
|
|
9
|
+
* event {"t":"ev","seq":<uint>,"m":"<topic>","p":{...}}
|
|
10
|
+
* heartbeat {"t":"ping","ts":<ms>} / {"t":"pong","ts":<ms>}
|
|
11
|
+
*
|
|
12
|
+
* Decisions this module owns (not restated by the frozen design):
|
|
13
|
+
* - the 10 MiB cap is measured in UTF-8 bytes of the received text, before
|
|
14
|
+
* parsing, so an oversized frame never allocates a parsed object graph;
|
|
15
|
+
* - direction violations (a `res` or `ev` arriving FROM the client) are their
|
|
16
|
+
* own failure code instead of `malformed`, because "the peer is speaking the
|
|
17
|
+
* wrong half of the protocol" is an actionable diagnostic;
|
|
18
|
+
* - a frame whose identity cannot be recovered is answered with the reserved
|
|
19
|
+
* id 0, since the envelope has no way to decline answering.
|
|
20
|
+
* @module dsh-remote-bridge/core/envelope
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
import { deflateRawSync } from 'node:zlib'
|
|
24
|
+
|
|
25
|
+
/** Largest single text frame either direction may carry, in UTF-8 bytes: 10 MiB. */
|
|
26
|
+
export const MAX_FRAME_BYTES = 10 * 1024 * 1024
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Smallest frame the host compresses, in UTF-8 bytes. Below it the DEFLATE
|
|
30
|
+
* header alone can outweigh a small object, so such a frame is never even tried.
|
|
31
|
+
*/
|
|
32
|
+
export const FRAME_DEFLATE_MIN_BYTES = 1024
|
|
33
|
+
|
|
34
|
+
/** Reserved response id for a frame whose own id could not be recovered. */
|
|
35
|
+
export const UNIDENTIFIED_FRAME_ID = 0
|
|
36
|
+
|
|
37
|
+
export interface ReqFrame {
|
|
38
|
+
readonly t: 'req'
|
|
39
|
+
readonly id: number
|
|
40
|
+
readonly m: string
|
|
41
|
+
readonly p: Readonly<Record<string, unknown>>
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export interface PingFrame {
|
|
45
|
+
readonly t: 'ping'
|
|
46
|
+
readonly ts: number
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export interface PongFrame {
|
|
50
|
+
readonly t: 'pong'
|
|
51
|
+
readonly ts: number
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Every frame a client may legitimately send. */
|
|
55
|
+
export type ClientFrame = ReqFrame | PingFrame | PongFrame
|
|
56
|
+
|
|
57
|
+
export interface ResFrame {
|
|
58
|
+
readonly t: 'res'
|
|
59
|
+
readonly id: number
|
|
60
|
+
readonly ok: boolean
|
|
61
|
+
readonly r?: unknown
|
|
62
|
+
readonly e?: { readonly code: string; readonly msg: string }
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export interface EvFrame {
|
|
66
|
+
readonly t: 'ev'
|
|
67
|
+
readonly seq: number
|
|
68
|
+
readonly m: string
|
|
69
|
+
readonly p: unknown
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export type ServerFrame = ResFrame | EvFrame | PingFrame | PongFrame
|
|
73
|
+
|
|
74
|
+
/** One refusal the decoder can state about the bytes it was handed. */
|
|
75
|
+
export interface FrameFailure {
|
|
76
|
+
readonly ok: false
|
|
77
|
+
/** Response id to answer on: the recovered request id, else {@link UNIDENTIFIED_FRAME_ID}. */
|
|
78
|
+
readonly id: number
|
|
79
|
+
readonly code: string
|
|
80
|
+
readonly msg: string
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export type DecodeOutcome = { readonly ok: true; readonly frame: ClientFrame } | FrameFailure
|
|
84
|
+
|
|
85
|
+
/** Failure codes the codec itself raises. */
|
|
86
|
+
export const FRAME_TOO_LARGE = 'frame-too-large'
|
|
87
|
+
export const MALFORMED_FRAME = 'malformed'
|
|
88
|
+
export const DIRECTION_VIOLATION = 'direction-violation'
|
|
89
|
+
|
|
90
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
91
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** An envelope id is a non-negative safe integer. */
|
|
95
|
+
function isFrameId(value: unknown): value is number {
|
|
96
|
+
return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Decode one received text frame.
|
|
101
|
+
* @param text - the frame body exactly as it crossed the wire.
|
|
102
|
+
* @returns the frame, or the refusal to answer with.
|
|
103
|
+
*/
|
|
104
|
+
export function decodeClientFrame(text: string): DecodeOutcome {
|
|
105
|
+
if (Buffer.byteLength(text, 'utf8') > MAX_FRAME_BYTES) {
|
|
106
|
+
return { ok: false, id: UNIDENTIFIED_FRAME_ID, code: FRAME_TOO_LARGE, msg: `frame exceeds ${MAX_FRAME_BYTES} bytes` }
|
|
107
|
+
}
|
|
108
|
+
let parsed: unknown
|
|
109
|
+
try {
|
|
110
|
+
parsed = JSON.parse(text)
|
|
111
|
+
} catch {
|
|
112
|
+
return { ok: false, id: UNIDENTIFIED_FRAME_ID, code: MALFORMED_FRAME, msg: 'frame is not JSON' }
|
|
113
|
+
}
|
|
114
|
+
if (!isRecord(parsed)) {
|
|
115
|
+
return { ok: false, id: UNIDENTIFIED_FRAME_ID, code: MALFORMED_FRAME, msg: 'frame is not a JSON object' }
|
|
116
|
+
}
|
|
117
|
+
const kind = parsed.t
|
|
118
|
+
if (kind === 'ping' || kind === 'pong') {
|
|
119
|
+
if (typeof parsed.ts !== 'number' || !Number.isFinite(parsed.ts)) {
|
|
120
|
+
return { ok: false, id: UNIDENTIFIED_FRAME_ID, code: MALFORMED_FRAME, msg: `${kind} requires a numeric ts` }
|
|
121
|
+
}
|
|
122
|
+
return { ok: true, frame: { t: kind, ts: parsed.ts } }
|
|
123
|
+
}
|
|
124
|
+
if (kind === 'res' || kind === 'ev') {
|
|
125
|
+
return {
|
|
126
|
+
ok: false,
|
|
127
|
+
id: isFrameId(parsed.id) ? parsed.id : UNIDENTIFIED_FRAME_ID,
|
|
128
|
+
code: DIRECTION_VIOLATION,
|
|
129
|
+
msg: `a client must not send a ${kind} frame`,
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
if (kind !== 'req') {
|
|
133
|
+
return { ok: false, id: UNIDENTIFIED_FRAME_ID, code: MALFORMED_FRAME, msg: 'frame has no known t discriminator' }
|
|
134
|
+
}
|
|
135
|
+
if (!isFrameId(parsed.id)) {
|
|
136
|
+
return { ok: false, id: UNIDENTIFIED_FRAME_ID, code: MALFORMED_FRAME, msg: 'req requires a non-negative integer id' }
|
|
137
|
+
}
|
|
138
|
+
if (typeof parsed.m !== 'string' || parsed.m === '') {
|
|
139
|
+
return { ok: false, id: parsed.id, code: MALFORMED_FRAME, msg: 'req requires a method name' }
|
|
140
|
+
}
|
|
141
|
+
if (parsed.p !== undefined && !isRecord(parsed.p)) {
|
|
142
|
+
return { ok: false, id: parsed.id, code: MALFORMED_FRAME, msg: 'req payload must be a JSON object' }
|
|
143
|
+
}
|
|
144
|
+
return { ok: true, frame: { t: 'req', id: parsed.id, m: parsed.m, p: parsed.p ?? {} } }
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** Encode one outgoing frame. */
|
|
148
|
+
export function encodeFrame(frame: ServerFrame): string {
|
|
149
|
+
return JSON.stringify(frame)
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* How one encoded frame crosses the wire: as the text the codec produced, or as
|
|
154
|
+
* raw DEFLATE of exactly that text.
|
|
155
|
+
*/
|
|
156
|
+
export type OutboundPayload =
|
|
157
|
+
| { readonly binary: false; readonly text: string }
|
|
158
|
+
| { readonly binary: true; readonly deflated: Buffer }
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* Decide the wire form of one encoded frame.
|
|
162
|
+
*
|
|
163
|
+
* The decision is a byte-level question only, asked after the frame has been
|
|
164
|
+
* measured against {@link MAX_FRAME_BYTES}: the text is deflated exactly as it
|
|
165
|
+
* stands, so a peer that inflates gets back the frame the text path would have
|
|
166
|
+
* written. A frame below {@link FRAME_DEFLATE_MIN_BYTES}, and a frame DEFLATE
|
|
167
|
+
* does not shrink (zlib's default level), both stay text — a binary frame that
|
|
168
|
+
* is larger than the text it replaces would pay for itself in neither direction.
|
|
169
|
+
* @param text - the frame as {@link encodeFrame} produced it.
|
|
170
|
+
* @param compress - whether the peer declared the capability that permits this.
|
|
171
|
+
* @param deflate - the compressor: zlib's raw DEFLATE at its default level, unless
|
|
172
|
+
* a caller injects one. Real deflate shrinks every frame that reaches the
|
|
173
|
+
* threshold, so an injected compressor is the only way to exercise the no-gain
|
|
174
|
+
* rule with content that truly cannot be compressed.
|
|
175
|
+
* @returns the text, or raw DEFLATE of it.
|
|
176
|
+
*/
|
|
177
|
+
export function outboundPayloadOf(
|
|
178
|
+
text: string,
|
|
179
|
+
compress: boolean,
|
|
180
|
+
deflate: (source: Buffer) => Buffer = deflateRawSync,
|
|
181
|
+
): OutboundPayload {
|
|
182
|
+
if (!compress) return { binary: false, text }
|
|
183
|
+
const source = Buffer.from(text, 'utf8')
|
|
184
|
+
if (source.length < FRAME_DEFLATE_MIN_BYTES) return { binary: false, text }
|
|
185
|
+
const deflated = deflate(source)
|
|
186
|
+
if (deflated.length >= source.length) return { binary: false, text }
|
|
187
|
+
return { binary: true, deflated }
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/** One successful response frame. */
|
|
191
|
+
export function responseFrame(id: number, result: unknown): ResFrame {
|
|
192
|
+
return { t: 'res', id, ok: true, r: result }
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/** One failed response frame. */
|
|
196
|
+
export function errorFrame(id: number, code: string, msg: string): ResFrame {
|
|
197
|
+
return { t: 'res', id, ok: false, e: { code, msg } }
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/**
|
|
201
|
+
* Per-connection event sequence. The frozen design gives each connection its
|
|
202
|
+
* own counter starting at 1; it is deliberately NOT the DSH session cursor
|
|
203
|
+
* (§3.4), so the two numbers are never compared.
|
|
204
|
+
*/
|
|
205
|
+
export class EventSequence {
|
|
206
|
+
#next = 1
|
|
207
|
+
|
|
208
|
+
/** @returns the next sequence number, advancing the counter. */
|
|
209
|
+
take(): number {
|
|
210
|
+
const value = this.#next
|
|
211
|
+
this.#next += 1
|
|
212
|
+
return value
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/** @returns the value {@link take} will return next, without advancing. */
|
|
216
|
+
peek(): number {
|
|
217
|
+
return this.#next
|
|
218
|
+
}
|
|
219
|
+
}
|
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The bridge's extension seam: the one place another plugin adds methods and
|
|
3
|
+
* events to protocol v1 without the bridge learning what they mean.
|
|
4
|
+
*
|
|
5
|
+
* The bridge publishes this seam as the cordis service
|
|
6
|
+
* {@link REMOTE_BRIDGE_SERVICE}. A plugin registers a table of methods plus the
|
|
7
|
+
* capability a client must declare before those methods exist for it, and
|
|
8
|
+
* publishes events to the clients that declared the capability it names.
|
|
9
|
+
* Nothing here carries protocol vocabulary of its own: method names, payloads,
|
|
10
|
+
* topics and refusal codes belong to the registering plugin, which is why this
|
|
11
|
+
* module never appears in `KNOWN_METHODS` and never reads a payload.
|
|
12
|
+
*
|
|
13
|
+
* A connection dispatches an extension method only after the protocol's own
|
|
14
|
+
* gates: an unregistered name, a plugin that is not mounted, and a client that
|
|
15
|
+
* never declared the capability all answer `unknown-method` — the method is
|
|
16
|
+
* absent from that client's protocol, not refused by it.
|
|
17
|
+
* @module dsh-remote-bridge/core/extension
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
import type { RemoteBridgeDeltas } from './delta.ts'
|
|
21
|
+
import { KNOWN_METHODS } from './protocol.ts'
|
|
22
|
+
|
|
23
|
+
/** Cordis service this seam is published under. */
|
|
24
|
+
export const REMOTE_BRIDGE_SERVICE = 'remoteBridge'
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Who is calling one extension method.
|
|
28
|
+
*
|
|
29
|
+
* The bridge exposes no device or session identity here on purpose: what an
|
|
30
|
+
* extension keys by connection is its own decision.
|
|
31
|
+
*/
|
|
32
|
+
export interface RemoteBridgeCall {
|
|
33
|
+
/**
|
|
34
|
+
* Stable identity of the calling connection, unique within this bridge
|
|
35
|
+
* process. Two calls from one socket carry the same id; a reconnected socket
|
|
36
|
+
* carries a new one, because nothing proves it is the same peer.
|
|
37
|
+
*/
|
|
38
|
+
readonly connectionId: string
|
|
39
|
+
/**
|
|
40
|
+
* @param capability - one capability name of this protocol or of the calling
|
|
41
|
+
* extension.
|
|
42
|
+
* @returns whether this connection announced it in `hello`.
|
|
43
|
+
*
|
|
44
|
+
* The seam hands handlers the same predicate the bridge itself gates on, so
|
|
45
|
+
* an extension can gate behind a bridge capability (§15's `delta.v1`) without
|
|
46
|
+
* holding a copy of the client's declaration.
|
|
47
|
+
*/
|
|
48
|
+
declares(capability: string): boolean
|
|
49
|
+
/**
|
|
50
|
+
* This connection's delta windows, released with the connection.
|
|
51
|
+
*
|
|
52
|
+
* The mechanism of §15 lives once, in this bridge, and an extension borrows it
|
|
53
|
+
* per connection: the difference is always computed where the last answer is
|
|
54
|
+
* already held, and a dropped connection takes its base with it instead of
|
|
55
|
+
* leaving one to be expired by a second registry.
|
|
56
|
+
*/
|
|
57
|
+
readonly deltas: RemoteBridgeDeltas
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* What one extension method answers: the response body, or a refusal stated in
|
|
62
|
+
* the extension's own code vocabulary. The bridge forwards either verbatim —
|
|
63
|
+
* it holds no table of extension codes and invents none.
|
|
64
|
+
*/
|
|
65
|
+
export type RemoteBridgeMethodResult =
|
|
66
|
+
| { readonly ok: true; readonly r?: unknown }
|
|
67
|
+
| { readonly ok: false; readonly code: string; readonly msg: string }
|
|
68
|
+
|
|
69
|
+
/** One client-callable method an extension owns. */
|
|
70
|
+
export type RemoteBridgeMethodHandler = (
|
|
71
|
+
payload: Readonly<Record<string, unknown>>,
|
|
72
|
+
call: RemoteBridgeCall,
|
|
73
|
+
) => RemoteBridgeMethodResult | Promise<RemoteBridgeMethodResult>
|
|
74
|
+
|
|
75
|
+
/** A table of methods and the capability that admits a client to them. */
|
|
76
|
+
export interface RemoteBridgeMethods {
|
|
77
|
+
/**
|
|
78
|
+
* Capability a client declares in `hello`'s `cap` array before these methods
|
|
79
|
+
* are part of its protocol. Absent means every paired connection may call
|
|
80
|
+
* them; an unpaired connection never may, whatever it declared.
|
|
81
|
+
*/
|
|
82
|
+
readonly capability?: string
|
|
83
|
+
/** Method name to handler; the name is the extension's, not the bridge's. */
|
|
84
|
+
readonly methods: Readonly<Record<string, RemoteBridgeMethodHandler>>
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** The seam, exactly as published on {@link REMOTE_BRIDGE_SERVICE}. */
|
|
88
|
+
export interface RemoteBridgeFace {
|
|
89
|
+
/**
|
|
90
|
+
* Add methods to the protocol surface.
|
|
91
|
+
* @returns the disposer withdrawing them; afterwards they answer `unknown-method` again.
|
|
92
|
+
*/
|
|
93
|
+
registerMethods(table: RemoteBridgeMethods): () => void
|
|
94
|
+
/**
|
|
95
|
+
* Publish one event to the connections that are paired — and, when a
|
|
96
|
+
* capability is named, have declared it.
|
|
97
|
+
* @returns how many connections took the frame.
|
|
98
|
+
*/
|
|
99
|
+
broadcast(topic: string, payload: unknown, capability?: string): number
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** The fan-out the seam publishes through; `BridgeHub` satisfies it. */
|
|
103
|
+
export interface RemoteBridgeFanout {
|
|
104
|
+
broadcast(topic: string, payload: unknown): number
|
|
105
|
+
broadcastTo(capability: string, topic: string, payload: unknown): number
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** One registered method. */
|
|
109
|
+
interface RegisteredMethod {
|
|
110
|
+
readonly capability: string | undefined
|
|
111
|
+
readonly handler: RemoteBridgeMethodHandler
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* The methods extensions registered, and the capability each one needs.
|
|
116
|
+
*
|
|
117
|
+
* Every connection consults this registry; nothing else holds extension state,
|
|
118
|
+
* so unmounting one plugin withdraws exactly its own methods.
|
|
119
|
+
*/
|
|
120
|
+
export class RemoteBridgeRegistry {
|
|
121
|
+
readonly #methods = new Map<string, RegisteredMethod>()
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* Register one table of methods, all or nothing: a table naming a protocol
|
|
125
|
+
* method, an empty name or a name already taken is refused before any of its
|
|
126
|
+
* methods becomes callable.
|
|
127
|
+
* @param table - the methods and the capability they require.
|
|
128
|
+
* @returns the disposer withdrawing this table; idempotent.
|
|
129
|
+
*/
|
|
130
|
+
registerMethods(table: RemoteBridgeMethods): () => void {
|
|
131
|
+
const entries: [string, RegisteredMethod][] = []
|
|
132
|
+
for (const [name, handler] of Object.entries(table.methods)) {
|
|
133
|
+
if (name.trim() === '') throw new Error('a remote bridge method needs a non-empty name')
|
|
134
|
+
if (typeof handler !== 'function') throw new Error(`remote bridge method ${name} has no handler`)
|
|
135
|
+
// A protocol method is decided by the bridge's own dispatch. Shadowing one
|
|
136
|
+
// here would change protocol v1 without changing its version, so it is
|
|
137
|
+
// refused at registration rather than resolved by dispatch order.
|
|
138
|
+
if (KNOWN_METHODS.has(name)) throw new Error(`remote bridge method ${name} is a protocol method`)
|
|
139
|
+
if (this.#methods.has(name)) throw new Error(`remote bridge method ${name} is already registered`)
|
|
140
|
+
entries.push([name, { capability: table.capability, handler }])
|
|
141
|
+
}
|
|
142
|
+
for (const [name, entry] of entries) this.#methods.set(name, entry)
|
|
143
|
+
return () => {
|
|
144
|
+
for (const [name, entry] of entries) {
|
|
145
|
+
// Identity, not just the name: a table registered after this disposer
|
|
146
|
+
// ran keeps its own method.
|
|
147
|
+
if (this.#methods.get(name) === entry) this.#methods.delete(name)
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* @param method - the method name a client asked for.
|
|
154
|
+
* @returns whether any plugin registered it, whatever capability it requires.
|
|
155
|
+
*/
|
|
156
|
+
has(method: string): boolean {
|
|
157
|
+
return this.#methods.has(method)
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* @param method - the method name a client asked for.
|
|
162
|
+
* @param declares - whether the calling connection declared a capability.
|
|
163
|
+
* @returns the handler when the caller may use the method, else undefined.
|
|
164
|
+
*/
|
|
165
|
+
handlerFor(method: string, declares: (capability: string) => boolean): RemoteBridgeMethodHandler | undefined {
|
|
166
|
+
const entry = this.#methods.get(method)
|
|
167
|
+
if (entry === undefined) return undefined
|
|
168
|
+
if (entry.capability !== undefined && !declares(entry.capability)) return undefined
|
|
169
|
+
return entry.handler
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* Compose the published seam over a registry and a fan-out.
|
|
175
|
+
* @param methods - the registry this bridge owns.
|
|
176
|
+
* @param fanout - the hub's broadcast pair.
|
|
177
|
+
* @returns the face a plugin resolves from {@link REMOTE_BRIDGE_SERVICE}.
|
|
178
|
+
*/
|
|
179
|
+
export function createRemoteBridgeFace(methods: RemoteBridgeRegistry, fanout: RemoteBridgeFanout): RemoteBridgeFace {
|
|
180
|
+
return {
|
|
181
|
+
registerMethods: table => methods.registerMethods(table),
|
|
182
|
+
broadcast: (topic, payload, capability) => capability === undefined
|
|
183
|
+
? fanout.broadcast(topic, payload)
|
|
184
|
+
: fanout.broadcastTo(capability, topic, payload),
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
declare module '@deepseek-ai/cordis' {
|
|
189
|
+
interface Context {
|
|
190
|
+
/**
|
|
191
|
+
* The bridge's extension seam, while this package serves protocol v1. A
|
|
192
|
+
* plugin resolves it structurally at use time: requiring it would let the
|
|
193
|
+
* bridge's absence take the registering plugin's start down with it.
|
|
194
|
+
*/
|
|
195
|
+
remoteBridge: RemoteBridgeFace
|
|
196
|
+
}
|
|
197
|
+
}
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Bounded retry for the DSH service-activation window.
|
|
3
|
+
*
|
|
4
|
+
* The gateway raises its activation failures as `error.code`, never as an
|
|
5
|
+
* `instanceof` identity, and two generations of code strings coexist: the
|
|
6
|
+
* namespace-qualified `gateway/service-unavailable` and the bare
|
|
7
|
+
* `service-unavailable`. Both are recognized, verbatim from the family's
|
|
8
|
+
* task-board runner, so a provider that is merely slow to activate is retried
|
|
9
|
+
* rather than reported to the phone as a broken deployment.
|
|
10
|
+
* @module dsh-remote-bridge/core/gateway-errors
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
/** Tries one unary call may consume while the target service is activating. */
|
|
14
|
+
export const SERVICE_UNAVAILABLE_ATTEMPTS = 5
|
|
15
|
+
/** Wait between those tries. */
|
|
16
|
+
export const SERVICE_UNAVAILABLE_BACKOFF_MS = 2_000
|
|
17
|
+
|
|
18
|
+
/** Namespace-qualified and bare spellings of the same failure. */
|
|
19
|
+
function codeIsOneOf(error: unknown, bare: string): boolean {
|
|
20
|
+
const code = (error as { code?: unknown } | null | undefined)?.code
|
|
21
|
+
return code === bare || code === `gateway/${bare}`
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Whether a failure means the target service has not finished activating.
|
|
26
|
+
* This is the one failure worth retrying: the same call succeeds moments later.
|
|
27
|
+
*/
|
|
28
|
+
export function isServiceUnavailable(error: unknown): boolean {
|
|
29
|
+
return codeIsOneOf(error, 'service-unavailable')
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Whether the running gateway does not serve this endpoint at all (the cohort
|
|
34
|
+
* changed under this plugin). Retrying cannot help; the caller reports it.
|
|
35
|
+
*/
|
|
36
|
+
export function isInvocationUnavailable(error: unknown): boolean {
|
|
37
|
+
return codeIsOneOf(error, 'invocation-unavailable')
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Whether the endpoint exists but its strict definition was withdrawn by the running gateway. */
|
|
41
|
+
export function isDefinitionWithdrawn(error: unknown): boolean {
|
|
42
|
+
return codeIsOneOf(error, 'definition-unavailable')
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Whether the call's named arguments did not match the descriptor. */
|
|
46
|
+
export function isArgumentsInvalid(error: unknown): boolean {
|
|
47
|
+
return codeIsOneOf(error, 'arguments-invalid')
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function delay(ms: number): Promise<void> {
|
|
51
|
+
return new Promise(resolve => { setTimeout(resolve, ms) })
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** One-line text of a failure, for a decideable reason the phone can show. */
|
|
55
|
+
export function failureText(error: unknown): string {
|
|
56
|
+
const message = error instanceof Error ? error.message : String(error)
|
|
57
|
+
return message.length > 300 ? `${message.slice(0, 297)}...` : message
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* The failure's own code, for the response envelope. The gateway's codes cross
|
|
62
|
+
* to the phone unchanged (`gateway/arguments-invalid` and friends) so the client
|
|
63
|
+
* can tell "this deployment cannot" from "this build is wrong"; anything
|
|
64
|
+
* without a string code is `internal`.
|
|
65
|
+
*/
|
|
66
|
+
export function errorCodeOf(error: unknown, fallback: string): string {
|
|
67
|
+
const code = (error as { code?: unknown } | null | undefined)?.code
|
|
68
|
+
return typeof code === 'string' && code !== '' ? code : fallback
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Run one unary call, retrying only the service-activation window.
|
|
73
|
+
* @param run - the call to attempt.
|
|
74
|
+
* @param options.attempts - total tries (default {@link SERVICE_UNAVAILABLE_ATTEMPTS}).
|
|
75
|
+
* @param options.backoffMs - wait between tries (default {@link SERVICE_UNAVAILABLE_BACKOFF_MS}).
|
|
76
|
+
* @returns the call's own result or failure; the failure is never swallowed.
|
|
77
|
+
*/
|
|
78
|
+
export async function withServiceUnavailableRetry<T>(
|
|
79
|
+
run: () => Promise<T>,
|
|
80
|
+
options: { attempts?: number; backoffMs?: number } = {},
|
|
81
|
+
): Promise<T> {
|
|
82
|
+
const attempts = options.attempts ?? SERVICE_UNAVAILABLE_ATTEMPTS
|
|
83
|
+
const backoffMs = options.backoffMs ?? SERVICE_UNAVAILABLE_BACKOFF_MS
|
|
84
|
+
for (let attempt = 1; ; attempt += 1) {
|
|
85
|
+
try {
|
|
86
|
+
return await run()
|
|
87
|
+
} catch (error) {
|
|
88
|
+
if (!isServiceUnavailable(error) || attempt >= attempts) throw error
|
|
89
|
+
await delay(backoffMs)
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
}
|