Skip to content

Commit

Permalink
feat(riot): add run_with_status function where main can return a stat…
Browse files Browse the repository at this point in the history
…us code/error (#61)

* feat(riot): add run_with_status function where main can return a status code/error

* refactor: run_with_status now depends on run and not the other way around

* change: run_with_status now returns `Msg error

* Change `run_with_status` to use an error handler

Make `run_with_status` use an error handler in optional argument
`on_error` or use a default that handles `` `Msg of string ``.
Also, `shutdown` is called when an error occurs now.

* Use Log.error instead of eprintf

* Use match on status instead of Result.fold

* Use generic error type instead of > `Msg

* Restrict default_on_error error type

* Fix syntax error in default_on_error

* fix: remove default on error
  • Loading branch information
Dev380 authored Mar 21, 2024
1 parent 1e40f70 commit 9b4ad81
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
16 changes: 16 additions & 0 deletions riot/riot.ml
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,22 @@ let run ?(rnd = Random.State.make_self_init ()) ?workers main =
Log.debug (fun f -> f "Riot runtime shutdown");
Stdlib.exit pool.status

let on_error (error : [ `Msg of string ]) =
let backtrace = Printexc.get_backtrace () in
let error_string =
match error with `Msg reason -> Printf.sprintf "%s\n%s" reason backtrace
in
Log.error (fun f -> f "Riot raised an error: %s\n" error_string);
1

let run_with_status ?(rnd = Random.State.make_self_init ()) ?workers ~on_error
main =
run ~rnd ?workers (fun _ ->
let status =
match main () with Ok code -> code | Error reason -> on_error reason
in
shutdown ~status ())

let start ?rnd ?workers ~apps () =
run ?rnd ?workers @@ fun () ->
let child_specs =
Expand Down
15 changes: 15 additions & 0 deletions riot/riot.mli
Original file line number Diff line number Diff line change
Expand Up @@ -304,6 +304,21 @@ val shutdown : ?status:int -> unit -> unit
val run : ?rnd:Random.State.t -> ?workers:int -> (unit -> unit) -> unit
(** Start the Riot runtime using function [main] to boot the system *)

val on_error : [ `Msg of string ] -> int

val run_with_status :
?rnd:Random.State.t ->
?workers:int ->
on_error:('error -> int) ->
(unit -> (int, 'error) result) ->
unit
(** [run_with_status ~on_error main] starts the Riot runtime using function
[main] to boot the system and handling errors with [on_error].
[main] should return a result of either an exit code or an error.
[on_error] should handle an error code appropriately, then return a status code.
*)

val start :
?rnd:Random.State.t ->
?workers:int ->
Expand Down

0 comments on commit 9b4ad81

Please sign in to comment.