-
Notifications
You must be signed in to change notification settings - Fork 656
/
Copy pathserver.ts
2172 lines (1977 loc) · 63.9 KB
/
server.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2019 gRPC authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
import * as http2 from 'http2';
import * as util from 'util';
import { ServiceError } from './call';
import { Status, LogVerbosity } from './constants';
import { Deserialize, Serialize, ServiceDefinition } from './make-client';
import { Metadata } from './metadata';
import {
BidiStreamingHandler,
ClientStreamingHandler,
HandleCall,
Handler,
HandlerType,
sendUnaryData,
ServerDuplexStream,
ServerDuplexStreamImpl,
ServerReadableStream,
ServerStreamingHandler,
ServerUnaryCall,
ServerWritableStream,
ServerWritableStreamImpl,
UnaryHandler,
ServerErrorResponse,
ServerStatusResponse,
serverErrorToStatus,
} from './server-call';
import { SecureContextWatcher, ServerCredentials } from './server-credentials';
import { ChannelOptions } from './channel-options';
import {
createResolver,
ResolverListener,
mapUriDefaultScheme,
} from './resolver';
import * as logging from './logging';
import {
SubchannelAddress,
isTcpSubchannelAddress,
subchannelAddressToString,
stringToSubchannelAddress,
} from './subchannel-address';
import {
GrpcUri,
combineHostPort,
parseUri,
splitHostPort,
uriToString,
} from './uri-parser';
import {
ChannelzCallTracker,
ChannelzCallTrackerStub,
ChannelzChildrenTracker,
ChannelzChildrenTrackerStub,
ChannelzTrace,
ChannelzTraceStub,
registerChannelzServer,
registerChannelzSocket,
ServerInfo,
ServerRef,
SocketInfo,
SocketRef,
TlsInfo,
unregisterChannelzRef,
} from './channelz';
import { CipherNameAndProtocol, TLSSocket } from 'tls';
import {
ServerInterceptingCallInterface,
ServerInterceptor,
getServerInterceptingCall,
} from './server-interceptors';
import { PartialStatusObject } from './call-interface';
import { CallEventTracker } from './transport';
import { Socket } from 'net';
import { Duplex } from 'stream';
const UNLIMITED_CONNECTION_AGE_MS = ~(1 << 31);
const KEEPALIVE_MAX_TIME_MS = ~(1 << 31);
const KEEPALIVE_TIMEOUT_MS = 20000;
const MAX_CONNECTION_IDLE_MS = ~(1 << 31);
const { HTTP2_HEADER_PATH } = http2.constants;
const TRACER_NAME = 'server';
const kMaxAge = Buffer.from('max_age');
function serverCallTrace(text: string) {
logging.trace(LogVerbosity.DEBUG, 'server_call', text);
}
type AnyHttp2Server = http2.Http2Server | http2.Http2SecureServer;
interface BindResult {
port: number;
count: number;
errors: string[];
}
interface SingleAddressBindResult {
port: number;
error?: string;
}
function noop(): void {}
/**
* Decorator to wrap a class method with util.deprecate
* @param message The message to output if the deprecated method is called
* @returns
*/
function deprecate(message: string) {
return function <This, Args extends any[], Return>(
target: (this: This, ...args: Args) => Return,
context: ClassMethodDecoratorContext<
This,
(this: This, ...args: Args) => Return
>
) {
return util.deprecate(target, message);
};
}
function getUnimplementedStatusResponse(
methodName: string
): PartialStatusObject {
return {
code: Status.UNIMPLEMENTED,
details: `The server does not implement the method ${methodName}`,
};
}
/* eslint-disable @typescript-eslint/no-explicit-any */
type UntypedUnaryHandler = UnaryHandler<any, any>;
type UntypedClientStreamingHandler = ClientStreamingHandler<any, any>;
type UntypedServerStreamingHandler = ServerStreamingHandler<any, any>;
type UntypedBidiStreamingHandler = BidiStreamingHandler<any, any>;
export type UntypedHandleCall = HandleCall<any, any>;
type UntypedHandler = Handler<any, any>;
export interface UntypedServiceImplementation {
[name: string]: UntypedHandleCall;
}
function getDefaultHandler(handlerType: HandlerType, methodName: string) {
const unimplementedStatusResponse =
getUnimplementedStatusResponse(methodName);
switch (handlerType) {
case 'unary':
return (
call: ServerUnaryCall<any, any>,
callback: sendUnaryData<any>
) => {
callback(unimplementedStatusResponse as ServiceError, null);
};
case 'clientStream':
return (
call: ServerReadableStream<any, any>,
callback: sendUnaryData<any>
) => {
callback(unimplementedStatusResponse as ServiceError, null);
};
case 'serverStream':
return (call: ServerWritableStream<any, any>) => {
call.emit('error', unimplementedStatusResponse);
};
case 'bidi':
return (call: ServerDuplexStream<any, any>) => {
call.emit('error', unimplementedStatusResponse);
};
default:
throw new Error(`Invalid handlerType ${handlerType}`);
}
}
interface ChannelzSessionInfo {
ref: SocketRef;
streamTracker: ChannelzCallTracker | ChannelzCallTrackerStub;
messagesSent: number;
messagesReceived: number;
keepAlivesSent: number;
lastMessageSentTimestamp: Date | null;
lastMessageReceivedTimestamp: Date | null;
}
/**
* Information related to a single invocation of bindAsync. This should be
* tracked in a map keyed by target string, normalized with a pass through
* parseUri -> mapUriDefaultScheme -> uriToString. If the target has a port
* number and the port number is 0, the target string is modified with the
* concrete bound port.
*/
interface BoundPort {
/**
* The key used to refer to this object in the boundPorts map.
*/
mapKey: string;
/**
* The target string, passed through parseUri -> mapUriDefaultScheme. Used
* to determine the final key when the port number is 0.
*/
originalUri: GrpcUri;
/**
* If there is a pending bindAsync operation, this is a promise that resolves
* with the port number when that operation succeeds. If there is no such
* operation pending, this is null.
*/
completionPromise: Promise<number> | null;
/**
* The port number that was actually bound. Populated only after
* completionPromise resolves.
*/
portNumber: number;
/**
* Set by unbind if called while pending is true.
*/
cancelled: boolean;
/**
* The credentials object passed to the original bindAsync call.
*/
credentials: ServerCredentials;
/**
* The set of servers associated with this listening port. A target string
* that expands to multiple addresses will result in multiple listening
* servers.
*/
listeningServers: Set<AnyHttp2Server>;
}
/**
* Should be in a map keyed by AnyHttp2Server.
*/
interface Http2ServerInfo {
channelzRef: SocketRef;
sessions: Set<http2.ServerHttp2Session>;
}
interface SessionIdleTimeoutTracker {
activeStreams: number;
lastIdle: number;
timeout: NodeJS.Timeout;
onClose: (session: http2.ServerHttp2Session) => void | null;
}
export interface ServerOptions extends ChannelOptions {
interceptors?: ServerInterceptor[];
}
export interface ConnectionInjector {
injectConnection(connection: Duplex): void;
drain(graceTimeMs: number): void;
destroy(): void;
}
export class Server {
private boundPorts: Map<string, BoundPort> = new Map();
private http2Servers: Map<AnyHttp2Server, Http2ServerInfo> = new Map();
private sessionIdleTimeouts = new Map<
http2.ServerHttp2Session,
SessionIdleTimeoutTracker
>();
private handlers: Map<string, UntypedHandler> = new Map<
string,
UntypedHandler
>();
private sessions = new Map<http2.ServerHttp2Session, ChannelzSessionInfo>();
/**
* This field only exists to ensure that the start method throws an error if
* it is called twice, as it did previously.
*/
private started = false;
private shutdown = false;
private options: ServerOptions;
private serverAddressString = 'null';
// Channelz Info
private readonly channelzEnabled: boolean = true;
private channelzRef: ServerRef;
private channelzTrace: ChannelzTrace | ChannelzTraceStub;
private callTracker: ChannelzCallTracker | ChannelzCallTrackerStub;
private listenerChildrenTracker:
| ChannelzChildrenTracker
| ChannelzChildrenTrackerStub;
private sessionChildrenTracker:
| ChannelzChildrenTracker
| ChannelzChildrenTrackerStub;
private readonly maxConnectionAgeMs: number;
private readonly maxConnectionAgeGraceMs: number;
private readonly keepaliveTimeMs: number;
private readonly keepaliveTimeoutMs: number;
private readonly sessionIdleTimeout: number;
private readonly interceptors: ServerInterceptor[];
/**
* Options that will be used to construct all Http2Server instances for this
* Server.
*/
private commonServerOptions: http2.ServerOptions;
constructor(options?: ServerOptions) {
this.options = options ?? {};
if (this.options['grpc.enable_channelz'] === 0) {
this.channelzEnabled = false;
this.channelzTrace = new ChannelzTraceStub();
this.callTracker = new ChannelzCallTrackerStub();
this.listenerChildrenTracker = new ChannelzChildrenTrackerStub();
this.sessionChildrenTracker = new ChannelzChildrenTrackerStub();
} else {
this.channelzTrace = new ChannelzTrace();
this.callTracker = new ChannelzCallTracker();
this.listenerChildrenTracker = new ChannelzChildrenTracker();
this.sessionChildrenTracker = new ChannelzChildrenTracker();
}
this.channelzRef = registerChannelzServer(
'server',
() => this.getChannelzInfo(),
this.channelzEnabled
);
this.channelzTrace.addTrace('CT_INFO', 'Server created');
this.maxConnectionAgeMs =
this.options['grpc.max_connection_age_ms'] ?? UNLIMITED_CONNECTION_AGE_MS;
this.maxConnectionAgeGraceMs =
this.options['grpc.max_connection_age_grace_ms'] ??
UNLIMITED_CONNECTION_AGE_MS;
this.keepaliveTimeMs =
this.options['grpc.keepalive_time_ms'] ?? KEEPALIVE_MAX_TIME_MS;
this.keepaliveTimeoutMs =
this.options['grpc.keepalive_timeout_ms'] ?? KEEPALIVE_TIMEOUT_MS;
this.sessionIdleTimeout =
this.options['grpc.max_connection_idle_ms'] ?? MAX_CONNECTION_IDLE_MS;
this.commonServerOptions = {
maxSendHeaderBlockLength: Number.MAX_SAFE_INTEGER,
};
if ('grpc-node.max_session_memory' in this.options) {
this.commonServerOptions.maxSessionMemory =
this.options['grpc-node.max_session_memory'];
} else {
/* By default, set a very large max session memory limit, to effectively
* disable enforcement of the limit. Some testing indicates that Node's
* behavior degrades badly when this limit is reached, so we solve that
* by disabling the check entirely. */
this.commonServerOptions.maxSessionMemory = Number.MAX_SAFE_INTEGER;
}
if ('grpc.max_concurrent_streams' in this.options) {
this.commonServerOptions.settings = {
maxConcurrentStreams: this.options['grpc.max_concurrent_streams'],
};
}
this.interceptors = this.options.interceptors ?? [];
this.trace('Server constructed');
}
private getChannelzInfo(): ServerInfo {
return {
trace: this.channelzTrace,
callTracker: this.callTracker,
listenerChildren: this.listenerChildrenTracker.getChildLists(),
sessionChildren: this.sessionChildrenTracker.getChildLists(),
};
}
private getChannelzSessionInfo(
session: http2.ServerHttp2Session
): SocketInfo {
const sessionInfo = this.sessions.get(session)!;
const sessionSocket = session.socket;
const remoteAddress = sessionSocket.remoteAddress
? stringToSubchannelAddress(
sessionSocket.remoteAddress,
sessionSocket.remotePort
)
: null;
const localAddress = sessionSocket.localAddress
? stringToSubchannelAddress(
sessionSocket.localAddress!,
sessionSocket.localPort
)
: null;
let tlsInfo: TlsInfo | null;
if (session.encrypted) {
const tlsSocket: TLSSocket = sessionSocket as TLSSocket;
const cipherInfo: CipherNameAndProtocol & { standardName?: string } =
tlsSocket.getCipher();
const certificate = tlsSocket.getCertificate();
const peerCertificate = tlsSocket.getPeerCertificate();
tlsInfo = {
cipherSuiteStandardName: cipherInfo.standardName ?? null,
cipherSuiteOtherName: cipherInfo.standardName ? null : cipherInfo.name,
localCertificate:
certificate && 'raw' in certificate ? certificate.raw : null,
remoteCertificate:
peerCertificate && 'raw' in peerCertificate
? peerCertificate.raw
: null,
};
} else {
tlsInfo = null;
}
const socketInfo: SocketInfo = {
remoteAddress: remoteAddress,
localAddress: localAddress,
security: tlsInfo,
remoteName: null,
streamsStarted: sessionInfo.streamTracker.callsStarted,
streamsSucceeded: sessionInfo.streamTracker.callsSucceeded,
streamsFailed: sessionInfo.streamTracker.callsFailed,
messagesSent: sessionInfo.messagesSent,
messagesReceived: sessionInfo.messagesReceived,
keepAlivesSent: sessionInfo.keepAlivesSent,
lastLocalStreamCreatedTimestamp: null,
lastRemoteStreamCreatedTimestamp:
sessionInfo.streamTracker.lastCallStartedTimestamp,
lastMessageSentTimestamp: sessionInfo.lastMessageSentTimestamp,
lastMessageReceivedTimestamp: sessionInfo.lastMessageReceivedTimestamp,
localFlowControlWindow: session.state.localWindowSize ?? null,
remoteFlowControlWindow: session.state.remoteWindowSize ?? null,
};
return socketInfo;
}
private trace(text: string): void {
logging.trace(
LogVerbosity.DEBUG,
TRACER_NAME,
'(' + this.channelzRef.id + ') ' + text
);
}
private keepaliveTrace(text: string): void {
logging.trace(
LogVerbosity.DEBUG,
'keepalive',
'(' + this.channelzRef.id + ') ' + text
);
}
addProtoService(): never {
throw new Error('Not implemented. Use addService() instead');
}
addService(
service: ServiceDefinition,
implementation: UntypedServiceImplementation
): void {
if (
service === null ||
typeof service !== 'object' ||
implementation === null ||
typeof implementation !== 'object'
) {
throw new Error('addService() requires two objects as arguments');
}
const serviceKeys = Object.keys(service);
if (serviceKeys.length === 0) {
throw new Error('Cannot add an empty service to a server');
}
serviceKeys.forEach(name => {
const attrs = service[name];
let methodType: HandlerType;
if (attrs.requestStream) {
if (attrs.responseStream) {
methodType = 'bidi';
} else {
methodType = 'clientStream';
}
} else {
if (attrs.responseStream) {
methodType = 'serverStream';
} else {
methodType = 'unary';
}
}
let implFn = implementation[name];
let impl;
if (implFn === undefined && typeof attrs.originalName === 'string') {
implFn = implementation[attrs.originalName];
}
if (implFn !== undefined) {
impl = implFn.bind(implementation);
} else {
impl = getDefaultHandler(methodType, name);
}
const success = this.register(
attrs.path,
impl as UntypedHandleCall,
attrs.responseSerialize,
attrs.requestDeserialize,
methodType
);
if (success === false) {
throw new Error(`Method handler for ${attrs.path} already provided.`);
}
});
}
removeService(service: ServiceDefinition): void {
if (service === null || typeof service !== 'object') {
throw new Error('removeService() requires object as argument');
}
const serviceKeys = Object.keys(service);
serviceKeys.forEach(name => {
const attrs = service[name];
this.unregister(attrs.path);
});
}
bind(port: string, creds: ServerCredentials): never {
throw new Error('Not implemented. Use bindAsync() instead');
}
private registerListenerToChannelz(boundAddress: SubchannelAddress) {
return registerChannelzSocket(
subchannelAddressToString(boundAddress),
() => {
return {
localAddress: boundAddress,
remoteAddress: null,
security: null,
remoteName: null,
streamsStarted: 0,
streamsSucceeded: 0,
streamsFailed: 0,
messagesSent: 0,
messagesReceived: 0,
keepAlivesSent: 0,
lastLocalStreamCreatedTimestamp: null,
lastRemoteStreamCreatedTimestamp: null,
lastMessageSentTimestamp: null,
lastMessageReceivedTimestamp: null,
localFlowControlWindow: null,
remoteFlowControlWindow: null,
};
},
this.channelzEnabled
);
}
private createHttp2Server(credentials: ServerCredentials) {
let http2Server: http2.Http2Server | http2.Http2SecureServer;
if (credentials._isSecure()) {
const credentialsSettings = credentials._getSettings();
const secureServerOptions: http2.SecureServerOptions = {
...this.commonServerOptions,
...credentialsSettings,
enableTrace: this.options['grpc-node.tls_enable_trace'] === 1
};
let areCredentialsValid = credentialsSettings !== null;
http2Server = http2.createSecureServer(secureServerOptions);
http2Server.on('connection', (socket: Socket) => {
if (!areCredentialsValid) {
socket.destroy();
}
});
http2Server.on('secureConnection', (socket: TLSSocket) => {
/* These errors need to be handled by the user of Http2SecureServer,
* according to https://github.com/nodejs/node/issues/35824 */
socket.on('error', (e: Error) => {
this.trace(
'An incoming TLS connection closed with error: ' + e.message
);
});
});
const credsWatcher: SecureContextWatcher = options => {
if (options) {
(http2Server as http2.Http2SecureServer).setSecureContext(options);
}
areCredentialsValid = options !== null;
}
credentials._addWatcher(credsWatcher);
http2Server.on('close', () => {
credentials._removeWatcher(credsWatcher);
});
} else {
http2Server = http2.createServer(this.commonServerOptions);
}
http2Server.setTimeout(0, noop);
this._setupHandlers(http2Server, credentials._getInterceptors());
return http2Server;
}
private bindOneAddress(
address: SubchannelAddress,
boundPortObject: BoundPort
): Promise<SingleAddressBindResult> {
this.trace('Attempting to bind ' + subchannelAddressToString(address));
const http2Server = this.createHttp2Server(boundPortObject.credentials);
return new Promise<SingleAddressBindResult>((resolve, reject) => {
const onError = (err: Error) => {
this.trace(
'Failed to bind ' +
subchannelAddressToString(address) +
' with error ' +
err.message
);
resolve({
port: 'port' in address ? address.port : 1,
error: err.message,
});
};
http2Server.once('error', onError);
http2Server.listen(address, () => {
const boundAddress = http2Server.address()!;
let boundSubchannelAddress: SubchannelAddress;
if (typeof boundAddress === 'string') {
boundSubchannelAddress = {
path: boundAddress,
};
} else {
boundSubchannelAddress = {
host: boundAddress.address,
port: boundAddress.port,
};
}
const channelzRef = this.registerListenerToChannelz(
boundSubchannelAddress
);
this.listenerChildrenTracker.refChild(channelzRef);
this.http2Servers.set(http2Server, {
channelzRef: channelzRef,
sessions: new Set(),
});
boundPortObject.listeningServers.add(http2Server);
this.trace(
'Successfully bound ' +
subchannelAddressToString(boundSubchannelAddress)
);
resolve({
port:
'port' in boundSubchannelAddress ? boundSubchannelAddress.port : 1,
});
http2Server.removeListener('error', onError);
});
});
}
private async bindManyPorts(
addressList: SubchannelAddress[],
boundPortObject: BoundPort
): Promise<BindResult> {
if (addressList.length === 0) {
return {
count: 0,
port: 0,
errors: [],
};
}
if (isTcpSubchannelAddress(addressList[0]) && addressList[0].port === 0) {
/* If binding to port 0, first try to bind the first address, then bind
* the rest of the address list to the specific port that it binds. */
const firstAddressResult = await this.bindOneAddress(
addressList[0],
boundPortObject
);
if (firstAddressResult.error) {
/* If the first address fails to bind, try the same operation starting
* from the second item in the list. */
const restAddressResult = await this.bindManyPorts(
addressList.slice(1),
boundPortObject
);
return {
...restAddressResult,
errors: [firstAddressResult.error, ...restAddressResult.errors],
};
} else {
const restAddresses = addressList
.slice(1)
.map(address =>
isTcpSubchannelAddress(address)
? { host: address.host, port: firstAddressResult.port }
: address
);
const restAddressResult = await Promise.all(
restAddresses.map(address =>
this.bindOneAddress(address, boundPortObject)
)
);
const allResults = [firstAddressResult, ...restAddressResult];
return {
count: allResults.filter(result => result.error === undefined).length,
port: firstAddressResult.port,
errors: allResults
.filter(result => result.error)
.map(result => result.error!),
};
}
} else {
const allResults = await Promise.all(
addressList.map(address =>
this.bindOneAddress(address, boundPortObject)
)
);
return {
count: allResults.filter(result => result.error === undefined).length,
port: allResults[0].port,
errors: allResults
.filter(result => result.error)
.map(result => result.error!),
};
}
}
private async bindAddressList(
addressList: SubchannelAddress[],
boundPortObject: BoundPort
): Promise<number> {
const bindResult = await this.bindManyPorts(addressList, boundPortObject);
if (bindResult.count > 0) {
if (bindResult.count < addressList.length) {
logging.log(
LogVerbosity.INFO,
`WARNING Only ${bindResult.count} addresses added out of total ${addressList.length} resolved`
);
}
return bindResult.port;
} else {
const errorString = `No address added out of total ${addressList.length} resolved`;
logging.log(LogVerbosity.ERROR, errorString);
throw new Error(
`${errorString} errors: [${bindResult.errors.join(',')}]`
);
}
}
private resolvePort(port: GrpcUri): Promise<SubchannelAddress[]> {
return new Promise<SubchannelAddress[]>((resolve, reject) => {
const resolverListener: ResolverListener = {
onSuccessfulResolution: (
endpointList,
serviceConfig,
serviceConfigError
) => {
// We only want one resolution result. Discard all future results
resolverListener.onSuccessfulResolution = () => {};
const addressList = ([] as SubchannelAddress[]).concat(
...endpointList.map(endpoint => endpoint.addresses)
);
if (addressList.length === 0) {
reject(new Error(`No addresses resolved for port ${port}`));
return;
}
resolve(addressList);
},
onError: error => {
reject(new Error(error.details));
},
};
const resolver = createResolver(port, resolverListener, this.options);
resolver.updateResolution();
});
}
private async bindPort(
port: GrpcUri,
boundPortObject: BoundPort
): Promise<number> {
const addressList = await this.resolvePort(port);
if (boundPortObject.cancelled) {
this.completeUnbind(boundPortObject);
throw new Error('bindAsync operation cancelled by unbind call');
}
const portNumber = await this.bindAddressList(addressList, boundPortObject);
if (boundPortObject.cancelled) {
this.completeUnbind(boundPortObject);
throw new Error('bindAsync operation cancelled by unbind call');
}
return portNumber;
}
private normalizePort(port: string): GrpcUri {
const initialPortUri = parseUri(port);
if (initialPortUri === null) {
throw new Error(`Could not parse port "${port}"`);
}
const portUri = mapUriDefaultScheme(initialPortUri);
if (portUri === null) {
throw new Error(`Could not get a default scheme for port "${port}"`);
}
return portUri;
}
bindAsync(
port: string,
creds: ServerCredentials,
callback: (error: Error | null, port: number) => void
): void {
if (this.shutdown) {
throw new Error('bindAsync called after shutdown');
}
if (typeof port !== 'string') {
throw new TypeError('port must be a string');
}
if (creds === null || !(creds instanceof ServerCredentials)) {
throw new TypeError('creds must be a ServerCredentials object');
}
if (typeof callback !== 'function') {
throw new TypeError('callback must be a function');
}
this.trace('bindAsync port=' + port);
const portUri = this.normalizePort(port);
const deferredCallback = (error: Error | null, port: number) => {
process.nextTick(() => callback(error, port));
};
/* First, if this port is already bound or that bind operation is in
* progress, use that result. */
let boundPortObject = this.boundPorts.get(uriToString(portUri));
if (boundPortObject) {
if (!creds._equals(boundPortObject.credentials)) {
deferredCallback(
new Error(`${port} already bound with incompatible credentials`),
0
);
return;
}
/* If that operation has previously been cancelled by an unbind call,
* uncancel it. */
boundPortObject.cancelled = false;
if (boundPortObject.completionPromise) {
boundPortObject.completionPromise.then(
portNum => callback(null, portNum),
error => callback(error as Error, 0)
);
} else {
deferredCallback(null, boundPortObject.portNumber);
}
return;
}
boundPortObject = {
mapKey: uriToString(portUri),
originalUri: portUri,
completionPromise: null,
cancelled: false,
portNumber: 0,
credentials: creds,
listeningServers: new Set(),
};
const splitPort = splitHostPort(portUri.path);
const completionPromise = this.bindPort(portUri, boundPortObject);
boundPortObject.completionPromise = completionPromise;
/* If the port number is 0, defer populating the map entry until after the
* bind operation completes and we have a specific port number. Otherwise,
* populate it immediately. */
if (splitPort?.port === 0) {
completionPromise.then(
portNum => {
const finalUri: GrpcUri = {
scheme: portUri.scheme,
authority: portUri.authority,
path: combineHostPort({ host: splitPort.host, port: portNum }),
};
boundPortObject!.mapKey = uriToString(finalUri);
boundPortObject!.completionPromise = null;
boundPortObject!.portNumber = portNum;
this.boundPorts.set(boundPortObject!.mapKey, boundPortObject!);
callback(null, portNum);
},
error => {
callback(error, 0);
}
);
} else {
this.boundPorts.set(boundPortObject.mapKey, boundPortObject);
completionPromise.then(
portNum => {
boundPortObject!.completionPromise = null;
boundPortObject!.portNumber = portNum;
callback(null, portNum);
},
error => {
callback(error, 0);
}
);
}
}
private registerInjectorToChannelz() {
return registerChannelzSocket(
'injector',
() => {
return {
localAddress: null,
remoteAddress: null,
security: null,
remoteName: null,
streamsStarted: 0,
streamsSucceeded: 0,
streamsFailed: 0,
messagesSent: 0,
messagesReceived: 0,
keepAlivesSent: 0,
lastLocalStreamCreatedTimestamp: null,
lastRemoteStreamCreatedTimestamp: null,
lastMessageSentTimestamp: null,
lastMessageReceivedTimestamp: null,
localFlowControlWindow: null,
remoteFlowControlWindow: null,
};
},
this.channelzEnabled
);
}
createConnectionInjector(credentials: ServerCredentials): ConnectionInjector {
if (credentials === null || !(credentials instanceof ServerCredentials)) {
throw new TypeError('creds must be a ServerCredentials object');
}
const server = this.createHttp2Server(credentials);
const channelzRef = this.registerInjectorToChannelz();
if (this.channelzEnabled) {
this.listenerChildrenTracker.refChild(channelzRef);
}
const sessionsSet: Set<http2.ServerHttp2Session> = new Set();
this.http2Servers.set(server, {
channelzRef: channelzRef,
sessions: sessionsSet
});
return {
injectConnection: (connection: Duplex) => {
server.emit('connection', connection);
},
drain: (graceTimeMs: number) => {
for (const session of sessionsSet) {
this.closeSession(session);
}
setTimeout(() => {
for (const session of sessionsSet) {
session.destroy(http2.constants.NGHTTP2_CANCEL as any);
}
}, graceTimeMs).unref?.();
},
destroy: () => {
this.closeServer(server)
for (const session of sessionsSet) {
this.closeSession(session);
}
}
};
}
private closeServer(server: AnyHttp2Server, callback?: () => void) {
this.trace(
'Closing server with address ' + JSON.stringify(server.address())
);
const serverInfo = this.http2Servers.get(server);
server.close(() => {
if (serverInfo) {
this.listenerChildrenTracker.unrefChild(serverInfo.channelzRef);
unregisterChannelzRef(serverInfo.channelzRef);
}
this.http2Servers.delete(server);
callback?.();
});
}
private closeSession(
session: http2.ServerHttp2Session,
callback?: () => void
) {