libp2p 0.43.4 → 0.44.0

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 (105) hide show
  1. package/dist/index.min.js +30 -30
  2. package/dist/src/autonat/index.d.ts +1 -2
  3. package/dist/src/autonat/index.d.ts.map +1 -1
  4. package/dist/src/autonat/index.js +4 -6
  5. package/dist/src/autonat/index.js.map +1 -1
  6. package/dist/src/circuit-relay/transport/reservation-store.d.ts +1 -1
  7. package/dist/src/circuit-relay/transport/reservation-store.d.ts.map +1 -1
  8. package/dist/src/circuit-relay/utils.d.ts.map +1 -1
  9. package/dist/src/circuit-relay/utils.js +3 -1
  10. package/dist/src/circuit-relay/utils.js.map +1 -1
  11. package/dist/src/components.d.ts +1 -6
  12. package/dist/src/components.d.ts.map +1 -1
  13. package/dist/src/components.js +0 -10
  14. package/dist/src/components.js.map +1 -1
  15. package/dist/src/config.d.ts.map +1 -1
  16. package/dist/src/config.js +0 -9
  17. package/dist/src/config.js.map +1 -1
  18. package/dist/src/connection-manager/auto-dial.d.ts +36 -0
  19. package/dist/src/connection-manager/auto-dial.d.ts.map +1 -0
  20. package/dist/src/connection-manager/auto-dial.js +122 -0
  21. package/dist/src/connection-manager/auto-dial.js.map +1 -0
  22. package/dist/src/connection-manager/connection-pruner.d.ts +28 -0
  23. package/dist/src/connection-manager/connection-pruner.d.ts.map +1 -0
  24. package/dist/src/connection-manager/connection-pruner.js +96 -0
  25. package/dist/src/connection-manager/connection-pruner.js.map +1 -0
  26. package/dist/src/connection-manager/constants.d.ts +49 -0
  27. package/dist/src/connection-manager/constants.d.ts.map +1 -0
  28. package/dist/src/connection-manager/constants.js +49 -0
  29. package/dist/src/connection-manager/constants.js.map +1 -0
  30. package/dist/src/connection-manager/dial-queue.d.ts +77 -0
  31. package/dist/src/connection-manager/dial-queue.d.ts.map +1 -0
  32. package/dist/src/connection-manager/dial-queue.js +366 -0
  33. package/dist/src/connection-manager/dial-queue.js.map +1 -0
  34. package/dist/src/connection-manager/index.d.ts +65 -69
  35. package/dist/src/connection-manager/index.d.ts.map +1 -1
  36. package/dist/src/connection-manager/index.js +116 -234
  37. package/dist/src/connection-manager/index.js.map +1 -1
  38. package/dist/src/connection-manager/utils.d.ts +9 -0
  39. package/dist/src/connection-manager/utils.d.ts.map +1 -0
  40. package/dist/src/connection-manager/utils.js +66 -0
  41. package/dist/src/connection-manager/utils.js.map +1 -0
  42. package/dist/src/fetch/index.js +3 -3
  43. package/dist/src/fetch/index.js.map +1 -1
  44. package/dist/src/identify/index.js +5 -5
  45. package/dist/src/identify/index.js.map +1 -1
  46. package/dist/src/insecure/index.d.ts.map +1 -1
  47. package/dist/src/insecure/index.js +3 -1
  48. package/dist/src/insecure/index.js.map +1 -1
  49. package/dist/src/libp2p.d.ts +10 -2
  50. package/dist/src/libp2p.d.ts.map +1 -1
  51. package/dist/src/libp2p.js +7 -13
  52. package/dist/src/libp2p.js.map +1 -1
  53. package/dist/src/upgrader.d.ts +1 -1
  54. package/dist/src/upgrader.d.ts.map +1 -1
  55. package/dist/src/upgrader.js +2 -1
  56. package/dist/src/upgrader.js.map +1 -1
  57. package/dist/typedoc-urls.json +1 -1
  58. package/package.json +18 -18
  59. package/src/autonat/index.ts +6 -9
  60. package/src/circuit-relay/transport/reservation-store.ts +1 -1
  61. package/src/circuit-relay/utils.ts +3 -1
  62. package/src/components.ts +1 -17
  63. package/src/config.ts +0 -9
  64. package/src/connection-manager/auto-dial.ts +171 -0
  65. package/src/connection-manager/connection-pruner.ts +137 -0
  66. package/src/connection-manager/constants.ts +60 -0
  67. package/src/connection-manager/dial-queue.ts +504 -0
  68. package/src/connection-manager/index.ts +190 -323
  69. package/src/connection-manager/utils.ts +76 -0
  70. package/src/fetch/index.ts +4 -4
  71. package/src/identify/index.ts +5 -5
  72. package/src/insecure/index.ts +5 -1
  73. package/src/libp2p.ts +17 -15
  74. package/src/upgrader.ts +3 -2
  75. package/src/version.ts +1 -1
  76. package/dist/src/connection-manager/auto-dialler.d.ts +0 -42
  77. package/dist/src/connection-manager/auto-dialler.d.ts.map +0 -1
  78. package/dist/src/connection-manager/auto-dialler.js +0 -105
  79. package/dist/src/connection-manager/auto-dialler.js.map +0 -1
  80. package/dist/src/connection-manager/dialer/dial-request.d.ts +0 -27
  81. package/dist/src/connection-manager/dialer/dial-request.d.ts.map +0 -1
  82. package/dist/src/connection-manager/dialer/dial-request.js +0 -114
  83. package/dist/src/connection-manager/dialer/dial-request.js.map +0 -1
  84. package/dist/src/connection-manager/dialer/index.d.ts +0 -121
  85. package/dist/src/connection-manager/dialer/index.d.ts.map +0 -1
  86. package/dist/src/connection-manager/dialer/index.js +0 -324
  87. package/dist/src/connection-manager/dialer/index.js.map +0 -1
  88. package/dist/src/connection-manager/latency-monitor.d.ts +0 -120
  89. package/dist/src/connection-manager/latency-monitor.d.ts.map +0 -1
  90. package/dist/src/connection-manager/latency-monitor.js +0 -220
  91. package/dist/src/connection-manager/latency-monitor.js.map +0 -1
  92. package/dist/src/connection-manager/visibility-change-emitter.d.ts +0 -66
  93. package/dist/src/connection-manager/visibility-change-emitter.d.ts.map +0 -1
  94. package/dist/src/connection-manager/visibility-change-emitter.js +0 -118
  95. package/dist/src/connection-manager/visibility-change-emitter.js.map +0 -1
  96. package/dist/src/constants.d.ts +0 -27
  97. package/dist/src/constants.d.ts.map +0 -1
  98. package/dist/src/constants.js +0 -31
  99. package/dist/src/constants.js.map +0 -1
  100. package/src/connection-manager/auto-dialler.ts +0 -158
  101. package/src/connection-manager/dialer/dial-request.ts +0 -144
  102. package/src/connection-manager/dialer/index.ts +0 -461
  103. package/src/connection-manager/latency-monitor.ts +0 -319
  104. package/src/connection-manager/visibility-change-emitter.ts +0 -135
  105. package/src/constants.ts +0 -36
