如何利用 PyO3 编写一个 Rust 加速中间件并在 Gunicorn 中调用?

解读

这道题表面问“怎么把 Rust 嵌进 Python”,实则考察候选人能否把性能热点从 Python 迁移到 Rust,并无缝嵌入 Gunicorn 的 WSGI 调用链。国内大厂线上环境普遍用 CentOS 7/8 + Gunicorn + gevent 或 Kubernetes + Gunicorn + uvicorn worker,对延迟和 CPU 极其敏感,因此面试官希望听到:

  1. 如何定位热点(cProfile、py-spy、perf)
  2. 如何用 PyO3 写出零拷贝、无 GIL、内存安全的 .so
  3. 如何让 .so 在 Gunicorn 的 pre-fork 模型下被所有 worker 共享内存、不重复初始化
  4. 如何打包成 manylinux_2_28 轮子进私有 PyPI,供 CI/CD 一键部署
  5. 灰度回滚方案(信号量热卸载、AB 实验开关)

只回答“pip install rust 模块”只能拿 30 分,必须给出线上可落地的工程闭环。

知识点

  1. PyO3 生命周期与 GIL 交互:py.allow_threads() 释放 GIL,让 Rust 并行计算;PyBytes::from_ptr 实现零拷贝返回到 Python。
  2. Gunicorn pre-fork 加载顺序:master 进程 import 阶段即 Py_Initialize,Rust 静态变量在此阶段初始化一次,子进程通过 fork 写时复制,避免重复开销。
  3. ABI 兼容:编译目标 x86_64-unknown-linux-gnu 必须生成 cpython-38-cp38-manylinux_2_28_x86_64.whl,否则生产 glibc 版本过低会 undefined symbol: __memcpy_chk。
  4. WSGI 中间件注入:在 Django/Flask 侧写 纯 Python 包装函数,把请求体 bytes 直接送进 Rust,返回 bytes 再 yield 给下游,不改变 Gunicorn 配置。
  5. 可观测性:Rust 内使用 tracing-subscriber 写 StatsD counter,通过 Unix Domain Socket 打到 node-exporter,与 Prometheus 拉取路径统一。
  6. 热升级:利用 Gunicorn 的 USR2 + WINCH 信号,做双缓冲 master,新 master 加载新 .so 版本,老 master 优雅退出,实现零停机灰度。

答案

步骤一:定位热点
线上用 py-spy top -d 5 -p <gunicorn-worker-pid> 发现 JSON 解析 + 敏感词过滤 占 38% CPU,决定用 Rust 重写。

步骤二:PyO3 实现

use pyo3::prelude::*;
use pyo3::types::PyBytes;

#[pyfunction]
fn filter_sensitive<'py>(py: Python<'py>, data: &'py [u8]) -> PyResult<&'py PyBytes> {
    // 释放 GIL,Rust 并行
    let out = py.allow_threads(|| {
        // 双数组 Trie + SIMD 加速
        sensitive::filter(data)
    });
    Ok(PyBytes::new(py, &out))
}

#[pymodule]
fn _rust_accel(_py: Python, m: &PyModule) -> PyResult<()> {
    m.add_function(wrap_pyfunction!(filter_sensitive, m)?)?;
    Ok(())
}

Cargo.toml 关键段

[lib]
name = "_rust_accel"
crate-type = ["cdylib"]

[dependencies]
pyo3 = { version = "0.21", features = ["extension-module"] }
sensitive = { path = "src/sensitive" }  # 自研 SIMD 库

步骤三:manylinux 构建
用 quay.io/pypa/manylinux_2_28_x86_64 镜像:

docker run --rm -v $PWD:/io quay.io/pypa/manylinux_2_28_x86_64 bash -c "
cd /io && python -m build --wheel -C--global-option=bdist_wheel \
-C--global-option=--plat-name=manylinux_2_28_x86_64"
auditwheel repair dist/*-linux*.whl -w dist/

产出 rust_accel-0.1.0-cp38-cp38-manylinux_2_28_x86_64.whl,上传至 私有 DevPI。

步骤四:WSGI 侧透明调用

# middleware.py
from rust_accel import filter_sensitive

class RustFilterMiddleware:
    def __init__(self, app):
        self.app = app

    def __call__(self, environ, start_response):
        if environ.get('CONTENT_TYPE') == 'application/json':
            length = int(environ.get('CONTENT_LENGTH', 0))
            body = environ['wsgi.input'].read(length)
            body = filter_sensitive(body)  # Rust 加速
            environ['wsgi.input'] = io.BytesIO(body)
            environ['CONTENT_LENGTH'] = str(len(body))
        return self.app(environ, start_response)

在 gunicorn.conf.py 里

from middleware import RustFilterMiddleware
application = RustFilterMiddleware(django.core.wsgi.get_wsgi_application())

步骤五:Gunicorn 预加载

gunicorn -c gunicorn.conf.py --preload -k gevent -w 48 app:application

--preload 保证 Rust 静态变量只在 master 初始化一次,worker 共享只读内存,RSS 节省 220 MB/进程。

步骤六:灰度与回滚
通过 Consul KV 下发开关 rust_accel/enabled=0,WSGI 中间件捕获异常自动降级到纯 Python 实现;同时利用 USR2 信号 做双缓冲升级,5 秒级回滚。

拓展思考

  1. 异步生态融合:如果后端已迁到 uvicorn + FastAPI,可把 Rust 编译成 PyO3-asyncio 的 async fn,用 anyio.to_thread 把 CPU 密集任务丢到 Rust,避免 FastAPI 的 event loop 阻塞。
  2. 内存安全审计:Rust .so 一旦 panic::catch_unwind 失败,会直接把 SIGABRT 传给 Gunicorn worker,导致 502;线上需打开 RUST_BACKTRACE=1 并接入 Sentry,同时用 systemd-coredump 保留现场。
  3. 跨语言链路追踪:在 Rust 内生成 W3C Traceparent header,与 Python 侧的 OpenTelemetry SDK 对齐,实现 Rust→Python→Redis→MySQL 全链路同一 TraceId,方便在 Jaeger 里定位 Rust 模块引入的延迟回归。