From 9d775c6d2fd3f1bae24d1ff897a6c1eeb9226787 Mon Sep 17 00:00:00 2001 From: Simon Whitty Date: Sun, 15 Nov 2026 09:29:21 +1100 Subject: [PATCH 1/3] Throw CancellationError from AsyncHandoff.send whenever the sender is cancelled send was documented to throw CancellationError when the sending task is cancelled, but only checked while suspended. A cancelled sender could still hand its element to a waiting receiver or add it to the buffer. --- FlyingSocks/Sources/AsyncHandoff.swift | 1 + FlyingSocks/Tests/AsyncHandoffTests.swift | 35 +++++++++++++++++++++++ 2 files changed, 36 insertions(+) diff --git a/FlyingSocks/Sources/AsyncHandoff.swift b/FlyingSocks/Sources/AsyncHandoff.swift index 62f32e18..0692eb49 100644 --- a/FlyingSocks/Sources/AsyncHandoff.swift +++ b/FlyingSocks/Sources/AsyncHandoff.swift @@ -54,6 +54,7 @@ package actor AsyncHandoff { /// Throws `AsyncHandoffFinishedError` if the handoff is finished before then, /// or `CancellationError` if the sending task is cancelled. package func send(_ element: Element) async throws { + try Task.checkCancellation() guard !isFinished else { throw AsyncHandoffFinishedError() } diff --git a/FlyingSocks/Tests/AsyncHandoffTests.swift b/FlyingSocks/Tests/AsyncHandoffTests.swift index fcafb5e9..6cb411b8 100644 --- a/FlyingSocks/Tests/AsyncHandoffTests.swift +++ b/FlyingSocks/Tests/AsyncHandoffTests.swift @@ -129,6 +129,41 @@ struct AsyncHandoffTests { #expect(try await handoff.next() == nil) } + @Test + func send_ThrowsCancellationError_WhenSenderIsCancelled_WhileBufferHasSpace() async throws { + let handoff = AsyncHandoff(capacity: 2) + + let sender = Task { + withUnsafeCurrentTask { $0?.cancel() } + try await handoff.send("Fish") + } + await #expect(throws: CancellationError.self) { + try await sender.value + } + // The cancelled element is not buffered. + await handoff.finish() + #expect(try await handoff.next() == nil) + } + + @Test + func send_ThrowsCancellationError_WhenSenderIsCancelled_WhileReceiverWaits() async throws { + let handoff = AsyncHandoff() + let receiver = Task { try await handoff.next() } + // Gives the receiver time to wait. If it has not, send must still throw. + try await Task.sleep(seconds: 0.05) + + let sender = Task { + withUnsafeCurrentTask { $0?.cancel() } + try await handoff.send("Fish") + } + await #expect(throws: CancellationError.self) { + try await sender.value + } + // The cancelled element is not delivered. + await handoff.finish() + #expect(try await receiver.value == nil) + } + @Test func next_ReturnsNil_WhenReceiverIsCancelled() async throws { let handoff = AsyncHandoff() From 760d5486f3e080b8a2243da93658b0a538d981b5 Mon Sep 17 00:00:00 2001 From: Simon Whitty Date: Sun, 15 Nov 2026 09:29:21 +1100 Subject: [PATCH 2/3] Keep WebSocket pings and closes answered when the handler stops reading MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Follow-up to #249: - Finish the handler's input once the task reading it is cancelled or the stream is released, and drop later client messages, so frames are still read and pings and closes still answered. Tests cover a handler that cancels while keeping its input, and one that releases it. - Keep the advice from #249: a handler that does not need the client's messages should still read and discard them, or now not keep its input at all. - Make capacity a public parameter of MessageFrameWSHandler.init and HTTPHandler.webSocket, as offered in #249. Its documentation notes that each waiting message can be as large as webSocketMaxFrameSize. - Only the frame loop ends the handler's input. Teardown could previously finish it first when the output loop ended, losing the close message. - Check the backpressure tests reach their expected counts, not only that they stay under them. - Cite RFC 6455 §5.5.1 for the close echo, and stop finishing the input with a Result that cannot fail. --- FlyingFox/Sources/HTTPHandler.swift | 7 +- FlyingFox/Sources/WebSocket/WSHandler.swift | 64 ++++++++-- .../Tests/WebSocket/WSHandlerTests.swift | 117 +++++++++++++++++- README.md | 6 +- 4 files changed, 174 insertions(+), 20 deletions(-) diff --git a/FlyingFox/Sources/HTTPHandler.swift b/FlyingFox/Sources/HTTPHandler.swift index 4c88ef01..ecc4e2e0 100644 --- a/FlyingFox/Sources/HTTPHandler.swift +++ b/FlyingFox/Sources/HTTPHandler.swift @@ -75,7 +75,10 @@ public extension HTTPHandler where Self == ClosureHTTPHandler { } public extension HTTPHandler where Self == WebSocketHTTPHandler { - static func webSocket(_ handler: some WSMessageHandler, frameSize: Int = 16384) -> WebSocketHTTPHandler { - WebSocketHTTPHandler(handler: MessageFrameWSHandler(handler: handler, frameSize: frameSize)) + /// - Parameters: + /// - frameSize: The largest payload of a frame sent to the client. + /// - capacity: How many messages or frames may wait in each direction. See `MessageFrameWSHandler.init`. + static func webSocket(_ handler: some WSMessageHandler, frameSize: Int = 16384, capacity: Int = 16) -> WebSocketHTTPHandler { + WebSocketHTTPHandler(handler: MessageFrameWSHandler(handler: handler, frameSize: frameSize, capacity: capacity)) } } diff --git a/FlyingFox/Sources/WebSocket/WSHandler.swift b/FlyingFox/Sources/WebSocket/WSHandler.swift index 62414cbd..f9271c76 100644 --- a/FlyingFox/Sources/WebSocket/WSHandler.swift +++ b/FlyingFox/Sources/WebSocket/WSHandler.swift @@ -68,11 +68,18 @@ public struct MessageFrameWSHandler: WSHandler { private let frameSize: Int private let capacity: Int - public init(handler: some WSMessageHandler, frameSize: Int = 16384) { - self.init(handler: handler, frameSize: frameSize, capacity: 16) - } - - init(handler: some WSMessageHandler, frameSize: Int, capacity: Int) { + /// - Parameters: + /// - handler: Receives the client's messages and provides the messages sent to the client. + /// - frameSize: The largest payload of a frame sent to the client. Longer messages are split into continuation frames. + /// - capacity: How many client messages may wait for the handler, and how many frames may wait to be written + /// to the client. Past that, no more frames are read from the client until the handler catches up, and no + /// more messages are read from the handler until the client does. Pings and closes from the client are only + /// answered while frames are being read, so a handler that does not need the client's messages should still + /// read and discard them, or not keep its input stream at all. Once the task reading the stream is cancelled, + /// or the stream is released, later client messages are dropped. Each waiting message can be as large as the + /// server's `webSocketMaxFrameSize`. + public init(handler: some WSMessageHandler, frameSize: Int = 16384, capacity: Int = 16) { + precondition(capacity >= 0, "capacity must not be negative") self.handler = handler self.frameSize = frameSize self.capacity = capacity @@ -87,8 +94,14 @@ public struct MessageFrameWSHandler: WSHandler { let messagesIn = AsyncHandoff(capacity: capacity) let framesOut = AsyncHandoff(capacity: capacity) - // messagesIn is never finished with an error. - let messagesOut = try await handler.makeMessages(for: AsyncStream { try? await messagesIn.next() }) + // Once the handler's input stream ends, is cancelled or is released, + // messagesIn is finished and later client messages are dropped, so + // frames are still read and pings and closes are still answered. + let input = HandlerInput(messagesIn) + let messagesOut = try await handler.makeMessages(for: AsyncStream { + // messagesIn is never finished with an error. + try? await input.messages.next() + }) let task = Task { await start(framesIn: framesIn, framesOut: framesOut, messagesIn: messagesIn, messagesOut: messagesOut) @@ -111,21 +124,32 @@ public struct MessageFrameWSHandler: WSHandler { if frame.opcode == .close { throw FrameError.closed(frame) } else if let message = try makeMessage(for: frame) { - try await messagesIn.send(message) + do { + try await messagesIn.send(message) + } catch is AsyncHandoffFinishedError { + // The handler no longer reads its input. + } } else if let frame = try makeResponseFrames(for: frame) { try await framesOut.send(frame) } } } catch FrameError.closed(let frame) { - // Echo the close and end the frames before telling the - // handler, so the closing handshake does not wait on it. + // RFC 6455 §5.5.1: an endpoint that receives a Close frame + // sends one in response. Echo it and end the frames before + // telling the handler, so the closing handshake does not wait on it. try? await framesOut.send(frame) await framesOut.finish() - await messagesIn.finish(with: Result { try makeMessage(for: frame) }) + // WSFrameValidator has already checked the close payload, so + // makeMessage does not throw here. + await messagesIn.finish(with: .success(try? makeMessage(for: frame))) + return } catch is CancellationError, is AsyncHandoffFinishedError { } catch { await framesOut.finish(throwing: error) } + // Only this loop ends the handler's input, so a close it is + // still delivering is not lost when the other loop ends first. + await messagesIn.finish() } group.addTask { do { @@ -142,9 +166,9 @@ public struct MessageFrameWSHandler: WSHandler { } } // The connection ends with either loop, even while the other waits - // on a handler that does not respond to cancellation. + // on a handler that does not respond to cancellation. Cancelling + // the frame loop ends the handler's input. await group.next() - await messagesIn.finish() await framesOut.finish() group.cancelAll() } @@ -219,6 +243,20 @@ extension MessageFrameWSHandler { case closed(WSFrame) case invalid(String) } + + // Held by the handler's input stream, which releases it when the stream + // ends, is cancelled or is no longer referenced. + private final class HandlerInput: Sendable { + let messages: AsyncHandoff + + init(_ messages: AsyncHandoff) { + self.messages = messages + } + + deinit { + Task { [messages] in await messages.finish() } + } + } } extension Collection { diff --git a/FlyingFox/Tests/WebSocket/WSHandlerTests.swift b/FlyingFox/Tests/WebSocket/WSHandlerTests.swift index fe0c7c1f..a41bf9cb 100644 --- a/FlyingFox/Tests/WebSocket/WSHandlerTests.swift +++ b/FlyingFox/Tests/WebSocket/WSHandlerTests.swift @@ -147,6 +147,62 @@ struct WSHandlerTests { ) } + @Test + func ping_IsAnswered_AfterMoreMessagesThanCapacity_WhenHandlerCancelsReadingItsInput() async throws { + let messages = OutputOnly(input: .readFirstThenCancel) + let handler = MessageFrameWSHandler.make(handler: messages, capacity: 2) + let (clientFrames, clientContinuation) = AsyncThrowingStream.makeStream() + defer { clientContinuation.finish() } + + let frames = try await handler.makeFrames(for: clientFrames) + for _ in 0..<5 { clientContinuation.yield(.fish) } + clientContinuation.yield(.ping) + + var iterator = frames.makeAsyncIterator() + #expect( + try await iterator.next() == .pong + ) + // the input was cancelled, not released + #expect(messages.keepsInput) + } + + @Test + func ping_IsAnswered_AfterMoreMessagesThanCapacity_WhenHandlerReleasesItsInput() async throws { + let handler = MessageFrameWSHandler.make(handler: OutputOnly(input: .release), capacity: 2) + let (clientFrames, clientContinuation) = AsyncThrowingStream.makeStream() + defer { clientContinuation.finish() } + + let frames = try await handler.makeFrames(for: clientFrames) + for _ in 0..<5 { clientContinuation.yield(.fish) } + clientContinuation.yield(.ping) + + var iterator = frames.makeAsyncIterator() + #expect( + try await iterator.next() == .pong + ) + } + + @Test + func ping_IsAnswered_AfterManyMessages_WhenCapacityIsMax_AndHandlerKeepsItsInputUnread() async throws { + let messages = Messages() + let handler = MessageFrameWSHandler.make(handler: messages, capacity: .max) + let (clientFrames, clientContinuation) = AsyncThrowingStream.makeStream() + defer { clientContinuation.finish() } + + let frames = try await handler.makeFrames(for: clientFrames) + for _ in 0..<100 { clientContinuation.yield(.fish) } + clientContinuation.yield(.ping) + + var iterator = frames.makeAsyncIterator() + #expect( + try await iterator.next() == .pong + ) + // the messages were kept for the handler + #expect( + try await messages.input.takeNext() == .text("Fish") + ) + } + @Test func close_IsEchoed_WhileHandlerIgnoresItsInput() async throws { let handler = MessageFrameWSHandler.make() @@ -202,9 +258,11 @@ struct WSHandlerTests { #expect( try await messages.input.takeNext() == .text("Fish") ) - try await Task.sleep(seconds: 0.05) // Besides the message received, 2 wait in the buffer and 1 waits for space. - #expect(read.withLock { $0 } <= 4) + #expect(await eventually { read.withLock { $0 } == 4 }) + // and no more are read + try await Task.sleep(seconds: 0.05) + #expect(read.withLock { $0 } == 4) withExtendedLifetime(frames) { } } @@ -224,9 +282,11 @@ struct WSHandlerTests { #expect( await iterator.next() == .make(fin: true, opcode: .text, payload: "Hello".data(using: .utf8)!) ) - try await Task.sleep(seconds: 0.05) // Besides the frame received, 2 wait in the buffer and 1 waits for space. - #expect(pulled.withLock { $0 } <= 4) + #expect(await eventually { pulled.withLock { $0 } == 4 }) + // and no more are pulled + try await Task.sleep(seconds: 0.05) + #expect(pulled.withLock { $0 } == 4) } @Test @@ -302,6 +362,55 @@ private struct UnfoldingMessages: WSMessageHandler { } } +// Keeps its output open, and stops reading its input as a broadcast-only +// handler would. +private final class OutputOnly: WSMessageHandler { + + enum Input { + // reads the first message, then cancels the task reading the input, + // but keeps the input, so only the cancellation ends it + case readFirstThenCancel + // never reads the input, and does not keep it + case release + } + + let input: Input + let output = AsyncStream.makeStream() + private let kept = Mutex?>(nil) + + var keepsInput: Bool { + kept.withLock { $0 != nil } + } + + init(input: Input) { + self.input = input + } + + func makeMessages(for client: AsyncStream) async throws -> AsyncStream { + switch input { + case .readFirstThenCancel: + kept.withLock { $0 = client } + Task { + for await _ in client { + withUnsafeCurrentTask { $0?.cancel() } + } + } + case .release: + break + } + return output.stream + } +} + +// Whether `condition` holds within a second. +private func eventually(_ condition: () -> Bool) async -> Bool { + for _ in 0..<200 { + if condition() { return true } + try? await Task.sleep(seconds: 0.005) + } + return condition() +} + // Suspends its waiters, ignoring cancellation, until it is opened. private final class Gate: Sendable { diff --git a/README.md b/README.md index 469a4cc1..3b990cac 100644 --- a/README.md +++ b/README.md @@ -184,7 +184,11 @@ enum WSMessage { } ``` -At most 16 messages from the client wait for the handler, and at most 16 frames wait to be written to the client. Beyond that, frames are not read from the client until the handler catches up, and no more messages are read from the handler's stream until the client does, so a slow handler or client holds the connection back instead of queueing without limit. Pings are answered while fewer messages wait; a handler that does not need the client's messages should still read and discard them. A handler that produces its messages on demand, for example with `AsyncStream(unfolding:onCancel:)`, is paced by the client, and should return when the connection ends and cancels it. +By default at most 16 messages from the client wait for the handler, and at most 16 frames wait to be written to the client. Beyond that, frames are not read from the client until the handler catches up, and no more messages are read from the handler's stream until the client does, so a slow handler or client holds the connection back instead of queueing without limit. Pings are answered while fewer messages wait; a handler that does not need the client's messages should still read and discard them, or not keep the `client` stream at all. Once the task reading the stream is cancelled, or the stream is released, further messages from the client are dropped. + +The limit can be changed with `capacity`, for example `.webSocket(handler, capacity: 32)`. A larger capacity gives a bursty client more slack, but lets every connection hold more in memory: each waiting message can be as large as the server's `webSocketMaxFrameSize`. + +A handler that produces its messages on demand, for example with `AsyncStream(unfolding:onCancel:)`, is paced by the client, and should return when the connection ends and cancels it. Raw WebSocket frames can also be [provided](#websockets). From 2170ff6b253876495fbc0abc82fc5a44cbd6b872 Mon Sep 17 00:00:00 2001 From: Simon Whitty Date: Mon, 16 Nov 2026 11:57:42 +1100 Subject: [PATCH 3/3] Remove try from non-throwing AsyncStream next() in WSHandlerTests --- FlyingFox/Tests/WebSocket/WSHandlerTests.swift | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/FlyingFox/Tests/WebSocket/WSHandlerTests.swift b/FlyingFox/Tests/WebSocket/WSHandlerTests.swift index a41bf9cb..99221919 100644 --- a/FlyingFox/Tests/WebSocket/WSHandlerTests.swift +++ b/FlyingFox/Tests/WebSocket/WSHandlerTests.swift @@ -160,7 +160,7 @@ struct WSHandlerTests { var iterator = frames.makeAsyncIterator() #expect( - try await iterator.next() == .pong + await iterator.next() == .pong ) // the input was cancelled, not released #expect(messages.keepsInput) @@ -178,7 +178,7 @@ struct WSHandlerTests { var iterator = frames.makeAsyncIterator() #expect( - try await iterator.next() == .pong + await iterator.next() == .pong ) } @@ -195,7 +195,7 @@ struct WSHandlerTests { var iterator = frames.makeAsyncIterator() #expect( - try await iterator.next() == .pong + await iterator.next() == .pong ) // the messages were kept for the handler #expect(