blob: c193946bb9fffb321a568e8b4337e82b897de74f [file] [log] [blame]
David Reissac549552008-06-10 22:56:59 +00001%%%-------------------------------------------------------------------
2%%% File : thrift_processor.erl
3%%% Author : <todd@lipcon.org>
4%%% Description :
5%%%
6%%% Created : 28 Jan 2008 by <todd@lipcon.org>
7%%%-------------------------------------------------------------------
8-module(thrift_processor).
9
10-export([start/4,init/4]).
11
12-include("thrift_constants.hrl").
13-include("thrift_protocol.hrl").
14
15-record(state, {handler, in_protocol, out_protocol, service}).
16
17start(IProt, OProt, Service, Handler) ->
18 spawn(thrift_processor, init, [IProt, OProt, Service, Handler]).
19
20init(IProt, OProt, Service, Handler) ->
21 io:format("Processor started~n"),
22 loop(#state{in_protocol = IProt,
23 out_protocol = OProt,
24 service = Service,
25 handler = Handler}).
26
27loop(State = #state{in_protocol = IProto,
28 out_protocol = OProto}) ->
David Reissae756f42008-06-10 22:57:11 +000029 case thrift_protocol:read(IProto, message_begin) of
30 #protocol_message_begin{name = Function,
31 type = ?tMessageType_CALL} ->
David Reissd93521b2008-06-10 22:58:07 +000032 ok= handle_function(State, list_to_atom(Function)),
David Reissae756f42008-06-10 22:57:11 +000033 loop(State);
34 {error, closed} ->
David Reiss76f0d112008-06-10 22:57:35 +000035 error_logger:info_msg("Client disconnected~n"),
David Reissae756f42008-06-10 22:57:11 +000036 ok
David Reissac549552008-06-10 22:56:59 +000037 end.
David Reissae756f42008-06-10 22:57:11 +000038
David Reiss1c1ca742008-06-10 22:57:21 +000039
40handle_function(State = #state{in_protocol = IProto,
41 out_protocol = OProto,
42 handler = Handler,
43 service = Service},
44 Function) ->
45 InParams = Service:function_info(Function, params_type),
46
47 {ok, Params} = thrift_protocol:read(IProto, InParams),
David Reiss76f0d112008-06-10 22:57:35 +000048
49 {Micro, Result} = timer:tc(Handler, handle_function, [Function, Params]),
50 error_logger:info_msg("Processed ~p(~p) in ~.4fms~n",
51 [Function, Params, Micro/1000.0]),
David Reiss1c1ca742008-06-10 22:57:21 +000052
53 ReplyType = Service:function_info(Function, reply_type),
54
55 case Result of
56 {reply, Reply} ->
David Reiss76f0d112008-06-10 22:57:35 +000057 StructName = atom_to_list(Function) ++ "_result",
David Reiss1c1ca742008-06-10 22:57:21 +000058 thrift_protocol:write(OProto, #protocol_message_begin{
David Reiss76f0d112008-06-10 22:57:35 +000059 name = StructName,
David Reissae756f42008-06-10 22:57:11 +000060 type = ?tMessageType_REPLY,
61 seqid = 0}),
David Reiss76f0d112008-06-10 22:57:35 +000062 thrift_protocol:write(OProto, {{struct, [{0, ReplyType}]}, {StructName, Reply}}),
David Reiss1c1ca742008-06-10 22:57:21 +000063 thrift_protocol:write(OProto, message_end)
64 end,
65 ok.