starpc 0.0.1 → 0.1.0

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.
Files changed (63) hide show
  1. package/LICENSE +19 -0
  2. package/README.md +122 -27
  3. package/dist/echo/echo.d.ts +59 -0
  4. package/dist/echo/echo.js +85 -0
  5. package/dist/srpc/broadcast-channel.d.ts +16 -0
  6. package/dist/srpc/broadcast-channel.js +60 -0
  7. package/dist/srpc/client-rpc.d.ts +31 -0
  8. package/dist/srpc/client-rpc.js +176 -0
  9. package/dist/srpc/client.d.ts +12 -0
  10. package/dist/srpc/client.js +129 -0
  11. package/dist/srpc/conn.d.ts +14 -0
  12. package/dist/srpc/conn.js +38 -0
  13. package/dist/srpc/index.d.ts +3 -0
  14. package/dist/srpc/index.js +2 -0
  15. package/dist/srpc/packet.d.ts +9 -0
  16. package/dist/srpc/packet.js +89 -0
  17. package/dist/srpc/rpcproto.d.ts +194 -0
  18. package/dist/srpc/rpcproto.js +322 -0
  19. package/dist/srpc/stream.d.ts +5 -0
  20. package/dist/srpc/stream.js +1 -0
  21. package/dist/srpc/ts-proto-rpc.d.ts +7 -0
  22. package/dist/srpc/ts-proto-rpc.js +1 -0
  23. package/dist/srpc/websocket.d.ts +7 -0
  24. package/dist/srpc/websocket.js +18 -0
  25. package/echo/echo.go +1 -0
  26. package/echo/echo.pb.go +165 -0
  27. package/echo/echo.proto +19 -0
  28. package/echo/echo.ts +191 -0
  29. package/echo/echo_srpc.pb.go +333 -0
  30. package/echo/echo_vtproto.pb.go +271 -0
  31. package/echo/server.go +73 -0
  32. package/package.json +71 -9
  33. package/srpc/broadcast-channel.ts +72 -0
  34. package/srpc/client-rpc.go +163 -0
  35. package/srpc/client-rpc.ts +197 -0
  36. package/srpc/client.go +96 -0
  37. package/srpc/client.ts +182 -0
  38. package/srpc/conn.go +7 -0
  39. package/srpc/conn.ts +49 -0
  40. package/srpc/errors.go +20 -0
  41. package/srpc/handler.go +13 -0
  42. package/srpc/index.ts +3 -0
  43. package/srpc/message.go +7 -0
  44. package/srpc/mux.go +76 -0
  45. package/srpc/packet-rw.go +102 -0
  46. package/srpc/packet.go +71 -0
  47. package/srpc/packet.ts +105 -0
  48. package/srpc/rpc-stream.go +76 -0
  49. package/srpc/rpcproto.pb.go +455 -0
  50. package/srpc/rpcproto.proto +46 -0
  51. package/srpc/rpcproto.ts +467 -0
  52. package/srpc/rpcproto_vtproto.pb.go +1094 -0
  53. package/srpc/server-http.go +66 -0
  54. package/srpc/server-pipe.go +26 -0
  55. package/srpc/server-rpc.go +160 -0
  56. package/srpc/server.go +29 -0
  57. package/srpc/stream-pipe.go +86 -0
  58. package/srpc/stream.go +24 -0
  59. package/srpc/stream.ts +11 -0
  60. package/srpc/ts-proto-rpc.ts +29 -0
  61. package/srpc/websocket.go +68 -0
  62. package/srpc/websocket.ts +22 -0
  63. package/srpc/writer.go +9 -0
package/LICENSE ADDED
@@ -0,0 +1,19 @@
1
+ Copyright (c) 2022 Aperture Robotics, LLC.
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy
4
+ of this software and associated documentation files (the "Software"), to deal
5
+ in the Software without restriction, including without limitation the rights
6
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7
+ copies of the Software, and to permit persons to whom the Software is
8
+ furnished to do so, subject to the following conditions:
9
+
10
+ The above copyright notice and this permission notice shall be included in all
11
+ copies or substantial portions of the Software.
12
+
13
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19
+ SOFTWARE.
package/README.md CHANGED
@@ -1,56 +1,151 @@
1
- # Stream RPC (starpc)
1
+ # Stream RPC
2
2
 
