scirs2-io 0.4.2

Input/Output utilities module for SciRS2 (scirs2-io)
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
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
//! Common pipeline stages for data processing

#![allow(dead_code)]
#![allow(missing_docs)]

use super::*;
use crate::csv::{read_csv, write_csv};
use crate::error::Result;
use scirs2_core::ndarray::Array2;
use std::fs::File;
use std::path::{Path, PathBuf};
use std::time::Duration;

/// File reading stage
pub struct FileReadStage {
    path: PathBuf,
    format: FileFormat,
}

#[derive(Debug, Clone)]
pub enum FileFormat {
    Csv,
    Json,
    Binary,
    Text,
    Auto,
}

impl FileReadStage {
    pub fn new(path: impl AsRef<Path>, format: FileFormat) -> Self {
        Self {
            path: path.as_ref().to_path_buf(),
            format,
        }
    }
}

impl PipelineStage for FileReadStage {
    fn execute(
        &self,
        mut input: PipelineData<Box<dyn Any + Send + Sync>>,
    ) -> Result<PipelineData<Box<dyn Any + Send + Sync>>> {
        let data = match self.format {
            FileFormat::Csv => {
                let data = read_csv(&self.path, None)?;
                Box::new(data) as Box<dyn Any + Send + Sync>
            }
            FileFormat::Json => {
                let file = File::open(&self.path).map_err(IoError::Io)?;
                let value: serde_json::Value = serde_json::from_reader(file)
                    .map_err(|e| IoError::SerializationError(e.to_string()))?;
                Box::new(value) as Box<dyn Any + Send + Sync>
            }
            FileFormat::Binary => {
                let data = std::fs::read(&self.path).map_err(IoError::Io)?;
                Box::new(data) as Box<dyn Any + Send + Sync>
            }
            FileFormat::Text => {
                let data = std::fs::read_to_string(&self.path).map_err(IoError::Io)?;
                Box::new(data) as Box<dyn Any + Send + Sync>
            }
            FileFormat::Auto => {
                // Auto-detect format based on file extension
                let extension = self
                    .path
                    .extension()
                    .and_then(|ext| ext.to_str())
                    .unwrap_or("");

                match extension.to_lowercase().as_str() {
                    "csv" => {
                        let data = read_csv(&self.path, None)?;
                        Box::new(data) as Box<dyn Any + Send + Sync>
                    }
                    "json" => {
                        let file = File::open(&self.path).map_err(IoError::Io)?;
                        let value: serde_json::Value = serde_json::from_reader(file)
                            .map_err(|e| IoError::SerializationError(e.to_string()))?;
                        Box::new(value) as Box<dyn Any + Send + Sync>
                    }
                    "txt" | "text" => {
                        let data = std::fs::read_to_string(&self.path).map_err(IoError::Io)?;
                        Box::new(data) as Box<dyn Any + Send + Sync>
                    }
                    _ => {
                        // Default to binary for unknown extensions
                        let data = std::fs::read(&self.path).map_err(IoError::Io)?;
                        Box::new(data) as Box<dyn Any + Send + Sync>
                    }
                }
            }
        };

        input.data = data;
        input
            .metadata
            .set("source_file", self.path.to_string_lossy().to_string());
        Ok(input)
    }

    fn name(&self) -> String {
        format!("read_{:?}", self.format)
    }

    fn stage_type(&self) -> String {
        "input".to_string()
    }
}

/// File writing stage
pub struct FileWriteStage {
    path: PathBuf,
    format: FileFormat,
}

impl FileWriteStage {
    pub fn new(path: impl AsRef<Path>, format: FileFormat) -> Self {
        Self {
            path: path.as_ref().to_path_buf(),
            format,
        }
    }
}

