# Rate Limit

> Limita el número de ejecuciones permitidas dentro de una ventana de tiempo determinada.

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

- Slug: `flow.rate.limit`
- Familia: Control de flujo
- Versión: 1.0.0
- Estado: Experimental. No aplica ningún límite: solo lo informa en `meta`, nunca emite `throttled` y la ejecución siempre sigue por `out`.
- Ejecución: sync

Limita el número de ejecuciones permitidas dentro de una ventana de tiempo determinada.

Este operador aplica una política de límite de tasa (p. ej., "10 solicitudes por minuto"). Si se supera el límite, las ejecuciones siguientes se dirigen al puerto 'throttled' (o se retrasan, según la configuración del motor).

**Comportamiento:**
- **Limitación por clave:** Puede limitar de forma global o por clave (p. ej., por ID de usuario).
- **Estrategias:** Ventana fija, ventana deslizante (según el motor).
- **Desbordamiento:** Las solicitudes excedentes activan el puerto 'throttled' de inmediato.

**Casos de uso:**
- Proteger de la sobrecarga a una API posterior frágil.
- Aplicar cuotas de uso para distintos niveles de usuario.
- Prevenir spam o abuso.

## Configuración

- `limit` (integer, opcional): Número de ejecuciones permitidas en la ventana. Por defecto: `10`.
- `window_seconds` (integer, opcional): Duración de la ventana del límite de tasa. Por defecto: `60`.
- `key_expr` (string, opcional, acepta expresiones): Expresión JSONata para obtener la clave única. Si está vacía, el límite se aplica de forma global.

Su configuración muestra los ajustes de ejecución compartidos, pero este nodo aún no aplica reintentos (`retryOnFail`, `maxTries`). Ningún nodo aplica `continueOnFail`.

## Puertos de salida

- `out` (por defecto): Ejecución permitida (dentro del límite).
- `throttled`: Ejecución bloqueada (límite superado).
- `error`: Error interno.

## Contrato de entrada

- `payload` (object, opcional)

## Contrato de salida

- `payload` (object, opcional)

## En expresiones

Lo que un nodo posterior puede leer de la salida de este nodo con `$("Rate Limit").item.json.<ruta>` (escribe la etiqueta de tu nodo en lugar de `Rate Limit`). **Editor** marca las rutas que sugiere el editor de workflows en Previous Nodes (el contrato de salida); **Worker** marca las rutas que el worker devuelve de verdad por `out`, según la salida que muestra Puertos.

- `$("Rate Limit").item.json.payload` (object) **El worker no la devuelve: se lee como undefined.**
- `$("Rate Limit").item.json.user_id` (string) = `"u-42"` (El editor no la sugiere)
- `$("Rate Limit").item.json.action` (string) = `"export"` (El editor no la sugiere)


## Cómo funciona

Calcula una clave de limitación y pasa el payload por `out` con el límite como metadatos; no se aplica ningún límite, porque el motor nunca lo lee.

1. Resuelve la configuración; `limit` vale 10 y `window_seconds` 60 por defecto.
2. Si el texto original de `key_expr` contiene `{{`, la clave es el valor resuelto (convertido en cadena). Si no, `key_expr` se evalúa como JSONata sobre el payload (`user_id`); un resultado falsy o la ausencia de `key_expr` da `global`.
3. Un error de JSONata se ignora y la clave queda en `global`.
4. Devuelve el payload sin cambios por `out` con `meta.rate_limit` `{ key, limit, window }`. El motor lo ignora: toda ejecución pasa.

## En un workflow

### Nodo

```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
    }
  }
}
```

## Puertos de salida (comportamiento en el código)

### `out`

Siempre.

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

### `throttled`

Nunca se emite: no se lleva ningún contador.

### `error`

Nunca se emite.

## Comportamiento en el código

- `limit`: Solo se repite en `meta.rate_limit`; `window_seconds` se repite como `window`.

## Notas y límites

- No implementado: no hay contador compartido, así que `throttled` nunca se activa. Limita la tasa en el servicio llamado o espacia las llamadas con tu propia lógica.
- `meta` solo queda en los pasos de la ejecución: los nodos siguientes reciben `data` como payload y no pueden leer `meta` con `$json` ni con `$("Node")`.


## Contratos (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."
  }
]
```
