fastxml 0.8.1

A fast, memory-efficient XML library with XPath and XSD validation support
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
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
//! CLI tool for XML schema validation.
//!
//! Usage: `fastxml-validate [OPTIONS] <FILES>...`
//!
//! Run with: `cargo run --features ureq --bin fastxml-validate -- <files>`

#![allow(clippy::collapsible_if)]

use std::fs::File;
use std::io::{BufReader, Read};
use std::path::Path;
use std::sync::{Arc, Mutex};
use std::time::Instant;

use clap::Parser;
use serde::Serialize;

use fastxml::error::StructuredError;
use fastxml::schema::{
    DefaultFetcher, FetchResult, SchemaFetcher, streaming_validate_with_schema_location_and_fetcher,
};

/// XML Schema Validator CLI
#[derive(Parser, Debug)]
#[command(name = "fastxml-validate")]
#[command(author, version, about = "Validate XML files against XSD schemas", long_about = None)]
struct Args {
    /// XML files to validate (local paths or URLs)
    #[arg(required = true)]
    files: Vec<String>,

    /// Schema file path (default: auto-detect from xsi:schemaLocation)
    #[arg(short, long, value_name = "PATH")]
    schema: Option<String>,

    /// Output as JSON
    #[arg(short, long)]
    json: bool,

    /// Only show errors (no timing/memory info)
    #[arg(short, long)]
    quiet: bool,

    /// Show detailed validation progress
    #[arg(short, long)]
    verbose: bool,

    /// Show timing and memory statistics
    #[arg(long)]
    stats: bool,
}

/// Result for a single file validation
#[derive(Debug, Serialize)]
struct FileResult {
    path: String,
    size_bytes: u64,
    valid: bool,
    errors: Vec<ErrorInfo>,
    schemas_downloaded: Vec<String>,
    time_ms: u64,
    throughput_mb_s: f64,
}

/// Error information for JSON output
#[derive(Debug, Serialize)]
struct ErrorInfo {
    line: Option<usize>,
    column: Option<usize>,
    level: String,
    message: String,
}

/// Summary of all validations
#[derive(Debug, Serialize)]
struct Summary {
    total: usize,
    valid: usize,
    invalid: usize,
}

/// Full JSON output
#[derive(Debug, Serialize)]
struct JsonOutput {
    files: Vec<FileResult>,
    summary: Summary,
}

impl From<&StructuredError> for ErrorInfo {
    fn from(err: &StructuredError) -> Self {
        ErrorInfo {
            line: err.line(),
            column: err.column(),
            level: err.level.to_string(),
            message: err.message.clone(),
        }
    }
}

fn main() {
    let args = Args::parse();

    match run(&args) {
        Ok(exit_code) => std::process::exit(exit_code),
        Err(e) => {
            eprintln!("Error: {}", e);
            std::process::exit(2);
        }
    }
}

fn run(args: &Args) -> Result<i32, Box<dyn std::error::Error>> {
    let mut results = Vec::new();
    let cache = Arc::new(DefaultFetcher::new());
    let downloaded_urls = Arc::new(Mutex::new(Vec::<String>::new()));

    for file_path in &args.files {
        let result = validate_file(
            file_path,
            args,
            Arc::clone(&cache),
            Arc::clone(&downloaded_urls),
        )?;
        results.push(result);
    }

    let valid_count = results.iter().filter(|r| r.valid).count();
    let invalid_count = results.len() - valid_count;

    if args.json {
        let output = JsonOutput {
            files: results,
            summary: Summary {
                total: args.files.len(),
                valid: valid_count,
                invalid: invalid_count,
            },
        };
        println!("{}", serde_json::to_string_pretty(&output)?);
    } else {
        // Print summary for multiple files
        if args.files.len() > 1 && !args.quiet {
            println!();
            println!(
                "Summary: {} files, {} valid, {} invalid",
                args.files.len(),
                valid_count,
                invalid_count
            );
        }
    }

    // Exit code: 0 if all valid, 1 if any invalid
    if invalid_count > 0 { Ok(1) } else { Ok(0) }
}

