# Emit Metric

> 将自定义运行遥测数据（指标）发布到监控系统。

Source: https://docs.sommatic.ai/zh/nodes/metrics.emit/

- 标识: `metrics.emit`
- 类别: 运维
- 版本: 1.0.0
- 状态: 部分可用. 执行成功时该 worker 不返回端口，引擎会沿 `out` 继续，而该节点并未声明 `out`：从其成功端口引出的连线永远不会触发。修复前，请勿在其成功路径后串接其他节点。
- 执行方式: fire-and-forget

将自定义运行遥测数据（指标）发布到监控系统。

这些指标由平台（例如 Prometheus、Datadog）聚合，用于可视化工作流健康状况、业务 KPI 或性能趋势。

**指标类型：**
- **Counter：** 单调递增的数值（例如“订单总数”）。
- **Gauge：** 可升可降的数值（例如“当前队列长度”）。
- **Histogram：** 数值的分布（例如“处理耗时”）。

**适用场景：**
- 跟踪校验失败的次数。
- 监控已处理交易的金额。
- 在出现意外的业务逻辑路径时告警。

## 配置

- `metric` (string, 必填): 唯一名称（例如 `workflow.order.processed`）。
- `kind` (string, 可选): 指标的聚合行为。 默认值: `counter`. 可选值: `counter`, `gauge`, `histogram`.

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

## 输出端口

- `success` (默认): 指标已发出。
- `error`: 可观测性系统不可用。

## 输入契约

- `value` (number, 必填): 要发出的数值。 默认值: `1`.
- `labels` (object, 可选): 用于按维度切分的键值对（标签）。

## 输出契约

- `success` (boolean, 可选)

## 在表达式中

后续节点可通过 `$("Emit Metric").item.json.<路径>` 读取此节点输出中的内容，即工作流编辑器在 Previous Nodes 中提示的路径（输出契约）。

- `$("Emit Metric").item.json.success` (boolean)


## 工作原理

向编排器日志写入一行 `[METRIC] <KIND> <metric>: <value>`，用于基于日志的采集，并返回 `{ success: true }`。不会调用任何指标后端，标签也不会写入。

1. 将输入项与解析后的配置合并（配置优先）。
2. `metric` 为空时抛出 `Missing 'metric'`；`value` 为 undefined 或 null 时抛出 `Missing 'value'`（接受 `0`）。
3. 在日志行中使用大写的 `kind`（默认 `counter`）；不会按枚举校验，也不检查 `value` 是否为数字。
4. 以 info 级别记录 `[METRIC] <KIND> <metric>: <value>`。随附的 `labels` 和时间戳不会写入。
5. 返回不带端口的 `{ success: true }`，因此引擎走 `out`。

## 在工作流中

### 节点

```json
{
  "node_id": "node-count-orders",
  "label": "Count processed orders",
  "operator_slug": "metrics.emit",
  "operator_version": "1.0.0",
  "config": {
    "metric": "workflow.order.processed",
    "kind": "counter",
    "value": 1
  }
}
```

### Envelope

```json
{
  "ok": true,
  "port": "out",
  "data": {
    "success": true
  }
}
```

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

### `success`

永远不会输出：worker 不返回端口，引擎因此走 `out`，而本节点并未声明该端口。从 `success` 画出的连线永远不会触发。

### `error`

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

## 代码中的行为

- `value`: 不在配置 schema 中（仅出现在输入契约中），但会从节点配置或输入项读取。尽管契约默认值为 `1`，运行时仍为必填。
- `labels`: 会从节点配置或输入项读取，但永远不会写入日志行。

## 错误

| 消息 | 端口 | 原因与处理 |
| --- | --- | --- |
| `Missing 'metric'` | `error` | 节点和输入项中都没有设置 `metric`。该错误会被抛出：运行失败。 |
| `Missing 'value'` | `error` | 节点和输入项中都没有设置 `value`；代码不会应用 schema 中的默认值 `1`。该错误会被抛出：运行失败。 |
| `kind.toUpperCase is not a function` | `error` | `kind` 解析为非字符串值。该错误会被抛出：运行失败。 |

