towerops/lib/towerops/workers/polling_offset.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

30 lines
997 B
Elixir

defmodule Towerops.Workers.PollingOffset do
@moduledoc """
Calculates deterministic polling offsets to distribute load across time.
Uses erlang's phash2 to generate stable offsets from device IDs,
ensuring each device polls at a different time within the interval.
This prevents the "thundering herd" problem.
"""
@doc """
Calculates a deterministic offset for polling based on device ID.
Returns an integer in the range [0, interval_seconds).
## Examples
iex> offset = PollingOffset.calculate_offset("device-123", 300)
iex> offset >= 0 and offset < 300
true
iex> offset1 = PollingOffset.calculate_offset("same-id", 60)
iex> offset2 = PollingOffset.calculate_offset("same-id", 60)
iex> offset1 == offset2
true
"""
@spec calculate_offset(term(), pos_integer()) :: non_neg_integer()
def calculate_offset(device_id, interval_seconds) when interval_seconds > 0 do
rem(:erlang.phash2(device_id), interval_seconds)
end
end