1 | "use strict";
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 | Object.defineProperty(exports, "__esModule", { value: true });
|
19 | exports.Server = void 0;
|
20 | const http2 = require("http2");
|
21 | const constants_1 = require("./constants");
|
22 | const server_call_1 = require("./server-call");
|
23 | const server_credentials_1 = require("./server-credentials");
|
24 | const resolver_1 = require("./resolver");
|
25 | const logging = require("./logging");
|
26 | const subchannel_address_1 = require("./subchannel-address");
|
27 | const uri_parser_1 = require("./uri-parser");
|
28 | const channelz_1 = require("./channelz");
|
29 | const { HTTP2_HEADER_PATH } = http2.constants;
|
30 | const TRACER_NAME = 'server';
|
31 | function noop() { }
|
32 | function getUnimplementedStatusResponse(methodName) {
|
33 | return {
|
34 | code: constants_1.Status.UNIMPLEMENTED,
|
35 | details: `The server does not implement the method ${methodName}`,
|
36 | };
|
37 | }
|
38 | function getDefaultHandler(handlerType, methodName) {
|
39 | const unimplementedStatusResponse = getUnimplementedStatusResponse(methodName);
|
40 | switch (handlerType) {
|
41 | case 'unary':
|
42 | return (call, callback) => {
|
43 | callback(unimplementedStatusResponse, null);
|
44 | };
|
45 | case 'clientStream':
|
46 | return (call, callback) => {
|
47 | callback(unimplementedStatusResponse, null);
|
48 | };
|
49 | case 'serverStream':
|
50 | return (call) => {
|
51 | call.emit('error', unimplementedStatusResponse);
|
52 | };
|
53 | case 'bidi':
|
54 | return (call) => {
|
55 | call.emit('error', unimplementedStatusResponse);
|
56 | };
|
57 | default:
|
58 | throw new Error(`Invalid handlerType ${handlerType}`);
|
59 | }
|
60 | }
|
61 | class Server {
|
62 | constructor(options) {
|
63 | this.http2ServerList = [];
|
64 | this.handlers = new Map();
|
65 | this.sessions = new Map();
|
66 | this.started = false;
|
67 | this.serverAddressString = 'null';
|
68 |
|
69 | this.channelzEnabled = true;
|
70 | this.channelzTrace = new channelz_1.ChannelzTrace();
|
71 | this.callTracker = new channelz_1.ChannelzCallTracker();
|
72 | this.listenerChildrenTracker = new channelz_1.ChannelzChildrenTracker();
|
73 | this.sessionChildrenTracker = new channelz_1.ChannelzChildrenTracker();
|
74 | this.options = options !== null && options !== void 0 ? options : {};
|
75 | if (this.options['grpc.enable_channelz'] === 0) {
|
76 | this.channelzEnabled = false;
|
77 | }
|
78 | this.channelzRef = channelz_1.registerChannelzServer(() => this.getChannelzInfo(), this.channelzEnabled);
|
79 | if (this.channelzEnabled) {
|
80 | this.channelzTrace.addTrace('CT_INFO', 'Server created');
|
81 | }
|
82 | this.trace('Server constructed');
|
83 | }
|
84 | getChannelzInfo() {
|
85 | return {
|
86 | trace: this.channelzTrace,
|
87 | callTracker: this.callTracker,
|
88 | listenerChildren: this.listenerChildrenTracker.getChildLists(),
|
89 | sessionChildren: this.sessionChildrenTracker.getChildLists()
|
90 | };
|
91 | }
|
92 | getChannelzSessionInfoGetter(session) {
|
93 | return () => {
|
94 | var _a, _b, _c;
|
95 | const sessionInfo = this.sessions.get(session);
|
96 | const sessionSocket = session.socket;
|
97 | const remoteAddress = sessionSocket.remoteAddress ? subchannel_address_1.stringToSubchannelAddress(sessionSocket.remoteAddress, sessionSocket.remotePort) : null;
|
98 | const localAddress = sessionSocket.localAddress ? subchannel_address_1.stringToSubchannelAddress(sessionSocket.localAddress, sessionSocket.localPort) : null;
|
99 | let tlsInfo;
|
100 | if (session.encrypted) {
|
101 | const tlsSocket = sessionSocket;
|
102 | const cipherInfo = tlsSocket.getCipher();
|
103 | const certificate = tlsSocket.getCertificate();
|
104 | const peerCertificate = tlsSocket.getPeerCertificate();
|
105 | tlsInfo = {
|
106 | cipherSuiteStandardName: (_a = cipherInfo.standardName) !== null && _a !== void 0 ? _a : null,
|
107 | cipherSuiteOtherName: cipherInfo.standardName ? null : cipherInfo.name,
|
108 | localCertificate: (certificate && 'raw' in certificate) ? certificate.raw : null,
|
109 | remoteCertificate: (peerCertificate && 'raw' in peerCertificate) ? peerCertificate.raw : null
|
110 | };
|
111 | }
|
112 | else {
|
113 | tlsInfo = null;
|
114 | }
|
115 | const socketInfo = {
|
116 | remoteAddress: remoteAddress,
|
117 | localAddress: localAddress,
|
118 | security: tlsInfo,
|
119 | remoteName: null,
|
120 | streamsStarted: sessionInfo.streamTracker.callsStarted,
|
121 | streamsSucceeded: sessionInfo.streamTracker.callsSucceeded,
|
122 | streamsFailed: sessionInfo.streamTracker.callsFailed,
|
123 | messagesSent: sessionInfo.messagesSent,
|
124 | messagesReceived: sessionInfo.messagesReceived,
|
125 | keepAlivesSent: 0,
|
126 | lastLocalStreamCreatedTimestamp: null,
|
127 | lastRemoteStreamCreatedTimestamp: sessionInfo.streamTracker.lastCallStartedTimestamp,
|
128 | lastMessageSentTimestamp: sessionInfo.lastMessageSentTimestamp,
|
129 | lastMessageReceivedTimestamp: sessionInfo.lastMessageReceivedTimestamp,
|
130 | localFlowControlWindow: (_b = session.state.localWindowSize) !== null && _b !== void 0 ? _b : null,
|
131 | remoteFlowControlWindow: (_c = session.state.remoteWindowSize) !== null && _c !== void 0 ? _c : null
|
132 | };
|
133 | return socketInfo;
|
134 | };
|
135 | }
|
136 | trace(text) {
|
137 | logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, '(' + this.channelzRef.id + ') ' + text);
|
138 | }
|
139 | addProtoService() {
|
140 | throw new Error('Not implemented. Use addService() instead');
|
141 | }
|
142 | addService(service, implementation) {
|
143 | if (service === null ||
|
144 | typeof service !== 'object' ||
|
145 | implementation === null ||
|
146 | typeof implementation !== 'object') {
|
147 | throw new Error('addService() requires two objects as arguments');
|
148 | }
|
149 | const serviceKeys = Object.keys(service);
|
150 | if (serviceKeys.length === 0) {
|
151 | throw new Error('Cannot add an empty service to a server');
|
152 | }
|
153 | serviceKeys.forEach((name) => {
|
154 | const attrs = service[name];
|
155 | let methodType;
|
156 | if (attrs.requestStream) {
|
157 | if (attrs.responseStream) {
|
158 | methodType = 'bidi';
|
159 | }
|
160 | else {
|
161 | methodType = 'clientStream';
|
162 | }
|
163 | }
|
164 | else {
|
165 | if (attrs.responseStream) {
|
166 | methodType = 'serverStream';
|
167 | }
|
168 | else {
|
169 | methodType = 'unary';
|
170 | }
|
171 | }
|
172 | let implFn = implementation[name];
|
173 | let impl;
|
174 | if (implFn === undefined && typeof attrs.originalName === 'string') {
|
175 | implFn = implementation[attrs.originalName];
|
176 | }
|
177 | if (implFn !== undefined) {
|
178 | impl = implFn.bind(implementation);
|
179 | }
|
180 | else {
|
181 | impl = getDefaultHandler(methodType, name);
|
182 | }
|
183 | const success = this.register(attrs.path, impl, attrs.responseSerialize, attrs.requestDeserialize, methodType);
|
184 | if (success === false) {
|
185 | throw new Error(`Method handler for ${attrs.path} already provided.`);
|
186 | }
|
187 | });
|
188 | }
|
189 | removeService(service) {
|
190 | if (service === null || typeof service !== 'object') {
|
191 | throw new Error('removeService() requires object as argument');
|
192 | }
|
193 | const serviceKeys = Object.keys(service);
|
194 | serviceKeys.forEach((name) => {
|
195 | const attrs = service[name];
|
196 | this.unregister(attrs.path);
|
197 | });
|
198 | }
|
199 | bind(port, creds) {
|
200 | throw new Error('Not implemented. Use bindAsync() instead');
|
201 | }
|
202 | bindAsync(port, creds, callback) {
|
203 | if (this.started === true) {
|
204 | throw new Error('server is already started');
|
205 | }
|
206 | if (typeof port !== 'string') {
|
207 | throw new TypeError('port must be a string');
|
208 | }
|
209 | if (creds === null || !(creds instanceof server_credentials_1.ServerCredentials)) {
|
210 | throw new TypeError('creds must be a ServerCredentials object');
|
211 | }
|
212 | if (typeof callback !== 'function') {
|
213 | throw new TypeError('callback must be a function');
|
214 | }
|
215 | const initialPortUri = uri_parser_1.parseUri(port);
|
216 | if (initialPortUri === null) {
|
217 | throw new Error(`Could not parse port "${port}"`);
|
218 | }
|
219 | const portUri = resolver_1.mapUriDefaultScheme(initialPortUri);
|
220 | if (portUri === null) {
|
221 | throw new Error(`Could not get a default scheme for port "${port}"`);
|
222 | }
|
223 | const serverOptions = {
|
224 | maxSendHeaderBlockLength: Number.MAX_SAFE_INTEGER,
|
225 | };
|
226 | if ('grpc-node.max_session_memory' in this.options) {
|
227 | serverOptions.maxSessionMemory = this.options['grpc-node.max_session_memory'];
|
228 | }
|
229 | else {
|
230 | |
231 |
|
232 |
|
233 |
|
234 | serverOptions.maxSessionMemory = Number.MAX_SAFE_INTEGER;
|
235 | }
|
236 | if ('grpc.max_concurrent_streams' in this.options) {
|
237 | serverOptions.settings = {
|
238 | maxConcurrentStreams: this.options['grpc.max_concurrent_streams'],
|
239 | };
|
240 | }
|
241 | const deferredCallback = (error, port) => {
|
242 | process.nextTick(() => callback(error, port));
|
243 | };
|
244 | const setupServer = () => {
|
245 | let http2Server;
|
246 | if (creds._isSecure()) {
|
247 | const secureServerOptions = Object.assign(serverOptions, creds._getSettings());
|
248 | http2Server = http2.createSecureServer(secureServerOptions);
|
249 | http2Server.on('secureConnection', (socket) => {
|
250 | |
251 |
|
252 | socket.on('error', (e) => {
|
253 | this.trace('An incoming TLS connection closed with error: ' + e.message);
|
254 | });
|
255 | });
|
256 | }
|
257 | else {
|
258 | http2Server = http2.createServer(serverOptions);
|
259 | }
|
260 | http2Server.setTimeout(0, noop);
|
261 | this._setupHandlers(http2Server);
|
262 | return http2Server;
|
263 | };
|
264 | const bindSpecificPort = (addressList, portNum, previousCount) => {
|
265 | if (addressList.length === 0) {
|
266 | return Promise.resolve({ port: portNum, count: previousCount });
|
267 | }
|
268 | return Promise.all(addressList.map((address) => {
|
269 | this.trace('Attempting to bind ' + subchannel_address_1.subchannelAddressToString(address));
|
270 | let addr;
|
271 | if (subchannel_address_1.isTcpSubchannelAddress(address)) {
|
272 | addr = {
|
273 | host: address.host,
|
274 | port: portNum,
|
275 | };
|
276 | }
|
277 | else {
|
278 | addr = address;
|
279 | }
|
280 | const http2Server = setupServer();
|
281 | return new Promise((resolve, reject) => {
|
282 | const onError = (err) => {
|
283 | this.trace('Failed to bind ' + subchannel_address_1.subchannelAddressToString(address) + ' with error ' + err.message);
|
284 | resolve(err);
|
285 | };
|
286 | http2Server.once('error', onError);
|
287 | http2Server.listen(addr, () => {
|
288 | const boundAddress = http2Server.address();
|
289 | let boundSubchannelAddress;
|
290 | if (typeof boundAddress === 'string') {
|
291 | boundSubchannelAddress = {
|
292 | path: boundAddress
|
293 | };
|
294 | }
|
295 | else {
|
296 | boundSubchannelAddress = {
|
297 | host: boundAddress.address,
|
298 | port: boundAddress.port
|
299 | };
|
300 | }
|
301 | let channelzRef;
|
302 | channelzRef = channelz_1.registerChannelzSocket(subchannel_address_1.subchannelAddressToString(boundSubchannelAddress), () => {
|
303 | return {
|
304 | localAddress: boundSubchannelAddress,
|
305 | remoteAddress: null,
|
306 | security: null,
|
307 | remoteName: null,
|
308 | streamsStarted: 0,
|
309 | streamsSucceeded: 0,
|
310 | streamsFailed: 0,
|
311 | messagesSent: 0,
|
312 | messagesReceived: 0,
|
313 | keepAlivesSent: 0,
|
314 | lastLocalStreamCreatedTimestamp: null,
|
315 | lastRemoteStreamCreatedTimestamp: null,
|
316 | lastMessageSentTimestamp: null,
|
317 | lastMessageReceivedTimestamp: null,
|
318 | localFlowControlWindow: null,
|
319 | remoteFlowControlWindow: null
|
320 | };
|
321 | }, this.channelzEnabled);
|
322 | if (this.channelzEnabled) {
|
323 | this.listenerChildrenTracker.refChild(channelzRef);
|
324 | }
|
325 | this.http2ServerList.push({ server: http2Server, channelzRef: channelzRef });
|
326 | this.trace('Successfully bound ' + subchannel_address_1.subchannelAddressToString(boundSubchannelAddress));
|
327 | resolve('port' in boundSubchannelAddress ? boundSubchannelAddress.port : portNum);
|
328 | http2Server.removeListener('error', onError);
|
329 | });
|
330 | });
|
331 | })).then((results) => {
|
332 | let count = 0;
|
333 | for (const result of results) {
|
334 | if (typeof result === 'number') {
|
335 | count += 1;
|
336 | if (result !== portNum) {
|
337 | throw new Error('Invalid state: multiple port numbers added from single address');
|
338 | }
|
339 | }
|
340 | }
|
341 | return {
|
342 | port: portNum,
|
343 | count: count + previousCount,
|
344 | };
|
345 | });
|
346 | };
|
347 | const bindWildcardPort = (addressList) => {
|
348 | if (addressList.length === 0) {
|
349 | return Promise.resolve({ port: 0, count: 0 });
|
350 | }
|
351 | const address = addressList[0];
|
352 | const http2Server = setupServer();
|
353 | return new Promise((resolve, reject) => {
|
354 | const onError = (err) => {
|
355 | this.trace('Failed to bind ' + subchannel_address_1.subchannelAddressToString(address) + ' with error ' + err.message);
|
356 | resolve(bindWildcardPort(addressList.slice(1)));
|
357 | };
|
358 | http2Server.once('error', onError);
|
359 | http2Server.listen(address, () => {
|
360 | const boundAddress = http2Server.address();
|
361 | const boundSubchannelAddress = {
|
362 | host: boundAddress.address,
|
363 | port: boundAddress.port
|
364 | };
|
365 | let channelzRef;
|
366 | channelzRef = channelz_1.registerChannelzSocket(subchannel_address_1.subchannelAddressToString(boundSubchannelAddress), () => {
|
367 | return {
|
368 | localAddress: boundSubchannelAddress,
|
369 | remoteAddress: null,
|
370 | security: null,
|
371 | remoteName: null,
|
372 | streamsStarted: 0,
|
373 | streamsSucceeded: 0,
|
374 | streamsFailed: 0,
|
375 | messagesSent: 0,
|
376 | messagesReceived: 0,
|
377 | keepAlivesSent: 0,
|
378 | lastLocalStreamCreatedTimestamp: null,
|
379 | lastRemoteStreamCreatedTimestamp: null,
|
380 | lastMessageSentTimestamp: null,
|
381 | lastMessageReceivedTimestamp: null,
|
382 | localFlowControlWindow: null,
|
383 | remoteFlowControlWindow: null
|
384 | };
|
385 | }, this.channelzEnabled);
|
386 | if (this.channelzEnabled) {
|
387 | this.listenerChildrenTracker.refChild(channelzRef);
|
388 | }
|
389 | this.http2ServerList.push({ server: http2Server, channelzRef: channelzRef });
|
390 | this.trace('Successfully bound ' + subchannel_address_1.subchannelAddressToString(boundSubchannelAddress));
|
391 | resolve(bindSpecificPort(addressList.slice(1), boundAddress.port, 1));
|
392 | http2Server.removeListener('error', onError);
|
393 | });
|
394 | });
|
395 | };
|
396 | const resolverListener = {
|
397 | onSuccessfulResolution: (addressList, serviceConfig, serviceConfigError) => {
|
398 |
|
399 | resolverListener.onSuccessfulResolution = () => { };
|
400 | if (addressList.length === 0) {
|
401 | deferredCallback(new Error(`No addresses resolved for port ${port}`), 0);
|
402 | return;
|
403 | }
|
404 | let bindResultPromise;
|
405 | if (subchannel_address_1.isTcpSubchannelAddress(addressList[0])) {
|
406 | if (addressList[0].port === 0) {
|
407 | bindResultPromise = bindWildcardPort(addressList);
|
408 | }
|
409 | else {
|
410 | bindResultPromise = bindSpecificPort(addressList, addressList[0].port, 0);
|
411 | }
|
412 | }
|
413 | else {
|
414 |
|
415 | bindResultPromise = bindSpecificPort(addressList, 1, 0);
|
416 | }
|
417 | bindResultPromise.then((bindResult) => {
|
418 | if (bindResult.count === 0) {
|
419 | const errorString = `No address added out of total ${addressList.length} resolved`;
|
420 | logging.log(constants_1.LogVerbosity.ERROR, errorString);
|
421 | deferredCallback(new Error(errorString), 0);
|
422 | }
|
423 | else {
|
424 | if (bindResult.count < addressList.length) {
|
425 | logging.log(constants_1.LogVerbosity.INFO, `WARNING Only ${bindResult.count} addresses added out of total ${addressList.length} resolved`);
|
426 | }
|
427 | deferredCallback(null, bindResult.port);
|
428 | }
|
429 | }, (error) => {
|
430 | const errorString = `No address added out of total ${addressList.length} resolved`;
|
431 | logging.log(constants_1.LogVerbosity.ERROR, errorString);
|
432 | deferredCallback(new Error(errorString), 0);
|
433 | });
|
434 | },
|
435 | onError: (error) => {
|
436 | deferredCallback(new Error(error.details), 0);
|
437 | },
|
438 | };
|
439 | const resolver = resolver_1.createResolver(portUri, resolverListener, this.options);
|
440 | resolver.updateResolution();
|
441 | }
|
442 | forceShutdown() {
|
443 |
|
444 | for (const { server: http2Server, channelzRef: ref } of this.http2ServerList) {
|
445 | if (http2Server.listening) {
|
446 | http2Server.close(() => {
|
447 | if (this.channelzEnabled) {
|
448 | this.listenerChildrenTracker.unrefChild(ref);
|
449 | channelz_1.unregisterChannelzRef(ref);
|
450 | }
|
451 | });
|
452 | }
|
453 | }
|
454 | this.started = false;
|
455 |
|
456 |
|
457 | this.sessions.forEach((channelzInfo, session) => {
|
458 |
|
459 |
|
460 |
|
461 | session.destroy(http2.constants.NGHTTP2_CANCEL);
|
462 | });
|
463 | this.sessions.clear();
|
464 | if (this.channelzEnabled) {
|
465 | channelz_1.unregisterChannelzRef(this.channelzRef);
|
466 | }
|
467 | }
|
468 | register(name, handler, serialize, deserialize, type) {
|
469 | if (this.handlers.has(name)) {
|
470 | return false;
|
471 | }
|
472 | this.handlers.set(name, {
|
473 | func: handler,
|
474 | serialize,
|
475 | deserialize,
|
476 | type,
|
477 | path: name,
|
478 | });
|
479 | return true;
|
480 | }
|
481 | unregister(name) {
|
482 | return this.handlers.delete(name);
|
483 | }
|
484 | start() {
|
485 | if (this.http2ServerList.length === 0 ||
|
486 | this.http2ServerList.every(({ server: http2Server }) => http2Server.listening !== true)) {
|
487 | throw new Error('server must be bound in order to start');
|
488 | }
|
489 | if (this.started === true) {
|
490 | throw new Error('server is already started');
|
491 | }
|
492 | if (this.channelzEnabled) {
|
493 | this.channelzTrace.addTrace('CT_INFO', 'Starting');
|
494 | }
|
495 | this.started = true;
|
496 | }
|
497 | tryShutdown(callback) {
|
498 | const wrappedCallback = (error) => {
|
499 | if (this.channelzEnabled) {
|
500 | channelz_1.unregisterChannelzRef(this.channelzRef);
|
501 | }
|
502 | callback(error);
|
503 | };
|
504 | let pendingChecks = 0;
|
505 | function maybeCallback() {
|
506 | pendingChecks--;
|
507 | if (pendingChecks === 0) {
|
508 | wrappedCallback();
|
509 | }
|
510 | }
|
511 |
|
512 | this.started = false;
|
513 | for (const { server: http2Server, channelzRef: ref } of this.http2ServerList) {
|
514 | if (http2Server.listening) {
|
515 | pendingChecks++;
|
516 | http2Server.close(() => {
|
517 | if (this.channelzEnabled) {
|
518 | this.listenerChildrenTracker.unrefChild(ref);
|
519 | channelz_1.unregisterChannelzRef(ref);
|
520 | }
|
521 | maybeCallback();
|
522 | });
|
523 | }
|
524 | }
|
525 | this.sessions.forEach((channelzInfo, session) => {
|
526 | if (!session.closed) {
|
527 | pendingChecks += 1;
|
528 | session.close(maybeCallback);
|
529 | }
|
530 | });
|
531 | if (pendingChecks === 0) {
|
532 | wrappedCallback();
|
533 | }
|
534 | }
|
535 | addHttp2Port() {
|
536 | throw new Error('Not yet implemented');
|
537 | }
|
538 | |
539 |
|
540 |
|
541 |
|
542 |
|
543 | getChannelzRef() {
|
544 | return this.channelzRef;
|
545 | }
|
546 | _verifyContentType(stream, headers) {
|
547 | const contentType = headers[http2.constants.HTTP2_HEADER_CONTENT_TYPE];
|
548 | if (typeof contentType !== 'string' ||
|
549 | !contentType.startsWith('application/grpc')) {
|
550 | stream.respond({
|
551 | [http2.constants.HTTP2_HEADER_STATUS]: http2.constants.HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE,
|
552 | }, { endStream: true });
|
553 | return false;
|
554 | }
|
555 | return true;
|
556 | }
|
557 | _retrieveHandler(headers) {
|
558 | const path = headers[HTTP2_HEADER_PATH];
|
559 | this.trace('Received call to method ' +
|
560 | path +
|
561 | ' at address ' +
|
562 | this.serverAddressString);
|
563 | const handler = this.handlers.get(path);
|
564 | if (handler === undefined) {
|
565 | this.trace('No handler registered for method ' +
|
566 | path +
|
567 | '. Sending UNIMPLEMENTED status.');
|
568 | throw getUnimplementedStatusResponse(path);
|
569 | }
|
570 | return handler;
|
571 | }
|
572 | _respondWithError(err, stream, channelzSessionInfo = null) {
|
573 | const call = new server_call_1.Http2ServerCallStream(stream, null, this.options);
|
574 | if (err.code === undefined) {
|
575 | err.code = constants_1.Status.INTERNAL;
|
576 | }
|
577 | if (this.channelzEnabled) {
|
578 | this.callTracker.addCallFailed();
|
579 | channelzSessionInfo === null || channelzSessionInfo === void 0 ? void 0 : channelzSessionInfo.streamTracker.addCallFailed();
|
580 | }
|
581 | call.sendError(err);
|
582 | }
|
583 | _channelzHandler(stream, headers) {
|
584 | const channelzSessionInfo = this.sessions.get(stream.session);
|
585 | this.callTracker.addCallStarted();
|
586 | channelzSessionInfo === null || channelzSessionInfo === void 0 ? void 0 : channelzSessionInfo.streamTracker.addCallStarted();
|
587 | if (!this._verifyContentType(stream, headers)) {
|
588 | this.callTracker.addCallFailed();
|
589 | channelzSessionInfo === null || channelzSessionInfo === void 0 ? void 0 : channelzSessionInfo.streamTracker.addCallFailed();
|
590 | return;
|
591 | }
|
592 | let handler;
|
593 | try {
|
594 | handler = this._retrieveHandler(headers);
|
595 | }
|
596 | catch (err) {
|
597 | this._respondWithError(err, stream, channelzSessionInfo);
|
598 | return;
|
599 | }
|
600 | const call = new server_call_1.Http2ServerCallStream(stream, handler, this.options);
|
601 | call.once('callEnd', (code) => {
|
602 | if (code === constants_1.Status.OK) {
|
603 | this.callTracker.addCallSucceeded();
|
604 | }
|
605 | else {
|
606 | this.callTracker.addCallFailed();
|
607 | }
|
608 | });
|
609 | if (channelzSessionInfo) {
|
610 | call.once('streamEnd', (success) => {
|
611 | if (success) {
|
612 | channelzSessionInfo.streamTracker.addCallSucceeded();
|
613 | }
|
614 | else {
|
615 | channelzSessionInfo.streamTracker.addCallFailed();
|
616 | }
|
617 | });
|
618 | call.on('sendMessage', () => {
|
619 | channelzSessionInfo.messagesSent += 1;
|
620 | channelzSessionInfo.lastMessageSentTimestamp = new Date();
|
621 | });
|
622 | call.on('receiveMessage', () => {
|
623 | channelzSessionInfo.messagesReceived += 1;
|
624 | channelzSessionInfo.lastMessageReceivedTimestamp = new Date();
|
625 | });
|
626 | }
|
627 | if (!this._runHandlerForCall(call, handler, headers)) {
|
628 | this.callTracker.addCallFailed();
|
629 | channelzSessionInfo === null || channelzSessionInfo === void 0 ? void 0 : channelzSessionInfo.streamTracker.addCallFailed();
|
630 | call.sendError({
|
631 | code: constants_1.Status.INTERNAL,
|
632 | details: `Unknown handler type: ${handler.type}`
|
633 | });
|
634 | }
|
635 | }
|
636 | _streamHandler(stream, headers) {
|
637 | if (this._verifyContentType(stream, headers) !== true) {
|
638 | return;
|
639 | }
|
640 | let handler;
|
641 | try {
|
642 | handler = this._retrieveHandler(headers);
|
643 | }
|
644 | catch (err) {
|
645 | this._respondWithError(err, stream, null);
|
646 | return;
|
647 | }
|
648 | const call = new server_call_1.Http2ServerCallStream(stream, handler, this.options);
|
649 | if (!this._runHandlerForCall(call, handler, headers)) {
|
650 | call.sendError({
|
651 | code: constants_1.Status.INTERNAL,
|
652 | details: `Unknown handler type: ${handler.type}`
|
653 | });
|
654 | }
|
655 | }
|
656 | _runHandlerForCall(call, handler, headers) {
|
657 | var _a;
|
658 | const metadata = call.receiveMetadata(headers);
|
659 | const encoding = (_a = metadata.get('grpc-encoding')[0]) !== null && _a !== void 0 ? _a : 'identity';
|
660 | metadata.remove('grpc-encoding');
|
661 | const { type } = handler;
|
662 | if (type === 'unary') {
|
663 | handleUnary(call, handler, metadata, encoding);
|
664 | }
|
665 | else if (type === 'clientStream') {
|
666 | handleClientStreaming(call, handler, metadata, encoding);
|
667 | }
|
668 | else if (type === 'serverStream') {
|
669 | handleServerStreaming(call, handler, metadata, encoding);
|
670 | }
|
671 | else if (type === 'bidi') {
|
672 | handleBidiStreaming(call, handler, metadata, encoding);
|
673 | }
|
674 | else {
|
675 | return false;
|
676 | }
|
677 | return true;
|
678 | }
|
679 | _setupHandlers(http2Server) {
|
680 | if (http2Server === null) {
|
681 | return;
|
682 | }
|
683 | const serverAddress = http2Server.address();
|
684 | let serverAddressString = 'null';
|
685 | if (serverAddress) {
|
686 | if (typeof serverAddress === 'string') {
|
687 | serverAddressString = serverAddress;
|
688 | }
|
689 | else {
|
690 | serverAddressString =
|
691 | serverAddress.address + ':' + serverAddress.port;
|
692 | }
|
693 | }
|
694 | this.serverAddressString = serverAddressString;
|
695 | const handler = this.channelzEnabled
|
696 | ? this._channelzHandler
|
697 | : this._streamHandler;
|
698 | http2Server.on('stream', handler.bind(this));
|
699 | http2Server.on('session', (session) => {
|
700 | var _a;
|
701 | if (!this.started) {
|
702 | session.destroy();
|
703 | return;
|
704 | }
|
705 | let channelzRef;
|
706 | channelzRef = channelz_1.registerChannelzSocket((_a = session.socket.remoteAddress) !== null && _a !== void 0 ? _a : 'unknown', this.getChannelzSessionInfoGetter(session), this.channelzEnabled);
|
707 | const channelzSessionInfo = {
|
708 | ref: channelzRef,
|
709 | streamTracker: new channelz_1.ChannelzCallTracker(),
|
710 | messagesSent: 0,
|
711 | messagesReceived: 0,
|
712 | lastMessageSentTimestamp: null,
|
713 | lastMessageReceivedTimestamp: null
|
714 | };
|
715 | this.sessions.set(session, channelzSessionInfo);
|
716 | const clientAddress = session.socket.remoteAddress;
|
717 | if (this.channelzEnabled) {
|
718 | this.channelzTrace.addTrace('CT_INFO', 'Connection established by client ' + clientAddress);
|
719 | this.sessionChildrenTracker.refChild(channelzRef);
|
720 | }
|
721 | session.on('close', () => {
|
722 | if (this.channelzEnabled) {
|
723 | this.channelzTrace.addTrace('CT_INFO', 'Connection dropped by client ' + clientAddress);
|
724 | this.sessionChildrenTracker.unrefChild(channelzRef);
|
725 | channelz_1.unregisterChannelzRef(channelzRef);
|
726 | }
|
727 | this.sessions.delete(session);
|
728 | });
|
729 | });
|
730 | }
|
731 | }
|
732 | exports.Server = Server;
|
733 | function handleUnary(call, handler, metadata, encoding) {
|
734 | call.receiveUnaryMessage(encoding, (err, request) => {
|
735 | if (err) {
|
736 | call.sendError(err);
|
737 | return;
|
738 | }
|
739 | if (request === undefined || call.cancelled) {
|
740 | return;
|
741 | }
|
742 | const emitter = new server_call_1.ServerUnaryCallImpl(call, metadata, request);
|
743 | handler.func(emitter, (err, value, trailer, flags) => {
|
744 | call.sendUnaryMessage(err, value, trailer, flags);
|
745 | });
|
746 | });
|
747 | }
|
748 | function handleClientStreaming(call, handler, metadata, encoding) {
|
749 | const stream = new server_call_1.ServerReadableStreamImpl(call, metadata, handler.deserialize, encoding);
|
750 | function respond(err, value, trailer, flags) {
|
751 | stream.destroy();
|
752 | call.sendUnaryMessage(err, value, trailer, flags);
|
753 | }
|
754 | if (call.cancelled) {
|
755 | return;
|
756 | }
|
757 | stream.on('error', respond);
|
758 | handler.func(stream, respond);
|
759 | }
|
760 | function handleServerStreaming(call, handler, metadata, encoding) {
|
761 | call.receiveUnaryMessage(encoding, (err, request) => {
|
762 | if (err) {
|
763 | call.sendError(err);
|
764 | return;
|
765 | }
|
766 | if (request === undefined || call.cancelled) {
|
767 | return;
|
768 | }
|
769 | const stream = new server_call_1.ServerWritableStreamImpl(call, metadata, handler.serialize, request);
|
770 | handler.func(stream);
|
771 | });
|
772 | }
|
773 | function handleBidiStreaming(call, handler, metadata, encoding) {
|
774 | const stream = new server_call_1.ServerDuplexStreamImpl(call, metadata, handler.serialize, handler.deserialize, encoding);
|
775 | if (call.cancelled) {
|
776 | return;
|
777 | }
|
778 | handler.func(stream);
|
779 | }
|
780 |
|
\ | No newline at end of file |