3
- **starpc** is a Protobuf RPC implementation leveraging an external Stream
4
- multiplexer and Message framing system like HTTP/2 or Yamux.
3
+ **starpc** is a fully-featured client and server for [Proto3 services] in both
4
+ TypeScript and Go.
5
5
 
6
- Uses any two-way ordered message channel like WebSocket or BroadcastChannel.
6
+ [Proto3 services]: https://developers.google.com/protocol-buffers/docs/proto3#services
7
7
 
8
- Implementation features:
8
+ One of the first libraries to support **client-to-server streaming** RPCs.
9
9
 
10
- - Generates a Go server for proto3 services that does not use reflection.
11
- - Uses the **ts-proto** RPC interface to implement TypeScript clients.
12
- - Each RPC call is mapped to a Stream preventing head-of-line blocking.
10
+ The [rpcproto](./srpc/rpcproto.proto) file contains the entire protocol.
13
11
 
14
- The Go backend provides an interface for forwarding the incoming RPC calls to
15
- the appropriate backend service.
12
+ Leverages the Stream multiplexing of the underlying transport; for example:
13
+ HTTP/2 or [libp2p-mplex] over a WebSocket.
16
14
 
17
- # Usage
15
+ [libp2p-mplex]: https://github.com/libp2p/js-libp2p-mplex
18
16
 
19
- ## Go
17
+ The server side has not yet been implemented in TypeScript.
18
+
19
+ # Examples
20
+
21
+ See the [protobuf-project] template on the "starpc" branch.
22
+
23
+ [protobuf-project]: https://github.com/aperturerobotics/protobuf-project
20
24
 
21
- TODO
25
+ ## Protobuf
22
26
 
23
- Copy the Go project boilerplate files:
27
+ The following examples use the [echo](./echo/echo.proto) protobuf sample.
24
28
 
25
- - Makefile: implements "make gengo" to generate Go code with protoc.
26
- - hack/: downloads & builds the necessary protoc-gen-go tools.
29
+ ```protobuf
30
+ syntax = "proto3";
31
+ package echo;
27
32
 
28
- To generate code for .proto files in your repository:
33
+ // Echoer service returns the given message.
34
+ service Echoer {
35
+ // Echo returns the given message.
36
+ rpc Echo(EchoMsg) returns (EchoMsg);
37
+ // EchoServerStream is an example of a server -> client one-way stream.
38
+ rpc EchoServerStream(EchoMsg) returns (stream EchoMsg);
39
+ // EchoClientStream is an example of client->server one-way stream.
40
+ rpc EchoClientStream(stream EchoMsg) returns (EchoMsg);
41
+ // EchoBidiStream is an example of a two-way stream.
42
+ rpc EchoBidiStream(stream EchoMsg) returns (stream EchoMsg);
43
+ }
29
44
 
30
- - `git add .` - stage all changes first.
31
- - `make gengo` - generate the protobuf files.
45
+ // EchoMsg is the message body for Echo.
46
+ message EchoMsg {
47
+ string body = 1;
48
+ }
49
+ ```
32
50
 
33
- Example of creating & serving a service in Go: (TODO)
51
+ ## Go
52
+
53
+ A basic example can be found in the [e2e test]:
54
+
55
+ ```go
56
+ // construct the server
57
+ echoServer := &echo.EchoServer{}
58
+ mux := srpc.NewMux()
59
+ if err := echo.SRPCRegisterEchoer(mux, echoServer); err != nil {
60
+ t.Fatal(err.Error())
61
+ }
62
+ server := srpc.NewServer(mux)
63
+
64
+ // create an in-memory connection to the server
65
+ openStream := srpc.NewServerPipe(server)
66
+
67
+ // construct the client
68
+ client := srpc.NewClient(openStream)
69
+
70
+ // construct the client rpc interface
71
+ clientEcho := echo.NewSRPCEchoerClient(client)
72
+ ctx := context.Background()
73
+ bodyTxt := "hello world"
74
+ out, err := clientEcho.Echo(ctx, &echo.EchoMsg{
75
+ Body: bodyTxt,
76
+ })
77
+ if err != nil {
78
+ t.Fatal(err.Error())
79
+ }
80
+ if out.GetBody() != bodyTxt {
81
+ t.Fatalf("expected %q got %q", bodyTxt, out.GetBody())
82
+ }
83
+ ```
84
+
85
+ [e2e test]: ./e2e/e2e_test.go
34
86
 
