GenLoop behaviour (GenLoop v2.0.0)

Features

  • OTP Compliant: Handles system messages (sys module), parent supervision, and debugging.
  • Selective Receive: Use receive blocks to pick messages when you want them, enabling complex state machines or protocols to be implemented more naturally.
  • Convenient Macros: rcall/2 and rcast/1 macros to easily match on GenLoop.call/2 and GenLoop.cast/2 messages.
  • Familiar API: Uses start_link/3, call/3, cast/2 similar to GenServer.

Usage

To use GenLoop, use GenLoop in your module. You need to define an entry point function (default is enter_loop/1 or specified via enter: :function_name).

Basic Example

Here is a simple Stack implementation:

defmodule Stack do
  use GenLoop

  # Client API

  def start_link(initial_stack) do
    GenLoop.start_link(__MODULE__, initial_stack, name: __MODULE__)
  end

  def push(item) do
    GenLoop.cast(__MODULE__, {:push, item})
  end

  def pop do
    GenLoop.call(__MODULE__, :pop)
  end

  # Server Callbacks

  # Optional: init/1 can be used to validate args or set up initial state.
  # It should return {:ok, state}, {:stop, reason}, or :ignore.
  def init(initial_stack) do
    {:ok, initial_stack}
  end

  # The main loop.
  # The `receive/2` macro (provided by GenLoop) is used instead of `receive/1`.
  # It takes the current state as the first argument to handle system messages automatically.
  def enter_loop(stack) do
    receive stack do
      # Match a synchronous call
      rcall(from, :pop) ->
        case stack do
          [head | tail] ->
            reply(from, head) # Helper to send reply
            enter_loop(tail)  # Loop with new state
          [] ->
            reply(from, nil)
            enter_loop([])
        end

      # Match an asynchronous cast
      rcast({:push, item}) ->
        enter_loop([item | stack])

      # Match standard messages
      other ->
        IO.inspect(other, label: "Unexpected message")
        enter_loop(stack)
    end
  end
end

Using the Process

{:ok, _pid} = Stack.start_link([1, 2])

Stack.pop()
#=> 1

Stack.push(3)
#=> :ok

Stack.pop()
#=> 3

Why GenLoop?

vs GenServer

GenServer is the standard abstraction for client-server relations. However, it forces you to handle every message in a callback (handle_call, handle_info, etc.). This is great for most cases, but can be cumbersome for complex state machines where the set of expected messages changes depending on the state.

GenLoop allows you to write a "plain" recursive loop with receive, so you can wait for specific messages at specific times (selective receive).

vs :gen_statem

:gen_statem is the OTP standard for state machines. It is very powerful but can be verbose. GenLoop offers a middle ground: it's simpler and feels more like writing a raw Elixir process, but with the safety net of OTP compliance.

Advanced Usage

Custom Entry Point

You can specify a different entry function name:

use GenLoop, enter: :my_loop

def my_loop(state) do
  # ...
end

Handling System Messages

The receive state do ... end macro is the magic that makes your loop OTP-compliant. It expands to a receive block that also includes clauses for handling system messages (like sys.get_state, sys.suspend, etc.) and parent exit signals.

If you want to handle everything manually (not recommended unless you know what you are doing), you can use the standard receive do ... end, but your process will not respond to standard OTP system calls.

Acknowledgements

This library is built on top of :plain_fsm by Ulf Wiger. It also draws inspiration from plain_fsm_ex by ashneyderman.

Summary

Types

Debug options supported by the start* functions

Tuple describing the client of a call request. pid is the PID of the caller and tag is a unique term used to identify the call.

The GenLoop name

Return values of start* functions

Option values used by the start* functions

Options used by the start* functions

The server reference

Types

debug()

@type debug() :: [:trace | :log | :statistics | {:log_to_file, Path.t()}]

Debug options supported by the start* functions

from()

@type from() :: {pid(), tag :: term()}

Tuple describing the client of a call request. pid is the PID of the caller and tag is a unique term used to identify the call.

name()

@type name() :: atom() | {:global, term()} | {:via, module(), term()}

The GenLoop name

on_start()

@type on_start() ::
  {:ok, pid()} | :ignore | {:error, {:already_started, pid()} | term()}

Return values of start* functions

option()

@type option() ::
  {:debug, debug()}
  | {:name, name()}
  | {:timeout, timeout()}
  | {:spawn_opt, Process.spawn_opt()}

Option values used by the start* functions

options()

@type options() :: [option()]

Options used by the start* functions

server()

@type server() :: pid() | name() | {atom(), node()}

The server reference

Callbacks

data_vsn()

@callback data_vsn() :: term()

init(args)

@callback init(args :: term()) ::
  {:ok, state}
  | {:ok, state, timeout() | :hibernate}
  | :ignore
  | {:stop, reason :: any()}
when state: any()

Functions

abcast(server, term)

See GenServer.abcast/2.

abcast(nodes, server, term)

@spec abcast([node()], name :: atom(), term()) :: :abcast

See GenServer.abcast/3.

call(server, request, timeout \\ 5000)

@spec call(server(), term(), timeout()) :: term()

cast(server, term)

@spec cast(server(), term()) :: term()

See GenServer.cast/2.

from_pid(from)

(macro)

hibernate(module, function, args)

(macro)

multi_call(nodes \\ [node() | Node.list()], name, request, timeout \\ :infinity)

@spec multi_call([node()], name :: atom(), term(), timeout()) ::
  {replies :: [{node(), term()}], bad_nodes :: [node()]}

rcall(from, msg)

(macro)

rcast(msg)

(macro)

receive(state_var, blocks)

(macro)

reply(from, term)

@spec reply(from(), term()) :: :ok

See GenServer.reply/2.

send(server, message)

@spec send(server(), term()) :: term()

Behaves just like Kernel.send but accepts atoms or registry tuples on top of pids to identify a process.

start(module, args, options \\ [])

@spec start(module(), any(), options()) :: on_start()

start_link(module, args, options \\ [])

@spec start_link(module(), any(), options()) :: on_start()

stop(server)

See GenServer.stop/1.

stop(server, reason)

See GenServer.stop/2.

stop(server, reason, timeout)

@spec stop(server(), reason :: term(), timeout()) :: :ok

See GenServer.stop/3.

whereis(name)

@spec whereis(server()) :: pid() | {atom(), node()} | nil

See GenServer.whereis/1.