New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Persist DHT nodes #1431
Open
bookmoons
wants to merge
9
commits into
webtorrent:master
from
bookmoons:bookmoons/persist
base: master
+221
−7
Open
Persist DHT nodes #1431
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
03b7ecc
Persist DHT nodes
bookmoons a7ed3a2
Move DHT persistence logic into lib/ module
bookmoons c2f5943
Add save DHT state test
bookmoons 2852b67
Distinguish addresses in DHT persistence test
bookmoons ff755bc
Correct DHT state loading
bookmoons d6e090f
Allow DHT state loading when bootstrap disabled
bookmoons 2a3e7ee
Add load DHT state test
bookmoons 02879a0
Exclude dhtpersist on browser
bookmoons 7f26a8c
Split DHT persistence options
bookmoons File filter...
Filter file types
Jump to…
Jump to file or symbol
Failed to load files and symbols.
| @@ -2,6 +2,7 @@ | ||
|
|
||
| module.exports = WebTorrent | ||
|
|
||
| var appDataFolder = require('app-data-folder') | ||
| var Buffer = require('safe-buffer').Buffer | ||
| var concat = require('simple-concat') | ||
| var createTorrent = require('create-torrent') | ||
| @@ -19,6 +20,7 @@ var randombytes = require('randombytes') | ||
| var speedometer = require('speedometer') | ||
| var zeroFill = require('zero-fill') | ||
|
|
||
| var dhtPersist = require('./lib/dhtpersist') // browser exclude | ||
bookmoons
Author
|
||
| var TCPPool = require('./lib/tcp-pool') // browser exclude | ||
| var Torrent = require('./lib/torrent') | ||
|
|
||
| @@ -78,6 +80,9 @@ function WebTorrent (opts) { | ||
| } | ||
| self.nodeIdBuffer = Buffer.from(self.nodeId, 'hex') | ||
|
|
||
| // Default DHT persistence flag | ||
| if (!('persistDht' in opts)) opts.persistDht = true | ||
|
|
||
| self._debugId = self.peerId.toString('hex').substring(0, 7) | ||
|
|
||
| self.destroyed = false | ||
| @@ -123,8 +128,38 @@ function WebTorrent (opts) { | ||
| self._uploadSpeed = speedometer() | ||
|
|
||
| if (opts.dht !== false && typeof DHT === 'function' /* browser exclude */) { | ||
| var dhtOpts = extend({ nodeId: self.nodeId }, opts.dht) | ||
|
|
||
| if (opts.persistDht) { | ||
| // Construct state save location | ||
| self.dhtSaveFile = | ||
| opts.persistDhtPath || | ||
| path.join(appDataFolder('webtorrent'), 'dht.json') | ||
|
|
||
| if (!dhtOpts.bootstrap) { | ||
| // Load persisted state | ||
| var nodes = dhtPersist.loadNodes(self.dhtSaveFile) | ||
| if (nodes) { | ||
| var bootstrap = [] | ||
| for (var node of nodes) { | ||
| var nodeString = node.host + ':' + node.port | ||
| bootstrap.push(nodeString) | ||
| } | ||
| dhtOpts.bootstrap = bootstrap | ||
| } | ||
| } | ||
| } | ||
|
|
||
| // use a single DHT instance for all torrents, so the routing table can be reused | ||
| self.dht = new DHT(extend({ nodeId: self.nodeId }, opts.dht)) | ||
| self.dht = new DHT(dhtOpts) | ||
|
|
||
| if (opts.persistDht) { | ||
| // Persist state periodically | ||
| var saveInterval = 15 * 60 * 1000 // 15 minutes | ||
| self.saveDhtStateTimer = setInterval(function saveDhtState () { | ||
| dhtPersist.save(self.dht, self.dhtSaveFile) | ||
| }, saveInterval) | ||
| } | ||
|
|
||
| self.dht.once('error', function (err) { | ||
| self._destroy(err) | ||
| @@ -400,6 +435,20 @@ WebTorrent.prototype.address = function () { | ||
| : { address: '0.0.0.0', family: 'IPv4', port: 0 } | ||
| } | ||
|
|
||
| /** | ||
| * Persist DHT state to disk. | ||
| * No effect if DHT is not loaded. | ||
| */ | ||
| WebTorrent.prototype.saveDhtState = function (cb) { | ||
| if ( | ||
| this.dht !== false && | ||
| this.dhtSaveFile && | ||
| typeof DHT === 'function' /* browser exclude */ | ||
| ) { | ||
| dhtPersist.save(this.dht, this.dhtSaveFile, cb) | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Destroy the client, including all torrents and connections to peers. | ||
| * @param {function} cb | ||
| @@ -428,6 +477,7 @@ WebTorrent.prototype._destroy = function (err, cb) { | ||
|
|
||
| if (self.dht) { | ||
| tasks.push(function (cb) { | ||
| clearInterval(self.saveDhtStateTimer) | ||
| self.dht.destroy(cb) | ||
| }) | ||
| } | ||
| @@ -0,0 +1,78 @@ | ||
| var fs = require('fs') | ||
| var mkdirp = require('mkdirp') | ||
| var path = require('path') | ||
|
|
||
| var savingDhtState = false | ||
| function saveDhtState (dht, file, cb) { | ||
| if (savingDhtState) return | ||
| if (!dht) return // Quell after destroy | ||
| savingDhtState = true | ||
| var dhtState = dht.toJSON() | ||
| var dhtStateJson = JSON.stringify(dhtState) | ||
| mkdirp( | ||
| path.dirname(file), | ||
| function handleDhtSaveDirCreated (err) { | ||
| if (err) { | ||
| savingDhtState = false | ||
| if (cb) cb(err) | ||
| return | ||
| } | ||
| fs.writeFile( | ||
| file, | ||
| dhtStateJson, | ||
| function handleDhtStateWritten () { | ||
| savingDhtState = false | ||
| if (cb) cb(null) | ||
| } | ||
| ) | ||
| } | ||
| ) | ||
| } | ||
|
|
||
| function readDhtState (file) { | ||
| try { | ||
| return fs.readFileSync(file) | ||
| } catch (e) { | ||
| switch (e.code) { | ||
| case 'EACCES': | ||
| case 'EISDIR': | ||
| case 'ENOENT': | ||
| case 'EPERM': | ||
| return null | ||
| default: | ||
| throw e | ||
| } | ||
| } | ||
| } | ||
|
|
||
| function parseDhtState (dhtStateJson) { | ||
| try { | ||
| return JSON.parse(dhtStateJson) | ||
| } catch (e) { | ||
| if (e instanceof SyntaxError) return null | ||
| else throw e | ||
| } | ||
| } | ||
|
|
||
| function loadDhtState (file) { | ||
| var dhtStateJson = readDhtState(file) | ||
| if (!dhtStateJson) return null | ||
| var dhtState = parseDhtState(dhtStateJson) | ||
| if (!dhtState) return null | ||
| return dhtState | ||
| } | ||
|
|
||
| function loadDhtNodes (file) { | ||
| var dhtState = loadDhtState(file) | ||
| if (!dhtState) return null | ||
| if (!('nodes' in dhtState)) return null | ||
| var nodes = dhtState.nodes | ||
| if (!Array.isArray(nodes)) return null | ||
| if (nodes.length === 0) return null // Don't load an empty nodes list | ||
| return nodes | ||
| } | ||
|
|
||
| module.exports = { | ||
| save: saveDhtState, | ||
| loadNodes: loadDhtNodes | ||
| } |
| @@ -0,0 +1,80 @@ | ||
| var test = require('tape') | ||
| var tmp = require('tmp') | ||
| var fs = require('fs') | ||
| var networkAddress = require('network-address') | ||
| var DHT = require('bittorrent-dht/server') | ||
| var WebTorrent = require('../../') | ||
|
|
||
| var loopback = '127.0.0.1' | ||
| var localAddress = networkAddress.ipv4() | ||
| var port = 9999 | ||
|
|
||
| test('Save DHT state', function (t) { | ||
| t.plan(4) | ||
| var saveFile = tmp.tmpNameSync() | ||
| var dhtServer = new DHT({ bootstrap: false }) | ||
| dhtServer.on('error', function (err) { t.fail(err) }) | ||
| dhtServer.on('warning', function (err) { t.fail(err) }) | ||
| dhtServer.listen(port, function handleServerListening () { | ||
| var client = new WebTorrent({ | ||
| dht: { bootstrap: false, host: localAddress }, | ||
| persistDhtPath: saveFile | ||
| }) | ||
| client.on('error', function (err) { t.fail(err) }) | ||
| client.on('warning', function (err) { t.fail(err) }) | ||
| client.dht.addNode({ host: loopback, port: port }) | ||
| client.dht.on('node', function handleNodeAdded () { | ||
| client.saveDhtState(function handleDhtStateSaved () { | ||
| var dhtStateJson = fs.readFileSync(saveFile) | ||
| var dhtState = JSON.parse(dhtStateJson) | ||
| var nodes = dhtState.nodes | ||
| var node = nodes[0] | ||
| t.equal(node.host, loopback) | ||
| t.equal(node.port, port) | ||
| client.destroy(function handleClientDestroyed (err) { | ||
| t.error(err, 'client destroyed') | ||
| }) | ||
| dhtServer.destroy(function handleDhtServerDestroyed (err) { | ||
| t.error(err, 'dht server destroyed') | ||
| }) | ||
| }) | ||
| }) | ||
| }) | ||
| }) | ||
|
|
||
| test('Load DHT state', function (t) { | ||
| t.plan(4) | ||
| var saveFile = tmp.tmpNameSync() | ||
| var node = { | ||
| host: loopback, | ||
| port: port | ||
| } | ||
| var nodes = [ node ] | ||
| var dhtState = { nodes: nodes, values: {} } | ||
| var dhtStateJson = JSON.stringify(dhtState) | ||
| fs.writeFileSync(saveFile, dhtStateJson) | ||
| var dhtServer = new DHT({ bootstrap: false }) | ||
| dhtServer.on('error', function (err) { t.fail(err) }) | ||
| dhtServer.on('warning', function (err) { t.fail(err) }) | ||
| dhtServer.listen(port, function handleServerListening () { | ||
| var client = new WebTorrent({ | ||
| dht: { host: localAddress }, | ||
| persistDhtPath: saveFile | ||
| }) | ||
| client.on('error', function (err) { t.fail(err) }) | ||
| client.on('warning', function (err) { t.fail(err) }) | ||
| client.dht.on('ready', function handleReady () { | ||
| var dhtState = client.dht.toJSON() | ||
| var nodes = dhtState.nodes | ||
| var node = nodes[0] | ||
| t.equal(node.host, loopback) | ||
| t.equal(node.port, port) | ||
| client.destroy(function handleClientDestroyed (err) { | ||
| t.error(err, 'client destroyed') | ||
| }) | ||
| dhtServer.destroy(function handleDhtServerDestroyed (err) { | ||
| t.error(err, 'dht server destroyed') | ||
| }) | ||
| }) | ||
| }) | ||
| }) |
ProTip!
Use n and p to navigate between commits in a pull request.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
It says browser exclude, but it's not actually excluded in the browser field of package.json?
like this