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 let resolution_mode = if options.dry_run {
179 io::storage::inputs::ResolveInputsMode::ListOnly
180 } else {
181 io::storage::inputs::ResolveInputsMode::Download
182 };
183 if !options.dry_run {
184 observer.on_event(RunEvent::RunStarted {
185 run_id: context.run_id.clone(),
186 config: context.config_path.display().to_string(),
187 report_base: context.report_base_path.clone(),
188 ts_ms: event_time_ms(),
189 });
190 crate::run::events::mark_run_started();
191 }
192 let resolve_start = perf_enabled.then(Instant::now);
193 let plans = resolve_entity_plans(&context, runtime, &selected_entities, resolution_mode)?;
194 if let Some(start) = resolve_start {
195 perf::emit_perf_log(
196 observer,
197 &context.run_id,
198 None,
199 "perf_run_phase_timings",
200 json!({
201 "phase": "resolve_inputs",
202 "elapsed_ms": start.elapsed().as_millis() as u64,
203 "entity_count": selected_entities.len(),
204 "mode": match resolution_mode {
205 io::storage::inputs::ResolveInputsMode::ListOnly => "list_only",
206 io::storage::inputs::ResolveInputsMode::Download => "download",
207 },
208 }),
209 );
210 }
211 if options.dry_run {
212 return create_dry_run_outcome(&context, plans);
213 }
214
215 let mut entity_outcomes = Vec::new();
216 let mut abort_run = false;
217
218 for plan in plans {
219 let entity_name = plan.entity.name.clone();
220 observer.on_event(RunEvent::EntityStarted {
221 run_id: context.run_id.clone(),
222 name: entity_name.clone(),
223 ts_ms: event_time_ms(),
224 });
225 let entity_result = run_entity(&context, runtime, observer, plan);
226 if let Err(err) = entity_result {
227 observer.on_event(RunEvent::EntityFinished {
228 run_id: context.run_id.clone(),
229 name: entity_name,
230 status: "failed".to_string(),
231 files: 0,
232 files_skipped: 0,
233 rows: 0,
234 accepted: 0,
235 rejected: 0,
236 warnings: 0,
237 errors: 0,
238 ts_ms: event_time_ms(),
239 });
240 return Err(err);
241 }
242 let EntityRunResult {
243 outcome,
244 abort_run: aborted,
245 } = entity_result.unwrap();
246 let report = &outcome.report;
247 let (mut status, _) = report::compute_run_outcome(
248 &report
249 .files
250 .iter()
251 .map(|file| file.status)
252 .collect::<Vec<_>>(),
253 );
254 status = upgrade_status_for_warnings(status, report.results.warnings_total);
255 observer.on_event(RunEvent::EntityFinished {
256 run_id: context.run_id.clone(),
257 name: report.entity.name.clone(),
258 status: run_status_str(status).to_string(),
259 files: report.results.files_total,
260 files_skipped: report.results.files_skipped,
261 rows: report.results.rows_total,
262 accepted: report.results.accepted_total,
263 rejected: report.results.rejected_total,
264 warnings: report.results.warnings_total,
265 errors: report.results.errors_total,
266 ts_ms: event_time_ms(),
267 });
268 entity_outcomes.push(outcome);
269 abort_run = abort_run || aborted;
270 if abort_run {
271 break;
272 }
273 }
274 let summary = build_run_summary(&context, &entity_outcomes);
275 if let Some(report_target) = &context.report_target {
276 let summary_write_start = perf_enabled.then(Instant::now);
277 write_summary_report(
278 report_target,
279 &context.run_id,
280 &summary,
281 runtime.storage(),
282 &context.storage_resolver,
283 )?;
284 if let Some(start) = summary_write_start {
285 perf::emit_perf_log(
286 observer,
287 &context.run_id,
288 None,
289 "perf_run_phase_timings",
290 json!({
291 "phase": "write_summary_report",
292 "elapsed_ms": start.elapsed().as_millis() as u64,
293 "entity_count": entity_outcomes.len(),
294 }),
295 );
296 }
297 }
298 observer.on_event(RunEvent::RunFinished {
299 run_id: context.run_id.clone(),
300 status: run_status_str(summary.run.status).to_string(),
301 exit_code: summary.run.exit_code,
302 files: summary.results.files_total,
303 files_skipped: summary.results.files_skipped,
304 rows: summary.results.rows_total,
305 accepted: summary.results.accepted_total,
306 rejected: summary.results.rejected_total,
307 warnings: summary.results.warnings_total,
308 errors: summary.results.errors_total,
309 summary_uri: context.report_target.as_ref().map(|target| {
310 target.join_relative(&report::ReportWriter::summary_relative_path(
311 &context.run_id,
312 ))
313 }),
314 ts_ms: event_time_ms(),
315 });
316
317 Ok(RunOutcome {
318 run_id: context.run_id.clone(),
319 report_base_path: context.report_base_path.clone(),
320 entity_outcomes,
321 summary,
322 dry_run_previews: None,
323 })
324}
325
326fn init_thread_pool() {
327 static INIT: Once = Once::new();
328 INIT.call_once(|| {
329 if std::env::var("RAYON_NUM_THREADS").is_ok() {
330 return;
331 }
332 let cap = std::env::var("FLOE_MAX_THREADS")
333 .ok()
334 .and_then(|value| value.parse::<usize>().ok())
335 .unwrap_or(4);
336 let available = std::thread::available_parallelism()
337 .map(|value| value.get())
338 .unwrap_or(1);
339 let threads = available.min(cap).max(1);
340 let _ = rayon::ThreadPoolBuilder::new()
341 .num_threads(threads)
342 .build_global();
343 });
344}
345
346fn select_entities<'a>(
347 context: &'a RunContext,
348 options: &RunOptions,
349) -> Vec<&'a config::EntityConfig> {
350 if options.entities.is_empty() {
351 context.config.entities.iter().collect()
352 } else {
353 let selected: HashSet<&str> = options.entities.iter().map(String::as_str).collect();
354 context
355 .config
356 .entities
357 .iter()
358 .filter(|entity| selected.contains(entity.name.as_str()))
359 .collect()
360 }
361}
362
363fn resolve_entity_plans<'a>(
364 context: &'a RunContext,
365 runtime: &mut dyn Runtime,
366 entities: &[&'a config::EntityConfig],
367 resolution_mode: io::storage::inputs::ResolveInputsMode,
368) -> FloeResult<Vec<EntityRunPlan<'a>>> {
369 let mut plans = Vec::with_capacity(entities.len());
370 for entity in entities {
371 let input_adapter = runtime.input_adapter(entity.source.format.as_str())?;
372 let resolved_targets = entity::resolve_entity_targets(&context.storage_resolver, entity)?;
373 let needs_temp = matches!(
374 resolution_mode,
375 io::storage::inputs::ResolveInputsMode::Download
376 ) && (resolved_targets.source.is_remote()
377 || resolved_targets.accepted.is_remote()
378 || resolved_targets
379 .rejected
380 .as_ref()
381 .is_some_and(io::storage::Target::is_remote));
382 let temp_dir = if needs_temp {
383 Some(
384 tempfile::TempDir::new()
385 .map_err(|err| Box::new(IoError(format!("tempdir failed: {err}"))))?,
386 )
387 } else {
388 None
389 };
390 let storage_client = Some(runtime.storage().client_for(
391 &context.storage_resolver,
392 resolved_targets.source.storage(),
393 entity,
394 )? as &dyn io::storage::StorageClient);
395 let resolved_inputs = io::storage::ops::resolve_inputs(
396 &context.config_dir,
397 entity,
398 input_adapter,
399 &resolved_targets.source,
400 resolution_mode,
401 temp_dir.as_ref().map(|dir| dir.path()),
402 storage_client,
403 )?;
404 plans.push(EntityRunPlan {
405 entity,
406 resolved_targets,
407 resolved_inputs,
408 temp_dir,
409 });
410 }
411 Ok(plans)
412}
413
414fn build_run_summary(
415 context: &RunContext,
416 entity_outcomes: &[EntityOutcome],
417) -> report::RunSummaryReport {
418 let mut totals = report::ResultsTotals {
419 files_total: 0,
420 files_skipped: 0,
421 rows_total: 0,
422 accepted_total: 0,
423 rejected_total: 0,
424 warnings_total: 0,
425 errors_total: 0,
426 };
427 let mut statuses = Vec::new();
428 let mut entities = Vec::with_capacity(entity_outcomes.len());
429
430 for outcome in entity_outcomes {
431 let report = &outcome.report;
432 totals.files_total += report.results.files_total;
433 totals.files_skipped += report.results.files_skipped;
434 totals.rows_total += report.results.rows_total;
435 totals.accepted_total += report.results.accepted_total;
436 totals.rejected_total += report.results.rejected_total;
437 totals.warnings_total += report.results.warnings_total;
438 totals.errors_total += report.results.errors_total;
439
440 let file_statuses = report
441 .files
442 .iter()
443 .map(|file| file.status)
444 .collect::<Vec<_>>();
445 let (mut status, _) = report::compute_run_outcome(&file_statuses);
446 status = upgrade_status_for_warnings(status, report.results.warnings_total);
447 statuses.extend(file_statuses);
448
449 let report_file = context
450 .report_target
451 .as_ref()
452 .map(|target| {
453 target.join_relative(&report::ReportWriter::report_relative_path(
454 &context.run_id,
455 &report.entity.name,
456 ))
457 })
458 .unwrap_or_else(|| "disabled".to_string());
459 entities.push(report::EntitySummary {
460 name: report.entity.name.clone(),
461 status,
462 results: report.results.clone(),
463 report_file,
464 });
465 }
466
467 let (mut status, exit_code) = report::compute_run_outcome(&statuses);
468 status = upgrade_status_for_warnings(status, totals.warnings_total);
469
470 let finished_at = report::now_rfc3339();
471 let duration_ms = context.run_timer.elapsed().as_millis() as u64;
472 let report_base_path = context
473 .report_base_path
474 .clone()
475 .unwrap_or_else(|| "disabled".to_string());
476 let report_file = context
477 .report_target
478 .as_ref()
479 .map(|target| {
480 target.join_relative(&report::ReportWriter::summary_relative_path(
481 &context.run_id,
482 ))
483 })
484 .unwrap_or_else(|| "disabled".to_string());
485
486 report::RunSummaryReport {
487 spec_version: context.config.version.clone(),
488 tool: build_tool_info(),
489 run: report::RunInfo {
490 run_id: context.run_id.clone(),
491 started_at: context.started_at.clone(),
492 finished_at,
493 duration_ms,
494 status,
495 exit_code,
496 },
497 config: build_config_echo(context),
498 report: build_report_echo(report_base_path, report_file),
499 results: totals,
500 entities,
501 }
502}
503
504fn create_dry_run_outcome(
505 context: &RunContext,
506 plans: Vec<EntityRunPlan<'_>>,
507) -> FloeResult<RunOutcome> {
508 let mut previews: Vec<DryRunEntityPreview> = Vec::new();
509
510 for plan in plans {
511 let entity = plan.entity;
512 let rejected_path = entity.sink.rejected.as_ref().map(|r| r.path.clone());
513 let rejected_format = entity.sink.rejected.as_ref().map(|r| r.format.clone());
514 let (archive_path, archive_storage) = entity
515 .sink
516 .archive
517 .as_ref()
518 .map(|a| (a.path.clone(), a.storage.clone()))
519 .unwrap_or_else(|| (String::new(), None));
520
521 let report_file = context.report_target.as_ref().map(|target| {
522 target.join_relative(&report::ReportWriter::report_relative_path(
523 &context.run_id,
524 &entity.name,
525 ))
526 });
527
528 previews.push(DryRunEntityPreview {
529 name: entity.name.clone(),
530 input_path: entity.source.path.clone(),
531 input_format: entity.source.format.clone(),
532 accepted_path: entity.sink.accepted.path.clone(),
533 accepted_format: entity.sink.accepted.format.clone(),
534 rejected_path,
535 rejected_format,
536 archive_path,
537 archive_storage,
538 report_file,
539 scanned_files: plan.resolved_inputs.listed,
540 });
541 }
542
543 Ok(RunOutcome {
544 run_id: context.run_id.clone(),
545 report_base_path: context.report_base_path.clone(),
546 entity_outcomes: Vec::new(),
547 summary: report::RunSummaryReport {
548 spec_version: context.config.version.clone(),
549 tool: build_tool_info(),
550 run: report::RunInfo {
551 run_id: context.run_id.clone(),
552 started_at: context.started_at.clone(),
553 finished_at: report::now_rfc3339(),
554 duration_ms: 0,
555 status: report::RunStatus::Success,
556 exit_code: 0,
557 },
558 config: build_config_echo(context),
559 report: build_report_echo(
560 context
561 .report_base_path
562 .clone()
563 .unwrap_or_else(|| "disabled".to_string()),
564 "disabled (dry-run)".to_string(),
565 ),
566 results: report::ResultsTotals {
567 files_total: 0,
568 files_skipped: 0,
569 rows_total: 0,
570 accepted_total: 0,
571 rejected_total: 0,
572 warnings_total: 0,
573 errors_total: 0,
574 },
575 entities: Vec::new(),
576 },
577 dry_run_previews: Some(previews),
578 })
579}
580
581fn upgrade_status_for_warnings(status: report::RunStatus, warnings: u64) -> report::RunStatus {
582 if status == report::RunStatus::Success && warnings > 0 {
583 report::RunStatus::SuccessWithWarnings
584 } else {
585 status
586 }
587}
588
589fn build_tool_info() -> report::ToolInfo {
590 report::ToolInfo {
591 name: "floe".to_string(),
592 version: env!("CARGO_PKG_VERSION").to_string(),
593 git: None,
594 }
595}
596
597fn build_config_echo(context: &RunContext) -> report::ConfigEcho {
598 report::ConfigEcho {
599 path: context.config_path.display().to_string(),
600 version: context.config.version.clone(),
601 metadata: context.config.metadata.as_ref().map(project_metadata_json),
602 }
603}
604
605fn build_report_echo(path: String, report_file: String) -> report::ReportEcho {
606 report::ReportEcho { path, report_file }
607}
608
609fn run_status_str(status: report::RunStatus) -> &'static str {
610 match status {
611 report::RunStatus::Success => "success",
612 report::RunStatus::SuccessWithWarnings => "success_with_warnings",
613 report::RunStatus::Rejected => "rejected",
614 report::RunStatus::Aborted => "aborted",
615 report::RunStatus::Failed => "failed",
616 }
617}