# Begin Saga

> 使用 Saga 模式启动一个分布式事务。

Source: https://docs.sommatic.ai/zh/nodes/saga.begin/

- 标识: `saga.begin`
- 类别: 运维
- 版本: 1.0.0
- 状态: 实验性. 返回一个 `saga_id` 和一个 `_context_update` 对象，但执行引擎从不读取它们：不会注册任何 saga 作用域，也不会跟踪任何补偿。
- 执行方式: sync

使用 Saga 模式启动一个分布式事务。

Saga 模式将长事务拆分为一系列子事务来管理。若任一步骤失败，Saga 编排器会执行补偿事务（撤销步骤）以回滚变更，保持最终一致性。

该算子标记 Saga 作用域的开始。它会初始化唯一的 Saga ID 并跟踪各事务步骤。

**核心概念：**
- **Steps：** 一系列操作（“do”）及其回滚（“undo”）。
- **Compensation：** 失败时触发的反向操作。
- **可追溯性：** 作用域内的所有操作都通过“saga_id”关联。

**适用场景：**
- 电商订单处理（库存 -> 支付 -> 发货）。
- 旅行预订（机票 -> 酒店 -> 租车）。

## 配置

- `rollback_on` (array<string>, 可选): 应自动触发回滚执行的错误码或状态列表。 默认值: `["ERROR","FAILURE"]`.

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

## 输出端口

- `success` (默认): Saga 初始化成功。
- `error`: Saga 初始化失败。

## 输入契约

- `steps` (array<object>, 可选): 定义执行与补偿逻辑的有序步骤列表。

## 输出契约

- `saga_id` (string, 可选): 唯一事务 ID
- `status` (string, 可选)

## 在表达式中

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

- `$("Begin Saga").item.json.saga_id` (string) = `"ce78b34b-0bf5-4372-89b0-ae0eb6adddc1"`: 唯一事务 ID
- `$("Begin Saga").item.json.status` (string) = `"active"`
- `$("Begin Saga").item.json.port` (string) = `"success"` (编辑器不提示)
- `$("Begin Saga").item.json._context_update` (object) = `{…}` (编辑器不提示)
- `$("Begin Saga").item.json._context_update.saga` (object) = `{…}` (编辑器不提示)


## 工作原理

实验性节点。生成 `saga_id`（UUID v4），记录 `[SAGA-BEGIN]`，并返回该 id 及一个引擎会忽略的 `_context_update` 对象：不会注册 saga 作用域，也不会跟踪补偿。

1. 将输入项与解析后的配置合并（配置优先）。
2. 使用 `rollback_on`（默认 `["ERROR", "FAILURE"]`）和 `steps`（默认 `[]`）。
3. 生成 `saga_id`，并以 info 级别记录 `[SAGA-BEGIN] Starting Saga <saga_id> with <n> steps.`。
4. 返回 `{ port: "success", saga_id, status: "active", _context_update }`；引擎把整个对象作为输出，且不读取 `_context_update`。

## 在工作流中

### 节点

```json
{
  "node_id": "node-begin-order-saga",
  "label": "Begin order saga",
  "operator_slug": "saga.begin",
  "operator_version": "1.0.0",
  "config": {
    "rollback_on": [
      "ERROR",
      "FAILURE"
    ],
    "steps": [
      {
        "name": "reserve_stock",
        "undo": {
          "action": "release_stock"
        }
      }
    ]
  }
}
```

### Envelope

```json
{
  "ok": true,
  "port": "success",
  "data": {
    "port": "success",
    "saga_id": "ce78b34b-0bf5-4372-89b0-ae0eb6adddc1",
    "status": "active",
    "_context_update": {
      "saga": {
        "id": "ce78b34b-0bf5-4372-89b0-ae0eb6adddc1",
        "steps": [
          {
            "name": "reserve_stock",
            "undo": {
              "action": "release_stock"
            }
          }
        ],
        "rollback_on": [
          "ERROR",
          "FAILURE"
        ],
        "history": []
      }
    }
  }
}
```

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

### `success`

实际上始终从此端口输出。

```json
{
  "port": "success",
  "saga_id": "ce78b34b-0bf5-4372-89b0-ae0eb6adddc1",
  "status": "active",
  "_context_update": {
    "saga": {
      "id": "ce78b34b-0bf5-4372-89b0-ae0eb6adddc1",
      "steps": [
        {
          "name": "reserve_stock",
          "undo": {
            "action": "release_stock"
          }
        }
      ],
      "rollback_on": [
        "ERROR",
        "FAILURE"
      ],
      "history": []
    }
  }
}
```

### `error`

仅在构建结果时出现意外异常时。

```json
{
  "port": "error",
  "error": "<message>"
}
```

## 代码中的行为

