towerops/lib/towerops/workers/cn_maestro_sync_worker.ex

77 lines
2.2 KiB
Elixir

defmodule Towerops.Workers.CnMaestroSyncWorker do
@moduledoc """
Oban worker for scheduled cnMaestro sync.
Same pattern as UispSyncWorker: cron dispatcher + staggered individual jobs.
"""
use Oban.Pro.Worker, queue: :maintenance
alias Towerops.CnMaestro.Sync
alias Towerops.Integrations
alias Towerops.Workers.PollingOffset
alias Towerops.Workers.SyncErrors
require Logger
@window_seconds 300
@impl Oban.Pro.Worker
def process(%Oban.Job{args: args}) when args == %{} do
integrations = Integrations.list_enabled_integrations("cn_maestro")
now = DateTime.utc_now()
enqueued =
Enum.count(integrations, fn integration ->
offset = PollingOffset.calculate_offset(integration.organization_id, @window_seconds)
scheduled_at = DateTime.add(now, offset, :second)
case %{"integration_id" => integration.id}
|> new(scheduled_at: scheduled_at, unique: [period: @window_seconds])
|> Oban.insert() do
{:ok, _} ->
true
{:error, changeset} ->
Logger.error(
"Failed to enqueue cnMaestro sync job for integration_id=#{integration.id}: #{inspect(changeset)}"
)
false
end
end)
if enqueued > 0 do
Logger.info("cnMaestro sync: dispatched #{enqueued} jobs")
end
:ok
end
def process(%Oban.Job{args: %{"integration_id" => id}}) do
case Integrations.get_integration_by_id(id) do
{:ok, integration} ->
sync_integration(integration)
{:error, :not_found} ->
Logger.warning("cnMaestro sync: integration #{id} not found")
:ok
end
end
defp sync_integration(integration) do
case Sync.sync_organization(integration) do
{:ok, result} ->
Logger.info("cnMaestro sync completed: #{inspect(result)}")
:ok
{:error, reason} ->
Logger.error("cnMaestro sync failed: #{inspect(reason)}")
# Distinguish permanent failures (auth, bad config) from transient
# ones (network, rate limits, 5xx) so Oban retries the latter —
# stale monitoring data is worse than a redundant retry on a
# permanent failure.
if SyncErrors.transient?(reason), do: {:error, reason}, else: :ok
end
end
end