retry
lib/retry.vklib/retry.vk
Pure-Veko resilience & concurrency utilities: exponential backoff retry with jitter,
token-bucket rate limiter, and shared-nothing spawn parallel fan-out (fan-out).
RetryOpts = struct { max_attempts i64 = ..., base_delay dur = ..., max_delay dur = ..., jitter_pct i64 = ... }
Retry policy configuration with sensible defaults.
RateLimiter = struct { capacity i64, tokens i64, refill_per_sec i64, last_ns i64 }
Token-bucket rate limiter (monotonic clock backed via time/now).
backoff-delay = fn [opts RetryOpts, attempt i64] dur
Computes the deterministic exponential backoff delay (in dur) for 0-based attempt.
Executable Example
use [retry]
opts = retry/RetryOpts { base_delay = 50ms, max_delay = 300ms, jitter_pct = 0 }
if (retry/backoff-delay opts 0) != 50ms or (retry/backoff-delay opts 2) != 200ms or (retry/backoff-delay opts 4) != 300ms [
err 'backoff'
] else [ .ok ]
run = fn [opts RetryOpts, action fn[i64->any]] any
Executes action (fn [attempt i64] any) up to opts.max_attempts times until it returns a non-err result.
Executable Example
use [retry]
opts = retry/RetryOpts { max_attempts = 3, base_delay = 1ms, max_delay = 5ms, jitter_pct = 0 }
r = retry/run opts fn [attempt] [ if attempt < 2 [ err 'transient' ] else [ 'ok' ] ]
if r != 'ok' [ err 'retry run' ] else [ .ok ]
limiter-new = fn [capacity i64, refill_per_sec i64] RateLimiter
Creates a new full token-bucket RateLimiter with capacity burst tokens refilling at refill_per_sec.
allow-at? = fn [mut rl RateLimiter, cost i64, now_ns i64] bool
Attempts to consume cost tokens at timestamp now_ns, returning true if allowed.
Executable Example
use [retry]
mut rl = retry/RateLimiter { capacity = 2, tokens = 2, refill_per_sec = 10, last_ns = 0 }
a = retry/allow-at? mut rl 1 0
b = retry/allow-at? mut rl 1 0
c = retry/allow-at? mut rl 1 0
d = retry/allow-at? mut rl 1 200000000 // +0.2s refills 2 tokens
if (not a) or (not b) or c or (not d) [ err 'rate limiter' ] else [ .ok ]
allow? = fn [mut rl RateLimiter, cost i64] bool
Attempts to consume cost tokens using the current monotonic clock (time/now).