Files
liteadmin/DEVELOPMENT.md
T

239 lines
6.0 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# LiteAdmin 高可用多进程改造方案
## 环境约束
- Python 3.8.2 标准库,无任何第三方依赖
- Ubuntu 内网,无法联网
- 最多 2000 人同时使用
- 树莓派 4 核 CPU
## 改造目标
1. 多进程共享 session,重启不丢登录
2. Keep-Alive 支持,大幅降低 TCP 连接开销
3. 自动检测 CPU 核数调度 Worker
4. 配置化(端口、Worker 数、缓存 TTL 等)
5. 首页改为客户端渲染,降低服务端压力
6. 简单 API 缓存,减少数据库查询
---
## 第一轮(P0):Session 持久化 + Keep-Alive
### 1.1 Session 持久化到 SQLite
**文件:** `auth.py`
**问题:** 当前 `SessionStore` 使用内存 dict,多进程不共享,进程重启全部丢失。
**方案:** 在 SQLite 中创建 `session` 表,所有进程共享同一数据库文件。
```sql
CREATE TABLE IF NOT EXISTS session (
id TEXT PRIMARY KEY,
user_id INTEGER NOT NULL,
expires REAL NOT NULL,
data TEXT DEFAULT '{}',
created_at TEXT DEFAULT (datetime('now'))
)
```
**SessionStore 改造:**
- `create()` → INSERT INTO session
- `get()` → SELECT FROM session WHERE expires > now
- `delete()` → DELETE FROM session
- 启动时清理过期 session:`DELETE FROM session WHERE expires < ?`
**注意:** 多进程并发写入 SQLite 时,WAL 模式已开启(`PRAGMA journal_mode=WAL`),读写不互斥。session 写入量很小(每次登录一次),不会成为瓶颈。
### 1.2 Keep-Alive 支持
**文件:** `server.py`
**问题:** 当前 `HTTPResponse.to_bytes()` 写死 `Connection: close`,每个请求新建 TCP 连接。
**方案:** 在 `_handle_client` 中加循环,一个连接处理多个请求。
```python
async def _handle_client(self, reader, writer):
try:
while True:
request = await asyncio.wait_for(
HTTPRequest.parse(reader),
timeout=self.keepalive_timeout
)
if request is None:
break
# 处理请求...
response = await self._process_request(request)
# 设置 keep-alive 头
response.headers['Connection'] = 'keep-alive'
writer.write(response.to_bytes())
await writer.drain()
except asyncio.TimeoutError:
pass # 空闲超时,关闭连接
except Exception:
pass
finally:
try:
writer.close()
except Exception:
pass
```
**关键点:**
- `asyncio.wait_for()` 实现空闲超时
- 客户端关闭连接时 `reader.readline()` 返回空,自动退出循环
- `Connection: keep-alive` 头让浏览器复用连接
- 默认超时 30 秒,可在配置中调整
---
## 第二轮(P1):配置增强 + 自动 Worker + 首页客户端渲染 + API 缓存
### 2.1 配置增强
**文件:** `config.json`、`config.py`
**新增配置项:**
```json
{
"server": {
"host": "0.0.0.0",
"port": 8080,
"workers": 0,
"keepalive_timeout": 30,
"max_body_size": 524288000
},
"database": {
"path": "db/liteadmin.db",
"busy_timeout": 5000
},
"session": {
"store": "db",
"max_age": 86400
},
"cache": {
"home_ttl": 30,
"list_ttl": 10,
"detail_ttl": 5
}
}
```
`workers: 0` 表示自动检测 CPU 核数。
### 2.2 自动 Worker 调度
**文件:** `launcher.py`
```python
import multiprocessing
def get_worker_count():
cfg = load_config()
if cfg['server']['workers'] > 0:
return cfg['server']['workers']
cores = multiprocessing.cpu_count()
return max(1, cores - 1) # 留一个核给系统
```
### 2.3 首页改为客户端渲染
**文件:** `templates/home.html`、`app.py`
**现状:** 首页是服务端渲染的完整 HTML,每次请求都要查 DB + 渲染模板。
**改造:**
- `home.html` 改为只有 HTML 壳(base.html 继承 + JS 渲染)
- JS 通过 `/api/home/` 获取 JSON 数据并渲染
- 首页请求从 ~16KB 降到 ~2KB
### 2.4 简单 API 缓存
**文件:** `cache.py`(新建)
```python
import time
_cache = {}
_cache_config = {}
def init_cache(config):
_cache_config.update(config)
def get(key):
if key in _cache:
data, expire = _cache[key]
if time.time() < expire:
return data
del _cache[key]
return None
def set(key, data, ttl=10):
_cache[key] = (data, time.time() + ttl)
def clear():
_cache.clear()
def invalidate(prefix=''):
"""按前缀清除缓存"""
if not prefix:
_cache.clear()
else:
keys = [k for k in _cache if k.startswith(prefix)]
for k in keys:
del _cache[k]
```
**使用场景:**
- 首页 API:缓存 30 秒
- 列表 API:缓存 10 秒
- 详情 API:缓存 5 秒
- 写操作时清除对应前缀的缓存
---
## 第三轮(P2):静态文件缓存 + 翻页优化
### 3.1 静态文件 Cache-Control
**文件:** `server.py`
静态文件响应加 `Cache-Control: public, max-age=86400`,浏览器缓存一天。
### 3.2 翻页组件优化
**文件:** 各前端模板
翻页逻辑已优化过(智能省略号),无需改动。
---
## 实施顺序
```
第一轮(P0)→ Session 持久化 + Keep-Alive
├── auth.py: SessionStore 改为 SQLite 存储
├── server.py: 添加 Keep-Alive 循环
└── 验证:多进程启动,登录后 kill 主进程再启动,session 不丢
第二轮(P1)→ 配置 + Worker + 首页 + 缓存
├── config.json: 新增配置项
├── config.py: 读取新配置
├── launcher.py: 自动检测 CPU 核数
├── cache.py: 简单 TTL 缓存
├── templates/home.html: 改为客户端渲染
└── app.py: 首页路由简化 + 缓存接入
第三轮(P2)→ 静态文件缓存
└── server.py: 静态文件加 Cache-Control
```
## 安全考虑
- Session 数据存 SQLite,不存敏感信息(只存 user_id)
- CSRF token 仍存内存 session(每个进程独立,不影响安全)
- 密码仍使用 SHA-256 加盐哈希
- 文件上传类型白名单不变
- 路径穿越防护不变