Skip to content

Commit 6a3691d

Browse files
committed
refactor ask handler with proper timeout
1 parent 09f1252 commit 6a3691d

File tree

2 files changed

+29
-29
lines changed

2 files changed

+29
-29
lines changed

core/lib/canary/interface/ask.ex

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,7 @@ defmodule Canary.Interface.Ask.Default do
8383
:ok
8484

8585
%{"choices" => [%{"delta" => %{"content" => content}}]} ->
86-
safe(handle_delta, {:delta, content})
86+
safe(handle_delta, content)
8787
Agent.update(pid, &(&1 <> content))
8888

8989
_ ->
@@ -93,8 +93,6 @@ defmodule Canary.Interface.Ask.Default do
9393
)
9494

9595
completion = if completion == "", do: Agent.get(pid, & &1), else: completion
96-
safe(handle_delta, {:done, completion})
97-
9896
{:ok, %{response: completion}}
9997
end
10098

core/lib/canary/interface/controller.ex

Lines changed: 28 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -100,13 +100,22 @@ defmodule CanaryWeb.Interface.Controller do
100100
here = self()
101101

102102
Task.start_link(fn ->
103-
Canary.Interface.Ask.run(
104-
conn.assigns.project,
105-
query,
106-
fn data -> send(here, data) end,
107-
tags: tags,
108-
cache: cache?()
109-
)
103+
try do
104+
{:ok, completion} =
105+
Canary.Interface.Ask.run(
106+
conn.assigns.project,
107+
query,
108+
&send(here, {:delta, &1}),
109+
tags: tags,
110+
cache: cache?()
111+
)
112+
113+
send(here, {:done, completion})
114+
catch
115+
exception ->
116+
Sentry.capture_exception(exception, stacktrace: __STACKTRACE__)
117+
send(here, {:error, exception})
118+
end
110119
end)
111120

112121
:ok =
@@ -119,28 +128,21 @@ defmodule CanaryWeb.Interface.Controller do
119128
end
120129

121130
defp receive_and_send(conn) do
122-
Stream.repeatedly(fn -> receive_event() end)
123-
|> Enum.reduce_while(conn, fn
124-
{:delta, data}, conn when is_binary(data) ->
125-
chunk(conn, sse_encode(data))
126-
{:cont, conn}
127-
128-
{:done, _data}, conn ->
129-
{:halt, conn}
130-
131-
{:error, _}, conn ->
132-
{:halt, conn}
131+
receive do
132+
{:delta, data} when is_binary(data) ->
133+
case chunk(conn, sse_encode(data)) do
134+
{:ok, conn} -> receive_and_send(conn)
135+
_ -> conn
136+
end
133137

134-
_, conn ->
135-
{:cont, conn}
136-
end)
137-
end
138+
{:done, _data} ->
139+
conn
138140

139-
defp receive_event() do
140-
receive do
141-
event -> event
141+
{:error, _} ->
142+
conn
142143
after
143-
60_000 -> {:error, :timeout}
144+
5_000 ->
145+
conn
144146
end
145147
end
146148

0 commit comments

Comments
 (0)