unis-oa/backend/scripts/perf_guard.py

432 lines
20 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.

#!/usr/bin/env python3
"""改完代码之后的自检:功能没被改坏,性能也没被改回去。
写路径的端到端不在这里,用 ``python3 -m advance_cash --run``(它跑完自己删单)。
本脚本只发 GET 与三个只读 POST(设计器试算 / 审批体检 / 审批人预览),不建单、不改配置;
只有个别接口按它自己的业务会顺手记一笔(打开文档加一次浏览量、打开详情记一条已读),
那与人在界面上点开一次是一样的,也正因如此这几个接口的报文本来就在变,扫描会把它们
单独报成"本身会变"而不是故障。
cd backend
python3 scripts/perf_guard.py # 只读扫描 + 分页冒烟 + 只读 POST 冒烟 + 语句数对账
python3 scripts/perf_guard.py --ab # 再加逐字节 A/B:读缓存开与关必须给同一份报文
python3 scripts/perf_guard.py --save-budget # 把这次的每接口语句数记成基线
python3 scripts/perf_guard.py --strict # 超过基线就退出码 1(发版前、CI 里用)
python3 scripts/perf_guard.py --user 437 # 换个人跑(默认 1,能看到所有接口)
python3 scripts/perf_guard.py --only org # 只跑路径里带 org 的接口
四件事
======
1. **只读接口扫描**:从路由表把所有 GET 捞出来,能拼出样例参数的逐个打两遍(冷 / 热),
记状态码与只读语句条数。5xx 一律算坏;4xx 只是样例参数对不上真数据,报出来不算坏。
2. **逐字节 A/B**(``--ab``):同一接口在「关读缓存」「开读缓存」下各打两遍。先用关缓存
那两遍判这个接口稳不稳(打开详情记一条已读、文档加一次浏览量,这类本来一直在变),
只在稳的接口上判开缓存有没有把报文改一个字。动过 :mod:`app.readcache` 的调用点就跑它。
3. **分页与只读 POST 冒烟**:翻页越界、页大小、关键字过滤这些边界,加上设计器那三个
只读 POST —— 它们不在 GET 扫描里,最容易漏。
4. **语句条数基线**:库在另一台机器上时慢的几乎从来不是某条 SQL 写得慢,而是这一个
接口排了几次队,所以「每个接口几条语句」要当回归线守着。基线记在
``scripts/perf_budget.json``;加了新功能确实要多问几条,就 ``--save-budget`` 重记一份。
退出码 0 = 全绿;非 0 = 有接口 5xx、报文被缓存改了字、分页字段不对,
或 ``--strict`` 下语句条数超线。
"""
from __future__ import annotations
import argparse
import hashlib
import json
import logging
import os
import re
import sys
import time
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
# 自检不该顺手起调度器、也不该改表结构:这两条要在导入应用之前就定下来。
os.environ.setdefault('OA_SCHEDULER', 'off')
os.environ.setdefault('OA_AUTO_CREATE_SCHEMA', 'false')
from fastapi.routing import APIRoute # noqa: E402
from sqlalchemy import event, select # noqa: E402
from starlette.testclient import TestClient # noqa: E402
from app import models, readcache # noqa: E402
from app.config import settings # noqa: E402
from app.db import SessionLocal, engine # noqa: E402
from app.main import app # noqa: E402
from app.security import create_access_token # noqa: E402
#: 一次扫描要打上百个接口,逐条 INFO 请求日志会把结果埋了;出错照报(WARNING 及以上)。
for _logger_name in ('httpx', 'httpcore', 'unisoa', 'unisoa.error', 'unisoa.cache', 'sqlalchemy.engine'):
logging.getLogger(_logger_name).setLevel(logging.WARNING)
BUDGET_PATH = Path(__file__).resolve().parent / 'perf_budget.json'
#: 这些接口要么是真在往下写(下载、导出、预览计数),要么是免登入口,扫描里一律跳过。
SKIP = re.compile(r'cover|download|preview|export|/ping$|open/|embed/|sso/|settings/public|/info$')
#: 越界翻页、页大小、关键字过滤:分页是全站最容易在改动里悄悄坏掉的一块。
PAGE_PATHS = (
'/api/v1/work/created?page=1&page_size=5',
'/api/v1/work/created?page=2&page_size=5',
'/api/v1/work/created?page=1&page_size=5&with_data=0',
'/api/v1/work/created?page=1&page_size=5&status=completed',
'/api/v1/work/created?page=40&page_size=5',
'/api/v1/work/related?page=1&page_size=5',
'/api/v1/work/related?page=99&page_size=5',
'/api/v1/work/related?page=1&page_size=5&status=completed',
)
#: 分页冒烟要拿不同权限的人各跑一遍:越权看不该看到的、以及没权限时别 500。
PAGE_USERS = ('1', '437', '591', '592')
ROWS: list[str] = []
@event.listens_for(engine, 'after_cursor_execute')
def _count_statement(conn, cur, stmt, params, ctx, many): # noqa: ANN001
ROWS.append(' '.join(stmt.split()))
def header(token: str) -> dict[str, str]:
return {'Authorization': 'Bearer ' + token}
#: ``--dups`` 那一趟用:记下每条语句的起止与全文,用来分"串着问"还是"并着问"。
SPANS: list[tuple[float, float, str]] = []
TRACE_SPANS = False
@event.listens_for(engine, 'before_cursor_execute')
def _trace_begin(conn, cur, stmt, params, ctx, many): # noqa: ANN001
if TRACE_SPANS:
conn.info['_span_t0'] = time.perf_counter()
@event.listens_for(engine, 'after_cursor_execute')
def _trace_end(conn, cur, stmt, params, ctx, many): # noqa: ANN001
if TRACE_SPANS:
SPANS.append((conn.info.pop('_span_t0', time.perf_counter()), time.perf_counter(),
' '.join(stmt.split())))
def duplicate_reads(client: TestClient, token: str, targets) -> int:
"""报出"一次请求里**串着**把同一张表问了两遍以上"的接口(只报告,不算故障)。
判据只看时间:三条各查一次同一张表、并发跑,关键路径还是一趟往返,那种不报;
后一条等前一条问完才发的才算——那一趟是白排的。分页接口那条 ``count(*)`` 与取行
天生两次同表,这类是本来的形状(总数这一格要的就是它),所以只报不说对错,
看一眼"值不值得并"由人判断。
"""
global TRACE_SPANS
TRACE_SPANS = True
hits: list[tuple[str, int, dict[str, tuple[int, int]]]] = []
try:
for _template, url in targets:
SPANS.clear()
try:
client.get(url, headers=header(token))
captured = list(SPANS)
except Exception: # noqa: BLE001 - 扫不动的接口不算问题
continue
per_table: dict[str, list] = {}
for start, end, sql in captured:
for table in {m.lower() for m in _FROM_TABLE.findall(sql)}:
per_table.setdefault(table, []).append((start, end, sql))
flagged = {}
for table, spans in per_table.items():
if len(spans) < 2:
continue
spans.sort()
serial = sum(1 for a, b in zip(spans, spans[1:]) if b[0] >= a[1] - 1e-9)
if serial:
flagged[table] = (len(spans), serial)
if flagged:
hits.append((url, len(captured), flagged))
finally:
TRACE_SPANS = False
print(f' 串着重复问同一张表的接口 {len(hits)} 个(分页的 count + 取行属正常形状)')
for url, total, flagged in sorted(hits, key=lambda r: -max(v[1] for v in r[2].values())):
print(f' {url} 合计 {total} 条 '
+ ' '.join(f'{t}:共{n}次/串{k}' for t, (n, k) in sorted(flagged.items())))
return len(hits)
_FROM_TABLE = re.compile(r'\bFROM\s+([a-zA-Z_][\w]*)', re.I)
def sample(db, model, column, limit: int = 6) -> list:
"""从真库里捞几个真实主键当样例参数;这张表空着就交空清单(相关接口跳过)。"""
try:
return [r[0] for r in db.execute(select(column).limit(limit)).all() if r[0] not in (None, '')]
except Exception: # noqa: BLE001
db.rollback()
return []
def route_targets(db) -> list[tuple[str, str]]:
"""路由模板 -> 可打的具体 URL:``/api/v1/job/{job}`` -> ``/api/v1/job/<真 job>``。"""
work_jobs = sample(db, models.WorkCompleted, models.Work.job) + sample(db, models.Work, models.Work.job)
work_ids = (
sample(db, models.WorkCompleted, models.WorkCompleted.id)
+ sample(db, models.Work, models.Work.id)
)
persons = sample(db, models.User, models.User.id)
processes = sample(db, models.Work, models.Work.process) + sample(
db, models.WorkCompleted, models.WorkCompleted.process
)
dicts = sample(db, models.Dict, models.Dict.code) if hasattr(models, 'Dict') else []
values = {
'job': work_jobs,
'work_id': work_ids,
'person_id': persons,
'person': persons,
'unit_id': sample(db, models.Unit, models.Unit.id),
'document_id': sample(db, models.CmsDocument, models.CmsDocument.id),
'file_id': sample(db, models.PortalFile, models.PortalFile.id),
'meeting_id': sample(db, models.Meeting, models.Meeting.id),
'schedule_id': sample(db, models.Schedule, models.Schedule.id),
'dict_code': dicts,
'dict_id': persons,
'agent_id': persons,
'task_id': work_jobs,
'code': dicts + processes,
'process': processes,
'process_id': sample(db, models.Process, models.Process.id),
'role_id': sample(db, models.Role, models.Role.id),
'group_id': sample(db, models.Group, models.Group.id),
'id': work_jobs + persons,
}
targets: list[tuple[str, str]] = []
for route in app.routes:
if not isinstance(route, APIRoute) or 'GET' not in getattr(route, 'methods', set()):
continue
path = route.path
if SKIP.search(path):
continue
names = re.findall(r'{([a-zA-Z_]+)', path)
if any(name not in values for name in names):
continue
combos = [values[name][0] for name in names]
if any(not value for value in combos):
continue
url = path
for name, value in zip(names, combos):
url = url.replace('{' + name + '}', str(value))
targets.append((path, url))
return sorted(set(targets))
def sweep(client: TestClient, token: str, targets, *, ab: bool) -> tuple[list[dict], int, int]:
"""逐个接口打一遍:返回每接口的语句条数与状态,并把 5xx / 报文不一致记成故障。
先整圈预热一遍再量:字典、引导配置这些走 Redis 的共享缓存是**跨请求**的,第一圈
还没焐热,问库的条数会比平时多几条(``/draft/types`` 在未并批量查询前差 7 条,
字典合成一条 ``IN`` 之后只剩 1 条),拿首跑当基线就会天天误报。量的时候每个接口
连打两次,记冷(这一次请求自己还没复用)与热(同一次请求里复用上了)两个数,
基线对的是热那个:那才是用户真实付的账。
``--ab`` 多打的两遍按"关缓存打一头一尾、开缓存夹在中间"摆:只要关缓存的头尾两遍
一字不差,就说明这一整个时间窗里库里数据没动,于是中间开缓存那两遍与它们的任何
差异都只能来自缓存本身。带秒级时间戳的接口(``/hub/schedule`` 那种每次都不一样的)
会在头尾比对时就被判成"本身会变",不会冤枉缓存。
"""
auth = header(token)
for _, url in targets:
client.get(url, headers=auth)
faults = 0
volatile: list[str] = []
report: list[dict] = []
for template, url in targets:
off1 = off2 = None
if ab:
readcache.ENABLED = False
ROWS.clear()
off1 = client.get(url, headers=auth)
readcache.ENABLED = True
ROWS.clear()
first = client.get(url, headers=auth)
cold = len(ROWS)
ROWS.clear()
second = client.get(url, headers=auth)
warm = len(ROWS)
bad: list[str] = []
if first.status_code >= 500:
bad.append('冷跑 5xx')
if second.status_code >= 500:
bad.append('热跑 5xx')
if first.status_code != second.status_code:
volatile.append(f'{url} 同一个接口两次状态码 {first.status_code}/{second.status_code}')
if ab and off1 is not None:
readcache.ENABLED = False
ROWS.clear()
off2 = client.get(url, headers=auth)
readcache.ENABLED = True
same_window = (
off1.status_code == off2.status_code
and hashlib.sha256(off1.content).hexdigest() == hashlib.sha256(off2.content).hexdigest()
)
if not same_window:
volatile.append(f'{url} 关缓存打两遍就不一样(接口自己会写数据,判不了缓存)')
elif (
off1.status_code != first.status_code
or off1.content != first.content
or off2.content != second.content
):
bad.append('读缓存一开报文就变')
for note in bad:
faults += 1
print(f' !! {url} :: {note}')
report.append({'route': template, 'url': url, 'cold': cold, 'warm': warm,
'status': second.status_code, 'bad': bool(bad)})
for note in volatile[:8]:
print(f' · {note}')
return report, faults, len(volatile)
def page_smoke(client: TestClient) -> int:
"""分页边界:字段齐不齐、页大小守没守住、total 与 items 对不对得上。"""
faults = 0
for uid in PAGE_USERS:
token, _ = create_access_token(uid)
for path in PAGE_PATHS:
try:
resp = client.get(path, headers=header(token))
except Exception as exc: # noqa: BLE001
faults += 1
print(f' !! uid={uid} {path} :: 抛异常 {type(exc).__name__}: {exc}')
continue
if resp.status_code in (401, 403):
continue
if resp.status_code >= 500:
faults += 1
print(f' !! uid={uid} {path} :: {resp.status_code} {resp.text[:160]}')
continue
data = (resp.json() or {}).get('data') or {}
items, total = data.get('items'), data.get('total')
if items is None or total is None:
faults += 1
print(f' !! uid={uid} {path} :: 缺分页字段 items={items} total={total}')
elif len(items) > 5:
faults += 1
print(f' !! uid={uid} {path} :: 页大小没守住,给了 {len(items)} 条')
elif isinstance(total, int) and total < len(items):
faults += 1
print(f' !! uid={uid} {path} :: total({total}) < items({len(items)})')
return faults
def readonly_posts(client: TestClient, db) -> int:
"""设计器试算 / 审批体检 / 审批人预览:只读 POST,不在 GET 扫描里。"""
process_ids = [r[0] for r in db.execute(select(models.Process.id).limit(3)).all()]
faults = 0
for uid in ('1', '437', '591'):
token, _ = create_access_token(uid)
calls = [('/api/v1/process/approvers/preview',
{'taskValues': [{'type': 'identity', 'data': ['admin']}]})]
for pid in process_ids:
calls.append((f'/api/v1/process/processes/{pid}/simulate', {'data': {'amount': 5000}}))
calls.append((f'/api/v1/process/processes/{pid}/dedup-audit', {}))
for path, body in calls:
try:
resp = client.post(path, headers=header(token), json=body)
except Exception as exc: # noqa: BLE001
faults += 1
print(f' !! uid={uid} {path} :: 抛异常 {type(exc).__name__}: {exc}')
continue
if resp.status_code >= 500:
faults += 1
print(f' !! uid={uid} {path} :: {resp.status_code} {resp.text[:160]}')
return faults
def compare_budget(report: list[dict], *, tolerance: int, strict: bool, save: bool) -> tuple[int, int]:
"""每个接口的只读语句条数与基线对账。返回 ``(超线数, 变少的接口数)``。"""
fresh = {row['route']: max(int(row['warm']), int(row['cold'])) for row in report}
if save:
BUDGET_PATH.write_text(
json.dumps({'generated': time.strftime('%Y-%m-%dT%H:%M:%S'), 'endpoints': fresh},
ensure_ascii=False, indent=2, sort_keys=True) + '\n',
encoding='utf-8',
)
print(f'基线已写入 {BUDGET_PATH.name}({len(fresh)} 个接口,合计 {sum(fresh.values())} 条)')
return 0, 0
if not BUDGET_PATH.exists():
print(f'没有 {BUDGET_PATH.name}:跑一次 --save-budget 就有基线可对账了')
return 0, 0
baseline = json.loads(BUDGET_PATH.read_text(encoding='utf-8')).get('endpoints') or {}
over = 0
saved = 0
for route, count in sorted(fresh.items()):
was = baseline.get(route)
if was is None:
print(f' · 新接口没有基线:{route} 现在 {count} 条')
continue
if count > was + tolerance:
over += 1
print(f' !! {route} 语句从 {was} 涨到 {count}(多了 {count - was} 条)')
elif count + tolerance < was:
saved += 1
print(f' ↓ {route} 语句从 {was} 降到 {count}')
if over and not strict:
print(f' ({over} 个接口超线;没带 --strict,只报不断)')
return (over if strict else 0), saved
def main() -> int:
parser = argparse.ArgumentParser(description='只读接口自检:功能没坏 + 语句条数没退')
parser.add_argument('--ab', action='store_true', help='加做读缓存开 / 关的逐字节报文对比')
parser.add_argument('--user', default='1', help='用哪个 users.id 登录跑扫描(默认 1)')
parser.add_argument('--only', default='', help='只跑路径里含这个串的接口')
parser.add_argument('--tolerance', type=int, default=2, help='语句条数允许的浮动(默认 2)')
parser.add_argument('--strict', action='store_true', help='超线就当失败(退出码 1)')
parser.add_argument('--save-budget', action='store_true', help='把这次的语句条数记成基线')
parser.add_argument('--dups', action='store_true',
help='再扫一趟,报出「一次请求里串着重复问同一张表」的接口(只报告,不算故障)')
args = parser.parse_args()
db = SessionLocal()
client = TestClient(app)
token, _ = create_access_token(args.user)
targets = route_targets(db)
if args.only:
targets = [item for item in targets if args.only in item[0]]
print(f'库:{settings.db_host}:{settings.db_port}/{settings.db_name} '
f'读缓存:{"开" if readcache.ENABLED else "关"} 登录:users.id={args.user}')
started = time.perf_counter()
report, faults, volatile = sweep(client, token, targets, ab=args.ab)
print(f'\n1) 只读 GET 扫描:{len(targets)} 个接口,故障 {faults} 个,本身会变的 {volatile} 个')
codes = {}
for row in report:
codes[row['status']] = codes.get(row['status'], 0) + 1
print(' 状态码分布:' + ' '.join(f'{code}×{n}' for code, n in sorted(codes.items())))
page_faults = page_smoke(client)
print(f'2) 分页冒烟:{len(PAGE_PATHS) * len(PAGE_USERS)} 次请求,故障 {page_faults} 个')
post_faults = readonly_posts(client, db)
print(f'3) 只读 POST 冒烟:故障 {post_faults} 个')
over, saved = compare_budget(report, tolerance=args.tolerance, strict=args.strict, save=args.save_budget)
total_warm = sum(int(r['warm']) for r in report)
print(f'4) 语句条数:合计 {total_warm} 条,超线 {over} 个,比基线少的 {saved} 个')
if args.dups:
print('5) 重复读扫描(只报告,不算故障):')
duplicate_reads(client, token, targets)
db.close()
bad = faults + page_faults + post_faults + over
took = time.perf_counter() - started
if bad:
print(f'\n不通过:{bad} 处问题({took:.0f}s)')
return 1
print(f'\n通过:{took:.0f}s')
return 0
if __name__ == '__main__':
raise SystemExit(main())