# Queue / Topic Consumer

> 从外部消息队列或 Pub/Sub 主题消费消息。

Source: https://docs.sommatic.ai/zh/nodes/queue.trigger/

- 标识: `queue.trigger`
- 类别: 触发器
- 版本: 1.0.0
- 状态: 实验性. 目前尚无队列消费者，因此该触发器不会自行启动运行；`source`、`prefetch` 与 `ack_mode` 不会被读取，也不会确认任何消息。
- 执行方式: async

从外部消息队列或 Pub/Sub 主题消费消息。

该触发器连接外部消息代理（如 RabbitMQ、Kafka、SQS 或 Redis），并为每条传入消息启动一个工作流实例。

**主要特性：**
- **背压：** 支持 `prefetch`，以限制并发创建的工作流实例数。
- **可靠性：** 支持自动或手动确认（Ack/Nack），保证消息投递。

**适用场景：**
- 处理从主 Web 服务器卸载出来的任务。
- 与遗留系统集成的事件驱动架构。

## 配置

- `source` (string, 必填): 消息代理连接的资源 ID。
- `subscription` (string, 必填): 要监听的具体通道。
- `prefetch` (integer, 可选): 未确认消息的最大数量。 默认值: `10`.
- `ack_mode` (string, 可选): Auto：工作流启动时确认。Manual：需要由特定应用确认。 默认值: `auto`. 可选值: `auto`, `manual`.

配置中会显示通用执行设置，但该节点目前不执行重试（`retryOnFail`、`maxTries`）。所有节点均未实现 `continueOnFail`。

## 输出端口

- `out` (默认): Message Received
- `error`: Error

## 输出契约

- `message_id` (string, 可选)
- `queue` (string, 可选)
- `content` (object, 可选): 消息正文。
- `attributes` (object, 可选): 消息头/元数据。

## 在表达式中

后续节点可通过 `$("Queue / Topic Consumer").item.json.<路径>` 读取此节点输出中的内容（请把 `Queue / Topic Consumer` 换成你的节点标签）。**Editor** 标记工作流编辑器在 Previous Nodes 中提示的路径（输出契约）；**Worker** 标记 worker 实际通过 `out` 返回的路径，依据“端口”一节所示的输出。

- `$("Queue / Topic Consumer").item.json.message_id` (string) = `"msg-7f3a9c"`
- `$("Queue / Topic Consumer").item.json.queue` (string) = `"orders.created"`
- `$("Queue / Topic Consumer").item.json.content` (object) = `{…}`: 消息正文。
- `$("Queue / Topic Consumer").item.json.attributes` (object) = `{…}`: 消息头/元数据。
- `$("Queue / Topic Consumer").item.json.content.order_id` (string) = `"ord_123"` (编辑器不提示)
- `$("Queue / Topic Consumer").item.json.content.total` (number) = `129.99` (编辑器不提示)
- `$("Queue / Topic Consumer").item.json.attributes.content-type` (string) = `"application/json"` (编辑器不提示)


## 工作原理

队列驱动工作流的入口节点。它将运行输入整理为 `{ message_id, queue, content, attributes }`，并拒绝来自 `subscription` 以外队列的消息；当前版本中没有消息代理消费者会启动它。

1. 触发来源：当前版本中没有后端组件为本节点消费消息代理。只有以 `{ message_id, queue, content, attributes }` 结构的输入显式启动工作流时才会运行。
2. 解析节点配置。若设置了 `subscription`，且输入中的 `queue` 存在但与之不同，则返回 `error`。
3. 否则输出 `message_id`（默认 `unknown`）、`queue`（取输入值或 `subscription`）、`content`（取输入的 `content`，否则为整个输入）和 `attributes`（默认 `{}`）。

## 在工作流中

### 节点

```json
{
  "node_id": "node-orders-queue",
  "label": "Orders queue",
  "operator_slug": "queue.trigger",
  "operator_version": "1.0.0",
  "config": {
    "source": "pi-credential-xxxx",
    "subscription": "orders.created",
    "prefetch": 10,
    "ack_mode": "auto"
  }
}
```

### Envelope

