_site/cover/mcd_reaper.COVER.html

1 %% Copyright (c) 2022 Peter Morgan <peter.james.morgan@gmail.com>
2 %%
3 %% Licensed under the Apache License, Version 2.0 (the "License");
4 %% you may not use this file except in compliance with the License.
5 %% You may obtain a copy of the License at
6 %%
7 %% http://www.apache.org/licenses/LICENSE-2.0
8 %%
9 %% Unless required by applicable law or agreed to in writing, software
10 %% distributed under the License is distributed on an "AS IS" BASIS,
11 %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 %% See the License for the specific language governing permissions and
13 %% limitations under the License.
14
15
16 -module(mcd_reaper).
17
18
19 -export([callback_mode/0]).
20 -export([handle_event/4]).
21 -export([init/1]).
22 -export([start_link/1]).
23
24
25 start_link(Arg) ->
26 11 gen_statem:start_link({local, ?MODULE},
27 ?MODULE,
28 [Arg],
29 envy_gen:options(?MODULE)).
30
31
32 init([Arg]) ->
33 11 process_flag(trap_exit, true),
34 11 {ok, ready, #{arg => Arg}}.
35
36
37 callback_mode() ->
38 11 handle_event_function.
39
40
41 handle_event({timeout, Key},
42 expire,
43 _,
44 #{arg := #{callback := Module},
45 callback_data := CallbackData}) ->
46 4 case Module:expire(#{key => Key, data => CallbackData}) of
47 ok ->
48 4 keep_state_and_data;
49
50 stop ->
51
:-(
stop;
52
53 {stop, Reason} ->
54
:-(
{stop, Reason}
55 end;
56
57
58 handle_event({timeout, _},
59 flush_all,
60 _,
61 #{arg := #{callback := Module},
62 callback_data := CallbackData}) ->
63 2 case Module:flush_all(#{data => CallbackData}) of
64 ok ->
65 2 keep_state_and_data;
66
67 stop ->
68
:-(
stop;
69
70 {stop, Reason} ->
71
:-(
{stop, Reason}
72 end;
73
74 handle_event({call, From}, {callback, #{data := CallbackData}}, _, Data) ->
75 11 {keep_state,
76 Data#{callback_data => CallbackData},
77 {reply, From, ok}};
78
79 handle_event({call, From},
80 {expire = Type, #{key := Key, seconds := Expiry}},
81 _,
82 _) ->
83 62 {keep_state_and_data,
84 [timeout_action(Key, Expiry, Type), {reply, From, ok}]};
85
86 handle_event({call, From},
87 {flush_all = Type, Timeout},
88 _,
89 _) ->
90 2 {keep_state_and_data,
91 [timeout_action(Type, Timeout, Type), {reply, From, ok}]}.
92
93
94 timeout_action(Name, 0, expire) ->
95 46 {{timeout, Name}, cancel};
96
97 timeout_action(Name, Time, Content) when Time < 60 * 60 * 24 * 30 ->
98 18 {{timeout, Name},
99 erlang:convert_time_unit(Time, second, millisecond),
100 Content};
101
102 timeout_action(Name, Time, Content) ->
103
:-(
{{timeout, Name},
104 mcd_time:system_to_monotonic(Time, second, millisecond),
105 Content,
106 [{abs, true}]}.
Line Hits Source