- `steps`: 不在配置 schema 中（仅出现在输入契约中），但会从节点配置或输入项读取。这些步骤只会被复制到 `_context_update` 中，没有任何逻辑执行 `do` 或 `undo`。
- `rollback_on`: 会被复制到 `_context_update` 中，但没有任何逻辑会评估它。

## 说明与限制

- 要实现可用的 saga 还缺少：引擎不读取 `_context_update`，不维护 saga 作用域，不记录步骤历史，也从不执行 `undo` 步骤。`saga.compensate` 也无法从上下文中找到该 saga。
- 如需使用该 id，请通过 `{{ $json.saga_id }}` 显式传递。目前请用 `flow.try` 加显式补偿节点来实现回滚。
- Worker 把字段直接放在顶层而不是 `data` 中，因此引擎把整个返回对象（包括 `port`）作为节点输出。
- `execution` 设置（`retryOnFail`、`maxTries`、`waitBetweenTries`、`continueOnFail`、`timeout_ms`）可以填写，但本 worker 和引擎都不会应用。


## 契约（JSON Schema）

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

```json
{
  "slug": "saga.begin",
  "name": "Begin Saga",
  "category": "ops",
  "version": "1.0.0",
  "description": "Initiates a distributed transaction using the Saga pattern.\n\n  The Saga pattern manages long-running transactions by breaking them into a sequence of sub-transactions. If any step fails, the Saga orchestrator executes compensating transactions (undo steps) to rollback the changes and maintain eventual consistency.\n\n  This operator marks the beginning of a Saga scope. It initializes a unique Saga ID and tracks the transaction steps.\n\n  **Key Concepts:**\n  - **Steps:** A sequence of actions (\"do\") and their rollbacks (\"undo\").\n  - **Compensation:** The reverse action triggered on failure.\n  - **Traceability:** All actions in the scope are linked by \"saga_id\".\n\n  **Use Cases:**\n  - E-commerce order processing (Inventory -> Payment -> Shipping).\n  - Booking travel (Flight -> Hotel -> Car).",
  "capabilities": [
    "saga",
    "transaction",
    "ops",
    "consistency"
  ],
  "config_schema": {
    "type": "object",
    "properties": {
      "rollback_on": {
        "type": "array",
        "items": {
          "type": "string"
        },
        "default": [
          "ERROR",
          "FAILURE"
        ],
        "title": "Rollback Triggers",
        "description": "List of error codes or statuses that should trigger an automatic rollback execution."
      },
      "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": {
    "type": "object",
    "properties": {
      "steps": {
        "type": "array",
        "description": "Ordered list of steps defining execution and compensation logic.",
        "items": {
          "type": "object",
          "properties": {
            "name": {
              "type": "string",
              "description": "Step Name"
            },
            "do": {
              "type": "object",
              "description": "Logic to execute"
            },
            "undo": {
              "type": "object",
              "description": "Logic to compensate"
            }
          },
          "required": [
            "name",
            "undo"
          ]
        }
      }
    }
  },
  "output_contract_schema": {
    "type": "object",
    "properties": {
      "saga_id": {
        "type": "string",
        "description": "Unique Transaction ID"
      },
      "status": {
        "type": "string"
      }
    }
  },
  "ports": [
    {
      "port_id": "success",
      "label": "Success",
      "is_default": true,
      "description": "Saga initialized successfully."
    },
    {
      "port_id": "error",
      "label": "Error",
      "description": "Failed to initialize Saga."
    }
  ],
  "execution_mode": "sync",
  "tags": [
    "saga",
    "transaction",
    "consistency"
  ],
  "is_stateful": true,
  "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",
  "properties": {
    "rollback_on": {
      "type": "array",
      "items": {
        "type": "string"
      },
      "default": [
        "ERROR",
        "FAILURE"
      ],
      "title": "Rollback Triggers",
      "description": "List of error codes or statuses that should trigger an automatic rollback execution."
    },
    "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

```json
{
  "type": "object",
  "properties": {
    "steps": {
      "type": "array",
      "description": "Ordered list of steps defining execution and compensation logic.",
      "items": {
        "type": "object",
        "properties": {
          "name": {
            "type": "string",
            "description": "Step Name"
          },
          "do": {
            "type": "object",
            "description": "Logic to execute"
          },
          "undo": {
            "type": "object",
            "description": "Logic to compensate"
          }
        },
        "required": [
          "name",
          "undo"
        ]
      }
    }
  }
}
```

### output_contract_schema

```json
{
  "type": "object",
  "properties": {
    "saga_id": {
      "type": "string",
      "description": "Unique Transaction ID"
    },
    "status": {
      "type": "string"
    }
  }
}
```

### ports

```json
[
  {
    "port_id": "success",
    "label": "Success",
    "is_default": true,
    "description": "Saga initialized successfully."
  },
  {
    "port_id": "error",
    "label": "Error",
    "description": "Failed to initialize Saga."
  }
]
```
