emqx_request_handler.erl 3.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. %% Copyright (c) 2013-2019 EMQ Technologies Co., Ltd. All Rights Reserved.
  2. %%
  3. %% Licensed under the Apache License, Version 2.0 (the "License");
  4. %% you may not use this file except in compliance with the License.
  5. %% You may obtain a copy of the License at
  6. %%
  7. %% http://www.apache.org/licenses/LICENSE-2.0
  8. %%
  9. %% Unless required by applicable law or agreed to in writing, software
  10. %% distributed under the License is distributed on an "AS IS" BASIS,
  11. %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. %% See the License for the specific language governing permissions and
  13. %% limitations under the License.
  14. %% @doc This module implements a request handler based on emqx_client.
  15. %% A request handler is a MQTT client which subscribes to a request topic,
  16. %% processes the requests then send response to another topic which is
  17. %% subscribed by the request sender.
  18. %% This code is in test directory because request and response are pure
  19. %% client-side behaviours.
  20. -module(emqx_request_handler).
  21. -export([start_link/4, stop/1]).
  22. -type qos() :: emqx_mqtt_types:qos_name() | emqx_mqtt_types:qos().
  23. -type topic() :: emqx_topic:topic().
  24. -type handler() :: fun((CorrData :: binary(), ReqPayload :: binary()) -> RspPayload :: binary()).
  25. -spec start_link(topic(), qos(), handler(), emqx_client:options()) ->
  26. {ok, pid()} | {error, any()}.
  27. start_link(RequestTopic, QoS, RequestHandler, Options0) ->
  28. Parent = self(),
  29. MsgHandler = make_msg_handler(RequestHandler, Parent),
  30. Options = [{msg_handler, MsgHandler} | Options0],
  31. case emqx_client:start_link(Options) of
  32. {ok, Pid} ->
  33. {ok, _} = emqx_client:connect(Pid),
  34. try subscribe(Pid, RequestTopic, QoS) of
  35. ok -> {ok, Pid};
  36. {error, _} = Error -> Error
  37. catch
  38. C : E : S ->
  39. emqx_client:stop(Pid),
  40. {error, {C, E, S}}
  41. end;
  42. {error, _} = Error -> Error
  43. end.
  44. stop(Pid) ->
  45. emqx_client:disconnect(Pid).
  46. make_msg_handler(RequestHandler, Parent) ->
  47. #{publish => fun(Msg) -> handle_msg(Msg, RequestHandler, Parent) end,
  48. puback => fun(_Ack) -> ok end,
  49. disconnected => fun(_Reason) -> ok end
  50. }.
  51. handle_msg(ReqMsg, RequestHandler, Parent) ->
  52. #{qos := QoS, properties := Props, payload := ReqPayload} = ReqMsg,
  53. case maps:find('Response-Topic', Props) of
  54. {ok, RspTopic} when RspTopic =/= <<>> ->
  55. CorrData = maps:get('Correlation-Data', Props),
  56. RspProps = maps:without(['Response-Topic'], Props),
  57. RspPayload = RequestHandler(CorrData, ReqPayload),
  58. emqx_logger:debug("~p sending response msg to topic ~s with~n"
  59. "corr-data=~p~npayload=~p",
  60. [?MODULE, RspTopic, CorrData, RspPayload]),
  61. ok = send_response(RspTopic, RspProps, RspPayload, QoS);
  62. _ ->
  63. Parent ! {discarded, ReqPayload},
  64. ok
  65. end.
  66. send_response(Topic, Properties, Payload, QoS) ->
  67. %% This function is evaluated by emqx_client itself.
  68. %% hence delegate to another temp process for the loopback gen_statem call.
  69. Client = self(),
  70. _ = spawn_link(fun() ->
  71. case emqx_client:publish(Client, Topic, Properties, Payload, [{qos, QoS}]) of
  72. ok -> ok;
  73. {ok, _} -> ok;
  74. {error, Reason} -> exit({failed_to_publish_response, Reason})
  75. end
  76. end),
  77. ok.
  78. subscribe(Client, Topic, QoS) ->
  79. {ok, _Props, _QoS} =
  80. emqx_client:subscribe(Client, [{Topic, [{rh, 2}, {rap, false},
  81. {nl, true}, {qos, QoS}]}]),
  82. ok.