# Time Window

> Agrupa eventos en ventanas basadas en tiempo o en cantidad.

Source: https://docs.sommatic.ai/es/nodes/flow.window/

- Slug: `flow.window`
- Familia: Control de flujo
- Versión: 1.0.0
- Estado: Disponible
- Ejecución: async

Agrupa eventos en ventanas basadas en tiempo o en cantidad.

Este operador permite procesar flujos de datos agrupándolos en "ventanas". Acumula los payloads entrantes y los emite como un lote cuando se cumplen las condiciones de la ventana.

**Tipos de ventana:**
- **Tumbling:** Ventanas fijas que no se solapan (p. ej., cada 5 minutos).
- **Sliding:** Ventanas que se solapan (p. ej., los últimos 5 minutos, actualizados cada minuto).
- **Count:** Ventana de N elementos.

**Casos de uso:**
- Agregar lecturas de sensores cada minuto.
- Agrupar eventos de analítica antes de enviarlos a un data warehouse.
- Detectar patrones A -> B dentro de un intervalo de tiempo concreto.

## Configuración

- `type` (string, opcional): Por defecto: `tumbling`. Valores permitidos: `tumbling`, `sliding`.
- `interval_seconds` (integer, opcional): Por defecto: `60`.
- `max_items` (integer, opcional): Fuerza el cierre de la ventana si el búfer alcanza este límite. Por defecto: `100`.

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): Emite el lote cuando se cierra la ventana.
- `error`: Fallo interno.

## Contrato de entrada

- `payload` (object, opcional)

## Contrato de salida

- `window_items` (array<object>, opcional)
- `window_meta` (object, opcional)
  - `start_time` (string, opcional)
  - `end_time` (string, opcional)

## En expresiones

Lo que un nodo posterior puede leer de la salida de este nodo con `$("Time Window").item.json.<ruta>` (escribe la etiqueta de tu nodo en lugar de `Time Window`). **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.

- `$("Time Window").item.json.window_items` (array) = `[…] (2)`
- `$("Time Window").item.json.window_meta` (object) = `{…}`
- `$("Time Window").item.json.window_meta.start_time` (string) = `1795705200000`
- `$("Time Window").item.json.window_meta.end_time` (string) = `1795705200150`
- `$("Time Window").item.json.window_meta.count` (number) = `2` (El editor no la sugiere)


## Cómo funciona

Acumula los elementos que le llegan durante una ejecución y los emite como un lote por `out` cuando el búfer llega a `max_items` o han pasado `interval_seconds` desde el primer elemento.

1. El worker envuelve el payload como `{ window_items: [payload], window_meta: { start_time, end_time } }` (cadenas ISO) y fija `meta.window` `{ type, interval, batch_size }` a partir de `type` (por defecto `tumbling`), `interval_seconds` (60) y `max_items` (100).
2. El motor lo intercepta y agrega ese envoltorio a un búfer en memoria de este nodo.
3. Cuando el búfer tiene `max_items` entradas, o pasaron `interval_seconds` desde la primera (solo se comprueba al llegar un elemento), el motor envía `{ window_items, window_meta: { start_time, end_time, count } }` por `out` (tiempos en milisegundos epoch) y vacía el búfer.
4. Si no, nada continúa desde la ventana para ese elemento.

## En un workflow

### Nodo

```json
{
  "node_id": "node-batch-events",
  "label": "Batch events",
  "operator_slug": "flow.window",
  "operator_version": "1.0.0",
  "config": {
    "type": "tumbling",
    "interval_seconds": 60,
    "max_items": 2
  }
}
```

### Envelope

```json
{
  "ok": true,
  "data": {
    "window_items": [
      {
        "id": 1
      }
    ],
    "window_meta": {
      "start_time": "2026-11-26T15:00:00.000Z",
      "end_time": "2026-11-26T15:00:00.000Z"
    }
  },
  "meta": {
    "window": {
      "type": "tumbling",
      "interval": 60,
      "batch_size": 2
    }
  },
  "port": "out"
}
```

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

### `out`

La ventana se cerró por cantidad o por tiempo. Cada entrada de `window_items` es el envoltorio del worker, así que el payload original está en `window_items[i].window_items[0]`.

```json
{
  "window_items": [
    {
      "window_items": [
        {
          "id": 1
        }
      ],
      "window_meta": {
        "start_time": "2026-11-26T15:00:00.000Z",
        "end_time": "2026-11-26T15:00:00.000Z"
      }
    },
    {
      "window_items": [
        {
          "id": 2
        }
      ],
      "window_meta": {
        "start_time": "2026-11-26T15:00:00.150Z",
        "end_time": "2026-11-26T15:00:00.150Z"
      }
    }
  ],
  "window_meta": {
    "start_time": 1795705200000,
    "end_time": 1795705200150,
    "count": 2
  }
}
```

### `error`

Solo cuando el worker lanza un error inesperado.

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

## Comportamiento en el código

- `type`: Se ignora: `sliding` se comporta como `tumbling`.
- `interval_seconds`: Un valor 0 cierra la ventana con cada elemento.

## Notas y límites

- El búfer vive en memoria solo durante una ejecución. Las entradas que quedan al terminar la ejecución se descartan y nunca se emiten.
- El sobre del ejemplo es lo que devuelve el worker para un elemento; el motor lo intercepta y solo el lote mostrado en `out` llega al siguiente nodo.
- Sin un `flow.split` antes, el nodo ve un elemento por ejecución, así que con los valores por defecto nunca se emite nada; fija `max_items` en la cantidad esperada de elementos, o `interval_seconds` en 0.


## Contratos (JSON Schema)

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

```json
{
  "slug": "flow.window",
  "name": "Time Window",
  "category": "flow",
  "version": "1.0.0",
  "description": "Aggregates events into time-based or count-based windows.\n\n  This operator allows processing of streams of data by grouping them into \"windows\". It buffers incoming payloads and emits them as a batch when the window conditions are met.\n\n  **Window Types:**\n  - **Tumbling:** Fixed non-overlapping windows (e.g., every 5 minutes).\n  - **Sliding:** Overlapping windows (e.g., last 5 minutes, updated every minute).\n  - **Count:** Window of N items.\n\n  **Use Cases:**\n  - Aggregating sensor readings every minute.\n  - Batching analytics events before sending to a data warehouse.\n  - Detecting patterns A -> B within a specific timeframe.",
  "capabilities": [
    "windowing",
    "aggregation",
    "stream",
    "buffer"
  ],
  "config_schema": {
    "type": "object",
    "properties": {
      "type": {
        "type": "string",
        "enum": [
          "tumbling",
          "sliding"
        ],
        "default": "tumbling",
        "title": "Window Type"
      },
      "interval_seconds": {
        "type": "integer",
        "default": 60,
        "title": "Interval (Seconds)"
      },
      "max_items": {
        "type": "integer",
        "default": 100,
        "title": "Max Items",
        "description": "Force close window if buffer size reaches this limit."
      },
      "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",
    "description": "Individual event payload.",
    "properties": {
      "payload": {
        "type": "object"
      }
    }
  },
  "output_contract_schema": {
    "type": "object",
    "description": "Array of buffered payloads.",
    "properties": {
      "window_items": {
        "type": "array",
        "items": {
          "type": "object"
        }
      },
      "window_meta": {
        "type": "object",
        "properties": {
          "start_time": {
            "type": "string"
          },
          "end_time": {
            "type": "string"
          }
        }
      }
    }
  },
  "ports": [
    {
      "port_id": "out",
      "label": "Window",
      "is_default": true,
      "description": "Emits the batch when window closes."
    },
    {
      "port_id": "error",
      "label": "Error",
      "description": "Internal failure."
    }
  ],
  "execution_mode": "async",
  "tags": [
    "stream",
    "window",
    "batch"
  ],
  "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": {
    "type": {
      "type": "string",
      "enum": [
        "tumbling",
        "sliding"
      ],
      "default": "tumbling",
      "title": "Window Type"
    },
    "interval_seconds": {
      "type": "integer",
      "default": 60,
      "title": "Interval (Seconds)"
    },
    "max_items": {
      "type": "integer",
      "default": 100,
      "title": "Max Items",
      "description": "Force close window if buffer size reaches this limit."
    },
    "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",
  "description": "Individual event payload.",
  "properties": {
    "payload": {
      "type": "object"
    }
  }
}
```

### output_contract_schema

```json
{
  "type": "object",
  "description": "Array of buffered payloads.",
  "properties": {
    "window_items": {
      "type": "array",
      "items": {
        "type": "object"
      }
    },
    "window_meta": {
      "type": "object",
      "properties": {
        "start_time": {
          "type": "string"
        },
        "end_time": {
          "type": "string"
        }
      }
    }
  }
}
```

### ports

```json
[
  {
    "port_id": "out",
    "label": "Window",
    "is_default": true,
    "description": "Emits the batch when window closes."
  },
  {
    "port_id": "error",
    "label": "Error",
    "description": "Internal failure."
  }
]
```
