Choosing and stacking decorators

library(fnware)

Which decorator do I want?

The problem Decorator Guide
A call fails now and then retry() vignette("retry")
A call hangs timeout() vignette("retry")
A service is down and callers keep waiting on it circuit_breaker() vignette("circuitbreaker")
An API allows only so many calls rate_limit() ?rate_limit
A failure should become a default value fallback() vignette("fallback")
A result is slow to compute and gets asked for again lru_cache(), cache, disk_cache() vignette("caching")
Setup should happen a single time once vignette("fallback")
You want to see what is being called log_call() vignette("logging")
Bad input or output should be caught early validate_args(), validate_return() vignette("validation")
Setup and teardown around a resource contextmanager vignette("contextmanager")

For a function that returns a promise, every decorator above except contextmanager has an async_ version. See vignette("async").

Stacking order

Decorators stack, and in a %@% b %@% f, a is outermost. The order changes what each one sees. This is the order that works for the common cases, from outside to inside:

validate_args()      reject bad input before doing any work
fallback()           use a default only once everything below has given up
circuit_breaker()    fail fast when the service is clearly down
cache / lru_cache()  skip the work for a repeated call
retry()              try again when a call fails
rate_limit()         throttle every attempt, retries included
timeout()            cap each attempt
log_call()           log the call itself

You will rarely need all of them. Skip the ones you do not need and keep the rest in this order.

n <- 0
fetch := validate_args(url = is.character) %@%
  fallback(value = NA_character_) %@%
  retry(stop = stop_after_attempt(3)) %@%
  function(url) {
    n <<- n + 1
    if (n < 3) stop("not yet")
    paste("response from", url)
  }
fetch("example.com")
#> [1] "response from example.com"

The reasons behind the order:

Put the caches where you want them to sit. Outside retry(), a successful result is cached once. Because only a returned value is stored, an error is never cached.