cowboy_stream.erl 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  1. %% Copyright (c) 2015-2017, Loïc Hoguin <essen@ninenines.eu>
  2. %%
  3. %% Permission to use, copy, modify, and/or distribute this software for any
  4. %% purpose with or without fee is hereby granted, provided that the above
  5. %% copyright notice and this permission notice appear in all copies.
  6. %%
  7. %% THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  8. %% WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  9. %% MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  10. %% ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  11. %% WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  12. %% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  13. %% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  14. -module(cowboy_stream).
  15. -type state() :: any().
  16. -type human_reason() :: atom().
  17. -type streamid() :: any().
  18. -export_type([streamid/0]).
  19. -type fin() :: fin | nofin.
  20. -export_type([fin/0]).
  21. %% @todo Perhaps it makes more sense to have resp_body in this module?
  22. -type resp_command()
  23. :: {response, cowboy:http_status(), cowboy:http_headers(), cowboy_req:resp_body()}.
  24. -export_type([resp_command/0]).
  25. -type commands() :: [resp_command()
  26. | {headers, cowboy:http_status(), cowboy:http_headers()}
  27. | {data, fin(), iodata()}
  28. | {push, binary(), binary(), binary(), inet:port_number(),
  29. binary(), binary(), cowboy:http_headers()}
  30. | {flow, pos_integer()}
  31. | {spawn, pid(), timeout()}
  32. | {error_response, cowboy:http_status(), cowboy:http_headers(), iodata()}
  33. | {switch_protocol, cowboy:http_headers(), module(), state()}
  34. | {internal_error, any(), human_reason()}
  35. | stop].
  36. -export_type([commands/0]).
  37. -type reason() :: normal | switch_protocol
  38. | {internal_error, timeout | {error | exit | throw, any()}, human_reason()}
  39. | {socket_error, closed | atom(), human_reason()}
  40. | {stream_error, cow_http2:error(), human_reason()}
  41. | {connection_error, cow_http2:error(), human_reason()}
  42. | {stop, cow_http2:frame(), human_reason()}.
  43. -export_type([reason/0]).
  44. -type partial_req() :: map(). %% @todo Take what's in cowboy_req with everything? optional.
  45. -export_type([partial_req/0]).
  46. -callback init(streamid(), cowboy_req:req(), cowboy:opts()) -> {commands(), state()}.
  47. -callback data(streamid(), fin(), binary(), State) -> {commands(), State} when State::state().
  48. -callback info(streamid(), any(), State) -> {commands(), State} when State::state().
  49. -callback terminate(streamid(), reason(), state()) -> any().
  50. -callback early_error(streamid(), reason(), partial_req(), Resp, cowboy:opts())
  51. -> Resp when Resp::resp_command().
  52. %% @todo To optimize the number of active timers we could have a command
  53. %% that enables a timeout that is called in the absence of any other call,
  54. %% similar to what gen_server does. However the nice thing about this is
  55. %% that the connection process can keep a single timer around (the same
  56. %% one that would be used to detect half-closed sockets) and use this
  57. %% timer and other events to trigger the timeout in streams at their
  58. %% intended time.
  59. %%
  60. %% This same timer can be used to try and send PING frames to help detect
  61. %% that the connection is indeed unresponsive.
  62. -export([init/3]).
  63. -export([data/4]).
  64. -export([info/3]).
  65. -export([terminate/3]).
  66. -export([early_error/5]).
  67. -export([report_error/5]).
  68. %% Note that this and other functions in this module do NOT catch
  69. %% exceptions. We want the exception to go all the way down to the
  70. %% protocol code.
  71. %%
  72. %% OK the failure scenario is not so clear. The problem is
  73. %% that the failure at any point in init/3 will result in the
  74. %% corresponding state being lost. I am unfortunately not
  75. %% confident we can do anything about this. If the crashing
  76. %% handler just created a process, we'll never know about it.
  77. %% Therefore at this time I choose to leave all failure handling
  78. %% to the protocol process.
  79. %%
  80. %% Note that a failure in init/3 will result in terminate/3
  81. %% NOT being called. This is because the state is not available.
  82. -spec init(streamid(), cowboy_req:req(), cowboy:opts())
  83. -> {commands(), {module(), state()} | undefined}.
  84. init(StreamID, Req, Opts) ->
  85. case maps:get(stream_handlers, Opts, [cowboy_stream_h]) of
  86. [] ->
  87. {[], undefined};
  88. [Handler|Tail] ->
  89. %% We call the next handler and remove it from the list of
  90. %% stream handlers. This means that handlers that run after
  91. %% it have no knowledge it exists. Should user require this
  92. %% knowledge they can just define a separate option that will
  93. %% be left untouched.
  94. {Commands, State} = Handler:init(StreamID, Req, Opts#{stream_handlers => Tail}),
  95. {Commands, {Handler, State}}
  96. end.
  97. -spec data(streamid(), fin(), binary(), {Handler, State} | undefined)
  98. -> {commands(), {Handler, State} | undefined}
  99. when Handler::module(), State::state().
  100. data(_, _, _, undefined) ->
  101. {[], undefined};
  102. data(StreamID, IsFin, Data, {Handler, State0}) ->
  103. {Commands, State} = Handler:data(StreamID, IsFin, Data, State0),
  104. {Commands, {Handler, State}}.
  105. -spec info(streamid(), any(), {Handler, State} | undefined)
  106. -> {commands(), {Handler, State} | undefined}
  107. when Handler::module(), State::state().
  108. info(_, _, undefined) ->
  109. {[], undefined};
  110. info(StreamID, Info, {Handler, State0}) ->
  111. {Commands, State} = Handler:info(StreamID, Info, State0),
  112. {Commands, {Handler, State}}.
  113. -spec terminate(streamid(), reason(), {module(), state()} | undefined) -> ok.
  114. terminate(_, _, undefined) ->
  115. ok;
  116. terminate(StreamID, Reason, {Handler, State}) ->
  117. _ = Handler:terminate(StreamID, Reason, State),
  118. ok.
  119. -spec early_error(streamid(), reason(), partial_req(), Resp, cowboy:opts())
  120. -> Resp when Resp::resp_command().
  121. early_error(StreamID, Reason, PartialReq, Resp, Opts) ->
  122. case maps:get(stream_handlers, Opts, [cowboy_stream_h]) of
  123. [] ->
  124. Resp;
  125. [Handler|Tail] ->
  126. %% This is the same behavior as in init/3.
  127. Handler:early_error(StreamID, Reason,
  128. PartialReq, Resp, Opts#{stream_handlers => Tail})
  129. end.
  130. -spec report_error(atom(), list(), error | exit | throw, any(), list()) -> ok.
  131. report_error(init, [StreamID, Req, Opts], Class, Exception, Stacktrace) ->
  132. error_logger:error_msg(
  133. "Unhandled exception ~p:~p in cowboy_stream:init(~p, Req, Opts)~n"
  134. "Stacktrace: ~p~n"
  135. "Req: ~p~n"
  136. "Opts: ~p~n",
  137. [Class, Exception, StreamID, Stacktrace, Req, Opts]);
  138. report_error(data, [StreamID, IsFin, Data, State], Class, Exception, Stacktrace) ->
  139. error_logger:error_msg(
  140. "Unhandled exception ~p:~p in cowboy_stream:data(~p, ~p, Data, State)~n"
  141. "Stacktrace: ~p~n"
  142. "Data: ~p~n"
  143. "State: ~p~n",
  144. [Class, Exception, StreamID, IsFin, Stacktrace, Data, State]);
  145. report_error(info, [StreamID, Msg, State], Class, Exception, Stacktrace) ->
  146. error_logger:error_msg(
  147. "Unhandled exception ~p:~p in cowboy_stream:info(~p, Msg, State)~n"
  148. "Stacktrace: ~p~n"
  149. "Msg: ~p~n"
  150. "State: ~p~n",
  151. [Class, Exception, StreamID, Stacktrace, Msg, State]);
  152. report_error(terminate, [StreamID, Reason, State], Class, Exception, Stacktrace) ->
  153. error_logger:error_msg(
  154. "Unhandled exception ~p:~p in cowboy_stream:terminate(~p, Reason, State)~n"
  155. "Stacktrace: ~p~n"
  156. "Reason: ~p~n"
  157. "State: ~p~n",
  158. [Class, Exception, StreamID, Stacktrace, Reason, State]);
  159. report_error(early_error, [StreamID, Reason, PartialReq, Resp, Opts], Class, Exception, Stacktrace) ->
  160. error_logger:error_msg(
  161. "Unhandled exception ~p:~p in cowboy_stream:early_error(~p, Reason, PartialReq, Resp, Opts)~n"
  162. "Stacktrace: ~p~n"
  163. "Reason: ~p~n"
  164. "PartialReq: ~p~n"
  165. "Resp: ~p~n"
  166. "Opts: ~p~n",
  167. [Class, Exception, StreamID, Stacktrace, Reason, PartialReq, Resp, Opts]);
  168. report_error(Callback, _, Class, Reason, Stacktrace) ->
  169. error_logger:error_msg(
  170. "Exception occurred in unknown callback ~p~n"
  171. "Reason: ~p:~p~n"
  172. "Stacktrace: ~p~n",
  173. [Callback, Class, Reason, Stacktrace]).