cowboy_stream.erl 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  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() :: [{inform, cowboy:http_status(), cowboy:http_headers()}
  26. | resp_command()
  27. | {headers, cowboy:http_status(), cowboy:http_headers()}
  28. | {data, fin(), cowboy_req:resp_body()}
  29. | {trailers, cowboy:http_headers()}
  30. | {push, binary(), binary(), binary(), inet:port_number(),
  31. binary(), binary(), cowboy:http_headers()}
  32. | {flow, pos_integer()}
  33. | {spawn, pid(), timeout()}
  34. | {error_response, cowboy:http_status(), cowboy:http_headers(), iodata()}
  35. | {switch_protocol, cowboy:http_headers(), module(), state()}
  36. | {internal_error, any(), human_reason()}
  37. | {set_options, map()}
  38. | {log, logger:level(), io:format(), list()}
  39. | stop].
  40. -export_type([commands/0]).
  41. -type reason() :: normal | switch_protocol
  42. | {internal_error, timeout | {error | exit | throw, any()}, human_reason()}
  43. | {socket_error, closed | atom(), human_reason()}
  44. | {stream_error, cow_http2:error(), human_reason()}
  45. | {connection_error, cow_http2:error(), human_reason()}
  46. | {stop, cow_http2:frame() | {exit, any()}, human_reason()}.
  47. -export_type([reason/0]).
  48. -type partial_req() :: map(). %% @todo Take what's in cowboy_req with everything? optional.
  49. -export_type([partial_req/0]).
  50. -callback init(streamid(), cowboy_req:req(), cowboy:opts()) -> {commands(), state()}.
  51. -callback data(streamid(), fin(), binary(), State) -> {commands(), State} when State::state().
  52. -callback info(streamid(), any(), State) -> {commands(), State} when State::state().
  53. -callback terminate(streamid(), reason(), state()) -> any().
  54. -callback early_error(streamid(), reason(), partial_req(), Resp, cowboy:opts())
  55. -> Resp when Resp::resp_command().
  56. %% @todo To optimize the number of active timers we could have a command
  57. %% that enables a timeout that is called in the absence of any other call,
  58. %% similar to what gen_server does. However the nice thing about this is
  59. %% that the connection process can keep a single timer around (the same
  60. %% one that would be used to detect half-closed sockets) and use this
  61. %% timer and other events to trigger the timeout in streams at their
  62. %% intended time.
  63. %%
  64. %% This same timer can be used to try and send PING frames to help detect
  65. %% that the connection is indeed unresponsive.
  66. -export([init/3]).
  67. -export([data/4]).
  68. -export([info/3]).
  69. -export([terminate/3]).
  70. -export([early_error/5]).
  71. -export([make_error_log/5]).
  72. %% Note that this and other functions in this module do NOT catch
  73. %% exceptions. We want the exception to go all the way down to the
  74. %% protocol code.
  75. %%
  76. %% OK the failure scenario is not so clear. The problem is
  77. %% that the failure at any point in init/3 will result in the
  78. %% corresponding state being lost. I am unfortunately not
  79. %% confident we can do anything about this. If the crashing
  80. %% handler just created a process, we'll never know about it.
  81. %% Therefore at this time I choose to leave all failure handling
  82. %% to the protocol process.
  83. %%
  84. %% Note that a failure in init/3 will result in terminate/3
  85. %% NOT being called. This is because the state is not available.
  86. -spec init(streamid(), cowboy_req:req(), cowboy:opts())
  87. -> {commands(), {module(), state()} | undefined}.
  88. init(StreamID, Req, Opts) ->
  89. case maps:get(stream_handlers, Opts, [cowboy_stream_h]) of
  90. [] ->
  91. {[], undefined};
  92. [Handler|Tail] ->
  93. %% We call the next handler and remove it from the list of
  94. %% stream handlers. This means that handlers that run after
  95. %% it have no knowledge it exists. Should user require this
  96. %% knowledge they can just define a separate option that will
  97. %% be left untouched.
  98. {Commands, State} = Handler:init(StreamID, Req, Opts#{stream_handlers => Tail}),
  99. {Commands, {Handler, State}}
  100. end.
  101. -spec data(streamid(), fin(), binary(), {Handler, State} | undefined)
  102. -> {commands(), {Handler, State} | undefined}
  103. when Handler::module(), State::state().
  104. data(_, _, _, undefined) ->
  105. {[], undefined};
  106. data(StreamID, IsFin, Data, {Handler, State0}) ->
  107. {Commands, State} = Handler:data(StreamID, IsFin, Data, State0),
  108. {Commands, {Handler, State}}.
  109. -spec info(streamid(), any(), {Handler, State} | undefined)
  110. -> {commands(), {Handler, State} | undefined}
  111. when Handler::module(), State::state().
  112. info(_, _, undefined) ->
  113. {[], undefined};
  114. info(StreamID, Info, {Handler, State0}) ->
  115. {Commands, State} = Handler:info(StreamID, Info, State0),
  116. {Commands, {Handler, State}}.
  117. -spec terminate(streamid(), reason(), {module(), state()} | undefined) -> ok.
  118. terminate(_, _, undefined) ->
  119. ok;
  120. terminate(StreamID, Reason, {Handler, State}) ->
  121. _ = Handler:terminate(StreamID, Reason, State),
  122. ok.
  123. -spec early_error(streamid(), reason(), partial_req(), Resp, cowboy:opts())
  124. -> Resp when Resp::resp_command().
  125. early_error(StreamID, Reason, PartialReq, Resp, Opts) ->
  126. case maps:get(stream_handlers, Opts, [cowboy_stream_h]) of
  127. [] ->
  128. Resp;
  129. [Handler|Tail] ->
  130. %% This is the same behavior as in init/3.
  131. Handler:early_error(StreamID, Reason,
  132. PartialReq, Resp, Opts#{stream_handlers => Tail})
  133. end.
  134. -spec make_error_log(init | data | info | terminate | early_error,
  135. list(), error | exit | throw, any(), list())
  136. -> {log, error, string(), list()}.
  137. make_error_log(init, [StreamID, Req, Opts], Class, Exception, Stacktrace) ->
  138. {log, error,
  139. "Unhandled exception ~p:~p in cowboy_stream:init(~p, Req, Opts)~n"
  140. "Stacktrace: ~p~n"
  141. "Req: ~p~n"
  142. "Opts: ~p~n",
  143. [Class, Exception, StreamID, Stacktrace, Req, Opts]};
  144. make_error_log(data, [StreamID, IsFin, Data, State], Class, Exception, Stacktrace) ->
  145. {log, error,
  146. "Unhandled exception ~p:~p in cowboy_stream:data(~p, ~p, Data, State)~n"
  147. "Stacktrace: ~p~n"
  148. "Data: ~p~n"
  149. "State: ~p~n",
  150. [Class, Exception, StreamID, IsFin, Stacktrace, Data, State]};
  151. make_error_log(info, [StreamID, Msg, State], Class, Exception, Stacktrace) ->
  152. {log, error,
  153. "Unhandled exception ~p:~p in cowboy_stream:info(~p, Msg, State)~n"
  154. "Stacktrace: ~p~n"
  155. "Msg: ~p~n"
  156. "State: ~p~n",
  157. [Class, Exception, StreamID, Stacktrace, Msg, State]};
  158. make_error_log(terminate, [StreamID, Reason, State], Class, Exception, Stacktrace) ->
  159. {log, error,
  160. "Unhandled exception ~p:~p in cowboy_stream:terminate(~p, Reason, State)~n"
  161. "Stacktrace: ~p~n"
  162. "Reason: ~p~n"
  163. "State: ~p~n",
  164. [Class, Exception, StreamID, Stacktrace, Reason, State]};
  165. make_error_log(early_error, [StreamID, Reason, PartialReq, Resp, Opts],
  166. Class, Exception, Stacktrace) ->
  167. {log, error,
  168. "Unhandled exception ~p:~p in cowboy_stream:early_error(~p, Reason, PartialReq, Resp, Opts)~n"
  169. "Stacktrace: ~p~n"
  170. "Reason: ~p~n"
  171. "PartialReq: ~p~n"
  172. "Resp: ~p~n"
  173. "Opts: ~p~n",
  174. [Class, Exception, StreamID, Stacktrace, Reason, PartialReq, Resp, Opts]}.