{"id":23289787,"url":"https://github.com/cmatosbc/alecto","last_synced_at":"2026-02-12T04:34:17.543Z","repository":{"id":266584544,"uuid":"898769228","full_name":"cmatosbc/alecto","owner":"cmatosbc","description":"A robust PHP implementation of the Circuit Breaker pattern with type safety, metrics tracking, and configurable behavior.","archived":false,"fork":false,"pushed_at":"2024-12-05T22:04:29.000Z","size":47,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-05-20T19:20:10.679Z","etag":null,"topics":["circuit-breaker","php","php-design-patterns","php-error-handler","php-exceptions","php-library","php8"],"latest_commit_sha":null,"homepage":"","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"gpl-3.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/cmatosbc.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-12-05T02:05:44.000Z","updated_at":"2024-12-05T22:06:22.000Z","dependencies_parsed_at":"2024-12-05T03:16:24.248Z","dependency_job_id":"8ba8ea30-9432-4625-b672-a8c1c017bae5","html_url":"https://github.com/cmatosbc/alecto","commit_stats":null,"previous_names":["cmatosbc/alecto"],"tags_count":2,"template":false,"template_full_name":null,"purl":"pkg:github/cmatosbc/alecto","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cmatosbc%2Falecto","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cmatosbc%2Falecto/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cmatosbc%2Falecto/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cmatosbc%2Falecto/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/cmatosbc","download_url":"https://codeload.github.com/cmatosbc/alecto/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cmatosbc%2Falecto/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":271606595,"owners_count":24788979,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-08-22T02:00:08.480Z","response_time":65,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["circuit-breaker","php","php-design-patterns","php-error-handler","php-exceptions","php-library","php8"],"created_at":"2024-12-20T04:18:08.515Z","updated_at":"2026-02-12T04:34:17.500Z","avatar_url":"https://github.com/cmatosbc.png","language":"PHP","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Alecto - PHP Circuit Breaker Library\n\n[![PHPUnit Tests](https://github.com/cmatosbc/alecto/actions/workflows/phpunit.yml/badge.svg)](https://github.com/cmatosbc/alecto/actions/workflows/phpunit.yml) [![PHP Composer](https://github.com/cmatosbc/alecto/actions/workflows/composer.yml/badge.svg)](https://github.com/cmatosbc/alecto/actions/workflows/composer.yml) [![PHP Lint](https://github.com/cmatosbc/alecto/actions/workflows/lint.yml/badge.svg)](https://github.com/cmatosbc/alecto/actions/workflows/lint.yml)\n\nA robust PHP implementation of the Circuit Breaker pattern with type safety, metrics tracking, and configurable behavior.\n\nIn the depths of Greek mythology, Alecto, one of the three Erinyes or Furies, emerges as a formidable figure. These divine beings were born from the blood of the castrated Uranus, embodying the relentless pursuit of vengeance. Alecto, in particular, is known for her unwavering determination and relentless pursuit of justice.\n\nHer story offers a powerful metaphor for a circuit breaker pattern in programming. Just as Alecto intervenes to stop a cycle of violence and retribution, a circuit breaker interrupts a process to prevent it from spiraling out of control. In the realm of software, this might mean stopping an infinite loop, halting a runaway process, or preventing a system from crashing.\n\nBy drawing inspiration from Alecto, we can design circuit breaker patterns that are:\n\n- Swift and decisive: Like the Erinyes, a circuit breaker must act quickly to prevent further damage.\n- Relentless: Once activated, a circuit breaker should remain in effect until the underlying issue is resolved.\n- Just: A circuit breaker should be used judiciously, only when necessary to protect the system.\n\n## 🌟 Features\n\n- Type-safe implementation using PHP 8.1+\n- Configurable failure and success thresholds\n- Operation timeout handling\n- Fallback mechanism support\n- Metrics tracking\n- State transition management\n- PSR-3 compatible logging support\n\n## 📦 Installation\n\nInstall via Composer:\n\n```bash\ncomposer require cmatosbc/alecto\n```\n\nRequirements:\n- PHP 8.1 or higher\n- `ext-pcntl` extension\n- `ext-posix` extension\n\n## 🚀 Quick Start\n\n```php\nuse Alecto\\CircuitBreaker;\nuse Alecto\\Config\\CircuitBreakerConfig;\nuse Alecto\\Service\\TimeoutExecutor;\n\n// Create configuration\n$config = new CircuitBreakerConfig(\n    failureThreshold: 3,    // Open circuit after 3 failures\n    successThreshold: 2,    // Close circuit after 2 successes\n    resetTimeout: 10,       // Wait 10 seconds before attempting recovery\n    operationTimeout: 5     // Timeout operations after 5 seconds\n);\n\n// Initialize circuit breaker\n$circuitBreaker = new CircuitBreaker(\n    config: $config,\n    timeoutExecutor: new TimeoutExecutor()\n);\n\n// Use the circuit breaker\ntry {\n    $result = $circuitBreaker-\u003ecall(\n        callback: function() {\n            return someRiskyOperation();\n        },\n        fallback: function() {\n            return \"Fallback response\";\n        }\n    );\n} catch (\\Exception $e) {\n    // Handle exception\n}\n```\n\n## 🔄 Circuit States\n\nThe circuit breaker operates in three states:\n\n### CLOSED (Normal Operation)\n- All requests are allowed through\n- Failures are counted\n- When failures reach `failureThreshold`, transitions to OPEN\n\n### OPEN (Failure Prevention)\n- All requests are immediately rejected\n- After `resetTimeout` seconds, transitions to HALF-OPEN\n- Supports fallback responses during rejection\n\n### HALF-OPEN (Recovery Attempt)\n- Limited requests are allowed through\n- Successes are counted\n- After `successThreshold` successes, transitions to CLOSED\n- Any failure returns to OPEN state\n\n## 📊 Metrics Tracking\n\nThe circuit breaker tracks key metrics:\n\n```php\n$metrics = $circuitBreaker-\u003egetMetrics();\n\n// Available metrics:\n$metrics['successes'];   // Successful operations count\n$metrics['failures'];    // Failed operations count\n$metrics['rejections']; // Rejected operations count (when circuit is open)\n```\n\n## 🎯 Real-World Examples\n\n### 1. API Client Protection\n\n```php\nclass ApiClient\n{\n    public function __construct(\n        private Alecto\\CircuitBreaker $circuitBreaker,\n        private HttpClient $httpClient\n    ) {}\n\n    public function fetchUserData(int $userId): array\n    {\n        return $this-\u003ecircuitBreaker-\u003ecall(\n            callback: function() use ($userId) {\n                $response = $this-\u003ehttpClient-\u003eget(\"/users/{$userId}\");\n                return $response-\u003etoArray();\n            },\n            fallback: function() use ($userId) {\n                return $this-\u003egetCachedUserData($userId);\n            }\n        );\n    }\n}\n```\n\n### 2. Database Query Protection\n\n```php\nclass DatabaseRepository\n{\n    public function __construct(\n        private Alecto\\CircuitBreaker $circuitBreaker,\n        private PDO $pdo\n    ) {}\n\n    public function executeQuery(string $query, array $params = []): array\n    {\n        return $this-\u003ecircuitBreaker-\u003ecall(\n            callback: function() use ($query, $params) {\n                $stmt = $this-\u003epdo-\u003eprepare($query);\n                $stmt-\u003eexecute($params);\n                return $stmt-\u003efetchAll(PDO::FETCH_ASSOC);\n            },\n            fallback: function() {\n                return $this-\u003egetFromCache() ?? [];\n            }\n        );\n    }\n}\n```\n\n### 3. Microservice Communication\n\n```php\nclass PaymentService\n{\n    public function __construct(\n        private Alecto\\CircuitBreaker $circuitBreaker,\n        private PaymentGateway $gateway\n    ) {}\n\n    public function processPayment(Order $order): PaymentResult\n    {\n        return $this-\u003ecircuitBreaker-\u003ecall(\n            callback: function() use ($order) {\n                return $this-\u003egateway-\u003eprocessPayment($order);\n            },\n            fallback: function() use ($order) {\n                $this-\u003equeueForRetry($order);\n                return new PaymentResult(status: 'QUEUED');\n            }\n        );\n    }\n}\n```\n\n## 🔌 Framework Integration\n\n### Symfony Integration\n\n```php\n// config/services.yaml\nservices:\n    Alecto\\Config\\CircuitBreakerConfig:\n        arguments:\n            $failureThreshold: '%env(int:CIRCUIT_FAILURE_THRESHOLD)%'\n            $successThreshold: '%env(int:CIRCUIT_SUCCESS_THRESHOLD)%'\n            $resetTimeout: '%env(int:CIRCUIT_RESET_TIMEOUT)%'\n            $operationTimeout: '%env(int:CIRCUIT_OPERATION_TIMEOUT)%'\n\n    Alecto\\Service\\TimeoutExecutor: ~\n\n    Alecto\\CircuitBreaker:\n        arguments:\n            $config: '@Alecto\\Config\\CircuitBreakerConfig'\n            $timeoutExecutor: '@Alecto\\Service\\TimeoutExecutor'\n            $logger: '@logger'\n\n    App\\Service\\ExternalApiClient:\n        arguments:\n            $circuitBreaker: '@Alecto\\CircuitBreaker'\n```\n\n```php\n// src/Service/ExternalApiClient.php\nnamespace App\\Service;\n\nuse Alecto\\CircuitBreaker;\nuse Symfony\\Contracts\\HttpClient\\HttpClientInterface;\n\nclass ExternalApiClient\n{\n    public function __construct(\n        private readonly Alecto\\CircuitBreaker $circuitBreaker,\n        private readonly HttpClientInterface $client\n    ) {}\n\n    public function fetchData(): array\n    {\n        return $this-\u003ecircuitBreaker-\u003ecall(\n            callback: function() {\n                $response = $this-\u003eclient-\u003erequest('GET', 'https://api.example.com/data');\n                return $response-\u003etoArray();\n            },\n            fallback: function() {\n                return $this-\u003egetCachedData();\n            }\n        );\n    }\n}\n```\n\n### Laravel Integration\n\n```php\n// app/Providers/CircuitBreakerServiceProvider.php\nnamespace App\\Providers;\n\nuse Alecto\\CircuitBreaker;\nuse Alecto\\Config\\CircuitBreakerConfig;\nuse Alecto\\Service\\TimeoutExecutor;\nuse Illuminate\\Support\\ServiceProvider;\n\nclass CircuitBreakerServiceProvider extends ServiceProvider\n{\n    public function register(): void\n    {\n        $this-\u003eapp-\u003esingleton(CircuitBreakerConfig::class, function ($app) {\n            return new CircuitBreakerConfig(\n                failureThreshold: config('services.circuit.failure_threshold', 3),\n                successThreshold: config('services.circuit.success_threshold', 2),\n                resetTimeout: config('services.circuit.reset_timeout', 30),\n                operationTimeout: config('services.circuit.operation_timeout', 5)\n            );\n        });\n\n        $this-\u003eapp-\u003esingleton(TimeoutExecutor::class);\n\n        $this-\u003eapp-\u003esingleton(CircuitBreaker::class, function ($app) {\n            return new CircuitBreaker(\n                config: $app-\u003emake(CircuitBreakerConfig::class),\n                timeoutExecutor: $app-\u003emake(TimeoutExecutor::class),\n                logger: $app-\u003emake('log')\n            );\n        });\n    }\n}\n```\n\n```php\n// config/services.php\nreturn [\n    'circuit' =\u003e [\n        'failure_threshold' =\u003e env('CIRCUIT_FAILURE_THRESHOLD', 3),\n        'success_threshold' =\u003e env('CIRCUIT_SUCCESS_THRESHOLD', 2),\n        'reset_timeout' =\u003e env('CIRCUIT_RESET_TIMEOUT', 30),\n        'operation_timeout' =\u003e env('CIRCUIT_OPERATION_TIMEOUT', 5),\n    ],\n];\n```\n\n```php\n// app/Services/PaymentGateway.php\nnamespace App\\Services;\n\nuse Alecto\\CircuitBreaker;\n\nclass PaymentGateway\n{\n    public function __construct(\n        private readonly Alecto\\CircuitBreaker $circuitBreaker\n    ) {}\n\n    public function processPayment(array $paymentData): array\n    {\n        return $this-\u003ecircuitBreaker-\u003ecall(\n            callback: function() use ($paymentData) {\n                return $this-\u003egateway-\u003echarge($paymentData);\n            },\n            fallback: function() use ($paymentData) {\n                $this-\u003equeuePaymentForRetry($paymentData);\n                return ['status' =\u003e 'queued'];\n            }\n        );\n    }\n}\n```\n\n## ⚙️ Advanced Configuration\n\n### Custom Timeout Handling\n\n```php\n$config = new CircuitBreakerConfig(\n    failureThreshold: 5,\n    successThreshold: 3,\n    resetTimeout: 30,\n    operationTimeout: 2  // Short timeout for time-sensitive operations\n);\n```\n\n### Adding Logging\n\n```php\nuse Psr\\Log\\LoggerInterface;\n\n$circuitBreaker = new CircuitBreaker(\n    config: $config,\n    timeoutExecutor: new TimeoutExecutor(),\n    logger: $psrLogger\n);\n```\n\n## 🧪 Testing\n\nRun the test suite:\n\n```bash\ncomposer test\n```\n\nThe tests demonstrate:\n- State transition behavior\n- Failure counting\n- Success threshold management\n- Timeout handling\n- Metrics accuracy\n\n## 🤝 Contributing\n\n1. Fork the repository\n2. Create a feature branch\n3. Write tests for new features\n4. Submit a pull request\n\n## 📄 License\n\nThis library is licensed under the GNU General Public License v3.0 - see the LICENSE file for details.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcmatosbc%2Falecto","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fcmatosbc%2Falecto","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcmatosbc%2Falecto/lists"}