httpstat 结构化输出与 SLO 阈值检查:`--format` / `--slo` / `--save` 设计实现深度解析
httpstat 结构化输出与 SLO 阈值检查:--format / --slo / --save 设计实现深度解析
httpstat 是一个以单个 Python 文件封装 curl、将 HTTP 请求耗时拆解为 DNS、TCP、TLS、服务器处理、内容传输等阶段的可视化诊断工具。本文围绕其"结构化输出与 SLO"能力展开:讲解 --format json/jsonl 稳定 JSON 输出的 v1 Schema、--slo 阈值判定与退出码 4 的约定、--save 文件落盘,以及 NO_COLOR 约定支持,并深入到 httpstat.py 源码与 tests/test_httpstat.py 单元测试,说明每一处设计在实现层面的落地方式。读完本文,你将能把这些参数直接用于自动化监控、CI 流水线与 Agent 诊断场景,并理解其底层数据流与边界行为。
设计背景:从"给人看"到"给机器消费"
httpstat 的定位是 curl 的计时可视化包装器:整个应用收敛在单个模块 httpstat.py 中,通过 subprocess 调用 curl,用 -w 的 curl_format(见 httpstat.py)一次性取回 time_namelookup、time_connect、time_pretransfer、time_starttransfer、time_total、speed_download、remote_ip 等 12 项原始指标,再渲染成人类友好的分阶段时序图。默认 pretty 模式的典型输出如下:
pretty 模式适合人眼阅读,但对自动化流水线、监控脚本与 AI Agent 并不友好:终端彩色文本难以稳定解析,时序图布局依赖具体 URL 是否带 https:// 前缀。此前仓库仅提供了 HTTPSTAT_METRICS_ONLY 环境变量来输出裸 JSON,粒度与结构都不够规范。
因此设计目标非常明确:在保持"单文件、零依赖、手工 sys.argv 解析"架构风格不变的前提下,新增三类机器友好能力:
--format json/--format jsonl:输出带稳定schema_version的结构化 JSON,取代对终端文本的脆弱解析;--slo key=value,...:声明响应时间阈值,超限时以固定退出码 4 失败,天然适配 CI 门槛与告警脚本;--save path:把结构化结果写入文件,衔接多步工作流;- 同时按 no-color.org 约定支持
NO_COLOR,保证管道场景输出干净无 ANSI 转义。
新参数体系一览
--format、--slo、--save 三个标志在 print_help() 中的完整说明如下:
-f --format output format: pretty, json, jsonl. Default is `pretty`.
--slo SLO thresholds as key=value pairs, e.g. `total=500,connect=100`.
Valid keys: total, connect, ttfb, dns, tls.
Exits with code 4 on violation.
--save save structured output to a file path.
结合源码可归纳为下表:
| 参数 | 短形式 | 取值/默认 | 作用 |
|---|---|---|---|
--format |
-f |
pretty(默认)、json、jsonl |
控制输出形态;非法取值直接报错退出(码 1) |
--slo |
无 | 形如 total=500,connect=100 的字符串 |
解析为阈值字典,超限后退出码置为 4 |
--save |
无 | 文件路径字符串 | 将结构化 JSON 写入指定文件,支持任意 --format |
NO_COLOR |
— | 环境变量,只要存在即生效 | 禁用全部彩色输出(无需特定取值) |
值得注意的兼容性细节:当 HTTPSTAT_METRICS_ONLY=true 且未显式指定 --format 时,输出格式会被自动提升为 json(见 httpstat.py),即旧环境变量成为 --format json 的别名,向后兼容旧脚本。
手工参数解析:pop_arg 的设计
新标志的解析刻意没有引入 argparse,而是延续仓库既有的手工 sys.argv 风格。核心是 pop_arg():
def pop_arg(args: list[str], flag: str, has_value: bool = True) -> str | bool | None:
"""Remove flag (and its value if has_value) from args list in-place.
Returns the value string, True (for valueless flags), or None if not found.
"""
if flag not in args:
return None
idx = args.index(flag)
if has_value:
if idx + 1 >= len(args):
return None # flag at end with no value
args.pop(idx) # remove flag
return args.pop(idx) # remove and return value
else:
args.pop(idx)
return True
它在原列表上"原地弹出"标志及其值,因此剩余参数可以原封不动地继续传给 curl,不会破坏既有的 httpstat URL <a href="https://link.gitcode.com/i/ac4132901fe20524cddd4de32c956c6e" target="_blank">CURL_OPTIONS] 传参模型。在 [main() 中一次性取出三个标志:
output_format = pop_arg(args, '--format') or pop_arg(args, '-f') or 'pretty'
slo_spec = pop_arg(args, '--slo')
save_path = pop_arg(args, '--save')
几个边界行为值得注意,并都有对应的单元测试:
- 标志位于末尾且缺值(
<a href="https://link.gitcode.com/i/223310948117401cb103264229afa47e" target="_blank">'https://example.com', '--format'])时返回None,随后output_format回落到pretty,而不是崩溃([tests/test_httpstat.py); - 无值标志(
has_value=False)返回布尔True,用于未来扩展布尔开关; - 多个标志连续出现时可依次弹出而不影响 URL 位置(tests/test_httpstat.py)。
--format json / jsonl:稳定 v1 Schema 的结构化输出
格式校验与旧环境变量兼容
标志弹出后,main() 对格式做白名单校验:
if output_format not in ('pretty', 'json', 'jsonl'):
_exit(f'Error: invalid format "{output_format}", must be pretty, json, or jsonl', 1)
json 与 jsonl 的唯一差异在于序列化缩进:json 使用 json.dumps(result, indent=2) 输出可读的多行 JSON,jsonl 使用紧凑单行输出(见 httpstat.py),便于直接追加到日志管道。E2E 测试以"输出恰好 1 行"来验证 jsonl 的形态(httpstat_test.sh)。
v1 JSON Schema 结构
--format json 的完整输出结构(示例来自 README.md 的 Structured Output 章节):
{
"schema_version": 1,
"url": "httpbin.org/get",
"ok": true,
"exit_code": 0,
"response": {
"status_line": "HTTP/2 200",
"status_code": 200,
"remote_ip": "...",
"remote_port": "443",
"headers": {"Content-Type": "application/json", "Server": "nginx", "...": "..."}
},
"timings_ms": {
"dns": 5, "connect": 10, "tls": 15,
"server": 50, "transfer": 20, "total": 100,
"namelookup": 5, "initial_connect": 15,
"pretransfer": 30, "starttransfer": 80
},
"speed": { "download_kbs": 1234.5, "upload_kbs": 0.0 },
"slo": null
}
顶层字段语义:
schema_version:恒为 1,是消费方做结构兼容判断的锚点(E2E 测试断言其存在,见 httpstat_test.sh);url:本次请求的目标地址(原样传入的字符串);ok:exit_code == 0的布尔派生值;exit_code:进程实际退出码,SLO 失败时为 4;response:状态行、状态码、远端 IP/端口,以及解析后的响应头字典;timings_ms:十个耗时字段,单位统一为毫秒(详见下一节);speed:download_kbs与upload_kbs,由 curl 返回的每秒字节数除以 1024 后保留一位小数(httpstat.py);slo:未指定--slo时为null,指定后为{"pass": bool, "violations": [...]}。
timings_ms 的十字段语义:区间值与累计值
这是结构化输出中最容易混淆、也最有信息量的一组字段,实现于 build_json_result()。十个字段分为两类:
区间值(每个阶段独立耗时,可直接相加约等于 total):
| 字段 | 计算方式(源码) | 含义 |
|---|---|---|
dns |
range_dns = time_namelookup |
DNS 解析耗时 |
connect |
range_connection = time_connect - time_namelookup |
TCP 握手耗时(不含 DNS) |
tls |
range_ssl = time_pretransfer - time_connect |
TLS 握手耗时(不含 DNS/TCP) |
server |
range_server = time_starttransfer - time_pretransfer |
服务器处理耗时(TTFB 前) |
transfer |
range_transfer = time_total - time_starttransfer |
内容传输耗时(首字节后) |
累计值(从请求开始计时的瀑布时间点):namelookup、initial_connect、pretransfer、starttransfer、total 分别对应 curl 原生计时器 time_namelookup、time_connect、time_pretransfer、time_starttransfer、time_total。其中 initial_connect 是"DNS + TCP"的累计值,与区间字段 connect 语义不同——这正是 skills/httpstat/SKILL.md 中强调"range 字段衡量各阶段独立耗时、累计字段衡量请求开始以来的经过时间"的原因。
区间值在 main() 中通过原生计时器做差得到:
d.update(
range_dns=d['time_namelookup'],
range_connection=d['time_connect'] - d['time_namelookup'],
range_ssl=d['time_pretransfer'] - d['time_connect'],
range_server=d['time_starttransfer'] - d['time_pretransfer'],
range_transfer=d['time_total'] - d['time_starttransfer'],
)
时间单位换算的前提与限制
curl 返回的 time_* 值存在两种历史单位,main() 做了统一换算:
if isinstance(v, float):
# Before 7.61.0, time values are represented as seconds in float
d[k] = int(v * 1000)
elif isinstance(v, int):
# Starting from 7.61.0, libcurl uses microsecond in int
d[k] = int(v / 1000)
即 curl 7.61.0 之前是秒(浮点),之后是微秒(整数),统一转成毫秒整数后进入 timings_ms。这是结构化输出的重要前提:JSON 中所有耗时均为毫秒整数,消费方无需关心底层 curl 版本差异。
--slo 阈值检查:从字符串到退出码 4
SLO 键映射
SLO 阈值使用人类友好的短键名,通过 SLO_KEY_MAP 映射到 curl 原生计时器:
SLO_KEY_MAP = {
'total': 'time_total',
'connect': 'time_connect',
'ttfb': 'time_starttransfer',
'dns': 'time_namelookup',
'tls': 'time_pretransfer',
}
| SLO 键 | 映射到 | 测量内容 |
|---|---|---|
dns |
time_namelookup |
DNS 解析 |
connect |
time_connect |
DNS + TCP 连接(累计) |
tls |
time_pretransfer |
DNS + TCP + TLS(累计) |
ttfb |
time_starttransfer |
首字节时间 TTFB |
total |
time_total |
完整请求 |
注意 SLO 键映射的是累计计时器而非区间值:connect=100 的阈值作用于 time_connect(含 DNS),这与 timings_ms 中的区间字段 connect 是不同的口径。单元测试 tests/test_httpstat.py 专门验证了 ttfb 取 time_starttransfer、tls 取 time_pretransfer 的映射行为。
parse_slo:严格校验的解析器
parse_slo() 把 'total=500,connect=100' 解析为 {'total': 500, 'connect': 100},并在任何非法输入上直接报错退出:
def parse_slo(spec: str) -> dict[str, int]:
"""Parse 'total=500,connect=100' → {'total': 500, 'connect': 100}.
Exits with error on invalid input.
"""
result = {}
for part in spec.split(','):
part = part.strip()
if not part:
print(f'Error: empty SLO spec')
sys.exit(1)
if '=' not in part:
print(f'Error: invalid SLO spec "{part}", expected key=value')
sys.exit(1)
key, _, val = part.partition('=')
key = key.strip()
val = val.strip()
if key not in SLO_KEY_MAP:
valid = ', '.join(SLO_KEY_MAP.keys())
print(f'Error: unknown SLO key "{key}", valid keys: {valid}')
sys.exit(1)
try:
ms = int(val)
except ValueError:
print(f'Error: SLO value for "{key}" must be a positive integer, got "{val}"')
sys.exit(1)
if ms <= 0:
print(f'Error: SLO value for "{key}" must be positive, got {ms}')
sys.exit(1)
result[key] = ms
return result
校验规则可归纳为四条,且每一条都有对应单元测试(tests/test_httpstat.py):
- 键必须是
SLO_KEY_MAP中的合法键,未知键(如badkey=100)报错退出; - 值必须能转成整数,
total=abc报错; - 值必须为正整数,
total=0与total=-1均报错; - 空片段、缺少
=的片段(如total)、整体空字符串均报错。
同时解析器对键与值都做 strip(),因此 ' total = 500 , connect = 100 ' 这类带空格写法也能正确解析(tests/test_httpstat.py)。
check_slo:恰好等于阈值视为通过
check_slo() 返回 (是否通过, 违规列表):
def check_slo(slo: dict[str, int], timings: dict) -> tuple[bool, list[dict]]:
"""Check timings against SLO thresholds.
Returns (pass, violations). Each violation: {'key': ..., 'threshold_ms': ..., 'actual_ms': ...}
"""
violations = []
for key, threshold in slo.items():
timing_key = SLO_KEY_MAP[key]
actual = timings[timing_key]
if actual > threshold:
violations.append({
'key': key,
'threshold_ms': threshold,
'actual_ms': actual,
})
return (len(violations) == 0, violations)
判定条件是 actual > threshold(严格大于才算违规),因此恰好等于阈值视为通过——这个边界语义由 tests/test_httpstat.py 的 test_exactly_at_threshold_passes 显式固化。每条违规记录携带 key、threshold_ms、actual_ms 三个字段,可直接供告警系统格式化输出。
退出码 4 的约定与两种呈现方式
在 main() 中,SLO 检查结果被转换为退出码:
slo_result = check_slo(slo, d) if slo else None
exit_code = 0
if slo_result and not slo_result[0]:
exit_code = 4
退出码 4 是固定的机器约定:--slo total=1(1ms 阈值必然失败)在 E2E 测试中被断言返回码恰为 4(httpstat_test.sh)。
违规信息有两种呈现路径:
- pretty 模式:在时序图之后打印红色警告行,格式为
SLO VIOLATION: {key} = {actual}ms (threshold: {threshold}ms)(httpstat.py); - json / jsonl 模式:写入
slo字段,形如:
{
"slo": {
"pass": false,
"violations": [
{ "key": "total", "threshold_ms": 500, "actual_ms": 823 }
]
}
}
配合 ok: false 与 exit_code: 4,消费方无需解析终端文本即可判断是否达标。
--save:结构化结果落盘
--save 在两种模式下行为略有差异(httpstat.py 与 httpstat.py):
- json/jsonl 模式:
output_text(含缩进或紧凑序列化)写入文件后立即以exit_code退出; - pretty 模式:终端仍打印人类可读的时序图,但文件里写入的是等价的
json.dumps(result, indent=2)结构化结果。
也就是说,--save 与 --format 正交:即使终端展示 pretty 文本,落盘内容也始终是结构化 JSON,便于"人看终端、机器读文件"的混合工作流。README 中的典型组合用法:
httpstat httpbin.org/get --save result.json
httpstat httpbin.org/get --format json --save result.json
E2E 测试验证了 --save /tmp/...json 后文件可被 json.load 且包含 schema_version(httpstat_test.sh)。
NO_COLOR:按 no-color.org 约定禁用彩色输出
模块级颜色开关 ISATTY 同时考虑终端与 NO_COLOR:
ISATTY = sys.stdout.isatty() and 'NO_COLOR' not in os.environ
其语义完全遵循 no-color.org 判断 ISATTY:
def make_color(code):
def color_func(s):
if not ISATTY:
return s
return f'\x1b[{code}m{s}\x1b[0m'
return color_func
当 ISATTY 为假时直接原样返回字符串,不产生任何 ANSI 转义。单元测试分别用 monkeypatch.setenv('NO_COLOR', '') 与 monkeypatch.setattr(httpstat, 'ISATTY', ...) 验证了空值 NO_COLOR 同样生效、以及颜色包装函数的开/关行为(tests/test_httpstat.py)。E2E 测试则通过检查输出中不存在 \x1b<a href="https://link.gitcode.com/i/cc6ee2ff09e7e4cb06a6f75cf395190a" target="_blank"> 字节序列来端到端验证([httpstat_test.sh)。日常用法:
NO_COLOR=1 httpstat httpbin.org/get
build_json_result 源码走读:从响应头到 JSON
v1 Schema 构造函数 的输入是 URL、curl 计时字典 d、响应头文本、SLO 结果与退出码,输出最终 JSON。几个关键解析细节:
- 状态行与状态码:取响应头首行,去掉尾部
\r,按空白切分提取第二段作为status_code——因此HTTP/2 200与HTTP/1.1 301 Moved Permanently都能正确解析(tests/test_httpstat.py 覆盖了 HTTP/1.1 301 用例);解析失败时状态码回落为 0; - 响应头字典:跳过状态行后按
key: value切分剩余行,同名头(如多个Set-Cookie)后值覆盖前值; ok字段:由exit_code == 0派生,SLO 失败(exit_code=4)时ok为false(tests/test_httpstat.py 验证了这一联动);- 可序列化保证:整个结果字典可直接
json.dumps而不抛异常(tests/test_httpstat.py)。
main() 集成流程:九个步骤的落地全貌
把上述组件串起来,main() 的完整流程与计划文档(kb/plans/format-option.md)中的设计步骤一一对应:
- 弹出
--format/--slo/--save,保留剩余参数给 curl(httpstat.py); - 读取并解析全部
HTTPSTAT_*环境变量(含HTTPSTAT_METRICS_ONLY,httpstat.py); - 旧环境变量向后兼容转换 + 格式白名单校验(httpstat.py);
parse_slo解析阈值(httpstat.py);- 组装 curl 命令并执行:
curl -w <format> -D <headerf> -o <bodyf> -s -S <curl_args> <url>(httpstat.py),同时保留LC_ALL=C环境以规避逗号小数(俄语 locale 等)导致的解析问题,这一点由 E2E 的LC_ALL=ru_RU用例覆盖(httpstat_test.sh); - 时间单位统一换算为毫秒(curl 7.61.0 前后差异);
- 计算五个区间值;
check_slo判定并决定exit_code(0 或 4);- 按
output_format三分支输出:pretty(原有逻辑 + 红色 SLO 警告)、json(缩进 2)、jsonl(紧凑单行),--save在此写文件,最终sys.exit(exit_code)。
值得一提的既有保护逻辑:curl 侧 -w、-D、-o、-s 属于 httpstat 内部占用的选项,用户传入会直接报错拒绝(httpstat.py),这保证了计时格式、响应头与正文文件的归属不会被用户参数破坏。
测试体系:单元测试 + E2E 双轨验证
单元测试(pytest)
新增的 tests/test_httpstat.py 以 pytest 组织,覆盖六个测试类,与设计步骤逐一对应:
| 测试类 | 覆盖对象 | 关键用例 |
|---|---|---|
TestParseBool |
parse_bool() |
truthy/falsy 值集合、非法值抛 ValueError |
TestPopArg |
pop_arg() |
长/短标志、无值标志、缺失标志、末尾缺值、多标志连续弹出 |
TestParseSlo |
parse_slo() |
全部合法键、未知键/非整数/非正数/空串均 SystemExit、空格修剪 |
TestCheckSlo |
check_slo() |
全部通过、单/多违规、恰好等于阈值通过、ttfb/tls 映射 |
TestBuildJsonResult |
build_json_result() |
schema_version、响应字段、timings_ms、speed、slo 各分支、HTTP/1.1 状态行、可序列化 |
TestNoColor |
NO_COLOR/make_color |
空值 NO_COLOR 生效、ISATTY 开关控制颜色包装 |
依赖管理上,pytest 被声明在 pyproject.toml 的 [dependency-groups] dev 组(pytest>=8.4.2),计划文档中的 uv add --dev pytest 对应此配置。
E2E 测试(bash)
httpstat_test.sh 在既有用例基础上新增五组端到端断言(httpstat_test.sh):
--format json输出可被json.load且schema_version == 1;--format jsonl输出恰好 1 行;--slo total=1退出码为 4;--save写出的文件可反序列化并含schema_version;NO_COLOR=1输出不含 ANSI 转义;HTTPSTAT_METRICS_ONLY=true输出可被json.load(向后兼容回归)。
仓库 Makefile 提供 make test 一键运行 bash httpstat_test.sh。
验证命令(来自计划文档)
# Unit tests
uv run pytest tests/ -v
# E2E tests
bash httpstat_test.sh
# Manual smoke tests
python httpstat.py https://example.com
python httpstat.py https://example.com --format json
python httpstat.py https://example.com --format json --slo total=100
python httpstat.py https://example.com --format json --save /tmp/out.json
NO_COLOR=1 python httpstat.py https://example.com
文档与 Agent 生态的联动
新参数在仓库文档中形成了完整的说明闭环:命令行为说明见 print_help() 的 Options 与 Environments 段落;完整 JSON 示例与 SLO 用法见 README.md 的 Structured Output、SLO Thresholds、Save Results 章节;面向 AI Agent 的 skills/httpstat/SKILL.md 则把 --format json 作为推荐的分析输出、把 --slo 作为持续监控手段,并给出了 5 个 SLO 键的语义对照表——三者共同把"结构化输出 + 阈值判定"沉淀为可复用的诊断工作流。
适用前提与限制
- 所有
timings_ms均为毫秒整数,换算逻辑依赖 curl 版本判定(< 7.61.0 秒转毫秒、≥ 7.61.0 微秒转毫秒),实际使用时应保持 curl 版本稳定; --slo的connect、tls键作用于累计计时器(含 DNS),与timings_ms中同名的区间字段语义不同,设置阈值前务必区分;- SLO 违规退出码固定为 4,且恰好等于阈值不算违规;
--save在 pretty 模式下落盘内容仍为 JSON,只有终端呈现是文本; NO_COLOR遵循"存在即禁用"约定,空值也生效。
从 kb/plans/format-option.md 的设计蓝图到 httpstat.py 的落地实现,--format json / --slo / --save 与 NO_COLOR 共同构成了 httpstat 面向自动化流水线的最小完整能力集:稳定的 v1 Schema 保证可解析,固定退出码 4 保证可判定,文件落盘保证可衔接多步任务,无 ANSI 保证管道干净。这套设计既服务于 CI 质量门槛,也为 AI Agent 提供了"先量化、再诊断、后监控"的完整闭环。
