# Mutex Lock

> 通过分布式锁确保对工作流关键区段的独占访问。

Source: https://docs.sommatic.ai/zh/nodes/flow.mutex/

- 标识: `flow.mutex`
- 类别: 流程控制
- 版本: 1.0.0
- 状态: 实验性. 会计算锁键并在 `meta.mutex` 中返回，但执行引擎从不读取它：不会获取任何锁，执行始终经由 `out` 继续。
- 执行方式: sync

通过分布式锁确保对工作流关键区段的独占访问。

当多个工作流实例（或并行分支）同时尝试访问共享资源时，互斥锁（Mutex，Mutual Exclusion）确保同一时刻只有一个能够继续执行。其他实例会一直等待，直到锁被释放或超时。

**行为：**
- **获取：** 尝试锁定该键。若未被占用，则授予锁。
- **等待：** 若已被锁定，进程会自旋或等待。
- **释放：** TTL 到期后锁会自动释放（以防死锁）。

**适用场景：**
- 防止用户钱包重复扣款。
- 对无法处理并发的遗留系统进行串行化访问。
- 确保数据库操作中“先检查后执行”（Check-then-Act）的原子性。

## 配置

- `key_expr` (string, 必填, 支持表达式): 用于生成唯一锁 ID 的 JSONata 表达式（例如 `data.userId`）。
- `ttl_seconds` (integer, 可选): 安全超时：工作流崩溃时自动释放锁。 默认值: `30`.

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

## 输出端口

- `out` (默认): 成功获取锁，进入关键区段。
- `timeout`: 未能在系统限制时间内获取锁。
- `error`: 加锁过程中发生系统错误。

## 输入契约

- `payload` (object, 可选)

## 输出契约

- `payload` (object, 可选)

## 在表达式中

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

- `$("Mutex Lock").item.json.payload` (object) **worker 不返回：读取结果为 undefined.**
- `$("Mutex Lock").item.json.user_id` (string) = `"u-42"` (编辑器不提示)
- `$("Mutex Lock").item.json.action` (string) = `"export"` (编辑器不提示)


## 工作原理

实验性。计算锁键并将 payload 从 `out` 传出；不会获取任何锁，因为引擎从不读取加锁请求。

1. 解析配置；`ttl_seconds` 默认为 30。
2. 若 `key_expr` 原始文本包含 `{{`，则以解析后的值作为键（转为字符串）。否则 `key_expr` 作为 JSONata 针对 payload 求值（`user_id`）；结果为假值或未设置 `key_expr` 时为 `global_lock`。
3. 通过 `out` 原样返回 payload，并带 `meta.mutex` `{ action: "acquire", key, ttl }`。
4. 引擎会忽略 `meta.mutex`：不加锁、不等待，并发运行也不会被串行化。

## 在工作流中

### 节点

```json
{
  "node_id": "node-lock-user",
  "label": "Lock user",
  "operator_slug": "flow.mutex",
  "operator_version": "1.0.0",
  "config": {
    "key_expr": "{{ $json.user_id }}",
    "ttl_seconds": 30
  }
}
```

### Envelope

```json
{
  "ok": true,
  "data": {
    "user_id": "u-42",
    "action": "export"
  },
  "port": "out",
  "meta": {
    "mutex": {
      "action": "acquire",
      "key": "u-42",
      "ttl": 30
    }
  }
}
```

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

### `out`

始终输出，包括 JSONata 键求值失败时（见错误）。

```json
{
  "user_id": "u-42",
  "action": "export"
}
```

### `timeout`

从不触发。

### `error`

从不触发。

## 代码中的行为

- `ttl_seconds`: 仅在 `meta.mutex.ttl` 中回显。

## 错误

| 消息 | 端口 | 原因与处理 |
| --- | --- | --- |
| `Lock key evaluation failed` | `out` | `key_expr` 不是有效 JSONata。信封没有端口，引擎将其路由到 `out`，下一个节点收到的 payload 是 `{ ok: false, errors: ["Lock key evaluation failed"] }`。 |

