Structure for a worker's state.
Fields
:id- Unique worker identifier:tasks- List of pending tasks (0-arity functions):status- Current state (:idle, :running, :finished, :error):started_at- Start timestamp in monotonic milliseconds:ended_at- End timestamp (only for :finished or :error):parent- PID of the parent process (Leader or supervisor):log?- Enable logging:progress- Current progress (0-100):total_tasks- Total number of tasks:completed_tasks- Number of completed tasks:results- List of completed task results:policy- Error/warning policy:retry_count- Retry counter:warnings- List of accumulated warnings
Usage
state = WorkerState.new(:worker_1, [fn -> :work end], parent: self(), log: true)
state = WorkerState.update_progress(state, 5)
state = WorkerState.add_result(state, {:ok, :result})
elapsed = WorkerState.elapsed_time(state)
Summary
Functions
Adds a result to the results list.
Calculates the elapsed time since the worker started.
Creates a new worker state.
Updates the worker progress.
Types
@type t() :: %Arrea.WorkerState{ completed_tasks: non_neg_integer(), ended_at: integer() | nil, id: atom() | String.t(), log?: boolean(), parent: pid() | nil, policy: map() | nil, progress: float(), results: [term()], retry_count: non_neg_integer(), started_at: integer() | nil, status: :idle | :running | :finished | :error, tasks: [function()], total_tasks: non_neg_integer(), warnings: [term()] }
Functions
Adds a result to the results list.
Examples
iex> state = WorkerState.new(:w1, [])
iex> state = WorkerState.add_result(state, {:ok, :value})
iex> state.results
[{:ok, :value}]
Calculates the elapsed time since the worker started.
If the worker has finished (:finished or :error), returns the final time. If the worker is running, returns the time up to now.
Examples
iex> state = WorkerState.new(:w1, [])
iex> elapsed = WorkerState.elapsed_time(state)
iex> is_integer(elapsed)
true
Creates a new worker state.
Parameters
id- Unique identifiertasks- List of functions to executeopts- Additional options
Options
:parent- PID of the parent process:log- Enable logging (default: false):policy- Error/warning policy (default: nil)
Examples
iex> WorkerState.new(:worker_1, [fn -> :ok end])
%WorkerState{id: :worker_1, tasks: [...], status: :idle, ...}
iex> WorkerState.new(:worker_1, [fn -> :ok end], parent: self(), log: true)
%WorkerState{id: :worker_1, parent: #PID<...>, log?: true, ...}
@spec update_progress(t(), non_neg_integer()) :: t()
Updates the worker progress.
Examples
iex> state = WorkerState.new(:w1, [fn -> :ok end, fn -> :ok end])
iex> state = WorkerState.update_progress(state, 1)
iex> state.progress
50.0