swift-async-algorithms
swift-async-algorithms copied to clipboard
Deadlines for channels
This is (probably?) not possible to implement now, but it would be awesome if we could add deadlines to Channels like we did on Venice (backed by libdill). Like the test excerpt below:
func testDoubleSendTimeout() throws {
let channel = try Channel<Int>()
let coroutine1 = try Coroutine {
XCTAssertThrowsError(
try channel.send(111, deadline: 50.milliseconds.fromNow()),
error: VeniceError.deadlineReached
)
}
let coroutine2 = try Coroutine {
XCTAssertThrowsError(
try channel.send(222, deadline: 50.milliseconds.fromNow()),
error: VeniceError.deadlineReached
)
}
try Coroutine.wakeUp(100.milliseconds.fromNow())
let coroutine3 = try Coroutine {
try channel.send(333, deadline: .never)
}
XCTAssertEqual(try channel.receive(deadline: .never), 333)
coroutine1.cancel()
coroutine2.cancel()
coroutine3.cancel()
}
If not possible right now, what would we need in place to make it happen?
I think a more general deadline API is an interesting concept worth investigating; because not just AsyncChannel could benefit from it. Ideally it would need to interoperate with Clock/Instant/Duration; and be composable with other deadlines being applied.
Perhaps something along the lines of:
// construct a deadline for work and throw some sort of "timeout" error that contains the clock & deadline that passed
func withDeadline<C: Clock, T>(_ deadline: C.Instant, clock: C, operation: @Sendable @escaping () async throws -> T) async throws -> T
However placement of such a thing is perhaps the quandary; does it belong in a lower layer or does it belong in a package such as this?
I agree that a general deadline concept is good to have but IMO not this packages problem to solve. This is rather something that we should look in the standard library. @paulofaria would you mind opening an issue over here: https://github.com/apple/swift/issues
Sorry, I don't have time to create the issue right how. I closed this issue, though.