forked from ipfs/js-ipfs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
289 lines (252 loc) · 5.96 KB
/
server.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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
'use strict'
/* eslint-env browser */
const { encodeError } = require('ipfs-message-port-protocol/src/error')
/**
* @typedef {import('ipfs-message-port-protocol/src/data').EncodedError} EncodedError
*/
/**
* @template X, T
* @typedef {import('ipfs-message-port-protocol/src/data').Result<X, T>} Result
*/
/**
* @template T
* @typedef {import('ipfs-message-port-protocol/src/rpc').ProcedureNames<T>} ProcedureNames
*/
/**
* @template T
* @typedef {import('ipfs-message-port-protocol/src/rpc').Method<T>} Method
*/
/**
* @template T
* @typedef {import('ipfs-message-port-protocol/src/rpc').Namespace<T>} Namespace
*/
/**
* @template T
* @typedef {import('ipfs-message-port-protocol/src/rpc').ServiceQuery<T>} ServiceQuery
*/
/**
* @template T
* @typedef {import('ipfs-message-port-protocol/src/rpc').RPCQuery<T>} RPCQuery
*/
/**
* @template T
* @typedef {import('ipfs-message-port-protocol/src/rpc').Inn<T>} Inn
*/
/**
* @template T
* @typedef {import('ipfs-message-port-protocol/src/rpc').Out<T>} Out
*/
/**
* @template T
* @typedef {Object} QueryMessage
* @property {'query'} type
* @property {Namespace<T>} namespace
* @property {Method<T>} method
* @property {string} id
* @property {Inn<T>} input
*/
/**
* @typedef {Object} AbortMessage
* @property {'abort'} type
* @property {string} id
*/
/**
* @typedef {Object} TransferOptions
* @property {Transferable[]} [transfer]
*/
/**
* @template O
* @typedef {O & TransferOptions} QueryResult
*/
/**
* @template T
* @typedef {AbortMessage|QueryMessage<T>} Message
*/
/**
* @template T, K
* @typedef {import('ipfs-message-port-protocol/src/rpc').NamespacedQuery<T, K>} NamespacedQuery
*/
/**
* Represents a client query received on the server.
*
* @template T
* @extends {ServiceQuery<T>}
*/
const Query = class Query {
/**
* @param {Namespace<T>} namespace
* @param {Method<T>} method
* @param {Inn<T>} input
*/
constructor (namespace, method, input) {
this.result = new Promise((resolve, reject) => {
this.succeed = resolve
this.fail = reject
this.namespace = namespace
this.method = method
this.input = input
this.abortController = new AbortController()
this.signal = this.abortController.signal
})
}
/**
* Aborts this query if it is still pending.
*/
abort () {
this.abortController.abort()
this.fail(new AbortError())
}
}
exports.Query = Query
/**
* @template T
* @typedef {import('ipfs-message-port-protocol/src/rpc').MultiService<T>} MultiService
*/
/**
* Server wraps `T` service and executes queries received from connected ports.
*
* @template T
*/
exports.Server = class Server {
/**
* @param {MultiService<T>} services
*/
constructor (services) {
this.services = services
/** @type {Record<string, Query<T>>} */
this.queries = Object.create(null)
}
/**
* @param {MessagePort} port
*/
connect (port) {
port.addEventListener('message', this)
port.start()
}
/**
* @param {MessagePort} port
*/
disconnect (port) {
port.removeEventListener('message', this)
port.close()
}
/**
* Handles messages received from connected clients
*
* @param {MessageEvent} event
* @returns {void}
*/
handleEvent (event) {
/** @type {Message<T>} */
const data = event.data
switch (data.type) {
case 'query': {
this.handleQuery(
data.id,
new Query(data.namespace, data.method, data.input),
/** @type {MessagePort} */
(event.target)
)
return undefined
}
case 'abort': {
return this.abort(data.id)
}
default: {
throw new UnsupportedMessageError(event)
}
}
}
/**
* Abort query for the given id.
*
* @param {string} id
*/
abort (id) {
const query = this.queries[id]
if (query) {
delete this.queries[id]
query.abort()
}
}
/**
* Handles query received from the client.
*
* @param {string} id
* @param {Query<T>} query
* @param {MessagePort} port
*/
async handleQuery (id, query, port) {
this.queries[id] = query
await this.run(query)
delete this.queries[id]
if (!query.signal.aborted) {
try {
const value = await query.result
const transfer = [...new Set(value.transfer || [])]
delete value.transfer
port.postMessage(
{ type: 'result', id, result: { ok: true, value } },
transfer
)
} catch (error) {
port.postMessage({
type: 'result',
id,
result: { ok: false, error: encodeError(error) }
})
}
}
}
/**
* @param {Query<T>} query
* @returns {void}
*/
run (query) {
const { services } = this
const { namespace, method } = query
const service = services[namespace]
if (service) {
if (typeof service[method] === 'function') {
try {
const result = service[method]({ ...query.input, signal: query.signal })
Promise.resolve(result).then(query.succeed, query.fail)
} catch (error) {
query.fail(error)
}
} else {
query.fail(new RangeError(`Method '${method}' is not found`))
}
} else {
query.fail(new RangeError(`Namespace '${namespace}' is not found`))
}
}
/**
* @param {RPCQuery<T>} data
* @returns {Out<T>}
*/
execute (data) {
const query = new Query(data.namespace, data.method, data.input)
this.run(query)
return query.result
}
}
const UnsupportedMessageError = class UnsupportedMessageError extends RangeError {
/**
* @param {MessageEvent} event
*/
constructor (event) {
super('Unexpected message was received by the server')
this.event = event
}
get name () {
return this.constructor.name
}
}
exports.UnsupportedMessageError = UnsupportedMessageError
const AbortError = class AbortError extends Error {
get name () {
return this.constructor.name
}
}
exports.AbortError = AbortError