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 /// Anything else; preserved exactly by the opaque floor.
127 Opaque,
128}
129
130impl DocumentFormat {
131 /// Stable lower-case name (used in JSON and in the manifest provenance token).
132 pub const fn name(self) -> &'static str {
133 match self {
134 DocumentFormat::Pdf => "pdf",
135 DocumentFormat::Docx => "docx",
136 DocumentFormat::Epub => "epub",
137 DocumentFormat::Odt => "odt",
138 DocumentFormat::Ods => "ods",
139 DocumentFormat::Odp => "odp",
140 DocumentFormat::Xlsx => "xlsx",
141 DocumentFormat::Pptx => "pptx",
142 DocumentFormat::Json => "json",
143 DocumentFormat::Opaque => "opaque",
144 }
145 }
146
147 /// The adapter that serves this format (the observation layer's name for it).
148 pub const fn adapter(self) -> &'static str {
149 match self {
150 DocumentFormat::Pdf => "pdf",
151 DocumentFormat::Docx => "docx",
152 DocumentFormat::Epub => "epub",
153 DocumentFormat::Odt => "odt",
154 DocumentFormat::Ods => "ods",
155 DocumentFormat::Odp => "odp",
156 DocumentFormat::Xlsx => "xlsx",
157 DocumentFormat::Pptx => "pptx",
158 DocumentFormat::Json => "json",
159 DocumentFormat::Opaque => "opaque",
160 }
161 }
162
163 /// Whether the adapter for this format is compiled into this build.
164 pub const fn compiled(self) -> bool {
165 match self {
166 DocumentFormat::Pdf | DocumentFormat::Opaque => true,
167 DocumentFormat::Docx => cfg!(feature = "docx"),
168 DocumentFormat::Epub => cfg!(feature = "epub"),
169 DocumentFormat::Odt => cfg!(feature = "odt"),
170 DocumentFormat::Ods => cfg!(feature = "ods"),
171 DocumentFormat::Odp => cfg!(feature = "odp"),
172 DocumentFormat::Xlsx => cfg!(feature = "xlsx"),
173 DocumentFormat::Pptx => cfg!(feature = "pptx"),
174 DocumentFormat::Json => cfg!(feature = "json"),
175 }
176 }
177
178 /// The machine-readable `format=<name>;` provenance prefix recorded at ingest.
179 pub fn provenance_prefix(self) -> String {
180 format!("format={};", self.name())
181 }
182
183 /// Recover the recorded format from a field manifest's provenance string.
184 ///
185 /// Returns `None` for a manifest that does not carry the token (e.g. a field
186 /// written before this subphase); such a field still serves every native
187 /// selector, but common observations decline typed rather than guessing.
188 pub fn from_provenance(provenance: &str) -> Option<DocumentFormat> {
189 let rest = provenance.strip_prefix("format=")?;
190 let name = rest.split(';').next()?;
191 match name {
192 "pdf" => Some(DocumentFormat::Pdf),
193 "docx" => Some(DocumentFormat::Docx),
194 "epub" => Some(DocumentFormat::Epub),
195 "odt" => Some(DocumentFormat::Odt),
196 "ods" => Some(DocumentFormat::Ods),
197 "odp" => Some(DocumentFormat::Odp),
198 "xlsx" => Some(DocumentFormat::Xlsx),
199 "pptx" => Some(DocumentFormat::Pptx),
200 "json" => Some(DocumentFormat::Json),
201 "opaque" => Some(DocumentFormat::Opaque),
202 _ => None,
203 }
204 }
205}
206
207/// Detect the document format of `source` from its bytes alone.
208///
209/// Never consults a file name or extension. A malformed or ambiguous input (or a
210/// format whose adapter is not compiled) falls back to [`DocumentFormat::Opaque`].
211pub fn detect_document_format(source: &[u8], limits: Limits) -> DocumentFormat {
212 if crate::adapter::pdf::detect(source, limits) {
213 return DocumentFormat::Pdf;
214 }
215 #[cfg(feature = "package")]
216 {
217 if let Some(format) = detect_zip_family(source, limits) {
218 return format;
219 }
220 }
221 // JSON is a Wave-2 structured-tree format with **no** package layer, so it is
222 // detected directly from the whole source (never through `detect_zip_family`).
223 // Conservative: the entire source must parse as exactly one JSON value within
224 // the JSON caps, else the input stays Opaque (Phase 21.5.1).
225 #[cfg(feature = "json")]
226 if crate::adapter::json::detect(source, limits) {
227 return DocumentFormat::Json;
228 }
229 DocumentFormat::Opaque
230}
231
232/// Whether `source` is a structurally valid ZIP archive.
233///
234/// Used by the universal ingest dispatcher so a generic ZIP (which detection
235/// reports as `Opaque`) is still inverted through the byte-authoritative package
236/// layer rather than the opaque floor.
237#[cfg(feature = "package")]
238pub fn is_zip(source: &[u8], limits: Limits) -> bool {
239 crate::adapter::package::scan(source, limits).is_ok()
240}
241
242#[cfg(feature = "package")]
243fn detect_zip_family(source: &[u8], limits: Limits) -> Option<DocumentFormat> {
244 let physical = crate::adapter::package::scan(source, limits).ok()?;
245
246 // EPUB (OCF): the mandatory `mimetype` member, or an OCF container that
247 // resolves to an OPF rootfile.
248 let mimetype = member_decoded(&physical, source, EPUB_MIMETYPE_MEMBER, limits);
249 let mimetype_ok = mimetype.as_deref() == Some(EPUB_MIMETYPE);
250 let container = member_decoded(&physical, source, CONTAINER_MEMBER, limits);
251 let container_ok = container
252 .as_deref()
253 .is_some_and(|c| contains(c, CONTAINER_NS) && contains(c, OPF_MEDIA_TYPE));
254 let is_epub = mimetype_ok || container_ok;
255
256 // DOCX: an OPC package whose content types declare a WordprocessingML main
257 // part, or whose package relationships declare an `officeDocument` part that
258 // targets `word/document.xml`. The positive WordprocessingML signal (rather
259 // than the mere absence of a SpreadsheetML one) keeps DOCX and XLSX mutually
260 // exclusive without misclassifying a Word document that *embeds* an Excel
261 // workbook (whose package declares SpreadsheetML content types for the
262 // embedded part, but no SpreadsheetML workbook main part). Without `xlsx`
263 // and `pptx` the legacy relationship-only rule stands.
264 let content_types = member_decoded(&physical, source, CONTENT_TYPES_MEMBER, limits);
265 let rels = member_decoded(&physical, source, PACKAGE_RELS_MEMBER, limits);
266 #[cfg(any(feature = "xlsx", feature = "pptx"))]
267 let is_docx = content_types
268 .as_deref()
269 .is_some_and(|ct| contains(ct, DOCX_MAIN_FRAGMENT))
270 || rels.as_deref().is_some_and(|r| {
271 contains(r, OFFICE_DOCUMENT_FRAGMENT) && contains(r, DOCX_MAIN_TARGET)
272 });
273 #[cfg(not(any(feature = "xlsx", feature = "pptx")))]
274 let is_docx = content_types.is_some()
275 && rels
276 .as_deref()
277 .is_some_and(|r| contains(r, OFFICE_DOCUMENT_FRAGMENT));
278
279 // XLSX: an OPC package whose content types declare a SpreadsheetML workbook
280 // (or whose `officeDocument` relationship targets a workbook part).
281 #[cfg(feature = "xlsx")]
282 let is_xlsx = content_types.as_deref().is_some_and(|ct| {
283 contains(ct, XLSX_MAIN_FRAGMENT)
284 || (contains(ct, XLSX_NS_FRAGMENT)
285 && rels
286 .as_deref()
287 .is_some_and(|r| contains(r, XLSX_WORKBOOK_TARGET)))
288 });
289 #[cfg(not(feature = "xlsx"))]
290 let is_xlsx = false;
291
292 // PPTX: an OPC package whose content types declare a PresentationML main part
293 // (or whose content types name PresentationML and whose `officeDocument`
294 // relationship targets `ppt/presentation.xml`). The positive PresentationML
295 // signal keeps it mutually exclusive with DOCX and XLSX: a Word/Excel document
296 // that *embeds* a PowerPoint part declares only the PresentationML embed type
297 // (`…presentationml.presentation`, not the `.main+xml` main part) and its
298 // `officeDocument` relationship targets `word/document.xml`/`xl/workbook.xml`,
299 // so it is never misclassified as PPTX.
300 #[cfg(feature = "pptx")]
301 let is_pptx = content_types.as_deref().is_some_and(|ct| {
302 contains(ct, PPTX_MAIN_FRAGMENT)
303 || (contains(ct, PPTX_NS_FRAGMENT)
304 && rels
305 .as_deref()
306 .is_some_and(|r| contains(r, PPTX_MAIN_TARGET)))
307 });
308 #[cfg(not(feature = "pptx"))]
309 let is_pptx = false;
310
311 // ODT: an ODF package whose mandatory `mimetype` (or `META-INF/manifest.xml`)
312 // declares an OpenDocument text media type.
313 #[cfg(feature = "odt")]
314 let is_odt = mimetype
315 .as_deref()
316 .is_some_and(|m| contains(m, ODT_TEXT_FRAGMENT))
317 || member_decoded(&physical, source, ODT_MANIFEST_MEMBER, limits)
318 .as_deref()
319 .is_some_and(|m| contains(m, ODT_TEXT_FRAGMENT));
320 #[cfg(not(feature = "odt"))]
321 let is_odt = false;
322
323 // ODS: an ODF package whose mandatory `mimetype` (or `META-INF/manifest.xml`)
324 // declares an OpenDocument *spreadsheet* media type. The positive spreadsheet
325 // fragment keeps it mutually exclusive with ODT (a text document declares the
326 // text media type, never the spreadsheet one).
327 #[cfg(feature = "ods")]
328 let is_ods = mimetype
329 .as_deref()
330 .is_some_and(|m| contains(m, ODS_SPREADSHEET_FRAGMENT))
331 || member_decoded(&physical, source, ODS_MANIFEST_MEMBER, limits)
332 .as_deref()
333 .is_some_and(|m| contains(m, ODS_SPREADSHEET_FRAGMENT));
334 #[cfg(not(feature = "ods"))]
335 let is_ods = false;
336
337 // ODP: an ODF package whose mandatory `mimetype` (or `META-INF/manifest.xml`)
338 // declares an OpenDocument *presentation* media type. The positive presentation
339 // fragment keeps it mutually exclusive with ODT/ODS.
340 #[cfg(feature = "odp")]
341 let is_odp = mimetype
342 .as_deref()
343 .is_some_and(|m| contains(m, ODP_PRESENTATION_FRAGMENT))
344 || member_decoded(&physical, source, ODP_MANIFEST_MEMBER, limits)
345 .as_deref()
346 .is_some_and(|m| contains(m, ODP_PRESENTATION_FRAGMENT));
347 #[cfg(not(feature = "odp"))]
348 let is_odp = false;
349
350 // A ZIP matching more than one native signature is ambiguous: fail safe.
351 let matches = [is_docx, is_epub, is_odt, is_ods, is_odp, is_xlsx, is_pptx]
352 .iter()
353 .filter(|b| **b)
354 .count();
355 match matches {
356 1 if is_docx => Some(DocumentFormat::Docx),
357 1 if is_epub => Some(DocumentFormat::Epub),
358 1 if is_odt => Some(DocumentFormat::Odt),
359 1 if is_ods => Some(DocumentFormat::Ods),
360 1 if is_odp => Some(DocumentFormat::Odp),
361 1 if is_xlsx => Some(DocumentFormat::Xlsx),
362 1 if is_pptx => Some(DocumentFormat::Pptx),
363 _ => None,
364 }
365}
366
367#[cfg(feature = "package")]
368const EPUB_MIMETYPE_MEMBER: &[u8] = b"mimetype";
369
370/// Decode one member's bytes by exact name, bounded and decline-safe: encrypted,
371/// oversized, unsupported-method, or out-of-range members yield `None`.
372#[cfg(feature = "package")]
373fn member_decoded(
374 physical: &crate::adapter::package::ZipPhysical,
375 source: &[u8],
376 name: &[u8],
377 limits: Limits,
378) -> Option<Vec<u8>> {
379 const FLAG_ENCRYPTED: u16 = 0x0001;
380 let member = physical.members.iter().find(|m| m.name == name)?;
381 if member.flags & FLAG_ENCRYPTED != 0 || member.uncompressed_size > limits.max_xml_part_bytes {
382 return None;
383 }
384 let off = usize::try_from(member.data.0).ok()?;
385 let len = usize::try_from(member.data.1).ok()?;
386 let raw = source.get(off..off.checked_add(len)?)?;
387 match member.method {
388 0 => Some(raw.to_vec()),
389 8 => crate::field::derive::inflate_raw_deflate(raw, member.uncompressed_size, limits).ok(),
390 _ => None,
391 }
392}
393
394/// Byte-substring search (no allocation, case-sensitive).
395#[cfg(feature = "package")]
396fn contains(haystack: &[u8], needle: &[u8]) -> bool {
397 !needle.is_empty()
398 && needle.len() <= haystack.len()
399 && haystack.windows(needle.len()).any(|w| w == needle)
400}
401
402#[cfg(test)]
403mod tests {
404 use super::*;
405
406 #[test]
407 fn names_and_provenance_roundtrip() {
408 for f in [
409 DocumentFormat::Pdf,
410 DocumentFormat::Docx,
411 DocumentFormat::Epub,
412 DocumentFormat::Odt,
413 DocumentFormat::Ods,
414 DocumentFormat::Odp,
415 DocumentFormat::Xlsx,
416 DocumentFormat::Pptx,
417 DocumentFormat::Json,
418 DocumentFormat::Opaque,
419 ] {
420 let token = format!("{}field:package;members=1", f.provenance_prefix());
421 assert_eq!(DocumentFormat::from_provenance(&token), Some(f));
422 }
423 assert_eq!(DocumentFormat::from_provenance("field:ingest-b"), None);
424 assert_eq!(DocumentFormat::from_provenance("format=exotic;x"), None);
425 }
426
427 #[test]
428 fn plain_bytes_are_opaque() {
429 assert_eq!(
430 detect_document_format(b"not a document", Limits::DEFAULT),
431 DocumentFormat::Opaque
432 );
433 }
434
435 #[test]
436 fn a_corpus_pdf_is_detected() {
437 let (_, pdf) = crate::adapter::pdf::sample_pdfs()
438 .into_iter()
439 .next()
440 .expect("the PDF corpus is non-empty");
441 assert_eq!(
442 detect_document_format(&pdf, Limits::DEFAULT),
443 DocumentFormat::Pdf
444 );
445 }
446}