Skip to content

Commit

Permalink
Handle invalid negative args to n_times
Browse files Browse the repository at this point in the history
  • Loading branch information
shonfeder committed Oct 28, 2024
1 parent 843b861 commit cd9f7e8
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 1 deletion.
3 changes: 2 additions & 1 deletion src/retry/lwt_retry.ml
Original file line number Diff line number Diff line change
Expand Up @@ -58,9 +58,10 @@ let with_sleep ?(duration=default_sleep_duration) (attempts : _ attempt Lwt_stre
end

let n_times n attempts =
if n < 0 then invalid_arg "Lwt_retry.n_times: n must be non-negative";
(* The first attempt is a try, and re-tries start counting from n + 1 *)
let retries = n + 1 in
let+ attempts = Lwt_stream.nget retries attempts in
match List.rev attempts with
| last :: _ -> last
| _ -> failwith "Lwt_retry.n_times impossible"
| _ -> failwith "Lwt_retry.n_times: impossible"
10 changes: 10 additions & 0 deletions test/retry/main.ml
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,16 @@ let suite = suite "lwt_retry" [
let+ success = Retry.(operation |> on_error |> n_times 5) in
success = Ok ());

test_direct "n_times on negative raises Invalid_argument" (fun () ->
let invalid_negative_retries = -5 in
let operation () = Lwt.return_error (`Retry ()) in
let attempts = Retry.(operation |> on_error) in
try
let _ = Retry.(attempts |> n_times invalid_negative_retries) in
false (* We failed to raise the invalid argument exception *)
with
Invalid_argument _ -> true);

(* test that the sleeps actually throttle computations as desired *)
test "with_sleep really does sleep" (fun () ->
let duration _ = 0.1 in
Expand Down

0 comments on commit cd9f7e8

Please sign in to comment.