fn validate_file(
    file_path: &str,
    args: &Args,
    cache: Arc<DefaultFetcher>,
    global_downloaded_urls: Arc<Mutex<Vec<String>>>,
) -> Result<FileResult, Box<dyn std::error::Error>> {
    let start = Instant::now();

    // Determine if URL or local file
    let (content, size_bytes) =
        if file_path.starts_with("http://") || file_path.starts_with("https://") {
            fetch_url(file_path, args)?
        } else {
            read_local_file(file_path, args)?
        };

    if !args.json && !args.quiet {
        println!(
            "Validating: {} ({:.2} MB)",
            file_path,
            size_bytes as f64 / 1024.0 / 1024.0
        );
        if let Some(schema) = &args.schema {
            println!("  Schema: {}", schema);
        } else {
            println!("  Schema: auto-detected from xsi:schemaLocation");
        }
    }

    // Create fetcher with shared cache
    let is_http = file_path.starts_with("http://") || file_path.starts_with("https://");

    let downloaded_urls = Arc::new(Mutex::new(Vec::<String>::new()));
    let base_url = if is_http {
        Some(file_path.to_string())
    } else {
        None
    };
    let fetcher =
        UrlTrackingFetcher::new(Arc::clone(&cache), Arc::clone(&downloaded_urls), base_url);

    if !args.json && !args.quiet && args.verbose {
        println!("  Resolving schemas...");
    }

    // Perform validation
    let reader = BufReader::new(content.as_slice());
    let errors = streaming_validate_with_schema_location_and_fetcher(reader, fetcher)?;

    let elapsed = start.elapsed();
    let time_ms = elapsed.as_millis() as u64;
    let throughput = size_bytes as f64 / 1024.0 / 1024.0 / elapsed.as_secs_f64();

    // Collect downloaded schema URLs
    let schemas_downloaded: Vec<String> = downloaded_urls.lock().unwrap().clone();
    let schema_count = cache.len();

    // Add to global downloaded URLs
    global_downloaded_urls
        .lock()
        .unwrap()
        .extend(schemas_downloaded.clone());

    // Separate errors and warnings
    let error_count = errors.iter().filter(|e| e.is_error()).count();
    let warning_count = errors.len() - error_count;
    let valid = error_count == 0;

    if !args.json {
        if !args.quiet && args.verbose {
            let cache_status = if schemas_downloaded.is_empty() {
                "using cached schemas".to_string()
            } else {
                format!("{} schemas", schema_count)
            };
            println!("  Resolving schemas... done ({})", cache_status);

            if !schemas_downloaded.is_empty() {
                println!("  Downloaded schemas:");
                for url in &schemas_downloaded {
                    println!("    - {}", url);
                }
            }
        }

        if !args.quiet && args.verbose {
            println!("  Validating... done");
        }

        // Print errors
        if !errors.is_empty() {
            println!();
            println!("  Errors: {}", error_count);
            for err in &errors {
                if err.is_error() {
                    if let Some(line) = err.line() {
                        print!("    line {}", line);
                        if let Some(col) = err.column() {
                            print!(":{}", col);
                        }
                        print!(": ");
                    } else {
                        print!("    ");
                    }
                    println!("{}", err.message);
                }
            }

            if warning_count > 0 && args.verbose {
                println!();
                println!("  Warnings: {}", warning_count);
                for err in &errors {
                    if !err.is_error() {
                        if let Some(line) = err.line() {
                            print!("    line {}: ", line);
                        } else {
                            print!("    ");
                        }
                        println!("{}", err.message);
                    }
                }
            }
        } else if !args.quiet {
            println!();
            println!("  No errors found");
        }

        // Print timing info
        if !args.quiet && (args.stats || args.verbose) {
            println!();
            println!("  Time: {}ms ({:.2} MB/s)", time_ms, throughput);
        }

        println!();
    }

    Ok(FileResult {
        path: file_path.to_string(),
        size_bytes,
        valid,
        errors: errors.iter().map(ErrorInfo::from).collect(),
        schemas_downloaded,
        time_ms,
        throughput_mb_s: throughput,
    })
}

