@peerbit/stream 4.0.4 → 4.0.5-218a5bb

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.
package/package.json CHANGED
@@ -1,69 +1,94 @@
1
1
  {
2
- "name": "@peerbit/stream",
3
- "version": "4.0.4",
4
- "description": "A building block for direct streaming protocols",
5
- "type": "module",
6
- "sideEffects": false,
7
- "private": false,
8
- "publishConfig": {
9
- "access": "public"
10
- },
11
- "module": "lib/esm/index.js",
12
- "types": "lib/esm/index.d.ts",
13
- "exports": {
14
- "import": "./lib/esm/index.js"
15
- },
16
- "scripts": {
17
- "bench": "node --loader ts-node/esm ./src/__benchmark__/index.ts",
18
- "clean": "shx rm -rf lib/*",
19
- "build": "yarn clean && tsc -p tsconfig.json",
20
- "test": "node ../../../node_modules/.bin/jest test -c ../../../jest.config.ts --runInBand --forceExit",
21
- "test:unit": "node ../../../node_modules/.bin/jest test -c ../../../jest.config.unit.ts --runInBand --forceExit",
22
- "test:integration": "node ../node_modules/.bin/jest test -c ../../../jest.config.integration.ts --runInBand --forceExit"
23
- },
24
- "files": [
25
- "lib",
26
- "src",
27
- "!src/**/__tests__",
28
- "!lib/**/__tests__",
29
- "!src/**/__benchmark__",
30
- "!lib/**/__benchmark__",
31
- "LICENSE"
32
- ],
33
- "engines": {
34
- "node": ">=16.15.1"
35
- },
36
- "repository": {
37
- "type": "git",
38
- "url": "git+https://github.com/dao-xyz/peerbit.git"
39
- },
40
- "keywords": [
41
- "peerbit"
42
- ],
43
- "author": "dao.xyz",
44
- "license": "MIT",
45
- "bugs": {
46
- "url": "https://github.com/dao-xyz/peerbit/issues"
47
- },
48
- "homepage": "https://github.com/dao-xyz/peerbit#readme",
49
- "localMaintainers": [
50
- "dao.xyz"
51
- ],
52
- "devDependencies": {
53
- "@peerbit/libp2p-test-utils": "2.1.3",
54
- "@types/fast-fifo": "^1.0.2",
55
- "@types/yallist": "^4.0.1"
56
- },
57
- "dependencies": {
58
- "@dao-xyz/borsh": "^5.2.1",
59
- "@peerbit/cache": "2.0.6",
60
- "@peerbit/crypto": "2.1.7",
61
- "@peerbit/stream-interface": "^5.0.1",
62
- "abortable-iterator": "^5.0.1",
63
- "fast-fifo": "^1.3.2",
64
- "libp2p": "^1.2.3",
65
- "p-queue": "^8.0.1",
66
- "yallist": "^4.0.0"
67
- },
68
- "gitHead": "eaabc8746086d126df86d4308ca1c4f65ac20f32"
2
+ "name": "@peerbit/stream",
3
+ "version": "4.0.5-218a5bb",
4
+ "description": "A building block for direct streaming protocols",
5
+ "sideEffects": false,
6
+ "type": "module",
7
+ "types": "./dist/src/index.d.ts",
8
+ "typesVersions": {
9
+ "*": {
10
+ "*": [
11
+ "*",
12
+ "dist/*",
13
+ "dist/src/*",
14
+ "dist/src/*/index"
15
+ ],
16
+ "src/*": [
17
+ "*",
18
+ "dist/*",
19
+ "dist/src/*",
20
+ "dist/src/*/index"
21
+ ]
22
+ }
23
+ },
24
+ "files": [
25
+ "src",
26
+ "dist",
27
+ "!dist/e2e",
28
+ "!dist/test",
29
+ "!**/*.tsbuildinfo"
30
+ ],
31
+ "exports": {
32
+ ".": {
33
+ "types": "./dist/src/index.d.ts",
34
+ "import": "./dist/src/index.js"
35
+ }
36
+ },
37
+ "eslintConfig": {
38
+ "extends": "ipfs",
39
+ "parserOptions": {
40
+ "project": true,
41
+ "sourceType": "module"
42
+ },
43
+ "ignorePatterns": [
44
+ "!.aegir.js",
45
+ "test/ts-use",
46
+ "*.d.ts"
47
+ ]
48
+ },
49
+ "publishConfig": {
50
+ "access": "public"
51
+ },
52
+ "scripts": {
53
+ "bench": "node --loader ts-node/esm ./src/__benchmark__/index.ts",
54
+ "clean": "aegir clean",
55
+ "build": "aegir build --no-bundle",
56
+ "test": "aegir test --target node"
57
+ },
58
+ "engines": {
59
+ "node": ">=16.15.1"
60
+ },
61
+ "repository": {
62
+ "type": "git",
63
+ "url": "git+https://github.com/dao-xyz/peerbit.git"
64
+ },
65
+ "keywords": [
66
+ "peerbit"
67
+ ],
68
+ "author": "dao.xyz",
69
+ "license": "MIT",
70
+ "bugs": {
71
+ "url": "https://github.com/dao-xyz/peerbit/issues"
72
+ },
73
+ "homepage": "https://github.com/dao-xyz/peerbit#readme",
74
+ "localMaintainers": [
75
+ "dao.xyz"
76
+ ],
77
+ "devDependencies": {
78
+ "@peerbit/libp2p-test-utils": "2.1.3-218a5bb",
79
+ "@types/yallist": "^4.0.4",
80
+ "@types/fast-fifo": "^1.0.2"
81
+ },
82
+ "dependencies": {
83
+ "p-queue": "^8.0.1",
84
+ "fast-fifo": "^1.3.2",
85
+ "@dao-xyz/borsh": "^5.2.2",
86
+ "@peerbit/cache": "2.0.6-218a5bb",
87
+ "@peerbit/crypto": "2.2.0-218a5bb",
88
+ "@peerbit/stream-interface": "5.0.2-218a5bb",
89
+ "@peerbit/logger": "1.0.2-218a5bb",
90
+ "libp2p": "^1.2.3",
91
+ "yallist": "^4.0.0",
92
+ "abortable-iterator": "^5.0.1"
93
+ }
69
94
  }
