mirror of
https://github.com/TheRealOwenRees/chess-endgame-trainer.git
synced 2026-11-18 03:32:06 +00:00
#5: normalise the full lichess tablebase category vocabulary (cursed-win and blessed-loss classify as draws), return {:ok, tablebase} on a cache hit, and unwrap the tablebase in game_from_fen. #6: replace the LRU cache with an LFU cache storing {key, value, frequency, last_access}, evicting the least-frequently-used entry (LRU tie-break) and halving every frequency on a weekly sweep. Persistence moves to a versioned v2 dets file, dropping the legacy backup; the cache restores synchronously at startup. Also updates stale tags enum and Play LiveView tests, and drops the tracked legacy cache backup.
59 lines
1.4 KiB
Elixir
59 lines
1.4 KiB
Elixir
defmodule Chesstrainer.Cache.Persist do
|
|
@moduledoc """
|
|
Persistence for the cache. Backup and restore functions.
|
|
"""
|
|
|
|
@backup_path "priv/static/backups"
|
|
@format_version "v2"
|
|
|
|
def backup(table) do
|
|
File.mkdir_p!(@backup_path)
|
|
name = backup_filename(table) |> String.to_charlist()
|
|
{:ok, dets_table} = :dets.open_file(name, type: :set)
|
|
:ets.to_dets(table, dets_table)
|
|
:dets.sync(dets_table)
|
|
:dets.close(dets_table)
|
|
end
|
|
|
|
def restore(table) do
|
|
File.mkdir_p!(@backup_path)
|
|
drop_legacy_backup(table)
|
|
|
|
path = backup_filename(table)
|
|
|
|
if File.exists?(path) do
|
|
name = String.to_charlist(path)
|
|
|
|
case :dets.open_file(table, file: name, type: :set) do
|
|
{:ok, ^table} ->
|
|
:dets.foldl(
|
|
fn
|
|
{key, value, frequency, last_access}, :ok when is_integer(frequency) ->
|
|
:ets.insert(table, {key, value, frequency, last_access})
|
|
:ok
|
|
|
|
_entry, :ok ->
|
|
:ok
|
|
end,
|
|
:ok,
|
|
table
|
|
)
|
|
|
|
:dets.close(table)
|
|
|
|
{:error, _} ->
|
|
:ok
|
|
end
|
|
end
|
|
|
|
:ok
|
|
end
|
|
|
|
defp backup_filename(table), do: Path.join(@backup_path, "#{table}.#{@format_version}.det")
|
|
|
|
defp drop_legacy_backup(table) do
|
|
legacy = Path.join(@backup_path, "#{table}.det")
|
|
if File.exists?(legacy), do: File.rm(legacy)
|
|
end
|
|
end
|