@dxos/rpc 0.6.9 → 0.6.10-main.48c066e

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.
@@ -13,7 +13,8 @@ import { Stream } from "@dxos/codec-protobuf";
13
13
  import { StackTrace as StackTrace2 } from "@dxos/debug";
14
14
  import { invariant } from "@dxos/invariant";
15
15
  import { log } from "@dxos/log";
16
- import { encodeError, RpcClosedError, RpcNotOpenError, schema } from "@dxos/protocols";
16
+ import { encodeError, RpcClosedError, RpcNotOpenError } from "@dxos/protocols";
17
+ import { schema } from "@dxos/protocols/proto";
17
18
  import { exponentialBackoffInterval } from "@dxos/util";
18
19
 
19
20
  // packages/core/mesh/rpc/src/errors.ts
@@ -97,7 +98,7 @@ var RpcPeer = class {
97
98
  } catch (err) {
98
99
  log.catch(err, void 0, {
99
100
  F: __dxlog_file,
100
- L: 155,
101
+ L: 156,
101
102
  S: this,
102
103
  C: (f, a) => f(...a)
103
104
  });
@@ -113,7 +114,7 @@ var RpcPeer = class {
113
114
  state: this._state
114
115
  }, {
115
116
  F: __dxlog_file,
116
- L: 167,
117
+ L: 168,
117
118
  S: this,
118
119
  C: (f, a) => f(...a)
119
120
  });
@@ -128,7 +129,7 @@ var RpcPeer = class {
128
129
  open: true
129
130
  }).catch((err) => log.warn(err, void 0, {
130
131
  F: __dxlog_file,
131
- L: 176,
132
+ L: 177,
132
133
  S: this,
133
134
  C: (f, a) => f(...a)
134
135
  }));
@@ -145,7 +146,7 @@ var RpcPeer = class {
145
146
  state: this._state
146
147
  }, {
147
148
  F: __dxlog_file,
148
- L: 190,
149
+ L: 191,
149
150
  S: this,
150
151
  C: (f, a) => f(...a)
151
152
  });
@@ -175,7 +176,7 @@ var RpcPeer = class {
175
176
  err
176
177
  }, {
177
178
  F: __dxlog_file,
178
- L: 212,
179
+ L: 213,
179
180
  S: this,
180
181
  C: (f, a) => f(...a)
181
182
  });
@@ -183,7 +184,7 @@ var RpcPeer = class {
183
184
  try {
184
185
  log("closing waiting on bye", void 0, {
185
186
  F: __dxlog_file,
186
- L: 215,
187
+ L: 216,
187
188
  S: this,
188
189
  C: (f, a) => f(...a)
189
190
  });
@@ -195,7 +196,7 @@ var RpcPeer = class {
195
196
  err
196
197
  }, {
197
198
  F: __dxlog_file,
198
- L: 218,
199
+ L: 219,
199
200
  S: this,
200
201
  C: (f, a) => f(...a)
201
202
  });
@@ -239,7 +240,7 @@ var RpcPeer = class {
239
240
  type: Object.keys(decoded)[0]
240
241
  }, {
241
242
  F: __dxlog_file,
242
- L: 262,
243
+ L: 263,
243
244
  S: this,
244
245
  C: (f, a) => f(...a)
245
246
  });
@@ -247,7 +248,7 @@ var RpcPeer = class {
247
248
  if (this._state !== "OPENED" && this._state !== "OPENING") {
248
249
  log("received request while closed", void 0, {
249
250
  F: __dxlog_file,
250
- L: 266,
251
+ L: 267,
251
252
  S: this,
252
253
  C: (f, a) => f(...a)
253
254
  });
@@ -265,7 +266,7 @@ var RpcPeer = class {
265
266
  method: req.method
266
267
  }, {
267
268
  F: __dxlog_file,
268
- L: 278,
269
+ L: 279,
269
270
  S: this,
270
271
  C: (f, a) => f(...a)
271
272
  });
@@ -277,7 +278,7 @@ var RpcPeer = class {
277
278
  close: response.close
278
279
  }, {
279
280
  F: __dxlog_file,
280
- L: 280,
281
+ L: 281,
281
282
  S: this,
282
283
  C: (f, a) => f(...a)
283
284
  });
@@ -286,7 +287,7 @@ var RpcPeer = class {
286
287
  }).catch((err) => {
287
288
  log.warn("failed during close", err, {
288
289
  F: __dxlog_file,
289
- L: 288,
290
+ L: 289,
290
291
  S: this,
291
292
  C: (f, a) => f(...a)
292
293
  });
@@ -297,7 +298,7 @@ var RpcPeer = class {
297
298
  method: req.method
298
299
  }, {
299
300
  F: __dxlog_file,
300
- L: 292,
301
+ L: 293,
301
302
  S: this,
302
303
  C: (f, a) => f(...a)
303
304
  });
@@ -308,7 +309,7 @@ var RpcPeer = class {
308
309
  error: response.error
309
310
  }, {
310
311
  F: __dxlog_file,
311
- L: 295,
312
+ L: 296,
312
313
  S: this,
313
314
  C: (f, a) => f(...a)
314
315
  });
