@@ -16,6 +16,7 @@ defmodule RabbitMQ.Cache do
1616 require Record
1717
1818 alias :os , as: Os
19+ alias :timer , as: Timer
1920 alias :mnesia , as: Mnesia
2021
2122 ## Client API
@@ -53,7 +54,7 @@ defmodule RabbitMQ.Cache do
5354 def init ( { cache , size , ttl } ) do
5455 Mnesia . start ( )
5556
56- cache_create ( cache , size , ttl )
57+ :ok = cache_create ( cache , size , ttl )
5758
5859 Process . send_after ( cache , { :cache , cache } , 3 )
5960
@@ -77,16 +78,17 @@ defmodule RabbitMQ.Cache do
7778 true -> nil
7879 end
7980
80- Mnesia . transaction ( fn ->
81- Mnesia . write ( { cache , value , expiration } )
82- end )
83-
81+ # Remove first element if full
8482 size = Mnesia . table_info ( cache , :size )
8583 { :limit , limit } = cache_limit ( cache )
86- if size > limit do
84+ if size >= limit do
8785 cache_delete_first ( cache )
8886 end
8987
88+ Mnesia . transaction ( fn ->
89+ Mnesia . write ( { cache , value , expiration } )
90+ end )
91+
9092 { :reply , :ok , state }
9193 end
9294
@@ -101,13 +103,13 @@ defmodule RabbitMQ.Cache do
101103 ## Utility functions
102104
103105 defp cache_create ( cache , size , ttl ) do
104- with { :atomic , :ok } <- Mnesia . create_table ( cache ,
105- [ attributes: [ :value , :expiration ] ,
106- index: [ :expiration ] ,
107- user_properties: [ limit: size , default_ttl: ttl ] ] ) ,
108- { :atomic , :ok } <- Mnesia . add_table_copy ( cache , node ( ) , :ram_copies ) ,
109- { :atomic , :ok } <- Mnesia . wait_for_tables ( [ cache ] , :timer . seconds ( 30 ) ) ,
110- do: :ok
106+ Mnesia . create_table ( cache ,
107+ [ attributes: [ :value , :expiration ] ,
108+ index: [ :expiration ] ,
109+ user_properties: [ limit: size , default_ttl: ttl ] ] )
110+ Mnesia . add_table_copy ( cache , node ( ) , :ram_copies )
111+
112+ Mnesia . wait_for_tables ( [ cache ] , Timer . seconds ( 30 ) )
111113 end
112114
113115 defp cache_member? ( cache , value ) do
0 commit comments