Compare commits

..
152 Commits
Author SHA1 Message Date
xuyueandClaude Opus 5 8b4d8899f9 feat(判题机): 自建镜像升级工具链,语言收敛到 C / C++ / Python
Deploy / deploy (push) Waiting to run
上游 QingdaoU/JudgeServer 停更在 2024-04(registry 上的 latest 和 1.6.1 是同一份
镜像,编译器停在 gcc-13),没有新版可拉,所以自己重编。docker/judge/ 是只改工具链
的 Dockerfile 分叉,server/ 和 Judger/ 从上游固定 commit b28aa56 拉,一行没动。

镜像 oj2-judge-2(不在任何 registry 上:本机 build.sh --save → scp → docker load)
- gcc/g++ 13 → 14.2,Python 3.12 → 3.13.5,都是 trixie 默认
- Go / JDK / Node 整套删掉:前端的题目语言复选框从来只给 C / C++ / Python / SQL,
  12 万条提交里 Java 44 条、Golang 15、JavaScript 3,全是很早以前的
- 体积 1.1GB → 433MB;默认走清华源,构建 12 分钟 → 40 秒(--no-mirror 换回官方)
- deploy.sh 加一道自检:镜像不在本机就中止,并打印该跑的三条命令

C 的编译参数加三个 -Wno-error(implicit-function-declaration / int-conversion /
incompatible-pointer-types):gcc-14 把它们从 warning 提成了 error,而 -w 压不住。

语言值统一成 Python(迁移 0019 / 0020)
- 0019:Python3(104527 条提交)与 Python2(3 条)并成 Python,一并改掉 937 道题的
  languages、75 个 template 键、15 个 ast_rules 键、257 条 answers、1235 个用户的
  成就指标 _languages(languages_used 重算,总和 1928 → 1925,少的 3 个是同时用过
  两种 Python 的人)
- 0020:把 Java / JavaScript / Golang 从 84 道题的可选语言里摘掉 —— 不摘的话那些题
  的语言下拉还能选 Java,提交必 SYSTEM_ERROR
- 契约新增 normalizeLanguage() 别名表,判题侧一律走 judgeConfigFor():旧客户端
  localStorage 里的 Python3、迁移前排进队列的任务都还能判;协作的语言归一也走它,
  否则上线那一刻学生页面里的 Python3 会静默落到 C
- 回滚要连数据一起回,只滚代码会让所有 Python 提交变 SYSTEM_ERROR

实跑
- 判题冒烟 docker/judge/smoke.ts 13 条全过:三种语言、六种状态码、gcc 宽松度
- 拿备份里的真实代码逐文件比对新旧镜像的编译结果,0 差异:C 提交 1951 份
  (1725 过 / 226 CE)、C++ 882 份、Python 2000 份、20 篇 C 教程的 93 个代码块。
  不加那三个 -Wno-error 的话,C 有 26 份会从能过变成 CE
- 迁移在灌了 12.4 万行真实数据的一次性库里跑过:0 残留、没有题目被清空;
  dev 库用真正的执行器跑通
- check:ast 56 个 target 全过,前后端 typecheck 均 0

顺带记下一个升级之前就有的坑(现在随 Go 一起消失,写在 README 里):GOCACHE 指向
容器的 tmpfs,判题机重启后第一次 Go 提交是冷构建,Go 1.22 要 5.6 秒 CPU、超过 3 秒
的编译预算,于是重启后第一个交 Go 的学生必吃一次 CE,后面的人缓存热了又都正常。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-20 06:24:05 -06:00
xuyue a872e8365b fix
Deploy / deploy (push) Canceled after 0s
2026-09-19 07:10:49 -06:00
xuyueandClaude Opus 5 b4c0f89291 fix(个人主页): 总共学习天数改为有提交的天数
Deploy / deploy (push) Has been cancelled
原来是首末提交之间跨了多久,现在按东八区日期对提交去重计数,比赛提交也算。
首末提交时间仍只看比赛外的提交,口径不变。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-19 07:07:57 -06:00
xuyueandClaude Opus 5 06ad6745b7 feat(AI 提示): 两段式提示——先诊断出错误标签,再生成提示
Deploy / deploy (push) Has been cancelled
AI 时代 OJ 设计的 2b。标准答案能让提示准得多,但不能进生成提示的 prompt
(学生代码里一段注释就能把它套走),所以拆成两段:
- 诊断:看得到标准答案、第一个没过的测试点、带行号的学生代码;出参只允许
  { tag, lines, confidence },safeParse 过闸、多余字段剥掉,没有自由文本通道
- 生成提示:看不到标准答案和测试点原文,只多一句「问题定位:X,大约在第 a 行」
- 诊断失败(20 秒超时、不是 JSON、校验不过)退回单段式;同一条提交复用诊断;
  编译失败不诊断
- 契约新增 HINT_ERROR_TAGS(13 个,落库值,只增不改)与 hintDiagnosisSchema
- 迁移 0018:ai_hint 加 diagnosis / diagnosis_error 两列
- 单段式 prompt 原样搬进 services/hint-diagnosis.ts,记版本 1;两段式记版本 2
- completeChat 支持 JSON 模式和自定义超时,现有调用不受影响
- 开关 AI_HINT_DIAGNOSE 默认关(2a 的基线还在攒),两套生产 compose 透传

实跑(一次性库 + 本地假 LLM):开关关时请求与 2a 逐字节相同;开时正常 /
复用 / 坏 JSON / 非法标签 / 行号越界 / 超时 / 编译失败七种场景符合预期;
12 次模型请求里诊断全都带标准答案和测试点,生成全都不带。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-19 06:56:38 -06:00
xuyueandClaude Opus 5 47d8f46bdb feat(AI 提示): 提示落库并收集学生评价,落进 ai_hint
Deploy / deploy (push) Has been cancelled
AI 时代 OJ 设计的 2a:先把现有提示记下来,为后面的分级和两段式诊断攒对照数据。
提示本身的行为不变,发给模型的 prompt 一字未改。
- 迁移 0017 建 ai_hint:模型、prompt 版本、内容、错误、耗时、学生评价;
  成功和失败都记(失败率是 AI 悄悄变差时最先动的数)。挂在 submission 上 CASCADE
- streamChat 第三个参数改成 { onComplete, onError }:onComplete 的返回值并进
  done 事件,提示 id 由此带回前端;班级学情分析那处调用同步改写,行为不变
- 落库失败只记日志,不影响学生拿到提示
- 新增 POST /ai/hint/:id/feedback:只能评自己的提示(别人的一律 404),可以改票
- 前端提示生成完出「有帮助 / 没帮助」,选中的高亮;后端没存上时不出按钮
- 实跑:本地假 LLM 验证成功 / provider 断开 / 缺 AI_KEY 三条路径的落库,
  评价接口六种请求,浏览器里按钮出现、改票、重复点不发请求

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-19 06:00:10 -06:00
xuyueandClaude Opus 5 a0ef204bd2 feat(提交): 采集编辑过程信号,落进 submission_trace
Deploy / deploy (push) Has been cancelled
AI 时代 OJ 设计的第 1 步:给「可信 AC」和学情分析攒数据,本身不判任何事。
- 契约:提交请求加可选的 trace(活跃时长、键入/粘贴/删除字符数、切后台次数等,
  只有计数、不含按键内容);写成 .optional().catch(undefined),坏了就当没带,
  不让附带数据把提交挡成 400
- 迁移 0016 建 submission_trace,与 submission 一对一、CASCADE;since_prev_ms
  由服务端在同一条 INSERT 里算(排掉自身),bigint —— 实测已有 44 天的间隔,int4 装不下
- 后端写 trace 失败只记日志,不影响提交
- 前端 oj/problem/utils/editTrace.ts 是模块单例(扩展对象不能过 Pinia 的响应式代理),
  只数带 userEvent 的事务:格式化回写 / 载入草稿 / 协作对方的改动天然排除;
  closeBrackets 越过右括号时是原样替换,按 no-op 跳过。比赛编辑器同样挂上
- 实跑:后端四种请求、前端浏览器里键入/粘贴/删除/setCode 回写/切后台/提交后清零,
  计数与预期逐项一致

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-19 05:46:55 -06:00
xuyueandClaude Sonnet 5 20a6ddc79c feat(自学): 重做学生端页面与教师端学情概览
Deploy / deploy (push) Has been cancelled
学生端:目录 + 居中限宽正文 + 可收起的示例代码栏;目录改成三态圆点,
顶部加总进度;上一课/下一课栏桌面端固定在底部。
教师端:汇总卡片、学生状态标签与筛选(未开始/7 天没学/只读不练等)、
最后学习补「N 天前」、按练习表加「没人一次对/多数人卡住」提示。

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-19 05:07:37 -06:00
xuyueandClaude Sonnet 5 c228b164cf refactor(提交): 教师统计路由拆出 submission-statistics.ts,check:routes 支持嵌套挂载
Deploy / deploy (push) Has been cancelled
- submission.ts 1416 行降到 751 行;统计三条路由拆成子路由,挂在原位置,
  仍排在 /submissions/:id 之前
- check-route-shadowing 原来只认 index.ts 直接挂载,拆分后漏检 3 条(178→175);
  现在按挂载位置展开嵌套的 .route(),恢复 178 条、无遮蔽

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-19 04:40:30 -06:00
xuyueandClaude Sonnet 5 b5ba56ccd0 refactor(契约): 判题状态码收进契约唯一一份,并收紧 18 处 as any
- 状态码常量与 judgeStatusSchema 移到 packages/contract/src/judge-status.ts,
  后端 judge/status.ts 只再导出;前端 SubmissionStatus 枚举加编译期断言对齐契约
  (实测改坏一个码会当场类型检查失败)
- 类型逃逸 22 处降到 4 处:collab/handler、pagination、configUpdate、
  ExerciseManager、ProblemSubmission、pk.vue tooltip;剩下的是词云插件无类型、
  生成的 .d.ts、skulpt 和 TextEditor

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-19 04:40:30 -06:00
xuyueandClaude Opus 5 f90d01338e feat(自学情况): 按学生加姓名/学号搜索,后端补稳定排序
Deploy / deploy (push) Has been cancelled
搜索是纯前端过滤(整表本来就一次拉完),和班级筛选可以叠加。

学生查询原来没有 orderBy,前端默认按「已读」升序排之后,同分的一大批
(尤其一堆 0)落回聚合的任意顺序,刷新一次换一个样;按班级、学号兜底。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-17 02:23:01 -06:00
xuyue 3cc2be77a9 fix
Deploy / deploy (push) Has been cancelled
2026-09-17 02:12:04 -06:00
xuyue 905ba2ee03 fix
Deploy / deploy (push) Has been cancelled
2026-09-17 02:07:52 -06:00
xuyueandClaude Opus 5 a8de8f3932 feat(排名): 本周进步榜移到全服 Top100 右边,左 2/3 右 1/3
Deploy / deploy (push) Has been cancelled
两张榜分开上下放的时候,谁也看不见谁:上面那张是历史全部 AC 的总榜,名次几乎不动;
下面那张的分母只有这一周。并排摆在同一屏里,「总榜追不上」和「这周还能进前十」
才是一眼对照出来的。桌面 cols=3、Top100 占 2 栏,移动端退回 cols=1 上下堆叠。

周榜宽度从整屏缩到 1/3,列跟着收:列头去掉「本周」前缀(卡片标题已经写着),
宽度压到 70/120min/100/90,用户名加 ellipsis tooltip —— 1280 那一档也不出横向滚动条。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-17 02:03:04 -06:00
xuyueandClaude Opus 5 24af385f33 feat(排名): 加本周进步榜,按本周首次 AC 数排,每周一清零
Deploy / deploy (push) Has been cancelled
存量榜(/rankings/users、班级榜)排的都是 user_profile 的 AC 总数,名次几乎不动,
中位学生看一眼就知道追不上 —— 榜单在那批人身上是负反馈。这张榜的分母换成「这一周」,
每周一 0:00(东八区)清零,谁都可能进前十。

口径是**本周首次 AC 的题目数**,不是「本周 AC 过的去重题数」:后者把上周就做出来的题
重交一遍也算成绩,一分钟能刷满一屏。靠 NOT EXISTS 排掉本周之前已通过的
(user, problem) 对,四个条件正好是 submission_public_metrics_idx 的全部列。

- time.ts 加 weekStart():localWeekday 的 0 是周日,要先折成 7,否则周日单独成一周
- GET /rankings/weekly?scope=global|class,入榜人群与全服榜一致(教师/超管不参与)
- 前端默认落在本班 —— 全服周榜上中位学生仍然看不到自己,班内 30 人那张才有答案
- 本周一题没做出来时 me 是 null,footer 那句「做出 1 题就能上榜」照样出现:
  它是说给还没上榜的人听的,而那正是最需要被推一把的一批

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-17 01:53:37 -06:00
xuyueandClaude Opus 5 ad858ed864 feat(提交列表): 代码详情弹框支持方向键翻阅,到头自动翻页
Deploy / deploy (push) Has been cancelled
老师看一个班的提交原来得「点开 → 看 → 关掉 → 点下一行」,现在弹框开着就能
用 ↑↓(←→ 等价)切上一条/下一条,Esc 关闭。

- 只在 showLink 为真的行之间走,跳到看不了的行只会得到空弹框
- 走到本页头尾自动翻页续上:向下落到下一页第一条,向上落到上一页最后一条。
  翻页是异步的,先记 pendingJump,等 listSubmissions() 回来再开;
  整页都看不了代码时保持原来那条不动,给一句提示
- 弹框没开不接管方向键,焦点在输入框里也不抢
- SubmissionDetail 加 :key="submissionID" —— 它只在 onMounted 拉一次代码,
  不换 key 切过去还是上一条的代码

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-16 19:26:51 -06:00
xuyueandClaude Opus 5 88b695d34f feat(课堂求助): 教师端接单直接跳题目页协作,删掉 CollabModal
Deploy / deploy (push) Has been cancelled
点求助列表里的一条 = 跳到 /problem/:id,在页面自带的那个编辑器里和学生同步。
原来是弹一个 CollabModal(弹框里再挂一个 CodeMirror + 一份只读题面):

- 按一下 Esc 弹框就关、协作跟着结束(`show` 的 setter 里 leave 是唯一的关闭语义,
  Esc 和点遮罩都走它),上课太容易误触;
- 弹框里那份题面不能跑测试、不能提交,老师还是得另开标签页对照。

现在结束协作只有两条明确的路:工具栏的「结束协作」按钮、离开这一页。教师端也少了
一个 CodeMirror 实例 —— setBinaryHandler 那个单例槽位只剩 SyncCodeEditor 一个使用者。

改造中撞出两个真问题,根因是同一个:`/problem/1002` → `/problem/1001` 是同一条路由
换 params,**组件被复用、不卸载**。

- 老师在别的题上接单跳过来,`@ready` 不会再触发,而 room 早在导航前就 open 了 ——
  老师停在一个空编辑器上干等。watch 的源从 room 一个变成 [room, roomIsHere] 两个。
- 反过来老师协作中切去别的题,onUnmounted 不触发 → 不发 leave,学生一直挂着
  「老师正在帮你」而老师的字一个也过不去。加 `bound` 标记区分「房间从我这儿挪走了」
  (补发 leave)和「房间在别处开起来了」(跟我无关,接单那一瞬间就是这种)。

`leave` 分两种语义(协议加 reason):

| 前端 | 求助记录 | 对面看到 |
|---|---|---|
| leave("done") 点「结束协作」 | 删除 | 老师已结束这次帮忙 |
| leave("left") 离开这道题的页面 | 教师走→退回排队;学生走→删除 | 老师暂时离开,已重新排队 |

"left" 复用的是老师掉线那条路(requeueAfterTeacherGone),两件事语义相同。原来两者
都按 done 处理 —— 老师点一下「提交信息」,学生就得重新举手,而他看到的是
「协作已结束」,会以为被处理完了。发起方收到的 reason 单独一份(self_left/done),
不然学生自己切走了却看到「老师已结束这次帮忙」。

其余为这套交互补的闸:

- 学生排队期间离开那道题 → 自动取消求助。那条求助说的是「我卡在这道题」,人走了
  就不成立;原来它会一直挂在队列里,老师接进来时学生的编辑器不在这道题上、根本
  不会绑,老师对着空编辑器敲字,两边都没提示。
- 协作中**教师的语言选择跟着 room.language 走**(写 codeStore,不只是改高亮),
  结束后还原。只改高亮的话老师会拿自己那档语言提交学生的代码(学生写 C、老师选的
  是 Python,当场 CE),工具栏还可能显示「提交流程图」。学生端一个字不动 ——
  服务端的 room_language 只发给教师,学生本地那份停在建房那一刻。
- 协作中不给「重置代码」:v-model 一写回就顺着 Yjs 同步过去,等于一键清空学生的作业。
- 协作中「提交信息」走新标签 —— 那是教师工具栏上唯一会跳路由的按钮。
- 接单时 resetScreenMode():分屏在「题目」「自测」两档时右侧编辑器根本没挂出来,
  停在同一道题上接单会落进一个没有编辑器的页面(跳到别的题时 detail.vue 的 init()
  会重置,同页不会)。
- 老师已在一个房间里时前端也拦住接下一单(服务端本来就拦),不拦的话前端已经跳到
  新题目上,等于把手上那场协作断掉。
- 文案:协议层那四条英文(Invalid problemId 之类)会被原样弹成 toast,改成中文;
  「请先退出当前协作」统一成「结束」;room_closed 的提示按 reason × 角色展开。

验证:本机起 api + web,三个账号两两组合实跑 —— 跨题接单 / 同页接单、双向编辑、
连按 Esc、结束协作、老师跳走后再接、学生跳走、学生排队中切题、学生协作中切语言、
分屏在「题目」档接单、协作中重复接单,以及上面每一句提示的实际文案。
api typecheck / check:routes、前端 type-check / build、fmt 全过。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-16 19:13:42 -06:00
xuyueandClaude Opus 5 ed56a209ea chore(格式): Prettier 统一到全仓,后端和契约一次性格式化
Deploy / deploy (push) Has been cancelled
原来只有 `apps/web` 在 Prettier 下(配置在 `apps/web/.prettierrc.toml`、脚本在
web 的 package.json),后端和契约从来没格式化过 —— 手写在 100 列上下,`db/schema.ts`
还是 drizzle-kit pull 留下的 tab 缩进。两套口径分叉久了,跨端改一处就得记着「这边
什么风格」。

- 配置搬到根目录 `.prettierrc.toml`,内容不变(`semi=false`,其余全默认,
  printWidth 80 —— 和前端已有的格式一致,不另立一套宽度);
- 脚本统一成根目录 `bun run fmt`,覆盖 `apps/*/src`、`apps/web/tests` 和两个构建
  配置;web 自己那份 `fmt` 和重复的 prettier 依赖删掉;
- `.prettierignore` 挡掉两类不该碰的:drizzle-kit 生成的 `src/db/meta/` 结构快照
  (它是 db:generate 的比对输入,只该由 drizzle-kit 写)、unplugin 每次 dev 都会
  重写的 `auto-imports.d.ts` / `components.d.ts`;
- 全量跑了一遍。纯格式,无行为改动:api typecheck / check:routes / check:ast、
  前端 type-check 全过,起 api 打了接口确认正常。前端这 39 个文件的小改动是
  prettier 版本漂移(类型断言的换行口径变了),不是新配置带来的。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-16 08:27:34 -06:00
xuyueandClaude Opus 5 e600fd24cf feat(提交列表): 今日提交数旁加「统计」按钮,弹框给今天的提交统计
筛到今天之后标签旁边出现「统计」,弹框里是全站今天的提交概况:总提交 / 正确 /
判题中 / 正确率 / 参与人数,外加按钟点的 24 格分布、按语言、按判题结果,以及
今天最热的 10 道题。

新接口 GET /submissions/today-statistics,公开、只出聚合数,口径和那颗标签一致
(东八区今天 + 非比赛提交):

- 钟点分桶走 time.ts 的 localTime()。`extract(hour from create_time)` 按会话时区
  算,容器是 UTC,整张分布图会左移 8 小时;
- 正确率的分母摘掉未判完的条数,正确数含 AST_CHECK_FAILED;
- 热门题只算 visible 的题目 —— 这个接口不需要登录,不能拿它探未发布题目的标题;
  「提交列表对学生全开」关掉时这张表整个不下发,跟提交列表同一个开关(数字照给,
  否则标签说 21、弹框说 0)。

前端组件异步加载,不进本路由的关键路径;小时分布是纯 CSS 柱状图,没有引 chart.js。
柱子和基线取 useThemeVars(),深浅色都跟着走,「现在」那一格是基线上一段主色刻度。
流程图那档不给这颗按钮 —— 流程图提交在另一张表、只有 AI 评级没有判题状态。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-16 08:23:45 -06:00
xuyueandClaude Opus 5 5eee13fe81 chore: 删掉两个跑完的一次性订正脚本,recount 留着
Deploy / deploy (push) Has been cancelled
fix-achievement-hours 订正的是时区丢失那两周误发的「夜猫子」「早起的鸟儿」,
2026-09-14 已跑完(修正 148 行 · 撤回 60 条),根因修在代码里之后不会再产生;
backfill-problemsets 补的三笔题单历史欠账也已结清,进度记账现在在判题这一路。
两个子命令、两条 npm 脚本一并去掉,services/problemset.ts 的 badgeHolderDiff
只服务于补发脚本,删完 0 处引用,一起清掉。

recount 留着 —— 反范式计数列会被重判、删提交带偏,是会复发的漂移,
补一条 npm 脚本(原来只有子命令)。

docs/timezone.md 里那节改成「账已平、脚本已删」,但保住那条教训:
unlockAchievements 是纯阈值比较,只删 user_achievement 不修 metrics 的话,
学生下次提交就把同一个成就原样再发一次。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-16 08:03:57 -06:00
xuyueandClaude Opus 5 6fdc3c588e chore(开发环境): 本机库改成靠迁移自举,db:migrate 换成线上同一个执行器
compose.dev.yml 不再把 schema dump 挂成 initdb:0000 就是完整的建表迁移,
起完库 bun run db:migrate 从 0000 自举即可。实测两条路子跑出来的结构一致 ——
空库自举 16 条迁移 vs 灌 dump + 打基线 + 跑迁移,pg_dump --schema-only
逐行零差异(1981 行)。docs/specs/schema.sql 与 sample-data.sql 随之删掉,
前者的内容已经在 0000_crazy_gateway.sql 里。

db:migrate 原来是 drizzle-kit migrate,和线上 oj2-api migrate 不是同一个
执行器:drizzle 那个所有迁移共用一个事务、跑不了 CREATE INDEX CONCURRENTLY,
对已打基线的库还会从 0000 撞表回滚且 exit 1 不打印任何错误。现在两边都走
db/migrate.ts。DATABASE_URL 从根目录 .env 读(--env-file),仓库里不留连接串。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-16 08:03:57 -06:00
xuyueandClaude Opus 5 a8408c0bb5 docs: 文档整理,CLAUDE.md 瘦身一半,删掉重写期已完成的 22 份阶段产物
CLAUDE.md 从 490 行降到 228 行:只留日常要当场记住的约束,展开拆成五份专题
文档 —— docs/deploy.md(部署与备份恢复)、database.md(迁移执行器、基线、
drizzle-kit 的坑)、timezone.md(时区口径与那次成就订正)、contract.md
(出参不 parse 的四次故障)、ast-rules.md(AST 规则与 C++ 的调用形态)。

删掉的是阶段 0–5 那批一次性产物:4 份实施计划、10 份评审/核验/修复报告、
endpoint-inventory.md(110 端点是 2026-08 的快照,现在 363 条路由)、
docs/spikes/ 的 spike 与提取脚本(结论早已落进代码)。phase5 切换手册删之前
先把仍然有效的部分提炼进 docs/deploy.md:拓扑、deploy.sh、部署后验证清单、
NPM 那两个不能关的开关、pg_dumpall 恢复的两个坑、镜像体积;演练报告与回滚
两节随旧栈下线一并作废。

两份设计文档保留,补上状态行说明它们是「当初为什么这么定」而不是现状。

apps/web/CLAUDE.md 顺手订正过期内容:PUBLIC_OJ_URL / PUBLIC_WS_URL 两个变量
早已不存在(baseURL 写死 /api,dev 走 vite proxy、线上由 Caddy 同源伺服),
store 与 composable 清单补齐到与目录一致。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-16 08:03:26 -06:00
xuyueandClaude Opus 5 3559ae4d6f chore(前端): 浏览器基线从 Chrome < 94 提到 105,删掉 mermaid@9 那套 fallback
机房只有部分电脑还是 Chrome 105,其余更新,按最低那档定基线。

- legacy 插件留着:vite 8 的默认 build.target 是 chrome111,比机房高。
  modernTargets 不写,用插件自带的 chrome>=105 基线,正好是这一档。
- polyfill 清单按 105 重新探测,63 → 50 项,仍然写死:自动探测要对每个产物
  跑 Babel 扫描,构建 3s → 12s。写死后产出的 polyfills chunk 与自动探测同尺寸。
- 删 mermaid-legacy(mermaid@9)、useMermaid 里按 UA 分叉的 v9 回调式 render、
  为它存在的 cytoscape UMD→ESM 别名 —— 105 直接用 mermaid 11。
- View Transitions 要 111,darkTransition 的降级分支保留,注释改成 105。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-16 07:43:21 -06:00
xuyueandClaude Opus 5 688005c081 perf(流程图): 列表裁掉整行 select、count 去掉 join,统计面板的数值全下推 SQL
Deploy / deploy (push) Has been cancelled
流程图提交量涨上去之后,先扛不住的是教师统计面板:它一条不带 limit 的 select
把整个时间窗的行拉进内存再用 JS 算,词云那个 3000 条上限是在 JS 里截的,行早就
全回来了。列表那边则是 `select({ flowchart: 整行, problem: 整行 })`,把
mermaid_code、flowchart_data、三个 AI 文本列和整张题目表一起拉回来,响应一个
都用不到(快照实测流程图行均 4.9KB、题目行均 2.2KB,10 行一页白拉 ~70KB,
limit=250 时 1.7MB)。

- 列表改成白名单列 flowchartListColumns,对齐 submission 那边的
  submissionListColumns(那边同样刻意不取 code / info)。
- 题号 / 用户名筛选先解析成 flowchart_submission 自己的列,count 因此一个 join
  都不用挂,回得到最小索引上的 index-only scan;筛条件落在驱动表上,规划器也走
  得上 flowchart_user_time_idx / flowchart_problem_time_idx。
- 统计面板拆成五条各自和行数脱钩的查询:数值聚合、等级分布、各项平均分
  (jsonb_each + group by)、词云原料(order by ... limit 3000)、谁没做。
  每项满分改从词云那批行里顺手取,省掉一次 21 万行的排序。
- matchedUsers() 从 submission.ts 挪进 helpers.ts,两条统计共用。

拿生产快照(2134 条)复制一份、另插三行脏数据(标量 jsonb、数组 jsonb、分数和
满分写成字符串),新旧两版各跑 24 个请求组合:23 个逐字节一致;剩下 1 个只是三行
create_time 完全相同的记录先后不同 —— 既有的不确定性(ORDER BY create_time 不是
全序),留给后面的 keyset 分页一并解决。

把表灌到 5.3 万 / 21.3 万行实测(HTTP 端到端,5 次取最好,旧 → 新):

  列表 limit=10       35 →  4 ms    |  56 →   8 ms
  列表 limit=250      36 →  5 ms    |  54 →   8 ms
  列表 offset=5万    108 → 39 ms    |  57 →  45 ms
  列表 按班级         33 →  4 ms    |  53 →   8 ms
  统计 全部时段      288 → 187 ms   | 1169 → 704 ms
  统计 一个班        143 →  43 ms   |  388 → 129 ms
  统计 一道题         94 → 194 ms   |  339 → 277 ms

「统计 一道题」在 5 万行量级是退步的:那个筛选命中全表 23% 的行,PG 侧的 jsonb
算子比「原样输出让 Bun 去 parse」更费 CPU,要到 21 万行才反超。它跟的是筛出来的
行数、不跟总量走,200ms 的教师面板可以接受,没有再调。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-15 22:19:21 -06:00
xuyueandClaude Opus 5 ed3b2cf6de feat(课堂求助): 教师协作弹框左侧直接显示题面
Deploy / deploy (push) Has been cancelled
原来弹框里只有编辑器,要看题得点「打开题面」另开标签页来回切。
现在左右分栏(可拖动):左侧只读题面(描述、输入输出、例子、提示,
SQL 题显示数据表与期望结果),右侧协作编辑器。

不复用 ProblemContent:它读写全局 problemStore,老师接单时正开着
的题目页会被换掉题面,测试按钮跑的也是老师自己的代码。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-15 08:48:40 -06:00
xuyue 4189c59162 update
Deploy / deploy (push) Has been cancelled
2026-09-14 08:39:58 -06:00
xuyueandClaude Opus 5 cc51e305cf refactor(时区): 常量收进契约、SQL 统一走 localTime,去掉会话时区与 TZ 兜底
Deploy / deploy (push) Has been cancelled
- TIME_ZONE / TIME_ZONE_OFFSET_MINUTES 移到 packages/contract/src/time.ts,
  前后端共用一份,不再各写一遍靠注释对齐。
- apps/api/src/time.ts 新增 localTime(列),替换散落 7 处的
  `at time zone ${TIME_ZONE_SQL}`;ac-trend 的 where 复用同一个 year 表达式。
- /problems/:displayId/yearly-ac 漏写了时区、按 UTC 切年,被会话时区兜底掩盖;
  改为按东八区切(只影响每年 12-31 北京 0–8 点的提交归年)。
- 删掉数据库连接的 TimeZone 和 Dockerfile 的 TZ:正确代码不依赖它们,
  它们只会在线上掩盖漏写处、让 dev 与线上答案不同。
- time.ts:calendarDayYearsAgo/pad 并入 shiftMonthsByCalendar,startOfCalendarDay
  并入 todayStart,localWeekday 改用 getUTCDay,删掉历史叙述注释。
- 前端 zonedParts 改为固定偏移 + getUTC*(与后端、日期选择器同一写法),
  去掉 Intl formatToParts;10 万次 299ms → 11ms。zonedYear 去掉按浏览器时区的兜底。
- 两份 CLAUDE.md 同步;n-date-picker 那条过时说明改成现用法。

验证:新旧「近两年起点」21359 个时刻 0 差异、localWeekday 0 差异、
前端固定偏移与 Intl 在 America/New_York 下 47821 个时刻 0 差异;
localTime 在 select/group by/where 复用可用;fix-achievement-hours 预演仍为 148 / 60。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K1d8B3f4SXJwDvUY625eQd
2026-09-14 06:06:52 -06:00
xuyueandClaude Opus 5 3921c496cb fix(成就): 后台补发成就后重算已解锁数并接着判「奖杯收藏家」;recount 订正存量
rescanAchievement 只插 user_achievement、加 unlock_count,不重算
achievement_unlocked_count,也不做元成就的第二轮判定(旧 rescan_achievement
原样如此)。判题结算只在「这次有新解锁」时才重算,所以被补发的人计数会一直停在
旧值。2026-09-07 一次补发之后 269 人少算,其中 10 人实际够 15 个却没拿到
「奖杯收藏家」。

- 新增 refreshUnlockedCount:一条 SQL 按 user_achievement 重算,只 jsonb_set
  这一个键、只写值变了的行。rescanAchievement 补发非白金成就后调用它,再补发元成就。
- recount 同时核对已解锁数与元成就漏发,--apply 先改计数再补发,复核同一份口径。

用 09-14 生产备份实跑:recount 订正 269 人、补发 10 条,复核通过、重跑无差异,
其余指标 0 行被动;模拟调低阈值补发 1504 条,「奖杯收藏家」随之 65 → 95,
与预先算出的跨线人数一致。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K1d8B3f4SXJwDvUY625eQd
2026-09-14 05:55:38 -06:00
xuyueandClaude Opus 5 f6995c841b ops(成就): 加 fix-achievement-hours,订正时区丢失期间误发的「夜猫子」「早起的鸟儿」
OJ2 上线到时区修复之间,成就的小时键按 UTC 判定:UTC 的 0–5 点 / 5–7 点是北京
的上午 9–13 点 / 下午 1–3 点,上课时间的提交被记成熬夜和早起。Django 时代的存量
本来就是东八区口径(已用生产备份做判别性核对),出问题的只有这两周的增量。

脚本按东八区重算两个小时指标(只合并这两个键,不整体覆盖 metrics)→ 撤回不达标
的 → 补发达标却没发的 → 同步 unlock_count → 校正已解锁数与「奖杯收藏家」连锁。
默认只读预演,--apply 落库后自动复核,幂等。

用 db_backup_2026_09_14_18_17_37.sql 实跑:修正 148 行、撤回 60 条(47 + 13,
50 人)、补发 0、连锁 0,其余指标 0 行被动。必须先部署时区修复再跑。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K1d8B3f4SXJwDvUY625eQd
2026-09-14 05:55:27 -06:00
xuyueandClaude Opus 5 4c0c38445c fix(时区): 日历口径收回东八区,读出的时刻统一成 ISO 并保留微秒
旧栈 Django 按 Asia/Shanghai 算日历,OJ2 重写时这个锚点丢了:容器和数据库会话
都是 UTC,于是「今日提交」在北京时间 0–8 点是空的,「凌晨/早起提交次数」整体偏
8 小时,热力图、AC 趋势年份、近两年活跃人数也各按进程时区切。

- 新增 apps/api/src/time.ts 作为唯一锚点(固定 +8 偏移,不依赖进程 TZ / tzdata),
  todayStart、成就小时/日期键、热力图、月份平移、年份夹逼全部改走它;
  SQL 里按日历切的一律显式 at time zone。
- db/index.ts:连接会话时区设为东八区(兜底);给 timestamptz(1184) 挂 parser,
  读出统一成 ISO 8601 UTC,撤掉为拿 PG 文本形状写的 ::text。parser 保留微秒 ——
  生产库 12.3 万条提交几乎全带微秒,截成毫秒会让翻页分界行和班级 AC 排名的
  <= min(create_time) 把自己排除(翻页每页丢一条、排名少 1)。
- 前端 parseTime/zonedParts/zonedYear 按 Asia/Shanghai 渲染,n-date-picker 做
  toPickerValue/fromPickerValue 平移,站内不再按浏览器时区取时间部件。
- Dockerfile 设 TZ=Asia/Shanghai 作为第二道兜底。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K1d8B3f4SXJwDvUY625eQd
2026-09-14 05:55:17 -06:00
xuyueandClaude Opus 5 6e63866cc9 perf(提交列表): 按用户名、题号筛选走索引,不再扫全表
Deploy / deploy (push) Has been cancelled
用户名筛选:user_id 先查成字面列表,不再把子查询夹在 OR 里(那样整条 OR 不可索引),
加 trigram 索引接住 ilike '%x%';翻页先圈出匹配行再排序取页,避开规划器顺着时间索引
倒扫、边扫边滤的计划。快照上查一个班 70~107ms → 5~14ms;匹配 9.5 万条的年级前缀
从 34ms 变成 70~90ms,实际不这么查。

题号筛选:先解析成 problem.id,加 (problem_id, create_time, id) 部分索引。老题和
不存在的题号不再倒扫大半张表(34~67ms → 4ms),题号筛选也能走游标深翻页,
count 不再 join problem。

迁移 0015 装 pg_trgm(官方镜像自带 contrib,trusted 扩展)。39 个筛选组合的响应
与改动前逐字节一致。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Xg91q3JsunDE7EYoi9G3i2
2026-09-13 23:47:24 -06:00
xuyue fe4fc46243 fix
Deploy / deploy (push) Has been cancelled
2026-09-13 23:40:58 -06:00
xuyue 271123179a fix
Deploy / deploy (push) Has been cancelled
2026-09-13 19:29:45 -06:00
xuyueandClaude Opus 5 9132901cc7 feat(提交结果): 没通过时显示「通过 x/y 个测试点」;编译失败不等三次就能用 AI 分析
Deploy / deploy (push) Has been cancelled
学生拿不到 info(每个点带 output_md5,只给管理员),测试点表格从来只有管理员看得见,
学生这边只有一句「答案错误」—— 从 2/8 交到 6/8 的人,感受是连输五次。

- 提交详情新增 caseSummary,后端从 info 数出通过数下发,不放开原文。
  比赛提交、SQL 题(被杀的测试点会 break,total 偏小)、无逐点结果时为 null
- 结果面板标题缀上通过数并加进度条,提交详情页标题同步;一个都没过时不缀
- POST /ai/hint 对编译失败跳过失败次数门槛,throttleAi 照旧;前端显示条件同口径

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013TecwAowmYcoNZRheSyTgH
2026-09-13 07:25:00 -06:00
xuyue a833819679 fix(统计面板): 班级选择不再记本地,别让上一个人的班悄悄留在框里
Deploy / deploy (push) Has been cancelled
提交统计弹框里的「班级或用户」原来点过「统计」就永久写进 localStorage
(statisticsClass),下次打开自动带上。机房一台电脑对一个班,下课换班或者
换个人坐这台机器时,上一个人查的班还留在选择框里,老师没注意就按了「统计」,
看到的整个是别人的班。

改成不存也不读,每次打开都从空的开始 —— 宁可多选一次。登录框的 LOGIN_CLASS
不动,那记的是这台机器的身份,不是一次临时查询。

STORAGE_KEY.STATISTICS_CLASS 随之没有调用方,一并删掉。
2026-09-10 20:57:34 -06:00
xuyueandClaude Opus 5 2b07040aee refactor(时段): 两份手抄的选项列表与五份 "weeks:1" 解析收成一处
Deploy / deploy (push) Has been cancelled
时段选项的 value 是 `<date-fns 单位>:<数量>`,把它解成 Duration 的那段 `split(":")`
在**五个组件里各写了一遍**(提交统计、流程图统计、AI 分析页、榜单页、班级对比页),
每份的兜底还都不一样;选项列表也抄了好几份:

- 两个统计面板逐字相同地拼「10/20/30 分钟 + DURATION_OPTIONS + 全部时段」;
- rank/list.vue 和 class/pk.vue 各手写了同样的五条长时段,pk.vue 里还留着一句
  「与 rank/list.vue 保持一致」的注释 —— 靠注释同步的东西迟早不同步。

现在:`PANEL_DURATION_OPTIONS`(面板用,含分钟级和 all)、`LONG_DURATION_OPTIONS`
(榜单/班级对比用,从 DURATION_OPTIONS 派生)、`durationFromValue()`(唯一解析)。
各站点自己的兜底保留在原处,那部分本来就该各不相同。

## 行为零变化,逐条比对过

把改动前各处手写的列表原样取出来和新的比:面板 12 条、榜单 5 条、班级对比 6 条,
标签与取值逐条一致;11 个时段值的解析结果与旧的内联写法逐个相同。

唯一的差异在 `all`:旧写法产出 `{all: NaN}`,新写法回 null。**两边都到不了** ——
三处用到 subOptions 的地方全在 `query.duration === "all" ? … : …` 的 else 分支里,
三元短路,all 时根本不求值。逐处确认过。

## 实跑

- 榜单页:下拉 5 条顺序正确;切一周内,请求从 start=2026-08-10(months:1)
  变成 start=2026-09-03(weeks:1),正好差 7 天;
- 班级对比页:下拉 6 条含「全部时间」;两个班 PK,全部时间和一个月内都正常出结果;
- 提交统计面板:默认 minutes:10,统计请求的 start 正好比 end 早 10 分钟。

另:ChartJS.register 那 15 处**没有动**。逐个列出来看,它们注册的是各自需要的那一套,
不是同一份重复(真正逐字相同的只有 4 个 Bar 图和 2 个 Line 图),而且组件各自声明依赖
正是 chart.js 该用的方式 —— 没用到的控制器不会进包,忘了注册会当场抛
`"bar" is not a registered controller`,是响的不是静默的。集中注册只会把懒加载的图表
代码推进首屏,为省 6 处重复不值得。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012j1vgeDqay8wKCh8dPgPcH
2026-09-10 20:28:33 -06:00
xuyueandClaude Opus 5 8eae4bea7b feat(统计面板): 展开一个学生后按题目分组,每道题画一条「状态轨迹」
Deploy / deploy (push) Has been cancelled
老师展开一个学生,原来看到的是一排 12 位十六进制的提交编号按钮。编号本身没有信息量,
而一节课里学生常在好几道题之间来回跳,那一排看不出他到底卡在哪一道。

现在一道题一行:题号、标题、交了几次、过没过,后面跟一排按时间**从早到晚**的小方块,
颜色就是判题状态(绿=通过 红=答错 黄=编译失败/超时 灰=判题中)。
「八绿一红一绿」和「五黄到底」一眼分得开。

- **排序按老师的用法来**:没过的排前面,其中交得越多越靠前 —— 卡得最久的那道顶到眼前;
  已通过的沉底,它们只是「做完了」。
- 鼠标悬停出「状态 · 时间 · 提交号」,点击照旧打开提交详情。
- 「语法未过」(ast_check_failed) 算做出来了,和表格上「已解决」那一列口径一致。
- 方块用内联样式而不是 class:它们是 h() 出来、挂在 NDataTable 展开槽里渲染的,
  <style scoped> 能不能盖到并不确定。色值沿用 Naive 的语义色,和 ExerciseMatch.vue 一致。

为此 GET /submissions/statistics/items 多带三个字段(problem / problemTitle /
createTime)—— 原来只有 id 和 result,分组和悬停都无从谈起。innerJoin problem 不会漏行:
submission.problem_id 是 NOT NULL 且外键 NO ACTION,题目删不掉。

## 验证

起全栈在浏览器里真点过(提交列表 → 数据统计 → 提交记录 → 展开 student):

- 五道题各成一行,顺序是 1005(5次未过) → 1006(4次) → 1020(1次) → 1018(1次) →
  1004(10次已通过),符合「没过的在前、交得多的在前、已过的沉底」;
- 现造一条「先错后对」:轨迹读出来是 绿绿绿绿绿绿绿绿红绿,新交的 WA→AC 落在末尾,
  确认是从早到晚而不是倒序;
- 悬停取到「编译失败 · 09-02 22:03:14 · 9f02da4c5f01」。

tsc、check:routes、vue-tsc、vite build、单二进制编译均通过。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012j1vgeDqay8wKCh8dPgPcH
2026-09-10 20:09:09 -06:00
xuyueandClaude Opus 5 f581029eb2 refactor(统计面板): 抽出 useHiddenStudents,两份逐字相同的「请假隐藏」合成一份
StatisticsPanel.vue 和 FlowchartStatisticsPanel.vue 各写了一遍隐藏学生的逻辑
(loadHidden / saveHidden / hideStudent / showAll / onMounted 里的过期清理),除了
存储键和一个参数名逐字相同;「这个人有没有被隐藏」的判断两边还各自内联了三处。

现在是 shared/composables/hiddenStudents.ts,存储键作参数传进去 —— 两个面板仍然各用
各的键,提交统计里隐掉的人不该连带在流程图统计里也消失,那是两件事。

composable 不导出 hiddenStudents 那张表本身,只给 isHidden / notHidden:两个面板要的
都是「这个人该不该显示」,把表递出去只会让判断逻辑又散回组件里。

## 验证

起全栈在浏览器里真点了一遍(提交列表 → 数据统计 → 未完成 tab):

- 打开「请假隐藏」开关后学生标签变成可关闭,关掉「单田芳」,未完成从 5 变 4、
  「还没交」也同步从 5 变 4;
- localStorage 落的是 {"ks251单田芳": <时间戳>},刷新页面后仍在,到期时间 120 分钟;
- 流程图那把键 oj_hidden_students_flowchart 全程为 null,没被串到。

vue-tsc、vite build 通过。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012j1vgeDqay8wKCh8dPgPcH
2026-09-10 19:46:32 -06:00
xuyueandClaude Opus 5 eda1eb7eee chore(题单): 删掉客户端自报进度的 PUT /problem-set-progress
Deploy / deploy (push) Has been cancelled
这个端点是「AC 之后前端回调一下,把进度写进题单」那套设计的残留,早就被服务端记账
取代了 —— SubmitCode.vue 里留着当时的说明:客户端那条路只认路由参数里的那一个题单
(从普通题库入口做出同一道题不计进度),网络一抖、页面提前关掉进度就静默丢失;
现在判完之后由 judge/run.ts → services/problemset.ts 的 recordSolvedProblem 记账,
而且记进所有已加入且包含这道题的题单。

上一个提交删掉前端最后一个调用方 updateProblemSetProgress 之后,它就彻底没人打了。
留着的代价不只是死代码:那是一条**学生可以自己写进度**的写入口。

删之前逐个核过:
- 前端零引用(唯一的 wrapper 已在上个提交删掉);
- recomputeProgress 还有 POST 那条在用,保留;computeProgress / eligibleForBadge /
  updateAchievementsForProblemSet / publishAchievementNotification 在别处都有调用方;
- 它往 problemset_submission 写的那一笔,services/problemset.ts:260 做的是一模一样的
  去重后插入,不会因此少写。

顺带清掉因此变成孤儿的四个 import 和契约里的 updateProblemSetProgressRequestSchema
与 UpdateProblemSetProgressRequest。

## 验证

起服务实跑:
- PUT /api/problem-set-progress 现在 404;
- 保留的 POST(加入题单)仍然 201,progress 行照常由 recomputeProgress 建出来;
- 服务端那条替代路径端到端跑通:新建题单 → 加入题目 1004 → 学生加入 → 交一发 AC,
  判完后 problemset_progress 自动变成 completed=1/total=1/100%/得分 10,
  problemset_submission 也落了一行 —— 全程没有任何客户端回调。

tsc、check:routes、vue-tsc、单二进制编译均通过;测试题单已清理。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012j1vgeDqay8wKCh8dPgPcH
2026-09-10 19:42:17 -06:00
xuyueandClaude Opus 5 79bfd28b07 chore: 删掉 369 行没有任何调用方的代码
Deploy / deploy (push) Has been cancelled
## utils/functions.ts 砍掉一半(622 → 291 行)

- trickOrTreat():317 行、八种页面恶搞效果(中文乱码、页面翻转、去掉鼠标……),
  **全仓零调用**,占这个共享工具文件的一半;
- 文件末尾注释掉的 getChromeVersion / isLowVersion / protocol 六行。

## 其余没有调用方的导出

- services/achievement-metrics.ts 的 RARITIES / OPERATORS —— 和契约的
  achievementRaritySchema / achievementOperatorSchema 取值逐字相同,是没人用的第二份;
- collab/state.ts 的 hasRequest;以及 resetCollabState,它的注释写着「仅供进程退出或
  测试用」,而本仓库不写测试(项目约定),进程退出那条路径也没调过;
- contract/language.ts 的 JUDGE_LANGUAGES,注释说「前端用它排语言 tab」——前端并没有,
  它排 tab 用的是 constants.ts 里以 ProblemLanguage 为键的 SOURCES / LANGUAGE_SHOW_VALUE
  (那组映射的完整性 tsc 已经在管);
- web 的 useSimplePagination(usePagination 的一层空壳包装)和 updateProblemSetProgress。

扫描口径:三个包全部 .ts / .vue 里逐个导出符号数出现次数,只在定义处出现的算无引用
(.vue 模板里的引用也计入)。剩下 56 个仍无引用的全部是契约里 `z.infer` 派生的一行
类型(46 个请求类型 + 10 个领域类型)—— 它们是在用的 schema 的类型另一半,成体系的
1:1 镜像,删一部分只会让那个文件变得随意,所以不动。

## 留给你定的一件事

`updateProblemSetProgress` 删掉之后,后端 `PUT /problem-set-progress`(routes/problemset.ts:249)
就没有任何调用方了。题单进度实际是判完之后由 services/problemset.ts 的 recordSolvedProblem
在服务端记账的(schema.ts 里那条注释写明了),这个端点是一条客户端自报进度的平行路径。
没顺手删:删端点是行为变化,而且不能排除有脚本在打它。

tsc、vue-tsc、vite build、单二进制编译、check:routes、check:ast 均通过。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012j1vgeDqay8wKCh8dPgPcH
2026-09-10 19:38:16 -06:00
xuyueandClaude Opus 5 91712b482d fix(AST): f-string 规则从上线起就没生效过;加 check:ast 把这类静默错判变成机器检查
Deploy / deploy (push) Has been cancelled
## check:ast

判题机拿 target 的 node 去比 tree-sitter 节点类型,**对不上不报错**:collectNodes 一个
都收不到,于是「必须使用 X」永远失败、「不能使用 X」永远通过,两头不报错,只有学生
受着。上一个提交把两张表合成一张,杜绝了「漏配」,但「配错」照样静默 —— 所以加一个
检查,逐个 target 去问语法:这个节点类型你到底有没有。

    bun run --filter '@oj2/api' check:ast

升级 tree-sitter-* 之后必须跑:语法改节点名是常事,后果全静默。它只验节点类型存在,
不验语义对不对(把 while_loop 配成 for_statement 这种两个都存在,机器看不出来)。

## 它抓出来的那个

56 个 target 里坏了一个:Python3 的 f_string 一直配的是 format_string,而这个版本的
tree-sitter-python **根本没有这种节点** —— f-string 是一个 string,靠 string_start 为
f" 和内部的 interpolation 子节点来认。也就是说「不能使用 f-string」这条规则从上线起
就一直判成通过,「必须使用 f-string」一直判成失败。

改成 interpolation。实测:带占位符的 f-string(单双引号都有)命中,而 % 格式化、
.format()、普通字符串、字符串拼接都不误伤。代价是 f"abc" 这种没有占位符的 f-string
认不出来 —— 它确实不含 interpolation,但没占位符的 f-string 本来也没意义,比起原来
「一个都认不出来」是严格的改善。这条写在表里的注释上了。

## 验证

给题目 1004 配「必须有 for 循环 + 不能用 f-string」两条规则实跑:

- 有 for、用了 f-string → 修复前 ACCEPTED(0),修复后 AST_CHECK_FAILED(10),
  ast_results 为「必须使用 for 循环/通过」「不能使用 f-string/不通过」;
- 有 for、不用 f-string → ACCEPTED(0);
- check:ast 修复前 exit 1 并指出这一条,修复后 56 个全过、exit 0。

tsc、check:routes、vue-tsc、vite build、单二进制编译均通过。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012j1vgeDqay8wKCh8dPgPcH
2026-09-10 19:33:19 -06:00
xuyueandClaude Opus 5 a6ba5cdf07 refactor(AST): 两张 target 表合成一张,加节点类型漏配在结构上不再可能
契约的 AST_NODE_TARGETS_BY_LANGUAGE 是 target → 中文名,judge/ast.ts 的 mappings 是
target → tree-sitter 节点类型,同一批键分在两个包里,靠一句「两边必须同增同减」的注释
维持。只加一边是静默错判:老师给 C 题选到只有 Python 有的 list_comprehension,判题机
拿裸名去比节点类型,C 的语法树里永远不存在它,于是「必须使用列表推导式」永远失败、
「不能使用 f-string」永远通过,两头都不报错,只有学生受着。

现在一个 target 一条 { label, node }:label 给后台下拉和题目页,node 给判题机。加 target
而漏配节点类型在结构上就不可能了。judge/ast.ts 的 mappings 整张删掉,解析统一走契约的
astTargetNodeType()(节点查 node,运算符查运算符表 —— 那张表的值本身就是要比的 token,
判题机原来抄的 and→&& 三条取值逐个相同,纯属重复)。

顺带把同一份数据的四份拷贝收成一份:C 的 14 条原来在契约和判题机里各抄了两遍
(C 一份、C++ 一份),现在 C++ 逐条引用 C_NODE_TARGETS;运算符表的 C++ 改成
{ ...C_OPERATOR_TARGETS, "<<", ">>" }。C++ 那几条仍逐条列出而不是 spread,是为了保住
下拉框的显示顺序(C++ 独有的几条插在中间)。

## 验证

行为零变化,是逐个 target 机械比对过的:把 HEAD 版的两张表原样取出来,对三种语言的
全部 target 比对「label / 运算符文案 / tree-sitter 解析结果 / 下拉框顺序」四项 ——
C 37 个、C++ 47 个、Python3 43 个,全部一致,键集与顺序也一致。

实跑:给题目 1004 配两条 Python3 规则(必须有 for 循环、不能用 f-string),交一发没有
for 循环的正确答案,判成 AST_CHECK_FAILED(10),statistic_info.ast_results 为
「必须使用 for 循环 / 不通过」「不能使用 f-string / 通过」—— label 与 node 两半都走到了。
再交一发带 for 循环的,判成 ACCEPTED(0)。

tsc、vue-tsc、vite build、单二进制编译均通过。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012j1vgeDqay8wKCh8dPgPcH
2026-09-10 19:30:35 -06:00
xuyueandClaude Opus 5 8520192a98 refactor(前端): websocket 合并三层继承与三份重复 composable,803 → 660 行
Deploy / deploy (push) Has been cancelled
## 删掉的

- **六个从没人传过的配置项。** WebSocketConfig 上的 maxReconnectAttempts /
  reconnectDelay / maxReconnectDelay / heartbeatTime / enableHeartbeat /
  enableAutoReconnect,六个默认值、六处 ??,而三条通道从建起来到现在没有一个调用方
  传过任何一个,也没在运行时改过。收成三个模块常量,连带三处恒真/恒不触发的分支
  (if (enableHeartbeat)、!enableAutoReconnect、reconnectAttempts >= Infinity)。
- **一个没人用的工厂。** createWebSocketComposable 顶着二十五行 @example,示例里那条
  通知通道并不存在,三个真实 composable 一个都没调它,各自手写一遍转发对象。
- **三个空壳子类。** SubmissionWebSocket / FlowchartWebSocket / ConfigWebSocket 的全部
  内容就是在构造函数里拼 URL;前两个连 URL 都是同一条 /ws/submissions,两个类加两份
  三十行 composable 的差异只有一个类型参数。改成 useChannel(path, handler) 一个工厂,
  三个 useXxxWebSocket 各自只剩一行。
- SubscribingWebSocket 这一层并进基类:三层继承变两层,只剩 CollabWebSocket 还在扩展
  (它确有自己的二进制缓冲与房间语义)。URL 拼接收进 channelUrl()。

行为一处没动:重连仍然不封顶(后端 deploy 重启一次就超过原来那 15 秒,这条注释保留)、
指数退避带抖动、30 秒上限、心跳 30 秒、force_logout、断线重连补订阅全部照旧。

## 验证

起全栈用浏览器实跑:

- 提交一发 Python3,/ws/submissions 连上并推回 judging → judging → finished,
  控制台没有出现「WebSocket未及时响应,启动轮询保底」,即结果确实走的 WS 而非轮询;
- kill 掉后端观察三条通道重连:682ms → 1.4s → 2.4s → 4.4s → …… → 15~26s 封顶,
  指数退避与 30 秒上限均符合;
- 后端起回来后**不刷新页面**自动恢复(/ws/config、/ws/collab 各自重连成功),
  再提交一发仍然全程走 WS —— 这正是「重连不封顶」要保的场景;
- vue-tsc --noEmit exit 0;vite build 通过。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012j1vgeDqay8wKCh8dPgPcH
2026-09-10 18:25:47 -06:00
xuyueandClaude Opus 5 ab47e71d6f refactor(契约): 出参不再 parse,后台老题详情和站内信页不再 500
Deploy / deploy (push) Has been cancelled
## 出参改 satisfies

出参是后端自己刚拼出来的字面量,TS 编译期已经验过;再 xxxSchema.parse({...}) 一遍
拿不到任何新信息,唯一可能失败的输入是库里的历史数据,而失败的代价是 500。136 处
全部撤掉,撤的时候当场炸出两个一直存在的线上故障:

- 后台打开任何一道没编辑过的题都是 500 —— problem.last_update_time 是全库唯一可空
  的列(961 道题里 470 道是 NULL),而 adminProblemSchema.lastUpdateTime 写的是
  z.string();
- 收到过站内信的人打开消息页全是 500 —— embeddedSubmissionSchema 从
  submissionDetailSchema 继承了 problemDisplayId 却没 omit,路由只填了同义的
  problem;列表为空时才碰巧不炸,所以一直没人报。

两个都是读出侧校验自己造出来的故障,不是它拦住的故障。

## 校验责任挪回写入侧

- db/schema.ts:枚举型的列和几个形状确定的 JSONB 挂 .$type<>()(submission.result /
  .language、problem.difficulty / .languages / .template / .astRules / .sqlConfig /
  .sqlDisplay、achievement.rarity / .operator、exercise.type、reaction.type、
  tutorial.type、problemset.difficulty / .status、flowchart_submission.status、
  problemset_badge.condition_type、acm_contest_rank.submission_info)。只影响 TS、
  不产生 SQL,断言逐列拿根目录那份生产备份核过全量数据。
- createProblemRequestSchema.languages 收窄成 problemLanguageSchema,兑现
  problem.languages 列上的断言。
- 新增 routes/helpers.ts 的 asFilterValue():query 筛选值(result / language /
  difficulty / status)要和收窄过的列比较时做纯类型交接,不加校验 —— 在这儿拦一道
  会把「筛出空列表」变成「筛条件被忽略、返回全部」。
- 判题产物(submission.info / statistic_info / exercise.data)照旧放行,形状真相
  在判题机那边;judge/sql、flowchart/run、events.ts 里对自家产物的 parse 一并撤掉。
- 仍然 parse 的只有 judge/events.ts 的 parseSubmissionEvent —— 从 Redis 收回来的
  报文是真边界,失败返回 null 而不是 500。

顺带清掉两处重复的真相:stringArray 原本在 routes/helpers.ts、routes/problem.ts、
routes/submission.ts 各有一份拷贝,5 个调用点全部只作用于 problem.languages,列有类型后
三份一起删;routes/site.ts 里和契约同名同形的本地 interface Quote 也删了 —— loadSentences
读入时已经逐字段守过,那处 parse 同样是多余的。

## 文档

CLAUDE.md 那一节从「契约收紧要挑地方」改写成「出参不 parse,用 satisfies」,写明
三处写入侧闸门(入参 safeParse 58 处、列上 $type、语义校验函数);apps/web/CLAUDE.md
同步 —— 现在收紧字段的后果落在 tsc 编译期,但契约形状仍要对得上存量数据。

## 验证

- 生产备份全量:12.4 万条提交的 result 全在 -2..6,10、961 道题的 languages 均为合法
  数组、10050 条榜单条目形状全对,无一例外;
- tsc -p apps/api 与 vue-tsc --noEmit 均 exit 0;check:routes 检查 177 条路由,无遮蔽;
  前端 build、单二进制编译并在仓库目录之外启动均通过;
- 实跑 40+ 端点(学生端 / 后台 / AI / 榜单 / 题目回写往返),以及一次完整比赛 e2e:
  建比赛 → 复制题目 → 错解 → 正解,把 judge/run.ts 榜单写入的三个分支全走到
  (error_number 0→1、is_first_ac + ac_time 671、totalTime 1871 = 671 + 1×20×60),
  后台核查页的勾选与 404 分支一并验过,测试数据已清理;
- 两个 500 用抓到的真实响应对着改动前的契约复验:lastUpdateTime 收到 null、
  problemDisplayId 收到 undefined,改动后同样两个响应均通过。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012j1vgeDqay8wKCh8dPgPcH
2026-09-10 18:14:05 -06:00
xuyueandClaude Opus 5 b9a80d62bc docs(CLAUDE.md): 合并顶部叠着的更正块,订正前端验证方式,补上契约收紧的边界
## 顶部

两层引用块套着一段「2026-09-10 更正」,说的是同一件事的两个版本(7 张表已删 →
其实还剩一张)。合成一段现状:旧栈不可逆下线、唯一退路是备份恢复、漏网那张
django_migrations 由 0014 补删。考古过程留在迁移文件的注释里,这里不重复。27 行 → 14 行。

## 常用检查

`cd apps/web && bun run build` 后面那句「vite 不做类型检查,构建即验证」是错的:
vite 确实不做类型检查,但**构建也不是验证**。补上 `bun run type-check`,并写明两条
会静默通过的假路子 —— `vue-tsc --noEmit -p tsconfig.json` 检查 0 个文件(那个
tsconfig 是 files: [] + references 的壳,0.2 秒跑完就是信号)、`vite build` 不看类型。
后端也改成 `bun run --filter '@oj2/api' typecheck`(脚本本来就有)。

## 新增「契约收紧要挑地方」

前一个 commit 的教训值得留在这儿:契约 schema 后端也在读路径上 parse,收紧字段
等于给历史数据加闸,对不上要么 500(exerciseSchema)、要么静默塌成 {}(info,
9163/124192 条)。JSONB 原文的形状真相在写入侧,闸就设在那里;要收紧先拿生产备份
跑全量,重点看空值不是键集合。AST 规则的 astRulesError() 本来就是同一个道理。

## apps/web/CLAUDE.md

Commands 段还是 ojnext 时代的 npm start / npm fmt,全部换成 bun 并补上 type-check
的坑。Module Pattern 写的 `views/` 这一层实际不存在(页面组件直接放模块根下),
api.ts 也不按模块分(学生端 oj/api.ts、后台 admin/api.ts、跨端 shared/api.ts)。

工作区根目录的 CLAUDE.md / AGENTS.md 同样折叠了那段更正、订正了类型检查命令
(那两份不在 git 里)。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012j1vgeDqay8wKCh8dPgPcH
2026-09-10 04:57:34 -06:00
xuyueandClaude Opus 5 7d15e6aeaa refactor(契约): 判题产物退回不校验,练一练的形状闸挪到写入侧,运行时闸门收回三处
前四轮把契约当成运行时闸门铺开,复盘下来三块里只有一块是赚的:类型收拢成一份
(语言联合、Problem/Message/ContestRank 的重复派生)留着;另外两块退回来。

## 判题产物:读出侧不再校验

judgeCaseResultSchema 按采样键集收紧的结果,用根目录那份生产备份全量跑了一遍:
124192 条提交里 9163 条对不上,**RE 8480/8480、TLE 338/338+26、MLE 1/1 全中**,
另有 270 条 WA、47 条 AC。原因不是键集合,是空值和 SQL 链路:

- 沙箱在非正常退出的测试点上写 `output_md5: null`,契约写的是 z.string();
- SQL 判题(judge/sql/engine.ts 的 CaseResult)根本没有 `output` 键;
- SQL 通过的测试点 `error_message` 是 null,契约写的是 z.string().optional()。

更糟的是失败方式:`info` 是 `union([完整形状, z.object({})])`,对不上的一律落进
第二支被剥成 `{}` 且 parse 成功 —— 管理员详情页的测试点表格**静默消失**,无日志。

JSONB 的形状真相在写入侧(判题机),读出侧再校验一遍只会在两边分叉时丢数据。
所以 `info` 回到 z.unknown(),形状改用 JudgeInfo / JudgeCaseResult 两个 TS 类型
描述(按判题机实际写的形状,不是采样出来的),取值处由 submissionCaseResults()
做唯一需要的运行时判断:有没有 data 数组。statisticInfo 换成 looseObject ——
所有键可选、不剥未知键,对任何对象都不会失败,它的作用是给类型不是当闸门。

## 练一练:形状闸从读路径挪到写路径

exerciseSchema 的 superRefine 挂在读路径上,而这个 schema 后端也在 parse
(routes/content.ts),等于一行脏数据就能让整条学生练习列表 500。同时写入侧的
exerciseDataError **一次都没查过 question**,两边严紧度不一致,脏数据进得来出不去。

exerciseDataByType 保留,改由 exerciseDataError 在写入前查,错误信息按字段翻成
中文给老师看;读路径回到不校验。

## 运行时闸门收回三处

contract() 从 41 个端点收回到题目详情 / 提交详情 / 用户资料 —— 原本就写了
.parse() 的那三条。留着的理由是「别抛错」(原来 parse 抛 ZodError 会白屏、
后面的 as 又让校验白做),不是校验:前后端同仓、共享同一份 schema,字段漂移
tsc 已经抓了。闸门本身也瘦掉了没人读的 window.__OJ2_CONTRACT_DRIFT__ 那套簿记。

## 验证

- 生产备份全量:124192 条提交过 submissionDetailSchema / submissionListItemSchema
  零失败,其中 112144 条能拿到测试点明细(另外 12048 条本来就是 data:null);
  151 道练习读路径 151/151、写入闸 151/151(老师改旧题不会被新闸挡);
- 反向验证写入闸:缺题干的排序题被拒并给出「题干的格式不对」;
- 本地实跑:种一条生产形状的 RE 提交(output_md5: null),管理员详情接口原样
  返回 info.data(改之前是 {});库里塞一行没有 options 的 mcq,学生端练习列表
  照常返回两条而不是 500;
- vue-tsc / tsc -p apps/api 均 exit 0,vite build 通过,check:routes 无遮蔽。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012j1vgeDqay8wKCh8dPgPcH
2026-09-10 04:53:28 -06:00
xuyue 684f2d29a5 feat(契约): 练一练的内容按题型收进契约,7 个题型组件不再裸读 data
Deploy / deploy (push) Has been cancelled
`Exercise*.vue` 七个组件直接读 `data.question` / `data.options` / `data.lines`,
而契约里 `data` 是 `Record<string, unknown>`(后端不校验)、前端只做了类型收窄
—— 也就是说这条路径**从来没有在运行时被看过一眼**,结构对不上时渲染期才炸。

现在 exerciseSchema 用 superRefine 按外层 `type` 分派到对应的内容形状,
外层与 data 对不上也会被抓住(`type: "mcq"` 配 `{question, code}` 会在渲染
mcq 组件时炸在 `data.options`)。七个题型的键集按生产库实测确定。

**这个 schema 后端也在 parse**(routes/content.ts 的 `exerciseSchema.parse`),
所以收紧它同时是一道服务端闸门:坏数据会让练习列表 500。因此先用生产全量
数据核验:151/151 通过,且反向验证确认能抓住题型与 data 不匹配的情况。

`getExercises` 另加了一层逐题型校验,让前端也能把内层分歧记进
`__OJ2_CONTRACT_DRIFT__`;`z.infer` 拿不到判别联合(superRefine 无法把校验
结果反映到推断类型上),所以类型上仍需一次经过 unknown 的断言 —— 它不掩盖
未经检查的分歧,因为运行时那一步已经做过。

顺带补上 getFlowchartSubmission 的闸门;被守卫端点达到 41 个。

验证:vue-tsc 与 tsc -p apps/api 均 exit 0;vite build 通过;check:routes 无遮蔽。
2026-09-10 04:28:26 -06:00
xuyue 5da661d7f0 refactor(契约): 补上 AI / 站内信 / 自学留痕等接口的闸门,并订正前端 CLAUDE.md 的过期内容
Deploy / deploy (push) Has been cancelled
闸门再补 13 个端点:AI 系列(detail / solved / duration / heatmap /
login-summary / pinned)、站内信列表、教程列表与学习进度、题目逐年 AC、
流程图列表。学生端读接口至此基本覆盖(写操作与纯前端伪状态不接)。

文档订正(原文写着"后端是 ../OnlineJudge 的 Django 5"、"utils/http.ts"、
"utils/permissions.ts",这些都早已不存在):
- 项目概述改成 OJ2 前端,并点明要兼容机房老 Chrome;
- HTTP 客户端改成实际存在的 utils/api.ts;
- 新增「Contract guard」一节,把**失败策略**(记日志 + 放行原始数据、不抛错)
  和排查入口(window.__OJ2_CONTRACT_DRIFT__)写清楚,并提醒同一个 schema
  后端也在 parse、收紧前要用生产数据核验;
- Related Repository 指向同仓的 ../api 与 packages/contract。

验证:vue-tsc 与 vite build 通过;13 个新端点对真实接口全部通过
(11 通过 / 0 失败 / 0 跳过)。
2026-09-10 04:25:24 -06:00
xuyue de34a47996 refactor(契约): 契约闸门铺到其余学生端接口,并清掉与契约等价的重复类型
Deploy / deploy (push) Has been cancelled
## 闸门覆盖

从 7 条扩到 20 条:竞赛列表/详情/口令/榜单、题单列表/详情/题目/徽章/进度、
全服榜与活跃榜、公告列表/详情、教程、用户度量、流程图历史/当前/统计、
提交统计与统计明细、相似题目、题目 AC 榜。

## 顺手把两处形状收进契约

- `contestRankItemSchema.submissionInfo` 原来只是 `Record<string, unknown>`,
  前端被迫再声明一份 `SubmissionInfo` 去覆盖它。现在 JSONB 的 snake_case 形状
  (is_ac / ac_time / is_first_ac / error_number / checked)进了契约,那层覆盖随之消失。
- 竞赛题目列表用 `problemListItemSchema.array()` 而不是契约里的
  `contestProblemsSchema` —— 后者是 `array(union([列表项, 详情]))`,联合类型会让
  `filterResult` 的类型收窄落到详情分支,而且学生侧这条接口只下发列表项。

## 清掉两处确证重复的派生

用类型探针(双向可赋值)逐对验证,`Problem` 与 `Message` 的本地派生与契约**完全等价**,
是没有内容的重复:`Problem` 的 languages/template 收窄、`Message` 的 submission 收窄
都已经在前两轮搬进契约。其余七处派生(Submission 的 result|9、Profile、AdminProblem、
Exercise、ContestRank、BlankProblem、TutorialEdit 等)探针确认**不等价**,都有真实理由,
一律保留。

`Problem` 原来还挂着 hasAstRules / visible / answers 三个可选字段,探针证明它们对
赋值没有影响(契约里本来就有 hasAstRules),去掉后没有任何调用点报错。

## 验证

- vue-tsc 与 tsc -p apps/api 均 exit 0;vite build 通过;check:routes 无遮蔽;
- 契约 schema 直跑真实接口:学生会话 13 通过 / 0 失败,管理员会话 15 通过 / 0 失败;
  跳过的三条都是预期的权限或空数据(/submissions/statistics 与 /flowcharts/statistics
  要教师权限、/users/:id/metrics 只统计公开提交)。
2026-09-10 04:23:41 -06:00
xuyue aab0404ed7 refactor(契约): 语言与判题产物的形状收进契约,学生端高频响应接上运行时校验
Deploy / deploy (push) Has been cancelled
契约在前端一直只当类型包用:45 处引用里几乎全是 import type,三个 .parse() 后面
还都紧跟一个 as 把校验结果断言回去,等于没校验。这一轮把形状的来源收拢。

## 语言:三份真相并成一份

前端 utils/types.ts 手写了一份 9 值的语言联合,后端 judge/languages.ts 有自己的一套,
生产库又有一套。手抄那份**漏了 SQL**,而生产库 961 道题里有 9 道 SQL 题、
124191 条提交里有 91 条 SQL 提交 —— 这些提交的 language 在前端类型上是 undefined。
现在唯一来源是契约的 problemLanguageSchema,constants.ts 的显示映射以它为键,
契约里加语言而那边没补映射会当场编译不过。

## 判题产物:按生产数据实测收紧

judgeInfoSchema / statisticInfoSchema 的形状来自 124191 条提交的实测,不是手抄:

- info.data 有 12048 条是 null(编译失败等没有逐测试点结果),前端手抄的 Info
  却把 data 写成非空数组 —— 这 12048 条在类型上根本不成立;
- info 还允许**空对象**:非管理员看提交详情时后端下发 info: {}(权限投影)。
  收紧时必须把它算进去,否则每条非管理员看的提交详情直接 500 —— 本地实测复现过;
- statistic_info 的五个键按出现次数定成全部可选;另有 8916 条 JSONB 原文因内嵌
  带转义的 shell 输出不是合法 JSON,被后端 objectValue() 兜成 { value: ... },
  所以不能用严格对象,否则这 8916 条会被误判成分歧。

## 运行时闸门

新增 utils/contract.ts:safeParse 失败时记一条分歧(去重、控制台可见、
window.__OJ2_CONTRACT_DRIFT__ 可查)后**放行原始数据**,不白屏 —— 面向学生的
生产站点,字段空着比整页崩掉可接受。接在 7 条高频链路上:/site、/site/online、
/problems、/problems/:id、/submissions、/submissions/:id、/me。

提交详情的 info 是联合类型,调用方不再直接取 .data,统一走
utils/functions.ts 的 submissionCaseResults()。

## 验证

- vue-tsc 与 tsc -p apps/api 均 exit 0;vite build 通过;
- 契约 schema 直跑真实接口:7/7 通过(自包含脚本,从登录到详情全链路);
- 用生产备份复核收紧后的约束:961 题的 languages 无越界值,template 只出现
  C/Python3 两个键 —— 不会因为这次收紧在生产上抛错。
2026-09-10 04:19:41 -06:00
xuyue a475cac128 fix(数据库): 生产库里还留着一张空的 django_migrations,补一条迁移删掉
Deploy / deploy (push) Has been cancelled
0002_drop_django_leftovers 声称删掉了旧 Django 的 7 张框架表,但生产库实测有 29 张
public 表 = schema.ts 的 28 张 + 一张 0 行的 django_migrations:另外 6 张
(auth_group* / auth_permission / django_content_type / django_dramatiq_task /
django_session)确实都不在了,只有它残留下来。原因已无法从库里复原——0002 的记账行
在,说明当年执行过,而 DROP TABLE IF EXISTS 不会静默跳过它后面的语句。

全仓(二进制、路由、compose、脚本)零处读写这张表,表里 0 行,所以直接删掉。
用 IF EXISTS 让两条既有路径收敛到同一结构:空库自举时 0002 已经删过它(空转),
老生产库还留着(真正动手)。实测两条路径出来的 pg_dump --schema-only 逐字节一致。

「旧栈起不来」这个结论不变——它缺的是 django_session 等表,不是这一张。

迁移会被破坏性迁移闸拦下,这是有意的,放行方式记进了 CLAUDE.md。
2026-09-10 04:02:33 -06:00
xuyue 78a42a42e7 update
Deploy / deploy (push) Has been cancelled
2026-09-10 03:44:32 -06:00
xuyueandClaude Opus 5 26b23aa7c0 fix(统计): 「提交记录」列出所有交过的人,不再只有做完的
Deploy / deploy (push) Has been cancelled
统计面板那张表原来只给 `isDone` 为真的人,于是一次没对的学生连同他的提交
在面板里根本不存在——tab 却叫「提交记录」,看起来就像统计只认成功的提交。

- `data` 改成给窗口里交过东西的全部人,每行带 `done`;「完成人数」和完成度
  跟着 `done` 数,不是 `data.length`,两个数字口径不变。
- 表格加「完成」列区分两种人;展开行拉的仍是那个人的全部提交(items 接口
  本来就不按结果过滤),对错都在里面。
- 「交了没全对」那一栏原来无条件按花名册取,不填班级/用户名时花名册为空、
  整栏跟着空掉,这批人两栏都不在。改成没有花名册时退回「有提交但没做完的
  全部普通学生」,教师和禁用账号仍然排除;全站视图里保留完整用户名不剥班级
  前缀。「还没交」那一栏没有花名册是真算不出来,仍然为空。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PZbWEaPCnGvmdfNFpPFNGb
2026-09-08 23:52:34 -06:00
xuyueandClaude Opus 5 6bef55904f fix(题目分析): 「卡住的题」只看公共题,别把比赛题也算进来
Deploy / deploy (push) Has been cancelled
这条查询原来一个 where 都没有,比赛题一起进榜。隔壁 ac-trend 在同一个文件、同一块
面板,isNull(contestId) 写得明明白白,所以判定是漏写而不是口径选择。

比赛题的题号是每场比赛各自从 1 开始编的(快照里 61 道不同的题都叫「1」、61 道叫
「2」),一旦挤进前 40,那一行显示的题号会指向一道根本不存在的公共题。眼下还没
发生:前 40 的门槛是 97 人卡住,比赛题最多的一道是 59 人 —— 但两个班一起考的场次
有 95 人,撞上一道难题就够得着。

对公共题的数字没有任何影响:比赛提交挂的是比赛自己的 problem 行(快照实测两个方向
的交叉都是 0 条),公共题那一行本来就只统计自己的提交。实跑接口逐行比对,改前改后
前 40 集合完全一致,只有三处并列名次的先后不同 —— 那是这条查询本来就没有确定性
tiebreaker,并列的题在两次刷新之间也会自己换位置。

顺带能用上 0013 的 submission_public_metrics_idx:183ms / 18646 buffers →
80ms / 788。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KqjE6qPo67fqVDKn6Bx7yd
2026-09-08 18:30:05 -06:00
xuyueandClaude Opus 5 80f3b21e95 perf(索引): 0012 删 21 个冗余索引,0013 加 4 个筛选/聚合索引
0012 —— 删的都是 Django 建的,列是某个复合索引的最左前缀,规划器本来就走那一个,
多出来的只是每次写入多维护一棵树:17 个前缀被覆盖的、3 个 _like(text_pattern_ops)
副本、1 个同表同列的完全重复(problemset_submission.user_id 上有两个)。
索引 107 → 86 个,32MB → 29MB。

删之前逐条确认过复合索引的第一列就是被删索引的那一列,删之后 19 条代表性查询的
执行计划逐条对过,没有一条退化成 Seq Scan,只是换了覆盖它的那个索引;级联删除会
用到的外键检查路径也都还有索引可走。

0013 —— 拿 auto_explain 把 60 多个读接口打一遍抓出来的真实慢查询,候选索引一个个
建出来实测:

- submission (language, create_time) WHERE contest_id IS NULL — 3.2MB
  语言筛选原来一个索引都没有,count 固定 75~82ms / 18448 buffers,筛什么值都一样。
  改后 Python3(占 8 成)80 → 11ms、C 77 → 1.6ms、SQL 82 → 0.06ms。更要命的是冷门
  语言翻页:Python2 只有 3 条全是 2022 年的,分页索引得从最新倒扫到底,43ms 全表扫
  → 0.02ms
- submission (result, create_time) WHERE contest_id IS NULL — 3.2MB
  count result=-1 75 → 2.0ms、result=-2 36 → 1.0ms
- submission (user_id, problem_id, result, create_time) WHERE contest_id IS NULL — 4.2MB
  覆盖索引,给「在全部公开提交上做聚合」那几个接口。它们慢的不是聚合本身,是为了读
  这四个小列把 145MB 的堆翻一遍(code 和 info 占了这张表绝大部分体积,聚合一列都用
  不上)。走 Index Only Scan 只读 6MB:教师统计全站 186 → 49ms(消掉 4.2MB 落盘
  排序)、活跃榜 108 → 18ms、AC 趋势 120 → 41ms
- flowchart_submission (create_time) — 64kB
  列表分页从 hash join 全表再 top-N 排序(4.5ms / 551 buffers)变成 0.19ms / 47

全列 ASC NULLS LAST 靠反向扫,理由同 submission_public_create_time_id_idx 那段注释。
动手前把三种写法在库上对了一遍:两列 ASC 和 create_time DESC NULLS FIRST 一样快,
写成 DESC NULLS LAST 规划器直接不认这条索引、回落到分页索引带 Filter,注释没说错。

回归检查:不带筛选的列表和深翻页仍然走 submission_public_create_time_id_idx,没被
新索引抢走。submission_result_37e2f67a 留着并补了注释 —— 它看着像被新的部分索引
覆盖了,但那条带 WHERE contest_id IS NULL,管不了全库含比赛按 result 统计(实测删掉
之后 count(*) where result in (6,7) 从走索引掉回 75ms 全表扫)。

两条迁移都在生产结构副本和本机 dev 库各跑过一遍。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KqjE6qPo67fqVDKn6Bx7yd
2026-09-08 18:29:53 -06:00
xuyueandClaude Opus 5 a5b57d8ab8 fix(判题): 任务被遗弃时给提交落一个终态,别永远停在「等待评分」
judgeSubmission 自己的 try/catch 已经把正常路径上的异常都接住、落成 SYSTEM_ERROR
了,但队列的 failed 事件只有一行 console.error。判题队列没配 attempts(flowchart
队列配了 3),失败即终局;worker 进程被杀那种 —— 机房断电、容器 OOM、部署重启 ——
BullMQ 走完 stalled 重入队还是没人接,最后 emit failed,那条提交就永远停在
「等待评分」:学生看着转圈,教师统计里还占着一个「判题中」的名额。

加 failAbandonedSubmission(),在 failed 里调用,复用已有的 markSystemError(只动
PENDING/JUDGING,判完的和重判过的都不会被覆盖)。三种情况实跑验过:不存在的提交
安全返回、卡住的那条变成 result=5 并写入 err_info、已 AC 的那条没被动。

生产库里 3 条卡死的 PENDING(2022-11 / 2026-03 / 2026-04)都是旧栈时代留下的,
OJ2 上没有实例 —— 这次是把口子堵上,不是修已发生的故障。那 3 行和跟着差 1 的三道题
计数器还得手工处理。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KqjE6qPo67fqVDKn6Bx7yd
2026-09-08 18:29:30 -06:00
xuyueandClaude Opus 5 64ad6139f5 fix(后台用户): 删账号前拦住还有提交的人,改名回填按 user_id
两处都是「提交与用户的归属」在写路径上没维护住。

删账号:处理器那段注释早就点到了 submission.user_id 没有外键、全连坐会留下孤儿行,
但只把它当成「不改成 CASCADE」的理由,没有加对应的检查。结果是报错文案里写着
「该用户还有提交、题目等历史数据」,而提交恰恰是唯一拦不住的那一类 —— 只交过题、
没拿过成就没进过题单没参加过比赛的学生照样删得掉。

生产快照实测复现:删 id=1454(李若菡,13 条提交)返回 200 deleted:1,用户没了、
13 条提交留在库里,孤儿总数从 935 涨到 948。那 935 条就是这么攒出来的(28 个已删
账号)。线上今天还有 5 个这样能删的学生。

补一次提交查询把它拦下来,和 delete 放同一个事务里免得中间正好交了一发。文案一个
字没改 —— 它本来就是对的,缺的是兑现它的代码。混批删除整批回滚,干净的那个也留着。

存量 935 条不动:四条读路径现在都用 leftJoin 兜住了,列表显示冻结的名字、不出死链,
统计按 user_id 聚合他们本来就不在花名册里。加外键得先清历史数据,收益只有「以后
不再产生」,而那一半这次已经解决了。

改名回填:条件从「等于旧用户名」改成按 user_id。前者只改得动当前正好还等于旧名的
行,一个已经漂移过的账号再改一次名,更早那批仍然改不动 —— 库里 726 条挂着旧名字的
提交就是旧栈时代这么留下的,之后每次改名都从它身边绕过去。实测拿 user 2039 验过:
user 表叫 ks248吴紫妍、13 条提交挂着 ks24数媒1班ks吴紫妍,老写法一行都匹配不上,
改成按 user_id 之后一次拉平。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KqjE6qPo67fqVDKn6Bx7yd
2026-09-08 18:29:19 -06:00
xuyueandClaude Opus 5 a89eed7bdd fix(提交统计): 按 user_id 归属提交,不再按提交时冻结的用户名
submission.username 是提交那一刻的快照。教师统计全程拿它当主键用 —— ilike 过滤、
group by、再拿结果去 user 表 join 班级 —— 学生改名之后旧提交还挂着旧名字,一条都
匹配不上。

生产快照实测(2026-09-08):24 级数媒两个班改成编号制用户名之后,查 ks249 旧口径
0 条、新口径 7 条,整个班 48 人全掉进「一条没交」;查 ks248 是 20 条 / 54 条,
13 个人的成绩查不出来。ks248林依晨那 8 条提交原来一条看不到,人在「一条没交」栏,
现在落到「交了没完成」并带出最后一次失败在 1082 题。

四条路径一起改:

- /submissions/statistics 的过滤、聚合、花名册全部改按 user_id,用户名从 user 表
  join 出来。已删号的学生 user 表里没有行,退回提交里冻结的名字(personCount
  那句兜底就是给这种情况的)
- /submissions/statistics/items 展开行先把用户名解析成 user_id
- /submissions 和 /contests/:id/submissions 的用户名筛选取并集:user_id 匹配到的
  账号,加上按冻结用户名匹配的(已删号的 28 个账号只剩这一份名字,顺带「按记得的
  旧名字搜」也还查得到)。列表显示的名字改成当前用户名,否则筛 ks248 出来一堆写着
  ks24数媒1班ks的行,看着像筛错了
- /rankings/activity 同样按 user_id 分组。这条眼下是预防性的:改过名又有 AC 记录的
  4 个人只有 1~2 题,够不到前 10,但真上榜会显示旧名字或被拆成两条

顺带把统计接口的四次全表扫换成索引扫:ilike 走不了索引,换成 user_id in (...)
之后单条 18448 → 537 buffers,整个接口查一个班 120~250ms → 10ms 上下。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KqjE6qPo67fqVDKn6Bx7yd
2026-09-08 18:29:02 -06:00
xuyueandClaude Opus 5 9c5a1d551d perf(教师统计): 展开行的明细改成按需拉,统计响应不再背着 4.9 万行没人看的数据
Deploy / deploy (push) Has been cancelled
上一版把明细收成「只取有 AC 的人、每人最近 50 条」,拿生产快照(12.4 万条提交)
实测下来只从 105631 行降到 49108 行 —— 2.1 倍,不是一个数量级。原因是绝大多数人
本来就不到 50 条,每人截断那道闸在真实分布上基本没咬到,最坏情况响应体仍有 ~2.4MB。

真正的问题是形状不对:表格一次只展开一行(updateExpandedRowKeys 只留最后一个 key),
却给 1900 个人各准备了一份。所以明细整个从统计响应里拿掉,改成展开时按需拉:

- 新端点 `GET /submissions/statistics/items`,要用户名 + 同一套时间窗和题号。
  用户名这里是**精确匹配**,不是统计接口那种 ilike —— 那边填 ks251 要圈出整个班,
  这边是「点开的这一行是谁」。上限 200 条,多取一条来判断 truncated,被截断时
  展开行里说明「只显示最近 200 条」,免得老师以为这人就交了这么多。
- 时间窗和题号抽成共用的 statisticsScope,两个接口必须同一个范围,否则展开行
  看到的是另一个窗口的数据。
- 前端按人缓存,收起再展开不重拉;每次重新统计(含 15 秒自动刷新)清缓存,
  并把当前展开着的那一行重拉一遍 —— 展开行跟着一起活着,不然刷新之后上面的数
  变了、下面的明细还是老的。
- 去重放在 loadItems 里:点一行会同时走 rowProps 的 onClick 和表格的
  update:expanded-row-keys,两边都想拉,改之前真发出了两条一模一样的请求。

顺带把 submissionItems 从 submissionStatisticsUserSchema 里删掉。

生产快照上的验证(12.4 万条提交 / 1956 用户 / 961 题,恢复进一次性容器跑完即删):

- 最坏情况(全部时段 + 不填条件)少搬 49108 行,约 2.4MB
- 真实课堂量级(最忙的一小时:583 条提交 / 81 人)四条查询分别是
  主聚合 45ms、明细 6.5ms、语法未过 2.4ms、最近错因 <1ms
- 「已解决」那条口径修正的实际影响:13.3% 的「人×题」有重复 AC,同一题最多 AC 45 次;
  按人看最夸张的是 419 条 AC 其实只有 38 道题
- 语法要求的题 15 道、result=10 共 57 条,其中「最后也没改对」的 18 个人×题
  —— 角标会出现,但稀有

浏览器实跑:展开前不发明细请求;展开后 1 条、12 个按钮;收起 +0、再展开 +0(走缓存);
自动刷新时统计与明细 1:1 配对、间隔 15 秒,没有重复请求。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KqjE6qPo67fqVDKn6Bx7yd
2026-09-08 05:43:32 -06:00
xuyueandClaude Opus 5 fdfb064d0c fix(备份): 磁盘余量检查在老 mawk 上崩掉
Deploy / deploy (push) Has been cancelled
服务器上跑 backup-db.sh 报:

    docker/backup-db.sh: 第 132 行:[: 4.29685e+10: 需要整数表达式

`df -Pk | awk 'NR==2 { print $4 * 1024 }'` 让 awk 做了那个乘法。**mawk 1.3.3**
(老 Debian 的 /usr/bin/awk)打印超过 2^31 的整数时会退回 OFMT(%.6g),42968547328
就成了 `4.29685e+10`,丢回 [ ] 比大小当场退出。用 debian:buster-slim 复现出了
一模一样的字符串;mawk 1.3.4(现在的 stable)和 busybox awk 都正常打整数,
我本机是 gawk,所以测不出来。

改成原样取 df 的第 4 列(KB),乘 1024 放到 bash 的 64 位算术里做,谁的 awk 都一样。
另外加一层 digits_or_zero:df 或 psql 返回的东西不是纯数字就当「读不出来」,
**跳过余量检查照常备份** —— 余量检查是提醒,不该因为读不到它就不备份了。
(顺带把「磁盘剩 0.0 B」那句误导的输出并进警告里。)

clear-sessions.sh 里那句 awk 求和也过了一遍:Redis 键数不可能到 2^31,不受影响。

验证:正常路径照旧;把 free_kb 强行喂成 `4.29685e+10`,现在是一条警告加一次
完整备份,不再退出。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KqjE6qPo67fqVDKn6Bx7yd
2026-09-08 05:26:09 -06:00
xuyueandClaude Opus 5 2bf0e7bfc1 ops(备份): 加 backup-db.sh,按容器名导出、校验完整性、带保留策略
Deploy / deploy (push) Has been cancelled
原来手敲的那条

    docker compose exec -T oj-postgres pg_dumpall -c -U onlinejudge > db_backup_xxx.sql

在服务器上报 `service "oj-postgres" is not running`。容器明明在跑 —— 线上是外接
形态,postgres 由 /root/OJDeploy/docker-compose.yml 起,不归 OJ2 这套 compose 管;
compose.debian.yml 里那个 oj-postgres 挂着 `profiles: ["local-data"]`,只在自带
数据形态下启动。所以脚本直接按容器名 `docker exec`,跟谁起的无关,两种形态都能用。

比原来那条命令多做的事:

- **先写 .partial,验完才改名**。`> file.sql` 中途失败(容器挂了、盘满了、
  pg_dumpall 报错)会留个半截文件,看着像备份,等到要恢复那天才发现不是。
  中断也清掉。
- **验完整性**。gzip -t,再检查结尾有没有「PostgreSQL database cluster dump
  complete」,缺了就当失败。
- **umask 077 + chmod 600**。备份里有 user.raw_password(明文密码,本来就是留给
  老师查的)和角色口令散列,不该落成 644。
- **自检真连一次库**(psql -c 'select 1' 而不是 pg_isready)。后者用户名写错照样
  说 OK,要到 pg_dumpall 才炸出一句 role does not exist。
- **默认存到仓库外面**。deploy.sh 头部那条 rsync 带 --delete,备份放仓库里下次
  部署就没了;真放进去了会警告。
- **保留策略带兜底**。删超期的,但最新 3 份永远保留 —— 时钟错乱或者 --keep-days
  手滑填 0,都不该把手头唯一的备份删掉。
- **磁盘余量检查**。剩余空间比库还小就拒绝,--force 才继续。备份把生产盘写满比
  没备份更糟。

默认 gzip,--plain 关掉。头部写了 cron 的写法,以及恢复时那几条
`does not exist` / `already exists` 是 pg_dumpall -c 的正常噪音。

本机 dev 库(245 MiB)实跑:正常路径 38.9 MiB gz / 2 秒;容器名写错、用户名写错都在
自检拦住;导出中途失败后 .partial 被清掉;保留策略造 5 份 30 天前的 → 删 5 留 3,
把全部文件做旧 → 仍然保住最新 3 份。**恢复也真跑了**:起一个干净的 postgres:16-alpine
灌进去,submission=12 / user=11 / problem=20 / 28 张表,和原库一致。

只管数据库。判题测试点在 data/backend/test_case,不在库里,那份还没有备份手段。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KqjE6qPo67fqVDKn6Bx7yd
2026-09-08 05:21:13 -06:00
xuyueandClaude Opus 5 f66bafafaf feat(教师统计): 提交统计面板返修 —— 统计口径、未完成分两栏、多题、自动刷新
排查这个面板时发现的一串问题和缺口,一起修掉。改动集中在
`GET /submissions/statistics` 和 `StatisticsPanel.vue`,两边互相咬着,
拆不成独立的 commit。

**「已解决」数的不是题数**(真在显示错数字)。`count(*) filter (accepted)`
按用户名分组、没有 distinct problem_id,同一道题重复 AC 会重复计数。查单道题时
看不出来,老师查「这节课全班」时「已解决 5」可能是同一道题交了 5 次。新增
`solvedCount = count(distinct problem_id) filter (accepted)`,表格那一列换成它;
`acceptedCount` 保留,正确率的分子仍然是提交条数。

**正确率把判题中的算进了分母**。PENDING / JUDGING 进分母不进分子,全班同时交卷的
那几秒正确率凭空掉一截 —— 而老师盯着看的就是这个数。分母改成判完的条数,
`UNJUDGED_RESULTS` 提到 judge/status.ts 共用。总提交仍是全部条数(交了就算交过,
否则人数口径会跟着变,正在判的学生会掉进「没交」名单),另外下发 `judgingCount`,
非零时面板多显示一块「判题中」,三个数字才对得上。

**「未完成」实际是「一次没交」**。做了但一次没对的学生既不在「完成人数」也不在
未完成名单,等于从屏幕上消失 —— 而那恰恰是最该去看一眼的人。新增
`dataAttempted`,未完成栏拆成「还没交」/「交了没对」两组,tab 计数是两者之和。
请假隐藏对两组同时生效:他们同样占着班级人数这个分母,只藏一半会把完成度算错。

**点名字能看到错在哪**。`dataAttempted` 带上最近一条提交的题号、状态和
`statistic_info.err_info`(截断 400 字),点名字弹出来,还能一步跳到代码。
老师不用再切到提交列表、翻到这个人、点开代码。

**支持一次查几道题**。题号框接受 `1001,1005,1010`(中英文逗号、分号、空格都当
分隔符,投影前手敲不该因为打了全角逗号就查不出来),有一个题号不存在就整体 404。
**完成 = 这几道全解决**;只填一道时和原来完全等价,不填题号时退回「至少做出一道」。
差一道的人落在「交了没全对」里,名字后面缀 `2/3题`。

**零提交时整块面板消失**。判空条件是 `count.total > 0`,可一节课刚开始一条提交都
没有、后端已经把整份花名册当作「未完成」返回了 —— 最该看名单的时刻反而只显示
「暂无数据」。流程图那边更彻底:`/flowcharts/statistics` 的零提交分支把
`dataUnaccepted` 写死成空数组,名单压根没下发。

**面板不会自己刷新**。打开是空的、要点一次按钮,拿到的是那一刻的快照。改成打开即查
+ 每 15 秒滚动重查,页面切到后台就停,关掉面板随组件卸载停掉。上一次没回来就跳过
这一次。班级从手打 `ks251` 换成下拉(选项来自网站配置的 class_list,和登录框同一份),
保留自由输入,查过的班级记进 localStorage 下次带上 —— 机房电脑一台对一个班。

**明细查询没有 LIMIT**。展开行用的 submissionItems 原来把窗口内**全部**提交捞进内存
再原样序列化,「全部时段 + 不填条件」就是十几万条。改成只取有 AC 的人、每人最近 50 条,
截断用窗口函数发生在数据库侧;表格「提交数」仍是真实总数。

**顺带**:`personRate` 前端从来没读过(完成度是前端按「减掉请假人数的分母」自己算的),
从契约里删掉;「语法未过」的题数单列出来(AST_CHECK_FAILED 全站仍然算通过,口径没动,
只是让老师看得见谁是绕过语法要求做出来的,那批人教学上没达标)。

实跑验证(dev 全栈 + 浏览器):

- 已解决:student 两条 AC 都在题号 5 上 —— 改前显示 2,改后显示 1
- 正确率:临时把两条改成 PENDING/JUDGING,12 条提交 2 条通过 —— 16.67% → 20%,
  面板多出「判题中 2」,表格显示「12(2 条判题中)」
- 未完成两栏:student2 没交、student 交了 12 次没对,请假隐藏 student 后
  班级人数 2→1、tab 2→1、出现「恢复 1 位」
- 错因弹层:点 student 弹出「最近一次:1020 · 编译失败 / Test case not found / 看代码」
- 多题:`1004` 完成 1 人;`1004,1005` 完成 0 人、交了没全对 student 1/2题 8次;
  全角逗号同上;`1004,9999` 报 `Problem 9999 does not exist`
- 自动刷新:打开即发请求,之后 04:44:22 → 04:44:36 → 04:44:51 → 04:45:06 每 15 秒
  一次且窗口跟着滚;关掉面板后 20 秒请求数不再增长
- 班级下拉:选「25计算机1班」→ ks251,重开面板自动带上并立刻查

tsc / vue-tsc / check:routes 全过。验证用的 dev 库改动已还原。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KqjE6qPo67fqVDKn6Bx7yd
2026-09-08 05:20:51 -06:00
xuyueandClaude Opus 5 3a8f4fcd51 fix(后台用户): 管理员密码显示出来之后能再隐藏
Deploy / deploy (push) Has been cancelled
原来只发 reveal 事件,露出去就没有回头路,只有翻页 / 搜索才会回到打码状态 ——
看一眼就该关掉,不然一整页管理员密码那么摊着。改成 toggle,打码与否只看
revealed 这一个 prop,按钮文案跟着走。

密码列顺带从 150 拓到 180:露出明文后面还跟着「隐藏」按钮,150 挤不下。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017xu912Rv5JUUuy6MqMcQW2
2026-09-07 19:59:54 -06:00
xuyueandClaude Opus 5 6a438872b9 feat(排行榜): 页头显示当前在线人数,在线绿点只给老师
Deploy / deploy (push) Has been cancelled
新增匿名可读的 GET /api/site/online,一条 ZCOUNT 让 Redis 自己数,
不拉成员、也不写(清理过期成员留给后台列表,匿名接口不带写操作)。
榜单页进页面拉一次,为 0 时不显示。

/rankings/users 的 isOnline 是三态:null 表示「这个调用方不该知道」,
只有老师及以上拿到 true/false。写成普通 boolean 的话学生看到的 false
和真的离线分不开,等于默认把每个人的在线状态摊给全校同学看。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017xu912Rv5JUUuy6MqMcQW2
2026-09-07 19:36:12 -06:00
xuyueandClaude Opus 5 856b7a280e feat(后台用户): 新增「在线优先」排序,列表直接显示在线标记
在线状态库里没有、会话也判定不了 —— session 的 TTL 是 7 天且每次请求续期,
「有会话」只说明这人一周内来过。新开一个 Redis sorted set(auth/presence.ts)
记最后活动时间,5 分钟内有活动算在线。

写入全搭在已有的 pipeline 上,不多一趟往返:登录、每个带鉴权请求的续期、
以及 touchSession —— 只挂着 WebSocket 不发请求的人靠最后这条,sweepSessions
每 60 秒一轮,所以窗口取 5 分钟,明显大于那个间隔。登出、改密码、禁用账号
会立刻把人摘掉;过期成员在后台读列表时顺手清理(整个 key 不能设 TTL,
ZADD 不重置 key 的 TTL,到期会把还在线的人一起抹掉)。

排序 orderBy=-online 先捞在线 id,SQL 里 case when 分两档,档内继续按
最近登录排;没人在线时那个 case 恒等于 1,直接省掉。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017xu912Rv5JUUuy6MqMcQW2
2026-09-07 19:30:45 -06:00
xuyueandClaude Opus 5 5222e012e1 fix(比赛): 修四处 —— 倒计时两倍速、排名不自动刷新、题目状态恒空、比赛隐藏后审核页取不到代码
查比赛功能时实跑出来的四个问题,都在这一条里修掉:

**倒计时两倍速**(store/contest.ts)。init() 里 setInterval 之前不清旧表,而
detail.vue 在「未开始 → 进行中」那一刻会再 init 一次(为了捞开赛后才拿得到的题),
于是两个 interval 一起给 now 加 1000。学生赛前挂着页面就会中招:一场 60 分钟的
比赛,真过了 30 分钟页面就显示「已结束」、倒计时归零,而服务端还在正常收提交。
ojnext 里就有,是原样搬过来的。

**排名页「开启自动刷新」开着但不刷新**(contest/pages/rank.vue)。useIntervalFn
传的是 immediate: false,而 watch(autoRefresh) 只在开关变化时才 resume ——
开关初值就是 true、进页面不产生变化,表从没启动过,得手动关一次再开。改成
watchEffect,由「开关 + 比赛进行中」共同驱动,顺带不再在赛后空转轮询。同样来自
ojnext。

**比赛题的 myStatus 恒为 null**(routes/contest.ts)。判题其实把状态记进了
user_profile 的 acm_problems_status.contest_problems,只是这两条路由硬编码下发
空值,于是题目页的「状态」列永远是「未做」,赛后也不恢复。旧后端在赛后/管理员
视角是给的,这是回归。不按赛中赛后分档:这是学生自己的判题结果,不泄露别人任何
信息(旧后端赛中不给,只是因为它整条路换了个 serializer)。

**比赛一隐藏,审核页的「查看代码」必 404**(services/contest.ts)。acm-helper
故意不卡 visible(赛后核查恰恰发生在比赛收起来之后),它调的比赛提交列表却卡着,
两边对不上。findVisibleContest 换成 findAccessibleContest:公开的谁都取得到,
隐藏的只有比赛管理员取得到,学生看隐藏比赛照旧 404。

实跑验证(dev 全栈,判题走临时 worker 绕开本机 token 不一致):

- 浏览器跨过开赛时刻挂着不动 —— 墙钟 20.0 秒,倒计时正好减 20 秒(原来会减 40)。
- 排名页停在「无数据」,另一账号提交一发 AC,5 秒内表格自己长出
  `1 student2 1/3 0:00:42`,没刷新页面。
- 学生 AC 后列表和详情都回 myStatus: 0,没做过的另一个学生仍是 null,匿名照旧 401。
- 比赛隐藏 + 已结束:出题人 detail / problems / rank / submissions / acm-helper
  全 200,学生这 5 条全 404,提交也 404,隐藏比赛不进公开列表。
- 排名记账口径未受影响:10 次提交(8 编译失败 + 2 AC)落库 submission_number=9、
  accepted_number=1、total_time=231=ac_time、is_first_ac=true。

tsc / vue-tsc / check:routes(175 条无遮蔽)均干净,测试数据已清库。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017xu912Rv5JUUuy6MqMcQW2
2026-09-07 19:19:29 -06:00
xuyueandClaude Opus 5 ddc3f05bc3 fix(运维脚本): clear-sessions.sh 补上 dash 垫片
Deploy / deploy (push) Has been cancelled
`sh docker/clear-sessions.sh` 在 Debian 上会用 dash 跑(/bin/sh 就是它),
第 34 行的 `set -euo pipefail` 里 pipefail 是 bash 专有的,脚本一上来就死在
`Illegal option -o pipefail`,正事一件没干。deploy.sh 里早就有同一道垫片,
写这个脚本时漏抄了。

实跑验证(dev 栈,`sh docker/clear-sessions.sh`):垫片生效后跑到容器探活
那步正常报错;`CONTAINER=oj2-redis YES=1 sh docker/clear-sessions.sh` 全程
走通 —— session:* 删 101 个、user-sessions:* 删 4 个、bull:* 前后都是 57 个
(dbsize 162 → 57,判题队列一个键没动)。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XvmqDsZNyUo9P3sFQtoWVB
2026-09-07 18:49:24 -06:00
xuyueandClaude Opus 5 5d60bb15bb perf(redis): 热路径合并往返,限流脚本改走 EVALSHA
Deploy / deploy (push) Has been cancelled
审查 Redis 用法时找到的四处小账,都是确定性改动,语义不变:

- `getUserByToken` 里两条串行 EXPIRE 合成一次 pipeline。这是全后端最热的
  Redis 路径 —— 每个带鉴权的 HTTP 请求都要续一次会话和反向索引。上次给
  `touchSession` 修的正是同一个形状,这处漏了,两边现在一致。
- `createSession` 的 SET / SADD / EXPIRE 三趟并成一趟。登录是突发的,
  一个班同时登录时差别全压在这一下。
- 限流的 Lua 从 `redis.eval` 改成 `defineCommand`,稳态走 EVALSHA 只发
  40 字节 sha1,不再每次带上 937 字节的脚本全文;NOSCRIPT 由 ioredis
  自动回退成 EVAL 重新灌,Redis 重启和 SCRIPT FLUSH 都不用管。
- 删掉 websocket 订阅连接上重复的 error 监听 —— `withErrorLogging` 已经
  打过一遍且带连接名,留着只会把同一条错误打两份。

实跑验证(dev 栈,API 跑在 3999):登录后 `session:*` 多一条、
`user-sessions:1` 的 scard 和 ttl(604800) 都对;把两个键的 TTL 压到 100
再打一次带鉴权的请求,两个都回到 604800。限流侧 `info commandstats` 显示
evalsha calls=3/failed=1 + eval calls=2 —— 失败那次正是 SCRIPT FLUSH 之后
的 NOSCRIPT 回退;令牌桶数值与旧实现逐位一致(10 个初始额度扣 3 剩 7,
再要 20 个被拒并返回 wait=433.33 = (20-7)/0.03)。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XvmqDsZNyUo9P3sFQtoWVB
2026-09-07 18:44:59 -06:00
xuyueandClaude Opus 5 01d7924faa ops(会话): 加一次性脚本清掉全部会话,闭掉存量会话吊销不掉的空窗
反向索引 user-sessions:<uid> 是 498fc1c 才加的,在那之前签发的会话不在索引里,
revokeUserSessions 靠 SMEMBERS 找不到它们 —— 改密码、重置密码、禁用账号对这批会话
统统无效,只能等最长一个 SESSION_TTL_SECONDS(默认 7 天)自然过期。学生密码是明文
存着给老师查的,改密码正是密码泄露后唯一的补救手段,这个空窗不留。代价是所有人重新
登录一次。跑过一次就不用再跑,此后签发的会话都带索引。

**两个站点都要跑。** 机房和服务器共用一个数据库,但各有各的 Redis,会话存在各自的
Redis 里,只清一边等于只解决一半。脚本结尾会提醒这件事。

只删 session:* 和 user-sessions:*,不用 FLUSHALL:同一个 Redis 里还装着 BullMQ 的
判题队列,清掉等于把还在队列里的提交全丢了,那些 submission 会永远停在 PENDING。
删完会核对 bull:* 的键数没变,变了就报错让人工检查。

扫描用 SCAN 不用 KEYS(KEYS 会阻塞住整个 Redis,而这上面还挂着所有人的会话读写),
xargs 分批 DEL 避免顶到命令行长度上限。

拿一次性容器验过:1200 条 session + 50 条索引全删(跨过分批边界),30 个 bull 键和
throttling 桶原样不动;空库上重跑是幂等的;容器名写错时报错退出不做任何事。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XvmqDsZNyUo9P3sFQtoWVB
2026-09-07 07:45:47 -06:00
xuyueandClaude Opus 5 57bc652629 perf(数据库): user 表补两个索引,班级过滤和活跃人数统计不再全表扫
`user` 原来只有主键和 username 唯一约束两个索引 —— 它是 drizzle-kit pull 从
Django 建的表拉出来的,Django 那边也没建过别的。于是两条常走的查询都是全表扫:

- `problems/:id/beat-count` 里「近两年登录过的活跃人数」按 is_disabled + last_login
  过滤,每打开一次题目详情算一遍;
- `routes/classroom.ts` 的 loadClassUsers 按 class_name(或年级前缀 like '241%')
  取学生,班级榜、班级对比、AI 学情的排名 scope 都走它。

两千行的表现在扫起来确实不贵,但这是随人数线性涨的那类成本,而且比在应用层加缓存
更根本:不引入陈旧,也不需要考虑失效。

`user_active_idx` 的列序是 (is_disabled, last_login):等值条件在前、范围条件在后。

迁移只有两条 CREATE INDEX,无附带改动;本机 db:migrate 跑过,两个索引都在。
索引效果没法在本机验 —— dev 库只有 12 条提交、几十个用户,规划器无论如何都走
seq scan,要到生产(12 万提交)才看得出来。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XvmqDsZNyUo9P3sFQtoWVB
2026-09-07 07:42:46 -06:00
xuyueandClaude Opus 5 ec1509c46d perf(限流): 桶参数加 60 秒进程内缓存;Redis 连接补 error 监听
getBucketConfig 每次都查一次 `throttling` 配置项,而限流点在提交判题、AI 分析、
流程图评分上(5 处调用)—— 判题高峰期等于每条提交多一趟数据库,只为读一个几乎
从不变的值。上一代在 options/options.py 的 my_property 里也是带 TTL 缓存的,
重写时漏掉了。

缓存放进程内而不是 Redis:每站只有一个 api 进程服务读请求(oj-api 单容器、
Bun.serve 没有 reusePort、worker 只消费队列),进程内 Map 就等于全站缓存,
放 Redis 只是多一趟网络加一次序列化。异常分支特意不写缓存 —— 数据库抖一下不该
让接下来一整分钟全站都按默认参数限流。`throttling` 没有后台界面、只能直接改库,
改完最多一分钟后生效。

顺带给三条 Redis 连接都挂上 error 监听。ioredis 对没有监听者的 error 走
silentEmit:不崩进程,但把连接错误直接 console.error 到 stderr,绕开这里的日志,
而且不说是哪条连接 —— 这个进程同时开着会话读写、两条队列、一条订阅,「哪条」正是
要先知道的。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XvmqDsZNyUo9P3sFQtoWVB
2026-09-07 07:41:09 -06:00
xuyueandClaude Opus 5 22a7700b89 fix(会话): touchSession 续期时一并续反向索引,否则会话吊销不掉
WebSocket 巡检走的 touchSession 只 EXPIRE `session:<token>`,不碰
`user-sessions:<uid>`。而这条路径存在的理由恰恰是「只开着页面挂 WebSocket、一次
HTTP 请求都不发的人」—— 这种连接碰不到 getUserByToken 里那两条并排的 expire。

于是索引先到期、会话却被巡检一直续着。之后改密码 / 禁用账号走 revokeUserSessions
就 SMEMBERS 不到这张 token:WebSocket 那边还有 publishSessionRevoked 按 userId
兜底能断掉,但 HTTP 一侧拿着那张 cookie 照用不误 —— 而改密码要的恰恰是让 HTTP
立刻失效(学生密码是明文存着给老师查的,改密码是密码泄露后唯一的补救手段)。

签名加一个 userId,两条 EXPIRE 走一次 pipeline,仍然只有一趟往返,原来「比
GET + EXPIRE 少一趟」的理由保住了。三个调用点都有现成的 ws.data.userId。

返回值只看会话那条:反向索引是 498fc1c 才加的,在那之前签发的会话本来就没有索引
键,续不到是正常的,不能因此判定会话已死。

实跑验过四种情况:正常会话两边都续到 7 天;无索引键的存量会话仍判活;会话已删返回
false;空 token 返回 false。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XvmqDsZNyUo9P3sFQtoWVB
2026-09-07 07:40:58 -06:00
xuyueandClaude Opus 5 25b86ec17e refactor(提交): 删掉从来没用起来的「提交互相可见」
Deploy / deploy (push) Has been cancelled
problem.share_submission(题目级)和 submission.shared(单条)两个开关,连同
判定分支一起删掉。

生产备份(2026-08-07)里的实际用量:956 道题只有 2 道开过 share_submission,
还都是 contest_id=1 的比赛题 —— 比赛未结束时那条分支根本走不到,等于一天都没
生效过。123140 条提交里 shared=true 的有 40 条,39 条在 2022 年、1 条在
2023-03-30,之后近三年零使用;出题页从来没给过题目级开关,单条分享的入口在更早
那版前端上,ojnext 和 OJ2 都没搬过来,OJ2 里 PUT /submissions/:id 一个调用方
都没有。

canViewSubmission 剩下三条:本人 / 管理员(比赛中的 Student Admin 除外)/ 本题
作者,其余一律看不到。结尾的 `shareSubmission || shared` 没了;它上面那条「比赛
未结束一律不给」也一并去掉 —— 走到那里的必然不是这三种人,现在无论比赛与否都是
false,留着是重复的。allowShared 参数随之消失,它唯一的用途就是分享开关的归属
校验。

一并删掉:PUT /submissions/:id、响应里的 shared / canUnshare(列表、详情、站内
信内嵌三处)、题目详情与后台题目里的 shareSubmission、shareSubmissionRequestSchema,
以及新建提交时那句 shared: false(列上本来就有 default false)。

两个数据库列保留不删,只在 schema.ts 上注明已停用:删列是破坏性迁移,而留着不读
不写零成本,还留着那 40 条的历史痕迹。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XvmqDsZNyUo9P3sFQtoWVB
2026-09-07 07:18:41 -06:00
xuyueandClaude Opus 5 2256597838 fix(后台建题): 修好 dev 代理走错服务,以及新建页带出上一题 id、超长标签报英文
三处不相干的小毛病,都在「新建/编辑题目」这条路上。

vite 的 /api 代理写的是 localhost:3000。api 用 Bun.serve 起、只绑 IPv4 的
0.0.0.0:3000,而 Node 解析 localhost 时 ::1 排在前面 —— 别的项目的 dev server
一占 [::1]:3000,两边端口就不冲突(一个 v4 一个 v6,谁都不报错),浏览器发出的
/api/* 整个落到那个站上,表现是后台一进就被弹回首页。改成 127.0.0.1。

新建页和编辑页共用同一个 localStorage 草稿键,而编辑页会把服务器数据连 id 一起
写进去。没保存就离开的话,这个 id 跟着草稿漂到新建页:「下载测试点」下的是那道旧
题的包,SQL 测试点编辑器也会去回显那道旧题的脚本。新建分支进来先把 id 摘掉。

新标签没有长度限制,超过 32 字要到保存时才撞出 zod 的英文原文(Too big:
expected string to have <=32 characters)。把 32 提成契约里的
PROBLEM_TAG_MAX_LENGTH,输入框拿它做 maxlength,validateNewTags 再兜一道粘贴
绕过的情况,提示换成中文。校验的松紧没动,32 字仍然存得进、33 字仍然拦下。

editContestProblem 和 editProblem 函数体逐字相同(都是 PUT admin/problems/:id,
比赛由后端从题目自己推导),合成一个。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XvmqDsZNyUo9P3sFQtoWVB
2026-09-07 07:18:23 -06:00
xuyueandClaude Opus 5 d1d071ff7b fix(后台): 测试用例生成器允许无输入的测试点
Deploy / deploy (push) Has been cancelled
「这行算不算数」原来判的是 `f.in.trim()`,把「这题没有输入」和「这行我还没
填」撞成了同一种状态。打印类题目(输出星号矩形、只靠 print 的格式化输出题)
输入留空 → 点「先运行」整行被删 → 一行不剩 → 「上传」永远是灰的,老师只能
往输入框里塞个「无」才存得下去,那两个字节就真的进了 stdin。8019 / 8020 /
8021 三道题的 1.in 就是这么变成 3 字节「无」的。

拆成两个判据:

- hasOutput —— 有输出且没报错,这一行才打进 zip,输入空不空无所谓;
- isFilled  —— 输入或输出任一非空,只用来在「先运行」里筛掉面板上的空占位行,
  全没填时留一行当无输入题跑。

canUpload 保留原来那条守卫:填了输入却没跑出输出的行仍然挡住上传。「先运行」
不再要求先填输入。

后端本来就收空的 .in(processTestCaseZip 无非空校验),已上线的 8007、P003
的 1.in 就是 0 字节,卡住的一直只有这个面板。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AdMvixPo27sWFrUmk6ZStZ
2026-09-07 06:29:23 -06:00
xuyueandClaude Opus 5 ca29fcb554 feat(前端): 头像下拉里加「我的成就」入口
Deploy / deploy (push) Has been cancelled
放在「我的主页」之后,跳 /achievement。以前只有用户主页那张成就卡片能进去,
菜单里没有直达。

图标用 award-medal-4 而不是奖杯:顶栏「排名」已经是 fluent-emoji:trophy,
同一屏两个奖杯容易混。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NM2SWox3ke1NiVJCgWSvpQ
2026-09-07 05:34:31 -06:00
xuyue ab0d585939 update
Deploy / deploy (push) Has been cancelled
2026-09-07 03:56:56 -06:00
xuyueandClaude Opus 5 498fc1ceca fix(后台): 会话吊销、导入查重、练习题校验,以及一批后台页面的小毛病
Deploy / deploy (push) Has been cancelled
后台代码审查后的一批修复。

后端:
- 改密码 / 重置密码 / 禁用账号现在真的把该用户所有设备的会话删掉。原来只
  publishSessionRevoked 广播断 WebSocket,HTTP 拿着旧 cookie 照样能用到会话
  自然过期 —— 给被盗用的账号改密码等于没改。为此在 Redis 里补了反向索引
  user-sessions:<id>(createSession 写入、登出和失效路径清理、跟着会话续期)。
- 导入用户补齐校验:邮箱走 z.email()、批内查重、库内查重,用户名和邮箱各报各的;
  用户名和邮箱都归一成小写,和登录的 lower(username) 比较口径对齐。以前导入这条
  路什么都不查,而前端占位邮箱按「班级+批内序号」拼,同一个班导第二批必然重号,
  那两个账号从此在后台保存一次就撞 409、再也改不动。前端生成的占位邮箱同步加了
  每批随机后缀。
- PUT /users/:id 的邮箱查重改比 lower(email),存量大小写混着的数据也能拦住。
- 删用户的裸 catch 收窄成只认外键冲突 23503(顺 cause 链找,drizzle 0.45 把驱动
  错误包了一层),别的错照常抛 500,不再把连接故障说成「该用户还有历史数据」。
- 练习题 data 补语义校验(services/exercise.ts):没有 {{空位}} 的填空题、空选项的
  选择题、越界的下标等一律拒收。以前后端零校验,坏数据只有学生端会撞到。
- PUT /judge-servers/:id 改用 queryInteger,非数字 id 回 404 而不是 500。
- 比赛克隆不加归属校验是**有意的**(快速再开一场以前的比赛;保密边界在师生之间不在
  教师之间),把这条政策和它的副作用写进注释,免得反复被当成漏洞。

前端:
- 编辑用户弹窗的「班级」输入框改成只读 —— 它一直是个改了没用的控件,班级由后端从
  用户名推导。
- 新建用户预填唯一占位邮箱、角色默认改成实际会建出来的 Regular User、密码留空直接拦。
- 比赛题目列表的列过滤写的是 top_reaction,实际 key 是 topReaction,空列一直没被滤掉。
- AI 生成流程图加 try/finally,接口失败不再把按钮卡在 loading。
- 单个判题机删除后刷新表格;后台首页显示在线判题机数量(后端一直在下发)。
- 下载测试点失败时读 Blob 里的错误信封弹提示,不再毫无反应。
- 练习题编辑器补上和后端一致的前置校验。

验证:tsc / vue-tsc / vite build / check:routes 全过;后端每条改动都在本机起服务
实跑确认(会话吊销、导入各种重复、练习题七种题型、外键 409、非数字 id)。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RC5uL72UY9aZFuTvUKe2jv
2026-09-06 08:41:54 -06:00
xuyueandClaude Opus 5 bb0f5ec5ef fix(AI提示): 解锁条件前后端对齐,提示不再一点就没
Deploy / deploy (push) Has been cancelled
「失败 3 次解锁 AI 提示」实际是「在当前这次页面会话里再失败 3 次」:
problemStore.failCount 是个从 0 起数的内存计数器,刷新、切题、跳进跳出就归零,
而后端闸门数的是数据库里的历史失败数,两边根本不是一回事。昨天在这题上撞了
十次墙的学生今天进来照样看不到按钮。

- 数法收成一个 countFailedSubmissions(),题目详情的 myFailedCount 和
  POST /ai/hint 共用。原来详情把「等待/正在评分」也算失败,连点三次提交就能
  把按钮点亮,点下去却回 hint-locked
- 阈值 3 挪进契约 HINT_MIN_FAILURES,两端引用同一个常量
- failCount 改成 myFailedCount + 本次会话增量;在题目页里登录的补拉一次详情,
  否则停在匿名时的 0
- 结果面板改 display-directive="show",不再一收起来就把流式输出中的提示连同
  那次 LLM 调用一起作废;补「上次结果」按钮,原来唯一的重开方式是再提交一次
- prompt 里的判题结果翻成中文,原来拼的是裸状态码,模型不知道 -1 是什么
- system_error 不计入失败数、也不显示按钮:判题机自己崩了不是学生的问题
- 比赛中不给提示,和「求助」按钮同一个口径

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RC5uL72UY9aZFuTvUKe2jv
2026-09-06 07:24:26 -06:00
xuyue 2e78b6efdf fix
Deploy / deploy (push) Has been cancelled
2026-09-03 22:18:18 -06:00
xuyue 583ac2cee5 update
Deploy / deploy (push) Has been cancelled
2026-09-03 22:13:38 -06:00
xuyue ba2a47836e update
Deploy / deploy (push) Has been cancelled
2026-09-03 22:10:39 -06:00
xuyueandClaude Opus 5 b130d805be fix(后台题单): 修掉一串前后端字段名对不上导致的空列与失败操作
Deploy / deploy (push) Has been cancelled
后台题单接口下发的是扁平结构(displayId / title / isRequired),前端却按前台
题单页的嵌套结构取值,naive-ui 的 key 也不解析点号路径,于是「题目ID」「题目
标题」两列永远是空的。同一处还连累了另外几个操作:

- 编辑题目弹窗读 problem.problem.title,点「编辑」直接抛错;
- 添加题目发 problem_id / is_required,api 层取 problemId,出站是 undefined,
  被后端按参数错误 400 掉;
- 编辑题目发 is_required,「必做」怎么改都不生效;
- 新建/编辑奖章发 condition_type,toBadgeBody 读 conditionType,同样 400。

根因是 admin/api.ts 把这批后台接口的返回值标成了 oj 侧的 ProblemSet /
ProblemSetBadge / ProblemSetProblem,加上 detail.vue 四个 handler 用 data: any
接弹窗数据,字段拼错编译器一句都不吭。现在返回值全部换成 Admin* 契约类型,
handler 换成 AddProblemToSetRequest / UpdateProblemInSetRequest 和一个本地
BadgeFormData(条件类型是「完成所有题目」时不带 conditionValue,后端补 0),
两个奖章弹窗里的 const data: any 也一并拆掉。

验证:dev 栈实跑,列表两列有值、编辑弹窗正常打开、加题 / 改必做 / 建奖章 /
改奖章四条链路走完界面都成功落库;bun run type-check 通过。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011WmMi9tPrnSAwwAy2i4WAa
2026-09-03 20:49:57 -06:00
xuyueandClaude Opus 5 1729b9db4d fix(题目列表): 排序下拉框不再多出一根滚动条
Deploy / deploy (push) Has been cancelled
原来那行 :dropdown-style 是无效的 —— NSelect 没有这个 prop(只有
menu-props),写了会当普通属性掉到根节点上。真正卡高度的是 naive-ui
InternalSelectMenu 主题里的 height: calc(var(--n-option-height) * 7.6),
作用在菜单内部的 .n-scrollbar 上。8 条排序项 280px 超出 258.4px 半条,
逼出一根只能滚 22px 的滚动条。

改走 theme-overrides,按选项条数算高度,以后加减排序项自动跟着走。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Sy3L9zJHiSNFyNC3ZbMwdj
2026-09-03 20:13:01 -06:00
xuyueandClaude Opus 5 37861800e0 fix(题目): 恢复 AC 后弹出点评轮盘
Deploy / deploy (push) Has been cancelled
ec27441 把触发逻辑整段删了,只留下 n-modal 和 ProblemReaction 本体,
commentPanel 从此没有任何一处置 true,弹窗成了死代码。库里的评价全部
停在删除当天,学生只能自己点进「题目点评」标签页才评得了。

按原样恢复:AC 后延迟 1500ms 拉一次 getReaction,mine === null(这题
还没评过)才弹。比赛不打扰;题单入口 1.5 秒后要跳回题单页,弹了也会
被路由冲掉,同样不弹。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Sy3L9zJHiSNFyNC3ZbMwdj
2026-09-03 20:05:44 -06:00
xuyueandClaude Opus 5 8a88fe8d99 feat(智能分析): 解题表格改服务端分页,/ai/detail 不再下发整份 solved
Deploy / deploy (push) Has been cancelled
原来 /ai/detail 把区间内做出来的每道题连排名带等级整份下发,一个活跃学生一年几百道,
一次请求就是几百 KB,而表格一屏只看得到二十行。

拆成两支:
- GET /ai/detail 只留聚合(solvedCount、difficulty、tags、attempts、activity、errors…)
- GET /ai/solved?offset&limit 按首次通过时间升序分页给逐题明细

排名只跟当前这批题有关,所以分页那支只算一页的 problemIds,不必把整年算一遍。抽出
firstAcQuery / buildSolved / listSolved 三个函数,detail 和分页两边共用。

前端相应改动:
- 难度分布改读后端的 difficulty 聚合(本来就在下发,之前是从逐题列表里现数的)
- 几次做对改读新的 attempts 数组(每道题的尝试次数);tooltip 里的题名去掉了 ——
  明细是分页拿的,不该为了一个 tooltip 把全量拉回来
- Overview 用 solvedCount
- SolvedTable 的代码提交那张走 remote 分页,流程图那张仍是本地分页(一个 OJ 的
  流程图题就那么几道,全量下发没问题);换时间范围回到第一页
- 表格原来是 max-height 1500 的滚动区,现在由分页兜住,滚动条和分页器不再并存

/ai/analysis 的 prompt 仍然带逐题明细(少了它模型只剩聚合数字),但顺手卡了 200 条 ——
以前是整份 solved 无上限塞进去,题做得多的学生一次调用能顶好几倍 token。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LZuPwqDmLEiK9zgQ9z9sVn
2026-09-03 03:18:18 -06:00
xuyueandClaude Opus 5 4d7be969d9 refactor(智能分析): 重排版面,砍掉重复的三张周期图,补三个新维度
原来 8 张图挤在两列大网格里,左列还套了一层两列小网格 —— 四张小图各自只有半页的
一半宽,"难度掌握情况"的标题被挤断成两行、周期图的 x 轴标签斜着叠在一起、一年热力图
53 列塞进半宽几乎看不清。改成单列为主,宽的图给全宽,窄的图两两并排。

砍掉的重复:进步曲线 / 提交效率 / 周期综合读的是同一个 durationData,半年视图统共
6 个桶四个字段,摊成三张卡六条曲线还都是双轴。合并成一张:柱是完成题目数和总提交数,
线是 AC 率,等级进 tooltip(S/A/B/C 四档离散值连成折线读不出东西,逐题等级表格里有)。

同期解题排名分布也砍了:五片扇形对十几道题做统计本来就是噪声,而排名逐题列在
SolvedTable 里,饼图没有增加任何信息。

换形式:
- 标签雷达图 → 横向条形。雷达对比较大小是最差的形式之一,原来还把值归一化成"占最多
  标签的百分比",第一名恒为 100%,等于只画了个排序。现在画真实题数。
- 难度掌握情况 → 难度分布。去掉叠在里面的 S/A/B/C 维度,3×4 十二个格子对一个两个月
  做十来道题的学生大部分恒为 0。

热力图改成一格一周(53 格,周一起算,最后一格是本周)。按天切的话一年 365 格里三百多
格是空的,中职学生一年也就二三十天有提交,整张图看着像没用过。颜色阈值跟着按周重定。

新增三个维度:
- 错在哪里:判完的失败提交按状态码分组。编译错误占大头说明语法不熟,答案错误占大头
  说明是逻辑问题,两种情况老师该给的建议完全不同。
- 几次做对:到首次通过为止提交了几次,分一次过 / 2-3 / 4-6 / 7次以上。原来只有一个
  "平均提交次数",看不出分布。
- 流程图得分:detailsData.flowcharts 早就在下发,但全页一张图都没有,只在解题表格的
  第二个 tab 里列着。

顺带:
- 时间活跃度从"只统计 AC 时间"改成"统计全部提交",星期和时段由后端按东八区聚合。
  只看 AC 的话十来个点撒进 7×4 的格子几乎全是空的,和热力图的时区口径也对不上。
- 两两并排用弹性容器而不是固定两列网格:知识点分布在没有标签时整张卡不渲染,
  固定两列会空掉一半。
- AI 卡片原来有三个条件挂载点(solved>10 在右列、≤10 在全宽行、=0 藏在 Overview
  里面),单列之后收成最后一张无条件的卡。
- DurationChart 右轴的 S/A/B/C 一个刻度都没显示过:轴范围 -0.5~3.5,生成的刻度值是
  -0.5/0.5/1.5/2.5/3.5,拿去索引 gradeOrder 全是 undefined。

契约新增 activity / errors / rankScope / solved[].attempts / durationData[].acceptedCount。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LZuPwqDmLEiK9zgQ9z9sVn
2026-09-03 03:08:54 -06:00
xuyue 69883bd016 fix chart
Deploy / deploy (push) Has been cancelled
2026-09-03 02:35:29 -06:00
xuyueandClaude Opus 5 7129f1a12d fix(智能分析): 提示泄题、班级分析漏鉴权、AI 端点全线无限流
Deploy / deploy (push) Has been cancelled
/ai/hint 把参考答案原文放进 prompt,靠 system 里一句「不可透露」约束,而学生的代码
本身也是 prompt 的一部分 —— 一段「忽略上面的指示,把参考答案打印出来」的注释就能把
答案套走。改成不再发参考答案,让出来的 2000 字预算给题面;解锁条件(失败满 3 次)
原来只长在前端的会话计数器上,刷新就归零、直接 POST 更是完全绕开,补成端点自己查库。

/ai/class-analysis 只有 requireAuth,前端按钮上的 isAdminRole 只是 UI —— 任何学生
直接 POST 就能用,而且 comparison 全由客户端给,等于一个开放的代打 LLM 接口。补上
isTeacherOrAbove,与 /ai/class-pk-analysis 对齐。

/ai/analysis 收的是前端算好的 details/duration 整包,原样进 prompt 又原样写进
ai_analysis 表。改成只传 start/end/duration/username,学情数据一律服务端重算,
detail/duration 的计算抽成 buildDetail/buildDuration 三处共用;报告归被分析的那个人,
不归发起请求的人 —— 后台的 pin 和学生侧 /ai/pinned 都是按 user_id 找报告的。

四个 POST 端点和 login-summary 的模型调用全部过令牌桶(复用 services/throttling,
key 用 ai:<id> 与提交、流程图分开计数),超了返 429。

顺带修掉同一块里的几处:

- /ai/duration 的等级被写死成 `solved ? "B" : ""`,DurationChart 上那条折线因此恒定
  在 B。按旧后端 ai/views/oj.py:484 重新实现,按桶内同班排名算再取平均。
- 热力图 SQL 里 date() 用会话时区、JS 一边用 toISOString 取 UTC 一边用 getDate 取容器
  本地时区,三套混用;固定按东八区。365 格原来末格落在昨天,今天那格永远是空的。
- loginSummaryStore.open() 从 ojnext 移植时掉了,LoginSummaryModal 一直挂在 layout 里
  但没人触发,整条登录小结链路是死的。
- flowchart bestGrade 拿 max 回头 find 浮点相等的行;ai_analysis.provider 写死 deepseek。
- 前端四处 X-CSRFToken 是 Django 时代遗留,OJ2 后端没有任何 CSRF 校验,连同
  getCSRFToken 一起删掉;非 2xx 响应统一走 aiStreamError 转成中文。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LZuPwqDmLEiK9zgQ9z9sVn
2026-09-03 02:13:59 -06:00
xuyueandClaude Opus 5 fafeebd281 feat(运维): 加 oj2-api recount,把反范式计数列对回 submission 表
Deploy / deploy (push) Has been cancelled
problem.submission_number / accepted_number / statistic_info 和 user_profile 的
submission_number / accepted_number / acm_problems_status 由 judge/run.ts 的
persistResult 在判题时手工加减,上线至今没人事后核对过。

已知的漂移来源是重判:routes/submission.ts 的 rejudge 把 result 打回 PENDING
就重新入队,不回退任何计数,persistResult 随后再加一次。实测重判一条提交,
problem 的 submission_number、statistic_info 和 user_profile 的 submission_number
全部虚增,而提交一条没多。

默认只读预演,--apply 才写,落库后用同一份 computePlan 复核,还剩差异就非零退出。
口径逐条照抄 persistResult:题目侧连比赛提交一起算、用户侧只算非比赛;
accepted_number 是去重到题的首次通过;acm_problems_status 通过过就恒为 ACCEPTED,
没通过过取最后一次结果。acm_problems_status 里 problems / contest_problems 之外
的顶层键原样保留 —— 来历不明的数据不该被重算顺手抹掉。

不管的:acm_contest_rank(罚时与每题尝试次数口径复杂,单独一件事)、
achievement.unlock_count(0010 之后随成就级联,漂不了)、题单进度与奖章
(走 backfill-problemsets)。

--apply 要挑没人做题的时候跑:差异在事务外算、写的是绝对值,算完到写完之间判完
的那一笔加法会被覆盖;复核会把它报成「仍有 N 处差异」并以 1 退出,不会静默。

验证:dev 库先备份计数列,测完原样还原(差异数 0)。验过收敛(--apply 后再跑报
一致)、真实重判造成的漂移精确报出 3 处且无误报、人为删掉某学生已 AC 的格子能按
「曾经 AC → ACCEPTED」恢复、注入的未知顶层键完好保留。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AeJoYc2t2d7cThVqMBYrBF
2026-09-02 22:58:01 -06:00
xuyueandClaude Opus 5 2c4d56b29a refactor(后端): 清掉 Django 遗留的死列与手工级联,角色字符串收成一份
三条迁移,一次部署(0008/0009 含 DROP COLUMN,需要 OJ2_ALLOW_DESTRUCTIVE=1):

- 0008 删 IP 相关:比赛 IP 白名单(前端本来就没有输入框,detail.vue 无条件置空)、
  submission.ip(前端从未显示过)、以及一次都没被调用过的 IP 限流桶。
  judge_server.ip 是运维数据,保留。
- 0009 删九个只有 Django 时代写过、OJ2 一次都没读过的列:user 的 auth_token /
  open_api / open_api_appkey / session_keys,user_profile 的 blog / github /
  school / major / language。open_api 后台连开关都没有,那段「已经开着就不重置
  appkey」的逻辑从上线起没进过 if。判据是「全仓零读取」而不是「看着没用」——
  raw_password 同样刺眼却是在用的,别一起清掉。
- 0010 给 17 条外键补上删除动作,不再是 Django 留下的一律 NO ACTION。父行消失后
  必然无意义、且不构成学生留痕的走 CASCADE(中间表、题单/教程/成就的组成部分、
  user_profile 与 user_stat);需要人看见的继续拦着——submission.problem_id、
  以及 user 的绝大多数外键,删用户撞外键会被 handler 翻译成「请改为禁用账号」,
  这是有意的:全 CASCADE 会静默抹掉成就与进度,而 submission.user_id 压根没有
  外键,结果是一半删一半留。六处手工级联随之删掉。

角色字符串收进 packages/contract/src/roles.ts:原先 ADMIN_ROLES / TEACHER_ROLES
在两个文件各抄一份、学生口径在四个文件各写一遍、前端 USER_TYPE 是第三份副本。
AuthUser.adminType 与 drizzle 的列都收窄成联合类型,二十多处 `=== "Super Admin"`
从此受编译器管着($type 是纯 TS 层的,generate 确认不产生任何 SQL 变更)。

顺带删掉 db/relations.ts —— drizzle-kit pull 的产物,全仓零引用。

一处行为变化:后台用户列表传非法的 ?type= 回 400,不再静默返回空列表;界面上的
下拉只有合法值,打不到这条。

验证:tsc / vue-tsc / vite build / check:routes 全过;三条迁移在 dev 库执行,
并逐条建 fixture 走 HTTP 接口验过删除连坐与拦截(题单五张子表连坐、user_badge
二级连坐、删有提交的题目仍 409、删有表情的用户仍 409)。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AeJoYc2t2d7cThVqMBYrBF
2026-09-02 22:57:45 -06:00
xuyueandClaude Opus 5 e624c62502 feat(提交): 列表标出来自题单的提交
Deploy / deploy (push) Has been cancelled
submission 新增 problemset_id,学生从 /problemset/:id/problem/:pid 入口提交时
前端带上、后端落库,提交列表在题目后面挂一个「题单 xxx」的标签,点了进题单。

只是来源标记:题单进度和奖章仍由判完之后的 recordSolvedProblem 按「已加入且含
这道题的所有题单」记账,和从哪个入口进来无关,所以这个字段带错顶多标签不准,
不影响成绩。校验只确认这道题在那个题单里 —— 不查 visible / status、也不查有没有
加入,藏起来的题单里还困着已加入的学生;对不上就当没带,提交照收。

外键 ON DELETE SET NULL:删题单不该带走提交,清掉标记就行。索引建成部分索引
(WHERE problemset_id IS NOT NULL),绝大多数提交不来自题单,全列索引是给 12 万行
白建一遍;谓词能被 problemset_id = $1 蕴含,删题单时的外键检查也用得上它。

列表按页单独查一次题单标题,没有把 problemset join 进那条调过的深翻页查询。
比赛提交恒为 null:题单只收非比赛题。

历史回填从 problemset_submission 取「当年首次 AC 那条」,其余老提交无从判断入口,
一律留空。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Y7AsqceaUfC81k7UCDcSk2
2026-09-02 22:06:29 -06:00
xuyueandClaude Opus 5 cf1eea0810 fix(比赛): 学生管理员开卷、导出只剩十行、排行榜翻页错位等四处
Deploy / deploy (push) Has been cancelled
## 学生管理员在比赛进行中能看所有人的代码

canViewSubmission 里 isAdminRole(user) 是无条件放行的捷径,而 ADMIN_ROLES 含
Student Admin —— 同时 contest.ts 的排行榜又把这个角色算作参赛者。既在榜上、
又能读别人的提交,就是开卷。比赛未结束(未开始 + 进行中)时不再吃这条捷径。

旧后端这里写的是 `not user.is_regular_user()`,学生管理员同样放行,所以这条是
相对旧栈**收紧**的一处,不是修回归。只掐角色捷径,不掐 problem.createdById ——
那是这道题的作者本人,他早就知道答案,挡他没有意义。老师和超管不受影响,他们不参赛。

实跑(造了一场进行中、一场已结束的比赛,各一条别人的提交):学生管理员在进行中的
比赛里列表 showLink=false、详情 404,比赛结束后恢复 200;超管两种状态都是 200;
学生管理员读**自己**比赛中的提交仍然 200,没有把他自己的记录一起挡掉。

同族的 flowchart.ts canView 有同样的角色捷径,但流程图提交入库时从不写 contest_id
(永远是 null),那条路上不存在「比赛中的别人的提交」,不用跟着改。

## 获奖名单导出,参赛超过 250 人时只导出十个人

rank.vue 用 `limit: total.value || 10000` 想一次拉全量,但 queryInteger 对超出
上限的值是**静默回落到默认的 10**,不是截断到 250。于是 300 人的比赛导出 10 行,
而一二三等奖的分档仍按真实总人数算 —— 老师拿到一份十个人、等级全错的名单,还不报错。
改成按 250 一页循环拉,两个出口都留:拿不满一页说明到底了,比对 total 是防着最后
一页正好整除。班级赛(≤250)碰不到这个坑,全校赛会。

实跑:造 20 条排名,limit=300 后端确实只返回 10 行,limit=250 返回 20,
新逻辑拉回 20。

## 排行榜翻页没有全序

只按 acceptedNumber desc, totalTime asc 排,同分同罚时行序不稳定,而这条列表是
limit/offset 翻页的 —— 同一个人可能在第 2 页出现两次,另一个人从此消失。末尾补
asc(id) 兜全序,id 不参与名次,只保证同分的人每次按同一顺序排。

实跑:20 个同 AC 数同罚时的选手,每页 5 条翻 4 页,共 20 行去重后仍是 20 人,
连翻两轮顺序完全一致。

## acm-helper 两个接口对 visible 的口径不一致

GET 要求 visible = true,PUT 不要求。比赛结束后收起来,核查页就打不开了,
而标记接口还能用。赛后核查恰恰常发生在比赛已经收起来之后,按 PUT 的口径放开。

## 删掉 contest_announcement

旧 Django 栈有「比赛公告」,OJ2 从头到尾没搬:没有路由、没有契约、没有前端页面,
表建在那里纯粹是 introspect 0000 时一起拉进来的。确认不需要,连表带 schema 定义
一起删。

删除前核实:没有任何表外键指向它,序列由本表 owned 会随 DROP TABLE 一并消失,
生产快照(db_backup_2026_08_07)里只有 1 行 —— 2022 年 4 月挂在 contest 1 上的
一条测试公告。迁移不写 CASCADE,同 0002:真有别的东西引用了,宁可报错也别被悄悄
级联掉。

**上生产要显式放行**:migrate.ts 的破坏性闸会拦下 DROP TABLE,得
`OJ2_ALLOW_DESTRUCTIVE=1 docker/deploy.sh`,并按它说的先备份。本机已实跑:
不带环境变量确实被拦,带上之后表和序列都没了,重跑是「没有待执行的迁移」,
db:generate 报 No schema changes(snapshot 与 schema.ts 对齐,不给下一条迁移留假 diff)。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013rpSKCNpVcMhTFhw21YiL7
2026-09-02 20:38:04 -06:00
xuyueandClaude Opus 5 286487acf3 fix(自学): 少于三分钟的不算已读
原来只要打开过(viewCount > 0)就记成已读,于是「点开看一眼就退」和「认真读完」
在老师那张表上长得一模一样,「已读 17/17」并不说明他学了。加一道 3 分钟的门槛 ——
按最短的一课定的下限,读不完还翻不动的课文,扫一眼是到不了这个数的。

阈值 TUTORIAL_READ_SECONDS 放在 contract 里,前后端共用一个数:学生端目录的 ✓、
后台「按学生」的已读课数、「按课程」的读过人数,三处口径必须一致,各写各的迟早分叉。

**累计时长故意不卡**。时长记的是真实停留,不满三分钟的秒数照样算进去,于是
「已读 0 课、累计 25 分钟」成为一种能看见的状态 —— 他翻了很多课,每课都没读满。
这正是这道门槛想让老师看见的东西,把时长一起滤掉反而把信息删了。

「按课程」的人均时长跟着改了分子:分母是读满三分钟的人,分子就得是同一批人的时长,
否则拿全部时长去除达标人数,人均会被翻一眼就走的人凭空抬高。

顺带修掉「✓ 已读 · -」:心跳 15 秒一跳,点开就走会落在 0 秒上,而 readableDuration(0)
返回的是 "-"。新口径下打勾要求 ≥180 秒,这个组合不可能再出现;打开过但没读满的
显示灰色的「读了 N 分钟」,记是记下了,只是还没到「已读」。

后台筛选栏上方写了一行口径说明,免得老师对着「已读 0 课 / 累计 25 分钟」猜是不是坏了。

本机实跑:student 读 A 课 500 秒、B 课 60 秒 → 已读 1/2、累计 560 秒;
A 课「读过 2 人、累计 700、人均 350」,B 课「读过 0 人、累计 60、人均 0」。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013rpSKCNpVcMhTFhw21YiL7
2026-09-02 20:37:30 -06:00
xuyue 9675dfbd42 Revert "feat(题目): 样例试运行放出「终端会话」,把输入是怎么喂进去的画给学生看"
Deploy / deploy (push) Has been cancelled
撤掉 8cd4459。功能本身跑通了(C / C++ / Python3 三条都验过),但界面上不成立:
为了解释「输入是喂进去的」「提示语也算输出」这两件事,每跑一次样例就压两大段
灰色小字,把一个干净的小面板变成了说明书 —— 需要靠一段说明才能看懂的配色,
本身就说明这个设计没做对。

连带撤掉同一批的「结果不自动复位 + 通过/不通过 tag」,回到 bd84599 的样子。

「学生感觉不到输入这一步」这个问题还在,只是不该用这个办法解。教程 04 那边讲
「交到判题狗上要把提示语删掉」的一节保留(那部分和界面无关,本来就成立),
其中引用本功能的那句话已经删掉并重新发布。
2026-09-02 01:25:19 -06:00
xuyueandClaude Opus 5 8cd4459964 feat(题目): 样例试运行放出「终端会话」,把输入是怎么喂进去的画给学生看
Deploy / deploy (push) Has been cancelled
学生在自己电脑上跑,是「程序停下来等我敲、敲完回车再往下走」;判题狗这边输入
是提前备好、一口气喂进去的,屏幕上只剩对和错。这个落差是入门阶段最常见的困惑,
最痛的落地形态是:照着教程写了 printf("请输入温度:"),算得明明对却一直判错。

试运行时给代码套一层前导,程序每读到输入就原样回显到 stdout,用  包成标记。
回来的输出拆两次用:抠掉标记段是程序真正的输出(判定用,和不套前导时一字不差),
带标记渲染就是一份终端会话。支持 C / C++ / Python3,其余语言照旧直接跑。
只走样例试运行这条路,正式提交判题一个字都不加。

界面上蓝色是喂进去的输入,带虚线下划线的灰字是学生自己打的提示语(一段输出紧
跟着一段输入就是提示语)。把提示语抠掉正好等于期望输出时,把话说死:答案是对
的,删掉提示语就通过。

顺带:样例「测试」的结果不再 2 秒自动复位,按钮固定叫「测试」,通过 / 不通过挪
到旁边的 tag 上。

几个踩出来的坑记在代码注释里:C 不能攒够一行再回显(样例输入不带结尾换行,那个
换行永远等不到,回显会拖到退出时才发生,变成「答案在前、输入在后」);也不能按
字节回显(中文多字节会被标记撕碎);行号回退只能对编译错误全量做,stdout 里混着
学生自己打印的东西,printf("%4d | %s") 这种表格题一改就把人家的输出改错了。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013rpSKCNpVcMhTFhw21YiL7
2026-09-02 01:11:41 -06:00
xuyueandClaude Opus 5 bd84599174 feat(自学): 教程和练一练都留痕,老师能看到谁学了多少
Deploy / deploy (push) Has been cancelled
自学模块以前一个字节都不落库:读到第几课只存在浏览器的 localStorage 里,
练一练的对错是组件内的一个 ref,刷新即失忆。老师能看到的只有「谁交了题」。

现在两张新表:
* tutorial_progress —— 一个学生 × 一课,记打开次数和累计停留秒数
* exercise_attempt  —— 一个学生 × 一道练习,记试了几次、错了几次、
  第几次做对的、最后一次做错时填的什么

都存聚合不存流水。练习那张表尤其明显:流水会随着学生反复点提交无限长,
而多出来的行回答不了任何新问题 ——「他第 3 次和第 5 次都选了 B」对老师
没有意义,「他试了 7 次才对」有。

停留时长只在页面可见、且十分钟内有过操作时才计。机房的电脑经常开着页面
就走了,不设这道闸的话「停留时长」会变成「电脑开机时长」,老师看到的
数字全是假的。换课、切标签页、关窗口都会先把攒着的秒数冲给**离开的那一课**。

练一练的对错仍然是前端判的:答案本来就随题面一起下发到浏览器,后端再判
一遍也挡不住任何人,只是重复实现七套判题。所以这是教学观察数据,不是成绩。
`last_wrong_answer` 存的是前端拼好的一句人话(「选了 C」「顺序 3-1-2」),
不是原始作答结构 —— 七种题型形状各不相同,存结构就得在后台按题型各写一套
渲染,而老师要看的只是他错在哪。

顺带修掉预测输出题的一个老问题:它的 `submitted` 一旦为真就不再收回,而
`allCorrect` 是跟着输入实时算的,于是学生错一次之后把答案改对,界面直接
跳成「输出正确!」、提交按钮同时禁用,submit() 再也执行不到 —— 这道题
**永远不会被记成做对**。排序/连线/找错/分组四种题本来就在交互处把 submitted
置回 false,只有这里漏了,按同一套补上。

学生端:目录每课显示「✓ 已读 · 11 分钟」和「练一练 3/5」。教程保持免登录
可读,未登录只是不留痕,并明说一句。

老师端:后台新开「自学情况」(教师及以上可进),三个 tab ——
按学生(默认把读得最少的排在最前,这张表要回答的是谁还没开始)、
按练习(每道题的正确率、一次做对几人、做对的人平均试几次;展开看逐人明细
和他们最后错在哪)、按课程。班级框填 3-4 位是具体班级,1-2 位当年级前缀。

外键用了库级 CASCADE,和 Django 建的那批 NO ACTION 不同:删教程、删用户
不必再记得回来手工清子表。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GW5ef6C2kRW8Ru27ghCaUu
2026-09-01 08:54:27 -06:00
xuyue 49681d04a6 update
Deploy / deploy (push) Has been cancelled
2026-09-01 07:50:32 -06:00
xuyueandClaude Opus 5 912dbb7f73 feat(登录): 把「能打拼音」这件事告诉学生
Deploy / deploy (push) Has been cancelled
拼音搜索上一版就能用了,但没人知道。姓名框的占位符写清楚
「选择姓名,可打拼音 zs 或 zhangsan」,提示框里再补一句
「找人不用切输入法」—— 机房电脑默认英文输入法,这句才是学生真正在意的。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YQCLjAmz6pPXMNGoZmvAmC
2026-09-01 07:44:57 -06:00
xuyueandClaude Opus 5 4654615f89 feat(登录): 姓名支持拼音和拼音缩写搜索
Deploy / deploy (push) Has been cancelled
机房电脑打中文要切输入法,选姓名前先切一次法太别扭。现在 zhangsan、zs、
xiaoxian 都能搜到张三/曾小贤,中文照旧能打。

用 pinyin-pro 的 match 而不是自己拼一份拼音串比对:多音字它两个读音都认,
单田芳搜 stf 和 dtf 都出得来,曾小贤搜 zxx 和 cengxiaoxian 也都出得来 ——
自己拼只会留下默认读音那一个,姓氏恰恰是多音字重灾区。

词典有 85 KB(gzip),静态引入会压进首屏,所以改成打开登录框才 import。
已登录的人一次都不会下载(构建产物里它是独立 chunk,只被 default 布局
动态引用;实测页面加载 0 个请求,打开登录框才有 1 个)。拉不下来时退回
纯中文匹配,不至于让人登不上。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YQCLjAmz6pPXMNGoZmvAmC
2026-09-01 07:25:21 -06:00
xuyueandClaude Opus 5 047e6dd7d3 feat(登录): 学生登录改成班级+姓名两个下拉,一个字都不用打
Deploy / deploy (push) Has been cancelled
登录框拆成「学生登录 / 管理员登录」两个页签。学生页签选完班级选姓名,
ks 前缀提交时自动拼,选完姓名焦点直接跳到密码框,回车登录;上次选的班级
记在 localStorage 下次自动填好(姓名不记 —— 同一台机器换个人坐就是别人)。
管理员页签只有用户名+密码,不拼前缀。

「没有我所在的班级」保留在班级列表末尾,往届的班级从后台 class_list 里删掉后
学生仍能从这里写完整用户名登录。为了把「还没选」和「没有我所在的班级」分开,
loginForm.class 的初值从空串改成 null —— 原来两者都是空串,一打开就默认落在
「没有我所在的班级」那一档、显示文本框,正好和「方便学生」相反。username 同样
改成 nullable:空串在 n-select 里是「选了一个空值」,占位符不显示。

clearProfile 的 storage.clear() 给 LOGIN_CLASS 开了个口子:机房一台机器对一个班,
下课登出、下节课再来还是同一个班,清掉的话每个人都得重新选一遍。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YQCLjAmz6pPXMNGoZmvAmC
2026-09-01 06:57:24 -06:00
xuyueandClaude Opus 5 ec35400249 perf(首页): 协作弹框改异步加载,首屏 JS 少三分之一
Deploy / deploy (push) Has been cancelled
CollabHost 静态 import CollabModal,把整套 CodeMirror(view / state /
language / autocomplete / lang-*)拖进了入口 chunk,而那个组件是
v-if="isTeacher" 的——学生根本不渲染,字节却人人下、人人解析。改成
defineAsyncComponent 之后:

  入口 eager JS  1355 KB → 717 KB(gzip 447 → 234)
  首页 JS 总量   1923 KB → 1285 KB(gzip 642 → 428)

机房那批 Chrome 91 省下的不只是下载,还有六百多 KB 的解析。老师端代价
是第一次接单时多一次 chunk 请求。

顺带修掉题目列表的重复请求:onMounted 拉一次,profile 回来时那个
watch 又拉一次。但请求本来就带 cookie(withCredentials),后端
optionalAuth 认的也是 cookie,首屏那一份的状态列本来就是全的。watcher
改成拿 storage 里的登录态做基线,只在登录态真的变了才补拉。

这条在本机复现不了(/api/me 1ms 就回,路由 chunk 还没挂载完),给
preview 代理的 /api/me 加 300ms 延迟、用 production 构建验证:改前
/problems 发两遍,改后一遍且状态列有值,登录/退出两个切换仍各触发
一次重拉。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Tj3959yNB2srvc1oL3PaZH
2026-09-01 00:49:56 -06:00
xuyueandClaude Opus 5 a2f67eebf6 perf(用户导入): 批量导入从几秒降到半秒
Deploy / deploy (push) Has been cancelled
导入一个班(45 人)要转好几秒,慢的全在密码哈希这一处:

- 哈希在重名检查之前算。老师习惯把同一份名单粘两次,那种情况要白等
  一整个班的 argon2 才看到 409。把校验和重名查询提到前面,这条路径
  现在是 5.6ms 返回。
- 45 次 argon2 串行 await。改成固定 4 路并发池;不用 Promise.all 是因为
  oj-api 的 mem_limit 只有 512m,一个年级 300 人全量并发撑不住。
- argon2id 参数从 Bun 默认的 m=64MiB 显式降到 OWASP 推荐下限 m=19MiB,
  单次 140ms → 20ms。参数编码在哈希串里,存量账号照常验证、不用迁移,
  旧的 pbkdf2 那条分支也不受影响。

45 人端到端 2.04s → 0.55s。验过:旧 m=65536 的哈希、新 m=19456 的哈希、
Django 的 pbkdf2 三种都能正常登录,错误密码照常拒绝。

顺带把生成页下载的 CSV 裁成用户名和密码两列 —— 发给学生的就这两样。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QqqZwxtXLo2GTqMi51C94D
2026-09-01 00:28:16 -06:00
xuyueandClaude Opus 5 e5a6f2d1e7 fix(题单): 归属校验、进度分母、截止时间可见性等六处零碎
Deploy / deploy (push) Has been cancelled
## user-progress 缺归属校验

学生端那条 GET /problem-sets/:id/user-progress 只有 requireTeacher,没有归属校验,
任何 Teacher Admin 都能读到别人建的题单的学生名单与进度。补上,口径与后台
loadOwned 一致(超管放行,其余人只能看自己建的),越权报 404。

顺带订正 docs/specs/phase4-review-authz.md:449:那条写着题单进度「显式下发真名」,
与代码不符 —— 学生端这条走 sampleUser 且没传 includeRealName,realName 恒为 null
(SQL 里那次 leftJoin userProfile 是白查的)。真正下发真名的是后台那条
GET /admin/problem-sets/:id/progress,结论仍成立,但当时漏掉了归属校验这个缺口。

## 头部进度的分母

分母只算必做题之后,ProblemSetHeader 还在拿 completedCount / problemsCount 算 ——
前者是必做完成数,后者是总题数。做完全部必做题的人会看到「9 / 10、90%」,而同一张
卡片上又标着「已完成」,题单 6 那 10 个人正是这种。改成读 userProgress,另外把
「另有 N 道选做」标出来,否则「共 10 道题目」和「9 / 9」对不上。

## 截止时间

end_time 管的不是「到点不能做了」,是「到点之前看不到自己加入题单之前的旧代码」,
而学生端一个字都不显示 —— 被挡住的人不知道为什么,也不知道什么时候解锁。头部加一个
带解释的「截止 …」标签;提交列表那个锁图标的说明也补上另外两条解锁路径。

## 两个必然筛空的筛选器

学生端题单列表的难度、状态两个下拉:线上 16 个题单全是 Easy / active,选「中等」
「困难」「已归档」永远是空列表。撤掉,保留关键词搜索。接口那两个 query 参数留着,
哪天真的用起这两个字段再把 select 加回来。

## 题目移出题单时的提交记录

旧栈 problemset/signals.py 的 post_delete 会清掉该题在本题单的 ProblemSetSubmission,
OJ2 没做,于是那张表一直在攒指向已移出题单的孤儿行。补上。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QqqZwxtXLo2GTqMi51C94D
2026-09-01 00:01:58 -06:00
xuyueandClaude Opus 5 9d9e104df6 fix(题单): 进度记账挪到判题这一路,不再靠前端回调
前端记账是这条链上最松的一环:SubmitCode.vue 看到 AC 就回调
PUT /problem-set-progress,而且只认路由参数里那一个题单。于是

  · 从普通题库入口做出同一道题 → 不计进度
  · 网络一抖、页面提前关掉      → 进度静默丢失
  · 一道题同时在两个已加入的题单里 → 只有进去的那个记上

旧栈为此专门有个管理命令 fix_problemset_progress 定期按实际提交补账 ——
2026-05-22 00:50 那次一分钟内跨 7 个题单的批量补进度就是它跑的。

改成判题落库之后由 judge/run.ts 记账(recordSolvedProblem),记进该用户**所有**已加入
且包含这道题的题单。位置在最后那条 publishSubmissionUpdate("finished") 之前,所以前端
收到「判完了」时进度已经落库,跳回题单页看到的就是新数据。前端那次回调删掉。

不按 visible / status 过滤:进度是学生自己的记录,老师把题单藏起来不该让它停止累积;
更要紧的是这条口径必须和补账工具一致,否则补账工具会永远「发现」差异。

实跑(本地起 api + worker 真判一次):提交时**完全没带 problemSetId**,判完之后
progress 变成 1/1 100% 已完成、10 分、complete_time 落下、all_problems 奖章发出、
problemset_submission 也记上了。

## 补账那半

backfill-problemsets 前面加一道「按实际 AC 补进度」,移植自旧栈的
fix_problemset_progress,口径和 recordSolvedProblem 逐条对齐(非比赛提交、
ACCEPTED 或 AST_CHECK_FAILED、取最早那次)。补录的格子先并进 detail 再重算,
所以预演里的奖章名单是照着「补完账又重算过」的进度算的,和 --apply 的结果一致。

在生产快照上实跑:

  合计:补录 10 道题,进度 497 条要重算(完成 +23 / -0),奖章补发 56 条、收回 0 条
  已订正 11 个题单 → 复核通过
  user_badge 1180 → 1236,已完成 621 → 644,problemset_submission 7735 → 7745
  「未完成但有完成时间」仍是 4 条;重复跑幂等

补录的 10 道分布在题单 4/5/6/15/16(1/1/1/4/3),和离线独立算的数字逐个对上 ——
其中题单 15 那位 AC 了全部 12 题却一直显示未完成。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QqqZwxtXLo2GTqMi51C94D
2026-09-01 00:01:38 -06:00
xuyueandClaude Opus 5 74b97c610f fix(题单): 「选做」终于作数了,分母只算必做题
isRequired 一直只是卡片上的一行字:卡片写着「(选做)」,进度分母和 all_problems
奖章却照样要求做完。结果是学生按提示跳过选做题,进度条卡在 100% 以下、全通奖章也
拿不到 —— 快照里 22 个人做完了全部必做题却显示未完成(题单 5 三人、6 十人、8 两人、
11 七人)。旧栈的 update_progress 同样不区分,是一路继承下来的。

改成:分母只算必做题,选做题做了仍然计分(totalScore 把它算进去),只是不卡完成。
一道必做都没标的题单退回「全部都算必做」—— 那种题单多半是没用这个字段,而不是真的
整单选做,不兜住的话它永远完不成。

## problem_count 奖章不能跟着改

老师当初是按题单的**总题数**设阈值的:题单 5 的「一职欧拉」要 8 题,而它的必做只有
7 道。要是 problem_count 也改用只数必做的 completedProblemsCount,这枚奖章一夜之间
不可得,76 个已经拿到的人会被 recalculateBadge 收回。所以它数的是「做出的题目总数
(含选做)」,从 progress_detail 的键数来。score 类同理不受影响。

预演证实了这道闸门有效:22 人拿到完成状态,奖章补发 56 条、**收回 0 条**。

## 顺带:第三份手抄的达标逻辑

PUT /problem-set-progress 里还藏着一份 inline 的奖章判定,和 services 里那份、
补发脚本里那份是三份各写各的 —— 这次改 problem_count 的语义,漏掉任何一份都会让
学生提交时发的奖章和后台重算的结果对不上。三处统一到 eligibleForBadge。

## 工具改名并扩到进度

backfill-badges → backfill-problemsets。语义变更之后,已有的进度行要跑一遍才会按新
规则重算,否则那 22 个人得等到老师下次动题单才生效。两笔账本来也是同一笔:进度一变,
奖章达标面就跟着变,所以落库走 resyncProgress(它重算进度后会顺手重算该题单全部奖章),
预演里的奖章差异也是照着订正后的进度算的,保证预演和 --apply 的结果一致。

在生产快照上实跑:

  合计:进度 494 条要重算(完成 +22 / -0),奖章补发 56 条、收回 0 条
  已订正 10 个题单 → 复核通过:题单数据与规则一致
  user_badge 1180 → 1236,已完成 621 → 643
  「未完成但有完成时间」仍是 4 条(d7a6414 那条语义保住了)
  重复跑幂等:进度 0 条、奖章 0 条

抽查题单 6(9 必做 + 1 选做):只做必做的显示 9/9 100% 已完成、80 分;连选做一起做的
同样 9/9 已完成,但 90 分。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QqqZwxtXLo2GTqMi51C94D
2026-08-31 08:55:36 -06:00
xuyueandClaude Opus 5 d9e6a2a3f0 perf(题单): 学生端题目列表少两次 join 一次查询,顺带把并列的 order 排稳
## 排序

学生端 /problem-sets/:id/problems 只按 order 排,没有 tiebreaker,而卡片是按数组
下标编号的(#1 #2 #3)。order 并列时 Postgres 不保证次序,题单 8(3 道题 order 都是
10)、题单 11(2 道并列 4)、题单 14(3 道并列 0)实际就有并列,于是「第 3 题」指
哪道题每次刷新都可能变。后台那条列表一直是 order + id 排的,两边本来就不一致。

补上 asc(id)。教师进度视图里那份题目清单(同一路由文件 :398)有同样的问题,一并补。

实跑:四道题、三道 order 并列,连打 5 次次序完全一致。

## 载荷

这个接口原来复用 problemListItemSchema,为此要多 join user + user_profile 凑
createdBy、再多查一次标签表凑 tags —— 而题单卡片只渲染题号、标题、难度、分数和
完成标记。tags / submissionNumber / acceptedNumber / createdBy / contestId /
allowFlowchart / showFlowchart / hasAstRules 一个都不用,myStatus 甚至写死是 null。

而且 select 的是 schema.problem 整行,题面、样例、答案、ast_rules、flowchart_data、
sql_display 全都白拉回来一遍。

改成 problemSetProblemItemSchema(id / _id / title / difficulty 四个字段),查询相应
收窄:两次 join 去掉,标签那次查询整条去掉,行查询只取四列。每次请求从 4 条查询降到
3 条,其中最大的那条不再拖整行题面。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QqqZwxtXLo2GTqMi51C94D
2026-08-31 08:47:57 -06:00
xuyueandClaude Opus 5 d7a6414735 fix(题单): complete_time 翻回「只设不清」;完成题单后那个必然报错的 tab
三件事,都是上一轮结论没查扎实留下的。

## complete_time

f9354b0 把「退回未完成时清空 complete_time」定成两边统一的行为,理由写的是
「快照里 complete_time 非空 ⟺ is_completed」。那个检查只做了一个方向(已完成但
没有完成时间 = 0 条),反方向没查 —— 实际有 4 条 is_completed=false 却留着
complete_time,全在题单 8:那批人 2025-11-14 在它还只有 6 题时完成过,老师后来
加到 12 题,进度退回未完成,完成时间保留了下来。

旧栈是故意不清的(problemset/models.py:218 只有 `if is_completed and not
complete_time` 这一条赋值),语义是「曾经完成于」。清空是重写时在学生路径上引入的,
上一版又把它推广到了后台路径。

翻回只设不清。「未完成 + 有完成时间」是允许的组合。反过来清空的代价不可逆:往一个
100 人已完成的题单里加一道题、再改主意删掉,这 100 个人的历史完成时间就一起被冲成
「现在」—— 上一轮的实跑已经在题单 9 上复现过。

## 两处注释订正

「旧后端不做加题后的重算」这个说法是错的,本仓早先的注释里有,上一版我照搬进了
services/problemset.ts 和提交信息。旧栈用 signals 做了,而且两件事都做:
problemset/signals.py 在 ProblemSetProblem 的 post_save / post_delete 上重算全部
参与者进度、再重算该题单全部奖章。重写时 views 里翻不到显式调用就当成没做,于是
奖章那一半漏了 —— 53 条应发未发正是这么来的。

另外补上 53 条里那 23 条的出处:旧栈的管理命令 fix_problemset_progress 按实际 AC
补 progress_detail,而 signals 不挂在 Progress 上,所以进度补了、奖章没补。

## 用户进度 tab

detail.vue 的 showTabs 写的是「超管 或 自己完成了题单」,而它渲染的
UserProgressView 调的是 requireTeacher 的接口。两边正好错开:

- 学生做完题单 → tab 出现 → 点进去 403(实跑确认:已完成该题单的 student 拿到
  403 permission-denied,devadmin 拿到 200)。而 loadUserProgress 没有 try/catch、
  loading.value = false 又写在 await 之后,转圈永远停不下来。
- Teacher Admin 看不到这一栏,尽管他们才是它的目标用户、也是唯一调得动的角色。

条件换成 isTeacherOrAbove,取数补 try/finally。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QqqZwxtXLo2GTqMi51C94D
2026-08-31 08:42:40 -06:00
xuyueandClaude Opus 5 05cf8011e3 fix(题单): 奖章补发改成二进制子命令,独立脚本在生产跑不了
Deploy / deploy (push) Has been cancelled
上一版把补发写成 `bun src/scripts/backfill-problemset-badges.ts`,那在生产上根本执行
不了 —— api 镜像是 debian-slim + 一个编译好的 oj2-api,既没有 bun 也没有源码。

改成 main.ts 的子命令,跑法对齐 migrate(deploy.sh:197 就是这个形态):

  docker compose -f docker/compose.debian.yml run --rm oj-api oj2-api backfill-badges
  docker compose -f docker/compose.debian.yml run --rm oj-api oj2-api backfill-badges --apply

脚本本身从「导入即执行」改成导出一个返回退出码的函数,main.ts 负责解析参数和 exit。
package.json 的 backfill:badges 也指向同一入口,本机和生产走的是同一条代码路径。

用编译出来的二进制在 /tmp 下实跑过全部四条路径(预演 / --apply 后自动复核 / 重复跑
幂等 / 误发时拒绝执行并退 1,加 --allow-revoke 才收回),确认动态 import 的模块进了
bundle、不依赖源码树。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QqqZwxtXLo2GTqMi51C94D
2026-08-31 08:26:27 -06:00
xuyueandClaude Opus 5 f9354b0df1 fix(题单): 进度重算漏了分数和完成状态,奖章没人补发
Deploy / deploy (push) Has been cancelled
进度算法在学生路径和后台路径各写了一遍,于是各自漂了一段。后台那份
(resyncProgress)名叫「把所有参与者的进度重算一遍」,实际只更新分母和百分比:

- 不碰 total_score。改题目分值时专门调了它,函数体里却没这个字段,score 类奖章
  因此按陈旧分数判定。
- 不碰 is_completed。加一道题之后分母变大、百分比掉下来,人还标着「已完成」。
- 不清理 progress_detail。删掉一道题之后 least(completed, total) 只保证不超过分母,
  会把没做的题算成做了 —— 3 题的题单只做出 C,删掉 C 就变成 1/2 = 50%。
- 不重算奖章。题目集一变 all_problems 的达标面就变了,没有任何地方补发。

最后一条攒下了实打实的欠账:8-07 的快照里 53 条应发未发,涉及 30 名学生,误发 0 条。
其中 23 条来自 2026-05-22 00:50 那次一分钟内跨 7 个题单的批量补进度 —— 进度补了,
奖章没人回头判。

两边不再分叉的唯一办法是只留一处算法,所以抽出 services/problemset.ts:
computeProgress 是纯函数,学生做出一题和后台改题目都只是调用者;
eligibleForBadge / recalculateBadge / resyncProgress 一并搬过来,补发脚本才能复用
同一套判定。批量写回仍是一条 UPDATE ... FROM (VALUES ...),没退回逐行往返。

顺带修掉空题单的坑:isCompleted 加了 total > 0 前提。原来 0 === 0 也成立,老师先建
题单、学生先加入、题目后加,加入那一刻就写下 complete_time 并计进「完成题单数」成就,
而且后面补上题目也不会自愈。

一处行为变化:退回未完成时 complete_time 会清空。后台那份原来保留旧时间,学生那份
一直是清空的,统一成后者 —— 否则同一行会出现「未完成 + 有完成时间」,破坏现有数据里
「complete_time 非空 ⟺ is_completed」这条不变量。代价是加题再删题会把历史完成时间
洗成「现在」。

scripts/backfill-problemset-badges.ts 补历史欠账,默认只读预演,--apply 才落库。
只要存在误发就拒绝执行并打出名单,要连收回一起做得显式加 --allow-revoke ——
recalculateBadge 的删除是真删,user_badge 的 earned_time 没有别处备份。

在生产快照上实跑:补发 1180 → 1233 条,复核全部一致,历史 earned_time 未被刷新;
resyncProgress 对题单 9(7 题 / 117 人 / 100 人完成)加题后正确退回 0 人完成并收回
100 枚奖章,删题后完整恢复;改题目分值 10→20 使总分和 7460 → 8590,正好 +113×10。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QqqZwxtXLo2GTqMi51C94D
2026-08-31 08:23:38 -06:00
xuyueandClaude Opus 5 ff31f7abd1 fix(题单): 补回加入题单前旧提交的遮挡
旧栈的 SubmissionListSerializer.get_show_link 有一条防作弊规则:学生加入含某道题的
题单后,他在加入之前留下的 AC 代码就摆在提交列表里,复制粘贴即可过关,所以要把这段
旧提交藏起来。重写时整条丢了 —— canViewSubmission 里 grep 不到一个 problemset,
自己的提交第一行就无条件 return true。

前端反而把 UI 留着了:ProblemSubmission.vue 那个锁图标的 tooltip 一直写着「这道题在
你已经加入的题单中,只有在题单中完成此题,代码才可见」,而后端永远不会给出
showLink: false,图标一次都没亮过 —— 提示语本身成了操作指引。

题单的 end_time 也因此成了孤儿字段:它不是「截止后不能提交」,是这道闸门的时间边界。

影响面不是边角:8-07 的快照里 1734 人次、188 名学生在加入题单之前就已经 AC 过题单
里的题,占全部已解题次的 22.5%。

补回来的同时改了三处旧栈的做法:

- 判断放进 canViewSubmission,列表和详情一起挡。旧栈只挡列表链接,
  SubmissionAPI.get 光走 check_user_permission,知道 submission id 直接访问照样
  拿得到代码,遮挡是虚的。
- 一题落在多个已加入题单里时取 max(join_time),「存在任一题单要求遮挡就遮挡」等价于
  「早于最晚的那次加入」。旧栈用 .first() 取任意一条,行为不确定。
- 比赛提交列表不挂闸门。题单里的题必定是非比赛题(加题时卡了 contestId IS NULL),
  而那条列表只出比赛提交,交集恒空,挂上去就是每页白跑一次查询 —— 而比赛进行中它是
  被刷得最狠的。旧栈 ContestSubmissionListAPI 照抄了 bulk_fetch,那边同样是死代码。

闸门只挡「看代码」这一路,不挡 allowShared=false 那一路 —— 后者是分享开关的归属校验,
与作弊无关,挡了学生连自己旧提交的分享都动不了。管理员不受限,对齐旧栈的
is_regular_user() 前提。

解锁三条路实跑验证过:在题单里做出该题、题单过 end_time、题单归档。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QqqZwxtXLo2GTqMi51C94D
2026-08-31 08:23:13 -06:00
xuyue 2031e6a434 update
Deploy / deploy (push) Has been cancelled
2026-08-31 07:41:44 -06:00
xuyueandClaude Opus 5 e62f41f6c7 refactor(web): Header 只管顶栏,全局的东西挂回 App
Header 一直兼着「全局挂载点」:课堂求助的提示、新求助 toast、求助列表和
教师端协作弹框都寄生在里面,只因为顶栏是全局的。它其实不是 ——
/admin/* 走的是 admin.vue,没有 Header,老师一进后台这四个消费者全部
卸载:求助照收,提示、角标、弹框一个都不出现,正好是 collab.ts 里写的
「老师可能正在后台改题时收到求助」那个场景。

这些东西跟着连接走,而连接在 App.vue 按登录态开关,所以搬进 CollabHost
挂在同一层。Header 因此不必再是单根组件,default.vue 那个靠 class 传
居中样式的写法也换成外层 div,连带删掉「必须挂在根 n-flex 内部」那段
补丁注释。

顺带:
- 圆环扩散的暗黑切换抽成 useDarkTransition
- 求助的角标/toast/列表不再限桌面端 —— 老师缩窗口也得知道有人在等;
  接单确实要在电脑上写代码,那道闸挪进 HelpRequestList
- 站名改 text 按钮,能 tab 到、回车能按
- logout 的两步收进 userStore.signOut()
- 清掉死代码:handleMenuSelect 只认一个不存在的 key、active 里
  ["user","setting"] 永远不生效的排除、两个 show:false 的菜单项

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QqqZwxtXLo2GTqMi51C94D
2026-08-31 07:36:14 -06:00
xuyue cbe6955c26 update
Deploy / deploy (push) Has been cancelled
2026-08-30 22:22:10 -06:00
xuyue 0e083225f1 update
Deploy / deploy (push) Has been cancelled
2026-08-30 22:11:31 -06:00
xuyueandClaude Opus 5 38b81881d5 feat(collab): 教师端弹框补上代码提示,语言跟着学生走
Deploy / deploy (push) Has been cancelled
教师端的协作编辑器只有高亮和括号匹配,没装 autocompletion —— 老师替学生
写代码时没有下拉补全,只能盲敲。而且语言写死 cpp(),学生写 Python 时老师
看到的是 C 的高亮。

- 求助协议带上语言:help_request 记到 HelpRequest,accept 时写进 Room,
  room_open 发给两端;认不出的语言一律当 C(老客户端不带这个字段,而它
  以前就是写死 C 的)
- 新增 help_language / room_language:学生在排队或协作期间切语言,只更新
  语言,不动队列位置和房间;已开房就把新语言推给老师,弹框的高亮和补全
  实时跟着换
- CollabModal 装上 autocompletion,和学生端用同一套 enhanceCompletion +
  completeAnyWord;语言→高亮扩展的映射抽到 shared/extensions/language.ts
  两端共用,免得再分叉
- 学生端求助按钮合并状态提示:原来按钮旁边还挂一个 n-tag,一行工具栏在
  1280 的机房屏上放不下,改成状态全进 label(已求助 · 待接入 / 已求助 ·
  前面 N 人 / xxx 老师帮你中)

扩展数组变了 vue-codemirror 会整体 reconfigure,但 CM6 对已存在的
compartment 取 `compartments.get() || ext.inner`,collabDoc 那个装 yCollab
的 compartment 内容会被沿用,切语言、切主题都不会把协作弄断 —— 实跑验证过
双向同步、补全下拉、协作中切语言三条路径。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015APGLsyaCUa7XFMYAaCho4
2026-08-30 10:28:36 -06:00
xuyue 2f9b6dbf03 FIX
Deploy / deploy (push) Has been cancelled
2026-08-30 09:59:27 -06:00
xuyueandClaude Opus 5 ffabcd4a0d fix(collab): 提示会丢、排队位置不刷新;显式声明 lib0
Deploy / deploy (push) Has been cancelled
- 一次性提示原来挂在题目页的 Form.vue 上消费:学生排着队切去看提交记录,
  老师这时取消了他的求助,那条提示就永远没人消费。挪到顶栏统一弹,
  教师端的 error 提示同理。另外加了序号——连着两次同样的文案在 Vue 眼里
  === 相等,watch(notice) 不会第二次触发。

- queueAhead 原来只在「建请求 / 重连 / 退回排队」推过,前面的人被接走或
  被取消之后不重算,第五个学生会一直显示「前面还有 4 人」。跟着
  broadcastRequests 一起推,两件事永远同时发生。

- collabDoc 动态 import 了 lib0/encoding 和 lib0/decoding,但 lib0 不在
  package.json 里,靠 yjs 提升到根 node_modules 才能解析。上游依赖树一变
  就断,而且断在运行时不在构建时。按现装的 0.2.117 钉住。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016DHxhKNxXfG89JnVzHbvgj
2026-08-30 09:38:04 -06:00
xuyueandClaude Opus 5 4abaf9c7e4 fix(collab): 动态 import 竞态、切走页面的语义、演示模式的身份错位
- collabDoc.start 要 await 六个动态 import,房间可能在这期间就关了(机房首次
  加载 y* 那几个 chunk 正是最慢的时候)。stop() 先跑完面对的是 doc === null,
  什么也拆不到;import 回来之后 start 的后半段照样建文档、装 binaryHandler、
  挂 yCollab、发 SyncStep1——给一个不存在的房间。加会话代号,过期就整个放弃。

- SyncCodeEditor 卸载(切走题目页、把语言切成流程图)原来只是悄悄 stop(),
  房间和 active 都还留着,老师那边模态框照开、字照敲,一个也到不了;watch
  没有 immediate,学生切回来也不会重建。改成明确 leave() 结束协作。
  另外 @ready 也作为起点之一:学生排队时切走、老师这期间接了单,切回来能接上。

- 演示模式下 isTeacherOrAbove 被强制 false,服务端却按库里的 adminType 照样
  把他算作在线老师:学生因此拿到 pending 而不是 no_teacher,排队等一个顶栏里
  根本没有求助列表的人;他自己看到的求助按钮点下去,服务端回「教师不能发起求助」。
  两头都不对,索性对演示模式整个关掉这个功能。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016DHxhKNxXfG89JnVzHbvgj
2026-08-30 09:38:04 -06:00
xuyueandClaude Opus 5 66a564710f fix(collab): 两处会让协作「看起来正常、其实各写各的」的缺陷
都是实测复现出来的,不是推测。

1. 教师第二次接单,看到的是上一个学生的代码拼在自己文档里
   CollabModal 的 code ref 跨会话不清。n-modal 默认 display-directive="if",
   每次打开都重挂 CodeMirror,拿这个 ref 当初始文档;而 yCollab 只观察 ytext、
   从不反过来用 ytext 覆盖编辑器。于是上一轮的代码留在文档里,新学生的内容
   作为 delta 插到位置 0,两边偏移从此对不上。
   实测三轮会累积成 CCC/BBB/AAA/XXX,且教师敲一行之后,教师看到
   「BBB/AAA/XXX」、学生看到「BBB/XXX」——两份不同的文档。
   改法:不绑 v-model,文档完全交给 Yjs;并把 start 的起点从「房间打开 +
   await nextTick」换成「编辑器 ready」,顺带修掉绑到已 destroy 的旧 view。

2. 学生换连接后房间静默死掉
   handleCollabOpen 迁移 socket 时只补发了 help_status,没补 room_open,
   而前端每次连接建立都会把 room 清成 null —— 页面显示「老师正在帮你」,
   编辑器却早把 yCollab 摘了,老师敲的字一个也到不了。
   补发 room_open 也修不好:CRDT 状态跟着旧连接没了,新建 Y.Doc 再 seed
   会和老师那份合并成重复文本。所以改成直接拆房、请求退回排队,
   老师再点一次 —— 和老师掉线走同一条路子。

顺带修掉验证时挖出来的第三个:握手帧会被丢。
两端挂 yCollab 的时刻不同步(教师等模态框、学生等 chunk),先挂好的那端发的
SyncStep1 到对面时还没有 binaryHandler,服务端转发是成功的、客户端却静静丢掉。
丢的偏偏是握手——y-protocols 里 A 的内容靠 B 发的 Step1 换回来,教师的 Step1
一丢,学生的代码就永远到不了教师那边(单向同步,同样看着像在协作)。
CollabWebSocket 改成 handler 装上之前先把二进制帧缓着,装上再按序放行。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016DHxhKNxXfG89JnVzHbvgj
2026-08-30 09:37:41 -06:00
xuyueandClaude Opus 5 bb33e0f0e5 refactor(web): 删掉 SyncCodeEditor 的 problem prop
老实现的残留:sync.ts 拿它拼房间名 problem-${problemId}。新实现的房间以
学生为键、由服务端分配,前端不需要题号 —— 这个必填 prop 声明之后
整个组件再没用过第二次。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016DHxhKNxXfG89JnVzHbvgj
2026-08-30 09:05:48 -06:00
xuyueandClaude Opus 5 4b6242ba70 fix(比赛): 比赛进行中,学生打开比赛题必 500
contest.ts 两处把「藏起来的难度」表示成空串,而 problemDifficultySchema
是严格的三值枚举,parse 直接抛 ZodError。contestDetailsAllowed 在
「比赛进行中 + 看的人不是管理员」时就是假 —— 也就是正常学生在正常比赛里,
比赛题列表和详情页一开就挂。dev 库 contest 表一直是空的,这条路径没被跑到过。

改成下发 null,契约里给这两个字段单独起了 maskedProblemDifficultySchema。
语义上对齐旧 Django:ProblemSafeSerializer 把 difficulty 放在 exclude 里,
字段整个不下发,而不是给一个假值。

端上顺着 null 补了四处:ProblemInfo 的「难度」项整条不渲染(和旧栈表现一致),
题目列表、题单列表同理,transforms 的 ProblemFiltered.difficulty 也放开为可空。
这几处是 vue-tsc 逐个揪出来的,正是严格枚举该起的作用。

实测(学生 / 超管 × 比赛题 / 普通题 四种组合):学生看比赛题详情与列表
从 500 变 200 且 difficulty 为 null,超管仍拿到真值 Low,普通题不受影响;
页面上「难度」整项消失,统计面板其余内容正常。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016DHxhKNxXfG89JnVzHbvgj
2026-08-30 09:01:56 -06:00
xuyueandClaude Opus 5 c7132025f7 fix(collab): 二进制帧的宽松限流档名存实亡
两档共用一个令牌桶:桶按严格档的 20 初始化,之后每条文本帧(含 30 秒
一次的心跳)都会 Math.min(RATE_BURST, ...) 把它压回 20,二进制帧那档
标的 200 突发根本拿不到。实测连打 150 帧在第 101 帧被 1008 踢下线——
正是设计里要避免的「协作编辑时打字把自己踢掉」。

改成两个独立的桶。文本帧仍是 20 / 每秒 2,二进制帧 200 / 每秒 100。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016DHxhKNxXfG89JnVzHbvgj
2026-08-30 08:29:36 -06:00
xuyueandClaude Opus 5 de4e745d90 docs: 课堂求助与协作编辑标记为已实施
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016DHxhKNxXfG89JnVzHbvgj
2026-08-30 08:22:12 -06:00
xuyueandClaude Opus 5 d1fc6349b7 refactor(web): 删掉 y-webrtc 协同编辑的旧实现
sync.ts / syncStatus.ts、y-webrtc 依赖、PUBLIC_SIGNALING_URL 全部移除,
外部信令服务器 signaling.xuyue.cc 不再被使用。
顺带修掉 CLAUDE.md 里「协作在流程图编辑器」这句一直是错的描述。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016DHxhKNxXfG89JnVzHbvgj
2026-08-30 08:22:06 -06:00
xuyueandClaude Opus 5 86857dedf0 feat(web): 协作编辑走 collab 通道
Yjs sync/awareness 协议直接跑在 /ws/collab 上,服务端哑转发。
内容源是学生:学生端先把编辑器内容写进 ytext 再挂 yCollab,
教师端 seedContent 恒为 null —— 这条根治了老实现里谁的代码活下来看运气的问题。

订正 brief 里的一处疏漏:SyncCodeEditor.vue 挂在每个用户的题目页上,教师也不例外
(ProblemEditor.vue 只按语言是不是 Flowchart 分支,不看角色)。教师接单同样会让
collabStore.room 非空,若不按角色收窄,教师自己停在某道题页面上接单时,这个组件
会把教师自己的编辑器内容当成种子插入文档,还会跟 CollabModal 抢
setBinaryHandler 这个单例槽位。改为 `room && !collabStore.isTeacher` 才起协作,
教师端的协作只归 CollabModal 管。

另外两处修正:
- editorView 用 shallowRef 而非 ref —— CodeMirror 的 EditorView 是带 getter 的类
  实例,ref() 的深度 UnwrapRef 会把它拆成丢了原型方法的假类型,vue-tsc 报错。
- Header.vue 挂 CollabModal 放进根 n-flex 内部而不是同级 —— 组件一旦变成多根
  fragment,default.vue 里 `<Header class="header" />` 的 class 就没有单一根节点
  可以落地,header 行会丢掉居中样式(实测触发了 Vue 的
  Extraneous non-props attributes 警告)。n-modal 默认 teleport 到 body,塞在
  这里不影响其实际渲染位置。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K1d8B3f4SXJwDvUY625eQd
2026-08-28 07:43:08 -06:00
xuyueandClaude Opus 5 bfe4468fdb feat(web): 教师顶栏的求助列表
按题目分组,同题多人时标出人数。按等待时长排序但不强制先来先到 ——
上课时有的问题一句话说清、有的要讲五分钟。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K1d8B3f4SXJwDvUY625eQd
2026-08-28 06:48:07 -06:00
xuyueandClaude Opus 5 6f873be367 feat(web): 题目页的「开启同步」换成「求助」
学生发起求助,状态与排队位置显示在按钮旁。
教师端入口不在题目页,所以对教师隐藏这个按钮。

顺带修正 handleHelpCancel:去掉 request.socket !== ws 的校验。
学生取消自己的求助,不管从他哪个标签页发起都合法——
getRequest(ws.data.userId) 已经把范围锁在这一个用户上了,
不是跨用户操作,不需要再比对是不是同一条连接。这层校验此前
会让「第二个标签页点取消」被服务端静默丢弃,前端却已经乐观
地把按钮变回「求助」,是一处 UI 说谎;现在两边状态一致。
handleCollabClose 里排队分支的 socket 归属校验不受影响,
那里的关闭事件是顺带触发的,仍然需要认出是不是本人这条连接。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K1d8B3f4SXJwDvUY625eQd
2026-08-28 06:33:25 -06:00
xuyueandClaude Opus 5 ab8fcc2d42 fix(collab): room_closed 无条件归位、断线重连补状态、学生 socket 重连迁移
Critical:room_closed 不再按 reason 挑着重置 helpStatus——学生自己的 socket
发送失败时服务端删了请求却发不出任何纠正帧,store 会卡在陈旧的 active/pending
上出不来。现在一律先归 idle,老师掉线那条路径服务端会紧跟着补一条
help_status:pending,同一条连接消息严格按序到达,不会被这次重置抢跑。

Critical:断线重连没有补状态。前端 CollabWebSocket 加 onConnected 钩子,
每次连接建立(含重连)都清空本地 requests/helpStatus/room,等服务端补发;
后端 handleCollabOpen 对非老师的重连方,如果这个账号名下还有请求,
补发对应的 help_status(pending 带重算的 queueAhead,active 带 teacherName)。

Critical:重连后请求仍绑在旧 socket 上,导致 handleHelpCancel 的归属校验
认不出新连接、后续通知也写进死连接。handleCollabOpen 里把请求和(如果有)
房间迁移到新 socket,并清掉旧 socket 的 roomOwnerId,防止它稍后的 close
反过来拆掉刚迁移出去的房间。

Minor:disconnect() 补齐 queueAhead/teacherName/notice 的重置,不留陈旧值。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K1d8B3f4SXJwDvUY625eQd
2026-08-28 06:01:41 -06:00
xuyueandClaude Opus 5 17aa69f8a7 feat(web): 课堂求助 store 与全局 collab 连接
连接全局常驻,不跟题目页起落 —— 老师在任何页面都要能收到求助。
列表按题目聚合,同题多人时能一眼看出该全班讲。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K1d8B3f4SXJwDvUY625eQd
2026-08-28 05:36:51 -06:00
xuyueandClaude Opus 5 aef687bcfc fix(api): collab 二进制转发的背压误判与发送失败后的幽灵请求
Important 1:handleCollabBinary 把 send() 返回的 -1 当成失败,实测证明
-1 只是背压——消息已排队,最终照样送达(8MB 帧原样完整到达);只有 0
才是真丢。之前 sent <= 0 一触发背压就拆房间,慢网/大粘贴反而先弄死正常
会话。改成只认 sent === 0;同时空 Uint8Array 的 send() 也回 0(送达和
真丢用同一个返回值分不清),先按长度 0 直接忽略,不转发也不参与失败
判定,否则任意一方发一个空二进制帧就能把房间拆了。

Important 2:发送失败后走 teardownRoom("peer_offline") 从不 removeRequest
(只有 reason === "done" 才删),请求卡在 status: "active" 没有房间,
之后 handleReject / handleHelpCancel / handleLeave / handleAccept 全部
因为状态或归属对不上而拒绝处理,那个学生的后续求助永远被静默吞掉。
补上 offlineSide 参数,和教师断线共用同一条收尾路径:老师那侧消失,
请求退回 pending 并清 teacherId/teacherName,学生收到新的 help_status
pending;学生那侧消失,请求整条清掉。两种情况都发 room_closed 并
broadcastRequests()。

Minor:handleHelpCancel 没有 request.socket === ws 校验,同一账号第二个
标签页能取消第一个标签页排队中的请求——和上一轮修的 close 排队分支是
同一类归属漏洞,补上同样的检查。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K1d8B3f4SXJwDvUY625eQd
2026-08-28 05:28:14 -06:00
xuyueandClaude Opus 5 457df1ef3c fix(api): collab 房间越权与几处时序/静默丢帧缺口
Critical:学生排队断线分支补归属+状态校验,避免同账号双标签页
把 active 请求错删、被另一个学生请求顶替后又被别的老师抢建出
第二间房;handleAccept 补 getRoom(studentId) 兜底同一学生 id
下已有房间的情况。

Important:handleAccept 的库查询是个 await 点,之后补上
teacherSockets().has(ws) 判活,教师在等待期间断线不会再对着
死 socket 建房间。

Minor:handleReject 补上和 handleAccept 一致的库复核,堵住
连接存活期间被降级/禁用的教师继续掐请求的口子;
handleCollabBinary 检查 peer.send() 返回值,转发失败时走既有
teardownRoom 拆房间,不再静默丢帧、悄悄分叉两边的代码。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K1d8B3f4SXJwDvUY625eQd
2026-08-28 02:48:35 -06:00
xuyueandClaude Opus 5 b14639d890 feat(api): collab 房间管理与 Yjs 帧转发
accept 时按库里的 adminType 复核身份,房间以学生为键。
服务端只按房间转发二进制帧,不解析内容。
老师掉线请求退回排队,学生掉线请求随人清除。

顺带处理三项 Task 2 评审遗留:
- TEACHER_ROLES 去重,handler.ts 改为从 routes/helpers.ts 导入,不再自留一份
- 补全学生排队中断线(尚未进房间)的清理分支,避免陈旧请求卡死在列表里
- 修正 websocket.ts 里一处过期注释:username/adminType 是三种 kind 都会填,
  不是只有 collab 才填

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K1d8B3f4SXJwDvUY625eQd
2026-08-28 02:36:12 -06:00
xuyueandClaude Opus 5 1db2c49b87 feat(api): 新增 /ws/collab 通道与课堂求助控制面
学生发起/撤销求助,在线教师收到全量列表。求助只在内存,不落库。
二进制帧的限流单独一档,避免协作输入把连接踢掉。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K1d8B3f4SXJwDvUY625eQd
2026-08-28 02:24:44 -06:00
xuyue c04570b4ad feat(web): BaseWebSocket 支持二进制帧收发
onmessage 原来无条件 JSON.parse,收到 Yjs 二进制帧会落进 catch。
加 onBinary 钩子与 sendRaw,让 collab 通道能复用基类的重连与心跳。
2026-08-28 02:06:13 -06:00
xuyueandClaude Opus 5 59191c9433 docs: 课堂求助与协作编辑实现计划
8 个任务:前端 WS 基类支持二进制 → 后端 collab 通道控制面 → 房间与帧转发
→ 前端 store → 学生求助按钮 → 教师顶栏列表 → 协作编辑 → 清理旧实现。
每个任务收尾是手动验证步骤(项目约定不写测试)。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K1d8B3f4SXJwDvUY625eQd
2026-08-28 02:00:37 -06:00
xuyueandClaude Opus 5 275e70e23a docs: 课堂求助与协作编辑设计文档
学生发起求助、老师从全局列表接单进入协作。传输从 y-webrtc P2P 改为
后端 WebSocket 通道,房间归属与权限由服务端判定。

替换掉现有 sync.ts 的四个结构性问题:房间按题号分导致老师无法指定帮谁、
初始内容源竞态、权限靠客户端自报且三人以上失效、信令服务器无部署源。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K1d8B3f4SXJwDvUY625eQd
2026-08-28 01:50:00 -06:00
xuyueandClaude Opus 5 f38444c97a fix(代码规则): 给 C 题配的规则一半是哑弹,C++ 题根本配不了
Deploy / deploy (push) Has been cancelled
后台的节点下拉是一张 C/Python 混在一起的 15 条表,整份铺给每种语言。给 C 题选到
只有 Python 有的 list_comprehension、f-string,规则存得进去,判题时拿裸名去比节点
类型,C 的语法树里永远不存在它——「必须使用列表推导式」永远失败、「不能使用
f-string」永远通过,两头都不报错,只有学生受着。反过来 mappings 支持的 do_while、
switch、struct、include 在表里没有,编辑器根本选不到。

标签表改成按语言分组,和判题机 mappings 的键集逐条对齐;保存时校验规则与语言是否
匹配,不匹配给中文提示。C 的 target 从 8 个可用变成 14 个。

C++ 接上了 tree-sitter-cpp,386 道 C++ 题从此能配规则。它继承 tree-sitter-c 的语法,
C 那 14 个 target 实测全部通用,另加范围 for、类定义、try-catch、throw、namespace、
模板、lambda、using 共 22 个。调用形态和 C/Python 都不同,一并处理:a.push_back()
和 p->push_back() 是 call_expression + field_expression,不是 Python 的 attribute;
std::sort(...) 的 function 是 qualified_identifier 而不是 identifier,所以额外比一次
:: 末段,否则学生写没写 using namespace std 会得到不同判定。

一起收掉的几处:

- Java/Golang/JavaScript 配的规则一条都不会跑,题目页却照常把它们渲染成「要求」
  挂给学生看。现在后台不给这些语言开 tab,下发给学生的要求也按语言过滤。
- 「出现次数」不填数字存下来是一条恒真规则,描述还退化成光秃秃一个「for 循环」。
  切换引擎时给默认值,保存时拦下,读取时整条丢弃。
- 次数规则失败只说「if 条件 出现 2 次 ✗」,学生不知道自己写了几次,补上「当前 N 次」。
  旧栈的引擎其实算了这个数,但 checker 只取 describe,算完就扔。
- must_have_nesting 的文案没走标签表,学生看到的是「必须使用 for_loop 嵌套」。
- 运算符文案给的是逻辑名,C 题的学生看到「必须使用 and 运算符」,而 C 里写的是 &&。

语义校验放在 astRulesError() 而不是 zod 的 refine 上:astRulesSchema 同时用于读后台
题目详情,在读路径上抛错会让历史脏数据把整个题目详情打不开。保存前先 pickAstRules()
剔除够不着的分组再校验,否则早年配过 C++ 规则的题会把老师锁死——tab 里看不到那组
规则,保存却被拦下。

生产库那 17 条规则(全是 Python3 的 must_exist_node / count_node)行为不变,逐条实跑
核对过。C++ 的 22 个节点 target、25 个运算符也逐个跑了,没有恒假的哑弹。改了带 wasm
内嵌的 ast.ts,dev 和编译两种形态都验过。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-27 11:53:37 -06:00
xuyue 280443c892 fix
Deploy / deploy (push) Has been cancelled
2026-08-27 11:26:00 -06:00
xuyueandClaude Opus 5 77717e439d fix(主题切换): 圆环从视口正中扩散,跟点击的地方对不上
Deploy / deploy (push) Has been cancelled
深浅色切换的圆环扩散原本把圆心写死在 window.innerWidth / 2,不管点哪儿都从屏幕
正中冒出来。改成取指针落点。

半径也跟着修了。原来是 hypot(x, y),只量到左上角——圆心居中时恰好是对的,一挪到
按钮(在右上角)就不够长了,右下角会留一大块旧配色等圆环扩过去,看着像没刷新。
现在取到最远那个角的距离。

键盘触发(Enter / 空格)时 clientX/clientY 是 0,照用会让圆环从屏幕左上角冒出来,
这种情况退回按钮自身中心,用 event.detail === 0 判断。

startViewTransition 的降级判断原样保留,机房那批 Chrome 低于 94 仍然是直接切。

实测(钩住 documentElement.animate 看真实关键帧,视口 1280x633、按钮中心 1255,29):
点正中得 circle at 1255px 29px / r=1392.78,点按钮左上角 (1246,22) 得 at 1246px 22px,
说明跟的是指针不是按钮;键盘 Enter 得 at 1255px 29px,没跑到 (0,0)。三次主题都正确
翻转,无报错。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-27 11:18:12 -06:00
xuyueandClaude Opus 5 6c2381ad2c perf(提交列表): 越早的页越慢,最后一页要等 1.2 秒
Deploy / deploy (push) Has been cancelled
翻页用的是 LIMIT n OFFSET m,而 Postgres 对 OFFSET 没有捷径:前 m 行必须真的
产出再丢掉,丢弃又发生在 join 之后,每一行都白回了一次表。生产快照(10.4 万条
公开提交)实测最后一页 1258ms、碰了 95347 个 buffer。最早那几页平时没人翻,
数据页从来不在缓存里,全是冷读,所以感受上比新的几页慢得多。

改成两步:先只 select create_time / id 数到第 m 行拿游标——这两列正好是部分索引
的全部内容,跳过 m 行走 Index Only Scan,Heap Fetches 为 0,纯在索引页里数数;
再拿这一行做 keyset 回查,只回表取 limit 行。同一页降到约 9ms、885 个 buffer,
端到端 HTTP 10.7ms。代价变成 O(m) 个索引条目而不是堆页,按快照密度外推,
涨到 100 万条时最深一页仍在几十毫秒量级。

接口签名和前端都没动,页码跳转照旧。offset 为 0、以及按题号筛选时(条件在
problem 表上,第一步得跟着 join,index-only 就没了)退回普通 offset。

部分索引从 (create_time) 换成 (create_time, id):create_time 由
new Date().toISOString() 生成,只有毫秒精度,不是全序,游标用 <= 回查时同毫秒的
上一页末行会重复出现在下一页页首。加 id 之后两步走同一个顺序。索引 2.3MB → 6.9MB。

索引两列都建成默认 ASC,靠 Index Only Scan Backward 反着扫。别照着 ORDER BY
写成 (create_time DESC, id DESC):ORDER BY 的 DESC 默认 NULLS FIRST,索引的 DESC
默认 NULLS LAST,规划器认为出不了序,会退化成 external merge sort(5.2MB 落盘),
比不加索引还糟。这一条已写进 schema.ts 和迁移文件的注释。

正确性:在快照上把新旧写法返回的 id 序列逐页比对,14 个 offset × 4 个 limit
共 56 组全部一致,含末尾残页与越界。

比赛提交列表暂不改:单场比赛撑死几千条,offset 不构成问题。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-27 11:13:38 -06:00
xuyueandClaude Opus 5 8861393529 fix(流程图): 评分明细的顺序是乱的,40 分的那项排在最后
Deploy / deploy (push) Has been cancelled
AI 是按分值从高到低返回的:`逻辑正确性(40) → 完整性(30) → 规范性(20) → 清晰度(10)`。
但 `ai_criteria_details` 存在 jsonb 列里,而 Postgres 的 jsonb **不保留键序** ——
它按「键长度 + 字节序」重排,读出来变成 `完整性 → 清晰度 → 规范性 → 逻辑正确性`,
权重最高的那项被排到了最后。

评分弹框和教师端的评分详情都是直接 `v-for` 遍历这个对象,所以两处都乱。
统计面板因为用的是写死的 `CRITERIA_ORDER`,一直是对的 —— 于是同一份数据在两个
地方的顺序还不一致。

把顺序抽到 `utils/constants` 共享,三处统一走 `sortFlowchartCriteria()`;
表里没有的键排到后面,AI 万一返回别的评分项也不会丢。

顺带把限流的提示改得能看懂:撞上 429 时原来只显示「流程图提交失败」,学生会以为
是自己的图有问题然后反复点,越点等得越久。现在按错误码分支,提示「提交太频繁了,
缓一会儿再交」。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-27 10:53:29 -06:00
xuyueandClaude Opus 5 e921506f40 fix(流程图): 「重新判题」从来没成功过,而且会把原来的评分清掉
`bullmq` 对自定义 jobId 有一条兼容老式可重复任务的校验:一旦包含 `:`,就必须
正好切成三段(`job.js` 里的 `split(':').length !== 3`),否则抛
`Custom Id cannot contain :`。

- 代码提交的重判用的是 `${id}:rejudge:${时间戳}` —— 三段,能过;
- 流程图的重判用的是 `${id}:${时间戳}` —— **两段,必抛**。

所以这个接口从上线起就没有成功过一次。更糟的是清空评分发生在入队**之前**:

    await db.update(...).set({ status: 0, aiScore: null, ... })
    await flowchartQueue.add(...)   // ← 在这里抛,500

每点一次「重新判题」,原来的分数、等级、反馈、评分明细就永久丢一次,提交卡在
PENDING,队列里没有任何任务会来救它,老师看到的只是「重新评分失败」。

改成三段式 jobId,并把入队失败落成 FAILED(而不是留在 PENDING)——
与 `POST /flowcharts` 的处理保持一致。

之前几轮验证没发现,是因为当时手上只有一条 PENDING 的提交,被 409(状态不允许
重判)挡在了入队之前,正好绕开了这个 bug。这次完整走教师流程才撞上。

实测:修复前点重判 → 前端「重新评分失败」、库里 status 变 0 且分数清空、
api 日志抛 `Custom Id cannot contain :`;修复后 → 「重新评分已提交」,
70分B级 重评为 86分A级。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-27 10:51:00 -06:00
xuyueandClaude Opus 5 e00ab7b876 perf(流程图统计): 给词云的分词量封顶
Deploy / deploy (push) Has been cancelled
统计接口会把时间窗内所有已完成提交的 criteria / feedback / suggestions 全取回来,
逐条走一遍 jieba。而前端的「全部时段」是不带 start 的 —— 攒一学年就得把所有评语
重新 cut 一遍,而这是个同步阻塞的请求。

只给词云的分词条数封顶(3000),并按时间倒序取,留下的是最近的那批。

**数值不封顶**:总数、均分、等级分布、各项平均分、完成人数仍然按整个时间窗精确
计算 —— 那只是已取回行上的算术,不额外花钱。这些数一旦采样,老师看到的完成率和
均分就是错的,而且从界面上完全看不出来;词云是辅助性的,看的是高频问题,取最近
这些条足够。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-27 06:27:33 -06:00
xuyueandClaude Opus 5 74d3b97f05 feat(流程图列表): 补上状态列,重判按钮按状态置灰
教师端的流程图提交列表一直没有状态列。「排队中」「评分中」「评分失败」三种情况
在界面上长得一模一样 —— 都只是分数栏空着,老师分不出是还没评完还是评失败了。

三处一起改:

- 加状态列(排队中 / 评分中 / 已完成 / 评分失败)。
- 分数列只在已完成时渲染 Grade。原来无论什么状态都渲染,没评完会显示成 0 分,
  看着像「评了但得了 0 分」。
- 重判按钮按状态置灰。后端只接受已完成 / 已失败的重判(其余返回 409),
  原来是点了才知道不行。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-27 06:27:33 -06:00
xuyueandClaude Opus 5 f5ad5318a0 fix(流程图编辑器): Ctrl+Y 没接、清空画布不问一声、存档里塞满 vue-flow 内部字段
## 存档里的一大半是运行时内部状态

画布上的 node 是 vue-flow 的 GraphNode,除了我们自己塞的字段,还挂着
`dimensions` / `computedPosition` / `handleBounds` / `selected` / `dragging` /
`resizing` / `initialized` / `isParent` / `events`(见 vue-flow 的 parseNode)。
这些会跟着一起写进 localStorage、进 20 份历史快照被反复深拷贝、还压缩后提交进
数据库**长期存着**。而重新挂载时它们全都会被重新算一遍 —— 存下来没有任何意义,
还把存档格式和 vue-flow 的内部实现绑死了,将来升级或迁移数据都得跟着动。

`handleBounds` 尤其占地方:一个循环节点有 4 个 handle,每个 6 个数字。

抽一个 `serialize.ts`,落盘/入历史/提交前统一裁成 id / type / position / data /
style 五个字段。`style` 保留 —— 它是建节点时按类型算好的,丢了恢复出来的图会变样。

实测:一个两节点带连线的图,存档 600 字节、节点上只剩那五个字段,九个内部字段
一个不剩;提交上去压缩后 396 字节。

## Ctrl+Y 是假的

工具栏按钮的 title 写着「重做 (Ctrl+Y)」,但只实现了 Ctrl+Shift+Z,按 Y 没反应。
顺手把 key 比较改成小写不敏感(按住 Shift 时 event.key 是大写的 "Z")。

## 清空画布点一下就没了

那个按钮不但清空画布,`clearCache()` 还会把这道题存着的草稿一起删掉,刷新也找
不回来。学生误点的代价太大,加一道确认;画布本来就是空的时候不弹。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-27 06:27:19 -06:00
xuyueandClaude Opus 5 9e41855610 fix(流程图): 点进去空白的 tab、以及「渲染成功」这个只进不出的开关
## 两个开关同时打开会做出一个空 tab

后端在 `allowFlowchart` 为真时把 `mermaidCode` 置成 null(不能把标准答案下发给
正要自己画图的学生,见 routes/problem.ts)。而前端 `tabOptions` 只看
`showFlowchart` 就把 "flowchart" 加进选项,面板那边却要求
`showFlowchart && mermaidCode` —— 两个开关都打开时,选项存在、面板不存在,
URL 里带 `?tab=flowchart` 就会选中一个渲染不出任何东西的页签。

三个断点条件还各不相同(两处要求两者都有,第三处只看 showFlowchart,那处会拿
null 去渲染 ProblemFlowchart)。统一成一个 `canShowFlowchart`。

后台那边把「显示标准流程图」在允许提交流程图时置灰并说明原因,再补一个 watch
把存量数据里两个都开着的情况纠正掉 —— 它们本来就是互斥的。

## 「渲染成功」只进不出

保存前的校验靠 `mermaidRenderSuccess`,而 MermaidEditor 只在成功时 emit、
这个 ref 也就只会从 false 变 true,永不复位。**先写对、再改坏,照样能存进库。**

改成上报渲染结果本身(`render-state`),并在 modelValue 一变就立刻打回
「未验证」,等防抖后的渲染真跑完再报结论 —— 只挂防抖那一支的话,改完 300ms 内
点保存读到的还是上一次的结论,刚改坏的代码会被当成校验通过。宁可让出题人多等
一下,也不能放脏数据进库。

实测:改动后 50ms 读到 false(此时保存会被拦),渲染完成后回到 true;
贴一段坏语法则一直是 false。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-27 06:27:02 -06:00
xuyueandClaude Opus 5 d10172f017 fix(流程图): 节点名里带一个双引号,生成的 mermaid 就是坏的
节点和连线的标签是学生自己敲的任意文字,而转换器是直接把它塞进 `"..."` 里:

    ${nodeId}(("${label}"))

出现一个双引号就把语法撑破了。后果不只是图渲染不出来 —— 这段坏掉的代码会**原样
提交给 AI 打分**,学生完全不知道自己被扣分是因为一个引号。把 `说"你好"` 当节点名
是很自然的写法。

改用 mermaid 的实体转义。`#` 必须先转,否则标签里本来就有的 `#quot;` 之类会被当
成实体解释;换行转成 `<br/>`,不然会截断整条语句。

实测:`说"你好" #1` 现在生成 `说#quot;你好#quot; #35;1`,渲染出来仍然显示
`说"你好" #1`;未转义的那版渲染报语法错误、一个 svg 都出不来。

顺带补上 `edges` 的空值保护 —— `nodes` 有,`edges` 一直没有,拿到 undefined 直接抛。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-27 06:26:45 -06:00
xuyueandClaude Opus 5 0392445dd2 fix(流程图): 补上几处静默失败 —— 点了没反应、弹框永久转圈
`utils/api.ts` 的拦截器只对 login-required / account-disabled / permission-denied
弹提示,其余业务错误一律静默 reject。而流程图这一块的调用点基本都没 catch,
于是失败时用户什么都看不到:

- **重新判题**:后端会拒掉还在评分中的提交(409 retry-not-allowed),也可能撞上
  限流。老师点下去完全没反应,连报错都没有。实测修复前 0 条提示,修复后弹出
  「这条还在评分中,等出了结果再重新评分」。
  提示按**错误码**分支而不是 match 文案(`utils/api.ts` 里写明的约定)——
  后端文案是英文的,直接弹给老师看不合适。
- **课堂统计**:请求失败后图表停在旧数据上,没有任何迹象表明这次没拉到。

同一批里 `SubmitFlowchart` 的三处(弹框翻页、打开评分详情、加载到编辑器)随
上一个提交一起改了,问题是一样的:前两处失败时 `rendering` 卡在 true,弹框
永久转圈。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-27 06:15:11 -06:00
xuyueandClaude Opus 5 5480abaaea fix(流程图编辑器): 换题草稿串题、第一步撤销不了、历史存的是改动前的状态
## 换题时画布不跟着换

storage key 是按题目 ID 算的 computed。`useStorage` 确实会 watch key,但它只把
新 key 的内容读进 `storedData`,**不会回填 `nodes`/`edges`**,而 `loadFromCache()`
只在 onMounted 调一次。于是同名路由换参数(题目 → 题目,组件不重新挂载)时,
画布上还留着上一题的图;学生一动,防抖保存就把上一题的内容写进**这一题的 key**,
把原本存着的草稿覆盖掉。

补一个 key 的 watch,重新载入并在载不到时清空画布。这里依赖 `useStorage` 内部
对 key 的 watch 先于本 watch 执行 —— 两者都是 pre flush,且 useStorage 在上方
先创建,pre 队列按创建顺序跑,此刻 `storedData` 已经是新 key 的数据。

实测(router.push 直接切题):修复前 1003 的画布上挂着 1002 的节点,修复后
1003 是空的、1002 的草稿完好。

**需要说明**:今天的 UI 走不到这条路 —— 题目页没有「下一题」入口,题单和比赛
切题都要先回列表页(不同路由、组件会重新挂载)。所以这条目前是加固,一旦以后
加了题内切题入口就立刻变成必需品。

## 撤销少一步、存的还是旧状态

`historyIndex` 从 -1 开始,而 `canUndo` 要求 `index > 0`,第一步操作永远撤销
不了。补 `resetHistory`,挂载时和换题后各播一次初始快照(换题不重建的话,一次
撤销会把上一题的图还原到这一题里)。

`addEdges` / `removeNodes` / `removeEdges` 之后紧接着 `saveState(nodes.value,
edges.value)` —— 而 vue-flow 的 store → v-model 回写走的是 `watchPausable`
(pre flush,异步),此刻读到的还是**改动前**的数组,存进历史整体错开一步。
画布上的 `handleDrop` 早就 `await nextTick()` 了,这几处一直漏了;
`clearCanvas` 因为是直接赋值 model ref(同步)反而是对的 —— 所以这套行为一直
是「有时对有时错」,更难排查。

顺带:`handleNodeDelete` 里手动删相连边是多余的,`removeNodes` 的
`removeConnectedEdges` 默认就是 true;`deleteSelected` 在什么都没选中时不再
白记一条历史。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-27 06:14:59 -06:00
xuyueandClaude Opus 5 5f0fe713dc fix(流程图渲染): 出错后再也画不出来、每失败一次往 body 漏一个 div
## 渲染失败后永久空白

四个渲染点都是同一个写法:

    <n-alert v-if="renderError" ... />
    <div v-else ref="mermaidContainer"></div>

一旦渲染出错,容器被 `v-else` 卸载,`mermaidContainer.value` 变成 null。而
`renderFlowchart` 一进来就先清 `renderError`、再因为 `!container` 直接 return ——
于是**报错提示消失了,图也再画不出来**,只剩一块空白,只能刷新页面。翻历史提交
最容易踩到。改成容器常驻、用 `v-show` 隐藏,和 MermaidEditor 本来的写法一致。
`FlowchartScoreDetail` 那处 Teleport 上不能挂 v-show,把条件挪到内层容器。

实测:修复前切回合法代码后 0 个 svg(永久空白),修复后正常渲染。

## 每次渲染失败都往 body 漏一个 div

`m.render(id, code)` 没传容器,mermaid 会在 `document.body` 上建一个临时
`div#d{id}`。而 `suppressErrorRendering` 默认关着,看 mermaid 源码,解析出错时
是先 `errorRenderer.draw()` 再 `throw`,**清理临时容器的那行在 throw 之后**,
永远执行不到;每次 render 用的又是新的随机 id,`removeExistingElements` 也清不掉
旧的。于是渲染失败一次就留一个。

出题页是边敲边预览,且没有防抖,每个字符触发一次完整渲染,中间态几乎全是语法
错误 —— 实测逐字符敲 26 个字符,body 里留下 16 个残留 div。打开
`suppressErrorRendering`(该分支是先清理再抛)+ 预览防抖 300ms,实测降到 0,
预览功能不受影响。

## 顺带

`loadMermaid` 缓存的是实例,两个组件同屏挂载时会双双落进 `if (!mermaidInstance)`,
import 和 initialize 各跑两次。改成缓存 Promise,并在失败时清掉缓存,避免一次
网络抖动把后续所有渲染都钉死在这个失败结果上。

`SubmitFlowchart` 的 `updatePage` / `openDetailModal` / `loadToEditor` 一并补了
错误兜底(同文件,见下一个提交的说明):前两个失败时 `rendering` 会卡在 true,
弹框永久转圈;`loadToEditor` 是裸 `JSON.parse`,老提交数据坏掉就点了没反应。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-27 06:14:40 -06:00
xuyueandClaude Opus 5 c27c9fdbf9 fix(流程图评分): 队列重试从没生效过、AI 调用不设超时、等级由模型自报
## 重试是摆设

`flowchartQueue` 配了 `attempts: 3` + 指数退避,但任务开头有一道守卫:

    if (!row || ![0, 1].includes(row.flowchart.status)) return

而 catch 里第一件事就是把 status 写成 3(FAILED)。于是第 2、3 次尝试进来一看
状态是 3,直接 return、算作成功 —— **实际只跑了一次**。AI 侧的偶发失败(限流、
超时、网络抖动)永远等不到重试,学生看到「评分失败」只能自己重新提交。

改成只有最后一次尝试才落 FAILED,中间几次把状态留在 PROCESSING(1) 让守卫放行。
「是不是最后一次」由 worker 算好传进来:`attemptsMade` 是「此前已失败几次」,
当前这次还没计入,所以判据是 `attemptsMade + 1 >= attempts`。

实测(用没配 AI_KEY 这条必然失败的路径):修复前 t+1s 就落 FAILED、只评一次;
修复后评满 3 次,状态到 t+7s 才落 FAILED。

## fetch 不设超时

`completeChat` 直接 `fetch`,而 fetch 默认不超时。AI 侧一挂就把 worker 的并发位
(只有 2 个)一直占着,学生那边的按钮也就一直转。加 60 秒超时。

流式调用**不加**:那边超时会把正在推的长回答直接掐断,而客户端断开本来就能收尾。

## 等级不该由模型说了算

提示词里写死了 S/A/B/C 四档分数区间,但模型偶尔会给出「88 分配 S 级」这种自相
矛盾的结果,甚至直接吐「优秀」。脏值会一路串到等级分布图、等级筛选,以及
「A/S 才把流程图展示给学生」的判断里。改成一律由分数推出等级,模型自报的 grade
不再采信;score 本来就已经 clamp 到 0-100。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-27 06:14:21 -06:00
xuyueandClaude Opus 5 8f08ed03a0 fix(流程图): 学生能翻出全班评分、AI 调用没有限流
## 列表漏了一道门

代码提交列表在 `routes/submission.ts` 里有 `submission_list_show_all` 兜底:
关掉时非管理员一律返回空。流程图列表**从来没有这道门**,而它的过滤是

    if (myself === "1" || (!username && 是普通用户)) 只看自己
    else if (username) 按用户名模糊匹配

—— 只要带上 `username`,第二支就把第一支的限制绕过去了。学生在提交记录页把
语言切成「流程图」、用户名框随便填一个字,就能翻出全班同学的 AI 评分,不需要
动接口。补上和代码提交同一套口径。

## 提交与重判没有限流

每一次流程图提交都会触发一次外部 AI 调用,是和判题沙箱同级的有限资源,而这两个
入口都没限流。`canView` 还允许**本人**重试自己的提交,等于学生可以对着自己的
提交反复点,无上限地刷 AI 调用。

限流桶不能直接用 `throttling:user:<id>` —— 那是代码提交在用的桶(capacity 20,
回填约 1.8 个/分钟),共用的话学生在机房连着交几次代码,流程图这边就会莫名其妙
交不上去。单独开 `throttling:user:flowchart:<id>`。

重判对教师放行:成批点几十行是他们的正常用法。

## 提交编号的权限判断在前端自己算了一遍

契约里 `flowchartListItem.showLink` 是后端逐行下发的(与 `GET /flowcharts/:id`
的放行条件同源),前端却没用,自己按「超管或本人」重算了一次 —— 教师因此看得到
「重新判题」却打不开评分详情。

更要命的是无权限那一支渲染的 `n-text` **照样挂着 @click**,权限判断只改了外观。
学生点别人的编号,后端以 404 挡下,`loadSubmission` 只 console.error,于是弹出
一个 600px 高的空白面板,什么提示都没有。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-27 06:14:05 -06:00
324 changed files with 95492 additions and 16888 deletions
+7
View File
@@ -0,0 +1,7 @@
# drizzle-kit 生成的迁移快照。内容等价的重排也别做 —— 这些文件是
# db:generate 拿来比对上一版结构的输入,只该由 drizzle-kit 写。
apps/api/src/db/meta/
# unplugin 每次 dev 都会重写,格式化了也留不住
apps/web/src/auto-imports.d.ts
apps/web/src/components.d.ts
+174 -188
View File
@@ -1,28 +1,28 @@
# CLAUDE.md
OJ2 是判题狗(Online Judge)的后端重写:Django 6 → Bun + TypeScript,前后端同仓。
上一代在 `../OnlineJudge/`Django)和 `../ojnext/`Vue SPA**仍然完全冻结、
一行都不改**。
上一代在 `../OnlineJudge/`Django)和 `../ojnext/`Vue SPA
> **2026-08-26:回滚路径已废弃,且已经不可逆。** 旧 Django 后端确认不再使用,
> `0002_drop_django_leftovers` 删掉了它的 7 张框架表(含 `django_session`、
> `django_migrations`)。**这条迁移已在生产库执行完毕**
> `docker exec oj-api oj2-api migrate` 回「没有待执行的迁移」)。
> **旧栈已不可逆地下线**`0002_drop_django_leftovers` 删掉了 Django 的框架表并已在生产库
> 执行完毕,漏网的一张空 `django_migrations` 由 `0014` 补删)。所以「停新栈起旧栈」已经
> 不是退路,**唯一退路是从数据库备份恢复**
>
> 所以旧栈现在**起不来**了:「停新栈起旧栈」「把 NPM 上游改回 8080」都已失效,
> 唯一退路是从数据库备份恢复。切换手册里的「回滚保证」那节只剩历史价值。
>
> 「改 schema 要考虑回滚」这条约束随之解除,schema 归 OJ2 独占,
> 走 drizzle migration 正常演进即可。
> **旧仓库仍然零改动**,没有例外 —— 包括修 bug、包括不影响外部接口的内部小修。
> 所有后续工作,包括在旧仓库里发现的 bug,都只落在 OJ2:先确认 OJ2 是否有对应逻辑、是否
> 重现了同样的问题,只在 OJ2 里修;旧仓库那边如实告知用户「未处理,按当前政策不动旧仓库」,
> 不要顺手改掉。冻结的理由现在只剩「留作参照、别分散精力」,不再是回滚保证。
> **旧仓库仍然零改动**,没有例外——包括修 bug、包括不影响外部接口的内部小修。
> 所有后续工作,包括在旧仓库里发现的 bug,都只落在 OJ2:先确认 OJ2 是否有对应逻辑、
> 是否重现了同样的问题,只在 OJ2 里修;旧仓库那边如实告知用户"未处理,按当前政策
> 不动旧仓库",不要顺手改掉。冻结的理由现在只剩「留作参照、别分散精力」,
> 不再是回滚保证。
细节文档(`CLAUDE.md` 只留日常要记住的,展开都在这几份里):
设计文档:`docs/specs/2026-08-06-bun-backend-rewrite-design.md`
切换手册:`docs/specs/phase5-cutover-runbook.md` ← 上线当天照这份走
| 文档 | 什么时候读 |
|---|---|
| `docs/deploy.md` | 部署、上线、备份恢复 |
| `docs/database.md` | 写迁移、给新库打基线、drizzle-kit 抽风 |
| `docs/timezone.md` | 动日历口径、动时间出参格式 |
| `docs/contract.md` | 动 zod 契约、想给某个字段加校验 |
| `docs/ast-rules.md` | 动 AST 代码规则、升级 tree-sitter |
| `docker/judge/README.md` | 换判题沙箱镜像、升语言版本(gcc / Python / Node …) |
| `docs/specs/` | 两份设计文档:后端重写、课堂求助与协作编辑 |
## 仓库结构
@@ -31,18 +31,18 @@ OJ2 是判题狗(Online Judge)的后端重写:Django 6 → Bun + TypeScrip
| `apps/api/` | 后端。Hono + Drizzle + BullMQ,编译成单二进制 |
| `apps/web/` | 前端。从 ojnext 原样搬来的 Vue 3 SPA |
| `packages/contract/` | 前后端共用的 Zod 契约 |
| `docker/` | Dockerfile + 三套 composedev / debian / school |
| `docs/specs/` | 设计、端点清单、各阶段评审报告与演练报告 |
| `docker/` | Dockerfile + 三套 composedev / debian / school+ 部署与运维脚本 |
| `docs/` | 上面那几份专题文档 + `specs/` 里的设计文档 |
## 本机环境
**Docker 可用,全套依赖都能在本机跑起来**PostgreSQL、Redis、判题沙箱),
镜像也能在本机构建并完整演练上线。这一点和上一代不同,别沿用"本机跑不起来后端"
的旧假设。
镜像也能在本机构建并完整演练上线。这一点和上一代不同,别沿用本机跑不起来后端」的旧假设。
```bash
bun install
bun run db:up # 起 postgres(5433) / redis(6380) / 判题沙箱(8081)
bun run db:migrate # 空库会从 0000 自举出全部结构
bun run dev # api(3000) + worker + web(5173) 一起起
```
@@ -52,28 +52,43 @@ bun run dev # api(3000) + worker + web(5173) 一起起
常用检查:
```bash
bunx tsc --noEmit -p apps/api # 后端类型检查
bun run --filter '@oj2/api' typecheck # 后端类型检查
bun run --filter '@oj2/api' check:routes # 路由遮蔽检查,加完路由跑一下
cd apps/web && bun run build # 前端构建(vite 不做类型检查,构建即验证)
bun run --filter '@oj2/api' check:ast # AST 节点类型检查,升级 tree-sitter 后跑
cd apps/web && bun run type-check # 前端类型检查
cd apps/web && bun run build # 前端构建
bun run fmt # Prettier,全仓一把(只在根目录有)
```
**格式化是全仓一套 Prettier**,配置只有根目录的 `.prettierrc.toml``semi=false`
其余全默认,printWidth 80)。`bun run fmt` 覆盖 `apps/*/src``packages/*/src` 和两个
构建配置;`.prettierignore` 挡掉 drizzle-kit 生成的 `src/db/meta/` 快照和 unplugin
每次 dev 都会重写的两个 `.d.ts`。后端和契约原来没进 Prettier(手写在 100 列上下),
2026-09-16 一次性全量格式化过 —— 之后**改完代码顺手跑一下 `bun run fmt`**
别再让两边的口径分叉。
⚠️ **前端类型检查只能走 `bun run type-check` 这个脚本。** 两条看起来等价的路子都会**静默
通过**`vue-tsc --noEmit -p tsconfig.json` 检查 0 个文件(那个 tsconfig 是 `files: []` +
references 的壳,真正的配置在 `tsconfig.app.json`),而 `vite build` 根本不做类型检查。
改完 .vue / .ts 别拿构建当验证。
**不要写测试** —— 沿用上一代的项目约定。验证靠实跑:起服务、打接口、看结果。
本机 Docker 全套都能起,实跑的成本比想象中低。
## 几件必须知道的事
### 单二进制是有代价的
`apps/api` 编译成 `bun build --compile` 的单二进制,所以**运行时不能依赖
node_modules**。任何 `require.resolve` / `Bun.resolveSync` / `__dirname` 去找文件的
写法,本地都正常、编译后都会炸,而且**只在离开仓库目录后才炸**(在仓库里跑时它顺着
cwd 摸到了 node_modules假装没事)。
`apps/api` 编译成 `bun build --compile` 的单二进制,所以**运行时不能依赖 node_modules**。
任何 `require.resolve` / `Bun.resolveSync` / `__dirname` 去找文件的写法,本地都正常、编译后
都会炸,而且**只在离开仓库目录后才炸**(在仓库里跑时它顺着 cwd 摸到了 node_modules
假装没事)。
资源要用 `with { type: "file" }` 内嵌。`.node` 原生模块还要额外注意:这个写法
只有打包器认、`bun run` 不认,所以必须按形态分叉 —— 见 `apps/api/src/vendor/jieba.ts`
的注释,那里把坑写全了。
资源要用 `with { type: "file" }` 内嵌。`.node` 原生模块还要额外注意:这个写法只有打包器认、
`bun run` 不认,所以必须按形态分叉 —— 见 `apps/api/src/vendor/jieba.ts` 的注释,
那里把坑写全了。
**改完这类代码,dev 和编译两种形态都要跑一遍。** 我吃过亏:只验了编译产物,
dev 直接起不来。
**改完这类代码,dev 和编译两种形态都要跑一遍。** 我吃过亏:只验了编译产物,dev 直接起不来。
### 路径解析看 `runtime.ts`
@@ -82,17 +97,15 @@ dev 直接起不来。
### SQL 判题会 spawn「自己」
`judge/sql/index.ts` 起的子进程是二进制自身 + `sql-child` 子命令(因为编译后磁盘上
没有 child.ts 可以 spawn)。所以**入口必须有 argv 分发**,否则「起自己」变成
「把整个程序再跑一遍」→ 指数级 fork。这不是假想,开发时炸过一次开发机。
`OJ2_SQL_CHILD` 那道递归闸不要删。
`judge/sql/index.ts` 起的子进程是二进制自身 + `sql-child` 子命令(因为编译后磁盘上没有
child.ts 可以 spawn)。所以**入口必须有 argv 分发**,否则「起自己」变成「把整个程序再跑
一遍」→ 指数级 fork。这不是假想,开发时炸过一次开发机。`OJ2_SQL_CHILD` 那道递归闸不要删。
### 加路由要防遮蔽
**Hono 按注册顺序匹配,不是静态优先**(实测确认过,别凭直觉)。`/problems/:id`
注册在 `/problems/random` 前面的话,后者永远进不去 —— 而且不报错、不警告,
只是静默走进前一条的 handler。阶段 4 真实发生过一次,两个教师用的分析端点被吃掉,
一直到评审才发现。
**Hono 按注册顺序匹配,不是静态优先**(实测确认过,别凭直觉)。`/problems/:id` 注册在
`/problems/random` 前面的话,后者永远进不去 —— 而且不报错、不警告,只是静默走进前一条的
handler。阶段 4 真实发生过一次,两个教师用的分析端点被吃掉,一直到评审才发现。
加完路由跑 `bun run --filter '@oj2/api' check:routes`
@@ -102,172 +115,145 @@ dev 直接起不来。
这些整数是**落库的值**:12 万条历史提交的 `submission.result` 就是它们,判题沙箱回的也是
这套编码,所以只能新增、不能改已有的含义。题目表情 reaction 的语义 key 同理。
### 判题镜像是自己构建的
`compose.*.yml` 里的 `oj2-judge-2` **不在任何 registry 上**:上游
QingdaoU/JudgeServer 停更在 2024-04(官方镜像的 `latest``1.6.1` 是同一份,
编译器停在 gcc-13),新工具链只能自己编。`docker/judge/` 里是只改版本的 Dockerfile
分叉 + 构建脚本 + 冒烟测试,判题逻辑一行没动。
- 新机器、换镜像:先 `docker/judge/build.sh --save` → scp → `docker load`,再部署。
**服务器和机房各有各的判题沙箱,两边都要装。**
- 改工具链就把末尾序号 +1(下一版 `oj2-judge-3`)。`up -d` 不带 `--pull`,名字没变会静默用旧镜像。
- 编译/运行命令在 `apps/api/src/judge/languages.ts`,不在镜像里。gcc-14 把隐式函数
声明等提成了 error`-w` 压不住),那边的 `cLooseErrors` 三个 `-Wno-error=` 就是
为此加的 —— 删掉它们等于让一批历史题解和 C 教程示例集体 CE。
- **判题沙箱只认 C / C++ / Python。** Java / JavaScript / Golang 连同镜像里的
JDK / Node / Go 在 2026-09 一起砍了(前端本来就没给入口,12 万条提交里它们共 62 条),
契约 `judgeLanguageSchema` 里的键留着是为了渲染那 62 条历史提交。
**`Python3` / `Python2` 这两个旧值已经没有了** —— 0019 迁移把 104530 条提交、937 道题、
1235 个用户的成就指标并成了一个 `Python`,0020 顺手把那三种语言从题目的可选语言里摘掉
(不摘的话 84 道题的语言下拉还能选 Java,提交必 SYSTEM_ERROR)。查判题配置走
`judgeConfigFor()`,它带旧值别名;**回滚要连数据一起回**,只滚代码会让 Python 提交全炸。
- 换完镜像跑 `bun docker/judge/smoke.ts`:三种语言、六种状态码、gcc 宽松度一起核。
### 出参不 `parse`,用 `satisfies`
**后端的响应一律 `satisfies XxxType`,不要写 `xxxSchema.parse({...})`。** 出参是后端自己刚
拼出来的字面量,TS 已经在编译期校验过;再 parse 一遍拿不到任何新信息,唯一可能失败的输入是
**库里的历史数据**,而失败的代价是 500 —— 这条规矩是被四次这样的线上故障换来的。
**闸设在写入侧**:入参 `safeParse`58 处)、`db/schema.ts``.$type<>()` 列收窄、
语义校验函数(`astRulesError()` / `exerciseDataError`)。JSONB 原文
`submission.info` / `statistic_info` / `exercise.data`)一律放行,它们的形状真相在判题机
那边。query 的筛选值走 `routes/helpers.ts``asFilterValue()`,那是纯类型交接、不加校验。
四次故障的细节、`.$type<>()` 断言该怎么核,见 `docs/contract.md`
前端为什么只在三处挂运行时闸门,见 `apps/web/CLAUDE.md`
### AST 代码规则:一张表,外加一个机器检查
契约的 `AST_NODE_TARGETS_BY_LANGUAGE` 是**唯一**一张表(`label` 给界面、`node` 给判题机),
判题机侧没有第二张表,所以加 target 漏配节点类型在结构上不可能。但**配错**仍然可能,
而且完全静默 —— 节点类型对不上就是「必须使用 X」永远失败、「不能使用 X」永远通过。
```bash
bun run --filter '@oj2/api' check:ast # 升级 tree-sitter-* 之后一定要跑
```
判题机只认 C / C++ / Python`AST_SUPPORTED_LANGUAGES`),别的语言配了规则一条都不会跑,
所以后台不给它们开 tab —— **看得见却不检查**比没有更糟。C++ 的调用形态和 C 不一样、
规则的语义校验为什么不挂在 zod 上,见 `docs/ast-rules.md`
### 比赛只有 ACM 模式
没有 OI。上一代残留的 OI 分支在阶段 0 已经砍掉,不要"顺手补回来"
没有 OI。上一代残留的 OI 分支在阶段 0 已经砍掉,不要顺手补回来
### 前端要兼容老 Chrome
### 前端基线是 Chrome 1052026-09-16 从 < 94 上调)
机房电脑 Chrome < 94。`mermaid-legacy` 等 fallback 依赖和 vite 的构建 target
不能动,`vite.config.ts` 里有注释说明。
机房**部分**电脑 Chrome 105,其余更新 —— 按最低那档定基线。
- **`@vitejs/plugin-legacy` 留着,别删**vite 8 的默认构建 target 是 `chrome111`,比 105 高。
这个插件同时把 `build.target` 压到 `es2020/chrome105`、给现代产物补 core-js polyfill
`toSorted` / `Set` 运算 / 迭代器辅助那批是 Chrome 110+ 才有的)。`modernTargets` 不写,
用插件自带的基线(`chrome>=105`),正好是这一档。polyfill 清单写死在 `vite.config.ts`
**升级前端依赖后重新审计**`DEBUG=vite:legacy bun run build` 会打印探测到的全集。
- **Chrome < 94 那套删掉了**`mermaid-legacy`mermaid@9)、cytoscape 的 UMD→ESM 别名、
`useMermaid.ts` 里按 UA 分叉的 v9 回调式 render —— 105 用得上 mermaid 11。
- **View Transitions 要 111105 没有**`darkTransition.ts` 的降级分支是真在用的。
### 时间只有一个锚点:`apps/api/src/time.ts`
**凡是要把一个时刻换算成「哪一天 / 几点 / 哪一年」,一律走那个模块。** 不要写
`new Date(x).getHours()``setHours(0,0,0,0)``getFullYear()``new Date(y, m, d)` 这类跟
**进程时区**走的代码 —— 容器是 UTC、开发机是本机时区,两边答案不同而且不报错。
SQL 里要按日历切,用 `localTime(列)`(生成 `列 at time zone 'Asia/Shanghai'`),
别依赖数据库会话时区。
**分层:存 UTC 时刻 → 后端判定按东八区 → 出参 ISO UTC → 前端按东八区渲染。**
- **存**35 个时间列全是 `timestamptz`,写侧一律 `new Date().toISOString()`
- **判定**:日历语义走 `time.ts`SQL 用 `localTime()`
- **出参**`db/index.ts` 给 OID 1184 挂了 parser,读出来的时刻统一成 ISO 8601 UTC
**微秒必须保留**(截成毫秒会让翻页每页丢一条、班级 AC 排名少 1)。
- **渲染**:前端 `parseTime()` / `zonedParts()` 按同一个固定偏移取东八区部件
(见 `apps/web/CLAUDE.md`)。
时区常量 `TIME_ZONE` / `TIME_ZONE_OFFSET_MINUTES``packages/contract/src/time.ts`
前后端共用一份,按**固定偏移**算(大陆 1991 年起没有夏令时)。旧栈的口径本来就是东八区,
重写时丢过一次、2026-09 才收回来 —— 期间「今日提交」在北京时间 0:00–8:00 是空的,
两个小时口径的成就整体偏 8 小时,事后已用一次性脚本对账订正(账平了,脚本已删)。
**再动日历口径之前先读 `docs/timezone.md`**,那里有实测数据和核实方法;
Dockerfile 的 `TZ` 和数据库连接的 `TimeZone` 是**刻意不设**的,别「顺手补上」。
## 数据库
Drizzle schema 最初是 `drizzle-kit pull` 从生产库拉出来的,所以它长得像 Django 建的表
(表名、bigint/int4 混用、外键全是 NO ACTION),`schema.ts` 顶部记了哪些地方是手工修的。
(表名、bigint/int4 混用),`schema.ts` 顶部记了哪些地方是手工修的。
**schema 现在归 OJ2 独占**,结构变更走 migration 正常演进。
**schema 现在归 OJ2 独占。** 旧后端已下线,「改 schema 要考虑回滚」这条约束不再存在,
结构变更走下面的 migration 正常演进即可。
**外键的删除动作从 0010 起是显式的**,不再是 Django 留下的一律 NO ACTION
- **CASCADE**:父行消失后子行必然无意义、且不构成「学生做过什么」的证据 —— 中间表
problem_tags)、题单/教程/成就的组成部分、一对一附属(user_profile)与可重算的缓存
user_stat)。
- **NO ACTION(即拦住)**:需要人看见的删除 —— `submission.problem_id`、以及 `user` 的绝大
多数外键。删用户撞外键会被 handler 翻译成「请改为禁用账号」,这是有意的。
**加新子表时必须回来想一遍该走哪一档**,别默认新外键会自己连坐 —— drizzle 不写
`.onDelete()` 就是 NO ACTION,而 0010 只改了当时存在的那批。
### 改 schema 走 drizzle migration
`bun run db:generate`(造迁移文件)→ `bun run db:migrate`(按 `drizzle.__drizzle_migrations`
增量执行),就是 Django `makemigrations` / `migrate`等价物。索引/结构变更走这条,
不要再手写 SQL 往 `docs/specs/` 里塞。
`bun run db:generate`(造迁移文件)→ `bun run db:migrate`(按
`drizzle.__drizzle_migrations` 增量执行),就是 Django `makemigrations` / `migrate`
等价物。索引/结构变更走这条,不要再手写 SQL 往 `docs/` 里塞。
**部署时自动执行。** `docker/deploy.sh` 在「构建镜像」之后、「起栈」之前会跑
`oj2-api migrate`,失败就中止部署(旧容器原样还在跑)。CI 走的也是 deploy.sh
所以不需要给 GitHub 配数据库凭据,也不用把生产库对外开放
- **执行器是自己的**`db/migrate.ts`,一条迁移一个事务),不是 drizzle 那个,
`db:migrate` 和线上 `oj2-api migrate` 是同一条代码路径。
- **部署时自动执行**`docker/deploy.sh` 在构建镜像之后、起栈之前跑,失败就中止部署
- 迁移文件**不内嵌进二进制**,随镜像装在 `/usr/local/share/oj2/migrations`
(见 `runtime.ts``migrationsDir`),所以新增迁移不用改任何代码。
- **破坏性迁移默认拦截**`DROP TABLE` / `DROP COLUMN` / `ALTER COLUMN ... TYPE` /
`TRUNCATE`),退出 4,要显式放行:`OJ2_ALLOW_DESTRUCTIVE=1 docker/deploy.sh`
- **空库能自举**,直接从 `0000` 建起,新环境不需要先灌 schema dump。
迁移文件**不内嵌进二进制**,随镜像装在 `/usr/local/share/oj2/migrations`
(见 `runtime.ts``migrationsDir`、Dockerfile 里那两条 COPY)。这样 drizzle 的
`migrate()` 能原样用——它靠 `meta/_journal.json` 自动发现迁移,**新增迁移不用改任何
代码**。内嵌就得为每条迁移手写一行 import,那是迟早会漏的账。
**破坏性迁移默认拦截。**`DROP TABLE` / `DROP COLUMN` / `DROP SCHEMA` /
`ALTER COLUMN ... TYPE` / `TRUNCATE` 的迁移会让部署停在迁移这步并退出 4,
需要确认备份后显式放行:
```bash
OJ2_ALLOW_DESTRUCTIVE=1 docker/deploy.sh
```
`DROP INDEX` / `DROP CONSTRAINT` 不算——它们不掉数据,拦了只会让人习惯性带上放行开关。
**空库自举时这道闸不生效**:没有数据可丢,0002 那串 `DROP ... IF EXISTS` 全是空转,
拦下来只会逼每个新环境都带一次放行开关,把它训练成习惯动作。
**空库能自举了。** `oj2-api migrate` 指向一个空库时直接从 `0000` 建起:
```bash
DATABASE_URL=postgres://... oj2-api migrate
# 空库,从 0000 开始自举。
# 待执行 3 条迁移,开始。
# ✓ 0000_crazy_gateway
# ✓ 0001_add_submission_public_create_time_idx
# ✓ 0002_drop_django_leftovers
```
`0000_crazy_gateway.sql` 原本是 `drizzle-kit pull` 的产物、整份被 `/* */` 包着、可执行
语句 0 条,所以以前新库只能先手工 `psql -f docs/specs/schema.sql`。现在它的内容由那份
生产 dump 机械转换而来(去掉 psql 专有指令、去掉 7 张 Django 遗留表及其索引外键,
其余原样保留)。**实测**:空库自举出来的结构,和「灌 schema.sql + 打基线 + 跑迁移」
这条老路子跑出来的结构,`pg_dump --schema-only` 逐字节一致(734 行,零差异)。
改 0000 对生产库没有影响 —— migrator 只比 `created_at`、**从不校验 hash**
`pg-core/dialect.js` 里就一句 `Number(lastDbMigration.created_at) < migration.folderMillis`),
而生产库那行 `baseline-0000-faked` 早把它挡在门外了。
⚠️ **0000 的注释里不要出现 statement-breakpoint 那个分隔标记的字面量。**
`readMigrationFiles` 是纯文本切分,不管它在不在注释里,照切不误 —— 注释被从中间切开,
后半截当成 SQL 发出去,报的是 `syntax error at or near "。"` 这种和真实原因毫不相干的错。
**给一个已经存在的库做基线**drizzle 没有 `--fake-initial``migrate` 见到空的
`__drizzle_migrations`、库里却已经有表,会拒绝执行并 exit 3(裸跑 `drizzle-kit migrate`
的话则是从 `0000` 撞上已存在的表、整个事务回滚,**而且 exit 1 却一个错误都不打印**)。
对已有数据的库第一次跑之前,先手插一行把 `0000` 标记成已执行:
```sql
CREATE SCHEMA IF NOT EXISTS drizzle;
CREATE TABLE IF NOT EXISTS drizzle.__drizzle_migrations (
id SERIAL PRIMARY KEY, hash text NOT NULL, created_at bigint);
INSERT INTO drizzle.__drizzle_migrations (hash, created_at)
VALUES ('baseline-0000-faked', 1786070652521); -- = meta/_journal.json 里 0000 的 when
```
migrator 只比 `created_at`,不校验 hash,所以 hash 随便填。
**已知的三个坑**`meta/0000_snapshot.json``pull` 出来的,没法无损还原 Django 建的
schema,下面三处已经修过了,别让它们回潮):
- ~~**快照里的 Django 序列**~~:已随 `0002_drop_django_leftovers` 删表一并解决,
`tablesFilter` 也移除了。(历史原因:`tablesFilter` 只过滤表、不过滤它们的序列,
于是 `generate` 会吐出 5 条 `DROP SEQUENCE`。)
- **bigint 上限精度**`pull` 生成的 `maxValue: 9223372036854775807` 是 JS number 字面量,
round-trip 成 `...776000`,每次 generate 都会多出 10 条 `ALTER COLUMN ... SET MAXVALUE`
已改成字符串。
- **表达式索引的 opclass**`problem_tag_name_ci_unique` 在快照里带 `opclass`,但 drizzle
自己序列化不出来,导致每次都 drop + recreate。已从快照里去掉。
**还有一个写代码时要绕开的**
- **`.op()` 会吞掉索引方向**:真正的根因不是 `.desc()`,是 opclass。drizzle-kit 的
`CreatePgIndexConvertor` 里那个三元一旦走进 opclass 分支就回不到方向分支:
`${it.opclass ? ` ${it.opclass}` : it.asc ? "" : " DESC"}`。而 `drizzle-kit pull`
给**每一列**都挂了 `.op(...)`,所以本仓库里"写了 `.desc()` 却生成不出 DESC"每次都会重演。
**要方向就别写 `.op()`。** 不写没有任何代价——`int4_ops` / `timestamptz_ops` 本来就是
这些类型的默认 opclass,写了等于没写。实测(drizzle-kit 0.31.10,探针索引跑过 generate):
| schema.ts | 生成的 SQL |
|---|---|
| `.desc().nullsFirst().op("timestamptz_ops")` | `"create_time" timestamptz_ops` ← 方向丢了 |
| `.desc().nullsFirst()` | `"create_time" DESC NULLS FIRST` ✅ |
| `.desc()` | `"create_time" DESC NULLS LAST` ✅ |
所以**多列混合方向的索引可以正常 generate**,不必手写。
假 diff 的机制也要理解对:带 `.op()` 时快照记的是 `asc: false`SQL 建出来却是 ASC
**分歧在快照和真实库之间**,不在快照和 schema.ts 之间——所以再跑 generate 是干净的,
要等到下次 pull 才炸出来。这是当初难定位的原因。
### 迁移执行器是自己的,不是 drizzle 那个
`db/migrate.ts` 不调用 drizzle 的 `migrate()`,自己按 journal 逐条执行。换掉它是因为
`pg-core/dialect.js` 里那个实现有两条硬伤:
1. **所有待执行的迁移共用一个事务**,第 3 条失败会把第 1、2 条一起回滚。现在是**一条一个
事务**,语义和 Django `migrate` 一致,失败时也说得清库停在哪儿。
2. 正因为全在事务里,`CREATE INDEX CONCURRENTLY` 一律跑不了,没有开关。
记账行的写法和 drizzle 完全一致(`hash` = 整个文件的 sha256`created_at` = journal 的
`when`),而 migrator 只比 `created_at`、不校验 hash,所以两套执行器可以互换,不会看不懂
对方写的记录。
**`CREATE INDEX CONCURRENTLY` 现在能跑了。** 在迁移文件**第一行**写上标记:
```sql
-- oj2:no-transaction
CREATE INDEX CONCURRENTLY "xxx_idx" ON "submission" USING btree ("language");
```
这条迁移就走裸执行(简单查询协议,不包事务)。代价是**没有回滚**:中途失败时前面的语句
已经生效,而且 CONCURRENTLY 失败会在库里留下一个 INVALID 索引,要先
`DROP INDEX` 再重来(`select indexrelid::regclass from pg_index where not indisvalid`
能找出来)。所以**这种迁移一个文件只放一条语句**。
要不要用是另一回事:参考量级是 12.3 万行的部分索引,普通 `CREATE INDEX` 只锁 74ms
一般不用纠结,CONCURRENTLY 留给真扛不住锁写窗口的场合。
退出码:2 = 配置/文件问题,3 = 基线不对,4 = 撞上破坏性迁移,5 = 某条迁移执行失败。
`CREATE INDEX CONCURRENTLY` 怎么写、给已有库打基线的 SQL、`.op()` 会吞掉索引方向这类
drizzle-kit 的坑,全在 `docs/database.md`
## 部署
三套 compose 在 `docker/``dev`(本机)、`debian`(服务器)、`school`(机房)。
**机房那套没有 postgres,连的是服务器的库。** 两个站点共用一个数据库,
但各有各的 Redis 和判题沙箱 —— 所以上线那天**两边必须一起切**
**机房那套没有 postgres,连的是服务器的库。** 两个站点共用一个数据库,但各有各的 Redis
和判题沙箱 —— 所以涉及两边的变更要一起做
`compose.debian.yml` 有两种形态,靠 env 切换:
`compose.debian.yml` 靠 env 切形态:设 `DATA_DIR` / `DB_HOST` / `REDIS_HOST` 就是接现有的库
(线上就是这个),留空并加 `--profile local-data` 就是自带 postgres / redis。
- **只换前后端**(上线用这个):设 `DATA_DIR` / `DB_HOST` / `REDIS_HOST`
沿用旧栈已经在跑的 postgres 和 redis,只起 api / worker / web / judge。
- **自带数据**(本机、演练):不设那几个变量,起栈时加 `--profile local-data`
- **并行试跑**(上线前先挂 `oj2.xuyue.cc` 跑几天):在「只换前后端」基础上再加
`WEB_PORT`8080 被旧 backend 占着)和 `JUDGE_STATE_DIR`(两个判题机不能共用运行目录)。
这种形态下旧栈一个容器都不用停,正式切换退化成改一行 NPM 上游。
⚠️ **`DATA_DIR` 默认值 `../data` `OJ2/data`,不是部署目录的 `data/`。** 沿用旧数据却忘了
设它,会静默起一套空数据(空库、没测试点、图片 404),而且**不报错** —— 这是整个部署里
唯一会静默走歪的地方,`deploy.sh` 为它专门设了一道自检
⚠️ `DATA_DIR` 默认值 `../data`**`OJ2/data`**,不是部署目录的 `data/`
沿用旧数据却忘了设它,会静默起一套空数据(空库、没测试点、图片 404),
而且**不报错** —— 这是切换当天唯一会静默走歪的地方。
细节和演练结果都在 `docs/specs/phase5-cutover-runbook.md`
上线两条路(push 触发 CI / 手工 `docker/deploy.sh`)、部署后的验证清单、NPM 反代那两个
不能关的开关、备份恢复的两个坑,都在 `docs/deploy.md`
+3 -1
View File
@@ -5,6 +5,8 @@ export default defineConfig({
schema: "./src/db/schema.ts",
out: "./src/db",
dbCredentials: {
url: process.env.DATABASE_URL ?? "postgres://onlinejudge:onlinejudge@localhost:5433/onlinejudge",
url:
process.env.DATABASE_URL ??
"postgres://onlinejudge:onlinejudge@localhost:5433/onlinejudge",
},
})
+4 -1
View File
@@ -11,11 +11,13 @@
"worker": "bun src/main.ts worker",
"build": "bun build --compile --target=bun-linux-x64 src/main.ts --outfile ../../dist/oj2-api",
"seed:dev": "bun src/scripts/seed-dev.ts",
"recount": "bun --env-file=../../.env src/main.ts recount",
"typecheck": "tsc --noEmit",
"check:routes": "bun src/scripts/check-route-shadowing.ts",
"check:ast": "bun src/scripts/check-ast-targets.ts",
"db:pull": "drizzle-kit pull",
"db:generate": "drizzle-kit generate",
"db:migrate": "drizzle-kit migrate"
"db:migrate": "bun --env-file=../../.env src/main.ts migrate"
},
"dependencies": {
"@node-rs/jieba": "^2.0.2",
@@ -29,6 +31,7 @@
"postgres": "^3.4.9",
"sql.js": "^1.14.2",
"tree-sitter-c": "^0.24.1",
"tree-sitter-cpp": "^0.23.4",
"tree-sitter-python": "^0.25.0",
"web-tree-sitter": "^0.26.13",
"zod": "^4.4.3"
+14 -8
View File
@@ -1,3 +1,4 @@
import { ADMIN_ROLES, TEACHER_ROLES } from "@oj2/contract"
import type { Context, MiddlewareHandler } from "hono"
import { failure } from "../http"
@@ -50,23 +51,27 @@ function requireRole(
return async (c, next) => {
const session = await resolveSession(c)
if (!session.user) return denied(c, session.reason)
if (!allowed(session.user)) return failure(c, 403, "permission-denied", "权限不足")
if (!allowed(session.user))
return failure(c, 403, "permission-denied", "权限不足")
c.set("user", session.user)
await next()
}
}
const ADMIN_ROLES = ["Student Admin", "Teacher Admin", "Super Admin"]
const TEACHER_ROLES = ["Teacher Admin", "Super Admin"]
/** 旧 `@admin_role_required` */
export const requireAdmin = requireRole((user) => ADMIN_ROLES.includes(user.adminType))
export const requireAdmin = requireRole((user) =>
ADMIN_ROLES.includes(user.adminType),
)
/** 旧 `@teacher_admin_required` */
export const requireTeacher = requireRole((user) => TEACHER_ROLES.includes(user.adminType))
export const requireTeacher = requireRole((user) =>
TEACHER_ROLES.includes(user.adminType),
)
/** 旧 `@super_admin_required` */
export const requireSuperAdmin = requireRole((user) => user.adminType === "Super Admin")
export const requireSuperAdmin = requireRole(
(user) => user.adminType === "Super Admin",
)
/**
* 旧 `@problem_permission_required`:先要是管理员,再要 problem_permission 不为 None。
@@ -74,5 +79,6 @@ export const requireSuperAdmin = requireRole((user) => user.adminType === "Super
* created_by 过滤 —— 旧后端也是这么分工的,别把两件事混在一起。
*/
export const requireProblemPermission = requireRole(
(user) => ADMIN_ROLES.includes(user.adminType) && user.problemPermission !== "None",
(user) =>
ADMIN_ROLES.includes(user.adminType) && user.problemPermission !== "None",
)
+22 -2
View File
@@ -16,7 +16,11 @@ async function verifyDjangoPbkdf2(password: string, encoded: string) {
const iterations = Number(iterationsText)
const expected = Buffer.from(digestText, "base64")
if (!Number.isSafeInteger(iterations) || iterations <= 0 || expected.length === 0) {
if (
!Number.isSafeInteger(iterations) ||
iterations <= 0 ||
expected.length === 0
) {
return false
}
@@ -53,6 +57,22 @@ export async function verifyPassword(password: string, encoded: string) {
return { valid: false, needsUpgrade: false }
}
/**
* 参数是显式写死的,不用 Bun 的默认值(`m=65536, t=2, p=1`,即每次哈希占 64 MiB)。
* 取的是 OWASP 对 argon2id 的推荐下限 `m=19MiB, t=2, p=1`
*
* - 批量导入一个班要连算几十次哈希,64 MiB 那档单次 ~140ms,而 `oj-api` 的
* mem_limit 只有 512mdocker/compose.debian.yml),并发度被内存卡死。
* 19 MiB 这档单次 ~20ms,并发 4 路的峰值也才 76 MiB。
* - 参数是编码进哈希串本身的(`$argon2id$v=19$m=19456,t=2,p=1$...`),所以**存量
* 账号一个都不用迁移**Bun.password.verify 读串里的参数验,改这里只影响此后新写的哈希。
*/
const ARGON2_OPTIONS = {
algorithm: "argon2id",
memoryCost: 19456,
timeCost: 2,
} as const
/**
* 写密码的**唯一入口**。五个调用方都走这里:注册、管理员改密码、批量导入用户、
* 重置密码、登录时升级存量 pbkdf2。
@@ -68,5 +88,5 @@ export async function verifyPassword(password: string, encoded: string) {
* 账号;靠开关只能拦住将来,修不了已经发生的。
*/
export function hashPassword(password: string) {
return Bun.password.hash(password, { algorithm: "argon2id" })
return Bun.password.hash(password, ARGON2_OPTIONS)
}
+62
View File
@@ -0,0 +1,62 @@
import type { ChainableCommander } from "ioredis"
import { redis } from "../redis"
/**
* 「谁现在在线」。member = userIdscore = 最后一次活动的毫秒时间戳。
*
* 会话本身判定不了在线:`session:<token>` 的 TTL 是 7 天且每次请求都续期,
* 「有会话」只说明这人一周内来过。所以这里单独记一个活动时间戳 ——
* 写入一律搭在已有的 pipeline 上(登录、每个带鉴权的请求、WebSocket 巡检),
* 不多一趟往返。
*/
const PRESENCE_KEY = "online-users"
/**
* 多久没动就算离线。挂着页面不操作的人靠 sweepSessions 每 60 秒续一次
* (见 websocket.ts),窗口必须明显大于那个间隔,否则开着页面的学生会一闪一闪。
*/
const ONLINE_WINDOW_MS = 5 * 60 * 1000
/** 记一笔活动。传 pipeline 而不是自己发命令:调用点都在热路径上 */
export function markOnline(pipeline: ChainableCommander, userId: number) {
pipeline.zadd(PRESENCE_KEY, Date.now(), String(userId))
}
/**
* 当前在线的用户 id。
*
* 顺手把过期成员删掉 —— 这是唯一的清理时机(整个 key 不能设 TTL:ZADD 不会重置
* key 的 TTL,到期会把还在线的人一起抹掉)。读这张表的只有后台用户列表,
* 不清理最坏也就是攒下全站用户数量级的成员,远谈不上要单开一个定时任务。
*/
export async function onlineUserIds() {
const cutoff = Date.now() - ONLINE_WINDOW_MS
const results = await redis
.pipeline()
.zremrangebyscore(PRESENCE_KEY, "-inf", `(${cutoff}`)
.zrange(PRESENCE_KEY, "0", "-1")
.exec()
const members = (results?.[1]?.[1] ?? []) as string[]
return new Set(members.map(Number).filter(Number.isInteger))
}
/**
* 在线人数。前台榜单页要的就是这一个数 —— 不必像 onlineUserIds 那样把成员全拉回来,
* ZCOUNT 让 Redis 自己数(O(log N))。这里不顺手清过期成员:清理是写操作,
* 而这个端点是匿名可访问的。
*/
export async function onlineCount() {
return redis.zcount(PRESENCE_KEY, Date.now() - ONLINE_WINDOW_MS, "+inf")
}
/** 登出、被禁用、被踢下线:立刻从在线名单里摘掉,别等窗口自然过期 */
export async function clearOnline(userId: number) {
await redis.zrem(PRESENCE_KEY, String(userId))
}
/** 单个用户在不在线。列表页用上面那个,别在循环里调这个 */
export async function isUserOnline(userId: number) {
const score = await redis.zscore(PRESENCE_KEY, String(userId))
return score !== null && Number(score) >= Date.now() - ONLINE_WINDOW_MS
}
+135 -17
View File
@@ -1,14 +1,24 @@
import { randomBytes } from "node:crypto"
import {
toAdminType,
toProblemPermission,
type AdminType,
type ProblemPermission,
} from "@oj2/contract"
import { eq } from "drizzle-orm"
import type { Context } from "hono"
import { deleteCookie, getCookie, setCookie } from "hono/cookie"
import { config } from "../config"
import { db, schema } from "../db"
import { publishSessionRevoked, type SessionRevokedReason } from "../events"
import { clearOnline, markOnline } from "./presence"
import { redis } from "../redis"
const SESSION_PREFIX = "session:"
const USER_SESSIONS_PREFIX = "user-sessions:"
interface StoredSession {
userId: number
@@ -17,12 +27,17 @@ interface StoredSession {
contestPasswords: Record<string, string>
}
/**
* 会话里的用户。`adminType` / `problemPermission` 是**联合类型而不是 string** ——
* 全仓二十多处 `user.adminType === "Super Admin"` 靠它兜底,拼错一个字母就编译不过。
* 收窄发生在下面读库那一处,是整个后端唯一一个把裸字符串变成角色的地方。
*/
export interface AuthUser {
id: number
username: string
email: string | null
adminType: string
problemPermission: string
adminType: AdminType
problemPermission: ProblemPermission
isDisabled: boolean
className: string | null
}
@@ -31,6 +46,21 @@ function sessionKey(token: string) {
return `${SESSION_PREFIX}${token}`
}
/**
* 某个用户名下所有还活着的会话 token。
*
* 会话本体是 `session:<token>`,里面记着 userId —— 从 token 找人很快,从人找 token
* 却只能 SCAN 整个 Redis。改密码、重置密码、禁用账号这三件事都要求「把这个人所有
* 设备上的会话立刻作废」,所以额外维护这张反向索引。
*
* **它是索引,不是真相**:成员可能指向已经过期的 token(集合成员没有各自的 TTL),
* 吊销时按成员逐个 DEL 即可,删到不存在的 key 没有代价。集合自己跟着会话续期,
* 整个人不活动满一个 TTL 之后自然消失。
*/
function userSessionsKey(userId: number) {
return `${USER_SESSIONS_PREFIX}${userId}`
}
export async function createSession(
c: Context,
userId: number,
@@ -43,12 +73,20 @@ export async function createSession(
previousLogin,
contestPasswords: {},
}
await redis.set(
sessionKey(token),
JSON.stringify(value),
"EX",
config.sessionTtlSeconds,
)
// 三条写进一个 pipeline:一个班四十号人同时登录时,三趟往返和一趟的差别
// 全压在登录这一下上
const pipeline = redis
.pipeline()
.set(
sessionKey(token),
JSON.stringify(value),
"EX",
config.sessionTtlSeconds,
)
.sadd(userSessionsKey(userId), token)
.expire(userSessionsKey(userId), config.sessionTtlSeconds)
markOnline(pipeline, userId)
await pipeline.exec()
setCookie(c, config.sessionCookie, token, {
httpOnly: true,
sameSite: "Lax",
@@ -61,11 +99,50 @@ export async function createSession(
/** 返回被删掉的 token:调用方要拿它去广播会话吊销,好断掉同一浏览器里其他标签页的连接 */
export async function destroySession(c: Context) {
const token = getCookie(c, config.sessionCookie)
if (token) await redis.del(sessionKey(token))
if (token) {
// 先读出 userId 再删,否则反向索引里会留下一个永远清不掉的成员
const userId = await sessionUserId(token)
await redis.del(sessionKey(token))
if (userId !== null) {
await redis.srem(userSessionsKey(userId), token)
await clearOnline(userId)
}
}
deleteCookie(c, config.sessionCookie, { path: "/" })
return token ?? null
}
async function sessionUserId(token: string) {
const raw = await redis.get(sessionKey(token))
if (!raw) return null
try {
const value = JSON.parse(raw) as StoredSession
return Number.isInteger(value.userId) ? value.userId : null
} catch {
return null
}
}
/**
* 把一个用户所有设备上的会话真的删掉,并广播给还挂着的 WebSocket。
*
* 光广播是不够的:`publishSessionRevoked` 只断 WebSocketHTTP 请求照样能拿着
* 那张 cookie 继续用。改密码之后旧密码登出来的会话必须立刻失效,否则「改密码」
* 对已经被别人登着的账号毫无作用 —— 而学生密码是明文存着给老师查的,
* 改密码正是发现密码泄露之后唯一的补救手段。
*/
export async function revokeUserSessions(
userId: number,
reason: SessionRevokedReason,
) {
const tokens = await redis.smembers(userSessionsKey(userId))
if (tokens.length) await redis.del(...tokens.map(sessionKey))
await redis.del(userSessionsKey(userId))
await clearOnline(userId)
await publishSessionRevoked({ userId }, reason)
return tokens.length
}
function readCookie(request: Request, name: string) {
const header = request.headers.get("cookie")
if (!header) return undefined
@@ -84,7 +161,9 @@ export type SessionResult =
| { user: AuthUser; reason?: undefined }
| { user: null; reason: "anonymous" | "disabled" }
async function getUserByToken(token: string | undefined): Promise<SessionResult> {
async function getUserByToken(
token: string | undefined,
): Promise<SessionResult> {
if (!token) return { user: null, reason: "anonymous" }
const raw = await redis.get(sessionKey(token))
@@ -114,6 +193,7 @@ async function getUserByToken(token: string | undefined): Promise<SessionResult>
if (!user) {
await redis.del(sessionKey(token))
await redis.srem(userSessionsKey(session.userId), token)
return { user: null, reason: "anonymous" }
}
@@ -122,11 +202,28 @@ async function getUserByToken(token: string | undefined): Promise<SessionResult>
// 都返回 null 的话,中途被禁用的学生看到的是 401 login-required
// 前端据此弹登录框,登进去又被弹 —— 死循环,而且看不出发生了什么。
await redis.del(sessionKey(token))
await redis.srem(userSessionsKey(session.userId), token)
return { user: null, reason: "disabled" }
}
await redis.expire(sessionKey(token), config.sessionTtlSeconds)
return { user }
// 反向索引跟着会话一起续期,否则活跃用户的索引会先于会话到期,
// 之后再吊销就找不到这张会话了。两条走一次 pipeline —— 这是全后端最热的 Redis
// 路径,每个带鉴权的请求都要走一趟,形状和 touchSession 里那对保持一致
const renew = redis
.pipeline()
.expire(sessionKey(token), config.sessionTtlSeconds)
.expire(userSessionsKey(session.userId), config.sessionTtlSeconds)
// 在线状态就是搭在这条 pipeline 上记的,见 presence.ts
markOnline(renew, session.userId)
await renew.exec()
// 唯一的收窄点。库里是 text 列,认不出来的值降成最低权限,见 toAdminType 的注释。
return {
user: {
...user,
adminType: toAdminType(user.adminType),
problemPermission: toProblemPermission(user.problemPermission),
},
}
}
/** 要区分「未登录」和「已被禁用」的用这个 —— 目前只有鉴权中间件需要 */
@@ -154,13 +251,30 @@ export function readRequestSessionToken(request: Request) {
/**
* 会话还在就续期并返回 true,已登出或已过期返回 false。
*
* 用 EXPIRE 一条命令同时完成「判断存在」和「续期」,比 GET + EXPIRE 少一趟往返
* 续期这件事本身也是要的:HTTP 请求会走 getUserByToken 里的 redis.expire 续期,
* 用 EXPIRE 同时完成「判断存在」和「续期」,比 GET + EXPIRE 少一趟往返;两条 EXPIRE
* 走一次 pipeline,仍然只有一趟。
*
* 续期这件事本身是要的:HTTP 请求会走 getUserByToken 里的 redis.expire 续期,
* 而只开着页面挂 WebSocket 的人一次请求都不发,不该因此被算成不活跃踢下线。
*
* **反向索引必须跟着一起续。** 走到这里的正是那种一次 HTTP 请求都不发的连接,
* 它碰不到 getUserByToken 里那两条并排的 expire。只续会话不续索引的话,索引先到期、
* 会话却被巡检一直续着,之后改密码 / 禁用账号走 revokeUserSessions 就 SMEMBERS
* 不到这张 token —— WebSocket 那边还有 publishSessionRevoked 按 userId 兜底能断掉,
* 但 HTTP 一侧拿着那张 cookie 照用不误,而改密码要的恰恰是让 HTTP 立刻失效。
*/
export async function touchSession(token: string) {
export async function touchSession(token: string, userId: number) {
if (!token) return false
return (await redis.expire(sessionKey(token), config.sessionTtlSeconds)) === 1
const pipeline = redis
.pipeline()
.expire(sessionKey(token), config.sessionTtlSeconds)
.expire(userSessionsKey(userId), config.sessionTtlSeconds)
// 只挂着 WebSocket 不发请求的人,在线状态全靠这里(sweepSessions 每 60 秒一轮)
markOnline(pipeline, userId)
const results = await pipeline.exec()
// 索引那条的返回值不看:存量会话(反向索引上线之前签发的)本来就没有索引键,
// 续不到很正常,不能因此判定会话已死
return results?.[0]?.[1] === 1
}
async function getStoredSession(c: Context) {
@@ -178,7 +292,11 @@ async function getStoredSession(c: Context) {
}
}
export async function setContestPassword(c: Context, contestId: number, password: string) {
export async function setContestPassword(
c: Context,
contestId: number,
password: string,
) {
const session = await getStoredSession(c)
if (!session) return false
session.value.contestPasswords[String(contestId)] = password
+566
View File
@@ -0,0 +1,566 @@
import { and, eq, isNull } from "drizzle-orm"
import { touchSession } from "../auth/session"
import { db, schema } from "../db"
import { toAdminType } from "@oj2/contract"
import { TEACHER_ROLES } from "../routes/helpers"
import {
addRequest,
addTeacher,
closeRoom,
getRequest,
getRoom,
hasTeacherOnline,
listRequests,
normalizeCollabLanguage,
openRoom,
queueAheadOf,
removeRequest,
removeTeacher,
roomOf,
teacherSockets,
type CollabSocket,
type HelpRequest,
type Room,
} from "./state"
/**
* `type: "error"` 的 message **会被前端原样弹成 toast**store 的 case "error"
* → setNotice → CollabHost 的 message.info),所以这里一律写中文、写成学生看得懂的
* 话。协议层的校验错误(格式不对、题号不对)正常前端触发不到,但真触发了也得是
* 一句人话 —— 原来那几条是 "Invalid problemId" 这样的英文,直接糊在学生脸上。
*/
function isTeacher(ws: CollabSocket) {
return TEACHER_ROLES.includes(toAdminType(ws.data.adminType ?? ""))
}
/** 推给老师的列表条目。不含 socket,也不含任何代码内容 */
function serializeRequest(request: HelpRequest) {
return {
studentId: request.studentId,
studentName: request.studentName,
className: request.className,
problemId: request.problemId,
problemTitle: request.problemTitle,
createdAt: request.createdAt,
status: request.status,
teacherName: request.teacherName ?? null,
}
}
/**
* 把最新的排队位置推给每个还在等的学生。
*
* queueAhead 原来只在「建请求 / 重连 / 退回排队」这三处推过,前面的人被接走或被
* 取消之后不重算 —— 五个人排队、前四个都处理完了,第五个还一直显示「前面还有 4 人」。
*/
function broadcastQueuePositions() {
for (const request of listRequests()) {
if (request.status !== "pending") continue
sendHelpStatus(request.socket, "pending", {
queueAhead: queueAheadOf(request.studentId),
})
}
}
/**
* 队列变了:老师端收全量列表,排队中的学生各自收自己的新位置。
*
* 两件事捏在一起是因为它们永远同时发生 —— 拆成两个函数分别调,迟早会在某条
* 路径上漏掉一个。
*/
export function broadcastRequests() {
const payload = JSON.stringify({
type: "requests",
list: listRequests().map(serializeRequest),
})
for (const ws of teacherSockets()) ws.send(payload)
broadcastQueuePositions()
}
function sendHelpStatus(
ws: CollabSocket,
status: "pending" | "active" | "cancelled" | "no_teacher",
extra: Record<string, unknown> = {},
) {
ws.send(JSON.stringify({ type: "help_status", status, ...extra }))
}
export function handleCollabOpen(ws: CollabSocket) {
if (isTeacher(ws)) {
addTeacher(ws)
// 新上线的老师要立刻看到当前队列,不能等下一次变更
ws.send(
JSON.stringify({
type: "requests",
list: listRequests().map(serializeRequest),
}),
)
return
}
// 学生(重)连:如果这个账号名下已经有一条请求(掉线重连回来,或者干脆是
// 同账号第二个标签页),把它迁移到这条新连接上,并把当前状态补发回去 ——
// 前端 onConnected 时会先把本地状态清空等着这条补发,不发的话就永远卡在
// idle;不迁移 socket 归属的话,sendHelpStatus/accept 等后续推送会发到一条
// 已经不用的旧连接上,新连接(新标签页)什么都收不到
const request = getRequest(ws.data.userId)
if (!request) return
request.socket = ws
const room = getRoom(ws.data.userId)
if (room && room.studentSocket !== ws) {
// 协作中的学生换了一条连接。**不迁移房间,直接拆掉。**
//
// 原来这里是把 studentSocket 换成新连接就算完,转发确实转到新连接了,
// 但客户端接不住:前端每次连接建立都会把 room 清成 null(旧连接的状态
// 不该越过重连活下来),而这里只补发了 help_status,没补 room_open ——
// 于是学生页面显示「老师正在帮你」、编辑器却早就把 yCollab 摘了,
// 老师照常敲字、一个字也到不了对面。正是 handleCollabBinary 注释里说的
// 「看起来在协作、其实各看各的」,比老实断开更糟。
//
// 而补发 room_open 也修不好:Yjs 的文档状态跟着旧连接一起没了,新连接
// 只能新建 Y.Doc,再拿学生编辑器里的内容当种子插进去,就会和老师那份
// 已有内容合并成重复文本(两份 doc 的 item 身份不同,CRDT 不去重)。
// 续接一个 CRDT 会话不是哑转发层做得到的事。
//
// 所以退回排队,老师再点一次 —— 和老师掉线走的是同一条路子。学生的代码
// 一直在他自己的编辑器里,不受影响。
closeRoom(room.studentId)
room.studentSocket.data.roomOwnerId = undefined
room.teacherSocket.data.roomOwnerId = undefined
room.teacherSocket.send(
JSON.stringify({ type: "room_closed", reason: "peer_offline" }),
)
request.status = "pending"
request.teacherId = undefined
request.teacherName = undefined
broadcastRequests()
}
if (request.status === "pending") {
sendHelpStatus(ws, "pending", { queueAhead: queueAheadOf(ws.data.userId) })
} else if (request.status === "active") {
sendHelpStatus(ws, "active", { teacherName: request.teacherName ?? "" })
}
}
/** 老师从房间消失(掉线,或发送失败被判定为事实上不可达):请求退回排队,
* 学生不必重新点 —— 可能只是网络抖了一下 */
function requeueAfterTeacherGone(studentId: number) {
const request = getRequest(studentId)
if (request) {
request.status = "pending"
request.teacherId = undefined
request.teacherName = undefined
sendHelpStatus(request.socket, "pending", {
queueAhead: queueAheadOf(studentId),
})
}
}
export function handleCollabClose(ws: CollabSocket) {
if (isTeacher(ws)) removeTeacher(ws)
const room = roomOf(ws)
if (room) {
closeRoom(room.studentId)
room.studentSocket.data.roomOwnerId = undefined
room.teacherSocket.data.roomOwnerId = undefined
const peer =
ws === room.teacherSocket ? room.studentSocket : room.teacherSocket
peer.send(JSON.stringify({ type: "room_closed", reason: "peer_offline" }))
if (ws === room.teacherSocket) {
requeueAfterTeacherGone(room.studentId)
} else {
// 学生掉线:请求随人走
removeRequest(room.studentId)
}
} else if (!isTeacher(ws)) {
// 还在排队时关掉页面,请求也该消失 —— 但只能收自己这条。同一账号可能开了两个
// 标签页,另一个标签页可能已经把请求接成 active(甚至已经换了一拨新请求),
// 不加 socket 归属和状态检查,这里会把活跃房间的请求记录连根拔起
const request = getRequest(ws.data.userId)
if (request && request.socket === ws && request.status !== "active") {
removeRequest(ws.data.userId)
}
}
broadcastRequests()
}
export async function handleCollabMessage(ws: CollabSocket, raw: string) {
let message: {
type?: unknown
problemId?: unknown
studentId?: unknown
language?: unknown
reason?: unknown
timestamp?: unknown
}
try {
message = JSON.parse(raw) as typeof message
} catch {
ws.send(
JSON.stringify({
type: "error",
message: "消息格式不对,请刷新页面重试",
}),
)
return
}
// 心跳不查库,和 /ws/submissions 的处理一致
if (message.type === "ping") {
ws.send(JSON.stringify({ type: "pong", timestamp: message.timestamp }))
return
}
// 握手时校验过一次不算数 —— 这条连接能挂几个小时
if (!(await touchSession(ws.data.token, ws.data.userId))) {
ws.close(1008, "Session expired")
return
}
switch (message.type) {
case "help_request":
await handleHelpRequest(ws, message.problemId, message.language)
return
case "help_language":
handleHelpLanguage(ws, message.language)
return
case "help_cancel":
handleHelpCancel(ws)
return
case "accept":
await handleAccept(ws, message.studentId)
return
case "reject":
await handleReject(ws, message.studentId)
return
case "leave":
handleLeave(ws, message.reason)
return
default:
ws.send(
JSON.stringify({
type: "error",
message: "不认识的操作,请刷新页面重试",
}),
)
}
}
async function handleHelpRequest(
ws: CollabSocket,
problemId: unknown,
language: unknown,
) {
if (typeof problemId !== "string" || !problemId) {
ws.send(
JSON.stringify({ type: "error", message: "题号不对,请刷新页面重试" }),
)
return
}
if (isTeacher(ws)) {
ws.send(JSON.stringify({ type: "error", message: "教师不能发起求助" }))
return
}
if (!hasTeacherOnline()) {
sendHelpStatus(ws, "no_teacher")
return
}
// 只认非比赛题:contest_id 为空的那条。比赛题不提供求助
const [problem] = await db
.select({ title: schema.problem.title })
.from(schema.problem)
.where(
and(
eq(schema.problem.displayId, problemId),
isNull(schema.problem.contestId),
),
)
.limit(1)
if (!problem) {
ws.send(
JSON.stringify({ type: "error", message: "题目不存在或不支持求助" }),
)
return
}
const existing = getRequest(ws.data.userId)
// 已经在协作中就不重复登记,否则会把正在进行的房间挤掉
if (existing?.status === "active") return
const [student] = await db
.select({ className: schema.user.className })
.from(schema.user)
.where(eq(schema.user.id, ws.data.userId))
.limit(1)
addRequest({
studentId: ws.data.userId,
studentName: ws.data.username ?? "",
className: student?.className ?? null,
problemId,
problemTitle: problem.title,
language: normalizeCollabLanguage(language),
createdAt: Date.now(),
status: "pending",
socket: ws,
})
sendHelpStatus(ws, "pending", { queueAhead: queueAheadOf(ws.data.userId) })
broadcastRequests()
}
/**
* 学生在求助期间换了语言。
*
* 只更新语言,不动队列位置、不动房间 —— 换语言不该让他重新排队。已经在协作中的
* 话再推一条 room_language,老师端的高亮和补全立刻跟着换;不推的话老师会拿着
* 建房那一刻的语言,对着一套错的补全替学生写代码。
*/
function handleHelpLanguage(ws: CollabSocket, language: unknown) {
const request = getRequest(ws.data.userId)
// 比对 socket 归属:同账号的另一个标签页停在别的题上切语言,不该改这条求助
if (!request || request.socket !== ws) return
const next = normalizeCollabLanguage(language)
if (request.language === next) return
request.language = next
const room = getRoom(ws.data.userId)
if (!room) return
room.language = next
room.teacherSocket.send(
JSON.stringify({ type: "room_language", language: next }),
)
}
function handleHelpCancel(ws: CollabSocket) {
const request = getRequest(ws.data.userId)
// 不比对 socket 归属:取消的是这个学生自己的求助,不管从他哪个标签页发起都
// 合法——getRequest(ws.data.userId) 已经把范围锁在这一个用户上了,不是跨用户
// 操作。这里和 handleCollabClose 的排队分支不是同一类问题:那边关闭事件是
// 「顺带」触发的,必须认出是不是本人这条连接;这里是用户主动点了取消
if (!request || request.status === "active") return
removeRequest(ws.data.userId)
broadcastRequests()
}
async function handleAccept(ws: CollabSocket, studentId: unknown) {
if (!isTeacher(ws)) {
ws.send(JSON.stringify({ type: "error", message: "无权限" }))
return
}
if (typeof studentId !== "number") {
ws.send(
JSON.stringify({
type: "error",
message: "学生标识不对,请刷新页面重试",
}),
)
return
}
// 握手时的 adminType 是那一刻的快照,接单前按库里的真实身份复核一次。
// 注意读的是库,不是前端传的任何东西 —— 前端的演示模式在这里没有意义
const [teacher] = await db
.select({ adminType: schema.user.adminType })
.from(schema.user)
.where(
and(
eq(schema.user.id, ws.data.userId),
eq(schema.user.isDisabled, false),
),
)
.limit(1)
if (!teacher || !TEACHER_ROLES.includes(toAdminType(teacher.adminType))) {
ws.close(1008, "Permission revoked")
return
}
// 上面这次查询是个 await 点,等待期间这条连接可能已经断开——断线时
// handleCollabClose 已经把它从 teacherSockets 摘掉了,用它来判断这次 accept
// 还作不作数。continuation 里不能再对着一个死 socket 建房间
if (!teacherSockets().has(ws)) return
// 老师同时只能在一个房间
if (roomOf(ws)) {
ws.send(JSON.stringify({ type: "error", message: "请先结束当前协作" }))
return
}
const request = getRequest(studentId)
if (!request || request.status === "active" || getRoom(studentId)) {
// 被别人接走了、学生已经撤销,或者这个学生 id 名下已经有一个房间在挂着
// (正常路径走不到,是两个标签页 + 断线重连缝隙的最后一道闸)——
// 回一份最新列表让老师端自己纠正
ws.send(
JSON.stringify({
type: "requests",
list: listRequests().map(serializeRequest),
}),
)
return
}
request.status = "active"
request.teacherId = ws.data.userId
request.teacherName = ws.data.username ?? ""
ws.data.roomOwnerId = studentId
request.socket.data.roomOwnerId = studentId
openRoom({
studentId,
teacherId: ws.data.userId,
studentSocket: request.socket,
teacherSocket: ws,
problemId: request.problemId,
language: request.language,
})
const openFrame = (peerName: string, peerRole: "student" | "teacher") =>
JSON.stringify({
type: "room_open",
peer: { name: peerName, role: peerRole },
problemId: request.problemId,
language: request.language,
})
request.socket.send(openFrame(request.teacherName, "teacher"))
ws.send(openFrame(request.studentName, "student"))
sendHelpStatus(request.socket, "active", { teacherName: request.teacherName })
broadcastRequests()
}
async function handleReject(ws: CollabSocket, studentId: unknown) {
if (!isTeacher(ws) || typeof studentId !== "number") return
// reject 很少见,多这一次查询不心疼;不然握手快照挡不住"连接活着期间被降级
// 或禁用"的老师继续掐掉排队中的求助
const [teacher] = await db
.select({ adminType: schema.user.adminType })
.from(schema.user)
.where(
and(
eq(schema.user.id, ws.data.userId),
eq(schema.user.isDisabled, false),
),
)
.limit(1)
if (!teacher || !TEACHER_ROLES.includes(toAdminType(teacher.adminType))) {
ws.close(1008, "Permission revoked")
return
}
const request = getRequest(studentId)
// 已经在协作中的不能靠 reject 掐掉,那是 leave 的事
if (!request || request.status === "active") return
removeRequest(studentId)
sendHelpStatus(request.socket, "cancelled")
broadcastRequests()
}
/**
* 主动退出房间。**两种语义,靠 reason 分**
*
* - 不带 reason(或 `"done"`)—— 有人点了「结束协作」,这次帮忙到此结束,
* 求助记录一并清掉;
* - `"left"` —— 人只是离开了这道题的页面(教师端「页面即协作现场」,跳走就不在
* 房间里了)。**这跟他掉线是同一件事**,所以走同一条收尾:教师离开 → 求助退回
* 排队,学生不用重新举手,老师回来再点一次就接上;学生离开 → 求助随人清掉。
*
* 分开是因为两者对学生的意义完全不同:前者是「搞定了」,后者是「老师先走一下」,
* 而原来都按前者处理 —— 老师点一下「提交信息」,学生就得重新举手。
*/
function handleLeave(ws: CollabSocket, reason: unknown) {
const room = roomOf(ws)
if (!room) return
if (reason !== "left") {
teardownRoom(room, "done")
return
}
const side = ws === room.teacherSocket ? "teacher" : "student"
teardownRoom(room, "peer_left", side, ws)
}
/**
* 拆房间。reason 决定两端看到什么:
* done —— 有人主动结束,双方都收到,请求一并清除
* peer_offline —— 有人断线或发送失败被判定为不可达,见 handleCollabClose /
* handleCollabBinary
* peer_left —— 有人离开了这道题的页面(handleLeave 的 "left"
*
* offlineSide 是消失的那一方,决定请求的去向:老师消失 → 退回排队;学生消失 →
* 随人清掉。不传时只拆房间。
*
* initiator 是主动发起的那条连接:**他收到的 reason 不一样** —— 点了「结束协作」
* 是 `done`,离开页面是 `self_left`。对他来说这是「我自己干的」,不该看到一句
* 「对方离开了」,也不该看到「老师已结束这次帮忙」。
*/
function teardownRoom(
room: Room,
reason: "done" | "peer_offline" | "peer_left",
offlineSide?: "student" | "teacher",
initiator?: CollabSocket,
) {
closeRoom(room.studentId)
room.studentSocket.data.roomOwnerId = undefined
room.teacherSocket.data.roomOwnerId = undefined
// 发起方收到的是「我自己干的」那一版:点了结束就是 done,离开页面是 self_left。
// 不能跟对面收同一条 —— 学生自己切走了却看到「老师已结束这次帮忙」是假话
const selfReason = reason === "peer_left" ? "self_left" : "done"
for (const socket of [room.studentSocket, room.teacherSocket]) {
socket.send(
JSON.stringify({
type: "room_closed",
reason: socket === initiator ? selfReason : reason,
}),
)
}
if (reason === "done") {
removeRequest(room.studentId)
} else if (offlineSide === "teacher") {
requeueAfterTeacherGone(room.studentId)
} else if (offlineSide === "student") {
removeRequest(room.studentId)
}
broadcastRequests()
}
/**
* Yjs 的 update / awareness 帧。服务端不解析、不留存,只转发给房间里的另一个人。
*
* 「服务端不知道代码内容」是有意的:这个通道要做的事只有认证和分房间,
* 权限由 accept 时的库查询决定,与帧里装的是什么无关。
*/
export function handleCollabBinary(
ws: CollabSocket,
data: Buffer | Uint8Array,
) {
// 空帧:Bun.serve 探测过,send() 对 0 字节帧也回 0(同一个返回值,
// 真实送达和真实丢弃分不清),不转发、不参与下面的失败判定,直接忽略。
// 否则任何一方发一个 0 字节二进制帧就能把整间房拆掉
if (data.length === 0) return
const room = roomOf(ws)
if (!room) return
const peer =
ws === room.teacherSocket ? room.studentSocket : room.teacherSocket
const sent = peer.send(data)
// Bun.serve 探测过:-1 不代表失败,是背压——消息已排队,最终会送达(实测 8MB
// 帧照样完整到达);只有 0 才是真的丢了(对端事实上已经断开)。之前把 <= 0
// 当成失败,慢网/大粘贴一触发背压就把正常房间拆掉,是本该保护的场景反而先死
if (sent === 0) {
// 真丢帧:两边的 Yjs 文档会从此悄悄分叉——教学工具里"看起来在协作、其实
// 各看各的代码"比老实断开更糟,不做续传,直接拆房间。和教师断线走同一条
// 收尾路径:老师那侧消失就把请求退回排队,不让学生卡死在 active 出不来
console.error("Collab binary forward failed, tearing down room", {
studentId: room.studentId,
})
const offlineSide = peer === room.teacherSocket ? "teacher" : "student"
teardownRoom(room, "peer_offline", offlineSide)
}
}
+143
View File
@@ -0,0 +1,143 @@
/**
* 课堂求助的内存状态。
*
* 不落库是有意的:求助是课堂上的即时行为,学生关掉页面这条请求就该消失。
* 服务端只有一个 serve 进程(main.ts 单二进制 + 子命令,compose 里 oj-api 一个容器),
* 所以内存态够用,不需要 Redis 同步。进程重启丢掉全部状态,两端重连后回到干净状态。
*/
import { normalizeLanguage } from "@oj2/contract"
export type CollabSocket = Bun.ServerWebSocket<
import("../websocket").SubmissionSocketData
>
/**
* 协作支持的语言。和前端 utils/types.ts 里的 LANGUAGE 对齐,去掉 Flowchart ——
* 流程图题没有代码编辑器,求助入口本身就是隐藏的。
*/
export const COLLAB_LANGUAGES = [
"C",
"C++",
"Python",
"Java",
"JavaScript",
"Golang",
"SQL",
] as const
export type CollabLanguage = (typeof COLLAB_LANGUAGES)[number]
/**
* 认不出来的一律当 C:老客户端不带这个字段,而它以前就是写死 C 的。
*
* 先过契约的别名表 —— 上线那一刻学生页面里还揣着 `Python3`,不翻译的话会**静默**
* 落到 C,求助窗口里的代码高亮和同步编辑都按 C 走,没人会报错。
*/
export function normalizeCollabLanguage(value: unknown): CollabLanguage {
const normalized = normalizeLanguage(value) ?? value
return (COLLAB_LANGUAGES as readonly string[]).includes(normalized as string)
? (normalized as CollabLanguage)
: "C"
}
export interface HelpRequest {
studentId: number
studentName: string
className: string | null
/** 题目的展示号(problem._id 列,前端一路用的都是它),不是自增主键 */
problemId: string
problemTitle: string
/**
* 学生编辑器当前的语言。决定教师端弹框用哪套高亮和补全 —— 求助时带上,
* 协作期间学生切语言会用 help_language 更新这里
*/
language: CollabLanguage
createdAt: number
status: "pending" | "active"
teacherId?: number
teacherName?: string
socket: CollabSocket
}
/** 求助表,以学生为键 —— 一个学生同时只有一个求助 */
const requests = new Map<number, HelpRequest>()
/** 在线老师的连接。用于推列表,也用于判断 no_teacher */
const teachers = new Set<CollabSocket>()
export function addRequest(request: HelpRequest) {
requests.set(request.studentId, request)
}
export function getRequest(studentId: number) {
return requests.get(studentId)
}
export function removeRequest(studentId: number) {
return requests.delete(studentId)
}
/** 按发起时间正序。老师端按等待时长排序展示,不强制先来先到 */
export function listRequests() {
return Array.from(requests.values()).sort((a, b) => a.createdAt - b.createdAt)
}
/** 比自己早创建、且仍在排队的请求数 */
export function queueAheadOf(studentId: number) {
const self = requests.get(studentId)
if (!self) return 0
let ahead = 0
for (const request of requests.values()) {
if (request.status === "pending" && request.createdAt < self.createdAt)
ahead += 1
}
return ahead
}
export function addTeacher(ws: CollabSocket) {
teachers.add(ws)
}
export function removeTeacher(ws: CollabSocket) {
teachers.delete(ws)
}
export function hasTeacherOnline() {
return teachers.size > 0
}
export function teacherSockets() {
return teachers
}
export interface Room {
/** 房主 = 学生。房间以学生为键,因为学生的代码是内容源 */
studentId: number
teacherId: number
studentSocket: CollabSocket
teacherSocket: CollabSocket
problemId: string
/** 建房那一刻学生的语言,之后跟着 help_language 走 */
language: CollabLanguage
}
const rooms = new Map<number, Room>()
export function openRoom(room: Room) {
rooms.set(room.studentId, room)
}
export function getRoom(studentId: number) {
return rooms.get(studentId)
}
export function closeRoom(studentId: number) {
return rooms.delete(studentId)
}
/** 这条连接当前所在的房间。ws.data.roomOwnerId 是房主(学生)的 id */
export function roomOf(ws: CollabSocket) {
const ownerId = ws.data.roomOwnerId
return ownerId === undefined ? undefined : rooms.get(ownerId)
}
+22 -5
View File
@@ -25,7 +25,10 @@ function loadRepoRootEnv() {
if (eq <= 0) continue
const key = trimmed.slice(0, eq).trim()
if (process.env[key] !== undefined) continue
process.env[key] = trimmed.slice(eq + 1).trim().replace(/^["']|["']$/g, "")
process.env[key] = trimmed
.slice(eq + 1)
.trim()
.replace(/^["']|["']$/g, "")
}
} catch {
// 根目录没有 .env 是正常情况(例如生产用真实环境变量注入),静默跳过
@@ -64,18 +67,24 @@ export const config = {
port: Number(process.env.PORT ?? 3000),
redisUrl: process.env.REDIS_URL ?? "redis://localhost:6380",
sessionCookie: "oj2_session",
sessionTtlSeconds: Number(process.env.SESSION_TTL_SECONDS ?? 7 * 24 * 60 * 60),
sessionTtlSeconds: Number(
process.env.SESSION_TTL_SECONDS ?? 7 * 24 * 60 * 60,
),
secureCookies: process.env.COOKIE_SECURE === "true",
judgeServerUrl: process.env.JUDGE_SERVER_URL ?? "http://localhost:8081",
judgeServerToken: judgeServerToken(),
judgeConcurrency: Number(process.env.JUDGE_CONCURRENCY ?? 2),
avatarDirectory: repoPath(process.env.AVATAR_DIRECTORY ?? "data/avatar"),
// 判题沙箱把这个目录挂成只读的 /test_case,两边必须指同一处
testCaseDirectory: repoPath(process.env.TEST_CASE_DIRECTORY ?? "data/test_case"),
testCaseDirectory: repoPath(
process.env.TEST_CASE_DIRECTORY ?? "data/test_case",
),
uploadDirectory: repoPath(process.env.UPLOAD_DIRECTORY ?? "data/upload"),
// 一言数据集(hitokoto.cn 官方导出),和旧后端读同一份:容器里是 /data/hitokoto。
// 本机 dev 默认路径下没有这份数据,读不到就回落到内置的几条,不影响启动。
hitokotoDirectory: repoPath(process.env.HITOKOTO_DIRECTORY ?? "data/hitokoto"),
hitokotoDirectory: repoPath(
process.env.HITOKOTO_DIRECTORY ?? "data/hitokoto",
),
/**
* WebSocket 升级时额外放行的来源(逗号分隔的完整 origin,如 https://oj.example.com)。
* 同源本来就放行,只有前后端分处不同域名时才需要配。
@@ -87,8 +96,16 @@ export const config = {
uploadUriPrefix: process.env.UPLOAD_URI_PREFIX ?? "/public/upload",
avatarUriPrefix: process.env.AVATAR_URI_PREFIX ?? "/public/avatar",
aiBaseUrl: process.env.AI_BASE_URL ?? "https://api.deepseek.com",
/** 只用来写 ai_analysis.provider 这一列,换 provider 时和 AI_BASE_URL 一起改 */
aiProvider: process.env.AI_PROVIDER ?? "deepseek",
aiKey: process.env.AI_KEY ?? "",
aiModel: process.env.AI_MODEL ?? "deepseek-v4-flash",
aiModel: process.env.AI_MODEL ?? "deepseek-flash",
/**
* AI 提示走两段式(先诊断、再生成),见 services/hint-diagnosis.ts。**默认关**
* 2026-09-19 起 ai_hint 在攒单段式的基线数据,攒够之前别打开,否则两批数据混在一起没法比。
* 设成 "1" 打开。
*/
aiHintDiagnose: process.env.AI_HINT_DIAGNOSE === "1",
ruffPath: process.env.RUFF_PATH ?? "ruff",
clangFormatPath: process.env.CLANG_FORMAT_PATH ?? "clang-format",
}
@@ -0,0 +1,20 @@
-- 把公开提交列表的部分索引从 (create_time) 换成 (create_time, id)。
--
-- 为什么要加 id:列表分页改用「offset → 游标」两步查询(见 routes/submission.ts 的
-- paginateSubmissionRows)。create_time 由 `new Date().toISOString()` 生成,只有毫秒
-- 精度,同毫秒的两条提交分不出先后,游标回查时上一页末行会重复出现在下一页页首。
-- 加上 id 让排序变成全序,两步走同一个顺序,翻页结果精确。
--
-- 两列都是 ASC:查询 `ORDER BY create_time DESC, id DESC` 靠 Index Only Scan Backward
-- 反着扫这条索引。写成 (create_time DESC, id DESC) 反而用不上——ORDER BY 的 DESC 默认
-- NULLS FIRST,索引的 DESC 默认 NULLS LAST,规划器认为出不了序,会退化成全量排序。
--
-- 锁窗口:这里是普通 CREATE INDEX(不是 CONCURRENTLY),建索引期间**阻塞写入**。
-- 生产快照 12.3 万行 / 171MB 上实测不到 1 秒,且部署本来就在停机窗口里做,够用。
-- 真要热更再拆成两条带 `oj2:no-transaction` 的迁移。
--
-- 先 DROP 再 CREATE 是安全的:两条语句在同一个事务里(migrate.ts 一条迁移一个事务),
-- 中途失败会整体回滚,不会留下「老的没了、新的没建成」的中间态。
DROP INDEX "submission_public_create_time_idx";--> statement-breakpoint
CREATE INDEX "submission_public_create_time_id_idx" ON "submission" USING btree ("create_time","id") WHERE "submission"."contest_id" is null;
@@ -0,0 +1,13 @@
CREATE TABLE "tutorial_progress" (
"user_id" integer NOT NULL,
"tutorial_id" integer NOT NULL,
"view_count" integer DEFAULT 0 NOT NULL,
"total_seconds" integer DEFAULT 0 NOT NULL,
"first_viewed_at" timestamp with time zone NOT NULL,
"last_viewed_at" timestamp with time zone NOT NULL,
CONSTRAINT "tutorial_progress_pkey" PRIMARY KEY("user_id","tutorial_id")
);
--> statement-breakpoint
ALTER TABLE "tutorial_progress" ADD CONSTRAINT "tutorial_progress_user_id_fk_user_id" FOREIGN KEY ("user_id") REFERENCES "public"."user"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "tutorial_progress" ADD CONSTRAINT "tutorial_progress_tutorial_id_fk_tutorial_id" FOREIGN KEY ("tutorial_id") REFERENCES "public"."tutorial"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
CREATE INDEX "tutorial_progress_tutorial_id_idx" ON "tutorial_progress" USING btree ("tutorial_id");
@@ -0,0 +1,17 @@
CREATE TABLE "exercise_attempt" (
"user_id" integer NOT NULL,
"exercise_id" integer NOT NULL,
"attempts" integer DEFAULT 0 NOT NULL,
"wrong_attempts" integer DEFAULT 0 NOT NULL,
"solved" boolean DEFAULT false NOT NULL,
"attempts_to_solve" integer,
"last_wrong_answer" text,
"first_attempt_at" timestamp with time zone NOT NULL,
"last_attempt_at" timestamp with time zone NOT NULL,
"solved_at" timestamp with time zone,
CONSTRAINT "exercise_attempt_pkey" PRIMARY KEY("user_id","exercise_id")
);
--> statement-breakpoint
ALTER TABLE "exercise_attempt" ADD CONSTRAINT "exercise_attempt_user_id_fk_user_id" FOREIGN KEY ("user_id") REFERENCES "public"."user"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "exercise_attempt" ADD CONSTRAINT "exercise_attempt_exercise_id_fk_exercise_id" FOREIGN KEY ("exercise_id") REFERENCES "public"."exercise"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
CREATE INDEX "exercise_attempt_exercise_id_idx" ON "exercise_attempt" USING btree ("exercise_id");
@@ -0,0 +1,12 @@
-- 删掉比赛公告表。旧 Django 栈有「比赛公告」这个功能,OJ2 从头到尾没有搬:
-- 没有任何路由、契约或前端页面引用它,表建在那里纯粹是 introspect 0000 时一起拉进来的。
--
-- 已核实:
-- * 没有任何表外键引用 contest_announcement,它只有两条指向 contest / user 的出边,
-- 删掉是自洽的;
-- * 序列 contest_announcement_id_seq 由本表 owned,随 DROP TABLE 一并消失;
-- * 数据:生产快照(db_backup_2026_08_07)里只有 1 行,是 2022 年 4 月挂在 contest 1 上的
-- 一条测试公告(「四月月赛」)。OJ2 侧没有写入路径,这个数字不会再增长。
--
-- 不写 CASCADE,同 0002:万一将来真有别的东西引用了,宁可这里报错,也别被悄悄级联掉。
DROP TABLE IF EXISTS contest_announcement;
@@ -0,0 +1,14 @@
ALTER TABLE "submission" ADD COLUMN "problemset_id" bigint;--> statement-breakpoint
ALTER TABLE "submission" ADD CONSTRAINT "submission_problemset_id_fk_problemset_id" FOREIGN KEY ("problemset_id") REFERENCES "public"."problemset"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint
CREATE INDEX "submission_problemset_id_idx" ON "submission" USING btree ("problemset_id") WHERE "submission"."problemset_id" is not null;--> statement-breakpoint
-- 历史回填。老提交没有入口信息,唯一可考的是 problemset_submission:它记的是
-- 「这条提交让这道题在这个题单里算完成了」,本来就是刷题单刷出来的那一条,标出来不算冤枉。
-- 覆盖不到的是同一道题在此之前的 WA 和之后的重复 AC —— 那些只能留空,往后新提交才准。
-- 一条提交在多个题单里都记过账时(recordSolvedProblem 会记进所有已加入的题单),
-- 任取其一:来源入口只有一个,但事后已经分不出是哪个了。
UPDATE "submission" SET "problemset_id" = "ps"."problemset_id"
FROM (
SELECT DISTINCT ON ("submission_id") "submission_id", "problemset_id"
FROM "problemset_submission" ORDER BY "submission_id", "problemset_id"
) AS "ps"
WHERE "ps"."submission_id" = "submission"."id" AND "submission"."problemset_id" IS NULL;
+2
View File
@@ -0,0 +1,2 @@
ALTER TABLE "contest" DROP COLUMN "allowed_ip_ranges";--> statement-breakpoint
ALTER TABLE "submission" DROP COLUMN "ip";
@@ -0,0 +1,9 @@
ALTER TABLE "user" DROP COLUMN "auth_token";--> statement-breakpoint
ALTER TABLE "user" DROP COLUMN "open_api";--> statement-breakpoint
ALTER TABLE "user" DROP COLUMN "open_api_appkey";--> statement-breakpoint
ALTER TABLE "user" DROP COLUMN "session_keys";--> statement-breakpoint
ALTER TABLE "user_profile" DROP COLUMN "blog";--> statement-breakpoint
ALTER TABLE "user_profile" DROP COLUMN "github";--> statement-breakpoint
ALTER TABLE "user_profile" DROP COLUMN "school";--> statement-breakpoint
ALTER TABLE "user_profile" DROP COLUMN "major";--> statement-breakpoint
ALTER TABLE "user_profile" DROP COLUMN "language";
@@ -0,0 +1,51 @@
ALTER TABLE "exercise" DROP CONSTRAINT "exercise_tutorial_id_6fd04055_fk_tutorial_id";
--> statement-breakpoint
ALTER TABLE "flowchart_submission" DROP CONSTRAINT "flowchart_submission_problem_id_8551edbf_fk_problem_id";
--> statement-breakpoint
ALTER TABLE "message" DROP CONSTRAINT "message_submission_id_2fdf8a47_fk_submission_id";
--> statement-breakpoint
ALTER TABLE "problem_tags" DROP CONSTRAINT "problem_tags_problem_id_866ecb8d_fk_problem_id";
--> statement-breakpoint
ALTER TABLE "problem_tags" DROP CONSTRAINT "problem_tags_problemtag_id_72d20571_fk_problem_tag_id";
--> statement-breakpoint
ALTER TABLE "problemset_badge" DROP CONSTRAINT "problemset_badge_problemset_id_6cb6c74f_fk_problemset_id";
--> statement-breakpoint
ALTER TABLE "problemset_problem" DROP CONSTRAINT "problemset_problem_problem_id_fff2d686_fk_problem_id";
--> statement-breakpoint
ALTER TABLE "problemset_problem" DROP CONSTRAINT "problemset_problem_problemset_id_350d17fb_fk_problemset_id";
--> statement-breakpoint
ALTER TABLE "problemset_progress" DROP CONSTRAINT "problemset_progress_problemset_id_20a9632e_fk_problemset_id";
--> statement-breakpoint
ALTER TABLE "problemset_submission" DROP CONSTRAINT "problemset_submission_problem_id_5629b105_fk_problem_id";
--> statement-breakpoint
ALTER TABLE "problemset_submission" DROP CONSTRAINT "problemset_submission_problemset_id_85290e17_fk_problemset_id";
--> statement-breakpoint
ALTER TABLE "problemset_submission" DROP CONSTRAINT "problemset_submission_submission_id_78e2b807_fk_submission_id";
--> statement-breakpoint
ALTER TABLE "reaction" DROP CONSTRAINT "reaction_problem_id_a7f3b9f3_fk_problem_id";
--> statement-breakpoint
ALTER TABLE "user_achievement" DROP CONSTRAINT "user_achievement_achievement_id_29db600d_fk_achievement_id";
--> statement-breakpoint
ALTER TABLE "user_badge" DROP CONSTRAINT "user_badge_badge_id_92a983e9_fk_problemset_badge_id";
--> statement-breakpoint
ALTER TABLE "user_profile" DROP CONSTRAINT "user_profile_user_id_8fdce8e2_fk_user_id";
--> statement-breakpoint
ALTER TABLE "user_stat" DROP CONSTRAINT "user_stat_user_id_73337fc0_fk_user_id";
--> statement-breakpoint
ALTER TABLE "exercise" ADD CONSTRAINT "exercise_tutorial_id_6fd04055_fk_tutorial_id" FOREIGN KEY ("tutorial_id") REFERENCES "public"."tutorial"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "flowchart_submission" ADD CONSTRAINT "flowchart_submission_problem_id_8551edbf_fk_problem_id" FOREIGN KEY ("problem_id") REFERENCES "public"."problem"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "message" ADD CONSTRAINT "message_submission_id_2fdf8a47_fk_submission_id" FOREIGN KEY ("submission_id") REFERENCES "public"."submission"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "problem_tags" ADD CONSTRAINT "problem_tags_problem_id_866ecb8d_fk_problem_id" FOREIGN KEY ("problem_id") REFERENCES "public"."problem"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "problem_tags" ADD CONSTRAINT "problem_tags_problemtag_id_72d20571_fk_problem_tag_id" FOREIGN KEY ("problemtag_id") REFERENCES "public"."problem_tag"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "problemset_badge" ADD CONSTRAINT "problemset_badge_problemset_id_6cb6c74f_fk_problemset_id" FOREIGN KEY ("problemset_id") REFERENCES "public"."problemset"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "problemset_problem" ADD CONSTRAINT "problemset_problem_problem_id_fff2d686_fk_problem_id" FOREIGN KEY ("problem_id") REFERENCES "public"."problem"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "problemset_problem" ADD CONSTRAINT "problemset_problem_problemset_id_350d17fb_fk_problemset_id" FOREIGN KEY ("problemset_id") REFERENCES "public"."problemset"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "problemset_progress" ADD CONSTRAINT "problemset_progress_problemset_id_20a9632e_fk_problemset_id" FOREIGN KEY ("problemset_id") REFERENCES "public"."problemset"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "problemset_submission" ADD CONSTRAINT "problemset_submission_problem_id_5629b105_fk_problem_id" FOREIGN KEY ("problem_id") REFERENCES "public"."problem"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "problemset_submission" ADD CONSTRAINT "problemset_submission_problemset_id_85290e17_fk_problemset_id" FOREIGN KEY ("problemset_id") REFERENCES "public"."problemset"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "problemset_submission" ADD CONSTRAINT "problemset_submission_submission_id_78e2b807_fk_submission_id" FOREIGN KEY ("submission_id") REFERENCES "public"."submission"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "reaction" ADD CONSTRAINT "reaction_problem_id_a7f3b9f3_fk_problem_id" FOREIGN KEY ("problem_id") REFERENCES "public"."problem"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "user_achievement" ADD CONSTRAINT "user_achievement_achievement_id_29db600d_fk_achievement_id" FOREIGN KEY ("achievement_id") REFERENCES "public"."achievement"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "user_badge" ADD CONSTRAINT "user_badge_badge_id_92a983e9_fk_problemset_badge_id" FOREIGN KEY ("badge_id") REFERENCES "public"."problemset_badge"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "user_profile" ADD CONSTRAINT "user_profile_user_id_8fdce8e2_fk_user_id" FOREIGN KEY ("user_id") REFERENCES "public"."user"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "user_stat" ADD CONSTRAINT "user_stat_user_id_73337fc0_fk_user_id" FOREIGN KEY ("user_id") REFERENCES "public"."user"("id") ON DELETE cascade ON UPDATE no action;
@@ -0,0 +1,2 @@
CREATE INDEX "user_active_idx" ON "user" USING btree ("is_disabled","last_login" DESC NULLS FIRST);--> statement-breakpoint
CREATE INDEX "user_class_name_idx" ON "user" USING btree ("class_name");
@@ -0,0 +1,21 @@
DROP INDEX "acm_contest_rank_contest_id_21030ccd";--> statement-breakpoint
DROP INDEX "acm_contest_rank_user_id_40391ab2";--> statement-breakpoint
DROP INDEX "flowchart_submission_id_0dbfc4f9_like";--> statement-breakpoint
DROP INDEX "flowchart_submission_problem_id_8551edbf";--> statement-breakpoint
DROP INDEX "flowchart_submission_user_id_225c83e8";--> statement-breakpoint
DROP INDEX "message_recipient_id_2aa5dd76";--> statement-breakpoint
DROP INDEX "message_submission_id_2fdf8a47_like";--> statement-breakpoint
DROP INDEX "problem__id_919b1d80";--> statement-breakpoint
DROP INDEX "problem_contest_id_328e013a";--> statement-breakpoint
DROP INDEX "problem_tags_problem_id_866ecb8d";--> statement-breakpoint
DROP INDEX "problemset_problem_problemset_id_350d17fb";--> statement-breakpoint
DROP INDEX "problemset_progress_problemset_id_20a9632e";--> statement-breakpoint
DROP INDEX "problemset_submission_problemset_id_85290e17";--> statement-breakpoint
DROP INDEX "problemset_submission_submission_id_78e2b807_like";--> statement-breakpoint
DROP INDEX "problemset_submission_user_id_915fc9c6";--> statement-breakpoint
DROP INDEX "reaction_problem_id_a7f3b9f3";--> statement-breakpoint
DROP INDEX "submission_contest_id_775716d5";--> statement-breakpoint
DROP INDEX "submission_problem_id_76847b55";--> statement-breakpoint
DROP INDEX "submission_user_id_3779a8c1";--> statement-breakpoint
DROP INDEX "user_achievement_user_id_b8ec7d6a";--> statement-breakpoint
DROP INDEX "user_badge_user_id_a286d718";
@@ -0,0 +1,4 @@
CREATE INDEX "flowchart_create_time_idx" ON "flowchart_submission" USING btree ("create_time");--> statement-breakpoint
CREATE INDEX "submission_language_time_idx" ON "submission" USING btree ("language","create_time") WHERE "submission"."contest_id" is null;--> statement-breakpoint
CREATE INDEX "submission_result_time_idx" ON "submission" USING btree ("result","create_time") WHERE "submission"."contest_id" is null;--> statement-breakpoint
CREATE INDEX "submission_public_metrics_idx" ON "submission" USING btree ("user_id","problem_id","result","create_time") WHERE "submission"."contest_id" is null;
@@ -0,0 +1,25 @@
-- 补删 django_migrations。它本该被 0002_drop_django_leftovers 删掉,但生产库里还留着。
--
-- 2026-09-10 核实(生产库 oj-postgres):
-- * 库里 29 张 public 表 = schema.ts 的 28 张 + 这张 django_migrations
-- * 它 0 行,且 0002 里另外 6 张表(auth_group* / auth_permission /
-- django_content_type / django_dramatiq_task / django_session)确实都不在了;
-- * 全仓(二进制、路由、compose、脚本)零处读写它;
-- * 服务器上已无任何 Django 容器,只有 oj-api / oj-worker / oj-web。
--
-- 为什么 0002 没删干净,已无法从库里复原现场:0002 的记账行(created_at
-- 1787740469403)在,说明它当年是执行过的,而 DROP TABLE IF EXISTS 不会因为
-- 「表不存在」静默跳过之后的分号——这条迁移只有一个语句块。最可能是事后有人为了
-- 「给已有数据的库打基线」手工建了它(CLAUDE.md 里那段基线 SQL 建的是
-- drizzle.__drizzle_migrations,不是这张),或从旧 dump 单独恢复过它。
-- 来源不明不影响处置:空表 + 零引用,删掉没有任何数据损失。
--
-- 用 IF EXISTS 是为了**两种环境收敛到同一个结构**:空库自举时 0002 已经把它删了,
-- 生产库还留着。新环境跑到这一条是空转,生产库跑到这一条才真正动手,之后两边一致。
--
-- ⚠️ 这条会被部署的破坏性迁移闸拦下(migrate.ts 的 DESTRUCTIVE_PATTERNS)。
-- 那是**有意保留**的:DROP TABLE 该有人看一眼再放行,不值得为一张空表在闸门上开洞。
-- 放行前确认已备份,然后:
--
-- OJ2_ALLOW_DESTRUCTIVE=1 docker/deploy.sh
DROP TABLE IF EXISTS django_migrations;
@@ -0,0 +1,9 @@
-- 提交列表「题号」「用户名」两个筛选的索引,用法和实测数据见 schema.ts 里两条索引的注释。
--
-- pg_trgm 是 contrib 模块,要先装扩展,drizzle-kit generate 不会替你写这一句。
-- 官方 postgres:16-alpine 镜像自带 contrib,且 pg_trgm 是 trusted 扩展(PG 13 起),
-- 库 owner 就能装。换成不带 contrib 的 Postgres 时这里会失败、部署停在迁移这步。
-- CREATE EXTENSION 可以在事务里执行,不需要 no-transaction 标记。
CREATE EXTENSION IF NOT EXISTS pg_trgm;--> statement-breakpoint
CREATE INDEX "submission_public_problem_time_idx" ON "submission" USING btree ("problem_id","create_time","id") WHERE "submission"."contest_id" is null;--> statement-breakpoint
CREATE INDEX "submission_public_username_trgm_idx" ON "submission" USING gin ("username" gin_trgm_ops) WHERE "submission"."contest_id" is null;
@@ -0,0 +1,18 @@
-- 提交的编辑过程信号(AI 时代 OJ 设计的第 1 步:过程信号采集),字段含义见 schema.ts 的
-- submissionTrace 与契约的 submissionTraceSchema。纯建表,历史提交没有对应行,这是预期的。
CREATE TABLE "submission_trace" (
"submission_id" text PRIMARY KEY NOT NULL,
"active_ms" integer NOT NULL,
"since_open_ms" integer NOT NULL,
"typed_chars" integer NOT NULL,
"pasted_chars" integer NOT NULL,
"paste_count" integer NOT NULL,
"max_paste" integer NOT NULL,
"deleted_chars" integer NOT NULL,
"blur_count" integer NOT NULL,
"initial_len" integer NOT NULL,
"collab" boolean NOT NULL,
"since_prev_ms" bigint
);
--> statement-breakpoint
ALTER TABLE "submission_trace" ADD CONSTRAINT "submission_trace_submission_id_fk_submission_id" FOREIGN KEY ("submission_id") REFERENCES "public"."submission"("id") ON DELETE cascade ON UPDATE no action;
+17
View File
@@ -0,0 +1,17 @@
-- AI 提示的留痕与学生评价(AI 时代 OJ 设计 2a:先记录、不改行为),字段含义见 schema.ts 的 aiHint。
-- 纯建表。上线之前的提示从未落库,这张表从空开始。
CREATE TABLE "ai_hint" (
"id" bigint PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY (sequence name "ai_hint_id_seq" INCREMENT BY 1 MINVALUE 1 MAXVALUE 9223372036854775807 START WITH 1 CACHE 1),
"submission_id" text NOT NULL,
"model" text NOT NULL,
"prompt_version" integer NOT NULL,
"content" text NOT NULL,
"error" text,
"duration_ms" integer NOT NULL,
"helpful" boolean,
"feedback_time" timestamp with time zone,
"create_time" timestamp with time zone NOT NULL
);
--> statement-breakpoint
ALTER TABLE "ai_hint" ADD CONSTRAINT "ai_hint_submission_id_fk_submission_id" FOREIGN KEY ("submission_id") REFERENCES "public"."submission"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
CREATE INDEX "ai_hint_submission_id_idx" ON "ai_hint" USING btree ("submission_id");
@@ -0,0 +1,4 @@
-- AI 提示两段式的诊断结果(AI 时代 OJ 设计 2b),字段含义见 schema.ts 的 aiHint。
-- 两列都可空、不带默认值,加列只改目录不重写表。
ALTER TABLE "ai_hint" ADD COLUMN "diagnosis" jsonb;--> statement-breakpoint
ALTER TABLE "ai_hint" ADD COLUMN "diagnosis_error" text;
@@ -0,0 +1,77 @@
-- 语言值统一成 `Python`:库里原来有 `Python3`104527 条提交)和 `Python2`3 条,
-- 全是 2022 年的),界面上两个都显示成「Python」,内部却是两个值。判题沙箱早就只剩
-- 一个 Python 了,这里把落库的值也并成一个。
--
-- 语言名不是判题状态码那种「判题机也认得的编码」—— 它只是我们自己的键(语言配置是
-- 整个对象发给判题机的),所以可以改。但它确实是**落库的值**,改完再回滚到旧版后端,
-- 旧代码查 languageConfigs["Python"] 会查不到 → 所有 Python 提交变 SYSTEM_ERROR。
-- 为此后端保留了 Python2/Python3 → Python 的别名(见 judge/languages.ts),
-- 新旧代码读哪一种数据都不会炸。
--
-- 涉及的四张表是全量扫备份确认过的(submission / problem / user_stat /
-- options_sysoptions)。options_sysoptions 里那行 `languages` 是 Django 时代的判题
-- 配置,OJ2 只读 website_* 几个键,不碰它,所以这里**故意不动**。
-- ① 提交记录。12 万条里 8 成是 Python,走一次全表 UPDATE。
UPDATE "submission" SET "language" = 'Python'
WHERE "language" IN ('Python2', 'Python3');--> statement-breakpoint
-- ② 题目的可选语言。用 WITH ORDINALITY 保住原来的顺序 —— 题目页的语言下拉和默认
-- 选中项就是按这个数组的顺序来的,打乱了学生打开题目看到的默认语言会变。
UPDATE "problem" p SET "languages" = (
SELECT COALESCE(jsonb_agg(
CASE WHEN v IN ('Python2', 'Python3') THEN 'Python' ELSE v END ORDER BY ord
), '[]'::jsonb)
FROM jsonb_array_elements_text(p."languages") WITH ORDINALITY AS t(v, ord)
)
WHERE EXISTS (
SELECT 1 FROM jsonb_array_elements_text(p."languages") x(v)
WHERE x.v IN ('Python2', 'Python3')
);--> statement-breakpoint
-- ③ 预制代码,键是语言名(75 道题有 Python3 的模板)。
UPDATE "problem"
SET "template" = ("template" - 'Python3') || jsonb_build_object('Python', "template" -> 'Python3')
WHERE jsonb_exists("template", 'Python3');--> statement-breakpoint
-- ④ AST 代码规则,键就是语言名(15 道题)。
UPDATE "problem"
SET "ast_rules" = ("ast_rules" - 'Python3') || jsonb_build_object('Python', "ast_rules" -> 'Python3')
WHERE "ast_rules" IS NOT NULL AND jsonb_exists("ast_rules", 'Python3');--> statement-breakpoint
-- ⑤ 参考答案,形如 [{"language": "...", "code": "..."}]257 条 Python3 答案)。
UPDATE "problem" p SET "answers" = (
SELECT jsonb_agg(
CASE WHEN a ->> 'language' IN ('Python2', 'Python3')
THEN jsonb_set(a, '{language}', '"Python"')
ELSE a END ORDER BY ord
)
FROM jsonb_array_elements(p."answers") WITH ORDINALITY AS t(a, ord)
)
WHERE p."answers" IS NOT NULL AND jsonb_typeof(p."answers") = 'array' AND EXISTS (
SELECT 1 FROM jsonb_array_elements(p."answers") x(a)
WHERE x.a ->> 'language' IN ('Python2', 'Python3')
);--> statement-breakpoint
-- ⑥ 成就指标里的「用过哪些语言」(1235 个用户)。_languages 去重之后重算
-- languages_used —— 同时用过 Python2 和 Python3 的那 3 个用户,数字会从 n 掉到
-- n-1,这是**对的**:那本来就是同一种语言。已经发出去的成就不回收。
WITH mapped AS (
SELECT s."id", jsonb_agg(d.v ORDER BY d.ord) AS arr
FROM "user_stat" s, LATERAL (
SELECT DISTINCT ON (val) val AS v, ord FROM (
SELECT CASE WHEN e IN ('Python2', 'Python3') THEN 'Python' ELSE e END AS val, ord
FROM jsonb_array_elements_text(s."metrics" -> '_languages') WITH ORDINALITY AS t(e, ord)
) m ORDER BY val, ord
) d
WHERE jsonb_typeof(s."metrics" -> '_languages') = 'array' AND EXISTS (
SELECT 1 FROM jsonb_array_elements_text(s."metrics" -> '_languages') x(e)
WHERE x.e IN ('Python2', 'Python3')
)
GROUP BY s."id"
)
UPDATE "user_stat" s SET "metrics" = jsonb_set(
jsonb_set(s."metrics", '{_languages}', mapped.arr),
'{languages_used}', to_jsonb(jsonb_array_length(mapped.arr))
)
FROM mapped WHERE mapped."id" = s."id";
@@ -0,0 +1,41 @@
-- 把 Java / JavaScript / Golang 从题目的可选语言里摘掉。
--
-- 这三种语言的判题配置和判题镜像里的 JDK / Node / Go 已经一起删了(见
-- judge/languages.ts 和 docker/judge/)。但生产库里有 84 道题的 `languages` 还留着
-- 它们,而题目页的语言下拉就是按这个数组渲染的 —— 不摘掉的话,学生能在那 84 道题上
-- 选 Java 提交,判题时 languageConfigs 查不到就抛 Unsupported judge language
-- 结果是 SYSTEM_ERROR。**这道迁移是那次删语言的收尾,不能只删代码不清数据。**
--
-- 备份实测:84 道题受影响,其中**没有**任何一道只有这三种语言,所以不会有题目被清空。
-- 保险起见加了 jsonb_array_length > 0 的条件:真要出现这种题,宁可留着不动、让它
-- 在后台显形,也不要把语言清空(题目页会渲染出一个空的语言下拉)。
--
-- 历史提交里那 62 条 Java/JS/Golang 记录**不动**,语言名留在契约里就是为了渲染它们。
UPDATE "problem" p SET "languages" = (
SELECT jsonb_agg(v ORDER BY ord)
FROM jsonb_array_elements_text(p."languages") WITH ORDINALITY AS t(v, ord)
WHERE v NOT IN ('Java', 'JavaScript', 'Golang')
)
WHERE EXISTS (
SELECT 1 FROM jsonb_array_elements_text(p."languages") x(v)
WHERE x.v IN ('Java', 'JavaScript', 'Golang')
) AND (
SELECT count(*) FROM jsonb_array_elements_text(p."languages") y(v)
WHERE y.v NOT IN ('Java', 'JavaScript', 'Golang')
) > 0;--> statement-breakpoint
-- 预制代码和参考答案里对应的条目一并清掉(生产库里是空的,防后台以后写进去)。
UPDATE "problem"
SET "template" = "template" - 'Java' - 'JavaScript' - 'Golang'
WHERE jsonb_exists_any("template", ARRAY['Java', 'JavaScript', 'Golang']);--> statement-breakpoint
UPDATE "problem" p SET "answers" = (
SELECT COALESCE(jsonb_agg(a ORDER BY ord), '[]'::jsonb)
FROM jsonb_array_elements(p."answers") WITH ORDINALITY AS t(a, ord)
WHERE a ->> 'language' NOT IN ('Java', 'JavaScript', 'Golang')
)
WHERE p."answers" IS NOT NULL AND jsonb_typeof(p."answers") = 'array' AND EXISTS (
SELECT 1 FROM jsonb_array_elements(p."answers") x(a)
WHERE x.a ->> 'language' IN ('Java', 'JavaScript', 'Golang')
);
+26 -1
View File
@@ -3,9 +3,34 @@ import postgres from "postgres"
import * as schema from "./schema"
const url = process.env.DATABASE_URL ?? "postgres://onlinejudge:onlinejudge@localhost:5433/onlinejudge"
const url =
process.env.DATABASE_URL ??
"postgres://onlinejudge:onlinejudge@localhost:5433/onlinejudge"
// 不设会话时区:日历语义的 SQL 一律显式 `at time zone``../time` 的 localTime),
// 不靠会话默认值兜底 —— 兜底会把漏写的地方在线上掩盖掉,dev 上又是另一个答案。
const client = postgres(url)
export const db = drizzle(client, { schema })
/**
* 读出来的时刻统一成 ISO 8601 UTC,和写侧的 `new Date().toISOString()` 同形状。
*
* drizzle 的 `construct()``drizzle-orm/postgres-js/driver.js`)把 1184(timestamptz) 等
* OID 的 parser 换成了恒等函数,不处理的话读出来是 PG 文本(`2026-09-14 20:00:00+08`),
* 接口上同一个字段就有两种形状。所以**必须在 `drizzle(client)` 之后**覆盖回来。
*
* - **只换 1184。** 1082(date) 要的就是 `2026-09-14`;全库时间列都是 timestamptz。
* - **`::text` 的 OID 是 25,绕过这里**:别再为了拿字符串形状给时间列加 `::text`。
* - **保留微秒。** `Date` 只到毫秒,而 Django 时代的提交几乎全带微秒;读出的时刻常被
* 原样塞回查询条件(提交列表翻页的分界行、班级 AC 排名的 `<= min(create_time)`),
* 截掉会让分界行把自己排除。所以偏移换算交给 `Date`(先去掉小数,免得进位),
* 小数位原文拼回去、至少补足 3 位。Bun、老 Chrome 和 date-fns 都能解析 6 位小数。
*/
client.options.parsers[1184] = (value: string) => {
const fraction = /\.\d+/.exec(value)?.[0]
if (!fraction) return new Date(value).toISOString()
return `${new Date(value.replace(fraction, "")).toISOString().slice(0, 19)}${fraction.padEnd(4, "0")}Z`
}
export { schema }
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+126
View File
@@ -22,6 +22,132 @@
"when": 1787740469403,
"tag": "0002_drop_django_leftovers",
"breakpoints": true
},
{
"idx": 3,
"version": "7",
"when": 1787850608174,
"tag": "0003_submission_public_create_time_id_idx",
"breakpoints": true
},
{
"idx": 4,
"version": "7",
"when": 1788271411343,
"tag": "0004_add_tutorial_progress",
"breakpoints": true
},
{
"idx": 5,
"version": "7",
"when": 1788272667927,
"tag": "0005_add_exercise_attempt",
"breakpoints": true
},
{
"idx": 6,
"version": "7",
"when": 1788402925980,
"tag": "0006_drop_contest_announcement",
"breakpoints": true
},
{
"idx": 7,
"version": "7",
"when": 1788408053304,
"tag": "0007_add_submission_problemset_id",
"breakpoints": true
},
{
"idx": 8,
"version": "7",
"when": 1788409130862,
"tag": "0008_drop_ip_columns",
"breakpoints": true
},
{
"idx": 9,
"version": "7",
"when": 1788409690565,
"tag": "0009_drop_django_dead_columns",
"breakpoints": true
},
{
"idx": 10,
"version": "7",
"when": 1788409961010,
"tag": "0010_fk_cascade_on_delete",
"breakpoints": true
},
{
"idx": 11,
"version": "7",
"when": 1788788493497,
"tag": "0011_user_lookup_indexes",
"breakpoints": true
},
{
"idx": 12,
"version": "7",
"when": 1788869393805,
"tag": "0012_drop_redundant_indexes",
"breakpoints": true
},
{
"idx": 13,
"version": "7",
"when": 1788913334948,
"tag": "0013_add_filter_and_metrics_indexes",
"breakpoints": true
},
{
"idx": 14,
"version": "7",
"when": 1789034426259,
"tag": "0014_drop_django_migrations",
"breakpoints": true
},
{
"idx": 15,
"version": "7",
"when": 1789364546358,
"tag": "0015_submission_filter_indexes",
"breakpoints": true
},
{
"idx": 16,
"version": "7",
"when": 1789817209482,
"tag": "0016_add_submission_trace",
"breakpoints": true
},
{
"idx": 17,
"version": "7",
"when": 1789818766735,
"tag": "0017_add_ai_hint",
"breakpoints": true
},
{
"idx": 18,
"version": "7",
"when": 1789822227451,
"tag": "0018_ai_hint_diagnosis",
"breakpoints": true
},
{
"idx": 19,
"version": "7",
"when": 1789906464541,
"tag": "0019_unify_python_language",
"breakpoints": true
},
{
"idx": 20,
"version": "7",
"when": 1789906612433,
"tag": "0020_drop_unsupported_languages",
"breakpoints": true
}
]
}
+20 -6
View File
@@ -57,7 +57,9 @@ export async function runMigrations() {
process.exit(2)
}
if (files.length === 0) {
console.error(`${migrationsDir} 下没找到任何迁移。镜像里的迁移目录是不是漏拷了?`)
console.error(
`${migrationsDir} 下没找到任何迁移。镜像里的迁移目录是不是漏拷了?`,
)
process.exit(2)
}
@@ -136,10 +138,16 @@ export async function runMigrations() {
// 自举时不拦:空库上没有数据可丢,0002 那串 DROP ... IF EXISTS 全是空转。
// 拦下来只会逼着每个新环境都带一次 OJ2_ALLOW_DESTRUCTIVE,把这道闸训练成习惯动作 ——
// 那正是它想避免的事。
if (blocked.length > 0 && !bootstrapping && process.env.OJ2_ALLOW_DESTRUCTIVE !== "1") {
if (
blocked.length > 0 &&
!bootstrapping &&
process.env.OJ2_ALLOW_DESTRUCTIVE !== "1"
) {
console.error(
"待执行的迁移里有破坏性语句,已停下:\n" +
blocked.map(({ tag, reasons }) => ` · ${tag}${reasons.join(" / ")}`).join("\n") +
blocked
.map(({ tag, reasons }) => ` · ${tag}${reasons.join(" / ")}`)
.join("\n") +
"\n\n这类改动不可逆,不该在一次日常部署里顺手执行。" +
"\n确认已经做过备份之后,用这个显式放行:\n\n" +
" OJ2_ALLOW_DESTRUCTIVE=1 docker/deploy.sh\n",
@@ -180,7 +188,9 @@ export async function runMigrations() {
function destructiveReasons(sql: string) {
const bare = stripComments(sql)
return DESTRUCTIVE_PATTERNS.filter(([re]) => re.test(bare)).map(([, label]) => label)
return DESTRUCTIVE_PATTERNS.filter(([re]) => re.test(bare)).map(
([, label]) => label,
)
}
/**
@@ -192,7 +202,9 @@ function destructiveReasons(sql: string) {
*/
function readMigrationTags(): Map<number, string> {
try {
const journal = JSON.parse(readFileSync(`${migrationsDir}/meta/_journal.json`, "utf8")) as {
const journal = JSON.parse(
readFileSync(`${migrationsDir}/meta/_journal.json`, "utf8"),
) as {
entries?: Array<{ when: number; tag: string }>
}
return new Map((journal.entries ?? []).map((e) => [e.when, e.tag]))
@@ -234,7 +246,9 @@ async function applyMigration(
) {
// 只留有可执行内容的段。`readMigrationFiles` 按 `--> statement-breakpoint` 切开后
// 保留原文,所以纯注释段(比如 0002 开头那一大段说明)会自成一段。
const statements = migration.sql.filter((stmt) => stripComments(stmt).trim() !== "")
const statements = migration.sql.filter(
(stmt) => stripComments(stmt).trim() !== "",
)
if (statements.length === 0) {
// 上游已经拦过一次(那条兜底检查),走到这里说明拦漏了,宁可响一声也别静默跳过
throw new Error(`${tag} 没有任何可执行语句`)
-273
View File
@@ -1,273 +0,0 @@
import { relations } from "drizzle-orm/relations";
import { user, aiAnalysis, announcement, contest, contestAnnouncement, problem, flowchartSubmission, message, submission, tutorial, exercise, problemset, problemsetProblem, problemsetProgress, problemsetSubmission, reaction, problemTags, problemTag, userStat, achievement, userAchievement, problemsetBadge, userBadge, userProfile, acmContestRank } from "./schema";
export const aiAnalysisRelations = relations(aiAnalysis, ({one}) => ({
user: one(user, {
fields: [aiAnalysis.userId],
references: [user.id]
}),
}));
export const userRelations = relations(user, ({many}) => ({
aiAnalyses: many(aiAnalysis),
announcements: many(announcement),
contests: many(contest),
contestAnnouncements: many(contestAnnouncement),
flowchartSubmissions: many(flowchartSubmission),
messages_recipientId: many(message, {
relationName: "message_recipientId_user_id"
}),
messages_senderId: many(message, {
relationName: "message_senderId_user_id"
}),
problemsets: many(problemset),
problemsetProgresses: many(problemsetProgress),
problemsetSubmissions: many(problemsetSubmission),
reactions: many(reaction),
problems: many(problem),
tutorials: many(tutorial),
userStats: many(userStat),
userAchievements: many(userAchievement),
userBadges: many(userBadge),
userProfiles: many(userProfile),
acmContestRanks: many(acmContestRank),
}));
export const announcementRelations = relations(announcement, ({one}) => ({
user: one(user, {
fields: [announcement.createdById],
references: [user.id]
}),
}));
export const contestRelations = relations(contest, ({one, many}) => ({
user: one(user, {
fields: [contest.createdById],
references: [user.id]
}),
contestAnnouncements: many(contestAnnouncement),
problems: many(problem),
submissions: many(submission),
acmContestRanks: many(acmContestRank),
}));
export const contestAnnouncementRelations = relations(contestAnnouncement, ({one}) => ({
contest: one(contest, {
fields: [contestAnnouncement.contestId],
references: [contest.id]
}),
user: one(user, {
fields: [contestAnnouncement.createdById],
references: [user.id]
}),
}));
export const flowchartSubmissionRelations = relations(flowchartSubmission, ({one}) => ({
problem: one(problem, {
fields: [flowchartSubmission.problemId],
references: [problem.id]
}),
user: one(user, {
fields: [flowchartSubmission.userId],
references: [user.id]
}),
}));
export const problemRelations = relations(problem, ({one, many}) => ({
flowchartSubmissions: many(flowchartSubmission),
problemsetProblems: many(problemsetProblem),
problemsetSubmissions: many(problemsetSubmission),
reactions: many(reaction),
contest: one(contest, {
fields: [problem.contestId],
references: [contest.id]
}),
user: one(user, {
fields: [problem.createdById],
references: [user.id]
}),
problemTags: many(problemTags),
submissions: many(submission),
}));
export const messageRelations = relations(message, ({one}) => ({
user_recipientId: one(user, {
fields: [message.recipientId],
references: [user.id],
relationName: "message_recipientId_user_id"
}),
user_senderId: one(user, {
fields: [message.senderId],
references: [user.id],
relationName: "message_senderId_user_id"
}),
submission: one(submission, {
fields: [message.submissionId],
references: [submission.id]
}),
}));
export const submissionRelations = relations(submission, ({one, many}) => ({
messages: many(message),
problemsetSubmissions: many(problemsetSubmission),
contest: one(contest, {
fields: [submission.contestId],
references: [contest.id]
}),
problem: one(problem, {
fields: [submission.problemId],
references: [problem.id]
}),
}));
export const exerciseRelations = relations(exercise, ({one}) => ({
tutorial: one(tutorial, {
fields: [exercise.tutorialId],
references: [tutorial.id]
}),
}));
export const tutorialRelations = relations(tutorial, ({one, many}) => ({
exercises: many(exercise),
user: one(user, {
fields: [tutorial.createdById],
references: [user.id]
}),
}));
export const problemsetRelations = relations(problemset, ({one, many}) => ({
user: one(user, {
fields: [problemset.createdById],
references: [user.id]
}),
problemsetProblems: many(problemsetProblem),
problemsetProgresses: many(problemsetProgress),
problemsetSubmissions: many(problemsetSubmission),
problemsetBadges: many(problemsetBadge),
}));
export const problemsetProblemRelations = relations(problemsetProblem, ({one}) => ({
problem: one(problem, {
fields: [problemsetProblem.problemId],
references: [problem.id]
}),
problemset: one(problemset, {
fields: [problemsetProblem.problemsetId],
references: [problemset.id]
}),
}));
export const problemsetProgressRelations = relations(problemsetProgress, ({one}) => ({
problemset: one(problemset, {
fields: [problemsetProgress.problemsetId],
references: [problemset.id]
}),
user: one(user, {
fields: [problemsetProgress.userId],
references: [user.id]
}),
}));
export const problemsetSubmissionRelations = relations(problemsetSubmission, ({one}) => ({
problem: one(problem, {
fields: [problemsetSubmission.problemId],
references: [problem.id]
}),
problemset: one(problemset, {
fields: [problemsetSubmission.problemsetId],
references: [problemset.id]
}),
submission: one(submission, {
fields: [problemsetSubmission.submissionId],
references: [submission.id]
}),
user: one(user, {
fields: [problemsetSubmission.userId],
references: [user.id]
}),
}));
export const reactionRelations = relations(reaction, ({one}) => ({
problem: one(problem, {
fields: [reaction.problemId],
references: [problem.id]
}),
user: one(user, {
fields: [reaction.userId],
references: [user.id]
}),
}));
export const problemTagsRelations = relations(problemTags, ({one}) => ({
problem: one(problem, {
fields: [problemTags.problemId],
references: [problem.id]
}),
problemTag: one(problemTag, {
fields: [problemTags.problemtagId],
references: [problemTag.id]
}),
}));
export const problemTagRelations = relations(problemTag, ({many}) => ({
problemTags: many(problemTags),
}));
export const userStatRelations = relations(userStat, ({one}) => ({
user: one(user, {
fields: [userStat.userId],
references: [user.id]
}),
}));
export const userAchievementRelations = relations(userAchievement, ({one}) => ({
achievement: one(achievement, {
fields: [userAchievement.achievementId],
references: [achievement.id]
}),
user: one(user, {
fields: [userAchievement.userId],
references: [user.id]
}),
}));
export const achievementRelations = relations(achievement, ({many}) => ({
userAchievements: many(userAchievement),
}));
export const userBadgeRelations = relations(userBadge, ({one}) => ({
problemsetBadge: one(problemsetBadge, {
fields: [userBadge.badgeId],
references: [problemsetBadge.id]
}),
user: one(user, {
fields: [userBadge.userId],
references: [user.id]
}),
}));
export const problemsetBadgeRelations = relations(problemsetBadge, ({one, many}) => ({
userBadges: many(userBadge),
problemset: one(problemset, {
fields: [problemsetBadge.problemsetId],
references: [problemset.id]
}),
}));
export const userProfileRelations = relations(userProfile, ({one}) => ({
user: one(user, {
fields: [userProfile.userId],
references: [user.id]
}),
}));
export const acmContestRankRelations = relations(acmContestRank, ({one}) => ({
contest: one(contest, {
fields: [acmContestRank.contestId],
references: [contest.id]
}),
user: one(user, {
fields: [acmContestRank.userId],
references: [user.id]
}),
}));
+1411 -627
View File
File diff suppressed because it is too large Load Diff
+31 -12
View File
@@ -1,4 +1,4 @@
import { flowchartUpdateSchema, type FlowchartUpdate } from "@oj2/contract"
import type { FlowchartUpdate } from "@oj2/contract"
import { redis } from "./redis"
@@ -13,7 +13,10 @@ export const configUpdateChannel = "config:updates"
export const configTopic = "events:config"
export async function publishConfigUpdate(key: string, value: unknown) {
await redis.publish(configUpdateChannel, JSON.stringify({ type: "config_update", key, value }))
await redis.publish(
configUpdateChannel,
JSON.stringify({ type: "config_update", key, value }),
)
}
/**
@@ -39,14 +42,19 @@ export async function publishSessionRevoked(
target: { token: string } | { userId: number },
reason: SessionRevokedReason,
) {
await redis.publish(sessionRevokedChannel, JSON.stringify({ ...target, reason }))
await redis.publish(
sessionRevokedChannel,
JSON.stringify({ ...target, reason }),
)
}
export function parseSessionRevoked(raw: string): SessionRevoked | null {
try {
const value = JSON.parse(raw) as SessionRevoked
if (typeof value.token !== "string" && !Number.isInteger(value.userId)) return null
if (value.reason !== "session-ended" && value.reason !== "account-disabled") return null
if (typeof value.token !== "string" && !Number.isInteger(value.userId))
return null
if (value.reason !== "session-ended" && value.reason !== "account-disabled")
return null
return value
} catch {
return null
@@ -71,8 +79,11 @@ export function userEventTopic(userId: number) {
return `events:user:${userId}`
}
export async function publishFlowchartUpdate(userId: number, data: FlowchartUpdate) {
await redis.publish(userEventChannel, JSON.stringify({ userId, data: flowchartUpdateSchema.parse(data) }))
export async function publishFlowchartUpdate(
userId: number,
data: FlowchartUpdate,
) {
await redis.publish(userEventChannel, JSON.stringify({ userId, data }))
}
export async function publishAchievementNotification(
@@ -80,16 +91,24 @@ export async function publishAchievementNotification(
achievements: AchievementNotification[],
) {
if (!achievements.length) return
await redis.publish(userEventChannel, JSON.stringify({
userId,
data: { type: "achievement_unlocked", achievements },
}))
await redis.publish(
userEventChannel,
JSON.stringify({
userId,
data: { type: "achievement_unlocked", achievements },
}),
)
}
export function parseUserEvent(raw: string): UserEvent | null {
try {
const value = JSON.parse(raw) as UserEvent
if (!Number.isInteger(value.userId) || !value.data || typeof value.data !== "object") return null
if (
!Number.isInteger(value.userId) ||
!value.data ||
typeof value.data !== "object"
)
return null
return value
} catch {
return null
+76 -32
View File
@@ -1,4 +1,4 @@
import { flowchartUpdateSchema } from "@oj2/contract"
import type { FlowchartUpdate } from "@oj2/contract"
import { eq } from "drizzle-orm"
import { db, schema } from "../db"
@@ -15,47 +15,83 @@ function evaluationPrompt(problem: typeof schema.problem.$inferSelect) {
${problem.title}\n${problem.description.slice(0, 2000)}`
}
/**
* grade
* 88 S
* A/S
*/
function gradeForScore(score: number) {
if (score >= 90) return "S"
if (score >= 80) return "A"
if (score >= 70) return "B"
return "C"
}
function parseEvaluation(value: string) {
const block = value.match(/```(?:json)?\s*([\s\S]*?)```/)?.[1]
const json = block ?? value.match(/\{[\s\S]*\}/)?.[0]
if (!json) throw new Error("AI response did not contain JSON")
const data = JSON.parse(json) as Record<string, unknown>
if (typeof data.score !== "number" || typeof data.grade !== "string") throw new Error("AI response is missing score or grade")
if (typeof data.score !== "number" || Number.isNaN(data.score))
throw new Error("AI response is missing score")
const score = Math.max(0, Math.min(100, data.score))
return {
score: Math.max(0, Math.min(100, data.score)),
grade: data.grade,
score,
grade: gradeForScore(score),
feedback: typeof data.feedback === "string" ? data.feedback : "",
suggestions: typeof data.suggestions === "string" ? data.suggestions : "",
criteria: data.criteria_details && typeof data.criteria_details === "object" ? data.criteria_details : {},
criteria:
data.criteria_details && typeof data.criteria_details === "object"
? data.criteria_details
: {},
}
}
export async function evaluateFlowchart(job: FlowchartJobData) {
const [row] = await db.select({ flowchart: schema.flowchartSubmission, problem: schema.problem }).from(schema.flowchartSubmission)
.innerJoin(schema.problem, eq(schema.flowchartSubmission.problemId, schema.problem.id))
.where(eq(schema.flowchartSubmission.id, job.submissionId)).limit(1)
export async function evaluateFlowchart(
job: FlowchartJobData,
{ isFinalAttempt = true }: { isFinalAttempt?: boolean } = {},
) {
const [row] = await db
.select({ flowchart: schema.flowchartSubmission, problem: schema.problem })
.from(schema.flowchartSubmission)
.innerJoin(
schema.problem,
eq(schema.flowchartSubmission.problemId, schema.problem.id),
)
.where(eq(schema.flowchartSubmission.id, job.submissionId))
.limit(1)
if (!row || ![0, 1].includes(row.flowchart.status)) return
await db.update(schema.flowchartSubmission).set({ status: 1 }).where(eq(schema.flowchartSubmission.id, row.flowchart.id))
await db
.update(schema.flowchartSubmission)
.set({ status: 1 })
.where(eq(schema.flowchartSubmission.id, row.flowchart.id))
const started = performance.now()
try {
const reference = row.problem.mermaidCode ? `\n标准答案参考:\n${row.problem.mermaidCode}` : "\n此题没有标准流程图。"
const result = parseEvaluation(await completeChat(
evaluationPrompt(row.problem),
`学生流程图:\n${row.flowchart.mermaidCode}${reference}\n设计提示:${row.problem.flowchartHint ?? "无"}`,
))
await db.update(schema.flowchartSubmission).set({
status: 2,
aiScore: result.score,
aiGrade: result.grade,
aiFeedback: result.feedback,
aiSuggestions: result.suggestions,
aiCriteriaDetails: result.criteria,
aiProvider: "deepseek",
aiModel: process.env.AI_MODEL ?? "deepseek-v4-flash",
processingTime: (performance.now() - started) / 1000,
evaluationTime: new Date().toISOString(),
}).where(eq(schema.flowchartSubmission.id, row.flowchart.id))
await publishFlowchartUpdate(row.flowchart.userId, flowchartUpdateSchema.parse({
const reference = row.problem.mermaidCode
? `\n标准答案参考:\n${row.problem.mermaidCode}`
: "\n此题没有标准流程图。"
const result = parseEvaluation(
await completeChat(
evaluationPrompt(row.problem),
`学生流程图:\n${row.flowchart.mermaidCode}${reference}\n设计提示:${row.problem.flowchartHint ?? "无"}`,
),
)
await db
.update(schema.flowchartSubmission)
.set({
status: 2,
aiScore: result.score,
aiGrade: result.grade,
aiFeedback: result.feedback,
aiSuggestions: result.suggestions,
aiCriteriaDetails: result.criteria,
aiProvider: "deepseek",
aiModel: process.env.AI_MODEL ?? "deepseek-flash",
processingTime: (performance.now() - started) / 1000,
evaluationTime: new Date().toISOString(),
})
.where(eq(schema.flowchartSubmission.id, row.flowchart.id))
await publishFlowchartUpdate(row.flowchart.userId, {
type: "flowchart_evaluation_completed",
submissionId: row.flowchart.id,
score: result.score,
@@ -63,17 +99,25 @@ export async function evaluateFlowchart(job: FlowchartJobData) {
feedback: result.feedback,
suggestions: result.suggestions,
criteriaDetails: result.criteria,
}))
} satisfies FlowchartUpdate)
} catch (error) {
// 原来这里把 error.message 原样推给学生、前端还直接 message.error 弹出来 ——
// AI provider 的地址、内部报错就这么进了浏览器。真实原因留在服务端日志里,
// 学生只需要知道「失败了,再试一次」;error 字段留空,前端有兜底文案。
console.error(`Failed to evaluate flowchart ${row.flowchart.id}`, error)
await db.update(schema.flowchartSubmission).set({ status: 3 }).where(eq(schema.flowchartSubmission.id, row.flowchart.id))
await publishFlowchartUpdate(row.flowchart.userId, flowchartUpdateSchema.parse({
// 只有最后一次尝试才落 FAILED。中间几次必须把状态留在 PROCESSING(1)
// 上面那道 `![0, 1].includes(status)` 的守卫会把状态为 3 的任务直接放行返回,
// 一旦提前写成 3,队列配的 attempts: 3 就成了摆设 —— 后两次尝试进来什么都不做
// 就算成功,AI 侧的偶发失败(限流、超时、网络抖动)永远等不到重试。
if (!isFinalAttempt) throw error
await db
.update(schema.flowchartSubmission)
.set({ status: 3 })
.where(eq(schema.flowchartSubmission.id, row.flowchart.id))
await publishFlowchartUpdate(row.flowchart.userId, {
type: "flowchart_evaluation_failed",
submissionId: row.flowchart.id,
}))
} satisfies FlowchartUpdate)
throw error
}
}
+89 -62
View File
@@ -44,16 +44,16 @@ app.route("/api", judgeServerRoutes)
app.route("/api/admin", adminRoutes)
app.onError((error, c) => {
console.error(error)
return c.json(
{ error: { code: "internal-error", message: "Internal server error" } },
500,
)
console.error(error)
return c.json(
{ error: { code: "internal-error", message: "Internal server error" } },
500,
)
})
/** 头像取不到时的占位图,避免每个没设头像的学生都打一次 404 */
const DEFAULT_AVATAR_SVG =
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128"><rect width="128" height="128" rx="64" fill="#e2e8f0"/><circle cx="64" cy="48" r="24" fill="#94a3b8"/><path d="M20 120c4-28 22-42 44-42s40 14 44 42" fill="#94a3b8"/></svg>'
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128"><rect width="128" height="128" rx="64" fill="#e2e8f0"/><circle cx="64" cy="48" r="24" fill="#94a3b8"/><path d="M20 120c4-28 22-42 44-42s40 14 44 42" fill="#94a3b8"/></svg>'
/**
* /public
@@ -64,65 +64,92 @@ const DEFAULT_AVATAR_SVG =
* Caddy /public/* Caddy
* Vite
*/
async function serveUpload(pathname: string, prefix: string, directory: string) {
const decoded = decodeURIComponent(pathname)
const filename = basename(decoded)
if (!filename || filename !== decoded.slice(prefix.length + 1)) {
return new Response("Not found", { status: 404 })
}
const file = Bun.file(resolve(directory, filename))
if (await file.exists()) {
// 文件名由后端生成且内容不变,可以放心长缓存
return new Response(file, { headers: { "cache-control": "public, max-age=86400" } })
}
return null
async function serveUpload(
pathname: string,
prefix: string,
directory: string,
) {
const decoded = decodeURIComponent(pathname)
const filename = basename(decoded)
if (!filename || filename !== decoded.slice(prefix.length + 1)) {
return new Response("Not found", { status: 404 })
}
const file = Bun.file(resolve(directory, filename))
if (await file.exists()) {
// 文件名由后端生成且内容不变,可以放心长缓存
return new Response(file, {
headers: { "cache-control": "public, max-age=86400" },
})
}
return null
}
const server = Bun.serve<SubmissionSocketData>({
port: config.port,
async fetch(request, bunServer) {
const url = new URL(request.url)
if (url.pathname.startsWith(`${config.avatarUriPrefix}/`)) {
const hit = await serveUpload(url.pathname, config.avatarUriPrefix, config.avatarDirectory)
if (hit) return hit
if (basename(decodeURIComponent(url.pathname)) === "default.png") {
return new Response(DEFAULT_AVATAR_SVG, {
headers: { "content-type": "image/svg+xml", "cache-control": "public, max-age=3600" },
})
}
return new Response("Not found", { status: 404 })
}
// 题面里插的图片。原来没有这一段 —— 后台上传成功、返回 /public/upload/xxx
// 但没有任何路由伺服它,题面图片一律 404。
if (url.pathname.startsWith(`${config.uploadUriPrefix}/`)) {
return (
(await serveUpload(url.pathname, config.uploadUriPrefix, config.uploadDirectory)) ??
new Response("Not found", { status: 404 })
)
}
if (url.pathname === "/ws/submissions" || url.pathname === "/ws/config") {
if (!isAllowedWebSocketOrigin(request.headers.get("origin"), url)) {
return new Response("Forbidden", { status: 403 })
}
const user = await getRequestSessionUser(request)
if (!user) return new Response("Unauthorized", { status: 401 })
const kind = url.pathname === "/ws/config" ? "config" : "submissions"
if (
bunServer.upgrade(request, {
data: {
userId: user.id,
kind,
token: readRequestSessionToken(request),
},
})
) {
return undefined
}
return new Response("WebSocket upgrade failed", { status: 400 })
}
return app.fetch(request)
},
websocket: submissionWebSocketHandler(),
port: config.port,
async fetch(request, bunServer) {
const url = new URL(request.url)
if (url.pathname.startsWith(`${config.avatarUriPrefix}/`)) {
const hit = await serveUpload(
url.pathname,
config.avatarUriPrefix,
config.avatarDirectory,
)
if (hit) return hit
if (basename(decodeURIComponent(url.pathname)) === "default.png") {
return new Response(DEFAULT_AVATAR_SVG, {
headers: {
"content-type": "image/svg+xml",
"cache-control": "public, max-age=3600",
},
})
}
return new Response("Not found", { status: 404 })
}
// 题面里插的图片。原来没有这一段 —— 后台上传成功、返回 /public/upload/xxx
// 但没有任何路由伺服它,题面图片一律 404。
if (url.pathname.startsWith(`${config.uploadUriPrefix}/`)) {
return (
(await serveUpload(
url.pathname,
config.uploadUriPrefix,
config.uploadDirectory,
)) ?? new Response("Not found", { status: 404 })
)
}
if (
url.pathname === "/ws/submissions" ||
url.pathname === "/ws/config" ||
url.pathname === "/ws/collab"
) {
if (!isAllowedWebSocketOrigin(request.headers.get("origin"), url)) {
return new Response("Forbidden", { status: 403 })
}
const user = await getRequestSessionUser(request)
if (!user) return new Response("Unauthorized", { status: 401 })
const kind =
url.pathname === "/ws/config"
? "config"
: url.pathname === "/ws/collab"
? "collab"
: "submissions"
if (
bunServer.upgrade(request, {
data: {
userId: user.id,
kind,
token: readRequestSessionToken(request),
username: user.username,
adminType: user.adminType,
},
})
) {
return undefined
}
return new Response("WebSocket upgrade failed", { status: 400 })
}
return app.fetch(request)
},
websocket: submissionWebSocketHandler(),
})
await bridgeSubmissionEvents(server)
+154 -81
View File
@@ -1,14 +1,22 @@
import {
AST_NODE_TARGETS_BY_LANGUAGE,
AST_OPERATOR_TARGETS_BY_LANGUAGE,
astNodeLabel,
astOperatorLabel,
astRuleIsMeaningful,
astTargetNodeType,
astRuleSchema,
AST_NODE_TARGET_LABELS,
AST_SUPPORTED_LANGUAGES,
type AstRequirement,
type AstRequirements,
type AstRule,
type AstRules,
} from "@oj2/contract"
import { Language, Parser, type Node } from "web-tree-sitter"
// 语法 wasm 内嵌成资源。原来是 `Bun.resolveSync(pkg + "/" + name, import.meta.dir)`
// 编译成单二进制后 import.meta.dir 是 /$bunfs/root,解析不到 node_modules。见 vendor/jieba.ts
import cWasmPath from "tree-sitter-c/tree-sitter-c.wasm" with { type: "file" }
import cppWasmPath from "tree-sitter-cpp/tree-sitter-cpp.wasm" with { type: "file" }
import pythonWasmPath from "tree-sitter-python/tree-sitter-python.wasm" with { type: "file" }
// web-tree-sitter 自己的运行时 wasmParser.init() 要用
import treeSitterWasmPath from "web-tree-sitter/web-tree-sitter.wasm" with { type: "file" }
@@ -20,66 +28,31 @@ export type { AstRule } from "@oj2/contract"
export interface AstResult {
description: string
passed: boolean
}
const mappings: Record<string, Record<string, string>> = {
C: {
for_loop: "for_statement",
while_loop: "while_statement",
do_while: "do_statement",
if_statement: "if_statement",
else_clause: "else_clause",
break: "break_statement",
continue: "continue_statement",
function_definition: "function_definition",
return: "return_statement",
switch_statement: "switch_statement",
case_statement: "case_statement",
assignment: "assignment_expression",
struct: "struct_specifier",
include: "preproc_include",
and: "&&",
or: "||",
not: "!",
},
Python3: {
for_loop: "for_statement",
while_loop: "while_statement",
if_statement: "if_statement",
else_clause: "else_clause",
elif_clause: "elif_clause",
break: "break_statement",
continue: "continue_statement",
function_definition: "function_definition",
return: "return_statement",
try_except: "try_statement",
with_statement: "with_statement",
list_comprehension: "list_comprehension",
list_literal: "list",
dict_literal: "dictionary",
set_literal: "set",
f_string: "format_string",
import: "import_statement",
import_from: "import_from_statement",
assignment: "assignment",
class_definition: "class_definition",
},
/** count_* 引擎实际数到的次数。失败时前端拿它补一句「当前 N 次」 */
actual?: number
}
let initPromise: Promise<void> | undefined
const languages = new Map<string, Language>()
async function loadLanguage(language: string) {
if (!(language in mappings)) return null
if (!AST_SUPPORTED_LANGUAGES.includes(language)) return null
// locateFile 指到内嵌的 tree-sitter.wasmemscripten 默认按脚本所在目录找,
// 单二进制里那个目录是 /$bunfs/root,它自己找不着
if (!initPromise) initPromise = Parser.init({ locateFile: () => treeSitterWasmPath })
if (!initPromise)
initPromise = Parser.init({ locateFile: () => treeSitterWasmPath })
await initPromise
const cached = languages.get(language)
if (cached) return cached
const loaded = await Language.load(language === "C" ? cWasmPath : pythonWasmPath)
const wasmPath =
language === "C"
? cWasmPath
: language === "C++"
? cppWasmPath
: pythonWasmPath
const loaded = await Language.load(wasmPath)
languages.set(language, loaded)
return loaded
}
@@ -95,9 +68,9 @@ function hasNode(root: Node, type: string): boolean {
return root.children.some((child) => hasNode(child, type))
}
function targetName(rule: AstRule) {
function targetName(rule: AstRule, language?: string) {
const target = rule.target ?? ""
return rule.label || AST_NODE_TARGET_LABELS[target] || target || "指定语法"
return rule.label || astNodeLabel(target, language) || "指定语法"
}
function countPhrase(verb: string, rule: AstRule) {
@@ -114,9 +87,9 @@ function countPhrase(verb: string, rule: AstRule) {
* ProblemContent.vue
* min/max
*/
export function describeAstRule(rule: AstRule): string {
export function describeAstRule(rule: AstRule, language?: string): string {
if (rule.message) return rule.message
const name = targetName(rule)
const name = targetName(rule, language)
const target = rule.target ?? ""
switch (rule.engine) {
case "must_exist_node":
@@ -136,10 +109,12 @@ export function describeAstRule(rule: AstRule): string {
case "must_not_call_method":
return `不能调用 .${target}()`
case "must_use_operator":
return `必须使用 ${target} 运算符`
return `必须使用 ${astOperatorLabel(target, language)} 运算符`
case "must_have_nesting": {
const outer = rule.outer ?? ""
const inner = rule.inner ?? ""
// 这两个走 astNodeLabel 而不是裸值 —— 少了这一步文案就是
// 「必须使用 for_loop 嵌套」,旧栈 ast_checker/engines/nesting.py 是翻的
const outer = astNodeLabel(rule.outer ?? "", language)
const inner = astNodeLabel(rule.inner ?? "", language)
return outer === inner
? `必须使用 ${outer} 嵌套`
: `必须在 ${outer} 中嵌套使用 ${inner}`
@@ -157,28 +132,100 @@ function requirementKind(engine: AstRule["engine"]): AstRequirement["kind"] {
/**
* engine / target
* 3 ast_rules
*
* C++
* 使 for loadLanguage C++ null
* checkAst
*/
export function astRequirements(value: unknown): AstRequirements | null {
const grouped = value && typeof value === "object" && !Array.isArray(value)
? (value as Record<string, unknown>)
: null
const grouped =
value && typeof value === "object" && !Array.isArray(value)
? (value as Record<string, unknown>)
: null
if (!grouped) return null
const out: AstRequirements = {}
for (const [language, rules] of Object.entries(grouped)) {
if (!Array.isArray(rules)) continue
if (!AST_SUPPORTED_LANGUAGES.includes(language)) continue
const items = rules.flatMap((rule) => {
const parsed = astRuleSchema.safeParse(rule)
if (!parsed.success) return []
return [{
description: describeAstRule(parsed.data),
kind: requirementKind(parsed.data.engine),
}]
if (!astRuleIsMeaningful(parsed.data)) return []
return [
{
description: describeAstRule(parsed.data, language),
kind: requirementKind(parsed.data.engine),
},
]
})
if (items.length > 0) out[language] = items
}
return Object.keys(out).length > 0 ? out : null
}
/**
* AST zod engine min
* C Python list_comprehension
* astTargetNodeType()
*
*
* astRulesSchema refine schema ****
*
*/
export function astRulesError(astRules: AstRules | null): string | null {
if (!astRules) return null
for (const [language, rules] of Object.entries(astRules)) {
if (rules.length === 0) continue
if (!AST_SUPPORTED_LANGUAGES.includes(language)) {
return `代码规则暂不支持 ${language},判题机只检查 ${AST_SUPPORTED_LANGUAGES.join(" / ")}`
}
const nodes = AST_NODE_TARGETS_BY_LANGUAGE[language] ?? {}
const operators = AST_OPERATOR_TARGETS_BY_LANGUAGE[language] ?? {}
for (const [index, rule] of rules.entries()) {
const at = `代码规则 ${language}${index + 1}`
const target = rule.target ?? ""
if (rule.engine.endsWith("_node")) {
if (!(target in nodes))
return `${at}${language} 没有「${target}」这种语法`
} else if (rule.engine === "must_use_operator") {
if (!(target in operators))
return `${at}${language} 没有「${target}」运算符`
} else if (rule.engine === "must_have_nesting") {
for (const value of [rule.outer ?? "", rule.inner ?? ""]) {
if (!(value in nodes))
return `${at}${language} 没有「${value}」这种语法`
}
} else if (!target.trim()) {
return `${at}:要检查的函数名/方法名不能为空`
}
if (!astRuleIsMeaningful(rule)) return `${at}:次数检查至少要填一个数字`
}
}
return null
}
/**
* languages
* C++ / Java / tab
*
* languages C++
* C++ tab C++
*
*/
export function pickAstRules(
astRules: AstRules | null,
languages: string[],
): AstRules | null {
if (!astRules) return null
const out: AstRules = {}
for (const [language, rules] of Object.entries(astRules)) {
if (!languages.includes(language)) continue
if (!AST_SUPPORTED_LANGUAGES.includes(language)) continue
if (rules.length > 0) out[language] = rules
}
return Object.keys(out).length > 0 ? out : null
}
function rangePassed(count: number, rule: AstRule) {
if (rule.exact !== undefined && count !== rule.exact) return false
if (rule.min !== undefined && count < rule.min) return false
@@ -186,16 +233,41 @@ function rangePassed(count: number, rule: AstRule) {
return true
}
const CALL_NODE_TYPES: Record<string, string> = {
C: "call_expression",
"C++": "call_expression",
Python: "call",
}
function functionCalls(root: Node, target: string, language: string) {
const callType = language === "C" ? "call_expression" : "call"
const callType = CALL_NODE_TYPES[language] ?? "call"
return collectNodes(root, callType).filter((call) => {
const fn = call.childForFieldName("function")
return fn?.type === "identifier" && fn.text === target
if (!fn) return false
if (fn.type === "identifier") return fn.text === target
// `std::sort(...)` 是 qualified_identifier。学生写 sort 还是 std::sort 取决于
// 有没有 using namespace std,两种都得认,所以末段也比一次
if (language === "C++" && fn.type === "qualified_identifier") {
return fn.text === target || fn.text.split("::").pop() === target
}
return false
})
}
function methodCalls(root: Node, target: string, language: string) {
if (language === "C") return []
// C++ 的 `a.push_back()` / `p->push_back()` 都是 call_expression + field_expression
// 和 Python 的 attribute 不是一回事 —— 少了这个分支,C++ 的「必须调用 .push_back()」
// 会静默地永远失败
if (language === "C++") {
return collectNodes(root, "call_expression").filter((call) => {
const fn = call.childForFieldName("function")
return (
fn?.type === "field_expression" &&
fn.childForFieldName("field")?.text === target
)
})
}
if (language !== "Python") return []
return collectNodes(root, "call").filter((call) => {
const fn = call.childForFieldName("function")
return (
@@ -209,70 +281,71 @@ function evaluateRule(
root: Node,
rule: AstRule,
language: string,
mapping: Record<string, string>,
): AstResult | null {
const target = rule.target ?? ""
const nodeType = mapping[target] ?? target
const nodeType = astTargetNodeType(target, language)
switch (rule.engine) {
case "must_exist_node":
return {
description: describeAstRule(rule),
description: describeAstRule(rule, language),
passed: hasNode(root, nodeType),
}
case "must_not_exist_node":
return {
description: describeAstRule(rule),
description: describeAstRule(rule, language),
passed: !hasNode(root, nodeType),
}
case "count_node": {
const count = collectNodes(root, nodeType).length
return {
description: describeAstRule(rule),
description: describeAstRule(rule, language),
passed: rangePassed(count, rule),
actual: count,
}
}
case "must_call_function":
return {
description: describeAstRule(rule),
description: describeAstRule(rule, language),
passed: functionCalls(root, target, language).length > 0,
}
case "must_not_call_function":
return {
description: describeAstRule(rule),
description: describeAstRule(rule, language),
passed: functionCalls(root, target, language).length === 0,
}
case "count_function_call": {
const count = functionCalls(root, target, language).length
return {
description: describeAstRule(rule),
description: describeAstRule(rule, language),
passed: rangePassed(count, rule),
actual: count,
}
}
case "must_call_method":
return {
description: describeAstRule(rule),
description: describeAstRule(rule, language),
passed: methodCalls(root, target, language).length > 0,
}
case "must_not_call_method":
return {
description: describeAstRule(rule),
description: describeAstRule(rule, language),
passed: methodCalls(root, target, language).length === 0,
}
case "must_use_operator":
return {
description: describeAstRule(rule),
description: describeAstRule(rule, language),
passed: hasNode(root, nodeType),
}
case "must_have_nesting": {
const outer = rule.outer ?? ""
const inner = rule.inner ?? ""
const outerType = mapping[outer] ?? outer
const innerType = mapping[inner] ?? inner
const outerType = astTargetNodeType(outer, language)
const innerType = astTargetNodeType(inner, language)
const passed = collectNodes(root, outerType).some((node) =>
node.children.some((child) => hasNode(child, innerType)),
)
return { description: describeAstRule(rule), passed }
return { description: describeAstRule(rule, language), passed }
}
default:
return null
@@ -295,9 +368,9 @@ export async function checkAst(
const tree = parser.parse(code)
if (!tree) return { passed: true, results: [] }
try {
const mapping = mappings[language] ?? {}
const results = rules
.map((rule) => evaluateRule(tree.rootNode, rule, language, mapping))
.filter(astRuleIsMeaningful)
.map((rule) => evaluateRule(tree.rootNode, rule, language))
.filter((result): result is AstResult => result !== null)
return { passed: results.every((result) => result.passed), results }
} finally {
+2 -8
View File
@@ -1,7 +1,4 @@
import {
submissionUpdateSchema,
type SubmissionUpdate,
} from "@oj2/contract"
import { submissionUpdateSchema, type SubmissionUpdate } from "@oj2/contract"
import { redis } from "../redis"
@@ -20,10 +17,7 @@ export async function publishSubmissionUpdate(
userId: number,
data: SubmissionUpdate,
) {
const event: SubmissionEvent = {
userId,
data: submissionUpdateSchema.parse(data),
}
const event: SubmissionEvent = { userId, data }
await redis.publish(submissionUpdateChannel, JSON.stringify(event))
}
+50 -57
View File
@@ -1,4 +1,39 @@
const defaultEnv = ["LANG=en_US.UTF-8", "LANGUAGE=en_US:en", "LC_ALL=en_US.UTF-8"]
import { normalizeLanguage } from "@oj2/contract"
/**
* ** C / C++ / Python **
*
* Java / Golang / JavaScript 2026-09 JDKGoNode
* Python / C / C++ / SQL
* 12 62
*
* `judgeLanguageSchema` ****
* `docker/judge/Dockerfile`
*
* `Python` 2026-09 `Python3` 3 `Python2`
* 0019 `judgeConfigFor()`
*
*
* SQL `judge/sql/` AI
*/
const defaultEnv = [
"LANG=en_US.UTF-8",
"LANGUAGE=en_US:en",
"LC_ALL=en_US.UTF-8",
]
/**
* gcc-14 warning error `-w` error
* `#include <stdio.h>` printfint
* 2026-09 gcc-13 14 docker/judge/
* ** 20 C CE**
*
* C C++ errorg++
*
* docs/c-tutorials/verify-code.sh
*/
const cLooseErrors =
"-Wno-error=implicit-function-declaration -Wno-error=int-conversion -Wno-error=incompatible-pointer-types"
export const languageConfigs: Record<string, Record<string, unknown>> = {
C: {
@@ -9,8 +44,7 @@ export const languageConfigs: Record<string, Record<string, unknown>> = {
max_cpu_time: 3000,
max_real_time: 10000,
max_memory: 256 * 1024 * 1024,
compile_command:
"/usr/bin/gcc -DONLINE_JUDGE -O2 -w -fmax-errors=3 -std=c17 {src_path} -lm -o {exe_path}",
compile_command: `/usr/bin/gcc -DONLINE_JUDGE -O2 -w -fmax-errors=3 -std=c17 ${cLooseErrors} {src_path} -lm -o {exe_path}`,
},
run: {
command: "{exe_path}",
@@ -35,24 +69,7 @@ export const languageConfigs: Record<string, Record<string, unknown>> = {
env: defaultEnv,
},
},
Java: {
template: "",
compile: {
src_name: "Main.java",
exe_name: "Main",
max_cpu_time: 5000,
max_real_time: 10000,
max_memory: -1,
compile_command: "/usr/bin/javac {src_path} -d {exe_dir}",
},
run: {
command: "/usr/bin/java -cp {exe_dir} -XX:MaxRAM={max_memory}k Main",
seccomp_rule: null,
env: defaultEnv,
memory_limit_check_only: 1,
},
},
Python3: {
Python: {
template: "",
compile: {
src_name: "solution.py",
@@ -68,40 +85,16 @@ export const languageConfigs: Record<string, Record<string, unknown>> = {
env: defaultEnv,
},
},
Golang: {
template: "",
compile: {
src_name: "main.go",
exe_name: "main",
max_cpu_time: 3000,
max_real_time: 5000,
max_memory: 1024 * 1024 * 1024,
compile_command: "/usr/bin/go build -o {exe_path} {src_path}",
env: ["GOCACHE=/tmp", "GOPATH=/tmp", "GOMAXPROCS=1", ...defaultEnv],
},
run: {
command: "{exe_path}",
seccomp_rule: "golang",
env: ["GOMAXPROCS=1", ...defaultEnv],
memory_limit_check_only: 1,
},
},
JavaScript: {
template: "",
compile: {
src_name: "main.js",
exe_name: "main.js",
max_cpu_time: 3000,
max_real_time: 5000,
max_memory: 1024 * 1024 * 1024,
compile_command: "/usr/bin/node --check {src_path}",
env: defaultEnv,
},
run: {
command: "/usr/bin/node {exe_path}",
seccomp_rule: "node",
env: defaultEnv,
memory_limit_check_only: 1,
},
},
}
/**
* **** `languageConfigs[x]`
* `normalizeLanguage()` `Python3` / `Python2`
*/
export function judgeConfigFor(language: string) {
return (
languageConfigs[language] ??
languageConfigs[normalizeLanguage(language) ?? ""] ??
null
)
}
+172 -54
View File
@@ -1,21 +1,21 @@
import { createHash } from "node:crypto"
import { astRuleSchema } from "@oj2/contract"
import { astRuleSchema, type ContestSubmissionInfo } from "@oj2/contract"
import { and, eq, inArray } from "drizzle-orm"
import { config } from "../config"
import { db, schema } from "../db"
import { publishAchievementNotification } from "../events"
import { updateAchievementsForSubmission } from "../services/achievements"
import {
updateAchievementsForProblemSet,
updateAchievementsForSubmission,
} from "../services/achievements"
import { recordSolvedProblem } from "../services/problemset"
import { checkAst, type AstRule } from "./ast"
import { publishSubmissionUpdate } from "./events"
import type { JudgeJobData } from "./job"
import { languageConfigs } from "./languages"
import {
isAccepted,
JudgeStatus,
type JudgeStatusValue,
} from "./status"
import { judgeConfigFor } from "./languages"
import { isAccepted, JudgeStatus, type JudgeStatusValue } from "./status"
import { parseProblemTemplate } from "./template"
import { runSqlCase } from "./sql"
import { readInfo } from "../services/test-case"
@@ -77,8 +77,9 @@ async function requestJudge(
memoryLimit: number,
testCaseId: string,
) {
const languageConfig = languageConfigs[language]
if (!languageConfig) throw new Error(`Unsupported judge language: ${language}`)
const languageConfig = judgeConfigFor(language)
if (!languageConfig)
throw new Error(`Unsupported judge language: ${language}`)
const token = createHash("sha256")
.update(config.judgeServerToken)
@@ -172,8 +173,7 @@ async function persistResult(
.update(schema.problem)
.set({
submissionNumber: problem.submissionNumber + 1,
acceptedNumber:
problem.acceptedNumber + (isAccepted(result) ? 1 : 0),
acceptedNumber: problem.acceptedNumber + (isAccepted(result) ? 1 : 0),
statisticInfo: problemStatistics,
})
.where(eq(schema.problem.id, problemId))
@@ -232,7 +232,10 @@ async function persistResult(
submissionInfo: {},
})
.onConflictDoNothing({
target: [schema.acmContestRank.contestId, schema.acmContestRank.userId],
target: [
schema.acmContestRank.contestId,
schema.acmContestRank.userId,
],
})
const [rank] = await tx
@@ -247,15 +250,12 @@ async function persistResult(
.for("update")
if (!rank) throw new Error("Contest rank could not be created")
const rankInfo = objectValue(rank.submissionInfo)
const previousInfo = objectValue(rankInfo[String(problemId)])
const alreadyAccepted = previousInfo.is_ac === true
const rankInfo = rank.submissionInfo
const previousInfo = rankInfo[String(problemId)]
const alreadyAccepted = previousInfo?.is_ac === true
if (!alreadyAccepted) {
const errorNumber =
typeof previousInfo.error_number === "number"
? previousInfo.error_number
: 0
const nextInfo: Record<string, unknown> = {
const errorNumber = previousInfo?.error_number ?? 0
const nextInfo: ContestSubmissionInfo = {
is_ac: acceptedNow,
ac_time: 0,
error_number:
@@ -269,7 +269,8 @@ async function persistResult(
const acTime = Math.max(
0,
Math.floor(
(Date.parse(submissionCreateTime) - Date.parse(contest.startTime)) /
(Date.parse(submissionCreateTime) -
Date.parse(contest.startTime)) /
1000,
),
)
@@ -295,7 +296,11 @@ async function persistResult(
})
}
async function markSystemError(submissionId: string, userId: number, error: unknown) {
async function markSystemError(
submissionId: string,
userId: number,
error: unknown,
) {
const message = error instanceof Error ? error.message : String(error)
const updated = await db
.update(schema.submission)
@@ -324,6 +329,34 @@ async function markSystemError(submissionId: string, userId: number, error: unkn
}
}
/**
* `judgeSubmission`
*
* judgeSubmission try/catch SYSTEM_ERROR
* `failed`
* **worker ** OOM
* BullMQ stalled attempts
*
* 3 PENDING
* 2022-11 / 2026-03 / 2026-04
*
* `markSystemError` PENDING / JUDGING
* PENDING
*
*/
export async function failAbandonedSubmission(
submissionId: string,
error: unknown,
) {
const [row] = await db
.select({ userId: schema.submission.userId })
.from(schema.submission)
.where(eq(schema.submission.id, submissionId))
.limit(1)
if (!row) return
await markSystemError(submissionId, row.userId, error)
}
export async function judgeSubmission(job: JudgeJobData) {
const [row] = await db
.select({
@@ -331,7 +364,10 @@ export async function judgeSubmission(job: JudgeJobData) {
problem: schema.problem,
})
.from(schema.submission)
.innerJoin(schema.problem, eq(schema.submission.problemId, schema.problem.id))
.innerJoin(
schema.problem,
eq(schema.submission.problemId, schema.problem.id),
)
.where(
and(
eq(schema.submission.id, job.submissionId),
@@ -341,7 +377,11 @@ export async function judgeSubmission(job: JudgeJobData) {
.limit(1)
if (!row) throw new Error(`Submission ${job.submissionId} does not exist`)
if (![JudgeStatus.PENDING, JudgeStatus.JUDGING].includes(row.submission.result as 6 | 7)) {
if (
![JudgeStatus.PENDING, JudgeStatus.JUDGING].includes(
row.submission.result as 6 | 7,
)
) {
return
}
@@ -368,15 +408,16 @@ export async function judgeSubmission(job: JudgeJobData) {
// SQL 题不经判题沙箱:沙箱是给编译型/脚本型语言用的,SQL 判的是结果集,
// 走 judge/sql 的 WASM 引擎(在独立子进程里跑,见那边的说明)。
const response = row.submission.language === "SQL"
? await judgeSqlSubmission(row.problem, row.submission.code)
: await requestJudge(
row.submission.language,
source,
row.problem.timeLimit,
row.problem.memoryLimit,
row.problem.testCaseId,
)
const response =
row.submission.language === "SQL"
? await judgeSqlSubmission(row.problem, row.submission.code)
: await requestJudge(
row.submission.language,
source,
row.problem.timeLimit,
row.problem.memoryLimit,
row.problem.testCaseId,
)
let result: JudgeStatusValue
let info: unknown = {}
@@ -399,11 +440,19 @@ export async function judgeSubmission(job: JudgeJobData) {
(left, right) => Number(left.test_case) - Number(right.test_case),
)
info = { err: null, data: cases }
const firstFailure = cases.find((item) => item.result !== JudgeStatus.ACCEPTED)
const firstFailure = cases.find(
(item) => item.result !== JudgeStatus.ACCEPTED,
)
result = statusValue(firstFailure?.result ?? JudgeStatus.ACCEPTED)
statisticInfo = {
time_cost: Math.max(0, ...cases.map((item) => Number(item.cpu_time) || 0)),
memory_cost: Math.max(0, ...cases.map((item) => Number(item.memory) || 0)),
time_cost: Math.max(
0,
...cases.map((item) => Number(item.cpu_time) || 0),
),
memory_cost: Math.max(
0,
...cases.map((item) => Number(item.memory) || 0),
),
score: 0,
}
// SQL 判题给出的中文提示(只读拒绝/超时/内存/无结果集)只存在测试点的
@@ -412,7 +461,8 @@ export async function judgeSubmission(job: JudgeJobData) {
const failedMessage = cases.find(
(item) => item.result !== JudgeStatus.ACCEPTED && item.error_message,
)?.error_message
if (typeof failedMessage === "string") statisticInfo.err_info = failedMessage
if (typeof failedMessage === "string")
statisticInfo.err_info = failedMessage
if (result === JudgeStatus.ACCEPTED) {
const rules = astRulesForLanguage(
@@ -446,18 +496,74 @@ export async function judgeSubmission(job: JudgeJobData) {
)
if (!saved) return
// 题单记账挪到判题这一路。以前靠前端 AC 之后回调 PUT /problem-set-progress
// 只认路由参数里那一个题单:从普通题库入口做出同一道题不计进度,网络一抖就静默丢失。
// 放在最后那条 publishSubmissionUpdate("finished") 之前 —— 前端收到「判完了」时
// 进度已经落库,跳回题单页看到的就是新数据。
// 比赛题不进题单(题单加题时卡了 contestId IS NULL),跳过。
if (row.submission.contestId === null && isAccepted(result)) {
try {
const { updated, earned } = await recordSolvedProblem(
row.submission.userId,
row.problem.id,
row.submission.id,
row.submission.createTime,
)
if (earned.length > 0) {
await publishAchievementNotification(
row.submission.userId,
earned.map((badge) => ({
id: badge.id,
name: badge.name,
description: badge.description,
icon: badge.icon,
rarity: "bronze",
kind: "badge",
})),
)
}
if (updated > 0) {
const unlocked = await updateAchievementsForProblemSet(
row.submission.userId,
)
await publishAchievementNotification(
row.submission.userId,
unlocked.map((achievement) => ({
id: achievement.id,
name: achievement.name,
description: achievement.description,
icon: achievement.icon,
rarity: achievement.rarity,
kind: "achievement",
})),
)
}
} catch (error) {
console.error(
`Failed to record problem set progress for ${row.submission.id}`,
error,
)
}
}
try {
const unlocked = await updateAchievementsForSubmission(row.submission.id)
await publishAchievementNotification(row.submission.userId, unlocked.map((achievement) => ({
id: achievement.id,
name: achievement.name,
description: achievement.description,
icon: achievement.icon,
rarity: achievement.rarity,
kind: "achievement",
})))
await publishAchievementNotification(
row.submission.userId,
unlocked.map((achievement) => ({
id: achievement.id,
name: achievement.name,
description: achievement.description,
icon: achievement.icon,
rarity: achievement.rarity,
kind: "achievement",
})),
)
} catch (error) {
console.error(`Failed to update achievements for ${row.submission.id}`, error)
console.error(
`Failed to update achievements for ${row.submission.id}`,
error,
)
}
await publishSubmissionUpdate(row.submission.userId, {
@@ -466,7 +572,9 @@ export async function judgeSubmission(job: JudgeJobData) {
result,
status: "finished",
score:
typeof statisticInfo.score === "number" ? statisticInfo.score : undefined,
typeof statisticInfo.score === "number"
? statisticInfo.score
: undefined,
})
} catch (error) {
console.error(`Failed to judge submission ${row.submission.id}`, error)
@@ -474,7 +582,6 @@ export async function judgeSubmission(job: JudgeJobData) {
}
}
/**
* SQL
* WebSocket
@@ -492,15 +599,23 @@ async function judgeSqlSubmission(
const answers = Array.isArray(problem.answers) ? problem.answers : []
const refSql = answers
.map((item) => objectValue(item))
.find((item) => item.language === "SQL" && typeof item.code === "string" && item.code.trim())?.code
.find(
(item) =>
item.language === "SQL" &&
typeof item.code === "string" &&
item.code.trim(),
)?.code
if (typeof refSql !== "string") throw new Error("题目缺少 SQL 标准答案")
const info = await readInfo(problem.testCaseId)
if (!info) throw new Error("测试点信息读取失败")
if (!info.sql) throw new Error("测试点不是 SQL 类型,请重新上传 SQL 测试点压缩包")
if (!info.sql)
throw new Error("测试点不是 SQL 类型,请重新上传 SQL 测试点压缩包")
// 按 "1","2",… 的数字序遍历,保证测试点顺序稳定
const keys = Object.keys(info.test_cases ?? {}).sort((a, b) => Number(a) - Number(b))
const keys = Object.keys(info.test_cases ?? {}).sort(
(a, b) => Number(a) - Number(b),
)
if (keys.length === 0) throw new Error("题目没有任何测试点")
const cases: JudgeCase[] = []
@@ -509,7 +624,9 @@ async function judgeSqlSubmission(
const initSql = await readFile(
resolvePath(config.testCaseDirectory, problem.testCaseId, inputName),
"utf8",
).catch(() => { throw new Error(`测试点脚本 ${inputName} 读取失败`) })
).catch(() => {
throw new Error(`测试点脚本 ${inputName} 读取失败`)
})
const outcome = await runSqlCase({
kind: "judge",
@@ -523,7 +640,8 @@ async function judgeSqlSubmission(
})
if (!outcome.ok) {
// 初始化/标准答案执行失败属出题配置问题,整题 SYSTEM_ERROR
if (outcome.result === JudgeStatus.SYSTEM_ERROR) throw new Error(outcome.message)
if (outcome.result === JudgeStatus.SYSTEM_ERROR)
throw new Error(outcome.message)
// 子进程被杀(超时/内存)也走这里,按学生错误记成一个测试点
cases.push({
test_case: String(index + 1),
+11 -3
View File
@@ -29,7 +29,12 @@ export type SqlJob =
timeLimitMs: number
memoryLimitMb: number
}
| { kind: "display"; initSql: string; refSql: string; mode: "query" | "modify" }
| {
kind: "display"
initSql: string
refSql: string
mode: "query" | "modify"
}
/**
* writeSync SIGKILL
@@ -90,10 +95,13 @@ export async function runSqlChild() {
// WASM 堆触顶时 emscripten 抛的是普通 Error"Aborted"/"out of memory"),
// 到这里说明连引擎自身都没撑住,按内存超限报,不当成出题人的错
const message = String((error as Error)?.message ?? error)
const memoryish = message.includes("out of memory") || message.includes("Aborted")
const memoryish =
message.includes("out of memory") || message.includes("Aborted")
finish({
ok: false,
result: memoryish ? JudgeStatus.MEMORY_LIMIT_EXCEEDED : JudgeStatus.SYSTEM_ERROR,
result: memoryish
? JudgeStatus.MEMORY_LIMIT_EXCEEDED
: JudgeStatus.SYSTEM_ERROR,
message: memoryish ? "内存超出限制" : message.slice(0, 200),
})
}
+194 -55
View File
@@ -45,10 +45,17 @@ const DISPLAY_ROW_LIMIT = 20
const ERROR_MESSAGE_MAX_LEN = 200
/** prepare 阶段的语法类错误,映射为 COMPILE_ERROR */
const SYNTAX_ERROR_MARKERS = ["syntax error", "unrecognized token", "incomplete input"]
const SYNTAX_ERROR_MARKERS = [
"syntax error",
"unrecognized token",
"incomplete input",
]
export class SqlCaseError extends Error {
constructor(readonly result: JudgeStatusValue, readonly detail: string) {
constructor(
readonly result: JudgeStatusValue,
readonly detail: string,
) {
super(detail)
}
}
@@ -82,9 +89,11 @@ type Canonical = string
*/
function canonicalValue(value: unknown): Canonical {
if (value === null || value === undefined) return "null"
if (value instanceof Uint8Array) return `blob:${Buffer.from(value).toString("hex")}`
if (value instanceof Uint8Array)
return `blob:${Buffer.from(value).toString("hex")}`
if (typeof value === "number") {
if (Number.isInteger(value) && Math.abs(value) < 2 ** 53) return `num:${value}`
if (Number.isInteger(value) && Math.abs(value) < 2 ** 53)
return `num:${value}`
// Python 的 format(v, ".6g")
return `num:${formatG6(value)}`
}
@@ -96,7 +105,10 @@ function canonicalValue(value: unknown): Canonical {
function formatG6(value: number) {
const exponent = value === 0 ? 0 : Math.floor(Math.log10(Math.abs(value)))
if (exponent < -4 || exponent >= 6) {
return value.toExponential(5).replace(/\.?0+e/, "e").replace(/e([+-])(\d)$/, "e$10$2")
return value
.toExponential(5)
.replace(/\.?0+e/, "e")
.replace(/e([+-])(\d)$/, "e$10$2")
}
const text = value.toPrecision(6)
return text.includes(".") ? text.replace(/\.?0+$/, "") : text
@@ -138,9 +150,11 @@ interface PreparedStatement {
}
function iterate(db: Database, script: string): Iterable<PreparedStatement> {
return (db as unknown as {
iterateStatements(sql: string): Iterable<PreparedStatement>
}).iterateStatements(script)
return (
db as unknown as {
iterateStatements(sql: string): Iterable<PreparedStatement>
}
).iterateStatements(script)
}
/**
@@ -157,9 +171,17 @@ function leadingKeyword(statement: PreparedStatement) {
}
// 万一这个 build 没开 SQLITE_ENABLE_NORMALIZE,退回到原文剥注释
if (!text) {
text = statement.getSQL().replace(/\/\*[\s\S]*?\*\//g, " ").replace(/--[^\n]*/g, " ")
text = statement
.getSQL()
.replace(/\/\*[\s\S]*?\*\//g, " ")
.replace(/--[^\n]*/g, " ")
}
return text.trimStart().split(/[\s(;]/, 1)[0]?.toUpperCase() ?? ""
return (
text
.trimStart()
.split(/[\s(;]/, 1)[0]
?.toUpperCase() ?? ""
)
}
/**
@@ -187,11 +209,17 @@ class ByteBudget {
? Buffer.byteLength(value)
: 8 // 数字和 NULL 按定长算,撑不出内存
if (bytes > this.maxBytes) {
throw new SqlCaseError(JudgeStatus.MEMORY_LIMIT_EXCEEDED, "单个数据值超出内存限制")
throw new SqlCaseError(
JudgeStatus.MEMORY_LIMIT_EXCEEDED,
"单个数据值超出内存限制",
)
}
this.used += bytes
if (this.used > this.maxBytes) {
throw new SqlCaseError(JudgeStatus.MEMORY_LIMIT_EXCEEDED, "查询结果超出内存限制")
throw new SqlCaseError(
JudgeStatus.MEMORY_LIMIT_EXCEEDED,
"查询结果超出内存限制",
)
}
}
}
@@ -226,12 +254,17 @@ function executeStatements(
budget?.charge(row)
rows.push(canonicalRow(row))
if (rows.length > ROW_LIMIT) {
throw new SqlCaseError(JudgeStatus.MEMORY_LIMIT_EXCEEDED, `查询结果超过 ${ROW_LIMIT}`)
throw new SqlCaseError(
JudgeStatus.MEMORY_LIMIT_EXCEEDED,
`查询结果超过 ${ROW_LIMIT}`,
)
}
}
last = { columns: names.length, rows }
} else {
while (statement.step()) { /* 无结果集语句,推进到结束 */ }
while (statement.step()) {
/* 无结果集语句,推进到结束 */
}
}
} finally {
statement.free()
@@ -242,7 +275,10 @@ function executeStatements(
/** dump 所有用户表:{表名: 列数 + 已排序的行},表状态天然无序 */
function dumpTables(db: Database, budget?: ByteBudget) {
const names = queryColumn(db, "SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' ORDER BY name")
const names = queryColumn(
db,
"SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' ORDER BY name",
)
const state: Record<string, { columns: number; rows: string[] }> = {}
for (const table of names) {
const quoted = String(table).replaceAll('"', '""')
@@ -253,7 +289,10 @@ function dumpTables(db: Database, budget?: ByteBudget) {
return canonicalRow(row as unknown[])
})
if (rows.length > ROW_LIMIT) {
throw new SqlCaseError(JudgeStatus.MEMORY_LIMIT_EXCEEDED, `${table} 超过 ${ROW_LIMIT}`)
throw new SqlCaseError(
JudgeStatus.MEMORY_LIMIT_EXCEEDED,
`${table} 超过 ${ROW_LIMIT}`,
)
}
state[String(table)] = {
// 空表 exec 不返回结果,列数用 table_info 兜底
@@ -278,14 +317,25 @@ function trustedErrorText(message: string) {
}
/** 执行受信脚本(初始化/标准答案),任何失败都是出题问题 → SYSTEM_ERROR */
function executeTrusted(db: Database, script: string, deadline: number, prefix: string) {
function executeTrusted(
db: Database,
script: string,
deadline: number,
prefix: string,
) {
try {
return executeStatements(db, script, deadline)
} catch (error) {
if (error instanceof SqlCaseError) {
throw new SqlCaseError(JudgeStatus.SYSTEM_ERROR, `${prefix}: ${error.detail}`)
throw new SqlCaseError(
JudgeStatus.SYSTEM_ERROR,
`${prefix}: ${error.detail}`,
)
}
throw new SqlCaseError(JudgeStatus.SYSTEM_ERROR, `${prefix}: ${trustedErrorText(String((error as Error).message))}`)
throw new SqlCaseError(
JudgeStatus.SYSTEM_ERROR,
`${prefix}: ${trustedErrorText(String((error as Error).message))}`,
)
}
}
@@ -300,36 +350,63 @@ function runStudent(
// 查询题只读:PRAGMA query_only 是 SQLite 原生开关,替代旧实现的 authorizer 白名单
if (mode === "query") db.run("PRAGMA query_only=1")
// 把题目的 memoryLimit 变成学生看得见的约束,替代旧实现的 setlimit(LIMIT_LENGTH)
const budget = new ByteBudget(Math.max(Math.trunc(memoryLimitMb), 1) * 1024 * 1024)
const budget = new ByteBudget(
Math.max(Math.trunc(memoryLimitMb), 1) * 1024 * 1024,
)
try {
const last = executeStatements(db, script, deadline, (statement) => {
// query_only 自己就是个 PRAGMA,不拦 PRAGMA 的话学生一句 `PRAGMA query_only=0`
// 就把只读关掉了。旧实现的 authorizer 把 SQLITE_PRAGMA 一律拒掉,这里对齐它。
// 教学场景下学生也没有用 PRAGMA 的正当需求,两种题型一律拒。
if (leadingKeyword(statement) === "PRAGMA") {
throw new SqlCaseError(JudgeStatus.RUNTIME_ERROR, "禁止使用 PRAGMA 语句")
}
// 兜底:万一漏掉某种改设置的写法,限制在每条语句前都重放一遍
applyLimits(db, memoryLimitMb)
if (mode === "query") db.run("PRAGMA query_only=1")
}, budget)
const last = executeStatements(
db,
script,
deadline,
(statement) => {
// query_only 自己就是个 PRAGMA,不拦 PRAGMA 的话学生一句 `PRAGMA query_only=0`
// 就把只读关掉了。旧实现的 authorizer 把 SQLITE_PRAGMA 一律拒掉,这里对齐它。
// 教学场景下学生也没有用 PRAGMA 的正当需求,两种题型一律拒。
if (leadingKeyword(statement) === "PRAGMA") {
throw new SqlCaseError(
JudgeStatus.RUNTIME_ERROR,
"禁止使用 PRAGMA 语句",
)
}
// 兜底:万一漏掉某种改设置的写法,限制在每条语句前都重放一遍
applyLimits(db, memoryLimitMb)
if (mode === "query") db.run("PRAGMA query_only=1")
},
budget,
)
if (mode === "query") return last
return dumpTables(db, budget)
} catch (error) {
if (error instanceof SqlCaseError) throw error
const message = String((error as Error).message)
if (message.includes("interrupted")) {
throw new SqlCaseError(JudgeStatus.CPU_TIME_LIMIT_EXCEEDED, "SQL 执行超时")
throw new SqlCaseError(
JudgeStatus.CPU_TIME_LIMIT_EXCEEDED,
"SQL 执行超时",
)
}
if (message.includes("database or disk is full")) {
throw new SqlCaseError(JudgeStatus.MEMORY_LIMIT_EXCEEDED, "数据量超出内存限制")
throw new SqlCaseError(
JudgeStatus.MEMORY_LIMIT_EXCEEDED,
"数据量超出内存限制",
)
}
// WASM 堆触顶(zeroblob/group_concat 构造出的超大单值)或 SQLite 自身的长度上限
if (message.includes("too big") || message.includes("out of memory") || message.includes("Aborted")) {
throw new SqlCaseError(JudgeStatus.MEMORY_LIMIT_EXCEEDED, "单个数据值超出内存限制")
if (
message.includes("too big") ||
message.includes("out of memory") ||
message.includes("Aborted")
) {
throw new SqlCaseError(
JudgeStatus.MEMORY_LIMIT_EXCEEDED,
"单个数据值超出内存限制",
)
}
if (message.includes("readonly database")) {
throw new SqlCaseError(JudgeStatus.RUNTIME_ERROR, "本题为查询题,禁止修改数据或表结构(INSERT/UPDATE/DELETE/CREATE 等)")
throw new SqlCaseError(
JudgeStatus.RUNTIME_ERROR,
"本题为查询题,禁止修改数据或表结构(INSERT/UPDATE/DELETE/CREATE 等)",
)
}
if (SYNTAX_ERROR_MARKERS.some((marker) => message.includes(marker))) {
throw new SqlCaseError(JudgeStatus.COMPILE_ERROR, truncate(message))
@@ -337,7 +414,11 @@ function runStudent(
throw new SqlCaseError(JudgeStatus.RUNTIME_ERROR, truncate(message))
} finally {
if (mode === "query") {
try { db.run("PRAGMA query_only=0") } catch { /* 连接可能已不可用 */ }
try {
db.run("PRAGMA query_only=0")
} catch {
/* 连接可能已不可用 */
}
}
}
}
@@ -412,14 +493,22 @@ export async function runCase(
const refDb = newDatabase(SQL, options.memoryLimitMb)
try {
executeTrusted(refDb, initSql, trustedDeadline, "初始化脚本执行失败")
const last = executeTrusted(refDb, refSql, trustedDeadline, "标准答案执行失败")
const last = executeTrusted(
refDb,
refSql,
trustedDeadline,
"标准答案执行失败",
)
if (options.mode === "query") {
expected = last
} else {
try {
expected = dumpTables(refDb)
} catch (error) {
throw new SqlCaseError(JudgeStatus.SYSTEM_ERROR, `标准答案结果超出限制: ${(error as SqlCaseError).detail}`)
throw new SqlCaseError(
JudgeStatus.SYSTEM_ERROR,
`标准答案结果超出限制: ${(error as SqlCaseError).detail}`,
)
}
}
} finally {
@@ -460,7 +549,13 @@ export async function runCase(
} catch (error) {
elapsed = Date.now() - start
const failure = error as SqlCaseError
return { ...result, result: failure.result, error_message: failure.detail, cpu_time: elapsed, real_time: elapsed }
return {
...result,
result: failure.result,
error_message: failure.detail,
cpu_time: elapsed,
real_time: elapsed,
}
}
elapsed = Date.now() - start
} finally {
@@ -496,20 +591,35 @@ interface DisplayTable {
/** 按建表顺序 dump 用户表的原始行用于展示(区别于 dumpTables 的归一化判题态) */
function dumpDisplayTables(db: Database, only?: Set<string>): DisplayTable[] {
const names = queryColumn(db, "SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'")
const names = queryColumn(
db,
"SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'",
)
const tables: DisplayTable[] = []
for (const raw of names) {
const name = String(raw)
if (only && !only.has(name)) continue
const quoted = name.replaceAll('"', '""')
const columns = (db.exec(`PRAGMA table_info("${quoted}")`)[0]?.values ?? []).map((row) => ({
const columns = (
db.exec(`PRAGMA table_info("${quoted}")`)[0]?.values ?? []
).map((row) => ({
name: String(row[1]),
type: String(row[2] ?? ""),
}))
const total = Number(db.exec(`SELECT COUNT(*) FROM "${quoted}"`)[0]?.values[0]?.[0] ?? 0)
const rows = (db.exec(`SELECT * FROM "${quoted}" LIMIT ${DISPLAY_ROW_LIMIT}`)[0]?.values ?? [])
.map((row) => (row as unknown[]).map(displayValue))
tables.push({ name, columns, rows, total_rows: total, truncated: total > DISPLAY_ROW_LIMIT })
const total = Number(
db.exec(`SELECT COUNT(*) FROM "${quoted}"`)[0]?.values[0]?.[0] ?? 0,
)
const rows = (
db.exec(`SELECT * FROM "${quoted}" LIMIT ${DISPLAY_ROW_LIMIT}`)[0]
?.values ?? []
).map((row) => (row as unknown[]).map(displayValue))
tables.push({
name,
columns,
rows,
total_rows: total,
truncated: total > DISPLAY_ROW_LIMIT,
})
}
return tables
}
@@ -546,17 +656,27 @@ export async function buildDisplay(
for (const statement of iterate(db, refSql)) {
try {
const names = statement.getColumnNames()
if (names.length === 0) { while (statement.step()) { /* 无结果集 */ } ; continue }
if (names.length === 0) {
while (statement.step()) {
/* 无结果集 */
}
continue
}
const rows: unknown[][] = []
while (statement.step()) {
rows.push(statement.get())
if (rows.length > ROW_LIMIT) {
throw new SqlCaseError(JudgeStatus.SYSTEM_ERROR, `标准答案结果超过 ${ROW_LIMIT}`)
throw new SqlCaseError(
JudgeStatus.SYSTEM_ERROR,
`标准答案结果超过 ${ROW_LIMIT}`,
)
}
}
expected = {
columns: queryResultColumns(names, tables),
rows: rows.slice(0, DISPLAY_ROW_LIMIT).map((row) => row.map(displayValue)),
rows: rows
.slice(0, DISPLAY_ROW_LIMIT)
.map((row) => row.map(displayValue)),
total_rows: rows.length,
truncated: rows.length > DISPLAY_ROW_LIMIT,
}
@@ -566,10 +686,16 @@ export async function buildDisplay(
}
} catch (error) {
if (error instanceof SqlCaseError) throw error
throw new SqlCaseError(JudgeStatus.SYSTEM_ERROR, `标准答案执行失败: ${trustedErrorText(String((error as Error).message))}`)
throw new SqlCaseError(
JudgeStatus.SYSTEM_ERROR,
`标准答案执行失败: ${trustedErrorText(String((error as Error).message))}`,
)
}
if (expected === null) {
throw new SqlCaseError(JudgeStatus.SYSTEM_ERROR, "标准答案未产生查询结果集")
throw new SqlCaseError(
JudgeStatus.SYSTEM_ERROR,
"标准答案未产生查询结果集",
)
}
return { tables, expected }
}
@@ -578,18 +704,31 @@ export async function buildDisplay(
executeTrusted(db, refSql, deadline, "标准答案执行失败")
const after = dumpTables(db)
const changed = new Set<string>()
for (const name of new Set([...Object.keys(before), ...Object.keys(after)])) {
if (JSON.stringify(before[name]) !== JSON.stringify(after[name])) changed.add(name)
for (const name of new Set([
...Object.keys(before),
...Object.keys(after),
])) {
if (JSON.stringify(before[name]) !== JSON.stringify(after[name]))
changed.add(name)
}
if (changed.size === 0) {
throw new SqlCaseError(JudgeStatus.SYSTEM_ERROR, "标准答案未修改任何表数据,请检查题目配置")
throw new SqlCaseError(
JudgeStatus.SYSTEM_ERROR,
"标准答案未修改任何表数据,请检查题目配置",
)
}
const changedTables = dumpDisplayTables(db, changed)
// 被标准答案 DROP 的表已不在库中,用初始展示数据补齐条目(前端据 dropped 提示「表已删除」)
const existing = new Set(changedTables.map((table) => table.name))
for (const table of tables) {
if (changed.has(table.name) && !existing.has(table.name)) {
changedTables.push({ ...table, rows: [], total_rows: 0, truncated: false, dropped: true })
changedTables.push({
...table,
rows: [],
total_rows: 0,
truncated: false,
dropped: true,
})
}
}
return { tables, expected: { changed_tables: changedTables } }
+39 -11
View File
@@ -1,3 +1,5 @@
import type { SqlDisplay } from "@oj2/contract"
import { selfCommand } from "../../runtime"
import { JudgeStatus, type JudgeStatusValue } from "../status"
import { DISPLAY_BUDGET_MS, trustedBudgetMs, type CaseResult } from "./engine"
@@ -83,16 +85,24 @@ const PHASE_FAILURE: Record<string, SqlJobFailure> = {
result: JudgeStatus.SYSTEM_ERROR,
message: "初始化脚本或标准答案超时/内存超限,请检查题目配置",
},
student: { ok: false, result: JudgeStatus.CPU_TIME_LIMIT_EXCEEDED, message: "SQL 执行超时" },
student: {
ok: false,
result: JudgeStatus.CPU_TIME_LIMIT_EXCEEDED,
message: "SQL 执行超时",
},
}
async function runJob<T>(job: SqlJob, budget: JobBudget): Promise<SqlJobOutcome<T>> {
async function runJob<T>(
job: SqlJob,
budget: JobBudget,
): Promise<SqlJobOutcome<T>> {
// 递归闸。子进程里绝不允许再 spawn 子进程 —— 见文件头「为什么必须有这道闸」。
if (process.env[CHILD_MARKER]) {
return {
ok: false,
result: JudgeStatus.SYSTEM_ERROR,
message: "SQL 判题子进程试图再起子进程,已阻断(入口子命令分发可能不正确)",
message:
"SQL 判题子进程试图再起子进程,已阻断(入口子命令分发可能不正确)",
}
}
@@ -113,7 +123,10 @@ async function runJob<T>(job: SqlJob, budget: JobBudget): Promise<SqlJobOutcome<
child.stdin.write(JSON.stringify(job))
await child.stdin.end()
let timer = setTimeout(() => child.kill("SIGKILL"), budget.trustedMs + STARTUP_SLACK_MS)
let timer = setTimeout(
() => child.kill("SIGKILL"),
budget.trustedMs + STARTUP_SLACK_MS,
)
let phase = ""
// stderr 要边读边看:阶段标记一到就得马上换兜底时限,攒到进程结束再读就没意义了
const readStderr = (async () => {
@@ -130,7 +143,10 @@ async function runJob<T>(job: SqlJob, budget: JobBudget): Promise<SqlJobOutcome<
phase = latest
if (phase === "student" && budget.studentMs !== null) {
clearTimeout(timer)
timer = setTimeout(() => child.kill("SIGKILL"), budget.studentMs + STUDENT_SLACK_MS)
timer = setTimeout(
() => child.kill("SIGKILL"),
budget.studentMs + STUDENT_SLACK_MS,
)
}
}
}
@@ -138,7 +154,10 @@ async function runJob<T>(job: SqlJob, budget: JobBudget): Promise<SqlJobOutcome<
let stdout = ""
try {
;[stdout] = await Promise.all([new Response(child.stdout).text(), readStderr])
;[stdout] = await Promise.all([
new Response(child.stdout).text(),
readStderr,
])
await child.exited
} finally {
clearTimeout(timer)
@@ -158,12 +177,15 @@ async function runJob<T>(job: SqlJob, budget: JobBudget): Promise<SqlJobOutcome<
try {
const parsed = JSON.parse(stdout) as
| { ok: true; case?: CaseResult; display?: unknown }
| SqlJobFailure
{ ok: true; case?: CaseResult; display?: unknown } | SqlJobFailure
if (!parsed.ok) return parsed
return { ok: true, value: (parsed.case ?? parsed.display) as T }
} catch {
return { ok: false, result: JudgeStatus.SYSTEM_ERROR, message: "SQL 判题子进程返回了无法解析的结果" }
return {
ok: false,
result: JudgeStatus.SYSTEM_ERROR,
message: "SQL 判题子进程返回了无法解析的结果",
}
}
}
@@ -174,8 +196,14 @@ export function runSqlCase(job: Extract<SqlJob, { kind: "judge" }>) {
})
}
export function buildSqlDisplay(initSql: string, refSql: string, mode: "query" | "modify") {
return runJob<{ tables: unknown[]; expected: unknown }>(
export function buildSqlDisplay(
initSql: string,
refSql: string,
mode: "query" | "modify",
) {
// 子进程产出的形状由 engine.ts 的 dumpDisplayTables / runDisplay 决定,就是契约里的
// SqlDisplay —— 同一个仓库里的两端,不在这儿再 parse 一遍
return runJob<SqlDisplay>(
{ kind: "display", initSql, refSql, mode },
{ trustedMs: DISPLAY_BUDGET_MS, studentMs: null },
)
+54 -16
View File
@@ -1,20 +1,58 @@
export const JudgeStatus = {
COMPILE_ERROR: -2,
WRONG_ANSWER: -1,
ACCEPTED: 0,
CPU_TIME_LIMIT_EXCEEDED: 1,
REAL_TIME_LIMIT_EXCEEDED: 2,
MEMORY_LIMIT_EXCEEDED: 3,
RUNTIME_ERROR: 4,
SYSTEM_ERROR: 5,
PENDING: 6,
JUDGING: 7,
PARTIALLY_ACCEPTED: 8,
AST_CHECK_FAILED: 10,
} as const
import { JudgeStatus, type JudgeStatusValue } from "@oj2/contract"
export type JudgeStatusValue = (typeof JudgeStatus)[keyof typeof JudgeStatus]
// 状态码的唯一一份在 packages/contract/src/judge-status.ts,这里只再导出,
// 省得二十几处 import 一起改
export { JudgeStatus, type JudgeStatusValue }
export function isAccepted(result: number) {
return result === JudgeStatus.ACCEPTED || result === JudgeStatus.AST_CHECK_FAILED
return (
result === JudgeStatus.ACCEPTED || result === JudgeStatus.AST_CHECK_FAILED
)
}
/**
* `utils/constants.ts` `JUDGE_STATUS`
* prompt `结果:-1`
* -1
*/
export const JUDGE_STATUS_NAME: Record<number, string> = {
[JudgeStatus.COMPILE_ERROR]: "编译失败",
[JudgeStatus.WRONG_ANSWER]: "答案错误",
[JudgeStatus.ACCEPTED]: "答案正确",
[JudgeStatus.CPU_TIME_LIMIT_EXCEEDED]: "运行超时",
[JudgeStatus.REAL_TIME_LIMIT_EXCEEDED]: "运行超时",
[JudgeStatus.MEMORY_LIMIT_EXCEEDED]: "内存超限",
[JudgeStatus.RUNTIME_ERROR]: "运行时错误",
[JudgeStatus.SYSTEM_ERROR]: "系统错误",
[JudgeStatus.PENDING]: "等待评分",
[JudgeStatus.JUDGING]: "正在评分",
[JudgeStatus.PARTIALLY_ACCEPTED]: "部分正确",
[JudgeStatus.AST_CHECK_FAILED]: "答案正确,但语法未通过",
}
export function judgeStatusName(result: number) {
return JUDGE_STATUS_NAME[result] ?? `未知状态(${result})`
}
/**
* ****
*
*
*/
export const UNJUDGED_RESULTS: JudgeStatusValue[] = [
JudgeStatus.PENDING,
JudgeStatus.JUDGING,
]
/**
* **** AST_CHECK_FAILED
* SYSTEM_ERROR
* AI
*/
export const NON_FAILURE_RESULTS: JudgeStatusValue[] = [
JudgeStatus.ACCEPTED,
JudgeStatus.AST_CHECK_FAILED,
JudgeStatus.PENDING,
JudgeStatus.JUDGING,
JudgeStatus.SYSTEM_ERROR,
]
+12 -1
View File
@@ -12,6 +12,7 @@
* oj2-api healthcheck # Dockerfile HEALTHCHECK
* oj2-api sql-child # SQL spawn
* oj2-api migrate # docker/deploy.sh
* oj2-api recount # /
*
* import import
* Bun.serve Redis sql-child
@@ -33,6 +34,14 @@ switch (command) {
await runMigrations()
break
}
// 数据订正,跟着二进制走而不是留成源码脚本 —— 生产镜像里没有 bun 也没有源码。
// 反范式计数列被重判等操作带偏之后拿它对账,默认只读预演,--apply 才写。
case "recount": {
const { recount } = await import("./scripts/recount")
process.exit(
await recount({ apply: process.argv.slice(3).includes("--apply") }),
)
}
case "sql-child": {
const { runSqlChild } = await import("./judge/sql/child")
await runSqlChild()
@@ -53,6 +62,8 @@ switch (command) {
}
}
default:
console.error(`未知子命令:${command}\n可用:serve | worker | migrate | healthcheck | sql-child`)
console.error(
`未知子命令:${command}\n可用:serve | worker | migrate | recount | healthcheck | sql-child`,
)
process.exit(2)
}
+31 -9
View File
@@ -2,18 +2,40 @@ import Redis from "ioredis"
import { config } from "./config"
export const redis = new Redis(config.redisUrl, {
maxRetriesPerRequest: 1,
})
/**
* error
*
* ioredis error silentEmit EventEmitter
* `console.error("[ioredis] Unhandled error event:", ...)`
* stderr
*
*/
function withErrorLogging(client: Redis, name: string) {
client.on("error", (error) => {
console.error(`Redis connection error (${name})`, error)
})
return client
}
/**
* `maxRetriesPerRequest: 1`
* Redis 500
*/
export const redis = withErrorLogging(
new Redis(config.redisUrl, { maxRetriesPerRequest: 1 }),
"main",
)
export function createBlockingRedis() {
return new Redis(config.redisUrl, {
maxRetriesPerRequest: null,
})
return withErrorLogging(
new Redis(config.redisUrl, { maxRetriesPerRequest: null }),
"blocking",
)
}
export function createSubscriberRedis() {
return new Redis(config.redisUrl, {
maxRetriesPerRequest: null,
})
return withErrorLogging(
new Redis(config.redisUrl, { maxRetriesPerRequest: null }),
"subscriber",
)
}
+436 -125
View File
@@ -2,14 +2,18 @@ import { randomBytes } from "node:crypto"
import { extname, resolve } from "node:path"
import {
activityRankItemSchema,
metricsSchema,
problemRankSchema,
myRankSchema,
rankProfileSchema,
registerRequestSchema,
STUDENT_ROLES,
updateProfileRequestSchema,
userRankSchema,
type ActivityRankItem,
type Metrics,
type MyRank,
type ProblemRank,
type RankProfile,
type UserRank,
type WeeklyRank,
type WeeklyRankItem,
} from "@oj2/contract"
import {
and,
@@ -24,13 +28,18 @@ import {
isNull,
lt,
lte,
max,
min,
ne,
notExists,
or,
sql,
} from "drizzle-orm"
import { alias } from "drizzle-orm/pg-core"
import { Hono } from "hono"
import { hashPassword } from "../auth/password"
import { onlineUserIds } from "../auth/presence"
import { optionalAuth, requireAuth, type AppEnv } from "../auth/middleware"
import { config } from "../config"
import { db, schema } from "../db"
@@ -38,15 +47,29 @@ import { failure, success } from "../http"
import { JudgeStatus } from "../judge/status"
import { getBooleanOption } from "../services/options"
import { getUserProfileById } from "../services/profile"
import { objectValue, queryInteger, sampleUser } from "./helpers"
import { localTime, weekStart } from "../time"
import {
isTeacherOrAbove,
objectValue,
queryInteger,
sampleUser,
} from "./helpers"
export const accountRoutes = new Hono<AppEnv>()
accountRoutes.post("/users", async (c) => {
const parsed = registerRequestSchema.safeParse(await c.req.json().catch(() => null))
if (!parsed.success) return failure(c, 400, "invalid-request", "Invalid registration payload")
const parsed = registerRequestSchema.safeParse(
await c.req.json().catch(() => null),
)
if (!parsed.success)
return failure(c, 400, "invalid-request", "Invalid registration payload")
if (!(await getBooleanOption("allow_register", true))) {
return failure(c, 403, "registration-disabled", "Register function has been disabled by admin")
return failure(
c,
403,
"registration-disabled",
"Register function has been disabled by admin",
)
}
const username = parsed.data.username.toLowerCase()
@@ -54,7 +77,12 @@ accountRoutes.post("/users", async (c) => {
const [duplicate] = await db
.select({ username: schema.user.username, email: schema.user.email })
.from(schema.user)
.where(or(sql`lower(${schema.user.username}) = ${username}`, sql`lower(${schema.user.email}) = ${email}`))
.where(
or(
sql`lower(${schema.user.username}) = ${username}`,
sql`lower(${schema.user.email}) = ${email}`,
),
)
.limit(1)
if (duplicate?.username.toLowerCase() === username) {
return failure(c, 409, "username-exists", "Username already exists")
@@ -66,22 +94,21 @@ accountRoutes.post("/users", async (c) => {
const now = new Date().toISOString()
const password = await hashPassword(parsed.data.password)
await db.transaction(async (tx) => {
const [created] = await tx.insert(schema.user).values({
username,
email,
password,
rawPassword: parsed.data.password.slice(0, 20),
lastLogin: null,
createTime: now,
adminType: "Regular User",
authToken: null,
openApi: false,
openApiAppkey: null,
isDisabled: false,
problemPermission: "None",
sessionKeys: [],
className: null,
}).returning({ id: schema.user.id })
const [created] = await tx
.insert(schema.user)
.values({
username,
email,
password,
rawPassword: parsed.data.password.slice(0, 20),
lastLogin: null,
createTime: now,
adminType: "Regular User",
isDisabled: false,
problemPermission: "None",
className: null,
})
.returning({ id: schema.user.id })
if (!created) throw new Error("User insert did not return an id")
await tx.insert(schema.userProfile).values({
userId: created.id,
@@ -101,31 +128,57 @@ accountRoutes.get("/profiles/:username", optionalAuth, async (c) => {
// `if not user.is_authenticated: return self.success()` —— 匿名一律返回空,
// 否则用户名可经 /rankings/users 公开枚举,进而无 cookie 批量收集全校学生的邮箱与最后登录时间。
if (!c.get("user")) return success(c, null)
const [target] = await db.select({ id: schema.user.id }).from(schema.user)
.where(and(sql`lower(${schema.user.username}) = lower(${c.req.param("username")})`, eq(schema.user.isDisabled, false))).limit(1)
const [target] = await db
.select({ id: schema.user.id })
.from(schema.user)
.where(
and(
sql`lower(${schema.user.username}) = lower(${c.req.param("username")})`,
eq(schema.user.isDisabled, false),
),
)
.limit(1)
if (!target) return failure(c, 404, "user-not-found", "User does not exist")
const profile = await getUserProfileById(target.id, c.get("user")?.id === target.id)
if (!profile) return failure(c, 404, "profile-not-found", "User profile does not exist")
const profile = await getUserProfileById(
target.id,
c.get("user")?.id === target.id,
)
if (!profile)
return failure(c, 404, "profile-not-found", "User profile does not exist")
return success(c, profile)
})
accountRoutes.put("/me/profile", requireAuth, async (c) => {
const parsed = updateProfileRequestSchema.safeParse(await c.req.json().catch(() => null))
if (!parsed.success) return failure(c, 400, "invalid-request", "Invalid profile payload")
const values = Object.fromEntries(
Object.entries(parsed.data).map(([key, value]) => [key, value === "" ? null : value]),
const parsed = updateProfileRequestSchema.safeParse(
await c.req.json().catch(() => null),
)
await db.update(schema.userProfile).set(values).where(eq(schema.userProfile.userId, c.get("user")!.id))
if (!parsed.success)
return failure(c, 400, "invalid-request", "Invalid profile payload")
const values = Object.fromEntries(
Object.entries(parsed.data).map(([key, value]) => [
key,
value === "" ? null : value,
]),
)
await db
.update(schema.userProfile)
.set(values)
.where(eq(schema.userProfile.userId, c.get("user")!.id))
const profile = await getUserProfileById(c.get("user")!.id, true)
if (!profile) return failure(c, 404, "profile-not-found", "User profile does not exist")
if (!profile)
return failure(c, 404, "profile-not-found", "User profile does not exist")
return success(c, profile)
})
accountRoutes.post("/me/avatar", requireAuth, async (c) => {
const body: Record<string, string | File> = await c.req.parseBody().catch(() => ({}))
const body: Record<string, string | File> = await c.req
.parseBody()
.catch(() => ({}))
const image = body.image
if (!(image instanceof File)) return failure(c, 400, "invalid-file", "Invalid file content")
if (image.size > 2 * 1024 * 1024) return failure(c, 400, "file-too-large", "Picture is too large")
if (!(image instanceof File))
return failure(c, 400, "invalid-file", "Invalid file content")
if (image.size > 2 * 1024 * 1024)
return failure(c, 400, "file-too-large", "Picture is too large")
const extension = extname(image.name).toLowerCase()
if (![".gif", ".jpg", ".jpeg", ".bmp", ".png"].includes(extension)) {
return failure(c, 400, "unsupported-file", "Unsupported file format")
@@ -135,17 +188,34 @@ accountRoutes.post("/me/avatar", requireAuth, async (c) => {
await Bun.$`mkdir -p ${directory}`.quiet()
await Bun.write(resolve(directory, filename), image)
const avatar = `${config.avatarUriPrefix}/${filename}`
await db.update(schema.userProfile).set({ avatar }).where(eq(schema.userProfile.userId, c.get("user")!.id))
await db
.update(schema.userProfile)
.set({ avatar })
.where(eq(schema.userProfile.userId, c.get("user")!.id))
return success(c, { avatar })
})
accountRoutes.get("/users/:id/metrics", async (c) => {
const userId = queryInteger(c.req.param("id"), 0, { min: 1 })
const [row] = await db.select({ total: count(), first: min(schema.submission.createTime), latest: sql<string>`max(${schema.submission.createTime})` })
// 比赛提交也算:首末提交时间、学习天数都连比赛一起统计
const [row] = await db
.select({
first: min(schema.submission.createTime),
latest: max(schema.submission.createTime),
activeDays: countDistinct(
sql`date(${localTime(schema.submission.createTime)})`,
),
})
.from(schema.submission)
.where(and(eq(schema.submission.userId, userId), isNull(schema.submission.contestId)))
if (!row?.total || !row.first || !row.latest) return failure(c, 404, "no-submissions", "暂无提交")
return success(c, metricsSchema.parse({ now: new Date().toISOString(), first: row.first, latest: row.latest }))
.where(eq(schema.submission.userId, userId))
if (!row?.first || !row.latest)
return failure(c, 404, "no-submissions", "暂无提交")
return success(c, {
now: new Date().toISOString(),
first: row.first,
latest: row.latest,
activeDays: row.activeDays,
} satisfies Metrics)
})
/**
@@ -161,7 +231,7 @@ const LEADERBOARD_SIZE = 100
/** 入榜人群:正常状态的学生与学生管理员。教师和超管不参与排名。 */
const leaderboardWhere = and(
inArray(schema.user.adminType, ["Regular User", "Student Admin"]),
inArray(schema.user.adminType, [...STUDENT_ROLES]),
eq(schema.user.isDisabled, false),
)
@@ -178,40 +248,64 @@ const leaderboardOrder = [
]
accountRoutes.get("/rankings/users", optionalAuth, async (c) => {
const limit = queryInteger(c.req.query("limit"), 10, { min: 1, max: LEADERBOARD_SIZE })
const limit = queryInteger(c.req.query("limit"), 10, {
min: 1,
max: LEADERBOARD_SIZE,
})
const offset = queryInteger(c.req.query("offset"), 0, { min: 0 })
const [totalRow] = await db.select({ value: count() }).from(schema.userProfile)
.innerJoin(schema.user, eq(schema.userProfile.userId, schema.user.id))
.where(leaderboardWhere)
const total = Math.min(totalRow?.value ?? 0, LEADERBOARD_SIZE)
// 榜单封顶 100 名,所以这一页最多还能取几条只取决于 offset,**不取决于总人数** ——
// 真人不够时数据库自己会少返回。不拿 total 当上限,三段查询就能并发发出去,
// 端点延迟从「四个来回相加」变成「最慢的那个」。越界页一条不剩,直接不发 SQL。
const pageLimit = Math.max(0, Math.min(limit, LEADERBOARD_SIZE - offset))
// 末页可能只剩不足 limit 条,越界页一条不剩 —— 后者直接不发 SQL
const pageLimit = Math.max(0, Math.min(limit, total - offset))
const rows = pageLimit === 0 ? [] : await db
.select({ profile: schema.userProfile, user: schema.user }).from(schema.userProfile)
.innerJoin(schema.user, eq(schema.userProfile.userId, schema.user.id))
.where(leaderboardWhere).orderBy(...leaderboardOrder)
.limit(pageLimit).offset(offset)
// 谁在线只给老师看,学生那边整列都是 null(见 rankProfileSchema.isOnline
const [totalRow, rows, me, online] = await Promise.all([
db
.select({ value: count() })
.from(schema.userProfile)
.innerJoin(schema.user, eq(schema.userProfile.userId, schema.user.id))
.where(leaderboardWhere)
.then(([row]) => row),
pageLimit === 0
? []
: db
.select({ profile: schema.userProfile, user: schema.user })
.from(schema.userProfile)
.innerJoin(schema.user, eq(schema.userProfile.userId, schema.user.id))
.where(leaderboardWhere)
.orderBy(...leaderboardOrder)
.limit(pageLimit)
.offset(offset),
myLeaderboardRank(c.get("user")?.id),
isTeacherOrAbove(c.get("user")) ? onlineUserIds() : null,
])
return success(c, userRankSchema.parse({
results: rows.map(serializeRankRow),
total,
me: await myLeaderboardRank(c.get("user")?.id),
}))
return success(c, {
results: rows.map((row) => serializeRankRow(row, online)),
total: Math.min(totalRow?.value ?? 0, LEADERBOARD_SIZE),
me,
} satisfies UserRank)
})
function serializeRankRow({ profile, user }: {
profile: typeof schema.userProfile.$inferSelect
user: typeof schema.user.$inferSelect
}) {
return rankProfileSchema.parse({
function serializeRankRow(
{
profile,
user,
}: {
profile: typeof schema.userProfile.$inferSelect
user: typeof schema.user.$inferSelect
},
online: Set<number> | null = null,
) {
return {
id: profile.id,
user: sampleUser(user, profile.realName),
acceptedNumber: profile.acceptedNumber,
submissionNumber: profile.submissionNumber,
mood: profile.mood,
})
isOnline: online ? online.has(user.id) : null,
} satisfies RankProfile
}
/**
@@ -224,72 +318,270 @@ function serializeRankRow({ profile, user }: {
async function myLeaderboardRank(userId: number | undefined) {
if (!userId) return null
const [mine] = await db
.select({ profile: schema.userProfile, user: schema.user }).from(schema.userProfile)
.select({ profile: schema.userProfile, user: schema.user })
.from(schema.userProfile)
.innerJoin(schema.user, eq(schema.userProfile.userId, schema.user.id))
.where(and(leaderboardWhere, eq(schema.user.id, userId))).limit(1)
.where(and(leaderboardWhere, eq(schema.user.id, userId)))
.limit(1)
if (!mine) return null
const { acceptedNumber, submissionNumber } = mine.profile
const [ahead] = await db.select({ value: count() }).from(schema.userProfile)
const [ahead] = await db
.select({ value: count() })
.from(schema.userProfile)
.innerJoin(schema.user, eq(schema.userProfile.userId, schema.user.id))
.where(and(leaderboardWhere, or(
gt(schema.userProfile.acceptedNumber, acceptedNumber),
.where(
and(
eq(schema.userProfile.acceptedNumber, acceptedNumber),
lt(schema.userProfile.submissionNumber, submissionNumber),
leaderboardWhere,
or(
gt(schema.userProfile.acceptedNumber, acceptedNumber),
and(
eq(schema.userProfile.acceptedNumber, acceptedNumber),
lt(schema.userProfile.submissionNumber, submissionNumber),
),
and(
eq(schema.userProfile.acceptedNumber, acceptedNumber),
eq(schema.userProfile.submissionNumber, submissionNumber),
lt(schema.user.id, userId),
),
),
),
and(
eq(schema.userProfile.acceptedNumber, acceptedNumber),
eq(schema.userProfile.submissionNumber, submissionNumber),
lt(schema.user.id, userId),
),
)))
)
return myRankSchema.parse({
return {
...serializeRankRow(mine),
rank: (ahead?.value ?? 0) + 1,
})
} satisfies MyRank
}
accountRoutes.get("/rankings/activity", async (c) => {
const start = c.req.query("start")
if (!start || Number.isNaN(Date.parse(start))) return failure(c, 400, "invalid-start", "start time is required")
const rows = await db.select({ username: schema.submission.username, value: countDistinct(schema.submission.problemId) })
if (!start || Number.isNaN(Date.parse(start)))
return failure(c, 400, "invalid-start", "start time is required")
/**
* **user_id** user `submission.username`
* AC
* `/submissions/statistics`
*
* innerJoin user
*/
const rows = await db
.select({
username: schema.user.username,
value: countDistinct(schema.submission.problemId),
})
.from(schema.submission)
.innerJoin(schema.user, eq(schema.submission.userId, schema.user.id))
.where(and(
isNull(schema.submission.contestId),
gte(schema.submission.createTime, start),
inArray(schema.submission.result, [JudgeStatus.ACCEPTED, JudgeStatus.AST_CHECK_FAILED]),
eq(schema.user.isDisabled, false),
sql`${schema.user.adminType} <> 'Super Admin'`,
))
.groupBy(schema.submission.username).orderBy(desc(countDistinct(schema.submission.problemId))).limit(10)
return success(c, rows.map((row) => activityRankItemSchema.parse({ username: row.username, count: row.value })))
.where(
and(
isNull(schema.submission.contestId),
gte(schema.submission.createTime, start),
inArray(schema.submission.result, [
JudgeStatus.ACCEPTED,
JudgeStatus.AST_CHECK_FAILED,
]),
eq(schema.user.isDisabled, false),
ne(schema.user.adminType, "Super Admin"),
),
)
.groupBy(schema.submission.userId, schema.user.username)
.orderBy(desc(countDistinct(schema.submission.problemId)))
.limit(10)
return success(
c,
rows.map(
(row) =>
({
username: row.username,
count: row.value,
}) satisfies ActivityRankItem,
),
)
})
/**
* **`/rankings/users`
* **
* `me`
*/
const WEEKLY_BOARD_SIZE = 10
/** 算「解决」的两个状态:AST_CHECK_FAILED 也是答案对了,与 /rankings/activity 同口径 */
const ACCEPTED_RESULTS = [JudgeStatus.ACCEPTED, JudgeStatus.AST_CHECK_FAILED]
/**
* ** AC ** 0:00
*
* `/rankings/users` `user_profile`
* AC
*
*
* AC NOT EXISTS (user, problem)
* AC
* `submission_public_metrics_idx`
* user_id, problem_id, result, create_timeWHERE contest_id IS NULL
* AC退
*/
accountRoutes.get("/rankings/weekly", optionalAuth, async (c) => {
const user = c.get("user")
const scope = c.req.query("scope") === "class" ? "class" : "global"
const className = scope === "class" ? (user?.className ?? null) : null
if (scope === "class" && !className)
return failure(c, 400, "class-missing", "用户没有班级信息")
const start = weekStart()
// 入榜人群与全服榜一致(leaderboardWhere):正常状态的学生与学生管理员
const audience = and(
inArray(schema.user.adminType, [...STUDENT_ROLES]),
eq(schema.user.isDisabled, false),
className ? eq(schema.user.className, className) : undefined,
)
const thisWeek = and(
isNull(schema.submission.contestId),
gte(schema.submission.createTime, start),
audience,
)
const earlier = alias(schema.submission, "earlier")
const [solvedRows, submittedRows] = await Promise.all([
db
.select({
userId: schema.submission.userId,
username: schema.user.username,
value: countDistinct(schema.submission.problemId),
})
.from(schema.submission)
.innerJoin(schema.user, eq(schema.user.id, schema.submission.userId))
.where(
and(
thisWeek,
inArray(schema.submission.result, ACCEPTED_RESULTS),
notExists(
db
.select({ one: sql`1` })
.from(earlier)
.where(
and(
eq(earlier.userId, schema.submission.userId),
eq(earlier.problemId, schema.submission.problemId),
isNull(earlier.contestId),
inArray(earlier.result, ACCEPTED_RESULTS),
lt(earlier.createTime, start),
),
),
),
),
)
.groupBy(schema.submission.userId, schema.user.username),
db
.select({ userId: schema.submission.userId, value: count() })
.from(schema.submission)
.innerJoin(schema.user, eq(schema.user.id, schema.submission.userId))
.where(thisWeek)
.groupBy(schema.submission.userId),
])
const submissions = new Map(
submittedRows.map((row) => [row.userId, row.value]),
)
/**
* id
* 1
* postgres
*/
const ranked = solvedRows
.sort(
(a, b) =>
b.value - a.value ||
(submissions.get(a.userId) ?? 0) - (submissions.get(b.userId) ?? 0) ||
a.userId - b.userId,
)
.map(
(row, index) =>
({
user: sampleUser({ id: row.userId, username: row.username }, null),
solvedCount: row.value,
submissionCount: submissions.get(row.userId) ?? 0,
rank: index + 1,
}) satisfies WeeklyRankItem,
)
return success(c, {
start,
scope,
className,
total: ranked.length,
results: ranked.slice(0, WEEKLY_BOARD_SIZE),
me: ranked.find((row) => row.user.id === user?.id) ?? null,
} satisfies WeeklyRank)
})
accountRoutes.get("/problems/:displayId/rank", requireAuth, async (c) => {
const user = c.get("user")!
const [problem] = await db.select({ id: schema.problem.id }).from(schema.problem)
.where(and(sql`lower(${schema.problem.displayId}) = lower(${c.req.param("displayId")})`, isNull(schema.problem.contestId), eq(schema.problem.visible, true))).limit(1)
if (!problem) return failure(c, 404, "problem-not-found", "Problem does not exist")
const accepted = and(eq(schema.submission.problemId, problem.id), inArray(schema.submission.result, [0, 10]))
const [all] = await db.select({ value: countDistinct(schema.submission.userId) }).from(schema.submission).where(accepted)
const [problem] = await db
.select({ id: schema.problem.id })
.from(schema.problem)
.where(
and(
sql`lower(${schema.problem.displayId}) = lower(${c.req.param("displayId")})`,
isNull(schema.problem.contestId),
eq(schema.problem.visible, true),
),
)
.limit(1)
if (!problem)
return failure(c, 404, "problem-not-found", "Problem does not exist")
const accepted = and(
eq(schema.submission.problemId, problem.id),
inArray(schema.submission.result, [0, 10]),
)
const [all] = await db
.select({ value: countDistinct(schema.submission.userId) })
.from(schema.submission)
.where(accepted)
const className = user.className ?? ""
const classWhere = className
? and(accepted, inArray(schema.submission.userId, db.select({ id: schema.user.id }).from(schema.user).where(and(eq(schema.user.className, className), eq(schema.user.isDisabled, false)))))
? and(
accepted,
inArray(
schema.submission.userId,
db
.select({ id: schema.user.id })
.from(schema.user)
.where(
and(
eq(schema.user.className, className),
eq(schema.user.isDisabled, false),
),
),
),
)
: accepted
const [classCount] = className
? await db.select({ value: countDistinct(schema.submission.userId) }).from(schema.submission).where(classWhere)
? await db
.select({ value: countDistinct(schema.submission.userId) })
.from(schema.submission)
.where(classWhere)
: [{ value: 0 }]
const [first] = await db.select({ value: min(schema.submission.createTime) }).from(schema.submission)
const [first] = await db
.select({ value: min(schema.submission.createTime) })
.from(schema.submission)
.where(and(classWhere, eq(schema.submission.userId, user.id)))
let rank = -1
if (first?.value) {
const [rankRow] = await db.select({ value: count() }).from(schema.submission).where(and(classWhere, lte(schema.submission.createTime, first.value)))
const [rankRow] = await db
.select({ value: count() })
.from(schema.submission)
.where(and(classWhere, lte(schema.submission.createTime, first.value)))
rank = rankRow?.value ?? -1
}
return success(c, problemRankSchema.parse({ className, rank, classAcCount: classCount?.value ?? 0, allAcCount: all?.value ?? 0 }))
return success(c, {
className,
rank,
classAcCount: classCount?.value ?? 0,
allAcCount: all?.value ?? 0,
} satisfies ProblemRank)
})
/**
@@ -304,25 +596,44 @@ accountRoutes.get("/problems/:displayId/rank", requireAuth, async (c) => {
* display_ids ids
* `id_map[k]` KeyError id Map
*/
accountRoutes.post("/me/problem-display-ids/refresh", requireAuth, async (c) => {
const user = c.get("user")!
const [profile] = await db.select({ value: schema.userProfile.acmProblemsStatus }).from(schema.userProfile)
.where(eq(schema.userProfile.userId, user.id)).limit(1)
const status = objectValue(profile?.value)
const problems = objectValue(status.problems)
const ids = Object.keys(problems).map(Number).filter(Number.isInteger)
if (ids.length > 0) {
const rows = await db.select({ id: schema.problem.id, displayId: schema.problem.displayId }).from(schema.problem)
.where(and(inArray(schema.problem.id, ids), eq(schema.problem.visible, true)))
const displayIds = new Map(rows.map((row) => [String(row.id), row.displayId]))
for (const [id, value] of Object.entries(problems)) {
const item = objectValue(value)
const displayId = displayIds.get(id)
if (displayId) item._id = displayId
problems[id] = item
accountRoutes.post(
"/me/problem-display-ids/refresh",
requireAuth,
async (c) => {
const user = c.get("user")!
const [profile] = await db
.select({ value: schema.userProfile.acmProblemsStatus })
.from(schema.userProfile)
.where(eq(schema.userProfile.userId, user.id))
.limit(1)
const status = objectValue(profile?.value)
const problems = objectValue(status.problems)
const ids = Object.keys(problems).map(Number).filter(Number.isInteger)
if (ids.length > 0) {
const rows = await db
.select({ id: schema.problem.id, displayId: schema.problem.displayId })
.from(schema.problem)
.where(
and(
inArray(schema.problem.id, ids),
eq(schema.problem.visible, true),
),
)
const displayIds = new Map(
rows.map((row) => [String(row.id), row.displayId]),
)
for (const [id, value] of Object.entries(problems)) {
const item = objectValue(value)
const displayId = displayIds.get(id)
if (displayId) item._id = displayId
problems[id] = item
}
status.problems = problems
await db
.update(schema.userProfile)
.set({ acmProblemsStatus: status })
.where(eq(schema.userProfile.userId, user.id))
}
status.problems = problems
await db.update(schema.userProfile).set({ acmProblemsStatus: status }).where(eq(schema.userProfile.userId, user.id))
}
return success(c, null)
})
return success(c, null)
},
)
+113 -37
View File
@@ -1,9 +1,9 @@
import {
achievementListSchema,
achievementSchema,
achievementSummarySchema,
markAchievementsReadSchema,
pendingAchievementSchema,
type Achievement,
type AchievementList,
type AchievementSummary,
type PendingAchievement,
} from "@oj2/contract"
import { and, asc, count, desc, eq, inArray } from "drizzle-orm"
import { Hono } from "hono"
@@ -17,33 +17,60 @@ export const achievementRoutes = new Hono<AppEnv>()
async function resolveUser(requested: string | undefined, currentId: number) {
if (!requested) {
const [current] = await db.select({ id: schema.user.id, username: schema.user.username }).from(schema.user)
.where(eq(schema.user.id, currentId)).limit(1)
const [current] = await db
.select({ id: schema.user.id, username: schema.user.username })
.from(schema.user)
.where(eq(schema.user.id, currentId))
.limit(1)
return current ?? null
}
const [target] = await db.select({ id: schema.user.id, username: schema.user.username }).from(schema.user)
.where(and(eq(schema.user.username, requested), eq(schema.user.isDisabled, false))).limit(1)
const [target] = await db
.select({ id: schema.user.id, username: schema.user.username })
.from(schema.user)
.where(
and(
eq(schema.user.username, requested),
eq(schema.user.isDisabled, false),
),
)
.limit(1)
return target ?? null
}
function pendingData(row: { achievement: typeof schema.achievement.$inferSelect }) {
return pendingAchievementSchema.parse({
function pendingData(row: {
achievement: typeof schema.achievement.$inferSelect
}) {
return {
id: row.achievement.id,
name: row.achievement.name,
description: row.achievement.description,
icon: row.achievement.icon,
rarity: row.achievement.rarity,
})
} satisfies PendingAchievement
}
achievementRoutes.get("/achievements", requireAuth, async (c) => {
const target = await resolveUser(c.req.query("username"), c.get("user")!.id)
if (!target) return failure(c, 404, "user-not-found", "用户不存在")
const [achievements, unlockedRows, statRows, activeRows] = await Promise.all([
db.select().from(schema.achievement).where(eq(schema.achievement.visible, true)).orderBy(asc(schema.achievement.order), asc(schema.achievement.id)),
db.select().from(schema.userAchievement).where(eq(schema.userAchievement.userId, target.id)),
db.select({ metrics: schema.userStat.metrics }).from(schema.userStat).where(eq(schema.userStat.userId, target.id)).limit(1),
db.select({ value: count() }).from(schema.user).where(eq(schema.user.isDisabled, false)),
db
.select()
.from(schema.achievement)
.where(eq(schema.achievement.visible, true))
.orderBy(asc(schema.achievement.order), asc(schema.achievement.id)),
db
.select()
.from(schema.userAchievement)
.where(eq(schema.userAchievement.userId, target.id)),
db
.select({ metrics: schema.userStat.metrics })
.from(schema.userStat)
.where(eq(schema.userStat.userId, target.id))
.limit(1),
db
.select({ value: count() })
.from(schema.user)
.where(eq(schema.user.isDisabled, false)),
])
const unlocked = new Map(unlockedRows.map((row) => [row.achievementId, row]))
const metrics = objectValue(statRows[0]?.metrics)
@@ -52,7 +79,7 @@ achievementRoutes.get("/achievements", requireAuth, async (c) => {
const record = unlocked.get(achievement.id)
const masked = achievement.hidden && !record
const progress = metrics[achievement.metric]
return achievementSchema.parse({
return {
id: achievement.id,
name: masked ? "???" : achievement.name,
description: masked ? "达成条件保密" : achievement.description,
@@ -66,56 +93,105 @@ achievementRoutes.get("/achievements", requireAuth, async (c) => {
unlockTime: record?.unlockTime ?? null,
backfilled: record?.backfilled ?? false,
progress: masked ? null : typeof progress === "number" ? progress : 0,
unlockRate: active > 0 ? Math.round(achievement.unlockCount / active * 1000) / 10 : 0,
})
unlockRate:
active > 0
? Math.round((achievement.unlockCount / active) * 1000) / 10
: 0,
} satisfies Achievement
})
return success(c, achievementListSchema.parse({ username: target.username, achievements: result }))
return success(c, {
username: target.username,
achievements: result,
} satisfies AchievementList)
})
achievementRoutes.get("/achievements/summary", requireAuth, async (c) => {
const target = await resolveUser(c.req.query("username"), c.get("user")!.id)
if (!target) return failure(c, 404, "user-not-found", "用户不存在")
const [achievements, unlockedRows] = await Promise.all([
db.select({ id: schema.achievement.id, rarity: schema.achievement.rarity }).from(schema.achievement).where(eq(schema.achievement.visible, true)),
db.select({ record: schema.userAchievement, achievement: schema.achievement }).from(schema.userAchievement)
.innerJoin(schema.achievement, eq(schema.userAchievement.achievementId, schema.achievement.id))
.where(and(eq(schema.userAchievement.userId, target.id), eq(schema.achievement.visible, true))).orderBy(desc(schema.userAchievement.unlockTime)),
db
.select({ id: schema.achievement.id, rarity: schema.achievement.rarity })
.from(schema.achievement)
.where(eq(schema.achievement.visible, true)),
db
.select({
record: schema.userAchievement,
achievement: schema.achievement,
})
.from(schema.userAchievement)
.innerJoin(
schema.achievement,
eq(schema.userAchievement.achievementId, schema.achievement.id),
)
.where(
and(
eq(schema.userAchievement.userId, target.id),
eq(schema.achievement.visible, true),
),
)
.orderBy(desc(schema.userAchievement.unlockTime)),
])
const labels = { bronze: "青铜", silver: "白银", gold: "黄金", platinum: "白金" }
const labels = {
bronze: "青铜",
silver: "白银",
gold: "黄金",
platinum: "白金",
}
const rarities = ["bronze", "silver", "gold", "platinum"] as const
const total = achievements.length
const unlocked = unlockedRows.length
return success(c, achievementSummarySchema.parse({
return success(c, {
username: target.username,
total,
unlocked,
percent: total > 0 ? Math.round(unlocked / total * 1000) / 10 : 0,
percent: total > 0 ? Math.round((unlocked / total) * 1000) / 10 : 0,
rarity: rarities.map((rarity) => ({
rarity,
label: labels[rarity],
total: achievements.filter((item) => item.rarity === rarity).length,
unlocked: unlockedRows.filter((item) => item.achievement.rarity === rarity).length,
unlocked: unlockedRows.filter(
(item) => item.achievement.rarity === rarity,
).length,
})),
recent: unlockedRows.slice(0, 10).map(pendingData),
}))
} satisfies AchievementSummary)
})
achievementRoutes.get("/achievements/pending", requireAuth, async (c) => {
const rows = await db.select({ record: schema.userAchievement, achievement: schema.achievement })
.from(schema.userAchievement).innerJoin(schema.achievement, eq(schema.userAchievement.achievementId, schema.achievement.id))
.where(and(eq(schema.userAchievement.userId, c.get("user")!.id), eq(schema.userAchievement.notified, false), eq(schema.achievement.visible, true)))
const rows = await db
.select({ record: schema.userAchievement, achievement: schema.achievement })
.from(schema.userAchievement)
.innerJoin(
schema.achievement,
eq(schema.userAchievement.achievementId, schema.achievement.id),
)
.where(
and(
eq(schema.userAchievement.userId, c.get("user")!.id),
eq(schema.userAchievement.notified, false),
eq(schema.achievement.visible, true),
),
)
.orderBy(asc(schema.userAchievement.unlockTime))
return success(c, rows.map(pendingData))
})
achievementRoutes.post("/achievements/pending/read", requireAuth, async (c) => {
const parsed = markAchievementsReadSchema.safeParse(await c.req.json().catch(() => null))
if (!parsed.success) return failure(c, 400, "invalid-request", "Invalid achievement ids")
const parsed = markAchievementsReadSchema.safeParse(
await c.req.json().catch(() => null),
)
if (!parsed.success)
return failure(c, 400, "invalid-request", "Invalid achievement ids")
if (parsed.data.ids.length > 0) {
await db.update(schema.userAchievement).set({ notified: true }).where(and(
eq(schema.userAchievement.userId, c.get("user")!.id),
inArray(schema.userAchievement.achievementId, parsed.data.ids),
))
await db
.update(schema.userAchievement)
.set({ notified: true })
.where(
and(
eq(schema.userAchievement.userId, c.get("user")!.id),
inArray(schema.userAchievement.achievementId, parsed.data.ids),
),
)
}
return success(c, null)
})
+448 -137
View File
@@ -1,23 +1,40 @@
import {
adminUserListSchema,
adminUserRankSchema,
adminUserSchema,
adminTypeSchema,
deleteUsersRequestSchema,
importUsersRequestSchema,
rankProfileSchema,
resetPasswordResponseSchema,
STUDENT_ROLES,
updateUserRequestSchema,
type AdminType,
type AdminUser,
type AdminUserList,
type AdminUserRank,
type ProblemPermission,
type RankProfile,
type ResetPasswordResponse,
} from "@oj2/contract"
import { randomInt } from "node:crypto"
import { and, asc, count, desc, eq, ilike, inArray, ne, or, sql } from "drizzle-orm"
import { z } from "zod"
import {
and,
asc,
count,
desc,
eq,
ilike,
inArray,
ne,
or,
sql,
} from "drizzle-orm"
import { Hono } from "hono"
import { hashPassword } from "../../auth/password"
import { isUserOnline, onlineUserIds } from "../../auth/presence"
import { revokeUserSessions } from "../../auth/session"
import { requireSuperAdmin, type AppEnv } from "../../auth/middleware"
import { db, schema } from "../../db"
import { failure, success } from "../../http"
import { queryInteger, sampleUser } from "../helpers"
import { publishSessionRevoked } from "../../events"
export const adminAccountRoutes = new Hono<AppEnv>()
@@ -32,11 +49,16 @@ const CLASS_NAME_MAX_DIGITS = 4
* `ks251001` 4
* `account/views/admin.py:get_class_name`
*/
function classNameOf(username: string): { ok: true; value: string | null } | { ok: false; message: string } {
function classNameOf(
username: string,
): { ok: true; value: string | null } | { ok: false; message: string } {
const matched = /^ks(\d+)/.exec(username)
if (!matched) return { ok: true, value: null }
const digits = matched[1]!
if (digits.length < CLASS_NAME_MIN_DIGITS || digits.length > CLASS_NAME_MAX_DIGITS) {
if (
digits.length < CLASS_NAME_MIN_DIGITS ||
digits.length > CLASS_NAME_MAX_DIGITS
) {
return {
ok: false,
message: `用户名 ${username} 的班级号 ${digits}${digits.length} 位,必须是 ${CLASS_NAME_MIN_DIGITS}~${CLASS_NAME_MAX_DIGITS} 位数字`,
@@ -50,17 +72,23 @@ function classNameOf(username: string): { ok: true; value: string | null } | { o
* All None Own
* All
*/
function normalizePermission(adminType: string, requested: string) {
function normalizePermission(
adminType: AdminType,
requested: ProblemPermission,
): ProblemPermission {
if (adminType === "Super Admin") return "All"
if (adminType === "Regular User") return "None"
return requested || "Own"
}
function serialize(row: {
user: typeof schema.user.$inferSelect
realName: string | null
}) {
return adminUserSchema.parse({
function serialize(
row: {
user: typeof schema.user.$inferSelect
realName: string | null
},
isOnline: boolean,
) {
return {
id: row.user.id,
username: row.user.username,
email: row.user.email,
@@ -69,18 +97,20 @@ function serialize(row: {
realName: row.realName,
createTime: row.user.createTime,
lastLogin: row.user.lastLogin,
openApi: row.user.openApi,
isDisabled: row.user.isDisabled,
isOnline,
rawPassword: row.user.rawPassword,
className: row.user.className,
})
} satisfies AdminUser
}
function selectUser(id: number) {
return db.select({ user: schema.user, realName: schema.userProfile.realName })
return db
.select({ user: schema.user, realName: schema.userProfile.realName })
.from(schema.user)
.leftJoin(schema.userProfile, eq(schema.userProfile.userId, schema.user.id))
.where(eq(schema.user.id, id)).limit(1)
.where(eq(schema.user.id, id))
.limit(1)
}
/**
@@ -98,34 +128,47 @@ adminAccountRoutes.get("/rankings/users", requireSuperAdmin, async (c) => {
const offset = queryInteger(c.req.query("offset"), 0, { min: 0 })
const keyword = c.req.query("keyword")?.trim()
const where = and(
inArray(schema.user.adminType, ["Regular User", "Student Admin"]),
inArray(schema.user.adminType, [...STUDENT_ROLES]),
eq(schema.user.isDisabled, false),
keyword ? ilike(schema.user.username, `%${keyword}%`) : undefined,
)
const [totalRows, rows] = await Promise.all([
db.select({ value: count() }).from(schema.userProfile)
.innerJoin(schema.user, eq(schema.userProfile.userId, schema.user.id)).where(where),
db.select({ profile: schema.userProfile, user: schema.user }).from(schema.userProfile)
.innerJoin(schema.user, eq(schema.userProfile.userId, schema.user.id)).where(where)
db
.select({ value: count() })
.from(schema.userProfile)
.innerJoin(schema.user, eq(schema.userProfile.userId, schema.user.id))
.where(where),
db
.select({ profile: schema.userProfile, user: schema.user })
.from(schema.userProfile)
.innerJoin(schema.user, eq(schema.userProfile.userId, schema.user.id))
.where(where)
.orderBy(
desc(schema.userProfile.acceptedNumber),
asc(schema.userProfile.submissionNumber),
asc(schema.user.id),
)
.limit(limit).offset(offset),
.limit(limit)
.offset(offset),
])
return success(c, adminUserRankSchema.parse({
results: rows.map(({ profile, user }) => rankProfileSchema.parse({
id: profile.id,
user: sampleUser(user, profile.realName),
acceptedNumber: profile.acceptedNumber,
submissionNumber: profile.submissionNumber,
mood: profile.mood,
})),
return success(c, {
results: rows.map(
({ profile, user }) =>
({
id: profile.id,
user: sampleUser(user, profile.realName),
acceptedNumber: profile.acceptedNumber,
submissionNumber: profile.submissionNumber,
mood: profile.mood,
// 这张榜不下发在线状态(null = 「调用方不该知道」,见契约里 isOnline 的注释)。
// 原来是靠 schema 的 .default(null) 填出来的,改成显式写死。
isOnline: null,
}) satisfies RankProfile,
),
total: totalRows[0]?.value ?? 0,
}))
} satisfies AdminUserRank)
})
adminAccountRoutes.get("/users", requireSuperAdmin, async (c) => {
@@ -134,59 +177,117 @@ adminAccountRoutes.get("/users", requireSuperAdmin, async (c) => {
const filters = []
const type = c.req.query("type")?.trim()
const keyword = c.req.query("keyword")?.trim()
if (type) filters.push(eq(schema.user.adminType, type))
if (type) {
// 以前这里直接把 query 塞进 eq(),传个不存在的角色名只会静默返回空列表。
// 列加了 $type 之后编译器会拦下来,顺势改成校验:前端的下拉只有这四个值。
const parsedType = adminTypeSchema.safeParse(type)
if (!parsedType.success)
return failure(c, 400, "invalid-request", "角色筛选值不合法")
filters.push(eq(schema.user.adminType, parsedType.data))
}
if (keyword) {
filters.push(or(
ilike(schema.user.username, `%${keyword}%`),
ilike(schema.userProfile.realName, `%${keyword}%`),
ilike(schema.user.email, `%${keyword}%`),
)!)
filters.push(
or(
ilike(schema.user.username, `%${keyword}%`),
ilike(schema.userProfile.realName, `%${keyword}%`),
ilike(schema.user.email, `%${keyword}%`),
)!,
)
}
const where = filters.length ? and(...filters) : undefined
// 在线状态每行都要下发(列表里显示),所以不管怎么排都先取一次
const online = await onlineUserIds()
const orderBy = c.req.query("orderBy")
// 「最近登录」排序要把从未登录的排在最后,否则一堆 null 顶在最前面,这个排序就没用了
const order = c.req.query("orderBy") === "-lastLogin"
? [sql`${schema.user.lastLogin} desc nulls last`]
: [desc(schema.user.createTime)]
//
// 「在线优先」没有对应的库表列 —— 在线只存在于 Redis,所以把在线的 id 捞出来
// 在 SQL 里分两档;档内仍按最近登录排,这样一屏离线用户之间还是有意义的顺序。
// 没人在线时那个 case 恒等于 1,直接省掉(inArray 拿空数组也不合法)。
const order =
orderBy === "-online"
? [
...(online.size
? [
sql`case when ${inArray(schema.user.id, [...online])} then 0 else 1 end`,
]
: []),
sql`${schema.user.lastLogin} desc nulls last`,
]
: orderBy === "-lastLogin"
? [sql`${schema.user.lastLogin} desc nulls last`]
: [desc(schema.user.createTime)]
const [totalRows, rows] = await Promise.all([
db.select({ value: count() }).from(schema.user)
.leftJoin(schema.userProfile, eq(schema.userProfile.userId, schema.user.id)).where(where),
db.select({ user: schema.user, realName: schema.userProfile.realName }).from(schema.user)
.leftJoin(schema.userProfile, eq(schema.userProfile.userId, schema.user.id)).where(where)
.orderBy(...order, asc(schema.user.id)).limit(limit).offset(offset),
db
.select({ value: count() })
.from(schema.user)
.leftJoin(
schema.userProfile,
eq(schema.userProfile.userId, schema.user.id),
)
.where(where),
db
.select({ user: schema.user, realName: schema.userProfile.realName })
.from(schema.user)
.leftJoin(
schema.userProfile,
eq(schema.userProfile.userId, schema.user.id),
)
.where(where)
.orderBy(...order, asc(schema.user.id))
.limit(limit)
.offset(offset),
])
return success(c, adminUserListSchema.parse({
results: rows.map(serialize),
return success(c, {
results: rows.map((row) => serialize(row, online.has(row.user.id))),
total: totalRows[0]?.value ?? 0,
}))
} satisfies AdminUserList)
})
adminAccountRoutes.get("/users/:id", requireSuperAdmin, async (c) => {
const [row] = await selectUser(queryInteger(c.req.param("id"), 0, { min: 1 }))
if (!row) return failure(c, 404, "user-not-found", "User does not exist")
return success(c, serialize(row))
return success(c, serialize(row, await isUserOnline(row.user.id)))
})
adminAccountRoutes.put("/users/:id", requireSuperAdmin, async (c) => {
const id = queryInteger(c.req.param("id"), 0, { min: 1 })
const parsed = updateUserRequestSchema.safeParse(await c.req.json().catch(() => null))
const parsed = updateUserRequestSchema.safeParse(
await c.req.json().catch(() => null),
)
if (!parsed.success) {
return failure(c, 400, "invalid-request", parsed.error.issues[0]?.message ?? "Invalid payload")
return failure(
c,
400,
"invalid-request",
parsed.error.issues[0]?.message ?? "Invalid payload",
)
}
const data = parsed.data
const [existing] = await selectUser(id)
if (!existing) return failure(c, 404, "user-not-found", "User does not exist")
const username = data.username.toLowerCase()
const email = data.email.toLowerCase()
const username = data.username.trim().toLowerCase()
const email = data.email.trim().toLowerCase()
const className = classNameOf(username)
if (!className.ok) return failure(c, 400, "invalid-class-name", className.message)
if (!className.ok)
return failure(c, 400, "invalid-class-name", className.message)
const [dupUsername] = await db.select({ id: schema.user.id }).from(schema.user)
.where(and(eq(schema.user.username, username), ne(schema.user.id, id))).limit(1)
if (dupUsername) return failure(c, 409, "username-exists", "Username already exists")
const [dupEmail] = await db.select({ id: schema.user.id }).from(schema.user)
.where(and(eq(schema.user.email, email), ne(schema.user.id, id))).limit(1)
const [dupUsername] = await db
.select({ id: schema.user.id })
.from(schema.user)
.where(and(eq(schema.user.username, username), ne(schema.user.id, id)))
.limit(1)
if (dupUsername)
return failure(c, 409, "username-exists", "Username already exists")
// 比 lower(email):存量数据里有大小写混着的邮箱,按原值比会漏掉冲突
const [dupEmail] = await db
.select({ id: schema.user.id })
.from(schema.user)
.where(
and(sql`lower(${schema.user.email}) = ${email}`, ne(schema.user.id, id)),
)
.limit(1)
if (dupEmail) return failure(c, 409, "email-exists", "Email already exists")
const patch: Partial<typeof schema.user.$inferInsert> = {
@@ -195,7 +296,10 @@ adminAccountRoutes.put("/users/:id", requireSuperAdmin, async (c) => {
className: className.value,
adminType: data.adminType,
isDisabled: data.isDisabled,
problemPermission: normalizePermission(data.adminType, data.problemPermission),
problemPermission: normalizePermission(
data.adminType,
data.problemPermission,
),
}
if (data.password) {
// 与旧 User.set_password 一致:哈希与明文一起写。明文是有意保留的运营需求,
@@ -203,128 +307,335 @@ adminAccountRoutes.put("/users/:id", requireSuperAdmin, async (c) => {
patch.password = await hashPassword(data.password)
patch.rawPassword = data.password
}
if (data.openApi) {
// 已经开着就不重置 appkey,否则每次保存用户都会把对方的 key 换掉
if (!existing.user.openApi) patch.openApiAppkey = randomBytes32()
} else {
patch.openApiAppkey = null
}
patch.openApi = data.openApi
await db.transaction(async (tx) => {
await tx.update(schema.user).set(patch).where(eq(schema.user.id, id))
// submission.username 是冗余列(判题历史按用户名查),改名后必须一起改,否则历史提交查不到
/**
* submission.username
*
* **user_id**
* 726
*
* user_id
*
* user
* 退
*/
if (existing.user.username !== username) {
await tx.update(schema.submission).set({ username })
.where(eq(schema.submission.username, existing.user.username))
await tx
.update(schema.submission)
.set({ username })
.where(eq(schema.submission.userId, id))
}
await tx.update(schema.userProfile).set({ realName: data.realName })
await tx
.update(schema.userProfile)
.set({ realName: data.realName })
.where(eq(schema.userProfile.userId, id))
})
// 禁用只改数据库这一列,不动 Redis 里的会话 —— 那个学生挂着的 WebSocket
// 靠会话巡检永远发现不了(token 还是好的),只能在这里主动断
// 禁用只改数据库这一列,会话在 Redis 里还好好的 —— 那个学生挂着的 WebSocket
// 靠会话巡检永远发现不了(token 还是好的),只能在这里主动断
//
// 改密码同样要吊销:不删旧会话的话,「给被盗用的账号改个密码」这个动作对已经
// 登着的那一方毫无作用,他能一直用到会话自然过期。两件事都发生时按禁用报,
// 学生看到的提示更贴近实际。
if (data.isDisabled && !existing.user.isDisabled) {
await publishSessionRevoked({ userId: id }, "account-disabled")
await revokeUserSessions(id, "account-disabled")
} else if (data.password) {
await revokeUserSessions(id, "session-ended")
}
const [row] = await selectUser(id)
return success(c, serialize(row!))
return success(c, serialize(row!, await isUserOnline(id)))
})
adminAccountRoutes.post("/users", requireSuperAdmin, async (c) => {
const parsed = importUsersRequestSchema.safeParse(await c.req.json().catch(() => null))
const parsed = importUsersRequestSchema.safeParse(
await c.req.json().catch(() => null),
)
if (!parsed.success) {
return failure(c, 400, "invalid-request", parsed.error.issues[0]?.message ?? "Invalid payload")
return failure(
c,
400,
"invalid-request",
parsed.error.issues[0]?.message ?? "Invalid payload",
)
}
const rows = parsed.data.users
const prepared: { username: string; password: string; raw: string; email: string; realName: string; className: string | null }[] = []
type Prepared = {
username: string
password: string
raw: string
email: string
realName: string
className: string | null
}
// 先把不花钱的校验全做完,再动 argon2。班级号错、用户名重复这两种情况占了失败的绝大多数
// (老师习惯把同一份名单粘两次),先算哈希的话要白等一整个班的 argon2 才看到报错。
//
// 用户名和邮箱都归一成小写:登录是 `lower(username) = lower(?)` 比的,注册和
// PUT /users/:id 也都存小写。只有这条导入路径原样存,于是 `ks251Ab` 能绕过下面的
// 查重建出第二个账号,两个人登录时撞成同一条记录。
const prepared: Prepared[] = []
for (const [username, password, email, realName] of rows) {
const className = classNameOf(username)
if (!className.ok) return failure(c, 400, "invalid-class-name", className.message)
const name = username.toLowerCase()
const className = classNameOf(name)
if (!className.ok)
return failure(c, 400, "invalid-class-name", className.message)
const mail = email.trim().toLowerCase()
// 邮箱在本站是唯一的(注册和 PUT /users/:id 两条路都查重),唯独导入这条以前
// 什么都不查 —— 而前端生成的占位邮箱按「班级+批内序号」拼,同一个班导第二批
// 必然重号。存进去不会报错(库里没有唯一约束),但这两个账号从此**编辑不了**:
// PUT 一保存就撞自己的查重回 409,老师只看到「Email already exists」。
if (!z.email().max(64).safeParse(mail).success) {
return failure(
c,
400,
"invalid-email",
`用户 ${name} 的邮箱 ${mail || "(空)"} 不是合法邮箱`,
)
}
prepared.push({
username,
password: await hashPassword(password),
username: name,
password: "",
raw: password,
email,
email: mail,
realName,
className: className.value,
})
}
const existing = await db.select({ username: schema.user.username }).from(schema.user)
.where(inArray(schema.user.username, prepared.map((item) => item.username)))
if (existing.length) {
return failure(c, 409, "username-exists", `用户名已存在:${existing.map((row) => row.username).join("、")}`)
const dupInBatch = (values: string[]) => {
const seen = new Set<string>()
return [
...new Set(values.filter((value) => seen.size === seen.add(value).size)),
]
}
const batchNames = dupInBatch(prepared.map((item) => item.username))
if (batchNames.length) {
return failure(
c,
409,
"username-exists",
`这批名单里用户名重复:${batchNames.join("、")}`,
)
}
const batchMails = dupInBatch(prepared.map((item) => item.email))
if (batchMails.length) {
return failure(
c,
409,
"email-exists",
`这批名单里邮箱重复:${batchMails.join("、")}`,
)
}
const existing = await db
.select({ username: schema.user.username, email: schema.user.email })
.from(schema.user)
.where(
or(
inArray(
schema.user.username,
prepared.map((item) => item.username),
),
inArray(
sql`lower(${schema.user.email})`,
prepared.map((item) => item.email),
),
),
)
const takenNames = new Set(prepared.map((item) => item.username))
const clashNames = existing
.filter((row) => takenNames.has(row.username))
.map((row) => row.username)
if (clashNames.length) {
return failure(
c,
409,
"username-exists",
`用户名已存在:${clashNames.join("、")}`,
)
}
const takenMails = new Set(prepared.map((item) => item.email))
const clashMails = existing
.map((row) => row.email?.toLowerCase())
.filter((mail): mail is string => !!mail && takenMails.has(mail))
if (clashMails.length) {
return failure(
c,
409,
"email-exists",
`邮箱已被占用:${[...new Set(clashMails)].join("、")}`,
)
}
// argon2id 是**故意**做慢的,串行 await 的话一个班要转好几秒。但也不能 Promise.all
// 全量:每次哈希占 m=19MiB(见 auth/password.ts 的 ARGON2_OPTIONS),一个年级 300 人
// 同时开就是 5.7GB,而 oj-api 的 mem_limit 只有 512mdocker/compose.debian.yml)。
// 固定 4 路并发,瞬时峰值 76MiB 封顶。
const HASH_CONCURRENCY = 4
let cursor = 0
await Promise.all(
Array.from(
{ length: Math.min(HASH_CONCURRENCY, prepared.length) },
async () => {
while (cursor < prepared.length) {
const item = prepared[cursor++]!
item.password = await hashPassword(item.raw)
}
},
),
)
// 整批要么全进要么全不进 —— 导入是粘一整个班的名单,进了一半再重试会撞已存在
const created = await db.transaction(async (tx) => {
const users = await tx.insert(schema.user).values(prepared.map((item) => ({
username: item.username,
password: item.password,
rawPassword: item.raw,
email: item.email,
className: item.className,
adminType: "Regular User",
problemPermission: "None",
createTime: new Date().toISOString(),
openApi: false,
isDisabled: false,
sessionKeys: [],
}))).returning({ id: schema.user.id, username: schema.user.username })
const users = await tx
.insert(schema.user)
.values(
prepared.map((item) => ({
username: item.username,
password: item.password,
rawPassword: item.raw,
email: item.email,
className: item.className,
adminType: "Regular User" as const,
problemPermission: "None" as const,
createTime: new Date().toISOString(),
isDisabled: false,
})),
)
.returning({ id: schema.user.id, username: schema.user.username })
const byName = new Map(users.map((row) => [row.username, row.id]))
await tx.insert(schema.userProfile).values(prepared.map((item) => ({
userId: byName.get(item.username)!,
realName: item.realName,
// avatar 是 notNull 且无默认值,必须显式给;路径与旧 UserProfile.avatar 的默认值一致
avatar: "/public/avatar/default.png",
acmProblemsStatus: {},
submissionNumber: 0,
acceptedNumber: 0,
})))
await tx.insert(schema.userProfile).values(
prepared.map((item) => ({
userId: byName.get(item.username)!,
realName: item.realName,
// avatar 是 notNull 且无默认值,必须显式给;路径与旧 UserProfile.avatar 的默认值一致
avatar: "/public/avatar/default.png",
acmProblemsStatus: {},
submissionNumber: 0,
acceptedNumber: 0,
})),
)
return users.length
})
return success(c, { imported: created }, 201)
})
/**
* PostgresError 23503 cause drizzle 0.45
* DrizzleQueryError`error.code` undefined
* 500
*/
function isForeignKeyViolation(error: unknown) {
for (
let current = error;
current;
current = (current as { cause?: unknown }).cause
) {
if ((current as { code?: string }).code === "23503") return true
}
return false
}
/** 「这人还有提交」的信号。提交那张表没有外键,拦不住,只能自己查出来再把事务掀了 */
class UserHasSubmissionsError extends Error {}
adminAccountRoutes.delete("/users", requireSuperAdmin, async (c) => {
const parsed = deleteUsersRequestSchema.safeParse(await c.req.json().catch(() => null))
if (!parsed.success) return failure(c, 400, "invalid-request", "ids is required")
const parsed = deleteUsersRequestSchema.safeParse(
await c.req.json().catch(() => null),
)
if (!parsed.success)
return failure(c, 400, "invalid-request", "ids is required")
const me = c.get("user")!.id
if (parsed.data.ids.includes(me)) {
return failure(c, 400, "cannot-delete-self", "Current user can not be deleted")
return failure(
c,
400,
"cannot-delete-self",
"Current user can not be deleted",
)
}
// 用户是被引用最广的一张表(提交、题目、比赛、公告……),级联删除牵连太大,
// 旧后端靠 Django 的应用层级联硬删。这里不复刻那个行为,改为让数据库拦下来:
// 撞外键说明该用户还有历史数据,应当禁用而不是删除。
//
// 所以 0010 那一批 CASCADE **有意跳过了 user 的绝大多数外键**:成就、表情、题单进度、
// AI 分析、站内信全都继续拦着。只有 user_profile 和 user_stat 走 CASCADE ——
// 一个是一对一附属、一个是可重算的统计缓存,都不构成「这人做过什么」的证据。
// 别顺手把这里也改成全 CASCADEsubmission.user_id 压根没有外键(Django 那边就是个
// 裸 IntegerField),全连坐的结果是成就没了、提交却留成孤儿行,一半删一半留。
try {
const deleted = await db.transaction(async (tx) => {
await tx.delete(schema.userProfile).where(inArray(schema.userProfile.userId, parsed.data.ids))
return tx.delete(schema.user).where(inArray(schema.user.id, parsed.data.ids))
/**
* ****
* `submission.user_id` Django IntegerField
*
*
* `submission.user_id` id
* 28 935
*
*
* delete
*/
const [withSubmission] = await tx
.select({ userId: schema.submission.userId })
.from(schema.submission)
.where(inArray(schema.submission.userId, parsed.data.ids))
.limit(1)
if (withSubmission) throw new UserHasSubmissionsError()
return tx
.delete(schema.user)
.where(inArray(schema.user.id, parsed.data.ids))
.returning({ id: schema.user.id })
})
return success(c, { deleted: deleted.length })
} catch {
return failure(c, 409, "user-in-use", "该用户还有提交、题目等历史数据,无法删除;请改为禁用账号")
} catch (error) {
// 只有外键冲突(23503)和上面那条提交检查才是「这人还有历史数据」。以前这里是裸
// catch,连接断了、语句超时也照报这句,超管会照着提示去禁用账号,真正的故障一直没人看见
if (
!(error instanceof UserHasSubmissionsError) &&
!isForeignKeyViolation(error)
)
throw error
return failure(
c,
409,
"user-in-use",
"该用户还有提交、题目等历史数据,无法删除;请改为禁用账号",
)
}
})
adminAccountRoutes.post("/users/:id/reset-password", requireSuperAdmin, async (c) => {
const id = queryInteger(c.req.param("id"), 0, { min: 1 })
const [existing] = await db.select({ id: schema.user.id }).from(schema.user)
.where(eq(schema.user.id, id)).limit(1)
if (!existing) return failure(c, 404, "user-not-found", "User does not exist")
// 6 位随机数字、不含 0,与旧后端一致:学生要照着念、要手输,0 和 O 分不清
const password = Array.from({ length: 6 }, () => "123456789"[randomInt(9)]).join("")
await db.update(schema.user).set({
password: await hashPassword(password),
rawPassword: password,
}).where(eq(schema.user.id, id))
return success(c, resetPasswordResponseSchema.parse({ password }))
})
function randomBytes32() {
return Array.from({ length: 32 }, () =>
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"[randomInt(62)]).join("")
}
adminAccountRoutes.post(
"/users/:id/reset-password",
requireSuperAdmin,
async (c) => {
const id = queryInteger(c.req.param("id"), 0, { min: 1 })
const [existing] = await db
.select({ id: schema.user.id })
.from(schema.user)
.where(eq(schema.user.id, id))
.limit(1)
if (!existing)
return failure(c, 404, "user-not-found", "User does not exist")
// 6 位随机数字、不含 0,与旧后端一致:学生要照着念、要手输,0 和 O 分不清
const password = Array.from(
{ length: 6 },
() => "123456789"[randomInt(9)],
).join("")
await db
.update(schema.user)
.set({
password: await hashPassword(password),
rawPassword: password,
})
.where(eq(schema.user.id, id))
// 旧密码登出来的会话立刻作废,理由同 PUT /users/:id
await revokeUserSessions(id, "session-ended")
return success(c, { password } satisfies ResetPasswordResponse)
},
)
+117 -56
View File
@@ -1,8 +1,8 @@
import {
achievementMetricSchema,
adminAchievementSchema,
createAchievementRequestSchema,
updateAchievementRequestSchema,
type AchievementMetric,
type AdminAchievement,
} from "@oj2/contract"
import { asc, eq } from "drizzle-orm"
import { Hono } from "hono"
@@ -10,14 +10,18 @@ import { Hono } from "hono"
import { requireSuperAdmin, type AppEnv } from "../../auth/middleware"
import { db, schema } from "../../db"
import { failure, success } from "../../http"
import { ACHIEVEMENT_METRICS, findMetric, metricName } from "../../services/achievement-metrics"
import {
ACHIEVEMENT_METRICS,
findMetric,
metricName,
} from "../../services/achievement-metrics"
import { rescanAchievement } from "../../services/achievements"
import { queryInteger } from "../helpers"
export const adminAchievementRoutes = new Hono<AppEnv>()
function serialize(row: typeof schema.achievement.$inferSelect) {
return adminAchievementSchema.parse({
return {
id: row.id,
name: row.name,
description: row.description,
@@ -32,83 +36,140 @@ function serialize(row: typeof schema.achievement.$inferSelect) {
unlockCount: row.unlockCount,
order: row.order,
createTime: row.createTime,
})
} satisfies AdminAchievement
}
/** 下拉框的可选项就是代码里注册了什么,见 services/achievement-metrics.ts 的说明 */
adminAchievementRoutes.get("/achievement-metrics", requireSuperAdmin, (c) =>
success(c, ACHIEVEMENT_METRICS.map((item) => achievementMetricSchema.parse(item))))
success(c, ACHIEVEMENT_METRICS satisfies AchievementMetric[]),
)
adminAchievementRoutes.get("/achievements", requireSuperAdmin, async (c) => {
const rows = await db.select().from(schema.achievement)
const rows = await db
.select()
.from(schema.achievement)
.orderBy(asc(schema.achievement.order), asc(schema.achievement.id))
return success(c, rows.map(serialize))
})
adminAchievementRoutes.get("/achievements/:id", requireSuperAdmin, async (c) => {
const [row] = await db.select().from(schema.achievement)
.where(eq(schema.achievement.id, queryInteger(c.req.param("id"), 0, { min: 1 }))).limit(1)
if (!row) return failure(c, 404, "achievement-not-found", "成就不存在")
return success(c, serialize(row))
})
adminAchievementRoutes.get(
"/achievements/:id",
requireSuperAdmin,
async (c) => {
const [row] = await db
.select()
.from(schema.achievement)
.where(
eq(
schema.achievement.id,
queryInteger(c.req.param("id"), 0, { min: 1 }),
),
)
.limit(1)
if (!row) return failure(c, 404, "achievement-not-found", "成就不存在")
return success(c, serialize(row))
},
)
adminAchievementRoutes.post("/achievements", requireSuperAdmin, async (c) => {
const parsed = createAchievementRequestSchema.safeParse(await c.req.json().catch(() => null))
const parsed = createAchievementRequestSchema.safeParse(
await c.req.json().catch(() => null),
)
if (!parsed.success) {
return failure(c, 400, "invalid-request", parsed.error.issues[0]?.message ?? "参数错误")
return failure(
c,
400,
"invalid-request",
parsed.error.issues[0]?.message ?? "参数错误",
)
}
if (!findMetric(parsed.data.metric)) return failure(c, 400, "invalid-metric", "指标不存在")
if (!findMetric(parsed.data.metric))
return failure(c, 400, "invalid-metric", "指标不存在")
const [created] = await db.insert(schema.achievement).values({
...parsed.data,
unlockCount: 0,
createTime: new Date().toISOString(),
}).returning()
const [created] = await db
.insert(schema.achievement)
.values({
...parsed.data,
unlockCount: 0,
createTime: new Date().toISOString(),
})
.returning()
// 新建的成就要补发给已达标的存量用户,否则「AC 满 10 题」这种成就
// 只有从今往后的提交才算,老用户永远拿不到
await rescanAchievement(created!.id)
const [row] = await db.select().from(schema.achievement).where(eq(schema.achievement.id, created!.id)).limit(1)
const [row] = await db
.select()
.from(schema.achievement)
.where(eq(schema.achievement.id, created!.id))
.limit(1)
return success(c, serialize(row!), 201)
})
adminAchievementRoutes.put("/achievements/:id", requireSuperAdmin, async (c) => {
const id = queryInteger(c.req.param("id"), 0, { min: 1 })
const parsed = updateAchievementRequestSchema.safeParse(await c.req.json().catch(() => null))
if (!parsed.success) {
return failure(c, 400, "invalid-request", parsed.error.issues[0]?.message ?? "参数错误")
}
if (!findMetric(parsed.data.metric)) return failure(c, 400, "invalid-metric", "指标不存在")
adminAchievementRoutes.put(
"/achievements/:id",
requireSuperAdmin,
async (c) => {
const id = queryInteger(c.req.param("id"), 0, { min: 1 })
const parsed = updateAchievementRequestSchema.safeParse(
await c.req.json().catch(() => null),
)
if (!parsed.success) {
return failure(
c,
400,
"invalid-request",
parsed.error.issues[0]?.message ?? "参数错误",
)
}
if (!findMetric(parsed.data.metric))
return failure(c, 400, "invalid-metric", "指标不存在")
const [before] = await db.select().from(schema.achievement).where(eq(schema.achievement.id, id)).limit(1)
if (!before) return failure(c, 404, "achievement-not-found", "成就不存在")
const [before] = await db
.select()
.from(schema.achievement)
.where(eq(schema.achievement.id, id))
.limit(1)
if (!before) return failure(c, 404, "achievement-not-found", "成就不存在")
const [after] = await db.update(schema.achievement).set(parsed.data)
.where(eq(schema.achievement.id, id)).returning()
const [after] = await db
.update(schema.achievement)
.set(parsed.data)
.where(eq(schema.achievement.id, id))
.returning()
// 只要「谁能达成」这件事可能变了就补发,不去精细判断是否放宽。补发幂等(唯一键 + 冲突忽略),
// 多跑一次只花一次扫描;漏跑却是学生已达标却拿不到,两个方向代价不对称。
// 判据必须包含 metric(换了维度)和 visible(草稿期已达标的人),
// 只看 operator/threshold 会漏掉这两种。
const changed =
before.metric !== after!.metric ||
before.operator !== after!.operator ||
before.threshold !== after!.threshold ||
before.visible !== after!.visible
if (after!.visible && changed) await rescanAchievement(id)
// 只要「谁能达成」这件事可能变了就补发,不去精细判断是否放宽。补发幂等(唯一键 + 冲突忽略),
// 多跑一次只花一次扫描;漏跑却是学生已达标却拿不到,两个方向代价不对称。
// 判据必须包含 metric(换了维度)和 visible(草稿期已达标的人),
// 只看 operator/threshold 会漏掉这两种。
const changed =
before.metric !== after!.metric ||
before.operator !== after!.operator ||
before.threshold !== after!.threshold ||
before.visible !== after!.visible
if (after!.visible && changed) await rescanAchievement(id)
const [row] = await db.select().from(schema.achievement).where(eq(schema.achievement.id, id)).limit(1)
return success(c, serialize(row!))
})
const [row] = await db
.select()
.from(schema.achievement)
.where(eq(schema.achievement.id, id))
.limit(1)
return success(c, serialize(row!))
},
)
adminAchievementRoutes.delete("/achievements/:id", requireSuperAdmin, async (c) => {
const id = queryInteger(c.req.param("id"), 0, { min: 1 })
// user_achievement 的外键同样是 NO ACTION(Django 的级联在应用层),先清子表
const deleted = await db.transaction(async (tx) => {
await tx.delete(schema.userAchievement).where(eq(schema.userAchievement.achievementId, id))
return tx.delete(schema.achievement).where(eq(schema.achievement.id, id))
adminAchievementRoutes.delete(
"/achievements/:id",
requireSuperAdmin,
async (c) => {
const id = queryInteger(c.req.param("id"), 0, { min: 1 })
// 解锁记录随成就一起没:user_achievement.achievement_id 是 CASCADE0010
const deleted = await db
.delete(schema.achievement)
.where(eq(schema.achievement.id, id))
.returning({ id: schema.achievement.id })
})
if (deleted.length === 0) return failure(c, 404, "achievement-not-found", "成就不存在")
return success(c, null)
})
if (deleted.length === 0)
return failure(c, 404, "achievement-not-found", "成就不存在")
return success(c, null)
},
)
+76 -35
View File
@@ -1,8 +1,8 @@
import {
adminAiReportListSchema,
adminAiReportListItemSchema,
adminAiReportSchema,
toggleAiReportPinResponseSchema,
import type {
AdminAiReport,
AdminAiReportList,
AdminAiReportListItem,
ToggleAiReportPinResponse,
} from "@oj2/contract"
import { and, count, desc, eq, ilike } from "drizzle-orm"
import { Hono } from "hono"
@@ -21,14 +21,20 @@ function excerpt(analysis: string | null) {
return text.length <= 120 ? text : `${text.slice(0, 120)}`
}
function listItem(row: { id: number; username: string; createTime: string; analysis: string; isPinned: boolean }) {
return adminAiReportListItemSchema.parse({
function listItem(row: {
id: number
username: string
createTime: string
analysis: string
isPinned: boolean
}) {
return {
id: row.id,
username: row.username,
createTime: row.createTime,
analysisExcerpt: excerpt(row.analysis),
isPinned: row.isPinned,
})
} satisfies AdminAiReportListItem
}
const listColumns = {
@@ -41,7 +47,9 @@ const listColumns = {
adminAiRoutes.get("/ai/reports", requireTeacher, async (c) => {
const username = c.req.query("username")?.trim()
const where = username ? ilike(schema.user.username, `%${username}%`) : undefined
const where = username
? ilike(schema.user.username, `%${username}%`)
: undefined
// 置顶列表不分页:它是「每个学生最新钉住的那份」,数量等于学生数,前端一次性拿走。
// 但**形状必须和分页那支一样**:同一个 URL 返回两种形状,调用方没法照着一个类型写。
@@ -49,60 +57,93 @@ adminAiRoutes.get("/ai/reports", requireTeacher, async (c) => {
// 读的是 res.results,于是拿到 undefined`pinnedReports.length` 在渲染时抛
// 「Cannot read properties of undefined」——空库也照抛,这个页面每次打开都白屏。
if (c.req.query("pinnedOnly") === "true") {
const rows = await db.select(listColumns).from(schema.aiAnalysis)
const rows = await db
.select(listColumns)
.from(schema.aiAnalysis)
.innerJoin(schema.user, eq(schema.aiAnalysis.userId, schema.user.id))
.where(and(eq(schema.aiAnalysis.isPinned, true), where))
.orderBy(desc(schema.aiAnalysis.createTime))
return success(c, adminAiReportListSchema.parse({
return success(c, {
results: rows.map(listItem),
total: rows.length,
}))
} satisfies AdminAiReportList)
}
const limit = queryInteger(c.req.query("limit"), 10, { min: 1, max: 250 })
const offset = queryInteger(c.req.query("offset"), 0, { min: 0 })
const [totalRows, rows] = await Promise.all([
db.select({ value: count() }).from(schema.aiAnalysis)
.innerJoin(schema.user, eq(schema.aiAnalysis.userId, schema.user.id)).where(where),
db.select(listColumns).from(schema.aiAnalysis)
.innerJoin(schema.user, eq(schema.aiAnalysis.userId, schema.user.id)).where(where)
.orderBy(desc(schema.aiAnalysis.createTime)).limit(limit).offset(offset),
db
.select({ value: count() })
.from(schema.aiAnalysis)
.innerJoin(schema.user, eq(schema.aiAnalysis.userId, schema.user.id))
.where(where),
db
.select(listColumns)
.from(schema.aiAnalysis)
.innerJoin(schema.user, eq(schema.aiAnalysis.userId, schema.user.id))
.where(where)
.orderBy(desc(schema.aiAnalysis.createTime))
.limit(limit)
.offset(offset),
])
return success(c, adminAiReportListSchema.parse({
return success(c, {
results: rows.map(listItem),
total: totalRows[0]?.value ?? 0,
}))
} satisfies AdminAiReportList)
})
adminAiRoutes.get("/ai/reports/:id", requireTeacher, async (c) => {
const [row] = await db.select({
id: schema.aiAnalysis.id,
username: schema.user.username,
className: schema.user.className,
createTime: schema.aiAnalysis.createTime,
analysis: schema.aiAnalysis.analysis,
}).from(schema.aiAnalysis)
const [row] = await db
.select({
id: schema.aiAnalysis.id,
username: schema.user.username,
className: schema.user.className,
createTime: schema.aiAnalysis.createTime,
analysis: schema.aiAnalysis.analysis,
})
.from(schema.aiAnalysis)
.innerJoin(schema.user, eq(schema.aiAnalysis.userId, schema.user.id))
.where(eq(schema.aiAnalysis.id, queryInteger(c.req.param("id"), 0, { min: 1 }))).limit(1)
.where(
eq(schema.aiAnalysis.id, queryInteger(c.req.param("id"), 0, { min: 1 })),
)
.limit(1)
if (!row) return failure(c, 404, "report-not-found", "AIAnalysis not found")
// data / systemPrompt / userPrompt 一律不下发:里面是喂给模型的原始学情数据与提示词
return success(c, adminAiReportSchema.parse(row))
return success(c, row satisfies AdminAiReport)
})
adminAiRoutes.post("/ai/reports/:id/pin", requireTeacher, async (c) => {
const id = queryInteger(c.req.param("id"), 0, { min: 1 })
const [report] = await db.select({ id: schema.aiAnalysis.id, userId: schema.aiAnalysis.userId, isPinned: schema.aiAnalysis.isPinned })
.from(schema.aiAnalysis).where(eq(schema.aiAnalysis.id, id)).limit(1)
if (!report) return failure(c, 404, "report-not-found", "AIAnalysis not found")
const [report] = await db
.select({
id: schema.aiAnalysis.id,
userId: schema.aiAnalysis.userId,
isPinned: schema.aiAnalysis.isPinned,
})
.from(schema.aiAnalysis)
.where(eq(schema.aiAnalysis.id, id))
.limit(1)
if (!report)
return failure(c, 404, "report-not-found", "AIAnalysis not found")
// 切换语义,与旧后端一致:已置顶则取消;未置顶则先把该学生其它置顶清掉,保证每人至多一份
const next = !report.isPinned
await db.transaction(async (tx) => {
if (next) {
await tx.update(schema.aiAnalysis).set({ isPinned: false })
.where(and(eq(schema.aiAnalysis.userId, report.userId), eq(schema.aiAnalysis.isPinned, true)))
await tx
.update(schema.aiAnalysis)
.set({ isPinned: false })
.where(
and(
eq(schema.aiAnalysis.userId, report.userId),
eq(schema.aiAnalysis.isPinned, true),
),
)
}
await tx.update(schema.aiAnalysis).set({ isPinned: next }).where(eq(schema.aiAnalysis.id, id))
await tx
.update(schema.aiAnalysis)
.set({ isPinned: next })
.where(eq(schema.aiAnalysis.id, id))
})
return success(c, toggleAiReportPinResponseSchema.parse({ isPinned: next }))
return success(c, { isPinned: next } satisfies ToggleAiReportPinResponse)
})
+119 -50
View File
@@ -1,8 +1,8 @@
import {
adminAnnouncementListSchema,
adminAnnouncementSchema,
createAnnouncementRequestSchema,
updateAnnouncementRequestSchema,
type AdminAnnouncement,
type AdminAnnouncementList,
} from "@oj2/contract"
import { count, desc, eq } from "drizzle-orm"
import { Hono } from "hono"
@@ -19,7 +19,7 @@ function serialize(row: {
user: typeof schema.user.$inferSelect
realName: string | null
}) {
return adminAnnouncementSchema.parse({
return {
id: row.announcement.id,
title: row.announcement.title,
tag: row.announcement.tag,
@@ -29,12 +29,16 @@ function serialize(row: {
createdBy: sampleUser(row.user, row.realName),
createTime: row.announcement.createTime,
lastUpdateTime: row.announcement.lastUpdateTime,
})
} satisfies AdminAnnouncement
}
function selectOne(id: number) {
return db
.select({ announcement: schema.announcement, user: schema.user, realName: schema.userProfile.realName })
.select({
announcement: schema.announcement,
user: schema.user,
realName: schema.userProfile.realName,
})
.from(schema.announcement)
.innerJoin(schema.user, eq(schema.announcement.createdById, schema.user.id))
.leftJoin(schema.userProfile, eq(schema.userProfile.userId, schema.user.id))
@@ -47,68 +51,133 @@ adminAnnouncementRoutes.get("/announcements", requireSuperAdmin, async (c) => {
const offset = queryInteger(c.req.query("offset"), 0, { min: 0 })
const [totalRows, rows] = await Promise.all([
db.select({ value: count() }).from(schema.announcement),
db.select({ announcement: schema.announcement, user: schema.user, realName: schema.userProfile.realName })
db
.select({
announcement: schema.announcement,
user: schema.user,
realName: schema.userProfile.realName,
})
.from(schema.announcement)
.innerJoin(schema.user, eq(schema.announcement.createdById, schema.user.id))
.leftJoin(schema.userProfile, eq(schema.userProfile.userId, schema.user.id))
.innerJoin(
schema.user,
eq(schema.announcement.createdById, schema.user.id),
)
.leftJoin(
schema.userProfile,
eq(schema.userProfile.userId, schema.user.id),
)
.orderBy(desc(schema.announcement.createTime))
.limit(limit)
.offset(offset),
])
return success(c, adminAnnouncementListSchema.parse({
return success(c, {
// 列表 schema omit 掉了 contentZod 会 strip 掉多出来的键,这里不必手工再挑一遍
results: rows.map(serialize),
total: totalRows[0]?.value ?? 0,
}))
} satisfies AdminAnnouncementList)
})
adminAnnouncementRoutes.post("/announcements", requireSuperAdmin, async (c) => {
const parsed = createAnnouncementRequestSchema.safeParse(await c.req.json().catch(() => null))
const parsed = createAnnouncementRequestSchema.safeParse(
await c.req.json().catch(() => null),
)
if (!parsed.success) {
return failure(c, 400, "invalid-request", parsed.error.issues[0]?.message ?? "Invalid payload")
return failure(
c,
400,
"invalid-request",
parsed.error.issues[0]?.message ?? "Invalid payload",
)
}
const now = new Date().toISOString()
const [created] = await db.insert(schema.announcement).values({
...parsed.data,
createTime: now,
lastUpdateTime: now,
createdById: c.get("user")!.id,
}).returning({ id: schema.announcement.id })
const [created] = await db
.insert(schema.announcement)
.values({
...parsed.data,
createTime: now,
lastUpdateTime: now,
createdById: c.get("user")!.id,
})
.returning({ id: schema.announcement.id })
const [row] = await selectOne(created!.id)
return success(c, serialize(row!), 201)
})
adminAnnouncementRoutes.get("/announcements/:id", requireSuperAdmin, async (c) => {
const [row] = await selectOne(queryInteger(c.req.param("id"), 0, { min: 1 }))
if (!row) return failure(c, 404, "announcement-not-found", "Announcement does not exist")
return success(c, serialize(row))
})
adminAnnouncementRoutes.get(
"/announcements/:id",
requireSuperAdmin,
async (c) => {
const [row] = await selectOne(
queryInteger(c.req.param("id"), 0, { min: 1 }),
)
if (!row)
return failure(
c,
404,
"announcement-not-found",
"Announcement does not exist",
)
return success(c, serialize(row))
},
)
adminAnnouncementRoutes.put("/announcements/:id", requireSuperAdmin, async (c) => {
const id = queryInteger(c.req.param("id"), 0, { min: 1 })
const parsed = updateAnnouncementRequestSchema.safeParse(await c.req.json().catch(() => null))
if (!parsed.success) {
return failure(c, 400, "invalid-request", parsed.error.issues[0]?.message ?? "Invalid payload")
}
const updated = await db.update(schema.announcement)
.set({ ...parsed.data, lastUpdateTime: new Date().toISOString() })
.where(eq(schema.announcement.id, id))
.returning({ id: schema.announcement.id })
if (updated.length === 0) {
return failure(c, 404, "announcement-not-found", "Announcement does not exist")
}
const [row] = await selectOne(id)
return success(c, serialize(row!))
})
adminAnnouncementRoutes.put(
"/announcements/:id",
requireSuperAdmin,
async (c) => {
const id = queryInteger(c.req.param("id"), 0, { min: 1 })
const parsed = updateAnnouncementRequestSchema.safeParse(
await c.req.json().catch(() => null),
)
if (!parsed.success) {
return failure(
c,
400,
"invalid-request",
parsed.error.issues[0]?.message ?? "Invalid payload",
)
}
const updated = await db
.update(schema.announcement)
.set({ ...parsed.data, lastUpdateTime: new Date().toISOString() })
.where(eq(schema.announcement.id, id))
.returning({ id: schema.announcement.id })
if (updated.length === 0) {
return failure(
c,
404,
"announcement-not-found",
"Announcement does not exist",
)
}
const [row] = await selectOne(id)
return success(c, serialize(row!))
},
)
adminAnnouncementRoutes.delete("/announcements/:id", requireSuperAdmin, async (c) => {
// 旧后端删不存在的公告也返回成功(filter().delete() 不报错)。这里改成 404:
// 后台是人手点删除,静默成功会让人以为删掉了,刷新后它还在。
const deleted = await db.delete(schema.announcement)
.where(eq(schema.announcement.id, queryInteger(c.req.param("id"), 0, { min: 1 })))
.returning({ id: schema.announcement.id })
if (deleted.length === 0) {
return failure(c, 404, "announcement-not-found", "Announcement does not exist")
}
return success(c, null)
})
adminAnnouncementRoutes.delete(
"/announcements/:id",
requireSuperAdmin,
async (c) => {
// 旧后端删不存在的公告也返回成功(filter().delete() 不报错)。这里改成 404:
// 后台是人手点删除,静默成功会让人以为删掉了,刷新后它还在。
const deleted = await db
.delete(schema.announcement)
.where(
eq(
schema.announcement.id,
queryInteger(c.req.param("id"), 0, { min: 1 }),
),
)
.returning({ id: schema.announcement.id })
if (deleted.length === 0) {
return failure(
c,
404,
"announcement-not-found",
"Announcement does not exist",
)
}
return success(c, null)
},
)
+153 -59
View File
@@ -1,12 +1,12 @@
import {
dashboardInfoSchema,
judgeServerListSchema,
judgeServerSchema,
orphanTestCaseSchema,
updateJudgeServerRequestSchema,
updateWebsiteConfigRequestSchema,
uploadImageResponseSchema,
websiteConfigSchema,
type DashboardInfo,
type JudgeServer,
type JudgeServerList,
type OrphanTestCase,
type UploadImageResponse,
type WebsiteConfig,
} from "@oj2/contract"
import { randomInt } from "node:crypto"
import { mkdir, readdir, rm, stat } from "node:fs/promises"
@@ -14,13 +14,18 @@ import { resolve } from "node:path"
import { count, desc, eq, gte, ilike, not, sql } from "drizzle-orm"
import { Hono } from "hono"
import { requireAdmin, requireSuperAdmin, type AppEnv } from "../../auth/middleware"
import {
requireAdmin,
requireSuperAdmin,
type AppEnv,
} from "../../auth/middleware"
import { config } from "../../config"
import { db, schema } from "../../db"
import { publishConfigUpdate } from "../../events"
import { failure, success } from "../../http"
import { getWebsiteOptions } from "../../services/options"
import { todayStart } from "../helpers"
import { todayStart } from "../../time"
import { queryInteger } from "../helpers"
export const adminConfRoutes = new Hono<AppEnv>()
@@ -38,7 +43,9 @@ function aliveSince() {
* **线**
*/
function isAlive(lastHeartbeat: string) {
return Date.parse(lastHeartbeat) >= Date.now() - HEARTBEAT_ALIVE_SECONDS * 1000
return (
Date.parse(lastHeartbeat) >= Date.now() - HEARTBEAT_ALIVE_SECONDS * 1000
)
}
// ---------------------------------------------------------------- 网站配置
@@ -57,7 +64,7 @@ const OPTION_KEYS = {
adminConfRoutes.get("/website", requireSuperAdmin, async (c) => {
const options = await getWebsiteOptions()
return success(c, websiteConfigSchema.parse({
return success(c, {
websiteBaseUrl: options.website_base_url,
websiteName: options.website_name,
websiteNameShortcut: options.website_name_shortcut,
@@ -66,18 +73,28 @@ adminConfRoutes.get("/website", requireSuperAdmin, async (c) => {
submissionListShowAll: options.submission_list_show_all,
classList: options.class_list,
enableMaxkb: options.enable_maxkb,
}))
} satisfies WebsiteConfig)
})
adminConfRoutes.post("/website", requireSuperAdmin, async (c) => {
const parsed = updateWebsiteConfigRequestSchema.safeParse(await c.req.json().catch(() => null))
const parsed = updateWebsiteConfigRequestSchema.safeParse(
await c.req.json().catch(() => null),
)
if (!parsed.success) {
return failure(c, 400, "invalid-request", parsed.error.issues[0]?.message ?? "Invalid payload")
return failure(
c,
400,
"invalid-request",
parsed.error.issues[0]?.message ?? "Invalid payload",
)
}
const entries = (Object.entries(OPTION_KEYS) as [keyof typeof OPTION_KEYS, string][])
.map(([field, key]) => ({ field, key, value: parsed.data[field] }))
const entries = (
Object.entries(OPTION_KEYS) as [keyof typeof OPTION_KEYS, string][]
).map(([field, key]) => ({ field, key, value: parsed.data[field] }))
// 8 个键一条 upsert 写完,不再一个键一次往返
await db.insert(schema.optionsSysoptions).values(entries.map(({ key, value }) => ({ key, value })))
await db
.insert(schema.optionsSysoptions)
.values(entries.map(({ key, value }) => ({ key, value })))
.onConflictDoUpdate({
target: schema.optionsSysoptions.key,
set: { value: sql`excluded.value` },
@@ -88,45 +105,75 @@ adminConfRoutes.post("/website", requireSuperAdmin, async (c) => {
// snake_case 是这张表从 Django 继承来的存储格式,只该活在库里;线上这一跳两边
// 都是新写的,没理由让前端再写一层换名胶水。曾经推 snake、前端拿它去比驼峰字段,
// 一条也命中不了,整个「改完不必刷新」空转了很久。
for (const entry of entries) await publishConfigUpdate(entry.field, entry.value)
for (const entry of entries)
await publishConfigUpdate(entry.field, entry.value)
return success(c, null)
})
// ---------------------------------------------------------------- 判题机
adminConfRoutes.get("/judge-servers", requireSuperAdmin, async (c) => {
const rows = await db.select().from(schema.judgeServer).orderBy(desc(schema.judgeServer.lastHeartbeat))
return success(c, judgeServerListSchema.parse({
const rows = await db
.select()
.from(schema.judgeServer)
.orderBy(desc(schema.judgeServer.lastHeartbeat))
return success(c, {
// 后台要显示 token 才能拿去配判题机。这个接口是超管专属的
token: config.judgeServerToken,
servers: rows.map((row) => judgeServerSchema.parse({
...row,
status: isAlive(row.lastHeartbeat) ? "normal" : "abnormal",
})),
}))
servers: rows.map(
(row) =>
({
...row,
status: isAlive(row.lastHeartbeat) ? "normal" : "abnormal",
}) satisfies JudgeServer,
),
} satisfies JudgeServerList)
})
adminConfRoutes.put("/judge-servers/:id", requireSuperAdmin, async (c) => {
const parsed = updateJudgeServerRequestSchema.safeParse(await c.req.json().catch(() => null))
if (!parsed.success) return failure(c, 400, "invalid-request", "isDisabled is required")
const updated = await db.update(schema.judgeServer)
const parsed = updateJudgeServerRequestSchema.safeParse(
await c.req.json().catch(() => null),
)
if (!parsed.success)
return failure(c, 400, "invalid-request", "isDisabled is required")
const updated = await db
.update(schema.judgeServer)
.set({ isDisabled: parsed.data.isDisabled })
.where(eq(schema.judgeServer.id, Number(c.req.param("id"))))
.where(
eq(schema.judgeServer.id, queryInteger(c.req.param("id"), 0, { min: 1 })),
)
.returning({ id: schema.judgeServer.id })
if (updated.length === 0) return failure(c, 404, "judge-server-not-found", "Judge server does not exist")
if (updated.length === 0)
return failure(
c,
404,
"judge-server-not-found",
"Judge server does not exist",
)
// 旧后端在这里会 process_pending_task() 把积压的待判任务重新分发。
// 新架构不需要:任务在 BullMQ 里排着,worker 恢复就自己接着消费,不存在「没有新提交
// 就一直 waiting」那种情况 —— 那是旧的自研分发器才有的问题。
return success(c, null)
})
adminConfRoutes.delete("/judge-servers/:hostname", requireSuperAdmin, async (c) => {
const deleted = await db.delete(schema.judgeServer)
.where(eq(schema.judgeServer.hostname, c.req.param("hostname")))
.returning({ id: schema.judgeServer.id })
if (deleted.length === 0) return failure(c, 404, "judge-server-not-found", "Judge server does not exist")
return success(c, null)
})
adminConfRoutes.delete(
"/judge-servers/:hostname",
requireSuperAdmin,
async (c) => {
const deleted = await db
.delete(schema.judgeServer)
.where(eq(schema.judgeServer.hostname, c.req.param("hostname")))
.returning({ id: schema.judgeServer.id })
if (deleted.length === 0)
return failure(
c,
404,
"judge-server-not-found",
"Judge server does not exist",
)
return success(c, null)
},
)
// ---------------------------------------------------------------- 孤儿测试用例
@@ -139,15 +186,24 @@ async function orphanTestCaseIds() {
db.select({ id: schema.problem.testCaseId }).from(schema.problem),
])
const referenced = new Set(inDb.map((row) => row.id))
return onDisk.filter((name) => TEST_CASE_ID_RE.test(name) && !referenced.has(name))
return onDisk.filter(
(name) => TEST_CASE_ID_RE.test(name) && !referenced.has(name),
)
}
adminConfRoutes.get("/orphan-test-cases", requireSuperAdmin, async (c) => {
const ids = await orphanTestCaseIds()
const rows = await Promise.all(ids.map(async (id) => {
const info = await stat(resolve(config.testCaseDirectory, id)).catch(() => null)
return orphanTestCaseSchema.parse({ id, createTime: info ? info.mtimeMs / 1000 : 0 })
}))
const rows = await Promise.all(
ids.map(async (id) => {
const info = await stat(resolve(config.testCaseDirectory, id)).catch(
() => null,
)
return {
id,
createTime: info ? info.mtimeMs / 1000 : 0,
} satisfies OrphanTestCase
}),
)
return success(c, rows)
})
@@ -158,10 +214,18 @@ adminConfRoutes.delete("/orphan-test-cases", requireSuperAdmin, async (c) => {
// 而测试数据没有别处备份 —— 旧后端这里是不校验的。
const targets = requested ? orphans.filter((id) => id === requested) : orphans
if (requested && targets.length === 0) {
return failure(c, 404, "not-an-orphan", "该用例目录不存在或仍被题目引用,未删除")
return failure(
c,
404,
"not-an-orphan",
"该用例目录不存在或仍被题目引用,未删除",
)
}
for (const id of targets) {
await rm(resolve(config.testCaseDirectory, id), { recursive: true, force: true })
await rm(resolve(config.testCaseDirectory, id), {
recursive: true,
force: true,
})
}
return success(c, { deleted: targets.length })
})
@@ -172,20 +236,26 @@ adminConfRoutes.get("/dashboard", requireSuperAdmin, async (c) => {
const now = new Date().toISOString()
const [[users], [submissions], [contests], [servers]] = await Promise.all([
db.select({ value: count() }).from(schema.user),
db.select({ value: count() }).from(schema.submission)
db
.select({ value: count() })
.from(schema.submission)
.where(gte(schema.submission.createTime, todayStart())),
db.select({ value: count() }).from(schema.contest)
db
.select({ value: count() })
.from(schema.contest)
.where(not(sql`${schema.contest.endTime} < ${now}`)),
db.select({ value: count() }).from(schema.judgeServer)
db
.select({ value: count() })
.from(schema.judgeServer)
.where(gte(schema.judgeServer.lastHeartbeat, aliveSince())),
])
// 旧接口还回了 env.FORCE_HTTPS / STATIC_CDN_HOST,前端从未读过,不再下发
return success(c, dashboardInfoSchema.parse({
return success(c, {
userCount: users?.value ?? 0,
todaySubmissionCount: submissions?.value ?? 0,
recentContestCount: contests?.value ?? 0,
judgeServerCount: servers?.value ?? 0,
}))
} satisfies DashboardInfo)
})
adminConfRoutes.get("/random-usernames", requireSuperAdmin, async (c) => {
@@ -194,10 +264,16 @@ adminConfRoutes.get("/random-usernames", requireSuperAdmin, async (c) => {
// 不额外按 className 过滤:那会改变旧行为,而这个功能就是随机点名,宁可宽松
const classroom = c.req.query("classroom")?.trim()
if (!classroom) return failure(c, 400, "invalid-request", "需要班级号")
const rows = await db.select({ username: schema.user.username }).from(schema.user)
const rows = await db
.select({ username: schema.user.username })
.from(schema.user)
.where(ilike(schema.user.username, `${classroom}%`))
.orderBy(sql`random()`).limit(10)
return success(c, rows.map((row) => row.username))
.orderBy(sql`random()`)
.limit(10)
return success(
c,
rows.map((row) => row.username),
)
})
// ---------------------------------------------------------------- 富文本图片上传
@@ -218,16 +294,28 @@ adminConfRoutes.post("/upload-image", requireAdmin, async (c) => {
const form = await c.req.formData().catch(() => null)
const image = form?.get("image")
if (!(image instanceof File)) {
return success(c, uploadImageResponseSchema.parse({ success: false, msg: "Upload failed", filePath: "" }))
return success(c, {
success: false,
msg: "Upload failed",
filePath: "",
} satisfies UploadImageResponse)
}
const suffix = image.name.slice(image.name.lastIndexOf(".")).toLowerCase()
if (!IMAGE_SUFFIXES.includes(suffix)) {
return success(c, uploadImageResponseSchema.parse({ success: false, msg: "Unsupported file format", filePath: "" }))
return success(c, {
success: false,
msg: "Unsupported file format",
filePath: "",
} satisfies UploadImageResponse)
}
// 旧后端没有大小限制,靠 nginx 兜。这里显式限一道:文件写在本地磁盘上,
// 一个超大文件就能把机房那台机器的盘写满,而写满之后判题也一起挂
if (image.size > MAX_IMAGE_BYTES) {
return success(c, uploadImageResponseSchema.parse({ success: false, msg: "图片不能超过 10MB", filePath: "" }))
return success(c, {
success: false,
msg: "图片不能超过 10MB",
filePath: "",
} satisfies UploadImageResponse)
}
// 文件名完全由服务端生成,不带用户提供的任何一段 —— 原名里的 ../ 或空字节都进不来
const name = `${randomFileName()}${suffix}`
@@ -236,16 +324,22 @@ adminConfRoutes.post("/upload-image", requireAdmin, async (c) => {
await Bun.write(resolve(config.uploadDirectory, name), image)
} catch (error) {
console.error("Failed to save uploaded image", error)
return success(c, uploadImageResponseSchema.parse({ success: false, msg: "Upload Error", filePath: "" }))
return success(c, {
success: false,
msg: "Upload Error",
filePath: "",
} satisfies UploadImageResponse)
}
return success(c, uploadImageResponseSchema.parse({
return success(c, {
success: true,
msg: "Success",
filePath: `${config.uploadUriPrefix}/${name}`,
}))
} satisfies UploadImageResponse)
})
function randomFileName() {
return Array.from({ length: 10 }, () =>
"abcdefghijklmnopqrstuvwxyz0123456789"[randomInt(36)]).join("")
return Array.from(
{ length: 10 },
() => "abcdefghijklmnopqrstuvwxyz0123456789"[randomInt(36)],
).join("")
}
+290 -177
View File
@@ -1,10 +1,10 @@
import {
acmHelperItemSchema,
adminContestListSchema,
adminContestSchema,
createContestRequestSchema,
updateAcmHelperRequestSchema,
updateContestRequestSchema,
type AcmHelperItem,
type AdminContest,
type AdminContestList,
} from "@oj2/contract"
import { and, count, desc, eq, ilike, inArray } from "drizzle-orm"
import { Hono } from "hono"
@@ -26,22 +26,12 @@ function ownedBy(user: AuthUser, contest: { createdById: number }) {
return user.adminType === "Super Admin" || contest.createdById === user.id
}
/** CIDR 校验。`ip_network(strict=False)` 的等价物:允许主机位非零,如 192.168.1.5/24 */
function validCidr(value: string) {
const [address, prefixText] = value.split("/")
const octets = (address ?? "").split(".")
if (octets.length !== 4) return false
if (!octets.every((part) => /^\d{1,3}$/.test(part) && Number(part) <= 255)) return false
if (prefixText === undefined) return true
return /^\d{1,2}$/.test(prefixText) && Number(prefixText) <= 32
}
async function serialize(row: {
contest: typeof schema.contest.$inferSelect
user: typeof schema.user.$inferSelect
realName: string | null
}) {
return adminContestSchema.parse({
return {
id: row.contest.id,
title: row.contest.title,
description: row.contest.description,
@@ -52,32 +42,33 @@ async function serialize(row: {
lastUpdateTime: row.contest.lastUpdateTime,
password: row.contest.password,
visible: row.contest.visible,
allowedIpRanges: Array.isArray(row.contest.allowedIpRanges)
? row.contest.allowedIpRanges.filter((item): item is string => typeof item === "string")
: [],
createdBy: sampleUser(row.user, row.realName),
status: contestStatus(row.contest),
contestType: row.contest.password ? "Password Protected" : "Public",
})
} satisfies AdminContest
}
function selectContest(id: number) {
return db.select({ contest: schema.contest, user: schema.user, realName: schema.userProfile.realName })
return db
.select({
contest: schema.contest,
user: schema.user,
realName: schema.userProfile.realName,
})
.from(schema.contest)
.innerJoin(schema.user, eq(schema.contest.createdById, schema.user.id))
.leftJoin(schema.userProfile, eq(schema.userProfile.userId, schema.user.id))
.where(eq(schema.contest.id, id)).limit(1)
.where(eq(schema.contest.id, id))
.limit(1)
}
/** 请求体里的时间与 CIDR 校验,创建和编辑共用 */
function validatePayload(data: { startTime: string; endTime: string; allowedIpRanges: string[] }) {
/** 请求体里的时间校验,创建和编辑共用 */
function validatePayload(data: { startTime: string; endTime: string }) {
const start = Date.parse(data.startTime)
const end = Date.parse(data.endTime)
if (!Number.isFinite(start) || !Number.isFinite(end)) return "开始或结束时间不是合法的时间格式"
if (!Number.isFinite(start) || !Number.isFinite(end))
return "开始或结束时间不是合法的时间格式"
if (end <= start) return "Start time must occur earlier than end time"
for (const range of data.allowedIpRanges) {
if (!validCidr(range)) return `${range} is not a valid cidr network`
}
return null
}
@@ -87,27 +78,41 @@ adminContestRoutes.get("/contests", requireTeacher, async (c) => {
const user = c.get("user")!
const filters = []
// 非超管只看得到自己建的比赛,与旧后端一致
if (user.adminType !== "Super Admin") filters.push(eq(schema.contest.createdById, user.id))
if (user.adminType !== "Super Admin")
filters.push(eq(schema.contest.createdById, user.id))
const keyword = c.req.query("keyword")?.trim()
if (keyword) filters.push(ilike(schema.contest.title, `%${keyword}%`))
const where = filters.length ? and(...filters) : undefined
const [totalRows, rows] = await Promise.all([
db.select({ value: count() }).from(schema.contest).where(where),
db.select({ contest: schema.contest, user: schema.user, realName: schema.userProfile.realName })
db
.select({
contest: schema.contest,
user: schema.user,
realName: schema.userProfile.realName,
})
.from(schema.contest)
.innerJoin(schema.user, eq(schema.contest.createdById, schema.user.id))
.leftJoin(schema.userProfile, eq(schema.userProfile.userId, schema.user.id))
.where(where).orderBy(desc(schema.contest.createTime)).limit(limit).offset(offset),
.leftJoin(
schema.userProfile,
eq(schema.userProfile.userId, schema.user.id),
)
.where(where)
.orderBy(desc(schema.contest.createTime))
.limit(limit)
.offset(offset),
])
return success(c, adminContestListSchema.parse({
return success(c, {
results: await Promise.all(rows.map(serialize)),
total: totalRows[0]?.value ?? 0,
}))
} satisfies AdminContestList)
})
adminContestRoutes.get("/contests/:id", requireTeacher, async (c) => {
const [row] = await selectContest(queryInteger(c.req.param("id"), 0, { min: 1 }))
const [row] = await selectContest(
queryInteger(c.req.param("id"), 0, { min: 1 }),
)
if (!row || !ownedBy(c.get("user")!, row.contest)) {
return failure(c, 404, "contest-not-found", "Contest does not exist")
}
@@ -115,37 +120,53 @@ adminContestRoutes.get("/contests/:id", requireTeacher, async (c) => {
})
adminContestRoutes.post("/contests", requireTeacher, async (c) => {
const parsed = createContestRequestSchema.safeParse(await c.req.json().catch(() => null))
const parsed = createContestRequestSchema.safeParse(
await c.req.json().catch(() => null),
)
if (!parsed.success) {
return failure(c, 400, "invalid-request", parsed.error.issues[0]?.message ?? "Invalid payload")
return failure(
c,
400,
"invalid-request",
parsed.error.issues[0]?.message ?? "Invalid payload",
)
}
const error = validatePayload(parsed.data)
if (error) return failure(c, 400, "invalid-contest", error)
const now = new Date().toISOString()
const [created] = await db.insert(schema.contest).values({
title: parsed.data.title,
description: parsed.data.description,
tag: parsed.data.tag,
startTime: new Date(parsed.data.startTime).toISOString(),
endTime: new Date(parsed.data.endTime).toISOString(),
// 空串归一成 null,否则 contestType 会把「密码是空字符串」当成密码保护赛
password: parsed.data.password || null,
visible: parsed.data.visible,
allowedIpRanges: parsed.data.allowedIpRanges,
createdById: c.get("user")!.id,
createTime: now,
lastUpdateTime: now,
}).returning({ id: schema.contest.id })
const [created] = await db
.insert(schema.contest)
.values({
title: parsed.data.title,
description: parsed.data.description,
tag: parsed.data.tag,
startTime: new Date(parsed.data.startTime).toISOString(),
endTime: new Date(parsed.data.endTime).toISOString(),
// 空串归一成 null,否则 contestType 会把「密码是空字符串」当成密码保护赛
password: parsed.data.password || null,
visible: parsed.data.visible,
createdById: c.get("user")!.id,
createTime: now,
lastUpdateTime: now,
})
.returning({ id: schema.contest.id })
const [row] = await selectContest(created!.id)
return success(c, await serialize(row!), 201)
})
adminContestRoutes.put("/contests/:id", requireTeacher, async (c) => {
const id = queryInteger(c.req.param("id"), 0, { min: 1 })
const parsed = updateContestRequestSchema.safeParse(await c.req.json().catch(() => null))
const parsed = updateContestRequestSchema.safeParse(
await c.req.json().catch(() => null),
)
if (!parsed.success) {
return failure(c, 400, "invalid-request", parsed.error.issues[0]?.message ?? "Invalid payload")
return failure(
c,
400,
"invalid-request",
parsed.error.issues[0]?.message ?? "Invalid payload",
)
}
const [existing] = await selectContest(id)
if (!existing || !ownedBy(c.get("user")!, existing.contest)) {
@@ -154,17 +175,19 @@ adminContestRoutes.put("/contests/:id", requireTeacher, async (c) => {
const error = validatePayload(parsed.data)
if (error) return failure(c, 400, "invalid-contest", error)
await db.update(schema.contest).set({
title: parsed.data.title,
description: parsed.data.description,
tag: parsed.data.tag,
startTime: new Date(parsed.data.startTime).toISOString(),
endTime: new Date(parsed.data.endTime).toISOString(),
password: parsed.data.password || null,
visible: parsed.data.visible,
allowedIpRanges: parsed.data.allowedIpRanges,
lastUpdateTime: new Date().toISOString(),
}).where(eq(schema.contest.id, id))
await db
.update(schema.contest)
.set({
title: parsed.data.title,
description: parsed.data.description,
tag: parsed.data.tag,
startTime: new Date(parsed.data.startTime).toISOString(),
endTime: new Date(parsed.data.endTime).toISOString(),
password: parsed.data.password || null,
visible: parsed.data.visible,
lastUpdateTime: new Date().toISOString(),
})
.where(eq(schema.contest.id, id))
const [row] = await selectContest(id)
return success(c, await serialize(row!))
})
@@ -172,11 +195,27 @@ adminContestRoutes.put("/contests/:id", requireTeacher, async (c) => {
adminContestRoutes.post("/contests/:id/clone", requireTeacher, async (c) => {
const id = queryInteger(c.req.param("id"), 0, { min: 1 })
const [original] = await selectContest(id)
// 克隆不要求 ownedBy:旧后端这里也没有 ensure_created_by,教师可以拿别人的比赛做模板
// 克隆出来的归调用者所有、且默认不可见,所以不构成越权修改。
if (!original) return failure(c, 404, "contest-not-found", "Contest does not exist")
// 这个接口是干什么的:**把以前那场比赛快速再开一场**,不用从头建一遍题
// 所以副本要带着整套题(含 answers 和 testCaseId),时间挪到 10 分钟后、默认不可见,
// 前端点完「复制」直接跳进副本的编辑页改标题和时间(admin/contest/components/Actions.vue)。
//
// 克隆**故意不要求 ownedBy**,任何教师都能克隆任何一场比赛,包括别人的、隐藏的、
// 还没开始的 —— 于是克隆完就能从 GET /admin/problems/:id 读到别人的标准答案、
// 从 /test-cases 下载别人的测试点。这是**明确定过的政策**(2026-09-06 确认):
// 保密边界在师生之间,不在教师之间。别再把它当越权读取报上来。
//
// 注意这条政策**不能顺手推广到 make-public / from-public**:那两条守的是另一件事 ——
// 别让 B 把 A 还没考的卷子发布给**学生**,或者把 A 的草稿拖进自己比赛再放出去。
// 边界是学生,所以那两处的归属校验照旧(见 admin/problem.ts 的注释)。
//
// 已知的副作用,别当成 bug 去"修":副本和原题共用同一个测试点目录(testCaseId 原样复制),
// 今天无害(删题特意不删目录),但以后要是加"删题顺手清测试点",得先把这里改成复制目录。
if (!original)
return failure(c, 404, "contest-not-found", "Contest does not exist")
const duration = Date.parse(original.contest.endTime) - Date.parse(original.contest.startTime)
const duration =
Date.parse(original.contest.endTime) -
Date.parse(original.contest.startTime)
// 新比赛从 10 分钟后开始,时长与原比赛相同 —— 给出题人留出改时间的余地,
// 又不至于建出一个已经结束的比赛
const start = new Date(Date.now() + 10 * 60 * 1000)
@@ -185,52 +224,79 @@ adminContestRoutes.post("/contests/:id/clone", requireTeacher, async (c) => {
const me = c.get("user")!.id
const cloned = await db.transaction(async (tx) => {
const [contest] = await tx.insert(schema.contest).values({
title: original.contest.title,
description: original.contest.description,
tag: original.contest.tag,
// 不复制原比赛的密码。两个理由:一是克隆出来是一场新比赛、时间也是新的,
// 沿用旧密码意味着拿着旧密码的学生直接能进;二是本接口不校验归属
// (旧后端也不校验,教师可以拿别人的比赛做模板),复制过来就等于把别人的
// 比赛密码原样回传给调用者。克隆者自己重新设一个。
password: null,
// 克隆出来的一律不可见:时间是拍脑袋定的 10 分钟后,直接开放会让学生看到一场没准备好的赛
visible: false,
allowedIpRanges: original.contest.allowedIpRanges,
startTime: start.toISOString(),
endTime: end.toISOString(),
createdById: me,
createTime: now,
lastUpdateTime: now,
}).returning({ id: schema.contest.id })
const [contest] = await tx
.insert(schema.contest)
.values({
title: original.contest.title,
description: original.contest.description,
tag: original.contest.tag,
// 不复制原比赛的密码。两个理由:一是克隆出来是一场新比赛、时间也是新的,
// 沿用旧密码意味着拿着旧密码的学生直接能进;二是本接口不校验归属
// (旧后端也不校验,教师可以拿别人的比赛做模板),复制过来就等于把别人的
// 比赛密码原样回传给调用者。克隆者自己重新设一个。
password: null,
// 克隆出来的一律不可见:时间是拍脑袋定的 10 分钟后,直接开放会让学生看到一场没准备好的赛
visible: false,
startTime: start.toISOString(),
endTime: end.toISOString(),
createdById: me,
createTime: now,
lastUpdateTime: now,
})
.returning({ id: schema.contest.id })
const problems = await tx.select().from(schema.problem)
const problems = await tx
.select()
.from(schema.problem)
.where(eq(schema.problem.contestId, id))
if (problems.length === 0) return contest!.id
// 题面、标签各一条语句,不再按题循环。新旧题的对应关系靠 _id 认:
// 克隆出来的题原样保留 _id,而它们全在同一场新比赛里,彼此不会重名。
const copies = await tx.insert(schema.problem).values(problems.map(({ id: _oldId, ...rest }) => ({
...rest,
contestId: contest!.id,
// 计数器归零:克隆的是题面,不是历史战绩
submissionNumber: 0,
acceptedNumber: 0,
statisticInfo: {},
createdById: me,
createTime: now,
lastUpdateTime: now,
}))).returning({ id: schema.problem.id, displayId: schema.problem.displayId })
const newIdByDisplayId = new Map(copies.map((copy) => [copy.displayId, copy.id]))
const copies = await tx
.insert(schema.problem)
.values(
problems.map(({ id: _oldId, ...rest }) => ({
...rest,
contestId: contest!.id,
// 计数器归零:克隆的是题面,不是历史战绩
submissionNumber: 0,
acceptedNumber: 0,
statisticInfo: {},
createdById: me,
createTime: now,
lastUpdateTime: now,
})),
)
.returning({ id: schema.problem.id, displayId: schema.problem.displayId })
const newIdByDisplayId = new Map(
copies.map((copy) => [copy.displayId, copy.id]),
)
// 标签是多对多中间表,Django 的 problem.tags.set(tags) 对应这里手工复制关系行
const tags = await tx.select({ problemId: schema.problemTags.problemId, tagId: schema.problemTags.problemtagId })
.from(schema.problemTags).where(inArray(schema.problemTags.problemId, problems.map((problem) => problem.id)))
const tags = await tx
.select({
problemId: schema.problemTags.problemId,
tagId: schema.problemTags.problemtagId,
})
.from(schema.problemTags)
.where(
inArray(
schema.problemTags.problemId,
problems.map((problem) => problem.id),
),
)
if (tags.length) {
const displayIdByOldId = new Map(problems.map((problem) => [problem.id, problem.displayId]))
const displayIdByOldId = new Map(
problems.map((problem) => [problem.id, problem.displayId]),
)
const links = tags.flatMap((tag) => {
const newId = newIdByDisplayId.get(displayIdByOldId.get(tag.problemId) ?? "")
return newId === undefined ? [] : [{ problemId: newId, problemtagId: tag.tagId }]
const newId = newIdByDisplayId.get(
displayIdByOldId.get(tag.problemId) ?? "",
)
return newId === undefined
? []
: [{ problemId: newId, problemtagId: tag.tagId }]
})
if (links.length) await tx.insert(schema.problemTags).values(links)
}
@@ -243,81 +309,128 @@ adminContestRoutes.post("/contests/:id/clone", requireTeacher, async (c) => {
// ---------------------------------------------------------------- ACM 赛后核查
adminContestRoutes.get("/contests/:id/acm-helper", requireTeacher, async (c) => {
const id = queryInteger(c.req.param("id"), 0, { min: 1 })
const [contest] = await db.select().from(schema.contest)
.where(and(eq(schema.contest.id, id), eq(schema.contest.visible, true))).limit(1)
if (!contest || !ownedBy(c.get("user")!, contest)) {
return failure(c, 404, "contest-not-found", "Contest does not exist")
}
const [problems, ranks] = await Promise.all([
db.select({ id: schema.problem.id, displayId: schema.problem.displayId })
.from(schema.problem).where(eq(schema.problem.contestId, id)),
db.select({
id: schema.acmContestRank.id,
username: schema.user.username,
realName: schema.userProfile.realName,
submissionInfo: schema.acmContestRank.submissionInfo,
acceptedNumber: schema.acmContestRank.acceptedNumber,
}).from(schema.acmContestRank)
.innerJoin(schema.user, eq(schema.acmContestRank.userId, schema.user.id))
.leftJoin(schema.userProfile, eq(schema.userProfile.userId, schema.user.id))
.where(eq(schema.acmContestRank.contestId, id)),
])
const displayIds = new Map(problems.map((problem) => [String(problem.id), problem.displayId]))
const results = []
for (const rank of ranks) {
if (rank.acceptedNumber <= 0) continue
for (const [problemId, raw] of Object.entries(objectValue(rank.submissionInfo))) {
const info = objectValue(raw)
if (info.is_ac !== true) continue
results.push({
id: rank.id,
username: rank.username,
// 真名在这里是**有意下发**的:核查页就是老师对着名单一个个确认谁抄了。
// 接口已由 requireTeacher + ownedBy 双重把关。
realName: rank.realName,
problemId,
problemDisplayId: displayIds.get(problemId) ?? problemId,
acInfo: info,
checked: info.checked === true,
_acTime: typeof info.ac_time === "number" ? info.ac_time : 0,
})
adminContestRoutes.get(
"/contests/:id/acm-helper",
requireTeacher,
async (c) => {
const id = queryInteger(c.req.param("id"), 0, { min: 1 })
// 不卡 visible:赛后核查恰恰常发生在比赛已经收起来之后,而同一场比赛的
// PUT acm-helper 从来不卡这一条 —— 卡着就成了「标记还能改、页面打不开」
const [contest] = await db
.select()
.from(schema.contest)
.where(eq(schema.contest.id, id))
.limit(1)
if (!contest || !ownedBy(c.get("user")!, contest)) {
return failure(c, 404, "contest-not-found", "Contest does not exist")
}
}
// 按 AC 用时倒序:最后才做出来的排前面,那是最值得看的
results.sort((left, right) => right._acTime - left._acTime)
return success(c, results.map(({ _acTime, ...item }) => acmHelperItemSchema.parse(item)))
})
adminContestRoutes.put("/contests/:id/acm-helper", requireTeacher, async (c) => {
const contestId = queryInteger(c.req.param("id"), 0, { min: 1 })
const parsed = updateAcmHelperRequestSchema.safeParse(await c.req.json().catch(() => null))
if (!parsed.success) {
return failure(c, 400, "invalid-request", parsed.error.issues[0]?.message ?? "Invalid payload")
}
const [contest] = await db.select().from(schema.contest).where(eq(schema.contest.id, contestId)).limit(1)
if (!contest || !ownedBy(c.get("user")!, contest)) {
return failure(c, 404, "contest-not-found", "Contest does not exist")
}
// rank 必须属于这场比赛。旧后端只按 rank_id 取,不校验归属 ——
// 那样带上任意 rank_id 就能改别的比赛的核查标记
const [rank] = await db.select().from(schema.acmContestRank).where(and(
eq(schema.acmContestRank.id, parsed.data.rankId),
eq(schema.acmContestRank.contestId, contestId),
)).limit(1)
if (!rank) return failure(c, 404, "rank-not-found", "Rank id does not exist")
const [problems, ranks] = await Promise.all([
db
.select({ id: schema.problem.id, displayId: schema.problem.displayId })
.from(schema.problem)
.where(eq(schema.problem.contestId, id)),
db
.select({
id: schema.acmContestRank.id,
username: schema.user.username,
realName: schema.userProfile.realName,
submissionInfo: schema.acmContestRank.submissionInfo,
acceptedNumber: schema.acmContestRank.acceptedNumber,
})
.from(schema.acmContestRank)
.innerJoin(
schema.user,
eq(schema.acmContestRank.userId, schema.user.id),
)
.leftJoin(
schema.userProfile,
eq(schema.userProfile.userId, schema.user.id),
)
.where(eq(schema.acmContestRank.contestId, id)),
])
const displayIds = new Map(
problems.map((problem) => [String(problem.id), problem.displayId]),
)
const info = objectValue(rank.submissionInfo)
const entry = objectValue(info[parsed.data.problemId])
if (!info[parsed.data.problemId]) {
return failure(c, 404, "problem-not-in-rank", "Problem id does not exist")
}
entry.checked = parsed.data.checked
info[parsed.data.problemId] = entry
await db.update(schema.acmContestRank).set({ submissionInfo: info })
.where(eq(schema.acmContestRank.id, rank.id))
return success(c, null)
})
const results = []
for (const rank of ranks) {
if (rank.acceptedNumber <= 0) continue
for (const [problemId, info] of Object.entries(rank.submissionInfo)) {
if (info.is_ac !== true) continue
results.push({
id: rank.id,
username: rank.username,
// 真名在这里是**有意下发**的:核查页就是老师对着名单一个个确认谁抄了。
// 接口已由 requireTeacher + ownedBy 双重把关。
realName: rank.realName,
problemId,
problemDisplayId: displayIds.get(problemId) ?? problemId,
acInfo: info,
checked: info.checked === true,
_acTime: typeof info.ac_time === "number" ? info.ac_time : 0,
})
}
}
// 按 AC 用时倒序:最后才做出来的排前面,那是最值得看的
results.sort((left, right) => right._acTime - left._acTime)
return success(
c,
results.map(({ _acTime, ...item }) => item) satisfies AcmHelperItem[],
)
},
)
adminContestRoutes.put(
"/contests/:id/acm-helper",
requireTeacher,
async (c) => {
const contestId = queryInteger(c.req.param("id"), 0, { min: 1 })
const parsed = updateAcmHelperRequestSchema.safeParse(
await c.req.json().catch(() => null),
)
if (!parsed.success) {
return failure(
c,
400,
"invalid-request",
parsed.error.issues[0]?.message ?? "Invalid payload",
)
}
const [contest] = await db
.select()
.from(schema.contest)
.where(eq(schema.contest.id, contestId))
.limit(1)
if (!contest || !ownedBy(c.get("user")!, contest)) {
return failure(c, 404, "contest-not-found", "Contest does not exist")
}
// rank 必须属于这场比赛。旧后端只按 rank_id 取,不校验归属 ——
// 那样带上任意 rank_id 就能改别的比赛的核查标记
const [rank] = await db
.select()
.from(schema.acmContestRank)
.where(
and(
eq(schema.acmContestRank.id, parsed.data.rankId),
eq(schema.acmContestRank.contestId, contestId),
),
)
.limit(1)
if (!rank)
return failure(c, 404, "rank-not-found", "Rank id does not exist")
const info = rank.submissionInfo
const entry = info[parsed.data.problemId]
if (!entry) {
return failure(c, 404, "problem-not-in-rank", "Problem id does not exist")
}
entry.checked = parsed.data.checked
info[parsed.data.problemId] = entry
await db
.update(schema.acmContestRank)
.set({ submissionInfo: info })
.where(eq(schema.acmContestRank.id, rank.id))
return success(c, null)
},
)
+2
View File
@@ -6,6 +6,7 @@ import { adminAchievementRoutes } from "./achievement"
import { adminAiRoutes } from "./ai"
import { adminConfRoutes } from "./conf"
import { adminContestRoutes } from "./contest"
import { adminLearnRoutes } from "./learn"
import { adminProblemRoutes } from "./problem"
import { adminProblemSetRoutes } from "./problemset"
import { adminTagRoutes } from "./tag"
@@ -27,6 +28,7 @@ adminRoutes.route("/", adminAchievementRoutes)
adminRoutes.route("/", adminAiRoutes)
adminRoutes.route("/", adminConfRoutes)
adminRoutes.route("/", adminContestRoutes)
adminRoutes.route("/", adminLearnRoutes)
adminRoutes.route("/", adminProblemRoutes)
adminRoutes.route("/", adminProblemSetRoutes)
adminRoutes.route("/", adminTagRoutes)
+386
View File
@@ -0,0 +1,386 @@
import {
STUDENT_ROLES,
TUTORIAL_READ_SECONDS,
type LearnExerciseAttempt,
type LearnExerciseProgress,
type LearnExerciseProgressList,
type LearnStudentProgress,
type LearnStudentProgressList,
type LearnTutorialProgress,
type LearnTutorialProgressList,
} from "@oj2/contract"
import { and, asc, count, desc, eq, inArray, like, sql } from "drizzle-orm"
import { Hono } from "hono"
import { requireTeacher, type AppEnv } from "../../auth/middleware"
import { db, schema } from "../../db"
import { failure, success } from "../../http"
import { queryInteger, rounded } from "../helpers"
/**
*
*
* `/learn-analytics` `/tutorials` tag.ts
* Hono `/tutorials/:id`
*/
export const adminLearnRoutes = new Hono<AppEnv>()
function tutorialTypeOf(value: string | undefined) {
return value === "c" ? "c" : "python"
}
/**
* `241`24 1
* like `%`
*/
function classFilter(className: string | undefined) {
const value = className?.trim()
if (!value) return { ok: true as const, value: null }
if (!/^\d{1,4}$/.test(value)) return { ok: false as const, value: null }
return { ok: true as const, value }
}
/**
* `className` 3 1-2 like
* 24
*/
function classCondition(value: string | null) {
if (!value) return undefined
return value.length >= 3
? eq(schema.user.className, value)
: like(schema.user.className, `${value}%`)
}
/**
* ****
* null admin/account.ts classNameOf
*
*/
function studentCondition(value: string | null) {
return and(
eq(schema.user.isDisabled, false),
inArray(schema.user.adminType, [...STUDENT_ROLES]),
classCondition(value),
)
}
adminLearnRoutes.get("/learn-analytics/students", requireTeacher, async (c) => {
const type = tutorialTypeOf(c.req.query("type"))
const className = classFilter(c.req.query("className"))
if (!className.ok) return failure(c, 400, "invalid-class", "班级只能是数字")
// 该语言下已公开的教程,既是分母,也是「哪些课算数」的白名单 ——
// 未公开的课学生本来就打不开,混进来会让读完的人显示成没读完
const tutorials = await db
.select({ id: schema.tutorial.id })
.from(schema.tutorial)
.where(
and(eq(schema.tutorial.isPublic, true), eq(schema.tutorial.type, type)),
)
const tutorialIds = tutorials.map((row) => row.id)
// 学生表打底 left join 进度:没读过的人也要出现在结果里,这是这张表的重点
const progressJoin = tutorialIds.length
? and(
eq(schema.tutorialProgress.userId, schema.user.id),
inArray(schema.tutorialProgress.tutorialId, tutorialIds),
)
: sql`false`
// 阅读和练习**分两条查**再在内存里拼。写成一条的话,一个学生读了 3 课、
// 做了 8 道练习,join 出来是 24 行,count 全是错的 —— 两个一对多挂在同一张表上
// 就是这个下场,用 filter 也救不回来
const [rows, exerciseRows] = await Promise.all([
db
.select({
userId: schema.user.id,
username: schema.user.username,
realName: schema.userProfile.realName,
className: schema.user.className,
// 「已读」按 TUTORIAL_READ_SECONDS 卡,不是「有这条记录」:点开一眼就退的不算。
// 累计时长不卡,那些秒数照样算 —— 「已读 0 课、累计 25 分钟」是要看见的一种情况
readCount:
sql<number>`count(${schema.tutorialProgress.tutorialId}) filter (where ${schema.tutorialProgress.totalSeconds} >= ${TUTORIAL_READ_SECONDS})`.mapWith(
Number,
),
totalSeconds:
sql<number>`coalesce(sum(${schema.tutorialProgress.totalSeconds}), 0)`.mapWith(
Number,
),
lastViewedAt: sql<
string | null
>`max(${schema.tutorialProgress.lastViewedAt})`,
})
.from(schema.user)
.leftJoin(
schema.userProfile,
eq(schema.userProfile.userId, schema.user.id),
)
.leftJoin(schema.tutorialProgress, progressJoin)
.where(studentCondition(className.value))
.groupBy(
schema.user.id,
schema.user.username,
schema.userProfile.realName,
schema.user.className,
)
// 前端默认按「已读」升序排,同分的一大批(尤其一堆 0)就落回这里的次序。
// 不给 orderBy 的话那是聚合吐出来的任意顺序,刷一次换一个样 —— 按班级、
// 学号排稳住它。className 为空的(推不出班级的)ASC 默认排在最后
.orderBy(asc(schema.user.className), asc(schema.user.username)),
db
.select({
userId: schema.exerciseAttempt.userId,
tried: count(),
solved:
sql<number>`count(*) filter (where ${schema.exerciseAttempt.solved})`.mapWith(
Number,
),
attempts:
sql<number>`coalesce(sum(${schema.exerciseAttempt.attempts}), 0)`.mapWith(
Number,
),
})
.from(schema.exerciseAttempt)
.innerJoin(
schema.exercise,
eq(schema.exercise.id, schema.exerciseAttempt.exerciseId),
)
.innerJoin(
schema.tutorial,
eq(schema.tutorial.id, schema.exercise.tutorialId),
)
.where(
and(eq(schema.tutorial.isPublic, true), eq(schema.tutorial.type, type)),
)
.groupBy(schema.exerciseAttempt.userId),
])
const attempts = new Map(exerciseRows.map((row) => [row.userId, row]))
const [exerciseCountRow] = tutorialIds.length
? await db
.select({ value: count() })
.from(schema.exercise)
.where(inArray(schema.exercise.tutorialId, tutorialIds))
: [{ value: 0 }]
return success(c, {
tutorialCount: tutorialIds.length,
exerciseCount: exerciseCountRow?.value ?? 0,
results: rows.map(
(row) =>
({
...row,
exerciseTried: attempts.get(row.userId)?.tried ?? 0,
exerciseSolved: attempts.get(row.userId)?.solved ?? 0,
exerciseAttempts: attempts.get(row.userId)?.attempts ?? 0,
}) satisfies LearnStudentProgress,
),
} satisfies LearnStudentProgressList)
})
adminLearnRoutes.get(
"/learn-analytics/tutorials",
requireTeacher,
async (c) => {
const type = tutorialTypeOf(c.req.query("type"))
const className = classFilter(c.req.query("className"))
if (!className.ok) return failure(c, 400, "invalid-class", "班级只能是数字")
const [studentCountRow] = await db
.select({ value: count() })
.from(schema.user)
.where(studentCondition(className.value))
const studentCount = studentCountRow?.value ?? 0
// 进度行 join 回 user 是为了让班级筛选生效,同时把老师自己试读的记录挡在外面
const rows = await db
.select({
tutorialId: schema.tutorial.id,
title: schema.tutorial.title,
order: schema.tutorial.order,
// 数的是 user.id 而不是 progress.user_idjoin 不上的(老师自己试读的、
// 已禁用的、不在所选班级的)在这一列是 NULL,count(distinct) 正好不算它,
// 而 progress.user_id 那边永远非空,会把过滤当没发生
readers:
sql<number>`count(distinct ${schema.user.id}) filter (where ${schema.tutorialProgress.totalSeconds} >= ${TUTORIAL_READ_SECONDS})`.mapWith(
Number,
),
totalSeconds:
sql<number>`coalesce(sum(${schema.tutorialProgress.totalSeconds}) filter (where ${schema.user.id} is not null), 0)`.mapWith(
Number,
),
// 人均时长的分母是 readers(读满 3 分钟的人),分子就得是同一批人的时长,
// 否则拿全部时长去除达标人数,人均会被翻了一眼就走的人凭空抬高
readSeconds:
sql<number>`coalesce(sum(${schema.tutorialProgress.totalSeconds}) filter (where ${schema.tutorialProgress.totalSeconds} >= ${TUTORIAL_READ_SECONDS}), 0)`.mapWith(
Number,
),
})
.from(schema.tutorial)
.leftJoin(
schema.tutorialProgress,
eq(schema.tutorialProgress.tutorialId, schema.tutorial.id),
)
.leftJoin(
schema.user,
and(
eq(schema.user.id, schema.tutorialProgress.userId),
studentCondition(className.value),
),
)
// 学生条件写在 join 的 on 上而不是 where 上:写 where 会把没人读过的课整行滤掉,
// 而「一节课一个人都没读」恰恰是老师最需要看见的一行
.where(
and(eq(schema.tutorial.isPublic, true), eq(schema.tutorial.type, type)),
)
.groupBy(schema.tutorial.id, schema.tutorial.title, schema.tutorial.order)
.orderBy(asc(schema.tutorial.order))
return success(c, {
studentCount,
results: rows.map(
({ readSeconds, ...row }) =>
({
...row,
avgSeconds: row.readers ? Math.round(readSeconds / row.readers) : 0,
}) satisfies LearnTutorialProgress,
),
} satisfies LearnTutorialProgressList)
},
)
/**
*
*
* /
*
*/
adminLearnRoutes.get(
"/learn-analytics/exercises",
requireTeacher,
async (c) => {
const type = tutorialTypeOf(c.req.query("type"))
const className = classFilter(c.req.query("className"))
if (!className.ok) return failure(c, 400, "invalid-class", "班级只能是数字")
const [studentCountRow] = await db
.select({ value: count() })
.from(schema.user)
.where(studentCondition(className.value))
const rows = await db
.select({
exerciseId: schema.exercise.id,
tutorialId: schema.tutorial.id,
tutorialTitle: schema.tutorial.title,
tutorialOrder: schema.tutorial.order,
type: schema.exercise.type,
order: schema.exercise.order,
// 题干在 jsonb 里,各题型的字段名都叫 question;取不到就给空串,别让整行挂掉
question: sql<string>`coalesce(${schema.exercise.data}->>'question', '')`,
triedUsers: sql<number>`count(distinct ${schema.user.id})`.mapWith(
Number,
),
solvedUsers:
sql<number>`count(distinct ${schema.user.id}) filter (where ${schema.exerciseAttempt.solved})`.mapWith(
Number,
),
firstTryUsers:
sql<number>`count(distinct ${schema.user.id}) filter (where ${schema.exerciseAttempt.attemptsToSolve} = 1)`.mapWith(
Number,
),
attempts:
sql<number>`coalesce(sum(${schema.exerciseAttempt.attempts}) filter (where ${schema.user.id} is not null), 0)`.mapWith(
Number,
),
// 只算做对的人:没做对的人「试了几次」还没停,混进平均值只会把它拉花
avgAttemptsToSolve:
sql<number>`coalesce(avg(${schema.exerciseAttempt.attemptsToSolve}) filter (where ${schema.user.id} is not null), 0)`.mapWith(
Number,
),
})
.from(schema.exercise)
.innerJoin(
schema.tutorial,
eq(schema.tutorial.id, schema.exercise.tutorialId),
)
.leftJoin(
schema.exerciseAttempt,
eq(schema.exerciseAttempt.exerciseId, schema.exercise.id),
)
// 学生条件挂在 join 的 on 上,不是 where 上:写 where 会把没人做过的题整行滤掉
.leftJoin(
schema.user,
and(
eq(schema.user.id, schema.exerciseAttempt.userId),
studentCondition(className.value),
),
)
.where(
and(eq(schema.tutorial.isPublic, true), eq(schema.tutorial.type, type)),
)
.groupBy(
schema.exercise.id,
schema.tutorial.id,
schema.tutorial.title,
schema.tutorial.order,
)
.orderBy(asc(schema.tutorial.order), asc(schema.exercise.order))
return success(c, {
studentCount: studentCountRow?.value ?? 0,
results: rows.map(
(row) =>
({
...row,
avgAttemptsToSolve: rounded(Number(row.avgAttemptsToSolve), 1),
}) satisfies LearnExerciseProgress,
),
} satisfies LearnExerciseProgressList)
},
)
/** 单道练习的逐人明细。后台表格展开某一行时才拉,不跟着列表一起下发 */
adminLearnRoutes.get(
"/learn-analytics/exercises/:id/attempts",
requireTeacher,
async (c) => {
const id = queryInteger(c.req.param("id"), 0, { min: 1 })
const className = classFilter(c.req.query("className"))
if (!className.ok) return failure(c, 400, "invalid-class", "班级只能是数字")
const rows = await db
.select({
userId: schema.user.id,
username: schema.user.username,
realName: schema.userProfile.realName,
className: schema.user.className,
attempts: schema.exerciseAttempt.attempts,
wrongAttempts: schema.exerciseAttempt.wrongAttempts,
solved: schema.exerciseAttempt.solved,
attemptsToSolve: schema.exerciseAttempt.attemptsToSolve,
lastWrongAnswer: schema.exerciseAttempt.lastWrongAnswer,
lastAttemptAt: schema.exerciseAttempt.lastAttemptAt,
})
.from(schema.exerciseAttempt)
.innerJoin(schema.user, eq(schema.user.id, schema.exerciseAttempt.userId))
.leftJoin(
schema.userProfile,
eq(schema.userProfile.userId, schema.user.id),
)
.where(
and(
eq(schema.exerciseAttempt.exerciseId, id),
studentCondition(className.value),
),
)
// 没做对的排前面,错得最多的最前 —— 展开这一行的人是来找卡住的学生的
.orderBy(
asc(schema.exerciseAttempt.solved),
desc(schema.exerciseAttempt.wrongAttempts),
)
return success(c, rows satisfies LearnExerciseAttempt[])
},
)
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+362 -167
View File
@@ -1,30 +1,53 @@
import {
acTrendSchema,
adminTagSchema,
batchProblemTagRequestSchema,
batchProblemTagResponseSchema,
generateFlowchartRequestSchema,
generateFlowchartResponseSchema,
renameTagRequestSchema,
renameTagResponseSchema,
stuckProblemSchema,
type AcTrend,
type AdminTag,
type BatchProblemTagResponse,
type GenerateFlowchartResponse,
type RenameTagResponse,
type StuckProblem,
} from "@oj2/contract"
import { and, asc, countDistinct, count, desc, eq, gte, ilike, inArray, isNull, lte, ne, sql } from "drizzle-orm"
import {
and,
asc,
countDistinct,
count,
desc,
eq,
gte,
ilike,
inArray,
isNull,
lte,
ne,
sql,
} from "drizzle-orm"
import { Hono } from "hono"
import { requireProblemPermission, requireTeacher, type AppEnv } from "../../auth/middleware"
import {
requireProblemPermission,
requireTeacher,
type AppEnv,
} from "../../auth/middleware"
import type { AuthUser } from "../../auth/session"
import { db, schema } from "../../db"
import { failure, success } from "../../http"
import { JudgeStatus } from "../../judge/status"
import { completeChat } from "../../services/ai"
import { localTime, localYear } from "../../time"
import { queryInteger, rounded } from "../helpers"
import { findTagsByName, normalizeTagNames } from "./problem"
export const adminTagRoutes = new Hono<AppEnv>()
const ACCEPTED = [JudgeStatus.ACCEPTED, JudgeStatus.AST_CHECK_FAILED]
const FAILED = [JudgeStatus.WRONG_ANSWER, JudgeStatus.COMPILE_ERROR, JudgeStatus.RUNTIME_ERROR]
const FAILED = [
JudgeStatus.WRONG_ANSWER,
JudgeStatus.COMPILE_ERROR,
JudgeStatus.RUNTIME_ERROR,
]
/** 能管所有题目:超管,或 problemPermission 为 All */
function canManageAllProblems(user: AuthUser) {
@@ -35,147 +58,250 @@ function canManageAllProblems(user: AuthUser) {
adminTagRoutes.get("/problem-tags", requireProblemPermission, async (c) => {
const keyword = c.req.query("keyword")?.trim()
const rows = await db.select({
id: schema.problemTag.id,
name: schema.problemTag.name,
problemCount: countDistinct(schema.problemTags.problemId),
}).from(schema.problemTag)
.leftJoin(schema.problemTags, eq(schema.problemTags.problemtagId, schema.problemTag.id))
const rows = await db
.select({
id: schema.problemTag.id,
name: schema.problemTag.name,
problemCount: countDistinct(schema.problemTags.problemId),
})
.from(schema.problemTag)
.leftJoin(
schema.problemTags,
eq(schema.problemTags.problemtagId, schema.problemTag.id),
)
.where(keyword ? ilike(schema.problemTag.name, `%${keyword}%`) : undefined)
.groupBy(schema.problemTag.id, schema.problemTag.name)
// 后台标签管理要看到 problemCount=0 的标签(正是要清理的那些),
// 所以这里用 leftJoin 且不加 having —— oj 侧的 /problem-tags 才过滤 >0
.orderBy(desc(countDistinct(schema.problemTags.problemId)), asc(schema.problemTag.name))
return success(c, rows.map((row) => adminTagSchema.parse(row)))
.orderBy(
desc(countDistinct(schema.problemTags.problemId)),
asc(schema.problemTag.name),
)
return success(c, rows satisfies AdminTag[])
})
adminTagRoutes.put("/problem-tags/:id", requireProblemPermission, async (c) => {
const id = queryInteger(c.req.param("id"), 0, { min: 1 })
const parsed = renameTagRequestSchema.safeParse(await c.req.json().catch(() => null))
if (!parsed.success) return failure(c, 400, "invalid-request", "标签名不能为空")
const parsed = renameTagRequestSchema.safeParse(
await c.req.json().catch(() => null),
)
if (!parsed.success)
return failure(c, 400, "invalid-request", "标签名不能为空")
const name = parsed.data.name
const [tag] = await db.select().from(schema.problemTag).where(eq(schema.problemTag.id, id)).limit(1)
const [tag] = await db
.select()
.from(schema.problemTag)
.where(eq(schema.problemTag.id, id))
.limit(1)
if (!tag) return failure(c, 404, "tag-not-found", "标签不存在,请刷新后重试")
const [target] = await db.select().from(schema.problemTag)
.where(and(sql`lower(${schema.problemTag.name}) = lower(${name})`, ne(schema.problemTag.id, id))).limit(1)
const [target] = await db
.select()
.from(schema.problemTag)
.where(
and(
sql`lower(${schema.problemTag.name}) = lower(${name})`,
ne(schema.problemTag.id, id),
),
)
.limit(1)
if (!target) {
await db.update(schema.problemTag).set({ name }).where(eq(schema.problemTag.id, id))
return success(c, renameTagResponseSchema.parse({ merged: false, id, name, affectedCount: 0 }))
await db
.update(schema.problemTag)
.set({ name })
.where(eq(schema.problemTag.id, id))
return success(c, {
merged: false,
id,
name,
affectedCount: 0,
} satisfies RenameTagResponse)
}
// 改名撞上已有标签,视为合并:题目关系转移过去,原标签删除
const affected = await db.transaction(async (tx) => {
const links = await tx.select({ problemId: schema.problemTags.problemId })
.from(schema.problemTags).where(eq(schema.problemTags.problemtagId, id))
const already = new Set((await tx.select({ problemId: schema.problemTags.problemId })
.from(schema.problemTags).where(eq(schema.problemTags.problemtagId, target.id)))
.map((row) => row.problemId))
const links = await tx
.select({ problemId: schema.problemTags.problemId })
.from(schema.problemTags)
.where(eq(schema.problemTags.problemtagId, id))
const already = new Set(
(
await tx
.select({ problemId: schema.problemTags.problemId })
.from(schema.problemTags)
.where(eq(schema.problemTags.problemtagId, target.id))
).map((row) => row.problemId),
)
// 只给还没挂目标标签的题目补关系,否则会撞 (problem_id, problemtag_id) 唯一约束
const missing = links.filter((link) => !already.has(link.problemId))
if (missing.length) {
await tx.insert(schema.problemTags).values(missing.map((link) => ({
problemId: link.problemId,
problemtagId: target.id,
})))
await tx.insert(schema.problemTags).values(
missing.map((link) => ({
problemId: link.problemId,
problemtagId: target.id,
})),
)
}
await tx.delete(schema.problemTags).where(eq(schema.problemTags.problemtagId, id))
// 旧标签上剩下的关系行随标签一起没:problem_tags.problemtag_id 是 CASCADE0010)。
// 上面那批 insert 已经把题目挂到 target 上了,这里删掉的只是旧的那一份关系。
await tx.delete(schema.problemTag).where(eq(schema.problemTag.id, id))
return links.length
})
return success(c, renameTagResponseSchema.parse({
merged: true, id: target.id, name: target.name, affectedCount: affected,
}))
return success(c, {
merged: true,
id: target.id,
name: target.name,
affectedCount: affected,
} satisfies RenameTagResponse)
})
adminTagRoutes.delete("/problem-tags/:id", requireProblemPermission, async (c) => {
const id = queryInteger(c.req.param("id"), 0, { min: 1 })
// 中间表是 NO ACTION 外键,得先清关系再删标签
const deleted = await db.transaction(async (tx) => {
await tx.delete(schema.problemTags).where(eq(schema.problemTags.problemtagId, id))
return tx.delete(schema.problemTag).where(eq(schema.problemTag.id, id))
adminTagRoutes.delete(
"/problem-tags/:id",
requireProblemPermission,
async (c) => {
const id = queryInteger(c.req.param("id"), 0, { min: 1 })
// 中间表 problem_tags 随标签一起清:problemtag_id 是 CASCADE0010
const deleted = await db
.delete(schema.problemTag)
.where(eq(schema.problemTag.id, id))
.returning({ id: schema.problemTag.id })
})
if (deleted.length === 0) return failure(c, 404, "tag-not-found", "标签不存在,请刷新后重试")
return success(c, null)
})
if (deleted.length === 0)
return failure(c, 404, "tag-not-found", "标签不存在,请刷新后重试")
return success(c, null)
},
)
adminTagRoutes.post("/problems/batch-tag", requireProblemPermission, async (c) => {
const parsed = batchProblemTagRequestSchema.safeParse(await c.req.json().catch(() => null))
if (!parsed.success) {
return failure(c, 400, "invalid-request", parsed.error.issues[0]?.message ?? "参数错误")
}
const user = c.get("user")!
const filters = [inArray(schema.problem.id, parsed.data.problemIds), isNull(schema.problem.contestId)]
if (!canManageAllProblems(user)) filters.push(eq(schema.problem.createdById, user.id))
const problems = await db.select({ id: schema.problem.id }).from(schema.problem).where(and(...filters))
if (problems.length === 0) return failure(c, 404, "no-problems", "没有可操作的题目")
adminTagRoutes.post(
"/problems/batch-tag",
requireProblemPermission,
async (c) => {
const parsed = batchProblemTagRequestSchema.safeParse(
await c.req.json().catch(() => null),
)
if (!parsed.success) {
return failure(
c,
400,
"invalid-request",
parsed.error.issues[0]?.message ?? "参数错误",
)
}
const user = c.get("user")!
const filters = [
inArray(schema.problem.id, parsed.data.problemIds),
isNull(schema.problem.contestId),
]
if (!canManageAllProblems(user))
filters.push(eq(schema.problem.createdById, user.id))
const problems = await db
.select({ id: schema.problem.id })
.from(schema.problem)
.where(and(...filters))
if (problems.length === 0)
return failure(c, 404, "no-problems", "没有可操作的题目")
// 去重且大小写不敏感,与旧 resolve_tags / find_tags 一致
const wanted = normalizeTagNames(parsed.data.tagNames)
// 去重且大小写不敏感,与旧 resolve_tags / find_tags 一致
const wanted = normalizeTagNames(parsed.data.tagNames)
const tagIds = await db.transaction(async (tx) => {
const existing = await findTagsByName(tx as unknown as typeof db, wanted)
// 添加时按需新建标签,移除时只认已有标签 —— 否则「移除」会顺手造出一堆空标签
if (parsed.data.action === "add") {
const missing = wanted.filter((name) => !existing.has(name.toLowerCase()))
if (missing.length) {
const created = await tx.insert(schema.problemTag).values(missing.map((name) => ({ name })))
.returning({ id: schema.problemTag.id, name: schema.problemTag.name })
for (const row of created) existing.set(row.name.toLowerCase(), row.id)
const tagIds = await db.transaction(async (tx) => {
const existing = await findTagsByName(tx as unknown as typeof db, wanted)
// 添加时按需新建标签,移除时只认已有标签 —— 否则「移除」会顺手造出一堆空标签
if (parsed.data.action === "add") {
const missing = wanted.filter(
(name) => !existing.has(name.toLowerCase()),
)
if (missing.length) {
const created = await tx
.insert(schema.problemTag)
.values(missing.map((name) => ({ name })))
.returning({
id: schema.problemTag.id,
name: schema.problemTag.name,
})
for (const row of created)
existing.set(row.name.toLowerCase(), row.id)
}
}
}
return wanted.map((name) => existing.get(name.toLowerCase())).filter((id) => id !== undefined)
})
if (tagIds.length === 0) return failure(c, 404, "no-tags", "没有匹配的标签")
return wanted
.map((name) => existing.get(name.toLowerCase()))
.filter((id) => id !== undefined)
})
if (tagIds.length === 0) return failure(c, 404, "no-tags", "没有匹配的标签")
const problemIds = problems.map((problem) => problem.id)
await db.transaction(async (tx) => {
if (parsed.data.action === "remove") {
await tx.delete(schema.problemTags).where(and(
inArray(schema.problemTags.problemId, problemIds),
inArray(schema.problemTags.problemtagId, tagIds),
))
return
}
const existing = await tx.select().from(schema.problemTags).where(and(
inArray(schema.problemTags.problemId, problemIds),
inArray(schema.problemTags.problemtagId, tagIds),
))
const have = new Set(existing.map((row) => `${row.problemId}:${row.problemtagId}`))
const rows = []
for (const problemId of problemIds) {
for (const tagId of tagIds) {
if (!have.has(`${problemId}:${tagId}`)) rows.push({ problemId, problemtagId: tagId })
const problemIds = problems.map((problem) => problem.id)
await db.transaction(async (tx) => {
if (parsed.data.action === "remove") {
await tx
.delete(schema.problemTags)
.where(
and(
inArray(schema.problemTags.problemId, problemIds),
inArray(schema.problemTags.problemtagId, tagIds),
),
)
return
}
}
if (rows.length) await tx.insert(schema.problemTags).values(rows)
})
const existing = await tx
.select()
.from(schema.problemTags)
.where(
and(
inArray(schema.problemTags.problemId, problemIds),
inArray(schema.problemTags.problemtagId, tagIds),
),
)
const have = new Set(
existing.map((row) => `${row.problemId}:${row.problemtagId}`),
)
const rows = []
for (const problemId of problemIds) {
for (const tagId of tagIds) {
if (!have.has(`${problemId}:${tagId}`))
rows.push({ problemId, problemtagId: tagId })
}
}
if (rows.length) await tx.insert(schema.problemTags).values(rows)
})
return success(c, batchProblemTagResponseSchema.parse({
problemCount: problems.length,
tagCount: tagIds.length,
}))
})
return success(c, {
problemCount: problems.length,
tagCount: tagIds.length,
} satisfies BatchProblemTagResponse)
},
)
// ---------------------------------------------------------------- 题目可见性
adminTagRoutes.put("/problems/:id/visibility", requireProblemPermission, async (c) => {
const id = queryInteger(c.req.param("id"), 0, { min: 1 })
const [problem] = await db.select({ id: schema.problem.id, visible: schema.problem.visible, createdById: schema.problem.createdById })
.from(schema.problem).where(eq(schema.problem.id, id)).limit(1)
// 旧后端这里的 `self.error(...)` 少写了 return,题目不存在时会继续往下跑并抛
// AttributeError500)。这里正常返回 404。
if (!problem) return failure(c, 404, "problem-not-found", "题目不存在")
const user = c.get("user")!
if (!canManageAllProblems(user) && problem.createdById !== user.id) {
return failure(c, 404, "problem-not-found", "题目不存在")
}
await db.update(schema.problem).set({ visible: !problem.visible }).where(eq(schema.problem.id, id))
return success(c, { visible: !problem.visible })
})
adminTagRoutes.put(
"/problems/:id/visibility",
requireProblemPermission,
async (c) => {
const id = queryInteger(c.req.param("id"), 0, { min: 1 })
const [problem] = await db
.select({
id: schema.problem.id,
visible: schema.problem.visible,
createdById: schema.problem.createdById,
})
.from(schema.problem)
.where(eq(schema.problem.id, id))
.limit(1)
// 旧后端这里的 `self.error(...)` 少写了 return,题目不存在时会继续往下跑并抛
// AttributeError500)。这里正常返回 404。
if (!problem) return failure(c, 404, "problem-not-found", "题目不存在")
const user = c.get("user")!
if (!canManageAllProblems(user) && problem.createdById !== user.id) {
return failure(c, 404, "problem-not-found", "题目不存在")
}
await db
.update(schema.problem)
.set({ visible: !problem.visible })
.where(eq(schema.problem.id, id))
return success(c, { visible: !problem.visible })
},
)
// ---------------------------------------------------------------- 卡点题目 / AC 趋势
@@ -185,65 +311,127 @@ adminTagRoutes.put("/problems/:id/visibility", requireProblemPermission, async (
// requireTeacher,而且完全没有报错。换个前缀,结构上就不可能再被遮蔽。
adminTagRoutes.get("/problem-analytics/stuck", requireTeacher, async (c) => {
const failedFilter = sql`filter (where ${inArray(schema.submission.result, FAILED)})`
const rows = await db.select({
displayId: schema.problem.displayId,
title: schema.problem.title,
total: count(),
accepted: sql<number>`count(*) filter (where ${inArray(schema.submission.result, ACCEPTED)})`.mapWith(Number),
failed: sql<number>`count(*) ${failedFilter}`.mapWith(Number),
failedUsers: sql<number>`count(distinct ${schema.submission.userId}) ${failedFilter}`.mapWith(Number),
}).from(schema.submission)
.innerJoin(schema.problem, eq(schema.submission.problemId, schema.problem.id))
const rows = await db
.select({
displayId: schema.problem.displayId,
title: schema.problem.title,
total: count(),
accepted:
sql<number>`count(*) filter (where ${inArray(schema.submission.result, ACCEPTED)})`.mapWith(
Number,
),
failed: sql<number>`count(*) ${failedFilter}`.mapWith(Number),
failedUsers:
sql<number>`count(distinct ${schema.submission.userId}) ${failedFilter}`.mapWith(
Number,
),
})
.from(schema.submission)
.innerJoin(
schema.problem,
eq(schema.submission.problemId, schema.problem.id),
)
/**
* ac-trend where
* 1 61
* 1 40
*
* 40 97 59
* 95
*
* **** problem
* 0
* 0013 submission_public_metrics_idx173ms 82ms
*/
.where(isNull(schema.submission.contestId))
.groupBy(schema.problem.id, schema.problem.displayId, schema.problem.title)
.having(sql`count(distinct ${schema.submission.userId}) ${failedFilter} > 0`)
.orderBy(desc(sql`count(distinct ${schema.submission.userId}) ${failedFilter}`))
.having(
sql`count(distinct ${schema.submission.userId}) ${failedFilter} > 0`,
)
.orderBy(
desc(sql`count(distinct ${schema.submission.userId}) ${failedFilter}`),
)
.limit(40)
return success(c, rows.map((row) => stuckProblemSchema.parse({
problemId: row.displayId,
problemTitle: row.title,
total: row.total,
failed: row.failed,
failedUsers: row.failedUsers,
acRate: row.total ? rounded((row.accepted / row.total) * 100, 1) : 0,
})))
return success(
c,
rows.map(
(row) =>
({
problemId: row.displayId,
problemTitle: row.title,
total: row.total,
failed: row.failed,
failedUsers: row.failedUsers,
acRate: row.total ? rounded((row.accepted / row.total) * 100, 1) : 0,
}) satisfies StuckProblem,
),
)
})
adminTagRoutes.get("/problem-analytics/ac-trend", requireTeacher, async (c) => {
const currentYear = new Date().getFullYear()
const currentYear = localYear()
// 参数按旧后端的口径夹逼:越界一律回落到默认值,不报错
let sinceYear = queryInteger(c.req.query("sinceYear"), 2023)
if (sinceYear < 2022 || sinceYear > currentYear) sinceYear = 2023
let untilYear = queryInteger(c.req.query("untilYear"), currentYear)
if (untilYear < sinceYear || untilYear > currentYear) untilYear = currentYear - 1
if (untilYear < sinceYear || untilYear > currentYear)
untilYear = currentYear - 1
let minPerYear = queryInteger(c.req.query("minPerYear"), 100)
if (![50, 100, 200].includes(minPerYear)) minPerYear = 100
const year = sql<number>`extract(year from ${schema.submission.createTime})`.mapWith(Number)
const rows = await db.select({
problemId: schema.problem.id,
displayId: schema.problem.displayId,
title: schema.problem.title,
year,
total: count(),
accepted: sql<number>`count(*) filter (where ${inArray(schema.submission.result, ACCEPTED)})`.mapWith(Number),
}).from(schema.submission)
.innerJoin(schema.problem, eq(schema.submission.problemId, schema.problem.id))
.where(and(
isNull(schema.submission.contestId),
gte(sql`extract(year from ${schema.submission.createTime})`, sinceYear),
lte(sql`extract(year from ${schema.submission.createTime})`, untilYear),
))
.groupBy(schema.problem.id, schema.problem.displayId, schema.problem.title, year)
// 年份按东八区切,和上面 `currentYear` 的夹逼同口径
const year =
sql<number>`extract(year from ${localTime(schema.submission.createTime)})`.mapWith(
Number,
)
const rows = await db
.select({
problemId: schema.problem.id,
displayId: schema.problem.displayId,
title: schema.problem.title,
year,
total: count(),
accepted:
sql<number>`count(*) filter (where ${inArray(schema.submission.result, ACCEPTED)})`.mapWith(
Number,
),
})
.from(schema.submission)
.innerJoin(
schema.problem,
eq(schema.submission.problemId, schema.problem.id),
)
.where(
and(
isNull(schema.submission.contestId),
gte(year, sinceYear),
lte(year, untilYear),
),
)
.groupBy(
schema.problem.id,
schema.problem.displayId,
schema.problem.title,
year,
)
.orderBy(asc(schema.problem.id), asc(year))
const required = new Set<number>()
for (let y = sinceYear; y <= untilYear; y += 1) required.add(y)
const grouped = new Map<number, { displayId: string; title: string; yearly: typeof rows }>()
const grouped = new Map<
number,
{ displayId: string; title: string; yearly: typeof rows }
>()
for (const row of rows) {
const bucket = grouped.get(row.problemId)
if (bucket) bucket.yearly.push(row)
else grouped.set(row.problemId, { displayId: row.displayId, title: row.title, yearly: [row] })
else
grouped.set(row.problemId, {
displayId: row.displayId,
title: row.title,
yearly: [row],
})
}
const result = []
@@ -252,7 +440,7 @@ adminTagRoutes.get("/problem-analytics/ac-trend", requireTeacher, async (c) => {
// 每一年都得有数据,且每年提交量都超过门槛 —— 否则趋势没有可比性
if (![...required].every((y) => years.has(y))) continue
if (!entry.yearly.every((row) => row.total > minPerYear)) continue
result.push(acTrendSchema.parse({
result.push({
problemId: entry.displayId,
problemTitle: entry.title,
yearly: entry.yearly
@@ -263,27 +451,34 @@ adminTagRoutes.get("/problem-analytics/ac-trend", requireTeacher, async (c) => {
acRate: row.total ? rounded((row.accepted / row.total) * 100, 1) : 0,
}))
.sort((left, right) => left.year - right.year),
}))
} satisfies AcTrend)
}
return success(c, result)
})
// ---------------------------------------------------------------- Python → 流程图
adminTagRoutes.post("/problems/flowchart", requireProblemPermission, async (c) => {
const parsed = generateFlowchartRequestSchema.safeParse(await c.req.json().catch(() => null))
if (!parsed.success) return failure(c, 400, "invalid-request", "python 代码不能为空")
try {
const flowchart = await completeChat(
`你是一个可以将Python代码转换为mermaid的助手。
adminTagRoutes.post(
"/problems/flowchart",
requireProblemPermission,
async (c) => {
const parsed = generateFlowchartRequestSchema.safeParse(
await c.req.json().catch(() => null),
)
if (!parsed.success)
return failure(c, 400, "invalid-request", "python 代码不能为空")
try {
const flowchart = await completeChat(
`你是一个可以将Python代码转换为mermaid的助手。
Python代码转换为 Mermaid
mermaid \`\`\` 都不需要。`,
parsed.data.python,
)
return success(c, generateFlowchartResponseSchema.parse({ flowchart }))
} catch (error) {
console.error("Flowchart generation failed", error)
return failure(c, 502, "ai-unavailable", "生成失败,请稍后再试")
}
})
parsed.data.python,
)
return success(c, { flowchart } satisfies GenerateFlowchartResponse)
} catch (error) {
console.error("Flowchart generation failed", error)
return failure(c, 502, "ai-unavailable", "生成失败,请稍后再试")
}
},
)
+164 -74
View File
@@ -1,12 +1,12 @@
import {
adminExerciseSchema,
adminTutorialGroupsSchema,
adminTutorialSchema,
createExerciseRequestSchema,
createTutorialRequestSchema,
setTutorialVisibilityRequestSchema,
updateExerciseRequestSchema,
updateTutorialRequestSchema,
type AdminExercise,
type AdminTutorial,
type AdminTutorialGroups,
} from "@oj2/contract"
import { asc, desc, eq } from "drizzle-orm"
import { Hono } from "hono"
@@ -14,6 +14,7 @@ import { Hono } from "hono"
import { requireSuperAdmin, type AppEnv } from "../../auth/middleware"
import { db, schema } from "../../db"
import { failure, success } from "../../http"
import { exerciseDataError } from "../../services/exercise"
import { objectValue, queryInteger, sampleUser } from "../helpers"
export const adminTutorialRoutes = new Hono<AppEnv>()
@@ -23,7 +24,7 @@ function serializeTutorial(row: {
user: typeof schema.user.$inferSelect
realName: string | null
}) {
return adminTutorialSchema.parse({
return {
id: row.tutorial.id,
title: row.tutorial.title,
content: row.tutorial.content,
@@ -34,12 +35,16 @@ function serializeTutorial(row: {
createdBy: sampleUser(row.user, row.realName),
createdAt: row.tutorial.createdAt,
updatedAt: row.tutorial.updatedAt,
})
} satisfies AdminTutorial
}
function selectTutorial(id: number) {
return db
.select({ tutorial: schema.tutorial, user: schema.user, realName: schema.userProfile.realName })
.select({
tutorial: schema.tutorial,
user: schema.user,
realName: schema.userProfile.realName,
})
.from(schema.tutorial)
.innerJoin(schema.user, eq(schema.tutorial.createdById, schema.user.id))
.leftJoin(schema.userProfile, eq(schema.userProfile.userId, schema.user.id))
@@ -49,137 +54,222 @@ function selectTutorial(id: number) {
adminTutorialRoutes.get("/tutorials", requireSuperAdmin, async (c) => {
const rows = await db
.select({ tutorial: schema.tutorial, user: schema.user, realName: schema.userProfile.realName })
.select({
tutorial: schema.tutorial,
user: schema.user,
realName: schema.userProfile.realName,
})
.from(schema.tutorial)
.innerJoin(schema.user, eq(schema.tutorial.createdById, schema.user.id))
.leftJoin(schema.userProfile, eq(schema.userProfile.userId, schema.user.id))
.orderBy(asc(schema.tutorial.order), desc(schema.tutorial.createdAt))
const all = rows.map(serializeTutorial)
// 分组返回,形状对齐旧 TutorialAdminAPI.get;列表 schema omit 掉了 content/codeZod 会 strip
return success(c, adminTutorialGroupsSchema.parse({
return success(c, {
python: all.filter((item) => item.type === "python"),
c: all.filter((item) => item.type === "c"),
}))
} satisfies AdminTutorialGroups)
})
adminTutorialRoutes.post("/tutorials", requireSuperAdmin, async (c) => {
const parsed = createTutorialRequestSchema.safeParse(await c.req.json().catch(() => null))
const parsed = createTutorialRequestSchema.safeParse(
await c.req.json().catch(() => null),
)
if (!parsed.success) {
return failure(c, 400, "invalid-request", parsed.error.issues[0]?.message ?? "Invalid payload")
return failure(
c,
400,
"invalid-request",
parsed.error.issues[0]?.message ?? "Invalid payload",
)
}
const now = new Date().toISOString()
const [created] = await db.insert(schema.tutorial).values({
...parsed.data,
createdAt: now,
updatedAt: now,
createdById: c.get("user")!.id,
}).returning({ id: schema.tutorial.id })
const [created] = await db
.insert(schema.tutorial)
.values({
...parsed.data,
createdAt: now,
updatedAt: now,
createdById: c.get("user")!.id,
})
.returning({ id: schema.tutorial.id })
const [row] = await selectTutorial(created!.id)
return success(c, serializeTutorial(row!), 201)
})
adminTutorialRoutes.get("/tutorials/:id", requireSuperAdmin, async (c) => {
const [row] = await selectTutorial(queryInteger(c.req.param("id"), 0, { min: 1 }))
if (!row) return failure(c, 404, "tutorial-not-found", "Tutorial does not exist")
const [row] = await selectTutorial(
queryInteger(c.req.param("id"), 0, { min: 1 }),
)
if (!row)
return failure(c, 404, "tutorial-not-found", "Tutorial does not exist")
return success(c, serializeTutorial(row))
})
adminTutorialRoutes.put("/tutorials/:id", requireSuperAdmin, async (c) => {
const id = queryInteger(c.req.param("id"), 0, { min: 1 })
const parsed = updateTutorialRequestSchema.safeParse(await c.req.json().catch(() => null))
const parsed = updateTutorialRequestSchema.safeParse(
await c.req.json().catch(() => null),
)
if (!parsed.success) {
return failure(c, 400, "invalid-request", parsed.error.issues[0]?.message ?? "Invalid payload")
return failure(
c,
400,
"invalid-request",
parsed.error.issues[0]?.message ?? "Invalid payload",
)
}
const updated = await db.update(schema.tutorial)
const updated = await db
.update(schema.tutorial)
.set({ ...parsed.data, updatedAt: new Date().toISOString() })
.where(eq(schema.tutorial.id, id)).returning({ id: schema.tutorial.id })
if (updated.length === 0) return failure(c, 404, "tutorial-not-found", "Tutorial does not exist")
.where(eq(schema.tutorial.id, id))
.returning({ id: schema.tutorial.id })
if (updated.length === 0)
return failure(c, 404, "tutorial-not-found", "Tutorial does not exist")
const [row] = await selectTutorial(id)
return success(c, serializeTutorial(row!))
})
adminTutorialRoutes.put("/tutorials/:id/visibility", requireSuperAdmin, async (c) => {
const id = queryInteger(c.req.param("id"), 0, { min: 1 })
const parsed = setTutorialVisibilityRequestSchema.safeParse(await c.req.json().catch(() => null))
if (!parsed.success) return failure(c, 400, "invalid-request", "isPublic is required")
// 只改可见性,不动 updatedAt —— 上下架不是内容修改,改了会打乱按更新时间排序的直觉
const updated = await db.update(schema.tutorial)
.set({ isPublic: parsed.data.isPublic })
.where(eq(schema.tutorial.id, id)).returning({ id: schema.tutorial.id })
if (updated.length === 0) return failure(c, 404, "tutorial-not-found", "Tutorial does not exist")
const [row] = await selectTutorial(id)
return success(c, serializeTutorial(row!))
})
adminTutorialRoutes.put(
"/tutorials/:id/visibility",
requireSuperAdmin,
async (c) => {
const id = queryInteger(c.req.param("id"), 0, { min: 1 })
const parsed = setTutorialVisibilityRequestSchema.safeParse(
await c.req.json().catch(() => null),
)
if (!parsed.success)
return failure(c, 400, "invalid-request", "isPublic is required")
// 只改可见性,不动 updatedAt —— 上下架不是内容修改,改了会打乱按更新时间排序的直觉
const updated = await db
.update(schema.tutorial)
.set({ isPublic: parsed.data.isPublic })
.where(eq(schema.tutorial.id, id))
.returning({ id: schema.tutorial.id })
if (updated.length === 0)
return failure(c, 404, "tutorial-not-found", "Tutorial does not exist")
const [row] = await selectTutorial(id)
return success(c, serializeTutorial(row!))
},
)
adminTutorialRoutes.delete("/tutorials/:id", requireSuperAdmin, async (c) => {
const id = queryInteger(c.req.param("id"), 0, { min: 1 })
// 必须先删练习。Django 的 on_delete=CASCADE 是**应用层**实现的,
// 库里的外键实际是 NO ACTION(已核对 pg_constraint.confdeltype='a'
// 直接删教程会撞外键约束、变成 500。后台每个 DELETE 都要照此核一遍子表
const deleted = await db.transaction(async (tx) => {
await tx.delete(schema.exercise).where(eq(schema.exercise.tutorialId, id))
return tx.delete(schema.tutorial).where(eq(schema.tutorial.id, id))
.returning({ id: schema.tutorial.id })
})
if (deleted.length === 0) return failure(c, 404, "tutorial-not-found", "Tutorial does not exist")
// 练习与学习留痕都随教程一起没:exercise.tutorial_id 与 tutorial_progress.tutorial_id
// 都是库级 CASCADE。**加子表时要回来想一遍该 CASCADE 还是该拦住**
// 别默认新表会自己连坐 —— 0010 只改了当时存在的那批外键
const deleted = await db
.delete(schema.tutorial)
.where(eq(schema.tutorial.id, id))
.returning({ id: schema.tutorial.id })
if (deleted.length === 0)
return failure(c, 404, "tutorial-not-found", "Tutorial does not exist")
return success(c, null)
})
// ---------------------------------------------------------------- 练习
function serializeExercise(row: typeof schema.exercise.$inferSelect) {
return adminExerciseSchema.parse({
return {
id: row.id,
type: row.type,
data: objectValue(row.data),
order: row.order,
})
} satisfies AdminExercise
}
// 练习挂在教程下,路径嵌套 —— 旧后端是 ?tutorial_id= 查询参数,
// 但它本来就是一对多的从属关系,嵌套路径更贴事实,也省掉「忘了传 tutorial_id」这类错误
adminTutorialRoutes.get("/tutorials/:id/exercises", requireSuperAdmin, async (c) => {
const rows = await db.select().from(schema.exercise)
.where(eq(schema.exercise.tutorialId, queryInteger(c.req.param("id"), 0, { min: 1 })))
.orderBy(asc(schema.exercise.order), asc(schema.exercise.id))
return success(c, rows.map(serializeExercise))
})
adminTutorialRoutes.get(
"/tutorials/:id/exercises",
requireSuperAdmin,
async (c) => {
const rows = await db
.select()
.from(schema.exercise)
.where(
eq(
schema.exercise.tutorialId,
queryInteger(c.req.param("id"), 0, { min: 1 }),
),
)
.orderBy(asc(schema.exercise.order), asc(schema.exercise.id))
return success(c, rows.map(serializeExercise))
},
)
adminTutorialRoutes.post("/exercises", requireSuperAdmin, async (c) => {
const parsed = createExerciseRequestSchema.safeParse(await c.req.json().catch(() => null))
const parsed = createExerciseRequestSchema.safeParse(
await c.req.json().catch(() => null),
)
if (!parsed.success) {
return failure(c, 400, "invalid-request", parsed.error.issues[0]?.message ?? "Invalid payload")
return failure(
c,
400,
"invalid-request",
parsed.error.issues[0]?.message ?? "Invalid payload",
)
}
const [tutorial] = await db.select({ id: schema.tutorial.id }).from(schema.tutorial)
.where(eq(schema.tutorial.id, parsed.data.tutorialId)).limit(1)
if (!tutorial) return failure(c, 404, "tutorial-not-found", "Tutorial does not exist")
const [created] = await db.insert(schema.exercise).values({
tutorialId: parsed.data.tutorialId,
type: parsed.data.type,
data: parsed.data.data,
order: parsed.data.order,
createdAt: new Date().toISOString(),
}).returning()
const [tutorial] = await db
.select({ id: schema.tutorial.id })
.from(schema.tutorial)
.where(eq(schema.tutorial.id, parsed.data.tutorialId))
.limit(1)
if (!tutorial)
return failure(c, 404, "tutorial-not-found", "Tutorial does not exist")
const dataError = exerciseDataError(parsed.data.type, parsed.data.data)
if (dataError) return failure(c, 400, "invalid-exercise", dataError)
const [created] = await db
.insert(schema.exercise)
.values({
tutorialId: parsed.data.tutorialId,
type: parsed.data.type,
data: parsed.data.data,
order: parsed.data.order,
createdAt: new Date().toISOString(),
})
.returning()
return success(c, serializeExercise(created!), 201)
})
adminTutorialRoutes.put("/exercises/:id", requireSuperAdmin, async (c) => {
const parsed = updateExerciseRequestSchema.safeParse(await c.req.json().catch(() => null))
const parsed = updateExerciseRequestSchema.safeParse(
await c.req.json().catch(() => null),
)
if (!parsed.success) {
return failure(c, 400, "invalid-request", parsed.error.issues[0]?.message ?? "Invalid payload")
return failure(
c,
400,
"invalid-request",
parsed.error.issues[0]?.message ?? "Invalid payload",
)
}
const [updated] = await db.update(schema.exercise)
.set({ type: parsed.data.type, data: parsed.data.data, order: parsed.data.order })
.where(eq(schema.exercise.id, queryInteger(c.req.param("id"), 0, { min: 1 })))
const dataError = exerciseDataError(parsed.data.type, parsed.data.data)
if (dataError) return failure(c, 400, "invalid-exercise", dataError)
const [updated] = await db
.update(schema.exercise)
.set({
type: parsed.data.type,
data: parsed.data.data,
order: parsed.data.order,
})
.where(
eq(schema.exercise.id, queryInteger(c.req.param("id"), 0, { min: 1 })),
)
.returning()
if (!updated) return failure(c, 404, "exercise-not-found", "Exercise does not exist")
if (!updated)
return failure(c, 404, "exercise-not-found", "Exercise does not exist")
return success(c, serializeExercise(updated))
})
adminTutorialRoutes.delete("/exercises/:id", requireSuperAdmin, async (c) => {
const deleted = await db.delete(schema.exercise)
.where(eq(schema.exercise.id, queryInteger(c.req.param("id"), 0, { min: 1 })))
const deleted = await db
.delete(schema.exercise)
.where(
eq(schema.exercise.id, queryInteger(c.req.param("id"), 0, { min: 1 })),
)
.returning({ id: schema.exercise.id })
if (deleted.length === 0) return failure(c, 404, "exercise-not-found", "Exercise does not exist")
if (deleted.length === 0)
return failure(c, 404, "exercise-not-found", "Exercise does not exist")
return success(c, null)
})
+998 -184
View File
File diff suppressed because it is too large Load Diff
+158 -69
View File
@@ -1,11 +1,12 @@
import {
classComparisonRequestSchema,
classComparisonResponseSchema,
classComparisonSchema,
classRankItemSchema,
classUserRankSchema,
STUDENT_ROLES,
type ClassComparison,
type ClassComparisonResponse,
type ClassRankItem,
type ClassUserRank,
} from "@oj2/contract"
import { and, asc, eq, gte, inArray, lte, sql } from "drizzle-orm"
import { and, eq, gte, inArray, like, lte, sql } from "drizzle-orm"
import { Hono } from "hono"
import { requireAuth, type AppEnv } from "../auth/middleware"
@@ -24,32 +25,49 @@ interface ClassUser {
submissionNumber: number
}
async function loadClassUsers(classNames?: string[]) {
/**
* AC/`gradePrefix` `241` = 24 1
* SQL like startsWith
* like
*/
async function loadClassUsers(classNames?: string[], gradePrefix?: string) {
const filters = [
eq(schema.user.isDisabled, false),
inArray(schema.user.adminType, ["Regular User", "Student Admin"]),
inArray(schema.user.adminType, [...STUDENT_ROLES]),
sql`${schema.user.className} is not null`,
]
if (classNames) filters.push(inArray(schema.user.className, classNames))
const rows = await db.select({
userId: schema.user.id,
username: schema.user.username,
className: schema.user.className,
acceptedNumber: schema.userProfile.acceptedNumber,
submissionNumber: schema.userProfile.submissionNumber,
}).from(schema.user).innerJoin(schema.userProfile, eq(schema.userProfile.userId, schema.user.id)).where(and(...filters))
if (gradePrefix) filters.push(like(schema.user.className, `${gradePrefix}%`))
const rows = await db
.select({
userId: schema.user.id,
username: schema.user.username,
className: schema.user.className,
acceptedNumber: schema.userProfile.acceptedNumber,
submissionNumber: schema.userProfile.submissionNumber,
})
.from(schema.user)
.innerJoin(
schema.userProfile,
eq(schema.userProfile.userId, schema.user.id),
)
.where(and(...filters))
return rows.filter((row): row is ClassUser => row.className !== null)
}
function mean(values: number[]) {
return values.length ? values.reduce((sum, value) => sum + value, 0) / values.length : 0
return values.length
? values.reduce((sum, value) => sum + value, 0) / values.length
: 0
}
function median(values: number[]) {
if (!values.length) return 0
const sorted = [...values].sort((a, b) => a - b)
const middle = Math.floor(sorted.length / 2)
return sorted.length % 2 ? sorted[middle]! : (sorted[middle - 1]! + sorted[middle]!) / 2
return sorted.length % 2
? sorted[middle]!
: (sorted[middle - 1]! + sorted[middle]!) / 2
}
function quantile(values: number[], p: number) {
@@ -66,35 +84,59 @@ function quantile(values: number[], p: number) {
function sampleStdDev(values: number[]) {
if (values.length <= 1) return 0
const average = mean(values)
return Math.sqrt(values.reduce((sum, value) => sum + (value - average) ** 2, 0) / (values.length - 1))
return Math.sqrt(
values.reduce((sum, value) => sum + (value - average) ** 2, 0) /
(values.length - 1),
)
}
classroomRoutes.get("/rankings/classes", async (c) => {
const grade = c.req.query("grade")?.trim()
if (!grade || !/^\d+$/.test(grade)) return failure(c, 400, "invalid-grade", "grade is required")
const users = (await loadClassUsers()).filter((user) => user.className.startsWith(grade))
if (!grade || !/^\d+$/.test(grade))
return failure(c, 400, "invalid-grade", "grade is required")
const users = await loadClassUsers(undefined, grade)
const groups = new Map<string, ClassUser[]>()
for (const user of users) groups.set(user.className, [...(groups.get(user.className) ?? []), user])
const result = [...groups].map(([className, members]) => {
const totalAc = members.reduce((sum, member) => sum + member.acceptedNumber, 0)
const totalSubmission = members.reduce((sum, member) => sum + member.submissionNumber, 0)
return {
className,
userCount: members.length,
totalAc,
totalSubmission,
avgAc: rounded(totalAc / members.length),
acRate: totalSubmission > 0 ? rounded(totalAc / totalSubmission * 100) : 0,
}
}).sort((a, b) => b.totalAc - a.totalAc || a.totalSubmission - b.totalSubmission)
return success(c, result.map((item, index) => classRankItemSchema.parse({ ...item, rank: index + 1 })))
for (const user of users)
groups.set(user.className, [...(groups.get(user.className) ?? []), user])
const result = [...groups]
.map(([className, members]) => {
const totalAc = members.reduce(
(sum, member) => sum + member.acceptedNumber,
0,
)
const totalSubmission = members.reduce(
(sum, member) => sum + member.submissionNumber,
0,
)
return {
className,
userCount: members.length,
totalAc,
totalSubmission,
avgAc: rounded(totalAc / members.length),
acRate:
totalSubmission > 0 ? rounded((totalAc / totalSubmission) * 100) : 0,
}
})
.sort(
(a, b) => b.totalAc - a.totalAc || a.totalSubmission - b.totalSubmission,
)
return success(
c,
result.map(
(item, index) => ({ ...item, rank: index + 1 }) satisfies ClassRankItem,
),
)
})
classroomRoutes.get("/me/class-rank", requireAuth, async (c) => {
const user = c.get("user")!
if (!user.className) return failure(c, 400, "class-missing", "用户没有班级信息")
if (!user.className)
return failure(c, 400, "class-missing", "用户没有班级信息")
const members = (await loadClassUsers([user.className])).sort(
(a, b) => b.acceptedNumber - a.acceptedNumber || a.submissionNumber - b.submissionNumber,
(a, b) =>
b.acceptedNumber - a.acceptedNumber ||
a.submissionNumber - b.submissionNumber,
)
const ranks = members.map((member, index) => ({
userId: member.userId,
@@ -114,35 +156,64 @@ classroomRoutes.get("/me/class-rank", requireAuth, async (c) => {
const start = Math.min(Math.max(0, myRank - 6), ranks.length - 10)
selected = ranks.slice(start, start + 10)
}
return success(c, classUserRankSchema.parse({ className: user.className, myRank, total: ranks.length, ranks: selected }))
return success(c, {
className: user.className,
myRank,
total: ranks.length,
ranks: selected,
} satisfies ClassUserRank)
})
classroomRoutes.post("/classes/comparison", async (c) => {
const parsed = classComparisonRequestSchema.safeParse(await c.req.json().catch(() => null))
if (!parsed.success) return failure(c, 400, "invalid-request", "At least one class is required")
const parsed = classComparisonRequestSchema.safeParse(
await c.req.json().catch(() => null),
)
if (!parsed.success)
return failure(c, 400, "invalid-request", "At least one class is required")
const users = await loadClassUsers(parsed.data.classNames)
const allAc = users.map((user) => user.acceptedNumber)
const globalQ1 = quantile(allAc, 0.25)
const globalQ3 = quantile(allAc, 0.75)
const byClass = new Map<string, ClassUser[]>()
for (const user of users) byClass.set(user.className, [...(byClass.get(user.className) ?? []), user])
for (const user of users)
byClass.set(user.className, [...(byClass.get(user.className) ?? []), user])
let recentByUser = new Map<number, Set<number>>()
let recentSubmissionCount = new Map<string, number>()
const hasTimeRange = Boolean(parsed.data.startTime && parsed.data.endTime)
if (hasTimeRange) {
const rows = await db.select({ userId: schema.submission.userId, problemId: schema.submission.problemId, result: schema.submission.result })
.from(schema.submission).where(and(
inArray(schema.submission.userId, users.map((user) => user.userId)),
gte(schema.submission.createTime, parsed.data.startTime!),
lte(schema.submission.createTime, parsed.data.endTime!),
))
const userClass = new Map(users.map((user) => [user.userId, user.className]))
const rows = await db
.select({
userId: schema.submission.userId,
problemId: schema.submission.problemId,
result: schema.submission.result,
})
.from(schema.submission)
.where(
and(
inArray(
schema.submission.userId,
users.map((user) => user.userId),
),
gte(schema.submission.createTime, parsed.data.startTime!),
lte(schema.submission.createTime, parsed.data.endTime!),
),
)
const userClass = new Map(
users.map((user) => [user.userId, user.className]),
)
for (const row of rows) {
const className = userClass.get(row.userId)
if (!className) continue
recentSubmissionCount.set(className, (recentSubmissionCount.get(className) ?? 0) + 1)
if ([JudgeStatus.ACCEPTED, JudgeStatus.AST_CHECK_FAILED].includes(row.result as 0 | 10)) {
recentSubmissionCount.set(
className,
(recentSubmissionCount.get(className) ?? 0) + 1,
)
if (
[JudgeStatus.ACCEPTED, JudgeStatus.AST_CHECK_FAILED].includes(
row.result as 0 | 10,
)
) {
const set = recentByUser.get(row.userId) ?? new Set<number>()
set.add(row.problemId)
recentByUser.set(row.userId, set)
@@ -151,15 +222,20 @@ classroomRoutes.post("/classes/comparison", async (c) => {
}
const comparisons = [...byClass].map(([className, members]) => {
const ac = members.map((member) => member.acceptedNumber).sort((a, b) => b - a)
const submissions = members.map((member) => member.submissionNumber).sort((a, b) => b - a)
const ac = members
.map((member) => member.acceptedNumber)
.sort((a, b) => b - a)
const submissions = members
.map((member) => member.submissionNumber)
.sort((a, b) => b - a)
const userCount = members.length
const topCount = Math.max(1, Math.ceil(userCount * 0.1))
const bottomCount = topCount
const middle = topCount + bottomCount < userCount ? ac.slice(topCount, -bottomCount) : ac
const middle =
topCount + bottomCount < userCount ? ac.slice(topCount, -bottomCount) : ac
const totalAc = ac.reduce((sum, value) => sum + value, 0)
const totalSubmission = submissions.reduce((sum, value) => sum + value, 0)
const base: Record<string, number | string> = {
const base: ClassComparison = {
className,
userCount,
totalAc,
@@ -173,38 +249,51 @@ classroomRoutes.post("/classes/comparison", async (c) => {
top10Avg: rounded(mean(ac.slice(0, topCount))),
middle80Avg: rounded(mean(middle)),
bottom10Avg: rounded(mean(ac.slice(-bottomCount))),
excellentRate: rounded(ac.filter((value) => value >= globalQ3).length / userCount * 100),
passRate: rounded(ac.filter((value) => value >= globalQ1).length / userCount * 100),
activeRate: rounded(submissions.filter((value) => value > 0).length / userCount * 100),
acRate: totalSubmission > 0 ? rounded(totalAc / totalSubmission * 100) : 0,
excellentRate: rounded(
(ac.filter((value) => value >= globalQ3).length / userCount) * 100,
),
passRate: rounded(
(ac.filter((value) => value >= globalQ1).length / userCount) * 100,
),
activeRate: rounded(
(submissions.filter((value) => value > 0).length / userCount) * 100,
),
acRate:
totalSubmission > 0 ? rounded((totalAc / totalSubmission) * 100) : 0,
compositeScore: 0,
}
if (hasTimeRange) {
const recent = members.map((member) => recentByUser.get(member.userId)?.size ?? 0).sort((a, b) => b - a)
const recent = members
.map((member) => recentByUser.get(member.userId)?.size ?? 0)
.sort((a, b) => b - a)
base.recentTotalAc = recent.reduce((sum, value) => sum + value, 0)
base.recentTotalSubmission = recentSubmissionCount.get(className) ?? 0
base.recentAvgAc = rounded(mean(recent))
base.recentMedianAc = rounded(median(recent))
base.recentTop10Avg = rounded(mean(recent.slice(0, Math.max(1, Math.ceil(recent.length * 0.1)))))
base.recentTop10Avg = rounded(
mean(recent.slice(0, Math.max(1, Math.ceil(recent.length * 0.1)))),
)
base.recentActiveCount = recent.filter((value) => value > 0).length
}
return base
})
const maxMedian = Math.max(1, ...comparisons.map((item) => Number(item.medianAc)))
const maxMiddle = Math.max(1, ...comparisons.map((item) => Number(item.middle80Avg)))
const maxMedian = Math.max(1, ...comparisons.map((item) => item.medianAc))
const maxMiddle = Math.max(1, ...comparisons.map((item) => item.middle80Avg))
for (const item of comparisons) {
item.compositeScore = rounded(
0.4 * (Number(item.medianAc) / maxMedian * 100) +
0.15 * (Number(item.middle80Avg) / maxMiddle * 100) +
0.2 * Number(item.activeRate) +
0.15 * Number(item.passRate) +
0.1 * Number(item.excellentRate),
0.4 * ((item.medianAc / maxMedian) * 100) +
0.15 * ((item.middle80Avg / maxMiddle) * 100) +
0.2 * item.activeRate +
0.15 * item.passRate +
0.1 * item.excellentRate,
1,
)
}
comparisons.sort((a, b) => Number(b.compositeScore) - Number(a.compositeScore) || Number(b.medianAc) - Number(a.medianAc))
return success(c, classComparisonResponseSchema.parse({
comparisons: comparisons.map((item) => classComparisonSchema.parse(item)),
comparisons.sort(
(a, b) => b.compositeScore - a.compositeScore || b.medianAc - a.medianAc,
)
return success(c, {
comparisons,
hasTimeRange,
}))
} satisfies ClassComparisonResponse)
})
+492 -113
View File
@@ -1,19 +1,24 @@
import {
announcementListItemSchema,
announcementListSchema,
announcementSchema,
createMessageRequestSchema,
exerciseSchema,
messageListSchema,
messageSchema,
reactionKeySchema,
reactionStateSchema,
setReactionRequestSchema,
embeddedSubmissionSchema,
tutorialSchema,
tutorialSummarySchema,
exerciseAttemptRequestSchema,
reactionKeySchema,
setReactionRequestSchema,
tutorialProgressPingSchema,
type Announcement,
type AnnouncementList,
type AnnouncementListItem,
type EmbeddedSubmission,
type Exercise,
type Message,
type MessageList,
type ReactionCounts,
type ReactionState,
type Tutorial,
type TutorialProgress,
type TutorialSummary,
} from "@oj2/contract"
import { and, asc, count, desc, eq, inArray } from "drizzle-orm"
import { and, asc, count, desc, eq, inArray, sql } from "drizzle-orm"
import { Hono } from "hono"
import { requireAuth, requireSuperAdmin, type AppEnv } from "../auth/middleware"
@@ -28,35 +33,76 @@ contentRoutes.get("/announcements", async (c) => {
const limit = queryInteger(c.req.query("limit"), 10, { min: 1, max: 250 })
const offset = queryInteger(c.req.query("offset"), 0, { min: 0 })
const [totalRows, rows] = await Promise.all([
db.select({ value: count() }).from(schema.announcement).where(eq(schema.announcement.visible, true)),
db.select({ announcement: schema.announcement, user: schema.user, realName: schema.userProfile.realName })
.from(schema.announcement).innerJoin(schema.user, eq(schema.announcement.createdById, schema.user.id))
.leftJoin(schema.userProfile, eq(schema.userProfile.userId, schema.user.id))
db
.select({ value: count() })
.from(schema.announcement)
.where(eq(schema.announcement.visible, true)),
db
.select({
announcement: schema.announcement,
user: schema.user,
realName: schema.userProfile.realName,
})
.from(schema.announcement)
.innerJoin(
schema.user,
eq(schema.announcement.createdById, schema.user.id),
)
.leftJoin(
schema.userProfile,
eq(schema.userProfile.userId, schema.user.id),
)
.where(eq(schema.announcement.visible, true))
.orderBy(desc(schema.announcement.top), desc(schema.announcement.createTime)).limit(limit).offset(offset),
.orderBy(
desc(schema.announcement.top),
desc(schema.announcement.createTime),
)
.limit(limit)
.offset(offset),
])
return success(c, announcementListSchema.parse({
results: rows.map(({ announcement, user, realName }) => announcementListItemSchema.parse({
id: announcement.id,
title: announcement.title,
tag: announcement.tag,
top: announcement.top,
createdBy: sampleUser(user, realName),
createTime: announcement.createTime,
lastUpdateTime: announcement.lastUpdateTime,
})),
return success(c, {
results: rows.map(
({ announcement, user, realName }) =>
({
id: announcement.id,
title: announcement.title,
tag: announcement.tag,
top: announcement.top,
createdBy: sampleUser(user, realName),
createTime: announcement.createTime,
lastUpdateTime: announcement.lastUpdateTime,
}) satisfies AnnouncementListItem,
),
total: totalRows[0]?.value ?? 0,
}))
} satisfies AnnouncementList)
})
contentRoutes.get("/announcements/:id", async (c) => {
const id = queryInteger(c.req.param("id"), 0, { min: 1 })
const [row] = await db.select({ announcement: schema.announcement, user: schema.user, realName: schema.userProfile.realName })
.from(schema.announcement).innerJoin(schema.user, eq(schema.announcement.createdById, schema.user.id))
const [row] = await db
.select({
announcement: schema.announcement,
user: schema.user,
realName: schema.userProfile.realName,
})
.from(schema.announcement)
.innerJoin(schema.user, eq(schema.announcement.createdById, schema.user.id))
.leftJoin(schema.userProfile, eq(schema.userProfile.userId, schema.user.id))
.where(and(eq(schema.announcement.id, id), eq(schema.announcement.visible, true))).limit(1)
if (!row) return failure(c, 404, "announcement-not-found", "Announcement does not exist")
return success(c, announcementSchema.parse({
.where(
and(
eq(schema.announcement.id, id),
eq(schema.announcement.visible, true),
),
)
.limit(1)
if (!row)
return failure(
c,
404,
"announcement-not-found",
"Announcement does not exist",
)
return success(c, {
id: row.announcement.id,
title: row.announcement.title,
tag: row.announcement.tag,
@@ -65,7 +111,7 @@ contentRoutes.get("/announcements/:id", async (c) => {
createdBy: sampleUser(row.user, row.realName),
createTime: row.announcement.createTime,
lastUpdateTime: row.announcement.lastUpdateTime,
}))
} satisfies Announcement)
})
contentRoutes.get("/messages", requireAuth, async (c) => {
@@ -73,40 +119,64 @@ contentRoutes.get("/messages", requireAuth, async (c) => {
const limit = queryInteger(c.req.query("limit"), 10, { min: 1, max: 250 })
const offset = queryInteger(c.req.query("offset"), 0, { min: 0 })
const [totalRows, rows] = await Promise.all([
db.select({ value: count() }).from(schema.message).where(eq(schema.message.recipientId, user.id)),
db.select({ message: schema.message, sender: schema.user, realName: schema.userProfile.realName, submission: schema.submission, displayId: schema.problem.displayId })
.from(schema.message).innerJoin(schema.user, eq(schema.message.senderId, schema.user.id))
.leftJoin(schema.userProfile, eq(schema.userProfile.userId, schema.user.id))
.innerJoin(schema.submission, eq(schema.message.submissionId, schema.submission.id))
.innerJoin(schema.problem, eq(schema.submission.problemId, schema.problem.id))
.where(eq(schema.message.recipientId, user.id)).orderBy(desc(schema.message.createTime)).limit(limit).offset(offset),
db
.select({ value: count() })
.from(schema.message)
.where(eq(schema.message.recipientId, user.id)),
db
.select({
message: schema.message,
sender: schema.user,
realName: schema.userProfile.realName,
submission: schema.submission,
displayId: schema.problem.displayId,
})
.from(schema.message)
.innerJoin(schema.user, eq(schema.message.senderId, schema.user.id))
.leftJoin(
schema.userProfile,
eq(schema.userProfile.userId, schema.user.id),
)
.innerJoin(
schema.submission,
eq(schema.message.submissionId, schema.submission.id),
)
.innerJoin(
schema.problem,
eq(schema.submission.problemId, schema.problem.id),
)
.where(eq(schema.message.recipientId, user.id))
.orderBy(desc(schema.message.createTime))
.limit(limit)
.offset(offset),
])
return success(c, messageListSchema.parse({
results: rows.map(({ message, sender, realName, submission, displayId }) => messageSchema.parse({
id: message.id,
sender: sampleUser(sender, realName),
createTime: message.createTime,
message: message.message,
submission: embeddedSubmissionSchema.parse({
id: submission.id,
createTime: submission.createTime,
userId: submission.userId,
username: submission.username,
code: submission.code,
result: submission.result,
// info / ip / contestId 三个字段不在 embeddedSubmissionSchema 里,故不传 ——
// 对齐旧后端 SubmissionSafeModelSerializer 的 exclude,这三个键不出现在响应中
language: submission.language,
shared: submission.shared,
statisticInfo: objectValue(submission.statisticInfo),
// 展示用题号而非数字主键,站内信页面拿它拼 /problem/<题号>
problem: displayId,
showLink: true,
canUnshare: false,
}),
})),
return success(c, {
results: rows.map(
({ message, sender, realName, submission, displayId }) =>
({
id: message.id,
sender: sampleUser(sender, realName),
createTime: message.createTime,
message: message.message,
submission: {
id: submission.id,
createTime: submission.createTime,
userId: submission.userId,
username: submission.username,
code: submission.code,
result: submission.result,
// info / ip / contestId 三个字段不在 embeddedSubmissionSchema 里,故不传 ——
// 对齐旧后端 SubmissionSafeModelSerializer 的 exclude,这三个键不出现在响应中
language: submission.language,
statisticInfo: objectValue(submission.statisticInfo),
// 展示用题号而非数字主键,站内信页面拿它拼 /problem/<题号>
problem: displayId,
showLink: true,
} satisfies EmbeddedSubmission,
}) satisfies Message,
),
total: totalRows[0]?.value ?? 0,
}))
} satisfies MessageList)
})
/**
@@ -117,15 +187,39 @@ contentRoutes.get("/messages", requireAuth, async (c) => {
*/
contentRoutes.post("/messages", requireSuperAdmin, async (c) => {
const user = c.get("user")!
const parsed = createMessageRequestSchema.safeParse(await c.req.json().catch(() => null))
if (!parsed.success) return failure(c, 400, "invalid-request", "Invalid message payload")
if (parsed.data.recipientId === user.id) return failure(c, 400, "invalid-recipient", "Can not send a message to yourself")
const parsed = createMessageRequestSchema.safeParse(
await c.req.json().catch(() => null),
)
if (!parsed.success)
return failure(c, 400, "invalid-request", "Invalid message payload")
if (parsed.data.recipientId === user.id)
return failure(
c,
400,
"invalid-recipient",
"Can not send a message to yourself",
)
const [[recipient], [submission]] = await Promise.all([
db.select({ id: schema.user.id }).from(schema.user).where(and(eq(schema.user.id, parsed.data.recipientId), eq(schema.user.isDisabled, false))).limit(1),
db.select({ id: schema.submission.id }).from(schema.submission).where(eq(schema.submission.id, parsed.data.submissionId)).limit(1),
db
.select({ id: schema.user.id })
.from(schema.user)
.where(
and(
eq(schema.user.id, parsed.data.recipientId),
eq(schema.user.isDisabled, false),
),
)
.limit(1),
db
.select({ id: schema.submission.id })
.from(schema.submission)
.where(eq(schema.submission.id, parsed.data.submissionId))
.limit(1),
])
if (!recipient) return failure(c, 404, "user-not-found", "User does not exist")
if (!submission) return failure(c, 404, "submission-not-found", "Submission does not exist")
if (!recipient)
return failure(c, 404, "user-not-found", "User does not exist")
if (!submission)
return failure(c, 404, "submission-not-found", "Submission does not exist")
await db.insert(schema.message).values({
message: parsed.data.message,
createTime: new Date().toISOString(),
@@ -137,17 +231,29 @@ contentRoutes.post("/messages", requireSuperAdmin, async (c) => {
})
async function reactionState(problemId: number, userId: number) {
const [mine] = await db.select({ type: schema.reaction.type }).from(schema.reaction)
.where(and(eq(schema.reaction.problemId, problemId), eq(schema.reaction.userId, userId))).limit(1)
if (!mine) return reactionStateSchema.parse({ mine: null, counts: null })
const rows = await db.select({ type: schema.reaction.type, value: count() }).from(schema.reaction)
.where(eq(schema.reaction.problemId, problemId)).groupBy(schema.reaction.type)
const counts = Object.fromEntries(reactionKeySchema.options.map((key) => [key, 0]))
for (const row of rows) {
const key = reactionKeySchema.safeParse(row.type)
if (key.success) counts[key.data] = row.value
}
return reactionStateSchema.parse({ mine: mine.type, counts })
const [mine] = await db
.select({ type: schema.reaction.type })
.from(schema.reaction)
.where(
and(
eq(schema.reaction.problemId, problemId),
eq(schema.reaction.userId, userId),
),
)
.limit(1)
if (!mine) return { mine: null, counts: null } satisfies ReactionState
const rows = await db
.select({ type: schema.reaction.type, value: count() })
.from(schema.reaction)
.where(eq(schema.reaction.problemId, problemId))
.groupBy(schema.reaction.type)
// fromEntries 推不出这个键集,但 options 就是 ReactionKey 的全集,断言是成立的。
// row.type 不必再 safeParsereaction.type 列上挂着 $type<ReactionKey>()
const counts = Object.fromEntries(
reactionKeySchema.options.map((key) => [key, 0]),
) as ReactionCounts
for (const row of rows) counts[row.type] = row.value
return { mine: mine.type, counts } satisfies ReactionState
}
contentRoutes.get("/problems/:id/reaction", requireAuth, async (c) => {
@@ -157,42 +263,86 @@ contentRoutes.get("/problems/:id/reaction", requireAuth, async (c) => {
contentRoutes.post("/problems/:id/reaction", requireAuth, async (c) => {
const problemId = queryInteger(c.req.param("id"), 0, { min: 1 })
const parsed = setReactionRequestSchema.safeParse(await c.req.json().catch(() => null))
if (!parsed.success) return failure(c, 400, "invalid-request", "Invalid reaction")
const parsed = setReactionRequestSchema.safeParse(
await c.req.json().catch(() => null),
)
if (!parsed.success)
return failure(c, 400, "invalid-request", "Invalid reaction")
const user = c.get("user")!
const [[problem], [solved]] = await Promise.all([
db.select({ id: schema.problem.id }).from(schema.problem).where(and(eq(schema.problem.id, problemId), eq(schema.problem.visible, true))).limit(1),
db.select({ id: schema.submission.id }).from(schema.submission).where(and(
eq(schema.submission.userId, user.id), eq(schema.submission.problemId, problemId),
inArray(schema.submission.result, [JudgeStatus.ACCEPTED, JudgeStatus.AST_CHECK_FAILED]),
)).limit(1),
db
.select({ id: schema.problem.id })
.from(schema.problem)
.where(
and(eq(schema.problem.id, problemId), eq(schema.problem.visible, true)),
)
.limit(1),
db
.select({ id: schema.submission.id })
.from(schema.submission)
.where(
and(
eq(schema.submission.userId, user.id),
eq(schema.submission.problemId, problemId),
inArray(schema.submission.result, [
JudgeStatus.ACCEPTED,
JudgeStatus.AST_CHECK_FAILED,
]),
),
)
.limit(1),
])
if (!problem) return failure(c, 404, "problem-not-found", "Problem does not exist")
if (!solved) return failure(c, 403, "accepted-submission-required", "An accepted submission is required")
await db.insert(schema.reaction).values({
problemId,
userId: user.id,
type: parsed.data.type,
createTime: new Date().toISOString(),
}).onConflictDoNothing({ target: [schema.reaction.problemId, schema.reaction.userId] })
if (!problem)
return failure(c, 404, "problem-not-found", "Problem does not exist")
if (!solved)
return failure(
c,
403,
"accepted-submission-required",
"An accepted submission is required",
)
await db
.insert(schema.reaction)
.values({
problemId,
userId: user.id,
type: parsed.data.type,
createTime: new Date().toISOString(),
})
.onConflictDoNothing({
target: [schema.reaction.problemId, schema.reaction.userId],
})
return success(c, await reactionState(problemId, user.id))
})
contentRoutes.get("/tutorials", async (c) => {
const type = c.req.query("type") === "c" ? "c" : "python"
const rows = await db.select({ id: schema.tutorial.id, title: schema.tutorial.title }).from(schema.tutorial)
.where(and(eq(schema.tutorial.isPublic, true), eq(schema.tutorial.type, type))).orderBy(asc(schema.tutorial.order))
return success(c, rows.map((row) => tutorialSummarySchema.parse(row)))
const rows = await db
.select({ id: schema.tutorial.id, title: schema.tutorial.title })
.from(schema.tutorial)
.where(
and(eq(schema.tutorial.isPublic, true), eq(schema.tutorial.type, type)),
)
.orderBy(asc(schema.tutorial.order))
return success(c, rows satisfies TutorialSummary[])
})
contentRoutes.get("/tutorials/:id", async (c) => {
const id = queryInteger(c.req.param("id"), 0, { min: 1 })
const [row] = await db.select({ tutorial: schema.tutorial, user: schema.user, realName: schema.userProfile.realName })
.from(schema.tutorial).innerJoin(schema.user, eq(schema.tutorial.createdById, schema.user.id))
const [row] = await db
.select({
tutorial: schema.tutorial,
user: schema.user,
realName: schema.userProfile.realName,
})
.from(schema.tutorial)
.innerJoin(schema.user, eq(schema.tutorial.createdById, schema.user.id))
.leftJoin(schema.userProfile, eq(schema.userProfile.userId, schema.user.id))
.where(and(eq(schema.tutorial.id, id), eq(schema.tutorial.isPublic, true))).limit(1)
if (!row) return failure(c, 404, "tutorial-not-found", "Tutorial does not exist")
return success(c, tutorialSchema.parse({
.where(and(eq(schema.tutorial.id, id), eq(schema.tutorial.isPublic, true)))
.limit(1)
if (!row)
return failure(c, 404, "tutorial-not-found", "Tutorial does not exist")
return success(c, {
id: row.tutorial.id,
title: row.tutorial.title,
content: row.tutorial.content,
@@ -203,14 +353,243 @@ contentRoutes.get("/tutorials/:id", async (c) => {
createdBy: sampleUser(row.user, row.realName),
createdAt: row.tutorial.createdAt,
updatedAt: row.tutorial.updatedAt,
}))
} satisfies Tutorial)
})
// ---------------------------------------------------------------- 自学留痕
/**
*
*
* `/tutorials` Hono ****
* `/tutorials/:id` `/tutorials/progress`
* `queryInteger("progress")` 0
*/
contentRoutes.get("/learn/progress", requireAuth, async (c) => {
const user = c.get("user")!
const type = c.req.query("type") === "c" ? "c" : "python"
const visible = and(
eq(schema.tutorial.type, type),
eq(schema.tutorial.isPublic, true),
)
// 从 tutorial 打底 left join 进度,而不是反过来:没读过的课也要有一行零,
// 否则目录里「练习 0/5」和「这课没有练习」在前端分不出来
const [rows, exerciseRows] = await Promise.all([
db
.select({
tutorialId: schema.tutorial.id,
viewCount: schema.tutorialProgress.viewCount,
totalSeconds: schema.tutorialProgress.totalSeconds,
firstViewedAt: schema.tutorialProgress.firstViewedAt,
lastViewedAt: schema.tutorialProgress.lastViewedAt,
})
.from(schema.tutorial)
.leftJoin(
schema.tutorialProgress,
and(
eq(schema.tutorialProgress.tutorialId, schema.tutorial.id),
eq(schema.tutorialProgress.userId, user.id),
),
)
.where(visible)
.orderBy(asc(schema.tutorial.order)),
db
.select({
tutorialId: schema.exercise.tutorialId,
total: count(),
solved:
sql<number>`count(*) filter (where ${schema.exerciseAttempt.solved})`.mapWith(
Number,
),
})
.from(schema.exercise)
.innerJoin(
schema.tutorial,
eq(schema.tutorial.id, schema.exercise.tutorialId),
)
.leftJoin(
schema.exerciseAttempt,
and(
eq(schema.exerciseAttempt.exerciseId, schema.exercise.id),
eq(schema.exerciseAttempt.userId, user.id),
),
)
.where(visible)
.groupBy(schema.exercise.tutorialId),
])
const exercises = new Map(exerciseRows.map((row) => [row.tutorialId, row]))
return success(
c,
rows.map(
(row) =>
({
tutorialId: row.tutorialId,
viewCount: row.viewCount ?? 0,
totalSeconds: row.totalSeconds ?? 0,
firstViewedAt: row.firstViewedAt,
lastViewedAt: row.lastViewedAt,
exerciseTotal: exercises.get(row.tutorialId)?.total ?? 0,
exerciseSolved: exercises.get(row.tutorialId)?.solved ?? 0,
}) satisfies TutorialProgress,
),
)
})
/**
* `opened`
* apps/web/src/oj/learn/composables/useLearnTrace.ts
*
* 401
*
*/
contentRoutes.post("/tutorials/:id/progress", requireAuth, async (c) => {
const user = c.get("user")!
const id = queryInteger(c.req.param("id"), 0, { min: 1 })
const parsed = tutorialProgressPingSchema.safeParse(
await c.req.json().catch(() => null),
)
if (!parsed.success)
return failure(c, 400, "invalid-request", "Invalid progress payload")
const [tutorial] = await db
.select({ id: schema.tutorial.id })
.from(schema.tutorial)
.where(and(eq(schema.tutorial.id, id), eq(schema.tutorial.isPublic, true)))
.limit(1)
if (!tutorial)
return failure(c, 404, "tutorial-not-found", "Tutorial does not exist")
const now = new Date().toISOString()
const { seconds, opened } = parsed.data
await db
.insert(schema.tutorialProgress)
.values({
userId: user.id,
tutorialId: id,
viewCount: opened ? 1 : 0,
totalSeconds: seconds,
firstViewedAt: now,
lastViewedAt: now,
})
.onConflictDoUpdate({
target: [
schema.tutorialProgress.userId,
schema.tutorialProgress.tutorialId,
],
set: {
// 累加在库里做,不是「读出来加一下再写回去」:同一个学生开两个标签页
// 同时上报时,读改写会互相覆盖,时长凭空少掉一半
viewCount: sql`${schema.tutorialProgress.viewCount} + ${opened ? 1 : 0}`,
totalSeconds: sql`${schema.tutorialProgress.totalSeconds} + ${seconds}`,
lastViewedAt: now,
},
})
return success(c, null)
})
/**
*
*
* ****
* `/tutorials/:id/exercises`
* ****
*
*
*
*/
contentRoutes.post("/exercises/:id/attempts", requireAuth, async (c) => {
const user = c.get("user")!
const id = queryInteger(c.req.param("id"), 0, { min: 1 })
const parsed = exerciseAttemptRequestSchema.safeParse(
await c.req.json().catch(() => null),
)
if (!parsed.success)
return failure(c, 400, "invalid-request", "Invalid attempt payload")
// 练习跟着教程走:教程没公开,它底下的练习也不该能上报
const [exercise] = await db
.select({ id: schema.exercise.id })
.from(schema.exercise)
.innerJoin(
schema.tutorial,
eq(schema.tutorial.id, schema.exercise.tutorialId),
)
.where(and(eq(schema.exercise.id, id), eq(schema.tutorial.isPublic, true)))
.limit(1)
if (!exercise)
return failure(c, 404, "exercise-not-found", "Exercise does not exist")
const now = new Date().toISOString()
const { correct } = parsed.data
const answer = correct ? null : (parsed.data.answer ?? null)
await db
.insert(schema.exerciseAttempt)
.values({
userId: user.id,
exerciseId: id,
attempts: 1,
wrongAttempts: correct ? 0 : 1,
solved: correct,
attemptsToSolve: correct ? 1 : null,
lastWrongAnswer: answer,
firstAttemptAt: now,
lastAttemptAt: now,
solvedAt: correct ? now : null,
})
.onConflictDoUpdate({
target: [
schema.exerciseAttempt.userId,
schema.exerciseAttempt.exerciseId,
],
set: {
// 一律在库里算,不读出来改了再写回去:两个标签页同时提交会互相覆盖。
//
// 每一列都先看 `solved`:做对之后这一行就冻住了,只有 lastAttemptAt 还动。
// 不冻的话,学生做对后随手再点几下提交,「他试了几次才做对」就被改花了。
attempts: sql`${schema.exerciseAttempt.attempts} + case when ${schema.exerciseAttempt.solved} then 0 else 1 end`,
wrongAttempts: sql`${schema.exerciseAttempt.wrongAttempts} + case when ${schema.exerciseAttempt.solved} or ${correct} then 0 else 1 end`,
solved: sql`${schema.exerciseAttempt.solved} or ${correct}`,
attemptsToSolve: sql`case
when ${schema.exerciseAttempt.solved} then ${schema.exerciseAttempt.attemptsToSolve}
when ${correct} then ${schema.exerciseAttempt.attempts} + 1
else null end`,
solvedAt: sql`case
when ${schema.exerciseAttempt.solved} then ${schema.exerciseAttempt.solvedAt}
when ${correct} then ${now}::timestamptz
else null end`,
lastWrongAnswer: sql`case
when ${schema.exerciseAttempt.solved} or ${correct} then ${schema.exerciseAttempt.lastWrongAnswer}
else ${answer} end`,
lastAttemptAt: now,
},
})
return success(c, null)
})
contentRoutes.get("/tutorials/:id/exercises", async (c) => {
const id = queryInteger(c.req.param("id"), 0, { min: 1 })
const [tutorial] = await db.select({ id: schema.tutorial.id }).from(schema.tutorial)
.where(and(eq(schema.tutorial.id, id), eq(schema.tutorial.isPublic, true))).limit(1)
if (!tutorial) return failure(c, 404, "tutorial-not-found", "Tutorial does not exist")
const rows = await db.select().from(schema.exercise).where(eq(schema.exercise.tutorialId, id)).orderBy(asc(schema.exercise.order))
return success(c, rows.map((row) => exerciseSchema.parse({ id: row.id, type: row.type, data: objectValue(row.data), order: row.order })))
const [tutorial] = await db
.select({ id: schema.tutorial.id })
.from(schema.tutorial)
.where(and(eq(schema.tutorial.id, id), eq(schema.tutorial.isPublic, true)))
.limit(1)
if (!tutorial)
return failure(c, 404, "tutorial-not-found", "Tutorial does not exist")
const rows = await db
.select()
.from(schema.exercise)
.where(eq(schema.exercise.tutorialId, id))
.orderBy(asc(schema.exercise.order))
return success(
c,
rows.map(
(row) =>
({
id: row.id,
type: row.type,
data: objectValue(row.data),
order: row.order,
}) satisfies Exercise,
),
)
})
+332 -140
View File
@@ -1,14 +1,26 @@
import {
contestAccessSchema,
contestListSchema,
contestPasswordRequestSchema,
contestRankItemSchema,
contestRankSchema,
contestSchema,
problemDetailSchema,
problemListItemSchema,
STUDENT_ROLES,
type Contest,
type ContestAccess,
type ContestList,
type ContestRank,
type ContestRankItem,
type ProblemDetail,
type ProblemListItem,
} from "@oj2/contract"
import { and, asc, count, desc, eq, gte, ilike, inArray, lte, sql } from "drizzle-orm"
import {
and,
asc,
count,
desc,
eq,
gte,
ilike,
inArray,
lte,
sql,
} from "drizzle-orm"
import { Hono } from "hono"
import { optionalAuth, requireAuth } from "../auth/middleware"
@@ -21,12 +33,17 @@ import {
checkContestPassword,
contestDetailsAllowed,
contestStatus,
findVisibleContest,
findAccessibleContest,
isContestAdmin,
requireContestAccess,
type ContestEnv,
} from "../services/contest"
import { objectValue, publicTemplates, queryInteger, sampleUser, stringArray } from "./helpers"
import {
objectValue,
publicTemplates,
queryInteger,
sampleUser,
} from "./helpers"
export const contestRoutes = new Hono<ContestEnv>()
@@ -34,8 +51,14 @@ export const contestRoutes = new Hono<ContestEnv>()
async function creators(ids: number[]) {
const map = new Map<number, ReturnType<typeof sampleUser>>()
if (ids.length === 0) return map
const rows = await db.select({ id: schema.user.id, username: schema.user.username, realName: schema.userProfile.realName })
.from(schema.user).leftJoin(schema.userProfile, eq(schema.userProfile.userId, schema.user.id))
const rows = await db
.select({
id: schema.user.id,
username: schema.user.username,
realName: schema.userProfile.realName,
})
.from(schema.user)
.leftJoin(schema.userProfile, eq(schema.userProfile.userId, schema.user.id))
.where(inArray(schema.user.id, ids))
for (const row of rows) map.set(row.id, sampleUser(row, row.realName))
return map
@@ -46,7 +69,7 @@ function serializeContest(
createdBy: ReturnType<typeof sampleUser>,
includeNow = false,
) {
return contestSchema.parse({
return {
id: contest.id,
title: contest.title,
description: contest.description,
@@ -59,7 +82,7 @@ function serializeContest(
status: contestStatus(contest),
contestType: contest.password ? "Password Protected" : "Public",
now: includeNow ? new Date().toISOString() : undefined,
})
} satisfies Contest
}
contestRoutes.get("/contests", async (c) => {
@@ -74,160 +97,329 @@ contestRoutes.get("/contests", async (c) => {
if (tag) filters.push(eq(schema.contest.tag, tag))
if (status === "1") filters.push(gte(schema.contest.startTime, now))
else if (status === "-1") filters.push(lte(schema.contest.endTime, now))
else if (status === "0") filters.push(and(lte(schema.contest.startTime, now), gte(schema.contest.endTime, now))!)
else if (status === "0")
filters.push(
and(
lte(schema.contest.startTime, now),
gte(schema.contest.endTime, now),
)!,
)
const where = and(...filters)
const [totalRow, rows] = await Promise.all([
db.select({ value: count() }).from(schema.contest).where(where),
db.select().from(schema.contest).where(where).orderBy(desc(schema.contest.startTime)).limit(limit).offset(offset),
db
.select()
.from(schema.contest)
.where(where)
.orderBy(desc(schema.contest.startTime))
.limit(limit)
.offset(offset),
])
const byId = await creators([...new Set(rows.map((row) => row.createdById))])
return success(c, contestListSchema.parse({
results: rows.map((row) => serializeContest(
row,
byId.get(row.createdById) ?? sampleUser({ id: row.createdById, username: "" }, null),
)),
return success(c, {
results: rows.map((row) =>
serializeContest(
row,
byId.get(row.createdById) ??
sampleUser({ id: row.createdById, username: "" }, null),
),
),
total: totalRow[0]?.value ?? 0,
}))
} satisfies ContestList)
})
contestRoutes.get("/contests/:id", async (c) => {
const contest = await findVisibleContest(queryInteger(c.req.param("id"), 0, { min: 1 }))
if (!contest) return failure(c, 404, "contest-not-found", "Contest does not exist")
// optionalAuth 是为了下面那句 findAccessibleContest 认得出「这是出题人自己」——
// 隐藏的比赛只有他看得到详情,匿名访问照旧当作不存在
contestRoutes.get("/contests/:id", optionalAuth, async (c) => {
const contest = await findAccessibleContest(
c.get("user"),
queryInteger(c.req.param("id"), 0, { min: 1 }),
)
if (!contest)
return failure(c, 404, "contest-not-found", "Contest does not exist")
const byId = await creators([contest.createdById])
return success(c, serializeContest(
contest,
byId.get(contest.createdById) ?? sampleUser({ id: contest.createdById, username: "" }, null),
true,
))
return success(
c,
serializeContest(
contest,
byId.get(contest.createdById) ??
sampleUser({ id: contest.createdById, username: "" }, null),
true,
),
)
})
contestRoutes.post("/contests/:id/access", requireAuth, async (c) => {
const contest = await findVisibleContest(queryInteger(c.req.param("id"), 0, { min: 1 }))
if (!contest || !contest.password) return failure(c, 404, "contest-not-found", "Contest does not exist")
const parsed = contestPasswordRequestSchema.safeParse(await c.req.json().catch(() => null))
if (!parsed.success) return failure(c, 400, "invalid-request", "Password is required")
const contest = await findAccessibleContest(
c.get("user"),
queryInteger(c.req.param("id"), 0, { min: 1 }),
)
if (!contest || !contest.password)
return failure(c, 404, "contest-not-found", "Contest does not exist")
const parsed = contestPasswordRequestSchema.safeParse(
await c.req.json().catch(() => null),
)
if (!parsed.success)
return failure(c, 400, "invalid-request", "Password is required")
if (!checkContestPassword(parsed.data.password, contest.password)) {
return failure(c, 403, "wrong-password", "Wrong password or password expired")
return failure(
c,
403,
"wrong-password",
"Wrong password or password expired",
)
}
await setContestPassword(c, contest.id, parsed.data.password)
return success(c, true)
})
contestRoutes.get("/contests/:id/access", requireAuth, async (c) => {
const contest = await findVisibleContest(queryInteger(c.req.param("id"), 0, { min: 1 }))
if (!contest || !contest.password) return failure(c, 404, "contest-not-found", "Contest does not exist")
const contest = await findAccessibleContest(
c.get("user"),
queryInteger(c.req.param("id"), 0, { min: 1 }),
)
if (!contest || !contest.password)
return failure(c, 404, "contest-not-found", "Contest does not exist")
const access = await canAccessContest(c, contest, "details")
return success(c, contestAccessSchema.parse({ access: access.ok }))
return success(c, { access: access.ok } satisfies ContestAccess)
})
/**
* **** user_profile
* `acm_problems_status.contest_problems`judge/run.ts `problems`
*
*
*
*
*
*
* serializer
*/
async function contestProblemStatuses(userId: number | undefined) {
if (!userId) return {}
const [profile] = await db
.select({ status: schema.userProfile.acmProblemsStatus })
.from(schema.userProfile)
.where(eq(schema.userProfile.userId, userId))
.limit(1)
return objectValue(objectValue(profile?.status).contest_problems)
}
function myStatusOf(statuses: Record<string, unknown>, problemId: number) {
const status = objectValue(statuses[String(problemId)]).status
return typeof status === "number" ? status : null
}
async function contestProblemTags(problemIds: number[]) {
if (problemIds.length === 0) return new Map<number, string[]>()
const rows = await db.select({ problemId: schema.problemTags.problemId, name: schema.problemTag.name })
.from(schema.problemTags).innerJoin(schema.problemTag, eq(schema.problemTags.problemtagId, schema.problemTag.id))
const rows = await db
.select({
problemId: schema.problemTags.problemId,
name: schema.problemTag.name,
})
.from(schema.problemTags)
.innerJoin(
schema.problemTag,
eq(schema.problemTags.problemtagId, schema.problemTag.id),
)
.where(inArray(schema.problemTags.problemId, problemIds))
const map = new Map<number, string[]>()
for (const row of rows) map.set(row.problemId, [...(map.get(row.problemId) ?? []), row.name])
for (const row of rows)
map.set(row.problemId, [...(map.get(row.problemId) ?? []), row.name])
return map
}
contestRoutes.get("/contests/:id/problems", optionalAuth, requireContestAccess("problems"), async (c) => {
const contest = c.get("contest")!
const rows = await db.select({ problem: schema.problem, user: schema.user, realName: schema.userProfile.realName })
.from(schema.problem).innerJoin(schema.user, eq(schema.problem.createdById, schema.user.id))
.leftJoin(schema.userProfile, eq(schema.userProfile.userId, schema.user.id))
.where(and(eq(schema.problem.contestId, contest.id), eq(schema.problem.visible, true))).orderBy(asc(schema.problem.displayId))
const tags = await contestProblemTags(rows.map((row) => row.problem.id))
const allowed = contestDetailsAllowed(c.get("user"), contest)
return success(c, rows.map(({ problem, user, realName }) => problemListItemSchema.parse({
id: problem.id,
_id: problem.displayId,
title: problem.title,
submissionNumber: allowed ? problem.submissionNumber : 0,
acceptedNumber: allowed ? problem.acceptedNumber : 0,
difficulty: allowed ? problem.difficulty : "",
createdBy: sampleUser(user, realName),
tags: tags.get(problem.id) ?? [],
contestId: contest.id,
allowFlowchart: problem.allowFlowchart,
showFlowchart: problem.showFlowchart,
hasAstRules: problem.astRules !== null,
myStatus: null,
})))
})
contestRoutes.get(
"/contests/:id/problems",
optionalAuth,
requireContestAccess("problems"),
async (c) => {
const contest = c.get("contest")!
const rows = await db
.select({
problem: schema.problem,
user: schema.user,
realName: schema.userProfile.realName,
})
.from(schema.problem)
.innerJoin(schema.user, eq(schema.problem.createdById, schema.user.id))
.leftJoin(
schema.userProfile,
eq(schema.userProfile.userId, schema.user.id),
)
.where(
and(
eq(schema.problem.contestId, contest.id),
eq(schema.problem.visible, true),
),
)
.orderBy(asc(schema.problem.displayId))
const tags = await contestProblemTags(rows.map((row) => row.problem.id))
const allowed = contestDetailsAllowed(c.get("user"), contest)
const statuses = await contestProblemStatuses(c.get("user")?.id)
return success(
c,
rows.map(
({ problem, user, realName }) =>
({
id: problem.id,
_id: problem.displayId,
title: problem.title,
submissionNumber: allowed ? problem.submissionNumber : 0,
acceptedNumber: allowed ? problem.acceptedNumber : 0,
difficulty: allowed ? problem.difficulty : null,
createdBy: sampleUser(user, realName),
tags: tags.get(problem.id) ?? [],
contestId: contest.id,
allowFlowchart: problem.allowFlowchart,
showFlowchart: problem.showFlowchart,
hasAstRules: problem.astRules !== null,
myStatus: myStatusOf(statuses, problem.id),
}) satisfies ProblemListItem,
),
)
},
)
contestRoutes.get("/contests/:id/problems/:displayId", optionalAuth, requireContestAccess("problems"), async (c) => {
const contest = c.get("contest")!
const [row] = await db.select({ problem: schema.problem, user: schema.user, realName: schema.userProfile.realName })
.from(schema.problem).innerJoin(schema.user, eq(schema.problem.createdById, schema.user.id))
.leftJoin(schema.userProfile, eq(schema.userProfile.userId, schema.user.id))
.where(and(eq(schema.problem.contestId, contest.id), eq(schema.problem.visible, true), sql`lower(${schema.problem.displayId}) = lower(${c.req.param("displayId")})`)).limit(1)
if (!row) return failure(c, 404, "problem-not-found", "Problem does not exist")
const tags = await contestProblemTags([row.problem.id])
const allowed = contestDetailsAllowed(c.get("user"), contest)
return success(c, problemDetailSchema.parse({
id: row.problem.id,
_id: row.problem.displayId,
title: row.problem.title,
description: row.problem.description,
inputDescription: row.problem.inputDescription,
outputDescription: row.problem.outputDescription,
samples: Array.isArray(row.problem.samples) ? row.problem.samples : [],
hint: row.problem.hint,
languages: stringArray(row.problem.languages),
template: publicTemplates(row.problem.template),
createTime: row.problem.createTime,
lastUpdateTime: row.problem.lastUpdateTime,
timeLimit: row.problem.timeLimit,
memoryLimit: row.problem.memoryLimit,
difficulty: allowed ? row.problem.difficulty : "",
source: row.problem.source,
prompt: row.problem.prompt,
submissionNumber: allowed ? row.problem.submissionNumber : 0,
acceptedNumber: allowed ? row.problem.acceptedNumber : 0,
statisticInfo: allowed ? objectValue(row.problem.statisticInfo) : {},
shareSubmission: row.problem.shareSubmission,
contestId: contest.id,
tags: tags.get(row.problem.id) ?? [],
createdBy: sampleUser(row.user, row.realName),
myStatus: null,
myFailedCount: 0,
allowFlowchart: row.problem.allowFlowchart,
showFlowchart: row.problem.showFlowchart,
mermaidCode: row.problem.allowFlowchart ? null : row.problem.mermaidCode,
flowchartData: row.problem.allowFlowchart ? null : objectValue(row.problem.flowchartData),
flowchartHint: row.problem.flowchartHint,
sqlConfig: row.problem.sqlConfig ? objectValue(row.problem.sqlConfig) : null,
sqlDisplay: row.problem.sqlDisplay ? objectValue(row.problem.sqlDisplay) : null,
// 代码要求:只给渲染好的文案,规则原文不下发给学生
astRequirements: astRequirements(row.problem.astRules),
}))
})
contestRoutes.get(
"/contests/:id/problems/:displayId",
optionalAuth,
requireContestAccess("problems"),
async (c) => {
const contest = c.get("contest")!
const [row] = await db
.select({
problem: schema.problem,
user: schema.user,
realName: schema.userProfile.realName,
})
.from(schema.problem)
.innerJoin(schema.user, eq(schema.problem.createdById, schema.user.id))
.leftJoin(
schema.userProfile,
eq(schema.userProfile.userId, schema.user.id),
)
.where(
and(
eq(schema.problem.contestId, contest.id),
eq(schema.problem.visible, true),
sql`lower(${schema.problem.displayId}) = lower(${c.req.param("displayId")})`,
),
)
.limit(1)
if (!row)
return failure(c, 404, "problem-not-found", "Problem does not exist")
const tags = await contestProblemTags([row.problem.id])
const allowed = contestDetailsAllowed(c.get("user"), contest)
const statuses = await contestProblemStatuses(c.get("user")?.id)
return success(c, {
id: row.problem.id,
_id: row.problem.displayId,
title: row.problem.title,
description: row.problem.description,
inputDescription: row.problem.inputDescription,
outputDescription: row.problem.outputDescription,
samples: Array.isArray(row.problem.samples) ? row.problem.samples : [],
hint: row.problem.hint,
languages: row.problem.languages,
template: publicTemplates(row.problem.template),
createTime: row.problem.createTime,
lastUpdateTime: row.problem.lastUpdateTime,
timeLimit: row.problem.timeLimit,
memoryLimit: row.problem.memoryLimit,
difficulty: allowed ? row.problem.difficulty : null,
source: row.problem.source,
prompt: row.problem.prompt,
submissionNumber: allowed ? row.problem.submissionNumber : 0,
acceptedNumber: allowed ? row.problem.acceptedNumber : 0,
statisticInfo: allowed ? objectValue(row.problem.statisticInfo) : {},
contestId: contest.id,
tags: tags.get(row.problem.id) ?? [],
createdBy: sampleUser(row.user, row.realName),
myStatus: myStatusOf(statuses, row.problem.id),
// 比赛里不给 AI 提示(POST /ai/hint 见到比赛提交直接 403),这个数只喂那个按钮,恒 0
myFailedCount: 0,
allowFlowchart: row.problem.allowFlowchart,
showFlowchart: row.problem.showFlowchart,
mermaidCode: row.problem.allowFlowchart ? null : row.problem.mermaidCode,
flowchartData: row.problem.allowFlowchart
? null
: objectValue(row.problem.flowchartData),
flowchartHint: row.problem.flowchartHint,
sqlConfig: row.problem.sqlConfig,
sqlDisplay: row.problem.sqlDisplay,
// 代码要求:只给渲染好的文案,规则原文不下发给学生
astRequirements: astRequirements(row.problem.astRules),
} satisfies ProblemDetail)
},
)
contestRoutes.get("/contests/:id/rank", optionalAuth, requireContestAccess("ranks"), async (c) => {
const contest = c.get("contest")!
const limit = queryInteger(c.req.query("limit"), 10, { min: 1, max: 250 })
const offset = queryInteger(c.req.query("offset"), 0, { min: 0 })
const where = and(eq(schema.acmContestRank.contestId, contest.id), inArray(schema.user.adminType, ["Regular User", "Student Admin"]), eq(schema.user.isDisabled, false))
const [totalRows, rows] = await Promise.all([
db.select({ value: count() }).from(schema.acmContestRank).innerJoin(schema.user, eq(schema.acmContestRank.userId, schema.user.id)).where(where),
db.select({ rank: schema.acmContestRank, user: schema.user, realName: schema.userProfile.realName })
.from(schema.acmContestRank).innerJoin(schema.user, eq(schema.acmContestRank.userId, schema.user.id))
.leftJoin(schema.userProfile, eq(schema.userProfile.userId, schema.user.id)).where(where)
.orderBy(desc(schema.acmContestRank.acceptedNumber), asc(schema.acmContestRank.totalTime)).limit(limit).offset(offset),
])
const admin = isContestAdmin(c.get("user"), contest)
return success(c, contestRankSchema.parse({
results: rows.map(({ rank, user, realName }) => contestRankItemSchema.parse({
id: rank.id,
// 唯一显式打开真名的地方,对齐旧后端 contest/serializers.py:84
// `UsernameSerializer(obj.user, need_real_name=self.is_contest_admin)`
user: sampleUser(user, realName, { includeRealName: admin }),
submissionNumber: rank.submissionNumber,
acceptedNumber: rank.acceptedNumber,
totalTime: rank.totalTime,
submissionInfo: objectValue(rank.submissionInfo),
contestId: rank.contestId,
})),
total: totalRows[0]?.value ?? 0,
}))
})
contestRoutes.get(
"/contests/:id/rank",
optionalAuth,
requireContestAccess("ranks"),
async (c) => {
const contest = c.get("contest")!
const limit = queryInteger(c.req.query("limit"), 10, { min: 1, max: 250 })
const offset = queryInteger(c.req.query("offset"), 0, { min: 0 })
const where = and(
eq(schema.acmContestRank.contestId, contest.id),
inArray(schema.user.adminType, [...STUDENT_ROLES]),
eq(schema.user.isDisabled, false),
)
const [totalRows, rows] = await Promise.all([
db
.select({ value: count() })
.from(schema.acmContestRank)
.innerJoin(
schema.user,
eq(schema.acmContestRank.userId, schema.user.id),
)
.where(where),
db
.select({
rank: schema.acmContestRank,
user: schema.user,
realName: schema.userProfile.realName,
})
.from(schema.acmContestRank)
.innerJoin(
schema.user,
eq(schema.acmContestRank.userId, schema.user.id),
)
.leftJoin(
schema.userProfile,
eq(schema.userProfile.userId, schema.user.id),
)
.where(where)
// 末尾的 id 是给排序兜全序用的:同 AC 数同罚时前两列分不出先后,而这条列表是
// limit/offset 翻页的,行序不稳定就意味着同一个人在第 2 页出现两次、另一个人
// 从此消失。id 本身不参与名次,只保证同分的人每次都按同一个顺序排
.orderBy(
desc(schema.acmContestRank.acceptedNumber),
asc(schema.acmContestRank.totalTime),
asc(schema.acmContestRank.id),
)
.limit(limit)
.offset(offset),
])
const admin = isContestAdmin(c.get("user"), contest)
return success(c, {
results: rows.map(
({ rank, user, realName }) =>
({
id: rank.id,
// 唯一显式打开真名的地方,对齐旧后端 contest/serializers.py:84
// `UsernameSerializer(obj.user, need_real_name=self.is_contest_admin)`
user: sampleUser(user, realName, { includeRealName: admin }),
submissionNumber: rank.submissionNumber,
acceptedNumber: rank.acceptedNumber,
totalTime: rank.totalTime,
submissionInfo: rank.submissionInfo,
contestId: rank.contestId,
}) satisfies ContestRankItem,
),
total: totalRows[0]?.value ?? 0,
} satisfies ContestRank)
},
)
+583 -164
View File
@@ -2,15 +2,25 @@ import { randomBytes } from "node:crypto"
import {
createFlowchartRequestSchema,
createFlowchartResponseSchema,
flowchartCurrentSchema,
flowchartDetailSchema,
flowchartListItemSchema,
flowchartListSchema,
flowchartStatisticsSchema,
flowchartSubmissionSchema,
type CreateFlowchartResponse,
type FlowchartCurrent,
type FlowchartDetail,
type FlowchartList,
type FlowchartListItem,
type FlowchartStatistics,
type FlowchartSubmission,
} from "@oj2/contract"
import { and, asc, count, desc, eq, ilike, isNull, sql } from "drizzle-orm"
import {
and,
asc,
count,
desc,
eq,
inArray,
isNull,
sql,
type SQL,
} from "drizzle-orm"
import { Hono } from "hono"
import { requireAuth, requireTeacher, type AppEnv } from "../auth/middleware"
@@ -18,27 +28,43 @@ import { config } from "../config"
import { db, schema } from "../db"
import { failure, success } from "../http"
import { flowchartQueue } from "../queue"
import { getBooleanOption } from "../services/options"
import { consumeToken } from "../services/throttling"
import { buildWordFrequencies } from "../services/word-frequency"
import { todayStart } from "../time"
import {
isAdminRole,
matchedUsers,
objectValue,
queryInteger,
rounded,
stripClassPrefix,
todayStart,
} from "./helpers"
export const flowchartRoutes = new Hono<AppEnv>()
function canView(user: import("../auth/session").AuthUser, row: { userId: number }, problem: { createdById: number }) {
return row.userId === user.id || isAdminRole(user) || problem.createdById === user.id
// AI 评分单独一个限流桶,与代码提交的 `throttling:user:<id>` 分开计数
function flowchartThrottleKey(userId: number) {
return `flowchart:${userId}`
}
function canView(
user: import("../auth/session").AuthUser,
row: { userId: number },
problem: { createdById: number },
) {
return (
row.userId === user.id ||
isAdminRole(user) ||
problem.createdById === user.id
)
}
function flowchartData(
flowchart: typeof schema.flowchartSubmission.$inferSelect,
username: string,
) {
return flowchartSubmissionSchema.parse({
return {
id: flowchart.id,
username,
problemId: flowchart.problemId,
@@ -55,18 +81,53 @@ function flowchartData(
aiModel: flowchart.aiModel,
processingTime: flowchart.processingTime,
evaluationTime: flowchart.evaluationTime,
})
} satisfies FlowchartSubmission
}
flowchartRoutes.post("/flowcharts", requireAuth, async (c) => {
const parsed = createFlowchartRequestSchema.safeParse(await c.req.json().catch(() => null))
if (!parsed.success || JSON.stringify(parsed.data?.flowchartData ?? {}).length > 500 * 1024) {
return failure(c, 400, "invalid-request", parsed.error?.issues[0]?.message ?? "Flowchart data is too large")
const parsed = createFlowchartRequestSchema.safeParse(
await c.req.json().catch(() => null),
)
if (
!parsed.success ||
JSON.stringify(parsed.data?.flowchartData ?? {}).length > 500 * 1024
) {
return failure(
c,
400,
"invalid-request",
parsed.error?.issues[0]?.message ?? "Flowchart data is too large",
)
}
const [problem] = await db
.select({ id: schema.problem.id, allow: schema.problem.allowFlowchart })
.from(schema.problem)
.where(eq(schema.problem.id, parsed.data.problemId))
.limit(1)
if (!problem)
return failure(c, 404, "problem-not-found", "Problem does not exist")
if (!problem.allow)
return failure(
c,
400,
"flowchart-not-allowed",
"This problem does not allow flowchart submission",
)
// 限流:每次提交都会触发一次外部 AI 调用,是和判题沙箱同级的有限资源。
// 身份前缀单独开一个桶,**不能**直接用 user id —— 那是代码提交在用的桶,
// 共用的话学生在机房连着交几次代码,流程图这边就会莫名其妙交不上去。
const throttle = await consumeToken(
"user",
flowchartThrottleKey(c.get("user")!.id),
)
if (!throttle.allowed) {
return failure(
c,
429,
"too-many-submissions",
`Please wait ${Math.floor(throttle.wait)} seconds`,
)
}
const [problem] = await db.select({ id: schema.problem.id, allow: schema.problem.allowFlowchart }).from(schema.problem)
.where(eq(schema.problem.id, parsed.data.problemId)).limit(1)
if (!problem) return failure(c, 404, "problem-not-found", "Problem does not exist")
if (!problem.allow) return failure(c, 400, "flowchart-not-allowed", "This problem does not allow flowchart submission")
const id = randomBytes(16).toString("hex")
await db.insert(schema.flowchartSubmission).values({
id,
@@ -89,220 +150,578 @@ flowchartRoutes.post("/flowcharts", requireAuth, async (c) => {
try {
await flowchartQueue.add("evaluate", { submissionId: id }, { jobId: id })
} catch (error) {
await db.update(schema.flowchartSubmission).set({ status: 3 }).where(eq(schema.flowchartSubmission.id, id))
return failure(c, 502, "queue-unavailable", "Evaluation queue is unavailable")
await db
.update(schema.flowchartSubmission)
.set({ status: 3 })
.where(eq(schema.flowchartSubmission.id, id))
return failure(
c,
502,
"queue-unavailable",
"Evaluation queue is unavailable",
)
}
return success(c, createFlowchartResponseSchema.parse({ submissionId: id, status: "pending" }), 201)
return success(
c,
{ submissionId: id, status: "pending" } satisfies CreateFlowchartResponse,
201,
)
})
/**
* / `flowchart_submission` join
* `problem._id` / `user.username` submission.ts
* problemFilter / usernameFilter
*
* - count ** join ** index-only
* scan 3KB flowchart_data + 1.2KB mermaid_code
* submission
* - flowchart_user_time_idx / flowchart_problem_time_idx
* join
*
* / **** filter
*
*/
async function flowchartProblemFilter(displayId: string) {
const problems = await db
.select({ id: schema.problem.id })
.from(schema.problem)
.where(
and(
sql`lower(${schema.problem.displayId}) = lower(${displayId})`,
// 流程图题都是公开题(快照里那 12 道 contest_id 全为空),
// 比赛题的 _id 撞号是常态,不该被筛进来
isNull(schema.problem.contestId),
),
)
return problems.length
? inArray(
schema.flowchartSubmission.problemId,
problems.map((row) => row.id),
)
: sql`false`
}
async function flowchartUserFilter(username: string) {
const ids = (await matchedUsers(username)).map((row) => row.id)
return ids.length
? inArray(schema.flowchartSubmission.userId, ids)
: sql`false`
}
/**
* `select({ flowchart: 整行, problem: 整行 })`
* mermaid_codeflowchart_dataai_feedbackai_suggestionsai_criteria_details
* ****description / /
* 4.9KBp90 6.9KB 2.2KB 10
* ~70KBlimit=250 1.7MB
*
* submission.ts submissionListColumns
* code / info
*/
const flowchartListColumns = {
flowchart: {
id: schema.flowchartSubmission.id,
// showLink 判定要,序列化本身用不到
userId: schema.flowchartSubmission.userId,
status: schema.flowchartSubmission.status,
createTime: schema.flowchartSubmission.createTime,
aiScore: schema.flowchartSubmission.aiScore,
aiGrade: schema.flowchartSubmission.aiGrade,
aiProvider: schema.flowchartSubmission.aiProvider,
aiModel: schema.flowchartSubmission.aiModel,
processingTime: schema.flowchartSubmission.processingTime,
evaluationTime: schema.flowchartSubmission.evaluationTime,
},
username: schema.user.username,
problem: {
displayId: schema.problem.displayId,
title: schema.problem.title,
// 同上,canView 要
createdById: schema.problem.createdById,
},
}
flowchartRoutes.get("/flowcharts", requireAuth, async (c) => {
const user = c.get("user")!
const limit = queryInteger(c.req.query("limit"), 10, { min: 1, max: 250 })
const offset = queryInteger(c.req.query("offset"), 0, { min: 0 })
const filters = []
const displayId = c.req.query("problemId")?.trim()
const username = c.req.query("username")?.trim()
const grade = c.req.query("grade")
if (displayId) filters.push(sql`lower(${schema.problem.displayId}) = lower(${displayId})`)
if (c.req.query("myself") === "1" || (!username && user.adminType === "Regular User")) filters.push(eq(schema.flowchartSubmission.userId, user.id))
else if (username) filters.push(ilike(schema.user.username, `%${username}%`))
if (c.req.query("today") === "1") filters.push(sql`${schema.flowchartSubmission.createTime} >= ${todayStart()}`)
if (["S", "A", "B", "C"].includes(grade ?? "")) filters.push(eq(schema.flowchartSubmission.aiGrade, grade!))
const where = filters.length ? and(...filters) : undefined
// 与代码提交列表同一套口径(submission.ts 的 GET /submissions):关掉
// submission_list_show_all 时非管理员看不到列表。流程图这边一直漏了这道门,
// 学生把语言切成「流程图」、用户名随便填一个字就能翻出全班的 AI 评分。
if (
!(await getBooleanOption("submission_list_show_all", true)) &&
!isAdminRole(user)
) {
return success(c, { results: [], total: 0 } satisfies FlowchartList)
}
// 「只看自己」盖过用户名;普通学生不填用户名时也只看自己
const onlyMyself =
c.req.query("myself") === "1" ||
(!username && user.adminType === "Regular User")
const filters: Array<SQL | undefined> = []
filters.push(
...(await Promise.all([
displayId ? flowchartProblemFilter(displayId) : undefined,
!onlyMyself && username ? flowchartUserFilter(username) : undefined,
])),
)
if (onlyMyself) filters.push(eq(schema.flowchartSubmission.userId, user.id))
if (c.req.query("today") === "1")
filters.push(
sql`${schema.flowchartSubmission.createTime} >= ${todayStart()}`,
)
if (["S", "A", "B", "C"].includes(grade ?? ""))
filters.push(eq(schema.flowchartSubmission.aiGrade, grade!))
const where = and(...filters)
const [totalRows, rows] = await Promise.all([
db.select({ value: count() }).from(schema.flowchartSubmission).innerJoin(schema.user, eq(schema.flowchartSubmission.userId, schema.user.id)).innerJoin(schema.problem, eq(schema.flowchartSubmission.problemId, schema.problem.id)).where(where),
db.select({ flowchart: schema.flowchartSubmission, username: schema.user.username, problem: schema.problem })
.from(schema.flowchartSubmission).innerJoin(schema.user, eq(schema.flowchartSubmission.userId, schema.user.id))
.innerJoin(schema.problem, eq(schema.flowchartSubmission.problemId, schema.problem.id)).where(where)
.orderBy(desc(schema.flowchartSubmission.createTime)).limit(limit).offset(offset),
// 筛条件已经全落在 flowchart_submission 自己的列上,count 不挂任何 join
db.select({ value: count() }).from(schema.flowchartSubmission).where(where),
db
.select(flowchartListColumns)
.from(schema.flowchartSubmission)
.innerJoin(
schema.user,
eq(schema.flowchartSubmission.userId, schema.user.id),
)
.innerJoin(
schema.problem,
eq(schema.flowchartSubmission.problemId, schema.problem.id),
)
.where(where)
.orderBy(desc(schema.flowchartSubmission.createTime))
.limit(limit)
.offset(offset),
])
return success(c, flowchartListSchema.parse({
results: rows.map(({ flowchart, username, problem }) => flowchartListItemSchema.parse({
id: flowchart.id,
username,
problem: problem.displayId,
problemTitle: problem.title,
status: flowchart.status,
createTime: flowchart.createTime,
aiScore: flowchart.aiScore,
aiGrade: flowchart.aiGrade,
aiProvider: flowchart.aiProvider,
aiModel: flowchart.aiModel,
processingTime: flowchart.processingTime,
evaluationTime: flowchart.evaluationTime,
showLink: canView(user, flowchart, problem),
})),
return success(c, {
results: rows.map(
({ flowchart, username, problem }) =>
({
id: flowchart.id,
username,
problem: problem.displayId,
problemTitle: problem.title,
status: flowchart.status,
createTime: flowchart.createTime,
aiScore: flowchart.aiScore,
aiGrade: flowchart.aiGrade,
aiProvider: flowchart.aiProvider,
aiModel: flowchart.aiModel,
processingTime: flowchart.processingTime,
evaluationTime: flowchart.evaluationTime,
showLink: canView(user, flowchart, problem),
}) satisfies FlowchartListItem,
),
total: totalRows[0]?.value ?? 0,
}))
} satisfies FlowchartList)
})
const FLOWCHART_COMPLETED = 2
/**
*
*
* ****
* SQL ****
*
*
* 线 feedback / suggestions / comment
* jieba start FlowchartStatisticsPanel.vue
* `duration === "all"` cut
*
*
* ****SQL `order by create_time desc limit N` N
* JS pushText N 5.97 comment +
* feedback + suggestions 1 3000
* 500
* JS
*/
const WORDCLOUD_TEXT_LIMIT = 3000
flowchartRoutes.get("/flowcharts/statistics", requireTeacher, async (c) => {
const end = c.req.query("end")?.trim()
if (!end) return failure(c, 400, "invalid-request", "end is required")
const start = c.req.query("start")?.trim()
const filters = [
const filters: Array<SQL | undefined> = [
eq(schema.flowchartSubmission.status, FLOWCHART_COMPLETED),
sql`${schema.flowchartSubmission.createTime} <= ${end}`,
]
if (start) filters.push(sql`${schema.flowchartSubmission.createTime} >= ${start}`)
if (start)
filters.push(sql`${schema.flowchartSubmission.createTime} >= ${start}`)
const displayId = c.req.query("problemId")?.trim()
if (displayId) {
const [problem] = await db
.select({ id: schema.problem.id })
.from(schema.problem)
.where(and(
sql`lower(${schema.problem.displayId}) = lower(${displayId})`,
isNull(schema.problem.contestId),
eq(schema.problem.visible, true),
))
.where(
and(
sql`lower(${schema.problem.displayId}) = lower(${displayId})`,
isNull(schema.problem.contestId),
eq(schema.problem.visible, true),
),
)
.limit(1)
if (!problem) return failure(c, 404, "problem-not-found", "Problem does not exist")
if (!problem)
return failure(c, 404, "problem-not-found", "Problem does not exist")
filters.push(eq(schema.flowchartSubmission.problemId, problem.id))
}
const username = c.req.query("username")?.trim()
if (username) filters.push(ilike(schema.user.username, `%${username}%`))
// 只有指定了用户名才谈得上「班级人数」,不指定时分母无意义
// 用户名先解析成账号,再拿 user_id 去筛 —— 理由同代码提交的统计接口
// submission.ts 的 GET /submissions/statistics),顺带让下面这几条一个 join 都不用挂
const matched = username ? await matchedUsers(username) : []
if (username) {
const ids = matched.map((row) => row.id)
// 一个账号都没匹配上时得留个恒假条件,否则「查无此班」变成「全站统计」
filters.push(
ids.length ? inArray(schema.flowchartSubmission.userId, ids) : sql`false`,
)
}
const where = and(...filters)
// 花名册:只有指定了用户名才谈得上「班级人数」,不指定时分母无意义。
// 未禁用的普通用户才进分母,教师和管理员不算
const roster = username
? await db
.select({ username: schema.user.username, className: schema.user.className })
.from(schema.user)
.where(and(
ilike(schema.user.username, `%${username}%`),
eq(schema.user.isDisabled, false),
eq(schema.user.adminType, "Regular User"),
))
? matched.filter(
(row) => !row.isDisabled && row.adminType === "Regular User",
)
: []
const rows = await db
.select({
username: schema.user.username,
score: schema.flowchartSubmission.aiScore,
grade: schema.flowchartSubmission.aiGrade,
criteria: schema.flowchartSubmission.aiCriteriaDetails,
feedback: schema.flowchartSubmission.aiFeedback,
suggestions: schema.flowchartSubmission.aiSuggestions,
})
.from(schema.flowchartSubmission)
.innerJoin(schema.user, eq(schema.flowchartSubmission.userId, schema.user.id))
.where(and(...filters))
/**
* limit
*
* **** limit `select(username, score, grade, criteria, feedback,
* suggestions) order by create_time desc`,把整个时间窗的行拉进内存再用 JS 算 ——
* 3000 JS AI 366B
* criteria 255 + suggestions 64 + feedback 47 2134 5
* 18MB
*/
const [[totals], gradeRows, criteriaRows, textRows, submittedRows] =
await Promise.all([
db
.select({
total: count(),
/**
* sum / count `avg()`****
* Django Avg() NULL
* avg() NULL
*/
scoreSum:
sql<number>`coalesce(sum(${schema.flowchartSubmission.aiScore}), 0)`.mapWith(
Number,
),
scoreCount:
sql<number>`count(${schema.flowchartSubmission.aiScore})::int`.mapWith(
Number,
),
// 完成人数。user_id 和 username 一一对应,按哪个 distinct 都一样,
// 按 user_id 就不必 join user
completedCount:
sql<number>`count(distinct ${schema.flowchartSubmission.userId})::int`.mapWith(
Number,
),
})
.from(schema.flowchartSubmission)
.where(where),
db
.select({ grade: schema.flowchartSubmission.aiGrade, n: count() })
.from(schema.flowchartSubmission)
.where(where)
.groupBy(schema.flowchartSubmission.aiGrade),
/**
* ****`ai_criteria_details` `{ 项名: { score, max, comment } }`
* jsonb_each JS
* `typeof detail.score !== "number"` continue
*
* ** `jsonb_typeof(...) = 'object'` jsonb_each **
* jsonb_each 500
* `'5'::jsonb` `'[1,2]'::jsonb`
*
* where 53350
* 180ms 360ms Partial HashAggregate
* GroupAggregate + 21 26MB
*
* **** criteriaMax SQL
* create_time 21 4 × 5
* 254ms 842ms
*/
db.execute<{ key: string; avg: number }>(sql`
select e.key as key, avg((e.value->>'score')::double precision) as avg
from ${schema.flowchartSubmission}
cross join lateral jsonb_each(
case when jsonb_typeof(${schema.flowchartSubmission.aiCriteriaDetails}) = 'object'
then ${schema.flowchartSubmission.aiCriteriaDetails}
else '{}'::jsonb end
) e
where ${where} and jsonb_typeof(e.value->'score') = 'number'
group by e.key
`),
// 词云的原料。只有这条要读大列,所以只有它按时间倒序取最近的 N 条
db
.select({
criteria: schema.flowchartSubmission.aiCriteriaDetails,
feedback: schema.flowchartSubmission.aiFeedback,
suggestions: schema.flowchartSubmission.aiSuggestions,
})
.from(schema.flowchartSubmission)
.where(where)
.orderBy(desc(schema.flowchartSubmission.createTime))
.limit(WORDCLOUD_TEXT_LIMIT),
// 「谁没做」只在有花名册时算得出来,行数也就一个班
roster.length
? db
.selectDistinct({ userId: schema.flowchartSubmission.userId })
.from(schema.flowchartSubmission)
.where(where)
: [],
])
const empty = {
totalCount: 0,
avgScore: 0,
gradeDistribution: {},
criteriaAverages: {},
personCount: roster.length,
completedCount: 0,
wordFrequencies: [],
dataUnaccepted: [],
if (!totals || totals.total === 0) {
return success(c, {
totalCount: 0,
avgScore: 0,
gradeDistribution: {},
criteriaAverages: {},
personCount: roster.length,
completedCount: 0,
wordFrequencies: [],
// 一条提交都没有时,花名册上的人**全都**是「没做」—— 原来这里写死空数组,
// 于是一节课刚开始、最该点名的时候,教师面板反而一个名字都不给
dataUnaccepted: roster.map((row) => ({
username: row.username,
realName: stripClassPrefix(row.username, row.className),
})),
} satisfies FlowchartStatistics)
}
if (rows.length === 0) return success(c, flowchartStatisticsSchema.parse(empty))
const gradeDistribution: Record<string, number> = {}
const criteriaTotals = new Map<string, { sum: number; count: number; max: number }>()
const texts: string[] = []
const submitted = new Set<string>()
let scoreSum = 0
let scoreCount = 0
for (const row of rows) {
submitted.add(row.username)
// 旧后端用 values_list("ai_grade") 分组,null 也会成为一个桶;这里保持同样的口径
for (const row of gradeRows) {
// 旧后端用 values_list("ai_grade") 分组,null 也会成为一个桶;这里保持同样的口径。
// null 和空串会分成两组,合并到同一个桶里
const grade = row.grade ?? ""
gradeDistribution[grade] = (gradeDistribution[grade] ?? 0) + 1
if (row.score !== null) {
scoreSum += row.score
scoreCount += 1
}
gradeDistribution[grade] = (gradeDistribution[grade] ?? 0) + row.n
}
/**
* textRows
*
*
* create_time **** max
* 退 100 `if (bucket) ... else set(max)`
* WORDCLOUD_TEXT_LIMIT
* 30 40****
* SQL 退 100
*/
const criteriaMax = new Map<string, number>()
const texts: string[] = []
const pushText = (value: string) => {
if (texts.length < WORDCLOUD_TEXT_LIMIT) texts.push(value)
}
for (const row of textRows) {
for (const [key, value] of Object.entries(objectValue(row.criteria))) {
const detail = objectValue(value)
// 和上面那条聚合同一道闸:分数不是数字的项当没配过,满分和评语也都不收
if (typeof detail.score !== "number") continue
const bucket = criteriaTotals.get(key)
if (bucket) {
bucket.sum += detail.score
bucket.count += 1
} else {
// max 取第一次见到的那条,与旧后端 `if key not in criteria_max` 一致
criteriaTotals.set(key, {
sum: detail.score,
count: 1,
max: typeof detail.max === "number" ? detail.max : 100,
})
if (!criteriaMax.has(key)) {
criteriaMax.set(key, typeof detail.max === "number" ? detail.max : 100)
}
if (typeof detail.comment === "string" && detail.comment) texts.push(detail.comment)
if (typeof detail.comment === "string" && detail.comment)
pushText(detail.comment)
}
if (row.feedback) texts.push(row.feedback)
if (row.suggestions) texts.push(row.suggestions)
if (row.feedback) pushText(row.feedback)
if (row.suggestions) pushText(row.suggestions)
}
const criteriaAverages: Record<string, { avg: number; max: number }> = {}
for (const [key, bucket] of criteriaTotals) {
criteriaAverages[key] = { avg: rounded(bucket.sum / bucket.count, 1), max: bucket.max }
for (const row of criteriaRows) {
criteriaAverages[row.key] = {
avg: rounded(row.avg, 1),
max: criteriaMax.get(row.key) ?? 100,
}
}
return success(c, flowchartStatisticsSchema.parse({
totalCount: rows.length,
// 分母是有分数的条数,不是总条数 —— 对齐 Django 的 Avg(),它跳过 NULL
avgScore: scoreCount ? rounded(scoreSum / scoreCount, 1) : 0,
const submitted = new Set(submittedRows.map((row) => row.userId))
return success(c, {
totalCount: totals.total,
avgScore: totals.scoreCount
? rounded(totals.scoreSum / totals.scoreCount, 1)
: 0,
gradeDistribution,
criteriaAverages,
personCount: roster.length,
completedCount: submitted.size,
completedCount: totals.completedCount,
wordFrequencies: await buildWordFrequencies(texts),
dataUnaccepted: roster
.filter((row) => !submitted.has(row.username))
.filter((row) => !submitted.has(row.id))
.map((row) => ({
username: row.username,
realName: stripClassPrefix(row.username, row.className),
})),
}))
} satisfies FlowchartStatistics)
})
flowchartRoutes.get("/flowcharts/:id", requireAuth, async (c) => {
const [row] = await db.select({ flowchart: schema.flowchartSubmission, username: schema.user.username, problem: schema.problem })
.from(schema.flowchartSubmission).innerJoin(schema.user, eq(schema.flowchartSubmission.userId, schema.user.id))
.innerJoin(schema.problem, eq(schema.flowchartSubmission.problemId, schema.problem.id))
.where(eq(schema.flowchartSubmission.id, c.req.param("id"))).limit(1)
if (!row || !canView(c.get("user")!, row.flowchart, row.problem)) return failure(c, 404, "flowchart-not-found", "Submission does not exist")
const [row] = await db
.select({
flowchart: schema.flowchartSubmission,
username: schema.user.username,
problem: schema.problem,
})
.from(schema.flowchartSubmission)
.innerJoin(
schema.user,
eq(schema.flowchartSubmission.userId, schema.user.id),
)
.innerJoin(
schema.problem,
eq(schema.flowchartSubmission.problemId, schema.problem.id),
)
.where(eq(schema.flowchartSubmission.id, c.req.param("id")))
.limit(1)
if (!row || !canView(c.get("user")!, row.flowchart, row.problem))
return failure(c, 404, "flowchart-not-found", "Submission does not exist")
return success(c, flowchartData(row.flowchart, row.username))
})
flowchartRoutes.post("/flowcharts/:id/retry", requireAuth, async (c) => {
const [row] = await db.select({ flowchart: schema.flowchartSubmission, problem: schema.problem }).from(schema.flowchartSubmission)
.innerJoin(schema.problem, eq(schema.flowchartSubmission.problemId, schema.problem.id))
.where(eq(schema.flowchartSubmission.id, c.req.param("id"))).limit(1)
if (!row || !canView(c.get("user")!, row.flowchart, row.problem)) return failure(c, 404, "flowchart-not-found", "Submission does not exist")
if (![2, 3].includes(row.flowchart.status)) return failure(c, 409, "retry-not-allowed", "Submission is not in a state that allows retry")
await db.update(schema.flowchartSubmission).set({
status: 0, aiScore: null, aiGrade: null, aiFeedback: null, aiSuggestions: null,
aiCriteriaDetails: {}, processingTime: null, evaluationTime: null,
}).where(eq(schema.flowchartSubmission.id, row.flowchart.id))
await flowchartQueue.add("evaluate", { submissionId: row.flowchart.id }, { jobId: `${row.flowchart.id}:${Date.now()}` })
return success(c, createFlowchartResponseSchema.parse({ submissionId: row.flowchart.id, status: "pending" }))
const user = c.get("user")!
const [row] = await db
.select({ flowchart: schema.flowchartSubmission, problem: schema.problem })
.from(schema.flowchartSubmission)
.innerJoin(
schema.problem,
eq(schema.flowchartSubmission.problemId, schema.problem.id),
)
.where(eq(schema.flowchartSubmission.id, c.req.param("id")))
.limit(1)
if (!row || !canView(user, row.flowchart, row.problem))
return failure(c, 404, "flowchart-not-found", "Submission does not exist")
if (![2, 3].includes(row.flowchart.status))
return failure(
c,
409,
"retry-not-allowed",
"Submission is not in a state that allows retry",
)
// canView 允许本人重试自己的提交,不限流的话学生可以反复点着刷 AI 调用。
// 教师放行:重新判题是他们的日常操作,成批点几十行是正常用法
if (!isAdminRole(user)) {
const throttle = await consumeToken("user", flowchartThrottleKey(user.id))
if (!throttle.allowed) {
return failure(
c,
429,
"too-many-submissions",
`Please wait ${Math.floor(throttle.wait)} seconds`,
)
}
}
await db
.update(schema.flowchartSubmission)
.set({
status: 0,
aiScore: null,
aiGrade: null,
aiFeedback: null,
aiSuggestions: null,
aiCriteriaDetails: {},
processingTime: null,
evaluationTime: null,
})
.where(eq(schema.flowchartSubmission.id, row.flowchart.id))
try {
// jobId 必须**正好三段**bullmq 对含 `:` 的自定义 id 有一条兼容老的可重复
// 任务的校验(job.js 的 `split(':').length !== 3`),两段会直接抛
// `Custom Id cannot contain :`。原来写的是 `${id}:${时间戳}`,于是这个接口
// 从来没成功过 —— 而清空评分在入队之前,每点一次就把原来的分数永久清掉、
// 提交卡在 PENDING 且没有任何任务会来救它。
await flowchartQueue.add(
"evaluate",
{ submissionId: row.flowchart.id },
{ jobId: `${row.flowchart.id}:retry:${Date.now()}` },
)
} catch (error) {
// 入队失败就落 FAILED,别把提交丢在 PENDING 上 —— 和 POST /flowcharts 同一处理
await db
.update(schema.flowchartSubmission)
.set({ status: 3 })
.where(eq(schema.flowchartSubmission.id, row.flowchart.id))
return failure(
c,
502,
"queue-unavailable",
"Evaluation queue is unavailable",
)
}
return success(c, {
submissionId: row.flowchart.id,
status: "pending",
} satisfies CreateFlowchartResponse)
})
flowchartRoutes.get("/problems/:id/flowchart/current", requireAuth, async (c) => {
const problemId = queryInteger(c.req.param("id"), 0, { min: 1 })
const rows = await db.select({ score: schema.flowchartSubmission.aiScore, grade: schema.flowchartSubmission.aiGrade })
.from(schema.flowchartSubmission).where(and(eq(schema.flowchartSubmission.userId, c.get("user")!.id), eq(schema.flowchartSubmission.problemId, problemId), eq(schema.flowchartSubmission.status, 2)))
.orderBy(desc(schema.flowchartSubmission.createTime))
return success(c, flowchartCurrentSchema.parse({ count: rows.length, score: rows[0]?.score ?? 0, grade: rows[0]?.grade ?? "" }))
})
flowchartRoutes.get(
"/problems/:id/flowchart/current",
requireAuth,
async (c) => {
const problemId = queryInteger(c.req.param("id"), 0, { min: 1 })
const rows = await db
.select({
score: schema.flowchartSubmission.aiScore,
grade: schema.flowchartSubmission.aiGrade,
})
.from(schema.flowchartSubmission)
.where(
and(
eq(schema.flowchartSubmission.userId, c.get("user")!.id),
eq(schema.flowchartSubmission.problemId, problemId),
eq(schema.flowchartSubmission.status, 2),
),
)
.orderBy(desc(schema.flowchartSubmission.createTime))
return success(c, {
count: rows.length,
score: rows[0]?.score ?? 0,
grade: rows[0]?.grade ?? "",
} satisfies FlowchartCurrent)
},
)
flowchartRoutes.get("/problems/:id/flowchart/history", requireAuth, async (c) => {
const problemId = queryInteger(c.req.param("id"), 0, { min: 1 })
const page = queryInteger(c.req.query("page"), 0, { min: 0 })
const rows = await db.select({ flowchart: schema.flowchartSubmission, username: schema.user.username })
.from(schema.flowchartSubmission).innerJoin(schema.user, eq(schema.flowchartSubmission.userId, schema.user.id))
.where(and(eq(schema.flowchartSubmission.userId, c.get("user")!.id), eq(schema.flowchartSubmission.problemId, problemId), eq(schema.flowchartSubmission.status, 2)))
.orderBy(asc(schema.flowchartSubmission.createTime))
const selected = page === 0 ? rows.at(-1) : rows[page - 1]
if (page > rows.length) return failure(c, 400, "page-out-of-range", "Page out of range")
return success(c, flowchartDetailSchema.parse({ submission: selected ? flowchartData(selected.flowchart, selected.username) : null, count: rows.length }))
})
flowchartRoutes.get(
"/problems/:id/flowchart/history",
requireAuth,
async (c) => {
const problemId = queryInteger(c.req.param("id"), 0, { min: 1 })
const page = queryInteger(c.req.query("page"), 0, { min: 0 })
const rows = await db
.select({
flowchart: schema.flowchartSubmission,
username: schema.user.username,
})
.from(schema.flowchartSubmission)
.innerJoin(
schema.user,
eq(schema.flowchartSubmission.userId, schema.user.id),
)
.where(
and(
eq(schema.flowchartSubmission.userId, c.get("user")!.id),
eq(schema.flowchartSubmission.problemId, problemId),
eq(schema.flowchartSubmission.status, 2),
),
)
.orderBy(asc(schema.flowchartSubmission.createTime))
const selected = page === 0 ? rows.at(-1) : rows[page - 1]
if (page > rows.length)
return failure(c, 400, "page-out-of-range", "Page out of range")
return success(c, {
submission: selected
? flowchartData(selected.flowchart, selected.username)
: null,
count: rows.length,
} satisfies FlowchartDetail)
},
)
+78 -23
View File
@@ -1,6 +1,10 @@
import { sampleUserSchema, type SampleUser } from "@oj2/contract"
import { ADMIN_ROLES, TEACHER_ROLES, type SampleUser } from "@oj2/contract"
import { and, count, eq, ilike, notInArray } from "drizzle-orm"
import type { AuthUser } from "../auth/session"
import { db, schema } from "../db"
import { NON_FAILURE_RESULTS } from "../judge/status"
/**
* `utils/api/_serializers.py` `UsernameSerializer`
@@ -17,11 +21,11 @@ export function sampleUser(
realName: string | null | undefined,
options: { includeRealName?: boolean } = {},
): SampleUser {
return sampleUserSchema.parse({
return {
id: source.id,
username: source.username,
realName: options.includeRealName === true ? (realName ?? null) : null,
})
} satisfies SampleUser
}
/**
@@ -40,18 +44,25 @@ export function stripClassPrefix(
return username.startsWith(prefix) ? username.slice(prefix.length) : username
}
/**
* query `$type` `submission.result``problem.difficulty`
*
* URL SQL
* ****
*
*/
export function asFilterValue<T extends string | number>(
value: string | number,
): T {
return value as T
}
export function objectValue(value: unknown): Record<string, unknown> {
return value && typeof value === "object" && !Array.isArray(value)
? (value as Record<string, unknown>)
: {}
}
export function stringArray(value: unknown): string[] {
return Array.isArray(value)
? value.filter((item): item is string => typeof item === "string")
: []
}
export function queryInteger(
value: string | undefined,
fallback: number,
@@ -64,14 +75,9 @@ export function queryInteger(
return parsed
}
// 角色判断一律用白名单,对齐旧后端 `account/models.py:65-73` 的 is_admin_role /
// is_teacher_or_above 显式列举写法
//
// 不要写成黑名单(`adminType !== "Regular User"`):当前四种角色下两者等价,但将来新增
// 任何角色(助教、家长……)都会**默认拿到管理员权限**,包括 canViewSubmission 里的
//「看所有人代码」。加角色的人多半想不到要回来改这里,白名单则会默认拒绝。
const ADMIN_ROLES = ["Student Admin", "Teacher Admin", "Super Admin"]
const TEACHER_ROLES = ["Teacher Admin", "Super Admin"]
// 角色白名单本身在 `@oj2/contract` 的 roles.ts,那是全仓唯一的定义处;
// 这里只是把它们包成吃 AuthUser 的谓词。为什么必须是白名单,见那边的注释
export { TEACHER_ROLES }
// 注意:不要再加 isRegularUser(user) 这类「是普通用户才受限」的判断 ——
// 匿名用户 user 为 null 时它返回 false,守卫会整体短路,匿名的权限反而大于登录学生。
@@ -98,13 +104,62 @@ export function publicTemplates(value: unknown) {
return templates
}
export function todayStart() {
const now = new Date()
now.setHours(0, 0, 0, 0)
return now.toISOString()
}
export function rounded(value: number, digits = 2) {
const factor = 10 ** digits
return Math.round(value * factor) / factor
}
/**
* AI
*
* `myFailedCount` `POST /ai/hint` ****
* `notInArray(result, [0, 10])`
* / hint
* `hint-locked`
*/
export async function countFailedSubmissions(
userId: number,
problemId: number,
) {
const [failed] = await db
.select({ value: count() })
.from(schema.submission)
.where(
and(
eq(schema.submission.userId, userId),
eq(schema.submission.problemId, problemId),
notInArray(schema.submission.result, NON_FAILURE_RESULTS),
),
)
return failed?.value ?? 0
}
/**
* **** id
* ****
*
* `user` `submission.username`
* `ilike submission.username`
*
* 2026-09-0824 85
* `ks249` 0 / 7 48
* `ks248` 20 / 54 13
*
* ****
* +
*
*
* `user_id` id
*/
export async function matchedUsers(username: string) {
return db
.select({
id: schema.user.id,
username: schema.user.username,
className: schema.user.className,
isDisabled: schema.user.isDisabled,
adminType: schema.user.adminType,
})
.from(schema.user)
.where(ilike(schema.user.username, `%${username}%`))
}
+463 -276
View File
@@ -1,25 +1,25 @@
import {
problemAuthorSchema,
problemDetailSchema,
problemListItemSchema,
problemListSchema,
tagSchema,
yearlyAcSchema,
import type {
ProblemAuthor,
ProblemDetail,
ProblemList,
ProblemListItem,
Tag,
YearlyAc,
} from "@oj2/contract"
import {
and,
asc,
count,
countDistinct,
desc,
eq,
gte,
ilike,
inArray,
isNull,
notInArray,
or,
sql,
and,
asc,
count,
countDistinct,
desc,
eq,
gte,
ilike,
inArray,
isNull,
notInArray,
or,
sql,
} from "drizzle-orm"
import { Hono } from "hono"
@@ -28,308 +28,495 @@ import { db, schema } from "../db"
import { astRequirements } from "../judge/ast"
import { failure, success } from "../http"
import { JudgeStatus } from "../judge/status"
import { objectValue as toObject, queryInteger, sampleUser } from "./helpers"
import { localTime, shiftMonthsByCalendar, todayStart } from "../time"
import {
asFilterValue,
countFailedSubmissions,
objectValue as toObject,
queryInteger,
sampleUser,
} from "./helpers"
export const problemRoutes = new Hono<AppEnv>()
function objectValue(value: unknown): Record<string, unknown> {
return value && typeof value === "object" && !Array.isArray(value)
? (value as Record<string, unknown>)
: {}
}
function stringArray(value: unknown): string[] {
return Array.isArray(value) ? value.filter((item): item is string => typeof item === "string") : []
return value && typeof value === "object" && !Array.isArray(value)
? (value as Record<string, unknown>)
: {}
}
function publicTemplates(value: unknown) {
const templates: Record<string, string> = {}
for (const [language, raw] of Object.entries(objectValue(value))) {
if (typeof raw !== "string") continue
const match = raw.match(/\/\/TEMPLATE BEGIN\n([\s\S]+?)\/\/TEMPLATE END/)
templates[language] = match?.[1] ?? ""
}
return templates
const templates: Record<string, string> = {}
for (const [language, raw] of Object.entries(objectValue(value))) {
if (typeof raw !== "string") continue
const match = raw.match(/\/\/TEMPLATE BEGIN\n([\s\S]+?)\/\/TEMPLATE END/)
templates[language] = match?.[1] ?? ""
}
return templates
}
async function getProblemStatuses(userId: number | undefined) {
if (!userId) return {}
const [profile] = await db.select({ value: schema.userProfile.acmProblemsStatus })
.from(schema.userProfile).where(eq(schema.userProfile.userId, userId)).limit(1)
return toObject(toObject(profile?.value).problems)
if (!userId) return {}
const [profile] = await db
.select({ value: schema.userProfile.acmProblemsStatus })
.from(schema.userProfile)
.where(eq(schema.userProfile.userId, userId))
.limit(1)
return toObject(toObject(profile?.value).problems)
}
async function getProblemTags(problemIds: number[]) {
if (problemIds.length === 0) return new Map<number, string[]>()
const rows = await db.select({ problemId: schema.problemTags.problemId, name: schema.problemTag.name })
.from(schema.problemTags)
.innerJoin(schema.problemTag, eq(schema.problemTags.problemtagId, schema.problemTag.id))
.where(inArray(schema.problemTags.problemId, problemIds))
const result = new Map<number, string[]>()
for (const row of rows) result.set(row.problemId, [...(result.get(row.problemId) ?? []), row.name])
return result
if (problemIds.length === 0) return new Map<number, string[]>()
const rows = await db
.select({
problemId: schema.problemTags.problemId,
name: schema.problemTag.name,
})
.from(schema.problemTags)
.innerJoin(
schema.problemTag,
eq(schema.problemTags.problemtagId, schema.problemTag.id),
)
.where(inArray(schema.problemTags.problemId, problemIds))
const result = new Map<number, string[]>()
for (const row of rows)
result.set(row.problemId, [...(result.get(row.problemId) ?? []), row.name])
return result
}
function listItem(
row: { problem: typeof schema.problem.$inferSelect; user: typeof schema.user.$inferSelect; realName: string | null },
tags: Map<number, string[]>,
statuses: Record<string, unknown>,
row: {
problem: typeof schema.problem.$inferSelect
user: typeof schema.user.$inferSelect
realName: string | null
},
tags: Map<number, string[]>,
statuses: Record<string, unknown>,
) {
const status = toObject(statuses[String(row.problem.id)]).status
return problemListItemSchema.parse({
id: row.problem.id,
_id: row.problem.displayId,
title: row.problem.title,
submissionNumber: row.problem.submissionNumber,
acceptedNumber: row.problem.acceptedNumber,
difficulty: row.problem.difficulty,
createdBy: sampleUser(row.user, row.realName),
tags: tags.get(row.problem.id) ?? [],
contestId: row.problem.contestId,
allowFlowchart: row.problem.allowFlowchart,
showFlowchart: row.problem.showFlowchart,
hasAstRules: row.problem.astRules !== null,
myStatus: typeof status === "number" ? status : null,
})
const status = toObject(statuses[String(row.problem.id)]).status
return {
id: row.problem.id,
_id: row.problem.displayId,
title: row.problem.title,
submissionNumber: row.problem.submissionNumber,
acceptedNumber: row.problem.acceptedNumber,
difficulty: row.problem.difficulty,
createdBy: sampleUser(row.user, row.realName),
tags: tags.get(row.problem.id) ?? [],
contestId: row.problem.contestId,
allowFlowchart: row.problem.allowFlowchart,
showFlowchart: row.problem.showFlowchart,
hasAstRules: row.problem.astRules !== null,
myStatus: typeof status === "number" ? status : null,
} satisfies ProblemListItem
}
problemRoutes.get("/problems", optionalAuth, async (c) => {
const limit = queryInteger(c.req.query("limit"), 20, { min: 1, max: 250 })
const offset = queryInteger(c.req.query("offset"), 0, { min: 0 })
const filters = [eq(schema.problem.visible, true), isNull(schema.problem.contestId)]
const author = c.req.query("author")?.trim()
const keyword = c.req.query("keyword")?.trim()
const difficulty = c.req.query("difficulty")?.trim()
const tag = c.req.query("tag")?.trim()
if (author) filters.push(eq(schema.user.username, author))
if (keyword) filters.push(or(ilike(schema.problem.title, `%${keyword}%`), ilike(schema.problem.displayId, `%${keyword}%`))!)
if (difficulty) filters.push(eq(schema.problem.difficulty, difficulty))
if (tag) {
filters.push(inArray(schema.problem.id, db.select({ id: schema.problemTags.problemId }).from(schema.problemTags)
.innerJoin(schema.problemTag, eq(schema.problemTags.problemtagId, schema.problemTag.id))
.where(eq(schema.problemTag.name, tag))))
}
const limit = queryInteger(c.req.query("limit"), 20, { min: 1, max: 250 })
const offset = queryInteger(c.req.query("offset"), 0, { min: 0 })
const filters = [
eq(schema.problem.visible, true),
isNull(schema.problem.contestId),
]
const author = c.req.query("author")?.trim()
const keyword = c.req.query("keyword")?.trim()
const difficulty = c.req.query("difficulty")?.trim()
const tag = c.req.query("tag")?.trim()
if (author) filters.push(eq(schema.user.username, author))
if (keyword)
filters.push(
or(
ilike(schema.problem.title, `%${keyword}%`),
ilike(schema.problem.displayId, `%${keyword}%`),
)!,
)
if (difficulty)
filters.push(eq(schema.problem.difficulty, asFilterValue(difficulty)))
if (tag) {
filters.push(
inArray(
schema.problem.id,
db
.select({ id: schema.problemTags.problemId })
.from(schema.problemTags)
.innerJoin(
schema.problemTag,
eq(schema.problemTags.problemtagId, schema.problemTag.id),
)
.where(eq(schema.problemTag.name, tag)),
),
)
}
const where = and(...filters)
const sort = c.req.query("sort")
const order = sort === "flowchart"
? [desc(schema.problem.allowFlowchart), desc(schema.problem.showFlowchart), desc(schema.problem.createTime)]
: sort === "ast"
? [desc(sql`(${schema.problem.astRules} is not null)`), desc(schema.problem.createTime)]
: sort === "-accepted_number"
? [desc(schema.problem.acceptedNumber)]
: sort === "accepted_number"
? [asc(schema.problem.acceptedNumber)]
: sort === "-submission_number"
? [desc(schema.problem.submissionNumber)]
: sort === "submission_number"
? [asc(schema.problem.submissionNumber)]
: sort === "difficulty"
? [asc(schema.problem.difficulty)]
: sort === "create_time"
? [asc(schema.problem.createTime)]
: [desc(schema.problem.createTime)]
const [totalRow] = await db.select({ value: countDistinct(schema.problem.id) }).from(schema.problem)
.innerJoin(schema.user, eq(schema.problem.createdById, schema.user.id)).where(where)
const rows = await db.select({ problem: schema.problem, user: schema.user, realName: schema.userProfile.realName })
.from(schema.problem)
.innerJoin(schema.user, eq(schema.problem.createdById, schema.user.id))
.leftJoin(schema.userProfile, eq(schema.userProfile.userId, schema.user.id))
.where(where).orderBy(...order).limit(limit).offset(offset)
const [tags, statuses] = await Promise.all([
getProblemTags(rows.map((row) => row.problem.id)),
getProblemStatuses(c.get("user")?.id),
])
return success(c, problemListSchema.parse({
results: rows.map((row) => listItem(row, tags, statuses)),
total: totalRow?.value ?? 0,
}))
const where = and(...filters)
const sort = c.req.query("sort")
const order =
sort === "flowchart"
? [
desc(schema.problem.allowFlowchart),
desc(schema.problem.showFlowchart),
desc(schema.problem.createTime),
]
: sort === "ast"
? [
desc(sql`(${schema.problem.astRules} is not null)`),
desc(schema.problem.createTime),
]
: sort === "-accepted_number"
? [desc(schema.problem.acceptedNumber)]
: sort === "accepted_number"
? [asc(schema.problem.acceptedNumber)]
: sort === "-submission_number"
? [desc(schema.problem.submissionNumber)]
: sort === "submission_number"
? [asc(schema.problem.submissionNumber)]
: sort === "difficulty"
? [asc(schema.problem.difficulty)]
: sort === "create_time"
? [asc(schema.problem.createTime)]
: [desc(schema.problem.createTime)]
const [totalRow] = await db
.select({ value: countDistinct(schema.problem.id) })
.from(schema.problem)
.innerJoin(schema.user, eq(schema.problem.createdById, schema.user.id))
.where(where)
const rows = await db
.select({
problem: schema.problem,
user: schema.user,
realName: schema.userProfile.realName,
})
.from(schema.problem)
.innerJoin(schema.user, eq(schema.problem.createdById, schema.user.id))
.leftJoin(schema.userProfile, eq(schema.userProfile.userId, schema.user.id))
.where(where)
.orderBy(...order)
.limit(limit)
.offset(offset)
const [tags, statuses] = await Promise.all([
getProblemTags(rows.map((row) => row.problem.id)),
getProblemStatuses(c.get("user")?.id),
])
return success(c, {
results: rows.map((row) => listItem(row, tags, statuses)),
total: totalRow?.value ?? 0,
} satisfies ProblemList)
})
problemRoutes.get("/problem-tags", async (c) => {
const keyword = c.req.query("keyword")?.trim()
// 只数公开题库里可见的题:隐藏的题和比赛题都不算,否则标签会出现在
// 首页列表里,点进去却一道题都筛不出来(对齐 /problems 的过滤条件)
const rows = await db.select({ id: schema.problemTag.id, name: schema.problemTag.name, problemCount: countDistinct(schema.problemTags.problemId) })
.from(schema.problemTag)
.innerJoin(schema.problemTags, eq(schema.problemTags.problemtagId, schema.problemTag.id))
.innerJoin(schema.problem, and(
eq(schema.problem.id, schema.problemTags.problemId),
eq(schema.problem.visible, true),
isNull(schema.problem.contestId),
))
.where(keyword ? ilike(schema.problemTag.name, `%${keyword}%`) : undefined)
.groupBy(schema.problemTag.id, schema.problemTag.name).having(sql`count(${schema.problemTags.problemId}) > 0`)
.orderBy(asc(schema.problemTag.name))
return success(c, rows.map((row) => tagSchema.parse(row)))
const keyword = c.req.query("keyword")?.trim()
// 只数公开题库里可见的题:隐藏的题和比赛题都不算,否则标签会出现在
// 首页列表里,点进去却一道题都筛不出来(对齐 /problems 的过滤条件)
const rows = await db
.select({
id: schema.problemTag.id,
name: schema.problemTag.name,
problemCount: countDistinct(schema.problemTags.problemId),
})
.from(schema.problemTag)
.innerJoin(
schema.problemTags,
eq(schema.problemTags.problemtagId, schema.problemTag.id),
)
.innerJoin(
schema.problem,
and(
eq(schema.problem.id, schema.problemTags.problemId),
eq(schema.problem.visible, true),
isNull(schema.problem.contestId),
),
)
.where(keyword ? ilike(schema.problemTag.name, `%${keyword}%`) : undefined)
.groupBy(schema.problemTag.id, schema.problemTag.name)
.having(sql`count(${schema.problemTags.problemId}) > 0`)
.orderBy(asc(schema.problemTag.name))
return success(c, rows satisfies Tag[])
})
problemRoutes.get("/problems/random", async (c) => {
const [row] = await db.select({ displayId: schema.problem.displayId }).from(schema.problem)
.where(and(eq(schema.problem.visible, true), isNull(schema.problem.contestId))).orderBy(sql`random()`).limit(1)
if (!row) return failure(c, 404, "no-problems", "No problem to pick")
return success(c, row.displayId)
const [row] = await db
.select({ displayId: schema.problem.displayId })
.from(schema.problem)
.where(
and(eq(schema.problem.visible, true), isNull(schema.problem.contestId)),
)
.orderBy(sql`random()`)
.limit(1)
if (!row) return failure(c, 404, "no-problems", "No problem to pick")
return success(c, row.displayId)
})
problemRoutes.get("/problem-authors", async (c) => {
const showAll = c.req.query("all") === "1"
const rows = await db.select({ username: schema.user.username, problemCount: count(schema.problem.id) })
.from(schema.problem).innerJoin(schema.user, eq(schema.problem.createdById, schema.user.id))
.where(and(isNull(schema.problem.contestId), eq(schema.user.isDisabled, false), showAll ? undefined : eq(schema.problem.visible, true)))
.groupBy(schema.user.username).orderBy(desc(count(schema.problem.id)))
return success(c, rows.map((row) => problemAuthorSchema.parse(row)))
const showAll = c.req.query("all") === "1"
const rows = await db
.select({
username: schema.user.username,
problemCount: count(schema.problem.id),
})
.from(schema.problem)
.innerJoin(schema.user, eq(schema.problem.createdById, schema.user.id))
.where(
and(
isNull(schema.problem.contestId),
eq(schema.user.isDisabled, false),
showAll ? undefined : eq(schema.problem.visible, true),
),
)
.groupBy(schema.user.username)
.orderBy(desc(count(schema.problem.id)))
return success(c, rows satisfies ProblemAuthor[])
})
problemRoutes.get("/problems/:id/beat-count", optionalAuth, async (c) => {
const user = c.get("user")
if (!user) return success(c, "0")
const id = queryInteger(c.req.param("id"), 0, { min: 1 })
const [mine] = await db.select({ value: count() }).from(schema.submission).where(and(
eq(schema.submission.userId, user.id), eq(schema.submission.problemId, id),
inArray(schema.submission.result, [JudgeStatus.ACCEPTED, JudgeStatus.AST_CHECK_FAILED]),
))
if (!mine?.value) return success(c, "0")
const since = new Date(); since.setFullYear(since.getFullYear() - 2); since.setHours(0, 0, 0, 0)
const [active, accepted] = await Promise.all([
db.select({ value: count() }).from(schema.user).where(and(eq(schema.user.isDisabled, false), gte(schema.user.lastLogin, since.toISOString()))),
db.select({ value: countDistinct(schema.submission.userId) }).from(schema.submission).where(and(
eq(schema.submission.problemId, id), inArray(schema.submission.result, [0, 10]), gte(schema.submission.createTime, since.toISOString()),
)),
])
const total = active[0]?.value ?? 0
const solved = accepted[0]?.value ?? 0
return success(c, total > 0 && solved < total ? (((total - solved) / total) * 100).toFixed(2) : "0")
const user = c.get("user")
if (!user) return success(c, "0")
const id = queryInteger(c.req.param("id"), 0, { min: 1 })
const [mine] = await db
.select({ value: count() })
.from(schema.submission)
.where(
and(
eq(schema.submission.userId, user.id),
eq(schema.submission.problemId, id),
inArray(schema.submission.result, [
JudgeStatus.ACCEPTED,
JudgeStatus.AST_CHECK_FAILED,
]),
),
)
if (!mine?.value) return success(c, "0")
// 「近两年」按东八区日历算到当天零点
const since = todayStart(shiftMonthsByCalendar(new Date(), -24))
const [active, accepted] = await Promise.all([
db
.select({ value: count() })
.from(schema.user)
.where(
and(
eq(schema.user.isDisabled, false),
gte(schema.user.lastLogin, since),
),
),
db
.select({ value: countDistinct(schema.submission.userId) })
.from(schema.submission)
.where(
and(
eq(schema.submission.problemId, id),
inArray(schema.submission.result, [0, 10]),
gte(schema.submission.createTime, since),
),
),
])
const total = active[0]?.value ?? 0
const solved = accepted[0]?.value ?? 0
return success(
c,
total > 0 && solved < total
? (((total - solved) / total) * 100).toFixed(2)
: "0",
)
})
problemRoutes.get("/problems/:displayId/similar", optionalAuth, async (c) => {
const [target] = await db.select({ id: schema.problem.id }).from(schema.problem)
.where(and(sql`lower(${schema.problem.displayId}) = lower(${c.req.param("displayId")})`, isNull(schema.problem.contestId))).limit(1)
if (!target) return failure(c, 404, "problem-not-found", "Problem not found")
const targetTags = await db.select({ id: schema.problemTags.problemtagId }).from(schema.problemTags).where(eq(schema.problemTags.problemId, target.id))
if (targetTags.length === 0) return success(c, [])
const rows = await db.select({ problem: schema.problem, user: schema.user, realName: schema.userProfile.realName })
.from(schema.problem)
.innerJoin(schema.user, eq(schema.problem.createdById, schema.user.id))
.leftJoin(schema.userProfile, eq(schema.userProfile.userId, schema.user.id))
.where(and(
eq(schema.problem.visible, true), isNull(schema.problem.contestId), sql`${schema.problem.id} <> ${target.id}`,
inArray(schema.problem.id, db.select({ id: schema.problemTags.problemId }).from(schema.problemTags)
.where(inArray(schema.problemTags.problemtagId, targetTags.map((tag) => tag.id)))),
)).groupBy(schema.problem.id, schema.user.id, schema.userProfile.realName).orderBy(asc(schema.problem.difficulty)).limit(5)
const [tags, statuses] = await Promise.all([getProblemTags(rows.map((row) => row.problem.id)), getProblemStatuses(c.get("user")?.id)])
const filtered = rows.filter((row) => toObject(statuses[String(row.problem.id)]).status !== JudgeStatus.ACCEPTED)
return success(c, filtered.map((row) => listItem(row, tags, statuses)))
const [target] = await db
.select({ id: schema.problem.id })
.from(schema.problem)
.where(
and(
sql`lower(${schema.problem.displayId}) = lower(${c.req.param("displayId")})`,
isNull(schema.problem.contestId),
),
)
.limit(1)
if (!target) return failure(c, 404, "problem-not-found", "Problem not found")
const targetTags = await db
.select({ id: schema.problemTags.problemtagId })
.from(schema.problemTags)
.where(eq(schema.problemTags.problemId, target.id))
if (targetTags.length === 0) return success(c, [])
const rows = await db
.select({
problem: schema.problem,
user: schema.user,
realName: schema.userProfile.realName,
})
.from(schema.problem)
.innerJoin(schema.user, eq(schema.problem.createdById, schema.user.id))
.leftJoin(schema.userProfile, eq(schema.userProfile.userId, schema.user.id))
.where(
and(
eq(schema.problem.visible, true),
isNull(schema.problem.contestId),
sql`${schema.problem.id} <> ${target.id}`,
inArray(
schema.problem.id,
db
.select({ id: schema.problemTags.problemId })
.from(schema.problemTags)
.where(
inArray(
schema.problemTags.problemtagId,
targetTags.map((tag) => tag.id),
),
),
),
),
)
.groupBy(schema.problem.id, schema.user.id, schema.userProfile.realName)
.orderBy(asc(schema.problem.difficulty))
.limit(5)
const [tags, statuses] = await Promise.all([
getProblemTags(rows.map((row) => row.problem.id)),
getProblemStatuses(c.get("user")?.id),
])
const filtered = rows.filter(
(row) =>
toObject(statuses[String(row.problem.id)]).status !==
JudgeStatus.ACCEPTED,
)
return success(
c,
filtered.map((row) => listItem(row, tags, statuses)),
)
})
problemRoutes.get("/problems/:displayId/yearly-ac", async (c) => {
const [problem] = await db.select({ id: schema.problem.id }).from(schema.problem)
.where(and(sql`lower(${schema.problem.displayId}) = lower(${c.req.param("displayId")})`, isNull(schema.problem.contestId), eq(schema.problem.visible, true))).limit(1)
if (!problem) return failure(c, 404, "problem-not-found", "Problem does not exist")
const year = sql<number>`extract(year from ${schema.submission.createTime})::int`
const rows = await db.select({
year,
total: count(),
accepted: sql<number>`count(*) filter (where ${schema.submission.result} in (0, 10))::int`,
}).from(schema.submission).where(and(eq(schema.submission.problemId, problem.id), isNull(schema.submission.contestId), notInArray(schema.submission.result, [6, 7])))
.groupBy(year).orderBy(year)
return success(c, rows.map((row) => yearlyAcSchema.parse({ ...row, acRate: row.total > 0 ? Math.round(row.accepted / row.total * 10_000) / 100 : 0 })))
const [problem] = await db
.select({ id: schema.problem.id })
.from(schema.problem)
.where(
and(
sql`lower(${schema.problem.displayId}) = lower(${c.req.param("displayId")})`,
isNull(schema.problem.contestId),
eq(schema.problem.visible, true),
),
)
.limit(1)
if (!problem)
return failure(c, 404, "problem-not-found", "Problem does not exist")
const year = sql<number>`extract(year from ${localTime(schema.submission.createTime)})::int`
const rows = await db
.select({
year,
total: count(),
accepted: sql<number>`count(*) filter (where ${schema.submission.result} in (0, 10))::int`,
})
.from(schema.submission)
.where(
and(
eq(schema.submission.problemId, problem.id),
isNull(schema.submission.contestId),
notInArray(schema.submission.result, [6, 7]),
),
)
.groupBy(year)
.orderBy(year)
return success(
c,
rows.map(
(row) =>
({
...row,
acRate:
row.total > 0
? Math.round((row.accepted / row.total) * 10_000) / 100
: 0,
}) satisfies YearlyAc,
),
)
})
problemRoutes.get("/problems/:displayId", optionalAuth, async (c) => {
const [row] = await db
.select({
problem: schema.problem,
creatorId: schema.user.id,
creatorUsername: schema.user.username,
})
.from(schema.problem)
.innerJoin(schema.user, eq(schema.problem.createdById, schema.user.id))
.where(
and(
eq(schema.problem.displayId, c.req.param("displayId")),
eq(schema.problem.visible, true),
isNull(schema.problem.contestId),
),
)
.limit(1)
const [row] = await db
.select({
problem: schema.problem,
creatorId: schema.user.id,
creatorUsername: schema.user.username,
})
.from(schema.problem)
.innerJoin(schema.user, eq(schema.problem.createdById, schema.user.id))
.where(
and(
eq(schema.problem.displayId, c.req.param("displayId")),
eq(schema.problem.visible, true),
isNull(schema.problem.contestId),
),
)
.limit(1)
if (!row) return failure(c, 404, "problem-not-found", "Problem does not exist")
if (!row)
return failure(c, 404, "problem-not-found", "Problem does not exist")
const tagRows = await db
.select({ name: schema.problemTag.name })
.from(schema.problemTags)
.innerJoin(
schema.problemTag,
eq(schema.problemTags.problemtagId, schema.problemTag.id),
)
.where(eq(schema.problemTags.problemId, row.problem.id))
const tagRows = await db
.select({ name: schema.problemTag.name })
.from(schema.problemTags)
.innerJoin(
schema.problemTag,
eq(schema.problemTags.problemtagId, schema.problemTag.id),
)
.where(eq(schema.problemTags.problemId, row.problem.id))
const user = c.get("user")
let myStatus: number | null = null
let myFailedCount = 0
if (user) {
const [profile] = await db
.select({ status: schema.userProfile.acmProblemsStatus })
.from(schema.userProfile)
.where(eq(schema.userProfile.userId, user.id))
.limit(1)
const statuses = objectValue(objectValue(profile?.status).problems)
const problemStatus = objectValue(statuses[String(row.problem.id)]).status
if (typeof problemStatus === "number") myStatus = problemStatus
const user = c.get("user")
let myStatus: number | null = null
let myFailedCount = 0
if (user) {
const [profile] = await db
.select({ status: schema.userProfile.acmProblemsStatus })
.from(schema.userProfile)
.where(eq(schema.userProfile.userId, user.id))
.limit(1)
const statuses = objectValue(objectValue(profile?.status).problems)
const problemStatus = objectValue(statuses[String(row.problem.id)]).status
if (typeof problemStatus === "number") myStatus = problemStatus
const [failed] = await db
.select({ value: count() })
.from(schema.submission)
.where(
and(
eq(schema.submission.userId, user.id),
eq(schema.submission.problemId, row.problem.id),
notInArray(schema.submission.result, [0, 10]),
),
)
myFailedCount = failed?.value ?? 0
}
// 前端拿这个数决定「让 AI 分析我的代码」露不露面,口径必须和 POST /ai/hint
// 的服务端闸门一致,所以两边共用 countFailedSubmissions
myFailedCount = await countFailedSubmissions(user.id, row.problem.id)
}
const samples = Array.isArray(row.problem.samples) ? row.problem.samples : []
const data = problemDetailSchema.parse({
id: row.problem.id,
_id: row.problem.displayId,
title: row.problem.title,
description: row.problem.description,
inputDescription: row.problem.inputDescription,
outputDescription: row.problem.outputDescription,
samples,
hint: row.problem.hint,
languages: stringArray(row.problem.languages),
template: publicTemplates(row.problem.template),
createTime: row.problem.createTime,
lastUpdateTime: row.problem.lastUpdateTime,
timeLimit: row.problem.timeLimit,
memoryLimit: row.problem.memoryLimit,
difficulty: row.problem.difficulty,
source: row.problem.source,
prompt: row.problem.prompt,
submissionNumber: row.problem.submissionNumber,
acceptedNumber: row.problem.acceptedNumber,
statisticInfo: objectValue(row.problem.statisticInfo),
shareSubmission: row.problem.shareSubmission,
contestId: row.problem.contestId,
tags: tagRows.map((tag) => tag.name),
createdBy: sampleUser({ id: row.creatorId, username: row.creatorUsername }, null),
myStatus,
myFailedCount,
allowFlowchart: row.problem.allowFlowchart,
showFlowchart: row.problem.showFlowchart,
mermaidCode: row.problem.allowFlowchart ? null : row.problem.mermaidCode,
flowchartData: row.problem.allowFlowchart
? null
: objectValue(row.problem.flowchartData),
flowchartHint: row.problem.flowchartHint,
sqlConfig: row.problem.sqlConfig ? objectValue(row.problem.sqlConfig) : null,
sqlDisplay: row.problem.sqlDisplay ? objectValue(row.problem.sqlDisplay) : null,
// 代码要求:只给渲染好的文案,规则原文不下发给学生
astRequirements: astRequirements(row.problem.astRules),
})
const samples = Array.isArray(row.problem.samples) ? row.problem.samples : []
const data = {
id: row.problem.id,
_id: row.problem.displayId,
title: row.problem.title,
description: row.problem.description,
inputDescription: row.problem.inputDescription,
outputDescription: row.problem.outputDescription,
samples,
hint: row.problem.hint,
languages: row.problem.languages,
template: publicTemplates(row.problem.template),
createTime: row.problem.createTime,
lastUpdateTime: row.problem.lastUpdateTime,
timeLimit: row.problem.timeLimit,
memoryLimit: row.problem.memoryLimit,
difficulty: row.problem.difficulty,
source: row.problem.source,
prompt: row.problem.prompt,
submissionNumber: row.problem.submissionNumber,
acceptedNumber: row.problem.acceptedNumber,
statisticInfo: objectValue(row.problem.statisticInfo),
contestId: row.problem.contestId,
tags: tagRows.map((tag) => tag.name),
createdBy: sampleUser(
{ id: row.creatorId, username: row.creatorUsername },
null,
),
myStatus,
myFailedCount,
allowFlowchart: row.problem.allowFlowchart,
showFlowchart: row.problem.showFlowchart,
mermaidCode: row.problem.allowFlowchart ? null : row.problem.mermaidCode,
flowchartData: row.problem.allowFlowchart
? null
: objectValue(row.problem.flowchartData),
flowchartHint: row.problem.flowchartHint,
sqlConfig: row.problem.sqlConfig,
sqlDisplay: row.problem.sqlDisplay,
// 代码要求:只给渲染好的文案,规则原文不下发给学生
astRequirements: astRequirements(row.problem.astRules),
} satisfies ProblemDetail
return success(c, data)
return success(c, data)
})
+467 -306
View File
@@ -1,14 +1,12 @@
import {
problemListItemSchema,
problemSetBadgeSchema,
problemSetListSchema,
problemSetProblemSchema,
problemSetProgressListSchema,
problemSetProgressSchema,
problemSetSchema,
updateProblemSetProgressRequestSchema,
joinProblemSetRequestSchema,
userBadgeSchema,
type ProblemSet,
type ProblemSetBadge,
type ProblemSetList,
type ProblemSetProblem,
type ProblemSetProgress,
type ProblemSetProgressList,
type UserBadge,
} from "@oj2/contract"
import {
and,
@@ -20,53 +18,68 @@ import {
gt,
ilike,
inArray,
isNull,
ne,
or,
sql,
} from "drizzle-orm"
import { Hono } from "hono"
import { optionalAuth, requireAuth, requireTeacher, type AppEnv } from "../auth/middleware"
import {
optionalAuth,
requireAuth,
requireTeacher,
type AppEnv,
} from "../auth/middleware"
import { db, schema } from "../db"
import { publishAchievementNotification } from "../events"
import { failure, success } from "../http"
import { JudgeStatus } from "../judge/status"
import { updateAchievementsForProblemSet } from "../services/achievements"
import { objectValue, queryInteger, sampleUser } from "./helpers"
import { computeProgress } from "../services/problemset"
import { asFilterValue, objectValue, queryInteger, sampleUser } from "./helpers"
export const problemsetRoutes = new Hono<AppEnv>()
type ProblemSetRow = typeof schema.problemset.$inferSelect
function progressSummary(progress: typeof schema.problemsetProgress.$inferSelect | undefined) {
return progress ? {
isJoined: true,
progressPercentage: progress.progressPercentage,
completedCount: progress.completedProblemsCount,
totalCount: progress.totalProblemsCount,
isCompleted: progress.isCompleted,
} : {
isJoined: false,
progressPercentage: 0,
completedCount: 0,
totalCount: 0,
isCompleted: false,
}
function progressSummary(
progress: typeof schema.problemsetProgress.$inferSelect | undefined,
) {
return progress
? {
isJoined: true,
progressPercentage: progress.progressPercentage,
completedCount: progress.completedProblemsCount,
totalCount: progress.totalProblemsCount,
isCompleted: progress.isCompleted,
}
: {
isJoined: false,
progressPercentage: 0,
completedCount: 0,
totalCount: 0,
isCompleted: false,
}
}
async function problemSetCreators(ids: number[]) {
const map = new Map<number, ReturnType<typeof sampleUser>>()
if (ids.length === 0) return map
const rows = await db.select({ id: schema.user.id, username: schema.user.username, realName: schema.userProfile.realName })
.from(schema.user).leftJoin(schema.userProfile, eq(schema.userProfile.userId, schema.user.id))
const rows = await db
.select({
id: schema.user.id,
username: schema.user.username,
realName: schema.userProfile.realName,
})
.from(schema.user)
.leftJoin(schema.userProfile, eq(schema.userProfile.userId, schema.user.id))
.where(inArray(schema.user.id, ids))
for (const row of rows) map.set(row.id, sampleUser(row, row.realName))
return map
}
function badgeData(badge: typeof schema.problemsetBadge.$inferSelect, earned?: boolean) {
return problemSetBadgeSchema.parse({
function badgeData(
badge: typeof schema.problemsetBadge.$inferSelect,
earned?: boolean,
) {
return {
id: badge.id,
problemsetId: badge.problemsetId,
name: badge.name,
@@ -75,7 +88,7 @@ function badgeData(badge: typeof schema.problemsetBadge.$inferSelect, earned?: b
conditionType: badge.conditionType,
conditionValue: badge.conditionValue,
isEarned: earned,
})
} satisfies ProblemSetBadge
}
/**
@@ -91,34 +104,78 @@ async function serializeProblemSets(
) {
if (rows.length === 0) return []
const ids = rows.map((row) => row.id)
const [problemCounts, progresses, badges, earnedRows, creators] = await Promise.all([
db.select({ problemsetId: schema.problemsetProblem.problemsetId, value: count() })
.from(schema.problemsetProblem).where(inArray(schema.problemsetProblem.problemsetId, ids))
.groupBy(schema.problemsetProblem.problemsetId),
userId ? db.select().from(schema.problemsetProgress)
.where(and(inArray(schema.problemsetProgress.problemsetId, ids), eq(schema.problemsetProgress.userId, userId)))
: Promise.resolve([] as (typeof schema.problemsetProgress.$inferSelect)[]),
includeBadges ? db.select().from(schema.problemsetBadge)
.where(inArray(schema.problemsetBadge.problemsetId, ids)).orderBy(asc(schema.problemsetBadge.id))
: Promise.resolve([] as (typeof schema.problemsetBadge.$inferSelect)[]),
includeBadges && userId ? db.select({ id: schema.userBadge.badgeId }).from(schema.userBadge)
.innerJoin(schema.problemsetBadge, eq(schema.userBadge.badgeId, schema.problemsetBadge.id))
.where(and(eq(schema.userBadge.userId, userId), inArray(schema.problemsetBadge.problemsetId, ids)))
: Promise.resolve([] as { id: number }[]),
problemSetCreators([...new Set(rows.map((row) => row.createdById))]),
])
const countBySet = new Map(problemCounts.map((item) => [item.problemsetId, item.value]))
const progressBySet = new Map(progresses.map((item) => [item.problemsetId, item]))
const badgesBySet = new Map<number, (typeof schema.problemsetBadge.$inferSelect)[]>()
for (const badge of badges) badgesBySet.set(badge.problemsetId, [...(badgesBySet.get(badge.problemsetId) ?? []), badge])
const [problemCounts, progresses, badges, earnedRows, creators] =
await Promise.all([
db
.select({
problemsetId: schema.problemsetProblem.problemsetId,
value: count(),
})
.from(schema.problemsetProblem)
.where(inArray(schema.problemsetProblem.problemsetId, ids))
.groupBy(schema.problemsetProblem.problemsetId),
userId
? db
.select()
.from(schema.problemsetProgress)
.where(
and(
inArray(schema.problemsetProgress.problemsetId, ids),
eq(schema.problemsetProgress.userId, userId),
),
)
: Promise.resolve(
[] as (typeof schema.problemsetProgress.$inferSelect)[],
),
includeBadges
? db
.select()
.from(schema.problemsetBadge)
.where(inArray(schema.problemsetBadge.problemsetId, ids))
.orderBy(asc(schema.problemsetBadge.id))
: Promise.resolve([] as (typeof schema.problemsetBadge.$inferSelect)[]),
includeBadges && userId
? db
.select({ id: schema.userBadge.badgeId })
.from(schema.userBadge)
.innerJoin(
schema.problemsetBadge,
eq(schema.userBadge.badgeId, schema.problemsetBadge.id),
)
.where(
and(
eq(schema.userBadge.userId, userId),
inArray(schema.problemsetBadge.problemsetId, ids),
),
)
: Promise.resolve([] as { id: number }[]),
problemSetCreators([...new Set(rows.map((row) => row.createdById))]),
])
const countBySet = new Map(
problemCounts.map((item) => [item.problemsetId, item.value]),
)
const progressBySet = new Map(
progresses.map((item) => [item.problemsetId, item]),
)
const badgesBySet = new Map<
number,
(typeof schema.problemsetBadge.$inferSelect)[]
>()
for (const badge of badges)
badgesBySet.set(badge.problemsetId, [
...(badgesBySet.get(badge.problemsetId) ?? []),
badge,
])
const earned = new Set(earnedRows.map((item) => item.id))
return rows.map((row) => {
const progress = progressBySet.get(row.id)
return problemSetSchema.parse({
return {
id: row.id,
title: row.title,
description: row.description,
createdBy: creators.get(row.createdById) ?? sampleUser({ id: row.createdById, username: "" }, null),
createdBy:
creators.get(row.createdById) ??
sampleUser({ id: row.createdById, username: "" }, null),
createTime: row.createTime,
lastUpdateTime: row.lastUpdateTime,
difficulty: row.difficulty,
@@ -128,36 +185,65 @@ async function serializeProblemSets(
problemsCount: countBySet.get(row.id) ?? 0,
completedCount: progress?.completedProblemsCount ?? 0,
userProgress: progressSummary(progress),
badges: includeBadges ? (badgesBySet.get(row.id) ?? []).map((badge) => badgeData(badge, earned.has(badge.id))) : undefined,
})
badges: includeBadges
? (badgesBySet.get(row.id) ?? []).map((badge) =>
badgeData(badge, earned.has(badge.id)),
)
: undefined,
} satisfies ProblemSet
})
}
problemsetRoutes.get("/problem-sets", optionalAuth, async (c) => {
const limit = queryInteger(c.req.query("limit"), 10, { min: 1, max: 250 })
const offset = queryInteger(c.req.query("offset"), 0, { min: 0 })
const filters = [eq(schema.problemset.visible, true), ne(schema.problemset.status, "draft")]
const filters = [
eq(schema.problemset.visible, true),
ne(schema.problemset.status, "draft"),
]
const keyword = c.req.query("keyword")?.trim()
const difficulty = c.req.query("difficulty")?.trim()
const status = c.req.query("status")?.trim()
if (keyword) filters.push(or(ilike(schema.problemset.title, `%${keyword}%`), ilike(schema.problemset.description, `%${keyword}%`))!)
if (difficulty) filters.push(eq(schema.problemset.difficulty, difficulty))
if (status) filters.push(eq(schema.problemset.status, status))
if (keyword)
filters.push(
or(
ilike(schema.problemset.title, `%${keyword}%`),
ilike(schema.problemset.description, `%${keyword}%`),
)!,
)
if (difficulty)
filters.push(eq(schema.problemset.difficulty, asFilterValue(difficulty)))
if (status) filters.push(eq(schema.problemset.status, asFilterValue(status)))
const where = and(...filters)
const [totalRows, rows] = await Promise.all([
db.select({ value: count() }).from(schema.problemset).where(where),
db.select().from(schema.problemset).where(where).orderBy(desc(schema.problemset.createTime)).limit(limit).offset(offset),
db
.select()
.from(schema.problemset)
.where(where)
.orderBy(desc(schema.problemset.createTime))
.limit(limit)
.offset(offset),
])
return success(c, problemSetListSchema.parse({
return success(c, {
results: await serializeProblemSets(rows, c.get("user")?.id, true),
total: totalRows[0]?.value ?? 0,
}))
} satisfies ProblemSetList)
})
problemsetRoutes.get("/problem-sets/:id", optionalAuth, async (c) => {
const id = queryInteger(c.req.param("id"), 0, { min: 1 })
const [row] = await db.select().from(schema.problemset)
.where(and(eq(schema.problemset.id, id), eq(schema.problemset.visible, true), ne(schema.problemset.status, "draft"))).limit(1)
const [row] = await db
.select()
.from(schema.problemset)
.where(
and(
eq(schema.problemset.id, id),
eq(schema.problemset.visible, true),
ne(schema.problemset.status, "draft"),
),
)
.limit(1)
if (!row) return failure(c, 404, "problem-set-not-found", "题单不存在")
const [data] = await serializeProblemSets([row], c.get("user")?.id)
return success(c, data)
@@ -165,48 +251,71 @@ problemsetRoutes.get("/problem-sets/:id", optionalAuth, async (c) => {
problemsetRoutes.get("/problem-sets/:id/problems", optionalAuth, async (c) => {
const id = queryInteger(c.req.param("id"), 0, { min: 1 })
const [problemSet] = await db.select({ id: schema.problemset.id }).from(schema.problemset)
.where(and(eq(schema.problemset.id, id), eq(schema.problemset.visible, true), ne(schema.problemset.status, "draft"))).limit(1)
const [problemSet] = await db
.select({ id: schema.problemset.id })
.from(schema.problemset)
.where(
and(
eq(schema.problemset.id, id),
eq(schema.problemset.visible, true),
ne(schema.problemset.status, "draft"),
),
)
.limit(1)
if (!problemSet) return failure(c, 404, "problem-set-not-found", "题单不存在")
const rows = await db.select({ link: schema.problemsetProblem, problem: schema.problem, user: schema.user, realName: schema.userProfile.realName })
.from(schema.problemsetProblem).innerJoin(schema.problem, eq(schema.problemsetProblem.problemId, schema.problem.id))
.innerJoin(schema.user, eq(schema.problem.createdById, schema.user.id))
.leftJoin(schema.userProfile, eq(schema.userProfile.userId, schema.user.id))
.where(eq(schema.problemsetProblem.problemsetId, id)).orderBy(asc(schema.problemsetProblem.order))
const problemIds = rows.map((row) => row.problem.id)
const [tagRows, progressRows] = await Promise.all([
problemIds.length ? db.select({ problemId: schema.problemTags.problemId, name: schema.problemTag.name }).from(schema.problemTags)
.innerJoin(schema.problemTag, eq(schema.problemTags.problemtagId, schema.problemTag.id)).where(inArray(schema.problemTags.problemId, problemIds)) : Promise.resolve([]),
c.get("user") ? db.select({ detail: schema.problemsetProgress.progressDetail }).from(schema.problemsetProgress)
.where(and(eq(schema.problemsetProgress.problemsetId, id), eq(schema.problemsetProgress.userId, c.get("user")!.id))).limit(1) : Promise.resolve([]),
])
const tags = new Map<number, string[]>()
for (const tag of tagRows) tags.set(tag.problemId, [...(tags.get(tag.problemId) ?? []), tag.name])
// 只取卡片要渲染的四列。取 schema.problem 整行会把题面、样例、答案、ast_rules、
// flowchart_data、sql_display 一起拉回来,题单页一个都不用。
//
// order 后面必须再跟一个 tiebreaker:并列时 Postgres 不保证次序,而卡片是按数组
// 下标编号的(#1 #2 #3),题单 8 / 11 / 14 实际就存在 order 重复,不定死的话
// 「第 3 题」指哪道题每次刷新都可能不一样。后台那条列表一直是这么排的。
const rows = await db
.select({
link: schema.problemsetProblem,
problemId: schema.problem.id,
displayId: schema.problem.displayId,
title: schema.problem.title,
difficulty: schema.problem.difficulty,
})
.from(schema.problemsetProblem)
.innerJoin(
schema.problem,
eq(schema.problemsetProblem.problemId, schema.problem.id),
)
.where(eq(schema.problemsetProblem.problemsetId, id))
.orderBy(
asc(schema.problemsetProblem.order),
asc(schema.problemsetProblem.id),
)
const progressRows = c.get("user")
? await db
.select({ detail: schema.problemsetProgress.progressDetail })
.from(schema.problemsetProgress)
.where(
and(
eq(schema.problemsetProgress.problemsetId, id),
eq(schema.problemsetProgress.userId, c.get("user")!.id),
),
)
.limit(1)
: []
const completed = objectValue(progressRows[0]?.detail)
return success(c, rows.map(({ link, problem, user, realName }) => problemSetProblemSchema.parse({
id: link.id,
problemsetId: link.problemsetId,
problem: problemListItemSchema.parse({
id: problem.id,
_id: problem.displayId,
title: problem.title,
submissionNumber: problem.submissionNumber,
acceptedNumber: problem.acceptedNumber,
difficulty: problem.difficulty,
createdBy: sampleUser(user, realName),
tags: tags.get(problem.id) ?? [],
contestId: problem.contestId,
allowFlowchart: problem.allowFlowchart,
showFlowchart: problem.showFlowchart,
hasAstRules: problem.astRules !== null,
myStatus: null,
}),
order: link.order,
isRequired: link.isRequired,
score: link.score,
hint: link.hint,
isCompleted: String(problem.id) in completed,
})))
return success(
c,
rows.map(
({ link, problemId, displayId, title, difficulty }) =>
({
id: link.id,
problemsetId: link.problemsetId,
problem: { id: problemId, _id: displayId, title, difficulty },
order: link.order,
isRequired: link.isRequired,
score: link.score,
hint: link.hint,
isCompleted: String(problemId) in completed,
}) satisfies ProblemSetProblem,
),
)
})
async function recomputeProgress(
@@ -214,226 +323,278 @@ async function recomputeProgress(
progress: typeof schema.problemsetProgress.$inferSelect,
detail: Record<string, unknown>,
) {
const links = await tx.select({ problemId: schema.problemsetProblem.problemId, score: schema.problemsetProblem.score })
.from(schema.problemsetProblem).where(eq(schema.problemsetProblem.problemsetId, progress.problemsetId))
const valid = new Map(links.map((link) => [String(link.problemId), link.score]))
for (const key of Object.keys(detail)) if (!valid.has(key)) delete detail[key]
let totalScore = 0
for (const [key, value] of Object.entries(detail)) {
const score = valid.get(key)
if (score === undefined) continue
totalScore += score
detail[key] = { ...objectValue(value), score }
}
const completed = Object.keys(detail).length
const total = links.length
const isCompleted = completed === total
const update = {
progressDetail: detail,
totalProblemsCount: total,
completedProblemsCount: completed,
totalScore,
progressPercentage: total > 0 ? completed / total * 100 : 0,
isCompleted,
completeTime: isCompleted ? progress.completeTime ?? new Date().toISOString() : null,
}
await tx.update(schema.problemsetProgress).set(update).where(eq(schema.problemsetProgress.id, progress.id))
const links = await tx
.select({
problemId: schema.problemsetProblem.problemId,
score: schema.problemsetProblem.score,
isRequired: schema.problemsetProblem.isRequired,
})
.from(schema.problemsetProblem)
.where(eq(schema.problemsetProblem.problemsetId, progress.problemsetId))
// 算法本身在 services/problemset.ts —— 后台改题目后的批量重算走的是同一份,
// 两边曾经各写一遍,结果后台那份少算了 total_score 和 is_completed
const update = computeProgress(detail, links, progress.completeTime)
await tx
.update(schema.problemsetProgress)
.set(update)
.where(eq(schema.problemsetProgress.id, progress.id))
return { ...progress, ...update }
}
problemsetRoutes.post("/problem-set-progress", requireAuth, async (c) => {
const parsed = joinProblemSetRequestSchema.safeParse(await c.req.json().catch(() => null))
if (!parsed.success) return failure(c, 400, "invalid-request", "Invalid problem set")
const parsed = joinProblemSetRequestSchema.safeParse(
await c.req.json().catch(() => null),
)
if (!parsed.success)
return failure(c, 400, "invalid-request", "Invalid problem set")
const user = c.get("user")!
const [problemSet] = await db.select({ id: schema.problemset.id }).from(schema.problemset)
.where(and(eq(schema.problemset.id, parsed.data.problemSetId), eq(schema.problemset.visible, true), ne(schema.problemset.status, "draft"))).limit(1)
const [problemSet] = await db
.select({ id: schema.problemset.id })
.from(schema.problemset)
.where(
and(
eq(schema.problemset.id, parsed.data.problemSetId),
eq(schema.problemset.visible, true),
ne(schema.problemset.status, "draft"),
),
)
.limit(1)
if (!problemSet) return failure(c, 404, "problem-set-not-found", "题单不存在")
const [existing] = await db.select({ id: schema.problemsetProgress.id }).from(schema.problemsetProgress)
.where(and(eq(schema.problemsetProgress.problemsetId, problemSet.id), eq(schema.problemsetProgress.userId, user.id))).limit(1)
const [existing] = await db
.select({ id: schema.problemsetProgress.id })
.from(schema.problemsetProgress)
.where(
and(
eq(schema.problemsetProgress.problemsetId, problemSet.id),
eq(schema.problemsetProgress.userId, user.id),
),
)
.limit(1)
if (existing) return failure(c, 409, "already-joined", "已经加入该题单")
await db.transaction(async (tx) => {
const [created] = await tx.insert(schema.problemsetProgress).values({
problemsetId: problemSet.id,
userId: user.id,
joinTime: new Date().toISOString(),
completeTime: null,
isCompleted: false,
progressPercentage: 0,
completedProblemsCount: 0,
totalProblemsCount: 0,
totalScore: 0,
progressDetail: {},
}).returning()
const [created] = await tx
.insert(schema.problemsetProgress)
.values({
problemsetId: problemSet.id,
userId: user.id,
joinTime: new Date().toISOString(),
completeTime: null,
isCompleted: false,
progressPercentage: 0,
completedProblemsCount: 0,
totalProblemsCount: 0,
totalScore: 0,
progressDetail: {},
})
.returning()
if (created) await recomputeProgress(tx, created, {})
})
return success(c, null, 201)
})
problemsetRoutes.put("/problem-set-progress", requireAuth, async (c) => {
const parsed = updateProblemSetProgressRequestSchema.safeParse(await c.req.json().catch(() => null))
if (!parsed.success) return failure(c, 400, "invalid-request", "Invalid progress payload")
const user = c.get("user")!
const result = await db.transaction(async (tx) => {
const [problemSet] = await tx.select().from(schema.problemset).where(and(
eq(schema.problemset.id, parsed.data.problemSetId), eq(schema.problemset.visible, true), ne(schema.problemset.status, "draft"),
)).limit(1)
if (!problemSet) return { error: "problem-set-not-found" as const }
const [progress] = await tx.select().from(schema.problemsetProgress).where(and(
eq(schema.problemsetProgress.problemsetId, problemSet.id), eq(schema.problemsetProgress.userId, user.id),
)).for("update").limit(1)
if (!progress) return { error: "not-joined" as const }
const [submission] = await tx.select().from(schema.submission).where(and(
eq(schema.submission.id, parsed.data.submissionId), eq(schema.submission.userId, user.id), eq(schema.submission.problemId, parsed.data.problemId),
)).limit(1)
if (!submission) return { error: "submission-not-found" as const }
if (![JudgeStatus.ACCEPTED, JudgeStatus.AST_CHECK_FAILED].includes(submission.result as 0 | 10)) return { error: "submission-not-accepted" as const }
const [link] = await tx.select().from(schema.problemsetProblem).where(and(
eq(schema.problemsetProblem.problemsetId, problemSet.id), eq(schema.problemsetProblem.problemId, parsed.data.problemId),
)).limit(1)
if (!link) return { error: "problem-not-in-set" as const }
const detail = objectValue(progress.progressDetail)
detail[String(parsed.data.problemId)] = { score: link.score, submit_time: new Date().toISOString() }
const updated = await recomputeProgress(tx, progress, detail)
const [existingSubmission] = await tx.select({ id: schema.problemsetSubmission.id })
.from(schema.problemsetSubmission).where(and(
eq(schema.problemsetSubmission.problemsetId, problemSet.id),
eq(schema.problemsetSubmission.userId, user.id),
eq(schema.problemsetSubmission.problemId, parsed.data.problemId),
)).limit(1)
if (!existingSubmission) {
await tx.insert(schema.problemsetSubmission).values({
problemsetId: problemSet.id,
userId: user.id,
submissionId: submission.id,
problemId: parsed.data.problemId,
})
}
const badges = await tx.select().from(schema.problemsetBadge).where(eq(schema.problemsetBadge.problemsetId, problemSet.id))
const hits = badges.filter((badge) => badge.conditionType === "all_problems"
? updated.totalProblemsCount > 0 && updated.completedProblemsCount === updated.totalProblemsCount
: badge.conditionType === "problem_count"
? updated.completedProblemsCount >= badge.conditionValue
: badge.conditionType === "score" && updated.totalScore >= badge.conditionValue)
if (hits.length === 0) return { earned: [] as (typeof schema.problemsetBadge.$inferSelect)[] }
// 达标的奖章一次插完,冲突忽略后 returning 回来的就是这次真拿到的
const inserted = await tx.insert(schema.userBadge).values(hits.map((badge) => ({
userId: user.id,
badgeId: badge.id,
earnedTime: new Date().toISOString(),
}))).onConflictDoNothing({ target: [schema.userBadge.badgeId, schema.userBadge.userId] })
.returning({ badgeId: schema.userBadge.badgeId })
const insertedIds = new Set(inserted.map((row) => row.badgeId))
return { earned: hits.filter((badge) => insertedIds.has(badge.id)) }
})
if ("error" in result && result.error) {
const error = result.error
const messages = {
"problem-set-not-found": "题单不存在",
"not-joined": "未加入该题单",
"submission-not-found": "提交记录不存在",
"submission-not-accepted": "只有通过的提交才能更新进度",
"problem-not-in-set": "题目不在题单中",
}
return failure(c, error.endsWith("not-found") ? 404 : 400, error, messages[error])
}
const unlocked = await updateAchievementsForProblemSet(user.id)
await Promise.all([
publishAchievementNotification(user.id, result.earned.map((badge) => ({
id: badge.id,
name: badge.name,
description: badge.description,
icon: badge.icon,
rarity: "bronze",
kind: "badge",
}))),
publishAchievementNotification(user.id, unlocked.map((achievement) => ({
id: achievement.id,
name: achievement.name,
description: achievement.description,
icon: achievement.icon,
rarity: achievement.rarity,
kind: "achievement",
}))),
])
return success(c, { earnedBadges: result.earned.map((badge) => badgeData(badge)) })
})
problemsetRoutes.get("/users/:username/badges", optionalAuth, async (c) => {
const requested = c.req.param("username")
const username = requested === "me" ? c.get("user")?.username : requested
if (!username) return failure(c, 401, "login-required", "Authentication required")
const [target] = await db.select({ id: schema.user.id }).from(schema.user)
.where(and(eq(schema.user.username, username), eq(schema.user.isDisabled, false))).limit(1)
if (!username)
return failure(c, 401, "login-required", "Authentication required")
const [target] = await db
.select({ id: schema.user.id })
.from(schema.user)
.where(
and(
eq(schema.user.username, username),
eq(schema.user.isDisabled, false),
),
)
.limit(1)
if (!target) return failure(c, 404, "user-not-found", "用户不存在")
const rows = await db.select({ userBadge: schema.userBadge, badge: schema.problemsetBadge, problemSet: schema.problemset })
.from(schema.userBadge).innerJoin(schema.problemsetBadge, eq(schema.userBadge.badgeId, schema.problemsetBadge.id))
.innerJoin(schema.problemset, eq(schema.problemsetBadge.problemsetId, schema.problemset.id))
.where(eq(schema.userBadge.userId, target.id)).orderBy(desc(schema.userBadge.earnedTime))
return success(c, rows.map(({ userBadge, badge, problemSet }) => userBadgeSchema.parse({
id: userBadge.id,
userId: userBadge.userId,
badge: badgeData(badge),
earnedTime: userBadge.earnedTime,
problemset: { id: problemSet.id, title: problemSet.title },
})))
const rows = await db
.select({
userBadge: schema.userBadge,
badge: schema.problemsetBadge,
problemSet: schema.problemset,
})
.from(schema.userBadge)
.innerJoin(
schema.problemsetBadge,
eq(schema.userBadge.badgeId, schema.problemsetBadge.id),
)
.innerJoin(
schema.problemset,
eq(schema.problemsetBadge.problemsetId, schema.problemset.id),
)
.where(eq(schema.userBadge.userId, target.id))
.orderBy(desc(schema.userBadge.earnedTime))
return success(
c,
rows.map(
({ userBadge, badge, problemSet }) =>
({
id: userBadge.id,
userId: userBadge.userId,
badge: badgeData(badge),
earnedTime: userBadge.earnedTime,
problemset: { id: problemSet.id, title: problemSet.title },
}) satisfies UserBadge,
),
)
})
problemsetRoutes.get("/problem-sets/:id/badges", async (c) => {
const id = queryInteger(c.req.param("id"), 0, { min: 1 })
const [problemSet] = await db.select({ id: schema.problemset.id }).from(schema.problemset).where(and(
eq(schema.problemset.id, id), eq(schema.problemset.visible, true), ne(schema.problemset.status, "draft"),
)).limit(1)
const [problemSet] = await db
.select({ id: schema.problemset.id })
.from(schema.problemset)
.where(
and(
eq(schema.problemset.id, id),
eq(schema.problemset.visible, true),
ne(schema.problemset.status, "draft"),
),
)
.limit(1)
if (!problemSet) return failure(c, 404, "problem-set-not-found", "题单不存在")
const badges = await db.select().from(schema.problemsetBadge).where(eq(schema.problemsetBadge.problemsetId, id))
return success(c, badges.map((badge) => badgeData(badge)))
const badges = await db
.select()
.from(schema.problemsetBadge)
.where(eq(schema.problemsetBadge.problemsetId, id))
return success(
c,
badges.map((badge) => badgeData(badge)),
)
})
problemsetRoutes.get("/problem-sets/:id/user-progress", requireTeacher, async (c) => {
const id = queryInteger(c.req.param("id"), 0, { min: 1 })
const [problemSet] = await db.select({ id: schema.problemset.id }).from(schema.problemset).where(and(
eq(schema.problemset.id, id), eq(schema.problemset.visible, true), ne(schema.problemset.status, "draft"),
)).limit(1)
if (!problemSet) return failure(c, 404, "problem-set-not-found", "题单不存在")
const limit = queryInteger(c.req.query("limit"), 10, { min: 1, max: 250 })
const offset = queryInteger(c.req.query("offset"), 0, { min: 0 })
const className = c.req.query("className")?.trim()
const completion = c.req.query("completionStatus")?.trim()
const filters = [eq(schema.problemsetProgress.problemsetId, id)]
if (className) filters.push(ilike(schema.user.username, `%${className}%`))
if (completion === "completed") filters.push(eq(schema.problemsetProgress.isCompleted, true))
else if (completion === "in_progress") filters.push(and(eq(schema.problemsetProgress.isCompleted, false), gt(schema.problemsetProgress.completedProblemsCount, 0))!)
else if (completion === "not_started") filters.push(eq(schema.problemsetProgress.completedProblemsCount, 0))
const where = and(...filters)
const [statsRows, rows, problemRows] = await Promise.all([
db.select({ total: count(), completed: sql<number>`count(*) filter (where ${schema.problemsetProgress.isCompleted})::int`, avgProgress: avg(schema.problemsetProgress.progressPercentage) })
.from(schema.problemsetProgress).innerJoin(schema.user, eq(schema.problemsetProgress.userId, schema.user.id)).where(where),
db.select({ progress: schema.problemsetProgress, user: schema.user, realName: schema.userProfile.realName })
.from(schema.problemsetProgress).innerJoin(schema.user, eq(schema.problemsetProgress.userId, schema.user.id))
.leftJoin(schema.userProfile, eq(schema.userProfile.userId, schema.user.id)).where(where)
.orderBy(desc(schema.problemsetProgress.isCompleted), desc(schema.problemsetProgress.progressPercentage), asc(schema.problemsetProgress.joinTime)).limit(limit).offset(offset),
db.select({ id: schema.problem.id, _id: schema.problem.displayId, title: schema.problem.title }).from(schema.problemsetProblem)
.innerJoin(schema.problem, eq(schema.problemsetProblem.problemId, schema.problem.id))
.where(eq(schema.problemsetProblem.problemsetId, id)).orderBy(asc(schema.problemsetProblem.order)),
])
const problemMap = new Map(problemRows.map((problem) => [String(problem.id), problem]))
const results = rows.map(({ progress, user: progressUser, realName }) => problemSetProgressSchema.parse({
id: progress.id,
problemsetId: progress.problemsetId,
user: sampleUser(progressUser, realName),
joinTime: progress.joinTime,
completeTime: progress.completeTime,
isCompleted: progress.isCompleted,
progressPercentage: progress.progressPercentage,
completedProblemsCount: progress.completedProblemsCount,
totalProblemsCount: progress.totalProblemsCount,
totalScore: progress.totalScore,
completedProblems: Object.keys(objectValue(progress.progressDetail)).flatMap((key) => problemMap.get(key) ?? []),
}))
const stats = statsRows[0]
return success(c, problemSetProgressListSchema.parse({
results,
total: stats?.total ?? 0,
statistics: { total: stats?.total ?? 0, completed: stats?.completed ?? 0, avgProgress: Number(stats?.avgProgress ?? 0) },
problems: problemRows,
}))
})
problemsetRoutes.get(
"/problem-sets/:id/user-progress",
requireTeacher,
async (c) => {
const id = queryInteger(c.req.param("id"), 0, { min: 1 })
const [problemSet] = await db
.select({
id: schema.problemset.id,
createdById: schema.problemset.createdById,
})
.from(schema.problemset)
.where(
and(
eq(schema.problemset.id, id),
eq(schema.problemset.visible, true),
ne(schema.problemset.status, "draft"),
),
)
.limit(1)
// 归属校验,和后台那条同类接口(admin/problemset.ts 的 loadOwned)一致:超管放行,
// 其余老师只能看自己建的题单。少了这一道,任何 Teacher Admin 都能读到别人班的名单。
// 越权报「不存在」,不泄露题单存在与否。
const user = c.get("user")!
if (
!problemSet ||
(user.adminType !== "Super Admin" && problemSet.createdById !== user.id)
) {
return failure(c, 404, "problem-set-not-found", "题单不存在")
}
const limit = queryInteger(c.req.query("limit"), 10, { min: 1, max: 250 })
const offset = queryInteger(c.req.query("offset"), 0, { min: 0 })
const className = c.req.query("className")?.trim()
const completion = c.req.query("completionStatus")?.trim()
const filters = [eq(schema.problemsetProgress.problemsetId, id)]
if (className) filters.push(ilike(schema.user.username, `%${className}%`))
if (completion === "completed")
filters.push(eq(schema.problemsetProgress.isCompleted, true))
else if (completion === "in_progress")
filters.push(
and(
eq(schema.problemsetProgress.isCompleted, false),
gt(schema.problemsetProgress.completedProblemsCount, 0),
)!,
)
else if (completion === "not_started")
filters.push(eq(schema.problemsetProgress.completedProblemsCount, 0))
const where = and(...filters)
const [statsRows, rows, problemRows] = await Promise.all([
db
.select({
total: count(),
completed: sql<number>`count(*) filter (where ${schema.problemsetProgress.isCompleted})::int`,
avgProgress: avg(schema.problemsetProgress.progressPercentage),
})
.from(schema.problemsetProgress)
.innerJoin(
schema.user,
eq(schema.problemsetProgress.userId, schema.user.id),
)
.where(where),
db
.select({
progress: schema.problemsetProgress,
user: schema.user,
realName: schema.userProfile.realName,
})
.from(schema.problemsetProgress)
.innerJoin(
schema.user,
eq(schema.problemsetProgress.userId, schema.user.id),
)
.leftJoin(
schema.userProfile,
eq(schema.userProfile.userId, schema.user.id),
)
.where(where)
.orderBy(
desc(schema.problemsetProgress.isCompleted),
desc(schema.problemsetProgress.progressPercentage),
asc(schema.problemsetProgress.joinTime),
)
.limit(limit)
.offset(offset),
db
.select({
id: schema.problem.id,
_id: schema.problem.displayId,
title: schema.problem.title,
})
.from(schema.problemsetProblem)
.innerJoin(
schema.problem,
eq(schema.problemsetProblem.problemId, schema.problem.id),
)
.where(eq(schema.problemsetProblem.problemsetId, id))
.orderBy(
asc(schema.problemsetProblem.order),
asc(schema.problemsetProblem.id),
),
])
const problemMap = new Map(
problemRows.map((problem) => [String(problem.id), problem]),
)
const results = rows.map(
({ progress, user: progressUser, realName }) =>
({
id: progress.id,
problemsetId: progress.problemsetId,
user: sampleUser(progressUser, realName),
joinTime: progress.joinTime,
completeTime: progress.completeTime,
isCompleted: progress.isCompleted,
progressPercentage: progress.progressPercentage,
completedProblemsCount: progress.completedProblemsCount,
totalProblemsCount: progress.totalProblemsCount,
totalScore: progress.totalScore,
completedProblems: Object.keys(
objectValue(progress.progressDetail),
).flatMap((key) => problemMap.get(key) ?? []),
}) satisfies ProblemSetProgress,
)
const stats = statsRows[0]
return success(c, {
results,
total: stats?.total ?? 0,
statistics: {
total: stats?.total ?? 0,
completed: stats?.completed ?? 0,
avgProgress: Number(stats?.avgProgress ?? 0),
},
problems: problemRows,
} satisfies ProblemSetProgressList)
},
)
+43 -18
View File
@@ -1,8 +1,9 @@
import { quoteSchema, websiteConfigSchema } from "@oj2/contract"
import type { OnlineCount, Quote, WebsiteConfig } from "@oj2/contract"
import { asc, desc, eq } from "drizzle-orm"
import { Hono } from "hono"
import { resolve } from "node:path"
import { onlineCount } from "../auth/presence"
import { config } from "../config"
import { db, schema } from "../db"
import { failure, success } from "../http"
@@ -13,7 +14,7 @@ export const siteRoutes = new Hono()
siteRoutes.get("/site", async (c) => {
const options = await getWebsiteOptions()
return success(c, websiteConfigSchema.parse({
return success(c, {
websiteBaseUrl: options.website_base_url,
websiteName: options.website_name,
websiteNameShortcut: options.website_name_shortcut,
@@ -22,12 +23,23 @@ siteRoutes.get("/site", async (c) => {
submissionListShowAll: options.submission_list_show_all,
classList: options.class_list,
enableMaxkb: options.enable_maxkb,
}))
} satisfies WebsiteConfig)
})
/**
* 线
* 线 /rankings/users
*/
siteRoutes.get("/site/online", async (c) => {
return success(c, { count: await onlineCount() } satisfies OnlineCount)
})
// 数据集读不到时的兜底(本机 dev 没挂 data/hitokoto 就会走这里)
const fallbackQuotes = [
{ hitokoto: "程序首先是写给人读的,其次才是让机器执行。", from: "Structure and Interpretation of Computer Programs" },
{
hitokoto: "程序首先是写给人读的,其次才是让机器执行。",
from: "Structure and Interpretation of Computer Programs",
},
{ hitokoto: "把大问题拆成足够小的问题,答案就会浮现。", from: "判题狗" },
{ hitokoto: "一次没通过,只是多得到了一条线索。", from: "判题狗" },
]
@@ -38,18 +50,18 @@ const fallbackQuotes = [
let categoryPaths: string[] | null = null
const sentenceCache = new Map<string, Quote[]>()
interface Quote {
hitokoto: string
from: string
}
async function loadSentences(path: string) {
const cached = sentenceCache.get(path)
if (cached) return cached
const raw = await Bun.file(resolve(config.hitokotoDirectory, path)).json() as { hitokoto?: unknown, from?: unknown }[]
const raw = (await Bun.file(
resolve(config.hitokotoDirectory, path),
).json()) as { hitokoto?: unknown; from?: unknown }[]
const rows = (Array.isArray(raw) ? raw : [])
.filter((it) => typeof it.hitokoto === "string" && it.hitokoto.length > 0)
.map((it) => ({ hitokoto: it.hitokoto as string, from: typeof it.from === "string" ? it.from : "佚名" }))
.map((it) => ({
hitokoto: it.hitokoto as string,
from: typeof it.from === "string" ? it.from : "佚名",
}))
if (rows.length === 0) throw new Error(`empty hitokoto category: ${path}`)
sentenceCache.set(path, rows)
return rows
@@ -57,8 +69,12 @@ async function loadSentences(path: string) {
async function randomQuote() {
if (!categoryPaths) {
const categories = await Bun.file(resolve(config.hitokotoDirectory, "categories.json")).json() as { path?: string }[]
const paths = categories.map((it) => it.path).filter((it): it is string => typeof it === "string")
const categories = (await Bun.file(
resolve(config.hitokotoDirectory, "categories.json"),
).json()) as { path?: string }[]
const paths = categories
.map((it) => it.path)
.filter((it): it is string => typeof it === "string")
if (paths.length === 0) throw new Error("no hitokoto categories")
categoryPaths = paths
}
@@ -69,17 +85,23 @@ async function randomQuote() {
siteRoutes.get("/quotes/random", async (c) => {
try {
return success(c, quoteSchema.parse(await randomQuote()))
return success(c, (await randomQuote()) satisfies Quote)
} catch {
const item = fallbackQuotes[Math.floor(Math.random() * fallbackQuotes.length)]!
return success(c, quoteSchema.parse(item))
const item =
fallbackQuotes[Math.floor(Math.random() * fallbackQuotes.length)]!
return success(c, item satisfies Quote)
}
})
siteRoutes.get("/classes/:className/usernames", async (c) => {
const className = c.req.param("className").trim()
if (!/^\d{3,4}$/.test(className)) {
return failure(c, 400, "invalid-class", "Class name must contain 3 or 4 digits")
return failure(
c,
400,
"invalid-class",
"Class name must contain 3 or 4 digits",
)
}
const rows = await db
.select({ username: schema.user.username })
@@ -87,5 +109,8 @@ siteRoutes.get("/classes/:className/usernames", async (c) => {
.where(eq(schema.user.className, className))
.orderBy(desc(schema.user.createTime), asc(schema.user.id))
// 用 stripClassPrefix 而不是 replacereplace 会把中间的匹配也删掉,前缀对不上时截出乱码
return success(c, rows.map(({ username }) => stripClassPrefix(username, className)))
return success(
c,
rows.map(({ username }) => stripClassPrefix(username, className)),
)
})
@@ -0,0 +1,704 @@
/**
* /
*
* submission.ts ****submission.ts
* `route("/", submissionStatisticsRoutes)` `/submissions/:id`
* `/submissions/statistics` id Hono
*/
import {
type SubmissionStatistics,
type SubmissionStatisticsItems,
type TodaySubmissionStatistics,
} from "@oj2/contract"
import {
and,
count,
desc,
eq,
ilike,
inArray,
isNull,
or,
sql,
type SQL,
} from "drizzle-orm"
import { Hono } from "hono"
import { optionalAuth, requireTeacher } from "../auth/middleware"
import type { AuthUser } from "../auth/session"
import { db, schema } from "../db"
import { failure, success } from "../http"
import {
JudgeStatus,
UNJUDGED_RESULTS,
type JudgeStatusValue,
} from "../judge/status"
import { type ContestEnv } from "../services/contest"
import { getBooleanOption } from "../services/options"
import { localTime, todayStart } from "../time"
import { isAdminRole, matchedUsers, rounded, stripClassPrefix } from "./helpers"
export const submissionStatisticsRoutes = new Hono<ContestEnv>()
const ACCEPTED_RESULTS = [JudgeStatus.ACCEPTED, JudgeStatus.AST_CHECK_FAILED]
/** 正确率。分母是判完的条数,一条都还没判完时给 0 而不是 NaN */
function judgedRate(accepted: number, judged: number) {
return judged > 0 ? rounded((accepted / judged) * 100) : 0
}
/**
* ****
* +
*
* `localTime()` `extract(hour from create_time)`
* UTC 8
*/
submissionStatisticsRoutes.get(
"/submissions/today-statistics",
optionalAuth,
async (c) => {
/**
*
* today-count
* 21 0
*/
const showProblems =
(await getBooleanOption("submission_list_show_all", true)) ||
isAdminRole(c.get("user"))
const where = and(
isNull(schema.submission.contestId),
sql`${schema.submission.createTime} >= ${todayStart()}`,
)
const acceptedFilter = sql`count(*) filter (where ${inArray(schema.submission.result, ACCEPTED_RESULTS)})`
const judgingFilter = sql`count(*) filter (where ${inArray(schema.submission.result, UNJUDGED_RESULTS)})`
const hour = sql<number>`extract(hour from ${localTime(schema.submission.createTime)})::int`
const [[totals], hourRows, languageRows, resultRows, problemRows] =
await Promise.all([
db
.select({
total: count(),
accepted: acceptedFilter.mapWith(Number),
judging: judgingFilter.mapWith(Number),
userCount:
sql<number>`count(distinct ${schema.submission.userId})`.mapWith(
Number,
),
})
.from(schema.submission)
.where(where),
db
.select({ hour, value: count() })
.from(schema.submission)
.where(where)
.groupBy(hour),
db
.select({ language: schema.submission.language, value: count() })
.from(schema.submission)
.where(where)
.groupBy(schema.submission.language)
.orderBy(desc(count())),
db
.select({ result: schema.submission.result, value: count() })
.from(schema.submission)
.where(where)
.groupBy(schema.submission.result)
.orderBy(desc(count())),
showProblems
? db
.select({
displayId: schema.problem.displayId,
title: schema.problem.title,
value: count(),
accepted: acceptedFilter.mapWith(Number),
})
.from(schema.submission)
.innerJoin(
schema.problem,
eq(schema.problem.id, schema.submission.problemId),
)
// 隐藏题目不出现在这张表里:接口不需要登录,标题本身就是不该外露的东西
.where(and(where, eq(schema.problem.visible, true)))
.groupBy(
schema.problem.id,
schema.problem.displayId,
schema.problem.title,
)
.orderBy(desc(count()))
.limit(10)
: [],
])
const total = totals?.total ?? 0
const judging = totals?.judging ?? 0
const hours = Array.from({ length: 24 }, () => 0)
for (const row of hourRows) hours[row.hour] = row.value
return success(c, {
total,
accepted: totals?.accepted ?? 0,
judging,
correctRate: judgedRate(totals?.accepted ?? 0, total - judging),
userCount: totals?.userCount ?? 0,
hours,
languages: languageRows.map((row) => ({
language: row.language,
count: row.value,
})),
results: resultRows.map((row) => ({
result: row.result,
count: row.value,
})),
problems: problemRows.map((row) => ({
problem: row.displayId,
problemTitle: row.title,
count: row.value,
acceptedCount: row.accepted,
})),
} satisfies TodaySubmissionStatistics)
},
)
/**
* `end` `start`
*/
function statisticsRange(c: {
req: { query(name: string): string | undefined }
}) {
const end = c.req.query("end")?.trim()
if (!end) return null
const start = c.req.query("start")?.trim()
return { start: start || null, end }
}
/** 一次最多查几道题。课堂上一节课布置三五道,20 是留足了余量的上限 */
const STATISTICS_MAX_PROBLEMS = 20
/**
* `1001,1005,1010`
*
*/
function parseDisplayIds(raw: string) {
const seen = new Set<string>()
const ids: string[] = []
for (const part of raw.split(/[,;\s]+/)) {
const id = part.trim()
if (!id) continue
const key = id.toLowerCase()
if (seen.has(key)) continue
seen.add(key)
ids.push(id)
}
return ids
}
/**
* _id****退
*
*/
async function findPublicProblemsByDisplayIds(displayIds: string[]) {
const lowered = displayIds.map((id) => id.toLowerCase())
const rows = await db
.select({ id: schema.problem.id, displayId: schema.problem.displayId })
.from(schema.problem)
.where(
and(
inArray(sql`lower(${schema.problem.displayId})`, lowered),
isNull(schema.problem.contestId),
eq(schema.problem.visible, true),
),
)
const found = new Set(rows.map((row) => row.displayId.toLowerCase()))
const missing = displayIds.find((id) => !found.has(id.toLowerCase()))
return { ids: rows.map((row) => row.id), missing: missing ?? null }
}
/**
* updateExpandedRowKeys key
* ****
*
* data +
* 49108 105631
*/
const STATISTICS_ITEMS_LIMIT = 200
/** 错误摘要截断长度。编译错误能刷几十行,弹层里放不下,也没必要 */
const FAILURE_MESSAGE_LIMIT = 400
/**
* ****
*
* 12
* err_info
* statistic_info
*/
async function lastFailureByUser(where: SQL | undefined, userIds: number[]) {
// result 手写成 JudgeStatusValue:这条裸 SQL 读的就是 submission.result 那一列,
// 口径要和列上的 $type 一致
const byUser = new Map<
number,
{
id: string
problem: string
result: JudgeStatusValue
error: string | null
}
>()
if (!userIds.length) return byUser
// 不给 submission 起别名:where 里的条件是 drizzle 拼的,引用的是 "submission"."x"
const rows = await db.execute<{
user_id: number
id: string
problem: string
result: JudgeStatusValue
error: string | null
}>(sql`
select user_id, id, problem, result, error from (
select
${schema.submission.userId} as user_id,
${schema.submission.id} as id,
${schema.problem.displayId} as problem,
${schema.submission.result} as result,
left(${schema.submission.statisticInfo}->>'err_info', ${FAILURE_MESSAGE_LIMIT}) as error,
row_number() over (
partition by ${schema.submission.userId}
order by ${schema.submission.createTime} desc
) as rn
from ${schema.submission}
join ${schema.problem} on ${schema.problem.id} = ${schema.submission.problemId}
where ${and(where, inArray(schema.submission.userId, userIds))}
) t
where rn = 1
`)
for (const row of rows) {
byUser.set(row.user_id, {
id: row.id,
problem: row.problem,
result: row.result,
error: row.error,
})
}
return byUser
}
/**
* AST_CHECK_FAILED
*
* **** AST_CHECK_FAILED ACCEPTED
* ×
* `count(distinct problem_id) filter (result = 10)`
*
* AST_CHECK_FAILED
*
*/
async function astOnlyByUser(where: SQL | undefined, userIds: number[]) {
const byUser = new Map<number, number>()
if (!userIds.length) return byUser
const rows = await db.execute<{ user_id: number; n: number }>(sql`
select user_id, count(*)::int as n from (
select
${schema.submission.userId} as user_id,
bool_or(${schema.submission.result} = ${JudgeStatus.AST_CHECK_FAILED}) as has_ast,
bool_or(${schema.submission.result} = ${JudgeStatus.ACCEPTED}) as has_ac
from ${schema.submission}
where ${and(where, inArray(schema.submission.userId, userIds))}
group by ${schema.submission.userId}, ${schema.submission.problemId}
) t
where has_ast and not has_ac
group by user_id
`)
for (const row of rows) byUser.set(row.user_id, row.n)
return byUser
}
/**
* ****
*
* - `user_id in (改过名的当前用户名匹配到的账号)`
* `ks248` 685
*
* - `submission.username ilike` `user`
*
*
* user_id
*
*
* ** id ** `user_id in (子查询)` OR
* hashed SubPlan OR trigram
* submission_public_metrics_idx + submission_public_username_trgm_idx
* count 65ms 0.6ms`ks2` 退30~50ms
*
*/
export async function usernameFilter(username: string) {
const like = `%${username}%`
const users = await db
.select({ id: schema.user.id })
.from(schema.user)
.where(ilike(schema.user.username, like))
const frozen = ilike(schema.submission.username, like)
return users.length
? or(
inArray(
schema.submission.userId,
users.map((row) => row.id),
),
frozen,
)!
: frozen
}
/**
* problem.id `submission.problem_id`
* join problem `lower(problem._id)` problem
* submission_public_problem_time_idx
*
* `_id`
* 0
* filter
*/
export async function problemFilter(
displayId: string,
contestId: number | null,
) {
const problems = await db
.select({ id: schema.problem.id })
.from(schema.problem)
.where(
and(
sql`lower(${schema.problem.displayId}) = lower(${displayId})`,
contestId === null
? isNull(schema.problem.contestId)
: eq(schema.problem.contestId, contestId),
),
)
return problems.length
? inArray(
schema.submission.problemId,
problems.map((row) => row.id),
)
: sql`false`
}
/**
* + ****
* ilike ks251
* `user` user_id user_id
*/
type StatisticsScope =
| { ok: true; filters: SQL[]; problemCount: number }
| { ok: false; status: 400 | 404; code: string; message: string }
async function statisticsScope(c: {
req: { query(name: string): string | undefined }
}): Promise<StatisticsScope> {
const range = statisticsRange(c)
if (!range) {
return {
ok: false,
status: 400,
code: "invalid-request",
message: "end is required",
}
}
const filters = [
isNull(schema.submission.contestId),
sql`${schema.submission.createTime} <= ${range.end}`,
]
if (range.start)
filters.push(sql`${schema.submission.createTime} >= ${range.start}`)
const displayIds = parseDisplayIds(c.req.query("problemId") ?? "")
if (displayIds.length > STATISTICS_MAX_PROBLEMS) {
return {
ok: false,
status: 400,
code: "invalid-request",
message: `At most ${STATISTICS_MAX_PROBLEMS} problems`,
}
}
if (displayIds.length) {
const { ids, missing } = await findPublicProblemsByDisplayIds(displayIds)
if (missing) {
return {
ok: false,
status: 404,
code: "problem-not-found",
message: `Problem ${missing} does not exist`,
}
}
filters.push(inArray(schema.submission.problemId, ids))
}
return { ok: true, filters, problemCount: displayIds.length }
}
submissionStatisticsRoutes.get(
"/submissions/statistics",
requireTeacher,
async (c) => {
const scope = await statisticsScope(c)
if (!scope.ok) return failure(c, scope.status, scope.code, scope.message)
const filters = scope.filters
const username = c.req.query("username")?.trim()
// 用户名先解析成账号,再拿 user_id 去筛提交。这一趟查询挡在 Promise.all 前面,
// 但换掉的是下面**四条**语句各一次的 submission 全表扫:`ilike` 走不了索引,
// 换成 `user_id in (...)` 之后四条全走索引(生产快照实测单条 18448 → 537
// buffers;同一个快照上整个接口查一个班 120~250ms → 10ms 上下),多这一次往返是赚的。
const matched = username ? await matchedUsers(username) : []
if (username) {
const matchedIds = matched.map((row) => row.id)
// 一个账号都没匹配上时得留个恒假条件。少推一个 filter 的话过滤条件整个消失,
// 「查无此班」会变成「全站统计」
filters.push(
matchedIds.length
? inArray(schema.submission.userId, matchedIds)
: sql`false`,
)
}
const where = and(...filters)
// 花名册:只有未禁用的普通用户算进班级人数和「谁没做」,教师和管理员不进分母
const rosterRows = matched.filter(
(row) => !row.isDisabled && row.adminType === "Regular User",
)
const acceptedFilter = sql`count(*) filter (where ${inArray(schema.submission.result, ACCEPTED_RESULTS)})`
// 判题中的条数。要单独数出来,正确率的分母才能把它们摘掉
const judgingFilter = sql`count(*) filter (where ${inArray(schema.submission.result, UNJUDGED_RESULTS)})`
/**
* **** AC
*
* 1
*/
const solvedFilter = sql`count(distinct ${schema.submission.problemId}) filter (where ${inArray(schema.submission.result, ACCEPTED_RESULTS)})`
const [[totals], perUser] = await Promise.all([
db
.select({
total: count(),
accepted: acceptedFilter.mapWith(Number),
judging: judgingFilter.mapWith(Number),
})
.from(schema.submission)
.where(where),
db
.select({
userId: schema.submission.userId,
/**
* **** user join submission.username
*
*
* user 退
* personCount
*/
username: sql<string>`coalesce(${schema.user.username}, max(${schema.submission.username}))`,
className: schema.user.className,
// 不传用户名时「交了没全对」那一栏靠它把教师和禁用账号挡在外面 ——
// 传了用户名时这件事是花名册(rosterRows)做的
isDisabled: schema.user.isDisabled,
adminType: schema.user.adminType,
submissionCount: count(),
acceptedCount: acceptedFilter.mapWith(Number),
solvedCount: solvedFilter.mapWith(Number),
judgingCount: judgingFilter.mapWith(Number),
})
.from(schema.submission)
.leftJoin(schema.user, eq(schema.user.id, schema.submission.userId))
.where(where)
// user_id 定了 user 那一行就定了,把 username / class_name 一起放进 group by
// 不会多分出组来,但省掉再对它们套一层聚合函数
.groupBy(
schema.submission.userId,
schema.user.username,
schema.user.className,
schema.user.isDisabled,
schema.user.adminType,
)
.orderBy(desc(count())),
])
const submissionCount = totals?.total ?? 0
const acceptedCount = totals?.accepted ?? 0
const judgingCount = totals?.judging ?? 0
// 正确率的分母是**判完的条数**,不是总条数
const judgedCount = submissionCount - judgingCount
/**
* ****
*
* `solvedCount`
*
* `solvedCount >= 1` `acceptedCount > 0`
* 退
*/
const requiredSolved = scope.problemCount
const isDone = (row: { solvedCount: number; acceptedCount: number }) =>
requiredSolved > 0
? row.solvedCount >= requiredSolved
: row.acceptedCount > 0
/**
* **西**`done`
*
*
* GET /submissions/statistics/items
*
* `done` `data.length`
*/
const doneCount = perUser.filter(isDone).length
// 要等 perUser 回来才能查,所以进不了上面那个 Promise.all
const astOnlyByUserMap = await astOnlyByUser(
where,
perUser.map((row) => row.userId),
)
const submittedUserIds = new Set(perUser.map((row) => row.userId))
const data = perUser.map((row) => ({
username: row.username,
className: row.className,
submissionCount: row.submissionCount,
acceptedCount: row.acceptedCount,
solvedCount: row.solvedCount,
astOnlyCount: astOnlyByUserMap.get(row.userId) ?? 0,
judgingCount: row.judgingCount,
correctRate: judgedRate(
row.acceptedCount,
row.submissionCount - row.judgingCount,
),
done: isDone(row),
}))
const dataUnaccepted = rosterRows
.filter((row) => !submittedUserIds.has(row.id))
.map((row) => ({
username: row.username,
realName: stripClassPrefix(row.username, row.className),
}))
/**
*
*
* **** dataUnaccepted
*
*
*
*
* 退
*
*
*
*/
const rosterIds = new Set(rosterRows.map((row) => row.id))
const attemptedRows = perUser.filter((row) => {
if (isDone(row)) return false
return username
? rosterIds.has(row.userId)
: !row.isDisabled && row.adminType === "Regular User"
})
const failureByUser = await lastFailureByUser(
where,
attemptedRows.map((row) => row.userId),
)
const dataAttempted = attemptedRows.map((row) => ({
username: row.username,
/**
* **** `ks251`
*
* perUser join
*/
realName: username
? stripClassPrefix(row.username, row.className)
: row.username,
submissionCount: row.submissionCount,
solvedCount: row.solvedCount,
lastFailure: failureByUser.get(row.userId) ?? null,
}))
// 「学生已删号但提交记录还在」时完成人数会大于花名册人数,分母兜到完成人数为止。
// 旧后端在这之前还先算了一个 person_rate 一起下发,前端从来没读过它(完成度是
// 前端自己按「减掉请假人数之后的分母」重算的),所以这条链路上只留 person_count。
let personCount = rosterRows.length
if (personCount && personCount < doneCount) personCount = doneCount
return success(c, {
submissionCount,
acceptedCount,
judgingCount,
correctRate: judgedRate(acceptedCount, judgedCount),
personCount,
data,
dataUnaccepted,
dataAttempted,
} satisfies SubmissionStatistics)
},
)
/**
*
*
* **** ilike `ks251`
* 沿 scope
*
*/
submissionStatisticsRoutes.get(
"/submissions/statistics/items",
requireTeacher,
async (c) => {
const username = c.req.query("username")?.trim()
if (!username)
return failure(c, 400, "invalid-request", "username is required")
const scope = await statisticsScope(c)
if (!scope.ok) return failure(c, scope.status, scope.code, scope.message)
/**
* **** user_id
* `submission.username`
*
*
* 退
*
*/
const [account] = await db
.select({ id: schema.user.id })
.from(schema.user)
.where(eq(schema.user.username, username))
.limit(1)
const identity = account
? eq(schema.submission.userId, account.id)
: eq(schema.submission.username, username)
// 多取一条,好知道是不是被截断了
// innerJoin 不会漏行:submission.problem_id 是 NOT NULL 且外键是 NO ACTION
// 题目删不掉(真要删会被外键拦住并提示改为隐藏)
const rows = await db
.select({
id: schema.submission.id,
result: schema.submission.result,
createTime: schema.submission.createTime,
problem: schema.problem.displayId,
problemTitle: schema.problem.title,
})
.from(schema.submission)
.innerJoin(
schema.problem,
eq(schema.problem.id, schema.submission.problemId),
)
.where(and(...scope.filters, identity))
.orderBy(desc(schema.submission.createTime), desc(schema.submission.id))
.limit(STATISTICS_ITEMS_LIMIT + 1)
const truncated = rows.length > STATISTICS_ITEMS_LIMIT
return success(c, {
items: rows.slice(0, STATISTICS_ITEMS_LIMIT),
truncated,
} satisfies SubmissionStatisticsItems)
},
)
File diff suppressed because it is too large Load Diff
+6 -2
View File
@@ -31,7 +31,9 @@ export function selfCommand(subcommand: string): string[] {
* docker/compose.dev.yml **** data/test_case cwd
* apps/api/data/
*/
export const pathBase = isCompiled ? process.cwd() : resolve(import.meta.dir, "../../..")
export const pathBase = isCompiled
? process.cwd()
: resolve(import.meta.dir, "../../..")
/**
* `0000_*.sql` + `meta/_journal.json`
@@ -48,4 +50,6 @@ export const pathBase = isCompiled ? process.cwd() : resolve(import.meta.dir, ".
*/
export const migrationsDir =
process.env.OJ2_MIGRATIONS_DIR ??
(isCompiled ? "/usr/local/share/oj2/migrations" : resolve(import.meta.dir, "db"))
(isCompiled
? "/usr/local/share/oj2/migrations"
: resolve(import.meta.dir, "db"))
+81
View File
@@ -0,0 +1,81 @@
/**
* AST target `node`
*
* bun run --filter '@oj2/api' check:ast
*
* ##
*
* `node` tree-sitter ****collectNodes
* 使 X使 X
* f-string使 f-stringjudge成通过
*
* `f_string` `format_string`
* tree-sitter-python f-string `string` `interpolation`
* 线56 target
*
* tree-sitter-*
*
*
* **** `while_loop` `for_statement`
*
*/
import { AST_NODE_TARGETS_BY_LANGUAGE } from "@oj2/contract"
import { Language, Parser } from "web-tree-sitter"
import cWasmPath from "tree-sitter-c/tree-sitter-c.wasm" with { type: "file" }
import cppWasmPath from "tree-sitter-cpp/tree-sitter-cpp.wasm" with { type: "file" }
import pythonWasmPath from "tree-sitter-python/tree-sitter-python.wasm" with { type: "file" }
import treeSitterWasmPath from "web-tree-sitter/web-tree-sitter.wasm" with { type: "file" }
const WASM_BY_LANGUAGE: Record<string, string> = {
C: cWasmPath,
"C++": cppWasmPath,
Python: pythonWasmPath,
}
await Parser.init({ locateFile: () => treeSitterWasmPath })
let checked = 0
const missing: Array<{ language: string; target: string; node: string }> = []
for (const [language, table] of Object.entries(AST_NODE_TARGETS_BY_LANGUAGE)) {
const wasmPath = WASM_BY_LANGUAGE[language]
if (!wasmPath) {
console.log(
`${language} 在 AST_NODE_TARGETS_BY_LANGUAGE 里,但这个脚本没有它的语法 wasm`,
)
console.log(
` 加语言时记得同步 WASM_BY_LANGUAGE 和 judge/ast.ts 的 loadLanguage`,
)
process.exit(2)
}
const loaded = await Language.load(wasmPath)
// 语法里声明过的全部节点类型名
const declared = new Set<string>()
for (let id = 0; id < loaded.nodeTypeCount; id++) {
const name = loaded.nodeTypeForId(id)
if (name) declared.add(name)
}
for (const [target, entry] of Object.entries(table)) {
checked++
if (!declared.has(entry.node))
missing.push({ language, target, node: entry.node })
}
}
console.log(`检查了 ${checked} 个 AST target 的节点类型`)
if (missing.length === 0) {
console.log("✓ 每个 target 的 node 都在对应语言的语法里真实存在")
process.exit(0)
}
for (const { language, target, node } of missing) {
console.log(`\n⚠ ${language}${target} → "${node}"`)
console.log(
` 这个节点类型在语法里不存在,规则永远失败(或永远通过),且不报错`,
)
console.log(
` 改法:在 packages/contract/src/problem.ts 把它的 node 改成语法里真实的名字`,
)
}
process.exit(1)
+32 -12
View File
@@ -16,7 +16,8 @@
*
* 200
*
* `xxxRoutes.get("字面量", …)`
* `xxxRoutes.get("字面量", …)`
* `xxxRoutes.route("字面量", 子路由)`
*
*/
@@ -63,7 +64,9 @@ export function shadows(pattern: string, target: string) {
function collect(): Route[] {
const routerFile = new Map<string, string>()
for (const file of walk(SRC)) {
for (const m of readFileSync(file, "utf8").matchAll(/export const (\w+) = new Hono/g)) {
for (const m of readFileSync(file, "utf8").matchAll(
/export const (\w+) = new Hono/g,
)) {
routerFile.set(m[1]!, file)
}
}
@@ -72,21 +75,35 @@ function collect(): Route[] {
const file = routerFile.get(router)
if (!file) return []
const text = readFileSync(file, "utf8")
const pattern = new RegExp(`${router}\\.(get|post|put|delete|patch)\\(\\s*"([^"]+)"`, "g")
return [...text.matchAll(pattern)].map((m) => ({
method: m[1]!.toUpperCase(),
path: (prefix + m[2]!).replace(/\/+/g, "/").replace(/\/$/, "") || "/",
file: file.replace(SRC + "/", ""),
}))
// 直接注册的路由和嵌套挂载(`router.route("/", child)`)放在一起按出现位置排序:
// 子路由挂在哪个位置,它的路由就在哪个位置参与匹配
const pattern = new RegExp(
`${router}\\.(get|post|put|delete|patch)\\(\\s*"([^"]+)"|${router}\\.route\\(\\s*"([^"]*)"\\s*,\\s*(\\w+)\\s*\\)`,
"g",
)
return [...text.matchAll(pattern)].flatMap((m) => {
if (m[4]) return routesOf(m[4], prefix + m[3]!)
return [
{
method: m[1]!.toUpperCase(),
path: (prefix + m[2]!).replace(/\/+/g, "/").replace(/\/$/, "") || "/",
file: file.replace(SRC + "/", ""),
},
]
})
}
// 挂载顺序就是匹配顺序,所以必须按 index.ts 里出现的先后来摊平
const index = readFileSync(join(SRC, "index.ts"), "utf8")
const adminIndex = readFileSync(join(SRC, "routes/admin/index.ts"), "utf8")
const adminMounts = [...adminIndex.matchAll(/\.route\(\s*"([^"]*)"\s*,\s*(\w+)\s*\)/g)]
const adminMounts = [
...adminIndex.matchAll(/\.route\(\s*"([^"]*)"\s*,\s*(\w+)\s*\)/g),
]
const all: Route[] = []
for (const m of index.matchAll(/app\.route\(\s*"([^"]+)"\s*,\s*(\w+)\s*\)/g)) {
for (const m of index.matchAll(
/app\.route\(\s*"([^"]+)"\s*,\s*(\w+)\s*\)/g,
)) {
const [, prefix, router] = m
if (router === "adminRoutes") {
for (const a of adminMounts) all.push(...routesOf(a[2]!, prefix! + a[1]!))
@@ -102,7 +119,8 @@ const hits: [Route, Route][] = []
for (let i = 0; i < routes.length; i++) {
for (let j = i + 1; j < routes.length; j++) {
if (routes[i]!.method !== routes[j]!.method) continue
if (shadows(routes[i]!.path, routes[j]!.path)) hits.push([routes[i]!, routes[j]!])
if (shadows(routes[i]!.path, routes[j]!.path))
hits.push([routes[i]!, routes[j]!])
}
}
@@ -113,7 +131,9 @@ if (hits.length === 0) {
}
for (const [first, second] of hits) {
console.log(`\n⚠ ${second.method} ${second.path} ${second.file}`)
console.log(` 进不去:被先注册的 ${first.method} ${first.path} 吃掉(${first.file}`)
console.log(
` 进不去:被先注册的 ${first.method} ${first.path} 吃掉(${first.file}`,
)
console.log(` 改法:把它挪到那条之前注册,或换一个不同形的路径`)
}
process.exit(1)
+447
View File
@@ -0,0 +1,447 @@
import { eq, sql } from "drizzle-orm"
import { db, schema } from "../db"
import { JudgeStatus, isAccepted } from "../judge/status"
import { objectValue } from "../routes/helpers"
import {
metaAchievements,
refreshUnlockedCount,
rescanAchievement,
} from "../services/achievements"
/**
* submission
*
* `judge/run.ts` persistResult
* ****`routes/submission.ts`
* rejudge result PENDING **退** persistResult
* submission_number
*
*
* problem.submission_number / accepted_number / statistic_info
* user_profile.submission_number / accepted_number / acm_problems_status
*
* `user_stat.metrics.achievement_unlocked_count`
* user_achievement
* `rescanAchievement` backfilled
* 2026-09-07 269 10 `rescanAchievement`
*
* ****acm_contest_rank submission_info
* achievement.unlock_count0010
* user_achievement services/problemset.ts
*
* --apply migrate
*
* docker compose -f docker/compose.debian.yml run --rm oj-api oj2-api recount
* docker compose -f docker/compose.debian.yml run --rm oj-api oj2-api recount --apply
*
* **--apply **
*
* N 1 退
*/
/** 判完的提交才计数。PENDING / JUDGING 是在途状态,persistResult 还没给它们记过账 */
const UNJUDGED = [JudgeStatus.PENDING, JudgeStatus.JUDGING]
type ProblemExpected = {
submissionNumber: number
acceptedNumber: number
statisticInfo: Record<string, number>
}
/**
* ****persistResult problem
* contestId user_profile
*/
async function expectedProblems() {
const rows = await db.execute<{
problem_id: number
result: number
n: number
}>(sql`
select problem_id, result, count(*)::int as n
from submission
where result not in (${UNJUDGED[0]}, ${UNJUDGED[1]})
group by problem_id, result
`)
const expected = new Map<number, ProblemExpected>()
for (const row of rows) {
const current = expected.get(row.problem_id) ?? {
submissionNumber: 0,
acceptedNumber: 0,
statisticInfo: {},
}
current.submissionNumber += row.n
if (isAccepted(row.result)) current.acceptedNumber += row.n
current.statisticInfo[String(row.result)] = row.n
expected.set(row.problem_id, current)
}
return expected
}
type ProfileExpected = {
submissionNumber: number
acceptedNumber: number
status: Record<string, Record<string, { status: number; _id: string }>>
}
/**
* persistResult
*
* - submission_number****
* - accepted_number****`acceptedNow && !wasAccepted`
* AC
* - acm_problems_status`{ problems / contest_problems: { 题号: { status, _id } } }`
* ACCEPTEDpersistResult `wasAccepted`
* ****
*
* create_time persistResult ****
*
* AC
* create_time
*/
async function expectedProfiles() {
const totals = await db.execute<{
user_id: number
submissions: number
accepted: number
}>(sql`
select user_id,
count(*)::int as submissions,
count(distinct problem_id) filter (where result in (${JudgeStatus.ACCEPTED}, ${JudgeStatus.AST_CHECK_FAILED}))::int as accepted
from submission
where result not in (${UNJUDGED[0]}, ${UNJUDGED[1]}) and contest_id is null
group by user_id
`)
const perProblem = await db.execute<{
user_id: number
is_public: boolean
problem_id: number
display_id: string
ever_accepted: boolean
last_result: number
}>(sql`
select s.user_id,
(s.contest_id is null) as is_public,
s.problem_id,
p._id as display_id,
bool_or(s.result in (${JudgeStatus.ACCEPTED}, ${JudgeStatus.AST_CHECK_FAILED})) as ever_accepted,
(array_agg(s.result order by s.create_time desc, s.id desc))[1] as last_result
from submission s
join problem p on p.id = s.problem_id
where s.result not in (${UNJUDGED[0]}, ${UNJUDGED[1]})
group by s.user_id, (s.contest_id is null), s.problem_id, p._id
`)
const expected = new Map<number, ProfileExpected>()
const blank = (): ProfileExpected => ({
submissionNumber: 0,
acceptedNumber: 0,
status: {},
})
for (const row of totals) {
const current = expected.get(row.user_id) ?? blank()
current.submissionNumber = row.submissions
current.acceptedNumber = row.accepted
expected.set(row.user_id, current)
}
for (const row of perProblem) {
const current = expected.get(row.user_id) ?? blank()
const bucket = row.is_public ? "problems" : "contest_problems"
current.status[bucket] ??= {}
current.status[bucket]![String(row.problem_id)] = {
status: row.ever_accepted ? JudgeStatus.ACCEPTED : row.last_result,
_id: row.display_id,
}
expected.set(row.user_id, current)
}
return expected
}
/** 稳定序列化,用来比对 jsonb —— 键序不同不该被当成差异 */
function stable(value: unknown): string {
if (Array.isArray(value)) return `[${value.map(stable).join(",")}]`
if (value && typeof value === "object") {
const entries = Object.entries(value as Record<string, unknown>).sort(
([a], [b]) => (a < b ? -1 : 1),
)
return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${stable(v)}`).join(",")}}`
}
return JSON.stringify(value) ?? "null"
}
type Diff = { label: string; field: string; before: unknown; after: unknown }
type Plan = {
diffs: Diff[]
problemFixes: { id: number; value: ProblemExpected }[]
profileFixes: {
id: number
value: ProfileExpected & { merged: Record<string, unknown> }
}[]
/** achievement_unlocked_count 不对的用户 */
unlockedCountFixes: number[]
/** 按正确计数已达标、却没持有元成就的 (用户, 元成就) */
metaGrants: { userId: number; achievementId: number }[]
}
/**
* `refreshUnlockedCount` /
* user_stat `rescanAchievement`
*/
async function unlockedCountPlan(plan: Plan) {
const [rows, metas] = await Promise.all([
db.execute<{ user_id: number; counter: unknown; actual: number }>(sql`
select s.user_id, s.metrics -> 'achievement_unlocked_count' as counter, coalesce(c.value, 0) as actual
from user_stat s
left join (
select ua.user_id, count(*)::int as value
from user_achievement ua
join achievement a on a.id = ua.achievement_id
where a.rarity <> 'platinum'
group by ua.user_id
) c on c.user_id = s.user_id
`),
metaAchievements(),
])
const holders = metas.length
? await db
.select({
userId: schema.userAchievement.userId,
achievementId: schema.userAchievement.achievementId,
})
.from(schema.userAchievement)
.where(
sql`${schema.userAchievement.achievementId} in ${metas.map((meta) => meta.id)}`,
)
: []
const held = new Set(
holders.map((row) => `${row.userId}:${row.achievementId}`),
)
for (const row of rows) {
const label = `用户 ${row.user_id}`
if (row.counter !== row.actual) {
plan.diffs.push({
label,
field: "achievement_unlocked_count",
before: row.counter ?? null,
after: row.actual,
})
plan.unlockedCountFixes.push(row.user_id)
}
for (const meta of metas) {
const met =
meta.operator === "gte"
? row.actual >= meta.threshold
: row.actual <= meta.threshold
if (!met || held.has(`${row.user_id}:${meta.id}`)) continue
plan.diffs.push({
label,
field: `成就「${meta.name}`,
before: "未发",
after: "补发",
})
plan.metaGrants.push({ userId: row.user_id, achievementId: meta.id })
}
}
}
/** 只算差异,不写库。预演和落库后的复核共用它 —— 两边口径必须是同一份代码 */
async function computePlan(): Promise<Plan> {
const [problems, profiles, expectedProblem, expectedProfile] =
await Promise.all([
db
.select({
id: schema.problem.id,
displayId: schema.problem.displayId,
submissionNumber: schema.problem.submissionNumber,
acceptedNumber: schema.problem.acceptedNumber,
statisticInfo: schema.problem.statisticInfo,
})
.from(schema.problem),
db
.select({
id: schema.userProfile.id,
userId: schema.userProfile.userId,
submissionNumber: schema.userProfile.submissionNumber,
acceptedNumber: schema.userProfile.acceptedNumber,
acmProblemsStatus: schema.userProfile.acmProblemsStatus,
})
.from(schema.userProfile),
expectedProblems(),
expectedProfiles(),
])
const plan: Plan = {
diffs: [],
problemFixes: [],
profileFixes: [],
unlockedCountFixes: [],
metaGrants: [],
}
for (const problem of problems) {
const want = expectedProblem.get(problem.id) ?? {
submissionNumber: 0,
acceptedNumber: 0,
statisticInfo: {},
}
const label = `题目 ${problem.displayId}(id=${problem.id})`
const rows: Diff[] = []
if (problem.submissionNumber !== want.submissionNumber) {
rows.push({
label,
field: "submission_number",
before: problem.submissionNumber,
after: want.submissionNumber,
})
}
if (problem.acceptedNumber !== want.acceptedNumber) {
rows.push({
label,
field: "accepted_number",
before: problem.acceptedNumber,
after: want.acceptedNumber,
})
}
if (
stable(objectValue(problem.statisticInfo)) !== stable(want.statisticInfo)
) {
rows.push({
label,
field: "statistic_info",
before: problem.statisticInfo,
after: want.statisticInfo,
})
}
if (rows.length) {
plan.diffs.push(...rows)
plan.problemFixes.push({ id: problem.id, value: want })
}
}
for (const profile of profiles) {
const want = expectedProfile.get(profile.userId) ?? {
submissionNumber: 0,
acceptedNumber: 0,
status: {},
}
// acm_problems_status 里除了 problems / contest_problems 之外的键原样保留 ——
// persistResult 只写这两个桶,别的键是从哪来的没人说得清,重算不该顺手抹掉。
const existing = objectValue(profile.acmProblemsStatus)
const merged: Record<string, unknown> = { ...existing }
delete merged.problems
delete merged.contest_problems
for (const [bucket, value] of Object.entries(want.status))
merged[bucket] = value
const label = `用户 ${profile.userId}`
const rows: Diff[] = []
if (profile.submissionNumber !== want.submissionNumber) {
rows.push({
label,
field: "submission_number",
before: profile.submissionNumber,
after: want.submissionNumber,
})
}
if (profile.acceptedNumber !== want.acceptedNumber) {
rows.push({
label,
field: "accepted_number",
before: profile.acceptedNumber,
after: want.acceptedNumber,
})
}
if (stable(existing) !== stable(merged)) {
const keys = new Set([
...Object.keys(objectValue(existing.problems)),
...Object.keys(want.status.problems ?? {}),
])
rows.push({
label,
field: "acm_problems_status",
before: `${Object.keys(objectValue(existing.problems)).length}`,
after: `${keys.size} 题(含比赛桶重建)`,
})
}
if (rows.length) {
plan.diffs.push(...rows)
plan.profileFixes.push({ id: profile.id, value: { ...want, merged } })
}
}
await unlockedCountPlan(plan)
return plan
}
function report(plan: Plan) {
console.log(
`发现 ${plan.diffs.length} 处不一致(题目 ${plan.problemFixes.length} 道 / 用户 ${plan.profileFixes.length} 人 / 已解锁数 ${plan.unlockedCountFixes.length} 人 / 元成就补发 ${plan.metaGrants.length} 条):`,
)
for (const diff of plan.diffs.slice(0, 40)) {
console.log(
` ${diff.label} ${diff.field}: ${JSON.stringify(diff.before)}${JSON.stringify(diff.after)}`,
)
}
if (plan.diffs.length > 40)
console.log(` ……另有 ${plan.diffs.length - 40}`)
}
/** 退出码:0 = 一致或预演正常,1 = 落库后复核仍有差异 */
export async function recount(options: { apply: boolean }) {
const plan = await computePlan()
if (plan.diffs.length === 0) {
console.log("计数列与 submission / user_achievement 一致,没有要订正的。")
return 0
}
report(plan)
if (!options.apply) {
console.log("\n以上为预演,没有写库。确认无误后加 --apply 落库。")
return 0
}
await db.transaction(async (tx) => {
for (const fix of plan.problemFixes) {
await tx
.update(schema.problem)
.set({
submissionNumber: fix.value.submissionNumber,
acceptedNumber: fix.value.acceptedNumber,
statisticInfo: fix.value.statisticInfo,
})
.where(eq(schema.problem.id, fix.id))
}
for (const fix of plan.profileFixes) {
await tx
.update(schema.userProfile)
.set({
submissionNumber: fix.value.submissionNumber,
acceptedNumber: fix.value.acceptedNumber,
acmProblemsStatus: fix.value.merged,
})
.where(eq(schema.userProfile.id, fix.id))
}
})
// 先改计数、再补发:rescanAchievement 读的是 metrics 里的计数。
// 补发幂等(唯一键 + 冲突忽略),重跑不会重复发
const recounted = await refreshUnlockedCount(plan.unlockedCountFixes)
if (plan.metaGrants.length) {
for (const meta of await metaAchievements())
await rescanAchievement(meta.id)
}
console.log(
`\n已订正题目 ${plan.problemFixes.length} 道、用户 ${plan.profileFixes.length} 人、已解锁数 ${recounted.length} 人,补发元成就 ${plan.metaGrants.length} 条,复核中……`,
)
// 复核跑的是同一份 computePlan。这里还剩差异说明口径本身有问题(不是数据脏),
// 必须让部署脚本看见非零退出码,而不是打一行字了事。
const after = await computePlan()
if (after.diffs.length === 0) {
console.log("复核通过:计数列与 submission / user_achievement 一致")
return 0
}
console.error(`复核未通过,仍有 ${after.diffs.length} 处差异:`)
report(after)
return 1
}
+6 -4
View File
@@ -8,7 +8,9 @@ import { db, schema } from "../db"
* raw_password
* DATABASE_URL OJ2_SEED_FORCE=true
*/
const url = process.env.DATABASE_URL ?? "postgres://onlinejudge:onlinejudge@localhost:5433/onlinejudge"
const url =
process.env.DATABASE_URL ??
"postgres://onlinejudge:onlinejudge@localhost:5433/onlinejudge"
const host = (() => {
try {
return new URL(url).hostname
@@ -61,9 +63,7 @@ async function seed(account: SeedAccount) {
createTime: now,
adminType: account.adminType,
problemPermission: account.problemPermission,
openApi: false,
isDisabled: false,
sessionKeys: [],
})
.onConflictDoUpdate({
target: schema.user.username,
@@ -95,7 +95,9 @@ async function seed(account: SeedAccount) {
})
}
console.log(` ${account.adminType.padEnd(13)} ${user.username} / ${account.password}`)
console.log(
` ${account.adminType.padEnd(13)} ${user.username} / ${account.password}`,
)
}
console.log("Seeded development logins:")
+76 -19
View File
@@ -14,24 +14,85 @@ export interface AchievementMetric {
}
export const ACHIEVEMENT_METRICS: AchievementMetric[] = [
{ key: "accepted_count", name: "AC 题目数", helpText: "去重后通过的题目数量(不含比赛)" },
{ key: "mid_ac_count", name: "中等题 AC 数", helpText: "去重后通过的中等难度题目数(不含比赛)" },
{ key: "hard_ac_count", name: "困难题 AC 数", helpText: "去重后通过的困难题目数(不含比赛)" },
{ key: "submission_count", name: "提交总数", helpText: "提交次数(不含比赛)" },
{
key: "accepted_count",
name: "AC 题目数",
helpText: "去重后通过的题目数量(不含比赛)",
},
{
key: "mid_ac_count",
name: "中等题 AC 数",
helpText: "去重后通过的中等难度题目数(不含比赛)",
},
{
key: "hard_ac_count",
name: "困难题 AC 数",
helpText: "去重后通过的困难题目数(不含比赛)",
},
{
key: "submission_count",
name: "提交总数",
helpText: "提交次数(不含比赛)",
},
{ key: "active_days", name: "活跃天数", helpText: "有过提交的累计天数" },
{ key: "max_ac_streak_days", name: "最长连续 AC 天数", helpText: "连续每天至少 AC 一题的最长天数" },
{
key: "max_ac_streak_days",
name: "最长连续 AC 天数",
helpText: "连续每天至少 AC 一题的最长天数",
},
{ key: "languages_used", name: "使用语言数", helpText: "用过多少种编程语言" },
{ key: "contest_joined", name: "参赛场次", helpText: "参加过的比赛数量(本指标是比赛维度,不受比赛提交不计入的限制)" },
{
key: "contest_joined",
name: "参赛场次",
helpText: "参加过的比赛数量(本指标是比赛维度,不受比赛提交不计入的限制)",
},
{ key: "badge_count", name: "题单奖章数", helpText: "获得的题单奖章数量" },
{ key: "problemset_completed", name: "完成题单数", helpText: "完成的题单数量" },
{ key: "first_try_ac_count", name: "一发入魂次数", helpText: "首次提交即通过的次数" },
{ key: "midnight_submissions", name: "凌晨提交次数", helpText: "0:005:00 之间的提交次数" },
{ key: "early_bird_submissions", name: "早起提交次数", helpText: "5:007:00 之间的提交次数" },
{ key: "compile_error_count", name: "编译错误次数", helpText: "累计编译错误的次数" },
{ key: "max_wa_before_ac", name: "屡败屡战", helpText: "单题失败最多多少次后终于通过" },
{ key: "max_ac_in_one_day", name: "单日最多 AC", helpText: "一天之内最多通过多少题" },
{ key: "max_code_lines", name: "最长代码行数", helpText: "提交过的最长代码有多少行" },
{ key: "achievement_unlocked_count", name: "已解锁成就数", helpText: "已解锁的成就数量(不含白金档)", meta: true },
{
key: "problemset_completed",
name: "完成题单数",
helpText: "完成的题单数量",
},
{
key: "first_try_ac_count",
name: "一发入魂次数",
helpText: "首次提交即通过的次数",
},
{
key: "midnight_submissions",
name: "凌晨提交次数",
helpText: "0:005:00 之间的提交次数",
},
{
key: "early_bird_submissions",
name: "早起提交次数",
helpText: "5:007:00 之间的提交次数",
},
{
key: "compile_error_count",
name: "编译错误次数",
helpText: "累计编译错误的次数",
},
{
key: "max_wa_before_ac",
name: "屡败屡战",
helpText: "单题失败最多多少次后终于通过",
},
{
key: "max_ac_in_one_day",
name: "单日最多 AC",
helpText: "一天之内最多通过多少题",
},
{
key: "max_code_lines",
name: "最长代码行数",
helpText: "提交过的最长代码有多少行",
},
{
key: "achievement_unlocked_count",
name: "已解锁成就数",
helpText: "已解锁的成就数量(不含白金档)",
meta: true,
},
]
const BY_KEY = new Map(ACHIEVEMENT_METRICS.map((item) => [item.key, item]))
@@ -43,7 +104,3 @@ export function findMetric(key: string) {
export function metricName(key: string) {
return BY_KEY.get(key)?.name ?? key
}
/** 稀有度四档。乱填的值会让成就汇总接口的分档统计对不上:野值算进总数却不出现在任何一档 */
export const RARITIES = ["bronze", "silver", "gold", "platinum"] as const
export const OPERATORS = ["gte", "lte"] as const
+348 -111
View File
@@ -1,7 +1,19 @@
import { and, count, countDistinct, eq, inArray, isNotNull, isNull, ne, notInArray, sql } from "drizzle-orm"
import {
and,
count,
countDistinct,
eq,
inArray,
isNotNull,
isNull,
ne,
notInArray,
sql,
} from "drizzle-orm"
import { db, schema } from "../db"
import { publishAchievementNotification } from "../events"
import { calendarDay, dayNumber, localHour } from "../time"
import { findMetric } from "./achievement-metrics"
import { isAccepted, JudgeStatus } from "../judge/status"
import { objectValue } from "../routes/helpers"
@@ -11,154 +23,276 @@ function numberMetric(metrics: Record<string, unknown>, key: string) {
return typeof value === "number" ? value : 0
}
function localDate(value: string) {
const date = new Date(value)
const year = date.getFullYear()
const month = String(date.getMonth() + 1).padStart(2, "0")
const day = String(date.getDate()).padStart(2, "0")
return `${year}-${month}-${day}`
}
async function unlockAchievements(userId: number, metrics: Record<string, unknown>, onlyMeta = false) {
const unlocked = await db.select({ id: schema.userAchievement.achievementId }).from(schema.userAchievement)
async function unlockAchievements(
userId: number,
metrics: Record<string, unknown>,
onlyMeta = false,
) {
const unlocked = await db
.select({ id: schema.userAchievement.achievementId })
.from(schema.userAchievement)
.where(eq(schema.userAchievement.userId, userId))
const filters = [eq(schema.achievement.visible, true)]
if (unlocked.length) filters.push(notInArray(schema.achievement.id, unlocked.map((row) => row.id)))
if (onlyMeta) filters.push(eq(schema.achievement.metric, "achievement_unlocked_count"))
if (unlocked.length)
filters.push(
notInArray(
schema.achievement.id,
unlocked.map((row) => row.id),
),
)
if (onlyMeta)
filters.push(eq(schema.achievement.metric, "achievement_unlocked_count"))
else filters.push(ne(schema.achievement.metric, "achievement_unlocked_count"))
const candidates = await db.select().from(schema.achievement).where(and(...filters))
const candidates = await db
.select()
.from(schema.achievement)
.where(and(...filters))
const hits = candidates.filter((achievement) => {
const value = metrics[achievement.metric]
if (typeof value !== "number") return false
return achievement.operator === "gte" ? value >= achievement.threshold : value <= achievement.threshold
return achievement.operator === "gte"
? value >= achievement.threshold
: value <= achievement.threshold
})
if (hits.length === 0) return []
// 命中的成就一次插完,冲突忽略后 returning 回来的就是「这次真新解锁的」。
// 一个用户对同一个成就只会解锁一次,所以每个成就都恰好 +1,一条 UPDATE 就够。
const inserted = await db.insert(schema.userAchievement).values(hits.map((achievement) => ({
userId,
achievementId: achievement.id,
unlockTime: new Date().toISOString(),
backfilled: false,
notified: false,
}))).onConflictDoNothing({ target: [schema.userAchievement.achievementId, schema.userAchievement.userId] })
const inserted = await db
.insert(schema.userAchievement)
.values(
hits.map((achievement) => ({
userId,
achievementId: achievement.id,
unlockTime: new Date().toISOString(),
backfilled: false,
notified: false,
})),
)
.onConflictDoNothing({
target: [
schema.userAchievement.achievementId,
schema.userAchievement.userId,
],
})
.returning({ achievementId: schema.userAchievement.achievementId })
if (inserted.length === 0) return []
const insertedIds = new Set(inserted.map((row) => row.achievementId))
await db.update(schema.achievement).set({ unlockCount: sql`${schema.achievement.unlockCount} + 1` })
await db
.update(schema.achievement)
.set({ unlockCount: sql`${schema.achievement.unlockCount} + 1` })
.where(inArray(schema.achievement.id, [...insertedIds]))
return hits.filter((achievement) => insertedIds.has(achievement.id))
}
export async function updateAchievementsForSubmission(submissionId: string) {
const [row] = await db.select({ submission: schema.submission, problem: schema.problem }).from(schema.submission)
.innerJoin(schema.problem, eq(schema.submission.problemId, schema.problem.id))
.where(eq(schema.submission.id, submissionId)).limit(1)
const [row] = await db
.select({ submission: schema.submission, problem: schema.problem })
.from(schema.submission)
.innerJoin(
schema.problem,
eq(schema.submission.problemId, schema.problem.id),
)
.where(eq(schema.submission.id, submissionId))
.limit(1)
if (!row || row.submission.contestId !== null) return []
const priorRows = await db.select({ result: schema.submission.result }).from(schema.submission).where(and(
eq(schema.submission.userId, row.submission.userId),
eq(schema.submission.problemId, row.submission.problemId),
isNull(schema.submission.contestId),
ne(schema.submission.id, row.submission.id),
))
const priorRows = await db
.select({ result: schema.submission.result })
.from(schema.submission)
.where(
and(
eq(schema.submission.userId, row.submission.userId),
eq(schema.submission.problemId, row.submission.problemId),
isNull(schema.submission.contestId),
ne(schema.submission.id, row.submission.id),
),
)
const priorAccepted = priorRows.some((item) => isAccepted(item.result))
const accepted = isAccepted(row.submission.result)
const firstAc = accepted && !priorAccepted
const firstTry = accepted && priorRows.length === 0
const date = localDate(row.submission.createTime)
const hour = new Date(row.submission.createTime).getHours()
const date = calendarDay(row.submission.createTime)
const hour = localHour(row.submission.createTime)
const metrics = await db.transaction(async (tx) => {
await tx.insert(schema.userStat).values({
userId: row.submission.userId,
metrics: {},
updateTime: new Date().toISOString(),
}).onConflictDoNothing({ target: schema.userStat.userId })
const [stat] = await tx.select().from(schema.userStat).where(eq(schema.userStat.userId, row.submission.userId)).for("update")
await tx
.insert(schema.userStat)
.values({
userId: row.submission.userId,
metrics: {},
updateTime: new Date().toISOString(),
})
.onConflictDoNothing({ target: schema.userStat.userId })
const [stat] = await tx
.select()
.from(schema.userStat)
.where(eq(schema.userStat.userId, row.submission.userId))
.for("update")
if (!stat) throw new Error("User achievement stat could not be created")
const value = objectValue(stat.metrics)
value.submission_count = numberMetric(value, "submission_count") + 1
if (firstAc) {
value.accepted_count = numberMetric(value, "accepted_count") + 1
if (row.problem.difficulty === "Mid") value.mid_ac_count = numberMetric(value, "mid_ac_count") + 1
if (row.problem.difficulty === "High") value.hard_ac_count = numberMetric(value, "hard_ac_count") + 1
if (firstTry) value.first_try_ac_count = numberMetric(value, "first_try_ac_count") + 1
value.max_wa_before_ac = Math.max(numberMetric(value, "max_wa_before_ac"), priorRows.length)
if (row.problem.difficulty === "Mid")
value.mid_ac_count = numberMetric(value, "mid_ac_count") + 1
if (row.problem.difficulty === "High")
value.hard_ac_count = numberMetric(value, "hard_ac_count") + 1
if (firstTry)
value.first_try_ac_count = numberMetric(value, "first_try_ac_count") + 1
value.max_wa_before_ac = Math.max(
numberMetric(value, "max_wa_before_ac"),
priorRows.length,
)
const perDay = objectValue(value._ac_per_day)
perDay[date] = (typeof perDay[date] === "number" ? perDay[date] : 0) + 1
value._ac_per_day = perDay
value.max_ac_in_one_day = Math.max(...Object.values(perDay).filter((item): item is number => typeof item === "number"))
value.max_ac_in_one_day = Math.max(
...Object.values(perDay).filter(
(item): item is number => typeof item === "number",
),
)
}
const activeDates = Array.isArray(value._active_dates) ? value._active_dates.filter((item): item is string => typeof item === "string") : []
const activeDates = Array.isArray(value._active_dates)
? value._active_dates.filter(
(item): item is string => typeof item === "string",
)
: []
if (!activeDates.includes(date)) activeDates.push(date)
value._active_dates = activeDates
value.active_days = activeDates.length
if (accepted) {
const last = typeof value._last_ac_date === "string" ? value._last_ac_date : null
const last =
typeof value._last_ac_date === "string" ? value._last_ac_date : null
if (last !== date) {
const current = last && (Date.parse(`${date}T00:00:00`) - Date.parse(`${last}T00:00:00`)) / 86_400_000 === 1
? numberMetric(value, "_current_ac_streak") + 1
: 1
// 差一天要按日历日算,不能用 Date 相减:夏令时地区相邻两天差 23/25 小时,
// 除 86400000 得到的不是 1,`=== 1` 会静默把连续打卡判成断掉。
const current =
last && dayNumber(date) - dayNumber(last) === 1
? numberMetric(value, "_current_ac_streak") + 1
: 1
value._last_ac_date = date
value._current_ac_streak = current
value.max_ac_streak_days = Math.max(numberMetric(value, "max_ac_streak_days"), current)
value.max_ac_streak_days = Math.max(
numberMetric(value, "max_ac_streak_days"),
current,
)
}
}
const languages = Array.isArray(value._languages) ? value._languages.filter((item): item is string => typeof item === "string") : []
if (!languages.includes(row.submission.language)) languages.push(row.submission.language)
const languages = Array.isArray(value._languages)
? value._languages.filter(
(item): item is string => typeof item === "string",
)
: []
if (!languages.includes(row.submission.language))
languages.push(row.submission.language)
value._languages = languages
value.languages_used = languages.length
if (hour < 5) value.midnight_submissions = numberMetric(value, "midnight_submissions") + 1
else if (hour < 7) value.early_bird_submissions = numberMetric(value, "early_bird_submissions") + 1
if (row.submission.result === JudgeStatus.COMPILE_ERROR) value.compile_error_count = numberMetric(value, "compile_error_count") + 1
value.max_code_lines = Math.max(numberMetric(value, "max_code_lines"), row.submission.code.split(/\r?\n/).length)
await tx.update(schema.userStat).set({ metrics: value, updateTime: new Date().toISOString() }).where(eq(schema.userStat.id, stat.id))
if (hour < 5)
value.midnight_submissions =
numberMetric(value, "midnight_submissions") + 1
else if (hour < 7)
value.early_bird_submissions =
numberMetric(value, "early_bird_submissions") + 1
if (row.submission.result === JudgeStatus.COMPILE_ERROR)
value.compile_error_count = numberMetric(value, "compile_error_count") + 1
value.max_code_lines = Math.max(
numberMetric(value, "max_code_lines"),
row.submission.code.split(/\r?\n/).length,
)
await tx
.update(schema.userStat)
.set({ metrics: value, updateTime: new Date().toISOString() })
.where(eq(schema.userStat.id, stat.id))
return value
})
const first = await unlockAchievements(row.submission.userId, metrics)
if (!first.length) return []
const [meta] = await db.select({ value: count() }).from(schema.userAchievement)
.innerJoin(schema.achievement, eq(schema.userAchievement.achievementId, schema.achievement.id))
.where(and(eq(schema.userAchievement.userId, row.submission.userId), ne(schema.achievement.rarity, "platinum")))
const [meta] = await db
.select({ value: count() })
.from(schema.userAchievement)
.innerJoin(
schema.achievement,
eq(schema.userAchievement.achievementId, schema.achievement.id),
)
.where(
and(
eq(schema.userAchievement.userId, row.submission.userId),
ne(schema.achievement.rarity, "platinum"),
),
)
metrics.achievement_unlocked_count = meta?.value ?? 0
await db.update(schema.userStat).set({ metrics, updateTime: new Date().toISOString() }).where(eq(schema.userStat.userId, row.submission.userId))
return [...first, ...(await unlockAchievements(row.submission.userId, metrics, true))]
await db
.update(schema.userStat)
.set({ metrics, updateTime: new Date().toISOString() })
.where(eq(schema.userStat.userId, row.submission.userId))
return [
...first,
...(await unlockAchievements(row.submission.userId, metrics, true)),
]
}
export async function updateAchievementsForProblemSet(userId: number) {
const [[badgeRow], [completedRow]] = await Promise.all([
db.select({ value: count() }).from(schema.userBadge).where(eq(schema.userBadge.userId, userId)),
db.select({ value: count() }).from(schema.problemsetProgress).where(and(
eq(schema.problemsetProgress.userId, userId),
eq(schema.problemsetProgress.isCompleted, true),
)),
db
.select({ value: count() })
.from(schema.userBadge)
.where(eq(schema.userBadge.userId, userId)),
db
.select({ value: count() })
.from(schema.problemsetProgress)
.where(
and(
eq(schema.problemsetProgress.userId, userId),
eq(schema.problemsetProgress.isCompleted, true),
),
),
])
const metrics = await db.transaction(async (tx) => {
await tx.insert(schema.userStat).values({
userId,
metrics: {},
updateTime: new Date().toISOString(),
}).onConflictDoNothing({ target: schema.userStat.userId })
const [stat] = await tx.select().from(schema.userStat)
.where(eq(schema.userStat.userId, userId)).for("update").limit(1)
await tx
.insert(schema.userStat)
.values({
userId,
metrics: {},
updateTime: new Date().toISOString(),
})
.onConflictDoNothing({ target: schema.userStat.userId })
const [stat] = await tx
.select()
.from(schema.userStat)
.where(eq(schema.userStat.userId, userId))
.for("update")
.limit(1)
if (!stat) throw new Error("User achievement stat could not be created")
const value = objectValue(stat.metrics)
value.badge_count = badgeRow?.value ?? 0
value.problemset_completed = completedRow?.value ?? 0
await tx.update(schema.userStat).set({ metrics: value, updateTime: new Date().toISOString() })
await tx
.update(schema.userStat)
.set({ metrics: value, updateTime: new Date().toISOString() })
.where(eq(schema.userStat.id, stat.id))
return value
})
const first = await unlockAchievements(userId, metrics)
if (!first.length) return []
const [meta] = await db.select({ value: count() }).from(schema.userAchievement)
.innerJoin(schema.achievement, eq(schema.userAchievement.achievementId, schema.achievement.id))
.where(and(eq(schema.userAchievement.userId, userId), ne(schema.achievement.rarity, "platinum")))
const [meta] = await db
.select({ value: count() })
.from(schema.userAchievement)
.innerJoin(
schema.achievement,
eq(schema.userAchievement.achievementId, schema.achievement.id),
)
.where(
and(
eq(schema.userAchievement.userId, userId),
ne(schema.achievement.rarity, "platinum"),
),
)
metrics.achievement_unlocked_count = meta?.value ?? 0
await db.update(schema.userStat).set({ metrics, updateTime: new Date().toISOString() })
await db
.update(schema.userStat)
.set({ metrics, updateTime: new Date().toISOString() })
.where(eq(schema.userStat.userId, userId))
return [...first, ...(await unlockAchievements(userId, metrics, true))]
}
@@ -175,22 +309,39 @@ const USER_ACHIEVEMENT_INSERT_CHUNK = 1000
*
*/
export async function rescanAchievement(achievementId: number) {
const [achievement] = await db.select().from(schema.achievement)
.where(and(eq(schema.achievement.id, achievementId), eq(schema.achievement.visible, true))).limit(1)
const [achievement] = await db
.select()
.from(schema.achievement)
.where(
and(
eq(schema.achievement.id, achievementId),
eq(schema.achievement.visible, true),
),
)
.limit(1)
if (!achievement) return { scanned: 0, unlocked: 0 }
const metric = findMetric(achievement.metric)
if (!metric) return { scanned: 0, unlocked: 0 }
// contest_joined 不由判题结算维护,扫之前先把它刷新一遍,否则永远读到旧值(或没有值)
if (achievement.metric === "contest_joined") await refreshContestJoinedForAll()
if (achievement.metric === "contest_joined")
await refreshContestJoinedForAll()
const already = new Set(
(await db.select({ userId: schema.userAchievement.userId }).from(schema.userAchievement)
.where(eq(schema.userAchievement.achievementId, achievement.id))).map((row) => row.userId),
(
await db
.select({ userId: schema.userAchievement.userId })
.from(schema.userAchievement)
.where(eq(schema.userAchievement.achievementId, achievement.id))
).map((row) => row.userId),
)
const stats = await db.select({ userId: schema.userStat.userId, metrics: schema.userStat.metrics })
const stats = await db
.select({
userId: schema.userStat.userId,
metrics: schema.userStat.metrics,
})
.from(schema.userStat)
const eligible = stats.filter((stat) => {
if (already.has(stat.userId)) return false
@@ -206,36 +357,116 @@ export async function rescanAchievement(achievementId: number) {
// 计数改成一次 +N,通知照旧逐人推(那是 Redis,不是数据库)。
const unlockTime = new Date().toISOString()
const unlockedUserIds: number[] = []
for (let start = 0; start < eligible.length; start += USER_ACHIEVEMENT_INSERT_CHUNK) {
for (
let start = 0;
start < eligible.length;
start += USER_ACHIEVEMENT_INSERT_CHUNK
) {
const chunk = eligible.slice(start, start + USER_ACHIEVEMENT_INSERT_CHUNK)
const inserted = await db.insert(schema.userAchievement).values(chunk.map((stat) => ({
userId: stat.userId,
achievementId: achievement.id,
unlockTime,
backfilled: true,
notified: false,
}))).onConflictDoNothing({ target: [schema.userAchievement.achievementId, schema.userAchievement.userId] })
const inserted = await db
.insert(schema.userAchievement)
.values(
chunk.map((stat) => ({
userId: stat.userId,
achievementId: achievement.id,
unlockTime,
backfilled: true,
notified: false,
})),
)
.onConflictDoNothing({
target: [
schema.userAchievement.achievementId,
schema.userAchievement.userId,
],
})
.returning({ userId: schema.userAchievement.userId })
unlockedUserIds.push(...inserted.map((row) => row.userId))
}
if (unlockedUserIds.length) {
await db.update(schema.achievement)
.set({ unlockCount: sql`${schema.achievement.unlockCount} + ${unlockedUserIds.length}` })
await db
.update(schema.achievement)
.set({
unlockCount: sql`${schema.achievement.unlockCount} + ${unlockedUserIds.length}`,
})
.where(eq(schema.achievement.id, achievement.id))
for (const userId of unlockedUserIds) {
await publishAchievementNotification(userId, [{
id: achievement.id,
name: achievement.name,
description: achievement.description,
icon: achievement.icon,
rarity: achievement.rarity,
kind: "achievement",
}])
await publishAchievementNotification(userId, [
{
id: achievement.id,
name: achievement.name,
description: achievement.description,
icon: achievement.icon,
rarity: achievement.rarity,
kind: "achievement",
},
])
}
// 补发的非白金成就同样计入「已解锁数」,要和判题结算一样接着做第二轮(元成就)判定。
// 旧 `rescan_achievement` 就漏了这步,OJ2 原样搬过来:2026-09-07 一次补发之后
// 269 人的计数停在旧值,其中 10 人实际够了「奖杯收藏家」却一直没发 ——
// 判题结算只在「这次有新解锁」时才重算,被补发的人不再解锁新成就就永远不会自愈。
if (
achievement.rarity !== "platinum" &&
achievement.metric !== "achievement_unlocked_count"
) {
await refreshUnlockedCount(unlockedUserIds)
for (const meta of await metaAchievements())
await rescanAchievement(meta.id)
}
}
return { scanned: stats.length, unlocked: unlockedUserIds.length }
}
/** 以「已解锁数」为指标的元成就(奖杯收藏家)。只取上架的,和 rescan 的口径一致 */
export function metaAchievements() {
return db
.select({
id: schema.achievement.id,
name: schema.achievement.name,
threshold: schema.achievement.threshold,
operator: schema.achievement.operator,
})
.from(schema.achievement)
.where(
and(
eq(schema.achievement.visible, true),
eq(schema.achievement.metric, "achievement_unlocked_count"),
),
)
}
/**
* `user_achievement` `achievement_unlocked_count` id
*
* **** `jsonb_set`
* `metrics`
* `userIds` `user_stat` `recount`
*/
export async function refreshUnlockedCount(userIds?: number[]) {
if (userIds && userIds.length === 0) return []
const scope = userIds ? sql`and s.user_id in ${userIds}` : sql``
const rows = await db.execute<{ user_id: number }>(sql`
update ${schema.userStat} as target
set metrics = jsonb_set(target.metrics, '{achievement_unlocked_count}', to_jsonb(fresh.value))
from (
select s.id, coalesce(c.value, 0) as value
from ${schema.userStat} s
left join (
select ua.user_id, count(*)::int as value
from ${schema.userAchievement} ua
join ${schema.achievement} a on a.id = ua.achievement_id
where a.rarity <> 'platinum'
group by ua.user_id
) c on c.user_id = s.user_id
where true ${scope}
) fresh
where target.id = fresh.id
and (target.metrics -> 'achievement_unlocked_count') is distinct from to_jsonb(fresh.value)
returning target.user_id
`)
return rows.map((row) => row.user_id)
}
/** 同上,3 个参数一行 */
const STAT_UPSERT_CHUNK = 1000
@@ -257,19 +488,25 @@ const STAT_UPSERT_CHUNK = 1000
*/
async function refreshContestJoinedForAll() {
const rows = await db
.select({ userId: schema.submission.userId, value: countDistinct(schema.submission.contestId) })
.select({
userId: schema.submission.userId,
value: countDistinct(schema.submission.contestId),
})
.from(schema.submission)
.where(isNotNull(schema.submission.contestId))
.groupBy(schema.submission.userId)
const now = new Date().toISOString()
for (let start = 0; start < rows.length; start += STAT_UPSERT_CHUNK) {
const chunk = rows.slice(start, start + STAT_UPSERT_CHUNK)
await db.insert(schema.userStat)
.values(chunk.map((row) => ({
userId: row.userId,
metrics: { contest_joined: row.value },
updateTime: now,
})))
await db
.insert(schema.userStat)
.values(
chunk.map((row) => ({
userId: row.userId,
metrics: { contest_joined: row.value },
updateTime: now,
})),
)
.onConflictDoUpdate({
target: schema.userStat.userId,
set: {
+96 -24
View File
@@ -5,56 +5,118 @@ interface ChatMessage {
content: string
}
function requestBody(messages: ChatMessage[], stream: boolean) {
function requestBody(messages: ChatMessage[], stream: boolean, json = false) {
return {
model: config.aiModel,
messages,
stream,
temperature: 0,
thinking: { type: "disabled" },
// DeepSeek 的 JSON 模式:保证回的是合法 JSON,但 prompt 里得出现「json」字样
...(json ? { response_format: { type: "json_object" } } : {}),
}
}
export async function completeChat(system: string, user: string) {
/**
* fetch AI worker
*
*
*/
const COMPLETE_TIMEOUT_MS = 60_000
export async function completeChat(
system: string,
user: string,
options: { json?: boolean; timeoutMs?: number } = {},
) {
if (!config.aiKey) throw new Error("缺少 AI_KEY")
const response = await fetch(new URL("/chat/completions", config.aiBaseUrl), {
method: "POST",
headers: { "content-type": "application/json", authorization: `Bearer ${config.aiKey}` },
body: JSON.stringify(requestBody([
{ role: "system", content: system },
{ role: "user", content: user },
], false)),
signal: AbortSignal.timeout(options.timeoutMs ?? COMPLETE_TIMEOUT_MS),
headers: {
"content-type": "application/json",
authorization: `Bearer ${config.aiKey}`,
},
body: JSON.stringify(
requestBody(
[
{ role: "system", content: system },
{ role: "user", content: user },
],
false,
options.json,
),
),
})
if (!response.ok) throw new Error(`AI provider returned HTTP ${response.status}: ${await response.text()}`)
const payload = await response.json() as { choices?: Array<{ message?: { content?: string } }> }
if (!response.ok)
throw new Error(
`AI provider returned HTTP ${response.status}: ${await response.text()}`,
)
const payload = (await response.json()) as {
choices?: Array<{ message?: { content?: string } }>
}
return payload.choices?.[0]?.message?.content?.trim() ?? ""
}
export interface StreamChatHooks {
/**
* ** `done` **
* 西 ai_hint id
*/
onComplete?: (value: string) => Promise<Record<string, unknown> | void>
/**
* AI_KEYprovider
*
*/
onError?: (message: string) => Promise<void>
}
export function streamChat(
system: string,
user: string,
onComplete?: (value: string) => Promise<void>,
hooks: StreamChatHooks = {},
) {
const encoder = new TextEncoder()
const reportError = (message: string) =>
hooks.onError?.(message).catch((error) => {
console.error("streamChat onError hook failed", error)
})
const body = new ReadableStream<Uint8Array>({
async start(controller) {
const send = (value: string) => controller.enqueue(encoder.encode(value))
if (!config.aiKey) {
send(`data: ${JSON.stringify({ type: "error", message: "缺少 AI_KEY" })}\n\n`)
await reportError("缺少 AI_KEY")
send(
`data: ${JSON.stringify({ type: "error", message: "缺少 AI_KEY" })}\n\n`,
)
send("event: end\n\n")
controller.close()
return
}
try {
const response = await fetch(new URL("/chat/completions", config.aiBaseUrl), {
method: "POST",
headers: { "content-type": "application/json", authorization: `Bearer ${config.aiKey}` },
body: JSON.stringify(requestBody([
{ role: "system", content: system },
{ role: "user", content: user },
], true)),
})
if (!response.ok || !response.body) throw new Error(`AI provider returned HTTP ${response.status}: ${await response.text()}`)
const response = await fetch(
new URL("/chat/completions", config.aiBaseUrl),
{
method: "POST",
headers: {
"content-type": "application/json",
authorization: `Bearer ${config.aiKey}`,
},
body: JSON.stringify(
requestBody(
[
{ role: "system", content: system },
{ role: "user", content: user },
],
true,
),
),
},
)
if (!response.ok || !response.body)
throw new Error(
`AI provider returned HTTP ${response.status}: ${await response.text()}`,
)
send("event: start\n\n")
const reader = response.body.getReader()
const decoder = new TextDecoder()
@@ -71,7 +133,12 @@ export function streamChat(
const data = line.slice(5).trim()
if (data === "[DONE]") continue
try {
const item = JSON.parse(data) as { choices?: Array<{ delta?: { content?: string }; finish_reason?: string | null }> }
const item = JSON.parse(data) as {
choices?: Array<{
delta?: { content?: string }
finish_reason?: string | null
}>
}
const choice = item.choices?.[0]
const content = choice?.delta?.content
if (content) {
@@ -85,10 +152,15 @@ export function streamChat(
if (done) break
}
const full = chunks.join("").trim()
if (onComplete) await onComplete(full)
send(`data: ${JSON.stringify({ type: "done" })}\n\n`)
const extra = hooks.onComplete
? await hooks.onComplete(full)
: undefined
send(`data: ${JSON.stringify({ ...extra, type: "done" })}\n\n`)
} catch (error) {
send(`data: ${JSON.stringify({ type: "error", message: error instanceof Error ? error.message : String(error) })}\n\n`)
const message = error instanceof Error ? error.message : String(error)
// 先留痕再回前端:客户端已经断开的话下面这个 send 自己也会抛
await reportError(message)
send(`data: ${JSON.stringify({ type: "error", message })}\n\n`)
} finally {
send("event: end\n\n")
controller.close()
+69 -39
View File
@@ -1,6 +1,6 @@
import { createHash } from "node:crypto"
import { and, eq } from "drizzle-orm"
import { eq } from "drizzle-orm"
import type { Context, MiddlewareHandler } from "hono"
import type { AppEnv } from "../auth/middleware"
@@ -29,29 +29,63 @@ export function contestStatus(contest: ContestRow) {
return "0" as const
}
export function isContestAdmin(user: AuthUser | null | undefined, contest: ContestRow) {
return Boolean(user && (user.id === contest.createdById || user.adminType === "Super Admin"))
export function isContestAdmin(
user: AuthUser | null | undefined,
contest: ContestRow,
) {
return Boolean(
user &&
(user.id === contest.createdById || user.adminType === "Super Admin"),
)
}
export function contestDetailsAllowed(user: AuthUser | null | undefined, contest: ContestRow) {
export function contestDetailsAllowed(
user: AuthUser | null | undefined,
contest: ContestRow,
) {
return contestStatus(contest) === "-1" || isContestAdmin(user, contest)
}
export function checkContestPassword(candidate: string | null | undefined, expected: string | null) {
export function checkContestPassword(
candidate: string | null | undefined,
expected: string | null,
) {
if (!candidate || !expected) return false
if (candidate === expected) return true
const parts = candidate.split("#")
if (parts.length !== 2) return false
const [signature, expiresAt] = parts
if (!signature || !expiresAt || !/^\d+$/.test(expiresAt)) return false
const expectedSignature = createHash("sha256").update(`${expected}${expiresAt}`).digest("hex").slice(0, 8)
return signature === expectedSignature && Date.now() < Number(expiresAt) * 1000
const expectedSignature = createHash("sha256")
.update(`${expected}${expiresAt}`)
.digest("hex")
.slice(0, 8)
return (
signature === expectedSignature && Date.now() < Number(expiresAt) * 1000
)
}
export async function findVisibleContest(id: number) {
const [contest] = await db.select().from(schema.contest)
.where(and(eq(schema.contest.id, id), eq(schema.contest.visible, true))).limit(1)
return contest ?? null
/**
* visible
* /
*
* visible 404
* **** visible
* admin/contest.ts
*
* 404
*/
export async function findAccessibleContest(
user: AuthUser | null | undefined,
id: number,
) {
const [contest] = await db
.select()
.from(schema.contest)
.where(eq(schema.contest.id, id))
.limit(1)
if (!contest) return null
return contest.visible || isContestAdmin(user, contest) ? contest : null
}
// 泛型而不是写死 Context<AppEnv>requireContestAccess 传进来的是 Context<ContestEnv>
@@ -62,16 +96,25 @@ export async function canAccessContest<E extends AppEnv>(
checkType: "details" | "problems" | "ranks" | "submissions",
) {
const user = c.get("user")
if (!user) return { ok: false as const, code: "login-required", message: "请先登录" }
if (!user)
return { ok: false as const, code: "login-required", message: "请先登录" }
if (isContestAdmin(user, contest)) return { ok: true as const }
if (contest.password) {
const stored = await getContestPassword(c, contest.id)
if (!checkContestPassword(stored, contest.password)) {
return { ok: false as const, code: "wrong-password", message: "Wrong password or password expired" }
return {
ok: false as const,
code: "wrong-password",
message: "Wrong password or password expired",
}
}
}
if (contestStatus(contest) === "1" && checkType !== "details") {
return { ok: false as const, code: "contest-not-started", message: "Contest has not started yet." }
return {
ok: false as const,
code: "contest-not-started",
message: "Contest has not started yet.",
}
}
return { ok: true as const }
}
@@ -93,35 +136,22 @@ export function requireContestAccess(
): MiddlewareHandler<ContestEnv> {
return async (c, next) => {
const id = Number(c.req.param(paramName))
const contest = Number.isInteger(id) && id > 0 ? await findVisibleContest(id) : null
if (!contest) return failure(c, 404, "contest-not-found", "Contest does not exist")
const contest =
Number.isInteger(id) && id > 0
? await findAccessibleContest(c.get("user"), id)
: null
if (!contest)
return failure(c, 404, "contest-not-found", "Contest does not exist")
const access = await canAccessContest(c, contest, checkType)
if (!access.ok) {
return failure(c, access.code === "login-required" ? 401 : 403, access.code, access.message)
return failure(
c,
access.code === "login-required" ? 401 : 403,
access.code,
access.message,
)
}
c.set("contest", contest)
await next()
}
}
function ipv4Number(value: string) {
const parts = value.split(".").map(Number)
if (parts.length !== 4 || parts.some((part) => !Number.isInteger(part) || part < 0 || part > 255)) return null
return parts.reduce((result, part) => (result * 256 + part) >>> 0, 0)
}
export function ipAllowed(ip: string | null, ranges: unknown) {
if (!Array.isArray(ranges) || ranges.length === 0) return true
if (!ip) return false
const target = ipv4Number(ip.replace(/^::ffff:/, ""))
if (target === null) return false
return ranges.some((raw) => {
const value = typeof raw === "string" ? raw : raw && typeof raw === "object" ? String((raw as { value?: unknown }).value ?? "") : ""
const [address, prefixText = "32"] = value.split("/")
const network = ipv4Number(address ?? "")
const prefix = Number(prefixText)
if (network === null || !Number.isInteger(prefix) || prefix < 0 || prefix > 32) return false
const mask = prefix === 0 ? 0 : (0xffffffff << (32 - prefix)) >>> 0
return (target & mask) === (network & mask)
})
}

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