unis-oa/backend/app/designcache.py

156 lines
6.7 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.

"""流程定义(流程 / 环节 / 路由)的**跨请求**共享缓存:省的是排队,不动口径。
为什么加这一层
==============
本部署的库在另一台机器上,一条 SQL 无论多轻都要 17-21ms,一个接口慢不慢只看它排了几次队。
审批一次(``POST /task/{id}/execute``)量出来 37 条语句,其中三条每次问的都一模一样:
按流程主键取 ``oa_process`` / ``oa_activity`` / ``oa_route``。设计是**发布之后就不再动**的
配置——一次审批里读它一遍,同一个人连着点五张单就再问五遍,而这五遍之间设计一个字没改。
单据详情(``GET /job/{job}``)、审批人预览、流程设计回显同理。
存什么
======
存**原始行的列值**(``list[dict]``),不存拼好的 :class:`~app.engine.definition.ProcessDefinition`:
取回之后照旧交给 ``definition.build`` 拼装。构造口径全站只有那一处,缓存不可能拼出另一种定义。
规则(宁可少缓存,不能读到旧设计)
==================================
* 作废挂在**连接层的写语句**上(见 :func:`app.db._invalidate_for_statement` 调
:func:`note_write`):ORM 刷的、bulk 的、裸 SQL 的、别的进程写的,统统算数。写了
``oa_process`` / ``oa_activity`` / ``oa_route`` 任何一张,这一层的键当场删掉。
* 认不出写了哪张表(DDL、存储过程、多表写)但语句里出现这三张表名 → 整层丢掉。
* **写完之后的那一小段时间里不许回填**:删键的同时留一个 30 秒的"刚改过"标记,
:func:`put` 只在标记不在的时候写进去(一个 Lua 脚本,判与写之间不给插队)。挡的是两类事:
一是"甲请求刚按旧设计查完、还没存,乙在这中间发布了新版"——没有这个标记,甲会把旧设计
存回去并一路用到 TTL;二是发布失败回滚,那一版根本没存在过的设计被留在缓存里。
标记只活 30 秒(够长到覆盖任何在飞的请求),过后回填照旧。
* 键与标记都在 Redis 里,删一次全进程都看得见;这一层没有进程内的第二级缓存,
于是也没有"这个进程还留着旧设计"那种事。
* 再兜一层 TTL:有人绕过应用直接改库,旧设计最多活 ``OA_DESIGN_CACHE_TTL`` 秒(默认 600)。
* 没配 Redis、或带 ``OA_DESIGN_CACHE=off`` 起进程:这一层整个不参与,回库现查,
与改动前一字不差。
"""
from __future__ import annotations
import json
import os
from typing import Any
from . import cache
#: 这三张表里的任何一行都算"设计",写任何一张都要作废这一层(表名与 ``app.db``
#: 认写语句的口径一致,改动别只改一处)。
TABLES = frozenset({"oa_process", "oa_activity", "oa_route"})
#: 设计类 TTL:写操作走连接层即时作废,这一层留 TTL 只为兜住"直接改库"。
DEFAULT_TTL_SECONDS = 600.0
#: "刚改过"标记活多久:只要盖得住任何在飞请求的回填即可,留长白瞎缓存。
STALE_MARK_SECONDS = 30
#: 判标记与写键合成一趟做掉,中间不给别的设计写插队(键 1=载荷 2=本流程标记 3=全局标记)。
_PUT_IF_FRESH = """
if redis.call('EXISTS', KEYS[2]) == 1 or redis.call('EXISTS', KEYS[3]) == 1 then
return 0
end
redis.call('SETEX', KEYS[1], ARGV[2], ARGV[1])
return 1
"""
def enabled() -> bool:
"""这一层开不开:Redis 没配就当作关(:mod:`app.cache` 自己也会一路回空)。"""
raw = os.environ.get("OA_DESIGN_CACHE")
if raw is not None and raw.strip().lower() in ("0", "false", "no", "off"):
return False
return cache.configured()
def ttl_seconds() -> float:
raw = os.environ.get("OA_DESIGN_CACHE_TTL", "").strip()
if raw:
try:
return max(0.0, float(raw))
except ValueError:
return DEFAULT_TTL_SECONDS
return DEFAULT_TTL_SECONDS
def key_of(process_id: Any) -> str:
return cache.key("design", str(process_id or ""))
def _stale_key(process_id: Any = None) -> str:
"""某个流程的"刚改过"标记;不给流程主键就是"整层刚改过"那一个。"""
return cache.key("design-stale", str(process_id) if process_id else "all")
def get(process_id: Any) -> dict | None:
"""命中给出原始行那份 dict;没命中、没参与、出错都回 ``None``。"""
if not enabled():
return None
payload = cache.get_json(key_of(process_id))
return payload if isinstance(payload, dict) else None
def put(process_id: Any, payload: dict) -> bool:
"""回填一份设计,但**刚改过就不回填**(理由见模块顶部)。"""
if not enabled() or not payload:
return False
key, ttl = key_of(process_id), int(ttl_seconds())
if ttl <= 0:
return False
try:
body = json.dumps(payload, ensure_ascii=False, default=str)
except (TypeError, ValueError):
return False
def run(cli: Any) -> Any:
try:
return cli.eval(_PUT_IF_FRESH, 3, key, _stale_key(process_id), _stale_key())
except Exception: # noqa: BLE001 - Redis 不认 eval:退回"先看标记再写"
if cli.exists(_stale_key(process_id)) or cli.exists(_stale_key()):
return 0
cli.setex(key, ttl, body)
return 1
return bool(cache.command("回填设计", run, 0))
def invalidate(process_id: Any = None) -> int:
"""丢掉一个流程(或整层)的设计,并留下"刚改过"的标记挡住在飞请求的回填。"""
if not cache.configured():
return 0
if process_id:
removed = cache.delete(key_of(process_id))
cache.set_value(_stale_key(process_id), "1", STALE_MARK_SECONDS)
else:
removed = cache.delete_prefix(cache.key("design") + ":")
cache.set_value(_stale_key(), "1", STALE_MARK_SECONDS)
return removed
def note_write(table: str, statement: str = "") -> None:
"""连接层看到一条写语句:写到设计上就把这一层删掉。
每条写语句都经过这里,所以**没写到设计时一个 Redis 请求都不许发**:先比表名,
比中了才动。表名认不出来(多表写、DDL)时退一步看语句里有没有这三张表的名字。
"""
if not cache.configured():
return
name = str(table or "").strip().lower()
if name in TABLES:
invalidate()
return
if not name and statement:
low = statement.lower()
if any(table_name in low for table_name in TABLES):
invalidate()
def clear() -> int:
"""运维与自检用:把这一层的键与标记一起丢掉。"""
removed = cache.delete_prefix(cache.key("design") + ":")
removed += cache.delete_prefix(cache.key("design-stale") + ":")
return removed