Module Consensus_heuristic.Worker

This worker implements a memoisation mechanism for the consensus heuristic with an expiry date mechanism. The worker also handles a hook mechanism to be executed on values found by the consensus heuristic.

type 'a t

A worker for a consensus over 'a.

val create : expire_time:Ptime.Span.t -> job:(unit -> 'a state Lwt.t) -> restart_delay:Ptime.Span.t -> 'a t

create ~expire_time ~job ~restart_delay creates a worker.

  • expire is a span of time during which a found consensus is memoised. After this span of time has elapsed, the found consensus is invalidated and a new consensus will be sought the next time it is queried.
  • job is the task the worker runs to seek a consensus. It is the responsibility of the caller to assemble job using the functions create, update, and get_state above.
  • restart_delay is a span of time that elapses between a non-successful run of job (a run that returns No_consensus or Need_more_candidates), and the next run. The delay leaves some time to elapse so that the network data has time to evolve before attempting to find a consensus again.

Note: Remember that the base heuristic states are meant to be short-lived. They are meant to be used as one-shot. Consequently, when you assemble a function for job, it should create a heuristic state, update it, and query it. You should NOT share a single heuristic state for multiple runs of job.

val wait : 'a t -> 'a Lwt.t

wait worker is a promise that resolves the next time the worker finds a consensus; i.e., the next time the worker's job returns Consensus.

If the worker has found a consensus less than expire time ago, the promise is already resolved with the found consensus.

If the worker is not currently seeking a consensus (and it doesn't have a currently memoised consensus), job is called again to seek one.

val on_next_consensus : 'a t -> ('a -> unit) -> unit

on_next_consensus worker hook registers a hook to be executed on the next consensus found by the worker or the current one if there is a non-expired consensus (i.e., Lwt.state (wait worker) = Lwt.Return hash).

Hooks are executed in the same order they are registered.

val on_all_consensus : 'a t -> ('a -> unit) -> unit

on_all_consensus worker hook registers a hook to be executed on every future consensus found by the worker as well as the current one if there is a valid consensus (i.e., Lwt.state (wait worker) = Lwt.Return hash).

It is guaranteed that a hook is executed exactly once for each time a consensus is reached. More precisely, between two executions of the same hook, there is at least one execution of job.

Hooks are executed in the same order they are registered.

val cancel : 'a t -> unit

cancel worker cancels the current task of the worker. All hooks are removed. If there are any pending promises returned by wait, they are canceled.