-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathconfig.rs
More file actions
1471 lines (1250 loc) · 50.1 KB
/
Copy pathconfig.rs
File metadata and controls
1471 lines (1250 loc) · 50.1 KB
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
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use anyhow::{Context, Result};
use clap::Parser;
use datafusion::datasource::MemTable;
use datafusion::prelude::*;
use pipeline::pipeline::{Pipeline, StandardPipeline};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::Path;
use std::path::PathBuf;
use std::sync::Arc;
use thiserror::Error;
use crate::remote_storage::{RemoteStorage, S3Storage};
pub use source::AccessMode;
/// CLI arguments for the Skardi server
#[derive(Parser, Debug)]
#[command(name = "skardi-server")]
#[command(about = "Skardi Online Serving Pipeline Server")]
pub struct CliArgs {
/// Path to pipeline YAML file or directory containing pipeline files
/// If a directory is provided, all .yaml and .yml files in it will be loaded as pipelines
#[arg(
long = "pipeline",
help = "Path to pipeline YAML file or directory containing pipeline files"
)]
pub pipeline_path: Option<PathBuf>,
/// Path to context YAML configuration file (optional)
#[arg(
long = "ctx",
help = "Path to context YAML configuration file (optional)"
)]
pub ctx_file: Option<PathBuf>,
/// Server port number
#[arg(long, default_value = "8080", help = "Server port number")]
pub port: u16,
}
/// Main server configuration containing pipelines and data sources
#[derive(Debug)]
pub struct ServerConfig {
/// Loaded pipeline definitions keyed by name (can be registered later via API)
pub pipelines: HashMap<String, StandardPipeline>,
/// Data sources to register with DataFusion
pub data_sources: Vec<DataSource>,
/// CLI arguments
pub args: CliArgs,
}
/// Data source configuration for context loading
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct DataSource {
/// Unique name for the data source (used as table name in SQL)
pub name: String,
/// Type of data source (CSV, Parquet, etc.)
#[serde(rename = "type")]
pub source_type: DataSourceType,
/// File path to the data source (for file-based sources)
#[serde(default)]
pub path: PathBuf,
/// Connection string for database sources (e.g., PostgreSQL)
pub connection_string: Option<String>,
/// Optional explicit schema (field name -> type mapping)
pub schema: Option<HashMap<String, String>>,
/// Optional format-specific options
pub options: Option<HashMap<String, String>>,
/// Access mode: read_only (default) or read_write
#[serde(default)]
pub access_mode: AccessMode,
/// If true, load the entire table into memory at startup (only for Csv, Parquet, Iceberg)
#[serde(default)]
pub enable_cache: bool,
}
/// Supported data source types
#[derive(Debug, Clone, Deserialize, Serialize, Hash, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum DataSourceType {
Csv,
Parquet,
Postgres,
Mysql,
Iceberg,
Mongo,
Lance,
}
/// Context configuration file structure
#[derive(Debug, Deserialize)]
struct ContextConfig {
data_sources: Vec<DataSource>,
}
/// Configuration-related errors
#[derive(Error, Debug)]
pub enum ConfigError {
#[error("Pipeline file not found: {path}")]
PipelineFileNotFound { path: PathBuf },
#[error("Pipeline directory not found: {path}")]
PipelineDirectoryNotFound { path: PathBuf },
#[error("No pipeline files found in directory: {path}")]
NoPipelineFilesInDirectory { path: PathBuf },
#[error("Context file not found: {path}")]
ContextFileNotFound { path: PathBuf },
#[error("Invalid YAML in context file: {error}")]
InvalidContextYaml { error: String },
#[error("Data source file not found: {name} -> {path}")]
DataSourceFileNotFound { name: String, path: PathBuf },
#[error("Duplicate data source name: {name}")]
DuplicateDataSourceName { name: String },
#[error("Data source registration failed: {name} - {error}")]
DataSourceRegistrationFailed { name: String, error: String },
#[error("Invalid schema type: {field} -> {type_name}")]
InvalidSchemaType { field: String, type_name: String },
#[error("Missing connection string for data source: {name}")]
MissingConnectionString { name: String },
#[error("PostgreSQL connection failed: {name} - {error}")]
PostgresConnectionFailed { name: String, error: String },
#[error("MySQL connection failed: {name} - {error}")]
MySQLConnectionFailed { name: String, error: String },
#[error("S3 path must start with 's3://' prefix: {path}")]
InvalidS3Path { path: String },
#[error("Missing required AWS configuration for S3 data source: {name} - missing {field}")]
MissingAwsConfig { name: String, field: String },
#[error("S3 object store registration failed: {name} - {error}")]
S3ObjectStoreRegistrationFailed { name: String, error: String },
#[error("Data source '{name}' has access_mode 'read_write' but type '{source_type:?}' does not support write operations. Only 'postgres' and 'mysql' sources support read_write mode.")]
UnsupportedWriteMode {
name: String,
source_type: DataSourceType,
},
#[error("DDL operation not allowed: {operation} on data source '{table_name}'. DDL operations (CREATE, DROP, ALTER, etc.) are not permitted.")]
DdlOperationNotAllowed {
operation: String,
table_name: String,
},
#[error("Write operation not allowed on data source '{table_name}'. The data source is configured with 'read_only' access mode. Set access_mode to 'read_write' to enable write operations.")]
WriteOperationNotAllowed { table_name: String },
}
// ============================================================================
// FUNCTION SIGNATURES - Implementation to be added later
// ============================================================================
/// Resolve pipeline files from a path that can be either a single file or a directory
///
/// If the path is a file, returns a vector containing just that file.
/// If the path is a directory, returns all .yaml and .yml files in that directory.
/// If the path is None, returns an empty vector.
fn resolve_pipeline_files(path: Option<&PathBuf>) -> Result<Vec<PathBuf>> {
let Some(path) = path else {
tracing::info!("No pipeline path specified");
return Ok(Vec::new());
};
if !path.exists() {
// Check if it looks like a file or directory based on extension
if path.extension().is_some() {
return Err(ConfigError::PipelineFileNotFound { path: path.clone() }.into());
} else {
return Err(ConfigError::PipelineDirectoryNotFound { path: path.clone() }.into());
}
}
if path.is_file() {
tracing::info!("Pipeline path is a single file: {:?}", path);
return Ok(vec![path.clone()]);
}
if path.is_dir() {
tracing::info!("Pipeline path is a directory: {:?}", path);
let mut pipeline_files = Vec::new();
for entry in std::fs::read_dir(path)
.with_context(|| format!("Failed to read pipeline directory: {:?}", path))?
{
let entry = entry.with_context(|| "Failed to read directory entry")?;
let file_path = entry.path();
if file_path.is_file() {
if let Some(ext) = file_path.extension() {
let ext = ext.to_string_lossy().to_lowercase();
if ext == "yaml" || ext == "yml" {
tracing::debug!("Found pipeline file: {:?}", file_path);
pipeline_files.push(file_path);
}
}
}
}
// Sort for consistent ordering
pipeline_files.sort();
if pipeline_files.is_empty() {
return Err(ConfigError::NoPipelineFilesInDirectory { path: path.clone() }.into());
}
tracing::info!(
"Found {} pipeline file(s) in directory",
pipeline_files.len()
);
return Ok(pipeline_files);
}
// Path exists but is neither file nor directory (e.g., symlink to nothing)
Err(ConfigError::PipelineFileNotFound { path: path.clone() }.into())
}
/// Load complete server configuration from CLI arguments
pub async fn load_server_config(args: CliArgs) -> Result<ServerConfig> {
tracing::info!("Loading server configuration");
tracing::debug!("Pipeline path: {:?}", args.pipeline_path);
tracing::debug!("Context file: {:?}", args.ctx_file);
// Load context configuration first (optional)
let data_sources = if let Some(ref ctx_file) = args.ctx_file {
load_context_config(ctx_file)
.with_context(|| format!("Failed to load context from {:?}", ctx_file))?
} else {
tracing::info!("No context file specified, using empty data sources");
Vec::new()
};
// Create optimizer registry before SessionState
let optimizer_registry = Arc::new(crate::optimizer_registry::OptimizerRegistry::new());
// Create federation-enabled SessionState
let state = datafusion_federation::default_session_state();
// Get all physical optimizer rules from the registry based on data sources
let additional_optimizers = optimizer_registry.get_physical_optimizer_rules(&data_sources);
// Rebuild SessionState with additional physical optimizers if any
let state = if !additional_optimizers.is_empty() {
tracing::info!(
"Adding {} physical optimizer(s) to SessionState",
additional_optimizers.len()
);
// Get current physical optimizers and add our additional ones
let mut physical_optimizer_rules = state.physical_optimizers().to_vec();
physical_optimizer_rules.extend(additional_optimizers);
// Rebuild SessionState with the new optimizer rules
datafusion::execution::SessionStateBuilder::new_from_existing(state)
.with_physical_optimizer_rules(physical_optimizer_rules)
.build()
} else {
state
};
let mut session_ctx = SessionContext::new_with_state(state);
// Register data sources with optimizer registry support
register_data_sources_with_registry(&mut session_ctx, &data_sources, &optimizer_registry)
.await
.with_context(|| "Failed to register data sources")?;
// Register UDFs
optimizer_registry
.register_udfs(&mut session_ctx, &data_sources)
.with_context(|| "Failed to register UDFs")?;
// Register onnx_predict UDF (lazy — models loaded on first call from inline path)
register_onnx_predict_udf(&mut session_ctx);
let ctx = Arc::new(session_ctx);
// Resolve pipeline files from path (can be file or directory)
let pipeline_files = resolve_pipeline_files(args.pipeline_path.as_ref())
.with_context(|| "Failed to resolve pipeline files")?;
for pipeline_file in &pipeline_files {
let (pipeline_name, sql) = extract_pipeline_sql(pipeline_file)
.with_context(|| format!("Failed to load pipeline from {:?}", pipeline_file))?;
validate_pipeline_sql(&pipeline_name, &sql, &data_sources)?;
}
// Load pipeline configurations with the populated SessionContext
let mut pipelines: HashMap<String, StandardPipeline> = HashMap::new();
for pipeline_file in &pipeline_files {
let loaded_pipeline = load_pipeline_config(pipeline_file, ctx.clone())
.await
.with_context(|| format!("Failed to load pipeline from {:?}", pipeline_file))?;
let pipeline_name = loaded_pipeline.name().to_string();
tracing::info!("Pipeline loaded successfully: {}", pipeline_name);
// Check for duplicate pipeline names
if pipelines.contains_key(&pipeline_name) {
return Err(anyhow::anyhow!(
"Duplicate pipeline name '{}' found. Each pipeline must have a unique name.",
pipeline_name
));
}
pipelines.insert(pipeline_name, loaded_pipeline);
}
if pipelines.is_empty() {
tracing::info!("No pipeline files specified, pipelines map is empty");
} else {
tracing::info!(
"Loaded {} pipeline(s): {:?}",
pipelines.len(),
pipelines.keys().collect::<Vec<_>>()
);
}
tracing::info!(
"Configuration loaded successfully: pipelines={}, data_sources={}",
pipelines.len(),
data_sources.len()
);
Ok(ServerConfig {
pipelines,
data_sources,
args,
})
}
/// Extract SQL query from pipeline file for early validation
/// This reads just the query field without full pipeline loading
fn extract_pipeline_sql(path: &Path) -> Result<(String, String)> {
use serde::Deserialize;
#[derive(Deserialize)]
struct PipelineMetadata {
name: String,
}
#[derive(Deserialize)]
struct MinimalPipeline {
metadata: PipelineMetadata,
query: String,
}
let content = std::fs::read_to_string(path)
.with_context(|| format!("Failed to read pipeline file: {:?}", path))?;
let pipeline: MinimalPipeline = serde_yaml::from_str(&content)
.with_context(|| format!("Failed to parse pipeline YAML: {:?}", path))?;
Ok((pipeline.metadata.name, pipeline.query))
}
/// Load pipeline configuration from YAML file
async fn load_pipeline_config(path: &Path, ctx: Arc<SessionContext>) -> Result<StandardPipeline> {
tracing::debug!("Loading pipeline from: {:?}", path);
if !path.exists() {
return Err(ConfigError::PipelineFileNotFound {
path: path.to_path_buf(),
}
.into());
}
// Use existing StandardPipeline infrastructure with provided context
StandardPipeline::load_from_file(path, ctx)
.await
.map_err(|e| anyhow::anyhow!("Pipeline loading failed: {}", e))
}
/// Register the onnx_predict UDF with the session context.
///
/// The UDF loads models lazily from file paths provided inline in SQL:
/// onnx_predict('path/to/model.onnx', input1, input2, ...)
///
/// No pre-configuration needed — ORT runtime and models are initialized on first call.
pub fn register_onnx_predict_udf(ctx: &mut SessionContext) {
let registry = Arc::new(model::OnnxModelRegistry::new());
registry.register_onnx_predict_udf(ctx);
}
/// Load context configuration from YAML file
fn load_context_config(path: &Path) -> Result<Vec<DataSource>> {
tracing::debug!("Loading context from: {:?}", path);
if !path.exists() {
return Err(ConfigError::ContextFileNotFound {
path: path.to_path_buf(),
}
.into());
}
// Read and parse YAML
let content = std::fs::read_to_string(path)
.with_context(|| format!("Failed to read context file: {:?}", path))?;
let context_config: ContextConfig =
serde_yaml::from_str(&content).map_err(|e| ConfigError::InvalidContextYaml {
error: e.to_string(),
})?;
// Validate data sources
validate_data_sources(&context_config.data_sources)?;
tracing::info!(
"Loaded {} data sources from context",
context_config.data_sources.len()
);
Ok(context_config.data_sources)
}
/// Data source types that support read_write access mode
const WRITABLE_SOURCE_TYPES: &[DataSourceType] = &[
DataSourceType::Postgres,
DataSourceType::Mysql,
DataSourceType::Mongo,
];
/// Validate data source configurations
fn validate_data_sources(data_sources: &[DataSource]) -> Result<()> {
tracing::debug!("Validating {} data sources", data_sources.len());
// Check for duplicate names
let mut names = std::collections::HashSet::new();
for source in data_sources {
if !names.insert(&source.name) {
return Err(ConfigError::DuplicateDataSourceName {
name: source.name.clone(),
}
.into());
}
}
// Initialize S3 storage handler for remote validation
let s3_storage = S3Storage::new();
// Validate each data source based on its path type
for source in data_sources {
// Validate access_mode compatibility
if source.access_mode.is_read_write()
&& !WRITABLE_SOURCE_TYPES.contains(&source.source_type)
{
return Err(ConfigError::UnsupportedWriteMode {
name: source.name.clone(),
source_type: source.source_type.clone(),
}
.into());
}
match (&source.source_type, s3_storage.is_remote_path(&source.path)) {
(DataSourceType::Csv | DataSourceType::Parquet | DataSourceType::Lance, true) => {
// Validate S3 configuration for S3 paths
s3_storage.validate_configuration(source)?;
}
(DataSourceType::Postgres | DataSourceType::Mysql | DataSourceType::Mongo, false) => {
// For database connections, ensure connection string is provided
if source.connection_string.is_none() {
return Err(ConfigError::MissingConnectionString {
name: source.name.clone(),
}
.into());
}
}
(DataSourceType::Iceberg, _) => {
// Validation happened during data source registration
}
_ => {
// Other combinations are valid without additional checks
}
}
let location_type = if s3_storage.is_remote_path(&source.path) {
"remote_s3"
} else {
"local"
};
let access_mode_str = if source.access_mode.is_read_write() {
"read_write"
} else {
"read_only"
};
tracing::debug!(
"✓ Validated data source: {} (type: {:?}, location: {}, access: {})",
source.name,
source.source_type,
location_type,
access_mode_str
);
}
tracing::info!(
"Validated {} data sources successfully ✅",
data_sources.len()
);
Ok(())
}
/// Validate schema type mappings
#[allow(dead_code)]
fn validate_schema_types(_schema: &HashMap<String, String>) -> Result<()> {
// TODO: Add schema type validation later - for now assume schema is valid
tracing::debug!("Skipping schema type validation for MVP");
Ok(())
}
/// Validate pipeline SQL against data source access modes
fn validate_pipeline_sql(
pipeline_name: &str,
sql: &str,
data_sources: &[DataSource],
) -> Result<()> {
use source::sql_validator::{validate_sql, SqlValidatorConfig};
// Build validator config from data sources
let mut validator_config = SqlValidatorConfig::new();
for ds in data_sources {
let mode = if ds.access_mode.is_read_write() {
source::sql_validator::AccessMode::ReadWrite
} else {
source::sql_validator::AccessMode::ReadOnly
};
validator_config = validator_config.with_table(&ds.name, mode);
}
// Validate the SQL against access mode restrictions
validate_sql(sql, &validator_config).map_err(|e| {
anyhow::anyhow!("Pipeline '{}' SQL validation failed: {}", pipeline_name, e)
})?;
tracing::info!(
"✅ Pipeline '{}' SQL validated against access modes",
pipeline_name
);
Ok(())
}
/// Register data sources with DataFusion SessionContext
pub async fn register_data_sources(
session_ctx: &mut SessionContext,
data_sources: &[DataSource],
) -> Result<()> {
tracing::info!(
"Registering {} data sources with DataFusion",
data_sources.len()
);
for source in data_sources {
register_data_source(session_ctx, source, None)
.await
.with_context(|| format!("Failed to register data source: {}", source.name))?;
}
tracing::info!("All data sources registered successfully");
Ok(())
}
/// Register data sources with DataFusion SessionContext and OptimizerRegistry
pub async fn register_data_sources_with_registry(
session_ctx: &mut SessionContext,
data_sources: &[DataSource],
optimizer_registry: &Arc<crate::optimizer_registry::OptimizerRegistry>,
) -> Result<()> {
tracing::info!(
"Registering {} data sources with DataFusion and optimizer registry",
data_sources.len()
);
for source in data_sources {
register_data_source(session_ctx, source, Some(optimizer_registry))
.await
.with_context(|| format!("Failed to register data source: {}", source.name))?;
}
tracing::info!("All data sources registered successfully");
Ok(())
}
/// Register a single data source with DataFusion
async fn register_data_source(
session_ctx: &mut SessionContext,
source: &DataSource,
optimizer_registry: Option<&Arc<crate::optimizer_registry::OptimizerRegistry>>,
) -> Result<()> {
tracing::info!(
"Registering data source: {} (type: {:?})",
source.name,
source.source_type
);
// Initialize S3 storage handler for remote operations
let s3_storage = S3Storage::new();
// Validate data source configuration based on path type
match (&source.source_type, s3_storage.is_remote_path(&source.path)) {
(DataSourceType::Csv | DataSourceType::Parquet | DataSourceType::Lance, false) => {
// For local files, verify the file exists
if !source.path.exists() {
return Err(ConfigError::DataSourceFileNotFound {
name: source.name.clone(),
path: source.path.clone(),
}
.into());
}
}
(DataSourceType::Csv | DataSourceType::Parquet | DataSourceType::Lance, true) => {
// For S3 files, validate S3 configuration and setup object store
s3_storage.validate_configuration(source)?;
let s3_path = source.path.to_str().unwrap_or("");
s3_storage
.setup_object_store(session_ctx, &source.name, s3_path)
.await?;
}
(DataSourceType::Postgres | DataSourceType::Mysql | DataSourceType::Mongo, _) => {
// Database sources don't need file path validation
}
(DataSourceType::Iceberg, _) => {
// Validation happened during data source registration
}
}
match source.source_type {
DataSourceType::Csv => {
tracing::debug!("Registering CSV file: {} at {:?}", source.name, source.path);
// Create CSV format options from source configuration
let mut csv_read_options = datafusion::prelude::CsvReadOptions::new();
// Apply options if specified
if let Some(ref options) = source.options {
if let Some(has_header) = options.get("has_header") {
csv_read_options =
csv_read_options.has_header(has_header.parse::<bool>().unwrap_or(true));
}
if let Some(delimiter) = options.get("delimiter") {
if let Some(delimiter_char) = delimiter.chars().next() {
csv_read_options = csv_read_options.delimiter(delimiter_char as u8);
}
}
if let Some(schema_infer_max) = options.get("schema_infer_max_records") {
if let Ok(max_records) = schema_infer_max.parse::<usize>() {
csv_read_options = csv_read_options.schema_infer_max_records(max_records);
}
}
}
// Register the CSV file as a table
session_ctx
.register_csv(
&source.name,
source.path.to_str().unwrap(),
csv_read_options,
)
.await
.map_err(|e| ConfigError::DataSourceRegistrationFailed {
name: source.name.clone(),
error: e.to_string(),
})?;
}
DataSourceType::Parquet => {
tracing::debug!(
"Registering Parquet file: {} at {:?}",
source.name,
source.path
);
// Register the Parquet file as a table
session_ctx
.register_parquet(
&source.name,
source.path.to_str().unwrap(),
datafusion::prelude::ParquetReadOptions::default(),
)
.await
.map_err(|e| ConfigError::DataSourceRegistrationFailed {
name: source.name.clone(),
error: e.to_string(),
})?;
}
DataSourceType::Postgres => {
tracing::info!(
"Registering PostgreSQL table: {} (access_mode: {:?})",
source.name,
source.access_mode
);
// Get connection string
let connection_string = source.connection_string.as_ref().ok_or_else(|| {
ConfigError::MissingConnectionString {
name: source.name.clone(),
}
})?;
tracing::debug!(
"Connection string for {}: {} (options: {:?})",
source.name,
connection_string,
source.options
);
// Register PostgreSQL table using the sqlx-based provider
source::providers::sqlx::postgres::register_postgres_tables(
session_ctx,
&source.name,
connection_string,
source.options.as_ref(),
source.access_mode.is_read_write(),
)
.await
.map_err(|e| {
tracing::error!(
"PostgreSQL registration failed for '{}': {:?}",
source.name,
e
);
ConfigError::PostgresConnectionFailed {
name: source.name.clone(),
error: format!("{:?}", e),
}
})?;
}
DataSourceType::Mysql => {
tracing::info!(
"Registering MySQL table: {} (access_mode: {:?})",
source.name,
source.access_mode
);
let connection_string = source.connection_string.as_ref().ok_or_else(|| {
ConfigError::MissingConnectionString {
name: source.name.clone(),
}
})?;
tracing::debug!(
"Connection string for {}: {} (options: {:?})",
source.name,
connection_string,
source.options
);
source::providers::mysql::register_mysql_tables(
session_ctx,
&source.name,
connection_string,
source.options.as_ref(),
source.access_mode.is_read_write(),
)
.await
.map_err(|e| {
tracing::error!("MySQL registration failed for '{}': {:?}", source.name, e);
ConfigError::MySQLConnectionFailed {
name: source.name.clone(),
error: format!("{:?}", e),
}
})?;
}
DataSourceType::Iceberg => {
tracing::info!(
"Registering Iceberg table: {} from warehouse {:?}",
source.name,
source.path
);
let warehouse_path =
source
.path
.to_str()
.ok_or_else(|| ConfigError::DataSourceRegistrationFailed {
name: source.name.clone(),
error: "Invalid warehouse path".to_string(),
})?;
source::providers::iceberg::register_iceberg_table(
session_ctx,
&source.name,
warehouse_path,
source.options.as_ref(),
)
.await
.map_err(|e| {
tracing::error!("Iceberg registration failed for '{}': {:?}", source.name, e);
ConfigError::DataSourceRegistrationFailed {
name: source.name.clone(),
error: format!("{:?}", e),
}
})?;
}
DataSourceType::Mongo => {
tracing::info!("Registering MongoDB collection: {}", source.name);
let connection_string = source.connection_string.as_ref().ok_or_else(|| {
ConfigError::MissingConnectionString {
name: source.name.clone(),
}
})?;
tracing::debug!(
"Connection string for {}: {} (options: {:?})",
source.name,
connection_string,
source.options
);
source::providers::mongo::register_mongo_tables(
session_ctx,
&source.name,
connection_string,
source.options.as_ref(),
)
.await
.map_err(|e| {
tracing::error!("MongoDB registration failed for '{}': {:?}", source.name, e);
ConfigError::DataSourceRegistrationFailed {
name: source.name.clone(),
error: format!("{:?}", e),
}
})?;
}
DataSourceType::Lance => {
tracing::info!(
"Registering Lance dataset: {} at {:?}",
source.name,
source.path
);
// Get the dataset registry if optimizer registry is provided
let dataset_registry = optimizer_registry.map(|reg| reg.lance_datasets());
// Register Lance dataset using the providers module
source::providers::lance::register_lance_table(
session_ctx,
&source.name,
source.path.to_str().unwrap(),
dataset_registry.as_ref(),
)
.await
.map_err(|e| ConfigError::DataSourceRegistrationFailed {
name: source.name.clone(),
error: e.to_string(),
})?;
}
}
// If enable_cache is set for Csv/Parquet/Iceberg, load the table into a MemTable
if source.enable_cache
&& matches!(
source.source_type,
DataSourceType::Csv | DataSourceType::Parquet | DataSourceType::Iceberg
)
{
tracing::info!(
"Caching data source '{}' into memory (enable_cache=true)",
source.name
);
let df = session_ctx
.sql(&format!("SELECT * FROM {}", source.name))
.await
.map_err(|e| ConfigError::DataSourceRegistrationFailed {
name: source.name.clone(),
error: format!("Failed to read table for caching: {}", e),
})?;
let batches =
df.collect()
.await
.map_err(|e| ConfigError::DataSourceRegistrationFailed {
name: source.name.clone(),
error: format!("Failed to collect batches for caching: {}", e),
})?;
let schema = if let Some(batch) = batches.first() {
batch.schema()
} else {
// Empty table — get schema from the dataframe
let df = session_ctx
.sql(&format!("SELECT * FROM {} LIMIT 0", source.name))
.await
.map_err(|e| ConfigError::DataSourceRegistrationFailed {
name: source.name.clone(),
error: format!("Failed to infer schema for caching: {}", e),
})?;
Arc::new(df.schema().as_arrow().clone())
};
// Deregister the original table and replace with MemTable
session_ctx.deregister_table(&source.name).map_err(|e| {
ConfigError::DataSourceRegistrationFailed {
name: source.name.clone(),
error: format!("Failed to deregister table for caching: {}", e),
}
})?;
let mem_table = MemTable::try_new(schema, vec![batches]).map_err(|e| {
ConfigError::DataSourceRegistrationFailed {
name: source.name.clone(),
error: format!("Failed to create MemTable for caching: {}", e),
}
})?;
session_ctx
.register_table(&source.name, Arc::new(mem_table))
.map_err(|e| ConfigError::DataSourceRegistrationFailed {
name: source.name.clone(),
error: format!("Failed to register cached MemTable: {}", e),
})?;
tracing::info!(
"Data source '{}' cached in memory successfully",
source.name
);
}
tracing::info!("Successfully registered data source: {}", source.name);
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
use tempfile::TempDir;
fn create_test_pipeline_file(dir: &TempDir) -> PathBuf {
let pipeline_content = r#"
metadata:
name: "test-pipeline"
version: "1.0.0"
description: "Test pipeline for configuration testing"
query: |
SELECT date, category, value
FROM sample_data
WHERE date >= {date_filter}
AND ({category_filter} IS NULL OR category = {category_filter})
"#;
let pipeline_path = dir.path().join("test-pipeline.yaml");
fs::write(&pipeline_path, pipeline_content).unwrap();
pipeline_path
}
fn create_test_simple_pipeline_file(dir: &TempDir) -> PathBuf {
let pipeline_content = r#"
metadata:
name: "test-pipeline"
version: "1.0.0"
description: "Simple test pipeline without external table dependencies"
query: |
SELECT 1 as id, 'test' as name
"#;
let pipeline_path = dir.path().join("simple-pipeline.yaml");
fs::write(&pipeline_path, pipeline_content).unwrap();
pipeline_path
}
fn create_test_context_file(dir: &TempDir) -> PathBuf {
// Create the actual CSV file in the temp directory
let data_dir = dir.path().join("data");
fs::create_dir_all(&data_dir).unwrap();
let csv_path = data_dir.join("test.csv");
let csv_content = "date,value,category\n2023-01-01,1.0,A\n2023-01-02,2.0,B\n";
fs::write(&csv_path, csv_content).unwrap();
// Create a second test file (CSV)
let csv2_path = data_dir.join("reference.csv");
let ref_content = "id,name\n1,test1\n2,test2\n";
fs::write(&csv2_path, ref_content).unwrap();
// Create context content with correct paths (both CSV for simplicity)
let context_content = format!(
r#"
data_sources:
- name: "sample_data"
type: "csv"
path: "{}"
schema:
date: "timestamp"
value: "float64"
category: "string"
options: