prop/lib/microwaveprop_web/controllers/contact_map_controller.ex
Graham McIntire 316fb2fbc7
Fix low-severity bugs and re-enable Credo checks
- Bug #12: Lower rate limit to 15/min
- Bug #13: Wrap model loading in Task.start
- Bug #14: Fix classify_time_period guard gap at -3.0
- Bug #15: Not applicable (Elixir has no ?? operator)
- Bug #16: Remove fallback Repo.get for station preload
- Bug #17: Extract cache_key() in ContactMapController
- Bug #18: Add has_many :contacts and :beacons to User schema
- A&D #4: Move serve_markdown_if_requested after secure headers
- Config #1: Move signing_salt to runtime.exs env var
- Config #2: Use --check-unused instead of --unused
- Config #3: Re-enable UnsafeToAtom Credo check
- Config #5: Re-enable LeakyEnvironment Credo check
- Add @spec annotations to fix re-enabled Specs violations
- Replace String.to_atom with to_existing_atom where guarded
2026-05-29 17:29:22 -05:00

56 lines
1.6 KiB
Elixir

defmodule MicrowavepropWeb.ContactMapController do
@moduledoc """
Serves the contact map JSON payload as a standalone HTTP endpoint. Keeps
the ~5 MB blob out of the `/contacts/map` LiveView's initial HTML response
and lets the browser's native `Content-Encoding: gzip` handling do the
compression. The payload itself is served from `Microwaveprop.Cache` via
`Radio.contact_map_payload/0`.
"""
use MicrowavepropWeb, :controller
alias Microwaveprop.Cache
alias Microwaveprop.Radio
@cache_key {__MODULE__, :gzipped_payload}
@cache_ttl_ms 10 * 60 * 1_000
@doc false
def cache_key, do: @cache_key
@spec show(Plug.Conn.t(), map()) :: Plug.Conn.t()
def show(conn, _params) do
{body, encoding} = gzipped_or_plain_body(conn)
conn
|> put_resp_content_type("application/json")
|> maybe_put_encoding(encoding)
|> put_resp_header("cache-control", "public, max-age=60")
|> send_resp(200, body)
end
defp gzipped_or_plain_body(conn) do
if accepts_gzip?(conn) do
{gzipped_payload(), :gzip}
else
%{json: iodata} = Radio.contact_map_payload()
{IO.iodata_to_binary(iodata), :identity}
end
end
defp gzipped_payload do
Cache.fetch_or_store(@cache_key, @cache_ttl_ms, fn ->
%{json: iodata} = Radio.contact_map_payload()
:zlib.gzip(IO.iodata_to_binary(iodata))
end)
end
defp accepts_gzip?(conn) do
case get_req_header(conn, "accept-encoding") do
[value | _] -> String.contains?(value, "gzip")
_ -> false
end
end
defp maybe_put_encoding(conn, :gzip), do: put_resp_header(conn, "content-encoding", "gzip")
defp maybe_put_encoding(conn, :identity), do: conn
end