convert-rs 2.0.0

Extensible file conversion library with graph routing and optional native tools
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
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
//! File conversion through a policy-controlled graph of independent adapters.
//!
//! Use [`Converter::new`] for compiled-in pure-Rust adapters. With the `external`
//! feature, `Converter::discover().await` also probes installed native tools.
//! Discovery does not enable external routes; set [`Policy::allow_external`]
//! explicitly. Register additional implementations through [`Converter::register`].
//!
//! # Convert a file
//!
//! Conversion requires a Tokio runtime. This example uses only the byte/text API
//! and no native tools. A same-format request stages a byte-for-byte copy without
//! decoding, validating the claimed format, or choosing a codec.
//!
//! ```rust
//! use convert_rs::{ConversionOptions, Converter};
//!
//! # #[tokio::main(flavor = "current_thread")]
//! # async fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let inputs = tempfile::tempdir()?;
//! let source = inputs.path().join("note.txt");
//! std::fs::write(&source, "Conversion example\n")?;
//! let converter = Converter::new();
//! let report = converter.convert(&[source], "txt", &ConversionOptions::default()).await?;
//! assert!(report.plan.steps.is_empty());
//! assert!(report.warnings.is_empty());
//! assert_eq!(std::fs::read_to_string(&report.artifacts[0].path)?, "Conversion example\n");
//! // Persist output outside the report-owned workspace before dropping it.
//! let saved = inputs.path().join("saved.txt");
//! std::fs::copy(&report.artifacts[0].path, &saved)?;
//! let temporary = report.artifacts[0].path.clone();
//! drop(report);
//! assert!(!temporary.exists());
//! assert!(saved.exists());
//! # Ok(())
//! # }
//! ```
//!
//! # Features and fidelity
//!
//! Default features are `data` (JSON, TOML, CSV), `media` (image and audio
//! operations), `archives` (archive and compression operations), and `external`
//! (native-tool discovery). Without default features, the built-in byte and text
//! operations remain. Registered formats and available routes depend on features
//! and adapters; listing a format does not promise an encoder for every input.
//!
//! Plans use adapter-declared costs and semantic classifications. The default
//! policy permits lossy conversions. There is no lossless-only policy flag:
//! inspect [`Plan::steps`] and, if appropriate, execute a reviewed forced plan.
//! [`ConversionReport::warnings`] describes non-lossless steps of the successful
//! route, not measured quality loss or every possible metadata change. An empty
//! warning list is not proof of complete fidelity. No public option selects
//! codecs, bitrates, or encoder quality settings.
//!
//! # Execution boundaries
//!
//! Inputs are staged separately for each attempted route. Final paths belong to
//! the returned [`ConversionReport`] and are removed when it is dropped. Cloning
//! an [`Artifact`] does not keep its file alive. Returned output paths, declared
//! formats, counts, and byte totals are checked, but file contents are not
//! independently decoded by the engine to verify their declared format.
//!
//! [`Limits`] provides staging checks and adapter-specific budgets, not a hard
//! memory, CPU, disk, or wall-clock sandbox. Custom adapters are trusted code.
//! Native tools require operating-system isolation when processing hostile data;
//! this library does not provide that isolation.
#![warn(missing_docs)]

#[cfg(feature = "archives")]
mod archives;
mod builtin;
mod engine;
#[cfg(feature = "external")]
mod external;
#[cfg(feature = "media")]
mod media;
#[cfg(feature = "external")]
mod process;

pub use convert_rs_core::{
    ContentKind, ContentProfile, Conversion, ConversionCategory, ConversionKind, Format, Graph,
    MediaKind, Plan, Policy, Stream,
};
pub use engine::{
    CapabilityReason, ConversionOptions, ConversionReport, Converter, Identification,
    IdentificationMethod, InputReport, ProfileReport, ProfileSource, RouteAttempt, StepCost,
    TargetCapability, Warning,
};

use std::collections::BTreeMap;
use std::future::Future;
use std::path::PathBuf;
use std::pin::Pin;
use std::time::Duration;

