diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6d83a2d..f63fe47 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -34,6 +34,7 @@ jobs: run: | xcodebuild -version swift --version + echo "ulimit -n: $(ulimit -n) hard: $(ulimit -Hn)"; sysctl hw.ncpu kern.maxfilesperproc; launchctl limit maxfiles || true # Until the shared modules move in (#3) the repo holds no package, and there is nothing to test. - name: Package tests diff --git a/Sources/MixerLink/OSCUDPClient.swift b/Sources/MixerLink/OSCUDPClient.swift index ea1cb79..60aa50f 100644 --- a/Sources/MixerLink/OSCUDPClient.swift +++ b/Sources/MixerLink/OSCUDPClient.swift @@ -2,6 +2,7 @@ import Foundation import Network import OSC +import Synchronization /// Sends OSC queries over UDP and matches replies to them by address. actor OSCUDPClient { @@ -68,6 +69,7 @@ actor OSCUDPClient { pending.append(Pending(id: id, address: replyAddress ?? message.address, continuation: continuation)) let connection = connection connection.send(content: Data(message.encoded()), completion: .contentProcessed { [weak self] error in + self?.diagNote("sent \(message.address) error=\(String(describing: error))") guard let error, let self else { return } // With the path, a send refused for Local Network access says so, not "join the Wi-Fi". let problem = MixerLinkProblem(error, path: connection.currentPath, host: self.endpoint.host, port: self.endpoint.port) @@ -97,6 +99,7 @@ actor OSCUDPClient { let connection = connection, generation = generation connection.stateUpdateHandler = { [weak self] state in guard let self else { return } + self.diagNote("state \(state) gen=\(generation) local=\(String(describing: connection.currentPath?.localEndpoint))") switch state { case .waiting(let error): // Waiting recovers by itself (the network comes back); fail requests meanwhile. @@ -117,6 +120,7 @@ actor OSCUDPClient { private nonisolated func receive(on connection: NWConnection, generation: Int) { connection.receiveMessage { [weak self] data, _, _, error in guard let self else { return } + self.diagNote("receive data=\(data?.count ?? -1) error=\(String(describing: error))") if let data, let packet = try? OSCPacket(decoding: Array(data)) { self.received.yield(packet.messages) } @@ -139,7 +143,14 @@ actor OSCUDPClient { problem = nil } + private nonisolated let diagTrace = Mutex<[String]>([]) + private nonisolated let diagStart = ContinuousClock.now + private nonisolated func diagNote(_ text: String) { + diagTrace.withLock { if $0.count < 40 { $0.append("\(ContinuousClock.now - diagStart) \(text)") } } + } + private func deliver(_ messages: [OSCMessage]) { + diagNote("deliver \(messages.map(\.address))") for message in messages { // An XR18 echoes each set back with no arguments: that's never the reply to a query. guard !message.arguments.isEmpty, let index = pending.firstIndex(where: { $0.address == message.address }) else { @@ -152,6 +163,7 @@ actor OSCUDPClient { private func fail(_ id: UUID, with problem: MixerLinkProblem) { guard let index = pending.firstIndex(where: { $0.id == id }) else { return } + fputs("[diag] osc fail port=\(endpoint.port) address=\(pending[index].address) problem=\(problem) state=\(connection.state) generation=\(generation) needsRebuild=\(needsRebuild) pending=\(pending.count) trace=\(diagTrace.withLock { $0 })\n", stderr) pending.remove(at: index).continuation.resume(throwing: problem) } diff --git a/Sources/MixerLink/WingDriver.swift b/Sources/MixerLink/WingDriver.swift index 5bc9eb6..5b1af8b 100644 --- a/Sources/MixerLink/WingDriver.swift +++ b/Sources/MixerLink/WingDriver.swift @@ -177,20 +177,34 @@ enum TextRequest { let finish: @Sendable ([UInt8]?) -> Void = { reply in waiting.withLock { $0.take() }?.resume(returning: reply) } + let trace = Mutex<[String]>([]) + let t0 = ContinuousClock.now + let note: @Sendable (String) -> Void = { text in trace.withLock { $0.append("\(ContinuousClock.now - t0) \(text)") } } + connection.stateUpdateHandler = { note("state \($0)") } let reply = await withTaskCancellationHandler { await withCheckedContinuation { (continuation: CheckedContinuation<[UInt8]?, Never>) in waiting.withLock { $0 = continuation } - connection.receiveMessage { data, _, _, _ in finish(data.map { Array($0) }) } + connection.receiveMessage { data, _, _, error in + note("receive data=\(data?.count ?? -1) error=\(String(describing: error))") + finish(data.map { Array($0) }) + } connection.start(queue: .global(qos: .userInitiated)) - connection.send(content: Data(request), completion: .contentProcessed { _ in }) + connection.send(content: Data(request), completion: .contentProcessed { note("sent error=\(String(describing: $0))") }) + note("started") Task { + note("timeout task began") try? await Task.sleep(for: timeout) + note("timeout") finish(nil) } } } onCancel: { + note("cancel") finish(nil) } + if reply == nil { + fputs("[diag] ask port=\(endpoint.port) timeout=\(timeout) nil after \(ContinuousClock.now - t0): \(trace.withLock { $0 })\n", stderr) + } guard let reply else { throw .noReply(host: endpoint.host) } return reply } diff --git a/Tests/MixerLinkTests/DiagnosticsTests.swift b/Tests/MixerLinkTests/DiagnosticsTests.swift new file mode 100644 index 0000000..78f3e2d --- /dev/null +++ b/Tests/MixerLinkTests/DiagnosticsTests.swift @@ -0,0 +1,116 @@ +#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 flows: Mutex<[NWConnection]> + let heard: Mutex + + init(listener: NWListener, port: UInt16, flows: Mutex<[NWConnection]>, heard: Mutex) { + self.listener = listener + self.port = port + self.flows = flows + self.heard = heard + } + + 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 flows = Mutex<[NWConnection]>([]) + let heard = Mutex(0) + let started = AsyncStream.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 + flows.withLock { $0.append(connection) } + connection.start(queue: .global()) + @Sendable func serve() { + connection.receiveMessage { data, _, _, error in + guard error == nil, let data else { return } + 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, flows: flows, heard: heard), attempt) + } + listener.cancel() + try await Task.sleep(for: .milliseconds(25)) + } + throw CancellationError() + } + + func closeFlows() { + 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) async throws -> (state: String, local: UInt16, replied: Bool) { + let connection = NWConnection(host: "127.0.0.1", port: NWEndpoint.Port(rawValue: port)!, using: .udp) + let replied = Mutex(false) + connection.start(queue: .global()) + connection.receiveMessage { data, _, _, _ in + if data != nil { replied.withLock { $0 = true } } + } + 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, replied.withLock { $0 }) + } +} + +@Suite("Diagnostics: leaked flow") +struct LeakedFlowTests { + @Test("A listener on a port that an unclosed flow elsewhere still names as its remote", arguments: 0..<12) + func leakedFlow(_ copy: Int) async throws { + let leaks = copy % 2 == 0 + let (first, _) = try await DiagEcho.listen() + let before = try await DiagEcho.ask(first.port) // its client is closed; `first` keeps the flow, as the fakes do + if !leaks { + first.closeFlows() + try await Task.sleep(for: .milliseconds(300)) + } + // A later fake is given the port that client used. + let (second, tries) = try await DiagEcho.listen(on: NWEndpoint.Port(rawValue: before.local)!) + let during = try await DiagEcho.ask(second.port) + let heardDuring = second.heard.withLock { $0 } + first.closeFlows() + try await Task.sleep(for: .milliseconds(300)) + let after = try await DiagEcho.ask(second.port) + Diag.log("leakedFlow[\(copy)] leaks=\(leaks) first=\(first.port) second=\(second.port) listenTries=\(tries) before=\(before) during=\(during) heardDuring=\(heardDuring) afterClosingFlows=\(after) heardAfter=\(second.heard.withLock { $0 })") + first.listener.cancel() + second.listener.cancel() + second.closeFlows() + } +} +#endif diff --git a/Tests/MixerLinkTests/Support/FakeWing.swift b/Tests/MixerLinkTests/Support/FakeWing.swift index ceef034..ae4aeaf 100644 --- a/Tests/MixerLinkTests/Support/FakeWing.swift +++ b/Tests/MixerLinkTests/Support/FakeWing.swift @@ -20,6 +20,8 @@ final class FakeWing: Sendable { var answersOSC = true /// Knocks still to go unanswered, as on a starved CI runner where the answer comes after the wait (#1223). var unansweredKnocks = 0 + /// DIAGNOSTICS: seconds each knock reply is held before it is sent. + var knockReplyDelay: TimeInterval = 0 /// OSC replies still to drop: each query is logged but gets no answer (#1223). var droppedOSCReplies = 0 } @@ -52,7 +54,10 @@ final class FakeWing: Sendable { init(_ initial: State = State()) async throws { let box = Box(initial) self.box = box - let (knock, port) = try await Self.listen { data in + let (knock, port) = try await Self.listen(deliver: { send in + let delay = box.state.withLock { $0.knockReplyDelay } + if delay > 0 { DispatchQueue.global().asyncAfter(deadline: .now() + delay) { send() } } else { send() } + }) { data in let text = String(decoding: data, as: UTF8.self) return box.state.withLock { state in state.queries.append(text) @@ -127,11 +132,16 @@ final class FakeWing: Sendable { case .failed: ready.continuation.finish() default: break } + if case .ready = update {} else { fputs("[diag] WING listener \(String(describing: listener.port)): \(update)\n", stderr) } } - listener.newConnectionHandler = { connection in + listener.newConnectionHandler = { [listener] connection in + let port = listener.port?.rawValue ?? 0 + DiagFlows.note(port, "new \(connection.endpoint)") + connection.stateUpdateHandler = { DiagFlows.note(port, "state \(connection.endpoint) \($0)") } connection.start(queue: .global()) @Sendable func serve() { connection.receiveMessage { data, _, _, error in + DiagFlows.note(port, "recv \(connection.endpoint) data=\(data?.count ?? -1) error=\(String(describing: error))") guard error == nil, let data else { return } if let reply = answer(data) { deliver { connection.send(content: reply, completion: .contentProcessed { _ in }) } @@ -147,4 +157,17 @@ final class FakeWing: Sendable { return (listener, port) } } + +/// DIAGNOSTICS: what each fake WING listener saw, by its port. +enum DiagFlows { + static let all = Mutex<[UInt16: [String]]>([:]) + static let start = ContinuousClock.now + static func note(_ port: UInt16, _ text: String) { + all.withLock { $0[port, default: []].append("\(ContinuousClock.now - start) \(text)") } + } + static func dump(_ port: UInt16, containing text: String) -> [String] { + all.withLock { ($0[port] ?? []).filter { $0.contains(text) } } + } + static func count(_ port: UInt16) -> Int { all.withLock { $0[port]?.count ?? 0 } } +} #endif diff --git a/Tests/MixerLinkTests/Support/FakeXAirMixer.swift b/Tests/MixerLinkTests/Support/FakeXAirMixer.swift index 4291d79..70e7ea4 100644 --- a/Tests/MixerLinkTests/Support/FakeXAirMixer.swift +++ b/Tests/MixerLinkTests/Support/FakeXAirMixer.swift @@ -43,6 +43,10 @@ final class FakeXAirMixer: Sendable { var auxReturn = Channel(name: "", color: 0) /// When false, the mixer receives queries but never answers. var answers = true + /// DIAGNOSTICS: seconds each reply is held before it is sent. + var replyDelay: TimeInterval = 0 + var diagRefusesLateFlows = false + var diagListenAttempts = 200 /// When false, mute, fader and input source queries go unanswered (older firmware, say). var answersMixState = true /// When true, faders are reported as integers instead of floats. @@ -118,26 +122,49 @@ final class FakeXAirMixer: Sendable { /// Opens a loopback UDP listener on `port` that answers with `responder`, and returns it with its port. 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.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) + var attempt = 0 + while true { + attempt += 1 + 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.makeStream() + listener.stateUpdateHandler = { [listener, attempt] update in + switch update { + case .ready: ready.continuation.yield(listener.port?.rawValue) + case .failed(let error), .waiting(let error): + fputs("[diag] X-Air listener on \(port) attempt \(attempt): \(update) \(error)\n", stderr) + ready.continuation.yield(nil) + default: break + } + } + let epoch = responder.epoch.withLock { $0 } + listener.newConnectionHandler = { connection in + let refuses = responder.state.withLock { $0.diagRefusesLateFlows } + if responder.epoch.withLock({ $0 }) != epoch { + fputs("[diag] X-Air listener on \(port): a flow after power-off from \(connection.endpoint), refused=\(refuses)\n", stderr) + if refuses { connection.cancel(); return } + } + connection.start(queue: .global()) + responder.serve(connection) + } + listener.start(queue: .global()) + var iterator = ready.stream.makeAsyncIterator() + if let found = await iterator.next(), let found { + if attempt > 1 { fputs("[diag] X-Air listener on \(port): ready at attempt \(attempt)\n", stderr) } + return (listener, found) + } + listener.cancel() + if attempt >= responder.state.withLock({ $0.diagListenAttempts }) || Task.isCancelled { throw CancellationError() } + try await Task.sleep(for: .milliseconds(25)) } - listener.start(queue: .global()) - var iterator = ready.stream.makeAsyncIterator() - return (listener, await iterator.next() ?? 0) } /// 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() { + responder.epoch.withLock { $0 += 1 } listener.withLock { $0?.cancel(); $0 = nil } responder.dropConnections() } @@ -208,6 +235,8 @@ final class FakeXAirMixer: Sendable { private let subscribers = Mutex<[(connection: NWConnection, expires: Date)]>([]) init(_ state: State) { self.state = Mutex(state) } + /// Counts power-offs: a flow a listener hands over after its power-off is not served. + let epoch = Mutex(0) /// Every connection served, so a power-off can close them all. private let connections = Mutex<[NWConnection]>([]) @@ -259,7 +288,14 @@ final class FakeXAirMixer: Sendable { } if echo { connection.send(content: Data(OSCMessage(message.address).encoded()), completion: .contentProcessed { _ in }) } } else if let data, let query = try? OSCMessage(decoding: Array(data)), let reply = reply(to: query) { - connection.send(content: Data(reply.encoded()), completion: .contentProcessed { _ in }) + let delay = state.withLock { $0.replyDelay } + if delay > 0 { + DispatchQueue.global().asyncAfter(deadline: .now() + delay) { + connection.send(content: Data(reply.encoded()), completion: .contentProcessed { _ in }) + } + } else { + connection.send(content: Data(reply.encoded()), completion: .contentProcessed { _ in }) + } } serve(connection) }