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
157 lines (140 loc) · 4.57 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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
import { logger } from '@libp2p/logger'
import { configure } from '../lib/configure.js'
import { toUrlSearchParams } from '../lib/to-url-search-params.js'
import { textToUrlSafeRpc, rpcToText, rpcToBytes, rpcToBigInt } from '../lib/http-rpc-wire-format.js'
import { peerIdFromString } from '@libp2p/peer-id'
const log = logger('ipfs-http-client:pubsub:subscribe')
/**
* @typedef {import('../types').HTTPClientExtraOptions} HTTPClientExtraOptions
* @typedef {import('@libp2p/interface-pubsub').Message} Message
* @typedef {(err: Error, fatal: boolean, msg?: Message) => void} ErrorHandlerFn
* @typedef {import('ipfs-core-types/src/pubsub').API<HTTPClientExtraOptions & { onError?: ErrorHandlerFn }>} PubsubAPI
* @typedef {import('../types').Options} Options
*/
/**
* @param {Options} options
* @param {import('./subscription-tracker').SubscriptionTracker} subsTracker
*/
export const createSubscribe = (options, subsTracker) => {
return configure((api) => {
/**
* @type {PubsubAPI["subscribe"]}
*/
async function subscribe (topic, handler, options = {}) { // eslint-disable-line require-await
options.signal = subsTracker.subscribe(topic, handler, options.signal)
/** @type {(value?: any) => void} */
let done
/** @type {(error: Error) => void} */
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
api.post('pubsub/sub', {
signal: options.signal,
searchParams: toUrlSearchParams({
arg: textToUrlSafeRpc(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, {
onMessage: (message) => {
if (!handler) {
return
}
if (typeof handler === 'function') {
handler(message)
return
}
if (typeof handler.handleEvent === 'function') {
handler.handleEvent(message)
}
},
onEnd: () => subsTracker.unsubscribe(topic, handler),
onError: options.onError
})
done()
})
return result
}
return subscribe
})(options)
}
/**
* @param {import('ipfs-utils/src/types').ExtendedResponse} response
* @param {object} options
* @param {(message: Message) => void} options.onMessage
* @param {() => void} options.onEnd
* @param {ErrorHandlerFn} [options.onError]
*/
async function readMessages (response, { onMessage, onEnd, onError }) {
onError = onError || log
try {
for await (const msg of response.ndjson()) {
try {
if (!msg.from) {
continue
}
if (msg.from != null && msg.seqno != null) {
onMessage({
type: 'signed',
from: peerIdFromString(msg.from),
data: rpcToBytes(msg.data),
sequenceNumber: rpcToBigInt(msg.seqno),
topic: rpcToText(msg.topicIDs[0]),
key: rpcToBytes(msg.key ?? 'u'),
signature: rpcToBytes(msg.signature ?? 'u')
})
} else {
onMessage({
type: 'unsigned',
data: rpcToBytes(msg.data),
topic: rpcToText(msg.topicIDs[0])
})
}
} catch (/** @type {any} */ err) {
err.message = `Failed to parse pubsub message: ${err.message}`
onError(err, false, msg) // Not fatal
}
}
} catch (/** @type {any} */ err) {
if (!isAbortError(err)) {
onError(err, true) // Fatal
}
} finally {
onEnd()
}
}
/**
* @param {Error & {type?:string}} error
* @returns {boolean}
*/
const isAbortError = error => {
switch (error.type) {
case 'aborted':
return true
// It is `abort` in Electron instead of `aborted`
case 'abort':
return true
default:
// FIXME: In testing with Chrome, err.type is undefined (should not be!)
// Temporarily use the name property instead.
return error.name === 'AbortError'
}
}