@nmtjs/protocol 0.15.0-beta.35 → 0.15.0-beta.37

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 (93) hide show
  1. package/LICENSE.md +1 -1
  2. package/README.md +1 -1
  3. package/dist/client/events.d.ts +15 -0
  4. package/dist/client/events.js +28 -0
  5. package/dist/client/format.d.ts +13 -18
  6. package/dist/client/format.js +0 -1
  7. package/dist/client/index.d.ts +1 -4
  8. package/dist/client/index.js +4 -7
  9. package/dist/client/protocol.d.ts +138 -102
  10. package/dist/client/protocol.js +336 -7
  11. package/dist/client/stream.d.ts +19 -37
  12. package/dist/client/stream.js +46 -138
  13. package/dist/common/binary.d.ts +6 -5
  14. package/dist/common/binary.js +9 -22
  15. package/dist/common/blob.d.ts +8 -15
  16. package/dist/common/blob.js +30 -55
  17. package/dist/common/enums.d.ts +7 -17
  18. package/dist/common/enums.js +14 -34
  19. package/dist/common/index.d.ts +0 -2
  20. package/dist/common/index.js +4 -7
  21. package/dist/common/types.d.ts +24 -5
  22. package/dist/common/types.js +0 -1
  23. package/dist/server/api.d.ts +33 -0
  24. package/dist/server/api.js +7 -0
  25. package/dist/server/connection.d.ts +25 -0
  26. package/dist/server/connection.js +22 -0
  27. package/dist/server/constants.d.ts +4 -0
  28. package/dist/server/constants.js +2 -0
  29. package/dist/server/format.d.ts +23 -17
  30. package/dist/server/format.js +8 -13
  31. package/dist/server/index.d.ts +6 -4
  32. package/dist/server/index.js +11 -9
  33. package/dist/server/injectables.d.ts +14 -0
  34. package/dist/server/injectables.js +22 -0
  35. package/dist/server/protocol.d.ts +114 -88
  36. package/dist/server/protocol.js +354 -5
  37. package/dist/server/registry.d.ts +3 -0
  38. package/dist/server/registry.js +3 -0
  39. package/dist/server/stream.d.ts +0 -5
  40. package/dist/server/stream.js +2 -31
  41. package/dist/server/transport.d.ts +23 -0
  42. package/dist/server/transport.js +3 -0
  43. package/dist/server/types.d.ts +8 -29
  44. package/dist/server/types.js +0 -1
  45. package/dist/server/utils.d.ts +6 -3
  46. package/dist/server/utils.js +4 -5
  47. package/package.json +24 -17
  48. package/dist/client/format.js.map +0 -1
  49. package/dist/client/index.js.map +0 -1
  50. package/dist/client/protocol.js.map +0 -1
  51. package/dist/client/stream.js.map +0 -1
  52. package/dist/client/versions/v1.d.ts +0 -108
  53. package/dist/client/versions/v1.js +0 -128
  54. package/dist/client/versions/v1.js.map +0 -1
  55. package/dist/common/binary.js.map +0 -1
  56. package/dist/common/blob.js.map +0 -1
  57. package/dist/common/constants.d.ts +0 -2
  58. package/dist/common/constants.js +0 -2
  59. package/dist/common/constants.js.map +0 -1
  60. package/dist/common/enums.js.map +0 -1
  61. package/dist/common/index.js.map +0 -1
  62. package/dist/common/types.js.map +0 -1
  63. package/dist/common/utils.d.ts +0 -2
  64. package/dist/common/utils.js +0 -7
  65. package/dist/common/utils.js.map +0 -1
  66. package/dist/server/format.js.map +0 -1
  67. package/dist/server/index.js.map +0 -1
  68. package/dist/server/protocol.js.map +0 -1
  69. package/dist/server/stream.js.map +0 -1
  70. package/dist/server/types.js.map +0 -1
  71. package/dist/server/utils.js.map +0 -1
  72. package/dist/server/versions/v1.d.ts +0 -77
  73. package/dist/server/versions/v1.js +0 -119
  74. package/dist/server/versions/v1.js.map +0 -1
  75. package/src/client/format.ts +0 -49
  76. package/src/client/index.ts +0 -8
  77. package/src/client/protocol.ts +0 -107
  78. package/src/client/stream.ts +0 -222
  79. package/src/client/versions/v1.ts +0 -205
  80. package/src/common/binary.ts +0 -70
  81. package/src/common/blob.ts +0 -94
  82. package/src/common/constants.ts +0 -2
  83. package/src/common/enums.ts +0 -62
  84. package/src/common/index.ts +0 -6
  85. package/src/common/types.ts +0 -18
  86. package/src/common/utils.ts +0 -12
  87. package/src/server/format.ts +0 -117
  88. package/src/server/index.ts +0 -10
  89. package/src/server/protocol.ts +0 -97
  90. package/src/server/stream.ts +0 -72
  91. package/src/server/types.ts +0 -42
  92. package/src/server/utils.ts +0 -22
  93. package/src/server/versions/v1.ts +0 -198