impl PipelineStage for FileWriteStage {
    fn execute(
        &self,
        input: PipelineData<Box<dyn Any + Send + Sync>>,
    ) -> Result<PipelineData<Box<dyn Any + Send + Sync>>> {
        match self.format {
            FileFormat::Csv => {
                if let Some(data) = input.data.downcast_ref::<Array2<f64>>() {
                    write_csv(&self.path, data, None, None)?;
                }
            }
            FileFormat::Json => {
                if let Some(value) = input.data.downcast_ref::<serde_json::Value>() {
                    let file = File::create(&self.path).map_err(IoError::Io)?;
                    serde_json::to_writer_pretty(file, value)
                        .map_err(|e| IoError::SerializationError(e.to_string()))?;
                }
            }
            FileFormat::Binary => {
                if let Some(data) = input.data.downcast_ref::<Vec<u8>>() {
                    std::fs::write(&self.path, data).map_err(IoError::Io)?;
                }
            }
            FileFormat::Text => {
                if let Some(data) = input.data.downcast_ref::<String>() {
                    std::fs::write(&self.path, data).map_err(IoError::Io)?;
                }
            }
            FileFormat::Auto => {
                // Auto-detect format based on file extension
                let extension = self
                    .path
                    .extension()
                    .and_then(|ext| ext.to_str())
                    .unwrap_or("");

                match extension.to_lowercase().as_str() {
                    "csv" => {
                        if let Some(data) = input.data.downcast_ref::<Array2<f64>>() {
                            write_csv(&self.path, data, None, None)?;
                        }
                    }
                    "json" => {
                        if let Some(value) = input.data.downcast_ref::<serde_json::Value>() {
                            let file = File::create(&self.path).map_err(IoError::Io)?;
                            serde_json::to_writer_pretty(file, value)
                                .map_err(|e| IoError::SerializationError(e.to_string()))?;
                        }
                    }
                    "txt" | "text" => {
                        if let Some(data) = input.data.downcast_ref::<String>() {
                            std::fs::write(&self.path, data).map_err(IoError::Io)?;
                        }
                    }
                    _ => {
                        // Default to binary for unknown extensions
                        if let Some(data) = input.data.downcast_ref::<Vec<u8>>() {
                            std::fs::write(&self.path, data).map_err(IoError::Io)?;
                        }
                    }
                }
            }
        }

        Ok(input)
    }

    fn name(&self) -> String {
        format!("write_{:?}", self.format)
    }

    fn stage_type(&self) -> String {
        "output".to_string()
    }
}

/// Data validation stage
pub struct ValidationStage {
    validators: Vec<Box<dyn Validator>>,
}

pub trait Validator: Send + Sync {
    fn validate(&self, data: &dyn Any) -> Result<()>;
    fn name(&self) -> &str;
}

impl Default for ValidationStage {
    fn default() -> Self {
        Self::new()
    }
}

impl ValidationStage {
    pub fn new() -> Self {
        Self {
            validators: Vec::new(),
        }
    }

    pub fn add_validator(mut self, validator: Box<dyn Validator>) -> Self {
        self.validators.push(validator);
        self
    }
}

impl PipelineStage for ValidationStage {
    fn execute(
        &self,
        input: PipelineData<Box<dyn Any + Send + Sync>>,
    ) -> Result<PipelineData<Box<dyn Any + Send + Sync>>> {
        for validator in &self.validators {
            validator.validate(input.data.as_ref())?;
        }
        Ok(input)
    }

    fn name(&self) -> String {
        "validation".to_string()
    }

    fn stage_type(&self) -> String {
        "validation".to_string()
    }
}

/// Data transformation stage
pub struct TransformStage {
    name: String,
    transformer: Box<dyn DataTransformer>,
}

pub trait DataTransformer: Send + Sync {
    fn transform(&self, data: Box<dyn Any + Send + Sync>) -> Result<Box<dyn Any + Send + Sync>>;
}

impl TransformStage {
    pub fn new(name: &str, transformer: Box<dyn DataTransformer>) -> Self {
        Self {
            name: name.to_string(),
            transformer,
        }
    }
}

