All files / async / unstable_circuit_breaker.ts

100.00% Branches 100/100
100.00% Functions 21/21
100.00% Lines 275/275
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
 
 
 
x9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x9
 
 
 
 
 
 
 
 
x9
x5
x5
 
x5
x5
x5
x9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x9
x49
x49
x49
x49
x49
x49
x49
 
 
x9
x47
x3
x3
 
x3
x47
 
 
x9
x244
x15
x15
 
x15
x244
 
 
x9
x61
x5
x5
 
x5
x61
 
 
 
 
 
 
x9
x9
 
x190
x18
x30
x30
x30
x2
x2
x2
x2
x18
x190
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x9
x9
x61
x61
x61
x61
x61
x61
x61
x61
 
 
x61
x61
x61
x61
x61
x61
x61
x9
 
 
 
 
 
 
 
 
 
x9
x61
x61
x61
x61
x61
x61
x61
x61
x61
x61
x61
x61
x61
x61
x61
x61
 
x61
x61
x61
x61
x61
x61
x61
 
x61
x61
x61
x61
x61
x61
x61
x61
x61
x61
x61
x61
x61
x61
x61
x61
x61
x61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x9
x45
x45
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x9
x9
x9
x9
x64
 
x64
x64
 
x64
x2
x2
x2
x2
 
x64
x16
x1
x1
x15
x15
x15
x15
x15
 
x60
x60
 
x60
x60
x60
x64
x36
x36
x34
x34
x36
x1
x1
x1
x1
x36
x64
x60
x15
x15
x15
x15
x15
x60
 
x24
x62
x2
x2
x2
x2
x64
x1
x1
x1
x1
x1
 
x21
x21
x64
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x9
x6
x6
x6
x6
x6
x6
x6
x6
x6
x6
x5
x5
x5
x6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x9
x4
x4
x4
x4
x3
x3
x3
x4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x9
x2
x2
x2
 
 
x9
x66
x66
x66
x3
x3
x3
x3
x66
 
 
x9
x11
x11
x11
x11
 
 
 
 
 
x9
x108
x76
x76
 
x32
x102
x18
x18
 
x14
x14
x14
x14
x14
x14
x108
x108
x108
x108
 
 
x9
x9
x9
x9
 
x36
x36
x36
 
x36
x36
x36
 
x36
x26
x26
x26
x26
x26
x26
x36
x10
x10
x10
x10
x10
 
x36
x36
x26
x26
x26
x36
 
 
x9
x21
x21
 
x9
x20
x5
x5
x5
x5
x5
x5
 
x4
x21
x9



















































































































































































































































































































































































































































































































































































































































































































































































































// Copyright 2018-2026 the Deno authors. MIT license.
// This module is browser compatible.

import { RollingCounter } from "@std/data-structures/unstable-rolling-counter";

/**
 * Circuit breaker states following the standard pattern.
 * - `"closed"`: Normal operation, requests pass through
 * - `"open"`: Failing, all requests rejected immediately
 * - `"half_open"`: Testing recovery, limited requests allowed
 *
 * @experimental **UNSTABLE**: New API, yet to be vetted.
 */
export type CircuitState = "closed" | "open" | "half_open";

/**
 * Options for {@linkcode CircuitBreaker}.
 *
 * @experimental **UNSTABLE**: New API, yet to be vetted.
 */
export interface CircuitBreakerOptions<T> {
  /**
   * Failure rate threshold as a ratio between 0 (exclusive) and 1 (inclusive).
   * The circuit opens when the failure rate in the sliding window meets or
   * exceeds this value and at least {@linkcode minimumThroughput} requests
   * have been recorded.
   *
   * @default {0.5}
   */
  failureRateThreshold?: number;

  /**
   * Minimum number of requests in the sliding window before the failure rate
   * is evaluated. Prevents the circuit from tripping on statistically
   * insignificant samples during low traffic.
   *
   * @default {20}
   */
  minimumThroughput?: number;

