unis-oa/backend/app/cache.py

977 lines
43 KiB
Python
Raw Permalink 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.

"""跨进程共享状态:缓存、限流计数、分布式锁、失效广播(Redis 实现,没配就退回进程内)。
为什么加这一层
==============
底座原本是一条 uvicorn 进程 + 一条调度线程,于是"缓存"和"计数"这类状态悄悄长在进程内存里。
``uvicorn --workers 4``、或者两台机器挂在负载均衡后面之后,每个进程各有一份:同一个人的
Hub 权限被问四遍、每个数据源的每分钟限额被放大四倍、界面上改一次配置最慢要等
运行配置快照的周期 ``OA_CONFIG_CACHE_SECONDS`` 才轮到别的进程跟上。这一层把这些状态搬到进程外面,
并且让每一样都留着"没有 Redis 时怎么办"的退路 —— 退路就是这份代码昨天的行为:
| 能力 | 有 Redis | 没有 Redis(默认,功能一个不少) |
| --- | --- | --- |
| 外部取数结果 / Hub 令牌 / Hub 权限 / 字典选项 | 各副本共用一份 | 各进程自己一份(现状) |
| 开放接口与数据源每分钟限流 | Redis 计数器 | 查调用留痕表 ``COUNT(*)``(现状) |
| 配置与缓存失效 | 发布订阅,毫秒级跟上 | 快照 TTL 到点重读(现状 ≤2 秒) |
| 全量组织同步互斥 | 跨副本一把锁 | 进程内 ``threading.Lock``(现状) |
**Redis 是可选件,不是依赖**:本模块每个公开函数都不许把异常递给业务代码。连不上、超时、
命令报错,一律当成"这一层今天没参与"——记一次日志(同类错误一段时间内只喊一遍)、计数器
加一格,然后走老路。少一个 Redis 只是退回单进程时代的性能,不该让整个 OA 起不来,
分寸与文件存储层一致(见 :mod:`app.storageconfig`)。
刻意没往 Redis 放的东西
======================
* **审批租约与选主**(:mod:`app.service.leader`):MySQL 一行 ``UPDATE`` 就够,时钟以库为准;
换成 Redis 反而多一个故障域,见 ``docs/multi-worker-deployment.md`` 第 1 节。
* **单据编号流水**(``oa_serial_number``):编号不能重号,``SELECT ... FOR UPDATE`` 是正确答案,
Redis 计数器在没开持久化时会吞号。
* **额度账本 / 发件箱 / 事件推送**:必须不丢的业务状态,留在库里。
* **权限判定结果**:「改了角色立刻生效」是 ``deps.py`` 顶部明写的口径,不缓存。
配置
====
连接参数是**运行配置**(存在库里的 ``config:redis``,界面上保存即生效,不用重启;客户端按
取值签名自己重建):``redis_url`` 一根连接串,或者 host / port / db / username / password
五项分开填。出厂值在配置文件的 ``[redis]`` 段,``config.dev.toml`` 与 ``config.prod.toml``
都留了空位(**留空 = 不启用**,走左边那一列)。清单与中文说明见 :mod:`app.dbconfig`。
密钥只进不出:``redis_password`` 与 ``redis_url`` 是 ``secret`` 类型,接口只回"配了没有",
日志里也不写值。
"""
from __future__ import annotations
import hashlib
import json
import logging
import random
import os
import socket
import threading
import time
from contextlib import contextmanager
from typing import Any, Callable, Iterator
logger = logging.getLogger("unisoa.cache")
#: 运行配置里这一组的键名与内置默认值。**默认值一律是"不启用"**:地址留空时
#: 连 ``configured()`` 都是假,本模块对业务代码完全透明
_DEFAULTS: dict[str, Any] = {
"redis_enabled": True,
"redis_url": "",
"redis_host": "",
"redis_port": 6379,
"redis_db": 0,
"redis_username": "",
"redis_password": "",
"redis_key_prefix": "unisoa",
"redis_socket_timeout_seconds": 2,
"redis_max_connections": 32,
"redis_rate_limit_enabled": True,
"redis_broadcast_enabled": True,
}
#: 连不上或命令出错之后,这么多秒之内不再尝试建连接。没有这道闸,每一个业务请求都要
#: 先等一次 socket 超时,等于把 Redis 的一次抖动放大成整站的响应时间
UNAVAILABLE_COOLDOWN_SECONDS = 15.0
#: 错误日志的间隔:同一种错误喊一遍就够,别在日志里刷屏
ERROR_LOG_INTERVAL_SECONDS = 60.0
#: 失效广播的重连与"还没配好"轮询间隔(秒)
BUS_POLL_SECONDS = 5.0
#: 订阅线程多久醒一次看"连接还是不是当前这一份"(秒)。用轮询而不是死等消息,
#: 是为了界面上改完 Redis 配置之后一秒内就能换到新连接,而不是等老连接自己报错
BUS_TICK_SECONDS = 1.0
#: 订阅连接真的断了之后隔多久重连(秒)。比 BUS_POLL_SECONDS 短:那一条是"还没配上"
#: 时候的慢轮询,这一条是连接确实断了,该快点回来
BUS_RETRY_SECONDS = 1.0
#: 上面那个间隔在连着失败时最多退到多少秒。
#:
#: 一秒一次是给"抖一下"准备的:那种情况确实该马上回来。可 Redis 整台不在的时候(地址写错、
#: 那边没起、端口不对)就变成一秒一次 TCP 连接 + 一次失败,一直撞到进程退出——真见过:
#: 端口填错的十来分钟里,状态页的 ``errors`` 涨到六百多,日志每分钟一句"订阅失效广播断了",
#: 把真正在静默回退的那几类的账也一起搅浑了。所以连着失败就指数退避,一旦订上立刻回到 1 秒。
BUS_BACKOFF_MAX_SECONDS = 15.0
#: 缓存 TTL 的抖动比例:一批同时写进去的键不该在同一秒集体过期
TTL_JITTER_RATIO = 0.1
#: 分布式锁的最短持有时间(秒)
LOCK_MIN_TTL_SECONDS = 5.0
#: 按前缀清理时一次最多删多少键(挡住"前缀写错 => 顺手清了别人整库"这类事故)
DELETE_PREFIX_MAX = 5000
#: 一看就是连不上/口令不对的错误特征:只有这类才把整层熔断一个冷却期并换掉连接池,
#: 命令用法错误(WRONGTYPE 之类)不该顺带把缓存也关掉
_CONNECTIVITY_MARKS = ("connection", "timeout", "refused", "unreachable", "reset by peer",
"closed", "authentication", "no such host", "name or service")
#: 失效广播的频道名(真正发出去时前面还会拼上键前缀)
TOPIC_CONFIG = "config"
TOPIC_FETCH = "fetch_cache"
TOPIC_HUB_PERM = "hub_perm"
#: 写回模板(环节触发点名单)变了:见 ``service/outbox.py`` 的 ``declared_activity_ids``
TOPIC_TEMPLATES = "templates"
#: 别的副本刚往发件箱放了一条报文:让每个副本的调度线程当场起来投递,
#: 而不是等下一个轮询周期。见 ``service/outbox.py`` 的 ``wake`` / ``_mark_wake``
TOPIC_OUTBOUND = "outbound"
#: 状态页上的计数器名字
#: ``errors`` 只算"命令那一侧"的失败(缓存读写、限流、锁)——状态页与文档都按
#: "这个数在涨 = 正在静默回退"来读。订阅线程的失败另记 ``bus_errors``:那条连接订不上
#: 只意味着失效广播跟不上(最坏等一个 TTL),命令与缓存照旧好好走着,混在一个数里
#: 就会把"配置改了不生效"和"缓存没了"看成同一件事。
STATS_KEYS = ("hits", "misses", "sets", "deletes", "errors", "bus_errors", "lock_acquired",
"lock_busy", "rate_allowed", "rate_blocked", "published", "received")
# ---------------------------------------------------------------------------
# redis 包与连接:全程可能回 None,调用方的退路就是"这一层没参与"
# ---------------------------------------------------------------------------
_module: Any = None
_module_missing = False
_state = threading.RLock()
_client: Any = None
_client_signature = ""
_unavailable_until = 0.0
_last_error = ""
_last_error_at = 0.0
_error_logged_until = 0.0
_config_snapshot: dict[str, Any] = {}
_config_revision = -1
_stats: dict[str, int] = {name: 0 for name in STATS_KEYS}
def _redis() -> Any:
"""延迟导入 ``redis`` 包:没装也得起得来服务(这一层整个不参与)。"""
global _module, _module_missing
if _module is not None or _module_missing:
return _module
try:
import redis # 只在真的配了 Redis 时才需要
except ModuleNotFoundError:
_module_missing = True
logger.warning("未安装 redis 包(pip install redis),共享缓存、限流计数与分布式锁一律不启用")
return None
_module = redis
return redis
def config() -> dict[str, Any]:
"""``redis_*`` 这组运行配置的快照。按配置版本号缓存,**当只读用**。"""
global _config_snapshot, _config_revision
from . import dbconfig
revision = dbconfig.revision()
with _state:
if _config_snapshot and _config_revision == revision:
return _config_snapshot
read = {name: dbconfig.value(name, default) for name, default in _DEFAULTS.items()}
snapshot = {name: (default if read.get(name) is None else read[name]) for name, default in _DEFAULTS.items()}
with _state:
_config_snapshot, _config_revision = snapshot, revision
return snapshot
def configured() -> bool:
"""总闸开着、并且地址给了(连接串或主机名任一)。"""
cfg = config()
if not bool(cfg["redis_enabled"]):
return False
return bool(str(cfg["redis_url"]).strip() or str(cfg["redis_host"]).strip())
def rate_limit_configured() -> bool:
"""配置上想让限流计数走不走 Redis(不看连接活不活,状态页用它说明"本意")。"""
return configured() and bool(config()["redis_rate_limit_enabled"])
def broadcast_enabled() -> bool:
"""失效广播走不走 Redis(关掉或没配就只靠各自的 TTL)。"""
return configured() and bool(config()["redis_broadcast_enabled"])
def _signature(cfg: dict[str, Any]) -> str:
"""连接参数的指纹:变了就重建客户端。取哈希,免得口令进日志。"""
parts = [str(cfg["redis_url"]), str(cfg["redis_host"]), str(cfg["redis_port"]), str(cfg["redis_db"]),
str(cfg["redis_username"]), str(cfg["redis_password"]), str(cfg["redis_socket_timeout_seconds"]),
str(cfg["redis_max_connections"])]
return hashlib.sha1("|".join(parts).encode("utf-8")).hexdigest()
def _build(module: Any, cfg: dict[str, Any], *, blocking: bool = False) -> Any:
"""按配置建一个客户端。``blocking=True`` 给订阅线程用:读不许超时
(等消息本来就该一直等),建连超时照旧受配置约束。"""
timeout = max(0.5, float(cfg["redis_socket_timeout_seconds"]))
common = {
"socket_timeout": None if blocking else timeout,
"socket_connect_timeout": timeout,
"socket_keepalive": True,
"health_check_interval": 30,
"decode_responses": True,
"max_connections": max(1, int(cfg["redis_max_connections"])),
}
url = str(cfg["redis_url"]).strip()
if url:
return module.Redis.from_url(url, **common)
return module.Redis(
host=str(cfg["redis_host"]).strip() or "127.0.0.1",
port=int(cfg["redis_port"] or 6379),
db=int(cfg["redis_db"] or 0),
username=str(cfg["redis_username"]).strip() or None,
password=str(cfg["redis_password"]).strip() or None,
**common,
)
def _close_locked() -> None:
global _client, _client_signature
client, _client, _client_signature = _client, None, ""
if client is not None:
try:
client.close()
except Exception: # pragma: no cover - 关连接失败不影响换新的
logger.debug("关闭 Redis 连接失败", exc_info=True)
def reset() -> None:
"""丢掉客户端与冷却期(界面上改过 ``redis_*`` 之后调用,下一次取值就是新连接)。"""
global _unavailable_until, _config_snapshot, _config_revision, _generation
with _state:
_close_locked()
_unavailable_until = 0.0
_config_snapshot, _config_revision = {}, -1
# 订阅线程那条连接也一起换(它是独立的一个客户端,见 _bus_client_of):
# 不换的话,改了地址或口令之后它还抱着旧连接等消息,本副本就再也收不到
# 别的副本的失效通知了。只丢引用、不当场 close:正堵在这条连接上读消息的
# 线程会被 close 炸掉(ValueError: I/O operation on closed file.),
# 连接交给它自己退出的时候关,见 _bus_loop 的 finally。
_forget_bus_client()
_generation += 1
def client() -> Any:
"""当前可用的 Redis 客户端;没配、没装包、正在冷却都回 ``None``。"""
global _client, _client_signature, _unavailable_until
if not configured():
with _state:
if _client is not None:
_close_locked()
return None
if time.time() < _unavailable_until:
return None
cfg = config()
signature = _signature(cfg)
with _state:
if _client is not None and _client_signature != signature:
_close_locked()
if _client is not None:
return _client
module = _redis()
if module is None:
return None
try:
_client = _build(module, cfg)
except Exception as exc:
_note_error("建连接", exc)
return None
_client_signature = signature
logger.info("共享缓存:已连接 Redis %s", _endpoint_label(cfg))
return _client
def _endpoint_label(cfg: dict[str, Any]) -> str:
"""日志里怎么说这台 Redis:只说地址与库号,口令一律不提。"""
url = str(cfg["redis_url"]).strip()
if url:
head, _, tail = url.partition("://")
return f"{head}://{tail.split('@')[-1] if '@' in tail else tail}"
return f"{cfg['redis_host']}:{cfg['redis_port']}/{cfg['redis_db']}"
def _looks_down(exc: Exception) -> bool:
text = f"{type(exc).__name__} {exc}".lower()
return any(mark in text for mark in _CONNECTIVITY_MARKS)
def _note_error(where: str, exc: Exception, *, trip_cooldown: bool = True,
counter: str = "errors") -> None:
"""记一次失败:状态页看得到,日志按间隔去重;连接类故障顺带熔断一会儿并换掉连接池。
``trip_cooldown=False`` 给**订阅线程**用:它那条连接自己断了、或者被 :func:`reset`
换掉了,是本线程要重连的事,跟"命令用的那台 Redis 还不活着"是两码事。让订阅线程
去拉闸,会变成"Redis 配置一改,全站缓存跟着冷却 15 秒"(真踩过:改完配置保存,
紧接着的字典读全部落回数据库)。
"""
global _last_error, _last_error_at, _error_logged_until, _unavailable_until
_stats[counter] += 1
_last_error, _last_error_at = f"{where}:{type(exc).__name__}: {exc}", time.time()
now = time.time()
if now >= _error_logged_until:
_error_logged_until = now + ERROR_LOG_INTERVAL_SECONDS
if trip_cooldown and _looks_down(exc):
logger.warning("共享缓存%s失败(%s),按没有 Redis 处理,%s 秒内不再重试;同错不重复刷日志",
where, exc, int(UNAVAILABLE_COOLDOWN_SECONDS))
else:
# 没拉全局闸,就不该说"不再重试"这种话:订阅线程那一类错误它自己会重连
logger.warning("共享缓存%s失败(%s),这一笔按没有 Redis 处理;同错不重复刷日志", where, exc)
if trip_cooldown and _looks_down(exc):
_unavailable_until = now + UNAVAILABLE_COOLDOWN_SECONDS
with _state:
_close_locked()
def _run(where: str, action: Callable[[Any], Any], fallback: Any = None) -> Any:
"""跑一条命令。Redis 没参与或出错都回 ``fallback``,**永不抛异常**。"""
instance = client()
if instance is None:
return fallback
try:
return action(instance)
except Exception as exc:
_note_error(where, exc)
return fallback
def command(where: str, action: Callable[[Any], Any], fallback: Any = None) -> Any:
"""要自己发一条非常规命令(Lua 脚本、``SETEX`` 这类)的调用方走这里。
与 :func:`_run` 同一条口径:没参与、出错都回 ``fallback``,**永不把 Redis 的毛病
弄成一次业务失败**。放出来是为了别的项目模块不去抓 ``cache._run`` 那根私有把手。
"""
return _run(where, action, fallback)
# ---------------------------------------------------------------------------
# 键与值:缓存
# ---------------------------------------------------------------------------
def key(*parts: Any) -> str:
"""拼一个带前缀的键:``key("fetch", code, sha)`` -> ``unisoa:fetch:CODE:SHA``。
前缀是运行配置 ``redis_key_prefix``:一台 Redis 给多个环境共用时靠它隔开,
免得测试档一次 ``FLUSHDB`` 把生产的缓存一起带走。
"""
prefix = str(config()["redis_key_prefix"]).strip().strip(":") or "unisoa"
tail = ":".join(str(part) for part in parts if str(part if part is not None else "").strip())
return f"{prefix}:{tail}" if tail else prefix
def _jitter(seconds: float) -> int:
"""给 TTL 加一点抖动,别让同一批键同一秒集体过期去挤同一条上游。"""
ttl = int(max(1, seconds))
if ttl < 10:
return ttl
return int(ttl * (1 + random.uniform(0, TTL_JITTER_RATIO)))
def get(name: str) -> str | None:
"""读一个字符串值;没参与、没命中、出错都回 ``None``。"""
value = _run("读", lambda cli: cli.get(name))
_stats["hits" if value is not None else "misses"] += 1
return value
def set_value(name: str, value: str, ttl_seconds: float) -> bool:
"""写一个字符串值并设过期时间;``ttl_seconds`` <= 0 时什么都不写。"""
if ttl_seconds <= 0:
return False
ok = _run("写", lambda cli: cli.set(name, value, ex=_jitter(ttl_seconds)))
_stats["sets"] += 1 if ok else 0
return bool(ok)
def get_json(name: str) -> Any:
"""读一个 JSON 值。约定**不缓存假值**,所以命中与没命中都分得清。"""
raw = get(name)
if raw is None:
return None
try:
return json.loads(raw)
except ValueError:
_note_error("解 JSON", ValueError(f"键 {name} 里装的不是合法 JSON"))
return None
def get_many_json(names: list[str]) -> dict[str, Any]:
"""一次往返读一批 JSON 键:``MGET`` 就是为这件事准备的。
逐个 :func:`get_json` 是"一个键一趟往返"。字典选项一次要读八个键,串起来就是
七十多毫秒的纯网络时间(本部署到 Redis 一趟 9ms,实测 ``/draft/types`` 138ms
里 105ms 花在这八趟上)。这里一趟问完。
没参与、出错、没命中、装的不是合法 JSON 的键**都不出现在结果里**——调用方
按"没命中、自己去算"处理即可,口径与 :func:`get_json` 回 ``None`` 完全一样。
"""
keys: list[str] = []
for raw in names:
name = str(raw or "")
if name and name not in keys:
keys.append(name)
if not keys:
return {}
values = _run("批量读", lambda cli: cli.mget(keys))
if not values:
# 没参与或出错:整批都当没命中,各去现算(与 get 回 None 同一口径)
_stats["misses"] += len(keys)
return {}
out: dict[str, Any] = {}
for name, raw in zip(keys, values):
if raw is None:
continue
try:
out[name] = json.loads(raw)
except ValueError:
_note_error("解 JSON", ValueError(f"键 {name} 里装的不是合法 JSON"))
_stats["hits"] += len(out)
_stats["misses"] += len(keys) - len(out)
return out
def set_json(name: str, value: Any, ttl_seconds: float) -> bool:
if ttl_seconds <= 0:
return False
try:
payload = json.dumps(value, ensure_ascii=False, default=str)
except (TypeError, ValueError) as exc:
_note_error("编 JSON", exc)
return False
return set_value(name, payload, ttl_seconds)
def get_or_build(name: str, ttl_seconds: float, producer: Callable[[], Any]) -> Any:
"""读缓存 -> 没有就现算 -> 算出来的东西共享存着。算出来是空的就不存(下次再算)。
``producer`` 抛的异常照原样递出去:那是业务失败,不是这一层的失败。
"""
if ttl_seconds <= 0:
return producer()
hit = get_json(name)
if hit is not None:
return hit
fresh = producer()
if fresh:
set_json(name, fresh, ttl_seconds)
return fresh
def delete(*names: str) -> int:
names = [name for name in names if name]
if not names:
return 0
removed = _run("删", lambda cli: int(cli.delete(*names) or 0), 0)
_stats["deletes"] += int(removed or 0)
return int(removed or 0)
def delete_prefix(prefix: str, *, chunk: int = 500) -> int:
"""按前缀清一批键(改了数据源配置就把它那份缓存整体丢掉)。
用 ``SCAN`` 不用 ``KEYS``:后者会堵住服务。带 ``DELETE_PREFIX_MAX`` 上限,
挡的是"前缀拼错 => 顺手清了别人一批键"这类事故。
"""
pattern = f"{prefix}*"
def run(cli: Any) -> int:
removed, batch = 0, []
for cursor in cli.scan_iter(match=pattern, count=chunk * 2):
batch.append(cursor)
if len(batch) >= chunk:
removed += int(cli.delete(*batch) or 0)
batch = []
if removed >= DELETE_PREFIX_MAX:
logger.warning("共享缓存:按前缀 %s 清理已达上限 %d 个键就停了,检查一下前缀是不是拼错",
prefix, DELETE_PREFIX_MAX)
break
if batch:
removed += int(cli.delete(*batch) or 0)
return removed
removed = int(_run("按前缀删", run, 0) or 0)
_stats["deletes"] += removed
return removed
# ---------------------------------------------------------------------------
# 限流计数
# ---------------------------------------------------------------------------
def allow(name: str, limit: int, window_seconds: int = 60) -> tuple[bool | None, int, int]:
"""固定窗口计数:这一段时间窗内还能不能再过一次。
返回 ``(放行吗, 本窗口已用几次, 建议等待秒数)``。**第一个位置可能是 ``None``**,
意思是"这一层没答上"(没配、正在冷却、命令出错),调用方必须去问自己的退路 ——
把它当"放行"就是"Redis 一抖,限额没了"。业务代码请直接用 :func:`limit_check`,
它把退路一起办了。
"""
limit = int(limit or 0)
window = max(1, int(window_seconds or 60))
if limit <= 0:
return True, 0, 0
bucket = int(time.time() // window)
counter_key = key("ratelimit", name, bucket)
def run(cli: Any) -> tuple[bool, int, int]:
pipe = cli.pipeline()
pipe.incr(counter_key)
pipe.expire(counter_key, window + 1)
count = int(pipe.execute()[0] or 0)
return count <= limit, count, max(1, window - int(time.time() % window))
answered = _run("限流计数", run)
if answered is None:
return None, 0, 0
allowed, count, retry_after = answered
_stats["rate_allowed" if allowed else "rate_blocked"] += 1
return bool(allowed), int(count), int(retry_after)
def limit_check(name: str, limit: int, fallback_counter: Callable[[], int],
*, window_seconds: int = 60) -> tuple[bool, int]:
"""限流的一站式问法:**能问 Redis 就问 Redis,问不到就调 ``fallback_counter()`` 数库**。
返回 ``(放行吗, 建议等待秒数)``。这么包一层是因为"退路"最容易写错的地方就在限流上:
Redis 正在冷却时如果直接放行,"每分钟 300 次"会变成那 15 秒里的"不限次"。
``fallback_counter`` 就是接 Redis 之前的那句 ``COUNT(*)``,只在 Redis 没参与时调用。
"""
limit = int(limit or 0)
if limit <= 0:
return True, 0
if rate_limit_configured():
allowed, _used, retry_after = allow(name, limit, window_seconds)
if allowed is not None:
return allowed, retry_after if not allowed else 0
logger.debug("限流计数没答上(%s),这一格改用本系统自己的计数口径", name)
return int(fallback_counter() or 0) < limit, 0
# ---------------------------------------------------------------------------
# 分布式锁
# ---------------------------------------------------------------------------
#: 只释放自己那一把:先比 token 再删,否则超时之后会把别人刚拿到的锁删掉
_RELEASE_SCRIPT = "if redis.call('GET', KEYS[1]) == ARGV[1] then return redis.call('DEL', KEYS[1]) else return 0 end"
def holder_id() -> str:
"""本进程的标识(``主机名:进程号``),写进锁的值里,排障时看得出是谁占着。"""
return f"{socket.gethostname()}:{os.getpid()}"
def try_lock(name: str, *, ttl_seconds: float) -> str:
"""抢一把跨副本的锁;拿到了返回 token(交还时用),拿不到返回空串。
**Redis 没参与时返回一个 ``local:`` 开头的非空 token**:语义退回单进程时代,
调用方自己那道 ``threading.Lock`` 仍然挡着同进程内的重复。所以这把锁只适合
"多副本同时做会白跑一趟 / 会重复外呼"的场合;**真的一次都不能重复**的动作
(发消息、扣款、发凭证)必须另有库里的唯一键或租约兜着,别把正确性压在一个
随时可能重启的缓存上。
``ttl_seconds`` 是崩溃兜底:进程被 ``kill -9`` 时锁最多留这么久就自己没了。
"""
token = f"{holder_id()}-{time.time_ns()}"
lock_key = key("lock", name)
instance = client()
if instance is None:
return f"local:{token}" # 没有对手:按"拿到了"处理,见上面
ttl = max(LOCK_MIN_TTL_SECONDS, float(ttl_seconds))
try:
got = instance.set(lock_key, token, nx=True, ex=int(ttl) + 1)
except Exception as exc:
_note_error("取分布式锁", exc)
return f"local:{token}" # 同上:出错就当成没有 Redis
_stats["lock_acquired" if got else "lock_busy"] += 1
return token if got else ""
def release_lock(name: str, token: str) -> None:
"""交还锁。**只交还自己那一把**:token 对不上就不动,免得把自己超时之后别人
刚拿到的锁删掉。释放失败不管(等它自己过期),绝不抛异常。"""
if not token or token.startswith("local:"):
return
def run(cli: Any) -> None:
cli.eval(_RELEASE_SCRIPT, 1, key("lock", name), token)
_run("释放分布式锁", run, None)
def force_release(name: str) -> bool:
"""不看 token 直接把锁删掉,回**删之前有没有人拿着**(界面上"终止同步"用)。
正常收尾一律走 :func:`release_lock`(只交还自己那一把)。这里要的是另一件事:
拿锁的那一趟已经不在了(进程被杀、线程卡在没人回话的上游上),管理员说"别等
``ttl`` 到点,现在放行"。误删的代价是下一趟可能和还没咽气的那一趟并行写一遍,
值不值由调用方判断,这一层只管把键删掉。
"""
def run(cli: Any) -> bool:
return bool(cli.delete(key("lock", name)))
return bool(_run("强制释放分布式锁", run, False))
@contextmanager
def cluster_lock(name: str, *, ttl_seconds: float) -> Iterator[bool]:
"""跨进程/跨副本互斥的上下文写法,``yield`` 出来的是**有没有拿到锁**。
规矩与 :func:`try_lock` 一样(Redis 没参与就算拿到),适合"这一段跑完就完了"的
场合;调用方自己已经有 ``try/finally`` 结构的话,直接用 :func:`try_lock` /
:func:`release_lock` 更顺手。
"""
token = try_lock(name, ttl_seconds=ttl_seconds)
try:
yield bool(token)
finally:
release_lock(name, token)
def lock_holder(name: str) -> str:
"""这把锁现在在谁手里(进程标识);没人拿或 Redis 没参与回空串。界面状态用。"""
return str(_run("读锁持有者", lambda cli: cli.get(key("lock", name)), "") or "")
def locked(name: str) -> bool:
"""这把锁现在被占着吗(本进程自己拿着时也是 True)。"""
return bool(lock_holder(name))
# ---------------------------------------------------------------------------
# 失效广播:改了配置/缓存,别的副本立刻跟上
# ---------------------------------------------------------------------------
_handlers: dict[str, list[Callable[[Any], None]]] = {}
_bus_thread: threading.Thread | None = None
_bus_stop = threading.Event()
#: 订阅线程**专用**的客户端与它自己的连接池。不共用命令那个:``reset()`` 一关那个池子,
#: 正堵在 ``get_message`` 里的订阅就跟着炸(真踩过:界面上保存一次 Redis 配置,之后
#: 本副本再也收不到失效通知),而且订阅连接是独占的,混在命令连接池里还会一格一格漏。
_bus_client: Any = None
#: 订阅线程当前真的订阅上了吗(只在订阅线程与 :func:`_forget_bus_client` 里改)
_bus_subscribed = False
#: 客户端换代号::func:`reset` 每调一次 +1,订阅线程发现自己对的是上一代就重连
_generation = 0
def bus_subscribed() -> bool:
"""订阅线程这会儿真的挂在频道上吗。
与 :func:`bus_running` 是两件事:那个只说线程活着。Redis 配了却连不上的时候,
线程活得好好的、每秒重连一次、一条消息也收不到 —— ``bus_running`` 一路是 ``true``,
看上去一切正常。状态页要报的是这一项。
"""
return _bus_subscribed
def _forget_bus_client() -> None:
"""把订阅连接从全局摘掉,但**不关**它。顺带说一声"现在没订上了"。正堵在这条连接上 ``get_message`` 的线程
会自己退出来关(调用方不许替它关:那样会把那次读炸掉,本副本之后再也收不到
失效通知——真踩过)。调用方随后要让 ``_generation`` +1,线程才发现自己过时了。
"""
global _bus_client, _bus_subscribed
_bus_subscribed = False
with _state:
_bus_client = None
def _retire_bus_client(instance: Any) -> None:
"""订阅线程收工时关掉自己那一条连接。只关自己这一代:全局那一格可能已经被
:func:`reset` 换成了新连接,顺手关掉会把刚建好的订阅弄死。"""
global _bus_client
with _state:
if _bus_client is instance:
_bus_client = None
try:
instance.close()
except Exception: # pragma: no cover - 关掉旧连接失败不影响重建
logger.debug("关闭订阅客户端失败", exc_info=True)
def _bus_client_of() -> Any:
"""订阅线程用的客户端(读不超时、连接池独立)。建不出来回 ``None``,下一轮再试。"""
global _bus_client
with _state:
if _bus_client is not None:
return _bus_client
module = _redis()
if module is None:
return None
try:
_bus_client = _build(module, config(), blocking=True)
except Exception as exc:
_note_error("建订阅连接", exc, trip_cooldown=False)
return None
return _bus_client
def channel() -> str:
return key("bus")
def watch(topic: str, handler: Callable[[Any], None]) -> None:
"""登记一个"别的进程说某某变了"的回调。
**回调必须幂等且便宜**(失效一个缓存、把一个时间戳归零这类):它可能连着本进程自己
发的那一条一起收到,也可能因为重连重复收到。别在里面读写数据库、开事务。
"""
_handlers.setdefault(topic, []).append(handler)
def publish(topic: str, data: Any = None) -> bool:
"""往广播频道发一条。Redis 没参与时静默回 ``False``(各自的 TTL 兜底)。"""
if not broadcast_enabled():
return False
payload = json.dumps({"topic": topic, "data": data}, ensure_ascii=False, default=str)
sent = _run("发广播", lambda cli: int(cli.publish(channel(), payload) or 0), 0)
_stats["published"] += 1 if sent else 0
return bool(sent)
def _dispatch(topic: str, data: Any) -> None:
_stats["received"] += 1
for handler in list(_handlers.get(topic, [])):
try:
handler(data)
except Exception: # 回调出错不能拖垮订阅线程
logger.exception("共享缓存:失效广播回调失败 topic=%s", topic)
def _handle_raw(raw: Any) -> None:
try:
message = json.loads(raw) if isinstance(raw, (str, bytes)) else {}
except ValueError:
return
if not isinstance(message, dict):
return
topic = str(message.get("topic") or "")
if topic:
_dispatch(topic, message.get("data"))
def _is_read_timeout(exc: Exception) -> bool:
"""是不是"等消息等到读超时"——订阅线程里这是常态,不是故障。"""
name = type(exc).__name__.lower()
return "timeout" in name and "connect" not in name
def _bus_loop() -> None:
"""订阅线程:断了重连,没配好就安静轮询。它一死,别的进程就收不到本进程的失效消息。"""
global _bus_subscribed
retry = BUS_RETRY_SECONDS
while not _bus_stop.is_set():
instance = _bus_client_of()
if instance is None or not broadcast_enabled():
_bus_stop.wait(BUS_POLL_SECONDS)
continue
generation = _generation
pubsub = None
try:
pubsub = instance.pubsub(ignore_subscribe_messages=True)
pubsub.subscribe(channel())
if not _bus_subscribed:
logger.info("共享缓存:已订阅失效广播频道 %s", channel())
_bus_subscribed = True
retry = BUS_RETRY_SECONDS # 订上了就把退避归零
while not _bus_stop.is_set() and _generation == generation:
try:
message = pubsub.get_message(timeout=BUS_TICK_SECONDS)
except Exception as exc:
if _is_read_timeout(exc):
continue # 这一秒没消息而已,别记成故障
raise
if message is None or message.get("type") != "message":
continue # 超时醒一次,顺便检查上面那条
_handle_raw(message.get("data"))
except Exception as exc:
# 只算订阅线程自己的账:不拉全局闸、不进 errors(见 _note_error 的 trip_cooldown)
# where 是个名词短语:_note_error 会拼成"共享缓存{where}失败(原因)"
_note_error("订阅失效广播(这条只影响失效广播,本线程自己会重连,命令与缓存照旧)",
exc, trip_cooldown=False, counter="bus_errors")
_forget_bus_client() # 这条不要了,下一轮重新建一条(顺带把 bus_subscribed 落成假)
_bus_stop.wait(retry)
# 连着失败就退着试:Redis 整台不在时一秒一次会撞到天荒地老
retry = min(BUS_BACKOFF_MAX_SECONDS, retry * 2)
finally:
if pubsub is not None:
try:
pubsub.close()
except Exception: # pragma: no cover
logger.debug("关闭订阅连接失败", exc_info=True)
# 过代的、出错的那条连接由本线程关;如果全局那一格还是它(正常续用),
# 就别关,下一轮接着用同一条
if _generation != generation or _bus_client is not instance:
_retire_bus_client(instance)
def start_bus() -> bool:
"""起订阅线程(幂等)。没配 Redis 就不起,省一条白跑的线程。"""
global _bus_thread
with _state:
if _bus_thread is not None and _bus_thread.is_alive():
return True
if not broadcast_enabled():
return False
_bus_stop.clear()
_bus_thread = threading.Thread(target=_bus_loop, name="unisoa-cache-bus", daemon=True)
_bus_thread.start()
return True
def stop_bus() -> None:
"""停订阅线程(进程退出时调用)。"""
global _generation, _bus_subscribed
_bus_subscribed = False
_bus_stop.set()
with _state:
_generation += 1 # 让堵在 get_message 里的线程下一轮就醒
thread = _bus_thread
# 等它自己退出并关掉那条连接(最多一个 BUS_TICK_SECONDS),主线程不替它关
if thread is not None and thread.is_alive():
thread.join(timeout=BUS_TICK_SECONDS + BUS_RETRY_SECONDS)
def bus_running() -> bool:
return _bus_thread is not None and _bus_thread.is_alive()
# ---------------------------------------------------------------------------
# 状态与探活
# ---------------------------------------------------------------------------
def ping() -> tuple[bool, str]:
"""连不连得上,外加一句人话(状态页与启动日志用)。"""
cfg = config()
if not bool(cfg["redis_enabled"]):
return False, "已关闭(配置项「启用 Redis」是关的)"
if not (str(cfg["redis_url"]).strip() or str(cfg["redis_host"]).strip()):
return False, "未配置:地址留空,共享缓存、分布式锁与失效广播都不启用"
if _module_missing:
return False, "未安装 redis 包(pip install redis)"
if _unavailable_until > time.time():
return False, f"暂时跳过:上一次失败后 {int(_unavailable_until - time.time())} 秒内不再重试({_last_error})"
if _run("探活", lambda cli: bool(cli.ping()), False):
return True, "连接正常"
return False, _last_error or "连不上,详情看后端日志"
def server_info() -> dict[str, Any]:
"""服务器自报家门(版本、运行模式、最大内存策略)。只挑没有敏感信息的几项。"""
info = _run("读服务器信息", lambda cli: cli.info(section="server"), {}) or {}
if not isinstance(info, dict):
return {}
wanted = ("redis_version", "redis_mode", "os", "uptime_in_seconds", "maxmemory_policy", "database")
return {name: info[name] for name in wanted if name in info}
def summary() -> dict[str, Any]:
"""状态页里那一小块:配了什么、用没用上、用得多不多。**不探活**,
``GET /api/v1/system/info`` 每次都拼上它,不该顺带打两次 Redis。"""
cfg = config()
return {
"enabled": bool(cfg["redis_enabled"]),
"configured": configured(),
"endpoint": _endpoint_label(cfg) if configured() else "",
"key_prefix": str(cfg["redis_key_prefix"]),
# 一律报"配置本意",不调 client():拼这块时不该顺手探一次 Redis
"rate_limit_enabled": rate_limit_configured(),
"broadcast_enabled": broadcast_enabled(),
"bus_running": bus_running(),
# 线程活着 != 订上了:配了 Redis 却连不上的那段时间就是前者真、后者假
"bus_subscribed": bus_subscribed(),
"stats": dict(_stats),
"last_error": _last_error,
}
def status_report() -> dict[str, Any]:
"""``GET /api/v1/system/redis`` 的返回体:配了什么、连不连得上、用得多不多。
口令与连接串永不外泄,只回"配了没有"。
"""
cfg = config()
reachable, message = ping()
return {
"enabled": bool(cfg["redis_enabled"]),
"configured": configured(),
"active": reachable,
"message": message,
"endpoint": _endpoint_label(cfg) if configured() else "",
"url_set": bool(str(cfg["redis_url"]).strip()),
"password_set": bool(str(cfg["redis_password"]).strip()),
"host": str(cfg["redis_host"]),
"port": int(cfg["redis_port"] or 6379),
"db": int(cfg["redis_db"] or 0),
"username": str(cfg["redis_username"]),
"key_prefix": str(cfg["redis_key_prefix"]),
# 配置本意;连不上时靠上面的 active / unavailable_seconds_left 说明
"rate_limit_enabled": rate_limit_configured(),
"broadcast_enabled": broadcast_enabled(),
"bus_running": bus_running(),
# 这两个要分开看:bus_running 只说线程在跑,bus_subscribed 才说消息进得来。
# "broadcast_enabled=true + bus_running=true + bus_subscribed=false"
# 就是"配了但连不上",靠 bus_errors 与 last_error 说出原因
"bus_subscribed": bus_subscribed(),
"channel": channel() if configured() else "",
"topics": sorted(_handlers),
"stats": dict(_stats),
"server": server_info() if reachable else {},
"last_error": {"message": _last_error, "at": _last_error_at} if _last_error else {},
"unavailable_seconds_left": max(0, int(_unavailable_until - time.time())),
}
def test(**overrides: Any) -> dict[str, Any]:
"""拿一组**还没保存**的参数试一轮:连接 -> 读写 -> 计数 -> 锁。
界面上填 Redis 表单时先试再存,省得"存了才发现地址写错,而这一层永远静默回退"。
临时连接用完就关,不碰正在用的那个客户端,也不写库。
``overrides`` 收配置项名,``redis_host`` 与简写 ``host`` 都认;没出现的项沿用
当前生效值(所以只想试换个口令时不用把整张表单重抄一遍)。
"""
cfg = dict(config())
for name, value in overrides.items():
if value in (None, ""):
continue # 与运行配置一样的规矩:留空 = 不改这一项,沿用已生效的值
item_name = name if name in _DEFAULTS else f"redis_{name}"
if item_name in _DEFAULTS:
cfg[item_name] = value
else:
logger.warning("Redis 探活收到不认识的参数 %s,已忽略(拼错时别静默按老配置试)", name)
module = _redis()
if module is None:
return {"ok": False, "message": "未安装 redis 包(pip install redis)", "steps": []}
steps: list[dict[str, Any]] = []
probe = None
try:
probe = _build(module, cfg)
probe.ping()
steps.append({"step": "连接", "ok": True, "value": _endpoint_label(cfg)})
marker = key("probe", f"{time.time_ns()}")
probe.set(marker, "1", ex=10)
read_back = probe.get(marker)
probe.delete(marker)
steps.append({"step": "读写", "ok": read_back == "1", "value": read_back or "读不到刚写进去的键"})
probe_counter = key("probe", "counter", f"{time.time_ns()}")
probe.incr(probe_counter)
probe.expire(probe_counter, 10)
steps.append({"step": "计数", "ok": True, "value": int(probe.get(probe_counter) or 0)})
probe.delete(probe_counter)
probe_lock = key("probe", "lock")
got = bool(probe.set(probe_lock, "probe", nx=True, ex=10))
if got:
probe.delete(probe_lock)
steps.append({"step": "分布式锁", "ok": got, "value": "拿到并已释放" if got else "拿不到(已被别的进程持有?)"})
info = probe.info(section="server") or {}
return {"ok": all(step["ok"] for step in steps), "message": "全部通过", "steps": steps,
"server": {name: info.get(name) for name in
("redis_version", "redis_mode", "maxmemory_policy", "database") if name in info}}
except Exception as exc:
return {"ok": False, "message": f"{type(exc).__name__}: {exc}", "steps": steps}
finally:
if probe is not None:
try:
probe.close()
except Exception: # pragma: no cover
logger.debug("关闭探活连接失败", exc_info=True)