SuperWorker.Supervisor.Utils (SuperWorker v0.6.0)

Copy Markdown View Source

Utility functions for SuperWorker.Supervisor.

This module provides common utility functions used across the supervisor implementation, including:

  • Hashing and partitioning utilities
  • Process information helpers

Summary

Functions

Counts the number of messages in a process's message queue.

Returns the number of online schedulers in the system.

Computes a hash-based order for partitioning data.

Generates a cryptographically secure random ID.

Invokes a zero-arity function and never lets exceptions escape.

Like safe_call/1 for remote calls: apply(module, function, arguments).

Functions

count_msgs(pid)

@spec count_msgs(pid()) :: non_neg_integer()

Counts the number of messages in a process's message queue.

Returns 0 if the process is not alive.

get_default_schedulers()

@spec get_default_schedulers() :: pos_integer()

Returns the number of online schedulers in the system.

This is typically used as the default number of partitions.

get_hash_order(term, num_partitions)

@spec get_hash_order(term(), pos_integer()) :: non_neg_integer()

Computes a hash-based order for partitioning data.

Uses Erlang's phash2 for consistent hashing across the cluster.

Examples

iex> order = get_hash_order("my_data", 10)
iex> order >= 0 and order < 10
true

random_id()

@spec random_id() :: String.t()

Generates a cryptographically secure random ID.

Returns a 32-character hexadecimal string.

Examples

iex> id = random_id()
iex> String.length(id)
32

safe_call(fun)

@spec safe_call((-> term())) :: {:ok, term()} | {:error, {atom(), term()}}

Invokes a zero-arity function and never lets exceptions escape.

Returns {:ok, result} on success or {:error, {kind, reason}} when the function throws, raises or exits. Used everywhere user supplied callbacks are invoked so a faulty callback cannot take down supervisor processes.

Examples

iex> safe_call(fn -> 1 + 1 end)
{:ok, 2}

iex> match?({:error, {:error, %RuntimeError{}}}, safe_call(fn -> raise "boom" end))
true

iex> match?({:error, {:exit, :halt}}, safe_call(fn -> exit(:halt) end))
true

iex> safe_call(Enum, :sum, [[1, 2, 3]])
{:ok, 6}

safe_call(module, function, arguments)

@spec safe_call(module(), atom(), [term()]) ::
  {:ok, term()} | {:error, {atom(), term()}}

Like safe_call/1 for remote calls: apply(module, function, arguments).

Examples

iex> safe_call(Enum, :sum, [[1, 2, 3]])
{:ok, 6}