  /**
   * Duration of the sliding window in milliseconds.
   *
   * @default {60000}
   */
  windowMs?: number;

  /**
   * Number of segments the sliding window is divided into. More segments
   * give finer-grained decay at the cost of slightly more memory.
   *
   * @default {10}
   */
  segmentsPerWindow?: number;

  /**
   * Duration in milliseconds the circuit stays open before entering half-open.
   *
   * @default {30000}
   */
  cooldownMs?: number;

  /**
   * Number of consecutive successes needed to close from half-open state.
   *
   * @default {2}
   */
  successThreshold?: number;

  /**
   * Maximum concurrent requests allowed in half-open state.
   *
   * @default {3}
   */
  halfOpenMaxConcurrent?: number;

  /**
   * Custom predicate to determine if an error should count as a circuit failure.
   * By default, any thrown error is a failure.
   *
   * @param error The error that was thrown.
   * @returns `true` if the error should count as a circuit failure.
   */
  isFailure?: (error: unknown) => boolean;

  /**
   * Custom predicate to determine if a successful result should count as failure.
   * Useful for HTTP responses where status codes indicate logical failures.
   *
   * @param result The successful result.
   * @returns `true` if the result should count as a circuit failure.
   */
  isResultFailure?: (result: T) => boolean;

  /**
   * Callback invoked when circuit state changes.
   *
   * If this callback throws, the error is reported asynchronously
   * without disrupting circuit breaker operation.
   *
   * @param from Previous state.
   * @param to New state.
   */
  onStateChange?: (from: CircuitState, to: CircuitState) => void;

  /**
   * Callback invoked when a failure is recorded.
   *
   * If this callback throws, the error is reported asynchronously
   * without disrupting circuit breaker operation.
   *
   * @param error The error that caused the failure, or a synthetic error
   *   when the result was classified as failure by {@linkcode isResultFailure}.
   * @param failureCount Current number of failures in the window.
   * @param totalRequests Current number of total requests in the window.
   */
  onFailure?: (
    error: unknown,
    failureCount: number,
    totalRequests: number,
  ) => void;

  /**
   * Callback invoked when circuit opens.
   *
   * If this callback throws, the error is reported asynchronously
   * without disrupting circuit breaker operation.
   *
   * @param failureCount Number of failures in the window that triggered the open.
   * @param totalRequests Number of total requests in the window.
   */
  onOpen?: (failureCount: number, totalRequests: number) => void;

  /**
   * Callback invoked when circuit enters half-open state (testing recovery).
   *
   * If this callback throws, the error is reported asynchronously
   * without disrupting circuit breaker operation.
   */
  onHalfOpen?: () => void;

  /**
   * Callback invoked when circuit closes (recovery complete).
   *
   * If this callback throws, the error is reported asynchronously
   * without disrupting circuit breaker operation.
   */
  onClose?: () => void;
}

/**
 * Options for {@linkcode CircuitBreaker.execute}.
 *
 * @experimental **UNSTABLE**: New API, yet to be vetted.
 */
export interface CircuitBreakerExecuteOptions {
  /**
   * An optional abort signal that can be used to cancel the operation
   * before it starts. If the signal is already aborted when `execute` is
   * called, the operation will fail immediately without executing the function.
   *
   * Note: This only checks the abort status before execution. It does not
   * interrupt an in-progress operation — pass the signal to your async
   * function for that behavior.
   */
  signal?: AbortSignal;
}

