A letterbox with a type

A process has a letterbox. The BEAM is happy to deliver almost anything to it.

This is generous. It also means somebody may eventually post a saucepan to your counter. I would like the compiler to raise a small objection before the saucepan leaves home.

Write the protocol down

In Pooka's OTP library, a server's message type describes what it accepts. A message that expects an answer carries a typed reply address:

module main

import pooka/otp.{Subject}
import pooka/otp/server

class Command {}

class Add(amount: Int) is Command

class Read(reply: Subject(Int)) is Command

Read asks for an integer. Its reply subject cannot be used to send a string. The request and its answer are connected by the types, rather than by a hopeful comment beside a tuple.

These declarations form the first part of one source file.

Give the callbacks a small object

The library accepts callback functions, and it also provides a Handler interface. An immutable class can implement it:

class Counting with server.Handler(Int, Command) {
  init(inbox: Subject(Command)) -> Result(Int, String) {
    let _ = inbox
    Ok(0)
  }

  handle(state: Int, message: Command) -> server.Next(Int) {
    match message {
      Add(amount) -> server.next(state + amount)
      Read(reply) -> {
        otp.send(reply, state)
        server.next(state)
      }
    }
  }
}

Int is the state. Command is the protocol. Each callback returns the next state explicitly; the object does not acquire a hidden mutable counter.

The callbacks run in the gen_server process. That detail matters when code uses its mailbox or creates a monitor. A native actor has its own process, so placing an actor behind an interface does not make the two process identities merge.

Ask, wait, and leave the room tidy

Add this below the handler:

main() {
  let specification = server.from_handler(Counting())
  let assert Ok(counter) = server.start(specification)
  server.send(counter, Add(3))
  assert server.call(counter, fn(reply) { Read(reply) }, 1000) == Ok(3)
  server.shutdown(counter)
}

The send is asynchronous. The call waits for a reply, with a timeout in milliseconds. Failure remains possible: a correct message type cannot promise that a process will still be alive when the letter arrives.

For a long-lived application, the server belongs under a supervisor. The supervisor owns starting and restarting it. A restarted process needs its state initialized again; a supervision tree is not a backup of the previous process's memory.

Pooka's native actors can join those trees too. Typed messages, interfaces and OTP are useful together, provided each keeps its own job.

Under the library is the ordinary Erlang gen_server. Familiar tools still have something familiar to inspect. The letterbox has gained a label; the post office remains the BEAM.

The OTP documentation has the supervisor and application pieces.

— Peregrine Finch

· pooka · otp · erlang