|
67 | 67 | * If false, remote errors will be replaced with a generic message. |
68 | 68 | * @param {boolean} [options.injectToThis=true] - If true, 'this' inside a function will be replaced with the iorpc object. |
69 | 69 | * Useful for context-aware APIs. |
| 70 | + * @param {boolean} [options.ignoreCallbackUnavailable=false] - If true, missing-callback errors are ignored. |
| 71 | + * @param {number} [options.callTimeout=0] - Milliseconds before a pending remote call is rejected with |
| 72 | + * an Error whose `code === 'IORPC_TIMEOUT'`. `0` disables timers (default). |
| 73 | + * @param {function} [options.cbIdGenerator] - Custom callback-id generator `() => number|string`. |
| 74 | + * Defaults to a random integer. Collision check against the local map remains. |
| 75 | + * @param {boolean} [options.taggedPackets=false] - If true, packets carry an explicit `kind: 'call'|'cb'` and routing |
| 76 | + * uses it instead of the isNaN heuristic. Both sides must match. Default keeps |
| 77 | + * the wire-format identical to 9.2.2. |
| 78 | + * @param {function} [options.onTrim] - Called as `(removedIds: Array)` whenever clbsTrim evicts entries. |
70 | 79 | * |
71 | | - * @returns {{ remoteApi: object, routeInput: function, pending: function }} - Returns an object with: |
| 80 | + * @returns {{ remoteApi: object, routeInput: function, pending: function, rejectAll: function, bindings: function }} |
72 | 81 | * - `remoteApi`: proxy API to call remote functions, |
73 | 82 | * - `routeInput`: function to pass incoming messages from the other side, |
74 | | - * - `pending`: returns the size of the waiting list to check if it is overflowing. |
| 83 | + * - `pending`: returns the size of the waiting list to check if it is overflowing, |
| 84 | + * - `rejectAll(err?)`: rejects all pending response promises and clears bindings (use on transport close), |
| 85 | + * - `bindings()`: returns `{ calls, callbacks }` diagnostic breakdown of `pending`. |
75 | 86 | */ |
76 | 87 | const createIorpc = (sendFn, localApi = {}, { |
77 | 88 | maxPendingResponses = 10000, |
78 | 89 | allowNestedFunctions = false, |
79 | 90 | exposeErrors = true, |
80 | 91 | injectToThis = true, |
81 | | - ignoreCallbackUnavailable = false |
| 92 | + ignoreCallbackUnavailable = false, |
| 93 | + callTimeout = 0, |
| 94 | + cbIdGenerator = null, |
| 95 | + taggedPackets = false, |
| 96 | + onTrim = null |
82 | 97 | }) => { |
83 | 98 | const clbs = {}; |
84 | 99 | let trimWarningFired = false; |
85 | 100 | let noWait = false; |
| 101 | + // taggedPackets: set right before invoking a remote callback wrapper, so the |
| 102 | + // outgoing packet is tagged kind:'cb'. Reset after each remoteApi access. |
| 103 | + let cbInvoke = false; |
86 | 104 | let pending = 0; |
87 | 105 | const clbsTrim = () => { |
88 | 106 | if (!trimWarningFired) { |
|
91 | 109 | } |
92 | 110 | const clbsArr = Object.values(clbs); |
93 | 111 | clbsArr.sort((a, b) => a.lastAck - b.lastAck); |
94 | | - clbsArr.slice(0, pending - maxPendingResponses).map(v => v.cbId).forEach(cbId => { |
| 112 | + const removed = clbsArr.slice(0, pending - maxPendingResponses).map(v => v.cbId); |
| 113 | + removed.forEach(cbId => { |
95 | 114 | pending--; |
96 | 115 | delete clbs[cbId]; |
97 | 116 | }); |
| 117 | + if (onTrim && removed.length) { |
| 118 | + try { |
| 119 | + onTrim(removed); |
| 120 | + } catch (e) {/* user callback must not break trimming */} |
| 121 | + } |
98 | 122 | }; |
99 | 123 | const genCbid = () => { |
100 | 124 | while (true) { |
101 | | - const cbId = Math.round(Math.random() * Number.MAX_SAFE_INTEGER); |
| 125 | + const cbId = cbIdGenerator ? cbIdGenerator() : Math.round(Math.random() * Number.MAX_SAFE_INTEGER); |
102 | 126 | if (cbId in clbs) continue; |
103 | 127 | return cbId; |
104 | 128 | } |
|
113 | 137 | noWait = true; |
114 | 138 | return remoteApi; |
115 | 139 | } else { |
| 140 | + // Capture and reset the callback-invoke flag at access time: the cb |
| 141 | + // wrapper sets it immediately before reading remoteApi[cbId]. |
| 142 | + const isCbInvoke = cbInvoke; |
| 143 | + cbInvoke = false; |
116 | 144 | return function (...args) { |
117 | 145 | const packet = { |
118 | 146 | apiFunc: thisArg, |
119 | 147 | cbId: false, |
120 | 148 | args, |
121 | 149 | argsTransform: allowNestedFunctions ? {} : [] |
122 | 150 | }; |
| 151 | + // taggedPackets: mark whether apiFunc is a named method call or a callback id. |
| 152 | + // Added only when the option is enabled so the default wire-format stays |
| 153 | + // byte-identical to 9.2.2. |
| 154 | + if (taggedPackets) { |
| 155 | + packet.kind = isCbInvoke ? 'cb' : 'call'; |
| 156 | + } |
123 | 157 | if (!noWait) packet.cbId = genCbid(); |
124 | 158 | if (allowNestedFunctions) { |
125 | 159 | recuFilter(args, packet.argsTransform, resolve => { |
|
159 | 193 | const delayPromise = new Promise((resolve, reject) => { |
160 | 194 | if (pending > maxPendingResponses) clbsTrim(); |
161 | 195 | pending++; |
| 196 | + let timer = null; |
| 197 | + if (callTimeout > 0) { |
| 198 | + timer = setTimeout(() => { |
| 199 | + if (!(packet.cbId in clbs)) return; |
| 200 | + delete clbs[packet.cbId]; |
| 201 | + pending--; |
| 202 | + // free the mirror record on the other side, if any |
| 203 | + noWait = true; |
| 204 | + remoteApi.iorpcUnbind(packet.cbId); |
| 205 | + const err = new Error('iorpc: call timeout'); |
| 206 | + err.code = 'IORPC_TIMEOUT'; |
| 207 | + reject(err); |
| 208 | + }, callTimeout); |
| 209 | + if (timer && typeof timer.unref === 'function') timer.unref(); |
| 210 | + } |
162 | 211 | clbs[packet.cbId] = { |
163 | 212 | resolve: arg => { |
| 213 | + if (timer) clearTimeout(timer); |
164 | 214 | delete clbs[packet.cbId]; |
165 | 215 | pending--; |
166 | 216 | return resolve(arg); |
167 | 217 | }, |
168 | 218 | reject, |
| 219 | + timer, |
169 | 220 | cbId: packet.cbId, |
170 | 221 | lastAck: Date.now() |
171 | 222 | }; |
172 | 223 | }); |
173 | 224 | return delayPromise.catch(e => { |
| 225 | + if (e && e.code === 'IORPC_TIMEOUT') throw e; |
174 | 226 | let err = e; |
175 | 227 | if (e instanceof Error) { |
176 | 228 | err = new RemoteError(e.stack, e.message); |
|
190 | 242 | const routeInput = message => { |
191 | 243 | if (message.apiFunc === 'iorpcThrowError') { |
192 | 244 | const [cbId, e, stack] = message.args; |
| 245 | + const rec = clbs[cbId]; |
| 246 | + if (rec && rec.timer) clearTimeout(rec.timer); |
193 | 247 | if (stack) { |
194 | 248 | const err = new Error(e); |
195 | 249 | err.stack = stack; |
|
202 | 256 | return; |
203 | 257 | } |
204 | 258 | if (message.apiFunc === 'iorpcUnbind') { |
| 259 | + const rec = clbs[message.args[0]]; |
| 260 | + if (rec && rec.timer) clearTimeout(rec.timer); |
205 | 261 | pending--; |
206 | 262 | delete clbs[message.args[0]]; |
207 | 263 | return; |
208 | 264 | } |
209 | 265 | let fn; |
210 | | - if (message.apiFunc in localApi) { |
| 266 | + // With taggedPackets both sides agree on routing via `kind`. |
| 267 | + // A 'cb' packet must never resolve a localApi method, and vice-versa. |
| 268 | + if (taggedPackets && (message.kind === 'call' || message.kind === 'cb')) { |
| 269 | + if (message.kind === 'call') { |
| 270 | + if (message.apiFunc in localApi) fn = localApi[message.apiFunc]; |
| 271 | + } else { |
| 272 | + if (message.apiFunc in clbs) { |
| 273 | + clbs[message.apiFunc].lastAck = Date.now(); |
| 274 | + fn = clbs[message.apiFunc].resolve; |
| 275 | + } |
| 276 | + } |
| 277 | + } else if (message.apiFunc in localApi) { |
211 | 278 | fn = localApi[message.apiFunc]; |
212 | 279 | } else { |
213 | 280 | if (message.apiFunc in clbs) { |
|
220 | 287 | recuPatch(message.argsTransform, message.args, (at, a, k) => { |
221 | 288 | const cbId = a[k]; |
222 | 289 | a[k] = function (...args) { |
| 290 | + cbInvoke = true; |
223 | 291 | return remoteApi[cbId](...args); |
224 | 292 | }; |
225 | 293 | a[k].unbind = () => { |
|
231 | 299 | for (let i of message.argsTransform) { |
232 | 300 | const cbId = message.args[i]; |
233 | 301 | message.args[i] = function (...args) { |
| 302 | + cbInvoke = true; |
234 | 303 | return remoteApi[cbId](...args); |
235 | 304 | }; |
236 | 305 | message.args[i].unbind = () => { |
|
266 | 335 | if (suc) { |
267 | 336 | if (message.cbId === false) return; |
268 | 337 | if (retCb instanceof Function || typeof retCb === "function") { |
| 338 | + cbInvoke = true; |
269 | 339 | remoteApi[message.cbId](retCb); // function as return |
270 | 340 | } else { |
271 | 341 | Promise.resolve(retCb).then(ret => { |
272 | 342 | noWait = true; |
| 343 | + cbInvoke = true; |
273 | 344 | remoteApi[message.cbId](ret); |
274 | 345 | }).catch(e => { |
275 | 346 | noWait = true; |
|
284 | 355 | } else { |
285 | 356 | noWait = true; |
286 | 357 | let errMsg; |
287 | | - if (isNaN(message.apiFunc)) { |
| 358 | + // Prefer the explicit kind tag when available; fall back to the isNaN heuristic. |
| 359 | + const isCallback = taggedPackets && (message.kind === 'cb' || message.kind === 'call') ? message.kind === 'cb' : !isNaN(message.apiFunc); |
| 360 | + if (!isCallback) { |
288 | 361 | errMsg = `Function '${message.apiFunc}' is not registered for the iorpc API. Please verify it is properly defined and exposed.`; |
289 | 362 | } else { |
290 | 363 | if (ignoreCallbackUnavailable) return; |
|
294 | 367 | remoteApi.iorpcThrowError(message.cbId, e.message, e.stack); |
295 | 368 | } |
296 | 369 | }; |
| 370 | + /** |
| 371 | + * Reject every pending response promise and clear all bindings. |
| 372 | + * Used when the transport dies (e.g. ws 'close'). Sends nothing to the wire. |
| 373 | + */ |
| 374 | + const rejectAll = (err = new Error('iorpc: transport closed')) => { |
| 375 | + for (const cbId of Object.keys(clbs)) { |
| 376 | + const rec = clbs[cbId]; |
| 377 | + if (rec && rec.timer) clearTimeout(rec.timer); |
| 378 | + if (rec && typeof rec.reject === 'function') { |
| 379 | + try { |
| 380 | + rec.reject(err); |
| 381 | + } catch (e) {/* ignore */} |
| 382 | + } |
| 383 | + delete clbs[cbId]; |
| 384 | + } |
| 385 | + pending = 0; |
| 386 | + }; |
| 387 | + /** |
| 388 | + * Diagnostic breakdown of `pending`: |
| 389 | + * - calls: response waiters (have a reject handler) |
| 390 | + * - callbacks: stored inbound callbacks (resolve-only records) |
| 391 | + */ |
| 392 | + const bindings = () => { |
| 393 | + let calls = 0; |
| 394 | + let callbacks = 0; |
| 395 | + for (const cbId of Object.keys(clbs)) { |
| 396 | + if (typeof clbs[cbId].reject === 'function') calls++;else callbacks++; |
| 397 | + } |
| 398 | + return { |
| 399 | + calls, |
| 400 | + callbacks |
| 401 | + }; |
| 402 | + }; |
297 | 403 | return { |
298 | 404 | remoteApi /* Object with remote functions */, |
299 | 405 | routeInput /* Function to handle incoming messages */, |
300 | | - pending: () => pending |
| 406 | + pending: () => pending, |
| 407 | + rejectAll, |
| 408 | + bindings |
301 | 409 | }; |
302 | 410 | }; |
303 | 411 | class RemoteError extends Error { |
|
349 | 457 | const { |
350 | 458 | routeInput, |
351 | 459 | remoteApi, |
352 | | - pending |
| 460 | + pending, |
| 461 | + rejectAll, |
| 462 | + bindings |
353 | 463 | } = createIorpc(send, local, options); |
354 | 464 | on(routeInput); |
355 | 465 | return { |
356 | 466 | local, |
357 | 467 | remote: remoteApi, |
358 | | - pending |
| 468 | + pending, |
| 469 | + rejectAll, |
| 470 | + bindings |
359 | 471 | }; |
360 | 472 | } |
361 | 473 | }; |
|
0 commit comments