GenServer
A Gale GenServer implements gale_std.gen_server.Server. The compiler
checks its callbacks like any behaviour implementation. This chapter builds
a counter, a supervisor, and a quota server with verified state transitions.
A typed GenServer
Section titled “A typed GenServer”The Server interface takes the module value, state type, and message
types; indexed request constructors fix each call’s reply type. Everything
else is ordinary functions:
OTP is standard library, not extra compiler syntax. A server is an ordinary
module that implements gale_std.gen_server.Server. Gale emits the native
callback module with @behaviour Elixir.GenServer and explicit @impl Elixir.GenServer
attributes. It does not emit use GenServer.
mod example_otp.counter
alias gale_std.gen_serveralias gale_std.otp
implements gen_server.Server<Integer,Integer,CounterCall,CounterCast,Never,Never> as Service
pub type CounterCall<R> =| Value : CounterCall<Integer>| Add(amount: Integer) : CounterCall<Integer>
pub type CounterCast = Reset | Incrementpub type CounterTarget = gen_server.ServerTarget<Service>
pub fn start_link(initial: Integer) -> gen_server.StartResult<Service> { name: gen_server.ServerName<Service> = gen_server.named(:counter) gen_server.start_link(example_otp.counter, initial, [{:name, name}])}
pub fn child_spec(initial: Integer) -> ChildSpec<Service> { gen_server.child_spec(example_otp.counter, initial, [{:id, :counter}])}
pub fn value(server: CounterTarget) -> Result<Integer, gen_server.CallError> { gen_server.call(server, Value)}
pub fn add(server: CounterTarget, amount: Integer) -> Result<Integer, gen_server.CallError> { gen_server.call(server, Add(amount: amount))}
pub fn reset(server: CounterTarget) -> :ok { gen_server.cast(server, Reset)}
pub fn increment(server: CounterTarget) -> :ok { gen_server.cast(server, Increment)}
pub fn init(initial: Integer) -> otp.Init<Integer, Never> { {:ok, initial}}
pub fn handle_call<R>( request: CounterCall<R>, from: gen_server.ReplyTo<R>, state: Integer) -> otp.CallNext<R, Integer, Never> { case request { Value -> { gen_server.reply(from, state) {:noreply, state} } Add(amount: amount) -> { next = state + amount gen_server.reply(from, next) {:noreply, next} } }}
pub fn handle_cast( message: CounterCast, state: Integer) -> otp.Next<Integer, Never> { case message { Reset -> {:noreply, 0} Increment -> {:noreply, state + 1} }}Calls return Result, with CallTimeout or CallFailed carrying the native
exit reason on failure; casts stay fire-and-forget; a nested Result reply stays
nested inside the call envelope. Matching a request refines R, so each
branch’s ReplyTo<R> accepts exactly that constructor’s reply type.
Supervisor callbacks
Section titled “Supervisor callbacks”gale_std.supervisor.Supervisor<Args> is Elixir.Supervisor. The callback
returns the same native init value as Elixir. There is no macro or extra
runtime supervisor module.
mod example_otp.tree
alias example_otp.counteralias gale_std.supervisor
implements supervisor.Supervisor<:ok> as Root
pub fn start_link() -> supervisor.SupervisorStartResult<mod supervisor.Supervisor<:ok>> { supervisor.start_link(example_otp.tree, :ok, [])}
pub fn child_spec(args: :ok) -> ChildSpec<mod supervisor.Supervisor<:ok>> { supervisor.child_spec(example_otp.tree, args)}
pub fn init(args: :ok) -> supervisor.SupervisorInit { supervisor.init( [supervisor.any_child(counter.child_spec(0))], [{:strategy, :one_for_one}] )}Opaque state with a proved invariant
Section titled “Opaque state with a proved invariant”The quota maintains 0 <= reserved <= capacity. Only quota_state can
construct its opaque state. gale verify proves that the API preserves the
invariant and that available returns a nonnegative result. Successful reservations and releases
state the exact change in available capacity. quota_input.decode_config uses the stdlib decoder to validate an untrusted
map with an integer "capacity" field before constructing the opaque state;
malformed or negative input returns Error(:invalid). An accepted state proves
available(state) >= 0. start_link_input passes
that validated result to the server, whose callbacks keep the business logic in
quota_state.
Run mix gale.verify in this example to prove the configured quota-state
functions. The runtime message test starts from untrusted configuration, reserves
capacity, rejects an excessive reservation without changing state, and releases
capacity. These checks do not prove message delivery or process survival.
A quota whose reserved amount stays between zero and capacity.
Outside this module, opaque State can only come from these functions.
A GenServer can store State without exposing its fields.
mod example_otp.quota_state
@moduledoc """A quota whose reserved amount stays between zero and capacity.
Outside this module, opaque `State` can only come from these functions.A GenServer can store `State` without exposing its fields."""
pub opaque type State = %{reserved: Integer, capacity: Integer}invariant(state) { state.reserved >= 0 and state.reserved <= state.capacity}
pub fn new(capacity: Integer) -> Result<State, :invalid>ensures { case result { Ok(state) -> available(state) == capacity Error(_) -> capacity < 0 }}{ if capacity >= 0 { Ok(State(%{reserved: 0, capacity: capacity})) } else { Error(:invalid) }}
pub fn reserve(current: State, amount: Integer) -> Result<State, :invalid>ensures { case result { Ok(next) -> available(next) == available(current) - amount Error(_) -> amount < 0 or amount > available(current) }}{ State(state) = current if amount >= 0 and amount <= state.capacity - state.reserved { Ok(State(%{state | reserved: state.reserved + amount})) } else { Error(:invalid) }}
pub fn release(current: State, amount: Integer) -> Result<State, :invalid>ensures { case result { Ok(next) -> available(next) == available(current) + amount Error(_) -> true }}{ State(state) = current if amount >= 0 and amount <= state.reserved { Ok(State(%{state | reserved: state.reserved - amount})) } else { Error(:invalid) }}
pub fn available(State(state): State) -> Integerensures { result >= 0 }ensures { result == state.capacity - state.reserved }{ state.capacity - state.reserved}Validates untrusted quota configuration before the server starts. Malformed fields and negative capacities return the same explicit error. The proved fact is that an accepted state has nonnegative availability. A complete account of which inputs are rejected would be a separate contract.
mod example_otp.quota_input
@moduledoc """Validates untrusted quota configuration before the server starts.Malformed fields and negative capacities return the same explicit error.The proved fact is that an accepted state has nonnegative availability.A complete account of which inputs are rejected would be a separate contract."""
alias example_otp.quota_statealias gale_std.decode
pub fn decode_config(input: Term) -> Result<quota_state.State, :invalid>ensures { case result { Ok(state) -> quota_state.available(state) >= 0 Error(_) -> true }}{ case decode.field(input, "capacity", decode.integer()) { Ok(capacity) -> quota_state.new(capacity) Error(_) -> Error(:invalid) }}The server callbacks translate messages into calls to the pure, proved transitions. A rejected reserve replies with the error and keeps the previous valid state:
A GenServer whose state is an opaque quota.
Callbacks handle messages and replies. quota_state owns the pure
transitions. A rejected reserve returns an error and keeps the previous
valid state. The type does not prove delivery, liveness, or crash freedom.
mod example_otp.quota
@moduledoc """A GenServer whose state is an opaque quota.
Callbacks handle messages and replies. `quota_state` owns the puretransitions. A rejected reserve returns an error and keeps the previousvalid state. The type does not prove delivery, liveness, or crash freedom."""
alias example_otp.quota_inputalias example_otp.quota_statealias gale_std.gen_serveralias gale_std.otp
implements gen_server.Server< Result<quota_state.State, :invalid>, quota_state.State, Request, Never, Never, Never> as Service
pub type Request<R> = | Available: Request<Integer> | Reserve(amount: Integer): Request<Result<Integer, :invalid>> | Release(amount: Integer): Request<Result<Integer, :invalid>>
pub type Target = gen_server.ServerTarget<Service>
pub fn start_link(capacity: Integer) -> gen_server.StartResult<Service> { gen_server.start_link(example_otp.quota, quota_state.new(capacity), [])}
pub fn start_link_input(input: Term) -> gen_server.StartResult<Service> { gen_server.start_link(example_otp.quota, quota_input.decode_config(input), [])}
pub fn available(server: Target) -> Result<Integer, gen_server.CallError> { gen_server.call(server, Available)}
pub fn reserve( server: Target, amount: Integer) -> Result<Result<Integer, :invalid>, gen_server.CallError> { gen_server.call(server, Reserve(amount: amount))}
pub fn release( server: Target, amount: Integer) -> Result<Result<Integer, :invalid>, gen_server.CallError> { gen_server.call(server, Release(amount: amount))}
pub fn init(initial: Result<quota_state.State, :invalid>) -> otp.Init<quota_state.State, Never> { case initial { Ok(state) -> {:ok, state} Error(reason) -> {:stop, reason} }}
fn finish( old: quota_state.State, next: Result<quota_state.State, :invalid>, reply_to: gen_server.ReplyTo<Result<Integer, :invalid>>) -> otp.Next<quota_state.State, Never> { case next { Ok(state) -> { gen_server.reply(reply_to, Ok(quota_state.available(state))) {:noreply, state} } Error(reason) -> { gen_server.reply(reply_to, Error(reason)) {:noreply, old} } }}
pub fn handle_call<R>( request: Request<R>, from: gen_server.ReplyTo<R>, state: quota_state.State) -> otp.CallNext<R, quota_state.State, Never> { case request { Available -> { gen_server.reply(from, quota_state.available(state)) {:noreply, state} } Reserve(amount: amount) -> finish(state, quota_state.reserve(state, amount), from) Release(amount: amount) -> finish(state, quota_state.release(state, amount), from) }}Opacity is enforced at the module boundary: a callback that builds the raw
%{reserved: _, capacity: _} record and returns it as quota_state.State
does not compile.
Failure and restart
Section titled “Failure and restart”A rejected reservation keeps the previous state. A process crash is different: OTP may restart the child, running initialization again. This example does not persist reservations across restarts. Typed messages and state proofs do not guarantee delivery, liveness, or recovery.
For callback defaults, registries, tasks and other OTP APIs, use the standard library reference and the verification reference.