```json
{
  "ok": true,
  "data": {
    "message_id": "msg-7f3a9c",
    "queue": "orders.created",
    "content": {
      "order_id": "ord_123",
      "total": 129.99
    },
    "attributes": {
      "content-type": "application/json"
    }
  },
  "port": "out"
}
```

## 输出端口 (代码中的行为)

### `out`

消息被接受。

```json
{
  "message_id": "msg-7f3a9c",
  "queue": "orders.created",
  "content": {
    "order_id": "ord_123",
    "total": 129.99
  },
  "attributes": {
    "content-type": "application/json"
  }
}
```

### `error`

输入中的 `queue` 与 `subscription` 不一致。输出为信封 `{ ok, errors, port }`。

```json
{
  "ok": false,
  "errors": [
    "Queue mismatch: orders.created is not equal to orders.cancelled"
  ],
  "port": "error"
}
```

## 代码中的行为

- `source`: 已声明且为必填，但不会被读取。`prefetch` 和 `ack_mode` 同样不会被读取：本节点不会确认（ack）任何消息。
- `subscription`: 仅用于拒绝来自其他队列的消息，并作为输出中 `queue` 的默认值。

## 错误

| 消息 | 端口 | 原因与处理 |
| --- | --- | --- |
| `Queue mismatch: <subscription> is not equal to <queue>` | `error` | 工作流以来自其他队列的消息启动。 |

## 说明与限制

- 输入中没有 `content` 时，整个输入（包括后端可能添加的 `$trigger_state`）都会成为 `content`。
- 使用示例数据时，引擎会跳过本节点，并经 `out` 原样输出示例输入。


## 契约（JSON Schema）

### All (`*.definition.js`)

```json
{
  "slug": "queue.trigger",
  "name": "Queue / Topic Consumer",
  "category": "triggers",
  "version": "1.0.0",
  "description": "Consumes messages from an external Message Queue or Pub/Sub Topic.\n\n  This trigger connects to external brokers (like RabbitMQ, Kafka, SQS, or Redis) and initiates a workflow instance for each incoming message.\n\n  **Key Features:**\n  - **Backpressure:** Supports `prefetch` to limit concurrent workflow instantiations.\n  - **Reliability:** Supports Auto or Manual Acknowledgement (Ack/Nack) to ensure message delivery guarantees.\n\n  **Use Cases:**\n  - Processing tasks offloaded from a main web server.\n  - Event-driven architecture integrating with legacy systems.",
  "capabilities": [
    "queue-consumer",
    "high-throughput",
    "async-processing"
  ],
  "config_schema": {
    "type": "object",
    "required": [
      "source",
      "subscription"
    ],
    "properties": {
      "source": {
        "type": "string",
        "title": "Connection / Broker",
        "description": "Resource ID of the message broker connection."
      },
      "subscription": {
        "type": "string",
        "title": "Queue Name / Topic",
        "description": "The specific channel to listen to."
      },
      "prefetch": {
        "type": "integer",
        "default": 10,
        "title": "Prefetch Count",
        "description": "Max unacknowledged messages."
      },
      "ack_mode": {
        "type": "string",
        "enum": [
          "auto",
          "manual"
        ],
        "default": "auto",
        "title": "Ack Mode",
        "description": "Auto: Ack on workflow start. Manual: Requires specific app to Ack."
      },
      "execution": {
        "type": "object",
        "title": "Execution Settings",
        "properties": {
          "alwaysOutputData": {
            "type": "boolean",
            "title": "Always Output Data",
            "description": "Always output data, even on error (if configured).",
            "default": false
          },
          "retryOnFail": {
            "type": "boolean",
            "title": "Retry On Fail",
            "description": "Retry the execution if it fails.",
            "default": false
          },
          "maxTries": {
            "type": "integer",
            "title": "Max Retries",
            "description": "Number of retries.",
            "default": 3,
            "displayOptions": {
              "show": {
                "retryOnFail": [
                  true
                ]
              }
            }
          },
          "waitBetweenTries": {
            "type": "integer",
            "title": "Wait Between Retries (ms)",
            "default": 1000,
            "displayOptions": {
              "show": {
                "retryOnFail": [
                  true
                ]
              }
            }
          },
          "continueOnFail": {
            "type": "boolean",
            "title": "Continue On Fail",
            "description": "Do not crash workflow on error.",
            "default": false
          },
          "timeout_ms": {
            "type": "integer",
            "title": "Timeout (ms)",
            "description": "Max execution time for this node before it is killed, in milliseconds. Honored by long-running operators (e.g. OCR/extraction, inline code). Default 300000 (5 min).",
            "default": 300000
          }
        }
      }
    }
  },
  "input_contract_schema": null,
  "output_contract_schema": {
    "type": "object",
    "properties": {
      "message_id": {
        "type": "string"
      },
      "queue": {
        "type": "string"
      },
      "content": {
        "type": "object",
        "description": "The message body."
      },
      "attributes": {
        "type": "object",
        "description": "Message headers/metadata."
      }
    }
  },
  "ports": [
    {
      "port_id": "out",
      "label": "Message Received",
      "is_default": true
    },
    {
      "port_id": "error",
      "label": "Error"
    }
  ],
  "execution_mode": "async",
  "tags": [
    "queue",
    "consumer",
    "kafka",
    "rabbitmq"
  ],
  "is_stateful": false,
  "publisher": {
    "identity": "org_sommatic_ai",
    "profile": {
      "name": "Sommatic AI",
      "verified": true,
      "url": "https://me.veripass.com/sommatic",
      "logo_url": null
    }
  }
}
```

