pytdxdata 0.7.0__tar.gz → 0.7.2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. {pytdxdata-0.7.0 → pytdxdata-0.7.2}/PKG-INFO +1 -1
  2. {pytdxdata-0.7.0 → pytdxdata-0.7.2}/pyproject.toml +1 -1
  3. {pytdxdata-0.7.0 → pytdxdata-0.7.2}/pyproject.toml.orig +1 -1
  4. {pytdxdata-0.7.0 → pytdxdata-0.7.2}/src/pytdxdata/__init__.py +1 -1
  5. {pytdxdata-0.7.0 → pytdxdata-0.7.2}/src/pytdxdata/api.py +35 -11
  6. {pytdxdata-0.7.0 → pytdxdata-0.7.2}/src/pytdxdata/frames.py +114 -23
  7. {pytdxdata-0.7.0 → pytdxdata-0.7.2}/src/pytdxdata/models/__init__.py +4 -0
  8. {pytdxdata-0.7.0 → pytdxdata-0.7.2}/src/pytdxdata/pool/ex_pool.py +63 -32
  9. {pytdxdata-0.7.0 → pytdxdata-0.7.2}/src/pytdxdata/pool/pool.py +125 -41
  10. {pytdxdata-0.7.0 → pytdxdata-0.7.2}/src/pytdxdata/protocol/commands/quotes.py +49 -11
  11. {pytdxdata-0.7.0 → pytdxdata-0.7.2}/src/pytdxdata/scheduler/paginator.py +72 -14
  12. {pytdxdata-0.7.0 → pytdxdata-0.7.2}/LICENSE +0 -0
  13. {pytdxdata-0.7.0 → pytdxdata-0.7.2}/README.md +0 -0
  14. {pytdxdata-0.7.0 → pytdxdata-0.7.2}/src/pytdxdata/_binary.py +0 -0
  15. {pytdxdata-0.7.0 → pytdxdata-0.7.2}/src/pytdxdata/cache/__init__.py +0 -0
  16. {pytdxdata-0.7.0 → pytdxdata-0.7.2}/src/pytdxdata/cache/disk.py +0 -0
  17. {pytdxdata-0.7.0 → pytdxdata-0.7.2}/src/pytdxdata/cache/key.py +0 -0
  18. {pytdxdata-0.7.0 → pytdxdata-0.7.2}/src/pytdxdata/cache/manager.py +0 -0
  19. {pytdxdata-0.7.0 → pytdxdata-0.7.2}/src/pytdxdata/cache/memory.py +0 -0
  20. {pytdxdata-0.7.0 → pytdxdata-0.7.2}/src/pytdxdata/cache/ttl.py +0 -0
  21. {pytdxdata-0.7.0 → pytdxdata-0.7.2}/src/pytdxdata/cli.py +0 -0
  22. {pytdxdata-0.7.0 → pytdxdata-0.7.2}/src/pytdxdata/codec/__init__.py +0 -0
  23. {pytdxdata-0.7.0 → pytdxdata-0.7.2}/src/pytdxdata/codec/block.py +0 -0
  24. {pytdxdata-0.7.0 → pytdxdata-0.7.2}/src/pytdxdata/codec/financial.py +0 -0
  25. {pytdxdata-0.7.0 → pytdxdata-0.7.2}/src/pytdxdata/codec/industry.py +0 -0
  26. {pytdxdata-0.7.0 → pytdxdata-0.7.2}/src/pytdxdata/codec/payload.py +0 -0
  27. {pytdxdata-0.7.0 → pytdxdata-0.7.2}/src/pytdxdata/config.py +0 -0
  28. {pytdxdata-0.7.0 → pytdxdata-0.7.2}/src/pytdxdata/decimal_sync.py +0 -0
  29. {pytdxdata-0.7.0 → pytdxdata-0.7.2}/src/pytdxdata/indicator.py +0 -0
  30. {pytdxdata-0.7.0 → pytdxdata-0.7.2}/src/pytdxdata/pool/__init__.py +0 -0
  31. {pytdxdata-0.7.0 → pytdxdata-0.7.2}/src/pytdxdata/pool/connection.py +0 -0
  32. {pytdxdata-0.7.0 → pytdxdata-0.7.2}/src/pytdxdata/pool/ex_connection.py +0 -0
  33. {pytdxdata-0.7.0 → pytdxdata-0.7.2}/src/pytdxdata/pool/health.py +0 -0
  34. {pytdxdata-0.7.0 → pytdxdata-0.7.2}/src/pytdxdata/pool/probe_cache.py +0 -0
  35. {pytdxdata-0.7.0 → pytdxdata-0.7.2}/src/pytdxdata/protocol/__init__.py +0 -0
  36. {pytdxdata-0.7.0 → pytdxdata-0.7.2}/src/pytdxdata/protocol/commands/__init__.py +0 -0
  37. {pytdxdata-0.7.0 → pytdxdata-0.7.2}/src/pytdxdata/protocol/commands/base.py +0 -0
  38. {pytdxdata-0.7.0 → pytdxdata-0.7.2}/src/pytdxdata/protocol/commands/ex_ext.py +0 -0
  39. {pytdxdata-0.7.0 → pytdxdata-0.7.2}/src/pytdxdata/protocol/commands/ex_proto.py +0 -0
  40. {pytdxdata-0.7.0 → pytdxdata-0.7.2}/src/pytdxdata/protocol/commands/finance.py +0 -0
  41. {pytdxdata-0.7.0 → pytdxdata-0.7.2}/src/pytdxdata/protocol/commands/kline.py +0 -0
  42. {pytdxdata-0.7.0 → pytdxdata-0.7.2}/src/pytdxdata/protocol/commands/mac.py +0 -0
  43. {pytdxdata-0.7.0 → pytdxdata-0.7.2}/src/pytdxdata/protocol/commands/mac_ext.py +0 -0
  44. {pytdxdata-0.7.0 → pytdxdata-0.7.2}/src/pytdxdata/protocol/commands/mac_tick.py +0 -0
  45. {pytdxdata-0.7.0 → pytdxdata-0.7.2}/src/pytdxdata/protocol/commands/minute.py +0 -0
  46. {pytdxdata-0.7.0 → pytdxdata-0.7.2}/src/pytdxdata/protocol/commands/security_list.py +0 -0
  47. {pytdxdata-0.7.0 → pytdxdata-0.7.2}/src/pytdxdata/protocol/commands/setup.py +0 -0
  48. {pytdxdata-0.7.0 → pytdxdata-0.7.2}/src/pytdxdata/protocol/commands/std_ext.py +0 -0
  49. {pytdxdata-0.7.0 → pytdxdata-0.7.2}/src/pytdxdata/protocol/commands/transaction.py +0 -0
  50. {pytdxdata-0.7.0 → pytdxdata-0.7.2}/src/pytdxdata/protocol/commands/xdxr.py +0 -0
  51. {pytdxdata-0.7.0 → pytdxdata-0.7.2}/src/pytdxdata/protocol/datetime_.py +0 -0
  52. {pytdxdata-0.7.0 → pytdxdata-0.7.2}/src/pytdxdata/protocol/frame.py +0 -0
  53. {pytdxdata-0.7.0 → pytdxdata-0.7.2}/src/pytdxdata/protocol/mac_frame.py +0 -0
  54. {pytdxdata-0.7.0 → pytdxdata-0.7.2}/src/pytdxdata/protocol/price.py +0 -0
  55. {pytdxdata-0.7.0 → pytdxdata-0.7.2}/src/pytdxdata/protocol/volume.py +0 -0
  56. {pytdxdata-0.7.0 → pytdxdata-0.7.2}/src/pytdxdata/router.py +0 -0
  57. {pytdxdata-0.7.0 → pytdxdata-0.7.2}/src/pytdxdata/scheduler/__init__.py +0 -0
  58. {pytdxdata-0.7.0 → pytdxdata-0.7.2}/src/pytdxdata/server_probe.py +0 -0
  59. {pytdxdata-0.7.0 → pytdxdata-0.7.2}/src/pytdxdata/servers.json +0 -0
  60. {pytdxdata-0.7.0 → pytdxdata-0.7.2}/src/pytdxdata/symbols.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pytdxdata
3
- Version: 0.7.0
3
+ Version: 0.7.2
4
4
  Summary: 通达信(TongDaXin)行情数据客户端:动态连接池 + 双层TTL缓存 + 3连接并发分页,纯asyncio零运行时依赖,支持A股/港股/美股/期货/期权
5
5
  Keywords: tdx,trading,stock,kline,quote,通达信,A股,港股,美股,期货,asyncio,quant
6
6
  Author: openbot-coder
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "pytdxdata"
3
- version = "0.7.0"
3
+ version = "0.7.2"
4
4
  description = "通达信(TongDaXin)行情数据客户端:动态连接池 + 双层TTL缓存 + 3连接并发分页,纯asyncio零运行时依赖,支持A股/港股/美股/期货/期权"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.11"
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "pytdxdata"
3
- version = "0.7.0"
3
+ version = "0.7.2"
4
4
  description = "通达信(TongDaXin)行情数据客户端:动态连接池 + 双层TTL缓存 + 3连接并发分页,纯asyncio零运行时依赖,支持A股/港股/美股/期货/期权"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.11"
@@ -18,7 +18,7 @@ from .models import (
18
18
  XdxrRecord,
19
19
  )
20
20
 
21
- __version__ = "0.7.0"
21
+ __version__ = "0.7.2"
22
22
  __all__ = [
23
23
  "TdxData",
24
24
  "Market",
@@ -187,6 +187,9 @@ _BULK_MAX_COUNT = 700 # MAC 单请求返回上限;超过只能逐只分页
187
187
  # 最多用几台服务器:池里 24 台全用反而更慢 —— 慢节点会成为长尾(最长的那台
188
188
  # 拖住整轮),实测 count=2 全市场 24 台 2.95s / 只取最快 12 台 1.45s。
189
189
  _BULK_MAX_CONNS = 12
190
+ # 流水线失败的一批最多回队几次。回队 = 交给**其它健康连接**立刻接手;
191
+ # 上限保证全节点失联时不会无限打转,超限后落到尾部并发兜底。
192
+ _BULK_MAX_RETRY = 2
190
193
  # 交易时段(分钟):上午 9:30-11:30、下午 13:00-15:00,共 240 分钟
191
194
  _AM_OPEN, _AM_CLOSE = 9 * 60 + 30, 11 * 60 + 30
192
195
  _PM_OPEN, _PM_CLOSE = 13 * 60, 15 * 60
@@ -973,6 +976,7 @@ class TdxData:
973
976
  by_text = {s.text: s for s in syms}
974
977
  acc: dict[str, list[SecurityBar]] = {}
975
978
  retry: dict[str, Symbol] = {}
979
+ attempts: dict[str, int] = {}
976
980
 
977
981
  async def worker(pc) -> None:
978
982
  broken = False
@@ -985,10 +989,22 @@ class TdxData:
985
989
  try:
986
990
  res = await pc.execute_pipeline(cmds)
987
991
  except Exception:
988
- # 流水线中途失败 = 响应流已错配,连接作废、整批交回逐只重试
992
+ # 流水线中途失败 = 响应流已错配,连接作废。
993
+ # 这一批**立刻放回队首**:其它健康连接会马上接手,
994
+ # 不必等 gather 结束再串行补(老实现每条重试都要重新
995
+ # 付一次 RTT,几百只就是十几秒的长尾)。
989
996
  broken = True
990
- for s, _, _ in batch:
991
- retry[s.text] = s
997
+ again: list[tuple[Symbol, int, int]] = []
998
+ for item in batch:
999
+ s = item[0]
1000
+ n = attempts.get(s.text, 0)
1001
+ if n < _BULK_MAX_RETRY:
1002
+ attempts[s.text] = n + 1
1003
+ again.append(item)
1004
+ else:
1005
+ retry[s.text] = s
1006
+ if again:
1007
+ tasks.extendleft(reversed(again))
992
1008
  return
993
1009
  for (s, _, _), bars in zip(batch, res):
994
1010
  acc.setdefault(s.text, []).extend(bars)
@@ -996,19 +1012,27 @@ class TdxData:
996
1012
  await pool.release(pc, broken=broken)
997
1013
 
998
1014
  await asyncio.gather(*(worker(pc) for pc in held))
999
- # 连接全挂时 worker 会提前 return,队列里剩下的标的没人取 —— 一并交回逐只,
1015
+ # 连接全挂时 worker 会提前 return,队列里剩下的标的没人取 —— 一并交回重试,
1000
1016
  # 否则会**静默少数据**(实测 20 只只回 16 只)。
1001
1017
  while tasks:
1002
1018
  s, _, _ = tasks.popleft()
1003
1019
  retry.setdefault(s.text, s)
1004
1020
  out = {k: self._finish_bars(v, by_text[k]) for k, v in acc.items()}
1005
- for text, s in retry.items():
1006
- try:
1007
- out[text] = await self._bars_one(
1008
- s, period, start=start, count=count, adjust=adj,
1009
- start_date=None, end_date=None)
1010
- except Exception:
1011
- out.setdefault(text, [])
1021
+ if retry:
1022
+ # 尾部兜底也并发做:坏节点把批次吐回来时可能有几十上百只,
1023
+ # 串行重试等于把「一台机器卡住」放大成「整批卡住」。
1024
+ sem = asyncio.Semaphore(max(2, min(len(retry), pool.max_size)))
1025
+
1026
+ async def rescue(text: str, s: Symbol) -> None:
1027
+ async with sem:
1028
+ try:
1029
+ out[text] = await self._bars_one(
1030
+ s, period, start=start, count=count, adjust=adj,
1031
+ start_date=None, end_date=None)
1032
+ except Exception:
1033
+ out.setdefault(text, [])
1034
+
1035
+ await asyncio.gather(*(rescue(t, s) for t, s in retry.items()))
1012
1036
  return out
1013
1037
 
1014
1038
  async def _bars_one(
@@ -28,7 +28,8 @@ from collections.abc import Callable, Sequence
28
28
  from contextvars import ContextVar
29
29
  from datetime import datetime as _dt
30
30
  from enum import IntEnum
31
- from typing import Any
31
+ from operator import attrgetter
32
+ from typing import Any, NamedTuple
32
33
 
33
34
  from . import models as _models
34
35
  from .models import (
@@ -166,13 +167,6 @@ def _json_or_none(value: Any) -> str | None:
166
167
  return json.dumps(value, ensure_ascii=False, separators=(",", ":"))
167
168
 
168
169
 
169
- def _getter(name: str) -> Callable[[Any], Any]:
170
- def _get(row: Any) -> Any:
171
- return _as_int(getattr(row, name))
172
-
173
- return _get
174
-
175
-
176
170
  def _json_getter(name: str) -> Callable[[Any], Any]:
177
171
  def _get(row: Any) -> Any:
178
172
  return _json_or_none(getattr(row, name))
@@ -227,17 +221,50 @@ _EXTRAS: dict[type, tuple[tuple[str, Callable[[Any], Any]], ...]] = {
227
221
  ),
228
222
  }
229
223
 
230
- #: 需要 JSON 化的字典字段(按类区分,避免误伤 ``FinancialRecord.fields: list[float]``)
224
+ #: 模型 -> 需要 JSON 化的字典字段(按类区分,避免误伤 ``FinancialRecord.fields: list[float]``)
231
225
  _JSON_FIELDS: dict[type, frozenset[str]] = {
232
226
  SecurityQuote: frozenset({"fields"}),
233
227
  TransactionRecord: frozenset({"fields"}),
234
228
  MinuteBar: frozenset({"fields"}),
235
229
  }
236
230
 
237
- _PLAN_CACHE: dict[type, tuple[tuple[str, Callable[[Any], Any]], ...]] = {}
231
+ #: 交易日列的缓存键(时间字段里参与 ``trading_date`` 计算的那些)。
232
+ #:
233
+ #: ``trading_date`` 是纯函数:A股/港股/期货就是自然日,美股凌晨段回退一天。
234
+ #: 但它每算一次都要格式化三个整数(美股还要减一天),240k 行里往往只有
235
+ #: **1~2 个不同的键** —— 按「除 minute 外的时间字段」缓存后,整列从 218ms 降到 33ms。
236
+ #: 键里保留 ``hour`` 是为了一箭双雕:既覆盖美股 ``hour < 12`` 的跨日判断,
237
+ #: 又不必把 ``_US_DAY_SPLIT_HOUR`` 的取值抄过来(切换点改了本文件也不用跟着改)。
238
+ _TD_KEYS: dict[type, tuple[str, ...]] = {
239
+ SecurityBar: ("year", "month", "day", "hour"),
240
+ MinuteBar: ("date", "day_offset", "hour"),
241
+ }
242
+
243
+ #: 交易日列名(走缓存路径,不按行取属性)
244
+ _TD_COL = "trading_date"
245
+
246
+ #: 增强列里可以直接用 ``attrgetter`` 取的(属性本身即得值,不需要额外加工)
247
+ _PLAIN_EXTRAS = frozenset({"datetime"})
248
+
249
+
250
+ class _ColPlan(NamedTuple):
251
+ """某模型的输出列计划(构造一次,按类缓存)。
252
+
253
+ 分成三类是性能决定的:逐行调 Python 闭包比 C 层 ``attrgetter`` 慢一倍以上,
254
+ 而 ``trading_date`` 这种「同一批里值大量重复」的列更是值得单独缓存。
255
+ """
238
256
 
257
+ order: tuple[str, ...] # 输出列顺序
258
+ plain: tuple[str, ...] # 直接取属性即可的列名
259
+ wrapped: tuple[tuple[str, Callable[[Any], Any]], ...] # 需要加工的列(JSON / 五档 / 除权日)
260
+ td_name: str | None # 交易日列名
261
+ td_key: Callable[[Any], Any] | None # 交易日缓存键
239
262
 
240
- def _plan_for(cls: type) -> tuple[tuple[str, Callable[[Any], Any]], ...]:
263
+
264
+ _PLAN_CACHE: dict[type, _ColPlan] = {}
265
+
266
+
267
+ def _plan_for(cls: type) -> _ColPlan:
241
268
  """构造(并缓存)某模型的输出列计划。
242
269
 
243
270
  查找顺序按 MRO 走:``IndexBar`` 没有自己的计划,但它是 ``SecurityBar`` 的子类,
@@ -250,6 +277,7 @@ def _plan_for(cls: type) -> tuple[tuple[str, Callable[[Any], Any]], ...]:
250
277
  drops: tuple[str, ...] = ()
251
278
  extras: tuple[tuple[str, Callable[[Any], Any]], ...] = ()
252
279
  json_fields: frozenset[str] = frozenset()
280
+ td_fields: tuple[str, ...] = ()
253
281
  for klass in cls.__mro__:
254
282
  if not drops and klass in _DROPS:
255
283
  drops = _DROPS[klass]
@@ -257,30 +285,92 @@ def _plan_for(cls: type) -> tuple[tuple[str, Callable[[Any], Any]], ...]:
257
285
  extras = _EXTRAS[klass]
258
286
  if not json_fields and klass in _JSON_FIELDS:
259
287
  json_fields = _JSON_FIELDS[klass]
288
+ if not td_fields and klass in _TD_KEYS:
289
+ td_fields = _TD_KEYS[klass]
260
290
 
261
291
  import dataclasses
262
292
 
263
- plan: list[tuple[str, Callable[[Any], Any]]] = []
293
+ order: list[str] = []
294
+ plain: list[str] = []
295
+ wrapped: list[tuple[str, Callable[[Any], Any]]] = []
296
+ td_name: str | None = None
297
+
298
+ def add(name: str, getter: Callable[[Any], Any] | None = None) -> None:
299
+ nonlocal td_name
300
+ order.append(name)
301
+ if name == _TD_COL:
302
+ td_name = name # 交易日列走缓存,不看 getter
303
+ elif getter is None or name in _PLAIN_EXTRAS:
304
+ plain.append(name)
305
+ else:
306
+ wrapped.append((name, getter))
307
+
264
308
  inserted = False
265
309
  for f in dataclasses.fields(cls): # type: ignore[arg-type]
266
310
  if f.name in drops:
267
311
  if not inserted:
268
- plan.extend(extras)
312
+ for name, getter in extras:
313
+ add(name, getter)
269
314
  inserted = True
270
315
  continue
271
- getter = _json_getter(f.name) if f.name in json_fields else _getter(f.name)
272
- plan.append((f.name, getter))
316
+ add(f.name, _json_getter(f.name) if f.name in json_fields else None)
273
317
  if not inserted:
274
318
  # 没有丢弃字段的模型(如 SecurityInfo):增强列直接追加到末尾
275
- plan.extend(extras)
276
-
277
- _PLAN_CACHE[cls] = tuple(plan)
278
- return _PLAN_CACHE[cls]
319
+ for name, getter in extras:
320
+ add(name, getter)
321
+
322
+ plan = _ColPlan(
323
+ order=tuple(order),
324
+ plain=tuple(plain),
325
+ wrapped=tuple(wrapped),
326
+ td_name=td_name,
327
+ td_key=attrgetter(*td_fields) if td_fields else None,
328
+ )
329
+ _PLAN_CACHE[cls] = plan
330
+ return plan
331
+
332
+
333
+ def _trading_dates(key_of: Callable[[Any], Any], rows: Sequence[Any]) -> list[str]:
334
+ """按缓存键批量算交易日串(同一批里绝大多数行是重复键)。"""
335
+ cache: dict[Any, str] = {}
336
+ out: list[str] = []
337
+ ap = out.append
338
+ for row in rows:
339
+ key = key_of(row)
340
+ value = cache.get(key)
341
+ if value is None: # trading_date 永远是字符串,不会与 None 混淆
342
+ value = cache[key] = row.trading_date
343
+ ap(value)
344
+ return out
279
345
 
280
346
 
281
347
  def _columns(cls: type, rows: Sequence[Any]) -> dict[str, list]:
282
- """列式采集:一次遍历填满所有列,比逐行 ``asdict()`` 快得多。"""
283
- return {name: [get(row) for row in rows] for name, get in _plan_for(cls)}
348
+ """列式采集:逐列一次遍历,比逐行 ``asdict()`` 快得多。
349
+
350
+ - 普通列用 ``list(map(attrgetter(name), rows))``:取值发生在 C 层,没有 Python 帧;
351
+ - ``trading_date`` 按时间字段缓存(240k 行常只有 1~2 个键);
352
+ - 其余列(JSON / 五档 / 除权日)才走逐行回调;
353
+ - ``IntEnum`` 归一化放在最后**按列**做一次,而不是每个单元格都判一次。
354
+ """
355
+ plan = _plan_for(cls)
356
+ if not rows:
357
+ return {name: [] for name in plan.order}
358
+
359
+ cols: dict[str, list] = {}
360
+ for name in plan.plain:
361
+ cols[name] = list(map(attrgetter(name), rows))
362
+ if plan.td_name is not None and plan.td_key is not None:
363
+ cols[plan.td_name] = _trading_dates(plan.td_key, rows)
364
+ for name, get in plan.wrapped:
365
+ cols[name] = [get(row) for row in rows]
366
+
367
+ # polars 对 IntEnum 的类型推断不可靠(会退化成 Object 列),统一转纯 int。
368
+ # 只在首元素就是 IntEnum 时才整列转,普通 int 列一次都不多花。
369
+ for name, col in cols.items():
370
+ if col and isinstance(col[0], IntEnum):
371
+ cols[name] = [_as_int(value) for value in col]
372
+
373
+ return {name: cols[name] for name in plan.order}
284
374
 
285
375
 
286
376
  def _columns_of_dicts(rows: Sequence[dict]) -> dict[str, list]:
@@ -375,7 +465,7 @@ def to_frame(data: Any, *, backend: str = "polars", model: str | None = None) ->
375
465
  if merged is not None:
376
466
  return merged
377
467
  cls = _model_by_name(model)
378
- return be.empty(tuple(name for name, _ in _plan_for(cls)) if cls else ())
468
+ return be.empty(_plan_for(cls).order if cls else ())
379
469
 
380
470
  if isinstance(data, list):
381
471
  if data and isinstance(data[0], IndexTradeStats):
@@ -390,7 +480,8 @@ def to_frame(data: Any, *, backend: str = "polars", model: str | None = None) ->
390
480
  if data:
391
481
  # 元素既不是 dataclass 也不是 dict(如 list[float])——不该走到这里
392
482
  raise TypeError(f"无法转换为 DataFrame 的列表元素:{type(data[0])!r}")
393
- return be.frame({name: [] for name, _ in _plan_for(cls)}) if cls else be.empty(())
483
+ return (be.frame({name: [] for name in _plan_for(cls).order})
484
+ if cls else be.empty(()))
394
485
 
395
486
  raise TypeError(f"无法转换为 DataFrame 的返回值类型:{type(data)!r}")
396
487
 
@@ -216,6 +216,10 @@ class SecurityQuote:
216
216
  A股(标准通道):五档 ``bid``/``ask`` + 买卖量 + 涨跌停价齐全,``name`` 为空。
217
217
  A股(``fields=[...]`` 走 MAC 0x122B):``name`` 与 ``fields`` 齐全,五档为空。
218
218
  扩展市场(港股/美股/期货):``name`` + 基础价量在属性上,其余字段位在 ``fields``。
219
+
220
+ ``server_time`` 是**行情快照时间**:``HH:MM:SS.ff``,小数位数等于该品种价格小数位
221
+ (股票 2 / ETF·LOF·B股 3 / 国债·回购 4),通常比本地时钟慢 5~15 秒。**指数恒为空串**
222
+ (协议里这个字段对指数不是时钟);判断行情是否更新看它有没有变,别看调用时刻。
219
223
  """
220
224
  market: int
221
225
  code: str
@@ -37,6 +37,9 @@ class ExPoolTimeoutError(ConnectionError):
37
37
  class ExPool:
38
38
  """EX通道连接池(港股/期货,端口7727,连接时自动login)。"""
39
39
 
40
+ FAIL_COOLDOWN = 30.0
41
+ """握手失败后拉黑该主机的秒数(EX 节点少,冷却比标准池短)。"""
42
+
40
43
  def __init__(self, servers: list[str], *, timeout: float = 10.0,
41
44
  min_size: int = 2, max_size: int = 6,
42
45
  per_server_cap: int = 1,
@@ -58,6 +61,9 @@ class ExPool:
58
61
  self._total = 0
59
62
  self._closed = False
60
63
  self._cond = asyncio.Condition()
64
+ # 死节点短期拉黑:一台 EX 主机握手失败后,后续 acquire 直接绕开它,
65
+ # 而不是每次都再付一遍 ``self.timeout`` 的握手超时。
66
+ self._fail_until: dict[str, float] = {}
61
67
 
62
68
  async def start(self) -> None:
63
69
  async with self._cond:
@@ -72,6 +78,7 @@ class ExPool:
72
78
  self._server_count[host] = self._server_count.get(host, 0) + 1
73
79
  except Exception as e:
74
80
  log.warning("EX连接失败 %s: %s", host, str(e)[:60])
81
+ self._fail_until[host] = time.monotonic() + self.FAIL_COOLDOWN
75
82
 
76
83
  async def close(self) -> None:
77
84
  self._closed = True
@@ -94,8 +101,11 @@ class ExPool:
94
101
  if timeout is None:
95
102
  timeout = self.acquire_timeout
96
103
  deadline = None if timeout is None else time.monotonic() + timeout
97
- async with self._cond:
98
- while True:
104
+ avoid: set[str] = set() # 本次 acquire 里已经握手失败、别再试的主机
105
+ while True:
106
+ new_conn = None
107
+ new_host = None
108
+ async with self._cond:
99
109
  # 1. 优先借用空闲连接(过期则丢弃,槽位在锁内回收)
100
110
  if self._idle:
101
111
  _, conn = self._idle.pop()
@@ -107,44 +117,65 @@ class ExPool:
107
117
  self._server_count[conn.host] = max(0, self._server_count.get(conn.host, 0) - 1)
108
118
  self._schedule_close(conn)
109
119
 
110
- # 2. 可扩容 → 锁内预留槽位,锁外建连
111
- new_conn = None
112
- new_host = None
120
+ # 2. 可扩容 → 锁内预留槽位,锁外建连(不能持锁做网络 IO)
113
121
  if self._total < self.max_size and self.servers:
114
- host = self._next_available_server()
122
+ host = self._next_available_server(avoid)
115
123
  if host is not None:
116
124
  self._total += 1
117
125
  self._server_count[host] = self._server_count.get(host, 0) + 1
118
- new_conn = ExTdxConnection(host, 7727, self.timeout, self.handshake_map.get(host, self.handshake))
126
+ new_conn = ExTdxConnection(
127
+ host, 7727, self.timeout,
128
+ self.handshake_map.get(host, self.handshake))
119
129
  new_host = host
120
- if new_conn is not None:
121
- # 锁外网络 IO:连接失败回滚槽位后继续等待
130
+ elif avoid and all(h in avoid for h in self.servers):
131
+ # 所有主机本次都试过了、全失败:等下去也不会有结果
132
+ raise ExPoolTimeoutError(self, timeout)
133
+
134
+ # 3. 没抢到槽位 → 在锁内排队等 release 唤醒(waiter 必须持锁)
135
+ if new_conn is None:
136
+ now = time.monotonic()
137
+ if deadline is not None and now >= deadline:
138
+ raise ExPoolTimeoutError(self, timeout)
122
139
  try:
123
- await new_conn.connect()
124
- return new_conn
125
- except Exception as e:
126
- log.warning("EX扩容失败 %s: %s", new_host, str(e)[:60])
127
- async with self._cond:
128
- self._total = max(0, self._total - 1)
129
- self._server_count[new_host] = max(0, self._server_count.get(new_host, 0) - 1)
130
-
131
- # 3. 池满:排队等待 release 唤醒(或超时)
132
- now = time.monotonic()
133
- if deadline is not None and now >= deadline:
134
- raise ExPoolTimeoutError(self, timeout)
135
- try:
136
- if deadline is None:
137
- await self._cond.wait()
138
- else:
139
- await asyncio.wait_for(self._cond.wait(), timeout=deadline - now)
140
- except asyncio.TimeoutError:
141
- raise ExPoolTimeoutError(self, timeout)
142
-
143
- def _next_available_server(self) -> str | None:
140
+ if deadline is None:
141
+ await self._cond.wait()
142
+ else:
143
+ await asyncio.wait_for(self._cond.wait(), timeout=deadline - now)
144
+ except asyncio.TimeoutError:
145
+ raise ExPoolTimeoutError(self, timeout) from None
146
+ continue
147
+
148
+ # ---- 锁外建连 ----
149
+ try:
150
+ await new_conn.connect()
151
+ async with self._cond:
152
+ self._fail_until.pop(new_host, None)
153
+ return new_conn
154
+ except Exception as e:
155
+ log.warning("EX扩容失败 %s: %s", new_host, str(e)[:60])
156
+ avoid.add(new_host) # type: ignore[arg-type]
157
+ async with self._cond:
158
+ self._total = max(0, self._total - 1)
159
+ self._server_count[new_host] = max(0, self._server_count.get(new_host, 0) - 1)
160
+ self._fail_until[new_host] = time.monotonic() + self.FAIL_COOLDOWN
161
+ self._cond.notify_all()
162
+ continue
163
+
164
+ def _next_available_server(self, avoid: set[str] | None = None) -> str | None:
165
+ """挑一台**未达并发上限**的主机:优先未冷却的,冷却中的只在别无选择时用。"""
166
+ avoid = avoid or set()
167
+ fallback: str | None = None
168
+ now = time.monotonic()
144
169
  for h in self.servers:
145
- if self._server_count.get(h, 0) < self.per_server_cap:
170
+ if h in avoid:
171
+ continue
172
+ if self._server_count.get(h, 0) >= self.per_server_cap:
173
+ continue
174
+ if now >= self._fail_until.get(h, 0.0):
146
175
  return h
147
- return None
176
+ if fallback is None:
177
+ fallback = h
178
+ return fallback
148
179
 
149
180
  def _schedule_close(self, conn: ExTdxConnection) -> None:
150
181
  async def _close():
@@ -75,6 +75,15 @@ class PooledConnection:
75
75
  class DynamicPool:
76
76
  """动态连接池:按服务器维度统计连接数,每台服务器最多 per_server_cap 个连接。"""
77
77
 
78
+ BLACKOUT_COOLDOWN = 2.0
79
+ """全主机失败后的熔断时长(秒)。
80
+
81
+ 全部服务器同时不可用时,每次 :meth:`acquire` 都会把每台主机握手一遍再放弃。
82
+ 上层是「按标的逐只重试」的循环,6000 只标的 × 16 台主机 × 握手耗时 = 几分钟
83
+ 的空转。熔断期内直接抛 :class:`PoolTimeoutError`,让调用方快速走完并返回,
84
+ 冷却结束再试一次探测全灭是否恢复。
85
+ """
86
+
78
87
  def __init__(self, servers: list[str], *, port: int = DEFAULT_PORT,
79
88
  timeout: float = 10.0, min_size: int = 4, max_size: int = 12,
80
89
  per_server_cap: int = 1,
@@ -104,6 +113,7 @@ class DynamicPool:
104
113
  self._total = 0
105
114
  self._closed = False
106
115
  self._started = False
116
+ self._blackout_until = 0.0 # 全灭熔断截止时刻(monotonic)
107
117
  self._lock = asyncio.Lock()
108
118
  self._cond = asyncio.Condition(self._lock)
109
119
  self._reaper_task: asyncio.Task | None = None
@@ -127,10 +137,12 @@ class DynamicPool:
127
137
  break
128
138
  try:
129
139
  pc = await self._new_conn(host)
130
- self._idle.append(pc)
131
- self._total += 1
132
140
  except Exception as e:
133
141
  log.warning("初始连接失败 %s: %s", host, str(e)[:60])
142
+ continue
143
+ async with self._lock:
144
+ self._register_locked(pc)
145
+ self._idle.append(pc)
134
146
 
135
147
  if self._total == 0:
136
148
  log.warning("连接池初始连接全部失败,将在使用时按需重试")
@@ -160,6 +172,12 @@ class DynamicPool:
160
172
  return out
161
173
 
162
174
  async def _new_conn(self, host: str) -> PooledConnection:
175
+ """建立一条连接(**纯 IO,不改任何计数**)。
176
+
177
+ 计数由调用方在锁内用 :meth:`_register_locked` / :meth:`_reserve_locked`
178
+ 单独完成——建连必须能在池锁之外进行,否则一台坏服务器的握手超时
179
+ 会把所有并发协程一起冻住。
180
+ """
163
181
  conn = TdxConnection(host, self.port, self.timeout)
164
182
  await conn.connect()
165
183
  if self.probe_factory is not None:
@@ -168,12 +186,28 @@ class DynamicPool:
168
186
  except Exception:
169
187
  await conn.close()
170
188
  raise
171
- pc = PooledConnection(conn, host)
189
+ return PooledConnection(conn, host)
190
+
191
+ def _register_locked(self, pc: PooledConnection) -> None:
192
+ """登记一条已建好的连接(调用方需持锁)。"""
172
193
  self._conns.add(pc)
173
- self._server_count[host] = self._server_count.get(host, 0) + 1
194
+ self._server_count[pc.host] = self._server_count.get(pc.host, 0) + 1
195
+ self._total += 1
196
+ self.stats.total = self._total
174
197
  self.stats.created += 1
175
- self.stats.total = self._total + 1
176
- return pc
198
+
199
+ def _reserve_locked(self, host: str) -> None:
200
+ """锁内**预留**一个槽位(真正建连在锁外做)。"""
201
+ self._total += 1
202
+ self._server_count[host] = self._server_count.get(host, 0) + 1
203
+ self.stats.total = self._total
204
+
205
+ def _unreserve_locked(self, host: str) -> None:
206
+ """撤销预留(建连失败时回滚计数)。"""
207
+ self._total = max(0, self._total - 1)
208
+ if self._server_count.get(host, 0) > 0:
209
+ self._server_count[host] -= 1
210
+ self.stats.total = self._total
177
211
 
178
212
  async def close(self) -> None:
179
213
  self._closed = True
@@ -208,10 +242,19 @@ class DynamicPool:
208
242
  单连接约束下,池大小 = 服务器数 × per_server_cap。当并发请求超过池大小时,
209
243
  超额协程在此**排队等待**(基于 Condition),待其他协程 release 后被唤醒,
210
244
  而非立即超时放弃。默认 timeout=30s 防止在坏服务器场景下永久挂起。
245
+
246
+ **建连在池锁之外**:锁内只预留槽位,TCP 握手 + 探针放到锁外做。否则
247
+ 一台坏服务器握手超时(最长 ``self.timeout``)期间,所有其它协程的
248
+ acquire/release 全部被这个锁挡住——5 台坏节点能把整批任务拖慢十几秒。
211
249
  """
212
250
  deadline = None if timeout is None else (time.monotonic() + timeout)
213
- async with self._cond:
214
- while True:
251
+ avoid: set[str] = set() # 本次 acquire 里已握手失败的主机,别再重复试
252
+ while True:
253
+ if time.monotonic() < self._blackout_until:
254
+ raise PoolTimeoutError(
255
+ "所有服务器均不可用(熔断中,稍后自动重试)")
256
+ host = ""
257
+ async with self._cond:
215
258
  now = time.monotonic()
216
259
  # 1. 优先借用空闲连接(跳过冷却中的服务器,避免反复选中坏节点)
217
260
  while self._idle:
@@ -222,35 +265,65 @@ class DynamicPool:
222
265
  return pc
223
266
  self._drop_locked(pc)
224
267
 
225
- # 2. 可扩容(未达上限且有可用服务器)→ 新建连接
268
+ # 2. 全坏场景下这里必须能退出:扩容失败分支会 continue,
269
+ # 没有这一行就会无限重试、永远不会抛 PoolTimeoutError。
270
+ if deadline is not None and now >= deadline:
271
+ raise PoolTimeoutError("连接池获取超时(连接数已达上限且无空闲)")
272
+
273
+ # 3. 可扩容 → 锁内**只预留槽位**
226
274
  if self._total < self.max_size:
227
- host = self._next_available_server()
228
- if host is None:
275
+ host = self._next_available_server(avoid=avoid) or ""
276
+ if not host:
229
277
  # 兜底:全部服务器都在冷却中,而池子未满 —— 此时等 release
230
278
  # 永远等不到(没人持有),只能挑最健康的一台顶着冷却重试
231
- host = self._next_available_server(ignore_cooldown=True)
279
+ host = self._next_available_server(
280
+ ignore_cooldown=True, avoid=avoid) or ""
232
281
  if host:
233
- try:
234
- pc = await self._new_conn(host)
235
- self._total += 1
236
- self.stats.borrowed += 1
237
- return pc
238
- except Exception as e:
239
- log.warning("扩容连接失败 %s: %s", host, str(e)[:60])
240
- self.health.record_failure(host)
241
- # 循环重试:可能换下一台服务器
242
- continue
243
-
244
- # 3. 池满:排队等待 release 唤醒(或超时)
245
- if deadline is not None and now >= deadline:
246
- raise PoolTimeoutError("连接池获取超时(连接数已达上限且无空闲)")
247
- try:
248
- if deadline is None:
249
- await self._cond.wait()
250
- else:
251
- await asyncio.wait_for(self._cond.wait(), timeout=deadline - now)
252
- except asyncio.TimeoutError:
253
- raise PoolTimeoutError("连接池获取超时(连接数已达上限且无空闲)")
282
+ self._reserve_locked(host)
283
+ elif avoid and all(h in avoid for h in self.servers):
284
+ # 本轮每台主机都握手失败过了 → 再等下去也不会有连接。
285
+ # 同时熔断一小段时间,避免上层「逐只重试」把握手放大成
286
+ # 成千上万次(实测 6000 标的能空转 60s+)。
287
+ self._blackout_until = now + self.BLACKOUT_COOLDOWN
288
+ raise PoolTimeoutError(
289
+ f"所有服务器均不可用({len(avoid)} 台均已失败)")
290
+
291
+ if not host:
292
+ # 4. 池满/无可用服务器:排队等 release 唤醒(或超时)
293
+ remaining = None if deadline is None else deadline - now
294
+ try:
295
+ if remaining is None:
296
+ await self._cond.wait()
297
+ else:
298
+ await asyncio.wait_for(self._cond.wait(), timeout=remaining)
299
+ except asyncio.TimeoutError:
300
+ raise PoolTimeoutError(
301
+ "连接池获取超时(连接数已达上限且无空闲)") from None
302
+ continue
303
+
304
+ # ---- 锁外建连:失败只影响本次请求,不冻结其它协程 ----
305
+ try:
306
+ pc = await self._new_conn(host)
307
+ except Exception as e:
308
+ avoid.add(host)
309
+ async with self._cond:
310
+ self._unreserve_locked(host)
311
+ self._cond.notify_all() # 槽位已回滚,唤醒排队者
312
+ self.health.record_failure(host)
313
+ log.warning("扩容连接失败 %s: %s", host, str(e)[:60])
314
+ continue
315
+ if self._closed:
316
+ await pc.close()
317
+ async with self._cond:
318
+ self._unreserve_locked(host)
319
+ self._cond.notify_all()
320
+ raise PoolTimeoutError("连接池已关闭")
321
+ # 槽位已在锁内预留,这里只补登记,不重复计数
322
+ self._conns.add(pc)
323
+ self.stats.created += 1
324
+ self.stats.borrowed += 1
325
+ self._blackout_until = 0.0 # 有连接成功 → 立刻解除熔断
326
+ return pc
254
327
 
255
328
  async def acquire_many(self, k: int) -> list[PooledConnection]:
256
329
  """批量借出 k 个连接(分页并发用),超额请求排队等待不丢。"""
@@ -262,8 +335,11 @@ class DynamicPool:
262
335
  break
263
336
  return out
264
337
 
265
- def _next_available_server(self, *, ignore_cooldown: bool = False) -> str | None:
266
- ranked = self.health.rank(self.servers)
338
+ def _next_available_server(self, *, ignore_cooldown: bool = False,
339
+ avoid: set[str] | None = None) -> str | None:
340
+ """挑一台主机(``avoid`` 里的跳过,用于同一次 acquire 内不重复试错)。"""
341
+ avoid = avoid or set()
342
+ ranked = self.health.rank([h for h in self.servers if h not in avoid])
267
343
  # 1. 优先选未冷却且未达并发上限的服务器
268
344
  for h in ranked:
269
345
  if self.health.in_cooldown(h) and not ignore_cooldown:
@@ -311,12 +387,20 @@ class DynamicPool:
311
387
  results = await asyncio.gather(
312
388
  *(self._new_conn(h) for h in hosts), return_exceptions=True)
313
389
  async with self._lock:
314
- for pc in results:
315
- if isinstance(pc, PooledConnection):
316
- self._total += 1
317
- self.stats.total = self._total
318
- if not self._closed and pc.alive:
319
- self._idle.append(pc)
390
+ for host, res in zip(hosts, results):
391
+ if not isinstance(res, PooledConnection):
392
+ # 建连失败 → 记一次失败,后续 acquire 会把它排到队尾
393
+ self.health.record_failure(host)
394
+ continue
395
+ pc: PooledConnection = res
396
+ if self._closed or not pc.alive or self._total >= self.max_size:
397
+ # 建好却发现池已满/已关闭:必须关掉,否则连接泄漏,
398
+ # 而且 _total 会被虚增(老实现就在这儿漏计数)
399
+ asyncio.create_task(self._safe_close(pc))
400
+ continue
401
+ self._register_locked(pc)
402
+ self._idle.append(pc)
403
+ self._cond.notify_all()
320
404
 
321
405
  async def release(self, pc: PooledConnection, *, broken: bool = False) -> None:
322
406
  if self.stats.borrowed > 0:
@@ -5,6 +5,7 @@ import struct
5
5
 
6
6
  from ..._binary import unpack_from
7
7
  from ...models import SecurityQuote
8
+ from ...symbols import is_cn_index
8
9
  from ..price import get_price
9
10
  from ..volume import get_volume
10
11
  from .base import BaseCommand
@@ -161,13 +162,49 @@ def price_decimal_digits(market: int, code: str) -> int:
161
162
  return _decimal_digits_static(m, code)
162
163
 
163
164
 
164
- def format_server_time(raw: int) -> str:
165
- """服务器时间编码:小时 + 百万分之一小时。14999212 -> 14:59:57.163"""
166
- hours, fractional_hour = divmod(raw, 1_000_000)
167
- total_millis = fractional_hour * 3600 // 1000
168
- minutes, remainder = divmod(total_millis, 60_000)
169
- seconds, millis = divmod(remainder, 1000)
170
- return f"{hours:02d}:{minutes:02d}:{seconds:02d}.{millis:03d}"
165
+ _SERVER_TIME_SKEW = 40
166
+ """服务端在「50~59 秒」段会写成「90~99」秒,整数值固定多 40×10**d。"""
167
+
168
+
169
+ def format_server_time(raw: int, digits: int = 2) -> str:
170
+ """报价快照时间解码:十进制数字拼接 ``HH MM SS`` + ``digits`` 位小数。
171
+
172
+ 编码(2026-10-30 盘中实测确定)::
173
+
174
+ 整数 = HH*10**(4+d) + MM*10**(2+d) + SS*10**d + 小数
175
+ d = 该品种**价格小数位**(股票 2 / ETF·LOF·B股 3 / 国债·回购 4)
176
+
177
+ 实测样例:``13224002``(d=2)→ ``13:22:40.02``;``132245903``(d=3)→
178
+ ``13:22:45.903``;``1310228050``(d=4)→ ``13:10:22.8050``。
179
+
180
+ 历史错误(0.8.0 修正):此前按「小时 + 百万分之一小时」解码 —— 用
181
+ ``divmod(raw, 1_000_000)`` 取小时、余数按每秒 3600/1e6 折算。股票会把
182
+ 11:29:59 解成 **11:17:57**(基准错了、速率也只有真实时钟的 53%),
183
+ ETF / 债券更会解出 ``113:00:21.222`` 这种小时 > 23 的非法值。
184
+
185
+ ⚠️ 服务端怪癖:**SS 落在 50~59 秒时写成 90~99**(编码值 +40 秒)。实测
186
+ 3 分钟连续采样,未修正时该区间的滞后会从稳定的 10.6 秒突然变成 -29.4 秒
187
+ (正好差 40)。因此这里对 ``SS >= 60`` 一律减 40 秒还原。
188
+
189
+ ⚠️ 指数(``sh000001`` / ``sz399001`` …)该字段**不是**这只时钟:解出来
190
+ MM 常 > 59、且不同指数互相矛盾(同一时刻 000001 是 12:89、399001 是 12:15),
191
+ 协议里没有给出可用信息。这类返回值一律为空串,不要编造时间;要指数时间
192
+ 请用 :meth:`~pytdxdata.api.TdxData.get_minutes` 或 K 线。
193
+ """
194
+ if raw <= 0:
195
+ return ""
196
+ d = digits if 0 <= digits <= 6 else 2
197
+ scale = 10 ** d
198
+ frac = raw % scale
199
+ rest = raw // scale
200
+ seconds = rest % 100
201
+ minutes = (rest // 100) % 100
202
+ hours = rest // 10000
203
+ if seconds >= 60:
204
+ seconds -= _SERVER_TIME_SKEW
205
+ if hours > 23 or minutes > 59 or not 0 <= seconds <= 59:
206
+ return ""
207
+ return f"{hours:02d}:{minutes:02d}:{seconds:02d}.{frac:0{d}d}"
171
208
 
172
209
 
173
210
  class GetSecurityQuotesCmd(BaseCommand[list[SecurityQuote]]):
@@ -235,13 +272,14 @@ class GetSecurityQuotesCmd(BaseCommand[list[SecurityQuote]]):
235
272
  pos += 4
236
273
 
237
274
  code = code_b.decode("utf-8").rstrip("\x00")
238
- divisor = 10 ** price_decimal_digits(market_b, code)
275
+ dp = price_decimal_digits(market_b, code)
276
+ divisor = 10 ** dp
239
277
  p = price_raw / divisor
240
278
  results.append(SecurityQuote(
241
279
  market=market_b, code=code, price=p,
242
280
  cur_vol=float(cur_vol),
243
281
  rise_speed=_rise_speed / 100.0,
244
- decimal_point=price_decimal_digits(market_b, code),
282
+ decimal_point=dp,
245
283
  open_amount=float(_unknown_3),
246
284
  pre_close=(price_raw + last_close_diff) / divisor,
247
285
  open=(price_raw + open_diff) / divisor,
@@ -250,8 +288,8 @@ class GetSecurityQuotesCmd(BaseCommand[list[SecurityQuote]]):
250
288
  vol=float(vol), amount=amount, s_vol=float(s_vol), b_vol=float(b_vol),
251
289
  bid=[((price_raw + d) / divisor, v) for d, v in bid],
252
290
  ask=[((price_raw + d) / divisor, v) for d, v in ask],
253
- server_time=format_server_time(unknown_0),
291
+ server_time="" if is_cn_index(market_b, code)
292
+ else format_server_time(unknown_0, dp),
254
293
  trading_status=trading_status,
255
294
  ))
256
295
  return results
257
- return results
@@ -10,6 +10,7 @@ from __future__ import annotations
10
10
 
11
11
  import asyncio
12
12
  import logging
13
+ from collections import deque
13
14
  from dataclasses import dataclass
14
15
  from typing import Any, Callable
15
16
 
@@ -81,15 +82,53 @@ class Paginator:
81
82
  stop = asyncio.Event()
82
83
  out: list[PageResult] = []
83
84
  out_lock = asyncio.Lock()
85
+ # 静态切片保证「每台连接都干活」(并发摊开),另备一个共享的
86
+ # ``leftover``:某个 worker 的连接坏掉退出时,它**没做完的页**会
87
+ # 放回这里,由还活着的 worker 接着做。老实现没有这层——一个
88
+ # worker 挂掉,它那一整份页就没人做了,要么整轮报错、要么静默缺页。
89
+ leftover: deque[tuple[int, int]] = deque()
90
+ q_lock = asyncio.Lock()
84
91
  k = len(slots)
85
92
  workers = [
86
93
  asyncio.create_task(
87
- self._worker(slots[wid], jobs[wid::k], cmd_factory,
88
- stop, out, out_lock, spec)
94
+ self._worker(slots[wid], jobs[wid::k], leftover, q_lock,
95
+ cmd_factory, stop, out, out_lock, spec)
89
96
  )
90
97
  for wid in range(k)
91
98
  ]
92
99
  await asyncio.gather(*workers)
100
+ # 收尾补页:所有 worker 都退出后 leftover 里可能还剩页(连接全坏时会
101
+ # 发生)。再借一条**新连接**顺序把它们补完,最多两轮——否则 skip 的页
102
+ # 就变成静默缺数据(strict=False 时最危险:不报错、只是少几页)。
103
+ rounds = 0
104
+ while leftover and not stop.is_set() and rounds < 2:
105
+ rounds += 1
106
+ try:
107
+ pc = await self.pool.acquire(timeout=5.0)
108
+ except PoolTimeoutError:
109
+ break
110
+ slot = _Slot(pc)
111
+ progressed = False
112
+ try:
113
+ while leftover and not stop.is_set():
114
+ start, count = leftover[0] # 成功后才出队,失败可重试
115
+ items, ok = await self._fetch_one(
116
+ slot, cmd_factory(start, count), count)
117
+ if not ok:
118
+ break
119
+ leftover.popleft()
120
+ progressed = True
121
+ async with out_lock:
122
+ out.append(PageResult(start=start, count=count, items=items))
123
+ if spec.stop_when_short and len(items) < count:
124
+ stop.set()
125
+ finally:
126
+ if slot.pc is not None:
127
+ await self.pool.release(slot.pc)
128
+ if not progressed:
129
+ break
130
+ if leftover:
131
+ log.warning("分页调度:%d 页最终未取到(strict=False 留空)", len(leftover))
93
132
  finally:
94
133
  for s in slots:
95
134
  if s.pc is not None:
@@ -117,21 +156,40 @@ class Paginator:
117
156
  return jobs
118
157
 
119
158
  async def _worker(
120
- self, slot: _Slot, jobs: list[tuple[int, int]],
159
+ self, slot: _Slot,
160
+ jobs: list[tuple[int, int]],
161
+ leftover: "deque[tuple[int, int]]",
162
+ q_lock: asyncio.Lock,
121
163
  cmd_factory: Callable[[int, int], Any], stop: asyncio.Event,
122
164
  out: list[PageResult], out_lock: asyncio.Lock, spec: PageSpec,
123
165
  ) -> None:
124
- for start, count in jobs:
125
- if stop.is_set() or slot.pc is None:
126
- return
127
- items, ok = await self._fetch_one(slot, cmd_factory(start, count), count)
128
- if not ok:
129
- return # 换连接失败 → 本 worker 退出(该页留空)
130
- async with out_lock:
131
- out.append(PageResult(start=start, count=count, items=items))
132
- if spec.stop_when_short and len(items) < count:
133
- stop.set()
134
- return
166
+ i = 0
167
+ try:
168
+ while True:
169
+ if i < len(jobs):
170
+ start, count = jobs[i]
171
+ i += 1
172
+ else:
173
+ # 自己的份额做完了 → 看看有没有别人掉下的活
174
+ async with q_lock:
175
+ if stop.is_set() or not leftover:
176
+ return
177
+ start, count = leftover.popleft()
178
+ if slot.pc is None or stop.is_set():
179
+ return
180
+ items, ok = await self._fetch_one(slot, cmd_factory(start, count), count)
181
+ if not ok:
182
+ return # 换连接失败 → 本 worker 退出(剩余页在 finally 里交还)
183
+ async with out_lock:
184
+ out.append(PageResult(start=start, count=count, items=items))
185
+ if spec.stop_when_short and len(items) < count:
186
+ stop.set()
187
+ return
188
+ finally:
189
+ rest = jobs[i:]
190
+ if rest:
191
+ async with q_lock:
192
+ leftover.extendleft(reversed(rest))
135
193
 
136
194
  async def _fetch_one(self, slot: _Slot, cmd, page_size: int):
137
195
  """单页拉取,失败换连接重试。
File without changes
File without changes