### Install Fuse for Laravel Source: https://github.com/harris21/laravel-fuse/blob/main/README.md Install the package using Composer and publish the configuration file. ```bash composer require harris21/laravel-fuse ``` ```bash php artisan vendor:publish --tag=fuse-config ``` -------------------------------- ### Listen to Circuit Breaker Events Source: https://github.com/harris21/laravel-fuse/blob/main/README.md Implement event listeners to react to circuit breaker state transitions. This example logs a critical message when a circuit breaker opens. ```php use Harris21\Fuse\Events\CircuitBreakerOpened; use Illuminate\Support\Facades\Log; class AlertOnCircuitOpen { public function handle(CircuitBreakerOpened $event): void { Log::critical("Circuit breaker opened for {$event->service}", [ 'failure_rate' => $event->failureRate, 'attempts' => $event->attempts, 'failures' => $event->failures, ]); // Send Slack notification, page on-call, etc. } } ``` -------------------------------- ### Registering Fuse Event Listeners Source: https://context7.com/harris21/laravel-fuse/llms.txt Shows how to register listeners for Fuse's state transition events in `EventServiceProvider`. Provides examples for handling `CircuitBreakerOpened`, `CircuitBreakerHalfOpen`, and `CircuitBreakerClosed` events. ```php // app/Providers/EventServiceProvider.php use Harris21\Fuse\Events\CircuitBreakerClosed; use Harris21\Fuse\Events\CircuitBreakerHalfOpen; use Harris21\Fuse\Events\CircuitBreakerOpened; protected $listen = [ CircuitBreakerOpened::class => [\App\Listeners\AlertCircuitOpened::class], CircuitBreakerHalfOpen::class => [\App\Listeners\LogCircuitHalfOpen::class], CircuitBreakerClosed::class => [\App\Listeners\NotifyCircuitRecovered::class], ]; // app/Listeners/AlertCircuitOpened.php class AlertCircuitOpened { public function handle(CircuitBreakerOpened $event): void { // $event->service — 'stripe' // $event->failureRate — 75.0 (percentage) // $event->attempts — 20 // $event->failures — 15 \Log::critical("Circuit OPENED: {$event->service}", [ 'failure_rate' => $event->failureRate, 'attempts' => $event->attempts, 'failures' => $event->failures, ]); // Page on-call, post to Slack, create PagerDuty incident, etc. } } // app/Listeners/NotifyCircuitRecovered.php class NotifyCircuitRecovered { public function handle(CircuitBreakerClosed $event): void { // $event->service — 'stripe' \Log::info("Circuit CLOSED (recovered): {$event->service}"); } } // app/Listeners/LogCircuitHalfOpen.php class LogCircuitHalfOpen { public function handle(CircuitBreakerHalfOpen $event): void { // $event->service — 'stripe' \Log::warning("Circuit HALF-OPEN (probing recovery): {$event->service}"); } } ``` -------------------------------- ### Status Page JSON API Response Example Source: https://context7.com/harris21/laravel-fuse/llms.txt This is an example of the JSON response from the status page's data endpoint, showing the current state, attempts, failures, and history for services. ```json { "services": { "stripe": { "state": "open", "attempts": 20, "failures": 15, "failure_rate": 75.0, "opened_at": 1718000000, "recovery_at": 1718000030, "timeout": 30, "threshold": 50, "min_requests": 5, "state_history": [ { "from": "closed", "to": "open", "time": "14:23:01" }, { "from": "open", "to": "half_open", "time": "14:23:31" }, { "from": "half_open", "to": "open", "time": "14:23:32" } ] } }, "circuit_breaker_enabled": true, "timestamp": "14:24:15" } ``` -------------------------------- ### Calculate Service Thresholds with Peak Hours Source: https://context7.com/harris21/laravel-fuse/llms.txt Use ThresholdCalculator::for() to get the effective failure threshold, which automatically switches between standard and peak-hours thresholds based on configured times. This allows for higher tolerance during business-critical hours. getConfig() provides full resolved configuration including peak hours status. ```php use Harris21\Fuse\ThresholdCalculator; // config/fuse.php services.stripe: // 'threshold' => 40, // off-peak: more sensitive // 'peak_hours_threshold' => 60, // peak hours: more tolerant // 'peak_hours_start' => 9, // 9 AM // 'peak_hours_end' => 17, // 5 PM // At 14:00 (2 PM — inside peak hours): ThresholdCalculator::for('stripe'); // returns 60 // At 02:00 (2 AM — outside peak hours): ThresholdCalculator::for('stripe'); // returns 40 // Get full resolved config including whether peak hours are active: ThresholdCalculator::getConfig('stripe'); // [ // 'threshold' => 60, // effective threshold right now // 'timeout' => 30, // 'min_requests' => 5, // 'is_peak_hours' => true, // ] ``` -------------------------------- ### Extend Default Failure Classifier Source: https://github.com/harris21/laravel-fuse/blob/main/README.md Extend the `DefaultFailureClassifier` to customize how specific exceptions are counted as failures. This example prevents counting Stripe's 500 errors for idempotency issues. ```php namespace App\Fuse; use GuzzleHttp\Exception\ServerException; use Harris21\Fuse\Classifiers\DefaultFailureClassifier; use Throwable; class StripeFailureClassifier extends DefaultFailureClassifier { public function shouldCount(Throwable $e): bool { // Stripe returns 500 for idempotency errors — not a real outage if ($e instanceof ServerException) { $body = (string) $e->getResponse()?->getBody(); if (str_contains($body, 'idempotency')) { return false; } } return parent::shouldCount($e); } } ``` -------------------------------- ### Custom Failure Classifier for Stripe Source: https://context7.com/harris21/laravel-fuse/llms.txt Example of extending `DefaultFailureClassifier` to handle specific API behaviors, like Stripe's use of HTTP 500 for idempotency key conflicts. Register the custom classifier in the service configuration. ```php // app/Fuse/StripeFailureClassifier.php namespace App\Fuse; use GuzzleHttp\Exception\ServerException; use Harris21\Fuse\Classifiers\DefaultFailureClassifier; use Throwable; class StripeFailureClassifier extends DefaultFailureClassifier { public function shouldCount(Throwable $e): bool { // Stripe uses HTTP 500 for idempotency key conflicts — not an outage if ($e instanceof ServerException) { $body = (string) $e->getResponse()?->getBody(); if (str_contains($body, 'idempotency')) { return false; // Don't count toward circuit threshold } } return parent::shouldCount($e); } } // config/fuse.php 'services' => [ 'stripe' => [ 'threshold' => 50, 'timeout' => 30, 'min_requests' => 5, 'release' => 15, 'failure_classifier' => \App\Fuse\StripeFailureClassifier::class, ], ] ``` -------------------------------- ### Direct Circuit Breaker Usage Source: https://github.com/harris21/laravel-fuse/blob/main/README.md Demonstrates how to directly use the `CircuitBreaker` class to wrap operations, record successes or failures, and handle open circuits with fallback logic. ```php use Harris21\Fuse\CircuitBreaker; $breaker = new CircuitBreaker('stripe'); if (!$breaker->isOpen()) { try { $result = Stripe::charges()->create([...]); $breaker->recordSuccess(); return $result; } catch (Exception $e) { $breaker->recordFailure($e); throw $e; } } else { // Circuit is open - use fallback return $this->fallbackResponse(); } ``` -------------------------------- ### Configure Peak Hours Thresholds Source: https://github.com/harris21/laravel-fuse/blob/main/README.md Set different sensitivity levels for peak and off-peak hours. Higher thresholds during peak hours allow for more successful transactions. ```php 'stripe' => [ 'threshold' => 40, // Off-peak: more sensitive (40%) 'peak_hours_threshold' => 60, // Peak hours: more tolerant (60%) 'peak_hours_start' => 9, // 9 AM 'peak_hours_end' => 17, // 5 PM ] ``` -------------------------------- ### Enable and Configure Status Page Source: https://context7.com/harris21/laravel-fuse/llms.txt Configure the status page by setting environment variables for enabling, prefix, and cache prefix. The status page provides a live dashboard accessible at a configurable URL. You can also override the default authorization gate in AppServiceProvider. ```dotenv FUSE_STATUS_PAGE_ENABLED=true FUSE_STATUS_PAGE_PREFIX=fuse // accessible at /fuse FUSE_CACHE_PREFIX=myapp_fuse // avoids key collisions in shared Redis ``` ```php // config/fuse.php 'status_page' => [ 'enabled' => env('FUSE_STATUS_PAGE_ENABLED', false), 'prefix' => env('FUSE_STATUS_PAGE_PREFIX', 'fuse'), 'middleware' => [], // replace default StatusPageMiddleware if needed 'polling_interval' => 2, // seconds between frontend polls ], ``` ```php // Override the authorization gate in AppServiceProvider: use Illuminate\Support\Facades\Gate; Gate::define('viewFuse', function ($user = null) { return $user?->hasRole('admin'); }); ``` -------------------------------- ### Enable Fuse Status Page Source: https://github.com/harris21/laravel-fuse/blob/main/README.md Enable the real-time monitoring dashboard by setting `FUSE_STATUS_PAGE_ENABLED` to `true` in your `.env` file. ```env FUSE_STATUS_PAGE_ENABLED=true ``` -------------------------------- ### Manual Override with `forceOpen()` and `forceClose()` Source: https://context7.com/harris21/laravel-fuse/llms.txt Explains how to manually override the circuit breaker's state using `forceOpen()` and `forceClose()` methods, useful for maintenance or immediate intervention. ```APIDOC ## `CircuitBreaker::forceOpen()` and `forceClose()` — Manual Override `forceOpen()` and `forceClose()` bypass failure-rate evaluation to immediately set circuit state. Useful for scheduled maintenance windows or when operator intervention is needed before failures accumulate. Both methods dispatch the corresponding Laravel event. ```php use Harris21\Fuse\CircuitBreaker; $breaker = new CircuitBreaker('stripe'); // Proactively open before a known maintenance window $breaker->forceOpen(); // Dispatches: CircuitBreakerOpened event // All jobs hitting this circuit are now released instantly // ... maintenance window ends ... // Re-open for normal traffic immediately without waiting for timeout $breaker->forceClose(); // Dispatches: CircuitBreakerClosed event // Jobs resume processing normally ``` **Equivalent Artisan commands:** ```bash # Manually open a circuit (dispatches CircuitBreakerOpened event) php artisan fuse:open stripe # Manually close a circuit (dispatches CircuitBreakerClosed event) php artisan fuse:close stripe # Reset to CLOSED and clear all window statistics php artisan fuse:reset stripe php artisan fuse:reset # reset all configured services # Inspect current state, failure rate, request counts, and threshold php artisan fuse:status stripe php artisan fuse:status # all configured services # Output: # +----------+---------+--------------+----------+----------+-----------+ # | Service | State | Failure Rate | Requests | Failures | Threshold | # +----------+---------+--------------+----------+----------+-----------+ # | stripe | CLOSED | 0.0% | 42 | 0 | 50% | # | mailgun | OPEN | 75.0% | 20 | 15 | 60% | # +----------+---------+--------------+----------+----------+-----------+ ``` ``` -------------------------------- ### Full Laravel Fuse Configuration Reference Source: https://context7.com/harris21/laravel-fuse/llms.txt This is a comprehensive reference for the `config/fuse.php` file, detailing global settings, default values, service-specific configurations including peak hours overrides and custom failure classifiers, cache settings, and status page options. ```php // config/fuse.php — published via: php artisan vendor:publish --tag=fuse-config return [ // Global on/off switch; can also be toggled at runtime via cache key 'fuse:enabled' 'enabled' => env('FUSE_ENABLED', true), // Defaults applied when a service has no specific config 'default_threshold' => 50, // % failure rate to open circuit 'default_timeout' => 60, // seconds in OPEN before moving to HALF-OPEN 'default_min_requests' => 10, // minimum requests before evaluating threshold 'default_release' => 10, // seconds to delay a released job 'services' => [ 'stripe' => [ 'threshold' => 50, 'timeout' => 30, 'min_requests' => 5, 'release' => 15, // Optional peak-hours overrides 'peak_hours_threshold' => 60, 'peak_hours_start' => 9, // hour 0-23 'peak_hours_end' => 17, // hour 0-23 // Optional custom failure classifier 'failure_classifier' => \App\Fuse\StripeFailureClassifier::class, ], 'mailgun' => [ 'threshold' => 60, 'timeout' => 120, 'min_requests' => 10, ], ], 'cache' => [ // Prefix for all cache keys; change when multiple apps share Redis 'prefix' => env('FUSE_CACHE_PREFIX', 'fuse'), ], 'status_page' => [ 'enabled' => env('FUSE_STATUS_PAGE_ENABLED', false), 'prefix' => env('FUSE_STATUS_PAGE_PREFIX', 'fuse'), 'middleware' => [], 'polling_interval' => 2, ], ]; ``` -------------------------------- ### Manually Open Circuit with Artisan Source: https://github.com/harris21/laravel-fuse/blob/main/README.md Force a circuit breaker into the OPEN state immediately using the `fuse:open` Artisan command. This is useful for proactively protecting against known service outages. ```bash php artisan fuse:open stripe ``` -------------------------------- ### Implement Failure Classifier Interface Source: https://github.com/harris21/laravel-fuse/blob/main/README.md Implement the `FailureClassifier` interface from scratch for complete control over failure classification logic. ```php namespace App\Fuse; use Harris21\Fuse\Contracts\FailureClassifier; use Throwable; class CustomFailureClassifier implements FailureClassifier { public function shouldCount(Throwable $e): bool { // Your classification logic } } ``` -------------------------------- ### Direct CircuitBreaker Usage in PHP Source: https://context7.com/harris21/laravel-fuse/llms.txt Instantiate CircuitBreaker with a service name and use isOpen(), recordSuccess(), and recordFailure() to manage circuit logic manually. Inspect state and statistics using getStats(). ```php use Harris21\Fuse\CircuitBreaker; use Stripe\Exception\ApiConnectionException; $breaker = new CircuitBreaker('stripe'); if ($breaker->isOpen()) { // Fast-fail without calling the service return response()->json(['error' => 'Payment service temporarily unavailable'], 503); } try { $charge = \Stripe\Charge::create([ 'amount' => 4999, 'currency' => 'usd', 'customer' => 'cus_abc123', ]); $breaker->recordSuccess(); // Counts as an attempt; closes circuit if HALF-OPEN return response()->json(['charge_id' => $charge->id]); } catch (ApiConnectionException $e) { $breaker->recordFailure($e); // Increments failure counter; may open circuit throw $e; } // Inspect state and statistics $stats = $breaker->getStats(); // [ // 'state' => 'closed', // 'closed' | 'open' | 'half_open' // 'attempts' => 42, // 'failures' => 3, // 'failure_rate'=> 7.1, // percentage // 'opened_at' => null, // Unix timestamp or null // 'recovery_at' => null, // opened_at + timeout, or null // 'timeout' => 30, // 'threshold' => 50, // 'min_requests'=> 5, // ] $breaker->isClosed(); // true — normal operations $breaker->isOpen(); // false — circuit is not tripped $breaker->isHalfOpen(); // false — not in recovery probe state $breaker->reset(); // Force back to CLOSED, clears all window counters ``` -------------------------------- ### Check Circuit Status with Artisan Source: https://github.com/harris21/laravel-fuse/blob/main/README.md Use the `fuse:status` Artisan command to view the current state, failure rate, and request counts for all or specific circuit breakers. ```bash php artisan fuse:status # all services php artisan fuse:status stripe # single service ``` -------------------------------- ### Artisan Commands for CircuitBreaker Management Source: https://context7.com/harris21/laravel-fuse/llms.txt Manage circuit states using Artisan commands like fuse:open, fuse:close, fuse:reset, and fuse:status. These commands provide an alternative to programmatic control. ```bash # Manually open a circuit (dispatches CircuitBreakerOpened event) php artisan fuse:open stripe # Manually close a circuit (dispatches CircuitBreakerClosed event) php artisan fuse:close stripe # Reset to CLOSED and clear all window statistics php artisan fuse:reset stripe php artisan fuse:reset # reset all configured services # Inspect current state, failure rate, request counts, and threshold php artisan fuse:status stripe php artisan fuse:status # all configured services # Output: # +----------+---------+--------------+----------+----------+-----------+ # | Service | State | Failure Rate | Requests | Failures | Threshold | # +----------+---------+--------------+----------+----------+-----------+ # | stripe | CLOSED | 0.0% | 42 | 0 | 50% | # | mailgun | OPEN | 75.0% | 20 | 15 | 60% | # +----------+---------+--------------+----------+----------+-----------+ ``` -------------------------------- ### Direct Programmatic Usage of CircuitBreaker Source: https://context7.com/harris21/laravel-fuse/llms.txt Demonstrates how to instantiate and use the CircuitBreaker class for direct control over circuit breaker logic in synchronous code like controllers or services. ```APIDOC ## `CircuitBreaker` — Direct Programmatic Usage `CircuitBreaker` can be used outside of jobs for synchronous code paths such as controllers, services, or CLI commands. Instantiate it with the service name matching a key in `config/fuse.php services`, then use `isOpen()` / `recordSuccess()` / `recordFailure()` to drive circuit logic manually. ```php use Harris21\Fuse\CircuitBreaker; use Stripe\Exception\ApiConnectionException; $breaker = new CircuitBreaker('stripe'); if ($breaker->isOpen()) { // Fast-fail without calling the service return response()->json(['error' => 'Payment service temporarily unavailable'], 503); } try { $charge = \Stripe\Charge::create([ 'amount' => 4999, 'currency' => 'usd', 'customer' => 'cus_abc123', ]); $breaker->recordSuccess(); // Counts as an attempt; closes circuit if HALF-OPEN return response()->json(['charge_id' => $charge->id]); } catch (ApiConnectionException $e) { $breaker->recordFailure($e); // Increments failure counter; may open circuit throw $e; } // Inspect state and statistics $stats = $breaker->getStats(); // [ // 'state' => 'closed', // 'closed' | 'open' | 'half_open' // 'attempts' => 42, // 'failures' => 3, // 'failure_rate'=> 7.1, // percentage // 'opened_at' => null, // Unix timestamp or null // 'recovery_at' => null, // opened_at + timeout, or null // 'timeout' => 30, // 'threshold' => 50, // 'min_requests'=> 5, // ] $breaker->isClosed(); // true — normal operations $breaker->isOpen(); // false — circuit is not tripped $breaker->isHalfOpen(); // false — not in recovery probe state $breaker->reset(); // Force back to CLOSED, clears all window counters ``` ``` -------------------------------- ### Fuse Configuration Options Source: https://github.com/harris21/laravel-fuse/blob/main/README.md Configure global defaults and service-specific settings for the circuit breaker, including failure thresholds, timeouts, minimum requests, and peak hour adjustments. ```php // config/fuse.php return [ 'enabled' => env('FUSE_ENABLED', true), 'default_threshold' => 50, // Failure rate percentage to trip circuit 'default_timeout' => 60, // Seconds before testing recovery 'default_min_requests' => 10, // Minimum requests before evaluating 'services' => [ 'stripe' => [ 'threshold' => 50, 'timeout' => 30, 'min_requests' => 5, 'release' => 15, // Peak hours: more tolerant during business hours 'peak_hours_threshold' => 60, 'peak_hours_start' => 9, // 9 AM 'peak_hours_end' => 17, // 5 PM ], 'mailgun' => [ 'threshold' => 60, 'timeout' => 120, 'min_requests' => 10, ], ], // Cache prefix — change if multiple apps share the same Redis instance 'cache' => [ 'prefix' => env('FUSE_CACHE_PREFIX', 'fuse'), ], ]; ``` -------------------------------- ### Check Circuit State Directly Source: https://github.com/harris21/laravel-fuse/blob/main/README.md Provides methods to check the current state of a circuit breaker (`isClosed`, `isOpen`, `isHalfOpen`), retrieve statistics, and manually reset the breaker. ```php $breaker = new CircuitBreaker('stripe'); $breaker->isClosed(); // Normal operations $breaker->isOpen(); // Protected, failing fast $breaker->isHalfOpen(); // Testing recovery $breaker->getStats(); // Get full statistics $breaker->reset(); # Manually reset to closed ``` -------------------------------- ### Manual CircuitBreaker Override in PHP Source: https://context7.com/harris21/laravel-fuse/llms.txt Use forceOpen() and forceClose() to manually set the circuit state, bypassing failure-rate evaluation. These methods dispatch corresponding Laravel events. ```php use Harris21\Fuse\CircuitBreaker; $breaker = new CircuitBreaker('stripe'); // Proactively open before a known maintenance window $breaker->forceOpen(); // Dispatches: CircuitBreakerOpened event // All jobs hitting this circuit are now released instantly // ... maintenance window ends ... // Re-open for normal traffic immediately without waiting for timeout $breaker->forceClose(); // Dispatches: CircuitBreakerClosed event // Jobs resume processing normally ``` -------------------------------- ### Protect a Job with Circuit Breaker Middleware Source: https://github.com/harris21/laravel-fuse/blob/main/README.md Add the CircuitBreakerMiddleware to your queue job's middleware array. Configure unlimited releases and limit the number of exceptions that count towards tripping the circuit. ```php use Harris21\Fuse\Middleware\CircuitBreakerMiddleware; class ChargeCustomer implements ShouldQueue { public $tries = 0; // Unlimited releases public $maxExceptions = 3; // Only real failures count public function middleware(): array { return [new CircuitBreakerMiddleware('stripe', release: 20)]; } public function handle(): void { // Your payment logic - unchanged Stripe::charges()->create([...]); } } ``` -------------------------------- ### Customize Status Page Authorization Source: https://github.com/harris21/laravel-fuse/blob/main/README.md Override the default `viewFuse` gate to control access to the status page. The default allows access only in the `local` environment. ```php use Illuminate\Support\Facades\Gate; Gate::define('viewFuse', function ($user = null) { return $user?->isAdmin(); }); ``` -------------------------------- ### Status Page JSON API Source: https://context7.com/harris21/laravel-fuse/llms.txt Provides a live dashboard with circuit state, failure rates, and state transition history via a JSON API endpoint. ```APIDOC ## Status Page JSON API Accessible at `/fuse/data` (configurable via `FUSE_STATUS_PAGE_PREFIX` in `.env` and `config/fuse.php`). This endpoint provides real-time monitoring data for services managed by Laravel Fuse. ### Method `GET` ### Endpoint `/fuse/data` ### Description Retrieves the current status of all monitored services, including their state, failure metrics, and history. ### Response #### Success Response (200) - **services** (object) - Contains status information for each monitored service. - **[serviceName]** (object) - Status details for a specific service. - **state** (string) - Current state of the circuit breaker (e.g., 'open', 'closed', 'half_open'). - **attempts** (integer) - Number of attempts made. - **failures** (integer) - Number of failures. - **failure_rate** (float) - Percentage of failures. - **opened_at** (integer) - Timestamp when the circuit was opened. - **recovery_at** (integer) - Timestamp when the circuit is expected to recover. - **timeout** (integer) - Timeout duration in seconds. - **threshold** (integer) - Failure threshold percentage. - **min_requests** (integer) - Minimum requests required to evaluate the threshold. - **state_history** (array) - An array of state transition objects. - **from** (string) - Previous state. - **to** (string) - New state. - **time** (string) - Time of transition. - **circuit_breaker_enabled** (boolean) - Indicates if the circuit breaker is globally enabled. - **timestamp** (string) - Current server time. ### Response Example ```json { "services": { "stripe": { "state": "open", "attempts": 20, "failures": 15, "failure_rate": 75.0, "opened_at": 1718000000, "recovery_at": 1718000030, "timeout": 30, "threshold": 50, "min_requests": 5, "state_history": [ { "from": "closed", "to": "open", "time": "14:23:01" }, { "from": "open", "to": "half_open", "time": "14:23:31" }, { "from": "half_open", "to": "open", "time": "14:23:32" } ] } }, "circuit_breaker_enabled": true, "timestamp": "14:24:15" } ``` ``` -------------------------------- ### Merge Circuit Breakers with Other Middleware Source: https://github.com/harris21/laravel-fuse/blob/main/README.md Use ResolvesCircuitBreakers::merge() to prepend circuit breaker middleware while including other custom middleware like RateLimited. ```php use Harris21\Fuse\Middleware\ResolvesCircuitBreakers; public function middleware(): array { return ResolvesCircuitBreakers::merge($this, [ new RateLimited('payments'), ]); } ``` -------------------------------- ### Protect a Job with CircuitBreakerMiddleware Source: https://context7.com/harris21/laravel-fuse/llms.txt Add CircuitBreakerMiddleware to a job's middleware method to wrap its execution with circuit breaker logic. Configure the service name and optional release delay. ```php use Harris21\Fuse\Middleware\CircuitBreakerMiddleware; use Illuminate\Contracts\Queue\ShouldQueue; class ChargeCustomer implements ShouldQueue { // $tries = 0 means unlimited releases; jobs never exhaust retries due to circuit protection public $tries = 0; // maxExceptions = 3 counts only real thrown exceptions, not circuit-triggered releases public $maxExceptions = 3; public function __construct( private readonly string $customerId, private readonly int $amountCents, ) {} public function middleware(): array { // 'stripe' maps to config/fuse.php services.stripe // release: 20 overrides the default delay (seconds) when circuit is OPEN return [new CircuitBreakerMiddleware('stripe', release: 20)]; } public function handle(): void { // Unchanged business logic — Fuse wraps it transparently \Stripe\Charge::create([ 'amount' => $this->amountCents, 'currency' => 'usd', 'customer' => $this->customerId, ]); } } // Dispatch normally — no change at the call site ChargeCustomer::dispatch('cus_abc123', 4999); ``` -------------------------------- ### Configure Fuse Status Page Source: https://github.com/harris21/laravel-fuse/blob/main/README.md Defines settings for the status page, including enablement, URL prefix, custom middleware, and polling interval. ```php // config/fuse.php 'status_page' => [ 'enabled' => env('FUSE_STATUS_PAGE_ENABLED', false), 'prefix' => env('FUSE_STATUS_PAGE_PREFIX', 'fuse'), 'middleware' => [], // Custom middleware (replaces default) 'polling_interval' => 2, // Frontend refresh interval in seconds ], ``` -------------------------------- ### Declarative Protection with #[UseCircuitBreaker] Attribute Source: https://context7.com/harris21/laravel-fuse/llms.txt Use the UseCircuitBreaker attribute as a declarative alternative to middleware. It can be repeated for multiple services. ```php use Harris21\Fuse\Attributes\UseCircuitBreaker; use Harris21\Fuse\Middleware\ResolvesCircuitBreakers; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Queue\Middleware\RateLimited; // Single service #[UseCircuitBreaker('stripe')] class ChargeCustomer implements ShouldQueue { public $tries = 0; public function middleware(): array { return ResolvesCircuitBreakers::resolve($this); // Equivalent to: [new CircuitBreakerMiddleware('stripe')] } public function handle(): void { /* ... */ } } // Multiple services — both circuits protect independently #[UseCircuitBreaker('stripe')] #[UseCircuitBreaker('mailgun', release: 30)] class ChargeAndNotify implements ShouldQueue { public $tries = 0; public function middleware(): array { // merge() prepends circuit breakers before other middleware return ResolvesCircuitBreakers::merge($this, [ new RateLimited('payments'), ]); // Result: [CircuitBreakerMiddleware('stripe'), CircuitBreakerMiddleware('mailgun', 30), RateLimited('payments')] } public function handle(): void { /* ... */ } } ``` -------------------------------- ### ThresholdCalculator Source: https://context7.com/harris21/laravel-fuse/llms.txt Calculates the effective failure threshold for a service, dynamically switching between standard and peak-hours thresholds based on the configured time window. ```APIDOC ## `ThresholdCalculator` — Peak Hours Threshold Calculation `ThresholdCalculator::for()` returns the effective failure threshold for a service at the current time, automatically switching between the standard threshold and the peak-hours threshold based on the configured time window. This allows higher tolerance during business-critical hours. ### Method `ThresholdCalculator::for(string $serviceName)` ### Description Retrieves the effective failure threshold for a given service, considering peak hours. ### Parameters #### Path Parameters - **serviceName** (string) - Required - The name of the service to get the threshold for. ### Request Example ```php use Harris21\Fuse\ThresholdCalculator; // Assuming config/fuse.php is set up for 'stripe' service: // 'threshold' => 40, // 'peak_hours_threshold' => 60, // 'peak_hours_start' => 9, // 'peak_hours_end' => 17, // Inside peak hours (e.g., 2 PM): ThresholdCalculator::for('stripe'); // Returns 60 // Outside peak hours (e.g., 2 AM): ThresholdCalculator::for('stripe'); // Returns 40 ``` ## `ThresholdCalculator::getConfig()` ### Description Gets the full resolved configuration for a service, including whether peak hours are currently active. ### Method `ThresholdCalculator::getConfig(string $serviceName)` ### Parameters #### Path Parameters - **serviceName** (string) - Required - The name of the service to get the configuration for. ### Response Example ```php // Returns an array like: // [ // 'threshold' => 60, // effective threshold right now // 'timeout' => 30, // 'min_requests' => 5, // 'is_peak_hours' => true, // ] ThresholdCalculator::getConfig('stripe'); ``` ``` -------------------------------- ### Default Failure Classifier Logic Source: https://context7.com/harris21/laravel-fuse/llms.txt Demonstrates how `DefaultFailureClassifier` determines if an exception should count as a failure. Excludes common client-side errors like 429, 401, and 403. ```php use Harris21\Fuse\Classifiers\DefaultFailureClassifier; use GuzzleHttp\Exception\ClientException; use GuzzleHttp\Psr7\Response; use GuzzleHttp\Psr7\Request; $classifier = new DefaultFailureClassifier; // These DO count as failures (circuit moves toward opening): $serverError = new \RuntimeException('Connection refused'); $badRequest = new ClientException('Bad Request', new Request('POST', '/'), new Response(400)); $classifier->shouldCount($serverError); // true $classifier->shouldCount($badRequest); // true // These do NOT count as failures (circuit stays closed): $rateLimited = new ClientException('Too Many Requests', new Request('POST', '/'), new Response(429)); $unauthorized = new ClientException('Unauthorized', new Request('POST', '/'), new Response(401)); $forbidden = new ClientException('Forbidden', new Request('POST', '/'), new Response(403)); $classifier->shouldCount($rateLimited); // false $classifier->shouldCount($unauthorized); // false $classifier->shouldCount($forbidden); // false ``` -------------------------------- ### Stack Multiple Circuit Breakers with Attributes Source: https://github.com/harris21/laravel-fuse/blob/main/README.md Stack multiple UseCircuitBreaker attributes on a job to protect it against multiple services. You can specify different release times for each service. ```php use Harris21\Fuse\Attributes\UseCircuitBreaker; use Harris21\Fuse\Middleware\ResolvesCircuitBreakers; #[UseCircuitBreaker('stripe')] #[UseCircuitBreaker('mailgun', release: 30)] class ChargeAndNotify implements ShouldQueue { public function middleware(): array { return ResolvesCircuitBreakers::resolve($this); } } ``` -------------------------------- ### Reset Circuit Breaker with Artisan Source: https://github.com/harris21/laravel-fuse/blob/main/README.md Manually reset a circuit breaker to the CLOSED state and clear its statistics using the `fuse:reset` Artisan command. ```bash php artisan fuse:reset # all services php artisan fuse:reset stripe # single service ``` -------------------------------- ### Manually Close Circuit with Artisan Source: https://github.com/harris21/laravel-fuse/blob/main/README.md Force a circuit breaker into the CLOSED state immediately using the `fuse:close` Artisan command. This is useful when a service has recovered but the circuit's timeout has not yet expired. ```bash php artisan fuse:close stripe ``` -------------------------------- ### Protect a Job with Circuit Breaker Attributes Source: https://github.com/harris21/laravel-fuse/blob/main/README.md Use the UseCircuitBreaker attribute to declare protection for a job. The ResolvesCircuitBreakers class resolves the necessary middleware. ```php use Harris21\Fuse\Attributes\UseCircuitBreaker; use Harris21\Fuse\Middleware\ResolvesCircuitBreakers; #[UseCircuitBreaker('stripe')] class ChargeCustomer implements ShouldQueue { public function middleware(): array { return ResolvesCircuitBreakers::resolve($this); } } ``` -------------------------------- ### Configure Custom Failure Classifier Source: https://github.com/harris21/laravel-fuse/blob/main/README.md Override the default failure classification logic for a specific service. This is useful when a service deviates from standard HTTP error codes. ```php 'services' => [ 'stripe' => [ 'threshold' => 50, 'timeout' => 30, 'min_requests' => 5, 'failure_classifier' => \App\Fuse\StripeFailureClassifier::class, ], ] ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.