tradingSystem/app/services/price_limit_provider.py

110 lines
4.6 KiB
Python
Raw Permalink Normal View History

"""单证券限制价主源。只访问固定地址,不重试、不输出凭据或响应正文。
Timeout.total 限定一次 HTTP 连接/读取的超时预算;流式读取还会检查单调时钟。
DNS 解析及两次流块之间的阻塞不保证被总预算中断,因此这不是绝对墙钟期限。
整轮预算、重试和退避由采集任务负责,执行报价路径只读本地缓存。
"""
import json
import math
import time
import requests
from urllib3.exceptions import TimeoutError as TransportTimeout
from urllib3.util import Timeout
from app.core import price_limits
ENDPOINT = 'https://api.tushare.pro'
FIELDS = 'ts_code,trade_date,pre_close,up_limit,down_limit'
MAX_BODY_BYTES = 64 * 1024
def _error(reason):
return {'records': {}, 'invalid': {}, 'errors': [reason]}
def fetch_limit(code, day, token, timeout_sec=5):
"""查询指定交易日的一只沪深证券;所有失败仅返回固定原因码。"""
if not price_limits.supported(code):
return _error('INVALID_REQUEST_CODE')
code = code.strip().upper()
try:
target = price_limits._day(day)
except (TypeError, ValueError):
return _error('INVALID_TARGET_DATE')
if not isinstance(token, str) or not token.strip():
return _error('MISSING_PROVIDER_TOKEN')
if isinstance(timeout_sec, bool):
return _error('INVALID_HTTP_TIMEOUT')
try:
budget = float(timeout_sec)
except (TypeError, ValueError, OverflowError):
return _error('INVALID_HTTP_TIMEOUT')
if not math.isfinite(budget) or budget <= 0:
return _error('INVALID_HTTP_TIMEOUT')
session = response = None
deadline = time.monotonic() + budget
try:
session = requests.Session()
# 不读取环境代理、.netrc 或环境 CA 设置,凭据只发往固定 HTTPS 地址。
session.trust_env = False
response = session.post(ENDPOINT, json={
'api_name': 'stk_limit', 'token': token.strip(),
'params': {'ts_code': code, 'trade_date': target.replace('-', '')},
'fields': FIELDS,
}, headers={'Accept': 'application/json', 'Accept-Encoding': 'identity'},
allow_redirects=False, stream=True,
timeout=Timeout(total=budget, connect=min(2., budget), read=budget))
if time.monotonic() >= deadline:
return _error('HTTP_TIMEOUT')
if response.status_code != 200:
return _error('HTTP_ERROR')
declared = response.headers.get('Content-Length')
if declared is not None:
try:
length = int(declared)
except (TypeError, ValueError, OverflowError):
return _error('INVALID_PROVIDER_RESPONSE')
if length < 0:
return _error('INVALID_PROVIDER_RESPONSE')
if length > MAX_BODY_BYTES:
return _error('RESPONSE_TOO_LARGE')
body = bytearray()
for chunk in response.iter_content(chunk_size=4096):
if time.monotonic() >= deadline:
return _error('HTTP_TIMEOUT')
if not isinstance(chunk, bytes):
return _error('INVALID_PROVIDER_RESPONSE')
if len(body) + len(chunk) > MAX_BODY_BYTES:
return _error('RESPONSE_TOO_LARGE')
body.extend(chunk)
if time.monotonic() >= deadline:
return _error('HTTP_TIMEOUT')
try:
decoded = json.loads(body)
# 永远传非空单代码白名单,不能借空集合放开到全市场。
result = price_limits.provider_decode(decoded, target, requested_codes=[code])
except Exception:
return _error('INVALID_PROVIDER_RESPONSE')
if time.monotonic() >= deadline:
return _error('HTTP_TIMEOUT')
return result
except (requests.exceptions.Timeout, TransportTimeout):
return _error('HTTP_TIMEOUT')
except requests.exceptions.ConnectionError as exc:
# requests 的流式读取会把 urllib3 读超时包装成 ConnectionError。
if any(isinstance(cause, TransportTimeout) for cause in exc.args):
return _error('HTTP_TIMEOUT')
return _error('HTTP_ERROR')
except Exception:
# Requests 异常可包含URL、请求信息或上游正文,禁止回显和记完整日志。
return _error('HTTP_ERROR')
finally:
for resource in (response, session):
if resource is not None:
try:
resource.close()
except Exception:
pass # 清理异常不覆盖固定错误结果,也不输出潜在凭据。