diff --git a/Tests/MixerLinkTests/LoopbackListenTests.swift b/Tests/MixerLinkTests/LoopbackListenTests.swift new file mode 100644 index 0000000..936b52b --- /dev/null +++ b/Tests/MixerLinkTests/LoopbackListenTests.swift @@ -0,0 +1,61 @@ +#if canImport(Network) +import Foundation +import Network +import Testing + +/// The listener every fake Mixer stands on. +@Suite("Loopback listener") +struct LoopbackListenTests { + /// macOS can hand a new fake Mixer a port that a client used a moment ago. Nothing then gets through to it: the + /// Mixer answered its knock on one port and never heard a query on the other, and the Link stayed down for as long + /// as the test waited (ShowRecorder #1248). + @Test("A listener asked onto a port that a client just used moves to a port that can be reached") + func movesOffAnUnreachablePort() async throws { + let (other, otherPort) = try await Loopback.listen { Self.echo($0) } + defer { other.cancel() } + // After this exchange every new connection to `used` gets `otherPort` as its local port, which is taken. + let used = try #require(await Self.ask(otherPort)) + + let (listener, port) = try await Loopback.listen(on: NWEndpoint.Port(rawValue: used)!) { Self.echo($0) } + defer { listener.cancel() } + + #expect(await Self.ask(port) != nil) + #expect(await Self.ask(port) != nil) + } + + /// Answers every datagram with itself. + private static func echo(_ connection: NWConnection) { + connection.receiveMessage { data, _, _, error in + guard error == nil, let data else { return } + connection.send(content: data, completion: .contentProcessed { _ in }) + echo(connection) + } + } + + /// Sends one datagram to `port` from a new connection. Returns the local port that connection used once the + /// answer is back, or nil when the connection can't get through. + private static func ask(_ port: UInt16) async -> UInt16? { + let connection = NWConnection(host: "127.0.0.1", port: NWEndpoint.Port(rawValue: port)!, using: .udp) + defer { connection.cancel() } + let answers = AsyncStream.makeStream() + connection.stateUpdateHandler = { state in + switch state { + case .waiting, .failed: answers.continuation.yield(false) + default: break + } + } + connection.start(queue: .global()) + connection.receiveMessage { data, _, _, _ in answers.continuation.yield(data != nil) } + connection.send(content: Data("ping".utf8), completion: .contentProcessed { _ in }) + let giveUp = Task { + try await Task.sleep(for: Loopback.replyTimeout) + answers.continuation.yield(false) + } + defer { giveUp.cancel() } + var iterator = answers.stream.makeAsyncIterator() + guard await iterator.next() == true else { return nil } + guard case .hostPort(_, let local)? = connection.currentPath?.localEndpoint else { return nil } + return local.rawValue + } +} +#endif diff --git a/Tests/MixerLinkTests/Support/FakeTextMixer.swift b/Tests/MixerLinkTests/Support/FakeTextMixer.swift index 62723a3..e0eed57 100644 --- a/Tests/MixerLinkTests/Support/FakeTextMixer.swift +++ b/Tests/MixerLinkTests/Support/FakeTextMixer.swift @@ -17,20 +17,8 @@ final class FakeTextMixer: Sendable { var requests: [String] { log.requests.withLock { $0 } } init(answering request: String, with reply: String) async throws { - let parameters = NWParameters.udp - parameters.requiredLocalEndpoint = .hostPort(host: "127.0.0.1", port: .any) - let listener = try NWListener(using: parameters) - let ready = AsyncStream.makeStream() - listener.stateUpdateHandler = { [listener] update in - switch update { - case .ready: if let port = listener.port?.rawValue { ready.continuation.yield(port) } - case .failed: ready.continuation.finish() - default: break - } - } let log = log - listener.newConnectionHandler = { connection in - connection.start(queue: .global()) + let (listener, port) = try await Loopback.listen { connection in @Sendable func serve() { connection.receiveMessage { data, _, _, error in guard error == nil, let data else { return } @@ -42,10 +30,7 @@ final class FakeTextMixer: Sendable { } serve() } - listener.start(queue: .global()) - var iterator = ready.stream.makeAsyncIterator() self.listener = listener - guard let port = await iterator.next() else { throw CancellationError() } self.port = port } diff --git a/Tests/MixerLinkTests/Support/FakeWing.swift b/Tests/MixerLinkTests/Support/FakeWing.swift index ceef034..3866247 100644 --- a/Tests/MixerLinkTests/Support/FakeWing.swift +++ b/Tests/MixerLinkTests/Support/FakeWing.swift @@ -117,19 +117,7 @@ final class FakeWing: Sendable { private static func listen( deliver: @escaping @Sendable (@escaping @Sendable () -> Void) -> Void = { $0() }, answer: @escaping @Sendable (Data) -> Data? ) async throws -> (NWListener, UInt16) { - let parameters = NWParameters.udp - parameters.requiredLocalEndpoint = .hostPort(host: "127.0.0.1", port: .any) - let listener = try NWListener(using: parameters) - let ready = AsyncStream.makeStream() - listener.stateUpdateHandler = { [listener] update in - switch update { - case .ready: if let port = listener.port?.rawValue { ready.continuation.yield(port) } - case .failed: ready.continuation.finish() - default: break - } - } - listener.newConnectionHandler = { connection in - connection.start(queue: .global()) + try await Loopback.listen { connection in @Sendable func serve() { connection.receiveMessage { data, _, _, error in guard error == nil, let data else { return } @@ -141,10 +129,6 @@ final class FakeWing: Sendable { } serve() } - listener.start(queue: .global()) - var iterator = ready.stream.makeAsyncIterator() - guard let port = await iterator.next() else { throw CancellationError() } - return (listener, port) } } #endif diff --git a/Tests/MixerLinkTests/Support/FakeXAirMixer.swift b/Tests/MixerLinkTests/Support/FakeXAirMixer.swift index 93dba8b..1df3656 100644 --- a/Tests/MixerLinkTests/Support/FakeXAirMixer.swift +++ b/Tests/MixerLinkTests/Support/FakeXAirMixer.swift @@ -116,46 +116,12 @@ final class FakeXAirMixer: Sendable { deinit { listener.withLock { $0?.cancel() } } - /// Opens a loopback UDP listener on `port` that answers with `responder`, and returns it with its port. - /// - /// A listen that fails is tried again. Right after `powerOff()`, with a Link still asking, the port is often still - /// taken (EADDRINUSE) for a moment; this used to wait for a `.ready` that never came, which hung the whole test run - /// (ShowRecorder #1215). + /// Opens a loopback UDP listener on `port` that answers with `responder`, and returns it with its port. A Mixer + /// switched on again keeps its port; a new one takes any port that can be reached. private static func listen(on port: NWEndpoint.Port, responder: Responder) async throws -> (NWListener, UInt16) { - var failure: NWError? - for _ in 0..>.makeStream() - listener.stateUpdateHandler = { [listener] update in - switch update { - case .ready: if let port = listener.port?.rawValue { started.continuation.yield(.success(port)) } - case .failed(let error), .waiting(let error): started.continuation.yield(.failure(error)) - default: break - } - } - listener.newConnectionHandler = { connection in - connection.start(queue: .global()) - responder.serve(connection) - } - listener.start(queue: .global()) - var iterator = started.stream.makeAsyncIterator() - switch await iterator.next() { - case .success(let port)?: return (listener, port) - case .failure(let error)?: failure = error - case nil: break // the test was canceled - } - listener.cancel() - try await Task.sleep(for: .milliseconds(25)) - } - throw failure ?? NWError.posix(.ETIMEDOUT) + try await Loopback.listen(on: port, keepsPort: port != .any, reusesPort: true) { responder.serve($0) } } - /// How many times a listen is tried, 25 ms apart: 10 s in all. One more try was enough in every run seen. - private static let listenTries = 400 - /// Switches the Mixer off, as a power cycle does: nothing listens on its port any more. (On loopback macOS doesn't /// report the bounce to the Link's connection, so this doesn't make it fail; `OSCUDPClientRecoveryTests` covers that.) func powerOff() { diff --git a/Tests/MixerLinkTests/Support/Loopback.swift b/Tests/MixerLinkTests/Support/Loopback.swift index 66c9c9a..2bf2e72 100644 --- a/Tests/MixerLinkTests/Support/Loopback.swift +++ b/Tests/MixerLinkTests/Support/Loopback.swift @@ -7,3 +7,87 @@ enum Loopback { /// busy Mac's answer, short enough that the silence costs little. static let mixedTimeout: Duration = .seconds(3) } + +#if canImport(Network) +import Foundation +import Network + +extension Loopback { + /// Opens a loopback UDP listener on `requested` and hands every connection it accepts, already started, to `serve`. + /// Returns the listener with its port. + /// + /// A listen that fails is tried again: right after a fake Mixer's power-off, with a Link still asking, its port is + /// often still taken (EADDRINUSE) for a moment, and waiting for a `.ready` that never came hung the whole test run + /// (ShowRecorder #1215). + /// + /// A listener that nothing can reach moves to another port, unless `keepsPort`. macOS can hand a new listener a + /// port that a client used a moment ago to talk to another listener in this process. Every new connection to such + /// a port then waits on EADDRINUSE, for as long as was measured, so a fake Mixer there never hears its driver + /// (ShowRecorder #1248). + static func listen( + on requested: NWEndpoint.Port = .any, keepsPort: Bool = false, reusesPort: Bool = false, + serve: @escaping @Sendable (NWConnection) -> Void + ) async throws -> (NWListener, UInt16) { + var port = requested + var failure: NWError? + for _ in 0..>.makeStream() + listener.stateUpdateHandler = { [listener] update in + switch update { + case .ready: if let port = listener.port?.rawValue { started.continuation.yield(.success(port)) } + case .failed(let error), .waiting(let error): started.continuation.yield(.failure(error)) + default: break + } + } + listener.newConnectionHandler = { connection in + connection.start(queue: .global()) + serve(connection) + } + listener.start(queue: .global()) + var iterator = started.stream.makeAsyncIterator() + switch await iterator.next() { + case .success(let found)?: + if keepsPort || !keepsPort { return (listener, found) } // DIAGNOSTICS: check off + if await isReachable(found) { return (listener, found) } + port = .any + case .failure(let error)?: failure = error + case nil: break // the test was canceled + } + listener.cancel() + try await Task.sleep(for: .milliseconds(25)) + } + throw failure ?? NWError.posix(.ETIMEDOUT) + } + + /// How many times a listen is tried, 25 ms apart: 10 s in all. One more try was enough in every run seen. + private static let listenTries = 400 + + /// Whether two new connections at once get through to the loopback UDP `port`. Nothing is sent, so the listener + /// there sees neither. On a port that can't be reached, macOS gives every connection the same local port: the + /// first waits on EADDRINUSE while that port is taken, and the second does when the first holds it. + static func isReachable(_ port: UInt16) async -> Bool { + let connections = (0..<2).map { _ in + NWConnection(host: "127.0.0.1", port: NWEndpoint.Port(rawValue: port)!, using: .udp) + } + defer { for connection in connections { connection.cancel() } } + for connection in connections { + let states = AsyncStream.makeStream() + connection.stateUpdateHandler = { state in + switch state { + case .ready: states.continuation.yield(true) + case .waiting, .failed, .cancelled: states.continuation.yield(false) + default: break + } + } + connection.start(queue: .global()) + var iterator = states.stream.makeAsyncIterator() + guard await iterator.next() == true else { return false } + } + return true + } +} +#endif