Arrea.Worker (Arrea v1.0.0)

Copy Markdown View Source

Worker GenServer para ejecución de tareas.

Ciclo de vida

  1. init/1 — Inicializa estado y se registra en Arrea.Monitor.
  2. handle_info(:execute_task, state) — Ejecuta la primera tarea de la cola.
  3. handle_cast({:message, msg}, state) — Procesa mensajes recibidos de otros workers.
  4. terminate/2 — Notifica al Monitor si el worker terminó de forma inesperada. Si terminó por su propio flujo normal (todas las tareas completadas o error gestionado), la notificación ya se emitió antes de {:stop, ...} y terminate no la duplica.

Formatos de mensaje aceptados

Worker.send_message/2 acepta:

  • Mapas con clave :type — mensaje estructurado genérico: %{type: :my_event, ...}
  • Tupla de enrutamiento: {:send_to_worker, target_worker_id, payload} — reenvía el payload al worker identificado por target_worker_id.

Política de errores

Si no se especifica policy al iniciar el worker, se usan los valores de Arrea.Config (:default_policy, :max_retries, :retry_delay).

Uso

Arrea.Worker.start_link(id: :worker_1, tasks: [fn -> :work end], parent: self())
Arrea.Worker.send_message(:worker_1, %{type: :ping})
Arrea.Worker.send_message(:worker_1, {:send_to_worker, :worker_2, %{type: :data, value: 42}})
{:ok, state} = Arrea.Worker.get_state(:worker_1)

Summary

Functions

Returns a specification to start this module under a supervisor.

Obtiene el estado actual del worker.

Envía un mensaje al worker identificado.

Inicia un worker con opciones configurables.

Functions

child_spec(init_arg)

Returns a specification to start this module under a supervisor.

See Supervisor.

get_state(worker_id)

@spec get_state(atom()) :: {:ok, Arrea.WorkerState.t()} | {:error, :not_found}

Obtiene el estado actual del worker.

Ejemplos

iex> Worker.get_state(:worker_1)
{:ok, %WorkerState{id: :worker_1, ...}}

iex> Worker.get_state(:nonexistent)
{:error, :not_found}

send_message(worker_id, message)

@spec send_message(atom(), term()) :: :ok

Envía un mensaje al worker identificado.

Formatos aceptados:

  • %{type: atom(), ...} — mensaje estructurado
  • {:send_to_worker, target_id, payload} — enruta payload a otro worker

Ejemplos

iex> Worker.send_message(:worker_1, %{type: :ping})
:ok

iex> Worker.send_message(:worker_1, {:send_to_worker, :worker_2, %{type: :data, value: 1}})
:ok

start_link(opts)

@spec start_link(keyword()) :: GenServer.on_start()

Inicia un worker con opciones configurables.

Opciones

  • :id — Identificador único del worker (requerido)
  • :tasks — Lista de funciones a ejecutar
  • :parent — PID del proceso padre (Leader)
  • :log — Habilitar logging (default: false)
  • :policy — Política de manejo de errores. Si es nil, se usan los valores de Arrea.Config (:default_policy, :max_retries, :retry_delay).
  • :telemetry — Habilitar telemetría (default: false)

Ejemplos

iex> Worker.start_link(id: :worker_1, tasks: [fn -> :ok end])
{:ok, pid}