Skip to content
Merged
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: 4 additions & 3 deletions lib/falcon/body/request_finished.rb
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,9 @@ module Body
# Wraps a response body and decrements a metric after the body is closed.
#
# Runs close on the underlying body first (which invokes rack.response_finished),
# then decrements the metric. Use this so requests_active stays elevated until
# the request is fully finished (including response_finished callbacks).
# then decrements the metric, even if closing raises. Use this so requests_active
# stays elevated until the request is fully finished (including response_finished
# callbacks), without leaking if close reports an error.
class RequestFinished < Protocol::HTTP::Body::Wrapper
# Wrap a response body with a metric.
#
Expand Down Expand Up @@ -56,7 +57,7 @@ def rewind
# @parameter error [Exception, nil] Optional error that caused the close.
def close(error = nil)
super
ensure
@metric&.decrement
@metric = nil
end
Expand Down
4 changes: 4 additions & 0 deletions releases.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# Releases

## Unreleased

- Ensure `requests_active` is decremented if closing the response body raises.

## v0.55.3

- Decrement `requests_active` in `Falcon::Server#call` when `super` or `Falcon::Body::RequestFinished.wrap` raises, so utilization metrics are not leaked on error paths.
Expand Down
19 changes: 19 additions & 0 deletions test/falcon/body/request_finished.rb
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,25 @@
expect(metric.value).to be == 0
end

it "decrements metric when body close raises" do
body = Class.new(Protocol::HTTP::Body::Buffered) do
def close(error = nil)
super
raise RuntimeError, "close failed"
end
end.new(["Hello World"])
response = Protocol::HTTP::Response[200, {"content-type" => "text/plain"}, body]

metric.increment
subject.wrap(response, metric)

expect do
response.body.close
end.to raise_exception(RuntimeError, message: be =~ /close failed/)

expect(metric.value).to be == 0
end

it "decrements only once on multiple close calls" do
metric.increment
subject.wrap(response, metric)
Expand Down
Loading