# `PgFlow.Worker.Lifecycle`
[🔗](https://github.com/agoodway/pgflow/blob/v0.1.0/lib/pgflow/worker/lifecycle.ex#L1)

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

# `state`

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

# `t`

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

# `can_accept_work?`

```elixir
@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`

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

Returns the current state.

## Examples

    Lifecycle.current(lifecycle)
    #=> :running

# `new`

```elixir
@spec new() :: t()
```

Creates a new lifecycle in the `:created` state.

## Examples

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

# `running?`

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

Returns true if in `:running` state.

# `stopped?`

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

Returns true if in `:stopped` state.

# `transition`

```elixir
@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!`

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

Transitions to a new state, raising on invalid transition.

## Examples

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

---

*Consult [api-reference.md](api-reference.md) for complete listing*
