当前位置: 首页 > Skill >

Durable Workflow

Durable Workflow

1.0.1 2026.11.17 浏览:120
获取Skill文件查看使用说明
作者:叶言许可证:
本文目录展开

Durable Workflow Patterns

Build automations that survive API failures, timeouts, and unexpected state — without rebuilding from scratch every time something breaks.

Core Principle

Every step in a multi-step workflow must answer three questions:

  1. What did I finish? (checkpoint)
  2. What do I do if this step fails? (recovery)
  3. Who finds out if something goes wrong? (alerting)

Skip any of these and the workflow will eventually fail silently.

Scripts

Ready-to-use implementations in scripts/:

Script Purpose
workflow-template.js Complete workflow skeleton with checkpoints, retry, DLQ, exit handler
lock.js File-based process lock — prevents concurrent runs

workflow-template.js

Copy and fill in the step TODOs:

cp scripts/workflow-template.js my-workflow.js
node my-workflow.js           # Run (or re-run — resumes from last checkpoint)
WORKFLOW_STATE_PATH=/tmp/state.json node my-workflow.js   # Custom state path

Features: atomic state saves, exponential backoff, timeout wrapper, DLQ, abnormal-exit logging.

lock.js

Prevent two instances of the same workflow from running at once:

const { withLock, LockError } = require('./lock');

withLock('/tmp/my-workflow.lock', async () => {
  // Only one process runs this block at a time
  await runWorkflow();
}).catch(e => {
  if (e.name === 'LockError') {
    console.error('Already running:', e.message);
  } else {
    throw e;
  }
});

Pattern 1: Checkpoint State

Save progress after every meaningful step. Never trust in-memory state across network calls.

// checkpoint.js pattern
const state = loadState('workflow-id') || { step: 0, results: [] };

if (state.step < 1) {
  state.results.push(await fetchData());
  state.step = 1;
  saveState('workflow-id', state);
}
if (state.step < 2) {
  state.results.push(await processData(state.results[0]));
  state.step = 2;
  saveState('workflow-id', state);
}
// Restart from any step — already-done steps are skipped

Pattern 2: Circuit Breaker

Stop hammering a failing service. Open the circuit after N failures, half-open after a cooldown.

class CircuitBreaker {
  constructor(threshold = 3, cooldownMs = 30000) {
    this.failures = 0; this.threshold = threshold;
    this.state = 'closed'; this.nextRetry = 0;
  }
  async call(fn) {
    if (this.state === 'open') {
      if (Date.now() < this.nextRetry) throw new Error('Circuit open');
      this.state = 'half-open';
    }
    try {
      const result = await fn();
      this.failures = 0; this.state = 'closed';
      return result;
    } catch (e) {
      this.failures++;
      if (this.failures >= this.threshold) {
        this.state = 'open';
        this.nextRetry = Date.now() + this.cooldownMs;
      }
      throw e;
    }
  }
}

Pattern 3: Exponential Backoff with Jitter

async function withRetry(fn, maxAttempts = 4, baseDelayMs = 1000) {
  for (let attempt = 0; attempt < maxAttempts; attempt++) {
    try { return await fn(); }
    catch (e) {
      if (attempt === maxAttempts - 1) throw e;
      const delay = baseDelayMs * Math.pow(2, attempt) + Math.random() * 500;
      await new Promise(r => setTimeout(r, delay));
    }
  }
}

Pattern 4: Dead Letter Queue

When a step fails after all retries, don't silently drop it. Route it somewhere reviewable.

async function processWithDLQ(items, processFn, dlqPath) {
  const failed = [];
  for (const item of items) {
    try { await withRetry(() => processFn(item)); }
    catch (e) { failed.push({ item, error: e.message, failedAt: new Date() }); }
  }
  if (failed.length) {
    const existing = fs.existsSync(dlqPath) ? JSON.parse(fs.readFileSync(dlqPath)) : [];
    fs.writeFileSync(dlqPath, JSON.stringify([...existing, ...failed], null, 2));
  }
}

Pattern 5: Idempotent Operations

Design every step so running it twice produces the same result as running it once.

// BAD: running twice creates two records
await db.insert({ id: uuid(), data });

// GOOD: upsert on natural key
await db.upsert({ id: deterministicId(data), data }, { onConflict: 'update' });

Pattern 6: Instance Lock

Prevent duplicate runs (e.g. cron overlap, manual re-trigger while running).

const { withLock, LockError } = require('./scripts/lock');

const LOCK_PATH = '/tmp/my-workflow.lock';

async function main() {
  await withLock(LOCK_PATH, async () => {
    // Safe: only one instance reaches here at a time
    await runWorkflow();
  });
}

main().catch(e => {
  if (e.name === 'LockError') {
    // Not an error — just another instance running
    console.log(`Skipping: ${e.message}`);
    process.exit(0);
  }
  console.error('Fatal:', e.message);
  process.exit(1);
});

The lock uses PID detection — stale locks from crashed processes are automatically reclaimed.

Workflow Design Checklist

Before shipping any multi-step automation:

  • Each step saves state before moving to the next
  • External API calls wrapped in retry + backoff
  • Circuit breaker on services called more than once per run
  • Failed items go to a dead letter file/queue, not /dev/null
  • The workflow can restart from any step without duplicating completed work
  • Alerting fires when the workflow exits abnormally (not just on exception)
  • Timeouts set on all external calls (never await fetch() without a deadline)
  • Instance lock in place if triggered by cron or multiple callers

Alerting

Send a Telegram message on workflow failure so you know before you look. Uses only the https built-in.

Set env vars: ALERT_TELEGRAM_TOKEN and ALERT_CHAT_ID.

