# @git-stunts/alfred 中文文档

规范地址：https://npmcn.com/package/%40git-stunts/alfred/

版本：0\.10\.4
npm 元数据更新时间：2026-06-24T21:23:44.846Z
中文译文更新时间：2026-11-16T10:25:33.265Z
软件包许可：Apache-2\.0

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40git-stunts/alfred
原文对照：https://npmcn.com/package/%40git-stunts/alfred/?lang=original
项目主页：https://github.com/git-stunts/alfred#readme
源码仓库：https://github.com/git-stunts/alfred

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：134 kB，22 个文件
- 模块格式：ES Module
- TypeScript 类型：包内自带
- Node.js 要求：\>=20\.0\.0
- 运行依赖：0 个
- 首次发布：2026-01-31T19:32:02.719Z
- 最新版本发布：2026-06-24T21:23:44.456Z
- 近 30 天下载量：7923（2026-10-17 至 2026-11-15，npm 官方下载统计）
- 已发布版本数：15（近 12 个月 15 个）

## 中文简介

生产级耐受性模式用于Aync ops:再试/后置+慢跑,断路器,散头,超时.

## 安装

```sh
npm install @git-stunts/alfred
```

也可以使用：`pnpm add @git-stunts/alfred`、`yarn add @git-stunts/alfred`、`bun add @git-stunts/alfred`

## README

# @git-stunts/ alfred (英语)

