/elibs/thrift_service.erl

https://github.com/toddlipcon/dynomite · Erlang · 70 lines · 51 code · 16 blank · 3 comment · 0 complexity · f4480e0780fea7cd2921ea1fa08b7ce2 MD5 · raw file

  1. -module(thrift_service).
  2. -export([start_link/1, stop/1,
  3. handle_function/2,
  4. % Internal
  5. put/3,
  6. get/1,
  7. has/1,
  8. remove/1
  9. ]).
  10. -include("config.hrl").
  11. -include("dynomite_types.hrl").
  12. %%%%% EXTERNAL INTERFACE %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  13. start_link(#config{thrift_port = Port}) ->
  14. application:load(thrift),
  15. thrift_server:start_link(Port, dynomite_thrift, ?MODULE).
  16. stop(Server) ->
  17. thrift_server:stop(Server),
  18. ok.
  19. %%%%% THRIFT INTERFACE %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  20. handle_function(Function, Args) when is_atom(Function), is_tuple(Args) ->
  21. case apply(?MODULE, Function, tuple_to_list(Args)) of
  22. ok -> ok;
  23. Reply -> {reply, Reply}
  24. end.
  25. put(Key, ContextData, Data) when
  26. is_binary(Key),
  27. (ContextData =:= undefined orelse is_binary(ContextData)),
  28. is_binary(Data) ->
  29. Context = if
  30. ContextData =:= undefined -> [];
  31. erlang:byte_size(ContextData) > 0 -> binary_to_term(ContextData);
  32. true -> []
  33. end,
  34. case mediator:put(binary_to_list(Key), Context, Data) of
  35. {ok, N} -> N;
  36. {failure, Reason} -> throw(#failureException{message = iolist_to_binary(Reason)})
  37. end.
  38. get(Key) when is_binary(Key) ->
  39. case mediator:get(binary_to_list(Key)) of
  40. {ok, not_found} -> #getResult{results = []};
  41. {ok, {Context, Values}} ->
  42. #getResult{context = term_to_binary(Context),
  43. results = Values};
  44. {failure, Error} ->
  45. throw(#failureException{message = iolist_to_binary(Error)})
  46. end.
  47. has(Key) when is_binary(Key) ->
  48. case mediator:has_key(binary_to_list(Key)) of
  49. {ok, {Bool, N}} when is_boolean(Bool) ->
  50. N
  51. end.
  52. remove(Key) when is_binary(Key) ->
  53. {ok, N} = mediator:delete(binary_to_list(Key)),
  54. N.