Skip to content
Open
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
7 changes: 5 additions & 2 deletions FlyingFox/Sources/HTTPHandler.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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))
}
}
64 changes: 51 additions & 13 deletions FlyingFox/Sources/WebSocket/WSHandler.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -87,8 +94,14 @@ public struct MessageFrameWSHandler: WSHandler {
let messagesIn = AsyncHandoff<WSMessage>(capacity: capacity)
let framesOut = AsyncHandoff<WSFrame>(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)
Expand All @@ -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 {
Expand All @@ -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()
}
Expand Down Expand Up @@ -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<WSMessage>

init(_ messages: AsyncHandoff<WSMessage>) {
self.messages = messages
}

deinit {
Task { [messages] in await messages.finish() }
}
}
}

extension Collection {
Expand Down
117 changes: 113 additions & 4 deletions FlyingFox/Tests/WebSocket/WSHandlerTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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<WSFrame, any Error>.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(
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<WSFrame, any Error>.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(
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<WSFrame, any Error>.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(
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()
Expand Down Expand Up @@ -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) { }
}

Expand All @@ -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
Expand Down Expand Up @@ -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<WSMessage>.makeStream()
private let kept = Mutex<AsyncStream<WSMessage>?>(nil)

var keepsInput: Bool {
kept.withLock { $0 != nil }
}

init(input: Input) {
self.input = input
}

func makeMessages(for client: AsyncStream<WSMessage>) async throws -> AsyncStream<WSMessage> {
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 {

Expand Down
1 change: 1 addition & 0 deletions FlyingSocks/Sources/AsyncHandoff.swift
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ package actor AsyncHandoff<Element: Sendable> {
/// 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()
}
Expand Down
35 changes: 35 additions & 0 deletions FlyingSocks/Tests/AsyncHandoffTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,41 @@ struct AsyncHandoffTests {
#expect(try await handoff.next() == nil)
}

@Test
func send_ThrowsCancellationError_WhenSenderIsCancelled_WhileBufferHasSpace() async throws {
let handoff = AsyncHandoff<String>(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<String>()
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<String>()
Expand Down
6 changes: 5 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).

Expand Down
Loading