/**
 * Error thrown when {@linkcode CircuitBreaker} is open and rejects a request.
 *
 * @experimental **UNSTABLE**: New API, yet to be vetted.
 *
 * @example Usage
 * ```ts
 * import { CircuitBreaker, CircuitBreakerOpenError } from "@std/async/unstable-circuit-breaker";
 * import { assert } from "@std/assert";
 *
 * const breaker = new CircuitBreaker({
 *   failureRateThreshold: 1,
 *   minimumThroughput: 1,
 * });
 *
 * // Trigger a failure to open the circuit
 * try {
 *   await breaker.execute(() => Promise.reject(new Error("fail")));
 * } catch (_) {
 *   // Expected to fail
 * }
 *
 * // Now the circuit is open
 * try {
 *   await breaker.execute(() => Promise.resolve("ok"));
 * } catch (error) {
 *   assert(error instanceof CircuitBreakerOpenError);
 *   assert(error.remainingCooldownMs >= 0);
 * }
 * ```
 */
export class CircuitBreakerOpenError extends Error {
  /**
   * Milliseconds until the circuit breaker cooldown expires.
   *
   * @experimental **UNSTABLE**: New API, yet to be vetted.
   *
   * @example Usage
   * ```ts
   * import { CircuitBreakerOpenError } from "@std/async/unstable-circuit-breaker";
   * import { assertEquals } from "@std/assert";
   *
   * const error = new CircuitBreakerOpenError(5000);
   * assertEquals(error.remainingCooldownMs, 5000);
   * ```
   */
  readonly remainingCooldownMs: number;

  /**
   * Constructs a new {@linkcode CircuitBreakerOpenError} instance.
   *
   * @experimental **UNSTABLE**: New API, yet to be vetted.
   *
   * @param remainingCooldownMs The number of milliseconds until the circuit breaker exits the open state.
   */
  constructor(remainingCooldownMs: number) {
    super(
      `Circuit breaker is open: retry after ${remainingCooldownMs}ms`,
    );
    this.name = "CircuitBreakerOpenError";
    this.remainingCooldownMs = remainingCooldownMs;
  }
}

/** Internal state managed by the circuit breaker. */
type CircuitBreakerState =
  | {
    readonly state: "closed";
    readonly openedAt: null;
    readonly consecutiveSuccesses: number;
    readonly halfOpenInFlight: number;
  }
  | {
    readonly state: "open";
    readonly openedAt: number;
    readonly consecutiveSuccesses: number;
    readonly halfOpenInFlight: number;
  }
  | {
    readonly state: "half_open";
    readonly openedAt: number;
    readonly consecutiveSuccesses: number;
    readonly halfOpenInFlight: number;
  };

/** Creates initial circuit breaker state. */
function createInitialState(): CircuitBreakerState & { state: "closed" } {
  return {
    state: "closed",
    consecutiveSuccesses: 0,
    openedAt: null,
    halfOpenInFlight: 0,
  };
}

/** Validates that a value is a finite non-negative number. */
function validateNonNegative(name: string, value: number): void {
  if (!Number.isFinite(value) || value < 0) {
    throw new RangeError(
      `Cannot create circuit breaker: "${name}" must be a finite non-negative number, received ${value}`,
    );
  }
}

/** Validates that a value is a positive integer. */
function validatePositiveInteger(name: string, value: number): void {
  if (!Number.isInteger(value) || value < 1) {
    throw new RangeError(
      `Cannot create circuit breaker: "${name}" must be a positive integer, received ${value}`,
    );
  }
}

/** Validates that a value is in the range (0, 1]. */
function validateRate(name: string, value: number): void {
  if (!Number.isFinite(value) || value <= 0 || value > 1) {
    throw new RangeError(
      `Cannot create circuit breaker: "${name}" must be a finite number in (0, 1], received ${value}`,
    );
  }
}

/**
 * Wraps a notification callback so that if it throws, the error is
 * re-thrown asynchronously (as an uncaught exception) without
 * disrupting the circuit breaker's synchronous control flow.
 */
function safeCallback<A extends unknown[]>(
  fn: ((...args: A) => void) | undefined,
): ((...args: A) => void) | undefined {
  if (!fn) return undefined;
  return (...args: A) => {
    try {
      fn(...args);
    } catch (error) {
      queueMicrotask(() => {
        throw error;
      });
    }
  };
}

