-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Signed-off-by: Guillaume Hivert <[email protected]>
- Loading branch information
Showing
3 changed files
with
118 additions
and
24 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,54 @@ | ||
import backend/index/error.{type Error} | ||
import gleam/erlang/process.{type Subject} | ||
import gleam/function | ||
import gleam/io | ||
import gleam/otp/actor | ||
|
||
pub opaque type Message { | ||
Rerun | ||
} | ||
|
||
type State(a) { | ||
State(self: Subject(Message), work: fn() -> Result(a, Error), interval: Int) | ||
} | ||
|
||
fn enqueue_next_rerun(state: State(a)) { | ||
process.send_after(state.self, state.interval, Rerun) | ||
} | ||
|
||
/// Repeatedly call a function, leaving `interval` milliseconds between each call. | ||
/// When the `work` function returns an error it is printed. | ||
pub fn retry( | ||
do work: fn() -> Result(a, Error), | ||
) -> Result(Subject(Message), actor.StartError) { | ||
fn() { init(60_000, work) } | ||
|> actor.Spec(loop: loop, init_timeout: 100) | ||
|> actor.start_spec() | ||
} | ||
|
||
fn init( | ||
interval: Int, | ||
work: fn() -> Result(a, Error), | ||
) -> actor.InitResult(State(a), Message) { | ||
let subject = process.new_subject() | ||
let state = State(subject, work, interval) | ||
process.new_selector() | ||
|> process.selecting(subject, function.identity) | ||
|> actor.Ready(state, _) | ||
|> function.tap(fn(_) { enqueue_next_rerun(state) }) | ||
} | ||
|
||
fn loop(message: Message, state: State(a)) -> actor.Next(Message, State(a)) { | ||
case message { | ||
Rerun -> { | ||
case state.work() { | ||
Ok(_) -> actor.Stop(process.Normal) | ||
Error(e) -> { | ||
io.debug(e) | ||
enqueue_next_rerun(state) | ||
actor.continue(state) | ||
} | ||
} | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters