unis-oa/backend/app/parallel.py

145 lines
6.5 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.

"""把一个请求里互不相干的只读查询并发跑掉,别让数据库往返在一条线上排队。
为什么加这一层
==============
库里只有几百行时问不出问题,量法换成"数语句条数"之后问题就露出来了:本部署的库在
另一台机器上,**任何一条 SQL 都要 17–21ms**,快慢完全取决于一个请求要排几次队,
跟语句本身写了什么关系不大。首页一次要问 18 条(13 块面板各查各的 + 计数 + 权限),
串行就是 400ms 上下;单据详情同理,12 条独立加载串成 220ms。这些块之间没有依赖,
串行纯属排队。
怎么保证不改行为
================
* **只并发只读块**。每个块拿到的是自己那条新 ``Session``,块内查完就地序列化成
能直接进 JSON 的值(``dict`` / ``list``),**不把 ORM 对象递到块外面**——递出去
等于把它连同那条 Session 的生命周期一起漏给调用方,主 Session 里那些
``lazy`` 关系、``expired`` 状态会当场变成 ``DetachedInstanceError``。
* **顺序不影响结果**。返回值按调用方给的键顺序装,块谁先跑完不参与拼装。
* **异常照原样往外抛**,串行时这个块报错、并发后也报错,不吞、不改状态码。
* **不碰写**。块里不许 ``add`` / ``commit``;要写就回主线写,别指望两个事务的顺序。
* 引导项 ``parallel_blocks`` 关掉、或这一组只剩一块时,直接在**调用方自己的
Session** 上按原顺序跑,一条连接都不多占,退化成改动前的样子。
连接数
======
块用的连接和主线程是同一个连接池,所以并发会把"一个请求占几条连接"从 1 抬到
1 + ``parallel_workers``。池子相应放大(见 :mod:`app.db`),MySQL 侧
``max_connections`` 要留得下 ``进程数 × 池上限``。
"""
from __future__ import annotations
import contextvars
import logging
import os
import queue
import threading
import time
from collections.abc import Callable, Mapping
from concurrent.futures import ThreadPoolExecutor
from typing import Any
from sqlalchemy.orm import Session
from .config import settings
from .db import SessionLocal
logger = logging.getLogger("unisoa.parallel")
_executor: ThreadPoolExecutor | None = None
_executor_lock_guard = object()
def blocks_enabled() -> bool:
"""这一档开不开。引导项之外再认一个环境变量,方便临时按进程关掉。"""
raw = os.environ.get("OA_PARALLEL_BLOCKS")
if raw is not None:
return raw.strip().lower() not in ("0", "false", "no", "off")
return bool(getattr(settings, "parallel_blocks", True))
def _workers() -> int:
"""一个请求最多同时占几条连接(= 同时领活的线程数)。"""
try:
return max(1, int(getattr(settings, "parallel_workers", 6) or 6))
except (TypeError, ValueError):
return 6
def _pool() -> ThreadPoolExecutor:
"""进程内共用一个有界线程池:线程创建是有成本的,首页每秒都在调这里。"""
global _executor
if _executor is None:
# 池子比"一个请求的并发上限"宽三倍:否则两个用户同时开首页会互相把对方
# 排在外面,反而比串行还慢。三倍是"三个请求同时在拼首页"这一档。
_executor = ThreadPoolExecutor(max_workers=_workers() * 3, thread_name_prefix="oa-block")
return _executor
def gather(db: Session, blocks: Mapping[str, Callable[[Session], Any]]) -> dict[str, Any]:
"""并发跑完 ``blocks`` 里每一块,返回 ``{键: 块的返回值}``,顺序与 ``blocks`` 一致。
每块的签名是 ``fn(session) -> 可 JSON 序列化的值``,它只能用传进去的那个 session,
也只能回序列化后的值(详见模块文档串里那几条约束)。关掉这一档、或只有一块时,
直接用调用方的 ``db`` 原地跑,行为与并发前完全一致。
Session 是**每条工作线程一条**、从任务队列里领活干,不是一块一条:一块一条看着
清楚,代价是每条都要付一次连接探活和关闭时的回滚(本机到库一个来回 17–21ms),
首页十三块就是白付十三份,实测一块从 20ms 涨到 80ms,并发省下来的时间全赔在
这里。改成一线程一条之后,这笔固定开销只剩 ``min(块数, 线程上限)`` 份。
"""
items = list(blocks.items())
if not items:
return {}
if len(items) == 1 or not blocks_enabled():
return {key: fn(db) for key, fn in items}
pending: queue.Queue = queue.Queue()
for item in items:
pending.put(item)
results: dict[str, Any] = {}
errors: dict[str, BaseException] = {}
bail = threading.Event()
guard = threading.Lock()
runners = min(len(items), _workers())
# 线程里也要看得见请求上下文(日志里的请求标识那类)。Context 对象一次只能被
# 一个线程进入,所以趁还在请求线程时按线程数各拷一份,一线程一份。
contexts = [contextvars.copy_context() for _ in range(runners)]
def work(context: contextvars.Context) -> None:
session = SessionLocal()
try:
while not bail.is_set():
try:
key, fn = pending.get_nowait()
except queue.Empty:
break
try:
value = context.run(fn, session)
except BaseException as exc: # noqa: BLE001 - 记下第一现场,回请求线程再抛
with guard:
errors.setdefault(key, exc)
bail.set() # 有一块已经失败,剩下的不必再捞
break
with guard:
results[key] = value
finally:
session.close()
pool = _pool()
# 等这几条线程全部收工:work() 自己把块的异常收进 errors,future 只管"跑完了没有"
futures = [pool.submit(work, contexts[index]) for index in range(runners)]
for future in futures:
try:
future.result()
except BaseException as exc: # noqa: BLE001 - 线程自己出问题时也算这一块失败
with guard:
errors.setdefault("_runner", exc)
if errors:
# 按调用方给的键顺序挑第一个失败的,报错口径和串行时一致
for key, _ in items:
if key in errors:
raise errors[key]
raise errors[next(iter(errors))]
return {key: results[key] for key, _ in items}