@streamr/dht 102.0.0-beta.0 → 102.0.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (264) hide show
  1. package/dist/generated/packages/dht/protos/DhtRpc.d.ts +16 -8
  2. package/dist/generated/packages/dht/protos/DhtRpc.js +7 -5
  3. package/dist/generated/packages/dht/protos/DhtRpc.js.map +1 -1
  4. package/dist/package.json +15 -16
  5. package/dist/src/connection/ConnectionManager.js +18 -8
  6. package/dist/src/connection/ConnectionManager.js.map +1 -1
  7. package/dist/src/connection/Handshaker.d.ts +1 -1
  8. package/dist/src/connection/Handshaker.js +9 -5
  9. package/dist/src/connection/Handshaker.js.map +1 -1
  10. package/dist/src/connection/ManagedConnection.js +17 -7
  11. package/dist/src/connection/ManagedConnection.js.map +1 -1
  12. package/dist/src/connection/connectivityChecker.js +20 -10
  13. package/dist/src/connection/connectivityChecker.js.map +1 -1
  14. package/dist/src/connection/connectivityRequestHandler.js +3 -3
  15. package/dist/src/connection/connectivityRequestHandler.js.map +1 -1
  16. package/dist/src/connection/simulator/Simulator.js +3 -2
  17. package/dist/src/connection/simulator/Simulator.js.map +1 -1
  18. package/dist/src/connection/simulator/pings.d.ts +1 -1
  19. package/dist/src/connection/simulator/pings.js +3 -3
  20. package/dist/src/connection/simulator/pings.js.map +1 -1
  21. package/dist/src/connection/webrtc/NodeWebrtcConnection.js +0 -2
  22. package/dist/src/connection/webrtc/NodeWebrtcConnection.js.map +1 -1
  23. package/dist/src/connection/webrtc/WebrtcConnector.js +19 -9
  24. package/dist/src/connection/webrtc/WebrtcConnector.js.map +1 -1
  25. package/dist/src/connection/webrtc/iceServerAsString.js +1 -2
  26. package/dist/src/connection/webrtc/iceServerAsString.js.map +1 -1
  27. package/dist/src/connection/websocket/AbstractWebsocketClientConnection.d.ts +0 -2
  28. package/dist/src/connection/websocket/WebsocketClientConnectorRpcLocal.d.ts +0 -1
  29. package/dist/src/connection/websocket/WebsocketServerConnection.d.ts +0 -1
  30. package/dist/src/connection/websocket/WebsocketServerConnector.js +28 -18
  31. package/dist/src/connection/websocket/WebsocketServerConnector.js.map +1 -1
  32. package/dist/src/dht/DhtNode.d.ts +1 -0
  33. package/dist/src/dht/DhtNode.js +3 -2
  34. package/dist/src/dht/DhtNode.js.map +1 -1
  35. package/dist/src/dht/DhtNodeRpcLocal.d.ts +1 -1
  36. package/dist/src/dht/PeerManager.d.ts +2 -1
  37. package/dist/src/dht/PeerManager.js +2 -1
  38. package/dist/src/dht/PeerManager.js.map +1 -1
  39. package/dist/src/dht/contact/SortedContactList.js +1 -1
  40. package/dist/src/dht/contact/SortedContactList.js.map +1 -1
  41. package/dist/src/dht/discovery/DiscoverySession.d.ts +0 -1
  42. package/dist/src/dht/discovery/PeerDiscovery.d.ts +0 -1
  43. package/dist/src/dht/discovery/RingDiscoverySession.d.ts +0 -1
  44. package/dist/src/dht/recursive-operation/RecursiveOperationManager.d.ts +2 -2
  45. package/dist/src/dht/routing/DuplicateDetector.js.map +1 -1
  46. package/dist/src/dht/routing/RoutingSession.js +2 -2
  47. package/dist/src/dht/routing/RoutingSession.js.map +1 -1
  48. package/dist/src/dht/routing/RoutingTablesCache.d.ts +1 -1
  49. package/dist/src/dht/store/LocalDataStore.js +1 -1
  50. package/dist/src/dht/store/LocalDataStore.js.map +1 -1
  51. package/dist/src/dht/store/StoreManager.d.ts +1 -1
  52. package/dist/src/dht/store/StoreRpcLocal.d.ts +1 -1
  53. package/dist/src/helpers/AddressTools.js +2 -3
  54. package/dist/src/helpers/AddressTools.js.map +1 -1
  55. package/dist/src/helpers/debugHelpers.js +2 -2
  56. package/dist/src/helpers/debugHelpers.js.map +1 -1
  57. package/dist/src/helpers/protoClasses.d.ts +1 -1
  58. package/dist/src/helpers/protoClasses.js.map +1 -1
  59. package/dist/src/helpers/protoToString.js +1 -2
  60. package/dist/src/helpers/protoToString.js.map +1 -1
  61. package/dist/src/helpers/version.d.ts +1 -1
  62. package/dist/src/helpers/version.js +4 -4
  63. package/dist/src/helpers/version.js.map +1 -1
  64. package/eslint.config.mjs +12 -0
  65. package/jest.config.ts +12 -0
  66. package/package.json +15 -16
  67. package/protos/DhtRpc.proto +6 -4
  68. package/.eslintignore +0 -5
  69. package/.eslintrc +0 -3
  70. package/generated/google/protobuf/any.ts +0 -326
  71. package/generated/google/protobuf/empty.ts +0 -81
  72. package/generated/google/protobuf/timestamp.ts +0 -287
  73. package/generated/packages/dht/protos/DhtRpc.client.ts +0 -419
  74. package/generated/packages/dht/protos/DhtRpc.server.ts +0 -165
  75. package/generated/packages/dht/protos/DhtRpc.ts +0 -1266
  76. package/generated/packages/proto-rpc/protos/ProtoRpc.ts +0 -108
  77. package/jest.config.js +0 -5
  78. package/src/connection/Connection.ts +0 -28
  79. package/src/connection/ConnectionLockRpcLocal.ts +0 -78
  80. package/src/connection/ConnectionLockRpcRemote.ts +0 -64
  81. package/src/connection/ConnectionLockStates.ts +0 -131
  82. package/src/connection/ConnectionManager.ts +0 -661
  83. package/src/connection/ConnectionsView.ts +0 -8
  84. package/src/connection/ConnectorFacade.ts +0 -217
  85. package/src/connection/Handshaker.ts +0 -205
  86. package/src/connection/IConnection.ts +0 -40
  87. package/src/connection/ManagedConnection.ts +0 -113
  88. package/src/connection/OutputBuffer.ts +0 -28
  89. package/src/connection/PendingConnection.ts +0 -68
  90. package/src/connection/connectivityChecker.ts +0 -108
  91. package/src/connection/connectivityRequestHandler.ts +0 -116
  92. package/src/connection/simulator/Simulator.ts +0 -368
  93. package/src/connection/simulator/SimulatorConnection.ts +0 -137
  94. package/src/connection/simulator/SimulatorConnector.ts +0 -98
  95. package/src/connection/simulator/SimulatorTransport.ts +0 -15
  96. package/src/connection/simulator/pings.ts +0 -42
  97. package/src/connection/webrtc/BrowserWebrtcConnection.ts +0 -242
  98. package/src/connection/webrtc/IWebrtcConnection.ts +0 -24
  99. package/src/connection/webrtc/NodeWebrtcConnection.ts +0 -247
  100. package/src/connection/webrtc/WebrtcConnector.ts +0 -234
  101. package/src/connection/webrtc/WebrtcConnectorRpcLocal.ts +0 -108
  102. package/src/connection/webrtc/WebrtcConnectorRpcRemote.ts +0 -60
  103. package/src/connection/webrtc/iceServerAsString.ts +0 -15
  104. package/src/connection/websocket/AbstractWebsocketClientConnection.ts +0 -122
  105. package/src/connection/websocket/AutoCertifierClientFacade.ts +0 -89
  106. package/src/connection/websocket/BrowserWebsocketClientConnection.ts +0 -44
  107. package/src/connection/websocket/NodeWebsocketClientConnection.ts +0 -39
  108. package/src/connection/websocket/WebsocketClientConnector.ts +0 -119
  109. package/src/connection/websocket/WebsocketClientConnectorRpcLocal.ts +0 -38
  110. package/src/connection/websocket/WebsocketClientConnectorRpcRemote.ts +0 -19
  111. package/src/connection/websocket/WebsocketServer.ts +0 -164
  112. package/src/connection/websocket/WebsocketServerConnection.ts +0 -109
  113. package/src/connection/websocket/WebsocketServerConnector.ts +0 -286
  114. package/src/dht/DhtNode.ts +0 -678
  115. package/src/dht/DhtNodeRpcLocal.ts +0 -84
  116. package/src/dht/DhtNodeRpcRemote.ts +0 -107
  117. package/src/dht/ExternalApiRpcLocal.ts +0 -58
  118. package/src/dht/ExternalApiRpcRemote.ts +0 -41
  119. package/src/dht/PeerManager.ts +0 -303
  120. package/src/dht/contact/Contact.ts +0 -19
  121. package/src/dht/contact/ContactList.ts +0 -43
  122. package/src/dht/contact/RandomContactList.ts +0 -56
  123. package/src/dht/contact/RingContactList.ts +0 -143
  124. package/src/dht/contact/RpcRemote.ts +0 -72
  125. package/src/dht/contact/SortedContactList.ts +0 -173
  126. package/src/dht/contact/getClosestNodes.ts +0 -24
  127. package/src/dht/contact/ringIdentifiers.ts +0 -62
  128. package/src/dht/discovery/DiscoverySession.ts +0 -129
  129. package/src/dht/discovery/PeerDiscovery.ts +0 -244
  130. package/src/dht/discovery/RingDiscoverySession.ts +0 -148
  131. package/src/dht/recursive-operation/RecursiveOperationManager.ts +0 -251
  132. package/src/dht/recursive-operation/RecursiveOperationRpcLocal.ts +0 -34
  133. package/src/dht/recursive-operation/RecursiveOperationRpcRemote.ts +0 -43
  134. package/src/dht/recursive-operation/RecursiveOperationSession.ts +0 -231
  135. package/src/dht/recursive-operation/RecursiveOperationSessionRpcLocal.ts +0 -35
  136. package/src/dht/recursive-operation/RecursiveOperationSessionRpcRemote.ts +0 -30
  137. package/src/dht/routing/DuplicateDetector.ts +0 -34
  138. package/src/dht/routing/Router.ts +0 -246
  139. package/src/dht/routing/RouterRpcLocal.ts +0 -78
  140. package/src/dht/routing/RouterRpcRemote.ts +0 -80
  141. package/src/dht/routing/RoutingSession.ts +0 -243
  142. package/src/dht/routing/RoutingTablesCache.ts +0 -60
  143. package/src/dht/routing/getPreviousPeer.ts +0 -6
  144. package/src/dht/store/LocalDataStore.ts +0 -84
  145. package/src/dht/store/StoreManager.ts +0 -170
  146. package/src/dht/store/StoreRpcLocal.ts +0 -89
  147. package/src/dht/store/StoreRpcRemote.ts +0 -32
  148. package/src/exports.ts +0 -33
  149. package/src/helpers/AddressTools.ts +0 -28
  150. package/src/helpers/Connectivity.ts +0 -19
  151. package/src/helpers/browser/isBrowserEnvironment.ts +0 -1
  152. package/src/helpers/browser/isBrowserEnvironment_override.ts +0 -3
  153. package/src/helpers/createPeerDescriptor.ts +0 -57
  154. package/src/helpers/createPeerDescriptorSignaturePayload.ts +0 -28
  155. package/src/helpers/debugHelpers.ts +0 -9
  156. package/src/helpers/errors.ts +0 -49
  157. package/src/helpers/offering.ts +0 -15
  158. package/src/helpers/protoClasses.ts +0 -57
  159. package/src/helpers/protoToString.ts +0 -21
  160. package/src/helpers/version.ts +0 -32
  161. package/src/identifiers.ts +0 -29
  162. package/src/rpc-protocol/DhtCallContext.ts +0 -14
  163. package/src/rpc-protocol/DhtRpcOptions.ts +0 -10
  164. package/src/transport/ITransport.ts +0 -37
  165. package/src/transport/ListeningRpcCommunicator.ts +0 -32
  166. package/src/transport/RoutingRpcCommunicator.ts +0 -66
  167. package/src/types/ServiceID.ts +0 -1
  168. package/src/types/textencoding.d.ts +0 -6
  169. package/test/benchmark/Find.test.ts +0 -72
  170. package/test/benchmark/KademliaCorrectness.test.ts +0 -114
  171. package/test/benchmark/RingCorrectness.test.ts +0 -157
  172. package/test/benchmark/SortedContactListBenchmark.test.ts +0 -108
  173. package/test/benchmark/WebsocketServerMemoryLeak.test.ts +0 -41
  174. package/test/benchmark/hybrid-network-simulation/RingContactList.test.ts +0 -71
  175. package/test/end-to-end/GeoIpLayer0.test.ts +0 -55
  176. package/test/end-to-end/Layer0-Layer1.test.ts +0 -93
  177. package/test/end-to-end/Layer0.test.ts +0 -76
  178. package/test/end-to-end/Layer0MixedConnectionTypes.test.ts +0 -110
  179. package/test/end-to-end/Layer0Webrtc-Layer1.test.ts +0 -137
  180. package/test/end-to-end/Layer0Webrtc.test.ts +0 -85
  181. package/test/end-to-end/Layer1-Scale-WebSocket.test.ts +0 -82
  182. package/test/end-to-end/Layer1-Scale-Webrtc.test.ts +0 -76
  183. package/test/end-to-end/RecoveryFromFailedAutoCertification.test.ts +0 -52
  184. package/test/end-to-end/WebsocketConnectionRequest.test.ts +0 -69
  185. package/test/end-to-end/memory-leak.test.ts +0 -80
  186. package/test/integration/ConnectionLocking.test.ts +0 -182
  187. package/test/integration/ConnectionManager.test.ts +0 -528
  188. package/test/integration/ConnectivityChecking.test.ts +0 -53
  189. package/test/integration/DhtJoinPeerDiscovery.test.ts +0 -49
  190. package/test/integration/DhtNode.test.ts +0 -66
  191. package/test/integration/DhtNodeExternalAPI.test.ts +0 -48
  192. package/test/integration/DhtNodeRpcRemote.test.ts +0 -66
  193. package/test/integration/DhtRpc.test.ts +0 -121
  194. package/test/integration/Find.test.ts +0 -45
  195. package/test/integration/GeoIpConnectivityChecking.test.ts +0 -72
  196. package/test/integration/Layer1-scale.test.ts +0 -189
  197. package/test/integration/Mock-Layer1-Layer0.test.ts +0 -85
  198. package/test/integration/MultipleEntryPointJoining.test.ts +0 -105
  199. package/test/integration/ReplicateData.test.ts +0 -104
  200. package/test/integration/RouteMessage.test.ts +0 -230
  201. package/test/integration/RouterRpcRemote.test.ts +0 -77
  202. package/test/integration/SimultaneousConnections.test.ts +0 -316
  203. package/test/integration/Store.test.ts +0 -85
  204. package/test/integration/StoreAndDelete.test.ts +0 -77
  205. package/test/integration/StoreOnDhtWithThreeNodes.test.ts +0 -59
  206. package/test/integration/StoreOnDhtWithTwoNodes.test.ts +0 -51
  207. package/test/integration/StoreRpcRemote.test.ts +0 -54
  208. package/test/integration/WebrtcConnectionManagement.test.ts +0 -219
  209. package/test/integration/WebrtcConnectorRpc.test.ts +0 -125
  210. package/test/integration/Websocket.test.ts +0 -65
  211. package/test/integration/WebsocketClientConnectorRpc.test.ts +0 -69
  212. package/test/integration/WebsocketConnectionManagement.test.ts +0 -191
  213. package/test/integration/rpc-connections-over-webrtc.test.ts +0 -158
  214. package/test/kademlia-simulation/data/nodeids.json +0 -13002
  215. package/test/kademlia-simulation/data/orderedneighbors.json +0 -1001
  216. package/test/types/global.d.ts +0 -1
  217. package/test/unit/AddressTools.test.ts +0 -44
  218. package/test/unit/AutoCertifierClientFacade.test.ts +0 -58
  219. package/test/unit/ConnectionManager.test.ts +0 -65
  220. package/test/unit/ConnectivityHelpers.test.ts +0 -61
  221. package/test/unit/DiscoverySession.test.ts +0 -87
  222. package/test/unit/DuplicateDetector.test.ts +0 -31
  223. package/test/unit/Handshaker.test.ts +0 -169
  224. package/test/unit/ListeningRpcCommunicator.test.ts +0 -52
  225. package/test/unit/LocalDataStore.test.ts +0 -108
  226. package/test/unit/ManagedConnection.test.ts +0 -58
  227. package/test/unit/PeerManager.test.ts +0 -93
  228. package/test/unit/PendingConnection.test.ts +0 -57
  229. package/test/unit/ProtobufMessage.test.ts +0 -21
  230. package/test/unit/RandomContactList.test.ts +0 -58
  231. package/test/unit/RecursiveOperationManager.test.ts +0 -161
  232. package/test/unit/RecursiveOperationSession.test.ts +0 -68
  233. package/test/unit/Router.test.ts +0 -137
  234. package/test/unit/RoutingSession.test.ts +0 -79
  235. package/test/unit/SortedContactList.test.ts +0 -115
  236. package/test/unit/StoreManager.test.ts +0 -146
  237. package/test/unit/StoreRpcLocal.test.ts +0 -167
  238. package/test/unit/WebrtcConnection.test.ts +0 -29
  239. package/test/unit/WebrtcConnector.test.ts +0 -56
  240. package/test/unit/WebsocketClientConnector.test.ts +0 -101
  241. package/test/unit/WebsocketServer.test.ts +0 -66
  242. package/test/unit/WebsocketServerConnector.test.ts +0 -102
  243. package/test/unit/connectivityRequestHandler.test.ts +0 -104
  244. package/test/unit/createPeerDescriptor.test.ts +0 -69
  245. package/test/unit/customMatchers.test.ts +0 -16
  246. package/test/unit/getClosestNodes.test.ts +0 -30
  247. package/test/unit/version.test.ts +0 -18
  248. package/test/unit/webrtcReplaceInternalIpWithExternalIp.test.ts +0 -18
  249. package/test/utils/FakeConnectorFacade.ts +0 -41
  250. package/test/utils/FakeRpcCommunicator.ts +0 -23
  251. package/test/utils/FakeTransport.ts +0 -79
  252. package/test/utils/customMatchers.ts +0 -71
  253. package/test/utils/mock/MockConnection.ts +0 -26
  254. package/test/utils/mock/MockConnectionsView.ts +0 -18
  255. package/test/utils/mock/MockRouter.ts +0 -62
  256. package/test/utils/mock/MockRpcCommunicator.ts +0 -7
  257. package/test/utils/mock/MockTransport.ts +0 -26
  258. package/test/utils/mock/mockDataEntry.ts +0 -38
  259. package/test/utils/topology.ts +0 -80
  260. package/test/utils/utils.ts +0 -268
  261. package/tsconfig.browser.json +0 -17
  262. package/tsconfig.jest.json +0 -25
  263. package/tsconfig.json +0 -3
  264. package/tsconfig.node.json +0 -24