## 说明与限制

- 部分实现：连在 `success` 之后的节点永远不会运行，请把它放在分支末尾。该节点在运行中的输出为 `{ success: true }`。
- 抛出的错误会使整个运行失败，信息为 `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": "metrics.emit",
  "name": "Emit Metric",
  "category": "ops",
  "version": "1.0.0",
  "description": "Publishes custom operational telemetry (metrics) to the monitoring system.\n\n  These metrics are aggregated by the platform (e.g., Prometheus, Datadog) to visualize workflow health, business KPIs, or performance trends.\n\n  **Metric Types:**\n  - **Counter:** Monotonically increasing number (e.g., \"Total Orders\").\n  - **Gauge:** A value that goes up and down (e.g., \"Current Queue Size\").\n  - **Histogram:** Distribution of values (e.g., \"Processing Time\").\n\n  **Use Cases:**\n  - Tracking the number of failed validations.\n  - Monitoring the value of processed transactions.\n  - Alerting on unexpected business logic paths.",
  "capabilities": [
    "observability",
    "metrics",
    "monitoring"
  ],
  "config_schema": {
    "type": "object",
    "required": [
      "metric"
    ],
    "properties": {
      "metric": {
        "type": "string",
        "title": "Metric Name",
        "description": "Unique name (e.g., `workflow.order.processed`)."
      },
      "kind": {
        "type": "string",
        "enum": [
          "counter",
          "gauge",
          "histogram"
        ],
        "default": "counter",
        "title": "Metric Type",
        "description": "The behavior of the metric aggregation."
      },
      "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": {
      "value": {
        "type": "number",
        "default": 1,
        "description": "The numeric value to emit."
      },
      "labels": {
        "type": "object",
        "description": "Key-value pairs for dimensional slicing (tags)."
      }
    },
    "required": [
      "value"
    ]
  },
  "output_contract_schema": {
    "type": "object",
    "description": "Confirmation.",
    "properties": {
      "success": {
        "type": "boolean"
      }
    }
  },
  "ports": [
    {
      "port_id": "success",
      "label": "Success",
      "is_default": true,
      "description": "Metric emitted."
    },
    {
      "port_id": "error",
      "label": "Error",
      "description": "Observability system unavailable."
    }
  ],
  "execution_mode": "fire-and-forget",
  "tags": [
    "observability",
    "monitoring",
    "telemetry"
  ],
  "is_stateful": false,
  "publisher": {
    "identity": "org_vectry",
    "profile": {
      "name": "Vectry Analytics",
      "verified": true,
      "url": "https://me.veripass.com/vectry",
      "logo_url": null
    }
  }
}
```

### config_schema

```json
{
  "type": "object",
  "required": [
    "metric"
  ],
  "properties": {
    "metric": {
      "type": "string",
      "title": "Metric Name",
      "description": "Unique name (e.g., `workflow.order.processed`)."
    },
    "kind": {
      "type": "string",
      "enum": [
        "counter",
        "gauge",
        "histogram"
      ],
      "default": "counter",
      "title": "Metric Type",
      "description": "The behavior of the metric aggregation."
    },
    "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": {
    "value": {
      "type": "number",
      "default": 1,
      "description": "The numeric value to emit."
    },
    "labels": {
      "type": "object",
      "description": "Key-value pairs for dimensional slicing (tags)."
    }
  },
  "required": [
    "value"
  ]
}
```

### output_contract_schema

```json
{
  "type": "object",
  "description": "Confirmation.",
  "properties": {
    "success": {
      "type": "boolean"
    }
  }
}
```

### ports

```json
[
  {
    "port_id": "success",
    "label": "Success",
    "is_default": true,
    "description": "Metric emitted."
  },
  {
    "port_id": "error",
    "label": "Error",
    "description": "Observability system unavailable."
  }
]
```
