summaryrefslogtreecommitdiff
blob: 341d128601d1829670d7c024619b58a153584b34 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
-module(timed_cache_object).
-behavior(gen_server).

%%%% gen_server exports
-export(
   [
      init/1,
      handle_cast/2,
      handle_call/3, %% No reply will ever be given.
      terminate/2,
      code_change/3,
      format_status/2,
      handle_info/2
   ]
).

%%%% actual interface
-export(
   [
      fetch/2,
      invalidate/2
   ]
).

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% LOCAL %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
add_to_cache (DB, ObjectID) ->
   {ok, TimerPID} = gen_server:start(?MODULE, {DB, ObjectID}, []),
   {ok, Data} = shim_database:fetch(DB, ObjectID),
   ets:insert(DB, {ObjectID, TimerPID, Data}),
   Data.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% EXPORTED %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%% gen_server

init ({DB, ObjectID}) ->
   {ok, {DB, ObjectID}}.

handle_call (invalidate, _, State) ->
   {stop, normal, State};
handle_call (ping, _, {DB, ObjectID}) ->
   {noreply, {DB, ObjectID}, timed_caches_manager:get_timeout(DB)}.

handle_cast (invalidate, State) ->
   {stop, normal, State};
handle_cast (ping, {DB, ObjectID}) ->
   {noreply, {DB, ObjectID}, timed_caches_manager:get_timeout(DB)}.

terminate (_, {DB, ObjectID}) ->
   ets:delete(DB, ObjectID).

code_change (_, State, _) ->
   {ok, State}.

format_status (_, [_, State]) ->
   [{data, [{"State", State}]}].

handle_info(timeout, State) ->
   {stop, normal, State};
handle_info(_, {DB, ObjectID}) ->
   {noreply, {DB, ObjectID}, timed_caches_manager:get_timeout(DB)}.

%%%% interface
fetch (DB, ObjectID) ->
   case ets:lookup(DB, ObjectID) of
      [] -> add_to_cache(DB, ObjectID);

      [{_, TimerPID, Data}] ->
         gen_server:cast(TimerPID, ping),
         Data
   end.

invalidate (DB, ObjectID) ->
   case ets:lookup(DB, ObjectID) of
      [] -> ok;

      [{_, TimerPID, _}] ->
         gen_server:stop(TimerPID)
   end.