/**
 * A circuit breaker that wraps async operations to prevent cascading failures.
 *
 * The circuit breaker monitors the failure rate within a sliding window and
 * "trips" (opens) when the rate exceeds a threshold, rejecting subsequent
 * requests immediately without executing them. After a cooldown period, it
 * enters a "half-open" state to test if the service has recovered.
 *
 * The failure rate is only evaluated once at least
 * {@linkcode CircuitBreakerOptions.minimumThroughput | minimumThroughput}
 * requests have been recorded in the window, preventing false positives
 * during low traffic.
 *
 * @experimental **UNSTABLE**: New API, yet to be vetted.
 *
 * @example Usage
 * ```ts
 * import { CircuitBreaker } from "@std/async/unstable-circuit-breaker";
 * import { assertEquals } from "@std/assert";
 *
 * const breaker = new CircuitBreaker({
 *   failureRateThreshold: 0.5,
 *   minimumThroughput: 20,
 *   cooldownMs: 30000,
 * });
 *
 * assertEquals(breaker.state, "closed");
 *
 * const result = await breaker.execute(() => Promise.resolve("success"));
 * assertEquals(result, "success");
 * ```
 *
 * @example Handling open circuit
 * ```ts ignore
 * import { CircuitBreaker, CircuitBreakerOpenError } from "@std/async/unstable-circuit-breaker";
 *
 * const breaker = new CircuitBreaker();
 *
 * try {
 *   const result = await breaker.execute(() => fetch("https://api.example.com"));
 * } catch (error) {
 *   if (error instanceof CircuitBreakerOpenError) {
 *     console.log(`Service unavailable, retry in ${error.remainingCooldownMs}ms`);
 *   }
 * }
 * ```
 *
 * @example With custom failure detection
 * ```ts no-assert
 * import { CircuitBreaker } from "@std/async/unstable-circuit-breaker";
 *
 * const breaker = new CircuitBreaker<Response>({
 *   failureRateThreshold: 0.1,
 *   isResultFailure: (response) => response.status >= 500,
 *   onStateChange: (from, to) => console.log(`Circuit: ${from} → ${to}`),
 * });
 * ```
 *
 * @example Composing with retry and AbortSignal
 * ```ts ignore
 * import { retry } from "@std/async/retry";
 * import { CircuitBreaker } from "@std/async/unstable-circuit-breaker";
 *
 * const breaker = new CircuitBreaker();
 *
 * // Timeout applies to the entire operation (circuit breaker + retries)
 * const signal = AbortSignal.timeout(5000);
 *
 * const result = await breaker.execute(
 *   () => retry(() => fetch("https://api.example.com"), { signal }),
 *   { signal },
 * );
 * ```
 *
 * @example Waiting out the cooldown with delay
 * ```ts ignore
 * import { delay } from "@std/async/delay";
 * import { CircuitBreaker, CircuitBreakerOpenError } from "@std/async/unstable-circuit-breaker";
 *
 * const breaker = new CircuitBreaker();
 *
 * try {
 *   return await breaker.execute(() => fetch("https://api.example.com"));
 * } catch (error) {
 *   if (error instanceof CircuitBreakerOpenError) {
 *     // Wait for the circuit to transition to half-open, then retry
 *     await delay(error.remainingCooldownMs);
 *     return await breaker.execute(() => fetch("https://api.example.com"));
 *   }
 *   throw error;
 * }
 * ```
 *
 * @typeParam T The type of value returned by the executed function.
 */
export class CircuitBreaker<T = unknown> {
  #failureRateThreshold: number;
  #minimumThroughput: number;
  #cooldownMs: number;
  #successThreshold: number;
  #halfOpenMaxConcurrent: number;
  #isFailure: (error: unknown) => boolean;
  #isResultFailure: (result: T) => boolean;
  #onStateChange: ((from: CircuitState, to: CircuitState) => void) | undefined;
  #onFailure:
    | ((error: unknown, failureCount: number, totalRequests: number) => void)
    | undefined;
  #onOpen: ((failureCount: number, totalRequests: number) => void) | undefined;
  #onHalfOpen: (() => void) | undefined;
  #onClose: (() => void) | undefined;
  #state: CircuitBreakerState;
  #requests: RollingCounter;
  #failures: RollingCounter;
  #lastRotationMs: number;
  #msPerSegment: number;

