resilience — retry, circuit breaker и bulkhead, собранные в правильном порядке
$ composer require rasuvaeff/resilience
$pipeline = Pipeline::for('billing') ->bulkhead(new SharedBulkhead( name: 'billing', maxConcurrent: 2, store: new InMemoryBulkheadStore(), lease: Duration::seconds(5), maxWait: Duration::zero(), )) ->retry( Retry::new() ->maxAttempts(maxAttempts: 3) ->withImmediate(), ) ->build();immutable, reusable
Пример из README, дополненный breaker'ом, выполняется при каждой сборке через doc-exec.
Retry, circuit breaker и bulkhead в правильном порядке, с готовой «склейкой».
Три базовых пакета компонуются через замыкания, но неверная склейка означает retry на открытом circuit или полном bulkhead, что усиливает перегрузку. Pipeline фиксирует порядок вложенности и добавляет правила остановки.
Pipeline::for(name) над retry, circuit breaker и bulkhead; build() неизменяем и переиспользуем.retry(circuitBreaker(bulkhead(callback))), поэтому сон между retry не удерживает слот.CircuitOpenException и StorageFailure breaker'а.BulkheadFullException, если не вызван retryOnBulkheadFull().breakerOutsideRetry() переключает учёт исходов breaker'а с попытки на операцию.Rejection::is() и retryAfter(); onRejected() отображает отказ в доменное исключение.context пробрасывается через каждый слой.Превращает отказ переполненного bulkhead в доменное исключение и читает подсказку Retry-After.
final class BillingUnavailable extends \RuntimeException {} $store = new InMemoryBulkheadStore();$store->tryAcquire('billing', 1, Duration::seconds(5)); // the only slot is busy $pipeline = Pipeline::for('billing') ->bulkhead(new SharedBulkhead( name: 'billing', maxConcurrent: 1, store: $store, lease: Duration::seconds(5), maxWait: Duration::zero(), )) ->onRejected(static fn(\Throwable $e): \Throwable => new BillingUnavailable('billing is busy', previous: $e)) ->build(); try { $pipeline->call(static fn(): string => 'charged');} catch (BillingUnavailable $e) { $e->getMessage(); // => "billing is busy" Rejection::is($e->getPrevious()); // => true Rejection::retryAfter($e->getPrevious())?->toMillis(); // => 5000}
При открытом контуре callback не вызывается, повторы прекращаются сразу, отвечает fallback.
$pipeline = Pipeline::for('payments') ->retry(Retry::new()->maxAttempts(maxAttempts: 5)->withImmediate()) ->circuitBreaker($breaker) ->build(); // $breaker is already open: a previous failing call tripped it// (see examples/02-fallback-on-open-circuit.php).// With the circuit open, it rejects instantly, the glue stops the retry// loop after zero callback invocations, and the fallback degrades gracefully.$calls = 0;$result = $pipeline->call( callback: function () use (&$calls): string { ++$calls; return 'never reached'; }, fallback: static fn(\Throwable $e): string => $e instanceof CircuitOpenException ? 'served from cache' : 'unexpected: ' . $e::class,); printf("with the circuit open: %s (callback invoked %d time(s))\n", $result, $calls);
Запускает конвейер под бюджетом запроса; брейкер не считает истечение контекста сбоем.
$charge = $pipeline->call( static fn(Context $context): Charge => $stripe->charge($payload, $context), context: $requestContext,); new BreakerConfig( // ... isFailure: ContextOutcome::ignoring(static fn(\Throwable $e): bool => $e instanceof ClientExceptionInterface),);
retry, circuit-breaker, bulkhead, duration и context для бюджета запроса.
Положение breaker'а — реальный семантический выбор. С breakerOutsideRetry() открытый circuit не может прервать цикл retry.
требует: bulkhead(3), circuit-breaker(3), context(3), duration(3), retry(3)
Первый релиз v0.1.0 — 2026-08-21, всего релизов: 4.
| v0.3.0 | 2026-10-15 |
| v0.2.1 | 2026-10-10 |
| v0.2.0 | 2026-10-10 |
| v0.1.0 | 2026-08-21 |
/ поиск · n N следующее, предыдущее · g G начало, конец · q к индексу