Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: ability to run custom callback on timeout for Absinthe.Middleware.Async middleware #1184

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

freevova
Copy link

@freevova freevova commented Aug 5, 2022

Async middleware sends an exit signal that kills the request and causes a 500 on timeout, as it uses
Task.await/2 under the hood. This PR adds the ability to pass on_timeout/1 callback function to
the middleware and trigger it on timeout.

By default, it stops the current process with exit/1, as before.

field :time_consuming, :thing do
  resolve fn _, _, _ ->
    async(
      fn -> {:ok, long_time_consuming_function()} end,
      timeout: 7_000,
      on_timeout: fn _timeout ->
        {:error, "Failed to get a result"}
      end
    )
  end
end

The only potential issue may be that in case someone uses try/catch like this:

    try do
      ...
    catch
      :exit, {:timeout, {Task, :await, _}} ->
        IO.inspect("catched error")
    end

it won't work, as now it exits with exit({:timeout, {Absinthe.Middleware.Async, :call, [task, timeout]}})
If we need to handle it, the only way that I see is to pattern match on options and call:

  • Task.yield/1 + Task.shutdown/1 when the on_timeout option is present
  • Task.await/2 otherwise

After I had already implemented the logic, I noticed that such a question had already been raised.

…re.Async middleware

Async middleware sends an exit signal that kills the request and causes a 500 on timeout, as it uses
Task.await/2 under the hood. This PR adds the ability to pass on_timeout/1 callback function to
the middleware and trigger it on timeout.
By default, it stops the process current process with exit/1, as before.

```elixir
field :time_consuming, :thing do
  resolve fn _, _, _ ->
    async(
      fn -> {:ok, long_time_consuming_function()} end,
      timeout: 7_000,
      on_timeout: fn _timeout ->
        {:error, "Failed to get a result"}
      end
    )
  end
end
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant