Skip to content

完整 API 参考手册 (Full API Reference)

本文档是后端所有 REST + WebSocket 端点的完整技术参考。


Base URL

http://localhost:8000

所有端点均以 JSON 交互(除文件下载外),请求 Content-Type 为 application/json


1. 健康与系统 (System)

1.1 GET /health

说明:全局健康检查,包含 API 状态、数据库连通性、适配器连通性、节点深度探测。

路由文件src/unet_dt/api/routes/health.py

请求参数:无

Response 200HealthResponse

字段类型说明
statusstring全局状态:healthy / degraded / unhealthy
checksobject{ api: {ok: bool}, database: {ok: bool, detail: str?} }
healthy_nodesint探测成功的节点数
total_nodesint配置的总节点数
dbDbHealth数据库健康详情
db.okbool数据库连接是否正常
db.tablesobject各表是否存在 {dt_runs: bool, dt_run_summary: bool, dt_run_events: bool}
db.detailstring?错误详情
adapterAdapterHealth适配器健康详情
adapter.okbool适配器/网关是否可达
adapter.backendstring适配器后端类型:fjagepy / arlpy / logonly
adapter.detailstring?错误详情
adapter.unet_hoststringUNet 网关主机
adapter.unet_portintUNet 网关端口
adapter.node_endpointsNodeEndpointHealth[]各节点的 TCP 可达性
nodesHealthNodeCheck[]各节点的深度探测结果

NodeEndpointHealth:

字段类型说明
nodestring节点名 (A-G)
endpointstringTCP 端点地址
reachableboolTCP 是否可达
detailstring?错误详情

HealthNodeCheck:

字段类型说明
node_idint节点数值 ID
namestring节点名称
okbool网关连接是否成功
phy_okbool物理层是否可用
agentsint运行中的 Agent 数量
servicesstring[]可用服务列表
unet_addrint?动态分配的 UNet 地址
detailstring?详情/错误信息

1.2 GET /health/nodes

说明:仅返回节点层面的深度检查结果。

路由文件src/unet_dt/api/routes/health.py

Response 200NodeHealthResponse

字段类型说明
statusstringhealthy / degraded / unhealthy
nodesHealthNodeCheck[]同上
healthy_countint健康节点数
total_countint总节点数

1.3 GET /config

说明:返回当前运行时配置(敏感信息已脱敏)。

路由文件src/unet_dt/api/routes/config.py

Response 200ConfigResponse

字段类型说明
unet_hoststringUNet 主机
unet_portintUNet 端口
node_endpointsConfigNodeEndpoint[]节点端点列表
location_initLocationInitConfig?位置初始化配置
db_url_maskedstring脱敏后的数据库连接串
adapter_backendstring适配器后端类型

ConfigNodeEndpoint: { node: string, endpoint: string }

LocationInitConfig: { enabled: bool, mode: string, script_path: string, timeout_seconds: float }


1.4 POST /config/location-init/run

说明:手动触发位置初始化脚本执行。

路由文件src/unet_dt/api/routes/config.py

Response 200LocationInitRunResponse

字段类型说明
enabledbool位置初始化是否启用
okbool执行是否成功
skippedbool是否跳过(未启用时)
modestring运行模式
commandstring[]实际执行的命令
return_codeint?进程返回码
stdoutstring标准输出
stderrstring标准错误
duration_msfloat执行耗时 (ms)
warningstring?警告信息

2. 策略 (Strategies)

2.1 GET /strategies

说明:列出所有已注册的调度策略。

路由文件src/unet_dt/api/routes/strategies.py

Response 200StrategyListResponse

字段类型说明
itemsStrategyItem[]策略列表
totalint策略总数

StrategyItem: { id: string, name: string }


3. 场景管理 (Scenarios)

3.1 GET /scenarios

说明:合并 YAML 文件 + 数据库两种来源的场景列表。

路由文件src/unet_dt/api/routes/scenarios.py

Response 200ScenarioMergedListResponse

字段类型说明
itemsScenarioDbItem[]场景列表
totalint场景总数

ScenarioDbItem:

字段类型说明
idstring场景 ID
namestring场景名称
sourcestring来源:db / yaml
created_atdatetime?创建时间(YAML 来源为 null)
updated_atdatetime?更新时间(YAML 来源为 null)

3.2 GET /scenarios/

说明:获取场景完整信息(含节点、流量、运行参数)。

路径参数scenario_id — 场景 ID

Response 200ScenarioFullResponse

字段类型说明
idstring场景 ID
namestring场景名称
nodesScenarioNodeItem[]节点列表
trafficScenarioTrafficItem[]流量配置
runScenarioRunConfig运行参数
unetobject?UNet 配置覆盖
sourcestring来源
created_atdatetime?创建时间
updated_atdatetime?更新时间

ScenarioNodeItem: { id: int, name: string?, position: [float, float]?, tcp: string? }

ScenarioTrafficItem: { flow_id: string, src: int, dst: int, period_ms: float, payload_bytes: int }

ScenarioRunConfig: { seed: int, dt_seconds: float, steps: int, output_dir: string }

Response 404: 场景不存在


3.3 POST /scenarios

说明:创建新场景(保存到数据库)。

Request BodyScenarioCreateRequest

字段类型必填说明
idstring场景 ID(唯一)
namestring场景名称
nodesScenarioNodeItem[]节点列表
trafficScenarioTrafficItem[]流量配置
runScenarioRunConfig运行参数

Response 201ScenarioFullResponse

Response 409: 场景 ID 已存在


3.4 PUT /scenarios/

说明:更新已有场景。

Request BodyScenarioUpdateRequest:字段同 Create,但均为可选。

Response 200ScenarioFullResponse

Response 404: 场景不存在


3.5 DELETE /scenarios/

说明:删除数据库中的场景(YAML 场景不可删除)。

Response 204: 删除成功

Response 404: 场景不存在


3.6 POST /scenarios/import

说明:从本地 YAML 文件导入场景到数据库。

Request Body{ "yaml_path": "string" }

Response 201ScenarioFullResponse


3.7 POST /scenarios/{scenario_id}/export

说明:将数据库场景导出为 YAML 文件。

Response 200{ "scenario_id": "string", "output_path": "string" }


4. 运行管理 (Runs)

4.1 POST /runs

说明:创建新的仿真运行实例(状态为 created,尚未开始执行)。

路由文件src/unet_dt/api/routes/runs.py

Request BodyRunCreateRequest

字段类型必填默认值说明
scenario_idstring场景 ID
strategy_idstringround_robin策略 ID
modestringmock运行模式:mock / gateway
stepsint100仿真步数
dt_secondsfloat1.0时间步长(秒)
seedint42随机种子
run_idstring?自动生成 UUID自定义 Run ID

Response 201RunItem


4.2 GET /runs

说明:分页查询运行列表。

Query Parameters

  • limit (int, 默认 50) — 每页数量
  • offset (int, 默认 0) — 偏移量

Response 200RunListResponse

字段类型说明
itemsRunItem[]运行列表
limitint请求的 limit
offsetint请求的 offset

RunItem:

字段类型说明
idstringRun ID
scenario_idstring场景 ID
strategy_idstring策略 ID
modestring运行模式
statusstring状态:created / running / stopping / finished / stopped / failed
stepsint总步数
current_stepint当前步数
dt_secondsfloat时间步长
seedint随机种子
created_atdatetime创建时间
started_atdatetime?启动时间
finished_atdatetime?结束时间
output_dirstring?产物输出目录
error_messagestring?错误信息

4.3 GET /runs/

说明:获取运行详情,包含摘要统计。

Response 200RunDetailResponse

字段类型说明
runRunItem运行基本信息
summaryRunSummaryItem?摘要统计(可能为 null)

RunSummaryItem:

字段类型说明
run_idstringRun ID
avg_throughput_bpsfloat?平均吞吐量 (bps)
avg_loss_ratefloat?平均丢包率
p95_delay_msfloat?P95 延迟 (ms)
trace_countint?追踪记录总数
received_countint?接收成功数
updated_atdatetime?最后更新时间

Response 404: Run 不存在


4.4 GET /runs/{run_id}/status

说明:获取运行实时状态(为前端轮询设计)。

Response 200RunStatusResponse

字段类型说明
runRunItem运行基本信息
summaryRunSummaryItem?摘要统计
current_stepint当前步
total_stepsint总步数
latest_metricsMetricItem?最新一步的指标

4.5 POST /runs/{run_id}/start

说明:启动已创建的运行实例。运行必须处于 created 状态。

