starpc 0.1.4 → 0.1.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -9,11 +9,11 @@ supported by any of the major RPC libraries.
9
9
 
10
10
  The [rpcproto](./srpc/rpcproto.proto) file describes the protocol.
11
11
 
12
- Uses any Stream multiplexer: defaults to [libp2p-mplex] over a WebSocket.
12
+ Can use any Stream multiplexer: defaults to [libp2p-mplex] over a WebSocket.
13
13
 
14
14
  [libp2p-mplex]: https://github.com/libp2p/js-libp2p-mplex
15
15
 
16
- The server side has not yet been implemented in TypeScript.
16
+ Note: the server has not yet been implemented in TypeScript.
17
17
 
18
18
  # Usage
19
19
 
@@ -85,7 +85,7 @@ export class ClientRPC {
85
85
  const callData = {
86
86
  data,
87
87
  complete: complete || false,
88
- error: error || "",
88
+ error: error || '',
89
89
  };
90
90
  await this.writePacket({
91
91
  body: {
@@ -144,7 +144,7 @@ export class ClientRPC {
144
144
  // close closes the active call if not already completed.
145
145
  async close(err) {
146
146
  if (!this.closed) {
147
- await this.writeCallData(new Uint8Array(0), true, err ? err.message : "");
147
+ await this.writeCallData(new Uint8Array(0), true, err ? err.message : '');
148
148
  }
149
149
  if (!err) {
150
150
  err = new Error('call closed');
@@ -38,7 +38,10 @@ function writeClientStream(call, data) {
38
38
  }
39
39
  // waitCallComplete handles the call complete promise.
40
40
  function waitCallComplete(call, resolve, reject) {
41
- call.waitComplete().catch(reject).finally(() => {
41
+ call
42
+ .waitComplete()
43
+ .catch(reject)
44
+ .finally(() => {
42
45
  // ensure we resolve it if no data was ever returned.
43
46
  resolve(new Uint8Array());
44
47
  });
@@ -86,9 +89,12 @@ export class Client {
86
89
  };
87
90
  this.startRpc(service, method, data, dataCb)
88
91
  .then((call) => {
89
- call.waitComplete().catch((err) => {
92
+ call
93
+ .waitComplete()
94
+ .catch((err) => {
90
95
  pushServerData.throw(err);
91
- }).finally(() => {
96
+ })
97
+ .finally(() => {
92
98
  pushServerData.end();
93
99
  });
94
100
  })
@@ -108,9 +114,12 @@ export class Client {
108
114
  this.startRpc(service, method, null, dataCb)
109
115
  .then((call) => {
110
116
  writeClientStream(call, data);
111
- call.waitComplete().catch((err) => {
117
+ call
118
+ .waitComplete()
119
+ .catch((err) => {
112
120
  pushServerData.throw(err);
113
- }).finally(() => {
121
+ })
122
+ .finally(() => {
114
123
  pushServerData.end();
115
124
  });
116
125
  })
@@ -1,12 +1,16 @@
1
1
  import type { Stream } from '@libp2p/interface-connection';
2
+ import type { StreamMuxerFactory } from '@libp2p/interface-stream-muxer';
2
3
  import type { Duplex } from 'it-stream-types';
3
4
  import type { Stream as SRPCStream } from './stream';
4
5
  import { Client } from './client';
6
+ export interface ConnParams {
7
+ muxerFactory?: StreamMuxerFactory;
8
+ }
5
9
  export declare class Conn implements Duplex<Uint8Array> {
6
10
  private muxer;
7
- constructor();
11
+ constructor(connParams?: ConnParams);
8
12
  get sink(): import("it-stream-types").Sink<Uint8Array, Promise<void>>;
9
- get source(): AsyncIterable<Uint8Array>;
13
+ get source(): import("it-stream-types").Source<Uint8Array>;
10
14
  get streams(): Stream[];
11
15
  buildClient(): Client;
12
16
  openStream(): Promise<SRPCStream>;
package/dist/srpc/conn.js CHANGED
@@ -1,13 +1,15 @@
1
- import { Components } from '@libp2p/components';
2
- import { MplexStreamMuxer } from '@libp2p/mplex';
1
+ import { Mplex } from '@libp2p/mplex';
3
2
  import { Client } from './client';
4
3
  // Conn implements a generic connection with a two-way stream.
5
4
  export class Conn {
6
5
  // muxer is the mplex stream muxer.
7
6
  muxer;
8
- constructor() {
9
- // see https://github.com/libp2p/js-libp2p-mplex/pull/179
10
- this.muxer = new MplexStreamMuxer(new Components(), {
7
+ constructor(connParams) {
8
+ let muxerFactory = connParams?.muxerFactory;
9
+ if (!muxerFactory) {
10
+ muxerFactory = new Mplex();
11
+ }
12
+ this.muxer = muxerFactory.createStreamMuxer({
11
13
  onIncomingStream: this.handleIncomingStream.bind(this),
12
14
  });
13
15
  }
@@ -1,12 +1,15 @@
1
1
  import { Conn } from './conn.js';
2
2
  import { duplex } from 'it-ws';
3
3
  import { pipe } from 'it-pipe';
4
+ import { Mplex } from '@libp2p/mplex';
4
5
  // WebSocketConn implements a connection with a WebSocket.
5
6
  export class WebSocketConn extends Conn {
6
7
  // socket is the web socket
7
8
  socket;
8
9
  constructor(socket) {
9
- super();
10
+ super({
11
+ muxerFactory: new Mplex(),
12
+ });
10
13
  this.socket = socket;
11
14
  const socketDuplex = duplex(socket);
12
15
  pipe(this.source, socketDuplex, this.sink);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "starpc",
3
- "version": "0.1.4",
3
+ "version": "0.1.7",
4
4
  "description": "Streaming protobuf RPC service protocol over any two-way channel.",
5
5
  "license": "MIT",
6
6
  "author": {
@@ -42,10 +42,11 @@
42
42
  "gen": "make genproto",
43
43
  "test": "make test && npm run check",
44
44
  "test:integration": "make integration",
45
+ "integration": "npm run test:integration",
45
46
  "lint": "npm run lint:go && npm run lint:js",
46
47
  "lint:go": "make lint",
47
48
  "lint:js": "eslint -c .eslintrc.js --ext .ts ./{srpc,echo}/**/*.ts",
48
- "postinstall": "patch-package",
49
+ "prepare": "patch-package",
49
50
  "precommit": "npm run format"
50
51
  },
51
52
  "prettier": {
@@ -80,7 +81,7 @@
80
81
  "patch-package": "^6.4.7",
81
82
  "protobufjs": "^6.11.3",
82
83
  "rxjs": "^7.5.5",
83
- "ts-poet": "^4.12.0",
84
+ "ts-poet": "^4.13.0",
84
85
  "ws": "^8.8.0"
85
86
  }
86
87
  }
@@ -0,0 +1,35 @@
1
+ diff --git a/node_modules/ts-poet/build/Import.js b/node_modules/ts-poet/build/Import.js
2
+ index c43569e..a77a1b1 100644
3
+ --- a/node_modules/ts-poet/build/Import.js
4
+ +++ b/node_modules/ts-poet/build/Import.js
5
+ @@ -293,6 +293,14 @@ function emitImports(imports, ourModulePath, importMappings) {
6
+ return '';
7
+ }
8
+ let result = '';
9
+ + // HACK: take the project root import path from $PROJECT
10
+ + const thisProject = process.env.PROJECT;
11
+ + let ourModuleImportPath = path.normalize(ourModulePath);
12
+ + // HACK: if this is an import from our project, set the path accordingly
13
+ + // github.com/aperturerobotics/protobuf-project/example/example -> ./example/example
14
+ + if (thisProject && ourModuleImportPath.startsWith(thisProject)) {
15
+ + ourModuleImportPath = './' + ourModuleImportPath.substr(thisProject.length + 1);
16
+ + }
17
+ const augmentImports = lodash_1.default.groupBy(filterInstances(imports, Augmented), (a) => a.augmented);
18
+ // Group the imports by source module they're imported from
19
+ const importsByModule = lodash_1.default.groupBy(imports.filter((it) => it.source !== undefined &&
20
+ @@ -307,7 +315,14 @@ function emitImports(imports, ourModulePath, importMappings) {
21
+ if (modulePath in importMappings) {
22
+ modulePath = importMappings[modulePath];
23
+ }
24
+ - const importPath = maybeRelativePath(ourModulePath, modulePath);
25
+ + if (thisProject && modulePath.startsWith('./')) {
26
+ + if (!modulePath.substr(2).startsWith(thisProject)) {
27
+ + modulePath = './vendor/' + path.normalize(modulePath);
28
+ + } else {
29
+ + modulePath = './' + modulePath.substr(3 + thisProject.length);
30
+ + }
31
+ + }
32
+ + const importPath = maybeRelativePath(ourModuleImportPath, modulePath);
33
+ // Output star imports individually
34
+ unique(filterInstances(imports, ImportsAll).map((i) => i.symbol)).forEach((symbol) => {
35
+ result += `import * as ${symbol} from '${importPath}';\n`;
@@ -95,11 +95,15 @@ export class ClientRPC {
95
95
  }
96
96
 
97
97
  // writeCallData writes the call data packet.
98
- public async writeCallData(data: Uint8Array, complete?: boolean, error?: string) {
98
+ public async writeCallData(
99
+ data: Uint8Array,
100
+ complete?: boolean,
101
+ error?: string
102
+ ) {
99
103
  const callData: CallData = {
100
104
  data,
101
105
  complete: complete || false,
102
- error: error || "",
106
+ error: error || '',
103
107
  }
104
108
  await this.writePacket({
105
109
  body: {
@@ -136,7 +140,9 @@ export class ClientRPC {
136
140
  // handleCallStart handles a CallStart packet.
137
141
  public async handleCallStart(packet: Partial<CallStart>) {
138
142
  // we do not implement server -> client RPCs.
139
- throw new Error(`unexpected server to client rpc: ${packet.rpcService}/${packet.rpcMethod}`)
143
+ throw new Error(
144
+ `unexpected server to client rpc: ${packet.rpcService}/${packet.rpcMethod}`
145
+ )
140
146
  }
141
147
 
142
148
  // handleCallStartResp handles a CallStartResp packet.
@@ -164,7 +170,7 @@ export class ClientRPC {
164
170
  // close closes the active call if not already completed.
165
171
  public async close(err?: Error) {
166
172
  if (!this.closed) {
167
- await this.writeCallData(new Uint8Array(0), true, err ? err.message : "")
173
+ await this.writeCallData(new Uint8Array(0), true, err ? err.message : '')
168
174
  }
169
175
  if (!err) {
170
176
  err = new Error('call closed')
package/srpc/client.ts CHANGED
@@ -13,9 +13,7 @@ import {
13
13
 
14
14
  // unaryDataCb builds a new unary request data callback.
15
15
  function unaryDataCb(resolve: (data: Uint8Array) => void): DataCb {
16
- return async (
17
- data: Uint8Array
18
- ): Promise<boolean | void> => {
16
+ return async (data: Uint8Array): Promise<boolean | void> => {
19
17
  // resolve the promise
20
18
  resolve(data)
21
19
  // this is the last data we expect.
@@ -53,12 +51,15 @@ function writeClientStream(call: ClientRPC, data: Observable<Uint8Array>) {
53
51
  function waitCallComplete(
54
52
  call: ClientRPC,
55
53
  resolve: (data: Uint8Array) => void,
56
- reject: (err: Error) => void,
54
+ reject: (err: Error) => void
57
55
  ) {
58
- call.waitComplete().catch(reject).finally(() => {
59
- // ensure we resolve it if no data was ever returned.
60
- resolve(new Uint8Array())
61
- })
56
+ call
57
+ .waitComplete()
58
+ .catch(reject)
59
+ .finally(() => {
60
+ // ensure we resolve it if no data was ever returned.
61
+ resolve(new Uint8Array())
62
+ })
62
63
  }
63
64
 
64
65
  // Client implements the ts-proto Rpc interface with the drpcproto protocol.
@@ -112,7 +113,9 @@ export class Client implements TsProtoRpc {
112
113
  ): Observable<Uint8Array> {
113
114
  const pushServerData: Pushable<Uint8Array> = pushable()
114
115
  const serverData = observableFrom(pushServerData)
115
- const dataCb: DataCb = async (data: Uint8Array): Promise<boolean | void> => {
116
+ const dataCb: DataCb = async (
117
+ data: Uint8Array
118
+ ): Promise<boolean | void> => {
116
119
  // push the message to the observable
117
120
  pushServerData.push(data)
118
121
  // expect more messages
@@ -120,11 +123,14 @@ export class Client implements TsProtoRpc {
120
123
  }
121
124
  this.startRpc(service, method, data, dataCb)
122
125
  .then((call) => {
123
- call.waitComplete().catch((err: Error) => {
124
- pushServerData.throw(err)
125
- }).finally(() => {
126
- pushServerData.end()
127
- })
126
+ call
127
+ .waitComplete()
128
+ .catch((err: Error) => {
129
+ pushServerData.throw(err)
130
+ })
131
+ .finally(() => {
132
+ pushServerData.end()
133
+ })
128
134
  })
129
135
  .catch(pushServerData.throw.bind(pushServerData))
130
136
  return serverData
@@ -138,7 +144,9 @@ export class Client implements TsProtoRpc {
138
144
  ): Observable<Uint8Array> {
139
145
  const pushServerData: Pushable<Uint8Array> = pushable()
140
146
  const serverData = observableFrom(pushServerData)
141
- const dataCb: DataCb = async (data: Uint8Array): Promise<boolean | void> => {
147
+ const dataCb: DataCb = async (
148
+ data: Uint8Array
149
+ ): Promise<boolean | void> => {
142
150
  // push the message to the observable
143
151
  pushServerData.push(data)
144
152
  // expect more messages
@@ -147,11 +155,14 @@ export class Client implements TsProtoRpc {
147
155
  this.startRpc(service, method, null, dataCb)
148
156
  .then((call) => {
149
157
  writeClientStream(call, data)
150
- call.waitComplete().catch((err: Error) => {
151
- pushServerData.throw(err)
152
- }).finally(() => {
153
- pushServerData.end()
154
- })
158
+ call
159
+ .waitComplete()
160
+ .catch((err: Error) => {
161
+ pushServerData.throw(err)
162
+ })
163
+ .finally(() => {
164
+ pushServerData.end()
165
+ })
155
166
  })
156
167
  .catch(pushServerData.throw.bind(pushServerData))
157
168
  return serverData
@@ -174,7 +185,7 @@ export class Client implements TsProtoRpc {
174
185
  call,
175
186
  encodePacketSource,
176
187
  prependLengthPrefixTransform(),
177
- conn,
188
+ conn
178
189
  )
179
190
  await call.writeCallStart(data || undefined)
180
191
  return call
package/srpc/conn.ts CHANGED
@@ -1,18 +1,27 @@
1
1
  import type { Stream } from '@libp2p/interface-connection'
2
+ import type { StreamMuxer, StreamMuxerFactory } from '@libp2p/interface-stream-muxer'
2
3
  import type { Duplex } from 'it-stream-types'
3
- import { Components } from '@libp2p/components'
4
- import { MplexStreamMuxer } from '@libp2p/mplex'
4
+ import { Mplex } from '@libp2p/mplex'
5
5
  import type { Stream as SRPCStream } from './stream'
6
6
  import { Client } from './client'
7
7
 
8
+ // ConnParams are parameters that can be passed to the Conn constructor.
9
+ export interface ConnParams {
10
+ // muxerFactory overrides using the default factory (@libp2p/mplex).
11
+ muxerFactory?: StreamMuxerFactory
12
+ }
13
+
8
14
  // Conn implements a generic connection with a two-way stream.
9
15
  export class Conn implements Duplex<Uint8Array> {
10
16
  // muxer is the mplex stream muxer.
11
- private muxer: MplexStreamMuxer
12
-
13
- constructor() {
14
- // see https://github.com/libp2p/js-libp2p-mplex/pull/179
15
- this.muxer = new MplexStreamMuxer(new Components(), {
17
+ private muxer: StreamMuxer
18
+
19
+ constructor(connParams?: ConnParams) {
20
+ let muxerFactory = connParams?.muxerFactory
21
+ if (!muxerFactory) {
22
+ muxerFactory = new Mplex()
23
+ }
24
+ this.muxer = muxerFactory.createStreamMuxer({
16
25
  onIncomingStream: this.handleIncomingStream.bind(this),
17
26
  })
18
27
  }
package/srpc/packet.ts CHANGED
@@ -47,7 +47,11 @@ const uint32LEDecode = (data: Uint8Array) => {
47
47
  uint32LEDecode.bytes = 4
48
48
 
49
49
  // uint32LEEncode adds the length prefix.
50
- const uint32LEEncode = (value: number, target?: Uint8Array, offset?: number) => {
50
+ const uint32LEEncode = (
51
+ value: number,
52
+ target?: Uint8Array,
53
+ offset?: number
54
+ ) => {
51
55
  target = target ?? new Uint8Array(4)
52
56
  const view = new DataView(target.buffer, target.byteOffset, target.byteLength)
53
57
  view.setUint32(offset ?? 0, value, true)
@@ -58,7 +62,7 @@ uint32LEEncode.bytes = 4
58
62
  // prependLengthPrefixTransform adds a length prefix to a message source.
59
63
  // little-endian uint32
60
64
  export function prependLengthPrefixTransform(): Transform<Uint8Array> {
61
- return lengthPrefixEncode({lengthEncoder: uint32LEEncode})
65
+ return lengthPrefixEncode({ lengthEncoder: uint32LEEncode })
62
66
  }
63
67
 
64
68
  // parseLengthPrefixTransform parses the length prefix from a message source.
package/srpc/websocket.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import { Conn } from './conn.js'
2
2
  import { duplex } from 'it-ws'
3
3
  import { pipe } from 'it-pipe'
4
+ import { Mplex } from '@libp2p/mplex'
4
5
  import type WebSocket from 'isomorphic-ws'
5
6
 
6
7
  // WebSocketConn implements a connection with a WebSocket.
@@ -9,7 +10,9 @@ export class WebSocketConn extends Conn {
9
10
  private socket: WebSocket
10
11
 
11
12
  constructor(socket: WebSocket) {
12
- super()
13
+ super({
14
+ muxerFactory: new Mplex(),
15
+ })
13
16
  this.socket = socket
14
17
  const socketDuplex = duplex(socket)
15
18
  pipe(this.source, socketDuplex, this.sink)
@@ -1,23 +0,0 @@
1
- diff --git a/node_modules/@libp2p/mplex/dist/src/index.d.ts b/node_modules/@libp2p/mplex/dist/src/index.d.ts
2
- index 14c5f6e..32d0ee0 100644
3
- --- a/node_modules/@libp2p/mplex/dist/src/index.d.ts
4
- +++ b/node_modules/@libp2p/mplex/dist/src/index.d.ts
5
- @@ -1,6 +1,7 @@
6
- import { Components, Initializable } from '@libp2p/components';
7
- import type { StreamMuxerFactory, StreamMuxerInit } from '@libp2p/interface-stream-muxer';
8
- import { MplexStreamMuxer } from './mplex.js';
9
- +export { MplexStreamMuxer } from './mplex.js';
10
- export interface MplexInit {
11
- /**
12
- * The maximum size of message that can be sent in one go in bytes.
13
- diff --git a/node_modules/@libp2p/mplex/dist/src/index.js b/node_modules/@libp2p/mplex/dist/src/index.js
14
- index 4d692df..7bf592c 100644
15
- --- a/node_modules/@libp2p/mplex/dist/src/index.js
16
- +++ b/node_modules/@libp2p/mplex/dist/src/index.js
17
- @@ -1,5 +1,6 @@
18
- import { Components } from '@libp2p/components';
19
- import { MplexStreamMuxer } from './mplex.js';
20
- +export { MplexStreamMuxer } from './mplex.js';
21
- export class Mplex {
22
- constructor(init = {}) {
23
- this.protocol = '/mplex/6.7.0';
@@ -1,72 +0,0 @@
1
- diff --git a/node_modules/ts-poet/build/Import.js b/node_modules/ts-poet/build/Import.js
2
- index 955a7eb..0ad3a67 100644
3
- --- a/node_modules/ts-poet/build/Import.js
4
- +++ b/node_modules/ts-poet/build/Import.js
5
- @@ -6,6 +6,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.sameModule = exports.maybeRelativePath = exports.emitImports = exports.SideEffect = exports.Augmented = exports.ImportsAll = exports.ImportsDefault = exports.ImportsName = exports.Imported = exports.Implicit = exports.Import = exports.importType = void 0;
7
- const lodash_1 = __importDefault(require("lodash"));
8
- const path_1 = __importDefault(require("path"));
9
- +const path = require("path");
10
- const Node_1 = require("./Node");
11
- const typeImportMarker = '(?:t:)?';
12
- const fileNamePattern = '(?:[a-zA-Z0-9._-]+)';
13
- @@ -274,6 +275,15 @@ function emitImports(imports, ourModulePath, importMappings) {
14
- return '';
15
- }
16
- let result = '';
17
- + const thisProject = process.env.PROJECT;
18
- + let ourModuleImportPath = path.normalize(ourModulePath);
19
- + // HACK: if this is an import from our project, set the path accordingly
20
- + // github.com/aperturerobotics/protobuf-project/example/example -> ./example/example
21
- + if (thisProject && ourModuleImportPath.startsWith(thisProject)) {
22
- + ourModuleImportPath = './' + ourModuleImportPath.substr(thisProject.length + 1);
23
- + }
24
- + // result += `// ourModulePath: ${ourModulePath}\n`;
25
- + // result += `// ourModuleImportPath: ${ourModuleImportPath}\n`;
26
- const augmentImports = lodash_1.default.groupBy(filterInstances(imports, Augmented), (a) => a.augmented);
27
- // Group the imports by source module they're imported from
28
- const importsByModule = lodash_1.default.groupBy(imports.filter((it) => it.source !== undefined &&
29
- @@ -288,7 +298,16 @@ function emitImports(imports, ourModulePath, importMappings) {
30
- if (modulePath in importMappings) {
31
- modulePath = importMappings[modulePath];
32
- }
33
- - const importPath = maybeRelativePath(ourModulePath, modulePath);
34
- + // HACK: if this is an import from a different project, use vendor/ tree.
35
- + if (thisProject && modulePath.startsWith('./')) {
36
- + if (!modulePath.substr(2).startsWith(thisProject)) {
37
- + modulePath = './vendor/' + path.normalize(modulePath);
38
- + } else {
39
- + modulePath = './' + modulePath.substr(3 + thisProject.length);
40
- + }
41
- + }
42
- + // result += `// modulePath: ${modulePath}\n`;
43
- + const importPath = maybeRelativePath(ourModuleImportPath, modulePath);
44
- // Output star imports individually
45
- unique(filterInstances(imports, ImportsAll).map((i) => i.symbol)).forEach((symbol) => {
46
- result += `import * as ${symbol} from '${importPath}';\n`;
47
- @@ -337,17 +356,15 @@ function maybeRelativePath(outputPath, importPath) {
48
- if (!importPath.startsWith('./')) {
49
- return importPath;
50
- }
51
- - // Drop the `./` prefix from the outputPath if it exists.
52
- - const basePath = outputPath.replace(/^.\//, '');
53
- - // Ideally we'd use a path library to do all this.
54
- - const numberOfDirs = basePath.split('').filter((l) => l === '/').length;
55
- - if (numberOfDirs === 0) {
56
- - return importPath;
57
- + importPath = path.normalize(importPath);
58
- + outputPath = path.normalize(outputPath);
59
- + const outputPathDir = path.dirname(outputPath);
60
- + let relativePath = path.relative(outputPathDir, importPath);
61
- + if (!relativePath.startsWith('.')) {
62
- + // ensure the js compiler recognizes this is a relative path.
63
- + relativePath = './' + relativePath;
64
- }
65
- - // Make an array of `..` to get our importPath to the root directory.
66
- - const a = new Array(numberOfDirs);
67
- - const prefix = a.fill('..', 0, numberOfDirs).join('/');
68
- - return prefix + importPath.substring(1);
69
- + return relativePath;
70
- }
71
- exports.maybeRelativePath = maybeRelativePath;
72
- /** Checks if `path1 === path2` despite minor path differences like `./foo` and `foo`. */