cover/Elixir.WalletSettlement.ReconciliationStore.html

1 defmodule WalletSettlement.ReconciliationStore do
2 @moduledoc """
3 ETS-backed GenServer for reconciliation run persistence.
4
5 Tables:
6 - `:wallet_recon_runs` — runs keyed by reconciliation_id.
7 """
8 use GenServer
9
10 alias WalletSettlement.ReconciliationRun
11
12 @table :wallet_recon_runs
13
14
:-(
def start_link(opts), do: GenServer.start_link(__MODULE__, opts, name: __MODULE__)
15
16 @spec store(ReconciliationRun.t()) :: :ok
17 5 def store(%ReconciliationRun{} = run), do: GenServer.call(__MODULE__, {:store, run})
18
19 @spec get(String.t()) :: {:ok, ReconciliationRun.t()} | {:error, :not_found}
20 6 def get(id), do: GenServer.call(__MODULE__, {:get, id})
21
22 @spec update(ReconciliationRun.t()) :: :ok | {:error, :not_found}
23 6 def update(%ReconciliationRun{} = run), do: GenServer.call(__MODULE__, {:update, run})
24
25 @spec list_all() :: [ReconciliationRun.t()]
26
:-(
def list_all, do: GenServer.call(__MODULE__, :list_all)
27
28 13 def reset, do: GenServer.call(__MODULE__, :reset)
29
30 @impl true
31 def init(_opts) do
32
:-(
:ets.new(@table, [:set, :protected, :named_table])
33 {:ok, %{}}
34 end
35
36 @impl true
37 def handle_call({:store, run}, _from, state) do
38 5 :ets.insert(@table, {run.reconciliation_id, run})
39 5 {:reply, :ok, state}
40 end
41
42 @impl true
43 def handle_call({:get, id}, _from, state) do
44 6 result = case :ets.lookup(@table, id) do
45 5 [{_, r}] -> {:ok, r}
46 1 [] -> {:error, :not_found}
47 end
48 6 {:reply, result, state}
49 end
50
51 @impl true
52 def handle_call({:update, run}, _from, state) do
53 6 result = case :ets.lookup(@table, run.reconciliation_id) do
54 6 [_] -> :ets.insert(@table, {run.reconciliation_id, run}); :ok
55
:-(
[] -> {:error, :not_found}
56 end
57 6 {:reply, result, state}
58 end
59
60 @impl true
61 def handle_call(:list_all, _from, state) do
62
:-(
{:reply, :ets.tab2list(@table) |> Enum.map(fn {_, r} -> r end), state}
63 end
64
65 @impl true
66 def handle_call(:reset, _from, state) do
67 13 :ets.delete_all_objects(@table)
68 13 {:reply, :ok, state}
69 end
70 end
Line Hits Source