Response 200RunItem(状态变为 running

Response 404: Run 不存在

Response 409: Run 状态不允许启动


4.6 POST /runs/{run_id}/stop

说明:请求停止正在运行的实例。运行必须处于 running 状态。

Response 200RunItem(状态变为 stopping

Response 404: Run 不存在

Response 409: Run 状态不允许停止


4.7 GET /runs/{run_id}/metrics

说明:获取运行的步进指标数据(从 CSV 产物或数据库读取)。

Response 200RunMetricsResponse

字段类型说明
run_idstringRun ID
statusstring运行状态
artifact_dirstring?产物目录
source_filestring?数据来源文件
countint指标条数
itemsMetricItem[]指标列表

MetricItem:

字段类型说明
step_idint?步序号
t_window_start_msfloat窗口起始时间
t_window_end_msfloat窗口结束时间
throughput_bpsfloat吞吐量 (bps)
loss_ratefloat丢包率
delay_p50_msfloatP50 延迟
delay_p95_msfloatP95 延迟
sent_countint发送数量
recv_countint接收数量
sync_error_msfloat同步误差
overhead_msfloat计算开销

4.8 GET /runs/{run_id}/traces

说明:分页获取通信追踪记录。

Query Parameters

  • limit (int, 默认 200)
  • offset (int, 默认 0)

Response 200RunTracesResponse

字段类型说明
run_idstringRun ID
statusstring运行状态
artifact_dirstring?产物目录
source_filestring?数据来源文件
totalint记录总数
limitint每页数量
offsetint偏移
itemsTraceItem[]追踪记录列表

TraceItem:

字段类型说明
run_idstringRun ID
step_idint步序号
seqint序列号
tx_time_msfloat发送时间
srcint源节点
dstint目标节点
rx_time_msfloat?接收时间
payload_bytesint载荷大小
receivedbool是否接收成功
sourcestring数据来源 (csv / db)

4.9 GET /runs/{run_id}/artifacts

说明:列出运行的产物文件清单。

Response 200RunArtifactsResponse

字段类型说明
run_idstringRun ID
artifact_dirstring?产物目录
filesArtifactFileItem[]文件列表

ArtifactFileItem:

字段类型说明
filenamestring文件名
existsbool文件是否存在
size_bytesint?文件大小
download_urlstring?下载 URL

4.10 GET /runs/{run_id}/artifacts/

说明:下载指定的产物文件。

路径参数

  • filename — 允许的值:traces.csv, metrics.csv, report.md, scenario.yaml, strategy.json, versions.json

Response 200: 文件流(Content-Type 根据文件类型确定)

Response 400: 不允许的文件名

Response 404: 文件不存在


4.11 GET /runs/{run_id}/events

说明:查询运行事件日志。

Query Parameters

  • limit (int, 默认 200)
  • offset (int, 默认 0)

Response 200RunEventsResponse

字段类型说明
run_idstringRun ID
itemsRunEventItem[]事件列表
totalint事件总数

RunEventItem:

字段类型说明
idint事件数据库 ID
run_idstringRun ID
event_typestring事件类型 (state_change, step, metrics, ...)
step_idint?关联的步序号
payloadobject事件 JSON 载荷
created_atdatetime事件时间

5. WebSocket 实时推送

5.1 WS /ws/runs/

说明:建立 WebSocket 连接以接收运行事件实时推送。

路由文件src/unet_dt/api/ws.py

连接流程

  1. 客户端连接 ws://host:port/ws/runs/{run_id}
  2. 服务器验证 run_id 存在后 accept
  3. 自动推送当前 statemetrics 快照
  4. 后续持续推送运行过程中的事件

关闭码

  • 4404: run_id 不存在

消息格式RunEventEnvelope

json
{
  "type": "step|schedule|metrics|sync|state|artifacts",
  "run_id": "string",
  "ts_ms": 1700000000123,
  "payload": {}
}

事件类型

type触发时机payload 关键字段
state状态变更id, status, scenario_id, strategy_id, mode, steps, dt_seconds, seed, created_at, started_at, finished_at, output_dir, error_message
step每步完成step_id
schedule调度决策执行策略决策相关字段
metrics指标更新avg_throughput_bps, avg_loss_rate, p95_delay_ms, trace_count, received_count, updated_at
sync时间同步同步精度相关字段
artifacts产物生成完毕文件列表

背压处理:服务端为每个连接维护大小为 128 的异步队列。队列满时采用 drop-oldest 策略丢弃最旧消息。


6. 错误响应格式

所有 4xx/5xx 错误遵循 FastAPI 标准格式:

json
{
  "detail": "error message string"
}

或 Pydantic 验证错误(422):

json
{
  "detail": [
    {
      "type": "value_error",
      "loc": ["body", "field_name"],
      "msg": "error description",
      "input": "invalid_value"
    }
  ]
}

7. CORS 配置

API 默认启用 CORS,允许所有来源访问:

python
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

生产环境应限制 allow_origins 为实际前端域名。


8. Pydantic Schema 对照表

所有请求/响应模型定义在 src/unet_dt/api/schemas.py,主要模型如下:

模型名用途
HealthResponseGET /health 响应
NodeHealthResponseGET /health/nodes 响应
ConfigResponseGET /config 响应
StrategyListResponseGET /strategies 响应
ScenarioMergedListResponseGET /scenarios 响应
ScenarioFullResponseGET /scenarios/{id} 响应
ScenarioCreateRequestPOST /scenarios 请求
ScenarioUpdateRequestPUT /scenarios/{id} 请求
RunCreateRequestPOST /runs 请求
RunListResponseGET /runs 响应
RunDetailResponseGET /runs/{id} 响应
RunStatusResponseGET /runs/{id}/status 响应
RunMetricsResponseGET /runs/{id}/metrics 响应
RunTracesResponseGET /runs/{id}/traces 响应
RunArtifactsResponseGET /runs/{id}/artifacts 响应
RunEventsResponseGET /runs/{id}/events 响应
LocationInitRunResponsePOST /config/location-init/run 响应
RunEventEnvelopeWebSocket 消息信封