Skip to content
Closed
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
125 changes: 125 additions & 0 deletions Tests/MixerLinkTests/DiagnosticsTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
#if canImport(Network)
import Foundation
import MixerLink
import Network
import Synchronization
import Testing

// DIAGNOSTICS ONLY (ShowRecorder #1248): never merge. Does a flow that a listener never closed make a later listener
// on that flow's remote port unreachable?

enum Diag {
static func log(_ text: String) {
fputs("[diag] \(text)\n", stderr)
}
}

/// A loopback UDP listener that answers every datagram and, like the fakes, keeps the flows it accepted.
final class DiagEcho: Sendable {
let listener: NWListener
let port: UInt16
let seen: Seen

final class Seen: Sendable {
let flows = Mutex<[NWConnection]>([])
let heard = Mutex(0)
let replied = Mutex(false)
}

init(listener: NWListener, port: UInt16, seen: Seen) {
self.listener = listener
self.port = port
self.seen = seen
}

static func listen(on port: NWEndpoint.Port = .any) async throws -> (echo: DiagEcho, tries: Int) {
for attempt in 1...200 {
let parameters = NWParameters.udp
parameters.requiredLocalEndpoint = .hostPort(host: "127.0.0.1", port: port)
let listener = try NWListener(using: parameters)
let seen = Seen()
let started = AsyncStream<UInt16?>.makeStream()
listener.stateUpdateHandler = { [listener] update in
switch update {
case .ready: started.continuation.yield(listener.port?.rawValue)
case .failed, .waiting: started.continuation.yield(nil)
default: break
}
}
listener.newConnectionHandler = { connection in
seen.flows.withLock { $0.append(connection) }
connection.start(queue: .global())
@Sendable func serve() {
connection.receiveMessage { data, _, _, error in
guard error == nil, let data else { return }
seen.heard.withLock { $0 += 1 }
connection.send(content: data, completion: .contentProcessed { _ in })
serve()
}
}
serve()
}
listener.start(queue: .global())
var iterator = started.stream.makeAsyncIterator()
if let found = await iterator.next(), let found {
return (DiagEcho(listener: listener, port: found, seen: seen), attempt)
}
listener.cancel()
try await Task.sleep(for: .milliseconds(25))
}
throw CancellationError()
}

func closeFlows() {
seen.flows.withLock { for flow in $0 { flow.cancel() }; $0 = [] }
}

/// Sends one datagram to `port` from a new connection and reports what became of it.
static func ask(_ port: UInt16, sends: Bool = true) async throws -> (state: String, local: UInt16, replied: Bool) {
let connection = NWConnection(host: "127.0.0.1", port: NWEndpoint.Port(rawValue: port)!, using: .udp)
let seen = Seen()
connection.start(queue: .global())
connection.receiveMessage { data, _, _, _ in
if data != nil { seen.replied.withLock { $0 = true } }
}
if sends { connection.send(content: Data("ping".utf8), completion: .contentProcessed { _ in }) }
try await Task.sleep(for: .milliseconds(600))
var local: UInt16 = 0
if case .hostPort(_, let found)? = connection.currentPath?.localEndpoint { local = found.rawValue }
let state = "\(connection.state)"
connection.cancel()
return (state, local, seen.replied.withLock { $0 })
}
}

@Suite("Diagnostics: leaked flow")
struct LeakedFlowTests {
static let variants = ["firstClosed", "firstClientSilent", "probeSilent", "waits5s"]

@Test("A listener on a port that a client of another listener used", arguments: 0..<12)
func leakedFlow(_ copy: Int) async throws {
let variant = Self.variants[copy % 4]
let (first, _) = try await DiagEcho.listen()
let before = try await DiagEcho.ask(first.port, sends: variant != "firstClientSilent")
if variant == "firstClosed" {
first.closeFlows()
first.listener.cancel()
try await Task.sleep(for: .milliseconds(500))
}
let (second, tries) = try await DiagEcho.listen(on: NWEndpoint.Port(rawValue: before.local)!)
if variant == "waits5s" { try await Task.sleep(for: .seconds(5)) }
let during = try await DiagEcho.ask(second.port, sends: variant != "probeSilent")
let again = try await DiagEcho.ask(second.port)
// What the fix would do: listen somewhere else.
let (third, _) = try await DiagEcho.listen()
let moved = try await DiagEcho.ask(third.port)
Diag.log("leak3[\(copy)] \(variant) first=\(first.port) second=\(second.port) third=\(third.port) listenTries=\(tries) before=\(before) during=\(during) again=\(again) moved=\(moved) heard=\(second.seen.heard.withLock { $0 })")
first.listener.cancel()
second.listener.cancel()
third.listener.cancel()
first.closeFlows()
second.closeFlows()
third.closeFlows()
}
}
#endif
Loading