const https = require('https');

function sendTelegramAlert(message) {
  const token  = process.env.ALERT_TELEGRAM_TOKEN;
  const chatId = process.env.ALERT_CHAT_ID;
  if (!token || !chatId) return Promise.resolve(); // alerting not configured, skip silently

  const body = JSON.stringify({ chat_id: chatId, text: message, parse_mode: 'Markdown' });
  return new Promise((resolve) => {
    const req = https.request(
      {
        hostname: 'api.telegram.org',
        path: `/bot${token}/sendMessage`,
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(body) },
      },
      res => { res.resume(); res.on('end', resolve); }
    );
    req.on('error', () => resolve()); // don't let alert failure crash the workflow
    req.setTimeout(5000, () => { req.destroy(); resolve(); });
    req.write(body);
    req.end();
  });
}

// Usage — in your main() catch block:
main().catch(async e => {
  console.error('Fatal:', e.message);
  await sendTelegramAlert(`❌ *Workflow failed*n`${e.message}``);
  process.exit(1);
});

Common Failure Modes

See references/failure-taxonomy.md for a full catalog of agent workflow failures with diagnosis and fix patterns.

推荐文章

更多
PHP时间戳与日期字符串相互转换方法详解

本文介绍PHP中时间数值(Unix时间戳)与日期字符串之间的相互转换方法。通过strtotime和date函数,实现将当前时间、指定日期转换为时间戳,以及将时间戳格式化为可读的日期时间字符串,并提供相关在线计算工具推荐。

2025.11.30 1,034
PHP日期转时间戳时区偏差怎么解决

在 PHP 中将日期字符串转换为时间戳时,若未显式指定时区,默认使用脚本配置的 date.timezone 或系统时区。当服务器时区与业务逻辑预期(如 UTC )不一致时,会产生偏差。解决核心是确保输入字符串携带明确时区信息,或在转换前统一设置时区上下文。

2026.10.24 1,031
PHP跨域配置:怎么安全地允许指定域名而非使用通配符

在 PHP 中安全地允许指定域名跨域,核心是解析请求头中的 Origin ,验证其是否在白名单内,然后动态设置 Access-Control-Allow-Origin 响应头。不要使用通配符 * ,也不要硬编码单一域名。

2025.03.29 1,018
JavaScript中利用replace结合正则实现replaceAll效果

JavaScript原生仅支持replace()进行单次或全局替换,缺乏类似Java的replaceAll()便捷方法。本文总结四种在JS中实现全量替换的方案:使用带g标志的正则、带gm标志的正则、扩展String原型以及split后join。通过对比代码示例,展示各方法的实现细节与适用场景,帮助开发者根据需求选择最优解。

2025.04.29 1,017
OpenAI的Jalapeno芯片未落地,教你分辨300兆瓦算力消息

OpenAI计划在SB Energy租赁的数据中心部署约300兆瓦自研Jalapeno推理芯片,但目前双方仍处于洽谈阶段,交易细节与上线时间表均未公布。本文带你按报道原文核实项目所处阶段,厘清芯片发布、电力功率与实际推理算力的边界,并将融资意向与签约、开工、投运节点分开追踪,避免误将规划容量计入现有算力。

2026.12.02 1,013
PHP实现基础文件上传:HTML表单与$_FILES处理流程

在 HTML 表单中设置 enctype="multipart/form-data" ,并在 PHP 后端通过 $_FILES 数组接收文件,调用 move_uploaded_file() 将临时文件移动到目标目录即可完成上传。

2026.09.07 1,013
Skill 文件
  • SKILL.md
    • Durable Workflow Patterns
    • Core Principle
    • Scripts
      • workflow-template.js
      • lock.js
    • Pattern 1: Checkpoint State
    • Pattern 2: Circuit Breaker
    • Pattern 3: Exponential Backoff with Jitter
    • Pattern 4: Dead Letter Queue
    • Pattern 5: Idempotent Operations
    • Pattern 6: Instance Lock
    • Workflow Design Checklist
    • Alerting
    • Common Failure Modes
  • 项目或源文件

相关 Skill

更多
Workflow Router Workflow Router Orchestrate a personal end-to-end workflow from inspiration documents through brainstorming, PRD, spec, code generation, TDD regression, personal validation, feedback loops, spec updates, and archival. Use when the user wants to run or standardize a durable workflow that chains skills such as grill-me, grilling, notion-mrd-prd, decision-mapping, implement, tdd, review, diagnosing-bugs, to-prd, request-refactor-plan, and skillhub-publish.
service-qa-coach service-qa-coach Review support quality for chat, email, phone, social DM, or marketplace service teams. Use when a team needs a QA scorecard, failure-mode analysis, coaching plan, calibration checklist, or service-improvement brief without live ticketing, CRM, or contact-center system access.
高中数学作业批改助手 高中数学作业批改助手 >图片识别 直接读取学生手写作答照片,识别公式、符号、步骤 🧮 自动推导 根据题目自动生成参考答案和评分细则,无需教师预设 📊 逐步给分 每个关键步骤独立评分,体现过程分 📝 结构化报告 输出含识别内容、参考答案、逐步评分、改进建议的完整报告 🗂 批量批改 支持一次性批改多道题,最终汇总得分表
Vibration Analysis Vibration Analysis 分析来自CMS趋势、RMS/峰值、频谱及SCADA报警的风机传动链(主轴、齿轮箱、发电机)振动数据。
Traditional Bone Tool Making Basics Traditional Bone Tool Making Basics Use when you need custom, durable, repairable tools like awls, needles, scrapers, harpoons, or fishing hooks made from local animal bones or antlers and comm...