diff --git a/.env.example b/.env.example index 4ac4eba..aa1697d 100644 --- a/.env.example +++ b/.env.example @@ -1,6 +1,7 @@ QB_DATABASE_URL=postgres://postgres:postgres@127.0.0.1:5432/qb QB_BIND_ADDR=127.0.0.1:8080 QB_EXPORT_DIR=./exports +QB_OBJECT_STORE_DIR=./objects QB_MAX_DB_CONNECTIONS=10 QB_CORS_ORIGINS=http://localhost:3000,http://localhost:5173 QB_JWT_SECRET=qb-dev-secret-change-me-in-production diff --git a/Cargo.lock b/Cargo.lock index 0a1e888..6b017ef 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -450,6 +450,17 @@ dependencies = [ "pin-project-lite", ] +[[package]] +name = "filetime" +version = "0.2.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f98844151eee8917efc50bd9e8318cb963ae8b297431495d3f758616ea5c57db" +dependencies = [ + "cfg-if", + "libc", + "libredox", +] + [[package]] name = "find-msvc-tools" version = "0.1.9" @@ -969,6 +980,12 @@ dependencies = [ "vcpkg", ] +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + [[package]] name = "litemap" version = "0.8.1" @@ -1307,13 +1324,14 @@ dependencies = [ [[package]] name = "qb_api" -version = "1.1.1" +version = "1.2.0" dependencies = [ "anyhow", "argon2", "axum", "chrono", "csv", + "flate2", "http-body-util", "jsonwebtoken", "mime_guess", @@ -1323,6 +1341,7 @@ dependencies = [ "serial_test", "sha2", "sqlx", + "tar", "tokio", "tokio-util", "tower", @@ -1459,6 +1478,19 @@ dependencies = [ "zeroize", ] +[[package]] +name = "rustix" +version = "1.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.61.2", +] + [[package]] name = "rustls" version = "0.23.37" @@ -1988,6 +2020,17 @@ dependencies = [ "syn", ] +[[package]] +name = "tar" +version = "0.4.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22692a6476a21fa75fdfc11d452fda482af402c008cdbaf3476414e122040973" +dependencies = [ + "filetime", + "libc", + "xattr", +] + [[package]] name = "thiserror" version = "2.0.18" @@ -2766,6 +2809,16 @@ version = "0.6.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9edde0db4769d2dc68579893f2306b26c6ecfbe0ef499b013d731b7b9247e0b9" +[[package]] +name = "xattr" +version = "1.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32e45ad4206f6d2479085147f02bc2ef834ac85886624a23575ae137c8aa8156" +dependencies = [ + "libc", + "rustix", +] + [[package]] name = "yoke" version = "0.8.1" diff --git a/Cargo.toml b/Cargo.toml index 63fc6b5..747fe07 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "qb_api" -version = "1.1.1" +version = "1.2.0" edition = "2021" [dependencies] @@ -9,6 +9,7 @@ argon2 = "0.5" axum = { version = "0.7", features = ["multipart"] } chrono = { version = "0.4", features = ["serde"] } csv = "1" +flate2 = "1" jsonwebtoken = "9" mime_guess = "2" regex = "1" @@ -16,6 +17,7 @@ serde = { version = "1", features = ["derive"] } serde_json = "1" sha2 = "0.10" sqlx = { version = "0.8", default-features = false, features = ["runtime-tokio-rustls", "postgres", "chrono"] } +tar = "0.4" tokio = { version = "1", features = ["macros", "rt-multi-thread", "net", "fs", "signal"] } tokio-util = { version = "0.7", features = ["io"] } tower-http = { version = "0.6", features = ["cors", "trace"] } diff --git a/compose.prod.env.example b/compose.prod.env.example index 7392bd6..179ccac 100644 --- a/compose.prod.env.example +++ b/compose.prod.env.example @@ -7,6 +7,7 @@ QB_JWT_SECRET=change-this-to-a-long-random-string QB_BIND_PORT=8080 QB_MAX_DB_CONNECTIONS=20 QB_EXPORT_DIR=/var/lib/qb/exports +QB_OBJECT_STORE_DIR=/var/lib/qb/objects QB_CORS_ORIGINS=https://your-frontend.example.com QB_IMAGE_NAME=qb_api QB_IMAGE_TAG=latest diff --git a/docker-compose.prod.yml b/docker-compose.prod.yml index c0175a2..0584b19 100644 --- a/docker-compose.prod.yml +++ b/docker-compose.prod.yml @@ -27,15 +27,18 @@ services: db: condition: service_healthy environment: + RUST_LOG: qb_api=info,tower_http=info QB_DATABASE_URL: ${QB_DATABASE_URL} QB_BIND_ADDR: 0.0.0.0:8080 QB_EXPORT_DIR: ${QB_EXPORT_DIR:-/var/lib/qb/exports} QB_MAX_DB_CONNECTIONS: ${QB_MAX_DB_CONNECTIONS:-20} QB_CORS_ORIGINS: ${QB_CORS_ORIGINS:-} QB_JWT_SECRET: ${QB_JWT_SECRET} + QB_OBJECT_STORE_DIR: ${QB_OBJECT_STORE_DIR:-/var/lib/qb/objects} ports: - "${QB_BIND_PORT:-8080}:8080" volumes: + - qb_object_store:${QB_OBJECT_STORE_DIR:-/var/lib/qb/objects} - qb_exports:${QB_EXPORT_DIR:-/var/lib/qb/exports} healthcheck: test: ["CMD-SHELL", "curl -fsS http://127.0.0.1:8080/health >/dev/null || exit 1"] @@ -46,4 +49,5 @@ services: volumes: qb_postgres_data: + qb_object_store: qb_exports: diff --git a/docs/API.md b/docs/API.md index 5cc975e..aa4862e 100644 --- a/docs/API.md +++ b/docs/API.md @@ -382,7 +382,7 @@ Bot 账号不会自动生成;管理员创建或轮换 bot 账号时,接口 ## Questions — 题目 -> 题目的增删改查、文件替换、审阅人管理、难度管理和批量打包接口。 +> 题目的增删改查、文件替换、审阅人管理、难度管理、对象下载和批量打包接口。 所有请求需携带 `Authorization: Bearer ` 头。普通账号使用 JWT access token;bot 使用管理员签发的长期 access token。 @@ -415,6 +415,7 @@ Bot 账号不会自动生成;管理员创建或轮换 bot 账号时,接口 - 上传时,后端自动设置 difficulty 为空、status 为 `none`、author 为上传者 display_name、reviewers 为 `[]` - 后端自动维护 `created_by`、`created_at`、`updated_at` - 题目创建者(`created_by`)始终可修改自己题目的 description、category、tags 和 file,不受 status 限制 +- 题目 TeX 和资源文件以对象形式存储;`QuestionDetail.tex_object_id` 和 `QuestionDetail.assets[].object_id` 可通过 `GET /objects/:object_id` 下载 --- @@ -462,7 +463,68 @@ Bot 账号不会自动生成;管理员创建或轮换 bot 账号时,接口 #### `QuestionDetail` -在 `QuestionSummary` 基础上增加 `tex_object_id`、`assets`、`papers`。 +```json +{ + "question_id": "uuid", + "tex_object_id": "uuid", + "source": { "tex": "problem.tex" }, + "category": "T", + "status": "reviewed", + "description": "热学标定 gamma", + "score": 20, + "author": "张三", + "reviewers": ["李四"], + "tags": ["optics", "thermodynamics"], + "difficulty": {}, + "created_by": "uuid or null", + "created_at": "2026-01-01T00:00:00.000Z", + "updated_at": "2026-01-01T00:00:00.000Z", + "assets": [ + { + "path": "assets/fig1.png", + "file_kind": "asset", + "object_id": "uuid", + "mime_type": "image/png" + } + ], + "papers": [ + { + "paper_id": "uuid", + "description": "综合训练试卷 A", + "title": "综合训练 2026 A 卷", + "subtitle": "校内选拔 初版", + "sort_order": 1 + } + ] +} +``` + +在 `QuestionSummary` 基础上增加以下字段: + +| 字段 | 类型 | 说明 | +|---|---|---| +| `tex_object_id` | string(UUID) | TeX 源文件对象 ID,可通过 `GET /objects/:object_id` 下载 | +| `assets` | object[] | 题目资源文件列表 | +| `papers` | object[] | 引用该题目的未软删除试卷列表 | + +`assets[]` 字段: + +| 字段 | 类型 | 说明 | +|---|---|---| +| `path` | string | 资源文件相对路径,如 `assets/fig1.png` | +| `file_kind` | string | 当前固定为 `"asset"` | +| `object_id` | string(UUID) | 对象 ID,可通过 `GET /objects/:object_id` 下载 | +| `mime_type` | string \| null | 推断出的 MIME 类型 | + +`papers[]` 字段: + +| 字段 | 类型 | 说明 | +|---|---|---| +| `paper_id` | string(UUID) | 试卷 ID | +| `description` | string | 试卷描述 | +| `title` | string | 试卷标题 | +| `subtitle` | string | 试卷副标题 | +| `sort_order` | int | 该题目在试卷中的顺序 | --- @@ -552,6 +614,32 @@ Bot 账号不会自动生成;管理员创建或轮换 bot 账号时,接口 --- +#### `GET /objects/:object_id` + +下载单个对象文件。该接口主要用于读取题目详情里的 `tex_object_id` 和 `assets[].object_id`。 + +- **认证**:`viewer` 及以上 +- **路径参数**:`object_id` — UUID + +**成功响应** `200`: + +- **Content-Type**:对象记录中的 `mime_type`;缺失时回退为 `application/octet-stream` +- **Header**: + - `content-disposition: inline; filename=""` + - `content-length` + - `cache-control: public, max-age=31536000, immutable` + - 若对象有内容哈希,还会返回 `etag` +- **Body**:对象原始二进制内容 + +**缓存行为**: + +- 支持 `If-None-Match` +- 当请求头中的 ETag 命中对象内容哈希时返回 `304 Not Modified` + +**错误**:`404` — 对象不存在 + +--- + #### `POST /questions` 上传新题目(zip 包)。 @@ -748,6 +836,46 @@ Bot 账号不会自动生成;管理员创建或轮换 bot 账号时,接口 批量下载题目 zip 打包。认证:`viewer` 及以上。 +- **Content-Type**:`application/json` + +**请求体**: + +| 字段 | 类型 | 必填 | 说明 | +|---|---|---|---| +| `question_ids` | string(UUID)[] | ✅ | 题目 ID 列表,非空、去重、每项必须为有效 UUID | + +```json +{ + "question_ids": ["uuid-1", "uuid-2"] +} +``` + +**成功响应** `200`: + +- **Content-Type**:`application/zip` +- **Header** 含 `content-disposition` 和 `content-length` + +**ZIP 结构**: + +``` +manifest.json +热学标定gamma_550e84/ + problem.tex + assets/ + fig1.png +``` + +- `manifest.json`:题目元数据和文件清单 +- 每个题目目录命名:`{description}_{uuid前6位}/` +- 目录内保留原始 TeX 路径和 `assets/` 结构 + +**错误**: + +| 状态码 | 场景 | +|---|---| +| `400` | 列表为空 / 含无效 UUID / 有重复 | +| `404` | 有题目不存在或已软删除 | + --- @@ -1086,21 +1214,23 @@ manifest.json #### `GET /database/backup` -下载当前数据库的 plain SQL 备份文件。 +下载当前数据库的 `.tar.gz` 备份文件。 - **认证**:`admin` - **请求体**:无 **成功响应** `200`: -- **Content-Type**:`application/sql` +- **Content-Type**:`application/gzip` - **Header** 含 `content-disposition`(下载文件名)和 `content-length` -- **Body**:`pg_dump` 生成的 plain SQL,可按 [部署文档](../docs/DEPLOYMENT.md) 中的恢复方式导入 +- **Body**:`.tar.gz` 归档,包含: + - `metadata.sql`:`pg_dump` 生成的 plain SQL 元数据备份 + - `objects/`:对象存储目录中的二进制文件 **说明**: - 该接口直接返回下载文件,不写入 `QB_EXPORT_DIR` -- 备份包含 PostgreSQL 中的全部业务表和对象数据(包括 `objects` 表中的题目 zip / 试卷附件内容) +- 备份同时覆盖 PostgreSQL 元数据和 `QB_OBJECT_STORE_DIR` 中的对象文件 - 如果内置 `pg_dump` 与数据库 major version 不匹配,接口会返回具体错误提示;需要重建 API 镜像并对齐 PostgreSQL client 版本 --- @@ -1182,14 +1312,14 @@ manifest.json ```json { "output_path": "/absolute/path/to/exports/quality_report.json", - "report": { - "missing_tex_object": ["question-uuid-1"], - "missing_tex_source": ["question-uuid-2"], - "missing_asset_objects": [ - { "question_id": "uuid", "path": "assets/fig.png", "object_id": "uuid" } - ], - "empty_papers": ["paper-uuid-1"] - } + "report": { + "missing_tex_object": ["question-uuid-1"], + "missing_tex_source": ["question-uuid-2"], + "missing_asset_objects": [ + { "question_id": "uuid", "file_path": "assets/fig.png", "object_id": "uuid" } + ], + "empty_papers": ["paper-uuid-1"] + } } ``` @@ -1198,37 +1328,41 @@ manifest.json | 字段 | 类型 | 说明 | |---|---|---| | `missing_tex_object` | string[] | tex 对象记录缺失的题目 ID | -| `missing_tex_source` | string[] | tex 对象内容为空的题目 ID | -| `missing_asset_objects` | object[] | 资源对象缺失的条目 | +| `missing_tex_source` | string[] | tex 对象记录存在,但内容为空的题目 ID | +| `missing_asset_objects` | object[] | 资源对象记录缺失的条目;字段为 `question_id`、`file_path`、`object_id` | | `empty_papers` | string[] | 不含任何题目的试卷 ID | --- #### `POST /database/restore` -上传 plain SQL 备份并覆盖恢复当前数据库内容。 +上传备份文件并覆盖恢复当前数据库内容。 - **认证**:`admin` - **Content-Type**:`multipart/form-data` -- **大小限制**:上传文件 ≤ 64 MiB +- **大小限制**:上传文件 ≤ 256 MiB **Multipart 字段**: | 字段 | 类型 | 必填 | 说明 | |---|---|---|---| -| `file` | binary (sql) | ✅ | 由 `GET /database/backup` 或 `pg_dump` 生成的 plain SQL 文件 | +| `file` | binary | ✅ | 优先上传 `GET /database/backup` 生成的 `.tar.gz` 文件;也兼容 legacy plain SQL 文件 | **行为**: -- 先执行 `DROP SCHEMA public CASCADE; CREATE SCHEMA public;` -- 再执行 `psql -v ON_ERROR_STOP=1 -f ` 导入上传文件 +- 如果上传的是 `.tar.gz`: + - 解压 `metadata.sql` + - 执行 `DROP SCHEMA public CASCADE; CREATE SCHEMA public;` + - 执行 `psql -v ON_ERROR_STOP=1 -f metadata.sql` + - 将归档中的 `objects/` 内容复制到 `QB_OBJECT_STORE_DIR` +- 如果上传的是 legacy `.sql`:仅恢复数据库内容,不写入对象目录 - 恢复流程与 [部署文档](../docs/DEPLOYMENT.md) 中“覆盖当前库”的恢复方法保持一致 **成功响应** `200`: ```json { - "file_name": "qb_backup.sql", + "file_name": "qb_backup.tar.gz", "restored_bytes": 123456, "status": "restored" } @@ -1238,7 +1372,7 @@ manifest.json | 状态码 | 场景 | |---|---| -| `400` | 缺少 `file` 字段 / 上传文件为空 / 文件超过 64 MiB | +| `400` | 缺少 `file` 字段 / 上传文件为空 / 文件超过 256 MiB | | `500` | `psql` 恢复失败;响应里的 `error` 会尽量返回具体 stderr 提示。如果失败发生在清空 schema 之后,数据库可能已被部分覆盖 | @@ -1394,6 +1528,8 @@ manifest.json } ``` +**说明**:preview 只回滚数据库事务,也不会删除对象存储目录中的文件。 + --- #### `POST /admin/garbage-collections/run` @@ -1408,7 +1544,8 @@ manifest.json 1. 硬删除所有已软删除试卷 2. 硬删除"已软删且不再被未软删试卷引用"的题目 -3. 删除所有无任何引用的 objects(含关联的二进制数据) +3. 删除所有无任何引用的 objects +4. 事务提交成功后,再清理对象存储目录中对应的二进制文件 **成功响应** `200`:格式同 preview,但 `dry_run: false`。 diff --git a/docs/v2-cleanup.md b/docs/v2-cleanup.md new file mode 100644 index 0000000..b080e5e --- /dev/null +++ b/docs/v2-cleanup.md @@ -0,0 +1,57 @@ +# v2.0.0 Legacy Cleanup + +v1.2.0 引入了文件系统对象存储,但保留了 BYTEA 回退和 `.sql` restore 兼容。 +v2.0.0 删除这些过渡代码。**前提:所有部署至少运行过一次 v1.2.0**。 + +## 1. 新增 SQL migration + +`migrations/0006_drop_legacy_bytea.sql`: + +```sql +-- 确认不存在未迁移的行 +DO $$ +BEGIN + IF EXISTS (SELECT 1 FROM objects WHERE storage_path IS NULL LIMIT 1) THEN + RAISE EXCEPTION 'unmigrated BYTEA objects exist — run v1.2.0 first'; + END IF; +END $$; + +ALTER TABLE objects DROP COLUMN content; +ALTER TABLE objects ALTER COLUMN storage_path SET NOT NULL; +ALTER TABLE objects ALTER COLUMN content_hash SET NOT NULL; +``` + +## 2. 新增 schema_migrations 跟踪表 + +`migrations/0007_schema_migrations.sql`: + +```sql +CREATE TABLE IF NOT EXISTS schema_migrations ( + version TEXT PRIMARY KEY, + applied_at TIMESTAMPTZ NOT NULL DEFAULT NOW() +); +``` + +Rust 端新增 `apply_pending_migrations(pool)` 函数:扫描 `migrations/*.sql`, +跳过 `schema_migrations` 中已存在的 version,执行后插入记录。 +`main.rs` 启动时调用,restore 后也调用(替代当前的逐文件重跑)。 + +## 3. 删除 legacy Rust 代码 + +| 文件 | 位置 | 改动 | +|------|------|------| +| `src/api/shared/db.rs` | `fetch_object_bytes` | 删除 BYTEA fallback 分支(`content` 列已不存在),只读文件系统 | +| `src/api/shared/db.rs` | `fetch_object_meta` | `storage_path`/`content_hash` 改为非 `Option` | +| `src/api/shared/db.rs` | `migrate_legacy_objects` | 删除整个方法 | +| `src/api/shared/db.rs` | `insert_object_tx` | SQL 中删除 `content` 字段 | +| `src/main.rs` | L33-40 | 删除 `migrate_legacy_objects()` 调用 | +| `src/api/ops/quality.rs` | `object_blob_nonempty` | 删除 `octet_length(content)` legacy 分支 | +| `src/api/ops/database.rs` | `restore_database_backup` | 删除 legacy raw `.sql` restore 路径,只保留 tar.gz | +| `src/api/ops/database.rs` | `temp_restore_upload_path` | 删除 `.sql` 扩展名处理 | + +## 4. 版本号 + +`Cargo.toml` → `version = "2.0.0"`。Major bump 因为: +- backup restore 不再接受旧 `.sql` 格式 +- `objects` 表 schema 变化(DROP COLUMN content) +- 必须从 v1.2.0+ 升级,不可跳版本 diff --git a/migrations/0005_objects_filesystem_storage.sql b/migrations/0005_objects_filesystem_storage.sql new file mode 100644 index 0000000..6148cd3 --- /dev/null +++ b/migrations/0005_objects_filesystem_storage.sql @@ -0,0 +1,8 @@ +-- Migrate binary object storage from BYTEA blobs to filesystem-backed storage. +-- After this migration, new objects are written to disk and the `content` column +-- is left NULL. Existing rows keep their BYTEA data until the application-level +-- auto-migration moves them to the filesystem on startup. + +ALTER TABLE objects ADD COLUMN IF NOT EXISTS content_hash TEXT; +ALTER TABLE objects ADD COLUMN IF NOT EXISTS storage_path TEXT; +ALTER TABLE objects ALTER COLUMN content DROP NOT NULL; diff --git a/scripts/tests/config.py b/scripts/tests/config.py index b43c859..12dfe38 100644 --- a/scripts/tests/config.py +++ b/scripts/tests/config.py @@ -9,7 +9,7 @@ API_LOG_PATH = TMP_DIR / "qb_api_e2e.log" EXPORT_PATH = TMP_DIR / "qb_e2e_internal.jsonl" QUALITY_PATH = TMP_DIR / "qb_e2e_quality.json" -DB_BACKUP_PATH = DOWNLOADS_DIR / "qb_e2e_backup.sql" +DB_BACKUP_PATH = DOWNLOADS_DIR / "qb_e2e_backup.tar.gz" REPORT_PATH = TMP_DIR / "qb_e2e_report.md" INVALID_PAPER_UPLOAD_PATH = SAMPLES_DIR / "paper_invalid_upload.bin" REAL_TEST_ZIP_PATH = ROOT_DIR / "scripts" / "test.zip" diff --git a/scripts/tests/session.py b/scripts/tests/session.py index 27d03a5..119c93b 100644 --- a/scripts/tests/session.py +++ b/scripts/tests/session.py @@ -331,12 +331,15 @@ def apply_migration(self) -> None: def start_api(self) -> None: self._api_log = API_LOG_PATH.open("wb") + object_store_dir = TMP_DIR / "object_store" + object_store_dir.mkdir(parents=True, exist_ok=True) env = { **os.environ, "QB_DATABASE_URL": DB_URL, "QB_BIND_ADDR": f"127.0.0.1:{API_PORT}", "QB_EXPORT_DIR": str(TMP_DIR), "QB_POSTGRES_CONTAINER_NAME": CONTAINER_NAME, + "QB_OBJECT_STORE_DIR": str(object_store_dir), } self._api_proc = subprocess.Popen( ["cargo", "run"], cwd=ROOT_DIR, env=env, diff --git a/scripts/tests/test_3_ops.py b/scripts/tests/test_3_ops.py index 5393897..5c269af 100644 --- a/scripts/tests/test_3_ops.py +++ b/scripts/tests/test_3_ops.py @@ -2,7 +2,9 @@ from __future__ import annotations +import gzip import json +import tarfile import uuid from .config import DB_BACKUP_PATH, DOWNLOADS_DIR, EXPORT_PATH, QUALITY_PATH @@ -91,14 +93,15 @@ def test_quality_check_path_traversal(api): def test_database_backup_download(api): backup_bytes, headers = api.download_file("/database/backup", DB_BACKUP_PATH) - sql_text = backup_bytes.decode("utf-8", errors="replace") - assert headers["content-type"] == "application/sql" + assert headers["content-type"] == "application/gzip" assert "attachment;" in headers["content-disposition"] - assert ".sql" in headers["content-disposition"] - assert sql_text.startswith("--") - assert "CREATE TABLE public.questions" in sql_text - assert "CREATE TABLE public.users" in sql_text + assert ".tar.gz" in headers["content-disposition"] + + # Verify it's a valid gzip/tar archive containing metadata.sql + with tarfile.open(fileobj=gzip.open(DB_BACKUP_PATH), mode="r:") as tar: + names = tar.getnames() + assert "metadata.sql" in names def test_database_restore_round_trip(api, state): @@ -118,7 +121,7 @@ def test_database_restore_round_trip(api, state): api.upload( "/database/restore", file_path=DB_BACKUP_PATH, - file_content_type="application/sql", + file_content_type="application/gzip", )[1] ) assert restored == { diff --git a/src/api/admin/API.md b/src/api/admin/API.md index 69d24b2..1223895 100644 --- a/src/api/admin/API.md +++ b/src/api/admin/API.md @@ -148,6 +148,8 @@ } ``` +**说明**:preview 只回滚数据库事务,也不会删除对象存储目录中的文件。 + --- ### `POST /admin/garbage-collections/run` @@ -162,7 +164,8 @@ 1. 硬删除所有已软删除试卷 2. 硬删除"已软删且不再被未软删试卷引用"的题目 -3. 删除所有无任何引用的 objects(含关联的二进制数据) +3. 删除所有无任何引用的 objects +4. 事务提交成功后,再清理对象存储目录中对应的二进制文件 **成功响应** `200`:格式同 preview,但 `dry_run: false`。 diff --git a/src/api/admin/handlers.rs b/src/api/admin/handlers.rs index 9e2b358..76eb29f 100644 --- a/src/api/admin/handlers.rs +++ b/src/api/admin/handlers.rs @@ -138,7 +138,7 @@ pub(crate) async fn run_gc( Json(_request): Json, ) -> ApiResult { Ok(Json( - run_garbage_collection(&state.pool) + run_garbage_collection(&state.pool, &state.object_store) .await .map_err(ApiError::from)?, )) diff --git a/src/api/admin/queries.rs b/src/api/admin/queries.rs index d514c05..df9fa9d 100644 --- a/src/api/admin/queries.rs +++ b/src/api/admin/queries.rs @@ -12,6 +12,7 @@ use crate::api::{ load_question_difficulties_batch, load_question_tags_batch, map_question_summary, }, shared::{ + db::ObjectStore, details::{load_paper_detail, load_question_detail, DetailVisibility, TIMESTAMP_SQL}, error::{ConflictError, NotFoundError}, utils::escape_ilike, @@ -432,16 +433,20 @@ pub(crate) async fn restore_paper(pool: &PgPool, paper_id: &str) -> Result Result { - execute_garbage_collection(pool, true).await + execute_garbage_collection(pool, true, None).await } -pub(crate) async fn run_garbage_collection(pool: &PgPool) -> Result { - execute_garbage_collection(pool, false).await +pub(crate) async fn run_garbage_collection( + pool: &PgPool, + object_store: &ObjectStore, +) -> Result { + execute_garbage_collection(pool, false, Some(object_store)).await } async fn execute_garbage_collection( pool: &PgPool, dry_run: bool, + object_store: Option<&ObjectStore>, ) -> Result { let mut tx = pool .begin() @@ -483,7 +488,7 @@ async fn execute_garbage_collection( AND NOT EXISTS ( SELECT 1 FROM papers p WHERE p.append_object_id = o.object_id ) - RETURNING o.size_bytes + RETURNING o.size_bytes, o.storage_path "#, ) .fetch_all(&mut *tx) @@ -491,9 +496,13 @@ async fn execute_garbage_collection( .context("purge orphaned objects failed")?; let deleted_objects = deleted_object_rows.len(); let freed_bytes = deleted_object_rows - .into_iter() + .iter() .map(|row| row.get::("size_bytes")) .sum(); + let deleted_storage_paths: Vec = deleted_object_rows + .iter() + .filter_map(|row| row.get::, _>("storage_path")) + .collect(); if dry_run { tx.rollback() @@ -503,6 +512,10 @@ async fn execute_garbage_collection( tx.commit() .await .context("commit garbage collection failed")?; + // Clean up object files from disk after successful commit. + if let Some(store) = object_store { + store.delete_object_files(&deleted_storage_paths); + } } Ok(GarbageCollectionResponse { diff --git a/src/api/mod.rs b/src/api/mod.rs index 7743b64..d045e98 100644 --- a/src/api/mod.rs +++ b/src/api/mod.rs @@ -22,10 +22,12 @@ pub use self::papers::models::{PaperDetail, PaperSummary}; pub use self::questions::models::{ QuestionAssetRef, QuestionDetail, QuestionPaperRef, QuestionSummary, }; +pub use self::shared::db::ObjectStore; #[derive(Clone)] pub struct AppState { pub pool: PgPool, + pub object_store: ObjectStore, pub database_url: String, pub export_dir: PathBuf, pub jwt_secret: String, @@ -149,6 +151,10 @@ pub fn router(state: AppState, cors_origins: &[String]) -> Router { "/papers/bundles", axum::routing::post(papers::handlers::download_papers_bundle), ) + .route( + "/objects/:object_id", + axum::routing::get(shared::serve::get_object), + ) .layer(axum_middleware::from_fn_with_state( state.clone(), auth::middleware::require_auth, diff --git a/src/api/ops/API.md b/src/api/ops/API.md index 9caa134..23d3304 100644 --- a/src/api/ops/API.md +++ b/src/api/ops/API.md @@ -11,21 +11,23 @@ ### `GET /database/backup` -下载当前数据库的 plain SQL 备份文件。 +下载当前数据库的 `.tar.gz` 备份文件。 - **认证**:`admin` - **请求体**:无 **成功响应** `200`: -- **Content-Type**:`application/sql` +- **Content-Type**:`application/gzip` - **Header** 含 `content-disposition`(下载文件名)和 `content-length` -- **Body**:`pg_dump` 生成的 plain SQL,可按 [部署文档](../../../docs/DEPLOYMENT.md) 中的恢复方式导入 +- **Body**:`.tar.gz` 归档,包含: + - `metadata.sql`:`pg_dump` 生成的 plain SQL 元数据备份 + - `objects/`:对象存储目录中的二进制文件 **说明**: - 该接口直接返回下载文件,不写入 `QB_EXPORT_DIR` -- 备份包含 PostgreSQL 中的全部业务表和对象数据(包括 `objects` 表中的题目 zip / 试卷附件内容) +- 备份同时覆盖 PostgreSQL 元数据和 `QB_OBJECT_STORE_DIR` 中的对象文件 - 如果内置 `pg_dump` 与数据库 major version 不匹配,接口会返回具体错误提示;需要重建 API 镜像并对齐 PostgreSQL client 版本 --- @@ -107,14 +109,14 @@ ```json { "output_path": "/absolute/path/to/exports/quality_report.json", - "report": { - "missing_tex_object": ["question-uuid-1"], - "missing_tex_source": ["question-uuid-2"], - "missing_asset_objects": [ - { "question_id": "uuid", "path": "assets/fig.png", "object_id": "uuid" } - ], - "empty_papers": ["paper-uuid-1"] - } + "report": { + "missing_tex_object": ["question-uuid-1"], + "missing_tex_source": ["question-uuid-2"], + "missing_asset_objects": [ + { "question_id": "uuid", "file_path": "assets/fig.png", "object_id": "uuid" } + ], + "empty_papers": ["paper-uuid-1"] + } } ``` @@ -123,37 +125,41 @@ | 字段 | 类型 | 说明 | |---|---|---| | `missing_tex_object` | string[] | tex 对象记录缺失的题目 ID | -| `missing_tex_source` | string[] | tex 对象内容为空的题目 ID | -| `missing_asset_objects` | object[] | 资源对象缺失的条目 | +| `missing_tex_source` | string[] | tex 对象记录存在,但内容为空的题目 ID | +| `missing_asset_objects` | object[] | 资源对象记录缺失的条目;字段为 `question_id`、`file_path`、`object_id` | | `empty_papers` | string[] | 不含任何题目的试卷 ID | --- ### `POST /database/restore` -上传 plain SQL 备份并覆盖恢复当前数据库内容。 +上传备份文件并覆盖恢复当前数据库内容。 - **认证**:`admin` - **Content-Type**:`multipart/form-data` -- **大小限制**:上传文件 ≤ 64 MiB +- **大小限制**:上传文件 ≤ 256 MiB **Multipart 字段**: | 字段 | 类型 | 必填 | 说明 | |---|---|---|---| -| `file` | binary (sql) | ✅ | 由 `GET /database/backup` 或 `pg_dump` 生成的 plain SQL 文件 | +| `file` | binary | ✅ | 优先上传 `GET /database/backup` 生成的 `.tar.gz` 文件;也兼容 legacy plain SQL 文件 | **行为**: -- 先执行 `DROP SCHEMA public CASCADE; CREATE SCHEMA public;` -- 再执行 `psql -v ON_ERROR_STOP=1 -f ` 导入上传文件 +- 如果上传的是 `.tar.gz`: + - 解压 `metadata.sql` + - 执行 `DROP SCHEMA public CASCADE; CREATE SCHEMA public;` + - 执行 `psql -v ON_ERROR_STOP=1 -f metadata.sql` + - 将归档中的 `objects/` 内容复制到 `QB_OBJECT_STORE_DIR` +- 如果上传的是 legacy `.sql`:仅恢复数据库内容,不写入对象目录 - 恢复流程与 [部署文档](../../../docs/DEPLOYMENT.md) 中“覆盖当前库”的恢复方法保持一致 **成功响应** `200`: ```json { - "file_name": "qb_backup.sql", + "file_name": "qb_backup.tar.gz", "restored_bytes": 123456, "status": "restored" } @@ -163,5 +169,5 @@ | 状态码 | 场景 | |---|---| -| `400` | 缺少 `file` 字段 / 上传文件为空 / 文件超过 64 MiB | +| `400` | 缺少 `file` 字段 / 上传文件为空 / 文件超过 256 MiB | | `500` | `psql` 恢复失败;响应里的 `error` 会尽量返回具体 stderr 提示。如果失败发生在清空 schema 之后,数据库可能已被部分覆盖 | diff --git a/src/api/ops/database.rs b/src/api/ops/database.rs index d80f85e..9152240 100644 --- a/src/api/ops/database.rs +++ b/src/api/ops/database.rs @@ -1,7 +1,7 @@ use std::{ env, fs::File, - io::ErrorKind, + io::{ErrorKind, Read}, path::{Path, PathBuf}, process::{Command, Output, Stdio}, }; @@ -13,14 +13,15 @@ use axum::{ response::Response, }; use chrono::Utc; +use flate2::{read::GzDecoder, write::GzEncoder, Compression}; use tokio::fs; use tokio_util::io::ReaderStream; use uuid::Uuid; -pub(crate) const MAX_RESTORE_UPLOAD_BYTES: usize = 64 * 1024 * 1024; +pub(crate) const MAX_RESTORE_UPLOAD_BYTES: usize = 256 * 1024 * 1024; pub(crate) fn backup_download_name() -> String { - format!("qb_backup_{}.sql", Utc::now().format("%Y%m%d_%H%M%S")) + format!("qb_backup_{}.tar.gz", Utc::now().format("%Y%m%d_%H%M%S")) } pub(crate) fn normalize_uploaded_backup_name(file_name: Option<&str>) -> String { @@ -29,13 +30,13 @@ pub(crate) fn normalize_uploaded_backup_name(file_name: Option<&str>) -> String .and_then(|name| name.to_str()) .map(str::trim) .filter(|name| !name.is_empty()) - .unwrap_or("database_backup.sql") + .unwrap_or("database_backup.tar.gz") .to_string() } pub(crate) fn temp_backup_path() -> PathBuf { env::temp_dir().join(format!( - "qb_database_backup_{}_{}.sql", + "qb_database_backup_{}_{}.tar.gz", Utc::now().format("%Y%m%d_%H%M%S"), Uuid::new_v4() )) @@ -46,27 +47,36 @@ pub(crate) fn temp_restore_upload_path(file_name: Option<&str>) -> PathBuf { .and_then(|name| Path::new(name).extension()) .and_then(|extension| extension.to_str()) .filter(|extension| !extension.trim().is_empty()) - .unwrap_or("sql"); + .unwrap_or("tar.gz"); + + // Handle double extension like .tar.gz + let ext = if file_name + .map(|n| n.ends_with(".tar.gz")) + .unwrap_or(false) + { + "tar.gz" + } else { + extension + }; env::temp_dir().join(format!( "qb_database_restore_upload_{}.{}", Uuid::new_v4(), - extension + ext )) } +/// Generate a full backup archive (tar.gz) containing: +/// - `metadata.sql`: pg_dump of the database (with BYTEA content excluded) +/// - `objects/`: copy of the filesystem object store pub(crate) async fn generate_database_backup( database_url: String, + object_store_dir: PathBuf, output_path: PathBuf, ) -> Result<()> { tokio::task::spawn_blocking(move || { - let result = run_native_backup(&database_url, &output_path).or_else(|err| { - if let Some(container_name) = postgres_container_name_if_missing_client(&err) { - run_container_backup(&container_name, &output_path) - } else { - Err(err) - } - }); + let result = + build_backup_archive(&database_url, &object_store_dir, &output_path); if result.is_err() { std::fs::remove_file(&output_path).ok(); @@ -74,45 +84,174 @@ pub(crate) async fn generate_database_backup( result }) .await - .context("wait pg_dump task failed")? + .context("wait backup task failed")? } +fn build_backup_archive( + database_url: &str, + object_store_dir: &Path, + output_path: &Path, +) -> Result<()> { + // Step 1: pg_dump to a temp file + let sql_path = env::temp_dir().join(format!("qb_pgdump_{}.sql", Uuid::new_v4())); + let dump_result = run_native_backup(database_url, &sql_path).or_else(|err| { + if let Some(container_name) = postgres_container_name_if_missing_client(&err) { + run_container_backup(&container_name, &sql_path) + } else { + Err(err) + } + }); + if dump_result.is_err() { + std::fs::remove_file(&sql_path).ok(); + return dump_result; + } + + // Step 2: Build tar.gz archive + let tar_file = + File::create(output_path).context("create backup archive file failed")?; + let gz = GzEncoder::new(tar_file, Compression::default()); + let mut tar_builder = tar::Builder::new(gz); + + // Add metadata.sql + tar_builder + .append_path_with_name(&sql_path, "metadata.sql") + .context("add metadata.sql to backup archive failed")?; + std::fs::remove_file(&sql_path).ok(); + + // Add objects directory if it exists + if object_store_dir.is_dir() { + tar_builder + .append_dir_all("objects", object_store_dir) + .context("add objects directory to backup archive failed")?; + } + + tar_builder + .finish() + .context("finalize backup archive failed")?; + + Ok(()) +} + +/// Restore from a backup archive. +/// +/// Accepts both the new tar.gz format and the legacy raw SQL format. pub(crate) async fn restore_database_backup( database_url: String, + object_store_dir: PathBuf, input_path: PathBuf, ) -> Result<()> { - let input_path = input_path.to_string_lossy().to_string(); + let input_path_clone = input_path.clone(); tokio::task::spawn_blocking(move || { - run_native_restore(&database_url, &input_path).or_else(|err| { - if let Some(container_name) = postgres_container_name_if_missing_client(&err) { - run_container_restore(&container_name, &input_path) - } else { - Err(err) - } - })?; - Ok(()) + // Detect format: try to read as gzip/tar first, fall back to raw SQL + if is_tar_gz(&input_path_clone) { + restore_from_archive(&database_url, &object_store_dir, &input_path_clone) + } else { + // Legacy: raw .sql file + let sql_path = input_path_clone.to_string_lossy().to_string(); + run_native_restore(&database_url, &sql_path).or_else(|err| { + if let Some(container_name) = postgres_container_name_if_missing_client(&err) { + run_container_restore(&container_name, &sql_path) + } else { + Err(err) + } + }) + } }) .await .context("wait database restore task failed")? } -pub(crate) async fn finish_sql_download_response( - sql_path: PathBuf, +fn is_tar_gz(path: &Path) -> bool { + // Check magic bytes: gzip starts with 0x1f 0x8b + let Ok(mut file) = File::open(path) else { + return false; + }; + let mut magic = [0u8; 2]; + file.read_exact(&mut magic).is_ok() && magic == [0x1f, 0x8b] +} + +fn restore_from_archive( + database_url: &str, + object_store_dir: &Path, + archive_path: &Path, +) -> Result<()> { + let file = File::open(archive_path).context("open backup archive failed")?; + let gz = GzDecoder::new(file); + let mut archive = tar::Archive::new(gz); + + let extract_dir = env::temp_dir().join(format!("qb_restore_{}", Uuid::new_v4())); + std::fs::create_dir_all(&extract_dir).context("create restore temp dir failed")?; + + archive + .unpack(&extract_dir) + .context("extract backup archive failed")?; + + // Apply the SQL dump + let sql_path = extract_dir.join("metadata.sql"); + if !sql_path.exists() { + // Cleanup temp dir + std::fs::remove_dir_all(&extract_dir).ok(); + bail!("backup archive does not contain metadata.sql"); + } + + let sql_path_str = sql_path.to_string_lossy().to_string(); + let restore_result = run_native_restore(database_url, &sql_path_str).or_else(|err| { + if let Some(container_name) = postgres_container_name_if_missing_client(&err) { + run_container_restore(&container_name, &sql_path_str) + } else { + Err(err) + } + }); + + if let Err(err) = restore_result { + std::fs::remove_dir_all(&extract_dir).ok(); + return Err(err); + } + + // Copy objects directory to the object store + let extracted_objects = extract_dir.join("objects"); + if extracted_objects.is_dir() { + copy_dir_contents(&extracted_objects, object_store_dir) + .context("copy restored objects to object store failed")?; + } + + std::fs::remove_dir_all(&extract_dir).ok(); + Ok(()) +} + +/// Recursively copy contents of `src` into `dst`. +fn copy_dir_contents(src: &Path, dst: &Path) -> Result<()> { + std::fs::create_dir_all(dst)?; + for entry in std::fs::read_dir(src)? { + let entry = entry?; + let src_path = entry.path(); + let dst_path = dst.join(entry.file_name()); + if src_path.is_dir() { + copy_dir_contents(&src_path, &dst_path)?; + } else { + std::fs::copy(&src_path, &dst_path)?; + } + } + Ok(()) +} + +pub(crate) async fn finish_backup_download_response( + archive_path: PathBuf, download_name: &str, ) -> Result { - let file = File::open(&sql_path) - .with_context(|| format!("open backup file failed: {}", sql_path.to_string_lossy()))?; + let file = File::open(&archive_path) + .with_context(|| format!("open backup file failed: {}", archive_path.to_string_lossy()))?; let size = file .metadata() .context("read backup metadata failed")? .len() .to_string(); - std::fs::remove_file(&sql_path).ok(); + std::fs::remove_file(&archive_path).ok(); let stream = ReaderStream::new(fs::File::from_std(file)); let body = Body::from_stream(stream); - let content_type = HeaderValue::from_static("application/sql"); + let content_type = HeaderValue::from_static("application/gzip"); let disposition = HeaderValue::from_str(&format!("attachment; filename=\"{download_name}\"")) .context("build content-disposition header failed")?; let content_length = @@ -327,14 +466,22 @@ mod tests { #[test] fn normalize_uploaded_backup_name_strips_parent_directories() { assert_eq!( - normalize_uploaded_backup_name(Some("../../nested/qb_backup.sql")), - "qb_backup.sql" + normalize_uploaded_backup_name(Some("../../nested/qb_backup.tar.gz")), + "qb_backup.tar.gz" ); } #[test] - fn temp_restore_upload_path_defaults_to_sql_extension() { + fn temp_restore_upload_path_defaults_to_tar_gz_extension() { let path = temp_restore_upload_path(None); + // Default extension + let path_str = path.to_string_lossy(); + assert!(path_str.ends_with(".tar.gz")); + } + + #[test] + fn temp_restore_upload_path_uses_sql_for_legacy() { + let path = temp_restore_upload_path(Some("backup.sql")); assert_eq!(path.extension().and_then(|ext| ext.to_str()), Some("sql")); } diff --git a/src/api/ops/exports.rs b/src/api/ops/exports.rs index e653241..a8cec6e 100644 --- a/src/api/ops/exports.rs +++ b/src/api/ops/exports.rs @@ -17,7 +17,7 @@ use crate::api::{ models::QuestionSourceRef, queries::{load_question_difficulties, load_question_files, load_question_tags}, }, - shared::{db::fetch_text_object, utils::canonical_or_original}, + shared::{db::ObjectStore, utils::canonical_or_original}, }; pub(crate) fn default_export_path(format: ExportFormat, is_public: bool) -> PathBuf { @@ -43,6 +43,7 @@ pub(crate) fn ensure_parent_dir(output_path: &Path, label: &str) -> Result<()> { pub(crate) async fn export_jsonl( pool: &PgPool, + object_store: &ObjectStore, output_path: &Path, include_tex_source: bool, ) -> Result { @@ -99,7 +100,7 @@ pub(crate) async fn export_jsonl( if include_tex_source && !tex_object_id.is_empty() { payload["tex_source"] = - serde_json::Value::String(fetch_text_object(pool, &tex_object_id).await?); + serde_json::Value::String(object_store.fetch_text_object(&tex_object_id).await?); } writer @@ -114,6 +115,7 @@ pub(crate) async fn export_jsonl( pub(crate) async fn export_csv( pool: &PgPool, + object_store: &ObjectStore, output_path: &Path, include_tex_source: bool, ) -> Result { @@ -183,7 +185,7 @@ pub(crate) async fn export_csv( row.get::("created_at"), row.get::("updated_at"), if include_tex_source && !tex_object_id.is_empty() { - fetch_text_object(pool, &tex_object_id).await? + object_store.fetch_text_object(&tex_object_id).await? } else { String::new() }, diff --git a/src/api/ops/handlers.rs b/src/api/ops/handlers.rs index 386c083..82c92f5 100644 --- a/src/api/ops/handlers.rs +++ b/src/api/ops/handlers.rs @@ -10,7 +10,7 @@ use serde_json::json; use super::{ database::{ - backup_download_name, finish_sql_download_response, generate_database_backup, + backup_download_name, finish_backup_download_response, generate_database_backup, normalize_uploaded_backup_name, restore_database_backup as restore_database_from_backup, temp_backup_path, temp_restore_upload_path, MAX_RESTORE_UPLOAD_BYTES, }, @@ -47,8 +47,24 @@ pub(crate) async fn run_export( ensure_parent_dir(&output_path, "export")?; let exported_count = match request.format { - ExportFormat::Jsonl => export_jsonl(&state.pool, &output_path, request.public).await?, - ExportFormat::Csv => export_csv(&state.pool, &output_path, request.public).await?, + ExportFormat::Jsonl => { + export_jsonl( + &state.pool, + &state.object_store, + &output_path, + request.public, + ) + .await? + } + ExportFormat::Csv => { + export_csv( + &state.pool, + &state.object_store, + &output_path, + request.public, + ) + .await? + } }; Ok(Json(ExportResponse { @@ -94,11 +110,15 @@ pub(crate) async fn download_database_backup( State(state): State, ) -> Result { let backup_path = temp_backup_path(); - generate_database_backup(state.database_url.clone(), backup_path.clone()) - .await - .map_err(ops_internal)?; + generate_database_backup( + state.database_url.clone(), + state.object_store.store_dir().to_path_buf(), + backup_path.clone(), + ) + .await + .map_err(ops_internal)?; - finish_sql_download_response(backup_path, &backup_download_name()) + finish_backup_download_response(backup_path, &backup_download_name()) .await .map_err(ops_internal) } @@ -122,8 +142,12 @@ pub(crate) async fn restore_database_backup( }) .map_err(ops_internal)?; - let restore_result = - restore_database_from_backup(state.database_url.clone(), upload_path.clone()).await; + let restore_result = restore_database_from_backup( + state.database_url.clone(), + state.object_store.store_dir().to_path_buf(), + upload_path.clone(), + ) + .await; std::fs::remove_file(&upload_path).ok(); restore_result.map_err(ops_internal)?; diff --git a/src/api/ops/quality.rs b/src/api/ops/quality.rs index 422b76d..dd0dc89 100644 --- a/src/api/ops/quality.rs +++ b/src/api/ops/quality.rs @@ -23,16 +23,31 @@ pub(crate) async fn object_exists(pool: &PgPool, object_id: &str) -> Result Result { - let row = query("SELECT octet_length(content) AS size FROM objects WHERE object_id = $1::uuid") - .bind(object_id) - .fetch_optional(pool) - .await - .with_context(|| format!("check object blob failed: {object_id}"))?; + let row = query( + "SELECT size_bytes, storage_path, octet_length(content) AS content_size FROM objects WHERE object_id = $1::uuid", + ) + .bind(object_id) + .fetch_optional(pool) + .await + .with_context(|| format!("check object blob failed: {object_id}"))?; - Ok(row - .and_then(|r| r.try_get::, _>("size").ok().flatten()) - .unwrap_or(0) - > 0) + match row { + Some(r) => { + // If migrated to filesystem, check size_bytes > 0 + let storage_path: Option = r.get("storage_path"); + if storage_path.is_some() { + let size_bytes: i64 = r.get("size_bytes"); + return Ok(size_bytes > 0); + } + // Legacy: check content BYTEA length + Ok(r.try_get::, _>("content_size") + .ok() + .flatten() + .unwrap_or(0) + > 0) + } + None => Ok(false), + } } pub(crate) async fn build_quality_report(pool: &PgPool) -> Result { diff --git a/src/api/papers/bundles.rs b/src/api/papers/bundles.rs index 6faf90a..c886b85 100644 --- a/src/api/papers/bundles.rs +++ b/src/api/papers/bundles.rs @@ -20,7 +20,7 @@ use crate::api::{ finish_zip_response, temp_zip_path, timestamp_unix, write_bundle_file, write_manifest, BundleFileEntry, }, - db::fetch_object_bytes, + db::ObjectStore, error::NotFoundError, utils::bundle_directory_name, }, @@ -71,7 +71,7 @@ struct PaperAppendixData { } pub(crate) async fn build_paper_bundle_response( - pool: &PgPool, + object_store: &ObjectStore, paper_ids: &[String], ) -> Result { let bundle_name = format!("papers_bundle_{}.zip", timestamp_unix()); @@ -86,12 +86,12 @@ pub(crate) async fn build_paper_bundle_response( let mut manifest_items = Vec::with_capacity(paper_ids.len()); for paper_id in paper_ids { - let bundle = load_paper_bundle_data(pool, paper_id).await?; + let bundle = load_paper_bundle_data(object_store.pool(), paper_id).await?; let directory = bundle_directory_name(&bundle.metadata.description, paper_id); let append_file = - write_paper_appendix_file(pool, &mut writer, bundle.appendix.as_ref(), &directory) + write_paper_appendix_file(object_store, &mut writer, bundle.appendix.as_ref(), &directory) .await?; - let rendered = render_paper_bundle(build_render_paper_input(pool, &bundle).await?)?; + let rendered = render_paper_bundle(build_render_paper_input(object_store, &bundle).await?)?; let main_tex_zip_path = format!("{directory}/main.tex"); write_bundle_file( @@ -160,7 +160,7 @@ pub(crate) async fn build_paper_bundle_response( } async fn write_paper_appendix_file( - pool: &PgPool, + object_store: &ObjectStore, writer: &mut ZipWriter, appendix: Option<&PaperAppendixData>, directory: &str, @@ -170,7 +170,7 @@ async fn write_paper_appendix_file( }; let zip_path = format!("{directory}/append.zip"); - let bytes = fetch_object_bytes(pool, &appendix.object_id).await?; + let bytes = object_store.fetch_object_bytes(&appendix.object_id).await?; write_bundle_file(writer, &zip_path, &bytes)?; Ok(Some(BundleFileEntry { @@ -244,14 +244,16 @@ async fn load_paper_bundle_data(pool: &PgPool, paper_id: &str) -> Result Result { let template_kind = determine_paper_template_kind(&bundle.questions)?; let mut questions = Vec::with_capacity(bundle.questions.len()); for (index, question) in bundle.questions.iter().enumerate() { - let tex_bytes = fetch_object_bytes(pool, &question.metadata.tex_object_id).await?; + let tex_bytes = object_store + .fetch_object_bytes(&question.metadata.tex_object_id) + .await?; let source_tex = String::from_utf8(tex_bytes).with_context(|| { format!( "question tex object is not valid UTF-8: {}", @@ -265,7 +267,9 @@ async fn build_render_paper_input( original_path: asset.path.clone(), object_id: asset.object_id.clone(), mime_type: asset.mime_type.clone(), - bytes: fetch_object_bytes(pool, &asset.object_id).await?, + bytes: object_store + .fetch_object_bytes(&asset.object_id) + .await?, }); } diff --git a/src/api/papers/handlers.rs b/src/api/papers/handlers.rs index 4c358d3..f06f494 100644 --- a/src/api/papers/handlers.rs +++ b/src/api/papers/handlers.rs @@ -133,7 +133,7 @@ pub(crate) async fn create_paper( Ok(Json( import_paper_zip( - &state.pool, + &state.object_store, file_name.as_deref(), &request, bytes, @@ -151,7 +151,7 @@ pub(crate) async fn download_papers_bundle( let paper_ids = request .normalize() .map_err(|err| ApiError::bad_request(err.to_string()))?; - build_paper_bundle_response(&state.pool, &paper_ids) + build_paper_bundle_response(&state.object_store, &paper_ids) .await .map_err(ApiError::from) } @@ -169,7 +169,7 @@ pub(crate) async fn replace_paper_file( validate_upload_size(&bytes, MAX_UPLOAD_BYTES)?; Ok(Json( - replace_paper_zip(&state.pool, &paper_id, file_name.as_deref(), bytes) + replace_paper_zip(&state.object_store, &paper_id, file_name.as_deref(), bytes) .await .map_err(ApiError::from)?, )) diff --git a/src/api/papers/imports.rs b/src/api/papers/imports.rs index 9c8b0bc..68f529b 100644 --- a/src/api/papers/imports.rs +++ b/src/api/papers/imports.rs @@ -1,20 +1,20 @@ use std::io::Cursor; use anyhow::{bail, Context, Result}; -use sqlx::{query, PgPool, Row}; +use sqlx::{query, Row}; use uuid::Uuid; use zip::ZipArchive; use super::models::{NormalizedCreatePaperRequest, PaperFileReplaceResponse, PaperImportResponse}; use crate::api::shared::{ - db::{insert_object_tx, normalize_upload_file_name}, + db::{normalize_upload_file_name, ObjectStore}, error::{NotFoundError, ValidationError}, }; pub(crate) const MAX_UPLOAD_BYTES: usize = 20 * 1024 * 1024; pub(crate) async fn import_paper_zip( - pool: &PgPool, + object_store: &ObjectStore, file_name: Option<&str>, request: &NormalizedCreatePaperRequest, zip_bytes: Vec, @@ -22,9 +22,17 @@ pub(crate) async fn import_paper_zip( ) -> Result { let paper_id = Uuid::new_v4().to_string(); let normalized_file_name = normalize_optional_paper_file_name(file_name, &zip_bytes)?; - let mut tx = pool.begin().await.context("begin paper import tx failed")?; + let mut tx = object_store + .pool() + .begin() + .await + .context("begin paper import tx failed")?; let append_object_id = if let Some(file_name) = normalized_file_name.as_deref() { - Some(insert_object_tx(&mut tx, file_name, &zip_bytes, Some("application/zip")).await?) + Some( + object_store + .insert_object_tx(&mut tx, file_name, &zip_bytes, Some("application/zip")) + .await?, + ) } else { None }; @@ -74,7 +82,7 @@ pub(crate) async fn import_paper_zip( } pub(crate) async fn replace_paper_zip( - pool: &PgPool, + object_store: &ObjectStore, paper_id: &str, file_name: Option<&str>, zip_bytes: Vec, @@ -89,28 +97,31 @@ pub(crate) async fn replace_paper_zip( validate_uploaded_zip(&zip_bytes)?; let normalized_file_name = normalize_upload_file_name(file_name, "paper.zip"); - let mut tx = pool + let mut tx = object_store + .pool() .begin() .await .context("begin paper file replace tx failed")?; - let previous_object_id = query( - "SELECT append_object_id::text AS append_object_id FROM papers WHERE paper_id = $1::uuid AND deleted_at IS NULL FOR UPDATE", + let previous_row = query( + "SELECT p.append_object_id::text AS append_object_id, o.storage_path FROM papers p LEFT JOIN objects o ON o.object_id = p.append_object_id WHERE p.paper_id = $1::uuid AND p.deleted_at IS NULL FOR UPDATE OF p", ) .bind(paper_id) .fetch_optional(&mut *tx) .await .context("load paper appendix reference failed")? - .map(|row| row.get::, _>("append_object_id")) .ok_or_else(|| NotFoundError(format!("paper not found: {paper_id}")))?; - - let append_object_id = insert_object_tx( - &mut tx, - &normalized_file_name, - &zip_bytes, - Some("application/zip"), - ) - .await?; + let previous_object_id: Option = previous_row.get("append_object_id"); + let previous_storage_path: Option = previous_row.get("storage_path"); + + let append_object_id = object_store + .insert_object_tx( + &mut tx, + &normalized_file_name, + &zip_bytes, + Some("application/zip"), + ) + .await?; query("UPDATE papers SET append_object_id = $2::uuid, updated_at = NOW() WHERE paper_id = $1::uuid") .bind(paper_id) @@ -119,9 +130,9 @@ pub(crate) async fn replace_paper_zip( .await .context("update paper appendix object failed")?; - if let Some(previous_object_id) = previous_object_id { + if let Some(previous_object_id) = &previous_object_id { query("DELETE FROM objects WHERE object_id = $1::uuid") - .bind(&previous_object_id) + .bind(previous_object_id) .execute(&mut *tx) .await .context("delete previous paper appendix object failed")?; @@ -131,6 +142,11 @@ pub(crate) async fn replace_paper_zip( .await .context("commit paper file replace failed")?; + // Clean up old file from disk after successful commit. + if let Some(path) = previous_storage_path { + object_store.delete_object_files(&[path]); + } + Ok(PaperFileReplaceResponse { paper_id: paper_id.to_string(), file_name: normalized_file_name, diff --git a/src/api/questions/API.md b/src/api/questions/API.md index 6a8b44a..a7a4f49 100644 --- a/src/api/questions/API.md +++ b/src/api/questions/API.md @@ -1,6 +1,6 @@ # Questions API -> 题目的增删改查、文件替换、审阅人管理、难度管理和批量打包接口。 +> 题目的增删改查、文件替换、审阅人管理、难度管理、对象下载和批量打包接口。 所有请求需携带 `Authorization: Bearer ` 头。普通账号使用 JWT access token;bot 使用管理员签发的长期 access token。 @@ -33,6 +33,7 @@ - 上传时,后端自动设置 difficulty 为空、status 为 `none`、author 为上传者 display_name、reviewers 为 `[]` - 后端自动维护 `created_by`、`created_at`、`updated_at` - 题目创建者(`created_by`)始终可修改自己题目的 description、category、tags 和 file,不受 status 限制 +- 题目 TeX 和资源文件以对象形式存储;`QuestionDetail.tex_object_id` 和 `QuestionDetail.assets[].object_id` 可通过 `GET /objects/:object_id` 下载 --- @@ -80,7 +81,68 @@ ### `QuestionDetail` -在 `QuestionSummary` 基础上增加 `tex_object_id`、`assets`、`papers`。 +```json +{ + "question_id": "uuid", + "tex_object_id": "uuid", + "source": { "tex": "problem.tex" }, + "category": "T", + "status": "reviewed", + "description": "热学标定 gamma", + "score": 20, + "author": "张三", + "reviewers": ["李四"], + "tags": ["optics", "thermodynamics"], + "difficulty": {}, + "created_by": "uuid or null", + "created_at": "2026-01-01T00:00:00.000Z", + "updated_at": "2026-01-01T00:00:00.000Z", + "assets": [ + { + "path": "assets/fig1.png", + "file_kind": "asset", + "object_id": "uuid", + "mime_type": "image/png" + } + ], + "papers": [ + { + "paper_id": "uuid", + "description": "综合训练试卷 A", + "title": "综合训练 2026 A 卷", + "subtitle": "校内选拔 初版", + "sort_order": 1 + } + ] +} +``` + +在 `QuestionSummary` 基础上增加以下字段: + +| 字段 | 类型 | 说明 | +|---|---|---| +| `tex_object_id` | string(UUID) | TeX 源文件对象 ID,可通过 `GET /objects/:object_id` 下载 | +| `assets` | object[] | 题目资源文件列表 | +| `papers` | object[] | 引用该题目的未软删除试卷列表 | + +`assets[]` 字段: + +| 字段 | 类型 | 说明 | +|---|---|---| +| `path` | string | 资源文件相对路径,如 `assets/fig1.png` | +| `file_kind` | string | 当前固定为 `"asset"` | +| `object_id` | string(UUID) | 对象 ID,可通过 `GET /objects/:object_id` 下载 | +| `mime_type` | string \| null | 推断出的 MIME 类型 | + +`papers[]` 字段: + +| 字段 | 类型 | 说明 | +|---|---|---| +| `paper_id` | string(UUID) | 试卷 ID | +| `description` | string | 试卷描述 | +| `title` | string | 试卷标题 | +| `subtitle` | string | 试卷副标题 | +| `sort_order` | int | 该题目在试卷中的顺序 | --- @@ -170,6 +232,32 @@ --- +### `GET /objects/:object_id` + +下载单个对象文件。该接口主要用于读取题目详情里的 `tex_object_id` 和 `assets[].object_id`。 + +- **认证**:`viewer` 及以上 +- **路径参数**:`object_id` — UUID + +**成功响应** `200`: + +- **Content-Type**:对象记录中的 `mime_type`;缺失时回退为 `application/octet-stream` +- **Header**: + - `content-disposition: inline; filename=""` + - `content-length` + - `cache-control: public, max-age=31536000, immutable` + - 若对象有内容哈希,还会返回 `etag` +- **Body**:对象原始二进制内容 + +**缓存行为**: + +- 支持 `If-None-Match` +- 当请求头中的 ETag 命中对象内容哈希时返回 `304 Not Modified` + +**错误**:`404` — 对象不存在 + +--- + ### `POST /questions` 上传新题目(zip 包)。 @@ -365,3 +453,43 @@ ### `POST /questions/bundles` 批量下载题目 zip 打包。认证:`viewer` 及以上。 + +- **Content-Type**:`application/json` + +**请求体**: + +| 字段 | 类型 | 必填 | 说明 | +|---|---|---|---| +| `question_ids` | string(UUID)[] | ✅ | 题目 ID 列表,非空、去重、每项必须为有效 UUID | + +```json +{ + "question_ids": ["uuid-1", "uuid-2"] +} +``` + +**成功响应** `200`: + +- **Content-Type**:`application/zip` +- **Header** 含 `content-disposition` 和 `content-length` + +**ZIP 结构**: + +``` +manifest.json +热学标定gamma_550e84/ + problem.tex + assets/ + fig1.png +``` + +- `manifest.json`:题目元数据和文件清单 +- 每个题目目录命名:`{description}_{uuid前6位}/` +- 目录内保留原始 TeX 路径和 `assets/` 结构 + +**错误**: + +| 状态码 | 场景 | +|---|---| +| `400` | 列表为空 / 含无效 UUID / 有重复 | +| `404` | 有题目不存在或已软删除 | diff --git a/src/api/questions/bundles.rs b/src/api/questions/bundles.rs index b2eaa8e..c7b2cc1 100644 --- a/src/api/questions/bundles.rs +++ b/src/api/questions/bundles.rs @@ -14,7 +14,7 @@ use crate::api::shared::{ finish_zip_response, temp_zip_path, timestamp_unix, write_bundle_file, write_manifest, BundleFileEntry, }, - db::fetch_object_bytes, + db::ObjectStore, details::{load_question_detail, DetailVisibility}, utils::bundle_directory_name, }; @@ -42,7 +42,7 @@ pub(crate) struct QuestionBundleData { } pub(crate) async fn build_question_bundle_response( - pool: &PgPool, + object_store: &ObjectStore, question_ids: &[String], ) -> Result { let bundle_name = format!("questions_bundle_{}.zip", timestamp_unix()); @@ -57,10 +57,10 @@ pub(crate) async fn build_question_bundle_response( let mut manifest_items = Vec::with_capacity(question_ids.len()); for question_id in question_ids { - let bundle = load_question_bundle_data(pool, question_id).await?; + let bundle = load_question_bundle_data(object_store.pool(), question_id).await?; let directory = bundle_directory_name(&bundle.metadata.description, question_id); let manifest_files = - write_question_bundle_files(pool, &mut writer, &bundle.files, &directory).await?; + write_question_bundle_files(object_store, &mut writer, &bundle.files, &directory).await?; manifest_items.push(QuestionBundleManifestItem { question_id: question_id.clone(), directory, @@ -129,7 +129,7 @@ pub(crate) fn question_detail_to_summary(detail: &QuestionDetail) -> QuestionSum } async fn write_question_bundle_files( - pool: &PgPool, + object_store: &ObjectStore, writer: &mut ZipWriter, files: &[QuestionAssetRef], directory: &str, @@ -138,7 +138,7 @@ async fn write_question_bundle_files( for file in files { let zip_path = format!("{directory}/{}", file.path); - let bytes = fetch_object_bytes(pool, &file.object_id).await?; + let bytes = object_store.fetch_object_bytes(&file.object_id).await?; write_bundle_file(writer, &zip_path, &bytes)?; manifest_entries.push(BundleFileEntry { diff --git a/src/api/questions/handlers.rs b/src/api/questions/handlers.rs index b9fceb8..a2ccc6f 100644 --- a/src/api/questions/handlers.rs +++ b/src/api/questions/handlers.rs @@ -138,7 +138,7 @@ pub(crate) async fn download_questions_bundle( let question_ids = request .normalize() .map_err(|err| ApiError::bad_request(err.to_string()))?; - build_question_bundle_response(&state.pool, &question_ids) + build_question_bundle_response(&state.object_store, &question_ids) .await .map_err(ApiError::from) } @@ -196,7 +196,7 @@ pub(crate) async fn create_question( Ok(Json( import_question_zip( - &state.pool, + &state.object_store, file_name.as_deref(), &request, bytes, @@ -227,7 +227,7 @@ pub(crate) async fn replace_question_file( Ok(Json( replace_question_zip( - &state.pool, + &state.object_store, &question_id, file_name.as_deref(), bytes, diff --git a/src/api/questions/imports.rs b/src/api/questions/imports.rs index b3181ee..4fbe3ea 100644 --- a/src/api/questions/imports.rs +++ b/src/api/questions/imports.rs @@ -9,7 +9,7 @@ use std::{ use anyhow::{bail, Context, Result}; use mime_guess::MimeGuess; use regex::Regex; -use sqlx::{query, PgPool, Postgres, QueryBuilder, Row, Transaction}; +use sqlx::{query, Postgres, QueryBuilder, Row, Transaction}; use uuid::Uuid; use zip::ZipArchive; @@ -17,7 +17,7 @@ use super::models::{ NormalizedCreateQuestionRequest, QuestionFileReplaceResponse, QuestionImportResponse, }; use crate::api::shared::{ - db::{insert_object_tx, normalize_upload_file_name}, + db::{normalize_upload_file_name, ObjectStore}, error::{NotFoundError, ValidationError}, }; @@ -38,7 +38,7 @@ struct LoadedQuestionZip { } pub(crate) async fn import_question_zip( - pool: &PgPool, + object_store: &ObjectStore, file_name: Option<&str>, request: &NormalizedCreateQuestionRequest, zip_bytes: Vec, @@ -54,7 +54,8 @@ pub(crate) async fn import_question_zip( let loaded = load_question_zip(&zip_bytes).map_err(|e| ValidationError(format!("{e:#}")))?; let question_id = Uuid::new_v4().to_string(); - let mut tx = pool + let mut tx = object_store + .pool() .begin() .await .context("begin question import tx failed")?; @@ -83,7 +84,7 @@ pub(crate) async fn import_question_zip( .await .context("insert uploaded question failed")?; - insert_loaded_question_files_tx(&mut tx, &question_id, &loaded).await?; + insert_loaded_question_files_tx(object_store, &mut tx, &question_id, &loaded).await?; insert_question_tags_tx(&mut tx, &question_id, &request.tags).await?; // No difficulty entries inserted — difficulty starts empty. @@ -98,7 +99,7 @@ pub(crate) async fn import_question_zip( } pub(crate) async fn replace_question_zip( - pool: &PgPool, + object_store: &ObjectStore, question_id: &str, file_name: Option<&str>, zip_bytes: Vec, @@ -112,7 +113,8 @@ pub(crate) async fn replace_question_zip( let loaded = load_question_zip(&zip_bytes).map_err(|e| ValidationError(format!("{e:#}")))?; let normalized_file_name = normalize_upload_file_name(file_name, "question.zip"); - let mut tx = pool + let mut tx = object_store + .pool() .begin() .await .context("begin question file replace tx failed")?; @@ -129,10 +131,10 @@ pub(crate) async fn replace_question_zip( return Err(NotFoundError(format!("question not found: {question_id}")).into()); } - replace_question_files_tx(&mut tx, question_id, &loaded).await?; + replace_question_files_tx(object_store, &mut tx, question_id, &loaded).await?; query( - "UPDATE questions SET source_tex_path = $2, score = $3, updated_at = NOW() WHERE question_id = $1::uuid", + "UPDATE questions SET source_tex_path = $2, score = $3, status = 'none', updated_at = NOW() WHERE question_id = $1::uuid", ) .bind(question_id) .bind(&loaded.tex_file.path) @@ -141,6 +143,12 @@ pub(crate) async fn replace_question_zip( .await .context("update question on file replace failed")?; + query("DELETE FROM question_difficulties WHERE question_id = $1::uuid") + .bind(question_id) + .execute(&mut *tx) + .await + .context("clear difficulty entries on file replace failed")?; + tx.commit() .await .context("commit question file replace failed")?; @@ -340,17 +348,19 @@ fn register_parent_directories(directories: &mut BTreeSet, path: &str) { } async fn insert_loaded_question_files_tx( + object_store: &ObjectStore, tx: &mut Transaction<'_, Postgres>, question_id: &str, loaded: &LoadedQuestionZip, ) -> Result<()> { - let tex_object_id = insert_object_tx( - tx, - &loaded.tex_file.path, - &loaded.tex_file.bytes, - Some("text/x-tex"), - ) - .await?; + let tex_object_id = object_store + .insert_object_tx( + tx, + &loaded.tex_file.path, + &loaded.tex_file.bytes, + Some("text/x-tex"), + ) + .await?; insert_question_file_tx( tx, question_id, @@ -365,7 +375,9 @@ async fn insert_loaded_question_files_tx( let mime = MimeGuess::from_path(&asset.path) .first_raw() .map(str::to_string); - let object_id = insert_object_tx(tx, &asset.path, &asset.bytes, mime.as_deref()).await?; + let object_id = object_store + .insert_object_tx(tx, &asset.path, &asset.bytes, mime.as_deref()) + .await?; insert_question_file_tx( tx, question_id, @@ -399,20 +411,23 @@ async fn insert_question_tags_tx( } async fn replace_question_files_tx( + object_store: &ObjectStore, tx: &mut Transaction<'_, Postgres>, question_id: &str, loaded: &LoadedQuestionZip, ) -> Result<()> { - let old_object_ids = query( - "SELECT object_id::text AS object_id FROM question_files WHERE question_id = $1::uuid", + let old_rows = query( + "SELECT qf.object_id::text AS object_id, o.storage_path FROM question_files qf JOIN objects o ON o.object_id = qf.object_id WHERE qf.question_id = $1::uuid", ) .bind(question_id) .fetch_all(&mut **tx) .await - .context("load existing question file objects failed")? - .into_iter() - .map(|row| row.get::("object_id")) - .collect::>(); + .context("load existing question file objects failed")?; + let old_object_ids: Vec = old_rows.iter().map(|r| r.get("object_id")).collect(); + let old_storage_paths: Vec = old_rows + .iter() + .filter_map(|r| r.get::, _>("storage_path")) + .collect(); query("DELETE FROM question_files WHERE question_id = $1::uuid") .bind(question_id) @@ -436,7 +451,12 @@ async fn replace_question_files_tx( .context("delete previous question file objects failed")?; } - insert_loaded_question_files_tx(tx, question_id, loaded).await + insert_loaded_question_files_tx(object_store, tx, question_id, loaded).await?; + + // Delete old files from disk after the DB transaction has removed them. + object_store.delete_object_files(&old_storage_paths); + + Ok(()) } async fn insert_question_file_tx( diff --git a/src/api/shared/db.rs b/src/api/shared/db.rs index 07b16f5..749b57a 100644 --- a/src/api/shared/db.rs +++ b/src/api/shared/db.rs @@ -1,59 +1,285 @@ -//! Shared database helpers used across question and paper modules. +//! Shared database helpers and filesystem-backed object storage. +//! +//! The [`ObjectStore`] struct encapsulates both the PostgreSQL pool and the +//! on-disk object directory. New objects are written to disk and only metadata +//! is persisted in the database. Legacy rows that still carry a BYTEA +//! `content` column are transparently served and can be migrated to the +//! filesystem with [`ObjectStore::migrate_legacy_objects`]. -use std::path::Path; +use std::{ + fs, + path::{Path, PathBuf}, +}; use anyhow::{Context, Result}; +use sha2::{Digest, Sha256}; use sqlx::{query, PgPool, Postgres, Row, Transaction}; use uuid::Uuid; -/// Insert a binary object into the `objects` table and return the new object ID. -pub(crate) async fn insert_object_tx( - tx: &mut Transaction<'_, Postgres>, - file_name: &str, - bytes: &[u8], - mime_type: Option<&str>, -) -> Result { - let object_id = Uuid::new_v4().to_string(); - let normalized_file_name = Path::new(file_name) - .file_name() - .map(|name| name.to_string_lossy().to_string()) - .unwrap_or_else(|| "blob.bin".to_string()); - - query( - r#" - INSERT INTO objects (object_id, file_name, mime_type, size_bytes, content, created_at) - VALUES ($1::uuid, $2, $3, $4, $5, NOW()) - "#, - ) - .bind(&object_id) - .bind(&normalized_file_name) - .bind(mime_type) - .bind(i64::try_from(bytes.len()).context("object bytes exceed i64 range")?) - .bind(bytes) - .execute(&mut **tx) - .await - .context("insert object failed")?; - - Ok(object_id) +// --------------------------------------------------------------------------- +// ObjectStore +// --------------------------------------------------------------------------- + +/// Filesystem-backed object store with PostgreSQL metadata. +#[derive(Clone)] +pub struct ObjectStore { + pool: PgPool, + store_dir: PathBuf, } -/// Fetch the raw binary content of an object by ID. -pub(crate) async fn fetch_object_bytes(pool: &PgPool, object_id: &str) -> Result> { - let row = query("SELECT content FROM objects WHERE object_id = $1::uuid") +impl ObjectStore { + /// Create a new object store, ensuring the base directory exists. + pub fn new(pool: PgPool, store_dir: PathBuf) -> Result { + fs::create_dir_all(&store_dir).with_context(|| { + format!( + "create object store directory failed: {}", + store_dir.to_string_lossy() + ) + })?; + Ok(Self { pool, store_dir }) + } + + /// Return the inner pool reference (for callers that only need SQL access). + pub(crate) fn pool(&self) -> &PgPool { + &self.pool + } + + /// Return the base directory of the object store. + pub fn store_dir(&self) -> &Path { + &self.store_dir + } + + // ----------------------------------------------------------------------- + // Write + // ----------------------------------------------------------------------- + + /// Insert a binary object: write bytes to the filesystem and persist + /// metadata in the `objects` table. Returns the new `object_id`. + pub(crate) async fn insert_object_tx( + &self, + tx: &mut Transaction<'_, Postgres>, + file_name: &str, + bytes: &[u8], + mime_type: Option<&str>, + ) -> Result { + let object_id = Uuid::new_v4().to_string(); + let normalized_file_name = Path::new(file_name) + .file_name() + .map(|name| name.to_string_lossy().to_string()) + .unwrap_or_else(|| "blob.bin".to_string()); + + // Compute SHA-256 content hash. + let content_hash = hex_sha256(bytes); + + // Write to filesystem *before* the DB insert so that a crash between + // the two leaves an orphan file (harmless) rather than a DB row + // pointing at nothing. + let storage_path = object_storage_path(&object_id); + let full_path = self.store_dir.join(&storage_path); + write_object_file(&full_path, bytes)?; + + query( + r#" + INSERT INTO objects (object_id, file_name, mime_type, size_bytes, content, content_hash, storage_path, created_at) + VALUES ($1::uuid, $2, $3, $4, NULL, $5, $6, NOW()) + "#, + ) + .bind(&object_id) + .bind(&normalized_file_name) + .bind(mime_type) + .bind(i64::try_from(bytes.len()).context("object bytes exceed i64 range")?) + .bind(&content_hash) + .bind(&storage_path) + .execute(&mut **tx) + .await + .context("insert object failed")?; + + Ok(object_id) + } + + // ----------------------------------------------------------------------- + // Read + // ----------------------------------------------------------------------- + + /// Fetch the raw binary content of an object. + /// + /// Reads from the filesystem if `storage_path` is set, otherwise falls + /// back to the legacy `content` BYTEA column. + pub(crate) async fn fetch_object_bytes(&self, object_id: &str) -> Result> { + let row = query( + "SELECT content, storage_path FROM objects WHERE object_id = $1::uuid", + ) .bind(object_id) - .fetch_one(pool) + .fetch_one(&self.pool) .await .with_context(|| format!("fetch object failed: {object_id}"))?; - Ok(row.get("content")) + let storage_path: Option = row.get("storage_path"); + if let Some(rel_path) = storage_path { + let full_path = self.store_dir.join(&rel_path); + tokio::fs::read(&full_path) + .await + .with_context(|| { + format!( + "read object file failed: {} (object_id={object_id})", + full_path.to_string_lossy() + ) + }) + } else { + // Legacy fallback: read from BYTEA column. + let content: Option> = row.get("content"); + content.ok_or_else(|| { + anyhow::anyhow!( + "object has neither storage_path nor content: {object_id}" + ) + }) + } + } + + /// Fetch the content of a text object (UTF-8 with lossy fallback). + pub(crate) async fn fetch_text_object(&self, object_id: &str) -> Result { + let bytes = self.fetch_object_bytes(object_id).await?; + Ok(String::from_utf8_lossy(&bytes).to_string()) + } + + /// Fetch object metadata needed for serving a single file. + pub(crate) async fn fetch_object_meta( + &self, + object_id: &str, + ) -> Result> { + let row = query( + r#" + SELECT file_name, mime_type, size_bytes, content_hash, storage_path + FROM objects + WHERE object_id = $1::uuid + "#, + ) + .bind(object_id) + .fetch_optional(&self.pool) + .await + .with_context(|| format!("fetch object meta failed: {object_id}"))?; + + Ok(row.map(|r| ObjectMeta { + file_name: r.get("file_name"), + mime_type: r.get("mime_type"), + size_bytes: r.get("size_bytes"), + content_hash: r.get("content_hash"), + storage_path: r.get("storage_path"), + })) + } + + // ----------------------------------------------------------------------- + // Delete + // ----------------------------------------------------------------------- + + /// Best-effort delete of object files from the filesystem. + /// + /// This should be called *after* the corresponding `DELETE FROM objects` + /// query has committed, so that a crash between the two leaves orphan + /// files rather than dangling DB rows. + pub(crate) fn delete_object_files(&self, storage_paths: &[String]) { + for rel_path in storage_paths { + let full_path = self.store_dir.join(rel_path); + if let Err(err) = fs::remove_file(&full_path) { + if err.kind() != std::io::ErrorKind::NotFound { + tracing::warn!( + path = %full_path.to_string_lossy(), + "delete object file failed: {err}" + ); + } + } + } + } + + // ----------------------------------------------------------------------- + // Legacy migration + // ----------------------------------------------------------------------- + + /// Migrate objects that still have BYTEA content to the filesystem. + /// + /// This is safe to call on every startup — it is a no-op once all objects + /// have been migrated. Objects are processed in batches to limit memory. + pub async fn migrate_legacy_objects(&self) -> Result { + const BATCH_SIZE: i64 = 50; + let mut total_migrated: usize = 0; + + loop { + let rows = query( + r#" + SELECT object_id::text AS object_id, content + FROM objects + WHERE content IS NOT NULL AND storage_path IS NULL + ORDER BY created_at + LIMIT $1 + "#, + ) + .bind(BATCH_SIZE) + .fetch_all(&self.pool) + .await + .context("query legacy objects for migration failed")?; + + if rows.is_empty() { + break; + } + + for row in &rows { + let object_id: String = row.get("object_id"); + let content: Vec = row.get("content"); + let content_hash = hex_sha256(&content); + let storage_path = object_storage_path(&object_id); + let full_path = self.store_dir.join(&storage_path); + + write_object_file(&full_path, &content)?; + + query( + r#" + UPDATE objects + SET storage_path = $2, content_hash = $3, content = NULL + WHERE object_id = $1::uuid + "#, + ) + .bind(&object_id) + .bind(&storage_path) + .bind(&content_hash) + .execute(&self.pool) + .await + .with_context(|| { + format!("update migrated object failed: {object_id}") + })?; + } + + total_migrated += rows.len(); + } + + if total_migrated > 0 { + tracing::info!( + count = total_migrated, + "migrated legacy BYTEA objects to filesystem" + ); + } + + Ok(total_migrated) + } } -/// Fetch the content of a text object (UTF-8 with lossy fallback). -pub(crate) async fn fetch_text_object(pool: &PgPool, object_id: &str) -> Result { - let bytes = fetch_object_bytes(pool, object_id).await?; - Ok(String::from_utf8_lossy(&bytes).to_string()) +// --------------------------------------------------------------------------- +// ObjectMeta (for the file serving endpoint) +// --------------------------------------------------------------------------- + +#[derive(Debug)] +#[allow(dead_code)] +pub(crate) struct ObjectMeta { + pub(crate) file_name: String, + pub(crate) mime_type: Option, + pub(crate) size_bytes: i64, + pub(crate) content_hash: Option, + pub(crate) storage_path: Option, } +// --------------------------------------------------------------------------- +// Free helpers (kept public for callers that don't need the full ObjectStore) +// --------------------------------------------------------------------------- + /// Normalize an upload file name, using the given default when the name is /// missing or blank. pub(crate) fn normalize_upload_file_name(file_name: Option<&str>, default: &str) -> String { @@ -63,3 +289,45 @@ pub(crate) fn normalize_upload_file_name(file_name: Option<&str>, default: &str) .filter(|value| !value.trim().is_empty()) .unwrap_or_else(|| default.to_string()) } + +// --------------------------------------------------------------------------- +// Internal helpers +// --------------------------------------------------------------------------- + +/// Compute the relative storage path for an object: `/`. +fn object_storage_path(object_id: &str) -> String { + let prefix = &object_id[..2.min(object_id.len())]; + format!("{prefix}/{object_id}") +} + +/// Compute hex-encoded SHA-256 of the given bytes. +fn hex_sha256(bytes: &[u8]) -> String { + let digest = Sha256::digest(bytes); + // Format as lowercase hex without pulling in another crate. + digest + .iter() + .fold(String::with_capacity(64), |mut acc, byte| { + use std::fmt::Write; + let _ = write!(acc, "{byte:02x}"); + acc + }) +} + +/// Write bytes to a file, creating parent directories as needed. +fn write_object_file(full_path: &Path, bytes: &[u8]) -> Result<()> { + if let Some(parent) = full_path.parent() { + fs::create_dir_all(parent).with_context(|| { + format!( + "create object directory failed: {}", + parent.to_string_lossy() + ) + })?; + } + fs::write(full_path, bytes).with_context(|| { + format!( + "write object file failed: {}", + full_path.to_string_lossy() + ) + })?; + Ok(()) +} diff --git a/src/api/shared/mod.rs b/src/api/shared/mod.rs index 00f329a..bb9a2a5 100644 --- a/src/api/shared/mod.rs +++ b/src/api/shared/mod.rs @@ -4,4 +4,5 @@ pub(crate) mod details; pub(crate) mod error; pub(crate) mod multipart; pub(crate) mod pagination; +pub(crate) mod serve; pub(crate) mod utils; diff --git a/src/api/shared/serve.rs b/src/api/shared/serve.rs new file mode 100644 index 0000000..e6a2048 --- /dev/null +++ b/src/api/shared/serve.rs @@ -0,0 +1,100 @@ +//! Individual object file serving endpoint. + +use axum::{ + body::Body, + extract::{Path as AxumPath, State}, + http::{ + header::{self, HeaderMap}, + HeaderValue, StatusCode, + }, + response::Response, +}; + +use super::{ + error::ApiError, + multipart::parse_uuid_param, +}; +use crate::api::AppState; + +/// `GET /objects/:object_id` — serve a single stored object with HTTP caching. +pub(crate) async fn get_object( + AxumPath(object_id): AxumPath, + State(state): State, + headers: HeaderMap, +) -> Result { + parse_uuid_param(&object_id, "object_id")?; + + let meta = state + .object_store + .fetch_object_meta(&object_id) + .await + .map_err(|e| { + tracing::error!("fetch object meta failed: {e:#}"); + ApiError::internal("internal server error") + })? + .ok_or_else(|| ApiError::not_found(format!("object not found: {object_id}")))?; + + // ETag-based conditional request support. + if let Some(hash) = &meta.content_hash { + let etag = format!("\"{hash}\""); + if let Some(if_none_match) = headers.get(header::IF_NONE_MATCH) { + if let Ok(value) = if_none_match.to_str() { + if value == etag || value == "*" { + return Response::builder() + .status(StatusCode::NOT_MODIFIED) + .body(Body::empty()) + .map_err(|e| ApiError::internal(e.to_string())); + } + } + } + } + + // Read the file content. + let bytes = state + .object_store + .fetch_object_bytes(&object_id) + .await + .map_err(|e| { + tracing::error!("fetch object bytes failed: {e:#}"); + ApiError::internal("internal server error") + })?; + + let content_type = meta + .mime_type + .as_deref() + .unwrap_or("application/octet-stream"); + + let mut builder = Response::builder() + .status(StatusCode::OK) + .header( + header::CONTENT_TYPE, + HeaderValue::from_str(content_type) + .unwrap_or_else(|_| HeaderValue::from_static("application/octet-stream")), + ) + .header( + header::CONTENT_LENGTH, + HeaderValue::from_str(&bytes.len().to_string()) + .unwrap_or_else(|_| HeaderValue::from_static("0")), + ) + .header( + header::CONTENT_DISPOSITION, + HeaderValue::from_str(&format!("inline; filename=\"{}\"", meta.file_name)) + .unwrap_or_else(|_| HeaderValue::from_static("inline")), + ); + + // Objects are immutable (UUID-addressed, write-once) — cache aggressively. + builder = builder.header( + header::CACHE_CONTROL, + HeaderValue::from_static("public, max-age=31536000, immutable"), + ); + + if let Some(hash) = &meta.content_hash { + if let Ok(val) = HeaderValue::from_str(&format!("\"{hash}\"")) { + builder = builder.header(header::ETAG, val); + } + } + + builder + .body(Body::from(bytes)) + .map_err(|e| ApiError::internal(e.to_string())) +} diff --git a/src/config.rs b/src/config.rs index 9f17003..1c58cec 100644 --- a/src/config.rs +++ b/src/config.rs @@ -10,6 +10,7 @@ pub struct AppConfig { pub bind_addr: SocketAddr, pub max_db_connections: u32, pub export_dir: PathBuf, + pub object_store_dir: PathBuf, pub cors_origins: Vec, pub jwt_secret: String, } @@ -33,6 +34,10 @@ impl AppConfig { .map(PathBuf::from) .unwrap_or_else(|_| PathBuf::from("exports")); + let object_store_dir = env::var("QB_OBJECT_STORE_DIR") + .map(PathBuf::from) + .unwrap_or_else(|_| PathBuf::from("/var/lib/qb/objects")); + let cors_origins = env::var("QB_CORS_ORIGINS") .unwrap_or_default() .split(',') @@ -48,6 +53,7 @@ impl AppConfig { bind_addr, max_db_connections, export_dir, + object_store_dir, cors_origins, jwt_secret, }) @@ -67,6 +73,7 @@ mod tests { let prev_bind = env::var("QB_BIND_ADDR").ok(); let prev_conn = env::var("QB_MAX_DB_CONNECTIONS").ok(); let prev_export = env::var("QB_EXPORT_DIR").ok(); + let prev_object_store = env::var("QB_OBJECT_STORE_DIR").ok(); let prev_cors = env::var("QB_CORS_ORIGINS").ok(); env::set_var( @@ -76,6 +83,7 @@ mod tests { env::remove_var("QB_BIND_ADDR"); env::remove_var("QB_MAX_DB_CONNECTIONS"); env::remove_var("QB_EXPORT_DIR"); + env::remove_var("QB_OBJECT_STORE_DIR"); env::remove_var("QB_CORS_ORIGINS"); let cfg = AppConfig::from_env().expect("config should load"); @@ -86,6 +94,10 @@ mod tests { ); assert_eq!(cfg.max_db_connections, 10); assert_eq!(cfg.export_dir.to_str().unwrap(), "exports"); + assert_eq!( + cfg.object_store_dir.to_str().unwrap(), + "/var/lib/qb/objects" + ); assert!(cfg.cors_origins.is_empty()); // Restore @@ -105,6 +117,10 @@ mod tests { Some(v) => env::set_var("QB_EXPORT_DIR", v), None => {} } + match prev_object_store { + Some(v) => env::set_var("QB_OBJECT_STORE_DIR", v), + None => {} + } match prev_cors { Some(v) => env::set_var("QB_CORS_ORIGINS", v), None => {} diff --git a/src/main.rs b/src/main.rs index b8d6042..fd6c850 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,6 +1,6 @@ use anyhow::Result; use qb_api::{ - api::{hash_password, router, seed_admin_if_empty, AppState}, + api::{hash_password, router, seed_admin_if_empty, AppState, ObjectStore}, config::AppConfig, db::create_pool, }; @@ -30,8 +30,18 @@ async fn main() -> Result<()> { Err(e) => tracing::warn!("could not hash default password: {e}"), } + // Initialise filesystem-backed object store and migrate any legacy BYTEA + // objects to disk. This is idempotent and fast when nothing needs migrating. + let object_store = ObjectStore::new(pool.clone(), cfg.object_store_dir.clone())?; + object_store + .migrate_legacy_objects() + .await + .inspect_err(|e| tracing::warn!("legacy object migration skipped: {e}")) + .ok(); + let state = AppState { pool, + object_store, database_url: cfg.database_url.clone(), export_dir: cfg.export_dir.clone(), jwt_secret: cfg.jwt_secret.clone(), diff --git a/tests/health_route.rs b/tests/health_route.rs index 71ac127..c61d70b 100644 --- a/tests/health_route.rs +++ b/tests/health_route.rs @@ -3,7 +3,7 @@ use axum::{ http::{Request, StatusCode}, }; use http_body_util::BodyExt; -use qb_api::api::{router, AppState}; +use qb_api::api::{router, AppState, ObjectStore}; use sqlx::postgres::PgPoolOptions; use std::path::PathBuf; use tower::ServiceExt; @@ -15,9 +15,12 @@ async fn health_route_returns_service_unavailable_when_db_is_unreachable() { .max_connections(1) .connect_lazy("postgres://postgres:postgres@127.0.0.1:1/qb") .unwrap(); + let temp_dir = std::env::temp_dir().join("qb_test_health_objects"); + let object_store = ObjectStore::new(pool.clone(), temp_dir).expect("create test object store"); let app = router( AppState { pool, + object_store, database_url: "postgres://postgres:postgres@127.0.0.1:1/qb".to_string(), export_dir: PathBuf::from("exports"), jwt_secret: "test-secret".to_string(),