unis-oa/backend/scripts/check_outbox_wake.py

248 lines
11 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.

#!/usr/bin/env python3
"""写回投递的即时性:入队当场就该起来发,同一张单排着的要一轮发干净。
PYTHONPATH=. python3 scripts/check_outbox_wake.py
界面上"待发送 / 0 次 / 0ms"挂着一整分钟不动,人只会读成"回写没成"。这几条把
延迟的三个来源逐个钉住:
1. **入队当场叫醒**:报文与单据状态同一事务提交,提交那一刻叫醒投递线程;
没提交不叫(那条报文对别的连接还不可见,叫了是跑空)、回滚不叫(单没过)、
第二次命中并回在途那一条时也不叫(没新报文);
2. **人工重推也叫醒**:人点过重推就是想看结果,别让他等下一个轮询周期;
3. **一轮发干净**:``due()`` 对同一张单只给队首一条(办结要排在冻结后面),
``run_due()`` 必须发完一条重新取队首,否则一张单挂两个写回点就要等两个周期;
4. **叫醒只改"何时醒"**:``_scheduler_sleep`` 被叫醒返回"继续跑",被停止返回"退出"。
数据源开影子模式(报文照渲染照留档,不打出去),跑完连数据源、模板、单据、报文一起删干净。
"""
from __future__ import annotations
import time
from datetime import datetime, timedelta
from sqlalchemy import delete, select
from app import models
from app.db import SessionLocal
from app.service import outbox
STAMP = int(time.time())
SRC = f"wbwake_src_{STAMP}"
T_ONE = f"wbwake_one_{STAMP}"
T_TWO = f"wbwake_two_{STAMP}"
JOB = f"wbwakejob{STAMP}"
PROCESS = f"wbwakeproc{STAMP}"
FAILS: list[str] = []
PASSED = 0
CLEAN: dict = {}
WAKES: list[int] = []
def check(label: str, condition, detail: str = "") -> None:
global PASSED
if condition:
PASSED += 1
print(f"[通过] {label}")
else:
FAILS.append(label)
print(f"[FAIL] {label}{f' -> {detail}' if detail else ''}")
#: 把刚入队的报文推到将来,别让**同时在跑的那个后端进程**的调度线程把它抢发掉:
#: 校验跑的是"什么时候醒、一轮发几条",被别的进程抢先发走就什么都测不出来了。
PARK_SECONDS = 600
def park(db, rows) -> None:
moment = datetime.now() + timedelta(seconds=PARK_SECONDS)
for row in rows:
row.next_attempt_at = moment.replace(microsecond=0)
db.flush()
db.commit()
def release(db, rows) -> None:
"""把 :func:`park` 推走的报文放回"现在就能发"。"""
moment = datetime.now().replace(microsecond=0)
for row in rows:
row.next_attempt_at = moment
db.flush()
db.commit()
def rows_of(db, code: str) -> list[models.OutboundMessage]:
return list(db.execute(
select(models.OutboundMessage)
.where(models.OutboundMessage.integration == code, models.OutboundMessage.job == JOB)
.order_by(models.OutboundMessage.id)
).scalars().all())
def build(db) -> dict:
"""一张真单据 + 一个影子数据源 + 两个写回模板(模拟一次提交命中两个写回点)。"""
form = models.FormElement(name=f"投递即时性校验表单 {STAMP}",
content={"fields": [{"key": "amount", "label": "金额", "type": "number"}]})
db.add(form)
db.flush()
db.add(models.DataSource(code=SRC, name=f"投递即时性数据源 {STAMP}",
direction=models.DataSource.DIRECTION_OUT,
provider=models.DataSource.PROVIDER_HTTP,
url="https://erp.invalid/api/update", shadow=True, enabled=True))
body = {"method": "POST", "path": "/api/update",
"fields": [{"to": "flowNo", "from": "{work.serial}"}, {"to": "amount", "from": "{form.amount}"}]}
for code in (T_ONE, T_TWO):
db.add(models.Integration(code=code, name=f"投递即时性 {code}", source=SRC, biz_form=form.id,
trigger_event=models.Integration.EVENT_ACTIVITY,
event_key="n1", payload=dict(body)))
work = models.Work(job=JOB, serial=f"WBWAKE{STAMP}", title=f"投递即时性校验单 {STAMP}",
process=PROCESS, process_name=f"投递即时性校验流程 {STAMP}", category="check",
creator="1", creator_person="1", form=form.id, status="running",
activity="n1", activity_name="复核", data={"amount": 100})
db.add(work)
db.flush()
db.commit()
CLEAN.update(form=form.id, work=work.id)
return {"form": form.id, "work": work,
"one": db.execute(select(models.Integration).where(models.Integration.code == T_ONE)).scalar_one(),
"two": db.execute(select(models.Integration).where(models.Integration.code == T_TWO)).scalar_one()}
def _run(db) -> int:
ids = build(db)
work, one, two = ids["work"], ids["one"], ids["two"]
# ---------------------------------------------- 1. 提交之前不叫,提交那一刻才叫
outbox.wake(lambda: WAKES.append(len(WAKES)))
row = outbox.enqueue(db, one, work, event=models.Integration.EVENT_ACTIVITY, event_key="n1")
db.flush()
check("入队当场还没叫醒(事务没提交就叫醒是跑空)", not WAKES, WAKES)
db.commit()
check("报文随事务提交 → 当场叫醒投递线程", len(WAKES) == 1, WAKES)
park(db, [row]) # 留在途:下面验"并回那一条",也别被同时在跑的后端抢发
# ---------------------------------------------- 2. 回滚不叫,并回在途那一条也不叫
WAKES.clear()
db.add(models.Work(job=JOB, serial=f"WBWAKE{STAMP}X", title="回滚不算数", process=PROCESS,
form=ids["form"], status="running", data={"amount": 1}))
outbox._mark_wake(db)
db.rollback()
check("事务回滚了不叫醒(单没过,报文也跟着没了)", not WAKES, WAKES)
WAKES.clear()
again = outbox.enqueue(db, one, work, event=models.Integration.EVENT_ACTIVITY, event_key="n1")
db.commit()
check("同一张单同一点再命中:并回在途那一条,不新增报文",
again is not None and again.id == row.id and len(rows_of(db, T_ONE)) == 1,
[(r.id, r.status) for r in rows_of(db, T_ONE)])
check("并回那一条没有新报文 → 不空叫一次", not WAKES, WAKES)
WAKES.clear()
work.data = {**(work.data or {}), "amount": 888}
merged = outbox.enqueue(db, one, work, event=models.Integration.EVENT_ACTIVITY, event_key="n1")
db.commit()
check("值变了再命中:报文按最新值重渲染,并当场叫醒(改完字段不该等下一个周期)",
merged is not None and merged.payload.get("amount") == 888 and len(WAKES) == 1,
f"{getattr(merged, 'payload', None)} {WAKES}")
# ---------------------------------------------- 3. 一轮把这张单排着的都发干净
WAKES.clear()
row2 = outbox.enqueue(db, two, work, event=models.Integration.EVENT_ACTIVITY, event_key="n2")
db.commit()
check("第二个写回点入队时也叫醒", len(WAKES) == 1, WAKES)
park(db, [row2])
# 用"未来的钟"探一次:两条都已到期,但同一张单仍只该给队首那一条
head = outbox.due(db, now=datetime.now() + timedelta(seconds=PARK_SECONDS + 60))
# 只看这张单的:那把"未来的钟"会把**别人**排着的重试也照出来——业务库里躺着几条
# 上游还没通、正在退避里的报文是常态(本部署此刻就有 6 条 reimb_update 在等下一轮),
# 按整份队首去断言"只有一条",测出来的是别人家发件箱有多挤,不是这里的排序口径。
mine = [item for item in head if item.job == JOB]
check("同一张单每轮仍只取队首一条(严格有序没被放宽)",
len(mine) == 1 and mine[0].id == row.id,
[(r.integration, r.job, r.id) for r in head if r.job == JOB] or [(r.integration, r.id) for r in head])
# 放行这两条:一次 run_due 要把这张单排着的都走完
release(db, [row, row2])
stats = outbox.run_due(db)
after_one, after_two = rows_of(db, T_ONE), rows_of(db, T_TWO)
check("一次 run_due 就把这张单排着的两条按顺序发干净(不用等下一个周期)",
len(after_one) == 1 and len(after_two) == 1
and after_one[0].status == models.OutboundMessage.STATUS_SUCCESS
and after_two[0].status == models.OutboundMessage.STATUS_SUCCESS
and stats.get("sent") == 2,
f"{stats} {[(r.integration, r.status) for r in after_one + after_two]}"
"(若另一条已是 success:多半是被同时在跑的后端进程抢发了,停掉后端再跑这一项)")
check("影子模式:报文照渲染照留档,没真打出去",
bool(after_one[0].shadowed) and after_one[0].payload.get("flowNo") == work.serial,
after_one[0].payload)
# ---------------------------------------------- 4. 人工重推也要当场叫
WAKES.clear()
replayed = outbox.replay(db, row2.id, reason="校验")
db.commit()
check("人工重推:修订版 +1 并当场叫醒",
replayed is not None and replayed.revision == 2 and len(WAKES) == 1,
f"{getattr(replayed, 'revision', None)} {WAKES}")
park(db, [replayed])
outbox.run_due(db)
# ---------------------------------------------- 5. 叫醒只改"何时醒"
from app import main as main_module
woke = main_module._wake_scheduler
stir, stop = main_module._scheduler_stir, main_module._scheduler_stop
saved_stop = stop.is_set()
stop.clear()
stir.clear()
started = time.monotonic()
woke()
check("被叫醒时 _scheduler_sleep 立刻返回,且不退出线程",
main_module._scheduler_sleep(30) is False and time.monotonic() - started < 5,
f"等了 {time.monotonic() - started:.2f}s")
stop.set()
stir.clear()
started = time.monotonic()
woke()
check("退出信号优先:睡里被叫醒也要认出该退出",
main_module._scheduler_sleep(30) is True and time.monotonic() - started < 5,
f"等了 {time.monotonic() - started:.2f}s")
if saved_stop:
stop.set()
else:
stop.clear()
stir.clear()
return 0
def main() -> int:
db = SessionLocal()
try:
code = _run(db)
finally:
cleanup(db)
print()
if FAILS:
print(f"{len(FAILS)} 条没对上:")
for item in FAILS:
print(f" - {item}")
else:
print(f"全部 {PASSED} 条对上。")
return 1 if FAILS else 0
def cleanup(db) -> None:
db.execute(delete(models.OutboundMessage).where(models.OutboundMessage.job == JOB))
db.execute(delete(models.Work).where(models.Work.job == JOB))
db.execute(delete(models.WorkCompleted).where(models.WorkCompleted.job == JOB))
db.execute(delete(models.Integration).where(models.Integration.code.in_([T_ONE, T_TWO])))
db.execute(delete(models.DataSource).where(models.DataSource.code == SRC))
if CLEAN.get("form"):
db.execute(delete(models.FormElement).where(models.FormElement.id == CLEAN["form"]))
db.commit()
print("[清理] 数据源、写回模板、单据与发件箱报文已删干净")
if __name__ == "__main__":
raise SystemExit(main())