[![JSR](https://jsr.io/badges/@git-stunts/alfred)](https://jsr.io/@git-stunts/alfred) [![NPM Version](https://img.shields.io/npm/v/@git-stunts/alfred)](https://www.npmjs.com/package/@git-stunts/alfred) [![CI](https://github.com/git-stunts/alfred/actions/workflows/ci.yml/badge.svg)](https://github.com/git-stunts/alfred/actions/workflows/ci.yml)

```text
      .o.       oooo   .o88o.                          .o8
     .888.      `888   888 `"                         "888
    .8"888.      888  o888oo  oooo d8b  .ooooo.   .oooo888
   .8' `888.     888   888    `888""8P d88' `88b d88' `888
  .88ooo8888.    888   888     888     888ooo888 888   888
 .8'     `888.   888   888     888     888    .o 888   888
o88o     o8888o o888o o888o   d888b    `Y8bod8P' `Y8bod88P"
```

> _"我们为什么摔倒,布鲁斯?"_
> 
> _"所以我们可以 `retry({ backoff: 'exponential', jitter: 'decorrelated' })`""("史记")_

合成作业的复原力模式. _大部分东西都装满了._

包括:再试-断路器-散头-超时-套接字-构件-测试钟-遥测汇

* * *

## 安装

### 无

```bash
npm install @git-stunts/alfred
```

### JSR (德诺、 Bun、 节点)

```bash
npx jsr add @git-stunts/alfred
```

* * *

## 路线图

见生态系统路线图 [ROADMAP.md 地图](https://github.com/git-stunts/alfred/blob/main/ROADMAP.md)。 。 。 .

## 直播控制计划

需要调整政策而不重新部署? 使用 `@git-stunts/alfred-live` 页:1 `LivePolicyPlan` + 键 `ControlPlane` 在跑道上驾驶阿尔弗雷德的捆绑.

* * *

## 20秒赢

一个现实的堆栈,你将实际运送: 全部超时 + 重试(decor recording jitter) + 断路器 + 批发头.

```javascript
import { Policy } from '@git-stunts/alfred';

const resilient = Policy.timeout(5_000)
  .wrap(
    Policy.retry({
      retries: 3,
      backoff: 'exponential',
      jitter: 'decorrelated',
      delay: 150,
      maxDelay: 3_000,
      shouldRetry: (err) =>
        err?.name === 'TimeoutError' || err?.code === 'ECONNRESET' || err?.code === 'ETIMEDOUT',
    })
  )
  .wrap(
    Policy.circuitBreaker({
      threshold: 5,
      duration: 60_000,
    })
  )
  .wrap(Policy.bulkhead({ limit: 10, queueLimit: 20 }));

const data = await resilient.execute(async () => {
  const res = await fetch('https://api.example.com/data');
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
  return res.json();
});
```

* * *

## 多跑期支助

阿尔弗雷德被设计为平台不可知并针对:

-   **节点.js** ( )
-   **阿宝** ( )
-   **德诺** (>= 1.35)
-   **浏览器** (Chrome 85+, Firefox 79+, Safari 14+, Edge 85+)
-   **云花岗工人**

使用标准Web API(Abort Controller, A中止Signal, promise.any),并带有Node特定依赖性. runtime-aware时钟管理确保在服务器环境中清洁的流程退出.

### 浏览器 Demo

运行交互式的“ Flaky Fettle Lab” , 查看恢复力政策在行动中:

```bash
npm run demo:web:install && npm run demo:web
```

或者运行 Playwright 浏览器测试 :

```bash
npm run demo:web:install && npm run test:browser
```

* * *

## 快速启动( 功能助手)

```javascript
import { retry, circuitBreaker, bulkhead, timeout } from '@git-stunts/alfred';

// 1) Simple retry with exponential backoff
const data = await retry(() => fetch('https://api.example.com/data'), {
  retries: 3,
  backoff: 'exponential',
  delay: 100,
});

// 2) Circuit breaker — fail fast when a service is down
const breaker = circuitBreaker({ threshold: 5, duration: 60_000 });
const result = await breaker.execute(() => callFlakeyService());

// 3) Bulkhead — limit concurrent executions
const limiter = bulkhead({ limit: 10, queueLimit: 20 });
await limiter.execute(() => heavyOperation());

// 4) Timeout — prevent operations from hanging
const fast = await timeout(5_000, () => slowOperation());
```

* * *

## 政策代数

阿尔弗雷德为构建复杂的复原力战略提供三个成分操作员:

| 运算符 | 流畅 | 职能 | 语义 |
| --- | --- | --- | --- |
| **关闭** | `.wrap(policy)` | `compose(a, b)` | 顺序:A 包 B(外-内) |
| **或者说** | `.or(policy)` | `fallback(a, b)` | 倒置: 尝试 A, 如果失败尝试 B |
| **种族** | `.race(policy)` | `race(a, b)` | 同时:第一次成功获胜 |

### 例1:生产堆栈(超时出局+重试+电路+批头)

经典回弹堆. 从 **外来**: 超时包装 重试 包装断路器 包装散头.

```javascript
import { Policy } from '@git-stunts/alfred';

const resilient = Policy.timeout(5_000) // 1. Total deadline
  .wrap(
    Policy.retry({
      // 2. Retry transient failures
      retries: 3,
      backoff: 'exponential',
      jitter: 'decorrelated',
      delay: 100,
    })
  )
  .wrap(
    Policy.circuitBreaker({
      // 3. Fail fast when broken
      threshold: 5,
      duration: 30_000,
    })
  )
  .wrap(Policy.bulkhead({ limit: 10, queueLimit: 20 })); // 4. Limit concurrency

await resilient.execute(() => fetch('https://api.example.com/data'));
```

### 例2:快速倒计时

首先尝试快取策略;如果失败(或时断时续),则回到较慢但更可靠的方法.

```javascript
import { Policy } from '@git-stunts/alfred';

// Fast path: short timeout, no retries
const fast = Policy.timeout(500);

// Slow path: longer timeout with retries
const slow = Policy.timeout(5_000).wrap(
  Policy.retry({ retries: 3, backoff: 'exponential', delay: 200 })
);

// Try fast first, fall back to slow
const resilient = fast.or(slow);

await resilient.execute(() => fetch('https://api.example.com/data'));
```

### 例3:套接字请求(雷克模式)

相并相并的"夹"请求来减少尾部空隙. 第一次成功获胜;失败者被取消.

```javascript
import { Policy } from '@git-stunts/alfred';

// Hedge: if primary is slow, spawn backup attempts
const hedged = Policy.hedge({ delay: 100, maxHedges: 2 });

// Combine with bulkhead to prevent self-DDOS
const safe = hedged.wrap(Policy.bulkhead({ limit: 5 }));

// The operation receives an AbortSignal to enable cancellation
await safe.execute((signal) => fetch('https://api.example.com/data', { signal }));
```

> **提示 :** 只有对冲一能操作。 非本能业务(写作,支付)不得套期.

### 流利对函数

两种风格都产生等效的结果:

```javascript
// Fluent API
const policy1 = Policy.timeout(5_000)
  .wrap(Policy.retry({ retries: 3 }))
  .wrap(Policy.circuitBreaker({ threshold: 5, duration: 60_000 }));

// Functional API
const policy2 = compose(
  Policy.timeout(5_000),
  Policy.retry({ retries: 3 }),
  circuitBreaker({ threshold: 5, duration: 60_000 }) // functional returns policy object
);
```

建议流利的API可读性. 使用函数 `compose()` 在动态地制定政策时.

* * *

## API 密码

-   [重试( fn, 选项)](https://npmcn.com/package/%40git-stunts/alfred/#readme-retryfn-options)
-   [电路Breaker( 选项)](https://npmcn.com/package/%40git-stunts/alfred/#readme-circuitbreakeroptions)
-   [散头( 选项)](https://npmcn.com/package/%40git-stunts/alfred/#readme-bulkheadoptions)
-   [比率限制( 选项)](https://npmcn.com/package/%40git-stunts/alfred/#readme-ratelimitoptions)
-   [超时( ms, fn, 选项)](https://npmcn.com/package/%40git-stunts/alfred/#readme-timeoutms-fn-options)
-   [套接字( 选项)](https://npmcn.com/package/%40git-stunts/alfred/#readme-hedgeoptions)
-   [政策代数](https://npmcn.com/package/%40git-stunts/alfred/#readme-policy-algebra)
-   [政策(流利的API)](https://npmcn.com/package/%40git-stunts/alfred/#readme-policy-fluent-api)
-   [作曲(... 政策)](https://npmcn.com/package/%40git-stunts/alfred/#readme-composepolicies)
-   [回落( 小学、 中学)](https://npmcn.com/package/%40git-stunts/alfred/#readme-fallbackprimary-secondary)
-   [种族(小学、中学)](https://npmcn.com/package/%40git-stunts/alfred/#readme-raceprimary-secondary)
-   [遥测和可观察性](https://npmcn.com/package/%40git-stunts/alfred/#readme-telemetry--observability)
-   [测试](https://npmcn.com/package/%40git-stunts/alfred/#readme-testing)
-   [错误类型](https://npmcn.com/package/%40git-stunts/alfred/#readme-error-types)
-   [决议时间](https://npmcn.com/package/%40git-stunts/alfred/#readme-resolution-timing-dynamic-options)

* * *

## 重试( fn, 选项)

以可配置回放重置操作失败 .

```javascript
import { retry } from '@git-stunts/alfred';

// Basic retry
await retry(() => mightFail(), { retries: 3 });

// Exponential backoff: 100ms, 200ms, 400ms...
await retry(() => mightFail(), {
  retries: 5,
  backoff: 'exponential',
  delay: 100,
  maxDelay: 10_000,
});

// Only retry specific errors
await retry(() => mightFail(), {
  retries: 3,
  shouldRetry: (err) => err?.code === 'ECONNREFUSED',
});

// With jitter to prevent thundering herd
await retry(() => mightFail(), {
  retries: 3,
  backoff: 'exponential',
  delay: 100,
  jitter: 'full', // or "equal" or "decorrelated"
});

// Abort retries early
const controller = new AbortController();
const promise = retry((signal) => fetch('https://api.example.com/data', { signal }), {
  retries: 3,
  backoff: 'exponential',
  delay: 100,
  signal: controller.signal,
});
controller.abort();
```

### 选项

| 选项 | 类型 | 默认 | 说明 |
| --- | --- | --- | --- |
| `retries` | `number` | `3` | 最大重试尝试 |
| `delay` | `number` | `1000` | 基准延迟( 毫秒) |
| `maxDelay` | `number` | `30000` | 最大延迟上限( 毫秒) |
| `backoff` | `"constant" | "linear" | "exponential"` | `"constant"` | 后退战略 |
| `jitter` | `"none" | "full" | "equal" | "decorrelated"` | `"none"` | 慢跑战略 |
| `shouldRetry` | `(error) => boolean` | `() => true` | 过滤器可重试错误 |
| `onRetry` | `(error, attempt, delay) => void` | \- 说吧 | 每次重试时回电 |
| `signal` | `AbortSignal` | \- 说吧 | 中止复试和后退睡眠 |

* * *

## 电路Breaker( 选项)

当某项服务退化时,故障迅速,防止级联故障.

```javascript
import { circuitBreaker } from '@git-stunts/alfred';

const breaker = circuitBreaker({
  threshold: 5, // Open after 5 failures
  duration: 60_000, // Stay open for 60 seconds
  onOpen: () => console.log('Circuit opened!'),
  onClose: () => console.log('Circuit closed!'),
  onHalfOpen: () => console.log('Testing recovery...'),
});

try {
  await breaker.execute(() => callService());
} catch (err) {
  if (err?.name === 'CircuitOpenError') {
    console.log('Service is down, failing fast');
  }
}
```

### 选项

| 选项 | 类型 | 默认 | 说明 |
| --- | --- | --- | --- |
| `threshold` | `number` | 所需经费 | 打开前失败 |
| `duration` | `number` | 所需经费 | 开放时间(分钟) |
| `successThreshold` | `number` | `1` | 半开关成功 |
| `shouldTrip` | `(error) => boolean` | `() => true` | 哪些错误算作失败 |
| `onOpen` | `() => void` | \- 说吧 | 当电路打开时调用 |
| `onClose` | `() => void` | \- 说吧 | 当电路关闭时调用 |
| `onHalfOpen` | `() => void` | \- 说吧 | 输入半开时调用 |

* * *

## 散头( 选项)

限制同时处决的次数,防止资源枯竭.

```javascript
import { bulkhead } from '@git-stunts/alfred';

const limiter = bulkhead({
  limit: 10, // Max 10 concurrent executions
  queueLimit: 20, // Max 20 pending requests in queue
});

try {
  await limiter.execute(() => heavyOperation());
} catch (err) {
  if (err?.name === 'BulkheadRejectedError') {
    console.log('Too many concurrent requests, failing fast');
  }
}

console.log(`Load: ${limiter.stats.active} active`);
```

### 选项

| 选项 | 类型 | 默认 | 说明 |
| --- | --- | --- | --- |
| `limit` | `number` | 所需经费 | 最大限度同时处决 |
| `queueLimit` | `number` | `0` | 队列中的最大待决请求 |

* * *

## 比率限制( 选项)

用于吞吐量控制的托肯桶速率限制器. 与批发头(会限制同币)不同的是,速率限制控制请求每秒.

```javascript
import { rateLimit } from '@git-stunts/alfred';

const limiter = rateLimit({ rate: 100 }); // 100 req/sec
await limiter.execute(() => fetch('/api'));
```

### 装有弹壳能力

允许超过基准率的临时暴发:

```javascript
const limiter = rateLimit({ rate: 100, burst: 150 });
```

### 用队列

排队过多的请求而不是立即拒绝 :

```javascript
const limiter = rateLimit({ rate: 10, queueLimit: 50 });
```

### 政策流利 API

```javascript
const policy = Policy.rateLimit({ rate: 100 }).wrap(Policy.retry({ retries: 3 }));
```

### 选项

| 选项 | 类型 | 默认 | 说明 |
| --- | --- | --- | --- |
| `rate` | `number` | 所需经费 | 每秒最大请求数 |
| `burst` | `number` | `rate` | 流量最大桶容量 |
| `queueLimit` | `number` | `0` | 队列中的最大待决请求 |
| `clock` | `Clock` | \- 说吧 | 自定义测试时钟 |
| `telemetry` | `TelemetrySink` | \- 说吧 | 沉入可观察事件 |

### 处理错误

超过速率限制且没有队列空间时, a `RateLimitExceededError` 丢出 :

```javascript
import { rateLimit, RateLimitExceededError } from '@git-stunts/alfred';

const limiter = rateLimit({ rate: 10 });

try {
  await limiter.execute(() => fetch('/api'));
} catch (err) {
  if (err instanceof RateLimitExceededError) {
    console.log(`Rate limit exceeded: ${err.rate} req/sec`);
    console.log(`Retry after: ${err.retryAfter}ms`);
  }
}
```

| 错误 | 丢弃 何时 | 属性 |
| --- | --- | --- |
| `RateLimitExceededError` | 超过费率限制并排队 | `rate`, (中文(简体) ), `retryAfter` |

* * *

## 超时( ms, fn, 选项)

防止操作无限期挂起.

```javascript
import { timeout } from '@git-stunts/alfred';

// Simple timeout
const result = await timeout(5_000, () => slowOperation());

// With callback
const result2 = await timeout(5_000, () => slowOperation(), {
  onTimeout: (elapsed) => console.log(`Timed out after ${elapsed}ms`),
});
```

掷出 `TimeoutError` 如果操作超过时限.

* * *

## 套接字( 选项)

分相执行:如果主请求缓慢,则会产出平行"对接"请求,以竞速响应.

```javascript
import { hedge } from '@git-stunts/alfred';

const hedger = hedge({
  delay: 100, // Wait 100ms before spawning a hedge
  maxHedges: 2, // Spawn up to 2 additional requests
});

// If the first request takes > 100ms, a second request starts.
// If still slow after another 100ms, a third starts.
// First successful response wins; others are aborted.
const result = await hedger.execute((signal) => fetch('https://api.example.com/data', { signal }));
```

### 选项

| 选项 | 类型 | 默认 | 说明 |
| --- | --- | --- | --- |
| `delay` | `number` | 所需经费 | 等待一毫秒 才能产出树篱 |
| `maxHedges` | `number` | `1` | 孵化的套期请求最多 |

### 安全护栏

> **警告:** Hedging产生平行请求. 负责地使用来避免后端超载.

1.  **只有对冲一能操作.** 阅读、检查和获取请求是安全的。 写作,支付,和状态变异都不是——你最后可能会出现重复的副作用.
    
2.  **总是使用中止符号 .** 您的操作收到 `AbortSignal` 当一个更快的树篱取胜时 就会起火 荣誉取消飞行中的工作(牵引,数据库查询等).
    
3.  **与散头+断路器相接.** 防止自失能和连锁故障:
    

```javascript
import { Policy } from '@git-stunts/alfred';

// Safe hedging: bulkhead limits total concurrency, circuit breaker fails fast
const safeHedge = Policy.hedge({ delay: 100, maxHedges: 2 })
  .wrap(Policy.bulkhead({ limit: 10 }))
  .wrap(Policy.circuitBreaker({ threshold: 5, duration: 30_000 }));

await safeHedge.execute((signal) => fetch(url, { signal }));
```

4.  **设置合理的延迟.** 这个 `delay` 应基于您的 P50/P90 延迟。 太短=负荷过重. 太长=没有好处.

### 食谱:被套读 (只读操作)

用于套期数据库的可重用模式读取或缓存检查:

```javascript
import { Policy } from '@git-stunts/alfred';

function createHedgedReader(options = {}) {
  const { delay = 50, maxHedges = 1, concurrencyLimit = 5 } = options;

  return Policy.hedge({ delay, maxHedges }).wrap(Policy.bulkhead({ limit: concurrencyLimit }));
}

const hedgedRead = createHedgedReader({ delay: 50, maxHedges: 1 });

// Use for any read-only operation
const user = await hedgedRead.execute((signal) => db.users.findById(id, { signal }));
const cached = await hedgedRead.execute((signal) => cache.get(key, { signal }));
```

### 食谱:快乐眼球 (Parallel Endpoints)

竞速请求到多个终点(例如IPv4 vs IPv6,主对复制) :

```javascript
import { Policy } from '@git-stunts/alfred';

async function happyEyeballsFetch(urls, options = {}) {
  const { delay = 50 } = options;

  // Create a hedge policy that spawns one hedge per additional URL
  const racer = Policy.hedge({ delay, maxHedges: urls.length - 1 });

  let urlIndex = 0;
  return racer.execute((signal) => {
    const url = urls[urlIndex++ % urls.length];
    return fetch(url, { signal }).then((res) => {
      if (!res.ok) throw new Error(`HTTP ${res.status}`);
      return res;
    });
  });
}

// First successful response wins
const response = await happyEyeballsFetch([
  'https://api-primary.example.com/data',
  'https://api-replica.example.com/data',
]);
```

### 运行时间要求

套接字用途 `Promise.any()` 内部。 可在下列网址查阅:

-   节点.js >= 15.0.0
-   德诺 1.2
-   Bun QQ 1.0 (英语)
-   现代浏览器(Chrome 85+,Firefox 79+,Safari 14+)
-   云花岗工人

对于较老的运行时间,使用多填充方式 [核心 js 数据](https://github.com/zloirock/core-js#promiseany) 或者说 [答应。 任何](https://www.npmjs.com/package/promise.any)。 。 。 .

* * *

## 政策(流利的API)

在可连锁的政策类中,制定复杂的政策比较容易.

```javascript
import { Policy, ConsoleSink } from '@git-stunts/alfred';

const telemetry = new ConsoleSink();

const resilient = Policy.timeout(30_000)
  .wrap(Policy.retry({ retries: 3, backoff: 'exponential', telemetry }))
  .wrap(Policy.circuitBreaker({ threshold: 5, duration: 60_000, telemetry }))
  .wrap(Policy.bulkhead({ limit: 5, queueLimit: 10, telemetry }));

await resilient.execute(() => riskyOperation());
```

### 静态方法

| 方法 | 说明 |
| --- | --- |
| `Policy.retry(options)` | 创建重试策略 |
| `Policy.circuitBreaker(options)` | 创建断路器策略 |
| `Policy.timeout(ms, options)` | 创建超时策略 |
| `Policy.bulkhead(options)` | 创建批头政策 |
| `Policy.rateLimit(options)` | 创建费率限制政策 |
| `Policy.hedge(options)` | 创建套期政策 |
| `Policy.noop()` | 创建过关( 不通过) 政策 |

### 实例方法

| 方法 | 说明 |
| --- | --- |
| `.wrap(policy)` | 与其它政策相接( 相应组成) |
| `.or(policy)` | 如果失败, 回到另一个政策 |
| `.race(policy)` | 以此政策相对抗 |
| `.execute(fn)` | 执行政策链 |

```javascript
// Fallback example: try primary, fall back to cache on failure
const withFallback = Policy.retry({ retries: 2 }).or(Policy.noop()); // fallback policy

// Race example: use whichever responds first
const racing = Policy.timeout(1_000).race(Policy.timeout(2_000));
```

* * *

## 作曲(... 政策)

组合多个政策对象. 政策执行左 - > 右 (最外 - > 最内侧) .

政策对象必须具有 `.execute(fn)` 方法。 使用 `circuitBreaker()` 财务报告和审定财务报表 `bulkhead()` 直接,或使用 `Policy` 类别 `retry()` 财务报告和审定财务报表 `timeout()`。 。 。 .

```javascript
import { compose, circuitBreaker, bulkhead, Policy } from '@git-stunts/alfred';

const resilient = compose(
  Policy.timeout(30_000), // Total timeout
  Policy.retry({ retries: 3, backoff: 'exponential' }), // Retry failures
  circuitBreaker({ threshold: 5, duration: 60_000 }), // Fail fast if broken
  bulkhead({ limit: 5, queueLimit: 10 }) // Limit concurrency
);

await resilient.execute(() => riskyOperation());
```

* * *

## 回落( 小学、 中学)

执行主要政策;如果失败,执行次要政策.

```javascript
import { fallback, circuitBreaker, Policy } from '@git-stunts/alfred';

const withFallback = fallback(
  Policy.retry({ retries: 3 }),
  circuitBreaker({ threshold: 5, duration: 60_000 })
);

await withFallback.execute(() => riskyOperation());
```

* * *

## 种族(小学、中学)

两项政策同时执行;第一个成功者获胜.

```javascript
import { race, Policy } from '@git-stunts/alfred';

const racing = race(Policy.timeout(1_000), Policy.timeout(2_000));

// Whichever completes first wins
await racing.execute(() => fetchFromMultipleSources());
```

* * *

## 遥测和可观察性

阿尔弗雷德提供可堆肥的遥测汇来监测政策行为.

```javascript
import { Policy, ConsoleSink, InMemorySink, MultiSink } from '@git-stunts/alfred';

const sink = new MultiSink([new ConsoleSink(), new InMemorySink()]);

await Policy.retry({
  retries: 3,
  telemetry: sink,
}).execute(() => doSomething());
```

### 可用的辛克

| 沉没 | 说明 |
| --- | --- |
| `ConsoleSink` | 记录要显示的事件 |
| `InMemorySink` | 在数组中存储事件( 用于测试) |
| `MetricsSink` | 汇总度量衡(计数、纬度统计) |
| `MultiSink` | 对多个汇的广播 |
| `NoopSink` | 丢弃所有事件( 残疾遥测) |

### 度量衡

生产监测总指标.

```javascript
import { Policy, MetricsSink } from '@git-stunts/alfred';

const metrics = new MetricsSink();

const policy = Policy.retry({ retries: 3, telemetry: metrics }).wrap(
  Policy.circuitBreaker({ threshold: 5, duration: 60_000, telemetry: metrics })
);

await policy.execute(() => doSomething());

console.log(metrics.stats);
// {
//   retries: 2,
//   failures: 1,
//   successes: 1,
//   circuitBreaks: 0,
//   circuitRejections: 0,
//   bulkheadRejections: 0,
//   timeouts: 0,
//   hedges: 0,
//   latency: { count: 1, sum: 150, min: 150, max: 150, avg: 150 }
// }

metrics.clear(); // Reset all metrics
```

### 活动

所有政策都发出事件:

-   **重试**:成功,失败,计划,疲劳
-   **电路**:打开、关闭、半打开、成功、失败、拒绝
-   **散头**: 执行、 完成、 队列、 拒绝
-   **超时**: 超时
-   **套接字**:产卵,成功,失败

* * *

## 测试

使用 `TestClock` 毫无延误地进行决定性测试。 所有基于时间的政策`retry`, (中文(简体) ), `timeout`, (中文(简体) ), `hedge`支持时钟注射.

```javascript
import { retry, timeout, TestClock, TimeoutError } from '@git-stunts/alfred';

test('retries with exponential backoff', async () => {
  const clock = new TestClock();
  let attempts = 0;

  const operation = async () => {
    attempts++;
    if (attempts < 3) throw new Error('fail');
    return 'success';
  };

  const promise = retry(operation, {
    retries: 3,
    backoff: 'exponential',
    delay: 1_000,
    clock,
  });

  await clock.tick(0);
  expect(attempts).toBe(1);

  await clock.advance(1_000);
  expect(attempts).toBe(2);

  await clock.advance(2_000);
  expect(attempts).toBe(3);

  expect(await promise).toBe('success');
});

test('timeout triggers after virtual time', async () => {
  const clock = new TestClock();

  const slowOp = () => clock.sleep(10_000).then(() => 'done');
  const promise = timeout(5_000, slowOp, { clock });

  await clock.advance(5_000);

  await expect(promise).rejects.toThrow(TimeoutError);
});
```

* * *

## 错误类型

```javascript
import {
  RetryExhaustedError,
  CircuitOpenError,
  TimeoutError,
  BulkheadRejectedError,
  RateLimitExceededError,
} from '@git-stunts/alfred';

try {
  await resilientOperation();
} catch (err) {
  if (err instanceof RetryExhaustedError) {
    console.log(`Failed after ${err.attempts} attempts`);
    console.log(`Last error: ${err.cause.message}`);
  } else if (err instanceof CircuitOpenError) {
    console.log(`Circuit open since ${err.openedAt}`);
  } else if (err instanceof TimeoutError) {
    console.log(`Timed out after ${err.elapsed}ms`);
  } else if (err instanceof BulkheadRejectedError) {
    console.log(`Bulkhead full: ${err.limit} active, ${err.queueLimit} queued`);
  } else if (err instanceof RateLimitExceededError) {
    console.log(`Rate limited: ${err.rate} req/sec, retry after ${err.retryAfter}ms`);
  }
}
```

| 错误 | 丢弃 何时 | 属性 |
| --- | --- | --- |
| `RetryExhaustedError` | 所有重试尝试都失败 | `attempts`, (中文(简体) ), `cause` |
| `CircuitOpenError` | 断路器已打开 | `openedAt`, (中文(简体) ), `failureCount` |
| `TimeoutError` | 行动超过时限 | `timeout`, (中文(简体) ), `elapsed` |
| `BulkheadRejectedError` | 块头限制和队列已满 | `limit`, (中文(简体) ), `queueLimit` |
| `RateLimitExceededError` | 超过费率限制并排队 | `rate`, (中文(简体) ), `retryAfter` |

* * *

## 解析时间( 动态选项)

所有政策选项均可作为 **函数** 用于动态/活性可触动行为。 本表为文档 **何时** 解决了每个选项:

| 政策 | 选项 | 决议时间 | 说明 |
| --- | --- | --- | --- |
| **重试** | `retries` | 每一次尝试 | 每次失败后检查过 |
| **重试** | `delay` | 每一次尝试 | 每次回放睡眠前计算 |
| **重试** | `maxDelay` | 每一次尝试 | 计算延迟时应用 |
| **重试** | `backoff` | 每一次尝试 | 按延迟计算解决的战略 |
| **重试** | `jitter` | 每一次尝试 | 按延迟计算解决的焦特类型 |
| **散头** | `limit` | 每一次录取 | 请求试图执行时已检查 |
| **散头** | `queueLimit` | 每一次录取 | 请求尝试队列时已选中 |
| **电路断层** | `threshold` | 每个事件 | 检查了每次失败 |
| **电路断层** | `duration` | 每个事件 | 测试半开放过渡时检查过 |
| **电路断层** | `successThreshold` | 每个事件 | 在半开放状态下检查每个成功 |
| **超时** | `ms` | 每次执行 | 暂停时解决一次 |
| **套接字** | `delay` | 每次执行 | 执行开始时解决一次 |
| **套接字** | `maxHedges` | 每次执行 | 执行开始时解决一次 |

### 解析时间语义

-   **每次执行**: 选项在 `execute()` 名为. 执行过程中的变化没有效果.
-   **每一次尝试**:每次尝试/重试时都会解决选项。 允许中执行调试.
-   **每一次录取**:每次试图进入批发头的请求都会解决选项.
-   **每个事件**: 当相关事件(失败、成功、状态检查)发生时, 选项将得到解决.

### 示例:动态重试限制

```javascript
let maxRetries = 2;

// Pass a function to make it dynamic
await retry(operation, {
  retries: () => maxRetries, // Resolved per attempt
  delay: 100,
});

// In another part of your code, you can adjust:
maxRetries = 5; // Future failures will see the new limit
```

### 示例:动态散列头限制

```javascript
let concurrencyLimit = 10;

const bh = bulkhead({
  limit: () => concurrencyLimit, // Resolved per admission
  queueLimit: 20,
});

// Later, reduce concurrency (takes effect on next admission)
concurrencyLimit = 5;
```

* * *

## 许可证

阿帕奇-2.0 由詹姆斯·罗斯所著"2026"

由 [飞行场馆](https://github.com/flyingrobots)

## 常见问题

### @git-stunts/alfred 是什么？

生产级耐受性模式用于Aync ops:再试/后置\+慢跑,断路器,散头,超时\.

### 如何安装 @git-stunts/alfred？

在项目目录运行 npm install @git-stunts/alfred，或使用 pnpm add / yarn add / bun add。

### @git-stunts/alfred 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @git-stunts/alfred 支持 ESM 还是 CommonJS？

以 ES Module 形式发布，推荐使用 import 引入。在 CommonJS 项目中，Node\.js 20\.19\+ / 22\.12\+ 可以直接 require\(\) 不含顶层 await 的 ES Module，更早的版本需要改用动态 import\(\)。

### @git-stunts/alfred 需要什么版本的 Node\.js？

package\.json 的 engines 字段要求 Node\.js \>=20\.0\.0。版本不符时 npm 默认只给出警告，开启 engine-strict 后会拒绝安装。

### @git-stunts/alfred 可以商用吗？

@git-stunts/alfred 使用 Apache-2\.0 许可。宽松许可：允许商业使用、修改和再分发，并附带明确的专利授权；分发时需保留许可与 NOTICE 文件，修改过的文件要注明改动。以上为概括，不构成法律意见，请以许可原文为准。

### @git-stunts/alfred 的下载量有多少？

根据 npm 官方下载统计，@git-stunts/alfred 在 2026/10/17 – 2026/11/15 这 30 天内被下载 7,923 次，日均约 264 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @git-stunts/alfred 还在维护吗？

最新版本 0\.10\.4 发布于 2026/06/25（4 个月前）；至今共发布 15 个版本，其中过去 12 个月发布了 15 个；首次发布于 2026/02/01。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

