Skip to main content

floe_core/run/
mod.rs

1use std::collections::HashSet;
2use std::path::Path;
3use std::sync::Once;
4use std::time::Instant;
5
6use crate::errors::IoError;
7use crate::report::build::project_metadata_json;
8use crate::report::output::write_summary_report;
9use crate::runtime::{DefaultRuntime, Runtime};
10use crate::{config, io, report, ConfigError, FloeResult, RunOptions, ValidateOptions};
11
12mod context;
13pub(crate) mod entity;
14pub mod events;
15mod file;
16mod output;
17mod perf;
18
19pub(crate) use context::RunContext;
20use entity::{run_entity, EntityRunResult, ResolvedEntityTargets};
21use events::{default_observer, event_time_ms, RunEvent};
22use serde_json::json;
23
24pub(super) const MAX_RESOLVED_INPUTS: usize = 50;
25
26pub(crate) struct EntityRunPlan<'a> {
27    pub(crate) entity: &'a config::EntityConfig,
28    pub(crate) resolved_targets: ResolvedEntityTargets,
29    pub(crate) resolved_inputs: io::storage::inputs::ResolvedInputs,
30    pub(crate) temp_dir: Option<tempfile::TempDir>,
31}
32
33#[derive(Debug, Clone)]
34pub struct RunOutcome {
35    pub run_id: String,
36    pub report_base_path: Option<String>,
37    pub entity_outcomes: Vec<EntityOutcome>,
38    pub summary: report::RunSummaryReport,
39    pub dry_run_previews: Option<Vec<DryRunEntityPreview>>,
40}
41
42#[derive(Debug, Clone)]
43pub struct DryRunEntityPreview {
44    pub name: String,
45    pub input_path: String,
46    pub input_format: String,
47    pub accepted_path: String,
48    pub accepted_format: String,
49    pub rejected_path: Option<String>,
50    pub rejected_format: Option<String>,
51    pub archive_path: String,
52    pub archive_storage: Option<String>,
53    pub report_file: Option<String>,
54    pub scanned_files: Vec<String>,
55}
56
57#[derive(Debug, Clone)]
58pub struct EntityOutcome {
59    pub report: crate::report::RunReport,
60    pub file_timings_ms: Vec<Option<u64>>,
61}
62
63pub(crate) fn validate_entities(
64    config: &config::RootConfig,
65    selected: &[String],
66) -> FloeResult<()> {
67    let missing: Vec<String> = selected
68        .iter()
69        .filter(|name| !config.entities.iter().any(|entity| &entity.name == *name))
70        .cloned()
71        .collect();
72
73    if !missing.is_empty() {
74        return Err(Box::new(ConfigError(format!(
75            "entities not found: {}",
76            missing.join(", ")
77        ))));
78    }
79    Ok(())
80}
81
82pub fn run(config_path: &Path, options: RunOptions) -> FloeResult<RunOutcome> {
83    let config_base = config::ConfigBase::local_from_path(config_path);
84    run_with_base(config_path, config_base, options)
85}
86
87pub fn run_with_base(
88    config_path: &Path,
89    config_base: config::ConfigBase,
90    options: RunOptions,
91) -> FloeResult<RunOutcome> {
92    let mut runtime = DefaultRuntime::new();
93    run_with_runtime(config_path, config_base, options, &mut runtime)
94}
95
96pub fn run_with_manifest_path(manifest_path: &Path, options: RunOptions) -> FloeResult<RunOutcome> {
97    let mut runtime = DefaultRuntime::new();
98    run_with_manifest_runtime(manifest_path, options, &mut runtime)
99}
100
101pub(crate) fn run_with_manifest_runtime(
102    manifest_path: &Path,
103    options: RunOptions,
104    runtime: &mut dyn Runtime,
105) -> FloeResult<RunOutcome> {
106    init_thread_pool();
107    let manifest_str = manifest_path.to_string_lossy();
108    let location = config::resolve_config_location(&manifest_str)?;
109    let json = std::fs::read_to_string(&location.path)?;
110    let (config, report_base_uri) = crate::manifest::config_from_manifest_json(&json)?;
111    let config_base = location.base.clone();
112    if !options.entities.is_empty() {
113        validate_entities(&config, &options.entities)?;
114    }
115    let context = RunContext::from_config(
116        config,
117        config_base,
118        manifest_path,
119        &report_base_uri,
120        &options,
121    )?;
122    run_from_context(context, options, runtime)
123}
124
125pub fn run_with_runtime(
126    config_path: &Path,
127    config_base: config::ConfigBase,
128    options: RunOptions,
129    runtime: &mut dyn Runtime,
130) -> FloeResult<RunOutcome> {
131    init_thread_pool();
132    let raw_config_env_vars = config::extract_raw_env_vars(config_path).unwrap_or_default();
133    let profile_vars = options
134        .profile
135        .as_ref()
136        .map(|p| {
137            crate::resolve_vars(crate::VarSources {
138                profile: &p.variables,
139                cli: &std::collections::HashMap::new(),
140                config: &raw_config_env_vars,
141            })
142        })
143        .transpose()?
144        .unwrap_or_default();
145    let validate_options = ValidateOptions {
146        entities: options.entities.clone(),
147        profile_vars: profile_vars.clone(),
148        profile_catalogs: options
149            .profile
150            .as_ref()
151            .and_then(|profile| profile.catalogs.clone()),
152        profile_storages: options
153            .profile
154            .as_ref()
155            .and_then(|profile| profile.storages.clone()),
156        profile_lineage: options
157            .profile
158            .as_ref()
159            .and_then(|profile| profile.lineage.clone()),
160    };
161    crate::validate_with_base(config_path, config_base.clone(), validate_options)?;
162    let context = RunContext::new(config_path, config_base, &options, profile_vars)?;
163    if !options.entities.is_empty() {
164        validate_entities(&context.config, &options.entities)?;
165    }
166
167    run_from_context(context, options, runtime)
168}
169
170fn run_from_context(
171    context: RunContext,
172    options: RunOptions,
173    runtime: &mut dyn Runtime,
174) -> FloeResult<RunOutcome> {
175    let observer = default_observer();
176    let perf_enabled = perf::phase_timing_enabled();
177    let selected_entities = select_entities(&context, &options);
178    if options.full_refresh {
179        for entity in &selected_entities {
180            if matches!(
181                entity.sink.write_mode,
182                config::WriteMode::MergeScd1 | config::WriteMode::MergeScd2
183            ) {
184                return Err(Box::new(ConfigError(format!(
185                    "entity '{}': --full-refresh is not supported with write_mode '{}'",
186                    entity.name,
187                    entity.sink.write_mode.as_str()
188                ))));
189            }
190        }
191    }
192    let resolution_mode = if options.dry_run {
193        io::storage::inputs::ResolveInputsMode::ListOnly
194    } else {
195        io::storage::inputs::ResolveInputsMode::Download
196    };
197    if !options.dry_run {
198        observer.on_event(RunEvent::RunStarted {
199            run_id: context.run_id.clone(),
200            config: context.config_path.display().to_string(),
201            report_base: context.report_base_path.clone(),
202            ts_ms: event_time_ms(),
203        });
204        crate::run::events::mark_run_started();
205    }
206    let resolve_start = perf_enabled.then(Instant::now);
207    let plans = resolve_entity_plans(&context, runtime, &selected_entities, resolution_mode)?;
208    if let Some(start) = resolve_start {
209        perf::emit_perf_log(
210            observer,
211            &context.run_id,
212            None,
213            "perf_run_phase_timings",
214            json!({
215                "phase": "resolve_inputs",
216                "elapsed_ms": start.elapsed().as_millis() as u64,
217                "entity_count": selected_entities.len(),
218                "mode": match resolution_mode {
219                    io::storage::inputs::ResolveInputsMode::ListOnly => "list_only",
220                    io::storage::inputs::ResolveInputsMode::Download => "download",
221                },
222            }),
223        );
224    }
225    if options.dry_run {
226        return create_dry_run_outcome(&context, plans);
227    }
228
229    let mut entity_outcomes = Vec::new();
230    let mut abort_run = false;
231
232    for plan in plans {
233        let entity_name = plan.entity.name.clone();
234        observer.on_event(RunEvent::EntityStarted {
235            run_id: context.run_id.clone(),
236            name: entity_name.clone(),
237            ts_ms: event_time_ms(),
238        });
239        let entity_result = run_entity(&context, runtime, observer, plan);
240        if let Err(err) = entity_result {
241            observer.on_event(RunEvent::EntityFinished {
242                run_id: context.run_id.clone(),
243                name: entity_name,
244                status: "failed".to_string(),
245                files: 0,
246                files_skipped: 0,
247                rows: 0,
248                accepted: 0,
249                rejected: 0,
250                warnings: 0,
251                errors: 0,
252                ts_ms: event_time_ms(),
253            });
254            return Err(err);
255        }
256        let EntityRunResult {
257            outcome,
258            abort_run: aborted,
259        } = entity_result.unwrap();
260        let report = &outcome.report;
261        let (mut status, _) = report::compute_run_outcome(
262            &report
263                .files
264                .iter()
265                .map(|file| file.status)
266                .collect::<Vec<_>>(),
267        );
268        status = upgrade_status_for_warnings(status, report.results.warnings_total);
269        observer.on_event(RunEvent::EntityFinished {
270            run_id: context.run_id.clone(),
271            name: report.entity.name.clone(),
272            status: run_status_str(status).to_string(),
273            files: report.results.files_total,
274            files_skipped: report.results.files_skipped,
275            rows: report.results.rows_total,
276            accepted: report.results.accepted_total,
277            rejected: report.results.rejected_total,
278            warnings: report.results.warnings_total,
279            errors: report.results.errors_total,
280            ts_ms: event_time_ms(),
281        });
282        entity_outcomes.push(outcome);
283        abort_run = abort_run || aborted;
284        if abort_run {
285            break;
286        }
287    }
288    let summary = build_run_summary(&context, &entity_outcomes);
289    if let Some(report_target) = &context.report_target {
290        let summary_write_start = perf_enabled.then(Instant::now);
291        write_summary_report(
292            report_target,
293            &context.run_id,
294            &summary,
295            runtime.storage(),
296            &context.storage_resolver,
297        )?;
298        if let Some(start) = summary_write_start {
299            perf::emit_perf_log(
300                observer,
301                &context.run_id,
302                None,
303                "perf_run_phase_timings",
304                json!({
305                    "phase": "write_summary_report",
306                    "elapsed_ms": start.elapsed().as_millis() as u64,
307                    "entity_count": entity_outcomes.len(),
308                }),
309            );
310        }
311    }
312    observer.on_event(RunEvent::RunFinished {
313        run_id: context.run_id.clone(),
314        status: run_status_str(summary.run.status).to_string(),
315        exit_code: summary.run.exit_code,
316        files: summary.results.files_total,
317        files_skipped: summary.results.files_skipped,
318        rows: summary.results.rows_total,
319        accepted: summary.results.accepted_total,
320        rejected: summary.results.rejected_total,
321        warnings: summary.results.warnings_total,
322        errors: summary.results.errors_total,
323        summary_uri: context.report_target.as_ref().map(|target| {
324            target.join_relative(&report::ReportWriter::summary_relative_path(
325                &context.run_id,
326            ))
327        }),
328        ts_ms: event_time_ms(),
329    });
330
331    Ok(RunOutcome {
332        run_id: context.run_id.clone(),
333        report_base_path: context.report_base_path.clone(),
334        entity_outcomes,
335        summary,
336        dry_run_previews: None,
337    })
338}
339
340fn init_thread_pool() {
341    static INIT: Once = Once::new();
342    INIT.call_once(|| {
343        if std::env::var("RAYON_NUM_THREADS").is_ok() {
344            return;
345        }
346        let cap = std::env::var("FLOE_MAX_THREADS")
347            .ok()
348            .and_then(|value| value.parse::<usize>().ok())
349            .unwrap_or(4);
350        let available = std::thread::available_parallelism()
351            .map(|value| value.get())
352            .unwrap_or(1);
353        let threads = available.min(cap).max(1);
354        let _ = rayon::ThreadPoolBuilder::new()
355            .num_threads(threads)
356            .build_global();
357    });
358}
359
360fn select_entities<'a>(
361    context: &'a RunContext,
362    options: &RunOptions,
363) -> Vec<&'a config::EntityConfig> {
364    if options.entities.is_empty() {
365        context.config.entities.iter().collect()
366    } else {
367        let selected: HashSet<&str> = options.entities.iter().map(String::as_str).collect();
368        context
369            .config
370            .entities
371            .iter()
372            .filter(|entity| selected.contains(entity.name.as_str()))
373            .collect()
374    }
375}
376
377fn resolve_entity_plans<'a>(
378    context: &'a RunContext,
379    runtime: &mut dyn Runtime,
380    entities: &[&'a config::EntityConfig],
381    resolution_mode: io::storage::inputs::ResolveInputsMode,
382) -> FloeResult<Vec<EntityRunPlan<'a>>> {
383    let mut plans = Vec::with_capacity(entities.len());
384    for entity in entities {
385        let input_adapter = runtime.input_adapter(entity.source.format.as_str())?;
386        let resolved_targets = entity::resolve_entity_targets(&context.storage_resolver, entity)?;
387        let needs_temp = matches!(
388            resolution_mode,
389            io::storage::inputs::ResolveInputsMode::Download
390        ) && (resolved_targets.source.is_remote()
391            || resolved_targets.accepted.is_remote()
392            || resolved_targets
393                .rejected
394                .as_ref()
395                .is_some_and(io::storage::Target::is_remote));
396        let temp_dir = if needs_temp {
397            Some(
398                tempfile::TempDir::new()
399                    .map_err(|err| Box::new(IoError(format!("tempdir failed: {err}"))))?,
400            )
401        } else {
402            None
403        };
404        let storage_client = Some(runtime.storage().client_for(
405            &context.storage_resolver,
406            resolved_targets.source.storage(),
407            entity,
408        )? as &dyn io::storage::StorageClient);
409        let resolved_inputs = io::storage::ops::resolve_inputs(
410            &context.config_dir,
411            entity,
412            input_adapter,
413            &resolved_targets.source,
414            resolution_mode,
415            temp_dir.as_ref().map(|dir| dir.path()),
416            storage_client,
417        )?;
418        plans.push(EntityRunPlan {
419            entity,
420            resolved_targets,
421            resolved_inputs,
422            temp_dir,
423        });
424    }
425    Ok(plans)
426}
427
428fn build_run_summary(
429    context: &RunContext,
430    entity_outcomes: &[EntityOutcome],
431) -> report::RunSummaryReport {
432    let mut totals = report::ResultsTotals {
433        files_total: 0,
434        files_skipped: 0,
435        rows_total: 0,
436        accepted_total: 0,
437        rejected_total: 0,
438        warnings_total: 0,
439        errors_total: 0,
440    };
441    let mut statuses = Vec::new();
442    let mut entities = Vec::with_capacity(entity_outcomes.len());
443
444    for outcome in entity_outcomes {
445        let report = &outcome.report;
446        totals.files_total += report.results.files_total;
447        totals.files_skipped += report.results.files_skipped;
448        totals.rows_total += report.results.rows_total;
449        totals.accepted_total += report.results.accepted_total;
450        totals.rejected_total += report.results.rejected_total;
451        totals.warnings_total += report.results.warnings_total;
452        totals.errors_total += report.results.errors_total;
453
454        let file_statuses = report
455            .files
456            .iter()
457            .map(|file| file.status)
458            .collect::<Vec<_>>();
459        let (mut status, _) = report::compute_run_outcome(&file_statuses);
460        status = upgrade_status_for_warnings(status, report.results.warnings_total);
461        statuses.extend(file_statuses);
462
463        let report_file = context
464            .report_target
465            .as_ref()
466            .map(|target| {
467                target.join_relative(&report::ReportWriter::report_relative_path(
468                    &context.run_id,
469                    &report.entity.name,
470                ))
471            })
472            .unwrap_or_else(|| "disabled".to_string());
473        entities.push(report::EntitySummary {
474            name: report.entity.name.clone(),
475            status,
476            results: report.results.clone(),
477            report_file,
478        });
479    }
480
481    let (mut status, exit_code) = report::compute_run_outcome(&statuses);
482    status = upgrade_status_for_warnings(status, totals.warnings_total);
483
484    let finished_at = report::now_rfc3339();
485    let duration_ms = context.run_timer.elapsed().as_millis() as u64;
486    let report_base_path = context
487        .report_base_path
488        .clone()
489        .unwrap_or_else(|| "disabled".to_string());
490    let report_file = context
491        .report_target
492        .as_ref()
493        .map(|target| {
494            target.join_relative(&report::ReportWriter::summary_relative_path(
495                &context.run_id,
496            ))
497        })
498        .unwrap_or_else(|| "disabled".to_string());
499
500    report::RunSummaryReport {
501        spec_version: context.config.version.clone(),
502        tool: build_tool_info(),
503        run: report::RunInfo {
504            run_id: context.run_id.clone(),
505            started_at: context.started_at.clone(),
506            finished_at,
507            duration_ms,
508            status,
509            exit_code,
510        },
511        config: build_config_echo(context),
512        report: build_report_echo(report_base_path, report_file),
513        results: totals,
514        entities,
515    }
516}
517
518fn create_dry_run_outcome(
519    context: &RunContext,
520    plans: Vec<EntityRunPlan<'_>>,
521) -> FloeResult<RunOutcome> {
522    let mut previews: Vec<DryRunEntityPreview> = Vec::new();
523
524    for plan in plans {
525        let entity = plan.entity;
526        let rejected_path = entity.sink.rejected.as_ref().map(|r| r.path.clone());
527        let rejected_format = entity.sink.rejected.as_ref().map(|r| r.format.clone());
528        let (archive_path, archive_storage) = entity
529            .sink
530            .archive
531            .as_ref()
532            .map(|a| (a.path.clone(), a.storage.clone()))
533            .unwrap_or_else(|| (String::new(), None));
534
535        let report_file = context.report_target.as_ref().map(|target| {
536            target.join_relative(&report::ReportWriter::report_relative_path(
537                &context.run_id,
538                &entity.name,
539            ))
540        });
541
542        previews.push(DryRunEntityPreview {
543            name: entity.name.clone(),
544            input_path: entity.source.path.clone(),
545            input_format: entity.source.format.clone(),
546            accepted_path: entity.sink.accepted.path.clone(),
547            accepted_format: entity.sink.accepted.format.clone(),
548            rejected_path,
549            rejected_format,
550            archive_path,
551            archive_storage,
552            report_file,
553            scanned_files: plan.resolved_inputs.listed,
554        });
555    }
556
557    Ok(RunOutcome {
558        run_id: context.run_id.clone(),
559        report_base_path: context.report_base_path.clone(),
560        entity_outcomes: Vec::new(),
561        summary: report::RunSummaryReport {
562            spec_version: context.config.version.clone(),
563            tool: build_tool_info(),
564            run: report::RunInfo {
565                run_id: context.run_id.clone(),
566                started_at: context.started_at.clone(),
567                finished_at: report::now_rfc3339(),
568                duration_ms: 0,
569                status: report::RunStatus::Success,
570                exit_code: 0,
571            },
572            config: build_config_echo(context),
573            report: build_report_echo(
574                context
575                    .report_base_path
576                    .clone()
577                    .unwrap_or_else(|| "disabled".to_string()),
578                "disabled (dry-run)".to_string(),
579            ),
580            results: report::ResultsTotals {
581                files_total: 0,
582                files_skipped: 0,
583                rows_total: 0,
584                accepted_total: 0,
585                rejected_total: 0,
586                warnings_total: 0,
587                errors_total: 0,
588            },
589            entities: Vec::new(),
590        },
591        dry_run_previews: Some(previews),
592    })
593}
594
595fn upgrade_status_for_warnings(status: report::RunStatus, warnings: u64) -> report::RunStatus {
596    if status == report::RunStatus::Success && warnings > 0 {
597        report::RunStatus::SuccessWithWarnings
598    } else {
599        status
600    }
601}
602
603fn build_tool_info() -> report::ToolInfo {
604    report::ToolInfo {
605        name: "floe".to_string(),
606        version: env!("CARGO_PKG_VERSION").to_string(),
607        git: None,
608    }
609}
610
611fn build_config_echo(context: &RunContext) -> report::ConfigEcho {
612    report::ConfigEcho {
613        path: context.config_path.display().to_string(),
614        version: context.config.version.clone(),
615        metadata: context.config.metadata.as_ref().map(project_metadata_json),
616    }
617}
618
619fn build_report_echo(path: String, report_file: String) -> report::ReportEcho {
620    report::ReportEcho { path, report_file }
621}
622
623fn run_status_str(status: report::RunStatus) -> &'static str {
624    match status {
625        report::RunStatus::Success => "success",
626        report::RunStatus::SuccessWithWarnings => "success_with_warnings",
627        report::RunStatus::Rejected => "rejected",
628        report::RunStatus::Aborted => "aborted",
629        report::RunStatus::Failed => "failed",
630    }
631}