351 lines
14 KiB
Python
351 lines
14 KiB
Python
#!/usr/bin/env python3
|
||
"""守 ``app/presence`` 那一层"这张表还有没有值得看的行":省的是往返,不许动口径。
|
||
|
||
审批、发起、办结这些路径上有四条查询常年空手回来(本部署 ``oa_open_webhook`` /
|
||
``oa_notify_channel`` / ``oa_agent`` / ``oa_outbound_message`` 各 0 行),一次流转
|
||
要为这四个"确实没有"排四次队。这一层把布尔结论留在进程里,写了才作废。
|
||
它只可能改变**问库的次数**,不许改变任何答案,所以这个脚本一次钉六条:
|
||
|
||
1. **只省往返、不改答案**:同一口径连续三趟,开了这一层问库的次数严格少于不开,
|
||
三趟给出的结论一模一样;
|
||
2. **提交才算数**:写语句发出去不作废、提交才作废(提前作废会把"甲正在改还没提交"
|
||
这段窗口里的一次探查询固化成"确实没有");真提交一行启用的渠道之后,另一趟必须
|
||
看见它,跑完删干净;
|
||
3. **回滚不作废别人**:本 Session 回滚只抹掉自己记的账,别人的结论与代号都不动;
|
||
4. **广播只作废那一张表**:别的进程说写了 ``oa_agent``,另外三张表的结论还得留着;
|
||
5. **认不出写了哪张表就一起作废**(多表写、DDL、裸 SQL 那一条路);
|
||
6. **自己写过的表不许用缓存**:同一个 Session 里先启用一个渠道 / 改一份表单,
|
||
紧接着在同一趟里读,必须看见自己刚写进去的那一份;
|
||
7. **表单定义那份快照同样只省往返**:三趟问一次库,改了并提交之后下一趟是新内容;
|
||
8. **关掉这一层就一字不差**:``OA_PRESENCE=off``(这里是把开关按下去)时每一趟照旧问库。
|
||
|
||
库里不留东西:临时行跑在事务里,脚本结束整体回滚。::
|
||
|
||
PYTHONPATH=. python3 scripts/check_presence_guard.py
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import sys
|
||
from datetime import datetime
|
||
|
||
from sqlalchemy import event, select
|
||
|
||
from app import models, presence
|
||
from app.db import SessionLocal, engine
|
||
from app.service import autofill, channels, events, org, outbox
|
||
|
||
FAILS: list[str] = []
|
||
PASSED = 0
|
||
CODE = "zz-check-presence"
|
||
|
||
#: 数语句条数:这一层买的就是"少排几次队",判据只看条数。
|
||
ROWS: list[str] = []
|
||
|
||
|
||
@event.listens_for(engine, "after_cursor_execute")
|
||
def _count(conn, cursor, statement, parameters, context, many): # noqa: ANN001
|
||
ROWS.append(" ".join(statement.split())[:120])
|
||
|
||
|
||
def check(label: str, ok: bool, detail: str = "") -> None:
|
||
global PASSED
|
||
if ok:
|
||
PASSED += 1
|
||
print(f"[通过] {label}")
|
||
else:
|
||
FAILS.append(label)
|
||
print(f"[FAIL] {label}{f' -> {detail}' if detail else ''}")
|
||
|
||
|
||
def counted(fn):
|
||
"""跑一趟,交回 ``(结果, 这一趟问了几条库)``。"""
|
||
start = len(ROWS)
|
||
value = fn()
|
||
return value, len(ROWS) - start
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# 探针本身
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
def probe(table: str):
|
||
"""一个永远查不到行的探针:与部署里有没有真数据无关,脚本自己说了能算。"""
|
||
|
||
def run(db):
|
||
return db.execute(select(models.NotifyChannel.id)
|
||
.where(models.NotifyChannel.code == f"{CODE}-{table}")
|
||
.limit(1)).first() is not None
|
||
|
||
return run
|
||
|
||
|
||
def probe_reuse() -> None:
|
||
"""同一个口径连问三趟:第一趟问库,后两趟一次都不许问,答案还得一模一样。"""
|
||
presence.clear()
|
||
first, n_first = counted(lambda: presence.any_row(SessionLocal(), "oa_notify_channel", probe("a")))
|
||
second, n_second = counted(lambda: presence.any_row(SessionLocal(), "oa_notify_channel", probe("a")))
|
||
third, n_third = counted(lambda: presence.any_row(SessionLocal(), "oa_notify_channel", probe("a")))
|
||
check("探针第一趟问了库", n_first >= 1, f"{n_first} 条")
|
||
check("探针后两趟一次都不问库", n_second == 0 and n_third == 0, f"{n_second}/{n_third} 条")
|
||
check("三趟答案一样", first == second == third)
|
||
|
||
# 关掉这一层:每一趟都照旧问库
|
||
enabled = presence.ENABLED
|
||
presence.ENABLED = False
|
||
try:
|
||
_, n_off = counted(lambda: presence.any_row(SessionLocal(), "oa_notify_channel", probe("a")))
|
||
_, n_off2 = counted(lambda: presence.any_row(SessionLocal(), "oa_notify_channel", probe("a")))
|
||
finally:
|
||
presence.ENABLED = enabled
|
||
check("关掉这一层每趟都问库", n_off >= 1 and n_off2 >= 1, f"{n_off}/{n_off2} 条")
|
||
|
||
ttl = presence.ttl_seconds()
|
||
presence.os.environ["OA_PRESENCE_TTL"] = "0"
|
||
try:
|
||
_, n_ttl = counted(lambda: presence.any_row(SessionLocal(), "oa_notify_channel", probe("a")))
|
||
finally:
|
||
if ttl:
|
||
presence.os.environ["OA_PRESENCE_TTL"] = str(ttl)
|
||
else:
|
||
presence.os.environ.pop("OA_PRESENCE_TTL", None)
|
||
check("TTL 填 0 等于关掉这一层", n_ttl >= 1, f"{n_ttl} 条")
|
||
|
||
|
||
def invalidation_paths() -> None:
|
||
"""作废的三条路:本进程写了这张表、广播说别人写了、认不出写了哪张表。"""
|
||
presence.clear()
|
||
presence.any_row(SessionLocal(), "oa_agent", probe("b")) # 先把四张表各存一份结论
|
||
presence.any_row(SessionLocal(), "oa_notify_channel", probe("b"))
|
||
presence.any_row(SessionLocal(), "oa_open_webhook", probe("b"))
|
||
|
||
base = {name: presence.generation(name) for name in sorted(presence.TRACKED)}
|
||
session = SessionLocal()
|
||
try:
|
||
presence.note_write(session, "oa_users")
|
||
presence.note_commit(session)
|
||
check("与这几张表无关的写不惊动这一层",
|
||
all(presence.generation(name) == base[name] for name in base))
|
||
|
||
presence.note_write(session, "oa_agent")
|
||
check("只发写语句还不作废(提交才算数)",
|
||
presence.generation("oa_agent") == base["oa_agent"])
|
||
presence.note_rollback(session)
|
||
check("回滚不作废任何人",
|
||
all(presence.generation(name) == base[name] for name in base))
|
||
|
||
presence.note_write(session, "oa_agent")
|
||
presence.note_commit(session)
|
||
check("提交了某张表只作废那张表",
|
||
presence.generation("oa_agent") == base["oa_agent"] + 1
|
||
and presence.generation("oa_notify_channel") == base["oa_notify_channel"])
|
||
finally:
|
||
session.close()
|
||
|
||
presence.on_cluster_invalidate("oa_notify_channel")
|
||
check("广播里那张表作废、别张留着",
|
||
presence.generation("oa_notify_channel") == base["oa_notify_channel"] + 1
|
||
and presence.generation("oa_open_webhook") == base["oa_open_webhook"])
|
||
|
||
presence.on_cluster_invalidate("")
|
||
bumped = sum(1 for name in base if presence.generation(name) > base[name])
|
||
check("广播没带表名就一起作废", bumped == len(base), f"{bumped}/{len(base)}")
|
||
|
||
# 认不出表的那条路(DDL、多表写、裸 SQL):整层作废
|
||
before = {name: presence.generation(name) for name in base}
|
||
presence.any_row(SessionLocal(), "oa_agent", probe("b"))
|
||
from app.db import _invalidate_for_statement
|
||
|
||
_invalidate_for_statement("ALTER TABLE oa_agent ADD COLUMN zz_check_flag INT", None)
|
||
check("认不出写了哪张表就整层作废",
|
||
all(presence.generation(name) >= before[name] for name in before)
|
||
and presence.generation("oa_agent") > before["oa_agent"])
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# 四个调用点:同一个答案,更少的往返
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
def call_site(label: str, call) -> None:
|
||
"""连开三趟独立 Session 问同一件事:开了这一层必须比不开问得少,答案一样。"""
|
||
presence.clear()
|
||
results = []
|
||
trips = 0
|
||
for _ in range(3):
|
||
value, n = counted(lambda: call(SessionLocal()))
|
||
results.append(value)
|
||
trips += n
|
||
enabled = presence.ENABLED
|
||
presence.ENABLED = False
|
||
try:
|
||
presence.clear()
|
||
bare_results = []
|
||
bare_trips = 0
|
||
for _ in range(3):
|
||
value, n = counted(lambda: call(SessionLocal()))
|
||
bare_results.append(value)
|
||
bare_trips += n
|
||
finally:
|
||
presence.ENABLED = enabled
|
||
same = repr(results[0]) == repr(bare_results[0])
|
||
fewer = trips < bare_trips
|
||
check(f"{label}:三趟的往返少了({bare_trips} → {trips})", fewer)
|
||
check(f"{label}:答案与不开这一层一模一样", same)
|
||
|
||
|
||
CHANNEL_CODE = f"{CODE}-channel"
|
||
FORM_ID = "chkpresenceform0000000000000001"
|
||
|
||
|
||
def truth_after_write() -> None:
|
||
"""真提交一个启用的渠道:另一趟必须看见它,作废不能等 TTL。跑完删干净。"""
|
||
db = SessionLocal()
|
||
try:
|
||
db.add(models.NotifyChannel(
|
||
code=CHANNEL_CODE, name="体检用渠道", kind="wecom", enabled=True,
|
||
events=["task.created"], config={"webhook": "https://example.invalid/hook"},
|
||
))
|
||
db.commit()
|
||
finally:
|
||
db.close()
|
||
try:
|
||
other = SessionLocal()
|
||
try:
|
||
hit = [item.code for item in channels.enabled_channels(other)]
|
||
finally:
|
||
other.close()
|
||
check("刚提交的渠道下一趟就看得见", CHANNEL_CODE in hit, str(hit))
|
||
|
||
other = SessionLocal()
|
||
try:
|
||
_, trips = counted(lambda: channels.channels_for(other, "task.created"))
|
||
finally:
|
||
other.close()
|
||
check("有真数据时该问库还是问库", trips >= 1, f"{trips} 条")
|
||
finally:
|
||
cleanup()
|
||
|
||
|
||
def cleanup() -> None:
|
||
"""把体检用的那两行删掉并提交(半路挨刀也不该留下一个真会发通知的渠道/一张野表单)。"""
|
||
db = SessionLocal()
|
||
try:
|
||
db.query(models.NotifyChannel).filter(models.NotifyChannel.code == CHANNEL_CODE).delete()
|
||
db.query(models.FormElement).filter(models.FormElement.id == FORM_ID).delete()
|
||
db.commit()
|
||
finally:
|
||
db.close()
|
||
presence.clear()
|
||
|
||
|
||
def same_session_write() -> None:
|
||
"""自己刚写的表不许用缓存:同一个 Session 里先改后读,读到的得是自己写的那份。"""
|
||
session = SessionLocal()
|
||
try:
|
||
# 先让这一层对这两张表各存一份结论(多半是"没有")
|
||
channels.enabled_channels(session)
|
||
autofill.form_fields(session, FORM_ID)
|
||
|
||
session.add(models.NotifyChannel(
|
||
code=CHANNEL_CODE, name="体检用渠道(未提交)", kind="wecom", enabled=True,
|
||
events=["task.created"], config={},
|
||
))
|
||
session.flush()
|
||
hit = [item.code for item in channels.enabled_channels(session)]
|
||
check("同一趟里刚启用的渠道看得见", CHANNEL_CODE in hit, str(hit))
|
||
|
||
form = session.get(models.FormElement, FORM_ID)
|
||
if form is not None:
|
||
form.content = {"fields": [{"key": "a", "type": "text", "label": "同一趟里改的"}]}
|
||
session.flush()
|
||
labels = [str(item.get("label")) for item in autofill.form_fields(session, FORM_ID)]
|
||
check("同一趟里刚改的表单看得见", "同一趟里改的" in labels, str(labels))
|
||
finally:
|
||
session.rollback()
|
||
session.close()
|
||
|
||
|
||
def snapshot_reuse() -> None:
|
||
"""表单定义那份快照:三趟问一次库;提交改动的下一趟必须换新。"""
|
||
db = SessionLocal()
|
||
try:
|
||
db.add(models.FormElement(id=FORM_ID, name="体检用表单",
|
||
content={"fields": [{"key": "a", "type": "text", "label": "改之前"}]}))
|
||
db.commit()
|
||
finally:
|
||
db.close()
|
||
presence.clear()
|
||
trips = 0
|
||
for _ in range(3):
|
||
session = SessionLocal()
|
||
try:
|
||
_, n = counted(lambda: autofill.form_fields(session, FORM_ID))
|
||
finally:
|
||
session.close()
|
||
trips += n
|
||
check("表单定义三趟只问一次库", trips == 1, f"{trips} 条")
|
||
|
||
db = SessionLocal()
|
||
try:
|
||
db.get(models.FormElement, FORM_ID).content = {
|
||
"fields": [{"key": "a", "type": "text", "label": "改之后"}]}
|
||
db.commit()
|
||
finally:
|
||
db.close()
|
||
session = SessionLocal()
|
||
try:
|
||
labels = [str(item.get("label")) for item in autofill.form_fields(session, FORM_ID)]
|
||
finally:
|
||
session.close()
|
||
check("提交过的表单改动下一趟就换新", labels == ["改之后"], str(labels))
|
||
|
||
|
||
def empty_fast_paths() -> None:
|
||
"""一张表里确实没有可用行时,这四条路一条库都不许多问。"""
|
||
presence.clear()
|
||
now = datetime.now()
|
||
probes = [
|
||
("没有启用的代理就不问库", lambda db: org.apply_agents(db, "", ["某个人"], now)),
|
||
("没有启用的渠道就不问库", lambda db: channels.channels_for(db, "task.created")),
|
||
("没有启用的订阅就不问库", lambda db: events.subscriptions(db, "task.created")),
|
||
("没有卡人的报文就不问库", lambda db: outbox.blocking(db, job="某个 job")),
|
||
]
|
||
for label, call in probes:
|
||
presence.clear()
|
||
first_value, first = counted(lambda: call(SessionLocal())) # 探针问一次
|
||
second_value, second = counted(lambda: call(SessionLocal())) # 结论在进程里
|
||
check(label, second == 0, f"第二趟 {second} 条")
|
||
check(f"{label}(两趟答案一致)", repr(first_value) == repr(second_value))
|
||
|
||
|
||
def main() -> int:
|
||
db = SessionLocal()
|
||
try:
|
||
probe_reuse()
|
||
invalidation_paths()
|
||
truth_after_write()
|
||
snapshot_reuse()
|
||
same_session_write()
|
||
call_site("通知渠道", lambda session: [row.code for row in channels.enabled_channels(session)])
|
||
call_site("事件订阅", lambda session: [row.code for row in events.enabled_webhooks(session)])
|
||
call_site("流程代理", lambda session: org.apply_agents(session, "", ["某个人"], datetime.now()))
|
||
call_site("卡人的报文", lambda session: len(outbox.blocking(session, job="某个 job")))
|
||
empty_fast_paths()
|
||
finally:
|
||
db.rollback()
|
||
db.close()
|
||
cleanup()
|
||
print()
|
||
print(f"共 {PASSED + len(FAILS)} 项,通过 {PASSED},失败 {len(FAILS)}")
|
||
if FAILS:
|
||
for item in FAILS:
|
||
print(" - " + item)
|
||
return 1
|
||
return 0
|
||
|
||
|
||
if __name__ == "__main__":
|
||
sys.exit(main())
|