unis-oa/backend/app/service/wake.py

86 lines
3.6 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

"""外发任务一入队就把投递线程叫醒 -- 三条外发路共用这一个通路。
为什么要单独一层
================
写回发件箱(:mod:`outbox`)、消息渠道(:mod:`channels`)、事件订阅(:mod:`events`)
是同一种活:与业务状态**同一事务**入队,真发交给后台调度线程,失败按退避重试。
叫醒线程这件事原本只写在 ``outbox`` 里,于是另外两路只能等下一个轮询周期——
本部署 ``oa_notify_delivery`` 上量得出来:一条企业微信推送从入队到发出去等了
28~60 秒,而真发那一次只用 1 秒。**慢的不是发送,是没人叫醒。**
规则
====
* **提交之后才叫**:入队与状态变更是同一个事务,事务没提交就把线程叫起来,它只会
跑一趟空(那条任务此刻对别的连接还不可见)。所以 :func:`mark` 只记账,
``after_commit`` 才真叫。
* **回滚不叫**:单没过,任务跟着一起回滚,这一趟不算数。
* **叫不醒只是慢,不是丢**:15/60 秒那一档轮询照旧跑(``main._scheduler_tick_seconds``),
这一层只把"最多等多久"从一分钟压到当下。
* **多副本一起叫**:本进程直接置事件,别的副本靠 :mod:`app.cache` 的广播。话题沿用
原来那条 ``outbound``,于是滚动发布时新旧副本互相都听得见。
* 回调必须便宜且幂等:叫一次和叫三次得是同一件事。
"""
from __future__ import annotations
import logging
from typing import Any, Callable
from sqlalchemy import event
from sqlalchemy.orm import Session
from .. import cache
logger = logging.getLogger("unisoa.wake")
#: 会话上"这一趟提交里排过新外发任务"的记号(``Session.info`` 正是给这种挂用途留的)
WAKE_KEY = "delivery_wake"
#: 谁在听"刚排上了一条外发任务":``app.main`` 登记的是"把调度线程叫醒",
#: 广播那条回调也接到这里,于是多副本下别的副本排上的任务同样当场起。
_hooks: list[Callable[[], None]] = []
def hook(handler: Callable[[], None]) -> None:
"""登记一个"现在就有活干"的回调。它必须便宜且幂等:叫一次和叫三次得是同一件事。"""
_hooks.append(handler)
def now() -> None:
"""叫醒所有登记过的监听者。叫不醒只是慢,不是丢:轮询那条路照旧兜底。"""
for item in list(_hooks):
try:
item()
except Exception: # pragma: no cover - defensive
logger.debug("叫醒投递线程失败,等下一个轮询周期", exc_info=True)
def mark(db: Session) -> None:
"""记一笔"这条会话排过新外发任务",**但不在这里叫醒**(等提交,见模块头)。
入队方只管在自己确认加了行的那一支调用它,一次事务里调几次都一样。
"""
db.info[WAKE_KEY] = True
@event.listens_for(Session, "after_commit")
def _after_commit(session: Session) -> None:
"""任务真的落库了才叫醒:本进程的叫醒回调 + 一条广播,让别的副本也当场起来。"""
if not session.info.pop(WAKE_KEY, None):
return
now()
cache.publish(cache.TOPIC_OUTBOUND, "enqueued")
@event.listens_for(Session, "after_rollback")
def _after_rollback(session: Session) -> None:
"""单没过,任务跟着一起回滚:这一趟不算数,别把投递线程空叫一次。"""
session.info.pop(WAKE_KEY, None)
def _on_shared_wake(_payload: Any = None) -> None:
"""别的副本排上了一条任务:本进程的投递线程也起来看一眼(幂等,自己那条也会收到)。"""
now()
cache.watch(cache.TOPIC_OUTBOUND, _on_shared_wake)