|
| 1 | +'use strict' |
| 2 | + |
| 3 | +const promisify = require('promisify-es6') |
| 4 | + |
| 5 | +const { blockKeyToCid } = require('../utils') |
| 6 | + |
| 7 | +// TODO Provide queue? |
| 8 | + |
| 9 | +// const initialDelay = 10000 |
| 10 | +const initialDelay = 5000 |
| 11 | + |
| 12 | +class Reprovider { |
| 13 | + /** |
| 14 | + * Reprovider goal is t§o reannounce blocks to the network. |
| 15 | + * @param {*} contentRouting |
| 16 | + * @param {Blockstore} blockstore |
| 17 | + * @param {object} options |
| 18 | + * @memberof Reprovider |
| 19 | + */ |
| 20 | + constructor (contentRouting, blockstore, options) { |
| 21 | + this._contentRouting = contentRouting |
| 22 | + this._blockstore = blockstore // use query({}) |
| 23 | + this._options = options |
| 24 | + |
| 25 | + this._timeoutId = undefined |
| 26 | + } |
| 27 | + |
| 28 | + /** |
| 29 | + * Begin processing the reprovider work and waiting for reprovide triggers |
| 30 | + * @returns {void} |
| 31 | + */ |
| 32 | + start () { |
| 33 | + // Start doing reprovides after the initial delay |
| 34 | + this._timeoutId = setTimeout(() => { |
| 35 | + // start runner immediately |
| 36 | + this._runPeriodically() |
| 37 | + }, initialDelay) |
| 38 | + } |
| 39 | + |
| 40 | + /** |
| 41 | + * Stops the reprovider. Any active reprovide actions should be aborted |
| 42 | + */ |
| 43 | + stop() { |
| 44 | + if (this._timeoutId) { |
| 45 | + clearTimeout(this._timeoutId) |
| 46 | + this._timeoutId = undefined |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + /** |
| 51 | + * Run reprovide on every `options.interval` ms |
| 52 | + * @returns {void} |
| 53 | + */ |
| 54 | + async _runPeriodically () { |
| 55 | + while (this._timeoutId) { |
| 56 | + const blocks = await promisify((callback) => this._blockstore.query({}, callback))() |
| 57 | + |
| 58 | + await this._reprovide(blocks) |
| 59 | + |
| 60 | + await new Promise(resolve => { |
| 61 | + this._timeoutId = setTimeout(resolve, 20000) |
| 62 | + }) |
| 63 | + |
| 64 | + /* |
| 65 | + // Each subsequent walk should run on a `this._options.interval` interval |
| 66 | + await new Promise(resolve => { |
| 67 | + this._timeoutId = setTimeout(resolve, this._options.interval) |
| 68 | + }) */ |
| 69 | + } |
| 70 | + } |
| 71 | + |
| 72 | + /** |
| 73 | + * provide all keys to libp2p content routing |
| 74 | + */ |
| 75 | + async _reprovide (blocks) { |
| 76 | + for (let i = 0; i < blocks.length && this._timeoutId; i++) { |
| 77 | + const cid = blockKeyToCid(blocks[i].key.toBuffer()) |
| 78 | + |
| 79 | + console.log('cid') |
| 80 | + // TODO: needs the DHT |
| 81 | + // await promisify((callback) => { |
| 82 | + // this._contentRouting.provide(cid, callback) |
| 83 | + // })() |
| 84 | + } |
| 85 | + console.log('end') |
| 86 | + } |
| 87 | + |
| 88 | + _dsKeyToCid (key) { |
| 89 | + |
| 90 | + } |
| 91 | +} |
| 92 | + |
| 93 | +exports = module.exports = Reprovider |
0 commit comments