  /**
   * Constructs a new {@linkcode CircuitBreaker} instance.
   *
   * @experimental **UNSTABLE**: New API, yet to be vetted.
   *
   * @param options Configuration options for the circuit breaker.
   * @throws {RangeError} If any numeric option is not a finite number within its valid range.
   */
  constructor(options: CircuitBreakerOptions<T> = {}) {
    const {
      failureRateThreshold = 0.5,
      minimumThroughput = 20,
      windowMs = 60_000,
      segmentsPerWindow = 10,
      cooldownMs = 30_000,
      successThreshold = 2,
      halfOpenMaxConcurrent = 3,
      isFailure = () => true,
      isResultFailure = () => false,
      onStateChange,
      onFailure,
      onOpen,
      onHalfOpen,
      onClose,
    } = options;

    validateRate("failureRateThreshold", failureRateThreshold);
    validatePositiveInteger("minimumThroughput", minimumThroughput);
    validatePositiveInteger("windowMs", windowMs);
    validatePositiveInteger("segmentsPerWindow", segmentsPerWindow);
    validateNonNegative("cooldownMs", cooldownMs);
    validatePositiveInteger("successThreshold", successThreshold);
    validatePositiveInteger("halfOpenMaxConcurrent", halfOpenMaxConcurrent);

    this.#failureRateThreshold = failureRateThreshold;
    this.#minimumThroughput = minimumThroughput;
    this.#cooldownMs = cooldownMs;
    this.#successThreshold = successThreshold;
    this.#halfOpenMaxConcurrent = halfOpenMaxConcurrent;
    this.#isFailure = isFailure;
    this.#isResultFailure = isResultFailure;
    this.#onStateChange = safeCallback(onStateChange);
    this.#onFailure = safeCallback(onFailure);
    this.#onOpen = safeCallback(onOpen);
    this.#onHalfOpen = safeCallback(onHalfOpen);
    this.#onClose = safeCallback(onClose);
    this.#state = createInitialState();
    this.#requests = new RollingCounter(segmentsPerWindow);
    this.#failures = new RollingCounter(segmentsPerWindow);
    this.#msPerSegment = windowMs / segmentsPerWindow;
    this.#lastRotationMs = Date.now();
  }

  /**
   * Current state of the circuit breaker.
   *
   * Time-based transitions (e.g. open to half-open after cooldown) are
   * resolved lazily when this property is read.
   *
   * @experimental **UNSTABLE**: New API, yet to be vetted.
   *
   * @example Usage
   * ```ts
   * import { CircuitBreaker } from "@std/async/unstable-circuit-breaker";
   * import { assertEquals } from "@std/assert";
   *
   * const breaker = new CircuitBreaker();
   * assertEquals(breaker.state, "closed");
   * ```
   *
   * @returns The current {@linkcode CircuitState}.
   */
  get state(): CircuitState {
    return this.#advanceState(Date.now()).state;
  }

