blob: 5099829bb3de2d7287f9f1b617fca28fa6ce7872 [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 Reissad74b322008-06-11 01:03:29 +000013-export([start_link/2, start_link/3, start_link/4, 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 Reiss464e3002008-06-11 01:00:45 +000096close(Client) when is_pid(Client) ->
David Reiss6f1cd532008-06-11 01:01:21 +000097 gen_server:cast(Client, close).
David Reiss464e3002008-06-11 01:00:45 +000098
David Reiss2c534032008-06-11 00:58:00 +000099%%====================================================================
100%% gen_server callbacks
101%%====================================================================
102
103%%--------------------------------------------------------------------
104%% Function: init(Args) -> {ok, State} |
105%% {ok, State, Timeout} |
106%% ignore |
107%% {stop, Reason}
108%% Description: Initiates the server
109%%--------------------------------------------------------------------
David Reissad74b322008-06-11 01:03:29 +0000110init([Service]) ->
111 {ok, #state{service = Service}}.
David Reiss2c534032008-06-11 00:58:00 +0000112
113%%--------------------------------------------------------------------
114%% Function: %% handle_call(Request, From, State) -> {reply, Reply, State} |
115%% {reply, Reply, State, Timeout} |
116%% {noreply, State} |
117%% {noreply, State, Timeout} |
118%% {stop, Reason, Reply, State} |
119%% {stop, Reason, State}
120%% Description: Handling call messages
121%%--------------------------------------------------------------------
David Reiss44f785e2008-06-11 01:03:37 +0000122handle_call({connect, ProtocolFactory}, _From,
David Reissad74b322008-06-11 01:03:29 +0000123 State = #state{service = Service}) ->
David Reiss44f785e2008-06-11 01:03:37 +0000124 case ProtocolFactory() of
David Reissad74b322008-06-11 01:03:29 +0000125 {ok, Protocol} ->
126 {reply, ok, State#state{protocol = Protocol,
127 seqid = 0}};
David Reisse5a4d0c2008-06-11 01:02:10 +0000128 Error ->
129 {stop, normal, Error, State}
130 end;
131
David Reiss2c534032008-06-11 00:58:00 +0000132handle_call({call, Function, Args}, _From, State = #state{service = Service,
133 protocol = Protocol,
134 seqid = SeqId}) ->
135 Result =
136 try
137 ok = send_function_call(State, Function, Args),
138 receive_function_result(State, Function)
139 catch
140 throw:{return, Return} ->
141 Return;
142 error:function_clause ->
143 ST = erlang:get_stacktrace(),
144 case hd(ST) of
145 {Service, function_info, [Function, _]} ->
146 {error, {no_function, Function}};
147 _ -> throw({error, {function_clause, ST}})
148 end
149 end,
David Reiss6b3e40f2008-06-11 00:59:03 +0000150
David Reiss6f1cd532008-06-11 01:01:21 +0000151 {reply, Result, State}.
David Reiss2c534032008-06-11 00:58:00 +0000152
153%%--------------------------------------------------------------------
154%% Function: handle_cast(Msg, State) -> {noreply, State} |
155%% {noreply, State, Timeout} |
156%% {stop, Reason, State}
157%% Description: Handling cast messages
158%%--------------------------------------------------------------------
David Reiss6f1cd532008-06-11 01:01:21 +0000159handle_cast(close, State=#state{protocol = Protocol}) ->
160%% error_logger:info_msg("thrift_client ~p received close", [self()]),
161 {stop,normal,State};
David Reiss2c534032008-06-11 00:58:00 +0000162handle_cast(_Msg, State) ->
163 {noreply, State}.
164
165%%--------------------------------------------------------------------
166%% Function: handle_info(Info, State) -> {noreply, State} |
167%% {noreply, State, Timeout} |
168%% {stop, Reason, State}
169%% Description: Handling all non call/cast messages
170%%--------------------------------------------------------------------
171handle_info(_Info, State) ->
172 {noreply, State}.
173
174%%--------------------------------------------------------------------
175%% Function: terminate(Reason, State) -> void()
176%% Description: This function is called by a gen_server when it is about to
177%% terminate. It should be the opposite of Module:init/1 and do any necessary
178%% cleaning up. When it returns, the gen_server terminates with Reason.
179%% The return value is ignored.
180%%--------------------------------------------------------------------
David Reisse5a4d0c2008-06-11 01:02:10 +0000181terminate(Reason, State = #state{protocol=undefined}) ->
182 ok;
183terminate(Reason, State = #state{protocol=Protocol}) ->
David Reiss464e3002008-06-11 01:00:45 +0000184 thrift_protocol:close_transport(Protocol),
David Reiss2c534032008-06-11 00:58:00 +0000185 ok.
186
187%%--------------------------------------------------------------------
188%% Func: code_change(OldVsn, State, Extra) -> {ok, NewState}
189%% Description: Convert process state when code is changed
190%%--------------------------------------------------------------------
191code_change(_OldVsn, State, _Extra) ->
192 {ok, State}.
193
194%%--------------------------------------------------------------------
195%%% Internal functions
196%%--------------------------------------------------------------------
197send_function_call(#state{protocol = Proto,
198 service = Service,
199 seqid = SeqId},
200 Function,
201 Args) ->
202 Params = Service:function_info(Function, params_type),
203 {struct, PList} = Params,
David Reissc5257452008-06-11 00:59:27 +0000204 if
205 length(PList) =/= length(Args) ->
David Reiss2c534032008-06-11 00:58:00 +0000206 throw({return, {error, {bad_args, Function, Args}}});
David Reissc5257452008-06-11 00:59:27 +0000207 true -> ok
David Reiss2c534032008-06-11 00:58:00 +0000208 end,
209
210 Begin = #protocol_message_begin{name = atom_to_list(Function),
211 type = ?tMessageType_CALL,
212 seqid = SeqId},
213 ok = thrift_protocol:write(Proto, Begin),
214 ok = thrift_protocol:write(Proto, {Params, list_to_tuple([Function | Args])}),
215 ok = thrift_protocol:write(Proto, message_end),
216 thrift_protocol:flush_transport(Proto),
217 ok.
218
David Reiss2c534032008-06-11 00:58:00 +0000219receive_function_result(State = #state{protocol = Proto,
220 service = Service},
221 Function) ->
222 ResultType = Service:function_info(Function, reply_type),
223 read_result(State, Function, ResultType).
224
225read_result(_State,
226 _Function,
227 async_void) ->
228 {ok, ok};
229
230read_result(State = #state{protocol = Proto,
231 seqid = SeqId},
232 Function,
233 ReplyType) ->
234 case thrift_protocol:read(Proto, message_begin) of
235 #protocol_message_begin{seqid = RetSeqId} when RetSeqId =/= SeqId ->
236 {error, {bad_seq_id, SeqId}};
David Reiss6b3e40f2008-06-11 00:59:03 +0000237
David Reiss2c534032008-06-11 00:58:00 +0000238 #protocol_message_begin{type = ?tMessageType_EXCEPTION} ->
239 handle_application_exception(State);
David Reiss6b3e40f2008-06-11 00:59:03 +0000240
David Reiss2c534032008-06-11 00:58:00 +0000241 #protocol_message_begin{type = ?tMessageType_REPLY} ->
242 handle_reply(State, Function, ReplyType)
243 end.
244
David Reiss2c534032008-06-11 00:58:00 +0000245handle_reply(State = #state{protocol = Proto,
246 service = Service},
247 Function,
248 ReplyType) ->
249 {struct, ExceptionFields} = Service:function_info(Function, exceptions),
250 ReplyStructDef = {struct, [{0, ReplyType}] ++ ExceptionFields},
David Reiss2c534032008-06-11 00:58:00 +0000251 {ok, Reply} = thrift_protocol:read(Proto, ReplyStructDef),
252 ReplyList = tuple_to_list(Reply),
253 true = length(ReplyList) == length(ExceptionFields) + 1,
254 ExceptionVals = tl(ReplyList),
255 Thrown = [X || X <- ExceptionVals,
256 X =/= undefined],
David Reiss2c534032008-06-11 00:58:00 +0000257 Result =
258 case Thrown of
259 [] when ReplyType == {struct, []} ->
260 {ok, ok};
261 [] ->
262 {ok, hd(ReplyList)};
263 [Exception] ->
264 {exception, Exception}
265 end,
266 ok = thrift_protocol:read(Proto, message_end),
267 Result.
David Reiss6b3e40f2008-06-11 00:59:03 +0000268
David Reiss55ff70f2008-06-11 00:58:25 +0000269handle_application_exception(State = #state{protocol = Proto}) ->
270 {ok, Exception} = thrift_protocol:read(Proto,
271 ?TApplicationException_Structure),
272 ok = thrift_protocol:read(Proto, message_end),
273 XRecord = list_to_tuple(
274 ['TApplicationException' | tuple_to_list(Exception)]),
David Reiss1af18682008-06-11 01:01:36 +0000275 error_logger:error_msg("X: ~p~n", [XRecord]),
David Reiss55ff70f2008-06-11 00:58:25 +0000276 true = is_record(XRecord, 'TApplicationException'),
277 {exception, XRecord}.