mineru 0.5.0

Rust client, CLI, and API server for OpenAI-compatible MinerU document parsing
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
use serde::{Deserialize, Deserializer, de::Error as DeError};
use serde_json::{Value, json};
use tokio::{
    io::{AsyncBufReadExt, AsyncWriteExt, BufReader},
    process::{ChildStdin, ChildStdout},
};

use super::super::{
    OfficialRequest, OfficialSessionConfig, PERSISTENT_OCR_MODES, PERSISTENT_PROTOCOL,
    PERSISTENT_TIERS, REQUEST_CAP,
};

pub(super) fn persistent_capabilities(config: &OfficialSessionConfig) -> Value {
    json!({
        "tiers": PERSISTENT_TIERS,
        "ocr_modes": PERSISTENT_OCR_MODES,
        "input_formats": config.input_formats,
        "bundle_name": crate::hybrid_v4_output::BUNDLE_NAME,
        "cancellation": "process-terminate",
    })
}

pub(super) fn validate_persistent_request(request: &OfficialRequest) -> Result<(), String> {
    if request.request_id.is_empty() {
        return Err("official persistent request id is empty".into());
    }
    if !PERSISTENT_TIERS.contains(&request.tier.as_str()) {
        return Err("official persistent tier is unsupported".into());
    }
    // Upstream honours a remote VLM at any tier (tier.py skips the local VLM
    // modules when a server_url is set), so only syntax matters here; the CLI
    // preflight already applied VlmConfig._normalize_server_url parity.
    if request
        .vlm_server_url
        .as_deref()
        .is_some_and(|url| !url.starts_with("http://") && !url.starts_with("https://"))
    {
        return Err("official persistent vlm_server_url must be an HTTP(S) URL".into());
    }
    if !PERSISTENT_OCR_MODES.contains(&request.ocr_mode.as_str()) {
        return Err("official persistent ocr_mode is unsupported".into());
    }
    if request.page_range.as_deref().is_some_and(str::is_empty) {
        return Err("official persistent page_range must be nonempty".into());
    }
    if request.max_bundle_bytes == 0 {
        return Err("official persistent max_bundle_bytes must be positive".into());
    }
    if request.bundle_name != crate::hybrid_v4_output::BUNDLE_NAME {
        return Err("official persistent bundle name mismatch".into());
    }
    Ok(())
}

pub(super) fn persistent_start_frame(config: &OfficialSessionConfig) -> Value {
    json!({
        "type": "start",
        "protocol": PERSISTENT_PROTOCOL,
        "package_version": config.package_version,
        "schema_version": config.schema_version,
        "model_base_dir": config.model_base_dir,
        "config": config.config,
        "vlm_api_key": config.vlm_api_key,
        "vlm_model": config.vlm_model,
        "capabilities": persistent_capabilities(config),
    })
}

