Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: avoid finishing write futures while stream is being closed #1032

Draft
wants to merge 2 commits into
base: master
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 12 additions & 5 deletions libp2p/muxers/mplex/lpchannel.nim
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ type
closeCode*: MessageType # cached in/out close code
resetCode*: MessageType # cached in/out reset code
writes*: int # In-flight writes
closing: Future[void]

func shortLog*(s: LPChannel): auto =
try:
Expand Down Expand Up @@ -99,7 +100,7 @@ proc reset*(s: LPChannel) {.async.} =
if s.isClosed:
trace "Already closed", s
return

s.closing = newFuture[void]()
s.isClosed = true
s.closedLocal = true
s.localReset = not s.remoteReset
Expand All @@ -120,7 +121,8 @@ proc reset*(s: LPChannel) {.async.} =
asyncSpawn resetMessage()

await s.closeImpl() # noraises, nocancels

if not s.closing.finished:
s.closing.complete()
trace "Channel reset", s

method close*(s: LPChannel) {.async.} =
Expand All @@ -130,6 +132,8 @@ method close*(s: LPChannel) {.async.} =
if s.closedLocal:
trace "Already closed", s
return

s.closing = newFuture[void]()
s.closedLocal = true

trace "Closing channel", s, conn = s.conn, len = s.len
Expand All @@ -147,7 +151,8 @@ method close*(s: LPChannel) {.async.} =
trace "Cannot send close message", s, id = s.id, msg = exc.msg

await s.closeUnderlying() # maybe already eofed

if not s.closing.finished:
s.closing.complete()
trace "Closed channel", s, len = s.len

method initStream*(s: LPChannel) =
Expand Down Expand Up @@ -200,6 +205,7 @@ proc prepareWrite(s: LPChannel, msg: seq[byte]): Future[void] {.async.} =
if s.remoteReset:
raise newLPStreamResetError()
if s.closedLocal:
await s.closing
raise newLPStreamClosedError()
if s.conn.closed:
raise newLPStreamConnDownError()
Expand Down Expand Up @@ -293,8 +299,9 @@ proc init*(
msgCode: if initiator: MessageType.MsgOut else: MessageType.MsgIn,
closeCode: if initiator: MessageType.CloseOut else: MessageType.CloseIn,
resetCode: if initiator: MessageType.ResetOut else: MessageType.ResetIn,
dir: if initiator: Direction.Out else: Direction.In)

dir: if initiator: Direction.Out else: Direction.In,
closing: newFuture[void]())
chann.closing.complete()
chann.initStream()

when chronicles.enabledLogLevel == LogLevel.TRACE:
Expand Down
Loading