You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
iTi-Flask/docs/ARCHITECTURE.md

125 lines
3.8 KiB
Markdown

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.

# 架构
iTi-Flask 是 FastAPI 框架基座。
它约束业务项目的工程方式,但不接管业务代码。
## 分层
- `iti.app`:应用工厂,组装 FastAPI、错误处理、模块、服务客户端、任务 runner、健康检查。
- `iti.config`dataclass 配置,默认 MySQL可通过 `DATABASE_DIALECT=postgresql` 使用 PostgreSQL。
- `iti.db`SQLAlchemy 2 `Base`、session、Alembic metadata。
- `iti.auth`JWT、Principal、Actor、用户权限依赖、服务 token 依赖。
- `iti.responses`:自动 envelope、`@raw_response`、响应工具。
- `iti.modules`:模块协议、权限元数据、菜单 seed 元数据。
- `iti.service_client`:同步 HTTP JSON 服务客户端。
- `iti.tasks`:单进程轻量任务注册和调度。
- `iti.audit`审计事件、diff、脱敏和异步 HTTP sender不拥有日志表。
- `iti.logging_config`:运行日志配置。
- `iti.cache`、`iti.limiter`、`iti.events`:常用通用能力。
- `iti.health``/health` 和 `/ready`
## 应用创建流程
`create_app()` 按顺序执行:
1. 解析配置。
2. 创建 `FastAPI`
3. 写入 `app.state.config/cache/limiter/permission_provider`
4. 配置 SQLAlchemy engine 和 sessionmaker。
5. 注册中间件、错误处理和运行日志。
6. 初始化服务客户端。
7. 初始化任务 runner。
8. 初始化审计 sender。
9. 初始化模块并运行 `init_app`、`register_tasks`。
10. 注册健康检查。
11. 注册模块路由、权限元数据和菜单 seed 元数据。
12. 安装自动 envelope。
## API 约定
业务 JSON API 默认返回 HTTP 200 envelope
```json
{"data": {}, "code": 200, "message": "成功"}
```
业务错误也包装进 envelope
```json
{"data": null, "code": 403, "message": "权限不足"}
```
成功时 `code` 固定为 `200`
业务错误、参数错误、框架 HTTP 错误都保留原始业务码,例如 `403`、`404`、`405`、`429`。
框架默认提供 JSON 错误响应,不提供服务端 HTML 错误页。
服务间 API 也默认使用 envelope。
框架服务客户端会自动识别 envelope 和 HTTP status。
如果响应体是 envelope则优先按 `code` 判断业务结果。
框架仍允许 raw 响应:
- `@raw_response`
- `raw_response_paths`
- `Response` / `FileResponse` / `StreamingResponse`
默认 raw
- `/health`
- `/ready`
- `/docs`
- `/openapi.json`
`/docs` 是文档入口。
它按 `docs_ui_enabled` 展示已启用的文档 UI。
默认包含 Swagger、Scalar 和 ReDoc。
`/openapi.json` 会按 tag 前缀生成 `x-tagGroups`
例如 `system.user` 会归入 `system` 分组。
## 鉴权
用户接口使用 JWT。
服务间调用使用静态服务 token。
双入口接口使用 `require_actor()`
- 用户 token 走权限码。
- 服务 token 只校验可信服务。
- 任一通过即可。
## 审计
`iti-flask` 只产生和发送审计事件。
它不写 `sys_log`
审计事件通过 `service_client` 发到配置的 `audit_service_name`
当前常见接收方是注册了 `iti-system` 的主业务项目。
审计发送默认异步、不阻塞业务。
diff 由业务显式提供 before / after 快照。
## 运行日志
运行日志由框架配置。
默认控制台输出。
生产可开启滚动文件:
- `runtime/logs/app.log`
- `runtime/logs/error.log`
请求摘要默认写入 app log。
摘要包含 method、path、HTTP status、业务 code、duration、actor、ip 和 trace id。
## 系统包边界
`iti-system` 只承载系统域业务:
- auth。
- user / role / menu / dept。
- config / dict。
- file / upload。
- log 查询和审计接收。
- user attributes。
业务项目单独使用 `iti-flask` 时,仍可使用鉴权依赖、权限 provider、数据库、迁移、缓存、限流、事件和任务。
加入 `iti-system` 时,只替换权限 provider 并增加系统域路由。