Skip to content

Transforms complex documents like PDFs and Office docs into LLM-ready markdown/JSON for your Agentic workflows.

feat(api): unify task uploads and result download links

myhlolic666e08dc7f4
diff --git a/docs/en/reference/migration_4.md b/docs/en/reference/migration_4.md
index 445c0d77..b5878b6b 100644
--- a/docs/en/reference/migration_4.md
+++ b/docs/en/reference/migration_4.md
@@ -60,7 +60,7 @@ Restart relevant services after configuration changes, and download and verify m
## API and WebUI
-V1 uses `/v1/health`, `/v1/tiers`, `/v1/uploads`, `/v1/parse/jobs`, and `/v1/files`. Legacy `/file_parse` and `/tasks` are not provided. SDK clients and the WebUI must connect to a V1 service. The parsing API and OpenAI-compatible VLM server are different interfaces; their addresses are not interchangeable. Self-hosted API servers and Routers now provide `/v1/file_parse` synchronous wrapping and `/v1/tasks` convenience submission, using current tier, ocr_mode and output contracts. Legacy parameters are not restored; see [HTTP API](../usage/http_api.md).
+V1 uses `/v1/health`, `/v1/tiers`, `/v1/uploads`, `/v1/parse/jobs`, and `/v1/files`. Legacy `/file_parse` and `/tasks` are not provided. SDK clients and the WebUI must connect to a V1 service. The parsing API and OpenAI-compatible VLM server are different interfaces; their addresses are not interchangeable. API servers and Routers provide `/v1/tasks` form manifests, per-file uploads, and ZIP download links. Local services also accept single-file multipart. Clients poll tasks and use returned URLs; synchronous wrapping and inline-result convenience routes are no longer provided; see [HTTP API](../usage/http_api.md).
Existing Gradio clients also need to follow the new event interface; renaming the command alone is insufficient. Retained third-party integration guides describe their original adaptations and do not imply V1 compatibility.
diff --git a/docs/en/usage/http_api.md b/docs/en/usage/http_api.md
index c7701ddd..543cecc7 100644
--- a/docs/en/usage/http_api.md
+++ b/docs/en/usage/http_api.md
@@ -1,50 +1,62 @@
# V1 HTTP API
-The self-hosted V1 API is the same interface the Python SDK and WebUI use. This page explains the request cycle — create an upload, upload the bytes, submit a parse job, poll to a terminal state, download the outputs — and points to a tested example script. For the Python client, see [Python SDK](sdk_api.md).
+HTTP clients can use the tasks form-manifest and download-link protocol. This page first covers that workflow, then the existing Uploads/Jobs resource workflow used by the Python SDK and WebUI. For the Python client, see [Python SDK](sdk_api.md).
-Start a local service, or point the examples at any V1 deployment including the official cloud service:
+Start a local service; for SaaS, use a deployment implementing the same tasks contract:
```bash
mineru-kit api-server --host 127.0.0.1 --port 8000 --tier standard
```
-## One-request parsing and asynchronous tasks
+## Tasks: manifests, per-file uploads, and ZIP links
-API servers and Routers expose `/v1/tasks` and `/v1/file_parse`, sharing the existing Job lifecycle and IDs:
+API servers, Routers, and SaaS deployments implementing this contract use the same client workflow: submit a manifest, upload missing files, poll status, and download the returned `result_url`.
+SaaS can return an OSS URL; a local service returns its Files URL. Clients use the returned links and do not require SaaS to implement the local Files API.
+See the [complete tasks contract](../../next/api/tasks.md).
```bash
-curl -sS 'http://127.0.0.1:8000/v1/file_parse?tier=flash&ocr_mode=txt' \
- -F '[email protected]' -o result.json
+# One or more files: preflight first and upload only cache misses.
+MINERU_API_URL=http://127.0.0.1:8000 \
+ bash scripts/http_task_example.sh a.pdf b.pdf
-curl -sS 'http://127.0.0.1:8000/v1/file_parse?tier=flash&response_format=zip' \
- -F '[email protected]' -o result.zip
+# Hashes are optional.
+SEND_HASH=0 MINERU_API_URL=http://127.0.0.1:8000 \
+ bash scripts/http_task_example.sh a.pdf b.pdf
-MINERU_API_URL=http://127.0.0.1:8002 MODE=async RESPONSE_FORMAT=zip \
- bash scripts/http_task_example.sh document.pdf
+# Continue the existing task using the original file list and order.
+TASK_ID=job_... MINERU_API_URL=http://127.0.0.1:8000 \
+ bash scripts/http_task_example.sh a.pdf b.pdf
+
+# Local multipart accepts one file and still returns an asynchronous task.
+curl --fail-with-body 'http://127.0.0.1:8000/v1/tasks' \
+ -F 'tier=flash' -F 'ocr_mode=txt' -F '[email protected]'
```
-Synchronous requests wait 300 seconds by default; `wait_timeout` accepts 1–3600 seconds including queue time.
-Timeout returns `202` with `task_id/status_url/result_url`; the task continues after timeout or HTTP disconnection.
-Use `POST /v1/tasks` for asynchronous submission and the returned V1 URLs for status and results.
-JSON results inline requested text/JSON artifacts in `files[].content`, retaining individual statuses, errors and output references.
-Asynchronous ZIP results require `output_formats=zip` at submission; synchronous ZIP requests add it automatically.
-Partial success returns `200` with `partial`; batch ZIPs contain numbered directories and a status manifest.
+All `POST /v1/tasks` parameters belong in the form body. `manifest` is a text field containing a JSON array: each item has a unique `client_file_id`, `filename`, actual `bytes`, and optional `sha256sum` and per-file `page_range`.
+Multi-file requests submit metadata only. Single-file direct uploads may include a one-item manifest to declare a hash.
+Parsing options remain `tier`, `ocr_mode`, `page_range`, and repeated `output_formats`; a final ZIP is always generated.
+POST query parameters return `400`; JSON and raw-byte task creation return `415`. Existing Uploads/Jobs JSON requests remain unchanged.
+
+Creation immediately returns a stable `task_id` and `status_url`. `uploads` contains only missing files, with their upload method, URL, headers, and expiration.
+Parsing starts automatically after every file passes validation; no client completion request is needed. Without a supplied hash, the service receives the file and still computes a hash for storage deduplication.
+Each fully uploaded file becomes `ready` independently. If another upload is interrupted, retry only that file on the same task. This is file-level retry, not resumable chunk upload within one file.
+
+Poll only `status_url`. States are `waiting_upload/queued/running/completed/partial/failed/canceled`.
+`completed/partial` and `result_url` are published only after the ZIP is saved. Status never includes inline document contents; SaaS clients download directly from object storage.
+Batch ZIPs contain numbered directories and a per-file manifest. Packaging failures produce a failed task, not an unusable download link.
-Use multipart files, raw bytes, or the existing Job JSON source structure. Upload parse options belong in query parameters; JSON options belong in the body.
-The limits are 200 MiB per file and 100 files per task. Batch uploads share a page range; use JSON for per-file options.
-Raw uploads require `filename` and `Content-Length`.
-The example script computes SHA-256 and uses `Expect: 100-continue`; a timely cache-hit response can avoid sending the body.
-Proxy buffering and client wait budgets affect this optimization. Reusing `file_id` or the existing uploads hash preflight reliably avoids repeated client uploads.
+The complete client is [`scripts/http_task_example.sh`](https://github.com/opendatalab/MinerU/blob/master/scripts/http_task_example.sh) and its adjacent Python file, requiring only Python 3.10+ standard library.
+`UPLOAD_MODE=direct` accepts one file. `RESULT_FILE` defaults to `result.zip`; `MAX_POLLS/POLL_INTERVAL` control polling, and `CONNECT_TIMEOUT/REQUEST_TIMEOUT` control transfer budgets.
+Each file gets at most three upload attempts. Creation is never automatically retried. After an uncertain upload response, query status before retransmitting; refresh expired links by querying the original task.
+The API Key is attached only to same-origin requests, never to OSS, external downloads, or cross-origin redirects.
+Exit codes are `0` for success, `2` for partial success with a saved ZIP, `1` for failure or cancellation, and `124` when the polling budget is exhausted without canceling the task.
-Router V1 uploads and convenience uploads share caller-scoped source bytes. Uploads select the lowest load and rotate on ties.
-Jobs reserve their selected worker before upstream network waits; file ownership takes priority only among the lowest-load candidates.
-A hash hit cannot pin a job to a busy worker. One batch stays on one worker; submit separate jobs for parallel work across workers.
-Remote workers currently have capacity weight 1; managed workers use `--worker-concurrency`.
-These convenience routes belong to the self-hosted services; verify cloud support against that deployment's documentation.
+Local services impose no fixed uploaded-file size or PDF page-count limit; the limit remains 100 files per task. Waiting uploads consume no parsing slot or Router worker reservation.
+Router selects by load and reserves before upstream submission; a cache hit cannot pin work to a busy worker. One batch stays on one worker, which produces the ZIP; Router maps resources and streams downloads.
-## Tested example script
+## Existing Uploads / Jobs resource example
-The complete cycle — including timeouts, response validation, bounded polling, exit codes, and credential isolation — is maintained as a single tested script in the repository:
+For independent Upload, File, and Job resources, continue using the following script. Its protocol and exit codes remain unchanged and are maintained separately from the tasks client above:
> [`scripts/http_api_example.sh`](https://github.com/opendatalab/MinerU/blob/master/scripts/http_api_example.sh)
@@ -65,7 +77,7 @@ The script's behavior is verified by `tests/unittest/test_http_api_example_scrip
| `4` | Job canceled |
| `124` | Polling budget exhausted; `job_id` printed so polling can resume |
-## Authentication and the byte upload
+## Resource API authentication and byte uploads
Requests to `/v1/*` carry `Authorization: Bearer $MINERU_API_KEY` when the service is started with `--api-key`; omit the header for anonymous local access.
@@ -78,7 +90,7 @@ The example script implements the same rule as the Python SDK (`api_client._same
Downloads go through `GET /v1/files/{file_id}/content`, which may answer with a `302` redirect. The example follows redirects without `--location-trusted`, so credentials are never re-sent to a different origin (including the same host on a different port; requires curl >= 7.83.0).
-## Request-cycle details the script deliberately covers
+## Resource-script request-cycle details
- **Upload lifecycle.** Pass `sha256sum` when creating the upload for integrity checking and instant reuse of an already-known file; in that case the response is `completed` and embeds the `file` object directly, so byte upload and completion are skipped.
- **A 200 response is not automatically valid.** The script validates JSON structure at every step: IDs must be non-empty strings and statuses must belong to the supported sets; anything else fails immediately instead of entering the polling loop with a `null` ID.
@@ -94,4 +106,4 @@ Downloads go through `GET /v1/files/{file_id}/content`, which may answer with a
- `--concurrency` caps concurrent parse jobs; queue growth beyond it shows up as longer `queued` times, not failures.
- `GET /v1/usage` reports consumption. Use `/v1/health` and the OpenAPI docs at `/docs` (when enabled) to separate service-side failures from client errors; check server logs before retrying a `failed` job.
-Convenience parsing uses `/v1/file_parse` and `/v1/tasks`; legacy root routes remain unavailable; see [migration](../reference/migration_4.md) for older clients.
+The convenience workflow uses `/v1/tasks` and its returned links, with no synchronous-wait or inline-result route. Legacy root routes remain unavailable; see [migration](../reference/migration_4.md) for older clients.
diff --git a/docs/next/api.md b/docs/next/api.md
index 00186230..5935d1f5 100644
--- a/docs/next/api.md
+++ b/docs/next/api.md
@@ -22,7 +22,7 @@ Unified API 文档描述两类部署形态下的同一套 API:
3. [Health、Models 与 Tiers](api/health-models.md): 服务能力、模型列表、解析档位。
4. [Uploads 与 Files](api/uploads-files.md): 上传生命周期、文件对象、产物下载。
5. [Parse Jobs](api/parse-jobs.md): 解析任务、轮询。
- [V1 便捷解析](api/tasks.md): 一次提交、内联结果、同步包装和 Router 调度。
+ [V1 tasks](api/tasks.md): 表单清单、逐文件上传、结果 ZIP 下载链接和 Router 调度。
6. [Chat 与 Responses](api/chat.md): OpenAI-compatible 文档对话接口。
7. [Webhooks](api/webhooks.md): 异步回调协议。
8. [Usage 与 Limits](api/usage-limits.md): access level、限流、用量查询。
diff --git a/docs/next/api/README.md b/docs/next/api/README.md
index af4b509a..12366ab5 100644
--- a/docs/next/api/README.md
+++ b/docs/next/api/README.md
@@ -54,11 +54,10 @@ ID 使用 OpenAI 风格的前缀加随机串。官方 API 使用 24 字符 base6
| `GET` | `/v1/files/{file_id}` | 查询文件元信息 |
| `GET` | `/v1/files/{file_id}/content` | 下载解析产物 |
| `DELETE` | `/v1/files/{file_id}` | 删除文件 |
-| `POST` | `/v1/tasks` | 自部署服务与 Router 的便捷异步提交 |
-| `GET` | `/v1/tasks/{task_id}` | 查询相同后台任务 |
-| `GET` | `/v1/tasks/{task_id}/result` | 获取内联 JSON 或 ZIP |
+| `POST` | `/v1/tasks` | 表单清单或本地单文件直传,返回异步任务 |
+| `GET` | `/v1/tasks/{task_id}` | 查询上传与解析状态,取得 ZIP 下载链接 |
+| `PUT` | 返回的上传链接 | 每个链接上传一个文件 |
| `DELETE` | `/v1/tasks/{task_id}` | 取消任务 |
-| `POST` | `/v1/file_parse` | 自部署同步包装,超时返回可查询任务 |
| `POST` | `/v1/parse/jobs` | 创建解析任务 |
| `GET` | `/v1/parse/jobs/{job_id}` | 查询任务 |
| `GET` | `/v1/parse/jobs` | 列出任务 |
@@ -67,7 +66,7 @@ ID 使用 OpenAI 风格的前缀加随机串。官方 API 使用 24 字符 base6
| `POST` | `/v1/responses` | Responses 文档对话 |
| `GET` | `/v1/usage` | 查询用量 |
-便捷路由的输入、结果与 Router 负载规则见 [V1 便捷解析](tasks.md)。这些路由是当前自部署接口,云端支持情况以具体部署为准。
+表单、逐文件上传、结果链接与 Router 负载规则见 [V1 tasks](tasks.md)。SaaS 可以独立实现同一契约,并返回 OSS 直链;客户端不要求其实现本地 Files 下载路由。
## 认证
@@ -85,10 +84,10 @@ Local Parse Server 默认监听 loopback 且不启用鉴权。启用 `--api-key`
- 成功响应直接返回资源对象,没有外层 envelope。
- 错误响应使用 OpenAI-compatible envelope,详见 [响应与错误](responses.md)。
-- `Content-Type` 默认为 `application/json; charset=utf-8`,上传字节流除外。
+- 资源级接口使用 JSON;`POST /v1/tasks` 使用表单,上传字节使用返回链接要求的内容类型。
- 时间字段按 endpoint 语义选择 ISO-8601 UTC 字符串或 Unix 秒级时间戳。
- 成功和失败响应都应携带 `X-Request-Id`。
-- `POST` endpoint 支持 `Idempotency-Key`,相同 key 在有效期内返回首次请求结果。
+- `Idempotency-Key` 支持属于部署能力;当前自部署 tasks 不提供创建请求幂等重试保证,恢复操作应使用原 `task_id`。
- 未知响应字段必须被客户端忽略,以支持服务端向后兼容扩展。
- 请求中的可选字段可以省略;省略时按该字段默认值处理。
- 请求中的未知字段由各 endpoint 决定是忽略还是返回 `400 invalid_request`;安全相关字段必须显式校验。
diff --git a/docs/next/api/responses.md b/docs/next/api/responses.md
index 8a42a981..8615a94c 100644
--- a/docs/next/api/responses.md
+++ b/docs/next/api/responses.md
@@ -74,7 +74,7 @@ X-Request-Id: req_01HXYZ123ABCDEF
## 幂等
-`POST` endpoint 支持 `Idempotency-Key`:
+公网部署可以为 `POST` endpoint 提供 `Idempotency-Key`。以下为该能力的契约;当前自部署 tasks 不实现创建请求幂等存储,客户端不自动重试创建,取得 `task_id` 后应继续原任务。
```http
Idempotency-Key: 7f5b7f7c-5c5a-4b2f-bb89-0c901c9a2d6a
diff --git a/docs/next/api/tasks.md b/docs/next/api/tasks.md
index a9c4f197..4655d985 100644
--- a/docs/next/api/tasks.md
+++ b/docs/next/api/tasks.md
@@ -1,111 +1,199 @@
-# V1 便捷解析接口
+# V1 tasks:逐文件上传与结果下载链接
-状态: Implemented
-读者: 自部署 API 与 Router 使用者、服务端开发者
-范围: 一次提交、异步结果、同步包装和源文件复用
+状态: Implemented(自部署 API server 与 Router)
+读者: HTTP 客户端、SaaS 接口与自部署服务开发者
-`mineru-kit api-server` 和 `mineru-kit router` 提供相同的 `/v1/tasks`、`/v1/file_parse` 接口。
-它们与 `/v1/parse/jobs` 共用任务:`task_id` 就是当前部署的 `job_id`,可以在两套查询接口之间交叉使用。
-官方云服务是否支持这些便捷路由,应以该部署的接口文档为准。
+共同流程是:**提交文件清单 → 上传缺失文件 → 轮询任务 → 使用返回链接下载 ZIP**。
+SaaS 可以把上传、下载地址指向 OSS,本地服务可以指向自身的文件接口。客户端只使用服务返回的链接,不拼接存储路径,也不要求 SaaS 实现本地 Files API。
+SaaS 的 Go 服务、OSS 配置及部署由其开发方实现;这里定义客户端共同契约。
-## 路由
+## 路由与状态
| 方法与路径 | 行为 |
|---|---|
-| `POST /v1/tasks` | 提交后返回 `202`、任务状态及查询地址。 |
-| `GET /v1/tasks/{task_id}` | 查询状态、进度和逐文件结果引用。 |
-| `GET /v1/tasks/{task_id}/result` | 直接返回 JSON 结果,或通过 `response_format=zip` 获取 ZIP。 |
-| `DELETE /v1/tasks/{task_id}` | 取消原有后台任务。 |
-| `POST /v1/file_parse` | 提交相同的异步任务,等待并直接返回结果。 |
+| `POST /v1/tasks` | 表单提交文件清单,或本地单文件 multipart 直传;返回 `202`。 |
+| 返回的 `upload_method` 与 `upload_url` | 每个链接上传一个文件,本地使用 `PUT /v1/tasks/{task_id}/uploads/{client_file_id}`。 |
+| `GET /v1/tasks/{task_id}` | 返回 `200` 和任务元数据、缺失文件上传项、可用的结果链接。 |
+| `DELETE /v1/tasks/{task_id}` | 取消等待上传或正在执行的任务。 |
-服务需要鉴权时,所有请求都携带 `Authorization: Bearer <key>`。上传解析参数只来自查询串;JSON 请求则通过主体传递解析参数。
-不提供根路径 `/tasks`、`/file_parse`,也不接受旧 `backend`、`parse_method` 或旧输出协议。
+任务首次创建就获得稳定的 `task_id`;执行提交后,它也是当前部署的公开 `job_id`。等待上传阶段使用 tasks 查询,既有 `/v1/parse/jobs` 执行资源尚未创建。
-## 一次请求获取结果
+状态为 `waiting_upload`、`queued`、`running`、`completed`、`partial`、`failed`、`canceled`。
+全部文件校验通过后自动启动,不要求客户端发送完成确认。等待上传不占解析并发,也不预占 Router worker。
+`completed/partial` 只在最终 ZIP 已保存后发布;打包时仍为 `running`。`partial` 保留成功文件产物及失败文件的错误。
-```bash
-curl -sS 'http://127.0.0.1:8000/v1/file_parse?tier=flash&ocr_mode=txt' \
- -F '[email protected]' -o result.json
-
-curl -sS 'http://127.0.0.1:8000/v1/file_parse?tier=flash&response_format=zip' \
- -F '[email protected]' -o result.zip
-```
+## 表单请求
-多个重复的 `files` 字段表示一个批量任务,整批交给一个 worker。上传方式的查询参数如下:
+`POST /v1/tasks` 只接受 `application/x-www-form-urlencoded` 或 `multipart/form-data`。
+所有业务参数放在表单主体;URL 查询参数返回 `400 invalid_request`,JSON 和原始字节创建请求返回 `415`。
+文件 PUT 使用原始字节。服务返回的 OSS 签名 URL 可以包含查询串,客户端必须原样使用。
-| 参数 | 默认值 | 说明 |
+| 表单字段 | 默认值 | 说明 |
|---|---|---|
-| `tier` | 服务默认值 | `flash/basic/standard/advanced`,仍受服务能力约束。 |
+| `manifest` | 无 | JSON 数组形式的**文本字段**;批量任务必填,最多 100 项。 |
+| `tier` | 服务默认值 | `flash/basic/standard/advanced`,受部署能力约束。 |
| `ocr_mode` | `auto` | `auto/txt/ocr`。 |
-| `page_range` | 整本 | PDF 页范围,批量文件共用;非 PDF 保持整本解析约束。 |
-| `output_formats` | `markdown` | 重复参数选择 `markdown/middle_json/structured_content/zip`。 |
-| `response_format` | `json` | 同步及结果接口支持 `json/zip`。 |
-| `wait_timeout` | `300` | 同步等待秒数,范围 `1–3600`,包含排队及解析。 |
-
-每文件最多 200 MiB,每任务最多 100 文件。需要逐文件页范围或不同来源时,使用与 [Parse Jobs](parse-jobs.md) 相同的 JSON:
-
-```json
-{
- "files": [{"source": {"type": "file_id", "file_id": "file-..."}, "page_range": "1-2"}],
- "tier": "flash",
- "ocr_mode": "txt",
- "output_formats": ["markdown", "middle_json", "zip"]
-}
+| `page_range` | 整本 | 全局 PDF 页范围;仍支持 `1-5`、`r1`、`all` 等现有语法。 |
+| `output_formats` | `markdown` | 可重复字段,支持 `markdown/middle_json/structured_content/zip`;最终 ZIP 始终生成。 |
+| `files` | 无 | 仅本地单文件 multipart 直传使用,最多一个文件。 |
+
+每个清单条目包含:
+
+| 字段 | 必填 | 说明 |
+|---|---|---|
+| `client_file_id` | 是 | 一次任务内唯一,1–64 个字母、数字、下划线或短横线。 |
+| `filename` | 是 | 逻辑文件名,保留扩展名;不同条目允许同名。 |
+| `bytes` | 是 | 文件实际字节数,正整数。 |
+| `sha256sum` | 否 | 64 位小写十六进制 SHA-256;省略时视为需要上传。 |
+| `page_range` | 否 | 逐文件页范围,未提供时继承全局值;非 PDF 仍只支持整本解析。 |
+
+用真实文件生成清单,再发送表单:
+
+```bash
+python3 - a.pdf b.pdf > manifest.json <<'PY'
+import hashlib
+import json
+from pathlib import Path
+import sys
+
+manifest = []
+for index, value in enumerate(sys.argv[1:], start=1):
+ path = Path(value)
+ hasher = hashlib.sha256()
+ with path.open('rb') as source:
+ for chunk in iter(lambda: source.read(1024 * 1024), b''):
+ hasher.update(chunk)
+ manifest.append({
+ 'client_file_id': f'f{index}',
+ 'filename': path.name,
+ 'bytes': path.stat().st_size,
+ 'sha256sum': hasher.hexdigest(),
+ })
+print(json.dumps(manifest, ensure_ascii=False))
+PY
+
+curl --fail-with-body "$MINERU_API_URL/v1/tasks" \
+ -H "Authorization: Bearer $MINERU_API_KEY" \
+ --data-urlencode 'tier=flash' \
+ --data-urlencode 'ocr_mode=txt' \
+ --data-urlencode '[email protected]'
```
-JSON 结果保留 `files[].status/error/output_files`,并在 `files[].content` 内联请求的文本和 JSON 产物。
-Middle JSON 保留 `schema: "docvortex.middle"` 和版本身份;Structured Content 保留当前消费结构,不转换成旧 Content List。
+匿名本地服务可省略 Authorization。无需 hash 时从清单中省略 `sha256sum`。
+`client_file_id` 用于关联文件和上传项,不能按文件名判断对应关系。
+
+## 缓存、上传与恢复
+
+- 全部 hash 命中:返回空 `uploads`,直接提交解析。
+- 部分命中:仅返回未命中文件的上传项,命中文件已经是 `ready`。
+- 无 hash 或未命中:上传完整文件;服务端计算实际 hash、校验大小与可选 hash,并去重保存。
+
+缓存是**源文件缓存**,本次解析仍使用本次 tier、页范围和其他参数。
+新请求不会凭文件 hash 复用不匹配的解析结果。
+
+响应中的共同字段:
-`completed/partial` 返回 `200`;`failed/canceled` 返回 `409`。部分成功保留成功文件和失败项,不把整个任务误报为成功。
-批量 ZIP 使用 `0001/`、`0002/` 等目录,并附带逐文件状态的 `manifest.json`。
+| 字段 | 说明 |
+|---|---|
+| `task_id`、`status`、`status_url` | 稳定任务 ID、当前状态和查询地址。 |
+| `files` | 按输入顺序返回清单、`upload_status: pending/ready`、逐文件解析状态及错误。 |
+| `uploads` | 尚需上传的文件,每项包含 `client_file_id`、`upload_url`、`upload_method: PUT`、`upload_headers`、`expires_at`。 |
+| `result_url` | 结果未就绪时为 `null`;`completed/partial` 时为最终 ZIP 下载地址。 |
+| `error` | 任务级错误,例如上传过期或结果打包失败。 |
+
+本地上传准备默认有效期为 3600 秒,链接的 `expires_at` 为 Unix 秒。
+一个文件完整校验后才变为 `ready`;中断内容不会进入解析或缓存。
+已成功的文件独立保留,后续文件中断只需重传失败文件,继续使用原 `task_id`。
+重复 PUT 已确认文件不会覆盖源字节;同时完成多个文件只会触发一次解析。
-## 异步任务与同步超时
+本轮提供文件级重试,单个文件失败后从头重传,不支持分块断点续传。
+上传响应丢失时先查询任务:文件已 `ready` 就跳过,否则重试该项。
+链接过期而任务仍有效时,重新查询同一任务获取当前链接;本地准备任务整体过期后返回 `failed/upload_expired`。
+
+## 本地单文件快捷直传
```bash
-curl -sS 'http://127.0.0.1:8000/v1/tasks?tier=flash&output_formats=markdown&output_formats=zip' \
+curl --fail-with-body "$MINERU_API_URL/v1/tasks" \
+ -H "Authorization: Bearer $MINERU_API_KEY" \
+ -F 'tier=flash' \
+ -F 'ocr_mode=txt' \
-
-# 使用响应中提供的实际 task_id / result_url。
-curl -sS 'http://127.0.0.1:8000/v1/tasks/job_.../result'
-curl -sS 'http://127.0.0.1:8000/v1/tasks/job_.../result?response_format=zip' -o result.zip
```
-未到终态的结果查询返回 `202`。异步 ZIP 下载要求提交时请求 `zip`,否则返回 `400 unsupported_output_format`;同步 ZIP 会自动请求该产物。
+返回异步任务,不保持连接等待解析。需要声明 hash 时,同时提交仅含一个条目的 manifest 文本字段,例如 `-F 'manifest=<single-manifest.json'`。
-同步等待预算耗尽时返回 `202`,包含 `task_id/status_url/result_url`。任务继续运行;HTTP 断连也不取消已经提交的任务。
-客户端应使用有界查询继续获取结果,不要重新提交同一请求,否则会创建另一份任务。
+多个文件字段,或者多文件清单混入文件字节,返回 `400`,应改用逐文件上传链接。
+直传时实际发送的字节全部接受完整性校验;它不承诺在 hash 命中时跳过网络传输。稳定的省流量由清单预检提供。
-## 哈希与上传复用
+## 下载结果
-新文件可直接 multipart 上传。该方式能复用存储,但文件字节仍经过网络。
-重复解析可以直接提交已有 `file_id`,或使用 [Uploads](uploads-files.md) 的 SHA-256 预检。
+轮询只访问响应的 `status_url`。状态接口不内联 Markdown、Middle JSON 或 ZIP 内容。
-原始字节入口允许在主体之前提交哈希;下面的客户端示例自动计算 SHA-256、编码文件名并支持同步/异步调用:
+- SaaS 返回 OSS 签名下载地址,客户端直接从 OSS 下载,结果字节不经过 API 网关。
+- 本地返回 `/v1/files/{file_id}/content` 的完整地址,服务端从已保存文件流式输出。
+- Router 返回自身的 Files 地址并流式代理 worker 产物,不泄露内部 worker 地址。
-```bash
-MINERU_API_URL=http://127.0.0.1:8000 \
- bash scripts/http_task_example.sh document.pdf
+所有 tasks 自动生成 ZIP;单文件保留现有自包含产物,批量使用 `0001/`、`0002/` 等目录并包含 `manifest.json`。
+manifest 使用 `client_file_id` 关联输入,`directory` 指向包内目录,不写入 worker 的私有 task/file ID 或短期链接。任务 ID 以 HTTP 响应为准。
+ZIP 在后台只生成一次;重复查询或下载不重新打包。打包失败返回 `failed/result_packaging_failed`,不会发布虚假的下载链接。
+签名链接过期但产物仍在保留期内时,重新查询任务获得有效地址,不重新提交解析。
-MINERU_API_URL=http://127.0.0.1:8002 MODE=async RESPONSE_FORMAT=zip \
- bash scripts/http_task_example.sh document.pdf
-```
+认证只附加到与 API 同源的请求。同源由协议、主机、有效端口共同决定;OSS、外部下载地址及跨源重定向不附加 MinerU API Key。
+上传额外请求头使用 `upload_headers`,不硬编码云存储 SDK 或 OSS 域名。
-该方式使用 `Content-Type: application/octet-stream`、查询参数 `filename/sha256sum` 和必须的 `Content-Length`。
-服务命中真实缓存字节时不读取主体;未命中时接收字节并核对实际大小和哈希。
-客户端配合 `Expect: 100-continue`,且服务响应在客户端等待预算内到达时,可以完全跳过文件传输。
-同步解析可能超过客户端的 Expect 等待预算;反向代理也可能自行确认并缓存上传,因此不能对所有部署保证零传输。
+## 完整客户端示例
-Router 仅复用当前调用方仍持有的私有源字节;仅 worker 已知该哈希不构成 Router 命中。
-Router 的 V1 上传与便捷上传共享缓存;哈希命中后仍按任务负载选择 worker,必要时在 worker 间传输缓存字节。
-源文件保持禁止公开下载,`file_id`、任务和上传索引仍是进程内状态,服务重启不提供恢复承诺。
+`scripts/http_task_example.sh` 调用同目录的 `http_task_example.py`,只需要 Python 3.10+ 标准库,无需安装 MinerU 或云存储 SDK。
+默认顺序上传,每个文件最多尝试三次,仅重试网络及临时服务错误;创建请求不自动重试。
+脚本校验任务身份、状态和文件对应关系,轮询有预算,下载先写临时文件并验证 ZIP 后再保存最终文件。
-## Router 调度
+```bash
+MINERU_API_URL=http://127.0.0.1:8000 \
+ bash scripts/http_task_example.sh a.pdf b.pdf
+
+SEND_HASH=0 MINERU_API_URL=http://127.0.0.1:8000 \
+ bash scripts/http_task_example.sh a.pdf b.pdf
-上传不再按凭证和 IP 固定分配。Router 先过滤健康和能力,再比较未完成任务及提交预占的负载;同负载轮询。
-任务按 `(active_jobs / max_concurrent_jobs, active_jobs)` 比较,源文件归属仅在最低负载候选中享有优先权。
-上传与任务的轮询游标独立,能力和状态查询不推进游标。
+# 恢复时使用首次提交的文件列表和顺序,不重新创建任务。
+TASK_ID=job_... MINERU_API_URL=http://127.0.0.1:8000 \
+ bash scripts/http_task_example.sh a.pdf b.pdf
-计数在复制或创建上游任务之前预占;失败、取消、终态和后台回收通过同一机制释放一次。
-一个批量任务仍交给一个 worker。需要多个 worker 同时处理时,提交多个独立任务。
-托管 worker 的容量来自 `--worker-concurrency`;外置 worker 当前按容量 1 计权,只统计通过本 Router 提交的任务。
-现有命令默认获得新策略,不增加调度开关、动态服务发现或多副本共享资源索引。
+UPLOAD_MODE=direct MINERU_API_URL=http://127.0.0.1:8000 \
+ bash scripts/http_task_example.sh a.pdf
+```
+
+| 配置 | 默认值 | 说明 |
+|---|---|---|
+| `MINERU_API_URL` | 必填 | API 或 Router 基地址。 |
+| `MINERU_API_KEY` | 空 | API 认证,匿名本地服务可省略。 |
+| `UPLOAD_MODE` | `preflight` | `preflight/direct`,direct 只支持一个文件。 |
+| `SEND_HASH` | `1` | `0` 时不计算或提交 hash。 |
+| `TASK_ID` | 空 | 继续已有任务,按原文件列表跳过 ready 文件。 |
+| `MINERU_TIER`、`OCR_MODE`、`PAGE_RANGE` | 服务默认 / `auto` / 整本 | 解析参数。 |
+| `OUTPUT_FORMATS` | `markdown` | 逗号分隔,自动加入 ZIP。 |
+| `RESULT_FILE` | `result.zip` | 最终文件位置。 |
+| `MAX_POLLS`、`POLL_INTERVAL` | `300`、`1` | 最多查询次数与间隔秒数。 |
+| `CONNECT_TIMEOUT`、`REQUEST_TIMEOUT` | `10`、`600` | 连接和单次传输超时秒数。 |
+| `MINERU_PYTHON` | `python3` | 可指定 Python 可执行文件。 |
+
+退出码为 `0`(全部成功且保存 ZIP)、`2`(部分成功且保存 ZIP)、`1`(失败或取消)、`124`(轮询预算耗尽)。
+取得任务 ID 后发生错误会打印恢复方式;轮询超时不会取消任务。
+
+## 本地限制与 Router 调度
+
+本地不设固定上传字节数或 PDF 页数上限;`usage.limits.max_file_size_bytes` 与 `max_pages_per_file` 为 `null`。
+每任务最多 100 文件。既有 Jobs 的 URL/inline 来源预算仍按其专用配置生效。
+源文件、上传索引和任务记录仍是进程内状态,重启不保证恢复;完成后的任务及产物沿用部署的保留策略。
+
+Router 的 tasks 与 V1 Uploads 复用按调用方隔离的源字节缓存。
+全部客户端文件齐备后才选择并预占 worker,再向该 worker 提交 tasks 和传输其缺失文件。
+worker 负责最终 ZIP,Router 只查询任务与 File 元数据并映射公开下载地址。
+同负载轮询,缓存命中不把任务固定到繁忙 worker;一个批量任务仍交给同一个 worker。
+失败、取消、终态和后台回收通过同一机制释放预占,等待上传不计入执行负载。
+
+## 迁移
+
+旧 `/v1/file_parse` 和 `/v1/tasks/{task_id}/result` 已移除;不提供同步等待 HTTP 路由或结果正文路由。
+客户端改为轮询 `status_url` 并下载 `result_url`,删除旧 `MODE=sync`、`RESPONSE_FORMAT`、`wait_timeout` 配置。
+旧 tasks JSON 来源、原始字节创建请求和 POST 查询参数不再接受;URL、inline、local、file_id 等资源来源继续使用既有 `/v1/parse/jobs` 协议。
+独立 `/v1/uploads` 与 `/v1/parse/jobs` 的 JSON 请求协议保持不变。
diff --git a/docs/next/api/uploads-files.md b/docs/next/api/uploads-files.md
index b943aab0..c55b8b3e 100644
--- a/docs/next/api/uploads-files.md
+++ b/docs/next/api/uploads-files.md
@@ -374,8 +374,8 @@ Local Parse Server 保持相同 endpoint 和对象结构,但传输实现可以
Router 把完成上传的源字节缓存在私有临时存储,并按调用方 scope 与实际 SHA-256 建立索引。
本地命中时,`POST /v1/uploads` 复用缓存完成选定 worker 的上传并返回 `completed`,客户端跳过 PUT/complete。
本地未命中时,即使某个 worker 已保存该 blob,Router 仍接收客户端字节以保留跨 worker 转移能力。
-`/v1/tasks` 与 `/v1/file_parse` 的上传共用此缓存;只改变源文件名视图不需要再次发送字节。
-删除一个文件别名不会删除其他别名或正在传输的数据。完整行为见 [V1 便捷解析](tasks.md)。
+`/v1/tasks` 的逐文件上传共用此缓存;清单 hash 命中时,只改变源文件名视图不需要再次发送字节。
+删除一个文件别名不会删除其他别名或正在传输的数据。完整行为见 [V1 tasks](tasks.md)。
## Local Server 保留期限
diff --git a/docs/next/api/usage-limits.md b/docs/next/api/usage-limits.md
index 8d088ea4..18583bad 100644
--- a/docs/next/api/usage-limits.md
+++ b/docs/next/api/usage-limits.md
@@ -92,8 +92,8 @@ Authorization: Bearer <MINERU_API_KEY>
"jobs_created": 12
},
"limits": {
- "max_pages_per_file": 1000,
- "max_file_size_bytes": 209715200,
+ "max_pages_per_file": null,
+ "max_file_size_bytes": null,
"max_files_per_job": 100,
"max_concurrent_jobs": 10,
"max_file_retention_days": 30
@@ -112,8 +112,8 @@ Authorization: Bearer <MINERU_API_KEY>
| `current.pages_processed` | integer | 当前周期累计处理页数。 |
| `current.files_processed` | integer | 当前周期累计处理文件数。 |
| `current.jobs_created` | integer | 当前周期累计创建任务数。 |
-| `limits.max_pages_per_file` | integer | 单文件最大页数。 |
-| `limits.max_file_size_bytes` | integer | 单文件最大字节数。 |
+| `limits.max_pages_per_file` | integer 或 null | 单文件最大页数;null 表示未设置固定上限。 |
+| `limits.max_file_size_bytes` | integer 或 null | 上传文件最大字节数;null 表示未设置固定上限。 |
| `limits.max_files_per_job` | integer | 单任务最大文件数。 |
| `limits.max_concurrent_jobs` | integer | 最大并发任务数。 |
| `limits.max_file_retention_days` | integer 或 null | 文件保留天数。 |
@@ -131,6 +131,8 @@ Authorization: Bearer <MINERU_API_KEY>
Local Parse Server 的 usage 不表达计费周期,而是表达本地进程视角:
+- `max_pages_per_file` 与 `max_file_size_bytes` 为 `null`,本地不套用 SaaS 上传大小或页数策略。URL/inline 来源仍受各自专用配置约束。
+
- `billing_period.start` 是服务进程启动时间。
- `billing_period.end` 为 `null`。
- `current.*` 是自启动以来的累计值。
diff --git a/docs/next/cli/mineru-kit.md b/docs/next/cli/mineru-kit.md
index 8cdde1d7..6da86f82 100644
--- a/docs/next/cli/mineru-kit.md
+++ b/docs/next/cli/mineru-kit.md
@@ -90,6 +90,6 @@ mineru-api --host 127.0.0.1 --port 8000 --tier standard
- `--upstream-url` 可重复,用于接入已有 MinerU V1 API base URL。
- `--local-gpus` 支持 `auto`、`none` 或 GPU CSV,例如 `0,1,2`。
- 本地 worker 统一启动 `mineru-kit api-server`;`--worker-tier` 默认 `standard`,`--worker-concurrency` 默认 `1`。
-- Router 完整代理 V1 health、models、tiers、uploads、files、parse jobs 与 usage,并提供 `/v1/tasks`、`/v1/file_parse` 便捷接口;不提供旧根路径。
+- Router 完整代理 V1 health、models、tiers、uploads、files、parse jobs 与 usage,并提供 `/v1/tasks` 表单任务、逐文件上传及结果下载链接;不提供旧根路径。
- Router 只接受显式声明的参数,不再透传未知模型引擎参数;需要额外调优时应部署独立 upstream。
- uploads、files 与 jobs 的公共路由状态保存在当前进程内,Router 重启后不保证旧公共 ID 继续可用。
diff --git a/docs/zh/reference/migration_4.md b/docs/zh/reference/migration_4.md
index 43ff1dae..99cf406e 100644
--- a/docs/zh/reference/migration_4.md
+++ b/docs/zh/reference/migration_4.md
@@ -60,7 +60,7 @@ model:
## API 与 WebUI
-V1 API 使用 `/v1/health`、`/v1/tiers`、`/v1/uploads`、`/v1/parse/jobs` 和 `/v1/files`;旧 `/file_parse`、`/tasks` 不再提供。SDK 客户端和 WebUI 必须连接 V1 服务。文档解析 API 与 OpenAI 兼容 VLM 服务是不同接口,地址不可互换。 自部署 API server 和 Router 新增 `/v1/file_parse` 同步包装和 `/v1/tasks` 便捷异步接口;使用当前 tier、ocr_mode 与输出协议,不恢复旧参数。详见[HTTP API](../usage/http_api.md)。
+V1 API 使用 `/v1/health`、`/v1/tiers`、`/v1/uploads`、`/v1/parse/jobs` 和 `/v1/files`;旧 `/file_parse`、`/tasks` 不再提供。SDK 客户端和 WebUI 必须连接 V1 服务。文档解析 API 与 OpenAI 兼容 VLM 服务是不同接口,地址不可互换。 API server 和 Router 提供 `/v1/tasks` 表单清单、逐文件上传和 ZIP 下载链接;本地另支持单文件 multipart。客户端轮询任务并使用返回链接下载,不再提供同步包装或结果正文便捷路由。详见[HTTP API](../usage/http_api.md)。
原 Gradio 客户端也需按新版事件接口调整,不能仅替换命令名称。第三方插件的旧适配文档保留历史说明,不表示已支持 V1 API。
diff --git a/docs/zh/usage/http_api.md b/docs/zh/usage/http_api.md
index fe990972..fe3b2ffd 100644
--- a/docs/zh/usage/http_api.md
+++ b/docs/zh/usage/http_api.md
@@ -1,45 +1,62 @@
# V1 HTTP API
-自部署 V1 API 与 Python SDK、WebUI 使用同一套接口。本页说明一次完整请求周期——创建上传、上传字节、提交解析任务、轮询到终态、下载产物——并指向一个经过测试的示例脚本。Python 客户端见 [Python SDK](sdk_api.md)。
+推荐 HTTP 客户端使用 tasks 的表单清单与下载链接协议。本页先介绍该流程,再给出 Python SDK、WebUI 使用的既有 Uploads/Jobs 资源工作流。Python 客户端见 [Python SDK](sdk_api.md)。
-先启动本地服务,或将示例指向任意 V1 部署(包括官方云服务):
+先启动本地服务;使用 SaaS 时,将客户端指向实现同一 tasks 契约的服务地址:
```bash
mineru-kit api-server --host 127.0.0.1 --port 8000 --tier standard
```
-## 一次请求解析与异步 tasks
+## tasks:清单、逐文件上传与 ZIP 下载
-API server 和 Router 都提供 `/v1/tasks`、`/v1/file_parse`,与现有 Job 共用后台解析和任务 ID:
+API server、Router 和采用同一契约的 SaaS 使用相同客户端流程:提交清单、上传缺失文件、轮询状态、下载返回的 `result_url`。
+SaaS 可以返回 OSS 直链,本地返回 Files 下载地址;客户端原样使用链接,不拼接下载路径,也不要求云端实现本地 Files API。
+完整契约见 [V1 tasks](../../next/api/tasks.md)。
```bash
-curl -sS 'http://127.0.0.1:8000/v1/file_parse?tier=flash&ocr_mode=txt' \
- -F '[email protected]' -o result.json
+# 单文件或多个文件:默认先预检,只上传未命中缓存的项。
+MINERU_API_URL=http://127.0.0.1:8000 \
+ bash scripts/http_task_example.sh a.pdf b.pdf
-curl -sS 'http://127.0.0.1:8000/v1/file_parse?tier=flash&response_format=zip' \
- -F '[email protected]' -o result.zip
+# hash 可选。
+SEND_HASH=0 MINERU_API_URL=http://127.0.0.1:8000 \
+ bash scripts/http_task_example.sh a.pdf b.pdf
-MINERU_API_URL=http://127.0.0.1:8002 MODE=async RESPONSE_FORMAT=zip \
- bash scripts/http_task_example.sh document.pdf
+# 使用首次提交的文件列表和顺序继续原任务。
+TASK_ID=job_... MINERU_API_URL=http://127.0.0.1:8000 \
+ bash scripts/http_task_example.sh a.pdf b.pdf
+
+# 本地仅保留单文件 multipart 快捷提交,仍返回异步任务。
+curl --fail-with-body 'http://127.0.0.1:8000/v1/tasks' \
+ -F 'tier=flash' -F 'ocr_mode=txt' -F '[email protected]'
```
-同步等待默认 300 秒,`wait_timeout` 支持 1–3600 秒;超时返回 `202` 和 `task_id/status_url/result_url`,任务继续执行。
-异步提交使用 `POST /v1/tasks`,通过返回的 V1 地址查询状态和结果。JSON 内联 `files[].content`,同时保留逐文件错误和产物引用。
-异步 ZIP 必须提交时请求 `output_formats=zip`;同步 ZIP 自动请求。部分成功返回 `200` 和 `partial`,批量 ZIP 含分目录产物及 manifest。
+`POST /v1/tasks` 的参数全部放在表单中。`manifest` 是 JSON 数组形式的文本字段,每项包含唯一 `client_file_id`、`filename`、实际 `bytes`,可选 `sha256sum` 与逐文件 `page_range`。
+多文件任务只能提交清单,不能在同一个请求中附带文件字节。单文件直传需要 hash 时,可附带单条 manifest。
+解析选项仍使用 `tier`、`ocr_mode`、`page_range` 和重复的 `output_formats`,ZIP 始终生成。
+POST 查询参数返回 `400`,JSON 和原始字节创建请求返回 `415`。独立 Uploads/Jobs 的现有 JSON 协议不受影响。
+
+创建立即返回稳定的 `task_id` 和 `status_url`;`uploads` 只包含需要上传的项,每项给出上传方法、地址、请求头与有效期。
+所有文件校验通过后自动开始,客户端不再发送完成确认。未提供 hash 时正常上传,服务端仍计算 hash 并去重保存。
+文件完整上传后独立标记为 `ready`;后续文件中断只需重传失败文件,已经成功的文件保留。当前支持文件级重试,不支持单文件分块续传。
+
+客户端只轮询 `status_url`。状态为 `waiting_upload/queued/running/completed/partial/failed/canceled`。
+最终 ZIP 已保存后才返回 `completed/partial` 和 `result_url`;状态接口不内联解析正文,下载不经过 SaaS API 网关。
+批量 ZIP 含编号目录及逐文件 manifest。打包失败是任务失败,不能返回不可用的下载链接。
-上传可以是 multipart 或原始字节,也可使用与 V1 Job 相同的 JSON 来源。上传解析参数放查询串,JSON 参数放主体。
-每文件最多 200 MiB,每任务最多 100 文件;批量上传共用页范围,逐文件配置使用 JSON。原始字节需提供 `filename` 和 `Content-Length`。
-上述脚本自动计算 SHA-256 并使用 `Expect: 100-continue`;命中缓存且及时响应时,可跳过主体传输。
-代理缓冲和客户端等待预算会影响省流量效果;直接复用 `file_id` 或现有 uploads 预检仍可可靠避免重复上传。
+完整客户端由 [`scripts/http_task_example.sh`](https://github.com/opendatalab/MinerU/blob/master/scripts/http_task_example.sh) 与同目录 Python 文件维护,只需 Python 3.10+ 标准库。
+`UPLOAD_MODE=direct` 只支持一个文件;`RESULT_FILE` 默认 `result.zip`。`MAX_POLLS/POLL_INTERVAL` 控制有界轮询,`CONNECT_TIMEOUT/REQUEST_TIMEOUT` 控制传输预算。
+每个文件最多尝试三次,创建任务不自动重试;响应丢失先查询文件状态,链接过期则查询原任务刷新。
+API Key 只附加到同源请求,OSS、外部下载和跨源重定向不携带该 Key。
+退出码为 `0`(成功)、`2`(部分成功且已保存 ZIP)、`1`(失败或取消)、`124`(等待预算耗尽,保留任务)。
-Router 的 V1 上传和便捷上传共享按调用方隔离的源字节缓存。上传按负载分配、同负载轮询;任务在上游网络等待前预占名额。
-文件归属仅在最低负载候选中享有优先权,哈希命中也不能把任务固定到繁忙 worker。
-一个批量任务仍整体交给一台 API,需要多 worker 并行时提交多个独立任务。
-外置 worker 当前按容量 1 计权;本地 worker 容量来自 `--worker-concurrency`。这些路由属于当前自部署服务,云端支持情况以具体部署为准。
+本地不设固定的上传字节数或 PDF 页数上限,每任务最多 100 文件。等待上传不占解析名额,也不预占 Router worker。
+Router 按负载选择 worker,并在向上游提交前预占;缓存命中不固定到繁忙 worker。批量文件仍交给同一个 worker,最终 ZIP 在 worker 生成,Router 只映射资源并流式下载。
-## 经过测试的示例脚本
+## 既有 Uploads / Jobs 资源示例
-包含超时、响应校验、有界轮询、退出码和凭据隔离的完整闭环,以仓库中单一经过测试的脚本维护:
+需要操作独立 Upload、File 与 Job 资源时,继续使用以下脚本;其协议和退出码保持不变,与上面的 tasks 脚本分别维护:
> [`scripts/http_api_example.sh`](https://github.com/opendatalab/MinerU/blob/master/scripts/http_api_example.sh)
@@ -60,7 +77,7 @@ export MINERU_API_KEY=secret-key # 匿名本地访问时省略
| `4` | 任务 canceled |
| `124` | 轮询预算耗尽;打印 `job_id`,可继续轮询 |
-## 鉴权与字节上传
+## 资源级接口的鉴权与字节上传
服务以 `--api-key` 启动时,`/v1/*` 请求携带 `Authorization: Bearer $MINERU_API_KEY`;匿名本地访问可省略该头。
@@ -73,7 +90,7 @@ export MINERU_API_KEY=secret-key # 匿名本地访问时省略
下载走 `GET /v1/files/{file_id}/content`,可能返回 `302` 重定向。示例跟随重定向但不使用 `--location-trusted`,凭据不会被重新发送到不同源(包括同主机不同端口;要求 curl >= 7.83.0)。
-## 脚本刻意覆盖的请求周期细节
+## 资源级脚本的请求周期细节
- **上传生命周期。** 创建上传时传 `sha256sum` 可启用完整性校验和秒传;命中已存在文件时响应直接为 `completed` 并内嵌 `file` 对象,跳过字节上传和完成两步。
- **HTTP 200 不等于合法响应。** 脚本在每一步校验 JSON 结构:ID 必须是非空字符串、状态必须属于支持集合;否则立即失败,而不是带着 null ID 进入轮询。
@@ -89,4 +106,4 @@ export MINERU_API_KEY=secret-key # 匿名本地访问时省略
- `--concurrency` 限制并发解析任务数;超出后表现为 `queued` 时间变长,而不是失败。
- `GET /v1/usage` 报告用量。用 `/v1/health` 和 `/docs`(启用时)的 OpenAPI 文档区分服务端故障与客户端错误;重试 `failed` 任务前先查看服务端日志。
-便捷解析使用 `/v1/file_parse`、`/v1/tasks`;根路径旧接口不提供,旧客户端迁移见[迁移指南](../reference/migration_4.md)。
+新的便捷工作流统一使用 `/v1/tasks` 和返回链接,不提供同步等待或结果正文路由。根路径旧接口不提供,旧客户端迁移见[迁移指南](../reference/migration_4.md)。
diff --git a/mineru/cli/commands/usage.py b/mineru/cli/commands/usage.py
index d1cd3f7a..5cf78a70 100644
--- a/mineru/cli/commands/usage.py
+++ b/mineru/cli/commands/usage.py
@@ -64,7 +64,11 @@ def _render_remote_usage(view: RemoteUsageOutput) -> RenderableOutput:
" " + t("Jobs created: {count}", count=usage.current.jobs_created),
"",
t("Limits"),
- " " + t("Max pages per file: {count}", count=usage.limits.max_pages_per_file),
+ " "
+ + t(
+ "Max pages per file: {count}",
+ count=usage.limits.max_pages_per_file if usage.limits.max_pages_per_file is not None else t("unlimited"),
+ ),
" " + t("Max file size: {size}", size=_format_bytes(usage.limits.max_file_size_bytes)),
" " + t("Max files per job: {count}", count=usage.limits.max_files_per_job),
" " + t("Max concurrent jobs: {count}", count=usage.limits.max_concurrent_jobs),
@@ -91,7 +95,10 @@ def _format_utc_timestamp(value: str) -> str:
return parsed.strftime("%Y-%m-%d %H:%M UTC")
-def _format_bytes(value: int) -> str:
+def _format_bytes(value: int | None) -> str:
+ """将明确的无限制值显示为文案,保留有上限部署的 MiB 展示。"""
+ if value is None:
+ return t("unlimited")
mib = value / (1024 * 1024)
return f"{mib:g} MiB"
diff --git a/mineru/doclib/types.py b/mineru/doclib/types.py
index f4967a27..68d82e06 100644
--- a/mineru/doclib/types.py
+++ b/mineru/doclib/types.py
@@ -412,8 +412,8 @@ class RemoteUsageCurrent(DoclibModel):
class RemoteUsageLimits(DoclibModel):
- max_pages_per_file: int
- max_file_size_bytes: int
+ max_pages_per_file: int | None
+ max_file_size_bytes: int | None
max_files_per_job: int
max_concurrent_jobs: int
max_file_retention_days: int | None = None
diff --git a/mineru/kit/router/app.py b/mineru/kit/router/app.py
index f89d1686..2d8e1e34 100644
--- a/mineru/kit/router/app.py
+++ b/mineru/kit/router/app.py
@@ -7,9 +7,8 @@ import asyncio
import copy
import hashlib
import json
-import secrets
import time
-from contextlib import ExitStack, asynccontextmanager
+from contextlib import asynccontextmanager
from pathlib import Path
from typing import Any, AsyncIterator, Literal, get_args
@@ -18,8 +17,8 @@ from fastapi import FastAPI, Query, Request
from fastapi.responses import JSONResponse, Response
from ...filetypes import is_flash_only_parse_extension
-from ...parser.api_server import CreateUploadRequest, OutputFormat
-from ...parser.task_api import TaskUpload, build_task_router
+from ...parser.api_server import ApiServerError, CreateUploadRequest, OutputFormat
+from ...parser.task_api import TaskStore, build_task_router
from ...types import TIERS, select_default_quality_tier, validate_tier
from ...utils.async_utils import drain_future
from ...version import __version__
@@ -191,8 +190,8 @@ def _usage_payload(request: Request, registry: ResourceRegistry, pool: WorkerPoo
**registry.usage(owner_scope),
},
"limits": {
- "max_pages_per_file": 1000,
- "max_file_size_bytes": 209715200,
+ "max_pages_per_file": None,
+ "max_file_size_bytes": None,
"max_files_per_job": 100,
"max_concurrent_jobs": sum(worker.max_concurrent_jobs for worker in pool.healthy_workers()),
"max_file_retention_days": None,
@@ -364,6 +363,12 @@ async def _reconcile_jobs_once(registry: ResourceRegistry, pool: WorkerPool) ->
worker = pool.get(route.worker_id)
generation = worker.generation
try:
+ if route.metadata.get("task_protocol"):
+ from .tasks import read_task_execution
+
+ execution = await read_task_execution(route, pool, registry, headers=headers)
+ await _finalize_terminal_job(route, execution.job, request=None, pool=pool, registry=registry, headers=headers)
+ continue
response = await request_upstream(
pool,
worker,
@@ -389,7 +394,7 @@ async def _reconcile_jobs_once(registry: ResourceRegistry, pool: WorkerPool) ->
registry=registry,
headers=headers,
)
- except RouterProxyError:
+ except (RouterProxyError, ApiServerError):
continue
@@ -413,6 +418,7 @@ def create_app(
resolved_settings = settings or RouterSettings.from_env()
registry = ResourceRegistry(resolved_settings.retention_seconds)
source_store = SourceFileStore(resolved_settings.retention_seconds)
+ task_store = TaskStore(resolved_settings.retention_seconds)
async def _invalidate_replaced_worker(worker: WorkerState) -> None:
"""在本地 worker replacement 发布前移除旧 generation 的资源状态。"""
@@ -463,6 +469,7 @@ def create_app(
if resolved_settings.retention_seconds:
collection_task = asyncio.create_task(collection_loop(), name="mineru-router-retention")
await pool.start()
+ task_store.start()
if resolved_settings.worker_refresh_interval_seconds > 0:
reconcile_task = asyncio.create_task(
_job_reconcile_loop(
@@ -483,6 +490,7 @@ def create_app(
await reconcile_task
except asyncio.CancelledError:
pass
+ await task_store.shutdown()
await pool.close()
source_store.close()
@@ -494,6 +502,7 @@ def create_app(
application.state.settings = resolved_settings
application.state.registry = registry
application.state.source_store = source_store
+ application.state.task_store = task_store
application.state.worker_pool = pool
application.state.started_at = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
@@ -804,11 +813,10 @@ def create_app(
result["id"] = file_id
return JSONResponse(result, status_code=upstream.status_code)
- async def submit_job(body: dict[str, Any], request: Request, uploads: dict[int, TaskUpload] | None = None) -> Response:
- """统一选择并预占 worker,V1 Job 和便捷任务共用上传与副本清理。"""
+ async def submit_job(body: dict[str, Any], request: Request) -> Response:
+ """为既有 V1 Job 选择并预占 worker,继续处理跨 worker 源文件复制。"""
owner_scope = _caller_scope(request)
body = copy.deepcopy(body)
- uploads = uploads or {}
output_formats = body.get("output_formats", ["markdown"])
if not isinstance(output_formats, list) or any(not isinstance(fmt, str) for fmt in output_formats):
raise RouterProxyError(400, "invalid_request", "output_formats must be a list of strings", "output_formats")
@@ -826,9 +834,7 @@ def create_app(
if not isinstance(source, dict) or not isinstance(source.get("type"), str):
raise RouterProxyError(400, "invalid_request", "Each file must contain a typed source", f"files.{index}.source")
required_sources.add(source["type"])
- if index in uploads:
- names.append(uploads[index].filename)
- elif source["type"] == "file_id":
+ if source["type"] == "file_id":
public_file_id = source.get("file_id")
if not isinstance(public_file_id, str):
raise RouterProxyError(400, "invalid_request", "file_id source requires a string file_id")
@@ -873,92 +879,53 @@ def create_app(
worker = reservation.worker
input_aliases: dict[str, str] = {}
copied_files: list[CopiedInputFile] = []
- registered_inputs: list[ResourceRoute] = []
- staged: list[str] = []
transferred = False
async def rollback() -> None:
"""回收未被任务接管的跨 worker 副本和本次创建的源文件视图。"""
if worker.generation == reservation.generation and worker.base_url:
await _cleanup_copied_files(copied_files, request=request, pool=pool, registry=registry)
- for route in registered_inputs:
- try:
- if worker.generation == reservation.generation and worker.base_url:
- await request_upstream(pool, worker, "DELETE", f"/v1/files/{route.upstream_id}", request=request)
- except RouterProxyError:
- pass
- registry.remove("file", route.public_id)
- source_store.delete_file(route.public_id)
try:
- with ExitStack() as pins:
- # 哈希命中输入在第一次网络等待前固定缓存引用,避免并发删除原文件。
- cached_inputs = {}
- for index, upload in uploads.items():
- cached = source_store.find_hash(owner_scope, upload.sha256sum)
- if cached is not None:
- pins.enter_context(source_store.pin(cached))
- cached_inputs[index] = cached
- for index, upload in uploads.items():
- stored = cached_inputs.get(index)
- if stored is None:
- staging_id = "task-" + secrets.token_hex(12)
- staged.append(staging_id)
- stored = await source_store.stage_upload(
- staging_id, stored_file_chunks(upload.path), mime_type=upload.mime_type, max_bytes=200 * 1024 * 1024
- )
- pins.enter_context(source_store.pin(stored))
- payload = await upload_stored_source(
- stored, upload.filename, worker, request=request, pool=pool, generation=reservation.generation
+ for source, route in file_routes:
+ target_file_id = route.upstream_id
+ if route.worker_id != worker.worker_id:
+ target_file_id = await copy_file_to_worker(
+ route, worker, request=request, pool=pool, registry=registry, source_store=source_store
)
- rewritten = rewrite_file_payload(payload["file"], worker, registry, owner_scope)
- public_id = str(rewritten["id"])
- route = _route_or_404(registry, "file", public_id, owner_scope)
- registered_inputs.append(route)
- source_store.bind_source(public_id, stored, owner_scope=owner_scope, expires_at=rewritten.get("expires_at"))
- input_aliases[route.upstream_id] = public_id
- files[index]["source"] = {"type": "file_id", "file_id": route.upstream_id}
- for source, route in file_routes:
- target_file_id = route.upstream_id
- if route.worker_id != worker.worker_id:
- target_file_id = await copy_file_to_worker(
- route, worker, request=request, pool=pool, registry=registry, source_store=source_store
+ copied_files.append(
+ CopiedInputFile(
+ source_public_id=route.public_id,
+ owner_scope=owner_scope,
+ worker_id=worker.worker_id,
+ upstream_file_id=target_file_id,
)
- copied_files.append(
- CopiedInputFile(
- source_public_id=route.public_id,
- owner_scope=owner_scope,
- worker_id=worker.worker_id,
- upstream_file_id=target_file_id,
- )
- )
- input_aliases[target_file_id] = route.public_id
- source["file_id"] = target_file_id
- upstream = await request_upstream(pool, worker, "POST", "/v1/parse/jobs", request=request, json_body=body)
- require_worker_generation(worker, reservation.generation)
- result = _successful_json(upstream)
- if isinstance(result, Response):
- return result
- upstream_job_id = result.get("job_id")
- if not isinstance(upstream_job_id, str):
- raise RouterProxyError(502, "invalid_upstream_response", "Created job did not return a job_id")
- job_route = registry.register(
- "job", owner_scope=owner_scope, worker_id=worker.worker_id, upstream_id=upstream_job_id
- )
- job_route.metadata.update(
- input_aliases=input_aliases,
- copied_inputs=copied_files,
- active_counted=True,
- reservation=reservation,
- upstream_headers=_authorization_headers(request),
- )
- transferred = True
- rewritten = rewrite_job_payload(result, worker, registry, pool, owner_scope)
- await _finalize_terminal_job(job_route, rewritten, request=request, pool=pool, registry=registry)
- return JSONResponse(rewritten, status_code=upstream.status_code)
+ )
+ input_aliases[target_file_id] = route.public_id
+ source["file_id"] = target_file_id
+ upstream = await request_upstream(pool, worker, "POST", "/v1/parse/jobs", request=request, json_body=body)
+ require_worker_generation(worker, reservation.generation)
+ result = _successful_json(upstream)
+ if isinstance(result, Response):
+ return result
+ upstream_job_id = result.get("job_id")
+ if not isinstance(upstream_job_id, str):
+ raise RouterProxyError(502, "invalid_upstream_response", "Created job did not return a job_id")
+ job_route = registry.register(
+ "job", owner_scope=owner_scope, worker_id=worker.worker_id, upstream_id=upstream_job_id
+ )
+ job_route.metadata.update(
+ input_aliases=input_aliases,
+ copied_inputs=copied_files,
+ active_counted=True,
+ reservation=reservation,
+ upstream_headers=_authorization_headers(request),
+ )
+ transferred = True
+ rewritten = rewrite_job_payload(result, worker, registry, pool, owner_scope)
+ await _finalize_terminal_job(job_route, rewritten, request=request, pool=pool, registry=registry)
+ return JSONResponse(rewritten, status_code=upstream.status_code)
finally:
- for staging_id in staged:
- source_store.discard_upload(staging_id)
if not transferred:
reservation.release()
await drain_future(asyncio.create_task(rollback()))
@@ -995,6 +962,10 @@ def create_app(
route = _route_or_404(registry, "job", job_id, owner_scope)
if route.metadata.get("upstream_lost"):
return JSONResponse(route.metadata["payload"])
+ if route.metadata.get("task_protocol"):
+ execution = await read_task_execution(route, pool, registry, request=request)
+ await _finalize_terminal_job(route, execution.job, request=request, pool=pool, registry=registry)
+ return JSONResponse(execution.job)
worker = pool.get(route.worker_id)
generation = worker.generation
upstream = await request_upstream(pool, worker, "GET", f"/v1/parse/jobs/{route.upstream_id}", request=request)
@@ -1025,6 +996,9 @@ def create_app(
route = _route_or_404(registry, "job", job_id, _caller_scope(request))
if route.metadata.get("upstream_lost"):
raise RouterProxyError(409, "job_already_terminal", "Job is failed")
+ if route.metadata.get("task_protocol"):
+ await task_backend(request).cancel(job_id)
+ return JSONResponse({"job_id": job_id, "status": "canceled", "canceled_at": utc_now_iso()})
worker = pool.get(route.worker_id)
upstream = await request_upstream(pool, worker, "DELETE", f"/v1/parse/jobs/{route.upstream_id}", request=request)
result = _successful_json(upstream)
@@ -1049,11 +1023,15 @@ def create_app(
"""返回当前 Router 进程聚合的 V1 usage。"""
return _usage_payload(request, registry, pool, _caller_scope(request))
- from .tasks import RouterTaskBackend, install_task_error_handlers
+ from .tasks import RouterTaskBackend, install_task_error_handlers, read_task_execution
+
+ async def finalize_task_job(route: ResourceRoute, payload: dict[str, Any], request: Request | None) -> None:
+ """新任务沿用既有产物元数据补齐及负载释放边界。"""
+ await _finalize_terminal_job(route, payload, request=request, pool=pool, registry=registry)
def task_backend(request: Request) -> RouterTaskBackend:
"""显式组装 Router 适配器,便捷入口不通过 HTTP 请求自身。"""
- return RouterTaskBackend(request, submit_job, get_job, cancel_job, _caller_scope(request))
+ return RouterTaskBackend(request, _caller_scope(request), finalize_task_job)
install_task_error_handlers(application)
application.include_router(build_task_router(task_backend))
diff --git a/mineru/kit/router/tasks.py b/mineru/kit/router/tasks.py
index a56b9732..6ba263ca 100644
--- a/mineru/kit/router/tasks.py
+++ b/mineru/kit/router/tasks.py
@@ -1,132 +1,469 @@
-"""把共享便捷任务接口适配到 Router 的公共资源和上游 V1 服务。"""
+"""Router 的逐文件任务适配器;worker 负责解析与最终 ZIP,Router 仅映射资源。"""
from __future__ import annotations
import asyncio
+import copy
import json
+import secrets
import time
-from collections.abc import Awaitable, Callable
+from collections.abc import AsyncIterator, Awaitable, Callable, Mapping
from contextlib import ExitStack
+from dataclasses import replace
from typing import Any
+from urllib.parse import SplitResult, quote, unquote, urlencode, urljoin, urlsplit
-from fastapi import FastAPI, Request, Response
+import httpx
+from fastapi import FastAPI, Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
+from pydantic import ValidationError
-from ...parser.api_server import ApiServerError, CreateJobRequest, ErrorDetail
-from ...parser.task_api import TERMINAL_TASK_STATUSES, TaskUpload
-from .proxy import RouterProxyError, request_upstream
-from .resources import ResourceRegistry, SourceFileStore
-from .workers import WorkerPool
+from ...filetypes import is_flash_only_parse_extension
+from ...parser.api_server import ApiServerError, ErrorDetail, _raise_api_error
+from ...parser.task_api import (
+ TERMINAL_TASK_STATUSES,
+ TaskExecution,
+ TaskManifestItem,
+ TaskStatusResponse,
+ TaskUpload,
+ UploadTaskOptions,
+ file_chunks,
+ resolve_task_tier,
+)
+from ...types import select_default_quality_tier
+from ...utils.async_utils import drain_future
+from .proxy import (
+ RouterProxyError,
+ release_job_load,
+ request_upstream,
+ require_worker_generation,
+ rewrite_file_payload,
+ rewrite_job_payload,
+)
+from .resources import ResourceRegistry, ResourceRoute, SourceFileStore, StoredSourceFile, utc_now_iso
+from .workers import WorkerPool, WorkerState
-SubmitJob = Callable[[dict[str, Any], Request, dict[int, TaskUpload]], Awaitable[Response]]
-ReadJob = Callable[[str, Request], Awaitable[Response]]
+FinalizeJob = Callable[[ResourceRoute, dict[str, Any], Request | None], Awaitable[None]]
-def _response_data(response: Response) -> dict[str, Any]:
- """读取内部服务 JSON,错误保留原 HTTP 状态和 V1 error 字段。"""
+def _checked_json(response: httpx.Response) -> dict[str, Any]:
+ """保留 worker 的业务错误码,非法响应不能伪装成成功任务。"""
try:
- data = json.loads(bytes(response.body))
- if not isinstance(data, dict):
- raise ValueError("Response must be an object")
- except ValueError as exc:
- status = response.status_code if response.status_code >= 400 else 502
- raise RouterProxyError(status, "invalid_upstream_response", "Upstream response is not a JSON object") from exc
+ payload = response.json()
+ if not isinstance(payload, dict):
+ raise ValueError("Expected an object")
+ except ValueError:
+ _raise_api_error(
+ response.status_code if response.status_code >= 400 else 502,
+ error_type="api_error",
+ code="invalid_upstream_response",
+ message="Upstream did not return a JSON object",
+ )
if response.status_code >= 400:
- raw = data.get("error") or {}
+ detail = payload.get("error") or {}
raise ApiServerError(
response.status_code,
- ErrorDetail(
- type=raw.get("type", "api_error"),
- code=raw.get("code"),
- message=raw.get("message", "Upstream error"),
- param=raw.get("param"),
+ ErrorDetail.model_validate(
+ {
+ "type": detail.get("type", "api_error"),
+ "code": detail.get("code", "upstream_error"),
+ "message": detail.get("message", "Upstream request failed"),
+ "param": detail.get("param"),
+ }
),
)
- return data
+ return payload
+
+
+async def _worker_request(
+ pool: WorkerPool,
+ worker: WorkerState,
+ method: str,
+ path: str,
+ *,
+ request: Request | None = None,
+ content: bytes | AsyncIterator[bytes] | None = None,
+ headers: Mapping[str, str] | None = None,
+) -> httpx.Response:
+ """把网络错误转换成共享 tasks 错误,监控阶段可识别临时失败并继续查询。"""
+ try:
+ return await request_upstream(pool, worker, method, path, request=request, content=content, headers=headers)
+ except RouterProxyError as exc:
+ _raise_api_error(exc.status_code, error_type="api_error", code=exc.code, message=exc.message, param=exc.param)
+
+
+def _worker_path(worker: WorkerState, url: str) -> str:
+ """只接受配置 worker 自身的资源链接,禁止把私有认证或源文件转发到其他地址。"""
+ base = urlsplit(worker.base_url)
+ target = urlsplit(urljoin(worker.base_url.rstrip("/") + "/", url))
+
+ def origin(item: SplitResult) -> tuple[str, str | None, int]:
+ """按协议、主机及有效端口比较来源,端口不同也属于跨源。"""
+ return item.scheme, item.hostname, item.port or (443 if item.scheme == "https" else 80)
+
+ prefix = base.path.rstrip("/")
+ if origin(base) != origin(target) or target.username or target.password or target.query or target.fragment:
+ _raise_api_error(502, error_type="api_error", code="invalid_upstream_response", message="Invalid worker resource URL")
+ if prefix and not target.path.startswith(prefix + "/"):
+ _raise_api_error(502, error_type="api_error", code="invalid_upstream_response", message="Invalid worker resource path")
+ return target.path[len(prefix) :]
+
+
+def _job_payload(payload: dict[str, Any], upstream_id: str, *, authenticated: bool) -> dict[str, Any]:
+ """把 worker 的 tasks 元数据转换成既有 Router Job 视图,不泄露上传或 worker 链接。"""
+ file_keys = ("file_id", "name", "page_range", "status", "parse", "output_files", "error")
+ files = [{key: item.get(key) for key in file_keys} for item in payload["files"]]
+ for file in files:
+ if file["status"] in {"waiting_upload", "canceled"}:
+ file["status"] = "queued"
+ return {
+ "job_id": upstream_id,
+ "status": "queued" if payload["status"] == "waiting_upload" else payload["status"],
+ "created_at": payload["created_at"],
+ "started_at": payload.get("started_at"),
+ "finished_at": payload.get("finished_at"),
+ "tier": payload["tier"],
+ "output_formats": payload["output_formats"],
+ "progress": payload["progress"],
+ "access_level": "registered" if authenticated else "anonymous",
+ "files": files,
+ "links": {"self": f"/v1/parse/jobs/{upstream_id}", "cancel": f"/v1/parse/jobs/{upstream_id}"},
+ }
+
+
+def _lost_execution(route: ResourceRoute, pool: WorkerPool) -> TaskExecution:
+ """worker 丢失时收敛失败和负载,保留已经成功文件的诊断信息。"""
+ payload = copy.deepcopy(route.metadata.get("payload") or {})
+ payload.update(job_id=route.public_id, status="failed", finished_at=utc_now_iso())
+ error = ErrorDetail(type="engine_error", code="upstream_task_lost", message="Upstream task no longer exists")
+ for file in payload.get("files") or []:
+ if file.get("status") != "completed":
+ file.update(status="failed", error=error.model_dump())
+ route.metadata.update(payload=payload, upstream_lost=True)
+ release_job_load(route, pool)
+ return TaskExecution(payload, error=error)
+
+
+async def read_task_execution(
+ route: ResourceRoute,
+ pool: WorkerPool,
+ registry: ResourceRegistry,
+ *,
+ request: Request | None = None,
+ headers: Mapping[str, str] | None = None,
+) -> TaskExecution:
+ """查询 worker 的轻量任务状态,并把最终 ZIP 登记为 Router 的公共 File。"""
+ if route.metadata.get("upstream_lost"):
+ return _lost_execution(route, pool)
+ worker = pool.get(route.worker_id)
+ generation = worker.generation
+ response = await _worker_request(
+ pool,
+ worker,
+ "GET",
+ f"/v1/tasks/{quote(route.upstream_id, safe='')}",
+ request=request,
+ headers=headers,
+ )
+ if response.status_code == 404 or worker.generation != generation or route.metadata.get("upstream_lost"):
+ return _lost_execution(route, pool)
+ try:
+ payload = TaskStatusResponse.model_validate(_checked_json(response)).model_dump()
+ except ValidationError as exc:
+ _raise_api_error(502, error_type="api_error", code="invalid_upstream_response", message=str(exc))
+ if payload["task_id"] != route.upstream_id:
+ _raise_api_error(502, error_type="api_error", code="invalid_upstream_response", message="Upstream task ID changed")
+ result_file_id: str | None = None
+ if payload["status"] in {"completed", "partial"}:
+ result_url = payload.get("result_url")
+ if not isinstance(result_url, str):
+ _raise_api_error(502, error_type="api_error", code="invalid_upstream_response", message="Missing ZIP URL")
+ path = _worker_path(worker, result_url)
+ parts = path.strip("/").split("/")
+ if len(parts) != 4 or parts[:2] != ["v1", "files"] or parts[-1] != "content":
+ _raise_api_error(502, error_type="api_error", code="invalid_upstream_response", message="Invalid ZIP File URL")
+ upstream_file_id = unquote(parts[2])
+ existing = registry.find_upstream("file", route.owner_scope, worker.worker_id, upstream_file_id)
+ if existing is None or not isinstance(existing.metadata.get("payload"), dict):
+ metadata = _checked_json(
+ await _worker_request(
+ pool,
+ worker,
+ "GET",
+ f"/v1/files/{quote(upstream_file_id, safe='')}",
+ request=request,
+ headers=headers,
+ )
+ )
+ require_worker_generation(worker, generation)
+ if metadata.get("id") != upstream_file_id or metadata.get("purpose") != "parse_output":
+ _raise_api_error(
+ 502, error_type="api_error", code="invalid_upstream_response", message="Invalid ZIP File metadata"
+ )
+ result_file_id = rewrite_file_payload(metadata, worker, registry, route.owner_scope)["id"]
+ else:
+ result_file_id = existing.public_id
+ authenticated = bool(request.headers.get("authorization") if request is not None else (headers or {}).get("authorization"))
+ rewritten = rewrite_job_payload(
+ _job_payload(payload, route.upstream_id, authenticated=authenticated),
+ worker,
+ registry,
+ pool,
+ route.owner_scope,
+ )
+ route.metadata["task_result_file_id"] = result_file_id
+ error = ErrorDetail.model_validate(payload["error"]) if payload.get("error") else None
+ return TaskExecution(rewritten, result_file_id, error)
class RouterTaskBackend:
- """复用 Router 的既有服务函数,所有产物访问均检查调用方资源 scope。"""
+ """输入全部就绪后才选择 worker,并通过同一 tasks 协议提交和上传缺失文件。"""
- def __init__(self, request: Request, submit: SubmitJob, get: ReadJob, cancel: ReadJob, owner_scope: str) -> None:
- """保存显式回调和当前 Router 资源,不建立独立任务队列。"""
- self.request = request
+ def __init__(self, request: Request, owner_scope: str, finalize: FinalizeJob) -> None:
+ """保存轻量上下文与显式收尾回调,不跨请求保存上传表单。"""
+ self.request = Request(dict(request.scope))
self.owner_scope = owner_scope
- self.submit_job = submit
- self.get_job = get
- self.cancel_job = cancel
+ self.finalize = finalize
self.sources: SourceFileStore = request.app.state.source_store
self.registry: ResourceRegistry = request.app.state.registry
self.pool: WorkerPool = request.app.state.worker_pool
- self._input_pins = ExitStack()
+ self._pins = ExitStack()
+ self._owned_files: list[str] = []
+
+ async def validate(self, options: UploadTaskOptions, manifest: list[TaskManifestItem]) -> None:
+ """能力预检不推进轮询游标,也不为尚未上传的任务预占 worker。"""
+ tiers = self.pool.available_tiers()
+ options.tier = resolve_task_tier(options, manifest, tiers, select_default_quality_tier(tiers))
+ lightweight = [is_flash_only_parse_extension(item.filename) for item in manifest]
+ selection_tier = "flash" if all(lightweight) and options.tier not in tiers else options.tier
+ candidates = self.pool.capable_workers(
+ tier=selection_tier,
+ required_sources={"file_id"},
+ required_outputs=set(options.output_formats),
+ require_flash=any(lightweight),
+ )
+ if not candidates:
+ _raise_api_error(
+ 503, error_type="api_error", code="quality_tier_unavailable", message="No worker supports requested formats"
+ )
- def release_uploads(self) -> None:
- """关闭预检阶段持有的输入引用,传输或校验失败也会释放。"""
- self._input_pins.close()
+ # 沿用 worker 的认证边界;只读检查不推进调度游标,也不预占解析容量。
+ worker = candidates[0]
+ _checked_json(await _worker_request(self.pool, worker, "GET", "/v1/files?limit=1", request=self.request))
async def find_upload(self, sha256sum: str, filename: str) -> TaskUpload | None:
- """只复用本调用方在 Router 中仍持有的源字节。"""
+ """仅复用当前调用方持有的 Router 源字节,worker 哈希命中不能替代本地缓存。"""
stored = self.sources.find_hash(self.owner_scope, sha256sum)
if stored is None:
return None
- self._input_pins.enter_context(self.sources.pin(stored))
+ self._pins.enter_context(self.sources.pin(stored))
return TaskUpload(stored.path, filename, stored.bytes, stored.sha256sum, stored.mime_type)
- async def submit(self, body: CreateJobRequest, uploads: dict[int, TaskUpload]) -> dict[str, Any]:
- """委托共享提交服务,源字节传输也纳入相同的负载预占。"""
- return _response_data(await self.submit_job(body.model_dump(exclude_none=True), self.request, uploads))
-
- async def get(self, task_id: str) -> dict[str, Any]:
- """使用既有查询服务更新终态、输出映射和副本回收。"""
- return _response_data(await self.get_job(task_id, self.request))
-
- async def cancel(self, task_id: str) -> dict[str, Any]:
- """使用既有取消入口,返回完整公共任务状态。"""
- _response_data(await self.cancel_job(task_id, self.request))
- return await self.get(task_id)
-
- async def wait(self, task_id: str, timeout: float) -> dict[str, Any]:
- """每秒查询所属 worker,预算包含查询时间且不取消远端任务。"""
- deadline = time.monotonic() + timeout
- while True:
- remaining = deadline - time.monotonic()
- if remaining <= 0:
- route = self.registry.find("job", task_id)
- if route is None or route.owner_scope != self.owner_scope:
- raise RouterProxyError(404, "job_not_found", f"Job {task_id} not found")
- return dict(route.metadata["payload"])
- try:
- payload = await asyncio.wait_for(self.get(task_id), timeout=remaining)
- except asyncio.TimeoutError:
- route = self.registry.find("job", task_id)
- if route is None or route.owner_scope != self.owner_scope:
- raise RouterProxyError(404, "job_not_found", f"Job {task_id} not found")
- return dict(route.metadata["payload"])
- if payload["status"] in TERMINAL_TASK_STATUSES:
- return payload
- await asyncio.sleep(min(1, max(0, deadline - time.monotonic())))
-
- async def read_output(self, file_id: str) -> bytes:
- """解析公共 File 路由并沿用上游产物下载边界。"""
- route = self.registry.find("file", file_id)
- if route is None or route.owner_scope != self.owner_scope:
- raise RouterProxyError(404, "file_not_found", f"File {file_id} not found")
- response = await request_upstream(
- self.pool,
- self.pool.get(route.worker_id),
- "GET",
- f"/v1/files/{route.upstream_id}/content",
- request=self.request,
- follow_redirects=True,
+ async def retain_upload(self, upload: TaskUpload) -> TaskUpload:
+ """为已校验文件建立准备引用,同一调用方相同内容复用现有暂存字节。"""
+ async with self.request.app.state.task_store.storage_lock:
+ private_id = "task-source-" + secrets.token_hex(12)
+ self._owned_files.append(private_id)
+ stored = self.sources.find_hash(self.owner_scope, upload.sha256sum)
+ if stored is None:
+ staging_id = "task-" + secrets.token_hex(12)
+ try:
+ stored = await self.sources.stage_upload(staging_id, file_chunks(upload.path), mime_type=upload.mime_type)
+ self.sources.bind_file(staging_id, private_id, owner_scope=self.owner_scope)
+ finally:
+ self.sources.discard_upload(staging_id)
+ else:
+ self.sources.bind_source(private_id, stored, owner_scope=self.owner_scope)
+ self._pins.enter_context(self.sources.pin(stored))
+ return replace(upload, path=stored.path, file_id=None)
+
+ def release_uploads(self, *, rollback: bool) -> None:
+ """关闭准备引用;成功提交后公开 File 绑定继续持有可复用源字节。"""
+ for file_id in self._owned_files:
+ self.sources.delete_file(file_id)
+ self._owned_files.clear()
+ self._pins.close()
+
+ async def submit(
+ self, task_id: str, options: UploadTaskOptions, manifest: list[TaskManifestItem], uploads: dict[int, TaskUpload]
+ ) -> TaskExecution:
+ """预占后提交 worker 任务,只向 worker 上传它实际缺失的文件。"""
+ lightweight = all(is_flash_only_parse_extension(item.filename) for item in manifest)
+ tier = "flash" if lightweight and options.tier not in self.pool.available_tiers() else options.tier
+ reservation = self.pool.reserve_job(
+ tier=tier,
+ required_sources={"file_id"},
+ required_outputs=set(options.output_formats),
+ require_flash=any(is_flash_only_parse_extension(item.filename) for item in manifest),
)
- if response.status_code >= 400:
- _response_data(Response(response.content, status_code=response.status_code))
- return response.content
+ if reservation is None:
+ _raise_api_error(
+ 503, error_type="api_error", code="quality_tier_unavailable", message="No capable worker is available"
+ )
+ worker = reservation.worker
+ upstream_id: str | None = None
+ route: ResourceRoute | None = None
+ registered_inputs: list[str] = []
+ transferred = False
+ try:
+ worker_manifest = [
+ {**item.model_dump(), "sha256sum": uploads[index].sha256sum} for index, item in enumerate(manifest)
+ ]
+ form = [("manifest", json.dumps(worker_manifest)), ("tier", options.tier), ("ocr_mode", options.ocr_mode)]
+ form.extend(("output_formats", value) for value in options.output_formats)
+ response = await _worker_request(
+ self.pool,
+ worker,
+ "POST",
+ "/v1/tasks",
+ request=self.request,
+ content=urlencode(form).encode(),
+ headers={"content-type": "application/x-www-form-urlencoded"},
+ )
+ require_worker_generation(worker, reservation.generation)
+ payload = TaskStatusResponse.model_validate(_checked_json(response)).model_dump()
+ upstream_id = payload["task_id"]
+ route = self.registry.register(
+ "job",
+ owner_scope=self.owner_scope,
+ worker_id=worker.worker_id,
+ upstream_id=upstream_id,
+ public_id=task_id,
+ )
+ authorization = self.request.headers.get("authorization")
+ route.metadata.update(
+ task_protocol=True,
+ active_counted=True,
+ reservation=reservation,
+ upstream_headers={"authorization": authorization} if authorization else {},
+ payload={"job_id": task_id, "status": "queued", "files": []},
+ )
+ by_client_id = {item.client_file_id: index for index, item in enumerate(manifest)}
+ for link in payload["uploads"]:
+ index = by_client_id.get(link["client_file_id"])
+ if index is None or link["upload_method"] != "PUT":
+ _raise_api_error(
+ 502, error_type="api_error", code="invalid_upstream_response", message="Unexpected worker upload"
+ )
+ path = _worker_path(worker, link["upload_url"])
+ expected_path = f"/v1/tasks/{quote(upstream_id, safe='')}/uploads/{quote(link['client_file_id'], safe='')}"
+ if path != expected_path:
+ _raise_api_error(
+ 502, error_type="api_error", code="invalid_upstream_response", message="Invalid worker upload path"
+ )
+ response = await _worker_request(
+ self.pool,
+ worker,
+ "PUT",
+ path,
+ request=self.request,
+ content=file_chunks(uploads[index].path),
+ headers={**link["upload_headers"], "content-length": str(uploads[index].bytes)},
+ )
+ if response.status_code >= 400:
+ _checked_json(response)
+ require_worker_generation(worker, reservation.generation)
+ # 上传就绪即可获取源 File 引用,后台 Job 尚未启动也不影响缓存交接。
+ response = await _worker_request(self.pool, worker, "GET", f"/v1/tasks/{upstream_id}", request=self.request)
+ require_worker_generation(worker, reservation.generation)
+ ready = TaskStatusResponse.model_validate(_checked_json(response)).model_dump()
+ if len(ready["files"]) != len(manifest) or ready["status"] == "waiting_upload":
+ _raise_api_error(
+ 502, error_type="api_error", code="invalid_upstream_response", message="Worker inputs are not ready"
+ )
+ aliases: dict[str, str] = {}
+ for index, item in enumerate(ready["files"]):
+ upstream_file_id = item.get("file_id")
+ if not isinstance(upstream_file_id, str) or item["client_file_id"] != manifest[index].client_file_id:
+ _raise_api_error(
+ 502, error_type="api_error", code="invalid_upstream_response", message="Missing worker source File"
+ )
+ upload = uploads[index]
+ rewritten = rewrite_file_payload(
+ {
+ "id": upstream_file_id,
+ "object": "file",
+ "filename": upload.filename,
+ "bytes": upload.bytes,
+ "sha256sum": upload.sha256sum,
+ "purpose": "parse",
+ "created_at": int(time.time()),
+ "expires_at": None,
+ },
+ worker,
+ self.registry,
+ self.owner_scope,
+ )
+ public_id = rewritten["id"]
+ registered_inputs.append(public_id)
+ self.sources.bind_source(
+ public_id,
+ StoredSourceFile(upload.path, upload.bytes, upload.sha256sum, upload.mime_type),
+ owner_scope=self.owner_scope,
+ )
+ aliases[upstream_file_id] = public_id
+ route.metadata["input_aliases"] = aliases
+ result = await self.get(task_id)
+ transferred = True
+ return result
+ finally:
+ if not transferred:
+ if upstream_id is not None and worker.generation == reservation.generation and worker.base_url:
+ await drain_future(asyncio.create_task(self._cancel_remote(worker, upstream_id)))
+ if route is not None:
+ release_job_load(route, self.pool)
+ route.metadata.update(
+ payload={"job_id": task_id, "status": "failed", "files": []}, finalized_at=utc_now_iso()
+ )
+ route.metadata.pop("upstream_headers", None)
+ else:
+ reservation.release()
+ for public_id in registered_inputs:
+ self.registry.remove("file", public_id)
+ self.sources.delete_file(public_id)
+
+ async def _cancel_remote(self, worker: WorkerState, upstream_id: str) -> None:
+ """尽力取消已经创建的 worker 任务,清理失败不覆盖最初的提交错误。"""
+ try:
+ await _worker_request(self.pool, worker, "DELETE", f"/v1/tasks/{upstream_id}", request=self.request)
+ except Exception:
+ # worker 已不可达或被替换时,原始错误及任务保留策略仍负责后续诊断。
+ return
+
+ def _route(self, task_id: str) -> ResourceRoute:
+ """检查本调用方的公共执行映射,不能用其他调用方的任务探测 worker。"""
+ route = self.registry.find("job", task_id)
+ if route is None or route.owner_scope != self.owner_scope:
+ _raise_api_error(
+ 404, error_type="invalid_request_error", code="task_not_found", message=f"Task {task_id} not found"
+ )
+ return route
+
+ async def get(self, task_id: str) -> TaskExecution:
+ """只查询 worker 元数据并登记结果引用,ZIP 字节走已有 Files 流式代理。"""
+ route = self._route(task_id)
+ execution = await read_task_execution(route, self.pool, self.registry, request=self.request)
+ await self.finalize(route, execution.job, self.request)
+ return execution
+
+ async def cancel(self, task_id: str) -> None:
+ """通过 worker tasks 取消准备或执行,成功后沿用一次性负载释放。"""
+ route = self._route(task_id)
+ if route.metadata.get("upstream_lost"):
+ release_job_load(route, self.pool)
+ return
+ worker = self.pool.get(route.worker_id)
+ response = await _worker_request(self.pool, worker, "DELETE", f"/v1/tasks/{route.upstream_id}", request=self.request)
+ if response.status_code not in {404, 409}:
+ _checked_json(response)
+ execution = await self.get(task_id)
+ if execution.job["status"] in TERMINAL_TASK_STATUSES:
+ release_job_load(route, self.pool)
def install_task_error_handlers(app: FastAPI) -> None:
- """让共享任务输入错误与直接 API server 使用相同的 V1 envelope。"""
+ """让共享任务输入和后台代理错误使用与 API server 相同的 V1 envelope。"""
@app.exception_handler(ApiServerError)
async def task_error(_request: Request, exc: ApiServerError) -> JSONResponse:
@@ -135,10 +472,11 @@ def install_task_error_handlers(app: FastAPI) -> None:
@app.exception_handler(RequestValidationError)
async def validation_error(_request: Request, exc: RequestValidationError) -> JSONResponse:
- """将路由查询参数校验错误统一转换为 400。"""
+ """把路径及表单校验错误统一转换成 400。"""
return JSONResponse(
- {"error": {"type": "invalid_request_error", "code": "invalid_request", "message": str(exc)}}, status_code=400
+ {"error": {"type": "invalid_request_error", "code": "invalid_request", "message": str(exc)}},
+ status_code=400,
)
-__all__ = ["RouterTaskBackend", "install_task_error_handlers"]
+__all__ = ["RouterTaskBackend", "install_task_error_handlers", "read_task_execution"]
diff --git a/mineru/kit/router/workers.py b/mineru/kit/router/workers.py
index 98ad26b5..d26381f0 100644
--- a/mineru/kit/router/workers.py
+++ b/mineru/kit/router/workers.py
@@ -523,15 +523,9 @@ class WorkerPool:
selection_kind: Literal["upload", "job"] = "job",
) -> WorkerState | None:
"""按能力和负载选取目标,文件归属仅在最低负载候选中优先。"""
- required = required_sources or set()
- eligible = [
- worker
- for worker in self.healthy_workers()
- if (tier is None or tier in worker.tiers)
- and required.issubset(set(worker.features.get("sources") or []))
- and (required_outputs or set()).issubset(set(worker.features.get("output_formats") or []))
- and (not require_flash or "flash" in worker.tiers)
- ]
+ eligible = self.capable_workers(
+ tier=tier, required_sources=required_sources, required_outputs=required_outputs, require_flash=require_flash
+ )
if not eligible:
return None
loads = {
@@ -550,6 +544,24 @@ class WorkerPool:
self._selection_cursors[selection_kind] = selected.worker_id
return selected
+ def capable_workers(
+ self,
+ *,
+ tier: Tier | None,
+ required_sources: set[str] | None = None,
+ required_outputs: set[str] | None = None,
+ require_flash: bool = False,
+ ) -> list[WorkerState]:
+ """只读过滤完整能力组合,供预检复用;不改变轮询游标或预占负载。"""
+ return [
+ worker
+ for worker in self.healthy_workers()
+ if (tier is None or tier in worker.tiers)
+ and (required_sources or set()).issubset(set(worker.features.get("sources") or []))
+ and (required_outputs or set()).issubset(set(worker.features.get("output_formats") or []))
+ and (not require_flash or "flash" in worker.tiers)
+ ]
+
def reserve_job(
self,
*,
diff --git a/mineru/parser/api_server.py b/mineru/parser/api_server.py
index 34d7155c..71e9e857 100644
--- a/mineru/parser/api_server.py
+++ b/mineru/parser/api_server.py
@@ -30,17 +30,18 @@ import click
import httpx
import uvicorn
from docvortex.assets import validate_image_sidecar_path
-from fastapi import APIRouter, Body, Depends, FastAPI, HTTPException, Path, Query, Request, Response, status
+from fastapi import APIRouter, Depends, FastAPI, HTTPException, Path, Query, Request, Response, status
from fastapi.exceptions import RequestValidationError
from fastapi.openapi.docs import get_redoc_html, get_swagger_ui_html, get_swagger_ui_oauth2_redirect_html
from fastapi_offline import FastAPIOffline
from fastapi.middleware.gzip import GZipMiddleware
-from fastapi.responses import JSONResponse
+from fastapi.responses import FileResponse, JSONResponse
from fastapi.security import HTTPBearer
from filelock import FileLock, Timeout as FileLockTimeout
from ..utils.retention import resolve_retention_seconds, RETENTION_SCAN_INTERVAL_SECONDS
from pydantic import BaseModel, ConfigDict, Field
from starlette.datastructures import State
+from starlette.types import Receive, Scope, Send
from ..config import VlmConfig
from ..config import config as mineru_config
@@ -83,7 +84,7 @@ from .writer import DataWriter
_DEFAULT_API_SERVER_TIER: ServerTier = "standard"
_MAX_INLINE_BYTES_DEFAULT = 1024 * 1024
_MAX_FILES_PER_JOB_DEFAULT = 100
-_MAX_FILE_SIZE_BYTES_DEFAULT = 209715200
+_MAX_URL_BYTES_DEFAULT = 209715200
_LOCAL_PARSE_OUTPUT_FORMATS: tuple[OutputFormat, ...] = (
"markdown",
"middle_json",
@@ -601,8 +602,8 @@ class UsageCurrent(BaseModel):
class UsageLimits(BaseModel):
model_config = _PYDANTIC_CONFIG
- max_pages_per_file: int = 1000
- max_file_size_bytes: int = _MAX_FILE_SIZE_BYTES_DEFAULT
+ max_pages_per_file: int | None = None
+ max_file_size_bytes: int | None = None
max_files_per_job: int = _MAX_FILES_PER_JOB_DEFAULT
max_concurrent_jobs: int = 1
max_file_retention_days: int | None = None
@@ -634,6 +635,7 @@ class _UploadRecord:
sha256sum: str | None = None
status: UploadStatus = "pending"
file_id: str | None = None # set on complete
+ write_lock: asyncio.Lock = field(default_factory=asyncio.Lock)
@dataclass
@@ -802,7 +804,9 @@ class FileStore:
finally:
temporary.unlink(missing_ok=True)
- def register_source_file(self, filename: str, path: pathlib.Path, sha256sum: str, file_id: str | None = None) -> str:
+ def register_source_file(
+ self, filename: str, path: pathlib.Path, sha256sum: str, file_id: str | None = None, *, keep_alive: bool = False
+ ) -> str:
"""从已校验的暂存文件原子注册源字节及独立的文件名视图。"""
with self._lock:
target = self._blob_abs(sha256sum)
@@ -823,10 +827,99 @@ class FileStore:
created_at=now,
purpose="parse",
sha256sum=sha256sum,
- expires_at=now + self.retention_seconds if self.retention_seconds else None,
+ expires_at=now + self.retention_seconds if self.retention_seconds and not keep_alive else None,
)
return file_id
+ def finalize_source_views(self, file_ids: list[str]) -> None:
+ """准备完成后恢复源文件视图的正常保留期,执行所需字节另由 Job 租约保护。"""
+ with self._lock:
+ expires_at = int(time.time()) + self.retention_seconds if self.retention_seconds else None
+ for file_id in file_ids:
+ record = self._files.get(file_id)
+ if record is not None:
+ record.expires_at = expires_at
+
+ def create_file_for_output_path(self, filename: str, path: pathlib.Path, *, job_id: str) -> str:
+ """从已完成的文件流式登记产物,避免批量 ZIP 再次整体载入内存。"""
+ hasher = hashlib.sha256()
+ with path.open("rb") as source:
+ while chunk := source.read(1024 * 1024):
+ hasher.update(chunk)
+ sha = hasher.hexdigest()
+ with self._lock:
+ file_id = self.register_source_file(filename, path, sha)
+ record = self._files[file_id]
+ record.purpose = "parse_output"
+ record.job_id = job_id
+ record.expires_at = None
+ pins = self._job_output_pins.setdefault(job_id, set())
+ if sha not in pins:
+ pins.add(sha)
+ self._pins[sha] = self._pins.get(sha, 0) + 1
+ return file_id
+
+ def pin_output_file(self, file_id: str) -> tuple[pathlib.Path, str, str]:
+ """检查产物权限并取得下载租约,防止传输途中被保留策略删除。"""
+ with self._lock:
+ rec = self.get_file(file_id)
+ if rec.purpose != "parse_output":
+ _raise_api_error(
+ 403,
+ error_type="permission_error",
+ code="feature_requires_api_key",
+ message="Source files cannot be downloaded",
+ )
+ if rec.sha256sum is None or not self._blob_abs(rec.sha256sum).is_file():
+ _raise_api_error(404, error_type="invalid_request_error", code="file_not_found", message="Output expired")
+ self._pins[rec.sha256sum] = self._pins.get(rec.sha256sum, 0) + 1
+ return self._blob_abs(rec.sha256sum), rec.filename, rec.sha256sum
+
+ async def store_upload_stream(self, upload_id: str, chunks: AsyncIterator[bytes]) -> None:
+ """逐块接收独立 Upload,校验完整大小后才原子替换暂存文件。"""
+ rec = self.get_upload(upload_id)
+ async with rec.write_lock:
+ rec = self.get_upload(upload_id)
+ if rec.status != "pending":
+ _raise_api_error(
+ 409, error_type="invalid_request_error", code="upload_already_terminal", message=f"Upload is {rec.status}"
+ )
+ directory = self._blobs / "_uploads"
+ directory.mkdir(parents=True, exist_ok=True)
+ temporary = directory / f"{upload_id}.{secrets.token_hex(8)}"
+ size = 0
+ try:
+ with temporary.open("wb") as target:
+ async for chunk in chunks:
+ size += len(chunk)
+ if size > rec.bytes:
+ _raise_api_error(
+ 413,
+ error_type="invalid_request_error",
+ code="upload_size_mismatch",
+ message=f"Upload expects {rec.bytes} bytes, received more",
+ )
+ await run_sync(target.write, chunk)
+ with self._lock:
+ current = self.get_upload(upload_id)
+ if current.status != "pending":
+ _raise_api_error(
+ 409,
+ error_type="invalid_request_error",
+ code="upload_already_terminal",
+ message=f"Upload is {current.status}",
+ )
+ if size != current.bytes:
+ _raise_api_error(
+ 413,
+ error_type="invalid_request_error",
+ code="upload_size_mismatch",
+ message=f"Upload expects {current.bytes} bytes, received {size}",
+ )
+ os.replace(temporary, directory / upload_id)
+ finally:
+ temporary.unlink(missing_ok=True)
+
def read_blob(self, sha256hex: str) -> bytes:
with self._lock:
p = self._blob_abs(sha256hex)
@@ -907,18 +1000,6 @@ class FileStore:
)
return rec
- def _read_upload_data(self, upload_id: str) -> bytes:
- with self._lock:
- p = self._blobs / "_uploads" / upload_id
- if not p.is_file():
- _raise_api_error(
- 409,
- error_type="invalid_request_error",
- code="upload_not_ready",
- message="Upload bytes not yet received",
- )
- return p.read_bytes()
-
def complete_upload(self, upload_id: str, sha256hex: str | None) -> UploadResponse:
with self._lock:
rec = self.get_upload(upload_id)
@@ -937,16 +1018,25 @@ class FileStore:
message=f"Upload is {rec.status}",
)
- # compute sha256 from uploaded data if not provided
- data = self._read_upload_data(upload_id)
- if len(data) != rec.bytes:
+ # 流式复核已上传内容,不在完成阶段把大文件整体读入内存。
+ staged = self._blobs / "_uploads" / upload_id
+ if not staged.is_file():
+ _raise_api_error(
+ 409, error_type="invalid_request_error", code="upload_not_ready", message="No uploaded content"
+ )
+ actual_size = staged.stat().st_size
+ if actual_size != rec.bytes:
_raise_api_error(
413,
error_type="invalid_request_error",
code="upload_size_mismatch",
- message=f"Upload expects {rec.bytes} bytes, received {len(data)}",
+ message=f"Upload expects {rec.bytes} bytes, received {actual_size}",
)
- actual_sha = hashlib.sha256(data).hexdigest()
+ hasher = hashlib.sha256()
+ with staged.open("rb") as source:
+ while chunk := source.read(1024 * 1024):
+ hasher.update(chunk)
+ actual_sha = hasher.hexdigest()
if sha256hex and sha256hex != actual_sha:
_raise_api_error(
@@ -966,7 +1056,9 @@ class FileStore:
# move from upload blob to content-addressed blob
sha = sha256hex or actual_sha
if not self.blob_exists(sha):
- self.store_blob(data, sha256hex=sha)
+ destination = self._blob_abs(sha)
+ destination.parent.mkdir(parents=True, exist_ok=True)
+ os.replace(staged, destination)
# remove temp upload blob
(self._blobs / "_uploads" / upload_id).unlink(missing_ok=True)
@@ -1284,6 +1376,8 @@ class _JobRecord:
input_blobs: dict[str, str] = field(default_factory=dict)
file_store: FileStore | None = None
usage_counted: bool = False
+ task_result_file_id: str | None = None
+ task_error: ErrorDetail | None = None
def __post_init__(self) -> None:
if self.files is None:
@@ -1412,10 +1506,13 @@ class JobStore:
def _now() -> str:
return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
- def create(self, req: CreateJobRequest, file_store: FileStore) -> _JobRecord:
+ def create(self, req: CreateJobRequest, file_store: FileStore, *, job_id: str | None = None) -> _JobRecord:
+ """创建唯一执行记录,允许 tasks 使用上传准备阶段预先分配的 ID。"""
if req.tier is None:
raise ValueError("CreateJobRequest.tier must be resolved before job creation")
- job_id = self._new_job_id()
+ job_id = job_id or self._new_job_id()
+ if job_id in self._jobs:
+ _raise_api_error(409, error_type="invalid_request_error", code="job_already_exists", message="Job already exists")
now = self._now()
rec = _JobRecord(
id=job_id,
@@ -1636,7 +1733,7 @@ async def _extract_bytes(
allow_local_source: bool = False,
max_inline_bytes: int = _MAX_INLINE_BYTES_DEFAULT,
allow_http_source: bool = False,
- max_url_bytes: int = _MAX_FILE_SIZE_BYTES_DEFAULT,
+ max_url_bytes: int = _MAX_URL_BYTES_DEFAULT,
input_blobs: dict[str, str] | None = None,
) -> _ExtractedSource:
"""按既有来源策略读取字节,并保留不会由临时文件替代的来源上下文。"""
@@ -1697,7 +1794,7 @@ async def _run_job(
allow_local_source: bool = False,
max_inline_bytes: int = _MAX_INLINE_BYTES_DEFAULT,
allow_http_source: bool = False,
- max_url_bytes: int = _MAX_FILE_SIZE_BYTES_DEFAULT,
+ max_url_bytes: int = _MAX_URL_BYTES_DEFAULT,
flash_enabled: bool = True,
vlm_config: VlmConfig | None = None,
job_store: JobStore | None = None,
@@ -1855,7 +1952,7 @@ _router = APIRouter(prefix="/v1")
# OpenAPI tag metadata: drives the group order and descriptions on /docs.
_OPENAPI_TAGS: list[dict[str, str]] = [
- {"name": "Tasks", "description": "One-request parsing, asynchronous tasks and inline or ZIP results."},
+ {"name": "Tasks", "description": "Form submissions, per-file uploads and asynchronous ZIP download links."},
{"name": "Health", "description": "Liveness and server readiness."},
{"name": "Tiers", "description": "Parsing tiers and runtime capability advertised by this server."},
{"name": "Models", "description": "VLM models available for parsing."},
@@ -1868,8 +1965,9 @@ _OPENAPI_TAGS: list[dict[str, str]] = [
_FASTAPI_DESCRIPTION = """\
Parse documents into structured Middle JSON via self-hosted or remote capacity.
-Use `/v1/file_parse` for a synchronous result or `/v1/tasks` for a one-request
-asynchronous submission. Both share the existing parse job lifecycle.
+Submit a form manifest to `/v1/tasks`, upload only missing files to their returned
+URLs, then poll the task and download its `result_url`. Local servers also accept
+one multipart file. Task status contains metadata only, never inline result bytes.
The resource workflow remains: create an upload, complete it, submit a parse job for the
resulting file, then poll the job and fetch its outputs. Health and usage
endpoints report server readiness and quota state. Tiers (`flash`, `basic`,
@@ -2028,14 +2126,20 @@ async def get_upload(
status_code=status.HTTP_200_OK,
responses={**_ERR_404, **_ERR_409, **_ERR_413},
tags=["Uploads"],
+ openapi_extra={
+ "requestBody": {
+ "required": True,
+ "content": {"application/octet-stream": {"schema": {"type": "string", "format": "binary"}}},
+ }
+ },
)
async def upload_content(
+ request: Request,
upload_id: str = Path(description="Upload ID"),
- data: bytes = Body(media_type="application/octet-stream"),
store: FileStore = Depends(_get_store),
) -> Response:
- """Upload raw bytes for an upload (OpenAI-compatible)."""
- store.store_upload_data(upload_id, data)
+ """流式接收原始文件字节,保持独立 Upload 的既有 HTTP 协议。"""
+ await store.store_upload_stream(upload_id, request.stream())
return Response(status_code=200)
@@ -2052,7 +2156,7 @@ async def complete_upload(
store: FileStore = Depends(_get_store),
) -> UploadResponse:
"""Complete an upload, creating the File object."""
- return store.complete_upload(upload_id, body.sha256sum if body else None)
+ return await run_sync(store.complete_upload, upload_id, body.sha256sum if body else None)
@_router.post(
@@ -2105,6 +2209,32 @@ async def get_file(
return store._make_file_object(store.get_file(file_id))
+class _OutputFileResponse(FileResponse):
+ """把文件租约绑定到 ASGI 响应,正常结束和断连都释放引用。"""
+
+ def __init__(self, store: FileStore, file_id: str) -> None:
+ """在响应头发送之前完成权限检查,并固定实际文件路径。"""
+ path, filename, sha = store.pin_output_file(file_id)
+ self._store = store
+ self._sha = sha
+ try:
+ super().__init__(
+ path,
+ filename=filename,
+ media_type="application/zip" if filename.lower().endswith(".zip") else "application/octet-stream",
+ )
+ except BaseException:
+ store.unpin_cached_blob(sha)
+ raise
+
+ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
+ """让文件响应负责分块和 Range,同时确保取消不会泄漏租约。"""
+ try:
+ await super().__call__(scope, receive, send)
+ finally:
+ self._store.unpin_cached_blob(self._sha)
+
+
@_router.get(
"/files/{file_id}/content",
response_model=None,
@@ -2121,9 +2251,8 @@ async def get_file_content(
file_id: str = Path(description="File ID"),
store: FileStore = Depends(_get_store),
) -> Response:
- """Download parse-output content."""
- data = store.read_file_data(file_id)
- return Response(content=data, media_type="application/octet-stream")
+ """直接流式发送已保存的产物,下载期间持有文件租约。"""
+ return _OutputFileResponse(store, file_id)
@_router.delete(
@@ -2151,6 +2280,9 @@ async def submit_parse_job(
file_store: FileStore,
job_store: JobStore,
access_level: AccessLevel,
+ *,
+ job_id: str | None = None,
+ finalize: Callable[[_JobRecord], Awaitable[None]] | None = None,
) -> _JobRecord:
"""统一校验并提交后台解析任务,供 V1 Job 与便捷入口共同调用。"""
for index, entry in enumerate(body.files):
@@ -2233,7 +2365,7 @@ async def submit_parse_job(
if job_store._closing:
_raise_api_error(503, error_type="engine_error", code="server_shutting_down", message="Server is shutting down")
- rec = job_store.create(body, file_store)
+ rec = job_store.create(body, file_store, job_id=job_id)
url_timeout_val: int = request.app.state.url_timeout
allow_local_source_val: bool = request.app.state.allow_local_source
max_inline_bytes_val: int = request.app.state.max_inline_bytes
@@ -2259,6 +2391,8 @@ async def submit_parse_job(
vlm_config=vlm_config_val,
job_store=job_store,
)
+ if finalize is not None and rec.status in {"completed", "partial"}:
+ await finalize(rec)
try:
job_store.start_task(rec, _bg_run)
@@ -2558,7 +2692,7 @@ def create_app(
url_timeout: int = 60,
allow_local_source: bool = False,
max_inline_bytes: int = _MAX_INLINE_BYTES_DEFAULT,
- max_url_bytes: int = _MAX_FILE_SIZE_BYTES_DEFAULT,
+ max_url_bytes: int = _MAX_URL_BYTES_DEFAULT,
allow_http_source: bool = False,
api_key: str | None = None,
image_analysis: bool = True,
@@ -2650,6 +2784,7 @@ def create_app(
job_store: JobStore = application.state.job_store
file_store: FileStore = application.state.file_store
file_store.claim_directory()
+ application.state.task_store.start()
collection_task: asyncio.Task[None] | None = None
async def collect_loop() -> None:
@@ -2694,6 +2829,7 @@ def create_app(
collection_task.cancel()
await asyncio.gather(collection_task, return_exceptions=True)
try:
+ await application.state.task_store.shutdown()
await job_store.shutdown()
finally:
file_store.release_directory()
@@ -2839,8 +2975,9 @@ def create_app(
application.middleware("http")(_auth_middleware)
application.include_router(_build_v1_router())
- from .task_api import ApiTaskBackend, build_task_router
+ from .task_api import ApiTaskBackend, TaskStore, build_task_router
+ application.state.task_store = TaskStore(retention_seconds)
application.include_router(build_task_router(ApiTaskBackend))
return application
@@ -2931,9 +3068,9 @@ def _build_server_log_config(log_level: str) -> dict[str, Any]:
)
@click.option(
"--max-url-bytes",
- default=_MAX_FILE_SIZE_BYTES_DEFAULT,
+ default=_MAX_URL_BYTES_DEFAULT,
type=int,
- help=f"Maximum bytes downloaded for url sources (default: {_MAX_FILE_SIZE_BYTES_DEFAULT})",
+ help=f"Maximum bytes downloaded for url sources (default: {_MAX_URL_BYTES_DEFAULT})",
)
@click.option(
"--allow-http-source",
diff --git a/mineru/parser/task_api.py b/mineru/parser/task_api.py
index 1a8630f1..798f3bd7 100644
--- a/mineru/parser/task_api.py
+++ b/mineru/parser/task_api.py
@@ -1,123 +1,183 @@
-"""两类 V1 服务共用的便捷任务输入、结果和同步等待接口。"""
+"""本地服务与 Router 共用的表单任务、逐文件上传和结果链接协议。"""
from __future__ import annotations
+import asyncio
import copy
import hashlib
-import io
import json
+import logging
+import secrets
+import shutil
import tempfile
+import time
import zipfile
from collections.abc import AsyncIterator, Callable
-from dataclasses import dataclass
+from dataclasses import dataclass, field, replace
+from datetime import datetime
from pathlib import Path
from typing import Any, Literal, NoReturn, Protocol
+from urllib.parse import quote
-from fastapi import APIRouter, Query, Request, Response
+from fastapi import APIRouter, Request, Response
from fastapi.responses import JSONResponse
from pydantic import BaseModel, ConfigDict, Field, ValidationError
from starlette.datastructures import UploadFile
from starlette.exceptions import HTTPException as StarletteHTTPException
+from starlette.requests import ClientDisconnect
from ..errors import MineruError
-from ..utils.async_utils import run_sync
+from ..filetypes import is_flash_only_parse_extension
+from ..types import Tier
+from ..utils.async_utils import drain_future, run_sync
from .api_server import (
AccessLevel,
+ ApiServerError,
CreateJobRequest,
+ ErrorDetail,
FileIdSource,
+ FileParseInfo,
FileStore,
- JobAsyncResponse,
JobFileEntry,
- JobFileResult,
+ JobProgress,
JobStore,
+ OutputFiles,
+ _JobRecord,
_raise_api_error,
+ _require_model_preload_ready,
submit_parse_job,
)
from .page_range import normalize_page_range_input
-MAX_TASK_FILE_BYTES = 200 * 1024 * 1024
MAX_TASK_FILES = 100
+TASK_UPLOAD_TTL = 3600
TERMINAL_TASK_STATUSES = frozenset({"completed", "partial", "failed", "canceled"})
-ResponseFormat = Literal["json", "zip"]
+TaskStatus = Literal["waiting_upload", "queued", "running", "completed", "partial", "failed", "canceled"]
+logger = logging.getLogger(__name__)
+
+
+class TaskManifestItem(BaseModel):
+ """按客户端标识关联独立上传,不依赖文件名唯一性。"""
+
+ model_config = ConfigDict(extra="forbid")
+ client_file_id: str = Field(pattern=r"^[A-Za-z0-9_-]{1,64}$")
+ filename: str = Field(min_length=1, max_length=1024)
+ bytes: int = Field(gt=0, strict=True)
+ sha256sum: str | None = Field(default=None, pattern=r"^[a-f0-9]{64}$")
+ page_range: str | None = None
+
+
+class UploadTaskOptions(BaseModel):
+ """解析选项仅来自表单,文件元数据独立保存在 manifest 中。"""
+
+ model_config = ConfigDict(extra="forbid")
+ tier: Tier | None = None
+ ocr_mode: Literal["auto", "txt", "ocr"] = "auto"
+ page_range: str = ""
+ output_formats: list[Literal["markdown", "middle_json", "structured_content", "zip"]] = Field(
+ default_factory=lambda: ["markdown"], min_length=1
+ )
+
+
+class TaskUploadLink(BaseModel):
+ """描述一个文件的上传目标,客户端原样使用服务端给出的地址和请求头。"""
+
+ client_file_id: str
+ upload_url: str
+ upload_method: Literal["PUT"] = "PUT"
+ upload_headers: dict[str, str]
+ expires_at: int
+
+
+class TaskFileStatus(TaskManifestItem):
+ """同时提供上传准备情况与逐文件解析状态,禁止内联解析正文。"""
+
+ upload_status: Literal["pending", "ready"]
+ file_id: str | None = None
+ name: str
+ status: Literal["waiting_upload", "queued", "running", "completed", "failed", "canceled"]
+ parse: FileParseInfo | None = None
+ output_files: OutputFiles | None = None
+ error: ErrorDetail | None = None
+
+
+class TaskStatusResponse(BaseModel):
+ """任务状态只携带元数据;最终 ZIP 由独立下载链接提供。"""
+
+ task_id: str
+ status: TaskStatus
+ status_url: str
+ result_url: str | None = None
+ created_at: str
+ started_at: str | None = None
+ finished_at: str | None = None
+ tier: Tier | None = None
+ output_formats: list[str]
+ progress: JobProgress
+ files: list[TaskFileStatus]
+ uploads: list[TaskUploadLink] = Field(default_factory=list)
+ error: ErrorDetail | None = None
@dataclass(frozen=True)
class TaskUpload:
- """表示已校验的输入字节,文件名视图独立于共享缓存路径。"""
+ """保存已校验的源字节位置,文件名视图独立于内容去重路径。"""
path: Path
filename: str
bytes: int
sha256sum: str
mime_type: str = "application/octet-stream"
+ file_id: str | None = None
+
+
+@dataclass(frozen=True)
+class TaskExecution:
+ """在后台适配器之间传递执行快照及本部署的 ZIP File 标识。"""
+
+ job: dict[str, Any]
+ result_file_id: str | None = None
+ error: ErrorDetail | None = None
class TaskBackend(Protocol):
- """便捷接口只依赖显式任务和文件操作,不维护独立队列。"""
+ """上传准备复用各部署的存储,执行仍交给已有 Job 服务。"""
- def release_uploads(self) -> None:
- """释放请求预检取得的输入租约,包括校验失败和取消路径。"""
+ owner_scope: str
+
+ async def validate(self, options: UploadTaskOptions, manifest: list[TaskManifestItem]) -> None:
+ """在接单之前校验部署能力,不能预占解析名额。"""
...
async def find_upload(self, sha256sum: str, filename: str) -> TaskUpload | None:
- """查找当前调用方可复用的源字节。"""
+ """原子查找并固定当前调用方可以复用的源文件。"""
...
- async def submit(self, body: CreateJobRequest, uploads: dict[int, TaskUpload]) -> dict[str, Any]:
- """接收源字节并通过既有任务服务提交。"""
+ async def retain_upload(self, upload: TaskUpload) -> TaskUpload:
+ """持久保存已校验的单个输入,并持有跨请求准备阶段的引用。"""
...
- async def get(self, task_id: str) -> dict[str, Any]:
- """查询既有任务,返回标准 Job 数据。"""
+ def release_uploads(self, *, rollback: bool) -> None:
+ """提交后交接输入引用;未提交的取消或失败同时清理文件视图。"""
...
- async def cancel(self, task_id: str) -> dict[str, Any]:
- """取消既有任务而不影响其他任务。"""
+ async def submit(
+ self, task_id: str, options: UploadTaskOptions, manifest: list[TaskManifestItem], uploads: dict[int, TaskUpload]
+ ) -> TaskExecution:
+ """使用预先分配的公开 ID 提交一次后台解析。"""
...
- async def wait(self, task_id: str, timeout: float) -> dict[str, Any]:
- """有界等待,等待方超时不能取消后台任务。"""
+ async def get(self, task_id: str) -> TaskExecution:
+ """只查询执行和产物元数据,不读取 ZIP 内容。"""
...
- async def read_output(self, file_id: str) -> bytes:
- """通过当前服务的授权边界读取产物。"""
+ async def cancel(self, task_id: str) -> None:
+ """取消对应后台工作,并收敛已有资源和预占。"""
...
-class TaskStatusResponse(JobAsyncResponse):
- """沿用 Job 字段,序列化为 task_id 并增加 V1 查询地址。"""
-
- job_id: str = Field(alias="task_id")
- status_url: str
- result_url: str
-
-
-class TaskFileContent(JobFileResult):
- """内联文本产物,同时保留既有文件状态、错误和资源引用。"""
-
- content: dict[str, Any] = Field(default_factory=dict)
-
-
-class TaskResultResponse(TaskStatusResponse):
- """描述可直接消费的 JSON 解析结果。"""
-
- files: list[TaskFileContent]
-
-
-class UploadTaskOptions(BaseModel):
- """上传解析参数仅来自查询串,保证哈希命中时无需读取表单。"""
-
- model_config = ConfigDict(extra="forbid")
- tier: Literal["flash", "basic", "standard", "advanced"] | None = None
- ocr_mode: Literal["auto", "txt", "ocr"] = "auto"
- page_range: str = ""
- output_formats: list[str] = Field(default_factory=lambda: ["markdown"])
- filename: str | None = Field(default=None, min_length=1)
- sha256sum: str | None = Field(default=None, pattern=r"^[a-f0-9]{64}$")
-
-
def _invalid(message: str, *, code: str = "invalid_request", status_code: int = 400, param: str | None = None) -> NoReturn:
- """将输入和产物错误转换为两端一致的 V1 错误结构。"""
+ """把协议校验错误转换成两类服务共用的 V1 error envelope。"""
_raise_api_error(
status_code,
error_type="api_error" if status_code >= 500 else "invalid_request_error",
@@ -127,402 +187,743 @@ def _invalid(message: str, *, code: str = "invalid_request", status_code: int =
)
-def task_payload(job: dict[str, Any]) -> dict[str, Any]:
- """重写任务名称与链接,保留上游语义树和公共资源标识。"""
- payload = copy.deepcopy(job)
- task_id = str(payload.pop("job_id"))
- base = f"/v1/tasks/{task_id}"
- payload.update(task_id=task_id, status_url=base, result_url=f"{base}/result", links={"self": base, "cancel": base})
- return payload
-
-
-async def _save_upload(chunks: AsyncIterator[bytes], path: Path, filename: str, mime_type: str) -> TaskUpload:
- """逐块写入并计算实际哈希,超过大小限制立即终止。"""
- hasher = hashlib.sha256()
- size = 0
- with path.open("wb") as target:
- async for chunk in chunks:
- size += len(chunk)
- if size > MAX_TASK_FILE_BYTES:
- _invalid("File exceeds 200 MiB", code="file_too_large", status_code=413)
- target.write(chunk)
- hasher.update(chunk)
- if not size:
- _invalid("Empty files are not supported", param="files")
- return TaskUpload(path, filename, size, hasher.hexdigest(), mime_type)
-
-
-async def _file_chunks(file: UploadFile) -> AsyncIterator[bytes]:
- """限制单次读取大小,不把 multipart 文件整体放入内存。"""
- while chunk := await file.read(1024 * 1024):
+def resolve_task_tier(
+ options: UploadTaskOptions, manifest: list[TaskManifestItem], tiers: set[Tier], default: Tier | None
+) -> Tier:
+ """按现有轻量格式回退规则解析 tier,不触发 worker 选择或模型执行。"""
+ lightweight = [is_flash_only_parse_extension(item.filename) for item in manifest]
+ if any(lightweight) and "flash" not in tiers:
+ _invalid("Flash parsing is disabled, but an input requires it", param="manifest")
+ tier = options.tier or default
+ if tier is None and all(lightweight) and "flash" in tiers:
+ tier = "flash"
+ if tier is None:
+ _invalid("No default quality tier is available; pass tier explicitly", code="quality_tier_unavailable", status_code=503)
+ if tier not in tiers and not (all(lightweight) and "flash" in tiers):
+ _invalid(f"Tier '{tier}' is not available", param="tier")
+ return tier
+
+
+async def file_chunks(path: Path) -> AsyncIterator[bytes]:
+ """以固定大小从磁盘读取,避免阻塞事件循环和完整文件缓冲。"""
+ with path.open("rb") as source:
+ while chunk := await run_sync(source.read, 1024 * 1024):
+ yield chunk
+
+
+async def _upload_chunks(upload: UploadFile) -> AsyncIterator[bytes]:
+ """分块读取已经由表单解析器暂存的单个直传文件。"""
+ while chunk := await upload.read(1024 * 1024):
yield chunk
-async def _prepare_submission(
- request: Request,
- backend: TaskBackend,
- directory: Path,
+async def _save_upload(
+ chunks: AsyncIterator[bytes],
+ path: Path,
+ filename: str,
+ mime_type: str,
*,
- sync: bool,
- force_zip: bool,
-) -> tuple[CreateJobRequest, dict[int, TaskUpload], bool]:
- """统一处理 JSON、表单和原始字节,命中时完全不读取请求主体。"""
+ expected: TaskManifestItem | None = None,
+ canceled: Callable[[], bool] | None = None,
+) -> TaskUpload:
+ """流式落盘并校验完整性;声明大小用于一致性检查,不是上传大小上限。"""
+ hasher = hashlib.sha256()
+ size = 0
+ try:
+ with path.open("wb") as target:
+ async for chunk in chunks:
+ if canceled is not None and canceled():
+ _invalid("Task was canceled during upload", status_code=409, code="task_already_terminal")
+ size += len(chunk)
+ if expected is not None and size > expected.bytes:
+ _invalid("Declared size does not match uploaded bytes", code="upload_size_mismatch")
+ await run_sync(target.write, chunk)
+ hasher.update(chunk)
+ if size == 0:
+ _invalid("Empty files are not supported", param="files")
+ if expected is not None and size != expected.bytes:
+ _invalid("Declared size does not match uploaded bytes", code="upload_size_mismatch")
+ sha = hasher.hexdigest()
+ if expected is not None and expected.sha256sum is not None and sha != expected.sha256sum:
+ _invalid("SHA-256 mismatch", code="file_hash_mismatch")
+ return TaskUpload(path, filename, size, sha, mime_type)
+ except BaseException:
+ path.unlink(missing_ok=True)
+ raise
+
+
+async def _read_submission(
+ request: Request, directory: Path
+) -> tuple[UploadTaskOptions, list[TaskManifestItem], TaskUpload | None]:
+ """解析表单清单或单文件直传,旧 JSON、原始字节及 URL 业务参数明确拒绝。"""
+ if request.query_params:
+ _invalid("POST parameters must be supplied in the form body, not the URL")
media_type = request.headers.get("content-type", "").split(";", 1)[0].strip().lower()
- params = dict(request.query_params)
- if sync:
- params.pop("response_format", None)
- params.pop("wait_timeout", None)
- uploads: dict[int, TaskUpload] = {}
- skipped = False
+ if media_type not in {"application/x-www-form-urlencoded", "multipart/form-data"}:
+ _invalid("Use application/x-www-form-urlencoded or multipart/form-data", status_code=415)
try:
- if media_type == "application/json":
- if params:
- _invalid("JSON parse options must be supplied in the request body")
- body = CreateJobRequest.model_validate(await request.json())
- else:
- if "output_formats" in params:
- params["output_formats"] = request.query_params.getlist("output_formats")
+ async with request.form(max_files=1, max_fields=32) as form:
+ for key in form:
+ if key not in {"output_formats", "files"} and len(form.getlist(key)) != 1:
+ _invalid(f"Duplicate form field: {key}", param=key)
+ params = {key: form[key] for key in form if key not in {"manifest", "files", "output_formats"}}
+ if "output_formats" in form:
+ params["output_formats"] = form.getlist("output_formats")
options = UploadTaskOptions.model_validate(params)
options.page_range = normalize_page_range_input(options.page_range)
- if not options.output_formats or any(
- fmt not in {"markdown", "middle_json", "structured_content", "zip"} for fmt in options.output_formats
- ):
- _invalid("Unsupported output format", code="unsupported_output_format", param="output_formats")
- if media_type == "application/octet-stream":
- if options.filename is None:
- _invalid("filename is required for raw uploads", param="filename")
- size_header = request.headers.get("content-length")
- if size_header is None:
- _invalid("Content-Length is required for raw uploads", status_code=411)
- declared_size = int(size_header)
- if declared_size <= 0 or declared_size > MAX_TASK_FILE_BYTES:
- _invalid("Invalid raw file size", code="file_too_large", status_code=413)
- cached = await backend.find_upload(options.sha256sum, options.filename) if options.sha256sum else None
- if cached is not None:
- if cached.bytes != declared_size:
- _invalid("Declared size does not match cached bytes", code="upload_size_mismatch")
- uploads[0] = cached
- skipped = True
- else:
- upload = await _save_upload(request.stream(), directory / "0", options.filename, media_type)
- if upload.bytes != declared_size:
- _invalid("Declared size does not match uploaded bytes", code="upload_size_mismatch")
- if options.sha256sum and upload.sha256sum != options.sha256sum:
- _invalid("SHA-256 mismatch", code="file_hash_mismatch")
- uploads[0] = upload
- elif media_type == "multipart/form-data":
- if options.filename is not None or options.sha256sum is not None:
- _invalid("filename and sha256sum are only supported for raw uploads")
- async with request.form(max_files=MAX_TASK_FILES, max_fields=0) as form:
- files = form.getlist("files")
- if not files or any(key != "files" for key in form):
- _invalid("Supply one or more files fields", param="files")
- for index, file in enumerate(files):
- if not isinstance(file, UploadFile) or not file.filename:
- _invalid("Every files field must contain a named file", param="files")
- if file.size is not None and file.size > MAX_TASK_FILE_BYTES:
- _invalid("File exceeds 200 MiB", code="file_too_large", status_code=413)
- uploads[index] = await _save_upload(
- _file_chunks(file),
- directory / str(index),
- file.filename,
- file.content_type or "application/octet-stream",
- )
- else:
- _invalid("Use application/json, multipart/form-data or application/octet-stream", status_code=415)
- body = CreateJobRequest(
- files=[
- JobFileEntry(source=FileIdSource(file_id=f"upload-{index}"), page_range=options.page_range or None)
- for index in uploads
- ],
- tier=options.tier,
- ocr_mode=options.ocr_mode,
- output_formats=options.output_formats,
- )
- for entry in body.files:
- entry.page_range = normalize_page_range_input(entry.page_range) or None
- if body.callback is not None:
- _invalid("Webhook callbacks are not supported by this service", param="callback")
- if any(fmt not in {"markdown", "middle_json", "structured_content", "zip"} for fmt in body.output_formats):
- _invalid("Unsupported output format", code="unsupported_output_format", param="output_formats")
- if force_zip and "zip" not in body.output_formats:
- body.output_formats.append("zip")
- return body, uploads, skipped
+ options.output_formats = list(dict.fromkeys([*options.output_formats, "zip"]))
+ manifest: list[TaskManifestItem] = []
+ if "manifest" in form:
+ raw = form["manifest"]
+ if not isinstance(raw, str):
+ _invalid("manifest must be a JSON text field", param="manifest")
+ values = json.loads(raw)
+ if not isinstance(values, list) or not 1 <= len(values) <= MAX_TASK_FILES:
+ _invalid("manifest must contain between 1 and 100 files", param="manifest")
+ manifest = [TaskManifestItem.model_validate(item) for item in values]
+ if len({item.client_file_id for item in manifest}) != len(manifest):
+ _invalid("client_file_id must be unique within a task", param="manifest")
+ files = form.getlist("files")
+ direct: TaskUpload | None = None
+ if files:
+ if len(files) != 1 or (manifest and len(manifest) != 1):
+ _invalid("Multipart direct upload supports one file; submit a manifest for multiple files", param="files")
+ file = files[0]
+ if not isinstance(file, UploadFile) or not file.filename:
+ _invalid("files must contain one named file", param="files")
+ filename = manifest[0].filename if manifest else file.filename
+ direct = await _save_upload(
+ _upload_chunks(file),
+ directory / "direct",
+ filename,
+ file.content_type or "application/octet-stream",
+ expected=manifest[0] if manifest else None,
+ )
+ if not manifest:
+ manifest = [TaskManifestItem(client_file_id="f1", filename=filename, bytes=direct.bytes)]
+ if not manifest:
+ _invalid("Supply manifest or one files field", param="manifest")
+ for item in manifest:
+ item.page_range = normalize_page_range_input(
+ item.page_range if item.page_range is not None else options.page_range
+ )
+ return options, manifest, direct
except StarletteHTTPException as exc:
_invalid(str(exc.detail), status_code=exc.status_code)
- raise AssertionError("unreachable") from exc
+ except ClientDisconnect:
+ _invalid("Upload interrupted; retry the request", code="upload_interrupted")
except MineruError as exc:
_invalid(str(exc), code=exc.code, param=exc.param)
- raise AssertionError("unreachable") from exc
except (ValidationError, ValueError) as exc:
_invalid(str(exc))
- raise AssertionError("unreachable") from exc
-
-
-async def build_task_result(job: dict[str, Any], backend: TaskBackend, response_format: ResponseFormat) -> Response:
- """只读取既有产物并共享结果封装,禁止为了下载而重新解析。"""
- payload = task_payload(job)
- status = str(job["status"])
- if status not in TERMINAL_TASK_STATUSES:
- return JSONResponse(payload, status_code=202)
- if status in {"failed", "canceled"}:
- return JSONResponse(payload, status_code=409)
- if response_format == "zip":
- if "zip" not in job.get("output_formats", []):
- _invalid("Request zip in output_formats when submitting the task", code="unsupported_output_format")
- archives: list[tuple[int, bytes]] = []
- for index, file in enumerate(job.get("files", [])):
- if file.get("status") == "completed":
- ref = (file.get("output_files") or {}).get("zip")
- if not ref:
- _invalid("ZIP output is missing", status_code=502, code="invalid_response")
- archives.append((index, await backend.read_output(ref["file_id"])))
- if len(job["files"]) == 1:
- data = archives[0][1]
- else:
- data = await run_sync(_combine_archives, archives, payload)
- return Response(
- data,
- media_type="application/zip",
- headers={
- "Content-Disposition": f'attachment; filename="{payload["task_id"]}.zip"',
- "X-MinerU-Task-Id": payload["task_id"],
- "X-MinerU-Task-Status": status,
- },
+
+
+@dataclass
+class _TaskRecord:
+ """只保存上传准备与执行映射;解析并发仍由既有 JobStore 管理。"""
+
+ id: str
+ backend: TaskBackend
+ options: UploadTaskOptions
+ manifest: list[TaskManifestItem]
+ directory: Path
+ expires_at: int
+ created_at: str = field(default_factory=JobStore._now)
+ status: TaskStatus = "waiting_upload"
+ uploads: dict[int, TaskUpload] = field(default_factory=dict)
+ upload_locks: dict[int, asyncio.Lock] = field(default_factory=dict)
+ refresh_lock: asyncio.Lock = field(default_factory=asyncio.Lock)
+ execution: TaskExecution | None = None
+ operation: asyncio.Task[None] | None = None
+ submitted: bool = False
+ active_uploads: int = 0
+ finished_at: str | None = None
+ finished_epoch: float | None = None
+ error: ErrorDetail | None = None
+
+
+class TaskStore:
+ """管理跨请求上传租约、稳定 ID 和提交一次语义,不建立第二个解析队列。"""
+
+ def __init__(self, retention_seconds: int) -> None:
+ """在应用创建时准备私有暂存目录,不在模块导入阶段产生副作用。"""
+ self.retention_seconds = retention_seconds
+ self._temporary = tempfile.TemporaryDirectory(prefix="mineru-tasks-")
+ self._root = Path(self._temporary.name)
+ self._records: dict[str, _TaskRecord] = {}
+ self.storage_lock = asyncio.Lock()
+ self._collector: asyncio.Task[None] | None = None
+ self._closing = False
+
+ def start(self) -> None:
+ """启动独立的准备记录回收,关闭产物保留策略时也能清理过期上传。"""
+ if self._collector is None and not self._closing:
+ self._collector = asyncio.create_task(self._collect_loop(), name="mineru-task-retention")
+
+ async def _collect_loop(self) -> None:
+ """定期回收等待上传的孤立任务和超过保留期的终态快照。"""
+ while True:
+ await asyncio.sleep(60)
+ self.collect_expired()
+
+ def _release(self, record: _TaskRecord, *, rollback: bool) -> None:
+ """没有在途写入时释放准备引用,避免取消与落盘并发导致路径提前消失。"""
+ if record.active_uploads:
+ return
+ record.backend.release_uploads(rollback=rollback)
+ shutil.rmtree(record.directory, ignore_errors=True)
+
+ def _finish(self, record: _TaskRecord, status: TaskStatus, error: ErrorDetail | None = None) -> None:
+ """统一记录终态时间,错误、过期和取消采用同一保留边界。"""
+ record.status = status
+ record.error = error
+ record.finished_at = JobStore._now()
+ record.finished_epoch = time.time()
+
+ def collect_expired(self) -> None:
+ """等待上传到期时释放缓存租约;活动写入与后台执行不被中途回收。"""
+ now = time.time()
+ for task_id, record in tuple(self._records.items()):
+ if record.status == "waiting_upload" and record.expires_at <= now and not record.active_uploads:
+ self._finish(
+ record, "failed", ErrorDetail(type="invalid_request_error", code="upload_expired", message="Upload expired")
+ )
+ self._release(record, rollback=True)
+ if (
+ self.retention_seconds
+ and record.finished_epoch is not None
+ and record.finished_epoch + self.retention_seconds <= now
+ and not record.active_uploads
+ and (record.operation is None or record.operation.done())
+ ):
+ self._release(record, rollback=not record.submitted)
+ self._records.pop(task_id, None)
+
+ def lookup(self, task_id: str, owner_scope: str) -> _TaskRecord:
+ """只有当前调用方可以读写任务,未知 ID 与越权 ID 使用同一错误。"""
+ self.collect_expired()
+ record = self._records.get(task_id)
+ if record is None or record.backend.owner_scope != owner_scope:
+ _invalid(f"Task {task_id} not found", status_code=404, code="task_not_found")
+ return record
+
+ async def create(
+ self, backend: TaskBackend, options: UploadTaskOptions, manifest: list[TaskManifestItem], direct: TaskUpload | None
+ ) -> _TaskRecord:
+ """校验并固定已命中源文件;只有全部就绪才提交后台执行。"""
+ if self._closing:
+ _invalid("Server is shutting down", status_code=503, code="server_shutting_down")
+ await backend.validate(options, manifest)
+ task_id = JobStore._new_job_id()
+ record = _TaskRecord(task_id, backend, options, manifest, self._root / task_id, int(time.time()) + TASK_UPLOAD_TTL)
+ try:
+ for index, item in enumerate(manifest):
+ upload = (
+ direct
+ if direct is not None
+ else (await backend.find_upload(item.sha256sum, item.filename) if item.sha256sum else None)
+ )
+ if upload is not None:
+ if upload.bytes != item.bytes:
+ _invalid("Declared size does not match cached bytes", code="upload_size_mismatch")
+ record.uploads[index] = await backend.retain_upload(upload)
+ self._records[task_id] = record
+ self.start()
+ self._maybe_start(record)
+ return record
+ except BaseException:
+ backend.release_uploads(rollback=True)
+ raise
+
+ def _maybe_start(self, record: _TaskRecord) -> None:
+ """事件循环内原子切换准备状态,最后多个上传并发完成也只创建一个执行句柄。"""
+ if record.status == "waiting_upload" and len(record.uploads) == len(record.manifest):
+ record.status = "queued"
+ record.operation = asyncio.create_task(self._dispatch(record), name=f"mineru-task-{record.id}")
+
+ def operation_finished(operation: asyncio.Task[None]) -> None:
+ """覆盖首次调度前取消,且让取消后的保留期从准备引用清理完成时开始。"""
+ if record.status == "canceled":
+ self._finish(record, "canceled")
+ self._release(record, rollback=not record.submitted)
+ if not operation.cancelled() and operation.exception() is not None:
+ error = operation.exception()
+ logger.error("Task cleanup failed: %s", record.id, exc_info=(type(error), error, error.__traceback__))
+
+ record.operation.add_done_callback(operation_finished)
+
+ def _apply_execution(self, record: _TaskRecord, execution: TaskExecution) -> None:
+ """更新已发布的执行快照,不能用迟到响应覆盖取消或失败终态。"""
+ if record.status in TERMINAL_TASK_STATUSES:
+ return
+ status = execution.job.get("status")
+ if status not in {"queued", "running", *TERMINAL_TASK_STATUSES}:
+ _invalid("Invalid task status from execution backend", code="invalid_response", status_code=502)
+ if status in {"completed", "partial"} and execution.result_file_id is None:
+ _invalid("Completed task has no ZIP file", code="invalid_response", status_code=502)
+ record.execution = execution
+ record.status = status
+ if status in TERMINAL_TASK_STATUSES:
+ self._finish(record, status, execution.error)
+ record.finished_at = execution.job.get("finished_at") or record.finished_at
+ if record.finished_at is not None:
+ record.finished_epoch = datetime.fromisoformat(record.finished_at.replace("Z", "+00:00")).timestamp()
+
+ async def refresh(self, record: _TaskRecord) -> None:
+ """状态刷新只查询元数据;串行化并发查询,防止旧快照覆盖新状态。"""
+ async with record.refresh_lock:
+ if record.submitted and record.status not in TERMINAL_TASK_STATUSES:
+ self._apply_execution(record, await record.backend.get(record.id))
+
+ async def _dispatch(self, record: _TaskRecord) -> None:
+ """提交与监控由应用持有,HTTP 断连不取消已经接受的任务。"""
+ try:
+ execution = await record.backend.submit(record.id, record.options, record.manifest, record.uploads)
+ record.submitted = True
+ self._apply_execution(record, execution)
+ self._release(record, rollback=False)
+ while record.status not in TERMINAL_TASK_STATUSES:
+ await asyncio.sleep(1)
+ try:
+ await self.refresh(record)
+ except ApiServerError as exc:
+ if exc.status_code not in {408, 429, 500, 502, 503, 504} or exc.error.code in {
+ "invalid_response",
+ "invalid_upstream_response",
+ }:
+ raise
+ logger.warning("Task status refresh failed: %s: %s", record.id, exc.error.code)
+ except asyncio.CancelledError:
+ if record.submitted and record.status not in {"completed", "partial", "failed"}:
+ try:
+ await drain_future(asyncio.create_task(record.backend.cancel(record.id)))
+ except Exception:
+ logger.exception("Task cancellation cleanup failed: %s", record.id)
+ if record.status not in TERMINAL_TASK_STATUSES:
+ self._finish(record, "canceled")
+ except Exception as exc:
+ error = (
+ exc.error
+ if isinstance(exc, ApiServerError)
+ else ErrorDetail(type="api_error", code="task_submission_failed", message=str(exc))
+ )
+ if record.status not in TERMINAL_TASK_STATUSES:
+ self._finish(record, "failed", error)
+ if record.submitted:
+ try:
+ await drain_future(asyncio.create_task(record.backend.cancel(record.id)))
+ except Exception:
+ logger.exception("Failed task cleanup could not reach execution backend: %s", record.id)
+ logger.exception("Task execution failed: %s", record.id)
+ finally:
+ self._release(record, rollback=not record.submitted)
+
+ async def upload(self, record: _TaskRecord, client_file_id: str, request: Request) -> bool:
+ """独立接收一个文件;返回是否跳过主体,供 HTTP/1.1 正确关闭连接。"""
+ index = next((index for index, item in enumerate(record.manifest) if item.client_file_id == client_file_id), None)
+ if index is None:
+ _invalid("Unknown client_file_id", status_code=404, code="upload_not_found")
+ lock = record.upload_locks.setdefault(index, asyncio.Lock())
+ async with lock:
+ if record.status in {"failed", "canceled"}:
+ _invalid("Task no longer accepts uploads", status_code=409, code="task_already_terminal")
+ if index in record.uploads:
+ return True
+ if record.status != "waiting_upload" or record.expires_at <= time.time():
+ _invalid("Task no longer accepts uploads", status_code=409, code="task_already_terminal")
+ expected = record.manifest[index]
+ length = request.headers.get("content-length")
+ if length is not None:
+ try:
+ declared = int(length)
+ except ValueError:
+ _invalid("Invalid Content-Length", code="upload_size_mismatch")
+ if declared != expected.bytes:
+ _invalid("Content-Length does not match manifest bytes", code="upload_size_mismatch")
+ record.active_uploads += 1
+ record.directory.mkdir(parents=True, exist_ok=True)
+ path = record.directory / secrets.token_hex(16)
+
+ def was_canceled() -> bool:
+ """每次接收数据时检查取消状态,避免继续写入已取消任务的剩余主体。"""
+ return record.status != "waiting_upload"
+
+ try:
+ upload = await _save_upload(
+ request.stream(),
+ path,
+ expected.filename,
+ request.headers.get("content-type", "application/octet-stream"),
+ expected=expected,
+ canceled=was_canceled,
+ )
+ if record.status != "waiting_upload":
+ _invalid("Task was canceled during upload", status_code=409, code="task_already_terminal")
+ retained = await record.backend.retain_upload(upload)
+ if record.status != "waiting_upload":
+ _invalid("Task was canceled during upload", status_code=409, code="task_already_terminal")
+ record.uploads[index] = retained
+ self._maybe_start(record)
+ return False
+ except ClientDisconnect:
+ _invalid("Upload interrupted; retry this file on the same task", code="upload_interrupted")
+ finally:
+ path.unlink(missing_ok=True)
+ record.active_uploads -= 1
+ if record.status in TERMINAL_TASK_STATUSES:
+ self._release(record, rollback=not record.submitted)
+ if record.status == "canceled" and not record.active_uploads:
+ self._finish(record, "canceled")
+
+ async def cancel(self, record: _TaskRecord, *, wait: bool = True) -> None:
+ """取消准备或执行阶段,后台清理结束之前不删除仍在使用的源文件。"""
+ if record.status in TERMINAL_TASK_STATUSES:
+ _invalid(f"Task is {record.status}", status_code=409, code="task_already_terminal")
+ self._finish(record, "canceled")
+ if record.operation is not None and not record.operation.done():
+ record.operation.cancel()
+ if not wait:
+ return
+ await drain_future(asyncio.gather(record.operation, return_exceptions=True))
+ self._finish(record, "canceled")
+ self._release(record, rollback=not record.submitted)
+
+ async def shutdown(self) -> None:
+ """关闭时先停止提交和监控,再释放所有准备阶段引用与暂存目录。"""
+ self._closing = True
+ if self._collector is not None:
+ self._collector.cancel()
+ await asyncio.gather(self._collector, return_exceptions=True)
+ for record in tuple(self._records.values()):
+ if record.status not in TERMINAL_TASK_STATUSES:
+ await self.cancel(record)
+ elif record.operation is not None and not record.operation.done():
+ record.operation.cancel()
+ await drain_future(asyncio.gather(record.operation, return_exceptions=True))
+ self._release(record, rollback=not record.submitted)
+ self._temporary.cleanup()
+
+
+def _url(request: Request, path: str) -> str:
+ """生成包含反向代理 root_path 的本部署地址,客户端无需自行拼接路径。"""
+ return str(request.base_url).rstrip("/") + path
+
+
+def task_payload(record: _TaskRecord, request: Request) -> dict[str, Any]:
+ """将任务准备记录与执行元数据合并,不读取任何解析产物字节。"""
+ job = record.execution.job if record.execution is not None else {}
+ results = job.get("files") or []
+ files: list[dict[str, Any]] = []
+ links: list[dict[str, Any]] = []
+ for index, item in enumerate(record.manifest):
+ upload = record.uploads.get(index)
+ file = item.model_dump()
+ file.update(
+ name=item.filename,
+ upload_status="ready" if upload is not None else "pending",
+ status="queued" if upload else "waiting_upload",
+ file_id=upload.file_id if upload else None,
)
- for file in payload["files"]:
- file["content"] = {}
- if file.get("status") != "completed":
- continue
- for fmt in job.get("output_formats", []):
- if fmt in {"markdown", "middle_json", "structured_content"} and not (file.get("output_files") or {}).get(fmt):
- _invalid(f"{fmt} output is missing", status_code=502, code="invalid_response")
- for fmt, ref in (file.get("output_files") or {}).items():
- if ref and fmt in {"markdown", "middle_json", "structured_content"}:
- data = await backend.read_output(ref["file_id"])
- file["content"][fmt] = data.decode("utf-8") if fmt == "markdown" else json.loads(data)
- return JSONResponse(payload)
-
-
-def _combine_archives(archives: list[tuple[int, bytes]], payload: dict[str, Any]) -> bytes:
- """按输入序号封装批量产物,拒绝源 ZIP 中的越界路径。"""
- buffer = io.BytesIO()
- with zipfile.ZipFile(buffer, "w", zipfile.ZIP_DEFLATED) as target:
- target.writestr("manifest.json", json.dumps(payload, ensure_ascii=False))
- for index, data in archives:
- with zipfile.ZipFile(io.BytesIO(data)) as source:
- for info in source.infolist():
- path = Path(info.filename)
- if path.is_absolute() or ".." in path.parts or "\\" in info.filename:
- _invalid("Invalid ZIP member path", status_code=502, code="invalid_response")
- target.writestr(f"{index + 1:04d}/{info.filename}", source.read(info))
- return buffer.getvalue()
+ if index < len(results):
+ file.update(results[index])
+ if record.status == "canceled" and file["status"] not in {"completed", "failed"}:
+ file["status"] = "canceled"
+ files.append(file)
+ if upload is None and record.status == "waiting_upload":
+ links.append(
+ {
+ "client_file_id": item.client_file_id,
+ "upload_url": _url(request, f"/v1/tasks/{record.id}/uploads/{quote(item.client_file_id, safe='')}"),
+ "upload_method": "PUT",
+ "upload_headers": {"Content-Type": "application/octet-stream"},
+ "expires_at": record.expires_at,
+ }
+ )
+ result_id = record.execution.result_file_id if record.execution is not None else None
+ payload = {
+ "task_id": record.id,
+ "status": record.status,
+ "status_url": _url(request, f"/v1/tasks/{record.id}"),
+ "result_url": _url(request, f"/v1/files/{quote(result_id, safe='')}/content")
+ if result_id and record.status in {"completed", "partial"}
+ else None,
+ "created_at": record.created_at,
+ "started_at": job.get("started_at"),
+ "finished_at": record.finished_at,
+ "tier": job.get("tier") or record.options.tier,
+ "output_formats": record.options.output_formats,
+ "progress": job.get("progress") or {"completed": 0, "failed": 0, "total": len(files)},
+ "files": files,
+ "uploads": links,
+ "error": record.error.model_dump() if record.error is not None else None,
+ }
+ return TaskStatusResponse.model_validate(payload).model_dump()
def _request_schema() -> dict[str, Any]:
- """展开模型引用,为手动读取主体的两端生成相同 OpenAPI 输入定义。"""
- schema = CreateJobRequest.model_json_schema()
- definitions = schema.pop("$defs", {})
-
- def expand(value: Any) -> Any:
- """展开当前请求模型的非递归定义,避免引用未注册的组件。"""
- if isinstance(value, dict):
- if "$ref" in value:
- return expand(definitions[value["$ref"].rsplit("/", 1)[-1]])
- if "discriminator" in value:
- value = dict(value)
- value["discriminator"] = {"propertyName": value["discriminator"]["propertyName"]}
- return {key: expand(item) for key, item in value.items()}
- if isinstance(value, list):
- return [expand(item) for item in value]
- return value
-
+ """明确记录表单字段和单文件约束,不再暴露查询参数或旧内容类型。"""
+ properties = UploadTaskOptions.model_json_schema()["properties"]
+ # 清单使用 JSON 文本表单字段,客户端无需发送 application/json 请求。
+ properties["manifest"] = {
+ "type": "string",
+ "description": "JSON array of 1-100 files: client_file_id, filename, bytes, optional sha256sum and page_range.",
+ "example": '[{"client_file_id":"f1","filename":"document.pdf","bytes":12345}]',
+ }
+ plain = {"type": "object", "required": ["manifest"], "additionalProperties": False, "properties": properties}
+ multipart = copy.deepcopy(plain)
+ multipart.pop("required")
+ multipart["anyOf"] = [{"required": ["manifest"]}, {"required": ["files"]}]
+ multipart["properties"]["files"] = {
+ "type": "array",
+ "minItems": 1,
+ "maxItems": 1,
+ "items": {"type": "string", "format": "binary"},
+ "description": "Local single-file direct upload only; a supplied manifest must also contain exactly one file.",
+ }
return {
"requestBody": {
"required": True,
"content": {
- "application/json": {"schema": expand(schema)},
- "multipart/form-data": {
- "schema": {
- "type": "object",
- "required": ["files"],
- "properties": {
- "files": {
- "type": "array",
- "maxItems": MAX_TASK_FILES,
- "items": {"type": "string", "format": "binary"},
- }
- },
- }
- },
- "application/octet-stream": {"schema": {"type": "string", "format": "binary"}},
+ "application/x-www-form-urlencoded": {"schema": plain},
+ "multipart/form-data": {"schema": multipart},
},
- },
- "parameters": [
- {"name": name, "in": "query", "required": False, "schema": value}
- for name, value in UploadTaskOptions.model_json_schema()["properties"].items()
- ]
- + [
- {
- "name": "Content-Length",
- "in": "header",
- "required": False,
- "description": "Required for application/octet-stream; must match actual file bytes.",
- "schema": {"type": "integer", "minimum": 1, "maximum": MAX_TASK_FILE_BYTES},
- }
- ],
+ }
}
def build_task_router(factory: Callable[[Request], TaskBackend]) -> APIRouter:
- """注册相同 V1 路由,后台实现由显式工厂选择。"""
+ """两类部署使用同一任务协议,下载交给已有 Files 入口。"""
router = APIRouter(prefix="/v1", tags=["Tasks"])
@router.post("/tasks", status_code=202, response_model=TaskStatusResponse, openapi_extra=_request_schema())
async def create_task(request: Request) -> Response:
- """提交任务后立即返回公共 ID,缓存命中时不读取请求主体。"""
+ """先验证表单再建立稳定任务 ID,HTTP 结束后后台工作独立继续。"""
backend = factory(request)
+ store: TaskStore = request.app.state.task_store
try:
- with tempfile.TemporaryDirectory(prefix="mineru-task-") as directory:
- body, uploads, skipped = await _prepare_submission(
- request, backend, Path(directory), sync=False, force_zip=False
- )
- job = await backend.submit(body, uploads)
- finally:
- backend.release_uploads()
- return JSONResponse(
- task_payload(job),
- status_code=202,
- headers={"Connection": "close"} if skipped and request.scope.get("http_version") == "1.1" else None,
- )
+ with tempfile.TemporaryDirectory(prefix="mineru-task-request-") as temporary:
+ options, manifest, direct = await _read_submission(request, Path(temporary))
+ record = await store.create(backend, options, manifest, direct)
+ except BaseException:
+ backend.release_uploads(rollback=True)
+ raise
+ return JSONResponse(task_payload(record, request), status_code=202)
@router.get("/tasks/{task_id}", response_model=TaskStatusResponse)
async def get_task(task_id: str, request: Request) -> Response:
- """查询与 V1 Job 共用的任务记录。"""
- return JSONResponse(task_payload(await factory(request).get(task_id)))
-
- @router.delete("/tasks/{task_id}")
- async def cancel_task(task_id: str, request: Request) -> Response:
- """通过后台已有取消机制取消任务。"""
- return JSONResponse(task_payload(await factory(request).cancel(task_id)))
-
- @router.get(
- "/tasks/{task_id}/result",
- response_model=None,
- responses={
- 200: {
- "model": TaskResultResponse,
- "content": {"application/zip": {"schema": {"type": "string", "format": "binary"}}},
- },
- 202: {"model": TaskStatusResponse},
- },
- )
- async def get_result(task_id: str, request: Request, response_format: ResponseFormat = "json") -> Response:
- """根据任务终态返回内联 JSON 或既有 ZIP 产物。"""
- backend = factory(request)
- return await build_task_result(await backend.get(task_id), backend, response_format)
-
- @router.post(
- "/file_parse",
- response_model=None,
- openapi_extra=_request_schema(),
- responses={
- 200: {
- "model": TaskResultResponse,
- "content": {"application/zip": {"schema": {"type": "string", "format": "binary"}}},
- },
- 202: {"model": TaskStatusResponse},
+ """读取上传准备与后台状态,成功时返回可直接下载的 ZIP 地址。"""
+ store: TaskStore = request.app.state.task_store
+ record = store.lookup(task_id, factory(request).owner_scope)
+ await store.refresh(record)
+ return JSONResponse(task_payload(record, request))
+
+ @router.put(
+ "/tasks/{task_id}/uploads/{client_file_id}",
+ response_model=TaskStatusResponse,
+ openapi_extra={
+ "requestBody": {
+ "required": True,
+ "content": {"application/octet-stream": {"schema": {"type": "string", "format": "binary"}}},
+ }
},
)
- async def file_parse(
- request: Request, response_format: ResponseFormat = "json", wait_timeout: int = Query(default=300, ge=1, le=3600)
- ) -> Response:
- """同步包装共享异步任务,等待超时不取消后台工作。"""
- backend = factory(request)
- try:
- with tempfile.TemporaryDirectory(prefix="mineru-task-") as directory:
- body, uploads, skipped = await _prepare_submission(
- request, backend, Path(directory), sync=True, force_zip=response_format == "zip"
- )
- job = await backend.submit(body, uploads)
- finally:
- backend.release_uploads()
- job = await backend.wait(job["job_id"], wait_timeout)
- response = await build_task_result(job, backend, response_format)
- if skipped and request.scope.get("http_version") == "1.1":
- response.headers["Connection"] = "close"
- return response
+ async def upload_task_file(task_id: str, client_file_id: str, request: Request) -> Response:
+ """每条上传链接只接受一个文件,最后一个文件就绪后自动提交。"""
+ store: TaskStore = request.app.state.task_store
+ record = store.lookup(task_id, factory(request).owner_scope)
+ skipped = await store.upload(record, client_file_id, request)
+ return JSONResponse(
+ task_payload(record, request),
+ headers={"Connection": "close"} if skipped and request.scope.get("http_version") == "1.1" else None,
+ )
+
+ @router.delete("/tasks/{task_id}", response_model=TaskStatusResponse)
+ async def cancel_task(task_id: str, request: Request) -> Response:
+ """统一取消等待上传与正在执行的任务,不重建后台作业。"""
+ store: TaskStore = request.app.state.task_store
+ record = store.lookup(task_id, factory(request).owner_scope)
+ await store.refresh(record)
+ await store.cancel(record, wait=False)
+ return JSONResponse(task_payload(record, request))
return router
+def _combine_archives(store: FileStore, job: _JobRecord, path: Path, manifest: list[TaskManifestItem], status: str) -> str:
+ """在后台流式构建批量 ZIP,固定输入顺序并拒绝越界成员路径。"""
+ snapshot = {
+ "status": status,
+ # ZIP 可独立消费;不把 worker 的私有 task/file ID 或短期下载地址写入产物。
+ "files": [
+ {
+ **item.model_dump(),
+ "name": result.name,
+ "page_range": result.page_range,
+ "status": result.status,
+ "directory": f"{index + 1:04d}/" if result.status == "completed" else None,
+ "parse": result.parse.model_dump() if result.parse is not None else None,
+ "error": result.error.model_dump() if result.error is not None else None,
+ }
+ for index, (item, result) in enumerate(zip(manifest, job.files))
+ ],
+ }
+ with zipfile.ZipFile(path, "w", zipfile.ZIP_DEFLATED, allowZip64=True) as target:
+ target.writestr("manifest.json", json.dumps(snapshot, ensure_ascii=False))
+ for index, file in enumerate(job.files):
+ if file.status != "completed":
+ continue
+ if file.output_files is None or file.output_files.zip is None:
+ raise ValueError("ZIP output is missing")
+ source_path, _, sha = store.pin_output_file(file.output_files.zip.file_id)
+ try:
+ with zipfile.ZipFile(source_path) as source:
+ for info in source.infolist():
+ member = Path(info.filename)
+ if member.is_absolute() or ".." in member.parts or "\\" in info.filename:
+ raise ValueError("Invalid ZIP member path")
+ name = f"{index + 1:04d}/{info.filename}"
+ if info.is_dir():
+ target.writestr(name, b"")
+ else:
+ with source.open(info) as incoming, target.open(name, "w", force_zip64=True) as outgoing:
+ shutil.copyfileobj(incoming, outgoing, length=1024 * 1024)
+ finally:
+ store.unpin_cached_blob(sha)
+ return store.create_file_for_output_path(f"{job.id}.zip", path, job_id=job.id)
+
+
class ApiTaskBackend:
- """把便捷接口适配到 API server 唯一的文件存储和 JobStore。"""
+ """把上传准备接入 API server 的唯一文件存储和 JobStore。"""
def __init__(self, request: Request) -> None:
- """保留已通过鉴权的请求及当前应用资源。"""
- self.request = request
+ """保留轻量请求上下文,避免跨请求持有已解析的表单和上传对象。"""
+ self.request = Request(dict(request.scope))
self.files: FileStore = request.app.state.file_store
self.jobs: JobStore = request.app.state.job_store
- self._cached_pins: list[str] = []
+ self.owner_scope = "local"
self.access: AccessLevel = "registered" if request.app.state.api_key else "anonymous"
+ self._pins: list[str] = []
+ self._owned_files: list[str] = []
- def release_uploads(self) -> None:
- """释放当前请求的哈希预检引用,失败和取消同样经过此处。"""
- for sha in self._cached_pins:
- self.files.unpin_cached_blob(sha)
- self._cached_pins.clear()
+ async def validate(self, options: UploadTaskOptions, manifest: list[TaskManifestItem]) -> None:
+ """复用引擎就绪状态,提前校验显式 tier 与轻量格式能力。"""
+ _require_model_preload_ready(self.request)
+ if self.jobs._closing:
+ _invalid("Server is shutting down", code="server_shutting_down", status_code=503)
+ state = self.request.app.state
+ options.tier = resolve_task_tier(options, manifest, set(state.tier_runtime_options), state.default_tier)
async def find_upload(self, sha256sum: str, filename: str) -> TaskUpload | None:
- """原子查找并持有可复用字节,直到提交或输入校验完成。"""
+ """原子查找并取得缓存租约,准备阶段不会因原文件视图到期丢失字节。"""
path = self.files.pin_cached_blob(sha256sum)
if path is None:
return None
- self._cached_pins.append(sha256sum)
+ self._pins.append(sha256sum)
return TaskUpload(path, filename, path.stat().st_size, sha256sum)
- async def submit(self, body: CreateJobRequest, uploads: dict[int, TaskUpload]) -> dict[str, Any]:
- """注册源字节后调用共享任务提交函数,失败时回滚文件视图。"""
- registered: list[str] = []
- try:
- for index, upload in uploads.items():
- file_id = self.files._new_file_id()
- registered.append(file_id)
- await run_sync(self.files.register_source_file, upload.filename, upload.path, upload.sha256sum, file_id)
- body.files[index].source = FileIdSource(file_id=file_id)
- rec = await submit_parse_job(body, self.request, self.files, self.jobs, self.access)
- return self.jobs.build_response(rec, access_level=self.access).model_dump(by_alias=True)
- except BaseException:
- for file_id in registered:
+ async def retain_upload(self, upload: TaskUpload) -> TaskUpload:
+ """立即按内容去重并登记独立文件视图,后续文件失败不丢弃已成功上传项。"""
+ file_id = self.files._new_file_id()
+ self._owned_files.append(file_id)
+ await run_sync(
+ self.files.register_source_file, upload.filename, upload.path, upload.sha256sum, file_id, keep_alive=True
+ )
+ path = self.files.pin_cached_blob(upload.sha256sum)
+ if path is None:
+ raise RuntimeError("New source file disappeared")
+ self._pins.append(upload.sha256sum)
+ return replace(upload, path=path, file_id=file_id)
+
+ def release_uploads(self, *, rollback: bool) -> None:
+ """成功提交后交接输入;准备失败时删除本任务视图但保留其他任务引用。"""
+ if rollback:
+ for file_id in self._owned_files:
if file_id in self.files._files:
self.files.delete_file(file_id)
- raise
-
- async def get(self, task_id: str) -> dict[str, Any]:
- """返回现有 Job 的规范数据。"""
- return self.jobs.build_response(self.jobs.get(task_id), access_level=self.access).model_dump(by_alias=True)
+ else:
+ self.files.finalize_source_views(self._owned_files)
+ self._owned_files.clear()
+ for sha in self._pins:
+ self.files.unpin_cached_blob(sha)
+ self._pins.clear()
+
+ async def submit(
+ self, task_id: str, options: UploadTaskOptions, manifest: list[TaskManifestItem], uploads: dict[int, TaskUpload]
+ ) -> TaskExecution:
+ """把已经校验的输入交给现有队列,在发布成功前完成最终 ZIP。"""
+ # 接单时已持有源字节;用户删除文件视图也不能破坏尚在等待其他文件的任务。
+ for upload in uploads.values():
+ await run_sync(
+ self.files.register_source_file, upload.filename, upload.path, upload.sha256sum, upload.file_id, keep_alive=True
+ )
+ body = CreateJobRequest(
+ files=[
+ JobFileEntry(source=FileIdSource(file_id=uploads[index].file_id), page_range=item.page_range or None)
+ for index, item in enumerate(manifest)
+ ],
+ tier=options.tier,
+ ocr_mode=options.ocr_mode,
+ output_formats=options.output_formats,
+ )
- async def cancel(self, task_id: str) -> dict[str, Any]:
- """取消同一份 Job 并返回当前完整状态。"""
- self.jobs.cancel(task_id)
+ async def finalize(job: _JobRecord) -> None:
+ """打包保持 running,失败与取消均不能发布一个不可用的下载链接。"""
+ terminal = job.status
+ job.status = "running"
+ job.finished_at = None
+ try:
+ if len(job.files) == 1:
+ output = job.files[0].output_files
+ if output is None or output.zip is None:
+ raise ValueError("ZIP output is missing")
+ file_id = output.zip.file_id
+ else:
+ with tempfile.TemporaryDirectory(prefix="mineru-task-zip-") as directory:
+ file_id = await run_sync(
+ _combine_archives, self.files, job, Path(directory) / "result.zip", manifest, terminal
+ )
+ if job.status not in {"canceled", "failed"}:
+ job.task_result_file_id = file_id
+ job.status = terminal
+ except asyncio.CancelledError:
+ raise
+ except Exception as exc:
+ if job.status != "canceled":
+ job.task_error = ErrorDetail(type="api_error", code="result_packaging_failed", message=str(exc))
+ job.status = "failed"
+ logger.exception("Task ZIP creation failed: %s", task_id)
+
+ await submit_parse_job(body, self.request, self.files, self.jobs, self.access, job_id=task_id, finalize=finalize)
return await self.get(task_id)
- async def wait(self, task_id: str, timeout: float) -> dict[str, Any]:
- """等待清理完成事件,不把 HTTP 请求取消传播到解析。"""
- await self.jobs.wait_for_terminal(task_id, timeout)
- return await self.get(task_id)
+ async def get(self, task_id: str) -> TaskExecution:
+ """只读取 Job 与最终 File 的标识,不在状态请求中访问产物正文。"""
+ record = self.jobs.get(task_id)
+ return TaskExecution(
+ self.jobs.build_response(record, access_level=self.access).model_dump(by_alias=True),
+ record.task_result_file_id,
+ record.task_error,
+ )
- async def read_output(self, file_id: str) -> bytes:
- """沿用文件存储的产物下载权限检查。"""
- return await run_sync(self.files.read_file_data, file_id)
+ async def cancel(self, task_id: str) -> None:
+ """沿用 JobStore 取消及线程清理边界,终态竞争不影响已经完成的任务。"""
+ record = self.jobs.get(task_id)
+ if record.status not in TERMINAL_TASK_STATUSES:
+ self.jobs.cancel(task_id)
+ await self.jobs.wait_for_terminal(task_id, 3600)
__all__ = [
"ApiTaskBackend",
"TaskBackend",
- "TaskResultResponse",
+ "TaskExecution",
+ "TaskManifestItem",
"TaskStatusResponse",
+ "TaskStore",
"TaskUpload",
+ "UploadTaskOptions",
"build_task_router",
+ "file_chunks",
+ "resolve_task_tier",
"task_payload",
]
diff --git a/mineru/utils/translations.py b/mineru/utils/translations.py
index 82ba205d..133c6048 100644
--- a/mineru/utils/translations.py
+++ b/mineru/utils/translations.py
@@ -143,6 +143,7 @@ ZH_MESSAGES: dict[str, str] = {
"File retention: {retention}": "文件保留期: {retention}",
"{start} - ongoing": "{start} - 进行中",
"not specified": "未指定",
+ "unlimited": "无限制",
"{days} day": "{days} 天",
"{days} days": "{days} 天",
# ------------------------------------------------------------------ list
diff --git a/scripts/http_task_example.py b/scripts/http_task_example.py
new file mode 100644
index 00000000..410d9679
--- /dev/null
+++ b/scripts/http_task_example.py
@@ -0,0 +1,523 @@
+#!/usr/bin/env python3
+"""仅使用 Python 标准库的 tasks HTTP 示例:清单、逐文件上传、轮询与 ZIP 下载。"""
+
+from __future__ import annotations
+
+import hashlib
+import http.client
+import json
+import os
+import secrets
+import socket
+import sys
+import tempfile
+import time
+import zipfile
+from collections.abc import Callable, Generator, Iterator, Mapping
+from contextlib import contextmanager
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Any
+from urllib.parse import quote, urlencode, urljoin, urlsplit
+
+TERMINAL = frozenset({"completed", "partial", "failed", "canceled"})
+STATUSES = TERMINAL | {"waiting_upload", "queued", "running"}
+RETRYABLE_HTTP = frozenset({408, 429, 500, 502, 503, 504})
+REDIRECTS = frozenset({301, 302, 303, 307, 308})
+CHUNK_BYTES = 1024 * 1024
+MAX_JSON_BYTES = 4 * 1024 * 1024
+BodyFactory = Callable[[], Generator[bytes, None, None]]
+
+
+class ClientError(RuntimeError):
+ """保存可重试属性,避免将错误 hash、鉴权或非法响应反复提交。"""
+
+ def __init__(self, message: str, *, retryable: bool = False, status: int | None = None) -> None:
+ """区分网络临时错误、HTTP 状态和确定性的协议错误。"""
+ super().__init__(message)
+ self.retryable = retryable
+ self.status = status
+
+
+@dataclass(frozen=True)
+class InputFile:
+ """固定文件顺序和客户端标识,恢复任务时仍按同一份清单对应文件。"""
+
+ path: Path
+ client_file_id: str
+ size: int
+ sha256sum: str | None
+
+ def manifest(self) -> dict[str, Any]:
+ """生成表单清单条目;关闭 hash 时完全省略该可选字段。"""
+ item: dict[str, Any] = {"client_file_id": self.client_file_id, "filename": self.path.name, "bytes": self.size}
+ if self.sha256sum is not None:
+ item["sha256sum"] = self.sha256sum
+ return item
+
+
+def _file_body(path: Path) -> Generator[bytes, None, None]:
+ """文件上传按固定块读取,中断或重试均关闭本次文件句柄。"""
+ try:
+ with path.open("rb") as source:
+ while chunk := source.read(CHUNK_BYTES):
+ yield chunk
+ except OSError as exc:
+ raise ClientError(f"Cannot read input file: {path.name}: {exc}") from exc
+
+
+def _bytes_body(data: bytes) -> Generator[bytes, None, None]:
+ """为小型表单主体提供可重新创建的发送迭代器。"""
+ yield data
+
+
+def _origin(url: str) -> tuple[str, str, int]:
+ """严格比较协议、主机和有效端口,阻止跨源转发 API Key。"""
+ parts = urlsplit(url)
+ if parts.scheme not in {"http", "https"} or not parts.hostname or parts.username or parts.password:
+ raise ClientError("Expected an http(s) URL without embedded credentials")
+ return parts.scheme.lower(), parts.hostname.lower(), parts.port or (443 if parts.scheme == "https" else 80)
+
+
+def _integer(name: str, default: int, minimum: int = 1) -> int:
+ """把环境变量明确校验为有界客户端预算,错误配置立即退出。"""
+ try:
+ value = int(os.environ.get(name, str(default)))
+ except ValueError as exc:
+ raise ClientError(f"{name} must be an integer") from exc
+ if value < minimum:
+ raise ClientError(f"{name} must be at least {minimum}")
+ return value
+
+
+class TaskClient:
+ """公共客户端只识别 task_id、状态和服务返回的上传及下载链接。"""
+
+ def __init__(self, files: list[InputFile]) -> None:
+ """读取连接与轮询预算,不依赖 MinerU SDK 或云存储 SDK。"""
+ self.base = os.environ.get("MINERU_API_URL", "").rstrip("/")
+ if not self.base:
+ raise ClientError("Set MINERU_API_URL to the API base URL")
+ self.origin = _origin(self.base)
+ if urlsplit(self.base).query or urlsplit(self.base).fragment:
+ raise ClientError("MINERU_API_URL must not contain a query or fragment")
+ self.key = os.environ.get("MINERU_API_KEY", "")
+ self.files = files
+ self.by_id = {item.client_file_id: item for item in files}
+ self.connect_timeout = _integer("CONNECT_TIMEOUT", 10)
+ self.timeout = _integer("REQUEST_TIMEOUT", 600)
+ self.max_polls = _integer("MAX_POLLS", 300, minimum=0)
+ try:
+ self.poll_interval = float(os.environ.get("POLL_INTERVAL", "1"))
+ except ValueError as exc:
+ raise ClientError("POLL_INTERVAL must be a non-negative number") from exc
+ if not 0 <= self.poll_interval < float("inf"):
+ raise ClientError("POLL_INTERVAL must be a non-negative finite number")
+ self.task_id: str | None = None
+ self.status_url: str | None = None
+
+ def resolve(self, url: str) -> str:
+ """解析服务返回的绝对或相对链接,保留 OSS 签名查询串。"""
+ resolved = urljoin(self.base + "/", url)
+ _origin(resolved)
+ return resolved
+
+ def _headers(self, url: str, headers: Mapping[str, str] | None) -> dict[str, str]:
+ """只向 API 同源地址附加 Key,同时保留明确给出的存储服务请求头。"""
+ result = dict(headers or {})
+ for name, value in result.items():
+ if not isinstance(name, str) or not isinstance(value, str) or "\r" in name + value or "\n" in name + value:
+ raise ClientError("Invalid service-provided HTTP header")
+ same_origin = _origin(url) == self.origin
+ if self.key and same_origin:
+ if not any(name.lower() == "authorization" for name in result):
+ result["Authorization"] = f"Bearer {self.key}"
+ elif self.key:
+ for name, value in result.items():
+ if name.lower() == "authorization" and value == f"Bearer {self.key}":
+ raise ClientError("Refusing to forward the API Key to another origin")
+ return result
+
+ @contextmanager
+ def request(
+ self,
+ method: str,
+ url: str,
+ *,
+ headers: Mapping[str, str] | None = None,
+ body: BodyFactory | None = None,
+ length: int | None = None,
+ ) -> Iterator[http.client.HTTPResponse]:
+ """流式发送与读取一次请求;创建任务不进行隐式重试或 POST 重定向。"""
+ resolved = self.resolve(url)
+ parts = urlsplit(resolved)
+ connection_type = http.client.HTTPSConnection if parts.scheme == "https" else http.client.HTTPConnection
+ connection = connection_type(parts.hostname, parts.port, timeout=self.connect_timeout)
+ outgoing = self._headers(resolved, headers)
+ if length is not None:
+ outgoing = {
+ name: value for name, value in outgoing.items() if name.lower() not in {"content-length", "transfer-encoding"}
+ }
+ outgoing["Content-Length"] = str(length)
+ iterator = body() if body is not None else None
+ try:
+ try:
+ connection.connect()
+ if connection.sock is not None:
+ connection.sock.settimeout(self.timeout)
+ target = parts.path or "/"
+ if parts.query:
+ target += "?" + parts.query
+ connection.request(method, target, body=iterator, headers=outgoing, encode_chunked=False)
+ response = connection.getresponse()
+ except (OSError, http.client.HTTPException, socket.timeout) as exc:
+ raise ClientError(f"{method} connection failed: {exc}", retryable=True) from exc
+ try:
+ yield response
+ finally:
+ response.close()
+ finally:
+ if iterator is not None:
+ iterator.close()
+ connection.close()
+
+ def _read_response(self, response: http.client.HTTPResponse, size: int) -> bytes:
+ """只把响应读取异常标记为网络错误,不能把本地写盘错误错误地加入重试。"""
+ try:
+ return response.read(size)
+ except (OSError, http.client.HTTPException, socket.timeout) as exc:
+ raise ClientError(f"Response interrupted: {exc}", retryable=True) from exc
+
+ def _http_error(self, response: http.client.HTTPResponse) -> ClientError:
+ """提取小型错误消息,不在日志中输出带签名的下载地址或认证信息。"""
+ content = self._read_response(response, MAX_JSON_BYTES + 1)
+ message = f"HTTP {response.status}"
+ try:
+ value = json.loads(content)
+ detail = value.get("error") if isinstance(value, dict) else None
+ if isinstance(detail, dict):
+ message += f": {detail.get('code', 'request_failed')}: {detail.get('message', '')}"
+ except (ValueError, UnicodeError):
+ pass
+ return ClientError(message, retryable=response.status in RETRYABLE_HTTP, status=response.status)
+
+ def json_request(
+ self,
+ method: str,
+ url: str,
+ *,
+ data: bytes | None = None,
+ body: BodyFactory | None = None,
+ length: int | None = None,
+ headers: Mapping[str, str] | None = None,
+ ) -> dict[str, Any]:
+ """读取有界的任务元数据,HTTP 200 的非法 JSON 也立即报告错误。"""
+ if data is not None:
+
+ def data_body() -> Generator[bytes, None, None]:
+ """闭包固定本次表单字节,避免把文件内容放进 JSON 请求。"""
+ yield from _bytes_body(data)
+
+ body, length = data_body, len(data)
+ with self.request(method, url, body=body, length=length, headers=headers) as response:
+ if response.status not in {200, 202}:
+ raise self._http_error(response)
+ content = self._read_response(response, MAX_JSON_BYTES + 1)
+ if len(content) > MAX_JSON_BYTES:
+ raise ClientError("Task metadata response is too large")
+ try:
+ payload = json.loads(content)
+ except (ValueError, UnicodeError) as exc:
+ raise ClientError("Task response is not valid JSON") from exc
+ if not isinstance(payload, dict):
+ raise ClientError("Task response must be a JSON object")
+ return self.validate_task(payload)
+
+ def validate_task(self, payload: dict[str, Any]) -> dict[str, Any]:
+ """校验任务身份和文件映射,恢复请求不能误把文件上传给另一项。"""
+ task_id = payload.get("task_id")
+ if not isinstance(task_id, str) or not task_id or (self.task_id is not None and task_id != self.task_id):
+ raise ClientError("Missing or inconsistent task_id")
+ if payload.get("status") not in STATUSES:
+ raise ClientError("Unknown task status")
+ if not isinstance(payload.get("status_url"), str) or not payload["status_url"]:
+ raise ClientError("Missing status_url")
+ files = payload.get("files")
+ if not isinstance(files, list) or len(files) != len(self.files):
+ raise ClientError("Task file count does not match local inputs")
+ seen: set[str] = set()
+ for item in files:
+ if not isinstance(item, dict):
+ raise ClientError("Invalid task file entry")
+ client_id = item.get("client_file_id")
+ if not isinstance(client_id, str) or client_id not in self.by_id or client_id in seen:
+ raise ClientError("Invalid or duplicate client_file_id")
+ seen.add(client_id)
+ local = self.by_id[client_id]
+ if item.get("filename") != local.path.name or item.get("bytes") != local.size:
+ raise ClientError("Task manifest differs from local inputs; use the original file list and order")
+ if local.sha256sum is not None and item.get("sha256sum") not in {None, local.sha256sum}:
+ raise ClientError("Task hash differs from the local file")
+ if item.get("upload_status") not in {"pending", "ready"}:
+ raise ClientError("Unknown upload_status")
+ uploads = payload.get("uploads")
+ if not isinstance(uploads, list):
+ raise ClientError("Missing uploads list")
+ seen_uploads: set[str] = set()
+ pending = {item["client_file_id"] for item in files if item["upload_status"] == "pending"}
+ for link in uploads:
+ if not isinstance(link, dict):
+ raise ClientError("Invalid upload descriptor")
+ client_id = link.get("client_file_id")
+ if not isinstance(client_id, str) or client_id not in self.by_id or client_id in seen_uploads:
+ raise ClientError("Invalid or duplicate upload client_file_id")
+ seen_uploads.add(client_id)
+ if link.get("upload_method") != "PUT" or not isinstance(link.get("upload_url"), str) or not link["upload_url"]:
+ raise ClientError("Invalid upload URL or method")
+ if not isinstance(link.get("upload_headers"), dict):
+ raise ClientError("Invalid upload headers")
+ if payload["status"] == "waiting_upload":
+ if seen_uploads != pending:
+ raise ClientError("Upload descriptors do not match pending files")
+ elif seen_uploads:
+ raise ClientError("Task no longer accepts uploads but still returns upload URLs")
+ if payload["status"] in {"queued", "running", "completed", "partial"} and pending:
+ raise ClientError("Task started before all files became ready")
+ if payload["status"] in {"completed", "partial"}:
+ if not isinstance(payload.get("result_url"), str) or not payload["result_url"]:
+ raise ClientError("Completed task has no ZIP download URL")
+ self.task_id = task_id
+ self.status_url = self.resolve(payload["status_url"])
+ return payload
+
+ def _form(self) -> list[tuple[str, str]]:
+ """所有解析参数都编码到表单,包括 JSON 文本形式的 manifest。"""
+ values = [
+ ("manifest", json.dumps([file.manifest() for file in self.files], ensure_ascii=False)),
+ ("ocr_mode", os.environ.get("OCR_MODE", "auto")),
+ ("page_range", os.environ.get("PAGE_RANGE", "")),
+ ]
+ if os.environ.get("MINERU_TIER"):
+ values.append(("tier", os.environ["MINERU_TIER"]))
+ formats = [value.strip() for value in os.environ.get("OUTPUT_FORMATS", "markdown").split(",")]
+ if not all(formats):
+ raise ClientError("OUTPUT_FORMATS contains an empty entry")
+ values.extend(("output_formats", value) for value in dict.fromkeys([*formats, "zip"]))
+ return values
+
+ def create(self, mode: str) -> dict[str, Any]:
+ """创建只执行一次;单文件直传也返回异步任务,不等待服务端同步解析。"""
+ values = self._form()
+ if mode == "preflight":
+ return self.json_request(
+ "POST",
+ self.base + "/v1/tasks",
+ data=urlencode(values).encode(),
+ headers={"Content-Type": "application/x-www-form-urlencoded"},
+ )
+ boundary = "mineru-" + secrets.token_hex(16)
+ prefix = bytearray()
+ for name, value in values:
+ prefix.extend(f'--{boundary}\r\nContent-Disposition: form-data; name="{name}"\r\n\r\n{value}\r\n'.encode())
+ # 逻辑文件名来自 manifest;固定 part 文件名避免引号、换行等字符破坏 MIME 头。
+ prefix.extend(
+ f'--{boundary}\r\nContent-Disposition: form-data; name="files"; filename="upload.bin"\r\n'
+ "Content-Type: application/octet-stream\r\n\r\n".encode()
+ )
+ suffix = f"\r\n--{boundary}--\r\n".encode()
+
+ def multipart_body() -> Generator[bytes, None, None]:
+ """只在内存保留小型表单元数据,文件主体仍从磁盘分块发送。"""
+ yield bytes(prefix)
+ yield from _file_body(self.files[0].path)
+ yield suffix
+
+ return self.json_request(
+ "POST",
+ self.base + "/v1/tasks",
+ body=multipart_body,
+ length=len(prefix) + self.files[0].size + len(suffix),
+ headers={"Content-Type": f"multipart/form-data; boundary={boundary}"},
+ )
+
+ def refresh(self) -> dict[str, Any]:
+ """只查询已有任务,任何查询失败都不能触发创建重试。"""
+ if self.status_url is None:
+ raise ClientError("No task status URL")
+ return self.json_request("GET", self.status_url)
+
+ def refresh_after_transfer_error(self) -> dict[str, Any]:
+ """传输结果不确定时先恢复状态查询,无法确认时不盲目重复发送文件。"""
+ for attempt in range(3):
+ try:
+ return self.refresh()
+ except ClientError as exc:
+ if not exc.retryable or attempt == 2:
+ raise
+ time.sleep(attempt + 1)
+ raise AssertionError("unreachable")
+
+ def upload_missing(self, task: dict[str, Any]) -> dict[str, Any]:
+ """逐文件上传与恢复,已经 ready 的文件永远不会重新发送。"""
+ for original in task["uploads"]:
+ client_id = original["client_file_id"]
+ local = self.by_id[client_id]
+ link = original
+ for attempt in range(3):
+
+ def upload_body() -> Generator[bytes, None, None]:
+ """每次重试重新打开同一个文件,单文件从头重传。"""
+ yield from _file_body(local.path)
+
+ try:
+ with self.request(
+ "PUT",
+ link["upload_url"],
+ headers=link["upload_headers"],
+ body=upload_body,
+ length=local.size,
+ ) as response:
+ if not 200 <= response.status < 300:
+ raise self._http_error(response)
+ break
+ except ClientError as exc:
+ if not exc.retryable and exc.status != 403:
+ raise
+ # 请求可能已经落盘但响应丢失;先看状态,再决定是否重传。
+ current = self.refresh_after_transfer_error()
+ remote = next(item for item in current["files"] if item["client_file_id"] == client_id)
+ if remote["upload_status"] == "ready":
+ break
+ if current["status"] != "waiting_upload":
+ return current
+ replacement = next((item for item in current["uploads"] if item["client_file_id"] == client_id), None)
+ if replacement is None:
+ raise ClientError("Pending file has no upload URL") from exc
+ if exc.status == 403 and replacement["upload_url"] == link["upload_url"]:
+ raise
+ if attempt == 2:
+ raise ClientError(f"Upload failed after three attempts: {local.path.name}") from exc
+ link = replacement
+ time.sleep(attempt + 1)
+ return self.refresh()
+
+ def download(self, task: dict[str, Any], output: Path) -> None:
+ """只访问返回的 ZIP 链接,支持过期链接刷新和安全的跨源重定向。"""
+ output.parent.mkdir(parents=True, exist_ok=True)
+ descriptor, name = tempfile.mkstemp(prefix=output.name + ".", suffix=".part", dir=output.parent)
+ os.close(descriptor)
+ temporary = Path(name)
+ url = self.resolve(task["result_url"])
+ try:
+ for attempt in range(3):
+ try:
+ for _ in range(6):
+ with self.request("GET", url) as response:
+ if response.status in REDIRECTS:
+ location = response.getheader("Location")
+ if not location:
+ raise ClientError("Download redirect is missing Location")
+ url = self.resolve(urljoin(url, location))
+ continue
+ if response.status != 200:
+ raise self._http_error(response)
+ with temporary.open("wb") as target:
+ while chunk := self._read_response(response, CHUNK_BYTES):
+ try:
+ target.write(chunk)
+ except OSError as exc:
+ raise ClientError(f"Cannot save ZIP: {exc}") from exc
+ expected = response.getheader("Content-Length")
+ if expected is not None and temporary.stat().st_size != int(expected):
+ raise ClientError("Incomplete ZIP download", retryable=True)
+ break
+ else:
+ raise ClientError("Too many download redirects")
+ if not zipfile.is_zipfile(temporary):
+ raise ClientError("Downloaded result is not a ZIP archive")
+ temporary.replace(output)
+ return
+ except ClientError as exc:
+ if attempt == 2 or (not exc.retryable and exc.status not in {401, 403, 404}):
+ raise
+ current = self.refresh_after_transfer_error()
+ if current["status"] not in {"completed", "partial"}:
+ raise ClientError("Task no longer has a downloadable result") from exc
+ replacement = self.resolve(current["result_url"])
+ if exc.status in {401, 403, 404} and replacement == url:
+ raise
+ url = replacement
+ time.sleep(attempt + 1)
+ finally:
+ temporary.unlink(missing_ok=True)
+
+ def run(self, mode: str, output: Path) -> int:
+ """一条命令等待异步任务并保存 ZIP,超时保留任务供后续恢复。"""
+ resume = os.environ.get("TASK_ID", "")
+ if resume:
+ self.task_id = resume
+ self.status_url = self.base + "/v1/tasks/" + quote(resume, safe="")
+ task = self.refresh()
+ else:
+ task = self.create(mode)
+ print(f"task_id={self.task_id}", file=sys.stderr)
+ if task["status"] == "waiting_upload":
+ task = self.upload_missing(task)
+ polls = 0
+ while task["status"] not in TERMINAL:
+ if polls >= self.max_polls:
+ print(f"Polling budget exhausted; task_id={self.task_id} continues running", file=sys.stderr)
+ return 124
+ polls += 1
+ time.sleep(self.poll_interval)
+ try:
+ task = self.refresh()
+ except ClientError as exc:
+ if not exc.retryable:
+ raise
+ if task["status"] in {"failed", "canceled"}:
+ print(
+ json.dumps({"status": task["status"], "error": task.get("error"), "files": task["files"]}, ensure_ascii=False),
+ file=sys.stderr,
+ )
+ return 1
+ self.download(task, output)
+ print(f"Saved {output}")
+ return 2 if task["status"] == "partial" else 0
+
+
+def main(arguments: list[str]) -> int:
+ """构造真实文件清单并报告可恢复的失败,所有文件读取都采用流式处理。"""
+ client: TaskClient | None = None
+ try:
+ if not arguments:
+ raise ClientError("usage: bash scripts/http_task_example.sh <file> [file ...]")
+ mode = os.environ.get("UPLOAD_MODE", "preflight")
+ if mode not in {"preflight", "direct"}:
+ raise ClientError("UPLOAD_MODE must be preflight or direct")
+ if mode == "direct" and len(arguments) != 1:
+ raise ClientError("Direct multipart upload accepts one file; use preflight for multiple files")
+ send_hash = os.environ.get("SEND_HASH", "1")
+ if send_hash not in {"0", "1"}:
+ raise ClientError("SEND_HASH must be 0 or 1")
+ inputs: list[InputFile] = []
+ for index, value in enumerate(arguments):
+ path = Path(value).resolve()
+ if not path.is_file() or path.stat().st_size == 0:
+ raise ClientError(f"Input must be a non-empty file: {value}")
+ hasher = hashlib.sha256() if send_hash == "1" else None
+ if hasher is not None:
+ for chunk in _file_body(path):
+ hasher.update(chunk)
+ inputs.append(InputFile(path, f"f{index + 1}", path.stat().st_size, hasher.hexdigest() if hasher else None))
+ client = TaskClient(inputs)
+ return client.run(mode, Path(os.environ.get("RESULT_FILE", "result.zip")))
+ except (ClientError, OSError, ValueError) as exc:
+ print(f"error: {exc}", file=sys.stderr)
+ if client is not None and client.task_id:
+ print(f"Resume with TASK_ID={client.task_id} and the original file list", file=sys.stderr)
+ return 1
+
+
+if __name__ == "__main__":
+ raise SystemExit(main(sys.argv[1:]))
diff --git a/scripts/http_task_example.sh b/scripts/http_task_example.sh
index 048bc034..9c0f6084 100644
--- a/scripts/http_task_example.sh
+++ b/scripts/http_task_example.sh
@@ -1,93 +1,7 @@
#!/usr/bin/env bash
-# V1 便捷解析:同一个原始字节请求携带哈希,命中时可跳过主体传输。
-# MODE=sync|async,RESPONSE_FORMAT=json|zip,OUTPUT_FORMATS=markdown,middle_json,...
-# 成功输出到 RESULT_FILE;部分成功退出 2,失败退出 1,预算耗尽退出 124。
+# tasks HTTP 示例:默认预检后逐文件上传,轮询状态并下载服务返回的 ZIP 链接。
+# SEND_HASH=0 可省略 hash;TASK_ID=... 恢复原任务;UPLOAD_MODE=direct 仅允许单文件。
+# 成功退出 0,部分成功退出 2,失败退出 1,轮询预算耗尽退出 124。
set -euo pipefail
-
-[ $# -eq 1 ] && [ -f "$1" ] || { echo 'usage: bash scripts/http_task_example.sh <file>' >&2; exit 1; }
-: "${MINERU_API_URL:?Set MINERU_API_URL to the API or Router base URL}"
-TASK_SOURCE=$1
-TASK_MODE=${MODE:-sync}
-TASK_FORMAT=${RESPONSE_FORMAT:-json}
-TASK_WAIT=${WAIT_TIMEOUT:-300}
-TASK_MAX_POLLS=${MAX_POLLS:-300}
-TASK_RESULT=${RESULT_FILE:-result.$TASK_FORMAT}
-case "$TASK_MODE" in sync|async) ;; *) echo 'MODE must be sync or async' >&2; exit 1 ;; esac
-case "$TASK_FORMAT" in json|zip) ;; *) echo 'RESPONSE_FORMAT must be json or zip' >&2; exit 1 ;; esac
-TASK_RESPONSE=$(mktemp)
-TASK_HEADERS=$(mktemp)
-trap 'rm -f "$TASK_RESPONSE" "$TASK_HEADERS"' EXIT
-TASK_AUTH=()
-if [ -n "${MINERU_API_KEY:-}" ]; then TASK_AUTH=(-H "Authorization: Bearer $MINERU_API_KEY"); fi
-
-# 用标准库编码查询串,文件名和页范围不进入 shell 求值。
-TASK_URL=$(python3 - "$TASK_SOURCE" "$TASK_MODE" "$TASK_FORMAT" "$TASK_WAIT" <<'PY'
-import hashlib
-import os
-import pathlib
-import sys
-from urllib.parse import urlencode
-
-path = pathlib.Path(sys.argv[1])
-hasher = hashlib.sha256()
-with path.open('rb') as source:
- for chunk in iter(lambda: source.read(1024 * 1024), b''):
- hasher.update(chunk)
-query = [('filename', path.name), ('sha256sum', hasher.hexdigest())]
-if os.environ.get('MINERU_TIER'):
- query.append(('tier', os.environ['MINERU_TIER']))
-query.extend([('ocr_mode', os.environ.get('OCR_MODE', 'auto')), ('page_range', os.environ.get('PAGE_RANGE', ''))])
-formats = [value.strip() for value in os.environ.get('OUTPUT_FORMATS', 'markdown').split(',')]
-if sys.argv[3] == 'zip' and 'zip' not in formats:
- formats.append('zip')
-query.extend(('output_formats', value) for value in formats)
-route = '/v1/file_parse' if sys.argv[2] == 'sync' else '/v1/tasks'
-if sys.argv[2] == 'sync':
- query.extend([('response_format', sys.argv[3]), ('wait_timeout', sys.argv[4])])
-print(os.environ['MINERU_API_URL'].rstrip('/') + route + '?' + urlencode(query))
-PY
-)
-
-TASK_CODE=$(curl --silent --show-error --http1.1 --connect-timeout 10 --max-time "${REQUEST_TIMEOUT:-600}" \
- --expect100-timeout "${EXPECT_TIMEOUT:-310}" -H 'Expect: 100-continue' -H 'Content-Type: application/octet-stream' \
- ${TASK_AUTH[@]+"${TASK_AUTH[@]}"} -X POST --upload-file "$TASK_SOURCE" \
- --output "$TASK_RESPONSE" --dump-header "$TASK_HEADERS" --write-out '%{http_code}' "$TASK_URL")
-
-TASK_POLLS=0
-while [ "$TASK_CODE" = 202 ]; do
- TASK_ID=$(python3 - "$TASK_RESPONSE" <<'PY'
-import json
-import sys
-from urllib.parse import quote
-
-with open(sys.argv[1], encoding='utf-8') as source:
- task_id = json.load(source)['task_id']
-print(quote(task_id, safe=''))
-PY
-)
- if [ "$TASK_POLLS" -ge "$TASK_MAX_POLLS" ]; then
- echo "Polling budget exhausted; task_id=$TASK_ID continues running" >&2
- exit 124
- fi
- TASK_POLLS=$((TASK_POLLS + 1))
- sleep "${POLL_INTERVAL:-1}"
- TASK_CODE=$(curl --silent --show-error --connect-timeout 10 --max-time "${REQUEST_TIMEOUT:-600}" \
- ${TASK_AUTH[@]+"${TASK_AUTH[@]}"} --output "$TASK_RESPONSE" --dump-header "$TASK_HEADERS" \
- --write-out '%{http_code}' "${MINERU_API_URL%/}/v1/tasks/$TASK_ID/result?response_format=$TASK_FORMAT")
-done
-if [ "$TASK_CODE" != 200 ]; then cat "$TASK_RESPONSE" >&2; exit 1; fi
-mv -- "$TASK_RESPONSE" "$TASK_RESULT"
-echo "Saved $TASK_RESULT"
-python3 - "$TASK_RESULT" "$TASK_FORMAT" <<'PY'
-import json
-import sys
-import zipfile
-
-if sys.argv[2] == 'json':
- with open(sys.argv[1], encoding='utf-8') as source:
- status = json.load(source)['status']
-else:
- with zipfile.ZipFile(sys.argv[1]) as archive:
- status = json.loads(archive.read('manifest.json'))['status'] if 'manifest.json' in archive.namelist() else 'completed'
-raise SystemExit(2 if status == 'partial' else 0)
-PY
+TASK_SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)
+exec "${MINERU_PYTHON:-python3}" "$TASK_SCRIPT_DIR/http_task_example.py" "$@"
diff --git a/tests/unittest/test_remote_usage.py b/tests/unittest/test_remote_usage.py
index cad3ed44..e3765e0d 100644
--- a/tests/unittest/test_remote_usage.py
+++ b/tests/unittest/test_remote_usage.py
@@ -279,6 +279,29 @@ def test_usage_human_output_shows_complete_remote_usage(monkeypatch: pytest.Monk
assert guidance.OFFICIAL_API_KEY_URL in result.stdout
+def test_usage_preserves_unlimited_local_limits(monkeypatch: pytest.MonkeyPatch) -> None:
+ """本地 API 的 null 上限经过 Doclib 校验、CLI JSON 与文本展示都不丢失语义。"""
+ payload = _usage_response("registered").model_dump()
+ payload["limits"].update(max_pages_per_file=None, max_file_size_bytes=None)
+ validated = RemoteUsageResponse.model_validate(payload)
+
+ class _LocalClient(_UsageClient):
+ """提供真实可空字段形状,保留已有客户端的调用方式。"""
+
+ remote_url = "http://127.0.0.1:8000"
+ response = validated
+
+ monkeypatch.setattr(usage, "DoclibClient", _LocalClient)
+ result = runner.invoke(app, ["usage"])
+ assert result.exit_code == 0, result.output
+ assert "Max pages per file: unlimited" in result.stdout
+ assert "Max file size: unlimited" in result.stdout
+ machine = runner.invoke(app, ["usage", "--json"])
+ assert machine.exit_code == 0, machine.output
+ limits = json.loads(machine.output)["usage"]["limits"]
+ assert limits["max_pages_per_file"] is None and limits["max_file_size_bytes"] is None
+
+
def test_usage_invalid_api_key_keeps_error_and_adds_required_guidance(monkeypatch: pytest.MonkeyPatch) -> None:
class _InvalidClient(_UsageClient):
def get_remote_usage(self) -> RemoteUsageResponse:
diff --git a/tests/unittest/test_resource_retention.py b/tests/unittest/test_resource_retention.py
index e9f18ff8..f2293ee6 100644
--- a/tests/unittest/test_resource_retention.py
+++ b/tests/unittest/test_resource_retention.py
@@ -4,6 +4,7 @@ from __future__ import annotations
import asyncio
import hashlib
+import json
import os
from datetime import datetime, timezone
from pathlib import Path
@@ -232,17 +233,24 @@ def test_queued_cancel_releases_input_before_execution(tmp_path: Path, clock: li
def test_hash_preflight_rejection_releases_request_lease(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
- """哈希命中后的 Content-Length 校验失败不会泄漏请求持有的 blob 引用。"""
+ """清单 hash 命中后的声明大小校验失败不会泄漏准备阶段的 blob 引用。"""
monkeypatch.setattr(api_server, "_preflight_tier_dependencies", lambda *args: None)
app = api_server.create_app(upload_dir=str(tmp_path / "files"), tier="flash")
with TestClient(app) as client:
_, sha = _source(app.state.file_store, tmp_path)
response = client.post(
- f"/v1/tasks?filename=input.pdf&sha256sum={sha}&tier=flash",
- content=b"bad",
- headers={"Content-Type": "application/octet-stream"},
+ "/v1/tasks",
+ data={
+ "tier": "flash",
+ "manifest": json.dumps(
+ [
+ {"client_file_id": "f1", "filename": "input.pdf", "bytes": 3, "sha256sum": sha},
+ ]
+ ),
+ },
)
assert response.status_code == 400
+ assert response.json()["error"]["code"] == "upload_size_mismatch"
assert not app.state.file_store._pins and not app.state.job_store._jobs
diff --git a/tests/unittest/test_router_balancing.py b/tests/unittest/test_router_balancing.py
index 4113e0b8..7b4f1488 100644
--- a/tests/unittest/test_router_balancing.py
+++ b/tests/unittest/test_router_balancing.py
@@ -3,7 +3,9 @@
from __future__ import annotations
import asyncio
-import hashlib
+import json
+import threading
+import time
from pathlib import Path
from typing import Any
@@ -11,6 +13,8 @@ import httpx
import pytest
from fastapi.testclient import TestClient
from test_v1_router import _FakeV1Upstream, _make_router, _upload_file
+from test_task_api import HTML, _WorkerTransport, _submit, _terminal, _upload
+from mineru.parser import api_server
from mineru.kit.router import RouterSettings, create_app
from mineru.kit.router.workers import JobReservation
@@ -47,6 +51,64 @@ def test_valid_unavailable_output_format_remains_a_capability_error() -> None:
assert upstream.job_counter == 0 and app.state.worker_pool.workers[0].active_jobs == 0
+def test_task_auth_preflight_uses_a_capable_worker_without_reservation() -> None:
+ """待上传任务只在匹配 tier 的 worker 校验凭证,不能被无关 worker 的权限误判。"""
+ first = _FakeV1Upstream("worker-a", ("flash",))
+ second = _FakeV1Upstream("worker-b", ("standard",))
+ checked: list[str] = []
+
+ async def handler(request: httpx.Request) -> httpx.Response:
+ """只有 standard worker 的资源接口要求认证,健康检查保持公开。"""
+ if request.url.path == "/v1/health":
+ response = await (first if request.url.host == "worker-a" else second).handle(request)
+ payload = response.json()
+ payload["features"]["output_formats"].append("zip")
+ return httpx.Response(200, json=payload, request=request)
+ if request.url.path == "/v1/files":
+ checked.append(request.url.host)
+ if request.url.host == "worker-b" and request.headers.get("authorization") != "Bearer owner":
+ return httpx.Response(
+ 401,
+ json={
+ "error": {
+ "type": "authentication_error",
+ "code": "invalid_api_key",
+ "message": "Invalid key",
+ }
+ },
+ request=request,
+ )
+ return httpx.Response(200, json={"object": "list", "data": []}, request=request)
+ return await (first if request.url.host == "worker-a" else second).handle(request)
+
+ app = create_app(
+ RouterSettings(
+ upstream_urls=("http://worker-a", "http://worker-b"), local_gpus="none", worker_refresh_interval_seconds=0
+ ),
+ transport=httpx.MockTransport(handler),
+ )
+ form = {
+ "tier": "standard",
+ "manifest": json.dumps(
+ [
+ {
+ "client_file_id": "f1",
+ "filename": "source.pdf",
+ "bytes": 3,
+ }
+ ]
+ ),
+ }
+ with TestClient(app) as client:
+ cursors = dict(app.state.worker_pool._selection_cursors)
+ assert client.post("/v1/tasks", data=form).status_code == 401
+ accepted = client.post("/v1/tasks", data=form, headers={"authorization": "Bearer owner"})
+ assert accepted.status_code == 202, accepted.text
+ assert checked == ["worker-b", "worker-b"]
+ assert app.state.worker_pool._selection_cursors == cursors
+ assert [worker.active_jobs for worker in app.state.worker_pool.workers] == [0, 0]
+
+
def test_same_caller_uploads_round_robin_without_affinity() -> None:
"""同一 IP 与凭证的独立文件应均衡上传,不再固定在一个 worker。"""
first, second = _FakeV1Upstream("worker-a", ("standard",)), _FakeV1Upstream("worker-b", ("standard",))
@@ -63,7 +125,7 @@ def test_completed_inline_jobs_rotate_and_reads_do_not_advance_cursors() -> None
app, _ = _make_router(first, second)
with TestClient(app) as client:
for index in range(10):
- response = client.post("/v1/tasks" if index % 2 else "/v1/parse/jobs", json=BODY)
+ response = client.post("/v1/parse/jobs", json=BODY)
assert response.status_code == 202, response.text
task_id = response.json().get("task_id") or response.json()["job_id"]
assert client.get(f"/v1/parse/jobs/{task_id}").json()["status"] == "completed"
@@ -91,9 +153,7 @@ def test_delayed_concurrent_submission_pre_reserves_worker_load() -> None:
async def run() -> list[httpx.Response]:
"""在 Router 所属事件循环内同时提交新旧入口。"""
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://router") as client:
- return await asyncio.gather(
- *(client.post("/v1/tasks" if index % 2 else "/v1/parse/jobs", json=BODY) for index in range(10))
- )
+ return await asyncio.gather(*(client.post("/v1/parse/jobs", json=BODY) for index in range(10)))
with TestClient(app) as client:
responses = client.portal.call(run)
@@ -111,7 +171,7 @@ def test_file_ownership_cannot_override_lower_load() -> None:
file_id = _upload_file(client, token="owner", content=b"source")
for _ in range(10):
response = client.post(
- "/v1/tasks",
+ "/v1/parse/jobs",
headers=headers,
json={"tier": "standard", "files": [{"source": {"type": "file_id", "file_id": file_id}}]},
)
@@ -120,21 +180,49 @@ def test_file_ownership_cannot_override_lower_load() -> None:
assert first.source_download_attempts == second.source_download_attempts == 0
-def test_cached_raw_tasks_still_balance() -> None:
- """新入口哈希命中仅复用字节,不能让后续任务跳过负载选择。"""
- first, second = _FakeV1Upstream("worker-a", ("standard",)), _FakeV1Upstream("worker-b", ("standard",))
- app, _ = _make_router(first, second)
+def test_cached_tasks_still_balance(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ """真实 tasks 命中缓存后仍按负载选择 worker,等待上传不预占模型名额。"""
+ release = threading.Event()
+ original = api_server.parse_async
+
+ async def delayed(*args: Any, **kwargs: Any) -> Any:
+ """保持已选任务处于活动状态,明确观察十个任务的并发负载分配。"""
+ while not release.is_set():
+ await asyncio.sleep(0.01)
+ return await original(*args, **kwargs)
+
+ monkeypatch.setattr(api_server, "parse_async", delayed)
+ workers = {host: api_server.create_app(upload_dir=str(tmp_path / host), tier="flash") for host in ("worker-a", "worker-b")}
+ transport = _WorkerTransport(workers)
+ app = create_app(
+ RouterSettings(
+ upstream_urls=tuple(f"http://{host}" for host in workers), local_gpus="none", worker_refresh_interval_seconds=0
+ ),
+ transport=transport,
+ )
+ tasks = []
with TestClient(app) as client:
- for _ in range(10):
- response = client.post(
- "/v1/tasks",
- params={"tier": "standard", "filename": "source.pdf", "sha256sum": hashlib.sha256(b"pdf").hexdigest()},
- headers={"content-type": "application/octet-stream"},
- content=b"pdf",
- )
- assert response.status_code == 202, response.text
- assert [worker.active_jobs for worker in app.state.worker_pool.workers] == [5, 5]
- assert (first.job_counter, second.job_counter) == (5, 5)
+ try:
+ for index in range(10):
+ task = _submit(client, [("source.html", HTML)])
+ if index == 0:
+ assert [worker.active_jobs for worker in app.state.worker_pool.workers] == [0, 0]
+ _upload(client, task, [("source.html", HTML)])
+ else:
+ assert task["uploads"] == []
+ tasks.append(task)
+ deadline = time.monotonic() + 5
+ while not app.state.task_store._records[task["task_id"]].submitted:
+ assert time.monotonic() < deadline
+ time.sleep(0.01)
+ assert [worker.active_jobs for worker in app.state.worker_pool.workers] == [5, 5]
+ assert [len(worker.state.job_store._jobs) for worker in workers.values()] == [5, 5]
+ assert sum(method == "PUT" for _, method, _ in transport.calls) == 2
+ finally:
+ release.set()
+ for task in tasks:
+ assert _terminal(client, task)["status"] == "completed"
+ assert [worker.active_jobs for worker in app.state.worker_pool.workers] == [0, 0]
def test_generation_change_and_duplicate_release_do_not_touch_new_jobs() -> None:
@@ -178,22 +266,20 @@ def test_late_job_response_after_replacement_is_not_published() -> None:
upstream._create_job = replaced # type: ignore[method-assign]
with TestClient(app) as client:
- response = client.post("/v1/tasks", json=BODY)
+ response = client.post("/v1/parse/jobs", json=BODY)
assert response.status_code == 503, response.text
assert not app.state.registry.list("job")
assert app.state.worker_pool.workers[0].active_jobs == 1
new_reservations[0].release()
-def test_inline_output_follows_redirect_without_forwarding_auth() -> None:
- """产物重定向保持可用,调用方鉴权不能被转发到不同源的下载地址。"""
+def test_output_redirect_does_not_fetch_remote_body() -> None:
+ """Files 下载只转发重定向,不在 Router 内回源下载外部结果正文。"""
upstream = _FakeV1Upstream("worker-a", ("standard",))
async def handler(request: httpx.Request) -> httpx.Response:
- """模拟 worker 返回签名下载地址,并检查 CDN 请求头。"""
- if request.url.host == "cdn.example":
- assert "authorization" not in request.headers
- return httpx.Response(200, content=b"Redirected markdown", request=request)
+ """worker 返回外部下载地址时,Router 不能主动请求 CDN 字节。"""
+ assert request.url.host != "cdn.example"
if request.url.path.endswith("/content"):
return httpx.Response(302, headers={"location": "https://cdn.example/output"}, request=request)
return await upstream.handle(request)
@@ -203,54 +289,98 @@ def test_inline_output_follows_redirect_without_forwarding_auth() -> None:
transport=httpx.MockTransport(handler),
)
with TestClient(app) as client:
- response = client.post("/v1/file_parse", headers={"authorization": "Bearer private-key"}, json=BODY)
- assert response.status_code == 200, response.text
- assert response.json()["files"][0]["content"]["markdown"] == "Redirected markdown"
+ headers = {"authorization": "Bearer private-key"}
+ created = client.post("/v1/parse/jobs", headers=headers, json=BODY).json()
+ result = client.get(f"/v1/parse/jobs/{created['job_id']}", headers=headers).json()
+ file_id = result["files"][0]["output_files"]["markdown"]["file_id"]
+ response = client.get(f"/v1/files/{file_id}/content", headers=headers, follow_redirects=False)
+ assert response.status_code == 302 and response.headers["location"] == "https://cdn.example/output"
def test_creation_failure_and_cancelled_copy_release_reservations() -> None:
- """创建失败和传输取消均归还名额,临时文件不会遗留。"""
+ """既有 Jobs 创建失败与跨 worker 复制取消仍归还预占,不损坏原源文件。"""
upstream = _FakeV1Upstream("worker-a", ("standard",), fail_jobs=True)
app, _ = _make_router(upstream)
with TestClient(app) as client:
- failed = client.post("/v1/tasks", json=BODY)
+ failed = client.post("/v1/parse/jobs", json=BODY)
assert failed.status_code == 502
assert app.state.worker_pool.workers[0].active_jobs == 0
- uploaded = client.post(
- "/v1/tasks?filename=source.pdf&tier=standard", headers={"content-type": "application/octet-stream"}, content=b"pdf"
- )
- assert uploaded.status_code == 502
- assert not upstream.files
- assert not app.state.source_store._files
- assert not app.state.source_store._uploads
- assert app.state.worker_pool.workers[0].active_jobs == 0
- upstream = _FakeV1Upstream("worker-a", ("standard",))
- original = upstream.handle
+ first = _FakeV1Upstream("worker-a", ("standard",))
+ second = _FakeV1Upstream("worker-b", ("standard",))
+ original = second.handle
async def canceled_put(request: httpx.Request) -> httpx.Response:
- """在目标 PUT 中模拟提交方的协程取消。"""
+ """仅取消目标 worker 的复制上传,原文件及其私有缓存仍可用。"""
if request.method == "PUT":
raise asyncio.CancelledError()
return await original(request)
- upstream.handle = canceled_put # type: ignore[method-assign]
- app, _ = _make_router(upstream)
-
- async def run_cancel() -> None:
- """捕获模拟取消,随后核对同一事件循环中的清理结果。"""
- async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://router") as client:
- try:
- await client.post(
- "/v1/tasks?filename=source.pdf&tier=standard",
- content=b"pdf",
- headers={"content-type": "application/octet-stream"},
- )
- except asyncio.CancelledError:
- pass
-
+ second.handle = canceled_put # type: ignore[method-assign]
+ app, _ = _make_router(first, second)
with TestClient(app) as client:
+ file_id = _upload_file(client, token="owner", content=b"source")
+ app.state.worker_pool.workers[0].active_jobs = 1
+
+ async def run_cancel() -> None:
+ """在 Router 所属事件循环捕获模拟取消,随后核对清理结果。"""
+ async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://router") as asynchronous:
+ try:
+ await asynchronous.post(
+ "/v1/parse/jobs",
+ headers={"authorization": "Bearer owner"},
+ json={"tier": "standard", "files": [{"source": {"type": "file_id", "file_id": file_id}}]},
+ )
+ except asyncio.CancelledError:
+ pass
+
client.portal.call(run_cancel)
- assert app.state.worker_pool.workers[0].active_jobs == 0
+ assert [worker.active_jobs for worker in app.state.worker_pool.workers] == [1, 0]
+ assert app.state.source_store.find_file(file_id) is not None
assert not app.state.source_store._uploads
- assert all(upload["status"] != "pending" for upload in upstream.uploads.values())
+ assert all(upload["status"] != "pending" for upload in second.uploads.values())
+ app.state.worker_pool.workers[0].active_jobs = 0
+
+
+def test_task_submission_failure_and_replacement_release_only_owned_load(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """新 tasks 的网络失败和迟到响应释放自身预占,不能扣除新 generation 的任务。"""
+ for replacement in (False, True):
+ worker_app = api_server.create_app(upload_dir=str(tmp_path / str(replacement)), tier="flash")
+ transport = _WorkerTransport({"worker-a": worker_app})
+ app = create_app(
+ RouterSettings(upstream_urls=("http://worker-a",), local_gpus="none", worker_refresh_interval_seconds=0),
+ transport=transport,
+ )
+ original = transport.handle_async_request
+ new_reservations = []
+
+ async def interrupted(request: httpx.Request) -> httpx.Response:
+ """在上游创建请求的网络边界模拟失败或 worker 替换。"""
+ if request.method == "POST" and request.url.path == "/v1/tasks":
+ if not replacement:
+ raise httpx.ConnectError("simulated disconnect", request=request)
+ response = await original(request)
+ pool = app.state.worker_pool
+ worker = pool.workers[0]
+ worker.generation += 1
+ worker.active_jobs = 0
+ reservation = pool.reserve_job(tier="flash", required_sources={"file_id"})
+ assert reservation is not None
+ new_reservations.append(reservation)
+ return response
+ return await original(request)
+
+ monkeypatch.setattr(transport, "handle_async_request", interrupted)
+ with TestClient(app) as client:
+ task = _submit(client, [("source.html", HTML)])
+ _upload(client, task, [("source.html", HTML)])
+ failed = _terminal(client, task)
+ assert failed["status"] == "failed" and failed["result_url"] is None
+ assert not app.state.registry.list("job")
+ assert not app.state.source_store._files and not app.state.source_store._uploads
+ assert app.state.worker_pool.workers[0].active_jobs == (1 if replacement else 0)
+ for reservation in new_reservations:
+ reservation.release()
diff --git a/tests/unittest/test_task_api.py b/tests/unittest/test_task_api.py
index e9c02f91..5b5b437a 100644
--- a/tests/unittest/test_task_api.py
+++ b/tests/unittest/test_task_api.py
@@ -1,4 +1,4 @@
-"""通过两类真实服务验证 V1 便捷接口、源字节复用和异步生命周期。"""
+"""真实 API 与双 worker Router 的表单任务、逐文件上传和 ZIP 链接契约。"""
from __future__ import annotations
@@ -15,7 +15,7 @@ from typing import Any
import httpx
import pytest
-from fastapi import FastAPI, Request
+from fastapi import FastAPI
from fastapi.testclient import TestClient
from mineru.kit.router import RouterSettings
@@ -23,386 +23,492 @@ from mineru.kit.router import create_app as create_router
from mineru.parser import api_server, task_api
HTML = b"<!doctype html><html><body><h1>Shared tasks</h1><p>Preserved content.</p></body></html>"
+SECOND = b"<h1>Second document</h1><p>Second content.</p>"
class _WorkerTransport(httpx.AsyncBaseTransport):
- """通过 ASGI 驱动两个真实 API server,避免 fake 允许源文件公开下载。"""
+ """使用真实 worker 路由验证源文件权限和任务生命周期,不以宽松 fake 替代。"""
def __init__(self, apps: dict[str, FastAPI]) -> None:
- """保存测试 worker 及其真实路由传输。"""
+ """保存 worker 和真实 ASGI transport,供断连与调度测试观察。"""
self.apps = apps
self.transports = {host: httpx.ASGITransport(app=app) for host, app in apps.items()}
+ self.calls: list[tuple[str, str, str]] = []
async def handle_async_request(self, request: httpx.Request) -> httpx.Response:
- """按主机路由到真实 worker 应用。"""
+ """按主机选择 worker,并记录真实上游协议。"""
+ self.calls.append((request.url.host, request.method, request.url.path))
return await self.transports[request.url.host].handle_async_request(request)
async def aclose(self) -> None:
- """关闭前等待真实后台任务清理,不遗留推理运行时租约。"""
+ """等待任务与 Job 清理完成,再释放测试 worker 的解析运行时。"""
for app in self.apps.values():
+ await app.state.task_store.shutdown()
await app.state.job_store.shutdown()
@pytest.fixture(params=["api", "router"])
def service(request: pytest.FixtureRequest, tmp_path: Path) -> Iterator[tuple[TestClient, FastAPI]]:
- """对直接 API 和双 worker Router 运行同一份公开接口合约。"""
+ """对本地服务与双 worker Router 执行同一份共同协议验收。"""
if request.param == "api":
app = api_server.create_app(upload_dir=str(tmp_path / "direct"), tier="flash")
else:
workers = {
host: api_server.create_app(upload_dir=str(tmp_path / host), tier="flash") for host in ("worker-a", "worker-b")
}
+ transport = _WorkerTransport(workers)
app = create_router(
RouterSettings(
upstream_urls=tuple(f"http://{host}" for host in workers), local_gpus="none", worker_refresh_interval_seconds=0
),
- transport=_WorkerTransport(workers),
+ transport=transport,
)
+ app.state.test_transport = transport
with TestClient(app) as client:
yield client, app
-def _terminal(client: TestClient, task_id: str) -> dict[str, Any]:
- """有界查询真实任务,任何失败均在测试中直接暴露。"""
- deadline = time.monotonic() + 15
+def _submit(
+ client: TestClient,
+ inputs: list[tuple[str, bytes]],
+ *,
+ hashes: bool = True,
+ headers: dict[str, str] | None = None,
+ **options: str | list[str],
+) -> dict[str, Any]:
+ """只用表单提交真实大小及可选 SHA-256,绝不在创建请求中发送多个文件。"""
+ manifest = [
+ {
+ "client_file_id": f"f{index + 1}",
+ "filename": name,
+ "bytes": len(data),
+ **({"sha256sum": hashlib.sha256(data).hexdigest()} if hashes else {}),
+ }
+ for index, (name, data) in enumerate(inputs)
+ ]
+ response = client.post("/v1/tasks", data={"manifest": json.dumps(manifest), "tier": "flash", **options}, headers=headers)
+ assert response.status_code == 202, response.text
+ return response.json()
+
+
+def _upload(
+ client: TestClient, task: dict[str, Any], inputs: list[tuple[str, bytes]], *, headers: dict[str, str] | None = None
+) -> None:
+ """仅上传返回链接对应的缺失文件,按 client_file_id 保持同名文件的关联。"""
+ for link in task["uploads"]:
+ index = int(link["client_file_id"][1:]) - 1
+ response = client.put(
+ link["upload_url"], content=inputs[index][1], headers={**link["upload_headers"], **(headers or {})}
+ )
+ assert response.status_code == 200, response.text
+
+
+def _terminal(client: TestClient, task: dict[str, Any], *, headers: dict[str, str] | None = None) -> dict[str, Any]:
+ """只轮询状态接口;成功前必须一直没有 result_url。"""
+ deadline = time.monotonic() + 20
while time.monotonic() < deadline:
- response = client.get(f"/v1/tasks/{task_id}/result")
- assert response.status_code in {200, 202, 409}, response.text
- if response.status_code != 202:
- return response.json()
+ response = client.get(task["status_url"], headers=headers)
+ assert response.status_code == 200, response.text
+ payload = response.json()
+ if payload["status"] in task_api.TERMINAL_TASK_STATUSES:
+ return payload
+ assert payload["result_url"] is None
time.sleep(0.01)
pytest.fail("Task did not reach a terminal state")
-def _raw(
- client: TestClient,
- data: bytes = HTML,
- *,
- name: str = "source.html",
- sha: str | None = None,
- headers: dict[str, str] | None = None,
-) -> httpx.Response:
- """提交原始字节,显式声明大小并保留调用方身份。"""
- params = {"filename": name, "tier": "flash"}
- if sha is not None:
- params["sha256sum"] = sha
- return client.post(
- "/v1/tasks", params=params, headers={"content-type": "application/octet-stream", **(headers or {})}, content=data
- )
+def _archive(client: TestClient, task: dict[str, Any]) -> dict[str, bytes]:
+ """从返回的独立 Files 链接下载并读取真实 ZIP 成员。"""
+ assert "/v1/files/" in task["result_url"]
+ response = client.get(task["result_url"])
+ assert response.status_code == 200, response.text
+ assert response.headers["content-type"] == "application/zip"
+ with zipfile.ZipFile(io.BytesIO(response.content)) as archive:
+ return {name: archive.read(name) for name in archive.namelist()}
[email protected]("source_type", ["multipart", "raw", "inline"])
-def test_task_sources_return_inline_results_and_v1_links(service: tuple[TestClient, FastAPI], source_type: str) -> None:
- """三类输入均通过真实解析并返回可直接消费的协议和 V1 链接。"""
- client, _ = service
- formats = ["markdown", "middle_json", "structured_content"]
- if source_type == "inline":
- import base64
+def _job_count(app: FastAPI) -> int:
+ """观察唯一执行队列,准备任务不应该产生 Job 或 worker 预占。"""
+ if hasattr(app.state, "job_store"):
+ return len(app.state.job_store._jobs)
+ return len(app.state.registry.list("job"))
- response = client.post(
- "/v1/tasks",
- json={
- "files": [{"source": {"type": "inline", "name": "source.html", "data": base64.b64encode(HTML).decode()}}],
- "tier": "flash",
- "output_formats": formats,
- },
- )
- elif source_type == "raw":
- response = client.post(
- "/v1/tasks",
- params=[("filename", "source.html"), ("tier", "flash"), *(("output_formats", fmt) for fmt in formats)],
- content=HTML,
- headers={"content-type": "application/octet-stream"},
- )
- else:
- response = client.post(
- "/v1/tasks",
- params=[("tier", "flash"), *(("output_formats", fmt) for fmt in formats)],
- files={"files": ("source.html", HTML, "text/html")},
- )
- assert response.status_code == 202, response.text
- task = response.json()
- assert "job_id" not in task
- assert task["status_url"] == f"/v1/tasks/{task['task_id']}"
- assert task["result_url"] == f"/v1/tasks/{task['task_id']}/result"
- assert task["links"]["cancel"] == task["status_url"]
- result = _terminal(client, task["task_id"])
- assert result["status"] == "completed", result
- content = result["files"][0]["content"]
- assert "Preserved content" in content["markdown"]
- assert content["middle_json"]["schema"] == "docvortex.middle"
- assert content["structured_content"]["pages"][0]["page_idx"] == 0
+
[email protected]("hashes", [False, True])
+def test_manifest_uploads_and_zip_only_status(service: tuple[TestClient, FastAPI], hashes: bool) -> None:
+ """单文件与批量都经过共同协议,状态只给元数据,ZIP 保留输入次序。"""
+ client, app = service
+ inputs = [("同名 文档.html", HTML), ("同名 文档.html", SECOND)]
+ task = _submit(client, inputs, hashes=hashes, output_formats=["markdown", "middle_json"])
+ assert task["status"] == "waiting_upload" and task["result_url"] is None
+ assert len(task["uploads"]) == 2 and _job_count(app) == 0
+ if hasattr(app.state, "worker_pool"):
+ assert [worker.active_jobs for worker in app.state.worker_pool.workers] == [0, 0]
+ first = client.put(task["uploads"][0]["upload_url"], content=HTML)
+ assert first.status_code == 200
+ ready = client.get(task["status_url"]).json()
+ assert ready["status"] == "waiting_upload"
+ assert [file["upload_status"] for file in ready["files"]] == ["ready", "pending"]
+ assert [link["client_file_id"] for link in ready["uploads"]] == ["f2"]
+ assert _job_count(app) == 0
+ _upload(client, ready, inputs)
+ result = _terminal(client, task)
+ assert result["status"] == "completed"
+ assert result["task_id"] == task["task_id"] and _job_count(app) == 1
+ assert all("content" not in file for file in result["files"])
+ assert client.get(f"/v1/parse/jobs/{task['task_id']}").json()["job_id"] == task["task_id"]
+ members = _archive(client, result)
+ assert b"Preserved content" in members["0001/markdown.md"]
+ assert b"Second content" in members["0002/markdown.md"]
+ manifest = json.loads(members["manifest.json"])
+ assert manifest["status"] == "completed"
+ assert [item["client_file_id"] for item in manifest["files"]] == ["f1", "f2"]
+ assert [item["directory"] for item in manifest["files"]] == ["0001/", "0002/"]
+ assert "task_id" not in manifest
+ assert all("file_id" not in item and "output_files" not in item for item in manifest["files"])
+ assert json.loads(members["0001/middle_json.json"])["schema"] == "docvortex.middle"
+ assert client.get(f"/v1/tasks/{task['task_id']}/result").status_code == 404
+ assert client.post("/v1/file_parse").status_code == 404
assert client.post("/tasks").status_code == 404
- assert client.post("/file_parse").status_code == 404
+ assert client.get(f"/v1/files/{result['files'][0]['file_id']}/content").status_code == 403
-def test_sync_defaults_and_zip_wrap_the_same_job(service: tuple[TestClient, FastAPI]) -> None:
- """省略 tier 的 HTML 自动使用 Flash,同步 ZIP 来自同一份任务产物。"""
- client, _ = service
- response = client.post("/v1/file_parse", files={"files": ("source.html", HTML)})
- assert response.status_code == 200, response.text
- task_id = response.json()["task_id"]
- job = client.get(f"/v1/parse/jobs/{task_id}")
- assert job.status_code == 200
- assert job.json()["job_id"] == task_id
- assert "Shared tasks" in response.json()["files"][0]["content"]["markdown"]
- archive = client.post("/v1/file_parse?response_format=zip&tier=flash", files={"files": ("source.html", HTML)})
- assert archive.status_code == 200, archive.text
- assert archive.headers["content-type"] == "application/zip"
- with zipfile.ZipFile(io.BytesIO(archive.content)) as zf:
- assert "middle_json.json" in zf.namelist()
- missing = client.get(f"/v1/tasks/{task_id}/result?response_format=zip")
- assert missing.status_code == 400
-
-
-def test_file_id_reuse_and_source_download_boundary(service: tuple[TestClient, FastAPI]) -> None:
- """新入口的源文件可被 V1 和便捷入口复用,仍不能公开下载。"""
- client, _ = service
- first = _terminal(client, _raw(client).json()["task_id"])
- file_id = first["files"][0]["file_id"]
- body = {"files": [{"source": {"type": "file_id", "file_id": file_id}}], "tier": "flash"}
- for route in ("/v1/file_parse", "/v1/parse/jobs"):
- response = client.post(route, json=body)
- assert response.status_code in {200, 202}, response.text
- assert client.get(f"/v1/files/{file_id}/content").status_code == 403
[email protected]("hashes", [False, True])
+def test_single_multipart_is_asynchronous_and_checks_hash(service: tuple[TestClient, FastAPI], hashes: bool) -> None:
+ """单文件直传保留便利性,实际发送的字节必须经过 hash 检查。"""
+ client, app = service
+ form: dict[str, Any] = {"tier": "flash"}
+ if hashes:
+ form["manifest"] = json.dumps(
+ [
+ {
+ "client_file_id": "f1",
+ "filename": "logical.html",
+ "bytes": len(HTML),
+ "sha256sum": hashlib.sha256(HTML).hexdigest(),
+ }
+ ]
+ )
+ response = client.post("/v1/tasks", data=form, files={"files": ("source.html", HTML)})
+ assert response.status_code == 202, response.text
+ result = _terminal(client, response.json())
+ assert result["status"] == "completed"
+ assert result["files"][0]["filename"] == ("logical.html" if hashes else "source.html")
+ assert b"Shared tasks" in _archive(client, result)["markdown.md"]
+ before = _job_count(app)
+ invalid = client.post(
+ "/v1/tasks",
+ data={
+ "manifest": json.dumps(
+ [
+ {
+ "client_file_id": "f1",
+ "filename": "source.html",
+ "bytes": len(HTML),
+ "sha256sum": hashlib.sha256(HTML).hexdigest(),
+ }
+ ]
+ )
+ },
+ files={"files": ("source.html", HTML.replace(b"Shared", b"Broken"))},
+ )
+ assert invalid.status_code == 400 and invalid.json()["error"]["code"] == "file_hash_mismatch"
+ assert _job_count(app) == before
class _UnreadableBody(httpx.SyncByteStream):
- """缓存命中时读取主体应立即导致测试失败。"""
+ """重复上传已确认文件时,读取主体应立即使测试失败。"""
def __iter__(self) -> Iterator[bytes]:
- """拒绝任何主体读取,验证提前返回并非上传后去重。"""
- raise AssertionError("Cached source body must not be read")
+ """验证服务端幂等返回,既不覆盖已确认字节也不读取重传主体。"""
+ raise AssertionError("Ready file body must not be read")
yield b"" # pragma: no cover
-def test_hash_hit_skips_body_and_preserves_new_filename(service: tuple[TestClient, FastAPI]) -> None:
- """命中哈希时无需发送主体,而且文件名视图不会沿用旧文件名。"""
- client, _ = service
- first = _raw(client)
- assert first.status_code == 202
- _terminal(client, first.json()["task_id"])
- response = client.post(
- "/v1/tasks",
- params={"filename": "renamed.html", "tier": "flash", "sha256sum": hashlib.sha256(HTML).hexdigest()},
- headers={"content-type": "application/octet-stream", "content-length": str(len(HTML)), "expect": "100-continue"},
- content=_UnreadableBody(),
- )
- assert response.status_code == 202, response.text
- assert response.headers["connection"] == "close"
- result = _terminal(client, response.json()["task_id"])
- assert result["files"][0]["name"] == "renamed.html"
-
-
-def test_hash_size_errors_do_not_create_jobs(service: tuple[TestClient, FastAPI], monkeypatch: pytest.MonkeyPatch) -> None:
- """错误哈希、声明大小与大小上限均在任务创建前被拒绝。"""
+def test_mixed_cache_hit_survives_source_deletion(service: tuple[TestClient, FastAPI]) -> None:
+ """命中项在等待其他文件时持有独立引用,原源文件删除不导致缓存竞态。"""
client, app = service
- assert _raw(client, sha="0" * 64).status_code == 400
- assert _raw(client, sha="invalid").status_code == 400
- initial = _raw(client)
- assert initial.status_code == 202
- result = _terminal(client, initial.json()["task_id"])
- wrong_size = client.post(
- "/v1/tasks",
- params={"filename": "source.html", "tier": "flash", "sha256sum": hashlib.sha256(HTML).hexdigest()},
- headers={"content-type": "application/octet-stream", "content-length": str(len(HTML) + 1)},
+ initial = _submit(client, [("original.html", HTML)])
+ _upload(client, initial, [("original.html", HTML)])
+ original = _terminal(client, initial)
+ inputs = [("renamed.html", HTML), ("new.html", SECOND)]
+ task = _submit(client, inputs)
+ assert [link["client_file_id"] for link in task["uploads"]] == ["f2"]
+ assert task["files"][0]["upload_status"] == "ready"
+ assert client.delete(f"/v1/files/{original['files'][0]['file_id']}").status_code == 200
+ duplicate = client.put(
+ f"/v1/tasks/{task['task_id']}/uploads/f1",
content=_UnreadableBody(),
+ headers={"content-length": str(len(HTML)), "expect": "100-continue"},
)
- assert wrong_size.status_code == 400
- monkeypatch.setattr(task_api, "MAX_TASK_FILE_BYTES", 8)
- assert _raw(client).status_code == 413
- count = len(app.state.job_store._jobs) if hasattr(app.state, "job_store") else len(app.state.registry.list("job"))
- assert count == 1
- assert result["status"] == "completed"
+ assert duplicate.status_code == 200 and duplicate.headers["connection"] == "close"
+ _upload(client, task, inputs)
+ result = _terminal(client, task)
+ assert result["status"] == "completed" and result["files"][0]["name"] == "renamed.html"
+ cached = _submit(client, inputs)
+ assert cached["uploads"] == [] and cached["status"] == "queued"
+ assert _terminal(client, cached)["status"] == "completed"
+ assert _job_count(app) == 3
+
+
+def test_no_hash_still_deduplicates_source_storage(service: tuple[TestClient, FastAPI]) -> None:
+ """不发送 hash 时仍计算实际内容标识,相同内容只保留一份源字节。"""
+ client, app = service
+ first = _submit(client, [("first.html", HTML)], hashes=False)
+ _upload(client, first, [("first.html", HTML)])
+ assert _terminal(client, first)["status"] == "completed"
+ second = _submit(client, [("second.html", HTML)], hashes=False)
+ assert len(second["uploads"]) == 1
+ _upload(client, second, [("second.html", HTML)])
+ assert _terminal(client, second)["status"] == "completed"
+ records = app.state.task_store._records
+ assert records[first["task_id"]].uploads[0].path == records[second["task_id"]].uploads[0].path
+
+
+def test_waiting_upload_retains_deleted_source_views(service: tuple[TestClient, FastAPI]) -> None:
+ """等待其他文件期间删除源视图,不影响任务已经取得的字节引用。"""
+ client, app = service
+ inputs = [("a.html", HTML), ("b.html", SECOND)]
+ task = _submit(client, inputs, hashes=False)
+ assert client.put(task["uploads"][0]["upload_url"], content=HTML).status_code == 200
+ record = app.state.task_store._records[task["task_id"]]
+ if hasattr(app.state, "file_store"):
+ file_id = record.uploads[0].file_id
+ assert app.state.file_store.get_file(file_id).expires_at is None
+ assert client.delete(f"/v1/files/{file_id}").status_code == 200
+ else:
+ app.state.source_store.delete_file(record.backend._owned_files[0])
+ assert record.uploads[0].path.is_file()
+ assert client.put(task["uploads"][1]["upload_url"], content=SECOND).status_code == 200
+ result = _terminal(client, task)
+ assert result["status"] == "completed", result
+ assert b"Preserved content" in _archive(client, result)["0001/markdown.md"]
-def test_partial_and_duplicate_names_have_distinct_zip_directories(service: tuple[TestClient, FastAPI]) -> None:
- """批量同名与部分失败均保留输入顺序,ZIP manifest 不隐藏错误。"""
- client, _ = service
- response = client.post(
- "/v1/file_parse?response_format=zip&tier=flash&ocr_mode=txt",
- files=[
- ("files", ("same.html", HTML)),
- ("files", ("same.html", b"<p>Second file</p>")),
- ("files", ("broken.pdf", b"not a pdf")),
- ],
- )
+def test_failed_upload_can_retry_without_reuploading_ready_file(service: tuple[TestClient, FastAPI]) -> None:
+ """一个文件校验失败只影响该项,其他成功文件保持 ready 且不提前创建 Job。"""
+ client, app = service
+ inputs = [("a.html", HTML), ("b.html", SECOND)]
+ task = _submit(client, inputs)
+ assert client.put(task["uploads"][0]["upload_url"], content=HTML).status_code == 200
+ failed = client.put(task["uploads"][1]["upload_url"], content=SECOND.replace(b"Second", b"Broken"))
+ assert failed.status_code == 400 and failed.json()["error"]["code"] == "file_hash_mismatch"
+ mismatch = client.put(task["uploads"][1]["upload_url"], content=SECOND + b"x")
+ assert mismatch.status_code == 400 and mismatch.json()["error"]["code"] == "upload_size_mismatch"
+ pending = client.get(task["status_url"]).json()
+ assert pending["status"] == "waiting_upload" and _job_count(app) == 0
+ assert [file["upload_status"] for file in pending["files"]] == ["ready", "pending"]
+ assert list(app.state.task_store._records[task["task_id"]].directory.iterdir()) == []
+ _upload(client, pending, inputs)
+ assert _terminal(client, task)["status"] == "completed" and _job_count(app) == 1
+
+
+def test_concurrent_last_uploads_and_duplicate_put_submit_once(service: tuple[TestClient, FastAPI]) -> None:
+ """并发上传与重复 PUT 共用提交门闩,批量文件只产生一个 Job。"""
+ client, app = service
+ task = _submit(client, [("a.html", HTML), ("b.html", SECOND)])
+
+ async def upload_all() -> list[httpx.Response]:
+ """在服务所属事件循环同时发起两个文件及同一文件的重复请求。"""
+ async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://testserver") as asynchronous:
+ return await asyncio.gather(
+ asynchronous.put(task["uploads"][0]["upload_url"], content=HTML),
+ asynchronous.put(task["uploads"][1]["upload_url"], content=SECOND),
+ asynchronous.put(task["uploads"][1]["upload_url"], content=SECOND),
+ )
+
+ responses = client.portal.call(upload_all)
+ assert all(response.status_code == 200 for response in responses)
+ assert _terminal(client, task)["status"] == "completed"
+ assert _job_count(app) == 1
+ if hasattr(app.state, "worker_pool"):
+ assert sum(worker.active_jobs for worker in app.state.worker_pool.workers) == 0
+
+
+def test_cancel_and_expire_waiting_upload_release_inputs(service: tuple[TestClient, FastAPI]) -> None:
+ """取消和过期不需要 worker,准备阶段保存的文件视图及引用都被释放。"""
+ client, app = service
+ for expired in (False, True):
+ task = _submit(client, [("a.html", HTML), ("b.html", SECOND)])
+ assert client.put(task["uploads"][0]["upload_url"], content=HTML).status_code == 200
+ record = app.state.task_store._records[task["task_id"]]
+ if expired:
+ record.expires_at = int(time.time()) - 1
+ response = client.get(task["status_url"])
+ assert response.json()["error"]["code"] == "upload_expired"
+ else:
+ response = client.delete(task["status_url"])
+ assert response.status_code == 200
+ assert response.json()["status"] == ("failed" if expired else "canceled")
+ assert response.json()["uploads"] == [] and _job_count(app) == 0
+ assert not record.directory.exists()
+ assert record.backend._owned_files == []
+ assert client.put(task["uploads"][1]["upload_url"], content=SECOND).status_code == 409
+
+
+def test_cancel_running_task_releases_execution_slot(
+ service: tuple[TestClient, FastAPI], monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """运行任务取消经过同一执行队列,HTTP 返回后不存在重复预占或悬挂解析。"""
+ client, app = service
+ started = threading.Event()
+
+ async def blocked_parse(*args: Any, **kwargs: Any) -> None:
+ """保持真实后台解析句柄可取消,避免依赖 GPU 或定时竞态。"""
+ started.set()
+ await asyncio.Event().wait()
+
+ monkeypatch.setattr(api_server, "parse_async", blocked_parse)
+ task = _submit(client, [("a.html", HTML)])
+ _upload(client, task, [("a.html", HTML)])
+ assert started.wait(5)
+ response = client.delete(task["status_url"])
assert response.status_code == 200, response.text
- with zipfile.ZipFile(io.BytesIO(response.content)) as zf:
- manifest = json.loads(zf.read("manifest.json"))
- assert manifest["status"] == "partial"
- assert manifest["files"][2]["error"]
- assert any(name.startswith("0001/") for name in zf.namelist())
- assert any(name.startswith("0002/") for name in zf.namelist())
- assert not any(name.startswith("0003/") for name in zf.namelist())
+ assert response.json()["status"] == "canceled"
+ assert client.get(task["status_url"]).json()["result_url"] is None
+ deadline = time.monotonic() + 5
+ operation = app.state.task_store._records[task["task_id"]].operation
+ while operation is not None and not operation.done():
+ assert time.monotonic() < deadline
+ time.sleep(0.01)
+ if hasattr(app.state, "worker_pool"):
+ assert sum(worker.active_jobs for worker in app.state.worker_pool.workers) == 0
+ else:
+ assert not app.state.job_store._tasks
-def test_sync_timeout_leaves_one_background_task(service: tuple[TestClient, FastAPI], monkeypatch: pytest.MonkeyPatch) -> None:
- """等待超时返回同一任务,该任务随后继续完成且不会重复解析。"""
+def test_status_never_reads_or_rebuilds_zip(service: tuple[TestClient, FastAPI], monkeypatch: pytest.MonkeyPatch) -> None:
+ """批量 ZIP 在后台只构建一次,状态与流式下载均不调用整包读取方法。"""
client, _ = service
- release = threading.Event()
- original = api_server.parse_async
+ combine = task_api._combine_archives
calls = 0
- async def delayed(*args: Any, **kwargs: Any) -> Any:
- """通过可控闸门模拟超过等待预算的真实解析。"""
+ def counted(*args: Any, **kwargs: Any) -> str:
+ """统计实际后台打包次数,确认多次查询及下载不重新构建。"""
nonlocal calls
calls += 1
- while not release.is_set():
- await asyncio.sleep(0.01)
- return await original(*args, **kwargs)
-
- monkeypatch.setattr(api_server, "parse_async", delayed)
- try:
- response = client.post("/v1/file_parse?wait_timeout=1&tier=flash", files={"files": ("source.html", HTML)})
- assert response.status_code == 202, response.text
- task_id = response.json()["task_id"]
- assert response.json()["status_url"] == f"/v1/tasks/{task_id}"
- finally:
- release.set()
- assert _terminal(client, task_id)["status"] == "completed"
+ return combine(*args, **kwargs)
+
+ monkeypatch.setattr(task_api, "_combine_archives", counted)
+ inputs = [("a.html", HTML), ("b.html", SECOND)]
+ task = _submit(client, inputs)
+ _upload(client, task, inputs)
+ result = _terminal(client, task)
+ assert result["status"] == "completed" and calls == 1
+
+ def forbid_read(*args: Any, **kwargs: Any) -> bytes:
+ """完成后的状态与下载必须使用元数据或文件流,禁止 read_blob 整包读取。"""
+ raise AssertionError("Result body was read into memory")
+
+ monkeypatch.setattr(api_server.FileStore, "read_blob", forbid_read)
+ monkeypatch.setattr(api_server.FileStore, "read_file_data", forbid_read)
+ for _ in range(3):
+ assert client.get(task["status_url"]).json()["result_url"] == result["result_url"]
+ assert "manifest.json" in _archive(client, result)
assert calls == 1
-def test_query_errors_and_openapi_match(service: tuple[TestClient, FastAPI]) -> None:
- """校验输入预算和公开文档,包括三种内容类型及完整 V1 前缀。"""
+def test_partial_and_packaging_failure_have_honest_results(
+ service: tuple[TestClient, FastAPI], monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """部分解析成功保留错误,打包失败不能发布 completed 或虚假的下载链接。"""
client, _ = service
- for query in ("wait_timeout=0", "wait_timeout=3601", "response_format=unsupported"):
- response = client.post(f"/v1/file_parse?{query}", json={"files": []})
+ inputs = [("same.html", HTML), ("broken.pdf", b"not a pdf")]
+ task = _submit(client, inputs)
+ _upload(client, task, inputs)
+ result = _terminal(client, task)
+ assert result["status"] == "partial" and result["files"][1]["error"]
+ members = _archive(client, result)
+ assert json.loads(members["manifest.json"])["status"] == "partial"
+ assert not any(name.startswith("0002/") for name in members)
+
+ def fail_packaging(*args: Any, **kwargs: Any) -> str:
+ """模拟 ZIP 落盘失败,执行状态必须反映产物不可用。"""
+ raise OSError("simulated full disk")
+
+ monkeypatch.setattr(task_api, "_combine_archives", fail_packaging)
+ good = [("a.html", HTML), ("b.html", SECOND)]
+ task = _submit(client, good)
+ _upload(client, task, good)
+ failed = _terminal(client, task)
+ assert failed["status"] == "failed" and failed["result_url"] is None
+ assert failed["error"]["code"] == "result_packaging_failed"
+
+
+def test_input_validation_and_openapi(service: tuple[TestClient, FastAPI]) -> None:
+ """新协议只接受表单和单文件直传,OpenAPI 不再宣传旧入口及大小限制。"""
+ client, app = service
+ valid = {"client_file_id": "f1", "filename": "a.html", "bytes": len(HTML)}
+ for manifest in (
+ [],
+ [valid] * 2,
+ [valid] * 101,
+ [{**valid, "bytes": 0}],
+ [{**valid, "sha256sum": "invalid"}],
+ [{**valid, "page_range": "invalid"}],
+ ):
+ response = client.post("/v1/tasks", data={"manifest": json.dumps(manifest)})
assert response.status_code == 400, response.text
- spec = client.get("/openapi.json").json()
- for path in ("/v1/tasks", "/v1/tasks/{task_id}", "/v1/tasks/{task_id}/result", "/v1/file_parse"):
- assert path in spec["paths"]
- schema = spec["paths"]["/v1/tasks"]["post"]["requestBody"]["content"]
- assert set(schema) == {"application/json", "multipart/form-data", "application/octet-stream"}
- assert "#/$defs/" not in json.dumps(schema)
- assert "application/zip" in spec["paths"]["/v1/file_parse"]["post"]["responses"]["200"]["content"]
- task_api.TaskStatusResponse.model_validate(_raw(client).json())
-
-
-def test_invalid_ranges_empty_and_too_many_uploads(service: tuple[TestClient, FastAPI]) -> None:
- """输入数量和页范围在两端均返回明确的 V1 错误,不进入解析。"""
- client, _ = service
for response in (
- client.post("/v1/tasks?page_range=invalid", files={"files": ("source.html", HTML)}),
- client.post("/v1/tasks", files={"files": ("source.html", b"")}),
- client.post("/v1/tasks", files=[("files", (f"file-{index}.html", b"x")) for index in range(101)]),
- client.post("/v1/tasks", files={"unknown": ("source.html", HTML)}),
+ client.post("/v1/tasks?tier=flash", data={"manifest": json.dumps([valid])}),
+ client.post("/v1/tasks", files=[("files", ("a.html", HTML)), ("files", ("b.html", SECOND))]),
+ client.post(
+ "/v1/tasks",
+ data={"manifest": json.dumps([valid, {**valid, "client_file_id": "f2"}])},
+ files={"files": ("a.html", HTML)},
+ ),
+ client.post("/v1/tasks", files={"files": ("a.html", b"")}),
+ client.post("/v1/tasks", data={"manifest": json.dumps([valid]), "wait_timeout": "300"}),
):
assert response.status_code == 400, response.text
- assert response.json()["error"]["code"]
-
-
-def test_cancellation_and_failed_results_are_terminal(
- service: tuple[TestClient, FastAPI], monkeypatch: pytest.MonkeyPatch
-) -> None:
- """取消使用共享 Job,失败结果不被误报成 200 或重新提交。"""
- client, _ = service
- release = threading.Event()
- original = api_server.parse_async
-
- async def delayed(*args: Any, **kwargs: Any) -> Any:
- """保持解析运行,以便通过公开取消接口验证后台任务归属。"""
- while not release.is_set():
- await asyncio.sleep(0.01)
- return await original(*args, **kwargs)
-
- monkeypatch.setattr(api_server, "parse_async", delayed)
- try:
- task = _raw(client).json()
- canceled = client.delete(task["status_url"])
- assert canceled.status_code == 200, canceled.text
- assert canceled.json()["status"] == "canceled"
- result = client.get(task["result_url"])
- assert result.status_code == 409
- assert result.json()["status"] == "canceled"
- assert client.delete(task["status_url"]).status_code == 409
- finally:
- release.set()
- monkeypatch.setattr(api_server, "parse_async", original)
- failed = client.post("/v1/file_parse?tier=flash&ocr_mode=txt", files={"files": ("broken.pdf", b"broken")})
- assert failed.status_code == 409, failed.text
- assert failed.json()["status"] == "failed"
- assert failed.json()["files"][0]["error"]
-
-
-def test_router_cached_uploads_keep_scope_and_alias_references(tmp_path: Path) -> None:
- """Router 秒传隔离身份;删除旧别名后新别名仍支持跨 worker 复制。"""
- workers = {host: api_server.create_app(upload_dir=str(tmp_path / host), tier="flash") for host in ("worker-a", "worker-b")}
+ assert client.post("/v1/tasks", json={"files": []}).status_code == 415
+ assert client.post("/v1/tasks", content=HTML, headers={"content-type": "application/octet-stream"}).status_code == 415
+ assert _job_count(app) == 0
+ spec = client.get("/openapi.json").json()
+ assert "/v1/file_parse" not in spec["paths"]
+ assert "/v1/tasks/{task_id}/result" not in spec["paths"]
+ creation = spec["paths"]["/v1/tasks"]["post"]
+ assert not creation.get("parameters")
+ assert set(creation["requestBody"]["content"]) == {"application/x-www-form-urlencoded", "multipart/form-data"}
+ assert "209715200" not in json.dumps(creation)
+ limits = client.get("/v1/usage").json()["limits"]
+ assert limits["max_file_size_bytes"] is None and limits["max_pages_per_file"] is None
+ assert limits["max_files_per_job"] == 100
+
+
+def test_router_private_hash_cache_and_task_scope(tmp_path: Path) -> None:
+ """Router 的缓存、任务与文件地址均隔离调用方,不能仅凭已知 hash 使用他人输入。"""
+ workers = {"worker-a": api_server.create_app(upload_dir=str(tmp_path / "worker"), tier="flash")}
app = create_router(
- RouterSettings(
- upstream_urls=tuple(f"http://{host}" for host in workers), local_gpus="none", worker_refresh_interval_seconds=0
- ),
+ RouterSettings(upstream_urls=("http://worker-a",), local_gpus="none", worker_refresh_interval_seconds=0),
transport=_WorkerTransport(workers),
)
- headers = {"authorization": "Bearer tenant-a"}
with TestClient(app) as client:
- task = _raw(client, headers=headers).json()
- deadline = time.monotonic() + 10
- while time.monotonic() < deadline:
- result = client.get(task["result_url"], headers=headers)
- if result.status_code == 200:
- break
- time.sleep(0.01)
- first_id = result.json()["files"][0]["file_id"]
- body = {
- "filename": "renamed.html",
- "bytes": len(HTML),
- "mime_type": "text/html",
- "sha256sum": hashlib.sha256(HTML).hexdigest(),
- }
- reused = client.post("/v1/uploads", headers=headers, json=body)
- assert reused.status_code == 200, reused.text
- assert reused.json()["status"] == "completed"
- second_id = reused.json()["file"]["id"]
- assert client.post("/v1/uploads", headers={"authorization": "Bearer tenant-b"}, json=body).json()["status"] == "pending"
- assert client.get(task["status_url"], headers={"authorization": "Bearer tenant-b"}).status_code == 404
- assert client.delete(f"/v1/files/{first_id}", headers=headers).status_code == 200
- stored = app.state.source_store.find_file(second_id)
- assert stored is not None and stored.path.is_file()
- parsed = client.post(
- "/v1/file_parse",
- headers=headers,
- json={"tier": "flash", "files": [{"source": {"type": "file_id", "file_id": second_id}}]},
- )
- assert parsed.status_code == 200, parsed.text
- assert "Preserved content" in parsed.json()["files"][0]["content"]["markdown"]
-
-
-def test_api_source_registration_cancel_rolls_back_view(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
- """磁盘线程完成时 HTTP 已取消,预先分配的源文件视图仍必须回滚。"""
- app = api_server.create_app(upload_dir=str(tmp_path / "api"), tier="flash")
- source = tmp_path / "source.html"
- source.write_bytes(HTML)
- entered, release = threading.Event(), threading.Event()
- original = api_server.FileStore.register_source_file
-
- def delayed(store: api_server.FileStore, filename: str, path: Path, sha256sum: str, file_id: str | None = None) -> str:
- """在线程注册完成后阻塞返回,复现取消时丢失返回 ID 的窗口。"""
- result = original(store, filename, path, sha256sum, file_id)
- entered.set()
- release.wait(5)
- return result
-
- monkeypatch.setattr(api_server.FileStore, "register_source_file", delayed)
-
- async def run() -> None:
- """取消提交方并等待线程清理,检查文件与任务索引。"""
- backend = task_api.ApiTaskBackend(Request({"type": "http", "app": app, "headers": []}))
- body = api_server.CreateJobRequest(
- files=[api_server.JobFileEntry(source=api_server.FileIdSource(file_id="pending"))], tier="flash"
- )
- work = asyncio.create_task(
- backend.submit(body, {0: task_api.TaskUpload(source, source.name, len(HTML), hashlib.sha256(HTML).hexdigest())})
- )
- while not entered.is_set():
- await asyncio.sleep(0.01)
- work.cancel()
- release.set()
- with pytest.raises(asyncio.CancelledError):
- await work
- assert not app.state.file_store._files
- assert not app.state.job_store._jobs
- await app.state.job_store.shutdown()
-
- asyncio.run(run())
+ owner, stranger = {"authorization": "Bearer owner"}, {"authorization": "Bearer stranger"}
+ task = _submit(client, [("a.html", HTML)], headers=owner)
+ _upload(client, task, [("a.html", HTML)], headers=owner)
+ result = _terminal(client, task, headers=owner)
+ assert client.get(task["status_url"], headers=stranger).status_code == 404
+ assert client.get(result["result_url"], headers=stranger).status_code == 404
+ other = _submit(client, [("a.html", HTML)], headers=stranger)
+ assert len(other["uploads"]) == 1
+ assert client.delete(other["status_url"], headers=stranger).status_code == 200
+ owned = _submit(client, [("a.html", HTML)], headers=owner)
+ assert not owned["uploads"]
+ assert _terminal(client, owned, headers=owner)["status"] == "completed"
+
+
[email protected]("root", ["", "/mineru"])
+def test_task_links_respect_proxy_root(tmp_path: Path, root: str) -> None:
+ """状态、上传与结果链接全部携带部署前缀,客户端不用重建任何地址。"""
+ app = api_server.create_app(upload_dir=str(tmp_path), tier="flash", api_key="secret")
+ with TestClient(app, root_path=root, headers={"Authorization": "Bearer secret"}) as client:
+ manifest = [{"client_file_id": "f1", "filename": "a.html", "bytes": len(HTML)}]
+ response = client.post(root + "/v1/tasks", data={"manifest": json.dumps(manifest), "tier": "flash"})
+ assert response.status_code == 202
+ task = response.json()
+ assert task["status_url"].startswith("http://testserver" + root + "/v1/tasks/")
+ _upload(client, task, [("a.html", HTML)])
+ result = _terminal(client, task)
+ assert result["result_url"].startswith("http://testserver" + root + "/v1/files/")
+ assert "markdown.md" in _archive(client, result)
diff --git a/tests/unittest/test_task_http.py b/tests/unittest/test_task_http.py
index 7bfcbc2e..70c1517e 100644
--- a/tests/unittest/test_task_http.py
+++ b/tests/unittest/test_task_http.py
@@ -1,4 +1,4 @@
-"""使用真实 TCP、curl 和两个 API worker 验证上传省流量及产物一致性。"""
+"""真实 TCP、客户端脚本及隔离 SaaS/OSS 模拟服务的共同协议验收。"""
from __future__ import annotations
@@ -7,251 +7,633 @@ import hashlib
import io
import json
import os
-import shutil
import socket
import subprocess
+import sys
import threading
import time
import zipfile
from collections.abc import Iterator
+from dataclasses import dataclass, field
from pathlib import Path
from typing import Any
-from urllib.parse import urlencode, urlsplit
+from urllib.parse import urlsplit
import httpx
import pytest
+from fastapi import FastAPI, Request, Response
+from fastapi.responses import JSONResponse, RedirectResponse
+from pypdf import PdfWriter
+from starlette.types import ASGIApp, Message, Receive, Scope, Send
from test_http_api_example_script import _Server
from mineru.kit.router import RouterSettings
from mineru.kit.router import create_app as create_router
from mineru.parser import api_server
-from mineru.parser.api_server import create_app
+from mineru.utils.async_utils import run_sync
+
+SCRIPT = Path(__file__).resolve().parents[2] / "scripts" / "http_task_example.sh"
+HTML = b"<h1>HTTP tasks</h1><p>Same source and output.</p>"
+TERMINAL = {"completed", "partial", "failed", "canceled"}
+
+
+class _UploadCounter:
+ """统计真实 ASGI 收到的逐文件字节,区分文件上传与元数据预检。"""
+
+ def __init__(self, app: ASGIApp, counts: dict[str, int]) -> None:
+ """使用外部计数表,测试可以在断连前确认部分主体已被消费。"""
+ self.app = app
+ self.counts = counts
+
+ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
+ """只统计 PUT 主体,不改变服务器的接收时序或断连信号。"""
+
+ async def counted_receive() -> Message:
+ """记录真实网络块,再原样传递给服务端上传逻辑。"""
+ message = await receive()
+ if message["type"] == "http.request":
+ path = scope["path"]
+ self.counts[path] = self.counts.get(path, 0) + len(message.get("body", b""))
+ return message
+
+ if scope["type"] == "http" and scope["method"] == "PUT":
+ await self.app(scope, counted_receive, send)
+ else:
+ await self.app(scope, receive, send)
+
+
+@dataclass
+class _LiveService:
+ """保留真实网络地址与应用对象,便于核对上传量和唯一任务记录。"""
+
+ url: str
+ app: FastAPI
+ counts: dict[str, int]
@pytest.fixture(params=["api", "router"])
-def live_service(request: pytest.FixtureRequest, tmp_path: Path) -> Iterator[str]:
- """通过真实 Uvicorn 提供直接服务或双 worker Router。"""
+def live_service(request: pytest.FixtureRequest, tmp_path: Path) -> Iterator[_LiveService]:
+ """启动真实 Uvicorn 服务;Router 的两个 worker 同样使用真实 TCP。"""
servers: list[_Server] = []
try:
if request.param == "api":
- service = _Server(create_app(upload_dir=str(tmp_path / "api"), tier="flash", api_key="test-key"))
+ app = api_server.create_app(upload_dir=str(tmp_path / "api"), tier="flash", api_key="test-key")
else:
for index in range(2):
- worker = _Server(create_app(upload_dir=str(tmp_path / f"worker-{index}"), tier="flash", api_key="test-key"))
+ worker = _Server(
+ api_server.create_app(upload_dir=str(tmp_path / f"worker-{index}"), tier="flash", api_key="test-key")
+ )
worker.start()
servers.append(worker)
- service = _Server(
- create_router(
- RouterSettings(
- upstream_urls=tuple(worker.url for worker in servers),
- local_gpus="none",
- worker_refresh_interval_seconds=0,
- )
+ app = create_router(
+ RouterSettings(
+ upstream_urls=tuple(server.url for server in servers),
+ local_gpus="none",
+ worker_refresh_interval_seconds=0,
)
)
- service.start()
- servers.append(service)
- yield service.url
+ counts: dict[str, int] = {}
+ app.add_middleware(_UploadCounter, counts=counts)
+ server = _Server(app)
+ server.start()
+ servers.append(server)
+ yield _LiveService(server.url, app, counts)
finally:
for server in reversed(servers):
server.stop()
-def _wait(client: httpx.Client, task_id: str) -> dict:
- """通过真实 HTTP 有界查询任务结果。"""
- deadline = time.monotonic() + 20
- while time.monotonic() < deadline:
- response = client.get(f"/v1/tasks/{task_id}/result")
- assert response.status_code in {200, 202}, response.text
- if response.status_code == 200:
- return response.json()
- time.sleep(0.01)
- pytest.fail("HTTP task did not complete")
-
-
[email protected](shutil.which("curl") is None, reason="curl is required for real upload accounting")
-def test_expect_continue_skips_bytes_and_checks_auth(live_service: str, tmp_path: Path) -> None:
- """curl 未命中时实际上传、命中时上传量为零,并经过真实鉴权。"""
- source = tmp_path / "source.html"
- data = b"<h1>Upload accounting</h1><p>" + b"content " * 32000 + b"</p>"
- source.write_bytes(data)
- query = urlencode({"filename": source.name, "sha256sum": hashlib.sha256(data).hexdigest(), "tier": "flash"})
- result_path = tmp_path / "result.json"
- command = [
- "curl",
- "--silent",
- "--show-error",
- "--http1.1",
- "--max-time",
- "20",
- "--expect100-timeout",
- "5",
- "-H",
- "Expect: 100-continue",
- "-H",
- "Content-Type: application/octet-stream",
- "-H",
- "Authorization: Bearer test-key",
- "-X",
- "POST",
- "--upload-file",
- str(source),
- "--output",
- str(result_path),
- "--write-out",
- "%{http_code} %{size_upload}",
- f"{live_service}/v1/tasks?{query}",
+def _client(service: _LiveService) -> httpx.Client:
+ """每个请求经过真实 HTTP 与已配置的 API Key,禁用外部代理环境。"""
+ return httpx.Client(base_url=service.url, headers={"Authorization": "Bearer test-key"}, timeout=90, trust_env=False)
+
+
+def _submit(client: httpx.Client, files: list[tuple[str, bytes]], *, hashes: bool = True, **options: Any) -> dict[str, Any]:
+ """以表单提交文件清单,hash 缺省时不放入任何替代标识。"""
+ manifest = [
+ {
+ "client_file_id": f"f{index + 1}",
+ "filename": name,
+ "bytes": len(data),
+ **({"sha256sum": hashlib.sha256(data).hexdigest()} if hashes else {}),
+ }
+ for index, (name, data) in enumerate(files)
]
- with httpx.Client(
- base_url=live_service, headers={"authorization": "Bearer test-key"}, timeout=20, trust_env=False
- ) as client:
- first = subprocess.run(command, capture_output=True, text=True, check=True)
- status, uploaded = first.stdout.split()
- assert status == "202", result_path.read_text()
- assert int(uploaded) == len(data)
- task = _wait(client, json.loads(result_path.read_text())["task_id"])
- assert "Upload accounting" in task["files"][0]["content"]["markdown"]
- second = subprocess.run(command, capture_output=True, text=True, check=True)
- assert second.stdout.split() == ["202", "0"]
- assert _wait(client, json.loads(result_path.read_text())["task_id"])["status"] == "completed"
- invalid = client.post(
- "/v1/tasks",
- headers={"authorization": "Bearer wrong-key"},
- json={"tier": "flash", "files": [{"source": {"type": "file_id", "file_id": task["files"][0]["file_id"]}}]},
- )
- assert invalid.status_code in {401, 404}
+ response = client.post("/v1/tasks", data={"manifest": json.dumps(manifest), "tier": "flash", "ocr_mode": "txt", **options})
+ assert response.status_code == 202, response.text
+ return response.json()
+
+def _wait(client: httpx.Client, task: dict[str, Any], timeout: float = 60) -> dict[str, Any]:
+ """有界轮询任务元数据,不能调用已删除的 result 路由。"""
+ deadline = time.monotonic() + timeout
+ while time.monotonic() < deadline:
+ response = client.get(task["status_url"])
+ assert response.status_code == 200, response.text
+ payload = response.json()
+ if payload["status"] in TERMINAL:
+ return payload
+ assert payload["result_url"] is None
+ time.sleep(0.02)
+ pytest.fail("Task did not complete over HTTP")
-def _archive_members(data: bytes) -> dict[str, bytes]:
- """比较实际成员内容,排除 ZIP 时间戳和压缩包装差异。"""
- with zipfile.ZipFile(io.BytesIO(data)) as zf:
- return {name: zf.read(name) for name in zf.namelist()}
+def _members(data: bytes) -> dict[str, bytes]:
+ """比较 ZIP 成员而非时间戳或压缩包装,验证语义与素材保持不变。"""
+ with zipfile.ZipFile(io.BytesIO(data)) as archive:
+ return {name: archive.read(name) for name in archive.namelist()}
-def test_disconnect_after_submission_keeps_background_job(live_service: str, monkeypatch: pytest.MonkeyPatch) -> None:
- """客户端在已接单后关闭真实 TCP,后台解析仍完成且只执行一次。"""
- release = threading.Event()
- original = api_server.parse_async
- calls = 0
- async def delayed(*args: Any, **kwargs: Any) -> Any:
- """保持同步请求等待,允许测试先观察已创建的后台任务。"""
- nonlocal calls
- calls += 1
- while not release.is_set():
- await asyncio.sleep(0.01)
- return await original(*args, **kwargs)
+def _script_env(tmp_path: Path, base: str, **extra: str) -> dict[str, str]:
+ """隔离示例脚本环境,只继承执行 Python 与本地字符编码所需变量。"""
+ env = {
+ "PATH": os.environ["PATH"],
+ "HOME": os.environ.get("HOME", str(tmp_path)),
+ "MINERU_API_URL": base,
+ "MINERU_API_KEY": "test-key",
+ "MINERU_PYTHON": sys.executable,
+ "MINERU_TIER": "flash",
+ "OCR_MODE": "txt",
+ "RESULT_FILE": str(tmp_path / "result.zip"),
+ "MAX_POLLS": "100",
+ "POLL_INTERVAL": "0.02",
+ "REQUEST_TIMEOUT": "30",
+ "CONNECT_TIMEOUT": "5",
+ }
+ env.update(extra)
+ return env
- monkeypatch.setattr(api_server, "parse_async", delayed)
- address = urlsplit(live_service)
- body = b"<h1>Disconnected client</h1>"
- connection = socket.create_connection((address.hostname, address.port), timeout=5)
- try:
- headers = (
- f"POST /v1/file_parse?filename=source.html&tier=flash HTTP/1.1\r\nHost: {address.netloc}\r\n"
- f"Authorization: Bearer test-key\r\nContent-Type: application/octet-stream\r\nContent-Length: {len(body)}\r\n\r\n"
+
+def _run_script(env: dict[str, str], *paths: Path) -> subprocess.CompletedProcess[str]:
+ """执行用户实际调用的 shell 入口,不在测试里重写客户端逻辑。"""
+ return subprocess.run(
+ ["bash", str(SCRIPT), *(str(path) for path in paths)], env=env, text=True, capture_output=True, timeout=90
+ )
+
+
[email protected]("mode,hashes,count", [("preflight", "1", 2), ("preflight", "0", 1), ("direct", "1", 1)])
+def test_documented_client_script(live_service: _LiveService, tmp_path: Path, mode: str, hashes: str, count: int) -> None:
+ """同一脚本处理本地、Router、单文件直传和多文件逐项上传。"""
+ paths: list[Path] = []
+ for index in range(count):
+ path = tmp_path / f"测试 文档 {index}.html"
+ path.write_text(f"<h1>中文内容 {index}</h1>", encoding="utf-8")
+ paths.append(path)
+ result = _run_script(_script_env(tmp_path, live_service.url, UPLOAD_MODE=mode, SEND_HASH=hashes), *paths)
+ assert result.returncode == 0, result.stdout + result.stderr
+ assert "task_id=" in result.stderr
+ members = _members((tmp_path / "result.zip").read_bytes())
+ assert "中文内容".encode() in members["0001/markdown.md" if count > 1 else "markdown.md"]
+
+
+def test_hash_preflight_sends_only_missing_file_bytes(live_service: _LiveService) -> None:
+ """真实网络计数证明混合命中仅上传缺失文件,全命中不发送任何文件 PUT。"""
+ with _client(live_service) as client:
+ first = _submit(client, [("a.html", HTML)])
+ assert client.put(first["uploads"][0]["upload_url"], content=HTML).status_code == 200
+ assert _wait(client, first)["status"] == "completed"
+ second_data = b"<h1>second</h1>"
+ mixed = _submit(client, [("renamed.html", HTML), ("b.html", second_data)])
+ assert [link["client_file_id"] for link in mixed["uploads"]] == ["f2"]
+ assert client.put(mixed["uploads"][0]["upload_url"], content=second_data).status_code == 200
+ assert _wait(client, mixed)["status"] == "completed"
+ base = f"/v1/tasks/{mixed['task_id']}/uploads/"
+ assert live_service.counts.get(base + "f1", 0) == 0
+ assert live_service.counts[base + "f2"] == len(second_data)
+ hit = _submit(client, [("a.html", HTML), ("b.html", second_data)])
+ assert hit["uploads"] == []
+ assert _wait(client, hit)["status"] == "completed"
+ assert not any(hit["task_id"] in path for path in live_service.counts)
+ denied = client.post(
+ "/v1/tasks",
+ headers={"Authorization": "Bearer wrong"},
+ data={
+ "manifest": json.dumps(
+ [
+ {"client_file_id": "f1", "filename": "a.html", "bytes": len(HTML)},
+ ]
+ )
+ },
)
- connection.sendall(headers.encode() + body)
- with httpx.Client(
- base_url=live_service, headers={"authorization": "Bearer test-key"}, timeout=5, trust_env=False
- ) as client:
- deadline = time.monotonic() + 10
- jobs = []
- while time.monotonic() < deadline:
- jobs = client.get("/v1/parse/jobs").json()["data"]
- if jobs:
- break
+ assert denied.status_code == 401
+
+
+def test_disconnect_then_resume_keeps_uploaded_files(live_service: _LiveService, tmp_path: Path) -> None:
+ """A 成功、B 半途断连后通过同一 task_id 恢复,A 不重传且解析仅执行一次。"""
+ second = b"<h1>Resumed file</h1><!--" + b"x" * (256 * 1024) + b"-->"
+ first_path, second_path = tmp_path / "a.html", tmp_path / "b.html"
+ first_path.write_bytes(HTML)
+ second_path.write_bytes(second)
+ with _client(live_service) as client:
+ task = _submit(client, [(first_path.name, HTML), (second_path.name, second)])
+ assert client.put(task["uploads"][0]["upload_url"], content=HTML).status_code == 200
+ target = urlsplit(task["uploads"][1]["upload_url"])
+ connection = socket.create_connection((target.hostname, target.port), timeout=5)
+ prefix = second[:4096]
+ try:
+ headers = (
+ f"PUT {target.path} HTTP/1.1\r\nHost: {target.netloc}\r\nAuthorization: Bearer test-key\r\n"
+ f"Content-Type: application/octet-stream\r\nContent-Length: {len(second)}\r\nConnection: close\r\n\r\n"
+ )
+ connection.sendall(headers.encode() + prefix)
+ deadline = time.monotonic() + 5
+ while live_service.counts.get(target.path, 0) != len(prefix) and time.monotonic() < deadline:
time.sleep(0.01)
- assert len(jobs) == 1
+ assert live_service.counts[target.path] == len(prefix)
+ finally:
connection.close()
- release.set()
- result = _wait(client, jobs[0]["job_id"])
- assert result["status"] == "completed"
- assert "Disconnected client" in result["files"][0]["content"]["markdown"]
- assert calls == 1
+ pending = client.get(task["status_url"]).json()
+ assert pending["status"] == "waiting_upload"
+ assert [item["upload_status"] for item in pending["files"]] == ["ready", "pending"]
+ result = _run_script(_script_env(tmp_path, live_service.url, TASK_ID=task["task_id"]), first_path, second_path)
+ assert result.returncode == 0, result.stdout + result.stderr
+ assert live_service.counts[urlsplit(task["uploads"][0]["upload_url"]).path] == len(HTML)
+ assert live_service.counts[target.path] == len(prefix) + len(second)
+ assert len(live_service.app.state.task_store._records) == 1
+ members = _members((tmp_path / "result.zip").read_bytes())
+ assert b"Resumed file" in members["0002/markdown.md"]
+ final = client.get(task["status_url"]).json()
+ assert final["task_id"] == task["task_id"] and final["status"] == "completed"
+
+
+def test_cancel_response_does_not_wait_for_native_thread_cleanup(
+ live_service: _LiveService,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """取消立即返回状态;不可中断的本地线程仍由后台安全等待并释放资源。"""
+ entered, release = threading.Event(), threading.Event()
+
+ async def native_work(path: str, **kwargs: Any) -> None:
+ """模拟线程推理的清理边界,取消不能强制关闭线程正在读取的文件。"""
+ entered.set()
+ await run_sync(release.wait, 10)
+
+ monkeypatch.setattr(api_server, "parse_async", native_work)
+ try:
+ with _client(live_service) as client:
+ task = _submit(client, [("a.html", HTML)])
+ assert client.put(task["uploads"][0]["upload_url"], content=HTML).status_code == 200
+ assert entered.wait(5)
+ canceled = client.delete(task["status_url"], timeout=2)
+ assert canceled.status_code == 200 and canceled.json()["status"] == "canceled"
+ assert not release.is_set()
+ assert client.get(task["status_url"]).json()["result_url"] is None
finally:
release.set()
- connection.close()
-
-
[email protected]("mode,format", [("sync", "json"), ("async", "zip")])
[email protected](shutil.which("curl") is None, reason="curl is required for the documented shell example")
-def test_documented_task_script(live_service: str, tmp_path: Path, mode: str, format: str) -> None:
- """执行文档中的真实脚本,验证 URL 编码、鉴权和两种结果形式。"""
- source = tmp_path / "测试 文档.html"
- source.write_text("<h1>Script output</h1><p>中文内容</p>", encoding="utf-8")
- output = tmp_path / f"result.{format}"
- env = dict(
- os.environ,
- MINERU_API_URL=live_service,
- MINERU_API_KEY="test-key",
- MINERU_TIER="flash",
- MODE=mode,
- RESPONSE_FORMAT=format,
- RESULT_FILE=str(output),
- OUTPUT_FORMATS="markdown",
- PAGE_RANGE="",
- OCR_MODE="txt",
- REQUEST_TIMEOUT="30",
- EXPECT_TIMEOUT="10",
- MAX_POLLS="30",
- POLL_INTERVAL="0.01",
- )
- script = Path(__file__).resolve().parents[2] / "scripts" / "http_task_example.sh"
- completed = subprocess.run(["bash", str(script), str(source)], env=env, capture_output=True, text=True, timeout=40)
- assert completed.returncode == 0, completed.stdout + completed.stderr
- if format == "json":
- result = json.loads(output.read_text())
- assert result["files"][0]["name"] == source.name
- assert "中文内容" in result["files"][0]["content"]["markdown"]
- else:
- assert "middle_json.json" in _archive_members(output.read_bytes())
+
+
[email protected]("upload_mode", ["preflight", "direct"])
+def test_upload_over_200_mib_is_accepted(
+ live_service: _LiveService,
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ upload_mode: str,
+) -> None:
+ """超过旧上限的完整文件经过真实 HTTP 和 worker 转发,校验后才进入解析。"""
+ started = threading.Event()
+
+ async def pause_parser(path: str, **kwargs: Any) -> None:
+ """只隔离耗时解析,真实源文件读取、完整上传和转发均保留。"""
+ assert Path(path).stat().st_size == 200 * 1024 * 1024 + 4096
+ started.set()
+ await asyncio.Event().wait()
+
+ monkeypatch.setattr(api_server, "parse_async", pause_parser)
+ source = tmp_path / "large.html"
+ size = 200 * 1024 * 1024 + 4096
+ with source.open("wb") as output:
+ output.write(b"<h1>Large upload</h1>")
+ output.seek(size - 1)
+ output.write(b"\n")
+ with _client(live_service) as client:
+ if upload_mode == "direct":
+ with source.open("rb") as stream:
+ response = client.post("/v1/tasks", data={"tier": "flash"}, files={"files": (source.name, stream)})
+ assert response.status_code == 202, response.text
+ task = response.json()
+ else:
+ response = client.post(
+ "/v1/tasks",
+ data={
+ "tier": "flash",
+ "manifest": json.dumps(
+ [
+ {"client_file_id": "large", "filename": source.name, "bytes": size},
+ ]
+ ),
+ },
+ )
+ assert response.status_code == 202, response.text
+ task = response.json()
+ with source.open("rb") as stream:
+ uploaded = client.put(task["uploads"][0]["upload_url"], content=stream, headers={"Content-Length": str(size)})
+ assert uploaded.status_code == 200, uploaded.text
+ assert live_service.counts[urlsplit(task["uploads"][0]["upload_url"]).path] == size
+ assert started.wait(60)
+ status = client.get(task["status_url"]).json()
+ assert status["files"][0]["upload_status"] == "ready"
+ assert client.delete(task["status_url"]).json()["status"] == "canceled"
+
+
[email protected]("page_count", [601, 1001])
+def test_large_page_count_pdf_is_not_rejected(live_service: _LiveService, page_count: int) -> None:
+ """真实 Flash txt 解析保留超过 SaaS 页数策略的全部 PDF 页面。"""
+ writer = PdfWriter()
+ for _ in range(page_count):
+ writer.add_blank_page(width=72, height=72)
+ buffer = io.BytesIO()
+ writer.write(buffer)
+ data = buffer.getvalue()
+ with _client(live_service) as client:
+ task = _submit(client, [("many-pages.pdf", data)])
+ assert client.put(task["uploads"][0]["upload_url"], content=data).status_code == 200
+ result = _wait(client, task, timeout=90)
+ assert result["status"] == "completed", result
+ download = client.get(result["result_url"])
+ middle = json.loads(_members(download.content)["middle_json.json"])
+ assert len(middle["pages"]) == page_count
+ assert middle["pages"][-1]["page_idx"] == page_count - 1
@pytest.mark.parametrize("document", ["html", "pdf"])
-def test_real_documents_match_v1_output_and_zip(live_service: str, document: str) -> None:
- """真实 HTML/PDF 的便捷 JSON 和 ZIP 与既有 V1 产物逐项一致。"""
+def test_real_documents_match_jobs_outputs(live_service: _LiveService, document: str) -> None:
+ """真实 HTML/PDF 的任务 ZIP 与既有 Jobs 产物逐项一致,不改变中间协议或素材。"""
if document == "pdf":
path = Path(__file__).resolve().parents[2] / "examples" / "demo1.pdf"
if not path.is_file():
- pytest.skip("Local real-PDF sample examples/demo1.pdf is unavailable")
- content = path.read_bytes()
- name, page_range = path.name, "1-2"
+ pytest.skip("Local real PDF examples/demo1.pdf is unavailable")
+ data, name, page_range = path.read_bytes(), path.name, "1-2"
else:
- content = b"<h1>HTTP equality</h1><p>Same source and output.</p>"
- name, page_range = "source.html", ""
+ data, name, page_range = HTML, "source.html", ""
formats = ["markdown", "middle_json", "structured_content", "zip"]
- with httpx.Client(
- base_url=live_service, headers={"authorization": "Bearer test-key"}, timeout=60, trust_env=False
- ) as client:
+ with _client(live_service) as client:
+ task = _submit(client, [(name, data)], page_range=page_range, output_formats=formats)
+ assert client.put(task["uploads"][0]["upload_url"], content=data).status_code == 200
+ result = _wait(client, task)
+ assert result["status"] == "completed", result
submitted = client.post(
- "/v1/tasks",
- params=[
- ("tier", "flash"),
- ("ocr_mode", "txt"),
- ("page_range", page_range),
- *(("output_formats", fmt) for fmt in formats),
- ],
- files={"files": (name, content)},
+ "/v1/parse/jobs",
+ json={
+ "tier": "flash",
+ "ocr_mode": "txt",
+ "output_formats": formats,
+ "files": [
+ {"source": {"type": "file_id", "file_id": result["files"][0]["file_id"]}, "page_range": page_range or None}
+ ],
+ },
)
assert submitted.status_code == 202, submitted.text
- result = _wait(client, submitted.json()["task_id"])
- file_id = result["files"][0]["file_id"]
- body = {
- "tier": "flash",
- "ocr_mode": "txt",
- "output_formats": formats,
- "files": [{"source": {"type": "file_id", "file_id": file_id}, "page_range": page_range or None}],
+ deadline = time.monotonic() + 60
+ while True:
+ baseline = client.get(f"/v1/parse/jobs/{submitted.json()['job_id']}").json()
+ if baseline["status"] in TERMINAL:
+ break
+ assert time.monotonic() < deadline
+ time.sleep(0.02)
+ assert baseline["status"] == "completed", baseline
+ first = client.get(result["result_url"])
+ second = client.get(f"/v1/files/{baseline['files'][0]['output_files']['zip']['file_id']}/content")
+ assert first.status_code == second.status_code == 200
+ assert _members(first.content) == _members(second.content)
+
+
+@dataclass
+class _CloudState:
+ """模拟仅处理元数据的 SaaS 网关与独立对象存储,覆盖客户端可观察的协议。"""
+
+ gateway_url: str = ""
+ storage_url: str = ""
+ tasks: dict[str, dict[str, Any]] = field(default_factory=dict)
+ cache: dict[str, bytes] = field(default_factory=dict)
+ requests: list[tuple[str, str, str, str | None]] = field(default_factory=list)
+ upload_attempts: dict[str, int] = field(default_factory=dict)
+ gateway_body_sizes: list[int] = field(default_factory=list)
+ transient_upload: bool = False
+ lost_upload_response: bool = False
+ expired_upload: bool = False
+ expired_download: bool = False
+ api_download_redirect: bool = False
+ forced_status: str | None = None
+ invalid_response: str | None = None
+
+ def payload(self, task_id: str) -> dict[str, Any]:
+ """只从元数据生成响应,网关不读取对象存储中的结果字节。"""
+ record = self.tasks[task_id]
+ ready = record["ready"]
+ status = (self.forced_status or "completed") if len(ready) == len(record["manifest"]) else "waiting_upload"
+ files = [
+ {
+ **item,
+ "name": item["filename"],
+ "upload_status": "ready" if item["client_file_id"] in ready else "pending",
+ "status": "completed" if status in {"completed", "partial"} else "queued",
+ }
+ for item in record["manifest"]
+ ]
+ result_url = None
+ if status in {"completed", "partial"}:
+ result_url = f"{self.storage_url}/download/{task_id}?signature={record['download_version']}"
+ if self.api_download_redirect:
+ result_url = f"{self.gateway_url}/redirect/{task_id}"
+ uploads = [
+ {
+ "client_file_id": item["client_file_id"],
+ "upload_method": "PUT",
+ "upload_url": (
+ f"{self.storage_url}/objects/{task_id}/{item['client_file_id']}?signature={record['upload_version']}"
+ ),
+ "upload_headers": {"Content-Type": "application/octet-stream", "X-Upload-Token": "storage-token"},
+ "expires_at": int(time.time()) + 3600,
+ }
+ for item in record["manifest"]
+ if item["client_file_id"] not in ready
+ ]
+ payload = {
+ "task_id": task_id,
+ "status": status,
+ "status_url": f"{self.gateway_url}/v1/tasks/{task_id}",
+ "result_url": result_url,
+ "files": files,
+ "uploads": uploads,
+ "error": None,
+ }
+ if self.invalid_response == "missing_id":
+ payload["task_id"] = None
+ elif self.invalid_response == "unknown_status":
+ payload["status"] = "mystery"
+ return payload
+
+
+def _cloud_apps(state: _CloudState) -> tuple[FastAPI, FastAPI]:
+ """构造两个独立服务;网关没有 result 路由,也没有文件字节上传路由。"""
+ gateway, storage = FastAPI(), FastAPI()
+
+ @gateway.middleware("http")
+ async def authorize(request: Request, call_next: Any) -> Response:
+ """网关请求必须带 API Key,对象存储请求则另行验证不能携带它。"""
+ state.requests.append(("gateway", request.method, request.url.path, request.headers.get("authorization")))
+ if request.headers.get("authorization") != "Bearer test-key":
+ return JSONResponse({"error": {"code": "invalid_api_key"}}, status_code=401)
+ return await call_next(request)
+
+ @gateway.post("/v1/tasks")
+ async def create_task(request: Request) -> Response:
+ """只接收体积很小的表单元数据,用 hash 判断哪些文件需要独立上传。"""
+ assert not request.query_params
+ assert request.headers["content-type"].startswith("application/x-www-form-urlencoded")
+ body = await request.body()
+ state.gateway_body_sizes.append(len(body))
+ assert len(body) < 4096
+ form = await request.form()
+ manifest = json.loads(form["manifest"])
+ task_id = f"cloud_{len(state.tasks) + 1}"
+ state.tasks[task_id] = {
+ "manifest": manifest,
+ "ready": {item["client_file_id"] for item in manifest if item.get("sha256sum") in state.cache},
+ "upload_version": 0,
+ "download_version": 0,
}
- legacy = client.post("/v1/parse/jobs", json=body)
- assert legacy.status_code == 202, legacy.text
- baseline = _wait(client, legacy.json()["job_id"])
- assert baseline["files"][0]["content"] == result["files"][0]["content"]
- first_zip = client.get(result["result_url"], params={"response_format": "zip"})
- second_zip = client.get(baseline["result_url"], params={"response_format": "zip"})
- assert first_zip.status_code == second_zip.status_code == 200
- assert _archive_members(first_zip.content) == _archive_members(second_zip.content)
- # 同步包装同样只调用一次现有解析服务,且不改变共享协议或图片素材。
- sync = client.post("/v1/file_parse", json=body)
- assert sync.status_code == 200, sync.text
- assert sync.json()["files"][0]["content"] == result["files"][0]["content"]
+ return JSONResponse(state.payload(task_id), status_code=202)
+
+ @gateway.get("/v1/tasks/{task_id}")
+ async def get_task(task_id: str) -> Response:
+ """仅返回元数据和 OSS 下载链接,不回源读取或代理 ZIP 内容。"""
+ return JSONResponse(state.payload(task_id))
+
+ @gateway.get("/redirect/{task_id}")
+ async def redirect(task_id: str) -> Response:
+ """模拟同源下载地址重定向到同主机不同端口,检查客户端凭据隔离。"""
+ return RedirectResponse(
+ f"{state.storage_url}/download/{task_id}?signature={state.tasks[task_id]['download_version']}",
+ status_code=302,
+ )
+
+ @storage.middleware("http")
+ async def no_api_key(request: Request, call_next: Any) -> Response:
+ """记录实际对象存储请求,MinerU API Key 不得跨源发送。"""
+ state.requests.append(("storage", request.method, request.url.path, request.headers.get("authorization")))
+ assert request.headers.get("authorization") is None
+ return await call_next(request)
+
+ @storage.put("/objects/{task_id}/{client_file_id}")
+ async def upload(task_id: str, client_file_id: str, request: Request) -> Response:
+ """只在对象存储接收文件字节,并模拟临时错误、链接过期和提交后响应丢失。"""
+ assert request.headers.get("x-upload-token") == "storage-token"
+ key = task_id + "/" + client_file_id
+ state.upload_attempts[key] = state.upload_attempts.get(key, 0) + 1
+ record = state.tasks[task_id]
+ if request.query_params.get("signature") != str(record["upload_version"]):
+ return Response(status_code=403)
+ if state.expired_upload and record["upload_version"] == 0:
+ record["upload_version"] = 1
+ return Response(status_code=403)
+ if state.transient_upload and state.upload_attempts[key] == 1:
+ return Response(status_code=503)
+ data = await request.body()
+ item = next(item for item in record["manifest"] if item["client_file_id"] == client_file_id)
+ assert len(data) == item["bytes"]
+ actual = hashlib.sha256(data).hexdigest()
+ assert item.get("sha256sum") in {None, actual}
+ state.cache[actual] = data
+ record["ready"].add(client_file_id)
+ if state.lost_upload_response:
+ return Response(status_code=503)
+ return Response(status_code=200)
+
+ @storage.get("/download/{task_id}")
+ async def download(task_id: str, request: Request) -> Response:
+ """结果字节仅由对象存储返回;过期地址通过再次查询原任务刷新。"""
+ record = state.tasks[task_id]
+ if request.query_params.get("signature") != str(record["download_version"]):
+ return Response(status_code=403)
+ if state.expired_download and record["download_version"] == 0:
+ record["download_version"] = 1
+ return Response(status_code=403)
+ output = io.BytesIO()
+ with zipfile.ZipFile(output, "w") as archive:
+ archive.writestr("result.md", "# OSS result\n")
+ archive.writestr("manifest.json", json.dumps({"task_id": task_id, "status": state.forced_status or "completed"}))
+ return Response(output.getvalue(), media_type="application/zip")
+
+ return gateway, storage
+
+
+def cloud() -> Iterator[_CloudState]:
+ """分别启动 SaaS 网关和 OSS 模拟服务,保证跨源认证检查经过真实 TCP。"""
+ state = _CloudState()
+ gateway, storage = _cloud_apps(state)
+ api_server_instance, storage_server = _Server(gateway), _Server(storage)
+ state.gateway_url, state.storage_url = api_server_instance.url, storage_server.url
+ storage_server.start()
+ api_server_instance.start()
+ try:
+ yield state
+ finally:
+ api_server_instance.stop()
+ storage_server.stop()
+
+
[email protected]("cache_mode", ["none", "mixed", "all", "no_hash"])
+def test_same_client_works_with_saas_and_oss(cloud: _CloudState, tmp_path: Path, cache_mode: str) -> None:
+ """通用客户端只向网关发送清单,文件和 ZIP 都直接走对象存储。"""
+ inputs = [tmp_path / "a.html", tmp_path / "b.html"]
+ data = [HTML, b"<h1>Other file</h1>" * 10000]
+ for path, content in zip(inputs, data):
+ path.write_bytes(content)
+ if cache_mode in {"mixed", "all", "no_hash"}:
+ cloud.cache[hashlib.sha256(data[0]).hexdigest()] = data[0]
+ if cache_mode == "all":
+ cloud.cache[hashlib.sha256(data[1]).hexdigest()] = data[1]
+ result = _run_script(_script_env(tmp_path, cloud.gateway_url, SEND_HASH="0" if cache_mode == "no_hash" else "1"), *inputs)
+ assert result.returncode == 0, result.stdout + result.stderr
+ expected = {"none": 2, "mixed": 1, "all": 0, "no_hash": 2}[cache_mode]
+ assert len(cloud.upload_attempts) == expected
+ assert len(cloud.tasks) == 1 and max(cloud.gateway_body_sizes) < 4096
+ assert not any(surface == "gateway" and method == "PUT" for surface, method, _, _ in cloud.requests)
+ assert not any(path.endswith("/result") for _, _, path, _ in cloud.requests)
+ assert all(auth is None for surface, _, _, auth in cloud.requests if surface == "storage")
+ assert _members((tmp_path / "result.zip").read_bytes())["result.md"] == b"# OSS result\n"
+
+
+ "failure", ["transient_upload", "lost_upload_response", "expired_upload", "expired_download", "api_download_redirect"]
+)
+def test_client_recovers_links_and_uncertain_uploads(cloud: _CloudState, tmp_path: Path, failure: str) -> None:
+ """恢复原任务和刷新地址不创建新任务;跨源重定向不能转发 API Key。"""
+ setattr(cloud, failure, True)
+ source = tmp_path / "a.html"
+ source.write_bytes(HTML)
+ result = _run_script(_script_env(tmp_path, cloud.gateway_url), source)
+ assert result.returncode == 0, result.stdout + result.stderr
+ assert len(cloud.tasks) == 1
+ assert cloud.upload_attempts["cloud_1/f1"] == (2 if failure in {"transient_upload", "expired_upload"} else 1)
+ assert all(auth is None for surface, _, _, auth in cloud.requests if surface == "storage")
+ assert (tmp_path / "result.zip").is_file()
+
+
[email protected]("invalid", ["missing_id", "unknown_status"])
+def test_invalid_success_response_does_not_upload_or_poll(cloud: _CloudState, tmp_path: Path, invalid: str) -> None:
+ """非法 HTTP 202 响应不会带着空 ID 或未知状态继续执行。"""
+ cloud.invalid_response = invalid
+ source = tmp_path / "a.html"
+ source.write_bytes(HTML)
+ result = _run_script(_script_env(tmp_path, cloud.gateway_url), source)
+ assert result.returncode == 1
+ assert not cloud.upload_attempts
+ assert not any(method == "GET" for _, method, _, _ in cloud.requests)
+ assert not (tmp_path / "result.zip").exists()
+
+
[email protected]("status,exit_code", [("partial", 2), ("failed", 1), ("running", 124)])
+def test_client_exit_codes_and_poll_budget(cloud: _CloudState, tmp_path: Path, status: str, exit_code: int) -> None:
+ """部分成功先保存 ZIP,失败不下载,等待预算耗尽保留原 task_id。"""
+ cloud.forced_status = status
+ source = tmp_path / "a.html"
+ source.write_bytes(HTML)
+ result = _run_script(_script_env(tmp_path, cloud.gateway_url, MAX_POLLS="2"), source)
+ assert result.returncode == exit_code, result.stdout + result.stderr
+ assert len(cloud.tasks) == 1 and "task_id=cloud_1" in result.stderr
+ assert (tmp_path / "result.zip").exists() == (status == "partial")
+ if status == "running":
+ assert "continues running" in result.stderr