Skip to content

Commit

Permalink
fix(RepositoryCache): Reduce cache key collisions (#247)
Browse files Browse the repository at this point in the history
* fix(RepositoryCache): Reduce cache key collisions

* style: use RepositoryCache alias

* refactor(RepositoryCache): implement KeyGenerator behavior directly
  • Loading branch information
KaylaBrady authored Nov 25, 2024
1 parent 0b4344b commit 1f01c6e
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 3 deletions.
8 changes: 6 additions & 2 deletions lib/mbta_v3_api/repository.ex
Original file line number Diff line number Diff line change
Expand Up @@ -60,28 +60,32 @@ defmodule MBTAV3API.Repository.Impl do

use Nebulex.Caching.Decorators

alias MBTAV3API.JsonApi
alias MBTAV3API.{JsonApi, RepositoryCache}

@ttl :timer.hours(1)

@impl true
@decorate cacheable(cache: RepositoryCache, on_error: :nothing, opts: [ttl: @ttl])
def route_patterns(params, opts \\ []), do: all(MBTAV3API.RoutePattern, params, opts)

@impl true
@decorate cacheable(cache: RepositoryCache, on_error: :nothing, opts: [ttl: @ttl])
def routes(params, opts \\ []), do: all(MBTAV3API.Route, params, opts)

@impl true
@decorate cacheable(cache: RepositoryCache, on_error: :nothing, opts: [ttl: @ttl])
def schedules(params, opts \\ []), do: all(MBTAV3API.Schedule, params, opts)

@impl true
@decorate cacheable(cache: RepositoryCache, on_error: :nothing, opts: [ttl: @ttl])
def stops(params, opts \\ []), do: all(MBTAV3API.Stop, params, opts)

@impl true
@decorate cacheable(cache: RepositoryCache, on_error: :nothing, opts: [ttl: @ttl])
def trips(params, opts \\ []), do: all(MBTAV3API.Trip, params, opts)

@spec all(module(), JsonApi.Params.t(), Keyword.t()) ::
{:ok, JsonApi.Response.t(JsonApi.Object.t())} | {:error, term()}
@decorate cacheable(cache: MBTAV3API.RepositoryCache, on_error: :nothing, opts: [ttl: @ttl])
defp all(module, params, opts) do
params = JsonApi.Params.flatten_params(params, module)
url = "/#{JsonApi.Object.plural_type(module.jsonapi_type())}"
Expand Down
20 changes: 19 additions & 1 deletion lib/mbta_v3_api/repository_cache.ex
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,23 @@ defmodule MBTAV3API.RepositoryCache do
@moduledoc """
Cache used to reduce the number of calls to the V3 API.
"""
use Nebulex.Cache, otp_app: :mobile_app_backend, adapter: Nebulex.Adapters.Local
use Nebulex.Cache,
otp_app: :mobile_app_backend,
adapter: Nebulex.Adapters.Local,
default_key_generator: __MODULE__

@behaviour Nebulex.Caching.KeyGenerator

@impl Nebulex.Caching.KeyGenerator
def generate(mod, fun, []) do
"#{mod}|#{fun}"
end

def generate(mod, fun, [arg]) do
"#{mod}|#{fun}|#{:erlang.phash2(arg)}"
end

def generate(mod, fun, args) do
"#{mod}|#{fun}|#{:erlang.phash2(args)}"
end
end

0 comments on commit 1f01c6e

Please sign in to comment.