peerpigeon 1.0.6 → 1.0.8
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/dist/peerpigeon-browser.js +361 -30
- package/dist/peerpigeon-browser.js.map +3 -3
- package/docs/BROADCAST_STREAMING.md +388 -0
- package/docs/PEER_DISCOVERY_FIXES.md +140 -0
- package/examples/broadcast-stream-demo.html +539 -0
- package/package.json +1 -1
- package/server/index.js +238 -38
- package/src/ConnectionManager.js +38 -8
- package/src/GossipManager.js +22 -0
- package/src/PeerConnection.js +12 -7
- package/src/PeerDiscovery.js +33 -18
- package/src/PeerPigeonMesh.js +333 -0
- package/src/SignalingHandler.js +18 -5
|
@@ -4397,20 +4397,37 @@ ${b64.match(/.{1,64}/g).join("\n")}
|
|
|
4397
4397
|
this.connectionAttempts.clear();
|
|
4398
4398
|
}
|
|
4399
4399
|
addDiscoveredPeer(peerId) {
|
|
4400
|
-
|
|
4401
|
-
|
|
4402
|
-
|
|
4400
|
+
const wasKnown = this.discoveredPeers.has(peerId);
|
|
4401
|
+
const now = Date.now();
|
|
4402
|
+
this.discoveredPeers.set(peerId, now);
|
|
4403
|
+
if (wasKnown) {
|
|
4404
|
+
this.debug.log(`Re-discovered peer ${peerId.substring(0, 8)}... (updating timestamp)`);
|
|
4405
|
+
if (this.connectionAttempts.has(peerId)) {
|
|
4406
|
+
const attemptTime = this.connectionAttempts.get(peerId);
|
|
4407
|
+
if (now - attemptTime > 5e3) {
|
|
4408
|
+
this.debug.log(`Clearing stale connection attempt for ${peerId.substring(0, 8)}...`);
|
|
4409
|
+
this.connectionAttempts.delete(peerId);
|
|
4410
|
+
}
|
|
4411
|
+
}
|
|
4412
|
+
} else {
|
|
4413
|
+
this.debug.log(`Discovered new peer ${peerId.substring(0, 8)}...`);
|
|
4414
|
+
this.emit("peerDiscovered", { peerId });
|
|
4403
4415
|
}
|
|
4404
|
-
this.
|
|
4405
|
-
this.
|
|
4406
|
-
this.
|
|
4407
|
-
|
|
4408
|
-
this.debug.log(`Considering connection to ${peerId.substring(0, 8)}...`);
|
|
4416
|
+
const alreadyTrying = this.connectionAttempts.has(peerId);
|
|
4417
|
+
const shouldInitiate = this.shouldInitiateConnection(peerId);
|
|
4418
|
+
if (this.autoDiscovery && shouldInitiate && !alreadyTrying) {
|
|
4419
|
+
this.debug.log(`Considering connection to ${peerId.substring(0, 8)}... (shouldInitiate: ${shouldInitiate}, alreadyTrying: ${alreadyTrying})`);
|
|
4409
4420
|
const canAccept = this.canAcceptMorePeers();
|
|
4410
4421
|
if (canAccept) {
|
|
4411
|
-
this.debug.log(
|
|
4422
|
+
this.debug.log(`\u{1F517} Initiating connection to ${peerId.substring(0, 8)}...`);
|
|
4412
4423
|
this.emit("connectToPeer", { peerId });
|
|
4424
|
+
} else {
|
|
4425
|
+
this.debug.log(`Cannot connect to ${peerId.substring(0, 8)}... (at max peers)`);
|
|
4413
4426
|
}
|
|
4427
|
+
} else if (alreadyTrying) {
|
|
4428
|
+
this.debug.log(`Already attempting connection to ${peerId.substring(0, 8)}...`);
|
|
4429
|
+
} else if (!shouldInitiate) {
|
|
4430
|
+
this.debug.log(`Not initiating to ${peerId.substring(0, 8)}... (should wait for them to initiate)`);
|
|
4414
4431
|
}
|
|
4415
4432
|
this.scheduleMeshOptimization();
|
|
4416
4433
|
}
|
|
@@ -4439,9 +4456,6 @@ ${b64.match(/.{1,64}/g).join("\n")}
|
|
|
4439
4456
|
return distance;
|
|
4440
4457
|
}
|
|
4441
4458
|
shouldInitiateConnection(targetPeerId) {
|
|
4442
|
-
if (this.connectionAttempts.has(targetPeerId)) {
|
|
4443
|
-
return false;
|
|
4444
|
-
}
|
|
4445
4459
|
this.emit("checkCapacity");
|
|
4446
4460
|
const currentConnectionCount = this._currentConnectionCount || 0;
|
|
4447
4461
|
const lexicographicShouldInitiate = this.peerId > targetPeerId;
|
|
@@ -4812,19 +4826,18 @@ ${b64.match(/.{1,64}/g).join("\n")}
|
|
|
4812
4826
|
const hasSignaling = this.mesh && this.mesh.signalingClient && this.mesh.signalingClient.isConnected();
|
|
4813
4827
|
const hasMeshConnectivity = this.mesh && this.mesh.connected && this.mesh.connectionManager.getConnectedPeerCount() > 0;
|
|
4814
4828
|
if (hasSignaling || hasMeshConnectivity) {
|
|
4815
|
-
this.debug.log(`\
|
|
4829
|
+
this.debug.log(`\u26A0\uFE0F ICE remained disconnected for ${this.peerId}, attempting restart (signaling: ${hasSignaling}, mesh: ${hasMeshConnectivity})`);
|
|
4816
4830
|
try {
|
|
4817
4831
|
this.restartIceViaSignaling().catch((error) => {
|
|
4818
4832
|
this.debug.error("Failed to restart ICE after disconnection:", error);
|
|
4819
|
-
this.
|
|
4833
|
+
this.debug.log(`Will wait for ICE to reach "failed" state before disconnecting ${this.peerId}`);
|
|
4820
4834
|
});
|
|
4821
4835
|
} catch (error) {
|
|
4822
4836
|
this.debug.error("Failed to restart ICE after disconnection:", error);
|
|
4823
|
-
this.
|
|
4837
|
+
this.debug.log(`Will wait for ICE to reach "failed" state before disconnecting ${this.peerId}`);
|
|
4824
4838
|
}
|
|
4825
4839
|
} else {
|
|
4826
|
-
this.debug.log(`\
|
|
4827
|
-
this.emit("disconnected", { peerId: this.peerId, reason: "ICE disconnected" });
|
|
4840
|
+
this.debug.log(`\u26A0\uFE0F ICE disconnected for ${this.peerId} without signaling - waiting for ICE state to resolve naturally`);
|
|
4828
4841
|
}
|
|
4829
4842
|
}
|
|
4830
4843
|
}, 5e3);
|
|
@@ -6066,12 +6079,30 @@ ${b64.match(/.{1,64}/g).join("\n")}
|
|
|
6066
6079
|
async connectToPeer(targetPeerId) {
|
|
6067
6080
|
this.debug.log(`connectToPeer called for ${targetPeerId.substring(0, 8)}...`);
|
|
6068
6081
|
if (this.peers.has(targetPeerId)) {
|
|
6069
|
-
this.
|
|
6070
|
-
|
|
6082
|
+
const existingPeer = this.peers.get(targetPeerId);
|
|
6083
|
+
const status = existingPeer.getStatus();
|
|
6084
|
+
if (status === "connected") {
|
|
6085
|
+
this.debug.log(`Already connected to ${targetPeerId.substring(0, 8)}... (status: ${status})`);
|
|
6086
|
+
return;
|
|
6087
|
+
}
|
|
6088
|
+
if (status === "connecting") {
|
|
6089
|
+
const connectionAge = Date.now() - (existingPeer.createdAt || 0);
|
|
6090
|
+
if (connectionAge < 1e4) {
|
|
6091
|
+
this.debug.log(`Connection to ${targetPeerId.substring(0, 8)}... still in progress (${Math.round(connectionAge / 1e3)}s)`);
|
|
6092
|
+
return;
|
|
6093
|
+
}
|
|
6094
|
+
this.debug.log(`Connection to ${targetPeerId.substring(0, 8)}... appears stuck (${Math.round(connectionAge / 1e3)}s), will retry`);
|
|
6095
|
+
this.cleanupFailedConnection(targetPeerId);
|
|
6096
|
+
}
|
|
6071
6097
|
}
|
|
6072
6098
|
if (this.mesh.peerDiscovery.isAttemptingConnection(targetPeerId)) {
|
|
6073
|
-
|
|
6074
|
-
|
|
6099
|
+
const attemptAge = Date.now() - (this.lastConnectionAttempt.get(targetPeerId) || 0);
|
|
6100
|
+
if (attemptAge < 1e4) {
|
|
6101
|
+
this.debug.log(`Already attempting connection to ${targetPeerId.substring(0, 8)}... via PeerDiscovery (${Math.round(attemptAge / 1e3)}s ago)`);
|
|
6102
|
+
return;
|
|
6103
|
+
}
|
|
6104
|
+
this.debug.log(`Old connection attempt to ${targetPeerId.substring(0, 8)}... (${Math.round(attemptAge / 1e3)}s ago), allowing retry`);
|
|
6105
|
+
this.mesh.peerDiscovery.clearConnectionAttempt(targetPeerId);
|
|
6075
6106
|
}
|
|
6076
6107
|
const shouldBeInitiator = this.mesh.peerId > targetPeerId;
|
|
6077
6108
|
if (!shouldBeInitiator) {
|
|
@@ -6087,17 +6118,22 @@ ${b64.match(/.{1,64}/g).join("\n")}
|
|
|
6087
6118
|
const attempts = this.connectionAttempts.get(targetPeerId) || 0;
|
|
6088
6119
|
if (attempts > 0) {
|
|
6089
6120
|
const lastAttempt = this.lastConnectionAttempt.get(targetPeerId) || 0;
|
|
6090
|
-
const
|
|
6091
|
-
const retryDelay =
|
|
6121
|
+
const connectedCount2 = this.getConnectedPeerCount();
|
|
6122
|
+
const retryDelay = connectedCount2 === 0 ? 200 : this.retryDelay;
|
|
6092
6123
|
if (now - lastAttempt < retryDelay) {
|
|
6093
6124
|
const remaining = retryDelay - (now - lastAttempt);
|
|
6094
|
-
this.debug.log(`Connection to ${targetPeerId.substring(0, 8)}... on cooldown (${Math.round(remaining
|
|
6125
|
+
this.debug.log(`Connection to ${targetPeerId.substring(0, 8)}... on cooldown (${Math.round(remaining)}ms remaining, isolated: ${connectedCount2 === 0})`);
|
|
6095
6126
|
return;
|
|
6096
6127
|
}
|
|
6097
6128
|
}
|
|
6098
|
-
|
|
6129
|
+
const connectedCount = this.getConnectedPeerCount();
|
|
6130
|
+
const maxAttempts = connectedCount === 0 ? this.maxConnectionAttempts * 2 : this.maxConnectionAttempts;
|
|
6131
|
+
if (attempts >= maxAttempts) {
|
|
6132
|
+
this.debug.log(`Max connection attempts (${maxAttempts}) reached for ${targetPeerId.substring(0, 8)}...`);
|
|
6099
6133
|
this.mesh.emit("statusChanged", { type: "warning", message: `Max connection attempts reached for ${targetPeerId.substring(0, 8)}...` });
|
|
6100
|
-
this.
|
|
6134
|
+
this.connectionAttempts.delete(targetPeerId);
|
|
6135
|
+
this.lastConnectionAttempt.delete(targetPeerId);
|
|
6136
|
+
this.mesh.peerDiscovery.clearConnectionAttempt(targetPeerId);
|
|
6101
6137
|
return;
|
|
6102
6138
|
}
|
|
6103
6139
|
this.debug.log(`Starting connection to ${targetPeerId.substring(0, 8)}... (attempt ${attempts + 1})`);
|
|
@@ -7028,11 +7064,22 @@ ${b64.match(/.{1,64}/g).join("\n")}
|
|
|
7028
7064
|
}
|
|
7029
7065
|
}
|
|
7030
7066
|
handlePeerAnnouncement(fromPeerId) {
|
|
7031
|
-
if (this.
|
|
7032
|
-
this.
|
|
7033
|
-
|
|
7067
|
+
if (this.connectionManager.hasPeer(fromPeerId)) {
|
|
7068
|
+
const peerStatus = this.connectionManager.getPeer(fromPeerId).getStatus();
|
|
7069
|
+
if (peerStatus === "connected") {
|
|
7070
|
+
this.debug.log(`Peer ${fromPeerId.substring(0, 8)}... already connected (${peerStatus}), updating timestamp`);
|
|
7071
|
+
this.mesh.peerDiscovery.updateDiscoveryTimestamp(fromPeerId);
|
|
7072
|
+
return;
|
|
7073
|
+
}
|
|
7074
|
+
this.debug.log(`Peer ${fromPeerId.substring(0, 8)}... exists but not connected (${peerStatus}), allowing re-discovery`);
|
|
7034
7075
|
}
|
|
7035
|
-
this.mesh.
|
|
7076
|
+
const wasKnown = this.mesh.peerDiscovery.hasPeer(fromPeerId);
|
|
7077
|
+
if (wasKnown) {
|
|
7078
|
+
this.debug.log(`Peer ${fromPeerId.substring(0, 8)}... already known, refreshing discovery`);
|
|
7079
|
+
} else {
|
|
7080
|
+
this.debug.log(`New peer discovered: ${fromPeerId.substring(0, 8)}...`);
|
|
7081
|
+
}
|
|
7082
|
+
this.mesh.emit("statusChanged", { type: "info", message: `Peer ${fromPeerId.substring(0, 8)}... ${wasKnown ? "re-announced" : "announced"}` });
|
|
7036
7083
|
this.debug.log(`Adding discovered peer: ${fromPeerId.substring(0, 8)}... to PeerDiscovery`);
|
|
7037
7084
|
this.debug.log(`Current peer count: ${this.connectionManager.getConnectedPeerCount()}/${this.mesh.maxPeers}`);
|
|
7038
7085
|
this.debug.log(`All discovered peers: ${Array.from(this.mesh.peerDiscovery.discoveredPeers.keys()).map((p) => p.substring(0, 8)).join(", ")}`);
|
|
@@ -8133,6 +8180,26 @@ ${b64.match(/.{1,64}/g).join("\n")}
|
|
|
8133
8180
|
this.handlePeerAnnouncement(content, originPeerId);
|
|
8134
8181
|
} else if (subtype === "mediaEvent") {
|
|
8135
8182
|
this.handleMediaEvent(content, originPeerId);
|
|
8183
|
+
} else if (subtype === "stream-chunk") {
|
|
8184
|
+
this.emit("messageReceived", {
|
|
8185
|
+
from: originPeerId,
|
|
8186
|
+
message: {
|
|
8187
|
+
type: "stream-chunk",
|
|
8188
|
+
...content
|
|
8189
|
+
},
|
|
8190
|
+
timestamp,
|
|
8191
|
+
messageId
|
|
8192
|
+
});
|
|
8193
|
+
} else if (subtype === "stream-control") {
|
|
8194
|
+
this.emit("messageReceived", {
|
|
8195
|
+
from: originPeerId,
|
|
8196
|
+
message: {
|
|
8197
|
+
type: "stream-control",
|
|
8198
|
+
...content
|
|
8199
|
+
},
|
|
8200
|
+
timestamp,
|
|
8201
|
+
messageId
|
|
8202
|
+
});
|
|
8136
8203
|
} else if (subtype === "dm") {
|
|
8137
8204
|
if (typeof to === "string" && typeof this.mesh.peerId === "string" && to.trim().toLowerCase() === this.mesh.peerId.trim().toLowerCase()) {
|
|
8138
8205
|
this.debug.log(`\u{1F50D} DM DEBUG: Received DM from ${originPeerId?.substring(0, 8)}, content type: ${typeof processedContent}`);
|
|
@@ -11276,6 +11343,7 @@ ${b64.match(/.{1,64}/g).join("\n")}
|
|
|
11276
11343
|
this.discoveredPeers = /* @__PURE__ */ new Map();
|
|
11277
11344
|
this.ongoingKeyExchanges = /* @__PURE__ */ new Set();
|
|
11278
11345
|
this.emittedPeerKeyEvents = /* @__PURE__ */ new Set();
|
|
11346
|
+
this.gossipStreams = /* @__PURE__ */ new Map();
|
|
11279
11347
|
this.storageManager = new StorageManager(this);
|
|
11280
11348
|
this.mediaManager = new MediaManager();
|
|
11281
11349
|
this.connectionManager = new ConnectionManager(this);
|
|
@@ -11318,6 +11386,14 @@ ${b64.match(/.{1,64}/g).join("\n")}
|
|
|
11318
11386
|
this.webDHT.handleMessage(data.message, data.from);
|
|
11319
11387
|
return;
|
|
11320
11388
|
}
|
|
11389
|
+
if (data.message && data.message.type === "stream-chunk") {
|
|
11390
|
+
this._handleGossipStreamChunk(data.message, data.from);
|
|
11391
|
+
return;
|
|
11392
|
+
}
|
|
11393
|
+
if (data.message && data.message.type === "stream-control") {
|
|
11394
|
+
this._handleGossipStreamControl(data.message, data.from);
|
|
11395
|
+
return;
|
|
11396
|
+
}
|
|
11321
11397
|
if (data.content && typeof data.content === "string") {
|
|
11322
11398
|
try {
|
|
11323
11399
|
const parsedContent = JSON.parse(data.content);
|
|
@@ -11941,6 +12017,149 @@ ${b64.match(/.{1,64}/g).join("\n")}
|
|
|
11941
12017
|
const stream = blob.stream();
|
|
11942
12018
|
await this.sendStream(targetPeerId, stream, streamOptions);
|
|
11943
12019
|
}
|
|
12020
|
+
/**
|
|
12021
|
+
* Create a writable stream that broadcasts data to all peers in the mesh using gossip
|
|
12022
|
+
* @param {object} options - Stream options (filename, mimeType, totalSize, etc.)
|
|
12023
|
+
* @returns {WritableStream} A writable stream that broadcasts via gossip protocol
|
|
12024
|
+
*/
|
|
12025
|
+
createBroadcastStream(options = {}) {
|
|
12026
|
+
const streamId = options.streamId || this._generateStreamId();
|
|
12027
|
+
const metadata = {
|
|
12028
|
+
streamId,
|
|
12029
|
+
type: options.type || "broadcast",
|
|
12030
|
+
filename: options.filename,
|
|
12031
|
+
mimeType: options.mimeType,
|
|
12032
|
+
totalSize: options.totalSize,
|
|
12033
|
+
timestamp: Date.now(),
|
|
12034
|
+
...options
|
|
12035
|
+
};
|
|
12036
|
+
const chunks = [];
|
|
12037
|
+
let chunkIndex = 0;
|
|
12038
|
+
let totalBytesWritten = 0;
|
|
12039
|
+
const self2 = this;
|
|
12040
|
+
this.debug.log(`\u{1F4E1} Creating gossip broadcast stream: ${streamId}`);
|
|
12041
|
+
return new WritableStream({
|
|
12042
|
+
async write(chunk) {
|
|
12043
|
+
const chunkData = chunk instanceof Uint8Array ? chunk : new Uint8Array(chunk);
|
|
12044
|
+
const chunkId = chunkIndex++;
|
|
12045
|
+
chunks.push({
|
|
12046
|
+
index: chunkId,
|
|
12047
|
+
data: chunkData
|
|
12048
|
+
});
|
|
12049
|
+
totalBytesWritten += chunkData.length;
|
|
12050
|
+
try {
|
|
12051
|
+
await self2.gossipManager.broadcastMessage({
|
|
12052
|
+
streamId,
|
|
12053
|
+
chunkIndex: chunkId,
|
|
12054
|
+
data: Array.from(chunkData),
|
|
12055
|
+
// Convert to regular array for JSON
|
|
12056
|
+
totalSize: metadata.totalSize,
|
|
12057
|
+
metadata: chunkId === 0 ? metadata : void 0
|
|
12058
|
+
// Include metadata with first chunk
|
|
12059
|
+
}, "stream-chunk");
|
|
12060
|
+
self2.debug.log(`\u{1F4E1} Gossiped chunk ${chunkId} (${chunkData.length} bytes) for stream ${streamId.substring(0, 8)}...`);
|
|
12061
|
+
} catch (error) {
|
|
12062
|
+
self2.debug.error(`Failed to gossip chunk ${chunkId}:`, error);
|
|
12063
|
+
throw error;
|
|
12064
|
+
}
|
|
12065
|
+
},
|
|
12066
|
+
async close() {
|
|
12067
|
+
try {
|
|
12068
|
+
await self2.gossipManager.broadcastMessage({
|
|
12069
|
+
streamId,
|
|
12070
|
+
action: "end",
|
|
12071
|
+
totalChunks: chunkIndex,
|
|
12072
|
+
totalBytes: totalBytesWritten,
|
|
12073
|
+
metadata
|
|
12074
|
+
}, "stream-control");
|
|
12075
|
+
self2.debug.log(`\u{1F4E1} Broadcast stream completed via gossip: ${totalBytesWritten} bytes in ${chunkIndex} chunks`);
|
|
12076
|
+
self2.emit("broadcastStreamComplete", {
|
|
12077
|
+
streamId,
|
|
12078
|
+
totalBytes: totalBytesWritten,
|
|
12079
|
+
totalChunks: chunkIndex,
|
|
12080
|
+
metadata
|
|
12081
|
+
});
|
|
12082
|
+
} catch (error) {
|
|
12083
|
+
self2.debug.error("Failed to broadcast stream end:", error);
|
|
12084
|
+
throw error;
|
|
12085
|
+
}
|
|
12086
|
+
},
|
|
12087
|
+
async abort(reason) {
|
|
12088
|
+
try {
|
|
12089
|
+
await self2.gossipManager.broadcastMessage({
|
|
12090
|
+
streamId,
|
|
12091
|
+
action: "abort",
|
|
12092
|
+
reason: reason?.message || String(reason),
|
|
12093
|
+
metadata
|
|
12094
|
+
}, "stream-control");
|
|
12095
|
+
self2.debug.log(`\u274C Broadcast stream aborted via gossip: ${reason}`);
|
|
12096
|
+
self2.emit("broadcastStreamAborted", {
|
|
12097
|
+
streamId,
|
|
12098
|
+
reason: reason?.message || String(reason),
|
|
12099
|
+
metadata
|
|
12100
|
+
});
|
|
12101
|
+
} catch (error) {
|
|
12102
|
+
self2.debug.error("Failed to broadcast stream abort:", error);
|
|
12103
|
+
}
|
|
12104
|
+
}
|
|
12105
|
+
});
|
|
12106
|
+
}
|
|
12107
|
+
/**
|
|
12108
|
+
* Broadcast a ReadableStream to all connected peers
|
|
12109
|
+
* @param {ReadableStream} readableStream - The stream to broadcast
|
|
12110
|
+
* @param {object} options - Stream options (filename, mimeType, etc.)
|
|
12111
|
+
* @returns {Promise<void>}
|
|
12112
|
+
*/
|
|
12113
|
+
async broadcastStream(readableStream, options = {}) {
|
|
12114
|
+
const writableStream = this.createBroadcastStream(options);
|
|
12115
|
+
try {
|
|
12116
|
+
await readableStream.pipeTo(writableStream);
|
|
12117
|
+
this.debug.log(`\u2705 Stream broadcasted successfully to all peers`);
|
|
12118
|
+
} catch (error) {
|
|
12119
|
+
this.debug.error(`\u274C Failed to broadcast stream:`, error);
|
|
12120
|
+
throw error;
|
|
12121
|
+
}
|
|
12122
|
+
}
|
|
12123
|
+
/**
|
|
12124
|
+
* Broadcast a File to all connected peers using streams
|
|
12125
|
+
* @param {File} file - The file to broadcast
|
|
12126
|
+
* @returns {Promise<void>}
|
|
12127
|
+
*/
|
|
12128
|
+
async broadcastFile(file) {
|
|
12129
|
+
this.debug.log(`\u{1F4C1} Broadcasting file "${file.name}" (${file.size} bytes) to all peers`);
|
|
12130
|
+
const options = {
|
|
12131
|
+
filename: file.name,
|
|
12132
|
+
mimeType: file.type,
|
|
12133
|
+
totalSize: file.size,
|
|
12134
|
+
type: "file"
|
|
12135
|
+
};
|
|
12136
|
+
const stream = file.stream();
|
|
12137
|
+
await this.broadcastStream(stream, options);
|
|
12138
|
+
}
|
|
12139
|
+
/**
|
|
12140
|
+
* Broadcast a Blob to all connected peers using streams
|
|
12141
|
+
* @param {Blob} blob - The blob to broadcast
|
|
12142
|
+
* @param {object} options - Additional options
|
|
12143
|
+
* @returns {Promise<void>}
|
|
12144
|
+
*/
|
|
12145
|
+
async broadcastBlob(blob, options = {}) {
|
|
12146
|
+
this.debug.log(`\u{1F4E6} Broadcasting blob (${blob.size} bytes) to all peers`);
|
|
12147
|
+
const streamOptions = {
|
|
12148
|
+
...options,
|
|
12149
|
+
mimeType: blob.type,
|
|
12150
|
+
totalSize: blob.size,
|
|
12151
|
+
type: "blob"
|
|
12152
|
+
};
|
|
12153
|
+
const stream = blob.stream();
|
|
12154
|
+
await this.broadcastStream(stream, streamOptions);
|
|
12155
|
+
}
|
|
12156
|
+
/**
|
|
12157
|
+
* Generate a unique stream ID
|
|
12158
|
+
* @private
|
|
12159
|
+
*/
|
|
12160
|
+
_generateStreamId() {
|
|
12161
|
+
return `stream_${Date.now()}_${Math.random().toString(36).substring(2, 11)}`;
|
|
12162
|
+
}
|
|
11944
12163
|
// Helper methods for backward compatibility
|
|
11945
12164
|
canAcceptMorePeers() {
|
|
11946
12165
|
return this.connectionManager.canAcceptMorePeers();
|
|
@@ -12599,6 +12818,118 @@ ${b64.match(/.{1,64}/g).join("\n")}
|
|
|
12599
12818
|
};
|
|
12600
12819
|
this.signalingHandler.handleSignalingMessage(reconstitutedMessage);
|
|
12601
12820
|
}
|
|
12821
|
+
/**
|
|
12822
|
+
* Handle incoming gossip stream chunk
|
|
12823
|
+
* @param {Object} message - The stream chunk message
|
|
12824
|
+
* @param {string} from - Sender peer ID
|
|
12825
|
+
* @private
|
|
12826
|
+
*/
|
|
12827
|
+
_handleGossipStreamChunk(message, from) {
|
|
12828
|
+
const { streamId, chunkIndex, data, metadata } = message;
|
|
12829
|
+
if (!streamId || chunkIndex === void 0 || !data) {
|
|
12830
|
+
this.debug.error("Invalid gossip stream chunk format");
|
|
12831
|
+
return;
|
|
12832
|
+
}
|
|
12833
|
+
this.debug.log(`\u{1F4E5} Received gossip stream chunk ${chunkIndex} for ${streamId.substring(0, 8)}... from ${from.substring(0, 8)}...`);
|
|
12834
|
+
if (!this.gossipStreams.has(streamId)) {
|
|
12835
|
+
const chunks = /* @__PURE__ */ new Map();
|
|
12836
|
+
let controller;
|
|
12837
|
+
const readable = new ReadableStream({
|
|
12838
|
+
start(ctrl) {
|
|
12839
|
+
controller = ctrl;
|
|
12840
|
+
},
|
|
12841
|
+
cancel: (reason) => {
|
|
12842
|
+
this.debug.log(`\u{1F4E5} Gossip stream ${streamId.substring(0, 8)}... cancelled: ${reason}`);
|
|
12843
|
+
}
|
|
12844
|
+
});
|
|
12845
|
+
this.gossipStreams.set(streamId, {
|
|
12846
|
+
chunks,
|
|
12847
|
+
metadata: metadata || {},
|
|
12848
|
+
controller,
|
|
12849
|
+
stream: readable,
|
|
12850
|
+
from,
|
|
12851
|
+
totalChunks: null
|
|
12852
|
+
});
|
|
12853
|
+
this.emit("streamReceived", {
|
|
12854
|
+
peerId: from,
|
|
12855
|
+
streamId,
|
|
12856
|
+
stream: readable,
|
|
12857
|
+
metadata: metadata || {}
|
|
12858
|
+
});
|
|
12859
|
+
}
|
|
12860
|
+
const streamData = this.gossipStreams.get(streamId);
|
|
12861
|
+
streamData.chunks.set(chunkIndex, new Uint8Array(data));
|
|
12862
|
+
this._enqueueOrderedChunks(streamId);
|
|
12863
|
+
}
|
|
12864
|
+
/**
|
|
12865
|
+
* Handle incoming gossip stream control message
|
|
12866
|
+
* @param {Object} message - The stream control message
|
|
12867
|
+
* @param {string} from - Sender peer ID
|
|
12868
|
+
* @private
|
|
12869
|
+
*/
|
|
12870
|
+
_handleGossipStreamControl(message, from) {
|
|
12871
|
+
const { streamId, action, totalChunks, totalBytes, metadata, reason } = message;
|
|
12872
|
+
if (!streamId || !action) {
|
|
12873
|
+
this.debug.error("Invalid gossip stream control format");
|
|
12874
|
+
return;
|
|
12875
|
+
}
|
|
12876
|
+
const streamData = this.gossipStreams.get(streamId);
|
|
12877
|
+
if (!streamData) {
|
|
12878
|
+
this.debug.warn(`Received control message for unknown stream: ${streamId.substring(0, 8)}...`);
|
|
12879
|
+
return;
|
|
12880
|
+
}
|
|
12881
|
+
if (action === "end") {
|
|
12882
|
+
this.debug.log(`\u{1F4E5} Gossip stream ${streamId.substring(0, 8)}... ended: ${totalBytes} bytes in ${totalChunks} chunks`);
|
|
12883
|
+
streamData.totalChunks = totalChunks;
|
|
12884
|
+
this._enqueueOrderedChunks(streamId);
|
|
12885
|
+
if (streamData.controller) {
|
|
12886
|
+
streamData.controller.close();
|
|
12887
|
+
}
|
|
12888
|
+
this.emit("streamCompleted", {
|
|
12889
|
+
peerId: from,
|
|
12890
|
+
streamId,
|
|
12891
|
+
totalChunks,
|
|
12892
|
+
totalBytes
|
|
12893
|
+
});
|
|
12894
|
+
setTimeout(() => {
|
|
12895
|
+
this.gossipStreams.delete(streamId);
|
|
12896
|
+
}, 5e3);
|
|
12897
|
+
} else if (action === "abort") {
|
|
12898
|
+
this.debug.log(`\u274C Gossip stream ${streamId.substring(0, 8)}... aborted: ${reason}`);
|
|
12899
|
+
if (streamData.controller) {
|
|
12900
|
+
streamData.controller.error(new Error(reason || "Stream aborted"));
|
|
12901
|
+
}
|
|
12902
|
+
this.emit("streamAborted", {
|
|
12903
|
+
peerId: from,
|
|
12904
|
+
streamId,
|
|
12905
|
+
reason
|
|
12906
|
+
});
|
|
12907
|
+
this.gossipStreams.delete(streamId);
|
|
12908
|
+
}
|
|
12909
|
+
}
|
|
12910
|
+
/**
|
|
12911
|
+
* Enqueue ordered chunks to the readable stream
|
|
12912
|
+
* @param {string} streamId - The stream ID
|
|
12913
|
+
* @private
|
|
12914
|
+
*/
|
|
12915
|
+
_enqueueOrderedChunks(streamId) {
|
|
12916
|
+
const streamData = this.gossipStreams.get(streamId);
|
|
12917
|
+
if (!streamData || !streamData.controller) return;
|
|
12918
|
+
const { chunks, controller } = streamData;
|
|
12919
|
+
let nextIndex = streamData.nextIndex || 0;
|
|
12920
|
+
while (chunks.has(nextIndex)) {
|
|
12921
|
+
const chunk = chunks.get(nextIndex);
|
|
12922
|
+
try {
|
|
12923
|
+
controller.enqueue(chunk);
|
|
12924
|
+
chunks.delete(nextIndex);
|
|
12925
|
+
nextIndex++;
|
|
12926
|
+
} catch (error) {
|
|
12927
|
+
this.debug.error(`Failed to enqueue chunk ${nextIndex}:`, error);
|
|
12928
|
+
break;
|
|
12929
|
+
}
|
|
12930
|
+
}
|
|
12931
|
+
streamData.nextIndex = nextIndex;
|
|
12932
|
+
}
|
|
12602
12933
|
/**
|
|
12603
12934
|
* Send a signaling message, using mesh connections for renegotiation
|
|
12604
12935
|
* @param {Object} message - The signaling message
|