Download the PHP package kissmint3395/aegis without Composer
On this page you can find all versions of the php package kissmint3395/aegis. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download kissmint3395/aegis
More information about kissmint3395/aegis
Files in kissmint3395/aegis
Package aegis
Short Description A PHP 8.2+ resilience library combining Retry, Circuit Breaker, Timeout, and more into a composable pipeline. Inspired by Resilience4j and .NET Polly.
License MIT
Informations about the package aegis
Aegis
日本語ドキュメント
A PHP 8.2+ resilience library that combines Retry, Circuit Breaker, Timeout, Rate Limiter, Bulkhead, Fallback, Cache, and Hedge into a single composable pipeline.
Inspired by Resilience4j and .NET Polly — the PHP ecosystem's missing equivalent.
Why Aegis?
PHP has several individual resilience libraries, but none that combine them into a composable pipeline:
| Library | Retry | CB | Timeout | Rate Limiter | Bulkhead | Fallback | Cache | Composable | PHP 8.2+ |
|---|---|---|---|---|---|---|---|---|---|
ackintosh/ganesha |
✗ | ✅ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | ✅ |
yohang/finite |
✗ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | ✅ |
cline/retry |
✅ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | ✅ |
| Aegis | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
Requirements
- PHP 8.2+
psr/event-dispatcher^1.0psr/simple-cache^3.0 (optional, for persistent Circuit Breaker, Rate Limiter, and Bulkhead state)
Installation
Usage
Retry
Retry a failing operation with configurable backoff.
Backoff strategies:
Conditional retry:
Circuit Breaker
Stop cascading failures by blocking calls when a service is unhealthy.
State transitions:
Persistent state across requests (Redis, APCu, etc.):
Ignore specific exceptions (e.g. validation errors should not trip the circuit):
Adaptive Circuit Breaker
A sliding-window variant that opens based on the failure rate (%) over the last N calls, rather than a consecutive-failure count. Equivalent to Resilience4j's sliding-window circuit breaker.
Persistent state:
Timeout
Enforce a maximum execution duration.
Note: On Unix systems with the
pcntlextension, Aegis usesSIGALRMfor true preemptive interruption. On Windows and environments withoutpcntl, elapsed time is checked after execution — useful for limiting total retry budgets.
Rate Limiter (Fixed Window)
Limit the number of calls within a fixed time window.
Persistent rate limiting across requests (Redis, APCu, etc.):
Note: The default
InMemoryStorageis process-scoped. For rate limiting across PHP-FPM workers, usePsr16Storagebacked by Redis or APCu.
Rate Limiter (Sliding Window)
Eliminates the "boundary burst" problem of fixed-window rate limiting by tracking individual request timestamps.
Persistent state:
Note: Each entry stores a full timestamp array. For very high-volume endpoints, prefer a Redis ZSET-backed implementation.
Rate Limiter (Token Bucket)
Allows burst traffic up to a capacity while enforcing an average rate via continuous token refill. Tokens are added at refillRate per refillPeriod.
Persistent state:
Bulkhead
Limit the number of concurrent executions to prevent resource exhaustion.
Persistent concurrency tracking across requests (Redis, APCu, etc.):
Note: The default
InMemoryStorageis process-scoped. For cross-worker concurrency limiting, usePsr16Storagebacked by Redis or APCu.
Fallback
Return a default value (or call an alternative callable) when all inner strategies fail.
The fallback handler receives the original \Throwable. If the handler itself throws, a FallbackNotAvailableException is raised wrapping both the original and fallback exceptions.
Cache
Cache successful results and serve them on subsequent calls. Optionally serve stale entries when the downstream call fails.
With staleOnFailure: true, if the downstream call throws and a (possibly expired) cache entry exists, the stale value is returned instead of propagating the exception.
Hedge (experimental)
Fire additional "hedge" requests after a configurable delay and return the first successful result. Reduces tail latency for operations where some replicas respond faster than others.
Note: True latency-based hedging requires callables that cooperatively yield via
Fiber::suspend()(e.g. ReactPHP / Swoole). For synchronous callables, hedges fire immediately after each failure.
Composing strategies
Strategies wrap each other in the order they are added (first = outermost). The recommended order is: Bulkhead → Rate Limiter → Timeout → Circuit Breaker → Retry → Fallback.
PSR-14 Events
Observe what happens inside the pipeline by wiring up a PSR-14 event dispatcher.
| Event | Fired when |
|---|---|
RetryAttempted |
A retry is about to be delayed and re-attempted |
CircuitOpened |
Circuit transitions Closed → Open |
CircuitClosed |
Circuit transitions HalfOpen → Closed |
CircuitHalfOpened |
Circuit transitions Open → HalfOpen |
RateLimitExceeded |
A call is rejected because the rate limit is reached |
BulkheadRejected |
A call is rejected because the bulkhead is full |
TokenBucketExhausted |
A call is rejected because the token bucket is empty |
Custom strategies
Implement StrategyInterface to plug in your own logic.
Exceptions
| Exception | Thrown when |
|---|---|
RetryExhaustedException |
All retry attempts failed. getPrevious() returns the last cause. |
CircuitOpenException |
A call is made while the circuit is Open. |
TimeoutExceededException |
Execution exceeded the configured duration. |
RateLimitExceededException |
The rate limit for the window has been reached. |
BulkheadFullException |
The maximum number of concurrent calls is already reached. |
TokenBucketExhaustedException |
The token bucket has no tokens available. |
FallbackNotAvailableException |
Both the primary call and the fallback handler failed. |
HedgeExhaustedException |
All hedge attempts failed. getExceptions() returns every cause. |
PHPStan integration
Aegis ships with a PHPStan rule that catches misuse at analysis time.
Rule: retryOn must contain Throwable subclasses
Install the extension via phpstan/extension-installer (automatic) or add manually:
Development
Roadmap
- [x] Rate Limiter (Fixed Window, Sliding Window, Token Bucket)
- [x] Bulkhead (concurrency limiting)
- [x] Fallback strategy
- [x] Adaptive Circuit Breaker (sliding-window failure rate)
- [x] Cache strategy
- [x] Hedge strategy (experimental)
- [ ] PHPStan 2.x upgrade
License
MIT
日本語ドキュメント
↑ English
PHP 8.2+ 向けのレジリエンスライブラリです。リトライ・サーキットブレーカー・タイムアウト・レートリミッター・バルクヘッド・フォールバック・キャッシュ・ヘッジを単一のコンポーザブルなパイプラインとして組み合わせられます。
Resilience4j(Java)や.NET Polly に相当するものが PHP エコシステムに存在しなかったため作成しました。
なぜ Aegis?
PHP には個別のレジリエンスライブラリが存在しますが、それらをパイプラインとして合成できるものはありませんでした。
| ライブラリ | リトライ | CB | タイムアウト | レートリミッター | バルクヘッド | フォールバック | キャッシュ | 合成可能 | PHP 8.2+ |
|---|---|---|---|---|---|---|---|---|---|
ackintosh/ganesha |
✗ | ✅ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | ✅ |
yohang/finite |
✗ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | ✅ |
cline/retry |
✅ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | ✅ |
| Aegis | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
要件
- PHP 8.2+
psr/event-dispatcher^1.0psr/simple-cache^3.0 (任意。サーキットブレーカー・レートリミッター・バルクヘッドの状態を永続化する場合)
インストール
使い方
リトライ
失敗した処理をバックオフ戦略付きで再試行します。
バックオフ戦略一覧:
条件付きリトライ:
サーキットブレーカー
サービスが不健全なときに呼び出しをブロックし、カスケード障害を防ぎます。
状態遷移:
リクエスト間で状態を永続化(Redis・APCu など):
アダプティブ サーキットブレーカー
直近 N 件の失敗率(%)に基づいてサーキットを開く、スライディングウィンドウ型のサーキットブレーカーです。
タイムアウト
処理の最大実行時間を設定します。
注意:
pcntl拡張が利用可能な Unix 環境ではSIGALRMによるプリエンプティブな割り込みを行います。Windows やpcntlが使えない環境では、実行後に経過時間をチェックする方式にフォールバックします。
レートリミッター(固定ウィンドウ)
固定ウィンドウ内の呼び出し回数を制限します。
レートリミッター(スライディングウィンドウ)
固定ウィンドウの「境界バースト問題」を解消します。個々のリクエストタイムスタンプを記録して正確にカウントします。
レートリミッター(トークンバケット)
最大 capacity バーストを許容しつつ、refillRate / refillPeriod の平均レートを連続補充で維持します。
バルクヘッド
同時実行数を制限してリソース枯渇を防ぎます。
フォールバック
全戦略が失敗したとき、代替値を返すか代替処理を実行します。
フォールバックハンドラー自体が例外をスローした場合は FallbackNotAvailableException が発生します。
キャッシュ
成功したレスポンスをキャッシュし、次回以降は呼び出しをスキップします。staleOnFailure: true を指定すると、ダウンストリームが失敗した際に期限切れのキャッシュを返します。
ヘッジ(実験的)
一定時間内に応答がない場合、追加のリクエストを並行して投げ、最初に成功したものを採用します(テールレイテンシー対策)。
注意: 真のレイテンシーベースのヘッジには、
Fiber::suspend()を使用した協調型非同期(ReactPHP / Swoole など)が必要です。同期的な callable の場合、ヘッジは各失敗後に即座に発火します。
戦略の合成
戦略は追加した順に外側から適用されます(最初に追加 = 最も外側)。 推奨順序は Bulkhead → Rate Limiter → Timeout → Circuit Breaker → Retry → Fallback です。
PSR-14 イベント
PSR-14 のイベントディスパッチャーを接続して、パイプライン内部の動作を観測できます。
| イベント | 発火タイミング |
|---|---|
RetryAttempted |
リトライ待機前 |
CircuitOpened |
Closed → Open に遷移したとき |
CircuitClosed |
HalfOpen → Closed に遷移したとき |
CircuitHalfOpened |
Open → HalfOpen に遷移したとき |
RateLimitExceeded |
レート制限に達して呼び出しを拒否したとき |
BulkheadRejected |
バルクヘッドが満杯で呼び出しを拒否したとき |
TokenBucketExhausted |
トークンバケットが空で呼び出しを拒否したとき |
カスタム戦略
StrategyInterface を実装して独自の戦略を追加できます。
例外一覧
| 例外 | 発生タイミング |
|---|---|
RetryExhaustedException |
全リトライが失敗。getPrevious() で最後の原因を取得可能 |
CircuitOpenException |
サーキットがオープン状態のときに呼び出しを行った |
TimeoutExceededException |
設定した時間内に処理が完了しなかった |
RateLimitExceededException |
ウィンドウ内のレート制限に達した |
BulkheadFullException |
最大同時実行数に達している |
TokenBucketExhaustedException |
トークンバケットにトークンがない |
FallbackNotAvailableException |
本処理とフォールバックの両方が失敗した |
HedgeExhaustedException |
全ヘッジ試行が失敗。getExceptions() で全原因を取得可能 |
PHPStan 連携
Aegis には静的解析時に誤用を検出する PHPStan ルールが同梱されています。
phpstan/extension-installer 経由で自動的に有効化されます。手動で追加する場合:
開発
ロードマップ
- [x] レートリミッター(固定ウィンドウ・スライディングウィンドウ・トークンバケット)
- [x] バルクヘッド(同時実行数制限)
- [x] フォールバック戦略
- [x] アダプティブ サーキットブレーカー(失敗率ベース)
- [x] キャッシュ戦略
- [x] ヘッジ戦略(実験的)
- [ ] PHPStan 2.x 対応