Hive.Worker

hive · API reference

Low-level fibers with typed mailboxes.

Low-level worker: a fiber + a typed mailbox + an effect context.

This is the substrate of Server; use it directly when you want a single message type and manual control (e.g. replies via explicit Eio.Promise values in your messages).

type 'msg t

A running worker consuming messages of type 'msg.

exception Stop

Raise from a handler to stop the worker gracefully: the worker's outcome resolves to Completed ().

val default_capacity : int

Default mailbox capacity used by spawn.

val spawn : 
  sw:Eio.Switch.t ->
  ?clock:Effects.clock ->
  ?capacity:int ->
  ?mailbox:'msg Mailbox.t ->
  ('msg t -> 'msg -> unit) ->
  'msg t

spawn ~sw handler forks a fiber under sw that takes messages from the mailbox in FIFO order and applies handler to each.

  • clock: when given, the Effects handler is installed so the handler body may call Effects.sleep.
  • capacity: mailbox bound (default default_capacity); ignored when mailbox is supplied.
  • An exception escaping handler stops the worker with outcome Failed; Stop stops it with Completed (); cancelling sw yields Cancelled. A small counter worker using explicit messages:
ocaml]
type msg = Incr | Stop

let count = ref 0 in
let worker =
  Hive.Worker.spawn ~sw (fun _self -> function
    | Incr -> incr count
    | Stop -> raise Hive.Worker.Stop)
in
ignore (Hive.Worker.send worker Incr)
val addr : 'msg t -> 'msg Addr.t

The worker's send capability.

val send : 'msg t -> 'msg -> (unit, [ `Closed ]) result

send t msg = Addr.send (addr t) msg.

val stop : 'msg t -> unit

Request immediate stop: closes the mailbox and cancels the worker fiber. Queued messages are dropped. Idempotent. For graceful, drain-first semantics use a protocol message or Server.

val outcome : 'msg t -> unit Outcome.t Eio.Promise.t

Resolved exactly once when the worker fiber finishes.

val is_running : 'msg t -> bool

true while the worker fiber is still accepting work.

This is a snapshot intended for diagnostics. A concurrent stop may make the result stale immediately after it is returned.