evict.js
1 import Client from '../index.js' 2 import common from './common.js' 3 import test from 'tape' 4 import wrtc from 'webrtc-polyfill' 5 6 const infoHash = '4cb67059ed6bd08362da625b3ae77f6f4a075705' 7 const peerId = Buffer.from('01234567890123456789') 8 const peerId2 = Buffer.from('12345678901234567890') 9 const peerId3 = Buffer.from('23456789012345678901') 10 11 function serverTest (t, serverType, serverFamily) { 12 t.plan(10) 13 14 const hostname = serverFamily === 'inet6' 15 ? '[::1]' 16 : '127.0.0.1' 17 18 const opts = { 19 serverType, 20 peersCacheLength: 2 // LRU cache can only contain a max of 2 peers 21 } 22 23 common.createServer(t, opts, server => { 24 // Not using announceUrl param from `common.createServer()` since we 25 // want to control IPv4 vs IPv6. 26 const port = server[serverType].address().port 27 const announceUrl = `${serverType}://${hostname}:${port}/announce` 28 29 const client1 = new Client({ 30 infoHash, 31 announce: [announceUrl], 32 peerId, 33 port: 6881, 34 wrtc 35 }) 36 if (serverType === 'ws') common.mockWebsocketTracker(client1) 37 38 client1.start() 39 40 client1.once('update', data => { 41 const client2 = new Client({ 42 infoHash, 43 announce: [announceUrl], 44 peerId: peerId2, 45 port: 6882, 46 wrtc 47 }) 48 if (serverType === 'ws') common.mockWebsocketTracker(client2) 49 50 client2.start() 51 52 client2.once('update', data => { 53 server.getSwarm(infoHash, (err, swarm) => { 54 t.error(err) 55 56 t.equal(swarm.complete + swarm.incomplete, 2) 57 58 // Ensure that first peer is evicted when a third one is added 59 let evicted = false 60 swarm.peers.once('evict', evictedPeer => { 61 t.equal(evictedPeer.value.peerId, peerId.toString('hex')) 62 t.equal(swarm.complete + swarm.incomplete, 2) 63 evicted = true 64 }) 65 66 const client3 = new Client({ 67 infoHash, 68 announce: [announceUrl], 69 peerId: peerId3, 70 port: 6880, 71 wrtc 72 }) 73 if (serverType === 'ws') common.mockWebsocketTracker(client3) 74 75 client3.start() 76 77 client3.once('update', data => { 78 t.ok(evicted, 'client1 was evicted from server before client3 gets response') 79 t.equal(swarm.complete + swarm.incomplete, 2) 80 81 client1.destroy(() => { 82 t.pass('client1 destroyed') 83 }) 84 85 client2.destroy(() => { 86 t.pass('client3 destroyed') 87 }) 88 89 client3.destroy(() => { 90 t.pass('client3 destroyed') 91 }) 92 93 server.close(() => { 94 t.pass('server destroyed') 95 }) 96 }) 97 }) 98 }) 99 }) 100 }) 101 } 102 103 test('evict: ipv4 server', t => { 104 serverTest(t, 'http', 'inet') 105 }) 106 107 test('evict: http ipv6 server', t => { 108 serverTest(t, 'http', 'inet6') 109 }) 110 111 test('evict: udp server', t => { 112 serverTest(t, 'udp', 'inet') 113 }) 114 115 test('evict: ws server', t => { 116 serverTest(t, 'ws', 'inet') 117 })