-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathNodeManager.ts
More file actions
2859 lines (2749 loc) · 95.4 KB
/
NodeManager.ts
File metadata and controls
2859 lines (2749 loc) · 95.4 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 { DB, DBTransaction, LevelPath } from '@matrixai/db';
import type { ContextTimed, ContextTimedInput } from '@matrixai/contexts';
import type { PromiseCancellable } from '@matrixai/async-cancellable';
import type { ResourceAcquire } from '@matrixai/resources';
import type KeyRing from '../keys/KeyRing.js';
import type Sigchain from '../sigchain/Sigchain.js';
import type TaskManager from '../tasks/TaskManager.js';
import type GestaltGraph from '../gestalts/GestaltGraph.js';
import type {
Task,
TaskHandler,
TaskHandlerId,
TaskInfo,
} from '../tasks/types.js';
import type { SignedTokenEncoded } from '../tokens/types.js';
import type { Host, Port } from '../network/types.js';
import type {
Claim,
ClaimId,
ClaimIdEncoded,
SignedClaim,
} from '../claims/types.js';
import type {
ClaimLinkNode,
ClaimNetworkAccess,
} from '../claims/payloads/index.js';
import type NodeConnection from '../nodes/NodeConnection.js';
import type {
AgentClaimMessage,
AgentRPCRequestParams,
AgentRPCResponseResult,
} from './agent/types.js';
import type {
NodeAddress,
NodeBucket,
NodeBucketIndex,
NodeContact,
NodeContactAddressData,
NodeId,
NodeIdEncoded,
} from './types.js';
import type NodeConnectionManager from './NodeConnectionManager.js';
import type NodeGraph from './NodeGraph.js';
import type { ServicePOJO } from '@matrixai/mdns';
import type { AgentClientManifestNodeManager } from './agent/callers/index.js';
import type { ClaimNetworkAuthority } from '../claims/payloads/claimNetworkAuthority.js';
import { withF } from '@matrixai/resources';
import { events as mdnsEvents, MDNS, utils as mdnsUtils } from '@matrixai/mdns';
import Logger from '@matrixai/logger';
import { startStop } from '@matrixai/async-init';
import { Lock, LockBox, Semaphore } from '@matrixai/async-locks';
import { IdInternal } from '@matrixai/id';
import { decorators } from '@matrixai/contexts';
import * as nodesUtils from './utils.js';
import * as nodesEvents from './events.js';
import * as nodesErrors from './errors.js';
import NodeConnectionQueue from './NodeConnectionQueue.js';
import config from '../config.js';
import * as claimNetworkAuthorityUtils from '../claims/payloads/claimNetworkAuthority.js';
import * as claimNetworkAccessUtils from '../claims/payloads/claimNetworkAccess.js';
import Token from '../tokens/Token.js';
import * as keysUtils from '../keys/utils/index.js';
import * as tasksErrors from '../tasks/errors.js';
import * as claimsUtils from '../claims/utils.js';
import * as claimsErrors from '../claims/errors.js';
import * as utils from '../utils/utils.js';
import * as networkUtils from '../network/utils.js';
const abortEphemeralTaskReason = Symbol('abort ephemeral task reason');
const abortSingletonTaskReason = Symbol('abort singleton task reason');
const abortPendingConnectionsReason = Symbol(
'abort pending connections reason',
);
/**
* NodeManager manages all operations involving nodes.
* It encapsulates mutations to the NodeGraph.
* It listens to the NodeConnectionManager events.
*/
// eslint-disable-next-line
interface NodeManager<Manifest extends AgentClientManifestNodeManager>
extends startStop.StartStop {}
@startStop.StartStop({
eventStart: nodesEvents.EventNodeManagerStart,
eventStarted: nodesEvents.EventNodeManagerStarted,
eventStop: nodesEvents.EventNodeManagerStop,
eventStopped: nodesEvents.EventNodeManagerStopped,
})
class NodeManager<Manifest extends AgentClientManifestNodeManager> {
/**
* Time used to establish `NodeConnection`
*/
public readonly connectionConnectTimeoutTime: number;
public readonly refreshBucketDelayTime: number;
public readonly refreshBucketDelayJitter: number;
/**
* Interval used to reestablish connections to maintain network health.
* Will trigger a refreshBucket for bucket 255 if it is missing connections.
* Will always trigger a findNode(this.keyRing.getNodeId()).
*/
public readonly retryConnectionsDelayTime: number;
/**
* Timeout for finding a connection via MDNS
*/
public readonly connectionFindMDNSTimeoutTime: number;
public readonly tasksPath = 'NodeManager';
protected db: DB;
protected logger: Logger;
protected keyRing: KeyRing;
protected sigchain: Sigchain;
protected gestaltGraph: GestaltGraph;
protected taskManager: TaskManager;
protected nodeGraph: NodeGraph;
protected nodeConnectionManager: NodeConnectionManager<Manifest>;
protected mdnsOptions:
| {
groups: Array<Host>;
port: Port;
}
| undefined;
protected mdns: MDNS | undefined;
protected pendingNodes: Map<
number,
Map<string, [NodeAddress, NodeContactAddressData]>
> = new Map();
protected concurrencyLimit = 3;
protected dnsServers: Array<string> | undefined = undefined;
/**
* Used to track locks for authentication failure and acquiring connections
*/
protected connectionLockBox: LockBox<Lock> = new LockBox();
/**
* If this node is acting as a network authority then the claim is stored here and used as needed.
* If the node is not acting as an authority then the lack of claim here should indicate that.
* If the claim is missing then any request that requires it should reject with an error.
*/
protected claimNetworkAuthority: Token<ClaimNetworkAuthority> | undefined =
undefined;
/**
* If a node has joined a network then it's `ClaimNetworkAccess` is tracked here
*/
protected claimNetworkAccess: Token<ClaimNetworkAccess> | undefined =
undefined;
/**
* These are the level paths for mapping the ClaimNetworkAccess and ClaimNetworkAuthority claims for each network it has joined.
* Used to look up and switch between networks as needed.
*/
protected nodeManagerDbPath: LevelPath = [this.constructor.name];
protected nodeManagerClaimNetworkAuthorityPath: LevelPath = [
...this.nodeManagerDbPath,
'claimNetworkAuthority',
];
protected nodeManagerClaimNetworkAccessPath: LevelPath = [
...this.nodeManagerDbPath,
'claimNetworkAccess',
];
protected refreshBucketHandler: TaskHandler = async (
ctx,
_taskInfo,
bucketIndex: NodeBucketIndex,
) => {
await this.refreshBucket(bucketIndex, undefined, ctx);
// When completed reschedule the task
// if refreshBucketDelay is 0 then it's considered disabled
if (this.refreshBucketDelayTime > 0) {
const jitter = nodesUtils.refreshBucketsDelayJitter(
this.refreshBucketDelayTime,
this.refreshBucketDelayJitter,
);
await this.taskManager.scheduleTask({
delay: this.refreshBucketDelayTime + jitter,
handlerId: this.refreshBucketHandlerId,
lazy: true,
parameters: [bucketIndex],
path: [this.tasksPath, this.refreshBucketHandlerId, `${bucketIndex}`],
priority: 0,
});
}
};
public readonly refreshBucketHandlerId =
`${this.tasksPath}.refreshBucketHandler` as TaskHandlerId;
protected gcBucketHandler: TaskHandler = async (
ctx,
_taskInfo,
bucketIndex: number,
) => {
await this.garbageCollectBucket(
bucketIndex,
this.connectionConnectTimeoutTime,
ctx,
);
// Checking for any new pending tasks
const pendingNodesRemaining = this.pendingNodes.get(bucketIndex);
if (pendingNodesRemaining == null || pendingNodesRemaining.size === 0) {
return;
}
// Re-schedule the task
await this.setupGCTask(bucketIndex);
};
public readonly gcBucketHandlerId =
`${this.tasksPath}.gcBucketHandler` as TaskHandlerId;
protected checkConnectionsHandler: TaskHandler = async (ctx, taskInfo) => {
this.logger.debug('Checking connections');
let connectionCount = 0;
for (const connection of this.nodeConnectionManager.listConnections()) {
if (connection.primary && connection.authenticated) {
const [bucketId] = this.nodeGraph.bucketIndex(connection.nodeId);
if (bucketId === 255) connectionCount++;
}
}
if (connectionCount > 0) {
this.logger.debug('triggering bucket refresh for bucket 255');
await this.updateRefreshBucketDelay(255, 0, undefined, undefined, ctx);
}
try {
this.logger.debug(
'triggering findNode for self to populate closest nodes',
);
await this.findNode(
{
nodeId: this.keyRing.getNodeId(),
},
ctx,
);
} finally {
this.logger.debug('Checked connections');
// Re-schedule this task
await this.taskManager.scheduleTask({
delay: taskInfo.delay,
deadline: taskInfo.deadline,
handlerId: this.checkConnectionsHandlerId,
lazy: true,
path: [this.tasksPath, this.checkConnectionsHandlerId],
priority: taskInfo.priority,
});
}
};
public readonly checkConnectionsHandlerId: TaskHandlerId =
`${this.tasksPath}.checkConnectionsHandler` as TaskHandlerId;
protected syncNodeGraphHandler = async (
ctx: ContextTimed,
_taskInfo: TaskInfo | undefined,
network: string | undefined,
initialNodes: Array<[NodeIdEncoded, NodeAddress]>,
connectionConnectTimeoutTime: number | undefined,
) => {
// Establishing connections to the initial nodes
const connectionResults = await Promise.allSettled(
initialNodes.map(async ([nodeIdEncoded, nodeAddress]) => {
const resolvedHosts = await networkUtils.resolveHostnames(
[nodeAddress],
undefined,
this.dnsServers,
ctx,
);
if (resolvedHosts.length === 0) {
throw new nodesErrors.ErrorNodeManagerResolveNodeFailed(
`Failed to resolve '${nodeAddress[0]}'`,
);
}
const nodeId = nodesUtils.decodeNodeId(nodeIdEncoded);
if (nodeId == null) {
utils.never(`failed to decode NodeId "${nodeIdEncoded}"`);
}
return this.nodeConnectionManager.createConnectionMultiple(
[nodeId],
resolvedHosts,
{ timer: connectionConnectTimeoutTime, signal: ctx.signal },
);
}),
);
const successfulConnections = connectionResults.filter(
(r) => r.status === 'fulfilled',
) as Array<PromiseFulfilledResult<NodeConnection<Manifest>>>;
if (successfulConnections.length === 0) {
const failedConnectionErrors = connectionResults
.filter((r) => r.status === 'rejected')
.map((v) => {
if (v.status === 'rejected') return v.reason;
});
throw new nodesErrors.ErrorNodeManagerSyncNodeGraphFailed(
`Failed to establish any connections with the following errors '[${failedConnectionErrors}]'`,
{
cause: new AggregateError(failedConnectionErrors),
},
);
}
if (ctx.signal.aborted) return;
if (network != null) {
if ((await this.getClaimNetworkAccess(network)) == null) {
await this.claimNetwork(successfulConnections[0].value.nodeId, network);
} else {
await this.switchNetwork(network);
}
}
// Attempt a findNode operation looking for ourselves
await this.findNode(
{
nodeId: this.keyRing.getNodeId(),
},
ctx,
);
if (ctx.signal.aborted) return;
// Getting the closest node from the `NodeGraph`
let bucketIndex: number | undefined;
for await (const bucket of this.nodeGraph.getBuckets('distance', 'asc')) {
if (ctx.signal.aborted) return;
bucketIndex = bucket[0];
}
// If no buckets then end here
if (bucketIndex == null) return;
// Trigger refreshBucket operations for all buckets above bucketIndex
const refreshBuckets: Array<Promise<any>> = [];
for (let i = bucketIndex; i < this.nodeGraph.nodeIdBits; i++) {
const task = await this.updateRefreshBucketDelay(i, 0, false);
refreshBuckets.push(task.promise());
}
const signalP = utils.signalPromise(ctx.signal);
await Promise.race([Promise.all(refreshBuckets), signalP]).finally(
async () => {
// Clean up signal promise when done
signalP.cancel();
await signalP;
},
);
};
public readonly syncNodeGraphHandlerId: TaskHandlerId =
`${this.tasksPath}.syncNodeGraphHandler` as TaskHandlerId;
protected handleEventNodeConnectionManagerConnectionAuthenticated = async (
e: nodesEvents.EventNodeConnectionManagerConnectionAuthenticated,
) => {
await this.setNode(
e.detail.remoteNodeId,
[e.detail.remoteHost, e.detail.remotePort],
// FIXME: We want to distinguish punched, direct and local connections
{
mode: 'direct',
connectedTime: Date.now(),
scopes: ['global'],
},
false,
false,
);
};
constructor({
db,
keyRing,
sigchain,
gestaltGraph,
taskManager,
nodeGraph,
nodeConnectionManager,
mdnsOptions,
connectionConnectTimeoutTime = config.defaultsSystem
.nodesConnectionConnectTimeoutTime,
refreshBucketDelayTime = config.defaultsSystem
.nodesRefreshBucketIntervalTime,
refreshBucketDelayJitter = config.defaultsSystem
.nodesRefreshBucketIntervalTimeJitter,
retryConnectionsDelayTime = 45_000, // 45 seconds
nodesConnectionFindLocalTimeoutTime = config.defaultsSystem
.nodesConnectionFindLocalTimeoutTime,
dnsServers,
logger,
}: {
db: DB;
keyRing: KeyRing;
sigchain: Sigchain;
gestaltGraph: GestaltGraph;
taskManager: TaskManager;
nodeGraph: NodeGraph;
mdnsOptions?: {
groups: Array<Host>;
port: Port;
};
nodeConnectionManager: NodeConnectionManager<Manifest>;
connectionConnectTimeoutTime?: number;
refreshBucketDelayTime?: number;
refreshBucketDelayJitter?: number;
retryConnectionsDelayTime?: number;
nodesConnectionFindLocalTimeoutTime?: number;
dnsServers?: Array<string>;
logger?: Logger;
}) {
this.logger = logger ?? new Logger(this.constructor.name);
this.db = db;
this.keyRing = keyRing;
this.sigchain = sigchain;
this.nodeConnectionManager = nodeConnectionManager;
this.nodeGraph = nodeGraph;
this.taskManager = taskManager;
this.gestaltGraph = gestaltGraph;
this.mdnsOptions = mdnsOptions;
if (mdnsOptions != null) {
this.mdns = new MDNS({ logger: this.logger.getChild(MDNS.name) });
}
this.connectionConnectTimeoutTime = connectionConnectTimeoutTime;
this.refreshBucketDelayTime = refreshBucketDelayTime;
this.refreshBucketDelayJitter = Math.max(0, refreshBucketDelayJitter);
this.retryConnectionsDelayTime = retryConnectionsDelayTime;
this.connectionFindMDNSTimeoutTime = nodesConnectionFindLocalTimeoutTime;
if (dnsServers != null) {
this.logger.info(
`Overriding DNS resolution servers with ${JSON.stringify(dnsServers)}`,
);
}
this.dnsServers = dnsServers;
}
public async start() {
this.logger.info(`Starting ${this.constructor.name}`);
this.taskManager.registerHandler(
this.refreshBucketHandlerId,
this.refreshBucketHandler,
);
this.taskManager.registerHandler(
this.gcBucketHandlerId,
this.gcBucketHandler,
);
this.taskManager.registerHandler(
this.checkConnectionsHandlerId,
this.checkConnectionsHandler,
);
this.taskManager.registerHandler(
this.syncNodeGraphHandlerId,
this.syncNodeGraphHandler,
);
// This will clean up tasks that were not properly cleaned up during an ungracefully shutdown of the process
await this.stopTasks();
await this.setupRefreshBucketTasks();
// Can be disabled with 0 delay, only use for testing
if (this.retryConnectionsDelayTime > 0) {
await this.taskManager.scheduleTask({
delay: this.retryConnectionsDelayTime,
handlerId: this.checkConnectionsHandlerId,
lazy: true,
path: [this.tasksPath, this.checkConnectionsHandlerId],
});
}
// Starting MDNS
if (this.mdns != null) {
const nodeId = this.keyRing.getNodeId();
await this.mdns.start({
id: nodeId.toBuffer().readUint16BE(),
hostname: nodesUtils.encodeNodeId(nodeId),
groups: this.mdnsOptions!.groups,
port: this.mdnsOptions!.port,
});
this.mdns.registerService({
name: nodesUtils.encodeNodeId(this.keyRing.getNodeId()),
port: this.nodeConnectionManager.port,
type: 'polykey',
protocol: 'udp',
});
}
// Add handling for connections
this.nodeConnectionManager.addEventListener(
nodesEvents.EventNodeConnectionManagerConnectionAuthenticated.name,
this.handleEventNodeConnectionManagerConnectionAuthenticated,
);
this.logger.info(`Started ${this.constructor.name}`);
}
public async stop() {
this.logger.info(`Stopping ${this.constructor.name}`);
// Remove handling for connections
this.nodeConnectionManager.removeEventListener(
nodesEvents.EventNodeConnectionManagerConnectionAuthenticated.name,
this.handleEventNodeConnectionManagerConnectionAuthenticated,
);
await this.mdns?.stop();
await this.stopTasks();
this.taskManager.deregisterHandler(this.refreshBucketHandlerId);
this.taskManager.deregisterHandler(this.gcBucketHandlerId);
this.taskManager.deregisterHandler(this.checkConnectionsHandlerId);
this.taskManager.deregisterHandler(this.syncNodeGraphHandlerId);
this.logger.info(`Stopped ${this.constructor.name}`);
}
/**
* For usage with withF, to acquire a 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).
* @param nodeId Id of target node to communicate with
* @param ctx
* @returns ResourceAcquire Resource API for use in with contexts
*/
public acquireConnection(
nodeId: NodeId,
ctx: ContextTimed,
): ResourceAcquire<NodeConnection<Manifest>> {
if (this.keyRing.getNodeId().equals(nodeId)) {
throw new nodesErrors.ErrorNodeManagerNodeIdOwn();
}
return async () => {
return await this.connectionLockBox.withF(
[['acquireConnection', nodeId.toString()].join('.'), Lock],
async () => {
// Checking if connection already exists
if (!this.nodeConnectionManager.hasConnection(nodeId)) {
// Establish the connection
const result = await this.findNode({ nodeId: nodeId }, ctx);
if (result == null) {
throw new nodesErrors.ErrorNodeManagerConnectionFailed();
}
}
// Initiate authentication and await
return await this.nodeConnectionManager.acquireConnection(
nodeId,
ctx,
)();
},
);
};
}
/**
* 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 nodeId Id of target node to communicate with
* @param f Function to handle communication
* @param ctx
*/
public async withConnF<T>(
nodeId: NodeId,
ctx: Partial<ContextTimedInput> | undefined,
f: (conn: NodeConnection<Manifest>) => Promise<T>,
): Promise<T>;
@startStop.ready(new nodesErrors.ErrorNodeManagerNotRunning())
public async withConnF<T>(
nodeId: NodeId,
@decorators.context ctx: ContextTimed,
f: (conn: NodeConnection<Manifest>) => Promise<T>,
): Promise<T> {
return await withF(
[this.acquireConnection(nodeId, 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 nodeId Id of target node to communicate with
* @param g Generator function to handle communication
* @param ctx
*/
public withConnG<T, TReturn, TNext>(
nodeId: NodeId,
ctx: Partial<ContextTimedInput> | undefined,
g: (conn: NodeConnection<Manifest>) => AsyncGenerator<T, TReturn, TNext>,
): AsyncGenerator<T, TReturn, TNext>;
@startStop.ready(new nodesErrors.ErrorNodeManagerNotRunning())
@decorators.timed()
public async *withConnG<T, TReturn, TNext>(
nodeId: NodeId,
@decorators.context ctx: ContextTimed,
g: (conn: NodeConnection<Manifest>) => AsyncGenerator<T, TReturn, TNext>,
): AsyncGenerator<T, TReturn, TNext> {
const acquire = this.acquireConnection(nodeId, 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);
}
}
/**
* Will attempt to find a node within the network using a hybrid strategy of
* attempting signalled connections, direct connections and checking MDNS.
*
* Will attempt to fix regardless of existing connection.
* @param nodeId - NodeId of target to find.
* @param connectionConnectTimeoutTime - timeout time for each individual connection.
* @param connectionFindLocalTimeoutTime
* @param concurrencyLimit - Limit the number of concurrent connections.
* @param limit - Limit the number of total connections to be made before giving up.
* @param ctx
*/
public findNode(
{
nodeId,
connectionConnectTimeoutTime,
connectionFindMDNSTimeoutTime,
concurrencyLimit,
limit,
}: {
nodeId: NodeId;
connectionConnectTimeoutTime?: number;
connectionFindMDNSTimeoutTime?: number;
concurrencyLimit?: number;
limit?: number;
},
ctx?: Partial<ContextTimedInput>,
): PromiseCancellable<[NodeAddress, NodeContactAddressData] | undefined>;
@decorators.timedCancellable(true)
public async findNode(
{
nodeId,
connectionConnectTimeoutTime = this.connectionConnectTimeoutTime,
connectionFindMDNSTimeoutTime = this.connectionFindMDNSTimeoutTime,
concurrencyLimit = this.concurrencyLimit,
limit = this.nodeGraph.nodeBucketLimit,
}: {
nodeId: NodeId;
connectionConnectTimeoutTime: number;
connectionFindMDNSTimeoutTime: number;
concurrencyLimit: number;
limit: number;
},
@decorators.context ctx: ContextTimed,
): Promise<[NodeAddress, NodeContactAddressData] | undefined> {
// Setting up intermediate signal
const abortController = new AbortController();
const newCtx = {
timer: ctx.timer,
signal: abortController.signal,
};
const handleAbort = () => {
abortController.abort(ctx.signal.reason);
};
if (ctx.signal.aborted) {
handleAbort();
} else {
ctx.signal.addEventListener('abort', handleAbort, { once: true });
}
const rateLimit = new Semaphore(concurrencyLimit);
const connectionsQueue = new NodeConnectionQueue(
this.keyRing.getNodeId(),
nodeId,
limit,
rateLimit,
rateLimit,
);
// Starting discovery strategies
const findBySignal = this.findNodeBySignal(
nodeId,
connectionsQueue,
connectionConnectTimeoutTime,
newCtx,
);
const findByDirect = this.findNodeByDirect(
nodeId,
connectionsQueue,
connectionConnectTimeoutTime,
newCtx,
);
const findByMDNS = this.findNodeByMDNS(nodeId, {
timer: connectionFindMDNSTimeoutTime,
signal: newCtx.signal,
});
try {
return await Promise.any([findBySignal, findByDirect, findByMDNS]);
} catch (e) {
if (e instanceof AggregateError) {
for (const error of e.errors) {
// Checking if each error is an expected error
if (!(error instanceof nodesErrors.ErrorNodeManagerFindNodeFailed)) {
throw e;
}
}
} else if (!(e instanceof nodesErrors.ErrorNodeManagerFindNodeFailed)) {
throw e;
}
return;
} finally {
abortController.abort(abortPendingConnectionsReason);
await Promise.allSettled([findBySignal, findByDirect, findByMDNS]);
ctx.signal.removeEventListener('abort', handleAbort);
}
}
/**
* Will try to make a connection to the node using hole punched connections only
*
* @param nodeId - NodeId of the target to find.
* @param nodeConnectionsQueue - shared nodeConnectionQueue helper class.
* @param connectionConnectTimeoutTime - timeout time for each individual connection.
* @param ctx
*/
public findNodeBySignal(
nodeId: NodeId,
nodeConnectionsQueue: NodeConnectionQueue,
connectionConnectTimeoutTime?: number,
ctx?: Partial<ContextTimedInput>,
): PromiseCancellable<[[Host, Port], NodeContactAddressData]>;
@decorators.timedCancellable(true)
public async findNodeBySignal(
nodeId: NodeId,
nodeConnectionsQueue: NodeConnectionQueue,
connectionConnectTimeoutTime: number = this.connectionConnectTimeoutTime,
@decorators.context ctx: ContextTimed,
): Promise<[[Host, Port], NodeContactAddressData]> {
// Setting up intermediate signal
const abortController = new AbortController();
utils.setMaxListeners(abortController.signal);
const newCtx = {
timer: ctx.timer,
signal: abortController.signal,
};
const handleAbort = () => {
abortController.abort(ctx.signal.reason);
};
if (ctx.signal.aborted) {
handleAbort();
} else {
ctx.signal.addEventListener('abort', handleAbort, { once: true });
}
const chain: Map<string, string | undefined> = new Map();
let connectionMade: [Host, Port] | undefined;
// Seed the initial queue
for (const {
nodeId: nodeIdConnected,
} of this.nodeConnectionManager.getClosestConnections(nodeId)) {
nodeConnectionsQueue.queueNodeSignal(nodeIdConnected, undefined);
}
while (true) {
const isDone = await nodeConnectionsQueue.withNodeSignal(
async (nodeIdTarget, nodeIdSignaller) => {
let nodeConnection: NodeConnection<Manifest> | undefined;
if (
!this.nodeConnectionManager.hasConnection(nodeIdTarget) &&
nodeIdSignaller != null
) {
this.logger.debug(
`attempting connection to ${nodesUtils.encodeNodeId(
nodeIdTarget,
)} via ${nodesUtils.encodeNodeId(nodeIdSignaller)}`,
);
nodeConnection =
await this.nodeConnectionManager.createConnectionPunch(
nodeIdTarget,
nodeIdSignaller,
{
timer: connectionConnectTimeoutTime,
signal: newCtx.signal,
},
);
// If connection succeeds add it to the chain
chain.set(nodeIdTarget.toString(), nodeIdSignaller?.toString());
}
nodeConnectionsQueue.contactedNode(nodeIdTarget);
// If connection was our target then we're done
if (nodeId.toString() === nodeIdTarget.toString()) {
nodeConnection =
nodeConnection ??
this.nodeConnectionManager.getConnection(nodeIdTarget)
?.connection;
if (nodeConnection == null) utils.never('connection should exist');
connectionMade = [nodeConnection.host, nodeConnection.port];
return true;
}
await this.queueDataFromRequest(
nodeIdTarget,
nodeId,
nodeConnectionsQueue,
newCtx,
);
this.logger.debug(
`connection attempt to ${nodesUtils.encodeNodeId(
nodeIdTarget,
)} succeeded`,
);
return false;
},
newCtx,
);
if (isDone) break;
}
// After queue is done we want to signal and await clean up
abortController.abort(abortPendingConnectionsReason);
ctx.signal.removeEventListener('abort', handleAbort);
// Wait for pending attempts to finish
for (const pendingP of nodeConnectionsQueue.nodesRunningSignal) {
await pendingP.catch((e) => {
if (e instanceof nodesErrors.ErrorNodeConnectionTimeout) return;
throw e;
});
}
// Connection was not made
if (connectionMade == null) {
throw new nodesErrors.ErrorNodeManagerFindNodeFailed(
'failed to find node via signal',
);
}
// We can get the path taken with this code
// const path: Array<NodeId> = [];
// let current: string | undefined = nodeId.toString();
// while (current != null) {
// const nodeId = IdInternal.fromString<NodeId>(current);
// path.unshift(nodeId);
// current = chain.get(current);
// }
// console.log(path);
return [
connectionMade,
{
mode: 'signal',
connectedTime: Date.now(),
scopes: ['global'],
},
] as [[Host, Port], NodeContactAddressData];
}
/**
* Will try to make a connection to the node using direct connections only
*
* @param nodeId - NodeId of the target to find.
* @param nodeConnectionsQueue - shared nodeConnectionQueue helper class.
* @param connectionConnectTimeoutTime - timeout time for each individual connection.
* @param ctx
*/
public findNodeByDirect(
nodeId: NodeId,
nodeConnectionsQueue: NodeConnectionQueue,
connectionConnectTimeoutTime?: number,
ctx?: Partial<ContextTimedInput>,
): PromiseCancellable<[[Host, Port], NodeContactAddressData]>;
@decorators.timedCancellable(true)
public async findNodeByDirect(
nodeId: NodeId,
nodeConnectionsQueue: NodeConnectionQueue,
connectionConnectTimeoutTime: number = this.connectionConnectTimeoutTime,
@decorators.context ctx: ContextTimed,
): Promise<[[Host, Port], NodeContactAddressData]> {
// Setting up intermediate signal
const abortController = new AbortController();
utils.setMaxListeners(abortController.signal);
const newCtx = {
timer: ctx.timer,
signal: abortController.signal,
};
const handleAbort = () => {
abortController.abort(ctx.signal.reason);
};
if (ctx.signal.aborted) {
handleAbort();
} else {
ctx.signal.addEventListener('abort', handleAbort, { once: true });
}
let connectionMade = false;
// Seed the initial queue
for (const [
nodeIdTarget,
nodeContact,
] of await this.nodeGraph.getClosestNodes(
nodeId,
this.nodeGraph.nodeBucketLimit,
undefined,
ctx,
)) {
nodeConnectionsQueue.queueNodeDirect(nodeIdTarget, nodeContact);
}
while (true) {
const isDone = await nodeConnectionsQueue.withNodeDirect(
async (nodeIdTarget, nodeContact) => {
if (!this.nodeConnectionManager.hasConnection(nodeIdTarget)) {
this.logger.debug(
`attempting connection to ${nodesUtils.encodeNodeId(
nodeIdTarget,
)} via direct connection`,
);
// Attempt all direct
const addresses: Array<NodeAddress> = [];
for (const [
nodeContactAddress,
nodeContactAddressData,
] of Object.entries(nodeContact)) {
const [host, port] =
nodesUtils.parseNodeContactAddress(nodeContactAddress);
if (nodeContactAddressData.mode === 'direct') {
addresses.push([host, port]);
}
}
const resolvedHosts = await networkUtils.resolveHostnames(
addresses,
undefined,
this.dnsServers,
ctx,
);
try {
await this.nodeConnectionManager.createConnectionMultiple(
[nodeIdTarget],
resolvedHosts,
{ timer: connectionConnectTimeoutTime, signal: newCtx.signal },
);
} catch (e) {
if (e instanceof nodesErrors.ErrorNodeConnectionTimeout) {
return false;
}
throw e;
}
}
nodeConnectionsQueue.contactedNode(nodeIdTarget);
// If connection was our target then we're done
if (nodeId.toString() === nodeIdTarget.toString()) {
connectionMade = true;
return true;
}
await this.queueDataFromRequest(
nodeIdTarget,
nodeId,
nodeConnectionsQueue,
newCtx,
);
this.logger.debug(
`connection attempt to ${nodesUtils.encodeNodeId(
nodeIdTarget,
)} succeeded`,
);
return false;
},
newCtx,
);
if (isDone) break;
}
// After queue is done we want to signal and await clean up
abortController.abort(abortPendingConnectionsReason);
ctx.signal.removeEventListener('abort', handleAbort);
// Wait for pending attempts to finish
for (const pendingP of nodeConnectionsQueue.nodesRunningDirect) {
await pendingP.catch((e) => {
if (e instanceof nodesErrors.ErrorNodeConnectionTimeout) return;
throw e;
});
}
if (!connectionMade) {
throw new nodesErrors.ErrorNodeManagerFindNodeFailed(
'failed to find node via direct',
);
}
const conAndTimer = this.nodeConnectionManager.getConnection(nodeId);
if (conAndTimer == null) {
utils.never('connection should have been established');
}
return [
[conAndTimer.connection.host, conAndTimer.connection.port],
{
mode: 'direct',
connectedTime: Date.now(),
scopes: ['global'],
},
] as [[Host, Port], NodeContactAddressData];
}
/**
* Will query via MDNS for running Polykey nodes with the matching NodeId
*
* @param nodeId
* @param ctx
*/
public queryMDNS(
nodeId: NodeId,
ctx?: Partial<ContextTimedInput>,
): PromiseCancellable<Array<[Host, Port]>>;
@decorators.timedCancellable(