@@ -22,6 +22,24 @@ const HttpError = error{
2222 Aborted,
2323 } || std.mem.Allocator.Error;
2424
25+// Blocking socket reads cannot observe the cancel token, so a watcher thread
26+// shuts the connection down when a cancel is requested, unblocking the read.
27+const CancelWatch = struct {
28+ cancel: *const std.atomic.Value(bool),
29+ connection: *std.http.Client.Connection,
30+ done: std.atomic.Value(bool) = std.atomic.Value(bool).init(false),
31+
32+ fn run(self: *CancelWatch) void {
33+ while (!self.done.load(.acquire)) {
34+ if (self.cancel.load(.acquire)) {
35+ self.connection.stream_reader.stream.shutdown(platform.io, .both) catch {};
36+ return;
37+ }
38+ std.Io.sleep(platform.io, .{ .nanoseconds = 25 * std.time.ns_per_ms }, .boot) catch {};
39+ }
40+ }
41+};
42+
2543 pub fn postSse(
2644 a: std.mem.Allocator,
2745 url: []const u8,
@@ -31,6 +49,7 @@ pub fn postSse(
3149 cancel: *const std.atomic.Value(bool),
3250 err_body: *?[]const u8,
3351 ) HttpError!void {
52+ if (cancel.load(.acquire)) return error.Aborted;
3453 const uri = std.Uri.parse(url) catch return error.RequestFailed;
3554 var client: std.http.Client = .{ .allocator = a, .io = platform.io };
3655 defer client.deinit();
@@ -52,6 +71,13 @@ pub fn postSse(
5271 bw.end() catch return error.RequestFailed;
5372 req.connection.?.flush() catch return error.RequestFailed;
5473
74+ var watch = CancelWatch{ .cancel = cancel, .connection = req.connection.? };
75+ const watcher = std.Thread.spawn(.{}, CancelWatch.run, .{&watch}) catch null;
76+ defer {
77+ watch.done.store(true, .release);
78+ if (watcher) |t| t.join();
79+ }
80+
5581 var response = req.receiveHead(&.{}) catch return error.RequestFailed;
5682 const status = @intFromEnum(response.head.status);