# Time Window

> 将事件聚合到基于时间或基于数量的窗口中。

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

- 标识: `flow.window`
- 类别: 流程控制
- 版本: 1.0.0
- 状态: 可用
- 执行方式: async

将事件聚合到基于时间或基于数量的窗口中。

该算子通过将数据流分组到“窗口”中进行处理。它会缓存传入的载荷，并在满足窗口条件时将其作为一个批次发出。

**窗口类型：**
- **Tumbling：** 固定且互不重叠的窗口（例如每 5 分钟）。
- **Sliding：** 相互重叠的窗口（例如最近 5 分钟，每分钟更新一次）。
- **Count：** 由 N 个条目组成的窗口。

**适用场景：**
- 每分钟聚合一次传感器读数。
- 在发送到数据仓库之前对分析事件分批。
- 检测特定时间范围内 A -> B 的模式。

## 配置

- `type` (string, 可选): 默认值: `tumbling`. 可选值: `tumbling`, `sliding`.
- `interval_seconds` (integer, 可选): 默认值: `60`.
- `max_items` (integer, 可选): 缓冲区大小达到此上限时强制关闭窗口。 默认值: `100`.

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

## 输出端口

- `out` (默认): 窗口关闭时发出批次。
- `error`: 内部故障。

## 输入契约

- `payload` (object, 可选)

## 输出契约

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

## 在表达式中

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

- `$("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` (编辑器不提示)


## 工作原理

缓存一次运行中到达的各项，当缓冲达到 `max_items` 或自第一项起已过 `interval_seconds` 时，作为一个批次从 `out` 输出。

1. worker 将 payload 包装为 `{ window_items: [payload], window_meta: { start_time, end_time } }`（ISO 字符串），并根据 `type`（默认 `tumbling`）、`interval_seconds`（60）和 `max_items`（100）设置 `meta.window` `{ type, interval, batch_size }`。
2. 引擎拦截该输出，并将包装对象追加到本节点的内存缓冲区。
3. 当缓冲区达到 `max_items` 条，或自第一条起已过 `interval_seconds`（仅在有新项到达时检查）时，引擎从 `out` 发送 `{ window_items, window_meta: { start_time, end_time, count } }`（时间为纪元毫秒）并清空缓冲区。
4. 否则该项不会从窗口继续向下流转。

## 在工作流中

### 节点

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

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

### `out`

窗口因数量或时间而关闭。`window_items` 的每一项都是 worker 的包装对象，原始 payload 位于 `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`

仅在 worker 意外抛错时。

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

## 代码中的行为

- `type`: 被忽略：`sliding` 的行为与 `tumbling` 相同。
- `interval_seconds`: 值为 0 时每一项都会关闭窗口。

## 说明与限制

- 缓冲区仅在一次运行期间存在于内存中。运行结束时剩余的条目会被丢弃，永远不会输出。
- 示例信封是 worker 针对单个项返回的内容；引擎会拦截它，只有 `out` 中所示的批次会到达下一个节点。
- 上游没有 `flow.split` 时，节点每次运行只看到一项，因此使用默认值时永远不会输出；请将 `max_items` 设为预期项数，或将 `interval_seconds` 设为 0。


## 契约（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."
  }
]
```
