# Compensate Saga

> 为分布式事务（Saga）触发补偿流程。

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

- 标识: `saga.compensate`
- 类别: 运维
- 版本: 1.0.0
- 状态: 实验性. 目前始终失败：worker 调用了运行时日志器不提供的 `logger.warn`。即使修复后，执行引擎也不会读取它返回的 `COMPENSATE` 信号。
- 执行方式: sync

为分布式事务（Saga）触发补偿流程。

长事务中发生故障时，该算子会指示引擎“回滚”：按相反顺序，为之前所有成功的活动执行已注册的补偿步骤。

**行为：**
- 识别当前活动的 Saga 作用域。
- 获取已完成步骤的“undo”操作。
- 按栈的方式（LIFO）执行。

**适用场景：**
- 库存预留失败时回滚支付。
- 航班无法预订时取消酒店预订。

## 配置

该节点没有配置项。

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

## 输出端口

- `compensated` (默认): 补偿流程已启动。
- `error`: 触发补偿失败。

## 输入契约

- `reason` (string, 可选): 触发补偿的原因。
- `saga_id` (string, 可选): 指定的 Saga ID（可选，默认取自上下文）。

## 输出契约

- `compensated` (boolean, 可选): 补偿流程已启动时为 true。

## 在表达式中

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

- `$("Compensate Saga").item.json.compensated` (boolean) = `true`: 补偿流程已启动时为 true。
- `$("Compensate Saga").item.json.__signal` (string) = `"COMPENSATE"` (编辑器不提示)
- `$("Compensate Saga").item.json.saga_id` (string) = `"ce78b34b-0bf5-4372-89b0-ae0eb6adddc1"` (编辑器不提示)
- `$("Compensate Saga").item.json.reason` (string) = `"Payment declined"` (编辑器不提示)
- `$("Compensate Saga").item.json.port` (string) = `"compensated"` (编辑器不提示)


## 工作原理

实验性节点。设计用途是触发 saga 回滚。在当前运行时中，它总是以 `logger.warn is not a function` 从 `error` 输出；即便如此，它本应返回的 `__signal: "COMPENSATE"` 也不会被引擎读取，因此不会执行任何撤销步骤。

1. 将输入项与解析后的配置合并（配置优先）。
2. 从配置或输入项中读取 `reason`（默认 `Manual Trigger`）和 `saga_id`。
3. 无论是否有 `saga_id`，都会调用 `logger.warn()` 并抛错；worker 捕获后从 `error` 输出。下面的步骤目前不会执行。
4. 没有 `saga_id` 时：本应以 `No Active Saga` 从 `error` 输出。
5. 有 `saga_id` 时：本应返回 `{ __signal: "COMPENSATE", saga_id, reason, port: "compensated", compensated: true }`，引擎只会把它当作普通输出传递。

## 在工作流中

### 节点

```json
{
  "node_id": "node-compensate-order",
  "label": "Compensate order saga",
  "operator_slug": "saga.compensate",
  "operator_version": "1.0.0",
  "config": {
    "saga_id": "{{ $json.saga_id }}",
    "reason": "Payment declined"
  }
}
```

### Envelope

```json
{
  "ok": false,
  "port": "error",
  "data": {
    "port": "error",
    "error": "logger.warn is not a function"
  }
}
```

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

### `compensated`

在当前运行时中不会到达：`logger.warn()` 调用会先失败。此处展示代码构建的数据结构。

```json
{
  "__signal": "COMPENSATE",
  "saga_id": "ce78b34b-0bf5-4372-89b0-ae0eb6adddc1",
  "reason": "Payment declined",
  "port": "compensated",
  "compensated": true
}
```

### `error`

目前每次运行都会如此。输出为整个返回对象 `{ port, error }`。

```json
{
  "port": "error",
  "error": "logger.warn is not a function"
}
```

## 代码中的行为

- `saga_id`: 不在配置 schema 中（仅出现在输入契约中），但会从节点配置读取；节点上未设置时从输入项读取：`saga_id`、`reason`。

## 错误

| 消息 | 端口 | 原因与处理 |
| --- | --- | --- |
| `logger.warn is not a function` | `error` | Worker 调用了运行时 logger 不提供的 `logger.warn()`。每次运行都会发生，任何配置都无法避免。 |
| `No Active Saga` | `error` | 目前不会到达。它表示节点和输入项中都没有设置 `saga_id`；从上下文回退查找活动 saga 的逻辑永远找不到。 |

## 说明与限制

- Worker 调用了 `logger.warn()`，而运行时 logger 没有该方法（只提供 `info`、`warning`、`error`、`log` 和 `success`）。每次运行该调用都会抛错。
- 要实现可用的补偿还缺少：引擎不读取 `__signal`，不维护 saga 历史，也没有执行 `undo` 逻辑的步骤。目前请用 `flow.try` 加显式补偿节点来实现回滚。
- 从 `error` 端口输出不会使运行失败：引擎沿 `error` 上的连线继续；若没有连线，该分支直接结束。
- `execution` 设置（`retryOnFail`、`maxTries`、`waitBetweenTries`、`continueOnFail`、`timeout_ms`）可以填写，但本 worker 和引擎都不会应用。


## 契约（JSON Schema）

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

```json
{
  "slug": "saga.compensate",
  "name": "Compensate Saga",
  "category": "ops",
  "version": "1.0.0",
  "description": "Triggers the compensation process for a distributed transaction (Saga).\n\n  When a failure occurs in a long-running transaction, this operator instructs the engine to \"rollback\" by executing the registered compensation steps for all previously successful activities in reverse order.\n\n  **Behavior:**\n  - Identifies the active Saga Scope.\n  - Retrieves the 'undo' operations for completed steps.\n  - Executes them stack-wise (LIFO).\n\n  **Use Cases:**\n  - Rolling back a payment if inventory reservation fails.\n  - Cancelling a hotel booking if the flight is unavailable.",
  "capabilities": [
    "saga",
    "transaction",
    "rollback",
    "ops"
  ],
  "config_schema": {
    "type": "object",
    "properties": {
      "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": {
      "reason": {
        "type": "string",
        "description": "Reason for compensation trigger."
      },
      "saga_id": {
        "type": "string",
        "description": "Specific Saga ID (optional, defaults to context)."
      }
    }
  },
  "output_contract_schema": {
    "type": "object",
    "properties": {
      "compensated": {
        "type": "boolean",
        "description": "True if compensation workflow initiated."
      }
    }
  },
  "ports": [
    {
      "port_id": "compensated",
      "label": "Compensated",
      "is_default": true,
      "description": "Compensation process started."
    },
    {
      "port_id": "error",
      "label": "Error",
      "description": "Failed to trigger compensation."
    }
  ],
  "execution_mode": "sync",
  "tags": [
    "saga",
    "rollback",
    "transaction"
  ],
  "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": {
    "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": {
    "reason": {
      "type": "string",
      "description": "Reason for compensation trigger."
    },
    "saga_id": {
      "type": "string",
      "description": "Specific Saga ID (optional, defaults to context)."
    }
  }
}
```

### output_contract_schema

```json
{
  "type": "object",
  "properties": {
    "compensated": {
      "type": "boolean",
      "description": "True if compensation workflow initiated."
    }
  }
}
```

### ports

```json
[
  {
    "port_id": "compensated",
    "label": "Compensated",
    "is_default": true,
    "description": "Compensation process started."
  },
  {
    "port_id": "error",
    "label": "Error",
    "description": "Failed to trigger compensation."
  }
]
```