impl PipelineStage for TransformStage {
    fn execute(
        &self,
        mut input: PipelineData<Box<dyn Any + Send + Sync>>,
    ) -> Result<PipelineData<Box<dyn Any + Send + Sync>>> {
        input.data = self.transformer.transform(input.data)?;
        Ok(input)
    }

    fn name(&self) -> String {
        self.name.clone()
    }

    fn stage_type(&self) -> String {
        "transform".to_string()
    }
}

/// Aggregation stage
pub struct AggregationStage<T> {
    name: String,
    aggregator: Box<dyn Fn(Vec<T>) -> Result<T> + Send + Sync>,
}

impl<T: 'static + Send + Sync> AggregationStage<T> {
    pub fn new<F>(name: &str, aggregator: F) -> Self
    where
        F: Fn(Vec<T>) -> Result<T> + Send + Sync + 'static,
    {
        Self {
            name: name.to_string(),
            aggregator: Box::new(aggregator),
        }
    }
}

impl<T: 'static + Send + Sync> PipelineStage for AggregationStage<T> {
    fn execute(
        &self,
        mut input: PipelineData<Box<dyn Any + Send + Sync>>,
    ) -> Result<PipelineData<Box<dyn Any + Send + Sync>>> {
        if let Ok(data) = input.data.downcast::<Vec<T>>() {
            let aggregated = (self.aggregator)(*data)?;
            input.data = Box::new(aggregated) as Box<dyn Any + Send + Sync>;
            Ok(input)
        } else {
            Err(IoError::Other(
                "Type mismatch in aggregation stage".to_string(),
            ))
        }
    }

    fn name(&self) -> String {
        self.name.clone()
    }

    fn stage_type(&self) -> String {
        "aggregation".to_string()
    }
}

/// Filtering stage
pub struct FilterStage<T> {
    name: String,
    predicate: Box<dyn Fn(&T) -> bool + Send + Sync>,
}

impl<T: 'static + Send + Sync + Clone> FilterStage<T> {
    pub fn new<F>(name: &str, predicate: F) -> Self
    where
        F: Fn(&T) -> bool + Send + Sync + 'static,
    {
        Self {
            name: name.to_string(),
            predicate: Box::new(predicate),
        }
    }
}

impl<T: 'static + Send + Sync + Clone> PipelineStage for FilterStage<T> {
    fn execute(
        &self,
        mut input: PipelineData<Box<dyn Any + Send + Sync>>,
    ) -> Result<PipelineData<Box<dyn Any + Send + Sync>>> {
        if let Ok(data) = input.data.downcast::<Vec<T>>() {
            let filtered: Vec<T> = data
                .iter()
                .filter(|item| (self.predicate)(item))
                .cloned()
                .collect();
            input.data = Box::new(filtered) as Box<dyn Any + Send + Sync>;
            Ok(input)
        } else {
            Err(IoError::Other("Type mismatch in filter stage".to_string()))
        }
    }

    fn name(&self) -> String {
        self.name.clone()
    }

    fn stage_type(&self) -> String {
        "filter".to_string()
    }
}

/// Enrichment stage - adds metadata or augments data
pub struct EnrichmentStage {
    name: String,
    enricher: Box<dyn DataEnricher>,
}

pub trait DataEnricher: Send + Sync {
    fn enrich(&self, data: &mut PipelineData<Box<dyn Any + Send + Sync>>) -> Result<()>;
}

impl EnrichmentStage {
    pub fn new(name: &str, enricher: Box<dyn DataEnricher>) -> Self {
        Self {
            name: name.to_string(),
            enricher,
        }
    }
}

impl PipelineStage for EnrichmentStage {
    fn execute(
        &self,
        mut input: PipelineData<Box<dyn Any + Send + Sync>>,
    ) -> Result<PipelineData<Box<dyn Any + Send + Sync>>> {
        self.enricher.enrich(&mut input)?;
        Ok(input)
    }

    fn name(&self) -> String {
        self.name.clone()
    }

    fn stage_type(&self) -> String {
        "enrichment".to_string()
    }
}