@@ -1,678 +0,0 @@
1
- import { ServerCallContext } from '@protobuf-ts/runtime-rpc'
2
- import {
3
- Logger,
4
- MetricsContext,
5
- merge,
6
- scheduleAtInterval,
7
- waitForCondition
8
- } from '@streamr/utils'
9
- import { EventEmitter } from 'eventemitter3'
10
- import { sample } from 'lodash'
11
- import type { MarkRequired } from 'ts-essentials'
12
- import { ConnectionLocker, ConnectionManager, PortRange, TlsCertificate } from '../connection/ConnectionManager'
13
- import { ConnectionsView } from '../connection/ConnectionsView'
14
- import { DefaultConnectorFacade, DefaultConnectorFacadeOptions } from '../connection/ConnectorFacade'
15
- import { IceServer } from '../connection/webrtc/WebrtcConnector'
16
- import { isBrowserEnvironment } from '../helpers/browser/isBrowserEnvironment'
17
- import { createPeerDescriptor } from '../helpers/createPeerDescriptor'
18
- import { DhtAddress, KADEMLIA_ID_LENGTH_IN_BYTES, toNodeId } from '../identifiers'
19
- import { Any } from '../../generated/google/protobuf/any'
20
- import {
21
- ClosestPeersRequest,
22
- ClosestPeersResponse,
23
- ClosestRingPeersRequest,
24
- ClosestRingPeersResponse,
25
- ConnectivityResponse,
26
- DataEntry,
27
- ExternalFetchDataRequest,
28
- ExternalFetchDataResponse,
29
- ExternalStoreDataRequest,
30
- ExternalStoreDataResponse,
31
- LeaveNotice,
32
- Message,
33
- PeerDescriptor,
34
- PingRequest,
35
- PingResponse,
36
- RecursiveOperation
37
- } from '../../generated/packages/dht/protos/DhtRpc'
38
- import { ExternalApiRpcClient, StoreRpcClient } from '../../generated/packages/dht/protos/DhtRpc.client'
39
- import { ITransport, TransportEvents } from '../transport/ITransport'
40
- import { RoutingRpcCommunicator } from '../transport/RoutingRpcCommunicator'
41
- import { ServiceID } from '../types/ServiceID'
42
- import { DhtNodeRpcLocal } from './DhtNodeRpcLocal'
43
- import { DhtNodeRpcRemote } from './DhtNodeRpcRemote'
44
- import { ExternalApiRpcLocal } from './ExternalApiRpcLocal'
45
- import { ExternalApiRpcRemote } from './ExternalApiRpcRemote'
46
- import { PeerManager } from './PeerManager'
47
- import { RingContacts } from './contact/RingContactList'
48
- import { RingIdRaw } from './contact/ringIdentifiers'
49
- import { PeerDiscovery } from './discovery/PeerDiscovery'
50
- import { RecursiveOperationManager } from './recursive-operation/RecursiveOperationManager'
51
- import { Router } from './routing/Router'
52
- import { LocalDataStore } from './store/LocalDataStore'
53
- import { StoreManager } from './store/StoreManager'
54
- import { StoreRpcRemote } from './store/StoreRpcRemote'
55
- import { getLocalRegionByCoordinates, getLocalRegionWithCache } from '@streamr/cdn-location'
56
-
57
- export interface DhtNodeEvents {
58
- nearbyContactAdded: (peerDescriptor: PeerDescriptor) => void
59
- nearbyContactRemoved: (peerDescriptor: PeerDescriptor) => void
60
- randomContactAdded: (peerDescriptor: PeerDescriptor) => void
61
- randomContactRemoved: (peerDescriptor: PeerDescriptor) => void
62
- ringContactAdded: (peerDescriptor: PeerDescriptor) => void
63
- ringContactRemoved: (peerDescriptor: PeerDescriptor) => void
64
- manualRejoinRequired: () => void
65
- }
66
-
67
- export interface DhtNodeOptions {
68
- serviceId?: ServiceID
69
- joinParallelism?: number
70
- maxContactCount?: number
71
- numberOfNodesPerKBucket?: number
72
- joinNoProgressLimit?: number
73
- peerDiscoveryQueryBatchSize?: number
74
- dhtJoinTimeout?: number
75
- metricsContext?: MetricsContext
76
- storeHighestTtl?: number
77
- storeMaxTtl?: number
78
- networkConnectivityTimeout?: number
79
- storageRedundancyFactor?: number
80
- periodicallyPingNeighbors?: boolean
81
- periodicallyPingRingContacts?: boolean
82
-
83
- transport?: ITransport
84
- connectionsView?: ConnectionsView
85
- connectionLocker?: ConnectionLocker
86
- peerDescriptor?: PeerDescriptor
87
- entryPoints?: PeerDescriptor[]
88
- websocketHost?: string
89
- websocketPortRange?: PortRange
90
- websocketServerEnableTls?: boolean
91
- nodeId?: DhtAddress
92
- region?: number
93
-
94
- rpcRequestTimeout?: number
95
- iceServers?: IceServer[]
96
- webrtcAllowPrivateAddresses?: boolean
97
- webrtcDatachannelBufferThresholdLow?: number
98
- webrtcDatachannelBufferThresholdHigh?: number
99
- webrtcPortRange?: PortRange
100
- maxMessageSize?: number
101
- maxConnections?: number
102
- tlsCertificate?: TlsCertificate
103
- externalIp?: string
104
- autoCertifierUrl?: string
105
- autoCertifierConfigFile?: string
106
- geoIpDatabaseFolder?: string
107
- allowIncomingPrivateConnections?: boolean
108
- }
109
-
110
- type StrictDhtNodeOptions = MarkRequired<DhtNodeOptions,
111
- 'serviceId' |
112
- 'joinParallelism' |
113
- 'maxContactCount' |
114
- 'numberOfNodesPerKBucket' |
115
- 'joinNoProgressLimit' |
116
- 'dhtJoinTimeout' |
117
- 'peerDiscoveryQueryBatchSize' |
118
- 'maxConnections' |
119
- 'storeHighestTtl' |
120
- 'storeMaxTtl' |
121
- 'networkConnectivityTimeout' |
122
- 'storageRedundancyFactor' |
123
- 'metricsContext'>
124
-
125
- const logger = new Logger(module)
126
-
127
- const PERIODICAL_PING_INTERVAL = 60 * 1000
128
-
129
- // TODO move this to trackerless-network package and change serviceId to be a required paramater
130
- export const CONTROL_LAYER_NODE_SERVICE_ID = 'layer0'
131
-
132
- export type Events = TransportEvents & DhtNodeEvents
133
-
134
- export class DhtNode extends EventEmitter<Events> implements ITransport {
135
-
136
- private readonly options: StrictDhtNodeOptions
137
- private rpcCommunicator?: RoutingRpcCommunicator
138
- private transport?: ITransport
139
- private localPeerDescriptor?: PeerDescriptor
140
- private router?: Router
141
- private storeManager?: StoreManager
142
- private localDataStore: LocalDataStore
143
- private recursiveOperationManager?: RecursiveOperationManager
144
- private peerDiscovery?: PeerDiscovery
145
- private peerManager?: PeerManager
146
- private connectionsView?: ConnectionsView
147
- public connectionLocker?: ConnectionLocker
148
- private started = false
149
- private abortController = new AbortController()
150
-
151
- constructor(conf: DhtNodeOptions) {
152
- super()
153
- this.options = merge({
154
- serviceId: CONTROL_LAYER_NODE_SERVICE_ID,
155
- joinParallelism: 3,
156
- maxContactCount: 200,
157
- numberOfNodesPerKBucket: 8,
158
- joinNoProgressLimit: 5,
159
- dhtJoinTimeout: 60000,
160
- peerDiscoveryQueryBatchSize: 5,
161
- maxConnections: 80,
162
- storeHighestTtl: 60000,
163
- storeMaxTtl: 60000,
164
- networkConnectivityTimeout: 10000,
165
- storageRedundancyFactor: 5, // TODO validate that this is > 1 (as each node should replicate the data to other node)
166
- metricsContext: new MetricsContext()
167
- }, conf)
168
- this.validateOptions()
169
- this.localDataStore = new LocalDataStore(this.options.storeMaxTtl)
170
- this.send = this.send.bind(this)
171
- }
172
-
173
- private validateOptions(): void {
174
- const expectedNodeIdLength = KADEMLIA_ID_LENGTH_IN_BYTES * 2
175
- if (this.options.nodeId !== undefined) {
176
- if (!/^[0-9a-fA-F]+$/.test(this.options.nodeId)) {
177
- throw new Error('Invalid nodeId, the nodeId should be a hex string')
178
- } else if (this.options.nodeId.length !== expectedNodeIdLength) {
179
- throw new Error(`Invalid nodeId, the length of the nodeId should be ${expectedNodeIdLength}`)
180
- }
181
- }
182
- if (this.options.peerDescriptor !== undefined) {
183
- if (this.options.peerDescriptor.nodeId.length !== KADEMLIA_ID_LENGTH_IN_BYTES) {
184
- throw new Error(`Invalid peerDescriptor, the length of the nodeId should be ${KADEMLIA_ID_LENGTH_IN_BYTES} bytes`)
185
- }
186
- }
187
- if (this.options.transport !== undefined && this.options.connectionsView === undefined) {
188
- throw new Error('connectionsView is required when transport is given')
189
- }
190
- }
191
-
192
- public async start(): Promise<void> {
193
- if (this.started || this.abortController.signal.aborted) {
194
- return
195
- }
196
- logger.trace(`Starting new Streamr Network DHT Node with serviceId ${this.options.serviceId}`)
197
- this.started = true
198
-
199
- if (isBrowserEnvironment()) {
200
- this.options.websocketPortRange = undefined
201
- if (this.options.peerDescriptor) {
202
- this.options.peerDescriptor.websocket = undefined
203
- }
204
- }
205
-
206
- // If transport is given, do not create a ConnectionManager
207
- if (this.options.transport) {
208
- this.transport = this.options.transport
209
- this.connectionsView = this.options.connectionsView
210
- this.connectionLocker = this.options.connectionLocker
211
- this.localPeerDescriptor = this.transport.getLocalPeerDescriptor()
212
- } else {
213
- const connectorFacadeOptions: DefaultConnectorFacadeOptions = {
214
- transport: this,
215
- entryPoints: this.options.entryPoints,
216
- iceServers: this.options.iceServers,
217
- webrtcAllowPrivateAddresses: this.options.webrtcAllowPrivateAddresses,
218
- webrtcDatachannelBufferThresholdLow: this.options.webrtcDatachannelBufferThresholdLow,
219
- webrtcDatachannelBufferThresholdHigh: this.options.webrtcDatachannelBufferThresholdHigh,
220
- webrtcPortRange: this.options.webrtcPortRange,
221
- maxMessageSize: this.options.maxMessageSize,
222
- websocketServerEnableTls: this.options.websocketServerEnableTls,
223
- tlsCertificate: this.options.tlsCertificate,
224
- externalIp: this.options.externalIp,
225
- autoCertifierUrl: this.options.autoCertifierUrl,
226
- autoCertifierConfigFile: this.options.autoCertifierConfigFile,
227
- geoIpDatabaseFolder: this.options.geoIpDatabaseFolder,
228
- createLocalPeerDescriptor: (connectivityResponse: ConnectivityResponse) => this.generatePeerDescriptorCallBack(connectivityResponse)
229
- }
230
- // If own PeerDescriptor is given in options, create a ConnectionManager with ws server
231
- if (this.options.peerDescriptor?.websocket) {
232
- connectorFacadeOptions.websocketHost = this.options.peerDescriptor.websocket.host
233
- connectorFacadeOptions.websocketPortRange = {
234
- min: this.options.peerDescriptor.websocket.port,
235
- max: this.options.peerDescriptor.websocket.port
236
- }
237
- // If websocketPortRange is given, create ws server using it, websocketHost can be undefined
238
- } else if (this.options.websocketPortRange) {
239
- connectorFacadeOptions.websocketHost = this.options.websocketHost
240
- connectorFacadeOptions.websocketPortRange = this.options.websocketPortRange
241
- }
242
-
243
- const connectionManager = new ConnectionManager({
244
- createConnectorFacade: () => new DefaultConnectorFacade(connectorFacadeOptions),
245
- maxConnections: this.options.maxConnections,
246
- metricsContext: this.options.metricsContext,
247
- allowIncomingPrivateConnections: this.options.allowIncomingPrivateConnections ?? false
248
- })
249
- await connectionManager.start()
250
- this.connectionsView = connectionManager
251
- this.connectionLocker = connectionManager
252
- this.transport = connectionManager
253
- }
254
-
255
- this.rpcCommunicator = new RoutingRpcCommunicator(
256
- this.options.serviceId,
257
- (msg, opts) => this.transport!.send(msg, opts),
258
- { rpcRequestTimeout: this.options.rpcRequestTimeout }
259
- )
260
-
261
- this.transport.on('message', (message: Message) => this.handleMessageFromTransport(message))
262
-
263
- this.initPeerManager()
264
-
265
- this.peerDiscovery = new PeerDiscovery({
266
- localPeerDescriptor: this.localPeerDescriptor!,
267
- joinNoProgressLimit: this.options.joinNoProgressLimit,
268
- joinTimeout: this.options.dhtJoinTimeout,
269
- serviceId: this.options.serviceId,
270
- parallelism: this.options.joinParallelism,
271
- connectionLocker: this.connectionLocker,
272
- peerManager: this.peerManager!,
273
- abortSignal: this.abortController.signal,
274
- createDhtNodeRpcRemote: (peerDescriptor: PeerDescriptor) => this.createDhtNodeRpcRemote(peerDescriptor),
275
- })
276
- this.router = new Router({
277
- rpcCommunicator: this.rpcCommunicator,
278
- localPeerDescriptor: this.localPeerDescriptor!,
279
- handleMessage: (message: Message) => this.handleMessageFromRouter(message),
280
- getConnections: () => this.connectionsView!.getConnections()
281
- })
282
- this.recursiveOperationManager = new RecursiveOperationManager({
283
- rpcCommunicator: this.rpcCommunicator,
284
- router: this.router,
285
- sessionTransport: this,
286
- connectionsView: this.connectionsView!,
287
- localPeerDescriptor: this.localPeerDescriptor!,
288
- serviceId: this.options.serviceId,
289
- localDataStore: this.localDataStore,
290
- addContact: (contact: PeerDescriptor) => this.peerManager!.addContact(contact),
291
- createDhtNodeRpcRemote: (peerDescriptor: PeerDescriptor) => this.createDhtNodeRpcRemote(peerDescriptor),
292
- })
293
- this.storeManager = new StoreManager({
294
- rpcCommunicator: this.rpcCommunicator,
295
- recursiveOperationManager: this.recursiveOperationManager,
296
- localPeerDescriptor: this.localPeerDescriptor!,
297
- serviceId: this.options.serviceId,
298
- highestTtl: this.options.storeHighestTtl,
299
- redundancyFactor: this.options.storageRedundancyFactor,
300
- localDataStore: this.localDataStore,
301
- getNeighbors: () => this.peerManager!.getNeighbors().map((n) => n.getPeerDescriptor()),
302
- createRpcRemote: (contact: PeerDescriptor) => {
303
- return new StoreRpcRemote(
304
- this.localPeerDescriptor!,
305
- contact,
306
- this.rpcCommunicator!,
307
- StoreRpcClient,
308
- this.options.rpcRequestTimeout
309
- )
310
- }
311
- })
312
- this.on('nearbyContactAdded', (peerDescriptor: PeerDescriptor) => {
313
- this.storeManager!.onContactAdded(peerDescriptor)
314
- })
315
- this.bindRpcLocalMethods()
316
-
317
- const pruneTargets = []
318
- if (this.options.periodicallyPingNeighbors === true) {
319
- pruneTargets.push(() => this.peerManager!.getNeighbors().map((node) => this.createDhtNodeRpcRemote(node.getPeerDescriptor())))
320
- }
321
- if (this.options.periodicallyPingRingContacts === true) {
322
- pruneTargets.push(() => this.peerManager!.getRingContacts().getAllContacts())
323
- }
324
- for (const pruneTarget of pruneTargets) {
325
- await scheduleAtInterval(
326
- async () => {
327
- const nodes = pruneTarget()
328
- await this.peerManager!.pruneOfflineNodes(nodes)
329
- }, PERIODICAL_PING_INTERVAL, false, this.abortController.signal
330
- )
331
- }
332
- }
333
-
334
- private initPeerManager() {
335
- this.peerManager = new PeerManager({
336
- numberOfNodesPerKBucket: this.options.numberOfNodesPerKBucket,
337
- maxContactCount: this.options.maxContactCount,
338
- localNodeId: this.getNodeId(),
339
- localPeerDescriptor: this.localPeerDescriptor!,
340
- connectionLocker: this.connectionLocker,
341
- lockId: this.options.serviceId,
342
- createDhtNodeRpcRemote: (peerDescriptor: PeerDescriptor) => this.createDhtNodeRpcRemote(peerDescriptor),
343
- hasConnection: (nodeId: DhtAddress) => this.connectionsView!.hasConnection(nodeId)
344
- })
345
- this.peerManager.on('nearbyContactRemoved', (peerDescriptor: PeerDescriptor) => {
346
- this.emit('nearbyContactRemoved', peerDescriptor)
347
- })
348
- this.peerManager.on('nearbyContactAdded', (peerDescriptor: PeerDescriptor) =>
349
- this.emit('nearbyContactAdded', peerDescriptor)
350
- )
351
- this.peerManager.on('randomContactRemoved', (peerDescriptor: PeerDescriptor) =>
352
- this.emit('randomContactRemoved', peerDescriptor)
353
- )
354
- this.peerManager.on('randomContactAdded', (peerDescriptor: PeerDescriptor) =>
355
- this.emit('randomContactAdded', peerDescriptor)
356
- )
357
- this.peerManager.on('ringContactRemoved', (peerDescriptor: PeerDescriptor) => {
358
- this.emit('ringContactRemoved', peerDescriptor)
359
- })
360
- this.peerManager.on('ringContactAdded', (peerDescriptor: PeerDescriptor) => {
361
- this.emit('ringContactAdded', peerDescriptor)
362
- })
363
- this.peerManager.on('kBucketEmpty', () => {
364
- if (!this.peerDiscovery!.isJoinOngoing()) {
365
- if (this.options.entryPoints && this.options.entryPoints.length > 0) {
366
- setImmediate(async () => {
367
- const contactedPeers = new Set<DhtAddress>()
368
- const distantJoinContactPeers = new Set<DhtAddress>()
369
- // TODO should we catch possible promise rejection?
370
- await Promise.all(this.options.entryPoints!.map((entryPoint) =>
371
- this.peerDiscovery!.rejoinDht(entryPoint, contactedPeers, distantJoinContactPeers)
372
- ))
373
- })
374
- } else {
375
- this.emit('manualRejoinRequired')
376
- }
377
- }
378
- })
379
- this.transport!.on('connected', (peerDescriptor: PeerDescriptor) => {
380
- this.router!.onNodeConnected(peerDescriptor)
381
- this.emit('connected', peerDescriptor)
382
- })
383
- this.transport!.on('disconnected', (peerDescriptor: PeerDescriptor, gracefulLeave: boolean) => {
384
- const isControlLayerNode = (this.connectionLocker !== undefined)
385
- if (isControlLayerNode) {
386
- const nodeId = toNodeId(peerDescriptor)
387
- if (gracefulLeave) {
388
- this.peerManager!.removeContact(nodeId)
389
- } else {
390
- this.peerManager!.removeNeighbor(nodeId)
391
- }
392
- }
393
- this.router!.onNodeDisconnected(peerDescriptor)
394
- this.emit('disconnected', peerDescriptor, gracefulLeave)
395
- })
396
- }
397
-
398
- private bindRpcLocalMethods(): void {
399
- if (!this.started || this.abortController.signal.aborted) {
400
- return
401
- }
402
- const dhtNodeRpcLocal = new DhtNodeRpcLocal({
403
- peerDiscoveryQueryBatchSize: this.options.peerDiscoveryQueryBatchSize,
404
- getNeighbors: () => this.peerManager!.getNeighbors().map((n) => n.getPeerDescriptor()),
405
- getClosestRingContactsTo: (ringIdRaw: RingIdRaw, limit: number) => {
406
- return this.getClosestRingContactsTo(ringIdRaw, limit)
407
- },
408
- addContact: (contact: PeerDescriptor) => this.peerManager!.addContact(contact),
409
- removeContact: (nodeId: DhtAddress) => this.removeContact(nodeId)
410
- })
411
- this.rpcCommunicator!.registerRpcMethod(ClosestPeersRequest, ClosestPeersResponse, 'getClosestPeers',
412
- (req: ClosestPeersRequest, context) => dhtNodeRpcLocal.getClosestPeers(req, context))
413
- this.rpcCommunicator!.registerRpcMethod(ClosestRingPeersRequest, ClosestRingPeersResponse, 'getClosestRingPeers',
414
- (req: ClosestRingPeersRequest, context) => dhtNodeRpcLocal.getClosestRingPeers(req, context))
415
- this.rpcCommunicator!.registerRpcMethod(PingRequest, PingResponse, 'ping',
416
- (req: PingRequest, context) => dhtNodeRpcLocal.ping(req, context))
417
- this.rpcCommunicator!.registerRpcNotification(LeaveNotice, 'leaveNotice',
418
- (_req: LeaveNotice, context) => dhtNodeRpcLocal.leaveNotice(context))
419
- const externalApiRpcLocal = new ExternalApiRpcLocal({
420
- executeRecursiveOperation: (key: DhtAddress, operation: RecursiveOperation, excludedPeer: DhtAddress) => {
421
- return this.recursiveOperationManager!.execute(key, operation, excludedPeer)
422
- },
423
- storeDataToDht: (key: DhtAddress, data: Any, creator?: DhtAddress) => this.storeDataToDht(key, data, creator)
424
- })
425
- this.rpcCommunicator!.registerRpcMethod(
426
- ExternalFetchDataRequest,
427
- ExternalFetchDataResponse,
428
- 'externalFetchData',
429
- (req: ExternalFetchDataRequest, context: ServerCallContext) => externalApiRpcLocal.externalFetchData(req, context),
430
- { timeout: 10000 } // TODO use options option or named constant?
431
- )
432
- this.rpcCommunicator!.registerRpcMethod(
433
- ExternalStoreDataRequest,
434
- ExternalStoreDataResponse,
435
- 'externalStoreData',
436
- (req: ExternalStoreDataRequest, context: ServerCallContext) => externalApiRpcLocal.externalStoreData(req, context),
437
- { timeout: 10000 } // TODO use options option or named constant?
438
- )
439
- }
440
-
441
- private handleMessageFromTransport(message: Message): void {
442
- if (message.serviceId === this.options.serviceId) {
443
- this.rpcCommunicator?.handleMessageFromPeer(message)
444
- }
445
- }
446
-
447
- private handleMessageFromRouter(message: Message): void {
448
- if (message.serviceId === this.options.serviceId) {
449
- this.rpcCommunicator?.handleMessageFromPeer(message)
450
- } else {
451
- this.emit('message', message)
452
- }
453
- }
454
-
455
- private async generatePeerDescriptorCallBack(connectivityResponse: ConnectivityResponse) {
456
- if (this.options.peerDescriptor !== undefined) {
457
- this.localPeerDescriptor = this.options.peerDescriptor
458
- } else {
459
- let region: number | undefined = undefined
460
- if (this.options.region !== undefined) {
461
- region = this.options.region
462
- logger.debug(`Using region ${region} from options when generating local PeerDescriptor`)
463
- } else if (connectivityResponse.latitude !== undefined && connectivityResponse.longitude !== undefined) {
464
- region = getLocalRegionByCoordinates(connectivityResponse.latitude, connectivityResponse.longitude)
465
- logger.debug(`Using region ${region} from GeoIP when generating local PeerDescriptor`)
466
- } else {
467
- // as a fallback get the region from the CDN
468
- // and if it's not available, use a random region
469
- region = await getLocalRegionWithCache()
470
- logger.debug(`Using region ${region} from CDN when generating local PeerDescriptor`)
471
- }
472
-
473
- this.localPeerDescriptor = createPeerDescriptor(connectivityResponse, region, this.options.nodeId)
474
- }
475
- return this.localPeerDescriptor
476
- }
477
-
478
- public getClosestContacts(limit?: number): PeerDescriptor[] {
479
- return this.peerManager!.getNearbyContacts()
480
- .getClosestContacts(limit)
481
- .map((peer) => peer.getPeerDescriptor())
482
- }
483
-
484
- getRandomContacts(limit?: number): PeerDescriptor[] {
485
- return this.peerManager!.getRandomContacts().getContacts(limit).map((c) => c.getPeerDescriptor())
486
- }
487
-
488
- getRingContacts(): RingContacts {
489
- const contacts = this.peerManager!.getRingContacts().getClosestContacts()
490
- return {
491
- left: contacts.left.map((c) => c.getPeerDescriptor()),
492
- right: contacts.right.map((c) => c.getPeerDescriptor())
493
- }
494
- }
495
-
496
- public getClosestRingContactsTo(ringIdRaw: RingIdRaw, limit?: number): RingContacts {
497
- const closest = this.peerManager!.getClosestRingContactsTo(ringIdRaw, limit)
498
- return {
499
- left: closest.left.map((dhtPeer: DhtNodeRpcRemote) => dhtPeer.getPeerDescriptor()),
500
- right: closest.right.map((dhtPeer: DhtNodeRpcRemote) => dhtPeer.getPeerDescriptor())
501
- }
502
- }
503
-
504
- public getNodeId(): DhtAddress {
505
- return toNodeId(this.localPeerDescriptor!)
506
- }
507
-
508
- public getNeighborCount(): number {
509
- return this.peerManager!.getNeighborCount()
510
- }
511
-
512
- public removeContact(nodeId: DhtAddress): void {
513
- if (!this.started) { // the stopped state is checked in PeerManager
514
- return
515
- }
516
- this.peerManager!.removeContact(nodeId)
517
- }
518
-
519
- public async send(msg: Message): Promise<void> {
520
- if (!this.started || this.abortController.signal.aborted) {
521
- return
522
- }
523
- const reachableThrough = this.peerDiscovery!.isJoinOngoing() ? this.getConnectedEntryPoints() : []
524
- this.router!.send(msg, reachableThrough)
525
- }
526
-
527
- private getConnectedEntryPoints(): PeerDescriptor[] {
528
- return this.options.entryPoints !== undefined ? this.options.entryPoints.filter((entryPoint) =>
529
- this.connectionsView!.hasConnection(toNodeId(entryPoint))
530
- ) : []
531
- }
532
-
533
- public async joinDht(entryPointDescriptors: PeerDescriptor[], doAdditionalDistantPeerDiscovery?: boolean, retry?: boolean): Promise<void> {
534
- if (!this.started) {
535
- throw new Error('Cannot join DHT before calling start() on DhtNode')
536
- }
537
- await this.peerDiscovery!.joinDht(entryPointDescriptors, doAdditionalDistantPeerDiscovery, retry)
538
- }
539
-
540
- public async joinRing(): Promise<void> {
541
- if (!this.started) {
542
- throw new Error('Cannot join ring before calling start() on DhtNode')
543
- }
544
- await this.peerDiscovery!.joinRing()
545
- }
546
-
547
- public async storeDataToDht(key: DhtAddress, data: Any, creator?: DhtAddress): Promise<PeerDescriptor[]> {
548
- const connectedEntryPoints = this.getConnectedEntryPoints()
549
- if (this.peerDiscovery!.isJoinOngoing() && connectedEntryPoints.length > 0) {
550
- return this.storeDataToDhtViaPeer(key, data, sample(connectedEntryPoints)!)
551
- }
552
- return this.storeManager!.storeDataToDht(key, data, creator ?? this.getNodeId())
553
- }
554
-
555
- public async storeDataToDhtViaPeer(key: DhtAddress, data: Any, peer: PeerDescriptor): Promise<PeerDescriptor[]> {
556
- const rpcRemote = new ExternalApiRpcRemote(
557
- this.localPeerDescriptor!,
558
- peer,
559
- this.rpcCommunicator!,
560
- ExternalApiRpcClient
561
- )
562
- return await rpcRemote.storeData(key, data)
563
- }
564
-
565
- public async fetchDataFromDht(key: DhtAddress): Promise<DataEntry[]> {
566
- const connectedEntryPoints = this.getConnectedEntryPoints()
567
- if (this.peerDiscovery!.isJoinOngoing() && connectedEntryPoints.length > 0) {
568
- return this.fetchDataFromDhtViaPeer(key, sample(connectedEntryPoints)!)
569
- }
570
- const result = await this.recursiveOperationManager!.execute(key, RecursiveOperation.FETCH_DATA)
571
- return result.dataEntries ?? [] // TODO is this fallback needed?
572
- }
573
-
574
- public async fetchDataFromDhtViaPeer(key: DhtAddress, peer: PeerDescriptor): Promise<DataEntry[]> {
575
- const rpcRemote = new ExternalApiRpcRemote(
576
- this.localPeerDescriptor!,
577
- peer,
578
- this.rpcCommunicator!,
579
- ExternalApiRpcClient
580
- )
581
- return await rpcRemote.externalFetchData(key)
582
- }
583
-
584
- public async deleteDataFromDht(key: DhtAddress, waitForCompletion: boolean): Promise<void> {
585
- if (!this.abortController.signal.aborted) {
586
- await this.recursiveOperationManager!.execute(key, RecursiveOperation.DELETE_DATA, undefined, waitForCompletion)
587
- }
588
- }
589
-
590
- async findClosestNodesFromDht(key: DhtAddress): Promise<PeerDescriptor[]> {
591
- const result = await this.recursiveOperationManager!.execute(key, RecursiveOperation.FIND_CLOSEST_NODES)
592
- return result.closestNodes
593
- }
594
-
595
- public getTransport(): ITransport {
596
- return this.transport!
597
- }
598
-
599
- public getLocalPeerDescriptor(): PeerDescriptor {
600
- return this.localPeerDescriptor!
601
- }
602
-
603
- public getNeighbors(): PeerDescriptor[] {
604
- return this.started ? this.peerManager!.getNeighbors().map((remote: DhtNodeRpcRemote) => remote.getPeerDescriptor()) : []
605
- }
606
-
607
- getConnectionsView(): ConnectionsView {
608
- return this.connectionsView!
609
- }
610
-
611
- public getLocalLockedConnectionCount(): number {
612
- return this.connectionLocker!.getLocalLockedConnectionCount()
613
- }
614
-
615
- public getRemoteLockedConnectionCount(): number {
616
- return this.connectionLocker!.getRemoteLockedConnectionCount()
617
- }
618
-
619
- public getWeakLockedConnectionCount(): number {
620
- return this.connectionLocker!.getWeakLockedConnectionCount()
621
- }
622
-
623
- public async waitForNetworkConnectivity(): Promise<void> {
624
- await waitForCondition(
625
- () => this.connectionsView!.getConnectionCount() > 0,
626
- this.options.networkConnectivityTimeout,
627
- 100,
628
- this.abortController.signal
629
- )
630
- }
631
-
632
- public hasJoined(): boolean {
633
- return this.peerDiscovery!.isJoinCalled()
634
- }
635
-
636
- public getDiagnosticInfo(): Record<string, unknown> {
637
- return {
638
- localPeerDescriptor: this.localPeerDescriptor,
639
- transport: this.transport!.getDiagnosticInfo(),
640
- router: this.router!.getDiagnosticInfo(),
641
- neighborCount: this.getNeighborCount(),
642
- nearbyContactCount: Array.from(this.peerManager!.getNearbyContacts().getAllContactsInUndefinedOrder()).length,
643
- randomContactCount: this.peerManager!.getRandomContacts().getSize()
644
- }
645
- }
646
-
647
- public async stop(): Promise<void> {
648
- if (this.abortController.signal.aborted || !this.started) {
649
- return
650
- }
651
- logger.trace('stop()')
652
- this.abortController.abort()
653
- await this.storeManager!.destroy()
654
- this.localDataStore.clear()
655
- this.peerManager?.stop()
656
- this.rpcCommunicator!.stop()
657
- this.router!.stop()
658
- this.recursiveOperationManager!.stop()
659
- if (this.options.transport === undefined) {
660
- // if the transport was not given in options, the instance was created in start() and
661
- // this component is responsible for stopping it
662
- await this.transport!.stop()
663
- }
664
- this.transport = undefined
665
- this.connectionLocker = undefined
666
- this.removeAllListeners()
667
- }
668
-
669
- private createDhtNodeRpcRemote(peerDescriptor: PeerDescriptor) {
670
- return new DhtNodeRpcRemote(
671
- this.localPeerDescriptor!,
672
- peerDescriptor,
673
- this.options.serviceId,
674
- this.rpcCommunicator!,
675
- this.options.rpcRequestTimeout
676
- )
677
- }
678
- }