# Rate Limit

> 限制特定时间窗口内允许的执行次数。

Source: https://docs.sommatic.ai/zh/nodes/flow.rate.limit/

- 标识: `flow.rate.limit`
- 类别: 流程控制
- 版本: 1.0.0
- 状态: 实验性. 不会执行任何限流：限制仅记录在 `meta` 中，从不输出 `throttled`，执行始终经 `out` 继续。
- 执行方式: sync

限制特定时间窗口内允许的执行次数。

该算子执行速率限制策略（例如“每分钟 10 次请求”）。超出限制后，后续执行会被路由到“throttled”端口（或根据引擎配置延迟执行）。

**行为：**
- **按键限流：** 可以全局限流，也可以按键限流（例如按用户 ID）。
- **策略：** 固定窗口、滑动窗口（取决于引擎）。
- **溢出：** 超额请求会立即触发“throttled”端口。

**适用场景：**
- 保护脆弱的下游 API 免于过载。
- 为不同用户等级执行用量配额。
- 防止垃圾请求或滥用。

## 配置

- `limit` (integer, 可选): 窗口内允许的执行次数。 默认值: `10`.
- `window_seconds` (integer, 可选): 速率限制窗口的时长。 默认值: `60`.
- `key_expr` (string, 可选, 支持表达式): 用于生成唯一键的 JSONata 表达式。留空则全局生效。

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

## 输出端口

- `out` (默认): 允许执行（未超出限制）。
- `throttled`: 执行被阻止（超出限制）。
- `error`: 内部错误。

## 输入契约

- `payload` (object, 可选)

## 输出契约

- `payload` (object, 可选)

## 在表达式中

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

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


## 工作原理

计算限流键，并将 payload 连同限额元数据从 `out` 传出；不会实施任何限流，因为引擎从不读取它。

1. 解析配置；`limit` 默认 10，`window_seconds` 默认 60。
2. 若 `key_expr` 原始文本包含 `{{`，则以解析后的值作为键（转为字符串）。否则 `key_expr` 作为 JSONata 针对 payload 求值（`user_id`）；结果为假值或未设置 `key_expr` 时为 `global`。
3. JSONata 出错会被忽略，键保持为 `global`。
4. 通过 `out` 原样返回 payload，并带 `meta.rate_limit` `{ key, limit, window }`。引擎会忽略它：每次执行都会通过。

## 在工作流中

### 节点

```json
{
  "node_id": "node-limit-exports",
  "label": "Limit exports",
  "operator_slug": "flow.rate.limit",
  "operator_version": "1.0.0",
  "config": {
    "limit": 10,
    "window_seconds": 60,
    "key_expr": "{{ $json.user_id }}"
  }
}
```

### Envelope

```json
{
  "ok": true,
  "data": {
    "user_id": "u-42",
    "action": "export"
  },
  "port": "out",
  "meta": {
    "rate_limit": {
      "key": "u-42",
      "limit": 10,
      "window": 60
    }
  }
}
```

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

### `out`

始终触发。

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

### `throttled`

从不触发：不维护任何计数。

### `error`

从不触发。

## 代码中的行为

- `limit`: 仅在 `meta.rate_limit` 中回显；`window_seconds` 以 `window` 回显。

## 说明与限制

- 尚未实现：没有共享计数器，因此 `throttled` 永远不会触发。请在被调用的服务端限流，或用自己的逻辑控制调用间隔。
- `meta` 只记录在运行步骤中：下游节点收到的 payload 是 `data`，无法通过 `$json` 或 `$("Node")` 读取 `meta`。


## 契约（JSON Schema）

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

```json
{
  "slug": "flow.rate.limit",
  "name": "Rate Limit",
  "category": "flow",
  "version": "1.0.0",
  "description": "Throttles the number of executions allowed within a specific time window.\n\n  This operator enforces a rate limit policy (e.g., \"10 requests per minute\"). If the limit is exceeded, subsequent executions are routed to the 'throttled' port (or delayed, depending on engine configuration).\n\n  **Behavior:**\n  - **Key-based Throttling:** Can throttle globally or per-key (e.g., per user ID).\n  - **Strategies:** Fixed Window, Sliding Window (engine dependent).\n  - **Overflow:** Excess requests trigger the 'throttled' port immediately.\n\n  **Use Cases:**\n  - Protecting a fragile downstream API from overload.\n  - Enforcing usage quotas for different user tiers.\n  - Preventing spam or abuse.",
  "capabilities": [
    "throttle",
    "limit",
    "control-flow"
  ],
  "config_schema": {
    "type": "object",
    "properties": {
      "limit": {
        "type": "integer",
        "default": 10,
        "title": "Max Executions",
        "description": "Number of allowed executions in the window."
      },
      "window_seconds": {
        "type": "integer",
        "default": 60,
        "title": "Window (Seconds)",
        "description": "Time duration for the rate limit window."
      },
      "key_expr": {
        "type": "string",
        "title": "Throttling Key",
        "format": "expression",
        "description": "JSONata expression to derive the unique key. If empty, applies globally."
      },
      "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": {
      "payload": {
        "type": "object"
      }
    }
  },
  "output_contract_schema": {
    "type": "object",
    "properties": {
      "payload": {
        "type": "object"
      }
    }
  },
  "ports": [
    {
      "port_id": "out",
      "label": "Passed",
      "is_default": true,
      "description": "Execution allowed (within limit)."
    },
    {
      "port_id": "throttled",
      "label": "Throttled",
      "description": "Execution blocked (limit exceeded)."
    },
    {
      "port_id": "error",
      "label": "Error",
      "description": "Internal error."
    }
  ],
  "execution_mode": "sync",
  "tags": [
    "throttle",
    "limit",
    "quota"
  ],
  "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": {
    "limit": {
      "type": "integer",
      "default": 10,
      "title": "Max Executions",
      "description": "Number of allowed executions in the window."
    },
    "window_seconds": {
      "type": "integer",
      "default": 60,
      "title": "Window (Seconds)",
      "description": "Time duration for the rate limit window."
    },
    "key_expr": {
      "type": "string",
      "title": "Throttling Key",
      "format": "expression",
      "description": "JSONata expression to derive the unique key. If empty, applies globally."
    },
    "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": {
    "payload": {
      "type": "object"
    }
  }
}
```

### output_contract_schema

```json
{
  "type": "object",
  "properties": {
    "payload": {
      "type": "object"
    }
  }
}
```

### ports

```json
[
  {
    "port_id": "out",
    "label": "Passed",
    "is_default": true,
    "description": "Execution allowed (within limit)."
  },
  {
    "port_id": "throttled",
    "label": "Throttled",
    "description": "Execution blocked (limit exceeded)."
  },
  {
    "port_id": "error",
    "label": "Error",
    "description": "Internal error."
  }
]
```
