Prune asset cache every 12 hours

This commit is contained in:
Claudio Ortolina
2025-09-20 08:17:16 +03:00
parent 772de1751e
commit a1b5842148
3 changed files with 40 additions and 1 deletions
+2 -1
View File
@@ -88,7 +88,8 @@ config :music_library, Oban,
{Oban.Plugins.Cron,
crontab: [
# every 12 hours
{"0 */12 * * *", MusicLibrary.Worker.ApplyScrobbleRules}
{"0 */12 * * *", MusicLibrary.Worker.ApplyScrobbleRules},
{"0 */12 * * *", MusicLibrary.Worker.PruneAssetCache}
]}
]
+20
View File
@@ -14,4 +14,24 @@ defmodule MusicLibrary.Assets.Cache do
[] -> :not_found
end
end
def total_content_size do
:ets.foldl(
fn {_key, _inserted_at, content}, acc -> acc + byte_size(content) end,
0,
__MODULE__
)
end
def prune(older_than_seconds) do
threshold =
DateTime.utc_now()
|> DateTime.add(older_than_seconds * -1, :second)
|> DateTime.to_unix()
:ets.select_delete(
__MODULE__,
[{{:"$1", :"$2", :"$3"}, [{:<, :"$2", threshold}], [true]}]
)
end
end
@@ -0,0 +1,18 @@
defmodule MusicLibrary.Worker.PruneAssetCache do
use Oban.Worker, queue: :default, max_attempts: 3
require Logger
alias MusicLibrary.Assets.Cache
@one_week_seconds 60 * 60 * 24 * 7
@impl Oban.Worker
def perform(_) do
prune_count = Cache.prune(@one_week_seconds)
Logger.info(fn ->
"Pruned #{prune_count} old cached assets. Cache size now #{Cache.total_content_size()} bytes."
end)
end
end