35
87
  ## TypeScript
36
88
 
37
89
  See the ts-proto README to generate the TypeScript for your protobufs.
38
90
 
91
+ Also check out the [integration](./integration/integration.ts) test.
92
+
93
+ Supports any AsyncIterable communication channel with an included implementation
94
+ for WebSockets.
95
+
96
+ This repository uses protowrap, see the [Makefile](./Makefile).
97
+
39
98
  ```typescript
40
- import { RpcClient, WebSocketConn } from 'starpc'
41
- import { DemoServiceClientImpl } from './demo'
99
+ import { WebSocketConn } from '../srpc'
100
+ import { EchoerClientImpl } from '../echo/echo'
42
101
 
43
102
  const ws = new WebSocket('ws://localhost:5000/demo')
44
103
  const channel = new WebSocketConn(ws)
45
- const rpc = new RpcClient(channel)
46
- const demoServiceClient = new DemoServiceClientImpl(rpc)
104
+ const client = channel.buildClient()
105
+ const demoServiceClient = new EchoerClientImpl(client)
106
+
107
+ const result = await demoServiceClient.Echo({
108
+ body: "Hello world!"
109
+ })
110
+ console.log('output', result.body)
47
111
 
48
- const result = await demoServiceClient.DemoEcho({
49
- msg: "Hello world!"
112
+ const clientRequestStream = new Observable<EchoMsg>(subscriber => {
113
+ subscriber.next({body: 'Hello world from streaming request.'})
114
+ subscriber.complete()
50
115
  })
51
- console.log('output', result.msg)
116
+
117
+ console.log('Calling EchoClientStream: client -> server...')
118
+ result = await demoServiceClient.EchoClientStream(clientRequestStream)
119
+ console.log('success: output', result.body)
52
120
  ```
53
121
 
54
122
  `WebSocketConn` uses [js-libp2p-mplex] to multiplex streams over the WebSocket.
55
123
 
56
124
  [js-libp2p-mplex]: https://github.com/libp2p/js-libp2p-mplex
