Repository navigation
Expand file tree
/
Copy pathmultistream.nim
More file actions
456 lines (395 loc) · 14.9 KB
/
Copy pathmultistream.nim
File metadata and controls
456 lines (395 loc) · 14.9 KB
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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
# SPDX-License-Identifier: Apache-2.0 OR MIT
# Copyright (c) Status Research & Development GmbH
{.push raises: [].}
import std/[strutils, sequtils]
import chronos, results, chronicles, stew/byteutils
import stream/connection, protocols/protocol, utils/opt
logScope:
topics = "libp2p multistream"
const
MsgSize = 1024
Codec = "/multistream/1.0.0"
Na = "na\n"
Ls = "ls\n"
type
Matcher* = proc(proto: string): bool {.gcsafe, raises: [].}
MultiStreamError* = object of LPError
MultiStreamFailure* {.pure.} = enum
MalformedMessage = "MultistreamSelect failed, malformed message"
HandshakeFailed = "MultistreamSelect handshake failed"
InvalidFirstMessage = "MultistreamSelect handling failed, invalid first message"
MultiStreamResult*[T] = Result[T, MultiStreamFailure]
HandlerHolder* = ref object
protos*: seq[string]
protocol*: LPProtocol
match*: Matcher
MultistreamSelect* = ref object of RootObj
handlers*: seq[HandlerHolder]
codec*: string
proc new*(T: typedesc[MultistreamSelect]): T =
T(codec: Codec)
func decodeMessage(data: openArray[byte]): MultiStreamResult[string] =
if data.len == 0 or data[^1] != byte('\n'):
return err(MultiStreamFailure.MalformedMessage)
ok(string.fromBytes(data.toOpenArray(0, data.high - 1)))
template readMessage(stream: Stream): MultiStreamResult[string] =
decodeMessage(await stream.readLp(MsgSize))
const DefaultOptimisticCloseTimeout* = 10.seconds
## Default acknowledgement wait before resetting an unconfirmed stream.
type OptimisticStream = ref object of Connection
stream: Stream
confirmed: bool
confirmFut: Future[void].Raising([CancelledError, LPStreamError])
closeTimeout: Duration
method getWrapped(s: OptimisticStream): Connection =
s.stream
method atEof(s: OptimisticStream): bool =
s.stream.atEof
method closed(s: OptimisticStream): bool =
s.isClosed or s.stream.closed
method join(s: OptimisticStream) {.async: (raises: [CancelledError]).} =
await s.stream.join()
if s.isClosed:
await s.closeEvent.wait()
else:
await s.close()
proc confirm(s: OptimisticStream) {.async: (raises: [CancelledError, LPStreamError]).} =
let header = s.stream.readMessage().valueOr:
raise
newException(LPStreamError, "Optimistic multistream handshake failed: " & $error)
if header != Codec:
raise newException(
LPStreamError, "Optimistic multistream handshake failed: unexpected codec"
)
let response = s.stream.readMessage().valueOr:
raise newException(
LPStreamError, "Optimistic multistream protocol negotiation failed: " & $error
)
if response != s.protocol:
raise newException(LPStreamError, "Optimistic multistream protocol rejected")
s.confirmed = true
method closeImpl(s: OptimisticStream) {.async: (raises: []).} =
if not s.confirmed and not s.stream.closed:
# Let the responder finish negotiation before signalling that reads ended.
# Otherwise it may discard already-written application data.
if s.confirmFut.isNil:
s.confirmFut = s.confirm()
# `race` does not cancel `confirmFut`, which a reader may also await.
let timer = sleepAsync(s.closeTimeout)
try:
discard await race(s.confirmFut, timer)
except CancelledError:
discard
timer.cancelSoon()
if not s.confirmFut.finished:
# Timed out or cancelled: reset instead of half-closing an unconfirmed stream.
await noCancel s.reset()
return
await s.stream.close()
await procCall Connection(s).closeImpl()
method resetImpl(s: OptimisticStream) {.async: (raises: []).} =
await s.stream.reset()
await procCall Connection(s).closeImpl()
method closeWrite(s: OptimisticStream) {.async: (raises: []).} =
await s.stream.closeWrite()
method write(
s: OptimisticStream, msg: sink seq[byte]
) {.async: (raises: [CancelledError, LPStreamError]).} =
if s.closed:
raise newLPStreamClosedError()
await s.stream.write(move(msg))
method readOnce(
s: OptimisticStream, pbytes: pointer, nbytes: int
): Future[int] {.async: (raises: [CancelledError, LPStreamError]).} =
# close() is a half-close, so reads continue until the remote side ends.
if s.wasResetLocally():
raise newLPStreamClosedError()
if not s.confirmed:
try:
if s.confirmFut.isNil:
s.confirmFut = s.confirm()
await s.confirmFut
except CancelledError as exc:
await noCancel s.reset()
raise exc
except LPStreamError as exc:
await s.reset()
raise exc
await s.stream.readOnce(pbytes, nbytes)
proc selectOptimistic*(
_: MultistreamSelect | type MultistreamSelect,
stream: Stream,
proto: string,
closeTimeout = DefaultOptimisticCloseTimeout,
): Future[Stream] {.async: (raises: [CancelledError, LPStreamError]).} =
## Propose one nonempty protocol without waiting for acknowledgement.
## Both streams expose the proposed protocol before acknowledgement.
## Use only the returned stream thereafter. Writes may precede acceptance;
## the first read validates negotiation and resets the stream on rejection,
## malformed responses, EOF, or cancellation. There is no protocol fallback.
## An unacknowledged close waits up to `closeTimeout`, then resets.
## Cancellation also resets the stream.
## As with the underlying stream, concurrent reads are not supported.
doAssert proto.len > 0, "Optimistic selection requires a protocol"
try:
await stream.writeLp(Codec & "\n")
await stream.writeLp(proto & "\n")
except CancelledError as exc:
await noCancel stream.reset()
raise exc
except LPStreamError as exc:
await stream.reset()
raise exc
stream.protocol = proto
let selected = OptimisticStream(
stream: stream,
protocol: proto,
peerId: stream.peerId,
dir: stream.dir,
transportDir: stream.transportDir,
observedAddr: stream.observedAddr,
localAddr: stream.localAddr,
objName: "OptimisticStream",
closeTimeout: closeTimeout,
)
when defined(libp2p_agents_metrics):
selected.shortAgent = stream.shortAgent
selected.initStream()
return selected
proc trySelect*(
_: MultistreamSelect | type MultistreamSelect, stream: Stream, proto: seq[string]
): Future[MultiStreamResult[string]] {.
async: (raises: [CancelledError, LPStreamError])
.} =
## Returns "" when the remote supports none of `proto`.
trace "Multistream handshake started", stream, protocol = Codec
await stream.writeLp(Codec & "\n")
if proto.len() > 0:
trace "Protocol negotiation started", stream, protocol = proto[0]
await stream.writeLp(proto[0] & "\n")
let header = ?stream.readMessage()
if header != Codec:
trace "Multistream handshake failed", stream, protocol = header
return err(MultiStreamFailure.HandshakeFailed)
trace "Multistream handshake completed", stream
if proto.len() == 0:
return ok(Codec)
let response = ?stream.readMessage()
trace "Protocol negotiation response received", stream, protocol = response
if response == proto[0]:
trace "Protocol negotiation completed", stream, protocol = proto[0]
stream.protocol = proto[0]
return ok(proto[0])
if proto.len() > 1:
trace "Protocol alternatives available", stream, protocols = proto[1 .. ^1]
for p in proto.toOpenArray(1, proto.high):
trace "Protocol negotiation retrying", stream, protocol = p
await stream.writeLp(p & "\n")
let alternative = ?stream.readMessage()
if alternative == p:
trace "Protocol negotiation completed", stream, protocol = p
stream.protocol = p
return ok(p)
ok("")
proc select*(
_: MultistreamSelect | type MultistreamSelect, stream: Stream, proto: seq[string]
): Future[string] {.async: (raises: [CancelledError, LPStreamError, MultiStreamError]).} =
(await MultistreamSelect.trySelect(stream, proto)).valueOrRaise(MultiStreamError)
proc select*(
_: MultistreamSelect | type MultistreamSelect,
stream: Stream,
protos: seq[string],
preferredProto: Opt[string],
): Future[tuple[protocol: string, stream: Stream]] {.
async: (raises: [CancelledError, LPStreamError, MultiStreamError])
.} =
## Select optimistically when `preferredProto` is present, otherwise use
## blocking negotiation. The preferred protocol must belong to `protos`.
preferredProto.ifValue(proto):
doAssert proto in protos,
"Preferred protocol must be one of the requested protocols"
return (proto, await MultistreamSelect.selectOptimistic(stream, proto))
(await MultistreamSelect.select(stream, protos), stream)
proc select*(
_: MultistreamSelect | type MultistreamSelect, stream: Stream, proto: string
): Future[bool] {.async: (raises: [CancelledError, LPStreamError, MultiStreamError]).} =
if proto.len > 0:
(await MultistreamSelect.select(stream, @[proto])) == proto
else:
(await MultistreamSelect.select(stream, @[])) == Codec
proc select*(
m: MultistreamSelect, stream: Stream
): Future[bool] {.
async: (raises: [CancelledError, LPStreamError, MultiStreamError], raw: true)
.} =
m.select(stream, "")
proc list*(
m: MultistreamSelect, stream: Stream
): Future[seq[string]] {.
async: (raises: [CancelledError, LPStreamError, MultiStreamError])
.} =
## list remote protos requests on connection
if not await m.select(stream):
return
await stream.writeLp(Ls) # send ls
var list = newSeq[string]()
let ms = string.fromBytes(await stream.readLp(MsgSize))
for s in ms.split("\n"):
if s.len() > 0:
list.add(s)
list
proc tryHandleImpl(
_: type MultistreamSelect,
stream: Stream,
protos: seq[string],
accept: Matcher,
active: bool,
): Future[MultiStreamResult[string]] {.
async: (raises: [CancelledError, LPStreamError])
.} =
trace "Multistream negotiation started", stream, handshaked = active
var handshaked = active
while not stream.atEof:
let ms = ?stream.readMessage()
if not handshaked and ms != Codec:
trace "Multistream handshake rejected",
stream, receivedProtocol = ms, reason = "unexpected first message"
return err(MultiStreamFailure.InvalidFirstMessage)
trace "Protocol negotiation request received", stream, protocol = ms
case ms
of "ls":
trace "Protocol list requested", stream
# TODO #3584: LS may require a length prefix for each protocol.
await stream.writeLp(protos.join("\n") & "\n")
of Codec:
if not handshaked:
await stream.writeLp(Codec & "\n")
handshaked = true
else:
trace "Duplicate multistream handshake rejected", stream
await stream.writeLp(Na)
elif ms.len > 0 and accept(ms):
trace "Protocol handler selected", stream, protocol = ms
await stream.writeLp(ms & "\n")
stream.protocol = ms
return ok(ms)
else:
trace "Protocol negotiation rejected",
stream, protocol = ms, reason = "no available handler"
await stream.writeLp(Na)
ok("")
proc tryHandle*(
_: type MultistreamSelect,
stream: Stream,
protos: seq[string],
matchers = newSeq[Matcher](),
active: bool = false,
): Future[MultiStreamResult[string]] {.
async: (raises: [CancelledError, LPStreamError], raw: true)
.} =
## Returns "" when the stream reaches EOF before a proposal matches.
proc matches(proto: string): bool {.gcsafe, raises: [].} =
proto in protos or matchers.anyIt(it(proto))
MultistreamSelect.tryHandleImpl(stream, protos, matches, active)
proc handle*(
_: type MultistreamSelect,
stream: Stream,
protos: seq[string],
matchers = newSeq[Matcher](),
active: bool = false,
): Future[string] {.async: (raises: [CancelledError, LPStreamError, MultiStreamError]).} =
(await MultistreamSelect.tryHandle(stream, protos, matchers, active)).valueOrRaise(
MultiStreamError
)
proc lookupProtocol*(m: MultistreamSelect, proto: string): Opt[LPProtocol] =
## Find the LPProtocol registered for the given protocol string, if any.
## Returns `Opt.none` when no handler matches.
for h in m.handlers:
if (h.match != nil and h.match(proto)) or h.protos.contains(proto):
return Opt.some(h.protocol)
return Opt.none(LPProtocol)
proc handle*(
m: MultistreamSelect, stream: Stream, active: bool = false
) {.async: (raises: [CancelledError]).} =
## Negotiates and awaits the selected protocol handler, then closes `stream`,
## including on cancellation. The handler owns any protocol-specific shutdown;
## this cleanup does not wait for peer EOF on half-closed streams.
trace "Multistream handler started", stream, handshaked = active
defer:
trace "Multistream handler stopped", stream
await noCancel stream.close()
var admitted: LPProtocol
proc admit(proto: string): bool {.gcsafe, raises: [].} =
m.lookupProtocol(proto).ifValue(p):
if p.reserveIncoming(stream.peerId):
admitted = p
return true
debug "Inbound stream budget exceeded, rejecting incoming stream",
stream, protocol = proto, peerId = stream.peerId
false
defer:
if admitted != nil:
admitted.releaseIncoming(stream.peerId)
let negotiated =
try:
let protos = m.handlers.mapIt(it.protos).concat()
await MultistreamSelect.tryHandleImpl(stream, protos, admit, active)
except LPStreamError as e:
trace "Multistream negotiation failed", err = e.msg, stream
return
let ms = negotiated.valueOr:
trace "Multistream negotiation failed", err = error, stream
return
if admitted != nil:
let h = admitted.handler
await h(stream, ms)
proc addHandler*(m: MultistreamSelect, protocol: LPProtocol, matcher: Matcher = nil) =
trace "Protocol handlers registered", protocols = protocol.codecs
m.handlers.add(
HandlerHolder(protos: protocol.codecs, protocol: protocol, match: matcher)
)
proc removeHandler*(m: MultistreamSelect, protocol: LPProtocol): bool =
## Removes the handler registered for `protocol`.
for i, handler in m.handlers:
if handler.protocol == protocol:
m.handlers.del(i)
return true
false
proc addHandler*[E](
m: MultistreamSelect,
codec: string,
handler:
LPProtoHandler | proc(
stream: Stream, proto: string
): InternalRaisesFuture[void, E],
matcher: Matcher = nil,
) =
## helper to allow registering pure handlers
let protocol = new LPProtocol
protocol.codec = codec
protocol.handler = handler
m.addHandler(protocol, matcher)
proc start*(m: MultistreamSelect) {.async: (raises: [CancelledError]).} =
let futs = m.handlers.mapIt(it.protocol.start())
try:
await allFutures(futs)
for fut in futs:
await fut
except CancelledError as exc:
var pending: seq[Future[void].Raising([])]
doAssert m.handlers.len == futs.len, "Handlers modified while starting"
for i, fut in futs:
if not fut.finished:
pending.add fut.cancelAndWait()
elif fut.completed:
pending.add m.handlers[i].protocol.stop()
else:
static:
doAssert typeof(fut).E is (CancelledError,)
await noCancel allFutures(pending)
raise exc
proc stop*(m: MultistreamSelect) {.async: (raises: []).} =
let futs = m.handlers.mapIt(it.protocol.stop())
await noCancel allFutures(futs)
for fut in futs:
await fut