Skip to main content

sz_rust_core/
lib.rs

1//! SZ-Rust Core — 主框架包
2//!
3//! 对标 ThinkPHP 8 的 Rust Web 框架核心,基于 axum 0.8 + SZ-ORM。
4//!
5//! ## 模块结构
6//!
7//! 所有模块均已实现并通过测试。`addons` 重导出 `sz-rust-addons-loader`,
8//! `macros` 重导出 `sz-rust-macros` 的过程宏。
9//!
10//! | 模块 | 对齐 PHP | 状态 |
11//! |------|---------|------|
12//! | `controller` | `app\SzController` / `app\BaseController` | ✅ |
13//! | `model` | `think\Model` | ✅ |
14//! | `schema_cache` | `think\db\Fetch` 字段缓存(SchemaCache + TableSchema + ColumnDefinition) | ✅ |
15//! | `relation` | `think\Model` 关联关系(HasMany/BelongsTo/HasOne/BelongsToMany/Morph) | ✅ |
16//! | `request` | `$this->request->post/get` | ✅ |
17//! | `response` | `renderJson/renderSuccess/renderError` | ✅ |
18//! | `middleware` | CORS/Auth/Log/RateLimit/Trace | ✅ |
19//! | `guard` | NestJS Guard + Spring Security(sz-rust 自研) | ✅ |
20//! | `hooks` | think-orm Model 钩子(HookDispatcher 16 事件) | ✅ |
21//! | `multi_app` | `auto_multi_app` | ✅ |
22//! | `health` | 健康检查端点(K8s liveness/readiness) | ✅ |
23//! | `static_files` | 静态文件路由(`tower-http::ServeDir`) | ✅ |
24//! | `error_handler` | 404/500 标准化 JSON 响应 | ✅ |
25//! | `h2` | HTTP/2 + TLS(`think-swoole` SSL) | ✅ |
26//! | `routing` | 三层路由机制(属性宏/配置式/约定式) | ✅ |
27//! | `addons` | `addons/` 插件 | ✅ 重导出 `sz-rust-addons-loader` |
28//! | `router` | `with_route` | ✅ |
29//! | `container` | `app()` 容器 | ✅ |
30//! | `error` | `BaseException` | ✅ |
31//! | `macros` | `compact()` | ✅ 重导出 `sz-rust-macros` |
32//! | `config` | `config/app.php` / `database.php` | ✅ |
33//! | `log` | `think-logger` | ✅ |
34//! | `server` | `think-swoole` / `think-worker` 启动入口 | ✅ |
35//! | `validate` | `think\Validate` 数据验证器 | ✅ |
36//! | `upload` | `think\File` + `think\file\UploadedFile` 文件上传 | ✅ |
37//! | `cache` | `think\facade\Cache` 缓存 facade | ✅ |
38//! | `session` | `think\facade\Session` 会话管理(SessionStore trait + MemorySessionStore) | ✅ |
39//! | `cookie` | `think\Cookie` Cookie 管理(CookieJar + CookieOptions) | ✅ |
40//! | `event` | `think\Event` 事件系统(Listener/Subscriber/Observer) | ✅ |
41//! | `env` | `think\facade\Env` 环境变量管理 | ✅ |
42//! | `i18n` | `think\facade\Lang` 多语言国际化 | ✅ |
43//! | `mail` | `think\facade\Mail` 邮件抽象(Mailer trait + MemoryMailer) | ✅ |
44//! | `notify` | `think\facade\Notify` 通知抽象(Notifier trait + MemoryNotifier + SlackNotifier) | ✅ |
45//! | `oauth` | Laravel Socialite OAuth2 客户端(OAuth2Provider trait + GenericOAuth2Provider) | ✅ |
46//! | `pay` | `yansongda/pay` 支付聚合(PayProvider trait + MemoryPayProvider + PayHttpTransport) | ✅ |
47//! | `migration_history` | `think migrate` 迁移历史表(多方言 DDL + CRUD SQL 生成) | ✅ |
48//! | `api_version` | API 版本管理(URL/Header/Query 多策略协商) | ✅ |
49//! | `cache_warmer` | 缓存预热管道(部署/启动时预热,串行/并行+超时控制) | ✅ |
50//! | `debug_page` | Whoops-style 调试页(开发环境 HTML + 生产环境简洁页) | ✅ |
51//! | `openapi` | OpenAPI 3.0.3 规范构建器 + Swagger UI / Redoc 渲染 | ✅ |
52//! | `qr_code` | `endroid/qr-code` 二维码生成(PNG/SVG/矩阵) | ✅ |
53//! | `wechat` | `overtrue/wechat` / `EasyWeChat` 微信 SDK(公众号/小程序/开放平台/企业微信) | ✅ |
54//! | `gateway` | `GatewayWorker\Gateway` WebSocket 客户端管理(Gateway API 抽象 + GatewayTransport trait + MemoryGatewayTransport) | ✅ |
55
56#![deny(unsafe_code)]
57// v0.2.0:启用 missing_docs 警告,要求所有公开项必须有文档注释
58#![warn(missing_docs)]
59// 文档构建时将 missing_docs 作为错误(CI 中 RUSTDOCFLAGS="-D warnings" 会强制)
60#![cfg_attr(doctest, warn(missing_docs))]
61
62pub mod addons;
63pub mod api_version;
64pub mod cache_warmer;
65pub mod container;
66pub mod error_handler;
67pub mod h2;
68pub mod health;
69pub mod json;
70pub mod macros;
71pub mod migration_history;
72pub mod multi_app;
73pub mod multi_tenant;
74pub mod plugin;
75
76// P3: alloc 计数 GlobalAlloc wrapper(仅 alloc-count feature 启用时编译)
77#[cfg(feature = "alloc-count")]
78pub mod alloc_counter;
79
80// P3: 内存池(区域分配器,仅 mem-pool feature 启用时编译)
81#[cfg(feature = "mem-pool")]
82pub mod mem_pool;
83
84// P3 拆包:MVC 层 facade(view/controller/guard 控制器与视图抽象),
85// 向下游保留 `sz_rust_core::{controller,guard,view}` 路径。
86pub use sz_rust_mvc_facade::{controller, guard, view};
87
88// P3 拆包:中间件层 facade(auth/sanctum/jwt_blacklist 等 14 个中间件 + log 门面),
89// 向下游保留 `sz_rust_core::middleware::*` 与 `sz_rust_core::log::*` 路径。
90pub use sz_rust_middleware_facade as middleware;
91pub use sz_rust_middleware_facade::log;
92
93// P3 拆包:ORM 扩展层 facade(model/hooks/relation 框架层抽象),
94// 基于 sz-rust-orm-facade 构建,向下游保留 `sz_rust_core::{model,hooks,relation}` 路径。
95pub use sz_rust_orm_ext_facade::{hooks, model, relation};
96
97// P2 拆包:ORM facade 作为独立 crate,通过 `sz_rust_core::orm::*` 访问
98// 下游业务包应通过此 facade 统一访问 sz-orm-* 全家桶,而非直接依赖各子包。
99pub use sz_rust_orm_facade as orm;
100
101// P2 拆包:HTTP facade 作为独立 crate,通过 `sz_rust_core::http::*` 访问
102// 包含 response、error、request 三大基础模块,下游可直接依赖以减少编译耦合。
103pub use sz_rust_http_facade as http;
104
105// P2 拆包:Cache facade 作为独立 crate,通过 `sz_rust_core::cache::*` 访问
106// 包含 CacheDriver trait + Memory/Redis/Memcached/MultiLevel 驱动,下游可直接依赖。
107pub use sz_rust_cache_facade as cache;
108
109// P2 拆包:State facade 作为独立 crate,通过 `sz_rust_core::state::*` 访问
110// 包含 session/cookie/env/event/i18n/mail/notify 七大应用状态模块,下游可直接依赖。
111pub use sz_rust_state_facade as state;
112
113// P2 拆包:Infra facade 作为独立 crate,通过 `sz_rust_core::infra::*` 访问
114// 包含 config/validate/static_files/upload/debug_page 五大基础设施模块,下游可直接依赖。
115pub use sz_rust_infra_facade as infra;
116
117// P2 拆包:Auth facade 作为独立 crate,通过 `sz_rust_core::auth::*` 访问
118// 包含 wechat/oauth/gateway 三大认证与网关模块,下游可直接依赖。
119pub use sz_rust_auth_facade as auth;
120
121// 向后兼容:保留 crate::session / crate::cookie / crate::env / crate::event /
122// crate::i18n / crate::mail / crate::notify 路径,内部模块和集成测试无需改动。
123pub use state::{cookie, env, event, i18n, mail, notify, session};
124
125// 向后兼容:保留 crate::config / crate::validate / crate::static_files /
126// crate::upload / crate::debug_page 路径。
127pub use infra::{config, debug_page, static_files, upload, validate};
128
129// 向后兼容:保留 crate::wechat / crate::oauth / crate::gateway 路径。
130pub use auth::{gateway, oauth, wechat};
131
132// 向后兼容:保留 crate::response / crate::error / crate::request 路径
133// 内部模块仍可通过 crate::response::ApiResponse 等方式访问,无需改动。
134pub use http::{error, request, response};
135
136// P2 拆包:Pay facade 作为独立 crate,通过 `sz_rust_core::pay::*` 访问
137// 包含 PayProvider trait + MemoryPayProvider + PayOrder/RefundOrder Builder,下游可直接依赖。
138pub use sz_rust_pay_facade::pay;
139
140pub mod qr_code;
141pub mod runtime;
142pub mod schema_cache;
143pub mod seed;
144pub mod server;
145
146// P3 拆包:路由层 facade(router/routing/websocket_route/openapi 三层路由机制),
147// 向下游保留 `sz_rust_core::{router,routing,websocket_route,openapi}` 路径。
148pub use sz_rust_router_facade::{openapi, router, routing, websocket_route};
149
150// P2: GraphQL / gRPC facade(可选 feature)
151#[cfg(feature = "graphql")]
152pub use orm::graphql;
153
154#[cfg(feature = "grpc")]
155pub use orm::grpc;
156
157// P2: Addon 热加载(可选 feature: hot-reload)
158#[cfg(feature = "hot-reload")]
159pub use runtime::hot_reload;
160
161// ============================================================================
162// 过程宏重导出
163// ============================================================================
164
165/// 编译时 SQL 校验宏 — 复用自 `sz-orm-macros`
166///
167/// 在编译期对 SQL 字符串字面量进行语法和注入模式校验,校验通过后
168/// 将 SQL 作为 `&'static str` 发出到调用处。任何校验失败都会触发
169/// `compile_error!`,二进制无法构建。
170///
171/// ## 校验规则
172///
173/// - SELECT 必须包含 FROM
174/// - INSERT 必须包含 INTO 和 VALUES
175/// - UPDATE 必须包含 SET
176/// - DELETE 必须包含 FROM
177/// - 括号必须平衡
178/// - 字符串字面量必须闭合
179/// - 禁止 SQL 注入模式(`; DROP TABLE` / `OR 1=1` / `UNION SELECT` / `--` / `/*` 等)
180///
181/// ## 用法
182///
183/// ```ignore
184/// use sz_rust_core::sql_string;
185///
186/// // 基础用法:校验通过后返回 &str
187/// let sql = sql_string!("SELECT * FROM users WHERE id = 1");
188///
189/// // 带参数数量校验
190/// let sql = sql_string!("SELECT * FROM users WHERE id = ?"; params: 1);
191///
192/// // ❌ 编译错误:SELECT 缺少 FROM
193/// // let sql = sql_string!("SELECT * users");
194///
195/// // ❌ 编译错误:检测到 SQL 注入模式
196/// // let sql = sql_string!("SELECT * FROM users WHERE name = 'x' OR '1'='1'");
197/// ```
198pub use crate::orm::sql_string;
199
200/// 编译时 SQL 校验 + 可选真实 DB 验证宏 — 复用自 `sz-orm-macros`
201///
202/// 与 [`sql_string!`] 行为一致,额外支持在 `db-verify` feature 启用且
203/// `SZ_ORM_QUERY_VERIFY=1` 环境变量设置时,连接 `DATABASE_URL` 指向的
204/// 数据库执行 `EXPLAIN` 进行真实 schema 校验。
205pub use crate::orm::query;
206
207// ============================================================================
208// 运行时 SQL 校验 — 复用自 sz-orm-sql-validator
209// ============================================================================
210
211pub use crate::orm::{
212    detect_statement_type, validate, validate_column_name, validate_delete, validate_insert,
213    validate_parameter_count, validate_select, validate_sql, validate_table_name, validate_update,
214    SqlStatementType, SqlValidationError, ValidationResult,
215};
216
217/// 运行时 SQL 校验便捷函数
218///
219/// 对 [`validate_sql`] 的薄包装,返回 `Result<(), String>` 以便上层不依赖
220/// `SqlValidationError` 类型也能处理错误。
221///
222/// ## 用法
223///
224/// ```rust,ignore
225/// use sz_rust_core::validate_sql_runtime;
226///
227/// // 合法 SQL
228/// assert!(validate_sql_runtime("SELECT * FROM users WHERE id = 1").is_ok());
229///
230/// // 非法 SQL(缺少 FROM)
231/// assert!(validate_sql_runtime("SELECT * users").is_err());
232///
233/// // SQL 注入
234/// assert!(validate_sql_runtime("SELECT * FROM users WHERE name = 'x' OR '1'='1'").is_err());
235/// ```
236pub fn validate_sql_runtime(sql: &str) -> Result<(), String> {
237    validate_sql(sql).map_err(|e| e.to_string())
238}