-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: Cache stop to route relationships
Adds a Nebulex cache for stops -> routes to weaken the dependency on the V3 API when querying the Alerts cache.
- Loading branch information
1 parent
f53e952
commit 99cc65e
Showing
2 changed files
with
59 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,57 @@ | ||
defmodule Screens.Stops.StopsToRoutes do | ||
@moduledoc """ | ||
Cache of stop ids to route ids. Information for stop ids missing from the | ||
cache is fetched automatically from the V3 API when requested. | ||
""" | ||
use Nebulex.Cache, | ||
otp_app: :screens, | ||
adapter: Nebulex.Adapters.Local | ||
|
||
@base_ttl :timer.hours(1) | ||
|
||
@spec stops_to_routes([stop_id :: String.t()]) :: [route_id :: String.t()] | ||
def stops_to_routes(stop_ids) do | ||
from_cache = get_all(stop_ids) | ||
missing_stop_ids = stop_ids -- Map.keys(from_cache) | ||
|
||
from_api = | ||
if Enum.empty?(missing_stop_ids) do | ||
%{} | ||
else | ||
from_api = | ||
for stop_id <- missing_stop_ids, into: %{} do | ||
{:ok, routes} = fetch_routes_for_stops(stop_id) | ||
route_ids = Enum.map(routes, & &1.id) | ||
|
||
{stop_id, route_ids} | ||
end | ||
|
||
put_all(from_api, ttl: ttl()) | ||
|
||
from_api | ||
end | ||
|
||
[from_cache, from_api] | ||
|> Enum.map(&ungroup_values/1) | ||
|> Enum.concat() | ||
|> Enum.uniq() | ||
end | ||
|
||
defp fetch_routes_for_stops(stop_ids) do | ||
stop_impl = Application.get_env(:screens, :stops_to_routes_stop_mod, Screens.Stops.Stop) | ||
stop_impl.fetch_routes_for_stops(stop_ids) | ||
end | ||
|
||
defp ungroup_values(map) do | ||
map | ||
|> Map.values() | ||
|> List.flatten() | ||
|> Enum.uniq() | ||
end | ||
|
||
# Set random TTLs from 1hr to 1.5hrs to alleviate the thundering herd problem | ||
defp ttl do | ||
additional_minutes = :rand.uniform(30) | ||
@base_ttl + :timer.minutes(additional_minutes) | ||
end | ||
end |