pub(super) fn persistent_request_frame(
    request: &OfficialRequest,
    config: &OfficialSessionConfig,
    sequence: u64,
) -> Value {
    let mut frame = json!({
        "type": "request",
        "protocol": PERSISTENT_PROTOCOL,
        "request_id": request.request_id,
        "sequence": sequence,
        "package_version": config.package_version,
        "schema_version": config.schema_version,
        "tier": request.tier,
        "ocr_mode": request.ocr_mode,
        "image_analysis": request.image_analysis,
        "vlm_server_url": request.vlm_server_url,
        "vlm_api_key": request.vlm_api_key,
        "vlm_model": request.vlm_model,
        "model_base_dir": config.model_base_dir,
        "config": config.config,
        "bundle_name": crate::hybrid_v4_output::BUNDLE_NAME,
        "input_path": request.input_path,
        "bundle_path": request.bundle_path,
        "max_bundle_bytes": request.max_bundle_bytes,
    });
    // Omit rather than null so the shim's strict field-set validation sees an
    // absent key for page-range-less documents.
    if let Some(page_range) = &request.page_range {
        frame["page_range"] = Value::String(page_range.clone());
    }
    if let Some(source_context) = &request.source_context {
        frame["source_context"] = source_context.clone();
    }
    if let Some(config) = &request.official_vlm_config {
        frame["official_vlm_config"] = config.clone();
    }
    frame
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub(super) struct PersistentHandshakeFrame {
    #[serde(rename = "type", default = "handshake_frame_type")]
    pub(super) frame_type: String,
    pub(super) protocol: String,
    pub(super) status: String,
    pub(super) package_version: String,
    pub(super) schema_version: String,
    pub(super) max_in_flight: u32,
    pub(super) capabilities: Value,
    pub(super) diagnostic: Option<String>,
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub(super) struct PersistentResultFrame {
    #[serde(rename = "type", default = "result_frame_type")]
    pub(super) frame_type: String,
    pub(super) protocol: String,
    pub(super) request_id: String,
    pub(super) sequence: u64,
    pub(super) status: String,
    pub(super) package_version: String,
    pub(super) schema_version: String,
    pub(super) bundle_name: String,
    pub(super) error: Option<String>,
    pub(super) diagnostic: Option<String>,
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub(super) struct PersistentErrorFrame {
    #[serde(rename = "type", default = "error_frame_type")]
    pub(super) frame_type: String,
    pub(super) protocol: String,
    pub(super) status: String,
    pub(super) package_version: String,
    pub(super) schema_version: String,
    pub(super) bundle_name: String,
    pub(super) error: String,
    pub(super) diagnostic: Option<String>,
}

#[derive(Debug)]
pub(super) enum PersistentFrame {
    Handshake(PersistentHandshakeFrame),
    Result(PersistentResultFrame),
    Error(PersistentErrorFrame),
}

fn handshake_frame_type() -> String {
    "handshake".into()
}

fn result_frame_type() -> String {
    "result".into()
}

fn error_frame_type() -> String {
    "error".into()
}

const HANDSHAKE_FRAME_ERROR: &str = "__official_persistent_handshake_frame_error__: ";
const RESULT_FRAME_ERROR: &str = "__official_persistent_result_frame_error__: ";
const ERROR_FRAME_ERROR: &str = "__official_persistent_error_frame_error__: ";

fn deserialize_handshake_frame<'de, D>(
    deserializer: D,
) -> Result<PersistentHandshakeFrame, D::Error>
where
    D: Deserializer<'de>,
{
    PersistentHandshakeFrame::deserialize(deserializer)
        .map_err(|error| D::Error::custom(format!("{HANDSHAKE_FRAME_ERROR}{error}")))
}

fn deserialize_result_frame<'de, D>(deserializer: D) -> Result<PersistentResultFrame, D::Error>
where
    D: Deserializer<'de>,
{
    PersistentResultFrame::deserialize(deserializer)
        .map_err(|error| D::Error::custom(format!("{RESULT_FRAME_ERROR}{error}")))
}

fn deserialize_error_frame<'de, D>(deserializer: D) -> Result<PersistentErrorFrame, D::Error>
where
    D: Deserializer<'de>,
{
    PersistentErrorFrame::deserialize(deserializer)
        .map_err(|error| D::Error::custom(format!("{ERROR_FRAME_ERROR}{error}")))
}

#[derive(Debug, Deserialize)]
#[serde(tag = "type")]
enum PersistentFrameEnvelope {
    #[serde(rename = "handshake", deserialize_with = "deserialize_handshake_frame")]
    Handshake { frame: PersistentHandshakeFrame },
    #[serde(rename = "result", deserialize_with = "deserialize_result_frame")]
    Result { frame: PersistentResultFrame },
    #[serde(rename = "error", deserialize_with = "deserialize_error_frame")]
    Error { frame: PersistentErrorFrame },
    #[serde(other)]
    Unsupported,
}

pub(super) fn parse_persistent_frame(bytes: &[u8]) -> Result<PersistentFrame, String> {
    let envelope = match serde_json::from_slice::<PersistentFrameEnvelope>(bytes) {
        Ok(envelope) => envelope,
        Err(error) if error.is_syntax() || error.is_eof() => {
            return Err(format!(
                "official persistent protocol JSON is invalid: {error}"
            ));
        }
        Err(error) => {
            let message = error.to_string();
            if message.contains("missing field `type`") || message.starts_with("invalid type") {
                return Err("official persistent protocol frame type is missing".into());
            }
            if let Some(detail) = message.strip_prefix(HANDSHAKE_FRAME_ERROR) {
                return Err(format!(
                    "official persistent handshake is invalid: {detail}"
                ));
            }
            if let Some(detail) = message.strip_prefix(RESULT_FRAME_ERROR) {
                return Err(format!("official persistent result is invalid: {detail}"));
            }
            if let Some(detail) = message.strip_prefix(ERROR_FRAME_ERROR) {
                return Err(format!(
                    "official persistent error frame is invalid: {detail}"
                ));
            }
            return Err(format!(
                "official persistent protocol frame is invalid: {message}"
            ));
        }
    };
    match envelope {
        PersistentFrameEnvelope::Handshake { frame } => Ok(PersistentFrame::Handshake(frame)),
        PersistentFrameEnvelope::Result { frame } => Ok(PersistentFrame::Result(frame)),
        PersistentFrameEnvelope::Error { frame } => Ok(PersistentFrame::Error(frame)),
        PersistentFrameEnvelope::Unsupported => {
            Err("official persistent protocol frame type is unsupported".into())
        }
    }
}

pub(super) fn validate_persistent_error(
    frame: &PersistentErrorFrame,
    config: &OfficialSessionConfig,
) -> Result<(), String> {
    if frame.frame_type != "error"
        || frame.protocol != PERSISTENT_PROTOCOL
        || frame.status != "error"
        || frame.package_version != config.package_version
        || frame.schema_version != config.schema_version
        || frame.bundle_name != crate::hybrid_v4_output::BUNDLE_NAME
    {
        return Err("official persistent error frame mismatch".into());
    }
    Ok(())
}

pub(super) async fn write_persistent_frame(
    stdin: &mut ChildStdin,
    frame: &Value,
) -> Result<(), String> {
    let mut encoded = serde_json::to_vec(frame)
        .map_err(|error| format!("official persistent frame encode failed: {error}"))?;
    encoded.push(b'\n');
    if encoded.len() > REQUEST_CAP {
        return Err("official persistent frame exceeds its limit".into());
    }
    stdin
        .write_all(&encoded)
        .await
        .map_err(|error| format!("official persistent stdin failed: {error}"))?;
    stdin
        .flush()
        .await
        .map_err(|error| format!("official persistent stdin flush failed: {error}"))
}

pub(super) async fn read_persistent_frame(
    stdout: &mut BufReader<ChildStdout>,
) -> Result<Vec<u8>, String> {
    let mut frame = Vec::new();
    loop {
        let available = stdout
            .fill_buf()
            .await
            .map_err(|error| format!("official persistent stdout failed: {error}"))?;
        if available.is_empty() {
            if frame.is_empty() {
                return Err("official persistent worker stdout EOF".into());
            }
            return Err("official persistent frame has no newline".into());
        }
        if let Some(newline) = available.iter().position(|byte| *byte == b'\n') {
            let size = newline + 1;
            if frame.len() + size > REQUEST_CAP {
                return Err("official persistent frame exceeds its limit".into());
            }
            frame.extend_from_slice(&available[..size]);
            stdout.consume(size);
            return Ok(frame);
        }
        if frame.len() + available.len() > REQUEST_CAP {
            return Err("official persistent frame exceeds its limit".into());
        }
        frame.extend_from_slice(available);
        let size = available.len();
        stdout.consume(size);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    fn handshake_frame() -> Value {
        json!({
            "type": "handshake",
            "protocol": "mineru-rs-official-worker/2",
            "status": "ready",
            "package_version": "4.2.3",
            "schema_version": "2.0",
            "max_in_flight": 1,
            "capabilities": {"bundle_name": "hybrid-v4"},
        })
    }

    fn result_frame() -> Value {
        json!({
            "type": "result",
            "protocol": "mineru-rs-official-worker/2",
            "request_id": "request-1",
            "sequence": 1,
            "status": "ok",
            "package_version": "4.2.3",
            "schema_version": "2.0",
            "bundle_name": "hybrid-v4",
        })
    }

    fn error_frame() -> Value {
        json!({
            "type": "error",
            "protocol": "mineru-rs-official-worker/2",
            "status": "error",
            "package_version": "4.2.3",
            "schema_version": "2.0",
            "bundle_name": "hybrid-v4",
            "error": "startup failed",
        })
    }

    fn parse(value: Value) -> Result<PersistentFrame, String> {
        parse_persistent_frame(&serde_json::to_vec(&value).unwrap())
    }

    #[test]
    fn parses_handshake_result_and_error_frames() {
        assert!(
            matches!(parse(handshake_frame()), Ok(PersistentFrame::Handshake(frame))
            if frame.frame_type == "handshake" && frame.max_in_flight == 1)
        );
        assert!(
            matches!(parse(result_frame()), Ok(PersistentFrame::Result(frame))
            if frame.frame_type == "result" && frame.request_id == "request-1")
        );
        assert!(
            matches!(parse(error_frame()), Ok(PersistentFrame::Error(frame))
            if frame.frame_type == "error" && frame.error == "startup failed")
        );
    }

    #[test]
    fn rejects_unknown_type_and_unknown_field() {
        let mut unknown_type = handshake_frame();
        unknown_type["type"] = json!("notice");
        assert_eq!(
            parse(unknown_type).unwrap_err(),
            "official persistent protocol frame type is unsupported"
        );

        let mut unknown_field = handshake_frame();
        unknown_field["unexpected"] = json!(true);
        let error = parse(unknown_field).unwrap_err();
        assert!(
            error.contains("official persistent handshake is invalid: unknown field `unexpected`")
        );
    }

    #[test]
    fn rejects_missing_type_and_malformed_json() {
        let mut missing_type = handshake_frame();
        missing_type.as_object_mut().unwrap().remove("type");
        assert_eq!(
            parse(missing_type).unwrap_err(),
            "official persistent protocol frame type is missing"
        );

        let error = parse_persistent_frame(br#"{"type":"handshake""#).unwrap_err();
        assert!(error.starts_with("official persistent protocol JSON is invalid: "));
    }

    #[cfg(unix)]
    fn value_with_encoded_len(target: usize) -> Value {
        let empty = serde_json::to_vec(&json!({"payload": ""})).unwrap();
        assert!(target > empty.len());
        json!({"payload": "x".repeat(target - empty.len())})
    }

    #[cfg(unix)]
    async fn read_from_cat(bytes: &[u8]) -> Result<Vec<u8>, String> {
        use std::process::Stdio;
        use tokio::process::Command;

        let mut child = Command::new("cat")
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .spawn()
            .unwrap();
        let mut stdin = child.stdin.take().unwrap();
        stdin.write_all(bytes).await.unwrap();
        drop(stdin);
        let stdout = child.stdout.take().unwrap();
        let result = read_persistent_frame(&mut BufReader::new(stdout)).await;
        child.wait().await.unwrap();
        result
    }

    #[cfg(unix)]
    async fn write_to_cat(frame: &Value) -> Result<(), String> {
        use std::process::Stdio;
        use tokio::process::Command;

        let mut child = Command::new("cat")
            .stdin(Stdio::piped())
            .stdout(Stdio::null())
            .spawn()
            .unwrap();
        let mut stdin = child.stdin.take().unwrap();
        let result = write_persistent_frame(&mut stdin, frame).await;
        drop(stdin);
        child.wait().await.unwrap();
        result
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn accepts_the_cap_and_rejects_one_byte_over_it() {
        let exact = serde_json::to_vec(&value_with_encoded_len(REQUEST_CAP - 1)).unwrap();
        assert_eq!(exact.len() + 1, REQUEST_CAP);
        let mut exact_with_newline = exact.clone();
        exact_with_newline.push(b'\n');
        assert_eq!(
            read_from_cat(&exact_with_newline).await.unwrap(),
            exact_with_newline
        );
        assert!(
            write_to_cat(&value_with_encoded_len(REQUEST_CAP - 1))
                .await
                .is_ok()
        );

        let over = serde_json::to_vec(&value_with_encoded_len(REQUEST_CAP)).unwrap();
        assert_eq!(over.len() + 1, REQUEST_CAP + 1);
        let mut over_with_newline = over.clone();
        over_with_newline.push(b'\n');
        assert_eq!(
            read_from_cat(&over_with_newline).await.unwrap_err(),
            "official persistent frame exceeds its limit"
        );
        assert_eq!(
            write_to_cat(&value_with_encoded_len(REQUEST_CAP))
                .await
                .unwrap_err(),
            "official persistent frame exceeds its limit"
        );
    }
}