#!/usr/bin/env python # -*- coding: utf-8 -*- """每秒任务:加权随机决定这一秒的流量形态,并发构造并发送请求(固定频率模式)。 这是**判断①** 的落点。每秒执行窗口是硬约束;把单次执行从 10s+ 压进 1 秒,关键不在 「把代码写快」,而在**消掉每秒重复付的固定成本**: * 数据源、缓存句柄、HTTP 会话只建一次,跨周期复用(而不是每秒重建一次); * 载荷构造按 ``--workers`` 摊到多个进程,让 CPU 密集的部分用上多核; * 发送走 asyncio + aiohttp 并发,把串行的 HTTP 等待压到重叠。 构造与发送刻意分开(``build_specs`` / ``send_specs``):同一套构造器既能 ``--dry-run`` (一个请求都不发),也能真实压测。 D3:原实现用 ``eval("api.{}()".format(name))`` 分发操作,装饰器内部又 ``eval`` 重建调用。 这里全部换成 ``getattr`` 与 ``*args`` 直接转发——行为等价,但不再执行字符串。 python -m requester --dry-run --seconds 5 # 只构造,一个请求都不发 python -m requester --seconds 10 --verbose # 打本机 mock """ from __future__ import annotations import argparse import asyncio import multiprocessing as mp import random import sqlite3 import time from functools import wraps import config from mark_price_service import PriceCache # ========================================================================== # 数据源:替代原实现的 MySQL 分库 + Redis 集群 # ========================================================================== _SCHEMA = """ CREATE TABLE IF NOT EXISTS position ( position_no TEXT PRIMARY KEY, user_id TEXT, contract_id INTEGER, side INTEGER, -- 1 -> ask,否则 bid(沿用原实现的约定) avg_price REAL, quantity REAL, margin_type INTEGER, -- 1 全仓,2 逐仓 create_time REAL ); CREATE TABLE IF NOT EXISTS open_order ( order_no TEXT PRIMARY KEY, user_id TEXT, contract_id INTEGER, status INTEGER -- 2 / 3 视为挂单中,原实现就是这么过滤的 ); """ class DataStore: """请求构造器要查的那层数据的替身。 真实的构造器会去分库的 MySQL(订单、用户、权益各自分库,表按 user_id 取模拆分)和 一个 Redis 集群里拉账户、持仓、挂单。这些都不该出现在便携版 demo 里,所以本类只复刻 构造器**消费到的那层形态**——同样的 ``get_*`` 方法、同样返回带同样字段名的 ``list[dict]``,背后换成一个内存 sqlite。日后要接回真实连接,换掉引擎即可,不必动 Api。 """ def __init__(self, seed: int = 20260921): self.conn = sqlite3.connect(":memory:", check_same_thread=False) self.conn.row_factory = sqlite3.Row self.conn.executescript(_SCHEMA) self._seed(random.Random(seed)) def _seed(self, rng: random.Random): pn = on = 0 for uid in config.USER_IDS: for cid in config.CONTRACT_IDS: if rng.random() < 0.6: # 多数用户在多数币对上持有仓位 pn += 1 self.conn.execute( "INSERT INTO position VALUES (?,?,?,?,?,?,?,?)", (f"POS{pn}", uid, cid, 1 if rng.random() < 0.5 else 0, round(config.SEED_PRICES[cid] * (1 + rng.uniform(-0.05, 0.05)), 4), float(rng.randint(1, 50)), 1 if uid in config.CROSS_MARGIN_USERS else 2, rng.random()), ) if rng.random() < 0.3: on += 1 self.conn.execute("INSERT INTO open_order VALUES (?,?,?,?)", (f"ORD{on}", uid, cid, rng.choice([2, 3]))) self.conn.commit() @staticmethod def _rows(cursor) -> list[dict]: return [dict(r) for r in cursor.fetchall()] def get_position(self, user_id): return self._rows(self.conn.execute( "SELECT * FROM position WHERE user_id=? AND quantity>0 " "ORDER BY create_time DESC LIMIT 5", (str(user_id),))) def get_position_by_contract_id(self, contract_id, user_id): return self._rows(self.conn.execute( "SELECT * FROM position WHERE contract_id=? AND user_id=? AND quantity>0 " "ORDER BY create_time DESC LIMIT 5", (int(contract_id), str(user_id)))) def get_order_no(self, contract_id, user_id): return self._rows(self.conn.execute( "SELECT * FROM open_order WHERE contract_id=? AND user_id=? AND status IN (2,3) LIMIT 5", (int(contract_id), str(user_id)))) def close(self): self.conn.close() # ========================================================================== # 业务操作 # ========================================================================== def action(func): """把产出的一条请求描述记进共享缓存,让一轮运行可回放(与原实现同一套机制)。""" @wraps(func) def adapter(self, *args, **kwargs): result = func(self, *args, **kwargs) if isinstance(result, dict): entry = dict(result) entry["class_name"] = func.__name__ cached = self.cache.get("order_info") or [] cached.append(entry) self.cache.set("order_info", cached) return result return adapter class Api: """按业务操作构造请求描述 ``{method, url, json}``;实际发送交给下面 asyncio 那层。 每个方法返回的都是一份描述,而不是已经发出去的请求——这样同一套构造器对 dry-run 和 真实运行都能用。 """ def __init__(self, store: DataStore | None = None, cache: PriceCache | None = None): self.store = store or DataStore() self.cache = cache or PriceCache() def mark_price(self, contract_id): """请求器认为的标记价:读常驻任务落下的缓存,缺价时回落到种子价。""" cached = self.cache.get_price(contract_id) return float(cached if cached is not None else config.SEED_PRICES.get(contract_id, 10.0)) @staticmethod def _spec(op, payload): method, path = config.OPERATIONS[op] return {"method": method, "url": config.MOCK_BASE_URL + path, "json": payload} @staticmethod def _skip(): """构造不出合法请求(例如该用户当前无持仓)——计数上跳过,不当成失败。""" return {"method": "SKIP", "url": None, "json": None} def _pick_position(self, user_id): rows = self.store.get_position(user_id) return random.choice(rows) if rows else None # -- 8 个业务操作 ---------------------------------------------------------- @action def open_order(self, user_id=None, contract_id=None): contract_id = contract_id or random.choice(config.CONTRACT_IDS) price = self.mark_price(contract_id) return self._spec("open_order", { "contractId": contract_id, "userId": user_id or random.choice(config.USER_IDS), "side": random.choice(["ask", "bid"]), "price": round(price + random.uniform(-config.PRICE_FLOAT, config.PRICE_FLOAT), 5), "quantity": random.randint(1, 50), "marginType": 2, "marginRate": 0.02, "durationQualifiers": "GTC", "txId": "burst", }) @action def market_open_order(self, user_id=None): return self._spec("market_open_order", { "contractId": random.choice(config.CONTRACT_IDS), "userId": user_id or random.choice(config.USER_IDS), "quantity": random.randint(1, 50), "marginType": 2, "marginRate": 0.02, "txId": "market_open", }) @action def close_order(self, user_id=None): pos = self._pick_position(user_id or random.choice(config.USER_IDS)) if pos is None: return self._skip() return self._spec("close_order", { "userId": pos["user_id"], "contractId": pos["contract_id"], "side": "ask" if pos["side"] == 1 else "bid", "price": str(abs(pos["avg_price"])), "quantity": random.randint(1, int(pos["quantity"])), "marginType": pos["margin_type"], "positionNo": pos["position_no"], "txId": "close_order", }) @action def cancel_order(self, user_id=None): user_id = user_id or random.choice(config.USER_IDS) rows = self.store.get_order_no(random.choice(config.CONTRACT_IDS), user_id) if not rows: return self._skip() row = random.choice(rows) return self._spec("cancel_order", { "contractId": row["contract_id"], "userId": user_id, "orderNo": row["order_no"]}) @action def condition_order(self, user_id=None, contract_id=None): contract_id = contract_id or random.choice(config.CONTRACT_IDS) price = self.mark_price(contract_id) return self._spec("condition_order", { "contractId": contract_id, "userId": user_id or random.choice(config.USER_IDS), "curtPrice": price, "triggerPrice": round(price + random.uniform(0, 0.5), 5), "conditionOrderType": random.randint(3, 4), "triggerType": 4, "orderType": random.randint(1, 2), "dependencyNo": "0", "dependencyType": "condition", "positionEffect": 1, }) @action def condition_position(self, user_id=None): user_id = user_id or random.choice(config.USER_IDS) pos = self._pick_position(user_id) if pos is None: return self._skip() price = self.mark_price(pos["contract_id"]) f = config.PRICE_FLOAT up = random.randint(1, 2) == 1 return self._spec("condition_position", { "contractId": pos["contract_id"], "userId": user_id, "side": "ask" if pos["side"] == 1 else "bid", "dependencyNo": pos["position_no"], "dependencyType": "position", "positionEffect": 2, "orderType": 2, "conditionOrderType": 1 if up else 2, "curtPrice": price + f if up else price - f, "triggerPrice": price + f * (1.5 if up else -0.5), "amount": str(random.randint(1, 50)), }) @action def reverse_position(self, user_id=None): user_id = user_id or random.choice(config.USER_IDS) rows = self.store.get_position_by_contract_id(random.choice(config.CONTRACT_IDS), user_id) if not rows: return self._skip() pos = random.choice(rows) return self._spec("reverse_position", { "positionNo": pos["position_no"], "userId": int(pos["user_id"]), "contractId": pos["contract_id"], "quantity": random.randint(1, int(pos["quantity"]) + 1), "txId": "reverse_position", }) @action def transfer(self, user_id=None, quantity=10000): return self._spec("transfer", { "currencyId": 21, "quantity": str(quantity), "transferFrom": "burst", "transferTo": "burst", "transferType": 1, "txId": "burst", "userId": int(user_id or random.choice(config.USER_IDS)), "userType": 4, }) # ========================================================================== # 流量形态 -> 载荷 -> 发送 # ========================================================================== def weighted_ops(count: int): """这一秒要构造哪些操作。它只决定流量的**形态**,不是重点(见判断③)。""" names = [name for name, _ in config.WEIGHTED_OPS] weights = [w for _, w in config.WEIGHTED_OPS] return random.choices(names, weights=weights, k=count) def _build(api: Api, ops): specs = [] for op in ops: fn = getattr(api, op, None) # D3:用 getattr,不用 eval if fn is None: continue spec = fn() if spec and spec.get("method") != "SKIP": specs.append(spec) return specs def _build_worker(ops): """放在模块顶层是为了能被进程池 pickle。每个进程自建数据源与缓存句柄。""" api = Api() try: return _build(api, ops) finally: api.store.close() api.cache.close() def build_specs(api: Api, ops, workers: int = 1): if workers <= 1: return _build(api, ops) chunks = [ops[i::workers] for i in range(workers)] with mp.Pool(workers) as pool: return [spec for group in pool.map(_build_worker, chunks) for spec in group] async def _send_all(specs): import aiohttp timeout = aiohttp.ClientTimeout(total=2) async with aiohttp.ClientSession(timeout=timeout) as session: tasks = [getattr(session, s["method"].lower())(url=s["url"], json=s.get("json") or {}) for s in specs] responses = await asyncio.gather(*tasks, return_exceptions=True) ok = 0 for r in responses: if not isinstance(r, Exception): await r.read() await r.release() ok += 1 return ok def send_specs(specs) -> int: return asyncio.run(_send_all(specs)) if specs else 0 def run_cycle(api: Api, *, dry_run: bool, workers: int, verbose: bool): ops = weighted_ops(max(1, len(config.WEIGHTED_OPS))) if verbose: print(f" 本轮采样到的操作:{sorted(set(ops))}") specs = build_specs(api, ops, workers=workers) return {"built": len(specs), "sent": 0 if dry_run else send_specs(specs)} def main(): p = argparse.ArgumentParser(description="加权随机的交易请求模拟器。") p.add_argument("--dry-run", action="store_true", help="只构造请求,一个都不发") p.add_argument("--seconds", type=int, default=5, help="每秒跑一轮,共跑 N 秒") p.add_argument("--workers", type=int, default=1, help="构造载荷用的进程数") p.add_argument("--interval", type=float, default=1.0, help="两轮之间的间隔秒数") p.add_argument("--verbose", action="store_true") args = p.parse_args() api = Api() total_built = total_sent = cycles = 0 start = time.time() try: while time.time() - start < args.seconds: t0 = time.time() summary = run_cycle(api, dry_run=args.dry_run, workers=args.workers, verbose=args.verbose) total_built += summary["built"] total_sent += summary["sent"] cycles += 1 elapsed = time.time() - t0 if args.verbose: print(f" 第 {cycles} 轮:构造={summary['built']} 发送={summary['sent']} " f"耗时={elapsed:.3f}s") # 保持约 1 秒的节奏,模拟固定频率调度器那样触发。 time.sleep(max(0.0, args.interval - elapsed)) finally: api.store.close() api.cache.close() mode = "dry-run" if args.dry_run else "live" print(f"burst[{mode}] 轮数={cycles} 构造={total_built} 发送={total_sent} " f"总耗时={time.time() - start:.2f}s") if __name__ == "__main__": main()