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.
pub use ;
pub use ;
use BTreeMap;
use Future;
use PathBuf;
use Pin;
use 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.
/// 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.
/// 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.
/// 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`].
pub
/// Result of a library operation, with [`Error`] describing failure.
pub type Result<T> = Result;
/// 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> = ;
/// Boxed future returned by [`Adapter::inspect`].
pub type InspectFuture<'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(())
/// # }
/// ```
/// An adapter's reported availability and diagnostic detail.
/// 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.