/// Cache stage - caches intermediate results
pub struct CacheStage {
    cache_key: String,
    cache_dir: PathBuf,
}

impl CacheStage {
    pub fn new(cache_key: &str, cache_dir: impl AsRef<Path>) -> Self {
        Self {
            cache_key: cache_key.to_string(),
            cache_dir: cache_dir.as_ref().to_path_buf(),
        }
    }
}

impl PipelineStage for CacheStage {
    fn execute(
        &self,
        mut input: PipelineData<Box<dyn Any + Send + Sync>>,
    ) -> Result<PipelineData<Box<dyn Any + Send + Sync>>> {
        // Create cache directory if needed
        std::fs::create_dir_all(&self.cache_dir).map_err(IoError::Io)?;

        let cache_path = self.cache_dir.join(format!("{}.cache", self.cache_key));

        // Check if cache exists
        if cache_path.exists() {
            // Try to load from cache
            if let Ok(_cache_data) = std::fs::read(&cache_path) {
                // Update metadata to indicate cache hit
                input.metadata.set("cache_hit", true);
                input.metadata.set("cache_key", self.cache_key.clone());

                // For demonstration, we'll store a simple flag in context
                input.context.set("cached_from", self.cache_key.clone());

                return Ok(input);
            }
        }

        // Cache miss - save data for future use
        // Note: In a real implementation, we would serialize the actual data
        // For now, we'll just create a marker file
        let cache_marker = format!(
            "Cache entry for: {}\nCreated: {:?}\n",
            self.cache_key,
            chrono::Utc::now()
        );
        std::fs::write(&cache_path, cache_marker).map_err(IoError::Io)?;

        // Update metadata
        input.metadata.set("cache_hit", false);
        input.metadata.set("cache_key", self.cache_key.clone());

        Ok(input)
    }

    fn name(&self) -> String {
        format!("cache_{}", self.cache_key)
    }

    fn stage_type(&self) -> String {
        "cache".to_string()
    }
}

/// Monitoring stage - logs metrics and progress
pub struct MonitoringStage {
    name: String,
    monitor: Box<dyn Monitor>,
}

pub trait Monitor: Send + Sync {
    fn monitor(&self, data: &PipelineData<Box<dyn Any + Send + Sync>>);
}

impl MonitoringStage {
    pub fn new(name: &str, monitor: Box<dyn Monitor>) -> Self {
        Self {
            name: name.to_string(),
            monitor,
        }
    }
}

impl PipelineStage for MonitoringStage {
    fn execute(
        &self,
        input: PipelineData<Box<dyn Any + Send + Sync>>,
    ) -> Result<PipelineData<Box<dyn Any + Send + Sync>>> {
        self.monitor.monitor(&input);
        Ok(input)
    }

    fn name(&self) -> String {
        self.name.clone()
    }

    fn stage_type(&self) -> String {
        "monitoring".to_string()
    }
}

/// Error handling stage - catches and handles errors
pub struct ErrorHandlingStage {
    name: String,
    handler: Box<dyn ErrorHandler>,
}

pub trait ErrorHandler: Send + Sync {
    fn handle_error(
        &self,
        error: IoError,
        data: PipelineData<Box<dyn Any + Send + Sync>>,
    ) -> Result<PipelineData<Box<dyn Any + Send + Sync>>>;
}

impl ErrorHandlingStage {
    pub fn new(name: &str, handler: Box<dyn ErrorHandler>) -> Self {
        Self {
            name: name.to_string(),
            handler,
        }
    }
}

impl PipelineStage for ErrorHandlingStage {
    fn execute(
        &self,
        input: PipelineData<Box<dyn Any + Send + Sync>>,
    ) -> Result<PipelineData<Box<dyn Any + Send + Sync>>> {
        // In a real pipeline, this would wrap the next stage's execution
        // For now, we'll simulate error handling by checking context for errors

        // Check if there's an error flag in the context
        if let Some(error_msg) = input.context.get::<String>("pipeline_error") {
            // Create an error from the message
            let error = IoError::Other(error_msg);

            // Let the handler decide what to do
            self.handler.handle_error(error, input)
        } else {
            // No error, pass through
            Ok(input)
        }
    }

