riot-ml / riot

An actor-model multi-core scheduler for OCaml 5 🐫
https://riot.ml
Other
548 stars 37 forks source link

Make Riot.run return a `(int, [> `Msg of string ]) result` #50

Closed leostera closed 5 months ago

leostera commented 7 months ago

To make it easier to write quick programs and use let* bindings for results, it'd be best if Riot.run takes a function that returns a result of an int (status code), or a polyvariant for an error.

This would allow us to run programs like:

let () = Riot.run @@ fun () -> Ok 0

which means we can do programs like the following much more easily:

let () = Riot.run @@ fun () ->
  let* conn = Blink.connect "URL" in
  (* ... *)
  Ok 0

Today we have to write this program by extracting the function that requires a Result, and then forcing the value out with a Result.iter, Result.get_ok, etc.

let main () = 
  let* conn = Blink.connect "URL" in
  (* ... *)
  Ok ()

let () = Riot.run @@ fun () -> main () |> Result.get_ok

Implementation notes

Start by modifying the type signature of run in riot.mli and let the compiler show you where the function lives.

We do not want to change the behavior of the underlying spawn function, but rather wrap the parameter to run (which is called main) so that we unwrap the result and handle it appropriately there.

So in the riot.ml file you'll find a line like:

(* ... *)

let _pid = _spawn ~pool ~scheduler:sch0 main in
Scheduler.run pool sch0 ();

(* ... *)

And this variable main is the function passed as input. We want this one to be wrapped in a function that calls main and handles the result.

To shutdown the Riot runtime you can call the shutdown function defined in the same file.