execution_policy library

execution_policy.dart

A resilient execution-policy framework for Dart applications.

This library provides: • Core abstractions and interfaces for defining resilience policies • Built-in policy implementations (retry, timeout, fallback, circuit-breaker) • A fluent PolicyBuilder for composing multiple policies in the correct order • A PolicyDebugger for instrumenting and tracing each policy’s execution

Getting Started

import 'package:execution_policy/execution_policy.dart';

final result = await PolicyBuilder<String>()
  // Retry up to 3 times with fixed 300ms delay
  .retry(RetryOptions.fixed,
    retryIf: (e) => e is HttpException,
    onError: (e, stack, attempt) async {
      print('Attempt $attempt failed: $e');
    })
  // Fail fast if action takes longer than 2s
  .timeout(Duration(seconds: 2))
  // If all else fails, return a default
  .fallback(() async => 'default')
  // Execute your asynchronous operation
  .execute(() async => fetchData());

For per-policy tracing of start/success/failure events:

await PolicyBuilder<String>()
  .retry(RetryOptions.exponentialJitter)
  .timeout(Duration(seconds: 1))
  .debugExecute(
    () async => unreliableOperation(),
    (msg) => print('[DEBUG] $msg'),
  );

Classes

CircuitBreakerPolicy<T>
A simple circuit breaker that opens after failureThreshold failures, stays open for resetTimeout, then allows one trial (half-open).
FallbackPolicy<T>
A fallback policy that catches any exception thrown by upstream policies or the action itself, and instead returns a fallback value.
Policy<T>
Core interface for resilience policies.
PolicyBuilder<T>
Builds and composes multiple Policy instances into a single execution pipeline.
PolicyDebugger<T>
A generic debugger that can wrap any Policy<\T> and emit start/done/failure logs with timings.
RetryOptions
Configure the behaviour or the retry mechanism
RetryPolicy<T>
Retries your action according to options, calls retryIf and onError if provided.
TimeoutPolicy<T>

Enums

CircuitState
The three states of the circuit.
RetryDelayType
How delay grows (optionally with jitter).

Typedefs

FutureFunction<T> = Future<T> Function()
A function that produces a Future<T>. This represents the asynchronous operation that policies will wrap.