#!/usr/bin/env python # -*- coding: utf-8 -*- """常驻任务:订阅标记价格行情,落进本地文件缓存(原始实现里的 XXL-JOB BEAN 模式)。 这是**判断②** 的落点。这个任务的失败不表现为崩溃,而是**慢性**的:原实现跑了一周, 内存从 50M 漂到 2G,因为 diskcache 从不自动淘汰、也没有任何东西去调 ``expire()``。 本模块的两处防腐设计: * 每个价格键带 TTL,并显式暴露 ``PriceCache.expire()`` 供调用方定期清理; * ZMQ socket 在 ``finally`` 里无条件释放(D2)。 它同时修掉了原实现的一处正确性缺陷(D1,见 ``MarkPriceSubscriber``)。 单独运行: python -m mark_price_service --duration 10 --verbose """ from __future__ import annotations import json import time from collections import deque import zmq from diskcache import Cache import config def price_key(contract_id) -> str: return f"mark_price:{contract_id}" class PriceCache: """diskcache 封装——两个任务唯一的交汇点。 持**单个**句柄:原实现每次 get/set 都新建一次 ``Cache()``,实测占构造耗时的 60%。 这正是判断① 说的「每秒重复付的固定成本」里的一块,顺手在这里消掉。 """ def __init__(self, path=None, ttl=None): self.path = str(path or config.CACHE_PATH) self.ttl = config.PRICE_TTL_SECONDS if ttl is None else ttl self._cache = Cache(self.path) def close(self): self._cache.close() def __enter__(self): return self def __exit__(self, *exc): self.close() # -- 通用接口 -------------------------------------------------------------- def set(self, key, value, ttl=None): self._cache.set(key, value, expire=self.ttl if ttl is None else ttl) def get(self, key, default=None): return self._cache.get(key, default) def expire(self) -> int: """清掉已过 TTL 的条目,返回被删除的数量。""" return self._cache.expire() def size(self) -> int: return len(self._cache) # -- 价格专用接口 ---------------------------------------------------------- def set_price(self, contract_id, price, ttl=None): self.set(price_key(contract_id), price, ttl=ttl) def get_price(self, contract_id): return self.get(price_key(contract_id)) def parse_frame(frame: str, topic: str): """把一帧 ``' '`` 解析成 (contract_id, mark_price)。""" payload = frame[len(topic):].strip() if frame.startswith(topic) else frame data = json.loads(payload) return int(data["contractId"]), float(data["markPrice"]) class MarkPriceSubscriber: """ZMQ SUB -> diskcache。 D1:原实现用一个**模块级** ``price_list`` 给所有币对共享去重窗口。contractId 4/5/6 交错推送时窗口被互相污染、去重逻辑失效,合法更新会被漏掉。这里窗口**按币对隔离**。 """ def __init__(self, addr=None, topic=None, cache=None, contracts=None, window_len=None): self.addr = addr or config.ZMQ_PUB_ADDR self.topic = topic or config.MARK_PRICE_TOPIC self.cache = cache or PriceCache() self.contracts = set(contracts or config.CONTRACT_IDS) self.window_len = window_len or config.SLIDING_WINDOW_LEN self._windows: dict[int, deque] = {} def handle_price(self, contract_id: int, price: float) -> bool: """喂入一次观测,返回是否写入了缓存。 去重规则(按币对):只有价格与该币对**上一次**观测不同才写入。 """ window = self._windows.setdefault(contract_id, deque(maxlen=self.window_len)) accept = (len(window) == 0) or (window[-1] != price) if accept: self.cache.set_price(contract_id, price) window.append(price) return accept def run(self, duration: float | None = None, max_messages: int | None = None) -> int: """持续消费直到达到时长/条数。无论怎么退出都会释放 socket。""" ctx = zmq.Context() sock = ctx.socket(zmq.SUB) received = 0 try: sock.connect(self.addr) sock.setsockopt_string(zmq.SUBSCRIBE, self.topic) poller = zmq.Poller() poller.register(sock, zmq.POLLIN) start = time.time() while True: if duration is not None and time.time() - start >= duration: break if max_messages is not None and received >= max_messages: break if sock not in dict(poller.poll(timeout=200)): continue try: contract_id, price = parse_frame(sock.recv_string(), self.topic) except (ValueError, KeyError): continue if contract_id in self.contracts: self.handle_price(contract_id, price) received += 1 finally: sock.close(linger=0) # D2:每条退出路径都显式释放,不留泄漏 ctx.term() return received def main(): import argparse p = argparse.ArgumentParser(description="订阅本机标记价格行情并写入本地缓存。") p.add_argument("--duration", type=float, default=None, help="运行秒数(默认一直跑)") p.add_argument("--dump", action="store_true", help="不订阅,只打印缓存里当前的标记价格(用来验证两个任务确实通过文件交换数据)") p.add_argument("--verbose", action="store_true") args = p.parse_args() cache = PriceCache() if args.dump: prices = {cid: cache.get_price(cid) for cid in config.CONTRACT_IDS} print(f"缓存里的标记价格:{prices}(存活条目 {cache.size()})") cache.close() return sub = MarkPriceSubscriber(cache=cache) if args.verbose: print(f"订阅器启动:{sub.addr} topic={sub.topic} " f"contracts={sorted(sub.contracts)}", flush=True) n = sub.run(duration=args.duration) if args.verbose: print(f"订阅器共处理 {n} 条标记价格消息,缓存存活条目 {cache.size()}", flush=True) cache.close() if __name__ == "__main__": main()