feat: 完善登录保持、栅格下载和任务调度

This commit is contained in:
2026-10-25 05:42:24 +08:00
parent dab26ff4ee
commit 4cf64957c5
25 changed files with 1871 additions and 320 deletions
+437 -17
View File
@@ -1,18 +1,23 @@
import asyncio
import csv
import hashlib
import io
import threading
from datetime import datetime
from pathlib import Path
from openpyxl import Workbook
from app.features.download.fields import columns_for
from app.features.download.ids import parse_table, parse_upload
from app.features.download import jobs as job_module
from app.features.download.jobs import DownloadJob, JobManager, _pump
from app.features.download.journal import CsvJournal
from app.platform.constants import APP_SECRET
from app.features.download.rows import build_rows
from app.platform.sign import build_sign, wfs_sig
from app.platform.client import month_end, rsa_encrypt
from app.platform.client import NqiClient, NqiError, login_page_url, month_end, rsa_encrypt, sms_notice
from app.platform import sessions
from app.platform.keepalive import refresh_saved_session
from app.shared.state import state
PUBLIC_KEY = (
"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCwjDm1HXDw8QH5ZtGMQIl2h/I8E+"
@@ -38,6 +43,35 @@ def test_month_end():
assert month_end("2026-02") == "20260228"
def test_login_page_keeps_service_query():
assert login_page_url("https://nqi.gmcc.net:20443/cas/login") == (
"https://nqi.gmcc.net:20443/cas/login?service=https%3A%2F%2Fnqi.gmcc.net%3A20443%2Fpro-portal%2F"
)
kept = "https://nqi.gmcc.net:20443/cas/login?service=https%3A%2F%2Fnqi.gmcc.net%3A20443%2Fpro-portal%2F"
assert login_page_url(kept) == kept
def test_saved_login_replaces_same_account(tmp_path: Path, monkeypatch):
monkeypatch.setattr(sessions, "STORE", tmp_path / "sessions.json")
user = {"loginId": "a", "userName": "甲", "cityName": "江门", "orgName": ""}
sessions.remember(user, [{"name": "TGC", "value": "old", "domain": "", "path": "/"}])
sessions.remember(
{"loginId": "b", "userName": "乙", "cityName": "广州", "orgName": ""},
[{"name": "TGC", "value": "b", "domain": "", "path": "/"}],
)
sessions.remember(user, [{"name": "TGC", "value": "new", "domain": "", "path": "/"}])
stored = sessions._read()
assert [item["loginId"] for item in stored] == ["a", "b"]
assert stored[0]["cookies"][0]["value"] == "new"
sessions.forget("b")
assert [item["loginId"] for item in sessions._read()] == ["a"]
def test_sms_notice_reads_accepted_message():
payload = {"msg": "success", "data": '{"Content":"短信发送已受理。","Code":"0000"}', "success": True}
assert sms_notice(payload) == "短信发送已受理。"
def test_rsa_block_size():
encrypted = rsa_encrypt(PUBLIC_KEY, "demo")
assert len(encrypted) == 172
@@ -85,23 +119,29 @@ def test_missing_grid_still_writes_requested_id():
assert rows[0][labels.index("小区ID")] == ""
def test_parse_ids_from_header_and_duplicates():
rows = parse_table([["20米栅格ID", "备注"], ["541927061", "a"], ["541927061", "b"], ["12", "c"], ["", ""]])
def test_fifty_meter_column_name():
labels = [column.label for column in columns_for("NR", ["rsrp"], "GRID50")]
assert "50米栅格ID" in labels
assert "20米栅格ID" not in labels
rows, duplicates = parse_table(
[["20米栅格ID", "备注"], ["541927061", "a"], ["541927061", "b"], [" 12 ", "c"], ["12", "d"], ["", ""]]
)
assert rows == ["541927061", "12"]
assert duplicates == 2
def test_parse_plain_lines_and_xlsx(tmp_path: Path):
text = tmp_path / "ids.txt"
text.write_text("541927061\n544536471\n", encoding="utf-8")
assert parse_upload(text) == ["541927061", "544536471"]
book = Workbook()
sheet = book.active
sheet.append(["栅格ID"])
sheet.append([544536471])
path = tmp_path / "ids.xlsx"
book.save(path)
book.close()
assert parse_upload(path) == ["544536471"]
def test_parse_csv_upload(tmp_path: Path):
path = tmp_path / "ids.csv"
path.write_bytes("20米栅格ID\n541927061\n544536471\n541927061\n".encode("utf-8-sig"))
assert parse_upload(path) == (["541927061", "544536471"], 1)
other = tmp_path / "ids.txt"
other.write_text("541927061\n", encoding="utf-8")
try:
parse_upload(other)
except ValueError as exc:
assert "CSV" in str(exc)
else:
raise AssertionError("txt 不应被接受")
def test_journal_discards_uncommitted_tail(tmp_path: Path):
@@ -142,3 +182,383 @@ def test_journal_writes_do_not_interleave(tmp_path: Path):
assert len(rows) == 41
assert all(len(row) == 3 for row in rows)
assert {row[0] for row in rows[1:]} == {"甲", "乙"}
def test_grid_ids_yield_before_the_scan_finishes():
asyncio.run(_grid_ids_yield_before_the_scan_finishes())
async def _grid_ids_yield_before_the_scan_finishes():
client = NqiClient()
release = asyncio.Event()
seen_tiles: list[float] = []
async def bounds(_self, _service_code):
return (0.0, 0.0, 0.1, 0.05)
async def tile(_self, _service_code, _id_field, area):
seen_tiles.append(area[0])
if area[0] >= 0.01:
await release.wait()
grid_id = "1" if area[0] < 0.01 else "2"
return [{"properties": {"grid20_id": grid_id}}], 1
client._layer_bounds = bounds.__get__(client, NqiClient)
client._tile_features = tile.__get__(client, NqiClient)
async def progress(_count: int) -> None:
return None
agen = client.iter_grid_ids("svc", "grid20_id", asyncio.Event(), progress)
try:
first = await agen.__anext__()
assert first == "1"
assert not release.is_set()
release.set()
second = await agen.__anext__()
assert second == "2"
finally:
await agen.aclose()
await client.aclose()
def test_grid_ids_skip_edges_already_seen():
asyncio.run(_grid_ids_skip_edges_already_seen())
async def _grid_ids_skip_edges_already_seen():
client = NqiClient()
async def bounds(_self, _service_code):
return (0.0, 0.0, 0.1, 0.05)
async def tile(_self, _service_code, _id_field, area):
grid_id = "7" if area[0] < 0.01 else "8"
return [{"properties": {"grid20_id": grid_id}}, {"properties": {"grid20_id": "7"}}], 2
client._layer_bounds = bounds.__get__(client, NqiClient)
client._tile_features = tile.__get__(client, NqiClient)
found: list[str] = []
async for grid_id in client.iter_grid_ids("svc", "grid20_id", asyncio.Event(), _noop, {"7"}):
found.append(grid_id)
await client.aclose()
assert found == ["8"]
async def _noop(_count: int) -> None:
return None
def test_download_starts_before_remaining_ids_arrive(tmp_path: Path):
asyncio.run(_download_starts_before_remaining_ids_arrive(tmp_path))
async def _download_starts_before_remaining_ids_arrive(tmp_path: Path):
started = asyncio.Event()
order: list[str] = []
class Fake:
async def grid_feature(self, _service_code, grid_id, _id_field):
order.append(grid_id)
if grid_id == "1":
started.set()
return {"grid20_id": grid_id}
async def cell_rows(self, _service_code, _grid_id, _network):
return []
async def source():
yield "1"
await started.wait()
order.append("rest")
yield "2"
job = DownloadJob(
id="a" * 32,
directory=tmp_path,
network="NR",
city_code="JM",
city_name="江门",
month="2026-09",
groups=["rsrp"],
concurrency=2,
grid_ids=["1", "2"],
csv_path=tmp_path / "out.csv",
created_at="",
)
columns = columns_for("NR", ["rsrp"])
journal = CsvJournal(job.csv_path, tmp_path / "progress.jsonl", [column.label for column in columns])
journal.open()
await _pump(job, Fake(), journal, columns, "svc", source())
journal.close()
assert order.index("1") < order.index("rest")
assert job.completed == 2
assert job.status == "done"
def test_touch_session_visits_portal_and_layer():
asyncio.run(_touch_session_visits_portal_and_layer())
async def _touch_session_visits_portal_and_layer():
client = NqiClient()
calls: list[tuple[str, str]] = []
class Response:
def __init__(self, payload: dict, status_code: int = 200):
self.status_code = status_code
self._payload = payload
self.headers = {"content-type": "application/json"}
def json(self):
return self._payload
async def get(url, headers=None, params=None, **_kwargs):
calls.append(("GET", str(url)))
if "roleCityMapping" in str(url):
return Response({"code": 0, "data": []})
if "getOnLineCount" in str(url):
return Response({"count": 1})
return Response({"loginId": "a", "userName": "甲", "cityName": "江门", "orgName": "江门", "roleId": "r1"})
async def post(url, json=None, headers=None, **_kwargs):
calls.append(("POST", str(url)))
return Response({})
client.client.get = get
client.client.post = post
try:
user = await client.touch_session()
finally:
await client.aclose()
assert user["loginId"] == "a"
assert user["userName"] == "甲"
joined = " ".join(url for _method, url in calls)
assert "getCasUser" in joined
assert "checkUserPasswordUpdated" in joined
assert "getOnLineCount" in joined
assert "roleCityMapping/cities" in joined
def test_touch_session_rejects_expired_login():
try:
asyncio.run(_touch_session_rejects_expired_login())
except NqiError as exc:
assert "失效" in str(exc)
else:
raise AssertionError("失效登录应被拒绝")
async def _touch_session_rejects_expired_login():
client = NqiClient()
class Response:
status_code = 200
headers = {"content-type": "application/json"}
def json(self):
return {"loginId": "a", "userName": "甲"}
class Denied:
status_code = 401
headers = {"content-type": "application/json"}
def json(self):
return {}
async def get(url, headers=None, params=None, **_kwargs):
return Response()
async def post(url, json=None, headers=None, **_kwargs):
return Denied()
client.client.get = get
client.client.post = post
try:
await client.touch_session()
finally:
await client.aclose()
def test_refresh_saved_session_rewrites_cookie(tmp_path: Path, monkeypatch):
monkeypatch.setattr(sessions, "STORE", tmp_path / "sessions.json")
class Fake:
async def touch_session(self):
return {"loginId": "a", "userName": "甲", "cityName": "江门", "orgName": ""}
def export_cookies(self):
return [{"name": "TGC", "value": "kept", "domain": "", "path": "/"}]
state.client = Fake()
state.user = {"loginId": "a", "userName": "旧", "cityName": "", "orgName": ""}
try:
asyncio.run(refresh_saved_session())
assert state.user["userName"] == "甲"
stored = sessions._read()
finally:
state.client = None
state.user = None
assert stored[0]["cookies"][0]["value"] == "kept"
def test_task_folder_uses_second_timestamp(tmp_path: Path, monkeypatch):
monkeypatch.setattr(job_module, "DATA_DIR", tmp_path / "jobs")
class Clock:
@staticmethod
def now():
return datetime(2026, 9, 21, 12, 0, 9)
monkeypatch.setattr(job_module, "datetime", Clock)
manager = JobManager()
output = tmp_path / "save" / "栅格.csv"
first = _make_job(manager, output)
assert first.id == "20260921120009"
assert first.directory == tmp_path / "jobs" / "20260921120009"
assert first.csv_path == tmp_path / "save" / "20260921120009" / "栅格.csv"
second = _make_job(manager, output)
assert second.id == "20260921120009_2"
assert second.directory != first.directory
def test_only_the_task_limit_runs(tmp_path: Path, monkeypatch):
monkeypatch.setattr(job_module, "DATA_DIR", tmp_path / "jobs")
manager = JobManager()
manager.max_concurrent = 1
first = _make_job(manager, None)
second = _make_job(manager, None)
assert manager.place(first) == "run"
assert manager.place(second) == "wait"
assert second.status == "queued"
assert second.message == "等待中"
manager.request_stop(second)
assert second.status == "cancelled"
assert second.message == "已取消"
class Alive:
def done(self):
return False
first.task = Alive()
manager.pause(first)
assert first.status == "paused"
assert manager.running_count() == 0
third = _make_job(manager, None)
assert manager.place(third) == "run"
assert manager.place(first) == "wait"
manager.jobs.clear()
manager.hydrate()
assert first.id in manager.jobs
assert manager.jobs[first.id].status == "queued"
assert third.id not in manager.jobs
def test_reader_stays_idle_while_paused():
asyncio.run(_reader_stays_idle_while_paused())
async def _reader_stays_idle_while_paused():
client = NqiClient()
run = asyncio.Event()
reached = asyncio.Event()
started: list[float] = []
async def bounds(_self, _service_code):
reached.set()
return (0.0, 0.0, 0.05, 0.05)
async def tile(_self, _service_code, _id_field, area):
started.append(area[0])
return [{"properties": {"grid20_id": "5"}}], 1
client._layer_bounds = bounds.__get__(client, NqiClient)
client._tile_features = tile.__get__(client, NqiClient)
agen = client.iter_grid_ids("svc", "grid20_id", asyncio.Event(), _noop, None, run)
nxt = asyncio.create_task(agen.__anext__())
try:
await asyncio.wait_for(reached.wait(), 1)
await asyncio.sleep(0.05)
assert started == []
assert not nxt.done()
run.set()
assert await nxt == "5"
assert started
finally:
run.set()
nxt.cancel()
await agen.aclose()
await client.aclose()
def test_pause_holds_the_next_grid(tmp_path: Path):
asyncio.run(_pause_holds_the_next_grid(tmp_path))
async def _pause_holds_the_next_grid(tmp_path: Path):
seen: list[str] = []
job = DownloadJob(
id="20260921120009",
directory=tmp_path,
network="NR",
city_code="JM",
city_name="江门",
month="2026-09",
groups=["rsrp"],
concurrency=1,
grid_ids=["1", "2"],
csv_path=tmp_path / "out.csv",
created_at="",
)
class Fake:
async def grid_feature(self, _service_code, grid_id, _id_field):
seen.append(grid_id)
if grid_id == "1":
job.run_event.clear()
job.status = "paused"
return {"grid20_id": grid_id}
async def cell_rows(self, _service_code, _grid_id, _network):
return []
async def source():
yield "1"
yield "2"
async def watch():
try:
for _ in range(50):
if seen == ["1"]:
break
await asyncio.sleep(0.01)
else:
raise AssertionError("下载没有在第一格停下")
await asyncio.sleep(0.15)
assert seen == ["1"]
finally:
job.run_event.set()
columns = columns_for("NR", ["rsrp"])
journal = CsvJournal(job.csv_path, tmp_path / "progress.jsonl", [column.label for column in columns])
journal.open()
await asyncio.gather(_pump(job, Fake(), journal, columns, "svc", source()), watch())
journal.close()
assert seen == ["1", "2"]
assert job.status == "done"
def _make_job(manager: JobManager, output: Path | None) -> DownloadJob:
return manager.create(
network="NR",
city_code="JM",
city_name="江门",
month="2026-09",
groups=["rsrp"],
concurrency=4,
grid_ids=["1"],
csv_path=output,
grid_size="GRID20",
whole_city=output is None,
)