AsyncAPI文档生成器Skill asyncapi-docs

AsyncAPI文档生成器是一款专门用于事件驱动API文档自动化的工具。它能够解析和验证AsyncAPI规范,为Kafka、MQTT、WebSocket、AMQP等消息系统生成专业文档,支持代码生成和规范检查。关键词:AsyncAPI文档生成、事件驱动API、消息队列文档、Kafka文档、API规范验证、微服务文档、代码生成工具、Spectral代码检查、API文档自动化、实时系统文档。

后端开发 0 次安装 0 次浏览 更新于 2/26/2026

name: asyncapi-docs description: 用于事件驱动API文档的AsyncAPI规范处理。解析、验证并为基于消息的API(包括Kafka、MQTT、WebSocket和AMQP系统)生成文档。 allowed-tools: Read, Write, Edit, Bash, Glob, Grep backlog-id: SK-016 metadata: author: babysitter-sdk version: “1.0.0”

AsyncAPI 文档技能

使用AsyncAPI规范为事件驱动API生成和验证文档,支持多种消息传递协议。

能力

  • 解析和验证AsyncAPI 2.x和3.x规范
  • 从AsyncAPI规范生成文档
  • 记录事件/消息模式
  • 通道和操作文档
  • 协议特定绑定文档(Kafka、MQTT、WebSocket、AMQP)
  • 代码生成器集成
  • AsyncAPI的Spectral代码检查
  • 模式验证和类型生成

使用场景

在以下情况下调用此技能:

  • 为事件驱动微服务编写文档
  • 创建消息代理API文档
  • 从异步规范生成客户端代码
  • 验证AsyncAPI规范
  • 创建交互式文档站点

输入参数

参数 类型 必填 描述
specPath string AsyncAPI规范文件路径
outputDir string 文档输出目录
generator string html, markdown, react (默认: html)
validate boolean 运行规范验证 (默认: true)
lint boolean 运行Spectral代码检查 (默认: true)
generateCode boolean 生成客户端/服务器存根
codeLanguage string 代码生成目标语言

输入示例

{
  "specPath": "./asyncapi.yaml",
  "outputDir": "docs/async",
  "generator": "html",
  "validate": true,
  "lint": true,
  "generateCode": true,
  "codeLanguage": "typescript"
}

输出结构

docs/async/
├── index.html              # 主文档页面
├── servers.html            # 服务器/代理文档
├── channels/
│   ├── user-events.html    # 通道文档
│   └── order-events.html
├── messages/
│   ├── UserCreated.html    # 消息文档
│   └── OrderPlaced.html
├── schemas/
│   ├── User.html           # 模式文档
│   └── Order.html
├── bindings/               # 协议绑定
│   └── kafka.html
├── search.json             # 搜索索引
└── asyncapi.json           # 打包后的规范

AsyncAPI 规范模式

基本AsyncAPI 3.0文档

asyncapi: 3.0.0
info:
  title: 用户事件API
  version: 1.0.0
  description: |
    用于用户管理操作的事件驱动API。

    ## 概述
    此API在用户数据更改时发布事件。
    消费者可以订阅特定通道以接收实时更新。

    ## 认证
    所有连接都需要在连接头中传递有效的API密钥。
  contact:
    name: API团队
    email: api-team@example.com
  license:
    name: Apache 2.0
    url: https://www.apache.org/licenses/LICENSE-2.0

servers:
  production:
    host: kafka.example.com:9092
    protocol: kafka
    description: 生产环境Kafka集群
    security:
      - $ref: '#/components/securitySchemes/sasl'
    tags:
      - name: production
        description: 生产环境

  staging:
    host: kafka-staging.example.com:9092
    protocol: kafka
    description: 测试环境

channels:
  userCreated:
    address: user.events.created
    messages:
      UserCreatedMessage:
        $ref: '#/components/messages/UserCreated'
    description: |
      当新用户账户创建时发布。

      **触发条件**: 用户注册完成
      **频率**: ~1000事件/天

  userUpdated:
    address: user.events.updated
    messages:
      UserUpdatedMessage:
        $ref: '#/components/messages/UserUpdated'

