Raxol.Core.Utils.GenServerHelpers (Raxol Core v2.4.0)

Copy Markdown View Source

Common GenServer patterns and utilities to reduce code duplication. Provides standardized handlers for common operations like state retrieval, metrics collection, and configuration management.

Summary

Functions

Ensures a named process is running. Starts it via start_fun if not found.

Standard handler for getting specific state fields.

Standard handler for getting metrics from state.

Standard handler for getting state information.

Standard handler for getting status information.

Standard handler for resetting metrics.

Standard handler for updating configuration.

Utility to increment a metric counter.

Initialize default state with common fields.

Splits a keyword list into GenServer server options and init args.

Utility to update a metric value.

Functions

ensure_started(name, start_fun)

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

Ensures a named process is running. Starts it via start_fun if not found.

The start_fun is a zero-arity function that should return {:ok, pid}.

Examples

ensure_started(MyServer, fn -> MyServer.start_link(name: MyServer) end)

handle_get_field(field, state)

Standard handler for getting specific state fields.

handle_get_metrics(state)

Standard handler for getting metrics from state.

handle_get_state(state)

Standard handler for getting state information.

handle_get_status(state)

Standard handler for getting status information.

handle_reset_metrics(state)

Standard handler for resetting metrics.

handle_update_config(new_config, state)

Standard handler for updating configuration.

increment_metric(state, metric_name, amount \\ 1)

Utility to increment a metric counter.

init_default_state(custom_state \\ %{})

Initialize default state with common fields.

split_server_opts(opts)

@spec split_server_opts(keyword() | map() | term()) :: {keyword(), keyword() | term()}

Splits a keyword list into GenServer server options and init args.

Server options (:name, :timeout, :debug, :spawn_opt) are separated from the remaining application-specific options.

Examples

iex> split_server_opts(name: MyServer, timeout: 5000, foo: :bar)
{[name: MyServer, timeout: 5000], [foo: :bar]}

iex> split_server_opts(%{name: MyServer})
{[name: MyServer], []}

update_metric(state, metric_name, value)

Utility to update a metric value.