220 lines
8.0 KiB
Python
220 lines
8.0 KiB
Python
"""标记价格缓存服务(独立进程,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()
|