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;
74
75// P3 拆包:MVC 层 facade(view/controller/guard 控制器与视图抽象),
76// 向下游保留 `sz_rust_core::{controller,guard,view}` 路径。
77pub use sz_rust_mvc_facade::{controller, guard, view};
78
79// P3 拆包:中间件层 facade(auth/sanctum/jwt_blacklist 等 14 个中间件 + log 门面),
80// 向下游保留 `sz_rust_core::middleware::*` 与 `sz_rust_core::log::*` 路径。
81pub use sz_rust_middleware_facade as middleware;
82pub use sz_rust_middleware_facade::log;
83
84// P3 拆包:ORM 扩展层 facade(model/hooks/relation 框架层抽象),
85// 基于 sz-rust-orm-facade 构建,向下游保留 `sz_rust_core::{model,hooks,relation}` 路径。
86pub use sz_rust_orm_ext_facade::{hooks, model, relation};
87
88// P2 拆包:ORM facade 作为独立 crate,通过 `sz_rust_core::orm::*` 访问
89// 下游业务包应通过此 facade 统一访问 sz-orm-* 全家桶,而非直接依赖各子包。
90pub use sz_rust_orm_facade as orm;
91
92// P2 拆包:HTTP facade 作为独立 crate,通过 `sz_rust_core::http::*` 访问
93// 包含 response、error、request 三大基础模块,下游可直接依赖以减少编译耦合。
94pub use sz_rust_http_facade as http;
95
96// P2 拆包:Cache facade 作为独立 crate,通过 `sz_rust_core::cache::*` 访问
97// 包含 CacheDriver trait + Memory/Redis/Memcached/MultiLevel 驱动,下游可直接依赖。
98pub use sz_rust_cache_facade as cache;
99
100// P2 拆包:State facade 作为独立 crate,通过 `sz_rust_core::state::*` 访问
101// 包含 session/cookie/env/event/i18n/mail/notify 七大应用状态模块,下游可直接依赖。
102pub use sz_rust_state_facade as state;
103
104// P2 拆包:Infra facade 作为独立 crate,通过 `sz_rust_core::infra::*` 访问
105// 包含 config/validate/static_files/upload/debug_page 五大基础设施模块,下游可直接依赖。
106pub use sz_rust_infra_facade as infra;
107
108// P2 拆包:Auth facade 作为独立 crate,通过 `sz_rust_core::auth::*` 访问
109// 包含 wechat/oauth/gateway 三大认证与网关模块,下游可直接依赖。
110pub use sz_rust_auth_facade as auth;
111
112// 向后兼容:保留 crate::session / crate::cookie / crate::env / crate::event /
113// crate::i18n / crate::mail / crate::notify 路径,内部模块和集成测试无需改动。
114pub use state::{cookie, env, event, i18n, mail, notify, session};
115
116// 向后兼容:保留 crate::config / crate::validate / crate::static_files /
117// crate::upload / crate::debug_page 路径。
118pub use infra::{config, debug_page, static_files, upload, validate};
119
120// 向后兼容:保留 crate::wechat / crate::oauth / crate::gateway 路径。
121pub use auth::{gateway, oauth, wechat};
122
123// 向后兼容:保留 crate::response / crate::error / crate::request 路径
124// 内部模块仍可通过 crate::response::ApiResponse 等方式访问,无需改动。
125pub use http::{error, request, response};
126
127// P2 拆包:Pay facade 作为独立 crate,通过 `sz_rust_core::pay::*` 访问
128// 包含 PayProvider trait + MemoryPayProvider + PayOrder/RefundOrder Builder,下游可直接依赖。
129pub use sz_rust_pay_facade::pay;
130
131pub mod qr_code;
132pub mod runtime;
133pub mod schema_cache;
134pub mod seed;
135pub mod server;
136
137// P3 拆包:路由层 facade(router/routing/websocket_route/openapi 三层路由机制),
138// 向下游保留 `sz_rust_core::{router,routing,websocket_route,openapi}` 路径。
139pub use sz_rust_router_facade::{openapi, router, routing, websocket_route};
140
141// P2: GraphQL / gRPC facade(可选 feature)
142#[cfg(feature = "graphql")]
143pub use orm::graphql;
144
145#[cfg(feature = "grpc")]
146pub use orm::grpc;
147
148// P2: Addon 热加载(可选 feature: hot-reload)
149#[cfg(feature = "hot-reload")]
150pub use runtime::hot_reload;
151
152// ============================================================================
153// 过程宏重导出
154// ============================================================================
155
156/// 编译时 SQL 校验宏 — 复用自 `sz-orm-macros`
157///
158/// 在编译期对 SQL 字符串字面量进行语法和注入模式校验,校验通过后
159/// 将 SQL 作为 `&'static str` 发出到调用处。任何校验失败都会触发
160/// `compile_error!`,二进制无法构建。
161///
162/// ## 校验规则
163///
164/// - SELECT 必须包含 FROM
165/// - INSERT 必须包含 INTO 和 VALUES
166/// - UPDATE 必须包含 SET
167/// - DELETE 必须包含 FROM
168/// - 括号必须平衡
169/// - 字符串字面量必须闭合
170/// - 禁止 SQL 注入模式(`; DROP TABLE` / `OR 1=1` / `UNION SELECT` / `--` / `/*` 等)
171///
172/// ## 用法
173///
174/// ```ignore
175/// use sz_rust_core::sql_string;
176///
177/// // 基础用法:校验通过后返回 &str
178/// let sql = sql_string!("SELECT * FROM users WHERE id = 1");
179///
180/// // 带参数数量校验
181/// let sql = sql_string!("SELECT * FROM users WHERE id = ?"; params: 1);
182///
183/// // ❌ 编译错误:SELECT 缺少 FROM
184/// // let sql = sql_string!("SELECT * users");
185///
186/// // ❌ 编译错误:检测到 SQL 注入模式
187/// // let sql = sql_string!("SELECT * FROM users WHERE name = 'x' OR '1'='1'");
188/// ```
189pub use crate::orm::sql_string;
190
191/// 编译时 SQL 校验 + 可选真实 DB 验证宏 — 复用自 `sz-orm-macros`
192///
193/// 与 [`sql_string!`] 行为一致,额外支持在 `db-verify` feature 启用且
194/// `SZ_ORM_QUERY_VERIFY=1` 环境变量设置时,连接 `DATABASE_URL` 指向的
195/// 数据库执行 `EXPLAIN` 进行真实 schema 校验。
196pub use crate::orm::query;
197
198// ============================================================================
199// 运行时 SQL 校验 — 复用自 sz-orm-sql-validator
200// ============================================================================
201
202pub use crate::orm::{
203 detect_statement_type, validate, validate_column_name, validate_delete, validate_insert,
204 validate_parameter_count, validate_select, validate_sql, validate_table_name, validate_update,
205 SqlStatementType, SqlValidationError, ValidationResult,
206};
207
208/// 运行时 SQL 校验便捷函数
209///
210/// 对 [`validate_sql`] 的薄包装,返回 `Result<(), String>` 以便上层不依赖
211/// `SqlValidationError` 类型也能处理错误。
212///
213/// ## 用法
214///
215/// ```rust,ignore
216/// use sz_rust_core::validate_sql_runtime;
217///
218/// // 合法 SQL
219/// assert!(validate_sql_runtime("SELECT * FROM users WHERE id = 1").is_ok());
220///
221/// // 非法 SQL(缺少 FROM)
222/// assert!(validate_sql_runtime("SELECT * users").is_err());
223///
224/// // SQL 注入
225/// assert!(validate_sql_runtime("SELECT * FROM users WHERE name = 'x' OR '1'='1'").is_err());
226/// ```
227pub fn validate_sql_runtime(sql: &str) -> Result<(), String> {
228 validate_sql(sql).map_err(|e| e.to_string())
229}