fn read_local_file(
    file_path: &str,
    args: &Args,
) -> Result<(Vec<u8>, u64), Box<dyn std::error::Error>> {
    let path = Path::new(file_path);
    if !path.exists() {
        return Err(format!("File not found: {}", file_path).into());
    }

    let file = File::open(path)?;
    let metadata = file.metadata()?;
    let compressed_size = metadata.len();

    let mut content = Vec::new();

    // Check if gzip compressed
    if file_path.ends_with(".gz") {
        use flate2::read::GzDecoder;
        let mut decoder = GzDecoder::new(BufReader::new(file));
        decoder.read_to_end(&mut content)?;

        if args.verbose && !args.json && !args.quiet {
            println!(
                "  Decompressed: {:.2} MB -> {:.2} MB",
                compressed_size as f64 / 1024.0 / 1024.0,
                content.len() as f64 / 1024.0 / 1024.0
            );
        }
    } else {
        BufReader::new(file).read_to_end(&mut content)?;
    }

    let size = content.len() as u64;
    Ok((content, size))
}

fn fetch_url(url: &str, args: &Args) -> Result<(Vec<u8>, u64), Box<dyn std::error::Error>> {
    if args.verbose && !args.json && !args.quiet {
        println!("  Downloading: {}", url);
    }

    let response = ureq::get(url)
        .set("Accept-Encoding", "gzip")
        .call()
        .map_err(|e| format!("Failed to fetch URL {}: {}", url, e))?;

    let content_encoding = response.header("Content-Encoding").map(|s| s.to_string());
    let mut content = Vec::new();
    response.into_reader().read_to_end(&mut content)?;

    // Handle gzip decompression if needed
    let is_gzip = content_encoding
        .as_ref()
        .map(|s| s.contains("gzip"))
        .unwrap_or(false)
        || url.ends_with(".gz");

    let final_content = if is_gzip {
        use flate2::read::GzDecoder;
        let mut decoder = GzDecoder::new(content.as_slice());
        let mut decompressed = Vec::new();
        decoder.read_to_end(&mut decompressed)?;

        if args.verbose && !args.json && !args.quiet {
            println!(
                "  Decompressed: {:.2} MB -> {:.2} MB",
                content.len() as f64 / 1024.0 / 1024.0,
                decompressed.len() as f64 / 1024.0 / 1024.0
            );
        }
        decompressed
    } else {
        content
    };

    let size = final_content.len() as u64;
    Ok((final_content, size))
}

/// A fetcher wrapper that tracks downloaded URLs and delegates to a shared DefaultFetcher.
///
/// This struct adds URL tracking (recording which URLs were freshly downloaded) and
/// base URL resolution (for resolving relative schema paths when the XML source is an HTTP URL)
/// on top of `DefaultFetcher` which handles the actual caching.
struct UrlTrackingFetcher {
    inner: Arc<DefaultFetcher>,
    downloaded_urls: Arc<Mutex<Vec<String>>>,
    /// Base URL for resolving relative paths (used for HTTP XML sources)
    base_url: Option<String>,
}

impl UrlTrackingFetcher {
    fn new(
        inner: Arc<DefaultFetcher>,
        downloaded_urls: Arc<Mutex<Vec<String>>>,
        base_url: Option<String>,
    ) -> Self {
        Self {
            inner,
            downloaded_urls,
            base_url,
        }
    }

    /// Resolve a potentially relative URL against the base URL
    fn resolve_url(&self, url: &str) -> String {
        // If already absolute, return as-is
        if url.starts_with("http://") || url.starts_with("https://") || url.starts_with("file://") {
            return url.to_string();
        }

        // Try to resolve against base URL
        if let Some(base) = &self.base_url {
            if base.starts_with("http://") || base.starts_with("https://") {
                // Find the last slash in the path
                if let Some(last_slash) = base.rfind('/') {
                    let base_dir = &base[..=last_slash];
                    let combined = format!("{}{}", base_dir, url);
                    return normalize_url_path(&combined);
                }
            }
        }

        // Can't resolve, return original
        url.to_string()
    }
}

