Skip to main content

vole_document/field/
document_format.rs

1//! Byte-based document-format detection for the universal observation API
2//! (Phase 12.7, ADR-0031, plan §DEC-5).
3//!
4//! The format of a field is decided from its **source bytes**, never from a file
5//! name or extension. Detection is deliberately conservative: an ambiguous or
6//! malformed input falls back to [`DocumentFormat::Opaque`] rather than guessing,
7//! and a format whose adapter is not compiled in cannot be detected (the input is
8//! then `Opaque`), so the reported capability set always matches what the build
9//! can actually serve.
10//!
11//! * **PDF** — the byte-authoritative physical scanner admits a validated PDF
12//!   ([`crate::adapter::pdf::detect`]).
13//! * **DOCX** — a valid ZIP that also carries the OPC content-types part
14//!   (`[Content_Types].xml`) and a package `officeDocument` relationship.
15//! * **EPUB** — a valid ZIP that is an OCF container: the mandatory stored
16//!   `mimetype` member equals `application/epub+zip`, or `META-INF/container.xml`
17//!   names the OCF namespace and an OPF (`application/oebps-package+xml`) rootfile.
18//! * **ODT** — a valid ZIP that is an OpenDocument (ODF) package: the mandatory
19//!   stored `mimetype` member is an OpenDocument *text* media type, or
20//!   `META-INF/manifest.xml` declares one.
21//! * **ODS** — a valid ZIP that is an OpenDocument (ODF) package whose mandatory
22//!   stored `mimetype` member is an OpenDocument *spreadsheet* media type, or whose
23//!   `META-INF/manifest.xml` declares one (Phase 21.3.1). Mutually exclusive with
24//!   ODT (a text document declares the text media type, a spreadsheet the
25//!   spreadsheet one).
26//! * **ODP** — a valid ZIP that is an OpenDocument (ODF) package whose mandatory
27//!   stored `mimetype` member is an OpenDocument *presentation* media type, or whose
28//!   `META-INF/manifest.xml` declares one (Phase 21.4.1). Mutually exclusive with
29//!   ODT/ODS (a presentation declares the presentation media type).
30//! * **Opaque** — everything else, including a ZIP that matches none of the above
31//!   (or more than one — an ambiguous ZIP fails safe).
32//! * **JSON** — the whole source parses as exactly one JSON value within the
33//!   JSON caps (Phase 21.5.1). JSON is a Wave-2 structured-tree format with no
34//!   package layer, so it is detected directly (never via `detect_zip_family`);
35//!   a malformed or oversized input stays `Opaque`.
36//!
37//! The detected format is recorded in the field manifest's provenance (a
38//! machine-readable `format=<name>;` prefix, see [`DocumentFormat::from_provenance`]),
39//! so `observe`/`find`/`explain` can dispatch common selectors without reading the
40//! whole source again.
41
42use crate::limits::Limits;
43
44/// The mandatory OCF `mimetype` payload.
45pub const EPUB_MIMETYPE: &[u8] = b"application/epub+zip";
46/// The mandatory OCF container descriptor member.
47pub const CONTAINER_MEMBER: &[u8] = b"META-INF/container.xml";
48/// The OCF container-descriptor namespace.
49pub const CONTAINER_NS: &[u8] = b"urn:oasis:names:tc:opendocument:xmlns:container";
50/// The default (and only normative) package-document media type.
51pub const OPF_MEDIA_TYPE: &[u8] = b"application/oebps-package+xml";
52/// The OPC content-types part.
53#[cfg(feature = "package")]
54const CONTENT_TYPES_MEMBER: &[u8] = b"[Content_Types].xml";
55/// The OPC package-relationships part.
56#[cfg(feature = "package")]
57const PACKAGE_RELS_MEMBER: &[u8] = b"_rels/.rels";
58/// The `officeDocument` relationship type fragment (transitional and strict).
59#[cfg(feature = "package")]
60const OFFICE_DOCUMENT_FRAGMENT: &[u8] = b"officeDocument";
61/// The WordprocessingML document main content-type fragment (Phase 21.1.2).
62#[cfg(feature = "package")]
63const DOCX_MAIN_FRAGMENT: &[u8] = b"wordprocessingml.document.main+xml";
64/// The canonical WordprocessingML main-part target fragment (Phase 21.1.2).
65#[cfg(feature = "package")]
66const DOCX_MAIN_TARGET: &[u8] = b"word/document.xml";
67/// The ODF package manifest member (Phase 13.3).
68#[cfg(feature = "odt")]
69const ODT_MANIFEST_MEMBER: &[u8] = b"META-INF/manifest.xml";
70/// The OpenDocument *text* media-type fragment (Phase 13.3).
71#[cfg(feature = "odt")]
72const ODT_TEXT_FRAGMENT: &[u8] = b"application/vnd.oasis.opendocument.text";
73/// The ODF package manifest member for the ODS detection rule (Phase 21.3.1).
74#[cfg(feature = "ods")]
75const ODS_MANIFEST_MEMBER: &[u8] = b"META-INF/manifest.xml";
76/// The OpenDocument *spreadsheet* media-type fragment (Phase 21.3.1).
77#[cfg(feature = "ods")]
78const ODS_SPREADSHEET_FRAGMENT: &[u8] = b"application/vnd.oasis.opendocument.spreadsheet";
79/// The ODF package manifest member for the ODP detection rule (Phase 21.4.1).
80#[cfg(feature = "odp")]
81const ODP_MANIFEST_MEMBER: &[u8] = b"META-INF/manifest.xml";
82/// The OpenDocument *presentation* media-type fragment (Phase 21.4.1).
83#[cfg(feature = "odp")]
84const ODP_PRESENTATION_FRAGMENT: &[u8] = b"application/vnd.oasis.opendocument.presentation";
85/// The SpreadsheetML workbook main content-type fragment (Phase 21.1.1).
86#[cfg(feature = "xlsx")]
87const XLSX_MAIN_FRAGMENT: &[u8] = b"spreadsheetml.sheet.main+xml";
88/// The SpreadsheetML content-type namespace fragment (Phase 21.1.1).
89#[cfg(feature = "xlsx")]
90const XLSX_NS_FRAGMENT: &[u8] = b"spreadsheetml";
91/// A SpreadsheetML workbook part-target fragment (Phase 21.1.1).
92#[cfg(feature = "xlsx")]
93const XLSX_WORKBOOK_TARGET: &[u8] = b"xl/workbook.xml";
94/// The PresentationML presentation main content-type fragment (Phase 21.2.1).
95#[cfg(feature = "pptx")]
96const PPTX_MAIN_FRAGMENT: &[u8] = b"presentationml.presentation.main+xml";
97/// The PresentationML content-type namespace fragment (Phase 21.2.1).
98#[cfg(feature = "pptx")]
99const PPTX_NS_FRAGMENT: &[u8] = b"presentationml";
100/// The canonical PresentationML main-part target fragment (Phase 21.2.1).
101#[cfg(feature = "pptx")]
102const PPTX_MAIN_TARGET: &[u8] = b"ppt/presentation.xml";
103
104/// A detected document format (the class of the field's source bytes).
105#[derive(Debug, Clone, Copy, PartialEq, Eq)]
106pub enum DocumentFormat {
107    /// A validated PDF (physical indicators).
108    Pdf,
109    /// An OPC package with a WordprocessingML `officeDocument` part.
110    Docx,
111    /// An OCF container with an EPUB package document.
112    Epub,
113    /// An ODF package with an OpenDocument text content part.
114    Odt,
115    /// An ODF package with an OpenDocument spreadsheet content part.
116    Ods,
117    /// An ODF package with an OpenDocument presentation content part.
118    Odp,
119    /// An OPC package with a SpreadsheetML workbook part.
120    Xlsx,
121    /// An OPC package with a PresentationML presentation part.
122    Pptx,
123    /// A structured JSON document (the whole source parses as exactly one JSON
124    /// value). Not a package: the exact leaf is the whole source (Phase 21.5.1).
125    Json,
126    /// A structured YAML document (the whole source parses as a bounded YAML
127    /// stream whose every document root is a mapping or a sequence). Not a package:
128    /// the exact leaf is the whole source (Phase 21.6.1).
129    Yaml,
130    /// Anything else; preserved exactly by the opaque floor.
131    Opaque,
132}
133
134impl DocumentFormat {
135    /// Stable lower-case name (used in JSON and in the manifest provenance token).
136    pub const fn name(self) -> &'static str {
137        match self {
138            DocumentFormat::Pdf => "pdf",
139            DocumentFormat::Docx => "docx",
140            DocumentFormat::Epub => "epub",
141            DocumentFormat::Odt => "odt",
142            DocumentFormat::Ods => "ods",
143            DocumentFormat::Odp => "odp",
144            DocumentFormat::Xlsx => "xlsx",
145            DocumentFormat::Pptx => "pptx",
146            DocumentFormat::Json => "json",
147            DocumentFormat::Yaml => "yaml",
148            DocumentFormat::Opaque => "opaque",
149        }
150    }
151
152    /// The adapter that serves this format (the observation layer's name for it).
153    pub const fn adapter(self) -> &'static str {
154        match self {
155            DocumentFormat::Pdf => "pdf",
156            DocumentFormat::Docx => "docx",
157            DocumentFormat::Epub => "epub",
158            DocumentFormat::Odt => "odt",
159            DocumentFormat::Ods => "ods",
160            DocumentFormat::Odp => "odp",
161            DocumentFormat::Xlsx => "xlsx",
162            DocumentFormat::Pptx => "pptx",
163            DocumentFormat::Json => "json",
164            DocumentFormat::Yaml => "yaml",
165            DocumentFormat::Opaque => "opaque",
166        }
167    }
168
169    /// Whether the adapter for this format is compiled into this build.
170    pub const fn compiled(self) -> bool {
171        match self {
172            DocumentFormat::Pdf | DocumentFormat::Opaque => true,
173            DocumentFormat::Docx => cfg!(feature = "docx"),
174            DocumentFormat::Epub => cfg!(feature = "epub"),
175            DocumentFormat::Odt => cfg!(feature = "odt"),
176            DocumentFormat::Ods => cfg!(feature = "ods"),
177            DocumentFormat::Odp => cfg!(feature = "odp"),
178            DocumentFormat::Xlsx => cfg!(feature = "xlsx"),
179            DocumentFormat::Pptx => cfg!(feature = "pptx"),
180            DocumentFormat::Json => cfg!(feature = "json"),
181            DocumentFormat::Yaml => cfg!(feature = "yaml"),
182        }
183    }
184
185    /// The machine-readable `format=<name>;` provenance prefix recorded at ingest.
186    pub fn provenance_prefix(self) -> String {
187        format!("format={};", self.name())
188    }
189
190    /// Recover the recorded format from a field manifest's provenance string.
191    ///
192    /// Returns `None` for a manifest that does not carry the token (e.g. a field
193    /// written before this subphase); such a field still serves every native
194    /// selector, but common observations decline typed rather than guessing.
195    pub fn from_provenance(provenance: &str) -> Option<DocumentFormat> {
196        let rest = provenance.strip_prefix("format=")?;
197        let name = rest.split(';').next()?;
198        match name {
199            "pdf" => Some(DocumentFormat::Pdf),
200            "docx" => Some(DocumentFormat::Docx),
201            "epub" => Some(DocumentFormat::Epub),
202            "odt" => Some(DocumentFormat::Odt),
203            "ods" => Some(DocumentFormat::Ods),
204            "odp" => Some(DocumentFormat::Odp),
205            "xlsx" => Some(DocumentFormat::Xlsx),
206            "pptx" => Some(DocumentFormat::Pptx),
207            "json" => Some(DocumentFormat::Json),
208            "yaml" => Some(DocumentFormat::Yaml),
209            "opaque" => Some(DocumentFormat::Opaque),
210            _ => None,
211        }
212    }
213}
214
215/// Detect the document format of `source` from its bytes alone.
216///
217/// Never consults a file name or extension. A malformed or ambiguous input (or a
218/// format whose adapter is not compiled) falls back to [`DocumentFormat::Opaque`].
219pub fn detect_document_format(source: &[u8], limits: Limits) -> DocumentFormat {
220    if crate::adapter::pdf::detect(source, limits) {
221        return DocumentFormat::Pdf;
222    }
223    #[cfg(feature = "package")]
224    {
225        if let Some(format) = detect_zip_family(source, limits) {
226            return format;
227        }
228    }
229    // JSON is a Wave-2 structured-tree format with **no** package layer, so it is
230    // detected directly from the whole source (never through `detect_zip_family`).
231    // Conservative: the entire source must parse as exactly one JSON value within
232    // the JSON caps, else the input stays Opaque (Phase 21.5.1).
233    #[cfg(feature = "json")]
234    if crate::adapter::json::detect(source, limits) {
235        return DocumentFormat::Json;
236    }
237    // YAML is the second Wave-2 structured-tree format (Phase 21.6.1), also with
238    // **no** package layer. It is detected directly and conservatively: the whole
239    // source must parse as a bounded YAML stream under the YAML caps, and every
240    // document root must be a mapping or a sequence, else the input stays Opaque.
241    #[cfg(feature = "yaml")]
242    if crate::adapter::yaml::detect(source, limits) {
243        return DocumentFormat::Yaml;
244    }
245    DocumentFormat::Opaque
246}
247
248/// Whether `source` is a structurally valid ZIP archive.
249///
250/// Used by the universal ingest dispatcher so a generic ZIP (which detection
251/// reports as `Opaque`) is still inverted through the byte-authoritative package
252/// layer rather than the opaque floor.
253#[cfg(feature = "package")]
254pub fn is_zip(source: &[u8], limits: Limits) -> bool {
255    crate::adapter::package::scan(source, limits).is_ok()
256}
257
258#[cfg(feature = "package")]
259fn detect_zip_family(source: &[u8], limits: Limits) -> Option<DocumentFormat> {
260    let physical = crate::adapter::package::scan(source, limits).ok()?;
261
262    // EPUB (OCF): the mandatory `mimetype` member, or an OCF container that
263    // resolves to an OPF rootfile.
264    let mimetype = member_decoded(&physical, source, EPUB_MIMETYPE_MEMBER, limits);
265    let mimetype_ok = mimetype.as_deref() == Some(EPUB_MIMETYPE);
266    let container = member_decoded(&physical, source, CONTAINER_MEMBER, limits);
267    let container_ok = container
268        .as_deref()
269        .is_some_and(|c| contains(c, CONTAINER_NS) && contains(c, OPF_MEDIA_TYPE));
270    let is_epub = mimetype_ok || container_ok;
271
272    // DOCX: an OPC package whose content types declare a WordprocessingML main
273    // part, or whose package relationships declare an `officeDocument` part that
274    // targets `word/document.xml`. The positive WordprocessingML signal (rather
275    // than the mere absence of a SpreadsheetML one) keeps DOCX and XLSX mutually
276    // exclusive without misclassifying a Word document that *embeds* an Excel
277    // workbook (whose package declares SpreadsheetML content types for the
278    // embedded part, but no SpreadsheetML workbook main part). Without `xlsx`
279    // and `pptx` the legacy relationship-only rule stands.
280    let content_types = member_decoded(&physical, source, CONTENT_TYPES_MEMBER, limits);
281    let rels = member_decoded(&physical, source, PACKAGE_RELS_MEMBER, limits);
282    #[cfg(any(feature = "xlsx", feature = "pptx"))]
283    let is_docx = content_types
284        .as_deref()
285        .is_some_and(|ct| contains(ct, DOCX_MAIN_FRAGMENT))
286        || rels.as_deref().is_some_and(|r| {
287            contains(r, OFFICE_DOCUMENT_FRAGMENT) && contains(r, DOCX_MAIN_TARGET)
288        });
289    #[cfg(not(any(feature = "xlsx", feature = "pptx")))]
290    let is_docx = content_types.is_some()
291        && rels
292            .as_deref()
293            .is_some_and(|r| contains(r, OFFICE_DOCUMENT_FRAGMENT));
294
295    // XLSX: an OPC package whose content types declare a SpreadsheetML workbook
296    // (or whose `officeDocument` relationship targets a workbook part).
297    #[cfg(feature = "xlsx")]
298    let is_xlsx = content_types.as_deref().is_some_and(|ct| {
299        contains(ct, XLSX_MAIN_FRAGMENT)
300            || (contains(ct, XLSX_NS_FRAGMENT)
301                && rels
302                    .as_deref()
303                    .is_some_and(|r| contains(r, XLSX_WORKBOOK_TARGET)))
304    });
305    #[cfg(not(feature = "xlsx"))]
306    let is_xlsx = false;
307
308    // PPTX: an OPC package whose content types declare a PresentationML main part
309    // (or whose content types name PresentationML and whose `officeDocument`
310    // relationship targets `ppt/presentation.xml`). The positive PresentationML
311    // signal keeps it mutually exclusive with DOCX and XLSX: a Word/Excel document
312    // that *embeds* a PowerPoint part declares only the PresentationML embed type
313    // (`…presentationml.presentation`, not the `.main+xml` main part) and its
314    // `officeDocument` relationship targets `word/document.xml`/`xl/workbook.xml`,
315    // so it is never misclassified as PPTX.
316    #[cfg(feature = "pptx")]
317    let is_pptx = content_types.as_deref().is_some_and(|ct| {
318        contains(ct, PPTX_MAIN_FRAGMENT)
319            || (contains(ct, PPTX_NS_FRAGMENT)
320                && rels
321                    .as_deref()
322                    .is_some_and(|r| contains(r, PPTX_MAIN_TARGET)))
323    });
324    #[cfg(not(feature = "pptx"))]
325    let is_pptx = false;
326
327    // ODT: an ODF package whose mandatory `mimetype` (or `META-INF/manifest.xml`)
328    // declares an OpenDocument text media type.
329    #[cfg(feature = "odt")]
330    let is_odt = mimetype
331        .as_deref()
332        .is_some_and(|m| contains(m, ODT_TEXT_FRAGMENT))
333        || member_decoded(&physical, source, ODT_MANIFEST_MEMBER, limits)
334            .as_deref()
335            .is_some_and(|m| contains(m, ODT_TEXT_FRAGMENT));
336    #[cfg(not(feature = "odt"))]
337    let is_odt = false;
338
339    // ODS: an ODF package whose mandatory `mimetype` (or `META-INF/manifest.xml`)
340    // declares an OpenDocument *spreadsheet* media type. The positive spreadsheet
341    // fragment keeps it mutually exclusive with ODT (a text document declares the
342    // text media type, never the spreadsheet one).
343    #[cfg(feature = "ods")]
344    let is_ods = mimetype
345        .as_deref()
346        .is_some_and(|m| contains(m, ODS_SPREADSHEET_FRAGMENT))
347        || member_decoded(&physical, source, ODS_MANIFEST_MEMBER, limits)
348            .as_deref()
349            .is_some_and(|m| contains(m, ODS_SPREADSHEET_FRAGMENT));
350    #[cfg(not(feature = "ods"))]
351    let is_ods = false;
352
353    // ODP: an ODF package whose mandatory `mimetype` (or `META-INF/manifest.xml`)
354    // declares an OpenDocument *presentation* media type. The positive presentation
355    // fragment keeps it mutually exclusive with ODT/ODS.
356    #[cfg(feature = "odp")]
357    let is_odp = mimetype
358        .as_deref()
359        .is_some_and(|m| contains(m, ODP_PRESENTATION_FRAGMENT))
360        || member_decoded(&physical, source, ODP_MANIFEST_MEMBER, limits)
361            .as_deref()
362            .is_some_and(|m| contains(m, ODP_PRESENTATION_FRAGMENT));
363    #[cfg(not(feature = "odp"))]
364    let is_odp = false;
365
366    // A ZIP matching more than one native signature is ambiguous: fail safe.
367    let matches = [is_docx, is_epub, is_odt, is_ods, is_odp, is_xlsx, is_pptx]
368        .iter()
369        .filter(|b| **b)
370        .count();
371    match matches {
372        1 if is_docx => Some(DocumentFormat::Docx),
373        1 if is_epub => Some(DocumentFormat::Epub),
374        1 if is_odt => Some(DocumentFormat::Odt),
375        1 if is_ods => Some(DocumentFormat::Ods),
376        1 if is_odp => Some(DocumentFormat::Odp),
377        1 if is_xlsx => Some(DocumentFormat::Xlsx),
378        1 if is_pptx => Some(DocumentFormat::Pptx),
379        _ => None,
380    }
381}
382
383#[cfg(feature = "package")]
384const EPUB_MIMETYPE_MEMBER: &[u8] = b"mimetype";
385
386/// Decode one member's bytes by exact name, bounded and decline-safe: encrypted,
387/// oversized, unsupported-method, or out-of-range members yield `None`.
388#[cfg(feature = "package")]
389fn member_decoded(
390    physical: &crate::adapter::package::ZipPhysical,
391    source: &[u8],
392    name: &[u8],
393    limits: Limits,
394) -> Option<Vec<u8>> {
395    const FLAG_ENCRYPTED: u16 = 0x0001;
396    let member = physical.members.iter().find(|m| m.name == name)?;
397    if member.flags & FLAG_ENCRYPTED != 0 || member.uncompressed_size > limits.max_xml_part_bytes {
398        return None;
399    }
400    let off = usize::try_from(member.data.0).ok()?;
401    let len = usize::try_from(member.data.1).ok()?;
402    let raw = source.get(off..off.checked_add(len)?)?;
403    match member.method {
404        0 => Some(raw.to_vec()),
405        8 => crate::field::derive::inflate_raw_deflate(raw, member.uncompressed_size, limits).ok(),
406        _ => None,
407    }
408}
409
410/// Byte-substring search (no allocation, case-sensitive).
411#[cfg(feature = "package")]
412fn contains(haystack: &[u8], needle: &[u8]) -> bool {
413    !needle.is_empty()
414        && needle.len() <= haystack.len()
415        && haystack.windows(needle.len()).any(|w| w == needle)
416}
417
418#[cfg(test)]
419mod tests {
420    use super::*;
421
422    #[test]
423    fn names_and_provenance_roundtrip() {
424        for f in [
425            DocumentFormat::Pdf,
426            DocumentFormat::Docx,
427            DocumentFormat::Epub,
428            DocumentFormat::Odt,
429            DocumentFormat::Ods,
430            DocumentFormat::Odp,
431            DocumentFormat::Xlsx,
432            DocumentFormat::Pptx,
433            DocumentFormat::Json,
434            DocumentFormat::Yaml,
435            DocumentFormat::Opaque,
436        ] {
437            let token = format!("{}field:package;members=1", f.provenance_prefix());
438            assert_eq!(DocumentFormat::from_provenance(&token), Some(f));
439        }
440        assert_eq!(DocumentFormat::from_provenance("field:ingest-b"), None);
441        assert_eq!(DocumentFormat::from_provenance("format=exotic;x"), None);
442    }
443
444    #[test]
445    fn plain_bytes_are_opaque() {
446        assert_eq!(
447            detect_document_format(b"not a document", Limits::DEFAULT),
448            DocumentFormat::Opaque
449        );
450    }
451
452    #[test]
453    fn a_corpus_pdf_is_detected() {
454        let (_, pdf) = crate::adapter::pdf::sample_pdfs()
455            .into_iter()
456            .next()
457            .expect("the PDF corpus is non-empty");
458        assert_eq!(
459            detect_document_format(&pdf, Limits::DEFAULT),
460            DocumentFormat::Pdf
461        );
462    }
463}