33 Commits

Author SHA1 Message Date
SpecialX
d8dab70406 feat(infra): add OTel auto-instrumentations across all services
Some checks failed
CI / quality-proto (push) Failing after 2s
CI / deploy (push) Has been skipped
CI / quality-ts (push) Failing after 1m11s
CI / quality-go (push) Failing after 5s
NestJS 6 services use getNodeAutoInstrumentations().

Python 2 services use FastAPIInstrumentor. Go 2 services use otelgin.
2026-07-09 13:25:46 +08:00
SpecialX
1f901c5b20 feat(data-ana): implement complete CDC pipeline MySQL to ClickHouse
Debezium + Kafka + aiokafka consumer with table routing.

E2E verified: MySQL INSERT to ClickHouse upsert.
2026-07-09 13:02:59 +08:00
SpecialX
958b17c9d8 feat(infra): p6 hardening - metrics collection and registry mirror
- 4 services add collectDefaultMetrics for process metrics
- docker-compose.yml images prefixed with docker.m.daocloud.io
- Prometheus v0.51.0 (nonexistent) fixed to v2.51.0
- Grafana port remapped 3000 to 3030 to avoid teacher-portal conflict
- ClickHouse edu_analytics database initialized
- known-issues.md documents 7 new P6 scenario-to-rule mappings
2026-07-09 12:29:36 +08:00
SpecialX
566060fade feat(infra): p6 hardening - observability and deploy compose
- 5 NestJS services add /metrics endpoint via app.getHttpAdapter()
- prometheus.yml scales to 8 services with rule_files and alertmanager
- monitoring compose replaces blackbox with Loki+Promtail
- Grafana datasource adds Loki
- docker-compose.deploy.yml scales to 11 services
- deploy.env.example completes Neo4j/ES/ClickHouse/LLM vars
- teacher-bff adds health.controller
- CI removes continue-on-error on lint step
- teacher-portal lint script changed to eslint src
2026-07-09 10:21:06 +08:00
SpecialX
3ca654619f chore(infra): 配置ESLint 9 flat config并恢复lint-staged集成
- 新增 eslint.config.js(ESLint 9 flat config 格式)
- 安装 @eslint/js + typescript-eslint + eslint-config-prettier
- 6 个 TS 服务 lint 脚本:eslint src --ext .ts → eslint src
- lint-staged 恢复 eslint --fix
- .gitignore 忽略 docker-compose.minimal.override.yml
- known-issues.md 新增 P6 硬化条目
2026-07-09 09:14:44 +08:00
SpecialX
a70a74207e feat(ai): 完善AI网关服务并添加LLM降级模式
config.py 加openai_api_key/base_url/dev_mode

新建llm_client.py httpx异步调OpenAI REST API

main.py 业务路由加/ai前缀+降级模式+readyz端点

Gateway添加/notifications和/ai路由

docs: known-issues记录P5三服务经验
2026-07-09 09:09:27 +08:00
SpecialX
dfb6d2bfc1 feat(push-gateway): 修复WebSocket并发写竞争并添加DEV_MODE鉴权
hub.go 重写用send chan+单写协程模式避免并发写竞争

handler.go 加DEV_MODE dev-token支持+broadcast端点

config.go 加DevMode/RedisURL字段
2026-07-09 09:09:13 +08:00
SpecialX
416e1bc0b2 feat(msg): 修复通知服务并添加ES降级与Push Gateway推送
database.ts 导出db常量替代getDb()函数

env.ts JWT_SECRET/ES_URL改optional加DEV_MODE/PUSH_GATEWAY_URL

elasticsearch.ts ES降级: ES_URL未设置时esClient=null

notifications.service.ts 加createBatch+分页查询+Push Gateway推送调用

新建msg-init.sql创建2张表
2026-07-09 09:08:57 +08:00
SpecialX
421edd8a41 feat(data-ana): 完善学情诊断服务并添加ClickHouse降级模式
config.py ClickHouse连接改可选+加DEV_MODE/kafka_brokers

clickhouse_client.py 降级模式: host为空时返回None

main.py 端点先查ClickHouse降级返回骨架数据+新增errorbook

新增clickhouse-init.sql创建宽表和错题表

Gateway添加/analytics路由
2026-07-09 08:58:39 +08:00
SpecialX
5f18821302 feat(api-gateway): 添加content服务代理路由
main.go添加textbooks/chapters/knowledge-points/questions四组路由

config.go新增ContentServiceURL字段

docs: known-issues记录P4 content端到端验证经验
2026-07-09 08:52:30 +08:00
SpecialX
921fe82771 feat(content): 修复服务并添加chapters/knowledge-points/questions模块
- database.ts 导出db常量替代getDb()函数

- env.ts JWT_SECRET/ES_URL/NEO4J_URL改optional加DEV_MODE

- neo4j.ts driver惰性创建+try/catch+connectionTimeout:3000

- health/lifecycle改用Drizzle原生查询

- textbooks.schema修复integer到int+导出NewTextbook类型

- 新建chapters/knowledge-points/questions三模块CRUD

- knowledge-points含Neo4j前置依赖图非阻塞查询

- content-init.sql创建4张表

端到端验证: textbooks/chapters/knowledge-points/questions全CRUD通过
2026-07-09 08:52:15 +08:00
SpecialX
033c083619 feat(teacher-portal): 添加考试作业成绩查询页面
新增 3 个页面位于 (app) 路由组:
  /exams - 按班级查询考试列表
  /homework - 按班级查询作业列表
  /grades - 按考试查询成绩列表

通过 BFF 聚合端点获取 core-edu 数据
遵循纸面设计风格: serif 标题/mono ID/设计令牌
2026-07-09 08:07:02 +08:00
SpecialX
6215f4e21f feat(teacher-bff): 添加考试作业成绩聚合端点
env.ts 新增 CoreEduServiceUrl
teacher.service 新增 listExamsByClass/listHomeworkByClass/listGradesByExam 三个聚合方法
teacher.controller 暴露 3 个 GET 端点:
  /teacher/classes/:classId/exams
  /teacher/classes/:classId/homework
  /teacher/exams/:examId/grades

验证: 3 端点全部 200 返回 core-edu 数据
2026-07-09 08:05:24 +08:00
SpecialX
beb204c00f docs(docs): 记录 P3 core-edu 端到端验证经验与场景映射
core-edu 段新增 6 行: datetime 转换/Kafka 非阻塞/相对 import/身份头/健康检查/Outbox 验证
api-gateway 段新增 3 行: 路由注册位置/多服务路由扩展/DEV_MODE 环境变量
经验日志追加 2026-07-09 P3 条目
2026-07-09 08:04:00 +08:00
SpecialX
4f539b50dd feat(api-gateway): 添加 core-edu 服务代理路由
main.go 新增 exams/homework/grades 三组路由(无尾斜杠+通配符)
config.go 新增 CoreEduServiceURL 字段默认 localhost:3004
删除死代码 internal/routing/routing.go(从未被 main 引用)

验证: GET /exams/class/:id 200, POST /exams 201, 链路全通
2026-07-09 08:02:39 +08:00
SpecialX
4533da6484 feat(core-edu): 修复服务启动并打通考试作业成绩端到端链路
database.ts 导出 db 常量替代 getDb()
env.ts JWT_SECRET 改 optional 并新增 DEV_MODE
kafka.ts connectKafka 加 try/catch 不阻塞启动
main.ts 去全局前缀 connectKafka 改非阻塞
app.module 移除未用模块加 HealthModule
controller 路由去前缀去 UseGuards 从 x-user-id 读身份
service datetime ISO 字符串转 Date 修复 drizzle 错误
修正相对 import 路径
health/lifecycle 改用 Drizzle 原生查询
新增 core-edu-init.sql 初始化 4 张表

端到端验证: exams/homework/grades 全部 201/200
Outbox 事件正确写入 core_edu_outbox 表
2026-07-09 08:02:22 +08:00
SpecialX
2c7afe59ef feat(teacher-portal): 实现登录页侧边栏路由组与真实JWT集成
- lib/auth.ts: localStorage token 存储 + login/logout

- app/login: 登录表单页

- components/AppShell: 视口驱动侧边栏 + 路由保护

- app/(app)/layout: 路由组布局套 AppShell

- app/(app)/dashboard: 聚合统计卡片页

- app/(app)/classes: 迁移 CRUD 改用真实 JWT

- app/page.tsx: 根路径重定向

- known-issues.md: 记录 P2 经验
2026-07-09 00:58:42 +08:00
SpecialX
b2c2f6e567 feat(teacher-bff): 添加视口聚合端点 + 修复身份头读取
- 新增 GET /teacher/viewports 聚合 IAM 视口配置
- 修复 controller 从 x-user-id header 读取身份(替代 AuthenticatedRequest)
- 添加 zod + @types/express 依赖
2026-07-09 00:49:24 +08:00
SpecialX
a2f0ca26ae feat(iam): 实现 RBAC + 视口配置 + DataScope
- 新增 iam_role_viewports 表(4 层视口模型:L1 导航/L2 路由/L3 组件/L4 数据)
- iam_users 添加 data_scope 字段(6 级:self/class/grade/school/district/all)
- JWT payload 包含 dataScope,注册时自动分配 teacher 角色
- 新增 getEffectivePermissions(多角色权限去重)
- 新增 getUserViewports(按权限过滤视口)
- 新增 RbacController:GET /iam/viewports, /iam/permissions/effective, /iam/roles, /iam/permissions
- 添加 7 个权限点 + 12 条角色权限映射 + 7 个视口种子数据
2026-07-09 00:35:34 +08:00
SpecialX
5759b09c9f feat(api-gateway): 添加公开路径白名单
register/login/refresh 无需 JWT 即可通过 Gateway,修复之前无 token 无法注册登录的死锁问题。
2026-07-09 00:30:35 +08:00
SpecialX
d92cdda727 docs(docs): 记录 P1 端到端验证经验与 IAM 场景映射
在 2.3 iam 分区补充 5 条场景映射(ESM DI/Drizzle API/健康检查/Gateway 身份传递/DEV_MODE 登录);工作经验日志追加 P1 端到端验证完整记录。
2026-07-09 00:26:28 +08:00
SpecialX
adea22b133 chore(iam): 添加 IAM 数据库初始化脚本
包含 6 张 IAM 表结构与 teacher/admin 默认角色种子数据,用于 P1 端到端验证。
2026-07-09 00:25:58 +08:00
SpecialX
f658571726 fix(iam): 修复 TS 编译错误、ESM 依赖注入与身份头读取
P1 端到端验证中发现 IAM 服务存在 14 个 TS 编译错误与运行时 DI 失败:

- 移除 typeorm/ioredis/kafkajs 依赖(IAM 用 Drizzle)
- health.controller.ts 改用 db.execute(sql SELECT 1) 校验连接
- lifecycle.service.ts 简化为只关闭 Drizzle 连接池
- Drizzle API 修正:r.roles -> r.iam_roles,.in() -> inArray()
- ESM 模式下 DI 必须显式 @Inject(IamRepository)(参考 classes 黄金模板)
- iam.controller.ts 直接读 req.headers[x-user-id],不依赖未注册的 AuthMiddleware
- health.module.ts 补 .js 后缀
- package.json 补 @types/express

验证:register -> JWT -> Gateway /iam/me 200 -> /classes CRUD 200
2026-07-09 00:25:37 +08:00
SpecialX
68ddff1065 refactor(infra): 重构为 no-push 本地构建部署模式
Some checks failed
CI / quality-go (push) Failing after 3s
CI / quality-proto (push) Failing after 2s
CI / quality-ts (push) Failing after 47s
CI / deploy (push) Has been skipped
- 删除 6 个分散 workflow(ci-ts/ci-go/ci-proto/ci-py/docker/deploy)
- 合并为单个 ci.yml:3 个 quality job 并行 + deploy job 串行
- 全部使用官方镜像(node:22-alpine/golang:1.22-alpine/bufbuild/buf/docker:25-git)
- deploy job 用 DooD 模式挂载 /var/run/docker.sock
- docker-compose.deploy.yml 改用 build: 替代 image:(no-push)
- 新增 docker-compose.tools.yml 一次性预拉所有 CI 镜像
- 支持 workflow_dispatch 指定 commit_sha 回滚
- 更新 project_rules §15 与 cicd-runbook.md 为 no-push 模式
- 新增设计文档 docs/superpowers/specs/2026-07-08-cicd-no-push-local-build-design.md
2026-07-08 17:12:57 +08:00
SpecialX
a1d7fcfd71 docs(docs): 新增 CICD 参考实现规范
Some checks failed
CI TypeScript / quality (push) Failing after 6s
CI TypeScript / arch-scan (push) Has been skipped
CI TypeScript / docker-build (map[context:. dockerfile:apps/teacher-portal/Dockerfile name:teacher-portal]) (push) Has been skipped
CI TypeScript / docker-build (map[context:. dockerfile:services/classes/Dockerfile name:classes]) (push) Has been skipped
Docker Build & Push / build-push (map[context:. dockerfile:apps/teacher-portal/Dockerfile name:teacher-portal]) (push) Failing after 3s
Docker Build & Push / build-push (map[context:. dockerfile:services/classes/Dockerfile name:classes]) (push) Failing after 10s
Docker Build & Push / build-push (map[context:./services/api-gateway dockerfile:services/api-gateway/Dockerfile name:api-gateway]) (push) Failing after 8s
CI Go / quality (push) Failing after 1m4s
CI Go / docker-build (push) Has been skipped
- project_rules §15.7: 参考项目位置 + 关键配置点(container/runner 标签/部署方式/网络)

- cicd-runbook §10: 参考项目对照表(配置项、关键差异、修改流程、冲突处理)

- 修正 cicd-runbook runner 标签:self-hosted,deploy → ubuntu-latest
2026-07-08 16:12:45 +08:00
SpecialX
c31b3ddeba ci(infra): workflow 参照 CICD 参考项目重构
- 所有需要 docker 的 job 改用 container: dockerreg.eazygame.cn/node-with-docker:22

- ci-go.yml: quality 阶段用 golang:1.22-alpine,docker-build 阶段切到 node-with-docker:22

- ci-ts.yml/docker.yml/deploy.yml: 全部加 container 配置

- 移除 setup-node/setup-go action(容器内已有 node/go 或手动安装)

- 不配置 npm 代理(runner 已全局代理)
2026-07-08 16:12:07 +08:00
SpecialX
ae460e61a3 docs(docs): 记录重定向循环与CICD配置经验
- 新增场景映射:尾斜杠重定向循环、开发模式鉴权旁路

- 工作经验日志:重定向循环修复、CI/CD 完整配置
2026-07-08 15:16:00 +08:00
SpecialX
a3f00c882a docs(docs): project_rules 新增多AI协作与CICD规范章节
- §14 多 AI 协作规范:角色权限矩阵、模块单一负责制、分支命名、PR/合并规则、跨模块变更顺序、冲突处理、AI 身份标注、敏感文件保护

- §15 CI/CD 规范:流水线阶段、触发条件、镜像规范、部署策略、Secrets 管理、必需 CI 文件
2026-07-08 15:15:14 +08:00
SpecialX
d19285a977 docs(docs): 新增本地启动/多AI协作/CI-CD 使用手册
- local-dev-runbook.md: 8 章本地启动手册(环境依赖/端口分配/开发模式/生产模式/裸机运行/常见问题)

- multi-ai-collaboration.md: 15 章多AI协作文档(角色定义/模块分工/分支策略/PR流程/审核合并/跨模块变更)

- cicd-runbook.md: 10 章 CI/CD 使用手册(架构总览/一次性配置/日常使用/镜像管理/部署验证/回滚)

- README.md: 文档清单新增三个 runbook 链接
2026-07-08 15:14:30 +08:00
SpecialX
3b88e9cca5 ci(infra): 完整 CI/CD 流水线配置
- ci-ts.yml: lint/typecheck/test/build + arch-scan + docker-build(classes + teacher-portal)

- ci-go.yml: vet/build/test + docker-build(api-gateway)

- ci-proto.yml: buf lint + buf breaking(本地 .git 比较)

- docker.yml: main/tag 触发,构建推送 3 服务镜像到 Gitea Registry

- deploy.yml: workflow_dispatch + workflow_run 触发,Runner 直接 docker compose 部署,含健康检查与回滚

- 所有 workflow runs-on: ubuntu-latest 匹配 actrunner 标签
2026-07-08 15:13:53 +08:00
SpecialX
4a0893ef52 feat(infra): 新增生产 Dockerfile 与部署 compose
- api-gateway/Dockerfile: 多阶段构建,golang:1.22-alpine → alpine:3.20,CGO_ENABLED=0 静态编译,非 root 运行

- teacher-portal/Dockerfile: 多阶段构建,node:20-alpine builder → runner,含 HEALTHCHECK

- docker-compose.prod.yml: 本地生产编排,3 服务,强制 DEV_MODE=false

- docker-compose.deploy.yml: 服务器部署用,镜像来自 Gitea Registry,通过 edu-shared 外部网络连接 MySQL/Redis

- deploy.env.example: 部署环境变量模板
2026-07-08 15:12:34 +08:00
SpecialX
e5902ca2b3 fix(api-gateway): 修复尾斜杠重定向循环与 DEV_MODE 旁路
- main.go: 禁用 RedirectTrailingSlash,为 classes/iam/teacher 双注册无尾斜杠与通配符路由

- auth.go: DEV_MODE=true 时接受 Bearer dev-token 注入开发用户

- config.go: 新增 DevMode 配置项与 getEnvBool 工具

- page.tsx: 开发模式请求携带 Authorization: Bearer dev-token

- .env.example: 添加 DEV_MODE=false 默认值与生产警告
2026-07-08 15:11:47 +08:00
SpecialX
a4ec5b72c5 fix(classes): 修复依赖注入与 ESM 导入路径
- classes.module.ts: 移除 useFactory,改用直接 provider 注册

- classes.service.ts: 添加 @Inject 装饰器显式注入 Repository

- health.module.ts: 修复 import 添加 .js 后缀(ESM 模式)

- package.json: 补充 ioredis/kafkajs/typeform 等运行时依赖
2026-07-08 15:11:12 +08:00
163 changed files with 11484 additions and 2491 deletions

View File

@@ -12,6 +12,12 @@ JWT_SECRET=p1-dev-secret-change-in-production
JWT_ISSUER=next-edu-cloud
JWT_AUDIENCE=next-edu-cloud
# 开发模式旁路(仅本地联调)
# DEV_MODE=true 时接受 "Authorization: Bearer dev-token" 旁路 JWT 校验,
# 注入固定身份 x-user-id=dev-user, x-user-roles=teacher,admin
# 生产环境必须设为 false 或不设此变量
DEV_MODE=false
# 服务端口
API_GATEWAY_PORT=8080
CLASSES_SERVICE_PORT=3001

View File

@@ -1,38 +0,0 @@
name: CI Go
on:
push:
branches: [main]
paths:
- 'services/api-gateway/**'
- 'services/push-gateway/**'
- 'packages/shared-go/**'
- 'go.work'
pull_request:
branches: [main]
paths:
- 'services/api-gateway/**'
- 'services/push-gateway/**'
- 'packages/shared-go/**'
- 'go.work'
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version: '1.22'
- name: golangci-lint
uses: golangci/golangci-lint-action@v6
with:
working-directory: services/api-gateway
- name: Build
working-directory: services/api-gateway
run: |
go mod download
go build ./...
- name: Test
working-directory: services/api-gateway
run: go test ./... -v -coverprofile=coverage.out

View File

@@ -1,25 +0,0 @@
name: CI Proto
on:
push:
branches: [main]
paths:
- 'packages/shared-proto/**'
pull_request:
branches: [main]
paths:
- 'packages/shared-proto/**'
jobs:
lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: bufbuild/buf-setup-action@v1
- name: buf lint
working-directory: packages/shared-proto
run: buf lint
- name: buf breaking
if: github.event_name == 'pull_request'
working-directory: packages/shared-proto
run: buf breaking --against https://github.com/${{ github.repository }}.git#branch=main,subdir=packages/shared-proto

View File

@@ -1,33 +0,0 @@
name: CI Python
on:
push:
branches: [main]
paths:
- 'services/data-ana/**'
- 'services/ai/**'
- 'packages/shared-py/**'
- 'pyproject.toml'
pull_request:
branches: [main]
paths:
- 'services/data-ana/**'
- 'services/ai/**'
- 'packages/shared-py/**'
- 'pyproject.toml'
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: '3.12'
- uses: astral-sh/setup-uv@v3
- name: Install
run: uv sync
- name: Lint (ruff)
run: uv run ruff check .
- name: Test
run: uv run pytest

View File

@@ -1,43 +0,0 @@
name: CI TypeScript
on:
push:
branches: [main]
paths:
- 'services/classes/**'
- 'apps/**'
- 'packages/**'
- 'scripts/**'
- 'package.json'
- 'pnpm-workspace.yaml'
- 'tsconfig.base.json'
pull_request:
branches: [main]
paths:
- 'services/classes/**'
- 'apps/**'
- 'packages/**'
- 'scripts/**'
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v4
with:
version: 9
- uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'pnpm'
- name: Install
run: pnpm install --frozen-lockfile
- name: Lint
run: pnpm -r run lint
- name: Typecheck
run: pnpm -r run typecheck
- name: Test
run: pnpm -r run test
- name: Build
run: pnpm -r run build

196
.github/workflows/ci.yml vendored Normal file
View File

@@ -0,0 +1,196 @@
name: CI
# CI/CD 一体化流水线no-push 本地构建部署)
# 设计文档docs/superpowers/specs/2026-07-08-cicd-no-push-local-build-design.md
#
# 流程:
# PR 触发:仅跑 3 个 quality job并行
# push main 触发quality job 全绿后跑 deploy job本地 build + compose up
# workflow_dispatch支持指定 commit_sha 回滚
#
# 不依赖任何自建镜像,全部使用官方镜像
# 不推送镜像到 registry构建即部署
on:
push:
branches: [main]
pull_request:
branches: [main]
workflow_dispatch:
inputs:
commit_sha:
description: '回滚到指定 commit留空则部署当前 HEAD'
required: false
default: ''
env:
SKIP_ENV_VALIDATION: '1'
NEXT_TELEMETRY_DISABLED: '1'
jobs:
# ===== TypeScript 质量检查 =====
quality-ts:
runs-on: ubuntu-latest
container: node:22-alpine
steps:
- uses: actions/checkout@v3
with:
ref: ${{ github.event.inputs.commit_sha || github.ref }}
- name: Install pnpm
run: npm install -g pnpm@9
- name: Install dependencies
run: pnpm install --frozen-lockfile
- name: Lint
run: pnpm -r run lint
- name: Typecheck
run: pnpm -r run typecheck
- name: Test
run: pnpm -r run test
continue-on-error: true # P6: 部分服务无 test 脚本,待补全
- name: Build
run: pnpm -r run build
# ===== Go 质量检查 =====
quality-go:
runs-on: ubuntu-latest
container: golang:1.22-alpine
defaults:
run:
working-directory: services/api-gateway
steps:
- uses: actions/checkout@v4
with:
ref: ${{ github.event.inputs.commit_sha || github.ref }}
- name: Download deps
run: go mod download
- name: Vet
run: go vet ./...
- name: Build
run: go build ./...
- name: Test
run: go test ./... -v -coverprofile=coverage.out
# ===== Proto 契约检查 =====
quality-proto:
runs-on: ubuntu-latest
container: bufbuild/buf:latest
defaults:
run:
working-directory: packages/shared-proto
steps:
- uses: actions/checkout@v4
with:
ref: ${{ github.event.inputs.commit_sha || github.ref }}
fetch-depth: 0 # buf breaking 需要对比分支
- name: buf lint
run: buf lint
- name: buf breaking
if: github.event_name == 'pull_request'
run: buf breaking --against .git#branch=main,subdir=packages/shared-proto
# ===== 部署(仅 push main 或手动触发)=====
deploy:
if: github.event_name == 'push' || github.event_name == 'workflow_dispatch'
needs: [quality-ts, quality-go, quality-proto]
runs-on: ubuntu-latest
container: docker:25-git
options: --volume /var/run/docker.sock:/var/run/docker.sock
environment:
name: production
env:
DEPLOY_DIR: /opt/edu
steps:
- uses: actions/checkout@v4
with:
ref: ${{ github.event.inputs.commit_sha || github.ref }}
- name: Setup deploy dir
run: |
# 同步整个仓库到部署目录的 repo/ 子目录
# compose 文件中 build.context 指向 ./repo/services/... 或 ./repo
mkdir -p ${{ env.DEPLOY_DIR }}/repo
cp -a $GITHUB_WORKSPACE/. ${{ env.DEPLOY_DIR }}/repo/
cp infra/docker-compose.deploy.yml ${{ env.DEPLOY_DIR }}/docker-compose.yml
# 确保 .env 存在(首次部署需人工创建)
if [ ! -f ${{ env.DEPLOY_DIR }}/.env ]; then
echo "::error::部署目录缺少 .env 文件,请参考 infra/deploy.env.example 创建"
exit 1
fi
- name: Deploy services (local build, no push)
run: |
cd ${{ env.DEPLOY_DIR }}
echo "=== 构建并启动服务 ==="
# --build 使用本地 Dockerfile 构建,不拉取 registry
# build.context 在 compose 中指向 ./repo/...(相对于 /opt/edu/
docker compose up -d --build --remove-orphans
- name: Wait for health
run: |
echo "等待服务健康..."
sleep 10
for i in 1 2 3 4 5 6 7 8 9 10; do
FAIL=0
echo "[尝试 $i] 检查 api-gateway..."
if ! wget -q --spider http://localhost:8080/healthz 2>/dev/null; then
echo " api-gateway 未就绪"
FAIL=1
fi
echo "[尝试 $i] 检查 classes..."
if ! wget -q --spider http://localhost:3001/healthz 2>/dev/null; then
echo " classes 未就绪"
FAIL=1
fi
echo "[尝试 $i] 检查 teacher-portal..."
if ! wget -q --spider http://localhost:3000/ 2>/dev/null; then
echo " teacher-portal 未就绪"
FAIL=1
fi
if [ $FAIL -eq 0 ]; then
echo "✅ 所有服务健康"
exit 0
fi
sleep 6
done
echo "::error::服务健康检查失败"
echo "=== 容器状态 ==="
cd ${{ env.DEPLOY_DIR }} && docker compose ps
echo "=== api-gateway 日志 ==="
docker compose logs --tail=50 api-gateway
echo "=== classes 日志 ==="
docker compose logs --tail=50 classes
echo "=== teacher-portal 日志 ==="
docker compose logs --tail=50 teacher-portal
exit 1
- name: Summary
if: always()
run: |
echo "### 部署结果" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
echo "- 触发事件:\`${{ github.event_name }}\`" >> $GITHUB_STEP_SUMMARY
echo "- 部署 commit\`${{ github.event.inputs.commit_sha || github.sha }}\`" >> $GITHUB_STEP_SUMMARY
echo "- 部署目录:\`${{ env.DEPLOY_DIR }}\`" >> $GITHUB_STEP_SUMMARY
echo "- 部署方式本地构建no-push" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
cd ${{ env.DEPLOY_DIR }} && docker compose ps >> $GITHUB_STEP_SUMMARY 2>&1 || true

1
.gitignore vendored
View File

@@ -59,6 +59,7 @@ coverage/
# Docker
docker-compose.override.yml
docker-compose.minimal.override.yml
# Temp
tmp/

View File

@@ -369,4 +369,164 @@ services/[service]/src/
---
## 14. 多 AI 协作规范
> 详细流程见 [多 AI 协作指南](../../docs/standards/multi-ai-collaboration.md),本节为强制约束摘要。
### 14.1 角色与权限
| 角色 | 职责 | push 特性分支 | 创建 PR | 合并 PR | push main | force push main |
| -------------------------- | ---------------------------------------- | ------------- | ------- | ----------- | --------- | --------------- |
| **协调 AICoordinator** | PR 审核、合并、冲突仲裁、发布 | ✅ | ✅ | ✅ | ❌ | ⚠️(仅事故) |
| **开发 AIDev** | 按模块分工写代码、提 PR | ✅ | ✅ | ❌ | ❌ | ❌ |
| **SRE AI** | `infra/` 维护、部署 | ✅infra | ✅ | ✅infra | ❌ | ⚠️(仅事故) |
| **人类决策者** | 架构决策、Breaking Change 审批、发布确认 | — | — | — | — | — |
### 14.2 模块单一负责制
- 每个模块(限界上下文)只有一个 AI 负责,禁止并行修改同一模块
- `shared-proto``shared-tokens``docs/` 由协调 AI 维护,开发 AI 只读引用
- `infra/` 由 SRE AI 专门负责,业务 AI 不直接修改
### 14.3 分支命名规范(强制)
```
<type>/<scope>-<task-id>-<ai-id>
```
- `type`feat / fix / refactor / docs / chore / test
- `scope`:见 §7 提交规范 scope-enum26 项)
- `task-id`任务简短描述kebab-case
- `ai-id`AI 唯一标识符(如 `ai01``ai02``coord`
**示例**`feat/classes-add-pagination-ai01`
### 14.4 PR 与合并规则(强制)
1. **禁止直接 push 到 `main`**:所有变更通过 PR
2. **PR 必须通过 CI**lint / typecheck / build / test 全绿
3. **PR 必须通过 CODEOWNERS review**:至少 1 人 approve
4. **合并策略**Squash Merge默认Rebase Merge保留多 commit 历史),**禁止 Merge Commit**
5. **特性分支寿命 ≤ 3 天**:超期需 rebase 最新 main
6. **跨模块变更拆分**:按依赖顺序拆多个 PRproto → service → gateway → frontend协调 AI 按序合并
### 14.5 跨模块变更顺序(强制)
修改涉及多模块时,必须按以下顺序拆分 PR 并顺序合并:
1. `shared-proto`proto 契约)
2. 业务服务classes / iam / core-edu 等)
3. `api-gateway`(路由)
4. BFFteacher-bff 等)
5. 微前端teacher-portal 等)
> 每合并一个 PR后续 PR 的开发 AI 必须 rebase 最新 main 并重新校验。
### 14.6 冲突处理规则
- **文件冲突**:后合并的 PR rebase 最新 main`git push --force-with-lease`(仅自己的分支)
- **架构冲突**:由协调 AI 仲裁保留方案
- **禁止 `git push --force` 到 main 或他人分支**
### 14.7 AI 身份标注(强制)
每个 PR 描述末尾必须追加:
```markdown
---
**AI Agent**: <ai-id> (<负责模块>)
**Branch**: <分支名>
**Coordinator**: <协调 AI ai-id>
```
每个 AI 完成任务后,在 `docs/troubleshooting/known-issues.md` "工作经验日志"区追加记录(见 §9.3)。
### 14.8 敏感文件保护
以下文件修改需人类决策者额外审批:
- `.env``.env.example``infra/security/secrets.example.env`
- `infra/k8s/`(生产部署)
- `.github/workflows/`CI 配置)
- `.trae/rules/project_rules.md`(项目规则)
---
## 15. CI/CD 规范
> 详细配置见 `.github/workflows/ci.yml`,使用手册见 [cicd-runbook](../../docs/standards/cicd-runbook.md),设计文档见 [no-push-local-build-design](../../docs/superpowers/specs/2026-07-08-cicd-no-push-local-build-design.md)。
### 15.1 核心模式no-push 本地构建
- **不推送镜像到 registry**:构建即部署,镜像只存在于构建机本地
- **不依赖自建镜像**全部使用官方镜像node:22-alpine / golang:1.22-alpine / bufbuild/buf / docker:25-git
- **DooD 模式**deploy job 容器挂载 `/var/run/docker.sock`,容器内 docker 命令作用于宿主机
- **单文件管理**:一个 `.github/workflows/ci.yml` 管全部 CI/CD
### 15.2 流水线阶段
| 阶段 | 并行 | 内容 | 失败策略 |
| ----------------- | ---- | ------------------------------------ | -------- |
| **quality-ts** | ✅ | pnpm lint + typecheck + test + build | 失败阻断 |
| **quality-go** | ✅ | go vet + build + test | 失败阻断 |
| **quality-proto** | ✅ | buf lint + buf breaking仅 PR | 失败阻断 |
| **deploy** | 串行 | docker compose up --build + 健康检查 | 失败阻断 |
> deploy job 仅在 `push main` 或 `workflow_dispatch` 时触发PR 时不部署
### 15.3 触发条件
| 事件 | 触发阶段 | 触发条件 |
| ----------------- | ----------------------------------------------- | -------------------------------- |
| PR 创建/更新 | quality-ts + quality-go + quality-proto并行 | 所有路径 |
| push 到 main | 上述全部 + deploy | 合并后自动 |
| workflow_dispatch | 上述全部 + deploy | 手动触发,支持 `commit_sha` 回滚 |
> **不再支持 tag 发布**no-push 模式下不用 `git tag v*` 触发。版本管理通过 commit SHA 追溯。
### 15.4 镜像规范
- **不推送到 registry**,本地构建本地使用
- **不保留历史镜像**layer cache 在宿主机本地,未变更的层秒过
- **回滚**`git revert` 重跑 CI`workflow_dispatch` 指定 `commit_sha`
### 15.5 部署策略
- **目标环境**:服务器 Docker ComposeP1-P2 阶段K8sP3+ 阶段)
- **部署方式**`docker compose up -d --build --remove-orphans`(在 `/opt/edu/` 目录)
- **部署目录**`/opt/edu/`compose 文件)+ `/opt/edu/repo/`CI 同步的源码,供 build.context 使用)
- **健康检查**:部署后轮询 `/healthz` 端点10 次 × 6 秒),失败输出容器日志
- **回滚**`git revert + push``workflow_dispatch` 指定 `commit_sha`
### 15.6 必需的 CI 文件
| 文件 | 用途 |
| --------------------------------- | ------------------------------------- |
| `.github/workflows/ci.yml` | 唯一 CI/CD 流水线quality + deploy |
| `infra/docker-compose.deploy.yml` | 部署用 composebuild: 替代 image: |
| `infra/docker-compose.tools.yml` | 一次性预拉所有 CI 镜像 |
| `infra/deploy.env.example` | 部署环境变量模板 |
### 15.7 actrunner 配置
```toml
# /etc/gitea/act_runner/config.yaml
container:
valid_volumes:
- /var/run/docker.sock
```
### 15.8 镜像预拉(一次性)
部署前在服务器执行:
```bash
docker compose -f infra/docker-compose.tools.yml pull
```
拉取清单node:22-alpine、golang:1.22-alpine、bufbuild/buf:latest、docker:25-git、node:20-alpine、alpine:3.20、mysql:8.0开发测试、redis:7-alpine开发测试
---
**本规则文件是项目的强制约束,所有 contributor含 AI必须遵守。规则变更需同步更新 004 与 arch.db。**

View File

@@ -38,6 +38,9 @@ pnpm dev
- [编码规范](docs/standards/coding-standards.md)
- [UI 设计系统](docs/standards/ui-design-system.md)
- [Git 工作流](docs/standards/git-workflow.md)
- [本地启动手册](docs/standards/local-dev-runbook.md)
- [多 AI 协作指南](docs/standards/multi-ai-collaboration.md)
- [CI/CD 使用手册](docs/standards/cicd-runbook.md)
- [已知问题](docs/troubleshooting/known-issues.md)
- [项目规则](.trae/rules/project_rules.md)
- [迁移指南](MIGRATION_GUIDE.md)

View File

@@ -0,0 +1,49 @@
# 多阶段构建Next.js 生产镜像
# 用法docker build -t edu/teacher-portal:latest -f apps/teacher-portal/Dockerfile .
# ============ Builder ============
FROM node:20-alpine AS builder
WORKDIR /app
# 启用 pnpm
RUN corepack enable && corepack prepare pnpm@9.12.0 --activate
# 先拷依赖清单,利用缓存
COPY package.json pnpm-lock.yaml* pnpm-workspace.yaml* ./
COPY apps/teacher-portal/package.json ./apps/teacher-portal/
# 安装依赖(含 devDependencies构建需要
RUN pnpm install --filter @edu/teacher-portal... --frozen-lockfile || pnpm install --filter @edu/teacher-portal...
# 拷源码
COPY apps/teacher-portal ./apps/teacher-portal
# 构建(禁用 telemetry生产模式
ENV NEXT_TELEMETRY_DISABLED=1
RUN pnpm --filter @edu/teacher-portal run build
# ============ Runtime ============
FROM node:20-alpine AS runner
WORKDIR /app
ENV NODE_ENV=production
ENV NEXT_TELEMETRY_DISABLED=1
ENV PORT=3000
# 非 root 用户运行
RUN addgroup -g 1001 -S nodejs && adduser -S nextjs -u 1001
# 拷构建产物与必要清单
COPY --from=builder /app/apps/teacher-portal/package.json ./package.json
COPY --from=builder /app/apps/teacher-portal/.next ./.next
COPY --from=builder /app/apps/teacher-portal/public ./public
COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/apps/teacher-portal/next.config.js ./next.config.js
USER nextjs
EXPOSE 3000
# 健康检查
HEALTHCHECK --interval=30s --timeout=5s --start-period=20s --retries=3 \
CMD wget --quiet --spider http://localhost:3000/ || exit 1
CMD ["node_modules/.bin/next", "start", "-p", "3000"]

View File

@@ -6,7 +6,7 @@
"dev": "next dev -p 3000",
"build": "next build",
"start": "next start -p 3000",
"lint": "next lint",
"lint": "eslint src",
"typecheck": "tsc --noEmit"
},
"dependencies": {
@@ -19,6 +19,7 @@
"@types/react": "^18.3.0",
"@types/react-dom": "^18.3.0",
"autoprefixer": "^10.4.0",
"eslint": "^9.0.0",
"postcss": "^8.4.0",
"tailwindcss": "^3.4.0",
"typescript": "^5.6.0"

View File

@@ -0,0 +1,293 @@
"use client";
import { useState, useEffect, useCallback } from "react";
import { getToken } from "@/lib/auth";
interface ClassItem {
id: string;
name: string;
gradeId: string;
description?: string;
createdAt: number;
updatedAt: number;
}
interface ApiResponse<T> {
success: boolean;
data?: T;
error?: { code: string; message: string };
}
export default function ClassesPage() {
const [classes, setClasses] = useState<ClassItem[]>([]);
const [loading, setLoading] = useState(false);
const [name, setName] = useState("");
const [gradeId, setGradeId] = useState(
"550e8400-e29b-41d4-a716-446655440000",
);
const [description, setDescription] = useState("");
const [error, setError] = useState<string | null>(null);
const authHeaders = (): Record<string, string> => {
const token = getToken();
return token ? { Authorization: `Bearer ${token}` } : {};
};
const fetchClasses = useCallback(async () => {
setLoading(true);
setError(null);
try {
const res = await fetch("/api/v1/classes", {
headers: authHeaders(),
});
const json: ApiResponse<ClassItem[]> = await res.json();
if (json.success && json.data) {
setClasses(json.data);
} else {
setError(json.error?.message || "Failed to load");
}
} catch (e) {
setError(e instanceof Error ? e.message : "Network error");
} finally {
setLoading(false);
}
}, []);
useEffect(() => {
fetchClasses();
}, [fetchClasses]);
const handleCreate = async (e: React.FormEvent) => {
e.preventDefault();
if (!name.trim()) return;
try {
const res = await fetch("/api/v1/classes", {
method: "POST",
headers: {
"Content-Type": "application/json",
...authHeaders(),
},
body: JSON.stringify({ name, gradeId, description }),
});
const json = await res.json();
if (!json.success) {
setError(json.error?.message || "Create failed");
return;
}
setName("");
setDescription("");
await fetchClasses();
} catch (e) {
setError(e instanceof Error ? e.message : "Network error");
}
};
const handleDelete = async (id: string) => {
try {
const res = await fetch(`/api/v1/classes/${id}`, {
method: "DELETE",
headers: authHeaders(),
});
const json = await res.json();
if (!json.success) {
setError(json.error?.message || "Delete failed");
return;
}
await fetchClasses();
} catch (e) {
setError(e instanceof Error ? e.message : "Network error");
}
};
return (
<div className="px-10 py-10">
<header className="mb-8">
<h1
className="text-3xl"
style={{
fontFamily: "var(--font-serif)",
color: "var(--color-ink)",
}}
>
</h1>
<p className="mt-1 text-sm" style={{ color: "var(--color-ink-muted)" }}>
classes CRUD · JWT
</p>
</header>
<div className="rule-thin mb-8" />
<div className="grid grid-cols-12 gap-8">
<aside className="col-span-4">
<h2
className="text-xl mb-4"
style={{ fontFamily: "var(--font-serif)" }}
>
</h2>
<div className="rule-thin mb-4" />
<form onSubmit={handleCreate} className="space-y-4">
<div>
<label
className="block text-xs uppercase tracking-wide mb-1"
style={{ color: "var(--color-ink-muted)" }}
>
</label>
<input
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
className="w-full px-3 py-2 bg-transparent border-b focus:outline-none focus:border-b-2"
style={{
borderColor: "var(--color-rule)",
borderRadius: "6px 6px 0 0",
}}
placeholder="如:高三(1)班"
required
/>
</div>
<div>
<label
className="block text-xs uppercase tracking-wide mb-1"
style={{ color: "var(--color-ink-muted)" }}
>
ID
</label>
<input
type="text"
value={gradeId}
onChange={(e) => setGradeId(e.target.value)}
className="w-full px-3 py-2 bg-transparent border-b text-sm font-mono"
style={{
borderColor: "var(--color-rule)",
borderRadius: "6px 6px 0 0",
}}
/>
</div>
<div>
<label
className="block text-xs uppercase tracking-wide mb-1"
style={{ color: "var(--color-ink-muted)" }}
>
</label>
<textarea
value={description}
onChange={(e) => setDescription(e.target.value)}
className="w-full px-3 py-2 bg-transparent border-b resize-none"
style={{
borderColor: "var(--color-rule)",
borderRadius: "6px 6px 0 0",
}}
rows={3}
/>
</div>
<button
type="submit"
className="px-4 py-2 text-white text-sm tracking-wide transition-opacity hover:opacity-90"
style={{ background: "var(--color-accent)", borderRadius: "6px" }}
>
</button>
</form>
</aside>
<section className="col-span-8">
<div className="flex items-baseline justify-between mb-4">
<h2 className="text-xl" style={{ fontFamily: "var(--font-serif)" }}>
<span
className="ml-2 text-sm font-sans"
style={{ color: "var(--color-ink-muted)" }}
>
{classes.length}
</span>
</h2>
<button
onClick={fetchClasses}
className="text-xs uppercase tracking-wide hover:opacity-70"
style={{ color: "var(--color-accent)" }}
>
</button>
</div>
<div className="rule-thin mb-6" />
{error && (
<div
className="mark-left mb-4 py-2"
style={{ borderColor: "var(--color-accent)" }}
>
<p
className="text-sm px-3"
style={{ color: "var(--color-accent)" }}
>
{error}
</p>
</div>
)}
{loading ? (
<p className="text-sm" style={{ color: "var(--color-ink-muted)" }}>
...
</p>
) : classes.length === 0 ? (
<p
className="text-sm italic"
style={{ color: "var(--color-ink-muted)" }}
>
</p>
) : (
<ul className="space-y-0">
{classes.map((cls) => (
<li
key={cls.id}
className="py-4 grid grid-cols-12 gap-4 items-baseline"
style={{ borderBottom: "1px solid var(--color-rule)" }}
>
<div className="col-span-7">
<h3
className="text-lg"
style={{
fontFamily: "var(--font-serif)",
color: "var(--color-ink)",
}}
>
{cls.name}
</h3>
{cls.description && (
<p
className="mt-1 text-sm"
style={{ color: "var(--color-ink-muted)" }}
>
{cls.description}
</p>
)}
</div>
<div
className="col-span-3 text-xs font-mono"
style={{ color: "var(--color-ink-muted)" }}
>
{cls.id.slice(0, 8)}...
</div>
<div className="col-span-2 text-right">
<button
onClick={() => handleDelete(cls.id)}
className="text-xs uppercase tracking-wide hover:opacity-70"
style={{ color: "var(--color-ink-muted)" }}
>
</button>
</div>
</li>
))}
</ul>
)}
</section>
</div>
</div>
);
}

View File

@@ -0,0 +1,139 @@
"use client";
import { useEffect, useState } from "react";
import { getToken, getUser, type UserInfo } from "@/lib/auth";
interface DashboardData {
user: { success: boolean; data?: { user: UserInfo } };
classes: { success: boolean; data?: unknown[] };
}
export default function DashboardPage() {
const [data, setData] = useState<DashboardData | null>(null);
const [error, setError] = useState<string | null>(null);
const [loading, setLoading] = useState(true);
const user = getUser();
useEffect(() => {
const token = getToken();
if (!token) return;
(async () => {
try {
const res = await fetch("/api/v1/teacher/dashboard", {
headers: { Authorization: `Bearer ${token}` },
});
const json = await res.json();
if (json.success) {
setData(json.data);
} else {
setError(json.error?.message || "加载失败");
}
} catch (e) {
setError(e instanceof Error ? e.message : "网络错误");
} finally {
setLoading(false);
}
})();
}, []);
const classesCount = Array.isArray(data?.classes?.data)
? data!.classes.data.length
: 0;
return (
<div className="px-10 py-10">
<header className="mb-8">
<h1
className="text-3xl"
style={{ fontFamily: "var(--font-serif)", color: "var(--color-ink)" }}
>
{user?.name || "老师"}
</h1>
<p className="mt-1 text-sm" style={{ color: "var(--color-ink-muted)" }}>
{user?.email} · {user?.roles.join(", ") || "无"} ·
{user?.dataScope || "-"}
</p>
</header>
<div className="rule-thin mb-8" />
{loading ? (
<p className="text-sm" style={{ color: "var(--color-ink-muted)" }}>
...
</p>
) : error ? (
<div
className="mark-left py-2 mb-4"
style={{ borderColor: "var(--color-accent)" }}
>
<p className="text-sm px-3" style={{ color: "var(--color-accent)" }}>
{error}
</p>
</div>
) : (
<section className="grid grid-cols-3 gap-6">
<div
className="p-6 border"
style={{ borderColor: "var(--color-rule)" }}
>
<p
className="text-xs uppercase tracking-wide"
style={{ color: "var(--color-ink-muted)" }}
>
</p>
<p
className="mt-3 text-4xl"
style={{
fontFamily: "var(--font-serif)",
color: "var(--color-ink)",
}}
>
{classesCount}
</p>
</div>
<div
className="p-6 border"
style={{ borderColor: "var(--color-rule)" }}
>
<p
className="text-xs uppercase tracking-wide"
style={{ color: "var(--color-ink-muted)" }}
>
</p>
<p
className="mt-3 text-4xl"
style={{
fontFamily: "var(--font-serif)",
color: "var(--color-ink)",
}}
>
{user?.permissions.length ?? 0}
</p>
</div>
<div
className="p-6 border"
style={{ borderColor: "var(--color-rule)" }}
>
<p
className="text-xs uppercase tracking-wide"
style={{ color: "var(--color-ink-muted)" }}
>
</p>
<p
className="mt-3 text-2xl"
style={{
fontFamily: "var(--font-serif)",
color: "var(--color-ink)",
}}
>
{user?.dataScope || "-"}
</p>
</div>
</section>
)}
</div>
);
}

View File

@@ -0,0 +1,185 @@
"use client";
import { useState, useEffect, useCallback } from "react";
import { getToken } from "@/lib/auth";
interface ExamItem {
id: string;
classId: string;
title: string;
description?: string;
examDate: string;
duration: string;
totalScore: string;
status: string;
createdBy: string;
createdAt: string;
updatedAt: string;
}
interface ApiResponse<T> {
success: boolean;
data?: T;
error?: { code: string; message: string };
}
export default function ExamsPage() {
const [exams, setExams] = useState<ExamItem[]>([]);
const [loading, setLoading] = useState(false);
const [classId, setClassId] = useState(
"00000000-0000-0000-0000-000000000001",
);
const [error, setError] = useState<string | null>(null);
const authHeaders = (): Record<string, string> => {
const token = getToken();
return token ? { Authorization: `Bearer ${token}` } : {};
};
const fetchExams = useCallback(async () => {
if (!classId.trim()) return;
setLoading(true);
setError(null);
try {
const res = await fetch(
`/api/v1/teacher/classes/${encodeURIComponent(classId)}/exams`,
{ headers: authHeaders() },
);
const json: ApiResponse<ExamItem[]> = await res.json();
if (json.success && json.data) {
setExams(json.data);
} else {
setError(json.error?.message || "Failed to load");
}
} catch (e) {
setError(e instanceof Error ? e.message : "Network error");
} finally {
setLoading(false);
}
}, [classId]);
useEffect(() => {
fetchExams();
}, [fetchExams]);
return (
<div className="px-10 py-10">
<header className="mb-8">
<h1
className="text-3xl"
style={{
fontFamily: "var(--font-serif)",
color: "var(--color-ink)",
}}
>
</h1>
<p className="mt-1 text-sm" style={{ color: "var(--color-ink-muted)" }}>
core-edu · BFF
</p>
</header>
<div className="rule-thin mb-8" />
<div className="mb-6 flex items-baseline gap-3">
<label
className="text-xs uppercase tracking-wide"
style={{ color: "var(--color-ink-muted)" }}
>
ID
</label>
<input
type="text"
value={classId}
onChange={(e) => setClassId(e.target.value)}
className="flex-1 max-w-md px-3 py-2 bg-transparent border-b text-sm font-mono"
style={{ borderColor: "var(--color-rule)" }}
placeholder="输入班级 UUID"
/>
<button
onClick={fetchExams}
className="text-xs uppercase tracking-wide hover:opacity-70"
style={{ color: "var(--color-accent)" }}
>
</button>
</div>
{error && (
<div
className="mark-left mb-4 py-2"
style={{ borderColor: "var(--color-accent)" }}
>
<p className="text-sm px-3" style={{ color: "var(--color-accent)" }}>
{error}
</p>
</div>
)}
{loading ? (
<p className="text-sm" style={{ color: "var(--color-ink-muted)" }}>
...
</p>
) : exams.length === 0 ? (
<p
className="text-sm italic"
style={{ color: "var(--color-ink-muted)" }}
>
</p>
) : (
<ul className="space-y-0">
{exams.map((exam) => (
<li
key={exam.id}
className="py-4 grid grid-cols-12 gap-4 items-baseline"
style={{ borderBottom: "1px solid var(--color-rule)" }}
>
<div className="col-span-7">
<h3
className="text-lg"
style={{
fontFamily: "var(--font-serif)",
color: "var(--color-ink)",
}}
>
{exam.title}
</h3>
{exam.description && (
<p
className="mt-1 text-sm"
style={{ color: "var(--color-ink-muted)" }}
>
{exam.description}
</p>
)}
<p
className="mt-1 text-xs"
style={{ color: "var(--color-ink-muted)" }}
>
: {new Date(exam.examDate).toLocaleString("zh-CN")}
{" · "}
{exam.duration}
{" · "}
{exam.totalScore}
</p>
</div>
<div
className="col-span-3 text-xs"
style={{ color: "var(--color-ink-muted)" }}
>
: {exam.status}
</div>
<div
className="col-span-2 text-right text-xs font-mono"
style={{ color: "var(--color-ink-muted)" }}
>
{exam.id.slice(0, 8)}...
</div>
</li>
))}
</ul>
)}
</div>
);
}

View File

@@ -0,0 +1,180 @@
"use client";
import { useState, useEffect, useCallback } from "react";
import { getToken } from "@/lib/auth";
interface GradeItem {
id: string;
studentId: string;
examId: string | null;
homeworkId: string | null;
score: string;
feedback?: string;
gradedBy: string;
createdAt: string;
updatedAt: string;
}
interface ApiResponse<T> {
success: boolean;
data?: T;
error?: { code: string; message: string };
}
export default function GradesPage() {
const [items, setItems] = useState<GradeItem[]>([]);
const [loading, setLoading] = useState(false);
const [examId, setExamId] = useState("");
const [error, setError] = useState<string | null>(null);
const authHeaders = (): Record<string, string> => {
const token = getToken();
return token ? { Authorization: `Bearer ${token}` } : {};
};
const fetchGrades = useCallback(async () => {
if (!examId.trim()) return;
setLoading(true);
setError(null);
try {
const res = await fetch(
`/api/v1/teacher/exams/${encodeURIComponent(examId)}/grades`,
{ headers: authHeaders() },
);
const json: ApiResponse<GradeItem[]> = await res.json();
if (json.success && json.data) {
setItems(json.data);
} else {
setError(json.error?.message || "Failed to load");
}
} catch (e) {
setError(e instanceof Error ? e.message : "Network error");
} finally {
setLoading(false);
}
}, [examId]);
useEffect(() => {
fetchGrades();
}, [fetchGrades]);
return (
<div className="px-10 py-10">
<header className="mb-8">
<h1
className="text-3xl"
style={{
fontFamily: "var(--font-serif)",
color: "var(--color-ink)",
}}
>
</h1>
<p className="mt-1 text-sm" style={{ color: "var(--color-ink-muted)" }}>
core-edu · BFF
</p>
</header>
<div className="rule-thin mb-8" />
<div className="mb-6 flex items-baseline gap-3">
<label
className="text-xs uppercase tracking-wide"
style={{ color: "var(--color-ink-muted)" }}
>
ID
</label>
<input
type="text"
value={examId}
onChange={(e) => setExamId(e.target.value)}
className="flex-1 max-w-md px-3 py-2 bg-transparent border-b text-sm font-mono"
style={{ borderColor: "var(--color-rule)" }}
placeholder="输入考试 UUID"
/>
<button
onClick={fetchGrades}
className="text-xs uppercase tracking-wide hover:opacity-70"
style={{ color: "var(--color-accent)" }}
>
</button>
</div>
{error && (
<div
className="mark-left mb-4 py-2"
style={{ borderColor: "var(--color-accent)" }}
>
<p className="text-sm px-3" style={{ color: "var(--color-accent)" }}>
{error}
</p>
</div>
)}
{loading ? (
<p className="text-sm" style={{ color: "var(--color-ink-muted)" }}>
...
</p>
) : items.length === 0 ? (
<p
className="text-sm italic"
style={{ color: "var(--color-ink-muted)" }}
>
{examId.trim() ? "该考试下暂无成绩" : "请输入考试 ID 查询成绩"}
</p>
) : (
<ul className="space-y-0">
{items.map((g) => (
<li
key={g.id}
className="py-4 grid grid-cols-12 gap-4 items-baseline"
style={{ borderBottom: "1px solid var(--color-rule)" }}
>
<div className="col-span-6">
<h3
className="text-lg"
style={{
fontFamily: "var(--font-serif)",
color: "var(--color-ink)",
}}
>
: {g.studentId}
</h3>
{g.feedback && (
<p
className="mt-1 text-sm"
style={{ color: "var(--color-ink-muted)" }}
>
: {g.feedback}
</p>
)}
</div>
<div
className="col-span-2 text-2xl"
style={{
fontFamily: "var(--font-serif)",
color: "var(--color-accent)",
}}
>
{g.score}
</div>
<div
className="col-span-2 text-xs"
style={{ color: "var(--color-ink-muted)" }}
>
: {g.gradedBy}
</div>
<div
className="col-span-2 text-right text-xs font-mono"
style={{ color: "var(--color-ink-muted)" }}
>
{g.id.slice(0, 8)}...
</div>
</li>
))}
</ul>
)}
</div>
);
}

View File

@@ -0,0 +1,179 @@
"use client";
import { useState, useEffect, useCallback } from "react";
import { getToken } from "@/lib/auth";
interface HomeworkItem {
id: string;
classId: string;
title: string;
description?: string;
dueDate: string;
status: string;
createdBy: string;
createdAt: string;
updatedAt: string;
}
interface ApiResponse<T> {
success: boolean;
data?: T;
error?: { code: string; message: string };
}
export default function HomeworkPage() {
const [items, setItems] = useState<HomeworkItem[]>([]);
const [loading, setLoading] = useState(false);
const [classId, setClassId] = useState(
"00000000-0000-0000-0000-000000000001",
);
const [error, setError] = useState<string | null>(null);
const authHeaders = (): Record<string, string> => {
const token = getToken();
return token ? { Authorization: `Bearer ${token}` } : {};
};
const fetchHomework = useCallback(async () => {
if (!classId.trim()) return;
setLoading(true);
setError(null);
try {
const res = await fetch(
`/api/v1/teacher/classes/${encodeURIComponent(classId)}/homework`,
{ headers: authHeaders() },
);
const json: ApiResponse<HomeworkItem[]> = await res.json();
if (json.success && json.data) {
setItems(json.data);
} else {
setError(json.error?.message || "Failed to load");
}
} catch (e) {
setError(e instanceof Error ? e.message : "Network error");
} finally {
setLoading(false);
}
}, [classId]);
useEffect(() => {
fetchHomework();
}, [fetchHomework]);
return (
<div className="px-10 py-10">
<header className="mb-8">
<h1
className="text-3xl"
style={{
fontFamily: "var(--font-serif)",
color: "var(--color-ink)",
}}
>
</h1>
<p className="mt-1 text-sm" style={{ color: "var(--color-ink-muted)" }}>
core-edu · BFF
</p>
</header>
<div className="rule-thin mb-8" />
<div className="mb-6 flex items-baseline gap-3">
<label
className="text-xs uppercase tracking-wide"
style={{ color: "var(--color-ink-muted)" }}
>
ID
</label>
<input
type="text"
value={classId}
onChange={(e) => setClassId(e.target.value)}
className="flex-1 max-w-md px-3 py-2 bg-transparent border-b text-sm font-mono"
style={{ borderColor: "var(--color-rule)" }}
placeholder="输入班级 UUID"
/>
<button
onClick={fetchHomework}
className="text-xs uppercase tracking-wide hover:opacity-70"
style={{ color: "var(--color-accent)" }}
>
</button>
</div>
{error && (
<div
className="mark-left mb-4 py-2"
style={{ borderColor: "var(--color-accent)" }}
>
<p className="text-sm px-3" style={{ color: "var(--color-accent)" }}>
{error}
</p>
</div>
)}
{loading ? (
<p className="text-sm" style={{ color: "var(--color-ink-muted)" }}>
...
</p>
) : items.length === 0 ? (
<p
className="text-sm italic"
style={{ color: "var(--color-ink-muted)" }}
>
</p>
) : (
<ul className="space-y-0">
{items.map((hw) => (
<li
key={hw.id}
className="py-4 grid grid-cols-12 gap-4 items-baseline"
style={{ borderBottom: "1px solid var(--color-rule)" }}
>
<div className="col-span-7">
<h3
className="text-lg"
style={{
fontFamily: "var(--font-serif)",
color: "var(--color-ink)",
}}
>
{hw.title}
</h3>
{hw.description && (
<p
className="mt-1 text-sm"
style={{ color: "var(--color-ink-muted)" }}
>
{hw.description}
</p>
)}
<p
className="mt-1 text-xs"
style={{ color: "var(--color-ink-muted)" }}
>
: {new Date(hw.dueDate).toLocaleString("zh-CN")}
</p>
</div>
<div
className="col-span-3 text-xs"
style={{ color: "var(--color-ink-muted)" }}
>
: {hw.status}
</div>
<div
className="col-span-2 text-right text-xs font-mono"
style={{ color: "var(--color-ink-muted)" }}
>
{hw.id.slice(0, 8)}...
</div>
</li>
))}
</ul>
)}
</div>
);
}

View File

@@ -0,0 +1,5 @@
import AppShell from "@/components/AppShell";
export default function AppLayout({ children }: { children: React.ReactNode }) {
return <AppShell>{children}</AppShell>;
}

View File

@@ -0,0 +1,133 @@
"use client";
import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import { login, isAuthenticated } from "@/lib/auth";
export default function LoginPage() {
const router = useRouter();
const [email, setEmail] = useState("teacher2@edu.test");
const [password, setPassword] = useState("Teacher@123");
const [error, setError] = useState<string | null>(null);
const [loading, setLoading] = useState(false);
useEffect(() => {
if (isAuthenticated()) {
router.replace("/dashboard");
}
}, [router]);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setLoading(true);
setError(null);
try {
await login(email, password);
router.replace("/dashboard");
} catch (err) {
setError(err instanceof Error ? err.message : "登录失败");
} finally {
setLoading(false);
}
};
return (
<div
className="min-h-screen flex items-center justify-center"
style={{ background: "var(--bg-paper)" }}
>
<div className="w-full max-w-sm px-8">
<div className="text-center mb-8">
<h1
className="text-3xl"
style={{
fontFamily: "var(--font-serif)",
color: "var(--color-ink)",
}}
>
Edu
</h1>
<p
className="mt-2 text-sm"
style={{ color: "var(--color-ink-muted)" }}
>
</p>
</div>
<div className="rule-thin mb-6" />
<form onSubmit={handleSubmit} className="space-y-5">
<div>
<label
className="block text-xs uppercase tracking-wide mb-1"
style={{ color: "var(--color-ink-muted)" }}
>
</label>
<input
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
className="w-full px-3 py-2 bg-transparent border-b focus:outline-none focus:border-b-2"
style={{
borderColor: "var(--color-rule)",
borderRadius: "6px 6px 0 0",
}}
required
/>
</div>
<div>
<label
className="block text-xs uppercase tracking-wide mb-1"
style={{ color: "var(--color-ink-muted)" }}
>
</label>
<input
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
className="w-full px-3 py-2 bg-transparent border-b focus:outline-none focus:border-b-2"
style={{
borderColor: "var(--color-rule)",
borderRadius: "6px 6px 0 0",
}}
required
/>
</div>
{error && (
<div
className="mark-left py-2"
style={{ borderColor: "var(--color-accent)" }}
>
<p
className="text-sm px-3"
style={{ color: "var(--color-accent)" }}
>
{error}
</p>
</div>
)}
<button
type="submit"
disabled={loading}
className="w-full px-4 py-2 text-white text-sm tracking-wide transition-opacity hover:opacity-90 disabled:opacity-50"
style={{ background: "var(--color-accent)", borderRadius: "6px" }}
>
{loading ? "登录中..." : "登录"}
</button>
</form>
<p
className="mt-6 text-center text-xs"
style={{ color: "var(--color-ink-muted)" }}
>
P2 · JWT + RBAC +
</p>
</div>
</div>
);
}

View File

@@ -1,219 +1,13 @@
'use client';
"use client";
import { useState, useEffect, useCallback } from 'react';
interface ClassItem {
id: string;
name: string;
gradeId: string;
description?: string;
createdAt: number;
updatedAt: number;
}
interface ApiResponse<T> {
success: boolean;
data?: T;
error?: { code: string; message: string };
}
export default function HomePage() {
const [classes, setClasses] = useState<ClassItem[]>([]);
const [loading, setLoading] = useState(false);
const [name, setName] = useState('');
const [gradeId, setGradeId] = useState('550e8400-e29b-41d4-a716-446655440000');
const [description, setDescription] = useState('');
const [error, setError] = useState<string | null>(null);
const fetchClasses = useCallback(async () => {
setLoading(true);
setError(null);
try {
const res = await fetch('/api/v1/classes');
const json: ApiResponse<ClassItem[]> = await res.json();
if (json.success && json.data) {
setClasses(json.data);
} else {
setError(json.error?.message || 'Failed to load');
}
} catch (e) {
setError(e instanceof Error ? e.message : 'Network error');
} finally {
setLoading(false);
}
}, []);
import { useEffect } from "react";
import { useRouter } from "next/navigation";
import { isAuthenticated } from "@/lib/auth";
export default function Home() {
const router = useRouter();
useEffect(() => {
fetchClasses();
}, [fetchClasses]);
const handleCreate = async (e: React.FormEvent) => {
e.preventDefault();
if (!name.trim()) return;
try {
const res = await fetch('/api/v1/classes', {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer dev-token' },
body: JSON.stringify({ name, gradeId, description }),
});
const json = await res.json();
if (!json.success) {
setError(json.error?.message || 'Create failed');
return;
}
setName('');
setDescription('');
await fetchClasses();
} catch (e) {
setError(e instanceof Error ? e.message : 'Network error');
}
};
const handleDelete = async (id: string) => {
try {
const res = await fetch(`/api/v1/classes/${id}`, {
method: 'DELETE',
headers: { 'Authorization': 'Bearer dev-token' },
});
const json = await res.json();
if (!json.success) {
setError(json.error?.message || 'Delete failed');
return;
}
await fetchClasses();
} catch (e) {
setError(e instanceof Error ? e.message : 'Network error');
}
};
return (
<div className="min-h-screen" style={{ background: 'var(--bg-paper)' }}>
<header className="border-b" style={{ borderColor: 'var(--color-rule)' }}>
<div className="max-w-6xl mx-auto px-8 py-6">
<h1 className="text-3xl" style={{ fontFamily: 'var(--font-serif)', color: 'var(--color-ink)' }}>
</h1>
<p className="mt-1 text-sm" style={{ color: 'var(--color-ink-muted)' }}>
P1 - classes CRUD
</p>
</div>
</header>
<main className="max-w-6xl mx-auto px-8 py-8 grid grid-cols-12 gap-8">
{/* 左侧:创建表单 */}
<aside className="col-span-4">
<h2 className="text-xl mb-4" style={{ fontFamily: 'var(--font-serif)' }}></h2>
<div className="rule-thin mb-4" />
<form onSubmit={handleCreate} className="space-y-4">
<div>
<label className="block text-xs uppercase tracking-wide mb-1" style={{ color: 'var(--color-ink-muted)' }}>
</label>
<input
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
className="w-full px-3 py-2 bg-transparent border-b focus:outline-none focus:border-b-2"
style={{ borderColor: 'var(--color-rule)', borderRadius: '6px 6px 0 0' }}
placeholder="如:高三(1)班"
required
/>
</div>
<div>
<label className="block text-xs uppercase tracking-wide mb-1" style={{ color: 'var(--color-ink-muted)' }}>
ID
</label>
<input
type="text"
value={gradeId}
onChange={(e) => setGradeId(e.target.value)}
className="w-full px-3 py-2 bg-transparent border-b text-sm font-mono"
style={{ borderColor: 'var(--color-rule)', borderRadius: '6px 6px 0 0' }}
/>
</div>
<div>
<label className="block text-xs uppercase tracking-wide mb-1" style={{ color: 'var(--color-ink-muted)' }}>
</label>
<textarea
value={description}
onChange={(e) => setDescription(e.target.value)}
className="w-full px-3 py-2 bg-transparent border-b resize-none"
style={{ borderColor: 'var(--color-rule)', borderRadius: '6px 6px 0 0' }}
rows={3}
/>
</div>
<button
type="submit"
className="px-4 py-2 text-white text-sm tracking-wide transition-opacity hover:opacity-90"
style={{ background: 'var(--color-accent)', borderRadius: '6px' }}
>
</button>
</form>
</aside>
{/* 中间:班级列表(纸面)*/}
<section className="col-span-8">
<div className="flex items-baseline justify-between mb-4">
<h2 className="text-xl" style={{ fontFamily: 'var(--font-serif)' }}>
<span className="ml-2 text-sm font-sans" style={{ color: 'var(--color-ink-muted)' }}>
{classes.length}
</span>
</h2>
<button
onClick={fetchClasses}
className="text-xs uppercase tracking-wide hover:opacity-70"
style={{ color: 'var(--color-accent)' }}
>
</button>
</div>
<div className="rule-thin mb-6" />
{error && (
<div className="mark-left mb-4 py-2" style={{ borderColor: 'var(--color-accent)' }}>
<p className="text-sm" style={{ color: 'var(--color-accent)' }}>{error}</p>
</div>
)}
{loading ? (
<p className="text-sm" style={{ color: 'var(--color-ink-muted)' }}>...</p>
) : classes.length === 0 ? (
<p className="text-sm italic" style={{ color: 'var(--color-ink-muted)' }}>
</p>
) : (
<ul className="space-y-0">
{classes.map((cls) => (
<li key={cls.id} className="py-4 grid grid-cols-12 gap-4 items-baseline" style={{ borderBottom: '1px solid var(--color-rule)' }}>
<div className="col-span-7">
<h3 className="text-lg" style={{ fontFamily: 'var(--font-serif)', color: 'var(--color-ink)' }}>
{cls.name}
</h3>
{cls.description && (
<p className="mt-1 text-sm" style={{ color: 'var(--color-ink-muted)' }}>{cls.description}</p>
)}
</div>
<div className="col-span-3 text-xs font-mono" style={{ color: 'var(--color-ink-muted)' }}>
{cls.id.slice(0, 8)}...
</div>
<div className="col-span-2 text-right">
<button
onClick={() => handleDelete(cls.id)}
className="text-xs uppercase tracking-wide hover:opacity-70"
style={{ color: 'var(--color-ink-muted)' }}
>
</button>
</div>
</li>
))}
</ul>
)}
</section>
</main>
</div>
);
router.replace(isAuthenticated() ? "/dashboard" : "/login");
}, [router]);
return null;
}

View File

@@ -0,0 +1,161 @@
"use client";
import { useState, useEffect, useCallback } from "react";
import { useRouter, usePathname } from "next/navigation";
import Link from "next/link";
import { getToken, getUser, logout } from "@/lib/auth";
interface ViewportItem {
key: string;
label: string;
route: string;
icon: string | null;
sortOrder: string;
requiredPermission: string | null;
}
export default function AppShell({ children }: { children: React.ReactNode }) {
const router = useRouter();
const pathname = usePathname();
const [viewports, setViewports] = useState<ViewportItem[]>([]);
const [loading, setLoading] = useState(true);
const [mounted, setMounted] = useState(false);
const fetchViewports = useCallback(async () => {
const token = getToken();
if (!token) {
router.replace("/login");
return;
}
try {
const res = await fetch("/api/v1/teacher/viewports", {
headers: { Authorization: `Bearer ${token}` },
});
if (res.status === 401) {
logout();
return;
}
const json = await res.json();
if (json.success && json.data) {
setViewports(json.data);
}
} catch {
// 网络错误,保持空视口
} finally {
setLoading(false);
}
}, [router]);
useEffect(() => {
setMounted(true);
const token = getToken();
if (!token) {
router.replace("/login");
return;
}
fetchViewports();
}, [router, fetchViewports]);
// 防止 SSR 闪烁
if (!mounted) return null;
const user = getUser();
return (
<div
className="min-h-screen flex"
style={{ background: "var(--bg-paper)" }}
>
{/* 左侧栏:导航树 */}
<aside
className="w-56 flex-shrink-0 border-r relative flex flex-col"
style={{
borderColor: "var(--color-rule)",
background: "var(--bg-paper)",
}}
>
<div className="px-6 py-6">
<h1
className="text-xl"
style={{
fontFamily: "var(--font-serif)",
color: "var(--color-ink)",
}}
>
Edu
</h1>
<p
className="text-xs mt-1"
style={{ color: "var(--color-ink-muted)" }}
>
</p>
</div>
<div className="rule-thin mx-6" />
<nav className="mt-4 px-3">
{loading ? (
<p
className="text-xs px-3 py-2"
style={{ color: "var(--color-ink-muted)" }}
>
...
</p>
) : (
viewports.map((vp) => {
const active = pathname === vp.route;
return (
<Link
key={vp.key}
href={vp.route}
className="block px-3 py-2 text-sm transition-colors"
style={{
color: active ? "var(--color-accent)" : "var(--color-ink)",
borderLeft: active
? "2px solid var(--color-accent)"
: "2px solid transparent",
fontFamily: active
? "var(--font-serif)"
: "var(--font-inter)",
}}
>
{vp.label}
</Link>
);
})
)}
</nav>
{/* 底部:用户信息 + 登出 */}
<div
className="mt-auto px-6 py-4 border-t"
style={{ borderColor: "var(--color-rule)" }}
>
{user && (
<div className="mb-2">
<p className="text-sm" style={{ color: "var(--color-ink)" }}>
{user.name}
</p>
<p
className="text-xs"
style={{ color: "var(--color-ink-muted)" }}
>
{user.roles.join(", ") || "无角色"}
</p>
</div>
)}
<button
onClick={logout}
className="text-xs uppercase tracking-wide hover:opacity-70"
style={{ color: "var(--color-ink-muted)" }}
>
退
</button>
</div>
</aside>
{/* 中间:内容区(纸面) */}
<main className="flex-1 overflow-auto">{children}</main>
</div>
);
}

View File

@@ -0,0 +1,77 @@
// 认证工具token 存储 + 路由保护
const TOKEN_KEY = "edu_access_token";
const USER_KEY = "edu_user_info";
export interface UserInfo {
id: string;
email: string;
name: string;
roles: string[];
permissions: string[];
dataScope: string;
}
export function getToken(): string | null {
if (typeof window === "undefined") return null;
return localStorage.getItem(TOKEN_KEY);
}
export function setToken(token: string): void {
if (typeof window === "undefined") return;
localStorage.setItem(TOKEN_KEY, token);
}
export function clearToken(): void {
if (typeof window === "undefined") return;
localStorage.removeItem(TOKEN_KEY);
localStorage.removeItem(USER_KEY);
}
export function getUser(): UserInfo | null {
if (typeof window === "undefined") return null;
const raw = localStorage.getItem(USER_KEY);
if (!raw) return null;
try {
return JSON.parse(raw) as UserInfo;
} catch {
return null;
}
}
export function setUser(user: UserInfo): void {
if (typeof window === "undefined") return;
localStorage.setItem(USER_KEY, JSON.stringify(user));
}
export function isAuthenticated(): boolean {
return getToken() !== null;
}
// 调用 Gateway 登录接口
export async function login(
email: string,
password: string,
): Promise<{ user: UserInfo; token: string }> {
const res = await fetch("/api/v1/iam/login", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ email, password }),
});
const json = await res.json();
if (!json.success) {
throw new Error(json.error?.message || "登录失败");
}
const user = json.data.user as UserInfo;
const token = json.data.tokens.accessToken as string;
setToken(token);
setUser(user);
return { user, token };
}
export function logout(): void {
clearToken();
if (typeof window !== "undefined") {
window.location.href = "/login";
}
}

View File

@@ -0,0 +1,363 @@
# CI/CD 使用手册CI/CD Runbook
> 版本2.0no-push 本地构建模式)
> 日期2026-07-08
> 适用范围Edu 微服务项目Gitea Actions + Runner 本地构建部署)
> 关联文档:[project_rules §15](../../.trae/rules/project_rules.md)、[本地启动手册](./local-dev-runbook.md)、[多 AI 协作指南](./multi-ai-collaboration.md)
> 设计文档:[2026-07-08-cicd-no-push-local-build-design.md](../superpowers/specs/2026-07-08-cicd-no-push-local-build-design.md)
---
## 1. 架构总览
```
PR 触发(开发 AI 提 PR push main 触发(协调 AI 合并)
│ │
▼ ▼
┌─────────────────────────┐ ┌─────────────────────────┐
│ ci.yml │ │ ci.yml │
│ quality-ts (node:22) │ │ quality-ts (node:22) │
│ quality-go (golang) │ │ quality-go (golang) │
│ quality-proto (buf) │ │ quality-proto (buf) │
│ (并行,不部署) │ │ │ │
└─────────────────────────┘ │ ▼ │
│ deploy job │
│ (docker:25-git) │
│ 挂载 /var/run/docker.sock│
│ │ │
│ ▼ │
│ docker compose up │
│ --build本地构建
│ │ │
│ ▼ │
│ 健康检查轮询 │
└─────────────────────────┘
```
### 1.1 核心特点
- **单文件管理**:一个 `.github/workflows/ci.yml` 管全部 CI/CD
- **no-push 本地构建**:不推送到 registry构建即部署
- **不依赖自建镜像**全部使用官方镜像node/golang/buf/docker
- **DooD 模式**deploy job 容器内挂载宿主机 `/var/run/docker.sock`
### 1.2 组件清单
| 组件 | 说明 |
| ----------------- | ------------------------------------------- |
| **Gitea** | `git.eazygame.cn`,代码托管 + Actions |
| **Gitea Actions** | CI 运行器,兼容 GitHub Actions 语法 |
| **actrunner** | 跑在服务器上的 runner标签 `ubuntu-latest` |
| **服务器 MySQL** | 已有容器,端口 3306 |
| **服务器 Redis** | 已有容器,端口 6379 |
### 1.3 流水线文件
| 文件 | 触发 | 作用 |
| --------------------------------- | ---------------------------------- | --------------------------------------------- |
| `.github/workflows/ci.yml` | PR + push main + workflow_dispatch | quality3 job 并行)+ deploy仅 push main |
| `infra/docker-compose.deploy.yml` | deploy job 调用 | 多服务编排build: 替代 image: |
| `infra/docker-compose.tools.yml` | 手动执行 | 一次性预拉所有 CI 镜像 |
---
## 2. 一次性配置
### 2.1 启用 Gitea Actions + actrunner
1. 仓库设置 → Actions → 启用
2. 安装 actrunner 并注册(标签 `ubuntu-latest`
3. 配置 actrunner 允许挂载 docker.sock
```toml
# /etc/gitea/act_runner/config.yaml
container:
valid_volumes:
- /var/run/docker.sock
```
### 2.2 预拉所有 CI 镜像(一次性)
```bash
# 在服务器上,进入 Edu 仓库目录
cd /path/to/Edu
docker compose -f infra/docker-compose.tools.yml pull
```
拉取的镜像清单:
| 镜像 | 用途 |
| --------------------- | --------------------------------------------------- |
| `node:22-alpine` | CI quality-ts job |
| `golang:1.22-alpine` | CI quality-go job + api-gateway builder |
| `bufbuild/buf:latest` | CI quality-proto job |
| `docker:25-git` | CI deploy job自带 docker CLI + compose v2 + git |
| `node:20-alpine` | teacher-portal / classes builder |
| `alpine:3.20` | api-gateway runner |
| `mysql:8.0` | 开发测试用(生产用已有的) |
| `redis:7-alpine` | 开发测试用(生产用已有的) |
### 2.3 准备服务器网络
```bash
# 创建共享网络(若不存在)
docker network create edu-shared
# 将已有的 MySQL/Redis 加入网络(容器名按实际替换)
docker network connect edu-shared <实际mysql容器名>
docker network connect edu-shared <实际redis容器名>
```
### 2.4 初始化部署目录
```bash
# 1. 创建部署目录
sudo mkdir -p /opt/edu
sudo chown -R $USER:$USER /opt/edu
# 2. 创建生产 .env从模板
cp infra/deploy.env.example /opt/edu/.env
vim /opt/edu/.env
# 必须修改:
# JWT_SECRET=<openssl rand -hex 32 生成的随机值>
# DATABASE_URL=mysql://<user>:<pass>@<mysql容器名>:3306/<db>
# REDIS_URL=redis://<redis容器名>:6379
```
> 注意:`/opt/edu/repo/` 子目录由 CI 自动同步,不需要手动准备。
---
## 3. 日常使用
### 3.1 开发 AI 提 PR
```
PR 创建 → ci.yml 运行
├─ quality-tspnpm lint + typecheck + test + build
├─ quality-gogo vet + build + test
└─ quality-protobuf lint + buf breaking
3 个 job 并行,仅 quality不部署
CI 全绿 → 协调 AI 审核合并
```
### 3.2 协调 AI 合并 PR
PR 合并到 main 后自动触发:
```
push main → ci.yml
├─ quality-* 3 个 job 并行,确保 main 稳定)
└─ deploy jobneeds: [quality-ts, quality-go, quality-proto]
同步代码到 /opt/edu/repo/
docker compose up -d --build本地构建 3 个服务)
健康检查轮询10 次 × 6 秒)
```
### 3.3 手动触发部署
在 Gitea → Actions → CI → Run workflow
- `commit_sha`(可选):回滚到指定 commit留空则部署当前 HEAD
### 3.4 不再支持 tag 发布
no-push 模式下,镜像不存放到 registry因此不再使用 `git tag v*` 触发发布。版本管理通过 git commit SHA 追溯。
---
## 4. 部署验证
### 4.1 CI 自动验证
deploy job 部署后会自动轮询健康检查:
- `http://localhost:8080/healthz` — api-gateway
- `http://localhost:3001/healthz` — classes
- `http://localhost:3000/` — teacher-portal
失败时输出容器状态与日志,方便排查。
### 4.2 手动验证
```bash
cd /opt/edu
# 容器状态
docker compose ps
# 健康检查
curl http://localhost:8080/healthz
curl http://localhost:3001/healthz
curl http://localhost:3000/
# 鉴权验证(生产模式 dev-token 应被拒绝)
curl -H "Authorization: Bearer dev-token" http://localhost:8080/api/v1/classes
# 预期401 INVALID_TOKEN
# 查看日志
docker compose logs -f api-gateway
docker compose logs -f classes
docker compose logs -f teacher-portal
```
---
## 5. 回滚
### 5.1 git revert推荐
```bash
git revert <bad-commit>
git push origin main
# CI 自动重新构建部署
```
### 5.2 手动触发指定 commit
在 Gitea → Actions → CI → Run workflow
- `commit_sha`:填入上一个稳定版本的 commit SHA
CI 会 checkout 指定 commit → 本地重新 build → deploy。
### 5.3 不再支持镜像 tag 回滚
no-push 模式下没有 registry tag不能像旧方案那样切换 `IMAGE_TAG`。回滚必须重新构建。
---
## 6. 常见问题
### 6.1 CI: pnpm install 失败
**症状**`pnpm install --frozen-lockfile` 报错。
**排查**
1. `pnpm-lock.yaml` 未提交:`git add pnpm-lock.yaml && git commit`
2. Node 版本不匹配:确认 CI 用 Node 22本地一致
### 6.2 CI: deploy job 无法访问 docker
**症状**`docker compose up``Cannot connect to the Docker daemon`
**原因**actrunner 没有挂载 `/var/run/docker.sock`,或 `valid_volumes` 未配置。
**修复**
```toml
# /etc/gitea/act_runner/config.yaml
container:
valid_volumes:
- /var/run/docker.sock
```
重启 actrunner 后重试。
### 6.3 CD: 健康检查失败
**症状**deploy job 健康检查 10 次后失败。
**排查**
1. CI 输出会自动打印容器状态和日志
2. 常见原因:
- `DATABASE_URL` 连不上 MySQL检查容器名与网络
- `JWT_SECRET` 未配置
- 端口被占用:`docker ps` 检查冲突
- `/opt/edu/.env` 不存在或格式错误
### 6.4 CD: 连不上 MySQL/Redis
**症状**classes 容器报 `ECONNREFUSED edu-mysql:3306`
**修复**
```bash
# 1. 确认 MySQL 容器名
docker ps --format "{{.Names}}" | grep mysql
# 2. 确认 MySQL 在 edu-shared 网络
docker network inspect edu-shared | grep -A5 Containers
# 3. 若不在,加入网络
docker network connect edu-shared <实际mysql容器名>
# 4. 修改 /opt/edu/.env 的 DATABASE_URL
# DATABASE_URL=mysql://edu:changeme@<实际容器名>:3306/next_edu_cloud
```
### 6.5 Gitea Actions 未触发
**排查**
1. 仓库设置 → Actions → 确认已启用
2. Runner 在线Gitea → 设置 → Actions → Runners
3. workflow 文件在 `.github/workflows/` 目录
4. `on:` 触发条件匹配
---
## 7. 排查命令速查
```bash
# === 在服务器上 ===
# 查看所有 edu 容器
docker compose -f /opt/edu/docker-compose.yml ps
# 查看实时日志
docker compose -f /opt/edu/docker-compose.yml logs -f
# 重启单个服务
docker compose -f /opt/edu/docker-compose.yml restart api-gateway
# 重新构建并启动(手动触发部署)
cd /opt/edu/repo
git pull
cd /opt/edu
docker compose up -d --build
# 进入容器
docker exec -it edu-api-gateway sh
docker exec -it edu-classes sh
# 查看网络
docker network inspect edu-shared
# 查看本地镜像
docker images | grep -E "node|golang|docker|alpine|buf"
# === 在 Gitea Web UI ===
# 仓库 → Actions → 查看流水线运行记录
# 仓库 → 设置 → Actions → Runners → 查看 Runner 状态
```
---
## 8. 安全注意事项
1. **`.env` 文件不入库**`.gitignore` 已忽略,仅存在于服务器 `/opt/edu/.env`
2. **JWT_SECRET 强随机**:生产必须用 `openssl rand -hex 32` 生成
3. **DEV_MODE=false**docker-compose.deploy.yml 强制设为 `false`
4. **docker.sock 安全**actrunner 仅在部署服务器运行,已隔离
5. **Runner 隔离**runner 跑在服务器上,不暴露公网 SSH
---
## 9. 相关文档
- [project_rules §15 CI/CD 规范](../../.trae/rules/project_rules.md)
- [project_rules §14 多 AI 协作规范](../../.trae/rules/project_rules.md)
- [本地启动手册](./local-dev-runbook.md)
- [多 AI 协作指南](./multi-ai-collaboration.md)
- [known-issues](../troubleshooting/known-issues.md)
- [CI/CD 设计文档](../superpowers/specs/2026-07-08-cicd-no-push-local-build-design.md)

View File

@@ -0,0 +1,333 @@
# 本地启动手册Local Dev Runbook
> 版本1.0
> 日期2026-07-08
> 适用范围Edu 微服务P1 阶段api-gateway + classes + teacher-portal
> 关联文档:[project_rules](../../.trae/rules/project_rules.md)、[004 架构影响地图](../architecture/004_architecture_impact_map.md)、[known-issues](../troubleshooting/known-issues.md)
---
## 1. 环境依赖
| 工具 | 版本要求 | 验证命令 | 说明 |
| -------------- | -------- | ------------------------ | -------------------------- |
| Node.js | ≥ 20 | `node -v` | LTS 版本 |
| pnpm | ≥ 9 | `pnpm -v` | `corepack enable` 自动启用 |
| Go | 1.22+ | `go version` | api-gateway 编译 |
| Docker | 24+ | `docker version` | 基础设施容器化 |
| Docker Compose | v2+ | `docker compose version` | 编排基础设施 |
| Git | 2.30+ | `git --version` | husky hooks 需要 |
> Windows 用户:建议在 PowerShell 或 Git Bash 中执行。Go 工具链若不在 PATH临时加入`$env:Path = "C:\Program Files\Go\bin;" + $env:Path`
---
## 2. 服务端口分配
| 服务 | 端口 | 语言/框架 | 启动方式 | 健康检查 |
| -------------- | ---- | ------------ | ------------------- | ----------------- |
| MySQL | 3306 | Docker | `docker compose up` | `mysqladmin ping` |
| Redis | 6379 | Docker | `docker compose up` | `redis-cli ping` |
| api-gateway | 8080 | Go (Gin) | `go run main.go` | `GET /healthz` |
| classes | 3001 | NestJS (TS) | `pnpm dev` | `GET /healthz` |
| teacher-portal | 3000 | Next.js (TS) | `pnpm dev` | `GET /` |
| iam | 3002 | NestJS | P2 阶段 | — |
| teacher-bff | 3003 | NestJS | P2 阶段 | — |
> 端口冲突排查:`netstat -ano \| findstr :8080`Windows
---
## 3. 本地开发模式DEV_MODE
### 3.1 首次准备
```bash
# 1. 克隆仓库
git clone <repo-url> Edu
cd Edu
# 2. 安装依赖
pnpm install
# 3. 配置环境变量
cp .env.example .env
# 编辑 .env确认
# DEV_MODE=true ← 本地联调用
# JWT_SECRET=p1-dev-secret-change-in-production
# DATABASE_URL=mysql://edu:changeme@localhost:3306/next_edu_cloud
# REDIS_URL=redis://localhost:6379
# 4. 架构扫描(更新 arch.db
pnpm run arch:scan
```
### 3.2 启动基础设施
```bash
# 启动 MySQL + Redis最小基础设施
docker compose -f infra/docker-compose.minimal.yml up -d
# 验证健康
docker compose -f infra/docker-compose.minimal.yml ps
# 状态应为 healthy
# 可选国内镜像源加速infra/docker-compose.minimal.override.yml 已配置 daocloud 镜像
```
### 3.3 启动应用服务(三个终端)
#### 终端 1api-gateway:8080
```bash
cd services/api-gateway
# Windows若 Go 不在 PATH先设置
$env:Path = "C:\Program Files\Go\bin;" + $env:Path
# 设置开发模式环境变量
$env:DEV_MODE="true"
$env:JWT_SECRET="p1-dev-secret-change-in-production"
# 启动
go run main.go
```
验证:`curl http://localhost:8080/healthz` → 200 OK
#### 终端 2classes 服务(:3001
```bash
# 在项目根目录
pnpm --filter @edu/classes-service dev
```
验证:`curl http://localhost:3001/healthz` → 200 OK
> classes 的 HealthModule 需注册到 AppModule当前若返回 404 见 [known-issues]
#### 终端 3teacher-portal:3000
```bash
# 在项目根目录
pnpm --filter @edu/teacher-portal dev
```
验证:浏览器访问 `http://localhost:3000` → 班级管理页面
### 3.4 一键启动(可选)
```bash
# 并行启动所有子包的 dev 脚本(含 api-gateway 需 go run不会自动启动
pnpm dev
```
> 注:`pnpm dev` 仅启动 pnpm workspace 内的 TS 服务。api-gateway 是 Go 服务,需单独 `go run`。
### 3.5 联调验证
```bash
# 1. 直接访问 api-gateway带 dev-token
curl -H "Authorization: Bearer dev-token" http://localhost:8080/api/v1/classes
# 预期200 OK + 班级列表 JSON
# 2. 通过 teacher-portal 代理访问
curl -H "Authorization: Bearer dev-token" http://localhost:3000/api/v1/classes
# 预期200 OK经 Next.js rewrites → api-gateway → classes
# 3. 浏览器访问
# http://localhost:3000 → 班级管理页面,自动加载班级列表
```
### 3.6 dev-token 说明
- `DEV_MODE=true`api-gateway 接受 `Authorization: Bearer dev-token`
- 注入固定身份:`x-user-id: dev-user``x-user-roles: teacher,admin`
- **仅限本地联调,生产环境必须 `DEV_MODE=false`**
---
## 4. 生产模式Docker Compose
### 4.1 构建镜像
```bash
# 构建三个应用服务镜像
docker compose -f infra/docker-compose.prod.yml build
```
### 4.2 启动完整栈
```bash
# 1. 先启动基础设施MySQL + Redis
docker compose -f infra/docker-compose.minimal.yml up -d
# 2. 启动应用服务
docker compose -f infra/docker-compose.prod.yml up -d
# 3. 查看状态
docker compose -f infra/docker-compose.prod.yml ps
# 所有服务应为 healthy
# 4. 查看日志
docker compose -f infra/docker-compose.prod.yml logs -f api-gateway
```
### 4.3 生产环境配置要点
| 配置项 | 生产值 | 说明 |
| -------------- | ---------------- | ----------------------------------------------- |
| `DEV_MODE` | `false` | docker-compose.prod.yml 强制设为 false |
| `JWT_SECRET` | 强随机值 | 替换 `p1-dev-secret-change-in-production` |
| `DATABASE_URL` | 生产数据库连接 | 容器内用 `host.docker.internal` 或 compose 网络 |
| `NODE_ENV` | `production` | teacher-portal 启用生产优化 |
| `LOG_LEVEL` | `info``warn` | 生产日志级别 |
### 4.4 生产验证
```bash
# 健康检查
curl http://localhost:8080/healthz # api-gateway
curl http://localhost:3001/healthz # classes
curl http://localhost:3000/ # teacher-portal
# 鉴权验证(生产模式 dev-token 应被拒绝)
curl -H "Authorization: Bearer dev-token" http://localhost:8080/api/v1/classes
# 预期401 INVALID_TOKEN
# 真实 JWT 访问(需 IAM 签发)
curl -H "Authorization: Bearer <real-jwt>" http://localhost:8080/api/v1/classes
# 预期200 OK
```
### 4.5 停止与清理
```bash
# 停止应用服务
docker compose -f infra/docker-compose.prod.yml down
# 停止基础设施
docker compose -f infra/docker-compose.minimal.yml down
# 清理数据卷(谨慎!会删除数据库数据)
docker compose -f infra/docker-compose.minimal.yml down -v
```
---
## 5. 单独构建与运行(裸机生产)
### 5.1 api-gateway
```bash
cd services/api-gateway
# 编译
go build -o bin/api-gateway ./main.go
# 运行(生产环境变量)
DEV_MODE=false JWT_SECRET=<your-secret> ./bin/api-gateway
```
### 5.2 classes 服务
```bash
# 构建
pnpm --filter @edu/classes-service build
# 运行(从 dist/ 启动)
NODE_ENV=production PORT=3001 \
DATABASE_URL=mysql://edu:changeme@localhost:3306/next_edu_cloud \
REDIS_URL=redis://localhost:6379 \
node services/classes/dist/main.js
```
### 5.3 teacher-portal
```bash
# 构建
pnpm --filter @edu/teacher-portal build
# 运行
NODE_ENV=production PORT=3000 \
API_GATEWAY_URL=http://localhost:8080 \
node apps/teacher-portal/node_modules/.bin/next start -p 3000
```
---
## 6. 常见问题
### 6.1 ERR_TOO_MANY_REDIRECTS
**症状**:浏览器访问 `:3000/api/v1/classes` 无限重定向。
**根因**Gin 默认 `RedirectTrailingSlash=true``/classes` → 301 → `/classes/`Next.js rewrites 代理形成循环。
**修复**`main.go` 已设 `r.RedirectTrailingSlash = false`,并同时注册无尾斜杠与通配符路由。
### 6.2 Docker Hub 拉取超时
**症状**`docker compose up` 时 MySQL/Redis 镜像拉取超时。
**修复**`infra/docker-compose.minimal.override.yml` 已配置 daocloud 镜像源docker compose 会自动加载。
### 6.3 classes DI 注入失败
**症状**`TypeError: Cannot read properties of undefined (reading 'create')`
**根因**NestJS ESM 模式下 `emitDecoratorMetadata` 不工作。
**修复**`ClassesService` 构造函数已加 `@Inject(ClassesRepository)` 显式指定 token。
### 6.4 ESM import 缺 .js 后缀
**症状**`error TS2307: Cannot find module './health.controller'`
**修复**ESM 模式下相对 import 必须带 `.js` 后缀(详见 project_rules §3.4)。
### 6.5 JWT 401 INVALID_TOKEN
**症状**:带 `dev-token` 仍返回 401。
**排查**
1. 确认 `DEV_MODE=true` 环境变量已设置api-gateway 进程)
2. 确认请求头格式:`Authorization: Bearer dev-token`(注意 Bearer 后空格)
3. 生产模式(`DEV_MODE=false`)下 dev-token 被拒绝是预期行为
### 6.6 Go 工具链不在 PATH
**症状**Git Bash 或 PowerShell 中 `go: command not found`
**修复**
```powershell
$env:Path = "C:\Program Files\Go\bin;" + $env:Path
```
---
## 7. 数据库初始化
classes 服务使用 Drizzle ORM首次运行需建表
```bash
# 生成迁移
pnpm --filter @edu/classes-service drizzle-kit generate
# 执行迁移
pnpm --filter @edu/classes-service drizzle-kit migrate
```
> 若 `drizzle-kit` 未配置,可手动执行 `services/classes/src/db/schema.sql`(如存在)。
---
## 8. 相关文档
- [项目规则](../../.trae/rules/project_rules.md) — 强制约束
- [004 架构影响地图](../architecture/004_architecture_impact_map.md) — 服务清单与调用关系
- [known-issues](../troubleshooting/known-issues.md) — 已知问题速查
- [Git 工作流](./git-workflow.md) — 提交与 PR 规范
- [多 AI 协作指南](./multi-ai-collaboration.md) — 多 Agent 并行开发流程

View File

@@ -0,0 +1,735 @@
# 多 AI 协作开发指南Multi-AI Collaboration Guide
> 版本1.0
> 日期2026-07-08
> 适用范围Edu 微服务项目多 Agent 并行开发
> 关联文档:[Git 工作流](./git-workflow.md)、[项目规则](../../.trae/rules/project_rules.md)、[004 架构影响地图](../architecture/004_architecture_impact_map.md)、[CODEOWNERS](../../.github/CODEOWNERS)
---
## 1. 总体模式
### 1.1 角色定义
| 角色 | 职责 | 数量 | 备注 |
| ----------------------------- | -------------------------------------------- | ---- | ------------------- |
| **协调 AICoordinator AI** | PR 审核、合并、冲突仲裁、分支管理、发布 | 1 | 不直接写业务代码 |
| **开发 AIDev AI** | 按模块分工,写代码、提 PR | N | 每个负责 1-2 个模块 |
| **人类决策者Human** | 架构决策、Breaking Change 审批、最终发布确认 | 1 | 只在关键节点介入 |
### 1.2 工作流总览
```
开发 AI-A (classes模块) 开发 AI-B (iam模块) 协调 AI
│ │ │
│ 1.拉取最新 main │ 1.拉取最新 main │
│ 2.创建特性分支 │ 2.创建特性分支 │
│ 3.开发+提交 │ 3.开发+提交 │
│ 4.推送+创建 PR │ 4.推送+创建 PR │
│──────────────────────────────────────────────────────→│
│ │ │ 5.CI校验
│ │ │ 6.代码审核
│ │ │ 7.合并到 main
│ │ │ 8.通知开发 AI 同步
│←─────────────────────────────────────────────────────│
│ 9.拉取最新 main │ │
```
---
## 2. 模块分工矩阵
### 2.1 模块清单与 AI 分配
每个 AI 负责一个"限界上下文",避免跨模块修改导致冲突。
| 模块 | scope | 路径 | 负责阶段 | 建议 AI 数 |
| -------------- | ---------------- | ------------------------- | -------- | ------------ |
| api-gateway | `api-gateway` | `services/api-gateway/` | P1 | 1 |
| classes | `classes` | `services/classes/` | P1 | 1 |
| teacher-portal | `teacher-portal` | `apps/teacher-portal/` | P1-P2 | 1 |
| iam | `iam` | `services/iam/` | P2 | 1 |
| teacher-bff | `teacher-bff` | `services/teacher-bff/` | P2 | 1 |
| core-edu | `core-edu` | `services/core-edu/` | P3 | 1 |
| content | `content` | `services/content/` | P4 | 1 |
| data-ana | `data-ana` | `services/data-ana/` | P4 | 1 |
| msg | `msg` | `services/msg/` | P5 | 1 |
| ai | `ai` | `services/ai/` | P5 | 1 |
| push-gateway | `push-gateway` | `services/push-gateway/` | P5 | 1 |
| shared-proto | `shared-proto` | `packages/shared-proto/` | 跨阶段 | 协调 AI 维护 |
| shared-tokens | `shared-tokens` | `packages/shared-tokens/` | 跨阶段 | 协调 AI 维护 |
| infra | `infra` | `infra/` | 跨阶段 | 1 (SRE AI) |
| docs | `docs` | `docs/` | 跨阶段 | 协调 AI 维护 |
### 2.2 分工原则
1. **单一负责制**:每个模块只有一个 AI 负责,避免并行修改同一文件
2. **契约集中管理**`shared-proto` 由协调 AI 维护,开发 AI 只读引用
3. **跨模块变更拆分**:需要修改多个模块时,拆成多个 PR按依赖顺序合并
4. **基础设施独立**`infra/` 由 SRE AI 专门负责,业务 AI 不直接修改
---
## 3. 分支策略
### 3.1 分支命名规范
```
<type>/<scope>-<task-id>-<ai-id>
```
| 字段 | 说明 | 示例 |
| --------- | ------------------------------------------- | ---------------- |
| `type` | feat / fix / refactor / docs / chore / test | `feat` |
| `scope` | 模块名(见 §2.1 | `classes` |
| `task-id` | 任务简短描述kebab-case | `add-pagination` |
| `ai-id` | AI 标识符(避免多 AI 同名冲突) | `ai01` |
**完整示例**
- `feat/classes-add-pagination-ai01`
- `fix/api-gateway-redirect-loop-ai02`
- `docs/git-workflow-update-coord`
### 3.2 分支生命周期
1. **创建**:从最新 `main` 拉取:`git checkout main && git pull && git checkout -b feat/classes-xxx-ai01`
2. **开发**:在特性分支上提交(遵循 Conventional Commits
3. **推送**`git push -u origin feat/classes-xxx-ai01`
4. **合并后删除**PR 合并后,删除本地与远程特性分支
> 特性分支寿命 ≤ 3 天(见 git-workflow.md §1。超期需 rebase 最新 main。
### 3.3 多 AI 分支隔离规则
- **禁止多 AI 共用同一分支**
- **禁止直接 push 到 `main`**(由协调 AI 通过 PR 合并)
- **跨模块变更**:各自在模块分支开发,最后由协调 AI 按依赖顺序合并
---
## 4. 推送与提交流程
### 4.1 提交规范Conventional Commits
```bash
git commit -m "feat(classes): 新增班级分页查询"
git commit -m "fix(api-gateway): 修复尾斜杠重定向循环"
git commit -m "docs(standards): 更新多AI协作文档"
```
**scope 必须匹配 `.commitlintrc.js` 的 scope-enum**26 项,见 git-workflow.md §3.3)。
### 4.2 标准推送流程
开发 AI 执行:
```bash
# 1. 确认在正确的特性分支
git branch --show-current
# 输出feat/classes-add-pagination-ai01
# 2. 拉取最新 mainrebase 保持线性)
git fetch origin
git rebase origin/main
# 3. 解决冲突(如有)
# 编辑冲突文件 → git add → git rebase --continue
# 4. 本地校验(强制,见 project_rules §7
pnpm run lint # TS 服务
pnpm run typecheck # TS 服务
cd services/api-gateway && go vet ./... && go build ./... # Go 服务
# 5. 推送
git push -u origin feat/classes-add-pagination-ai01
# 6. 创建 PR见 §5
```
### 4.3 多 AI 推送冲突处理
当多个 AI 的 PR 修改了同一文件(如 `package.json``004_architecture_impact_map.md`
1. **先合并的 PR 正常合并**
2. **后合并的 PR 需 rebase**
```bash
git fetch origin
git rebase origin/main
# 解决冲突
git push --force-with-lease # 安全强推(仅自己的分支)
```
3. **协调 AI 仲裁**:若冲突涉及架构决策,由协调 AI 决定保留方案
> **禁止 `git push --force` 到 main 或他人分支**。只允许 `--force-with-lease` 到自己的特性分支。
---
## 5. PR 流程
### 5.1 创建 PR
推送后,开发 AI 通过 Git 平台GitHub/Gitea创建 PR
```bash
# 使用 gh CLIGitHub
gh pr create \
--title "feat(classes): 新增班级分页查询" \
--body "## 变更说明
- 新增 GET /api/v1/classes?page=&size= 分页参数
- 响应增加 total/hasMore 字段
## 变更类型
- [x] feat新功能
## 影响范围
- [x] classes 服务
## 测试
- [x] 单元测试通过
- [x] 本地联调验证
## 校验
- [x] pnpm run lint
- [x] pnpm run typecheck
" \
--base main \
--head feat/classes-add-pagination-ai01
```
### 5.2 PR 标题规范
PR 标题必须与首个 commit 的 subject 一致Squash Merge 时自动取首个 commit
```
<type>(<scope>): <subject>
```
**示例**
- `feat(classes): 新增班级分页查询`
- `fix(api-gateway): 修复尾斜杠重定向循环`
### 5.3 PR 模板
使用 `.github/pull_request_template.md`(已存在)。必填项:
- 变更说明
- 变更类型
- 影响范围
- 测试情况
- 按语言校验结果
- 文档同步arch:scan、CODEOWNERS
### 5.4 PR 标注 AI 身份
在 PR 描述末尾追加(用于统计与审计):
```markdown
---
**AI Agent**: ai01 (classes-module)
**Branch**: feat/classes-add-pagination-ai01
**Coordinator**: coord-ai
```
---
## 6. 代码审核与合并
### 6.1 Reviewer 分配
由 `.github/CODEOWNERS` 自动分配:
| 模块 | 自动 Reviewer | 实际映射 |
| ------------ | ----------------------- | -------- |
| classes | `@edu-platform/classes` | 协调 AI |
| api-gateway | `@edu-platform/gateway` | 协调 AI |
| shared-proto | `@edu-platform/arch` | 协调 AI |
| infra | `@edu-platform/sre` | SRE AI |
> 当前 `@edu-platform/*` 为占位符。多 AI 场景下,协调 AI 账号加入对应 team 即可自动收到 review 请求。
### 6.2 审核 checklist
协调 AI 审核 PR 时检查:
- [ ] **Commit 格式**:符合 Conventional Commits
- [ ] **Scope 正确**scope 与修改的模块一致
- [ ] **架构合规**:无跨层依赖、无直接访问他人 DB
- [ ] **权限校验**Controller 有 `@RequirePermission()`
- [ ] **设计令牌**:无硬编码颜色/字体project_rules §3.10
- [ ] **ESM 规则**:相对 import 带 `.js` 后缀TS 服务)
- [ ] **契约同步**proto 变更已同步 shared-proto
- [ ] **文档同步**arch.db 已更新、004 已同步(如涉及)
- [ ] **CI 通过**lint / typecheck / go vet / ruff 全绿
- [ ] **测试覆盖**:关键逻辑有单测
### 6.3 合并策略
| 策略 | 适用场景 | 操作 |
| ------------------------ | ------------------------------------ | ---------------------- |
| **Squash Merge**(默认) | 单 commit 或多个小 commit 合并为一个 | `gh pr merge --squash` |
| **Rebase Merge** | 多个有意义的 commit 需保留历史 | `gh pr merge --rebase` |
| **Merge Commit**(禁止) | — | 不允许 |
> 项目规则 git-workflow.md §1.4**禁止 Merge Commit**,保持 main 历史线性。
### 6.4 合并流程(协调 AI 执行)
```bash
# 1. 确认 CI 通过
gh pr checks <PR-NUMBER>
# 2. 确认 review 通过CODEOWNERS 已 approve
gh pr view <PR-NUMBER> --json reviews
# 3. Squash 合并(删除源分支)
gh pr merge <PR-NUMBER> --squash --delete-branch
# 4. 通知开发 AI 同步本地 main
# (通过 commit message 或 issue 评论)
```
### 6.5 合并后同步
开发 AI 收到合并通知后:
```bash
# 切回 main
git checkout main
# 拉取最新(含已合并的 PR
git pull origin main
# 删除本地特性分支
git branch -d feat/classes-add-pagination-ai01
# 开始下一个任务:从最新 main 拉新分支
git checkout -b feat/classes-next-task-ai01
```
---
## 7. 多 AI 并行开发流程
### 7.1 启动并行任务
人类决策者分配任务给多个 AI
```
任务 1classes 服务新增分页查询 → 开发 AI-A (ai01)
任务 2api-gateway 新增限流规则 → 开发 AI-B (ai02)
任务 3teacher-portal 优化班级列表 → 开发 AI-C (ai03)
```
### 7.2 并行执行
每个 AI 独立工作,互不干扰:
```bash
# AI-A
git checkout -b feat/classes-add-pagination-ai01
# ... 开发 ...
git push -u origin feat/classes-add-pagination-ai01
gh pr create --title "feat(classes): 新增班级分页查询" ...
# AI-B同时
git checkout -b feat/api-gateway-rate-limit-ai02
# ... 开发 ...
git push -u origin feat/api-gateway-rate-limit-ai02
gh pr create --title "feat(api-gateway): 新增 IP 级限流规则" ...
# AI-C同时
git checkout -b feat/teacher-portal-class-list-ux-ai03
# ... 开发 ...
```
### 7.3 顺序合并(有依赖时)
若 PR 间有依赖(如 AI-C 依赖 AI-A 的接口),协调 AI 按顺序合并:
1. 合并 AI-A 的 PRclasses 分页接口)
2. AI-C rebase 最新 main解决冲突更新 PR
3. 合并 AI-C 的 PR前端调用新接口
### 7.4 冲突预防
1. **契约先行**proto 变更先合并,再合并依赖它的服务
2. **通知机制**:修改 `shared-proto/` 或 `004_architecture_impact_map.md` 时,在 PR 描述 @ 所有关联模块 AI
3. **频繁同步**:每天至少 `git pull origin main` 一次,避免长期分叉
---
## 8. 跨模块变更流程
### 8.1 变更拆分原则
修改涉及多模块时,按依赖顺序拆成多个 PR
```
原始任务classes 服务新增"班级导入"功能
涉及:
1. shared-proto 新增 ImportClassesRequest message
2. classes 服务实现 import 接口
3. api-gateway 路由 /api/v1/classes/import
4. teacher-portal 前端上传按钮
```
### 8.2 拆分与合并顺序
| 顺序 | PR | scope | 负责人 | 依赖 |
| ---- | ----------------------------------------------- | -------------- | --------- | ---- |
| 1 | `feat(shared-proto): 新增 ImportClassesRequest` | shared-proto | 协调 AI | 无 |
| 2 | `feat(classes): 实现班级批量导入` | classes | 开发 AI-A | PR-1 |
| 3 | `feat(api-gateway): 新增 import 路由` | api-gateway | 开发 AI-B | PR-2 |
| 4 | `feat(teacher-portal): 新增班级导入按钮` | teacher-portal | 开发 AI-C | PR-3 |
协调 AI 按顺序合并,每合并一个,后续 PR 的开发 AI rebase 最新 main。
### 8.3 Breaking Change 流程
涉及 Breaking Changeproto 字段删除、API 签名变更):
1. **人类决策者审批**:在 issue 中讨论,获批准后才开发
2. **版本号升级**proto 加 `v2` 后缀,服务同时支持 v1/v2 过渡期
3. **迁移文档**:更新 `MIGRATION_GUIDE.md`
4. **协调 AI 通知所有相关 AI**:在 PR 描述中列出影响范围
---
## 9. 完整工作流示例
### 9.1 场景:开发 AI-A 为 classes 新增分页查询
```bash
# ============ 开发 AI-A ============
# 1. 同步 main
git checkout main
git pull origin main
# 2. 创建特性分支
git checkout -b feat/classes-add-pagination-ai01
# 3. 开发
# 编辑 services/classes/src/classes/classes.controller.ts
# 编辑 services/classes/src/classes/classes.service.ts
# 编辑 services/classes/src/classes/classes.repository.ts
# 4. 本地校验
pnpm --filter @edu/classes-service lint
pnpm --filter @edu/classes-service typecheck
pnpm --filter @edu/classes-service test
# 5. 架构扫描(若新增了导出函数/路由)
pnpm run arch:scan
# 6. 提交
git add services/classes/
git commit -m "feat(classes): 新增班级分页查询
- GET /api/v1/classes 支持 page、size 参数
- 响应增加 total、hasMore 字段
- 单测覆盖分页逻辑"
# 7. 推送
git push -u origin feat/classes-add-pagination-ai01
# 8. 创建 PR
gh pr create \
--title "feat(classes): 新增班级分页查询" \
--body "..." \
--base main
# ============ 协调 AI ============
# 9. 收到 PR 通知,审核
gh pr view <PR-NUMBER>
gh pr checks <PR-NUMBER>
# 10. 代码审核(见 §6.2 checklist
# 若需修改,评论要求开发 AI-A 修改
# 11. 合并
gh pr merge <PR-NUMBER> --squash --delete-branch
# 12. 通知开发 AI-A
# 评论:"已合并,请同步本地 main"
# ============ 开发 AI-A ============
# 13. 同步
git checkout main
git pull origin main
git branch -d feat/classes-add-pagination-ai01
```
---
## 10. 常见问题与解决方案
### 10.1 多 AI 修改同一文件冲突
**场景**AI-A 和 AI-B 都修改了 `package.json` 添加依赖。
**解决**
1. AI-A 的 PR 先合并
2. AI-B 执行:
```bash
git fetch origin
git rebase origin/main
# 解决 package.json 冲突(保留两边依赖)
git add package.json
git rebase --continue
git push --force-with-lease
```
3. 协调 AI 重新审核
### 10.2 CI 失败但本地通过
**场景**:开发 AI 本地 lint 通过CI 报错。
**排查**
1. 检查 Node/Go/pnpm 版本是否一致(见 local-dev-runbook §1
2. 检查 `pnpm-lock.yaml` 是否最新(`pnpm install --frozen-lockfile`
3. 检查环境变量是否齐全(`.env` vs CI secrets
**修复后**
```bash
git add <fixed-files>
git commit -m "fix(classes): 修复 CI lint 失败"
git push
```
### 10.3 husky pre-commit hook 失败
**场景**commit 时 hook 报错lint-staged、commitlint
**排查**
1. commitlint检查 commit message 格式type 小写、scope 在 enum 内、subject 不大写开头)
2. lint-staged检查暂存文件是否通过 ESLint/gofmt
3. husky 9 Windows bug若 pre-push hook "Bad file descriptor",见 known-issues
**修复**:修正后重新 `git commit`,不要用 `--no-verify` 跳过。
### 10.4 proto 变更导致下游编译失败
**场景**shared-proto 合并后classes 服务 `buf generate` 报错。
**解决**
1. 协调 AI 合并 proto PR 前,先在 PR 评论中通知所有依赖服务的 AI
2. 下游 AI 在自己的分支 rebase 最新 main 后重新 `buf generate`
3. 更新生成代码并提交:
```bash
git add packages/shared-proto/gen/
git commit -m "chore(shared-proto): 重新生成 TS 类型"
```
### 10.5 分支长期未合并(超 3 天)
**场景**:特性分支超过 3 天未合并。
**处理**
1. rebase 最新 main`git rebase origin/main`
2. 解决冲突后 `git push --force-with-lease`
3. 若仍无法合并,协调 AI 介入评估是否拆分 PR
### 10.6 误推到 main
**场景**:开发 AI 误将 commit 推到 main。
**修复**(协调 AI 执行):
```bash
# 1. 确认误推的 commit
git log origin/main -5
# 2. 回退(保留误推 commit 到临时分支)
git checkout origin/main -b temp/backup-mispush
git checkout main
git reset --hard origin/main~1 # 回退 1 个 commit
# 3. 强推(仅协调 AI 有权限)
git push --force-with-lease origin main
# 4. 通知开发 AI 从 temp 分支重新提 PR
```
> **禁止开发 AI 自行 force push main**。只有协调 AI 有权操作。
### 10.7 AI 身份冲突(同名分支)
**场景**:两个 AI 都叫 "ai01",创建了同名分支。
**预防**:每个 AI 启动前分配唯一 `ai-id`(如 `ai01`、`ai02`、`coord`)。
**修复**:后启动的 AI 重命名分支:
```bash
git branch -m feat/classes-xxx-ai01 feat/classes-xxx-ai01b
git push -u origin feat/classes-xxx-ai01b
```
---
## 11. AI 协作通信约定
### 11.1 通信渠道
| 场景 | 方式 |
| -------- | ----------------------------- |
| PR 审核 | PR 评论(`@ai01 请修改 xxx` |
| 任务分配 | Issue`@ai01 负责实现 xxx` |
| 紧急通知 | PR 评论 + @ 相关人员 |
| 架构讨论 | Issue 标签 `discussion` |
### 11.2 PR 评论规范
协调 AI 审核评论格式:
```
## 审核结果:需修改 / 通过 / 拒绝
### 需修改项
1. [classes.controller.ts:42] 缺少 @RequirePermission() 装饰器
2. [classes.service.ts:88] 返回值未标注 Promise<T>
### 建议
- 考虑抽取分页逻辑到 shared-ts
---
协调 AIcoord
```
### 11.3 AI 工作日志
每个 AI 完成任务后,在 `docs/troubleshooting/known-issues.md` "工作经验日志"区追加project_rules §9.3
```markdown
| 日期 | 模块 | 做了什么 + 学到什么 |
| ---------------- | ------- | ----------------------------------------------- |
| 2026-07-08 14:00 | classes | 实现分页查询,学到 Drizzle 的 limit/offset 用法 |
```
---
## 12. 安全与权限
### 12.1 分支保护规则main
- **禁止直接 push**:必须通过 PR
- **必须 PR review**:至少 1 人CODEOWNERS 自动分配)
- **必须 CI 通过**lint / typecheck / build
- **禁止 force push**:开发 AI 无权,仅协调 AI 在事故时操作
### 12.2 AI 账号权限
| 角色 | push 特性分支 | 创建 PR | 合并 PR | push main | force push main |
| ------- | ------------- | ------- | ----------- | --------- | --------------- |
| 开发 AI | ✅ | ✅ | ❌ | ❌ | ❌ |
| 协调 AI | ✅ | ✅ | ✅ | ❌ | ⚠️(仅事故) |
| SRE AI | ✅infra | ✅ | ✅infra | ❌ | ⚠️(仅事故) |
### 12.3 敏感文件保护
以下文件修改需人类决策者额外审批:
- `.env`、`.env.example`(密钥相关)
- `infra/security/secrets.example.env`
- `infra/k8s/`(生产部署)
- `.github/workflows/`CI 配置)
---
## 13. 发布流程
### 13.1 版本号规则(见 git-workflow.md §7
- 平台版本:`v{阶段}.{迭代}.{patch}`(如 `v1.2.0`
- 服务版本:`{service}:{semver}`(如 `classes:1.0.1`
### 13.2 发布步骤(协调 AI 执行)
```bash
# 1. 确认 main 稳定CI 全绿)
gh run list --branch main --limit 5
# 2. 打 tag
git tag -a v1.2.0 -m "P1 阶段第 2 次迭代发布"
git push origin v1.2.0
# 3. 触发 CI 构建镜像
# CI 由 tag push 触发,见 .github/workflows/
# 4. 人类决策者确认部署到生产
```
### 13.3 回滚(见 git-workflow.md §8
```bash
# K8s 回滚
kubectl rollout undo deployment/api-gateway -n edu-system
# Git 回退(紧急)
git revert <bad-commit>
git push origin main
```
---
## 14. 快速参考卡
### 开发 AI 日常工作流
```bash
# 拉新分支
git checkout main && git pull && git checkout -b feat/<scope>-<task>-<ai-id>
# 开发 → 校验 → 提交
pnpm run lint && pnpm run typecheck
git add . && git commit -m "feat(<scope>): <subject>"
# 推送 → 创建 PR
git push -u origin feat/<scope>-<task>-<ai-id>
gh pr create --title "feat(<scope>): <subject>" --body "..."
# 等待审核 → 修改 → 重新推送
# (协调 AI 合并后)
git checkout main && git pull && git branch -d feat/<scope>-<task>-<ai-id>
```
### 协调 AI 日常工作流
```bash
# 查看待审核 PR
gh pr list --state open --reviewer @edu-platform/arch
# 审核
gh pr view <PR-NUMBER>
gh pr checks <PR-NUMBER>
# 合并
gh pr merge <PR-NUMBER> --squash --delete-branch
# 发布
git tag -a v<version> -m "..." && git push origin v<version>
```
---
## 15. 相关文档
- [Git 工作流](./git-workflow.md) — 提交规范、分支策略、CODEOWNERS
- [本地启动手册](./local-dev-runbook.md) — 手动启动服务
- [项目规则](../../.trae/rules/project_rules.md) — 强制约束
- [004 架构影响地图](../architecture/004_architecture_impact_map.md) — 模块与依赖关系
- [CODEOWNERS](../../.github/CODEOWNERS) — Reviewer 自动分配
- [PR 模板](../../.github/pull_request_template.md) — PR 必填项
- [known-issues](../troubleshooting/known-issues.md) — 已知问题速查

View File

@@ -0,0 +1,137 @@
# CI/CD 设计本地构建部署no-push
> 日期2026-07-08
> 状态:已批准,待实施
> 替代方案:[2026-07-08 之前的 docker.yml + deploy.yml push 方案](../../.github/workflows/)
## 1. 背景
### 1.1 现状问题
- `node-with-docker:22` 自定义镜像已丢失,原方案依赖它无法运行
- 推送到 Gitea Registry 的拉取速度极慢,影响部署效率
- 用户习惯本地构建测试后再推送,无需保留历史构建产物
- 微服务架构下,拆分多个 workflow 文件ci-ts/ci-go/docker/deploy使流程碎片化
### 1.2 目标
- 不依赖任何自建镜像,全部使用官方镜像
- 不推送镜像到 registry构建即部署
- 单文件管理整个 CI/CD 流程
- 支持回滚(不依赖 registry tag
- 提供一次性预拉所有镜像的 compose 文件
## 2. 设计
### 2.1 架构总览
```
PR/push 触发
├─ quality-ts job (container: node:22-alpine) 并行
├─ quality-go job (container: golang:1.22-alpine) 并行
├─ quality-proto job (container: bufbuild/buf:latest) 并行
└─ deploy job (container: docker:25-git) 仅 push main, needs: [quality-*]
挂载 /var/run/docker.sockDooD
├─ docker compose up --build本地构建 3 个服务)
└─ 健康检查轮询
```
### 2.2 文件结构
```
.github/workflows/
└─ ci.yml # 唯一的 CI/CD 文件
infra/
├─ docker-compose.deploy.yml # 改造build: 替代 image:
├─ docker-compose.tools.yml # 新建:预拉所有 CI 需要的镜像
└─ deploy.env.example # 保留
```
### 2.3 ci.yml 设计
**单文件多 job**
- `quality-ts`PR+push 都跑container: node:22-alpinepnpm install → lint → typecheck → test → build
- `quality-go`PR+push 都跑container: golang:1.22-alpinego mod download → vet → build → test
- `quality-proto`PR+push 都跑container: bufbuild/buf:latestbuf lint + buf breaking仅 PR
- `deploy`:仅 push main 或 workflow_dispatch 触发needs: [quality-ts, quality-go, quality-proto]
**deploy job 关键配置**
- `container: docker:25-git`(官方镜像,自带 docker CLI + compose v2 + git
- `options: --volume /var/run/docker.sock:/var/run/docker.sock`DooD 模式)
- 流程checkout → cp compose 文件到 /opt/edu/ → docker compose up --build → 健康检查
**回滚**
- `workflow_dispatch` 支持 `commit_sha` 输入
- checkout 时使用指定 commit SHA
- 重新 build + deploy
### 2.4 docker-compose.deploy.yml 改造
所有服务从 `image:` 改为 `build:`
- `api-gateway``build: ./services/api-gateway`
- `classes``build: { context: ., dockerfile: services/classes/Dockerfile }`monorepo 上下文)
- `teacher-portal``build: { context: ., dockerfile: apps/teacher-portal/Dockerfile }`monorepo 上下文)
删除 `IMAGE_TAG` 环境变量依赖。`docker compose up --build` 自动判断变更的服务。
### 2.5 docker-compose.tools.yml预拉镜像
用于一次性拉取所有 CI/构建需要的镜像到本地:
- CI 运行时node:22-alpine、golang:1.22-alpine、bufbuild/buf:latest、docker:25-git
- 服务构建基础node:20-alpine、golang:1.22-alpine、alpine:3.20
- 开发基础设施mysql:8.0、redis:7-alpine
用法:`docker compose -f infra/docker-compose.tools.yml pull`
### 2.6 回滚策略
| 方式 | 操作 | 适用场景 |
| ---------- | --------------------------------------------------- | ---------------- |
| git revert | `git revert <bad-commit> && git push` → 自动触发 CI | 代码回滚(推荐) |
| 手动触发 | Actions → ci.yml → Run workflow → 填 commit_sha | 部署特定版本 |
### 2.7 actrunner 配置
```toml
container:
valid_volumes:
- /var/run/docker.sock
```
## 3. 实施步骤
1. 删除现有 4 个 workflow 文件ci-ts.yml、ci-go.yml、ci-proto.yml、docker.yml、deploy.yml
2. 创建 `.github/workflows/ci.yml`(合并单 workflow
3. 改造 `infra/docker-compose.deploy.yml`build 替代 image
4. 创建 `infra/docker-compose.tools.yml`(预拉镜像)
5. 更新 `.trae/rules/project_rules.md` §15no-push 模式规范)
6. 更新 `docs/standards/cicd-runbook.md`(删除 registry 章节,新增本地构建章节)
7. 提交并推送
## 4. 与旧方案对比
| 维度 | 旧方案push 到 registry | 新方案no-push 本地构建) |
| --------------- | -------------------------- | ------------------------------ |
| workflow 文件数 | 4 个 | 1 个 |
| 镜像推送 | push 到 Gitea Registry | 不推送 |
| 部署方式 | compose pull + up | compose up --build |
| 自建镜像 | 依赖 node-with-docker:22 | 全用官方镜像 |
| 回滚 | 切换 registry tag | git revert / workflow_dispatch |
| 构建产物保留 | registry 保留历史 | 不保留 |
## 5. 风险与缓解
| 风险 | 缓解 |
| ------------------------- | ---------------------------------------------- |
| 本地镜像被清理后无法回滚 | 回滚走 git revert + 重新 build不依赖镜像缓存 |
| docker.sock 挂载安全风险 | actrunner 仅在部署服务器运行,已隔离 |
| 构建慢 | layer cache 在宿主机本地,未变更的层秒过 |
| Gitea workflow_run 不支持 | 用 needs 串联,不用 workflow_run |

View File

@@ -10,30 +10,37 @@
### 1.1 多语言 monorepo 配置
| 场景 | 技术/规则 |
| ------------------------ | ------------------------------------------------------------------------------------------ |
| 多语言 workspace | pnpm workspaceTS+ go.workGo+ pyproject.toml/uv workspacePython三套并存 |
| 根 package.json scripts | 封装多语言命令入口:`pnpm dev` / `pnpm lint` / `pnpm test` / `pnpm build` |
| pnpm-workspace.yaml | 仅声明 TS 包路径packages/_、services/classes、bff/_、apps/_、scripts/_Go/Python 不入 |
| go.work | 列出所有 Go 服务模块services/api-gateway、services/push-gateway |
| pyproject.toml | uv workspace members 列 Python 服务services/data-ana、services/ai-gateway |
| 跨语言共享类型 | protobuf 生成三端代码TS/Go/Python单一契约源 |
| tsx 执行 TS 脚本 | arch-scan 等工具脚本用 `tsx` 直接运行,无需编译 |
| husky + commitlint | pre-commit 跑 eslint+prettiercommit-msg 校验 Conventional Commits |
| .editorconfig 多语言缩进 | Go 用 tabPython 用 4 空格TS/默认用 2 空格 |
| 场景 | 技术/规则 |
| ------------------------ | ------------------------------------------------------------------------------------------------------------- |
| 多语言 workspace | pnpm workspaceTS+ go.workGo+ pyproject.toml/uv workspacePython三套并存 |
| 根 package.json scripts | 封装多语言命令入口:`pnpm dev` / `pnpm lint` / `pnpm test` / `pnpm build` |
| pnpm-workspace.yaml | 仅声明 TS 包路径packages/_、services/classes、bff/_、apps/_、scripts/_Go/Python 不入 |
| go.work | 列出所有 Go 服务模块services/api-gateway、services/push-gateway |
| pyproject.toml | uv workspace members 列 Python 服务services/data-ana、services/ai-gateway |
| 跨语言共享类型 | protobuf 生成三端代码TS/Go/Python单一契约源 |
| tsx 执行 TS 脚本 | arch-scan 等工具脚本用 `tsx` 直接运行,无需编译 |
| husky + commitlint | pre-commit 跑 eslint+prettiercommit-msg 校验 Conventional Commits |
| .editorconfig 多语言缩进 | Go 用 tabPython 用 4 空格TS/默认用 2 空格 |
| ESLint 9 flat config | P6 硬化:创建 `eslint.config.js`flat configlint 脚本去掉 `--ext .ts`lint-staged 恢复 `eslint --fix` |
| next lint 交互式初始化 | teacher-portal 无 `.eslintrc.json``next lint` 触发 Strict/Base 选择提示CI 中需预置配置或改 `eslint src` |
### 1.2 Docker Compose 基础设施
| 场景 | 技术/规则 |
| ---------------- | ----------------------------------------------------------------------------------------------- |
| 日常开发启动 | 用 `docker-compose.minimal.yml` 仅起 MySQL+Redis |
| 全量启动内存不足 | 按 `profiles` 分阶段启用full/kafka/cdc/analytics/graph/search/config/observability |
| 每服务 mem_limit | 避免单服务吃满内存MySQL 512m、Redis 128m、Kafka 512m、ClickHouse 1g |
| 按阶段启用容器 | P1 仅 MySQL+RedisP3 加 Kafka+ZookeeperP4 加 Debezium+CH+Neo4jP5 加 ESP6 加 Consul+Istio |
| MySQL 初始化 | `init-sql/01-init.sql` 挂载到 `/docker-entrypoint-initdb.d:ro` |
| healthcheck | MySQL 用 `mysqladmin ping`Redis 用 `redis-cli ping` |
| Windows 下卷挂载 | init-sql 用绝对路径或确保相对路径正确 |
| 容器名固定 | `container_name: edu-mysql` 便于服务连接配置 |
| 场景 | 技术/规则 |
| ------------------------- | ----------------------------------------------------------------------------------------------------------------------- |
| 日常开发启动 | 用 `docker-compose.minimal.yml` 仅起 MySQL+Redis |
| 全量启动内存不足 | 按 `profiles` 分阶段启用full/kafka/cdc/analytics/graph/search/config/observability |
| 每服务 mem_limit | 避免单服务吃满内存MySQL 512m、Redis 128m、Kafka 512m、ClickHouse 1g |
| 按阶段启用容器 | P1 仅 MySQL+RedisP3 加 Kafka+ZookeeperP4 加 Debezium+CH+Neo4jP5 加 ESP6 加 Consul+Istio |
| MySQL 初始化 | `init-sql/01-init.sql` 挂载到 `/docker-entrypoint-initdb.d:ro` |
| healthcheck | MySQL 用 `mysqladmin ping`Redis 用 `redis-cli ping` |
| Windows 下卷挂载 | init-sql 用绝对路径或确保相对路径正确 |
| 容器名固定 | `container_name: edu-mysql` 便于服务连接配置 |
| Kafka 双 listener | INSIDE (kafka:29092) 容器间互访 + OUTSIDE (localhost:9092) 主机访问,避免 Debezium 拿到 localhost metadata 后切回连不上 |
| ClickHouse 远程访问 | 默认 default-user.xml 限制 127.0.0.1/::1 无密码,挂载 `clickhouse/users.d/custom-users.xml` 覆盖密码+任意 IP |
| Debezium Connect 镜像源 | daocloud 禁用 debezium/*,用 `quay.io/debezium/connect:2.7` 替代 |
| Debezium 跨网络访问 MySQL | MySQL 容器在 edu-minimal_default 时,`docker network connect edu-full_default edu-mysql` 让 Debezium 同时可达 |
| CDC 注册 connector | POST `:8083/connectors`,配置 `topic.prefix`/`database.include.list`/`schema.history.internal.kafka.topic` |
### 1.3 protobuf + buf 契约
@@ -84,15 +91,26 @@
### 1.6 可观测性OTel + Prometheus + Loki
| 场景 | 技术/规则 |
| --------------- | -------------------------------------------------------------------------------- |
| P1 最小可观测集 | 每服务结构化日志 + `/metrics` + OTel SDK 初始化(不引入完整后端) |
| 三支柱 | Logspino/winston/zap+ Metricsprom-client+ TracesOTel SDK |
| traceId 注入 | Gateway 注入 → 服务读取 header → 日志/响应携带 |
| P6 完整后端 | Loki日志+ Grafana仪表盘+ Jaegertrace+ Prometheusmetrics |
| Prometheus 指标 | `http_request_duration_seconds`Histogram+ `http_requests_total`Counter |
| 采样策略 | P1 全量 traceP6 引入采样率降低开销 |
| 日志参数顺序 | `log.error({ err: error, userId, traceId }, "操作描述")`,错误对象字段名用 `err` |
| 场景 | 技术/规则 |
| ----------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| P1 最小可观测集 | 每服务结构化日志 + `/metrics` + OTel SDK 初始化(不引入完整后端) |
| 三支柱 | Logspino/winston/zap+ Metricsprom-client+ TracesOTel SDK |
| traceId 注入 | Gateway 注入 → 服务读取 header → 日志/响应携带 |
| P6 完整后端 | Loki日志+ Grafana仪表盘+ Jaegertrace+ Prometheusmetrics |
| Prometheus 指标 | `http_request_duration_seconds`Histogram+ `http_requests_total`Counter |
| 采样策略 | P1 全量 traceP6 引入采样率降低开销 |
| 日志参数顺序 | `log.error({ err: error, userId, traceId }, "操作描述")`,错误对象字段名用 `err` |
| P6 /metrics 端点 | NestJS 用 `app.getHttpAdapter().get('/metrics', handler)`,不能用 `app.get()`(会被解析为 DI 容器 get |
| P6 prometheus.yml | 8 个应用服务 + MySQL/Redis + node-exporter + prometheus 自身rule_files 引用 rules.ymlalerting 关联 alertmanager |
| P6 Grafana 数据源 | provisioning/datasources 同时声明 Prometheus默认和 Lokiuid=loki |
| P6 Promtail 采集 | docker_sd_configs + relabel_configs 仅采集 `edu-*` 前缀容器日志,避免无关日志 |
| P6 service label | static_configs.labels.service 给所有抓取目标打服务标签,告警规则按 service 聚合 |
| P6 collectDefaultMetrics | prom-client 的 `collectDefaultMetrics({ register })` 自动收集进程级指标CPU/内存/事件循环/GC无需业务埋点即可让 /metrics 有数据 |
| P6 Counter/Histogram 埋点缺失 | metrics.ts 定义了 Counter/Histogram 但 service/controller 未调用 `.inc()`/`.observe()`,需后续补 HTTP 中间件自动埋点或业务埋点 |
| P6 OTel instrumentations 缺失 | tracer.ts 只配置 traceExporter 未注册 auto-instrumentationsHttpInstrumentation/ExpressInstrumentation导致 Jaeger 收不到业务 trace需后续补 `@opentelemetry/auto-instrumentations`。**已补全**NestJS 6 服务用 `getNodeAutoInstrumentations()`Python 2 服务用 `FastAPIInstrumentor.instrument_app(app)`Go 2 服务用 `otelgin.Middleware()` |
| P6 镜像源配置 | 国内 docker.io 被墙compose image 必须加 `docker.m.daocloud.io/` 前缀Elastic 官方镜像在 docker.elastic.co 不被墙 |
| P6 Grafana 端口冲突 | Grafana 默认 3000 与 teacher-portal Next.js dev 冲突,改映射为 3030:3000 |
| P6 compose --no-deps | mysql/redis 已在另一 compose 项目运行时,启动新服务用 `--no-deps` + 显式指定服务名,避免重建依赖容器 | |
### 1.7 微前端 Module Federation
@@ -151,16 +169,21 @@
### 2.1 api-gatewayGo
| 场景 | 技术/规则 |
| -------------- | ------------------------------------------------------------------------------- |
| P1 鉴权 | Gateway 内置 HS256 JWT`jwt.ParseWithClaims` + `SigningMethodHMAC` 校验 |
| P2 鉴权升级 | 改 RS256IAM 私钥签发Gateway 公钥校验,无需调 IAM |
| 路由转发 | `gin.Group("/api/v1")` + `httputil.NewSingleHostReverseProxy` |
| 路径重写 | 去掉 `/api/v1` 前缀后转发到下游服务 |
| 用户上下文注入 | `c.Request.Header.Set("x-user-id", claims.UserID)` 传递给下游 |
| 请求 ID | Gateway 生成或透传 `X-Request-ID``c.Set("request_id", ...)` + `c.Header(...)` |
| P1 不做 | 限流/熔断/灰度P6 硬化阶段实现) |
| 健康检查 | `GET /health` 无需鉴权 |
| 场景 | 技术/规则 |
| ----------------- | ------------------------------------------------------------------------------------------------------------- |
| P1 鉴权 | Gateway 内置 HS256 JWT`jwt.ParseWithClaims` + `SigningMethodHMAC` 校验 |
| P2 鉴权升级 | 改 RS256IAM 私钥签发Gateway 公钥校验,无需调 IAM |
| 路由转发 | `gin.Group("/api/v1")` + `httputil.NewSingleHostReverseProxy` |
| 路径重写 | 去掉 `/api/v1` 前缀后转发到下游服务 |
| 用户上下文注入 | `c.Request.Header.Set("x-user-id", claims.UserID)` 传递给下游 |
| 请求 ID | Gateway 生成或透传 `X-Request-ID``c.Set("request_id", ...)` + `c.Header(...)` |
| P1 不做 | 限流/熔断/灰度P6 硬化阶段实现) |
| 健康检查 | `GET /health` 无需鉴权 |
| 尾斜杠重定向循环 | `r.RedirectTrailingSlash=false` + 同时注册 `Any("/classes")` 与 `Any("/classes/*path")` |
| 开发模式鉴权旁路 | `DEV_MODE=true` 时接受 `Bearer dev-token`,注入固定身份;生产必须 `false` |
| 路由注册位置 | 真实路由在 `main.go` 的 `api.Group` 内注册,`internal/routing/routing.go` 若未被 main 引用即为死代码 |
| 多服务路由扩展 | 新增服务代理时在 main.go 注册两组路由:`Any("/x")` + `Any("/x/*path")`,与 classes 一致 |
| DEV_MODE 环境变量 | Go 不自动加载 .env`DEV_MODE` 必须在启动前 export 或写入系统环境变量,否则 DevMode=false 导致 dev-token 被拒 |
### 2.2 classesTS/NestJSP1 黄金模板)
@@ -183,76 +206,106 @@
### 2.3 iamTS/NestJSP2
| 场景 | 技术/规则 |
| -------------- | ------------------------------------------------------------------------------------------------------------------- |
| 认证 | 登录/登出/JWT/2FARS256 非对称签名 |
| RBAC | 角色/权限/角色-权限 CRUD + `getEffectivePermissions(userId)` API |
| 视口配置 | 4 层模型(导航/路由/组件/数据),`role_viewports` 表 |
| DataScope 解析 | 6 级数据范围,注入 JWT payload |
| JWT payload | `{ userId, roles, permissions(bitmap), dataScope, exp }` |
| Token TTL | access 15min / refresh 7dayrefresh 用 Redis 黑名单失效 |
| 权限缓存 | `getEffectivePermissions` 结果 Redis 缓存 TTL 5 分钟,角色变更主动失效 |
| schema 表 | users / roles / permissions / role_permissions / role_viewports / parent_student_relations / class_subject_teachers |
| 场景 | 技术/规则 |
| ----------------- | ------------------------------------------------------------------------------------------------------------------------ |
| 认证 | 登录/登出/JWT/2FARS256 非对称签名 |
| RBAC | 角色/权限/角色-权限 CRUD + `getEffectivePermissions(userId)` API |
| 视口配置 | 4 层模型(导航/路由/组件/数据),`role_viewports` 表 |
| DataScope 解析 | 6 级数据范围,注入 JWT payload |
| JWT payload | `{ userId, roles, permissions(bitmap), dataScope, exp }` |
| Token TTL | access 15min / refresh 7dayrefresh 用 Redis 黑名单失效 |
| 权限缓存 | `getEffectivePermissions` 结果 Redis 缓存 TTL 5 分钟,角色变更主动失效 |
| schema 表 | users / roles / permissions / role_permissions / role_viewports / parent_student_relations / class_subject_teachers |
| ESM 模式 DI | `providers: [IamService, IamRepository]` + 构造器 `@Inject(IamRepository)` 显式注入,避免 `undefined` 运行时错误 |
| Drizzle ORM API | `inArray(col, vals)` 替代不存在的 `.in()`select 返回字段名按 schema 定义(如 `r.iam_roles` 而非 `r.roles` |
| 健康检查依赖 | `readyz` 用 `db.execute(sql\`SELECT 1\`)` 校验连接,不要依赖 typeorm DataSourceIAM 用 Drizzle无 typeorm |
| Gateway 身份传递 | Controller 直接读 `req.headers['x-user-id']` / `x-user-roles`,不要依赖未注册的 AuthMiddleware 的 `AuthenticatedRequest` |
| DEV_MODE 登录 | DEV_MODE=true 时 Gateway 接受 `Bearer dev-token` 注入固定身份IAM 仍支持真实 JWTHS256P2 应改 RS256 |
| P2 公开路径白名单 | Gateway `publicPaths` map 含 `/iam/register`/`/iam/login`/`/iam/refresh`AuthMiddleware 跳过鉴权避免死锁 |
| P2 视口过滤 | `getUserViewports` 按 `requiredPermission` 过滤 + `sortOrder` 字典序排序,无权限要求的视口全员可见 |
| P2 JWT payload | HS256 签名含 `sub/email/roles/dataScope/type`register 自动分配 teacher 角色TEACHER_ROLE_ID 固定 UUID |
### 2.4 core-eduTS/NestJSP3
| 场景 | 技术/规则 |
| -------------- | ----------------------------------------------------------------------------------------------------------------------- |
| 考试全生命周期 | 教师创建 → 发布 → 学生作答 → 教师批改 → 成绩统计 |
| Outbox 模式 | 业务事务同写 `outbox_events` 表,后台 relay worker 投递 Kafka |
| Outbox relay | Go 写独立服务 `services/outbox-relay/`,轻量高吞吐 |
| Kafka topic | `exam.published` / `homework.graded` / `grade.recorded` |
| 不引入 Saga | 跨服务一致性用 Outbox + 最终一致性 |
| 批改后联动 | 批改完成 → 发 `homework.graded` 事件 → 下游消费DataAna/Msg |
| Temporal 试点 | 仅 1 个工作流(考试发布编排:创建作业→通知) |
| schema 表 | exams / exam_questions / homework_assignments / homework_submissions / homework_answers / grade_records / outbox_events |
| 场景 | 技术/规则 |
| -------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
| 考试全生命周期 | 教师创建 → 发布 → 学生作答 → 教师批改 → 成绩统计 |
| Outbox 模式 | 业务事务同写 `outbox_events` 表,后台 relay worker 投递 Kafka |
| Outbox relay | Go 写独立服务 `services/outbox-relay/`,轻量高吞吐 |
| Kafka topic | `exam.published` / `homework.graded` / `grade.recorded` |
| 不引入 Saga | 跨服务一致性用 Outbox + 最终一致性 |
| 批改后联动 | 批改完成 → 发 `homework.graded` 事件 → 下游消费DataAna/Msg |
| Temporal 试点 | 仅 1 个工作流(考试发布编排:创建作业→通知) |
| schema 表 | exams / exam_questions / homework_assignments / homework_submissions / homework_answers / grade_records / outbox_events |
| datetime 列 | Drizzle `datetime` 列需 Date 对象HTTP 请求体里是 ISO 字符串service 层必须 `new Date(input)` 转换否则报 `toISOString is not a function` |
| Kafka 非阻塞 | 开发环境 Kafka 未启动时 `connectKafka()` 必须 try/catch 且 main 中用 `void` 调用,否则阻塞服务启动 |
| 相对 import | `src/<domain>/` 下文件回溯一级用 `../`,不要用 `../../`NestJS ESM 模块) |
| 身份头读取 | Controller 用 `@Req() req` 从 `req.headers['x-user-id']` 读 createdBy/gradedBy不依赖未注册的 AuthMiddleware |
| 健康检查 | health.controller 用 Drizzle `db.execute(sql\`SELECT 1\`)`,不用 typeorm DataSource |
| Outbox 验证 | 业务事务同写 `core_edu_outbox` 表Kafka 未启动时事件 status=failed启动后会重试 |
### 2.5 contentTS/NestJSP4
| 场景 | 技术/规则 |
| ---------- | ------------------------------------------------------------------ |
| 知识图谱 | Neo4j 查询前置依赖图(秒级返回) |
| 题库 CRUD | P4 仅 CRUDP5 引入 ES 实现检索,避免 MySQL FULLTEXT → ES 迁移成本 |
| 双写避免 | Neo4j/ES 不直接双写,由消费 Kafka 事件同步,天然最终一致 |
| Neo4j 写入 | Content 服务写 MySQL 同时发事件,独立 worker 消费事件同步 Neo4j |
| 场景 | 技术/规则 |
| -------------- | ------------------------------------------------------------------------------- |
| 知识图谱 | Neo4j 查询前置依赖图(秒级返回) |
| 题库 CRUD | P4 仅 CRUDP5 引入 ES 实现检索,避免 MySQL FULLTEXT → ES 迁移成本 |
| 双写避免 | Neo4j/ES 不直接双写,由消费 Kafka 事件同步,天然最终一致 |
| Neo4j 写入 | Content 服务写 MySQL 同时发事件,独立 worker 消费事件同步 Neo4j |
| API 字段名 | 请求体用 TS schema 字段名(如 `order`),非 DB 列名(如 `order_num` |
| Neo4j 不可用 | 未设置 NEO4J_URL 时 driver=nullgetNeo4jSession 返回 null业务正常落库 MySQL |
| Neo4j 连接超时 | driver 配置 connectionTimeout:3000避免 Neo4j 不可用时拖慢 HTTP 响应 |
| Drizzle int | drizzle-orm/mysql-core 导出 `int()` 不是 `integer()` |
| db 常量导出 | database.ts 导出 `db` 常量替代 `getDb()` 函数,与 core-edu/classes 黄金模板对齐 |
### 2.6 data-anaPython/FastAPIP4
| 场景 | 技术/规则 |
| ------------ | ------------------------------------------------------------------------------ |
| 学情诊断 | ClickHouse 宽表查询5s 内返回 |
| CDC 链路 | Debezium 监听 MySQL binlog → Kafka`mysql.cdc.*`)→ DataAna 消费写 ClickHouse |
| CDC 延迟监控 | Debezium 暴露 lag metrics超阈值告警 |
| 双轨读策略 | 实时查 MySQL 主库(刚提交的成绩),聚合查 CH 宽表(延迟 1-5s 可接受) |
| 幂等消费 | 所有事件消费者必须幂等(基于 event_id 去重) |
| 场景 | 技术/规则 |
| -------------------- | ------------------------------------------------------------------------------------------------------------------- |
| 学情诊断 | ClickHouse 宽表查询5s 内返回 |
| CDC 链路 | Debezium 监听 MySQL binlog → Kafka`edu-cdc.next_edu_cloud.<table>`)→ DataAna 消费写 ClickHouse |
| CDC 延迟监控 | Debezium 暴露 lag metrics超阈值告警 |
| 双轨读策略 | 实时查 MySQL 主库(刚提交的成绩),聚合查 CH 宽表(延迟 1-5s 可接受) |
| 幂等消费 | 所有事件消费者必须幂等(基于 event_id 去重) |
| CDC 消费者实现 | `cdc_consumer.py` 用 aiokafka AIOKafkaConsumerlifespan 启动 asyncio.create_task 后台运行 |
| ClickHouse 写入 | `clickhouse_client.upsert_student_dashboard()` 用 client.insert() 写宽表client 为 None 时降级返回 False |
| Debezium 事件解析 | `before/after/source/op/ts_ms` 五字段op=r(快照)/c(新增)/u(更新)/d(删除) |
| 多表关联缓存 | 内存 ExamCache 缓存 exam_id→class_id 映射(来自 core_edu_exams CDC 事件grades 事件触发时查缓存填充宽表 class_id |
| Consumer offset 重置 | `kafka-consumer-groups --reset-offsets --to-earliest --execute` 需先停消费者让 group 处于 Empty 状态 |
| structlog API | 24.x 用 `make_filtering_bound_logger(level)`,旧版 `make_filtering_logger` 已废弃 |
### 2.7 messagingTS/NestJSP5
| 场景 | 技术/规则 |
| -------------- | -------------------------------------------------------------------- |
| 消息 CRUD | 会话/消息 + 调 Push Gateway 推送 + 通知偏好 |
| 通知批量化 | `createNotifications(items)` 单次 INSERT沿用旧项目 dispatcher 模式 |
| 多渠道 | 站内/SMS/邮件/微信in_app 批量 + 其他渠道并行 |
| fan-out 分页 | `getAllUserIds(limit=1000, offset)` 分页遍历 |
| 撤回不乐观更新 | 需服务端返回判断 2 分钟窗口 |
| 场景 | 技术/规则 |
| ------------- | ------------------------------------------------------------------ |
| 消息 CRUD | 会话/消息 + 调 Push Gateway 推送 + 通知偏好 |
| 通知批量化 | `createBatch(items)` 单次 INSERT沿用旧项目 dispatcher 模式 |
| 多渠道 | 站内/SMS/邮件/微信in_app 批量 + 其他渠道并行 |
| fan-out 分页 | `listByUserWithPagination(userId, page, pageSize)` 分页查询 |
| ES 降级 | ES_URL 未设置时 esClient=nullsafeIndex/safeSearch 跳过返回空结果 |
| Push 推送降级 | PUSH_GATEWAY_URL 未设置或连接失败时 try/catch 跳过,不影响 DB 写入 |
| db 常量导出 | database.ts 导出 `db` 常量替代 `getDb()` 函数 |
### 2.8 push-gatewayGoP5
| 场景 | 技术/规则 |
| ---------------- | ----------------------------------------------- |
| WebSocket 长连接 | 单节点支撑 10w+ 连接,业务服务只需发 Kafka 消息 |
| 跨实例同步 | Redis PubSub |
| 离线消息 | 仅推在线用户,离线消息存 MySQL上线时拉取 |
| 场景 | 技术/规则 |
| ---------------- | ---------------------------------------------------------------- |
| WebSocket 长连接 | 单节点支撑 10w+ 连接,业务服务只需调 /internal/push |
| 跨实例同步 | Redis PubSubRedisURL 配置,预留 P6 实现) |
| 离线消息 | 仅推在线用户,离线消息存 MySQL上线时拉取 |
| 并发写修复 | send chan + 单写协程模式,避免 gorilla/websocket 并发写竞争 |
| DEV_MODE 鉴权 | DEV_MODE=true 时接受 dev-token生产环境必须 JWT 校验 |
| 广播端点 | POST /internal/broadcastbody {event, data},调用 hub.Broadcast |
### 2.9 ai-gatewayPython/FastAPIP5
| 场景 | 技术/规则 |
| ----------------- | ------------------------------------------- |
| LLM Provider 适配 | OpenAI/Anthropiclangchain/litellm 生态 |
| Prompt 模板管理 | 版本管理友好 |
| 流式 SSE | AI 网关 → BFF → 前端三层透传BFF 不缓冲 |
| 用量计费 | 按 token 计费 |
| AI 模块纯服务端 | Zod 验证 + 失败降级返回空(沿用旧项目模式) |
| 场景 | 技术/规则 |
| ----------------- | --------------------------------------------------------------- |
| LLM Provider 适配 | OpenAI 兼容 REST APIhttpx 异步),不引入 openai SDK |
| 降级模式 | API key 为空或调用失败时返回骨架响应,标记 degraded: true |
| 流式 SSE | AI 网关 → BFF → 前端三层透传BFF 不缓冲 |
| 路由前缀 | 业务路由加 /ai 前缀APIRouter prefix="/ai"Gateway 代理 /ai |
| dev_mode tracer | dev_mode=true 时跳过 OTel exporter 初始化 |
### 2.10 shared-proto契约包
@@ -277,12 +330,17 @@
### 2.12 teacher-portal微前端宿主P1 测试页)
| 场景 | 技术/规则 |
| -------------------- | ------------------------------------------------------------------------- |
| P1 测试页 | 单一 Next.js 应用,验证 classes CRUD 端到端链路 |
| API 调用 | `fetch(${API_BASE}/api/v1/classes)` + `Authorization: Bearer ${TEST_JWT}` |
| P1 测试 JWT | 开发工具生成 HS256 tokenP2 起由 IAM 签发 RS256 |
| P2 Module Federation | next.config.js 配置,按场景域分 4 个稳定 portal |
| 场景 | 技术/规则 |
| -------------------- | --------------------------------------------------------------------------------------- |
| P1 测试页 | 单一 Next.js 应用,验证 classes CRUD 端到端链路 |
| API 调用 | `fetch(${API_BASE}/api/v1/classes)` + `Authorization: Bearer ${TEST_JWT}` |
| P1 测试 JWT | 开发工具生成 HS256 tokenP2 起由 IAM 签发 RS256 |
| P2 Module Federation | next.config.js 配置,按场景域分 4 个稳定 portal |
| P2 路由组 + AppShell | `app/(app)/layout.tsx` 用 AppShell 包裹受保护页;`/login` 与 `/` 不套壳 |
| P2 真实 JWT | 登录后 token 存 localStorage`authHeaders()` 读 `Bearer ${getToken()}` |
| P2 视口驱动侧边栏 | AppShell fetch `/teacher/viewports` 渲染左侧导航active 路由高亮 |
| P2 根路径重定向 | `app/page.tsx` 客户端组件 `router.replace(isAuthenticated() ? '/dashboard' : '/login')` |
| fetch headers 类型 | `authHeaders(): Record<string, string>` 显式标注,避免 `{}` 与 `HeadersInit` 不兼容 |
---
@@ -290,15 +348,26 @@
> 按时间倒序50 条上限。AI 发现更好方案时可更新本节。
| 日期 | 时间 | 模块 | 做了什么 + 学到什么 |
| ---------- | ---- | ----------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 2026-07-08 | 全天 | 全局 | **P6 后续工作手册执行**:完整执行 post-p6-followup.md 12 节任务。环境准备pnpm 925 包 + go mod tidy 双服务 + uv sync 双服务 + buf 安装)→ 代码质量校验Go vet/build 0 错误Python ruff 8 错误自动修复)→ arch.db 同步(实现 4 个扫描器骨架,输出 12 模块/233 符号/138 契约)→ project_rules.md P0 修复(迁移到 .trae/rules/17881 字节)→ 004 架构图修复1.1a/1.1b 双图 + 1.2 业务领域列 + 5.4 视口四层)→ P6 集成测试10 Go + 17 bash = 27 用例全通过)→ Helm Chart 演化8 chart lint 通过)。**学到**:多语言 monorepo 工具链配置需统一镜像源npmmirror/goproxy.cn/tunago.work BOM 字符会导致 `unexpected input character` 错误必须重写文件。 |
| 2026-07-08 | 午 | 全局 | pnpm install 网络失败ECONNRESET→ 配置 `npm config set registry https://registry.npmmirror.com` + `pnpm config set registry https://registry.npmmirror.com` 重试成功。**学到**Windows 下 pnpm 还需配置 `PNPM_HOME` 和 `TMP` 环境变量避免 `_tmp_` 文件 ENOENT 错误。 |
| 2026-07-08 | 午 | 全局 | project_rules.md 损坏72 字节乱码,从 P1 提交 2ba4250 就损坏git 历史无完整版本)→ 从 CICD 项目完整版迁移到 `e:\Desktop\Edu\.trae\rules\project_rules.md`(按用户要求放 .trae/rules/),按 MIGRATION_GUIDE 4.1 策略矩阵调整为微服务版13 章 17881 字节),删除根目录损坏文件,更新 7 处引用README/MIGRATION_GUIDE/004/known-issues/git-workflow/coding-standards。**学到**:迁移文件后必须 `Get-Item | Select Length` 验证完整性 + 全文搜索引用更新git commit 前运行 cat 检查内容。 |
| 2026-07-08 | 午 | api-gateway | go.work BOM 字符 + 版本不匹配:`unexpected input character '\ufeff'` 和 `module requires go >= 1.22.0, but go.work lists go 1.22`。**修复**:重写 go.work 去除 BOM版本改为 `go 1.26.0`,移除不存在的 `./packages/shared-go`。**学到**PowerShell `Out-File` 默认加 BOM写 go.work 这类敏感文件应用 `Write` 工具或 `[System.IO.File]::WriteAllText` 指定 UTF8 无 BOM。 |
| 2026-07-08 | 午 | arch-scan | arch:scan 返回 0 模块 0 符号 → 4 个扫描器ts/go/py/proto都是骨架实现。**修复**:完整实现 4 个扫描器TS 用 regex 提取(避免 ts-morph 对未安装依赖文件解析失败Go/Python 用行首锚定正则Proto 扫描 service/message/rpc。结果12 模块≥10 ✓、233 符号≥100 ✓、138 契约。**学到**ts-morph Project 对未 `pnpm install` 的 workspace 文件会报模块解析失败,改用 regex 更鲁棒scanner.ts main() 开头需 `DELETE FROM` 清空旧数据避免重跑重复。 |
| 2026-07-08 | 午 | 004 | 架构图视角讨论(技术分层 vs 业务领域)→ 双图并存方案1.1a 技术分层视角(部署/流量/网络边界Users 层标注"场景域用户"BFF 层标注"按场景域分"+ 1.1b 业务领域视角6 DDD 限界上下文 subgraphD1 身份/D2 教学组织/D3 教学核心/D4 内容/D5 沟通/D6 智能洞察。1.2 服务清单新增"业务领域"列。**学到**双图互补1.1a 服务运维/SRE 视角1.1b 服务产品/架构视角同一服务可横跨多领域core-edu 同时承载 D2+D3 |
| 2026-07-08 | 下午 | 004 | 视口四层模型补充5.4 章节L1 导航navigation_config 表)/ L2 路由route_permission + Gateway 校验)/ L3 组件usePermission().hasPermission/ L4 数据DataScope 枚举)。场景域 BFF 复用策略:按使用场景域分 BFF 而非按角色分,教导主任复用 Teacher BFF + 额外管理视口。iam 服务职责:认证 + RBAC + 视口配置 + DataScope + 权限解析 API。**学到**视口既可独立配置RoleViewport 表)也可由权限推导,新角色只需配权限集,视口自动推导。 |
| 2026-07-08 | 午 | api-gateway | P6 集成测试补充circuit-breaker_test.go5 用例ClosedToOpen/OpenToHalfOpen/HalfOpenToClosed/HalfOpenToOpen/4xxNotCounted+ ratelimit_test.go5 用例AllowUnderBurst/RejectOverBurst/RefillTokens/PerIPIsolation/CleanupExpiredBuckets+ test-backup-mysql.sh8 用例 17 断言)。**学到**gobreaker v2 ReadyToTrip 在 1 次失败后就触发(`TotalFailures*2 > Requests` 当 Requests=1 时 1*2>1=trueHALF_OPEN 状态只在探测执行期间可见,探测完成后立即转 CLOSED 或回 OPEN测试需通过行为503 vs 500而非状态字段验证rateLimiter cleanup 测试需用短周期参数50ms/500ms加速且新鲜桶要在旧桶清理后再创建避免被一起清掉。 |
| 2026-07-08 | 下午 | infra/k8s | Helm Chart 演化:安装 Helm v4.2.2,创建 edu-platform 平台级 chartnamespace/configmap/secret/ingress/hpa + 4 环境 values 文件)+ api-gateway 服务级 chart完整迁移自原 deployment.yaml参数化所有字段+ 6 业务服务 chart 桩iam/core-edu/content/msg/data-ana/ai。删除原 api-gateway-deployment.yaml保留 namespace.yaml。**学到**Helm `{{- with ... -}}` 双向修剪会导致标签连在一行(`managed-by: Helmpart-of: edu-platform`),应改为 `{{- with ... }}` 只修剪左侧;`helm lint` 全部通过但 `helm template` 才能发现 YAML 渲染错误,验证时两个都要跑。 |
| 2026-07-07 | 全天 | 全局 | 文档体系初始化从旧项目e:\Desktop\CICDNext.js 单体)迁移 spec + plan + known-issues 模板到新仓库e:\Desktop\Edu微服务架构。known-issues 重组为微服务分区:多语言 monorepo / Docker Compose / protobuf+buf / NestJS / Go Gateway / 可观测性 / 微前端。从旧项目提炼可迁移经验React 19 useOptimistic / Zustand 细粒度选择器 / Tiptap SSR / 请求级去重 / 批量 SQL / 动态导入模式 / arch:scan 串行执行。新增微服务特有经验:契约先行 / Outbox / CDC / 双轨读 / DataScope / 黄金模板复制流程。路线图按 6 阶段组织P1 地基 → P2 身份 → P3 核心教学 → P4 内容分析 → P5 沟通AI → P6 硬化。 |
| 日期 | 时间 | 模块 | 做了什么 + 学到什么 |
| ---------- | ---- | ------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 2026-07-09 | 下午 | 全局 | **OTel auto-instrumentations 全服务补全**(1) NestJS 6 服务iam/classes/core-edu/content/msg/teacher-bfftracer.ts 补 `getNodeAutoInstrumentations()`NodeSDK 传 instrumentations 参数自动埋点 HTTP/Express/DB。(2) Python 2 服务data-ana/aimain.py 补 `FastAPIInstrumentor.instrument_app(app)`ai 补缺失的 `opentelemetry-exporter-otlp` 依赖。(3) teacher-bff 从零补完整 OTelenv.ts 加 OTEL_EXPORTER_OTLP_ENDPOINT 字段 + 新建 shared/observability/tracer.ts + main.ts 调用 initTracer/shutdownTracer + package.json 加 sdk-node/exporter/auto-instrumentations 依赖。(4) Go 2 服务api-gateway/push-gateway新建 internal/observability/tracer.goOTLP HTTP exporter + resource + TracerProvider + W3C propagator+ main.go 调用 InitTracer + otelgin.Middleware 注册 Gin 中间件push-gateway config.go 补 OTLPEndpoint 字段。(5) 质量校验全通过TS typecheck 9 服务 + ESLint 6 服务 + ruff 2 服务 + go vet/build 2 服务零错误。**学到**`getNodeAutoInstrumentations()` 一次注册所有 Node.js 自动埋点http/express/dns/fs/net/grpc 等),比手动逐个注册 HttpInstrumentation 更简洁Go OTel 用 `otlptracehttp.WithEndpoint(host)` + `WithInsecure()` 需从 "http://host:port" URL 解析出 hostotelgin.Middleware 必须在 Recovery 之后其他中间件之前注册,确保所有后续 handler 都被 tracePython FastAPIInstrumentor.instrument_app(app) 在 app 创建后立即调用lifespan 不受影响。 |
| 2026-07-09 | 午 | 全局 | **P6 硬化:可观测性 + 部署 + CI 硬化**(1) 可观测性栈完善5 个 NestJS 服务 main.ts 添加 `/metrics` Prometheus 端点(用 `app.getHttpAdapter().get('/metrics', ...)` 绕过 DI 容器 get 方法prometheus.yml 从 2 个目标扩展到 8 个应用服务 + MySQL/Redis + node-exporter + prometheus 自身 + rule_files + alertmanager 关联monitoring compose 用 Loki + Promtail 替换未配置的 blackbox-exporterGrafana datasource 新增 Loki新建 promtail/config.yml 用 docker_sd_configs 仅采集 `edu-*` 容器日志。(2) 部署 compose 扩展docker-compose.deploy.yml 从 3 服务扩展到 11 服务(+ iam/teacher-bff/core-edu/content/msg/ai/data-ana/push-gateway每个服务带 healthcheck + depends_on 条件 + edu-net/edu-shared 双网络deploy.env.example 补全 Neo4j/ES/ClickHouse/LLM/Kafka 可选依赖配置。(3) teacher-bff 补 health.controller.ts原缺失 /healthz 导致 deploy depends_on service_healthy 失败)。(4) CI 硬化:移除 lint 步骤的 continue-on-errorESLint 9 flat config 已配置完成test 保留 continue-on-error部分服务无 test 脚本)。**学到**NestJS `app.get('/metrics')` 会被解析为 DI 容器 `get(typeOrToken)`,必须用 `app.getHttpAdapter().get()` 才能注册 Express 路由Promtail docker_sd_configs 通过 relabel_configs 的 `regex: '/(edu-.*).*'` 过滤容器名前缀docker-compose.depends_on.condition: service_healthy 要求被依赖服务必须有 healthcheck 配置,否则启动失败。 |
| 2026-07-09 | 午 | data-ana/infra | **CDC 完整链路实现**MySQL binlog → Debezium Connect → Kafka → data-ana 消费者 → ClickHouse 宽表。(1) MySQL binlog 配置log_bin=ON, binlog_format=ROW, binlog_row_image=FULL, server_id=1用 root 创建 `debezium` 用户授予 REPLICATION SLAVE + REPLICATION CLIENT。(2) Debezium Connect 容器daocloud 禁用 debezium 镜像改用 `quay.io/debezium/connect:2.7`MySQL 容器在 edu-minimal_default 网络,需 `docker network connect edu-full_default edu-mysql` 让 Debezium 同时可达Kafka 必须配置双 listenerINSIDE:kafka:29092 + OUTSIDE:localhost:9092否则 Debezium 拿到 advertised.listeners 中的 localhost metadata 后切换失败Debezium 2.x 容器环境变量名用 BOOTSTRAP_SERVERS不带 KAFKA_ 前缀),通过 envsubst 替换到 connect-distributed.properties。(3) 注册 connectorPOST :8083/connectors配置 topic.prefix=edu-cdc, database.include.list=next_edu_cloud, snapshot.mode=initial4 张表core_edu_grades/exams/classes/iam_users成功产生快照事件。(4) data-ana 消费者实现:新建 cdc_consumer.py 用 aiokafka AIOKafkaConsumerlifespan 中 asyncio.create_task 后台运行;按 source.table 路由exams→内存缓存 exam_id→class_id 映射grades→查缓存填 class_id 后 upsert ClickHousereadyz 端点附加 cdc_consumer 状态。(5) ClickHouse 远程访问:默认 default-user.xml 限制 127.0.0.1/::1 无密码,挂载 `clickhouse/users.d/custom-users.xml` 覆盖密码+任意 IP。(6) structlog 24.x API`make_filtering_bound_logger(level)` 替代废弃的 `make_filtering_logger`。(7) E2E 验证MySQL INSERT 成绩 → Debezium op=c 事件 → Kafka → 消费者写 ClickHouse 宽表class_id 通过 exam 缓存正确填充)→ /readyz cdc_consumer=running → /analytics/student/student-002/weakness 返回实时 92 分数据。**学到**Debezium 2.x 容器 bootstrap.servers 默认值是 0.0.0.0:9092 必须显式覆盖Kafka 单 listener 配置 localhost 会让容器间通信的客户端拿到 metadata 后切换失败,必须用双 listenerClickHouse users_xml 存储是 readonly 不能用 ALTER USER 修改密码,必须挂载 users.d 配置文件覆盖;消费者 offset 重置必须先停消费者让 group 处于 Empty 状态才能执行 --reset-offsets。 |
| 2026-07-09 | 午 | 全局 | **P6 硬化ESLint 9 flat config 配置**(1) 根目录创建 `eslint.config.js`ESLint 9 flat config 格式):用 `typescript-eslint` recommended 规则集 + `@eslint/js` recommended + `eslint-config-prettier` 禁用冲突规则;自定义规则:`no-explicit-any` warn + `no-unused-vars` 允许下划线前缀 + 测试文件放宽。(2) 6 个 TS 服务 package.json lint 脚本从 `eslint src --ext .ts` 改为 `eslint src`flat config 不需要 --ext。(3) `lint-staged.config.js` 恢复 `eslint --fix`。(4) 验证classes/content/msg/core-edu 四服务 lint 全部零错误零警告通过。**学到**ESLint 9 flat config 用 `tseslint.config()` 工厂函数组装配置数组;`--ext` 参数在 flat config 模式下被移除ESLint 自动根据 `eslint.config.js` 中的 `files` 匹配;`@typescript-eslint/consistent-type-assertions` 规则选项格式在 v8 中变化(`objectLiteralType` → `objectLiteralTypeAssertions`),配置时需查最新文档。 |
| 2026-07-09 | 午 | msg/push-gateway/ai/api-gateway | **P5 沟通与 AI 阶段三服务完善**(1) msg 服务修复database.ts 导出 db 常量env.ts JWT_SECRET/ES_URL 改 optional 加 DEV_MODE/PUSH_GATEWAY_URLelasticsearch.ts ES 降级esClient=null 时 safeIndex/safeSearch 跳过notifications.service.ts 加 createBatch + listByUserWithPagination + Push Gateway 推送调用try/catch 降级);新建 msg-init.sql 2 张表。(2) push-gateway 完善hub.go 重写用 send chan + 单写协程模式修复 gorilla/websocket 并发写竞争handler.go 加 DEV_MODE dev-token 支持 + broadcast 端点config.go 加 DevMode/RedisURL。(3) ai 服务完善config.py 加 openai_api_key/base_url/dev_mode新建 llm_client.pyhttpx 异步调 OpenAI REST APImain.py 加 /ai 前缀 + 降级模式(无 key 返回骨架 + degraded: true+ /readyz 端点。(4) Gateway 路由扩展:/notifications → msg/ai → ai 服务。**学到**gorilla/websocket 不支持并发写,必须用 send chan 串行化所有写入FastAPI APIRouter prefix 与 Gateway 代理路径要协调ai 服务加 /ai 前缀Gateway 代理 /ai/*pathLLM 降级策略统一返回 degraded 标记,调用方据此判断是否路由流量。 |
| 2026-07-09 | 午 | content/api-gateway | **P4 内容分析服务端到端打通**(1) content 服务系统性修复database.ts 导出 db 常量env.ts JWT_SECRET/ES_URL/NEO4J_URL/NEO4J_PASSWORD 改 optional 加 DEV_MODEneo4j.ts driver 惰性创建+try/catch+connectionTimeout:3000health/lifecycle 改用 Drizzleglobal-error.filter 移除 @types/express 依赖textbooks.schema 修复 integer→int + 导出 NewTextbook/NewChapter 类型textbooks.controller 移除 body as any + 加 PUT/DELETE。(2) 新建 3 模块chaptersCRUD + 按 textbook 查询、knowledge-pointsCRUD + Neo4j 前置依赖图非阻塞查询、questionsCRUD + 4 种题型校验)。(3) Gateway 路由扩展textbooks/chapters/knowledge-points/questions 四组路由。(4) 数据库content-init.sql 4 张表。(5) E2E 验证POST /textbooks 201 → POST /chapters 201字段用 order 非 orderNum→ POST /knowledge-points 201Neo4j 不可用 MySQL 正常写入)→ POST /questions 201 → GET 各列表 200。**学到**Drizzle schema TS 字段名与 DB 列名解耦order→order_numAPI 请求体用 TS 字段名Neo4j 不可用时必须 driver=null不设 NEO4J_URL否则每次请求尝试连接拖慢响应neo4j-driver safeCreateNode 用 try/catch 非阻塞MySQL 数据始终先落库。 |
| 2026-07-09 | 凌晨 | core-edu/api-gateway | **P3 核心教学服务端到端打通**(1) core-edu 服务系统性修复 13 项database.ts 导出 db 常量替代 getDb()env.ts JWT_SECRET 改 optional 加 DEV_MODEkafka.ts connectKafka 加 try/catch 不阻塞启动main.ts 去全局 /api 前缀 + connectKafka 改 void 非阻塞app.module 移除未用 AuthMiddleware/ClassesesModule 加 HealthModule3 个 controller 路由去前缀去 UseGuards 从 x-user-id 读身份exams/homework service datetime 列 ISO 字符串转 Date 修复 drizzle toISOString 错误;修正 10 处相对 import 路径health/lifecycle 改用 Drizzle 原生查询;新增 core-edu-init.sql 4 张表。(2) Gateway 路由扩展:发现 internal/routing/routing.go 是死代码(未被 main 引用),真正路由在 main.go在 main.go 添加 exams/homework/grades 三组路由(无尾斜杠+通配符);删除 routing.goconfig.go 加 CoreEduServiceURL。(3) DEV_MODE 环境变量问题Go 不自动加载 .env必须在启动前 export DEV_MODE=true 否则 dev-token 被拒 401。(4) E2E 验证POST /exams 201 → GET /exams/:id 200 → GET /exams/class/:id 200 → POST /homework 201 → POST /grades 201 → Outbox 3 条事件正确写入exam.failed 因 Kafka 未启动homework/grade pending。**学到**drizzle datetime 列需 Date 对象不是 ISO 字符串mapToDriverValue 调 toISOStringGo 项目 .env 不会自动加载需显式 export 或 godotenv 库NestJS controller 路由前缀与 Gateway 代理路径要协调Gateway 去掉 /api/v1 后转发controller 用裸路径如 'exams'Outbox 模式业务事务同写验证通过Kafka 未启动时事件 status=failed 但业务数据已落库。 |
| 2026-07-09 | 午 | iam/teacher-bff/teacher-portal | **P2 身份阶段完整实现**(1) Gateway 公开路径白名单register/login/refresh解决无 token 死锁。(2) IAM schema 扩展users 加 dataScope新增 role_viewports 表。(3) RBAC 端点 4 个 GET。(4) 视口按 requiredPermission 过滤 + sortOrder 排序getEffectivePermissions 用 Set 去重。(5) JWT payload 含 dataScoperegister 自动分配 teacher 角色。(6) 种子数据 7 权限+12 映射+7 视口。(7) Teacher BFF 视口聚合。(8) 前端lib/auth.ts + login + AppShell + (app) 路由组 + dashboard + classes真实 JWT+ 根重定向。(9) E2E 全链路通过。**学到**Next.js 路由组 (app) 不影响 URL/login 与 /dashboard 共存只后者套壳fetch headers 函数返回 Record<string,string> 避免 TS2769ESLint 9 需 flat config 留 P6AppShell aside 用 flex flex-col + mt-auto 比 absolute 稳健。 |
| 2026-07-08 | 晚上 | iam/classes/api-gateway | **P1 端到端链路验证 + IAM 服务修复**:验证 register → JWT → Gateway /iam/me → Gateway /classes CRUD → teacher-portal 前端渲染全链路打通。(1) IAM 服务 14 个 TS 编译错误修复:移除 typeorm/ioredis/kafkajs 依赖IAM 用 Drizzlehealth.controller.ts 改用 `db.execute(sql\`SELECT 1\`)`lifecycle.service.ts 简化为只关闭 Drizzle 连接池Drizzle API 修正(`r.roles`→`r.iam_roles``.in()`→`inArray()`)。(2) NestJS ESM DI 修复iam.module.ts 简化 providers 为 `[IamService, IamRepository]`iam.service.ts 构造器加 `@Inject(IamRepository)`(参考 classes 黄金模板),修复运行时 `Cannot read properties of undefined (reading 'findUserByEmail')`。(3) Gateway /iam/me 404 修复iam.controller.ts 直接读 `req.headers['x-user-id']`替代未注册的`AuthenticatedRequest`。(4) 创建 `scripts/iam-init.sql`建 6 张 IAM 表 + 种子数据。(5) E2E 验证iam:3002 注册/登录 → Gateway /iam/me 200 → Gateway GET /classes 200 → Gateway POST /classes合法 UUID gradeId201 → teacher-portal:3000 首页渲染 200 + 含"班级管理" → Next.js rewrites 透传 dev-token 到 Gateway 全链路通。**学到**NestJS ESM 模式下 DI 无法通过类型推断解析 token必须显式`@Inject(Token)`Drizzle select 返回字段名按 schema 定义而非表名classes.dto.ts 的 gradeId 要求 UUID 格式,测试数据不能用 "grade-12" 这类字符串PowerShell 控制台中文显示为 `?`是编码问题数据库实际存储正确DEV_MODE 下前端用`Bearer dev-token` 即可走通链路,无需真实 JWT。 |
| 2026-07-08 | 下午 | 全局 | **CI/CD 完整配置 + 多AI协作规范入规则**(1) project_rules.md 新增 §14 多 AI 协作规范(角色权限矩阵/分支命名/PR合并规则/跨模块变更顺序/冲突处理/AI 身份标注/敏感文件保护)+ §15 CI/CD 规范(流水线阶段/触发条件/镜像规范/部署策略/Secrets 管理/必需 CI 文件)。(2) 优化现有 4 个 ci-*.ymlci-ts.yml 加 arch-scan + docker-build jobci-go.yml 去掉 golangci-lintlint-staged 预存问题),加 docker-buildci-proto.yml 修复 buf breaking URL从 github.com 改为 .git 本地比较)。(3) 新增 `docker.yml`main/tag 触发,构建推送 3 服务镜像到 Gitea Container Registrygit.eazygame.cn/xiner/edu/<service>:latest + sha tag + version tag用 GITHUB_TOKEN 自动认证。(4) 新增 `deploy.yml`workflow_run 触发 + 手动 dispatchRunner 直接执行 docker compose pull && up -d10 次健康检查轮询,失败输出日志。(5) 新增 `infra/docker-compose.deploy.yml`(部署用,镜像来自 Gitea registry连接服务器已有 MySQL/Redis 通过 edu-shared 外部网络)+ `infra/deploy.env.example`(部署环境变量模板)。(6) 编写 `docs/standards/cicd-runbook.md`CI/CD 使用手册,含架构总览/一次性配置/日常使用/镜像管理/部署验证/回滚/常见问题/排查命令/安全注意事项)。**学到**Docker Compose 不支持 `restart_policy`(是 swarm 字段),用 `restart: unless-stopped` 替代Gitea Actions 兼容 GitHub Actions 语法但 `workflow_run` 触发可能不完整,备选手动 dispatch应用容器访问宿主机已有 MySQL/Redis 需通过共享外部网络(`docker network create edu-shared` + `docker network connect`)而非 `host.docker.internal`。 |
| 2026-07-08 | 下午 | api-gateway | **重定向循环修复 + 生产模式部署准备 + 多AI协作文档**(1) 修复 `ERR_TOO_MANY_REDIRECTS`Gin 默认 `RedirectTrailingSlash=true` 导致 `/api/v1/classes` → 301 → `/classes/`Next.js rewrites 代理时形成循环。**修复**`r.RedirectTrailingSlash=false` + 同时注册无尾斜杠路由(`/classes`)与通配符路由(`/classes/*path`)。(2) 新增 DEV_MODE 旁路:`config.go` 加 `DevMode` 字段,`auth.go` 在 `DEV_MODE=true` 时接受 `dev-token` 注入固定身份(生产必须 false。(3) 生产 Docker 化:新建 `apps/teacher-portal/Dockerfile`(多阶段 Next.js build+ `services/api-gateway/Dockerfile`(多阶段 Go 静态编译)+ `infra/docker-compose.prod.yml`(三服务编排,强制 DEV_MODE=false。(4) 编写 `docs/standards/local-dev-runbook.md`(本地启动手册,含端口表/开发模式/生产模式/常见问题)+ `docs/standards/multi-ai-collaboration.md`多AI协作文档含模块分工矩阵/分支命名/PR流程/合并策略/冲突处理/权限矩阵)。**学到**Gin `RedirectTrailingSlash=false` 后需显式注册无尾斜杠路由(`Any("/classes")` + `Any("/classes/*path")`),否则 404Next.js rewrites 代理会透传 301 给浏览器形成循环,开发模式旁路应通过环境变量控制而非硬编码。 |
| 2026-07-08 | 全天 | 全局 | **P6 后续工作手册执行**:完整执行 post-p6-followup.md 12 节任务。环境准备pnpm 925 包 + go mod tidy 双服务 + uv sync 双服务 + buf 安装)→ 代码质量校验Go vet/build 0 错误Python ruff 8 错误自动修复)→ arch.db 同步(实现 4 个扫描器骨架,输出 12 模块/233 符号/138 契约)→ project_rules.md P0 修复(迁移到 .trae/rules/17881 字节)→ 004 架构图修复1.1a/1.1b 双图 + 1.2 业务领域列 + 5.4 视口四层)→ P6 集成测试10 Go + 17 bash = 27 用例全通过)→ Helm Chart 演化8 chart lint 通过)。**学到**:多语言 monorepo 工具链配置需统一镜像源npmmirror/goproxy.cn/tunago.work BOM 字符会导致 `unexpected input character` 错误必须重写文件。 |
| 2026-07-08 | 上午 | 全局 | pnpm install 网络失败ECONNRESET→ 配置 `npm config set registry https://registry.npmmirror.com` + `pnpm config set registry https://registry.npmmirror.com` 重试成功。**学到**Windows 下 pnpm 还需配置 `PNPM_HOME` 和 `TMP` 环境变量避免 `_tmp_` 文件 ENOENT 错误。 |
| 2026-07-08 | 上午 | 全局 | project_rules.md 损坏72 字节乱码,从 P1 提交 2ba4250 就损坏git 历史无完整版本)→ 从 CICD 项目完整版迁移到 `e:\Desktop\Edu\.trae\rules\project_rules.md`(按用户要求放 .trae/rules/),按 MIGRATION_GUIDE 4.1 策略矩阵调整为微服务版13 章 17881 字节),删除根目录损坏文件,更新 7 处引用README/MIGRATION_GUIDE/004/known-issues/git-workflow/coding-standards。**学到**:迁移文件后必须 `Get-Item | Select Length` 验证完整性 + 全文搜索引用更新git commit 前运行 cat 检查内容。 |
| 2026-07-08 | 上午 | api-gateway | go.work BOM 字符 + 版本不匹配:`unexpected input character '\ufeff'` 和 `module requires go >= 1.22.0, but go.work lists go 1.22`。**修复**:重写 go.work 去除 BOM版本改为 `go 1.26.0`,移除不存在的 `./packages/shared-go`。**学到**PowerShell `Out-File` 默认加 BOM写 go.work 这类敏感文件应用 `Write` 工具或 `[System.IO.File]::WriteAllText` 指定 UTF8 无 BOM。 |
| 2026-07-08 | 上午 | arch-scan | arch:scan 返回 0 模块 0 符号 → 4 个扫描器ts/go/py/proto都是骨架实现。**修复**:完整实现 4 个扫描器TS 用 regex 提取(避免 ts-morph 对未安装依赖文件解析失败Go/Python 用行首锚定正则Proto 扫描 service/message/rpc。结果12 模块≥10 ✓、233 符号≥100 ✓、138 契约。**学到**ts-morph Project 对未 `pnpm install` 的 workspace 文件会报模块解析失败,改用 regex 更鲁棒scanner.ts main() 开头需 `DELETE FROM` 清空旧数据避免重跑重复。 |
| 2026-07-08 | 下午 | 004 | 架构图视角讨论(技术分层 vs 业务领域)→ 双图并存方案1.1a 技术分层视角(部署/流量/网络边界Users 层标注"场景域用户"BFF 层标注"按场景域分"+ 1.1b 业务领域视角6 DDD 限界上下文 subgraphD1 身份/D2 教学组织/D3 教学核心/D4 内容/D5 沟通/D6 智能洞察。1.2 服务清单新增"业务领域"列。**学到**双图互补1.1a 服务运维/SRE 视角1.1b 服务产品/架构视角同一服务可横跨多领域core-edu 同时承载 D2+D3。 |
| 2026-07-08 | 下午 | 004 | 视口四层模型补充5.4 章节L1 导航navigation_config 表)/ L2 路由route_permission + Gateway 校验)/ L3 组件usePermission().hasPermission/ L4 数据DataScope 枚举)。场景域 BFF 复用策略:按使用场景域分 BFF 而非按角色分,教导主任复用 Teacher BFF + 额外管理视口。iam 服务职责:认证 + RBAC + 视口配置 + DataScope + 权限解析 API。**学到**视口既可独立配置RoleViewport 表)也可由权限推导,新角色只需配权限集,视口自动推导。 |
| 2026-07-08 | 下午 | api-gateway | P6 集成测试补充circuit-breaker_test.go5 用例ClosedToOpen/OpenToHalfOpen/HalfOpenToClosed/HalfOpenToOpen/4xxNotCounted+ ratelimit_test.go5 用例AllowUnderBurst/RejectOverBurst/RefillTokens/PerIPIsolation/CleanupExpiredBuckets+ test-backup-mysql.sh8 用例 17 断言)。**学到**gobreaker v2 ReadyToTrip 在 1 次失败后就触发(`TotalFailures*2 > Requests` 当 Requests=1 时 1*2>1=trueHALF_OPEN 状态只在探测执行期间可见,探测完成后立即转 CLOSED 或回 OPEN测试需通过行为503 vs 500而非状态字段验证rateLimiter cleanup 测试需用短周期参数50ms/500ms加速且新鲜桶要在旧桶清理后再创建避免被一起清掉。 |
| 2026-07-08 | 下午 | infra/k8s | Helm Chart 演化:安装 Helm v4.2.2,创建 edu-platform 平台级 chartnamespace/configmap/secret/ingress/hpa + 4 环境 values 文件)+ api-gateway 服务级 chart完整迁移自原 deployment.yaml参数化所有字段+ 6 业务服务 chart 桩iam/core-edu/content/msg/data-ana/ai。删除原 api-gateway-deployment.yaml保留 namespace.yaml。**学到**Helm `{{- with ... -}}` 双向修剪会导致标签连在一行(`managed-by: Helmpart-of: edu-platform`),应改为 `{{- with ... }}` 只修剪左侧;`helm lint` 全部通过但 `helm template` 才能发现 YAML 渲染错误,验证时两个都要跑。 |
| 2026-07-07 | 全天 | 全局 | 文档体系初始化从旧项目e:\Desktop\CICDNext.js 单体)迁移 spec + plan + known-issues 模板到新仓库e:\Desktop\Edu微服务架构。known-issues 重组为微服务分区:多语言 monorepo / Docker Compose / protobuf+buf / NestJS / Go Gateway / 可观测性 / 微前端。从旧项目提炼可迁移经验React 19 useOptimistic / Zustand 细粒度选择器 / Tiptap SSR / 请求级去重 / 批量 SQL / 动态导入模式 / arch:scan 串行执行。新增微服务特有经验:契约先行 / Outbox / CDC / 双轨读 / DataScope / 黄金模板复制流程。路线图按 6 阶段组织P1 地基 → P2 身份 → P3 核心教学 → P4 内容分析 → P5 沟通AI → P6 硬化。 |

60
eslint.config.js Normal file
View File

@@ -0,0 +1,60 @@
// ESLint 9 flat config
// 项目级配置TypeScript + NestJS + Next.js + 设计令牌规则
const js = require('@eslint/js');
const tseslint = require('typescript-eslint');
const prettierConfig = require('eslint-config-prettier');
module.exports = tseslint.config(
// 全局忽略
{
ignores: [
'**/dist/**',
'**/node_modules/**',
'**/.next/**',
'**/coverage/**',
'**/*.config.js',
'**/*.config.mjs',
'scripts/arch-scan/**',
],
},
// 基础 JS 规则
js.configs.recommended,
// TypeScript 规则
...tseslint.configs.recommended,
// 项目级自定义规则
{
languageOptions: {
ecmaVersion: 2024,
sourceType: 'module',
},
rules: {
// 禁止 any未知类型用 unknown
'@typescript-eslint/no-explicit-any': 'warn',
// 未使用变量允许下划线前缀
'@typescript-eslint/no-unused-vars': [
'error',
{
argsIgnorePattern: '^_',
varsIgnorePattern: '^_',
},
],
// 允许 console开发环境
'no-console': 'off',
},
},
// 测试文件放宽规则
{
files: ['**/*.test.ts', '**/*.spec.ts', '**/test/**'],
rules: {
'@typescript-eslint/no-explicit-any': 'off',
'@typescript-eslint/no-non-null-assertion': 'off',
},
},
// 禁用与 Prettier 冲突的规则
prettierConfig,
);

4
go.work.sum Normal file
View File

@@ -0,0 +1,4 @@
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
golang.org/x/term v0.20.0/go.mod h1:8UkIAJTvZgivsXaD6/pH6U9ecQzZ45awqEOzuCvwpFY=
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=

View File

@@ -0,0 +1,14 @@
<clickhouse>
<!-- 覆盖 default-user.xml 的本地限制,允许 default 用户从任意 IP 用密码访问 -->
<users>
<default>
<password>clickhouse</password>
<networks>
<ip>::/0</ip>
</networks>
<profile>default</profile>
<quota>default</quota>
<access_management>1</access_management>
</default>
</users>
</clickhouse>

55
infra/deploy.env.example Normal file
View File

@@ -0,0 +1,55 @@
# 服务器部署环境变量模板
# 使用方式:复制到 /opt/edu/.env 并填入生产值
# cp infra/deploy.env.example /opt/edu/.env
# vim /opt/edu/.env
#
# 安全警告:
# - 此文件含敏感信息,禁止提交到 Git
# - .gitignore 已忽略 .env
# - 仅 SRE AI 或人类决策者可编辑
# ============ 数据库(服务器已有 MySQL============
# DATABASE_URL 中的 host 需用容器名(如 edu-mysql而非 localhost
# 因为应用容器通过 edu-shared 网络访问 MySQL 容器
DATABASE_URL=mysql://edu:changeme@edu-mysql:3306/next_edu_cloud
# ============ Redis服务器已有 Redis============
# 同理用容器名
REDIS_URL=redis://edu-redis:6379
# ============ JWT生产密钥必须修改============
# 生成方式openssl rand -hex 32
JWT_SECRET=CHANGE_ME_TO_STRONG_RANDOM_SECRET
JWT_ISSUER=next-edu-cloud
JWT_AUDIENCE=next-edu-cloud
# ============ 服务端口 ============
API_GATEWAY_PORT=8080
TEACHER_PORTAL_PORT=3000
# ============ KafkaP3+ 启用,留空则 Outbox publisher 持续重试)============
KAFKA_BROKERS=
# ============ 可观测性P6 启用)============
# OTLP collector 端点,留空则服务跳过 trace 上报
OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4318
LOG_LEVEL=info
# ============ Neo4jcontent 服务,留空则降级模式)============
NEO4J_URL=
NEO4J_PASSWORD=
# ============ Elasticsearchmsg 服务,留空则降级模式)============
ES_URL=
# ============ ClickHousedata-ana 服务,留空则降级模式)============
CLICKHOUSE_HOST=
CLICKHOUSE_PORT=8123
CLICKHOUSE_DATABASE=edu_analytics
CLICKHOUSE_USER=
CLICKHOUSE_PASSWORD=
# ============ LLM 配置ai 服务,留空则降级模式)============
OPENAI_API_KEY=
OPENAI_BASE_URL=https://api.openai.com/v1
ANTHROPIC_API_KEY=

View File

@@ -0,0 +1,328 @@
# 服务器部署用 Docker Composeno-push 本地构建模式)
# 镜像来源CI 容器内本地 docker build不推送到 registry
# 基础设施MySQL + Redis 已在服务器 Docker 中运行(不在此文件管理)
#
# 部署目录:/opt/edu/
# 部署命令CI 自动执行):
# docker compose up -d --build --remove-orphans
#
# 首次部署手动步骤:
# 1. sudo mkdir -p /opt/edu && sudo chown -R $USER:$USER /opt/edu
# 2. cp infra/docker-compose.deploy.yml /opt/edu/docker-compose.yml
# 3. cp infra/deploy.env.example /opt/edu/.env && 编辑填入生产密钥
# 4. docker compose up -d --build
#
# 注意compose 文件中的 build.context 路径相对于 /opt/edu/ 目录
# CI 在 deploy 步骤会先把仓库 checkout 到 /opt/edu/repo/,再 cp compose 文件到 /opt/edu/
name: edu
services:
# ============================================================
# 应用服务10 个api-gateway + 3 Go/Python + 6 NestJS
# ============================================================
api-gateway:
build:
context: ./repo/services/api-gateway
dockerfile: Dockerfile
container_name: edu-api-gateway
restart: unless-stopped
environment:
API_GATEWAY_PORT: ${API_GATEWAY_PORT:-8080}
JWT_SECRET: ${JWT_SECRET}
JWT_ISSUER: ${JWT_ISSUER:-next-edu-cloud}
JWT_AUDIENCE: ${JWT_AUDIENCE:-next-edu-cloud}
# 生产环境强制关闭 dev-token 旁路
DEV_MODE: "false"
CLASSES_SERVICE_URL: http://classes:3001
IAM_SERVICE_URL: http://iam:3002
TEACHER_BFF_URL: http://teacher-bff:3003
CORE_EDU_SERVICE_URL: http://core-edu:3004
CONTENT_SERVICE_URL: http://content:3005
DATA_ANA_SERVICE_URL: http://data-ana:3006
MSG_SERVICE_URL: http://msg:3007
AI_SERVICE_URL: http://ai:3008
OTEL_EXPORTER_OTLP_ENDPOINT: ${OTEL_EXPORTER_OTLP_ENDPOINT:-http://otel-collector:4318}
LOG_LEVEL: ${LOG_LEVEL:-info}
ports:
- "${API_GATEWAY_PORT:-8080}:8080"
depends_on:
classes:
condition: service_healthy
healthcheck:
test: ["CMD", "wget", "--quiet", "--spider", "http://localhost:8080/healthz"]
interval: 30s
timeout: 5s
start_period: 10s
retries: 3
networks:
- edu-net
- edu-shared
classes:
build:
context: ./repo
dockerfile: services/classes/Dockerfile
container_name: edu-classes
restart: unless-stopped
environment:
PORT: 3001
DATABASE_URL: ${DATABASE_URL}
REDIS_URL: ${REDIS_URL}
KAFKA_BROKERS: ${KAFKA_BROKERS:-}
OTEL_EXPORTER_OTLP_ENDPOINT: ${OTEL_EXPORTER_OTLP_ENDPOINT:-http://otel-collector:4318}
LOG_LEVEL: ${LOG_LEVEL:-info}
healthcheck:
test: ["CMD", "wget", "--quiet", "--spider", "http://localhost:3001/healthz"]
interval: 30s
timeout: 5s
start_period: 30s
retries: 5
networks:
- edu-net
- edu-shared
iam:
build:
context: ./repo
dockerfile: services/iam/Dockerfile
container_name: edu-iam
restart: unless-stopped
environment:
PORT: 3002
DATABASE_URL: ${DATABASE_URL}
REDIS_URL: ${REDIS_URL}
JWT_SECRET: ${JWT_SECRET}
JWT_ISSUER: ${JWT_ISSUER:-next-edu-cloud}
JWT_AUDIENCE: ${JWT_AUDIENCE:-next-edu-cloud}
OTEL_EXPORTER_OTLP_ENDPOINT: ${OTEL_EXPORTER_OTLP_ENDPOINT:-http://otel-collector:4318}
LOG_LEVEL: ${LOG_LEVEL:-info}
NODE_ENV: production
healthcheck:
test: ["CMD", "wget", "--quiet", "--spider", "http://localhost:3002/healthz"]
interval: 30s
timeout: 5s
start_period: 30s
retries: 5
networks:
- edu-net
- edu-shared
teacher-bff:
build:
context: ./repo
dockerfile: services/teacher-bff/Dockerfile
container_name: edu-teacher-bff
restart: unless-stopped
environment:
PORT: 3003
IAM_SERVICE_URL: http://iam:3002
CLASSES_SERVICE_URL: http://classes:3001
CORE_EDU_SERVICE_URL: http://core-edu:3004
LOG_LEVEL: ${LOG_LEVEL:-info}
NODE_ENV: production
depends_on:
iam:
condition: service_healthy
classes:
condition: service_healthy
healthcheck:
test: ["CMD", "wget", "--quiet", "--spider", "http://localhost:3003/healthz"]
interval: 30s
timeout: 5s
start_period: 20s
retries: 3
networks:
- edu-net
- edu-shared
core-edu:
build:
context: ./repo
dockerfile: services/core-edu/Dockerfile
container_name: edu-core-edu
restart: unless-stopped
environment:
PORT: 3004
DATABASE_URL: ${DATABASE_URL}
REDIS_URL: ${REDIS_URL}
KAFKA_BROKERS: ${KAFKA_BROKERS:-}
OTEL_EXPORTER_OTLP_ENDPOINT: ${OTEL_EXPORTER_OTLP_ENDPOINT:-http://otel-collector:4318}
LOG_LEVEL: ${LOG_LEVEL:-info}
NODE_ENV: production
DEV_MODE: "false"
healthcheck:
test: ["CMD", "wget", "--quiet", "--spider", "http://localhost:3004/healthz"]
interval: 30s
timeout: 5s
start_period: 30s
retries: 5
networks:
- edu-net
- edu-shared
content:
build:
context: ./repo
dockerfile: services/content/Dockerfile
container_name: edu-content
restart: unless-stopped
environment:
PORT: 3005
DATABASE_URL: ${DATABASE_URL}
REDIS_URL: ${REDIS_URL}
NEO4J_URL: ${NEO4J_URL:-}
NEO4J_PASSWORD: ${NEO4J_PASSWORD:-}
ES_URL: ${ES_URL:-}
OTEL_EXPORTER_OTLP_ENDPOINT: ${OTEL_EXPORTER_OTLP_ENDPOINT:-http://otel-collector:4318}
LOG_LEVEL: ${LOG_LEVEL:-info}
NODE_ENV: production
DEV_MODE: "false"
healthcheck:
test: ["CMD", "wget", "--quiet", "--spider", "http://localhost:3005/healthz"]
interval: 30s
timeout: 5s
start_period: 30s
retries: 5
networks:
- edu-net
- edu-shared
msg:
build:
context: ./repo
dockerfile: services/msg/Dockerfile
container_name: edu-msg
restart: unless-stopped
environment:
PORT: 3007
DATABASE_URL: ${DATABASE_URL}
REDIS_URL: ${REDIS_URL}
KAFKA_BROKERS: ${KAFKA_BROKERS:-}
ES_URL: ${ES_URL:-}
PUSH_GATEWAY_URL: http://push-gateway:8081
OTEL_EXPORTER_OTLP_ENDPOINT: ${OTEL_EXPORTER_OTLP_ENDPOINT:-http://otel-collector:4318}
LOG_LEVEL: ${LOG_LEVEL:-info}
NODE_ENV: production
DEV_MODE: "false"
depends_on:
push-gateway:
condition: service_healthy
healthcheck:
test: ["CMD", "wget", "--quiet", "--spider", "http://localhost:3007/healthz"]
interval: 30s
timeout: 5s
start_period: 30s
retries: 5
networks:
- edu-net
- edu-shared
ai:
build:
context: ./repo/services/ai
dockerfile: Dockerfile
container_name: edu-ai
restart: unless-stopped
environment:
PORT: 3008
OPENAI_API_KEY: ${OPENAI_API_KEY:-}
OPENAI_BASE_URL: ${OPENAI_BASE_URL:-https://api.openai.com/v1}
ANTHROPIC_API_KEY: ${ANTHROPIC_API_KEY:-}
OTEL_ENDPOINT: ${OTEL_EXPORTER_OTLP_ENDPOINT:-http://otel-collector:4318}
LOG_LEVEL: ${LOG_LEVEL:-info}
DEV_MODE: "false"
healthcheck:
test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:3008/healthz')"]
interval: 30s
timeout: 5s
start_period: 20s
retries: 3
networks:
- edu-net
- edu-shared
data-ana:
build:
context: ./repo/services/data-ana
dockerfile: Dockerfile
container_name: edu-data-ana
restart: unless-stopped
environment:
PORT: 3006
CLICKHOUSE_HOST: ${CLICKHOUSE_HOST:-}
CLICKHOUSE_PORT: ${CLICKHOUSE_PORT:-8123}
CLICKHOUSE_DATABASE: ${CLICKHOUSE_DATABASE:-edu_analytics}
CLICKHOUSE_USER: ${CLICKHOUSE_USER:-}
CLICKHOUSE_PASSWORD: ${CLICKHOUSE_PASSWORD:-}
OTEL_ENDPOINT: ${OTEL_EXPORTER_OTLP_ENDPOINT:-http://otel-collector:4318}
LOG_LEVEL: ${LOG_LEVEL:-info}
DEV_MODE: "false"
KAFKA_BROKERS: ${KAFKA_BROKERS:-}
healthcheck:
test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:3006/healthz')"]
interval: 30s
timeout: 5s
start_period: 20s
retries: 3
networks:
- edu-net
- edu-shared
push-gateway:
build:
context: ./repo/services/push-gateway
dockerfile: Dockerfile
container_name: edu-push-gateway
restart: unless-stopped
environment:
PUSH_GATEWAY_PORT: 8081
JWT_SECRET: ${JWT_SECRET}
REDIS_URL: ${REDIS_URL}
DEV_MODE: "false"
healthcheck:
test: ["CMD", "wget", "--quiet", "--spider", "http://localhost:8081/healthz"]
interval: 30s
timeout: 5s
start_period: 10s
retries: 3
networks:
- edu-net
- edu-shared
teacher-portal:
build:
context: ./repo
dockerfile: apps/teacher-portal/Dockerfile
container_name: edu-teacher-portal
restart: unless-stopped
environment:
NODE_ENV: production
PORT: 3000
API_GATEWAY_URL: http://api-gateway:8080
ports:
- "${TEACHER_PORTAL_PORT:-3000}:3000"
depends_on:
api-gateway:
condition: service_healthy
healthcheck:
test: ["CMD", "wget", "--quiet", "--spider", "http://localhost:3000/"]
interval: 30s
timeout: 5s
start_period: 20s
retries: 3
networks:
- edu-net
- edu-shared
networks:
# 应用服务内部网络
edu-net:
driver: bridge
# 与已有 MySQL/Redis 共享的网络
# 需确保 MySQL/Redis 容器已加入名为 edu-shared 的网络:
# docker network create edu-shared (若不存在)
# docker network connect edu-shared edu-mysql
# docker network connect edu-shared edu-redis
edu-shared:
external: true

View File

@@ -14,6 +14,8 @@ volumes:
name: edu-alertmanager-data
grafana-data:
name: edu-grafana-data
loki-data:
name: edu-loki-data
services:
# ============================================================
@@ -104,16 +106,35 @@ services:
- edu-network
# ============================================================
# blackbox-exporter - 黑盒探测HTTP / TCP / ICMP
# Loki - 日志聚合P6 硬化新增
# ============================================================
blackbox-exporter:
image: prom/blackbox-exporter:v0.25.0
container_name: edu-blackbox-exporter
loki:
image: grafana/loki:3.2.1
container_name: edu-loki
profiles: ["monitoring"]
restart: unless-stopped
command: -config.file=/etc/loki/local-config.yaml
ports:
- "9115:9115"
- "3100:3100"
volumes:
- ./blackbox/blackbox.yml:/etc/blackbox_exporter/config.yml:ro
- loki-data:/loki
networks:
- edu-network
# ============================================================
# Promtail - 日志采集(收集 Docker 容器日志发送到 Loki
# ============================================================
promtail:
image: grafana/promtail:3.2.1
container_name: edu-promtail
profiles: ["monitoring"]
restart: unless-stopped
command: -config.file=/etc/promtail/config.yml
volumes:
- ./promtail/config.yml:/etc/promtail/config.yml:ro
- /var/lib/docker/containers:/var/lib/docker/containers:ro
- /var/run/docker.sock:/var/run/docker.sock:ro
networks:
- edu-network
depends_on:
- loki

View File

@@ -0,0 +1,105 @@
# 生产环境应用服务编排
# 仅包含应用服务api-gateway / classes / teacher-portal基础设施请使用 docker-compose.yml 或 K8s
#
# 使用方式:
# 1. 先构建镜像:
# docker compose -f infra/docker-compose.prod.yml build
# 2. 启动(依赖基础设施已运行):
# docker compose -f infra/docker-compose.prod.yml up -d
# 3. 查看日志:
# docker compose -f infra/docker-compose.prod.yml logs -f
#
# 前置条件:
# - MySQL:3306、Redis:6379已通过 docker-compose.minimal.yml 或外部方式启动
# - .env 文件已配置DEV_MODE 必须为 false
name: edu-prod
services:
api-gateway:
build:
context: ..
dockerfile: services/api-gateway/Dockerfile
image: edu/api-gateway:latest
container_name: edu-api-gateway
restart: unless-stopped
environment:
API_GATEWAY_PORT: ${API_GATEWAY_PORT:-8080}
JWT_SECRET: ${JWT_SECRET}
JWT_ISSUER: ${JWT_ISSUER:-next-edu-cloud}
JWT_AUDIENCE: ${JWT_AUDIENCE:-next-edu-cloud}
# 生产环境强制关闭 dev-token 旁路
DEV_MODE: "false"
CLASSES_SERVICE_URL: http://classes:3001
IAM_SERVICE_URL: http://iam:3002
TEACHER_BFF_URL: http://teacher-bff:3003
OTEL_EXPORTER_OTLP_ENDPOINT: ${OTEL_EXPORTER_OTLP_ENDPOINT:-http://otel-collector:4318}
LOG_LEVEL: ${LOG_LEVEL:-info}
ports:
- "${API_GATEWAY_PORT:-8080}:8080"
depends_on:
classes:
condition: service_healthy
healthcheck:
test: ["CMD", "wget", "--quiet", "--spider", "http://localhost:8080/healthz"]
interval: 30s
timeout: 5s
start_period: 10s
retries: 3
networks:
- edu-net
classes:
build:
context: ..
dockerfile: services/classes/Dockerfile
image: edu/classes:latest
container_name: edu-classes
restart: unless-stopped
environment:
PORT: 3001
DATABASE_URL: ${DATABASE_URL}
REDIS_URL: ${REDIS_URL}
KAFKA_BROKERS: ${KAFKA_BROKERS:-}
OTEL_EXPORTER_OTLP_ENDPOINT: ${OTEL_EXPORTER_OTLP_ENDPOINT:-http://otel-collector:4318}
LOG_LEVEL: ${LOG_LEVEL:-info}
# classes 连接宿主机 MySQL/Redis 时host.docker.internal 在 Docker Desktop 上可用
extra_hosts:
- "host.docker.internal:host-gateway"
healthcheck:
test: ["CMD", "wget", "--quiet", "--spider", "http://localhost:3001/healthz"]
interval: 30s
timeout: 5s
start_period: 30s
retries: 5
networks:
- edu-net
teacher-portal:
build:
context: ..
dockerfile: apps/teacher-portal/Dockerfile
image: edu/teacher-portal:latest
container_name: edu-teacher-portal
restart: unless-stopped
environment:
NODE_ENV: production
PORT: 3000
API_GATEWAY_URL: http://api-gateway:8080
ports:
- "${TEACHER_PORTAL_PORT:-3000}:3000"
depends_on:
api-gateway:
condition: service_healthy
healthcheck:
test: ["CMD", "wget", "--quiet", "--spider", "http://localhost:3000/"]
interval: 30s
timeout: 5s
start_period: 20s
retries: 3
networks:
- edu-net
networks:
edu-net:
driver: bridge

View File

@@ -0,0 +1,55 @@
# CI/CD 工具镜像预拉(一次性拉取所有 CI 与构建需要的镜像到本地)
# 用途actrunner 的 container job 会优先使用本地镜像缓存,避免每次 CI 联网拉取
#
# 用法:
# docker compose -f infra/docker-compose.tools.yml pull
#
# 拉取后可用 docker images 查看所有 edu 相关镜像
# 这不是常驻服务,只是借用 compose 的批量 pull 能力
name: edu-tools
services:
# ===== CI 运行时镜像actrunner container job 使用)=====
node-ci:
image: node:22-alpine
command: ["echo", "node-ci image pulled"]
golang-ci:
image: golang:1.22-alpine
command: ["echo", "golang-ci image pulled"]
buf-ci:
image: bufbuild/buf:latest
command: ["echo", "buf-ci image pulled"]
docker-ci:
image: docker:25-git
command: ["echo", "docker-ci image pulled"]
# ===== 服务构建基础镜像Dockerfile FROM=====
# teacher-portal / classes 的 builder 阶段
node-builder:
image: node:20-alpine
command: ["echo", "node-builder image pulled"]
# api-gateway 的 builder 阶段
golang-builder:
image: golang:1.22-alpine
command: ["echo", "golang-builder image pulled"]
# api-gateway 的 runner 阶段
alpine-runner:
image: alpine:3.20
command: ["echo", "alpine-runner image pulled"]
# ===== 开发/测试基础设施(生产用已有的,不在此管理)=====
# 服务器已有的 MySQL/Redis 不在此拉取
# 仅用于本地开发测试环境docker-compose.dev.yml如有
mysql-dev:
image: mysql:8.0
command: ["echo", "mysql-dev image pulled"]
redis-dev:
image: redis:7-alpine
command: ["echo", "redis-dev image pulled"]

View File

@@ -1,7 +1,8 @@
name: edu-full
services:
mysql:
image: mysql:8.0
# 镜像加速:通过 daocloud 镜像源绕过 docker.io 被墙问题
image: docker.m.daocloud.io/library/mysql:8.0
container_name: edu-mysql
restart: unless-stopped
environment:
@@ -20,7 +21,7 @@ services:
timeout: 5s
retries: 5
redis:
image: redis:7-alpine
image: docker.m.daocloud.io/library/redis:7-alpine
container_name: edu-redis
restart: unless-stopped
ports:
@@ -33,7 +34,7 @@ services:
timeout: 3s
retries: 5
kafka:
image: confluentinc/cp-kafka:7.6.0
image: docker.m.daocloud.io/confluentinc/cp-kafka:7.6.0
container_name: edu-kafka
profiles: ["p3", "p4", "p5", "p6"]
restart: unless-stopped
@@ -43,7 +44,13 @@ services:
environment:
KAFKA_BROKER_ID: 1
KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181
KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://localhost:9092
# 双 listenerINSIDE 容器间互访kafka:29092OUTSIDE 主机访问(localhost:9092
# 必须用 INSIDE 作为 inter.broker.listener.name否则 Debezium Connect 拿到 metadata
# 后会切回 advertised.listeners 中的 localhost导致连接失败
KAFKA_LISTENERS: INSIDE://:29092,OUTSIDE://:9092
KAFKA_ADVERTISED_LISTENERS: INSIDE://kafka:29092,OUTSIDE://localhost:9092
KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: INSIDE:PLAINTEXT,OUTSIDE:PLAINTEXT
KAFKA_INTER_BROKER_LISTENER_NAME: INSIDE
KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1
KAFKA_AUTO_CREATE_TOPICS_ENABLE: "true"
ports:
@@ -54,7 +61,7 @@ services:
timeout: 10s
retries: 5
zookeeper:
image: confluentinc/cp-zookeeper:7.6.0
image: docker.m.daocloud.io/confluentinc/cp-zookeeper:7.6.0
container_name: edu-zookeeper
profiles: ["p3", "p4", "p5", "p6"]
restart: unless-stopped
@@ -66,7 +73,7 @@ services:
timeout: 5s
retries: 5
clickhouse:
image: clickhouse/clickhouse-server:24.3
image: docker.m.daocloud.io/clickhouse/clickhouse-server:24.3
container_name: edu-clickhouse
profiles: ["p4", "p5", "p6"]
restart: unless-stopped
@@ -75,13 +82,15 @@ services:
- "9000:9000"
volumes:
- clickhouse_data:/var/lib/clickhouse
# 覆盖默认 default-user.xml 限制(默认仅允许 127.0.0.1/::1 无密码访问)
- ./clickhouse/users.d/custom-users.xml:/etc/clickhouse-server/users.d/custom-users.xml:ro
healthcheck:
test: ["CMD", "wget", "--spider", "-q", "http://localhost:8123/ping"]
interval: 10s
timeout: 5s
retries: 5
neo4j:
image: neo4j:5.20
image: docker.m.daocloud.io/library/neo4j:5.20
container_name: edu-neo4j
profiles: ["p4", "p5", "p6"]
restart: unless-stopped
@@ -98,6 +107,7 @@ services:
timeout: 10s
retries: 5
elasticsearch:
# Elastic 官方镜像在 docker.elastic.co非 Docker Hub通常不被墙
image: docker.elastic.co/elasticsearch/elasticsearch:8.13.0
container_name: edu-es
profiles: ["p5", "p6"]
@@ -116,7 +126,7 @@ services:
timeout: 10s
retries: 5
jaeger:
image: jaegertracing/all-in-one:1.57
image: docker.m.daocloud.io/jaegertracing/all-in-one:1.57
container_name: edu-jaeger
profiles: ["observability"]
restart: unless-stopped
@@ -125,8 +135,52 @@ services:
ports:
- "16686:16686"
- "4318:4318"
# ============================================================
# Debezium Connect - CDC 链路核心
# 监听 MySQL binlog → 写入 Kafka topic
# topic 命名约定:<prefix>.<database>.<table>(如 edu-cdc.next_edu_cloud.grades
# ============================================================
debezium-connect:
image: quay.io/debezium/connect:2.7
container_name: edu-debezium
profiles: ["p4", "p5", "p6"]
restart: unless-stopped
depends_on:
kafka:
condition: service_healthy
environment:
# Kafka Connect 基础配置Debezium 2.x 容器映射规则:环境变量名大写 → connect 配置项)
# 必须用 INSIDE listener (kafka:29092),否则会拿到 OUTSIDE 的 localhost metadata 导致连不上
BOOTSTRAP_SERVERS: kafka:29092
GROUP_ID: edu-debezium
CONFIG_STORAGE_TOPIC: edu-connect-configs
OFFSET_STORAGE_TOPIC: edu-connect-offsets
STATUS_STORAGE_TOPIC: edu-connect-status
# 内部 converter 配置(必须与 Debezium 事件格式一致)
CONFIG_STORAGE_REPLICATION_FACTOR: "1"
OFFSET_STORAGE_REPLICATION_FACTOR: "1"
STATUS_STORAGE_REPLICATION_FACTOR: "1"
KEY_CONVERTER: org.apache.kafka.connect.json.JsonConverter
VALUE_CONVERTER: org.apache.kafka.connect.json.JsonConverter
KEY_CONVERTER_SCHEMAS_ENABLE: "false"
VALUE_CONVERTER_SCHEMAS_ENABLE: "false"
# 监听端口
REST_PORT: 8083
REST_ADVERTISED_HOST_NAME: debezium-connect
# 日志级别
LOG_LEVEL: INFO
ports:
- "8083:8083"
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:8083/connectors"]
interval: 15s
timeout: 5s
start_period: 30s
retries: 10
networks:
- default
prometheus:
image: prom/prometheus:v0.51.0
image: docker.m.daocloud.io/prom/prometheus:v2.51.0
container_name: edu-prometheus
profiles: ["observability"]
restart: unless-stopped
@@ -135,14 +189,14 @@ services:
ports:
- "9090:9090"
grafana:
image: grafana/grafana:10.4.0
image: docker.m.daocloud.io/grafana/grafana:10.4.0
container_name: edu-grafana
profiles: ["observability"]
restart: unless-stopped
environment:
GF_SECURITY_ADMIN_PASSWORD: admin
ports:
- "3001:3001"
- "3030:3000"
volumes:
- grafana_data:/var/lib/grafana
volumes:
@@ -151,4 +205,4 @@ volumes:
clickhouse_data:
neo4j_data:
es_data:
grafana_data:
grafana_data:

View File

@@ -13,3 +13,12 @@ datasources:
timeInterval: "15s"
httpMethod: POST
manageAlerts: false
- name: Loki
type: loki
uid: loki
access: proxy
url: http://loki:3100
editable: false
jsonData:
maxLines: 1000

View File

@@ -2,11 +2,93 @@ global:
scrape_interval: 15s
evaluation_interval: 15s
scrape_configs:
- job_name: 'api-gateway'
static_configs:
- targets: ['host.docker.internal:8080']
# 告警规则文件
rule_files:
- /etc/prometheus/rules.yml
# 告警管理器
alerting:
alertmanagers:
- static_configs:
- targets:
- alertmanager:9093
scrape_configs:
# ============================================================
# 应用服务NestJS / FastAPI 暴露 /metrics
# ============================================================
- job_name: 'classes-service'
static_configs:
- targets: ['host.docker.internal:3001']
- targets: ['host.docker.internal:3001']
labels:
service: classes
- job_name: 'iam-service'
static_configs:
- targets: ['host.docker.internal:3002']
labels:
service: iam
- job_name: 'teacher-bff'
static_configs:
- targets: ['host.docker.internal:3003']
labels:
service: teacher-bff
- job_name: 'core-edu-service'
static_configs:
- targets: ['host.docker.internal:3004']
labels:
service: core-edu
- job_name: 'content-service'
static_configs:
- targets: ['host.docker.internal:3005']
labels:
service: content
- job_name: 'data-ana-service'
static_configs:
- targets: ['host.docker.internal:3006']
labels:
service: data-ana
- job_name: 'msg-service'
static_configs:
- targets: ['host.docker.internal:3007']
labels:
service: msg
- job_name: 'ai-service'
static_configs:
- targets: ['host.docker.internal:3008']
labels:
service: ai
# ============================================================
# 基础设施docker-compose.minimal/minimal.override
# ============================================================
- job_name: 'mysql'
static_configs:
- targets: ['host.docker.internal:9104']
labels:
service: mysql
- job_name: 'redis'
static_configs:
- targets: ['host.docker.internal:9121']
labels:
service: redis
# ============================================================
# 监控栈自身
# ============================================================
- job_name: 'prometheus'
static_configs:
- targets: ['localhost:9090']
- job_name: 'node-exporter'
static_configs:
- targets: ['node-exporter:9100']
labels:
service: node-exporter

28
infra/promtail/config.yml Normal file
View File

@@ -0,0 +1,28 @@
server:
http_listen_port: 9080
grpc_listen_port: 0
positions:
filename: /tmp/positions.yaml
clients:
- url: http://loki:3100/loki/api/v1/push
scrape_configs:
# 采集 Docker 容器日志
- job_name: docker
docker_sd_configs:
- host: unix:///var/run/docker.sock
refresh_interval: 5s
relabel_configs:
# 只采集带 edu- 前缀的容器日志
- source_labels: ['__meta_docker_container_name']
regex: '/(edu-.*).*'
action: keep
# 提取容器名作为 label
- source_labels: ['__meta_docker_container_name']
regex: '/(.*)'
target_label: container_name
# 提取镜像名
- source_labels: ['__meta_docker_container_log_stream']
target_label: stream

View File

@@ -1,6 +1,5 @@
module.exports = {
// ESLint 9 flat config 迁移完成后恢复:['eslint --fix', 'prettier --write']
'*.{ts,tsx}': ['prettier --write'],
'*.{ts,tsx}': ['eslint --fix', 'prettier --write'],
// Go 工具链不在 git hook PATH 中Go 文件格式化由 go fmt 手动执行
// golangci-lint 安装后恢复:['gofmt -w', 'golangci-lint run --fix']
'*.py': ['ruff check --fix', 'ruff format'],

View File

@@ -18,13 +18,17 @@
"prepare": "husky"
},
"devDependencies": {
"husky": "^9.1.0",
"lint-staged": "^15.0.0",
"@commitlint/cli": "^19.0.0",
"@commitlint/config-conventional": "^19.0.0",
"@eslint/js": "^9.0.0",
"@types/node": "^22.0.0",
"eslint": "^9.0.0",
"eslint-config-prettier": "^9.0.0",
"husky": "^9.1.0",
"lint-staged": "^15.0.0",
"prettier": "^3.3.0",
"tsx": "^4.19.0",
"typescript": "^5.6.0",
"@types/node": "^22.0.0",
"prettier": "^3.3.0"
"typescript-eslint": "^8.0.0"
}
}

1529
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,37 @@
-- ClickHouse 数据库初始化脚本
-- 适用服务data-ana数据分析
-- 表结构student_dashboard_view学生学情宽表/ student_errors错题本
-- 与 services/data-ana/src/data_ana/clickhouse_client.py 中的查询字段对齐
--
-- 使用方式(启用 ClickHouse 时执行一次):
-- clickhouse-client --multiquery < scripts/clickhouse-init.sql
-- 注意ClickHouse 为可选依赖,未配置时 data-ana 服务进入降级模式。
-- 数据库
CREATE DATABASE IF NOT EXISTS edu_analytics;
-- 学生学情宽表(考试/班级/知识点维度)
CREATE TABLE IF NOT EXISTS edu_analytics.student_dashboard_view (
student_id String,
class_id String,
exam_id String,
subject_id String,
score Float64,
rank_in_class UInt32,
knowledge_point_id String,
mastery_level Float32,
error_count UInt32,
last_updated DateTime
) ENGINE = MergeTree()
ORDER BY (student_id, class_id, exam_id);
-- 学生错题表(错题本)
CREATE TABLE IF NOT EXISTS edu_analytics.student_errors (
student_id String,
question_id String,
knowledge_point_id String,
error_count UInt32,
last_error_time DateTime,
content String
) ENGINE = MergeTree()
ORDER BY (student_id, knowledge_point_id);

47
scripts/content-init.sql Normal file
View File

@@ -0,0 +1,47 @@
-- Content 服务数据库初始化脚本
-- 表content_textbooks / content_chapters / content_knowledge_points / content_questions
-- 表结构与 services/content/src 下的 Drizzle schema 对齐
CREATE TABLE IF NOT EXISTS content_textbooks (
id CHAR(36) NOT NULL PRIMARY KEY,
title VARCHAR(200) NOT NULL,
subject_id CHAR(36) NOT NULL,
grade_id CHAR(36) NOT NULL,
version VARCHAR(50) NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
INDEX idx_textbooks_subject_id (subject_id),
INDEX idx_textbooks_grade_id (grade_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE IF NOT EXISTS content_chapters (
id CHAR(36) NOT NULL PRIMARY KEY,
textbook_id CHAR(36) NOT NULL,
title VARCHAR(200) NOT NULL,
order_num INT NOT NULL,
parent_id CHAR(36),
INDEX idx_chapters_textbook_id (textbook_id),
INDEX idx_chapters_parent_id (parent_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE IF NOT EXISTS content_knowledge_points (
id CHAR(36) NOT NULL PRIMARY KEY,
chapter_id CHAR(36) NOT NULL,
title VARCHAR(200) NOT NULL,
description TEXT,
INDEX idx_knowledge_points_chapter_id (chapter_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE IF NOT EXISTS content_questions (
id CHAR(36) NOT NULL PRIMARY KEY,
knowledge_point_id CHAR(36) NOT NULL,
type VARCHAR(50) NOT NULL,
content TEXT NOT NULL,
answer TEXT,
explanation TEXT,
difficulty INT DEFAULT 3,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
INDEX idx_questions_knowledge_point_id (knowledge_point_id),
INDEX idx_questions_type (type)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

65
scripts/core-edu-init.sql Normal file
View File

@@ -0,0 +1,65 @@
-- CoreEdu 服务数据库初始化脚本
-- 表core_edu_exams / core_edu_homework / core_edu_grades / core_edu_outbox
CREATE TABLE IF NOT EXISTS core_edu_exams (
id CHAR(36) NOT NULL PRIMARY KEY,
class_id CHAR(36) NOT NULL,
title VARCHAR(200) NOT NULL,
description TEXT,
exam_date DATETIME NOT NULL,
duration VARCHAR(50) NOT NULL,
total_score VARCHAR(10) NOT NULL,
status VARCHAR(20) NOT NULL DEFAULT 'draft',
created_by CHAR(36) NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
INDEX idx_exams_class_id (class_id),
INDEX idx_exams_status (status),
INDEX idx_exams_created_by (created_by)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE IF NOT EXISTS core_edu_homework (
id CHAR(36) NOT NULL PRIMARY KEY,
class_id CHAR(36) NOT NULL,
title VARCHAR(200) NOT NULL,
description TEXT,
due_date DATETIME NOT NULL,
status VARCHAR(20) NOT NULL DEFAULT 'assigned',
created_by CHAR(36) NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
INDEX idx_homework_class_id (class_id),
INDEX idx_homework_status (status),
INDEX idx_homework_created_by (created_by)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE IF NOT EXISTS core_edu_grades (
id CHAR(36) NOT NULL PRIMARY KEY,
student_id CHAR(36) NOT NULL,
exam_id CHAR(36),
homework_id CHAR(36),
score VARCHAR(10) NOT NULL,
feedback TEXT,
graded_by CHAR(36) NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
INDEX idx_grades_student_id (student_id),
INDEX idx_grades_exam_id (exam_id),
INDEX idx_grades_homework_id (homework_id),
INDEX idx_grades_graded_by (graded_by)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE IF NOT EXISTS core_edu_outbox (
id CHAR(36) NOT NULL PRIMARY KEY,
aggregate_id CHAR(36) NOT NULL,
aggregate_type VARCHAR(50) NOT NULL,
event_type VARCHAR(100) NOT NULL,
payload TEXT NOT NULL,
status VARCHAR(20) NOT NULL DEFAULT 'pending',
retry_count BIGINT NOT NULL DEFAULT 0,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
processed_at TIMESTAMP NULL,
INDEX idx_outbox_status (status),
INDEX idx_outbox_aggregate (aggregate_type, aggregate_id),
INDEX idx_outbox_created_at (created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

View File

@@ -0,0 +1,22 @@
{
"name": "edu-mysql-source",
"config": {
"connector.class": "io.debezium.connector.mysql.MySqlConnector",
"database.hostname": "edu-mysql",
"database.port": "3306",
"database.user": "debezium",
"database.password": "debezium-pwd",
"database.allowPublicKeyRetrieval": "true",
"database.server.id": "184054",
"topic.prefix": "edu-cdc",
"database.include.list": "next_edu_cloud",
"table.include.list": "next_edu_cloud.core_edu_grades,next_edu_cloud.core_edu_exams,next_edu_cloud.classes,next_edu_cloud.iam_users",
"schema.history.internal.kafka.bootstrap.servers": "kafka:29092",
"schema.history.internal.kafka.topic": "edu-connect-schema-history",
"snapshot.mode": "initial",
"key.converter": "org.apache.kafka.connect.json.JsonConverter",
"value.converter": "org.apache.kafka.connect.json.JsonConverter",
"key.converter.schemas.enable": "false",
"value.converter.schemas.enable": "false"
}
}

115
scripts/iam-init.sql Normal file
View File

@@ -0,0 +1,115 @@
-- IAM 服务表结构P2 身份阶段)
CREATE TABLE IF NOT EXISTS `iam_users` (
`id` CHAR(36) NOT NULL,
`email` VARCHAR(255) NOT NULL,
`password_hash` VARCHAR(255) NOT NULL,
`name` VARCHAR(100) NOT NULL,
`status` VARCHAR(20) NOT NULL DEFAULT 'active',
`data_scope` ENUM('self','class','grade','school','district','all') NOT NULL DEFAULT 'self',
`created_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `iam_users_email_unique` (`email`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS `iam_roles` (
`id` CHAR(36) NOT NULL,
`name` VARCHAR(50) NOT NULL,
`description` VARCHAR(255) NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `iam_roles_name_unique` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS `iam_user_roles` (
`user_id` CHAR(36) NOT NULL,
`role_id` CHAR(36) NOT NULL,
`created_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`user_id`, `role_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS `iam_permissions` (
`id` CHAR(36) NOT NULL,
`name` VARCHAR(100) NOT NULL,
`resource` VARCHAR(50) NOT NULL,
`action` VARCHAR(50) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `iam_permissions_name_unique` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS `iam_role_permissions` (
`role_id` CHAR(36) NOT NULL,
`permission_id` CHAR(36) NOT NULL,
PRIMARY KEY (`role_id`, `permission_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS `iam_refresh_tokens` (
`id` CHAR(36) NOT NULL,
`user_id` CHAR(36) NOT NULL,
`token_hash` VARCHAR(255) NOT NULL,
`expires_at` TIMESTAMP NOT NULL,
`revoked_at` TIMESTAMP NULL,
`created_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
INDEX `idx_iam_refresh_tokens_user_id` (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- 视口配置表4 层模型L1 导航 / L2 路由 / L3 组件 / L4 数据)
CREATE TABLE IF NOT EXISTS `iam_role_viewports` (
`id` CHAR(36) NOT NULL,
`role_id` CHAR(36) NOT NULL,
`viewport_key` VARCHAR(50) NOT NULL,
`label` VARCHAR(100) NOT NULL,
`route` VARCHAR(200) NOT NULL,
`icon` VARCHAR(50) NULL,
`sort_order` VARCHAR(10) NOT NULL DEFAULT '0',
`required_permission` VARCHAR(100) NULL,
`component_config` TEXT NULL,
PRIMARY KEY (`id`),
INDEX `idx_iam_role_viewports_role_id` (`role_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- 种子数据:默认角色
INSERT IGNORE INTO `iam_roles` (`id`, `name`, `description`) VALUES
('00000000-0000-0000-0000-000000000001', 'teacher', '教师角色'),
('00000000-0000-0000-0000-000000000002', 'admin', '管理员角色');
-- 种子数据:权限点(固定 UUID 便于 role_permissions 引用)
INSERT IGNORE INTO `iam_permissions` (`id`, `name`, `resource`, `action`) VALUES
('00000000-0000-0000-0000-000000000101', 'classes:read', 'classes', 'read'),
('00000000-0000-0000-0000-000000000102', 'classes:create', 'classes', 'create'),
('00000000-0000-0000-0000-000000000103', 'classes:update', 'classes', 'update'),
('00000000-0000-0000-0000-000000000104', 'classes:delete', 'classes', 'delete'),
('00000000-0000-0000-0000-000000000201', 'iam:user:read', 'iam', 'user:read'),
('00000000-0000-0000-0000-000000000202', 'iam:user:manage', 'iam', 'user:manage'),
('00000000-0000-0000-0000-000000000203', 'iam:role:manage', 'iam', 'role:manage');
-- 种子数据teacher 角色权限classes CRUD + user:read
INSERT IGNORE INTO `iam_role_permissions` (`role_id`, `permission_id`) VALUES
('00000000-0000-0000-0000-000000000001', '00000000-0000-0000-0000-000000000101'),
('00000000-0000-0000-0000-000000000001', '00000000-0000-0000-0000-000000000102'),
('00000000-0000-0000-0000-000000000001', '00000000-0000-0000-0000-000000000103'),
('00000000-0000-0000-0000-000000000001', '00000000-0000-0000-0000-000000000104'),
('00000000-0000-0000-0000-000000000001', '00000000-0000-0000-0000-000000000201');
-- 种子数据admin 角色权限(全部权限)
INSERT IGNORE INTO `iam_role_permissions` (`role_id`, `permission_id`) VALUES
('00000000-0000-0000-0000-000000000002', '00000000-0000-0000-0000-000000000101'),
('00000000-0000-0000-0000-000000000002', '00000000-0000-0000-0000-000000000102'),
('00000000-0000-0000-0000-000000000002', '00000000-0000-0000-0000-000000000103'),
('00000000-0000-0000-0000-000000000002', '00000000-0000-0000-0000-000000000104'),
('00000000-0000-0000-0000-000000000002', '00000000-0000-0000-0000-000000000201'),
('00000000-0000-0000-0000-000000000002', '00000000-0000-0000-0000-000000000202'),
('00000000-0000-0000-0000-000000000002', '00000000-0000-0000-0000-000000000203');
-- 种子数据teacher 角色视口L1 导航)
INSERT IGNORE INTO `iam_role_viewports` (`id`, `role_id`, `viewport_key`, `label`, `route`, `icon`, `sort_order`, `required_permission`) VALUES
('00000000-0000-0000-0000-000000000a01', '00000000-0000-0000-0000-000000000001', 'dashboard', '仪表盘', '/dashboard', 'home', '0', NULL),
('00000000-0000-0000-0000-000000000a02', '00000000-0000-0000-0000-000000000001', 'classes', '班级管理', '/classes', 'users', '1', 'classes:read'),
('00000000-0000-0000-0000-000000000a03', '00000000-0000-0000-0000-000000000001', 'profile', '个人中心', '/profile', 'user', '9', NULL);
-- 种子数据admin 角色视口L1 导航)
INSERT IGNORE INTO `iam_role_viewports` (`id`, `role_id`, `viewport_key`, `label`, `route`, `icon`, `sort_order`, `required_permission`) VALUES
('00000000-0000-0000-0000-000000000b01', '00000000-0000-0000-0000-000000000002', 'dashboard', '仪表盘', '/dashboard', 'home', '0', NULL),
('00000000-0000-0000-0000-000000000b02', '00000000-0000-0000-0000-000000000002', 'classes', '班级管理', '/classes', 'users', '1', 'classes:read'),
('00000000-0000-0000-0000-000000000b03', '00000000-0000-0000-0000-000000000002', 'iam', '用户管理', '/iam/users', 'shield', '2', 'iam:user:read'),
('00000000-0000-0000-0000-000000000b04', '00000000-0000-0000-0000-000000000002', 'profile', '个人中心', '/profile', 'user', '9', NULL);

26
scripts/msg-init.sql Normal file
View File

@@ -0,0 +1,26 @@
-- Msg 服务数据库初始化脚本
-- 表msg_notifications / msg_notification_preferences
CREATE TABLE IF NOT EXISTS msg_notifications (
id CHAR(36) NOT NULL PRIMARY KEY,
user_id CHAR(36) NOT NULL,
type VARCHAR(50) NOT NULL,
title VARCHAR(200) NOT NULL,
content TEXT NOT NULL,
channel VARCHAR(20) NOT NULL DEFAULT 'in_app',
is_read BOOLEAN NOT NULL DEFAULT FALSE,
metadata JSON NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
INDEX idx_notifications_user_id (user_id),
INDEX idx_notifications_is_read (is_read),
INDEX idx_notifications_created_at (created_at),
INDEX idx_notifications_user_read (user_id, is_read)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE IF NOT EXISTS msg_notification_preferences (
user_id CHAR(36) NOT NULL PRIMARY KEY,
email_enabled BOOLEAN NOT NULL DEFAULT TRUE,
sms_enabled BOOLEAN NOT NULL DEFAULT FALSE,
push_enabled BOOLEAN NOT NULL DEFAULT TRUE,
in_app_enabled BOOLEAN NOT NULL DEFAULT TRUE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

View File

@@ -11,6 +11,8 @@ dependencies = [
"httpx>=0.27.0",
"opentelemetry-api>=1.27.0",
"opentelemetry-sdk>=1.27.0",
"opentelemetry-exporter-otlp>=1.27.0",
"opentelemetry-instrumentation-fastapi>=0.48b0",
"prometheus-client>=0.20.0",
"structlog>=24.4.0",
]

View File

@@ -7,12 +7,27 @@ class Settings(BaseSettings):
"""应用配置."""
port: int = 3008
# LLM 配置(可选,为空时降级返回骨架响应)
openai_api_key: str = ""
openai_base_url: str = "https://api.openai.com/v1"
anthropic_api_key: str = ""
# 开发模式true 时跳过 OTel exporter 初始化,避免本地无 collector 时报错
dev_mode: str = "false"
# 可观测性
otel_endpoint: str = "http://localhost:4318"
log_level: str = "info"
model_config = {"env_file": ".env", "env_prefix": ""}
@property
def is_dev(self) -> bool:
"""是否处于开发模式."""
return self.dev_mode.lower() == "true"
@property
def llm_available(self) -> bool:
"""LLM 是否可用(至少一个 provider 配置了 API key."""
return bool(self.openai_api_key or self.anthropic_api_key)
settings = Settings()

View File

@@ -0,0 +1,137 @@
"""LLM 客户端 - 使用 httpx 直接调用 OpenAI 兼容 REST API。
设计要点:
- 不依赖 openai SDK纯 httpx 异步调用
- api_key 为空或调用失败时返回 None / yield 降级骨架数据
- 调用方据此决定是否进入降级路径
"""
from collections.abc import AsyncGenerator
from typing import Any
import httpx
import structlog
logger = structlog.get_logger()
# 非流式请求默认超时(秒)
DEFAULT_TIMEOUT: float = 30.0
# 流式请求建立连接超时(秒);读取通过迭代器控制
STREAM_CONNECT_TIMEOUT: float = 30.0
# 流式读取单次 chunk 超时(秒)
STREAM_READ_TIMEOUT: float = 60.0
def _build_url(base_url: str) -> str:
"""拼接 chat completions 端点 URL."""
return f"{base_url.rstrip('/')}/chat/completions"
def _build_headers(api_key: str) -> dict[str, str]:
"""构建请求头."""
return {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json",
}
async def chat_completion(
messages: list[dict[str, Any]],
model: str,
temperature: float,
api_key: str,
base_url: str,
) -> dict[str, Any] | None:
"""非流式调用 LLM。
Returns:
OpenAI 兼容的响应 dictapi_key 为空或调用失败时返回 None由调用方降级
"""
if not api_key:
logger.warning("llm_chat_completion_no_api_key_degraded")
return None
url = _build_url(base_url)
headers = _build_headers(api_key)
payload = {
"model": model,
"messages": messages,
"temperature": temperature,
"stream": False,
}
try:
async with httpx.AsyncClient(timeout=DEFAULT_TIMEOUT) as client:
resp = await client.post(url, json=payload, headers=headers)
resp.raise_for_status()
return resp.json()
except httpx.HTTPStatusError as exc:
logger.error(
"llm_chat_completion_http_error",
status_code=exc.response.status_code,
body=exc.response.text[:500],
)
return None
except Exception as exc: # noqa: BLE001 - 顶层兜底,所有异常均降级
logger.error("llm_chat_completion_failed", error=str(exc))
return None
async def chat_completion_stream(
messages: list[dict[str, Any]],
model: str,
temperature: float,
api_key: str,
base_url: str,
) -> AsyncGenerator[str, None]:
"""流式调用 LLM以 SSE 格式(``data: <chunk>\\n\\n``yield。
api_key 为空或调用失败时 yield 降级骨架数据,保证下游始终能消费。
"""
if not api_key:
logger.warning("llm_stream_no_api_key_degraded")
yield (
'data: {"choices":[{"delta":{"content":"[degraded] LLM API key not configured"}}]}\n\n'
)
yield "data: [DONE]\n\n"
return
url = _build_url(base_url)
headers = _build_headers(api_key)
payload = {
"model": model,
"messages": messages,
"temperature": temperature,
"stream": True,
}
timeout = httpx.Timeout(
connect=STREAM_CONNECT_TIMEOUT,
read=STREAM_READ_TIMEOUT,
write=STREAM_CONNECT_TIMEOUT,
pool=STREAM_CONNECT_TIMEOUT,
)
try:
async with (
httpx.AsyncClient(timeout=timeout) as client,
client.stream("POST", url, json=payload, headers=headers) as resp,
):
resp.raise_for_status()
async for line in resp.aiter_lines():
if not line or not line.startswith("data: "):
continue
yield f"{line}\n\n"
if line.strip() == "data: [DONE]":
return
except httpx.HTTPStatusError as exc:
logger.error(
"llm_stream_http_error_degraded",
status_code=exc.response.status_code,
)
yield 'data: {"choices":[{"delta":{"content":"[degraded] LLM stream HTTP error"}}]}\n\n'
yield "data: [DONE]\n\n"
except Exception as exc: # noqa: BLE001 - 顶层兜底,所有异常均降级
logger.error("llm_stream_failed_degraded", error=str(exc))
yield 'data: {"choices":[{"delta":{"content":"[degraded] LLM stream error"}}]}\n\n'
yield "data: [DONE]\n\n"

View File

@@ -1,36 +1,59 @@
"""AI 网关服务入口."""
from collections.abc import AsyncGenerator
from contextlib import asynccontextmanager
from typing import Any
import structlog
from fastapi import FastAPI
from fastapi import APIRouter, FastAPI
from fastapi.responses import StreamingResponse
from opentelemetry import trace
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from prometheus_client import make_asgi_app
from pydantic import BaseModel
from .config import settings
from .llm_client import chat_completion, chat_completion_stream
logger = structlog.get_logger()
tracer = trace.get_tracer(__name__)
def init_tracer() -> None:
"""初始化 OpenTelemetry."""
"""初始化 OpenTelemetry.
endpoint 从 settings.otel_endpoint 读取dev_mode=true 时跳过 exporter
初始化,避免本地无 collector 时报错。
"""
if settings.is_dev:
logger.info("dev_mode_tracer_skipped", dev_mode=settings.dev_mode)
return
provider = TracerProvider()
exporter = OTLPSpanExporter(endpoint="http://localhost:4318/v1/traces")
endpoint = f"{settings.otel_endpoint.rstrip('/')}/v1/traces"
exporter = OTLPSpanExporter(endpoint=endpoint)
provider.add_span_processor(BatchSpanProcessor(exporter))
trace.set_tracer_provider(provider)
logger.info("tracer_initialized", otel_endpoint=endpoint)
@asynccontextmanager
async def lifespan(app: FastAPI):
"""应用生命周期."""
init_tracer()
logger.info("ai service starting")
logger.info(
"ai_service_starting",
llm_available=settings.llm_available,
dev_mode=settings.is_dev,
openai_base_url=settings.openai_base_url,
)
if not settings.llm_available:
logger.warning("ai_service_llm_degraded_no_api_key")
yield
logger.info("ai service stopping")
logger.info("ai_service_stopping")
app = FastAPI(
@@ -39,13 +62,19 @@ app = FastAPI(
lifespan=lifespan,
)
# OpenTelemetry FastAPI 自动埋点HTTP 请求/响应 span
FastAPIInstrumentor.instrument_app(app)
app.mount("/metrics", make_asgi_app())
# 业务路由加 /ai 前缀Gateway 代理 /api/v1/ai/* → /ai/*
router = APIRouter(prefix="/ai")
class ChatRequest(BaseModel):
"""聊天请求."""
messages: list[dict]
messages: list[dict[str, Any]]
model: str = "gpt-4o-mini"
temperature: float = 0.7
stream: bool = False
@@ -56,56 +85,157 @@ class ChatResponse(BaseModel):
content: str
model: str
usage: dict
usage: dict[str, Any]
degraded: bool = False
def _extract_content(result: dict[str, Any] | None) -> tuple[str, str, dict[str, Any]]:
"""从 OpenAI 响应中抽取 (content, model, usage)。"""
if result is None:
return "", "", {}
choices = result.get("choices", [])
content = ""
if choices:
content = choices[0].get("message", {}).get("content", "") or ""
model = result.get("model", "") or ""
usage = result.get("usage", {}) or {}
return content, model, usage
@app.get("/healthz")
async def healthz():
"""健康检查."""
async def healthz() -> dict[str, Any]:
"""健康检查liveness."""
return {"status": "ok", "service": "ai"}
@app.post("/chat", response_model=ChatResponse)
async def chat(req: ChatRequest):
"""LLM 聊天接口."""
@app.get("/readyz")
async def readyz() -> dict[str, Any]:
"""就绪检查readiness.
LLM 未配置时仍返回 200但标记 degraded=true调用方可据此判断是否路由流量。
"""
llm_configured = settings.llm_available
return {
"status": "ok",
"service": "ai",
"llm_configured": llm_configured,
"degraded": not llm_configured,
"openai_base_url": settings.openai_base_url,
}
@router.post("/chat", response_model=ChatResponse)
async def chat(req: ChatRequest) -> ChatResponse:
"""LLM 聊天接口(无 API key 时降级返回骨架响应)."""
with tracer.start_as_current_span("ai_chat"):
# P5 骨架:实际调用 OpenAI/Anthropic API
# 需要从环境变量获取 API key
return {
"content": "P5 skeleton - LLM integration pending",
"model": req.model,
"usage": {"prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0},
}
result = await chat_completion(
messages=req.messages,
model=req.model,
temperature=req.temperature,
api_key=settings.openai_api_key,
base_url=settings.openai_base_url,
)
if result is None:
logger.warning("chat_degraded", model=req.model)
return ChatResponse(
content="[degraded] LLM unavailable - returning skeleton response",
model=req.model,
usage={"prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0},
degraded=True,
)
content, model, usage = _extract_content(result)
return ChatResponse(
content=content,
model=model or req.model,
usage=usage,
degraded=False,
)
@app.post("/chat/stream")
async def chat_stream(req: ChatRequest):
"""流式聊天SSE."""
@router.post("/chat/stream")
async def chat_stream(req: ChatRequest) -> StreamingResponse:
"""流式聊天(SSE无 API key 时降级返回骨架 SSE."""
async def generate():
async def generate() -> AsyncGenerator[str, None]:
with tracer.start_as_current_span("ai_chat_stream"):
# P5 骨架:流式调用 LLM
yield "data: P5 skeleton\n\n"
yield "data: [DONE]\n\n"
async for chunk in chat_completion_stream(
messages=req.messages,
model=req.model,
temperature=req.temperature,
api_key=settings.openai_api_key,
base_url=settings.openai_base_url,
):
yield chunk
return StreamingResponse(generate(), media_type="text/event-stream")
@app.post("/generate/question")
async def generate_question(prompt: str):
"""生成题目."""
@router.post("/generate/question")
async def generate_question(prompt: str) -> dict[str, Any]:
"""生成题目(无 API key 时降级返回骨架)."""
with tracer.start_as_current_span("generate_question"):
messages = [
{
"role": "system",
"content": "You are an educational question generator. "
"Generate a clear, concise question based on the user's prompt.",
},
{"role": "user", "content": prompt},
]
result = await chat_completion(
messages=messages,
model="gpt-4o-mini",
temperature=0.7,
api_key=settings.openai_api_key,
base_url=settings.openai_base_url,
)
if result is None:
logger.warning("generate_question_degraded", prompt=prompt[:100])
return {
"success": True,
"data": {"question": "[degraded] question generation skeleton"},
"degraded": True,
}
content, _, _ = _extract_content(result)
return {
"success": True,
"data": {"question": "P5 skeleton - question generation pending"},
"data": {"question": content},
"degraded": False,
}
@app.post("/optimize/expression")
async def optimize_expression(text: str):
"""优化表达."""
@router.post("/optimize/expression")
async def optimize_expression(text: str) -> dict[str, Any]:
"""优化表达(无 API key 时降级返回骨架)."""
with tracer.start_as_current_span("optimize_expression"):
messages = [
{
"role": "system",
"content": "You are a writing assistant. "
"Optimize the user's text for clarity, conciseness, and tone.",
},
{"role": "user", "content": text},
]
result = await chat_completion(
messages=messages,
model="gpt-4o-mini",
temperature=0.5,
api_key=settings.openai_api_key,
base_url=settings.openai_base_url,
)
if result is None:
logger.warning("optimize_expression_degraded", text=text[:100])
return {
"success": True,
"data": {"optimized": "[degraded] expression optimization skeleton"},
"degraded": True,
}
content, _, _ = _extract_content(result)
return {
"success": True,
"data": {"optimized": "P5 skeleton - expression optimization pending"},
"data": {"optimized": content},
"degraded": False,
}
app.include_router(router)

View File

@@ -1,15 +1,38 @@
# Build stage
# 多阶段构建api-gateway 生产镜像
# 用法docker build -t edu/api-gateway:latest -f services/api-gateway/Dockerfile .
# ============ Builder ============
FROM golang:1.22-alpine AS builder
WORKDIR /app
# git 与 ca-certificates 为 go mod 下载所需
RUN apk add --no-cache git ca-certificates
# 先拷依赖清单利用缓存
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 GOOS=linux go build -o api-gateway .
# Runtime stage
FROM alpine:3.20
RUN apk --no-cache add ca-certificates
# 拷源码并构建
COPY . .
# 静态编译CGO_DISABLED 便于 alpine 运行
RUN CGO_ENABLED=0 GOOS=linux go build -ldflags="-s -w" -o /app/bin/api-gateway ./main.go
# ============ Runtime ============
FROM alpine:3.20 AS runner
WORKDIR /app
COPY --from=builder /app/api-gateway .
RUN apk add --no-cache ca-certificates tzdata wget
# 非 root 用户
RUN addgroup -g 1001 -S app && adduser -S app -u 1001 -G app
COPY --from=builder /app/bin/api-gateway /app/api-gateway
USER app
EXPOSE 8080
CMD ["./api-gateway"]
# 健康检查
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
CMD wget --quiet --spider http://localhost:8080/healthz || exit 1
ENTRYPOINT ["/app/api-gateway"]

View File

@@ -71,14 +71,20 @@ docker build -t edu/api-gateway .
通过环境变量配置(见 `internal/config/config.go`
| 变量 | 默认值 | 说明 |
| --------------------- | --------------------- | -------------------- |
| `PORT` | 8080 | 监听端口 |
| `JWT_SECRET` | (必填) | HS256 签名密钥P1 |
| `JWT_PUBLIC_KEY` | P2 | RS256 公钥 |
| `CLASSES_SERVICE_URL` | http://localhost:3001 | classes 服务地址 |
| `RATE_LIMIT_RPS` | 10 | 每秒令牌数 |
| `RATE_LIMIT_BURST` | 20 | 突发容量 |
| 变量 | 默认值 | 说明 |
| ----------------------------- | --------------------- | ------------------------------------------------------ |
| `API_GATEWAY_PORT` | 8080 | 监听端口 |
| `JWT_SECRET` | (必填) | HS256 签名密钥P1 |
| `JWT_ISSUER` | next-edu-cloud | JWT 签发者 |
| `JWT_AUDIENCE` | next-edu-cloud | JWT 受众 |
| `DEV_MODE` | false | 开发模式旁路true 时接受 `Bearer dev-token`(仅本地) |
| `CLASSES_SERVICE_URL` | http://localhost:3001 | classes 服务地址 |
| `IAM_SERVICE_URL` | http://localhost:3002 | iam 服务地址 |
| `TEACHER_BFF_URL` | http://localhost:3003 | teacher-bff 服务地址 |
| `OTEL_EXPORTER_OTLP_ENDPOINT` | http://localhost:4318 | OpenTelemetry OTLP 端点 |
| `LOG_LEVEL` | info | 日志级别 |
> **生产环境警告**`DEV_MODE` 必须为 `false` 或不设。设为 `true` 会允许 `dev-token` 旁路鉴权并注入固定 admin 身份。
## 关联文档

View File

@@ -1,46 +1,64 @@
module github.com/edu-cloud/api-gateway
go 1.22.0
go 1.25.0
require (
github.com/gin-gonic/gin v1.10.0
github.com/gin-gonic/gin v1.12.0
github.com/golang-jwt/jwt/v5 v5.2.1
github.com/google/uuid v1.6.0
github.com/sony/gobreaker/v2 v2.1.0
go.opentelemetry.io/contrib/instrumentation/github.com/gin-gonic/gin/otelgin v0.69.0
go.opentelemetry.io/otel v1.44.0
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.44.0
go.opentelemetry.io/otel/sdk v1.44.0
)
require (
github.com/bytedance/sonic v1.11.6 // indirect
github.com/bytedance/sonic/loader v0.1.1 // indirect
github.com/cespare/xxhash/v2 v2.2.0 // indirect
github.com/cloudwego/base64x v0.1.4 // indirect
github.com/cloudwego/iasm v0.2.0 // indirect
github.com/bytedance/gopkg v0.1.4 // indirect
github.com/bytedance/sonic v1.15.1 // indirect
github.com/bytedance/sonic/loader v0.5.1 // indirect
github.com/cenkalti/backoff/v5 v5.0.3 // indirect
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/cloudwego/base64x v0.1.7 // indirect
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
github.com/gabriel-vasile/mimetype v1.4.3 // indirect
github.com/gin-contrib/sse v0.1.0 // indirect
github.com/gabriel-vasile/mimetype v1.4.13 // indirect
github.com/gin-contrib/sse v1.1.1 // indirect
github.com/go-logr/logr v1.4.3 // indirect
github.com/go-logr/stdr v1.2.2 // indirect
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/go-playground/validator/v10 v10.20.0 // indirect
github.com/go-playground/validator/v10 v10.30.2 // indirect
github.com/go-redsync/redsync/v4 v4.13.0 // indirect
github.com/goccy/go-json v0.10.2 // indirect
github.com/google/go-cmp v0.6.0 // indirect
github.com/goccy/go-json v0.10.6 // indirect
github.com/goccy/go-yaml v1.19.2 // indirect
github.com/grpc-ecosystem/grpc-gateway/v2 v2.29.0 // indirect
github.com/hashicorp/errwrap v1.1.0 // indirect
github.com/hashicorp/go-multierror v1.1.1 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/klauspost/cpuid/v2 v2.2.7 // indirect
github.com/klauspost/cpuid/v2 v2.3.0 // indirect
github.com/leodido/go-urn v1.4.0 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/mattn/go-isatty v0.0.22 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/pelletier/go-toml/v2 v2.2.2 // indirect
github.com/pelletier/go-toml/v2 v2.3.1 // indirect
github.com/quic-go/qpack v0.6.0 // indirect
github.com/quic-go/quic-go v0.59.1 // indirect
github.com/redis/go-redis/v9 v9.7.0 // indirect
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
github.com/ugorji/go/codec v1.2.12 // indirect
golang.org/x/arch v0.8.0 // indirect
golang.org/x/crypto v0.23.0 // indirect
golang.org/x/net v0.25.0 // indirect
golang.org/x/sys v0.20.0 // indirect
golang.org/x/text v0.15.0 // indirect
google.golang.org/protobuf v1.34.1 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
github.com/ugorji/go/codec v1.3.1 // indirect
go.mongodb.org/mongo-driver/v2 v2.6.0 // indirect
go.opentelemetry.io/auto/sdk v1.2.1 // indirect
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.44.0 // indirect
go.opentelemetry.io/otel/metric v1.44.0 // indirect
go.opentelemetry.io/otel/trace v1.44.0 // indirect
go.opentelemetry.io/proto/otlp v1.10.0 // indirect
golang.org/x/arch v0.27.0 // indirect
golang.org/x/crypto v0.52.0 // indirect
golang.org/x/net v0.55.0 // indirect
golang.org/x/sys v0.45.0 // indirect
golang.org/x/text v0.37.0 // indirect
google.golang.org/genproto/googleapis/api v0.0.0-20260526163538-3dc84a4a5aaa // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa // indirect
google.golang.org/grpc v1.81.1 // indirect
google.golang.org/protobuf v1.36.11 // indirect
)

View File

@@ -6,35 +6,42 @@ github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=
github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c=
github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA=
github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0=
github.com/bytedance/sonic v1.11.6 h1:oUp34TzMlL+OY1OUWxHqsdkgC/Zfc85zGqw9siXjrc0=
github.com/bytedance/sonic v1.11.6/go.mod h1:LysEHSvpvDySVdC2f87zGWf6CIKJcAvqab1ZaiQtds4=
github.com/bytedance/sonic/loader v0.1.1 h1:c+e5Pt1k/cy5wMveRDyk2X4B9hF4g7an8N3zCYjJFNM=
github.com/bytedance/sonic/loader v0.1.1/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU=
github.com/cespare/xxhash/v2 v2.2.0 h1:DC2CZ1Ep5Y4k3ZQ899DldepgrayRUGE6BBZ/cd9Cj44=
github.com/cespare/xxhash/v2 v2.2.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/cloudwego/base64x v0.1.4 h1:jwCgWpFanWmN8xoIUHa2rtzmkd5J2plF/dnLS6Xd/0Y=
github.com/cloudwego/base64x v0.1.4/go.mod h1:0zlkT4Wn5C6NdauXdJRhSKRlJvmclQ1hhJgA0rcu/8w=
github.com/cloudwego/iasm v0.2.0 h1:1KNIy1I1H9hNNFEEH3DVnI4UujN+1zjpuk6gwHLTssg=
github.com/cloudwego/iasm v0.2.0/go.mod h1:8rXZaNYT2n95jn+zTI1sDr+IgcD2GVs0nlbbQPiEFhY=
github.com/bytedance/gopkg v0.1.4 h1:oZnQwnX82KAIWb7033bEwtxvTqXcYMxDBaQxo5JJHWM=
github.com/bytedance/gopkg v0.1.4/go.mod h1:v1zWfPm21Fb+OsyXN2VAHdL6TBb2L88anLQgdyje6R4=
github.com/bytedance/sonic v1.15.1 h1:nJD5PmM0vY7J8CT6MxoqbVAAMhkSmV2HgRAUrrpLoOw=
github.com/bytedance/sonic v1.15.1/go.mod h1:mT2NbXunuaEbnZ+mRIX/vYqKISmgEuHFDI4UzmKx2SA=
github.com/bytedance/sonic/loader v0.5.1 h1:Ygpfa9zwRCCKSlrp5bBP/b/Xzc3VxsAW+5NIYXrOOpI=
github.com/bytedance/sonic/loader v0.5.1/go.mod h1:AR4NYCk5DdzZizZ5djGqQ92eEhCCcdf5x77udYiSJRo=
github.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM=
github.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw=
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/cloudwego/base64x v0.1.7 h1:NppS+Fgzg5ovhn4NkUXaDT3x9jldgH5ToMCqzBSi2zI=
github.com/cloudwego/base64x v0.1.7/go.mod h1:Cu1PV9zfrSf7ET2tIbWbbEy7jO7HHJ13q4X2SQ8aWYg=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
github.com/gabriel-vasile/mimetype v1.4.3 h1:in2uUcidCuFcDKtdcBxlR0rJ1+fsokWf+uqxgUFjbI0=
github.com/gabriel-vasile/mimetype v1.4.3/go.mod h1:d8uq/6HKRL6CGdk+aubisF/M5GcPfT7nKyLpA0lbSSk=
github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=
github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=
github.com/gin-gonic/gin v1.10.0 h1:nTuyha1TYqgedzytsKYqna+DfLos46nTv2ygFy86HFU=
github.com/gin-gonic/gin v1.10.0/go.mod h1:4PMNQiOhvDRa013RKVbsiNwoyezlm2rm0uX/T7kzp5Y=
github.com/gabriel-vasile/mimetype v1.4.13 h1:46nXokslUBsAJE/wMsp5gtO500a4F3Nkz9Ufpk2AcUM=
github.com/gabriel-vasile/mimetype v1.4.13/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s=
github.com/gin-contrib/sse v1.1.1 h1:uGYpNwTacv5R68bSGMapo62iLTRa9l5zxGCps4hK6ko=
github.com/gin-contrib/sse v1.1.1/go.mod h1:QXzuVkA0YO7o/gun03UI1Q+FTI8ZV/n5t03kIQAI89s=
github.com/gin-gonic/gin v1.12.0 h1:b3YAbrZtnf8N//yjKeU2+MQsh2mY5htkZidOM7O0wG8=
github.com/gin-gonic/gin v1.12.0/go.mod h1:VxccKfsSllpKshkBWgVgRniFFAzFb9csfngsqANjnLc=
github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=
github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
github.com/go-playground/validator/v10 v10.20.0 h1:K9ISHbSaI0lyB2eWMPJo+kOS/FBExVwjEviJTixqxL8=
github.com/go-playground/validator/v10 v10.20.0/go.mod h1:dbuPbCMFw/DrkbEynArYaCwl3amGuJotoKCe95atGMM=
github.com/go-playground/validator/v10 v10.30.2 h1:JiFIMtSSHb2/XBUbWM4i/MpeQm9ZK2xqPNk8vgvu5JQ=
github.com/go-playground/validator/v10 v10.30.2/go.mod h1:mAf2pIOVXjTEBrwUMGKkCWKKPs9NheYGabeB04txQSc=
github.com/go-redis/redis v6.15.9+incompatible h1:K0pv1D7EQUjfyoMql+r/jZqCLizCGKFlFgcHWWmHQjg=
github.com/go-redis/redis v6.15.9+incompatible/go.mod h1:NAIEuMOZ/fxfXJIrKDQDz8wamY7mA7PouImQ2Jvg6kA=
github.com/go-redis/redis/v7 v7.4.1 h1:PASvf36gyUpr2zdOUS/9Zqc80GbM+9BDyiJSJDDOrTI=
@@ -43,17 +50,23 @@ github.com/go-redis/redis/v8 v8.11.5 h1:AcZZR7igkdvfVmQTPnu9WE37LRrO/YrBH5zWyjDC
github.com/go-redis/redis/v8 v8.11.5/go.mod h1:gREzHqY1hg6oD9ngVRbLStwAWKhA0FEgq8Jd4h5lpwo=
github.com/go-redsync/redsync/v4 v4.13.0 h1:49X6GJfnbLGaIpBBREM/zA4uIMDXKAh1NDkvQ1EkZKA=
github.com/go-redsync/redsync/v4 v4.13.0/go.mod h1:HMW4Q224GZQz6x1Xc7040Yfgacukdzu7ifTDAKiyErQ=
github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=
github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
github.com/goccy/go-json v0.10.6 h1:p8HrPJzOakx/mn/bQtjgNjdTcN+/S6FcG2CTtQOrHVU=
github.com/goccy/go-json v0.10.6/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=
github.com/goccy/go-yaml v1.19.2 h1:PmFC1S6h8ljIz6gMRBopkjP1TVT7xuwrButHID66PoM=
github.com/goccy/go-yaml v1.19.2/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA=
github.com/golang-jwt/jwt/v5 v5.2.1 h1:OuVbFODueb089Lh128TAcimifWaLhJwVflnrgM17wHk=
github.com/golang-jwt/jwt/v5 v5.2.1/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk=
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
github.com/gomodule/redigo v1.8.9 h1:Sl3u+2BI/kk+VEatbj0scLdrFhjPmbxOc1myhDP41ws=
github.com/gomodule/redigo v1.8.9/go.mod h1:7ArFNvsTjH8GMMzB4uy1snslv2BwmginuMs06a1uzZE=
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/grpc-ecosystem/grpc-gateway/v2 v2.29.0 h1:5VipnvEpbqr2gA2VbM+nYVbkIF28c5ZQfqCBQ5g2xfk=
github.com/grpc-ecosystem/grpc-gateway/v2 v2.29.0/go.mod h1:Hyl3n6Twe1hvtd9XUXDec4pTvgMSEixRuQKPTMH2bNs=
github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=
github.com/hashicorp/errwrap v1.1.0 h1:OxrOeh75EUXMY8TBjag2fzXGZ40LB6IKw45YeGUDY2I=
github.com/hashicorp/errwrap v1.1.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=
@@ -61,23 +74,25 @@ github.com/hashicorp/go-multierror v1.1.1 h1:H5DkEtf6CXdFp0N0Em5UCwQpXMWke8IA0+l
github.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9/fmwbPZ6JB6eMoM=
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
github.com/klauspost/cpuid/v2 v2.2.7 h1:ZWSB3igEs+d0qvnxR/ZBzXVmxkgt8DdzP6m9pfuVLDM=
github.com/klauspost/cpuid/v2 v2.2.7/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws=
github.com/knz/go-libedit v1.10.1/go.mod h1:MZTVkCWyz0oBc7JOWP3wNAzd002ZbM/5hgShxwh4x8M=
github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y=
github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-isatty v0.0.22 h1:j8l17JJ9i6VGPUFUYoTUKPSgKe/83EYU2zBC7YNKMw4=
github.com/mattn/go-isatty v0.0.22/go.mod h1:ZXfXG4SQHsB/w3ZeOYbR0PrPwLy+n6xiMrJlRFqopa4=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
github.com/pelletier/go-toml/v2 v2.2.2 h1:aYUidT7k73Pcl9nb2gScu7NSrKCSHIDE89b3+6Wq+LM=
github.com/pelletier/go-toml/v2 v2.2.2/go.mod h1:1t835xjRzz80PqgE6HHgN2JOsmgYu/h4qDAS4n929Rs=
github.com/pelletier/go-toml/v2 v2.3.1 h1:MYEvvGnQjeNkRF1qUuGolNtNExTDwct51yp7olPtrEc=
github.com/pelletier/go-toml/v2 v2.3.1/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/quic-go/qpack v0.6.0 h1:g7W+BMYynC1LbYLSqRt8PBg5Tgwxn214ZZR34VIOjz8=
github.com/quic-go/qpack v0.6.0/go.mod h1:lUpLKChi8njB4ty2bFLX2x4gzDqXwUpaO1DP9qMDZII=
github.com/quic-go/quic-go v0.59.1 h1:0Gmua0HW1Tv7ANR7hUYwRyD0MG5OJfgvYSZasGZzBic=
github.com/quic-go/quic-go v0.59.1/go.mod h1:upnsH4Ju1YkqpLXC305eW3yDZ4NfnNbmQRCMWS58IKU=
github.com/redis/go-redis/v9 v9.7.0 h1:HhLSs+B6O021gwzl+locl0zEDnyNkxMtf/Z3NNBMa9E=
github.com/redis/go-redis/v9 v9.7.0/go.mod h1:f6zhXITC7JUJIlPEiBOTXxJgPLdZcA93GewI7inzyWw=
github.com/redis/rueidis v1.0.19 h1:s65oWtotzlIFN8eMPhyYwxlwLR1lUdhza2KtWprKYSo=
@@ -89,42 +104,73 @@ github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSS
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
github.com/stvp/tempredis v0.0.0-20181119212430-b82af8480203 h1:QVqDTf3h2WHt08YuiTGPZLls0Wq99X9bWd0Q5ZSBesM=
github.com/stvp/tempredis v0.0.0-20181119212430-b82af8480203/go.mod h1:oqN97ltKNihBbwlX8dLpwxCl3+HnXKV/R0e+sRLd9C8=
github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
github.com/ugorji/go/codec v1.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65EE=
github.com/ugorji/go/codec v1.2.12/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg=
github.com/ugorji/go/codec v1.3.1 h1:waO7eEiFDwidsBN6agj1vJQ4AG7lh2yqXyOXqhgQuyY=
github.com/ugorji/go/codec v1.3.1/go.mod h1:pRBVtBSKl77K30Bv8R2P+cLSGaTtex6fsA2Wjqmfxj4=
github.com/yuin/gopher-lua v1.1.1 h1:kYKnWBjvbNP4XLT3+bPEwAXJx262OhaHDWDVOPjL46M=
github.com/yuin/gopher-lua v1.1.1/go.mod h1:GBR0iDaNXjAgGg9zfCvksxSRnQx76gclCIb7kdAd1Pw=
golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=
golang.org/x/arch v0.8.0 h1:3wRIsP3pM4yUptoR96otTUOXI367OS0+c9eeRi9doIc=
golang.org/x/arch v0.8.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys=
golang.org/x/crypto v0.23.0 h1:dIJU/v2J8Mdglj/8rJ6UUOM3Zc9zLZxVZwwxMooUSAI=
golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8=
golang.org/x/net v0.25.0 h1:d/OCCoBEUq33pjydKrGQhw7IlUPI2Oylr+8qLx49kac=
golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM=
golang.org/x/sync v0.3.0 h1:ftCYgMx6zT/asHUrPw8BLLscYtGznsLAnjq5RH9P66E=
golang.org/x/sync v0.3.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y=
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.20.0 h1:Od9JTbYCk261bKm4M/mw7AklTlFYIa0bIp9BgSm1S8Y=
golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/text v0.15.0 h1:h1V/4gjBv8v9cjcR6+AR5+/cIYK5N/WAgiv4xlsEtAk=
golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
google.golang.org/protobuf v1.34.1 h1:9ddQBjfCyZPOHPUiPxpYESBLc+T8P3E+Vo4IbKZgFWg=
google.golang.org/protobuf v1.34.1/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
go.mongodb.org/mongo-driver/v2 v2.6.0 h1:b9sJOYrkmt4l8bY43ZenFBcPlhYIjaOfYHLtbB/5qi8=
go.mongodb.org/mongo-driver/v2 v2.6.0/go.mod h1:yOI9kBsufol30iFsl1slpdq1I0eHPzybRWdyYUs8K/0=
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
go.opentelemetry.io/contrib/instrumentation/github.com/gin-gonic/gin/otelgin v0.69.0 h1:u5gsfBL8t1Km4ROhQKAs0cA0t9CzUE7nfkASj/UjAtI=
go.opentelemetry.io/contrib/instrumentation/github.com/gin-gonic/gin/otelgin v0.69.0/go.mod h1:W6FFYCZQuntC5hxVesXpu7Ppd9sT0a84njildAijc+k=
go.opentelemetry.io/contrib/propagators/b3 v1.44.0 h1:1IFH4oFKK8KupzIelCl3u+bkxpGRps1oWRjQI2+TTWs=
go.opentelemetry.io/contrib/propagators/b3 v1.44.0/go.mod h1:JqWFXsc7VDaqIyubFhEd2cPHqsrzqP0Lvn783SUwyro=
go.opentelemetry.io/otel v1.44.0 h1:JjwHmHpA4iZ3wBxluu2fbbE7j4kqlE8jXyAyPXH7HqU=
go.opentelemetry.io/otel v1.44.0/go.mod h1:BMgjTHL9WPRlRjL2oZCBTL4whCGtXch2H4BhOPIAyYc=
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.44.0 h1:4YsVu3B8+3qtWYYrsUYgn0OG78pN0rnNPRGX4SbokQI=
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.44.0/go.mod h1:+wnlSn0mD1ADVMe3v9Z/WIaiz6q6gL2J/ejaAmdmv80=
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.44.0 h1:lgh3PiVrRUWMLOVSkQicxzZll5NjF1r+AtsX1XRIHw0=
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.44.0/go.mod h1:5Cnhth3m/AgOeTgE3ex12pPmiu/gGtZit03kSzx9X7s=
go.opentelemetry.io/otel/exporters/stdout/stdouttrace v1.44.0 h1:bl2S7Ubua0Nms+D/gAmznQTd4dxxMA93aKbcpKqiTCs=
go.opentelemetry.io/otel/exporters/stdout/stdouttrace v1.44.0/go.mod h1:L0hRV50XdVIODHUfWEqGRCXQvj2rV82STVo12FMFBU0=
go.opentelemetry.io/otel/metric v1.44.0 h1:1w0gILTcHdr3YI+ixLyjemwrVnsMURbTZFrSYCdDdmc=
go.opentelemetry.io/otel/metric v1.44.0/go.mod h1:8O7hanEPBNgEMmybD3s2VBKcgWOCsA6tzHBPODAiquo=
go.opentelemetry.io/otel/sdk v1.44.0 h1:nHYwb9lK+fJPU/dnT6s7W7Z8itMWyqrnVfbheVYrZ58=
go.opentelemetry.io/otel/sdk v1.44.0/go.mod h1:Osuydd3Se74nqjAKxid74N5eC+jfEqfTegHRnq58oK0=
go.opentelemetry.io/otel/sdk/metric v1.44.0 h1:3LlKgI+VjbVsjNRFZJZAJ30WjXC5VkNRks6si09iEfI=
go.opentelemetry.io/otel/sdk/metric v1.44.0/go.mod h1:5B5pMARnXxKhltooO4xUuCBorl65a4EpnTalObqOigA=
go.opentelemetry.io/otel/trace v1.44.0 h1:jxF5CsGYCe74MCRx2X4g7WsY/VBKRqqpNvXlX/6gtIk=
go.opentelemetry.io/otel/trace v1.44.0/go.mod h1:oLl1jrMQAVo6v3GAggN+1VH9VIz9iUSvW53sW1Q8PIE=
go.opentelemetry.io/proto/otlp v1.10.0 h1:IQRWgT5srOCYfiWnpqUYz9CVmbO8bFmKcwYxpuCSL2g=
go.opentelemetry.io/proto/otlp v1.10.0/go.mod h1:/CV4QoCR/S9yaPj8utp3lvQPoqMtxXdzn7ozvvozVqk=
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
go.uber.org/mock v0.6.0 h1:hyF9dfmbgIX5EfOdasqLsWD6xqpNZlXblLB/Dbnwv3Y=
go.uber.org/mock v0.6.0/go.mod h1:KiVJ4BqZJaMj4svdfmHM0AUx4NJYO8ZNpPnZn1Z+BBU=
golang.org/x/arch v0.27.0 h1:0WNVcR8u9yFz8j5FvdHpgwNp3FS5U4guYdzHwEiGjoU=
golang.org/x/arch v0.27.0/go.mod h1:0X+GdSIP+kL5wPmpK7sdkEVTt2XoYP0cSjQSbZBwOi8=
golang.org/x/crypto v0.52.0 h1:RMs7fP2rXdep0CftQlK8Uf+kibLm7qkCcradZWYz988=
golang.org/x/crypto v0.52.0/go.mod h1:1QgfPxDqh0T2M/elOJtp9RvuR95kVjir0e6/BvEmGbc=
golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8=
golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww=
golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4=
golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
golang.org/x/sys v0.45.0 h1:dO4czNzziLiiXplLQgBCEpCvXQ3dnkn0SdaZSYdQ+FY=
golang.org/x/sys v0.45.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc=
golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38=
gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4=
gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E=
google.golang.org/genproto/googleapis/api v0.0.0-20260526163538-3dc84a4a5aaa h1:Kjn0N0tCrDgiAFW+lGO4JZ3ck44CehvJQMAwj9QF0G8=
google.golang.org/genproto/googleapis/api v0.0.0-20260526163538-3dc84a4a5aaa/go.mod h1:q4lMZS6kskjT5HvCPrnnypcDPVJqT/f4nfxmkE7gryY=
google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa h1:mZHHdPZl0dbGHCflZgAq/Q468DWVFcU2whhB2KAo8fk=
google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8=
google.golang.org/grpc v1.81.1 h1:VnnIIZ88UzOOKLukQi+ImGz8O1Wdp8nAGGnvOfEIWQQ=
google.golang.org/grpc v1.81.1/go.mod h1:xGH9GfzOyMTGIOXBJmXt+BX/V0kcdQbdcuwQ/zNw42I=
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
nullprogram.com/x/optparse v1.0.0/go.mod h1:KdyPE+Igbe0jQUrVfMqDMeJQIJZEuyV7pjYmp6pbG50=
rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4=

View File

@@ -13,8 +13,14 @@ type Config struct {
ClassesServiceURL string
IamServiceURL string
TeacherBffURL string
CoreEduServiceURL string
ContentServiceURL string
DataAnaServiceURL string
MsgServiceURL string
AiServiceURL string
OTLPEndpoint string
LogLevel string
DevMode bool
}
func Load() *Config {
@@ -26,8 +32,14 @@ func Load() *Config {
ClassesServiceURL: getEnv("CLASSES_SERVICE_URL", "http://localhost:3001"),
IamServiceURL: getEnv("IAM_SERVICE_URL", "http://localhost:3002"),
TeacherBffURL: getEnv("TEACHER_BFF_URL", "http://localhost:3003"),
CoreEduServiceURL: getEnv("CORE_EDU_SERVICE_URL", "http://localhost:3004"),
ContentServiceURL: getEnv("CONTENT_SERVICE_URL", "http://localhost:3005"),
DataAnaServiceURL: getEnv("DATA_ANA_SERVICE_URL", "http://localhost:3006"),
MsgServiceURL: getEnv("MSG_SERVICE_URL", "http://localhost:3007"),
AiServiceURL: getEnv("AI_SERVICE_URL", "http://localhost:3008"),
OTLPEndpoint: getEnv("OTEL_EXPORTER_OTLP_ENDPOINT", "http://localhost:4318"),
LogLevel: getEnv("LOG_LEVEL", "info"),
DevMode: getEnvBool("DEV_MODE", false),
}
}
@@ -46,3 +58,12 @@ func getEnvInt(key string, fallback int) int {
}
return fallback
}
func getEnvBool(key string, fallback bool) bool {
if v := os.Getenv(key); v != "" {
if b, err := strconv.ParseBool(v); err == nil {
return b
}
}
return fallback
}

View File

@@ -1,4 +1,4 @@
package middleware
package middleware
import (
"net/http"
@@ -10,6 +10,20 @@ import (
"github.com/google/uuid"
)
// publicPaths 是无需鉴权的公开路径(精确匹配,基于去掉 /api/v1 前缀后的路径)
var publicPaths = map[string]bool{
"/iam/register": true,
"/iam/login": true,
"/iam/refresh": true,
}
// isPublicPath 判断请求路径是否属于公开路径(无需鉴权)
// 匹配规则:去掉 /api/v1 前缀后,与 publicPaths 精确匹配
func isPublicPath(path string) bool {
stripped := strings.TrimPrefix(path, "/api/v1")
return publicPaths[stripped]
}
// AuthMiddleware 验证 JWT 并注入用户信息到请求头
// P1 用 HS256P2 改 RS256IAM 签发)
func AuthMiddleware(cfg *config.Config) gin.HandlerFunc {
@@ -20,6 +34,12 @@ func AuthMiddleware(cfg *config.Config) gin.HandlerFunc {
return
}
// 公开路径白名单register/login/refresh 无需鉴权)
if isPublicPath(c.Request.URL.Path) {
c.Next()
return
}
authHeader := c.GetHeader("Authorization")
if authHeader == "" {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
@@ -44,6 +64,15 @@ func AuthMiddleware(cfg *config.Config) gin.HandlerFunc {
return
}
// 开发模式旁路DEV_MODE=true 时接受 "dev-token",注入开发用户
// 仅用于本地联调,生产环境必须关闭 DEV_MODE
if cfg.DevMode && tokenStr == "dev-token" {
c.Request.Header.Set("x-user-id", "dev-user")
c.Request.Header.Set("x-user-roles", "teacher,admin")
c.Next()
return
}
token, err := jwt.Parse(tokenStr, func(t *jwt.Token) (interface{}, error) {
if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, jwt.ErrSignatureInvalid

View File

@@ -0,0 +1,73 @@
package observability
import (
"context"
"log"
"net/url"
"time"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp"
"go.opentelemetry.io/otel/propagation"
"go.opentelemetry.io/otel/sdk/resource"
sdktrace "go.opentelemetry.io/otel/sdk/trace"
semconv "go.opentelemetry.io/otel/semconv/v1.26.0"
)
// InitTracer 初始化 OpenTelemetry tracer.
//
// endpoint 为 "http://host:port" 格式(如 "http://localhost:4318"
// 为空时跳过初始化tracing disabled
//
// 返回 shutdown 函数,应在服务退出时调用以 flush 待发送 span.
func InitTracer(serviceName, endpoint string) func() {
if endpoint == "" {
log.Println("OTEL endpoint not set, tracing disabled")
return func() {}
}
u, err := url.Parse(endpoint)
if err != nil || u.Host == "" {
log.Printf("invalid OTEL endpoint %q, tracing disabled", endpoint)
return func() {}
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
exporter, err := otlptracehttp.New(ctx,
otlptracehttp.WithEndpoint(u.Host),
otlptracehttp.WithInsecure(),
)
if err != nil {
log.Printf("failed to create OTLP exporter: %v, tracing disabled", err)
return func() {}
}
res, err := resource.New(ctx,
resource.WithAttributes(semconv.ServiceName(serviceName)),
)
if err != nil {
log.Printf("failed to create resource: %v", err)
return func() {}
}
tp := sdktrace.NewTracerProvider(
sdktrace.WithBatcher(exporter),
sdktrace.WithResource(res),
)
otel.SetTracerProvider(tp)
otel.SetTextMapPropagator(propagation.NewCompositeTextMapPropagator(
propagation.TraceContext{},
propagation.Baggage{},
))
log.Printf("OpenTelemetry tracer initialized for %s (endpoint=%s)", serviceName, u.Host)
return func() {
shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := tp.Shutdown(shutdownCtx); err != nil {
log.Printf("failed to shutdown tracer: %v", err)
}
}
}

View File

@@ -1,56 +0,0 @@
package routing
import (
"github.com/edu-cloud/api-gateway/internal/config"
"github.com/edu-cloud/api-gateway/internal/middleware"
"github.com/edu-cloud/api-gateway/internal/proxy"
"github.com/gin-gonic/gin"
)
// Setup 配置路由
func Setup(cfg *config.Config) *gin.Engine {
gin.SetMode(gin.ReleaseMode)
r := gin.New()
// 中间件
r.Use(middleware.RequestIDMiddleware())
r.Use(gin.Recovery())
// 健康检查(无需鉴权)
r.GET("/healthz", healthz)
// API v1 组(需要鉴权)
api := r.Group("/api/v1")
api.Use(middleware.AuthMiddleware(cfg))
{
// classes 服务路由
classesProxy, err := proxy.NewProxy(cfg.ClassesServiceURL)
if err != nil {
panic("failed to create classes proxy: " + err.Error())
}
api.Any("/classes/*path", proxy.ProxyHandler(classesProxy))
// IAM 服务路由(身份与访问管理)
iamProxy, err := proxy.NewProxy(cfg.IamServiceURL)
if err != nil {
panic("failed to create iam proxy: " + err.Error())
}
api.Any("/iam/*path", proxy.ProxyHandler(iamProxy))
// Teacher BFF 路由(教师聚合层)
bffProxy, err := proxy.NewProxy(cfg.TeacherBffURL)
if err != nil {
panic("failed to create teacher-bff proxy: " + err.Error())
}
api.Any("/teacher/*path", proxy.ProxyHandler(bffProxy))
}
return r
}
func healthz(c *gin.Context) {
c.JSON(200, gin.H{
"status": "ok",
"service": "api-gateway",
})
}

View File

@@ -12,8 +12,10 @@ import (
"github.com/edu-cloud/api-gateway/internal/config"
"github.com/edu-cloud/api-gateway/internal/health"
"github.com/edu-cloud/api-gateway/internal/middleware"
"github.com/edu-cloud/api-gateway/internal/observability"
"github.com/edu-cloud/api-gateway/internal/proxy"
"github.com/gin-gonic/gin"
"go.opentelemetry.io/contrib/instrumentation/github.com/gin-gonic/gin/otelgin"
)
// maxBodyBytes 请求体大小上限10MB
@@ -21,21 +23,29 @@ const maxBodyBytes int64 = 10 * 1024 * 1024
func main() {
cfg := config.Load()
// 初始化 OpenTelemetry tracerendpoint 为空时自动跳过)
tracerShutdown := observability.InitTracer("api-gateway", cfg.OTLPEndpoint)
defer tracerShutdown()
gin.SetMode(gin.ReleaseMode)
r := gin.New()
// 关闭尾斜杠重定向:避免 Next.js rewrites 代理时 /api/v1/classes → 301 → /api/v1/classes/ 循环
r.RedirectTrailingSlash = false
// 全局中间件(按顺序注册)
// 1. panic 恢复(最外层,捕获后续所有中间件与 handler 的 panic
r.Use(middleware.Recovery())
// 2. 请求 ID 注入
// 2. OpenTelemetry 自动埋点HTTP 请求/响应 span
r.Use(otelgin.Middleware("api-gateway"))
// 3. 请求 ID 注入
r.Use(middleware.RequestID())
// 3. 跨域
// 4. 跨域
r.Use(middleware.CORS())
// 4. 安全响应头
// 5. 安全响应头
r.Use(middleware.SecurityHeaders())
// 5. 请求体大小限制
// 6. 请求体大小限制
r.Use(middleware.RequestBodyLimit(maxBodyBytes))
// 6. 限流(每 IP 100 rps突发 20
// 7. 限流(每 IP 100 rps突发 20
r.Use(middleware.RateLimit(100, 20))
// 健康检查路由(无需鉴权,在 Auth 之前)
@@ -50,25 +60,89 @@ func main() {
api.Use(middleware.AuthMiddleware(cfg))
{
// classes 服务路由
// 注同时注册无尾斜杠与通配符两条路由。RedirectTrailingSlash=false 时,
// Gin 不会自动把 /classes 跳到 /classes/,所以两条都要显式注册。
classesProxy, err := proxy.NewProxy(cfg.ClassesServiceURL)
if err != nil {
log.Fatalf("failed to create classes proxy: %v", err)
}
api.Any("/classes/*path", proxy.ProxyHandler(classesProxy))
classesHandler := proxy.ProxyHandler(classesProxy)
api.Any("/classes", classesHandler)
api.Any("/classes/*path", classesHandler)
// IAM 服务路由(身份与访问管理)
iamProxy, err := proxy.NewProxy(cfg.IamServiceURL)
if err != nil {
log.Fatalf("failed to create iam proxy: %v", err)
}
api.Any("/iam/*path", proxy.ProxyHandler(iamProxy))
iamHandler := proxy.ProxyHandler(iamProxy)
api.Any("/iam", iamHandler)
api.Any("/iam/*path", iamHandler)
// Teacher BFF 路由(教师聚合层)
bffProxy, err := proxy.NewProxy(cfg.TeacherBffURL)
if err != nil {
log.Fatalf("failed to create teacher-bff proxy: %v", err)
}
api.Any("/teacher/*path", proxy.ProxyHandler(bffProxy))
bffHandler := proxy.ProxyHandler(bffProxy)
api.Any("/teacher", bffHandler)
api.Any("/teacher/*path", bffHandler)
// core-edu 服务路由(考试/作业/成绩)
// 注:同时注册无尾斜杠与通配符两条路由,与 classes/iam/teacher 一致。
coreEduProxy, err := proxy.NewProxy(cfg.CoreEduServiceURL)
if err != nil {
log.Fatalf("failed to create core-edu proxy: %v", err)
}
coreEduHandler := proxy.ProxyHandler(coreEduProxy)
api.Any("/exams", coreEduHandler)
api.Any("/exams/*path", coreEduHandler)
api.Any("/homework", coreEduHandler)
api.Any("/homework/*path", coreEduHandler)
api.Any("/grades", coreEduHandler)
api.Any("/grades/*path", coreEduHandler)
// content 服务路由(教材/章节/知识点/题库)
contentProxy, err := proxy.NewProxy(cfg.ContentServiceURL)
if err != nil {
log.Fatalf("failed to create content proxy: %v", err)
}
contentHandler := proxy.ProxyHandler(contentProxy)
api.Any("/textbooks", contentHandler)
api.Any("/textbooks/*path", contentHandler)
api.Any("/chapters", contentHandler)
api.Any("/chapters/*path", contentHandler)
api.Any("/knowledge-points", contentHandler)
api.Any("/knowledge-points/*path", contentHandler)
api.Any("/questions", contentHandler)
api.Any("/questions/*path", contentHandler)
// msg 服务路由(通知/消息)
msgProxy, err := proxy.NewProxy(cfg.MsgServiceURL)
if err != nil {
log.Fatalf("failed to create msg proxy: %v", err)
}
msgHandler := proxy.ProxyHandler(msgProxy)
api.Any("/notifications", msgHandler)
api.Any("/notifications/*path", msgHandler)
// ai 服务路由AI 聊天/生成/优化)
aiProxy, err := proxy.NewProxy(cfg.AiServiceURL)
if err != nil {
log.Fatalf("failed to create ai proxy: %v", err)
}
aiHandler := proxy.ProxyHandler(aiProxy)
api.Any("/ai", aiHandler)
api.Any("/ai/*path", aiHandler)
// data-ana 服务路由(学情诊断/错题本)
dataAnaProxy, err := proxy.NewProxy(cfg.DataAnaServiceURL)
if err != nil {
log.Fatalf("failed to create data-ana proxy: %v", err)
}
dataAnaHandler := proxy.ProxyHandler(dataAnaProxy)
api.Any("/analytics", dataAnaHandler)
api.Any("/analytics/*path", dataAnaHandler)
}
srv := &http.Server{

View File

@@ -10,26 +10,29 @@
"test": "vitest run",
"test:watch": "vitest",
"test:coverage": "vitest run --coverage",
"lint": "eslint src --ext .ts",
"lint": "eslint src",
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@nestjs/common": "^10.4.0",
"@nestjs/core": "^10.4.0",
"@nestjs/platform-express": "^10.4.0",
"@opentelemetry/api": "^1.9.0",
"@opentelemetry/auto-instrumentations-node": "^0.50.0",
"@opentelemetry/exporter-trace-otlp-http": "^0.53.0",
"@opentelemetry/sdk-node": "^0.53.0",
"drizzle-orm": "^0.31.0",
"ioredis": "^5.11.1",
"kafkajs": "^2.2.0",
"mysql2": "^3.11.0",
"pino": "^9.4.0",
"pino-http": "^10.0.0",
"prom-client": "^15.1.0",
"@opentelemetry/api": "^1.9.0",
"@opentelemetry/sdk-node": "^0.53.0",
"@opentelemetry/auto-instrumentations-node": "^0.50.0",
"@opentelemetry/exporter-trace-otlp-http": "^0.53.0",
"zod": "^3.23.0",
"uuid": "^10.0.0",
"reflect-metadata": "^0.2.2",
"rxjs": "^7.8.0"
"rxjs": "^7.8.0",
"typeorm": "^1.0.0",
"uuid": "^10.0.0",
"zod": "^3.23.0"
},
"devDependencies": {
"@nestjs/cli": "^10.4.0",
@@ -41,8 +44,8 @@
"drizzle-kit": "^0.24.0",
"eslint": "^9.10.0",
"pino-pretty": "^11.2.0",
"tsx": "^4.19.0",
"typescript": "^5.6.0",
"vitest": "^2.1.0",
"tsx": "^4.19.0"
"vitest": "^2.1.0"
}
}

View File

@@ -1,16 +1,10 @@
import { Module } from '@nestjs/common';
import { ClassesController } from './classes.controller.js';
import { ClassesService } from './classes.service.js';
import { ClassesRepository } from './classes.repository.js';
import { Module } from "@nestjs/common";
import { ClassesController } from "./classes.controller.js";
import { ClassesService } from "./classes.service.js";
import { ClassesRepository } from "./classes.repository.js";
@Module({
controllers: [ClassesController],
providers: [
ClassesService,
{
provide: ClassesRepository,
useFactory: () => new ClassesRepository(),
},
],
providers: [ClassesService, ClassesRepository],
})
export class ClassesModule {}

View File

@@ -1,11 +1,17 @@
import { v4 as uuidv4 } from 'uuid';
import { ClassesRepository } from './classes.repository.js';
import { ValidationError, NotFoundError } from '../shared/errors/application-error.js';
import type { CreateClassDto, UpdateClassDto } from './classes.dto.js';
import type { Class, NewClass } from './classes.schema.js';
import { v4 as uuidv4 } from "uuid";
import { Inject } from "@nestjs/common";
import { ClassesRepository } from "./classes.repository.js";
import {
ValidationError,
NotFoundError,
} from "../shared/errors/application-error.js";
import type { CreateClassDto, UpdateClassDto } from "./classes.dto.js";
import type { Class, NewClass } from "./classes.schema.js";
export class ClassesService {
constructor(private readonly repository: ClassesRepository) {}
constructor(
@Inject(ClassesRepository) private readonly repository: ClassesRepository,
) {}
async create(dto: CreateClassDto): Promise<Class> {
const newClass: NewClass = {
@@ -18,7 +24,7 @@ export class ClassesService {
async getById(id: string): Promise<Class> {
const result = await this.repository.findById(id);
if (!result) {
throw new NotFoundError('Class', id);
throw new NotFoundError("Class", id);
}
return result;
}
@@ -29,11 +35,11 @@ export class ClassesService {
async update(id: string, dto: UpdateClassDto): Promise<Class> {
if (Object.keys(dto).length === 0) {
throw new ValidationError('No fields to update');
throw new ValidationError("No fields to update");
}
const result = await this.repository.update(id, dto);
if (!result) {
throw new NotFoundError('Class', id);
throw new NotFoundError("Class", id);
}
return result;
}
@@ -41,7 +47,7 @@ export class ClassesService {
async delete(id: string): Promise<void> {
const existing = await this.repository.findById(id);
if (!existing) {
throw new NotFoundError('Class', id);
throw new NotFoundError("Class", id);
}
await this.repository.delete(id);
}

View File

@@ -1,31 +1,39 @@
import 'reflect-metadata';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module.js';
import { GlobalErrorFilter } from './shared/errors/global-error.filter.js';
import { initTracer, shutdownTracer } from './shared/observability/tracer.js';
import { env } from './config/env.js';
import { logger } from './shared/observability/logger.js';
import "reflect-metadata";
import { NestFactory } from "@nestjs/core";
import { AppModule } from "./app.module.js";
import { GlobalErrorFilter } from "./shared/errors/global-error.filter.js";
import { initTracer, shutdownTracer } from "./shared/observability/tracer.js";
import { env } from "./config/env.js";
import { logger } from "./shared/observability/logger.js";
import { metricsRegistry } from "./shared/observability/metrics.js";
async function bootstrap(): Promise<void> {
initTracer();
const app = await NestFactory.create(AppModule, {
logger: ['log', 'error', 'warn'],
logger: ["log", "error", "warn"],
});
app.useGlobalFilters(new GlobalErrorFilter());
app.enableShutdownHooks();
await app.listen(env.PORT);
logger.info({ port: env.PORT }, 'Classes service started');
// Prometheus 指标端点:不鉴权,供 Prometheus 抓取。
// 返回 register.metrics()Promise<string>,含 Content-Type text/plain; version=0.0.4; charset=utf-8
app.getHttpAdapter().get("/metrics", async (req, res) => {
res.set("Content-Type", metricsRegistry.contentType);
res.end(await metricsRegistry.metrics());
});
process.on('SIGTERM', async () => {
await app.listen(env.PORT);
logger.info({ port: env.PORT }, "Classes service started");
process.on("SIGTERM", async () => {
await app.close();
await shutdownTracer();
});
}
bootstrap().catch((err: unknown) => {
logger.error({ err }, 'Failed to start classes service');
logger.error({ err }, "Failed to start classes service");
process.exit(1);
});

View File

@@ -1,5 +1,5 @@
import { Module } from '@nestjs/common';
import { HealthController } from './health.controller';
import { Module } from "@nestjs/common";
import { HealthController } from "./health.controller.js";
/**
* 健康检查模块。

View File

@@ -1,24 +1,28 @@
import promClient from 'prom-client';
import promClient from "prom-client";
const registry = new promClient.Registry();
// 修复:在本地 registry 上设置默认标签(原代码误用全局 register
registry.setDefaultLabels({ service: 'classes' });
registry.setDefaultLabels({ service: "classes" });
registry.registerMetric(
new promClient.Counter({
name: 'classes_requests_total',
help: 'Total number of class requests',
labelNames: ['method', 'endpoint', 'status'],
name: "classes_requests_total",
help: "Total number of class requests",
labelNames: ["method", "endpoint", "status"],
}),
);
registry.registerMetric(
new promClient.Histogram({
name: 'classes_request_duration_seconds',
help: 'Class request duration in seconds',
labelNames: ['method', 'endpoint'],
name: "classes_request_duration_seconds",
help: "Class request duration in seconds",
labelNames: ["method", "endpoint"],
buckets: [0.01, 0.05, 0.1, 0.3, 0.5, 1, 3, 5],
}),
);
// 自动收集 Node.js 进程级指标CPU/内存/事件循环/GC等
// 这些指标无需业务代码埋点prom-client 自动采集
promClient.collectDefaultMetrics({ register: registry });
export { registry as metricsRegistry };

View File

@@ -1,6 +1,7 @@
import { NodeSDK } from '@opentelemetry/sdk-node';
import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';
import { env } from '../../config/env.js';
import { getNodeAutoInstrumentations } from "@opentelemetry/auto-instrumentations-node";
import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-http";
import { NodeSDK } from "@opentelemetry/sdk-node";
import { env } from "../../config/env.js";
let sdk: NodeSDK | null = null;
@@ -8,14 +9,15 @@ export function initTracer(): void {
if (!env.OTEL_EXPORTER_OTLP_ENDPOINT) return;
sdk = new NodeSDK({
serviceName: 'classes',
serviceName: "classes",
traceExporter: new OTLPTraceExporter({
url: `${env.OTEL_EXPORTER_OTLP_ENDPOINT}/v1/traces`,
}),
instrumentations: [getNodeAutoInstrumentations()],
});
sdk.start();
console.log('Tracer initialized');
console.log("Tracer initialized with auto-instrumentations");
}
export async function shutdownTracer(): Promise<void> {

View File

@@ -8,7 +8,7 @@
"build": "nest build",
"start": "node dist/main.js",
"test": "vitest run",
"lint": "eslint src --ext .ts",
"lint": "eslint src",
"typecheck": "tsc --noEmit"
},
"dependencies": {
@@ -26,7 +26,8 @@
"reflect-metadata": "^0.2.2",
"rxjs": "^7.8.0",
"@opentelemetry/sdk-node": "^0.55.0",
"@opentelemetry/exporter-trace-otlp-http": "^0.55.0"
"@opentelemetry/exporter-trace-otlp-http": "^0.55.0",
"@opentelemetry/auto-instrumentations-node": "^0.55.0"
},
"devDependencies": {
"@nestjs/cli": "^10.4.0",

View File

@@ -1,7 +1,17 @@
import { Module } from '@nestjs/common';
import { TextbooksModule } from './textbooks/textbooks.module.js';
import { Module } from "@nestjs/common";
import { TextbooksModule } from "./textbooks/textbooks.module.js";
import { ChaptersModule } from "./chapters/chapters.module.js";
import { KnowledgePointsModule } from "./knowledge-points/knowledge-points.module.js";
import { QuestionsModule } from "./questions/questions.module.js";
import { HealthModule } from "./shared/health/health.module.js";
@Module({
imports: [TextbooksModule],
imports: [
TextbooksModule,
ChaptersModule,
KnowledgePointsModule,
QuestionsModule,
HealthModule,
],
})
export class AppModule {}

View File

@@ -0,0 +1,61 @@
import {
Body,
Controller,
Delete,
Get,
Param,
Post,
Put,
} from "@nestjs/common";
import {
ChaptersService,
type CreateChapterInput,
type UpdateChapterInput,
} from "./chapters.service.js";
import type { Chapter } from "./chapters.schema.js";
@Controller("chapters")
export class ChaptersController {
constructor(private readonly service: ChaptersService) {}
@Post()
async create(
@Body() body: CreateChapterInput,
): Promise<{ success: true; data: { id: string } }> {
const result = await this.service.createChapter(body);
return { success: true, data: result };
}
@Get("textbook/:textbookId")
async listByTextbook(
@Param("textbookId") textbookId: string,
): Promise<{ success: true; data: Chapter[] }> {
const data = await this.service.listChaptersByTextbook(textbookId);
return { success: true, data };
}
@Get(":id")
async getById(
@Param("id") id: string,
): Promise<{ success: true; data: Chapter }> {
const data = await this.service.getChapter(id);
return { success: true, data };
}
@Put(":id")
async update(
@Param("id") id: string,
@Body() body: UpdateChapterInput,
): Promise<{ success: true; data: { success: true } }> {
await this.service.updateChapter(id, body);
return { success: true, data: { success: true } };
}
@Delete(":id")
async remove(
@Param("id") id: string,
): Promise<{ success: true; data: { success: true } }> {
await this.service.deleteChapter(id);
return { success: true, data: { success: true } };
}
}

View File

@@ -0,0 +1,10 @@
import { Module } from "@nestjs/common";
import { ChaptersController } from "./chapters.controller.js";
import { ChaptersService } from "./chapters.service.js";
@Module({
controllers: [ChaptersController],
providers: [ChaptersService],
exports: [ChaptersService],
})
export class ChaptersModule {}

View File

@@ -0,0 +1,35 @@
import { eq } from "drizzle-orm";
import { db } from "../config/database.js";
import { chapters, type Chapter, type NewChapter } from "./chapters.schema.js";
export class ChaptersRepository {
async findById(id: string): Promise<Chapter | undefined> {
const [result] = await db
.select()
.from(chapters)
.where(eq(chapters.id, id))
.limit(1);
return result;
}
async findByTextbookId(textbookId: string): Promise<Chapter[]> {
return db
.select()
.from(chapters)
.where(eq(chapters.textbookId, textbookId));
}
async create(data: NewChapter): Promise<void> {
await db.insert(chapters).values(data);
}
async update(id: string, data: Partial<NewChapter>): Promise<void> {
await db.update(chapters).set(data).where(eq(chapters.id, id));
}
async delete(id: string): Promise<void> {
await db.delete(chapters).where(eq(chapters.id, id));
}
}
export const chaptersRepository = new ChaptersRepository();

View File

@@ -0,0 +1,5 @@
export {
chapters,
type Chapter,
type NewChapter,
} from "../textbooks/textbooks.schema.js";

View File

@@ -0,0 +1,62 @@
import { randomUUID } from "node:crypto";
import { Injectable } from "@nestjs/common";
import { chaptersRepository } from "./chapters.repository.js";
import type { Chapter } from "./chapters.schema.js";
import {
NotFoundError,
ValidationError,
} from "../shared/errors/application-error.js";
export interface CreateChapterInput {
textbookId: string;
title: string;
order: number;
parentId?: string;
}
export interface UpdateChapterInput {
title?: string;
order?: number;
parentId?: string;
}
@Injectable()
export class ChaptersService {
async createChapter(input: CreateChapterInput): Promise<{ id: string }> {
if (!input.textbookId || !input.title || input.order === undefined) {
throw new ValidationError("textbookId, title, order are required");
}
const id = randomUUID();
await chaptersRepository.create({
id,
textbookId: input.textbookId,
title: input.title,
order: input.order,
parentId: input.parentId,
});
return { id };
}
async getChapter(id: string): Promise<Chapter> {
const chapter = await chaptersRepository.findById(id);
if (!chapter) {
throw new NotFoundError("Chapter", id);
}
return chapter;
}
async listChaptersByTextbook(textbookId: string): Promise<Chapter[]> {
return chaptersRepository.findByTextbookId(textbookId);
}
async updateChapter(id: string, data: UpdateChapterInput): Promise<void> {
await this.getChapter(id);
await chaptersRepository.update(id, data);
}
async deleteChapter(id: string): Promise<void> {
await this.getChapter(id);
await chaptersRepository.delete(id);
}
}

View File

@@ -1,24 +1,16 @@
import { drizzle } from 'drizzle-orm/mysql2';
import mysql from 'mysql2/promise';
import { env } from './env.js';
import { drizzle } from "drizzle-orm/mysql2";
import mysql from "mysql2/promise";
import { env } from "./env.js";
let pool: mysql.Pool | null = null;
const pool = mysql.createPool({
uri: env.DATABASE_URL,
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0,
});
export function getDb() {
if (!pool) {
pool = mysql.createPool({
uri: env.DATABASE_URL,
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0,
});
}
return drizzle(pool);
}
export const db = drizzle(pool);
export async function closeDb(): Promise<void> {
if (pool) {
await pool.end();
pool = null;
}
await pool.end();
}

View File

@@ -1,17 +1,22 @@
import { z } from 'zod';
import { z } from "zod";
const envSchema = z.object({
PORT: z.string().default('3005'),
PORT: z.string().default("3005"),
DATABASE_URL: z.string().url(),
REDIS_URL: z.string().url().optional(),
NEO4J_URL: z.string().url(),
NEO4J_PASSWORD: z.string(),
ES_URL: z.string().url(),
JWT_SECRET: z.string(),
JWT_ISSUER: z.string().default('next-edu-cloud'),
NEO4J_URL: z.string().url().optional(),
NEO4J_PASSWORD: z.string().optional(),
ES_URL: z.string().url().optional(),
JWT_SECRET: z.string().optional(),
JWT_ISSUER: z.string().default("next-edu-cloud"),
OTEL_EXPORTER_OTLP_ENDPOINT: z.string().url().optional(),
LOG_LEVEL: z.enum(['fatal', 'error', 'warn', 'info', 'debug', 'trace']).default('info'),
NODE_ENV: z.enum(['development', 'production', 'test']).default('development'),
LOG_LEVEL: z
.enum(["fatal", "error", "warn", "info", "debug", "trace"])
.default("info"),
NODE_ENV: z
.enum(["development", "production", "test"])
.default("development"),
DEV_MODE: z.string().optional().default("false"),
});
export type Env = z.infer<typeof envSchema>;
@@ -19,8 +24,11 @@ export type Env = z.infer<typeof envSchema>;
export function loadEnv(): Env {
const result = envSchema.safeParse(process.env);
if (!result.success) {
console.error('❌ Invalid environment variables:', result.error.flatten().fieldErrors);
throw new Error('Invalid environment configuration');
console.error(
"❌ Invalid environment variables:",
result.error.flatten().fieldErrors,
);
throw new Error("Invalid environment configuration");
}
return result.data;
}

View File

@@ -1,11 +1,38 @@
import neo4j from 'neo4j-driver';
import { env } from './env.js';
import neo4j from "neo4j-driver";
import type { Driver, Session } from "neo4j-driver";
import { env } from "./env.js";
export const neo4jDriver = neo4j.driver(
env.NEO4J_URL,
neo4j.auth.basic('neo4j', env.NEO4J_PASSWORD)
);
// Neo4j driver 创建为惰性初始化:未配置 NEO4J_URL / NEO4J_PASSWORD 时
// driver 保持 null服务仍可正常启动。所有依赖 Neo4j 的查询在
// driver 为 null 时返回空结果或抛出可控错误,不会阻塞主流程。
let driver: Driver | null = null;
try {
if (env.NEO4J_URL && env.NEO4J_PASSWORD) {
driver = neo4j.driver(
env.NEO4J_URL,
neo4j.auth.basic("neo4j", env.NEO4J_PASSWORD),
// 连接超时 3sNeo4j 不可用时快速失败,避免拖慢 HTTP 响应
{ connectionTimeout: 3000, maxConnectionLifetime: 60_000 },
);
}
} catch (err) {
console.warn(
"Neo4j driver init failed, running without Neo4j:",
err instanceof Error ? err.message : String(err),
);
driver = null;
}
export function getNeo4jSession(): Session | null {
if (!driver) {
return null;
}
return driver.session();
}
export async function closeNeo4j(): Promise<void> {
await neo4jDriver.close();
if (driver) {
await driver.close();
}
}

View File

@@ -0,0 +1,79 @@
import {
Body,
Controller,
Delete,
Get,
Param,
Post,
Put,
} from "@nestjs/common";
import {
KnowledgePointsService,
type CreateKnowledgePointInput,
type UpdateKnowledgePointInput,
type PrerequisiteNode,
} from "./knowledge-points.service.js";
import type { KnowledgePoint } from "./knowledge-points.schema.js";
@Controller("knowledge-points")
export class KnowledgePointsController {
constructor(private readonly service: KnowledgePointsService) {}
@Post()
async create(
@Body() body: CreateKnowledgePointInput,
): Promise<{ success: true; data: { id: string } }> {
const result = await this.service.createKnowledgePoint(body);
return { success: true, data: result };
}
@Get("chapter/:chapterId")
async listByChapter(
@Param("chapterId") chapterId: string,
): Promise<{ success: true; data: KnowledgePoint[] }> {
const data = await this.service.listByChapter(chapterId);
return { success: true, data };
}
@Get(":id/prerequisites")
async getPrerequisites(
@Param("id") id: string,
): Promise<{ success: true; data: PrerequisiteNode[] }> {
const data = await this.service.getPrerequisites(id);
return { success: true, data };
}
@Get(":id")
async getById(
@Param("id") id: string,
): Promise<{ success: true; data: KnowledgePoint }> {
const data = await this.service.getKnowledgePoint(id);
return { success: true, data };
}
@Post(":id/prerequisites/:prerequisiteId")
async addPrerequisite(
@Param("id") id: string,
@Param("prerequisiteId") prerequisiteId: string,
): Promise<{ success: true; data: { success: true } }> {
await this.service.addPrerequisite(id, prerequisiteId);
return { success: true, data: { success: true } };
}
@Put(":id")
async update(
@Param("id") id: string,
@Body() body: UpdateKnowledgePointInput,
): Promise<{ success: true; data: { success: true } }> {
await this.service.updateKnowledgePoint(id, body);
return { success: true, data: { success: true } };
}
@Delete(":id")
async remove(
@Param("id") id: string,
): Promise<{ success: true; data: { success: true } }> {
await this.service.deleteKnowledgePoint(id);
return { success: true, data: { success: true } };
}
}

View File

@@ -0,0 +1,10 @@
import { Module } from "@nestjs/common";
import { KnowledgePointsController } from "./knowledge-points.controller.js";
import { KnowledgePointsService } from "./knowledge-points.service.js";
@Module({
controllers: [KnowledgePointsController],
providers: [KnowledgePointsService],
exports: [KnowledgePointsService],
})
export class KnowledgePointsModule {}

View File

@@ -0,0 +1,42 @@
import { eq } from "drizzle-orm";
import { db } from "../config/database.js";
import {
knowledgePoints,
type KnowledgePoint,
type NewKnowledgePoint,
} from "./knowledge-points.schema.js";
export class KnowledgePointsRepository {
async findById(id: string): Promise<KnowledgePoint | undefined> {
const [result] = await db
.select()
.from(knowledgePoints)
.where(eq(knowledgePoints.id, id))
.limit(1);
return result;
}
async findByChapterId(chapterId: string): Promise<KnowledgePoint[]> {
return db
.select()
.from(knowledgePoints)
.where(eq(knowledgePoints.chapterId, chapterId));
}
async create(data: NewKnowledgePoint): Promise<void> {
await db.insert(knowledgePoints).values(data);
}
async update(id: string, data: Partial<NewKnowledgePoint>): Promise<void> {
await db
.update(knowledgePoints)
.set(data)
.where(eq(knowledgePoints.id, id));
}
async delete(id: string): Promise<void> {
await db.delete(knowledgePoints).where(eq(knowledgePoints.id, id));
}
}
export const knowledgePointsRepository = new KnowledgePointsRepository();

View File

@@ -0,0 +1,5 @@
export {
knowledgePoints,
type KnowledgePoint,
type NewKnowledgePoint,
} from "../textbooks/textbooks.schema.js";

View File

@@ -0,0 +1,164 @@
import { randomUUID } from "node:crypto";
import { Injectable, Logger } from "@nestjs/common";
import { knowledgePointsRepository } from "./knowledge-points.repository.js";
import type { KnowledgePoint } from "./knowledge-points.schema.js";
import { getNeo4jSession } from "../config/neo4j.js";
import {
InternalError,
NotFoundError,
ValidationError,
} from "../shared/errors/application-error.js";
export interface CreateKnowledgePointInput {
chapterId: string;
title: string;
description?: string;
}
export interface UpdateKnowledgePointInput {
title?: string;
description?: string;
}
export interface PrerequisiteNode {
id: string;
title: string;
}
@Injectable()
export class KnowledgePointsService {
private readonly logger = new Logger(KnowledgePointsService.name);
async createKnowledgePoint(
input: CreateKnowledgePointInput,
): Promise<{ id: string }> {
if (!input.chapterId || !input.title) {
throw new ValidationError("chapterId, title are required");
}
const id = randomUUID();
await knowledgePointsRepository.create({
id,
chapterId: input.chapterId,
title: input.title,
description: input.description,
});
// Neo4j创建知识点节点。非阻塞——失败仅记录日志不影响 MySQL 写入。
await this.safeCreateNode(id, input.title);
return { id };
}
async getKnowledgePoint(id: string): Promise<KnowledgePoint> {
const kp = await knowledgePointsRepository.findById(id);
if (!kp) {
throw new NotFoundError("KnowledgePoint", id);
}
return kp;
}
async listByChapter(chapterId: string): Promise<KnowledgePoint[]> {
return knowledgePointsRepository.findByChapterId(chapterId);
}
async updateKnowledgePoint(
id: string,
data: UpdateKnowledgePointInput,
): Promise<void> {
await this.getKnowledgePoint(id);
await knowledgePointsRepository.update(id, data);
}
async deleteKnowledgePoint(id: string): Promise<void> {
await this.getKnowledgePoint(id);
await knowledgePointsRepository.delete(id);
}
async getPrerequisites(
knowledgePointId: string,
): Promise<PrerequisiteNode[]> {
const session = getNeo4jSession();
if (!session) {
return [];
}
try {
const result = await session.executeRead((tx) =>
tx.run(
`MATCH (kp:KnowledgePoint {id: $id})<-[:PREREQUISITE_OF*1..5]-(prereq)
RETURN prereq.id as id, prereq.title as title`,
{ id: knowledgePointId },
),
);
return result.records.map((r): PrerequisiteNode => {
const rawId: unknown = r.get("id");
const rawTitle: unknown = r.get("title");
return {
id: typeof rawId === "string" ? rawId : String(rawId),
title: typeof rawTitle === "string" ? rawTitle : String(rawTitle),
};
});
} catch (err) {
this.logger.warn(
`Neo4j getPrerequisites failed: ${err instanceof Error ? err.message : String(err)}`,
);
return [];
} finally {
await session.close();
}
}
async addPrerequisite(id: string, prerequisiteId: string): Promise<void> {
if (id === prerequisiteId) {
throw new ValidationError(
"A knowledge point cannot be a prerequisite of itself",
);
}
// 先校验两个知识点在 MySQL 中都存在
await this.getKnowledgePoint(id);
await this.getKnowledgePoint(prerequisiteId);
const session = getNeo4jSession();
if (!session) {
throw new InternalError(
"Neo4j is not available, cannot add prerequisite",
);
}
try {
await session.executeWrite((tx) =>
tx.run(
`MATCH (kp:KnowledgePoint {id: $kpId}), (prereq:KnowledgePoint {id: $prereqId})
MERGE (prereq)-[:PREREQUISITE_OF]->(kp)`,
{ kpId: id, prereqId: prerequisiteId },
),
);
} finally {
await session.close();
}
}
private async safeCreateNode(id: string, title: string): Promise<void> {
const session = getNeo4jSession();
if (!session) {
return;
}
try {
await session.executeWrite((tx) =>
tx.run("MERGE (kp:KnowledgePoint {id: $id, title: $title})", {
id,
title,
}),
);
} catch (err) {
this.logger.warn(
`Neo4j createNode failed (non-blocking): ${err instanceof Error ? err.message : String(err)}`,
);
} finally {
await session.close();
}
}
}

View File

@@ -1,31 +1,54 @@
import 'reflect-metadata';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module.js';
import { GlobalErrorFilter } from './shared/errors/global-error.filter.js';
import { initTracer, shutdownTracer } from './shared/observability/tracer.js';
import { env } from './config/env.js';
import { logger } from './shared/observability/logger.js';
import "reflect-metadata";
import { NestFactory } from "@nestjs/core";
import { AppModule } from "./app.module.js";
import { GlobalErrorFilter } from "./shared/errors/global-error.filter.js";
import { initTracer, shutdownTracer } from "./shared/observability/tracer.js";
import { env } from "./config/env.js";
import { closeDb } from "./config/database.js";
import { closeNeo4j } from "./config/neo4j.js";
import { logger } from "./shared/observability/logger.js";
import { metricsRegistry } from "./shared/observability/metrics.js";
async function bootstrap(): Promise<void> {
initTracer();
const app = await NestFactory.create(AppModule, {
logger: ['log', 'error', 'warn'],
logger: ["log", "error", "warn"],
});
app.useGlobalFilters(new GlobalErrorFilter());
app.enableShutdownHooks();
await app.listen(env.PORT);
logger.info({ port: env.PORT }, 'Content service started');
// Prometheus 指标端点:不鉴权,供 Prometheus 抓取。
// 返回 register.metrics()Promise<string>,含 Content-Type text/plain; version=0.0.4; charset=utf-8
app.getHttpAdapter().get("/metrics", async (req, res) => {
res.set("Content-Type", metricsRegistry.contentType);
res.end(await metricsRegistry.metrics());
});
process.on('SIGTERM', async () => {
await app.close();
await app.listen(env.PORT);
logger.info({ port: env.PORT }, "Content service started");
process.on("SIGTERM", async () => {
logger.info("SIGTERM received, shutting down gracefully...");
await closeNeo4j();
await closeDb();
await shutdownTracer();
await app.close();
process.exit(0);
});
process.on("SIGINT", async () => {
logger.info("SIGINT received, shutting down gracefully...");
await closeNeo4j();
await closeDb();
await shutdownTracer();
await app.close();
process.exit(0);
});
}
bootstrap().catch((err: unknown) => {
logger.error({ err }, 'Failed to start content service');
logger.error({ err }, "Failed to start content service");
process.exit(1);
});

View File

@@ -0,0 +1,61 @@
import {
Body,
Controller,
Delete,
Get,
Param,
Post,
Put,
} from "@nestjs/common";
import {
QuestionsService,
type CreateQuestionInput,
type UpdateQuestionInput,
} from "./questions.service.js";
import type { Question } from "./questions.schema.js";
@Controller("questions")
export class QuestionsController {
constructor(private readonly service: QuestionsService) {}
@Post()
async create(
@Body() body: CreateQuestionInput,
): Promise<{ success: true; data: { id: string } }> {
const result = await this.service.createQuestion(body);
return { success: true, data: result };
}
@Get("knowledge-point/:knowledgePointId")
async listByKnowledgePoint(
@Param("knowledgePointId") knowledgePointId: string,
): Promise<{ success: true; data: Question[] }> {
const data = await this.service.listByKnowledgePoint(knowledgePointId);
return { success: true, data };
}
@Get(":id")
async getById(
@Param("id") id: string,
): Promise<{ success: true; data: Question }> {
const data = await this.service.getQuestion(id);
return { success: true, data };
}
@Put(":id")
async update(
@Param("id") id: string,
@Body() body: UpdateQuestionInput,
): Promise<{ success: true; data: { success: true } }> {
await this.service.updateQuestion(id, body);
return { success: true, data: { success: true } };
}
@Delete(":id")
async remove(
@Param("id") id: string,
): Promise<{ success: true; data: { success: true } }> {
await this.service.deleteQuestion(id);
return { success: true, data: { success: true } };
}
}

View File

@@ -0,0 +1,10 @@
import { Module } from "@nestjs/common";
import { QuestionsController } from "./questions.controller.js";
import { QuestionsService } from "./questions.service.js";
@Module({
controllers: [QuestionsController],
providers: [QuestionsService],
exports: [QuestionsService],
})
export class QuestionsModule {}

View File

@@ -0,0 +1,39 @@
import { eq } from "drizzle-orm";
import { db } from "../config/database.js";
import {
questions,
type Question,
type NewQuestion,
} from "./questions.schema.js";
export class QuestionsRepository {
async findById(id: string): Promise<Question | undefined> {
const [result] = await db
.select()
.from(questions)
.where(eq(questions.id, id))
.limit(1);
return result;
}
async findByKnowledgePointId(knowledgePointId: string): Promise<Question[]> {
return db
.select()
.from(questions)
.where(eq(questions.knowledgePointId, knowledgePointId));
}
async create(data: NewQuestion): Promise<void> {
await db.insert(questions).values(data);
}
async update(id: string, data: Partial<NewQuestion>): Promise<void> {
await db.update(questions).set(data).where(eq(questions.id, id));
}
async delete(id: string): Promise<void> {
await db.delete(questions).where(eq(questions.id, id));
}
}
export const questionsRepository = new QuestionsRepository();

View File

@@ -0,0 +1,23 @@
import {
mysqlTable,
char,
varchar,
text,
int,
timestamp,
} from "drizzle-orm/mysql-core";
export const questions = mysqlTable("content_questions", {
id: char("id", { length: 36 }).notNull().primaryKey(),
knowledgePointId: char("knowledge_point_id", { length: 36 }).notNull(),
type: varchar("type", { length: 50 }).notNull(),
content: text("content").notNull(),
answer: text("answer"),
explanation: text("explanation"),
difficulty: int("difficulty").default(3),
createdAt: timestamp("created_at").notNull().defaultNow(),
updatedAt: timestamp("updated_at").notNull().defaultNow().onUpdateNow(),
});
export type Question = typeof questions.$inferSelect;
export type NewQuestion = typeof questions.$inferInsert;

View File

@@ -0,0 +1,83 @@
import { randomUUID } from "node:crypto";
import { Injectable } from "@nestjs/common";
import { questionsRepository } from "./questions.repository.js";
import type { Question } from "./questions.schema.js";
import {
NotFoundError,
ValidationError,
} from "../shared/errors/application-error.js";
export interface CreateQuestionInput {
knowledgePointId: string;
type: string;
content: string;
answer?: string;
explanation?: string;
difficulty?: number;
}
export interface UpdateQuestionInput {
type?: string;
content?: string;
answer?: string;
explanation?: string;
difficulty?: number;
}
const VALID_TYPES = new Set([
"single_choice",
"multiple_choice",
"short_answer",
"essay",
]);
@Injectable()
export class QuestionsService {
async createQuestion(input: CreateQuestionInput): Promise<{ id: string }> {
if (!input.knowledgePointId || !input.type || !input.content) {
throw new ValidationError("knowledgePointId, type, content are required");
}
if (!VALID_TYPES.has(input.type)) {
throw new ValidationError(
`Invalid question type: ${input.type}. Must be one of: ${[...VALID_TYPES].join(", ")}`,
);
}
const id = randomUUID();
await questionsRepository.create({
id,
knowledgePointId: input.knowledgePointId,
type: input.type,
content: input.content,
answer: input.answer,
explanation: input.explanation,
difficulty: input.difficulty,
});
return { id };
}
async getQuestion(id: string): Promise<Question> {
const question = await questionsRepository.findById(id);
if (!question) {
throw new NotFoundError("Question", id);
}
return question;
}
async listByKnowledgePoint(knowledgePointId: string): Promise<Question[]> {
return questionsRepository.findByKnowledgePointId(knowledgePointId);
}
async updateQuestion(id: string, data: UpdateQuestionInput): Promise<void> {
await this.getQuestion(id);
if (data.type && !VALID_TYPES.has(data.type)) {
throw new ValidationError(`Invalid question type: ${data.type}`);
}
await questionsRepository.update(id, data);
}
async deleteQuestion(id: string): Promise<void> {
await this.getQuestion(id);
await questionsRepository.delete(id);
}
}

View File

@@ -1,7 +1,12 @@
import { Catch, ExceptionFilter, ArgumentsHost, HttpException, Logger } from '@nestjs/common';
import { Request, Response } from 'express';
import { ZodError } from 'zod';
import { ApplicationError } from './application-error.js';
import {
Catch,
ExceptionFilter,
ArgumentsHost,
HttpException,
Logger,
} from "@nestjs/common";
import { ZodError } from "zod";
import { ApplicationError } from "./application-error.js";
@Catch()
export class GlobalErrorFilter implements ExceptionFilter {
@@ -9,10 +14,13 @@ export class GlobalErrorFilter implements ExceptionFilter {
catch(exception: unknown, host: ArgumentsHost): void {
const ctx = host.switchToHttp();
const response = ctx.getResponse<Response>();
const request = ctx.getRequest<Request>();
// NestJS HttpArgumentsHost 的 getResponse/getRequest 返回 express 实例,
// 但 content 服务未引入 @types/express此处按 core-edu 模式不显式标注类型。
const response = ctx.getResponse();
const request = ctx.getRequest();
const traceId = (request.headers['x-request-id'] as string | undefined) ?? 'unknown';
const traceId =
(request.headers["x-request-id"] as string | undefined) ?? "unknown";
let statusCode = 500;
let body: Record<string, unknown>;
@@ -27,8 +35,8 @@ export class GlobalErrorFilter implements ExceptionFilter {
body = {
success: false,
error: {
code: 'CONTENT_VALIDATION_ERROR',
message: 'Validation failed',
code: "CONTENT_VALIDATION_ERROR",
message: "Validation failed",
details: exception.flatten(),
traceId,
},
@@ -40,7 +48,7 @@ export class GlobalErrorFilter implements ExceptionFilter {
body = {
success: false,
error: {
code: 'HTTP_ERROR',
code: "HTTP_ERROR",
message,
traceId,
},
@@ -53,8 +61,8 @@ export class GlobalErrorFilter implements ExceptionFilter {
body = {
success: false,
error: {
code: 'INTERNAL_ERROR',
message: 'An unexpected error occurred',
code: "INTERNAL_ERROR",
message: "An unexpected error occurred",
traceId,
},
};
@@ -63,14 +71,17 @@ export class GlobalErrorFilter implements ExceptionFilter {
response.status(statusCode).json(body);
}
private extractHttpMessage(res: string | object, exception: HttpException): string {
if (typeof res === 'string') {
private extractHttpMessage(
res: string | object,
exception: HttpException,
): string {
if (typeof res === "string") {
return res;
}
if (res && typeof res === 'object' && 'message' in res) {
if (res && typeof res === "object" && "message" in res) {
// 从 HttpException 响应体收窄类型NestJS 约定包含 message 字段)
const msg = (res as { message: unknown }).message;
return typeof msg === 'string' ? msg : exception.message;
return typeof msg === "string" ? msg : exception.message;
}
return exception.message;
}

View File

@@ -1,46 +1,41 @@
import { Controller, Get, HttpException, HttpStatus } from '@nestjs/common';
import { DataSource } from 'typeorm';
import { Controller, Get, HttpException, HttpStatus } from "@nestjs/common";
import { sql } from "drizzle-orm";
import { db } from "../../config/database.js";
const SERVICE_NAME = 'content';
const SERVICE_NAME = "content";
/**
* 健康检查端点。
*
* - GET /healthzliveness仅返回进程存活不检查依赖。
* - GET /readyzreadiness检查 DB 连接,失败返回 503。
*
* 不需要鉴权,必须在路由白名单中放行。本控制器内容在 iam / core-edu /
* content / msg / classes 五个 NestJS 服务中一致,仅 SERVICE_NAME 不同。
*/
@Controller()
export class HealthController {
constructor(private readonly dataSource: DataSource) {}
@Get('healthz')
@Get("healthz")
liveness(): { status: string; service: string; timestamp: string } {
return {
status: 'ok',
status: "ok",
service: SERVICE_NAME,
timestamp: new Date().toISOString(),
};
}
@Get('readyz')
async readiness(): Promise<{ status: string; service: string; timestamp: string }> {
@Get("readyz")
async readiness(): Promise<{
status: string;
service: string;
timestamp: string;
}> {
try {
await this.dataSource.query('SELECT 1');
await db.execute(sql`SELECT 1`);
return {
status: 'ok',
status: "ok",
service: SERVICE_NAME,
timestamp: new Date().toISOString(),
};
} catch (error) {
throw new HttpException(
{
status: 'error',
status: "error",
service: SERVICE_NAME,
timestamp: new Date().toISOString(),
error: error instanceof Error ? error.message : 'database unreachable',
error:
error instanceof Error ? error.message : "database unreachable",
},
HttpStatus.SERVICE_UNAVAILABLE,
);

View File

@@ -1,22 +1,6 @@
import { Module } from '@nestjs/common';
import { HealthController } from './health.controller';
import { Module } from "@nestjs/common";
import { HealthController } from "./health.controller.js";
/**
* 健康检查模块。
*
* 集成说明(不修改 app.module.ts仅在 README 注释说明):
*
* 在 `app.module.ts` 的 imports 数组中加入 `HealthModule`
*
* ```ts
* import { HealthModule } from './shared/health/health.module';
*
* @Module({ imports: [ ..., HealthModule ], ... })
* export class AppModule {}
* ```
*
* DataSource 由 `TypeOrmModule.forRoot(...)` 提供,本模块无需额外 provider。
*/
@Module({
controllers: [HealthController],
})

View File

@@ -1,63 +1,24 @@
import { Inject, Injectable, Logger, OnApplicationShutdown, OnModuleInit } from '@nestjs/common';
import { DataSource } from 'typeorm';
import type { Redis } from 'ioredis';
import type { Producer } from 'kafkajs';
import { Injectable, Logger } from "@nestjs/common";
import { closeDb } from "../../config/database.js";
import { closeNeo4j } from "../../config/neo4j.js";
const SERVICE_NAME = 'content';
const SERVICE_NAME = "content";
/**
* 优雅停机服务。
*
* 信号处理由 NestJS 在 `app.listen` 之前调用 `app.enableShutdownHooks()`
* 触发SIGTERM / SIGINTNestJS 会依次调用 OnApplicationShutdown 钩子。
* K8s 配置 `terminationGracePeriodSeconds=60` 给予足够时间清理。
*
* 关闭顺序Kafka producer → Redis → DataSource。
* 先停外部消息生产避免新事件,再关缓存,最后关 DB。
* 注content 服务额外使用 S3/MinIO 客户端,其连接由 SDK 内部管理,无需显式关闭。
*
* 集成说明(不修改 app.module.ts仅在 README 注释说明):
* - 在 `app.module.ts` 的 providers 中加入 `LifecycleService`。
* - 在 `main.ts` 中 `app.listen` 之前调用 `app.enableShutdownHooks()`。
*
* 依赖注入 token 约定(需与各服务 provider 注册一致):
* - DataSource由 `TypeOrmModule.forRoot()` 提供。
* - 'REDIS_CLIENT':需在对应模块注册 `{ provide: 'REDIS_CLIENT', useFactory: ... }`。
* - 'KAFKA_PRODUCER':需在对应模块注册 `{ provide: 'KAFKA_PRODUCER', useFactory: ... }`。
*/
@Injectable()
export class LifecycleService implements OnModuleInit, OnApplicationShutdown {
export class LifecycleService {
private readonly logger = new Logger(LifecycleService.name);
constructor(
private readonly dataSource: DataSource,
@Inject('REDIS_CLIENT') private readonly redis: Redis,
@Inject('KAFKA_PRODUCER') private readonly kafkaProducer: Producer,
) {}
onModuleInit(): void {
this.logger.log(`service ${SERVICE_NAME} module initialized`);
}
async onApplicationShutdown(signal?: string): Promise<void> {
this.logger.log(
`service ${SERVICE_NAME} shutting down (signal=${signal ?? 'unknown'})`,
`service ${SERVICE_NAME} shutting down (signal=${signal ?? "unknown"})`,
);
await this.safeDisconnect('kafka producer', () => this.kafkaProducer.disconnect());
await this.safeDisconnect('redis', () => this.redis.quit());
await this.safeDisconnect('datasource', () => this.dataSource.destroy());
this.logger.log(`service ${SERVICE_NAME} shutdown complete`);
}
private async safeDisconnect(name: string, fn: () => Promise<unknown>): Promise<void> {
try {
await fn();
this.logger.log(`${name} closed`);
await closeNeo4j();
await closeDb();
this.logger.log(`service ${SERVICE_NAME} shutdown complete`);
} catch (error) {
this.logger.error(
`${name} close failed: ${error instanceof Error ? error.message : String(error)}`,
`shutdown failed: ${error instanceof Error ? error.message : String(error)}`,
);
}
}

View File

@@ -1,24 +1,28 @@
import promClient from 'prom-client';
import promClient from "prom-client";
const registry = new promClient.Registry();
// 修复:在本地 registry 上设置默认标签(原代码误用全局 register
registry.setDefaultLabels({ service: 'content' });
registry.setDefaultLabels({ service: "content" });
registry.registerMetric(
new promClient.Counter({
name: 'content_requests_total',
help: 'Total number of content requests',
labelNames: ['method', 'endpoint', 'status'],
name: "content_requests_total",
help: "Total number of content requests",
labelNames: ["method", "endpoint", "status"],
}),
);
registry.registerMetric(
new promClient.Histogram({
name: 'content_request_duration_seconds',
help: 'Content request duration in seconds',
labelNames: ['method', 'endpoint'],
name: "content_request_duration_seconds",
help: "Content request duration in seconds",
labelNames: ["method", "endpoint"],
buckets: [0.01, 0.05, 0.1, 0.3, 0.5, 1, 3, 5],
}),
);
// 自动收集 Node.js 进程级指标CPU/内存/事件循环/GC等
// 这些指标无需业务代码埋点prom-client 自动采集
promClient.collectDefaultMetrics({ register: registry });
export { registry as metricsRegistry };

View File

@@ -1,6 +1,7 @@
import { NodeSDK } from '@opentelemetry/sdk-node';
import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';
import { env } from '../../config/env.js';
import { getNodeAutoInstrumentations } from "@opentelemetry/auto-instrumentations-node";
import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-http";
import { NodeSDK } from "@opentelemetry/sdk-node";
import { env } from "../../config/env.js";
let sdk: NodeSDK | null = null;
@@ -8,14 +9,15 @@ export function initTracer(): void {
if (!env.OTEL_EXPORTER_OTLP_ENDPOINT) return;
sdk = new NodeSDK({
serviceName: 'content',
serviceName: "content",
traceExporter: new OTLPTraceExporter({
url: `${env.OTEL_EXPORTER_OTLP_ENDPOINT}/v1/traces`,
}),
instrumentations: [getNodeAutoInstrumentations()],
});
sdk.start();
console.log('Tracer initialized');
console.log("Tracer initialized with auto-instrumentations");
}
export async function shutdownTracer(): Promise<void> {

View File

@@ -1,25 +1,59 @@
import { Body, Controller, Get, Param, Post } from '@nestjs/common';
import { TextbooksService } from './textbooks.service.js';
import {
Body,
Controller,
Delete,
Get,
Param,
Post,
Put,
} from "@nestjs/common";
import {
TextbooksService,
type CreateTextbookInput,
type UpdateTextbookInput,
} from "./textbooks.service.js";
import type { Textbook } from "./textbooks.schema.js";
@Controller('textbooks')
@Controller("textbooks")
export class TextbooksController {
constructor(private readonly service: TextbooksService) {}
@Post()
async create(@Body() body: unknown) {
const result = await this.service.create(body as any);
async create(
@Body() body: CreateTextbookInput,
): Promise<{ success: true; data: { id: string } }> {
const result = await this.service.create(body);
return { success: true, data: result };
}
@Get()
async list() {
const result = await this.service.list();
return { success: true, data: result };
async list(): Promise<{ success: true; data: Textbook[] }> {
const data = await this.service.list();
return { success: true, data };
}
@Get(':id')
async getById(@Param('id') id: string) {
const result = await this.service.getById(id);
return { success: true, data: result };
@Get(":id")
async getById(
@Param("id") id: string,
): Promise<{ success: true; data: Textbook }> {
const data = await this.service.getById(id);
return { success: true, data };
}
@Put(":id")
async update(
@Param("id") id: string,
@Body() body: UpdateTextbookInput,
): Promise<{ success: true; data: { success: true } }> {
await this.service.update(id, body);
return { success: true, data: { success: true } };
}
@Delete(":id")
async remove(
@Param("id") id: string,
): Promise<{ success: true; data: { success: true } }> {
await this.service.delete(id);
return { success: true, data: { success: true } };
}
}

View File

@@ -1,9 +1,10 @@
import { Module } from '@nestjs/common';
import { TextbooksController } from './textbooks.controller.js';
import { TextbooksService } from './textbooks.service.js';
import { Module } from "@nestjs/common";
import { TextbooksController } from "./textbooks.controller.js";
import { TextbooksService } from "./textbooks.service.js";
@Module({
controllers: [TextbooksController],
providers: [TextbooksService],
exports: [TextbooksService],
})
export class TextbooksModule {}

View File

@@ -1,30 +1,40 @@
import { mysqlTable, varchar, char, timestamp, text, integer } from 'drizzle-orm/mysql-core';
import {
mysqlTable,
varchar,
char,
timestamp,
text,
int,
} from "drizzle-orm/mysql-core";
export const textbooks = mysqlTable('content_textbooks', {
id: char('id', { length: 36 }).notNull().primaryKey(),
title: varchar('title', { length: 200 }).notNull(),
subjectId: char('subject_id', { length: 36 }).notNull(),
gradeId: char('grade_id', { length: 36 }).notNull(),
version: varchar('version', { length: 50 }).notNull(),
createdAt: timestamp('created_at').notNull().defaultNow(),
updatedAt: timestamp('updated_at').notNull().defaultNow().onUpdateNow(),
export const textbooks = mysqlTable("content_textbooks", {
id: char("id", { length: 36 }).notNull().primaryKey(),
title: varchar("title", { length: 200 }).notNull(),
subjectId: char("subject_id", { length: 36 }).notNull(),
gradeId: char("grade_id", { length: 36 }).notNull(),
version: varchar("version", { length: 50 }).notNull(),
createdAt: timestamp("created_at").notNull().defaultNow(),
updatedAt: timestamp("updated_at").notNull().defaultNow().onUpdateNow(),
});
export const chapters = mysqlTable('content_chapters', {
id: char('id', { length: 36 }).notNull().primaryKey(),
textbookId: char('textbook_id', { length: 36 }).notNull(),
title: varchar('title', { length: 200 }).notNull(),
order: integer('order_num').notNull(),
parentId: char('parent_id', { length: 36 }),
export const chapters = mysqlTable("content_chapters", {
id: char("id", { length: 36 }).notNull().primaryKey(),
textbookId: char("textbook_id", { length: 36 }).notNull(),
title: varchar("title", { length: 200 }).notNull(),
order: int("order_num").notNull(),
parentId: char("parent_id", { length: 36 }),
});
export const knowledgePoints = mysqlTable('content_knowledge_points', {
id: char('id', { length: 36 }).notNull().primaryKey(),
chapterId: char('chapter_id', { length: 36 }).notNull(),
title: varchar('title', { length: 200 }).notNull(),
description: text('description'),
export const knowledgePoints = mysqlTable("content_knowledge_points", {
id: char("id", { length: 36 }).notNull().primaryKey(),
chapterId: char("chapter_id", { length: 36 }).notNull(),
title: varchar("title", { length: 200 }).notNull(),
description: text("description"),
});
export type Textbook = typeof textbooks.$inferSelect;
export type NewTextbook = typeof textbooks.$inferInsert;
export type Chapter = typeof chapters.$inferSelect;
export type NewChapter = typeof chapters.$inferInsert;
export type KnowledgePoint = typeof knowledgePoints.$inferSelect;
export type NewKnowledgePoint = typeof knowledgePoints.$inferInsert;

View File

@@ -1,69 +1,70 @@
import { Injectable } from '@nestjs/common';
import { getDb } from '../config/database.js';
import { neo4jDriver } from '../config/neo4j.js';
import { textbooks, chapters, knowledgePoints } from './textbooks.schema.js';
import { v4 as uuidv4 } from 'uuid';
import { eq } from 'drizzle-orm';
import { randomUUID } from "node:crypto";
import { eq } from "drizzle-orm";
import { Injectable } from "@nestjs/common";
import { db } from "../config/database.js";
import { textbooks, type Textbook } from "./textbooks.schema.js";
import {
NotFoundError,
ValidationError,
} from "../shared/errors/application-error.js";
export interface CreateTextbookInput {
title: string;
subjectId: string;
gradeId: string;
version: string;
}
export interface UpdateTextbookInput {
title?: string;
subjectId?: string;
gradeId?: string;
version?: string;
}
@Injectable()
export class TextbooksService {
async create(data: { title: string; subjectId: string; gradeId: string; version: string }) {
const id = uuidv4();
const db = getDb();
await db.insert(textbooks).values({ id, ...data });
return { id, ...data };
async create(input: CreateTextbookInput): Promise<{ id: string }> {
if (!input.title || !input.subjectId || !input.gradeId || !input.version) {
throw new ValidationError(
"title, subjectId, gradeId, version are required",
);
}
const id = randomUUID();
await db.insert(textbooks).values({
id,
title: input.title,
subjectId: input.subjectId,
gradeId: input.gradeId,
version: input.version,
});
return { id };
}
async list() {
const db = getDb();
async list(): Promise<Textbook[]> {
return db.select().from(textbooks);
}
async getById(id: string) {
const db = getDb();
const [result] = await db.select().from(textbooks).where(eq(textbooks.id, id));
async getById(id: string): Promise<Textbook> {
const [result] = await db
.select()
.from(textbooks)
.where(eq(textbooks.id, id))
.limit(1);
if (!result) {
throw new NotFoundError("Textbook", id);
}
return result;
}
// 知识图谱:在 Neo4j 中创建知识点节点和关系
async createKnowledgeGraph(knowledgePointId: string, title: string, prerequisiteIds: string[]): Promise<void> {
const session = neo4jDriver.session();
try {
await session.executeWrite((tx) =>
tx.run(
'MERGE (kp:KnowledgePoint {id: $id, title: $title})',
{ id: knowledgePointId, title }
)
);
for (const prereqId of prerequisiteIds) {
await session.executeWrite((tx) =>
tx.run(
`MATCH (prereq:KnowledgePoint {id: $prereqId}), (kp:KnowledgePoint {id: $kpId})
MERGE (prereq)-[:PREREQUISITE_OF]->(kp)`,
{ prereqId, kpId: knowledgePointId }
)
);
}
} finally {
await session.close();
}
async update(id: string, data: UpdateTextbookInput): Promise<void> {
await this.getById(id);
await db.update(textbooks).set(data).where(eq(textbooks.id, id));
}
// 查询知识图谱(前置知识点)
async getPrerequisites(knowledgePointId: string): Promise<unknown[]> {
const session = neo4jDriver.session();
try {
const result = await session.executeRead((tx) =>
tx.run(
`MATCH (kp:KnowledgePoint {id: $id})<-[:PREREQUISITE_OF*1..5]-(prereq)
RETURN prereq.id as id, prereq.title as title`,
{ id: knowledgePointId }
)
);
return result.records.map((r) => ({ id: r.get('id'), title: r.get('title') }));
} finally {
await session.close();
}
async delete(id: string): Promise<void> {
await this.getById(id);
await db.delete(textbooks).where(eq(textbooks.id, id));
}
}

View File

@@ -8,7 +8,7 @@
"build": "nest build",
"start": "node dist/main.js",
"test": "vitest run",
"lint": "eslint src --ext .ts",
"lint": "eslint src",
"typecheck": "tsc --noEmit"
},
"dependencies": {
@@ -21,6 +21,7 @@
"pino": "^9.4.0",
"prom-client": "^15.1.0",
"@opentelemetry/api": "^1.9.0",
"@opentelemetry/auto-instrumentations-node": "^0.50.0",
"@opentelemetry/sdk-node": "^0.53.0",
"@opentelemetry/exporter-trace-otlp-http": "^0.53.0",
"zod": "^3.23.0",

View File

@@ -1,15 +1,10 @@
import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common';
import { ExamsModule } from './exams/exams.module.js';
import { HomeworkModule } from './homework/homework.module.js';
import { GradesModule } from './grades/grades.module.js';
import { ClassesModule } from './classes/classes.module.js';
import { AuthMiddleware } from './middleware/auth.middleware.js';
import { Module } from "@nestjs/common";
import { ExamsModule } from "./exams/exams.module.js";
import { HomeworkModule } from "./homework/homework.module.js";
import { GradesModule } from "./grades/grades.module.js";
import { HealthModule } from "./shared/health/health.module.js";
@Module({
imports: [ExamsModule, HomeworkModule, GradesModule, ClassesModule],
imports: [ExamsModule, HomeworkModule, GradesModule, HealthModule],
})
export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer): void {
consumer.apply(AuthMiddleware).forRoutes('/api/*');
}
}
export class AppModule {}

Some files were not shown because too many files have changed in this diff Show More