/// A path and declared format for a staged input or adapter output.
///
/// Artifact vectors preserve order. This value neither owns the file nor verifies
/// its contents. Cloning it clones only the path and format; report output files
/// remain owned by the [`ConversionReport`]'s temporary directory.
///
/// Construct through [`Artifact::new`]; the struct is `#[non_exhaustive]` so new
/// fields can be added without breaking semver. Direct struct literals only
/// compile inside this crate.
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct Artifact {
    /// Path to the artifact in the report-owned temporary workspace.
    pub path: PathBuf,
    /// Canonical format ID for the artifact.
    pub format: String,
    /// Logical name this file had (or should have) outside the workspace.
    ///
    /// Set by extraction adapters to the archive member path and preserved
    /// unchanged through steps that carry files forward. Packaging adapters use
    /// it as the member name when present. It is a naming hint, not a trusted
    /// path: adapters must sanitize it before using it, and the engine never
    /// resolves it against the filesystem.
    pub logical_name: Option<String>,
}

impl Artifact {
    /// Construct an artifact from a path and its declared canonical format ID.
    #[must_use]
    pub fn new(path: impl Into<PathBuf>, format: impl Into<String>) -> Self {
        Self {
            path: path.into(),
            format: format.into(),
            logical_name: None,
        }
    }

    /// Attach a logical name; see [`Self::logical_name`].
    #[must_use]
    pub fn with_logical_name(mut self, name: impl Into<String>) -> Self {
        self.logical_name = Some(name.into());
        self
    }
}

/// Resource budgets used during staging, output checks, and adapter execution.
///
/// The engine enforces input count, input bytes per staged file, and returned
/// output count and aggregate bytes per step, plus a cumulative output byte
/// budget across every step of one attempt. Other checks depend on the adapter.
/// The engine does not wrap arbitrary adapter futures in a timeout, preempt
/// blocking work, or enforce process-wide memory and disk quotas. Budgets do
/// not bound unreported files that adapters create but do not return.
/// Identity copies do not pass through adapter output validation.
///
/// Defaults are 120 seconds, 256 MiB input bytes, 512 MiB output bytes per step,
/// 4 GiB cumulative output bytes per attempt, 256 artifacts, 16 million pixels
/// and audio samples, 256 archive entries, a 100:1 expansion ratio, and a
/// 256 MiB adapter memory budget. Values are not validated
/// by [`Converter::limits`]; zero and small budgets can make operations fail.
#[derive(Clone, Debug)]
pub struct Limits {
    /// Per-invocation time budget used by adapters, not a universal hard deadline.
    ///
    /// Pure-Rust adapters check elapsed time at operation-specific points; native
    /// process execution uses a timeout. Staging and arbitrary custom adapters
    /// are not interrupted by the engine.
    pub timeout: Duration,
    /// Maximum bytes per file during engine staging.
    ///
    /// Some adapters additionally apply this as an aggregate input budget.
    pub max_input_bytes: u64,
    /// Maximum aggregate bytes of returned output files per step.
    ///
    /// Engine validation occurs after the adapter returns; this is not a disk quota.
    pub max_output_bytes: u64,
    /// Maximum bytes summed across every step of a single conversion attempt.
    ///
    /// The engine tracks each validated step's byte total as it executes a route
    /// and exposes the running sum through [`StepRequest::spent_output_bytes`],
    /// so adapters can budget before writing. Unlike [`Self::max_output_bytes`],
    /// which resets per step, this budget covers intermediates: a 6-step route
    /// that emits 1 GiB per step trips a 4 GiB total budget. Zero disables.
    /// Default: 4 GiB.
    pub max_total_output_bytes: u64,
    /// Maximum input count and maximum returned output count per step.
    pub max_artifacts: usize,
    /// Decoded image pixel budget used by media operations, not by engine validation.
    pub max_pixels: u64,
    /// Decoded audio sample budget used by media operations.
    pub max_audio_samples: u64,
    /// Archive entry budget used by archive operations, including directory entries.
    pub max_archive_entries: usize,
    /// Decompression byte expansion ratio used by archive operations.
    pub max_expansion_ratio: u64,
    /// Memory budget for adapter-specific allocation checks, not process resident memory.
    pub max_memory_bytes: u64,
}

