blob: d6508bb21bade5b2722b3ccb3f76566be17aef95 [file] [log] [blame]
David Reiss2c534032008-06-11 00:58:00 +00001%%%-------------------------------------------------------------------
2%%% File : thrift_client.erl
3%%% Author : Todd Lipcon <todd@lipcon.org>
4%%% Description : A client which connects to a thrift service
5%%%
6%%% Created : 24 Feb 2008 by Todd Lipcon <todd@lipcon.org>
7%%%-------------------------------------------------------------------
8-module(thrift_client).
9
10-behaviour(gen_server).
11
12%% API
David Reiss65cf7202008-06-11 01:12:20 +000013-export([start_link/2, start_link/3, start_link/4, call/3, send_call/3, close/1]).
David Reiss2c534032008-06-11 00:58:00 +000014
15%% gen_server callbacks
16-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
17 terminate/2, code_change/3]).
18
19
20-include("thrift_constants.hrl").
21-include("thrift_protocol.hrl").
22
David Reissad74b322008-06-11 01:03:29 +000023-record(state, {service, protocol, seqid}).
David Reiss2c534032008-06-11 00:58:00 +000024
25%%====================================================================
26%% API
27%%====================================================================
28%%--------------------------------------------------------------------
29%% Function: start_link() -> {ok,Pid} | ignore | {error,Error}
30%% Description: Starts the server
31%%--------------------------------------------------------------------
David Reissad74b322008-06-11 01:03:29 +000032start_link(Host, Port, Service) when is_integer(Port), is_atom(Service) ->
David Reiss914ebb42008-06-11 01:01:48 +000033 start_link(Host, Port, Service, []).
David Reiss4fd78182008-06-11 01:01:13 +000034
David Reissfc427af2008-06-11 01:11:57 +000035
36%%
37%% Splits client options into protocol options and transport options
38%%
39%% split_options([Options...]) -> {ProtocolOptions, TransportOptions}
40%%
41split_options(Options) ->
42 split_options(Options, [], []).
43
44split_options([], ProtoIn, TransIn) ->
45 {ProtoIn, TransIn};
46
47split_options([Opt = {OptKey, _} | Rest], ProtoIn, TransIn)
48 when OptKey =:= strict_read;
49 OptKey =:= strict_write ->
50 split_options(Rest, [Opt | ProtoIn], TransIn);
51
52split_options([Opt = {OptKey, _} | Rest], ProtoIn, TransIn)
53 when OptKey =:= framed;
54 OptKey =:= connect_timeout;
55 OptKey =:= sockopts ->
56 split_options(Rest, ProtoIn, [Opt | TransIn]).
57
58
59%% Backwards-compatible starter for the common-case of socket transports
David Reiss2fe905e2008-06-11 01:02:23 +000060start_link(Host, Port, Service, Options)
61 when is_integer(Port), is_atom(Service), is_list(Options) ->
David Reissfc427af2008-06-11 01:11:57 +000062 {ProtoOpts, TransOpts} = split_options(Options),
63
64 {ok, TransportFactory} =
65 thrift_socket_transport:new_transport_factory(Host, Port, TransOpts),
66
67 {ok, ProtocolFactory} = thrift_binary_protocol:new_protocol_factory(
68 TransportFactory, ProtoOpts),
69
David Reiss44f785e2008-06-11 01:03:37 +000070 start_link(ProtocolFactory, Service).
David Reissad74b322008-06-11 01:03:29 +000071
David Reissfc427af2008-06-11 01:11:57 +000072
David Reiss44f785e2008-06-11 01:03:37 +000073%% ProtocolFactory :: fun() -> thrift_protocol()
74start_link(ProtocolFactory, Service)
75 when is_function(ProtocolFactory), is_atom(Service) ->
David Reissad74b322008-06-11 01:03:29 +000076 case gen_server:start_link(?MODULE, [Service], []) of
David Reisse5a4d0c2008-06-11 01:02:10 +000077 {ok, Pid} ->
David Reiss44f785e2008-06-11 01:03:37 +000078 case gen_server:call(Pid, {connect, ProtocolFactory}) of
David Reisse5a4d0c2008-06-11 01:02:10 +000079 ok ->
80 {ok, Pid};
81 Error ->
82 Error
83 end;
84 Else ->
85 Else
86 end.
David Reiss2c534032008-06-11 00:58:00 +000087
David Reiss2c534032008-06-11 00:58:00 +000088call(Client, Function, Args)
89 when is_pid(Client), is_atom(Function), is_list(Args) ->
90 case gen_server:call(Client, {call, Function, Args}) of
91 R = {ok, _} -> R;
92 R = {error, _} -> R;
93 {exception, Exception} -> throw(Exception)
94 end.
David Reiss2c534032008-06-11 00:58:00 +000095
David Reiss65cf7202008-06-11 01:12:20 +000096%% Sends a function call but does not read the result. This is useful
97%% if you're trying to log non-async function calls to write-only
98%% transports like thrift_disk_log_transport.
99send_call(Client, Function, Args)
100 when is_pid(Client), is_atom(Function), is_list(Args) ->
101 gen_server:call(Client, {send_call, Function, Args}).
102
103
David Reiss464e3002008-06-11 01:00:45 +0000104close(Client) when is_pid(Client) ->
David Reiss6f1cd532008-06-11 01:01:21 +0000105 gen_server:cast(Client, close).
David Reiss464e3002008-06-11 01:00:45 +0000106
David Reiss2c534032008-06-11 00:58:00 +0000107%%====================================================================
108%% gen_server callbacks
109%%====================================================================
110
111%%--------------------------------------------------------------------
112%% Function: init(Args) -> {ok, State} |
113%% {ok, State, Timeout} |
114%% ignore |
115%% {stop, Reason}
116%% Description: Initiates the server
117%%--------------------------------------------------------------------
David Reissad74b322008-06-11 01:03:29 +0000118init([Service]) ->
119 {ok, #state{service = Service}}.
David Reiss2c534032008-06-11 00:58:00 +0000120
121%%--------------------------------------------------------------------
122%% Function: %% handle_call(Request, From, State) -> {reply, Reply, State} |
123%% {reply, Reply, State, Timeout} |
124%% {noreply, State} |
125%% {noreply, State, Timeout} |
126%% {stop, Reason, Reply, State} |
127%% {stop, Reason, State}
128%% Description: Handling call messages
129%%--------------------------------------------------------------------
David Reiss44f785e2008-06-11 01:03:37 +0000130handle_call({connect, ProtocolFactory}, _From,
David Reissad74b322008-06-11 01:03:29 +0000131 State = #state{service = Service}) ->
David Reiss44f785e2008-06-11 01:03:37 +0000132 case ProtocolFactory() of
David Reissad74b322008-06-11 01:03:29 +0000133 {ok, Protocol} ->
134 {reply, ok, State#state{protocol = Protocol,
135 seqid = 0}};
David Reisse5a4d0c2008-06-11 01:02:10 +0000136 Error ->
137 {stop, normal, Error, State}
138 end;
139
David Reiss65cf7202008-06-11 01:12:20 +0000140handle_call({call, Function, Args}, _From, State = #state{service = Service}) ->
141 Result = catch_function_exceptions(
142 fun() ->
143 ok = send_function_call(State, Function, Args),
144 receive_function_result(State, Function)
145 end,
146 Service),
147 {reply, Result, State};
David Reiss6b3e40f2008-06-11 00:59:03 +0000148
David Reiss65cf7202008-06-11 01:12:20 +0000149
150handle_call({send_call, Function, Args}, _From, State = #state{service = Service}) ->
151 Result = catch_function_exceptions(
152 fun() ->
153 send_function_call(State, Function, Args)
154 end,
155 Service),
David Reiss6f1cd532008-06-11 01:01:21 +0000156 {reply, Result, State}.
David Reiss2c534032008-06-11 00:58:00 +0000157
David Reiss65cf7202008-06-11 01:12:20 +0000158
159%% Helper function that catches exceptions thrown by sending or receiving
160%% a function and returns the correct response for call or send_only above.
161catch_function_exceptions(Fun, Service) ->
162 try
163 Fun()
164 catch
165 throw:{return, Return} ->
166 Return;
167 error:function_clause ->
168 ST = erlang:get_stacktrace(),
169 case hd(ST) of
170 {Service, function_info, [Function, _]} ->
171 {error, {no_function, Function}};
172 _ -> throw({error, {function_clause, ST}})
173 end
174 end.
175
176
David Reiss2c534032008-06-11 00:58:00 +0000177%%--------------------------------------------------------------------
178%% Function: handle_cast(Msg, State) -> {noreply, State} |
179%% {noreply, State, Timeout} |
180%% {stop, Reason, State}
181%% Description: Handling cast messages
182%%--------------------------------------------------------------------
David Reiss6f1cd532008-06-11 01:01:21 +0000183handle_cast(close, State=#state{protocol = Protocol}) ->
184%% error_logger:info_msg("thrift_client ~p received close", [self()]),
185 {stop,normal,State};
David Reiss2c534032008-06-11 00:58:00 +0000186handle_cast(_Msg, State) ->
187 {noreply, State}.
188
189%%--------------------------------------------------------------------
190%% Function: handle_info(Info, State) -> {noreply, State} |
191%% {noreply, State, Timeout} |
192%% {stop, Reason, State}
193%% Description: Handling all non call/cast messages
194%%--------------------------------------------------------------------
195handle_info(_Info, State) ->
196 {noreply, State}.
197
198%%--------------------------------------------------------------------
199%% Function: terminate(Reason, State) -> void()
200%% Description: This function is called by a gen_server when it is about to
201%% terminate. It should be the opposite of Module:init/1 and do any necessary
202%% cleaning up. When it returns, the gen_server terminates with Reason.
203%% The return value is ignored.
204%%--------------------------------------------------------------------
David Reisse5a4d0c2008-06-11 01:02:10 +0000205terminate(Reason, State = #state{protocol=undefined}) ->
206 ok;
207terminate(Reason, State = #state{protocol=Protocol}) ->
David Reiss464e3002008-06-11 01:00:45 +0000208 thrift_protocol:close_transport(Protocol),
David Reiss2c534032008-06-11 00:58:00 +0000209 ok.
210
211%%--------------------------------------------------------------------
212%% Func: code_change(OldVsn, State, Extra) -> {ok, NewState}
213%% Description: Convert process state when code is changed
214%%--------------------------------------------------------------------
215code_change(_OldVsn, State, _Extra) ->
216 {ok, State}.
217
218%%--------------------------------------------------------------------
219%%% Internal functions
220%%--------------------------------------------------------------------
221send_function_call(#state{protocol = Proto,
222 service = Service,
223 seqid = SeqId},
224 Function,
225 Args) ->
226 Params = Service:function_info(Function, params_type),
227 {struct, PList} = Params,
David Reissc5257452008-06-11 00:59:27 +0000228 if
229 length(PList) =/= length(Args) ->
David Reiss2c534032008-06-11 00:58:00 +0000230 throw({return, {error, {bad_args, Function, Args}}});
David Reissc5257452008-06-11 00:59:27 +0000231 true -> ok
David Reiss2c534032008-06-11 00:58:00 +0000232 end,
233
234 Begin = #protocol_message_begin{name = atom_to_list(Function),
235 type = ?tMessageType_CALL,
236 seqid = SeqId},
237 ok = thrift_protocol:write(Proto, Begin),
238 ok = thrift_protocol:write(Proto, {Params, list_to_tuple([Function | Args])}),
239 ok = thrift_protocol:write(Proto, message_end),
240 thrift_protocol:flush_transport(Proto),
241 ok.
242
David Reiss2c534032008-06-11 00:58:00 +0000243receive_function_result(State = #state{protocol = Proto,
244 service = Service},
245 Function) ->
246 ResultType = Service:function_info(Function, reply_type),
247 read_result(State, Function, ResultType).
248
249read_result(_State,
250 _Function,
251 async_void) ->
252 {ok, ok};
253
254read_result(State = #state{protocol = Proto,
255 seqid = SeqId},
256 Function,
257 ReplyType) ->
258 case thrift_protocol:read(Proto, message_begin) of
259 #protocol_message_begin{seqid = RetSeqId} when RetSeqId =/= SeqId ->
260 {error, {bad_seq_id, SeqId}};
David Reiss6b3e40f2008-06-11 00:59:03 +0000261
David Reiss2c534032008-06-11 00:58:00 +0000262 #protocol_message_begin{type = ?tMessageType_EXCEPTION} ->
263 handle_application_exception(State);
David Reiss6b3e40f2008-06-11 00:59:03 +0000264
David Reiss2c534032008-06-11 00:58:00 +0000265 #protocol_message_begin{type = ?tMessageType_REPLY} ->
266 handle_reply(State, Function, ReplyType)
267 end.
268
David Reiss2c534032008-06-11 00:58:00 +0000269handle_reply(State = #state{protocol = Proto,
270 service = Service},
271 Function,
272 ReplyType) ->
273 {struct, ExceptionFields} = Service:function_info(Function, exceptions),
274 ReplyStructDef = {struct, [{0, ReplyType}] ++ ExceptionFields},
David Reiss2c534032008-06-11 00:58:00 +0000275 {ok, Reply} = thrift_protocol:read(Proto, ReplyStructDef),
276 ReplyList = tuple_to_list(Reply),
277 true = length(ReplyList) == length(ExceptionFields) + 1,
278 ExceptionVals = tl(ReplyList),
279 Thrown = [X || X <- ExceptionVals,
280 X =/= undefined],
David Reiss2c534032008-06-11 00:58:00 +0000281 Result =
282 case Thrown of
283 [] when ReplyType == {struct, []} ->
284 {ok, ok};
285 [] ->
286 {ok, hd(ReplyList)};
287 [Exception] ->
288 {exception, Exception}
289 end,
290 ok = thrift_protocol:read(Proto, message_end),
291 Result.
David Reiss6b3e40f2008-06-11 00:59:03 +0000292
David Reiss55ff70f2008-06-11 00:58:25 +0000293handle_application_exception(State = #state{protocol = Proto}) ->
294 {ok, Exception} = thrift_protocol:read(Proto,
295 ?TApplicationException_Structure),
296 ok = thrift_protocol:read(Proto, message_end),
297 XRecord = list_to_tuple(
298 ['TApplicationException' | tuple_to_list(Exception)]),
David Reiss1af18682008-06-11 01:01:36 +0000299 error_logger:error_msg("X: ~p~n", [XRecord]),
David Reiss55ff70f2008-06-11 00:58:25 +0000300 true = is_record(XRecord, 'TApplicationException'),
301 {exception, XRecord}.