# Emit Metric

> Publishes custom operational telemetry (metrics) to the monitoring system.

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

- Slug: `metrics.emit`
- Family: Operations
- Version: 1.0.0
- Status: Partial. On success the worker returns no port, so the engine follows `out`, which this node does not declare: an edge drawn from its success port never fires. Until it is fixed, do not chain nodes after its success path.
- Execution: fire-and-forget

Publishes custom operational telemetry (metrics) to the monitoring system.

These metrics are aggregated by the platform (e.g., Prometheus, Datadog) to visualize workflow health, business KPIs, or performance trends.

**Metric Types:**
- **Counter:** Monotonically increasing number (e.g., "Total Orders").
- **Gauge:** A value that goes up and down (e.g., "Current Queue Size").
- **Histogram:** Distribution of values (e.g., "Processing Time").

**Use Cases:**
- Tracking the number of failed validations.
- Monitoring the value of processed transactions.
- Alerting on unexpected business logic paths.

## Configuration

- `metric` (string, required): Unique name (e.g., `workflow.order.processed`).
- `kind` (string, optional): The behavior of the metric aggregation. Default: `counter`. Allowed values: `counter`, `gauge`, `histogram`.

Its configuration shows the shared execution settings, but this node does not apply retries (`retryOnFail`, `maxTries`) yet. `continueOnFail` is not applied by any node.

## Output ports

- `success` (default): Metric emitted.
- `error`: Observability system unavailable.

## Input contract

- `value` (number, required): The numeric value to emit. Default: `1`.
- `labels` (object, optional): Key-value pairs for dimensional slicing (tags).

## Output contract

- `success` (boolean, optional)

## In expressions

What a later node can read from this node's output with `$("Emit Metric").item.json.<path>`, as the workflow editor suggests it under Previous Nodes (the output contract).

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


## How it works

Writes one `[METRIC] <KIND> <metric>: <value>` line to the orchestrator log, meant for log-based collection, and returns `{ success: true }`. No metrics backend is called and labels are not written.

1. Merges the input item with the resolved config (config wins).
2. Throws `Missing 'metric'` when `metric` is empty and `Missing 'value'` when `value` is undefined or null (`0` is accepted).
3. Uses `kind` (default `counter`) upper-cased in the line; it is not checked against the enum and `value` is not checked to be numeric.
4. Logs `[METRIC] <KIND> <metric>: <value>` at info level. `labels` and the timestamp passed with it are not written.
5. Returns `{ success: true }` with no port, so the engine routes through `out`.

## In a workflow

### Node

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

## Output ports (behaviour in the code)

### `success`

Never emitted: the worker returns no port, so the engine routes through `out`, which this node does not declare. Edges drawn from `success` never fire.

### `error`

Never emitted: failures throw instead, which fails the run.

## Behaviour in the code

- `value`: Not in the config schema (only in the input contract), but read from the node config or the input item. Required at runtime despite the contract default of `1`.
- `labels`: Read from the node config or the input item, but never written to the log line.

## Errors

| Message | Port | Cause and fix |
| --- | --- | --- |
| `Missing 'metric'` | `error` | `metric` is set neither on the node nor in the input item. Thrown: the run fails. |
| `Missing 'value'` | `error` | `value` is set neither on the node nor in the input item; the schema default `1` is not applied by the code. Thrown: the run fails. |
| `kind.toUpperCase is not a function` | `error` | `kind` resolved to a non-string value. Thrown: the run fails. |

## Notes and limits

- Partial: nodes wired after `success` never run, so place it at the end of a branch. The node output in the run is `{ success: true }`.
- A thrown error fails the whole run with `Node <node_id> (<slug>) failed: <message>` and edges from `error` do not fire. Inside a `flow.try` scope the engine sends it to the catch node instead.
- The `execution` settings (`retryOnFail`, `maxTries`, `waitBetweenTries`, `continueOnFail`, `timeout_ms`) are accepted, but neither this worker nor the engine applies them.


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