cowboy_clock.erl 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. %% Copyright (c) 2011, Loïc Hoguin <essen@dev-extend.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. %% @doc Date and time related functions.
  15. %%
  16. %% While a gen_server process runs in the background to update
  17. %% the cache of formatted dates every second, all API calls are
  18. %% local and directly read from the ETS cache table, providing
  19. %% fast time and date computations.
  20. -module(cowboy_clock).
  21. -behaviour(gen_server).
  22. -export([start_link/0, stop/0, rfc1123/0, rfc2109/1]). %% API.
  23. -export([init/1, handle_call/3, handle_cast/2,
  24. handle_info/2, terminate/2, code_change/3]). %% gen_server.
  25. %% @todo Use calendar types whenever they get exported.
  26. -type year() :: non_neg_integer().
  27. -type month() :: 1..12.
  28. -type day() :: 1..31.
  29. -type hour() :: 0..23.
  30. -type minute() :: 0..59.
  31. -type second() :: 0..59.
  32. -type daynum() :: 1..7.
  33. -type date() :: {year(), month(), day()}.
  34. -type time() :: {hour(), minute(), second()}.
  35. -type datetime() :: {date(), time()}.
  36. -export_type([date/0, time/0, datetime/0]).
  37. -record(state, {
  38. universaltime = undefined :: undefined | datetime(),
  39. rfc1123 = <<>> :: binary(),
  40. tref = undefined :: undefined | timer:tref()
  41. }).
  42. -define(SERVER, ?MODULE).
  43. -define(TABLE, ?MODULE).
  44. -include_lib("eunit/include/eunit.hrl").
  45. %% API.
  46. %% @private
  47. -spec start_link() -> {ok, pid()}.
  48. start_link() ->
  49. gen_server:start_link({local, ?SERVER}, ?MODULE, [], []).
  50. %% @private
  51. -spec stop() -> stopped.
  52. stop() ->
  53. gen_server:call(?SERVER, stop).
  54. %% @doc Return the current date and time formatted according to RFC-1123.
  55. %%
  56. %% This format is used in the <em>'Date'</em> header sent with HTTP responses.
  57. -spec rfc1123() -> binary().
  58. rfc1123() ->
  59. ets:lookup_element(?TABLE, rfc1123, 2).
  60. %% @doc Return the current date and time formatted according to RFC-2109.
  61. %%
  62. %% This format is used in the <em>'Set-Cookie'</em> header sent with
  63. %% HTTP responses.
  64. -spec rfc2109(datetime()) -> binary().
  65. rfc2109(LocalTime) ->
  66. {{YYYY,MM,DD},{Hour,Min,Sec}} =
  67. case calendar:local_time_to_universal_time_dst(LocalTime) of
  68. [Gmt] -> Gmt;
  69. [_,Gmt] -> Gmt
  70. end,
  71. Wday = calendar:day_of_the_week({YYYY,MM,DD}),
  72. DayBin = pad_int(DD),
  73. YearBin = list_to_binary(integer_to_list(YYYY)),
  74. HourBin = pad_int(Hour),
  75. MinBin = pad_int(Min),
  76. SecBin = pad_int(Sec),
  77. WeekDay = weekday(Wday),
  78. Month = month(MM),
  79. <<WeekDay/binary, ", ",
  80. DayBin/binary, " ", Month/binary, " ",
  81. YearBin/binary, " ",
  82. HourBin/binary, ":",
  83. MinBin/binary, ":",
  84. SecBin/binary, " GMT">>.
  85. %% gen_server.
  86. %% @private
  87. -spec init([]) -> {ok, #state{}}.
  88. init([]) ->
  89. ?TABLE = ets:new(?TABLE, [set, protected,
  90. named_table, {read_concurrency, true}]),
  91. T = erlang:universaltime(),
  92. B = update_rfc1123(<<>>, undefined, T),
  93. {ok, TRef} = timer:send_interval(1000, update),
  94. ets:insert(?TABLE, {rfc1123, B}),
  95. {ok, #state{universaltime=T, rfc1123=B, tref=TRef}}.
  96. %% @private
  97. -spec handle_call(_, _, State)
  98. -> {reply, ignored, State} | {stop, normal, stopped, State}.
  99. handle_call(stop, _From, State=#state{tref=TRef}) ->
  100. {ok, cancel} = timer:cancel(TRef),
  101. {stop, normal, stopped, State};
  102. handle_call(_Request, _From, State) ->
  103. {reply, ignored, State}.
  104. %% @private
  105. -spec handle_cast(_, State) -> {noreply, State}.
  106. handle_cast(_Msg, State) ->
  107. {noreply, State}.
  108. %% @private
  109. -spec handle_info(_, State) -> {noreply, State}.
  110. handle_info(update, #state{universaltime=Prev, rfc1123=B1, tref=TRef}) ->
  111. T = erlang:universaltime(),
  112. B2 = update_rfc1123(B1, Prev, T),
  113. ets:insert(?TABLE, {rfc1123, B2}),
  114. {noreply, #state{universaltime=T, rfc1123=B2, tref=TRef}};
  115. handle_info(_Info, State) ->
  116. {noreply, State}.
  117. %% @private
  118. -spec terminate(_, _) -> ok.
  119. terminate(_Reason, _State) ->
  120. ok.
  121. %% @private
  122. -spec code_change(_, State, _) -> {ok, State}.
  123. code_change(_OldVsn, State, _Extra) ->
  124. {ok, State}.
  125. %% Internal.
  126. -spec update_rfc1123(binary(), undefined | datetime(), datetime()) -> binary().
  127. update_rfc1123(Bin, Now, Now) ->
  128. Bin;
  129. update_rfc1123(<< Keep:23/binary, _/bits >>,
  130. {Date, {H, M, _}}, {Date, {H, M, S}}) ->
  131. << Keep/binary, (pad_int(S))/binary, " GMT" >>;
  132. update_rfc1123(<< Keep:20/binary, _/bits >>,
  133. {Date, {H, _, _}}, {Date, {H, M, S}}) ->
  134. << Keep/binary, (pad_int(M))/binary, $:, (pad_int(S))/binary, " GMT" >>;
  135. update_rfc1123(<< Keep:17/binary, _/bits >>, {Date, _}, {Date, {H, M, S}}) ->
  136. << Keep/binary, (pad_int(H))/binary, $:, (pad_int(M))/binary,
  137. $:, (pad_int(S))/binary, " GMT" >>;
  138. update_rfc1123(<< _:7/binary, Keep:10/binary, _/bits >>,
  139. {{Y, Mo, _}, _}, {Date = {Y, Mo, D}, {H, M, S}}) ->
  140. Wday = calendar:day_of_the_week(Date),
  141. << (weekday(Wday))/binary, ", ", (pad_int(D))/binary, Keep/binary,
  142. (pad_int(H))/binary, $:, (pad_int(M))/binary,
  143. $:, (pad_int(S))/binary, " GMT" >>;
  144. update_rfc1123(<< _:11/binary, Keep:6/binary, _/bits >>,
  145. {{Y, _, _}, _}, {Date = {Y, Mo, D}, {H, M, S}}) ->
  146. Wday = calendar:day_of_the_week(Date),
  147. << (weekday(Wday))/binary, ", ", (pad_int(D))/binary, " ",
  148. (month(Mo))/binary, Keep/binary,
  149. (pad_int(H))/binary, $:, (pad_int(M))/binary,
  150. $:, (pad_int(S))/binary, " GMT" >>;
  151. update_rfc1123(_, _, {Date = {Y, Mo, D}, {H, M, S}}) ->
  152. Wday = calendar:day_of_the_week(Date),
  153. << (weekday(Wday))/binary, ", ", (pad_int(D))/binary, " ",
  154. (month(Mo))/binary, " ", (list_to_binary(integer_to_list(Y)))/binary,
  155. " ", (pad_int(H))/binary, $:, (pad_int(M))/binary,
  156. $:, (pad_int(S))/binary, " GMT" >>.
  157. %% Following suggestion by MononcQc on #erlounge.
  158. -spec pad_int(0..59) -> binary().
  159. pad_int(X) when X < 10 ->
  160. << $0, ($0 + X) >>;
  161. pad_int(X) ->
  162. list_to_binary(integer_to_list(X)).
  163. -spec weekday(daynum()) -> <<_:24>>.
  164. weekday(1) -> <<"Mon">>;
  165. weekday(2) -> <<"Tue">>;
  166. weekday(3) -> <<"Wed">>;
  167. weekday(4) -> <<"Thu">>;
  168. weekday(5) -> <<"Fri">>;
  169. weekday(6) -> <<"Sat">>;
  170. weekday(7) -> <<"Sun">>.
  171. -spec month(month()) -> <<_:24>>.
  172. month( 1) -> <<"Jan">>;
  173. month( 2) -> <<"Feb">>;
  174. month( 3) -> <<"Mar">>;
  175. month( 4) -> <<"Apr">>;
  176. month( 5) -> <<"May">>;
  177. month( 6) -> <<"Jun">>;
  178. month( 7) -> <<"Jul">>;
  179. month( 8) -> <<"Aug">>;
  180. month( 9) -> <<"Sep">>;
  181. month(10) -> <<"Oct">>;
  182. month(11) -> <<"Nov">>;
  183. month(12) -> <<"Dec">>.
  184. %% Tests.
  185. -ifdef(TEST).
  186. update_rfc1123_test_() ->
  187. Tests = [
  188. {<<"Sat, 14 May 2011 14:25:33 GMT">>, undefined,
  189. {{2011, 5, 14}, {14, 25, 33}}, <<>>},
  190. {<<"Sat, 14 May 2011 14:25:33 GMT">>, {{2011, 5, 14}, {14, 25, 33}},
  191. {{2011, 5, 14}, {14, 25, 33}}, <<"Sat, 14 May 2011 14:25:33 GMT">>},
  192. {<<"Sat, 14 May 2011 14:25:34 GMT">>, {{2011, 5, 14}, {14, 25, 33}},
  193. {{2011, 5, 14}, {14, 25, 34}}, <<"Sat, 14 May 2011 14:25:33 GMT">>},
  194. {<<"Sat, 14 May 2011 14:26:00 GMT">>, {{2011, 5, 14}, {14, 25, 59}},
  195. {{2011, 5, 14}, {14, 26, 0}}, <<"Sat, 14 May 2011 14:25:59 GMT">>},
  196. {<<"Sat, 14 May 2011 15:00:00 GMT">>, {{2011, 5, 14}, {14, 59, 59}},
  197. {{2011, 5, 14}, {15, 0, 0}}, <<"Sat, 14 May 2011 14:59:59 GMT">>},
  198. {<<"Sun, 15 May 2011 00:00:00 GMT">>, {{2011, 5, 14}, {23, 59, 59}},
  199. {{2011, 5, 15}, { 0, 0, 0}}, <<"Sat, 14 May 2011 23:59:59 GMT">>},
  200. {<<"Wed, 01 Jun 2011 00:00:00 GMT">>, {{2011, 5, 31}, {23, 59, 59}},
  201. {{2011, 6, 1}, { 0, 0, 0}}, <<"Tue, 31 May 2011 23:59:59 GMT">>},
  202. {<<"Sun, 01 Jan 2012 00:00:00 GMT">>, {{2011, 5, 31}, {23, 59, 59}},
  203. {{2012, 1, 1}, { 0, 0, 0}}, <<"Sat, 31 Dec 2011 23:59:59 GMT">>}
  204. ],
  205. [{R, fun() -> R = update_rfc1123(B, P, N) end} || {R, P, N, B} <- Tests].
  206. pad_int_test_() ->
  207. Tests = [
  208. { 0, <<"00">>}, { 1, <<"01">>}, { 2, <<"02">>}, { 3, <<"03">>},
  209. { 4, <<"04">>}, { 5, <<"05">>}, { 6, <<"06">>}, { 7, <<"07">>},
  210. { 8, <<"08">>}, { 9, <<"09">>}, {10, <<"10">>}, {11, <<"11">>},
  211. {12, <<"12">>}, {13, <<"13">>}, {14, <<"14">>}, {15, <<"15">>},
  212. {16, <<"16">>}, {17, <<"17">>}, {18, <<"18">>}, {19, <<"19">>},
  213. {20, <<"20">>}, {21, <<"21">>}, {22, <<"22">>}, {23, <<"23">>},
  214. {24, <<"24">>}, {25, <<"25">>}, {26, <<"26">>}, {27, <<"27">>},
  215. {28, <<"28">>}, {29, <<"29">>}, {30, <<"30">>}, {31, <<"31">>},
  216. {32, <<"32">>}, {33, <<"33">>}, {34, <<"34">>}, {35, <<"35">>},
  217. {36, <<"36">>}, {37, <<"37">>}, {38, <<"38">>}, {39, <<"39">>},
  218. {40, <<"40">>}, {41, <<"41">>}, {42, <<"42">>}, {43, <<"43">>},
  219. {44, <<"44">>}, {45, <<"45">>}, {46, <<"46">>}, {47, <<"47">>},
  220. {48, <<"48">>}, {49, <<"49">>}, {50, <<"50">>}, {51, <<"51">>},
  221. {52, <<"52">>}, {53, <<"53">>}, {54, <<"54">>}, {55, <<"55">>},
  222. {56, <<"56">>}, {57, <<"57">>}, {58, <<"58">>}, {59, <<"59">>}
  223. ],
  224. [{I, fun() -> O = pad_int(I) end} || {I, O} <- Tests].
  225. -endif.