125
+
126
+ # Attribution
127
+
128
+ `protoc-gen-go-starpc` is a heavily modified version of `protoc-gen-go-drpc`.
129
+
130
+ Be sure to check out [drpc] as well: it's compatible with grpc, twirp, and more.
131
+
132
+ [drpc]: https://github.com/storj/drpc
133
+
134
+ Uses [vtprotobuf] to generate Protobuf marshal / unmarshal code.
135
+
136
+ [vtprotobuf]: https://github.com/planetscale/vtprotobuf
137
+
138
+ # Support
139
+
140
+ Starpc is built & supported by Aperture Robotics, LLC.
141
+
142
+ Community contributions and discussion are welcomed!
143
+
144
+ Please open a [GitHub issue] with any questions / issues.
145
+
146
+ [GitHub issue]: https://github.com/aperturerobotics/bifrost/issues/new
147
+
148
+ ... or feel free to reach out on [Matrix Chat] or [Discord].
149
+
150
+ [Discord]: https://discord.gg/KJutMESRsT
151
+ [Matrix Chat]: https://matrix.to/#/#aperturerobotics:matrix.org
@@ -0,0 +1,59 @@
1
+ import Long from 'long';
2
+ import * as _m0 from 'protobufjs/minimal';
3
+ import { Observable } from 'rxjs';
4
+ export declare const protobufPackage = "echo";
5
+ /** EchoMsg is the message body for Echo. */
6
+ export interface EchoMsg {
7
+ body: string;
8
+ }
9
+ export declare const EchoMsg: {
10
+ encode(message: EchoMsg, writer?: _m0.Writer): _m0.Writer;
11
+ decode(input: _m0.Reader | Uint8Array, length?: number): EchoMsg;
12
+ fromJSON(object: any): EchoMsg;
13
+ toJSON(message: EchoMsg): unknown;
14
+ fromPartial<I extends {
15
+ body?: string | undefined;
16
+ } & {
17
+ body?: string | undefined;
18
+ } & Record<Exclude<keyof I, "body">, never>>(object: I): EchoMsg;
19
+ };
20
+ /** Echoer service returns the given message. */
21
+ export interface Echoer {
22
+ /** Echo returns the given message. */
23
+ Echo(request: EchoMsg): Promise<EchoMsg>;
24
+ /** EchoServerStream is an example of a server -> client one-way stream. */
25
+ EchoServerStream(request: EchoMsg): Observable<EchoMsg>;
26
+ /** EchoClientStream is an example of client->server one-way stream. */
27
+ EchoClientStream(request: Observable<EchoMsg>): Promise<EchoMsg>;
28
+ /** EchoBidiStream is an example of a two-way stream. */
29
+ EchoBidiStream(request: Observable<EchoMsg>): Observable<EchoMsg>;
30
+ }
31
+ export declare class EchoerClientImpl implements Echoer {
32
+ private readonly rpc;
33
+ constructor(rpc: Rpc);
34
+ Echo(request: EchoMsg): Promise<EchoMsg>;
35
+ EchoServerStream(request: EchoMsg): Observable<EchoMsg>;
36
+ EchoClientStream(request: Observable<EchoMsg>): Promise<EchoMsg>;
37
+ EchoBidiStream(request: Observable<EchoMsg>): Observable<EchoMsg>;
38
+ }
39
+ interface Rpc {
40
+ request(service: string, method: string, data: Uint8Array): Promise<Uint8Array>;
41
+ clientStreamingRequest(service: string, method: string, data: Observable<Uint8Array>): Promise<Uint8Array>;
42
+ serverStreamingRequest(service: string, method: string, data: Uint8Array): Observable<Uint8Array>;
43
+ bidirectionalStreamingRequest(service: string, method: string, data: Observable<Uint8Array>): Observable<Uint8Array>;
44
+ }
45
+ declare type Builtin = Date | Function | Uint8Array | string | number | boolean | undefined;
46
+ export declare type DeepPartial<T> = T extends Builtin ? T : T extends Long ? string | number | Long : T extends Array<infer U> ? Array<DeepPartial<U>> : T extends ReadonlyArray<infer U> ? ReadonlyArray<DeepPartial<U>> : T extends {
47
+ $case: string;
48
+ } ? {
49
+ [K in keyof Omit<T, '$case'>]?: DeepPartial<T[K]>;
50
+ } & {
51
+ $case: T['$case'];
52
+ } : T extends {} ? {
53
+ [K in keyof T]?: DeepPartial<T[K]>;
54
+ } : Partial<T>;
55
+ declare type KeysOfUnion<T> = T extends T ? keyof T : never;
56
+ export declare type Exact<P, I extends P> = P extends Builtin ? P : P & {
57
+ [K in keyof P]: Exact<P[K], I[K]>;
58
+ } & Record<Exclude<keyof I, KeysOfUnion<P>>, never>;
59
+ export {};
@@ -0,0 +1,85 @@
1
+ /* eslint-disable */
2
+ import Long from 'long';
3
+ import * as _m0 from 'protobufjs/minimal';
4
+ import { map } from 'rxjs/operators';
5
+ export const protobufPackage = 'echo';
6
+ function createBaseEchoMsg() {
7
+ return { body: '' };
8
+ }
9
+ export const EchoMsg = {
10
+ encode(message, writer = _m0.Writer.create()) {
11
+ if (message.body !== '') {
12
+ writer.uint32(10).string(message.body);
13
+ }
14
+ return writer;
15
+ },
16
+ decode(input, length) {
17
+ const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);
18
+ let end = length === undefined ? reader.len : reader.pos + length;
19
+ const message = createBaseEchoMsg();
20
+ while (reader.pos < end) {
21
+ const tag = reader.uint32();
22
+ switch (tag >>> 3) {
23
+ case 1:
24
+ message.body = reader.string();
25
+ break;
26
+ default:
27
+ reader.skipType(tag & 7);
28
+ break;
29
+ }
30
+ }
31
+ return message;
32
+ },
33
+ fromJSON(object) {
34
+ return {
35
+ body: isSet(object.body) ? String(object.body) : '',
36
+ };
37
+ },
38
+ toJSON(message) {
39
+ const obj = {};
40
+ message.body !== undefined && (obj.body = message.body);
41
+ return obj;
42
+ },
43
+ fromPartial(object) {
44
+ const message = createBaseEchoMsg();
45
+ message.body = object.body ?? '';
46
+ return message;
47
+ },
48
+ };
49
+ export class EchoerClientImpl {
50
+ rpc;
51
+ constructor(rpc) {
52
+ this.rpc = rpc;
53
+ this.Echo = this.Echo.bind(this);
54
+ this.EchoServerStream = this.EchoServerStream.bind(this);
55
+ this.EchoClientStream = this.EchoClientStream.bind(this);
56
+ this.EchoBidiStream = this.EchoBidiStream.bind(this);
57
+ }
58
+ Echo(request) {
59
+ const data = EchoMsg.encode(request).finish();
60
+ const promise = this.rpc.request('echo.Echoer', 'Echo', data);
61
+ return promise.then((data) => EchoMsg.decode(new _m0.Reader(data)));
62
+ }
63
+ EchoServerStream(request) {
64
+ const data = EchoMsg.encode(request).finish();
65
+ const result = this.rpc.serverStreamingRequest('echo.Echoer', 'EchoServerStream', data);
66
+ return result.pipe(map((data) => EchoMsg.decode(new _m0.Reader(data))));
67
+ }
68
+ EchoClientStream(request) {
69
+ const data = request.pipe(map((request) => EchoMsg.encode(request).finish()));
70
+ const promise = this.rpc.clientStreamingRequest('echo.Echoer', 'EchoClientStream', data);
71
+ return promise.then((data) => EchoMsg.decode(new _m0.Reader(data)));
72
+ }
73
+ EchoBidiStream(request) {
74
+ const data = request.pipe(map((request) => EchoMsg.encode(request).finish()));
75
+ const result = this.rpc.bidirectionalStreamingRequest('echo.Echoer', 'EchoBidiStream', data);
76
+ return result.pipe(map((data) => EchoMsg.decode(new _m0.Reader(data))));
77
+ }
78
+ }
79
+ if (_m0.util.Long !== Long) {
80
+ _m0.util.Long = Long;
81
+ _m0.configure();
82
+ }
83
+ function isSet(value) {
84
+ return value !== null && value !== undefined;
85
+ }
@@ -0,0 +1,16 @@
1
+ import type { Duplex, Sink } from 'it-stream-types';
2
+ import { Conn } from './conn';
3
+ export declare class BroadcastChannelIterable<T> implements Duplex<T> {
4
+ readonly channel: BroadcastChannel;
5
+ sink: Sink<T>;
6
+ source: AsyncIterable<T>;
7
+ constructor(channel: BroadcastChannel);
8
+ private _createSink;
9
+ private _createSource;
10
+ }
11
+ export declare function newBroadcastChannelIterable<T>(name: string): BroadcastChannelIterable<T>;
12
+ export declare class BroadcastChannelConn extends Conn {
13
+ private channel;
14
+ constructor(channel: BroadcastChannel);
15
+ getBroadcastChannel(): BroadcastChannel;
16
+ }
@@ -0,0 +1,60 @@
1
+ import { Conn } from './conn';
2
+ import { EventIterator } from 'event-iterator';
3
+ import { pipe } from 'it-pipe';
4
+ // BroadcastChannelIterable is a AsyncIterable wrapper for BroadcastChannel.
5
+ export class BroadcastChannelIterable {
6
+ // channel is the broadcast channel
7
+ channel;
8
+ // sink is the sink for incoming messages.
9
+ sink;
10
+ // source is the source for outgoing messages.
11
+ source;
12
+ constructor(channel) {
13
+ this.channel = channel;
14
+ this.sink = this._createSink();
15
+ this.source = this._createSource();
16
+ }
17
+ // _createSink initializes the sink field.
18
+ _createSink() {
19
+ return async (source) => {
20
+ for await (const msg of source) {
21
+ this.channel.postMessage(msg);
22
+ }
23
+ };
24
+ }
25
+ // _createSource initializes the source field.
26
+ _createSource() {
27
+ return new EventIterator((queue) => {
28
+ const messageListener = (ev) => {
29
+ if (ev.data) {
30
+ queue.push(ev.data);
31
+ }
32
+ };
33
+ this.channel.addEventListener('message', messageListener);
34
+ return () => {
35
+ this.channel.removeEventListener('message', messageListener);
36
+ };
37
+ });
38
+ }
39
+ }
40
+ // newBroadcastChannelIterable constructs a BroadcastChannelIterable with a channel name.
41
+ export function newBroadcastChannelIterable(name) {
42
+ const channel = new BroadcastChannel(name);
43
+ return new BroadcastChannelIterable(channel);
44
+ }
45
+ // BroadcastChannelConn implements a connection with a BroadcastChannel.
46
+ //
47
+ // expects Uint8Array objects over the BroadcastChannel.
48
+ export class BroadcastChannelConn extends Conn {
49
+ // channel is the broadcast channel iterable
50
+ channel;
51
+ constructor(channel) {
52
+ super();
53
+ this.channel = new BroadcastChannelIterable(channel);
54
+ pipe(this, this.channel, this);
55
+ }
56
+ // getBroadcastChannel returns the BroadcastChannel.
57
+ getBroadcastChannel() {
58
+ return this.channel.channel;
59
+ }
60
+ }
@@ -0,0 +1,31 @@
1
+ import type { CallData, CallStart, CallStartResp } from './rpcproto';
2
+ import { Packet } from './rpcproto';
3
+ import type { Sink } from 'it-stream-types';
4
+ export declare type DataCb = (data: Uint8Array) => Promise<boolean | void>;
5
+ export declare class ClientRPC {
6
+ sink: Sink<Packet>;
7
+ source: AsyncIterable<Packet>;
8
+ private readonly _source;
9
+ private service;
10
+ private method;
11
+ private dataCb?;
12
+ private started;
13
+ private onStarted?;
14
+ private complete;
15
+ private onComplete?;
16
+ private closed;
17
+ constructor(service: string, method: string, dataCb: DataCb | null);
18
+ waitStarted(): Promise<void>;
19
+ waitComplete(): Promise<void>;
20
+ writeCallStart(data?: Uint8Array): Promise<void>;
21
+ writeCallData(data: Uint8Array, complete?: boolean, error?: string): Promise<void>;
22
+ private writePacket;
23
+ handleMessage(message: Uint8Array): Promise<void>;
24
+ handlePacket(packet: Partial<Packet>): Promise<void>;
25
+ handleCallStart(packet: Partial<CallStart>): Promise<void>;
26
+ handleCallStartResp(packet: Partial<CallStartResp>): Promise<void>;
27
+ handleCallData(packet: Partial<CallData>): Promise<void>;
28
+ close(err?: Error): Promise<void>;
29
+ private _createSink;
30
+ private _createSource;
31
+ }
@@ -0,0 +1,176 @@
1
+ import { Packet } from './rpcproto';
2
+ import { pushable } from 'it-pushable';
3
+ // ClientRPC is an ongoing RPC from the client side.
4
+ export class ClientRPC {
5
+ // sink is the data sink for incoming messages.
6
+ sink;
7
+ // source is the packet source for outgoing Packets.
8
+ source;
9
+ // _source is used to write to the source.
10
+ _source;
11
+ // service is the rpc service
12
+ service;
13
+ // method is the rpc method
14
+ method;
15
+ // dataCb is called with any incoming data.
16
+ dataCb;
17
+ // started is resolved when the request starts.
18
+ started;
19
+ // onStarted is called by the message handler when the request starts.
20
+ onStarted;
21
+ // complete is resolved when the request completes.
22
+ // rejected with an error if the call encountered any error.
23
+ complete;
24
+ // onComplete is called by the message handler when the call completes.
25
+ onComplete;
26
+ // closed indicates close has been called
27
+ closed;
28
+ constructor(service, method, dataCb) {
29
+ this.closed = false;
30
+ this.sink = this._createSink();
31
+ const sourcev = this._createSource();
32
+ this.source = sourcev;
33
+ this._source = sourcev;
34
+ this.service = service;
35
+ this.method = method;
36
+ if (dataCb) {
37
+ this.dataCb = dataCb;
38
+ }
39
+ this.started = new Promise((resolveStarted, rejectStarted) => {
40
+ this.onStarted = (err) => {
41
+ if (err) {
42
+ rejectStarted(err);
43
+ }
44
+ else {
45
+ resolveStarted();
46
+ }
47
+ };
48
+ });
49
+ this.complete = new Promise((resolveComplete, rejectComplete) => {
50
+ this.onComplete = (err) => {
51
+ this.closed = true;
52
+ if (err) {
53
+ rejectComplete(err);
54
+ }
55
+ else {
56
+ resolveComplete();
57
+ }
58
+ };
59
+ });
60
+ }
61
+ // waitStarted returns the started promise.
62
+ waitStarted() {
63
+ return this.started;
64
+ }
65
+ // waitComplete returns the complete promise.
66
+ waitComplete() {
67
+ return this.complete;
68
+ }
69
+ // writeCallStart writes the call start packet.
70
+ async writeCallStart(data) {
71
+ const callStart = {
72
+ rpcService: this.service,
73
+ rpcMethod: this.method,
74
+ data: data || new Uint8Array(0),
75
+ };
76
+ await this.writePacket({
77
+ body: {
78
+ $case: 'callStart',
79
+ callStart,
80
+ },
81
+ });
82
+ }
83
+ // writeCallData writes the call data packet.
84
+ async writeCallData(data, complete, error) {
85
+ const callData = {
86
+ data,
87
+ complete: complete || false,
88
+ error: error || "",
89
+ };
90
+ await this.writePacket({
91
+ body: {
92
+ $case: 'callData',
93
+ callData,
94
+ },
95
+ });
96
+ }
97
+ // writePacket writes a packet to the stream.
98
+ async writePacket(packet) {
99
+ this._source.push(packet);
100
+ }
101
+ // handleMessage handles an incoming encoded Packet.
102
+ //
103
+ // note: may throw an error if the message was unexpected or invalid.
104
+ async handleMessage(message) {
105
+ return this.handlePacket(Packet.decode(message));
106
+ }
107
+ // handlePacket handles an incoming packet.
108
+ async handlePacket(packet) {
109
+ switch (packet?.body?.$case) {
110
+ case 'callStart':
111
+ return this.handleCallStart(packet.body.callStart);
112
+ case 'callStartResp':
113
+ return this.handleCallStartResp(packet.body.callStartResp);
114
+ case 'callData':
115
+ return this.handleCallData(packet.body.callData);
116
+ }
117
+ }
118
+ // handleCallStart handles a CallStart packet.
119
+ async handleCallStart(packet) {
120
+ // we do not implement server -> client RPCs.
121
+ throw new Error(`unexpected server to client rpc: ${packet.rpcService}/${packet.rpcMethod}`);
122
+ }
123
+ // handleCallStartResp handles a CallStartResp packet.
124
+ async handleCallStartResp(packet) {
125
+ if (packet.error && packet.error.length) {
126
+ const err = new Error(packet.error);
127
+ this.onStarted(err);
128
+ this.onComplete(err);
129
+ }
130
+ }
131
+ // handleCallData handles a CallData packet.
132
+ async handleCallData(packet) {
133
+ const data = packet.data;
134
+ if (this.dataCb && data?.length) {
135
+ await this.dataCb(data);
136
+ }
137
+ if (packet.error && packet.error.length) {
138
+ this.onComplete(new Error(packet.error));
139
+ }
140
+ else if (packet.complete) {
141
+ this.onComplete();
142
+ }
143
+ }
144
+ // close closes the active call if not already completed.
145
+ async close(err) {
146
+ if (!this.closed) {
147
+ await this.writeCallData(new Uint8Array(0), true, err ? err.message : "");
148
+ }
149
+ if (!err) {
150
+ err = new Error('call closed');
151
+ }
152
+ this.onComplete(err);
153
+ }
154
+ // _createSink initializes the sink field.
155
+ _createSink() {
156
+ return async (source) => {
157
+ try {
158
+ for await (const msg of source) {
159
+ await this.handlePacket(msg);
160
+ }
161
+ }
162
+ catch (err) {
163
+ this.close(err);
164
+ }
165
+ };
166
+ }
167
+ // _createSource initializes the source field.
168
+ _createSource() {
169
+ return pushable({
170
+ objectMode: true,
171
+ onEnd: (err) => {
172
+ this.onComplete(err);
173
+ },
174
+ });
175
+ }
176
+ }
@@ -0,0 +1,12 @@
1
+ import { Observable } from 'rxjs';
2
+ import type { TsProtoRpc } from './ts-proto-rpc';
3
+ import type { OpenStreamFunc } from './stream';
4
+ export declare class Client implements TsProtoRpc {
5
+ private openConnFn;
6
+ constructor(openConnFn: OpenStreamFunc);
7
+ request(service: string, method: string, data: Uint8Array): Promise<Uint8Array>;
8
+ clientStreamingRequest(service: string, method: string, data: Observable<Uint8Array>): Promise<Uint8Array>;
9
+ serverStreamingRequest(service: string, method: string, data: Uint8Array): Observable<Uint8Array>;
10
+ bidirectionalStreamingRequest(service: string, method: string, data: Observable<Uint8Array>): Observable<Uint8Array>;
11
+ private startRpc;
12
+ }