This repository has been archived by the owner on Jan 21, 2022. It is now read-only.
forked from comtihon/mongodb-erlang
/
mongo_pool.erl
89 lines (76 loc) · 2.09 KB
/
mongo_pool.erl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
-module(mongo_pool).
-export([
start/3,
start_link/3,
get/1
]).
-behaviour(gen_server).
-export([
init/1,
handle_call/3,
handle_cast/2,
handle_info/2,
terminate/2,
code_change/3
]).
-record(state, {
supervisor :: pid(),
connections :: array:array(),
monitors :: orddict:orddict()
}).
-spec start(atom(), pos_integer(), pid()) -> {ok, pid()}.
start(Name, Size, Sup) ->
gen_server:start({local, Name}, ?MODULE, [Size, Sup], []).
-spec start_link(atom(), pos_integer(), pid()) -> {ok, pid()}.
start_link(Name, Size, Sup) ->
gen_server:start_link({local, Name}, ?MODULE, [Size, Sup], []).
-spec get(atom() | pid()) -> mongo_connection:connection().
get(Pool) ->
case gen_server:call(Pool, get, infinity) of
{ok, Connection} -> Connection;
{error, Reason} -> erlang:exit(Reason)
end.
%% @hidden
init([Size, Sup]) ->
random:seed(erlang:now()),
{ok, #state{
supervisor = Sup,
connections = array:new(Size, [{fixed, false}, {default, undefined}]),
monitors = orddict:new()
}}.
%% @hidden
handle_call(get, _From, #state{connections = Connections} = State) ->
Index = random:uniform(array:size(Connections)) - 1,
case array:get(Index, Connections) of
undefined ->
case supervisor:start_child(State#state.supervisor, []) of
{ok, Connection} ->
Monitor = erlang:monitor(process, Connection),
{reply, {ok, Connection}, State#state{
connections = array:set(Index, Connection, Connections),
monitors = orddict:store(Monitor, Index, State#state.monitors)
}};
{error, Error} ->
{reply, {error, Error}, State}
end;
Connection ->
{reply, {ok, Connection}, State}
end.
%% @hidden
handle_cast(_, State) ->
{noreply, State}.
%% @hidden
handle_info({'DOWN', Monitor, process, _Pid, _}, #state{monitors = Monitors} = State) ->
{ok, Index} = orddict:find(Monitor, Monitors),
{noreply, State#state{
connections = array:set(Index, undefined, State#state.connections),
monitors = orddict:erase(Index, Monitors)
}};
handle_info(_, State) ->
{noreply, State}.
%% @hidden
terminate(_, _State) ->
ok.
%% @hidden
code_change(_Old, State, _Extra) ->
{ok, State}.