Skip to content
This repository has been archived by the owner on Mar 10, 2020. It is now read-only.

Commit

Permalink
fix: add workaround for subscribe in Firefox
Browse files Browse the repository at this point in the history
License: MIT
Signed-off-by: Alan Shaw <[email protected]>
  • Loading branch information
Alan Shaw committed Jul 26, 2019
1 parent 370a801 commit 3a0fe8a
Showing 1 changed file with 18 additions and 3 deletions.
21 changes: 18 additions & 3 deletions src/pubsub/subscribe.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,15 @@ const ndjson = require('iterable-ndjson')
const explain = require('explain-error')
const bs58 = require('bs58')
const { Buffer } = require('buffer')
const log = require('debug')('ipfs-http-client:pubsub:subscribe')
const { objectToQuery } = require('../lib/querystring')
const configure = require('../lib/configure')
const { ok, toIterable } = require('../lib/fetch')
const SubscriptionTracker = require('./subscription-tracker')

module.exports = configure(({ fetch, apiAddr, apiPath, headers }) => {
const subsTracker = SubscriptionTracker.singleton()
const publish = require('./publish')({ fetch, apiAddr, apiPath, headers })

return async (topic, handler, options) => {
options = options || {}
Expand All @@ -25,6 +27,18 @@ module.exports = configure(({ fetch, apiAddr, apiPath, headers }) => {
const url = `${apiAddr}${apiPath}/pubsub/sub${qs}`
let res

// In Firefox, the initial call to fetch does not resolve until some data
// is received. If this doesn't happen within 1 second send an empty message
// to kickstart the process.
const ffWorkaround = setTimeout(async () => {
log(`Publishing empty message to "${topic}" to resolve subscription request`)
try {
await publish(topic, Buffer.alloc(0), options)
} catch (err) {
log('Failed to publish empty message', err)
}
}, 1000)

try {
res = await ok(fetch(url, {
method: 'POST',
Expand All @@ -36,6 +50,8 @@ module.exports = configure(({ fetch, apiAddr, apiPath, headers }) => {
throw err
}

clearTimeout(ffWorkaround)

readMessages(ndjson(toIterable(res.body)), {
onMessage: handler,
onEnd: () => subsTracker.unsubscribe(topic, handler),
Expand All @@ -45,8 +61,7 @@ module.exports = configure(({ fetch, apiAddr, apiPath, headers }) => {
})

async function readMessages (msgStream, { onMessage, onEnd, onError }) {
// eslint-disable-next-line no-console
onError = onError || (err => console.error(err))
onError = onError || log

try {
for await (const msg of msgStream) {
Expand All @@ -58,7 +73,7 @@ async function readMessages (msgStream, { onMessage, onEnd, onError }) {
topicIDs: msg.topicIDs
})
} catch (err) {
onError(explain(err, 'Failed to parse pubsub message'), false) // Not fatal
onError(explain(err, 'Failed to parse pubsub message'), false, msg) // Not fatal
}
}
} catch (err) {
Expand Down

0 comments on commit 3a0fe8a

Please sign in to comment.