## 说明与限制

- 尚未实现：引擎没有锁存储。不要依赖此节点实现互斥，应让受保护的操作具备幂等性。
- `meta` 只记录在运行步骤中：下游节点收到的 payload 是 `data`，无法通过 `$json` 或 `$("Node")` 读取 `meta`。


## 契约（JSON Schema）

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

```json
{
  "slug": "flow.mutex",
  "name": "Mutex Lock",
  "category": "flow",
  "version": "1.0.0",
  "description": "Ensures exclusive access to a critical section of the workflow via a distributed lock.\n\n  When multiple workflow instances (or parallel branches) try to access a shared resource simultaneously, a Mutex (Mutual Exclusion) ensures only one can proceed at a time. Other instances will wait until the lock is released or a timeout occurs.\n\n  **Behavior:**\n  - **Acquire:** Attempts to lock the key. If free, lock is granted.\n  - **Wait:** If locked, the process spins/waits.\n  - **Release:** The lock is automatically released after the TTL expires (to prevent deadlocks).\n\n  **Use Cases:**\n  - Preventing double-spending on a user wallet.\n  - Serializing access to a legacy system that cannot handle concurrency.\n  - Ensuring \"Check-then-Act\" atomicity in database operations.",
  "capabilities": [
    "locking",
    "concurrency",
    "safety"
  ],
  "config_schema": {
    "type": "object",
    "properties": {
      "key_expr": {
        "type": "string",
        "title": "Lock Key",
        "format": "expression",
        "description": "JSONata expression to derive the unique lock ID (e.g. `data.userId`)."
      },
      "ttl_seconds": {
        "type": "integer",
        "default": 30,
        "title": "Lock TTL (Seconds)",
        "description": "Safety timeout to automatically release the lock if the workflow crashes."
      },
      "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
          }
        }
      }
    },
    "required": [
      "key_expr"
    ]
  },
  "input_contract_schema": {
    "type": "object",
    "description": "Payload to evaluate the key against.",
    "properties": {
      "payload": {
        "type": "object"
      }
    }
  },
  "output_contract_schema": {
    "type": "object",
    "description": "Passes through the original payload.",
    "properties": {
      "payload": {
        "type": "object"
      }
    }
  },
  "ports": [
    {
      "port_id": "out",
      "label": "Acquired",
      "is_default": true,
      "description": "Lock successfully acquired. Proceed with critical section."
    },
    {
      "port_id": "timeout",
      "label": "Timeout",
      "description": "Failed to acquire lock within the system limit."
    },
    {
      "port_id": "error",
      "label": "Error",
      "description": "System error during locking."
    }
  ],
  "execution_mode": "sync",
  "tags": [
    "lock",
    "mutex",
    "atomic",
    "concurrency"
  ],
  "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": {
    "key_expr": {
      "type": "string",
      "title": "Lock Key",
      "format": "expression",
      "description": "JSONata expression to derive the unique lock ID (e.g. `data.userId`)."
    },
    "ttl_seconds": {
      "type": "integer",
      "default": 30,
      "title": "Lock TTL (Seconds)",
      "description": "Safety timeout to automatically release the lock if the workflow crashes."
    },
    "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
        }
      }
    }
  },
  "required": [
    "key_expr"
  ]
}
```

### input_contract_schema

```json
{
  "type": "object",
  "description": "Payload to evaluate the key against.",
  "properties": {
    "payload": {
      "type": "object"
    }
  }
}
```

### output_contract_schema

```json
{
  "type": "object",
  "description": "Passes through the original payload.",
  "properties": {
    "payload": {
      "type": "object"
    }
  }
}
```

### ports

```json
[
  {
    "port_id": "out",
    "label": "Acquired",
    "is_default": true,
    "description": "Lock successfully acquired. Proceed with critical section."
  },
  {
    "port_id": "timeout",
    "label": "Timeout",
    "description": "Failed to acquire lock within the system limit."
  },
  {
    "port_id": "error",
    "label": "Error",
    "description": "System error during locking."
  }
]
```
