Files
live-hub-py/web/backend/services/automation/jobs/account_sync_queue.py
T

72 lines
1.9 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""账号内部同步队列作业。"""
from __future__ import annotations
from datetime import UTC, datetime
from typing import Any
from sqlalchemy.orm import Session
from ....models import AccountWorkItem, AutomationJob
from ...account_sync_runner import ACCOUNT_SYNC_WORK_TYPES, run_account_sync_queue
from ...account_work_queue import (
expire_stale_login_work,
recover_stale_running_account_work,
)
JOB_KEY = "account_sync_queue"
def count_pending_work(db: Session, *, now: datetime | None = None) -> int:
moment = now or datetime.now(UTC)
return int(
db.query(AccountWorkItem.id)
.filter(
AccountWorkItem.work_type.in_(ACCOUNT_SYNC_WORK_TYPES),
AccountWorkItem.status == "pending",
AccountWorkItem.due_at <= moment,
)
.count()
or 0
)
def run_account_sync_queue_job(
db: Session,
job: AutomationJob,
) -> dict[str, Any]:
moment = datetime.now(UTC)
expired = expire_stale_login_work(db, now=moment)
recovered_stale = recover_stale_running_account_work(
db,
work_types=ACCOUNT_SYNC_WORK_TYPES,
now=moment,
)
if expired or recovered_stale:
db.commit()
result = run_account_sync_queue(
db,
batch_size=max(1, int(job.batch_size or 20)),
)
if result.get("scanned"):
result["remaining"] = count_pending_work(db)
notes: list[str] = []
if recovered_stale:
result["recovered_stale"] = recovered_stale
notes.append(f"回收卡死工作 {recovered_stale} 条")
if expired:
result["expired_login"] = expired
notes.append(f"过期重登转人工 {expired} 条")
if notes:
result["message"] = (
f"{result.get('message') or '账号同步完成'}," + ",".join(notes)
)
return result
__all__ = [
"JOB_KEY",
"count_pending_work",
"run_account_sync_queue_job",
]