138 lines
4.6 KiB
Python
138 lines
4.6 KiB
Python
"""PostgreSQL 上的 Procrastinate 队列。采集和导出都由排队进程执行。"""
|
|
|
|
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 current_concurrency, execute_collection, execute_export
|
|
|
|
logger = logging.getLogger("decom")
|
|
|
|
conninfo = postgres_conninfo() or "postgresql://invalid"
|
|
queue = procrastinate.App(connector=procrastinate.PsycopgConnector(conninfo=conninfo))
|
|
defer_queue = procrastinate.App(connector=procrastinate.PsycopgConnector(conninfo=conninfo))
|
|
|
|
|
|
@queue.task(name="decom_export", queue="decom")
|
|
def decom_export(task_id: int) -> None:
|
|
execute_export(task_id)
|
|
|
|
|
|
@queue.task(name="decom_collect", queue="decom")
|
|
def decom_collect(source_id: int) -> None:
|
|
execute_collection(source_id)
|
|
|
|
|
|
def defer(name: str, **kwargs) -> None:
|
|
# API 和 worker 是两个进程;worker 自己还会从后台线程提交采集任务。
|
|
# 使用独立的同步连接,避免与 worker 持有的异步连接互相关闭。
|
|
with defer_queue.open():
|
|
defer_queue.configure_task(name, queue="decom").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:
|
|
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())
|