OCaml token bucket rate limiter over Unix time
OCaml
type bucket = {
rate : float;
burst : float;
mutable tokens : float;
mutable last : float;
}
let create ~rate ~burst =
if rate <= 0. || burst <= 0. then invalid_arg "bucket: rate and burst must be positive";
{ rate; burst; tokens = burst; last = Unix.gettimeofday () }
let refill bucket now =
let elapsed = Float.max 0. (now -. bucket.last) in
bucket.tokens <- Float.min bucket.burst (bucket.tokens +. (elapsed *. bucket.rate));
bucket.last <- now
let take ?(amount = 1.) bucket =
refill bucket (Unix.gettimeofday ());
if bucket.tokens >= amount then (bucket.tokens <- bucket.tokens -. amount; true) else false