# Deduplicate

> 根据推导出的键和时间窗口过滤重复载荷。

Source: https://docs.sommatic.ai/zh/nodes/ops.dedupe/

- 标识: `ops.dedupe`
- 类别: 运维
- 版本: 1.0.0
- 状态: 实验性. 目前始终失败：worker 调用了运行时日志器不提供的 `logger.debug`，且该错误未被捕获，导致整个运行失败。`ttl_ms` 也不会生效。
- 执行方式: sync

根据推导出的键和时间窗口过滤重复载荷。

该算子确保特定事件在给定时间范围内只被处理一次。对于可能出现重复消息的“至少一次”投递系统（例如队列重试、Webhook 重放），这一点至关重要。

**行为：**
- 根据输入载荷计算唯一键（通过模板/表达式）。
- 检查该键是否已在缓存中。
- **Unique：** 若为新键，则传给“unique”端口并缓存该键。
- **Duplicate：** 若已存在，则传给“duplicate”端口（或丢弃）。

**适用场景：**
- 忽略“Submit”按钮的重复点击。
- 确保特定 webhook ID 只处理一次。

## 配置

- `key_template` (string, 必填, 支持表达式): 生成去重键的表达式，例如 `{{ $json.messageId }}`。`payload` 不是表达式引擎中的变量，因此 `{{payload.messageId}}` 永远无法解析，每次运行都会共用同一个字面键。
- `ttl_ms` (number, 可选): 记住键的时间窗口长度。 默认值: `3600000`.

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

## 输出端口

- `unique` (默认): 首次出现。
- `duplicate`: 在 TTL 内已出现过。
- `error`: Error

## 输入契约

- `payload` (object, 可选)

## 输出契约

- `payload` (object, 可选)

## 在表达式中

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

- `$("Deduplicate").item.json.payload` (object) **worker 不返回：读取结果为 undefined.**
- `$("Deduplicate").item.json.messageId` (string) = `"msg_8f2a"` (编辑器不提示)
- `$("Deduplicate").item.json.subject` (string) = `"Invoice 1042"` (编辑器不提示)


## 工作原理

设计用途是：某个键首次出现时把输入项路由到 `unique`，之后路由到 `duplicate`，依赖工作流键值状态。在当前运行时中，它会在检查前抛出 `logger.debug is not a function`，导致运行失败。

1. 将 `key_template` 作为表达式解析，并把输入项与配置合并（配置优先）。
2. 键为空时抛出 `Missing 'key_template'`。
3. 构建状态键 `dedupe:<key_template>`。
4. 调用 `logger.debug()` 时抛错；worker 不捕获该错误，因此运行失败。下面的步骤目前不会执行。
5. 在 `$input.$kv_state` 中查找该键：找到 → `duplicate`；未找到 → `unique`，并通过 `meta.kv_state` 以当前毫秒时间戳保存该键。两种情况都原样传出输入项。

## 在工作流中

### 节点

```json
{
  "node_id": "node-dedupe-mail",
  "label": "Skip repeated emails",
  "operator_slug": "ops.dedupe",
  "operator_version": "1.0.0",
  "config": {
    "key_template": "{{ $json.messageId }}",
    "ttl_ms": 3600000
  }
}
```

### Envelope

```json
{
  "ok": true,
  "port": "unique",
  "data": {
    "messageId": "msg_8f2a",
    "subject": "Invoice 1042"
  },
  "meta": {
    "kv_state": {
      "dedupe:msg_8f2a": 1795705445000
    }
  }
}
```

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

### `unique`

在当前运行时中不会到达：`logger.debug()` 调用会先失败。此处展示代码构建的数据结构。

```json
{
  "messageId": "msg_8f2a",
  "subject": "Invoice 1042"
}
```

### `duplicate`

在当前运行时中不会到达：`logger.debug()` 调用会先失败。此处展示代码构建的数据结构。

```json
{
  "messageId": "msg_8f2a",
  "subject": "Invoice 1042"
}
```

### `error`

永远不会输出：失败时会直接抛错，导致运行失败。

## 代码中的行为

- `key_template`: 作为节点配置只解析一次：`{{ $json.messageId }}` 可用，`{{payload.messageId}}` 不可用（会保持字面量，导致所有运行共享同一个键）。混合文本如 `mail:{{ $json.messageId }}` 会得到字符串键。
- `ttl_ms`: 会读取但从不应用：键一旦保存，将永远被视为重复。

## 错误

| 消息 | 端口 | 原因与处理 |
| --- | --- | --- |
| `logger.debug is not a function` | `error` | Worker 调用了运行时 logger 不提供的 `logger.debug()`。每次运行都会抛出：运行失败。 |
| `Missing 'key_template'` | `error` | 节点和输入项中都没有设置 `key_template`。该错误会被抛出：运行失败。 |

