moonpool — resource pools, backoff and flow control for MoonBit. The bookkeeping of holding a limited number of things, of deciding when to try again, and of not going too fast — with the clock and the randomness passed in, so every sequence is reproducible and none of it touches I/O.
Dependencies
// A pool that hands out what it has and says when to make or wait for more.
let pool : @moonpool.Pool[Conn] = @moonpool.Pool::new(
limits=@moonpool.Limits::new(size=20),
)
match pool.take(now) {
Ready(conn) => use(conn)
Stale(conn) => close(conn) // too old to use; take again
Make => {
let conn = open()
pool.made(conn, now)
use(conn)
}
Wait => queue()
}
pool.give(conn, now) // or pool.drop(conn) when it broke
// A retry policy that says how long to wait, and when to stop.
let policy = @moonpool.Backoff::new(attempts=5)
if policy.more(tries) { sleep(policy.delay(tries, random=draw())) }
// A rate limit, a quota and a concurrency limit.
@moonpool.Bucket::new(100.0, burst=200.0).take(now)
@moonpool.Window::new(1000, @moondate.Span::new(days=1L)).take(now)
@moonpool.Gate::new(64).enter()| What it answers | |
|---|---|
| Pool[T] | Which resource to hand out, whether to make another, which have sat or lived long enough to let go |
| Backoff | How long before the next try, and whether there should be one |
| Bucket | Whether this request is within a rate, and how long until it would be |
| Window | Whether it is within a quota — a thousand a day is a window, not a rate |
| Gate | Whether there is room right now, which has nothing to do with time |
moon add moonbitstack/moonpoolpub struct Bucket {
rate : Double
burst : Double
tokens : Double
at : Int64
}pub struct Gate {
limit : Int
held : Int
}| Rigid | the computed delay, unchanged. Reproducible, and it synchronises clients |
| Full | uniform over [0, cap]. The one that spreads clients furthest, and what gRPC sleeps |
| Equal | half the cap plus uniform over [0, cap/2]. Keeps a floor under the wait |
| Decorrelated | uniform over [base, previous × 3]. Grows from where it last landed rather than from the attempt number |
pub(all) enum Taken[T] {
Ready(T)
Stale(T)
Make
Wait
}Install
Download zipmoonpool — resource pools, backoff and flow control for MoonBit. The bookkeeping of holding a limited number of things, of deciding when to try again, and of not going too fast — with the clock and the randomness passed in, so every sequence is reproducible and none of it touches I/O.
Dependencies