/// Normalizes a URL path by resolving `.` and `..` components.
fn normalize_url_path(url: &str) -> String {
    // Split URL into protocol+host and path
    let (prefix, path) = if let Some(pos) = url.find("://") {
        let after_protocol = &url[pos + 3..];
        if let Some(slash_pos) = after_protocol.find('/') {
            let host_end = pos + 3 + slash_pos;
            (&url[..host_end], &url[host_end..])
        } else {
            return url.to_string();
        }
    } else {
        return url.to_string();
    };

    // Normalize the path
    let mut segments: Vec<&str> = Vec::new();
    for segment in path.split('/') {
        match segment {
            "" | "." => {}
            ".." => {
                segments.pop();
            }
            s => segments.push(s),
        }
    }

    format!("{}/{}", prefix, segments.join("/"))
}

impl SchemaFetcher for UrlTrackingFetcher {
    fn fetch(&self, url: &str) -> fastxml::error::Result<FetchResult> {
        // Resolve relative URLs
        let resolved_url = self.resolve_url(url);

        // Track cache size before fetch to detect new downloads
        let cache_size_before = self.inner.len();

        // Delegate to the shared CachingFetcher (handles caching + actual fetching)
        let result = self.inner.fetch(&resolved_url)?;

        // If the cache grew, this was a fresh download — track the URL
        if self.inner.len() > cache_size_before {
            self.downloaded_urls
                .lock()
                .unwrap()
                .push(result.final_url.clone());
        }

        Ok(result)
    }
}

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

    #[test]
    fn test_normalize_url_path() {
        // Basic normalization
        assert_eq!(
            normalize_url_path("https://example.com/a/b/c"),
            "https://example.com/a/b/c"
        );

        // With parent directory references
        assert_eq!(
            normalize_url_path("https://example.com/a/b/../c"),
            "https://example.com/a/c"
        );

        // Multiple parent references
        assert_eq!(
            normalize_url_path("https://example.com/a/b/c/../../d"),
            "https://example.com/a/d"
        );

        // Current directory references
        assert_eq!(
            normalize_url_path("https://example.com/a/./b/./c"),
            "https://example.com/a/b/c"
        );
    }

    #[test]
    fn test_url_tracking_fetcher_resolve_url_with_different_base_urls() {
        // This test verifies that the same relative path resolves to different
        // absolute URLs when the base URL changes
        let cache = Arc::new(DefaultFetcher::new());
        let downloaded_urls = Arc::new(Mutex::new(Vec::<String>::new()));

        // Create fetcher with first base URL
        let fetcher1 = UrlTrackingFetcher::new(
            Arc::clone(&cache),
            Arc::clone(&downloaded_urls),
            Some("https://example.com/dir1/file1.xml".to_string()),
        );

        // Create fetcher with second base URL
        let fetcher2 = UrlTrackingFetcher::new(
            Arc::clone(&cache),
            Arc::clone(&downloaded_urls),
            Some("https://example.com/dir2/file2.xml".to_string()),
        );

        // Same relative path should resolve to different absolute URLs
        let relative_path = "../schemas/test.xsd";
        let resolved1 = fetcher1.resolve_url(relative_path);
        let resolved2 = fetcher2.resolve_url(relative_path);

        assert_eq!(resolved1, "https://example.com/schemas/test.xsd");
        assert_eq!(resolved2, "https://example.com/schemas/test.xsd");

        // Different base directories
        let fetcher3 = UrlTrackingFetcher::new(
            Arc::clone(&cache),
            Arc::clone(&downloaded_urls),
            Some("https://other.com/project/data/file.xml".to_string()),
        );

        let resolved3 = fetcher3.resolve_url(relative_path);
        assert_eq!(resolved3, "https://other.com/project/schemas/test.xsd");
    }

    #[test]
    fn test_url_tracking_fetcher_resolve_url_deep_relative_path() {
        let cache = Arc::new(DefaultFetcher::new());
        let downloaded_urls = Arc::new(Mutex::new(Vec::<String>::new()));

        let fetcher = UrlTrackingFetcher::new(
            Arc::clone(&cache),
            Arc::clone(&downloaded_urls),
            Some("https://example.com/assets/abc/project/udx/area/file.xml".to_string()),
        );

        // This mimics the PLATEAU schema path: ../../schemas/iur/urf/3.1/urbanFunction.xsd
        let resolved = fetcher.resolve_url("../../schemas/iur/urf/3.1/urbanFunction.xsd");
        assert_eq!(
            resolved,
            "https://example.com/assets/abc/project/schemas/iur/urf/3.1/urbanFunction.xsd"
        );
    }
}