Skip to content

Commit

Permalink
Merge pull request #1169 from andrewhr/async-middleware-telemetry
Browse files Browse the repository at this point in the history
Add telemetry events to async middleware
  • Loading branch information
benwilson512 authored May 8, 2022
2 parents 658d510 + df41b03 commit 453fd12
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 3 deletions.
10 changes: 8 additions & 2 deletions lib/absinthe/middleware/async.ex
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,14 @@ defmodule Absinthe.Middleware.Async do
# This function inserts additional middleware into the remaining middleware
# stack for this field. On the next resolution pass, we need to `Task.await` the
# task so we have actual data. Thus, we prepend this module to the middleware stack.
def call(%{state: :unresolved} = res, {fun, opts}) when is_function(fun),
do: call(res, {Task.async(fun), opts})
def call(%{state: :unresolved} = res, {fun, opts}) when is_function(fun) do
task =
Task.async(fn ->
:telemetry.span([:absinthe, :middleware, :async, :task], %{}, fn -> {fun.(), %{}} end)
end)

call(res, {task, opts})
end

def call(%{state: :unresolved} = res, {task, opts}) do
task_data = {task, opts}
Expand Down
29 changes: 28 additions & 1 deletion test/absinthe/middleware/async_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -75,12 +75,39 @@ defmodule Absinthe.Middleware.AsyncTest do
assert {:ok, %{data: %{"asyncBareThing" => "bare task"}}} == Absinthe.run(doc, Schema)
end

test "can resolve a field using the normal test helper" do
test "can resolve a field using the normal test helper and emit telemetry event", %{test: test} do
doc = """
{asyncThing}
"""

pid = self()

:ok =
:telemetry.attach_many(
"#{test}",
[
[:absinthe, :middleware, :async, :task, :start],
[:absinthe, :middleware, :async, :task, :stop]
],
fn name, measurements, metadata, _config ->
send(pid, {:telemetry_event, name, measurements, metadata})
end,
_config = %{}
)

assert {:ok, %{data: %{"asyncThing" => "we async now"}}} == Absinthe.run(doc, Schema)

assert_receive {:telemetry_event, [:absinthe, :middleware, :async, :task, :start],
%{system_time: _}, %{}}

assert_receive {:telemetry_event, [:absinthe, :middleware, :async, :task, :stop],
%{duration: _}, %{}}

assert_receive {:telemetry_event, [:absinthe, :middleware, :async, :task, :start],
%{system_time: _}, %{}}

assert_receive {:telemetry_event, [:absinthe, :middleware, :async, :task, :stop],
%{duration: _}, %{}}
end

test "can resolve a field using a cooler but probably confusing to some people helper" do
Expand Down

0 comments on commit 453fd12

Please sign in to comment.