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: add receive_events_non_blocking #65

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions src/snabbkaffe.erl
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
, subscribe/2
, subscribe/1
, receive_events/1
, receive_events_non_blocking/1
, wait_async_action/3
, push_stat/2
, push_stat/3
Expand Down Expand Up @@ -249,6 +250,13 @@ subscribe(Predicate, NEvents, Timeout, BackInTime) ->
receive_events(SubRef) ->
snabbkaffe_collector:receive_events(SubRef).

%% @doc Like `receive_events', but returns immediatelly with all collected events so far,
%% without blocking for more expected events.
-spec receive_events_non_blocking(snabbkaffe_collector:subscription()) ->
[snabbkaffe:event()].
receive_events_non_blocking(SubRef) ->
snabbkaffe_collector:receive_events_non_blocking(SubRef).

-spec start_trace() -> ok.
start_trace() ->
case snabbkaffe_sup:start_link() of
Expand Down
23 changes: 23 additions & 0 deletions src/snabbkaffe_collector.erl
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
, block_until/3
, subscribe/4
, receive_events/1
, receive_events_non_blocking/1
, tp/3
, push_stat/3
]).
Expand Down Expand Up @@ -159,6 +160,12 @@ receive_events(Sub = #subscription{ref = Ref, n = NEvents}) ->
unsubscribe(Sub),
Ret.

-spec receive_events_non_blocking(subscription()) -> [snabbkaffe:event()].
receive_events_non_blocking(Sub = #subscription{ref = Ref, n = NEvents}) ->
Ret = do_recv_events_non_blocking(Ref, NEvents, []),
unsubscribe(Sub),
Ret.

%% @doc NOTE: This function should be called from the same process
%% that subscribed to `SubRef'
-spec unsubscribe(subscription()) -> ok.
Expand Down Expand Up @@ -425,6 +432,22 @@ do_recv_events(Ref, N, Acc) ->
do_recv_events(Ref, N - 1, [Event|Acc])
end.

-spec do_recv_events_non_blocking(reference(),
non_neg_integer(),
[snabbkaffe:event()]
) -> [snabbkaffe:event()].
do_recv_events_non_blocking(_Ref, 0, Acc) ->
lists:reverse(Acc);
do_recv_events_non_blocking(Ref, N, Acc) ->
receive
{'DOWN', Ref, _, _, _} ->
exit(snabbkaffe_collector_died);
{Ref, Event} ->
do_recv_events_non_blocking(Ref, N - 1, [Event|Acc])
after
0 -> lists:reverse(Acc)
end.

-spec do_wait_for_silence(integer(), integer()) -> ok.
do_wait_for_silence(SilenceInterval, SleepTime) ->
timer:sleep(SleepTime),
Expand Down