towerops/lib/towerops/workers/cn_maestro_sync_worker.ex
Graham McIntire efaf5558ff refactor: convert 6 Gleam modules to idiomatic Elixir with TDD (#196)
Phase 1: Foundation Types (100% complete)
- query_helpers: SQL LIKE sanitization with pipe operators
- numeric: Integer parsing with pattern matching guards
- result: Pure Elixir Result monad (map, and_then, unwrap_or)

Phase 2: Ecto Domain Types (100% complete)
- ip_address: IPv4/IPv6 validation using :inet directly
- mac_address: Multi-format MAC parsing (colon/hyphen/dot/compact)
- snmp_oid: OID parsing/manipulation with recursive pattern matching

All 198 tests passing across converted modules.
API changed from Gleam-style {:some/:none to idiomatic {:ok/:error.
Refactored parse_numeric_oid to use with statement, reducing nesting depth.

Reviewed-on: graham/towerops-web#196
2026-03-28 09:52:07 -05:00

68 lines
1.8 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.Worker, queue: :maintenance
alias Towerops.CnMaestro.Sync
alias Towerops.Integrations
alias Towerops.Workers.PollingOffset
require Logger
@window_seconds 300
@impl Oban.Worker
def perform(%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 perform(%Oban.Job{args: %{"integration_id" => id}}) do
case Integrations.get_integration_by_id(id) do
{:ok, integration} ->
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)}")
:ok
end
{:error, :not_found} ->
Logger.warning("cnMaestro sync: integration #{id} not found")
:ok
end
end
end