diff --git a/server/.env.example b/server/.env.example new file mode 100644 index 0000000..baeba14 --- /dev/null +++ b/server/.env.example @@ -0,0 +1,31 @@ +# The API starts without this variable, but data endpoints return HTTP 503. +# DATABASE_URL=postgres://username:password@hostname:5432/teaching_feedback?sslmode=require + +HOST=127.0.0.1 +PORT=8080 +DATABASE_MAX_CONNECTIONS=5 + +# A single development origin. Leave unset to disable CORS middleware. +# CORS_ALLOWED_ORIGIN=https://servicewechat.com + +# Private server directory used to retain uploaded audio for transcription retry. +AUDIO_STORAGE_DIR=./data/audio + +# Local FunASR is the default Chinese transcription provider. +ASR_PROVIDER=local +LOCAL_ASR_URL=http://127.0.0.1:10095 +ASR_REQUEST_TIMEOUT_SECONDS=1800 +ASR_WORKER_CONCURRENCY=1 +ASR_JOB_LEASE_SECONDS=3600 + +# Optional Tencent Cloud fallback. Set ASR_PROVIDER=tencent and configure all values. +# TENCENT_CLOUD_ASR_APP_ID=1234567890 +# TENCENT_CLOUD_ASR_SECRET_ID=your-secret-id +# TENCENT_CLOUD_ASR_SECRET_KEY=your-secret-key +TENCENT_CLOUD_ASR_ENGINE_TYPE=16k_zh + +# Optional OpenAI-compatible chat completions endpoint for polished feedback summaries. +# Without it, the API uses a local extractive summary and remains functional. +# FEEDBACK_SUMMARY_API_URL=https://api.example.com/v1/chat/completions +# FEEDBACK_SUMMARY_API_KEY=your-api-key +# FEEDBACK_SUMMARY_MODEL=your-model diff --git a/server/.gitignore b/server/.gitignore new file mode 100644 index 0000000..c10ee8c --- /dev/null +++ b/server/.gitignore @@ -0,0 +1,11 @@ +# Rust build output +/target/ +/data/ + +# Local configuration and secrets +.env +.env.* +!.env.example + +# Graphify generated knowledge graphs +/graphify-out/ diff --git a/server/API.md b/server/API.md new file mode 100644 index 0000000..0289534 --- /dev/null +++ b/server/API.md @@ -0,0 +1,131 @@ +# 教学反馈助手 API + +## 交互文档 + +服务启动后提供以下文档入口: + +- Scalar:`GET /scalar` +- OpenAPI JSON:`GET /openapi.json` +- 完整调用流程:[API_GUIDE.md](./API_GUIDE.md) + +Scalar 中的业务接口已预填开发用户 ID 和请求体示例。创建、列表、预设和健康检查可以直接发起请求;按 ID 操作时,应使用创建或列表接口返回的真实 ID。 + +## 启动和数据库策略 + +本服务不会创建或启动本地 PostgreSQL。 + +- 未设置 `DATABASE_URL` 时,`cargo run` 只启动 HTTP 服务;`GET /health` 返回成功,数据接口返回 `503`。 +- 获得远程 PostgreSQL 地址后,将其写入本地未提交的 `server/.env`,执行 `cargo run --bin migrate`,再执行 `cargo run`。 +- 迁移不会使用 PostgreSQL 扩展,UUID 由 Rust 服务生成。 + +```bash +cd server +cp .env.example .env +# 在 .env 中填写 DATABASE_URL +cargo run --bin migrate +cargo run +``` + +## 语音转录和反馈汇总 + +长短录音统一通过小程序原生录音器上传到本服务。服务先将音频保存在 `AUDIO_STORAGE_DIR` 并立即响应,再由持久化后台队列调用本地 FunASR;模型暂时不可用或 API 重启都不会丢失已上传音频。 + +```text +AUDIO_STORAGE_DIR=./data/audio +ASR_PROVIDER=local +LOCAL_ASR_URL=http://127.0.0.1:10095 +ASR_REQUEST_TIMEOUT_SECONDS=1800 +ASR_WORKER_CONCURRENCY=1 +ASR_JOB_LEASE_SECONDS=3600 +``` + +在项目根目录执行 `docker compose -f compose.asr.yml up --build -d` 启动中文模型。`GET /health` 中 `speech_available=true` 表示模型已下载并可以接收任务。 + +腾讯云仅作为可选提供方保留。需要切换时配置: + +```text +ASR_PROVIDER=tencent +TENCENT_CLOUD_ASR_APP_ID=1234567890 +TENCENT_CLOUD_ASR_SECRET_ID=your-secret-id +TENCENT_CLOUD_ASR_SECRET_KEY=your-secret-key +TENCENT_CLOUD_ASR_ENGINE_TYPE=16k_zh +``` + +反馈汇总支持可选的 OpenAI 兼容 Chat Completions 接口。未配置时使用本地抽取式汇总,录音转录和保存流程仍可工作: + +```text +FEEDBACK_SUMMARY_API_URL=https://api.example.com/v1/chat/completions +FEEDBACK_SUMMARY_API_KEY=your-api-key +FEEDBACK_SUMMARY_MODEL=your-model +``` + +## 临时身份边界 + +目前所有业务接口都要求 `X-User-Id` 请求头,值为 UUID。例如: + +```text +X-User-Id: 5a4da7f0-d70c-465f-bcab-124c504aa9f0 +``` + +这是微信登录接入完成前的开发身份边界,用于确保每位教师只能访问自己的记录。接入微信登录后,后端会从登录凭据解析用户身份,客户端不再直接提供此请求头。 + +## 接口 + +| 方法 | 路径 | 说明 | +| --- | --- | --- | +| `GET` | `/health` | 服务、数据库、语音提供方及模型可用状态。 | +| `GET` | `/api/v1/profiles` | 列出学生档案;可选 `query`、`grade`、`subject` 参数。 | +| `POST` | `/api/v1/profiles` | 创建学生档案。 | +| `GET` | `/api/v1/profiles/{profile_id}` | 读取单个学生档案。 | +| `PUT` | `/api/v1/profiles/{profile_id}` | 更新学生档案。 | +| `DELETE` | `/api/v1/profiles/{profile_id}` | 删除学生档案。 | +| `GET` | `/api/v1/profile-defaults` | 读取学生档案预设;未配置时返回美术课默认值。 | +| `PUT` | `/api/v1/profile-defaults` | 写入年级、学科和上课时长预设。 | +| `GET` | `/api/v1/feedback-records` | 列出反馈记录;可选 `profile_id` 参数。 | +| `POST` | `/api/v1/feedback-records` | 创建反馈记录。 | +| `DELETE` | `/api/v1/feedback-records/{record_id}` | 删除反馈记录。 | +| `GET` | `/api/v1/feedback-sessions/active` | 读取指定学生进行中的语音反馈批次。 | +| `POST` | `/api/v1/feedback-sessions` | 创建或恢复语音反馈批次。 | +| `PUT` | `/api/v1/feedback-sessions/{session_id}` | 自动保存反馈正文和日期。 | +| `POST` | `/api/v1/feedback-sessions/{session_id}/lessons` | 开始下一节课堂录音。 | +| `POST` | `/api/v1/feedback-lessons/{lesson_id}/segments` | 上传一个自动切分的片段并加入后台转录队列。 | +| `POST` | `/api/v1/feedback-lessons/{lesson_id}/finish` | 结束课节并汇总片段状态。 | +| `POST` | `/api/v1/feedback-lessons/{lesson_id}/mark-applied` | 标记短录音文字已直接加入反馈。 | +| `POST` | `/api/v1/audio-segments/{segment_id}/retry` | 重试失败片段的转录。 | +| `POST` | `/api/v1/feedback-sessions/{session_id}/generate` | 汇总多节转录并生成反馈正文。 | + +### 创建学生档案 + +```json +{ + "name": "小谢", + "grade": "艺术类", + "subject": "美术", + "academic_year": 2026, + "term": "暑", + "guardian_title": "小谢妈妈", + "start_time": "18:00", + "end_time": "19:00" +} +``` + +### 保存默认预设 + +```json +{ + "grade": "艺术类", + "subject": "美术", + "lesson_duration_minutes": 60 +} +``` + +### 创建反馈记录 + +```json +{ + "profile_id": "5fa5af2c-cfc9-4bb8-b0b3-8715f080b167", + "feedback_date": "2026-07-14", + "content": "今天完成了色彩搭配练习,构图有明显进步。", + "feedback_session_id": null +} +``` diff --git a/server/API_GUIDE.md b/server/API_GUIDE.md new file mode 100644 index 0000000..3e1af0f --- /dev/null +++ b/server/API_GUIDE.md @@ -0,0 +1,128 @@ +# 教学反馈助手 API 使用指南 + +## 1. 启动服务 + +先在项目根目录启动中文转录服务: + +```bash +docker compose -f compose.asr.yml up --build -d +``` + +在 `server/.env` 中配置 `DATABASE_URL` 后执行: + +```bash +cd server +cargo run --bin migrate +cargo run +``` + +默认地址取决于 `.env` 中的 `HOST` 和 `PORT`。使用示例配置时,可访问: + +- Scalar 交互文档: +- OpenAPI JSON: +- 健康检查: + +如果未配置 `DATABASE_URL`,服务仍可启动并访问健康检查和 API 文档,但业务接口返回 `503`。 + +## 2. 在 Scalar 中直接测试 + +打开 `/scalar`,选择接口后点击 **Test Request**。业务接口已经预填以下开发用户 ID: + +```text +X-User-Id: 5a4da7f0-d70c-465f-bcab-124c504aa9f0 +``` + +请求体接口也已提供可发送的默认 JSON。建议按以下顺序测试: + +1. 执行 `GET /health`,确认 `database_configured` 和 `speech_available` 均为 `true`。首次模型下载期间后者为 `false`。 +2. 执行 `GET /api/v1/profile-defaults`,即使用户未保存过预设也会返回系统默认值。 +3. 执行 `PUT /api/v1/profile-defaults`,可直接发送预填的美术课预设。 +4. 执行 `POST /api/v1/profiles`,可直接发送预填档案;保存响应中的 `id`。 +5. 将真实档案 `id` 填入 `{profile_id}`,测试单条查询、更新或删除。 +6. 执行 `POST /api/v1/feedback-records`。默认 `profile_id` 和 `feedback_session_id` 为 `null`,无需档案或录音即可直接创建。 +7. 如需关联档案,将第 4 步得到的 `id` 写入 `profile_id`。创建后保存反馈响应中的 `id`。 +8. 将真实反馈 `id` 填入 `{record_id}`,测试删除接口。 + +OpenAPI 中的 `11111111-...` 和 `22222222-...` 仅用于展示路径参数格式,并不是数据库预置记录。调用按 ID 查询、更新或删除的接口时,必须换成创建或列表接口返回的真实 ID。 + +## 3. 常用请求示例 + +### 健康检查 + +```bash +curl http://127.0.0.1:8080/health +``` + +### 创建学生档案 + +```bash +curl -X POST http://127.0.0.1:8080/api/v1/profiles \ + -H 'Content-Type: application/json' \ + -H 'X-User-Id: 5a4da7f0-d70c-465f-bcab-124c504aa9f0' \ + -d '{ + "name": "小谢", + "grade": "艺术类", + "subject": "美术", + "academic_year": 2026, + "term": "暑", + "guardian_title": "小谢妈妈", + "start_time": "18:00", + "end_time": "19:00" + }' +``` + +### 创建不关联档案的反馈 + +```bash +curl -X POST http://127.0.0.1:8080/api/v1/feedback-records \ + -H 'Content-Type: application/json' \ + -H 'X-User-Id: 5a4da7f0-d70c-465f-bcab-124c504aa9f0' \ + -d '{ + "profile_id": null, + "feedback_date": "2026-07-15", + "content": "今天完成了色彩搭配练习,构图有明显进步。", + "feedback_session_id": null + }' +``` + +### 筛选反馈记录 + +```bash +curl 'http://127.0.0.1:8080/api/v1/feedback-records?profile_id=<真实档案ID>' \ + -H 'X-User-Id: 5a4da7f0-d70c-465f-bcab-124c504aa9f0' +``` + +## 4. 身份和数据隔离 + +当前尚未接入微信登录,所有业务接口临时使用 `X-User-Id` 标识用户。相同 UUID 可以访问自己创建的数据,不同 UUID 之间的数据互相不可见。 + +`X-User-Id` 缺失时返回 `401`,格式不是 UUID 时返回 `400`。接入微信登录后,应由后端根据登录凭据确定用户身份,客户端不再直接提交该请求头。 + +小程序开发客户端当前使用同一个测试 UUID,并默认连接 `http://127.0.0.1:8080`。可在小程序“我的”页面修改 API 地址并执行健康检查。真机或正式环境应使用已配置为微信 request 合法域名的 HTTPS 地址。 + +## 5. 响应状态码 + +| 状态码 | 含义 | +| --- | --- | +| `200` | 查询或更新成功 | +| `201` | 创建成功 | +| `204` | 删除成功,无响应体 | +| `400` | 参数格式或业务校验失败 | +| `401` | 缺少 `X-User-Id` | +| `404` | 记录不存在或不属于当前用户 | +| `500` | 数据库查询或服务内部错误 | +| `503` | 未配置数据库连接 | + +错误响应统一为: + +```json +{ + "error": "错误说明" +} +``` + +录音上传接口在音频入库后立即返回 `processing`。Rust 后台工作线程会调用 FunASR,并将片段更新为 `ready` 或 `failed`;小程序会自动刷新状态,短录音转写完成后仍会直接加入反馈正文。 + +## 6. OpenAPI 维护方式 + +`/openapi.json` 在服务运行时由 `utoipa` 根据 Rust 路由注解生成,Scalar 使用同一份规范。新增或修改接口时,需要同时更新处理函数上的 `#[utoipa::path]`、请求/响应 schema 注释和示例;规范完整性测试会检查操作数量、接口说明和默认身份参数。 diff --git a/server/Cargo.lock b/server/Cargo.lock new file mode 100644 index 0000000..b79f207 --- /dev/null +++ b/server/Cargo.lock @@ -0,0 +1,2729 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "aho-corasick" +version = "1.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301" +dependencies = [ + "memchr", +] + +[[package]] +name = "allocator-api2" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" + +[[package]] +name = "android_system_properties" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311" +dependencies = [ + "libc", +] + +[[package]] +name = "atoi" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f28d99ec8bfea296261ca1af174f24225171fea9664ba9003cbebee704810528" +dependencies = [ + "num-traits", +] + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "axum" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90" +dependencies = [ + "axum-core", + "axum-macros", + "bytes", + "form_urlencoded", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-util", + "itoa", + "matchit", + "memchr", + "mime", + "multer", + "percent-encoding", + "pin-project-lite", + "serde_core", + "serde_json", + "serde_path_to_error", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tower", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "axum-core" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "mime", + "pin-project-lite", + "sync_wrapper", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "axum-macros" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7aa268c23bfbbd2c4363b9cd302a4f504fb2a9dfe7e3451d66f35dd392e20aca" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "base64ct" +version = "1.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" + +[[package]] +name = "bitflags" +version = "2.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4388bee8683e3d04af747c73422af53102d2bd24d9eadb6cbc100baef4b43f8" +dependencies = [ + "serde_core", +] + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + +[[package]] +name = "byteorder" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + +[[package]] +name = "cc" +version = "1.2.67" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e17dd265a7d0f31ef544e1b20e03add05d3b45b491b633b10d67145d2acc1a38" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" + +[[package]] +name = "cfg_aliases" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724" + +[[package]] +name = "chacha20" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d524456ba66e72eb8b115ff89e01e497f8e6d11d78b70b1aa13c0fbd97540a81" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.0", + "rand_core 0.10.1", +] + +[[package]] +name = "chrono" +version = "0.4.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" +dependencies = [ + "iana-time-zone", + "js-sys", + "num-traits", + "serde", + "wasm-bindgen", + "windows-link", +] + +[[package]] +name = "concurrent-queue" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "const-oid" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "cpufeatures" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b2a41393f66f16b0823bb79094d54ac5fbd34ab292ddafb9a0456ac9f87d201" +dependencies = [ + "libc", +] + +[[package]] +name = "crc" +version = "3.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5eb8a2a1cd12ab0d987a5d5e825195d372001a4094a0376319d5a0ad71c1ba0d" +dependencies = [ + "crc-catalog", +] + +[[package]] +name = "crc-catalog" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "217698eaf96b4a3f0bc4f3662aaa55bdf913cd54d7204591faa790070c6d0853" + +[[package]] +name = "crossbeam-queue" +version = "0.3.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "803d13fb3b09d88be9f4dbc29062c66b19bf7170867ceb746d2a8689bf6c7a26" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61803da095bee82a81bb1a452ecc25d3b2f1416d1897eb86430c6159ef717c17" + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "der" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" +dependencies = [ + "const-oid", + "pem-rfc7468", + "zeroize", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "const-oid", + "crypto-common", + "subtle", +] + +[[package]] +name = "displaydoc" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ac70aa55017e108007fbaf5aa0f54b021c98f92ff8af59d42eda9da96e3dd4f" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "dotenvy" +version = "0.15.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aaf95b3e5c8f23aa320147307562d361db0ae0d51242340f558153b4eb2439b" + +[[package]] +name = "either" +version = "1.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91622ff5e7162018101f2fea40d6ebf4a78bbe5a49736a2020649edf9693679e" +dependencies = [ + "serde", +] + +[[package]] +name = "encoding_rs" +version = "0.8.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75030f3c4f45dafd7586dd6780965a8c7e8e285a5ecb86713e63a79c5b2766f3" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "equivalent" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "etcetera" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "136d1b5283a1ab77bd9257427ffd09d8667ced0570b6f938942bc7568ed5b943" +dependencies = [ + "cfg-if", + "home", + "windows-sys 0.48.0", +] + +[[package]] +name = "event-listener" +version = "5.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13b66accf52311f30a0db42147dadea9850cb48cd070028831ae5f5d4b856ab" +dependencies = [ + "concurrent-queue", + "parking", + "pin-project-lite", +] + +[[package]] +name = "find-msvc-tools" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582" + +[[package]] +name = "flume" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da0e4dd2a88388a1f4ccc7c9ce104604dab68d9f408dc34cd45823d5a9069095" +dependencies = [ + "futures-core", + "futures-sink", + "spin", +] + +[[package]] +name = "foldhash" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "futures-channel" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07bbe89c50d7a535e539b8c17bc0b49bdb77747034daa8087407d655f3f7cc1d" +dependencies = [ + "futures-core", + "futures-sink", +] + +[[package]] +name = "futures-core" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e3450815272ef58cec6d564423f6e755e25379b217b0bc688e295ba24df6b1d" + +[[package]] +name = "futures-executor" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baf29c38818342a3b26b5b923639e7b1f4a61fc5e76102d4b1981c6dc7a7579d" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-intrusive" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d930c203dd0b6ff06e0201a4a2fe9149b43c684fd4420555b26d21b1a02956f" +dependencies = [ + "futures-core", + "lock_api", + "parking_lot", +] + +[[package]] +name = "futures-io" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cecba35d7ad927e23624b22ad55235f2239cfa44fd10428eecbeba6d6a717718" + +[[package]] +name = "futures-sink" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c39754e157331b013978ec91992bde1ac089843443c49cbc7f46150b0fad0893" + +[[package]] +name = "futures-task" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "037711b3d59c33004d3856fbdc83b99d4ff37a24768fa1be9ce3538a1cde4393" + +[[package]] +name = "futures-util" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "389ca41296e6190b48053de0321d02a77f32f8a5d2461dd38762c0593805c6d6" +dependencies = [ + "futures-core", + "futures-io", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "slab", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "wasi", + "wasm-bindgen", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "r-efi", + "rand_core 0.10.1", + "wasm-bindgen", +] + +[[package]] +name = "hashbrown" +version = "0.15.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" +dependencies = [ + "allocator-api2", + "equivalent", + "foldhash", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[package]] +name = "hashlink" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7382cf6263419f2d8df38c55d7da83da5c18aef87fc7a7fc1fb1e344edfe14c1" +dependencies = [ + "hashbrown 0.15.5", +] + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + +[[package]] +name = "hkdf" +version = "0.12.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b5f8eb2ad728638ea2c7d47a21db23b7b58a72ed6a38256b8a1849f15fbbdf7" +dependencies = [ + "hmac", +] + +[[package]] +name = "hmac" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" +dependencies = [ + "digest", +] + +[[package]] +name = "home" +version = "0.5.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589533453244b0995c858700322199b2becb13b627df2851f64a2775d024abcf" +dependencies = [ + "windows-sys 0.59.0", +] + +[[package]] +name = "http" +version = "1.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6970f50e31d6fc17d3fa27329444bfa74e196cf62e95052a3f6fee181dba6425" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e9f41fd6a08e4d4ec69df65976da761afd5ad5e58a9d4acb46bd1c953a9e3ff2" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "httpdate" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" + +[[package]] +name = "hyper" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "55281c53a1894c864990125767da440a4e630446785086f52523b20033b74498" +dependencies = [ + "atomic-waker", + "bytes", + "futures-channel", + "futures-core", + "http", + "http-body", + "httparse", + "httpdate", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", + "want", +] + +[[package]] +name = "hyper-rustls" +version = "0.27.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33ca68d021ef39cf6463ab54c1d0f5daf03377b70561305bb89a8f83aab66e0f" +dependencies = [ + "http", + "hyper", + "hyper-util", + "rustls", + "tokio", + "tokio-rustls", + "tower-service", + "webpki-roots 1.0.8", +] + +[[package]] +name = "hyper-util" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0" +dependencies = [ + "base64", + "bytes", + "futures-channel", + "futures-util", + "http", + "http-body", + "hyper", + "ipnet", + "libc", + "percent-encoding", + "pin-project-lite", + "socket2", + "tokio", + "tower-service", + "tracing", +] + +[[package]] +name = "iana-time-zone" +version = "0.1.65" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "log", + "wasm-bindgen", + "windows-core", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" +dependencies = [ + "cc", +] + +[[package]] +name = "icu_collections" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c6b649701667bbe825c3b7e6388cb521c23d88644678e83c0c4d0a621a34b43" +dependencies = [ + "displaydoc", + "potential_utf", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edba7861004dd3714265b4db54a3c390e880ab658fec5f7db895fae2046b5bb6" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5f6c8828b67bf8908d82127b2054ea1b4427ff0230ee9141c54251934ab1b599" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7aedcccd01fc5fe81e6b489c15b247b8b0690feb23304303a9e560f37efc560a" + +[[package]] +name = "icu_properties" +version = "2.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "020bfc02fe870ec3a66d93e677ccca0562506e5872c650f893269e08615d74ec" +dependencies = [ + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "616c294cf8d725c6afcd8f55abc17c56464ef6211f9ed59cccffe534129c77af" + +[[package]] +name = "icu_provider" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85962cf0ce02e1e0a629cc34e7ca3e373ce20dda4c4d7294bbd0bf1fdb59e614" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3acae9609540aa318d1bc588455225fb2085b9ed0c4f6bd0d9d5bcd86f1a0344" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "indexmap" +version = "2.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9" +dependencies = [ + "equivalent", + "hashbrown 0.17.1", + "serde", + "serde_core", +] + +[[package]] +name = "ipnet" +version = "2.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d98f6fed1fde3f8c21bc40a1abb88dd75e67924f9cffc3ef95607bad8017f8e2" + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "js-sys" +version = "0.3.103" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53b44bfcdb3f8d5837a46dae1ca9660a837176eee74a28b229bc626816589102" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "lazy_static" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" +dependencies = [ + "spin", +] + +[[package]] +name = "libc" +version = "0.2.186" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66" + +[[package]] +name = "libm" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" + +[[package]] +name = "libredox" +version = "0.1.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c943259e342f1e06ff2da7a83eabdfe7f92ce10262688dbf1895ff0b3e6e4652" +dependencies = [ + "bitflags", + "libc", + "plain", + "redox_syscall 0.9.0", +] + +[[package]] +name = "libsqlite3-sys" +version = "0.30.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e99fb7a497b1e3339bc746195567ed8d3e24945ecd636e3619d20b9de9e9149" +dependencies = [ + "pkg-config", + "vcpkg", +] + +[[package]] +name = "litemap" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92daf443525c4cce67b150400bc2316076100ce0b3686209eb8cf3c31612e6f0" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad" + +[[package]] +name = "lru-slab" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154" + +[[package]] +name = "matchers" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9" +dependencies = [ + "regex-automata", +] + +[[package]] +name = "matchit" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3" + +[[package]] +name = "md-5" +version = "0.10.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf" +dependencies = [ + "cfg-if", + "digest", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "mime" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" + +[[package]] +name = "mime_guess" +version = "2.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f7c44f8e672c00fe5308fa235f821cb4198414e1c77935c1ab6948d3fd78550e" +dependencies = [ + "mime", + "unicase", +] + +[[package]] +name = "mio" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "30d65c71f1ce40ab09135ce117d742b9f8a19ff91a41a8b57ed50bc2de59c427" +dependencies = [ + "libc", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "multer" +version = "3.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83e87776546dc87511aa5ee218730c92b666d7264ab6ed41f9d215af9cd5224b" +dependencies = [ + "bytes", + "encoding_rs", + "futures-util", + "http", + "httparse", + "memchr", + "mime", + "spin", + "version_check", +] + +[[package]] +name = "nu-ansi-term" +version = "0.50.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "num-bigint-dig" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e661dda6640fad38e827a6d4a310ff4763082116fe217f279885c97f511bb0b7" +dependencies = [ + "lazy_static", + "libm", + "num-integer", + "num-iter", + "num-traits", + "rand 0.8.7", + "smallvec", + "zeroize", +] + +[[package]] +name = "num-integer" +version = "0.1.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7969661fd2958a5cb096e56c8e1ad0444ac2bbcd0061bd28660485a44879858f" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-iter" +version = "0.1.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c92800bd69a1eac91786bcfe9da64a897eb72911b8dc3095decbd07429e8048b" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", + "libm", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "parking" +version = "2.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba" + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall 0.5.18", + "smallvec", + "windows-link", +] + +[[package]] +name = "paste" +version = "1.0.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a" + +[[package]] +name = "pem-rfc7468" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88b39c9bfcfc231068454382784bb460aae594343fb030d46e9f50a645418412" +dependencies = [ + "base64ct", +] + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "pkcs1" +version = "0.7.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8ffb9f10fa047879315e6625af03c164b16962a5368d724ed16323b68ace47f" +dependencies = [ + "der", + "pkcs8", + "spki", +] + +[[package]] +name = "pkcs8" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7" +dependencies = [ + "der", + "spki", +] + +[[package]] +name = "pkg-config" +version = "0.3.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19f132c84eca552bf34cab8ec81f1c1dcc229b811638f9d283dceabe58c5569e" + +[[package]] +name = "plain" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6" + +[[package]] +name = "potential_utf" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0103b1cef7ec0cf76490e969665504990193874ea05c85ff9bab8b911d0a0564" +dependencies = [ + "zerovec", +] + +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + +[[package]] +name = "proc-macro2" +version = "1.0.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quinn" +version = "0.11.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c1a41e437b6bbd489372cd4971de128e85c855f56c57f283d20ff016cf7c0a8" +dependencies = [ + "bytes", + "cfg_aliases", + "pin-project-lite", + "quinn-proto", + "quinn-udp", + "rustc-hash", + "rustls", + "socket2", + "thiserror", + "tokio", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-proto" +version = "0.11.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f4bfc015262b9df63c8845072ce59068853ff5872180c2ce2f13038b970e560" +dependencies = [ + "bytes", + "getrandom 0.4.3", + "lru-slab", + "rand 0.10.2", + "rand_pcg", + "ring", + "rustc-hash", + "rustls", + "rustls-pki-types", + "slab", + "thiserror", + "tinyvec", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-udp" +version = "0.5.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "35a133f956daabe89a61a685c2649f13d82d5aa4bd5d12d1277e1072a21c0694" +dependencies = [ + "cfg_aliases", + "libc", + "once_cell", + "socket2", + "tracing", + "windows-sys 0.61.2", +] + +[[package]] +name = "quote" +version = "1.0.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfbc457d0c7a0759a614551b11a6409e5951f6c7537be1f1b7682b9ae9230368" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rand" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22f6172bdec972074665ed81ed53b71da00bfc44b65a753cfde883ec4c702a1a" +dependencies = [ + "libc", + "rand_chacha", + "rand_core 0.6.4", +] + +[[package]] +name = "rand" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7f5fa3a058cd35567ef9bfa5e75732bee0f9e4c55fa90477bef2dfcdbc4be80" +dependencies = [ + "chacha20", + "getrandom 0.4.3", + "rand_core 0.10.1", +] + +[[package]] +name = "rand_chacha" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" +dependencies = [ + "ppv-lite86", + "rand_core 0.6.4", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom 0.2.17", +] + +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + +[[package]] +name = "rand_pcg" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "caa0f4137e1c0a72f4c651489402276c8e8e1cf081f3b0ba156d2cbeef09e86a" +dependencies = [ + "rand_core 0.10.1", +] + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags", +] + +[[package]] +name = "redox_syscall" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c5102a6aaa05aa011a238e178e6bca86d2cb56fc9f586d37cb80f5bca6e07759" +dependencies = [ + "bitflags", +] + +[[package]] +name = "regex-automata" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f388202e4b80542a0921078cc23b6333bcf1409c1e3f86404cae4766a6131db" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + +[[package]] +name = "reqwest" +version = "0.12.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147" +dependencies = [ + "base64", + "bytes", + "futures-core", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-util", + "js-sys", + "log", + "mime_guess", + "percent-encoding", + "pin-project-lite", + "quinn", + "rustls", + "rustls-pki-types", + "serde", + "serde_json", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tokio-rustls", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "webpki-roots 1.0.8", +] + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "rsa" +version = "0.9.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8573f03f5883dcaebdfcf4725caa1ecb9c15b2ef50c43a07b816e06799bb12d" +dependencies = [ + "const-oid", + "digest", + "num-bigint-dig", + "num-integer", + "num-traits", + "pkcs1", + "pkcs8", + "rand_core 0.6.4", + "signature", + "spki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustc-hash" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" + +[[package]] +name = "rustls" +version = "0.23.42" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c54fcab019b409d04215d3a17cb438fd7fbf192ee61461f20f4fe18704bc138" +dependencies = [ + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "764899a24af3980067ee14bc143654f297b22eaebfe3c7b6b211920a5a59b046" +dependencies = [ + "web-time", + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61c429a8649f110dddef65e2a5ad240f747e85f7758a6bccc7e5777bd33f756e" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "serde" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.150" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8014e44b4736ed0538adeecded0fce2a272f22dc9578a7eb6b2d9993c74cfb9" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_path_to_error" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457" +dependencies = [ + "itoa", + "serde", + "serde_core", +] + +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "sha1" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "digest", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "digest", +] + +[[package]] +name = "sharded-slab" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" +dependencies = [ + "lazy_static", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "signature" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" +dependencies = [ + "digest", + "rand_core 0.6.4", +] + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.15.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ed6a63f02c8539c91a8685a86f4099661ba3da017932f6ebbea6de3f0fa7c90" +dependencies = [ + "serde", +] + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "spin" +version = "0.9.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e" +dependencies = [ + "lock_api", +] + +[[package]] +name = "spki" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d" +dependencies = [ + "base64ct", + "der", +] + +[[package]] +name = "sqlx" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fefb893899429669dcdd979aff487bd78f4064e5e7907e4269081e0ef7d97dc" +dependencies = [ + "sqlx-core", + "sqlx-macros", + "sqlx-mysql", + "sqlx-postgres", + "sqlx-sqlite", +] + +[[package]] +name = "sqlx-core" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee6798b1838b6a0f69c007c133b8df5866302197e404e8b6ee8ed3e3a5e68dc6" +dependencies = [ + "base64", + "bytes", + "chrono", + "crc", + "crossbeam-queue", + "either", + "event-listener", + "futures-core", + "futures-intrusive", + "futures-io", + "futures-util", + "hashbrown 0.15.5", + "hashlink", + "indexmap", + "log", + "memchr", + "once_cell", + "percent-encoding", + "rustls", + "serde", + "serde_json", + "sha2", + "smallvec", + "thiserror", + "tokio", + "tokio-stream", + "tracing", + "url", + "uuid", + "webpki-roots 0.26.11", +] + +[[package]] +name = "sqlx-macros" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2d452988ccaacfbf5e0bdbc348fb91d7c8af5bee192173ac3636b5fb6e6715d" +dependencies = [ + "proc-macro2", + "quote", + "sqlx-core", + "sqlx-macros-core", + "syn", +] + +[[package]] +name = "sqlx-macros-core" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19a9c1841124ac5a61741f96e1d9e2ec77424bf323962dd894bdb93f37d5219b" +dependencies = [ + "dotenvy", + "either", + "heck", + "hex", + "once_cell", + "proc-macro2", + "quote", + "serde", + "serde_json", + "sha2", + "sqlx-core", + "sqlx-mysql", + "sqlx-postgres", + "sqlx-sqlite", + "syn", + "tokio", + "url", +] + +[[package]] +name = "sqlx-mysql" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa003f0038df784eb8fecbbac13affe3da23b45194bd57dba231c8f48199c526" +dependencies = [ + "atoi", + "base64", + "bitflags", + "byteorder", + "bytes", + "chrono", + "crc", + "digest", + "dotenvy", + "either", + "futures-channel", + "futures-core", + "futures-io", + "futures-util", + "generic-array", + "hex", + "hkdf", + "hmac", + "itoa", + "log", + "md-5", + "memchr", + "once_cell", + "percent-encoding", + "rand 0.8.7", + "rsa", + "serde", + "sha1", + "sha2", + "smallvec", + "sqlx-core", + "stringprep", + "thiserror", + "tracing", + "uuid", + "whoami", +] + +[[package]] +name = "sqlx-postgres" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db58fcd5a53cf07c184b154801ff91347e4c30d17a3562a635ff028ad5deda46" +dependencies = [ + "atoi", + "base64", + "bitflags", + "byteorder", + "chrono", + "crc", + "dotenvy", + "etcetera", + "futures-channel", + "futures-core", + "futures-util", + "hex", + "hkdf", + "hmac", + "home", + "itoa", + "log", + "md-5", + "memchr", + "once_cell", + "rand 0.8.7", + "serde", + "serde_json", + "sha2", + "smallvec", + "sqlx-core", + "stringprep", + "thiserror", + "tracing", + "uuid", + "whoami", +] + +[[package]] +name = "sqlx-sqlite" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2d12fe70b2c1b4401038055f90f151b78208de1f9f89a7dbfd41587a10c3eea" +dependencies = [ + "atoi", + "chrono", + "flume", + "futures-channel", + "futures-core", + "futures-executor", + "futures-intrusive", + "futures-util", + "libsqlite3-sys", + "log", + "percent-encoding", + "serde", + "serde_urlencoded", + "sqlx-core", + "thiserror", + "tracing", + "url", + "uuid", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "stringprep" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b4df3d392d81bd458a8a621b8bffbd2302a12ffe288a9d931670948749463b1" +dependencies = [ + "unicode-bidi", + "unicode-normalization", + "unicode-properties", +] + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "syn" +version = "2.0.118" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b9ae57f904213ebb649ce6895b8a66c66f0203b9319718f69a5612a065b1422" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +dependencies = [ + "futures-core", +] + +[[package]] +name = "synstructure" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "teaching-feedback-api" +version = "0.1.0" +dependencies = [ + "axum", + "base64", + "chrono", + "dotenvy", + "hmac", + "reqwest", + "serde", + "serde_json", + "sha1", + "sqlx", + "thiserror", + "tokio", + "tower-http", + "tracing", + "tracing-subscriber", + "url", + "utoipa", + "utoipa-axum", + "utoipa-scalar", + "uuid", +] + +[[package]] +name = "thiserror" +version = "2.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "thread_local" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "tinystr" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8323304221c2a851516f22236c5722a72eaa19749016521d6dff0824447d96d" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tinyvec" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb4ebadaa0af04fab11ae01eb5f9fdb5f9c5b875506e210e71c07873528baa7f" +dependencies = [ + "tinyvec_macros", +] + +[[package]] +name = "tinyvec_macros" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" + +[[package]] +name = "tokio" +version = "1.52.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fc7f01b389ac15039e4dc9531aa973a135d7a4135281b12d7c1bc79fd57fffe" +dependencies = [ + "bytes", + "libc", + "mio", + "pin-project-lite", + "signal-hook-registry", + "socket2", + "tokio-macros", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-macros" +version = "2.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "385a6cb71ab9ab790c5fe8d67f1645e6c450a7ce006a33de03daa956cf70a496" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "tokio-rustls" +version = "0.26.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1729aa945f29d91ba541258c8df89027d5792d85a8841fb65e8bf0f4ede4ef61" +dependencies = [ + "rustls", + "tokio", +] + +[[package]] +name = "tokio-stream" +version = "0.1.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32da49809aab5c3bc678af03902d4ccddea2a87d028d86392a4b1560c6906c70" +dependencies = [ + "futures-core", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "tower-http" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" +dependencies = [ + "bitflags", + "bytes", + "futures-util", + "http", + "http-body", + "pin-project-lite", + "tower", + "tower-layer", + "tower-service", + "tracing", + "url", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "log", + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", + "valuable", +] + +[[package]] +name = "tracing-log" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3" +dependencies = [ + "log", + "once_cell", + "tracing-core", +] + +[[package]] +name = "tracing-subscriber" +version = "0.3.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319" +dependencies = [ + "matchers", + "nu-ansi-term", + "once_cell", + "regex-automata", + "sharded-slab", + "smallvec", + "thread_local", + "tracing", + "tracing-core", + "tracing-log", +] + +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unicase" +version = "2.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75b844d17643ee918803943289730bec8aac480150456169e647ed0b576ba539" + +[[package]] +name = "unicode-bidi" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5" + +[[package]] +name = "unicode-ident" +version = "1.0.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" + +[[package]] +name = "unicode-normalization" +version = "0.1.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5fd4f6878c9cb28d874b009da9e8d183b5abc80117c40bbd187a1fde336be6e8" +dependencies = [ + "tinyvec", +] + +[[package]] +name = "unicode-properties" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7df058c713841ad818f1dc5d3fd88063241cc61f49f5fbea4b951e8cf5a8d71d" + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf8_iter" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + +[[package]] +name = "utoipa" +version = "5.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8bde15df68e80b16c7d16b9616e80770ad158988daa56a27dccd1e55558b0160" +dependencies = [ + "indexmap", + "serde", + "serde_json", + "utoipa-gen", +] + +[[package]] +name = "utoipa-axum" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c25bae5bccc842449ec0c5ddc5cbb6a3a1eaeac4503895dc105a1138f8234a0" +dependencies = [ + "axum", + "paste", + "tower-layer", + "tower-service", + "utoipa", +] + +[[package]] +name = "utoipa-gen" +version = "5.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ba0b99ee52df3028635d93840c797102da61f8a7bb3cf751032455895b52ef8" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "uuid", +] + +[[package]] +name = "utoipa-scalar" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59559e1509172f6b26c1cdbc7247c4ddd1ac6560fe94b584f81ee489b141f719" +dependencies = [ + "axum", + "serde", + "serde_json", + "utoipa", +] + +[[package]] +name = "uuid" +version = "1.23.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea5fab0d6c3c01ae70085a09cb03d4c7a1d6314e2b3e075392783396d724ca0a" +dependencies = [ + "getrandom 0.4.3", + "js-sys", + "serde_core", + "wasm-bindgen", +] + +[[package]] +name = "valuable" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" + +[[package]] +name = "vcpkg" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "want" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e" +dependencies = [ + "try-lock", +] + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasite" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8dad83b4f25e74f184f64c43b150b91efe7647395b42289f38e50566d82855b" + +[[package]] +name = "wasm-bindgen" +version = "0.2.126" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b067c0c11094aef6b7a801c1e34a26affafdf3d051dba08456b868789aaf9a4" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.76" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c62df1340f32221cb9c54d6a27b030e3dba64361d4a95bed55f9aacb44da291d" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.126" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "167ce5e579f6bcf889c4f7175a8a5a585de84e8ff93976ce393efa5f2837aab1" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.126" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3997c7839262f4ef12cf90b818d6340c18e80f263f1a94bf157d0ec4420380e" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.126" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc1b4cb0cc549fcf58d7dfc081778139b3d283a081644e833e84682ad71cea24" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "web-sys" +version = "0.3.103" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8622dcb61c0bcc9fffa6938bed81210af2da9a7e4a1a834b2e37a59b6dfb6141" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "webpki-roots" +version = "0.26.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9" +dependencies = [ + "webpki-roots 1.0.8", +] + +[[package]] +name = "webpki-roots" +version = "1.0.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf85cb06032201fa7c6f829d7db5a7e5aa45bcc0655327713065f6f0576731bf" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "whoami" +version = "1.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d4a4db5077702ca3015d3d02d74974948aba2ad9e12ab7df718ee64ccd7e97d" +dependencies = [ + "libredox", + "wasite", +] + +[[package]] +name = "windows-core" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-implement" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "windows-interface" +version = "0.59.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-sys" +version = "0.48.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9" +dependencies = [ + "windows-targets 0.48.5", +] + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-sys" +version = "0.59.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" +dependencies = [ + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c" +dependencies = [ + "windows_aarch64_gnullvm 0.48.5", + "windows_aarch64_msvc 0.48.5", + "windows_i686_gnu 0.48.5", + "windows_i686_msvc 0.48.5", + "windows_x86_64_gnu 0.48.5", + "windows_x86_64_gnullvm 0.48.5", + "windows_x86_64_msvc 0.48.5", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm 0.52.6", + "windows_aarch64_msvc 0.52.6", + "windows_i686_gnu 0.52.6", + "windows_i686_gnullvm", + "windows_i686_msvc 0.52.6", + "windows_x86_64_gnu 0.52.6", + "windows_x86_64_gnullvm 0.52.6", + "windows_x86_64_msvc 0.52.6", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8" + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "writeable" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ffae5123b2d3fc086436f8834ae3ab053a283cfac8fe0a0b8eaae044768a4c4" + +[[package]] +name = "yoke" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "synstructure", +] + +[[package]] +name = "zerocopy" +version = "0.8.54" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7cbbc0a705a0fd05cc3676525980d2bf5a9bc4adac6d6475209a7887cf59d19" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.54" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2e817b7b52d0c7358d3246da9d69935ebb18116b2b102b4230dac079b4862f5" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11532158c46691caf0f2593ea8358fed6bbf68a0315e80aae9bd41fbade684a1" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e" + +[[package]] +name = "zerotrie" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f9152d31db0792fa83f70fb2f83148effb5c1f5b8c7686c3459e361d9bc20bf" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "90f911cbc359ab6af17377d242225f4d75119aec87ea711a880987b18cd7b239" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "625dc425cab0dca6dc3c3319506e6593dcb08a9f387ea3b284dbd52a92c40555" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/server/Cargo.toml b/server/Cargo.toml new file mode 100644 index 0000000..e976154 --- /dev/null +++ b/server/Cargo.toml @@ -0,0 +1,28 @@ +[package] +name = "teaching-feedback-api" +version = "0.1.0" +edition = "2024" +rust-version = "1.85" +default-run = "teaching-feedback-api" + +[dependencies] +axum = { version = "0.8", features = ["macros", "multipart"] } +base64 = "0.22" +chrono = { version = "0.4", features = ["serde"] } +dotenvy = "0.15" +hmac = "0.12" +reqwest = { version = "0.12", default-features = false, features = ["json", "multipart", "rustls-tls"] } +serde = { version = "1", features = ["derive"] } +serde_json = "1" +sha1 = "0.10" +sqlx = { version = "0.8", default-features = false, features = ["runtime-tokio-rustls", "postgres", "chrono", "uuid", "migrate", "macros"] } +thiserror = "2" +tokio = { version = "1", features = ["fs", "macros", "rt-multi-thread", "net", "signal"] } +tower-http = { version = "0.6", features = ["cors", "trace"] } +tracing = "0.1" +tracing-subscriber = { version = "0.3", features = ["env-filter"] } +url = "2" +utoipa = { version = "5.5", features = ["chrono", "uuid"] } +utoipa-axum = "0.2" +utoipa-scalar = { version = "0.3", features = ["axum"] } +uuid = { version = "1", features = ["serde", "v4"] } diff --git a/server/migrations/0001_initial_schema.sql b/server/migrations/0001_initial_schema.sql new file mode 100644 index 0000000..0bafb6f --- /dev/null +++ b/server/migrations/0001_initial_schema.sql @@ -0,0 +1,45 @@ +CREATE TABLE student_profiles ( + id UUID PRIMARY KEY, + owner_id UUID NOT NULL, + name VARCHAR(20) NOT NULL CHECK (char_length(btrim(name)) BETWEEN 1 AND 20), + grade VARCHAR(40) NOT NULL CHECK (char_length(btrim(grade)) > 0), + subject VARCHAR(40) NOT NULL CHECK (char_length(btrim(subject)) > 0), + academic_year SMALLINT NOT NULL CHECK (academic_year BETWEEN 2000 AND 2200), + term VARCHAR(1) NOT NULL CHECK (term IN ('春', '暑', '秋', '寒')), + guardian_title VARCHAR(24) NOT NULL CHECK (char_length(btrim(guardian_title)) BETWEEN 1 AND 24), + start_time CHAR(5) NOT NULL, + end_time CHAR(5) NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT now() +); + +CREATE INDEX student_profiles_owner_updated_idx + ON student_profiles (owner_id, updated_at DESC); + +CREATE INDEX student_profiles_owner_grade_subject_idx + ON student_profiles (owner_id, grade, subject); + +CREATE TABLE student_profile_defaults ( + owner_id UUID PRIMARY KEY, + grade VARCHAR(40) NOT NULL CHECK (char_length(btrim(grade)) > 0), + subject VARCHAR(40) NOT NULL CHECK (char_length(btrim(subject)) > 0), + lesson_duration_minutes SMALLINT NOT NULL + CHECK (lesson_duration_minutes BETWEEN 15 AND 360 AND lesson_duration_minutes % 15 = 0), + updated_at TIMESTAMPTZ NOT NULL DEFAULT now() +); + +CREATE TABLE feedback_records ( + id UUID PRIMARY KEY, + owner_id UUID NOT NULL, + profile_id UUID REFERENCES student_profiles(id) ON DELETE SET NULL, + feedback_date DATE NOT NULL, + content TEXT NOT NULL CHECK (char_length(btrim(content)) > 0), + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT now() +); + +CREATE INDEX feedback_records_owner_date_idx + ON feedback_records (owner_id, feedback_date DESC, updated_at DESC); + +CREATE INDEX feedback_records_owner_profile_idx + ON feedback_records (owner_id, profile_id); diff --git a/server/migrations/0002_voice_feedback_sessions.sql b/server/migrations/0002_voice_feedback_sessions.sql new file mode 100644 index 0000000..d0bd60f --- /dev/null +++ b/server/migrations/0002_voice_feedback_sessions.sql @@ -0,0 +1,57 @@ +CREATE TABLE feedback_sessions ( + id UUID PRIMARY KEY, + owner_id UUID NOT NULL, + profile_id UUID REFERENCES student_profiles(id) ON DELETE CASCADE, + feedback_date DATE NOT NULL, + content TEXT NOT NULL DEFAULT '', + status VARCHAR(16) NOT NULL DEFAULT 'active' + CHECK (status IN ('active', 'finalized')), + finalized_record_id UUID REFERENCES feedback_records(id) ON DELETE SET NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT now() +); + +CREATE INDEX feedback_sessions_owner_status_idx + ON feedback_sessions (owner_id, status, updated_at DESC); + +CREATE UNIQUE INDEX feedback_sessions_one_active_idx + ON feedback_sessions (owner_id, COALESCE(profile_id, '00000000-0000-0000-0000-000000000000'::UUID)) + WHERE status = 'active'; + +CREATE TABLE lesson_sessions ( + id UUID PRIMARY KEY, + feedback_session_id UUID NOT NULL REFERENCES feedback_sessions(id) ON DELETE CASCADE, + sequence INTEGER NOT NULL CHECK (sequence > 0), + status VARCHAR(16) NOT NULL DEFAULT 'recording' + CHECK (status IN ('recording', 'processing', 'ready', 'failed')), + duration_ms INTEGER NOT NULL DEFAULT 0 CHECK (duration_ms >= 0), + applied_directly BOOLEAN NOT NULL DEFAULT FALSE, + included_in_generation BOOLEAN NOT NULL DEFAULT FALSE, + started_at TIMESTAMPTZ NOT NULL DEFAULT now(), + ended_at TIMESTAMPTZ, + updated_at TIMESTAMPTZ NOT NULL DEFAULT now(), + UNIQUE (feedback_session_id, sequence) +); + +CREATE INDEX lesson_sessions_feedback_session_idx + ON lesson_sessions (feedback_session_id, sequence); + +CREATE TABLE audio_segments ( + id UUID PRIMARY KEY, + lesson_session_id UUID NOT NULL REFERENCES lesson_sessions(id) ON DELETE CASCADE, + sequence INTEGER NOT NULL CHECK (sequence > 0), + duration_ms INTEGER NOT NULL CHECK (duration_ms > 0), + audio_format VARCHAR(8) NOT NULL, + audio_path TEXT NOT NULL, + status VARCHAR(16) NOT NULL DEFAULT 'processing' + CHECK (status IN ('processing', 'ready', 'failed')), + transcript TEXT, + error_message TEXT, + provider_request_id VARCHAR(100), + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT now(), + UNIQUE (lesson_session_id, sequence) +); + +CREATE INDEX audio_segments_lesson_session_idx + ON audio_segments (lesson_session_id, sequence); diff --git a/server/migrations/0003_async_transcription_jobs.sql b/server/migrations/0003_async_transcription_jobs.sql new file mode 100644 index 0000000..1f05673 --- /dev/null +++ b/server/migrations/0003_async_transcription_jobs.sql @@ -0,0 +1,8 @@ +ALTER TABLE audio_segments + ADD COLUMN transcription_attempts INTEGER NOT NULL DEFAULT 0 + CHECK (transcription_attempts >= 0), + ADD COLUMN processing_started_at TIMESTAMPTZ; + +CREATE INDEX audio_segments_processing_queue_idx + ON audio_segments (created_at, id) + WHERE status = 'processing'; diff --git a/server/src/bin/migrate.rs b/server/src/bin/migrate.rs new file mode 100644 index 0000000..0bad08b --- /dev/null +++ b/server/src/bin/migrate.rs @@ -0,0 +1,17 @@ +use sqlx::{migrate::Migrator, postgres::PgPoolOptions}; + +static MIGRATOR: Migrator = sqlx::migrate!("./migrations"); + +#[tokio::main] +async fn main() -> Result<(), Box> { + dotenvy::dotenv().ok(); + let database_url = std::env::var("DATABASE_URL") + .map_err(|_| "DATABASE_URL is required before running migrations")?; + let pool = PgPoolOptions::new() + .max_connections(1) + .connect(&database_url) + .await?; + MIGRATOR.run(&pool).await?; + println!("PostgreSQL migrations completed"); + Ok(()) +} diff --git a/server/src/config.rs b/server/src/config.rs new file mode 100644 index 0000000..6cf8a67 --- /dev/null +++ b/server/src/config.rs @@ -0,0 +1,167 @@ +use std::{env, net::IpAddr, path::PathBuf}; + +#[derive(Debug, Clone)] +pub enum SpeechProviderConfig { + Local { api_url: String }, + Tencent(TencentSpeechConfig), +} + +#[derive(Debug, Clone)] +pub struct TencentSpeechConfig { + pub app_id: u64, + pub secret_id: String, + pub secret_key: String, + pub engine_type: String, +} + +#[derive(Debug, Clone)] +pub struct SpeechConfig { + pub provider: SpeechProviderConfig, + pub request_timeout_seconds: u64, + pub worker_concurrency: usize, + pub job_lease_seconds: i64, +} + +#[derive(Debug, Clone)] +pub struct SummaryConfig { + pub api_url: String, + pub api_key: Option, + pub model: String, +} + +#[derive(Debug, Clone)] +pub struct Config { + pub host: IpAddr, + pub port: u16, + pub database_url: Option, + pub database_max_connections: u32, + pub cors_allowed_origin: Option, + pub audio_storage_dir: PathBuf, + pub speech: Option, + pub summary: Option, +} + +impl Config { + pub fn from_env() -> Result { + let host = env::var("HOST") + .unwrap_or_else(|_| "127.0.0.1".to_owned()) + .parse() + .map_err(|_| "HOST must be a valid IP address".to_owned())?; + let port = env::var("PORT") + .unwrap_or_else(|_| "8080".to_owned()) + .parse() + .map_err(|_| "PORT must be a valid u16 value".to_owned())?; + let database_max_connections = env::var("DATABASE_MAX_CONNECTIONS") + .unwrap_or_else(|_| "5".to_owned()) + .parse() + .map_err(|_| "DATABASE_MAX_CONNECTIONS must be a valid u32 value".to_owned())?; + + let speech = speech_config()?; + let summary = summary_config()?; + + Ok(Self { + host, + port, + database_url: env::var("DATABASE_URL") + .ok() + .filter(|value| !value.trim().is_empty()), + database_max_connections, + cors_allowed_origin: env::var("CORS_ALLOWED_ORIGIN") + .ok() + .filter(|value| !value.trim().is_empty()), + audio_storage_dir: env::var("AUDIO_STORAGE_DIR") + .map(PathBuf::from) + .unwrap_or_else(|_| PathBuf::from("./data/audio")), + speech, + summary, + }) + } +} + +fn speech_config() -> Result, String> { + let provider = optional_env("ASR_PROVIDER").unwrap_or_else(|| "local".to_owned()); + if matches!(provider.as_str(), "disabled" | "none") { + return Ok(None); + } + + let provider = match provider.as_str() { + "local" | "funasr" => SpeechProviderConfig::Local { + api_url: optional_env("LOCAL_ASR_URL") + .unwrap_or_else(|| "http://127.0.0.1:10095".to_owned()) + .trim_end_matches('/') + .to_owned(), + }, + "tencent" => { + let app_id = required_env("TENCENT_CLOUD_ASR_APP_ID")? + .parse() + .map_err(|_| "TENCENT_CLOUD_ASR_APP_ID must be an integer".to_owned())?; + SpeechProviderConfig::Tencent(TencentSpeechConfig { + app_id, + secret_id: required_env("TENCENT_CLOUD_ASR_SECRET_ID")?, + secret_key: required_env("TENCENT_CLOUD_ASR_SECRET_KEY")?, + engine_type: optional_env("TENCENT_CLOUD_ASR_ENGINE_TYPE") + .unwrap_or_else(|| "16k_zh".to_owned()), + }) + } + _ => { + return Err( + "ASR_PROVIDER must be local, funasr, tencent, disabled, or none".to_owned(), + ); + } + }; + + let request_timeout_seconds = parse_env("ASR_REQUEST_TIMEOUT_SECONDS", 1_800_u64)?; + let worker_concurrency = parse_env("ASR_WORKER_CONCURRENCY", 1_usize)?; + let job_lease_seconds = parse_env("ASR_JOB_LEASE_SECONDS", 3_600_i64)?; + if request_timeout_seconds == 0 { + return Err("ASR_REQUEST_TIMEOUT_SECONDS must be greater than 0".to_owned()); + } + if worker_concurrency == 0 { + return Err("ASR_WORKER_CONCURRENCY must be greater than 0".to_owned()); + } + if job_lease_seconds <= 0 { + return Err("ASR_JOB_LEASE_SECONDS must be greater than 0".to_owned()); + } + + Ok(Some(SpeechConfig { + provider, + request_timeout_seconds, + worker_concurrency, + job_lease_seconds, + })) +} + +fn summary_config() -> Result, String> { + let Some(api_url) = optional_env("FEEDBACK_SUMMARY_API_URL") else { + return Ok(None); + }; + let model = optional_env("FEEDBACK_SUMMARY_MODEL").ok_or_else(|| { + "FEEDBACK_SUMMARY_MODEL is required when summary API is configured".to_owned() + })?; + Ok(Some(SummaryConfig { + api_url: api_url.trim_end_matches('/').to_owned(), + api_key: optional_env("FEEDBACK_SUMMARY_API_KEY"), + model, + })) +} + +fn optional_env(name: &str) -> Option { + env::var(name) + .ok() + .map(|value| value.trim().to_owned()) + .filter(|value| !value.is_empty()) +} + +fn required_env(name: &str) -> Result { + optional_env(name).ok_or_else(|| format!("{name} is required for the selected ASR provider")) +} + +fn parse_env(name: &str, default: T) -> Result +where + T: std::str::FromStr, +{ + optional_env(name).map_or_else( + || Ok(default), + |value| value.parse().map_err(|_| format!("{name} is invalid")), + ) +} diff --git a/server/src/error.rs b/server/src/error.rs new file mode 100644 index 0000000..3d821ac --- /dev/null +++ b/server/src/error.rs @@ -0,0 +1,96 @@ +use axum::{ + Json, + http::StatusCode, + response::{IntoResponse, Response}, +}; +use serde::Serialize; +use utoipa::{IntoResponses, ToSchema}; + +#[derive(Debug, thiserror::Error)] +pub enum ApiError { + #[error("{0}")] + BadRequest(String), + #[error("authentication is required")] + Unauthorized, + #[error("resource not found")] + NotFound, + #[error("database has not been configured")] + DatabaseUnavailable, + #[error("{0}")] + ServiceUnavailable(String), + #[error("internal server error")] + Internal, +} + +/// API 错误响应。 +#[derive(Serialize, ToSchema)] +#[schema(example = json!({"error": "resource not found"}))] +pub struct ErrorBody { + /// 面向调用方的错误信息。 + pub error: String, +} + +/// 所有需要数据库和临时用户身份的业务接口都可能返回的公共错误。 +#[allow(dead_code)] +#[derive(IntoResponses)] +pub enum CommonApiErrors { + /// 参数格式或业务校验失败。 + #[response( + status = 400, + description = "请求参数无效", + example = json!({"error": "X-User-Id must be a UUID"}) + )] + BadRequest(ErrorBody), + /// 缺少 `X-User-Id` 请求头。 + #[response( + status = 401, + description = "缺少开发阶段身份请求头", + example = json!({"error": "authentication is required"}) + )] + Unauthorized(ErrorBody), + /// 服务未配置数据库连接。 + #[response( + status = 503, + description = "未配置 DATABASE_URL", + example = json!({"error": "database has not been configured"}) + )] + DatabaseUnavailable(ErrorBody), + /// 数据库查询或服务内部处理失败。 + #[response( + status = 500, + description = "服务内部错误", + example = json!({"error": "internal server error"}) + )] + Internal(ErrorBody), +} + +impl IntoResponse for ApiError { + fn into_response(self) -> Response { + let (status, message) = match self { + Self::BadRequest(message) => (StatusCode::BAD_REQUEST, message), + Self::Unauthorized => ( + StatusCode::UNAUTHORIZED, + "authentication is required".to_owned(), + ), + Self::NotFound => (StatusCode::NOT_FOUND, "resource not found".to_owned()), + Self::DatabaseUnavailable => ( + StatusCode::SERVICE_UNAVAILABLE, + "database has not been configured".to_owned(), + ), + Self::ServiceUnavailable(message) => (StatusCode::SERVICE_UNAVAILABLE, message), + Self::Internal => ( + StatusCode::INTERNAL_SERVER_ERROR, + "internal server error".to_owned(), + ), + }; + + (status, Json(ErrorBody { error: message })).into_response() + } +} + +impl From for ApiError { + fn from(error: sqlx::Error) -> Self { + tracing::error!(?error, "database query failed"); + Self::Internal + } +} diff --git a/server/src/main.rs b/server/src/main.rs new file mode 100644 index 0000000..2d76a9d --- /dev/null +++ b/server/src/main.rs @@ -0,0 +1,100 @@ +mod config; +mod error; +mod recording_routes; +mod routes; +mod speech; +mod summary; +mod transcription_worker; + +use std::{path::PathBuf, sync::Arc}; + +use axum::{Json, Router, extract::DefaultBodyLimit, http::HeaderValue, routing::get}; +use config::Config; +use sqlx::{PgPool, postgres::PgPoolOptions}; +use tower_http::{cors::CorsLayer, trace::TraceLayer}; +use tracing_subscriber::EnvFilter; +use utoipa_scalar::{Scalar, Servable}; + +#[derive(Clone)] +pub struct AppState { + pub pool: Option, + pub audio_storage_dir: PathBuf, + pub speech: speech::SpeechService, + pub summary: summary::SummaryService, +} + +#[tokio::main] +async fn main() -> Result<(), Box> { + dotenvy::dotenv().ok(); + tracing_subscriber::fmt() + .with_env_filter(EnvFilter::try_from_default_env().unwrap_or_else(|_| "info".into())) + .init(); + + let config = Config::from_env().map_err(std::io::Error::other)?; + let pool = connect_database(&config).await?; + let speech = speech::SpeechService::new(config.speech.clone()); + let state = AppState { + pool, + audio_storage_dir: config.audio_storage_dir.clone(), + speech: speech.clone(), + summary: summary::SummaryService::new(config.summary.clone()), + }; + if let Some(pool) = state.pool.clone() + && speech.configured() + { + transcription_worker::spawn(pool, speech); + } + let app = build_app(state, config.cors_allowed_origin.as_deref())?; + let address = std::net::SocketAddr::from((config.host, config.port)); + let listener = tokio::net::TcpListener::bind(address).await?; + + tracing::info!(%address, scalar = %format!("http://{address}/scalar"), "API server is listening"); + axum::serve(listener, app) + .with_graceful_shutdown(shutdown_signal()) + .await?; + Ok(()) +} + +pub fn build_app(state: AppState, cors_allowed_origin: Option<&str>) -> Result { + let (api_router, openapi) = routes::router(); + let openapi_json = openapi.clone(); + let mut app = api_router + .route( + "/openapi.json", + get(move || { + let openapi = openapi_json.clone(); + async move { Json(openapi) } + }), + ) + .merge(Scalar::with_url("/scalar", openapi)) + .with_state(Arc::new(state)) + .layer(DefaultBodyLimit::max(20 * 1024 * 1024)) + .layer(TraceLayer::new_for_http()); + + if let Some(origin) = cors_allowed_origin { + let allowed_origin = HeaderValue::from_str(origin) + .map_err(|_| "CORS_ALLOWED_ORIGIN must be a valid HTTP header value".to_owned())?; + app = app.layer(CorsLayer::new().allow_origin(allowed_origin)); + } + + Ok(app) +} + +async fn connect_database(config: &Config) -> Result, sqlx::Error> { + let Some(database_url) = &config.database_url else { + tracing::warn!("DATABASE_URL is not set; data endpoints will return HTTP 503"); + return Ok(None); + }; + + let pool = PgPoolOptions::new() + .max_connections(config.database_max_connections) + .connect(database_url) + .await?; + tracing::info!("connected to PostgreSQL"); + Ok(Some(pool)) +} + +async fn shutdown_signal() { + let _ = tokio::signal::ctrl_c().await; + tracing::info!("shutdown signal received"); +} diff --git a/server/src/recording_routes.rs b/server/src/recording_routes.rs new file mode 100644 index 0000000..83fbb71 --- /dev/null +++ b/server/src/recording_routes.rs @@ -0,0 +1,957 @@ +use std::{collections::HashMap, sync::Arc}; + +use axum::{ + Json, + extract::{Multipart, Path, Query, State}, + http::HeaderMap, +}; +use chrono::{DateTime, NaiveDate, Utc}; +use serde::{Deserialize, Serialize}; +use sqlx::{FromRow, PgPool}; +use utoipa::ToSchema; +use utoipa_axum::{router::OpenApiRouter, routes}; +use uuid::Uuid; + +use crate::{ + AppState, + error::{ApiError, CommonApiErrors, ErrorBody}, +}; + +type SharedState = Arc; + +const MAX_AUDIO_UPLOAD_BYTES: usize = 15 * 1024 * 1024; +const MAX_SEGMENT_DURATION_MS: i32 = 600_000; +const SHORT_RECORDING_DURATION_MS: i32 = 60_000; +const SHORT_TRANSCRIPT_CHARS: usize = 600; + +pub fn router() -> OpenApiRouter { + OpenApiRouter::new() + .routes(routes!(get_active_feedback_session)) + .routes(routes!(ensure_feedback_session)) + .routes(routes!(update_feedback_session)) + .routes(routes!(create_lesson_session)) + .routes(routes!(upload_audio_segment)) + .routes(routes!(finish_lesson_session)) + .routes(routes!(mark_lesson_applied)) + .routes(routes!(retry_audio_segment)) + .routes(routes!(generate_feedback_content)) +} + +#[derive(Debug, Deserialize)] +struct ActiveSessionQuery { + profile_id: Option, +} + +#[derive(Debug, Deserialize, ToSchema)] +#[schema(example = json!({ + "profile_id": "11111111-1111-4111-8111-111111111111", + "feedback_date": "2026-07-16", + "content": "" +}))] +struct FeedbackSessionInput { + profile_id: Option, + feedback_date: NaiveDate, + #[serde(default)] + content: String, +} + +#[derive(Debug, Deserialize, ToSchema)] +struct FeedbackSessionUpdateInput { + feedback_date: NaiveDate, + content: String, +} + +#[derive(Debug, FromRow)] +struct FeedbackSessionRow { + id: Uuid, + profile_id: Option, + feedback_date: NaiveDate, + content: String, + status: String, + created_at: DateTime, + updated_at: DateTime, +} + +#[derive(Debug, FromRow)] +struct LessonRow { + id: Uuid, + sequence: i32, + status: String, + duration_ms: i32, + applied_directly: bool, + included_in_generation: bool, + started_at: DateTime, + ended_at: Option>, +} + +#[derive(Debug, FromRow)] +struct SegmentRow { + id: Uuid, + lesson_session_id: Uuid, + sequence: i32, + duration_ms: i32, + status: String, + error_message: Option, +} + +#[derive(Debug, Serialize, ToSchema)] +struct FeedbackSessionResponse { + id: Uuid, + profile_id: Option, + feedback_date: NaiveDate, + content: String, + status: String, + lesson_count: usize, + total_duration_ms: i64, + processing_segment_count: usize, + failed_segment_count: usize, + needs_generation: bool, + lessons: Vec, + created_at: DateTime, + updated_at: DateTime, +} + +#[derive(Debug, Serialize, ToSchema)] +struct LessonSummaryResponse { + id: Uuid, + sequence: i32, + status: String, + duration_ms: i32, + applied_directly: bool, + included_in_generation: bool, + segments: Vec, + started_at: DateTime, + ended_at: Option>, +} + +#[derive(Debug, Serialize, ToSchema)] +struct AudioSegmentResponse { + id: Uuid, + sequence: i32, + duration_ms: i32, + status: String, + error_message: Option, +} + +#[derive(Debug, Serialize, ToSchema)] +struct LessonCreatedResponse { + id: Uuid, + sequence: i32, + status: String, + started_at: DateTime, +} + +#[derive(Debug, Serialize, ToSchema)] +struct FinishedLessonResponse { + id: Uuid, + status: String, + duration_ms: i32, + transcript: String, + can_apply_directly: bool, +} + +#[derive(Debug, Deserialize, ToSchema)] +struct GenerateFeedbackInput { + #[schema(example = "学生本周构图更加稳定。")] + existing_content: String, +} + +#[derive(Debug, Deserialize, ToSchema)] +struct MarkLessonAppliedInput { + content: String, +} + +#[derive(Debug, Serialize, ToSchema)] +struct GenerateFeedbackResponse { + content: String, + method: String, +} + +#[derive(Debug, ToSchema)] +#[allow(dead_code)] +struct AudioSegmentUpload { + sequence: i32, + duration_ms: i32, + audio_format: String, + audio: String, +} + +#[utoipa::path( + get, + path = "/api/v1/feedback-sessions/active", + tag = "语音反馈", + summary = "读取进行中的反馈批次", + description = "读取当前用户指定学生下尚未保存的反馈批次;profile_id 留空时读取不关联学生的批次。", + params( + ("X-User-Id" = Uuid, Header, description = "开发阶段用户 ID", example = json!("5a4da7f0-d70c-465f-bcab-124c504aa9f0")), + ("profile_id" = Option, Query, description = "学生档案 ID;留空表示不关联学生") + ), + responses( + (status = 200, description = "进行中的反馈批次;不存在时返回 null", body = Option), + CommonApiErrors + ) +)] +async fn get_active_feedback_session( + State(state): State, + headers: HeaderMap, + Query(query): Query, +) -> Result>, ApiError> { + let owner_id = current_user(&headers)?; + let session = sqlx::query_as::<_, FeedbackSessionRow>( + "SELECT id, profile_id, feedback_date, content, status, created_at, updated_at \ + FROM feedback_sessions \ + WHERE owner_id = $1 AND profile_id IS NOT DISTINCT FROM $2 AND status = 'active' \ + ORDER BY updated_at DESC LIMIT 1", + ) + .bind(owner_id) + .bind(query.profile_id) + .fetch_optional(pool(&state)?) + .await?; + + match session { + Some(session) => Ok(Json(Some( + load_session_response(pool(&state)?, session).await?, + ))), + None => Ok(Json(None)), + } +} + +#[utoipa::path( + post, + path = "/api/v1/feedback-sessions", + tag = "语音反馈", + summary = "创建或恢复反馈批次", + description = "为学生创建一个反馈批次;已有未保存批次时直接恢复,并同步最新反馈日期。", + params(("X-User-Id" = Uuid, Header, description = "开发阶段用户 ID", example = json!("5a4da7f0-d70c-465f-bcab-124c504aa9f0"))), + request_body(content = FeedbackSessionInput, content_type = "application/json"), + responses( + (status = 200, description = "创建或恢复后的反馈批次", body = FeedbackSessionResponse), + (status = 404, description = "学生档案不存在或不属于当前用户", body = ErrorBody), + CommonApiErrors + ) +)] +async fn ensure_feedback_session( + State(state): State, + headers: HeaderMap, + Json(input): Json, +) -> Result, ApiError> { + let owner_id = current_user(&headers)?; + let pool = pool(&state)?; + validate_draft_content(&input.content)?; + if let Some(profile_id) = input.profile_id { + assert_profile_owner(pool, owner_id, profile_id).await?; + } + + let existing = sqlx::query_as::<_, FeedbackSessionRow>( + "UPDATE feedback_sessions SET feedback_date = $3, content = $4, updated_at = now() \ + WHERE id = ( \ + SELECT id FROM feedback_sessions \ + WHERE owner_id = $1 AND profile_id IS NOT DISTINCT FROM $2 AND status = 'active' \ + ORDER BY updated_at DESC LIMIT 1 \ + ) \ + RETURNING id, profile_id, feedback_date, content, status, created_at, updated_at", + ) + .bind(owner_id) + .bind(input.profile_id) + .bind(input.feedback_date) + .bind(&input.content) + .fetch_optional(pool) + .await?; + let session = + match existing { + Some(session) => session, + None => sqlx::query_as::<_, FeedbackSessionRow>( + "INSERT INTO feedback_sessions (id, owner_id, profile_id, feedback_date, content) \ + VALUES ($1, $2, $3, $4, $5) \ + RETURNING id, profile_id, feedback_date, content, status, created_at, updated_at", + ) + .bind(Uuid::new_v4()) + .bind(owner_id) + .bind(input.profile_id) + .bind(input.feedback_date) + .bind(&input.content) + .fetch_one(pool) + .await?, + }; + + Ok(Json(load_session_response(pool, session).await?)) +} + +#[utoipa::path( + put, + path = "/api/v1/feedback-sessions/{session_id}", + tag = "语音反馈", + summary = "自动保存反馈草稿", + description = "在用户编辑反馈正文或日期时自动保存进行中的反馈批次。", + params( + ("X-User-Id" = Uuid, Header, description = "开发阶段用户 ID", example = json!("5a4da7f0-d70c-465f-bcab-124c504aa9f0")), + ("session_id" = Uuid, Path, description = "反馈批次 ID") + ), + request_body(content = FeedbackSessionUpdateInput, content_type = "application/json"), + responses( + (status = 200, description = "更新后的反馈批次", body = FeedbackSessionResponse), + (status = 404, description = "反馈批次不存在或不属于当前用户", body = ErrorBody), + CommonApiErrors + ) +)] +async fn update_feedback_session( + State(state): State, + headers: HeaderMap, + Path(session_id): Path, + Json(input): Json, +) -> Result, ApiError> { + let owner_id = current_user(&headers)?; + validate_draft_content(&input.content)?; + let session = sqlx::query_as::<_, FeedbackSessionRow>( + "UPDATE feedback_sessions SET feedback_date = $3, content = $4, updated_at = now() \ + WHERE id = $1 AND owner_id = $2 AND status = 'active' \ + RETURNING id, profile_id, feedback_date, content, status, created_at, updated_at", + ) + .bind(session_id) + .bind(owner_id) + .bind(input.feedback_date) + .bind(&input.content) + .fetch_optional(pool(&state)?) + .await? + .ok_or(ApiError::NotFound)?; + Ok(Json(load_session_response(pool(&state)?, session).await?)) +} + +#[utoipa::path( + post, + path = "/api/v1/feedback-sessions/{session_id}/lessons", + tag = "语音反馈", + summary = "开始一节课堂录音", + description = "在反馈批次中自动创建下一节课堂录音。", + params( + ("X-User-Id" = Uuid, Header, description = "开发阶段用户 ID", example = json!("5a4da7f0-d70c-465f-bcab-124c504aa9f0")), + ("session_id" = Uuid, Path, description = "反馈批次 ID") + ), + responses( + (status = 201, description = "课堂录音已创建", body = LessonCreatedResponse), + (status = 404, description = "反馈批次不存在或不属于当前用户", body = ErrorBody), + CommonApiErrors + ) +)] +async fn create_lesson_session( + State(state): State, + headers: HeaderMap, + Path(session_id): Path, +) -> Result<(axum::http::StatusCode, Json), ApiError> { + let owner_id = current_user(&headers)?; + assert_session_owner(pool(&state)?, owner_id, session_id).await?; + sqlx::query( + "DELETE FROM lesson_sessions \ + WHERE feedback_session_id = $1 AND status IN ('recording', 'processing')", + ) + .bind(session_id) + .execute(pool(&state)?) + .await?; + let id = Uuid::new_v4(); + let lesson = sqlx::query_as::<_, (Uuid, i32, String, DateTime)>( + "INSERT INTO lesson_sessions (id, feedback_session_id, sequence) \ + SELECT $1, $2, COALESCE(MAX(sequence), 0) + 1 \ + FROM lesson_sessions WHERE feedback_session_id = $2 \ + RETURNING id, sequence, status, started_at", + ) + .bind(id) + .bind(session_id) + .fetch_one(pool(&state)?) + .await?; + touch_session(pool(&state)?, session_id).await?; + Ok(( + axum::http::StatusCode::CREATED, + Json(LessonCreatedResponse { + id: lesson.0, + sequence: lesson.1, + status: lesson.2, + started_at: lesson.3, + }), + )) +} + +#[utoipa::path( + post, + path = "/api/v1/feedback-lessons/{lesson_id}/segments", + tag = "语音反馈", + summary = "上传并转录录音片段", + description = "上传单个录音片段并加入后端转录队列。接口保存音频后立即返回,页面通过反馈批次状态无感获取转录结果。", + params( + ("X-User-Id" = Uuid, Header, description = "开发阶段用户 ID", example = json!("5a4da7f0-d70c-465f-bcab-124c504aa9f0")), + ("lesson_id" = Uuid, Path, description = "课堂录音 ID") + ), + request_body(content = AudioSegmentUpload, content_type = "multipart/form-data"), + responses( + (status = 201, description = "片段已保存并进入转录队列", body = AudioSegmentResponse), + (status = 404, description = "课堂录音不存在或不属于当前用户", body = ErrorBody), + CommonApiErrors + ) +)] +async fn upload_audio_segment( + State(state): State, + headers: HeaderMap, + Path(lesson_id): Path, + mut multipart: Multipart, +) -> Result<(axum::http::StatusCode, Json), ApiError> { + let owner_id = current_user(&headers)?; + let session_id = assert_lesson_owner(pool(&state)?, owner_id, lesson_id).await?; + let mut sequence = None; + let mut duration_ms = None; + let mut audio_format = None; + let mut audio = None; + + while let Some(field) = multipart + .next_field() + .await + .map_err(|error| ApiError::BadRequest(format!("invalid multipart body: {error}")))? + { + let name = field.name().unwrap_or_default().to_owned(); + match name.as_str() { + "sequence" => sequence = Some(parse_multipart_i32(field, "sequence").await?), + "duration_ms" => duration_ms = Some(parse_multipart_i32(field, "duration_ms").await?), + "audio_format" => { + audio_format = Some( + field + .text() + .await + .map_err(|_| ApiError::BadRequest("audio_format is invalid".to_owned()))?, + ) + } + "audio" => { + let bytes = field + .bytes() + .await + .map_err(|_| ApiError::BadRequest("audio file is invalid".to_owned()))?; + if bytes.len() > MAX_AUDIO_UPLOAD_BYTES { + return Err(ApiError::BadRequest("audio file exceeds 15 MB".to_owned())); + } + audio = Some(bytes.to_vec()); + } + _ => {} + } + } + + let sequence = sequence + .filter(|value| *value > 0) + .ok_or_else(|| ApiError::BadRequest("sequence must be a positive integer".to_owned()))?; + let duration_ms = duration_ms + .filter(|value| (1..=MAX_SEGMENT_DURATION_MS).contains(value)) + .ok_or_else(|| { + ApiError::BadRequest("duration_ms must be between 1 and 600000".to_owned()) + })?; + let audio_format = audio_format + .map(|value| value.trim().to_ascii_lowercase()) + .filter(|value| matches!(value.as_str(), "mp3" | "aac" | "wav" | "m4a" | "amr")) + .ok_or_else(|| ApiError::BadRequest("unsupported audio_format".to_owned()))?; + let audio = audio + .filter(|bytes| !bytes.is_empty()) + .ok_or_else(|| ApiError::BadRequest("audio file cannot be empty".to_owned()))?; + + let file_id = Uuid::new_v4(); + let directory = state + .audio_storage_dir + .join(owner_id.to_string()) + .join(lesson_id.to_string()); + tokio::fs::create_dir_all(&directory) + .await + .map_err(internal_io_error)?; + let audio_path = directory.join(format!("{file_id}.{audio_format}")); + tokio::fs::write(&audio_path, &audio) + .await + .map_err(internal_io_error)?; + + let segment_id = sqlx::query_scalar::<_, Uuid>( + "INSERT INTO audio_segments \ + (id, lesson_session_id, sequence, duration_ms, audio_format, audio_path, status) \ + VALUES ($1, $2, $3, $4, $5, $6, 'processing') \ + ON CONFLICT (lesson_session_id, sequence) DO UPDATE SET \ + duration_ms = EXCLUDED.duration_ms, audio_format = EXCLUDED.audio_format, \ + audio_path = EXCLUDED.audio_path, status = 'processing', transcript = NULL, \ + error_message = NULL, provider_request_id = NULL, processing_started_at = NULL, \ + updated_at = now() \ + RETURNING id", + ) + .bind(file_id) + .bind(lesson_id) + .bind(sequence) + .bind(duration_ms) + .bind(&audio_format) + .bind(audio_path.to_string_lossy().as_ref()) + .fetch_one(pool(&state)?) + .await?; + sqlx::query( + "UPDATE lesson_sessions SET status = 'processing', updated_at = now() WHERE id = $1", + ) + .bind(lesson_id) + .execute(pool(&state)?) + .await?; + + touch_session(pool(&state)?, session_id).await?; + Ok(( + axum::http::StatusCode::CREATED, + Json(AudioSegmentResponse { + id: segment_id, + sequence, + duration_ms, + status: "processing".to_owned(), + error_message: None, + }), + )) +} + +#[utoipa::path( + post, + path = "/api/v1/feedback-lessons/{lesson_id}/finish", + tag = "语音反馈", + summary = "结束一节课堂录音", + description = "汇总该节课的片段状态和转录文本;短录音会标记为可直接加入反馈。", + params( + ("X-User-Id" = Uuid, Header, description = "开发阶段用户 ID", example = json!("5a4da7f0-d70c-465f-bcab-124c504aa9f0")), + ("lesson_id" = Uuid, Path, description = "课堂录音 ID") + ), + responses( + (status = 200, description = "课堂录音汇总结果", body = FinishedLessonResponse), + (status = 404, description = "课堂录音不存在或不属于当前用户", body = ErrorBody), + CommonApiErrors + ) +)] +async fn finish_lesson_session( + State(state): State, + headers: HeaderMap, + Path(lesson_id): Path, +) -> Result, ApiError> { + let owner_id = current_user(&headers)?; + let session_id = assert_lesson_owner(pool(&state)?, owner_id, lesson_id).await?; + let segments = sqlx::query_as::<_, (String, i32, Option)>( + "SELECT status, duration_ms, transcript FROM audio_segments \ + WHERE lesson_session_id = $1 ORDER BY sequence", + ) + .bind(lesson_id) + .fetch_all(pool(&state)?) + .await?; + let duration_ms = segments.iter().map(|segment| segment.1).sum::(); + let transcript = segments + .iter() + .filter_map(|segment| segment.2.as_deref()) + .collect::>() + .join("\n"); + let status = if segments.is_empty() || segments.iter().any(|segment| segment.0 == "failed") { + "failed" + } else if segments.iter().any(|segment| segment.0 == "processing") { + "processing" + } else { + "ready" + }; + sqlx::query( + "UPDATE lesson_sessions SET status = $2, duration_ms = $3, ended_at = now(), updated_at = now() \ + WHERE id = $1", + ) + .bind(lesson_id) + .bind(status) + .bind(duration_ms) + .execute(pool(&state)?) + .await?; + touch_session(pool(&state)?, session_id).await?; + + Ok(Json(FinishedLessonResponse { + id: lesson_id, + status: status.to_owned(), + duration_ms, + can_apply_directly: status == "ready" + && duration_ms <= SHORT_RECORDING_DURATION_MS + && transcript.chars().count() <= SHORT_TRANSCRIPT_CHARS, + transcript, + })) +} + +#[utoipa::path( + post, + path = "/api/v1/feedback-lessons/{lesson_id}/mark-applied", + tag = "语音反馈", + summary = "标记短录音已加入反馈", + description = "短录音文字直接加入反馈内容后,标记该节课无需再次汇总。", + params( + ("X-User-Id" = Uuid, Header, description = "开发阶段用户 ID", example = json!("5a4da7f0-d70c-465f-bcab-124c504aa9f0")), + ("lesson_id" = Uuid, Path, description = "课堂录音 ID") + ), + request_body(content = MarkLessonAppliedInput, content_type = "application/json"), + responses( + (status = 204, description = "已标记"), + (status = 404, description = "课堂录音不存在或不属于当前用户", body = ErrorBody), + CommonApiErrors + ) +)] +async fn mark_lesson_applied( + State(state): State, + headers: HeaderMap, + Path(lesson_id): Path, + Json(input): Json, +) -> Result { + let owner_id = current_user(&headers)?; + validate_draft_content(&input.content)?; + let pool = pool(&state)?; + let session_id = assert_lesson_owner(pool, owner_id, lesson_id).await?; + let mut transaction = pool.begin().await?; + let result = sqlx::query( + "UPDATE lesson_sessions SET applied_directly = TRUE, updated_at = now() \ + WHERE id = $1 AND status = 'ready'", + ) + .bind(lesson_id) + .execute(&mut *transaction) + .await?; + if result.rows_affected() == 0 { + return Err(ApiError::BadRequest("lesson is not ready".to_owned())); + } + sqlx::query("UPDATE feedback_sessions SET content = $2, updated_at = now() WHERE id = $1") + .bind(session_id) + .bind(&input.content) + .execute(&mut *transaction) + .await?; + transaction.commit().await?; + Ok(axum::http::StatusCode::NO_CONTENT) +} + +#[utoipa::path( + post, + path = "/api/v1/audio-segments/{segment_id}/retry", + tag = "语音反馈", + summary = "重试失败的录音转录", + description = "将后端保留的失败音频重新加入转录队列,接口立即返回。", + params( + ("X-User-Id" = Uuid, Header, description = "开发阶段用户 ID", example = json!("5a4da7f0-d70c-465f-bcab-124c504aa9f0")), + ("segment_id" = Uuid, Path, description = "录音片段 ID") + ), + responses( + (status = 200, description = "片段已重新进入转录队列", body = AudioSegmentResponse), + (status = 404, description = "录音片段不存在或不属于当前用户", body = ErrorBody), + CommonApiErrors + ) +)] +async fn retry_audio_segment( + State(state): State, + headers: HeaderMap, + Path(segment_id): Path, +) -> Result, ApiError> { + let owner_id = current_user(&headers)?; + let segment = sqlx::query_as::<_, (i32, i32, String, Uuid)>( + "SELECT s.sequence, s.duration_ms, s.audio_path, l.id \ + FROM audio_segments s \ + JOIN lesson_sessions l ON l.id = s.lesson_session_id \ + JOIN feedback_sessions f ON f.id = l.feedback_session_id \ + WHERE s.id = $1 AND f.owner_id = $2 AND f.status = 'active'", + ) + .bind(segment_id) + .bind(owner_id) + .fetch_optional(pool(&state)?) + .await? + .ok_or(ApiError::NotFound)?; + tokio::fs::metadata(&segment.2) + .await + .map_err(internal_io_error)?; + sqlx::query( + "UPDATE audio_segments SET status = 'processing', error_message = NULL, \ + processing_started_at = NULL, updated_at = now() WHERE id = $1", + ) + .bind(segment_id) + .execute(pool(&state)?) + .await?; + sqlx::query( + "UPDATE lesson_sessions SET status = 'processing', updated_at = now() WHERE id = $1", + ) + .bind(segment.3) + .execute(pool(&state)?) + .await?; + let session_id = sqlx::query_scalar::<_, Uuid>( + "SELECT feedback_session_id FROM lesson_sessions WHERE id = $1", + ) + .bind(segment.3) + .fetch_one(pool(&state)?) + .await?; + touch_session(pool(&state)?, session_id).await?; + Ok(Json(AudioSegmentResponse { + id: segment_id, + sequence: segment.0, + duration_ms: segment.1, + status: "processing".to_owned(), + error_message: None, + })) +} + +#[utoipa::path( + post, + path = "/api/v1/feedback-sessions/{session_id}/generate", + tag = "语音反馈", + summary = "生成汇总反馈", + description = "将尚未处理的长录音或多节课堂转录与教师已有内容合并。未配置大模型时使用本地抽取式汇总。", + params( + ("X-User-Id" = Uuid, Header, description = "开发阶段用户 ID", example = json!("5a4da7f0-d70c-465f-bcab-124c504aa9f0")), + ("session_id" = Uuid, Path, description = "反馈批次 ID") + ), + request_body(content = GenerateFeedbackInput, content_type = "application/json"), + responses( + (status = 200, description = "汇总后的反馈正文", body = GenerateFeedbackResponse), + (status = 404, description = "反馈批次不存在或不属于当前用户", body = ErrorBody), + CommonApiErrors + ) +)] +async fn generate_feedback_content( + State(state): State, + headers: HeaderMap, + Path(session_id): Path, + Json(input): Json, +) -> Result, ApiError> { + let owner_id = current_user(&headers)?; + validate_draft_content(&input.existing_content)?; + assert_session_owner(pool(&state)?, owner_id, session_id).await?; + let pending_status = sqlx::query_as::<_, (bool, bool)>( + "SELECT \ + EXISTS(SELECT 1 FROM audio_segments s JOIN lesson_sessions l ON l.id = s.lesson_session_id \ + WHERE l.feedback_session_id = $1 AND s.status = 'processing'), \ + EXISTS(SELECT 1 FROM audio_segments s JOIN lesson_sessions l ON l.id = s.lesson_session_id \ + WHERE l.feedback_session_id = $1 AND s.status = 'failed')", + ) + .bind(session_id) + .fetch_one(pool(&state)?) + .await?; + if pending_status.0 { + return Err(ApiError::BadRequest( + "录音仍在后台转录中,请稍后再生成反馈".to_owned(), + )); + } + if pending_status.1 { + return Err(ApiError::BadRequest( + "部分录音转录失败,请重试后再生成反馈".to_owned(), + )); + } + let lessons = sqlx::query_as::<_, (Uuid, String)>( + "SELECT l.id, string_agg(s.transcript, E'\\n' ORDER BY s.sequence) \ + FROM lesson_sessions l \ + JOIN audio_segments s ON s.lesson_session_id = l.id \ + WHERE l.feedback_session_id = $1 AND l.status = 'ready' \ + AND l.applied_directly = FALSE AND l.included_in_generation = FALSE \ + AND s.status = 'ready' AND s.transcript IS NOT NULL \ + GROUP BY l.id, l.sequence ORDER BY l.sequence", + ) + .bind(session_id) + .fetch_all(pool(&state)?) + .await?; + if lessons.is_empty() { + return Err(ApiError::BadRequest("没有待汇总的录音内容".to_owned())); + } + let transcripts = lessons + .iter() + .map(|lesson| lesson.1.clone()) + .collect::>(); + let summary = state + .summary + .summarize(&input.existing_content, &transcripts) + .await + .map_err(ApiError::ServiceUnavailable)?; + let lesson_ids = lessons.iter().map(|lesson| lesson.0).collect::>(); + let pool = pool(&state)?; + let mut transaction = pool.begin().await?; + sqlx::query( + "UPDATE lesson_sessions SET included_in_generation = TRUE, updated_at = now() \ + WHERE id = ANY($1)", + ) + .bind(&lesson_ids) + .execute(&mut *transaction) + .await?; + sqlx::query("UPDATE feedback_sessions SET content = $2, updated_at = now() WHERE id = $1") + .bind(session_id) + .bind(&summary.content) + .execute(&mut *transaction) + .await?; + transaction.commit().await?; + + Ok(Json(GenerateFeedbackResponse { + content: summary.content, + method: summary.method.to_owned(), + })) +} + +async fn load_session_response( + pool: &PgPool, + session: FeedbackSessionRow, +) -> Result { + let lessons = sqlx::query_as::<_, LessonRow>( + "SELECT id, sequence, status, duration_ms, applied_directly, included_in_generation, \ + started_at, ended_at FROM lesson_sessions \ + WHERE feedback_session_id = $1 ORDER BY sequence", + ) + .bind(session.id) + .fetch_all(pool) + .await?; + let segments = sqlx::query_as::<_, SegmentRow>( + "SELECT s.id, s.lesson_session_id, s.sequence, s.duration_ms, s.status, s.error_message \ + FROM audio_segments s JOIN lesson_sessions l ON l.id = s.lesson_session_id \ + WHERE l.feedback_session_id = $1 ORDER BY l.sequence, s.sequence", + ) + .bind(session.id) + .fetch_all(pool) + .await?; + let processing_segment_count = segments + .iter() + .filter(|segment| segment.status == "processing") + .count() + + lessons + .iter() + .filter(|lesson| matches!(lesson.status.as_str(), "recording" | "processing")) + .count(); + let failed_segment_count = segments + .iter() + .filter(|segment| segment.status == "failed") + .count(); + let total_duration_ms = lessons + .iter() + .map(|lesson| i64::from(lesson.duration_ms)) + .sum(); + let needs_generation = lessons.iter().any(|lesson| { + lesson.status == "ready" && !lesson.applied_directly && !lesson.included_in_generation + }); + let mut segments_by_lesson: HashMap> = HashMap::new(); + for segment in segments { + segments_by_lesson + .entry(segment.lesson_session_id) + .or_default() + .push(AudioSegmentResponse { + id: segment.id, + sequence: segment.sequence, + duration_ms: segment.duration_ms, + status: segment.status, + error_message: segment.error_message, + }); + } + let lesson_count = lessons.len(); + let lesson_responses = lessons + .into_iter() + .map(|lesson| LessonSummaryResponse { + id: lesson.id, + sequence: lesson.sequence, + status: lesson.status, + duration_ms: lesson.duration_ms, + applied_directly: lesson.applied_directly, + included_in_generation: lesson.included_in_generation, + segments: segments_by_lesson.remove(&lesson.id).unwrap_or_default(), + started_at: lesson.started_at, + ended_at: lesson.ended_at, + }) + .collect(); + + Ok(FeedbackSessionResponse { + id: session.id, + profile_id: session.profile_id, + feedback_date: session.feedback_date, + content: session.content, + status: session.status, + lesson_count, + total_duration_ms, + processing_segment_count, + failed_segment_count, + needs_generation, + lessons: lesson_responses, + created_at: session.created_at, + updated_at: session.updated_at, + }) +} + +async fn parse_multipart_i32( + field: axum::extract::multipart::Field<'_>, + name: &str, +) -> Result { + field + .text() + .await + .map_err(|_| ApiError::BadRequest(format!("{name} is invalid")))? + .parse() + .map_err(|_| ApiError::BadRequest(format!("{name} must be an integer"))) +} + +fn current_user(headers: &HeaderMap) -> Result { + let value = headers + .get("x-user-id") + .and_then(|header| header.to_str().ok()) + .ok_or(ApiError::Unauthorized)?; + Uuid::parse_str(value).map_err(|_| ApiError::BadRequest("X-User-Id must be a UUID".to_owned())) +} + +fn pool(state: &AppState) -> Result<&PgPool, ApiError> { + state.pool.as_ref().ok_or(ApiError::DatabaseUnavailable) +} + +async fn assert_profile_owner( + pool: &PgPool, + owner_id: Uuid, + profile_id: Uuid, +) -> Result<(), ApiError> { + let exists = sqlx::query_scalar::<_, bool>( + "SELECT EXISTS(SELECT 1 FROM student_profiles WHERE id = $1 AND owner_id = $2)", + ) + .bind(profile_id) + .bind(owner_id) + .fetch_one(pool) + .await?; + if exists { + Ok(()) + } else { + Err(ApiError::NotFound) + } +} + +async fn assert_session_owner( + pool: &PgPool, + owner_id: Uuid, + session_id: Uuid, +) -> Result<(), ApiError> { + let exists = sqlx::query_scalar::<_, bool>( + "SELECT EXISTS(SELECT 1 FROM feedback_sessions WHERE id = $1 AND owner_id = $2 AND status = 'active')", + ) + .bind(session_id) + .bind(owner_id) + .fetch_one(pool) + .await?; + if exists { + Ok(()) + } else { + Err(ApiError::NotFound) + } +} + +async fn assert_lesson_owner( + pool: &PgPool, + owner_id: Uuid, + lesson_id: Uuid, +) -> Result { + sqlx::query_scalar::<_, Uuid>( + "SELECT f.id FROM lesson_sessions l \ + JOIN feedback_sessions f ON f.id = l.feedback_session_id \ + WHERE l.id = $1 AND f.owner_id = $2 AND f.status = 'active'", + ) + .bind(lesson_id) + .bind(owner_id) + .fetch_optional(pool) + .await? + .ok_or(ApiError::NotFound) +} + +async fn touch_session(pool: &PgPool, session_id: Uuid) -> Result<(), ApiError> { + sqlx::query("UPDATE feedback_sessions SET updated_at = now() WHERE id = $1") + .bind(session_id) + .execute(pool) + .await?; + Ok(()) +} + +fn internal_io_error(error: std::io::Error) -> ApiError { + tracing::error!(?error, "audio file operation failed"); + ApiError::Internal +} + +fn validate_draft_content(content: &str) -> Result<(), ApiError> { + if content.chars().count() > 2000 { + return Err(ApiError::BadRequest( + "feedback content cannot exceed 2000 characters".to_owned(), + )); + } + Ok(()) +} diff --git a/server/src/routes.rs b/server/src/routes.rs new file mode 100644 index 0000000..4ab7de8 --- /dev/null +++ b/server/src/routes.rs @@ -0,0 +1,941 @@ +use std::sync::Arc; + +use axum::{ + Json, Router, + extract::{Path, Query, State}, + http::HeaderMap, +}; +use chrono::{DateTime, NaiveDate, NaiveTime, Utc}; +use serde::{Deserialize, Serialize}; +use sqlx::{FromRow, PgPool, Postgres, QueryBuilder, postgres::PgQueryResult}; +use utoipa::{ + ToSchema, + openapi::{Info, OpenApi, Server, Tag}, +}; +use utoipa_axum::{router::OpenApiRouter, routes}; +use uuid::Uuid; + +use crate::{ + AppState, + error::{ApiError, CommonApiErrors, ErrorBody}, + recording_routes, +}; + +type SharedState = Arc; + +const DEFAULT_GRADE: &str = "艺术类"; +const DEFAULT_SUBJECT: &str = "美术"; +const DEFAULT_DURATION_MINUTES: i16 = 60; + +pub fn router() -> (Router, OpenApi) { + let (router, mut openapi) = OpenApiRouter::new() + .routes(routes!(health)) + .routes(routes!(list_profiles, create_profile)) + .routes(routes!(get_profile, update_profile, delete_profile)) + .routes(routes!(get_defaults, update_defaults)) + .routes(routes!(list_feedback_records, create_feedback_record)) + .routes(routes!(delete_feedback_record)) + .merge(recording_routes::router()) + .split_for_parts(); + + let mut info = Info::new("教学反馈助手 API", env!("CARGO_PKG_VERSION")); + info.description = Some( + "学生档案、档案预设和教学反馈记录 API。\n\n\ + 业务接口使用 `X-User-Id` 作为开发阶段身份边界;Scalar 已预填测试 UUID 和请求体示例。" + .to_owned(), + ); + openapi.info = info; + openapi.servers = Some(vec![Server::new("/")]); + openapi.tags = Some(vec![ + api_tag("健康检查", "检查 HTTP 服务状态和数据库是否已配置。"), + api_tag("学生档案", "创建、查询、更新和删除当前用户的学生档案。"), + api_tag("档案预设", "读取或保存当前用户新建档案时使用的默认值。"), + api_tag("反馈记录", "创建、查询和删除当前用户的教学反馈记录。"), + api_tag("语音反馈", "录制多节课堂、转录音频并生成反馈草稿。"), + ]); + + (router, openapi) +} + +fn api_tag(name: &str, description: &str) -> Tag { + let mut tag = Tag::new(name); + tag.description = Some(description.to_owned()); + tag +} + +/// 健康检查响应。 +#[derive(Serialize, ToSchema)] +#[schema(example = json!({ + "status": "ok", + "database_configured": true, + "speech_configured": true, + "speech_available": true, + "speech_provider": "local-funasr", + "summary_configured": false +}))] +struct HealthResponse { + /// HTTP 服务状态;正常时固定为 `ok`。 + status: &'static str, + /// 是否已经通过 `DATABASE_URL` 配置数据库连接。 + database_configured: bool, + /// 是否已经配置长音频转录服务。 + speech_configured: bool, + /// 当前转录服务是否可连接;本地模型启动和下载完成后为 `true`。 + speech_available: bool, + /// 当前语音提供方;未启用转录时为 `null`。 + speech_provider: Option<&'static str>, + /// 是否已经配置生成式反馈汇总服务;未配置时使用本地抽取式汇总。 + summary_configured: bool, +} + +/// 检查服务状态。 +#[utoipa::path( + get, + path = "/health", + tag = "健康检查", + summary = "健康检查", + description = "不需要身份请求头。返回 HTTP 服务状态,并标记数据库连接是否已配置。", + responses( + (status = 200, description = "服务正在运行", body = HealthResponse) + ) +)] +async fn health(State(state): State) -> Json { + Json(HealthResponse { + status: "ok", + database_configured: state.pool.is_some(), + speech_configured: state.speech.configured(), + speech_available: state.speech.available().await, + speech_provider: state.speech.provider_name(), + summary_configured: state.summary.configured(), + }) +} + +/// 学生档案。 +#[derive(Debug, Serialize, FromRow, ToSchema)] +#[schema(example = json!({ + "id": "11111111-1111-4111-8111-111111111111", + "name": "小谢", + "grade": "艺术类", + "subject": "美术", + "academic_year": 2026, + "term": "暑", + "guardian_title": "小谢妈妈", + "start_time": "18:00", + "end_time": "19:00", + "created_at": "2026-07-15T10:00:00Z", + "updated_at": "2026-07-15T10:00:00Z" +}))] +struct StudentProfile { + /// 档案 ID。 + id: Uuid, + /// 学生姓名,1 到 20 个字符。 + name: String, + /// 年级或学生类别。 + grade: String, + /// 授课学科。 + subject: String, + /// 学年,范围为 2000 到 2200。 + academic_year: i16, + /// 学期,可选值为春、暑、秋、寒。 + term: String, + /// 家长称呼,1 到 24 个字符。 + guardian_title: String, + /// 上课开始时间,格式为 `HH:MM`。 + start_time: String, + /// 上课结束时间,格式为 `HH:MM`。 + end_time: String, + /// 创建时间,UTC。 + created_at: DateTime, + /// 最近更新时间,UTC。 + updated_at: DateTime, +} + +/// 创建或完整更新学生档案的请求体。 +#[derive(Debug, Deserialize, ToSchema)] +#[schema(example = json!({ + "name": "小谢", + "grade": "艺术类", + "subject": "美术", + "academic_year": 2026, + "term": "暑", + "guardian_title": "小谢妈妈", + "start_time": "18:00", + "end_time": "19:00" +}))] +struct ProfileInput { + /// 学生姓名,1 到 20 个字符。 + name: String, + /// 年级或学生类别,不可为空。 + grade: String, + /// 授课学科,不可为空。 + subject: String, + /// 学年,范围为 2000 到 2200。 + academic_year: i16, + /// 学期,可选值为春、暑、秋、寒。 + term: String, + /// 家长称呼,1 到 24 个字符。 + guardian_title: String, + /// 上课开始时间,格式为 `HH:MM`。 + start_time: String, + /// 上课结束时间,格式为 `HH:MM`。 + end_time: String, +} + +#[derive(Debug, Deserialize)] +struct ProfileQuery { + query: Option, + grade: Option, + subject: Option, +} + +/// 列出当前用户的学生档案。 +#[utoipa::path( + get, + path = "/api/v1/profiles", + tag = "学生档案", + summary = "列出学生档案", + description = "按最近更新时间倒序返回当前用户的档案。三个查询条件均可省略,也可以组合使用。", + params( + ("X-User-Id" = Uuid, Header, description = "开发阶段用户 ID;Scalar 已预填测试值", example = json!("5a4da7f0-d70c-465f-bcab-124c504aa9f0")), + ("query" = Option, Query, description = "模糊匹配姓名、年级、学科或家长称呼", example = "小谢"), + ("grade" = Option, Query, description = "精确匹配年级或学生类别", example = "艺术类"), + ("subject" = Option, Query, description = "精确匹配学科", example = "美术") + ), + responses( + (status = 200, description = "学生档案列表", body = [StudentProfile]), + CommonApiErrors + ) +)] +async fn list_profiles( + State(state): State, + headers: HeaderMap, + Query(query): Query, +) -> Result>, ApiError> { + let owner_id = current_user(&headers)?; + let pool = pool(&state)?; + let mut statement = QueryBuilder::::new( + "SELECT id, name, grade, subject, academic_year, term, guardian_title, start_time, end_time, created_at, updated_at \ + FROM student_profiles WHERE owner_id = ", + ); + statement.push_bind(owner_id); + + if let Some(grade) = query.grade.filter(|value| !value.trim().is_empty()) { + statement.push(" AND grade = "); + statement.push_bind(grade.trim().to_owned()); + } + if let Some(subject) = query.subject.filter(|value| !value.trim().is_empty()) { + statement.push(" AND subject = "); + statement.push_bind(subject.trim().to_owned()); + } + if let Some(keyword) = query.query.filter(|value| !value.trim().is_empty()) { + let pattern = format!("%{}%", keyword.trim()); + statement.push(" AND (name ILIKE "); + statement.push_bind(pattern.clone()); + statement.push(" OR grade ILIKE "); + statement.push_bind(pattern.clone()); + statement.push(" OR subject ILIKE "); + statement.push_bind(pattern.clone()); + statement.push(" OR guardian_title ILIKE "); + statement.push_bind(pattern); + statement.push(")"); + } + + statement.push(" ORDER BY updated_at DESC"); + let profiles = statement + .build_query_as::() + .fetch_all(pool) + .await?; + Ok(Json(profiles)) +} + +/// 读取当前用户的单个学生档案。 +#[utoipa::path( + get, + path = "/api/v1/profiles/{profile_id}", + tag = "学生档案", + summary = "读取学生档案", + description = "只允许读取属于当前 `X-User-Id` 的档案。请先从创建或列表接口复制真实的档案 ID。", + params( + ("X-User-Id" = Uuid, Header, description = "开发阶段用户 ID;必须与档案所属用户一致", example = json!("5a4da7f0-d70c-465f-bcab-124c504aa9f0")), + ("profile_id" = Uuid, Path, description = "学生档案 ID;将示例值替换为创建接口返回的 ID", example = json!("11111111-1111-4111-8111-111111111111")) + ), + responses( + (status = 200, description = "学生档案", body = StudentProfile), + (status = 404, description = "档案不存在或不属于当前用户", body = ErrorBody, example = json!({"error": "resource not found"})), + CommonApiErrors + ) +)] +async fn get_profile( + State(state): State, + headers: HeaderMap, + Path(profile_id): Path, +) -> Result, ApiError> { + let owner_id = current_user(&headers)?; + let profile = sqlx::query_as::<_, StudentProfile>( + "SELECT id, name, grade, subject, academic_year, term, guardian_title, start_time, end_time, created_at, updated_at \ + FROM student_profiles WHERE id = $1 AND owner_id = $2", + ) + .bind(profile_id) + .bind(owner_id) + .fetch_optional(pool(&state)?) + .await? + .ok_or(ApiError::NotFound)?; + Ok(Json(profile)) +} + +/// 创建学生档案。 +#[utoipa::path( + post, + path = "/api/v1/profiles", + tag = "学生档案", + summary = "创建学生档案", + description = "使用请求头中的用户 ID 创建档案。Scalar 已预填完整请求体,可以直接执行测试。", + params( + ("X-User-Id" = Uuid, Header, description = "开发阶段用户 ID;Scalar 已预填测试值", example = json!("5a4da7f0-d70c-465f-bcab-124c504aa9f0")) + ), + request_body( + content = ProfileInput, + description = "学生档案内容", + content_type = "application/json", + example = json!({ + "name": "小谢", + "grade": "艺术类", + "subject": "美术", + "academic_year": 2026, + "term": "暑", + "guardian_title": "小谢妈妈", + "start_time": "18:00", + "end_time": "19:00" + }) + ), + responses( + (status = 201, description = "档案创建成功", body = StudentProfile), + CommonApiErrors + ) +)] +async fn create_profile( + State(state): State, + headers: HeaderMap, + Json(input): Json, +) -> Result<(axum::http::StatusCode, Json), ApiError> { + validate_profile(&input)?; + let owner_id = current_user(&headers)?; + let profile = sqlx::query_as::<_, StudentProfile>( + "INSERT INTO student_profiles \ + (id, owner_id, name, grade, subject, academic_year, term, guardian_title, start_time, end_time) \ + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10) \ + RETURNING id, name, grade, subject, academic_year, term, guardian_title, start_time, end_time, created_at, updated_at", + ) + .bind(Uuid::new_v4()) + .bind(owner_id) + .bind(input.name.trim()) + .bind(input.grade.trim()) + .bind(input.subject.trim()) + .bind(input.academic_year) + .bind(input.term.trim()) + .bind(input.guardian_title.trim()) + .bind(input.start_time.trim()) + .bind(input.end_time.trim()) + .fetch_one(pool(&state)?) + .await?; + Ok((axum::http::StatusCode::CREATED, Json(profile))) +} + +/// 完整更新学生档案。 +#[utoipa::path( + put, + path = "/api/v1/profiles/{profile_id}", + tag = "学生档案", + summary = "更新学生档案", + description = "完整替换指定档案的可编辑字段。请先从创建或列表接口复制真实的档案 ID。", + params( + ("X-User-Id" = Uuid, Header, description = "开发阶段用户 ID;必须与档案所属用户一致", example = json!("5a4da7f0-d70c-465f-bcab-124c504aa9f0")), + ("profile_id" = Uuid, Path, description = "学生档案 ID;将示例值替换为创建接口返回的 ID", example = json!("11111111-1111-4111-8111-111111111111")) + ), + request_body( + content = ProfileInput, + description = "更新后的完整档案内容", + content_type = "application/json", + example = json!({ + "name": "小谢", + "grade": "艺术类", + "subject": "美术", + "academic_year": 2026, + "term": "暑", + "guardian_title": "小谢妈妈", + "start_time": "18:00", + "end_time": "19:00" + }) + ), + responses( + (status = 200, description = "更新后的学生档案", body = StudentProfile), + (status = 404, description = "档案不存在或不属于当前用户", body = ErrorBody, example = json!({"error": "resource not found"})), + CommonApiErrors + ) +)] +async fn update_profile( + State(state): State, + headers: HeaderMap, + Path(profile_id): Path, + Json(input): Json, +) -> Result, ApiError> { + validate_profile(&input)?; + let owner_id = current_user(&headers)?; + let profile = sqlx::query_as::<_, StudentProfile>( + "UPDATE student_profiles \ + SET name = $1, grade = $2, subject = $3, academic_year = $4, term = $5, guardian_title = $6, \ + start_time = $7, end_time = $8, updated_at = now() \ + WHERE id = $9 AND owner_id = $10 \ + RETURNING id, name, grade, subject, academic_year, term, guardian_title, start_time, end_time, created_at, updated_at", + ) + .bind(input.name.trim()) + .bind(input.grade.trim()) + .bind(input.subject.trim()) + .bind(input.academic_year) + .bind(input.term.trim()) + .bind(input.guardian_title.trim()) + .bind(input.start_time.trim()) + .bind(input.end_time.trim()) + .bind(profile_id) + .bind(owner_id) + .fetch_optional(pool(&state)?) + .await? + .ok_or(ApiError::NotFound)?; + Ok(Json(profile)) +} + +/// 删除学生档案。 +#[utoipa::path( + delete, + path = "/api/v1/profiles/{profile_id}", + tag = "学生档案", + summary = "删除学生档案", + description = "删除属于当前用户的档案。关联反馈记录不会被删除,其 `profile_id` 会被置空。", + params( + ("X-User-Id" = Uuid, Header, description = "开发阶段用户 ID;必须与档案所属用户一致", example = json!("5a4da7f0-d70c-465f-bcab-124c504aa9f0")), + ("profile_id" = Uuid, Path, description = "学生档案 ID;将示例值替换为创建接口返回的 ID", example = json!("11111111-1111-4111-8111-111111111111")) + ), + responses( + (status = 204, description = "档案已删除"), + (status = 404, description = "档案不存在或不属于当前用户", body = ErrorBody, example = json!({"error": "resource not found"})), + CommonApiErrors + ) +)] +async fn delete_profile( + State(state): State, + headers: HeaderMap, + Path(profile_id): Path, +) -> Result { + let owner_id = current_user(&headers)?; + let result = sqlx::query("DELETE FROM student_profiles WHERE id = $1 AND owner_id = $2") + .bind(profile_id) + .bind(owner_id) + .execute(pool(&state)?) + .await?; + affected_or_not_found(result)?; + Ok(axum::http::StatusCode::NO_CONTENT) +} + +/// 当前用户的新建档案预设。 +#[derive(Debug, Serialize, FromRow, ToSchema)] +#[schema(example = json!({ + "grade": "艺术类", + "subject": "美术", + "lesson_duration_minutes": 60, + "updated_at": "2026-07-15T10:00:00Z" +}))] +struct ProfileDefaults { + /// 默认年级或学生类别。 + grade: String, + /// 默认授课学科。 + subject: String, + /// 默认课程时长,必须为 15 到 360 之间的 15 的倍数。 + lesson_duration_minutes: i16, + /// 最近更新时间,UTC;未保存过预设时为本次请求时间。 + updated_at: DateTime, +} + +/// 保存档案预设的请求体。 +#[derive(Debug, Deserialize, ToSchema)] +#[schema(example = json!({ + "grade": "艺术类", + "subject": "美术", + "lesson_duration_minutes": 60 +}))] +struct ProfileDefaultsInput { + /// 默认年级或学生类别,不可为空。 + grade: String, + /// 默认授课学科,不可为空。 + subject: String, + /// 默认课程时长,必须为 15 到 360 之间的 15 的倍数。 + lesson_duration_minutes: i16, +} + +/// 读取当前用户的新建档案预设。 +#[utoipa::path( + get, + path = "/api/v1/profile-defaults", + tag = "档案预设", + summary = "读取档案预设", + description = "读取当前用户的预设;尚未保存时直接返回艺术类、美术、60 分钟的系统默认值。", + params( + ("X-User-Id" = Uuid, Header, description = "开发阶段用户 ID;Scalar 已预填测试值", example = json!("5a4da7f0-d70c-465f-bcab-124c504aa9f0")) + ), + responses( + (status = 200, description = "当前档案预设", body = ProfileDefaults), + CommonApiErrors + ) +)] +async fn get_defaults( + State(state): State, + headers: HeaderMap, +) -> Result, ApiError> { + let owner_id = current_user(&headers)?; + let defaults = sqlx::query_as::<_, ProfileDefaults>( + "SELECT grade, subject, lesson_duration_minutes, updated_at \ + FROM student_profile_defaults WHERE owner_id = $1", + ) + .bind(owner_id) + .fetch_optional(pool(&state)?) + .await?; + + Ok(Json(defaults.unwrap_or_else(default_profile_defaults))) +} + +/// 保存当前用户的新建档案预设。 +#[utoipa::path( + put, + path = "/api/v1/profile-defaults", + tag = "档案预设", + summary = "保存档案预设", + description = "新增或覆盖当前用户的档案预设。Scalar 已预填完整请求体,可以直接执行测试。", + params( + ("X-User-Id" = Uuid, Header, description = "开发阶段用户 ID;Scalar 已预填测试值", example = json!("5a4da7f0-d70c-465f-bcab-124c504aa9f0")) + ), + request_body( + content = ProfileDefaultsInput, + description = "要保存的档案预设", + content_type = "application/json", + example = json!({ + "grade": "艺术类", + "subject": "美术", + "lesson_duration_minutes": 60 + }) + ), + responses( + (status = 200, description = "保存后的档案预设", body = ProfileDefaults), + CommonApiErrors + ) +)] +async fn update_defaults( + State(state): State, + headers: HeaderMap, + Json(input): Json, +) -> Result, ApiError> { + validate_defaults(&input)?; + let owner_id = current_user(&headers)?; + let defaults = sqlx::query_as::<_, ProfileDefaults>( + "INSERT INTO student_profile_defaults (owner_id, grade, subject, lesson_duration_minutes) \ + VALUES ($1, $2, $3, $4) \ + ON CONFLICT (owner_id) DO UPDATE SET \ + grade = EXCLUDED.grade, \ + subject = EXCLUDED.subject, \ + lesson_duration_minutes = EXCLUDED.lesson_duration_minutes, \ + updated_at = now() \ + RETURNING grade, subject, lesson_duration_minutes, updated_at", + ) + .bind(owner_id) + .bind(input.grade.trim()) + .bind(input.subject.trim()) + .bind(input.lesson_duration_minutes) + .fetch_one(pool(&state)?) + .await?; + Ok(Json(defaults)) +} + +/// 教学反馈记录。 +#[derive(Debug, Serialize, FromRow, ToSchema)] +#[schema(example = json!({ + "id": "22222222-2222-4222-8222-222222222222", + "profile_id": null, + "feedback_date": "2026-07-15", + "content": "今天完成了色彩搭配练习,构图有明显进步。", + "created_at": "2026-07-15T10:00:00Z", + "updated_at": "2026-07-15T10:00:00Z" +}))] +struct FeedbackRecord { + /// 反馈记录 ID。 + id: Uuid, + /// 关联的学生档案 ID;可以为空。 + profile_id: Option, + /// 反馈对应日期,格式为 `YYYY-MM-DD`。 + feedback_date: NaiveDate, + /// 教学反馈正文。 + content: String, + /// 创建时间,UTC。 + created_at: DateTime, + /// 最近更新时间,UTC。 + updated_at: DateTime, +} + +/// 创建教学反馈记录的请求体。 +#[derive(Debug, Deserialize, ToSchema)] +#[schema(example = json!({ + "profile_id": null, + "feedback_date": "2026-07-15", + "content": "今天完成了色彩搭配练习,构图有明显进步。", + "feedback_session_id": null +}))] +struct FeedbackRecordInput { + /// 可选的学生档案 ID;如填写,必须属于当前用户。Scalar 默认留空以便直接测试。 + profile_id: Option, + /// 反馈对应日期,格式为 `YYYY-MM-DD`。 + feedback_date: NaiveDate, + /// 教学反馈正文,不可为空。 + content: String, + /// 可选的语音反馈批次 ID;保存后对应批次会被标记为已完成。 + feedback_session_id: Option, +} + +#[derive(Debug, Deserialize)] +struct FeedbackRecordQuery { + profile_id: Option, +} + +/// 列出当前用户的教学反馈记录。 +#[utoipa::path( + get, + path = "/api/v1/feedback-records", + tag = "反馈记录", + summary = "列出反馈记录", + description = "按反馈日期和更新时间倒序返回当前用户的记录;可按学生档案 ID 筛选。", + params( + ("X-User-Id" = Uuid, Header, description = "开发阶段用户 ID;Scalar 已预填测试值", example = json!("5a4da7f0-d70c-465f-bcab-124c504aa9f0")), + ("profile_id" = Option, Query, description = "只返回关联到指定档案的记录;直接测试时可留空", example = json!("11111111-1111-4111-8111-111111111111")) + ), + responses( + (status = 200, description = "教学反馈记录列表", body = [FeedbackRecord]), + CommonApiErrors + ) +)] +async fn list_feedback_records( + State(state): State, + headers: HeaderMap, + Query(query): Query, +) -> Result>, ApiError> { + let owner_id = current_user(&headers)?; + let pool = pool(&state)?; + let mut statement = QueryBuilder::::new( + "SELECT id, profile_id, feedback_date, content, created_at, updated_at \ + FROM feedback_records WHERE owner_id = ", + ); + statement.push_bind(owner_id); + if let Some(profile_id) = query.profile_id { + statement.push(" AND profile_id = "); + statement.push_bind(profile_id); + } + statement.push(" ORDER BY feedback_date DESC, updated_at DESC"); + let records = statement + .build_query_as::() + .fetch_all(pool) + .await?; + Ok(Json(records)) +} + +/// 创建教学反馈记录。 +#[utoipa::path( + post, + path = "/api/v1/feedback-records", + tag = "反馈记录", + summary = "创建反馈记录", + description = "创建一条教学反馈。Scalar 默认将 `profile_id` 设为 null,因此无需先创建档案即可直接测试。", + params( + ("X-User-Id" = Uuid, Header, description = "开发阶段用户 ID;Scalar 已预填测试值", example = json!("5a4da7f0-d70c-465f-bcab-124c504aa9f0")) + ), + request_body( + content = FeedbackRecordInput, + description = "教学反馈内容", + content_type = "application/json", + example = json!({ + "profile_id": null, + "feedback_date": "2026-07-15", + "content": "今天完成了色彩搭配练习,构图有明显进步。", + "feedback_session_id": null + }) + ), + responses( + (status = 201, description = "反馈记录创建成功", body = FeedbackRecord), + (status = 404, description = "指定的学生档案不存在或不属于当前用户", body = ErrorBody, example = json!({"error": "resource not found"})), + CommonApiErrors + ) +)] +async fn create_feedback_record( + State(state): State, + headers: HeaderMap, + Json(input): Json, +) -> Result<(axum::http::StatusCode, Json), ApiError> { + if input.content.trim().is_empty() || input.content.chars().count() > 2000 { + return Err(ApiError::BadRequest( + "content must contain 1 to 2000 characters".to_owned(), + )); + } + let owner_id = current_user(&headers)?; + let pool = pool(&state)?; + if let Some(profile_id) = input.profile_id { + assert_profile_owner(pool, owner_id, profile_id).await?; + } + if let Some(session_id) = input.feedback_session_id { + let session_profile_id = sqlx::query_scalar::<_, Option>( + "SELECT profile_id FROM feedback_sessions \ + WHERE id = $1 AND owner_id = $2 AND status = 'active'", + ) + .bind(session_id) + .bind(owner_id) + .fetch_optional(pool) + .await? + .ok_or(ApiError::NotFound)?; + if session_profile_id != input.profile_id { + return Err(ApiError::BadRequest( + "feedback session profile does not match feedback record".to_owned(), + )); + } + } + let mut transaction = pool.begin().await?; + let record = sqlx::query_as::<_, FeedbackRecord>( + "INSERT INTO feedback_records (id, owner_id, profile_id, feedback_date, content) \ + VALUES ($1, $2, $3, $4, $5) \ + RETURNING id, profile_id, feedback_date, content, created_at, updated_at", + ) + .bind(Uuid::new_v4()) + .bind(owner_id) + .bind(input.profile_id) + .bind(input.feedback_date) + .bind(input.content.trim()) + .fetch_one(&mut *transaction) + .await?; + if let Some(session_id) = input.feedback_session_id { + sqlx::query( + "UPDATE feedback_sessions SET status = 'finalized', finalized_record_id = $2, updated_at = now() \ + WHERE id = $1", + ) + .bind(session_id) + .bind(record.id) + .execute(&mut *transaction) + .await?; + } + transaction.commit().await?; + Ok((axum::http::StatusCode::CREATED, Json(record))) +} + +/// 删除教学反馈记录。 +#[utoipa::path( + delete, + path = "/api/v1/feedback-records/{record_id}", + tag = "反馈记录", + summary = "删除反馈记录", + description = "删除属于当前用户的反馈记录。请先从创建或列表接口复制真实的记录 ID。", + params( + ("X-User-Id" = Uuid, Header, description = "开发阶段用户 ID;必须与记录所属用户一致", example = json!("5a4da7f0-d70c-465f-bcab-124c504aa9f0")), + ("record_id" = Uuid, Path, description = "反馈记录 ID;将示例值替换为创建接口返回的 ID", example = json!("22222222-2222-4222-8222-222222222222")) + ), + responses( + (status = 204, description = "反馈记录已删除"), + (status = 404, description = "记录不存在或不属于当前用户", body = ErrorBody, example = json!({"error": "resource not found"})), + CommonApiErrors + ) +)] +async fn delete_feedback_record( + State(state): State, + headers: HeaderMap, + Path(record_id): Path, +) -> Result { + let owner_id = current_user(&headers)?; + let result = sqlx::query("DELETE FROM feedback_records WHERE id = $1 AND owner_id = $2") + .bind(record_id) + .bind(owner_id) + .execute(pool(&state)?) + .await?; + affected_or_not_found(result)?; + Ok(axum::http::StatusCode::NO_CONTENT) +} + +fn current_user(headers: &HeaderMap) -> Result { + let value = headers + .get("x-user-id") + .and_then(|header| header.to_str().ok()) + .ok_or(ApiError::Unauthorized)?; + Uuid::parse_str(value).map_err(|_| ApiError::BadRequest("X-User-Id must be a UUID".to_owned())) +} + +fn pool(state: &AppState) -> Result<&PgPool, ApiError> { + state.pool.as_ref().ok_or(ApiError::DatabaseUnavailable) +} + +fn validate_profile(input: &ProfileInput) -> Result<(), ApiError> { + if input.name.trim().is_empty() || input.name.trim().chars().count() > 20 { + return Err(ApiError::BadRequest( + "name must contain 1 to 20 characters".to_owned(), + )); + } + if input.grade.trim().is_empty() || input.subject.trim().is_empty() { + return Err(ApiError::BadRequest( + "grade and subject are required".to_owned(), + )); + } + if !(2000..=2200).contains(&input.academic_year) { + return Err(ApiError::BadRequest( + "academic_year must be between 2000 and 2200".to_owned(), + )); + } + if !matches!(input.term.as_str(), "春" | "暑" | "秋" | "寒") { + return Err(ApiError::BadRequest( + "term must be 春, 暑, 秋, or 寒".to_owned(), + )); + } + if input.guardian_title.trim().is_empty() || input.guardian_title.trim().chars().count() > 24 { + return Err(ApiError::BadRequest( + "guardian_title must contain 1 to 24 characters".to_owned(), + )); + } + validate_time(&input.start_time, "start_time")?; + validate_time(&input.end_time, "end_time") +} + +fn validate_defaults(input: &ProfileDefaultsInput) -> Result<(), ApiError> { + if input.grade.trim().is_empty() || input.subject.trim().is_empty() { + return Err(ApiError::BadRequest( + "grade and subject are required".to_owned(), + )); + } + if !(15..=360).contains(&input.lesson_duration_minutes) + || input.lesson_duration_minutes % 15 != 0 + { + return Err(ApiError::BadRequest( + "lesson_duration_minutes must be a multiple of 15 between 15 and 360".to_owned(), + )); + } + Ok(()) +} + +fn validate_time(value: &str, field: &str) -> Result<(), ApiError> { + NaiveTime::parse_from_str(value, "%H:%M") + .map(|_| ()) + .map_err(|_| ApiError::BadRequest(format!("{field} must use HH:MM format"))) +} + +fn default_profile_defaults() -> ProfileDefaults { + ProfileDefaults { + grade: DEFAULT_GRADE.to_owned(), + subject: DEFAULT_SUBJECT.to_owned(), + lesson_duration_minutes: DEFAULT_DURATION_MINUTES, + updated_at: Utc::now(), + } +} + +fn affected_or_not_found(result: PgQueryResult) -> Result<(), ApiError> { + if result.rows_affected() == 0 { + return Err(ApiError::NotFound); + } + Ok(()) +} + +async fn assert_profile_owner( + pool: &PgPool, + owner_id: Uuid, + profile_id: Uuid, +) -> Result<(), ApiError> { + let exists = sqlx::query_scalar::<_, bool>( + "SELECT EXISTS(SELECT 1 FROM student_profiles WHERE id = $1 AND owner_id = $2)", + ) + .bind(profile_id) + .bind(owner_id) + .fetch_one(pool) + .await?; + if exists { + Ok(()) + } else { + Err(ApiError::NotFound) + } +} + +#[cfg(test)] +mod tests { + use serde_json::Value; + + use super::router; + + const TEST_USER_ID: &str = "5a4da7f0-d70c-465f-bcab-124c504aa9f0"; + + #[test] + fn openapi_documents_all_routes_and_default_test_data() { + let (_, openapi) = router(); + let document = serde_json::to_value(openapi).expect("OpenAPI should serialize"); + let paths = document["paths"] + .as_object() + .expect("OpenAPI should contain paths"); + + let operations = paths + .values() + .flat_map(|path| { + path.as_object() + .expect("path item should be an object") + .values() + }) + .filter(|operation| operation.get("responses").is_some()) + .collect::>(); + + assert_eq!(operations.len(), 20); + for operation in &operations { + assert_non_empty(operation, "summary"); + assert_non_empty(operation, "description"); + } + + let request_examples = operations + .iter() + .filter_map(|operation| { + operation.pointer("/requestBody/content/application~1json/example") + }) + .collect::>(); + assert_eq!(request_examples.len(), 4); + assert!(request_examples.iter().all(|example| example.is_object())); + + let business_operations = paths + .iter() + .filter(|(path, _)| path.starts_with("/api/v1/")) + .flat_map(|(_, path)| { + path.as_object() + .expect("path item should be an object") + .values() + }) + .filter(|operation| operation.get("responses").is_some()); + + for operation in business_operations { + let user_header = operation["parameters"] + .as_array() + .expect("business operation should have parameters") + .iter() + .find(|parameter| parameter["name"] == "X-User-Id" && parameter["in"] == "header") + .expect("business operation should document X-User-Id"); + assert_eq!(user_header["example"], TEST_USER_ID); + } + + assert_eq!(document["servers"][0]["url"], "/"); + assert!(document["info"].get("contact").is_none()); + assert!(document["info"].get("license").is_none()); + assert!(document["components"]["schemas"]["ProfileInput"]["example"].is_object()); + assert!(document["components"]["schemas"]["ProfileDefaultsInput"]["example"].is_object()); + assert!( + document["components"]["schemas"]["FeedbackRecordInput"]["example"]["profile_id"] + .is_null() + ); + } + + fn assert_non_empty(operation: &Value, field: &str) { + assert!( + operation[field] + .as_str() + .is_some_and(|value| !value.trim().is_empty()), + "operation should have a non-empty {field}" + ); + } +} diff --git a/server/src/speech.rs b/server/src/speech.rs new file mode 100644 index 0000000..aa3843d --- /dev/null +++ b/server/src/speech.rs @@ -0,0 +1,350 @@ +use std::{collections::BTreeMap, time::Duration}; + +use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64}; +use hmac::{Hmac, Mac}; +use reqwest::{ + Client, + header::{AUTHORIZATION, CONTENT_TYPE}, + multipart::{Form, Part}, +}; +use serde::Deserialize; +use sha1::Sha1; + +use crate::config::{SpeechConfig, SpeechProviderConfig, TencentSpeechConfig}; + +const ASR_HOST: &str = "asr.cloud.tencent.com"; + +#[derive(Clone)] +pub struct SpeechService { + config: Option, + client: Client, +} + +#[derive(Debug)] +pub struct Transcription { + pub text: String, + pub duration_ms: i32, + pub request_id: String, +} + +#[derive(Deserialize)] +struct LocalResponse { + text: String, + #[serde(default)] + duration_ms: i32, + #[serde(default)] + request_id: String, +} + +#[derive(Deserialize)] +struct FlashResponse { + code: i32, + message: String, + request_id: Option, + audio_duration: Option, + #[serde(default)] + flash_result: Vec, +} + +#[derive(Deserialize)] +struct FlashResult { + text: String, +} + +impl SpeechService { + pub fn new(config: Option) -> Self { + let timeout = config.as_ref().map_or(Duration::from_secs(30), |value| { + Duration::from_secs(value.request_timeout_seconds) + }); + let client = Client::builder() + .timeout(timeout) + .build() + .expect("reqwest client configuration should be valid"); + Self { config, client } + } + + pub fn configured(&self) -> bool { + self.config.is_some() + } + + pub fn provider_name(&self) -> Option<&'static str> { + self.config.as_ref().map(|config| match config.provider { + SpeechProviderConfig::Local { .. } => "local-funasr", + SpeechProviderConfig::Tencent(_) => "tencent", + }) + } + + pub fn worker_concurrency(&self) -> usize { + self.config + .as_ref() + .map_or(0, |config| config.worker_concurrency) + } + + pub fn job_lease_seconds(&self) -> i64 { + self.config + .as_ref() + .map_or(3_600, |config| config.job_lease_seconds) + } + + pub async fn available(&self) -> bool { + let Some(config) = &self.config else { + return false; + }; + match &config.provider { + SpeechProviderConfig::Local { api_url } => { + let request = self.client.get(format!("{api_url}/health")).send(); + matches!( + tokio::time::timeout(Duration::from_secs(2), request).await, + Ok(Ok(response)) if response.status().is_success() + ) + } + SpeechProviderConfig::Tencent(_) => true, + } + } + + pub async fn transcribe( + &self, + audio: Vec, + audio_format: &str, + duration_ms: i32, + ) -> Result { + let config = self + .config + .as_ref() + .ok_or_else(|| "语音转录服务尚未配置".to_owned())?; + match &config.provider { + SpeechProviderConfig::Local { api_url } => { + self.transcribe_local(api_url, audio, audio_format, duration_ms) + .await + } + SpeechProviderConfig::Tencent(config) => { + self.transcribe_tencent(config, audio, audio_format).await + } + } + } + + async fn transcribe_local( + &self, + api_url: &str, + audio: Vec, + audio_format: &str, + duration_ms: i32, + ) -> Result { + let part = Part::bytes(audio) + .file_name(format!("segment.{audio_format}")) + .mime_str(audio_content_type(audio_format)) + .map_err(|error| format!("录音格式无效:{error}"))?; + let form = Form::new() + .part("file", part) + .text("language", "zh") + .text("duration_ms", duration_ms.to_string()); + let response = self + .client + .post(local_transcription_url(api_url)) + .multipart(form) + .send() + .await + .map_err(|error| format!("本地语音转录服务连接失败:{error}"))?; + let status = response.status(); + let body = response + .text() + .await + .map_err(|error| format!("读取本地语音转录响应失败:{error}"))?; + if !status.is_success() { + return Err(format!( + "本地语音转录服务返回 HTTP {status}:{}", + compact_error(&body) + )); + } + let result: LocalResponse = serde_json::from_str(&body) + .map_err(|error| format!("本地语音转录响应格式无效:{error}"))?; + transcription(result.text, result.duration_ms, result.request_id) + } + + async fn transcribe_tencent( + &self, + config: &TencentSpeechConfig, + audio: Vec, + audio_format: &str, + ) -> Result { + let timestamp = chrono::Utc::now().timestamp(); + let (url, signature) = signed_request(config, audio_format, timestamp)?; + let response = self + .client + .post(url) + .header(AUTHORIZATION, signature) + .header(CONTENT_TYPE, "application/octet-stream") + .body(audio) + .send() + .await + .map_err(|error| format!("语音转录服务连接失败:{error}"))?; + let status = response.status(); + let body = response + .text() + .await + .map_err(|error| format!("读取语音转录响应失败:{error}"))?; + if !status.is_success() { + return Err(format!("语音转录服务返回 HTTP {status}")); + } + + let result: FlashResponse = serde_json::from_str(&body) + .map_err(|error| format!("语音转录响应格式无效:{error}"))?; + if result.code != 0 { + return Err(format!( + "语音转录失败({}):{}", + result.code, result.message + )); + } + let text = result + .flash_result + .into_iter() + .map(|channel| channel.text) + .collect::>() + .join("\n"); + transcription( + text, + result.audio_duration.unwrap_or_default(), + result.request_id.unwrap_or_default(), + ) + } +} + +fn transcription( + text: String, + duration_ms: i32, + request_id: String, +) -> Result { + let text = text.trim().to_owned(); + if text.is_empty() { + return Err("未识别到清晰语音".to_owned()); + } + Ok(Transcription { + text, + duration_ms, + request_id, + }) +} + +fn local_transcription_url(api_url: &str) -> String { + format!("{}/v1/transcriptions", api_url.trim_end_matches('/')) +} + +fn audio_content_type(audio_format: &str) -> &'static str { + match audio_format { + "aac" => "audio/aac", + "wav" => "audio/wav", + "m4a" => "audio/mp4", + "amr" => "audio/amr", + _ => "audio/mpeg", + } +} + +fn compact_error(body: &str) -> String { + let value = body.split_whitespace().collect::>().join(" "); + value.chars().take(240).collect() +} + +fn signed_request( + config: &TencentSpeechConfig, + audio_format: &str, + timestamp: i64, +) -> Result<(String, String), String> { + let mut params = BTreeMap::new(); + params.insert("convert_num_mode", "1".to_owned()); + params.insert("engine_type", config.engine_type.clone()); + params.insert("filter_dirty", "0".to_owned()); + params.insert("filter_modal", "1".to_owned()); + params.insert("filter_punc", "0".to_owned()); + params.insert("first_channel_only", "1".to_owned()); + params.insert("secretid", config.secret_id.clone()); + params.insert("speaker_diarization", "0".to_owned()); + params.insert("timestamp", timestamp.to_string()); + params.insert("voice_format", audio_format.to_owned()); + params.insert("word_info", "0".to_owned()); + + let query = url::form_urlencoded::Serializer::new(String::new()) + .extend_pairs(params.iter()) + .finish(); + let path = format!("/asr/flash/v1/{}", config.app_id); + let source = format!("POST{ASR_HOST}{path}?{query}"); + let mut mac = Hmac::::new_from_slice(config.secret_key.as_bytes()) + .map_err(|_| "语音转录密钥格式无效".to_owned())?; + mac.update(source.as_bytes()); + let signature = BASE64.encode(mac.finalize().into_bytes()); + + Ok((format!("https://{ASR_HOST}{path}?{query}"), signature)) +} + +#[cfg(test)] +mod tests { + use axum::{ + Json, Router, + routing::{get, post}, + }; + use serde_json::json; + + use crate::config::{SpeechConfig, SpeechProviderConfig, TencentSpeechConfig}; + + use super::{SpeechService, local_transcription_url, signed_request}; + + #[test] + fn signed_request_sorts_parameters_and_is_stable() { + let config = TencentSpeechConfig { + app_id: 123, + secret_id: "secret-id".to_owned(), + secret_key: "secret-key".to_owned(), + engine_type: "16k_zh".to_owned(), + }; + let first = signed_request(&config, "mp3", 1_700_000_000).unwrap(); + let second = signed_request(&config, "mp3", 1_700_000_000).unwrap(); + + assert_eq!(first, second); + assert!(first.0.contains("convert_num_mode=1&engine_type=16k_zh")); + assert!(first.0.ends_with("voice_format=mp3&word_info=0")); + assert!(!first.1.is_empty()); + } + + #[test] + fn local_url_has_one_transcription_suffix() { + assert_eq!( + local_transcription_url("http://127.0.0.1:10095/"), + "http://127.0.0.1:10095/v1/transcriptions" + ); + } + + #[tokio::test] + async fn local_provider_sends_audio_and_parses_response() { + let app = Router::new() + .route("/health", get(|| async { Json(json!({"status": "ok"})) })) + .route( + "/v1/transcriptions", + post(|| async { + Json(json!({ + "text": "课堂练习完成。", + "duration_ms": 12_345, + "request_id": "local-request" + })) + }), + ); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + let service = SpeechService::new(Some(SpeechConfig { + provider: SpeechProviderConfig::Local { + api_url: format!("http://{address}"), + }, + request_timeout_seconds: 5, + worker_concurrency: 1, + job_lease_seconds: 60, + })); + + assert!(service.available().await); + let result = service + .transcribe(vec![1, 2, 3], "mp3", 10_000) + .await + .unwrap(); + assert_eq!(result.text, "课堂练习完成。"); + assert_eq!(result.duration_ms, 12_345); + assert_eq!(result.request_id, "local-request"); + } +} diff --git a/server/src/summary.rs b/server/src/summary.rs new file mode 100644 index 0000000..df5dbd5 --- /dev/null +++ b/server/src/summary.rs @@ -0,0 +1,193 @@ +use std::collections::HashSet; + +use reqwest::header::{AUTHORIZATION, CONTENT_TYPE}; +use serde::{Deserialize, Serialize}; + +use crate::config::SummaryConfig; + +const MAX_FEEDBACK_CHARS: usize = 2000; + +#[derive(Clone)] +pub struct SummaryService { + config: Option, + client: reqwest::Client, +} + +#[derive(Debug)] +pub struct SummaryResult { + pub content: String, + pub method: &'static str, +} + +#[derive(Serialize)] +struct ChatRequest<'a> { + model: &'a str, + messages: Vec>, + temperature: f32, +} + +#[derive(Serialize)] +struct ChatMessage<'a> { + role: &'a str, + content: &'a str, +} + +#[derive(Deserialize)] +struct ChatResponse { + choices: Vec, +} + +#[derive(Deserialize)] +struct ChatChoice { + message: ChatChoiceMessage, +} + +#[derive(Deserialize)] +struct ChatChoiceMessage { + content: String, +} + +impl SummaryService { + pub fn new(config: Option) -> Self { + Self { + config, + client: reqwest::Client::new(), + } + } + + pub fn configured(&self) -> bool { + self.config.is_some() + } + + pub async fn summarize( + &self, + existing_content: &str, + lesson_transcripts: &[String], + ) -> Result { + let Some(config) = &self.config else { + return Ok(SummaryResult { + content: extractive_summary(existing_content, lesson_transcripts), + method: "extractive", + }); + }; + + let transcript_text = lesson_transcripts + .iter() + .enumerate() + .map(|(index, transcript)| format!("第{}节课:\n{}", index + 1, transcript)) + .collect::>() + .join("\n\n"); + let user_prompt = format!( + "教师已填写内容:\n{}\n\n新增课堂转录:\n{}", + existing_content.trim(), + transcript_text + ); + let system_prompt = "你是教学反馈整理助手。请把教师已有内容与课堂转录合并成一份面向家长的中文反馈,保留具体事实,按课堂表现、进步、问题和后续建议组织。不要虚构,不要提及录音或转录,不超过2000个汉字,只输出反馈正文。"; + let request = ChatRequest { + model: &config.model, + messages: vec![ + ChatMessage { + role: "system", + content: system_prompt, + }, + ChatMessage { + role: "user", + content: &user_prompt, + }, + ], + temperature: 0.2, + }; + let mut builder = self + .client + .post(&config.api_url) + .header(CONTENT_TYPE, "application/json") + .json(&request); + if let Some(api_key) = &config.api_key { + builder = builder.header(AUTHORIZATION, format!("Bearer {api_key}")); + } + let response = builder + .send() + .await + .map_err(|error| format!("反馈汇总服务连接失败:{error}"))?; + let status = response.status(); + if !status.is_success() { + return Err(format!("反馈汇总服务返回 HTTP {status}")); + } + let result: ChatResponse = response + .json() + .await + .map_err(|error| format!("反馈汇总响应格式无效:{error}"))?; + let content = result + .choices + .into_iter() + .next() + .map(|choice| choice.message.content.trim().to_owned()) + .filter(|content| !content.is_empty()) + .ok_or_else(|| "反馈汇总服务未返回内容".to_owned())?; + + Ok(SummaryResult { + content: content.chars().take(MAX_FEEDBACK_CHARS).collect(), + method: "llm", + }) + } +} + +fn extractive_summary(existing_content: &str, lesson_transcripts: &[String]) -> String { + let existing = existing_content.trim(); + let mut result = existing + .chars() + .take(MAX_FEEDBACK_CHARS) + .collect::(); + let mut seen = HashSet::new(); + let mut selected = Vec::new(); + + for transcript in lesson_transcripts { + for sentence in transcript.split_inclusive(['。', '!', '?', '\n']) { + let sentence = sentence.trim(); + if sentence.chars().count() < 4 || !seen.insert(sentence.to_owned()) { + continue; + } + selected.push(sentence.to_owned()); + } + } + + if !selected.is_empty() && result.chars().count() < MAX_FEEDBACK_CHARS { + if !result.is_empty() { + result.push_str("\n\n"); + } + result.push_str("课堂记录汇总:\n"); + for sentence in selected { + let prefix = "- "; + let remaining = MAX_FEEDBACK_CHARS.saturating_sub(result.chars().count()); + if remaining <= prefix.chars().count() + 4 { + break; + } + result.push_str(prefix); + result.extend( + sentence + .chars() + .take(remaining - prefix.chars().count() - 1), + ); + result.push('\n'); + } + } + + result.trim().to_owned() +} + +#[cfg(test)] +mod tests { + use super::extractive_summary; + + #[test] + fn extractive_summary_preserves_manual_content_and_deduplicates() { + let result = extractive_summary( + "手动备注。", + &["完成了构图练习。完成了构图练习。色彩更大胆。".to_owned()], + ); + + assert!(result.starts_with("手动备注。")); + assert_eq!(result.matches("完成了构图练习。").count(), 1); + assert!(result.contains("色彩更大胆。")); + } +} diff --git a/server/src/transcription_worker.rs b/server/src/transcription_worker.rs new file mode 100644 index 0000000..36b325f --- /dev/null +++ b/server/src/transcription_worker.rs @@ -0,0 +1,202 @@ +use std::time::Duration; + +use sqlx::{FromRow, PgPool}; +use uuid::Uuid; + +use crate::speech::{SpeechService, Transcription}; + +const IDLE_POLL_INTERVAL: Duration = Duration::from_millis(750); +const UNAVAILABLE_POLL_INTERVAL: Duration = Duration::from_secs(5); + +#[derive(Debug, FromRow)] +struct TranscriptionJob { + id: Uuid, + lesson_session_id: Uuid, + duration_ms: i32, + audio_format: String, + audio_path: String, +} + +pub fn spawn(pool: PgPool, speech: SpeechService) { + for worker_id in 1..=speech.worker_concurrency() { + let pool = pool.clone(); + let speech = speech.clone(); + tokio::spawn(async move { + run(worker_id, pool, speech).await; + }); + } +} + +async fn run(worker_id: usize, pool: PgPool, speech: SpeechService) { + let mut service_available = true; + loop { + match has_claimable_job(&pool, speech.job_lease_seconds()).await { + Ok(false) => { + tokio::time::sleep(IDLE_POLL_INTERVAL).await; + continue; + } + Ok(true) => {} + Err(error) => { + tracing::error!(worker_id, error = %error, "failed to inspect transcription queue"); + tokio::time::sleep(UNAVAILABLE_POLL_INTERVAL).await; + continue; + } + } + let available = speech.available().await; + if !available { + if service_available { + tracing::warn!(worker_id, provider = ?speech.provider_name(), "ASR service is unavailable; queued audio will wait"); + } + service_available = false; + tokio::time::sleep(UNAVAILABLE_POLL_INTERVAL).await; + continue; + } + if !service_available { + tracing::info!(worker_id, provider = ?speech.provider_name(), "ASR service is available again"); + } + service_available = true; + + match claim_next_job(&pool, speech.job_lease_seconds()).await { + Ok(Some(job)) => { + tracing::info!(worker_id, segment_id = %job.id, "transcribing audio segment"); + if let Err(error) = process_job(&pool, &speech, &job).await { + tracing::error!(worker_id, segment_id = %job.id, error = %error, "transcription job update failed"); + tokio::time::sleep(IDLE_POLL_INTERVAL).await; + } + } + Ok(None) => tokio::time::sleep(IDLE_POLL_INTERVAL).await, + Err(error) => { + tracing::error!(worker_id, error = %error, "failed to claim transcription job"); + tokio::time::sleep(UNAVAILABLE_POLL_INTERVAL).await; + } + } + } +} + +async fn has_claimable_job(pool: &PgPool, lease_seconds: i64) -> Result { + sqlx::query_scalar( + "SELECT EXISTS(\ + SELECT 1 FROM audio_segments \ + WHERE status = 'processing' \ + AND (processing_started_at IS NULL \ + OR processing_started_at < now() - ($1 * interval '1 second'))\ + )", + ) + .bind(lease_seconds) + .fetch_one(pool) + .await +} + +async fn claim_next_job( + pool: &PgPool, + lease_seconds: i64, +) -> Result, sqlx::Error> { + sqlx::query_as::<_, TranscriptionJob>( + "WITH next_job AS (\ + SELECT id FROM audio_segments \ + WHERE status = 'processing' \ + AND (processing_started_at IS NULL \ + OR processing_started_at < now() - ($1 * interval '1 second')) \ + ORDER BY created_at, id \ + FOR UPDATE SKIP LOCKED LIMIT 1\ + ) \ + UPDATE audio_segments AS segment \ + SET processing_started_at = now(), \ + transcription_attempts = transcription_attempts + 1, \ + updated_at = now() \ + FROM next_job \ + WHERE segment.id = next_job.id \ + RETURNING segment.id, segment.lesson_session_id, segment.duration_ms, \ + segment.audio_format, segment.audio_path", + ) + .bind(lease_seconds) + .fetch_optional(pool) + .await +} + +async fn process_job( + pool: &PgPool, + speech: &SpeechService, + job: &TranscriptionJob, +) -> Result<(), sqlx::Error> { + let result = match tokio::fs::read(&job.audio_path).await { + Ok(audio) => { + speech + .transcribe(audio, &job.audio_format, job.duration_ms) + .await + } + Err(error) => Err(format!("读取录音文件失败:{error}")), + }; + + match result { + Ok(transcription) => complete_job(pool, job, transcription).await?, + Err(message) => fail_job(pool, job, &message).await?, + } + refresh_lesson(pool, job.lesson_session_id).await?; + Ok(()) +} + +async fn complete_job( + pool: &PgPool, + job: &TranscriptionJob, + transcription: Transcription, +) -> Result<(), sqlx::Error> { + let duration_ms = if transcription.duration_ms > 0 { + transcription.duration_ms + } else { + job.duration_ms + }; + sqlx::query( + "UPDATE audio_segments \ + SET status = 'ready', duration_ms = $2, transcript = $3, error_message = NULL, \ + provider_request_id = $4, processing_started_at = NULL, updated_at = now() \ + WHERE id = $1", + ) + .bind(job.id) + .bind(duration_ms) + .bind(&transcription.text) + .bind(&transcription.request_id) + .execute(pool) + .await?; + tracing::info!(segment_id = %job.id, "audio segment transcription is ready"); + Ok(()) +} + +async fn fail_job(pool: &PgPool, job: &TranscriptionJob, message: &str) -> Result<(), sqlx::Error> { + tracing::warn!(segment_id = %job.id, error = %message, "audio transcription failed"); + sqlx::query( + "UPDATE audio_segments \ + SET status = 'failed', error_message = $2, processing_started_at = NULL, updated_at = now() \ + WHERE id = $1", + ) + .bind(job.id) + .bind(message) + .execute(pool) + .await?; + Ok(()) +} + +async fn refresh_lesson(pool: &PgPool, lesson_id: Uuid) -> Result<(), sqlx::Error> { + sqlx::query( + "UPDATE lesson_sessions AS lesson \ + SET status = CASE \ + WHEN EXISTS (SELECT 1 FROM audio_segments WHERE lesson_session_id = $1 AND status = 'failed') THEN 'failed' \ + WHEN EXISTS (SELECT 1 FROM audio_segments WHERE lesson_session_id = $1 AND status = 'processing') THEN 'processing' \ + ELSE 'ready' \ + END, \ + duration_ms = COALESCE((SELECT SUM(duration_ms) FROM audio_segments WHERE lesson_session_id = $1), 0), \ + updated_at = now() \ + WHERE lesson.id = $1 AND lesson.ended_at IS NOT NULL", + ) + .bind(lesson_id) + .execute(pool) + .await?; + sqlx::query( + "UPDATE feedback_sessions SET updated_at = now() \ + WHERE id = (SELECT feedback_session_id FROM lesson_sessions WHERE id = $1)", + ) + .bind(lesson_id) + .execute(pool) + .await?; + Ok(()) +}