    fn name(&self) -> String {
        self.name.clone()
    }

    fn stage_type(&self) -> String {
        "error_handling".to_string()
    }
}

/// Default error handler that logs and retries
pub struct RetryErrorHandler {
    max_retries: usize,
    retry_delay: Duration,
}

impl RetryErrorHandler {
    pub fn new(max_retries: usize) -> Self {
        Self {
            max_retries,
            retry_delay: Duration::from_secs(1),
        }
    }

    pub fn with_delay(mut self, delay: Duration) -> Self {
        self.retry_delay = delay;
        self
    }
}

impl ErrorHandler for RetryErrorHandler {
    fn handle_error(
        &self,
        error: IoError,
        mut data: PipelineData<Box<dyn Any + Send + Sync>>,
    ) -> Result<PipelineData<Box<dyn Any + Send + Sync>>> {
        // Get current retry count
        let retry_count = data.context.get::<usize>("retry_count").unwrap_or(0);

        if retry_count < self.max_retries {
            // Increment retry count
            data.context.set("retry_count", retry_count + 1);

            // Log retry attempt
            data.metadata.set("last_error", format!("{:?}", error));
            data.metadata.set("retry_attempt", (retry_count + 1) as i64);

            // Clear error flag to retry
            data.context.set::<Option<String>>("pipeline_error", None);

            Ok(data)
        } else {
            // Max retries exceeded
            Err(error)
        }
    }
}

/// Skip error handler that continues on error
pub struct SkipErrorHandler;

impl ErrorHandler for SkipErrorHandler {
    fn handle_error(
        &self,
        _error: IoError,
        mut data: PipelineData<Box<dyn Any + Send + Sync>>,
    ) -> Result<PipelineData<Box<dyn Any + Send + Sync>>> {
        // Mark as skipped in metadata
        data.metadata.set("skipped", true);
        data.metadata.set("skip_reason", "error_occurred");

        // Continue processing
        Ok(data)
    }
}

/// Fallback error handler that provides default values
pub struct FallbackErrorHandler<T: Any + Send + Sync + Clone + 'static> {
    fallback_value: T,
}

impl<T: Any + Send + Sync + Clone + 'static> FallbackErrorHandler<T> {
    pub fn new(fallback_value: T) -> Self {
        Self { fallback_value }
    }
}

impl<T: Any + Send + Sync + Clone + 'static> ErrorHandler for FallbackErrorHandler<T> {
    fn handle_error(
        &self,
        _error: IoError,
        mut data: PipelineData<Box<dyn Any + Send + Sync>>,
    ) -> Result<PipelineData<Box<dyn Any + Send + Sync>>> {
        // Replace data with fallback value
        data.data = Box::new(self.fallback_value.clone());
        data.metadata.set("used_fallback", true);

        Ok(data)
    }
}

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

    struct SimpleValidator;

    impl Validator for SimpleValidator {
        fn validate(&self, data: &dyn Any) -> Result<()> {
            if let Some(nums) = data.downcast_ref::<Vec<i32>>() {
                if nums.is_empty() {
                    return Err(IoError::ValidationError("Empty data".to_string()));
                }
            }
            Ok(())
        }

        fn name(&self) -> &str {
            "simple"
        }
    }

    #[test]
    fn test_validation_stage() {
        let stage = ValidationStage::new().add_validator(Box::new(SimpleValidator));

        let data = PipelineData::new(Box::new(vec![1, 2, 3]) as Box<dyn Any + Send + Sync>);
        let result = stage.execute(data);
        assert!(result.is_ok());

        let empty_data =
            PipelineData::new(Box::new(vec![] as Vec<i32>) as Box<dyn Any + Send + Sync>);
        let result = stage.execute(empty_data);
        assert!(result.is_err());
    }
}