topfans/docs/superpowers/specs/2026-04-13-hot-reload-dev-script-design.md
zerosaturation a77e16a150 docs: translate hot-reload dev script spec to Chinese
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-13 12:02:12 +08:00

81 lines
3.1 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.

# 热更新开发脚本设计 (dev.sh)
## 1. 概述
`dev.sh` 是一个开发脚本,用于启动所有后端微服务并监听文件变化,实现热更新。当某个服务的 `.go` 文件发生变更时,只重新编译和重启该服务。
## 2. 架构
```
dev.sh
├── 加载 .env 文件(与 start.sh 相同)
├── 按依赖顺序启动所有服务(后台运行)
└── 并发运行多个文件监听器(后台运行)
├── watcher(gateway) → 监听 gateway/ → 重启 gateway
├── watcher(userService) → 监听 services/userService/ → 重启 userService
├── watcher(assetService) → 监听 services/assetService/ → 重启 assetService
├── watcher(socialService) → 监听 services/socialService/ → 重启 socialService
├── watcher(galleryService) → 监听 services/galleryService/ → 重启 galleryService
└── watcher(activityService) → 监听 services/activityService/ → 重启 activityService
```
## 3. 服务启动顺序
`start.sh` 保持一致:
1. userService (端口 20000)
2. assetService (端口 20003)
3. socialService (端口 20002)
4. galleryService (端口 20004)
5. activityService (端口 20005)
6. gateway (端口 8080)
## 4. 监听器行为
每个服务对应一个独立的监听器:
- **监听范围**: `<service_dir>/**/*.go`
- **触发条件**: 任意 `.go` 文件的创建/修改/写入事件
- **防抖**: 300ms 冷却期 —— 触发重启后300ms 内的后续事件会被忽略,避免频繁重建
- **操作步骤**(在服务自己的模块目录下执行,与 `start.sh` 一致):
1. 重新编译: `cd <service_dir> && go build -o <binary> .`
2. **构建失败安全**: 若编译失败,记录错误日志,保持旧进程继续运行
3. 仅在编译成功后: 终止旧进程
4. 使用与 `start.sh` 相同的参数启动新进程
5. 在控制台输出热更新事件(青色)
## 5. 依赖工具
- **Mac**: `fswatch`(通过 `brew install fswatch` 安装)
- **Linux**: `inotifywait`(通过系统包管理器安装)
若所需工具未安装,脚本打印安装说明后退出。
## 6. 信号处理
- **Ctrl+C / SIGINT / SIGTERM**: 使用 `trap` 捕获信号,停止所有服务和监听器后退出
- 退出时按启动相反顺序(先 gateway再各个服务杀灭所有进程
## 7. 日志
- 各服务日志写入 `/tmp/<service_name>.log`(与 start.sh 相同)
- 控制台显示变更的文件路径和被重启的服务
- 热更新事件以青色输出
## 8. 文件结构
```
backend/
├── dev.sh # 热更新开发脚本(新增)
└── start.sh # 生产环境启动脚本(现有)
```
## 9. 边界情况
- **构建失败**: 旧进程保持运行,错误同时记录到控制台和 `/tmp/<service>.log`
- **监听目录不存在**: 脚本退出并报错
- **工具未安装**: 打印安装说明后退出
- **文件快速连续变更**: 300ms 防抖机制确保每批变更最多触发一次重启
## 10. 不修改现有文件
`dev.sh` 不修改任何现有文件,仅参考 `start.sh` 的实现逻辑,并新增一个文件。