Skip to content

Commit

Permalink
Merge pull request #30 from jeremyckahn/bugfix/29__clean-up-peers
Browse files Browse the repository at this point in the history
fix: (#29) Replace offer when peer is disconnected
  • Loading branch information
dmotz authored Dec 9, 2022
2 parents 78a65e7 + 65ca75b commit bed5b35
Showing 1 changed file with 19 additions and 6 deletions.
25 changes: 19 additions & 6 deletions src/torrent.js
Original file line number Diff line number Diff line change
Expand Up @@ -55,9 +55,9 @@ export const joinRoom = initGuard(occupiedRooms, (config, ns) => {
.slice(0, hashLimit)
)

const makeOffers = () =>
const makeOffers = (howMany) =>
fromEntries(
new Array(offerPoolSize).fill().map(() => {
new Array(howMany).fill().map(() => {
const peer = initPeer(true, false, config.rtcConfig)

return [
Expand All @@ -67,6 +67,9 @@ export const joinRoom = initGuard(occupiedRooms, (config, ns) => {
})
)


const makeOfferPool = () => makeOffers(offerPoolSize)

const onSocketMessage = async (socket, e) => {
const infoHash = await infoHashP
let val
Expand Down Expand Up @@ -123,7 +126,7 @@ export const joinRoom = initGuard(occupiedRooms, (config, ns) => {
)
)
peer.on(events.connect, () => onConnect(peer, val.peer_id))
peer.on(events.close, () => onDisconnect(val.peer_id))
peer.on(events.close, () => onDisconnect(peer, val.peer_id, val.offer_id))
peer.signal(
key ? {...val.offer, sdp: await decrypt(key, val.offer.sdp)} : val.offer
)
Expand All @@ -149,7 +152,7 @@ export const joinRoom = initGuard(occupiedRooms, (config, ns) => {
peer.on(events.connect, () =>
onConnect(peer, val.peer_id, val.offer_id)
)
peer.on(events.close, () => onDisconnect(val.peer_id))
peer.on(events.close, () => onDisconnect(peer, val.peer_id, val.offer_id))
peer.signal(
key
? {...val.answer, sdp: await decrypt(key, val.answer.sdp)}
Expand Down Expand Up @@ -207,7 +210,7 @@ export const joinRoom = initGuard(occupiedRooms, (config, ns) => {
cleanPool()
}

offerPool = makeOffers()
offerPool = makeOfferPool()

trackerUrls.forEach(async url => {
const socket = await makeSocket(url, infoHash)
Expand Down Expand Up @@ -239,7 +242,17 @@ export const joinRoom = initGuard(occupiedRooms, (config, ns) => {
}
}

const onDisconnect = id => delete connectedPeers[id]
const onDisconnect = (peer, peerId, offerId) => {
delete connectedPeers[peerId]
peer.destroy()

const isInOfferPool = offerId in offerPool

if (isInOfferPool) {
delete offerPool[offerId]
offerPool = {...offerPool, ...makeOffers(1)}
}
}

let announceSecs = defaultAnnounceSecs
let announceInterval = setInterval(announceAll, announceSecs * 1000)
Expand Down

0 comments on commit bed5b35

Please sign in to comment.