Module: Zeridion::Flare::Worker::Identity

Defined in:
lib/zeridion_flare/worker/identity.rb

Overview

Builds the worker id: wrk_host_pid_rand

* host is SANITIZED to [A-Za-z0-9_-] (replace "." with "-", strip
anything else) so a raw FQDN like "web-01.prod.internal" can't
violate the server's `^[A-Za-z0-9_\-]+$` regex — which would 422 and
silently kill BOTH register and poll.
* rand is >= 12 hex chars (>= 48 bits) from a CSPRNG, so two workers
sharing a container hostname (PID 1) don't collide and cross-talk.
* the whole id is truncated to <= 200 chars (register's cap). The
random suffix is preserved; the HOST portion is trimmed if needed so
uniqueness survives truncation.

Constant Summary collapse

MAX_LEN =
200
RAND_HEX =

48 bits of entropy

12

Class Method Summary collapse

Class Method Details

.default_hostnameObject



54
55
56
57
58
# File 'lib/zeridion_flare/worker/identity.rb', line 54

def default_hostname
  Socket.gethostname
rescue StandardError
  "host"
end

.generate(hostname: nil, pid: Process.pid, rand_hex: RAND_HEX) ⇒ String

Parameters:

  • hostname (String, nil) (defaults to: nil)

    override host (default: machine hostname)

  • pid (Integer) (defaults to: Process.pid)

    override pid (default: this process)

  • rand_hex (Integer) (defaults to: RAND_HEX)

    hex chars of CSPRNG entropy (>= 12)

Returns:

  • (String)


30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/zeridion_flare/worker/identity.rb', line 30

def generate(hostname: nil, pid: Process.pid, rand_hex: RAND_HEX)
  host = sanitize(hostname || default_hostname)
  rand = secure_hex([rand_hex, RAND_HEX].max)
  suffix = "_#{pid}_#{rand}"
  prefix = "wrk_"

  # Trim the host so prefix + host + suffix <= MAX_LEN, never sacrificing
  # the random suffix (uniqueness lives there).
  budget = MAX_LEN - prefix.length - suffix.length
  host = "w" if host.empty? # never emit "wrk__<pid>_<rand>" with a blank host
  host = host[0, budget] if budget.positive? && host.length > budget
  host = "w" if budget <= 0

  "#{prefix}#{host}#{suffix}"
end

.sanitize(raw) ⇒ Object

Sanitize a hostname to the server-allowed alphabet.



47
48
49
50
51
52
# File 'lib/zeridion_flare/worker/identity.rb', line 47

def sanitize(raw)
  s = raw.to_s
  s = s.tr(".", "-")        # dotted FQDN segments become dashes
  s = s.gsub(/[^A-Za-z0-9_-]/, "") # strip everything else
  s
end

.secure_hex(n) ⇒ Object

n hex characters from a CSPRNG (n rounded up to an even count).



61
62
63
64
# File 'lib/zeridion_flare/worker/identity.rb', line 61

def secure_hex(n)
  bytes = (n + 1) / 2
  SecureRandom.hex(bytes)[0, n]
end