## 说明与限制

- Worker 调用了 `logger.debug()`，而运行时 logger 没有该方法（只提供 `info`、`warning`、`error`、`log` 和 `success`）。每次运行该调用都会抛错。
- 键值状态保存在工作流定义的元数据（`kv_state`）中，由该工作流的所有运行共享。只有当运行使用草稿图时，后端才会在启动时把它注入为 `$input.$kv_state`；已发布版本的运行不会收到。写入（每个步骤的 `meta.kv_state`）在运行结束后才合并进元数据，因此同一次运行中的后续节点看不到。没有过期机制。
- 即使修复后，同一次运行中键相同的两个输入项也都会走 `unique`，因为写入要到运行结束后才保存。
- 抛出的错误会使整个运行失败，信息为 `Node <node_id> (<slug>) failed: <message>`，`error` 上的连线不会触发。在 `flow.try` 作用域内，引擎会将其转到 catch 节点。
- `execution` 设置（`retryOnFail`、`maxTries`、`waitBetweenTries`、`continueOnFail`、`timeout_ms`）可以填写，但本 worker 和引擎都不会应用。


## 契约（JSON Schema）

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

```json
{
  "slug": "ops.dedupe",
  "name": "Deduplicate",
  "category": "ops",
  "version": "1.0.0",
  "description": "Filters duplicate payloads based on a derived key and time window.\n\n  This operator ensures that specific events are processed only once within a given timeframe. It is crucial for handling \"at-least-once\" delivery systems where duplicate messages might occur (e.g., Queue retries, Webhook replays).\n\n  **Behavior:**\n  - Calculates a unique key from the input payload (via template/expression).\n  - Checks if the key exists in the cache.\n  - **Unique:** If new, passes to 'unique' port and caches key.\n  - **Duplicate:** If exists, passes to 'duplicate' port (or drops).\n\n  **Use Cases:**\n  - Ignorning double-clicks on a \"Submit\" button.\n  - Processing a specific webhook ID only once.",
  "capabilities": [
    "filter",
    "dedupe",
    "reliability"
  ],
  "config_schema": {
    "type": "object",
    "required": [
      "key_template"
    ],
    "properties": {
      "key_template": {
        "type": "string",
        "title": "Dedupe Key",
        "format": "expression",
        "description": "Expression that produces the dedupe key, e.g. `{{ $json.messageId }}`. `payload` is not a variable of the expression engine, so `{{payload.messageId}}` never resolves and every run shares the same literal key."
      },
      "ttl_ms": {
        "type": "number",
        "default": 3600000,
        "title": "TTL (ms)",
        "description": "Window duration to remember keys."
      },
      "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",
    "description": "Passes original payload.",
    "properties": {
      "payload": {
        "type": "object"
      }
    }
  },
  "ports": [
    {
      "port_id": "unique",
      "label": "Unique",
      "is_default": true,
      "description": "First time seen."
    },
    {
      "port_id": "duplicate",
      "label": "Duplicate",
      "description": "Already seen within TTL."
    },
    {
      "port_id": "error",
      "label": "Error"
    }
  ],
  "execution_mode": "sync",
  "tags": [
    "filter",
    "dedupe",
    "idempotency"
  ],
  "is_stateful": true,
  "publisher": {
    "identity": "org_link_loom",
    "profile": {
      "name": "Link Loom",
      "verified": true,
      "url": "https://me.veripass.com/link-loom",
      "logo_url": null
    }
  }
}
```

### config_schema

```json
{
  "type": "object",
  "required": [
    "key_template"
  ],
  "properties": {
    "key_template": {
      "type": "string",
      "title": "Dedupe Key",
      "format": "expression",
      "description": "Expression that produces the dedupe key, e.g. `{{ $json.messageId }}`. `payload` is not a variable of the expression engine, so `{{payload.messageId}}` never resolves and every run shares the same literal key."
    },
    "ttl_ms": {
      "type": "number",
      "default": 3600000,
      "title": "TTL (ms)",
      "description": "Window duration to remember keys."
    },
    "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",
  "description": "Passes original payload.",
  "properties": {
    "payload": {
      "type": "object"
    }
  }
}
```

### ports

```json
[
  {
    "port_id": "unique",
    "label": "Unique",
    "is_default": true,
    "description": "First time seen."
  },
  {
    "port_id": "duplicate",
    "label": "Duplicate",
    "description": "Already seen within TTL."
  },
  {
    "port_id": "error",
    "label": "Error"
  }
]
```
