cowboy_clock.erl 9.0 KB

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