PgFlow.Worker.Lifecycle (PgFlow v0.1.0)

Copy Markdown View Source

Worker lifecycle state machine.

Manages worker state transitions following the same pattern as the TypeScript/Deno pgflow WorkerState. Validates that only allowed transitions occur.

States

  • :created - Worker has been created but not yet started
  • :starting - Worker is starting but not yet processing messages
  • :running - Worker is actively processing messages
  • :stopping - Worker stopped processing, releasing resources
  • :stopped - Worker has stopped and released resources (terminal state)

State Transitions

created -> starting -> running -> stopping -> stopped

Usage

lifecycle = Lifecycle.new()
{:ok, lifecycle} = Lifecycle.transition(lifecycle, :starting)
{:ok, lifecycle} = Lifecycle.transition(lifecycle, :running)

Lifecycle.running?(lifecycle)
#=> true

Summary

Functions

Returns true if the worker can accept new work.

Returns the current state.

Creates a new lifecycle in the :created state.

Returns true if in :running state.

Returns true if in :stopped state.

Transitions to a new state if the transition is valid.

Transitions to a new state, raising on invalid transition.

Types

state()

@type state() :: :created | :starting | :running | :stopping | :stopped

t()

@type t() :: %PgFlow.Worker.Lifecycle{state: state()}

Functions

can_accept_work?(arg1)

@spec can_accept_work?(t()) :: boolean()

Returns true if the worker can accept new work.

A worker can accept work only when in the :running state.

current(lifecycle)

@spec current(t()) :: state()

Returns the current state.

Examples

Lifecycle.current(lifecycle)
#=> :running

new()

@spec new() :: t()

Creates a new lifecycle in the :created state.

Examples

lifecycle = Lifecycle.new()
lifecycle.state
#=> :created

running?(arg1)

@spec running?(t()) :: boolean()

Returns true if in :running state.

stopped?(arg1)

@spec stopped?(t()) :: boolean()

Returns true if in :stopped state.

transition(lifecycle, new_state)

@spec transition(t(), state()) ::
  {:ok, t()} | {:error, {:invalid_transition, state(), state()}}

Transitions to a new state if the transition is valid.

Returns {:ok, lifecycle} if the transition is valid, or {:error, reason} if the transition is not allowed.

Examples

{:ok, lifecycle} = Lifecycle.transition(lifecycle, :starting)
{:error, {:invalid_transition, :created, :running}} = Lifecycle.transition(lifecycle, :running)

transition!(lifecycle, new_state)

@spec transition!(t(), state()) :: t()

Transitions to a new state, raising on invalid transition.

Examples

lifecycle = Lifecycle.transition!(lifecycle, :starting)