@@ -1,220 +0,0 @@
1
- /**
2
- * This code is based on `latency-monitor` (https://github.com/mlucool/latency-monitor) by `mlucool` (https://github.com/mlucool), available under Apache License 2.0 (https://github.com/mlucool/latency-monitor/blob/master/LICENSE)
3
- */
4
- import { CustomEvent, EventEmitter } from '@libp2p/interfaces/events';
5
- import { VisibilityChangeEmitter } from './visibility-change-emitter.js';
6
- import { logger } from '@libp2p/logger';
7
- const log = logger('libp2p:connection-manager:latency-monitor');
8
- /**
9
- * A class to monitor latency of any async function which works in a browser or node. This works by periodically calling
10
- * the asyncTestFn and timing how long it takes the callback to be called. It can also periodically emit stats about this.
11
- * This can be disabled and stats can be pulled via setting dataEmitIntervalMs = 0.
12
- *
13
- * @extends {EventEmitter}
14
- *
15
- * The default implementation is an event loop latency monitor. This works by firing periodic events into the event loop
16
- * and timing how long it takes to get back.
17
- *
18
- * @example
19
- * const monitor = new LatencyMonitor();
20
- * monitor.on('data', (summary) => console.log('Event Loop Latency: %O', summary));
21
- *
22
- * @example
23
- * const monitor = new LatencyMonitor({latencyCheckIntervalMs: 1000, dataEmitIntervalMs: 60000, asyncTestFn:ping});
24
- * monitor.on('data', (summary) => console.log('Ping Pong Latency: %O', summary));
25
- */
26
- export class LatencyMonitor extends EventEmitter {
27
- constructor(init = {}) {
28
- super();
29
- const { latencyCheckIntervalMs, dataEmitIntervalMs, asyncTestFn, latencyRandomPercentage } = init;
30
- // 0 isn't valid here, so its ok to use ||
31
- this.latencyCheckIntervalMs = latencyCheckIntervalMs ?? 500; // 0.5s
32
- this.latencyRandomPercentage = latencyRandomPercentage ?? 10;
33
- this.latencyCheckMultiply = 2 * (this.latencyRandomPercentage / 100.0) * this.latencyCheckIntervalMs;
34
- this.latencyCheckSubtract = this.latencyCheckMultiply / 2;
35
- this.dataEmitIntervalMs = (dataEmitIntervalMs === null || dataEmitIntervalMs === 0)
36
- ? undefined
37
- : dataEmitIntervalMs ?? 5 * 1000; // 5s
38
- log('latencyCheckIntervalMs: %s dataEmitIntervalMs: %s', this.latencyCheckIntervalMs, this.dataEmitIntervalMs);
39
- if (this.dataEmitIntervalMs != null) {
40
- log('Expecting ~%s events per summary', this.latencyCheckIntervalMs / this.dataEmitIntervalMs);
41
- }
42
- else {
43
- log('Not emitting summaries');
44
- }
45
- this.asyncTestFn = asyncTestFn; // If there is no asyncFn, we measure latency
46
- // If process: use high resolution timer
47
- if (globalThis.process?.hrtime != null) {
48
- log('Using process.hrtime for timing');
49
- this.now = globalThis.process.hrtime; // eslint-disable-line no-undef
50
- this.getDeltaMS = (startTime) => {
51
- const hrtime = this.now(startTime);
52
- return (hrtime[0] * 1000) + (hrtime[1] / 1000000);
53
- };
54
- // Let's try for a timer that only monotonically increases
55
- }
56
- else if (typeof window !== 'undefined' && window.performance?.now != null) {
57
- log('Using performance.now for timing');
58
- this.now = window.performance.now.bind(window.performance);
59
- this.getDeltaMS = (startTime) => Math.round(this.now() - startTime);
60
- }
61
- else {
62
- log('Using Date.now for timing');
63
- this.now = Date.now;
64
- this.getDeltaMS = (startTime) => this.now() - startTime;
65
- }
66
- this.latencyData = this.initLatencyData();
67
- }
68
- start() {
69
- // We check for isBrowser because of browsers set max rates of timeouts when a page is hidden,
70
- // so we fall back to another library
71
- // See: http://stackoverflow.com/questions/6032429/chrome-timeouts-interval-suspended-in-background-tabs
72
- if (isBrowser()) {
73
- this.visibilityChangeEmitter = new VisibilityChangeEmitter();
74
- this.visibilityChangeEmitter.addEventListener('visibilityChange', (evt) => {
75
- const { detail: pageInFocus } = evt;
76
- if (pageInFocus) {
77
- this._startTimers();
78
- }
79
- else {
80
- this._emitSummary();
81
- this._stopTimers();
82
- }
83
- });
84
- }
85
- if (this.visibilityChangeEmitter?.isVisible() === true) {
86
- this._startTimers();
87
- }
88
- }
89
- stop() {
90
- this._stopTimers();
91
- }
92
- /**
93
- * Start internal timers
94
- *
95
- * @private
96
- */
97
- _startTimers() {
98
- // Timer already started, ignore this
99
- if (this.checkLatencyID != null) {
100
- return;
101
- }
102
- this.checkLatency();
103
- if (this.dataEmitIntervalMs != null) {
104
- this.emitIntervalID = setInterval(() => { this._emitSummary(); }, this.dataEmitIntervalMs);
105
- if (typeof this.emitIntervalID.unref === 'function') {
106
- this.emitIntervalID.unref(); // Doesn't block exit
107
- }
108
- }
109
- }
110
- /**
111
- * Stop internal timers
112
- *
113
- * @private
114
- */
115
- _stopTimers() {
116
- if (this.checkLatencyID != null) {
117
- clearTimeout(this.checkLatencyID);
118
- this.checkLatencyID = undefined;
119
- }
120
- if (this.emitIntervalID != null) {
121
- clearInterval(this.emitIntervalID);
122
- this.emitIntervalID = undefined;
123
- }
124
- }
125
- /**
126
- * Emit summary only if there were events. It might not have any events if it was forced via a page hidden/show
127
- *
128
- * @private
129
- */
130
- _emitSummary() {
131
- const summary = this.getSummary();
132
- if (summary.events > 0) {
133
- this.dispatchEvent(new CustomEvent('data', {
134
- detail: summary
135
- }));
136
- }
137
- }
138
- /**
139
- * Calling this function will end the collection period. If a timing event was already fired and somewhere in the queue,
140
- * it will not count for this time period
141
- */
142
- getSummary() {
143
- // We might want to adjust for the number of expected events
144
- // Example: first 1 event it comes back, then such a long blocker that the next emit check comes
145
- // Then this fires - looks like no latency!!
146
- const latency = {
147
- events: this.latencyData.events,
148
- minMs: this.latencyData.minMs,
149
- maxMs: this.latencyData.maxMs,
150
- avgMs: this.latencyData.events > 0
151
- ? this.latencyData.totalMs / this.latencyData.events
152
- : Number.POSITIVE_INFINITY,
153
- lengthMs: this.getDeltaMS(this.latencyData.startTime)
154
- };
155
- this.latencyData = this.initLatencyData(); // Clear
156
- log.trace('Summary: %O', latency);
157
- return latency;
158
- }
159
- /**
160
- * Randomly calls an async fn every roughly latencyCheckIntervalMs (plus some randomness). If no async fn is found,
161
- * it will simply report on event loop latency.
162
- */
163
- checkLatency() {
164
- // Randomness is needed to avoid alignment by accident to regular things in the event loop
165
- const randomness = (Math.random() * this.latencyCheckMultiply) - this.latencyCheckSubtract;
166
- // We use this to ensure that in case some overlap somehow, we don't take the wrong startTime/offset
167
- const localData = {
168
- deltaOffset: Math.ceil(this.latencyCheckIntervalMs + randomness),
169
- startTime: this.now()
170
- };
171
- const cb = () => {
172
- // We are already stopped, ignore this datapoint
173
- if (this.checkLatencyID == null) {
174
- return;
175
- }
176
- const deltaMS = this.getDeltaMS(localData.startTime) - localData.deltaOffset;
177
- this.checkLatency(); // Start again ASAP
178
- // Add the data point. If this gets complex, refactor it
179
- this.latencyData.events++;
180
- this.latencyData.minMs = Math.min(this.latencyData.minMs, deltaMS);
181
- this.latencyData.maxMs = Math.max(this.latencyData.maxMs, deltaMS);
182
- this.latencyData.totalMs += deltaMS;
183
- log.trace('MS: %s Data: %O', deltaMS, this.latencyData);
184
- };
185
- log.trace('localData: %O', localData);
186
- this.checkLatencyID = setTimeout(() => {
187
- // This gets rid of including event loop
188
- if (this.asyncTestFn != null) {
189
- // Clear timing related things
190
- localData.deltaOffset = 0;
191
- localData.startTime = this.now();
192
- this.asyncTestFn(cb);
193
- }
194
- else {
195
- // setTimeout is not more accurate than 1ms, so this will ensure positive numbers. Add 1 to emitted data to remove.
196
- // This is not the best, but for now it'll be just fine. This isn't meant to be sub ms accurate.
197
- localData.deltaOffset -= 1;
198
- // If there is no function to test, we mean check latency which is a special case that is really cb => cb()
199
- // We avoid that for the few extra function all overheads. Also, we want to keep the timers different
200
- cb();
201
- }
202
- }, localData.deltaOffset);
203
- if (typeof this.checkLatencyID.unref === 'function') {
204
- this.checkLatencyID.unref(); // Doesn't block exit
205
- }
206
- }
207
- initLatencyData() {
208
- return {
209
- startTime: this.now(),
210
- minMs: Number.POSITIVE_INFINITY,
211
- maxMs: Number.NEGATIVE_INFINITY,
212
- events: 0,
213
- totalMs: 0
214
- };
215
- }
216
- }
217
- function isBrowser() {
218
- return typeof globalThis.window !== 'undefined';
219
- }
220
- //# sourceMappingURL=latency-monitor.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"latency-monitor.js","sourceRoot":"","sources":["../../../src/connection-manager/latency-monitor.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,2BAA2B,CAAA;AACrE,OAAO,EAAE,uBAAuB,EAAE,MAAM,gCAAgC,C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ACL,mHAAmH;gBACnH,gGAAgG;gBAChG,SAAS,CAAC,WAAW,IAAI,CAAC,CAAA;gBAC1B,2GAA2G;gBAC3G,qGAAqG;gBACrG,EAAE,EAAE,CAAA;aACL;QACH,CAAC,EAAE,SAAS,CAAC,WAAW,CAAC,CAAA;QAEzB,IAAI,OAAO,IAAI,CAAC,cAAc,CAAC,KAAK,KAAK,UAAU,EAAE;YACnD,IAAI,CAAC,cAAc,CAAC,KAAK,EAAE,CAAA,CAAC,qBAAqB;SAClD;IACH,CAAC;IAED,eAAe;QACb,OAAO;YACL,SAAS,EAAE,IAAI,CAAC,GAAG,EAAE;YACrB,KAAK,EAAE,MAAM,CAAC,iBAAiB;YAC/B,KAAK,EAAE,MAAM,CAAC,iBAAiB;YAC/B,MAAM,EAAE,CAAC;YACT,OAAO,EAAE,CAAC;SACX,CAAA;IACH,CAAC;CACF;AAED,SAAS,SAAS;IAChB,OAAO,OAAO,UAAU,CAAC,MAAM,KAAK,WAAW,CAAA;AACjD,CAAC"}
@@ -1,66 +0,0 @@
1
- /**
2
- * This code is based on `latency-monitor` (https://github.com/mlucool/latency-monitor) by `mlucool` (https://github.com/mlucool), available under Apache License 2.0 (https://github.com/mlucool/latency-monitor/blob/master/LICENSE)
3
- */
4
- import { EventEmitter } from '@libp2p/interfaces/events';
5
- interface VisibilityChangeEmitterEvents {
6
- 'visibilityChange': CustomEvent<boolean>;
7
- }
8
- /**
9
- * Listen to page visibility change events (i.e. when the page is focused / blurred) by an event emitter.
10
- *
11
- * Warning: This does not work on all browsers, but should work on all modern browsers
12
- *
13
- * @example
14
- *
15
- * const myVisibilityEmitter = new VisibilityChangeEmitter();
16
- *
17
- * myVisibilityEmitter.on('visibilityChange', (pageInFocus) => {
18
- * if ( pageInFocus ){
19
- * // Page is in focus
20
- * console.log('In focus');
21
- * }
22
- * else {
23
- * // Page is blurred
24
- * console.log('Out of focus');
25
- * }
26
- * });
27
- * // To access the visibility state directly, call:
28
- * console.log('Am I focused now? ' + myVisibilityEmitter.isVisible());
29
- */
30
- export declare class VisibilityChangeEmitter extends EventEmitter<VisibilityChangeEmitterEvents> {
31
- private hidden;
32
- private visibilityChange;
33
- constructor();
34
- /**
35
- * document.hidden and document.visibilityChange are the two variables we need to check for;
36
- * Since these variables are named differently in different browsers, this function sets
37
- * the appropriate name based on the browser being used. Once executed, tha actual names of
38
- * document.hidden and document.visibilityChange are found in this._hidden and this._visibilityChange
39
- * respectively
40
- *
41
- * @private
42
- */
43
- _initializeVisibilityVarNames(): void;
44
- /**
45
- * Adds an event listener on the document that listens to changes in document.visibilityChange
46
- * (or whatever name by which the visibilityChange variable is known in the browser)
47
- *
48
- * @private
49
- */
50
- _addVisibilityChangeListener(): void;
51
- /**
52
- * The function returns ```true``` if the page is visible or ```false``` if the page is not visible and
53
- * ```undefined``` if the page visibility API is not supported by the browser.
54
- */
55
- isVisible(): boolean | undefined;
56
- /**
57
- * The function that is called when document.visibilityChange has changed
58
- * It emits an event called visibilityChange and sends the value of document.hidden as a
59
- * parameter
60
- *
61
- * @private
62
- */
63
- _handleVisibilityChange(): void;
64
- }
65
- export {};
66
- //# sourceMappingURL=visibility-change-emitter.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"visibility-change-emitter.d.ts","sourceRoot":"","sources":["../../../src/connection-manager/visibility-change-emitter.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAe,YAAY,EAAE,MAAM,2BAA2B,CAAA;AAKrE,UAAU,6BAA6B;IACrC,kBAAkB,EAAE,WAAW,CAAC,OAAO,CAAC,CAAA;CACzC;AAID;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,qBAAa,uBAAwB,SAAQ,YAAY,CAAC,6BAA6B,CAAC;IACtF,OAAO,CAAC,MAAM,CAAQ;IACtB,OAAO,CAAC,gBAAgB,CAAQ;;IAchC;;;;;;;;OAQG;IACH,6BAA6B,IAAK,IAAI;IAyBtC;;;;;OAKG;IACH,4BAA4B,IAAK,IAAI;IAUrC;;;OAGG;IACH,SAAS,IAAK,OAAO,GAAG,SAAS;IAUjC;;;;;;OAMG;IACH,uBAAuB,IAAK,IAAI;CAUjC"}
@@ -1,118 +0,0 @@
1
- /**
2
- * This code is based on `latency-monitor` (https://github.com/mlucool/latency-monitor) by `mlucool` (https://github.com/mlucool), available under Apache License 2.0 (https://github.com/mlucool/latency-monitor/blob/master/LICENSE)
3
- */
4
- import { CustomEvent, EventEmitter } from '@libp2p/interfaces/events';
5
- import { logger } from '@libp2p/logger';
6
- const log = logger('libp2p:connection-manager:latency-monitor:visibility-change-emitter');
7
- /**
8
- * Listen to page visibility change events (i.e. when the page is focused / blurred) by an event emitter.
9
- *
10
- * Warning: This does not work on all browsers, but should work on all modern browsers
11
- *
12
- * @example
13
- *
14
- * const myVisibilityEmitter = new VisibilityChangeEmitter();
15
- *
16
- * myVisibilityEmitter.on('visibilityChange', (pageInFocus) => {
17
- * if ( pageInFocus ){
18
- * // Page is in focus
19
- * console.log('In focus');
20
- * }
21
- * else {
22
- * // Page is blurred
23
- * console.log('Out of focus');
24
- * }
25
- * });
26
- * // To access the visibility state directly, call:
27
- * console.log('Am I focused now? ' + myVisibilityEmitter.isVisible());
28
- */
29
- export class VisibilityChangeEmitter extends EventEmitter {
30
- constructor() {
31
- super();
32
- this.hidden = 'hidden';
33
- this.visibilityChange = 'visibilityChange';
34
- if (globalThis.document != null) {
35
- this._initializeVisibilityVarNames();
36
- this._addVisibilityChangeListener();
37
- }
38
- }
39
- /**
40
- * document.hidden and document.visibilityChange are the two variables we need to check for;
41
- * Since these variables are named differently in different browsers, this function sets
42
- * the appropriate name based on the browser being used. Once executed, tha actual names of
43
- * document.hidden and document.visibilityChange are found in this._hidden and this._visibilityChange
44
- * respectively
45
- *
46
- * @private
47
- */
48
- _initializeVisibilityVarNames() {
49
- let hidden = 'hidden';
50
- let visibilityChange = 'visibilitychange';
51
- if (typeof globalThis.document.hidden !== 'undefined') { // Opera 12.10 and Firefox 18 and later support
52
- hidden = 'hidden';
53
- visibilityChange = 'visibilitychange';
54
- // @ts-expect-error mozHidden is a non-standard field name
55
- }
56
- else if (typeof globalThis.document.mozHidden !== 'undefined') {
57
- hidden = 'mozHidden';
58
- visibilityChange = 'mozvisibilitychange';
59
- // @ts-expect-error msHidden is a non-standard field name
60
- }
61
- else if (typeof globalThis.document.msHidden !== 'undefined') {
62
- hidden = 'msHidden';
63
- visibilityChange = 'msvisibilitychange';
64
- // @ts-expect-error webkitHidden is a non-standard field name
65
- }
66
- else if (typeof globalThis.document.webkitHidden !== 'undefined') {
67
- hidden = 'webkitHidden';
68
- visibilityChange = 'webkitvisibilitychange';
69
- }
70
- this.hidden = hidden;
71
- this.visibilityChange = visibilityChange;
72
- }
73
- /**
74
- * Adds an event listener on the document that listens to changes in document.visibilityChange
75
- * (or whatever name by which the visibilityChange variable is known in the browser)
76
- *
77
- * @private
78
- */
79
- _addVisibilityChangeListener() {
80
- // @ts-expect-error cannot index document object with string key
81
- if (typeof globalThis.document.addEventListener === 'undefined' || typeof document[this.hidden] === 'undefined') {
82
- log('Checking page visibility requires a browser that supports the Page Visibility API.');
83
- }
84
- else {
85
- // Handle page visibility change
86
- globalThis.document.addEventListener(this.visibilityChange, this._handleVisibilityChange.bind(this), false);
87
- }
88
- }
89
- /**
90
- * The function returns ```true``` if the page is visible or ```false``` if the page is not visible and
91
- * ```undefined``` if the page visibility API is not supported by the browser.
92
- */
93
- isVisible() {
94
- // @ts-expect-error cannot index document object with string key
95
- if (this.hidden === undefined || document[this.hidden] === undefined) {
96
- return undefined;
97
- }
98
- // @ts-expect-error cannot index document object with string key
99
- return document[this.hidden] == null;
100
- }
101
- /**
102
- * The function that is called when document.visibilityChange has changed
103
- * It emits an event called visibilityChange and sends the value of document.hidden as a
104
- * parameter
105
- *
106
- * @private
107
- */
108
- _handleVisibilityChange() {
109
- // @ts-expect-error cannot index document object with string key
110
- const visible = globalThis.document[this.hidden] === false;
111
- log(visible ? 'Page Visible' : 'Page Hidden');
112
- // Emit the event
113
- this.dispatchEvent(new CustomEvent('visibilityChange', {
114
- detail: visible
115
- }));
116
- }
117
- }
118
- //# sourceMappingURL=visibility-change-emitter.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"visibility-change-emitter.js","sourceRoot":"","sources":["../../../src/connection-manager/visibility-change-emitter.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,2BAA2B,CAAA;AACrE,OAAO,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAA;AAEvC,MAAM,GAAG,GAAG,MAAM,CAAC,qEAAqE,CAAC,CAAA;AAQzF;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,MAAM,OAAO,uBAAwB,SAAQ,YAA2C;IAItF;QACE,KAAK,EAAE,CAAA;QAEP,IAAI,CAAC,MAAM,GAAG,QAAQ,CAAA;QACtB,IAAI,CAAC,gBAAgB,GAAG,kBAAkB,CAAA;QAE1C,IAAI,UAAU,CAAC,QAAQ,IAAI,IAAI,EAAE;YAC/B,IAAI,CAAC,6BAA6B,EAAE,CAAA;YACpC,IAAI,CAAC,4BAA4B,EAAE,CAAA;SACpC;IACH,CAAC;IAED;;;;;;;;OAQG;IACH,6BAA6B;QAC3B,IAAI,MAAM,GAAW,QAAQ,CAAA;QAC7B,IAAI,gBAAgB,GAAG,kBAAkB,CAAA;QAEzC,IAAI,OAAO,UAAU,CAAC,QAAQ,CAAC,MAAM,KAAK,WAAW,EAAE,EAAE,+CAA+C;YACtG,MAAM,GAAG,QAAQ,CAAA;YACjB,gBAAgB,GAAG,kBAAkB,CAAA;YACrC,0DAA0D;SAC3D;aAAM,IAAI,OAAO,UAAU,CAAC,QAAQ,CAAC,SAAS,KAAK,WAAW,EAAE;YAC/D,MAAM,GAAG,WAAW,CAAA;YACpB,gBAAgB,GAAG,qBAAqB,CAAA;YACxC,yDAAyD;SAC1D;aAAM,IAAI,OAAO,UAAU,CAAC,QAAQ,CAAC,QAAQ,KAAK,WAA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7C,iBAAiB;QACjB,IAAI,CAAC,aAAa,CAAC,IAAI,WAAW,CAAU,kBAAkB,EAAE;YAC9D,MAAM,EAAE,OAAO;SAChB,CAAC,CAAC,CAAA;IACL,CAAC;CACF"}
@@ -1,27 +0,0 @@
1
- /**
2
- * How long in ms a dial attempt is allowed to take
3
- */
4
- export declare const DIAL_TIMEOUT = 30000;
5
- /**
6
- * How long in ms an inbound connection upgrade is allowed to take
7
- */
8
- export declare const INBOUND_UPGRADE_TIMEOUT = 30000;
9
- /**
10
- * Maximum allowed concurrent dials
11
- */
12
- export declare const MAX_PARALLEL_DIALS = 100;
13
- /**
14
- * Allowed parallel dials per DialRequest
15
- */
16
- export declare const MAX_PER_PEER_DIALS = 4;
17
- /**
18
- * Maximum number of allowed addresses to attempt to dial
19
- */
20
- export declare const MAX_ADDRS_TO_DIAL = 25;
21
- export declare const METRICS: {
22
- computeThrottleMaxQueueSize: number;
23
- computeThrottleTimeout: number;
24
- movingAverageIntervals: number[];
25
- maxOldPeersRetention: number;
26
- };
27
- //# sourceMappingURL=constants.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../../src/constants.ts"],"names":[],"mappings":"AACA;;GAEG;AACH,eAAO,MAAM,YAAY,QAAO,CAAA;AAEhC;;GAEG;AACH,eAAO,MAAM,uBAAuB,QAAO,CAAA;AAE3C;;GAEG;AACH,eAAO,MAAM,kBAAkB,MAAM,CAAA;AAErC;;GAEG;AACH,eAAO,MAAM,kBAAkB,IAAI,CAAA;AAEnC;;GAEG;AACH,eAAO,MAAM,iBAAiB,KAAK,CAAA;AAEnC,eAAO,MAAM,OAAO;;;;;CASnB,CAAA"}
@@ -1,31 +0,0 @@
1
- /**
2
- * How long in ms a dial attempt is allowed to take
3
- */
4
- export const DIAL_TIMEOUT = 30e3;
5
- /**
6
- * How long in ms an inbound connection upgrade is allowed to take
7
- */
8
- export const INBOUND_UPGRADE_TIMEOUT = 30e3;
9
- /**
10
- * Maximum allowed concurrent dials
11
- */
12
- export const MAX_PARALLEL_DIALS = 100;
13
- /**
14
- * Allowed parallel dials per DialRequest
15
- */
16
- export const MAX_PER_PEER_DIALS = 4;
17
- /**
18
- * Maximum number of allowed addresses to attempt to dial
19
- */
20
- export const MAX_ADDRS_TO_DIAL = 25;
21
- export const METRICS = {
22
- computeThrottleMaxQueueSize: 1000,
23
- computeThrottleTimeout: 2000,
24
- movingAverageIntervals: [
25
- 60 * 1000,
26
- 5 * 60 * 1000,
27
- 15 * 60 * 1000 // 15 minutes
28
- ],
29
- maxOldPeersRetention: 50
30
- };
31
- //# sourceMappingURL=constants.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"constants.js","sourceRoot":"","sources":["../../src/constants.ts"],"names":[],"mappings":"AACA;;GAEG;AACH,MAAM,CAAC,MAAM,YAAY,GAAG,IAAI,CAAA;AAEhC;;GAEG;AACH,MAAM,CAAC,MAAM,uBAAuB,GAAG,IAAI,CAAA;AAE3C;;GAEG;AACH,MAAM,CAAC,MAAM,kBAAkB,GAAG,GAAG,CAAA;AAErC;;GAEG;AACH,MAAM,CAAC,MAAM,kBAAkB,GAAG,CAAC,CAAA;AAEnC;;GAEG;AACH,MAAM,CAAC,MAAM,iBAAiB,GAAG,EAAE,CAAA;AAEnC,MAAM,CAAC,MAAM,OAAO,GAAG;IACrB,2BAA2B,EAAE,IAAI;IACjC,sBAAsB,EAAE,IAAI;IAC5B,sBAAsB,EAAE;QACtB,EAAE,GAAG,IAAI;QACT,CAAC,GAAG,EAAE,GAAG,IAAI;QACb,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC,aAAa;KAC7B;IACD,oBAAoB,EAAE,EAAE;CACzB,CAAA"}
@@ -1,158 +0,0 @@
1
- import { logger } from '@libp2p/logger'
2
- import mergeOptions from 'merge-options'
3
- // @ts-expect-error retimer does not have types
4
- import retimer from 'retimer'
5
- import type { Startable } from '@libp2p/interfaces/startable'
6
- import type { PeerId } from '@libp2p/interface-peer-id'
7
- import type { ConnectionManager } from '@libp2p/interface-connection-manager'
8
- import type { PeerStore } from '@libp2p/interface-peer-store'
9
-
10
- const log = logger('libp2p:connection-manager:auto-dialler')
11
-
12
- export interface AutoDiallerInit {
13
- /**
14
- * The minimum number of connections to avoid pruning
15
- */
16
- minConnections?: number
17
-
18
- /**
19
- * How often, in milliseconds, it should preemptively guarantee connections are above the low watermark
20
- */
21
- autoDialInterval?: number
22
- }
23
-
24
- export interface AutoDiallerComponents {
25
- peerId: PeerId
26
- connectionManager: ConnectionManager
27
- peerStore: PeerStore
28
- }
29
-
30
- const defaultOptions: Partial<AutoDiallerInit> = {
31
- minConnections: 0,
32
- autoDialInterval: 10000
33
- }
34
-
35
- export class AutoDialler implements Startable {
36
- private readonly components: AutoDiallerComponents
37
- private readonly options: Required<AutoDiallerInit>
38
- private running: boolean
39
- private autoDialTimeout?: ReturnType<retimer>
40
-
41
- /**
42
- * Proactively tries to connect to known peers stored in the PeerStore.
43
- * It will keep the number of connections below the upper limit and sort
44
- * the peers to connect based on wether we know their keys and protocols.
45
- */
46
- constructor (components: AutoDiallerComponents, init: AutoDiallerInit) {
47
- this.components = components
48
- this.options = mergeOptions.call({ ignoreUndefined: true }, defaultOptions, init)
49
- this.running = false
50
- this._autoDial = this._autoDial.bind(this)
51
-
52
- log('options: %j', this.options)
53
- }
54
-
55
- isStarted (): boolean {
56
- return this.running
57
- }
58
-
59
- /**
60
- * Starts the auto dialer
61
- */
62
- async start (): Promise<void> {
63
- this.running = true
64
-
65
- void this._autoDial().catch(err => {
66
- log.error('could not start autodial', err)
67
- })
68
-
69
- log('started')
70
- }
71
-
72
- /**
73
- * Stops the auto dialler
74
- */
75
- async stop (): Promise<void> {
76
- this.running = false
77
-
78
- if (this.autoDialTimeout != null) {
79
- this.autoDialTimeout.clear()
80
- }
81
-
82
- log('stopped')
83
- }
84
-
85
- async _autoDial (): Promise<void> {
86
- if (this.autoDialTimeout != null) {
87
- this.autoDialTimeout.clear()
88
- }
89
-
90
- const minConnections = this.options.minConnections
91
-
92
- // Already has enough connections
93
- if (this.components.connectionManager.getConnections().length >= minConnections) {
94
- this.autoDialTimeout = retimer(this._autoDial, this.options.autoDialInterval)
95
-
96
- return
97
- }
98
-
99
- // Sort peers on whether we know protocols or public keys for them
100
- let peers = await this.components.peerStore.all()
101
-
102
- peers = peers.filter((peer) => {
103
- // do not dial ourselves
104
- if (peer.id.equals(this.components.peerId)) {
105
- return false
106
- }
107
-
108
- // do not dial peers without multiaddrs
109
- if (peer.addresses.length === 0) {
110
- return false
111
- }
112
-
113
- return true
114
- })
115
-
116
- // shuffle the peers
117
- peers = peers.sort(() => Math.random() > 0.5 ? 1 : -1)
118
-
119
- peers = peers.sort((a, b) => {
120
- // dial peers with the most protocols first
121
- if (b.protocols.length > a.protocols.length) {
122
- return 1
123
- }
124
-
125
- // dial peers with public keys first
126
- if (b.id.publicKey != null && a.id.publicKey == null) {
127
- return 1
128
- }
129
-
130
- return -1
131
- })
132
-
133
- for (let i = 0; this.running && i < peers.length && this.components.connectionManager.getConnections().length < minConnections; i++) {
134
- // Connection Manager was stopped during async dial
135
- if (!this.running) {
136
- return
137
- }
138
-
139
- const peer = peers[i]
140
-
141
- if (this.components.connectionManager.getConnections(peer.id).length === 0) {
142
- log('connecting to a peerStore stored peer %p', peer.id)
143
- try {
144
- await this.components.connectionManager.openConnection(peer.id)
145
- } catch (err: any) {
146
- log.error('could not connect to peerStore stored peer', err)
147
- }
148
- }
149
- }
150
-
151
- // Connection Manager was stopped
152
- if (!this.running) {
153
- return
154
- }
155
-
156
- this.autoDialTimeout = retimer(this._autoDial, this.options.autoDialInterval)
157
- }
158
- }