stream_handler_h.erl 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. %% This module behaves differently depending on a specific header.
  2. -module(stream_handler_h).
  3. -behavior(cowboy_stream).
  4. -export([init/3]).
  5. -export([data/4]).
  6. -export([info/3]).
  7. -export([terminate/3]).
  8. -export([early_error/5]).
  9. -record(state, {
  10. pid,
  11. test
  12. }).
  13. init(StreamID, Req, Opts) ->
  14. Pid = list_to_pid(binary_to_list(cowboy_req:header(<<"x-test-pid">>, Req))),
  15. Test = binary_to_atom(cowboy_req:header(<<"x-test-case">>, Req), latin1),
  16. State = #state{pid=Pid, test=Test},
  17. Pid ! {Pid, self(), init, StreamID, Req, Opts},
  18. {init_commands(StreamID, Req, State), State}.
  19. init_commands(_, _, State=#state{test=shutdown_on_stream_stop}) ->
  20. Spawn = init_process(false, State),
  21. [{headers, 200, #{}}, {spawn, Spawn, 5000}, stop];
  22. init_commands(_, _, State=#state{test=shutdown_on_socket_close}) ->
  23. Spawn = init_process(false, State),
  24. [{headers, 200, #{}}, {spawn, Spawn, 5000}];
  25. init_commands(_, _, State=#state{test=shutdown_timeout_on_stream_stop}) ->
  26. Spawn = init_process(true, State),
  27. [{headers, 200, #{}}, {spawn, Spawn, 2000}, stop];
  28. init_commands(_, _, State=#state{test=shutdown_timeout_on_socket_close}) ->
  29. Spawn = init_process(true, State),
  30. [{headers, 200, #{}}, {spawn, Spawn, 2000}];
  31. init_commands(_, _, _) ->
  32. [{headers, 200, #{}}].
  33. init_process(TrapExit, #state{pid=Pid}) ->
  34. Self = self(),
  35. Spawn = spawn_link(fun() ->
  36. process_flag(trap_exit, TrapExit),
  37. Pid ! {Pid, Self, spawned, self()},
  38. receive {Pid, ready} -> ok after 1000 -> error(timeout) end,
  39. Self ! {self(), ready},
  40. receive after 5000 ->
  41. Pid ! {Pid, Self, still_alive, self()}
  42. end
  43. end),
  44. receive {Spawn, ready} -> ok after 1000 -> error(timeout) end,
  45. Spawn.
  46. data(StreamID, IsFin, Data, State=#state{pid=Pid}) ->
  47. Pid ! {Pid, self(), data, StreamID, IsFin, Data, State},
  48. {[], State}.
  49. info(StreamID, Info, State=#state{pid=Pid}) ->
  50. Pid ! {Pid, self(), info, StreamID, Info, State},
  51. {[], State}.
  52. terminate(StreamID, Reason, State=#state{pid=Pid}) ->
  53. Pid ! {Pid, self(), terminate, StreamID, Reason, State},
  54. ok.
  55. %% This clause can only test for early errors that reached the required header.
  56. early_error(StreamID, Reason, PartialReq, Resp, Opts) ->
  57. Pid = list_to_pid(binary_to_list(cowboy_req:header(<<"x-test-pid">>, PartialReq))),
  58. Pid ! {Pid, self(), early_error, StreamID, Reason, PartialReq, Resp, Opts},
  59. Resp.