1005 B · text History 4b6fe3b
defmodule OhMyExOhIrcd.Sightings.Writer do
  @moduledoc """
  Takes sighting writes off the IRC connection's hot path: connections
  `cast` here and move on. One per node. A failed write is logged and
  dropped — it never reaches (or crashes) the connection.
  """

  use GenServer
  require Logger

  alias OhMyExOhIrcd.Sightings

  def start_link(opts), do: GenServer.start_link(__MODULE__, opts, name: __MODULE__)

  @doc "Queue a sighting event (see `Sightings.record/1`)."
  def record(event), do: GenServer.cast(__MODULE__, {:record, event})

  @impl true
  def init(_opts), do: {:ok, %{}}

  @impl true
  def handle_cast({:record, event}, state) do
    case Sightings.record(event) do
      {:error, reason} ->
        Logger.warning("Sighting of #{event.nick} not saved: #{inspect(reason)}")

      _ ->
        :ok
    end

    {:noreply, state}
  rescue
    e ->
      Logger.warning("Sighting of #{inspect(event[:nick])} not saved: #{Exception.message(e)}")
      {:noreply, state}
  end
end