Skip to content
Merged
Show file tree
Hide file tree
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
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 (#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<Bool>.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
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,12 @@ struct MixerLinkEndToEndTests {
state.channels[0] = .init(name: "Kick", color: 1)
state.usbRouting = XAirDriverTests.defaultRouting // answered, so no read waits out its timeout
let mixer = try await FakeXAirMixer(state)
// Connecting asks the Mixer about 100 things one after another; each must answer in time even on a busy Mac,
// or the Link never comes up and every wait below runs out (#464). Noticing the power-off takes one timeout.
// Connecting asks the Mixer about 100 things one after another, and on a busy Mac one answer can come after the
// timeout (#464): that connect fails and the Link keeps trying (#1209). So wait for the Link to come up rather
// than check at once (#1215). Noticing the power-off takes one timeout.
let link = MixerLinkController(timeout: Loopback.mixedTimeout, renewEvery: .milliseconds(100))
await link.connect(to: "127.0.0.1:\(mixer.port)", usbChannelCount: 18)
#expect(link.sources[safe: 0]?.name == "Kick")
#expect(await eventually(30) { link.sources[safe: 0]?.name == "Kick" }, "\(link.status)")

mixer.powerOff()
#expect(await eventually(30) { if case .down = link.status { true } else { false } })
Expand All @@ -28,4 +29,26 @@ struct MixerLinkEndToEndTests {
mixer.rename(channel: 2, to: "Snare")
#expect(await eventually(30) { link.sources[safe: 1]?.name == "Snare" })
}

/// With the Link already down at power-off, nothing waits between the power-off and the power-on, as when the
/// connect failed on a busy CI runner. The fake's first try to listen on its port again then often fails
/// (EADDRINUSE); it used to wait forever for that listener, and the package tests ran into their 40-minute limit
/// (#1215).
@Test("Switched off and on again at once while the Link keeps trying, the Mixer answers again and the Link comes up")
func powerCycleAtOnce() async throws {
var state = FakeXAirMixer.State()
state.channels[0] = .init(name: "Kick", color: 1)
state.usbRouting = XAirDriverTests.defaultRouting
state.answers = false // the connect fails, and the Link keeps trying (#1209)
let mixer = try await FakeXAirMixer(state)
let link = MixerLinkController(timeout: .seconds(1), renewEvery: .milliseconds(100))
await link.connect(to: "127.0.0.1:\(mixer.port)", usbChannelCount: 18)
#expect(await eventually(30) { if case .down = link.status { true } else { false } })

mixer.powerOff()
mixer.update { $0.answers = true }
try await mixer.powerOn()

#expect(await eventually(30) { link.sources[safe: 0]?.name == "Kick" }, "\(link.status)")
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,20 +16,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<UInt16>.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 }
Expand All @@ -41,10 +29,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
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -116,19 +116,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<UInt16>.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 }
Expand All @@ -140,9 +128,5 @@ 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)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -113,23 +113,10 @@ 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.
/// 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) {
let parameters = NWParameters.udp
parameters.requiredLocalEndpoint = .hostPort(host: "127.0.0.1", port: port)
parameters.allowLocalEndpointReuse = true
let listener = try NWListener(using: parameters)
let ready = AsyncStream<UInt16>.makeStream()
listener.stateUpdateHandler = { [listener] update in
if case .ready = update, let port = listener.port?.rawValue { ready.continuation.yield(port) }
}
listener.newConnectionHandler = { connection in
connection.start(queue: .global())
responder.serve(connection)
}
listener.start(queue: .global())
var iterator = ready.stream.makeAsyncIterator()
return (listener, await iterator.next() ?? 0)
try await Loopback.listen(on: port, keepsPort: port != .any, reusesPort: true) { responder.serve($0) }
}

/// Switches the Mixer off, as a power cycle does: nothing listens on its port any more. (On loopback macOS doesn't
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
import Foundation
import Network

/// Timing for tests that talk to a fake Mixer over loopback UDP (#462). The fake always answers, so a generous reply
/// timeout costs nothing when the Mac is idle and stops a busy Mac (several sessions building at once) from turning a
/// slow answer into `.noReply`. Production keeps its own 1–1.5 s; tests that wait on silence keep short ones.
Expand All @@ -7,3 +10,82 @@ enum Loopback {
/// busy Mac's answer, short enough that the silence costs little.
static let mixedTimeout: Duration = .seconds(3)
}

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
/// (#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
/// (#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..<listenTries {
let parameters = NWParameters.udp
parameters.requiredLocalEndpoint = .hostPort(host: "127.0.0.1", port: port)
parameters.allowLocalEndpointReuse = reusesPort
let listener = try NWListener(using: parameters)
let started = AsyncStream<Result<UInt16, NWError>>.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 { return (listener, found) }
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<Bool>.makeStream()
connection.stateUpdateHandler = { state in
switch state {
case .ready: states.continuation.yield(true)
case .waiting, .failed: 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
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -102,18 +102,19 @@ struct XAirDriverTests {
var state = FakeXAirMixer.State()
state.channels[0] = .init(name: "Kick", color: 1)
state.answersMixState = false
state.usbRouting = Self.defaultRouting // answered, so the only silence is the mix state (#462)
let mixer = try await FakeXAirMixer(state)
// A 1 s timeout, so a loaded machine can still answer the names (#323); missing mix state still costs one
// timeout (under 3 s), not one per Source (18 s).
let driver = XAirDriver(endpoint: MixerEndpoint(host: "127.0.0.1", port: mixer.port), timeout: .seconds(1))
// The one unanswered query waits out this timeout; every other query is answered, however busy the machine.
let driver = XAirDriver(endpoint: MixerEndpoint(host: "127.0.0.1", port: mixer.port), timeout: Loopback.mixedTimeout)

let clock = ContinuousClock()
var sources: [Source] = []
let elapsed = try await clock.measure { sources = try await driver.sources(usbChannelCount: 18) }
let sources = try await driver.sources(usbChannelCount: 18)

#expect(try #require(sources.first).name == "Kick")
#expect(sources.allSatisfy { $0.isMuted == nil && $0.fader == nil && $0.inputSource == nil })
#expect(elapsed < .seconds(3), "one timeout, not one per Source")
// Counted, not timed: a clock limit failed on a busy CI runner with nothing wrong (#1249). Each
// unanswered query costs one timeout, so one mix-state query asked is one timeout, not one per Source.
let mixStateQueries = mixer.queries.filter { $0.contains("/mix/") || $0.hasSuffix("/config/insrc") }
#expect(mixStateQueries == ["/ch/01/mix/on"], "asked once, then skipped for the other 17 Sources")
}

@Test("An unexpected reply for mute, fader or input source leaves that value unknown, not the Link down")
Expand Down
Loading