impl Default for Limits {
    fn default() -> Self {
        Self {
            timeout: Duration::from_secs(120),
            max_input_bytes: 256 * 1024 * 1024,
            max_output_bytes: 512 * 1024 * 1024,
            max_total_output_bytes: 4 * 1024 * 1024 * 1024,
            max_artifacts: 256,
            max_pixels: 16_000_000,
            max_audio_samples: 16_000_000,
            max_archive_entries: 256,
            max_expansion_ratio: 100,
            max_memory_bytes: 256 * 1024 * 1024,
        }
    }
}

/// One adapter invocation. Adapters must write only inside `output_dir`, must
/// not change inputs, and must return at least one regular file on success.
///
/// The engine creates the output directory before calling the adapter. The
/// adapter is responsible for validating operation-specific inputs, observing
/// limits, and keeping blocking work off the asynchronous executor. The engine
/// checks returned files but does not enforce every part of this contract; in
/// particular, it currently accepts an empty output vector.
#[derive(Clone, Debug)]
pub struct StepRequest {
    /// Ordered staged inputs or outputs from the preceding step; do not mutate them.
    pub inputs: Vec<Artifact>,
    /// Existing private step directory where the adapter must create outputs.
    pub output_dir: PathBuf,
    /// Concrete source format ID, not a filename extension or wildcard.
    pub from: String,
    /// Concrete target format ID that every returned artifact must declare.
    pub to: String,
    /// Adapter-specific operation ID copied from the selected conversion edge.
    pub operation: String,
    /// Resource budgets for this invocation; see [`Limits`] for enforcement scope.
    pub limits: Limits,
    /// Quality knobs copied from [`ConversionOptions::params`](engine::ConversionOptions::params).
    ///
    /// Keys are adapter-defined names such as `quality`; the reserved key
    /// `quality` carries a 0-100 integer string and should be mapped onto the
    /// closest native encoder control. Adapters must ignore unknown keys and
    /// must never treat these values as paths or shell input.
    pub params: BTreeMap<String, String>,
    /// Cumulative bytes the engine has already validated across earlier steps
    /// of the current route, used with [`Limits::max_total_output_bytes`].
    pub spent_output_bytes: u64,
}

impl StepRequest {
    /// Build a request with no params and no prior output spend.
    #[must_use]
    pub fn new(
        inputs: Vec<Artifact>,
        output_dir: impl Into<PathBuf>,
        from: impl Into<String>,
        to: impl Into<String>,
        operation: impl Into<String>,
        limits: Limits,
    ) -> Self {
        Self {
            inputs,
            output_dir: output_dir.into(),
            from: from.into(),
            to: to.into(),
            operation: operation.into(),
            limits,
            params: BTreeMap::new(),
            spent_output_bytes: 0,
        }
    }

    /// Attach quality params; see [`Self::params`].
    #[must_use]
    pub fn with_params(mut self, params: &BTreeMap<String, String>) -> Self {
        self.params = params.clone();
        self
    }

    /// Record cumulative earlier-step output bytes; see [`Self::spent_output_bytes`].
    #[must_use]
    pub fn with_spent_output_bytes(mut self, spent: u64) -> Self {
        self.spent_output_bytes = spent;
        self
    }
}

/// Read the reserved `quality` param as a 1-100 encoder value.
///
/// Unparseable or absent values return `None`; out-of-range values clamp to the
/// supported range. Adapters ignore every other key of [`StepRequest::params`].
#[cfg(any(feature = "media", feature = "external"))]
pub(crate) fn requested_quality(params: &BTreeMap<String, String>) -> Option<u8> {
    let value = params.get("quality")?.trim().parse::<u32>().ok()?;
    Some(value.clamp(1, 100) as u8)
}

/// Result of a library operation, with [`Error`] describing failure.
pub type Result<T> = std::result::Result<T, Error>;
/// A sendable, boxed adapter future yielding ordered artifacts or an [`Error`].
///
/// The lifetime allows the future to borrow both the adapter and its request.
pub type ConversionFuture<'a> = Pin<Box<dyn Future<Output = Result<Vec<Artifact>>> + Send + 'a>>;

/// Boxed future returned by [`Adapter::inspect`].
pub type InspectFuture<'a> =
    Pin<Box<dyn Future<Output = Option<Result<ContentProfile>>> + Send + 'a>>;

