*Send all items to the peer we bootstrapped from if we have their connection

*Send all items to the peer we connect to in addPeerHandler only if we are already bootstrapped
*Extract item creation into private helpers
This commit is contained in:
Derrick Hammer 2022-12-17 11:03:29 -05:00
parent 0603c456ae
commit 76755b4644
Signed by: pcfreak30
GPG Key ID: C997C339BE476FF2
1 changed files with 29 additions and 5 deletions

View File

@ -113,11 +113,7 @@ export default class DHTCache extends EventEmitter {
this._addEntityConnection(this.id, item);
const broadcast = () => {
this._broadcastMessage({
type: Type.ADD_ITEM,
data: b4a.from(item as string, "hex"),
signature: this._signItem(item),
});
this._broadcastMessage(this._createAddItemRequest(item));
};
if (!this.bootstrapped) {
@ -201,6 +197,7 @@ export default class DHTCache extends EventEmitter {
}
if (this.bootstrapped) {
this._sendItemsToPeer(peer);
return;
}
@ -316,6 +313,11 @@ export default class DHTCache extends EventEmitter {
} else if (type === Type.BOOTSTRAP_RESPONSE) {
const { bootstrap } = decoded;
this._bootstrapFrom(bootstrap);
if (this.swarm._allConnections.has(id)) {
this._sendItemsToPeer(this.swarm._allConnections.get(id));
}
this.log.debug(`Bootstrap response received`);
} else if (type === Type.HEARTBEAT) {
const { id: toId, signature, data: bufData } = decoded;
@ -590,4 +592,26 @@ export default class DHTCache extends EventEmitter {
this.send(peer, b4a.from("hello"));
this.swarm.leavePeer(peer.remotePublicKey);
}
private _sendItemsToPeer(peer: any) {
for (let item of this.cache) {
item = this._maybeHexify(item);
this.send(peer, this._createAddItemRequestMessage(item));
}
}
private _createAddItemRequestMessage(item: string | Buffer): Uint8Array {
item = this._maybeHexify(item);
return Message.toBinary(Message.create(this._createAddItemRequest(item)));
}
private _createAddItemRequest(
item: string | Buffer
): PartialMessage<Message> {
return {
type: Type.ADD_ITEM,
data: b4a.from(item as string, "hex"),
signature: this._signItem(item),
};
}
}