|
| 1 | +defmodule Cache.MultiLayer do |
| 2 | + @moduledoc """ |
| 3 | + Multi-layer caching strategy that cascades through multiple cache layers. |
| 4 | +
|
| 5 | + Keys are read from fastest to slowest, with automatic backfill on cache hits |
| 6 | + from slower layers. Writes go slowest-first to avoid polluting fast layers |
| 7 | + with data that failed to persist in slow ones. |
| 8 | +
|
| 9 | + ## Usage |
| 10 | +
|
| 11 | + Pass a list of layers as the strategy config. Each element can be: |
| 12 | +
|
| 13 | + - A module that implements `Cache` (already running, not supervised by this adapter) |
| 14 | + - An adapter module (e.g. `Cache.ETS`) — will be auto-started and supervised |
| 15 | + - A tuple `{AdapterModule, opts}` — adapter with inline opts |
| 16 | +
|
| 17 | + ```elixir |
| 18 | + defmodule MyApp.LayeredCache do |
| 19 | + use Cache, |
| 20 | + adapter: {Cache.MultiLayer, [Cache.ETS, MyApp.RedisCache]}, |
| 21 | + name: :layered_cache, |
| 22 | + opts: [] |
| 23 | + end |
| 24 | + ``` |
| 25 | +
|
| 26 | + ## `__MODULE__` in Layers |
| 27 | +
|
| 28 | + You may include `__MODULE__` in the layer list to position the current |
| 29 | + module's own underlying cache within the chain. If `__MODULE__` is omitted, |
| 30 | + no local cache is created for the defining module—it acts as a pure facade. |
| 31 | +
|
| 32 | + ```elixir |
| 33 | + defmodule MyApp.LayeredCache do |
| 34 | + use Cache, |
| 35 | + adapter: {Cache.MultiLayer, [Cache.ETS, __MODULE__, MyApp.RedisCache]}, |
| 36 | + name: :layered_cache, |
| 37 | + opts: [uri: "redis://localhost"] |
| 38 | + end |
| 39 | + ``` |
| 40 | +
|
| 41 | + ## Read Behaviour |
| 42 | +
|
| 43 | + Layers are iterated fastest → slowest (list order). On a hit from layer N, |
| 44 | + the value is backfilled into layers 1..N-1. |
| 45 | +
|
| 46 | + ## Write Behaviour |
| 47 | +
|
| 48 | + Layers are written slowest → fastest (reverse list order). If a slow write |
| 49 | + fails, the write stops and an error is returned — preventing polluting faster |
| 50 | + layers with potentially-unsaved data. |
| 51 | +
|
| 52 | + ## Fetch Callback (Optional) |
| 53 | +
|
| 54 | + If all layers miss, an optional fetch callback can supply the value. The |
| 55 | + fetched value is then backfilled into all layers. |
| 56 | +
|
| 57 | + Define it as a module callback or pass it via opts: |
| 58 | +
|
| 59 | + ```elixir |
| 60 | + defmodule MyApp.LayeredCache do |
| 61 | + use Cache, |
| 62 | + adapter: {Cache.MultiLayer, [Cache.ETS, MyApp.RedisCache]}, |
| 63 | + name: :layered_cache, |
| 64 | + opts: [on_fetch: &__MODULE__.fetch/1] |
| 65 | +
|
| 66 | + def fetch(key) do |
| 67 | + {:ok, "value_for_\#{key}"} |
| 68 | + end |
| 69 | + end |
| 70 | + ``` |
| 71 | +
|
| 72 | + ## Options |
| 73 | +
|
| 74 | + #{NimbleOptions.docs([ |
| 75 | + on_fetch: [ |
| 76 | + type: {:or, [:mfa, {:fun, 1}]}, |
| 77 | + doc: "Optional fetch callback invoked on total cache miss. Receives the key, returns `{:ok, value}` or `{:error, reason}`." |
| 78 | + ], |
| 79 | + backfill_ttl: [ |
| 80 | + type: {:or, [:pos_integer, nil]}, |
| 81 | + doc: "TTL in milliseconds to use when backfilling layers on a hit from a slower layer. Defaults to nil (no expiry)." |
| 82 | + ] |
| 83 | + ])} |
| 84 | + """ |
| 85 | + |
| 86 | + @behaviour Cache.Strategy |
| 87 | + |
| 88 | + @opts_definition [ |
| 89 | + on_fetch: [ |
| 90 | + type: {:or, [:mfa, {:fun, 1}]}, |
| 91 | + doc: "Optional fetch callback for cache miss." |
| 92 | + ], |
| 93 | + backfill_ttl: [ |
| 94 | + type: {:or, [:pos_integer, nil]}, |
| 95 | + doc: "TTL for backfilled entries." |
| 96 | + ] |
| 97 | + ] |
| 98 | + |
| 99 | + @impl Cache.Strategy |
| 100 | + def opts_definition, do: @opts_definition |
| 101 | + |
| 102 | + @impl Cache.Strategy |
| 103 | + def child_spec({cache_name, _layers, _adapter_opts}) do |
| 104 | + %{ |
| 105 | + id: :"#{cache_name}_multi_layer", |
| 106 | + start: {Agent, :start_link, [fn -> :ok end, [name: :"#{cache_name}_multi_layer"]]} |
| 107 | + } |
| 108 | + end |
| 109 | + |
| 110 | + @impl Cache.Strategy |
| 111 | + def get(cache_name, key, layers, adapter_opts) do |
| 112 | + backfill_ttl = adapter_opts[:backfill_ttl] |
| 113 | + |
| 114 | + case get_from_layers(cache_name, key, layers, adapter_opts, []) do |
| 115 | + {:hit, value, layers_to_backfill} -> |
| 116 | + backfill_layers(cache_name, key, layers_to_backfill, value, backfill_ttl) |
| 117 | + {:ok, value} |
| 118 | + |
| 119 | + :miss -> |
| 120 | + fetch_on_miss(cache_name, key, layers, adapter_opts) |
| 121 | + end |
| 122 | + end |
| 123 | + |
| 124 | + @impl Cache.Strategy |
| 125 | + def put(cache_name, key, ttl, value, layers, adapter_opts) do |
| 126 | + reversed = Enum.reverse(layers) |
| 127 | + put_to_layers(cache_name, key, ttl, value, reversed, adapter_opts) |
| 128 | + end |
| 129 | + |
| 130 | + @impl Cache.Strategy |
| 131 | + def delete(cache_name, key, layers, _adapter_opts) do |
| 132 | + Enum.reduce_while(layers, :ok, fn layer, _acc -> |
| 133 | + case layer_delete(cache_name, key, layer) do |
| 134 | + :ok -> {:cont, :ok} |
| 135 | + {:error, _} = error -> {:halt, error} |
| 136 | + end |
| 137 | + end) |
| 138 | + end |
| 139 | + |
| 140 | + defp get_from_layers(_cache_name, _key, [], _adapter_opts, _visited), do: :miss |
| 141 | + |
| 142 | + defp get_from_layers(cache_name, key, [layer | rest], adapter_opts, visited) do |
| 143 | + case layer_get(cache_name, key, layer) do |
| 144 | + {:ok, nil} -> |
| 145 | + get_from_layers(cache_name, key, rest, adapter_opts, [layer | visited]) |
| 146 | + |
| 147 | + {:ok, value} -> |
| 148 | + {:hit, value, visited} |
| 149 | + |
| 150 | + {:error, _} -> |
| 151 | + get_from_layers(cache_name, key, rest, adapter_opts, [layer | visited]) |
| 152 | + end |
| 153 | + end |
| 154 | + |
| 155 | + defp fetch_on_miss(cache_name, key, layers, adapter_opts) do |
| 156 | + on_fetch = adapter_opts[:on_fetch] |
| 157 | + |
| 158 | + if is_nil(on_fetch) do |
| 159 | + {:ok, nil} |
| 160 | + else |
| 161 | + case invoke_callback(on_fetch, [key]) do |
| 162 | + {:ok, value} -> |
| 163 | + backfill_ttl = adapter_opts[:backfill_ttl] |
| 164 | + backfill_layers(cache_name, key, layers, value, backfill_ttl) |
| 165 | + {:ok, value} |
| 166 | + |
| 167 | + {:error, _} = error -> |
| 168 | + error |
| 169 | + end |
| 170 | + end |
| 171 | + end |
| 172 | + |
| 173 | + defp put_to_layers(_cache_name, _key, _ttl, _value, [], _adapter_opts), do: :ok |
| 174 | + |
| 175 | + defp put_to_layers(cache_name, key, ttl, value, [layer | rest], adapter_opts) do |
| 176 | + case layer_put(cache_name, key, ttl, value, layer) do |
| 177 | + :ok -> put_to_layers(cache_name, key, ttl, value, rest, adapter_opts) |
| 178 | + {:error, _} = error -> error |
| 179 | + end |
| 180 | + end |
| 181 | + |
| 182 | + defp backfill_layers(_cache_name, _key, [], _value, _ttl), do: :ok |
| 183 | + |
| 184 | + defp backfill_layers(cache_name, key, [layer | rest], value, ttl) do |
| 185 | + layer_put(cache_name, key, ttl, value, layer) |
| 186 | + backfill_layers(cache_name, key, rest, value, ttl) |
| 187 | + end |
| 188 | + |
| 189 | + defp layer_get(_cache_name, key, layer) when is_atom(layer) do |
| 190 | + if cache_module?(layer) do |
| 191 | + layer.get(key) |
| 192 | + else |
| 193 | + {:ok, nil} |
| 194 | + end |
| 195 | + end |
| 196 | + |
| 197 | + defp layer_put(_cache_name, key, ttl, value, layer) when is_atom(layer) do |
| 198 | + if cache_module?(layer) do |
| 199 | + layer.put(key, ttl, value) |
| 200 | + else |
| 201 | + :ok |
| 202 | + end |
| 203 | + end |
| 204 | + |
| 205 | + defp layer_delete(_cache_name, key, layer) when is_atom(layer) do |
| 206 | + if cache_module?(layer) do |
| 207 | + layer.delete(key) |
| 208 | + else |
| 209 | + :ok |
| 210 | + end |
| 211 | + end |
| 212 | + |
| 213 | + defp cache_module?(module) do |
| 214 | + function_exported?(module, :get, 1) and function_exported?(module, :put, 2) |
| 215 | + end |
| 216 | + |
| 217 | + defp invoke_callback({module, function, args}, extra_args) do |
| 218 | + apply(module, function, args ++ extra_args) |
| 219 | + end |
| 220 | + |
| 221 | + defp invoke_callback(fun, args) when is_function(fun) do |
| 222 | + apply(fun, args) |
| 223 | + end |
| 224 | +end |
0 commit comments