Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix the infinite loop issue when WebSocket returns an error message in the example case. #3508

Merged
merged 3 commits into from
Dec 3, 2024

Conversation

LukeWei
Copy link
Contributor

@LukeWei LukeWei commented Nov 23, 2024

When websocket.receive() encounters an error, it cannot be properly thrown, resulting in an infinite loop within AsyncStream, which negatively impacts performance.
Writing this way allows the error to be handled properly, avoiding the issue mentioned earlier.

socket.receive() is a throwing function.

extension URLSessionWebSocketTask {
    // ...
    public func receive() async throws -> URLSessionWebSocketTask.Message
}

In the case of SwiftUICaseStudies: 03-Effects-WebSocket.swift

func receive(id: ID) throws -> AsyncStream<Result<Message, any Error>> {
  let socket = try self.socket(id: id)
  return AsyncStream { continuation in
    let task = Task {
      while !Task.isCancelled {
        continuation.yield(await Result { try await Message(socket.receive()) }) // 🚨throw error indefinitely
      }
      continuation.finish()
    }
    continuation.onTermination = { _ in task.cancel() }
  }
}

The error throwing form Message(socket.receive()) will be caught by Result<Success, Failure>
This will cause the AsyncStream to continuously unexpectedly throw errors indefinitely.

It would be better to handle the Success and Failure cases separately.

do {
  let socketMessage = try await Message(socket.receive())
  continuation.yield(.success(socketMessage))
} catch {
  continuation.yield(.failure(error))
}

@LukeWei LukeWei changed the title Fix the infinite loop issue when the WebSocket returns an error message in the example case. Fix the infinite loop issue when WebSocket returns an error message in the example case. Nov 23, 2024
Copy link
Member

@mbrandonw mbrandonw left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for this @LukeWei!

@mbrandonw mbrandonw merged commit f6ae757 into pointfreeco:main Dec 3, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants