fix: 分块读取失败时重试,超时或结果过大就继续拆开
This commit is contained in:
+164
-39
@@ -49,6 +49,22 @@ class NqiAuthError(NqiError):
|
||||
pass
|
||||
|
||||
|
||||
class TileReadError(NqiError):
|
||||
"""分块读取失败,调用方决定重试、拆分或记入失败块。"""
|
||||
|
||||
def __init__(self, message: str, kind: str) -> None:
|
||||
super().__init__(message)
|
||||
self.kind = kind
|
||||
|
||||
|
||||
# 每块最多重试 3 次,依次等待这些秒数。GRID20 从 0.02° 起拆,GRID50 从 0.05° 起拆。
|
||||
TILE_RETRY_WAITS = (1, 3, 9)
|
||||
MIN_TILE_WIDTH = 0.005
|
||||
MAX_TILE_DEPTH = 8
|
||||
# 没有 numberMatched 时,单块条数达到这个值就继续拆,避免服务端截断后悄悄少读。
|
||||
TILE_SPLIT_AT = 10000
|
||||
|
||||
|
||||
def rsa_encrypt(public_key_b64: str, text: str) -> str:
|
||||
der = base64.b64decode(public_key_b64)
|
||||
key = serialization.load_der_public_key(der)
|
||||
@@ -422,7 +438,7 @@ class NqiClient:
|
||||
params = {
|
||||
"maxFeatures": "5",
|
||||
"SERVICE": "Wfs",
|
||||
"VERSION": "",
|
||||
"VERSION": "2.0.0",
|
||||
"REQUEST": "Getfeature",
|
||||
"outputFormat": "application/json",
|
||||
"SRS": "EPSG:4326",
|
||||
@@ -431,13 +447,12 @@ class NqiClient:
|
||||
"sig": wfs_sig(service_code),
|
||||
"CQL_FILTER": f"{id_field}={grid_id}",
|
||||
}
|
||||
response = await self.client.get(
|
||||
response = await self._request(
|
||||
"GET",
|
||||
f"{GIS_PROD}/api/{service_code}/wfs",
|
||||
params=params,
|
||||
headers={"Referer": f"{ORIGIN}/pro-problem-warehouse-web/"},
|
||||
)
|
||||
if response.status_code in {401, 403}:
|
||||
raise NqiError("登录已失效,请重新登录")
|
||||
if response.status_code != 200:
|
||||
raise NqiError(f"栅格查询失败({response.status_code})")
|
||||
text = response.text.lstrip()
|
||||
@@ -460,18 +475,46 @@ class NqiClient:
|
||||
progress,
|
||||
skip: set[str] | None = None,
|
||||
run_event: asyncio.Event | None = None,
|
||||
*,
|
||||
grid_size: str = "GRID20",
|
||||
failed_tiles: list | None = None,
|
||||
seen: set[int] | None = None,
|
||||
tiles: list | None = None,
|
||||
) -> AsyncIterator[str]:
|
||||
"""按图层范围分块产出编号。一块返回就交出,不等整层读完。"""
|
||||
bounds = await self._layer_bounds(service_code)
|
||||
seen: set[str] = set(skip or ())
|
||||
pending: deque[tuple[tuple[float, float, float, float], int]] = deque(
|
||||
(tile, 0) for tile in _tiles(*bounds, 0.05)
|
||||
)
|
||||
if seen is None:
|
||||
seen = set()
|
||||
for item in skip or ():
|
||||
if str(item).isdigit():
|
||||
seen.add(int(item))
|
||||
if tiles is None:
|
||||
bounds = await self._layer_bounds(service_code)
|
||||
step = 0.05 if grid_size == "GRID50" else 0.02
|
||||
pending: deque[tuple[tuple[float, float, float, float], int]] = deque(
|
||||
(tile, 0) for tile in _tiles(*bounds, step)
|
||||
)
|
||||
else:
|
||||
pending = deque((tuple(tile), 0) for tile in tiles)
|
||||
inflight: set[asyncio.Task] = set()
|
||||
|
||||
async def fetch(tile: tuple[float, float, float, float], depth: int):
|
||||
features, matched = await self._tile_features(service_code, id_field, tile)
|
||||
return tile, depth, features, matched
|
||||
width = tile[2] - tile[0]
|
||||
for attempt in range(len(TILE_RETRY_WAITS) + 1):
|
||||
try:
|
||||
features, matched = await self._tile_features(service_code, id_field, tile)
|
||||
return "ok", tile, depth, features, matched
|
||||
except NqiAuthError:
|
||||
raise
|
||||
except TileReadError as exc:
|
||||
if exc.kind == "timeout" and _can_split(width, depth):
|
||||
return "split", tile, depth, [], None
|
||||
if attempt >= len(TILE_RETRY_WAITS):
|
||||
return "fail", tile, depth, [], None
|
||||
if not await _interruptible_sleep(TILE_RETRY_WAITS[attempt], cancel_event, run_event):
|
||||
return "stop", tile, depth, [], None
|
||||
except NqiError:
|
||||
return "fail", tile, depth, [], None
|
||||
return "fail", tile, depth, [], None
|
||||
|
||||
try:
|
||||
await progress(len(seen))
|
||||
@@ -492,16 +535,34 @@ class NqiClient:
|
||||
continue
|
||||
fresh: list[str] = []
|
||||
for task in done:
|
||||
tile, depth, features, matched = task.result()
|
||||
try:
|
||||
kind, tile, depth, features, matched = task.result()
|
||||
except NqiAuthError:
|
||||
raise
|
||||
width = tile[2] - tile[0]
|
||||
if matched > len(features) and width > 0.02 and depth < 5:
|
||||
if kind == "stop":
|
||||
continue
|
||||
if kind == "fail":
|
||||
if failed_tiles is not None:
|
||||
failed_tiles.append([tile[0], tile[1], tile[2], tile[3]])
|
||||
continue
|
||||
if kind == "split" or _should_split(features, matched, width, depth):
|
||||
pending.extend((child, depth + 1) for child in _split_tile(tile))
|
||||
continue
|
||||
matched_count = _matched_count(matched)
|
||||
truncated = (matched_count is not None and matched_count > len(features)) or (
|
||||
matched_count is None and len(features) >= TILE_SPLIT_AT
|
||||
)
|
||||
if truncated and failed_tiles is not None:
|
||||
failed_tiles.append([tile[0], tile[1], tile[2], tile[3]])
|
||||
for feature in features:
|
||||
grid_id = normalize_id((feature.get("properties") or {}).get(id_field))
|
||||
if not grid_id or grid_id in seen:
|
||||
if not grid_id:
|
||||
continue
|
||||
seen.add(grid_id)
|
||||
number = int(grid_id)
|
||||
if number in seen:
|
||||
continue
|
||||
seen.add(number)
|
||||
fresh.append(grid_id)
|
||||
await progress(len(seen))
|
||||
for grid_id in fresh:
|
||||
@@ -517,9 +578,16 @@ class NqiClient:
|
||||
await asyncio.gather(*inflight, return_exceptions=True)
|
||||
|
||||
async def _layer_bounds(self, service_code: str) -> tuple[float, float, float, float]:
|
||||
response = await self.client.get(
|
||||
response = await self._request(
|
||||
"GET",
|
||||
f"{GIS_PROD}/api/{service_code}/wfs",
|
||||
params={"SERVICE": "Wfs", "REQUEST": "GetCapabilities", "ak": APP_KEY, "sig": wfs_sig(service_code)},
|
||||
params={
|
||||
"SERVICE": "Wfs",
|
||||
"VERSION": "2.0.0",
|
||||
"REQUEST": "GetCapabilities",
|
||||
"ak": APP_KEY,
|
||||
"sig": wfs_sig(service_code),
|
||||
},
|
||||
headers={"Referer": f"{ORIGIN}/pro-problem-warehouse-web/"},
|
||||
)
|
||||
if response.status_code != 200:
|
||||
@@ -534,31 +602,51 @@ class NqiClient:
|
||||
west, south, east, north = (float(item) for item in match.groups())
|
||||
return west, south, east, north
|
||||
|
||||
async def _tile_features(self, service_code: str, id_field: str, tile: tuple[float, float, float, float]) -> tuple[list[dict], int]:
|
||||
async def _tile_features(self, service_code: str, id_field: str, tile: tuple[float, float, float, float]) -> tuple[list[dict], int | None]:
|
||||
west, south, east, north = tile
|
||||
ring = f"{west} {south},{east} {south},{east} {north},{west} {north},{west} {south}"
|
||||
response = await self.client.get(
|
||||
f"{GIS_PROD}/api/{service_code}/wfs",
|
||||
params={
|
||||
"SERVICE": "Wfs",
|
||||
"REQUEST": "Getfeature",
|
||||
"outputFormat": "application/json",
|
||||
"SRS": "EPSG:4326",
|
||||
"ak": APP_KEY,
|
||||
"sig": wfs_sig(service_code),
|
||||
"propertyName": id_field,
|
||||
"CQL_FILTER": f"INTERSECTS(the_geom,SRID=4326;POLYGON(({ring})))",
|
||||
},
|
||||
headers={"Referer": f"{ORIGIN}/pro-problem-warehouse-web/"},
|
||||
timeout=httpx.Timeout(40.0, connect=10.0),
|
||||
)
|
||||
if response.status_code != 200 or not response.text.lstrip().startswith("{"):
|
||||
try:
|
||||
response = await self._request(
|
||||
"GET",
|
||||
f"{GIS_PROD}/api/{service_code}/wfs",
|
||||
params={
|
||||
"SERVICE": "Wfs",
|
||||
"VERSION": "2.0.0",
|
||||
"REQUEST": "Getfeature",
|
||||
"outputFormat": "application/json",
|
||||
"SRS": "EPSG:4326",
|
||||
"ak": APP_KEY,
|
||||
"sig": wfs_sig(service_code),
|
||||
"propertyName": id_field,
|
||||
"CQL_FILTER": f"INTERSECTS(the_geom,SRID=4326;POLYGON(({ring})))",
|
||||
},
|
||||
headers={"Referer": f"{ORIGIN}/pro-problem-warehouse-web/"},
|
||||
timeout=httpx.Timeout(40.0, connect=10.0),
|
||||
)
|
||||
except NqiAuthError:
|
||||
raise
|
||||
except NqiError as exc:
|
||||
text = str(exc)
|
||||
if "超时" in text:
|
||||
raise TileReadError(text, "timeout") from exc
|
||||
if "连接失败" in text:
|
||||
raise TileReadError(text, "connect") from exc
|
||||
raise
|
||||
if response.status_code >= 500:
|
||||
raise TileReadError("平台暂时不可用,请稍后重试", "server")
|
||||
if response.status_code != 200:
|
||||
raise NqiError("读取地市栅格失败")
|
||||
payload = response.json()
|
||||
features = list(payload.get("features") or [])
|
||||
matched = payload.get("numberMatched")
|
||||
total = int(matched) if isinstance(matched, int) else len(features)
|
||||
return features, total
|
||||
text = response.text.lstrip()
|
||||
if not text.startswith("{"):
|
||||
raise TileReadError("读取地市栅格失败", "json")
|
||||
try:
|
||||
payload = response.json()
|
||||
except json.JSONDecodeError as exc:
|
||||
raise TileReadError("读取地市栅格失败", "json") from exc
|
||||
features = payload.get("features")
|
||||
if not isinstance(features, list):
|
||||
raise TileReadError("读取地市栅格失败", "json")
|
||||
return features, _matched_count(payload.get("numberMatched"))
|
||||
|
||||
async def cell_rows(self, service_code: str, grid_id: str, network: str) -> list[dict]:
|
||||
body = {
|
||||
@@ -614,6 +702,43 @@ class NqiClient:
|
||||
return _api_payload(response)
|
||||
|
||||
|
||||
def _can_split(width: float, depth: int) -> bool:
|
||||
return width > MIN_TILE_WIDTH + 1e-9 and depth < MAX_TILE_DEPTH
|
||||
|
||||
|
||||
def _matched_count(matched) -> int | None:
|
||||
if isinstance(matched, bool) or matched is None:
|
||||
return None
|
||||
if isinstance(matched, int):
|
||||
return matched
|
||||
if isinstance(matched, float):
|
||||
return int(matched)
|
||||
if isinstance(matched, str) and matched.strip().isdigit():
|
||||
return int(matched.strip())
|
||||
return None
|
||||
|
||||
|
||||
def _should_split(features: list, matched, width: float, depth: int) -> bool:
|
||||
if not _can_split(width, depth):
|
||||
return False
|
||||
count = _matched_count(matched)
|
||||
if count is None:
|
||||
return len(features) >= TILE_SPLIT_AT
|
||||
return count > len(features)
|
||||
|
||||
|
||||
async def _interruptible_sleep(seconds: float, cancel_event: asyncio.Event, run_event: asyncio.Event | None) -> bool:
|
||||
"""重试等待可被暂停或停止打断。返回 False 表示任务已停止。"""
|
||||
left = seconds
|
||||
while left > 0:
|
||||
if not await _wait_turn(cancel_event, run_event):
|
||||
return False
|
||||
step = min(0.2, left)
|
||||
await asyncio.sleep(step)
|
||||
left -= step
|
||||
return not cancel_event.is_set()
|
||||
|
||||
|
||||
async def _wait_turn(cancel_event: asyncio.Event, run_event: asyncio.Event | None) -> bool:
|
||||
"""暂停时停住。返回 False 表示任务已停止。"""
|
||||
if run_event is None:
|
||||
|
||||
Reference in New Issue
Block a user