Skip to content

Commit

Permalink
fix(event-stream): don't send a message if we're stopping immediately
Browse files Browse the repository at this point in the history
Related to mtrudel/bandit#141, we get into
this situation when we close the connection before truly entering the
hibernate loop. Instead, we close/unsubscribe directly, and return the
conn immediately.

Sample error from `api-prod` (truncated):
```
Bandit.HTTP1.Handler #PID<0.5319.7> received unexpected message in
handle_info/2: {:close, <conn>}
```
  • Loading branch information
paulswartz committed Jan 17, 2024
1 parent d0f0c86 commit 557dac4
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 7 deletions.
15 changes: 10 additions & 5 deletions apps/api_web/lib/api_web/event_stream.ex
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,16 @@ defmodule ApiWeb.EventStream do

@spec call(Plug.Conn.t(), module, map) :: Plug.Conn.t()
def call(conn, module, _params) do
state = initialize(conn, module)
hibernate_loop(state)
case initialize(conn, module) do
%__MODULE__{} = state ->
hibernate_loop(state)

%Plug.Conn{} = conn ->
conn
end
end

@spec initialize(Plug.Conn.t(), module) :: state
@spec initialize(Plug.Conn.t(), module) :: state | Plug.Conn.t()
def initialize(conn, module, timeout \\ 30_000) do
conn =
conn
Expand All @@ -41,8 +46,8 @@ defmodule ApiWeb.EventStream do

ensure_timer(%__MODULE__{conn: conn, pid: pid, timeout: timeout})
else
send(self(), {:close, conn})
%__MODULE__{conn: conn, pid: nil, timeout: timeout}
state = %__MODULE__{conn: conn, pid: nil, timeout: timeout}
unsubscribe(state)
end
end

Expand Down
4 changes: 2 additions & 2 deletions apps/api_web/test/api_web/event_stream_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -141,8 +141,8 @@ defmodule ApiWeb.EventStreamTest do
} do
CheckForShutdown.shutdown()

state = initialize(conn, @module)
assert {:close, conn} = receive_result(state)
conn = call(conn, @module, %{})
assert_receive {:plug_conn, :sent}

assert chunks(conn) == ""
end
Expand Down

0 comments on commit 557dac4

Please sign in to comment.