Files
live-hub-py/web/backend/services/account_work_queue.py
T

463 lines
14 KiB
Python

"""账号内部维护工作队列。"""
from __future__ import annotations
from datetime import UTC, datetime, timedelta
from typing import Any
from sqlalchemy import case, func, or_, select
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session
from ..models import Account, AccountWorkItem
WORK_AGING_SECONDS = 30 * 60
STALE_RUNNING_SECONDS = 30 * 60
#: 供给补货任务的 reason 前缀;队列靠它给通用供给保留固定处理配额。
SUPPLY_REASON_PREFIX = "供给短缺:"
#: 履约商品能力补货任务的 reason 前缀;队列把它归入订单补货一侧。
ORDER_REFRESH_REASON_PREFIX = "待履约商品补货:"
def active_account_work_exists(*, work_type: str):
"""SQL 子查询:同一账号已有同类型的待执行或运行中工作。"""
return (
select(AccountWorkItem.id)
.where(
AccountWorkItem.account_id == Account.id,
AccountWorkItem.work_type == work_type,
AccountWorkItem.active_dedupe_key.isnot(None),
)
.exists()
)
def active_account_work_ids(
db: Session,
*,
work_type: str,
limit: int = 5000,
) -> tuple[int, ...] | None:
"""读取指定类型的在途账号 ID 集合(仅扫 active_dedupe_key 非空行)。
当在途数量超过 ``limit`` 时返回 ``None``,由调用方回退到 SQL 子查询。
"""
rows = (
db.query(AccountWorkItem.account_id)
.filter(
AccountWorkItem.active_dedupe_key.isnot(None),
AccountWorkItem.work_type == work_type,
)
.limit(max(1, int(limit)) + 1)
.all()
)
if len(rows) > limit:
return None
return tuple(dict.fromkeys(int(account_id) for (account_id,) in rows))
def active_account_work_count(
db: Session,
*,
work_types: tuple[str, ...],
reason_prefix: str | None = None,
exclude_reason_prefix: str | None = None,
) -> int:
"""当前账号同步队列中尚未结束的工作数(可按 reason 分类)。"""
if not work_types:
return 0
query = db.query(func.count(AccountWorkItem.id)).filter(
AccountWorkItem.work_type.in_(work_types),
AccountWorkItem.active_dedupe_key.isnot(None),
)
if reason_prefix:
query = query.filter(AccountWorkItem.reason.like(f"{reason_prefix}%"))
if exclude_reason_prefix:
query = query.filter(
~AccountWorkItem.reason.like(f"{exclude_reason_prefix}%")
)
return int(query.scalar() or 0)
def enqueue_account_work(
db: Session,
*,
account_id: int,
work_type: str,
priority: int = 100,
due_at: datetime | None = None,
max_attempts: int = 3,
reason: str = "",
payload: dict[str, Any] | None = None,
) -> AccountWorkItem:
dedupe_key = f"{work_type}:{account_id}"
existing = (
db.query(AccountWorkItem)
.filter(
AccountWorkItem.account_id == account_id,
AccountWorkItem.work_type == work_type,
AccountWorkItem.status.in_(("pending", "running")),
)
.first()
)
if existing is not None:
existing.priority = min(existing.priority, priority)
existing.max_attempts = max(existing.max_attempts, max(1, int(max_attempts)))
if due_at is not None and due_at < existing.due_at:
existing.due_at = due_at
db.flush()
return existing
bind = db.get_bind()
last_exc: IntegrityError | None = None
for _ in range(3):
item = AccountWorkItem(
account_id=account_id,
work_type=work_type[:32],
priority=int(priority),
# MySQL DATETIME 不保存微秒;立即到期的工作项必须落在当前秒,
# 否则四舍五入到下一秒后,本轮 claim 会误判“还没到期”。
due_at=(due_at or datetime.now(UTC)).replace(microsecond=0),
max_attempts=max(1, int(max_attempts)),
dedupe_key=dedupe_key[:191],
reason=reason[:255],
payload_json=payload,
)
try:
with db.begin_nested():
db.add(item)
db.flush()
return item
except IntegrityError as exc:
last_exc = exc
existing = (
db.query(AccountWorkItem)
.filter(AccountWorkItem.active_dedupe_key == dedupe_key[:191])
.first()
)
if existing is not None:
return existing
# MySQL REPEATABLE READ 快照看不到并发事务刚提交的行(或对方刚消费完成并
# 清空 active_dedupe_key),用同 bind 的新只读会话查最新已提交状态。
with Session(bind=bind) as probe:
existing_latest = (
probe.query(AccountWorkItem)
.filter(AccountWorkItem.active_dedupe_key == dedupe_key[:191])
.first()
)
if existing_latest is not None:
probe.expunge(existing_latest)
return existing_latest
assert last_exc is not None
raise last_exc
def claim_account_work(
db: Session,
*,
work_types: tuple[str, ...],
limit: int = 10,
now: datetime | None = None,
account_ids: tuple[int, ...] | None = None,
reason_prefix: str | None = None,
exclude_reason_prefix: str | None = None,
) -> list[AccountWorkItem]:
moment = now or datetime.now(UTC)
query = (
db.query(AccountWorkItem)
.filter(
AccountWorkItem.work_type.in_(work_types),
AccountWorkItem.status == "pending",
AccountWorkItem.due_at <= moment,
)
)
if account_ids is not None:
if not account_ids:
return []
query = query.filter(AccountWorkItem.account_id.in_(account_ids))
if reason_prefix:
query = query.filter(AccountWorkItem.reason.like(f"{reason_prefix}%"))
if exclude_reason_prefix:
query = query.filter(
~AccountWorkItem.reason.like(f"{exclude_reason_prefix}%")
)
rows = (
query
.order_by(
# 到期超过 30 分钟的工作优先出队,避免固定业务优先级造成永久饥饿。
# due_at 是工作项真正可执行的起点;未来重试项不会命中这个分支。
case(
(
AccountWorkItem.due_at
<= moment - timedelta(seconds=WORK_AGING_SECONDS),
0,
),
else_=1,
),
AccountWorkItem.priority.asc(),
AccountWorkItem.due_at.asc(),
AccountWorkItem.id.asc(),
)
.with_for_update(skip_locked=True)
.limit(max(1, int(limit)))
.all()
)
for row in rows:
row.status = "running"
row.started_at = moment
row.attempt_count = int(row.attempt_count or 0) + 1
row.updated_at = moment
if rows:
db.flush()
return rows
def complete_account_work(
db: Session,
item: AccountWorkItem,
*,
now: datetime | None = None,
) -> None:
moment = now or datetime.now(UTC)
item.status = "success"
item.finished_at = moment
item.last_error = ""
item.updated_at = moment
db.flush()
def complete_account_work_type(
db: Session,
*,
account_id: int,
work_type: str,
now: datetime | None = None,
) -> int:
"""完成某个账号指定类型的待办;成功后旧待办不再阻塞后续工作。"""
moment = now or datetime.now(UTC)
items = (
db.query(AccountWorkItem)
.filter(
AccountWorkItem.account_id == account_id,
AccountWorkItem.work_type == work_type,
AccountWorkItem.status.in_(("pending", "running")),
)
.all()
)
for item in items:
complete_account_work(db, item, now=moment)
return len(items)
def fail_account_work(
db: Session,
item: AccountWorkItem,
*,
error: BaseException | str,
retry_after_seconds: int = 300,
now: datetime | None = None,
) -> None:
moment = now or datetime.now(UTC)
message = str(error)[:2000]
item.last_error = message
item.updated_at = moment
if int(item.attempt_count or 0) >= int(item.max_attempts or 1):
item.status = "failed"
item.finished_at = moment
else:
item.status = "pending"
item.due_at = (
moment + timedelta(seconds=max(1, retry_after_seconds))
).replace(microsecond=0)
db.flush()
def recover_running_account_work(
db: Session,
*,
now: datetime | None = None,
) -> int:
"""服务重启后把中断的 running 工作项退回 pending。"""
moment = (now or datetime.now(UTC)).replace(microsecond=0)
items = (
db.query(AccountWorkItem)
.filter(AccountWorkItem.status == "running")
.all()
)
for item in items:
item.status = "pending"
item.due_at = moment
item.last_error = "工作执行中断(服务重启),已重新排队"
item.updated_at = moment
if items:
db.commit()
return len(items)
def _stale_running_seconds(override: int | None = None) -> int:
import os
if override is not None:
return max(60, int(override))
try:
return max(
60,
int(os.getenv("ACCOUNT_WORK_STALE_RUNNING_SECONDS", str(STALE_RUNNING_SECONDS))),
)
except ValueError:
return STALE_RUNNING_SECONDS
def recover_stale_running_account_work(
db: Session,
*,
work_types: tuple[str, ...] | None = None,
stale_seconds: int | None = None,
now: datetime | None = None,
) -> int:
"""回收运行超时仍停留在 running 的工作项,防止单线程异常后永久占住队列去重键。"""
moment = (now or datetime.now(UTC)).replace(microsecond=0)
seconds = _stale_running_seconds(stale_seconds)
cutoff = moment - timedelta(seconds=seconds)
query = db.query(AccountWorkItem).filter(
AccountWorkItem.status == "running",
or_(
AccountWorkItem.started_at <= cutoff,
(AccountWorkItem.started_at.is_(None) & (AccountWorkItem.updated_at <= cutoff)),
),
)
if work_types:
query = query.filter(AccountWorkItem.work_type.in_(work_types))
items = query.all()
for item in items:
fail_account_work(
db,
item,
error=f"工作执行超过 {seconds // 60} 分钟未完成(疑似卡死),已回收",
retry_after_seconds=60,
now=moment,
)
if items:
db.flush()
return len(items)
def expire_stale_login_work(
db: Session,
*,
now: datetime | None = None,
ttl_seconds: int | None = None,
) -> int:
"""关闭长时间未执行的重登工作,避免暂停作业后永久挂在待处理。
重登作业因 100% 失败自动暂停时,队列里会残留 pending 的
``login_relogin``;它们既不会执行,也会在页面上冒充“待处理”。超过 TTL
后置为 failed,转人工处理,不再占用队列观测。
"""
import os
moment = now or datetime.now(UTC)
if ttl_seconds is None:
try:
ttl_seconds = max(
60,
int(os.getenv("ACCOUNT_RELOGIN_WORK_TTL_SECONDS", "86400")),
)
except ValueError:
ttl_seconds = 86400
cutoff = (moment - timedelta(seconds=ttl_seconds)).replace(microsecond=0)
items = (
db.query(AccountWorkItem)
.filter(
AccountWorkItem.work_type == "login_relogin",
AccountWorkItem.status.in_(("pending", "running")),
AccountWorkItem.due_at < cutoff,
)
.all()
)
for item in items:
item.status = "failed"
item.finished_at = moment
item.last_error = (
f"重登工作超过 {ttl_seconds // 3600} 小时未执行"
"(重登作业可能已暂停),已转人工处理"
)
item.updated_at = moment
if items:
db.flush()
return len(items)
def reschedule_account_work_type(
db: Session,
*,
account_id: int,
work_type: str,
due_at: datetime,
reason: str = "",
) -> int:
"""把自动重登失败的工作项按账号退避时间重新排队。"""
moment = (due_at if due_at.tzinfo else due_at.replace(tzinfo=UTC)).replace(
microsecond=0
)
items = (
db.query(AccountWorkItem)
.filter(
AccountWorkItem.account_id == account_id,
AccountWorkItem.work_type == work_type,
AccountWorkItem.status.in_(("pending", "running")),
)
.all()
)
for item in items:
item.status = "pending"
item.due_at = moment
item.last_error = reason[:2000]
item.updated_at = datetime.now(UTC)
db.flush()
return len(items)
def fail_account_work_type(
db: Session,
*,
account_id: int,
work_type: str,
reason: str,
now: datetime | None = None,
) -> int:
"""关闭不再自动处理的工作项,例如重登已转人工。"""
moment = now or datetime.now(UTC)
items = (
db.query(AccountWorkItem)
.filter(
AccountWorkItem.account_id == account_id,
AccountWorkItem.work_type == work_type,
AccountWorkItem.status.in_(("pending", "running")),
)
.all()
)
for item in items:
item.status = "failed"
item.finished_at = moment
item.last_error = reason[:2000]
item.updated_at = moment
db.flush()
return len(items)
__all__ = [
"STALE_RUNNING_SECONDS",
"active_account_work_count",
"active_account_work_exists",
"claim_account_work",
"complete_account_work",
"complete_account_work_type",
"enqueue_account_work",
"fail_account_work",
"fail_account_work_type",
"recover_running_account_work",
"recover_stale_running_account_work",
"reschedule_account_work_type",
]