@std/concurrency/resilience.ms#
Import each required symbol with import Name from "@std/concurrency/resilience.ms".
CircuitBreaker Type#
Stops calling something that keeps failing. After threshold failures in a row the circuit opens, and calls fail at once with Open.
After cooldown, one call is let through: success closes the circuit, and failure opens it again.
import CircuitBreaker from "@std/concurrency/resilience.ms"
import fetch from "@std/net/fetch.ms"
import seconds from "@std/time.ms"
var breaker = CircuitBreaker(threshold: 5, cooldown: seconds(10))
reply := breaker.call(() => fetch(request).wait())
if reply.is_error() { print("circuit open or call failed") }type CircuitBreaker {
threshold Int
cooldown Duration
failures Int = 0
opened Instant? = null
}CircuitBreaker.cooldown#
How long the circuit stays open before a trial call.
cooldown DurationCircuitBreaker.failures#
Internal state: the current run of failures.
failures Int = 0CircuitBreaker.opened#
Internal state: when the circuit opened, or null while closed.
opened Instant? = nullCircuitBreaker.threshold#
Consecutive failures that open the circuit; at least 1.
threshold IntCircuitBreaker.call#
Runs operation unless the circuit is open, and records the outcome. An open
circuit returns CircuitError.Open without calling it; a failed call returns
CircuitError.Failed with the error.
var fn call[T, E](operation fn() Result[T, E]) Result[T, CircuitError[E]]CircuitBreaker.is_open#
Reports whether the circuit is open and still cooling down, so a call fails at once. It is false while the circuit is closed, and once the cooldown has passed, which lets the trial call through.
fn is_open() BoolCircuitError Enum#
Why a circuit breaker call produced no result: the circuit was open, or the call failed.
enum CircuitError[E] {
Open
Failed(error E)
}CircuitError.Failed#
The call ran and failed with this error.
Failed(error E)CircuitError.Open#
The circuit is open: the call was not made.
OpenCircuitError.Failed.error#
The error the call returned.
error ERateLimiter Type#
A token bucket: holds up to burst tokens and gains one every interval. Each use of the limited resource takes a token.
import rate_limiter from "@std/concurrency/resilience.ms"
import fetch from "@std/net/fetch.ms"
var limiter = rate_limiter(10, burst: 20)?
for url in urls {
limiter.acquire()
void fetch(url).wait()?
}type RateLimiter {
burst Int
interval Duration
tokens Int
stamp Instant
}RateLimiter.burst#
Most tokens held at once; at least 1.
burst IntRateLimiter.interval#
Time to gain one token.
interval DurationRateLimiter.stamp#
Internal state: the reading up to which refills are counted.
stamp InstantRateLimiter.tokens#
Internal state: tokens available as of stamp.
tokens IntRateLimiter.acquire#
Waits until a token is available, then takes it. Cancelling the task ends the wait.
var fn acquire() VoidRateLimiter.refill#
Internal: adds the tokens earned since the last refill.
var fn refill() VoidRateLimiter.try_acquire#
Takes a token if one is available and reports whether it did. It never waits.
var fn try_acquire() BoolRetryPolicy Type#
How retry spaces and bounds its attempts. The wait before attempt n + 1 is delay doubled n - 1 times, never more than max_delay.
With jitter, the wait is a random share of that, so many callers do not retry in step.
import RetryPolicy, retry from "@std/concurrency/resilience.ms"
import fetch from "@std/net/fetch.ms"
import milliseconds from "@std/time.ms"
policy := RetryPolicy(attempts: 5, delay: milliseconds(50))
body := retry(policy, attempt => fetch(url).wait())
if body.is_error() { print("gave up") }type RetryPolicy {
attempts Int = 3
delay Duration = milliseconds(100)
max_delay Duration = seconds(30)
jitter Bool = true
}RetryPolicy.attempts#
Total tries, including the first; at least 1.
attempts Int = 3RetryPolicy.delay#
Wait before the second attempt.
delay Duration = milliseconds(100)RetryPolicy.jitter#
Whether each wait is a random share (0 to 1) of its computed length.
jitter Bool = trueRetryPolicy.max_delay#
Upper bound on any wait.
max_delay Duration = seconds(30)RetryPolicy.wait_after#
Internal: the wait after failed attempt number attempt (1 for the first), before
jitter.
fn wait_after(attempt Int) DurationThrottle Type#
A minimum spacing between actions: at most one per interval, the first one at once. Use it to throttle a stream of events.
import Throttle from "@std/concurrency/resilience.ms"
import milliseconds from "@std/time.ms"
var spacing = Throttle(interval: milliseconds(200))
for event in events {
if spacing.allow() { print(event) }
}type Throttle {
interval Duration
last Instant? = null
}Throttle.interval#
The least time between two allowed actions.
interval DurationThrottle.last#
Internal state: when the last action was allowed, or null before the first.
last Instant? = nullThrottle.allow#
Reports whether an action may happen now, and if so counts it. It never waits.
var fn allow() BoolThrottle.wait#
Waits until an action may happen, then counts it. Cancelling the task ends the wait.
var fn wait() Voidmap_concurrent Function#
Applies work to every item with at most limit running at once and returns the
results in the order of items. A failed worker promise cancels the others. If
work returns a Result, that Result is an item in the returned list; inspect each
outcome. A limit below 1 is EINVAL.
import map_concurrent from "@std/concurrency/resilience.ms"
doubled := map_concurrent([1, 2, 3], 2, n => n * 2)? // [2, 4, 6]
print(doubled.length())fn map_concurrent[T, U](items List[T], limit Int, move work fn(T) U, site String = caller_frame()) Result[List[U], Error] { ... }rate_limiter Function#
Returns a rate limiter that allows count uses per second, with room for burst
uses at once. It starts full. A count or burst below 1 returns EINVAL.
fn rate_limiter(count Int, burst Int) Result[RateLimiter, Error] { ... }retry Function#
Runs operation until it succeeds, retryable rejects its error, or policy.attempts is used up, and returns the last result.
operation receives the attempt number, starting at 1. retryable defaults to retrying every error.
Waiting uses sleep, so cancelling the task ends the wait. The operation always runs once, so a policy with fewer than one attempt still runs it once.
fn retry[T, E](policy RetryPolicy, operation fn(Int) Result[T, E], retryable (fn(E) Bool)? = null) Result[T, E] { ... }