@@ -0,0 +1,22 @@
1
+ import { createFactoryInjectable, createLazyInjectable, Scope, } from '@nmtjs/core';
2
+ const connection = createLazyInjectable(Scope.Connection, 'RPC connection');
3
+ const connectionData = createLazyInjectable(Scope.Connection, "RPC connection's data");
4
+ const connectionAbortSignal = createLazyInjectable(Scope.Connection, 'Connection abort signal');
5
+ const rpcClientAbortSignal = createLazyInjectable(Scope.Call, 'RPC client abort signal');
6
+ const rpcTimeoutSignal = createLazyInjectable(Scope.Call, 'RPC timeout signal');
7
+ const rpcAbortSignal = createFactoryInjectable({
8
+ dependencies: {
9
+ rpcTimeoutSignal,
10
+ rpcClientAbortSignal,
11
+ connectionAbortSignal,
12
+ },
13
+ factory: (ctx) => AbortSignal.any(Object.values(ctx)),
14
+ }, 'Any RPC abort signal');
15
+ export const ProtocolInjectables = {
16
+ connection,
17
+ connectionData,
18
+ connectionAbortSignal,
19
+ rpcClientAbortSignal,
20
+ rpcTimeoutSignal,
21
+ rpcAbortSignal,
22
+ };
@@ -1,7 +1,16 @@
1
- import type { ClientMessageType, ProtocolVersion, ServerMessageType } from '../common/enums.ts';
2
- import type { BaseProtocolError, EncodeRPCStreams } from '../common/types.ts';
3
- import type { MessageContext } from './types.ts';
4
- export declare class ProtocolError extends Error implements BaseProtocolError {
1
+ import type { Callback } from '@nmtjs/common';
2
+ import type { AnyInjectable, Container, Logger } from '@nmtjs/core';
3
+ import type { ProtocolBlob, ProtocolBlobMetadata } from '../common/blob.ts';
4
+ import type { ProtocolRPC } from '../common/types.ts';
5
+ import type { ProtocolApi, ProtocolApiCallOptions } from './api.ts';
6
+ import type { ConnectionOptions } from './connection.ts';
7
+ import type { ProtocolFormat } from './format.ts';
8
+ import type { ProtocolRegistry } from './registry.ts';
9
+ import type { Transport } from './transport.ts';
10
+ import type { ResolveFormatParams } from './utils.ts';
11
+ import { Connection, ConnectionContext } from './connection.ts';
12
+ import { ProtocolClientStream, ProtocolServerStream } from './stream.ts';
13
+ export declare class ProtocolError extends Error {
5
14
  code: string;
6
15
  data?: any;
7
16
  constructor(code: string, message?: string, data?: any);
@@ -13,90 +22,107 @@ export declare class ProtocolError extends Error implements BaseProtocolError {
13
22
  data: any;
14
23
  };
15
24
  }
16
- export declare abstract class ProtocolVersionInterface {
17
- abstract version: ProtocolVersion;
18
- abstract decodeMessage(context: MessageContext, buffer: ArrayBufferView): {
19
- [K in keyof ClientMessageTypePayload]: {
20
- type: K;
21
- } & ClientMessageTypePayload[K];
22
- }[keyof ClientMessageTypePayload];
23
- abstract encodeMessage<T extends ServerMessageType = ServerMessageType>(context: MessageContext, messageType: T, payload: ServerMessageTypePayload[T]): ArrayBufferView;
24
- protected encode(...chunks: (ArrayBuffer | ArrayBufferView)[]): ArrayBufferView;
25
+ export type ProtocolConnectionTransport = {
26
+ send: Transport<any>['send'];
27
+ };
28
+ export declare class ProtocolConnections {
29
+ #private;
30
+ private readonly application;
31
+ constructor(application: {
32
+ logger: Logger;
33
+ registry: ProtocolRegistry;
34
+ format: ProtocolFormat;
35
+ container: Container;
36
+ });
37
+ get(connectionId: string): {
38
+ connection: Connection;
39
+ context: ConnectionContext;
40
+ transport: ProtocolConnectionTransport;
41
+ };
42
+ add<T>(transport: ProtocolConnectionTransport, options: ConnectionOptions<T>, params: ResolveFormatParams): Promise<{
43
+ connection: Connection<T>;
44
+ context: ConnectionContext;
45
+ }>;
46
+ remove(connectionId: string): Promise<void>;
47
+ initialize(connection: Connection): Promise<void>;
25
48
  }
26
- export type ServerMessageTypePayload = {
27
- [ServerMessageType.RpcResponse]: {
28
- callId: number;
29
- result: any;
30
- streams: EncodeRPCStreams;
31
- error: any | null;
32
- };
33
- [ServerMessageType.RpcStreamAbort]: {
34
- callId: number;
35
- reason?: string;
36
- };
37
- [ServerMessageType.RpcStreamEnd]: {
38
- callId: number;
39
- };
40
- [ServerMessageType.RpcStreamChunk]: {
41
- callId: number;
42
- chunk: ArrayBufferView;
43
- };
44
- [ServerMessageType.RpcStreamResponse]: {
45
- callId: number;
46
- };
47
- [ServerMessageType.ClientStreamAbort]: {
48
- streamId: number;
49
- reason?: string;
50
- };
51
- [ServerMessageType.ClientStreamPull]: {
52
- streamId: number;
53
- size: number;
54
- };
55
- [ServerMessageType.ServerStreamAbort]: {
56
- streamId: number;
57
- reason?: string;
58
- };
59
- [ServerMessageType.ServerStreamEnd]: {
60
- streamId: number;
61
- };
62
- [ServerMessageType.ServerStreamPush]: {
63
- streamId: number;
64
- chunk: ArrayBufferView;
65
- };
49
+ export declare class ProtocolClientStreams {
50
+ private readonly connections;
51
+ constructor(connections: ProtocolConnections);
52
+ get(connectionId: string, streamId: number): ProtocolClientStream;
53
+ remove(connectionId: string, streamId: number): void;
54
+ add(connectionId: string, streamId: number, metadata: ProtocolBlobMetadata, read: Callback): ProtocolClientStream;
55
+ push(connectionId: string, streamId: number, chunk: ArrayBuffer): void;
56
+ end(connectionId: string, streamId: number): void;
57
+ abort(connectionId: string, streamId: number, error?: Error): void;
58
+ }
59
+ export declare class ProtocolServerStreams {
60
+ private readonly connections;
61
+ constructor(connections: ProtocolConnections);
62
+ get(connectionId: string, streamId: number): ProtocolServerStream;
63
+ add(connectionId: string, streamId: number, blob: ProtocolBlob): ProtocolServerStream;
64
+ remove(connectionId: string, streamId: number): void;
65
+ pull(connectionId: string, streamId: number): void;
66
+ abort(connectionId: string, streamId: number, error?: Error): void;
67
+ }
68
+ export type ProtocolRPCOptions = {
69
+ signal?: AbortSignal;
70
+ provides?: [AnyInjectable, any][];
71
+ validateMetadata?: ProtocolApiCallOptions['validateMetadata'];
66
72
  };
67
- export type ClientMessageTypePayload = {
68
- [ClientMessageType.Rpc]: {
69
- rpc: {
70
- callId: number;
71
- procedure: string;
72
- payload: unknown;
73
- streams?: EncodeRPCStreams;
73
+ export declare class Protocol {
74
+ #private;
75
+ protected readonly application: {
76
+ logger: Logger;
77
+ format: ProtocolFormat;
78
+ container: Container;
79
+ registry: ProtocolRegistry;
80
+ api: ProtocolApi;
81
+ };
82
+ protected readonly options?: {
83
+ persistConnections?: {
84
+ timeout: number;
74
85
  };
75
- };
76
- [ClientMessageType.RpcPull]: {
77
- callId: number;
78
- };
79
- [ClientMessageType.RpcAbort]: {
80
- callId: number;
81
- reason?: string;
82
- };
83
- [ClientMessageType.ClientStreamPush]: {
84
- streamId: number;
85
- chunk: ArrayBufferView;
86
- };
87
- [ClientMessageType.ClientStreamEnd]: {
88
- streamId: number;
89
- };
90
- [ClientMessageType.ClientStreamAbort]: {
91
- streamId: number;
92
- reason?: string;
93
- };
94
- [ClientMessageType.ServerStreamPull]: {
95
- streamId: number;
96
- size: number;
97
- };
98
- [ClientMessageType.ServerStreamAbort]: {
99
- streamId: number;
100
- reason?: string;
101
- };
102
- };
86
+ } | undefined;
87
+ constructor(application: {
88
+ logger: Logger;
89
+ format: ProtocolFormat;
90
+ container: Container;
91
+ registry: ProtocolRegistry;
92
+ api: ProtocolApi;
93
+ }, options?: {
94
+ persistConnections?: {
95
+ timeout: number;
96
+ };
97
+ } | undefined);
98
+ call(options: ProtocolApiCallOptions): Promise<import("./api.ts").ProtocolApiCallResult>;
99
+ rpc(connectionId: string, rpc: ProtocolRPC, params?: ProtocolRPCOptions): Promise<void>;
100
+ rpcRaw(connectionId: string, buffer: ArrayBuffer, params?: ProtocolRPCOptions): Promise<void>;
101
+ rpcAbort(connectionId: string, callId: number): void;
102
+ rpcAbortRaw(connectionId: string, buffer: ArrayBuffer): void;
103
+ rpcStreamAbort(connectionId: string, callId: number): void;
104
+ rpcStreamAbortRaw(connectionId: string, buffer: ArrayBuffer): void;
105
+ notify(): void;
106
+ addConnection(transport: ProtocolConnectionTransport, options: ConnectionOptions, params: ResolveFormatParams): Promise<{
107
+ connection: Connection<unknown>;
108
+ context: ConnectionContext;
109
+ }>;
110
+ removeConnection(connectionId: string): Promise<void>;
111
+ getConnection(connectionId: string): {
112
+ connection: Connection;
113
+ context: ConnectionContext;
114
+ transport: ProtocolConnectionTransport;
115
+ };
116
+ initializeConnection(connection: Connection): Promise<void>;
117
+ getClientStream(connectionId: string, streamId: number): ProtocolClientStream;
118
+ addClientStream(connectionId: string, streamId: number, metadata: ProtocolBlobMetadata, read: Callback): ProtocolClientStream;
119
+ removeClientStream(connectionId: string, streamId: number): void;
120
+ pushClientStream(connectionId: string, streamId: number, chunk: ArrayBuffer): void;
121
+ endClientStream(connectionId: string, streamId: number): void;
122
+ abortClientStream(connectionId: string, streamId: number, error?: Error): void;
123
+ getServerStream(connectionId: string, streamId: number): ProtocolServerStream;
124
+ addServerStream(connectionId: string, streamId: number, blob: ProtocolBlob): ProtocolServerStream;
125
+ removeServerStream(connectionId: string, streamId: number): void;
126
+ pullServerStream(connectionId: string, streamId: number): void;
127
+ abortServerStream(connectionId: string, streamId: number, error?: Error): void;
128
+ }
@@ -1,4 +1,12 @@
1
- import { concat } from '../common/binary.js';
1
+ import { defer, isAbortError, throwError } from '@nmtjs/common';
2
+ import { Hook, Scope } from '@nmtjs/core';
3
+ import { concat, decodeNumber, encodeNumber } from "../common/binary.js";
4
+ import { ErrorCode, ServerMessageType } from "../common/enums.js";
5
+ import { isIterableResult } from "./api.js";
6
+ import { Connection, ConnectionContext } from "./connection.js";
7
+ import { ProtocolInjectables } from "./injectables.js";
8
+ import { ProtocolClientStream, ProtocolServerStream } from "./stream.js";
9
+ import { getFormat } from "./utils.js";
2
10
  export class ProtocolError extends Error {
3
11
  code;
4
12
  data;
@@ -17,9 +25,350 @@ export class ProtocolError extends Error {
17
25
  return { code: this.code, message: this.message, data: this.data };
18
26
  }
19
27
  }
20
- export class ProtocolVersionInterface {
21
- encode(...chunks) {
22
- return concat(...chunks);
28
+ export class ProtocolConnections {
29
+ application;
30
+ #collection = new Map();
31
+ constructor(application) {
32
+ this.application = application;
33
+ }
34
+ get(connectionId) {
35
+ const connection = this.#collection.get(connectionId);
36
+ if (!connection)
37
+ throwError('Connection not found');
38
+ return connection;
39
+ }
40
+ async add(transport, options, params) {
41
+ const connection = new Connection(options);
42
+ const format = getFormat(this.application.format, params);
43
+ const container = this.application.container.fork(Scope.Connection);
44
+ const context = new ConnectionContext(container, format);
45
+ container.provide(ProtocolInjectables.connection, connection);
46
+ try {
47
+ await this.initialize(connection);
48
+ this.#collection.set(connection.id, { connection, context, transport });
49
+ return { connection, context };
50
+ }
51
+ catch (error) {
52
+ container.dispose().catch((error) => {
53
+ this.application.logger.error({ error, connection }, 'Error during disposing connection');
54
+ });
55
+ throw error;
56
+ }
57
+ }
58
+ async remove(connectionId) {
59
+ const { connection, context } = this.get(connectionId);
60
+ this.application.registry.hooks.call(Hook.OnDisconnect, { concurrent: true }, connection);
61
+ this.#collection.delete(connectionId);
62
+ const { rpcs, serverStreams, clientStreams, rpcStreams, container } = context;
63
+ for (const call of rpcs.values()) {
64
+ call.abort(new Error('Connection closed'));
65
+ }
66
+ for (const stream of clientStreams.values()) {
67
+ stream.destroy(new Error('Connection closed'));
68
+ }
69
+ for (const stream of serverStreams.values()) {
70
+ stream.destroy(new Error('Connection closed'));
71
+ }
72
+ for (const stream of rpcStreams.values()) {
73
+ stream.abort(new Error('Connection closed'));
74
+ }
75
+ try {
76
+ await container.dispose();
77
+ }
78
+ catch (error) {
79
+ this.application.logger.error({ error, connection }, 'Error during closing connection');
80
+ }
81
+ }
82
+ async initialize(connection) {
83
+ await this.application.registry.hooks.call(Hook.OnConnect, { concurrent: false }, connection);
84
+ }
85
+ }
86
+ export class ProtocolClientStreams {
87
+ connections;
88
+ constructor(connections) {
89
+ this.connections = connections;
90
+ }
91
+ get(connectionId, streamId) {
92
+ const { context } = this.connections.get(connectionId);
93
+ const { clientStreams } = context;
94
+ const stream = clientStreams.get(streamId) ?? throwError('Stream not found');
95
+ return stream;
96
+ }
97
+ remove(connectionId, streamId) {
98
+ const { context } = this.connections.get(connectionId);
99
+ const { clientStreams } = context;
100
+ clientStreams.get(streamId) || throwError('Stream not found');
101
+ clientStreams.delete(streamId);
102
+ }
103
+ add(connectionId, streamId, metadata, read) {
104
+ const { context } = this.connections.get(connectionId);
105
+ const { clientStreams } = context;
106
+ const stream = new ProtocolClientStream(streamId, metadata, { read });
107
+ clientStreams.set(streamId, stream);
108
+ return stream;
109
+ }
110
+ push(connectionId, streamId, chunk) {
111
+ const stream = this.get(connectionId, streamId);
112
+ stream.write(Buffer.from(chunk));
113
+ }
114
+ end(connectionId, streamId) {
115
+ const stream = this.get(connectionId, streamId);
116
+ stream.end(null);
117
+ this.remove(connectionId, streamId);
118
+ }
119
+ abort(connectionId, streamId, error = new Error('Aborted')) {
120
+ const stream = this.get(connectionId, streamId);
121
+ stream.destroy(error);
122
+ this.remove(connectionId, streamId);
123
+ }
124
+ }
125
+ export class ProtocolServerStreams {
126
+ connections;
127
+ constructor(connections) {
128
+ this.connections = connections;
129
+ }
130
+ get(connectionId, streamId) {
131
+ const { context } = this.connections.get(connectionId);
132
+ const { serverStreams } = context;
133
+ const stream = serverStreams.get(streamId) ?? throwError('Stream not found');
134
+ return stream;
135
+ }
136
+ add(connectionId, streamId, blob) {
137
+ const { context } = this.connections.get(connectionId);
138
+ const { serverStreams } = context;
139
+ const stream = new ProtocolServerStream(streamId, blob);
140
+ serverStreams.set(streamId, stream);
141
+ return stream;
142
+ }
143
+ remove(connectionId, streamId) {
144
+ const { context } = this.connections.get(connectionId);
145
+ const { serverStreams } = context;
146
+ serverStreams.has(streamId) || throwError('Stream not found');
147
+ serverStreams.delete(streamId);
148
+ }
149
+ pull(connectionId, streamId) {
150
+ const stream = this.get(connectionId, streamId);
151
+ stream.resume();
152
+ }
153
+ abort(connectionId, streamId, error = new Error('Aborted')) {
154
+ const stream = this.get(connectionId, streamId);
155
+ stream.destroy(error);
156
+ this.remove(connectionId, streamId);
157
+ }
158
+ }
159
+ export class Protocol {
160
+ application;
161
+ options;
162
+ #connections;
163
+ #clientStreams;
164
+ #serverStreams;
165
+ constructor(application, options) {
166
+ this.application = application;
167
+ this.options = options;
168
+ this.#connections = new ProtocolConnections(this.application);
169
+ this.#clientStreams = new ProtocolClientStreams(this.#connections);
170
+ this.#serverStreams = new ProtocolServerStreams(this.#connections);
171
+ }
172
+ async call(options) {
173
+ const { container, connection } = options;
174
+ try {
175
+ return await this.application.api.call(options);
176
+ }
177
+ catch (error) {
178
+ if (error instanceof ProtocolError === false) {
179
+ this.application.logger.error({ error, connection }, 'Error during RPC call');
180
+ throw new ProtocolError(ErrorCode.InternalServerError, 'Internal server error');
181
+ }
182
+ throw error;
183
+ }
184
+ finally {
185
+ container.dispose().catch((error) => {
186
+ this.application.logger.error({ error, connection }, "Error during disposing connection's container");
187
+ });
188
+ }
189
+ }
190
+ async rpc(connectionId, rpc, params = {}) {
191
+ const { connection, context, transport } = this.#connections.get(connectionId);
192
+ const { rpcs, format } = context;
193
+ const { callId, procedure, payload } = rpc;
194
+ const abortController = new AbortController();
195
+ const signal = params.signal
196
+ ? AbortSignal.any([params.signal, abortController.signal])
197
+ : abortController.signal;
198
+ rpcs.set(callId, abortController);
199
+ const callIdEncoded = encodeNumber(callId, 'Uint32');
200
+ const container = context.container.fork(Scope.Call);
201
+ if (params.provides) {
202
+ for (const [key, value] of params.provides) {
203
+ container.provide(key, value);
204
+ }
205
+ }
206
+ try {
207
+ const response = await this.call({
208
+ connection,
209
+ container,
210
+ payload,
211
+ procedure,
212
+ signal,
213
+ validateMetadata: params.validateMetadata,
214
+ });
215
+ const responseEncoded = format.encoder.encodeRPC({ callId, result: response.output }, {
216
+ addStream: (blob) => {
217
+ const streamId = context.streamId++;
218
+ const stream = this.#serverStreams.add(connectionId, streamId, blob);
219
+ stream.on('data', (chunk) => {
220
+ stream.pause();
221
+ const buf = Buffer.from(chunk);
222
+ transport.send(connection, ServerMessageType.ServerStreamPush, concat(encodeNumber(streamId, 'Uint32'), buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength)), { callId, streamId });
223
+ });
224
+ stream.on('error', () => {
225
+ transport.send(connection, ServerMessageType.ServerStreamAbort, encodeNumber(streamId, 'Uint32'), { callId, streamId });
226
+ });
227
+ stream.on('end', () => {
228
+ transport.send(connection, ServerMessageType.ServerStreamEnd, encodeNumber(streamId, 'Uint32'), { callId, streamId });
229
+ });
230
+ return stream;
231
+ },
232
+ getStream: (id) => {
233
+ return this.#serverStreams.get(connectionId, id);
234
+ },
235
+ });
236
+ if (isIterableResult(response)) {
237
+ transport.send(connection, ServerMessageType.RpcStreamResponse, responseEncoded, { callId });
238
+ try {
239
+ const controller = new AbortController();
240
+ context.rpcStreams.set(callId, controller);
241
+ const iterable = typeof response.iterable === 'function'
242
+ ? await response.iterable(controller.signal)
243
+ : response.iterable;
244
+ try {
245
+ for await (const chunk of iterable) {
246
+ controller.signal.throwIfAborted();
247
+ const chunkEncoded = format.encoder.encode(chunk);
248
+ transport.send(connection, ServerMessageType.RpcStreamChunk, concat(callIdEncoded, chunkEncoded), { callId });
249
+ }
250
+ transport.send(connection, ServerMessageType.RpcStreamEnd, callIdEncoded, { callId });
251
+ }
252
+ catch (error) {
253
+ // do not re-throw AbortError errors, they are expected
254
+ if (!isAbortError(error)) {
255
+ throw error;
256
+ }
257
+ }
258
+ }
259
+ catch (error) {
260
+ this.application.logger.error(error);
261
+ transport.send(connection, ServerMessageType.RpcStreamAbort, callIdEncoded, { callId });
262
+ }
263
+ finally {
264
+ context.rpcStreams.delete(callId);
265
+ response.onFinish && defer(response.onFinish);
266
+ }
267
+ }
268
+ else {
269
+ transport.send(connection, ServerMessageType.RpcResponse, responseEncoded, { callId });
270
+ }
271
+ }
272
+ catch (error) {
273
+ const payload = format.encoder.encodeRPC({ callId, error }, {
274
+ addStream() {
275
+ throwError('Cannot handle stream for error response');
276
+ },
277
+ getStream() {
278
+ throwError('Cannot handle stream for error response');
279
+ },
280
+ });
281
+ transport.send(connection, ServerMessageType.RpcResponse, payload, {
282
+ error,
283
+ callId,
284
+ });
285
+ }
286
+ finally {
287
+ rpcs.delete(callId);
288
+ container.dispose().catch((error) => {
289
+ this.application.logger.error({ error, connection }, 'Error during disposing connection');
290
+ });
291
+ }
292
+ }
293
+ async rpcRaw(connectionId, buffer, params = {}) {
294
+ const { connection, context, transport } = this.#connections.get(connectionId);
295
+ const { format } = context;
296
+ const rpc = format.decoder.decodeRPC(buffer, {
297
+ addStream: (streamId, callId, metadata) => {
298
+ return this.#clientStreams.add(connectionId, streamId, metadata, (size) => {
299
+ transport.send(connection, ServerMessageType.ClientStreamPull, concat(encodeNumber(streamId, 'Uint32'), encodeNumber(size, 'Uint32')), { callId, streamId });
300
+ });
301
+ },
302
+ getStream: (id) => {
303
+ return this.#clientStreams.get(connectionId, id);
304
+ },
305
+ });
306
+ return await this.rpc(connectionId, rpc, params);
307
+ }
308
+ rpcAbort(connectionId, callId) {
309
+ const { context } = this.#connections.get(connectionId);
310
+ const call = context.rpcs.get(callId) ?? throwError('Call not found');
311
+ call.abort();
312
+ }
313
+ rpcAbortRaw(connectionId, buffer) {
314
+ const callId = decodeNumber(buffer, 'Uint32');
315
+ return this.rpcAbort(connectionId, callId);
316
+ }
317
+ rpcStreamAbort(connectionId, callId) {
318
+ const { context } = this.#connections.get(connectionId);
319
+ const ab = context.rpcStreams.get(callId) ?? throwError('Call stream not found');
320
+ ab.abort();
321
+ }
322
+ rpcStreamAbortRaw(connectionId, buffer) {
323
+ const callId = decodeNumber(buffer, 'Uint32');
324
+ return this.rpcStreamAbort(connectionId, callId);
325
+ }
326
+ notify() {
327
+ throw Error('Unimplemented');
328
+ }
329
+ addConnection(transport, options, params) {
330
+ return this.#connections.add(transport, options, params);
331
+ }
332
+ removeConnection(connectionId) {
333
+ return this.#connections.remove(connectionId);
334
+ }
335
+ getConnection(connectionId) {
336
+ return this.#connections.get(connectionId);
337
+ }
338
+ initializeConnection(connection) {
339
+ return this.#connections.initialize(connection);
340
+ }
341
+ getClientStream(connectionId, streamId) {
342
+ return this.#clientStreams.get(connectionId, streamId);
343
+ }
344
+ addClientStream(connectionId, streamId, metadata, read) {
345
+ return this.#clientStreams.add(connectionId, streamId, metadata, read);
346
+ }
347
+ removeClientStream(connectionId, streamId) {
348
+ return this.#clientStreams.remove(connectionId, streamId);
349
+ }
350
+ pushClientStream(connectionId, streamId, chunk) {
351
+ return this.#clientStreams.push(connectionId, streamId, chunk);
352
+ }
353
+ endClientStream(connectionId, streamId) {
354
+ return this.#clientStreams.end(connectionId, streamId);
355
+ }
356
+ abortClientStream(connectionId, streamId, error) {
357
+ return this.#clientStreams.abort(connectionId, streamId, error);
358
+ }
359
+ getServerStream(connectionId, streamId) {
360
+ return this.#serverStreams.get(connectionId, streamId);
361
+ }
362
+ addServerStream(connectionId, streamId, blob) {
363
+ return this.#serverStreams.add(connectionId, streamId, blob);
364
+ }
365
+ removeServerStream(connectionId, streamId) {
366
+ return this.#serverStreams.remove(connectionId, streamId);
367
+ }
368
+ pullServerStream(connectionId, streamId) {
369
+ return this.#serverStreams.pull(connectionId, streamId);
370
+ }
371
+ abortServerStream(connectionId, streamId, error) {
372
+ return this.#serverStreams.abort(connectionId, streamId, error);
23
373
  }
24
374
  }
25
- //# sourceMappingURL=protocol.js.map
@@ -0,0 +1,3 @@
1
+ import { Registry } from '@nmtjs/core';
2
+ export declare class ProtocolRegistry extends Registry {
3
+ }
@@ -0,0 +1,3 @@
1
+ import { Registry } from '@nmtjs/core';
2
+ export class ProtocolRegistry extends Registry {
3
+ }
@@ -2,17 +2,12 @@ import type { ReadableOptions } from 'node:stream';
2
2
  import { PassThrough } from 'node:stream';
3
3
  import type { ProtocolBlob, ProtocolBlobMetadata } from '../common/blob.ts';
4
4
  export declare class ProtocolClientStream extends PassThrough {
5
- #private;
6
5
  readonly id: number;
7
6
  readonly metadata: ProtocolBlobMetadata;
8
7
  constructor(id: number, metadata: ProtocolBlobMetadata, options?: ReadableOptions);
9
- _read(size: number): void;
10
8
  }
11
9
  export declare class ProtocolServerStream extends PassThrough {
12
- #private;
13
10
  readonly id: number;
14
11
  readonly metadata: ProtocolBlobMetadata;
15
12
  constructor(id: number, blob: ProtocolBlob);
16
- resume(): this;
17
- destroy(error?: Error | null): this;
18
13
  }