package/src/index.ts CHANGED
@@ -3,7 +3,7 @@ import { pipe } from "it-pipe";
3
3
  import Queue from "p-queue";
4
4
  import type { PeerId } from "@libp2p/interface";
5
5
  import type { Connection } from "@libp2p/interface";
6
- import { PushableLanes, pushableLanes } from "./pushable-lanes.js";
6
+ import { type PushableLanes, pushableLanes } from "./pushable-lanes.js";
7
7
  import type { Stream } from "@libp2p/interface";
8
8
  import { Uint8ArrayList } from "uint8arraylist";
9
9
  import { abortableSource } from "abortable-iterator";
@@ -12,7 +12,7 @@ import { MAX_ROUTE_DISTANCE, Routes } from "./routes.js";
12
12
  import type { IncomingStreamData, Registrar } from "@libp2p/interface-internal";
13
13
  import type { AddressManager } from "@libp2p/interface-internal";
14
14
  import type { ConnectionManager } from "@libp2p/interface-internal";
15
- import { PeerStore } from "@libp2p/interface";
15
+ import { type PeerStore } from "@libp2p/interface";
16
16
  import pDefer from "p-defer";
17
17
 
18
18
  import { AbortError, delay, TimeoutError, waitFor } from "@peerbit/time";
@@ -27,7 +27,7 @@ import {
27
27
  } from "@peerbit/crypto";
28
28
 
29
29
  import { multiaddr } from "@multiformats/multiaddr";
30
- import { Components } from "libp2p/components";
30
+ import type { Components } from "libp2p/components";
31
31
  import type { TypedEventTarget } from "@libp2p/interface";
32
32
 
33
33
  import { logger } from "./logger.js";
@@ -40,27 +40,27 @@ import {
40
40
  Message as Message,
41
41
  DataMessage,
42
42
  getMsgId,
43
- WaitForPeer,
43
+ type WaitForPeer,
44
44
  ACK,
45
45
  SeekDelivery,
46
46
  AcknowledgeDelivery,
47
47
  SilentDelivery,
48
48
  MessageHeader,
49
49
  Goodbye,
50
- StreamEvents,
50
+ type StreamEvents,
51
51
  TracedDelivery,
52
52
  AnyWhere,
53
53
  NotStartedError,
54
54
  deliveryModeHasReceiver,
55
55
  DeliveryError,
56
- WithTo,
57
- WithMode,
58
- PriorityOptions
56
+ type WithTo,
57
+ type WithMode,
58
+ type PriorityOptions
59
59
  } from "@peerbit/stream-interface";
60
60
 
61
61
  import { MultiAddrinfo } from "@peerbit/stream-interface";