  /**
   * Executes a function through the circuit breaker.
   *
   * The function can be synchronous or asynchronous. The result is always
   * returned as a promise.
   *
   * @experimental **UNSTABLE**: New API, yet to be vetted.
   *
   * @example Usage with async function
   * ```ts ignore
   * import { CircuitBreaker } from "@std/async/unstable-circuit-breaker";
   *
   * const breaker = new CircuitBreaker();
   * const response = await breaker.execute(() => fetch("https://api.example.com"));
   * ```
   *
   * @example With timeout
   * ```ts ignore
   * import { CircuitBreaker } from "@std/async/unstable-circuit-breaker";
   *
   * const breaker = new CircuitBreaker();
   *
   * // Abort if operation takes longer than 5 seconds
   * const response = await breaker.execute(
   *   () => fetch("https://api.example.com"),
   *   { signal: AbortSignal.timeout(5000) },
   * );
   * ```
   *
   * @typeParam R The return type of the function, must extend T.
   * @param fn The function to execute through the circuit breaker.
   * @param options Options for this execution, such as an abort signal.
   * @returns A promise that resolves to the result of the operation.
   * @throws {CircuitBreakerOpenError} If circuit is open.
   * @throws {DOMException} If the abort signal is already aborted.
   */
  async execute<R extends T>(
    fn: () => R | Promise<R>,
    options?: CircuitBreakerExecuteOptions,
  ): Promise<R> {
    options?.signal?.throwIfAborted();

    const currentTime = Date.now();
    const currentState = this.#advanceState(currentTime);

    if (currentState.state === "open") {
      const cooldownEnd = currentState.openedAt + this.#cooldownMs;
      const remainingMs = Math.max(0, cooldownEnd - currentTime);
      throw new CircuitBreakerOpenError(Math.round(remainingMs));
    }

    if (currentState.state === "half_open") {
      if (currentState.halfOpenInFlight >= this.#halfOpenMaxConcurrent) {
        throw new CircuitBreakerOpenError(0);
      }
      this.#state = {
        ...this.#state,
        halfOpenInFlight: this.#state.halfOpenInFlight + 1,
      };
    }

    this.#rotateToNow(currentTime);
    this.#requests.increment();

    let result: R;
    try {
      result = await fn();
    } catch (error) {
      try {
        if (this.#isFailure(error)) {
          this.#handleFailure(error, currentState.state, currentTime);
        }
      } catch (predicateError) {
        queueMicrotask(() => {
          throw predicateError;
        });
      }
      throw error;
    } finally {
      if (currentState.state === "half_open") {
        this.#state = {
          ...this.#state,
          halfOpenInFlight: Math.max(0, this.#state.halfOpenInFlight - 1),
        };
      }
    }

    try {
      if (this.#isResultFailure(result)) {
        const syntheticError = new Error("Result classified as failure");
        this.#handleFailure(syntheticError, currentState.state, currentTime);
        return result;
      }
    } catch (predicateError) {
      queueMicrotask(() => {
        throw predicateError;
      });
      return result;
    }

