Skip to content
Closed
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
8 changes: 8 additions & 0 deletions lib/async/http/protocol/http2/client.rb
Original file line number Diff line number Diff line change
Expand Up @@ -42,10 +42,18 @@ def call(request)
raise ::Protocol::HTTP::RefusedError, "Connection closed!" if self.closed?

response = create_response
completed = false

write_request(response, request)
read_response(response)
completed = true

return response
ensure
# Cancel abandoned requests, including when the task is stopped while waiting for headers.
if response && !completed && !self.closed? && response.stream.active?
response.stream.send_reset_stream(::Protocol::HTTP2::Error::CANCEL)
end
end

# Write a request to the remote server via the given response stream.
Expand Down
41 changes: 41 additions & 0 deletions test/async/http/protocol/http2/request_cancellation.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
# frozen_string_literal: true

# Released under the MIT License.
# Copyright, 2026, by Samuel Williams.

require "async/http/protocol/http2"
require "sus/fixtures/async/http"

describe Async::HTTP::Protocol::HTTP2 do
include Sus::Fixtures::Async::HTTP::ServerContext

let(:protocol) {subject}

let(:app) do
Protocol::HTTP::Middleware.for do |request|
Async::Task.current.sleep(10) if request.path == "/slow"

Protocol::HTTP::Response[200, {}, ["OK"]]
end
end

it "cancels a timed-out request and reuses the connection" do
connection = Async::HTTP::Protocol::HTTP2.client(client_endpoint.connect)
task = Async::Task.current

expect do
task.with_timeout(0.1) do
connection.call(Protocol::HTTP::Request["GET", "/slow", scheme: "http", authority: "localhost"])
end
end.to raise_exception(Async::TimeoutError)

expect(connection.streams).to be(:empty?)

response = connection.call(Protocol::HTTP::Request["GET", "/fast", scheme: "http", authority: "localhost"])
expect(response).to be(:success?)
expect(response.read).to be == "OK"
ensure
response&.close
connection&.close
end
end