/// Output port for conversion backends. Implement this to add formats without
/// changing the planner or orchestrator. Backend names identify registrations;
/// registering the same name replaces its previous implementation.
///
/// Implementations are trusted code, not sandboxed plugins. Advertised metadata
/// should remain stable between calls. Each edge's `backend` must match the
/// adapter's name, and the implementation must reject unsupported operations.
/// Registration validates graph metadata, not this correspondence or fidelity.
///
/// # Register a custom adapter
///
/// This adapter copies one text file into a custom text representation. It uses
/// asynchronous file I/O and checks its input size and timeout explicitly.
///
/// ```rust
/// use std::sync::Arc;
/// use convert_rs::{Adapter, Artifact, Conversion, ConversionFuture, ConversionKind,
///     ConversionOptions, Converter, Error, Format, MediaKind, StepRequest};
///
/// struct NoteAdapter;
/// impl Adapter for NoteAdapter {
///     fn name(&self) -> &str { "note-example" }
///     fn formats(&self) -> Vec<Format> {
///         vec![Format::new("example-note", "Example note", MediaKind::Text)]
///     }
///     fn conversions(&self) -> Vec<Conversion> {
///         vec![Conversion::new("txt", "example-note", self.name(), "copy-note",
///             ConversionKind::Lossless, 1)]
///     }
///     fn convert<'a>(&'a self, request: &'a StepRequest) -> ConversionFuture<'a> {
///         Box::pin(async move {
///             if request.operation != "copy-note" || request.from != "txt"
///                 || request.to != "example-note" || request.inputs.len() != 1 {
///                 return Err(Error::Invalid("unsupported note request".into()));
///             }
///             let job = async {
///                 let size = tokio::fs::metadata(&request.inputs[0].path).await?.len();
///                 if size > request.limits.max_input_bytes
///                     || size > request.limits.max_output_bytes {
///                     return Err(Error::Limit("note bytes".into()));
///                 }
///                 let path = request.output_dir.join("note.example-note");
///                 tokio::fs::copy(&request.inputs[0].path, &path).await?;
///                 Ok(vec![Artifact::new(path, request.to.clone())])
///             };
///             tokio::time::timeout(request.limits.timeout, job).await
///                 .map_err(|_| Error::Timeout { backend: self.name().into() })?
///         })
///     }
/// }
///
/// # #[tokio::main(flavor = "current_thread")]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let mut converter = Converter::new();
/// converter.register(Arc::new(NoteAdapter))?;
/// let inputs = tempfile::tempdir()?;
/// let source = inputs.path().join("note.txt");
/// std::fs::write(&source, "custom adapter")?;
/// let report = converter.convert(&[source], "example-note",
///     &ConversionOptions::default()).await?;
/// assert_eq!(report.plan.steps[0].backend, "note-example");
/// assert_eq!(std::fs::read_to_string(&report.artifacts[0].path)?, "custom adapter");
/// # Ok(())
/// # }
/// ```
pub trait Adapter: Send + Sync {
    /// Stable registration name, nonempty and at most 64 bytes.
    fn name(&self) -> &str;
    /// Format declarations contributed to the graph.
    ///
    /// Registration requires 1 through 8,192 declarations. Edges can also refer
    /// to formats supplied by other registered adapters.
    fn formats(&self) -> Vec<Format>;
    /// Supported directed edges, including their semantic kind and relative cost.
    ///
    /// Registration accepts at most 1,000,000 edges from the incoming adapter.
    fn conversions(&self) -> Vec<Conversion>;
    /// Execute one operation using the [`StepRequest`] contract.
    ///
    /// # Errors
    ///
    /// Return an appropriate [`Error`] for invalid requests, unsupported content,
    /// I/O failure, or exceeded limits. A failed route may be retried through
    /// another adapter; do not rely on side effects outside the output directory.
    fn convert<'a>(&'a self, request: &'a StepRequest) -> ConversionFuture<'a>;

    /// Return availability information for this adapter.
    ///
    /// The default reports availability unconditionally with an empty detail.
    /// An implementation may return cached discovery results rather than probe
    /// again. Availability is informational and does not guarantee execution.
    fn status(&self) -> BackendStatus {
        BackendStatus {
            name: self.name().to_owned(),
            available: true,
            detail: String::new(),
        }
    }

