prop/lib/microwaveprop_web/controllers/contact_map_controller.ex
Graham McIntire 578b4ede86 Serve /contacts/map payload via HTTP endpoint, parallel hydrate
- Add ContactMapController serving /api/contacts/map with pre-gzipped
  JSON from Microwaveprop.Cache. Browsers handle Content-Encoding: gzip
  natively; payload drops from 5.7 MB raw to 1.5 MB on the wire (73%).
  Cache TTL 10 min, invalidated on contact insert alongside the other
  contact-map cache keys.
- Move contact map payload out of the LiveView's initial HTML entirely.
  Shell renders with the filter chrome (count + band list); the hook
  fetches contacts from the HTTP endpoint in parallel with map init.
  This also avoids Phoenix.Socket's 64 KB frame limit (push_event would
  have required chunked transfer or a global frame size bump).
- Parallelize ContactLive.Show hydrate: five independent DB loads
  (weather, solar, hrrr_path, terrain, iemre) now run concurrently via
  Task.async + Task.await_many. Total latency drops from sum(each) to
  max(each), cutting contact show hydrate time roughly 5x.
2026-04-12 13:10:51 -05:00

53 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
@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