21 Commits

Author SHA1 Message Date
wonder b95bcde445 chore: 移除 Gitee 平台相关配置文件 2026-05-29 16:57:56 +08:00
wonder c7b2313351 docs: 新增限流与协程池实施计划 2026-05-29 16:55:37 +08:00
wonder 39cef82eff docs: 补充哔哩哔哩视频链接
Signed-off-by: 何朝晖 <hezhaohui0807@163.com>
2026-05-25 15:39:34 +00:00
wonder 0493d900dc !81 docs: 优化 README
Merge pull request !81 from 何朝晖/N/A
2026-05-25 13:55:05 +00:00
wonder cccd1c5428 docs: 优化 README
Signed-off-by: 何朝晖 <hezhaohui0807@163.com>
2026-05-25 13:54:43 +00:00
Gmarker689 03cecab59b !80 fix: 将帧动画与单独帧分开为独立分类
Merge pull request !80 from 郭永昊/fix/tag-labels-and-click
2026-05-25 13:37:12 +00:00
Gmarker689 9af74408b8 fix: 将帧动画与单独帧分开为独立分类
- 新增「帧动画」分类:匹配 metaType=preview 或 format=gif
- 「帧」分类仅匹配 metaType=frame(静态单帧)
2026-05-25 21:36:04 +08:00
wonder 5a6aba16a0 !79 fix: 详情弹窗使用 Portal 渲染到 body,确保始终居中
Merge pull request !79 from 郭永昊/fix/tag-labels-and-click
2026-05-25 13:35:49 +00:00
wonder 433bf88698 Merge branch 'master' of gitee.com:hezhaohui123/gen2d into fix/tag-labels-and-click
Signed-off-by: 何朝晖 <hezhaohui0807@163.com>
2026-05-25 13:35:26 +00:00
Gmarker689 882e05955b fix: 详情弹窗使用 Portal 渲染到 body,确保始终居中
父级 .page-enter 动画中的 transform 创建了新的 CSS containing block,
导致 position:fixed 相对父级而非视口定位。改用 createPortal 渲染到
document.body 绕过此限制。
2026-05-25 21:31:27 +08:00
Gmarker689 55aaa26549 docs: 在 README 架构章节添加全局/后端/前端架构图 2026-05-25 21:30:35 +08:00
Gmarker689 96285014b1 feat: 首页素材点击查看详情,支持下载
- 后端 GetRecentAssets 增加 projectName/width/height/projectId 字段
- 前端 AssetGallery 点击图片弹出详情弹窗:提示词/工程/分辨率/格式
- 详情弹窗提供下载按钮,走 /api/v1/assets/download?key= 接口
2026-05-25 21:28:54 +08:00
Gmarker689 e650cea11c !77 feat: 首页素材画廊增加分类筛选标签
Merge pull request !77 from 郭永昊/fix/tag-labels-and-click
2026-05-25 13:08:38 +00:00
Gmarker689 1a78744766 feat: 首页素材画廊增加分类筛选标签
- 后端 SQL 增加 json_extract 提取素材 metaType (frame/spritesheet/preview)
- 前端 AssetGallery 新增分类标签栏:全部/精灵表/帧/场景瓦片/背景/UI
- 按 metaType + assetType 组合过滤展示
2026-05-25 21:07:15 +08:00
wonder d611a2c142 !76 docs: 添加全局/后端/前端架构图生成提示词
Merge pull request !76 from 何朝晖/docs/README
2026-05-25 13:04:39 +00:00
Gmarker689 b88f9aaf03 feat: 首页展示最近生成的素材画廊
- 后端新增 GET /api/v1/assets 接口,返回已完成任务的素材列表(按创建时间倒序)
- 前端新增 AssetGallery 组件,网格展示素材缩略图、类型标签和提示词
- HomePage 中工程列表上方展示最近生成素材
2026-05-25 21:02:03 +08:00
Gmarker689 5be74e3ce1 feat: 左上角品牌图标更换为自定义 logo
- 文本 "gen2d" 替换为 logo.png 图片
- 同时更新浏览器 favicon
2026-05-25 20:52:06 +08:00
Gmarker689 8e3b576954 feat: 更换网页图标为自定义 favicon 2026-05-25 20:49:47 +08:00
wonder d30bee18a7 !75 !74 fix: 任务侧边栏点击详情后"任务不存在"问题
Merge pull request !75 from 何朝晖/develop
2026-05-25 12:30:29 +00:00
Gmarker689 47b31b5c13 !71 !70 fix: 自定义标签融入原生标签栏,点击切换而非消失
Merge pull request !71 from 郭永昊/develop
2026-05-25 12:06:51 +00:00
Gmarker689 7cc472052f !68 !67 fix: 修复管线context取消、添加FIFO任务队列、移除重复提示词优化
Merge pull request !68 from 何朝晖/develop
2026-05-25 11:13:54 +00:00
18 changed files with 829 additions and 61 deletions
-13
View File
@@ -1,13 +0,0 @@
### 该问题是怎么引起的?
### 重现步骤
### 报错信息
-12
View File
@@ -1,12 +0,0 @@
### 相关的Issue
### 原因(目的、解决的问题等)
### 描述(做了什么,变更了什么)
### 测试用例(新增、改动、可能影响的功能)
-32
View File
@@ -1,32 +0,0 @@
version: '1.0'
name: pipeline-20260525
displayName: pipeline-20260525
triggers:
trigger: auto
push:
branches:
precise:
- master
stages:
- name: stage-b0e54961
displayName: deploy
strategy: naturally
trigger: auto
executor: []
steps:
- step: shell@agent
name: execute_shell
displayName: Shell 脚本执行
schedulerType: DISTRIBUTED
hostGroupID:
ID: i-f8zc4nf8y8u267zwn9vw
hostID:
- 0c13eac4-c35d-455e-a162-ce11a0ab9e37
scriptType: SH
script:
- cd ~/gen2d
- ./deploy.sh
gitClone: false
notify: []
strategy:
retry: '0'
+16
View File
@@ -26,6 +26,18 @@
<b><a href="#api">API</a></b>
</p>
> 🎈 **哔哩哔哩视频**:【七牛云 XEngineer 暑期实训营 | 2D 游戏素材 | 团体作品演示】 https://www.bilibili.com/video/BV1jAGo6DEbC
> 🔥 **在线体验**:http://47.121.181.112:10000/
> 详细架构说明见 [docs/_index.md](docs/_index.md)。
![全局架构](assets/global-architecture.png)
![后端架构](assets/backend-architecture.png)
![前端架构](assets/frontend-architecture.png)
---
## 目录
@@ -161,6 +173,8 @@ graph TD
C --> D["三段式规范提示词<br/>【主题】【风格】【技术】"]
```
### 预设风格键
| 分类 | 键名 | 可选值示例 |
@@ -172,6 +186,8 @@ graph TD
| 光照 | `lighting` | bright, dim, dramatic, ambient, neon |
| 情绪 | `mood` | cheerful, dark, mysterious, epic, calm |
## API
接口统一前缀 `/api/v1/`,统一响应格式:
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 MiB

+1
View File
@@ -78,6 +78,7 @@ func main() {
v1Auth.POST("/generate", handler.Generate) // 素材生成管线
v1Auth.GET("/tasks/:taskId", handler.GetTask) // 查询任务
v1Auth.GET("/tasks/:taskId/assets", handler.GetAssets) // 查询任务素材
v1Auth.GET("/assets", handler.GetRecentAssets) // 首页最近素材
// 图片编辑
v1Auth.POST("/images/edit", handler.EditImage) // 图片编辑
}
+72
View File
@@ -306,6 +306,78 @@ func getTaskDBID(ctx context.Context, taskID string) uint {
return task.ID
}
// RecentAssetItem 首页素材展示项。
type RecentAssetItem struct {
Key string `json:"key"`
URL string `json:"url"`
Format string `json:"format"`
Prompt string `json:"prompt"`
AssetType string `json:"assetType"`
MetaType string `json:"metaType"`
TaskID string `json:"taskId"`
ProjectID string `json:"projectId"`
ProjectName string `json:"projectName"`
Width int `json:"width"`
Height int `json:"height"`
CreatedAt string `json:"createdAt"`
}
// GetRecentAssets 获取最近生成的素材列表(已完成任务的全部素材)。
func GetRecentAssets(c *gin.Context) {
limit := 60
var dbRows []struct {
Key string
URL string
Format string
Prompt string
AssetType string
MetaType string
TaskID string
ProjectID uint
ProjectName string
Width int
Height int
CreatedAt string
}
db.GetDB().WithContext(c.Request.Context()).
Raw(`SELECT a.key, a.url, a.format, t.prompt, t.asset_type as asset_type,
COALESCE(json_extract(a.metadata, '$.type'), 'frame') as meta_type,
t.external_id as task_id, t.project_id,
p.name as project_name,
CAST(COALESCE(json_extract(t.metadata, '$.frameWidth'), '0') AS INTEGER) as width,
CAST(COALESCE(json_extract(t.metadata, '$.frameHeight'), '0') AS INTEGER) as height,
t.created_at as created_at
FROM assets a
INNER JOIN tasks t ON a.task_id = t.id
INNER JOIN projects p ON t.project_id = p.id
WHERE t.status = 'completed'
ORDER BY a.created_at DESC
LIMIT ?`, limit).
Scan(&dbRows)
result := make([]RecentAssetItem, len(dbRows))
for i, r := range dbRows {
result[i] = RecentAssetItem{
Key: r.Key,
URL: storageSvc.GetSignedURL(r.Key),
Format: r.Format,
Prompt: r.Prompt,
AssetType: r.AssetType,
MetaType: r.MetaType,
TaskID: r.TaskID,
ProjectID: fmt.Sprintf("%d", r.ProjectID),
ProjectName: r.ProjectName,
Width: r.Width,
Height: r.Height,
CreatedAt: r.CreatedAt,
}
}
c.JSON(http.StatusOK, model.OK(result))
}
// toTaskResponse 转换任务响应格式。
func toTaskResponse(task *model.Task) model.TaskResponse {
return model.TaskResponse{
+431
View File
@@ -0,0 +1,431 @@
# 实施计划:限流 + 协程池 + 消息队列
> 基于简历描述,本项目需要落地两个核心能力:
> 1. 基于 go-redis 的分布式令牌桶限流
> 2. 自定义 IO 密集型协程池 + RabbitMQ 消息队列
## 现状分析
| 维度 | 当前状态 | 目标状态 |
|------|---------|---------|
| 限流 | 无任何限流中间件;API 错误码 429 已预留但未实现 | 令牌桶算法,支持按用户/全局维度限流 |
| 并发控制 | 每个请求裸 `go` 起协程,无上限 | 有界协程池,可控并发度 |
| 任务队列 | 同步阻塞,任务状态通过 DB 轮询 | RabbitMQ 异步队列,生产者-消费者模式 |
| 基础设施 | SQLite + 七牛云,无 Redis / MQ | 新增 Redis + RabbitMQ 依赖 |
---
## 阶段一:基础设施接入
### 1.1 Redis 接入
**新增依赖:** `github.com/redis/go-redis/v9`
**新增配置:** `internal/config/redis.go`
```go
type RedisConfig struct {
Addr string `yaml:"addr"` // 默认 "localhost:6379"
Password string `yaml:"password"`
DB int `yaml:"db"` // 默认 0
}
```
**新增初始化:** `internal/pkg/redis/client.go` — 全局 `*redis.Client` 单例,`InitRedis(cfg)` + `CloseRedis()`,在 `cmd/main.go` 启动时调用。
**配置文件:** `config.yaml` 新增 `redis` 节。
### 1.2 RabbitMQ 接入
**新增依赖:** `github.com/rabbitmq/amqp091-go`
**新增配置:** `internal/config/rabbitmq.go`
```go
type RabbitMQConfig struct {
URL string `yaml:"url"` // 默认 "amqp://guest:guest@localhost:5672/"
Queue string `yaml:"queue"` // 默认 "gen2d:tasks"
}
```
**新增初始化:** `internal/pkg/mq/rabbitmq.go` — 封装连接、Channel、Queue 声明,提供 `Publish(body)` 和 `Consume(handler)` 方法。
**Docker Compose:** 新增 `docker-compose.yml`(或更新已有文件),包含 Redis 和 RabbitMQ 服务。
---
## 阶段二:分布式令牌桶限流
### 2.1 算法选型分析
| 方案 | 优点 | 缺点 | 适用场景 |
|------|------|------|---------|
| 固定窗口计数器 | 实现简单 | 窗口边界突发 | 对精度要求不高的场景 |
| 滑动窗口 | 解决边界问题 | 内存开销较大 | 中等精度需求 |
| 漏桶 | 平滑输出 | 无法应对突发 | 流量整形 |
| **令牌桶** | 平滑 + 允许突发 | 实现稍复杂 | **API 限流(本项目选用)** |
**选用令牌桶理由:**
- 用户提交生成任务时存在突发行为(连续点几次生成),令牌桶允许一定的突发消费
- go-redis 社区有成熟的 Lua 脚本实现,原子性有保证
- 天然支持分布式,未来多实例部署无缝扩展
### 2.2 实现方案
**新增包:** `internal/pkg/ratelimit/`
```
internal/pkg/ratelimit/
├── limiter.go // 接口定义 + 令牌桶实现
├── middleware.go // Gin 限流中间件
└── config.go // 限流配置
```
**核心接口:**
```go
// limiter.go
type Limiter interface {
// Allow 检查 key 是否允许通过,返回 (是否允许, 剩余令牌数, 重试等待时间)
Allow(ctx context.Context, key string) (bool, int, time.Duration)
}
```
**令牌桶实现要点:**
- 底层使用 Redis + Lua 脚本保证原子性(单次 Redis 请求完成令牌检查 + 扣减)
- Lua 脚本逻辑:计算上次调用到当前的时间差 → 按速率补充令牌 → 判断桶内令牌是否足够 → 扣减并返回
- Key 设计:`ratelimit:{scope}:{identifier}`,例如 `ratelimit:user:123` 或 `ratelimit:global:generate`
- 支持两级限流:用户级(per-user)+ 全局级(per-endpoint)
**配置:**
```go
// config.go
type Config struct {
Rate int // 每秒产生的令牌数
Burst int // 桶容量(允许的突发量)
KeyPrefix string // Redis key 前缀
Expiration time.Duration // key 过期时间,防止冷用户占用内存
}
```
**推荐参数(生成接口):**
- 用户级:Rate=1/s, Burst=3(允许用户连续提交 3 个任务,之后每秒最多 1 个)
- 全局级:Rate=10/s, Burst=20(系统总并发上限)
### 2.3 Gin 中间件集成
**middleware.go:**
```go
func RateLimit(limiter Limiter, keyFunc func(c *gin.Context) string) gin.HandlerFunc
```
- `keyFunc` 负责从请求中提取限流 key(如 JWT 中的 userID,或 endpoint 标识)
- 被限流时返回 HTTP 429 + 统一错误格式 `{"code": 429, "message": "请求过于频繁,请稍后再试", "data": nil}`
- 响应头添加 `X-RateLimit-Remaining` 和 `Retry-After`
**路由注册(修改 `internal/router/router.go`):**
```go
// 用户级限流 — 基于 JWT userID
authGroup.Use(ratelimit.RateLimit(userLimiter, func(c *gin.Context) string {
return c.GetString("userID")
}))
// 生成接口额外加全局限流
v1.POST("/generate", ratelimit.RateLimit(globalLimiter, func(c *gin.Context) string {
return "generate"
}), generateHandler.Create)
```
---
## 阶段三:自定义协程池
### 3.1 设计思路
当前问题:每个 `POST /api/v1/generate` 裸起 `go RunPipeline()`,在高并发下可能耗尽系统资源(goroutine 数、文件描述符、DB 连接)。
**方案选型:**
| 方案 | 优点 | 缺点 | 适用场景 |
|------|------|------|---------|
| `ants` 库 | 开箱即用,成熟 | 黑盒,简历无亮点 | 快速实现 |
| **手写协程池** | 可控性强,体现设计能力 | 需要维护 | **本项目选用** |
| Semaphore | 极简 | 无排队机制 | 临时方案 |
**选用自定义协程池理由:**
- 简历明确写"自定义 IO 密集型协程池",需要有手写实现
- 可以针对 IO 密集型特征做专门调参(worker 数可设为 CPU 核数的数倍)
- 可以与 RabbitMQ 消费者共用池,统一管理
### 3.2 实现方案
**新增包:** `internal/pkg/workerpool/`
```
internal/pkg/workerpool/
├── pool.go // 协程池核心实现
├── option.go // 配置选项(函数选项模式)
└── task.go // 任务定义
```
**核心结构:**
```go
// pool.go
type Pool struct {
workers int // worker 数量
taskQueue chan Task // 有界任务队列
wg sync.WaitGroup
ctx context.Context
cancel context.CancelFunc
metrics *Metrics // 运行指标
}
type Task struct {
ID string
Fn func(ctx context.Context) error
Priority int // 预留优先级支持
}
type Metrics struct {
ActiveWorkers atomic.Int32
QueuedTasks atomic.Int32
CompletedTasks atomic.Int64
FailedTasks atomic.Int64
}
```
**关键设计点:**
1. **IO 密集型调参:** 默认 worker 数 = `runtime.NumCPU() * 4`(而非 CPU 密集型的 1:1),通过 `WithWorkers(n)` 可覆盖
2. **有界队列:** `taskQueue` channel 容量有上限(默认 100),满时提交阻塞或返回 `ErrPoolFull`,防止任务无限堆积
3. **优雅关闭:** `Shutdown(ctx)` 等待所有正在执行的任务完成或 ctx 超时
4. **指标暴露:** 活跃 worker 数、排队任务数、完成/失败任务数,通过 `GET /api/v1/metrics` 或 Prometheus 格式暴露
**函数选项模式配置:**
```go
// option.go
type Option func(*Pool)
func WithWorkers(n int) Option // 自定义 worker 数
func WithQueueSize(n int) Option // 自定义队列容量
func WithMetrics(reg prometheus.Registerer) Option // 注册 Prometheus 指标
```
### 3.3 接入服务层
**修改 `internal/service/generate.go`:**
```go
// Before:
go svc.runPipeline(ctx, taskID, input)
// After:
err := svc.pool.Submit(workerpool.Task{
ID: taskID,
Fn: func(ctx context.Context) error {
return svc.runPipeline(ctx, taskID, input)
},
})
if err != nil {
// 更新任务状态为 failed,记录原因
return err
}
```
---
## 阶段四:RabbitMQ 消息队列
### 4.1 架构设计
```
POST /api/v1/generate
│
▼
┌─────────────┐ ┌──────────────┐ ┌─────────────────┐
│ Producer │────▶│ RabbitMQ │────▶│ Consumer │
│ (API Handler)│ │ gen2d:tasks │ │ (Worker Goroutine)│
└─────────────┘ └──────────────┘ └────────┬────────┘
│
▼
┌─────────────────┐
│ Worker Pool │
│ (协程池执行 Pipeline)│
└─────────────────┘
```
**同步路径(现有,保留):** 简单请求、Prompt 优化等轻量操作仍走 HTTP 同步返回。
**异步路径(新增):** `POST /api/v1/generate` → 生产者发送消息到 RabbitMQ → 消费者从队列取出 → 提交到协程池执行 Pipeline。
### 4.2 消息格式
```go
// internal/pkg/mq/message.go
type TaskMessage struct {
TaskID string `json:"task_id"`
UserID string `json:"user_id"`
Input service.PipelineInput `json:"input"`
CreatedAt time.Time `json:"created_at"`
RetryCount int `json:"retry_count"`
}
```
### 4.3 生产者(API Handler 层)
**修改 `internal/handler/generate.go`:**
```go
func (h *GenerateHandler) Create(c *gin.Context) {
// 1. 参数绑定、校验
// 2. 去重检查(现有逻辑保留)
// 3. 创建 DB 任务记录(status=pending)
// 4. 发布消息到 RabbitMQ(替代原来的 go runPipeline)
err := h.mq.Publish(ctx, mq.TaskMessage{...})
// 5. 返回 taskId
}
```
### 4.4 消费者(独立启动)
**新增:** `internal/worker/consumer.go`
```go
type Consumer struct {
mq *mq.RabbitMQ
pool *workerpool.Pool
service *service.GenerateService
logger *slog.Logger
}
func (c *Consumer) Start(ctx context.Context) error {
// 持续消费 RabbitMQ 消息
// 每条消息提交到协程池执行
return c.mq.Consume(ctx, func(msg mq.TaskMessage) error {
return c.pool.Submit(workerpool.Task{
ID: msg.TaskID,
Fn: func(ctx context.Context) error {
return c.service.RunPipeline(ctx, msg.TaskID, msg.Input)
},
})
})
}
```
**启动方式:** `cmd/main.go` 中,API 服务和消费者在同一个进程内启动(通过配置开关控制是否启用消费者),便于开发调试;生产环境可拆分为独立进程。
### 4.5 消息可靠性
| 环节 | 保障措施 |
|------|---------|
| 生产者发送失败 | 降级为同步执行(fallback),记录告警日志 |
| 消费者处理失败 | RabbitMQ NACK + 重新入队(max retry = 3) |
| 消费者崩溃 | 手动 ACK 模式,未 ACK 的消息自动重新投递 |
| 消息堆积 | 监控队列深度,超阈值触发告警 |
---
## 阶段五:可观测性与配置
### 5.1 运行指标
新增 `GET /api/v1/metrics` 接口(或接入 Prometheus),暴露:
- **限流指标:** 各 key 被限流次数、当前令牌数
- **协程池指标:** 活跃 worker 数、队列深度、任务完成/失败数、平均执行耗时
- **MQ 指标:** 队列深度、生产/消费速率、NACK 次数
### 5.2 配置汇总
新增配置项(`config.yaml`):
```yaml
redis:
addr: "localhost:6379"
password: ""
db: 0
rabbitmq:
url: "amqp://guest:guest@localhost:5672/"
queue: "gen2d:tasks"
ratelimit:
user:
rate: 1
burst: 3
global:
rate: 10
burst: 20
workerpool:
workers: 16 # NumCPU * 4
queue_size: 100
consumer_enabled: true
```
---
## 文件变更清单
### 新增文件
| 文件路径 | 用途 |
|---------|------|
| `internal/config/redis.go` | Redis 配置结构体 |
| `internal/config/rabbitmq.go` | RabbitMQ 配置结构体 |
| `internal/pkg/redis/client.go` | Redis 客户端初始化 |
| `internal/pkg/mq/rabbitmq.go` | RabbitMQ 连接封装 |
| `internal/pkg/mq/message.go` | 消息体定义 |
| `internal/pkg/ratelimit/limiter.go` | 令牌桶限流器 |
| `internal/pkg/ratelimit/middleware.go` | Gin 限流中间件 |
| `internal/pkg/ratelimit/config.go` | 限流配置 |
| `internal/pkg/workerpool/pool.go` | 协程池核心 |
| `internal/pkg/workerpool/option.go` | 协程池配置选项 |
| `internal/pkg/workerpool/task.go` | 任务定义 |
| `internal/worker/consumer.go` | MQ 消费者 |
| `docker-compose.yml` | Redis + RabbitMQ 服务编排 |
### 修改文件
| 文件路径 | 变更内容 |
|---------|---------|
| `cmd/main.go` | 初始化 Redis、RabbitMQ、WorkerPool;启动 Consumer |
| `internal/config/config.go` | 顶层 Config 新增 Redis / RabbitMQ / Ratelimit / WorkerPool 字段 |
| `internal/router/router.go` | 注册限流中间件 |
| `internal/handler/generate.go` | 将 `go runPipeline` 改为发布 MQ 消息 |
| `internal/service/generate.go` | 接受协程池提交,`RunPipeline` 签名不变 |
| `config.yaml` | 新增 redis / rabbitmq / ratelimit / workerpool 配置节 |
| `go.mod` | 新增 go-redis、amqp091-go 依赖 |
---
## 实施顺序建议
```
Phase 1: 基础设施(Redis + RabbitMQ 接入、配置、初始化)
↓
Phase 2: 令牌桶限流(独立模块,可先接入不影响其他功能)
↓
Phase 3: 协程池(独立模块,替换裸 go 调用)
↓
Phase 4: MQ 异步化(依赖协程池,改造生成流程)
↓
Phase 5: 可观测性(指标暴露、告警配置)
```
Phase 2 和 Phase 3 可并行开发,Phase 4 依赖 Phase 3 完成。
---
## 注意事项
1. **向后兼容:** 各阶段独立可部署,不依赖全部完成才能上线。限流可以先上线,协程池和 MQ 可以后续接入。
2. **开发环境:** `docker-compose.yml` 提供 Redis + RabbitMQ,前端开发者无需关心。
3. **降级策略:** Redis 不可用时限流中间件自动放行(fail-open);RabbitMQ 不可用时降级为同步执行。
4. **测试覆盖:** 每个模块需编写单元测试 + 集成测试。限流器可用 `miniredis` 做内存 Redis 测试;协程池测试并发正确性;MQ 测试用 `rabbitmq-testcontainers` 或本地 Docker。
+1
View File
@@ -17,6 +17,7 @@ Go + Gin + Eino / Vite + React + TypeScript + zustand / SQLite / 七牛云对象
| [异步任务](async-tasks.md) | 任务生命周期、并发控制、重试策略、进度推送 |
| [预设风格键](style-keys.md) | 美术风格、色调、线条等风格键分类与可选值 |
| [架构图提示词](prompts/) | 全局/后端/前端架构图生成提示词,供多模态 AI 生成架构图 |
| [实施计划](PLAN.md) | 限流(令牌桶)、协程池、RabbitMQ 异步化的详细设计方案与实施步骤 |
## 系统架构
+1
View File
@@ -3,6 +3,7 @@
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="icon" type="image/png" href="/logo.png" />
<title>gen2d</title>
</head>
<body>
Binary file not shown.

After

Width:  |  Height:  |  Size: 40 KiB

+5
View File
@@ -1,4 +1,9 @@
import { post, get } from './client'
import type { RecentAssetItem } from './types'
export async function getRecentAssets(): Promise<RecentAssetItem[]> {
return get<RecentAssetItem[]>('/api/v1/assets')
}
import type {
Asset,
AssetsResponse,
+16
View File
@@ -98,6 +98,22 @@ export interface Asset {
index: number
}
// 首页最近素材
export interface RecentAssetItem {
key: string
url: string
format: string
prompt: string
assetType: string
metaType: string
taskId: string
projectId: string
projectName: string
width: number
height: number
createdAt: string
}
// 生成请求 — 对应 POST /api/v1/generate
export interface GenerateRequest {
projectId: string
+276
View File
@@ -0,0 +1,276 @@
import { useEffect, useState, useMemo } from 'react'
import { createPortal } from 'react-dom'
import { getRecentAssets } from '../api/generate'
import type { RecentAssetItem } from '../api/types'
const ASSET_TYPE_LABELS: Record<string, string> = {
sprite: '精灵',
background: '背景',
ui: 'UI',
animation: '动画',
}
const CATEGORIES = [
{ key: 'all', label: '全部' },
{ key: 'spritesheet', label: '精灵表' },
{ key: 'frame', label: '帧' },
{ key: 'animation', label: '帧动画' },
{ key: 'tileset', label: '场景瓦片' },
{ key: 'background', label: '背景' },
{ key: 'ui', label: 'UI' },
]
function matchCategory(item: RecentAssetItem, cat: string): boolean {
switch (cat) {
case 'all':
return true
case 'spritesheet':
return item.metaType === 'spritesheet'
case 'frame':
return item.metaType === 'frame'
case 'animation':
return item.metaType === 'preview' || item.format === 'gif'
case 'tileset':
return item.assetType === 'sprite' && item.metaType === 'spritesheet'
case 'background':
return item.assetType === 'background'
case 'ui':
return item.assetType === 'ui'
default:
return true
}
}
function DetailModal({ item, onClose }: { item: RecentAssetItem; onClose: () => void }) {
const downloadUrl = `/api/v1/assets/download?key=${encodeURIComponent(item.key)}`
return createPortal(
<div
style={{
position: 'fixed',
inset: 0,
zIndex: 1000,
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
}}
onClick={onClose}
>
<div
style={{ position: 'absolute', inset: 0, background: 'rgba(0,0,0,0.6)' }}
/>
<div
className="card"
style={{
position: 'relative',
zIndex: 1,
maxWidth: 640,
width: '90%',
maxHeight: '90vh',
overflow: 'auto',
padding: 24,
}}
onClick={e => e.stopPropagation()}
>
<button
onClick={onClose}
style={{
position: 'absolute',
top: 12,
right: 12,
background: 'transparent',
border: 'none',
fontSize: 20,
cursor: 'pointer',
color: 'var(--text-secondary)',
lineHeight: 1,
}}
>
x
</button>
<div
style={{
width: '100%',
background: 'var(--bg-input)',
borderRadius: 'var(--radius)',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
marginBottom: 20,
minHeight: 200,
}}
>
<img
src={item.url}
alt={item.prompt}
style={{ maxWidth: '100%', maxHeight: 400, objectFit: 'contain' }}
/>
</div>
<table style={{ width: '100%', fontSize: 13, borderCollapse: 'collapse' }}>
<tbody>
<Row label="提示词" value={item.prompt} />
<Row label="工程" value={item.projectName} />
<Row label="素材类型" value={`${ASSET_TYPE_LABELS[item.assetType] || item.assetType} / ${item.metaType}`} />
<Row label="分辨率" value={item.width > 0 ? `${item.width} x ${item.height}` : '—'} />
<Row label="格式" value={item.format} />
</tbody>
</table>
<div style={{ marginTop: 20, display: 'flex', gap: 12, justifyContent: 'flex-end' }}>
<a
href={downloadUrl}
className="btn-primary"
style={{ textDecoration: 'none', padding: '8px 24px', fontSize: 14 }}
download
>
下载
</a>
<button className="btn-secondary" onClick={onClose} style={{ padding: '8px 24px', fontSize: 14 }}>
关闭
</button>
</div>
</div>
</div>,
document.body
)
}
function Row({ label, value }: { label: string; value: string }) {
return (
<tr>
<td style={{ padding: '6px 12px 6px 0', color: 'var(--text-secondary)', whiteSpace: 'nowrap', verticalAlign: 'top', width: 80 }}>
{label}
</td>
<td style={{ padding: '6px 0', wordBreak: 'break-all' }}>{value}</td>
</tr>
)
}
export default function AssetGallery() {
const [assets, setAssets] = useState<RecentAssetItem[]>([])
const [loading, setLoading] = useState(true)
const [activeCat, setActiveCat] = useState('all')
const [detailItem, setDetailItem] = useState<RecentAssetItem | null>(null)
useEffect(() => {
getRecentAssets()
.then(setAssets)
.catch(() => {})
.finally(() => setLoading(false))
}, [])
const filtered = useMemo(
() => assets.filter(item => matchCategory(item, activeCat)),
[assets, activeCat]
)
if (loading) return null
if (assets.length === 0) return null
return (
<section style={{ marginBottom: 32 }}>
<h2 style={{ fontSize: 18, marginBottom: 12 }}>最近生成</h2>
{/* 分类标签 */}
<div style={{ display: 'flex', gap: 8, marginBottom: 16, flexWrap: 'wrap' }}>
{CATEGORIES.map(cat => (
<button
key={cat.key}
type="button"
onClick={() => setActiveCat(cat.key)}
style={{
fontSize: 13,
padding: '4px 14px',
borderRadius: 999,
border: `1px solid ${activeCat === cat.key ? 'var(--accent)' : 'var(--border)'}`,
background: activeCat === cat.key ? 'var(--accent-dim)' : 'transparent',
color: activeCat === cat.key ? 'var(--accent)' : 'var(--text-secondary)',
cursor: 'pointer',
fontWeight: activeCat === cat.key ? 600 : 400,
}}
>
{cat.label}
</button>
))}
</div>
{/* 素材网格 */}
{filtered.length === 0 ? (
<p style={{ fontSize: 13, color: 'var(--text-muted)' }}>暂无此类素材</p>
) : (
<div
style={{
display: 'grid',
gridTemplateColumns: 'repeat(auto-fill, minmax(180px, 1fr))',
gap: 12,
}}
>
{filtered.map((item, i) => (
<div
key={`${item.taskId}-${i}`}
className="card"
style={{ padding: 8, cursor: 'pointer' }}
onClick={() => setDetailItem(item)}
>
<div
style={{
width: '100%',
aspectRatio: '1',
overflow: 'hidden',
borderRadius: 'var(--radius)',
background: 'var(--bg-input)',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
}}
>
<img
src={item.url}
alt={item.prompt}
loading="lazy"
style={{
maxWidth: '100%',
maxHeight: '100%',
objectFit: 'contain',
}}
/>
</div>
<div style={{ marginTop: 6 }}>
<span
style={{
fontSize: 11,
padding: '1px 6px',
borderRadius: 999,
background: 'var(--accent-dim)',
color: 'var(--accent)',
}}
>
{ASSET_TYPE_LABELS[item.assetType] || item.assetType}
</span>
</div>
<p
style={{
fontSize: 12,
color: 'var(--text-secondary)',
marginTop: 4,
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
}}
>
{item.prompt}
</p>
</div>
))}
</div>
)}
{/* 详情弹窗 */}
{detailItem && (
<DetailModal item={detailItem} onClose={() => setDetailItem(null)} />
)}
</section>
)
}
+7 -4
View File
@@ -27,13 +27,16 @@ export default function Layout() {
<Link
to="/"
style={{
fontSize: 20,
fontWeight: 700,
color: 'var(--accent)',
display: 'flex',
alignItems: 'center',
textDecoration: 'none',
}}
>
gen2d
<img
src="/logo.png"
alt="gen2d"
style={{ height: 38, width: 64 }}
/>
</Link>
<div style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
+3
View File
@@ -2,6 +2,7 @@ import { useEffect, useState } from 'react'
import { useProjectListStore } from '../stores/projectList'
import { useToastStore } from '../stores/toast'
import ProjectCard from '../components/ProjectCard'
import AssetGallery from '../components/AssetGallery'
import CreateProjectModal from '../components/CreateProjectModal'
import EmptyState from '../components/EmptyState'
import Skeleton from '../components/Skeleton'
@@ -39,6 +40,8 @@ export default function HomePage() {
return (
<div className="container page-enter" style={{ paddingTop: 32, paddingBottom: 32 }}>
<AssetGallery />
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 24 }}>
<h1 style={{ fontSize: 22 }}>我的工程</h1>
<button className="btn-primary" onClick={() => setModalOpen(true)}>