This repository has been archived by the owner on Feb 12, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
subscribe.js
97 lines (82 loc) · 2.76 KB
/
subscribe.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
'use strict'
const uint8ArrayFromString = require('uint8arrays/from-string')
const uint8ArrayToString = require('uint8arrays/to-string')
const log = require('debug')('ipfs-http-client:pubsub:subscribe')
const SubscriptionTracker = require('./subscription-tracker')
const configure = require('../lib/configure')
const toUrlSearchParams = require('../lib/to-url-search-params')
module.exports = configure((api, options) => {
const subsTracker = SubscriptionTracker.singleton()
return async (topic, handler, options = {}) => { // eslint-disable-line require-await
options.signal = subsTracker.subscribe(topic, handler, options.signal)
let done
let fail
const result = new Promise((resolve, reject) => {
done = resolve
fail = reject
})
// In Firefox, the initial call to fetch does not resolve until some data
// is received. If this doesn't happen within 1 second assume success
const ffWorkaround = setTimeout(() => done(), 1000)
// Do this async to not block Firefox
setTimeout(() => {
api.post('pubsub/sub', {
timeout: options.timeout,
signal: options.signal,
searchParams: toUrlSearchParams({
arg: topic,
...options
}),
headers: options.headers
})
.catch((err) => {
// Initial subscribe fail, ensure we clean up
subsTracker.unsubscribe(topic, handler)
fail(err)
})
.then((response) => {
clearTimeout(ffWorkaround)
if (!response) {
// if there was no response, the subscribe failed
return
}
readMessages(response.ndjson(), {
onMessage: handler,
onEnd: () => subsTracker.unsubscribe(topic, handler),
onError: options.onError
})
done()
})
}, 0)
return result
}
})
async function readMessages (msgStream, { onMessage, onEnd, onError }) {
onError = onError || log
try {
for await (const msg of msgStream) {
try {
if (!msg.from) {
continue
}
onMessage({
from: uint8ArrayToString(uint8ArrayFromString(msg.from, 'base64pad'), 'base58btc'),
data: uint8ArrayFromString(msg.data, 'base64pad'),
seqno: uint8ArrayFromString(msg.seqno, 'base64pad'),
topicIDs: msg.topicIDs
})
} catch (err) {
err.message = `Failed to parse pubsub message: ${err.message}`
onError(err, false, msg) // Not fatal
}
}
} catch (err) {
// FIXME: In testing with Chrome, err.type is undefined (should not be!)
// Temporarily use the name property instead.
if (err.type !== 'aborted' && err.name !== 'AbortError') {
onError(err, true) // Fatal
}
} finally {
onEnd()
}
}