@@ -320,7 +321,7 @@ var RpcPeer = class {
320
321
  if (this._state !== "OPENED") {
321
322
  log("received response while closed", void 0, {
322
323
  F: __dxlog_file,
323
- L: 304,
324
+ L: 305,
324
325
  S: this,
325
326
  C: (f, a) => f(...a)
326
327
  });
@@ -329,7 +330,7 @@ var RpcPeer = class {
329
330
  const responseId = decoded.response.id;
330
331
  invariant(typeof responseId === "number", void 0, {
331
332
  F: __dxlog_file,
332
- L: 309,
333
+ L: 310,
333
334
  S: this,
334
335
  A: [
335
336
  "typeof responseId === 'number'",
@@ -341,7 +342,7 @@ var RpcPeer = class {
341
342
  responseId
342
343
  }, {
343
344
  F: __dxlog_file,
344
- L: 311,
345
+ L: 312,
345
346
  S: this,
346
347
  C: (f, a) => f(...a)
347
348
  });
@@ -355,7 +356,7 @@ var RpcPeer = class {
355
356
  type_url: decoded.response.payload?.type_url
356
357
  }, {
357
358
  F: __dxlog_file,
358
- L: 321,
359
+ L: 322,
359
360
  S: this,
360
361
  C: (f, a) => f(...a)
361
362
  });
@@ -365,7 +366,7 @@ var RpcPeer = class {
365
366
  state: this._state
366
367
  }, {
367
368
  F: __dxlog_file,
368
- L: 324,
369
+ L: 325,
369
370
  S: this,
370
371
  C: (f, a) => f(...a)
371
372
  });
@@ -380,7 +381,7 @@ var RpcPeer = class {
380
381
  state: this._state
381
382
  }, {
382
383
  F: __dxlog_file,
383
- L: 331,
384
+ L: 332,
384
385
  S: this,
385
386
  C: (f, a) => f(...a)
386
387
  });
@@ -393,7 +394,7 @@ var RpcPeer = class {
393
394
  if (this._state !== "OPENED") {
394
395
  log("received stream close while closed", void 0, {
395
396
  F: __dxlog_file,
396
- L: 340,
397
+ L: 341,
397
398
  S: this,
398
399
  C: (f, a) => f(...a)
399
400
  });
@@ -403,13 +404,13 @@ var RpcPeer = class {
403
404
  id: decoded.streamClose.id
404
405
  }, {
405
406
  F: __dxlog_file,
406
- L: 344,
407
+ L: 345,
407
408
  S: this,
408
409
  C: (f, a) => f(...a)
409
410
  });
410
411
  invariant(typeof decoded.streamClose.id === "number", void 0, {
411
412
  F: __dxlog_file,
412
- L: 345,
413
+ L: 346,
413
414
  S: this,
414
415
  A: [
415
416
  "typeof decoded.streamClose.id === 'number'",
@@ -422,7 +423,7 @@ var RpcPeer = class {
422
423
  id: decoded.streamClose.id
423
424
  }, {
424
425
  F: __dxlog_file,
425
- L: 348,
426
+ L: 349,
426
427
  S: this,
427
428
  C: (f, a) => f(...a)
428
429
  });
@@ -435,7 +436,7 @@ var RpcPeer = class {
435
436
  if (this._state !== "CLOSING" && this._state !== "CLOSED") {
436
437
  log("replying to bye", void 0, {
437
438
  F: __dxlog_file,
438
- L: 358,
439
+ L: 359,
439
440
  S: this,
440
441
  C: (f, a) => f(...a)
441
442
  });
@@ -451,7 +452,7 @@ var RpcPeer = class {
451
452
  msg
452
453
  }, {
453
454
  F: __dxlog_file,
454
- L: 366,
455
+ L: 367,
455
456
  S: this,
456
457
  C: (f, a) => f(...a)
457
458
  });
@@ -467,7 +468,7 @@ var RpcPeer = class {
467
468
  method
468
469
  }, {
469
470
  F: __dxlog_file,
470
- L: 376,
471
+ L: 377,
471
472
  S: this,
472
473
  C: (f, a) => f(...a)
473
474
  });
@@ -495,7 +496,7 @@ var RpcPeer = class {
495
496
  response = await waiting;
496
497
  invariant(response.id === id, void 0, {
497
498
  F: __dxlog_file,
498
- L: 404,
499
+ L: 405,
499
500
  S: this,
500
501
  A: [
501
502
  "response.id === id",
@@ -574,7 +575,7 @@ ${stack.getStack()}`;
574
575
  }).catch((err) => {
575
576
  log.catch(err, void 0, {
576
577
  F: __dxlog_file,
577
- L: 477,
578
+ L: 478,
578
579
  S: this,
579
580
  C: (f, a) => f(...a)
580
581
  });
@@ -588,7 +589,7 @@ ${stack.getStack()}`;
588
589
  type: Object.keys(message)[0]
589
590
  }, {
590
591
  F: __dxlog_file,
591
- L: 485,
592
+ L: 486,
592
593
  S: this,
593
594
  C: (f, a) => f(...a)
594
595
  });
@@ -600,7 +601,7 @@ ${stack.getStack()}`;
600
601
  try {
601
602
  invariant(typeof req.id === "number", void 0, {
602
603
  F: __dxlog_file,
603
- L: 491,
604
+ L: 492,
604
605
  S: this,
605
606
  A: [
606
607
  "typeof req.id === 'number'",
@@ -609,7 +610,7 @@ ${stack.getStack()}`;
609
610
  });
610
611
  invariant(req.payload, void 0, {
611
612
  F: __dxlog_file,
612
- L: 492,
613
+ L: 493,
613
614
  S: this,
614
615
  A: [
615
616
  "req.payload",
@@ -618,7 +619,7 @@ ${stack.getStack()}`;
618
619
  });
619
620
  invariant(req.method, void 0, {
620
621
  F: __dxlog_file,
621
- L: 493,
622
+ L: 494,
622
623
  S: this,
623
624
  A: [
624
625
  "req.method",
@@ -641,7 +642,7 @@ ${stack.getStack()}`;
641
642
  try {
642
643
  invariant(this._params.streamHandler, "Requests with streaming responses are not supported.", {
643
644
  F: __dxlog_file,
644
- L: 510,
645
+ L: 511,
645
646
  S: this,
646
647
  A: [
647
648
  "this._params.streamHandler",
@@ -650,7 +651,7 @@ ${stack.getStack()}`;
650
651
  });
651
652
  invariant(typeof req.id === "number", void 0, {
652
653
  F: __dxlog_file,
653
- L: 511,
654
+ L: 512,
654
655
  S: this,
655
656
  A: [
656
657
  "typeof req.id === 'number'",
@@ -659,7 +660,7 @@ ${stack.getStack()}`;
659
660
  });
660
661
  invariant(req.payload, void 0, {
661
662
  F: __dxlog_file,
662
- L: 512,
663
+ L: 513,
663
664
  S: this,
664
665
  A: [
665
666
  "req.payload",
@@ -668,7 +669,7 @@ ${stack.getStack()}`;
668
669
  });
669
670
  invariant(req.method, void 0, {
670
671
  F: __dxlog_file,
671
- L: 513,
672
+ L: 514,
672
673
  S: this,
673
674
  A: [
674
675
  "req.method",
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/rpc.ts", "../../../src/errors.ts", "../../../src/service.ts", "../../../src/testing.ts", "../../../src/trace.ts"],
4
- "sourcesContent": ["//\n// Copyright 2021 DXOS.org\n//\n\nimport { asyncTimeout, synchronized, Trigger } from '@dxos/async';\nimport { type Any, Stream, type RequestOptions, type ProtoCodec } from '@dxos/codec-protobuf';\nimport { StackTrace } from '@dxos/debug';\nimport { invariant } from '@dxos/invariant';\nimport { log } from '@dxos/log';\nimport { encodeError, RpcClosedError, RpcNotOpenError, schema } from '@dxos/protocols';\nimport { type Request, type Response, type RpcMessage } from '@dxos/protocols/proto/dxos/rpc';\nimport { exponentialBackoffInterval } from '@dxos/util';\n\nimport { decodeRpcError } from './errors';\n\nconst DEFAULT_TIMEOUT = 3_000;\nconst BYE_SEND_TIMEOUT = 2_000;\n\nconst DEBUG_CALLS = true;\n\ntype MaybePromise<T> = Promise<T> | T;\n\nexport interface RpcPeerOptions {\n port: RpcPort;\n\n /**\n * Time to wait for a response to an RPC call.\n */\n timeout?: number;\n\n callHandler: (method: string, request: Any, options?: RequestOptions) => MaybePromise<Any>;\n streamHandler?: (method: string, request: Any, options?: RequestOptions) => Stream<Any>;\n\n /**\n * Do not require or send handshake messages.\n */\n noHandshake?: boolean;\n\n /**\n * What options get passed to the `callHandler` and `streamHandler`.\n */\n handlerRpcOptions?: RequestOptions;\n}\n\n/**\n * Interface for a transport-agnostic port to send/receive binary messages.\n */\nexport interface RpcPort {\n send: (msg: Uint8Array, timeout?: number) => MaybePromise<void>;\n subscribe: (cb: (msg: Uint8Array) => void) => (() => void) | void;\n}\n\nconst CLOSE_TIMEOUT = 3_000;\n\nexport type CloseOptions = {\n /**\n * Time to wait for the other side to confirm close.\n */\n timeout?: number;\n};\n\nclass PendingRpcRequest {\n constructor(\n public readonly resolve: (response: Response) => void,\n public readonly reject: (error?: Error) => void,\n public readonly stream: boolean,\n ) {}\n}\n\n// NOTE: Lazy so that code that doesn't use indexing doesn't need to load the codec (breaks in workerd).\nlet RpcMessageCodec!: ProtoCodec<RpcMessage>;\nconst getRpcMessageCodec = () => (RpcMessageCodec ??= schema.getCodecForType('dxos.rpc.RpcMessage'));\n\nenum RpcState {\n INITIAL = 'INITIAL',\n\n OPENING = 'OPENING',\n\n OPENED = 'OPENED',\n\n /**\n * Bye message sent, waiting for the other side to close.\n * Not possible to send requests.\n * All pending requests will be rejected.\n */\n CLOSING = 'CLOSING',\n\n /**\n * Connection fully closed.\n * The underlying transport can be disposed.\n */\n CLOSED = 'CLOSED',\n}\n\n/**\n * A remote procedure call peer.\n *\n * Provides a away to make RPC calls and get a response back as a promise.\n * Does not handle encoding/decoding and only works with byte buffers.\n * For type safe approach see `createRpcClient` and `createRpcServer`.\n *\n * Must be connected with another instance on the other side via `send`/`receive` methods.\n * Both sides must be opened before making any RPC calls.\n *\n * Errors inside the handler get serialized and sent to the other side.\n *\n * Inspired by JSON-RPC 2.0 https://www.jsonrpc.org/specification.\n */\nexport class RpcPeer {\n private readonly _params: RpcPeerOptions;\n\n private readonly _outgoingRequests = new Map<number, PendingRpcRequest>();\n private readonly _localStreams = new Map<number, Stream<any>>();\n private readonly _remoteOpenTrigger = new Trigger();\n\n /**\n * Triggered when the peer starts closing.\n */\n private readonly _closingTrigger = new Trigger();\n\n /**\n * Triggered when peer receives a bye message.\n */\n private readonly _byeTrigger = new Trigger();\n\n private _nextId = 0;\n private _state: RpcState = RpcState.INITIAL;\n private _unsubscribeFromPort: (() => void) | undefined = undefined;\n private _clearOpenInterval: (() => void) | undefined = undefined;\n\n constructor(params: RpcPeerOptions) {\n this._params = {\n timeout: undefined,\n streamHandler: undefined,\n noHandshake: false,\n ...params,\n };\n }\n\n /**\n * Open the peer. Required before making any calls.\n *\n * Will block before the other peer calls `open`.\n */\n @synchronized\n async open() {\n if (this._state !== RpcState.INITIAL) {\n return;\n }\n\n this._unsubscribeFromPort = this._params.port.subscribe(async (msg) => {\n try {\n await this._receive(msg);\n } catch (err: any) {\n log.catch(err);\n }\n }) as any;\n\n this._state = RpcState.OPENING;\n\n if (this._params.noHandshake) {\n this._state = RpcState.OPENED;\n this._remoteOpenTrigger.wake();\n return;\n }\n\n log('sending open message', { state: this._state });\n await this._sendMessage({ open: true });\n\n if (this._state !== RpcState.OPENING) {\n return;\n }\n\n // Retry sending.\n this._clearOpenInterval = exponentialBackoffInterval(() => {\n void this._sendMessage({ open: true }).catch((err) => log.warn(err));\n }, 50);\n\n await Promise.race([this._remoteOpenTrigger.wait(), this._closingTrigger.wait()]);\n\n this._clearOpenInterval?.();\n\n if ((this._state as RpcState) !== RpcState.OPENED) {\n // Closed while opening.\n return; // TODO(dmaretskyi): Throw error?\n }\n\n // TODO(burdon): This seems error prone.\n // Send an \"open\" message in case the other peer has missed our first \"open\" message and is still waiting.\n log('sending second open message', { state: this._state });\n await this._sendMessage({ openAck: true });\n }\n\n /**\n * Close the peer.\n * Stop taking or making requests.\n * Will wait for confirmation from the other side.\n * Any responses for RPC calls made before close will be delivered.\n */\n async close({ timeout = CLOSE_TIMEOUT }: CloseOptions = {}) {\n if (this._state === RpcState.CLOSED) {\n return;\n }\n\n this._abortRequests();\n\n if (this._state === RpcState.OPENED && !this._params.noHandshake) {\n try {\n this._state = RpcState.CLOSING;\n await this._sendMessage({ bye: {} }, BYE_SEND_TIMEOUT);\n } catch (err: any) {\n log('error closing peer, sending bye', { err });\n }\n try {\n log('closing waiting on bye');\n await this._byeTrigger.wait({ timeout });\n } catch (err: any) {\n log('error closing peer', { err });\n return;\n }\n }\n\n this._disposeAndClose();\n }\n\n /**\n * Dispose the connection without waiting for the other side.\n */\n async abort() {\n if (this._state === RpcState.CLOSED) {\n return;\n }\n\n this._abortRequests();\n this._disposeAndClose();\n }\n\n private _abortRequests() {\n // Abort open\n this._clearOpenInterval?.();\n this._closingTrigger.wake();\n\n // Abort pending requests\n for (const req of this._outgoingRequests.values()) {\n req.reject(new RpcClosedError());\n }\n this._outgoingRequests.clear();\n }\n\n private _disposeAndClose() {\n this._unsubscribeFromPort?.();\n this._unsubscribeFromPort = undefined;\n this._clearOpenInterval?.();\n this._state = RpcState.CLOSED;\n }\n\n /**\n * Handle incoming message. Should be called as the result of other peer's `send` callback.\n */\n private async _receive(msg: Uint8Array): Promise<void> {\n const decoded = getRpcMessageCodec().decode(msg, { preserveAny: true });\n DEBUG_CALLS && log('received message', { type: Object.keys(decoded)[0] });\n\n if (decoded.request) {\n if (this._state !== RpcState.OPENED && this._state !== RpcState.OPENING) {\n log('received request while closed');\n await this._sendMessage({\n response: {\n id: decoded.request.id,\n error: encodeError(new RpcClosedError()),\n },\n });\n return;\n }\n\n const req = decoded.request;\n if (req.stream) {\n log('stream request', { method: req.method });\n this._callStreamHandler(req, (response) => {\n log('sending stream response', {\n method: req.method,\n response: response.payload?.type_url,\n error: response.error,\n close: response.close,\n });\n\n void this._sendMessage({ response }).catch((err) => {\n log.warn('failed during close', err);\n });\n });\n } else {\n DEBUG_CALLS && log('request', { method: req.method });\n const response = await this._callHandler(req);\n DEBUG_CALLS &&\n log('sending response', {\n method: req.method,\n response: response.payload?.type_url,\n error: response.error,\n });\n await this._sendMessage({ response });\n }\n } else if (decoded.response) {\n if (this._state !== RpcState.OPENED) {\n log('received response while closed');\n return; // Ignore when not open.\n }\n\n const responseId = decoded.response.id;\n invariant(typeof responseId === 'number');\n if (!this._outgoingRequests.has(responseId)) {\n log('received response with invalid id', { responseId });\n return; // Ignore requests with incorrect id.\n }\n\n const item = this._outgoingRequests.get(responseId)!;\n // Delete the request record if no more responses are expected.\n if (!item.stream) {\n this._outgoingRequests.delete(responseId);\n }\n\n DEBUG_CALLS && log('response', { type_url: decoded.response.payload?.type_url });\n item.resolve(decoded.response);\n } else if (decoded.open) {\n log('received open message', { state: this._state });\n if (this._params.noHandshake) {\n return;\n }\n\n await this._sendMessage({ openAck: true });\n } else if (decoded.openAck) {\n log('received openAck message', { state: this._state });\n if (this._params.noHandshake) {\n return;\n }\n\n this._state = RpcState.OPENED;\n this._remoteOpenTrigger.wake();\n } else if (decoded.streamClose) {\n if (this._state !== RpcState.OPENED) {\n log('received stream close while closed');\n return; // Ignore when not open.\n }\n\n log('received stream close', { id: decoded.streamClose.id });\n invariant(typeof decoded.streamClose.id === 'number');\n const stream = this._localStreams.get(decoded.streamClose.id);\n if (!stream) {\n log('no local stream', { id: decoded.streamClose.id });\n return; // Ignore requests with incorrect id.\n }\n\n this._localStreams.delete(decoded.streamClose.id);\n await stream.close();\n } else if (decoded.bye) {\n this._byeTrigger.wake();\n // If we haven't already started closing, close now.\n if (this._state !== RpcState.CLOSING && this._state !== RpcState.CLOSED) {\n log('replying to bye');\n this._state = RpcState.CLOSING;\n await this._sendMessage({ bye: {} });\n\n this._abortRequests();\n this._disposeAndClose();\n }\n } else {\n log.error('received malformed message', { msg });\n throw new Error('Malformed message.');\n }\n }\n\n /**\n * Make RPC call. Will trigger a handler on the other side.\n * Peer should be open before making this call.\n */\n async call(method: string, request: Any, options?: RequestOptions): Promise<Any> {\n DEBUG_CALLS && log('calling', { method });\n throwIfNotOpen(this._state);\n\n let response: Response;\n try {\n // Set-up response listener.\n const id = this._nextId++;\n const responseReceived = new Promise<Response>((resolve, reject) => {\n this._outgoingRequests.set(id, new PendingRpcRequest(resolve, reject, false));\n });\n\n // Send request call.\n const sending = this._sendMessage({\n request: {\n id,\n method,\n payload: request,\n stream: false,\n },\n });\n\n // Wait until send completes or throws an error (or response throws a timeout), the resume waiting.\n const timeout = options?.timeout ?? this._params.timeout;\n const waiting =\n timeout === 0 ? responseReceived : asyncTimeout<any>(responseReceived, timeout ?? DEFAULT_TIMEOUT);\n\n await Promise.race([sending, waiting]);\n response = await waiting;\n invariant(response.id === id);\n } catch (err) {\n if (err instanceof RpcClosedError) {\n // Rethrow the error here to have the correct stack-trace.\n const error = new RpcClosedError();\n error.stack += `\\n\\n info: RPC client was closed at:\\n${err.stack?.split('\\n').slice(1).join('\\n')}`;\n throw error;\n }\n\n throw err;\n }\n\n if (response.payload) {\n return response.payload;\n } else if (response.error) {\n throw decodeRpcError(response.error, method);\n } else {\n throw new Error('Malformed response.');\n }\n }\n\n /**\n * Make RPC call with a streaming response.\n * Will trigger a handler on the other side.\n * Peer should be open before making this call.\n */\n callStream(method: string, request: Any, options?: RequestOptions): Stream<Any> {\n throwIfNotOpen(this._state);\n const id = this._nextId++;\n\n return new Stream(({ ready, next, close }) => {\n const onResponse = (response: Response) => {\n if (response.streamReady) {\n ready();\n } else if (response.close) {\n close();\n } else if (response.error) {\n // TODO(dmaretskyi): Stack trace might be lost because the stream producer function is called asynchronously.\n close(decodeRpcError(response.error, method));\n } else if (response.payload) {\n next(response.payload);\n } else {\n throw new Error('Malformed response.');\n }\n };\n\n const stack = new StackTrace();\n const closeStream = (err?: Error) => {\n if (!err) {\n close();\n } else {\n err.stack += `\\n\\nError happened in the stream at:\\n${stack.getStack()}`;\n close(err);\n }\n };\n\n this._outgoingRequests.set(id, new PendingRpcRequest(onResponse, closeStream, true));\n\n this._sendMessage({\n request: {\n id,\n method,\n payload: request,\n stream: true,\n },\n }).catch((err) => {\n close(err);\n });\n\n return () => {\n this._sendMessage({\n streamClose: { id },\n }).catch((err) => {\n log.catch(err);\n });\n this._outgoingRequests.delete(id);\n };\n });\n }\n\n private async _sendMessage(message: RpcMessage, timeout?: number) {\n DEBUG_CALLS && log('sending message', { type: Object.keys(message)[0] });\n await this._params.port.send(getRpcMessageCodec().encode(message, { preserveAny: true }), timeout);\n }\n\n private async _callHandler(req: Request): Promise<Response> {\n try {\n invariant(typeof req.id === 'number');\n invariant(req.payload);\n invariant(req.method);\n\n const response = await this._params.callHandler(req.method, req.payload, this._params.handlerRpcOptions);\n return {\n id: req.id,\n payload: response,\n };\n } catch (err) {\n return {\n id: req.id,\n error: encodeError(err),\n };\n }\n }\n\n private _callStreamHandler(req: Request, callback: (response: Response) => void) {\n try {\n invariant(this._params.streamHandler, 'Requests with streaming responses are not supported.');\n invariant(typeof req.id === 'number');\n invariant(req.payload);\n invariant(req.method);\n\n const responseStream = this._params.streamHandler(req.method, req.payload, this._params.handlerRpcOptions);\n responseStream.onReady(() => {\n callback({\n id: req.id,\n streamReady: true,\n });\n });\n\n responseStream.subscribe(\n (msg) => {\n callback({\n id: req.id,\n payload: msg,\n });\n },\n (error) => {\n if (error) {\n callback({\n id: req.id,\n error: encodeError(error),\n });\n } else {\n callback({\n id: req.id,\n close: true,\n });\n }\n },\n );\n\n this._localStreams.set(req.id, responseStream);\n } catch (err: any) {\n callback({\n id: req.id,\n error: encodeError(err),\n });\n }\n }\n}\n\nconst throwIfNotOpen = (state: RpcState) => {\n switch (state) {\n case RpcState.OPENED: {\n return;\n }\n case RpcState.INITIAL: {\n throw new RpcNotOpenError();\n }\n case RpcState.CLOSED: {\n throw new RpcClosedError();\n }\n }\n};\n", "//\n// Copyright 2021 DXOS.org\n//\n\nimport { StackTrace } from '@dxos/debug';\nimport { decodeError } from '@dxos/protocols';\nimport { type Error as ErrorResponse } from '@dxos/protocols/proto/dxos/error';\n\nexport const decodeRpcError = (err: ErrorResponse, rpcMethod: string): Error =>\n decodeError(err, {\n appendStack: `\\n at RPC ${rpcMethod} \\n` + new StackTrace().getStack(1),\n });\n", "//\n// Copyright 2021 DXOS.org\n//\n\nimport {\n type EncodingOptions,\n type ServiceDescriptor,\n type ServiceHandler,\n type ServiceProvider,\n} from '@dxos/codec-protobuf';\nimport { invariant } from '@dxos/invariant';\n\nimport { RpcPeer, type RpcPeerOptions } from './rpc';\n\n/**\n * Map of service definitions.\n */\n// TODO(burdon): Rename ServiceMap.\nexport type ServiceBundle<Services> = { [Key in keyof Services]: ServiceDescriptor<Services[Key]> };\n\nexport type ServiceHandlers<Services> = { [ServiceName in keyof Services]: ServiceProvider<Services[ServiceName]> };\n\nexport type ServiceTypesOf<Bundle extends ServiceBundle<any>> =\n Bundle extends ServiceBundle<infer Services> ? Services : never;\n\n/**\n * Groups multiple services together to be served by a single RPC peer.\n */\nexport const createServiceBundle = <Service>(services: ServiceBundle<Service>): ServiceBundle<Service> => services;\n\n/**\n * Type-safe RPC peer.\n */\nexport class ProtoRpcPeer<Service> {\n constructor(\n public readonly rpc: Service,\n private readonly _peer: RpcPeer,\n ) {}\n\n async open() {\n await this._peer.open();\n }\n\n async close() {\n await this._peer.close();\n }\n\n async abort() {\n await this._peer.abort();\n }\n}\n\nexport interface ProtoRpcPeerOptions<Client, Server> extends Omit<RpcPeerOptions, 'callHandler' | 'streamHandler'> {\n /**\n * Services that are expected to be implemented by the counter-space.\n */\n // TODO(burdon): Rename proxy.\n requested?: ServiceBundle<Client>;\n\n /**\n * Services exposed to the counter-space.\n */\n // TODO(burdon): Rename service.\n exposed?: ServiceBundle<Server>;\n\n /**\n * Handlers for the exposed services\n */\n handlers?: ServiceHandlers<Server>;\n\n /**\n * Encoding options passed to the underlying proto codec.\n */\n encodingOptions?: EncodingOptions;\n}\n\n/**\n * Create type-safe RPC peer from a service bundle.\n * Can both handle and issue requests.\n */\n// TODO(burdon): Currently assumes that the proto service name is unique.\n// Support multiple instances services definitions (e.g., halo/space invitations).\nexport const createProtoRpcPeer = <Client = {}, Server = {}>({\n requested,\n exposed,\n handlers,\n encodingOptions,\n ...rest\n}: ProtoRpcPeerOptions<Client, Server>): ProtoRpcPeer<Client> => {\n // Create map of RPCs.\n const exposedRpcs: Record<string, ServiceHandler<any>> = {};\n if (exposed) {\n invariant(handlers);\n for (const serviceName of Object.keys(exposed) as (keyof Server)[]) {\n // Get full service name with the package name without '.' at the beginning.\n const serviceFqn = exposed[serviceName].serviceProto.fullName.slice(1);\n const serviceProvider = handlers[serviceName];\n exposedRpcs[serviceFqn] = exposed[serviceName].createServer(serviceProvider, encodingOptions);\n }\n }\n\n // Create peer.\n const peer = new RpcPeer({\n ...rest,\n\n callHandler: (method, request, options) => {\n const [serviceName, methodName] = parseMethodName(method);\n if (!exposedRpcs[serviceName]) {\n throw new Error(`Service not supported: ${serviceName}`);\n }\n\n return exposedRpcs[serviceName].call(methodName, request, options);\n },\n\n streamHandler: (method, request, options) => {\n const [serviceName, methodName] = parseMethodName(method);\n if (!exposedRpcs[serviceName]) {\n throw new Error(`Service not supported: ${serviceName}`);\n }\n\n return exposedRpcs[serviceName].callStream(methodName, request, options);\n },\n });\n\n const requestedRpcs: Client = {} as Client;\n if (requested) {\n for (const serviceName of Object.keys(requested) as (keyof Client)[]) {\n // Get full service name with the package name without '.' at the beginning.\n const serviceFqn = requested[serviceName].serviceProto.fullName.slice(1);\n\n requestedRpcs[serviceName] = requested[serviceName].createClient(\n {\n call: (method, req, options) => peer.call(`${serviceFqn}.${method}`, req, options),\n callStream: (method, req, options) => peer.callStream(`${serviceFqn}.${method}`, req, options),\n },\n encodingOptions,\n );\n }\n }\n\n return new ProtoRpcPeer(requestedRpcs, peer);\n};\n\nexport const parseMethodName = (method: string): [serviceName: string, methodName: string] => {\n const separator = method.lastIndexOf('.');\n const serviceName = method.slice(0, separator);\n const methodName = method.slice(separator + 1);\n if (serviceName.length === 0 || methodName.length === 0) {\n throw new Error(`Invalid method: ${method}`);\n }\n\n return [serviceName, methodName];\n};\n\n//\n// TODO(burdon): Remove deprecated (only bot factory).\n//\n\n/**\n * Create a type-safe RPC client.\n * @deprecated Use createProtoRpcPeer instead.\n */\nexport const createRpcClient = <S>(\n serviceDef: ServiceDescriptor<S>,\n options: Omit<RpcPeerOptions, 'callHandler'>,\n): ProtoRpcPeer<S> => {\n const peer = new RpcPeer({\n ...options,\n callHandler: () => {\n throw new Error('Requests to client are not supported.');\n },\n });\n\n const client = serviceDef.createClient({\n call: peer.call.bind(peer),\n callStream: peer.callStream.bind(peer),\n });\n\n return new ProtoRpcPeer(client, peer);\n};\n\n/**\n * @deprecated\n */\nexport interface RpcServerOptions<S> extends Omit<RpcPeerOptions, 'callHandler'> {\n service: ServiceDescriptor<S>;\n handlers: S;\n}\n\n/**\n * Create a type-safe RPC server.\n * @deprecated Use createProtoRpcPeer instead.\n */\nexport const createRpcServer = <S>({ service, handlers, ...rest }: RpcServerOptions<S>): RpcPeer => {\n const server = service.createServer(handlers);\n return new RpcPeer({\n ...rest,\n callHandler: server.call.bind(server),\n streamHandler: server.callStream.bind(server),\n });\n};\n\n/**\n * Create type-safe RPC client from a service bundle.\n * @deprecated Use createProtoRpcPeer instead.\n */\nexport const createBundledRpcClient = <S>(\n descriptors: ServiceBundle<S>,\n options: Omit<RpcPeerOptions, 'callHandler' | 'streamHandler'>,\n): ProtoRpcPeer<S> => {\n return createProtoRpcPeer({\n requested: descriptors,\n ...options,\n });\n};\n\n/**\n * @deprecated\n */\nexport interface RpcBundledServerOptions<S> extends Omit<RpcPeerOptions, 'callHandler'> {\n services: ServiceBundle<S>;\n handlers: S;\n}\n\n/**\n * Create type-safe RPC server from a service bundle.\n * @deprecated Use createProtoRpcPeer instead.\n */\n// TODO(burdon): Support late-binding via providers.\nexport const createBundledRpcServer = <S>({ services, handlers, ...rest }: RpcBundledServerOptions<S>): RpcPeer => {\n const rpc: Record<string, ServiceHandler<any>> = {};\n for (const serviceName of Object.keys(services) as (keyof S)[]) {\n // Get full service name with the package name without '.' at the beginning.\n const serviceFqn = services[serviceName].serviceProto.fullName.slice(1);\n rpc[serviceFqn] = services[serviceName].createServer(handlers[serviceName] as any);\n }\n\n return new RpcPeer({\n ...rest,\n\n callHandler: (method, request) => {\n const [serviceName, methodName] = parseMethodName(method);\n if (!rpc[serviceName]) {\n throw new Error(`Service not supported: ${serviceName}`);\n }\n\n return rpc[serviceName].call(methodName, request);\n },\n\n streamHandler: (method, request) => {\n const [serviceName, methodName] = parseMethodName(method);\n if (!rpc[serviceName]) {\n throw new Error(`Service not supported: ${serviceName}`);\n }\n\n return rpc[serviceName].callStream(methodName, request);\n },\n });\n};\n", "//\n// Copyright 2021 DXOS.org\n//\n\nimport { type RpcPort } from './rpc';\n\nexport type CreateLinkedPortsOptions = {\n delay?: number;\n};\n\n/**\n * Create bi-directionally linked ports.\n */\nexport const createLinkedPorts = ({ delay }: CreateLinkedPortsOptions = {}): [RpcPort, RpcPort] => {\n let port1Received: RpcPort['send'] | undefined;\n let port2Received: RpcPort['send'] | undefined;\n\n const send = (handler: RpcPort['send'] | undefined, msg: Uint8Array) => {\n if (delay) {\n setTimeout(() => handler?.(msg), delay);\n } else {\n void handler?.(msg);\n }\n };\n\n const port1: RpcPort = {\n send: (msg) => send(port2Received, msg),\n subscribe: (cb) => {\n port1Received = cb;\n },\n };\n\n const port2: RpcPort = {\n send: (msg) => send(port1Received, msg),\n subscribe: (cb) => {\n port2Received = cb;\n },\n };\n\n return [port1, port2];\n};\n", "//\n// Copyright 2021 DXOS.org\n//\n\nimport { Event } from '@dxos/async';\nimport { MessageTrace } from '@dxos/protocols/proto/dxos/rpc';\n\nimport { type RpcPort } from './rpc';\n\nexport class PortTracer {\n readonly message = new Event<MessageTrace>();\n\n private readonly _port: RpcPort;\n\n constructor(private readonly _wrappedPort: RpcPort) {\n this._port = {\n send: (msg: Uint8Array) => {\n this.message.emit({\n direction: MessageTrace.Direction.OUTGOING,\n data: msg,\n });\n\n return this._wrappedPort.send(msg);\n },\n subscribe: (cb: (msg: Uint8Array) => void) => {\n return this._wrappedPort.subscribe((msg) => {\n this.message.emit({\n direction: MessageTrace.Direction.INCOMING,\n data: msg,\n });\n cb(msg);\n });\n },\n };\n }\n\n public get port() {\n return this._port;\n }\n}\n"],
5
- "mappings": ";;;;;;;;;;AAIA,SAASA,cAAcC,cAAcC,eAAe;AACpD,SAAmBC,cAAoD;AACvE,SAASC,cAAAA,mBAAkB;AAC3B,SAASC,iBAAiB;AAC1B,SAASC,WAAW;AACpB,SAASC,aAAaC,gBAAgBC,iBAAiBC,cAAc;AAErE,SAASC,kCAAkC;;;ACP3C,SAASC,kBAAkB;AAC3B,SAASC,mBAAmB;AAGrB,IAAMC,iBAAiB,CAACC,KAAoBC,cACjDC,YAAYF,KAAK;EACfG,aAAa;aAAgBF,SAAAA;IAAiB,IAAIG,WAAAA,EAAaC,SAAS,CAAA;AAC1E,CAAA;;;;;;;;;;;;;;ADIF,IAAMC,kBAAkB;AACxB,IAAMC,mBAAmB;AAEzB,IAAMC,cAAc;AAkCpB,IAAMC,gBAAgB;A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AAA;AACF;;;ACrPO,IAAMwB,oBAAoB,CAAC,EAAEC,MAAK,IAA+B,CAAC,MAAC;AACxE,MAAIC;AACJ,MAAIC;AAEJ,QAAMC,OAAO,CAACC,SAAsCC,QAAAA;AAClD,QAAIL,OAAO;AACTM,iBAAW,MAAMF,UAAUC,GAAAA,GAAML,KAAAA;IACnC,OAAO;AACL,WAAKI,UAAUC,GAAAA;IACjB;EACF;AAEA,QAAME,QAAiB;IACrBJ,MAAM,CAACE,QAAQF,KAAKD,eAAeG,GAAAA;IACnCG,WAAW,CAACC,OAAAA;AACVR,sBAAgBQ;IAClB;EACF;AAEA,QAAMC,QAAiB;IACrBP,MAAM,CAACE,QAAQF,KAAKF,eAAeI,GAAAA;IACnCG,WAAW,CAACC,OAAAA;AACVP,sBAAgBO;IAClB;EACF;AAEA,SAAO;IAACF;IAAOG;;AACjB;;;ACpCA,SAASC,aAAa;AACtB,SAASC,oBAAoB;AAItB,IAAMC,aAAN,MAAMA;EAKXC,YAA6BC,cAAuB;SAAvBA,eAAAA;SAJpBC,UAAU,IAAIC,MAAAA;AAKrB,SAAKC,QAAQ;MACXC,MAAM,CAACC,QAAAA;AACL,aAAKJ,QAAQK,KAAK;UAChBC,WAAWC,aAAaC,UAAUC;UAClCC,MAAMN;QACR,CAAA;AAEA,eAAO,KAAKL,aAAaI,KAAKC,GAAAA;MAChC;MACAO,WAAW,CAACC,OAAAA;AACV,eAAO,KAAKb,aAAaY,UAAU,CAACP,QAAAA;AAClC,eAAKJ,QAAQK,KAAK;YAChBC,WAAWC,aAAaC,UAAUK;YAClCH,MAAMN;UACR,CAAA;AACAQ,aAAGR,GAAAA;QACL,CAAA;MACF;IACF;EACF;EAEA,IAAWU,OAAO;AAChB,WAAO,KAAKZ;EACd;AACF;",
4
+ "sourcesContent": ["//\n// Copyright 2021 DXOS.org\n//\n\nimport { asyncTimeout, synchronized, Trigger } from '@dxos/async';\nimport { type Any, Stream, type RequestOptions, type ProtoCodec } from '@dxos/codec-protobuf';\nimport { StackTrace } from '@dxos/debug';\nimport { invariant } from '@dxos/invariant';\nimport { log } from '@dxos/log';\nimport { encodeError, RpcClosedError, RpcNotOpenError } from '@dxos/protocols';\nimport { schema } from '@dxos/protocols/proto';\nimport { type Request, type Response, type RpcMessage } from '@dxos/protocols/proto/dxos/rpc';\nimport { exponentialBackoffInterval } from '@dxos/util';\n\nimport { decodeRpcError } from './errors';\n\nconst DEFAULT_TIMEOUT = 3_000;\nconst BYE_SEND_TIMEOUT = 2_000;\n\nconst DEBUG_CALLS = true;\n\ntype MaybePromise<T> = Promise<T> | T;\n\nexport interface RpcPeerOptions {\n port: RpcPort;\n\n /**\n * Time to wait for a response to an RPC call.\n */\n timeout?: number;\n\n callHandler: (method: string, request: Any, options?: RequestOptions) => MaybePromise<Any>;\n streamHandler?: (method: string, request: Any, options?: RequestOptions) => Stream<Any>;\n\n /**\n * Do not require or send handshake messages.\n */\n noHandshake?: boolean;\n\n /**\n * What options get passed to the `callHandler` and `streamHandler`.\n */\n handlerRpcOptions?: RequestOptions;\n}\n\n/**\n * Interface for a transport-agnostic port to send/receive binary messages.\n */\nexport interface RpcPort {\n send: (msg: Uint8Array, timeout?: number) => MaybePromise<void>;\n subscribe: (cb: (msg: Uint8Array) => void) => (() => void) | void;\n}\n\nconst CLOSE_TIMEOUT = 3_000;\n\nexport type CloseOptions = {\n /**\n * Time to wait for the other side to confirm close.\n */\n timeout?: number;\n};\n\nclass PendingRpcRequest {\n constructor(\n public readonly resolve: (response: Response) => void,\n public readonly reject: (error?: Error) => void,\n public readonly stream: boolean,\n ) {}\n}\n\n// NOTE: Lazy so that code that doesn't use indexing doesn't need to load the codec (breaks in workerd).\nlet RpcMessageCodec!: ProtoCodec<RpcMessage>;\nconst getRpcMessageCodec = () => (RpcMessageCodec ??= schema.getCodecForType('dxos.rpc.RpcMessage'));\n\nenum RpcState {\n INITIAL = 'INITIAL',\n\n OPENING = 'OPENING',\n\n OPENED = 'OPENED',\n\n /**\n * Bye message sent, waiting for the other side to close.\n * Not possible to send requests.\n * All pending requests will be rejected.\n */\n CLOSING = 'CLOSING',\n\n /**\n * Connection fully closed.\n * The underlying transport can be disposed.\n */\n CLOSED = 'CLOSED',\n}\n\n/**\n * A remote procedure call peer.\n *\n * Provides a away to make RPC calls and get a response back as a promise.\n * Does not handle encoding/decoding and only works with byte buffers.\n * For type safe approach see `createRpcClient` and `createRpcServer`.\n *\n * Must be connected with another instance on the other side via `send`/`receive` methods.\n * Both sides must be opened before making any RPC calls.\n *\n * Errors inside the handler get serialized and sent to the other side.\n *\n * Inspired by JSON-RPC 2.0 https://www.jsonrpc.org/specification.\n */\nexport class RpcPeer {\n private readonly _params: RpcPeerOptions;\n\n private readonly _outgoingRequests = new Map<number, PendingRpcRequest>();\n private readonly _localStreams = new Map<number, Stream<any>>();\n private readonly _remoteOpenTrigger = new Trigger();\n\n /**\n * Triggered when the peer starts closing.\n */\n private readonly _closingTrigger = new Trigger();\n\n /**\n * Triggered when peer receives a bye message.\n */\n private readonly _byeTrigger = new Trigger();\n\n private _nextId = 0;\n private _state: RpcState = RpcState.INITIAL;\n private _unsubscribeFromPort: (() => void) | undefined = undefined;\n private _clearOpenInterval: (() => void) | undefined = undefined;\n\n constructor(params: RpcPeerOptions) {\n this._params = {\n timeout: undefined,\n streamHandler: undefined,\n noHandshake: false,\n ...params,\n };\n }\n\n /**\n * Open the peer. Required before making any calls.\n *\n * Will block before the other peer calls `open`.\n */\n @synchronized\n async open() {\n if (this._state !== RpcState.INITIAL) {\n return;\n }\n\n this._unsubscribeFromPort = this._params.port.subscribe(async (msg) => {\n try {\n await this._receive(msg);\n } catch (err: any) {\n log.catch(err);\n }\n }) as any;\n\n this._state = RpcState.OPENING;\n\n if (this._params.noHandshake) {\n this._state = RpcState.OPENED;\n this._remoteOpenTrigger.wake();\n return;\n }\n\n log('sending open message', { state: this._state });\n await this._sendMessage({ open: true });\n\n if (this._state !== RpcState.OPENING) {\n return;\n }\n\n // Retry sending.\n this._clearOpenInterval = exponentialBackoffInterval(() => {\n void this._sendMessage({ open: true }).catch((err) => log.warn(err));\n }, 50);\n\n await Promise.race([this._remoteOpenTrigger.wait(), this._closingTrigger.wait()]);\n\n this._clearOpenInterval?.();\n\n if ((this._state as RpcState) !== RpcState.OPENED) {\n // Closed while opening.\n return; // TODO(dmaretskyi): Throw error?\n }\n\n // TODO(burdon): This seems error prone.\n // Send an \"open\" message in case the other peer has missed our first \"open\" message and is still waiting.\n log('sending second open message', { state: this._state });\n await this._sendMessage({ openAck: true });\n }\n\n /**\n * Close the peer.\n * Stop taking or making requests.\n * Will wait for confirmation from the other side.\n * Any responses for RPC calls made before close will be delivered.\n */\n async close({ timeout = CLOSE_TIMEOUT }: CloseOptions = {}) {\n if (this._state === RpcState.CLOSED) {\n return;\n }\n\n this._abortRequests();\n\n if (this._state === RpcState.OPENED && !this._params.noHandshake) {\n try {\n this._state = RpcState.CLOSING;\n await this._sendMessage({ bye: {} }, BYE_SEND_TIMEOUT);\n } catch (err: any) {\n log('error closing peer, sending bye', { err });\n }\n try {\n log('closing waiting on bye');\n await this._byeTrigger.wait({ timeout });\n } catch (err: any) {\n log('error closing peer', { err });\n return;\n }\n }\n\n this._disposeAndClose();\n }\n\n /**\n * Dispose the connection without waiting for the other side.\n */\n async abort() {\n if (this._state === RpcState.CLOSED) {\n return;\n }\n\n this._abortRequests();\n this._disposeAndClose();\n }\n\n private _abortRequests() {\n // Abort open\n this._clearOpenInterval?.();\n this._closingTrigger.wake();\n\n // Abort pending requests\n for (const req of this._outgoingRequests.values()) {\n req.reject(new RpcClosedError());\n }\n this._outgoingRequests.clear();\n }\n\n private _disposeAndClose() {\n this._unsubscribeFromPort?.();\n this._unsubscribeFromPort = undefined;\n this._clearOpenInterval?.();\n this._state = RpcState.CLOSED;\n }\n\n /**\n * Handle incoming message. Should be called as the result of other peer's `send` callback.\n */\n private async _receive(msg: Uint8Array): Promise<void> {\n const decoded = getRpcMessageCodec().decode(msg, { preserveAny: true });\n DEBUG_CALLS && log('received message', { type: Object.keys(decoded)[0] });\n\n if (decoded.request) {\n if (this._state !== RpcState.OPENED && this._state !== RpcState.OPENING) {\n log('received request while closed');\n await this._sendMessage({\n response: {\n id: decoded.request.id,\n error: encodeError(new RpcClosedError()),\n },\n });\n return;\n }\n\n const req = decoded.request;\n if (req.stream) {\n log('stream request', { method: req.method });\n this._callStreamHandler(req, (response) => {\n log('sending stream response', {\n method: req.method,\n response: response.payload?.type_url,\n error: response.error,\n close: response.close,\n });\n\n void this._sendMessage({ response }).catch((err) => {\n log.warn('failed during close', err);\n });\n });\n } else {\n DEBUG_CALLS && log('request', { method: req.method });\n const response = await this._callHandler(req);\n DEBUG_CALLS &&\n log('sending response', {\n method: req.method,\n response: response.payload?.type_url,\n error: response.error,\n });\n await this._sendMessage({ response });\n }\n } else if (decoded.response) {\n if (this._state !== RpcState.OPENED) {\n log('received response while closed');\n return; // Ignore when not open.\n }\n\n const responseId = decoded.response.id;\n invariant(typeof responseId === 'number');\n if (!this._outgoingRequests.has(responseId)) {\n log('received response with invalid id', { responseId });\n return; // Ignore requests with incorrect id.\n }\n\n const item = this._outgoingRequests.get(responseId)!;\n // Delete the request record if no more responses are expected.\n if (!item.stream) {\n this._outgoingRequests.delete(responseId);\n }\n\n DEBUG_CALLS && log('response', { type_url: decoded.response.payload?.type_url });\n item.resolve(decoded.response);\n } else if (decoded.open) {\n log('received open message', { state: this._state });\n if (this._params.noHandshake) {\n return;\n }\n\n await this._sendMessage({ openAck: true });\n } else if (decoded.openAck) {\n log('received openAck message', { state: this._state });\n if (this._params.noHandshake) {\n return;\n }\n\n this._state = RpcState.OPENED;\n this._remoteOpenTrigger.wake();\n } else if (decoded.streamClose) {\n if (this._state !== RpcState.OPENED) {\n log('received stream close while closed');\n return; // Ignore when not open.\n }\n\n log('received stream close', { id: decoded.streamClose.id });\n invariant(typeof decoded.streamClose.id === 'number');\n const stream = this._localStreams.get(decoded.streamClose.id);\n if (!stream) {\n log('no local stream', { id: decoded.streamClose.id });\n return; // Ignore requests with incorrect id.\n }\n\n this._localStreams.delete(decoded.streamClose.id);\n await stream.close();\n } else if (decoded.bye) {\n this._byeTrigger.wake();\n // If we haven't already started closing, close now.\n if (this._state !== RpcState.CLOSING && this._state !== RpcState.CLOSED) {\n log('replying to bye');\n this._state = RpcState.CLOSING;\n await this._sendMessage({ bye: {} });\n\n this._abortRequests();\n this._disposeAndClose();\n }\n } else {\n log.error('received malformed message', { msg });\n throw new Error('Malformed message.');\n }\n }\n\n /**\n * Make RPC call. Will trigger a handler on the other side.\n * Peer should be open before making this call.\n */\n async call(method: string, request: Any, options?: RequestOptions): Promise<Any> {\n DEBUG_CALLS && log('calling', { method });\n throwIfNotOpen(this._state);\n\n let response: Response;\n try {\n // Set-up response listener.\n const id = this._nextId++;\n const responseReceived = new Promise<Response>((resolve, reject) => {\n this._outgoingRequests.set(id, new PendingRpcRequest(resolve, reject, false));\n });\n\n // Send request call.\n const sending = this._sendMessage({\n request: {\n id,\n method,\n payload: request,\n stream: false,\n },\n });\n\n // Wait until send completes or throws an error (or response throws a timeout), the resume waiting.\n const timeout = options?.timeout ?? this._params.timeout;\n const waiting =\n timeout === 0 ? responseReceived : asyncTimeout<any>(responseReceived, timeout ?? DEFAULT_TIMEOUT);\n\n await Promise.race([sending, waiting]);\n response = await waiting;\n invariant(response.id === id);\n } catch (err) {\n if (err instanceof RpcClosedError) {\n // Rethrow the error here to have the correct stack-trace.\n const error = new RpcClosedError();\n error.stack += `\\n\\n info: RPC client was closed at:\\n${err.stack?.split('\\n').slice(1).join('\\n')}`;\n throw error;\n }\n\n throw err;\n }\n\n if (response.payload) {\n return response.payload;\n } else if (response.error) {\n throw decodeRpcError(response.error, method);\n } else {\n throw new Error('Malformed response.');\n }\n }\n\n /**\n * Make RPC call with a streaming response.\n * Will trigger a handler on the other side.\n * Peer should be open before making this call.\n */\n callStream(method: string, request: Any, options?: RequestOptions): Stream<Any> {\n throwIfNotOpen(this._state);\n const id = this._nextId++;\n\n return new Stream(({ ready, next, close }) => {\n const onResponse = (response: Response) => {\n if (response.streamReady) {\n ready();\n } else if (response.close) {\n close();\n } else if (response.error) {\n // TODO(dmaretskyi): Stack trace might be lost because the stream producer function is called asynchronously.\n close(decodeRpcError(response.error, method));\n } else if (response.payload) {\n next(response.payload);\n } else {\n throw new Error('Malformed response.');\n }\n };\n\n const stack = new StackTrace();\n const closeStream = (err?: Error) => {\n if (!err) {\n close();\n } else {\n err.stack += `\\n\\nError happened in the stream at:\\n${stack.getStack()}`;\n close(err);\n }\n };\n\n this._outgoingRequests.set(id, new PendingRpcRequest(onResponse, closeStream, true));\n\n this._sendMessage({\n request: {\n id,\n method,\n payload: request,\n stream: true,\n },\n }).catch((err) => {\n close(err);\n });\n\n return () => {\n this._sendMessage({\n streamClose: { id },\n }).catch((err) => {\n log.catch(err);\n });\n this._outgoingRequests.delete(id);\n };\n });\n }\n\n private async _sendMessage(message: RpcMessage, timeout?: number) {\n DEBUG_CALLS && log('sending message', { type: Object.keys(message)[0] });\n await this._params.port.send(getRpcMessageCodec().encode(message, { preserveAny: true }), timeout);\n }\n\n private async _callHandler(req: Request): Promise<Response> {\n try {\n invariant(typeof req.id === 'number');\n invariant(req.payload);\n invariant(req.method);\n\n const response = await this._params.callHandler(req.method, req.payload, this._params.handlerRpcOptions);\n return {\n id: req.id,\n payload: response,\n };\n } catch (err) {\n return {\n id: req.id,\n error: encodeError(err),\n };\n }\n }\n\n private _callStreamHandler(req: Request, callback: (response: Response) => void) {\n try {\n invariant(this._params.streamHandler, 'Requests with streaming responses are not supported.');\n invariant(typeof req.id === 'number');\n invariant(req.payload);\n invariant(req.method);\n\n const responseStream = this._params.streamHandler(req.method, req.payload, this._params.handlerRpcOptions);\n responseStream.onReady(() => {\n callback({\n id: req.id,\n streamReady: true,\n });\n });\n\n responseStream.subscribe(\n (msg) => {\n callback({\n id: req.id,\n payload: msg,\n });\n },\n (error) => {\n if (error) {\n callback({\n id: req.id,\n error: encodeError(error),\n });\n } else {\n callback({\n id: req.id,\n close: true,\n });\n }\n },\n );\n\n this._localStreams.set(req.id, responseStream);\n } catch (err: any) {\n callback({\n id: req.id,\n error: encodeError(err),\n });\n }\n }\n}\n\nconst throwIfNotOpen = (state: RpcState) => {\n switch (state) {\n case RpcState.OPENED: {\n return;\n }\n case RpcState.INITIAL: {\n throw new RpcNotOpenError();\n }\n case RpcState.CLOSED: {\n throw new RpcClosedError();\n }\n }\n};\n", "//\n// Copyright 2021 DXOS.org\n//\n\nimport { StackTrace } from '@dxos/debug';\nimport { decodeError } from '@dxos/protocols';\nimport { type Error as ErrorResponse } from '@dxos/protocols/proto/dxos/error';\n\nexport const decodeRpcError = (err: ErrorResponse, rpcMethod: string): Error =>\n decodeError(err, {\n appendStack: `\\n at RPC ${rpcMethod} \\n` + new StackTrace().getStack(1),\n });\n", "//\n// Copyright 2021 DXOS.org\n//\n\nimport {\n type EncodingOptions,\n type ServiceDescriptor,\n type ServiceHandler,\n type ServiceProvider,\n} from '@dxos/codec-protobuf';\nimport { invariant } from '@dxos/invariant';\n\nimport { RpcPeer, type RpcPeerOptions } from './rpc';\n\n/**\n * Map of service definitions.\n */\n// TODO(burdon): Rename ServiceMap.\nexport type ServiceBundle<Services> = { [Key in keyof Services]: ServiceDescriptor<Services[Key]> };\n\nexport type ServiceHandlers<Services> = { [ServiceName in keyof Services]: ServiceProvider<Services[ServiceName]> };\n\nexport type ServiceTypesOf<Bundle extends ServiceBundle<any>> =\n Bundle extends ServiceBundle<infer Services> ? Services : never;\n\n/**\n * Groups multiple services together to be served by a single RPC peer.\n */\nexport const createServiceBundle = <Service>(services: ServiceBundle<Service>): ServiceBundle<Service> => services;\n\n/**\n * Type-safe RPC peer.\n */\nexport class ProtoRpcPeer<Service> {\n constructor(\n public readonly rpc: Service,\n private readonly _peer: RpcPeer,\n ) {}\n\n async open() {\n await this._peer.open();\n }\n\n async close() {\n await this._peer.close();\n }\n\n async abort() {\n await this._peer.abort();\n }\n}\n\nexport interface ProtoRpcPeerOptions<Client, Server> extends Omit<RpcPeerOptions, 'callHandler' | 'streamHandler'> {\n /**\n * Services that are expected to be implemented by the counter-space.\n */\n // TODO(burdon): Rename proxy.\n requested?: ServiceBundle<Client>;\n\n /**\n * Services exposed to the counter-space.\n */\n // TODO(burdon): Rename service.\n exposed?: ServiceBundle<Server>;\n\n /**\n * Handlers for the exposed services\n */\n handlers?: ServiceHandlers<Server>;\n\n /**\n * Encoding options passed to the underlying proto codec.\n */\n encodingOptions?: EncodingOptions;\n}\n\n/**\n * Create type-safe RPC peer from a service bundle.\n * Can both handle and issue requests.\n */\n// TODO(burdon): Currently assumes that the proto service name is unique.\n// Support multiple instances services definitions (e.g., halo/space invitations).\nexport const createProtoRpcPeer = <Client = {}, Server = {}>({\n requested,\n exposed,\n handlers,\n encodingOptions,\n ...rest\n}: ProtoRpcPeerOptions<Client, Server>): ProtoRpcPeer<Client> => {\n // Create map of RPCs.\n const exposedRpcs: Record<string, ServiceHandler<any>> = {};\n if (exposed) {\n invariant(handlers);\n for (const serviceName of Object.keys(exposed) as (keyof Server)[]) {\n // Get full service name with the package name without '.' at the beginning.\n const serviceFqn = exposed[serviceName].serviceProto.fullName.slice(1);\n const serviceProvider = handlers[serviceName];\n exposedRpcs[serviceFqn] = exposed[serviceName].createServer(serviceProvider, encodingOptions);\n }\n }\n\n // Create peer.\n const peer = new RpcPeer({\n ...rest,\n\n callHandler: (method, request, options) => {\n const [serviceName, methodName] = parseMethodName(method);\n if (!exposedRpcs[serviceName]) {\n throw new Error(`Service not supported: ${serviceName}`);\n }\n\n return exposedRpcs[serviceName].call(methodName, request, options);\n },\n\n streamHandler: (method, request, options) => {\n const [serviceName, methodName] = parseMethodName(method);\n if (!exposedRpcs[serviceName]) {\n throw new Error(`Service not supported: ${serviceName}`);\n }\n\n return exposedRpcs[serviceName].callStream(methodName, request, options);\n },\n });\n\n const requestedRpcs: Client = {} as Client;\n if (requested) {\n for (const serviceName of Object.keys(requested) as (keyof Client)[]) {\n // Get full service name with the package name without '.' at the beginning.\n const serviceFqn = requested[serviceName].serviceProto.fullName.slice(1);\n\n requestedRpcs[serviceName] = requested[serviceName].createClient(\n {\n call: (method, req, options) => peer.call(`${serviceFqn}.${method}`, req, options),\n callStream: (method, req, options) => peer.callStream(`${serviceFqn}.${method}`, req, options),\n },\n encodingOptions,\n );\n }\n }\n\n return new ProtoRpcPeer(requestedRpcs, peer);\n};\n\nexport const parseMethodName = (method: string): [serviceName: string, methodName: string] => {\n const separator = method.lastIndexOf('.');\n const serviceName = method.slice(0, separator);\n const methodName = method.slice(separator + 1);\n if (serviceName.length === 0 || methodName.length === 0) {\n throw new Error(`Invalid method: ${method}`);\n }\n\n return [serviceName, methodName];\n};\n\n//\n// TODO(burdon): Remove deprecated (only bot factory).\n//\n\n/**\n * Create a type-safe RPC client.\n * @deprecated Use createProtoRpcPeer instead.\n */\nexport const createRpcClient = <S>(\n serviceDef: ServiceDescriptor<S>,\n options: Omit<RpcPeerOptions, 'callHandler'>,\n): ProtoRpcPeer<S> => {\n const peer = new RpcPeer({\n ...options,\n callHandler: () => {\n throw new Error('Requests to client are not supported.');\n },\n });\n\n const client = serviceDef.createClient({\n call: peer.call.bind(peer),\n callStream: peer.callStream.bind(peer),\n });\n\n return new ProtoRpcPeer(client, peer);\n};\n\n/**\n * @deprecated\n */\nexport interface RpcServerOptions<S> extends Omit<RpcPeerOptions, 'callHandler'> {\n service: ServiceDescriptor<S>;\n handlers: S;\n}\n\n/**\n * Create a type-safe RPC server.\n * @deprecated Use createProtoRpcPeer instead.\n */\nexport const createRpcServer = <S>({ service, handlers, ...rest }: RpcServerOptions<S>): RpcPeer => {\n const server = service.createServer(handlers);\n return new RpcPeer({\n ...rest,\n callHandler: server.call.bind(server),\n streamHandler: server.callStream.bind(server),\n });\n};\n\n/**\n * Create type-safe RPC client from a service bundle.\n * @deprecated Use createProtoRpcPeer instead.\n */\nexport const createBundledRpcClient = <S>(\n descriptors: ServiceBundle<S>,\n options: Omit<RpcPeerOptions, 'callHandler' | 'streamHandler'>,\n): ProtoRpcPeer<S> => {\n return createProtoRpcPeer({\n requested: descriptors,\n ...options,\n });\n};\n\n/**\n * @deprecated\n */\nexport interface RpcBundledServerOptions<S> extends Omit<RpcPeerOptions, 'callHandler'> {\n services: ServiceBundle<S>;\n handlers: S;\n}\n\n/**\n * Create type-safe RPC server from a service bundle.\n * @deprecated Use createProtoRpcPeer instead.\n */\n// TODO(burdon): Support late-binding via providers.\nexport const createBundledRpcServer = <S>({ services, handlers, ...rest }: RpcBundledServerOptions<S>): RpcPeer => {\n const rpc: Record<string, ServiceHandler<any>> = {};\n for (const serviceName of Object.keys(services) as (keyof S)[]) {\n // Get full service name with the package name without '.' at the beginning.\n const serviceFqn = services[serviceName].serviceProto.fullName.slice(1);\n rpc[serviceFqn] = services[serviceName].createServer(handlers[serviceName] as any);\n }\n\n return new RpcPeer({\n ...rest,\n\n callHandler: (method, request) => {\n const [serviceName, methodName] = parseMethodName(method);\n if (!rpc[serviceName]) {\n throw new Error(`Service not supported: ${serviceName}`);\n }\n\n return rpc[serviceName].call(methodName, request);\n },\n\n streamHandler: (method, request) => {\n const [serviceName, methodName] = parseMethodName(method);\n if (!rpc[serviceName]) {\n throw new Error(`Service not supported: ${serviceName}`);\n }\n\n return rpc[serviceName].callStream(methodName, request);\n },\n });\n};\n", "//\n// Copyright 2021 DXOS.org\n//\n\nimport { type RpcPort } from './rpc';\n\nexport type CreateLinkedPortsOptions = {\n delay?: number;\n};\n\n/**\n * Create bi-directionally linked ports.\n */\nexport const createLinkedPorts = ({ delay }: CreateLinkedPortsOptions = {}): [RpcPort, RpcPort] => {\n let port1Received: RpcPort['send'] | undefined;\n let port2Received: RpcPort['send'] | undefined;\n\n const send = (handler: RpcPort['send'] | undefined, msg: Uint8Array) => {\n if (delay) {\n setTimeout(() => handler?.(msg), delay);\n } else {\n void handler?.(msg);\n }\n };\n\n const port1: RpcPort = {\n send: (msg) => send(port2Received, msg),\n subscribe: (cb) => {\n port1Received = cb;\n },\n };\n\n const port2: RpcPort = {\n send: (msg) => send(port1Received, msg),\n subscribe: (cb) => {\n port2Received = cb;\n },\n };\n\n return [port1, port2];\n};\n", "//\n// Copyright 2021 DXOS.org\n//\n\nimport { Event } from '@dxos/async';\nimport { MessageTrace } from '@dxos/protocols/proto/dxos/rpc';\n\nimport { type RpcPort } from './rpc';\n\nexport class PortTracer {\n readonly message = new Event<MessageTrace>();\n\n private readonly _port: RpcPort;\n\n constructor(private readonly _wrappedPort: RpcPort) {\n this._port = {\n send: (msg: Uint8Array) => {\n this.message.emit({\n direction: MessageTrace.Direction.OUTGOING,\n data: msg,\n });\n\n return this._wrappedPort.send(msg);\n },\n subscribe: (cb: (msg: Uint8Array) => void) => {\n return this._wrappedPort.subscribe((msg) => {\n this.message.emit({\n direction: MessageTrace.Direction.INCOMING,\n data: msg,\n });\n cb(msg);\n });\n },\n };\n }\n\n public get port() {\n return this._port;\n }\n}\n"],
5
+ "mappings": ";;;;;;;;;;AAIA,SAASA,cAAcC,cAAcC,eAAe;AACpD,SAAmBC,cAAoD;AACvE,SAASC,cAAAA,mBAAkB;AAC3B,SAASC,iBAAiB;AAC1B,SAASC,WAAW;AACpB,SAASC,aAAaC,gBAAgBC,uBAAuB;AAC7D,SAASC,cAAc;AAEvB,SAASC,kCAAkC;;;ACR3C,SAASC,kBAAkB;AAC3B,SAASC,mBAAmB;AAGrB,IAAMC,iBAAiB,CAACC,KAAoBC,cACjDC,YAAYF,KAAK;EACfG,aAAa;aAAgBF,SAAAA;IAAiB,IAAIG,WAAAA,EAAaC,SAAS,CAAA;AAC1E,CAAA;;;;;;;;;;;;;;ADKF,IAAMC,kBAAkB;AACxB,IAAMC,mBAAmB;AAEzB,IAAMC,cAAc;AAkCpB,IAAMC,gBAAgB;AAStB,IAAMC,oBAAN,MAAMA;EACJC,YACkBC,SACAC,QACAC,QAChB;SAHgBF,UAAAA;SACAC,SAAAA;SACAC,SAAAA;EACf;AACL;AAGA,IAAIC;AACJ,IAAMC,qB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AAA;AAClD,QAAIL,OAAO;AACTM,iBAAW,MAAMF,UAAUC,GAAAA,GAAML,KAAAA;IACnC,OAAO;AACL,WAAKI,UAAUC,GAAAA;IACjB;EACF;AAEA,QAAME,QAAiB;IACrBJ,MAAM,CAACE,QAAQF,KAAKD,eAAeG,GAAAA;IACnCG,WAAW,CAACC,OAAAA;AACVR,sBAAgBQ;IAClB;EACF;AAEA,QAAMC,QAAiB;IACrBP,MAAM,CAACE,QAAQF,KAAKF,eAAeI,GAAAA;IACnCG,WAAW,CAACC,OAAAA;AACVP,sBAAgBO;IAClB;EACF;AAEA,SAAO;IAACF;IAAOG;;AACjB;;;ACpCA,SAASC,aAAa;AACtB,SAASC,oBAAoB;AAItB,IAAMC,aAAN,MAAMA;EAKXC,YAA6BC,cAAuB;SAAvBA,eAAAA;SAJpBC,UAAU,IAAIC,MAAAA;AAKrB,SAAKC,QAAQ;MACXC,MAAM,CAACC,QAAAA;AACL,aAAKJ,QAAQK,KAAK;UAChBC,WAAWC,aAAaC,UAAUC;UAClCC,MAAMN;QACR,CAAA;AAEA,eAAO,KAAKL,aAAaI,KAAKC,GAAAA;MAChC;MACAO,WAAW,CAACC,OAAAA;AACV,eAAO,KAAKb,aAAaY,UAAU,CAACP,QAAAA;AAClC,eAAKJ,QAAQK,KAAK;YAChBC,WAAWC,aAAaC,UAAUK;YAClCH,MAAMN;UACR,CAAA;AACAQ,aAAGR,GAAAA;QACL,CAAA;MACF;IACF;EACF;EAEA,IAAWU,OAAO;AAChB,WAAO,KAAKZ;EACd;AACF;",
6
6
  "names": ["asyncTimeout", "synchronized", "Trigger", "Stream", "StackTrace", "invariant", "log", "encodeError", "RpcClosedError", "RpcNotOpenError", "schema", "exponentialBackoffInterval", "StackTrace", "decodeError", "decodeRpcError", "err", "rpcMethod", "decodeError", "appendStack", "StackTrace", "getStack", "DEFAULT_TIMEOUT", "BYE_SEND_TIMEOUT", "DEBUG_CALLS", "CLOSE_TIMEOUT", "PendingRpcRequest", "constructor", "resolve", "reject", "stream", "RpcMessageCodec", "getRpcMessageCodec", "schema", "getCodecForType", "RpcState", "RpcPeer", "params", "_outgoingRequests", "Map", "_localStreams", "_remoteOpenTrigger", "Trigger", "_closingTrigger", "_byeTrigger", "_nextId", "_state", "_unsubscribeFromPort", "undefined", "_clearOpenInterval", "_params", "timeout", "streamHandler", "noHandshake", "open", "port", "subscribe", "msg", "_receive", "err", "log", "catch", "wake", "state", "_sendMessage", "exponentialBackoffInterval", "warn", "Promise", "race", "wait", "openAck", "close", "_abortRequests", "bye", "_disposeAndClose", "abort", "req", "values", "RpcClosedError", "clear", "decoded", "decode", "preserveAny", "type", "Object", "keys", "request", "response", "id", "error", "encodeError", "method", "_callStreamHandler", "payload", "type_url", "_callHandler", "responseId", "invariant", "has", "item", "get", "delete", "streamClose", "Error", "call", "options", "throwIfNotOpen", "responseReceived", "set", "sending", "waiting", "asyncTimeout", "stack", "split", "slice", "join", "decodeRpcError", "callStream", "Stream", "ready", "next", "onResponse", "streamReady", "StackTrace", "closeStream", "getStack", "message", "send", "encode", "callHandler", "handlerRpcOptions", "callback", "responseStream", "onReady", "synchronized", "RpcNotOpenError", "invariant", "createServiceBundle", "services", "ProtoRpcPeer", "constructor", "rpc", "_peer", "open", "close", "abort", "createProtoRpcPeer", "requested", "exposed", "handlers", "encodingOptions", "rest", "exposedRpcs", "invariant", "serviceName", "Object", "keys", "serviceFqn", "serviceProto", "fullName", "slice", "serviceProvider", "createServer", "peer", "RpcPeer", "callHandler", "method", "request", "options", "methodName", "parseMethodName", "Error", "call", "streamHandler", "callStream", "requestedRpcs", "createClient", "req", "separator", "lastIndexOf", "length", "createRpcClient", "serviceDef", "client", "bind", "createRpcServer", "service", "server", "createBundledRpcClient", "descriptors", "createBundledRpcServer", "createLinkedPorts", "delay", "port1Received", "port2Received", "send", "handler", "msg", "setTimeout", "port1", "subscribe", "cb", "port2", "Event", "MessageTrace", "PortTracer", "constructor", "_wrappedPort", "message", "Event", "_port", "send", "msg", "emit", "direction", "MessageTrace", "Direction", "OUTGOING", "data", "subscribe", "cb", "INCOMING", "port"]
7
7
  }
@@ -1 +1 @@
1
- {"inputs":{"inject-globals:@inject-globals":{"bytes":384,"imports":[{"path":"@dxos/node-std/inject-globals","kind":"import-statement","external":true}],"format":"esm"},"packages/core/mesh/rpc/src/errors.ts":{"bytes":1518,"imports":[{"path":"@dxos/debug","kind":"import-statement","external":true},{"path":"@dxos/protocols","kind":"import-statement","external":true},{"path":"@inject-globals","kind":"import-statement","external":true}],"format":"esm"},"packages/core/mesh/rpc/src/rpc.ts":{"bytes":63286,"imports":[{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/codec-protobuf","kind":"import-statement","external":true},{"path":"@dxos/debug","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/protocols","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true},{"path":"packages/core/mesh/rpc/src/errors.ts","kind":"import-statement","original":"./errors"},{"path":"@inject-globals","kind":"import-statement","external":true}],"format":"esm"},"packages/core/mesh/rpc/src/service.ts":{"bytes":22633,"imports":[{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"packages/core/mesh/rpc/src/rpc.ts","kind":"import-statement","original":"./rpc"},{"path":"@inject-globals","kind":"import-statement","external":true}],"format":"esm"},"packages/core/mesh/rpc/src/testing.ts":{"bytes":3040,"imports":[{"path":"@inject-globals","kind":"import-statement","external":true}],"format":"esm"},"packages/core/mesh/rpc/src/trace.ts":{"bytes":3615,"imports":[{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/protocols/proto/dxos/rpc","kind":"import-statement","external":true},{"path":"@inject-globals","kind":"import-statement","external":true}],"format":"esm"},"packages/core/mesh/rpc/src/index.ts":{"bytes":822,"imports":[{"path":"packages/core/mesh/rpc/src/rpc.ts","kind":"import-statement","original":"./rpc"},{"path":"packages/core/mesh/rpc/src/errors.ts","kind":"import-statement","original":"./errors"},{"path":"packages/core/mesh/rpc/src/service.ts","kind":"import-statement","original":"./service"},{"path":"packages/core/mesh/rpc/src/testing.ts","kind":"import-statement","original":"./testing"},{"path":"packages/core/mesh/rpc/src/trace.ts","kind":"import-statement","original":"./trace"},{"path":"@inject-globals","kind":"import-statement","external":true}],"format":"esm"}},"outputs":{"packages/core/mesh/rpc/dist/lib/browser/index.mjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":43134},"packages/core/mesh/rpc/dist/lib/browser/index.mjs":{"imports":[{"path":"@dxos/node-std/inject-globals","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/codec-protobuf","kind":"import-statement","external":true},{"path":"@dxos/debug","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/protocols","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true},{"path":"@dxos/debug","kind":"import-statement","external":true},{"path":"@dxos/protocols","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/protocols/proto/dxos/rpc","kind":"import-statement","external":true}],"exports":["PortTracer","ProtoRpcPeer","RpcPeer","createBundledRpcClient","createBundledRpcServer","createLinkedPorts","createProtoRpcPeer","createRpcClient","createRpcServer","createServiceBundle","decodeRpcError","parseMethodName"],"entryPoint":"packages/core/mesh/rpc/src/index.ts","inputs":{"inject-globals:@inject-globals":{"bytesInOutput":79},"packages/core/mesh/rpc/src/rpc.ts":{"bytesInOutput":18113},"packages/core/mesh/rpc/src/errors.ts":{"bytesInOutput":228},"packages/core/mesh/rpc/src/index.ts":{"bytesInOutput":0},"packages/core/mesh/rpc/src/service.ts":{"bytesInOutput":4242},"packages/core/mesh/rpc/src/testing.ts":{"bytesInOutput":528},"packages/core/mesh/rpc/src/trace.ts":{"bytesInOutput":732}},"bytes":24511}}}
1
+ {"inputs":{"inject-globals:@inject-globals":{"bytes":384,"imports":[{"path":"@dxos/node-std/inject-globals","kind":"import-statement","external":true}],"format":"esm"},"packages/core/mesh/rpc/src/errors.ts":{"bytes":1518,"imports":[{"path":"@dxos/debug","kind":"import-statement","external":true},{"path":"@dxos/protocols","kind":"import-statement","external":true},{"path":"@inject-globals","kind":"import-statement","external":true}],"format":"esm"},"packages/core/mesh/rpc/src/rpc.ts":{"bytes":63406,"imports":[{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/codec-protobuf","kind":"import-statement","external":true},{"path":"@dxos/debug","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/protocols","kind":"import-statement","external":true},{"path":"@dxos/protocols/proto","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true},{"path":"packages/core/mesh/rpc/src/errors.ts","kind":"import-statement","original":"./errors"},{"path":"@inject-globals","kind":"import-statement","external":true}],"format":"esm"},"packages/core/mesh/rpc/src/service.ts":{"bytes":22633,"imports":[{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"packages/core/mesh/rpc/src/rpc.ts","kind":"import-statement","original":"./rpc"},{"path":"@inject-globals","kind":"import-statement","external":true}],"format":"esm"},"packages/core/mesh/rpc/src/testing.ts":{"bytes":3040,"imports":[{"path":"@inject-globals","kind":"import-statement","external":true}],"format":"esm"},"packages/core/mesh/rpc/src/trace.ts":{"bytes":3615,"imports":[{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/protocols/proto/dxos/rpc","kind":"import-statement","external":true},{"path":"@inject-globals","kind":"import-statement","external":true}],"format":"esm"},"packages/core/mesh/rpc/src/index.ts":{"bytes":822,"imports":[{"path":"packages/core/mesh/rpc/src/rpc.ts","kind":"import-statement","original":"./rpc"},{"path":"packages/core/mesh/rpc/src/errors.ts","kind":"import-statement","original":"./errors"},{"path":"packages/core/mesh/rpc/src/service.ts","kind":"import-statement","original":"./service"},{"path":"packages/core/mesh/rpc/src/testing.ts","kind":"import-statement","original":"./testing"},{"path":"packages/core/mesh/rpc/src/trace.ts","kind":"import-statement","original":"./trace"},{"path":"@inject-globals","kind":"import-statement","external":true}],"format":"esm"}},"outputs":{"packages/core/mesh/rpc/dist/lib/browser/index.mjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":43186},"packages/core/mesh/rpc/dist/lib/browser/index.mjs":{"imports":[{"path":"@dxos/node-std/inject-globals","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/codec-protobuf","kind":"import-statement","external":true},{"path":"@dxos/debug","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/protocols","kind":"import-statement","external":true},{"path":"@dxos/protocols/proto","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true},{"path":"@dxos/debug","kind":"import-statement","external":true},{"path":"@dxos/protocols","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/protocols/proto/dxos/rpc","kind":"import-statement","external":true}],"exports":["PortTracer","ProtoRpcPeer","RpcPeer","createBundledRpcClient","createBundledRpcServer","createLinkedPorts","createProtoRpcPeer","createRpcClient","createRpcServer","createServiceBundle","decodeRpcError","parseMethodName"],"entryPoint":"packages/core/mesh/rpc/src/index.ts","inputs":{"inject-globals:@inject-globals":{"bytesInOutput":79},"packages/core/mesh/rpc/src/rpc.ts":{"bytesInOutput":18153},"packages/core/mesh/rpc/src/errors.ts":{"bytesInOutput":228},"packages/core/mesh/rpc/src/index.ts":{"bytesInOutput":0},"packages/core/mesh/rpc/src/service.ts":{"bytesInOutput":4242},"packages/core/mesh/rpc/src/testing.ts":{"bytesInOutput":528},"packages/core/mesh/rpc/src/trace.ts":{"bytesInOutput":732}},"bytes":24551}}}
@@ -38,6 +38,7 @@ var import_debug = require("@dxos/debug");
38
38
  var import_invariant = require("@dxos/invariant");
39
39
  var import_log = require("@dxos/log");
40
40
  var import_protocols = require("@dxos/protocols");
41
+ var import_proto = require("@dxos/protocols/proto");
41
42
  var import_util = require("@dxos/util");
42
43
  var import_debug2 = require("@dxos/debug");
43
44
  var import_protocols2 = require("@dxos/protocols");
@@ -72,7 +73,7 @@ var PendingRpcRequest = class {
72
73
  }
73
74
  };
74
75
  var RpcMessageCodec;
75
- var getRpcMessageCodec = () => RpcMessageCodec ??= import_protocols.schema.getCodecForType("dxos.rpc.RpcMessage");
76
+ var getRpcMessageCodec = () => RpcMessageCodec ??= import_proto.schema.getCodecForType("dxos.rpc.RpcMessage");
76
77
  var RpcState;
77
78
  (function(RpcState2) {
78
79
  RpcState2["INITIAL"] = "INITIAL";
@@ -114,7 +115,7 @@ var RpcPeer = class {
114
115
  } catch (err) {
115
116
  import_log.log.catch(err, void 0, {
116
117
  F: __dxlog_file,
117
- L: 155,
118
+ L: 156,
118
119
  S: this,
119
120
  C: (f, a) => f(...a)
120
121
  });
@@ -130,7 +131,7 @@ var RpcPeer = class {
130
131
  state: this._state
131
132
  }, {
132
133
  F: __dxlog_file,
133
- L: 167,
134
+ L: 168,
134
135
  S: this,
135
136
  C: (f, a) => f(...a)
136
137
  });
@@ -145,7 +146,7 @@ var RpcPeer = class {
145
146
  open: true
146
147
  }).catch((err) => import_log.log.warn(err, void 0, {
147
148
  F: __dxlog_file,
148
- L: 176,
149
+ L: 177,
149
150
  S: this,
150
151
  C: (f, a) => f(...a)
151
152
  }));
@@ -162,7 +163,7 @@ var RpcPeer = class {
162
163
  state: this._state
163
164
  }, {
164
165
  F: __dxlog_file,
165
- L: 190,
166
+ L: 191,
166
167
  S: this,
167
168
  C: (f, a) => f(...a)
168
169
  });
@@ -192,7 +193,7 @@ var RpcPeer = class {
192
193
  err
193
194
  }, {
194
195
  F: __dxlog_file,
195
- L: 212,
196
+ L: 213,
196
197
  S: this,
197
198
  C: (f, a) => f(...a)
198
199
  });
@@ -200,7 +201,7 @@ var RpcPeer = class {
200
201
  try {
201
202
  (0, import_log.log)("closing waiting on bye", void 0, {
202
203
  F: __dxlog_file,
203
- L: 215,
204
+ L: 216,
204
205
  S: this,
205
206
  C: (f, a) => f(...a)
206
207
  });
@@ -212,7 +213,7 @@ var RpcPeer = class {
212
213
  err
213
214
  }, {
214
215
  F: __dxlog_file,
215
- L: 218,
216
+ L: 219,
216
217
  S: this,
217
218
  C: (f, a) => f(...a)
218
219
  });
@@ -256,7 +257,7 @@ var RpcPeer = class {
256
257
  type: Object.keys(decoded)[0]
257
258
  }, {
258
259
  F: __dxlog_file,
259
- L: 262,
260
+ L: 263,
260
261
  S: this,
261
262
  C: (f, a) => f(...a)
262
263
  });
@@ -264,7 +265,7 @@ var RpcPeer = class {
264
265
  if (this._state !== "OPENED" && this._state !== "OPENING") {
265
266
  (0, import_log.log)("received request while closed", void 0, {
266
267
  F: __dxlog_file,
267
- L: 266,
268
+ L: 267,
268
269
  S: this,
269
270
  C: (f, a) => f(...a)
270
271
  });
@@ -282,7 +283,7 @@ var RpcPeer = class {
282
283
  method: req.method
283
284
  }, {
284
285
  F: __dxlog_file,
285
- L: 278,
286
+ L: 279,
286
287
  S: this,
287
288
  C: (f, a) => f(...a)
288
289
  });
@@ -294,7 +295,7 @@ var RpcPeer = class {
294
295
  close: response.close
295
296
  }, {
296
297
  F: __dxlog_file,
297
- L: 280,
298
+ L: 281,
298
299
  S: this,
299
300
  C: (f, a) => f(...a)
300
301
  });
@@ -303,7 +304,7 @@ var RpcPeer = class {
303
304
  }).catch((err) => {
304
305
  import_log.log.warn("failed during close", err, {
305
306
  F: __dxlog_file,
306
- L: 288,
307
+ L: 289,
307
308
  S: this,
308
309
  C: (f, a) => f(...a)
309
310
  });
@@ -314,7 +315,7 @@ var RpcPeer = class {
314
315
  method: req.method
315
316
  }, {
316
317
  F: __dxlog_file,
317
- L: 292,
318
+ L: 293,
318
319
  S: this,
319
320
  C: (f, a) => f(...a)
320
321
  });
@@ -325,7 +326,7 @@ var RpcPeer = class {
325
326
  error: response.error
326
327
  }, {
327
328
  F: __dxlog_file,
328
- L: 295,
329
+ L: 296,
329
330
  S: this,
330
331
  C: (f, a) => f(...a)
331
332
  });
@@ -337,7 +338,7 @@ var RpcPeer = class {
337
338
  if (this._state !== "OPENED") {
338
339
  (0, import_log.log)("received response while closed", void 0, {
339
340
  F: __dxlog_file,
340
- L: 304,
341
+ L: 305,
341
342
  S: this,
342
343
  C: (f, a) => f(...a)
343
344
  });
@@ -346,7 +347,7 @@ var RpcPeer = class {
346
347
  const responseId = decoded.response.id;
347
348
  (0, import_invariant.invariant)(typeof responseId === "number", void 0, {
348
349
  F: __dxlog_file,
349
- L: 309,
350
+ L: 310,
350
351
  S: this,
351
352
  A: [
352
353
  "typeof responseId === 'number'",
@@ -358,7 +359,7 @@ var RpcPeer = class {
358
359
  responseId
359
360
  }, {
360
361
  F: __dxlog_file,
361
- L: 311,
362
+ L: 312,
362
363
  S: this,
363
364
  C: (f, a) => f(...a)
364
365
  });
@@ -372,7 +373,7 @@ var RpcPeer = class {
372
373
  type_url: decoded.response.payload?.type_url
373
374
  }, {
374
375
  F: __dxlog_file,
375
- L: 321,
376
+ L: 322,
376
377
  S: this,
377
378
  C: (f, a) => f(...a)
378
379
  });
@@ -382,7 +383,7 @@ var RpcPeer = class {
382
383
  state: this._state
383
384
  }, {
384
385
  F: __dxlog_file,
385
- L: 324,
386
+ L: 325,
386
387
  S: this,
387
388
  C: (f, a) => f(...a)
388
389
  });
@@ -397,7 +398,7 @@ var RpcPeer = class {
397
398
  state: this._state
398
399
  }, {
399
400
  F: __dxlog_file,
400
- L: 331,
401
+ L: 332,
401
402
  S: this,
402
403
  C: (f, a) => f(...a)
403
404
  });
@@ -410,7 +411,7 @@ var RpcPeer = class {
410
411
  if (this._state !== "OPENED") {
411
412
  (0, import_log.log)("received stream close while closed", void 0, {
412
413
  F: __dxlog_file,
413
- L: 340,
414
+ L: 341,
414
415
  S: this,
415
416
  C: (f, a) => f(...a)
416
417
  });
@@ -420,13 +421,13 @@ var RpcPeer = class {
420
421
  id: decoded.streamClose.id
421
422
  }, {
422
423
  F: __dxlog_file,
423
- L: 344,
424
+ L: 345,
424
425
  S: this,
425
426
  C: (f, a) => f(...a)
426
427
  });
427
428
  (0, import_invariant.invariant)(typeof decoded.streamClose.id === "number", void 0, {
428
429
  F: __dxlog_file,
429
- L: 345,
430
+ L: 346,
430
431
  S: this,
431
432
  A: [
432
433
  "typeof decoded.streamClose.id === 'number'",
@@ -439,7 +440,7 @@ var RpcPeer = class {
439
440
  id: decoded.streamClose.id
440
441
  }, {
441
442
  F: __dxlog_file,
442
- L: 348,
443
+ L: 349,
443
444
  S: this,
444
445
  C: (f, a) => f(...a)
445
446
  });
@@ -452,7 +453,7 @@ var RpcPeer = class {
452
453
  if (this._state !== "CLOSING" && this._state !== "CLOSED") {
453
454
  (0, import_log.log)("replying to bye", void 0, {
454
455
  F: __dxlog_file,
455
- L: 358,
456
+ L: 359,
456
457
  S: this,
457
458
  C: (f, a) => f(...a)
458
459
  });
@@ -468,7 +469,7 @@ var RpcPeer = class {
468
469
  msg
469
470
  }, {
470
471
  F: __dxlog_file,
471
- L: 366,
472
+ L: 367,
472
473
  S: this,
473
474
  C: (f, a) => f(...a)
474
475
  });
@@ -484,7 +485,7 @@ var RpcPeer = class {
484
485
  method
485
486
  }, {
486
487
  F: __dxlog_file,
487
- L: 376,
488
+ L: 377,
488
489
  S: this,
489
490
  C: (f, a) => f(...a)
490
491
  });
@@ -512,7 +513,7 @@ var RpcPeer = class {
512
513
  response = await waiting;
513
514
  (0, import_invariant.invariant)(response.id === id, void 0, {
514
515
  F: __dxlog_file,
515
- L: 404,
516
+ L: 405,
516
517
  S: this,
517
518
  A: [
518
519
  "response.id === id",
@@ -591,7 +592,7 @@ ${stack.getStack()}`;
591
592
  }).catch((err) => {
592
593
  import_log.log.catch(err, void 0, {
593
594
  F: __dxlog_file,
594
- L: 477,
595
+ L: 478,
595
596
  S: this,
596
597
  C: (f, a) => f(...a)
597
598
  });
@@ -605,7 +606,7 @@ ${stack.getStack()}`;
605
606
  type: Object.keys(message)[0]
606
607
  }, {
607
608
  F: __dxlog_file,
608
- L: 485,
609
+ L: 486,
609
610
  S: this,
610
611
  C: (f, a) => f(...a)
611
612
  });
@@ -617,7 +618,7 @@ ${stack.getStack()}`;
617
618
  try {
618
619
  (0, import_invariant.invariant)(typeof req.id === "number", void 0, {
619
620
  F: __dxlog_file,
620
- L: 491,
621
+ L: 492,
621
622
  S: this,
622
623
  A: [
623
624
  "typeof req.id === 'number'",
@@ -626,7 +627,7 @@ ${stack.getStack()}`;
626
627
  });
627
628
  (0, import_invariant.invariant)(req.payload, void 0, {
628
629
  F: __dxlog_file,
629
- L: 492,
630
+ L: 493,
630
631
  S: this,
631
632
  A: [
632
633
  "req.payload",
@@ -635,7 +636,7 @@ ${stack.getStack()}`;
635
636
  });
636
637
  (0, import_invariant.invariant)(req.method, void 0, {
637
638
  F: __dxlog_file,
638
- L: 493,
639
+ L: 494,
639
640
  S: this,
640
641
  A: [
641
642
  "req.method",
@@ -658,7 +659,7 @@ ${stack.getStack()}`;
658
659
  try {
659
660
  (0, import_invariant.invariant)(this._params.streamHandler, "Requests with streaming responses are not supported.", {
660
661
  F: __dxlog_file,
661
- L: 510,
662
+ L: 511,
662
663
  S: this,
663
664
  A: [
664
665
  "this._params.streamHandler",
@@ -667,7 +668,7 @@ ${stack.getStack()}`;
667
668
  });
668
669
  (0, import_invariant.invariant)(typeof req.id === "number", void 0, {
669
670
  F: __dxlog_file,
670
- L: 511,
671
+ L: 512,
671
672
  S: this,
672
673
  A: [
673
674
  "typeof req.id === 'number'",
@@ -676,7 +677,7 @@ ${stack.getStack()}`;
676
677
  });
677
678
  (0, import_invariant.invariant)(req.payload, void 0, {
678
679
  F: __dxlog_file,
679
- L: 512,
680
+ L: 513,
680
681
  S: this,
681
682
  A: [
682
683
  "req.payload",
@@ -685,7 +686,7 @@ ${stack.getStack()}`;
685
686
  });
686
687
  (0, import_invariant.invariant)(req.method, void 0, {
687
688
  F: __dxlog_file,
688
- L: 513,
689
+ L: 514,
689
690
  S: this,
690
691
  A: [
691
692
  "req.method",
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/rpc.ts", "../../../src/errors.ts", "../../../src/service.ts", "../../../src/testing.ts", "../../../src/trace.ts"],
4
- "sourcesContent": ["//\n// Copyright 2021 DXOS.org\n//\n\nimport { asyncTimeout, synchronized, Trigger } from '@dxos/async';\nimport { type Any, Stream, type RequestOptions, type ProtoCodec } from '@dxos/codec-protobuf';\nimport { StackTrace } from '@dxos/debug';\nimport { invariant } from '@dxos/invariant';\nimport { log } from '@dxos/log';\nimport { encodeError, RpcClosedError, RpcNotOpenError, schema } from '@dxos/protocols';\nimport { type Request, type Response, type RpcMessage } from '@dxos/protocols/proto/dxos/rpc';\nimport { exponentialBackoffInterval } from '@dxos/util';\n\nimport { decodeRpcError } from './errors';\n\nconst DEFAULT_TIMEOUT = 3_000;\nconst BYE_SEND_TIMEOUT = 2_000;\n\nconst DEBUG_CALLS = true;\n\ntype MaybePromise<T> = Promise<T> | T;\n\nexport interface RpcPeerOptions {\n port: RpcPort;\n\n /**\n * Time to wait for a response to an RPC call.\n */\n timeout?: number;\n\n callHandler: (method: string, request: Any, options?: RequestOptions) => MaybePromise<Any>;\n streamHandler?: (method: string, request: Any, options?: RequestOptions) => Stream<Any>;\n\n /**\n * Do not require or send handshake messages.\n */\n noHandshake?: boolean;\n\n /**\n * What options get passed to the `callHandler` and `streamHandler`.\n */\n handlerRpcOptions?: RequestOptions;\n}\n\n/**\n * Interface for a transport-agnostic port to send/receive binary messages.\n */\nexport interface RpcPort {\n send: (msg: Uint8Array, timeout?: number) => MaybePromise<void>;\n subscribe: (cb: (msg: Uint8Array) => void) => (() => void) | void;\n}\n\nconst CLOSE_TIMEOUT = 3_000;\n\nexport type CloseOptions = {\n /**\n * Time to wait for the other side to confirm close.\n */\n timeout?: number;\n};\n\nclass PendingRpcRequest {\n constructor(\n public readonly resolve: (response: Response) => void,\n public readonly reject: (error?: Error) => void,\n public readonly stream: boolean,\n ) {}\n}\n\n// NOTE: Lazy so that code that doesn't use indexing doesn't need to load the codec (breaks in workerd).\nlet RpcMessageCodec!: ProtoCodec<RpcMessage>;\nconst getRpcMessageCodec = () => (RpcMessageCodec ??= schema.getCodecForType('dxos.rpc.RpcMessage'));\n\nenum RpcState {\n INITIAL = 'INITIAL',\n\n OPENING = 'OPENING',\n\n OPENED = 'OPENED',\n\n /**\n * Bye message sent, waiting for the other side to close.\n * Not possible to send requests.\n * All pending requests will be rejected.\n */\n CLOSING = 'CLOSING',\n\n /**\n * Connection fully closed.\n * The underlying transport can be disposed.\n */\n CLOSED = 'CLOSED',\n}\n\n/**\n * A remote procedure call peer.\n *\n * Provides a away to make RPC calls and get a response back as a promise.\n * Does not handle encoding/decoding and only works with byte buffers.\n * For type safe approach see `createRpcClient` and `createRpcServer`.\n *\n * Must be connected with another instance on the other side via `send`/`receive` methods.\n * Both sides must be opened before making any RPC calls.\n *\n * Errors inside the handler get serialized and sent to the other side.\n *\n * Inspired by JSON-RPC 2.0 https://www.jsonrpc.org/specification.\n */\nexport class RpcPeer {\n private readonly _params: RpcPeerOptions;\n\n private readonly _outgoingRequests = new Map<number, PendingRpcRequest>();\n private readonly _localStreams = new Map<number, Stream<any>>();\n private readonly _remoteOpenTrigger = new Trigger();\n\n /**\n * Triggered when the peer starts closing.\n */\n private readonly _closingTrigger = new Trigger();\n\n /**\n * Triggered when peer receives a bye message.\n */\n private readonly _byeTrigger = new Trigger();\n\n private _nextId = 0;\n private _state: RpcState = RpcState.INITIAL;\n private _unsubscribeFromPort: (() => void) | undefined = undefined;\n private _clearOpenInterval: (() => void) | undefined = undefined;\n\n constructor(params: RpcPeerOptions) {\n this._params = {\n timeout: undefined,\n streamHandler: undefined,\n noHandshake: false,\n ...params,\n };\n }\n\n /**\n * Open the peer. Required before making any calls.\n *\n * Will block before the other peer calls `open`.\n */\n @synchronized\n async open() {\n if (this._state !== RpcState.INITIAL) {\n return;\n }\n\n this._unsubscribeFromPort = this._params.port.subscribe(async (msg) => {\n try {\n await this._receive(msg);\n } catch (err: any) {\n log.catch(err);\n }\n }) as any;\n\n this._state = RpcState.OPENING;\n\n if (this._params.noHandshake) {\n this._state = RpcState.OPENED;\n this._remoteOpenTrigger.wake();\n return;\n }\n\n log('sending open message', { state: this._state });\n await this._sendMessage({ open: true });\n\n if (this._state !== RpcState.OPENING) {\n return;\n }\n\n // Retry sending.\n this._clearOpenInterval = exponentialBackoffInterval(() => {\n void this._sendMessage({ open: true }).catch((err) => log.warn(err));\n }, 50);\n\n await Promise.race([this._remoteOpenTrigger.wait(), this._closingTrigger.wait()]);\n\n this._clearOpenInterval?.();\n\n if ((this._state as RpcState) !== RpcState.OPENED) {\n // Closed while opening.\n return; // TODO(dmaretskyi): Throw error?\n }\n\n // TODO(burdon): This seems error prone.\n // Send an \"open\" message in case the other peer has missed our first \"open\" message and is still waiting.\n log('sending second open message', { state: this._state });\n await this._sendMessage({ openAck: true });\n }\n\n /**\n * Close the peer.\n * Stop taking or making requests.\n * Will wait for confirmation from the other side.\n * Any responses for RPC calls made before close will be delivered.\n */\n async close({ timeout = CLOSE_TIMEOUT }: CloseOptions = {}) {\n if (this._state === RpcState.CLOSED) {\n return;\n }\n\n this._abortRequests();\n\n if (this._state === RpcState.OPENED && !this._params.noHandshake) {\n try {\n this._state = RpcState.CLOSING;\n await this._sendMessage({ bye: {} }, BYE_SEND_TIMEOUT);\n } catch (err: any) {\n log('error closing peer, sending bye', { err });\n }\n try {\n log('closing waiting on bye');\n await this._byeTrigger.wait({ timeout });\n } catch (err: any) {\n log('error closing peer', { err });\n return;\n }\n }\n\n this._disposeAndClose();\n }\n\n /**\n * Dispose the connection without waiting for the other side.\n */\n async abort() {\n if (this._state === RpcState.CLOSED) {\n return;\n }\n\n this._abortRequests();\n this._disposeAndClose();\n }\n\n private _abortRequests() {\n // Abort open\n this._clearOpenInterval?.();\n this._closingTrigger.wake();\n\n // Abort pending requests\n for (const req of this._outgoingRequests.values()) {\n req.reject(new RpcClosedError());\n }\n this._outgoingRequests.clear();\n }\n\n private _disposeAndClose() {\n this._unsubscribeFromPort?.();\n this._unsubscribeFromPort = undefined;\n this._clearOpenInterval?.();\n this._state = RpcState.CLOSED;\n }\n\n /**\n * Handle incoming message. Should be called as the result of other peer's `send` callback.\n */\n private async _receive(msg: Uint8Array): Promise<void> {\n const decoded = getRpcMessageCodec().decode(msg, { preserveAny: true });\n DEBUG_CALLS && log('received message', { type: Object.keys(decoded)[0] });\n\n if (decoded.request) {\n if (this._state !== RpcState.OPENED && this._state !== RpcState.OPENING) {\n log('received request while closed');\n await this._sendMessage({\n response: {\n id: decoded.request.id,\n error: encodeError(new RpcClosedError()),\n },\n });\n return;\n }\n\n const req = decoded.request;\n if (req.stream) {\n log('stream request', { method: req.method });\n this._callStreamHandler(req, (response) => {\n log('sending stream response', {\n method: req.method,\n response: response.payload?.type_url,\n error: response.error,\n close: response.close,\n });\n\n void this._sendMessage({ response }).catch((err) => {\n log.warn('failed during close', err);\n });\n });\n } else {\n DEBUG_CALLS && log('request', { method: req.method });\n const response = await this._callHandler(req);\n DEBUG_CALLS &&\n log('sending response', {\n method: req.method,\n response: response.payload?.type_url,\n error: response.error,\n });\n await this._sendMessage({ response });\n }\n } else if (decoded.response) {\n if (this._state !== RpcState.OPENED) {\n log('received response while closed');\n return; // Ignore when not open.\n }\n\n const responseId = decoded.response.id;\n invariant(typeof responseId === 'number');\n if (!this._outgoingRequests.has(responseId)) {\n log('received response with invalid id', { responseId });\n return; // Ignore requests with incorrect id.\n }\n\n const item = this._outgoingRequests.get(responseId)!;\n // Delete the request record if no more responses are expected.\n if (!item.stream) {\n this._outgoingRequests.delete(responseId);\n }\n\n DEBUG_CALLS && log('response', { type_url: decoded.response.payload?.type_url });\n item.resolve(decoded.response);\n } else if (decoded.open) {\n log('received open message', { state: this._state });\n if (this._params.noHandshake) {\n return;\n }\n\n await this._sendMessage({ openAck: true });\n } else if (decoded.openAck) {\n log('received openAck message', { state: this._state });\n if (this._params.noHandshake) {\n return;\n }\n\n this._state = RpcState.OPENED;\n this._remoteOpenTrigger.wake();\n } else if (decoded.streamClose) {\n if (this._state !== RpcState.OPENED) {\n log('received stream close while closed');\n return; // Ignore when not open.\n }\n\n log('received stream close', { id: decoded.streamClose.id });\n invariant(typeof decoded.streamClose.id === 'number');\n const stream = this._localStreams.get(decoded.streamClose.id);\n if (!stream) {\n log('no local stream', { id: decoded.streamClose.id });\n return; // Ignore requests with incorrect id.\n }\n\n this._localStreams.delete(decoded.streamClose.id);\n await stream.close();\n } else if (decoded.bye) {\n this._byeTrigger.wake();\n // If we haven't already started closing, close now.\n if (this._state !== RpcState.CLOSING && this._state !== RpcState.CLOSED) {\n log('replying to bye');\n this._state = RpcState.CLOSING;\n await this._sendMessage({ bye: {} });\n\n this._abortRequests();\n this._disposeAndClose();\n }\n } else {\n log.error('received malformed message', { msg });\n throw new Error('Malformed message.');\n }\n }\n\n /**\n * Make RPC call. Will trigger a handler on the other side.\n * Peer should be open before making this call.\n */\n async call(method: string, request: Any, options?: RequestOptions): Promise<Any> {\n DEBUG_CALLS && log('calling', { method });\n throwIfNotOpen(this._state);\n\n let response: Response;\n try {\n // Set-up response listener.\n const id = this._nextId++;\n const responseReceived = new Promise<Response>((resolve, reject) => {\n this._outgoingRequests.set(id, new PendingRpcRequest(resolve, reject, false));\n });\n\n // Send request call.\n const sending = this._sendMessage({\n request: {\n id,\n method,\n payload: request,\n stream: false,\n },\n });\n\n // Wait until send completes or throws an error (or response throws a timeout), the resume waiting.\n const timeout = options?.timeout ?? this._params.timeout;\n const waiting =\n timeout === 0 ? responseReceived : asyncTimeout<any>(responseReceived, timeout ?? DEFAULT_TIMEOUT);\n\n await Promise.race([sending, waiting]);\n response = await waiting;\n invariant(response.id === id);\n } catch (err) {\n if (err instanceof RpcClosedError) {\n // Rethrow the error here to have the correct stack-trace.\n const error = new RpcClosedError();\n error.stack += `\\n\\n info: RPC client was closed at:\\n${err.stack?.split('\\n').slice(1).join('\\n')}`;\n throw error;\n }\n\n throw err;\n }\n\n if (response.payload) {\n return response.payload;\n } else if (response.error) {\n throw decodeRpcError(response.error, method);\n } else {\n throw new Error('Malformed response.');\n }\n }\n\n /**\n * Make RPC call with a streaming response.\n * Will trigger a handler on the other side.\n * Peer should be open before making this call.\n */\n callStream(method: string, request: Any, options?: RequestOptions): Stream<Any> {\n throwIfNotOpen(this._state);\n const id = this._nextId++;\n\n return new Stream(({ ready, next, close }) => {\n const onResponse = (response: Response) => {\n if (response.streamReady) {\n ready();\n } else if (response.close) {\n close();\n } else if (response.error) {\n // TODO(dmaretskyi): Stack trace might be lost because the stream producer function is called asynchronously.\n close(decodeRpcError(response.error, method));\n } else if (response.payload) {\n next(response.payload);\n } else {\n throw new Error('Malformed response.');\n }\n };\n\n const stack = new StackTrace();\n const closeStream = (err?: Error) => {\n if (!err) {\n close();\n } else {\n err.stack += `\\n\\nError happened in the stream at:\\n${stack.getStack()}`;\n close(err);\n }\n };\n\n this._outgoingRequests.set(id, new PendingRpcRequest(onResponse, closeStream, true));\n\n this._sendMessage({\n request: {\n id,\n method,\n payload: request,\n stream: true,\n },\n }).catch((err) => {\n close(err);\n });\n\n return () => {\n this._sendMessage({\n streamClose: { id },\n }).catch((err) => {\n log.catch(err);\n });\n this._outgoingRequests.delete(id);\n };\n });\n }\n\n private async _sendMessage(message: RpcMessage, timeout?: number) {\n DEBUG_CALLS && log('sending message', { type: Object.keys(message)[0] });\n await this._params.port.send(getRpcMessageCodec().encode(message, { preserveAny: true }), timeout);\n }\n\n private async _callHandler(req: Request): Promise<Response> {\n try {\n invariant(typeof req.id === 'number');\n invariant(req.payload);\n invariant(req.method);\n\n const response = await this._params.callHandler(req.method, req.payload, this._params.handlerRpcOptions);\n return {\n id: req.id,\n payload: response,\n };\n } catch (err) {\n return {\n id: req.id,\n error: encodeError(err),\n };\n }\n }\n\n private _callStreamHandler(req: Request, callback: (response: Response) => void) {\n try {\n invariant(this._params.streamHandler, 'Requests with streaming responses are not supported.');\n invariant(typeof req.id === 'number');\n invariant(req.payload);\n invariant(req.method);\n\n const responseStream = this._params.streamHandler(req.method, req.payload, this._params.handlerRpcOptions);\n responseStream.onReady(() => {\n callback({\n id: req.id,\n streamReady: true,\n });\n });\n\n responseStream.subscribe(\n (msg) => {\n callback({\n id: req.id,\n payload: msg,\n });\n },\n (error) => {\n if (error) {\n callback({\n id: req.id,\n error: encodeError(error),\n });\n } else {\n callback({\n id: req.id,\n close: true,\n });\n }\n },\n );\n\n this._localStreams.set(req.id, responseStream);\n } catch (err: any) {\n callback({\n id: req.id,\n error: encodeError(err),\n });\n }\n }\n}\n\nconst throwIfNotOpen = (state: RpcState) => {\n switch (state) {\n case RpcState.OPENED: {\n return;\n }\n case RpcState.INITIAL: {\n throw new RpcNotOpenError();\n }\n case RpcState.CLOSED: {\n throw new RpcClosedError();\n }\n }\n};\n", "//\n// Copyright 2021 DXOS.org\n//\n\nimport { StackTrace } from '@dxos/debug';\nimport { decodeError } from '@dxos/protocols';\nimport { type Error as ErrorResponse } from '@dxos/protocols/proto/dxos/error';\n\nexport const decodeRpcError = (err: ErrorResponse, rpcMethod: string): Error =>\n decodeError(err, {\n appendStack: `\\n at RPC ${rpcMethod} \\n` + new StackTrace().getStack(1),\n });\n", "//\n// Copyright 2021 DXOS.org\n//\n\nimport {\n type EncodingOptions,\n type ServiceDescriptor,\n type ServiceHandler,\n type ServiceProvider,\n} from '@dxos/codec-protobuf';\nimport { invariant } from '@dxos/invariant';\n\nimport { RpcPeer, type RpcPeerOptions } from './rpc';\n\n/**\n * Map of service definitions.\n */\n// TODO(burdon): Rename ServiceMap.\nexport type ServiceBundle<Services> = { [Key in keyof Services]: ServiceDescriptor<Services[Key]> };\n\nexport type ServiceHandlers<Services> = { [ServiceName in keyof Services]: ServiceProvider<Services[ServiceName]> };\n\nexport type ServiceTypesOf<Bundle extends ServiceBundle<any>> =\n Bundle extends ServiceBundle<infer Services> ? Services : never;\n\n/**\n * Groups multiple services together to be served by a single RPC peer.\n */\nexport const createServiceBundle = <Service>(services: ServiceBundle<Service>): ServiceBundle<Service> => services;\n\n/**\n * Type-safe RPC peer.\n */\nexport class ProtoRpcPeer<Service> {\n constructor(\n public readonly rpc: Service,\n private readonly _peer: RpcPeer,\n ) {}\n\n async open() {\n await this._peer.open();\n }\n\n async close() {\n await this._peer.close();\n }\n\n async abort() {\n await this._peer.abort();\n }\n}\n\nexport interface ProtoRpcPeerOptions<Client, Server> extends Omit<RpcPeerOptions, 'callHandler' | 'streamHandler'> {\n /**\n * Services that are expected to be implemented by the counter-space.\n */\n // TODO(burdon): Rename proxy.\n requested?: ServiceBundle<Client>;\n\n /**\n * Services exposed to the counter-space.\n */\n // TODO(burdon): Rename service.\n exposed?: ServiceBundle<Server>;\n\n /**\n * Handlers for the exposed services\n */\n handlers?: ServiceHandlers<Server>;\n\n /**\n * Encoding options passed to the underlying proto codec.\n */\n encodingOptions?: EncodingOptions;\n}\n\n/**\n * Create type-safe RPC peer from a service bundle.\n * Can both handle and issue requests.\n */\n// TODO(burdon): Currently assumes that the proto service name is unique.\n// Support multiple instances services definitions (e.g., halo/space invitations).\nexport const createProtoRpcPeer = <Client = {}, Server = {}>({\n requested,\n exposed,\n handlers,\n encodingOptions,\n ...rest\n}: ProtoRpcPeerOptions<Client, Server>): ProtoRpcPeer<Client> => {\n // Create map of RPCs.\n const exposedRpcs: Record<string, ServiceHandler<any>> = {};\n if (exposed) {\n invariant(handlers);\n for (const serviceName of Object.keys(exposed) as (keyof Server)[]) {\n // Get full service name with the package name without '.' at the beginning.\n const serviceFqn = exposed[serviceName].serviceProto.fullName.slice(1);\n const serviceProvider = handlers[serviceName];\n exposedRpcs[serviceFqn] = exposed[serviceName].createServer(serviceProvider, encodingOptions);\n }\n }\n\n // Create peer.\n const peer = new RpcPeer({\n ...rest,\n\n callHandler: (method, request, options) => {\n const [serviceName, methodName] = parseMethodName(method);\n if (!exposedRpcs[serviceName]) {\n throw new Error(`Service not supported: ${serviceName}`);\n }\n\n return exposedRpcs[serviceName].call(methodName, request, options);\n },\n\n streamHandler: (method, request, options) => {\n const [serviceName, methodName] = parseMethodName(method);\n if (!exposedRpcs[serviceName]) {\n throw new Error(`Service not supported: ${serviceName}`);\n }\n\n return exposedRpcs[serviceName].callStream(methodName, request, options);\n },\n });\n\n const requestedRpcs: Client = {} as Client;\n if (requested) {\n for (const serviceName of Object.keys(requested) as (keyof Client)[]) {\n // Get full service name with the package name without '.' at the beginning.\n const serviceFqn = requested[serviceName].serviceProto.fullName.slice(1);\n\n requestedRpcs[serviceName] = requested[serviceName].createClient(\n {\n call: (method, req, options) => peer.call(`${serviceFqn}.${method}`, req, options),\n callStream: (method, req, options) => peer.callStream(`${serviceFqn}.${method}`, req, options),\n },\n encodingOptions,\n );\n }\n }\n\n return new ProtoRpcPeer(requestedRpcs, peer);\n};\n\nexport const parseMethodName = (method: string): [serviceName: string, methodName: string] => {\n const separator = method.lastIndexOf('.');\n const serviceName = method.slice(0, separator);\n const methodName = method.slice(separator + 1);\n if (serviceName.length === 0 || methodName.length === 0) {\n throw new Error(`Invalid method: ${method}`);\n }\n\n return [serviceName, methodName];\n};\n\n//\n// TODO(burdon): Remove deprecated (only bot factory).\n//\n\n/**\n * Create a type-safe RPC client.\n * @deprecated Use createProtoRpcPeer instead.\n */\nexport const createRpcClient = <S>(\n serviceDef: ServiceDescriptor<S>,\n options: Omit<RpcPeerOptions, 'callHandler'>,\n): ProtoRpcPeer<S> => {\n const peer = new RpcPeer({\n ...options,\n callHandler: () => {\n throw new Error('Requests to client are not supported.');\n },\n });\n\n const client = serviceDef.createClient({\n call: peer.call.bind(peer),\n callStream: peer.callStream.bind(peer),\n });\n\n return new ProtoRpcPeer(client, peer);\n};\n\n/**\n * @deprecated\n */\nexport interface RpcServerOptions<S> extends Omit<RpcPeerOptions, 'callHandler'> {\n service: ServiceDescriptor<S>;\n handlers: S;\n}\n\n/**\n * Create a type-safe RPC server.\n * @deprecated Use createProtoRpcPeer instead.\n */\nexport const createRpcServer = <S>({ service, handlers, ...rest }: RpcServerOptions<S>): RpcPeer => {\n const server = service.createServer(handlers);\n return new RpcPeer({\n ...rest,\n callHandler: server.call.bind(server),\n streamHandler: server.callStream.bind(server),\n });\n};\n\n/**\n * Create type-safe RPC client from a service bundle.\n * @deprecated Use createProtoRpcPeer instead.\n */\nexport const createBundledRpcClient = <S>(\n descriptors: ServiceBundle<S>,\n options: Omit<RpcPeerOptions, 'callHandler' | 'streamHandler'>,\n): ProtoRpcPeer<S> => {\n return createProtoRpcPeer({\n requested: descriptors,\n ...options,\n });\n};\n\n/**\n * @deprecated\n */\nexport interface RpcBundledServerOptions<S> extends Omit<RpcPeerOptions, 'callHandler'> {\n services: ServiceBundle<S>;\n handlers: S;\n}\n\n/**\n * Create type-safe RPC server from a service bundle.\n * @deprecated Use createProtoRpcPeer instead.\n */\n// TODO(burdon): Support late-binding via providers.\nexport const createBundledRpcServer = <S>({ services, handlers, ...rest }: RpcBundledServerOptions<S>): RpcPeer => {\n const rpc: Record<string, ServiceHandler<any>> = {};\n for (const serviceName of Object.keys(services) as (keyof S)[]) {\n // Get full service name with the package name without '.' at the beginning.\n const serviceFqn = services[serviceName].serviceProto.fullName.slice(1);\n rpc[serviceFqn] = services[serviceName].createServer(handlers[serviceName] as any);\n }\n\n return new RpcPeer({\n ...rest,\n\n callHandler: (method, request) => {\n const [serviceName, methodName] = parseMethodName(method);\n if (!rpc[serviceName]) {\n throw new Error(`Service not supported: ${serviceName}`);\n }\n\n return rpc[serviceName].call(methodName, request);\n },\n\n streamHandler: (method, request) => {\n const [serviceName, methodName] = parseMethodName(method);\n if (!rpc[serviceName]) {\n throw new Error(`Service not supported: ${serviceName}`);\n }\n\n return rpc[serviceName].callStream(methodName, request);\n },\n });\n};\n", "//\n// Copyright 2021 DXOS.org\n//\n\nimport { type RpcPort } from './rpc';\n\nexport type CreateLinkedPortsOptions = {\n delay?: number;\n};\n\n/**\n * Create bi-directionally linked ports.\n */\nexport const createLinkedPorts = ({ delay }: CreateLinkedPortsOptions = {}): [RpcPort, RpcPort] => {\n let port1Received: RpcPort['send'] | undefined;\n let port2Received: RpcPort['send'] | undefined;\n\n const send = (handler: RpcPort['send'] | undefined, msg: Uint8Array) => {\n if (delay) {\n setTimeout(() => handler?.(msg), delay);\n } else {\n void handler?.(msg);\n }\n };\n\n const port1: RpcPort = {\n send: (msg) => send(port2Received, msg),\n subscribe: (cb) => {\n port1Received = cb;\n },\n };\n\n const port2: RpcPort = {\n send: (msg) => send(port1Received, msg),\n subscribe: (cb) => {\n port2Received = cb;\n },\n };\n\n return [port1, port2];\n};\n", "//\n// Copyright 2021 DXOS.org\n//\n\nimport { Event } from '@dxos/async';\nimport { MessageTrace } from '@dxos/protocols/proto/dxos/rpc';\n\nimport { type RpcPort } from './rpc';\n\nexport class PortTracer {\n readonly message = new Event<MessageTrace>();\n\n private readonly _port: RpcPort;\n\n constructor(private readonly _wrappedPort: RpcPort) {\n this._port = {\n send: (msg: Uint8Array) => {\n this.message.emit({\n direction: MessageTrace.Direction.OUTGOING,\n data: msg,\n });\n\n return this._wrappedPort.send(msg);\n },\n subscribe: (cb: (msg: Uint8Array) => void) => {\n return this._wrappedPort.subscribe((msg) => {\n this.message.emit({\n direction: MessageTrace.Direction.INCOMING,\n data: msg,\n });\n cb(msg);\n });\n },\n };\n }\n\n public get port() {\n return this._port;\n }\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAIA,mBAAoD;AACpD,4BAAuE;AACvE,mBAA2B;AAC3B,uBAA0B;AAC1B,iBAAoB;AACpB,uBAAqE;AAErE,kBAA2C;ACP3C,IAAAA,gBAA2B;AAC3B,IAAAC,oBAA4B;ACK5B,IAAAC,oBAA0B;AEN1B,IAAAC,gBAAsB;AACtB,iBAA6B;AHGtB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avD,KAAKpE,GAAAA;MAChC;MACAD,WAAW,CAACyH,OAAAA;AACV,eAAO,KAAKG,aAAa5H,UAAU,CAACC,QAAAA;AAClC,eAAKmE,QAAQ2D,KAAK;YAChBC,WAAWC,wBAAaC,UAAUG;YAClCD,MAAMnI;UACR,CAAA;AACAwH,aAAGxH,GAAAA;QACL,CAAA;MACF;IACF;EACF;EAEA,IAAWF,OAAO;AAChB,WAAO,KAAK+H;EACd;AACF;",
4
+ "sourcesContent": ["//\n// Copyright 2021 DXOS.org\n//\n\nimport { asyncTimeout, synchronized, Trigger } from '@dxos/async';\nimport { type Any, Stream, type RequestOptions, type ProtoCodec } from '@dxos/codec-protobuf';\nimport { StackTrace } from '@dxos/debug';\nimport { invariant } from '@dxos/invariant';\nimport { log } from '@dxos/log';\nimport { encodeError, RpcClosedError, RpcNotOpenError } from '@dxos/protocols';\nimport { schema } from '@dxos/protocols/proto';\nimport { type Request, type Response, type RpcMessage } from '@dxos/protocols/proto/dxos/rpc';\nimport { exponentialBackoffInterval } from '@dxos/util';\n\nimport { decodeRpcError } from './errors';\n\nconst DEFAULT_TIMEOUT = 3_000;\nconst BYE_SEND_TIMEOUT = 2_000;\n\nconst DEBUG_CALLS = true;\n\ntype MaybePromise<T> = Promise<T> | T;\n\nexport interface RpcPeerOptions {\n port: RpcPort;\n\n /**\n * Time to wait for a response to an RPC call.\n */\n timeout?: number;\n\n callHandler: (method: string, request: Any, options?: RequestOptions) => MaybePromise<Any>;\n streamHandler?: (method: string, request: Any, options?: RequestOptions) => Stream<Any>;\n\n /**\n * Do not require or send handshake messages.\n */\n noHandshake?: boolean;\n\n /**\n * What options get passed to the `callHandler` and `streamHandler`.\n */\n handlerRpcOptions?: RequestOptions;\n}\n\n/**\n * Interface for a transport-agnostic port to send/receive binary messages.\n */\nexport interface RpcPort {\n send: (msg: Uint8Array, timeout?: number) => MaybePromise<void>;\n subscribe: (cb: (msg: Uint8Array) => void) => (() => void) | void;\n}\n\nconst CLOSE_TIMEOUT = 3_000;\n\nexport type CloseOptions = {\n /**\n * Time to wait for the other side to confirm close.\n */\n timeout?: number;\n};\n\nclass PendingRpcRequest {\n constructor(\n public readonly resolve: (response: Response) => void,\n public readonly reject: (error?: Error) => void,\n public readonly stream: boolean,\n ) {}\n}\n\n// NOTE: Lazy so that code that doesn't use indexing doesn't need to load the codec (breaks in workerd).\nlet RpcMessageCodec!: ProtoCodec<RpcMessage>;\nconst getRpcMessageCodec = () => (RpcMessageCodec ??= schema.getCodecForType('dxos.rpc.RpcMessage'));\n\nenum RpcState {\n INITIAL = 'INITIAL',\n\n OPENING = 'OPENING',\n\n OPENED = 'OPENED',\n\n /**\n * Bye message sent, waiting for the other side to close.\n * Not possible to send requests.\n * All pending requests will be rejected.\n */\n CLOSING = 'CLOSING',\n\n /**\n * Connection fully closed.\n * The underlying transport can be disposed.\n */\n CLOSED = 'CLOSED',\n}\n\n/**\n * A remote procedure call peer.\n *\n * Provides a away to make RPC calls and get a response back as a promise.\n * Does not handle encoding/decoding and only works with byte buffers.\n * For type safe approach see `createRpcClient` and `createRpcServer`.\n *\n * Must be connected with another instance on the other side via `send`/`receive` methods.\n * Both sides must be opened before making any RPC calls.\n *\n * Errors inside the handler get serialized and sent to the other side.\n *\n * Inspired by JSON-RPC 2.0 https://www.jsonrpc.org/specification.\n */\nexport class RpcPeer {\n private readonly _params: RpcPeerOptions;\n\n private readonly _outgoingRequests = new Map<number, PendingRpcRequest>();\n private readonly _localStreams = new Map<number, Stream<any>>();\n private readonly _remoteOpenTrigger = new Trigger();\n\n /**\n * Triggered when the peer starts closing.\n */\n private readonly _closingTrigger = new Trigger();\n\n /**\n * Triggered when peer receives a bye message.\n */\n private readonly _byeTrigger = new Trigger();\n\n private _nextId = 0;\n private _state: RpcState = RpcState.INITIAL;\n private _unsubscribeFromPort: (() => void) | undefined = undefined;\n private _clearOpenInterval: (() => void) | undefined = undefined;\n\n constructor(params: RpcPeerOptions) {\n this._params = {\n timeout: undefined,\n streamHandler: undefined,\n noHandshake: false,\n ...params,\n };\n }\n\n /**\n * Open the peer. Required before making any calls.\n *\n * Will block before the other peer calls `open`.\n */\n @synchronized\n async open() {\n if (this._state !== RpcState.INITIAL) {\n return;\n }\n\n this._unsubscribeFromPort = this._params.port.subscribe(async (msg) => {\n try {\n await this._receive(msg);\n } catch (err: any) {\n log.catch(err);\n }\n }) as any;\n\n this._state = RpcState.OPENING;\n\n if (this._params.noHandshake) {\n this._state = RpcState.OPENED;\n this._remoteOpenTrigger.wake();\n return;\n }\n\n log('sending open message', { state: this._state });\n await this._sendMessage({ open: true });\n\n if (this._state !== RpcState.OPENING) {\n return;\n }\n\n // Retry sending.\n this._clearOpenInterval = exponentialBackoffInterval(() => {\n void this._sendMessage({ open: true }).catch((err) => log.warn(err));\n }, 50);\n\n await Promise.race([this._remoteOpenTrigger.wait(), this._closingTrigger.wait()]);\n\n this._clearOpenInterval?.();\n\n if ((this._state as RpcState) !== RpcState.OPENED) {\n // Closed while opening.\n return; // TODO(dmaretskyi): Throw error?\n }\n\n // TODO(burdon): This seems error prone.\n // Send an \"open\" message in case the other peer has missed our first \"open\" message and is still waiting.\n log('sending second open message', { state: this._state });\n await this._sendMessage({ openAck: true });\n }\n\n /**\n * Close the peer.\n * Stop taking or making requests.\n * Will wait for confirmation from the other side.\n * Any responses for RPC calls made before close will be delivered.\n */\n async close({ timeout = CLOSE_TIMEOUT }: CloseOptions = {}) {\n if (this._state === RpcState.CLOSED) {\n return;\n }\n\n this._abortRequests();\n\n if (this._state === RpcState.OPENED && !this._params.noHandshake) {\n try {\n this._state = RpcState.CLOSING;\n await this._sendMessage({ bye: {} }, BYE_SEND_TIMEOUT);\n } catch (err: any) {\n log('error closing peer, sending bye', { err });\n }\n try {\n log('closing waiting on bye');\n await this._byeTrigger.wait({ timeout });\n } catch (err: any) {\n log('error closing peer', { err });\n return;\n }\n }\n\n this._disposeAndClose();\n }\n\n /**\n * Dispose the connection without waiting for the other side.\n */\n async abort() {\n if (this._state === RpcState.CLOSED) {\n return;\n }\n\n this._abortRequests();\n this._disposeAndClose();\n }\n\n private _abortRequests() {\n // Abort open\n this._clearOpenInterval?.();\n this._closingTrigger.wake();\n\n // Abort pending requests\n for (const req of this._outgoingRequests.values()) {\n req.reject(new RpcClosedError());\n }\n this._outgoingRequests.clear();\n }\n\n private _disposeAndClose() {\n this._unsubscribeFromPort?.();\n this._unsubscribeFromPort = undefined;\n this._clearOpenInterval?.();\n this._state = RpcState.CLOSED;\n }\n\n /**\n * Handle incoming message. Should be called as the result of other peer's `send` callback.\n */\n private async _receive(msg: Uint8Array): Promise<void> {\n const decoded = getRpcMessageCodec().decode(msg, { preserveAny: true });\n DEBUG_CALLS && log('received message', { type: Object.keys(decoded)[0] });\n\n if (decoded.request) {\n if (this._state !== RpcState.OPENED && this._state !== RpcState.OPENING) {\n log('received request while closed');\n await this._sendMessage({\n response: {\n id: decoded.request.id,\n error: encodeError(new RpcClosedError()),\n },\n });\n return;\n }\n\n const req = decoded.request;\n if (req.stream) {\n log('stream request', { method: req.method });\n this._callStreamHandler(req, (response) => {\n log('sending stream response', {\n method: req.method,\n response: response.payload?.type_url,\n error: response.error,\n close: response.close,\n });\n\n void this._sendMessage({ response }).catch((err) => {\n log.warn('failed during close', err);\n });\n });\n } else {\n DEBUG_CALLS && log('request', { method: req.method });\n const response = await this._callHandler(req);\n DEBUG_CALLS &&\n log('sending response', {\n method: req.method,\n response: response.payload?.type_url,\n error: response.error,\n });\n await this._sendMessage({ response });\n }\n } else if (decoded.response) {\n if (this._state !== RpcState.OPENED) {\n log('received response while closed');\n return; // Ignore when not open.\n }\n\n const responseId = decoded.response.id;\n invariant(typeof responseId === 'number');\n if (!this._outgoingRequests.has(responseId)) {\n log('received response with invalid id', { responseId });\n return; // Ignore requests with incorrect id.\n }\n\n const item = this._outgoingRequests.get(responseId)!;\n // Delete the request record if no more responses are expected.\n if (!item.stream) {\n this._outgoingRequests.delete(responseId);\n }\n\n DEBUG_CALLS && log('response', { type_url: decoded.response.payload?.type_url });\n item.resolve(decoded.response);\n } else if (decoded.open) {\n log('received open message', { state: this._state });\n if (this._params.noHandshake) {\n return;\n }\n\n await this._sendMessage({ openAck: true });\n } else if (decoded.openAck) {\n log('received openAck message', { state: this._state });\n if (this._params.noHandshake) {\n return;\n }\n\n this._state = RpcState.OPENED;\n this._remoteOpenTrigger.wake();\n } else if (decoded.streamClose) {\n if (this._state !== RpcState.OPENED) {\n log('received stream close while closed');\n return; // Ignore when not open.\n }\n\n log('received stream close', { id: decoded.streamClose.id });\n invariant(typeof decoded.streamClose.id === 'number');\n const stream = this._localStreams.get(decoded.streamClose.id);\n if (!stream) {\n log('no local stream', { id: decoded.streamClose.id });\n return; // Ignore requests with incorrect id.\n }\n\n this._localStreams.delete(decoded.streamClose.id);\n await stream.close();\n } else if (decoded.bye) {\n this._byeTrigger.wake();\n // If we haven't already started closing, close now.\n if (this._state !== RpcState.CLOSING && this._state !== RpcState.CLOSED) {\n log('replying to bye');\n this._state = RpcState.CLOSING;\n await this._sendMessage({ bye: {} });\n\n this._abortRequests();\n this._disposeAndClose();\n }\n } else {\n log.error('received malformed message', { msg });\n throw new Error('Malformed message.');\n }\n }\n\n /**\n * Make RPC call. Will trigger a handler on the other side.\n * Peer should be open before making this call.\n */\n async call(method: string, request: Any, options?: RequestOptions): Promise<Any> {\n DEBUG_CALLS && log('calling', { method });\n throwIfNotOpen(this._state);\n\n let response: Response;\n try {\n // Set-up response listener.\n const id = this._nextId++;\n const responseReceived = new Promise<Response>((resolve, reject) => {\n this._outgoingRequests.set(id, new PendingRpcRequest(resolve, reject, false));\n });\n\n // Send request call.\n const sending = this._sendMessage({\n request: {\n id,\n method,\n payload: request,\n stream: false,\n },\n });\n\n // Wait until send completes or throws an error (or response throws a timeout), the resume waiting.\n const timeout = options?.timeout ?? this._params.timeout;\n const waiting =\n timeout === 0 ? responseReceived : asyncTimeout<any>(responseReceived, timeout ?? DEFAULT_TIMEOUT);\n\n await Promise.race([sending, waiting]);\n response = await waiting;\n invariant(response.id === id);\n } catch (err) {\n if (err instanceof RpcClosedError) {\n // Rethrow the error here to have the correct stack-trace.\n const error = new RpcClosedError();\n error.stack += `\\n\\n info: RPC client was closed at:\\n${err.stack?.split('\\n').slice(1).join('\\n')}`;\n throw error;\n }\n\n throw err;\n }\n\n if (response.payload) {\n return response.payload;\n } else if (response.error) {\n throw decodeRpcError(response.error, method);\n } else {\n throw new Error('Malformed response.');\n }\n }\n\n /**\n * Make RPC call with a streaming response.\n * Will trigger a handler on the other side.\n * Peer should be open before making this call.\n */\n callStream(method: string, request: Any, options?: RequestOptions): Stream<Any> {\n throwIfNotOpen(this._state);\n const id = this._nextId++;\n\n return new Stream(({ ready, next, close }) => {\n const onResponse = (response: Response) => {\n if (response.streamReady) {\n ready();\n } else if (response.close) {\n close();\n } else if (response.error) {\n // TODO(dmaretskyi): Stack trace might be lost because the stream producer function is called asynchronously.\n close(decodeRpcError(response.error, method));\n } else if (response.payload) {\n next(response.payload);\n } else {\n throw new Error('Malformed response.');\n }\n };\n\n const stack = new StackTrace();\n const closeStream = (err?: Error) => {\n if (!err) {\n close();\n } else {\n err.stack += `\\n\\nError happened in the stream at:\\n${stack.getStack()}`;\n close(err);\n }\n };\n\n this._outgoingRequests.set(id, new PendingRpcRequest(onResponse, closeStream, true));\n\n this._sendMessage({\n request: {\n id,\n method,\n payload: request,\n stream: true,\n },\n }).catch((err) => {\n close(err);\n });\n\n return () => {\n this._sendMessage({\n streamClose: { id },\n }).catch((err) => {\n log.catch(err);\n });\n this._outgoingRequests.delete(id);\n };\n });\n }\n\n private async _sendMessage(message: RpcMessage, timeout?: number) {\n DEBUG_CALLS && log('sending message', { type: Object.keys(message)[0] });\n await this._params.port.send(getRpcMessageCodec().encode(message, { preserveAny: true }), timeout);\n }\n\n private async _callHandler(req: Request): Promise<Response> {\n try {\n invariant(typeof req.id === 'number');\n invariant(req.payload);\n invariant(req.method);\n\n const response = await this._params.callHandler(req.method, req.payload, this._params.handlerRpcOptions);\n return {\n id: req.id,\n payload: response,\n };\n } catch (err) {\n return {\n id: req.id,\n error: encodeError(err),\n };\n }\n }\n\n private _callStreamHandler(req: Request, callback: (response: Response) => void) {\n try {\n invariant(this._params.streamHandler, 'Requests with streaming responses are not supported.');\n invariant(typeof req.id === 'number');\n invariant(req.payload);\n invariant(req.method);\n\n const responseStream = this._params.streamHandler(req.method, req.payload, this._params.handlerRpcOptions);\n responseStream.onReady(() => {\n callback({\n id: req.id,\n streamReady: true,\n });\n });\n\n responseStream.subscribe(\n (msg) => {\n callback({\n id: req.id,\n payload: msg,\n });\n },\n (error) => {\n if (error) {\n callback({\n id: req.id,\n error: encodeError(error),\n });\n } else {\n callback({\n id: req.id,\n close: true,\n });\n }\n },\n );\n\n this._localStreams.set(req.id, responseStream);\n } catch (err: any) {\n callback({\n id: req.id,\n error: encodeError(err),\n });\n }\n }\n}\n\nconst throwIfNotOpen = (state: RpcState) => {\n switch (state) {\n case RpcState.OPENED: {\n return;\n }\n case RpcState.INITIAL: {\n throw new RpcNotOpenError();\n }\n case RpcState.CLOSED: {\n throw new RpcClosedError();\n }\n }\n};\n", "//\n// Copyright 2021 DXOS.org\n//\n\nimport { StackTrace } from '@dxos/debug';\nimport { decodeError } from '@dxos/protocols';\nimport { type Error as ErrorResponse } from '@dxos/protocols/proto/dxos/error';\n\nexport const decodeRpcError = (err: ErrorResponse, rpcMethod: string): Error =>\n decodeError(err, {\n appendStack: `\\n at RPC ${rpcMethod} \\n` + new StackTrace().getStack(1),\n });\n", "//\n// Copyright 2021 DXOS.org\n//\n\nimport {\n type EncodingOptions,\n type ServiceDescriptor,\n type ServiceHandler,\n type ServiceProvider,\n} from '@dxos/codec-protobuf';\nimport { invariant } from '@dxos/invariant';\n\nimport { RpcPeer, type RpcPeerOptions } from './rpc';\n\n/**\n * Map of service definitions.\n */\n// TODO(burdon): Rename ServiceMap.\nexport type ServiceBundle<Services> = { [Key in keyof Services]: ServiceDescriptor<Services[Key]> };\n\nexport type ServiceHandlers<Services> = { [ServiceName in keyof Services]: ServiceProvider<Services[ServiceName]> };\n\nexport type ServiceTypesOf<Bundle extends ServiceBundle<any>> =\n Bundle extends ServiceBundle<infer Services> ? Services : never;\n\n/**\n * Groups multiple services together to be served by a single RPC peer.\n */\nexport const createServiceBundle = <Service>(services: ServiceBundle<Service>): ServiceBundle<Service> => services;\n\n/**\n * Type-safe RPC peer.\n */\nexport class ProtoRpcPeer<Service> {\n constructor(\n public readonly rpc: Service,\n private readonly _peer: RpcPeer,\n ) {}\n\n async open() {\n await this._peer.open();\n }\n\n async close() {\n await this._peer.close();\n }\n\n async abort() {\n await this._peer.abort();\n }\n}\n\nexport interface ProtoRpcPeerOptions<Client, Server> extends Omit<RpcPeerOptions, 'callHandler' | 'streamHandler'> {\n /**\n * Services that are expected to be implemented by the counter-space.\n */\n // TODO(burdon): Rename proxy.\n requested?: ServiceBundle<Client>;\n\n /**\n * Services exposed to the counter-space.\n */\n // TODO(burdon): Rename service.\n exposed?: ServiceBundle<Server>;\n\n /**\n * Handlers for the exposed services\n */\n handlers?: ServiceHandlers<Server>;\n\n /**\n * Encoding options passed to the underlying proto codec.\n */\n encodingOptions?: EncodingOptions;\n}\n\n/**\n * Create type-safe RPC peer from a service bundle.\n * Can both handle and issue requests.\n */\n// TODO(burdon): Currently assumes that the proto service name is unique.\n// Support multiple instances services definitions (e.g., halo/space invitations).\nexport const createProtoRpcPeer = <Client = {}, Server = {}>({\n requested,\n exposed,\n handlers,\n encodingOptions,\n ...rest\n}: ProtoRpcPeerOptions<Client, Server>): ProtoRpcPeer<Client> => {\n // Create map of RPCs.\n const exposedRpcs: Record<string, ServiceHandler<any>> = {};\n if (exposed) {\n invariant(handlers);\n for (const serviceName of Object.keys(exposed) as (keyof Server)[]) {\n // Get full service name with the package name without '.' at the beginning.\n const serviceFqn = exposed[serviceName].serviceProto.fullName.slice(1);\n const serviceProvider = handlers[serviceName];\n exposedRpcs[serviceFqn] = exposed[serviceName].createServer(serviceProvider, encodingOptions);\n }\n }\n\n // Create peer.\n const peer = new RpcPeer({\n ...rest,\n\n callHandler: (method, request, options) => {\n const [serviceName, methodName] = parseMethodName(method);\n if (!exposedRpcs[serviceName]) {\n throw new Error(`Service not supported: ${serviceName}`);\n }\n\n return exposedRpcs[serviceName].call(methodName, request, options);\n },\n\n streamHandler: (method, request, options) => {\n const [serviceName, methodName] = parseMethodName(method);\n if (!exposedRpcs[serviceName]) {\n throw new Error(`Service not supported: ${serviceName}`);\n }\n\n return exposedRpcs[serviceName].callStream(methodName, request, options);\n },\n });\n\n const requestedRpcs: Client = {} as Client;\n if (requested) {\n for (const serviceName of Object.keys(requested) as (keyof Client)[]) {\n // Get full service name with the package name without '.' at the beginning.\n const serviceFqn = requested[serviceName].serviceProto.fullName.slice(1);\n\n requestedRpcs[serviceName] = requested[serviceName].createClient(\n {\n call: (method, req, options) => peer.call(`${serviceFqn}.${method}`, req, options),\n callStream: (method, req, options) => peer.callStream(`${serviceFqn}.${method}`, req, options),\n },\n encodingOptions,\n );\n }\n }\n\n return new ProtoRpcPeer(requestedRpcs, peer);\n};\n\nexport const parseMethodName = (method: string): [serviceName: string, methodName: string] => {\n const separator = method.lastIndexOf('.');\n const serviceName = method.slice(0, separator);\n const methodName = method.slice(separator + 1);\n if (serviceName.length === 0 || methodName.length === 0) {\n throw new Error(`Invalid method: ${method}`);\n }\n\n return [serviceName, methodName];\n};\n\n//\n// TODO(burdon): Remove deprecated (only bot factory).\n//\n\n/**\n * Create a type-safe RPC client.\n * @deprecated Use createProtoRpcPeer instead.\n */\nexport const createRpcClient = <S>(\n serviceDef: ServiceDescriptor<S>,\n options: Omit<RpcPeerOptions, 'callHandler'>,\n): ProtoRpcPeer<S> => {\n const peer = new RpcPeer({\n ...options,\n callHandler: () => {\n throw new Error('Requests to client are not supported.');\n },\n });\n\n const client = serviceDef.createClient({\n call: peer.call.bind(peer),\n callStream: peer.callStream.bind(peer),\n });\n\n return new ProtoRpcPeer(client, peer);\n};\n\n/**\n * @deprecated\n */\nexport interface RpcServerOptions<S> extends Omit<RpcPeerOptions, 'callHandler'> {\n service: ServiceDescriptor<S>;\n handlers: S;\n}\n\n/**\n * Create a type-safe RPC server.\n * @deprecated Use createProtoRpcPeer instead.\n */\nexport const createRpcServer = <S>({ service, handlers, ...rest }: RpcServerOptions<S>): RpcPeer => {\n const server = service.createServer(handlers);\n return new RpcPeer({\n ...rest,\n callHandler: server.call.bind(server),\n streamHandler: server.callStream.bind(server),\n });\n};\n\n/**\n * Create type-safe RPC client from a service bundle.\n * @deprecated Use createProtoRpcPeer instead.\n */\nexport const createBundledRpcClient = <S>(\n descriptors: ServiceBundle<S>,\n options: Omit<RpcPeerOptions, 'callHandler' | 'streamHandler'>,\n): ProtoRpcPeer<S> => {\n return createProtoRpcPeer({\n requested: descriptors,\n ...options,\n });\n};\n\n/**\n * @deprecated\n */\nexport interface RpcBundledServerOptions<S> extends Omit<RpcPeerOptions, 'callHandler'> {\n services: ServiceBundle<S>;\n handlers: S;\n}\n\n/**\n * Create type-safe RPC server from a service bundle.\n * @deprecated Use createProtoRpcPeer instead.\n */\n// TODO(burdon): Support late-binding via providers.\nexport const createBundledRpcServer = <S>({ services, handlers, ...rest }: RpcBundledServerOptions<S>): RpcPeer => {\n const rpc: Record<string, ServiceHandler<any>> = {};\n for (const serviceName of Object.keys(services) as (keyof S)[]) {\n // Get full service name with the package name without '.' at the beginning.\n const serviceFqn = services[serviceName].serviceProto.fullName.slice(1);\n rpc[serviceFqn] = services[serviceName].createServer(handlers[serviceName] as any);\n }\n\n return new RpcPeer({\n ...rest,\n\n callHandler: (method, request) => {\n const [serviceName, methodName] = parseMethodName(method);\n if (!rpc[serviceName]) {\n throw new Error(`Service not supported: ${serviceName}`);\n }\n\n return rpc[serviceName].call(methodName, request);\n },\n\n streamHandler: (method, request) => {\n const [serviceName, methodName] = parseMethodName(method);\n if (!rpc[serviceName]) {\n throw new Error(`Service not supported: ${serviceName}`);\n }\n\n return rpc[serviceName].callStream(methodName, request);\n },\n });\n};\n", "//\n// Copyright 2021 DXOS.org\n//\n\nimport { type RpcPort } from './rpc';\n\nexport type CreateLinkedPortsOptions = {\n delay?: number;\n};\n\n/**\n * Create bi-directionally linked ports.\n */\nexport const createLinkedPorts = ({ delay }: CreateLinkedPortsOptions = {}): [RpcPort, RpcPort] => {\n let port1Received: RpcPort['send'] | undefined;\n let port2Received: RpcPort['send'] | undefined;\n\n const send = (handler: RpcPort['send'] | undefined, msg: Uint8Array) => {\n if (delay) {\n setTimeout(() => handler?.(msg), delay);\n } else {\n void handler?.(msg);\n }\n };\n\n const port1: RpcPort = {\n send: (msg) => send(port2Received, msg),\n subscribe: (cb) => {\n port1Received = cb;\n },\n };\n\n const port2: RpcPort = {\n send: (msg) => send(port1Received, msg),\n subscribe: (cb) => {\n port2Received = cb;\n },\n };\n\n return [port1, port2];\n};\n", "//\n// Copyright 2021 DXOS.org\n//\n\nimport { Event } from '@dxos/async';\nimport { MessageTrace } from '@dxos/protocols/proto/dxos/rpc';\n\nimport { type RpcPort } from './rpc';\n\nexport class PortTracer {\n readonly message = new Event<MessageTrace>();\n\n private readonly _port: RpcPort;\n\n constructor(private readonly _wrappedPort: RpcPort) {\n this._port = {\n send: (msg: Uint8Array) => {\n this.message.emit({\n direction: MessageTrace.Direction.OUTGOING,\n data: msg,\n });\n\n return this._wrappedPort.send(msg);\n },\n subscribe: (cb: (msg: Uint8Array) => void) => {\n return this._wrappedPort.subscribe((msg) => {\n this.message.emit({\n direction: MessageTrace.Direction.INCOMING,\n data: msg,\n });\n cb(msg);\n });\n },\n };\n }\n\n public get port() {\n return this._port;\n }\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAIA,mBAAoD;AACpD,4BAAuE;AACvE,mBAA2B;AAC3B,uBAA0B;AAC1B,iBAAoB;AACpB,uBAA6D;AAC7D,mBAAuB;AAEvB,kBAA2C;ACR3C,IAAAA,gBAA2B;AAC3B,IAAAC,oBAA4B;ACK5B,IAAAC,o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UAClCC,MAAMnI;QACR,CAAA;AAEA,eAAO,KAAK2H,aAAavD,KAAKpE,GAAAA;MAChC;MACAD,WAAW,CAACyH,OAAAA;AACV,eAAO,KAAKG,aAAa5H,UAAU,CAACC,QAAAA;AAClC,eAAKmE,QAAQ2D,KAAK;YAChBC,WAAWC,wBAAaC,UAAUG;YAClCD,MAAMnI;UACR,CAAA;AACAwH,aAAGxH,GAAAA;QACL,CAAA;MACF;IACF;EACF;EAEA,IAAWF,OAAO;AAChB,WAAO,KAAK+H;EACd;AACF;",
6
6
  "names": ["import_debug", "import_protocols", "import_invariant", "import_async", "decodeRpcError", "err", "rpcMethod", "decodeError", "appendStack", "StackTrace", "getStack", "DEFAULT_TIMEOUT", "BYE_SEND_TIMEOUT", "DEBUG_CALLS", "CLOSE_TIMEOUT", "PendingRpcRequest", "constructor", "resolve", "reject", "stream", "RpcMessageCodec", "getRpcMessageCodec", "schema", "getCodecForType", "RpcState", "RpcPeer", "params", "_outgoingRequests", "Map", "_localStreams", "_remoteOpenTrigger", "Trigger", "_nextId", "_state", "_unsubscribeFromPort", "undefined", "_clearOpenInterval", "_params", "timeout", "streamHandler", "noHandshake", "open", "port", "subscribe", "msg", "_receive", "log", "catch", "wake", "state", "_sendMessage", "exponentialBackoffInterval", "warn", "Promise", "race", "wait", "_closingTrigger", "openAck", "close", "_abortRequests", "bye", "_byeTrigger", "_disposeAndClose", "abort", "req", "values", "RpcClosedError", "clear", "decoded", "decode", "preserveAny", "type", "Object", "keys", "request", "response", "id", "error", "encodeError", "method", "_callStreamHandler", "payload", "type_url", "_callHandler", "responseId", "invariant", "has", "item", "get", "delete", "streamClose", "Error", "call", "options", "throwIfNotOpen", "responseReceived", "set", "sending", "waiting", "asyncTimeout", "stack", "split", "slice", "join", "callStream", "Stream", "ready", "next", "onResponse", "streamReady", "closeStream", "message", "send", "encode", "callHandler", "handlerRpcOptions", "callback", "responseStream", "onReady", "synchronized", "RpcNotOpenError", "createServiceBundle", "services", "ProtoRpcPeer", "rpc", "_peer", "createProtoRpcPeer", "requested", "exposed", "handlers", "encodingOptions", "rest", "exposedRpcs", "serviceName", "serviceFqn", "serviceProto", "fullName", "serviceProvider", "createServer", "peer", "methodName", "parseMethodName", "requestedRpcs", "createClient", "separator", "lastIndexOf", "length", "createRpcClient", "serviceDef", "client", "bind", "createRpcServer", "service", "server", "createBundledRpcClient", "descriptors", "createBundledRpcServer", "createLinkedPorts", "delay", "port1Received", "port2Received", "handler", "setTimeout", "port1", "cb", "port2", "PortTracer", "_wrappedPort", "Event", "_port", "emit", "direction", "MessageTrace", "Direction", "OUTGOING", "data", "INCOMING"]
7
7
  }
@@ -1 +1 @@
1
- {"inputs":{"packages/core/mesh/rpc/src/errors.ts":{"bytes":1518,"imports":[{"path":"@dxos/debug","kind":"import-statement","external":true},{"path":"@dxos/protocols","kind":"import-statement","external":true}],"format":"esm"},"packages/core/mesh/rpc/src/rpc.ts":{"bytes":63286,"imports":[{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/codec-protobuf","kind":"import-statement","external":true},{"path":"@dxos/debug","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/protocols","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true},{"path":"packages/core/mesh/rpc/src/errors.ts","kind":"import-statement","original":"./errors"}],"format":"esm"},"packages/core/mesh/rpc/src/service.ts":{"bytes":22633,"imports":[{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"packages/core/mesh/rpc/src/rpc.ts","kind":"import-statement","original":"./rpc"}],"format":"esm"},"packages/core/mesh/rpc/src/testing.ts":{"bytes":3040,"imports":[],"format":"esm"},"packages/core/mesh/rpc/src/trace.ts":{"bytes":3615,"imports":[{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/protocols/proto/dxos/rpc","kind":"import-statement","external":true}],"format":"esm"},"packages/core/mesh/rpc/src/index.ts":{"bytes":822,"imports":[{"path":"packages/core/mesh/rpc/src/rpc.ts","kind":"import-statement","original":"./rpc"},{"path":"packages/core/mesh/rpc/src/errors.ts","kind":"import-statement","original":"./errors"},{"path":"packages/core/mesh/rpc/src/service.ts","kind":"import-statement","original":"./service"},{"path":"packages/core/mesh/rpc/src/testing.ts","kind":"import-statement","original":"./testing"},{"path":"packages/core/mesh/rpc/src/trace.ts","kind":"import-statement","original":"./trace"}],"format":"esm"}},"outputs":{"packages/core/mesh/rpc/dist/lib/node/index.cjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":43125},"packages/core/mesh/rpc/dist/lib/node/index.cjs":{"imports":[{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/codec-protobuf","kind":"import-statement","external":true},{"path":"@dxos/debug","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/protocols","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true},{"path":"@dxos/debug","kind":"import-statement","external":true},{"path":"@dxos/protocols","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/protocols/proto/dxos/rpc","kind":"import-statement","external":true}],"exports":["PortTracer","ProtoRpcPeer","RpcPeer","createBundledRpcClient","createBundledRpcServer","createLinkedPorts","createProtoRpcPeer","createRpcClient","createRpcServer","createServiceBundle","decodeRpcError","parseMethodName"],"entryPoint":"packages/core/mesh/rpc/src/index.ts","inputs":{"packages/core/mesh/rpc/src/rpc.ts":{"bytesInOutput":18113},"packages/core/mesh/rpc/src/errors.ts":{"bytesInOutput":228},"packages/core/mesh/rpc/src/index.ts":{"bytesInOutput":0},"packages/core/mesh/rpc/src/service.ts":{"bytesInOutput":4242},"packages/core/mesh/rpc/src/testing.ts":{"bytesInOutput":528},"packages/core/mesh/rpc/src/trace.ts":{"bytesInOutput":732}},"bytes":24363}}}
1
+ {"inputs":{"packages/core/mesh/rpc/src/errors.ts":{"bytes":1518,"imports":[{"path":"@dxos/debug","kind":"import-statement","external":true},{"path":"@dxos/protocols","kind":"import-statement","external":true}],"format":"esm"},"packages/core/mesh/rpc/src/rpc.ts":{"bytes":63406,"imports":[{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/codec-protobuf","kind":"import-statement","external":true},{"path":"@dxos/debug","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/protocols","kind":"import-statement","external":true},{"path":"@dxos/protocols/proto","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true},{"path":"packages/core/mesh/rpc/src/errors.ts","kind":"import-statement","original":"./errors"}],"format":"esm"},"packages/core/mesh/rpc/src/service.ts":{"bytes":22633,"imports":[{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"packages/core/mesh/rpc/src/rpc.ts","kind":"import-statement","original":"./rpc"}],"format":"esm"},"packages/core/mesh/rpc/src/testing.ts":{"bytes":3040,"imports":[],"format":"esm"},"packages/core/mesh/rpc/src/trace.ts":{"bytes":3615,"imports":[{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/protocols/proto/dxos/rpc","kind":"import-statement","external":true}],"format":"esm"},"packages/core/mesh/rpc/src/index.ts":{"bytes":822,"imports":[{"path":"packages/core/mesh/rpc/src/rpc.ts","kind":"import-statement","original":"./rpc"},{"path":"packages/core/mesh/rpc/src/errors.ts","kind":"import-statement","original":"./errors"},{"path":"packages/core/mesh/rpc/src/service.ts","kind":"import-statement","original":"./service"},{"path":"packages/core/mesh/rpc/src/testing.ts","kind":"import-statement","original":"./testing"},{"path":"packages/core/mesh/rpc/src/trace.ts","kind":"import-statement","original":"./trace"}],"format":"esm"}},"outputs":{"packages/core/mesh/rpc/dist/lib/node/index.cjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":43177},"packages/core/mesh/rpc/dist/lib/node/index.cjs":{"imports":[{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/codec-protobuf","kind":"import-statement","external":true},{"path":"@dxos/debug","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/protocols","kind":"import-statement","external":true},{"path":"@dxos/protocols/proto","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true},{"path":"@dxos/debug","kind":"import-statement","external":true},{"path":"@dxos/protocols","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/protocols/proto/dxos/rpc","kind":"import-statement","external":true}],"exports":["PortTracer","ProtoRpcPeer","RpcPeer","createBundledRpcClient","createBundledRpcServer","createLinkedPorts","createProtoRpcPeer","createRpcClient","createRpcServer","createServiceBundle","decodeRpcError","parseMethodName"],"entryPoint":"packages/core/mesh/rpc/src/index.ts","inputs":{"packages/core/mesh/rpc/src/rpc.ts":{"bytesInOutput":18153},"packages/core/mesh/rpc/src/errors.ts":{"bytesInOutput":228},"packages/core/mesh/rpc/src/index.ts":{"bytesInOutput":0},"packages/core/mesh/rpc/src/service.ts":{"bytesInOutput":4242},"packages/core/mesh/rpc/src/testing.ts":{"bytesInOutput":528},"packages/core/mesh/rpc/src/trace.ts":{"bytesInOutput":732}},"bytes":24403}}}
@@ -1 +1 @@
1
- {"version":3,"file":"rpc.d.ts","sourceRoot":"","sources":["../../../src/rpc.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,KAAK,GAAG,EAAE,MAAM,EAAE,KAAK,cAAc,EAAmB,MAAM,sBAAsB,CAAC;AAe9F,KAAK,YAAY,CAAC,CAAC,IAAI,OAAO,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;AAEtC,MAAM,WAAW,cAAc;IAC7B,IAAI,EAAE,OAAO,CAAC;IAEd;;OAEG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC;IAEj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AkDhF;;;;OAIG;IACH,UAAU,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,GAAG,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,MAAM,CAAC,GAAG,CAAC;YAsDjE,YAAY;YAKZ,YAAY;IAmB1B,OAAO,CAAC,kBAAkB;CA6C3B"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dxos/rpc",
3
- "version": "0.6.9",
3
+ "version": "0.6.10-main.48c066e",
4
4
  "description": "A lightweight, transport-agnostic RPC implementation",
5
5
  "homepage": "https://dxos.org",
6
6
  "bugs": "https://github.com/dxos/dxos/issues",
@@ -24,14 +24,14 @@
24
24
  "src"
25
25
  ],
26
26
  "dependencies": {
27
- "@dxos/debug": "0.6.9",
28
- "@dxos/async": "0.6.9",
29
- "@dxos/invariant": "0.6.9",
30
- "@dxos/codec-protobuf": "0.6.9",
31
- "@dxos/log": "0.6.9",
32
- "@dxos/node-std": "0.6.9",
33
- "@dxos/protocols": "0.6.9",
34
- "@dxos/util": "0.6.9"
27
+ "@dxos/async": "0.6.10-main.48c066e",
28
+ "@dxos/codec-protobuf": "0.6.10-main.48c066e",
29
+ "@dxos/invariant": "0.6.10-main.48c066e",
30
+ "@dxos/debug": "0.6.10-main.48c066e",
31
+ "@dxos/log": "0.6.10-main.48c066e",
32
+ "@dxos/node-std": "0.6.10-main.48c066e",
33
+ "@dxos/protocols": "0.6.10-main.48c066e",
34
+ "@dxos/util": "0.6.10-main.48c066e"
35
35
  },
36
36
  "devDependencies": {
37
37
  "earljs": "~0.1.10",
package/src/rpc.test.ts CHANGED
@@ -7,7 +7,8 @@ import { expect } from 'earljs';
7
7
  import { Trigger, sleep } from '@dxos/async';
8
8
  import { type Any, Stream, type TaggedType } from '@dxos/codec-protobuf';
9
9
  import { log } from '@dxos/log';
10
- import { SystemError, type TYPES } from '@dxos/protocols';
10
+ import { SystemError } from '@dxos/protocols';
11
+ import { type TYPES } from '@dxos/protocols/proto';
11
12
  import { describe, test } from '@dxos/test';
12
13
 
13
14
  import { RpcPeer } from './rpc';
package/src/rpc.ts CHANGED
@@ -7,7 +7,8 @@ import { type Any, Stream, type RequestOptions, type ProtoCodec } from '@dxos/co
7
7
  import { StackTrace } from '@dxos/debug';
8
8
  import { invariant } from '@dxos/invariant';
9
9
  import { log } from '@dxos/log';
10
- import { encodeError, RpcClosedError, RpcNotOpenError, schema } from '@dxos/protocols';
10
+ import { encodeError, RpcClosedError, RpcNotOpenError } from '@dxos/protocols';
11
+ import { schema } from '@dxos/protocols/proto';
11
12
  import { type Request, type Response, type RpcMessage } from '@dxos/protocols/proto/dxos/rpc';
12
13
  import { exponentialBackoffInterval } from '@dxos/util';
13
14
 
@@ -7,7 +7,8 @@ import expectJest from 'expect';
7
7
 
8
8
  import { sleep, latch } from '@dxos/async';
9
9
  import { Stream } from '@dxos/codec-protobuf';
10
- import { SystemError, schema } from '@dxos/protocols';
10
+ import { SystemError } from '@dxos/protocols';
11
+ import { schema } from '@dxos/protocols/proto';
11
12
  import {
12
13
  type TestStreamService,
13
14
  type TestRpcResponse,