commit 26cdd4b5c13044c0cd182a723c0bfeeaa1f0e450 Author: WbiubiuW Date: Tue Sep 22 14:28:45 2026 +0800 feat: Python(Locust) + Go(boomer) 混合压测框架(演示版) diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..286a8b4 --- /dev/null +++ b/.gitignore @@ -0,0 +1,7 @@ +bin/ +.pids/ +__pycache__/ +.pytest_cache/ +*.pyc +*.log +.DS_Store diff --git a/README.md b/README.md new file mode 100644 index 0000000..03c1c5b --- /dev/null +++ b/README.md @@ -0,0 +1,219 @@ +# perf-harness-demo —— Python / Go 混合压测实验台 + +用一个**可复现的小规模实验台**,验证压测工程里最容易出错的三条判断。 + +同一个本机 mock 服务,分别用 **Python worker(Locust 原生)** 和 **Go worker(boomer)** 施压, +统计口径统一,产出两者的 TPS / 延迟对比报告。所有数字都由本仓库自己跑出来,随时可复跑。 + +--- + +## 先说结论 + +本仓库跑出来的东西是三张表、三条判断。数字取自 `report.md`(本机单机实测): + +| # | 判断 | 怎么验出来的 | 实测 | +|---|---|---|---| +| ① | **工具选型要能被证伪**,不是选"最好的" | 同并发、同场景、同请求体,只换 worker | Go 的 TPS ≈ **Python 的 4 倍**(多次复跑 3.9–4.2×) | +| ② | **压测脚本的失真比被测系统的 bug 更隐蔽** | 条件单触发价「写死」vs「缓存服务实时驱动」 | 写死:**100% / 0%**;缓存驱动:**≈50%**(历次 48–55%)。三组**失败数全为 0** | +| ③ | **瓶颈要定位到"谁不够",而不是"慢"** | 给 mock 设单实例上限,对比 1 / 4 实例 | 1 实例封顶 **≈500 TPS**、P95 200ms → 4 实例 **≈2000 TPS**、P95 ≈50ms(**≈4×**) | + +绝对数字随机器与负载波动,以 `report.md` 里的当轮实测为准;**稳定的是倍数差与瓶颈归属**。 + +②是全篇最值钱的一条:写死触发价的两个相位,**HTTP 全 200、失败数 0、延迟正常** —— +报表上挑不出任何毛病,但触发率塌缩到 0% 和 100%,这批数据对容量评估毫无意义。 +「数据是错的,但看起来是对的」。 + +--- + +## 这不是什么 + +先讲清楚,免得被误读: + +- **这不是生产系统**,也不是任何线上系统的代码。它是一个**实验台**:把三条工程判断做成可运行、可复跑的最小装置。 +- **它不追求压出高 TPS**。本机单机压测的量级(几千 TPS)和生产环境没有可比性 —— + 可比的是**同一台机器上的倍数差**和**瓶颈在哪一层**,这才是要证明的东西。 +- **只压本机 `127.0.0.1` 的 mock**,不连任何真实服务、绝不对外发压。 + +--- + +## 快速开始 + +**依赖** + +| 项 | 版本 | 用于 | +|---|---|---| +| Python | 3.9+ | 全部 | +| [locust](https://locust.io) | 2.x | 压测(Python worker / master) | +| pytest | — | 仅跑单测(单测不依赖 locust) | +| Go | 1.21+ | 编译 Go worker(本机 go1.25 验证通过) | + +```bash +python3 -m pip install locust pytest +``` + +> macOS 上 `python3` 常指向一个没装这些包的解释器。确认一下: +> `python3 -c "import locust, pytest"` 不报错再往下走;否则换成你实际装了依赖的那个解释器 +> (本机是 `~/miniconda3/bin/python3`)。 + +**跑一遍** + +```bash +bash run.sh target # 起本机 mock(HTTP :18099) +bash run.sh python --users 50 --duration 60s # 判断①:Python worker +bash run.sh go --users 50 --duration 60s # 判断①:Go worker(master/slave) + +python3 scenarios/verify_trigger.py # 判断②:写死 vs 缓存驱动,一次跑完两组 + +bash run.sh scale-1 # 判断③:1 实例 +bash run.sh scale-4 # 判断③:4 实例 + +bash run.sh report # 汇总 results/*.json → report.md +``` + +每条压测命令都会往 `results/` 落一份 JSON,报告的数字**只从这些 JSON 里读**,不手写。 + +**验证** + +```bash +python3 -m pytest tests/ -q # 21 passed +(cd go && go test ./...) # Go 侧:连接池断言 +``` + +单测钉住的是最容易做假、且做假了没人看得见的语义:滑动窗口去重(含 A-B-A 交替)、 +断流回退、触发判定方向、限流器、分流器、连接池断言。 + +--- + +## 架构 + +``` + run.sh python run.sh go + ───────────── ────────── + Locust 单进程直跑 Locust master(控制面 + 统计汇总) + (不经 master) │ ZMQ :5557 + │ ▼ + │ Go worker (boomer slave) + │ goroutine × N + │ │ + └──────────────┬──────────────────────┘ + │ HTTP /api/v1/order/...(同场景、同请求体) + ▼ + ┌──────────────────────┐ + │ HTTP mock :18099│ 条件单 endpoint + TARGET_MAX_QPS 上限 + └──────────┬───────────┘ + ▲ 行情轮询 + ┌──────────┴───────────┐ ┌────────────────────────┐ + │ mark_price_service │ │ dispatcher :18100│ + │ :18097 标记价缓存 │ │ 扩展实验的入口分流 │ + └──────────────────────┘ └────────────────────────┘ +``` + +两种 worker 的统计都汇到同一个 Locust master,保证**同口径出数**。 +任务表是配置驱动的(`python/locustfile.py` 的 `TASK_WEIGHTS`、`go/tasks.go` 的 `taskTable()`), +增删任务不动框架。 + +--- + +## 关键技术点 + +1. **GIL 取舍**:Python 单进程内所有协程共享一个 GIL,JSON 编解码、locust 统计、gevent 调度 + 都是纯 CPU 段,并发上去单核打满、TPS 触顶。Go 的 goroutine 由 runtime 多线程调度、 + 网络 I/O 走 netpoller,没有这个天花板。 + +2. **连接池调优必须落在"真身"上**:手写 `http.Transport` 时,参数很容易落在一个 + **从未被 `client.Transport` 引用**的变量上 —— 于是默认的 `MaxIdleConnsPerHost=2` 生效, + 压不上去,却极易被误归因到被测服务。`TestTransportPool` **断言 client 实际使用的 + transport 就是调优过的那个**,把「我调优了」从错觉变成事实。 + +3. **标记价缓存的两条硬语义**(`target/mark_price_service.py`,由 `tests/` 钉死): + - **滑动窗口去重**:窗口必须保存最近两个**已接受**的价格。只存"最后一个值"的伪窗口 + 识别不了 A-B-A 交替重复(100→105→100 时第三笔会被误判为新变化),等于没去重。 + - **断流回退**:行情源挂掉时**回退默认价继续出价**,不是报错退出 —— 压测不能中断。 + +4. **单实例上限要可测量**:mock 支持 `TARGET_MAX_QPS`(超限请求排队等位,表现为 TPS 封顶 + + 延迟上升,而**不是**错误率上升)与 `TARGET_EXTRA_LATENCY_MS`。`run.sh scale-N` 起 N 个实例 + + 入口分流器,用**除实例数外完全一致**的参数对比 —— 扩展是有依据的决策,不是"感觉慢了加机器"。 + +5. **boomer 与 locust 2.x 的协议补丁**(`go/third_party/boomer`,3 处,见 + [THIRD_PARTY.md](THIRD_PARTY.md)):`client_ready` data `nil → -1`;`spawn` 消息迁移到 + `user_classes_count/parsed_options`;`stats` / `spawning_complete` 上报 + `user_classes_count`(否则被当 unknown worker 踢掉)。 + +--- + +## 背景:这套东西是怎么来的 + +> 这一节讲的是**动机**,不是本仓库能提供的证据。下面那些生产数字来自我此前的合约交易系统 +> 压测经历,**本仓库不承载、也无法复现它们**;本仓库只复现方法论。 + +当时的指标是:10 个用户并发下单,下单接口 TPS 达到 10 万。用阶梯压测(1h → 2h → 4/8/12/24h) +验证长期稳定性,而不是测瞬时峰值。过程中撞了三次瓶颈: + +| # | 瓶颈 | 破局 | +|---|---|---| +| 1 | 压测脚本自己失真:条件单触发价写死 → 全触发或全不触发,整批数据作废 | 自建标记价格缓存服务:订阅行情 → 滑动窗口去重 → 本地缓存 TTL;**断流时回退默认价**保证压测不中断 | +| 2 | Python GIL:Locust 动态参数灵活,但单机打不满并发 | 用 Go + boomer 重写压力机,Python 只留 Locust master 做控制;另用 gRPC 客户端直压绕过 HTTP 层(**这条 gRPC 通道本仓库没有复刻**) | +| 3 | 单服务集群上限约 12000,撑不起指标 | 横向扩展:把委托/结算/权益、撮合/风控、入口按服务拆分,各自独立扩容 | + +结果:10 用户并发、平均响应 1-2s、24h 稳定运行、实测 10-12 万 TPS。 + +**工具选型的试错路径**(JMeter → Locust → Go + boomer): + +| 方案 | 为什么没走到最后 | +|---|---| +| JMeter | 参数化机制很难表达「按实时行情动态触发」,要写复杂预处理器 | +| Locust(Python) | 用代码表达动态参数很自然,但受 GIL 限制,单机并发有瓶颈 | +| **Go + boomer 重写 worker** | 保住动态参数的灵活性,同时突破并发瓶颈 —— 最终选它 | + +**一个取舍**:换引擎不难,难的是选对切换时机。第一轮交付沿用原方案保进度, +把调研结论整理成文档同步给团队,后续轮次才切到 Go 方案。 + +**另一条经验**:本机压测会撞到多层瓶颈(mock 网关、loopback、worker 自身)。 +归因时必须说清「这次测出来的瓶颈在哪一层」—— 能定位瓶颈比能跑高 TPS 更值钱。 + +--- + +## 目录 + +``` +python/locustfile.py Python worker(4 类订单请求,权重 4:2:2:1) +python/master_locustfile.py Go 压测时的 master 入口(复用统计落盘) +python/stats_dump.py 统计落盘(results/*.json) +go/ boomer worker(编译产物压测,非 go run) +go/third_party/boomer/ vendored boomer v1.6.0 + locust 2.x 协议补丁(MIT) + 仅保留编译所需文件,见 THIRD_PARTY.md +target/http_server.py 本机被测 mock(:18099;条件单 endpoint + + 可配置单实例上限 TARGET_MAX_QPS / TARGET_EXTRA_LATENCY_MS) +target/mark_price_service.py 标记价格缓存服务(:18097) +target/dispatcher.py 入口分流器(:18100),扩展实验用 +scenarios/verify_trigger.py 失真对比实验(写死 vs 缓存驱动,一次跑完两组) +tests/ 21 条单测(去重 / 断流回退 / 触发判定 / 限流 / 分流) +compare.py 报告生成器(数字只来自 results/) +results/ 原始 JSON +report.md 对比报告(由 compare.py 生成) +``` + +--- + +## 边界与口径 + +- 只压本机 mock(`127.0.0.1`),**绝不对外发压**。 +- 报告里的数字**必须真实跑出**;`compare.py` 只读 `results/*.json`。 +- 两种 worker 必须**同场景、同并发、同请求体**;扩展实验除实例数外参数必须完全一致。 +- 接口路径与合约 ID 均为中性自造值,无凭据、无真实域名。 +- **口径分栏**:本仓库跑出的数字一律属「**本机演示实测**」;「背景」一节提到的历史业绩属 + 「**生产真实业绩**」,只作动机,本仓库不提供其证据。两者**不可混写**,也不可互相换算。 + +--- + +## 第三方 + +`go/third_party/boomer` 是 [boomer](https://github.com/myzhan/boomer) v1.6.0 的 vendored 副本 +(MIT License, Copyright (c) 2019 myzhan),其上打了 3 处 locust 2.x 协议补丁。 +许可证与补丁明细见 [THIRD_PARTY.md](THIRD_PARTY.md)。 + +副本**只保留了编译与运行所需的 15 个文件**(13 个 `.go` + `go.mod` + `LICENSE`); +上游自带的 `examples/`、`docs/`、自测与 CI 配置已移出(本项目从不引用)。 +保留文件的内容未做任何改动(3 处协议补丁除外)。 + +本仓库自身的 LICENSE 尚未选定 —— 若要公开,需要先补一个。 diff --git a/THIRD_PARTY.md b/THIRD_PARTY.md new file mode 100644 index 0000000..3a9cd23 --- /dev/null +++ b/THIRD_PARTY.md @@ -0,0 +1,68 @@ +# 第三方组件与补丁 / Third-party Components & Patches + +## boomer v1.6.0 + +| 项 | 值 | +|---|---| +| 名称 | boomer(Locust 的 Go 兼容实现,用 Go 写 Locust worker) | +| 版本 | v1.6.0 | +| 上游 | https://github.com/myzhan/boomer | +| 许可证 | **MIT License, Copyright (c) 2019 myzhan** | +| 本地位置 | `go/third_party/boomer/` | +| 引入方式 | vendored 源码副本;`go/go.mod` 里用 `replace github.com/myzhan/boomer => ./third_party/boomer` 指过来 | + +`LICENSE` 原样保留在 `go/third_party/boomer/LICENSE`,未做任何修改。 + +## 为什么 vendored + +上游 boomer v1.6.0 只兼容 **locust 1.x** 的 master/slave 通信协议,而本项目的 +Locust master 是 **2.x**。不改协议就没法握手,因此把源码放进仓库直接打补丁。 + +## 关于裁剪(2026-09-22) + +上游仓库是整仓复制过来的,其中大部分文件与「编译出一个 Go worker」无关。 +本项目**只保留编译与运行所需的文件**(15 个:13 个 `.go` + `go.mod` + `LICENSE`), +移出了上游自带的 `examples/`、`docs/`、`_test.go`、`README*.md`、CI 配置等约 50 个文件。 + +- 移出的都是**上游自带的示例、文档与自测**,本项目从不引用、也从不运行它们 + (`third_party/boomer` 是独立 module,`go test ./...` 不会进入)。 +- **没有改动任何被保留文件的内容**(3 处协议补丁除外,见下节)。 +- 判据:裁剪前后 `go build` 产出的二进制 **md5 完全一致**,`go mod verify` 通过。 +- 若要对照上游原文,去 https://github.com/myzhan/boomer 取 v1.6.0 全量源码即可。 + +## 打了哪 3 处补丁 + +全部集中在 `runner.go`(另 `message.go` 有配套小改),补丁位置按行号列出,便于日后 +升级 boomer 时对照重打。 + +| # | 位置 | 改了什么 | 为什么 | +|---|---|---|---| +| 1 | `runner.go:463`、`runner.go:516` | `newMessage("client_ready", nil, ...)` → `newMessage("client_ready", -1, ...)` | locust 2.x 约定用 `-1` 表示「跳过版本检查」;传 `nil` 会被拒绝 | +| 2 | `runner.go:337-342`、`runner.go:259/314/526` | `spawn` 消息从旧的 `num_users` / `spawn_rate` 迁移到 `user_classes_count` / `parsed_options` | locust 2.x 改了 spawn 消息结构,旧字段被忽略 | +| 3 | `runner.go:259/314/526`、`runner.go:315` | `stats` 与 `spawning_complete` 上报 `user_classes_count`(`{"BoomerWorker": numClients}`) | 不上报会被 master 当成 unknown worker 踢掉,表现为「连上了但不发压」 | + +> 三处都不改动 boomer 的业务逻辑,只补协议字段 —— 属于「让它能接上 2.x master」的最小改动。 + +## 如何验证补丁在位 + +```bash +cd go/third_party/boomer + +# 补丁 1 +grep -n 'client_ready' runner.go # 期望看到 -1,而不是 nil + +# 补丁 2 + 3 +grep -n 'user_classes_count' runner.go # 期望 5 处命中: + # 259 / 314 / 526 = 赋值上报 + # 337 = 说明注释,342 = 读取 spawn 消息里的值 + +# 补丁 3 +grep -n 'spawning_complete' runner.go +``` + +端到端验证(起 master 与 go worker,看 worker 是否被认领并出数): + +```bash +bash run.sh target +bash run.sh go --users 50 --duration 60s # 若协议不通,master 会一直等 worker +``` diff --git a/compare.py b/compare.py new file mode 100644 index 0000000..20c3c03 --- /dev/null +++ b/compare.py @@ -0,0 +1,211 @@ +#!/usr/bin/env python3 +"""perf-harness-demo 对比报告生成器。 + +用法:python3 compare.py results/*.json → 输出 markdown 到 stdout +(run.sh / 验收命令里重定向为 report.md) + +报告内容:负载参数核对(公平性)→ worker 指标对比 → 归因分析 +→ 失真对比实验(触发率)→ 横向扩展实验(TPS vs 实例数)。 +所有数字来自 results/ 下真实跑出来的 JSON,不编造。 +""" + +import json +import re +import sys + + +def load(paths): + runs = [] + for p in sorted(paths): + with open(p) as f: + d = json.load(f) + d["_file"] = p + runs.append(d) + return runs + + +def fmt_pct(num, den): + return f"{100.0 * num / den:.2f}%" if den else "0.00%" + + +def _section_trigger(out, trigger_runs): + """§5 失真对比实验:写死触发价 vs 缓存服务驱动 的触发率对照。""" + latest = {} + for r in trigger_runs: + latest[r["trigger"]["mode"]] = r # 文件按时间排序,后者覆盖前者 = 最近一轮 + out.append("## 5. 失真对比实验(条件单触发率)\n") + out.append("两种脚本打**同一个**条件单 endpoint(`POST /api/v1/order/condition/open`)," + "负载参数相同,唯一变量是**触发价的来源**。mock 标记价随时间波动" + "(contract 1 ≈ 31000 ± 1%)。\n") + out.append("| 脚本 | 相位 | 触发价策略 | 请求数 | 失败 | 触发数 | 触发率 |") + out.append("|---|---|---|---|---|---|---|") + for mode in ("stale", "live"): + r = latest.get(mode) + if not r: + continue + for ph in r["trigger"]["phases"]: + out.append(f"| {r['worker']} | {ph['name']} | {ph['detail']} | " + f"{ph['requests']} | {ph['failures']} | {ph['triggered']} | " + f"{ph['trigger_rate']:.2%} |") + out.append("") + stale, live = latest.get("stale"), latest.get("live") + out.append("**判读**:") + out.append("- 所有相位失败数都是 0 —— 单看压测报表(TPS / 错误率 / 延迟)," + "**每一轮都「一切正常」**。") + if stale: + rates = " 与 ".join(f"{ph['trigger_rate']:.0%}" + for ph in stale["trigger"]["phases"]) + out.append(f"- 但写死触发价的相位触发率塌缩到 **{rates}**:市场状态稍偏离" + "写死的值,结论整个翻转 —— 这批数据对条件单链路的容量评估毫无意义," + "而报表上看不出任何问题(「数据是错的,但看起来是对的」)。") + if live: + rate = live["trigger"]["phases"][0]["trigger_rate"] + out.append(f"- 缓存服务实时驱动的触发率为 **{rate:.2%}**,落在由行情波动决定的" + "中间区间(不退化到 0/1),压测数据才对触发链路有评估意义。") + out.append("- 缓存服务的滑动窗口去重 / 断流回退语义由 " + "`tests/test_mark_price_service.py` 钉死;触发判定方向由 " + "`tests/test_condition_trigger.py` 钉死。") + out.append("") + + +def _section_scale(out, scale_runs): + """§6 横向扩展实验:TPS 随实例数变化(除实例数外参数完全一致)。""" + latest = {} + for r in scale_runs: + m = re.match(r"scale-(\d+)$", r["worker"]) + if m: + latest[int(m.group(1))] = r + if not latest: + return + out.append("## 6. 横向扩展实验(单实例上限 → 多实例)\n") + out.append("被测 mock 设了单实例能力上限(`TARGET_MAX_QPS`,超限请求排队等位、" + "延迟上升),入口分流器轮询分发。各组实验**除实例数外参数完全一致**" + "(worker / 并发 / 时长 / 单实例上限,见「参数」列)。\n") + out.append("| 实例数 | 请求数 | 错误率 | TPS | P50 (ms) | P95 (ms) | P99 (ms) | 参数 |") + out.append("|---|---|---|---|---|---|---|---|") + for n in sorted(latest): + r = latest[n] + t = r["total"] + out.append(f"| {n} | {t['num_requests']} | " + f"{fmt_pct(t['num_failures'], t['num_requests'])} | " + f"{t['rps']:.1f} | {t['p50']} | {t['p95']} | {t['p99']} | " + f"{r.get('label', '')} |") + out.append("") + if 1 in latest and len(latest) > 1: + base = latest[1]["total"]["rps"] + top_n = max(latest) + top = latest[top_n]["total"]["rps"] + if base > 0: + out.append(f"**{top_n} 实例 TPS / 1 实例 TPS = {top / base:.2f}**" + f"({top:.0f} vs {base:.0f};不要求线性 —— 分流器与 loopback " + "也会吃一份,TPS 随实例数上升即说明扩展是有效的)。") + out.append("- 单实例触顶时 P99 被排队显著拉高 —— 「上限」是**测出来的能力边界**," + "不是一句「慢」;扩展实例数的决策依据正是这个数字。") + out.append("") + + +def main(paths): + runs = load(paths) + # 三类结果分开渲染:worker 对比(python/go)、失真实验、扩展实验 + bench, trigger_runs, scale_runs = [], [], [] + for r in runs: + if "trigger" in r: + trigger_runs.append(r) + elif r["worker"].startswith("scale-"): + scale_runs.append(r) + else: + bench.append(r) + by_worker = {} + for r in bench: + by_worker.setdefault(r["worker"], []).append(r) + + out = [] + out.append("# perf-harness-demo 对比报告\n") + out.append(f"> 生成自 {len(runs)} 份真实压测结果:" + + ", ".join(f"`{r['_file']}`" for r in runs) + "\n") + + # ★ 数字口径:生产业绩与本机实测必须物理分栏,禁止混写(见 README §数字口径) + out.append("## 0. 数字口径(先读这一节)\n") + out.append("| 口径 | 环境 | 数字 |") + out.append("|---|---|---|") + out.append("| **生产真实业绩** | 公司环境 · 多机集群 —— **不可由本仓库复现** " + "| 10 用户并发 · 平均响应 1-2s · 24h 稳定 · 实测 10-12 万 TPS |") + out.append("| **本机演示实测** | 单机 —— 由本仓库跑出,见下方第 2 节 | 见第 2 节表格 |") + out.append("") + out.append("> 生产数字是**背景**,不是本仓库的产出。本仓库是复现方法论的实验台," + "单机量级与生产环境不可比;**可比的是 Python 与 Go 两种 worker 的倍数差**。\n") + + # 负载参数(公平性核对) + out.append("## 1. 负载参数(公平性核对)\n") + out.append("| worker | users | run_time | host |") + out.append("|---|---|---|---|") + for r in bench: + l = r["load"] + out.append(f"| {r['worker']} | {l['users']} | {l['run_time']} | {l['host']} |") + out.append("\n两种 worker 跑**同一场景、同一并发、同一请求体**(4 类订单请求," + "权重 4:2:2:1,用户池 1000),唯一变量是执行引擎。\n") + + # 指标对比 + out.append("## 2. 指标对比(每 worker 取最近一轮)\n") + out.append("| worker | 请求数 | 错误率 | TPS | P50 (ms) | P95 (ms) | P99 (ms) |") + out.append("|---|---|---|---|---|---|---|") + latest = {} + for w, rs in by_worker.items(): + latest[w] = rs[-1] + for w, r in latest.items(): + t = r["total"] + out.append(f"| {w} | {t['num_requests']} | " + f"{fmt_pct(t['num_failures'], t['num_requests'])} | " + f"{t['rps']:.1f} | {t['p50']} | {t['p95']} | {t['p99']} |") + + ratio = None + if "python" in latest and "go" in latest: + p, g = latest["python"]["total"], latest["go"]["total"] + if p["rps"] > 0: + ratio = g["rps"] / p["rps"] + out.append(f"\n**Go worker TPS 是 Python worker 的 {ratio:.2f} 倍**" + f"({g['rps']:.0f} vs {p['rps']:.0f},同并发同场景)。") + + # 分 endpoint 明细 + out.append("\n## 3. 分 endpoint 明细\n") + for w, r in latest.items(): + out.append(f"### {w}\n") + out.append("| endpoint | 请求数 | 错误 | TPS | P95 (ms) | P99 (ms) |") + out.append("|---|---|---|---|---|---|") + for e in sorted(r["entries"], key=lambda x: x["name"]): + out.append(f"| {e['method']} {e['name']} | {e['num_requests']} | " + f"{e['num_failures']} | {e['rps']:.1f} | {e['p95']} | {e['p99']} |") + out.append("") + + # 归因分析 + out.append("## 4. 归因分析\n") + out.append("- **GIL 瓶颈**:Python worker 单进程内所有用户协程共享一个 GIL," + "requests 库虽然 I/O 多,但 JSON 编解码、locust 统计、gevent 调度都是" + "纯 CPU 段;并发越高,GIL 争抢越明显,单核打满后 TPS 触顶。") + out.append("- **Go 怎么绕开**:goroutine 由 Go runtime 多线程调度(GOMAXPROCS=核数)," + "网络 I/O 走 netpoller,无全局锁;连接池调优后" + "(MaxIdleConnsPerHost=1000,且有断言测试保证配置真的生效)," + "单机轻松压出数倍 TPS。") + out.append("- **瓶颈定位**:本机压测会撞到多层瓶颈(mock 网关的 Python HTTP 层、" + "loopback、worker 自身)。若两种 worker 的 P99 都高,瓶颈在被测服务侧;" + "若 Go 的 TPS 显著高于 Python 且 P99 更低,瓶颈在 worker 侧(GIL)。" + "本报告数字即按此判读。") + if ratio is not None: + verdict = ("瓶颈在 **Python worker 侧(GIL)**" if ratio > 1.3 + else "本轮瓶颈大概率在**被测 mock 服务侧**(两种 worker 都压不满它)" + if ratio <= 1.3 else "不确定") + out.append(f"- **本轮判读**:TPS 比 {ratio:.2f} → {verdict}。") + out.append("") + + # 实验分节(失真实验 / 扩展实验),数据缺省时自动跳过 + if trigger_runs: + _section_trigger(out, trigger_runs) + if scale_runs: + _section_scale(out, scale_runs) + print("\n".join(out)) + + +if __name__ == "__main__": + if len(sys.argv) < 2: + sys.exit("usage: compare.py results/*.json") + main(sys.argv[1:]) diff --git a/go/client.go b/go/client.go new file mode 100644 index 0000000..9629e3e --- /dev/null +++ b/go/client.go @@ -0,0 +1,96 @@ +package main + +import ( + "bytes" + "encoding/json" + "fmt" + "io" + "net" + "net/http" + "time" +) + +// newTunedTransport 返回调优后的 Transport。 +// 注意:调优参数必须落在**真正被 client 引用**的那个 Transport 上 —— 若参数 +// 写在一个从未被使用的变量上,默认 MaxIdleConnsPerHost=2 会让压测根本压不上去, +// 而且**不报任何错**,最难查。因此本文件配套 TestTransportPool, +// 断言「client 实际使用的 transport 就是调优过的那个」。 +func newTunedTransport() *http.Transport { + return &http.Transport{ + DialContext: (&net.Dialer{ + Timeout: 3 * time.Second, + KeepAlive: 30 * time.Second, + }).DialContext, + MaxIdleConns: 2000, + MaxIdleConnsPerHost: 1000, + MaxConnsPerHost: 1000, + IdleConnTimeout: 60 * time.Second, + } +} + +// APIClient 是被测 mock 网关的 HTTP 客户端。 +type APIClient struct { + base string + hc *http.Client +} + +func NewAPIClient(base string) *APIClient { + return &APIClient{ + base: base, + hc: &http.Client{ + Transport: newTunedTransport(), // ← 调优对象就在这里被引用 + Timeout: 10 * time.Second, + }, + } +} + +// Transport 暴露 client 实际使用的 transport(供断言测试用)。 +func (c *APIClient) Transport() *http.Transport { + return c.hc.Transport.(*http.Transport) +} + +type apiResponse struct { + Code int `json:"code"` + Msg string `json:"msg"` + Data json.RawMessage `json:"data"` +} + +// do 发起请求并返回 (httpStatus, bizCode, err)。latency 由调用方统计。 +func (c *APIClient) do(method, path string, body any) (int, int, error) { + var reader io.Reader + if body != nil { + raw, err := json.Marshal(body) + if err != nil { + return 0, -1, err + } + reader = bytes.NewReader(raw) + } + req, err := http.NewRequest(method, c.base+path, reader) + if err != nil { + return 0, -1, err + } + req.Header.Set("Content-Type", "application/json") + resp, err := c.hc.Do(req) + if err != nil { + return 0, -1, err + } + defer resp.Body.Close() + raw, err := io.ReadAll(resp.Body) + if err != nil { + return resp.StatusCode, -1, err + } + var ar apiResponse + if err := json.Unmarshal(raw, &ar); err != nil { + return resp.StatusCode, -1, fmt.Errorf("decode: %w", err) + } + return resp.StatusCode, ar.Code, nil +} + +func (c *APIClient) OpenOrder(path string, p OrderPayload) (int, int, error) { + return c.do(http.MethodPost, path, p) +} + +func (c *APIClient) BatchCancel(userID int, orderIDs []int64) (int, int, error) { + return c.do(http.MethodDelete, "/api/v1/order/batch/cancel", + map[string]any{"user_id": userID, "order_ids": orderIDs}) +} diff --git a/go/client_test.go b/go/client_test.go new file mode 100644 index 0000000..453526c --- /dev/null +++ b/go/client_test.go @@ -0,0 +1,23 @@ +package main + +import "testing" + +// TestTransportPool:连接池调优参数必须落在 client 实际使用的 transport 上, +// 而不是一个从未被引用的变量(否则调优静默失效)。 +func TestTransportPool(t *testing.T) { + c := NewAPIClient("http://127.0.0.1:1") + tr := c.Transport() + if tr == nil { + t.Fatal("client.Transport 为 nil:连接池配置根本没有被引用") + } + if tr.MaxIdleConnsPerHost < 1000 { + t.Fatalf("MaxIdleConnsPerHost = %d,期望 >= 1000(调优未生效)", + tr.MaxIdleConnsPerHost) + } + if tr.MaxConnsPerHost < 1000 { + t.Fatalf("MaxConnsPerHost = %d,期望 >= 1000", tr.MaxConnsPerHost) + } + if tr.MaxIdleConns < 1000 { + t.Fatalf("MaxIdleConns = %d,期望 >= 1000", tr.MaxIdleConns) + } +} diff --git a/go/go.mod b/go/go.mod new file mode 100644 index 0000000..0c67524 --- /dev/null +++ b/go/go.mod @@ -0,0 +1,26 @@ +module perf-harness-demo/go + +go 1.25.0 + +require github.com/myzhan/boomer v1.6.0 + +require ( + github.com/asaskevich/EventBus v0.0.0-20200907212545-49d423059eef // indirect + github.com/clipperhouse/uax29/v2 v2.6.0 // indirect + github.com/go-ole/go-ole v1.2.6 // indirect + github.com/google/uuid v1.6.0 // indirect + github.com/mattn/go-runewidth v0.0.19 // indirect + github.com/olekukonko/tablewriter v0.0.5 // indirect + github.com/shirou/gopsutil v3.21.11+incompatible // indirect + github.com/stretchr/testify v1.12.1 // indirect + github.com/tklauser/go-sysconf v0.4.0 // indirect + github.com/tklauser/numcpus v0.12.0 // indirect + github.com/ugorji/go/codec v1.3.2 // indirect + github.com/yusufpapurcu/wmi v1.2.4 // indirect + github.com/zeromq/goczmq v4.1.0+incompatible // indirect + github.com/zeromq/gomq v0.0.0-20201031135124-cef4e507bb8e // indirect + github.com/zeromq/gomq/zmtp v0.0.0-20201031135124-cef4e507bb8e // indirect + golang.org/x/sys v0.44.0 // indirect +) + +replace github.com/myzhan/boomer => ./third_party/boomer diff --git a/go/go.sum b/go/go.sum new file mode 100644 index 0000000..8285755 --- /dev/null +++ b/go/go.sum @@ -0,0 +1,38 @@ +github.com/asaskevich/EventBus v0.0.0-20200907212545-49d423059eef h1:2JGTg6JapxP9/R33ZaagQtAM4EkkSYnIAlOG5EI8gkM= +github.com/asaskevich/EventBus v0.0.0-20200907212545-49d423059eef/go.mod h1:JS7hed4L1fj0hXcyEejnW57/7LCetXggd+vwrRnYeII= +github.com/clipperhouse/uax29/v2 v2.6.0 h1:z0cDbUV+aPASdFb2/ndFnS9ts/WNXgTNNGFoKXuhpos= +github.com/clipperhouse/uax29/v2 v2.6.0/go.mod h1:Wn1g7MK6OoeDT0vL+Q0SQLDz/KpfsVRgg6W7ihQeh4g= +github.com/go-ole/go-ole v1.2.6 h1:/Fpf6oFPoeFik9ty7siob0G6Ke8QvQEuVcuChpwXzpY= +github.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0= +github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= +github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= +github.com/mattn/go-runewidth v0.0.19 h1:v++JhqYnZuu5jSKrk9RbgF5v4CGUjqRfBm05byFGLdw= +github.com/mattn/go-runewidth v0.0.19/go.mod h1:XBkDxAl56ILZc9knddidhrOlY5R/pDhgLpndooCuJAs= +github.com/olekukonko/tablewriter v0.0.5 h1:P2Ga83D34wi1o9J6Wh1mRuqd4mF/x/lgBS7N7AbDhec= +github.com/olekukonko/tablewriter v0.0.5/go.mod h1:hPp6KlRPjbx+hW8ykQs1w3UBbZlj6HuIJcUGPhkA7kY= +github.com/shirou/gopsutil v3.21.11+incompatible h1:+1+c1VGhc88SSonWP6foOcLhvnKlUeu/erjjvaPEYiI= +github.com/shirou/gopsutil v3.21.11+incompatible/go.mod h1:5b4v6he4MtMOwMlS0TUMTu2PcXUg8+E1lC7eC3UO/RA= +github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE= +github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg= +github.com/tklauser/go-sysconf v0.4.0 h1:7H0uAN+7RkwWRaxhYXDLqa5V3LPrJeV8wmD9dRUgPQU= +github.com/tklauser/go-sysconf v0.4.0/go.mod h1:8mTNWyog7H+MpKijp4VmKJAd2bbYQ2zuUwkYRbUArPI= +github.com/tklauser/numcpus v0.12.0 h1:NR85qdvHA9pFse3x3weVZ0r0ST8R6l5RHbZrlRaqob4= +github.com/tklauser/numcpus v0.12.0/go.mod h1:ABHeXzJnr/qqwguhClkZKT1/8VABcYrsyUiUGobwWJg= +github.com/ugorji/go/codec v1.3.2 h1:zkEASHHyEClGeURfgNT9PJZVfAbs9oEX9QXggwWNJbc= +github.com/ugorji/go/codec v1.3.2/go.mod h1:pRBVtBSKl77K30Bv8R2P+cLSGaTtex6fsA2Wjqmfxj4= +github.com/yusufpapurcu/wmi v1.2.4 h1:zFUKzehAFReQwLys1b/iSMl+JQGSCSjtVqQn9bBrPo0= +github.com/yusufpapurcu/wmi v1.2.4/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0= +github.com/zeromq/goczmq v4.1.0+incompatible h1:cGVQaU6kIwwrGso0Pgbl84tzAz/h7FJ3wYQjSonjFFc= +github.com/zeromq/goczmq v4.1.0+incompatible/go.mod h1:1uZybAJoSRCvZMH2rZxEwWBSmC4T7CB/xQOfChwPEzg= +github.com/zeromq/gomq v0.0.0-20201031135124-cef4e507bb8e h1:vGjfCnWv/zWeO1ivv4+OUPgTzG/WV1iGfZwVdtUpLkM= +github.com/zeromq/gomq v0.0.0-20201031135124-cef4e507bb8e/go.mod h1:SkCxcSQ7BQEA9FvDzbj+3hV6EMhSywyxWnHwUXVIyLY= +github.com/zeromq/gomq/zmtp v0.0.0-20201031135124-cef4e507bb8e h1:pjp04/sSr2TYuaPdt+u6Cc1M38Aocp+3er0akr3auFg= +github.com/zeromq/gomq/zmtp v0.0.0-20201031135124-cef4e507bb8e/go.mod h1:LBjWEodY/ESvKRwLw3bc7mhn49oiI8qlXUqeqLn0pcU= +go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw= +go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg= +golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.44.0 h1:ildZl3J4uzeKP07r2F++Op7E9B29JRUy+a27EibtBTQ= +golang.org/x/sys v0.44.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= diff --git a/go/main.go b/go/main.go new file mode 100644 index 0000000..43c9cc1 --- /dev/null +++ b/go/main.go @@ -0,0 +1,26 @@ +package main + +import ( + "flag" + "log" + + "github.com/myzhan/boomer" +) + +func main() { + // 注意:boomer 在 init 里已注册 --master-host/--master-port 等 flag, + // 这里只新增自己的 flag,绝不能重复定义(会 panic)。 + target := flag.String("target", "http://127.0.0.1:18099", "被测 mock 地址(只打本机)") + flag.Parse() + + client := NewAPIClient(*target) + + tasks := buildBoomerTasks(client) + log.Printf("[go-worker] target=%s, tasks=%d", *target, len(tasks)) + + boomer.Events.Subscribe("boomer:spawn", func(workers int, spawnRate float64) { + log.Printf("[go-worker] master asks to spawn %d workers (rate %.0f)", workers, spawnRate) + }) + + boomer.Run(tasks...) +} diff --git a/go/tasks.go b/go/tasks.go new file mode 100644 index 0000000..4bc18b3 --- /dev/null +++ b/go/tasks.go @@ -0,0 +1,104 @@ +package main + +import ( + "sync/atomic" + "time" + + "github.com/myzhan/boomer" +) + +// OrderPayload 与 python/locustfile.py 的请求体**完全一致**(公平对比前提)。 +type OrderPayload struct { + UserID int `json:"user_id"` + ContractID int `json:"contract_id"` + Side string `json:"side"` + MarginType int `json:"margin_type"` + Quantity string `json:"quantity"` + Price string `json:"price,omitempty"` +} + +const userPoolSize = 1000 + +var ( + rngMu atomic.Int64 // 简单计数即可,payload 随机性不影响正确性 + openOrder atomic.Int64 // 记录一个最近开仓的 order_id 供撤单用 +) + +func randIntn(n int) int { + // 压测下用原子计数打散即可,不追求密码学随机 + return int(rngMu.Add(1) * 2654435761 % (int64(n) * 9973) % int64(n)) +} + +func payload(withPrice bool) OrderPayload { + p := OrderPayload{ + UserID: randIntn(userPoolSize) + 1, // 真随机用户池:避免全员压同一用户导致分布失真 + ContractID: randIntn(3) + 1, + MarginType: randIntn(2) + 1, + Quantity: "10", + } + if randIntn(2) == 0 { + p.Side = "ask" + } else { + p.Side = "bid" + } + if withPrice { + p.Price = "30000.5" + } + return p +} + +// TaskDef 配置驱动的任务注册。若把任务硬写死在 boomer.Run(t1, t2) 里, +// 新增任务极易漏注册,且不会有任何报错提示。增删任务只改这张表。 +type TaskDef struct { + Name string + Weight int + Fn func(c *APIClient) (method, name string, httpStatus, bizCode int, err error) +} + +func taskTable() []TaskDef { + return []TaskDef{ + {"limit_open", 4, func(c *APIClient) (string, string, int, int, error) { + s, b, err := c.OpenOrder("/api/v1/order/limit/open", payload(true)) + return "POST", "/api/v1/order/limit/open", s, b, err + }}, + {"market_quantity_open", 2, func(c *APIClient) (string, string, int, int, error) { + s, b, err := c.OpenOrder("/api/v1/order/market/quantity/open", payload(false)) + return "POST", "/api/v1/order/market/quantity/open", s, b, err + }}, + {"market_amount_open", 2, func(c *APIClient) (string, string, int, int, error) { + s, b, err := c.OpenOrder("/api/v1/order/market/amount/open", payload(false)) + return "POST", "/api/v1/order/market/amount/open", s, b, err + }}, + {"batch_cancel", 1, func(c *APIClient) (string, string, int, int, error) { + s, b, err := c.BatchCancel(randIntn(userPoolSize)+1, + []int64{openOrder.Load()}) + return "DELETE", "/api/v1/order/batch/cancel", s, b, err + }}, + } +} + +// buildBoomerTasks 把任务表转成 boomer.Task 列表。 +func buildBoomerTasks(c *APIClient) []*boomer.Task { + var tasks []*boomer.Task + for _, d := range taskTable() { + def := d + tasks = append(tasks, &boomer.Task{ + Name: def.Name, + Weight: def.Weight, + Fn: func() { + start := time.Now() + method, name, httpStatus, bizCode, err := def.Fn(c) + elapsed := time.Since(start).Milliseconds() + switch { + case err != nil: + boomer.RecordFailure(method, name, elapsed, err.Error()) + case httpStatus != 200 || bizCode != 0: + boomer.RecordFailure(method, name, elapsed, "biz error") + default: + boomer.RecordSuccess(method, name, elapsed, 0) + } + }, + }) + } + return tasks +} diff --git a/go/third_party/boomer/LICENSE b/go/third_party/boomer/LICENSE new file mode 100644 index 0000000..d54a5b8 --- /dev/null +++ b/go/third_party/boomer/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2019 myzhan + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/go/third_party/boomer/boomer.go b/go/third_party/boomer/boomer.go new file mode 100644 index 0000000..aa1ab1c --- /dev/null +++ b/go/third_party/boomer/boomer.go @@ -0,0 +1,280 @@ +package boomer + +import ( + "flag" + "log" + "os" + "os/signal" + "strings" + "syscall" + "time" + + "github.com/asaskevich/EventBus" +) + +// Events is the global event bus instance. +var Events = EventBus.New() + +var defaultBoomer = &Boomer{} + +// Mode is the running mode of boomer, both standalone and distributed are supported. +type Mode int + +const ( + // DistributedMode requires connecting to a master. + DistributedMode Mode = iota + // StandaloneMode will run without a master. + StandaloneMode +) + +// A Boomer is used to run tasks. +// This type is exposed, so users can create and control a Boomer instance programmatically. +type Boomer struct { + masterHost string + masterPort int + mode Mode + rateLimiter RateLimiter + slaveRunner *slaveRunner + + localRunner *localRunner + spawnCount int + spawnRate float64 + + cpuProfile string + cpuProfileDuration time.Duration + + memoryProfile string + memoryProfileDuration time.Duration + + outputs []Output +} + +// NewBoomer returns a new Boomer. +func NewBoomer(masterHost string, masterPort int) *Boomer { + return &Boomer{ + masterHost: masterHost, + masterPort: masterPort, + mode: DistributedMode, + } +} + +// NewStandaloneBoomer returns a new Boomer, which can run without master. +func NewStandaloneBoomer(spawnCount int, spawnRate float64) *Boomer { + return &Boomer{ + spawnCount: spawnCount, + spawnRate: spawnRate, + mode: StandaloneMode, + } +} + +// SetRateLimiter allows user to use their own rate limiter. +// It must be called before the test is started. +func (b *Boomer) SetRateLimiter(rateLimiter RateLimiter) { + b.rateLimiter = rateLimiter +} + +// SetMode only accepts boomer.DistributedMode and boomer.StandaloneMode. +func (b *Boomer) SetMode(mode Mode) { + switch mode { + case DistributedMode: + b.mode = DistributedMode + case StandaloneMode: + b.mode = StandaloneMode + default: + log.Println("Invalid mode, ignored!") + } +} + +// AddOutput accepts outputs which implements the boomer.Output interface. +func (b *Boomer) AddOutput(o Output) { + b.outputs = append(b.outputs, o) +} + +// EnableCPUProfile will start cpu profiling after run. +func (b *Boomer) EnableCPUProfile(cpuProfile string, duration time.Duration) { + b.cpuProfile = cpuProfile + b.cpuProfileDuration = duration +} + +// EnableMemoryProfile will start memory profiling after run. +func (b *Boomer) EnableMemoryProfile(memoryProfile string, duration time.Duration) { + b.memoryProfile = memoryProfile + b.memoryProfileDuration = duration +} + +// Run accepts a slice of Task and connects to the locust master. +func (b *Boomer) Run(tasks ...*Task) { + if b.cpuProfile != "" { + err := StartCPUProfile(b.cpuProfile, b.cpuProfileDuration) + if err != nil { + log.Printf("Error starting cpu profiling, %v", err) + } + } + if b.memoryProfile != "" { + err := StartMemoryProfile(b.memoryProfile, b.memoryProfileDuration) + if err != nil { + log.Printf("Error starting memory profiling, %v", err) + } + } + + switch b.mode { + case DistributedMode: + b.slaveRunner = newSlaveRunner(b.masterHost, b.masterPort, tasks, b.rateLimiter) + for _, o := range b.outputs { + b.slaveRunner.addOutput(o) + } + b.slaveRunner.run() + case StandaloneMode: + b.localRunner = newLocalRunner(tasks, b.rateLimiter, b.spawnCount, b.spawnRate) + for _, o := range b.outputs { + b.localRunner.addOutput(o) + } + b.localRunner.run() + default: + log.Println("Invalid mode, expected boomer.DistributedMode or boomer.StandaloneMode") + } +} + +// RecordSuccess reports a success. +func (b *Boomer) RecordSuccess(requestType, name string, responseTime int64, responseLength int64) { + if b.localRunner == nil && b.slaveRunner == nil { + return + } + switch b.mode { + case DistributedMode: + b.slaveRunner.stats.requestSuccessChan <- &requestSuccess{ + requestType: requestType, + name: name, + responseTime: responseTime, + responseLength: responseLength, + } + case StandaloneMode: + b.localRunner.stats.requestSuccessChan <- &requestSuccess{ + requestType: requestType, + name: name, + responseTime: responseTime, + responseLength: responseLength, + } + } +} + +// RecordFailure reports a failure. +func (b *Boomer) RecordFailure(requestType, name string, responseTime int64, exception string) { + if b.localRunner == nil && b.slaveRunner == nil { + return + } + switch b.mode { + case DistributedMode: + b.slaveRunner.stats.requestFailureChan <- &requestFailure{ + requestType: requestType, + name: name, + responseTime: responseTime, + error: exception, + } + case StandaloneMode: + b.localRunner.stats.requestFailureChan <- &requestFailure{ + requestType: requestType, + name: name, + responseTime: responseTime, + error: exception, + } + } +} + +// Quit will send a quit message to the master. +func (b *Boomer) Quit() { + Events.Publish("boomer:quit") + var ticker = time.NewTicker(3 * time.Second) + + switch b.mode { + case DistributedMode: + // wait for quit message is sent to master + select { + case <-b.slaveRunner.client.disconnectedChannel(): + break + case <-ticker.C: + log.Println("Timeout waiting for sending quit message to master, boomer will quit any way.") + break + } + b.slaveRunner.close() + case StandaloneMode: + b.localRunner.close() + } +} + +// Run tasks without connecting to the master. +func runTasksForTest(tasks ...*Task) { + taskNames := strings.Split(runTasks, ",") + for _, task := range tasks { + if task.Name == "" { + continue + } else { + for _, name := range taskNames { + if name == task.Name { + log.Println("Running " + task.Name) + task.Fn() + } + } + } + } +} + +// Run accepts a slice of Task and connects to a locust master. +// It's a convenience function to use the defaultBoomer. +func Run(tasks ...*Task) { + if !flag.Parsed() { + flag.Parse() + } + + if runTasks != "" { + runTasksForTest(tasks...) + return + } + + initLegacyEventHandlers() + + rateLimiter, err := createRateLimiter(maxRPS, requestIncreaseRate) + if err != nil { + log.Fatalf("%v\n", err) + } + defaultBoomer.SetRateLimiter(rateLimiter) + defaultBoomer.masterHost = masterHost + defaultBoomer.masterPort = masterPort + defaultBoomer.EnableMemoryProfile(memoryProfile, memoryProfileDuration) + defaultBoomer.EnableCPUProfile(cpuProfile, cpuProfileDuration) + + defaultBoomer.Run(tasks...) + + quitByMe := false + quitChan := make(chan bool) + + Events.SubscribeOnce("boomer:quit", func() { + if !quitByMe { + close(quitChan) + } + }) + + c := make(chan os.Signal) + signal.Notify(c, syscall.SIGINT, syscall.SIGTERM) + + select { + case <-c: + quitByMe = true + defaultBoomer.Quit() + case <-quitChan: + } + + log.Println("shut down") +} + +// RecordSuccess reports a success. +// It's a convenience function to use the defaultBoomer. +func RecordSuccess(requestType, name string, responseTime int64, responseLength int64) { + defaultBoomer.RecordSuccess(requestType, name, responseTime, responseLength) +} + +// RecordFailure reports a failure. +// It's a convenience function to use the defaultBoomer. +func RecordFailure(requestType, name string, responseTime int64, exception string) { + defaultBoomer.RecordFailure(requestType, name, responseTime, exception) +} diff --git a/go/third_party/boomer/client.go b/go/third_party/boomer/client.go new file mode 100644 index 0000000..7379c1e --- /dev/null +++ b/go/third_party/boomer/client.go @@ -0,0 +1,9 @@ +package boomer + +type client interface { + connect() (err error) + close() + recvChannel() chan *message + sendChannel() chan *message + disconnectedChannel() chan bool +} diff --git a/go/third_party/boomer/client_czmq.go b/go/third_party/boomer/client_czmq.go new file mode 100644 index 0000000..67c2fcc --- /dev/null +++ b/go/third_party/boomer/client_czmq.go @@ -0,0 +1,127 @@ +// +build goczmq + +package boomer + +import ( + "fmt" + "log" + + "github.com/zeromq/goczmq" +) + +type czmqSocketClient struct { + masterHost string + masterPort int + identity string + + dealerSocket *goczmq.Sock + + fromMaster chan *message + toMaster chan *message + disconnectedFromMaster chan bool + shutdownChan chan bool +} + +func newClient(masterHost string, masterPort int, identity string) (client *czmqSocketClient) { + log.Println("Boomer is built with goczmq support.") + client = &czmqSocketClient{ + masterHost: masterHost, + masterPort: masterPort, + identity: identity, + fromMaster: make(chan *message, 100), + toMaster: make(chan *message, 100), + disconnectedFromMaster: make(chan bool), + shutdownChan: make(chan bool), + } + + return client +} + +func (c *czmqSocketClient) connect() (err error) { + addr := fmt.Sprintf("tcp://%s:%d", c.masterHost, c.masterPort) + dealer := goczmq.NewSock(goczmq.Dealer) + dealer.SetOption(goczmq.SockSetIdentity(c.identity)) + err = dealer.Connect(addr) + if err != nil { + return err + } + + c.dealerSocket = dealer + + log.Printf("Boomer is connected to master(%s) press Ctrl+c to quit.\n", addr) + + go c.recv() + go c.send() + + return nil +} + +func (c *czmqSocketClient) close() { + close(c.shutdownChan) + if c.dealerSocket != nil { + c.dealerSocket.Destroy() + } +} + +func (c *czmqSocketClient) recvChannel() chan *message { + return c.fromMaster +} + +func (c *czmqSocketClient) recv() { + for { + select { + case <-c.shutdownChan: + return + default: + msg, _, err := c.dealerSocket.RecvFrame() + if err != nil { + log.Printf("Error reading: %v\n", err) + continue + } + decodedMsg, err := newMessageFromBytes(msg) + if err != nil { + log.Printf("Msgpack decode fail: %v\n", err) + continue + } + if decodedMsg.NodeID != c.identity { + log.Printf("Recv a %s message for node(%s), not for me(%s), dropped.\n", decodedMsg.Type, decodedMsg.NodeID, c.identity) + continue + } + c.fromMaster <- decodedMsg + } + } +} + +func (c *czmqSocketClient) sendChannel() chan *message { + return c.toMaster +} + +func (c *czmqSocketClient) send() { + for { + select { + case <-c.shutdownChan: + return + case msg := <-c.toMaster: + c.sendMessage(msg) + if msg.Type == "quit" { + c.disconnectedFromMaster <- true + } + } + } +} + +func (c *czmqSocketClient) sendMessage(msg *message) { + serializedMessage, err := msg.serialize() + if err != nil { + log.Printf("Msgpack encode fail: %v\n", err) + return + } + err = c.dealerSocket.SendFrame(serializedMessage, goczmq.FlagNone) + if err != nil { + log.Printf("Error sending: %v\n", err) + } +} + +func (c *czmqSocketClient) disconnectedChannel() chan bool { + return c.disconnectedFromMaster +} diff --git a/go/third_party/boomer/client_gomq.go b/go/third_party/boomer/client_gomq.go new file mode 100644 index 0000000..30e29a4 --- /dev/null +++ b/go/third_party/boomer/client_gomq.go @@ -0,0 +1,129 @@ +// +build !goczmq + +package boomer + +import ( + "fmt" + "log" + + "github.com/zeromq/gomq" + "github.com/zeromq/gomq/zmtp" +) + +type gomqSocketClient struct { + masterHost string + masterPort int + identity string + + dealerSocket gomq.Dealer + + fromMaster chan *message + toMaster chan *message + disconnectedFromMaster chan bool + shutdownChan chan bool +} + +func newClient(masterHost string, masterPort int, identity string) (client *gomqSocketClient) { + log.Println("Boomer is built with gomq support.") + client = &gomqSocketClient{ + masterHost: masterHost, + masterPort: masterPort, + identity: identity, + fromMaster: make(chan *message, 100), + toMaster: make(chan *message, 100), + disconnectedFromMaster: make(chan bool), + shutdownChan: make(chan bool), + } + return client +} + +func (c *gomqSocketClient) connect() (err error) { + addr := fmt.Sprintf("tcp://%s:%d", c.masterHost, c.masterPort) + c.dealerSocket = gomq.NewDealer(zmtp.NewSecurityNull(), c.identity) + + if err = c.dealerSocket.Connect(addr); err != nil { + return err + } + + log.Printf("Boomer is connected to master(%s) press Ctrl+c to quit.\n", addr) + go c.recv() + go c.send() + + return nil +} + +func (c *gomqSocketClient) close() { + close(c.shutdownChan) + if c.dealerSocket != nil { + c.dealerSocket.Close() + } +} + +func (c *gomqSocketClient) recvChannel() chan *message { + return c.fromMaster +} + +func (c *gomqSocketClient) recv() { + for { + select { + case <-c.shutdownChan: + return + case msg := <-c.dealerSocket.RecvChannel(): + if msg.MessageType == zmtp.CommandMessage { + continue + } + if len(msg.Body) == 0 { + continue + } + body, err := msg.Body[0], msg.Err + if err != nil { + log.Printf("Error reading: %v\n", err) + continue + } + decodedMsg, err := newMessageFromBytes(body) + if err != nil { + log.Printf("Msgpack decode fail: %v\n", err) + continue + } + if decodedMsg.NodeID != c.identity { + log.Printf("Recv a %s message for node(%s), not for me(%s), dropped.\n", decodedMsg.Type, decodedMsg.NodeID, c.identity) + continue + } + c.fromMaster <- decodedMsg + } + } +} + +func (c *gomqSocketClient) sendChannel() chan *message { + return c.toMaster +} + +func (c *gomqSocketClient) send() { + for { + select { + case <-c.shutdownChan: + return + case msg := <-c.toMaster: + c.sendMessage(msg) + if msg.Type == "quit" { + c.disconnectedFromMaster <- true + } + } + } +} + +func (c *gomqSocketClient) sendMessage(msg *message) { + serializedMessage, err := msg.serialize() + if err != nil { + log.Printf("Msgpack encode fail: %v\n", err) + return + } + err = c.dealerSocket.Send(serializedMessage) + if err != nil { + log.Printf("Error sending: %v\n", err) + } +} + +func (c *gomqSocketClient) disconnectedChannel() chan bool { + return c.disconnectedFromMaster +} diff --git a/go/third_party/boomer/go.mod b/go/third_party/boomer/go.mod new file mode 100644 index 0000000..7ae92db --- /dev/null +++ b/go/third_party/boomer/go.mod @@ -0,0 +1,3 @@ +module github.com/myzhan/boomer + +go 1.21 diff --git a/go/third_party/boomer/legacy.go b/go/third_party/boomer/legacy.go new file mode 100644 index 0000000..6427512 --- /dev/null +++ b/go/third_party/boomer/legacy.go @@ -0,0 +1,89 @@ +// This file is kept to ensure backward compatibility. + +package boomer + +import ( + "flag" + "fmt" + "log" + "math" + "reflect" + "sync" + "time" +) + +var masterHost string +var masterPort int +var maxRPS int64 +var requestIncreaseRate string +var runTasks string +var memoryProfile string +var memoryProfileDuration time.Duration +var cpuProfile string +var cpuProfileDuration time.Duration + +var successRetiredWarning = &sync.Once{} +var failureRetiredWarning = &sync.Once{} + +func createRateLimiter(maxRPS int64, requestIncreaseRate string) (rateLimiter RateLimiter, err error) { + if requestIncreaseRate != "-1" { + if maxRPS > 0 { + log.Println("The max RPS that boomer may generate is limited to", maxRPS, "with a increase rate", requestIncreaseRate) + rateLimiter, err = NewRampUpRateLimiter(maxRPS, requestIncreaseRate, time.Second) + } else { + log.Println("The max RPS that boomer may generate is limited by a increase rate", requestIncreaseRate) + rateLimiter, err = NewRampUpRateLimiter(math.MaxInt64, requestIncreaseRate, time.Second) + } + } else { + if maxRPS > 0 { + log.Println("The max RPS that boomer may generate is limited to", maxRPS) + rateLimiter = NewStableRateLimiter(maxRPS, time.Second) + } + } + return rateLimiter, err +} + +// According to locust, responseTime should be int64, in milliseconds. +// But previous version of boomer required responseTime to be float64, so sad. +func convertResponseTime(origin interface{}) int64 { + responseTime := int64(0) + if _, ok := origin.(float64); ok { + responseTime = int64(origin.(float64)) + } else if _, ok := origin.(int64); ok { + responseTime = origin.(int64) + } else { + panic(fmt.Sprintf("responseTime should be float64 or int64, not %s", reflect.TypeOf(origin))) + } + return responseTime +} + +func legacySuccessHandler(requestType string, name string, responseTime interface{}, responseLength int64) { + successRetiredWarning.Do(func() { + log.Println("boomer.Events.Publish(\"request_success\") is less performant and deprecated, use boomer.RecordSuccess() instead.") + }) + defaultBoomer.RecordSuccess(requestType, name, convertResponseTime(responseTime), responseLength) +} + +func legacyFailureHandler(requestType string, name string, responseTime interface{}, exception string) { + failureRetiredWarning.Do(func() { + log.Println("boomer.Events.Publish(\"request_failure\") is less performant and deprecated, use boomer.RecordFailure() instead.") + }) + defaultBoomer.RecordFailure(requestType, name, convertResponseTime(responseTime), exception) +} + +func initLegacyEventHandlers() { + Events.Subscribe("request_success", legacySuccessHandler) + Events.Subscribe("request_failure", legacyFailureHandler) +} + +func init() { + flag.Int64Var(&maxRPS, "max-rps", 0, "Max RPS that boomer can generate, disabled by default.") + flag.StringVar(&requestIncreaseRate, "request-increase-rate", "-1", "Request increase rate, disabled by default.") + flag.StringVar(&runTasks, "run-tasks", "", "Run tasks without connecting to the master, multiply tasks is separated by comma. Usually, it's for debug purpose.") + flag.StringVar(&masterHost, "master-host", "127.0.0.1", "Host or IP address of locust master for distributed load testing.") + flag.IntVar(&masterPort, "master-port", 5557, "The port to connect to that is used by the locust master for distributed load testing.") + flag.StringVar(&memoryProfile, "mem-profile", "", "Enable memory profiling.") + flag.DurationVar(&memoryProfileDuration, "mem-profile-duration", 30*time.Second, "Memory profile duration.") + flag.StringVar(&cpuProfile, "cpu-profile", "", "Enable CPU profiling.") + flag.DurationVar(&cpuProfileDuration, "cpu-profile-duration", 30*time.Second, "CPU profile duration.") +} diff --git a/go/third_party/boomer/message.go b/go/third_party/boomer/message.go new file mode 100644 index 0000000..7962c05 --- /dev/null +++ b/go/third_party/boomer/message.go @@ -0,0 +1,38 @@ +package boomer + +import ( + "github.com/ugorji/go/codec" +) + +var ( + mh codec.MsgpackHandle +) + +type message struct { + Type string `codec:"type"` + Data interface{} `codec:"data"` + NodeID string `codec:"node_id"` +} + +func newMessage(t string, data interface{}, nodeID string) (msg *message) { + return &message{ + Type: t, + Data: data, + NodeID: nodeID, + } +} + +func (m *message) serialize() (out []byte, err error) { + mh.StructToArray = true + enc := codec.NewEncoderBytes(&out, &mh) + err = enc.Encode(m) + return out, err +} + +func newMessageFromBytes(raw []byte) (newMsg *message, err error) { + mh.StructToArray = true + dec := codec.NewDecoderBytes(raw, &mh) + newMsg = &message{} + err = dec.Decode(newMsg) + return newMsg, err +} diff --git a/go/third_party/boomer/output.go b/go/third_party/boomer/output.go new file mode 100644 index 0000000..e4e20f0 --- /dev/null +++ b/go/third_party/boomer/output.go @@ -0,0 +1,146 @@ +package boomer + +import ( + "fmt" + "os" + "sort" + "strconv" + "time" + + "github.com/olekukonko/tablewriter" +) + +// Output is primarily responsible for printing test results to different destinations +// such as consoles, files. You can write you own output and add to boomer. +// When running in standalone mode, the default output is ConsoleOutput, you can add more. +// When running in distribute mode, test results will be reported to master with or without +// an output. +// All the OnXXX function will be call in a separated goroutine, just in case some output will block. +// But it will wait for all outputs return to avoid data lost. +type Output interface { + // OnStart will be call before the test starts. + OnStart() + + // By default, each output receive stats data from runner every three seconds. + // OnEvent is responsible for dealing with the data. + OnEvent(data map[string]interface{}) + + // OnStop will be called before the test ends. + OnStop() +} + +// ConsoleOutput is the default output for standalone mode. +type ConsoleOutput struct { +} + +// NewConsoleOutput returns a ConsoleOutput. +func NewConsoleOutput() *ConsoleOutput { + return &ConsoleOutput{} +} + +func getMedianResponseTime(numRequests int64, responseTimes map[int64]int64) int64 { + medianResponseTime := int64(0) + if len(responseTimes) != 0 { + pos := (numRequests - 1) / 2 + var sortedKeys []int64 + for k := range responseTimes { + sortedKeys = append(sortedKeys, k) + } + sort.Slice(sortedKeys, func(i, j int) bool { + return sortedKeys[i] < sortedKeys[j] + }) + for _, k := range sortedKeys { + if pos < responseTimes[k] { + medianResponseTime = k + break + } + pos -= responseTimes[k] + } + } + return medianResponseTime +} + +func getAvgResponseTime(numRequests int64, totalResponseTime int64) (avgResponseTime float64) { + avgResponseTime = float64(0) + if numRequests != 0 { + avgResponseTime = float64(totalResponseTime) / float64(numRequests) + } + return avgResponseTime +} + +func getAvgContentLength(numRequests int64, totalContentLength int64) (avgContentLength int64) { + avgContentLength = int64(0) + if numRequests != 0 { + avgContentLength = totalContentLength / numRequests + } + return avgContentLength +} + +func getCurrentRps(numRequests int64, numReqsPerSecond map[int64]int64) (currentRps int64) { + currentRps = int64(0) + numReqsPerSecondLength := int64(len(numReqsPerSecond)) + if numReqsPerSecondLength != 0 { + currentRps = numRequests / numReqsPerSecondLength + } + return currentRps +} + +// OnStart of ConsoleOutput has nothing to do. +func (o *ConsoleOutput) OnStart() { + +} + +// OnStop of ConsoleOutput has nothing to do. +func (o *ConsoleOutput) OnStop() { + +} + +// OnEvent will print to the console. +func (o *ConsoleOutput) OnEvent(data map[string]interface{}) { + stats, ok := data["stats"].([]interface{}) + if !ok { + return + } + + currentTime := time.Now() + println(fmt.Sprintf("Current time: %s", currentTime.Format("2006/01/02 15:04:05"))) + table := tablewriter.NewWriter(os.Stdout) + table.SetHeader([]string{"Type", "Name", "# requests", "# fails", "Median", "Average", "Min", "Max", "Content Size", "# reqs/sec"}) + + for _, stat := range stats { + s := stat.(map[string]interface{}) + row := make([]string, 10) + row[0], row[1] = s["name"].(string), s["method"].(string) + + numRequests := s["num_requests"].(int64) + row[2] = strconv.FormatInt(numRequests, 10) + + numFailures := s["num_failures"].(int64) + row[3] = strconv.FormatInt(numFailures, 10) + + medianResponseTime := getMedianResponseTime(numRequests, s["response_times"].(map[int64]int64)) + row[4] = strconv.FormatInt(medianResponseTime, 10) + + totalResponseTime := s["total_response_time"].(int64) + avgResponseTime := getAvgResponseTime(numRequests, totalResponseTime) + row[5] = strconv.FormatFloat(avgResponseTime, 'f', 2, 64) + + minResponseTime := s["min_response_time"].(int64) + row[6] = strconv.FormatInt(minResponseTime, 10) + + maxResponseTime := s["max_response_time"].(int64) + row[7] = strconv.FormatInt(maxResponseTime, 10) + + totalContentLength := s["total_content_length"].(int64) + avgContentLength := getAvgContentLength(numRequests, totalContentLength) + row[8] = strconv.FormatInt(avgContentLength, 10) + + numReqsPerSecond := s["num_reqs_per_sec"].(map[int64]int64) + currentRps := getCurrentRps(numRequests, numReqsPerSecond) + row[9] = strconv.FormatInt(currentRps, 10) + + table.Append(row) + } + table.Render() + println() +} diff --git a/go/third_party/boomer/ratelimiter.go b/go/third_party/boomer/ratelimiter.go new file mode 100644 index 0000000..5cf98b9 --- /dev/null +++ b/go/third_party/boomer/ratelimiter.go @@ -0,0 +1,213 @@ +package boomer + +import ( + "errors" + "math" + "strconv" + "strings" + "sync/atomic" + "time" +) + +// RateLimiter is used to put limits on task executions. +type RateLimiter interface { + // Start is used to enable the rate limiter. + // It can be implemented as a noop if not needed. + Start() + + // Acquire() is called before executing a task.Fn function. + // If Acquire() returns true, the task.Fn function will be executed. + // If Acquire() returns false, the task.Fn function won't be executed this time, but Acquire() will be called very soon. + // It works like: + // for { + // blocked := rateLimiter.Acquire() + // if !blocked { + // task.Fn() + // } + // } + // Acquire() should block the caller until execution is allowed. + Acquire() bool + + // Stop is used to disable the rate limiter. + // It can be implemented as a noop if not needed. + Stop() +} + +// A StableRateLimiter uses the token bucket algorithm. +// the bucket is refilled according to the refill period, no burst is allowed. +type StableRateLimiter struct { + threshold int64 + currentThreshold int64 + refillPeriod time.Duration + broadcastChannel chan bool + quitChannel chan bool +} + +// NewStableRateLimiter returns a StableRateLimiter. +func NewStableRateLimiter(threshold int64, refillPeriod time.Duration) (rateLimiter *StableRateLimiter) { + rateLimiter = &StableRateLimiter{ + threshold: threshold, + currentThreshold: threshold, + refillPeriod: refillPeriod, + broadcastChannel: make(chan bool), + } + return rateLimiter +} + +// Start to refill the bucket periodically. +func (limiter *StableRateLimiter) Start() { + limiter.quitChannel = make(chan bool) + quitChannel := limiter.quitChannel + go func() { + for { + select { + case <-quitChannel: + return + default: + atomic.StoreInt64(&limiter.currentThreshold, limiter.threshold) + time.Sleep(limiter.refillPeriod) + close(limiter.broadcastChannel) + limiter.broadcastChannel = make(chan bool) + } + } + }() +} + +// Acquire a token from the bucket, returns true if the bucket is exhausted. +func (limiter *StableRateLimiter) Acquire() (blocked bool) { + permit := atomic.AddInt64(&limiter.currentThreshold, -1) + if permit < 0 { + blocked = true + // block until the bucket is refilled + <-limiter.broadcastChannel + } else { + blocked = false + } + return blocked +} + +// Stop the rate limiter. +func (limiter *StableRateLimiter) Stop() { + close(limiter.quitChannel) +} + +// ErrParsingRampUpRate is the error returned if the format of rampUpRate is invalid. +var ErrParsingRampUpRate = errors.New("ratelimiter: invalid format of rampUpRate, try \"1\" or \"1/1s\"") + +// A RampUpRateLimiter uses the token bucket algorithm. +// the threshold is updated according to the warm up rate. +// the bucket is refilled according to the refill period, no burst is allowed. +type RampUpRateLimiter struct { + maxThreshold int64 + nextThreshold int64 + currentThreshold int64 + refillPeriod time.Duration + rampUpRate string + rampUpStep int64 + rampUpPeroid time.Duration + broadcastChannel chan bool + rampUpChannel chan bool + quitChannel chan bool +} + +// NewRampUpRateLimiter returns a RampUpRateLimiter. +// Valid formats of rampUpRate are "1", "1/1s". +func NewRampUpRateLimiter(maxThreshold int64, rampUpRate string, refillPeriod time.Duration) (rateLimiter *RampUpRateLimiter, err error) { + rateLimiter = &RampUpRateLimiter{ + maxThreshold: maxThreshold, + nextThreshold: 0, + currentThreshold: 0, + rampUpRate: rampUpRate, + refillPeriod: refillPeriod, + broadcastChannel: make(chan bool), + } + rateLimiter.rampUpStep, rateLimiter.rampUpPeroid, err = rateLimiter.parseRampUpRate(rateLimiter.rampUpRate) + if err != nil { + return nil, err + } + return rateLimiter, nil +} + +func (limiter *RampUpRateLimiter) parseRampUpRate(rampUpRate string) (rampUpStep int64, rampUpPeroid time.Duration, err error) { + if strings.Contains(rampUpRate, "/") { + tmp := strings.Split(rampUpRate, "/") + if len(tmp) != 2 { + return rampUpStep, rampUpPeroid, ErrParsingRampUpRate + } + rampUpStep, err := strconv.ParseInt(tmp[0], 10, 64) + if err != nil { + return rampUpStep, rampUpPeroid, ErrParsingRampUpRate + } + rampUpPeroid, err := time.ParseDuration(tmp[1]) + if err != nil { + return rampUpStep, rampUpPeroid, ErrParsingRampUpRate + } + return rampUpStep, rampUpPeroid, nil + } + + rampUpStep, err = strconv.ParseInt(rampUpRate, 10, 64) + if err != nil { + return rampUpStep, rampUpPeroid, ErrParsingRampUpRate + } + rampUpPeroid = time.Second + return rampUpStep, rampUpPeroid, nil +} + +// Start to refill the bucket periodically. +func (limiter *RampUpRateLimiter) Start() { + limiter.quitChannel = make(chan bool) + quitChannel := limiter.quitChannel + // bucket updater + go func() { + for { + select { + case <-quitChannel: + return + default: + atomic.StoreInt64(&limiter.currentThreshold, limiter.nextThreshold) + time.Sleep(limiter.refillPeriod) + close(limiter.broadcastChannel) + limiter.broadcastChannel = make(chan bool) + } + } + }() + // threshold updater + go func() { + for { + select { + case <-quitChannel: + return + default: + nextValue := limiter.nextThreshold + limiter.rampUpStep + if nextValue < 0 { + // int64 overflow + nextValue = int64(math.MaxInt64) + } + if nextValue > limiter.maxThreshold { + nextValue = limiter.maxThreshold + } + atomic.StoreInt64(&limiter.nextThreshold, nextValue) + time.Sleep(limiter.rampUpPeroid) + } + } + }() +} + +// Acquire a token from the bucket, returns true if the bucket is exhausted. +func (limiter *RampUpRateLimiter) Acquire() (blocked bool) { + permit := atomic.AddInt64(&limiter.currentThreshold, -1) + if permit < 0 { + blocked = true + // block until the bucket is refilled + <-limiter.broadcastChannel + } else { + blocked = false + } + return blocked +} + +// Stop the rate limiter. +func (limiter *RampUpRateLimiter) Stop() { + limiter.nextThreshold = 0 + close(limiter.quitChannel) +} diff --git a/go/third_party/boomer/runner.go b/go/third_party/boomer/runner.go new file mode 100644 index 0000000..cc2d31e --- /dev/null +++ b/go/third_party/boomer/runner.go @@ -0,0 +1,555 @@ +package boomer + +import ( + "fmt" + "log" + "math/rand" + "os" + "runtime/debug" + "strings" + "sync" + "sync/atomic" + "time" +) + +const ( + stateInit = "ready" + stateSpawning = "spawning" + stateRunning = "running" + stateStopped = "stopped" + stateQuitting = "quitting" +) + +const ( + slaveReportInterval = 3 * time.Second + heartbeatInterval = 1 * time.Second +) + +type runner struct { + state string + + tasks []*Task + totalTaskWeight int + + rateLimiter RateLimiter + rateLimitEnabled bool + stats *requestStats + + numClients int32 + spawnRate float64 + + // all running workers(goroutines) will select on this channel. + // close this channel will stop all running workers. + stopChan chan bool + + // close this channel will stop all goroutines used in runner. + closeChan chan bool + + outputs []Output +} + +// safeRun runs fn and recovers from unexpected panics. +// it prevents panics from Task.Fn crashing boomer. +func (r *runner) safeRun(fn func()) { + defer func() { + // don't panic + err := recover() + if err != nil { + stackTrace := debug.Stack() + errMsg := fmt.Sprintf("%v", err) + os.Stderr.Write([]byte(errMsg)) + os.Stderr.Write([]byte("\n")) + os.Stderr.Write(stackTrace) + } + }() + fn() +} + +func (r *runner) addOutput(o Output) { + r.outputs = append(r.outputs, o) +} + +func (r *runner) outputOnStart() { + size := len(r.outputs) + if size == 0 { + return + } + wg := sync.WaitGroup{} + wg.Add(size) + for _, output := range r.outputs { + go func(o Output) { + o.OnStart() + wg.Done() + }(output) + } + wg.Wait() +} + +func (r *runner) outputOnEevent(data map[string]interface{}) { + size := len(r.outputs) + if size == 0 { + return + } + wg := sync.WaitGroup{} + wg.Add(size) + for _, output := range r.outputs { + go func(o Output) { + o.OnEvent(data) + wg.Done() + }(output) + } + wg.Wait() +} + +func (r *runner) outputOnStop() { + size := len(r.outputs) + if size == 0 { + return + } + wg := sync.WaitGroup{} + wg.Add(size) + for _, output := range r.outputs { + go func(o Output) { + o.OnStop() + wg.Done() + }(output) + } + wg.Wait() +} + +func (r *runner) spawnWorkers(spawnCount int, quit chan bool, spawnCompleteFunc func()) { + log.Println("Spawning", spawnCount, "clients at the rate", r.spawnRate, "clients/s...") + + for i := 1; i <= spawnCount; i++ { + sleepTime := time.Duration(1000000/r.spawnRate) * time.Microsecond + time.Sleep(sleepTime) + + select { + case <-quit: + // quit spawning goroutine + return + default: + atomic.AddInt32(&r.numClients, 1) + go func() { + for { + select { + case <-quit: + return + default: + if r.rateLimitEnabled { + blocked := r.rateLimiter.Acquire() + if !blocked { + task := r.getTask() + r.safeRun(task.Fn) + } + } else { + task := r.getTask() + r.safeRun(task.Fn) + } + } + } + }() + } + } + + if spawnCompleteFunc != nil { + spawnCompleteFunc() + } +} + +// setTasks will set the runner's task list AND the total task weight +// which is used to get a random task later +func (r *runner) setTasks(t []*Task) { + r.tasks = t + + weightSum := 0 + for _, task := range r.tasks { + weightSum += task.Weight + } + r.totalTaskWeight = weightSum +} + +func (r *runner) getTask() *Task { + tasksCount := len(r.tasks) + if tasksCount == 1 { + // Fast path + return r.tasks[0] + } + + rs := rand.New(rand.NewSource(time.Now().UnixNano())) + + totalWeight := r.totalTaskWeight + if totalWeight <= 0 { + // If all the tasks have not weights defined, they have the same chance to run + randNum := rs.Intn(tasksCount) + return r.tasks[randNum] + } + + randNum := rs.Intn(totalWeight) + runningSum := 0 + for _, task := range r.tasks { + runningSum += task.Weight + if runningSum > randNum { + return task + } + } + + return nil +} + +func (r *runner) startSpawning(spawnCount int, spawnRate float64, spawnCompleteFunc func()) { + Events.Publish("boomer:hatch", spawnCount, spawnRate) + Events.Publish("boomer:spawn", spawnCount, spawnRate) + + r.stats.clearStatsChan <- true + r.stopChan = make(chan bool) + + r.spawnRate = spawnRate + r.numClients = 0 + + go r.spawnWorkers(spawnCount, r.stopChan, spawnCompleteFunc) +} + +func (r *runner) stop() { + // publish the boomer stop event + // user's code can subscribe to this event and do thins like cleaning up + Events.Publish("boomer:stop") + + // stop previous goroutines without blocking + // those goroutines will exit when r.safeRun returns + close(r.stopChan) + if r.rateLimitEnabled { + r.rateLimiter.Stop() + } +} + +type localRunner struct { + runner + + spawnCount int +} + +func newLocalRunner(tasks []*Task, rateLimiter RateLimiter, spawnCount int, spawnRate float64) (r *localRunner) { + r = &localRunner{} + r.setTasks(tasks) + r.spawnRate = spawnRate + r.spawnCount = spawnCount + r.closeChan = make(chan bool) + r.addOutput(NewConsoleOutput()) + + if rateLimiter != nil { + r.rateLimitEnabled = true + r.rateLimiter = rateLimiter + } + + r.stats = newRequestStats() + return r +} + +func (r *localRunner) run() { + r.state = stateInit + r.stats.start() + + wg := sync.WaitGroup{} + wg.Add(1) + go func() { + for { + select { + case data := <-r.stats.messageToRunnerChan: + data["user_classes_count"] = map[string]int{"BoomerWorker": int(r.numClients)} + r.outputOnEevent(data) + case <-r.closeChan: + Events.Publish("boomer:quit") + r.stop() + wg.Done() + return + } + } + }() + + if r.rateLimitEnabled { + r.rateLimiter.Start() + } + r.startSpawning(r.spawnCount, r.spawnRate, nil) + + wg.Wait() +} + +func (r *localRunner) close() { + if r.stats != nil { + r.stats.close() + } + close(r.closeChan) +} + +// SlaveRunner connects to the master, spawns goroutines and collects stats. +type slaveRunner struct { + runner + + nodeID string + masterHost string + masterPort int + client client +} + +func newSlaveRunner(masterHost string, masterPort int, tasks []*Task, rateLimiter RateLimiter) (r *slaveRunner) { + r = &slaveRunner{} + r.masterHost = masterHost + r.masterPort = masterPort + r.setTasks(tasks) + r.nodeID = getNodeID() + r.closeChan = make(chan bool) + + if rateLimiter != nil { + r.rateLimitEnabled = true + r.rateLimiter = rateLimiter + } + + r.stats = newRequestStats() + return r +} + +func (r *slaveRunner) spawnComplete() { + data := make(map[string]interface{}) + data["user_classes_count"] = map[string]int{"BoomerWorker": int(r.numClients)} + r.client.sendChannel() <- newMessage("spawning_complete", data, r.nodeID) + r.state = stateRunning +} + +func (r *slaveRunner) onQuiting() { + if r.state != stateQuitting { + r.client.sendChannel() <- newMessage("quit", nil, r.nodeID) + } +} + +func (r *slaveRunner) close() { + if r.stats != nil { + r.stats.close() + } + if r.client != nil { + r.client.close() + } + close(r.closeChan) +} + +func (r *slaveRunner) onSpawnMessage(msg *message) { + r.client.sendChannel() <- newMessage("spawning", nil, r.nodeID) + // locust >= 2.0: user_classes_count is a map[class]count; spawn_rate lives + // in parsed_options. Fall back to legacy num_users/spawn_rate fields. + var spawnRate float64 + workers := 0 + data := msgDataMap(msg) + if ucc, ok := data["user_classes_count"]; ok { + switch m := ucc.(type) { + case map[string]interface{}: + for _, v := range m { + workers += int(toInt64(v)) + } + case map[interface{}]interface{}: + for _, v := range m { + workers += int(toInt64(v)) + } + } + if po, ok := data["parsed_options"]; ok { + switch pm := po.(type) { + case map[string]interface{}: + if sr, ok := pm["spawn_rate"]; ok { + spawnRate = toFloat64(sr) + } + case map[interface{}]interface{}: + if sr, ok := pm["spawn_rate"]; ok { + spawnRate = toFloat64(sr) + } + } + } + } else { + rate := data["spawn_rate"] + users := data["num_users"] + spawnRate = rate.(float64) + if _, ok := users.(uint64); ok { + workers = int(users.(uint64)) + } else { + workers = int(users.(int64)) + } + } + if spawnRate <= 0 { + spawnRate = float64(workers) + } + + if r.rateLimitEnabled { + r.rateLimiter.Start() + } + r.startSpawning(workers, spawnRate, r.spawnComplete) +} + + +func msgDataMap(msg *message) map[string]interface{} { + switch m := msg.Data.(type) { + case map[string]interface{}: + return m + case map[interface{}]interface{}: + out := make(map[string]interface{}, len(m)) + for k, v := range m { + if ks, ok := k.(string); ok { + out[ks] = v + } + } + return out + } + return nil +} + +func toInt64(v interface{}) int64 { + switch n := v.(type) { + case int64: + return n + case uint64: + return int64(n) + case int: + return int64(n) + case int32: + return int64(n) + case uint32: + return int64(n) + case float64: + return int64(n) + } + return 0 +} + +func toFloat64(v interface{}) float64 { + switch n := v.(type) { + case float64: + return n + case int64: + return float64(n) + case uint64: + return float64(n) + case int: + return float64(n) + } + return 0 +} + +// Runner acts as a state machine. +func (r *slaveRunner) onMessage(msg *message) { + if msg.Type == "hatch" { + log.Println("The master sent a 'hatch' message, you are using an unsupported locust version, please update locust to 1.2.") + return + } + + switch r.state { + case stateInit: + switch msg.Type { + case "spawn": + r.state = stateSpawning + r.onSpawnMessage(msg) + case "quit": + Events.Publish("boomer:quit") + } + case stateSpawning: + fallthrough + case stateRunning: + switch msg.Type { + case "spawn": + r.state = stateSpawning + r.stop() + r.onSpawnMessage(msg) + case "stop": + r.stop() + r.state = stateStopped + log.Println("Recv stop message from master, all the goroutines are stopped") + r.client.sendChannel() <- newMessage("client_stopped", nil, r.nodeID) + r.client.sendChannel() <- newMessage("client_ready", -1, r.nodeID) + r.state = stateInit + case "quit": + r.stop() + log.Println("Recv quit message from master, all the goroutines are stopped") + Events.Publish("boomer:quit") + r.state = stateInit + } + case stateStopped: + switch msg.Type { + case "spawn": + r.state = stateSpawning + r.onSpawnMessage(msg) + case "quit": + Events.Publish("boomer:quit") + r.state = stateInit + } + } +} + +func (r *slaveRunner) startListener() { + go func() { + for { + select { + case msg := <-r.client.recvChannel(): + r.onMessage(msg) + case <-r.closeChan: + return + } + } + }() +} + +func (r *slaveRunner) run() { + r.state = stateInit + r.client = newClient(r.masterHost, r.masterPort, r.nodeID) + + err := r.client.connect() + if err != nil { + if strings.Contains(err.Error(), "Socket type DEALER is not compatible with PULL") { + log.Println("Newer version of locust changes ZMQ socket to DEALER and ROUTER, you should update your locust version.") + } else { + log.Printf("Failed to connect to master(%s:%d) with error %v\n", r.masterHost, r.masterPort, err) + } + return + } + + // listen to master + r.startListener() + + r.stats.start() + + // tell master, I'm ready + r.client.sendChannel() <- newMessage("client_ready", -1, r.nodeID) + + // report to master + go func() { + for { + select { + case data := <-r.stats.messageToRunnerChan: + if r.state == stateInit || r.state == stateStopped { + continue + } + data["user_classes_count"] = map[string]int{"BoomerWorker": int(r.numClients)} + r.client.sendChannel() <- newMessage("stats", data, r.nodeID) + r.outputOnEevent(data) + case <-r.closeChan: + return + } + } + }() + + // heartbeat + // See: https://github.com/locustio/locust/commit/a8c0d7d8c588f3980303358298870f2ea394ab93 + go func() { + var ticker = time.NewTicker(heartbeatInterval) + for { + select { + case <-ticker.C: + CPUUsage := GetCurrentCPUUsage() + data := map[string]interface{}{ + "state": r.state, + "current_cpu_usage": CPUUsage, + } + r.client.sendChannel() <- newMessage("heartbeat", data, r.nodeID) + case <-r.closeChan: + return + } + } + }() + + Events.Subscribe("boomer:quit", r.onQuiting) +} diff --git a/go/third_party/boomer/stats.go b/go/third_party/boomer/stats.go new file mode 100644 index 0000000..be5b63a --- /dev/null +++ b/go/third_party/boomer/stats.go @@ -0,0 +1,309 @@ +package boomer + +import ( + "time" +) + +type requestSuccess struct { + requestType string + name string + responseTime int64 + responseLength int64 +} + +type requestFailure struct { + requestType string + name string + responseTime int64 + error string +} + +type requestStats struct { + entries map[string]*statsEntry + errors map[string]*statsError + total *statsEntry + startTime int64 + + requestSuccessChan chan *requestSuccess + requestFailureChan chan *requestFailure + clearStatsChan chan bool + messageToRunnerChan chan map[string]interface{} + shutdownChan chan bool +} + +func newRequestStats() (stats *requestStats) { + entries := make(map[string]*statsEntry) + errors := make(map[string]*statsError) + + stats = &requestStats{ + entries: entries, + errors: errors, + } + stats.requestSuccessChan = make(chan *requestSuccess, 100) + stats.requestFailureChan = make(chan *requestFailure, 100) + stats.clearStatsChan = make(chan bool) + stats.messageToRunnerChan = make(chan map[string]interface{}, 10) + stats.shutdownChan = make(chan bool) + + stats.total = &statsEntry{ + name: "Total", + method: "", + } + stats.total.reset() + + return stats +} + +func (s *requestStats) logRequest(method, name string, responseTime int64, contentLength int64) { + s.total.log(responseTime, contentLength) + s.get(name, method).log(responseTime, contentLength) +} + +func (s *requestStats) logError(method, name, err string) { + s.total.logError(err) + s.get(name, method).logError(err) + + // store error in errors map + key := MD5(method, name, err) + entry, ok := s.errors[key] + if !ok { + entry = &statsError{ + name: name, + method: method, + error: err, + } + s.errors[key] = entry + } + entry.occured() +} + +func (s *requestStats) get(name string, method string) (entry *statsEntry) { + entry, ok := s.entries[name+method] + if !ok { + newEntry := &statsEntry{ + name: name, + method: method, + numReqsPerSec: make(map[int64]int64), + responseTimes: make(map[int64]int64), + } + newEntry.reset() + s.entries[name+method] = newEntry + return newEntry + } + return entry +} + +func (s *requestStats) clearAll() { + s.total = &statsEntry{ + name: "Total", + method: "", + } + s.total.reset() + + s.entries = make(map[string]*statsEntry) + s.errors = make(map[string]*statsError) + s.startTime = time.Now().Unix() +} + +func (s *requestStats) serializeStats() []interface{} { + entries := make([]interface{}, 0, len(s.entries)) + for _, v := range s.entries { + if !(v.numRequests == 0 && v.numFailures == 0) { + entries = append(entries, v.getStrippedReport()) + } + } + return entries +} + +func (s *requestStats) serializeErrors() map[string]map[string]interface{} { + errors := make(map[string]map[string]interface{}) + for k, v := range s.errors { + errors[k] = v.toMap() + } + return errors +} + +func (s *requestStats) collectReportData() map[string]interface{} { + data := make(map[string]interface{}) + data["stats"] = s.serializeStats() + data["stats_total"] = s.total.getStrippedReport() + data["errors"] = s.serializeErrors() + s.errors = make(map[string]*statsError) + return data +} + +func (s *requestStats) start() { + go func() { + var ticker = time.NewTicker(slaveReportInterval) + for { + select { + case m := <-s.requestSuccessChan: + s.logRequest(m.requestType, m.name, m.responseTime, m.responseLength) + case n := <-s.requestFailureChan: + s.logRequest(n.requestType, n.name, n.responseTime, 0) + s.logError(n.requestType, n.name, n.error) + case <-s.clearStatsChan: + s.clearAll() + case <-ticker.C: + data := s.collectReportData() + // send data to channel, no network IO in this goroutine + s.messageToRunnerChan <- data + case <-s.shutdownChan: + return + } + } + }() +} + +// close is used by unit tests to avoid leakage of goroutines +func (s *requestStats) close() { + close(s.shutdownChan) +} + +type statsEntry struct { + name string + method string + numRequests int64 + numFailures int64 + totalResponseTime int64 + minResponseTime int64 + maxResponseTime int64 + numReqsPerSec map[int64]int64 + numFailPerSec map[int64]int64 + responseTimes map[int64]int64 + totalContentLength int64 + startTime int64 + lastRequestTimestamp int64 +} + +func (s *statsEntry) reset() { + s.startTime = time.Now().Unix() + s.numRequests = 0 + s.numFailures = 0 + s.totalResponseTime = 0 + s.responseTimes = make(map[int64]int64) + s.minResponseTime = 0 + s.maxResponseTime = 0 + s.lastRequestTimestamp = time.Now().Unix() + s.numReqsPerSec = make(map[int64]int64) + s.numFailPerSec = make(map[int64]int64) + s.totalContentLength = 0 +} + +func (s *statsEntry) log(responseTime int64, contentLength int64) { + s.numRequests++ + + s.logTimeOfRequest() + s.logResponseTime(responseTime) + + s.totalContentLength += contentLength +} + +func (s *statsEntry) logTimeOfRequest() { + key := time.Now().Unix() + _, ok := s.numReqsPerSec[key] + if !ok { + s.numReqsPerSec[key] = 1 + } else { + s.numReqsPerSec[key]++ + } + + s.lastRequestTimestamp = key +} + +func (s *statsEntry) logResponseTime(responseTime int64) { + s.totalResponseTime += responseTime + + if s.minResponseTime == 0 { + s.minResponseTime = responseTime + } + + if responseTime < s.minResponseTime { + s.minResponseTime = responseTime + } + + if responseTime > s.maxResponseTime { + s.maxResponseTime = responseTime + } + + var roundedResponseTime int64 + + // to avoid to much data that has to be transferred to the master node when + // running in distributed mode, we save the response time rounded in a dict + // so that 147 becomes 150, 3432 becomes 3400 and 58760 becomes 59000 + // see also locust's stats.py + if responseTime < 100 { + roundedResponseTime = responseTime + } else if responseTime < 1000 { + roundedResponseTime = int64(round(float64(responseTime), .5, -1)) + } else if responseTime < 10000 { + roundedResponseTime = int64(round(float64(responseTime), .5, -2)) + } else { + roundedResponseTime = int64(round(float64(responseTime), .5, -3)) + } + + _, ok := s.responseTimes[roundedResponseTime] + if !ok { + s.responseTimes[roundedResponseTime] = 1 + } else { + s.responseTimes[roundedResponseTime]++ + } +} + +func (s *statsEntry) logError(err string) { + s.numFailures++ + key := time.Now().Unix() + _, ok := s.numFailPerSec[key] + if !ok { + s.numFailPerSec[key] = 1 + } else { + s.numFailPerSec[key]++ + } +} + +func (s *statsEntry) serialize() map[string]interface{} { + result := make(map[string]interface{}) + result["name"] = s.name + result["method"] = s.method + result["last_request_timestamp"] = s.lastRequestTimestamp + result["start_time"] = s.startTime + result["num_requests"] = s.numRequests + // Boomer doesn't allow None response time for requests like locust. + // num_none_requests is added to keep compatible with locust. + result["num_none_requests"] = 0 + result["num_failures"] = s.numFailures + result["total_response_time"] = s.totalResponseTime + result["max_response_time"] = s.maxResponseTime + result["min_response_time"] = s.minResponseTime + result["total_content_length"] = s.totalContentLength + result["response_times"] = s.responseTimes + result["num_reqs_per_sec"] = s.numReqsPerSec + result["num_fail_per_sec"] = s.numFailPerSec + return result +} + +func (s *statsEntry) getStrippedReport() map[string]interface{} { + report := s.serialize() + s.reset() + return report +} + +type statsError struct { + name string + method string + error string + occurrences int64 +} + +func (err *statsError) occured() { + err.occurrences++ +} + +func (err *statsError) toMap() map[string]interface{} { + m := make(map[string]interface{}) + m["method"] = err.method + m["name"] = err.name + m["error"] = err.error + m["occurrences"] = err.occurrences + return m +} diff --git a/go/third_party/boomer/task.go b/go/third_party/boomer/task.go new file mode 100644 index 0000000..e913d09 --- /dev/null +++ b/go/third_party/boomer/task.go @@ -0,0 +1,13 @@ +package boomer + +// Task is like the "Locust object" in locust, the python version. +// When boomer receives a start message from master, it will spawn several goroutines to run Task.Fn. +// But users can keep some information in the python version, they can't do the same things in boomer. +// Because Task.Fn is a pure function. +type Task struct { + // The weight is used to distribute goroutines over multiple tasks. + Weight int + // Fn is called by the goroutines allocated to this task, in a loop. + Fn func() + Name string +} diff --git a/go/third_party/boomer/taskset.go b/go/third_party/boomer/taskset.go new file mode 100644 index 0000000..112332c --- /dev/null +++ b/go/third_party/boomer/taskset.go @@ -0,0 +1,107 @@ +package boomer + +import ( + "math/rand" + "sync" + "time" +) + +// TaskSet is an experimental feature, the API is not stabilized. +// It needs to be more considered and tested. +type TaskSet interface { + // Add a Task to the TaskSet. + AddTask(task *Task) + // Set the weight of the TaskSet. + SetWeight(weight int) + // Get the weight of the TaskSet. + GetWeight() (weight int) + // Run will pick up a Task from the TaskSet and run. + Run() +} + +// WeighingTaskSet is a implementation of the TaskSet interface. +// When a Task is added to WeighingTaskSet, it's weight is used +// to calculate the probability to be called. +type WeighingTaskSet struct { + weight int + offset int + tasks []*Task + index []int + lock sync.RWMutex +} + +// NewWeighingTaskSet returns a new WeighingTaskSet. +func NewWeighingTaskSet() *WeighingTaskSet { + return &WeighingTaskSet{ + weight: 0, + offset: 0, + tasks: make([]*Task, 0), + index: make([]int, 0), + } +} + +// AddTask add a Task to the Weighing TaskSet. +// If the task's weight is <=0, it will be ignored. +func (ts *WeighingTaskSet) AddTask(task *Task) { + if task.Weight <= 0 { + return + } + ts.lock.Lock() + ts.tasks = append(ts.tasks, task) + ts.offset = ts.offset + task.Weight + ts.index = append(ts.index, ts.offset) + ts.lock.Unlock() +} + +func (ts *WeighingTaskSet) binarySearch(roll int) (task *Task) { + left := 0 + right := len(ts.index) - 1 + for left <= right { + mid := (left + right) / 2 + if left == mid { + if roll < ts.index[mid] { + return ts.tasks[mid] + } + return ts.tasks[mid+1] + } + if ts.index[mid-1] <= roll && roll < ts.index[mid] { + return ts.tasks[mid] + } + if roll < ts.index[mid-1] { + right = mid - 1 + } else { + left = mid + 1 + } + } + return nil +} + +// GetTask returns a task in the task set. +func (ts *WeighingTaskSet) GetTask(roll int) (task *Task) { + if roll < 0 || roll >= ts.offset { + return nil + } + ts.lock.RLock() + task = ts.binarySearch(roll) + ts.lock.RUnlock() + return task +} + +// SetWeight sets the weight of the task set. +func (ts *WeighingTaskSet) SetWeight(weight int) { + ts.weight = weight +} + +// GetWeight returns the weight of the task set. +func (ts *WeighingTaskSet) GetWeight() (weight int) { + return ts.weight +} + +// Run will pick up a task in the task set randomly and run. +// It can is used as a Task.Fn. +func (ts *WeighingTaskSet) Run() { + r := rand.New(rand.NewSource(time.Now().UnixNano())) + roll := r.Intn(ts.offset) + task := ts.GetTask(roll) + task.Fn() +} diff --git a/go/third_party/boomer/utils.go b/go/third_party/boomer/utils.go new file mode 100644 index 0000000..69599e8 --- /dev/null +++ b/go/third_party/boomer/utils.go @@ -0,0 +1,110 @@ +package boomer + +import ( + "crypto/md5" + "fmt" + "io" + "log" + "math" + "os" + "runtime" + "runtime/pprof" + "strings" + "time" + + "github.com/google/uuid" + "github.com/shirou/gopsutil/process" +) + +func round(val float64, roundOn float64, places int) (newVal float64) { + var round float64 + pow := math.Pow(10, float64(places)) + digit := pow * val + _, div := math.Modf(digit) + if div >= roundOn { + round = math.Ceil(digit) + } else { + round = math.Floor(digit) + } + newVal = round / pow + return +} + +// MD5 returns the md5 hash of strings. +func MD5(slice ...string) string { + h := md5.New() + for _, v := range slice { + io.WriteString(h, v) + } + return fmt.Sprintf("%x", h.Sum(nil)) +} + +// generate a random nodeID like locust does, using the same algorithm. +func getNodeID() (nodeID string) { + hostname, _ := os.Hostname() + id := strings.Replace(uuid.New().String(), "-", "", -1) + nodeID = fmt.Sprintf("%s_%s", hostname, id) + return +} + +// Now returns the current timestamp in milliseconds. +func Now() int64 { + return time.Now().UnixNano() / int64(time.Millisecond) +} + +// StartMemoryProfile starts memory profiling and save the results in file. +func StartMemoryProfile(file string, duration time.Duration) (err error) { + f, err := os.Create(file) + if err != nil { + return err + } + + log.Println("Start memory profiling for", duration) + time.AfterFunc(duration, func() { + err = pprof.WriteHeapProfile(f) + if err != nil { + log.Println(err) + } + f.Close() + log.Println("Stop memory profiling after", duration) + }) + return nil +} + +// StartCPUProfile starts cpu profiling and save the results in file. +func StartCPUProfile(file string, duration time.Duration) (err error) { + f, err := os.Create(file) + if err != nil { + return err + } + + log.Println("Start cpu profiling for", duration) + err = pprof.StartCPUProfile(f) + if err != nil { + f.Close() + return err + } + + time.AfterFunc(duration, func() { + pprof.StopCPUProfile() + f.Close() + log.Println("Stop CPU profiling after", duration) + }) + return nil +} + +// GetCurrentCPUUsage get current CPU usage +func GetCurrentCPUUsage() float64 { + currentPid := os.Getpid() + p, err := process.NewProcess(int32(currentPid)) + if err != nil { + log.Printf("Fail to get CPU percent, %v\n", err) + return 0.0 + } + percent, err := p.CPUPercent() + if err != nil { + log.Printf("Fail to get CPU percent, %v\n", err) + return 0.0 + } + return percent / float64(runtime.NumCPU()) +} diff --git a/python/locustfile.py b/python/locustfile.py new file mode 100644 index 0000000..9f1d896 --- /dev/null +++ b/python/locustfile.py @@ -0,0 +1,75 @@ +"""Python worker(Locust 原生 HttpUser):4 类交易请求建模。 + +与 go/ 下的 boomer worker 跑**完全相同**的场景、请求体与用户池, +唯一差异是执行引擎(Python/GIL vs Go/goroutine),保证对比公平。 + +任务注册由 TASK_WEIGHTS 配置驱动(避免把任务硬写死在入口导致漏注册)。 +""" + +import os +import random +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import stats_dump # noqa: F401,E402 (注册 quitting 落盘监听) + +from locust import HttpUser, between, task # noqa: E402 + +USER_POOL_SIZE = 1000 # 真随机用户池:避免全员压同一用户导致分布失真 +TASK_WEIGHTS = { # 配置驱动,改权重不用动代码 + "limit_open": 4, + "market_quantity_open": 2, + "market_amount_open": 2, + "batch_cancel": 1, +} + + +class TraderUser(HttpUser): + wait_time = between(0.001, 0.005) # 尽量压满,把瓶颈暴露给 worker 侧 + + def on_start(self): + self.user_id = random.randint(1, USER_POOL_SIZE) + self.open_orders = [] + + def _payload(self, with_price=True): + p = { + "user_id": self.user_id, + "contract_id": random.choice([1, 2, 3]), + "side": random.choice(["ask", "bid"]), + "margin_type": random.choice([1, 2]), + "quantity": str(random.randint(1, 50)), + } + if with_price: + p["price"] = str(round(random.uniform(28000, 32000), 2)) + return p + + @task(TASK_WEIGHTS["limit_open"]) + def limit_open(self): + with self.client.post("/api/v1/order/limit/open", + json=self._payload(), + catch_response=True, + name="/api/v1/order/limit/open") as r: + if r.status_code == 200 and r.json().get("code") == 0: + self.open_orders.append(r.json()["data"]["order_id"]) + else: + r.failure(f"biz error: {r.text[:100]}") + + @task(TASK_WEIGHTS["market_quantity_open"]) + def market_quantity_open(self): + self.client.post("/api/v1/order/market/quantity/open", + json=self._payload(with_price=False), + name="/api/v1/order/market/quantity/open") + + @task(TASK_WEIGHTS["market_amount_open"]) + def market_amount_open(self): + self.client.post("/api/v1/order/market/amount/open", + json=self._payload(with_price=False), + name="/api/v1/order/market/amount/open") + + @task(TASK_WEIGHTS["batch_cancel"]) + def batch_cancel(self): + ids, self.open_orders = self.open_orders[:10], self.open_orders[10:] + self.client.request("DELETE", "/api/v1/order/batch/cancel", + json={"user_id": self.user_id, + "order_ids": ids or [0]}, + name="/api/v1/order/batch/cancel") diff --git a/python/master_locustfile.py b/python/master_locustfile.py new file mode 100644 index 0000000..d7dbbec --- /dev/null +++ b/python/master_locustfile.py @@ -0,0 +1,21 @@ +"""Go worker 压测时的 Locust master 入口。 + +master 本身不执行请求(负载由 boomer worker 产生),只需一个 User 类占位, +并复用 stats_dump 在 quitting 时落 JSON 结果。 +""" + +import os +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import stats_dump # noqa: F401,E402 + +from locust import HttpUser, task # noqa: E402 + + +class PlaceholderUser(HttpUser): + """占位 User:master 不跑任务,真实 task 在 boomer worker 侧注册。""" + + @task + def noop(self): + pass diff --git a/python/stats_dump.py b/python/stats_dump.py new file mode 100644 index 0000000..28454ff --- /dev/null +++ b/python/stats_dump.py @@ -0,0 +1,70 @@ +"""Locust 统计落盘插件:run 结束时把 stats 序列化为 JSON 到 results/。 + +供 python worker 与 go worker(master 侧)共用 —— go 压测时统计也在 master 汇总, +所以两份 locustfile 都 import 本模块。文件名前缀由环境变量 PERF_WORKER 决定。 +""" + +import json +import os +import time + +from locust import events + +RESULTS_DIR = os.path.join(os.path.dirname(os.path.dirname( + os.path.abspath(__file__))), "results") + + +def _serialize(environment): + stats = environment.stats + entries = [] + for e in stats.entries.values(): + entries.append({ + "name": e.name, + "method": e.method, + "num_requests": e.num_requests, + "num_failures": e.num_failures, + "avg_response_time": round(e.avg_response_time, 3), + "min_response_time": e.min_response_time, + "max_response_time": e.max_response_time, + "p50": round(e.get_response_time_percentile(0.50), 3), + "p95": round(e.get_response_time_percentile(0.95), 3), + "p99": round(e.get_response_time_percentile(0.99), 3), + "rps": round(e.total_rps, 3), + }) + total = stats.total + doc = { + "worker": os.environ.get("PERF_WORKER", "unknown"), + "timestamp": time.strftime("%Y-%m-%dT%H:%M:%S"), + "load": { + "users": getattr(environment.parsed_options, "num_users", None), + "run_time": getattr(environment.parsed_options, "run_time", None), + "host": getattr(environment.parsed_options, "host", None), + }, + "total": { + "num_requests": total.num_requests, + "num_failures": total.num_failures, + "avg_response_time": round(total.avg_response_time, 3), + "p50": round(total.get_response_time_percentile(0.50), 3), + "p95": round(total.get_response_time_percentile(0.95), 3), + "p99": round(total.get_response_time_percentile(0.99), 3), + "rps": round(total.total_rps, 3), + }, + "entries": entries, + } + label = os.environ.get("PERF_LABEL") + if label: + # 实验参数透传(如 scale 实验的 instances/max_qps),写进结果便于报告核对 + doc["label"] = label + return doc + + +@events.quitting.add_listener +def _dump(environment, **kwargs): + if environment.parsed_options and environment.parsed_options.worker: + return # worker 进程不落盘 + os.makedirs(RESULTS_DIR, exist_ok=True) + worker = os.environ.get("PERF_WORKER", "unknown") + path = os.path.join(RESULTS_DIR, f"{worker}-{int(time.time())}.json") + with open(path, "w", encoding="utf-8") as f: + json.dump(_serialize(environment), f, ensure_ascii=False, indent=2) + print(f"\n[stats] written to {path}") diff --git a/report.md b/report.md new file mode 100644 index 0000000..fed0aad --- /dev/null +++ b/report.md @@ -0,0 +1,94 @@ +# perf-harness-demo 对比报告 + +> 生成自 24 份真实压测结果:`results/go-1789962012.json`, `results/go-1790009273.json`, `results/go-1790010541.json`, `results/go-1790054848.json`, `results/go-1790055182.json`, `results/live_trigger-1790009033.json`, `results/live_trigger-1790010331.json`, `results/live_trigger-1790054558.json`, `results/python-1789961949.json`, `results/python-1790009211.json`, `results/python-1790010434.json`, `results/python-1790054714.json`, `results/python-1790055119.json`, `results/scale-1-1790009085.json`, `results/scale-1-1790010617.json`, `results/scale-1-1790054950.json`, `results/scale-1-1790055215.json`, `results/scale-4-1790009118.json`, `results/scale-4-1790010691.json`, `results/scale-4-1790055053.json`, `results/scale-4-1790055249.json`, `results/stale_trigger-1790009032.json`, `results/stale_trigger-1790010330.json`, `results/stale_trigger-1790054558.json` + +## 0. 数字口径(先读这一节) + +| 口径 | 环境 | 数字 | +|---|---|---| +| **生产真实业绩** | 公司环境 · 多机集群 —— **不可由本仓库复现** | 10 用户并发 · 平均响应 1-2s · 24h 稳定 · 实测 10-12 万 TPS | +| **本机演示实测** | 单机 —— 由本仓库跑出,见下方第 2 节 | 见第 2 节表格 | + +> 生产数字是**背景**,不是本仓库的产出。本仓库是复现方法论的实验台,单机量级与生产环境不可比;**可比的是 Python 与 Go 两种 worker 的倍数差**。 + +## 1. 负载参数(公平性核对) + +| worker | users | run_time | host | +|---|---|---|---| +| go | 50 | 60 | http://127.0.0.1:18099 | +| go | 50 | 60 | http://127.0.0.1:18099 | +| go | 50 | 60 | http://127.0.0.1:18099 | +| go | 50 | 60 | http://127.0.0.1:18099 | +| go | 50 | 60 | http://127.0.0.1:18099 | +| python | 50 | 60 | http://127.0.0.1:18099 | +| python | 50 | 60 | http://127.0.0.1:18099 | +| python | 50 | 60 | http://127.0.0.1:18099 | +| python | 50 | 60 | http://127.0.0.1:18099 | +| python | 50 | 60 | http://127.0.0.1:18099 | + +两种 worker 跑**同一场景、同一并发、同一请求体**(4 类订单请求,权重 4:2:2:1,用户池 1000),唯一变量是执行引擎。 + +## 2. 指标对比(每 worker 取最近一轮) + +| worker | 请求数 | 错误率 | TPS | P50 (ms) | P95 (ms) | P99 (ms) | +|---|---|---|---|---|---|---| +| go | 1181444 | 0.00% | 20024.5 | 2 | 5 | 8 | +| python | 298351 | 0.00% | 4980.2 | 5 | 7 | 9 | + +**Go worker TPS 是 Python worker 的 4.02 倍**(20024 vs 4980,同并发同场景)。 + +## 3. 分 endpoint 明细 + +### go + +| endpoint | 请求数 | 错误 | TPS | P95 (ms) | P99 (ms) | +|---|---|---|---|---|---| +| DELETE /api/v1/order/batch/cancel | 131815 | 0 | 2234.2 | 5 | 8 | +| POST /api/v1/order/limit/open | 523948 | 0 | 8880.5 | 5 | 8 | +| POST /api/v1/order/market/amount/open | 262600 | 0 | 4450.8 | 5 | 8 | +| POST /api/v1/order/market/quantity/open | 263081 | 0 | 4459.0 | 5 | 8 | + +### python + +| endpoint | 请求数 | 错误 | TPS | P95 (ms) | P99 (ms) | +|---|---|---|---|---|---| +| DELETE /api/v1/order/batch/cancel | 33109 | 0 | 552.7 | 7 | 9 | +| POST /api/v1/order/limit/open | 132585 | 0 | 2213.2 | 7 | 9 | +| POST /api/v1/order/market/amount/open | 66841 | 0 | 1115.7 | 7 | 9 | +| POST /api/v1/order/market/quantity/open | 65816 | 0 | 1098.6 | 7 | 9 | + +## 4. 归因分析 + +- **GIL 瓶颈**:Python worker 单进程内所有用户协程共享一个 GIL,requests 库虽然 I/O 多,但 JSON 编解码、locust 统计、gevent 调度都是纯 CPU 段;并发越高,GIL 争抢越明显,单核打满后 TPS 触顶。 +- **Go 怎么绕开**:goroutine 由 Go runtime 多线程调度(GOMAXPROCS=核数),网络 I/O 走 netpoller,无全局锁;连接池调优后(MaxIdleConnsPerHost=1000,且有断言测试保证配置真的生效),单机轻松压出数倍 TPS。 +- **瓶颈定位**:本机压测会撞到多层瓶颈(mock 网关的 Python HTTP 层、loopback、worker 自身)。若两种 worker 的 P99 都高,瓶颈在被测服务侧;若 Go 的 TPS 显著高于 Python 且 P99 更低,瓶颈在 worker 侧(GIL)。本报告数字即按此判读。 +- **本轮判读**:TPS 比 4.02 → 瓶颈在 **Python worker 侧(GIL)**。 + +## 5. 失真对比实验(条件单触发率) + +两种脚本打**同一个**条件单 endpoint(`POST /api/v1/order/condition/open`),负载参数相同,唯一变量是**触发价的来源**。mock 标记价随时间波动(contract 1 ≈ 31000 ± 1%)。 + +| 脚本 | 相位 | 触发价策略 | 请求数 | 失败 | 触发数 | 触发率 | +|---|---|---|---|---|---|---| +| stale_trigger | hardcoded_low | 触发价写死 30500(低于行情区间) | 300 | 0 | 300 | 100.00% | +| stale_trigger | hardcoded_high | 触发价写死 31500(高于行情区间) | 300 | 0 | 0 | 0.00% | +| live_trigger | cache_driven | 触发价=实时标记价±20(缓存服务驱动) | 300 | 0 | 166 | 55.33% | + +**判读**: +- 所有相位失败数都是 0 —— 单看压测报表(TPS / 错误率 / 延迟),**每一轮都「一切正常」**。 +- 但写死触发价的相位触发率塌缩到 **100% 与 0%**:市场状态稍偏离写死的值,结论整个翻转 —— 这批数据对条件单链路的容量评估毫无意义,而报表上看不出任何问题(「数据是错的,但看起来是对的」)。 +- 缓存服务实时驱动的触发率为 **55.33%**,落在由行情波动决定的中间区间(不退化到 0/1),压测数据才对触发链路有评估意义。 +- 缓存服务的滑动窗口去重 / 断流回退语义由 `tests/test_mark_price_service.py` 钉死;触发判定方向由 `tests/test_condition_trigger.py` 钉死。 + +## 6. 横向扩展实验(单实例上限 → 多实例) + +被测 mock 设了单实例能力上限(`TARGET_MAX_QPS`,超限请求排队等位、延迟上升),入口分流器轮询分发。各组实验**除实例数外参数完全一致**(worker / 并发 / 时长 / 单实例上限,见「参数」列)。 + +| 实例数 | 请求数 | 错误率 | TPS | P50 (ms) | P95 (ms) | P99 (ms) | 参数 | +|---|---|---|---|---|---|---|---| +| 1 | 14696 | 0.00% | 506.8 | 200 | 200 | 200 | instances=1 max_qps=500/instance extra_latency=2ms users=100 | +| 4 | 58752 | 0.00% | 2025.9 | 49 | 52 | 53 | instances=4 max_qps=500/instance extra_latency=2ms users=100 | + +**4 实例 TPS / 1 实例 TPS = 4.00**(2026 vs 507;不要求线性 —— 分流器与 loopback 也会吃一份,TPS 随实例数上升即说明扩展是有效的)。 +- 单实例触顶时 P99 被排队显著拉高 —— 「上限」是**测出来的能力边界**,不是一句「慢」;扩展实例数的决策依据正是这个数字。 + diff --git a/results/go-1789962012.json b/results/go-1789962012.json new file mode 100644 index 0000000..8ff52b4 --- /dev/null +++ b/results/go-1789962012.json @@ -0,0 +1,72 @@ +{ + "worker": "go", + "timestamp": "2026-09-21T11:40:12", + "load": { + "users": 50, + "run_time": 60, + "host": "http://127.0.0.1:18099" + }, + "total": { + "num_requests": 1204302, + "num_failures": 0, + "avg_response_time": 1.899, + "p50": 1, + "p95": 5, + "p99": 8, + "rps": 20411.898 + }, + "entries": [ + { + "name": "/api/v1/order/market/quantity/open", + "method": "POST", + "num_requests": 267432, + "num_failures": 0, + "avg_response_time": 1.898, + "min_response_time": 0, + "max_response_time": 41, + "p50": 1, + "p95": 5, + "p99": 8, + "rps": 4532.746 + }, + { + "name": "/api/v1/order/limit/open", + "method": "POST", + "num_requests": 536115, + "num_failures": 0, + "avg_response_time": 1.9, + "min_response_time": 0, + "max_response_time": 44, + "p50": 1, + "p95": 5, + "p99": 8, + "rps": 9086.695 + }, + { + "name": "/api/v1/order/market/amount/open", + "method": "POST", + "num_requests": 267098, + "num_failures": 0, + "avg_response_time": 1.896, + "min_response_time": 0, + "max_response_time": 44, + "p50": 1, + "p95": 5, + "p99": 8, + "rps": 4527.085 + }, + { + "name": "/api/v1/order/batch/cancel", + "method": "DELETE", + "num_requests": 133657, + "num_failures": 0, + "avg_response_time": 1.905, + "min_response_time": 0, + "max_response_time": 45, + "p50": 1, + "p95": 5, + "p99": 8, + "rps": 2265.373 + } + ] +} \ No newline at end of file diff --git a/results/go-1790009273.json b/results/go-1790009273.json new file mode 100644 index 0000000..d39b508 --- /dev/null +++ b/results/go-1790009273.json @@ -0,0 +1,72 @@ +{ + "worker": "go", + "timestamp": "2026-09-22T00:47:53", + "load": { + "users": 50, + "run_time": 60, + "host": "http://127.0.0.1:18099" + }, + "total": { + "num_requests": 1178990, + "num_failures": 0, + "avg_response_time": 1.952, + "p50": 1, + "p95": 6, + "p99": 8, + "rps": 19649.833 + }, + "entries": [ + { + "name": "/api/v1/order/market/amount/open", + "method": "POST", + "num_requests": 261974, + "num_failures": 0, + "avg_response_time": 1.952, + "min_response_time": 0, + "max_response_time": 44, + "p50": 1, + "p95": 6, + "p99": 8, + "rps": 4366.233 + }, + { + "name": "/api/v1/order/market/quantity/open", + "method": "POST", + "num_requests": 261443, + "num_failures": 0, + "avg_response_time": 1.96, + "min_response_time": 0, + "max_response_time": 45, + "p50": 2, + "p95": 6, + "p99": 8, + "rps": 4357.383 + }, + { + "name": "/api/v1/order/batch/cancel", + "method": "DELETE", + "num_requests": 130859, + "num_failures": 0, + "avg_response_time": 1.95, + "min_response_time": 0, + "max_response_time": 33, + "p50": 1, + "p95": 6, + "p99": 8, + "rps": 2180.983 + }, + { + "name": "/api/v1/order/limit/open", + "method": "POST", + "num_requests": 524714, + "num_failures": 0, + "avg_response_time": 1.949, + "min_response_time": 0, + "max_response_time": 36, + "p50": 1, + "p95": 6, + "p99": 8, + "rps": 8745.233 + } + ] +} \ No newline at end of file diff --git a/results/go-1790010541.json b/results/go-1790010541.json new file mode 100644 index 0000000..6428db7 --- /dev/null +++ b/results/go-1790010541.json @@ -0,0 +1,72 @@ +{ + "worker": "go", + "timestamp": "2026-09-22T01:09:01", + "load": { + "users": 50, + "run_time": 60, + "host": "http://127.0.0.1:18099" + }, + "total": { + "num_requests": 1207984, + "num_failures": 0, + "avg_response_time": 1.882, + "p50": 1, + "p95": 5, + "p99": 8, + "rps": 20474.305 + }, + "entries": [ + { + "name": "/api/v1/order/limit/open", + "method": "POST", + "num_requests": 536645, + "num_failures": 0, + "avg_response_time": 1.881, + "min_response_time": 0, + "max_response_time": 39, + "p50": 1, + "p95": 5, + "p99": 8, + "rps": 9095.678 + }, + { + "name": "/api/v1/order/market/amount/open", + "method": "POST", + "num_requests": 268468, + "num_failures": 0, + "avg_response_time": 1.882, + "min_response_time": 0, + "max_response_time": 35, + "p50": 1, + "p95": 5, + "p99": 8, + "rps": 4550.305 + }, + { + "name": "/api/v1/order/market/quantity/open", + "method": "POST", + "num_requests": 268488, + "num_failures": 0, + "avg_response_time": 1.881, + "min_response_time": 0, + "max_response_time": 36, + "p50": 1, + "p95": 5, + "p99": 8, + "rps": 4550.644 + }, + { + "name": "/api/v1/order/batch/cancel", + "method": "DELETE", + "num_requests": 134383, + "num_failures": 0, + "avg_response_time": 1.889, + "min_response_time": 0, + "max_response_time": 36, + "p50": 2, + "p95": 5, + "p99": 8, + "rps": 2277.678 + } + ] +} \ No newline at end of file diff --git a/results/go-1790054848.json b/results/go-1790054848.json new file mode 100644 index 0000000..516158b --- /dev/null +++ b/results/go-1790054848.json @@ -0,0 +1,72 @@ +{ + "worker": "go", + "timestamp": "2026-09-22T13:27:28", + "load": { + "users": 50, + "run_time": 60, + "host": "http://127.0.0.1:18099" + }, + "total": { + "num_requests": 1224254, + "num_failures": 0, + "avg_response_time": 1.845, + "p50": 1, + "p95": 5, + "p99": 8, + "rps": 20750.068 + }, + "entries": [ + { + "name": "/api/v1/order/limit/open", + "method": "POST", + "num_requests": 543420, + "num_failures": 0, + "avg_response_time": 1.847, + "min_response_time": 0, + "max_response_time": 38, + "p50": 1, + "p95": 5, + "p99": 8, + "rps": 9210.508 + }, + { + "name": "/api/v1/order/batch/cancel", + "method": "DELETE", + "num_requests": 136373, + "num_failures": 0, + "avg_response_time": 1.848, + "min_response_time": 0, + "max_response_time": 44, + "p50": 1, + "p95": 5, + "p99": 8, + "rps": 2311.407 + }, + { + "name": "/api/v1/order/market/quantity/open", + "method": "POST", + "num_requests": 272441, + "num_failures": 0, + "avg_response_time": 1.843, + "min_response_time": 0, + "max_response_time": 34, + "p50": 1, + "p95": 5, + "p99": 8, + "rps": 4617.644 + }, + { + "name": "/api/v1/order/market/amount/open", + "method": "POST", + "num_requests": 272020, + "num_failures": 0, + "avg_response_time": 1.843, + "min_response_time": 0, + "max_response_time": 35, + "p50": 1, + "p95": 5, + "p99": 8, + "rps": 4610.508 + } + ] +} \ No newline at end of file diff --git a/results/go-1790055182.json b/results/go-1790055182.json new file mode 100644 index 0000000..93fcac8 --- /dev/null +++ b/results/go-1790055182.json @@ -0,0 +1,72 @@ +{ + "worker": "go", + "timestamp": "2026-09-22T13:33:02", + "load": { + "users": 50, + "run_time": 60, + "host": "http://127.0.0.1:18099" + }, + "total": { + "num_requests": 1181444, + "num_failures": 0, + "avg_response_time": 1.939, + "p50": 2, + "p95": 5, + "p99": 8, + "rps": 20024.475 + }, + "entries": [ + { + "name": "/api/v1/order/market/quantity/open", + "method": "POST", + "num_requests": 263081, + "num_failures": 0, + "avg_response_time": 1.935, + "min_response_time": 0, + "max_response_time": 52, + "p50": 2, + "p95": 5, + "p99": 8, + "rps": 4459.0 + }, + { + "name": "/api/v1/order/batch/cancel", + "method": "DELETE", + "num_requests": 131815, + "num_failures": 0, + "avg_response_time": 1.941, + "min_response_time": 0, + "max_response_time": 37, + "p50": 2, + "p95": 5, + "p99": 8, + "rps": 2234.153 + }, + { + "name": "/api/v1/order/limit/open", + "method": "POST", + "num_requests": 523948, + "num_failures": 0, + "avg_response_time": 1.94, + "min_response_time": 0, + "max_response_time": 56, + "p50": 2, + "p95": 5, + "p99": 8, + "rps": 8880.475 + }, + { + "name": "/api/v1/order/market/amount/open", + "method": "POST", + "num_requests": 262600, + "num_failures": 0, + "avg_response_time": 1.94, + "min_response_time": 0, + "max_response_time": 53, + "p50": 2, + "p95": 5, + "p99": 8, + "rps": 4450.847 + } + ] +} \ No newline at end of file diff --git a/results/live_trigger-1790009033.json b/results/live_trigger-1790009033.json new file mode 100644 index 0000000..9daa33b --- /dev/null +++ b/results/live_trigger-1790009033.json @@ -0,0 +1,47 @@ +{ + "worker": "live_trigger", + "timestamp": "2026-09-22T00:43:53", + "load": { + "users": 10, + "run_time": "300 req", + "host": "http://127.0.0.1:18099" + }, + "total": { + "num_requests": 300, + "num_failures": 0, + "avg_response_time": 1.81, + "p50": 1.489, + "p95": 3.806, + "p99": 8.439, + "rps": 2845.399 + }, + "entries": [ + { + "name": "/api/v1/order/condition/open", + "method": "POST", + "num_requests": 300, + "num_failures": 0, + "avg_response_time": 1.81, + "p50": 1.489, + "p95": 3.806, + "p99": 8.439, + "rps": 2845.399 + } + ], + "trigger": { + "mode": "live", + "phases": [ + { + "name": "cache_driven", + "detail": "触发价=实时标记价±20(缓存服务驱动)", + "requests": 300, + "failures": 0, + "triggered": 153, + "trigger_rate": 0.51, + "p50": 1.489, + "p95": 3.806, + "p99": 8.439 + } + ] + } +} \ No newline at end of file diff --git a/results/live_trigger-1790010331.json b/results/live_trigger-1790010331.json new file mode 100644 index 0000000..1aca80c --- /dev/null +++ b/results/live_trigger-1790010331.json @@ -0,0 +1,47 @@ +{ + "worker": "live_trigger", + "timestamp": "2026-09-22T01:05:31", + "load": { + "users": 10, + "run_time": "300 req", + "host": "http://127.0.0.1:18099" + }, + "total": { + "num_requests": 300, + "num_failures": 0, + "avg_response_time": 1.694, + "p50": 1.49, + "p95": 3.175, + "p99": 5.049, + "rps": 2941.507 + }, + "entries": [ + { + "name": "/api/v1/order/condition/open", + "method": "POST", + "num_requests": 300, + "num_failures": 0, + "avg_response_time": 1.694, + "p50": 1.49, + "p95": 3.175, + "p99": 5.049, + "rps": 2941.507 + } + ], + "trigger": { + "mode": "live", + "phases": [ + { + "name": "cache_driven", + "detail": "触发价=实时标记价±20(缓存服务驱动)", + "requests": 300, + "failures": 0, + "triggered": 145, + "trigger_rate": 0.4833, + "p50": 1.49, + "p95": 3.175, + "p99": 5.049 + } + ] + } +} \ No newline at end of file diff --git a/results/live_trigger-1790054558.json b/results/live_trigger-1790054558.json new file mode 100644 index 0000000..ee1a97b --- /dev/null +++ b/results/live_trigger-1790054558.json @@ -0,0 +1,47 @@ +{ + "worker": "live_trigger", + "timestamp": "2026-09-22T13:22:38", + "load": { + "users": 10, + "run_time": "300 req", + "host": "http://127.0.0.1:18099" + }, + "total": { + "num_requests": 300, + "num_failures": 0, + "avg_response_time": 1.804, + "p50": 1.696, + "p95": 3.125, + "p99": 3.866, + "rps": 2940.055 + }, + "entries": [ + { + "name": "/api/v1/order/condition/open", + "method": "POST", + "num_requests": 300, + "num_failures": 0, + "avg_response_time": 1.804, + "p50": 1.696, + "p95": 3.125, + "p99": 3.866, + "rps": 2940.055 + } + ], + "trigger": { + "mode": "live", + "phases": [ + { + "name": "cache_driven", + "detail": "触发价=实时标记价±20(缓存服务驱动)", + "requests": 300, + "failures": 0, + "triggered": 166, + "trigger_rate": 0.5533, + "p50": 1.696, + "p95": 3.125, + "p99": 3.866 + } + ] + } +} \ No newline at end of file diff --git a/results/python-1789961949.json b/results/python-1789961949.json new file mode 100644 index 0000000..1c9ecfb --- /dev/null +++ b/results/python-1789961949.json @@ -0,0 +1,72 @@ +{ + "worker": "python", + "timestamp": "2026-09-21T11:39:09", + "load": { + "users": 50, + "run_time": 60, + "host": "http://127.0.0.1:18099" + }, + "total": { + "num_requests": 302363, + "num_failures": 0, + "avg_response_time": 5.445, + "p50": 5, + "p95": 7, + "p99": 8, + "rps": 5047.173 + }, + "entries": [ + { + "name": "/api/v1/order/market/quantity/open", + "method": "POST", + "num_requests": 67210, + "num_failures": 0, + "avg_response_time": 5.446, + "min_response_time": 1.637083012610674, + "max_response_time": 147.2237499547191, + "p50": 5, + "p95": 7, + "p99": 8, + "rps": 1121.898 + }, + { + "name": "/api/v1/order/market/amount/open", + "method": "POST", + "num_requests": 67266, + "num_failures": 0, + "avg_response_time": 5.449, + "min_response_time": 1.7586250323802233, + "max_response_time": 114.38475002069026, + "p50": 5, + "p95": 7, + "p99": 8, + "rps": 1122.833 + }, + { + "name": "/api/v1/order/limit/open", + "method": "POST", + "num_requests": 134403, + "num_failures": 0, + "avg_response_time": 5.443, + "min_response_time": 1.49741698987782, + "max_response_time": 147.01154100475833, + "p50": 5, + "p95": 7, + "p99": 8, + "rps": 2243.513 + }, + { + "name": "/api/v1/order/batch/cancel", + "method": "DELETE", + "num_requests": 33484, + "num_failures": 0, + "avg_response_time": 5.442, + "min_response_time": 1.625208999030292, + "max_response_time": 114.47287502232939, + "p50": 5, + "p95": 7, + "p99": 8, + "rps": 558.929 + } + ] +} \ No newline at end of file diff --git a/results/python-1790009211.json b/results/python-1790009211.json new file mode 100644 index 0000000..5f1455c --- /dev/null +++ b/results/python-1790009211.json @@ -0,0 +1,72 @@ +{ + "worker": "python", + "timestamp": "2026-09-22T00:46:51", + "load": { + "users": 50, + "run_time": 60, + "host": "http://127.0.0.1:18099" + }, + "total": { + "num_requests": 296702, + "num_failures": 0, + "avg_response_time": 5.58, + "p50": 5, + "p95": 7, + "p99": 8, + "rps": 4956.687 + }, + "entries": [ + { + "name": "/api/v1/order/market/amount/open", + "method": "POST", + "num_requests": 65942, + "num_failures": 0, + "avg_response_time": 5.579, + "min_response_time": 1.4875420019961894, + "max_response_time": 214.37204198446125, + "p50": 5, + "p95": 7, + "p99": 8, + "rps": 1101.623 + }, + { + "name": "/api/v1/order/limit/open", + "method": "POST", + "num_requests": 132040, + "num_failures": 0, + "avg_response_time": 5.579, + "min_response_time": 1.0395830031484365, + "max_response_time": 215.44579102192074, + "p50": 5, + "p95": 7, + "p99": 9, + "rps": 2205.853 + }, + { + "name": "/api/v1/order/market/quantity/open", + "method": "POST", + "num_requests": 65812, + "num_failures": 0, + "avg_response_time": 5.575, + "min_response_time": 1.0592920007184148, + "max_response_time": 215.488791000098, + "p50": 5, + "p95": 7, + "p99": 8, + "rps": 1099.452 + }, + { + "name": "/api/v1/order/batch/cancel", + "method": "DELETE", + "num_requests": 32908, + "num_failures": 0, + "avg_response_time": 5.599, + "min_response_time": 1.211458002217114, + "max_response_time": 214.32587498566136, + "p50": 5, + "p95": 7, + "p99": 8, + "rps": 549.759 + } + ] +} \ No newline at end of file diff --git a/results/python-1790010434.json b/results/python-1790010434.json new file mode 100644 index 0000000..f42e960 --- /dev/null +++ b/results/python-1790010434.json @@ -0,0 +1,72 @@ +{ + "worker": "python", + "timestamp": "2026-09-22T01:07:14", + "load": { + "users": 50, + "run_time": 60, + "host": "http://127.0.0.1:18099" + }, + "total": { + "num_requests": 298452, + "num_failures": 0, + "avg_response_time": 5.567, + "p50": 5, + "p95": 7, + "p99": 8, + "rps": 4964.34 + }, + "entries": [ + { + "name": "/api/v1/order/limit/open", + "method": "POST", + "num_requests": 132791, + "num_failures": 0, + "avg_response_time": 5.568, + "min_response_time": 1.6007079975679517, + "max_response_time": 104.5600840006955, + "p50": 5, + "p95": 7, + "p99": 8, + "rps": 2208.796 + }, + { + "name": "/api/v1/order/market/quantity/open", + "method": "POST", + "num_requests": 66118, + "num_failures": 0, + "avg_response_time": 5.564, + "min_response_time": 0.5286250379867852, + "max_response_time": 39.89279200322926, + "p50": 5, + "p95": 7, + "p99": 8, + "rps": 1099.782 + }, + { + "name": "/api/v1/order/batch/cancel", + "method": "DELETE", + "num_requests": 33267, + "num_failures": 0, + "avg_response_time": 5.573, + "min_response_time": 2.1492079831659794, + "max_response_time": 104.59970799274743, + "p50": 5, + "p95": 7, + "p99": 8, + "rps": 553.351 + }, + { + "name": "/api/v1/order/market/amount/open", + "method": "POST", + "num_requests": 66276, + "num_failures": 0, + "avg_response_time": 5.565, + "min_response_time": 0.5042909760959446, + "max_response_time": 72.90029199793935, + "p50": 5, + "p95": 7, + "p99": 8, + "rps": 1102.41 + } + ] +} \ No newline at end of file diff --git a/results/python-1790054714.json b/results/python-1790054714.json new file mode 100644 index 0000000..f1f2b80 --- /dev/null +++ b/results/python-1790054714.json @@ -0,0 +1,72 @@ +{ + "worker": "python", + "timestamp": "2026-09-22T13:25:14", + "load": { + "users": 50, + "run_time": 60, + "host": "http://127.0.0.1:18099" + }, + "total": { + "num_requests": 302734, + "num_failures": 0, + "avg_response_time": 5.457, + "p50": 5, + "p95": 7, + "p99": 8, + "rps": 5036.0 + }, + "entries": [ + { + "name": "/api/v1/order/market/amount/open", + "method": "POST", + "num_requests": 67753, + "num_failures": 0, + "avg_response_time": 5.459, + "min_response_time": 0.34954200964421034, + "max_response_time": 100.51916696829721, + "p50": 5, + "p95": 7, + "p99": 8, + "rps": 1127.076 + }, + { + "name": "/api/v1/order/batch/cancel", + "method": "DELETE", + "num_requests": 33489, + "num_failures": 0, + "avg_response_time": 5.456, + "min_response_time": 0.5381250521168113, + "max_response_time": 69.15754196234047, + "p50": 5, + "p95": 7, + "p99": 8, + "rps": 557.092 + }, + { + "name": "/api/v1/order/limit/open", + "method": "POST", + "num_requests": 134531, + "num_failures": 0, + "avg_response_time": 5.456, + "min_response_time": 0.30212500132620335, + "max_response_time": 130.8213339652866, + "p50": 5, + "p95": 7, + "p99": 8, + "rps": 2237.932 + }, + { + "name": "/api/v1/order/market/quantity/open", + "method": "POST", + "num_requests": 66961, + "num_failures": 0, + "avg_response_time": 5.459, + "min_response_time": 0.3657920169644058, + "max_response_time": 100.56133300531656, + "p50": 5, + "p95": 7, + "p99": 8, + "rps": 1113.901 + } + ] +} \ No newline at end of file diff --git a/results/python-1790055119.json b/results/python-1790055119.json new file mode 100644 index 0000000..617ba25 --- /dev/null +++ b/results/python-1790055119.json @@ -0,0 +1,72 @@ +{ + "worker": "python", + "timestamp": "2026-09-22T13:31:59", + "load": { + "users": 50, + "run_time": 60, + "host": "http://127.0.0.1:18099" + }, + "total": { + "num_requests": 298351, + "num_failures": 0, + "avg_response_time": 5.557, + "p50": 5, + "p95": 7, + "p99": 9, + "rps": 4980.236 + }, + "entries": [ + { + "name": "/api/v1/order/limit/open", + "method": "POST", + "num_requests": 132585, + "num_failures": 0, + "avg_response_time": 5.557, + "min_response_time": 0.2804999821819365, + "max_response_time": 366.4294590125792, + "p50": 5, + "p95": 7, + "p99": 9, + "rps": 2213.18 + }, + { + "name": "/api/v1/order/market/amount/open", + "method": "POST", + "num_requests": 66841, + "num_failures": 0, + "avg_response_time": 5.544, + "min_response_time": 0.3406250034458935, + "max_response_time": 181.25120899640024, + "p50": 5, + "p95": 7, + "p99": 9, + "rps": 1115.746 + }, + { + "name": "/api/v1/order/market/quantity/open", + "method": "POST", + "num_requests": 65816, + "num_failures": 0, + "avg_response_time": 5.568, + "min_response_time": 0.37462502950802445, + "max_response_time": 366.4718749932945, + "p50": 5, + "p95": 7, + "p99": 9, + "rps": 1098.636 + }, + { + "name": "/api/v1/order/batch/cancel", + "method": "DELETE", + "num_requests": 33109, + "num_failures": 0, + "avg_response_time": 5.56, + "min_response_time": 0.30929199419915676, + "max_response_time": 150.7683329982683, + "p50": 5, + "p95": 7, + "p99": 9, + "rps": 552.673 + } + ] +} \ No newline at end of file diff --git a/results/scale-1-1790009085.json b/results/scale-1-1790009085.json new file mode 100644 index 0000000..6a06075 --- /dev/null +++ b/results/scale-1-1790009085.json @@ -0,0 +1,73 @@ +{ + "worker": "scale-1", + "timestamp": "2026-09-22T00:44:45", + "load": { + "users": 100, + "run_time": 30, + "host": "http://127.0.0.1:18100" + }, + "total": { + "num_requests": 14879, + "num_failures": 0, + "avg_response_time": 195.469, + "p50": 200, + "p95": 200, + "p99": 210, + "rps": 495.967 + }, + "entries": [ + { + "name": "/api/v1/order/market/quantity/open", + "method": "POST", + "num_requests": 3379, + "num_failures": 0, + "avg_response_time": 195.305, + "min_response_time": 3, + "max_response_time": 222, + "p50": 200, + "p95": 200, + "p99": 210, + "rps": 112.633 + }, + { + "name": "/api/v1/order/limit/open", + "method": "POST", + "num_requests": 6594, + "num_failures": 0, + "avg_response_time": 195.442, + "min_response_time": 3, + "max_response_time": 223, + "p50": 200, + "p95": 200, + "p99": 210, + "rps": 219.8 + }, + { + "name": "/api/v1/order/batch/cancel", + "method": "DELETE", + "num_requests": 1659, + "num_failures": 0, + "avg_response_time": 194.741, + "min_response_time": 6, + "max_response_time": 212, + "p50": 200, + "p95": 200, + "p99": 210, + "rps": 55.3 + }, + { + "name": "/api/v1/order/market/amount/open", + "method": "POST", + "num_requests": 3247, + "num_failures": 0, + "avg_response_time": 196.067, + "min_response_time": 7, + "max_response_time": 216, + "p50": 200, + "p95": 200, + "p99": 210, + "rps": 108.233 + } + ], + "label": "instances=1 max_qps=500/instance extra_latency=2ms users=100" +} \ No newline at end of file diff --git a/results/scale-1-1790010617.json b/results/scale-1-1790010617.json new file mode 100644 index 0000000..c569172 --- /dev/null +++ b/results/scale-1-1790010617.json @@ -0,0 +1,73 @@ +{ + "worker": "scale-1", + "timestamp": "2026-09-22T01:10:17", + "load": { + "users": 100, + "run_time": 30, + "host": "http://127.0.0.1:18100" + }, + "total": { + "num_requests": 14557, + "num_failures": 0, + "avg_response_time": 195.358, + "p50": 200, + "p95": 210, + "p99": 210, + "rps": 501.966 + }, + "entries": [ + { + "name": "/api/v1/order/limit/open", + "method": "POST", + "num_requests": 6545, + "num_failures": 0, + "avg_response_time": 195.228, + "min_response_time": 2, + "max_response_time": 217, + "p50": 200, + "p95": 210, + "p99": 210, + "rps": 225.69 + }, + { + "name": "/api/v1/order/market/amount/open", + "method": "POST", + "num_requests": 3253, + "num_failures": 0, + "avg_response_time": 195.087, + "min_response_time": 4, + "max_response_time": 213, + "p50": 200, + "p95": 210, + "p99": 210, + "rps": 112.172 + }, + { + "name": "/api/v1/order/market/quantity/open", + "method": "POST", + "num_requests": 3152, + "num_failures": 0, + "avg_response_time": 195.739, + "min_response_time": 3, + "max_response_time": 217, + "p50": 200, + "p95": 210, + "p99": 210, + "rps": 108.69 + }, + { + "name": "/api/v1/order/batch/cancel", + "method": "DELETE", + "num_requests": 1607, + "num_failures": 0, + "avg_response_time": 195.693, + "min_response_time": 5, + "max_response_time": 211, + "p50": 200, + "p95": 210, + "p99": 210, + "rps": 55.414 + } + ], + "label": "instances=1 max_qps=500/instance extra_latency=2ms users=100" +} \ No newline at end of file diff --git a/results/scale-1-1790054950.json b/results/scale-1-1790054950.json new file mode 100644 index 0000000..f090132 --- /dev/null +++ b/results/scale-1-1790054950.json @@ -0,0 +1,73 @@ +{ + "worker": "scale-1", + "timestamp": "2026-09-22T13:29:10", + "load": { + "users": 100, + "run_time": 30, + "host": "http://127.0.0.1:18100" + }, + "total": { + "num_requests": 14520, + "num_failures": 0, + "avg_response_time": 195.387, + "p50": 200, + "p95": 200, + "p99": 200, + "rps": 500.69 + }, + "entries": [ + { + "name": "/api/v1/order/market/quantity/open", + "method": "POST", + "num_requests": 3241, + "num_failures": 0, + "avg_response_time": 195.428, + "min_response_time": 3, + "max_response_time": 211, + "p50": 200, + "p95": 200, + "p99": 200, + "rps": 111.759 + }, + { + "name": "/api/v1/order/limit/open", + "method": "POST", + "num_requests": 6511, + "num_failures": 0, + "avg_response_time": 195.262, + "min_response_time": 4, + "max_response_time": 208, + "p50": 200, + "p95": 200, + "p99": 200, + "rps": 224.517 + }, + { + "name": "/api/v1/order/batch/cancel", + "method": "DELETE", + "num_requests": 1645, + "num_failures": 0, + "avg_response_time": 195.049, + "min_response_time": 2, + "max_response_time": 205, + "p50": 200, + "p95": 200, + "p99": 200, + "rps": 56.724 + }, + { + "name": "/api/v1/order/market/amount/open", + "method": "POST", + "num_requests": 3123, + "num_failures": 0, + "avg_response_time": 195.78, + "min_response_time": 3, + "max_response_time": 207, + "p50": 200, + "p95": 200, + "p99": 200, + "rps": 107.69 + } + ], + "label": "instances=1 max_qps=500/instance extra_latency=2ms users=100" +} \ No newline at end of file diff --git a/results/scale-1-1790055215.json b/results/scale-1-1790055215.json new file mode 100644 index 0000000..1cefac9 --- /dev/null +++ b/results/scale-1-1790055215.json @@ -0,0 +1,73 @@ +{ + "worker": "scale-1", + "timestamp": "2026-09-22T13:33:35", + "load": { + "users": 100, + "run_time": 30, + "host": "http://127.0.0.1:18100" + }, + "total": { + "num_requests": 14696, + "num_failures": 0, + "avg_response_time": 195.44, + "p50": 200, + "p95": 200, + "p99": 200, + "rps": 506.759 + }, + "entries": [ + { + "name": "/api/v1/order/market/amount/open", + "method": "POST", + "num_requests": 3296, + "num_failures": 0, + "avg_response_time": 195.985, + "min_response_time": 10, + "max_response_time": 205, + "p50": 200, + "p95": 200, + "p99": 200, + "rps": 113.655 + }, + { + "name": "/api/v1/order/market/quantity/open", + "method": "POST", + "num_requests": 3298, + "num_failures": 0, + "avg_response_time": 195.768, + "min_response_time": 2, + "max_response_time": 206, + "p50": 200, + "p95": 200, + "p99": 200, + "rps": 113.724 + }, + { + "name": "/api/v1/order/limit/open", + "method": "POST", + "num_requests": 6493, + "num_failures": 0, + "avg_response_time": 195.038, + "min_response_time": 3, + "max_response_time": 207, + "p50": 200, + "p95": 200, + "p99": 200, + "rps": 223.897 + }, + { + "name": "/api/v1/order/batch/cancel", + "method": "DELETE", + "num_requests": 1609, + "num_failures": 0, + "avg_response_time": 195.273, + "min_response_time": 5, + "max_response_time": 205, + "p50": 200, + "p95": 200, + "p99": 200, + "rps": 55.483 + } + ], + "label": "instances=1 max_qps=500/instance extra_latency=2ms users=100" +} \ No newline at end of file diff --git a/results/scale-4-1790009118.json b/results/scale-4-1790009118.json new file mode 100644 index 0000000..fb4fc93 --- /dev/null +++ b/results/scale-4-1790009118.json @@ -0,0 +1,73 @@ +{ + "worker": "scale-4", + "timestamp": "2026-09-22T00:45:18", + "load": { + "users": 100, + "run_time": 30, + "host": "http://127.0.0.1:18100" + }, + "total": { + "num_requests": 58737, + "num_failures": 0, + "avg_response_time": 48.666, + "p50": 49, + "p95": 53, + "p99": 55, + "rps": 1957.9 + }, + "entries": [ + { + "name": "/api/v1/order/market/amount/open", + "method": "POST", + "num_requests": 13042, + "num_failures": 0, + "avg_response_time": 48.646, + "min_response_time": 2, + "max_response_time": 86, + "p50": 49, + "p95": 53, + "p99": 55, + "rps": 434.733 + }, + { + "name": "/api/v1/order/limit/open", + "method": "POST", + "num_requests": 26123, + "num_failures": 0, + "avg_response_time": 48.653, + "min_response_time": 2, + "max_response_time": 86, + "p50": 49, + "p95": 53, + "p99": 55, + "rps": 870.767 + }, + { + "name": "/api/v1/order/market/quantity/open", + "method": "POST", + "num_requests": 13092, + "num_failures": 0, + "avg_response_time": 48.731, + "min_response_time": 3, + "max_response_time": 79, + "p50": 49, + "p95": 53, + "p99": 55, + "rps": 436.4 + }, + { + "name": "/api/v1/order/batch/cancel", + "method": "DELETE", + "num_requests": 6480, + "num_failures": 0, + "avg_response_time": 48.625, + "min_response_time": 3, + "max_response_time": 82, + "p50": 49, + "p95": 53, + "p99": 55, + "rps": 216.0 + } + ], + "label": "instances=4 max_qps=500/instance extra_latency=2ms users=100" +} \ No newline at end of file diff --git a/results/scale-4-1790010691.json b/results/scale-4-1790010691.json new file mode 100644 index 0000000..27e896c --- /dev/null +++ b/results/scale-4-1790010691.json @@ -0,0 +1,73 @@ +{ + "worker": "scale-4", + "timestamp": "2026-09-22T01:11:31", + "load": { + "users": 100, + "run_time": 30, + "host": "http://127.0.0.1:18100" + }, + "total": { + "num_requests": 58161, + "num_failures": 0, + "avg_response_time": 48.644, + "p50": 49, + "p95": 55, + "p99": 57, + "rps": 2005.552 + }, + "entries": [ + { + "name": "/api/v1/order/limit/open", + "method": "POST", + "num_requests": 25885, + "num_failures": 0, + "avg_response_time": 48.651, + "min_response_time": 2, + "max_response_time": 64, + "p50": 49, + "p95": 55, + "p99": 57, + "rps": 892.586 + }, + { + "name": "/api/v1/order/market/quantity/open", + "method": "POST", + "num_requests": 12900, + "num_failures": 0, + "avg_response_time": 48.607, + "min_response_time": 2, + "max_response_time": 61, + "p50": 49, + "p95": 55, + "p99": 57, + "rps": 444.828 + }, + { + "name": "/api/v1/order/market/amount/open", + "method": "POST", + "num_requests": 12816, + "num_failures": 0, + "avg_response_time": 48.678, + "min_response_time": 2, + "max_response_time": 61, + "p50": 49, + "p95": 55, + "p99": 57, + "rps": 441.931 + }, + { + "name": "/api/v1/order/batch/cancel", + "method": "DELETE", + "num_requests": 6560, + "num_failures": 0, + "avg_response_time": 48.623, + "min_response_time": 2, + "max_response_time": 60, + "p50": 49, + "p95": 55, + "p99": 57, + "rps": 226.207 + } + ], + "label": "instances=4 max_qps=500/instance extra_latency=2ms users=100" +} \ No newline at end of file diff --git a/results/scale-4-1790055053.json b/results/scale-4-1790055053.json new file mode 100644 index 0000000..6d6b6fb --- /dev/null +++ b/results/scale-4-1790055053.json @@ -0,0 +1,73 @@ +{ + "worker": "scale-4", + "timestamp": "2026-09-22T13:30:53", + "load": { + "users": 100, + "run_time": 30, + "host": "http://127.0.0.1:18100" + }, + "total": { + "num_requests": 58257, + "num_failures": 0, + "avg_response_time": 48.649, + "p50": 49, + "p95": 52, + "p99": 54, + "rps": 2008.862 + }, + "entries": [ + { + "name": "/api/v1/order/batch/cancel", + "method": "DELETE", + "num_requests": 6392, + "num_failures": 0, + "avg_response_time": 48.586, + "min_response_time": 2, + "max_response_time": 55, + "p50": 49, + "p95": 53, + "p99": 54, + "rps": 220.414 + }, + { + "name": "/api/v1/order/limit/open", + "method": "POST", + "num_requests": 25905, + "num_failures": 0, + "avg_response_time": 48.608, + "min_response_time": 2, + "max_response_time": 58, + "p50": 49, + "p95": 52, + "p99": 54, + "rps": 893.276 + }, + { + "name": "/api/v1/order/market/quantity/open", + "method": "POST", + "num_requests": 13002, + "num_failures": 0, + "avg_response_time": 48.767, + "min_response_time": 2, + "max_response_time": 56, + "p50": 49, + "p95": 53, + "p99": 54, + "rps": 448.345 + }, + { + "name": "/api/v1/order/market/amount/open", + "method": "POST", + "num_requests": 12958, + "num_failures": 0, + "avg_response_time": 48.644, + "min_response_time": 2, + "max_response_time": 56, + "p50": 49, + "p95": 52, + "p99": 53, + "rps": 446.828 + } + ], + "label": "instances=4 max_qps=500/instance extra_latency=2ms users=100" +} \ No newline at end of file diff --git a/results/scale-4-1790055249.json b/results/scale-4-1790055249.json new file mode 100644 index 0000000..5ce29d1 --- /dev/null +++ b/results/scale-4-1790055249.json @@ -0,0 +1,73 @@ +{ + "worker": "scale-4", + "timestamp": "2026-09-22T13:34:09", + "load": { + "users": 100, + "run_time": 30, + "host": "http://127.0.0.1:18100" + }, + "total": { + "num_requests": 58752, + "num_failures": 0, + "avg_response_time": 48.646, + "p50": 49, + "p95": 52, + "p99": 53, + "rps": 2025.931 + }, + "entries": [ + { + "name": "/api/v1/order/market/amount/open", + "method": "POST", + "num_requests": 13019, + "num_failures": 0, + "avg_response_time": 48.698, + "min_response_time": 2, + "max_response_time": 55, + "p50": 49, + "p95": 52, + "p99": 53, + "rps": 448.931 + }, + { + "name": "/api/v1/order/limit/open", + "method": "POST", + "num_requests": 26121, + "num_failures": 0, + "avg_response_time": 48.621, + "min_response_time": 2, + "max_response_time": 55, + "p50": 49, + "p95": 52, + "p99": 53, + "rps": 900.724 + }, + { + "name": "/api/v1/order/batch/cancel", + "method": "DELETE", + "num_requests": 6415, + "num_failures": 0, + "avg_response_time": 48.599, + "min_response_time": 2, + "max_response_time": 55, + "p50": 49, + "p95": 53, + "p99": 53, + "rps": 221.207 + }, + { + "name": "/api/v1/order/market/quantity/open", + "method": "POST", + "num_requests": 13197, + "num_failures": 0, + "avg_response_time": 48.667, + "min_response_time": 2, + "max_response_time": 55, + "p50": 49, + "p95": 52, + "p99": 53, + "rps": 455.069 + } + ], + "label": "instances=4 max_qps=500/instance extra_latency=2ms users=100" +} \ No newline at end of file diff --git a/results/stale_trigger-1790009032.json b/results/stale_trigger-1790009032.json new file mode 100644 index 0000000..79d432f --- /dev/null +++ b/results/stale_trigger-1790009032.json @@ -0,0 +1,58 @@ +{ + "worker": "stale_trigger", + "timestamp": "2026-09-22T00:43:52", + "load": { + "users": 10, + "run_time": "2 phases x 300 req", + "host": "http://127.0.0.1:18099" + }, + "total": { + "num_requests": 600, + "num_failures": 0, + "avg_response_time": 1.678, + "p50": 1.285, + "p95": 2.533, + "p99": 4.767, + "rps": 4597.287 + }, + "entries": [ + { + "name": "/api/v1/order/condition/open", + "method": "POST", + "num_requests": 600, + "num_failures": 0, + "avg_response_time": 1.678, + "p50": 1.285, + "p95": 2.533, + "p99": 4.767, + "rps": 4597.287 + } + ], + "trigger": { + "mode": "stale", + "phases": [ + { + "name": "hardcoded_low", + "detail": "触发价写死 30500(低于行情区间)", + "requests": 300, + "failures": 0, + "triggered": 300, + "trigger_rate": 1.0, + "p50": 1.202, + "p95": 2.571, + "p99": 30.233 + }, + { + "name": "hardcoded_high", + "detail": "触发价写死 31500(高于行情区间)", + "requests": 300, + "failures": 0, + "triggered": 0, + "trigger_rate": 0.0, + "p50": 1.355, + "p95": 2.508, + "p99": 3.206 + } + ] + } +} \ No newline at end of file diff --git a/results/stale_trigger-1790010330.json b/results/stale_trigger-1790010330.json new file mode 100644 index 0000000..ab2bbaf --- /dev/null +++ b/results/stale_trigger-1790010330.json @@ -0,0 +1,58 @@ +{ + "worker": "stale_trigger", + "timestamp": "2026-09-22T01:05:30", + "load": { + "users": 10, + "run_time": "2 phases x 300 req", + "host": "http://127.0.0.1:18099" + }, + "total": { + "num_requests": 600, + "num_failures": 0, + "avg_response_time": 1.561, + "p50": 1.347, + "p95": 2.401, + "p99": 3.261, + "rps": 5288.231 + }, + "entries": [ + { + "name": "/api/v1/order/condition/open", + "method": "POST", + "num_requests": 600, + "num_failures": 0, + "avg_response_time": 1.561, + "p50": 1.347, + "p95": 2.401, + "p99": 3.261, + "rps": 5288.231 + } + ], + "trigger": { + "mode": "stale", + "phases": [ + { + "name": "hardcoded_low", + "detail": "触发价写死 30500(低于行情区间)", + "requests": 300, + "failures": 0, + "triggered": 300, + "trigger_rate": 1.0, + "p50": 1.263, + "p95": 2.528, + "p99": 8.345 + }, + { + "name": "hardcoded_high", + "detail": "触发价写死 31500(高于行情区间)", + "requests": 300, + "failures": 0, + "triggered": 0, + "trigger_rate": 0.0, + "p50": 1.417, + "p95": 2.316, + "p99": 2.495 + } + ] + } +} \ No newline at end of file diff --git a/results/stale_trigger-1790054558.json b/results/stale_trigger-1790054558.json new file mode 100644 index 0000000..ee9b7c9 --- /dev/null +++ b/results/stale_trigger-1790054558.json @@ -0,0 +1,58 @@ +{ + "worker": "stale_trigger", + "timestamp": "2026-09-22T13:22:38", + "load": { + "users": 10, + "run_time": "2 phases x 300 req", + "host": "http://127.0.0.1:18099" + }, + "total": { + "num_requests": 600, + "num_failures": 0, + "avg_response_time": 1.772, + "p50": 1.637, + "p95": 2.968, + "p99": 4.371, + "rps": 5471.066 + }, + "entries": [ + { + "name": "/api/v1/order/condition/open", + "method": "POST", + "num_requests": 600, + "num_failures": 0, + "avg_response_time": 1.772, + "p50": 1.637, + "p95": 2.968, + "p99": 4.371, + "rps": 5471.066 + } + ], + "trigger": { + "mode": "stale", + "phases": [ + { + "name": "hardcoded_low", + "detail": "触发价写死 30500(低于行情区间)", + "requests": 300, + "failures": 0, + "triggered": 300, + "trigger_rate": 1.0, + "p50": 1.78, + "p95": 3.561, + "p99": 4.737 + }, + { + "name": "hardcoded_high", + "detail": "触发价写死 31500(高于行情区间)", + "requests": 300, + "failures": 0, + "triggered": 0, + "trigger_rate": 0.0, + "p50": 1.525, + "p95": 2.297, + "p99": 2.733 + } + ] + } +} \ No newline at end of file diff --git a/run.sh b/run.sh new file mode 100644 index 0000000..0537ea0 --- /dev/null +++ b/run.sh @@ -0,0 +1,148 @@ +#!/usr/bin/env bash +# perf-harness-demo 一键压测编排: +# bash run.sh target 启动本机被测 mock(HTTP 18099) +# bash run.sh python --users 50 --duration 60s +# bash run.sh go --users 50 --duration 60s +# bash run.sh scale-N 横向扩展实验:N 个 mock 实例 + 入口分流(固定参数) +# bash run.sh report 生成 report.md +set -euo pipefail +cd "$(dirname "$0")" + +HTTP_PORT=18099 +MASTER_PORT=5557 +TARGET_HOST="http://127.0.0.1:${HTTP_PORT}" +PID_DIR=".pids" + +# 横向扩展实验的固定参数(scale-1 与 scale-4 除实例数外必须完全一致) +SCALE_PORT=18100 # 分流器端口;后端实例占用 18101..18100+N +SCALE_USERS=100 +SCALE_DURATION=30s +SCALE_MAX_QPS=500 # 每个后端实例的能力上限(两组实验相同) +SCALE_EXTRA_LATENCY_MS=2 # 每笔请求附加处理耗时(两组实验相同) + +usage() { grep '^#' "$0" | head -8; exit 1; } + +ensure_http_target() { + if curl -sf "http://127.0.0.1:${HTTP_PORT}/health" >/dev/null 2>&1; then + return + fi + mkdir -p "$PID_DIR" + nohup python3 target/http_server.py >"$PID_DIR/http.log" 2>&1 & + echo $! >"$PID_DIR/http.pid" + for i in $(seq 1 30); do + curl -sf "http://127.0.0.1:${HTTP_PORT}/health" >/dev/null 2>&1 && return + sleep 0.3 + done + echo "http target failed to start" >&2; exit 1 +} + +parse_args() { + USERS=50; DURATION="60s" + while [ $# -gt 0 ]; do + case "$1" in + --users) USERS="$2"; shift 2;; + --duration) DURATION="$2"; shift 2;; + *) echo "unknown arg: $1" >&2; usage;; + esac + done +} + +scale_teardown() { + local f + for f in "$PID_DIR"/scale-*.pid; do + [ -f "$f" ] || continue + kill "$(cat "$f")" 2>/dev/null || true + rm -f "$f" + done +} + +scale_run() { + local n="$1" i port backends="" + mkdir -p "$PID_DIR" results + scale_teardown + trap scale_teardown EXIT # 失败/中断也不留残留进程 + for i in $(seq 1 "$n"); do + port=$((SCALE_PORT + i)) + TARGET_PORT=$port TARGET_MAX_QPS=$SCALE_MAX_QPS \ + TARGET_EXTRA_LATENCY_MS=$SCALE_EXTRA_LATENCY_MS \ + nohup python3 target/http_server.py >"$PID_DIR/scale-backend-$port.log" 2>&1 & + echo $! >"$PID_DIR/scale-backend-$port.pid" + backends="${backends:+$backends,}$port" + done + nohup python3 target/dispatcher.py --port "$SCALE_PORT" --backends "$backends" \ + >"$PID_DIR/scale-dispatcher.log" 2>&1 & + echo $! >"$PID_DIR/scale-dispatcher.pid" + for i in $(seq 1 50); do + curl -sf "http://127.0.0.1:${SCALE_PORT}/health" >/dev/null 2>&1 && break + sleep 0.2 + done + if ! curl -sf "http://127.0.0.1:${SCALE_PORT}/health" >/dev/null 2>&1; then + echo "scale dispatcher failed to start" >&2; exit 1 + fi + echo "[scale-$n] backends=$backends max_qps=${SCALE_MAX_QPS}/instance " \ + "users=$SCALE_USERS duration=$SCALE_DURATION" + (cd go && go build -o ../bin/go-worker .) + PERF_WORKER="scale-$n" \ + PERF_LABEL="instances=$n max_qps=${SCALE_MAX_QPS}/instance extra_latency=${SCALE_EXTRA_LATENCY_MS}ms users=$SCALE_USERS" \ + locust -f python/master_locustfile.py --master \ + --master-bind-port "$MASTER_PORT" --expect-workers 1 \ + --headless -u "$SCALE_USERS" -r "$SCALE_USERS" -t "$SCALE_DURATION" \ + --host "http://127.0.0.1:${SCALE_PORT}" --only-summary & + MASTER_PID=$! + for i in $(seq 1 30); do + nc -z 127.0.0.1 "$MASTER_PORT" 2>/dev/null && break + sleep 0.3 + done + ./bin/go-worker -target "http://127.0.0.1:${SCALE_PORT}" \ + >"$PID_DIR/go-worker-scale.log" 2>&1 & + WORKER_PID=$! + wait "$MASTER_PID" + kill "$WORKER_PID" 2>/dev/null || true + scale_teardown + trap - EXIT + echo "[scale-$n] done → results/scale-$n-*.json" +} + +cmd="${1:-}"; shift || true +case "$cmd" in + target) + ensure_http_target + echo "targets up: http=:${HTTP_PORT}" + ;; + python) + parse_args "$@" + ensure_http_target + PERF_WORKER=python locust -f python/locustfile.py \ + --headless -u "$USERS" -r "$USERS" -t "$DURATION" \ + --host "$TARGET_HOST" --only-summary + ;; + go) + parse_args "$@" + ensure_http_target + (cd go && go build -o ../bin/go-worker .) + PERF_WORKER=go locust -f python/master_locustfile.py --master \ + --master-bind-port "$MASTER_PORT" --expect-workers 1 \ + --headless -u "$USERS" -r "$USERS" -t "$DURATION" \ + --host "$TARGET_HOST" --only-summary & + MASTER_PID=$! + mkdir -p "$PID_DIR" + for i in $(seq 1 30); do + nc -z 127.0.0.1 "$MASTER_PORT" 2>/dev/null && break + sleep 0.3 + done + ./bin/go-worker -target "$TARGET_HOST" >"$PID_DIR/go-worker.log" 2>&1 & + WORKER_PID=$! + wait "$MASTER_PID" + kill "$WORKER_PID" 2>/dev/null || true + ;; + report) + python3 compare.py results/*.json > report.md + echo "report.md generated" + ;; + scale-*) + n="${cmd#scale-}" + [[ "$n" =~ ^[0-9]+$ ]] && [ "$n" -ge 1 ] || usage + scale_run "$n" + ;; + *) usage;; +esac diff --git a/scenarios/verify_trigger.py b/scenarios/verify_trigger.py new file mode 100644 index 0000000..270fbc8 --- /dev/null +++ b/scenarios/verify_trigger.py @@ -0,0 +1,319 @@ +"""失真对比实验:条件单触发价「写死」vs「标记价缓存服务实时驱动」。 + +一次运行跑完两组对照。两组打**同一个** endpoint、同样的负载参数(10 线程 × 300 请求), +唯一变量是触发价的来源 —— 这一点在代码里就只差传给 `make_request` 的那个取价函数: + + stale 组:触发价写死常量。两个相位分别低于 / 高于行情区间 → 触发率塌缩到 100% / 0%。 + live 组:触发价 = 缓存服务(:18097)返回的实时标记价 ± 20 窄带。 + +★ 为什么这是全篇最值钱的一条:两组相位的 HTTP 状态码全是 200、业务 code 全是 0、 + 失败数全是 0 —— 单看压测报表(TPS / 错误率 / 延迟)挑不出任何毛病, + 但 stale 组的触发率是 0% / 100%,这批数据对条件单链路的容量评估毫无意义。 + 「数据是错的,但看起来是对的」。 + +落盘:两组各写一份 results/{stale_trigger,live_trigger}-.json; +compare.py 的 §5 按 trigger.mode 分组,直接读它们出对照表。 + +用法:python3 scenarios/verify_trigger.py +""" + +import itertools +import json +import math +import os +import random +import subprocess +import sys +import threading +import time +import urllib.request + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +RESULTS_DIR = os.path.join(ROOT, "results") +TARGET_BASE = "http://127.0.0.1:18099" +MARK_SERVICE_BASE = "http://127.0.0.1:18097" + +CONTRACT_ID = 1 +SIDE = "bid" +WORKERS = 10 +REQUESTS_PER_PHASE = 300 +BAND = 20.0 # live 组:触发价相对实时标记价的偏移带宽(约 0.06%) + +# stale 组的两个相位:写死的触发价,分别落在行情区间下方 / 上方 +STALE_PHASES = [ + ("hardcoded_low", 30500.0, "触发价写死 30500(低于行情区间)"), + ("hardcoded_high", 31500.0, "触发价写死 31500(高于行情区间)"), +] + +# ---------------------------------------------------------------- 基础设施 + +def http_json(method, url, payload=None, timeout=5.0): + data = json.dumps(payload).encode() if payload is not None else None + req = urllib.request.Request(url, data=data, method=method, + headers={"Content-Type": "application/json"}) + with urllib.request.urlopen(req, timeout=timeout) as r: + return json.loads(r.read().decode()) + + +def is_healthy(base): + try: + http_json("GET", base + "/health", timeout=1.0) + return True + except Exception: + return False + + +def ensure_process(base, script, tag): + """依赖进程自检:已在跑就复用;没在跑就在本机拉起(日志进 .pids/)。""" + if is_healthy(base): + return None + os.makedirs(os.path.join(ROOT, ".pids"), exist_ok=True) + log = open(os.path.join(ROOT, ".pids", f"{tag}.log"), "ab") + proc = subprocess.Popen([sys.executable, os.path.join(ROOT, script)], + cwd=ROOT, stdout=log, stderr=subprocess.STDOUT) + for _ in range(50): + if is_healthy(base): + return proc + if proc.poll() is not None: + raise SystemExit(f"{script} 启动即退出,见 .pids/{tag}.log") + time.sleep(0.2) + proc.kill() + raise SystemExit(f"{script} 10s 内未就绪,见 .pids/{tag}.log") + + +class Stats: + """单相位统计:请求数 / 失败数 / 触发数 / 延迟样本(毫秒)。""" + + def __init__(self): + self._lock = threading.Lock() + self.requests = 0 + self.failures = 0 + self.triggered = 0 + self.latencies = [] + + def record(self, latency_ms, ok, triggered=False): + with self._lock: + self.requests += 1 + if not ok: + self.failures += 1 + if triggered: + self.triggered += 1 + self.latencies.append(latency_ms) + + def summary(self): + with self._lock: + lat = sorted(self.latencies) + return { + "requests": self.requests, + "failures": self.failures, + "triggered": self.triggered, + "trigger_rate": (round(self.triggered / self.requests, 4) + if self.requests else 0.0), + "p50": _pct(lat, 0.50), + "p95": _pct(lat, 0.95), + "p99": _pct(lat, 0.99), + } + + +def _pct(sorted_vals, p): + if not sorted_vals: + return 0.0 + k = (len(sorted_vals) - 1) * p + f = math.floor(k) + c = math.ceil(k) + if f == c: + return round(sorted_vals[int(k)], 3) + return round(sorted_vals[f] + (sorted_vals[c] - sorted_vals[f]) * (k - f), 3) + + +def run_phase(workers, total_requests, make_request): + """workers 个线程抢索引,共执行 total_requests 次 make_request(i)。 + + make_request(i) 返回 (latency_ms, ok, triggered);抛异常按失败计。 + 返回 (Stats, elapsed_seconds)。 + """ + stats = Stats() + counter = itertools.count() + started = time.perf_counter() + + def work(): + while True: + i = next(counter) + if i >= total_requests: + return + try: + lat, ok, trig = make_request(i) + except Exception: + lat, ok, trig = 0.0, False, False + stats.record(lat, ok, trig) + + threads = [threading.Thread(target=work) for _ in range(workers)] + for t in threads: + t.start() + for t in threads: + t.join() + return stats, time.perf_counter() - started + + +def write_result(worker, host, users, run_time_desc, phases, mode): + """落一份与 compare.py 兼容的 JSON(多一个 trigger 字段承载实验数据)。 + + phases: [{"name", "detail", "stats": Stats, "elapsed": float}] + """ + total_req = sum(p["stats"].requests for p in phases) + total_fail = sum(p["stats"].failures for p in phases) + all_lat = sorted(lat for p in phases for lat in p["stats"].latencies) + elapsed = sum(p["elapsed"] for p in phases) + avg = round(sum(all_lat) / len(all_lat), 3) if all_lat else 0.0 + rps = round(total_req / elapsed, 3) if elapsed > 0 else 0.0 + result = { + "worker": worker, + "timestamp": time.strftime("%Y-%m-%dT%H:%M:%S"), + "load": {"users": users, "run_time": run_time_desc, "host": host}, + "total": { + "num_requests": total_req, + "num_failures": total_fail, + "avg_response_time": avg, + "p50": _pct(all_lat, 0.50), + "p95": _pct(all_lat, 0.95), + "p99": _pct(all_lat, 0.99), + "rps": rps, + }, + "entries": [{ + "name": "/api/v1/order/condition/open", + "method": "POST", + "num_requests": total_req, + "num_failures": total_fail, + "avg_response_time": avg, + "p50": _pct(all_lat, 0.50), + "p95": _pct(all_lat, 0.95), + "p99": _pct(all_lat, 0.99), + "rps": rps, + }], + "trigger": { + "mode": mode, + "phases": [{"name": p["name"], "detail": p["detail"], + **p["stats"].summary()} for p in phases], + }, + } + os.makedirs(RESULTS_DIR, exist_ok=True) + path = os.path.join(RESULTS_DIR, f"{worker}-{int(time.time())}.json") + with open(path, "w", encoding="utf-8") as f: + json.dump(result, f, ensure_ascii=False, indent=2) + return path + + +# ---------------------------------------------------------------- 实验本体 + +def make_request(price_source): + """构造一次条件单请求。**两组唯一差异就是这个 price_source 参数。**""" + + def call(_i): + trigger_price = price_source() + t0 = time.perf_counter() + resp = http_json( + "POST", TARGET_BASE + "/api/v1/order/condition/open", + payload={ + "user_id": 1 + (_i % 1000), + "contract_id": CONTRACT_ID, + "side": SIDE, + "trigger_price": trigger_price, + "quantity": "1", + }) + lat = (time.perf_counter() - t0) * 1000 + data = resp.get("data") or {} + return lat, resp.get("code") == 0, bool(data.get("triggered")) + + return call + + +def smoke_check(): + """冒烟:条件单 endpoint 必须存在(否则 18099 上跑的是旧版 mock)。""" + probe = http_json( + "POST", TARGET_BASE + "/api/v1/order/condition/open", + payload={"user_id": 0, "contract_id": CONTRACT_ID, "side": SIDE, + "trigger_price": 31000.0}) + if probe.get("code") != 0 or "triggered" not in (probe.get("data") or {}): + raise SystemExit("18099 上的 mock 不含条件单 endpoint,请重启 target") + + +def fetch_live_price(): + """从缓存服务取实时标记价(断流时服务自动回退默认价,不中断)。""" + quote = http_json("GET", MARK_SERVICE_BASE + + f"/mark/price?contract_id={CONTRACT_ID}") + return float(quote["price"]) + + +def wait_live_price(timeout=5.0): + """等缓存服务从行情源拿到第一笔实时价(stale=False 即缓存已激活)。""" + deadline = time.time() + timeout + while time.time() < deadline: + try: + q = http_json("GET", MARK_SERVICE_BASE + + f"/mark/price?contract_id={CONTRACT_ID}", timeout=1.0) + if not q.get("stale", True): + return q["price"] + except Exception: + pass + time.sleep(0.2) + raise SystemExit("缓存服务未在限时内取到实时价(行情源 18099 是否在跑?)") + + +def run_stale(): + """对照组:触发价写死 —— 两个相位分别全触发 / 全不触发。""" + phases = [] + for name, price, detail in STALE_PHASES: + stats, elapsed = run_phase( + WORKERS, REQUESTS_PER_PHASE, make_request(lambda p=price: p)) + phases.append({"name": name, "detail": detail, + "stats": stats, "elapsed": elapsed}) + s = stats.summary() + print(f"[{name}] requests={s['requests']} failures={s['failures']} " + f"triggered={s['triggered']} trigger_rate={s['trigger_rate']:.2%} " + f"p95={s['p95']}ms") + path = write_result("stale_trigger", TARGET_BASE, WORKERS, + f"{len(STALE_PHASES)} phases x {REQUESTS_PER_PHASE} req", + phases, mode="stale") + total_fail = sum(p["stats"].failures for p in phases) + print(f"\n结果已写入 {os.path.relpath(path, ROOT)}") + print(f"★ 失败数={total_fail}(报表一切正常),但两个相位触发率塌缩到 " + f"0%/100% —— 这就是「数据是错的,但看起来是对的」。") + + +def run_live(): + """实验组:触发价由缓存服务的实时标记价驱动 —— 触发率落在中间区间。""" + price0 = wait_live_price() + print(f"[live] 缓存服务已激活,实时标记价 ≈ {price0}") + + def price_source(): + return round(fetch_live_price() + random.uniform(-BAND, BAND), 2) + + stats, elapsed = run_phase(WORKERS, REQUESTS_PER_PHASE, + make_request(price_source)) + s = stats.summary() + print(f"[cache_driven] requests={s['requests']} failures={s['failures']} " + f"triggered={s['triggered']} trigger_rate={s['trigger_rate']:.2%} " + f"p95={s['p95']}ms") + + phases = [{"name": "cache_driven", + "detail": f"触发价=实时标记价±{BAND:.0f}(缓存服务驱动)", + "stats": stats, "elapsed": elapsed}] + path = write_result("live_trigger", TARGET_BASE, WORKERS, + f"{REQUESTS_PER_PHASE} req", phases, mode="live") + print(f"\n结果已写入 {os.path.relpath(path, ROOT)}") + print(f"★ 触发率 {s['trigger_rate']:.2%} 落在中间区间 —— 跟随行情的" + f"触发价让数据有业务意义。") + + +def main(): + ensure_process(TARGET_BASE, os.path.join("target", "http_server.py"), "http") + smoke_check() + ensure_process(MARK_SERVICE_BASE, + os.path.join("target", "mark_price_service.py"), "mark-service") + run_stale() + print() + run_live() + + +if __name__ == "__main__": + main() diff --git a/target/dispatcher.py b/target/dispatcher.py new file mode 100644 index 0000000..58d0e0e --- /dev/null +++ b/target/dispatcher.py @@ -0,0 +1,141 @@ +"""极简入口分流器(perf-harness-demo 横向扩展实验用)。 + +扮演真实架构里入口 Nginx 的角色:把请求**轮询**转发给后端 N 个 mock 实例。 +横向扩展实验里,后端实例数是唯一变量 —— 分流策略与负载参数保持不变。 + +用法: + python3 target/dispatcher.py --port 18100 --backends 18101,18102,18103,18104 + +零第三方依赖;每线程到每个后端保持一条 keep-alive 连接(http.client)。 +只监听 127.0.0.1,只做本机压测,绝不对外。 +""" + +import argparse +import http.client +import itertools +import json +import sys +import threading +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + + +class BackendPool: + """轮询选后端 + 每线程 keep-alive 连接复用(断连自动重建重试一次)。""" + + def __init__(self, ports, host="127.0.0.1", timeout=30.0): + self.backends = [(host, p) for p in ports] + self.timeout = timeout + self._rr = itertools.count() + self._local = threading.local() + + def pick(self): + # itertools.count.__next__ 在 GIL 下原子,多线程轮询无需加锁 + return self.backends[next(self._rr) % len(self.backends)] + + def _conn(self, backend): + conns = getattr(self._local, "conns", None) + if conns is None: + conns = self._local.conns = {} + conn = conns.get(backend) + if conn is None: + conn = http.client.HTTPConnection(backend[0], backend[1], + timeout=self.timeout) + conns[backend] = conn + return conn + + def _drop(self, backend): + conns = getattr(self._local, "conns", None) + if conns and backend in conns: + try: + conns.pop(backend).close() + except OSError: + pass + + def forward(self, method, path, body, headers): + backend = self.pick() + for attempt in range(2): + conn = self._conn(backend) + try: + conn.request(method, path, body=body, headers=headers) + resp = conn.getresponse() + data = resp.read() + return resp.status, data + except (http.client.HTTPException, OSError): + # keep-alive 连接可能已被后端关闭:丢弃重建,重试一次 + self._drop(backend) + if attempt == 1: + raise + raise RuntimeError("unreachable") + + +def make_handler(pool): + class Handler(BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" + + def log_message(self, *args): # 静默 + pass + + def handle_error(self, request, client_address): + # 对端先断连(压测收尾)是常态,不刷 traceback(会带本机绝对路径) + err = sys.exc_info()[1] + if isinstance(err, (BrokenPipeError, ConnectionResetError)): + return + super().handle_error(request, client_address) + + def _write(self, status, data): + self.send_response(status) + self.send_header("Content-Type", "application/json; charset=utf-8") + self.send_header("Content-Length", str(len(data))) + self.end_headers() + self.wfile.write(data) + + def _proxy(self): + length = int(self.headers.get("Content-Length") or 0) + body = self.rfile.read(length) if length else None + headers = {"Content-Type": self.headers.get( + "Content-Type", "application/json")} + try: + status, data = pool.forward(self.command, self.path, + body, headers) + except (http.client.HTTPException, OSError) as e: + payload = json.dumps( + {"code": 502, "msg": f"backend error: {e}", + "data": None}).encode() + self._write(502, payload) + return + self._write(status, data) + + def do_GET(self): + if self.path.startswith("/health"): + # 就绪探针本地应答,不转发(探的是分流器自己) + self._write(200, json.dumps( + {"code": 0, "msg": "ok", + "data": {"status": "up", + "backends": len(pool.backends)}}).encode()) + else: + self._proxy() + + do_POST = _proxy + do_DELETE = _proxy + + return Handler + + +def main(): + ap = argparse.ArgumentParser(description="本机轮询分流器(横向扩展实验用)") + ap.add_argument("--port", type=int, default=18100) + ap.add_argument("--backends", required=True, + help="逗号分隔的后端端口,如 18101,18102") + args = ap.parse_args() + ports = [int(p) for p in args.backends.split(",") if p.strip()] + if not ports: + ap.error("--backends 至少一个端口") + pool = BackendPool(ports) + srv = ThreadingHTTPServer(("127.0.0.1", args.port), make_handler(pool)) + print(f"[dispatcher] listening on http://127.0.0.1:{args.port} " + f"backends={ports}") + srv.serve_forever() + + +if __name__ == "__main__": + main() diff --git a/target/http_server.py b/target/http_server.py new file mode 100644 index 0000000..b9e7f27 --- /dev/null +++ b/target/http_server.py @@ -0,0 +1,203 @@ +"""本地被测 mock 网关(perf-harness-demo 专用,中性路径)。 + +实现 5 个交易类 endpoint + 1 个标记价查询: + POST /api/v1/order/limit/open 限价开仓 + POST /api/v1/order/market/quantity/open 市价按量开仓 + POST /api/v1/order/market/amount/open 市价按金额开仓 + POST /api/v1/order/condition/open 条件单开仓(按当前标记价判定是否触发) + DELETE /api/v1/order/batch/cancel 批量撤单 + GET /api/v1/mark/price?contract_id=1 标记价(随时间波动,供条件单/缓存链路用) + +环境变量(全部可选;缺省时行为与单实例基线完全一致): + TARGET_PORT 监听端口(默认 18099;横向扩展实验用它起多实例) + TARGET_MAX_QPS 单实例处理能力上限(请求/秒)。超限请求**排队等位**, + 表现为延迟上升、实测 TPS 触顶 —— 即「可测量的单实例上限」 + TARGET_EXTRA_LATENCY_MS 每笔请求附加的固定处理耗时(模拟下游处理耗时) + +零第三方依赖,ThreadingHTTPServer 实现。只做本机压测,绝不对外。 +""" + +import json +import math +import os +import random +import sys +import threading +import time +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +_HOST = "127.0.0.1" +_PORT = int(os.environ.get("TARGET_PORT", "18099")) +_MAX_QPS = float(os.environ.get("TARGET_MAX_QPS", "0")) # 0 = 不限 +_EXTRA_LATENCY = float(os.environ.get("TARGET_EXTRA_LATENCY_MS", "0")) / 1000.0 + +_lock = threading.Lock() +_orders = {} # order_id -> order +_next_order_id = [1] +_start_ts = time.time() + + +def evaluate_trigger(side, trigger_price, mark_price): + """条件单触发判定(纯函数,便于单测)。 + + 演示简化:在请求时刻按当前标记价评估(真实系统是未来价格触碰时触发)。 + side=bid:标记价上穿/触及触发价 → mark >= trigger + side=ask:标记价下穿/触及触发价 → mark <= trigger + """ + if side == "bid": + return mark_price >= trigger_price + return mark_price <= trigger_price + + +class _Pacer: + """等距放行器:把请求放行时刻排到间隔 1/qps 的槽位上。 + + 超过上限的请求不失败,而是排队到后续槽位 —— 延迟升高、TPS 封顶在 + qps 附近,这正好把「单实例能力边界」变成可测量的数字。 + """ + + def __init__(self, qps): + self._interval = 1.0 / qps + self._lock = threading.Lock() + self._next_slot = time.monotonic() + + def wait(self): + with self._lock: + now = time.monotonic() + slot = self._next_slot if self._next_slot > now else now + self._next_slot = slot + self._interval + delay = slot - now + if delay > 0: + time.sleep(delay) + + +_pacer = _Pacer(_MAX_QPS) if _MAX_QPS > 0 else None + + +def _mark_price(contract_id: int) -> float: + """伪标记价:base + 正弦波动 + 微小随机抖动。""" + base = 30000.0 + contract_id * 1000.0 + t = time.time() - _start_ts + return round(base + base * 0.005 * math.sin(t / 10.0) + random.uniform(-5, 5), 2) + + +class Handler(BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" + + def log_message(self, *args): # 静默 + pass + + def handle_error(self, request, client_address): + # 压测结束时对端(worker)先断连是常态;BrokenPipe/ConnectionReset + # 不刷 traceback(traceback 会带本机绝对路径,污染日志) + err = sys.exc_info()[1] + if isinstance(err, (BrokenPipeError, ConnectionResetError)): + return + super().handle_error(request, client_address) + + def _reply(self, code, msg, data): + body = json.dumps({"code": code, "msg": msg, "data": data}).encode() + self.send_response(200) + self.send_header("Content-Type", "application/json; charset=utf-8") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def _read_json(self): + length = int(self.headers.get("Content-Length") or 0) + raw = self.rfile.read(length) if length else b"" + try: + return json.loads(raw.decode() or "{}") + except json.JSONDecodeError: + return None + + def _throttle(self): + """限流 + 附加延迟;/health 不参与(保持就绪探针轻量)。""" + if self.path.startswith("/health"): + return + if _pacer is not None: + _pacer.wait() + if _EXTRA_LATENCY > 0: + time.sleep(_EXTRA_LATENCY) + + def _open_order(self, order_type): + payload = self._read_json() + if payload is None: + return self._reply(400, "bad json", None) + if "user_id" not in payload or "contract_id" not in payload: + return self._reply(400, "missing field", None) + with _lock: + oid = _next_order_id[0] + _next_order_id[0] += 1 + _orders[oid] = {"order_id": oid, "order_type": order_type, **payload} + self._reply(0, "ok", {"order_id": oid}) + + def _open_condition_order(self): + payload = self._read_json() + if payload is None: + return self._reply(400, "bad json", None) + try: + trigger_price = float(payload["trigger_price"]) + cid = int(payload["contract_id"]) + side = payload.get("side", "bid") + except (KeyError, TypeError, ValueError): + return self._reply(400, "missing/bad field", None) + mark = _mark_price(cid) + triggered = evaluate_trigger(side, trigger_price, mark) + with _lock: + oid = _next_order_id[0] + _next_order_id[0] += 1 + _orders[oid] = {"order_id": oid, "order_type": "condition", + "triggered": triggered, **payload} + # 注意:triggered 是业务结果,不是错误 —— code 恒为 0。 + # 这正是「触发价写死」难以被发现的原因:报表全绿,业务数据却是退化的。 + self._reply(0, "ok", {"order_id": oid, "triggered": triggered, + "mark_price": mark}) + + def do_POST(self): + self._throttle() + path = self.path.split("?")[0] + if path == "/api/v1/order/condition/open": + self._open_condition_order() + elif path == "/api/v1/order/limit/open": + self._open_order("limit") + elif path == "/api/v1/order/market/quantity/open": + self._open_order("market_quantity") + elif path == "/api/v1/order/market/amount/open": + self._open_order("market_amount") + else: + self._reply(404, "not found", None) + + def do_DELETE(self): + self._throttle() + path = self.path.split("?")[0] + if path == "/api/v1/order/batch/cancel": + payload = self._read_json() or {} + ids = payload.get("order_ids", []) + with _lock: + canceled = sum(1 for i in ids if _orders.pop(i, None)) + self._reply(0, "ok", {"canceled": canceled}) + else: + self._reply(404, "not found", None) + + def do_GET(self): + self._throttle() + if self.path.startswith("/api/v1/mark/price"): + qs = dict(p.split("=", 1) for p in + self.path.split("?", 1)[-1].split("&") if "=" in p) + cid = int(qs.get("contract_id", 1)) + self._reply(0, "ok", {"contract_id": cid, "price": _mark_price(cid)}) + elif self.path.startswith("/health"): + self._reply(0, "ok", {"status": "up"}) + else: + self._reply(404, "not found", None) + + +def main(): + srv = ThreadingHTTPServer((_HOST, _PORT), Handler) + print(f"[target] http mock listening on http://{_HOST}:{_PORT}") + srv.serve_forever() + + +if __name__ == "__main__": + main() diff --git a/target/mark_price_service.py b/target/mark_price_service.py new file mode 100644 index 0000000..7281d46 --- /dev/null +++ b/target/mark_price_service.py @@ -0,0 +1,219 @@ +"""标记价格缓存服务(独立进程,perf-harness-demo 专用)。 + +链路:轮询行情源(本机 mock 的 /api/v1/mark/price,扮演「行情推送」) +→ 双元素滑动窗口去重 → 本地缓存(TTL)→ 对压测脚本提供 GET /mark/price。 + +两条硬语义(对应 tests/ 下的用例): + +1. 断流回退 —— 行情源不可用时**压测不中断**: + 出价顺序为 新鲜缓存(TTL 内)→ 默认价(stale=True,source=default)。 + 进程不因源故障退出,接口不因源故障报错。 + +2. 滑动窗口去重 —— 窗口保存最近两个**已接受**的价格(量化到 tick 后比较): + 新报价与窗口内任一值相同 → 重复推送,丢弃;都不同 → 真实变化,接受。 + ★ 只存「最后一个值」的伪窗口识别不了 A-B-A 交替重复(100→105→100 时 + 第三笔会被误判为新变化)—— 那样等于没去重。 + +端口默认 18097(env MARK_SERVICE_PORT);行情源默认 http://127.0.0.1:18099 +(env MARK_SOURCE)。零第三方依赖,只监听本机,绝不对外。 +""" + +import json +import os +import sys +import threading +import time +import urllib.request +from collections import deque +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +_DEFAULT_PORT = 18097 + + +def default_price_for(contract_id): + """默认兜底价:与 mock 的标记价基准同式(行情未接入时的静态参考价)。""" + return 30000.0 + contract_id * 1000.0 + + +class PriceCache: + """单合约的标记价缓存:去重窗口 + TTL + 断流回退。时钟可注入,便于测试。""" + + def __init__(self, contract_id, ttl=120.0, tick_size=1.0, window_size=2, + now=time.monotonic): + self.contract_id = contract_id + self.default_price = default_price_for(contract_id) + self.ttl = ttl + self.tick_size = tick_size + self.window_size = window_size + self._now = now + self._lock = threading.Lock() + self._window = deque(maxlen=window_size) + self._price = None # 最近一笔被接受的价格(原始值) + self._updated_at = None + self.stats = {"ticks": 0, "accepted": 0, "dups": 0, "fetch_errors": 0, + "served_cache": 0, "served_default": 0} + + def _quantize(self, price): + return round(round(price / self.tick_size) * self.tick_size, 6) + + def ingest_tick(self, price): + """喂入一笔行情。True=真实变化已接受;False=重复推送已丢弃。""" + with self._lock: + self.stats["ticks"] += 1 + q = self._quantize(price) + if q in self._window: + self.stats["dups"] += 1 + return False + self._window.append(q) + self._price = price + self._updated_at = self._now() + self.stats["accepted"] += 1 + return True + + def note_source_error(self): + with self._lock: + self.stats["fetch_errors"] += 1 + + def get_price(self): + """断流回退出价:TTL 内缓存 → 默认价。任何情况下不抛异常。""" + with self._lock: + if (self._price is not None + and self._now() - self._updated_at <= self.ttl): + self.stats["served_cache"] += 1 + return {"contract_id": self.contract_id, "price": self._price, + "stale": False, "source": "cache"} + self.stats["served_default"] += 1 + return {"contract_id": self.contract_id, "price": self.default_price, + "stale": True, "source": "default"} + + +class Poller: + """后台轮询行情源并喂给缓存;源故障只计数,绝不向外抛(断流≠进程死亡)。""" + + def __init__(self, source, cache, interval=0.2, timeout=1.0): + self.source = source.rstrip("/") + self.cache = cache + self.interval = interval + self.timeout = timeout + self._stop = threading.Event() + self._thread = None + + def poll_once(self): + url = (f"{self.source}/api/v1/mark/price" + f"?contract_id={self.cache.contract_id}") + try: + with urllib.request.urlopen(url, timeout=self.timeout) as r: + body = json.loads(r.read().decode()) + self.cache.ingest_tick(float(body["data"]["price"])) + except Exception: + self.cache.note_source_error() + + def start(self): + def loop(): + while not self._stop.is_set(): + self.poll_once() + self._stop.wait(self.interval) + + self._thread = threading.Thread(target=loop, daemon=True) + self._thread.start() + + def stop(self): + self._stop.set() + + +class Service: + """按合约懒加载 PriceCache + Poller;聚合 stats 供观测。""" + + def __init__(self, source, ttl=120.0, tick_size=1.0, poll_interval=0.2): + self.source = source + self.ttl = ttl + self.tick_size = tick_size + self.poll_interval = poll_interval + self._lock = threading.Lock() + self._caches = {} + self._pollers = {} + + def cache_for(self, contract_id): + with self._lock: + cache = self._caches.get(contract_id) + if cache is None: + cache = PriceCache(contract_id, ttl=self.ttl, + tick_size=self.tick_size) + poller = Poller(self.source, cache, interval=self.poll_interval) + poller.start() + self._caches[contract_id] = cache + self._pollers[contract_id] = poller + return cache + + def get_price(self, contract_id): + return self.cache_for(contract_id).get_price() + + def stats(self): + with self._lock: + return {str(cid): dict(c.stats) for cid, c in self._caches.items()} + + def stop_all(self): + with self._lock: + for p in self._pollers.values(): + p.stop() + + +def make_handler(service): + class Handler(BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" + + def log_message(self, *args): # 静默 + pass + + def handle_error(self, request, client_address): + # 对端先断连(压测收尾)是常态,不刷 traceback(会带本机绝对路径) + err = sys.exc_info()[1] + if isinstance(err, (BrokenPipeError, ConnectionResetError)): + return + super().handle_error(request, client_address) + + def _json(self, obj): + body = json.dumps(obj).encode() + self.send_response(200) + self.send_header("Content-Type", "application/json; charset=utf-8") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def do_GET(self): + if self.path.startswith("/mark/price"): + qs = dict(p.split("=", 1) for p in + self.path.split("?", 1)[-1].split("&") if "=" in p) + cid = int(qs.get("contract_id", 1)) + self._json(service.get_price(cid)) + elif self.path.startswith("/stats"): + self._json(service.stats()) + elif self.path.startswith("/health"): + self._json({"status": "up"}) + else: + self._json({"error": "not found"}) + + return Handler + + +def main(): + port = int(os.environ.get("MARK_SERVICE_PORT", str(_DEFAULT_PORT))) + source = os.environ.get("MARK_SOURCE", "http://127.0.0.1:18099") + ttl = float(os.environ.get("MARK_CACHE_TTL", "120")) + tick_size = float(os.environ.get("MARK_TICK_SIZE", "1")) + interval = float(os.environ.get("MARK_POLL_INTERVAL", "0.2")) + service = Service(source, ttl=ttl, tick_size=tick_size, + poll_interval=interval) + srv = ThreadingHTTPServer(("127.0.0.1", port), make_handler(service)) + print(f"[mark-service] listening on http://127.0.0.1:{port} " + f"source={source} ttl={ttl}s") + try: + srv.serve_forever() + except KeyboardInterrupt: + pass + finally: + service.stop_all() + + +if __name__ == "__main__": + main() diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000..e0d0015 --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,9 @@ +"""pytest 路径装配:让 tests/ 能直接 import target/ 与 scenarios/ 下的模块。""" + +import os +import sys + +_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +for _d in (os.path.join(_ROOT, "target"), os.path.join(_ROOT, "scenarios")): + if _d not in sys.path: + sys.path.insert(0, _d) diff --git a/tests/test_condition_trigger.py b/tests/test_condition_trigger.py new file mode 100644 index 0000000..27955b5 --- /dev/null +++ b/tests/test_condition_trigger.py @@ -0,0 +1,51 @@ +"""条件单触发语义(mock 端纯函数 evaluate_trigger)+ 写死触发价的退化演示。 + +evaluate_trigger 是失真实验的判定核心:方向写反(bid/ask 颠倒)会让 +「写死低价全触发」变成「写死低价全不触发」,实验结论整个颠倒 —— 必须钉死。 +""" + +from http_server import evaluate_trigger + +# mock 标记价区间(contract_id=1):base 31000 ± 0.5% 正弦 ± 抖动 ≈ [30840, 31160] +MARK_LOW, MARK_HIGH = 30840.0, 31160.0 + + +class TestBidSide: + """bid(买):标记价上穿/触及触发价才触发。""" + + def test_triggers_when_mark_at_or_above_trigger(self): + assert evaluate_trigger("bid", 30500.0, 31000.0) is True + assert evaluate_trigger("bid", 31000.0, 31000.0) is True # 边界:触及即触发 + + def test_not_triggered_when_mark_below_trigger(self): + assert evaluate_trigger("bid", 31500.0, 31000.0) is False + + +class TestAskSide: + """ask(卖):标记价下穿/触及触发价才触发。""" + + def test_triggers_when_mark_at_or_below_trigger(self): + assert evaluate_trigger("ask", 31500.0, 31000.0) is True + assert evaluate_trigger("ask", 31000.0, 31000.0) is True + + def test_not_triggered_when_mark_above_trigger(self): + assert evaluate_trigger("ask", 30500.0, 31000.0) is False + + +class TestHardcodedPriceDegenerates: + """把「写死触发价」的退化模式钉成用例:整个行情区间内结论恒为 0%/100%。""" + + def test_hardcoded_low_triggers_everywhere(self): + for mark in (MARK_LOW, 31000.0, MARK_HIGH): + assert evaluate_trigger("bid", 30500.0, mark) is True + + def test_hardcoded_high_triggers_nowhere(self): + for mark in (MARK_LOW, 31000.0, MARK_HIGH): + assert evaluate_trigger("bid", 31500.0, mark) is False + + def test_live_band_prices_can_go_either_way(self): + """挂在实时价 ±20 窄带内的触发价:同一价位带内既可触发也可不触发, + 即触发率由行情波动决定(不塌缩到 0/1)。""" + p = 31000.0 + outcomes = {evaluate_trigger("bid", p + d, 31000.0) for d in (-20, 20)} + assert outcomes == {True, False} diff --git a/tests/test_dispatcher.py b/tests/test_dispatcher.py new file mode 100644 index 0000000..247f974 --- /dev/null +++ b/tests/test_dispatcher.py @@ -0,0 +1,81 @@ +"""入口分流器:轮询必须均匀(否则 scale 实验的「实例数是唯一变量」不成立)。""" + +import json +import threading +import urllib.request +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +from dispatcher import BackendPool, make_handler + + +def _start_echo_backend(tag): + """起一个在响应里带回自己 tag 的假后端,返回 (server, port)。""" + class Echo(BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" + + def log_message(self, *args): + pass + + def do_POST(self): + length = int(self.headers.get("Content-Length") or 0) + if length: + self.rfile.read(length) + body = json.dumps({"backend": tag}).encode() + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + srv = ThreadingHTTPServer(("127.0.0.1", 0), Echo) + threading.Thread(target=srv.serve_forever, daemon=True).start() + return srv, srv.server_address[1] + + +def _post(port, path="/api/v1/order/limit/open"): + req = urllib.request.Request( + f"http://127.0.0.1:{port}{path}", data=b"{}", + headers={"Content-Type": "application/json"}) + with urllib.request.urlopen(req, timeout=5) as r: + return json.loads(r.read().decode()) + + +def test_round_robin_even_split(): + """20 个请求过 2 个后端:各 10 个(轮询均匀)。""" + srv_a, port_a = _start_echo_backend("A") + srv_b, port_b = _start_echo_backend("B") + try: + pool = BackendPool([port_a, port_b]) + dispatcher = ThreadingHTTPServer(("127.0.0.1", 0), make_handler(pool)) + threading.Thread(target=dispatcher.serve_forever, daemon=True).start() + try: + dport = dispatcher.server_address[1] + hits = {"A": 0, "B": 0} + for _ in range(20): + hits[_post(dport)["backend"]] += 1 + assert hits == {"A": 10, "B": 10} + finally: + dispatcher.shutdown() + dispatcher.server_close() + finally: + srv_a.shutdown() + srv_a.server_close() + srv_b.shutdown() + srv_b.server_close() + + +def test_health_is_local_not_proxied(): + """就绪探针由分流器本地应答(探的是分流器自己)。""" + pool = BackendPool([18999]) # 后端不存在也应能探活 + dispatcher = ThreadingHTTPServer(("127.0.0.1", 0), make_handler(pool)) + threading.Thread(target=dispatcher.serve_forever, daemon=True).start() + try: + dport = dispatcher.server_address[0:2][1] + with urllib.request.urlopen( + f"http://127.0.0.1:{dport}/health", timeout=5) as r: + body = json.loads(r.read().decode()) + assert body["data"]["status"] == "up" + assert body["data"]["backends"] == 1 + finally: + dispatcher.shutdown() + dispatcher.server_close() diff --git a/tests/test_mark_price_service.py b/tests/test_mark_price_service.py new file mode 100644 index 0000000..33535f1 --- /dev/null +++ b/tests/test_mark_price_service.py @@ -0,0 +1,116 @@ +"""标记价缓存服务的两条硬语义:断流回退 + 滑动窗口去重。 + +这是「压测脚本失真」判断的落点:缓存服务一旦写错(断流就崩 / 去重形同虚设), +下游所有触发率数据悄悄作废,而接口照常返回 200。 +""" + +import mark_price_service as mps + + +class FakeClock: + def __init__(self): + self.t = 0.0 + + def __call__(self): + return self.t + + def advance(self, dt): + self.t += dt + + +def make_cache(ttl=120.0): + clock = FakeClock() + cache = mps.PriceCache(contract_id=1, ttl=ttl, tick_size=1.0, + window_size=2, now=clock) + return cache, clock + + +class TestSlidingWindowDedup: + def test_same_price_repeated_is_deduped(self): + """同一价格连推多次:只接受第一笔,其余判重复。""" + cache, _ = make_cache() + assert cache.ingest_tick(31000.2) is True + for _ in range(5): + # 量化到 tick=1 后同为 31000 → 重复推送 + assert cache.ingest_tick(31000.4) is False + assert cache.stats["accepted"] == 1 + assert cache.stats["dups"] == 5 + + def test_alternating_prices_are_deduped(self): + """A-B-A-B 交替抖动也要判重复。 + + ★ 这是双元素窗口存在的理由:只存「最后一个值」的伪窗口在 + 100→105→100 时会把第三笔误判成新变化(只和 105 比),去重形同虚设。 + """ + cache, _ = make_cache() + assert cache.ingest_tick(31000.0) is True # 窗口 [31000] + assert cache.ingest_tick(31005.0) is True # 窗口 [31000, 31005] + assert cache.ingest_tick(31000.0) is False # 在窗口内 → 重复 + assert cache.ingest_tick(31005.0) is False # 在窗口内 → 重复 + assert cache.stats["accepted"] == 2 + assert cache.stats["dups"] == 2 + + def test_real_change_is_accepted(self): + """价格真实变化(落在窗口外)必须被识别接受,不能被去重误杀。""" + cache, _ = make_cache() + assert cache.ingest_tick(31000.0) is True + assert cache.ingest_tick(31005.0) is True + assert cache.ingest_tick(31003.0) is True # 新值,不在窗口内 + assert cache.stats["accepted"] == 3 + + def test_accepted_price_is_what_get_served(self): + """接受的新值要成为对外出价的值(不能去重把价格「冻」在旧值上)。""" + cache, _ = make_cache() + cache.ingest_tick(31000.0) + cache.ingest_tick(31050.0) + assert cache.get_price()["price"] == 31050.0 + + +class TestFallbackOnSourceOutage: + """断流回退:源不可用时压测不中断 —— 接口照常出价,绝不抛异常。""" + + def test_never_seen_source_serves_default(self): + """行情源从未可用过:回退默认价(与 mock 基准同式),标记 stale。""" + cache, _ = make_cache() + out = cache.get_price() + assert out["price"] == mps.default_price_for(1) # 31000.0 + assert out["stale"] is True + assert out["source"] == "default" + + def test_fresh_cache_served_within_ttl(self): + cache, _ = make_cache(ttl=120.0) + cache.ingest_tick(31234.5) + out = cache.get_price() + assert out["price"] == 31234.5 + assert out["stale"] is False + assert out["source"] == "cache" + + def test_outage_within_ttl_still_serves_cache(self): + """断流但缓存还在 TTL 内:继续用缓存价,压测不中断。""" + cache, clock = make_cache(ttl=120.0) + cache.ingest_tick(31234.5) + clock.advance(30) # 源挂了 30s(无新 tick),仍在 TTL 内 + out = cache.get_price() + assert out["price"] == 31234.5 + assert out["stale"] is False + + def test_outage_beyond_ttl_falls_back_to_default(self): + """断流超过 TTL:回退默认价,接口正常返回(不抛异常、不退出)。""" + cache, clock = make_cache(ttl=120.0) + cache.ingest_tick(31234.5) + clock.advance(121) # 缓存已过期 + out = cache.get_price() + assert out["price"] == mps.default_price_for(1) + assert out["stale"] is True + assert out["source"] == "default" + assert cache.stats["served_default"] == 1 + + def test_dead_source_counts_error_and_still_serves(self): + """源进程整个不在(连接被拒):poll 只计数不抛出,出价走回退。""" + cache, _ = make_cache() + poller = mps.Poller("http://127.0.0.1:9", cache, + interval=0.05, timeout=0.2) + poller.poll_once() # 端口 9 连接被拒 —— 必须被吞掉 + assert cache.stats["fetch_errors"] == 1 + out = cache.get_price() + assert out["source"] == "default" and out["stale"] is True diff --git a/tests/test_pacer.py b/tests/test_pacer.py new file mode 100644 index 0000000..e834644 --- /dev/null +++ b/tests/test_pacer.py @@ -0,0 +1,38 @@ +"""限流器(_Pacer):等距放行槽位。 + +它是横向扩展实验里「单实例上限」的实现 —— 如果限流不准,scale-1 与 +scale-4 的对比就没有意义。 +""" + +import time + +from http_server import _Pacer + + +def test_pacer_caps_rate(): + """qps=1000(1ms 槽位)连取 30 次:至少排满 29 个间隔。""" + pacer = _Pacer(1000) + t0 = time.monotonic() + for _ in range(30): + pacer.wait() + elapsed = time.monotonic() - t0 + assert elapsed >= 29 * 0.001 * 0.8 # 留 20% 调度余量,防 CI 抖动误报 + assert elapsed < 1.0 # 但也不能离谱(实现有 bug 时会卡死) + + +def test_pacer_first_slot_immediate(): + """第一个请求不应排队。""" + pacer = _Pacer(100) + t0 = time.monotonic() + pacer.wait() + assert time.monotonic() - t0 < 0.05 + + +def test_pacer_recovers_after_idle(): + """空闲一段时间后时隙立即给,不累积旧债(槽位取 max(now, next))。""" + pacer = _Pacer(100) # 10ms 槽位 + pacer.wait() + time.sleep(0.2) + t0 = time.monotonic() + pacer.wait() + assert time.monotonic() - t0 < 0.05