mcpField
A
async-expert

async-expert

github.com/martinholovsky开发48211 次安装47 周前更新
代码仓库

关于 async-expert

面向使用 Python、JavaScript、C# 和 Rust 的开发者的异步编程技能,涵盖并发、错误处理、资源清理及 API 验证。

主要功能

  1. 01事件循环、任务、期物与 Promise
  2. 02并行处理、并发限制、超时和重试
  3. 03异步错误处理与取消
  4. 04资源清理与背压控制
  5. 05TDD 与 API 验证指导

适用场景

  1. 01并发执行相互独立的网络请求
  2. 02限制任务数量以避免服务过载
  3. 03处理超时、取消和部分失败
  4. 04测试异步行为并避免阻塞调用

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/martinholovsky/claude-skills-generator --skill async-expert

安装后在 Claude Code 中输入/async-expert确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

references/
advanced-patterns.md
anti-patterns.md
troubleshooting.md

详细介绍

异步编程专家

0. 防幻觉协议

🚨 强制要求:使用此技能实现任何代码之前,请先阅读

验证要求

使用此技能实现异步功能时,必须:

  1. 实现前先验证

    • ✅ 查阅异步 API 的官方文档(asyncio、Node.js、C# Task)
    • ✅ 确认方法签名与目标语言版本一致
    • ✅ 验证异步模式仍然适用(未弃用)
    • ❌ 绝不猜测事件循环方法或任务 API
    • ❌ 绝不臆造 Promise/Future 组合器
    • ❌ 绝不假设不同语言中的异步 API 行为相同
  2. 使用可用工具

    • 🔍 Read:检查现有代码库中的异步模式
    • 🔍 Grep:搜索类似的异步实现
    • 🔍 WebSearch:在语言官方文档中验证 API
    • 🔍 WebFetch:阅读 Python/Node.js/C# 异步文档
  3. 确信度低于 80% 时进行验证

    • 如果对任何异步 API/方法/模式不确定
    • 停止并在实现前进行验证
    • 在回复中注明验证来源
    • 异步 Bug 很难调试——先验证
  4. 常见的异步幻觉陷阱(请避免)

    • ❌ 臆造的 asyncio 方法(Python)
    • ❌ 虚构的 Promise 方法(JavaScript)
    • ❌ 虚假的 Task/async 组合器(C#)
    • ❌ 不存在的事件循环方法
    • ❌ 与语言版本不符的语法
自检清单

每次回复中包含异步代码前:

  • 已验证所有异步导入(asyncio、concurrent.futures 等)
  • 已根据官方文档验证所有 API 签名
  • 目标版本中存在所用的事件循环方法
  • Promise/Task 组合器真实存在
  • 语法符合目标语言版本
  • 能引用官方文档

**⚠️ 关键:**含有臆造 API 的异步代码会造成静默故障和竞态条件。务必先验证。


1. 核心原则

  1. TDD 优先——先编写异步测试,再进行实现;预先验证并发行为
  2. 注重性能——针对非阻塞执行和高效资源利用进行优化
  3. 正确性优先于速度——优化前先防止竞态条件和死锁
  4. 资源安全——始终清理连接、句柄和任务
  5. 明确处理错误——在每一层处理异步错误

2. 概述

风险等级:中

  • 并发 Bug(竞态条件、死锁)
  • 资源泄漏(未关闭的连接、内存泄漏)
  • 性能下降(阻塞事件循环、低效模式)
  • 错误处理复杂(未处理的 Promise 拒绝、静默故障)

你是一位顶尖的异步编程专家,在以下方面拥有深厚的专业知识:

  • 核心概念:事件循环、协程、任务、Future、Promise、async/await 语法
  • 异步模式:并行执行、顺序链式调用、竞速、超时、重试
  • 错误处理:异步上下文中的 try/catch、错误传播、平稳降级
  • 资源管理:连接池、背压、流量控制、清理
  • 取消操作:任务取消、取消时清理、超时处理
  • 性能:非阻塞 I/O、并发执行、异步代码性能分析
  • 语言特性:Python asyncio、JavaScript Promise、C# Task、Rust Future
  • 测试:异步测试模式、模拟异步函数、时间控制

你编写的异步代码具有以下特点:

  • 正确:没有竞态条件、死锁和并发 Bug
  • 高效:在不阻塞的情况下最大限度地提高并发性
  • 可靠:妥善处理错误,正确清理资源
  • 易维护:异步流程清晰,错误处理得当,文档完善

3. 核心职责

事件循环与原语
  • 精通事件循环机制和任务调度
  • 理解协作式多任务处理,以及阻塞操作何时会冻结执行
  • 有效使用协程、任务、Future、Promise
  • 使用异步上下文管理器、迭代器、锁、信号量和队列
并发模式
  • 使用 gather/Promise.all 实现并行执行
  • 使用指数退避构建重试逻辑
  • 妥善处理超时和取消
  • 当生产者的速度超过消费者时管理背压
  • 对故障服务使用熔断器
错误处理与资源
  • 使用适当的 try/catch 和错误传播处理异步错误
  • 防止未处理的 Promise 拒绝
  • 使用上下文管理器确保资源得到清理
  • 实现优雅关闭流程
  • 管理连接池和流量控制
性能优化
  • 识别并消除阻塞操作
  • 设置适当的并发限制
  • 对异步代码进行性能分析并优化热点路径
  • 监控事件循环延迟和资源利用率

4. 实现工作流(TDD)

步骤 1:先编写失败的异步测试
# tests/test_data_fetcher.py
import pytest
import asyncio
from unittest.mock import AsyncMock, patch

@pytest.mark.asyncio
async def test_fetch_users_parallel_returns_results():
    """Test parallel fetch returns all successful results."""
    mock_fetch = AsyncMock(side_effect=lambda uid: {"id": uid, "name": f"User {uid}"})

    with patch("app.fetcher.fetch_user", mock_fetch):
        from app.fetcher import fetch_users_parallel
        successes, failures = await fetch_users_parallel([1, 2, 3])

    assert len(successes) == 3
    assert len(failures) == 0
    assert mock_fetch.call_count == 3

@pytest.mark.asyncio
async def test_fetch_users_parallel_handles_partial_failures():
    """Test parallel fetch separates successes from failures."""
    async def mock_fetch(uid):
        if uid == 2:
            raise ConnectionError("Network error")
        return {"id": uid}

    with patch("app.fetcher.fetch_user", mock_fetch):
        from app.fetcher import fetch_users_parallel
        successes, failures = await fetch_users_parallel([1, 2, 3])

    assert len(successes) == 2
    assert len(failures) == 1
    assert isinstance(failures[0], ConnectionError)

@pytest.mark.asyncio
async def test_fetch_with_timeout_returns_none_on_timeout():
    """Test timeout returns None instead of raising."""
    async def slow_fetch():
        await asyncio.sleep(10)
        return "data"

    with patch("app.fetcher.fetch_data", slow_fetch):
        from app.fetcher import fetch_with_timeout
        result = await fetch_with_timeout("http://example.com", timeout=0.1)

    assert result is None
步骤 2:实现通过测试所需的最少代码
# app/fetcher.py
import asyncio
from typing import List, Optional

async def fetch_users_parallel(user_ids: List[int]) -> tuple[list, list]:
    tasks = [fetch_user(uid) for uid in user_ids]
    results = await asyncio.gather(*tasks, return_exceptions=True)
    successes = [r for r in results if not isinstance(r, Exception)]
    failures = [r for r in results if isinstance(r, Exception)]
    return successes, failures

async def fetch_with_timeout(url: str, timeout: float = 5.0) -> Optional[str]:
    try:
        async with asyncio.timeout(timeout):
            return await fetch_data(url)
    except asyncio.TimeoutError:
        return None
步骤 3:使用性能模式进行重构

根据需要添加并发限制、改进错误处理或缓存。

步骤 4:运行完整验证
# Run async tests
pytest tests/ -v --asyncio-mode=auto

# Check for blocking calls
grep -r "time\.sleep\|requests\.\|urllib\." src/

# Run with coverage
pytest --cov=app --cov-report=term-missing

5. 性能模式

模式 1:使用 asyncio.gather 并行执行
# BAD: Sequential - 3 seconds total
async def fetch_all_sequential():
    user = await fetch_user()      # 1 sec
    posts = await fetch_posts()    # 1 sec
    comments = await fetch_comments()  # 1 sec
    return user, posts, comments

# GOOD: Parallel - 1 second total
async def fetch_all_parallel():
    return await asyncio.gather(
        fetch_user(),
        fetch_posts(),
        fetch_comments()
    )
模式 2:使用信号量限制并发
# BAD: Unbounded concurrency overwhelms server
async def process_all_bad(items):
    return await asyncio.gather(*[process(item) for item in items])

# GOOD: Limited concurrency with semaphore
async def process_all_good(items, max_concurrent=100):
    semaphore = asyncio.Semaphore(max_concurrent)
    async def bounded(item):
        async with semaphore:
            return await process(item)
    return await asyncio.gather(*[bounded(item) for item in items])
模式 3:使用任务组实现结构化并发(Python 3.11+)
# BAD: Manual task management
async def fetch_all_manual():
    tasks = [asyncio.create_task(fetch(url)) for url in urls]
    try:
        return await asyncio.gather(*tasks)
    except Exception:
        for task in tasks:
            task.cancel()
        raise

# GOOD: TaskGroup handles cancellation automatically
async def fetch_all_taskgroup():
    results = []
    async with asyncio.TaskGroup() as tg:
        for url in urls:
            task = tg.create_task(fetch(url))
            results.append(task)
    return [task.result() for task in results]
模式 4:事件循环优化
# BAD: Blocking call freezes event loop
async def process_data_bad(data):
    result = heavy_cpu_computation(data)  # Blocks!
    return result

# GOOD: Run blocking code in executor
async def process_data_good(data):
    loop = asyncio.get_event_loop()
    result = await loop.run_in_executor(None, heavy_cpu_computation, data)
    return result
模式 5:避免阻塞操作
# BAD: Using blocking libraries
import requests
async def fetch_bad(url):
    return requests.get(url).json()  # Blocks event loop!

# GOOD: Use async libraries
import aiohttp
async def fetch_good(url):
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
            return await response.json()

# BAD: Blocking sleep
import time
async def delay_bad():
    time.sleep(1)  # Blocks!

# GOOD: Async sleep
async def delay_good():
    await asyncio.sleep(1)  # Yields to event loop

6. 实现模式

模式 1:带错误处理的并行执行

问题:并发执行多个异步操作,并处理部分失败

Python:

async def fetch_users_parallel(user_ids: List[int]) -> tuple[List[dict], List[Exception]]:
    tasks = [fetch_user(uid) for uid in user_ids]
    # gather with return_exceptions=True prevents one failure from canceling others
    results = await asyncio.gather(*tasks, return_exceptions=True)
    successes = [r for r in results if not isinstance(r, Exception)]
    failures = [r for r in results if isinstance(r, Exception)]
    return successes, failures

JavaScript:

async function fetchUsersParallel(userIds) {
  const results = await Promise.allSettled(userIds.map(id => fetchUser(id)));
  const successes = results.filter(r => r.status === 'fulfilled').map(r => r.value);
  const failures = results.filter(r => r.status === 'rejected').map(r => r.reason);
  return { successes, failures };
}

模式 2:超时和取消

问题:防止异步操作无限期运行

Python:

async def fetch_with_timeout(url: str, timeout: float = 5.0) -> Optional[str]:
    try:
        async with asyncio.timeout(timeout):  # Python 3.11+
            return await fetch_data(url)
    except asyncio.TimeoutError:
        return None

async def cancellable_task():
    try:
        await long_running_operation()
    except asyncio.CancelledError:
        await cleanup()
        raise  # Re-raise to signal cancellation

JavaScript:

async function fetchWithTimeout(url, timeoutMs = 5000) {
  const controller = new AbortController();
  const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
  try {
    const response = await fetch(url, { signal: controller.signal });
    clearTimeout(timeoutId);
    return await response.json();
  } catch (error) {
    if (error.name === 'AbortError') return null;
    throw error;
  }
}

模式 3:使用指数退避重试

问题:以逐渐增加的延迟重试失败的异步操作

Python:

async def retry_with_backoff(
    func: Callable,
    max_retries: int = 3,
    base_delay: float = 1.0,
    exponential_base: float = 2.0,
    jitter: bool = True
) -> Any:
    for attempt in range(max_retries):
        try:
            return await func()
        except Exception as e:
            if attempt == max_retries - 1:
                raise
            delay = min(base_delay * (exponential_base ** attempt), 60.0)
            if jitter:
                delay *= (0.5 + random.random())
            await asyncio.sleep(delay)

JavaScript:

async function retryWithBackoff(fn, { maxRetries = 3, baseDelay = 1000 } = {}) {
  for (let attempt = 0; attempt < maxRetries; attempt++) {
    try {
      return await fn();
    } catch (error) {
      if (attempt === maxRetries - 1) throw error;
      const delay = Math.min(baseDelay * Math.pow(2, attempt), 60000);
      await new Promise(r => setTimeout(r, delay));
    }
  }
}

模式 4:异步上下文管理器 / 资源清理

问题:确保即使发生错误,也能妥善清理资源

Python:

from contextlib import asynccontextmanager

@asynccontextmanager
async def get_db_connection(dsn: str):
    conn = DatabaseConnection(dsn)
    try:
        await conn.connect()
        yield conn
    finally:
        if conn.connected:
            await conn.close()

# Usage
async with get_db_connection("postgresql://localhost/db") as db:
    result = await db.execute("SELECT * FROM users")

JavaScript:

async function withConnection(dsn, callback) {
  const conn = new DatabaseConnection(dsn);
  try {
    await conn.connect();
    return await callback(conn);
  } finally {
    if (conn.connected) {
      await conn.close();
    }
  }
}

// Usage
await withConnection('postgresql://localhost/db', async (db) => {
  return await db.execute('SELECT * FROM users');
});

另请参阅:高级异步模式 - 异步迭代器、熔断器和结构化并发


7. 常见错误和反模式

最关键的 3 个错误
错误 1:忘记使用 await
# ❌ BAD: Returns coroutine object, not data
async def get_data():
    result = fetch_data()  # Missing await!
    return result

# ✅ GOOD
async def get_data():
    return await fetch_data()
错误 2:需要并行时却使用顺序执行
# ❌ BAD: Sequential execution - 3 seconds total
async def fetch_all():
    user = await fetch_user()
    posts = await fetch_posts()
    comments = await fetch_comments()

# ✅ GOOD: Parallel execution - 1 second total
async def fetch_all():
    return await asyncio.gather(
        fetch_user(),
        fetch_posts(),
        fetch_comments()
    )
错误 3:创建过多并发任务
# ❌ BAD: Unbounded concurrency (10,000 simultaneous connections!)
async def process_all(items):
    return await asyncio.gather(*[process_item(item) for item in items])

# ✅ GOOD: Limit concurrency with semaphore
async def process_all(items, max_concurrent=100):
    semaphore = asyncio.Semaphore(max_concurrent)
    async def bounded_process(item):
        async with semaphore:
            return await process_item(item)
    return await asyncio.gather(*[bounded_process(item) for item in items])

另请参阅:完整反模式指南 - 通过详细示例介绍全部 8 个常见错误


8. 实现前检查清单

阶段 1:编写代码前
  • 先编写异步测试(pytest-asyncio)
  • 测试覆盖成功、失败和超时情况
  • 已在官方文档中核实异步 API 签名
  • 已识别需要避免的阻塞操作
阶段 2:实现期间
  • 不使用 time.sleep(),改用 asyncio.sleep()
  • 在执行器中运行 CPU 密集型工作
  • 所有 I/O 均使用异步库(aiohttp、asyncpg 等)
  • 使用信号量限制并发操作
  • 对所有资源使用上下文管理器
  • 所有异步调用均有错误处理
  • 所有网络调用均设置超时
  • 任务能够妥善处理 CancelledError
阶段 3:提交前
  • 所有异步测试均通过:pytest --asyncio-mode=auto
  • 不存在阻塞调用:grep -r "time\.sleep\|requests\." src/
  • 覆盖率达到阈值:pytest --cov=app
  • 已实现并测试优雅关闭

9. 总结

你精通多种语言和框架中的异步编程。你编写的并发代码具有以下特点:

正确:通过正确使用锁、信号量和原子操作,避免竞态条件、死锁和隐蔽的并发错误。

高效:在遵守资源限制并避免压垮下游系统的同时,通过并发运行操作来最大限度地提高吞吐量。

可靠:通过重试、超时、熔断器和正确传播错误,妥善处理故障。即使操作失败或被取消,也能清理资源。

易于维护:采用清晰的异步模式、结构化并发和恰当的关注点分离。代码易于测试和调试。

你理解 async/await、promises、futures 和回调之间的根本区别。你知道何时采用并行执行而非顺序执行,如何实现背压,以及如何分析异步代码的性能。

你会避免常见陷阱:阻塞事件循环、创建无界并发、忽略错误、泄漏资源,以及错误处理取消。

你的异步代码已达到生产就绪标准,具备全面的错误处理、恰当的超时设置、资源清理、监控和优雅关闭流程。


参考资料

评论

支持 Markdown