@celljs/grpc 0.0.0-stage → 4.4.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 (187) hide show
  1. package/README.md +121 -2
  2. package/cell.schema.json +32 -0
  3. package/cell.yml +9 -0
  4. package/esm/node/call/async-queue.d.ts +31 -0
  5. package/esm/node/call/async-queue.js +80 -0
  6. package/esm/node/call/async-queue.js.map +1 -0
  7. package/esm/node/call/grpc-status.d.ts +33 -0
  8. package/esm/node/call/grpc-status.js +48 -0
  9. package/esm/node/call/grpc-status.js.map +1 -0
  10. package/esm/node/call/message-framer.d.ts +24 -0
  11. package/esm/node/call/message-framer.js +105 -0
  12. package/esm/node/call/message-framer.js.map +1 -0
  13. package/esm/node/call/metadata.d.ts +15 -0
  14. package/esm/node/call/metadata.js +81 -0
  15. package/esm/node/call/metadata.js.map +1 -0
  16. package/esm/node/client/grpc-channel.d.ts +64 -0
  17. package/esm/node/client/grpc-channel.js +285 -0
  18. package/esm/node/client/grpc-channel.js.map +1 -0
  19. package/esm/node/codec/proto-reader.d.ts +26 -0
  20. package/esm/node/codec/proto-reader.js +153 -0
  21. package/esm/node/codec/proto-reader.js.map +1 -0
  22. package/esm/node/codec/proto-writer.d.ts +29 -0
  23. package/esm/node/codec/proto-writer.js +150 -0
  24. package/esm/node/codec/proto-writer.js.map +1 -0
  25. package/esm/node/index.d.ts +15 -0
  26. package/esm/node/index.js +16 -0
  27. package/esm/node/index.js.map +1 -0
  28. package/esm/node/module.d.ts +3 -0
  29. package/esm/node/module.js +4 -0
  30. package/esm/node/module.js.map +1 -0
  31. package/esm/node/proto/proto-ast.d.ts +46 -0
  32. package/esm/node/proto/proto-ast.js +2 -0
  33. package/esm/node/proto/proto-ast.js.map +1 -0
  34. package/esm/node/proto/proto-parser.d.ts +45 -0
  35. package/esm/node/proto/proto-parser.js +451 -0
  36. package/esm/node/proto/proto-parser.js.map +1 -0
  37. package/esm/node/proto/proto-types.d.ts +76 -0
  38. package/esm/node/proto/proto-types.js +444 -0
  39. package/esm/node/proto/proto-types.js.map +1 -0
  40. package/esm/node/proto/proto.d.ts +57 -0
  41. package/esm/node/proto/proto.js +174 -0
  42. package/esm/node/proto/proto.js.map +1 -0
  43. package/esm/node/proto/well-known.d.ts +5 -0
  44. package/esm/node/proto/well-known.js +41 -0
  45. package/esm/node/proto/well-known.js.map +1 -0
  46. package/esm/node/server/grpc-server-lifecycle.d.ts +21 -0
  47. package/esm/node/server/grpc-server-lifecycle.js +65 -0
  48. package/esm/node/server/grpc-server-lifecycle.js.map +1 -0
  49. package/esm/node/server/grpc-server.d.ts +60 -0
  50. package/esm/node/server/grpc-server.js +312 -0
  51. package/esm/node/server/grpc-server.js.map +1 -0
  52. package/esm/node/server/grpc-service.d.ts +24 -0
  53. package/esm/node/server/grpc-service.js +38 -0
  54. package/esm/node/server/grpc-service.js.map +1 -0
  55. package/esm/node/test/proto-loader.d.ts +2 -0
  56. package/esm/node/test/proto-loader.js +13 -0
  57. package/esm/node/test/proto-loader.js.map +1 -0
  58. package/esm/node/test/test-protos.d.ts +28 -0
  59. package/esm/node/test/test-protos.js +145 -0
  60. package/esm/node/test/test-protos.js.map +1 -0
  61. package/esm/package.json +3 -0
  62. package/lib/node/call/async-queue.d.ts +32 -0
  63. package/lib/node/call/async-queue.d.ts.map +1 -0
  64. package/lib/node/call/async-queue.js +84 -0
  65. package/lib/node/call/async-queue.js.map +1 -0
  66. package/lib/node/call/grpc-status.d.ts +34 -0
  67. package/lib/node/call/grpc-status.d.ts.map +1 -0
  68. package/lib/node/call/grpc-status.js +52 -0
  69. package/lib/node/call/grpc-status.js.map +1 -0
  70. package/lib/node/call/message-framer.d.ts +25 -0
  71. package/lib/node/call/message-framer.d.ts.map +1 -0
  72. package/lib/node/call/message-framer.js +109 -0
  73. package/lib/node/call/message-framer.js.map +1 -0
  74. package/lib/node/call/metadata.d.ts +16 -0
  75. package/lib/node/call/metadata.d.ts.map +1 -0
  76. package/lib/node/call/metadata.js +84 -0
  77. package/lib/node/call/metadata.js.map +1 -0
  78. package/lib/node/client/grpc-channel.d.ts +65 -0
  79. package/lib/node/client/grpc-channel.d.ts.map +1 -0
  80. package/lib/node/client/grpc-channel.js +289 -0
  81. package/lib/node/client/grpc-channel.js.map +1 -0
  82. package/lib/node/codec/proto-reader.d.ts +27 -0
  83. package/lib/node/codec/proto-reader.d.ts.map +1 -0
  84. package/lib/node/codec/proto-reader.js +157 -0
  85. package/lib/node/codec/proto-reader.js.map +1 -0
  86. package/lib/node/codec/proto-writer.d.ts +30 -0
  87. package/lib/node/codec/proto-writer.d.ts.map +1 -0
  88. package/lib/node/codec/proto-writer.js +154 -0
  89. package/lib/node/codec/proto-writer.js.map +1 -0
  90. package/lib/node/grpc.spec.d.ts +2 -0
  91. package/lib/node/grpc.spec.d.ts.map +1 -0
  92. package/lib/node/grpc.spec.js +148 -0
  93. package/lib/node/grpc.spec.js.map +1 -0
  94. package/lib/node/index.d.ts +16 -0
  95. package/lib/node/index.d.ts.map +1 -0
  96. package/lib/node/index.js +32 -0
  97. package/lib/node/index.js.map +1 -0
  98. package/lib/node/interop.spec.d.ts +2 -0
  99. package/lib/node/interop.spec.d.ts.map +1 -0
  100. package/lib/node/interop.spec.js +194 -0
  101. package/lib/node/interop.spec.js.map +1 -0
  102. package/lib/node/module.d.ts +4 -0
  103. package/lib/node/module.d.ts.map +1 -0
  104. package/lib/node/module.js +6 -0
  105. package/lib/node/module.js.map +1 -0
  106. package/lib/node/proto/proto-ast.d.ts +47 -0
  107. package/lib/node/proto/proto-ast.d.ts.map +1 -0
  108. package/lib/node/proto/proto-ast.js +3 -0
  109. package/lib/node/proto/proto-ast.js.map +1 -0
  110. package/lib/node/proto/proto-parser.d.ts +46 -0
  111. package/lib/node/proto/proto-parser.d.ts.map +1 -0
  112. package/lib/node/proto/proto-parser.js +455 -0
  113. package/lib/node/proto/proto-parser.js.map +1 -0
  114. package/lib/node/proto/proto-parser.spec.d.ts +2 -0
  115. package/lib/node/proto/proto-parser.spec.d.ts.map +1 -0
  116. package/lib/node/proto/proto-parser.spec.js +95 -0
  117. package/lib/node/proto/proto-parser.spec.js.map +1 -0
  118. package/lib/node/proto/proto-types.d.ts +77 -0
  119. package/lib/node/proto/proto-types.d.ts.map +1 -0
  120. package/lib/node/proto/proto-types.js +449 -0
  121. package/lib/node/proto/proto-types.js.map +1 -0
  122. package/lib/node/proto/proto-types.spec.d.ts +2 -0
  123. package/lib/node/proto/proto-types.spec.d.ts.map +1 -0
  124. package/lib/node/proto/proto-types.spec.js +120 -0
  125. package/lib/node/proto/proto-types.spec.js.map +1 -0
  126. package/lib/node/proto/proto.d.ts +58 -0
  127. package/lib/node/proto/proto.d.ts.map +1 -0
  128. package/lib/node/proto/proto.js +178 -0
  129. package/lib/node/proto/proto.js.map +1 -0
  130. package/lib/node/proto/well-known.d.ts +6 -0
  131. package/lib/node/proto/well-known.d.ts.map +1 -0
  132. package/lib/node/proto/well-known.js +44 -0
  133. package/lib/node/proto/well-known.js.map +1 -0
  134. package/lib/node/server/grpc-server-lifecycle.d.ts +22 -0
  135. package/lib/node/server/grpc-server-lifecycle.d.ts.map +1 -0
  136. package/lib/node/server/grpc-server-lifecycle.js +68 -0
  137. package/lib/node/server/grpc-server-lifecycle.js.map +1 -0
  138. package/lib/node/server/grpc-server-lifecycle.spec.d.ts +2 -0
  139. package/lib/node/server/grpc-server-lifecycle.spec.d.ts.map +1 -0
  140. package/lib/node/server/grpc-server-lifecycle.spec.js +100 -0
  141. package/lib/node/server/grpc-server-lifecycle.spec.js.map +1 -0
  142. package/lib/node/server/grpc-server.d.ts +61 -0
  143. package/lib/node/server/grpc-server.d.ts.map +1 -0
  144. package/lib/node/server/grpc-server.js +316 -0
  145. package/lib/node/server/grpc-server.js.map +1 -0
  146. package/lib/node/server/grpc-service.d.ts +25 -0
  147. package/lib/node/server/grpc-service.d.ts.map +1 -0
  148. package/lib/node/server/grpc-service.js +42 -0
  149. package/lib/node/server/grpc-service.js.map +1 -0
  150. package/lib/node/test/proto-loader.d.ts +3 -0
  151. package/lib/node/test/proto-loader.d.ts.map +1 -0
  152. package/lib/node/test/proto-loader.js +16 -0
  153. package/lib/node/test/proto-loader.js.map +1 -0
  154. package/lib/node/test/test-protos.d.ts +29 -0
  155. package/lib/node/test/test-protos.d.ts.map +1 -0
  156. package/lib/node/test/test-protos.js +150 -0
  157. package/lib/node/test/test-protos.js.map +1 -0
  158. package/lib/package.spec.d.ts +2 -0
  159. package/lib/package.spec.d.ts.map +1 -0
  160. package/lib/package.spec.js +7 -0
  161. package/lib/package.spec.js.map +1 -0
  162. package/package.json +70 -4
  163. package/src/node/call/async-queue.ts +79 -0
  164. package/src/node/call/grpc-status.ts +49 -0
  165. package/src/node/call/message-framer.ts +109 -0
  166. package/src/node/call/metadata.ts +85 -0
  167. package/src/node/client/grpc-channel.ts +327 -0
  168. package/src/node/codec/proto-reader.ts +172 -0
  169. package/src/node/codec/proto-writer.ts +170 -0
  170. package/src/node/grpc.spec.ts +160 -0
  171. package/src/node/index.ts +15 -0
  172. package/src/node/interop.spec.ts +174 -0
  173. package/src/node/module.ts +4 -0
  174. package/src/node/proto/proto-ast.ts +48 -0
  175. package/src/node/proto/proto-parser.spec.ts +104 -0
  176. package/src/node/proto/proto-parser.ts +477 -0
  177. package/src/node/proto/proto-types.spec.ts +128 -0
  178. package/src/node/proto/proto-types.ts +497 -0
  179. package/src/node/proto/proto.ts +218 -0
  180. package/src/node/proto/well-known.ts +40 -0
  181. package/src/node/server/grpc-server-lifecycle.spec.ts +88 -0
  182. package/src/node/server/grpc-server-lifecycle.ts +56 -0
  183. package/src/node/server/grpc-server.ts +368 -0
  184. package/src/node/server/grpc-service.ts +40 -0
  185. package/src/node/test/proto-loader.ts +13 -0
  186. package/src/node/test/test-protos.ts +159 -0
  187. package/src/package.spec.ts +5 -0
