summaryrefslogtreecommitdiff
path: root/apps/rexi/src/rexi_utils.erl
diff options
context:
space:
mode:
authorBrad Anderson <brad@cloudant.com>2010-08-17 22:04:15 -0400
committerAdam Kocoloski <adam@cloudant.com>2010-08-27 16:52:26 -0400
commit3b64928720ce15c92374b031ff24b10022671261 (patch)
tree0535ad8bb4f6c3cfd148c62c8c0a0f24c1a7f589 /apps/rexi/src/rexi_utils.erl
parent794d78eb02a20e6c545d24fa9649839ebe763636 (diff)
split some rexi utilities out from fabric
Diffstat (limited to 'apps/rexi/src/rexi_utils.erl')
-rw-r--r--apps/rexi/src/rexi_utils.erl53
1 files changed, 53 insertions, 0 deletions
diff --git a/apps/rexi/src/rexi_utils.erl b/apps/rexi/src/rexi_utils.erl
new file mode 100644
index 00000000..79183951
--- /dev/null
+++ b/apps/rexi/src/rexi_utils.erl
@@ -0,0 +1,53 @@
+-module(rexi_utils).
+
+-export([recv/6]).
+
+%% @doc set up the receive loop with an overall timeout
+-spec recv([any()], integer(), function(), any(), timeout(), timeout()) ->
+ {ok, any()} | timeout | {error, any()}.
+recv(Refs, Keypos, Fun, Acc0, infinity, PerMsgTO) ->
+ process_mailbox(Refs, Keypos, Fun, Acc0, nil, PerMsgTO);
+recv(Refs, Keypos, Fun, Acc0, GlobalTimeout, PerMsgTO) ->
+ TimeoutRef = erlang:make_ref(),
+ {ok, TRef} = timer:send_after(GlobalTimeout, {timeout, TimeoutRef}),
+ try
+ process_mailbox(Refs, Keypos, Fun, Acc0, TimeoutRef, PerMsgTO)
+ after
+ timer:cancel(TRef)
+ end.
+
+process_mailbox(RefList, Keypos, Fun, Acc0, TimeoutRef, PerMsgTO) ->
+ case process_message(RefList, Keypos, Fun, Acc0, TimeoutRef, PerMsgTO) of
+ {ok, Acc} ->
+ process_mailbox(RefList, Keypos, Fun, Acc, TimeoutRef, PerMsgTO);
+ {stop, Acc} ->
+ {ok, Acc};
+ Error ->
+ Error
+ end.
+
+process_message(RefList, Keypos, Fun, Acc0, TimeoutRef, PerMsgTO) ->
+ receive
+ {timeout, TimeoutRef} ->
+ timeout;
+ {Ref, Msg} ->
+ case lists:keyfind(Ref, Keypos, RefList) of
+ false ->
+ % this was some non-matching message which we will ignore
+ {ok, Acc0};
+ Worker ->
+ Fun(Msg, Worker, Acc0)
+ end;
+ {Ref, From, Msg} ->
+ case lists:keyfind(Ref, Keypos, RefList) of
+ false ->
+ {ok, Acc0};
+ Worker ->
+ Fun(Msg, {Worker, From}, Acc0)
+ end;
+ {rexi_DOWN, _RexiMonPid, ServerPid, Reason} = Msg ->
+ io:format("rexi_DOWN ~p ~p", [ServerPid, Reason]),
+ Fun(Msg, nil, Acc0)
+ after PerMsgTO ->
+ timeout
+ end.