@git-stunts/alfred

中文文档
0.10.4发布于 2026/06/25Apache-2.0TypeScriptES Module零依赖构建来源已验证近 30 天下载 7923

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

中文使用文档
文档目录51 节
  1. 安装
  2. 无
  3. JSR (德诺、 Bun、 节点)
  4. 路线图
  5. 直播控制计划
  6. 20秒赢
  7. 多跑期支助
  8. 浏览器 Demo
  9. 快速启动( 功能助手)
  10. 政策代数
  11. 例1:生产堆栈(超时出局+重试+电路+批头)
  12. 例2:快速倒计时
  13. 例3:套接字请求(雷克模式)
  14. 流利对函数
  15. API 密码
  16. 重试( fn, 选项)
  17. 选项
  18. 电路Breaker( 选项)
  19. 选项
  20. 散头( 选项)
  21. 选项
  22. 比率限制( 选项)
  23. 装有弹壳能力
  24. 用队列
  25. 政策流利 API
  26. 选项
  27. 处理错误
  28. 超时( ms, fn, 选项)
  29. 套接字( 选项)
  30. 选项
  31. 安全护栏
  32. 食谱:被套读 (只读操作)
  33. 食谱:快乐眼球 (Parallel Endpoints)
  34. 运行时间要求
  35. 政策(流利的API)
  36. 静态方法
  37. 实例方法
  38. 作曲(... 政策)
  39. 回落( 小学、 中学)
  40. 种族(小学、中学)
  41. 遥测和可观察性
  42. 可用的辛克
  43. 度量衡
  44. 活动
  45. 测试
  46. 错误类型
  47. 解析时间( 动态选项)
  48. 解析时间语义
  49. 示例:动态重试限制
  50. 示例:动态散列头限制
  51. 许可证

@git-stunts/ alfred (英语)

JSR NPM Version CI

      .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' })""("史记")

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

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


安装

无

npm install @git-stunts/alfred

JSR (德诺、 Bun、 节点)

npx jsr add @git-stunts/alfred

路线图

见生态系统路线图 ROADMAP.md 地图。 。 。 .

直播控制计划

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


20秒赢

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

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” , 查看恢复力政策在行动中:

npm run demo:web:install && npm run demo:web

或者运行 Playwright 浏览器测试 :

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

快速启动( 功能助手)

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:生产堆栈(超时出局+重试+电路+批头)

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

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:快速倒计时

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

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:套接字请求(雷克模式)

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

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 }));

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

流利对函数

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

// 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, 选项)

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

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();

选项

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

电路Breaker( 选项)

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

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');
  }
}

选项

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

散头( 选项)

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

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`);

选项

选项类型默认说明
limitnumber所需经费最大限度同时处决
queueLimitnumber0队列中的最大待决请求

比率限制( 选项)

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

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

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

装有弹壳能力

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

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

用队列

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

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

政策流利 API

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

选项

选项类型默认说明
ratenumber所需经费每秒最大请求数
burstnumberrate流量最大桶容量
queueLimitnumber0队列中的最大待决请求
clockClock- 说吧自定义测试时钟
telemetryTelemetrySink- 说吧沉入可观察事件

处理错误

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

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, 选项)

防止操作无限期挂起.

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 如果操作超过时限.


套接字( 选项)

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

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 }));

选项

选项类型默认说明
delaynumber所需经费等待一毫秒 才能产出树篱
maxHedgesnumber1孵化的套期请求最多

安全护栏

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

  1. 只有对冲一能操作. 阅读、检查和获取请求是安全的。 写作,支付,和状态变异都不是——你最后可能会出现重复的副作用.

  2. 总是使用中止符号 . 您的操作收到 AbortSignal 当一个更快的树篱取胜时 就会起火 荣誉取消飞行中的工作(牵引,数据库查询等).

  3. 与散头+断路器相接. 防止自失能和连锁故障:

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 }));
  1. 设置合理的延迟. 这个 delay 应基于您的 P50/P90 延迟。 太短=负荷过重. 太长=没有好处.

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

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

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,主对复制) :

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 数据 或者说 答应。 任何。 。 。 .


政策(流利的API)

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

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)执行政策链
// 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()。 。 。 .

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());

回落( 小学、 中学)

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

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());

种族(小学、中学)

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

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());

遥测和可观察性

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

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丢弃所有事件( 残疾遥测)

度量衡

生产监测总指标.

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支持时钟注射.

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);
});

错误类型

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

示例:动态重试限制

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

示例:动态散列头限制

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"

由 飞行场馆

版本与发布记录

@git-stunts/alfred 共发布 15 个版本,首次发布于 2026/02/01;过去 12 个月发布了 15 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.10.4latest2026/06/254 个月前
0.10.32026/02/099 个月前
0.10.02026/02/049 个月前
0.9.12026/02/049 个月前
0.8.22026/02/049 个月前
0.8.12026/02/049 个月前

关于 @git-stunts/alfred 的常见问题

@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 和提交记录判断。