@celljs/grpc 0.0.0-stage → 4.3.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.
- package/README.md +123 -2
- package/cell.yml +12 -0
- package/esm/node/call/async-queue.d.ts +31 -0
- package/esm/node/call/async-queue.js +80 -0
- package/esm/node/call/async-queue.js.map +1 -0
- package/esm/node/call/grpc-status.d.ts +33 -0
- package/esm/node/call/grpc-status.js +48 -0
- package/esm/node/call/grpc-status.js.map +1 -0
- package/esm/node/call/message-framer.d.ts +24 -0
- package/esm/node/call/message-framer.js +105 -0
- package/esm/node/call/message-framer.js.map +1 -0
- package/esm/node/call/metadata.d.ts +15 -0
- package/esm/node/call/metadata.js +81 -0
- package/esm/node/call/metadata.js.map +1 -0
- package/esm/node/client/grpc-channel.d.ts +64 -0
- package/esm/node/client/grpc-channel.js +285 -0
- package/esm/node/client/grpc-channel.js.map +1 -0
- package/esm/node/codec/proto-reader.d.ts +26 -0
- package/esm/node/codec/proto-reader.js +153 -0
- package/esm/node/codec/proto-reader.js.map +1 -0
- package/esm/node/codec/proto-writer.d.ts +29 -0
- package/esm/node/codec/proto-writer.js +150 -0
- package/esm/node/codec/proto-writer.js.map +1 -0
- package/esm/node/index.d.ts +15 -0
- package/esm/node/index.js +16 -0
- package/esm/node/index.js.map +1 -0
- package/esm/node/module.d.ts +3 -0
- package/esm/node/module.js +4 -0
- package/esm/node/module.js.map +1 -0
- package/esm/node/proto/proto-ast.d.ts +46 -0
- package/esm/node/proto/proto-ast.js +2 -0
- package/esm/node/proto/proto-ast.js.map +1 -0
- package/esm/node/proto/proto-parser.d.ts +45 -0
- package/esm/node/proto/proto-parser.js +451 -0
- package/esm/node/proto/proto-parser.js.map +1 -0
- package/esm/node/proto/proto-types.d.ts +76 -0
- package/esm/node/proto/proto-types.js +444 -0
- package/esm/node/proto/proto-types.js.map +1 -0
- package/esm/node/proto/proto.d.ts +57 -0
- package/esm/node/proto/proto.js +174 -0
- package/esm/node/proto/proto.js.map +1 -0
- package/esm/node/proto/well-known.d.ts +5 -0
- package/esm/node/proto/well-known.js +41 -0
- package/esm/node/proto/well-known.js.map +1 -0
- package/esm/node/server/grpc-server-lifecycle.d.ts +21 -0
- package/esm/node/server/grpc-server-lifecycle.js +65 -0
- package/esm/node/server/grpc-server-lifecycle.js.map +1 -0
- package/esm/node/server/grpc-server.d.ts +60 -0
- package/esm/node/server/grpc-server.js +312 -0
- package/esm/node/server/grpc-server.js.map +1 -0
- package/esm/node/server/grpc-service.d.ts +24 -0
- package/esm/node/server/grpc-service.js +38 -0
- package/esm/node/server/grpc-service.js.map +1 -0
- package/esm/node/test/proto-loader.d.ts +2 -0
- package/esm/node/test/proto-loader.js +13 -0
- package/esm/node/test/proto-loader.js.map +1 -0
- package/esm/node/test/test-protos.d.ts +28 -0
- package/esm/node/test/test-protos.js +145 -0
- package/esm/node/test/test-protos.js.map +1 -0
- package/esm/package.json +3 -0
- package/lib/node/call/async-queue.d.ts +32 -0
- package/lib/node/call/async-queue.d.ts.map +1 -0
- package/lib/node/call/async-queue.js +84 -0
- package/lib/node/call/async-queue.js.map +1 -0
- package/lib/node/call/grpc-status.d.ts +34 -0
- package/lib/node/call/grpc-status.d.ts.map +1 -0
- package/lib/node/call/grpc-status.js +52 -0
- package/lib/node/call/grpc-status.js.map +1 -0
- package/lib/node/call/message-framer.d.ts +25 -0
- package/lib/node/call/message-framer.d.ts.map +1 -0
- package/lib/node/call/message-framer.js +109 -0
- package/lib/node/call/message-framer.js.map +1 -0
- package/lib/node/call/metadata.d.ts +16 -0
- package/lib/node/call/metadata.d.ts.map +1 -0
- package/lib/node/call/metadata.js +84 -0
- package/lib/node/call/metadata.js.map +1 -0
- package/lib/node/client/grpc-channel.d.ts +65 -0
- package/lib/node/client/grpc-channel.d.ts.map +1 -0
- package/lib/node/client/grpc-channel.js +289 -0
- package/lib/node/client/grpc-channel.js.map +1 -0
- package/lib/node/codec/proto-reader.d.ts +27 -0
- package/lib/node/codec/proto-reader.d.ts.map +1 -0
- package/lib/node/codec/proto-reader.js +157 -0
- package/lib/node/codec/proto-reader.js.map +1 -0
- package/lib/node/codec/proto-writer.d.ts +30 -0
- package/lib/node/codec/proto-writer.d.ts.map +1 -0
- package/lib/node/codec/proto-writer.js +154 -0
- package/lib/node/codec/proto-writer.js.map +1 -0
- package/lib/node/grpc.spec.d.ts +2 -0
- package/lib/node/grpc.spec.d.ts.map +1 -0
- package/lib/node/grpc.spec.js +148 -0
- package/lib/node/grpc.spec.js.map +1 -0
- package/lib/node/index.d.ts +16 -0
- package/lib/node/index.d.ts.map +1 -0
- package/lib/node/index.js +32 -0
- package/lib/node/index.js.map +1 -0
- package/lib/node/interop.spec.d.ts +2 -0
- package/lib/node/interop.spec.d.ts.map +1 -0
- package/lib/node/interop.spec.js +194 -0
- package/lib/node/interop.spec.js.map +1 -0
- package/lib/node/module.d.ts +4 -0
- package/lib/node/module.d.ts.map +1 -0
- package/lib/node/module.js +6 -0
- package/lib/node/module.js.map +1 -0
- package/lib/node/proto/proto-ast.d.ts +47 -0
- package/lib/node/proto/proto-ast.d.ts.map +1 -0
- package/lib/node/proto/proto-ast.js +3 -0
- package/lib/node/proto/proto-ast.js.map +1 -0
- package/lib/node/proto/proto-parser.d.ts +46 -0
- package/lib/node/proto/proto-parser.d.ts.map +1 -0
- package/lib/node/proto/proto-parser.js +455 -0
- package/lib/node/proto/proto-parser.js.map +1 -0
- package/lib/node/proto/proto-parser.spec.d.ts +2 -0
- package/lib/node/proto/proto-parser.spec.d.ts.map +1 -0
- package/lib/node/proto/proto-parser.spec.js +95 -0
- package/lib/node/proto/proto-parser.spec.js.map +1 -0
- package/lib/node/proto/proto-types.d.ts +77 -0
- package/lib/node/proto/proto-types.d.ts.map +1 -0
- package/lib/node/proto/proto-types.js +449 -0
- package/lib/node/proto/proto-types.js.map +1 -0
- package/lib/node/proto/proto-types.spec.d.ts +2 -0
- package/lib/node/proto/proto-types.spec.d.ts.map +1 -0
- package/lib/node/proto/proto-types.spec.js +120 -0
- package/lib/node/proto/proto-types.spec.js.map +1 -0
- package/lib/node/proto/proto.d.ts +58 -0
- package/lib/node/proto/proto.d.ts.map +1 -0
- package/lib/node/proto/proto.js +178 -0
- package/lib/node/proto/proto.js.map +1 -0
- package/lib/node/proto/well-known.d.ts +6 -0
- package/lib/node/proto/well-known.d.ts.map +1 -0
- package/lib/node/proto/well-known.js +44 -0
- package/lib/node/proto/well-known.js.map +1 -0
- package/lib/node/server/grpc-server-lifecycle.d.ts +22 -0
- package/lib/node/server/grpc-server-lifecycle.d.ts.map +1 -0
- package/lib/node/server/grpc-server-lifecycle.js +68 -0
- package/lib/node/server/grpc-server-lifecycle.js.map +1 -0
- package/lib/node/server/grpc-server-lifecycle.spec.d.ts +2 -0
- package/lib/node/server/grpc-server-lifecycle.spec.d.ts.map +1 -0
- package/lib/node/server/grpc-server-lifecycle.spec.js +100 -0
- package/lib/node/server/grpc-server-lifecycle.spec.js.map +1 -0
- package/lib/node/server/grpc-server.d.ts +61 -0
- package/lib/node/server/grpc-server.d.ts.map +1 -0
- package/lib/node/server/grpc-server.js +316 -0
- package/lib/node/server/grpc-server.js.map +1 -0
- package/lib/node/server/grpc-service.d.ts +25 -0
- package/lib/node/server/grpc-service.d.ts.map +1 -0
- package/lib/node/server/grpc-service.js +42 -0
- package/lib/node/server/grpc-service.js.map +1 -0
- package/lib/node/test/proto-loader.d.ts +3 -0
- package/lib/node/test/proto-loader.d.ts.map +1 -0
- package/lib/node/test/proto-loader.js +16 -0
- package/lib/node/test/proto-loader.js.map +1 -0
- package/lib/node/test/test-protos.d.ts +29 -0
- package/lib/node/test/test-protos.d.ts.map +1 -0
- package/lib/node/test/test-protos.js +150 -0
- package/lib/node/test/test-protos.js.map +1 -0
- package/lib/package.spec.d.ts +2 -0
- package/lib/package.spec.d.ts.map +1 -0
- package/lib/package.spec.js +7 -0
- package/lib/package.spec.js.map +1 -0
- package/package.json +69 -4
- package/src/node/call/async-queue.ts +79 -0
- package/src/node/call/grpc-status.ts +49 -0
- package/src/node/call/message-framer.ts +109 -0
- package/src/node/call/metadata.ts +85 -0
- package/src/node/client/grpc-channel.ts +327 -0
- package/src/node/codec/proto-reader.ts +172 -0
- package/src/node/codec/proto-writer.ts +170 -0
- package/src/node/grpc.spec.ts +160 -0
- package/src/node/index.ts +15 -0
- package/src/node/interop.spec.ts +174 -0
- package/src/node/module.ts +4 -0
- package/src/node/proto/proto-ast.ts +48 -0
- package/src/node/proto/proto-parser.spec.ts +104 -0
- package/src/node/proto/proto-parser.ts +477 -0
- package/src/node/proto/proto-types.spec.ts +128 -0
- package/src/node/proto/proto-types.ts +497 -0
- package/src/node/proto/proto.ts +218 -0
- package/src/node/proto/well-known.ts +40 -0
- package/src/node/server/grpc-server-lifecycle.spec.ts +88 -0
- package/src/node/server/grpc-server-lifecycle.ts +56 -0
- package/src/node/server/grpc-server.ts +368 -0
- package/src/node/server/grpc-service.ts +40 -0
- package/src/node/test/proto-loader.ts +13 -0
- package/src/node/test/test-protos.ts +159 -0
- package/src/package.spec.ts +5 -0
|
@@ -0,0 +1,368 @@
|
|
|
1
|
+
import { createServer, type Http2Server, type IncomingHttpHeaders, type ServerHttp2Session, type ServerHttp2Stream } from 'node:http2';
|
|
2
|
+
import type { AddressInfo } from 'node:net';
|
|
3
|
+
import { AsyncQueue } from '../call/async-queue';
|
|
4
|
+
import { GrpcError, GrpcStatus } from '../call/grpc-status';
|
|
5
|
+
import { ACCEPT_ENCODING, DEFAULT_MAX_RECEIVE_MESSAGE_SIZE, MessageDeframer, MessageFramer } from '../call/message-framer';
|
|
6
|
+
import { type Metadata, MetadataUtil } from '../call/metadata';
|
|
7
|
+
import type { MethodDefinition, ServiceDefinition } from '../proto/proto';
|
|
8
|
+
|
|
9
|
+
/** What a service method gets besides the request: the call's metadata, cancellation and response metadata. */
|
|
10
|
+
export interface ServerCall {
|
|
11
|
+
readonly method: MethodDefinition;
|
|
12
|
+
/** The request metadata (headers), keys in lowercase. */
|
|
13
|
+
readonly metadata: Metadata;
|
|
14
|
+
/** Aborted when the client cancels, the deadline passes or the server closes. */
|
|
15
|
+
readonly signal: AbortSignal;
|
|
16
|
+
readonly deadline?: Date;
|
|
17
|
+
/** Adds response metadata; only before the first response message. */
|
|
18
|
+
setHeader(key: string, value: Metadata[string]): void;
|
|
19
|
+
/** Adds metadata to the trailers that end the call. */
|
|
20
|
+
setTrailer(key: string, value: Metadata[string]): void;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
type Awaitable<T> = T | Promise<T>;
|
|
24
|
+
type Stream<T> = Iterable<T> | AsyncIterable<T>;
|
|
25
|
+
|
|
26
|
+
/** `rpc M (Req) returns (Res)` */
|
|
27
|
+
export type UnaryHandler<Req = any, Res = any> = (request: Req, call: ServerCall) => Awaitable<Res>;
|
|
28
|
+
/** `rpc M (stream Req) returns (Res)` */
|
|
29
|
+
export type ClientStreamHandler<Req = any, Res = any> = (requests: AsyncIterable<Req>, call: ServerCall) => Awaitable<Res>;
|
|
30
|
+
/** `rpc M (Req) returns (stream Res)`: return an async generator or any (async) iterable. */
|
|
31
|
+
export type ServerStreamHandler<Req = any, Res = any> = (request: Req, call: ServerCall) => Awaitable<Stream<Res>>;
|
|
32
|
+
/** `rpc M (stream Req) returns (stream Res)` */
|
|
33
|
+
export type BidiStreamHandler<Req = any, Res = any> = (requests: AsyncIterable<Req>, call: ServerCall) => Awaitable<Stream<Res>>;
|
|
34
|
+
|
|
35
|
+
export interface GrpcServerOptions {
|
|
36
|
+
/** Largest request message accepted, in bytes. Default 4 MiB. */
|
|
37
|
+
maxReceiveMessageSize?: number;
|
|
38
|
+
/** Reports errors of service methods that are not {@link GrpcError}s. Default `console.error`. */
|
|
39
|
+
onError?: (error: unknown, method: MethodDefinition) => void;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
interface Handler {
|
|
43
|
+
method: MethodDefinition;
|
|
44
|
+
fn: (...args: any[]) => any;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* A gRPC server on `node:http2` (cleartext HTTP/2). Each method of a service is the method of the
|
|
49
|
+
* implementation named after it in lowerCamelCase (`SayHello` → `sayHello`); see {@link UnaryHandler}
|
|
50
|
+
* and the other handler types for their signatures. Methods without an implementation answer
|
|
51
|
+
* `UNIMPLEMENTED`.
|
|
52
|
+
*
|
|
53
|
+
* In a Cell application, use {@link GrpcService} instead: the application starts the server.
|
|
54
|
+
*/
|
|
55
|
+
export class GrpcServer {
|
|
56
|
+
protected readonly handlers = new Map<string, Handler>();
|
|
57
|
+
protected readonly sessions = new Set<ServerHttp2Session>();
|
|
58
|
+
protected server?: Http2Server;
|
|
59
|
+
|
|
60
|
+
constructor(protected readonly options: GrpcServerOptions = {}) {}
|
|
61
|
+
|
|
62
|
+
addService(service: ServiceDefinition, implementation: object): this {
|
|
63
|
+
for (const method of service.methods) {
|
|
64
|
+
const impl = implementation as Record<string, unknown>;
|
|
65
|
+
const fn = impl[method.jsName] ?? impl[method.name];
|
|
66
|
+
if (this.handlers.has(method.path)) {
|
|
67
|
+
throw new Error(`${method.path} is served twice: add ${service.fullName} to the server once.`);
|
|
68
|
+
}
|
|
69
|
+
if (typeof fn === 'function') {
|
|
70
|
+
this.handlers.set(method.path, { method, fn: fn.bind(implementation) });
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
return this;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** Starts listening; resolves to the port, which is a free one when `port` is 0. */
|
|
77
|
+
listen(port = 50051, host = '127.0.0.1'): Promise<number> {
|
|
78
|
+
if (this.server) {
|
|
79
|
+
throw new Error('The gRPC server is already listening.');
|
|
80
|
+
}
|
|
81
|
+
const server = createServer();
|
|
82
|
+
this.server = server;
|
|
83
|
+
server.on('session', session => {
|
|
84
|
+
this.sessions.add(session);
|
|
85
|
+
session.on('close', () => this.sessions.delete(session));
|
|
86
|
+
session.on('error', () => undefined);
|
|
87
|
+
});
|
|
88
|
+
server.on('stream', (stream, headers) => this.handleStream(stream, headers));
|
|
89
|
+
return new Promise((resolve, reject) => {
|
|
90
|
+
server.once('error', reject);
|
|
91
|
+
server.listen(port, host, () => {
|
|
92
|
+
server.off('error', reject);
|
|
93
|
+
resolve((server.address() as AddressInfo).port);
|
|
94
|
+
});
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
get port(): number | undefined {
|
|
99
|
+
const address = this.server?.address();
|
|
100
|
+
return address && typeof address === 'object' ? address.port : undefined;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** Stops accepting connections and closes the open ones; `force` also cancels the calls in progress. */
|
|
104
|
+
close(force = false): Promise<void> {
|
|
105
|
+
const server = this.server;
|
|
106
|
+
this.server = undefined;
|
|
107
|
+
if (!server) {
|
|
108
|
+
return Promise.resolve();
|
|
109
|
+
}
|
|
110
|
+
const closed = new Promise<void>(resolve => server.close(() => resolve()));
|
|
111
|
+
for (const session of this.sessions) {
|
|
112
|
+
if (force) {
|
|
113
|
+
session.destroy();
|
|
114
|
+
} else {
|
|
115
|
+
session.close();
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
return closed;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** Serves one HTTP/2 stream; for servers of your own (`server.on('stream', ...)`). */
|
|
122
|
+
handleStream(stream: ServerHttp2Stream, headers: IncomingHttpHeaders): void {
|
|
123
|
+
stream.on('error', () => undefined);
|
|
124
|
+
const contentType = headers['content-type'];
|
|
125
|
+
if (headers[':method'] !== 'POST' || typeof contentType !== 'string' || !contentType.startsWith('application/grpc')) {
|
|
126
|
+
stream.respond({ ':status': 415, 'grpc-status': String(GrpcStatus.UNKNOWN), 'grpc-message': 'Not a gRPC request' }, { endStream: true });
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
const path = String(headers[':path']);
|
|
130
|
+
const handler = this.handlers.get(path);
|
|
131
|
+
if (!handler) {
|
|
132
|
+
stream.respond(
|
|
133
|
+
{
|
|
134
|
+
':status': 200,
|
|
135
|
+
'content-type': 'application/grpc+proto',
|
|
136
|
+
'grpc-status': String(GrpcStatus.UNIMPLEMENTED),
|
|
137
|
+
'grpc-message': MetadataUtil.encodeMessage(`The server does not implement ${path}`),
|
|
138
|
+
},
|
|
139
|
+
{ endStream: true },
|
|
140
|
+
);
|
|
141
|
+
stream.resume();
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
const call = new GrpcServerCall(stream, headers, handler.method, this.options);
|
|
145
|
+
call.run(handler.fn).catch(error => call.fail(error));
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
class GrpcServerCall implements ServerCall {
|
|
150
|
+
readonly metadata: Metadata;
|
|
151
|
+
readonly deadline?: Date;
|
|
152
|
+
protected readonly controller = new AbortController();
|
|
153
|
+
protected readonly responseHeaders: Metadata = {};
|
|
154
|
+
protected readonly trailers: Metadata = {};
|
|
155
|
+
protected readonly timer?: ReturnType<typeof setTimeout>;
|
|
156
|
+
protected headersSent = false;
|
|
157
|
+
protected finished = false;
|
|
158
|
+
protected requestsRead = false;
|
|
159
|
+
|
|
160
|
+
constructor(
|
|
161
|
+
protected readonly stream: ServerHttp2Stream,
|
|
162
|
+
protected readonly headers: IncomingHttpHeaders,
|
|
163
|
+
readonly method: MethodDefinition,
|
|
164
|
+
protected readonly options: GrpcServerOptions,
|
|
165
|
+
) {
|
|
166
|
+
this.metadata = MetadataUtil.fromHeaders(headers);
|
|
167
|
+
const timeout = MetadataUtil.parseTimeout(headers['grpc-timeout']);
|
|
168
|
+
if (timeout !== undefined) {
|
|
169
|
+
this.deadline = new Date(Date.now() + timeout);
|
|
170
|
+
this.timer = setTimeout(() => this.finish(new GrpcError(GrpcStatus.DEADLINE_EXCEEDED, 'Deadline exceeded')), timeout);
|
|
171
|
+
}
|
|
172
|
+
stream.once('close', () => {
|
|
173
|
+
clearTimeout(this.timer);
|
|
174
|
+
if (!this.finished) {
|
|
175
|
+
this.finished = true;
|
|
176
|
+
this.controller.abort(new GrpcError(GrpcStatus.CANCELLED, 'The call was cancelled'));
|
|
177
|
+
}
|
|
178
|
+
});
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
get signal(): AbortSignal {
|
|
182
|
+
return this.controller.signal;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
setHeader(key: string, value: Metadata[string]): void {
|
|
186
|
+
if (this.headersSent) {
|
|
187
|
+
throw new Error('Response metadata is sent with the first response message; set it before.');
|
|
188
|
+
}
|
|
189
|
+
this.responseHeaders[key.toLowerCase()] = value;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
setTrailer(key: string, value: Metadata[string]): void {
|
|
193
|
+
this.trailers[key.toLowerCase()] = value;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
async run(fn: (...args: any[]) => any): Promise<void> {
|
|
197
|
+
const { method } = this;
|
|
198
|
+
const input = method.requestStream ? this.requests() : await this.single();
|
|
199
|
+
const output = await fn(input, this);
|
|
200
|
+
if (method.responseStream) {
|
|
201
|
+
const iterator = toAsyncIterator(output, method);
|
|
202
|
+
try {
|
|
203
|
+
for (let r = await iterator.next(); !r.done; r = await iterator.next()) {
|
|
204
|
+
if (this.finished) {
|
|
205
|
+
break;
|
|
206
|
+
}
|
|
207
|
+
await this.write(r.value);
|
|
208
|
+
}
|
|
209
|
+
} finally {
|
|
210
|
+
if (this.finished) {
|
|
211
|
+
await iterator.return?.();
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
} else {
|
|
215
|
+
await this.write(output ?? {});
|
|
216
|
+
}
|
|
217
|
+
this.finish();
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/** Ends the call with the status of `error`, reporting errors that are not gRPC statuses. */
|
|
221
|
+
fail(error: unknown): void {
|
|
222
|
+
const status = GrpcError.from(error);
|
|
223
|
+
if (status !== error && status.code === GrpcStatus.UNKNOWN && !this.finished) {
|
|
224
|
+
(this.options.onError ?? console.error)(error, this.method);
|
|
225
|
+
}
|
|
226
|
+
this.finish(status);
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/** Sends the status (OK when `error` is undefined) in the trailers and ends the call. */
|
|
230
|
+
finish(error?: GrpcError): void {
|
|
231
|
+
if (this.finished) {
|
|
232
|
+
return;
|
|
233
|
+
}
|
|
234
|
+
this.finished = true;
|
|
235
|
+
clearTimeout(this.timer);
|
|
236
|
+
if (error) {
|
|
237
|
+
this.controller.abort(error);
|
|
238
|
+
}
|
|
239
|
+
if (this.stream.destroyed || this.stream.closed) {
|
|
240
|
+
return;
|
|
241
|
+
}
|
|
242
|
+
const trailers = MetadataUtil.toHeaders({ ...this.trailers, ...error?.metadata }, { 'grpc-status': String(error?.code ?? GrpcStatus.OK) });
|
|
243
|
+
if (error?.details) {
|
|
244
|
+
trailers['grpc-message'] = MetadataUtil.encodeMessage(error.details);
|
|
245
|
+
}
|
|
246
|
+
try {
|
|
247
|
+
if (this.headersSent) {
|
|
248
|
+
this.stream.once('wantTrailers', () => this.stream.sendTrailers(trailers));
|
|
249
|
+
this.stream.end();
|
|
250
|
+
} else {
|
|
251
|
+
// Trailers-Only: the status in the only HEADERS frame.
|
|
252
|
+
this.stream.respond({ ...this.responseHeaderBlock(), ...trailers }, { endStream: true });
|
|
253
|
+
}
|
|
254
|
+
if (!this.stream.readableEnded) {
|
|
255
|
+
this.stream.resume();
|
|
256
|
+
}
|
|
257
|
+
} catch {
|
|
258
|
+
// The client went away meanwhile.
|
|
259
|
+
this.stream.destroy();
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
protected responseHeaderBlock() {
|
|
264
|
+
return MetadataUtil.toHeaders(this.responseHeaders, {
|
|
265
|
+
':status': 200,
|
|
266
|
+
'content-type': 'application/grpc+proto',
|
|
267
|
+
'grpc-accept-encoding': ACCEPT_ENCODING,
|
|
268
|
+
});
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
protected async write(message: unknown): Promise<void> {
|
|
272
|
+
if (this.finished) {
|
|
273
|
+
return;
|
|
274
|
+
}
|
|
275
|
+
let framed: Uint8Array;
|
|
276
|
+
try {
|
|
277
|
+
framed = MessageFramer.frame(this.method.responseType.encode(message));
|
|
278
|
+
} catch (error) {
|
|
279
|
+
throw new GrpcError(GrpcStatus.INTERNAL, `Could not encode the response of ${this.method.path}: ${(error as Error).message}`);
|
|
280
|
+
}
|
|
281
|
+
if (!this.headersSent) {
|
|
282
|
+
this.headersSent = true;
|
|
283
|
+
this.stream.respond(this.responseHeaderBlock(), { waitForTrailers: true });
|
|
284
|
+
}
|
|
285
|
+
if (!this.stream.write(framed)) {
|
|
286
|
+
await new Promise<void>(resolve => {
|
|
287
|
+
const done = () => {
|
|
288
|
+
this.stream.off('drain', done);
|
|
289
|
+
this.stream.off('close', done);
|
|
290
|
+
resolve();
|
|
291
|
+
};
|
|
292
|
+
this.stream.on('drain', done);
|
|
293
|
+
this.stream.on('close', done);
|
|
294
|
+
});
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
protected async single(): Promise<unknown> {
|
|
299
|
+
let request: unknown;
|
|
300
|
+
let count = 0;
|
|
301
|
+
for await (const message of this.requests()) {
|
|
302
|
+
request = message;
|
|
303
|
+
count++;
|
|
304
|
+
}
|
|
305
|
+
if (count !== 1) {
|
|
306
|
+
throw new GrpcError(GrpcStatus.INTERNAL, `${this.method.path} takes one request message, received ${count}`);
|
|
307
|
+
}
|
|
308
|
+
return request;
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
protected requests(): AsyncIterable<unknown> {
|
|
312
|
+
if (this.requestsRead) {
|
|
313
|
+
throw new Error('The request stream can be read once.');
|
|
314
|
+
}
|
|
315
|
+
this.requestsRead = true;
|
|
316
|
+
const { stream } = this;
|
|
317
|
+
const type = this.method.requestType;
|
|
318
|
+
const queue = new AsyncQueue<unknown>({ pause: () => stream.pause(), resume: () => stream.resume() });
|
|
319
|
+
let deframer: MessageDeframer;
|
|
320
|
+
try {
|
|
321
|
+
deframer = new MessageDeframer(
|
|
322
|
+
String(this.headers['grpc-encoding'] ?? 'identity'),
|
|
323
|
+
this.options.maxReceiveMessageSize ?? DEFAULT_MAX_RECEIVE_MESSAGE_SIZE,
|
|
324
|
+
);
|
|
325
|
+
} catch (error) {
|
|
326
|
+
queue.end(error);
|
|
327
|
+
return queue;
|
|
328
|
+
}
|
|
329
|
+
let failed = false;
|
|
330
|
+
stream.on('data', (chunk: Uint8Array) => {
|
|
331
|
+
if (failed) {
|
|
332
|
+
return;
|
|
333
|
+
}
|
|
334
|
+
try {
|
|
335
|
+
for (const message of deframer.push(chunk)) {
|
|
336
|
+
queue.push(decode(type, message));
|
|
337
|
+
}
|
|
338
|
+
} catch (error) {
|
|
339
|
+
failed = true;
|
|
340
|
+
queue.end(error);
|
|
341
|
+
}
|
|
342
|
+
});
|
|
343
|
+
stream.once('end', () =>
|
|
344
|
+
queue.end(deframer.pending ? new GrpcError(GrpcStatus.INTERNAL, 'The request stream ended in the middle of a message') : undefined),
|
|
345
|
+
);
|
|
346
|
+
this.signal.addEventListener('abort', () => queue.end(this.signal.reason), { once: true });
|
|
347
|
+
return queue;
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
function decode(type: MethodDefinition['requestType'], message: Uint8Array): unknown {
|
|
352
|
+
try {
|
|
353
|
+
return type.decode(message);
|
|
354
|
+
} catch (error) {
|
|
355
|
+
throw new GrpcError(GrpcStatus.INTERNAL, `Could not parse a ${type.fullName}: ${(error as Error).message}`);
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
function toAsyncIterator(output: any, method: MethodDefinition): AsyncIterator<unknown> {
|
|
360
|
+
if (output && typeof output[Symbol.asyncIterator] === 'function') {
|
|
361
|
+
return output[Symbol.asyncIterator]();
|
|
362
|
+
}
|
|
363
|
+
if (output && typeof output[Symbol.iterator] === 'function') {
|
|
364
|
+
const iterator: Iterator<unknown> = output[Symbol.iterator]();
|
|
365
|
+
return { next: async () => iterator.next(), return: async () => iterator.return?.() ?? { done: true, value: undefined } };
|
|
366
|
+
}
|
|
367
|
+
throw new GrpcError(GrpcStatus.INTERNAL, `${method.path} streams its responses: the method must return an (async) iterable, such as an async generator.`);
|
|
368
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { Component, type ComponentId, type ComponentOption, parseComponentOption } from '@celljs/core';
|
|
2
|
+
import type { ServiceDefinition } from '../proto/proto';
|
|
3
|
+
|
|
4
|
+
/** DI id of every {@link GrpcService} component. */
|
|
5
|
+
export const GRPC_SERVICE = Symbol('GrpcService');
|
|
6
|
+
|
|
7
|
+
export const GRPC_SERVICE_TAG = 'GrpcService';
|
|
8
|
+
|
|
9
|
+
const SERVICE_KEY = 'cell:grpc-service';
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Serves the class as the implementation of a gRPC service on the application's gRPC server
|
|
13
|
+
* (`cell.grpc.server`, port 50051 by default). Methods are named after the .proto methods in
|
|
14
|
+
* lowerCamelCase; the class is a component, so it can `@Autowired` others.
|
|
15
|
+
*
|
|
16
|
+
* ```ts
|
|
17
|
+
* @GrpcService(Greeter)
|
|
18
|
+
* export class GreeterService {
|
|
19
|
+
* sayHello({ name }: HelloRequest): HelloReply {
|
|
20
|
+
* return { message: `Hello ${name}` };
|
|
21
|
+
* }
|
|
22
|
+
* }
|
|
23
|
+
* ```
|
|
24
|
+
*/
|
|
25
|
+
export function GrpcService(service: ServiceDefinition, option?: ComponentOption): ClassDecorator {
|
|
26
|
+
return target => {
|
|
27
|
+
const parsed = parseComponentOption(target, option ?? {});
|
|
28
|
+
(parsed.id as ComponentId[]).push(GRPC_SERVICE);
|
|
29
|
+
parsed.sysTags = [...(parsed.sysTags ?? []), GRPC_SERVICE_TAG];
|
|
30
|
+
Reflect.defineMetadata(SERVICE_KEY, service, target);
|
|
31
|
+
Component(parsed)(target);
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export namespace GrpcServiceUtil {
|
|
36
|
+
/** The service a {@link GrpcService} class implements. */
|
|
37
|
+
export function getService(target: object): ServiceDefinition | undefined {
|
|
38
|
+
return Reflect.getOwnMetadata(SERVICE_KEY, target);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { mkdtempSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { tmpdir } from 'node:os';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { loadSync } from '@grpc/proto-loader';
|
|
5
|
+
import { TEST_PROTO } from './test-protos';
|
|
6
|
+
|
|
7
|
+
/** TEST_PROTO loaded by @grpc/proto-loader (protobuf.js), the reference implementation of the tests. */
|
|
8
|
+
export function loadTestProto() {
|
|
9
|
+
const dir = mkdtempSync(join(tmpdir(), 'cell-grpc-'));
|
|
10
|
+
const file = join(dir, 'test.proto');
|
|
11
|
+
writeFileSync(file, TEST_PROTO);
|
|
12
|
+
return loadSync(file, { keepCase: false, longs: String, enums: String, defaults: true, oneofs: true });
|
|
13
|
+
}
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
import { GrpcError, GrpcStatus } from '../call/grpc-status';
|
|
2
|
+
import type { ServerCall } from '../server/grpc-server';
|
|
3
|
+
|
|
4
|
+
/** The .proto of the package's tests: every field kind, and a service with every kind of method. */
|
|
5
|
+
export const TEST_PROTO = `
|
|
6
|
+
syntax = "proto3";
|
|
7
|
+
package cell.test;
|
|
8
|
+
|
|
9
|
+
import "google/protobuf/empty.proto";
|
|
10
|
+
import "google/protobuf/timestamp.proto";
|
|
11
|
+
|
|
12
|
+
// Colors.
|
|
13
|
+
enum Color {
|
|
14
|
+
COLOR_UNSPECIFIED = 0;
|
|
15
|
+
RED = 1;
|
|
16
|
+
GREEN = 2 [deprecated = true];
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
message Scalars {
|
|
20
|
+
double d = 1;
|
|
21
|
+
float f = 2;
|
|
22
|
+
int32 i32 = 3;
|
|
23
|
+
int64 i64 = 4;
|
|
24
|
+
uint32 u32 = 5;
|
|
25
|
+
uint64 u64 = 6;
|
|
26
|
+
sint32 s32 = 7;
|
|
27
|
+
sint64 s64 = 8;
|
|
28
|
+
fixed32 fx32 = 9;
|
|
29
|
+
fixed64 fx64 = 10;
|
|
30
|
+
sfixed32 sfx32 = 11;
|
|
31
|
+
sfixed64 sfx64 = 12;
|
|
32
|
+
bool flag = 13;
|
|
33
|
+
string text = 14;
|
|
34
|
+
bytes data = 15;
|
|
35
|
+
Color color = 16;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/* Everything else. */
|
|
39
|
+
message Everything {
|
|
40
|
+
option deprecated = false;
|
|
41
|
+
Scalars scalars = 1;
|
|
42
|
+
repeated int32 numbers = 2;
|
|
43
|
+
repeated string names = 3;
|
|
44
|
+
repeated Scalars items = 4;
|
|
45
|
+
map<string, int32> counts = 5;
|
|
46
|
+
map<int64, Scalars> by_id = 6;
|
|
47
|
+
oneof choice {
|
|
48
|
+
string label = 7;
|
|
49
|
+
int32 code = 8;
|
|
50
|
+
Scalars nested = 9;
|
|
51
|
+
}
|
|
52
|
+
optional int32 maybe = 10;
|
|
53
|
+
google.protobuf.Timestamp at = 11;
|
|
54
|
+
repeated Color colors = 12;
|
|
55
|
+
message Inner { string value = 1; }
|
|
56
|
+
Inner inner = 13;
|
|
57
|
+
string snake_case_name = 14;
|
|
58
|
+
reserved 100 to 110;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
message HelloRequest {
|
|
62
|
+
string name = 1;
|
|
63
|
+
int32 count = 2;
|
|
64
|
+
bytes payload = 3;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
message HelloReply {
|
|
68
|
+
string message = 1;
|
|
69
|
+
bytes payload = 2;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
service Greeter {
|
|
73
|
+
option deprecated = false;
|
|
74
|
+
rpc SayHello (HelloRequest) returns (HelloReply);
|
|
75
|
+
rpc SayHellos (HelloRequest) returns (stream HelloReply);
|
|
76
|
+
rpc CollectHellos (stream HelloRequest) returns (HelloReply);
|
|
77
|
+
rpc Chat (stream HelloRequest) returns (stream HelloReply) {
|
|
78
|
+
option deprecated = false;
|
|
79
|
+
}
|
|
80
|
+
rpc Echo (Everything) returns (Everything);
|
|
81
|
+
rpc Nothing (google.protobuf.Empty) returns (google.protobuf.Empty);
|
|
82
|
+
}
|
|
83
|
+
`;
|
|
84
|
+
|
|
85
|
+
interface HelloRequest {
|
|
86
|
+
name: string;
|
|
87
|
+
count: number;
|
|
88
|
+
payload: Uint8Array;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** An implementation of cell.test.Greeter whose answers depend on the request, for the tests. */
|
|
92
|
+
export class TestGreeter {
|
|
93
|
+
sayHello(request: HelloRequest, call: ServerCall) {
|
|
94
|
+
if (request.name === 'fail') {
|
|
95
|
+
throw new GrpcError(GrpcStatus.INVALID_ARGUMENT, 'name must not be "fail" — ünïcode', { 'x-reason': 'bad name' });
|
|
96
|
+
}
|
|
97
|
+
if (request.name === 'crash') {
|
|
98
|
+
throw new Error('boom');
|
|
99
|
+
}
|
|
100
|
+
if (request.name === 'slow') {
|
|
101
|
+
return new Promise((resolve, reject) => {
|
|
102
|
+
const timer = setTimeout(() => resolve({ message: 'late' }), 2000);
|
|
103
|
+
call.signal.addEventListener('abort', () => {
|
|
104
|
+
clearTimeout(timer);
|
|
105
|
+
reject(call.signal.reason);
|
|
106
|
+
});
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
call.setHeader('x-greeting', 'hi');
|
|
110
|
+
call.setTrailer('x-done', 'yes');
|
|
111
|
+
const user = call.metadata['x-user'];
|
|
112
|
+
const token = call.metadata['x-token-bin'];
|
|
113
|
+
const suffix = (user ? ` (${user})` : '') + (token instanceof Uint8Array ? ` [${[...token].join(',')}]` : '');
|
|
114
|
+
return { message: `Hello ${request.name}${suffix}`, payload: request.payload };
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
async *sayHellos(request: HelloRequest, call: ServerCall) {
|
|
118
|
+
for (let i = 0; i < request.count; i++) {
|
|
119
|
+
if (call.signal.aborted) {
|
|
120
|
+
return;
|
|
121
|
+
}
|
|
122
|
+
if (request.name === 'fail' && i === 2) {
|
|
123
|
+
throw new GrpcError(GrpcStatus.ABORTED, 'stopped at 2');
|
|
124
|
+
}
|
|
125
|
+
yield { message: `Hello ${request.name} ${i}` };
|
|
126
|
+
await new Promise(r => setTimeout(r, 1));
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
async collectHellos(requests: AsyncIterable<HelloRequest>) {
|
|
131
|
+
const names: string[] = [];
|
|
132
|
+
for await (const request of requests) {
|
|
133
|
+
names.push(request.name);
|
|
134
|
+
}
|
|
135
|
+
return { message: `Hello ${names.join(', ')}` };
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
async *chat(requests: AsyncIterable<HelloRequest>) {
|
|
139
|
+
for await (const request of requests) {
|
|
140
|
+
yield { message: `> ${request.name}` };
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
echo(message: unknown) {
|
|
145
|
+
return message;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
nothing() {
|
|
149
|
+
return {};
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
export async function collect<T>(iterable: AsyncIterable<T>): Promise<T[]> {
|
|
154
|
+
const items: T[] = [];
|
|
155
|
+
for await (const item of iterable) {
|
|
156
|
+
items.push(item);
|
|
157
|
+
}
|
|
158
|
+
return items;
|
|
159
|
+
}
|