|
| 1 | +'use strict' |
| 2 | + |
| 3 | +const promisify = require('promisify-es6') |
| 4 | +const WorkerQueue = require('./queue') |
| 5 | + |
| 6 | +const { blockKeyToCid } = require('../utils') |
| 7 | + |
| 8 | +// const initialDelay = 15000 |
| 9 | +const initialDelay = 3000 |
| 10 | + |
| 11 | +class Reprovider { |
| 12 | + /** |
| 13 | + * Reprovider goal is to reannounce blocks to the network. |
| 14 | + * @param {object} contentRouting |
| 15 | + * @param {Blockstore} blockstore |
| 16 | + * @param {object} options |
| 17 | + * @memberof Reprovider |
| 18 | + */ |
| 19 | + constructor (contentRouting, blockstore, options) { |
| 20 | + this._contentRouting = contentRouting |
| 21 | + this._blockstore = blockstore |
| 22 | + this._options = options |
| 23 | + |
| 24 | + this._timeoutId = undefined |
| 25 | + this._worker = new WorkerQueue(this._provideBlock) |
| 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 | + this._runPeriodically() |
| 36 | + }, initialDelay) |
| 37 | + } |
| 38 | + |
| 39 | + /** |
| 40 | + * Stops the reprovider. Any active reprovide actions should be aborted |
| 41 | + * @returns {void} |
| 42 | + */ |
| 43 | + stop () { |
| 44 | + if (this._timeoutId) { |
| 45 | + clearTimeout(this._timeoutId) |
| 46 | + this._timeoutId = undefined |
| 47 | + } |
| 48 | + this._worker.stop() |
| 49 | + } |
| 50 | + |
| 51 | + /** |
| 52 | + * Run reprovide on every `options.interval` ms |
| 53 | + * @returns {void} |
| 54 | + */ |
| 55 | + async _runPeriodically () { |
| 56 | + while (this._timeoutId) { |
| 57 | + const blocks = await promisify((callback) => this._blockstore.query({}, callback))() |
| 58 | + |
| 59 | + // TODO strategy logic here |
| 60 | + if (this._options.strategy === 'pinned') { |
| 61 | + |
| 62 | + } else if (this._options.strategy === 'pinned') { |
| 63 | + |
| 64 | + } |
| 65 | + |
| 66 | + await this._worker.execute(blocks) |
| 67 | + |
| 68 | + // Each subsequent walk should run on a `this._options.interval` interval |
| 69 | + await new Promise(resolve => { |
| 70 | + this._timeoutId = setTimeout(resolve, this._options.interval) |
| 71 | + }) |
| 72 | + } |
| 73 | + } |
| 74 | + |
| 75 | + /** |
| 76 | + * Do the reprovide work to libp2p content routing |
| 77 | + * @param {Block} block |
| 78 | + * @returns {void} |
| 79 | + */ |
| 80 | + async _provideBlock (block) { |
| 81 | + const cid = blockKeyToCid(block.key.toBuffer()) |
| 82 | + |
| 83 | + await promisify((callback) => { |
| 84 | + this._contentRouting.provide(cid, callback) |
| 85 | + })() |
| 86 | + } |
| 87 | +} |
| 88 | + |
| 89 | +exports = module.exports = Reprovider |
0 commit comments