-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathNodeConnectionManager.ts
More file actions
2233 lines (2128 loc) · 78.2 KB
/
NodeConnectionManager.ts
File metadata and controls
2233 lines (2128 loc) · 78.2 KB
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
import type { ResourceAcquire } from '@matrixai/resources';
import type { ContextTimed, ContextTimedInput } from '@matrixai/contexts';
import type { QUICConnection } from '@matrixai/quic';
import type {
ClientManifest,
JSONRPCRequest,
JSONRPCResponse,
ServerManifest,
} from '@matrixai/rpc';
import type {
AuthenticateNetworkForwardCallback,
AuthenticateNetworkReverseCallback,
NodeId,
NodeIdString,
} from './types.js';
import type {
NodesAuthenticateConnectionMessage,
SuccessMessage,
} from './agent/types.js';
import type { AgentClientManifestNodeConnectionManager } from './agent/callers/index.js';
import type KeyRing from '../keys/KeyRing.js';
import type { CertificatePEM } from '../keys/types.js';
import type {
ConnectionData,
Host,
Hostname,
Port,
TLSConfig,
} from '../network/types.js';
import type { JSONValue } from '../types.js';
import { TransformStream } from 'stream/web';
import {
events as quicEvents,
QUICServer,
QUICSocket,
utils as quicUtils,
} from '@matrixai/quic';
import { withF } from '@matrixai/resources';
import {
errors as rpcErrors,
middleware as rpcMiddleware,
RPCServer,
} from '@matrixai/rpc';
import Logger from '@matrixai/logger';
import { Timer } from '@matrixai/timer';
import { IdInternal } from '@matrixai/id';
import { startStop } from '@matrixai/async-init';
import { AbstractEvent, EventAll } from '@matrixai/events';
import { decorators } from '@matrixai/contexts';
import { Semaphore } from '@matrixai/async-locks';
import { PromiseCancellable } from '@matrixai/async-cancellable';
import NodeConnection from './NodeConnection.js';
import * as nodesUtils from './utils.js';
import * as nodesErrors from './errors.js';
import * as nodesEvents from './events.js';
import * as agentUtils from './agent/utils.js';
import * as keysUtils from '../keys/utils/index.js';
import * as networkUtils from '../network/utils.js';
import * as utils from '../utils/index.js';
import RateLimiter from '../utils/ratelimiter/RateLimiter.js';
import config from '../config.js';
type ConnectionAndTimer<Manifest extends ClientManifest> = {
connection: NodeConnection<Manifest>;
timer: Timer | null;
usageCount: number;
};
enum AuthenticatingState {
PENDING = 1,
SUCCESS = 2,
FAIL = 3,
}
type ConnectionsEntry<Manifest extends ClientManifest> = {
activeConnection: string;
connections: Record<string, ConnectionAndTimer<Manifest>>;
// This tracks the authentication state machine
authenticatedForward: AuthenticatingState;
authenticatedReverse: AuthenticatingState;
authenticateComplete: boolean;
authenticatedP: Promise<void>;
authenticatedResolveP: (value: void) => void;
authenticatedRejectP: (reason?: Error) => void;
};
type ConnectionInfo = {
host: Host;
hostName: Hostname | undefined;
port: Port;
timeout: number | undefined;
primary: boolean;
};
type ActiveConnectionsInfo = {
nodeId: NodeId;
connections: Record<string, ConnectionInfo>;
};
const abortPendingConnectionsReason = Symbol(
'abort pending connections reason',
);
const timerCancellationReason = Symbol('timer cancellation reason');
const activePunchCancellationReason = Symbol(
'active punch cancellation reason',
);
const activeForwardAuthenticateCancellationReason = Symbol(
'active forward authenticate cancellation reason',
);
const rpcMethodsWhitelist = [
'nodesAuthenticateConnection',
'nodesClaimNetworkSign',
'nodesClaimNetworkAuthorityGet',
];
/**
* NodeConnectionManager is a server that manages all node connections.
* It manages both initiated and received connections.
*
* It acts like a phone call system.
* It can maintain multiple calls to other nodes.
* There's no guarantee that we need to make it.
*
* Node connections make use of the QUIC protocol.
* The NodeConnectionManager encapsulates `QUICServer`.
* While the NodeConnection encapsulates `QUICClient`.
*/
interface NodeConnectionManager<
// eslint-disable-next-line
Manifest extends AgentClientManifestNodeConnectionManager,
> extends startStop.StartStop {}
@startStop.StartStop({
eventStart: nodesEvents.EventNodeConnectionManagerStart,
eventStarted: nodesEvents.EventNodeConnectionManagerStarted,
eventStop: nodesEvents.EventNodeConnectionManagerStop,
eventStopped: nodesEvents.EventNodeConnectionManagerStopped,
})
class NodeConnectionManager<
Manifest extends AgentClientManifestNodeConnectionManager,
> {
/**
* Alpha constant for kademlia
* The number of the closest nodes to contact initially
*/
public readonly connectionFindConcurrencyLimit: number;
/**
* Default limit used when getting the closest active connections of a node.
* Defaults to the `nodesGraphBucketLimit`
*/
public readonly connectionGetClosestLimit: number;
/**
* Time used to find a node using `findNodeLocal`.
*/
public readonly connectionFindLocalTimeoutTime: number;
/**
* Minimum time to wait to garbage collect un-used node connections.
*/
public readonly connectionIdleTimeoutTimeMin: number;
/**
* Scaling factor to apply to Idle timeout
*/
public readonly connectionIdleTimeoutTimeScale: number;
/**
* Time used to establish `NodeConnection`
*/
public readonly connectionConnectTimeoutTime: number;
/**
* Time to keep alive node connection.
*/
public readonly connectionKeepAliveTimeoutTime: number;
/**
* Time interval for sending keep alive messages.
*/
public readonly connectionKeepAliveIntervalTime: number;
/**
* Initial delay between punch packets, delay doubles each attempt.
*/
public readonly connectionHolePunchIntervalTime: number;
/**
* Total number of active bidirectional streams that can be created
*/
public readonly connectionInitialMaxStreamsBidi: number;
/**
* Total number of active unidirectional streams that can be created
*/
public readonly connectionInitialMaxStreamsUni: number;
/**
* Max parse buffer size before RPC parser throws a parse error.
*/
public readonly rpcParserBufferSize: number;
/**
* Default timeout for RPC handlers
*/
public readonly rpcCallTimeoutTime: number;
/**
* Used to track active hole punching attempts.
* Attempts are mapped by a string of `${host}:${port}`.
* This is used to coalesce attempts to a target host and port.
* Used to cancel and await punch attempts when stopping to prevent orphaned promises.
*/
protected activeHolePunchPs = new Map<string, PromiseCancellable<void>>();
/**
* Used to rate limit hole punch attempts per IP Address.
* We use a semaphore to track the number of active hole punch attempts to that address.
* We Use a semaphore here to allow a limit of 3 attempts per host.
* To allow concurrent attempts to the same host while limiting the number of different ports.
* This is mainly used to limit requests to a single target host.
*/
protected activeHolePunchAddresses = new Map<string, Semaphore>();
/**
* Used track the active `nodesConnectionSignalFinal` attempts and prevent orphaned promises.
* Used to cancel and await the active `nodesConnectionSignalFinal` when stopping.
*/
protected activeSignalFinalPs = new Set<Promise<void>>();
/**
* Used to limit signalling requests on a per-requester basis.
* This is mainly used to limit a single source node making too many requests through a relay.
*/
protected rateLimiter = new RateLimiter(60000, 20, 10, 1);
/**
* Used to track the active authentication RPC calls
*/
protected activeForwardAuthenticateCalls = new Map<
string,
PromiseCancellable<void>
>();
/**
* Callback used to generate authentication data when making the authentication call
*/
protected authenticateNetworkForwardCallback: AuthenticateNetworkForwardCallback;
/**
* Callback used to authenticate the peer when processing an authentication request from the peer
*/
protected authenticateNetworkReverseCallback: AuthenticateNetworkReverseCallback;
protected logger: Logger;
protected keyRing: KeyRing;
protected tlsConfig: TLSConfig;
protected quicSocket: QUICSocket;
protected quicServer: QUICServer;
/**
* Data structure to store all NodeConnections. If a connection to a node `N` does
* not exist, no entry for `N` will exist in the map. Alternatively, if a
* connection is currently being instantiated by some thread, an entry will
* exist in the map, but only with the lock (no connection object). Once a
* connection is instantiated, the entry in the map is updated to include the
* connection object.
* A nodeIdString is used for the key here since
* NodeIds can't be used to properly retrieve a value from the map.
*/
protected connections: Map<NodeIdString, ConnectionsEntry<Manifest>> =
new Map();
protected rpcServer: RPCServer;
protected rpcClientManifest: Manifest;
/**
* Dispatches a `EventNodeConnectionManagerClose` in response to any `NodeConnectionManager`
* error event. Will trigger stop of the `NodeConnectionManager` via the
* `EventNodeConnectionManagerError` -> `EventNodeConnectionManagerClose` event path.
*/
protected handleEventNodeConnectionManagerError = (
evt: nodesEvents.EventNodeConnectionManagerError,
) => {
this.logger.warn(
`NodeConnectionManager error caused by ${evt.detail.message}`,
);
this.dispatchEvent(new nodesEvents.EventNodeConnectionManagerClose());
};
/**
* Triggers the destruction of the `NodeConnectionManager`. Since this is only in
* response to an underlying problem or close it will force destroy.
* Dispatched by the `EventNodeConnectionManagerError` event as the
* `EventNodeConnectionManagerError` -> `EventNodeConnectionManagerClose` event path.
*/
protected handleEventNodeConnectionManagerClose = async (
_evt: nodesEvents.EventNodeConnectionManagerClose,
) => {
this.logger.debug(`close event triggering NodeConnectionManager.stop`);
if (this[startStop.running] && this[startStop.status] !== 'stopping') {
await this.stop();
}
};
protected handleEventNodeConnectionStream = (
evt: nodesEvents.EventNodeConnectionStream,
) => {
if (evt.target == null) utils.never('target should be defined here');
const nodeConnection = evt.target as NodeConnection<Manifest>;
const connectionId = nodeConnection.connectionId;
const nodeId = nodeConnection.validatedNodeId as NodeId;
const nodeIdString = nodeId.toString() as NodeIdString;
const stream = evt.detail;
this.rpcServer.handleStream(stream);
const connectionsEntry = this.connections.get(nodeIdString);
if (connectionsEntry == null) utils.never('should have a connection entry');
const connectionAndTimer = connectionsEntry.connections[connectionId];
if (connectionAndTimer == null) utils.never('should have a connection');
connectionAndTimer.usageCount += 1;
connectionAndTimer.timer?.cancel(timerCancellationReason);
connectionAndTimer.timer = null;
void stream.closedP.finally(() => {
connectionAndTimer.usageCount -= 1;
if (connectionAndTimer.usageCount <= 0) {
const delay = this.getStickyTimeoutValue(
nodeId,
connectionsEntry.activeConnection ===
connectionAndTimer.connection.connectionId,
);
this.logger.debug(
`creating TTL for ${nodesUtils.encodeNodeId(nodeId)}`,
);
connectionAndTimer.timer = new Timer({
handler: async () =>
await this.destroyConnection(nodeId, false, connectionId),
delay,
});
// Prevent unhandled exceptions when cancelling
connectionAndTimer.timer.catch(() => {});
}
});
};
protected handleEventNodeConnectionDestroyed = async (
evt: nodesEvents.EventNodeConnectionDestroyed,
) => {
if (evt.target == null) utils.never('target should be defined here');
const nodeConnection = evt.target as NodeConnection<Manifest>;
const nodeId = nodeConnection.validatedNodeId as NodeId;
const connectionId = nodeConnection.connectionId;
await this.destroyConnection(nodeId, true, connectionId);
nodeConnection.removeEventListener(
nodesEvents.EventNodeConnectionStream.name,
this.handleEventNodeConnectionStream,
);
nodeConnection.removeEventListener(EventAll.name, this.handleEventAll);
};
/**
* Redispatches `QUICSocket` or `QUICServer` error events as `NodeConnectionManager` error events.
* This should trigger the destruction of the `NodeConnection` through the
* `EventNodeConnectionError` -> `EventNodeConnectionClose` event path.
*/
protected handleEventQUICError = (
evt: quicEvents.EventQUICSocketError,
): void => {
const err = new nodesErrors.ErrorNodeConnectionManagerInternalError(
undefined,
{ cause: evt.detail },
);
this.dispatchEvent(
new nodesEvents.EventNodeConnectionManagerError({ detail: err }),
);
};
/**
* Handle unexpected stoppage of the QUICSocket. Not expected to happen
* without error, but we have it just in case.
*/
protected handleEventQUICSocketStopped = (
_evt: quicEvents.EventQUICSocketStopped,
): void => {
const err = new nodesErrors.ErrorNodeConnectionManagerInternalError(
'QUICSocket stopped unexpectedly',
);
this.dispatchEvent(
new nodesEvents.EventNodeConnectionManagerError({ detail: err }),
);
};
/**
* Handle unexpected stoppage of the QUICServer. Not expected to happen
* without error, but we have it just in case.
*/
protected handleEventQUICServerStopped = (
_evt: quicEvents.EventQUICServerStopped,
): void => {
const err = new nodesErrors.ErrorNodeConnectionManagerInternalError(
'QUICServer stopped unexpectedly',
);
this.dispatchEvent(
new nodesEvents.EventNodeConnectionManagerError({ detail: err }),
);
};
/**
* Handles `EventQUICServerConnection` events. These are reverser or server
* peer initiated connections that needs to be handled and added to the
* connection map.
*/
protected handleEventQUICServerConnection = (
evt: quicEvents.EventQUICServerConnection,
): void => {
this.handleConnectionReverse(evt.detail);
};
/**
* Handles all events and redispatches them upwards
*/
protected handleEventAll = (evt: EventAll) => {
const event = evt.detail;
if (event instanceof AbstractEvent) {
this.dispatchEvent(event.clone());
}
};
/**
* Constructs the `NodeConnectionManager`.
*/
public constructor({
keyRing,
tlsConfig,
rpcClientManifest,
connectionFindConcurrencyLimit = config.defaultsSystem
.nodesConnectionFindConcurrencyLimit,
connectionGetClosestLimit = config.defaultsSystem.nodesGraphBucketLimit,
connectionFindLocalTimeoutTime = config.defaultsSystem
.nodesConnectionFindLocalTimeoutTime,
connectionIdleTimeoutTimeMin = config.defaultsSystem
.nodesConnectionIdleTimeoutTimeMin,
connectionIdleTimeoutTimeScale = config.defaultsSystem
.nodesConnectionIdleTimeoutTimeScale,
connectionConnectTimeoutTime = config.defaultsSystem
.nodesConnectionConnectTimeoutTime,
connectionKeepAliveTimeoutTime = config.defaultsSystem
.nodesConnectionKeepAliveTimeoutTime,
connectionKeepAliveIntervalTime = config.defaultsSystem
.nodesConnectionKeepAliveIntervalTime,
connectionHolePunchIntervalTime = config.defaultsSystem
.nodesConnectionHolePunchIntervalTime,
connectionInitialMaxStreamsBidi = config.defaultsSystem
.nodesConnectionInitialMaxStreamsBidi,
connectionInitialMaxStreamsUni = config.defaultsSystem
.nodesConnectionInitialMaxStreamsUni,
rpcParserBufferSize = config.defaultsSystem.rpcParserBufferSize,
rpcCallTimeoutTime = config.defaultsSystem.rpcCallTimeoutTime,
authenticateNetworkForwardCallback = nodesUtils.nodesAuthenticateConnectionForwardDefault,
authenticateNetworkReverseCallback = nodesUtils.nodesAuthenticateConnectionReverseDefault,
logger,
}: {
keyRing: KeyRing;
tlsConfig: TLSConfig;
rpcClientManifest: Manifest;
connectionFindConcurrencyLimit?: number;
connectionGetClosestLimit?: number;
connectionFindLocalTimeoutTime?: number;
connectionIdleTimeoutTimeMin?: number;
connectionIdleTimeoutTimeScale?: number;
connectionConnectTimeoutTime?: number;
connectionKeepAliveTimeoutTime?: number;
connectionKeepAliveIntervalTime?: number;
connectionHolePunchIntervalTime?: number;
connectionInitialMaxStreamsBidi?: number;
connectionInitialMaxStreamsUni?: number;
rpcParserBufferSize?: number;
rpcCallTimeoutTime?: number;
authenticateNetworkForwardCallback?: AuthenticateNetworkForwardCallback;
authenticateNetworkReverseCallback?: AuthenticateNetworkReverseCallback;
logger?: Logger;
}) {
this.logger = logger ?? new Logger(this.constructor.name);
this.keyRing = keyRing;
this.tlsConfig = tlsConfig;
this.rpcClientManifest = rpcClientManifest;
this.connectionFindConcurrencyLimit = connectionFindConcurrencyLimit;
this.connectionGetClosestLimit = connectionGetClosestLimit;
this.connectionFindLocalTimeoutTime = connectionFindLocalTimeoutTime;
this.connectionIdleTimeoutTimeMin = connectionIdleTimeoutTimeMin;
this.connectionIdleTimeoutTimeScale = connectionIdleTimeoutTimeScale;
this.connectionConnectTimeoutTime = connectionConnectTimeoutTime;
this.connectionKeepAliveTimeoutTime = connectionKeepAliveTimeoutTime;
this.connectionKeepAliveIntervalTime = connectionKeepAliveIntervalTime;
this.connectionHolePunchIntervalTime = connectionHolePunchIntervalTime;
this.connectionInitialMaxStreamsBidi = connectionInitialMaxStreamsBidi;
this.connectionInitialMaxStreamsUni = connectionInitialMaxStreamsUni;
this.rpcParserBufferSize = rpcParserBufferSize;
this.rpcCallTimeoutTime = rpcCallTimeoutTime;
this.authenticateNetworkForwardCallback =
authenticateNetworkForwardCallback;
this.authenticateNetworkReverseCallback =
authenticateNetworkReverseCallback;
const quicSocket = new QUICSocket({
resolveHostname: () => {
utils.never(
'"NodeConnectionManager" must resolve all hostnames before it reaches "QUICSocket"',
);
},
logger: this.logger.getChild(QUICSocket.name),
});
const quicServer = new QUICServer({
crypto: nodesUtils.quicServerCrypto,
config: {
maxIdleTimeout: connectionKeepAliveTimeoutTime,
keepAliveIntervalTime: connectionKeepAliveIntervalTime,
key: tlsConfig.keyPrivatePem,
cert: tlsConfig.certChainPem,
verifyPeer: true,
verifyCallback: nodesUtils.verifyClientCertificateChain,
initialMaxStreamsBidi: 1000,
initialMaxStreamsUni: 0,
},
socket: quicSocket,
reasonToCode: nodesUtils.reasonToCode,
codeToReason: nodesUtils.codeToReason,
minIdleTimeout: connectionConnectTimeoutTime,
logger: this.logger.getChild(QUICServer.name),
});
const rpcServer = new RPCServer({
middlewareFactory: rpcMiddleware.defaultServerMiddlewareWrapper(
this.authenticationMiddlewareClient,
this.rpcParserBufferSize,
),
fromError: networkUtils.fromError,
timeoutTime: this.rpcCallTimeoutTime,
logger: this.logger.getChild(RPCServer.name),
});
this.quicSocket = quicSocket;
this.quicServer = quicServer;
this.rpcServer = rpcServer;
}
/**
* Get the host that node connection manager is bound to.
*/
@startStop.ready(new nodesErrors.ErrorNodeConnectionManagerNotRunning())
public get host(): Host {
return this.quicSocket.host as unknown as Host;
}
/**
* Get the port that node connection manager is bound to.
*/
@startStop.ready(new nodesErrors.ErrorNodeConnectionManagerNotRunning())
public get port(): Port {
return this.quicSocket.port as unknown as Port;
}
@startStop.ready(new nodesErrors.ErrorNodeConnectionManagerNotRunning())
public get type(): 'ipv4' | 'ipv6' | 'ipv4&ipv6' {
return this.quicSocket.type;
}
public async start({
agentService,
host = '::' as Host,
port = 0 as Port,
reuseAddr,
ipv6Only,
}: {
agentService: ServerManifest;
host?: Host;
port?: Port;
reuseAddr?: boolean;
ipv6Only?: boolean;
}) {
const address = networkUtils.buildAddress(host, port);
this.logger.info(`Start ${this.constructor.name} on ${address}`);
// We should expect that seed nodes are already in the node manager
// It should not be managed here!
await this.rpcServer.start({ manifest: agentService });
// Setting up QUICSocket
await this.quicSocket.start({
host,
port,
reuseAddr,
ipv6Only,
});
this.quicSocket.addEventListener(
quicEvents.EventQUICSocketError.name,
this.handleEventQUICError,
);
this.quicSocket.addEventListener(
quicEvents.EventQUICSocketStopped.name,
this.handleEventQUICSocketStopped,
);
this.quicSocket.addEventListener(EventAll.name, this.handleEventAll);
// QUICServer will simply re-use the shared `QUICSocket`
await this.quicServer.start({
host,
port,
reuseAddr,
ipv6Only,
});
this.quicServer.addEventListener(
quicEvents.EventQUICServerError.name,
this.handleEventQUICError,
);
this.quicServer.addEventListener(
quicEvents.EventQUICServerStopped.name,
this.handleEventQUICServerStopped,
);
this.quicServer.addEventListener(
quicEvents.EventQUICServerConnection.name,
this.handleEventQUICServerConnection,
);
this.quicSocket.addEventListener(EventAll.name, this.handleEventAll);
this.rateLimiter.startRefillInterval();
await this.rpcServer.start({ manifest: agentService });
this.logger.info(`Started ${this.constructor.name}`);
}
public async stop({
force = false,
}: {
force?: boolean;
} = {}) {
this.logger.info(`Stop ${this.constructor.name}`);
this.rateLimiter.stop();
this.removeEventListener(
nodesEvents.EventNodeConnectionManagerError.name,
this.handleEventNodeConnectionManagerError,
);
this.removeEventListener(
nodesEvents.EventNodeConnectionManagerClose.name,
this.handleEventNodeConnectionManagerClose,
);
this.quicSocket.removeEventListener(
quicEvents.EventQUICSocketError.name,
this.handleEventQUICError,
);
this.quicSocket.removeEventListener(
quicEvents.EventQUICSocketStopped.name,
this.handleEventQUICSocketStopped,
);
this.quicSocket.removeEventListener(EventAll.name, this.handleEventAll);
this.quicServer.removeEventListener(
quicEvents.EventQUICServerError.name,
this.handleEventQUICError,
);
this.quicServer.removeEventListener(
quicEvents.EventQUICServerStopped.name,
this.handleEventQUICServerStopped,
);
this.quicServer.removeEventListener(
quicEvents.EventQUICServerConnection.name,
this.handleEventQUICServerConnection,
);
this.quicSocket.removeEventListener(EventAll.name, this.handleEventAll);
const destroyConnectionPs: Array<Promise<void>> = [];
const cancelSignallingPs: Array<PromiseCancellable<void> | Promise<void>> =
[];
const authenticationCancelPs: Array<Promise<void>> = [];
const cancelAuthenticationPs: Array<PromiseCancellable<void>> = [];
const cancelReason = new nodesErrors.ErrorNodeConnectionManagerStopping();
for (const [nodeIdString] of this.connections) {
this.authenticateCancel(nodeIdString, cancelReason);
const destroyP = this.destroyConnection(
IdInternal.fromString<NodeId>(nodeIdString),
force,
);
destroyConnectionPs.push(destroyP);
}
for (const [, activePunch] of this.activeHolePunchPs) {
cancelSignallingPs.push(activePunch);
activePunch.cancel(activePunchCancellationReason);
}
for (const activeSignal of this.activeSignalFinalPs) {
cancelSignallingPs.push(activeSignal);
}
for (const activeForwardAuthenticateCall of this.activeForwardAuthenticateCalls.values()) {
cancelAuthenticationPs.push(activeForwardAuthenticateCall);
activeForwardAuthenticateCall.cancel(
activeForwardAuthenticateCancellationReason,
);
}
await Promise.all(destroyConnectionPs);
await Promise.allSettled(cancelSignallingPs);
await Promise.allSettled(authenticationCancelPs);
await Promise.allSettled(cancelAuthenticationPs);
await this.quicServer.stop({ force: true });
await this.quicSocket.stop({ force: true });
await this.rpcServer.stop({ force: true });
this.logger.info(`Stopped ${this.constructor.name}`);
}
/**
* This is the internal acquireConnection for using connections without
* authentication. For usage with withF, to acquire a connection. To wait for
* authentication, use {@link acquireConnection}.
*
* This unique acquire function structure of returning the ResourceAcquire
* itself is such that we can pass targetNodeId as a parameter (as opposed to
* an acquire function with no parameters).
*
* @param targetNodeId Id of target node to communicate with
* @returns ResourceAcquire Resource API for use in with contexts
*/
public acquireConnectionInternal(
targetNodeId: NodeId,
): ResourceAcquire<NodeConnection<Manifest>> {
if (this.keyRing.getNodeId().equals(targetNodeId)) {
this.logger.warn('Attempting connection to our own NodeId');
}
return async () => {
this.logger.debug(
`acquiring connection to node ${nodesUtils.encodeNodeId(targetNodeId)}`,
);
const targetNodeIdString = targetNodeId.toString() as NodeIdString;
const connectionsEntry = this.connections.get(targetNodeIdString);
if (connectionsEntry == null) {
throw new nodesErrors.ErrorNodeConnectionManagerConnectionNotFound();
}
const connectionAndTimer =
connectionsEntry.connections[connectionsEntry.activeConnection];
if (connectionAndTimer == null) {
utils.never('ConnectionAndTimer should exist');
}
// Increment usage count, and cancel timer
connectionAndTimer.usageCount += 1;
connectionAndTimer.timer?.cancel(timerCancellationReason);
connectionAndTimer.timer = null;
// Return tuple of [ResourceRelease, Resource]
return [
async () => {
// Decrement usage count and set up TTL if needed.
// We're only setting up TTLs for non-seed nodes.
connectionAndTimer.usageCount -= 1;
if (connectionAndTimer.usageCount <= 0) {
this.logger.debug(
`creating TTL for ${nodesUtils.encodeNodeId(targetNodeId)}`,
);
const delay = this.getStickyTimeoutValue(
targetNodeId,
connectionsEntry.activeConnection ===
connectionAndTimer.connection.connectionId,
);
connectionAndTimer.timer = new Timer({
handler: async () => {
await this.destroyConnection(
targetNodeId,
false,
connectionAndTimer.connection.connectionId,
);
},
delay,
});
// Prevent unhandled exceptions when cancelling
connectionAndTimer.timer.catch(() => {});
}
},
connectionAndTimer.connection,
];
};
}
/**
* This unique acquire function structure of returning the ResourceAcquire
* itself is such that we can pass targetNodeId as a parameter (as opposed to
* an acquire function with no parameters). It waits for the connection to be
* authenticated, otherwise throws an error. See {@link acquireConnectionInternal}
* to connect to a node without waiting for authentication.
*
* If a connection exists but is not authenticated, the authentication is
* attempted. Authentication is reattempted if it has failed before but
* another attmept is being made to connect to a node.
*
* For usage with withF, to acquire a connection.
*
* @param targetNodeId Id of target node to communicate with
* @param ctx
* @returns ResourceAcquire Resource API for use in with contexts
*/
public acquireConnection(
targetNodeId: NodeId,
ctx: ContextTimed,
): ResourceAcquire<NodeConnection<Manifest>> {
return async () => {
await this.isAuthenticatedP(targetNodeId, ctx);
return await this.acquireConnectionInternal(targetNodeId)();
};
}
/**
* Perform some function on another node over the network with a connection.
* Will either retrieve an existing connection, or create a new one if it
* doesn't exist.
* for use with normal arrow function
* @param targetNodeId Id of target node to communicate with
* @param ctx
* @param f Function to handle communication
*/
public async withConnF<T>(
targetNodeId: NodeId,
ctx: Partial<ContextTimedInput> | undefined,
f: (conn: NodeConnection<Manifest>) => Promise<T>,
): Promise<T>;
@decorators.timedCancellable(true)
public async withConnF<T>(
targetNodeId: NodeId,
@decorators.context ctx: ContextTimed,
f: (conn: NodeConnection<Manifest>) => Promise<T>,
): Promise<T> {
return await withF(
[this.acquireConnection(targetNodeId, ctx)],
async ([conn]) => {
return await f(conn);
},
);
}
/**
* Perform some function on another node over the network with a connection.
* Will either retrieve an existing connection, or create a new one if it
* doesn't exist.
* for use with a generator function
* @param targetNodeId Id of target node to communicate with
* @param ctx
* @param g Generator function to handle communication
*/
public withConnG<T, TReturn, TNext>(
targetNodeId: NodeId,
ctx: Partial<ContextTimedInput> | undefined,
g: (conn: NodeConnection<Manifest>) => AsyncGenerator<T, TReturn, TNext>,
): AsyncGenerator<T, TReturn, TNext>;
@startStop.ready(new nodesErrors.ErrorNodeConnectionManagerNotRunning())
@decorators.timed()
public async *withConnG<T, TReturn, TNext>(
targetNodeId: NodeId,
@decorators.context ctx: ContextTimed,
g: (conn: NodeConnection<Manifest>) => AsyncGenerator<T, TReturn, TNext>,
): AsyncGenerator<T, TReturn, TNext> {
const acquire = this.acquireConnection(targetNodeId, ctx);
const [release, conn] = await acquire();
let caughtError: Error | undefined;
try {
if (conn == null) utils.never('NodeConnection should exist');
return yield* g(conn);
} catch (e) {
caughtError = e;
throw e;
} finally {
await release(caughtError);
}
// Wait for any destruction to complete after locking is removed
}
/**
* Starts a connection. This step also attemps to authenticate the connection.
*/
public createConnection(
nodeIds: Array<NodeId>,
host: Host,
port: Port,
ctx?: Partial<ContextTimedInput>,
): PromiseCancellable<NodeConnection<Manifest>>;
@startStop.ready(new nodesErrors.ErrorNodeConnectionManagerNotRunning())
@decorators.timedCancellable(
true,
(nodeConnectionManager: NodeConnectionManager<Manifest>) =>
nodeConnectionManager.connectionConnectTimeoutTime,
)
public async createConnection(
nodeIds: Array<NodeId>,
host: Host,
port: Port,
@decorators.context ctx: ContextTimed,
): Promise<NodeConnection<Manifest>> {
const nodeConnection = await NodeConnection.createNodeConnection<Manifest>(
{
targetNodeIds: nodeIds,
manifest: this.rpcClientManifest,
targetHost: host,
targetPort: port,
tlsConfig: this.tlsConfig,
connectionKeepAliveIntervalTime: this.connectionKeepAliveIntervalTime,
connectionKeepAliveTimeoutTime: this.connectionKeepAliveTimeoutTime,
connectionInitialMaxStreamsBidi: this.connectionInitialMaxStreamsBidi,
connectionInitialMaxStreamsUni: this.connectionInitialMaxStreamsUni,
quicSocket: this.quicSocket,
logger: this.logger.getChild(
`${NodeConnection.name}Forward [${host}:${port}]`,
),
},
ctx,
);
this.addConnection(nodeConnection.validatedNodeId, nodeConnection);
this.initiateForwardAuthenticate(nodeConnection.nodeId);
// Dispatch the connection event
const connectionData: ConnectionData = {
remoteNodeId: nodeConnection.nodeId,
remoteHost: nodeConnection.host,
remotePort: nodeConnection.port,
};
this.dispatchEvent(
new nodesEvents.EventNodeConnectionManagerConnectionForward({
detail: connectionData,
}),
);
this.dispatchEvent(
new nodesEvents.EventNodeConnectionManagerConnection({
detail: connectionData,
}),
);
if (this.isAuthenticated(connectionData.remoteNodeId)) {
this.dispatchEvent(
new nodesEvents.EventNodeConnectionManagerConnectionAuthenticated({
detail: connectionData,
}),
);
}
return nodeConnection;
}
/**
* Creates multiple connections looking for a single node. Once the connection
* has been established then all pending connections are cancelled.
* This will return the first connection made or timeout.
*/
public createConnectionMultiple(
nodeIds: Array<NodeId>,
addresses: Array<[Host, Port]>,
ctx?: Partial<ContextTimedInput>,
): PromiseCancellable<NodeConnection<Manifest>>;
@startStop.ready(new nodesErrors.ErrorNodeConnectionManagerNotRunning())
@decorators.timedCancellable(
true,
(nodeConnectionManager: NodeConnectionManager<Manifest>) =>
nodeConnectionManager.connectionConnectTimeoutTime,
)
public async createConnectionMultiple(
nodeIds: Array<NodeId>,
addresses: Array<[Host, Port]>,
@decorators.context ctx: ContextTimed,
): Promise<NodeConnection<Manifest>> {
// Setting up intermediate signal
const abortControllerMultiConn = new AbortController();
const handleAbort = () => {
abortControllerMultiConn.abort(ctx.signal.reason);
};
if (ctx.signal.aborted) {
handleAbort();
} else {
ctx.signal.addEventListener('abort', handleAbort, {
once: true,
});
}
const newCtx = {
timer: ctx.timer,
signal: abortControllerMultiConn.signal,
};
const attempts = addresses.map(([host, port]) => {
return this.createConnection(nodeIds, host, port, newCtx);
});
try {
// Await first success
return await Promise.any(attempts).catch((e) => {
throw new nodesErrors.ErrorNodeConnectionTimeout(undefined, {
cause: e,
});
});
} finally {
// Abort and clean up the rest
abortControllerMultiConn.abort(abortPendingConnectionsReason);
await Promise.allSettled(attempts);
ctx.signal.removeEventListener('abort', handleAbort);
}
}
/**
* This will start a new connection using a signalling node to coordinate hole punching.
*/
public createConnectionPunch(
nodeIdTarget: NodeId,
nodeIdSignaller: NodeId,
ctx?: Partial<ContextTimedInput>,
): PromiseCancellable<NodeConnection<Manifest>>;