# End Trace Span

> 关闭一个活动的分布式追踪 span。

Source: https://docs.sommatic.ai/zh/nodes/ops.trace.end/

- 标识: `ops.trace.end`
- 类别: 运维
- 版本: 1.0.0
- 状态: 可用
- 执行方式: sync

关闭一个活动的分布式追踪 span。

该算子标记某个具体工作单元（Span）的完成。它会计算耗时并确定 span 的最终状态（success/error）。这对准确的 APM（应用性能监控）以及构建完整的追踪瀑布图至关重要。

**适用场景：**
- 测量一段外部 API 调用的延迟。
- 将一组复杂的逻辑步骤归入一个便于阅读的 span。
- 记录自定义事务的最终状态。

## 配置

- `name` (string, 必填): 要关闭的 span 名称（必须与 Start Span 一致）。

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

## 输出端口

- `success` (默认): Span 已成功关闭。
- `error`: 未找到或无法关闭 span。

## 输入契约

- `trace_id` (string, 可选): 活动的 Trace ID。
- `span_id` (string, 必填): 要关闭的 Span ID。
- `attributes` (object, 可选): 最终的标签/属性（例如状态码）。

## 输出契约

- `success` (boolean, 可选)
- `duration_ms` (number, 可选)

## 在表达式中

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

- `$("End Trace Span").item.json.success` (boolean) = `true`
- `$("End Trace Span").item.json.duration_ms` (number) **worker 不返回：读取结果为 undefined.**
- `$("End Trace Span").item.json.port` (string) = `"success"` (编辑器不提示)


## 工作原理

向编排器日志写入一行 `[TRACE-END] <name>`，并从 `success` 返回 `{ success: true }`。不会查找或关闭 span，也不计算耗时。

1. 将输入项与解析后的配置合并（配置优先）。
2. `name` 为空时以 `Missing 'name'` 从 `error` 输出。虽然输入契约把 `span_id` 标为必填，但不会检查它。
3. 以 info 级别记录 `[TRACE-END] <name>`；随附的 `trace_id`、`span_id` 和 `attributes` 不会写入。
4. 返回 `{ port: "success", success: true }`；引擎把整个对象作为输出。

## 在工作流中

### 节点

```json
{
  "node_id": "node-trace-end-checkout",
  "label": "End checkout span",
  "operator_slug": "ops.trace.end",
  "operator_version": "1.0.0",
  "config": {
    "name": "checkout",
    "trace_id": "{{ $json.trace_id }}",
    "span_id": "{{ $json.span_id }}"
  }
}
```

### Envelope

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

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

### `success`

已设置 `name`。

```json
{
  "port": "success",
  "success": true
}
```

### `error`

`name` 为空。

```json
{
  "port": "error",
  "error": "Missing 'name'"
}
```

## 代码中的行为

- `span_id`: 不在配置 schema 中（仅出现在输入契约中），但会从节点配置读取；节点上未设置时从输入项读取：`trace_id`、`span_id`、`attributes`。它们都不会写入日志。

## 错误

| 消息 | 端口 | 原因与处理 |
| --- | --- | --- |
| `Missing 'name'` | `error` | 节点和输入项中都没有设置 `name`。 |

## 说明与限制

- `duration_ms` 出现在输出契约中，但从不返回。
- 运行时 logger 只输出消息文本，随附的结构化对象不会写入日志。
- Worker 把字段直接放在顶层而不是 `data` 中，因此引擎把整个返回对象（包括 `port`）作为节点输出。
- 从 `error` 端口输出不会使运行失败：引擎沿 `error` 上的连线继续；若没有连线，该分支直接结束。
- `execution` 设置（`retryOnFail`、`maxTries`、`waitBetweenTries`、`continueOnFail`、`timeout_ms`）可以填写，但本 worker 和引擎都不会应用。


## 契约（JSON Schema）

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

```json
{
  "slug": "ops.trace.end",
  "name": "End Trace Span",
  "category": "ops",
  "version": "1.0.0",
  "description": "Closes an active distributed tracing span.\n\n  This operator marks the completion of a specific unit of work (Span). It calculates the duration and finalizing the span status (success/error). It is essential for accurate APM (Application Performance Monitoring) and constructing the full trace waterfall.\n\n  **Use Cases:**\n  - Measuring the latency of an external API call block.\n  - Grouping a set of complex logic steps into a single readable span.\n  - Recording the final status of a custom transaction.",
  "capabilities": [
    "observability",
    "tracing",
    "apm"
  ],
  "config_schema": {
    "type": "object",
    "required": [
      "name"
    ],
    "properties": {
      "name": {
        "type": "string",
        "title": "Span Name",
        "description": "Name of the span to close (must match Start Span)."
      },
      "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": {
      "trace_id": {
        "type": "string",
        "description": "The active Trace ID."
      },
      "span_id": {
        "type": "string",
        "description": "The Span ID to close."
      },
      "attributes": {
        "type": "object",
        "description": "Final tags/attributes (e.g. status code)."
      }
    },
    "required": [
      "span_id"
    ]
  },
  "output_contract_schema": {
    "type": "object",
    "description": "Confirmation.",
    "properties": {
      "success": {
        "type": "boolean"
      },
      "duration_ms": {
        "type": "number"
      }
    }
  },
  "ports": [
    {
      "port_id": "success",
      "label": "Ended",
      "is_default": true,
      "description": "Span closed successfully."
    },
    {
      "port_id": "error",
      "label": "Error",
      "description": "Failed to find or close span."
    }
  ],
  "execution_mode": "sync",
  "tags": [
    "observability",
    "tracing",
    "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": [
    "name"
  ],
  "properties": {
    "name": {
      "type": "string",
      "title": "Span Name",
      "description": "Name of the span to close (must match Start Span)."
    },
    "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": {
    "trace_id": {
      "type": "string",
      "description": "The active Trace ID."
    },
    "span_id": {
      "type": "string",
      "description": "The Span ID to close."
    },
    "attributes": {
      "type": "object",
      "description": "Final tags/attributes (e.g. status code)."
    }
  },
  "required": [
    "span_id"
  ]
}
```

### output_contract_schema

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

### ports

```json
[
  {
    "port_id": "success",
    "label": "Ended",
    "is_default": true,
    "description": "Span closed successfully."
  },
  {
    "port_id": "error",
    "label": "Error",
    "description": "Failed to find or close span."
  }
]
```
