Skip to content

Commit

Permalink
Hydrating Cache accepts CRON intervals
Browse files Browse the repository at this point in the history
  • Loading branch information
bchamagne authored and Neylix committed Mar 24, 2023
1 parent ef4047c commit 04706b3
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
12 changes: 11 additions & 1 deletion lib/archethic/oracle_chain/services/hydrating_cache.ex
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ defmodule Archethic.OracleChain.Services.HydratingCache do
"""
use GenServer

alias Archethic.Utils
require Logger

defmodule State do
Expand All @@ -15,6 +16,7 @@ defmodule Archethic.OracleChain.Services.HydratingCache do
:mfa,
:ttl,
:ttl_timer,
# refresh_interval :: Int | CronInterval
:refresh_interval,
:value,
:hydrating_task,
Expand Down Expand Up @@ -108,7 +110,7 @@ defmodule Archethic.OracleChain.Services.HydratingCache do
end

# start a new hydrate timer
hydrating_timer = Process.send_after(self(), :hydrate, refresh_interval)
hydrating_timer = Process.send_after(self(), :hydrate, next_tick_in_seconds(refresh_interval))

new_state = %{
state
Expand All @@ -132,4 +134,12 @@ defmodule Archethic.OracleChain.Services.HydratingCache do
def handle_info(:discard_value, state) do
{:noreply, %State{state | value: nil, ttl_timer: nil}}
end

defp next_tick_in_seconds(refresh_interval) do
if is_binary(refresh_interval) do
Utils.time_offset(refresh_interval) * 1000
else
refresh_interval
end
end
end
19 changes: 19 additions & 0 deletions test/archethic/oracle_chain/services/hydrating_cache_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,25 @@ defmodule ArchethicCache.OracleChain.Services.HydratingCacheTest do
assert date != date2
end

test "should work with cron interval" do
{:ok, pid} =
HydratingCache.start_link(
mfa: {DateTime, :utc_now, []},
refresh_interval: "* * * * *",
ttl: :infinity
)

:erlang.trace(pid, true, [:receive])
assert_receive {:trace, ^pid, :receive, :hydrate}
Process.sleep(1)
{:ok, date} = HydratingCache.get(pid)

# minimum interval is 1s
Process.sleep(1005)
{:ok, date2} = HydratingCache.get(pid)
assert date != date2
end

test "should discard the value after the ttl is reached" do
{:ok, pid} =
HydratingCache.start_link(
Expand Down

0 comments on commit 04706b3

Please sign in to comment.