-
Notifications
You must be signed in to change notification settings - Fork 445
/
select.ts
365 lines (308 loc) · 11.5 KB
/
select.ts
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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
import { CodeError } from '@libp2p/interface'
import { lpStream } from 'it-length-prefixed-stream'
import pDefer from 'p-defer'
import { raceSignal } from 'race-signal'
import * as varint from 'uint8-varint'
import { Uint8ArrayList } from 'uint8arraylist'
import { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'
import { MAX_PROTOCOL_LENGTH } from './constants.js'
import * as multistream from './multistream.js'
import { PROTOCOL_ID } from './index.js'
import type { MultistreamSelectInit, ProtocolStream } from './index.js'
import type { AbortOptions } from '@libp2p/interface'
import type { Duplex } from 'it-stream-types'
export interface SelectStream extends Duplex<any, any, any> {
readStatus?: string
closeWrite?(options?: AbortOptions): Promise<void>
closeRead?(options?: AbortOptions): Promise<void>
close?(options?: AbortOptions): Promise<void>
}
/**
* Negotiate a protocol to use from a list of protocols.
*
* @param stream - A duplex iterable stream to dial on
* @param protocols - A list of protocols (or single protocol) to negotiate with. Protocols are attempted in order until a match is made.
* @param options - An options object containing an AbortSignal and an optional boolean `writeBytes` - if this is true, `Uint8Array`s will be written into `duplex`, otherwise `Uint8ArrayList`s will
* @returns A stream for the selected protocol and the protocol that was selected from the list of protocols provided to `select`.
* @example
*
* ```js
* import { pipe } from 'it-pipe'
* import * as mss from '@libp2p/multistream-select'
* import { Mplex } from '@libp2p/mplex'
*
* const muxer = new Mplex()
* const muxedStream = muxer.newStream()
*
* // mss.select(protocol(s))
* // Select from one of the passed protocols (in priority order)
* // Returns selected stream and protocol
* const { stream: dhtStream, protocol } = await mss.select(muxedStream, [
* // This might just be different versions of DHT, but could be different impls
* '/ipfs-dht/2.0.0', // Most of the time this will probably just be one item.
* '/ipfs-dht/1.0.0'
* ])
*
* // Typically this stream will be passed back to the caller of libp2p.dialProtocol
* //
* // ...it might then do something like this:
* // try {
* // await pipe(
* // [uint8ArrayFromString('Some DHT data')]
* // dhtStream,
* // async source => {
* // for await (const chunk of source)
* // // DHT response data
* // }
* // )
* // } catch (err) {
* // // Error in stream
* // }
* ```
*/
export async function select <Stream extends SelectStream> (stream: Stream, protocols: string | string[], options: MultistreamSelectInit): Promise<ProtocolStream<Stream>> {
protocols = Array.isArray(protocols) ? [...protocols] : [protocols]
if (protocols.length === 1) {
return optimisticSelect(stream, protocols[0], options)
}
const lp = lpStream(stream, {
...options,
maxDataLength: MAX_PROTOCOL_LENGTH
})
const protocol = protocols.shift()
if (protocol == null) {
throw new Error('At least one protocol must be specified')
}
options.log.trace('select: write ["%s", "%s"]', PROTOCOL_ID, protocol)
const p1 = uint8ArrayFromString(`${PROTOCOL_ID}\n`)
const p2 = uint8ArrayFromString(`${protocol}\n`)
await multistream.writeAll(lp, [p1, p2], options)
options.log.trace('select: reading multistream-select header')
let response = await multistream.readString(lp, options)
options.log.trace('select: read "%s"', response)
// Read the protocol response if we got the protocolId in return
if (response === PROTOCOL_ID) {
options.log.trace('select: reading protocol response')
response = await multistream.readString(lp, options)
options.log.trace('select: read "%s"', response)
}
// We're done
if (response === protocol) {
return { stream: lp.unwrap(), protocol }
}
// We haven't gotten a valid ack, try the other protocols
for (const protocol of protocols) {
options.log.trace('select: write "%s"', protocol)
await multistream.write(lp, uint8ArrayFromString(`${protocol}\n`), options)
options.log.trace('select: reading protocol response')
const response = await multistream.readString(lp, options)
options.log.trace('select: read "%s" for "%s"', response, protocol)
if (response === protocol) {
return { stream: lp.unwrap(), protocol }
}
}
throw new CodeError('protocol selection failed', 'ERR_UNSUPPORTED_PROTOCOL')
}
/**
* Optimistically negotiates a protocol.
*
* It *does not* block writes waiting for the other end to respond. Instead, it
* simply assumes the negotiation went successfully and starts writing data.
*
* Use when it is known that the receiver supports the desired protocol.
*/
function optimisticSelect <Stream extends SelectStream> (stream: Stream, protocol: string, options: MultistreamSelectInit): ProtocolStream<Stream> {
const originalSink = stream.sink.bind(stream)
const originalSource = stream.source
let negotiated = false
let negotiating = false
const doneNegotiating = pDefer()
let sentProtocol = false
let sendingProtocol = false
const doneSendingProtocol = pDefer()
let readProtocol = false
let readingProtocol = false
const doneReadingProtocol = pDefer()
const lp = lpStream({
sink: originalSink,
source: originalSource
}, {
...options,
maxDataLength: MAX_PROTOCOL_LENGTH
})
stream.sink = async source => {
const { sink } = lp.unwrap()
await sink(async function * () {
let sentData = false
for await (const buf of source) {
// started reading before the source yielded, wait for protocol send
if (sendingProtocol) {
await doneSendingProtocol.promise
}
// writing before reading, send the protocol and the first chunk of data
if (!sentProtocol) {
sendingProtocol = true
options.log.trace('optimistic: write ["%s", "%s", data(%d)] in sink', PROTOCOL_ID, protocol, buf.byteLength)
const protocolString = `${protocol}\n`
// send protocols in first chunk of data written to transport
yield new Uint8ArrayList(
Uint8Array.from([19]), // length of PROTOCOL_ID plus newline
uint8ArrayFromString(`${PROTOCOL_ID}\n`),
varint.encode(protocolString.length),
uint8ArrayFromString(protocolString),
buf
).subarray()
options.log.trace('optimistic: wrote ["%s", "%s", data(%d)] in sink', PROTOCOL_ID, protocol, buf.byteLength)
sentProtocol = true
sendingProtocol = false
doneSendingProtocol.resolve()
// read the negotiation response but don't block more sending
negotiate()
.catch(err => {
options.log.error('could not finish optimistic protocol negotiation of %s', protocol, err)
})
} else {
yield buf
}
sentData = true
}
// special case - the source passed to the sink has ended but we didn't
// negotiated the protocol yet so do it now
if (!sentData) {
await negotiate()
}
}())
}
async function negotiate (): Promise<void> {
if (negotiating) {
options.log.trace('optimistic: already negotiating %s stream', protocol)
await doneNegotiating.promise
return
}
negotiating = true
try {
// we haven't sent the protocol yet, send it now
if (!sentProtocol) {
options.log.trace('optimistic: doing send protocol for %s stream', protocol)
await doSendProtocol()
}
// if we haven't read the protocol response yet, do it now
if (!readProtocol) {
options.log.trace('optimistic: doing read protocol for %s stream', protocol)
await doReadProtocol()
}
} finally {
negotiating = false
negotiated = true
doneNegotiating.resolve()
}
}
async function doSendProtocol (): Promise<void> {
if (sendingProtocol) {
await doneSendingProtocol.promise
return
}
sendingProtocol = true
try {
options.log.trace('optimistic: write ["%s", "%s", data] in source', PROTOCOL_ID, protocol)
await lp.writeV([
uint8ArrayFromString(`${PROTOCOL_ID}\n`),
uint8ArrayFromString(`${protocol}\n`)
])
options.log.trace('optimistic: wrote ["%s", "%s", data] in source', PROTOCOL_ID, protocol)
} finally {
sentProtocol = true
sendingProtocol = false
doneSendingProtocol.resolve()
}
}
async function doReadProtocol (): Promise<void> {
if (readingProtocol) {
await doneReadingProtocol.promise
return
}
readingProtocol = true
try {
options.log.trace('optimistic: reading multistream select header')
let response = await multistream.readString(lp, options)
options.log.trace('optimistic: read multistream select header "%s"', response)
if (response === PROTOCOL_ID) {
response = await multistream.readString(lp, options)
}
options.log.trace('optimistic: read protocol "%s", expecting "%s"', response, protocol)
if (response !== protocol) {
throw new CodeError('protocol selection failed', 'ERR_UNSUPPORTED_PROTOCOL')
}
} finally {
readProtocol = true
readingProtocol = false
doneReadingProtocol.resolve()
}
}
stream.source = (async function * () {
// make sure we've done protocol negotiation before we read stream data
await negotiate()
options.log.trace('optimistic: reading data from "%s" stream', protocol)
yield * lp.unwrap().source
})()
if (stream.closeRead != null) {
const originalCloseRead = stream.closeRead.bind(stream)
stream.closeRead = async (opts) => {
// we need to read & write to negotiate the protocol so ensure we've done
// this before closing the readable end of the stream
if (!negotiated) {
await negotiate().catch(err => {
options.log.error('could not negotiate protocol before close read', err)
})
}
// protocol has been negotiated, ok to close the readable end
await originalCloseRead(opts)
}
}
if (stream.closeWrite != null) {
const originalCloseWrite = stream.closeWrite.bind(stream)
stream.closeWrite = async (opts) => {
// we need to read & write to negotiate the protocol so ensure we've done
// this before closing the writable end of the stream
if (!negotiated) {
await negotiate().catch(err => {
options.log.error('could not negotiate protocol before close write', err)
})
}
// protocol has been negotiated, ok to close the writable end
await originalCloseWrite(opts)
}
}
if (stream.close != null) {
const originalClose = stream.close.bind(stream)
stream.close = async (opts) => {
// if we are in the process of negotiation, let it finish before closing
// because we may have unsent early data
const tasks = []
if (sendingProtocol) {
tasks.push(doneSendingProtocol.promise)
}
if (readingProtocol) {
tasks.push(doneReadingProtocol.promise)
}
if (tasks.length > 0) {
// let the in-flight protocol negotiation finish gracefully
await raceSignal(
Promise.all(tasks),
opts?.signal
)
} else {
// no protocol negotiation attempt has occurred so don't start one
negotiated = true
negotiating = false
doneNegotiating.resolve()
}
// protocol has been negotiated, ok to close the writable end
await originalClose(opts)
}
}
return {
stream,
protocol
}
}