feat: 管理后台可动态调整采集和导出的并行数量
This commit is contained in:
+1
-1
@@ -29,7 +29,7 @@ Vue 3、TypeScript、Naive UI。Node.js 只用于安装依赖、本地开发和
|
||||
## Capabilities and Constraints
|
||||
|
||||
- 用户功能:提交任务,取得结果文件。多个任务可以并行,也可以排队。
|
||||
- 管理功能:选择登录方式,管理用户,管理大数据平台账号池,设置凭证刷新间隔,手动添加账号。
|
||||
- 管理功能:选择登录方式,管理用户,管理大数据平台账号池,设置凭证刷新间隔和并行数量,手动添加账号。并行数量范围是 1 到 32,采集和导出共用。调大后马上多领任务。调小后不中断正在运行的任务,等它们结束后再降到新的数量。
|
||||
- 登录方式只启用一种。大数据平台账号登录成功后进入账号池。自有账号由管理员添加,不能自行注册,不发送手机验证码。
|
||||
- 平台登录使用 JWT。账号池另行保存大数据平台凭证。退出只清除平台登录,不删除账号池中的账号。退出后再次登录需要重新发送手机验证码,成功后账号池改用新凭证。
|
||||
- 账号池凭证默认每 5 分钟刷新一次。采集从账号池选择凭证仍然有效的账号。
|
||||
|
||||
@@ -28,4 +28,4 @@ cd backend
|
||||
docker compose up -d --build
|
||||
```
|
||||
|
||||
启动前设置 `POSTGRES_PASSWORD`。首次打开网页完成安装,数据库主机使用 `postgres`。排队进程负责采集和导出,不能关掉。
|
||||
启动前设置 `POSTGRES_PASSWORD`。首次打开网页完成安装,数据库主机使用 `postgres`。排队进程负责采集和导出。管理后台可以修改并行数量,范围是 1 到 32。
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
"""管理后台可以调整采集和导出共用的并行数量。"""
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
revision = "0004_worker_concurrency"
|
||||
down_revision = "0003_drop_inline_worker"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.add_column("app_setting", sa.Column("worker_concurrency", sa.Integer(), nullable=False, server_default="4"))
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_column("app_setting", "worker_concurrency")
|
||||
+17
-4
@@ -16,7 +16,7 @@ from app.models import AppSetting, CollectionSource, ExportTask, NqiAccount, Use
|
||||
from app.nqi.client import NqiAuthError, NqiClient, NqiError
|
||||
from app.nqi.flows import drop, purge, remember, take
|
||||
from app.security import hash_password, issue_token, verify_password
|
||||
from app.tasks.runner import check_period, check_refresh, enqueue_export
|
||||
from app.tasks.runner import check_concurrency, check_period, check_refresh, enqueue_export
|
||||
|
||||
router = APIRouter(prefix="/api")
|
||||
|
||||
@@ -50,7 +50,7 @@ def _bad(message: str, status: int = 400) -> HTTPException:
|
||||
def _setting(session: Session) -> AppSetting:
|
||||
setting = session.get(AppSetting, 1)
|
||||
if setting is None:
|
||||
setting = AppSetting(id=1, login_mode="local", credential_refresh_seconds=300)
|
||||
setting = AppSetting(id=1, login_mode="local", credential_refresh_seconds=300, worker_concurrency=4)
|
||||
session.add(setting)
|
||||
session.flush()
|
||||
return setting
|
||||
@@ -280,7 +280,11 @@ def download_task(task_id: int, actor: Actor = Depends(current_actor), session:
|
||||
def admin_settings(actor: Actor = Depends(current_actor), session: Session = Depends(get_session)) -> dict:
|
||||
require_admin(actor)
|
||||
setting = _setting(session)
|
||||
return {"loginMode": setting.login_mode, "credentialRefreshSeconds": setting.credential_refresh_seconds}
|
||||
return {
|
||||
"loginMode": setting.login_mode,
|
||||
"credentialRefreshSeconds": setting.credential_refresh_seconds,
|
||||
"workerConcurrency": setting.worker_concurrency,
|
||||
}
|
||||
|
||||
|
||||
@router.put("/admin/settings")
|
||||
@@ -297,8 +301,17 @@ def update_settings(body: dict, actor: Actor = Depends(current_actor), session:
|
||||
setting.credential_refresh_seconds = check_refresh(int(body.get("credentialRefreshSeconds")))
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise _bad(str(exc)) from exc
|
||||
if "workerConcurrency" in body:
|
||||
try:
|
||||
setting.worker_concurrency = check_concurrency(int(body.get("workerConcurrency")))
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise _bad(str(exc)) from exc
|
||||
setting.login_mode = mode
|
||||
return {"loginMode": setting.login_mode, "credentialRefreshSeconds": setting.credential_refresh_seconds}
|
||||
return {
|
||||
"loginMode": setting.login_mode,
|
||||
"credentialRefreshSeconds": setting.credential_refresh_seconds,
|
||||
"workerConcurrency": setting.worker_concurrency,
|
||||
}
|
||||
|
||||
|
||||
@router.get("/admin/users")
|
||||
|
||||
@@ -94,6 +94,7 @@ def perform_install(body: dict) -> None:
|
||||
id=1,
|
||||
login_mode="local",
|
||||
credential_refresh_seconds=300,
|
||||
worker_concurrency=4,
|
||||
db_host=host,
|
||||
db_port=port,
|
||||
db_name=database,
|
||||
|
||||
@@ -20,6 +20,7 @@ class AppSetting(Base):
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||
login_mode: Mapped[str] = mapped_column(String(16), default="local")
|
||||
credential_refresh_seconds: Mapped[int] = mapped_column(Integer, default=300)
|
||||
worker_concurrency: Mapped[int] = mapped_column(Integer, default=4)
|
||||
db_host: Mapped[str] = mapped_column(String(255), default="")
|
||||
db_port: Mapped[int] = mapped_column(Integer, default=5432)
|
||||
db_name: Mapped[str] = mapped_column(String(128), default="")
|
||||
|
||||
+107
-2
@@ -2,10 +2,17 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import contextlib
|
||||
import logging
|
||||
|
||||
import procrastinate
|
||||
from procrastinate.worker import Worker
|
||||
|
||||
from app.config import postgres_conninfo
|
||||
from app.tasks.runner import execute_collection, execute_export
|
||||
from app.tasks.runner import current_concurrency, execute_collection, execute_export
|
||||
|
||||
logger = logging.getLogger("decom")
|
||||
|
||||
conninfo = postgres_conninfo() or "postgresql://invalid"
|
||||
queue = procrastinate.App(connector=procrastinate.PsycopgConnector(conninfo=conninfo))
|
||||
@@ -26,6 +33,97 @@ def defer(name: str, **kwargs) -> None:
|
||||
job.defer(**kwargs)
|
||||
|
||||
|
||||
class DynamicGate:
|
||||
"""正在执行的数量低于目标才允许再领任务。调小目标时不打断已开始的任务。"""
|
||||
|
||||
def __init__(self, limit: int) -> None:
|
||||
self._limit = limit
|
||||
self._held = 0
|
||||
self._waiters: list[asyncio.Event] = []
|
||||
|
||||
@property
|
||||
def limit(self) -> int:
|
||||
return self._limit
|
||||
|
||||
@property
|
||||
def held(self) -> int:
|
||||
return self._held
|
||||
|
||||
def set_limit(self, value: int) -> None:
|
||||
self._limit = value
|
||||
self._wake()
|
||||
|
||||
async def acquire(self) -> None:
|
||||
while True:
|
||||
if self._held < self._limit:
|
||||
self._held += 1
|
||||
return
|
||||
event = asyncio.Event()
|
||||
self._waiters.append(event)
|
||||
await event.wait()
|
||||
|
||||
def release(self) -> None:
|
||||
self._held = max(0, self._held - 1)
|
||||
self._wake()
|
||||
|
||||
def _wake(self) -> None:
|
||||
waiters = self._waiters
|
||||
self._waiters = []
|
||||
for event in waiters:
|
||||
event.set()
|
||||
|
||||
|
||||
class DynamicWorker(Worker):
|
||||
def __init__(self, gate: DynamicGate, **kwargs) -> None:
|
||||
self._gate = gate
|
||||
super().__init__(**kwargs)
|
||||
|
||||
async def _watch_limit(self) -> None:
|
||||
while not self._stop_event.is_set():
|
||||
try:
|
||||
limit = await asyncio.to_thread(current_concurrency)
|
||||
if limit != self._gate.limit:
|
||||
logger.info("并行数量改为 %s", limit)
|
||||
self._gate.set_limit(limit)
|
||||
except Exception as exc:
|
||||
logger.info("读取并行数量未完成: %s", exc)
|
||||
await asyncio.sleep(2)
|
||||
|
||||
async def _run_loop(self) -> None:
|
||||
from procrastinate import signals, utils
|
||||
|
||||
self.logger.info(
|
||||
f"Starting worker on {utils.queues_display(self.queues)}",
|
||||
extra=self._log_extra(action="start_worker", context=None, queues=self.queues, job_result=None),
|
||||
)
|
||||
self._new_job_event.clear()
|
||||
self._running_jobs = {}
|
||||
self._job_semaphore = self._gate
|
||||
watch = asyncio.create_task(self._watch_limit(), name="decom-concurrency")
|
||||
side_tasks = self._start_side_tasks()
|
||||
side_tasks_monitor = asyncio.create_task(self._monitor_side_tasks(side_tasks), name="side_tasks_monitor")
|
||||
context = signals.on_stop(self.stop) if self.install_signal_handlers else contextlib.nullcontext()
|
||||
try:
|
||||
with context:
|
||||
await self._fetch_and_process_jobs()
|
||||
if not self.wait:
|
||||
self._stop_event.set()
|
||||
while not self._stop_event.is_set():
|
||||
await utils.wait_any(
|
||||
self._new_job_event.wait(),
|
||||
asyncio.sleep(self.fetch_job_polling_interval),
|
||||
self._stop_event.wait(),
|
||||
)
|
||||
await self._fetch_and_process_jobs()
|
||||
finally:
|
||||
watch.cancel()
|
||||
with contextlib.suppress(asyncio.CancelledError):
|
||||
await watch
|
||||
if not side_tasks_monitor.done():
|
||||
side_tasks_monitor.cancel()
|
||||
await self._shutdown(side_tasks=side_tasks)
|
||||
|
||||
|
||||
def serve() -> None:
|
||||
import logging
|
||||
|
||||
@@ -35,4 +133,11 @@ def serve() -> None:
|
||||
queue.schema_manager.apply_schema()
|
||||
except Exception as exc:
|
||||
logger.info("队列结构已存在: %s", exc)
|
||||
queue.run_worker(queues=["decom"], concurrency=4)
|
||||
|
||||
async def run() -> None:
|
||||
gate = DynamicGate(current_concurrency())
|
||||
async with queue.open_async():
|
||||
worker = DynamicWorker(app=queue, gate=gate, queues=["decom"])
|
||||
await worker.run()
|
||||
|
||||
asyncio.run(run())
|
||||
|
||||
+54
-30
@@ -1,4 +1,4 @@
|
||||
"""用户任务只读库里已有的数据,再写成表格。采集另走自己的队列。"""
|
||||
"""用户任务只读库里已有的数据,再写成表格。采集和导出共用排队进程的并行数量。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -16,7 +16,9 @@ from app.models import CellData, CollectionSource, ExportTask, NqiAccount, utcno
|
||||
from app.nqi.client import NqiAuthError, NqiClient, NqiError
|
||||
|
||||
logger = logging.getLogger("decom")
|
||||
_pool = threading.Semaphore(4)
|
||||
MIN_CONCURRENCY = 1
|
||||
MAX_CONCURRENCY = 32
|
||||
DEFAULT_CONCURRENCY = 4
|
||||
|
||||
|
||||
def check_period(days: int) -> int:
|
||||
@@ -31,6 +33,29 @@ def check_refresh(seconds: int) -> int:
|
||||
return seconds
|
||||
|
||||
|
||||
def check_concurrency(value: int) -> int:
|
||||
if value < MIN_CONCURRENCY or value > MAX_CONCURRENCY:
|
||||
raise ValueError("并行数量需要在 1 到 32 之间")
|
||||
return value
|
||||
|
||||
|
||||
def current_concurrency() -> int:
|
||||
from app.config import installed
|
||||
|
||||
if not installed():
|
||||
return DEFAULT_CONCURRENCY
|
||||
from app.models import AppSetting
|
||||
|
||||
with session_scope() as session:
|
||||
setting = session.get(AppSetting, 1)
|
||||
if setting is None:
|
||||
return DEFAULT_CONCURRENCY
|
||||
try:
|
||||
return check_concurrency(int(setting.worker_concurrency))
|
||||
except (TypeError, ValueError):
|
||||
return DEFAULT_CONCURRENCY
|
||||
|
||||
|
||||
def upsert_rows(session, source: str, rows: list[dict]) -> int:
|
||||
count = 0
|
||||
for row in rows:
|
||||
@@ -87,37 +112,36 @@ def _optional_time(value) -> datetime | None:
|
||||
|
||||
|
||||
def execute_export(task_id: int) -> None:
|
||||
with _pool:
|
||||
with session_scope() as session:
|
||||
task = session.get(ExportTask, task_id)
|
||||
if task is None or task.status not in {"queued", "running"}:
|
||||
return
|
||||
task.status = "running"
|
||||
params = dict(task.params or {})
|
||||
file_format = task.file_format
|
||||
try:
|
||||
with session_scope() as session:
|
||||
rows = query_cells(session, params)
|
||||
name, content = write_table(file_format, rows)
|
||||
result_dir().mkdir(parents=True, exist_ok=True)
|
||||
path = result_dir() / f"{task_id}-{name}"
|
||||
path.write_bytes(content)
|
||||
with session_scope() as session:
|
||||
task = session.get(ExportTask, task_id)
|
||||
if task is None or task.status not in {"queued", "running"}:
|
||||
if task is None:
|
||||
return
|
||||
task.status = "running"
|
||||
params = dict(task.params or {})
|
||||
file_format = task.file_format
|
||||
try:
|
||||
with session_scope() as session:
|
||||
rows = query_cells(session, params)
|
||||
name, content = write_table(file_format, rows)
|
||||
result_dir().mkdir(parents=True, exist_ok=True)
|
||||
path = result_dir() / f"{task_id}-{name}"
|
||||
path.write_bytes(content)
|
||||
with session_scope() as session:
|
||||
task = session.get(ExportTask, task_id)
|
||||
if task is None:
|
||||
return
|
||||
task.status = "done"
|
||||
task.result_name = path.name
|
||||
task.finished_at = utcnow()
|
||||
except Exception as exc:
|
||||
logger.info("导出失败: %s", exc)
|
||||
with session_scope() as session:
|
||||
task = session.get(ExportTask, task_id)
|
||||
if task is None:
|
||||
return
|
||||
task.status = "failed"
|
||||
task.error = str(exc) or "导出失败"
|
||||
task.finished_at = utcnow()
|
||||
task.status = "done"
|
||||
task.result_name = path.name
|
||||
task.finished_at = utcnow()
|
||||
except Exception as exc:
|
||||
logger.info("导出失败: %s", exc)
|
||||
with session_scope() as session:
|
||||
task = session.get(ExportTask, task_id)
|
||||
if task is None:
|
||||
return
|
||||
task.status = "failed"
|
||||
task.error = str(exc) or "导出失败"
|
||||
task.finished_at = utcnow()
|
||||
|
||||
|
||||
def execute_collection(source_id: int) -> None:
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
import shutil
|
||||
import time
|
||||
@@ -16,7 +17,7 @@ from app.collect.io import parse_csv, write_csv # noqa: E402
|
||||
from app.db import reset_engine # noqa: E402
|
||||
from app.main import create_app # noqa: E402
|
||||
from app.nqi.client import needs_captcha, rsa_encrypt # noqa: E402
|
||||
from app.tasks.runner import check_period # noqa: E402
|
||||
from app.tasks.runner import check_concurrency, check_period # noqa: E402
|
||||
|
||||
PUBLIC_KEY = (
|
||||
"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCwjDm1HXDw8QH5ZtGMQIl2h/I8E+"
|
||||
@@ -92,3 +93,58 @@ def test_local_login_task_and_admin(client: TestClient):
|
||||
downloaded = client.get(f"/api/tasks/{task_id}/file", headers=user_headers)
|
||||
assert downloaded.status_code == 200
|
||||
assert "小区" in downloaded.content.decode("utf-8-sig")
|
||||
|
||||
|
||||
def test_concurrency_bounds():
|
||||
assert check_concurrency(1) == 1
|
||||
assert check_concurrency(32) == 32
|
||||
with pytest.raises(ValueError):
|
||||
check_concurrency(0)
|
||||
with pytest.raises(ValueError):
|
||||
check_concurrency(33)
|
||||
|
||||
|
||||
def test_admin_can_set_concurrency(client: TestClient):
|
||||
logged = client.post("/api/auth/local", json={"username": "admin", "password": "admin-pass"})
|
||||
headers = {"Authorization": f"Bearer {logged.json()['token']}"}
|
||||
current = client.get("/api/admin/settings", headers=headers)
|
||||
assert current.json()["workerConcurrency"] == 4
|
||||
saved = client.put(
|
||||
"/api/admin/settings",
|
||||
json={"loginMode": "local", "credentialRefreshSeconds": 300, "workerConcurrency": 8},
|
||||
headers=headers,
|
||||
)
|
||||
assert saved.status_code == 200
|
||||
assert saved.json()["workerConcurrency"] == 8
|
||||
rejected = client.put(
|
||||
"/api/admin/settings",
|
||||
json={"loginMode": "local", "credentialRefreshSeconds": 300, "workerConcurrency": 0},
|
||||
headers=headers,
|
||||
)
|
||||
assert rejected.status_code == 400
|
||||
|
||||
|
||||
def test_dynamic_gate_shrinks_after_running_tasks_finish():
|
||||
from app.tasks.queue import DynamicGate
|
||||
|
||||
async def scenario() -> None:
|
||||
gate = DynamicGate(1)
|
||||
await gate.acquire()
|
||||
waiting = asyncio.create_task(gate.acquire())
|
||||
await asyncio.sleep(0.05)
|
||||
assert not waiting.done()
|
||||
gate.set_limit(2)
|
||||
await asyncio.wait_for(waiting, timeout=1)
|
||||
assert gate.held == 2
|
||||
gate.set_limit(1)
|
||||
blocked = asyncio.create_task(gate.acquire())
|
||||
await asyncio.sleep(0.05)
|
||||
assert not blocked.done()
|
||||
gate.release()
|
||||
await asyncio.sleep(0.05)
|
||||
assert not blocked.done()
|
||||
gate.release()
|
||||
await asyncio.wait_for(blocked, timeout=1)
|
||||
assert gate.held == 1
|
||||
|
||||
asyncio.run(scenario())
|
||||
|
||||
@@ -9,8 +9,10 @@ from app.runtime import start_background
|
||||
|
||||
def main() -> None:
|
||||
import asyncio
|
||||
import logging
|
||||
import sys
|
||||
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
if sys.platform == "win32":
|
||||
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
|
||||
init_db()
|
||||
|
||||
@@ -6,12 +6,14 @@ import { api } from "../../shared/http";
|
||||
|
||||
const mode = ref("local");
|
||||
const seconds = ref(300);
|
||||
const concurrency = ref(4);
|
||||
const message = ref("");
|
||||
|
||||
async function load() {
|
||||
const result = await api<{ loginMode: string; credentialRefreshSeconds: number }>("/api/admin/settings");
|
||||
const result = await api<{ loginMode: string; credentialRefreshSeconds: number; workerConcurrency: number }>("/api/admin/settings");
|
||||
mode.value = result.loginMode;
|
||||
seconds.value = result.credentialRefreshSeconds;
|
||||
concurrency.value = result.workerConcurrency;
|
||||
}
|
||||
|
||||
async function save() {
|
||||
@@ -19,7 +21,7 @@ async function save() {
|
||||
try {
|
||||
await api("/api/admin/settings", {
|
||||
method: "PUT",
|
||||
body: JSON.stringify({ loginMode: mode.value, credentialRefreshSeconds: seconds.value }),
|
||||
body: JSON.stringify({ loginMode: mode.value, credentialRefreshSeconds: seconds.value, workerConcurrency: concurrency.value }),
|
||||
});
|
||||
message.value = "已保存";
|
||||
} catch (error) {
|
||||
@@ -33,18 +35,20 @@ onMounted(load);
|
||||
<template>
|
||||
<Shell>
|
||||
<header class="topbar">
|
||||
<h1>登录方式 <n-tooltip><template #trigger><span class="hint">?</span></template>同时只启用一种登录方式</n-tooltip></h1>
|
||||
<h1>设置</h1>
|
||||
<n-button type="primary" @click="save">保存</n-button>
|
||||
</header>
|
||||
<div class="content">
|
||||
<div class="form-grid">
|
||||
<label>方式</label>
|
||||
<label>方式 <n-tooltip><template #trigger><span class="hint">?</span></template>同时只启用一种登录方式</n-tooltip></label>
|
||||
<n-radio-group v-model:value="mode">
|
||||
<n-radio value="local">自有账号</n-radio>
|
||||
<n-radio value="nqi">大数据平台账号</n-radio>
|
||||
</n-radio-group>
|
||||
<label>刷新间隔</label>
|
||||
<n-input-number v-model:value="seconds" :min="60" :max="86400" />
|
||||
<label>并行数量 <n-tooltip><template #trigger><span class="hint">?</span></template>采集和导出共用。调大后马上多领任务;调小后等正在运行的结束,再降到新的数量</n-tooltip></label>
|
||||
<n-input-number v-model:value="concurrency" :min="1" :max="32" />
|
||||
</div>
|
||||
<p>{{ message }}</p>
|
||||
</div>
|
||||
|
||||
@@ -9,7 +9,7 @@ const role = sessionStorage.getItem("decom-role");
|
||||
const name = sessionStorage.getItem("decom-name") || "";
|
||||
const items = role === "admin"
|
||||
? [
|
||||
{ label: "登录方式", path: "/admin/settings" },
|
||||
{ label: "设置", path: "/admin/settings" },
|
||||
{ label: "用户", path: "/admin/users" },
|
||||
{ label: "账号池", path: "/admin/pool" },
|
||||
{ label: "采集", path: "/admin/sources" },
|
||||
|
||||
Reference in New Issue
Block a user