62
62
  import { BandwidthTracker } from "./stats.js";
63
- import { IdentificationOptions } from "@peerbit/stream-interface";
63
+ import { type IdentificationOptions } from "@peerbit/stream-interface";
64
64
  export { BandwidthTracker }; // might be useful for others
65
65
 
66
66
  const logError = (e?: { message: string }) => {
@@ -180,8 +180,7 @@ export class PeerStreams extends TypedEventEmitter<PeerStreamEvents> {
180
180
  write(data: Uint8Array | Uint8ArrayList, priority: number) {
181
181
  if (data.length > MAX_DATA_LENGTH_OUT) {
182
182
  throw new Error(
183
- `Message too large (${data.length * 1e-6}) mb). Needs to be less than ${
184
- MAX_DATA_LENGTH_OUT * 1e-6
183
+ `Message too large (${data.length * 1e-6}) mb). Needs to be less than ${MAX_DATA_LENGTH_OUT * 1e-6
185
184
  } mb`
186
185
  );
187
186
  }
@@ -378,17 +377,16 @@ export interface DirectStreamComponents extends Components {
378
377
 
379
378
  export type ConnectionManagerArguments =
380
379
  | (Partial<Pick<ConnectionManagerOptions, "minConnections">> &
381
- Partial<Pick<ConnectionManagerOptions, "maxConnections">> & {
382
- pruner?: Partial<PrunerOptions> | false;
383
- } & { dialer?: Partial<DialerOptions> | false })
380
+ Partial<Pick<ConnectionManagerOptions, "maxConnections">> & {
381
+ pruner?: Partial<PrunerOptions> | false;
382
+ } & { dialer?: Partial<DialerOptions> | false })
384
383
  | false;
385
384
 
386
385
  export abstract class DirectStream<
387
- Events extends { [s: string]: any } = StreamEvents
388
- >
386
+ Events extends { [s: string]: any } = StreamEvents
387
+ >
389
388
  extends TypedEventEmitter<Events>
390
- implements WaitForPeer
391
- {
389
+ implements WaitForPeer {
392
390
  public peerId: PeerId;
393
391
  public publicKey: PublicSignKey;
394
392
  public publicKeyHash: string;
@@ -494,34 +492,34 @@ export abstract class DirectStream<
494
492
  ...connectionManager,
495
493
  dialer:
496
494
  connectionManager?.dialer !== false &&
497
- connectionManager?.dialer !== null
495
+ connectionManager?.dialer !== null
498
496
  ? { retryDelay: 60 * 1000, ...connectionManager?.dialer }
499
497
  : undefined,
500
498
  pruner:
501
499
  connectionManager?.pruner !== false &&
502
- connectionManager?.pruner !== null
500
+ connectionManager?.pruner !== null
503
501
  ? {
504
- connectionTimeout: DEFAULT_PRUNED_CONNNECTIONS_TIMEOUT,
505
- interval: DEFAULT_PRUNE_CONNECTIONS_INTERVAL,
506
- maxBuffer: MAX_QUEUED_BYTES,
507
- ...connectionManager?.pruner
508
- }
502
+ connectionTimeout: DEFAULT_PRUNED_CONNNECTIONS_TIMEOUT,
503
+ interval: DEFAULT_PRUNE_CONNECTIONS_INTERVAL,
504
+ maxBuffer: MAX_QUEUED_BYTES,
505
+ ...connectionManager?.pruner
506
+ }
509
507
  : undefined
510
508
  };
511
509
  }
512
510
 
513
511
  this.recentDials = this.connectionManagerOptions.dialer
514
512
  ? new Cache({
515
- ttl: this.connectionManagerOptions.dialer.retryDelay,
516
- max: 1e3
517
- })
513
+ ttl: this.connectionManagerOptions.dialer.retryDelay,
514
+ max: 1e3
515
+ })
518
516
  : undefined;
519
517
 
520
518
  this.prunedConnectionsCache = this.connectionManagerOptions.pruner
521
519
  ? new Cache({
522
- max: 1e6,
523
- ttl: this.connectionManagerOptions.pruner.connectionTimeout
524
- })
520
+ max: 1e6,
521
+ ttl: this.connectionManagerOptions.pruner.connectionTimeout
522
+ })
525
523
  : undefined;
526
524
  }
527
525
 
@@ -640,7 +638,7 @@ export abstract class DirectStream<
640
638
  await peerStreams.close();
641
639
  }
642
640
 
643
- for (const [k, v] of this.healthChecks) {
641
+ for (const [_k, v] of this.healthChecks) {
644
642
  clearTimeout(v);
645
643
  }
646
644
  this.healthChecks.clear();
@@ -652,7 +650,7 @@ export abstract class DirectStream<
652
650
  this.routes.clear();
653
651
  this.peerKeyHashToPublicKey.clear();
654
652
 
655
- for (const [k, v] of this._ackCallbacks) {
653
+ for (const [_k, v] of this._ackCallbacks) {
656
654
  v.clear();
657
655
  }
658
656
 
@@ -1009,9 +1007,9 @@ export abstract class DirectStream<
1009
1007
  } catch (err: any) {
1010
1008
  logger.warn(
1011
1009
  "Failed processing messages to id: " +
1012
- peerStreams.peerId.toString() +
1013
- ". " +
1014
- err?.message
1010
+ peerStreams.peerId.toString() +
1011
+ ". " +
1012
+ err?.message
1015
1013
  );
1016
1014
  this.onPeerDisconnected(peerStreams.peerId);
1017
1015
  }
@@ -1230,14 +1228,14 @@ export abstract class DirectStream<
1230
1228
  // include our origin if message is SeekDelivery and we have not recently pruned a connection to this peer
1231
1229
  origin:
1232
1230
  message.header.mode instanceof SeekDelivery &&
1233
- !message.header.signatures!.publicKeys.find((x) =>
1234
- this.prunedConnectionsCache?.has(x.hashcode())
1235
- )
1231
+ !message.header.signatures!.publicKeys.find((x) =>
1232
+ this.prunedConnectionsCache?.has(x.hashcode())
1233
+ )
1236
1234
  ? new MultiAddrinfo(
1237
- this.components.addressManager
1238
- .getAddresses()
1239
- .map((x) => x.toString())
1240
- )
1235
+ this.components.addressManager
1236
+ .getAddresses()
1237
+ .map((x) => x.toString())
1238
+ )
1241
1239
  : undefined
1242
1240
  })
1243
1241
  }).sign(this.sign),
@@ -1412,9 +1410,9 @@ export abstract class DirectStream<
1412
1410
  ).mode
1413
1411
  ? (options as WithMode).mode!
1414
1412
  : new SilentDelivery({
1415
- to: (options as WithTo).to!,
1416
- redundancy: DEFAULT_SILENT_MESSAGE_REDUDANCY
1417
- });
1413
+ to: (options as WithTo).to!,
1414
+ redundancy: DEFAULT_SILENT_MESSAGE_REDUDANCY
1415
+ });
1418
1416
 
1419
1417
  if (
1420
1418
  mode instanceof AcknowledgeDelivery ||
@@ -1436,7 +1434,7 @@ export abstract class DirectStream<
1436
1434
  if (
1437
1435
  !neighbourRoutes ||
1438
1436
  now - neighbourRoutes.session >
1439
- neighbourRoutes.list.length * this.routeSeekInterval ||
1437
+ neighbourRoutes.list.length * this.routeSeekInterval ||
1440
1438
  !this.routes.isUpToDate(hash, neighbourRoutes)
1441
1439
  ) {
1442
1440
  mode = new SeekDelivery({
@@ -1536,7 +1534,6 @@ export abstract class DirectStream<
1536
1534
  return { promise: existing.promise };
1537
1535
  }
1538
1536
 
1539
- const deliveryDeferredPromise = pDefer<void>();
1540
1537
  const fastestNodesReached = new Map<string, number[]>();
1541
1538
  const messageToSet: Set<string> = new Set();
1542
1539
  if (message.header.mode.to) {
@@ -1557,6 +1554,18 @@ export abstract class DirectStream<
1557
1554
  }
1558
1555
  }
1559
1556
  const haveReceivers = messageToSet.size > 0;
1557
+
1558
+ if (haveReceivers && this.peers.size === 0) {
1559
+ return {
1560
+ promise: Promise.reject(
1561
+ new DeliveryError(
1562
+ "Cannnot deliver message to peers because there are no peers to deliver to"
1563
+ )
1564
+ )
1565
+ };
1566
+ }
1567
+
1568
+ const deliveryDeferredPromise = pDefer<void>();
1560
1569
  if (!haveReceivers) {
1561
1570
  deliveryDeferredPromise.resolve(); // we dont know how many answer to expect, just resolve immediately
1562
1571
  }
@@ -1575,7 +1584,7 @@ export abstract class DirectStream<
1575
1584
 
1576
1585
  const onUnreachable =
1577
1586
  !relayed &&
1578
- ((ev) => {
1587
+ ((ev: any) => {
1579
1588
  const deletedReceiver = messageToSet.delete(ev.detail.hashcode());
1580
1589
  if (deletedReceiver) {
1581
1590
  // Only reject if we are the sender
@@ -1621,11 +1630,9 @@ export abstract class DirectStream<
1621
1630
  new DeliveryError(
1622
1631
  `Failed to get message ${idString} ${filterMessageForSeenCounter} ${[
1623
1632
  ...messageToSet
1624
- ]} delivery acknowledges from all nodes (${
1625
- fastestNodesReached.size
1626
- }/${messageToSet.size}). Mode: ${
1627
- message.header.mode.constructor.name
1628
- }. Redundancy: ${message.header.mode["redundancy"]}`
1633
+ ]} delivery acknowledges from all nodes (${fastestNodesReached.size
1634
+ }/${messageToSet.size}). Mode: ${message.header.mode.constructor.name
1635
+ }. Redundancy: ${(message.header.mode as any)["redundancy"]}`
1629
1636
  )
1630
1637
  );
1631
1638
  } else {
@@ -1806,7 +1813,7 @@ export abstract class DirectStream<
1806
1813
  (peers instanceof Map && peers.size === 0)
1807
1814
  ) {
1808
1815
  logger.debug("No peers to send to");
1809
- return;
1816
+ return delivereyPromise;
1810
1817
  }
1811
1818
 
1812
1819
  let sentOnce = false;
@@ -1859,9 +1866,9 @@ export abstract class DirectStream<
1859
1866
  } catch (error: any) {
1860
1867
  logger.info(
1861
1868
  "Failed to connect directly to: " +
1862
- JSON.stringify(addresses.map((x) => x.toString())) +
1863
- ". " +
1864
- error?.message
1869
+ JSON.stringify(addresses.map((x) => x.toString())) +
1870
+ ". " +
1871
+ error?.message
1865
1872
  );
1866
1873
  }