### config_schema

```json
{
  "type": "object",
  "required": [
    "source",
    "subscription"
  ],
  "properties": {
    "source": {
      "type": "string",
      "title": "Connection / Broker",
      "description": "Resource ID of the message broker connection."
    },
    "subscription": {
      "type": "string",
      "title": "Queue Name / Topic",
      "description": "The specific channel to listen to."
    },
    "prefetch": {
      "type": "integer",
      "default": 10,
      "title": "Prefetch Count",
      "description": "Max unacknowledged messages."
    },
    "ack_mode": {
      "type": "string",
      "enum": [
        "auto",
        "manual"
      ],
      "default": "auto",
      "title": "Ack Mode",
      "description": "Auto: Ack on workflow start. Manual: Requires specific app to Ack."
    },
    "execution": {
      "type": "object",
      "title": "Execution Settings",
      "properties": {
        "alwaysOutputData": {
          "type": "boolean",
          "title": "Always Output Data",
          "description": "Always output data, even on error (if configured).",
          "default": false
        },
        "retryOnFail": {
          "type": "boolean",
          "title": "Retry On Fail",
          "description": "Retry the execution if it fails.",
          "default": false
        },
        "maxTries": {
          "type": "integer",
          "title": "Max Retries",
          "description": "Number of retries.",
          "default": 3,
          "displayOptions": {
            "show": {
              "retryOnFail": [
                true
              ]
            }
          }
        },
        "waitBetweenTries": {
          "type": "integer",
          "title": "Wait Between Retries (ms)",
          "default": 1000,
          "displayOptions": {
            "show": {
              "retryOnFail": [
                true
              ]
            }
          }
        },
        "continueOnFail": {
          "type": "boolean",
          "title": "Continue On Fail",
          "description": "Do not crash workflow on error.",
          "default": false
        },
        "timeout_ms": {
          "type": "integer",
          "title": "Timeout (ms)",
          "description": "Max execution time for this node before it is killed, in milliseconds. Honored by long-running operators (e.g. OCR/extraction, inline code). Default 300000 (5 min).",
          "default": 300000
        }
      }
    }
  }
}
```

### output_contract_schema

```json
{
  "type": "object",
  "properties": {
    "message_id": {
      "type": "string"
    },
    "queue": {
      "type": "string"
    },
    "content": {
      "type": "object",
      "description": "The message body."
    },
    "attributes": {
      "type": "object",
      "description": "Message headers/metadata."
    }
  }
}
```

### ports

```json
[
  {
    "port_id": "out",
    "label": "Message Received",
    "is_default": true
  },
  {
    "port_id": "error",
    "label": "Error"
  }
]
```