    /// List the [`StepRequest::params`] keys this operation consumes.
    ///
    /// The engine uses the union over an executed route's steps to report params
    /// that no step honored as [`ConversionReport::ignored_params`](engine::ConversionReport::ignored_params),
    /// surfacing typos instead of silently discarding knobs. The `engine` key
    /// prefix is reserved. The default declares no supported keys.
    fn param_keys(&self, _operation: &str) -> Vec<String> {
        Vec::new()
    }

    /// Deep-check whether `path` really decodes as `format`.
    ///
    /// [`engine::ConversionOptions::verify`](engine::ConversionOptions::verify)
    /// first re-sniffs magic signatures, then asks available adapters that own
    /// the format. `Some(true)` confirms, `Some(false)` rejects the artifact and
    /// fails the route, and `None` (the default) expresses no opinion and never
    /// blocks verification. Implementations must not allocate more than
    /// `limits.max_input_bytes` and must treat the file as hostile input.
    fn accepts_input(
        &self,
        _path: &std::path::Path,
        _format: &str,
        _limits: &Limits,
    ) -> Option<bool> {
        None
    }

    /// Report the content streams this adapter observes inside `path`.
    ///
    /// [`Converter::profile`](crate::Converter::profile) and profile-driven
    /// planning call this on adapters available for the identified format. The
    /// default returns `None`, meaning this adapter has no content view and the
    /// engine falls back to another adapter or to declared [`Format::payloads`].
    ///
    /// Implementations must not allocate more than `limits.max_input_bytes`,
    /// must stay within `limits.timeout`, and must treat the file as hostile
    /// input. A returned profile's `format` field must equal `format`; an
    /// adapter that inspects the file but finds no describable streams returns
    /// `Some` with an empty stream list, and returns `Err` when inspection of
    /// this file fails.
    fn inspect<'a>(
        &'a self,
        _path: &'a std::path::Path,
        _format: &'a str,
        _limits: &'a Limits,
    ) -> InspectFuture<'a> {
        Box::pin(async { None })
    }
}

/// An adapter's reported availability and diagnostic detail.
#[derive(Clone, Debug)]
pub struct BackendStatus {
    /// Registered adapter name.
    pub name: String,
    /// Whether the adapter reports itself available; not a per-file capability check.
    pub available: bool,
    /// Human-readable probe details.
    pub detail: String,
}

/// Failures from registration, identification, planning, and execution.
///
/// Errors raised while attempting routes are rendered into [`Self::RoutesFailed`]
/// by [`Converter::convert`], rather than returned as their original variants.
#[derive(Debug, thiserror::Error)]
pub enum Error {
    /// A filesystem or other I/O operation failed.
    #[error(transparent)]
    Io(
        /// Underlying I/O failure.
        #[from]
        std::io::Error,
    ),
    /// Graph registration or route search failed.
    #[error(transparent)]
    Plan(
        /// Underlying graph or search failure.
        #[from]
        convert_rs_core::PlanError,
    ),
    /// Invalid caller input or unsupported request parameters.
    #[error("invalid request: {0}")]
    Invalid(
        /// Explanation of the rejected request.
        String,
    ),
    /// An adapter operation or artifact format check failed.
    #[error("conversion failed: {0}")]
    Conversion(
        /// Adapter or output-validation failure details.
        String,
    ),
    /// An adapter reported exceeding its time budget.
    #[error("{backend} exceeded its timeout")]
    Timeout {
        /// Name of the adapter whose time budget was exceeded.
        backend: String,
    },
    /// A checked resource budget was exceeded.
    #[error("resource limit exceeded: {0}")]
    Limit(
        /// Description of the exceeded budget.
        String,
    ),
    /// A policy or input/output safety check rejected the operation.
    #[error("security policy rejected input: {0}")]
    Security(
        /// Description of the rejected condition.
        String,
    ),
    /// Every attempted route failed, with route descriptions and rendered errors.
    ///
    /// Only routes returned within the planner's budgets are attempted. This
    /// does not mean every possible graph route was tried.
    #[error("all attempted routes failed: {0}")]
    RoutesFailed(
        /// Semicolon-separated route descriptions and rendered failure messages.
        String,
    ),
}