operations:
  publishUserCreated:
    action: send
    channel:
      $ref: '#/channels/userCreated'
    summary: 发布用户创建事件
    description: |
      当新用户创建时发布事件。
      事件按用户ID分区。
    tags:
      - name: users
    bindings:
      kafka:
        groupId: user-service
        clientId: user-publisher

  subscribeUserCreated:
    action: receive
    channel:
      $ref: '#/channels/userCreated'
    summary: 订阅用户创建事件
    description: |
      订阅以在新用户创建时接收通知。适用于:
      - 欢迎邮件服务
      - 分析跟踪
      - 审计日志

components:
  messages:
    UserCreated:
      name: UserCreated
      title: 用户创建事件
      summary: 用户创建时发布的事件
      contentType: application/json
      traits:
        - $ref: '#/components/messageTraits/commonHeaders'
      payload:
        $ref: '#/components/schemas/UserCreatedPayload'
      examples:
        - name: NewUser
          summary: 标准用户创建
          payload:
            userId: "usr_123456"
            email: "john@example.com"
            createdAt: "2026-01-24T10:30:00Z"
            source: "web-signup"

    UserUpdated:
      name: UserUpdated
      title: 用户更新事件
      summary: 用户数据更改时发布的事件
      contentType: application/json
      payload:
        $ref: '#/components/schemas/UserUpdatedPayload'

  schemas:
    UserCreatedPayload:
      type: object
      description: 用户创建事件的有效负载
      required:
        - userId
        - email
        - createdAt
      properties:
        userId:
          type: string
          description: 唯一用户标识符
          pattern: "^usr_[a-zA-Z0-9]+$"
          examples:
            - "usr_123456"
        email:
          type: string
          format: email
          description: 用户邮箱地址
        createdAt:
          type: string
          format: date-time
          description: 用户创建时间戳
        source:
          type: string
          enum:
            - web-signup
            - mobile-app
            - admin-portal
            - api
          description: 注册来源

    UserUpdatedPayload:
      type: object
      required:
        - userId
        - updatedAt
        - changes
      properties:
        userId:
          type: string
          description: 唯一用户标识符
        updatedAt:
          type: string
          format: date-time
        changes:
          type: array
          items:
            type: object
            properties:
              field:
                type: string
              oldValue:
                type: string
              newValue:
                type: string

  messageTraits:
    commonHeaders:
      headers:
        type: object
        properties:
          correlationId:
            type: string
            description: 用于分布式追踪的关联ID
            format: uuid
          timestamp:
            type: string
            format: date-time
            description: 事件时间戳
          version:
            type: string
            description: 模式版本

  securitySchemes:
    sasl:
      type: scramSha256
      description: SASL/SCRAM-SHA-256认证

Kafka特定绑定

channels:
  orderEvents:
    address: orders.events
    bindings:
      kafka:
        topic: orders.events.v1
        partitions: 12
        replicas: 3
        topicConfiguration:
          cleanup.policy:
            - delete
          retention.ms: 604800000  # 7天
          segment.bytes: 1073741824
    messages:
      OrderCreated:
        bindings:
          kafka:
            key:
              type: string
              description: 用作分区键的订单ID
            schemaIdLocation: header
            schemaIdPayloadEncoding: confluent

WebSocket通道

asyncapi: 3.0.0
info:
  title: 实时通知API
  version: 1.0.0

servers:
  production:
    host: ws.example.com
    protocol: wss
    description: 用于实时通知的WebSocket服务器

channels:
  notifications:
    address: /notifications/{userId}
    parameters:
      userId:
        description: 接收通知的用户ID
    messages:
      Notification:
        $ref: '#/components/messages/Notification'
    bindings:
      ws:
        query:
          type: object
          properties:
            token:
              type: string
              description: 认证令牌
          required:
            - token

MQTT通道

asyncapi: 3.0.0
info:
  title: IoT传感器API
  version: 1.0.0

servers:
  production:
    host: mqtt.example.com:8883
    protocol: mqtts
    description: 用于IoT设备的MQTT代理

channels:
  sensorReadings:
    address: sensors/{sensorId}/readings
    parameters:
      sensorId:
        description: 唯一传感器标识符
    messages:
      SensorReading:
        $ref: '#/components/messages/SensorReading'
    bindings:
      mqtt:
        qos: 1
        retain: false
        bindingVersion: '0.2.0'