    this.#handleSuccess(currentState.state);
    return result;
  }

  /**
   * Forces the circuit breaker to open state.
   * Useful for maintenance or known outages.
   *
   * @experimental **UNSTABLE**: New API, yet to be vetted.
   *
   * @example Usage
   * ```ts
   * import { CircuitBreaker } from "@std/async/unstable-circuit-breaker";
   * import { assertEquals } from "@std/assert";
   *
   * const breaker = new CircuitBreaker();
   * breaker.forceOpen();
   * assertEquals(breaker.state, "open");
   * ```
   */
  forceOpen(): void {
    const previous = this.#state.state;
    const now = Date.now();
    this.#rotateToNow(now);
    this.#state = {
      ...this.#state,
      state: "open",
      openedAt: now,
      consecutiveSuccesses: 0,
    };
    if (previous !== "open") {
      this.#onStateChange?.(previous, "open");
      this.#onOpen?.(this.#failures.total, this.#requests.total);
    }
  }

  /**
   * Forces the circuit breaker to closed state and notifies observers.
   *
   * This is an operational transition that fires {@linkcode onStateChange}
   * and {@linkcode onClose} callbacks. Use this when the protected service
   * has recovered and you want observers to be notified.
   *
   * For silent resets (e.g., in tests), use {@linkcode reset} instead.
   *
   * @experimental **UNSTABLE**: New API, yet to be vetted.
   *
   * @example Usage
   * ```ts
   * import { CircuitBreaker } from "@std/async/unstable-circuit-breaker";
   * import { assertEquals } from "@std/assert";
   *
   * const breaker = new CircuitBreaker();
   * breaker.forceOpen();
   * breaker.forceClose();
   * assertEquals(breaker.state, "closed");
   * ```
   */
  forceClose(): void {
    const previous = this.#state.state;
    this.#state = createInitialState();
    this.#clearCounters();
    if (previous !== "closed") {
      this.#onStateChange?.(previous, "closed");
      this.#onClose?.();
    }
  }

  /**
   * Silently resets the circuit breaker to initial state.
   *
   * Unlike {@linkcode forceClose}, this does not fire any callbacks
   * (`onStateChange`, `onClose`). Use this for testing or administrative
   * resets where observers should not be notified.
   *
   * @experimental **UNSTABLE**: New API, yet to be vetted.
   *
   * @example Usage
   * ```ts
   * import { CircuitBreaker } from "@std/async/unstable-circuit-breaker";
   * import { assertEquals } from "@std/assert";
   *
   * const breaker = new CircuitBreaker();
   * breaker.reset();
   * assertEquals(breaker.state, "closed");
   * ```
   */
  reset(): void {
    this.#state = createInitialState();
    this.#clearCounters();
  }

  /** Advances both counters to the current time, evicting stale segments. */
  #rotateToNow(now: number): void {
    const elapsed = now - this.#lastRotationMs;
    const steps = Math.floor(elapsed / this.#msPerSegment);
    if (steps > 0) {
      this.#requests.rotate(steps);
      this.#failures.rotate(steps);
      this.#lastRotationMs += steps * this.#msPerSegment;
    }
  }

  /** Resets both counters and the rotation timestamp. */
  #clearCounters(): void {
    this.#requests.clear();
    this.#failures.clear();
    this.#lastRotationMs = Date.now();
  }

  /**
   * Advances the state machine, transitioning OPEN -> HALF_OPEN when
   * the cooldown has expired. No-op for other states.
   */
  #advanceState(now: number): CircuitBreakerState {
    if (this.#state.state !== "open") {
      return this.#state;
    }

    const cooldownEnd = this.#state.openedAt + this.#cooldownMs;
    if (now < cooldownEnd) {
      return this.#state;
    }

    this.#state = {
      ...this.#state,
      state: "half_open",
      consecutiveSuccesses: 0,
      halfOpenInFlight: 0,
    };
    this.#onStateChange?.("open", "half_open");
    this.#onHalfOpen?.();
    return this.#state;
  }

  /** Records a failure and potentially opens the circuit. */
  #handleFailure(
    error: unknown,
    previousState: CircuitState,
    now: number,
  ): void {
    this.#failures.increment();
    const totalRequests = this.#requests.total;
    const failureCount = this.#failures.total;

    const shouldOpen = previousState === "half_open" ||
      (totalRequests >= this.#minimumThroughput &&
        failureCount / totalRequests >= this.#failureRateThreshold);

    if (shouldOpen) {
      this.#state = {
        ...this.#state,
        state: "open",
        openedAt: now,
        consecutiveSuccesses: 0,
      };
    } else {
      this.#state = {
        ...this.#state,
        consecutiveSuccesses: 0,
      };
    }

    this.#onFailure?.(error, failureCount, totalRequests);
    if (shouldOpen) {
      this.#onStateChange?.(previousState, "open");
      this.#onOpen?.(failureCount, totalRequests);
    }
  }

  /** Records a success and potentially closes the circuit from half-open. */
  #handleSuccess(previousState: CircuitState): void {
    if (previousState === "closed") return;
    if (this.#state.state !== "half_open") return;

    const newSuccessCount = this.#state.consecutiveSuccesses + 1;
    if (newSuccessCount >= this.#successThreshold) {
      this.#state = createInitialState();
      this.#clearCounters();
      this.#onStateChange?.("half_open", "closed");
      this.#onClose?.();
      return;
    }

    this.#state = { ...this.#state, consecutiveSuccesses: newSuccessCount };
  }
}