1867
1874
  }
@@ -1895,11 +1902,11 @@ export abstract class DirectStream<
1895
1902
  } catch (error) {
1896
1903
  throw new Error(
1897
1904
  "Stream to " +
1898
- hash +
1899
- " does not exist. Connection exist: " +
1900
- this.peers.has(hash) +
1901
- ". Route exist: " +
1902
- this.routes.isReachable(this.publicKeyHash, hash, 0)
1905
+ hash +
1906
+ " does not exist. Connection exist: " +
1907
+ this.peers.has(hash) +
1908
+ ". Route exist: " +
1909
+ this.routes.isReachable(this.publicKeyHash, hash, 0)
1903
1910
  );
1904
1911
  }
1905
1912
  if (options?.neighbour) {
@@ -1913,11 +1920,11 @@ export abstract class DirectStream<
1913
1920
  } catch (error) {
1914
1921
  throw new Error(
1915
1922
  "Stream to " +
1916
- stream.publicKey.hashcode() +
1917
- " not ready. Readable: " +
1918
- stream.isReadable +
1919
- ". Writable " +
1920
- stream.isWritable
1923
+ stream.publicKey.hashcode() +
1924
+ " not ready. Readable: " +
1925
+ stream.isReadable +
1926
+ ". Writable " +
1927
+ stream.isWritable
1921
1928
  );
1922
1929
  }
1923
1930
  }
package/src/logger.ts CHANGED
@@ -1,2 +1,3 @@
1
1
  import { logger as logFn } from "@peerbit/logger";
2
2
  export const logger = logFn({ module: "lazystream", level: "warn" });
3
+
package/src/routes.ts CHANGED
@@ -247,7 +247,7 @@ export class Routes {
247
247
  }
248
248
 
249
249
  hasTarget(target: string) {
250
- for (const [k, v] of this.routes) {
250
+ for (const [_k, v] of this.routes) {
251
251
  if (v.has(target)) {
252
252
  return true;
253
253
  }
@@ -338,8 +338,8 @@ export class Routes {
338
338
 
339
339
  countAll() {
340
340
  let size = 0;
341
- for (const [from, map] of this.routes) {
342
- for (const [k, v] of map) {
341
+ for (const [_from, map] of this.routes) {
342
+ for (const [_k, v] of map) {
343
343
  size += v.list.length;
344
344
  }
345
345
  }