AsyncAPI CLI命令

验证

# 验证规范
asyncapi validate asyncapi.yaml

# 使用自定义规则验证
asyncapi validate asyncapi.yaml --rule-file .spectral.yaml

文档生成

# 生成HTML文档
asyncapi generate fromTemplate asyncapi.yaml @asyncapi/html-template -o docs

# 生成Markdown
asyncapi generate fromTemplate asyncapi.yaml @asyncapi/markdown-template -o docs

# 生成React应用
asyncapi generate fromTemplate asyncapi.yaml @asyncapi/react-component -o docs

代码生成

# TypeScript类型
asyncapi generate models asyncapi.yaml typescript -o src/types

# Java模型
asyncapi generate models asyncapi.yaml java -o src/main/java

# Python模型
asyncapi generate models asyncapi.yaml python -o src/models

Spectral代码检查规则

.spectral.yaml

extends:
  - "@asyncapi/spectral-ruleset"

rules:
  # 要求描述
  asyncapi-info-description: error
  asyncapi-channel-description: warn
  asyncapi-operation-description: warn

  # 要求示例
  asyncapi-message-examples: warn

  # 模式验证
  asyncapi-payload-unsupported-schemaFormat: error
  asyncapi-schema: error

  # 自定义规则
  operation-summary-required:
    description: 操作必须包含摘要
    given: "$.operations[*]"
    then:
      field: summary
      function: truthy
    severity: warn

  message-content-type:
    description: 消息必须指定内容类型
    given: "$.components.messages[*]"
    then:
      field: contentType
      function: truthy
    severity: error

文档最佳实践

通道文档

channels:
  paymentCompleted:
    address: payments.completed.v1
    description: |
      ## 支付完成事件

      当支付成功处理时发布。

      ### 使用场景
      - 订单履行启动
      - 客户通知
      - 财务对账

      ### 消费者指南
      - 幂等处理事件(使用`paymentId`进行去重)
      - 30秒内确认
      - 实现死信队列处理

      ### SLA
      - **延迟**: 支付完成后1秒内发布事件
      - **顺序**: 事件在分区内按`paymentId`排序
      - **保留期**: 7天

模式文档

components:
  schemas:
    Payment:
      type: object
      title: 支付
      description: |
        表示完成的支付交易。

        ## 版本控制
        此模式遵循语义版本控制。重大更改将导致新的主版本。

        ## 隐私
        包含PII - 根据数据保护政策处理。
      required:
        - paymentId
        - amount
        - currency
      properties:
        paymentId:
          type: string
          format: uuid
          description: 唯一支付标识符
          x-field-extra-annotation: "@Id"
        amount:
          type: number
          format: decimal
          description: 以最小单位(分)表示的支付金额
          minimum: 0
          examples:
            - 1999
            - 50000
        currency:
          type: string
          pattern: "^[A-Z]{3}$"
          description: ISO 4217货币代码
          examples:
            - USD
            - EUR
            - GBP

工作流程

  1. 解析规范 - 加载并验证AsyncAPI文档
  2. 检查规范 - 运行Spectral规则
  3. 验证模式 - 检查JSON Schema有效性
  4. 生成文档 - 创建HTML/Markdown输出
  5. 生成代码 - 创建类型化模型(可选)
  6. 打包规范 - 创建打包输出文件

依赖项

{
  "devDependencies": {
    "@asyncapi/cli": "^1.0.0",
    "@asyncapi/html-template": "^2.0.0",
    "@asyncapi/markdown-template": "^1.0.0",
    "@asyncapi/generator": "^1.0.0",
    "@asyncapi/modelina": "^3.0.0",
    "@stoplight/spectral-cli": "^6.0.0",
    "@asyncapi/spectral-ruleset": "^1.0.0"
  }
}

应用的最佳实践

  • 在规范信息中使用语义版本控制
  • 用描述记录所有通道
  • 包含消息示例
  • 为消息指定内容类型
  • 使用特征表示常见模式
  • 记录协议特定绑定
  • 包含消费者指南
  • 在文档中定义SLA

参考资料

目标流程

  • api-doc-generation.js
  • api-reference-docs.js
  • data-model-docs.js
  • docs-as-code-pipeline.js