@@ -0,0 +1,218 @@
1
+ import type { EnumAst, MessageAst, ProtoFileAst } from './proto-ast';
2
+ import { ProtoParser } from './proto-parser';
3
+ import { EnumType, type FieldInfo, MessageType, SCALAR_KINDS, type ScalarKind, type ValueInfo } from './proto-types';
4
+ import { WELL_KNOWN_PROTOS } from './well-known';
5
+
6
+ /** A method of a gRPC service. */
7
+ export interface MethodDefinition<Req = any, Res = any> {
8
+ /** Name in the .proto file, e.g. `SayHello`. */
9
+ readonly name: string;
10
+ /** Name of the JavaScript method that implements or calls it: `sayHello`. */
11
+ readonly jsName: string;
12
+ /** HTTP/2 path: `/helloworld.Greeter/SayHello`. */
13
+ readonly path: string;
14
+ readonly requestType: MessageType<Req>;
15
+ readonly responseType: MessageType<Res>;
16
+ readonly requestStream: boolean;
17
+ readonly responseStream: boolean;
18
+ }
19
+
20
+ /** A gRPC service of a .proto file, what {@link GrpcService} serves and {@link GrpcChannel.createClient} calls. */
21
+ export interface ServiceDefinition {
22
+ /** `helloworld.Greeter` */
23
+ readonly fullName: string;
24
+ readonly methods: readonly MethodDefinition[];
25
+ }
26
+
27
+ interface PendingMessage {
28
+ type: MessageType;
29
+ ast: MessageAst;
30
+ syntax: ProtoFileAst['syntax'];
31
+ }
32
+
33
+ /**
34
+ * The messages, enums and services of one or more .proto files.
35
+ *
36
+ * ```ts
37
+ * // source: the text of greeter.proto, e.g. imported with Vite's `?raw` suffix
38
+ * export const Greeter = Proto.parse(source).service('Greeter');
39
+ * ```
40
+ *
41
+ * Pass every file the sources import, in any order; imports of `google/protobuf/*.proto` well-known
42
+ * types are built in. Names are full names (`helloworld.Greeter`) or, when unambiguous, short ones.
43
+ */
44
+ export class Proto {
45
+ protected readonly types = new Map<string, MessageType | EnumType>();
46
+ protected readonly serviceMap = new Map<string, ServiceDefinition>();
47
+
48
+ static parse(...sources: string[]): Proto {
49
+ return new Proto(sources);
50
+ }
51
+
52
+ constructor(sources: string[]) {
53
+ const files = sources.map((source, i) => ProtoParser.parse(source, sources.length > 1 ? `<source ${i + 1}>` : '<source>'));
54
+ const included = new Set<string>();
55
+ for (let i = 0; i < files.length; i++) {
56
+ for (const name of files[i].imports) {
57
+ if (WELL_KNOWN_PROTOS[name] && !included.has(name)) {
58
+ included.add(name);
59
+ files.push(ProtoParser.parse(WELL_KNOWN_PROTOS[name], name));
60
+ }
61
+ }
62
+ }
63
+ const pending: PendingMessage[] = [];
64
+ for (const file of files) {
65
+ const prefix = file.package ? `${file.package}.` : '';
66
+ for (const message of file.messages) {
67
+ this.registerMessage(message, prefix, file.syntax, pending);
68
+ }
69
+ for (const e of file.enums) {
70
+ this.registerEnum(e, prefix);
71
+ }
72
+ }
73
+ for (const { type, ast, syntax } of pending) {
74
+ type.setFields(
75
+ ast.fields.map(field => {
76
+ const proto3 = syntax === 'proto3';
77
+ const repeated = field.rule === 'repeated' || field.keyType !== undefined;
78
+ const value = this.resolveValue(field.type, type.fullName);
79
+ const info: FieldInfo = {
80
+ ...value,
81
+ name: camelCase(field.name),
82
+ protoName: field.name,
83
+ number: field.number,
84
+ repeated,
85
+ packed: field.packed ?? (proto3 && repeated),
86
+ presence:
87
+ !repeated &&
88
+ (value.kind === 'message' || field.oneof !== undefined || field.rule === 'optional' || field.rule === 'required' || !proto3),
89
+ oneof: field.oneof,
90
+ map: field.keyType ? { key: this.mapKeyKind(field.keyType, type.fullName), value } : undefined,
91
+ };
92
+ return info;
93
+ }),
94
+ );
95
+ }
96
+ for (const file of files) {
97
+ const prefix = file.package ? `${file.package}.` : '';
98
+ for (const service of file.services) {
99
+ const fullName = prefix + service.name;
100
+ this.serviceMap.set(fullName, {
101
+ fullName,
102
+ methods: service.methods.map(method => ({
103
+ name: method.name,
104
+ jsName: method.name[0].toLowerCase() + method.name.slice(1),
105
+ path: `/${fullName}/${method.name}`,
106
+ requestType: this.resolveMessage(method.requestType, fullName),
107
+ responseType: this.resolveMessage(method.responseType, fullName),
108
+ requestStream: method.requestStream,
109
+ responseStream: method.responseStream,
110
+ })),
111
+ });
112
+ }
113
+ }
114
+ }
115
+
116
+ get services(): ServiceDefinition[] {
117
+ return [...this.serviceMap.values()];
118
+ }
119
+
120
+ service(name: string): ServiceDefinition {
121
+ return this.lookup(this.serviceMap, name, 'service');
122
+ }
123
+
124
+ message<T = any>(name: string): MessageType<T> {
125
+ const types = new Map([...this.types].filter(([, type]) => type instanceof MessageType)) as Map<string, MessageType>;
126
+ return this.lookup(types, name, 'message');
127
+ }
128
+
129
+ enum(name: string): EnumType {
130
+ const types = new Map([...this.types].filter(([, type]) => type instanceof EnumType)) as Map<string, EnumType>;
131
+ return this.lookup(types, name, 'enum');
132
+ }
133
+
134
+ protected lookup<V>(map: Map<string, V>, name: string, what: string): V {
135
+ const exact = map.get(name.replace(/^\./, ''));
136
+ if (exact) {
137
+ return exact;
138
+ }
139
+ const matches = [...map.keys()].filter(key => key.endsWith(`.${name}`));
140
+ const match = matches.length === 1 ? map.get(matches[0]) : undefined;
141
+ if (match) {
142
+ return match;
143
+ }
144
+ if (matches.length > 1) {
145
+ throw new Error(`The ${what} name '${name}' is ambiguous: ${matches.join(', ')}. Use the full name.`);
146
+ }
147
+ throw new Error(`No ${what} '${name}' in the .proto sources. ${what[0].toUpperCase() + what.slice(1)}s: ${[...map.keys()].join(', ') || 'none'}.`);
148
+ }
149
+
150
+ protected registerMessage(ast: MessageAst, prefix: string, syntax: ProtoFileAst['syntax'], pending: PendingMessage[]): void {
151
+ const type = new MessageType(prefix + ast.name);
152
+ this.register(type);
153
+ pending.push({ type, ast, syntax });
154
+ for (const nested of ast.messages) {
155
+ this.registerMessage(nested, `${type.fullName}.`, syntax, pending);
156
+ }
157
+ for (const e of ast.enums) {
158
+ this.registerEnum(e, `${type.fullName}.`);
159
+ }
160
+ }
161
+
162
+ protected registerEnum(ast: EnumAst, prefix: string): void {
163
+ this.register(new EnumType(prefix + ast.name, ast.values));
164
+ }
165
+
166
+ protected register(type: MessageType | EnumType): void {
167
+ if (this.types.has(type.fullName)) {
168
+ throw new Error(`The type ${type.fullName} is defined twice in the .proto sources.`);
169
+ }
170
+ this.types.set(type.fullName, type);
171
+ }
172
+
173
+ protected resolveValue(typeName: string, scope: string): ValueInfo {
174
+ if (SCALAR_KINDS.has(typeName)) {
175
+ return { kind: typeName as ScalarKind };
176
+ }
177
+ const type = this.resolve(typeName, scope);
178
+ return type instanceof MessageType ? { kind: 'message', messageType: type } : { kind: 'enum', enumType: type };
179
+ }
180
+
181
+ protected resolveMessage(typeName: string, scope: string): MessageType {
182
+ const type = this.resolve(typeName, scope);
183
+ if (!(type instanceof MessageType)) {
184
+ throw new Error(`${typeName}, used by ${scope}, is an enum; methods take and return messages.`);
185
+ }
186
+ return type;
187
+ }
188
+
189
+ protected mapKeyKind(typeName: string, scope: string): ScalarKind {
190
+ if (!SCALAR_KINDS.has(typeName) || typeName === 'double' || typeName === 'float' || typeName === 'bytes') {
191
+ throw new Error(`${typeName} cannot be a map key (in ${scope}); use an integer, bool or string type.`);
192
+ }
193
+ return typeName as ScalarKind;
194
+ }
195
+
196
+ /** Protobuf scoping: `.a.B` is absolute; otherwise the innermost enclosing scope that has the name wins. */
197
+ protected resolve(typeName: string, scope: string): MessageType | EnumType {
198
+ if (typeName.startsWith('.')) {
199
+ const type = this.types.get(typeName.slice(1));
200
+ if (type) {
201
+ return type;
202
+ }
203
+ } else {
204
+ const parts = scope.split('.');
205
+ for (let i = parts.length; i >= 0; i--) {
206
+ const type = this.types.get([...parts.slice(0, i), typeName].join('.'));
207
+ if (type) {
208
+ return type;
209
+ }
210
+ }
211
+ }
212
+ throw new Error(`Unknown type ${typeName} in ${scope}. If it is defined in an imported .proto file, pass that file's source to Proto.parse() too.`);
213
+ }
214
+ }
215
+
216
+ function camelCase(name: string): string {
217
+ return name.replace(/(?!^)_+([a-zA-Z0-9])/g, (_, c: string) => c.toUpperCase());
218
+ }
@@ -0,0 +1,40 @@
1
+ /**
2
+ * The well-known types of google/protobuf that services commonly import. Their messages are plain
3
+ * messages here: a Timestamp is `{ seconds: '1700000000', nanos: 0 }`, not a `Date`.
4
+ */
5
+ export const WELL_KNOWN_PROTOS: Readonly<Record<string, string>> = {
6
+ 'google/protobuf/empty.proto': `syntax = "proto3"; package google.protobuf;
7
+ message Empty {}`,
8
+ 'google/protobuf/timestamp.proto': `syntax = "proto3"; package google.protobuf;
9
+ message Timestamp { int64 seconds = 1; int32 nanos = 2; }`,
10
+ 'google/protobuf/duration.proto': `syntax = "proto3"; package google.protobuf;
11
+ message Duration { int64 seconds = 1; int32 nanos = 2; }`,
12
+ 'google/protobuf/any.proto': `syntax = "proto3"; package google.protobuf;
13
+ message Any { string type_url = 1; bytes value = 2; }`,
14
+ 'google/protobuf/field_mask.proto': `syntax = "proto3"; package google.protobuf;
15
+ message FieldMask { repeated string paths = 1; }`,
16
+ 'google/protobuf/wrappers.proto': `syntax = "proto3"; package google.protobuf;
17
+ message DoubleValue { double value = 1; }
18
+ message FloatValue { float value = 1; }
19
+ message Int64Value { int64 value = 1; }
20
+ message UInt64Value { uint64 value = 1; }
21
+ message Int32Value { int32 value = 1; }
22
+ message UInt32Value { uint32 value = 1; }
23
+ message BoolValue { bool value = 1; }
24
+ message StringValue { string value = 1; }
25
+ message BytesValue { bytes value = 1; }`,
26
+ 'google/protobuf/struct.proto': `syntax = "proto3"; package google.protobuf;
27
+ message Struct { map<string, Value> fields = 1; }
28
+ message Value {
29
+ oneof kind {
30
+ NullValue null_value = 1;
31
+ double number_value = 2;
32
+ string string_value = 3;
33
+ bool bool_value = 4;
34
+ Struct struct_value = 5;
35
+ ListValue list_value = 6;
36
+ }
37
+ }
38
+ enum NullValue { NULL_VALUE = 0; }
39
+ message ListValue { repeated Value values = 1; }`,
40
+ };
@@ -0,0 +1,88 @@
1
+ import { afterEach, describe, expect, it } from 'bun:test';
2
+ import { Autowired, Component } from '@celljs/core';
3
+ import { Application } from '@celljs/core/lib/common/application/application-protocol';
4
+ import { autoBind } from '@celljs/core/lib/common/container/auto-bind';
5
+ import { Container } from '@celljs/core/lib/common/container/container';
6
+ import { ContainerProvider } from '@celljs/core/lib/common/container/container-provider';
7
+ // Loaded in the order of the backend entry the CLI generates: core's static modules, then this package's module.
8
+ import coreCommonStatic from '@celljs/core/lib/common/static-module';
9
+ import { currentThis } from '@celljs/core/lib/common/utils';
10
+ import coreNodeStatic from '@celljs/core/lib/node/static-module';
11
+ import { GrpcError, GrpcStatus } from '../call/grpc-status';
12
+ import { GrpcChannel } from '../client/grpc-channel';
13
+ import grpcModule from '../module';
14
+ import { Proto } from '../proto/proto';
15
+ import { TEST_PROTO } from '../test/test-protos';
16
+ import { GrpcServerLifecycle } from './grpc-server-lifecycle';
17
+ import { GrpcService } from './grpc-service';
18
+
19
+ const Greeter = Proto.parse(TEST_PROTO).service('Greeter');
20
+
21
+ let app: Application | undefined;
22
+
23
+ /** The error a call fails with. (Not `expect(call).rejects`: under Bun 1.4 it breaks HTTP/2 streams of the same process.) */
24
+ async function failure(call: Promise<unknown>): Promise<GrpcError> {
25
+ try {
26
+ await call;
27
+ } catch (error) {
28
+ return error as GrpcError;
29
+ }
30
+ throw new Error('The call did not fail');
31
+ }
32
+ afterEach(async () => {
33
+ await app?.stop();
34
+ app = undefined;
35
+ });
36
+
37
+ async function start(server: Record<string, unknown> = {}) {
38
+ currentThis.cellProps = { logger: { level: 'error' }, grpc: { server: { enabled: true, port: 0, host: '127.0.0.1', ...server } } };
39
+ const container = new Container(coreCommonStatic, coreNodeStatic, grpcModule, autoBind());
40
+ ContainerProvider.set(container);
41
+ app = container.get<Application>(Application);
42
+ await app.start();
43
+ return container.get(GrpcServerLifecycle);
44
+ }
45
+
46
+ describe('GrpcService in an application', () => {
47
+ it('serves the @GrpcService components on the configured port, with their dependencies injected', async () => {
48
+ @Component()
49
+ class Names {
50
+ format(name: string) {
51
+ return name.toUpperCase();
52
+ }
53
+ }
54
+
55
+ @GrpcService(Greeter)
56
+ class GreeterService {
57
+ @Autowired(Names)
58
+ protected readonly names: Names;
59
+
60
+ sayHello({ name }: { name: string }) {
61
+ if (!name) {
62
+ throw new GrpcError(GrpcStatus.INVALID_ARGUMENT, 'name is required');
63
+ }
64
+ return { message: `Hello ${this.names.format(name)}` };
65
+ }
66
+ }
67
+
68
+ const lifecycle = await start();
69
+ expect(lifecycle.port).toBeGreaterThan(0);
70
+ const channel = new GrpcChannel(`127.0.0.1:${lifecycle.port}`);
71
+ const greeter: any = channel.createClient(Greeter);
72
+ expect(await greeter.sayHello({ name: 'cell' })).toMatchObject({ message: 'Hello CELL' });
73
+ expect((await failure(greeter.sayHello({}))).message).toBe('INVALID_ARGUMENT: name is required');
74
+ expect((await failure(greeter.chat([])[Symbol.asyncIterator]().next())).code).toBe(GrpcStatus.UNIMPLEMENTED);
75
+
76
+ // Stopping the application closes the server.
77
+ await app?.stop();
78
+ app = undefined;
79
+ expect((await failure(greeter.sayHello({ name: 'again' }))).code).toBe(GrpcStatus.UNAVAILABLE);
80
+ channel.close();
81
+ expect([GreeterService, Names]).toHaveLength(2);
82
+ });
83
+
84
+ it('starts no server when disabled', async () => {
85
+ const lifecycle = await start({ enabled: false });
86
+ expect(lifecycle.server).toBeUndefined();
87
+ });
88
+ });
@@ -0,0 +1,56 @@
1
+ import { type Application, ApplicationLifecycle, Autowired, Component, getTargetClass, Logger, Optional, Value } from '@celljs/core';
2
+ import { GrpcServer } from './grpc-server';
3
+ import { GRPC_SERVICE, GrpcServiceUtil } from './grpc-service';
4
+
5
+ export interface GrpcServerConfig {
6
+ enabled?: boolean;
7
+ port?: number;
8
+ host?: string;
9
+ maxReceiveMessageSize?: number;
10
+ }
11
+
12
+ /**
13
+ * Starts the gRPC server of the application with its {@link GrpcService} components (none: no server)
14
+ * and closes it when the application stops. `port` is the bound port once started.
15
+ */
16
+ @Component(ApplicationLifecycle)
17
+ export class GrpcServerLifecycle implements ApplicationLifecycle<Application> {
18
+ @Autowired(GRPC_SERVICE)
19
+ @Optional()
20
+ protected readonly services: object[] = [];
21
+
22
+ @Value('grpc.server')
23
+ protected readonly config?: GrpcServerConfig;
24
+
25
+ @Autowired(Logger)
26
+ protected readonly logger: Logger;
27
+
28
+ server?: GrpcServer;
29
+ port?: number;
30
+
31
+ async onStart(): Promise<void> {
32
+ const config = this.config ?? {};
33
+ if (this.services.length === 0 || config.enabled === false) {
34
+ return;
35
+ }
36
+ const server = new GrpcServer({
37
+ maxReceiveMessageSize: config.maxReceiveMessageSize,
38
+ onError: (error, method) => this.logger.error(error, `gRPC ${method.path}`),
39
+ });
40
+ for (const service of this.services) {
41
+ const definition = GrpcServiceUtil.getService(getTargetClass(service));
42
+ if (definition) {
43
+ server.addService(definition, service);
44
+ }
45
+ }
46
+ const host = config.host ?? '127.0.0.1';
47
+ this.port = await server.listen(config.port ?? 50051, host);
48
+ this.server = server;
49
+ this.logger.info(`gRPC serve ${host}:${this.port}`);
50
+ }
51
+
52
+ onStop(): void {
53
+ this.server?.close(true);
54
+ this.server = undefined;
55
+ }
56
+ }