4 -export([start/1, start/2, connect/1, connect/2, asend/2, send/3, send/2,
5 disconnect/1, ssend/3, str/1, format/1, sformat/1, ssend/2,
7 -export([init/1, handle_call/3, handle_cast/2,
8 handle_info/2, terminate/2, code_change/3]).
10 -include("erldis.hrl").
16 str(X) when is_list(X) ->
18 str(X) when is_atom(X) ->
20 str(X) when is_binary(X) ->
22 str(X) when is_integer(X) ->
24 str(X) when is_float(X) ->
28 string:join(lists:reverse(Result), ?EOL);
29 format([Line|Rest], Result) ->
30 JoinedLine = string:join([str(X) || X <- Line], " "),
31 format(Rest, [JoinedLine|Result]).
37 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
48 connect(Host, Port) ->
49 gen_server:start_link(?MODULE, [Host, Port], []).
51 ssend(Client, Cmd) -> ssend(Client, Cmd, []).
52 ssend(Client, Cmd, Args) ->
53 gen_server:cast(Client, {send, sformat([Cmd|Args])}).
55 send(Client, Cmd) -> send(Client, Cmd, []).
56 send(Client, Cmd, Args) ->
57 gen_server:cast(Client, {send,
58 string:join([str(Cmd), format(Args)], " ")}).
61 gen_server:cast(Client, {asend, Cmd}).
63 gen_server:call(Client, disconnect).
65 get_all_results(Client) ->
66 gen_server:call(Client, get_all_results).
67 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
71 %% gen_server callbacks
73 process_flag(trap_exit, true),
74 ConnectOptions = [list, {active, once}, {packet, line}, {nodelay, true}],
75 case gen_tcp:connect(Host, Port, ConnectOptions) of
77 {error, {socket_error, Why}};
79 {ok, #redis{socket=Socket, calls=0}}
82 handle_call({send, Cmd}, From, State) ->
83 gen_tcp:send(State#redis.socket, [Cmd|?EOL]),
84 {noreply, State#redis{reply_caller=fun(V) -> gen_server:reply(From, lists:nth(1, V)) end,
87 handle_call(disconnect, _From, State) ->
88 {stop, normal, ok, State};
89 handle_call(get_all_results, From, State) ->
90 case State#redis.calls of
92 % answers came earlier than we could start listening...
93 % Very unlikely but totally possible.
94 {reply, lists:reverse(State#redis.results), State#redis{results=[], calls=0}};
96 % We are here earlier than results came, so just make
97 % ourselves wait until stuff is ready.
98 {noreply, State#redis{reply_caller=fun(V) -> gen_server:reply(From, V) end}}
100 handle_call(_, _From, State) -> {noreply, State}.
103 handle_cast({asend, Cmd}, State) ->
104 gen_tcp:send(State#redis.socket, [Cmd|?EOL]),
106 handle_cast({send, Cmd}, State=#redis{remaining=Remaining, calls=Calls}) ->
107 % how we should do here: if remaining is already != 0 then we'll
108 % let handle_info take care of keeping track how many remaining things
109 % there are. If instead it's 0 we are the first call so let's just
111 gen_tcp:send(State#redis.socket, [Cmd|?EOL]),
114 {noreply, State#redis{remaining=1, calls=1}};
116 {noreply, State#redis{calls=Calls+1}}
118 handle_cast(_Msg, State) -> {noreply, State}.
122 string:substr(S, 1, length(S)-2);
126 % This function helps with pipelining by creating a pubsub system with
127 % the caller. The caller could submit multiple requests and not listen
128 % until later when all or some of them have been answered, at that
129 % point 2 conditions can be true:
130 % 1) We still need to process more things in this response chain
131 % 2) We are finished.
133 % And these 2 are together with the following 2:
134 % 1) We called get_all_results before the end of the responses.
135 % 2) We called get_all_results after the end of the responses.
137 % If there's stuff missing in the chain we just push results, this also
138 % happens when there's nothing more to process BUT we haven't requested
140 % In case we have requested results: if requests are not yet ready we
141 % just push them, otherwise we finally answer all of them.
142 save_or_reply(Result, State=#redis{calls=Calls, results=Results, reply_caller=ReplyCaller}) ->
145 % We don't reverse results here because if all the requests
146 % come in and then we submit another one, if we reverse
147 % they will be scrambled in the results field of the record.
148 % instead if we wait just before we reply they will be
149 % in the right order.
150 FullResults = [Result|Results],
151 NewState = case ReplyCaller of
153 State#redis{results=FullResults};
155 ReplyCaller(lists:reverse(FullResults)),
156 State#redis{results=[]}
158 NewState#redis{remaining=0, pstate=empty,
159 reply_caller=undefined, buffer=[],
162 State#redis{results=[Result|Results], remaining=1, pstate=empty, buffer=[], calls=Calls}
166 handle_info({tcp, Socket, Data}, State=#redis{calls=Calls}) ->
167 Trimmed = trim2(Data),
168 NewState = case {State#redis.remaining-1, proto:parse(State#redis.pstate, Trimmed)} of
169 % This line contained an error code. Next line will hold
170 % The error message that we will parse.
172 State#redis{remaining=1, pstate=error};
174 % The stateful parser just started and tells us the number
175 % of results that we will have to parse for those calls
176 % where more than one result is expected. The next
177 % line will start with the first item to read.
178 {0, {hold, Remaining}} ->
181 save_or_reply(nil, State#redis{calls=Calls-1});
183 % Reset the remaining value to the number of results that we need to parse.
184 State#redis{remaining=Remaining, pstate=read}
187 % We either had only one thing to read or we are at the
188 % end of the stuff that we need to read. either way
189 % just pack up the buffer and send.
190 {0, {read, NBytes}} ->
191 CurrentValue = case NBytes of
195 inet:setopts(Socket, [{packet, 0}]), % go into raw mode to read bytes
196 CV = trim2(gen_tcp:recv(Socket, NBytes+2)), % also consume the \r\n
197 inet:setopts(Socket, [{packet, line}]), % go back to line mode
200 OldBuffer = State#redis.buffer,
203 save_or_reply(CurrentValue, State#redis{calls=Calls-1});
205 save_or_reply(lists:reverse([CurrentValue|OldBuffer]), State#redis{calls=Calls-1})
208 % The stateful parser tells us to read some bytes
209 {N, {read, NBytes}} ->
210 % annoying repetition... I should reuse this code.
211 CurrentValue = case NBytes of
215 inet:setopts(Socket, [{packet, 0}]), % go into raw mode to read bytes
216 CV = trim2(gen_tcp:recv(Socket, NBytes+2)), % also consume the \r\n
217 inet:setopts(Socket, [{packet, line}]), % go back to line mode
220 OldBuffer = State#redis.buffer,
221 State#redis{remaining=N, buffer=[CurrentValue|OldBuffer], pstate=read};
224 % Simple return values contained in a single line
226 save_or_reply(Value, State#redis{calls=Calls-1})
229 inet:setopts(Socket, [{active, once}]),
231 handle_info(_Info, State) -> {noreply, State}.
234 terminate(_Reason, State) ->
235 case State#redis.socket of
239 gen_tcp:close(Socket)
244 code_change(_OldVsn, State, _Extra) -> {ok, State}.
245 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%