|
| 1 | +'use strict' |
| 2 | + |
| 3 | +const debug = require('debug') |
| 4 | +const errcode = require('err-code') |
| 5 | +const promisify = require('promisify-es6') |
| 6 | + |
| 7 | +const IpnsPubsubDatastore = require('../ipns/routing/pubsub-datastore') |
| 8 | + |
| 9 | +const log = debug('jsipfs:name-pubsub') |
| 10 | +log.error = debug('jsipfs:name-pubsub:error') |
| 11 | + |
| 12 | +// Is pubsub enabled |
| 13 | +const isNamePubsubEnabled = (node) => { |
| 14 | + try { |
| 15 | + return Boolean(getPubsubRouting(node)) |
| 16 | + } catch (err) { |
| 17 | + return false |
| 18 | + } |
| 19 | +} |
| 20 | + |
| 21 | +// Get pubsub from IPNS routing |
| 22 | +const getPubsubRouting = (node) => { |
| 23 | + if (!node._ipns || !node._options.EXPERIMENTAL.ipnsPubsub) { |
| 24 | + const errMsg = 'IPNS pubsub subsystem is not enabled' |
| 25 | + |
| 26 | + throw errcode(errMsg, 'ERR_IPNS_PUBSUB_NOT_ENABLED') |
| 27 | + } |
| 28 | + |
| 29 | + // Only one store and it is pubsub |
| 30 | + if (IpnsPubsubDatastore.isIpnsPubsubDatastore(node._ipns.routing)) { |
| 31 | + return node._ipns.routing |
| 32 | + } |
| 33 | + |
| 34 | + // Find in tiered |
| 35 | + const pubsub = (node._ipns.routing.stores || []).find(s => IpnsPubsubDatastore.isIpnsPubsubDatastore(s)) |
| 36 | + |
| 37 | + if (!pubsub) { |
| 38 | + const errMsg = 'IPNS pubsub datastore not found' |
| 39 | + |
| 40 | + throw errcode(errMsg, 'ERR_PUBSUB_DATASTORE_NOT_FOUND') |
| 41 | + } |
| 42 | + |
| 43 | + return pubsub |
| 44 | +} |
| 45 | + |
| 46 | +module.exports = function namePubsub (self) { |
| 47 | + return { |
| 48 | + /** |
| 49 | + * Query the state of IPNS pubsub. |
| 50 | + * |
| 51 | + * @returns {Promise|void} |
| 52 | + */ |
| 53 | + state: promisify((callback) => { |
| 54 | + callback(null, { |
| 55 | + enabled: isNamePubsubEnabled(self) |
| 56 | + }) |
| 57 | + }), |
| 58 | + /** |
| 59 | + * Cancel a name subscription. |
| 60 | + * |
| 61 | + * @param {String} name subscription name. |
| 62 | + * @param {function(Error)} [callback] |
| 63 | + * @returns {Promise|void} |
| 64 | + */ |
| 65 | + cancel: promisify((name, callback) => { |
| 66 | + let pubsub |
| 67 | + try { |
| 68 | + pubsub = getPubsubRouting(self) |
| 69 | + } catch (err) { |
| 70 | + return callback(err) |
| 71 | + } |
| 72 | + |
| 73 | + pubsub.cancel(name, callback) |
| 74 | + }), |
| 75 | + /** |
| 76 | + * Show current name subscriptions. |
| 77 | + * |
| 78 | + * @param {function(Error)} [callback] |
| 79 | + * @returns {Promise|void} |
| 80 | + */ |
| 81 | + subs: promisify((callback) => { |
| 82 | + let pubsub |
| 83 | + try { |
| 84 | + pubsub = getPubsubRouting(self) |
| 85 | + } catch (err) { |
| 86 | + return callback(err) |
| 87 | + } |
| 88 | + |
| 89 | + pubsub.getSubscriptions(callback) |
| 90 | + }) |
| 91 | + } |
| 92 | +} |
0 commit comments