# `Octoroom.Agent.Processor.StateMachine`
[🔗](https://github.com/samrat/octoroom/blob/v0.1.0/agents/lib/octoroom/agent/processor/state_machine.ex#L1)

A processor written as a state machine, with `gen_statem` semantics.

    defmodule MyApp.Turns do
      use Octoroom.Agent.Processor.StateMachine

      @impl true
      def init(_opts, _ctx), do: {:ok, :idle, %{}}

      @impl true
      def handle_event(%Frames.VADUserStoppedSpeaking{}, :speaking, data),
        do: {:next_state, :paused, data, [{:state_timeout, 2_000, :silence}]}

      def handle_event({:state_timeout, :silence}, :paused, data),
        do: {:next_state, :idle, data, [{:push, %Frames.UserStoppedSpeaking{}, :downstream}]}
    end

Events:

  * a frame moving downstream, as the frame itself
  * `{:upstream, frame}` for a frame moving upstream
  * `{:async, key, message}` for task messages
  * `{:timer, key}` for timers started with `{:timer, key, ms}`
  * `{:state_timeout, key}` for state timeouts
  * `{:info, message}` for other messages
  * `{:update, opts}` for an `UpdateStage` frame naming the stage (see
    `Octoroom.Agent.Processor`). Unmatched, it reports an error.

Results: `{:next_state, name, data}`, `{:next_state, name, data, actions}`,
`{:keep_state, data}`, `{:keep_state, data, actions}`,
`:keep_state_and_data` or `{:keep_state_and_data, actions}`.

Actions are processor effects (see `Octoroom.Agent.Processor`) plus:

  * `{:state_timeout, ms, key}` - fires `{:state_timeout, key}` unless the
    state changes first
  * `:postpone` - hold the current event and deliver it again after the next
    state change

On a state change, the optional `state_enter(old_state, new_state, data)`
runs and returns `{:keep_state, data, actions}` (or `:keep_state_and_data`),
then postponed events are delivered again in order.

Frames and other events that no `handle_event/3` clause matches pass through
(frames) or are ignored (everything else).

# `handle_event`

```elixir
@callback handle_event(event :: term(), state_name :: term(), data :: term()) :: term()
```

# `init`

```elixir
@callback init(opts :: keyword(), ctx :: map()) ::
  {:ok, state_name :: term(), data :: term()} | {:error, term()}
```

# `state_enter`
*optional* 

```elixir
@callback state_enter(old :: term(), new :: term(), data :: term()) :: term()
```

---

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