第 8 章 模組
8.1 內建模組
內建模組隨主程式編譯,設定位於 modules.<模組名> 或 location 頂層鍵。按用途大致分類:
| 類別 | 模組 |
|---|---|
| HTTP 核心 | http_staticfile、http_proxy、http_rewrite、http_headers、http_accesslog |
| 協定客戶端 | http_fastcgi、http_uwsgi、http_scgi、http_grpc、http_memcached |
| 安全 | http_waf、http_access、http_auth_basic、http_auth_request、http_auth_jwt、http_secure_link、http_security_headers、http_limit、http_error_guard |
| 過濾與壓縮 | http_gzip、http_gunzip、http_brotli、http_zstd、http_sub、http_addition、http_ssi、http_charset、http_minify、http_concat |
| 媒體與內容 | http_image_thumb、http_mp4、http_empty_gif、http_stub_status、http_nchan、http_upload |
| 變數與分流 | http_map、http_geo、http_geoip、http_split_clients、http_realip、http_userid、http_browser、http_referer |
| 可觀測與保護 | http_otel、http_logsink、http_mirror、http_sysguard |
模組在 GET /api/modules 與管理後台「模組管理」頁列出名稱、版本、說明與載入狀態。
8.2 外置動態模組
外置模組為原生動態庫(cdylib):Linux/FreeBSD 為 .so、macOS 為 .dylib、Windows 為 .dll,透過穩定的 C ABI v2 載入——模組匯出 wxserver_module_v2 符號(manifest JSON + on_hook 回呼),按需另匯出 wxserver_body_filter_v1(串流回應主體過濾)與 wxserver_action_v1(管理台動作)。
用任意 Rust crate 建置為 cdylib:
cargo build --release --manifest-path /path/to/plugin/Cargo.toml
# 產物: target/release/lib<name>.so / .dylib / .dll
在設定中啟用並傳入模組全域設定(按 manifest 的 config schema 驗證):
external_modules = [{ path = "/usr/share/wxserver/modules/libexample.so", enabled = true }]
modules = { example = { greeting = "hi" } }
manifest 宣告模組實作的掛鉤、開啟條件、設定 schema 與管理台表單/詞條;宿主統一校驗 manifest、依賴(depends,必選缺失啟動失敗)與 scope 設定。可選 sha256 雜湊固定與 signature/signature_key Ed25519 簽章校驗(plugin_trust.keys 設定公鑰)。增刪模組經設定重載生效;範例外掛見原始碼樹 plugins/example_echo/。C ABI 細節見 docs/plugin-abi-c.md。
8.3 模組開發介面
內建模組位於 modules/<name>/ 子 crate,用 modules/common 的輔助宣告 manifest 並實作對應階段的 hook trait,經 register_entry! 自註冊(linkme 分散式切片)。外置模組透過 C ABI 實作同一 manifest 模型。
按階段劃分的呼叫方式:
| 階段 | trait / 機制 | 典型用途 |
|---|---|---|
| Rewrite | BuiltinHandler / AsyncBuiltinHandler |
改寫路徑、重定向 |
| PreAccess / Access | 同上 | 限流、認證、IP 控制 |
| Content | ContentBuiltin(按 location.type 分發) |
代理、FastCGI、靜態檔案 |
| HeaderFilter | BuiltinHandler |
回應標頭過濾 |
| BodyFilter | BuiltinHandler / AsyncBodyBuiltin / 外置 wxserver_body_filter_v1 |
壓縮、替換、SSI |
| Log | BuiltinHandler(帶 LogMeta) |
存取日誌 |
| WAF | Phase::WafRequest/WafResponse | 攔截(返回 blocked) |
| service | ServiceBuiltin(plugin::start_services 啟動) |
metrics/otel/stream/mail |
階段順序固定為 Rewrite → PreAccess → Access → Content → HeaderFilter → BodyFilter → Log。hook 可宣告 conditions(methods/path/host/header/cookie/status/tls/cidr)與 priority;HookOutcome 為 Continue / Handled(Resp) / InternalRedirect。完整設計見 docs/plugin-architecture.md,實作狀態見 docs/plugin-architecture.md。
8.4 模組停用
內建模組可以在不重新編譯的情況下停用:
http = {
disabled_modules = ["http_waf", "http_zstd"],
servers = [{ disabled_modules = ["http_image_thumb"] }],
}
停用的模組不再執行對應階段與 content 處理器。停用 content 模組前,必須移除所有引用它的 location.type,否則 wxserver -t 與管理後台儲存都會驗證失敗。執行期停用不會強制釋放模組已初始化的資源;需要徹底回收請重新啟動程序。必選依賴被停用時啟動失敗,可選依賴僅告警。