-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathindex.js
256 lines (246 loc) · 7.31 KB
/
index.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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
class BrowserProvider {
constructor (url, options = {}) {
this.url = url
this.wsUrl =
options.wsUrl || url.replace(/^https:/, 'wss:').replace(/^http:/, 'ws:')
this.httpUrl =
options.httpUrl || url.replace(/^wss:/, 'https:').replace(/^ws:/, 'http:')
this.importUrl =
options.importUrl || this.httpUrl.replace(/\/rpc\//, '/rest/') + '/import'
this.transport = options.transport || (url.match(/^http/) ? 'http' : 'ws')
this.sendHttpContentType = options.sendHttpContentType || 'text/plain;charset=UTF-8'
this.id = 0
this.inflight = new Map()
this.cancelled = new Map()
this.subscriptions = new Map()
if (typeof options.token === 'function') {
this.tokenCallback = options.token
} else {
this.token = options.token
if (this.token && this.token !== '') {
this.url += `?token=${this.token}`
}
}
this.authorizationHeader = options.authorizationHeader
this.WebSocket = options.WebSocket || globalThis.WebSocket
this.fetch = options.fetch || globalThis.fetch.bind(globalThis)
}
connect () {
if (!this.connectPromise) {
const getConnectPromise = () => {
return new Promise((resolve, reject) => {
if (this.transport !== 'ws') return resolve()
this.ws = new this.WebSocket(this.url)
// FIXME: reject on error or timeout
this.ws.onopen = function () {
resolve()
}
this.ws.onerror = function () {
console.error('ws error')
reject(new Error('websocket error'))
}
this.ws.onmessage = this.receive.bind(this)
})
}
if (this.tokenCallback) {
const getToken = async () => {
this.token = await this.tokenCallback()
delete this.tokenCallback
if (this.token && this.token !== '') {
this.url += `?token=${this.token}`
}
}
this.connectPromise = getToken().then(() => getConnectPromise())
} else {
this.connectPromise = getConnectPromise()
}
}
return this.connectPromise
}
send (request, schemaMethod) {
const jsonRpcRequest = {
jsonrpc: '2.0',
id: this.id++,
...request
}
if (this.transport === 'ws') {
return this.sendWs(jsonRpcRequest)
} else {
return this.sendHttp(jsonRpcRequest)
}
}
async sendHttp (jsonRpcRequest) {
await this.connect()
const headers = {
'Content-Type': this.sendHttpContentType,
Accept: '*/*'
}
if (this.token) {
headers.Authorization = `Bearer ${this.token}`
}
if (this.authorizationHeader) {
headers.Authorization = this.authorizationHeader
}
const response = await this.fetch(this.httpUrl, {
method: 'POST',
headers,
body: JSON.stringify(jsonRpcRequest)
})
// FIXME: Check return code, errors
const { error, result } = await response.json()
if (error) {
// FIXME: Return error class with error.code
throw new Error(error.message)
}
return result
}
sendWs (jsonRpcRequest) {
const promise = new Promise((resolve, reject) => {
if (this.destroyed) {
reject(new Error('WebSocket has already been destroyed'))
}
this.ws.send(JSON.stringify(jsonRpcRequest))
// FIXME: Add timeout
this.inflight.set(jsonRpcRequest.id, (err, result) => {
if (err) {
reject(err)
} else {
resolve(result)
}
})
})
return promise
}
sendSubscription (request, schemaMethod, subscriptionCb) {
let chanId = null
const json = {
jsonrpc: '2.0',
id: this.id++,
...request
}
if (this.transport !== 'ws') {
return [
() => {},
Promise.reject(
new Error('Subscriptions only supported for WebSocket transport')
)
]
}
const promise = this.connect().then(() => {
this.ws.send(JSON.stringify(json))
// FIXME: Add timeout
return new Promise((resolve, reject) => {
this.inflight.set(json.id, (err, result) => {
chanId = result
// console.info(`New subscription ${json.id} using channel ${chanId}`)
this.subscriptions.set(chanId, subscriptionCb)
if (err) {
reject(err)
} else {
resolve()
}
})
})
})
return [cancel.bind(this), promise]
async function cancel () {
await promise
this.inflight.delete(json.id)
if (chanId !== null) {
this.subscriptions.delete(chanId)
await new Promise(resolve => {
// FIXME: Add timeout
this.cancelled.set(chanId, {
cancelledAt: Date.now(),
closeCb: resolve
})
if (!this.destroyed) {
this.sendWs({
jsonrpc: '2.0',
method: 'xrpc.cancel',
params: [json.id]
})
}
})
// console.info(`Subscription ${json.id} cancelled, channel ${chanId} closed.`)
}
}
}
receive (event) {
try {
const { id, error, result, method, params } = JSON.parse(event.data)
// FIXME: Check return code, errors
if (method === 'xrpc.ch.val') {
// FIXME: Check return code, errors
const [chanId, data] = params
const subscriptionCb = this.subscriptions.get(chanId)
if (subscriptionCb) {
subscriptionCb(data)
} else {
const { cancelledAt } = this.cancelled.get(chanId)
if (cancelledAt) {
if (Date.now() - cancelledAt > 2000) {
console.warn(
'Received stale response for cancelled subscription on channel',
chanId
)
}
} else {
console.warn('Could not find subscription for channel', chanId)
}
}
} else if (method === 'xrpc.ch.close') {
// FIXME: Check return code, errors
const [chanId] = params
const { closeCb } = this.cancelled.get(chanId)
if (!closeCb) {
console.warn(`Channel ${chanId} was closed before being cancelled`)
} else {
// console.info(`Channel ${chanId} was closed, calling callback`)
closeCb()
}
} else {
const cb = this.inflight.get(id)
if (cb) {
this.inflight.delete(id)
if (error) {
// FIXME: Return error class with error.code
return cb(new Error(error.message))
}
cb(null, result)
} else {
console.warn(`Couldn't find request for ${id}`)
}
}
} catch (e) {
console.error('RPC receive error', e)
}
}
async importFile (body) {
await this.connect()
const headers = {
'Content-Type': body.type,
Accept: '*/*',
Authorization: `Bearer ${this.token}`
}
const response = await this.fetch(this.importUrl, {
method: 'PUT',
headers,
body
})
// FIXME: Check return code, errors
const result = await response.json()
const {
Cid: { '/': cid }
} = result
return cid
}
async destroy (code = 1000) {
// List of codes: https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent#Status_codes
if (this.ws) {
this.ws.close(code)
this.destroyed = true
}
}
}
module.exports = { BrowserProvider }