Skip to content

Commit

Permalink
Do not send a fallback if the plug has already sent a response (#289)
Browse files Browse the repository at this point in the history
* Do not send a fallback if the plug has already sent a response
  • Loading branch information
mtrudel authored Jan 12, 2024
1 parent feb275e commit 4143589
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 3 deletions.
16 changes: 13 additions & 3 deletions lib/bandit/http1/handler.ex
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ defmodule Bandit.HTTP1.Handler do

use ThousandIsland.Handler

@already_sent {:plug_conn, :sent}

@impl ThousandIsland.Handler
def handle_data(data, socket, state) do
connection_span = ThousandIsland.Socket.telemetry_span(socket)
Expand Down Expand Up @@ -109,9 +111,17 @@ defmodule Bandit.HTTP1.Handler do
defp code_for_reason(_), do: 400

defp attempt_to_send_fallback(req, code) do
Bandit.HTTP1.Adapter.send_resp(req, code, [], <<>>)
rescue
_ -> :ok
receive do
@already_sent ->
send(self(), @already_sent)
after
0 ->
try do
Bandit.HTTP1.Adapter.send_resp(req, code, [], <<>>)
rescue
_ -> :ok
end
end
end

defp maybe_keepalive(req, state) do
Expand Down
14 changes: 14 additions & 0 deletions test/bandit/http1/request_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -1393,6 +1393,20 @@ defmodule HTTP1RequestTest do
raise "boom"
end

@tag capture_log: true
test "does not send an error response if the plug has already sent one before raising",
context do
client = SimpleHTTP1Client.tcp_client(context)
SimpleHTTP1Client.send(client, "GET", "/send_and_raise_error", ["host: banana"])
assert {:ok, "200 OK", _headers, _} = SimpleHTTP1Client.recv_reply(client)
assert SimpleHTTP1Client.connection_closed_for_reading?(client)
end

def send_and_raise_error(conn) do
send_resp(conn, 200, "OK")
raise "boom"
end

@tag capture_log: true
test "returns a 500 if the plug does not return anything", context do
response = Req.get!(context.req, url: "/noop")
Expand Down

0 comments on commit 4143589

Please sign in to comment.