diff --git a/Cargo.lock b/Cargo.lock index 970d89740c..afde69957d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2231,6 +2231,7 @@ dependencies = [ "convert_case 0.6.0", "dal-macros", "dal-materialized-views", + "dal-summary-generator", "dal-test", "dashmap", "derive_more", @@ -2329,6 +2330,21 @@ dependencies = [ "syn 2.0.104", ] +[[package]] +name = "dal-summary-generator" +version = "0.1.0" +dependencies = [ + "chrono", + "dal", + "remain", + "serde_json", + "si-events", + "si-id", + "si-layer-cache", + "telemetry", + "thiserror 2.0.12", +] + [[package]] name = "dal-test" version = "0.1.0" @@ -4818,6 +4834,7 @@ dependencies = [ "color-eyre", "dal", "dal-materialized-views", + "dal-summary-generator", "derive_builder", "edda-client", "edda-core", diff --git a/Cargo.toml b/Cargo.toml index 758bb0af35..20f17d3078 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -37,6 +37,7 @@ members = [ "lib/dal-macros", "lib/dal-materialized-views", "lib/dal-materialized-views-macros", + "lib/dal-summary-generator", "lib/dal-test", "lib/data-warehouse-stream-client", "lib/edda-client", diff --git a/lib/dal-summary-generator/BUCK b/lib/dal-summary-generator/BUCK new file mode 100644 index 0000000000..9c02762070 --- /dev/null +++ b/lib/dal-summary-generator/BUCK @@ -0,0 +1,19 @@ +load("@prelude-si//:macros.bzl", "rust_library") + +rust_library( + name = "dal-summary-generator", + deps = [ + "//lib/dal:dal", + "//lib/si-events-rs:si-events", + "//lib/si-id:si-id", + "//lib/si-layer-cache:si-layer-cache", + "//lib/telemetry-rs:telemetry", + "//third-party/rust:chrono", + "//third-party/rust:remain", + "//third-party/rust:serde_json", + "//third-party/rust:thiserror", + ], + srcs = glob([ + "src/**/*.rs", + ]), +) diff --git a/lib/dal-summary-generator/Cargo.toml b/lib/dal-summary-generator/Cargo.toml new file mode 100644 index 0000000000..7e849fa77c --- /dev/null +++ b/lib/dal-summary-generator/Cargo.toml @@ -0,0 +1,20 @@ +[package] +name = "dal-summary-generator" +version.workspace = true +authors.workspace = true +license.workspace = true +repository.workspace = true +edition.workspace = true +rust-version.workspace = true +publish.workspace = true + +[dependencies] +chrono = { workspace = true } +dal = { path = "../../lib/dal" } +remain = { workspace = true } +serde_json = { workspace = true } +si-events = { path = "../../lib/si-events-rs" } +si-id = { path = "../../lib/si-id" } +si-layer-cache = { path = "../../lib/si-layer-cache" } +telemetry = { path = "../../lib/telemetry-rs" } +thiserror = { workspace = true } diff --git a/lib/dal-summary-generator/src/component_summary.rs b/lib/dal-summary-generator/src/component_summary.rs new file mode 100644 index 0000000000..b775cef7e6 --- /dev/null +++ b/lib/dal-summary-generator/src/component_summary.rs @@ -0,0 +1,706 @@ +use std::{ + collections::{ + BTreeMap, + HashMap, + }, + hash::{ + Hash, + Hasher, + }, + time::Instant, +}; + +use chrono::{ + DateTime, + Utc, +}; +use dal::{ + AttributeValue, + Component, + ComponentId, + DalContext, + action::{ + Action, + dependency_graph::ActionDependencyGraph, + prototype::ActionPrototype, + }, + component::properties::ComponentProperties, + diagram::Diagram, +}; +use execution_histories::ExecutionHistories; +use si_events::ActionState; +use si_id::{ + ActionId, + FuncRunId, +}; +use telemetry::prelude::*; + +pub(crate) mod execution_histories; + +#[derive(Debug, Clone)] +pub struct ComponentSummary { + pub component_name: String, + pub schema_name: String, + pub has_resource: Option, + pub resource_id: Option, + pub resource_status: Option, + pub has_diff: Option, + pub diff_status: Option, + pub subscriptions: Vec, + pub manages: Vec, + pub action_functions: Vec, + pub management_functions: Vec, + pub qualification_functions: Vec, +} + +#[derive(Debug, Clone)] +pub struct SubscriptionRelationship { + pub to_component_id: ComponentId, + pub to_component_name: String, + pub from_path: String, + pub to_path: String, + pub current_value: Option, +} + +#[derive(Debug, Clone)] +pub struct ManagementRelationship { + pub to_component_id: ComponentId, + pub to_component_name: String, +} + +#[derive(Debug, Clone)] +pub struct FunctionRelationship { + pub function_name: String, + pub execution_status: Option, + pub depends_on: Vec, + pub execution_history: Vec, +} + +#[derive(Debug, Clone)] +pub struct FunctionExecutionStatus { + pub state: String, + pub has_active_run: bool, + pub func_run_id: Option, + pub action_id: Option, +} + +#[derive(Debug, Clone)] +pub struct ExecutionHistoryEntry { + pub func_run_id: FuncRunId, + pub state: String, + pub started_at: DateTime, +} + +#[derive(Debug, Clone)] +pub struct ComponentSummaryGenerator { + include_action_functions: bool, + include_diff_status: bool, + include_execution_history: bool, + include_management_functions: bool, + include_manages: bool, + include_qualification_functions: bool, + include_resource_info: bool, + include_subscriptions: bool, +} + +impl ComponentSummaryGenerator { + #[allow(clippy::too_many_arguments)] + pub fn new( + include_action_functions: bool, + include_diff_status: bool, + include_execution_history: bool, + include_management_functions: bool, + include_manages: bool, + include_qualification_functions: bool, + include_resource_info: bool, + include_subscriptions: bool, + ) -> Self { + Self { + include_action_functions, + include_diff_status, + include_execution_history, + include_management_functions, + include_manages, + include_qualification_functions, + include_resource_info, + include_subscriptions, + } + } + + #[instrument( + name = "dal_summary_generator.component.generate" + level = "info", + skip_all, + fields( + %self.include_action_functions, + %self.include_diff_status, + %self.include_execution_history, + %self.include_management_functions, + %self.include_manages, + %self.include_qualification_functions, + %self.include_resource_info, + %self.include_subscriptions, + count_action_lookup = Empty, + count_components = %component_ids.len(), + count_current_change_set_actions = Empty, + count_head_actions = Empty, + duration_ms_diff_status = Empty, + duration_ms_execution_history = Empty, + duration_ms_functions = Empty, + duration_ms_manages = Empty, + duration_ms_resource_info = Empty, + duration_ms_subscriptions = Empty, + duration_ms_summary = Empty, + ) + )] + pub async fn generate( + &self, + ctx: &DalContext, + head_ctx: &DalContext, + component_ids: &[ComponentId], + ) -> Result, super::Error> { + let span = current_span_for_instrument_at!("info"); + let start_time = Instant::now(); + + let mut component_summaries: BTreeMap = BTreeMap::new(); + + // Initialize component summaries with basic info + for component_id in component_ids { + let component = Component::get_by_id(ctx, *component_id).await?; + let component_name = component.name(ctx).await?; + let schema_name = component.schema(ctx).await?.name; + let component_id_str = component_id.to_string(); + + component_summaries.insert( + component_id_str, + ComponentSummary { + component_name, + schema_name, + has_resource: None, + resource_id: None, + resource_status: None, + has_diff: None, + diff_status: None, + subscriptions: Vec::new(), + manages: Vec::new(), + action_functions: Vec::new(), + management_functions: Vec::new(), + qualification_functions: Vec::new(), + }, + ); + } + + // Add resource information if requested + if self.include_resource_info { + let resource_start = Instant::now(); + for component_id in component_ids { + let component = Component::get_by_id(ctx, *component_id).await?; + let resource_data = component.resource(ctx).await?; + let resource_id = component.resource_id(ctx).await?; + + if let Some(summary) = component_summaries.get_mut(&component_id.to_string()) { + summary.has_resource = Some(resource_data.is_some()); + summary.resource_id = if resource_id.is_empty() { + None + } else { + Some(resource_id) + }; + summary.resource_status = resource_data.map(|r| { + let status = r.status; + format!("{status:?}") + }); + } + } + span.record( + "duration_ms_resource_info", + resource_start.elapsed().as_millis(), + ); + } + + // Add diff status information if requested + if self.include_diff_status { + let diff_start = Instant::now(); + + for component_id in component_ids { + let exists_in_head = Component::exists_by_id(head_ctx, *component_id).await?; + let exists_in_changeset = Component::exists_by_id(ctx, *component_id).await?; + + let (has_diff, diff_status) = if !exists_in_head && exists_in_changeset { + (true, "Added") + } else if exists_in_head && !exists_in_changeset { + (true, "Removed") + } else if exists_in_head && exists_in_changeset { + let has_changes = + Self::has_meaningful_component_changes(ctx, head_ctx, *component_id) + .await?; + (has_changes, if has_changes { "Modified" } else { "None" }) + } else { + (false, "None") + }; + + if let Some(summary) = component_summaries.get_mut(&component_id.to_string()) { + summary.has_diff = Some(has_diff); + summary.diff_status = Some(diff_status.to_string()); + } + } + span.record("duration_ms_diff_status", diff_start.elapsed().as_millis()); + } + + // Add subscription relationships if requested + if self.include_subscriptions { + let subscriptions_start = Instant::now(); + + let diagram = Diagram::assemble(ctx, None).await?; + + for edge in &diagram.attribute_subscription_edges { + let to_name = Component::name_by_id(ctx, edge.to_component_id).await?; + let current_value = AttributeValue::view(ctx, edge.to_attribute_value_id).await?; + + let from_component_str = edge.from_component_id.to_string(); + if let Some(summary) = component_summaries.get_mut(&from_component_str) { + summary.subscriptions.push(SubscriptionRelationship { + to_component_id: edge.to_component_id, + to_component_name: to_name, + from_path: edge.from_attribute_path.clone(), + to_path: edge.to_attribute_path.clone(), + current_value, + }); + } + } + span.record( + "duration_ms_subscriptions", + subscriptions_start.elapsed().as_millis(), + ); + } + + // Add management relationships if requested + if self.include_manages { + let manages_start = Instant::now(); + + for component_id in component_ids { + let component = Component::get_by_id(ctx, *component_id).await?; + let managed_components = component.get_managed(ctx).await?; + + for managed_id in managed_components { + let to_name = Component::name_by_id(ctx, managed_id).await?; + let from_component_str = component_id.to_string(); + + if let Some(summary) = component_summaries.get_mut(&from_component_str) { + summary.manages.push(ManagementRelationship { + to_component_id: managed_id, + to_component_name: to_name, + }); + } + } + } + span.record("duration_ms_manages", manages_start.elapsed().as_millis()); + } + + let mut execution_histories = ExecutionHistories::default(); + if self.include_execution_history { + let execution_history_start = Instant::now(); + execution_histories + .populate( + ctx, + head_ctx, + self.include_action_functions, + self.include_management_functions, + self.include_qualification_functions, + ) + .await?; + span.record( + "duration_ms_execution_history", + execution_history_start.elapsed().as_millis(), + ); + } + let action_history_map = execution_histories.action_history_map; + let management_history_map = execution_histories.management_history_map; + let qualification_history_map = execution_histories.qualification_history_map; + + // Add function relationships based on specific parameters + let need_any_functions = self.include_action_functions + || self.include_management_functions + || self.include_qualification_functions; + if need_any_functions { + let functions_start = Instant::now(); + + // Build UNIFIED action lookup: HEAD executions + current changeset scheduled/on-hold + let mut action_lookup: HashMap< + (ComponentId, dal::ActionPrototypeId), + (ActionState, Option, si_id::ActionId), + > = HashMap::new(); + + // Build action dependency graph to get dependencies + let action_dependency_graph = ActionDependencyGraph::for_workspace(ctx).await?; + + // Phase 1: Get scheduled/on-hold actions from current changeset + let mut current_change_set_actions = Vec::new(); + for component_id in component_ids { + if let Ok(actions) = Action::find_for_component_id(ctx, *component_id).await { + current_change_set_actions.extend(actions); + } + } + span.record( + "count_current_change_set_actions", + current_change_set_actions.len(), + ); + + for action_id in current_change_set_actions { + if let (Ok(Some(comp_id)), Ok(proto_id), Ok(action)) = ( + Action::component_id(ctx, action_id).await, + Action::prototype_id(ctx, action_id).await, + Action::get_by_id(ctx, action_id).await, + ) { + let func_run_id = Action::last_func_run_id_for_id_opt(ctx, action_id).await?; + + action_lookup.insert( + (comp_id, proto_id), + (action.state(), func_run_id, action_id), + ); + } + } + + // Phase 2: Get executed actions from HEAD context (ONLY if no current action exists) + let current_change_set_id = ctx.change_set_id(); + let head_change_set_id = head_ctx.change_set_id(); + + if current_change_set_id != head_change_set_id { + let head_actions = Action::list_topologically(head_ctx).await?; + span.record("count_head_actions", head_actions.len()); + + for action_id in head_actions { + if let (Ok(Some(comp_id)), Ok(proto_id), Ok(action)) = ( + Action::component_id(head_ctx, action_id).await, + Action::prototype_id(head_ctx, action_id).await, + Action::get_by_id(head_ctx, action_id).await, + ) { + // Only add HEAD actions if we don't already have a current action for this component+prototype + if let std::collections::hash_map::Entry::Vacant(e) = + action_lookup.entry((comp_id, proto_id)) + { + let func_run_id = + Action::last_func_run_id_for_id_opt(head_ctx, action_id).await?; + e.insert((action.state(), func_run_id, action_id)); + } + } + } + } + + span.record("count_action_lookup", action_lookup.len()); + + // Process each component to add function data + for component_id in component_ids { + if let Some(summary) = component_summaries.get_mut(&component_id.to_string()) { + let component = Component::get_by_id(ctx, *component_id).await?; + + // Add action functions with REAL status + if self.include_action_functions { + // Get all action prototypes for this component's schema variant + let schema_variant = component.schema_variant(ctx).await?; + let schema_variant_id = schema_variant.id(); + + // Get action prototypes from the schema variant + if let Ok(action_prototypes) = + ActionPrototype::for_variant(ctx, schema_variant_id).await + { + for prototype in action_prototypes { + let key = (*component_id, prototype.id()); + + // Check if there's an actual action scheduled for this function + if let Some((state, func_run_id, action_id)) = + action_lookup.get(&key) + { + // There's a real action scheduled + let execution_history = if self.include_execution_history { + action_history_map + .get(&key) + .cloned() + .unwrap_or_else(Vec::new) + } else { + Vec::new() + }; + + let depends_on: Vec = action_dependency_graph + .direct_dependencies_of(*action_id) + .into_iter() + .collect(); + + let execution_status = Some(FunctionExecutionStatus { + state: format!("{state:?}"), + has_active_run: *state == ActionState::Running + || *state == ActionState::Dispatched, + func_run_id: *func_run_id, + action_id: Some(*action_id), + }); + + summary.action_functions.push(FunctionRelationship { + function_name: prototype.name.clone(), + execution_status, + depends_on, + execution_history, + }); + } else { + // No action scheduled - show as Idle + let execution_history = if self.include_execution_history { + action_history_map + .get(&key) + .cloned() + .unwrap_or_else(Vec::new) + } else { + Vec::new() + }; + + let execution_status = Some(FunctionExecutionStatus { + state: "Idle".to_string(), + has_active_run: false, + func_run_id: None, + action_id: None, + }); + + summary.action_functions.push(FunctionRelationship { + function_name: prototype.name.clone(), + execution_status, + depends_on: Vec::new(), + execution_history, + }); + } + } + } + } + + // Add management functions with execution state + if self.include_management_functions { + // Get management prototypes from the schema variant + let schema_variant = component.schema_variant(ctx).await?; + let schema_variant_id = schema_variant.id(); + + if let Ok(mgmt_prototypes) = + dal::management::prototype::ManagementPrototype::list_for_variant_id( + ctx, + schema_variant_id, + ) + .await + { + for mgmt_prototype in mgmt_prototypes { + // Get execution history for this management function + let execution_history = if self.include_execution_history { + management_history_map + .get(&(*component_id, mgmt_prototype.id())) + .cloned() + .unwrap_or_else(Vec::new) + } else { + Vec::new() + }; + + // Determine execution status based on most recent job state + let execution_status = if !execution_history.is_empty() { + let most_recent = &execution_history[0]; // Already sorted by most recent first + Some(FunctionExecutionStatus { + state: match most_recent.state.as_str() { + "success" => "Succeeded".to_string(), + "failure" => "Failed".to_string(), + "running" => "Running".to_string(), + _ => most_recent.state.clone(), + }, + has_active_run: most_recent.state == "running", + func_run_id: Some(most_recent.func_run_id), + action_id: None, + }) + } else { + Some(FunctionExecutionStatus { + state: "Available".to_string(), + has_active_run: false, + func_run_id: None, + action_id: None, + }) + }; + + summary.management_functions.push(FunctionRelationship { + function_name: mgmt_prototype.name.clone(), + execution_status, + depends_on: Vec::new(), // Management functions don't have action dependencies + execution_history, + }); + } + } + } + + // Add qualification functions with REAL status + if self.include_qualification_functions { + let qualification_avs = + Component::list_qualification_avs(ctx, *component_id).await?; + + for qualification_av in &qualification_avs { + if let Ok(Some(qualification)) = + dal::qualification::QualificationView::new( + ctx, + qualification_av.id(), + ) + .await + { + let qual_func_run = ctx + .layer_db() + .func_run() + .get_last_qualification_for_attribute_value_id( + ctx.events_tenancy().workspace_pk, + qualification_av.id(), + ) + .await?; + + let func_run_id = qual_func_run.as_ref().map(|run| run.id()); + + let execution_status = if qualification.finalized { + if let Some(result) = &qualification.result { + match result.status { + dal::qualification::QualificationSubCheckStatus::Success => { + Some(FunctionExecutionStatus{ + state: "Succeeded".to_string(), + has_active_run: false, + func_run_id, + action_id: None, + }) + } + dal::qualification::QualificationSubCheckStatus::Failure => { + Some(FunctionExecutionStatus { + state: "Failed".to_string(), + has_active_run: false, + func_run_id, + action_id: None, + }) + } + dal::qualification::QualificationSubCheckStatus::Warning => { + Some(FunctionExecutionStatus{ + state: "Warning".to_string(), + has_active_run: false, + func_run_id, + action_id: None, + }) + } + _ => { + Some(FunctionExecutionStatus{ + state: "Completed".to_string(), + has_active_run: false, + func_run_id, + action_id: None, + }) + } + } + } else { + Some(FunctionExecutionStatus { + state: "Completed".to_string(), + has_active_run: false, + func_run_id, + action_id: None, + }) + } + } else { + Some(FunctionExecutionStatus { + state: "Running".to_string(), + has_active_run: true, + func_run_id, + action_id: None, + }) + }; + + // Get execution history for this qualification function + let execution_history = if self.include_execution_history { + qualification_history_map + .get(&(*component_id, qualification_av.id())) + .cloned() + .unwrap_or_else(Vec::new) + } else { + Vec::new() + }; + + summary.qualification_functions.push(FunctionRelationship { + function_name: qualification.qualification_name, + execution_status, + depends_on: Vec::new(), // Qualification functions don't have action dependencies + execution_history, + }); + } + } + } + } + } + + span.record( + "duration_ms_functions", + functions_start.elapsed().as_millis(), + ); + } + + // Record the overall duration! + span.record("duration_ms_summary", start_time.elapsed().as_millis()); + + Ok(component_summaries) + } + + // Hash-based component diff check + async fn has_meaningful_component_changes( + ctx: &DalContext, + head_ctx: &DalContext, + component_id: ComponentId, + ) -> Result { + use std::collections::hash_map::DefaultHasher; + + let exists_in_changeset = Component::exists_by_id(ctx, component_id).await?; + let exists_in_head = Component::exists_by_id(head_ctx, component_id).await?; + + if exists_in_changeset != exists_in_head { + return Ok(true); + } + + if !exists_in_changeset { + return Ok(false); + } + + // Calculate hash of all component attributes in changeset + let changeset_hash = { + let mut hasher = DefaultHasher::new(); + if let Some(view) = Component::view_by_id(ctx, component_id).await? { + if let Ok(props) = ComponentProperties::try_from(view) { + if let Ok(json_str) = serde_json::to_string(&props) { + json_str.hash(&mut hasher); + } + } + } + if let Ok(action_ids) = Action::find_for_component_id(ctx, component_id).await { + for action_id in action_ids { + if let Ok(action) = Action::get_by_id(ctx, action_id).await { + action.state().hash(&mut hasher); + if let Ok(proto_id) = Action::prototype_id(ctx, action_id).await { + proto_id.hash(&mut hasher); + } + } + } + } + hasher.finish() + }; + + // Calculate hash of all component attributes in HEAD + let head_hash = { + let mut hasher = DefaultHasher::new(); + if let Some(view) = Component::view_by_id(head_ctx, component_id).await? { + if let Ok(props) = ComponentProperties::try_from(view) { + if let Ok(json_str) = serde_json::to_string(&props) { + json_str.hash(&mut hasher); + } + } + } + if let Ok(action_ids) = Action::find_for_component_id(head_ctx, component_id).await { + for action_id in action_ids { + if let Ok(action) = Action::get_by_id(head_ctx, action_id).await { + action.state().hash(&mut hasher); + if let Ok(proto_id) = Action::prototype_id(head_ctx, action_id).await { + proto_id.hash(&mut hasher); + } + } + } + } + hasher.finish() + }; + + Ok(changeset_hash != head_hash) + } +} diff --git a/lib/dal-summary-generator/src/component_summary/execution_histories.rs b/lib/dal-summary-generator/src/component_summary/execution_histories.rs new file mode 100644 index 0000000000..6a140d8da4 --- /dev/null +++ b/lib/dal-summary-generator/src/component_summary/execution_histories.rs @@ -0,0 +1,286 @@ +use std::collections::HashMap; + +use dal::{ + AttributeValueId, + ComponentId, + DalContext, + action::{ + Action, + prototype::ActionPrototype, + }, +}; +use si_events::{ + ActionKind, + ActionResultState, + FuncRun, + FuncRunState, +}; +use si_id::ManagementPrototypeId; +use telemetry::prelude::*; + +use super::ExecutionHistoryEntry; + +#[derive(Default, Debug)] +pub(crate) struct ExecutionHistories { + pub(crate) action_history_map: + HashMap<(ComponentId, dal::ActionPrototypeId), Vec>, + pub(crate) management_history_map: + HashMap<(ComponentId, ManagementPrototypeId), Vec>, + pub(crate) qualification_history_map: + HashMap<(ComponentId, AttributeValueId), Vec>, +} + +impl ExecutionHistories { + #[instrument( + name = "dal_summary_generator.component.execution_histories.populate" + level = "info", + skip_all, + fields( + %include_action_functions, + %include_management_functions, + %include_qualification_functions, + head_action_runs_count = Empty, + refresh_action_runs_count = Empty, + action_history_map_len = Empty + ) + )] + pub(crate) async fn populate( + &mut self, + ctx: &DalContext, + head_ctx: &DalContext, + include_action_functions: bool, + include_management_functions: bool, + include_qualification_functions: bool, + ) -> Result<(), crate::Error> { + let span = current_span_for_instrument_at!("info"); + + let workspace_pk = ctx.tenancy().workspace_pk().unwrap_or_default(); + + // Build action execution history using DUAL CONTEXT approach + if include_action_functions { + // Create HEAD context for regular action history (Create/Update/Delete) + let head_workspace_pk = head_ctx.tenancy().workspace_pk().unwrap_or_default(); + + // Phase 1: Get regular action func runs from HEAD context (excludes refresh) + if let Ok(Some(all_func_runs)) = head_ctx + .layer_db() + .func_run() + .read_many_for_workspace(head_workspace_pk) + .await + { + let head_action_runs: Vec<_> = all_func_runs + .into_iter() + .filter(|fr| fr.function_kind() == si_events::FuncKind::Action) + .take(500) + .collect(); + + span.record("head_action_runs_count", head_action_runs.len()); + + for func_run in head_action_runs { + if let Some(action_id) = func_run.action_id() { + if let (Ok(Some(comp_id)), Ok(proto_id)) = ( + Action::component_id(head_ctx, action_id).await, + Action::prototype_id(head_ctx, action_id).await, + ) { + let result_state = Self::get_action_result_from_func_run(&func_run); + + let entry = ExecutionHistoryEntry { + func_run_id: func_run.id(), + state: result_state, + started_at: func_run.created_at(), + }; + + self.action_history_map + .entry((comp_id, proto_id)) + .or_default() + .push(entry); + } + } + } + } + + // Phase 2: Get refresh action history from CURRENT context (refresh can run on changesets) + if let Ok(Some(current_func_runs)) = ctx + .layer_db() + .func_run() + .read_many_for_workspace(workspace_pk) + .await + { + let refresh_action_runs: Vec<_> = current_func_runs + .into_iter() + .filter(|fr| fr.function_kind() == si_events::FuncKind::Action) + .take(500) + .collect(); + + span.record("refresh_action_runs_count", refresh_action_runs.len()); + + for func_run in refresh_action_runs { + if let Some(action_id) = func_run.action_id() { + // Check if this is a refresh action by trying current context first + if let (Ok(Some(comp_id)), Ok(proto_id)) = ( + Action::component_id(ctx, action_id).await, + Action::prototype_id(ctx, action_id).await, + ) { + // Get the action prototype to check if it's a refresh action + if let Ok(prototype) = ActionPrototype::get_by_id(ctx, proto_id).await { + if ActionKind::Refresh == prototype.kind.into() { + let result_state = + Self::get_action_result_from_func_run(&func_run); + + let entry = ExecutionHistoryEntry { + func_run_id: func_run.id(), + state: result_state, + started_at: func_run.created_at(), + }; + + self.action_history_map + .entry((comp_id, proto_id)) + .or_default() + .push(entry); + } + } + } + } + } + } + + span.record("action_history_map_len", self.action_history_map.len()); + } + + // Build qualification execution history by parsing actual output logs + if include_qualification_functions { + if let Ok(Some(all_func_runs)) = ctx + .layer_db() + .func_run() + .read_many_for_workspace(workspace_pk) + .await + { + let qual_func_runs: Vec<_> = all_func_runs + .into_iter() + .filter(|fr| fr.function_kind() == si_events::FuncKind::Qualification) + .take(500) + .collect(); + + for func_run in qual_func_runs { + if let (Some(comp_id), Some(av_id)) = + (func_run.component_id(), func_run.attribute_value_id()) + { + // Parse the actual qualification result from func_run logs + let state = if let Ok(Some(func_run_log)) = ctx + .layer_db() + .func_run_log() + .get_for_func_run_id(func_run.id()) + .await + { + let func_run_log = + std::sync::Arc::::unwrap_or_clone( + func_run_log, + ); + + // Look for output logs that contain the qualification result + let mut result_state = None; + for log_entry in func_run_log.logs() { + if log_entry.stream == "output" { + // Remove "Output: " prefix if present + let json_str = if log_entry.message.starts_with("Output: ") { + &log_entry.message[8..] // Skip "Output: " + } else { + &log_entry.message + }; + + if let Ok(output_value) = + serde_json::from_str::(json_str) + { + // Check direct status field (new format) + if let Some(status) = output_value.get("status") { + if let Some(status_str) = status.as_str() { + result_state = Some(match status_str { + "success" => "Succeeded".to_string(), + "failure" => "Failed".to_string(), + "warning" => "Warning".to_string(), + _ => "Completed".to_string(), + }); + break; + } + } + // Fallback: check old format (data.result) + else if let Some(data) = output_value.get("data") { + if let Some(result) = data.get("result") { + if let Some(result_str) = result.as_str() { + result_state = Some(match result_str { + "success" => "Succeeded".to_string(), + "failure" => "Failed".to_string(), + "warning" => "Warning".to_string(), + _ => "Completed".to_string(), + }); + break; + } + } + } + } + } + } + + // Use parsed result or fall back to function execution state + result_state.unwrap_or_else(|| match func_run.state() { + si_events::FuncRunState::Success => "Succeeded".to_string(), + si_events::FuncRunState::Failure => "Failed".to_string(), + _ => { + let state = func_run.state(); + format!("{state:?}") + } + }) + } else { + // No logs available, use function execution state + match func_run.state() { + si_events::FuncRunState::Success => "Succeeded".to_string(), + si_events::FuncRunState::Failure => "Failed".to_string(), + _ => { + let state = func_run.state(); + format!("{state:?}") + } + } + }; + + let entry = ExecutionHistoryEntry { + func_run_id: func_run.id(), + state, + started_at: func_run.created_at(), + }; + + self.qualification_history_map + .entry((comp_id, av_id)) + .or_default() + .push(entry); + } + } + } + + // Sort and limit qualification history + for history in self.qualification_history_map.values_mut() { + history.sort_by(|a, b| b.started_at.cmp(&a.started_at)); + history.truncate(10); + } + } + + Ok(()) + } + + // Helper function for action execution status + fn get_action_result_from_func_run(func_run: &FuncRun) -> String { + if func_run.state() == FuncRunState::Failure { + return "Failed".to_string(); + } + + match func_run.action_result_state() { + Some(ActionResultState::Success) => "Succeeded".to_string(), + Some(ActionResultState::Failure) => "Failed".to_string(), + Some(ActionResultState::Unknown) => "Unknown".to_string(), + None => match func_run.state() { + FuncRunState::Success => "Succeeded".to_string(), + FuncRunState::Failure => "Failed".to_string(), + _ => "Idle".to_string(), + }, + } + } +} diff --git a/lib/dal-summary-generator/src/lib.rs b/lib/dal-summary-generator/src/lib.rs new file mode 100644 index 0000000000..f5ae94cfe7 --- /dev/null +++ b/lib/dal-summary-generator/src/lib.rs @@ -0,0 +1,54 @@ +//! This is a DAL-wrapper crate for functions used for solely "graph lab". + +#![warn( + bad_style, + clippy::missing_panics_doc, + clippy::panic, + clippy::panic_in_result_fn, + clippy::unwrap_in_result, + clippy::unwrap_used, + dead_code, + improper_ctypes, + missing_debug_implementations, + // TODO(nick): enable this and add docs. + // missing_docs, + no_mangle_generic_items, + non_shorthand_field_patterns, + overflowing_literals, + path_statements, + patterns_in_fns_without_body, + unconditional_recursion, + unreachable_pub, + unused, + unused_allocation, + unused_comparisons, + unused_parens, + while_true +)] + +use dal::{ + ComponentError, + action::ActionError, + attribute::value::AttributeValueError, + diagram::DiagramError, +}; +use si_layer_cache::LayerDbError; + +mod component_summary; + +pub use component_summary::*; + +#[remain::sorted] +#[derive(Debug, thiserror::Error)] +pub enum Error { + #[error("action error: {0}")] + Action(#[from] ActionError), + #[error("attribute value error: {0}")] + AttributeValue(#[from] AttributeValueError), + #[error("component error: {0}")] + Component(#[from] ComponentError), + #[error("diagram error: {0}")] + Diagram(#[from] DiagramError), + #[error("layer db error: {0}")] + LayerDb(#[from] LayerDbError), +} diff --git a/lib/dal/BUCK b/lib/dal/BUCK index 98b7ddc416..58f67aa705 100644 --- a/lib/dal/BUCK +++ b/lib/dal/BUCK @@ -95,6 +95,7 @@ rust_test( "//lib/audit-database:audit-database", "//lib/audit-logs-stream:audit-logs-stream", "//lib/dal-materialized-views:dal-materialized-views", + "//lib/dal-summary-generator:dal-summary-generator", "//lib/dal-test:dal-test", "//lib/pending-events:pending-events", "//lib/rebaser-server:rebaser-server", diff --git a/lib/dal/Cargo.toml b/lib/dal/Cargo.toml index 0f92fac4e1..f4e2303cdc 100644 --- a/lib/dal/Cargo.toml +++ b/lib/dal/Cargo.toml @@ -78,6 +78,7 @@ veritech-client = { path = "../../lib/veritech-client" } [dev-dependencies] dal-materialized-views = { path = "../../lib/dal-materialized-views" } +dal-summary-generator = { path = "../../lib/dal-summary-generator" } dal-test = { path = "../../lib/dal-test" } derive_more = { workspace = true } pretty_assertions_sorted = { workspace = true } diff --git a/lib/dal/src/diagram.rs b/lib/dal/src/diagram.rs index 555ef70584..b0cbb808a5 100644 --- a/lib/dal/src/diagram.rs +++ b/lib/dal/src/diagram.rs @@ -35,6 +35,7 @@ use si_id::{ use si_layer_cache::LayerDbError; use telemetry::prelude::*; use thiserror::Error; +use tokio::time::Instant; use crate::{ AttributePrototype, @@ -382,7 +383,6 @@ pub struct DiagramComponentViews { } impl Diagram { - #[instrument(level = "info", skip_all)] async fn assemble_component_views( ctx: &DalContext, base_snapshot: &WorkspaceSnapshotSelector, @@ -511,7 +511,6 @@ impl Diagram { .collect() } - #[instrument(level = "info", skip_all)] async fn get_base_snapshot( ctx: &DalContext, ) -> DiagramResult<(WorkspaceSnapshotSelector, bool)> { @@ -553,7 +552,6 @@ impl Diagram { } } - #[instrument(level = "info", skip_all)] async fn assemble_removed_components( ctx: &DalContext, base_snapshot: WorkspaceSnapshotSelector, @@ -622,7 +620,6 @@ impl Diagram { /// not in this changeset, we can ignore the deleted edge, since we won't /// render it. If the components are restored from the base, the edge will /// *magically* reappear as deleted. - #[instrument(level = "info", skip_all)] async fn assemble_removed_management_edges( ctx: &DalContext, base_snapshot: &WorkspaceSnapshotSelector, @@ -684,26 +681,21 @@ impl Diagram { Ok(removed_edges) } - /// If a subscription is in the base snapshot, but not in the current - /// snapshot, that means it has been deleted. If one of the components is - /// not in this changeset, we can ignore the deleted edge, since we won't - /// render it. If the components are restored from the base, the edge will - /// *magically* reappear as deleted. - #[instrument(level = "info", skip_all)] - async fn assemble_removed_attribute_subscription_edges( - _ctx: &DalContext, - _base_snapshot: &WorkspaceSnapshotSelector, - ) -> DiagramResult> { - // TODO implement this - Ok(vec![]) - } - - /// Assemble a [`Diagram`](Self) based on existing [`Nodes`](crate::Node) and - /// [`Connections`](crate::Connection). - /// If passed a [ViewId], assemble it for that view only, otherwise, do it for the whole - /// graph. - #[instrument(level = "info", skip(ctx))] + #[instrument( + name = "diagram.assemble", + level = "info", + skip_all, + fields( + ?maybe_view_id, + duration_ms_get_base_snapshot = Empty, + duration_ms_assemble_component_views = Empty, + duration_ms_assemble_removed_components = Empty, + duration_ms_assemble_removed_management_edges = Empty + ) + )] pub async fn assemble(ctx: &DalContext, maybe_view_id: Option) -> DiagramResult { + let span = current_span_for_instrument_at!("info"); + let mut views = vec![]; let component_info_cache = { let mut map = HashMap::new(); @@ -756,8 +748,13 @@ impl Diagram { map }; + let start = Instant::now(); let (base_snapshot, not_on_head) = Self::get_base_snapshot(ctx).await?; + span.record("duration_ms_get_base_snapshot", start.elapsed().as_millis()); + let mut diagram_sockets = HashMap::new(); + + let start = Instant::now(); let mut diagram_component_views = Self::assemble_component_views( ctx, &base_snapshot, @@ -765,8 +762,13 @@ impl Diagram { &mut diagram_sockets, ) .await?; + span.record( + "duration_ms_assemble_component_views", + start.elapsed().as_millis(), + ); if not_on_head { + let start = Instant::now(); let removed_component_summaries = Self::assemble_removed_components( ctx, base_snapshot.clone(), @@ -774,20 +776,26 @@ impl Diagram { &mut diagram_sockets, ) .await?; + span.record( + "duration_ms_assemble_removed_components", + start.elapsed().as_millis(), + ); + diagram_component_views .component_views .extend(removed_component_summaries); + let start = Instant::now(); let removed_management_edges = Self::assemble_removed_management_edges(ctx, &base_snapshot).await?; + span.record( + "duration_ms_assemble_removed_management_edges", + start.elapsed().as_millis(), + ); + diagram_component_views .management_edges .extend(removed_management_edges); - let removed_attribute_subscription_edges = - Self::assemble_removed_attribute_subscription_edges(ctx, &base_snapshot).await?; - diagram_component_views - .attribute_subscription_edges - .extend(removed_attribute_subscription_edges); } Ok(Self { diff --git a/lib/dal/tests/integration_test/mod.rs b/lib/dal/tests/integration_test/mod.rs index 6cb50bb6dc..f68a3df10a 100644 --- a/lib/dal/tests/integration_test/mod.rs +++ b/lib/dal/tests/integration_test/mod.rs @@ -28,6 +28,7 @@ mod resource_metadata; mod schema; mod secret; mod split_snapshot; +mod summary_generator; mod validations; mod view; mod workspace; diff --git a/lib/dal/tests/integration_test/summary_generator.rs b/lib/dal/tests/integration_test/summary_generator.rs new file mode 100644 index 0000000000..e3dc71165b --- /dev/null +++ b/lib/dal/tests/integration_test/summary_generator.rs @@ -0,0 +1,225 @@ +use dal::DalContext; +use dal_summary_generator::ComponentSummaryGenerator; +use dal_test::{ + Result, + helpers::{ + ChangeSetTestHelpers, + attribute::value, + component, + schema::variant, + }, + test, +}; +use pretty_assertions_sorted::assert_eq; +use serde_json::json; + +#[test] +async fn generate_component_summaries(ctx: &mut DalContext) -> Result<()> { + // Create three variants for a subscription daisy chain. + variant::create( + ctx, + "source-component", + r#" + function main() { + return { + props: [ + { name: "output", kind: "string" }, + ] + }; + } + "#, + ) + .await?; + variant::create( + ctx, + "target-component", + r#" + function main() { + return { + props: [ + { name: "input", kind: "string" }, + ] + }; + } + "#, + ) + .await?; + variant::create( + ctx, + "middle-component", + r#" + function main() { + return { + props: [ + { name: "passthrough", kind: "string" }, + ] + }; + } + "#, + ) + .await?; + + // Create a component for each variant. + let source_id = component::create(ctx, "source-component", "source").await?; + let middle_id = component::create(ctx, "middle-component", "middle").await?; + let target_id = component::create(ctx, "target-component", "target").await?; + + // Set a value on the source component. + value::set(ctx, ("source", "/domain/output"), "toddhoward").await?; + + // Set up subscriptions: middle subscribes to source and target subscribes to middle. After that, commit. + value::subscribe( + ctx, + ("middle", "/domain/passthrough"), + ("source", "/domain/output"), + ) + .await?; + value::subscribe( + ctx, + ("target", "/domain/input"), + ("middle", "/domain/passthrough"), + ) + .await?; + ChangeSetTestHelpers::commit_and_update_snapshot_to_visibility(ctx).await?; + + // Verify that the subscriptions worked. + assert_eq!( + json!("toddhoward"), + value::get(ctx, ("middle", "/domain/passthrough")).await? + ); + assert_eq!( + json!("toddhoward"), + value::get(ctx, ("target", "/domain/input")).await? + ); + + // Create components from existing test schemas that have actions and commit. + let component_one_id = component::create(ctx, "swifty", "component_one").await?; + let component_two_id = component::create(ctx, "swifty", "component_two").await?; + ChangeSetTestHelpers::commit_and_update_snapshot_to_visibility(ctx).await?; + + // Now we can apply! + ChangeSetTestHelpers::apply_change_set_to_base(ctx).await?; + ChangeSetTestHelpers::wait_for_actions_to_run(ctx).await?; + + // Cache the HEAD context before creating a new one. We need both. + let head_ctx = ctx.clone(); + ChangeSetTestHelpers::fork_from_head_change_set(ctx).await?; + + // Add two more components in the new change set and commit. + let component_three_id = component::create(ctx, "swifty", "component_three").await?; + let component_four_id = component::create(ctx, "swifty", "component_four").await?; + ChangeSetTestHelpers::commit_and_update_snapshot_to_visibility(ctx).await?; + + // Call the generate function with all flags enabled. + let generator = ComponentSummaryGenerator::new(true, true, true, true, true, true, true, true); + let summaries = generator + .generate( + ctx, + &head_ctx, + &[ + source_id, + middle_id, + target_id, + component_one_id, + component_two_id, + component_three_id, + component_four_id, + ], + ) + .await?; + assert_eq!(7, summaries.len()); + + // Fetch all sumaries. + let source_summary = summaries + .get(&source_id.to_string()) + .expect("source component summary not found"); + let middle_summary = summaries + .get(&middle_id.to_string()) + .expect("middle component summary not found"); + let target_summary = summaries + .get(&target_id.to_string()) + .expect("target component summary not found"); + let component_one_summary = summaries + .get(&component_one_id.to_string()) + .expect("component_one summary not found"); + let component_two_summary = summaries + .get(&component_two_id.to_string()) + .expect("component_two summary not found"); + let component_three_summary = summaries + .get(&component_three_id.to_string()) + .expect("component_three summary not found"); + let component_four_summary = summaries + .get(&component_four_id.to_string()) + .expect("component_four summary not found"); + dbg!( + "relevant summaries found", + &source_summary, + &middle_summary, + &target_summary, + &component_one_summary, + &component_two_summary, + &component_three_summary, + &component_four_summary, + ); + + // Verify the source component summary - middle subscribes to source + assert_eq!("source", source_summary.component_name); + assert_eq!("source-component", source_summary.schema_name); + assert_eq!(1, source_summary.subscriptions.len()); + let source_sub = &source_summary.subscriptions[0]; + assert_eq!(middle_id, source_sub.to_component_id); + assert_eq!("middle", source_sub.to_component_name); + assert!(source_sub.from_path.contains("output")); + assert!(source_sub.to_path.contains("passthrough")); + assert_eq!(Some(json!("toddhoward")), source_sub.current_value); + + // Verify the middle component summary - target subscribes to middle + assert_eq!("middle", middle_summary.component_name); + assert_eq!("middle-component", middle_summary.schema_name); + assert_eq!(1, middle_summary.subscriptions.len()); + let middle_sub = &middle_summary.subscriptions[0]; + assert_eq!(target_id, middle_sub.to_component_id); + assert_eq!("target", middle_sub.to_component_name); + assert!(middle_sub.from_path.contains("passthrough")); + assert!(middle_sub.to_path.contains("input")); + assert_eq!(Some(json!("toddhoward")), middle_sub.current_value); + + // Verify the target component summary - no one subscribes to target + assert_eq!("target", target_summary.component_name); + assert_eq!("target-component", target_summary.schema_name); + assert_eq!(0, target_summary.subscriptions.len()); + + // Verify component_one has action functions + assert_eq!("component_one", component_one_summary.component_name); + assert_eq!("swifty", component_one_summary.schema_name); + assert!( + !component_one_summary.action_functions.is_empty(), + "component_one should have action functions" + ); + + // Verify component_two has action functions + assert_eq!("component_two", component_two_summary.component_name); + assert_eq!("swifty", component_two_summary.schema_name); + assert!( + !component_two_summary.action_functions.is_empty(), + "component_two should have action functions" + ); + + // Verify component_three has action functions + assert_eq!("component_three", component_three_summary.component_name); + assert_eq!("swifty", component_three_summary.schema_name); + assert!( + !component_three_summary.action_functions.is_empty(), + "component_three should have action functions" + ); + + // Verify component_four has action functions + assert_eq!("component_four", component_four_summary.component_name); + assert_eq!("swifty", component_four_summary.schema_name); + assert!( + !component_four_summary.action_functions.is_empty(), + "component_four should have action functions" + ); + + Ok(()) +} diff --git a/lib/luminork-server/BUCK b/lib/luminork-server/BUCK index c22aa652c8..d7884d5346 100644 --- a/lib/luminork-server/BUCK +++ b/lib/luminork-server/BUCK @@ -7,6 +7,7 @@ rust_library( "//lib/buck2-resources:buck2-resources", "//lib/dal:dal", "//lib/dal-materialized-views:dal-materialized-views", + "//lib/dal-summary-generator:dal-summary-generator", "//lib/si-db:si-db", "//lib/edda-client:edda-client", "//lib/edda-core:edda-core", diff --git a/lib/luminork-server/Cargo.toml b/lib/luminork-server/Cargo.toml index 1127edb109..b0478722e1 100644 --- a/lib/luminork-server/Cargo.toml +++ b/lib/luminork-server/Cargo.toml @@ -16,6 +16,7 @@ buck2-resources = { path = "../../lib/buck2-resources" } chrono = { workspace = true } dal = { path = "../../lib/dal" } dal-materialized-views = { path = "../../lib/dal-materialized-views" } +dal-summary-generator = { path = "../../lib/dal-summary-generator" } derive_builder = { workspace = true } edda-client = { path = "../../lib/edda-client" } edda-core = { path = "../../lib/edda-core" } diff --git a/lib/luminork-server/src/service/v1/components/list_components.rs b/lib/luminork-server/src/service/v1/components/list_components.rs index b5870d18cd..cf0d5789bd 100644 --- a/lib/luminork-server/src/service/v1/components/list_components.rs +++ b/lib/luminork-server/src/service/v1/components/list_components.rs @@ -1,12 +1,3 @@ -use std::{ - collections::HashMap, - hash::{ - Hash, - Hasher, - }, - time::Instant, -}; - use axum::{ extract::Query, response::Json, @@ -15,26 +6,14 @@ use dal::{ AttributeValue, Component, ComponentId, - action::{ - Action, - dependency_graph::ActionDependencyGraph, - prototype::{ - ActionKind, - ActionPrototype, - }, - }, - attribute::value::AttributeValueId, - component::properties::ComponentProperties, - diagram::Diagram, + DalContext, }; +use dal_summary_generator::ComponentSummaryGenerator; use serde::Serialize; use serde_json::{ Value, json, }; -use si_events::ActionState; -use si_id::ManagementPrototypeId; -use telemetry::prelude::*; use utoipa::{ self, ToSchema, @@ -125,922 +104,6 @@ pub struct ComponentDetailsV1 { pub qualification_functions: Vec, } -// Graph summary data structures -#[derive(Serialize, Debug, Clone, ToSchema)] -#[serde(rename_all = "camelCase")] -pub struct SubscriptionRelationshipV1 { - #[schema(value_type = String)] - pub to_component_id: ComponentId, - pub to_component_name: String, - pub from_path: String, - pub to_path: String, - #[serde(skip_serializing_if = "Option::is_none")] - pub current_value: Option, -} - -#[derive(Serialize, Debug, Clone, ToSchema)] -#[serde(rename_all = "camelCase")] -pub struct ManagementRelationshipV1 { - #[schema(value_type = String)] - pub to_component_id: ComponentId, - pub to_component_name: String, -} - -#[derive(Serialize, Debug, Clone, ToSchema)] -#[serde(rename_all = "camelCase")] -pub struct FunctionRelationshipV1 { - pub function_name: String, - #[serde(skip_serializing_if = "Option::is_none")] - pub execution_status: Option, - #[serde(skip_serializing_if = "Vec::is_empty")] - #[schema(value_type = Vec)] - pub depends_on: Vec, - #[serde(skip_serializing_if = "Vec::is_empty")] - pub execution_history: Vec, -} - -#[derive(Serialize, Debug, Clone, ToSchema)] -#[serde(rename_all = "camelCase")] -pub struct FunctionExecutionStatusV1 { - pub state: String, - pub has_active_run: bool, - #[serde(skip_serializing_if = "Option::is_none")] - #[schema(value_type = Option)] - pub func_run_id: Option, - #[serde(skip_serializing_if = "Option::is_none")] - #[schema(value_type = Option)] - pub action_id: Option, -} - -#[derive(Serialize, Debug, Clone, ToSchema)] -#[serde(rename_all = "camelCase")] -pub struct ExecutionHistoryEntry { - #[schema(value_type = String)] - pub func_run_id: si_id::FuncRunId, - pub state: String, - #[schema(value_type = String, format = DateTime)] - pub started_at: chrono::DateTime, -} - -// Graph summary implementation - moved from graph module -#[derive(Serialize, Debug, Clone)] -#[serde(rename_all = "camelCase")] -pub struct ComponentSummaryV1 { - pub component_name: String, - pub schema_name: String, - #[serde(skip_serializing_if = "Option::is_none")] - pub has_resource: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub resource_id: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub resource_status: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub has_diff: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub diff_status: Option, - #[serde(skip_serializing_if = "Vec::is_empty")] - pub subscriptions: Vec, - #[serde(skip_serializing_if = "Vec::is_empty")] - pub manages: Vec, - #[serde(skip_serializing_if = "Vec::is_empty")] - pub action_functions: Vec, - #[serde(skip_serializing_if = "Vec::is_empty")] - pub management_functions: Vec, - #[serde(skip_serializing_if = "Vec::is_empty")] - pub qualification_functions: Vec, -} - -// Helper functions for action execution status -fn get_action_result_from_func_run(func_run: &si_events::FuncRun) -> String { - if func_run.state() == si_events::FuncRunState::Failure { - return "Failed".to_string(); - } - - match func_run.action_result_state() { - Some(si_events::ActionResultState::Success) => "Succeeded".to_string(), - Some(si_events::ActionResultState::Failure) => "Failed".to_string(), - Some(si_events::ActionResultState::Unknown) => "Unknown".to_string(), - None => match func_run.state() { - si_events::FuncRunState::Success => "Succeeded".to_string(), - si_events::FuncRunState::Failure => "Failed".to_string(), - _ => "Idle".to_string(), - }, - } -} - -// Hash-based component diff check -async fn has_meaningful_component_changes( - ctx: &dal::DalContext, - component_id: ComponentId, -) -> Result { - use std::collections::hash_map::DefaultHasher; - - let head_ctx = ctx.clone_with_head().await?; - let exists_in_changeset = Component::exists_by_id(ctx, component_id).await?; - let exists_in_head = Component::exists_by_id(&head_ctx, component_id).await?; - - if exists_in_changeset != exists_in_head { - return Ok(true); - } - - if !exists_in_changeset { - return Ok(false); - } - - // Calculate hash of all component attributes in changeset - let changeset_hash = { - let mut hasher = DefaultHasher::new(); - if let Some(view) = Component::view_by_id(ctx, component_id).await? { - if let Ok(props) = ComponentProperties::try_from(view) { - if let Ok(json_str) = serde_json::to_string(&props) { - json_str.hash(&mut hasher); - } - } - } - if let Ok(action_ids) = Action::find_for_component_id(ctx, component_id).await { - for action_id in action_ids { - if let Ok(action) = Action::get_by_id(ctx, action_id).await { - action.state().hash(&mut hasher); - if let Ok(proto_id) = Action::prototype_id(ctx, action_id).await { - proto_id.hash(&mut hasher); - } - } - } - } - hasher.finish() - }; - - // Calculate hash of all component attributes in HEAD - let head_hash = { - let mut hasher = DefaultHasher::new(); - if let Some(view) = Component::view_by_id(&head_ctx, component_id).await? { - if let Ok(props) = ComponentProperties::try_from(view) { - if let Ok(json_str) = serde_json::to_string(&props) { - json_str.hash(&mut hasher); - } - } - } - if let Ok(action_ids) = Action::find_for_component_id(&head_ctx, component_id).await { - for action_id in action_ids { - if let Ok(action) = Action::get_by_id(&head_ctx, action_id).await { - action.state().hash(&mut hasher); - if let Ok(proto_id) = Action::prototype_id(&head_ctx, action_id).await { - proto_id.hash(&mut hasher); - } - } - } - } - hasher.finish() - }; - - Ok(changeset_hash != head_hash) -} - -#[allow(clippy::too_many_arguments)] -async fn build_graph_summary( - ctx: &dal::DalContext, - include_subscriptions: bool, - include_manages: bool, - include_action_functions: bool, - include_management_functions: bool, - include_qualification_functions: bool, - include_resource_info: bool, - include_diff_status: bool, - include_execution_history: bool, -) -> Result, ComponentsError> { - let start_time = Instant::now(); - info!("Starting graph summary generation"); - - let component_ids = Component::list_ids(ctx).await?; - debug!("Found {} components for graph summary", component_ids.len()); - - let mut component_summaries: std::collections::BTreeMap = - std::collections::BTreeMap::new(); - - // Initialize component summaries with basic info - for component_id in &component_ids { - let component = Component::get_by_id(ctx, *component_id).await?; - let component_name = component.name(ctx).await?; - let schema_name = component.schema(ctx).await?.name; - let component_id_str = component_id.to_string(); - - component_summaries.insert( - component_id_str, - ComponentSummaryV1 { - component_name, - schema_name, - has_resource: None, - resource_id: None, - resource_status: None, - has_diff: None, - diff_status: None, - subscriptions: Vec::new(), - manages: Vec::new(), - action_functions: Vec::new(), - management_functions: Vec::new(), - qualification_functions: Vec::new(), - }, - ); - } - - // Add resource information if requested - if include_resource_info { - let resource_start = Instant::now(); - for component_id in &component_ids { - let component = Component::get_by_id(ctx, *component_id).await?; - let resource_data = component.resource(ctx).await?; - let resource_id = component.resource_id(ctx).await?; - - if let Some(summary) = component_summaries.get_mut(&component_id.to_string()) { - summary.has_resource = Some(resource_data.is_some()); - summary.resource_id = if resource_id.is_empty() { - None - } else { - Some(resource_id) - }; - summary.resource_status = resource_data.map(|r| { - let status = r.status; - format!("{status:?}") - }); - } - } - debug!( - "Resource info processed in {}ms", - resource_start.elapsed().as_millis() - ); - } - - // Add diff status information if requested - if include_diff_status { - let diff_start = Instant::now(); - let head_ctx = ctx.clone_with_head().await?; - - for component_id in &component_ids { - let exists_in_head = Component::exists_by_id(&head_ctx, *component_id).await?; - let exists_in_changeset = Component::exists_by_id(ctx, *component_id).await?; - - let (has_diff, diff_status) = if !exists_in_head && exists_in_changeset { - (true, "Added") - } else if exists_in_head && !exists_in_changeset { - (true, "Removed") - } else if exists_in_head && exists_in_changeset { - let has_changes = has_meaningful_component_changes(ctx, *component_id).await?; - - if has_changes { - debug!( - "Component {} ({}) has meaningful changes detected", - component_id, - Component::get_by_id(ctx, *component_id) - .await? - .name(ctx) - .await? - ); - } else { - debug!( - "Component {} ({}) has no meaningful changes", - component_id, - Component::get_by_id(ctx, *component_id) - .await? - .name(ctx) - .await? - ); - } - - (has_changes, if has_changes { "Modified" } else { "None" }) - } else { - (false, "None") - }; - - if let Some(summary) = component_summaries.get_mut(&component_id.to_string()) { - summary.has_diff = Some(has_diff); - summary.diff_status = Some(diff_status.to_string()); - } - } - debug!( - "Diff status processed in {}ms", - diff_start.elapsed().as_millis() - ); - } - - // Add subscription relationships if requested - if include_subscriptions { - let diagram_start = Instant::now(); - let diagram = Diagram::assemble(ctx, None).await?; - debug!( - "Diagram assembly completed in {}ms", - diagram_start.elapsed().as_millis() - ); - - for edge in &diagram.attribute_subscription_edges { - let to_name = Component::name_by_id(ctx, edge.to_component_id).await?; - let current_value = AttributeValue::view(ctx, edge.to_attribute_value_id).await?; - - let from_component_str = edge.from_component_id.to_string(); - if let Some(summary) = component_summaries.get_mut(&from_component_str) { - summary.subscriptions.push(SubscriptionRelationshipV1 { - to_component_id: edge.to_component_id, - to_component_name: to_name, - from_path: edge.from_attribute_path.clone(), - to_path: edge.to_attribute_path.clone(), - current_value, - }); - } - } - debug!("Subscription relationships processed"); - } - - // Add management relationships if requested - if include_manages { - for component_id in &component_ids { - let component = Component::get_by_id(ctx, *component_id).await?; - let managed_components = component.get_managed(ctx).await?; - - for managed_id in managed_components { - let to_name = Component::name_by_id(ctx, managed_id).await?; - let from_component_str = component_id.to_string(); - - if let Some(summary) = component_summaries.get_mut(&from_component_str) { - summary.manages.push(ManagementRelationshipV1 { - to_component_id: managed_id, - to_component_name: to_name, - }); - } - } - } - debug!("Management relationships processed"); - } - - // Build execution history lookup maps if requested - let mut action_history_map: HashMap< - (ComponentId, dal::ActionPrototypeId), - Vec, - > = HashMap::new(); - let management_history_map: HashMap< - (ComponentId, ManagementPrototypeId), - Vec, - > = HashMap::new(); - let mut qualification_history_map: HashMap< - (ComponentId, AttributeValueId), - Vec, - > = HashMap::new(); - - if include_execution_history { - let history_start = Instant::now(); - let workspace_pk = ctx.tenancy().workspace_pk().unwrap_or_default(); - info!("Building execution history - include_execution_history is TRUE"); - - // Build action execution history using DUAL CONTEXT approach - if include_action_functions { - info!("Building action execution history with dual context"); - - // Create HEAD context for regular action history (Create/Update/Delete) - let head_ctx = ctx.clone_with_head().await?; - let head_workspace_pk = head_ctx.tenancy().workspace_pk().unwrap_or_default(); - - // Phase 1: Get regular action func runs from HEAD context (excludes refresh) - if let Ok(Some(all_func_runs)) = head_ctx - .layer_db() - .func_run() - .read_many_for_workspace(head_workspace_pk) - .await - { - let head_action_runs: Vec<_> = all_func_runs - .into_iter() - .filter(|fr| fr.function_kind() == si_events::FuncKind::Action) - .take(500) - .collect(); - - info!( - "Found {} action func runs from HEAD context", - head_action_runs.len() - ); - - for func_run in head_action_runs { - if let Some(action_id) = func_run.action_id() { - if let (Ok(Some(comp_id)), Ok(proto_id)) = ( - Action::component_id(&head_ctx, action_id).await, - Action::prototype_id(&head_ctx, action_id).await, - ) { - let result_state = get_action_result_from_func_run(&func_run); - - let entry = ExecutionHistoryEntry { - func_run_id: func_run.id(), - state: result_state, - started_at: func_run.created_at(), - }; - - action_history_map - .entry((comp_id, proto_id)) - .or_default() - .push(entry); - } - } - } - } - - // Phase 2: Get refresh action history from CURRENT context (refresh can run on changesets) - if let Ok(Some(current_func_runs)) = ctx - .layer_db() - .func_run() - .read_many_for_workspace(workspace_pk) - .await - { - let refresh_action_runs: Vec<_> = current_func_runs - .into_iter() - .filter(|fr| fr.function_kind() == si_events::FuncKind::Action) - .take(500) - .collect(); - - debug!( - "Found {} refresh action func runs from current context", - refresh_action_runs.len() - ); - - for func_run in refresh_action_runs { - if let Some(action_id) = func_run.action_id() { - // Check if this is a refresh action by trying current context first - if let (Ok(Some(comp_id)), Ok(proto_id)) = ( - Action::component_id(ctx, action_id).await, - Action::prototype_id(ctx, action_id).await, - ) { - // Get the action prototype to check if it's a refresh action - if let Ok(prototype) = ActionPrototype::get_by_id(ctx, proto_id).await { - if prototype.kind == ActionKind::Refresh { - let result_state = get_action_result_from_func_run(&func_run); - - let entry = ExecutionHistoryEntry { - func_run_id: func_run.id(), - state: result_state, - started_at: func_run.created_at(), - }; - - action_history_map - .entry((comp_id, proto_id)) - .or_default() - .push(entry); - } - } - } - } - } - } - - debug!( - "Built complete action history map with {} entries", - action_history_map.len() - ); - } - - // Build management execution history (simplified - API changes) - if include_management_functions { - debug!("Building management execution history using job states"); - // Simplified - skip complex management history for now - } - - // Build qualification execution history by parsing actual output logs - if include_qualification_functions { - if let Ok(Some(all_func_runs)) = ctx - .layer_db() - .func_run() - .read_many_for_workspace(workspace_pk) - .await - { - let qual_func_runs: Vec<_> = all_func_runs - .into_iter() - .filter(|fr| fr.function_kind() == si_events::FuncKind::Qualification) - .take(500) - .collect(); - - for func_run in qual_func_runs { - if let (Some(comp_id), Some(av_id)) = - (func_run.component_id(), func_run.attribute_value_id()) - { - // Parse the actual qualification result from func_run logs - let state = if let Ok(Some(func_run_log)) = ctx - .layer_db() - .func_run_log() - .get_for_func_run_id(func_run.id()) - .await - { - let func_run_log = - std::sync::Arc::::unwrap_or_clone( - func_run_log, - ); - - // Look for output logs that contain the qualification result - let mut result_state = None; - for log_entry in func_run_log.logs() { - if log_entry.stream == "output" { - // Remove "Output: " prefix if present - let json_str = if log_entry.message.starts_with("Output: ") { - &log_entry.message[8..] // Skip "Output: " - } else { - &log_entry.message - }; - - if let Ok(output_value) = - serde_json::from_str::(json_str) - { - // Check direct status field (new format) - if let Some(status) = output_value.get("status") { - if let Some(status_str) = status.as_str() { - result_state = Some(match status_str { - "success" => "Succeeded".to_string(), - "failure" => "Failed".to_string(), - "warning" => "Warning".to_string(), - _ => "Completed".to_string(), - }); - break; - } - } - // Fallback: check old format (data.result) - else if let Some(data) = output_value.get("data") { - if let Some(result) = data.get("result") { - if let Some(result_str) = result.as_str() { - result_state = Some(match result_str { - "success" => "Succeeded".to_string(), - "failure" => "Failed".to_string(), - "warning" => "Warning".to_string(), - _ => "Completed".to_string(), - }); - break; - } - } - } - } - } - } - - // Use parsed result or fall back to function execution state - result_state.unwrap_or_else(|| match func_run.state() { - si_events::FuncRunState::Success => "Succeeded".to_string(), - si_events::FuncRunState::Failure => "Failed".to_string(), - _ => { - let state = func_run.state(); - format!("{state:?}") - } - }) - } else { - // No logs available, use function execution state - match func_run.state() { - si_events::FuncRunState::Success => "Succeeded".to_string(), - si_events::FuncRunState::Failure => "Failed".to_string(), - _ => { - let state = func_run.state(); - format!("{state:?}") - } - } - }; - - let entry = ExecutionHistoryEntry { - func_run_id: func_run.id(), - state, - started_at: func_run.created_at(), - }; - - qualification_history_map - .entry((comp_id, av_id)) - .or_default() - .push(entry); - } - } - } - - // Sort and limit qualification history - for history in qualification_history_map.values_mut() { - history.sort_by(|a, b| b.started_at.cmp(&a.started_at)); - history.truncate(10); - } - } - - debug!( - "Execution history built in {}ms", - history_start.elapsed().as_millis() - ); - } - - // Add function relationships based on specific parameters - let need_any_functions = - include_action_functions || include_management_functions || include_qualification_functions; - if need_any_functions { - let functions_start = Instant::now(); - - // Build UNIFIED action lookup: HEAD executions + current changeset scheduled/on-hold - let mut action_lookup: HashMap< - (ComponentId, dal::ActionPrototypeId), - (ActionState, Option, si_id::ActionId), - > = HashMap::new(); - - // Build action dependency graph to get dependencies - let action_dependency_graph = ActionDependencyGraph::for_workspace(ctx).await?; - - // Phase 1: Get scheduled/on-hold actions from current changeset - let mut current_changeset_actions = Vec::new(); - for component_id in &component_ids { - if let Ok(actions) = Action::find_for_component_id(ctx, *component_id).await { - current_changeset_actions.extend(actions); - } - } - debug!( - "Found {} actions in current changeset", - current_changeset_actions.len() - ); - - for action_id in current_changeset_actions { - if let (Ok(Some(comp_id)), Ok(proto_id), Ok(action)) = ( - Action::component_id(ctx, action_id).await, - Action::prototype_id(ctx, action_id).await, - Action::get_by_id(ctx, action_id).await, - ) { - let func_run_id = Action::last_func_run_id_for_id_opt(ctx, action_id).await?; - - action_lookup.insert( - (comp_id, proto_id), - (action.state(), func_run_id, action_id), - ); - } - } - - // Phase 2: Get executed actions from HEAD context (ONLY if no current action exists) - let head_ctx = ctx.clone_with_head().await?; - let current_change_set_id = ctx.change_set_id(); - let head_change_set_id = head_ctx.change_set_id(); - - if current_change_set_id != head_change_set_id { - let head_actions = Action::list_topologically(&head_ctx).await?; - debug!("Found {} actions in HEAD context", head_actions.len()); - - for action_id in head_actions { - if let (Ok(Some(comp_id)), Ok(proto_id), Ok(action)) = ( - Action::component_id(&head_ctx, action_id).await, - Action::prototype_id(&head_ctx, action_id).await, - Action::get_by_id(&head_ctx, action_id).await, - ) { - // Only add HEAD actions if we don't already have a current action for this component+prototype - if let std::collections::hash_map::Entry::Vacant(e) = - action_lookup.entry((comp_id, proto_id)) - { - let func_run_id = - Action::last_func_run_id_for_id_opt(&head_ctx, action_id).await?; - e.insert((action.state(), func_run_id, action_id)); - } - } - } - } - - info!( - "Built unified action lookup with {} total entries", - action_lookup.len() - ); - - // Process each component to add function data - for component_id in &component_ids { - if let Some(summary) = component_summaries.get_mut(&component_id.to_string()) { - let component = Component::get_by_id(ctx, *component_id).await?; - - // Add action functions with REAL status - if include_action_functions { - // Get all action prototypes for this component's schema variant - let schema_variant = component.schema_variant(ctx).await?; - let schema_variant_id = schema_variant.id(); - - // Get action prototypes from the schema variant - if let Ok(action_prototypes) = - ActionPrototype::for_variant(ctx, schema_variant_id).await - { - for prototype in action_prototypes { - let key = (*component_id, prototype.id()); - - // Check if there's an actual action scheduled for this function - if let Some((state, func_run_id, action_id)) = action_lookup.get(&key) { - // There's a real action scheduled - let execution_history = if include_execution_history { - action_history_map - .get(&key) - .cloned() - .unwrap_or_else(Vec::new) - } else { - Vec::new() - }; - - let depends_on: Vec = action_dependency_graph - .direct_dependencies_of(*action_id) - .into_iter() - .collect(); - - let execution_status = Some(FunctionExecutionStatusV1 { - state: format!("{state:?}"), - has_active_run: *state == ActionState::Running - || *state == ActionState::Dispatched, - func_run_id: *func_run_id, - action_id: Some(*action_id), - }); - - summary.action_functions.push(FunctionRelationshipV1 { - function_name: prototype.name.clone(), - execution_status, - depends_on, - execution_history, - }); - } else { - // No action scheduled - show as Idle - let execution_history = if include_execution_history { - action_history_map - .get(&key) - .cloned() - .unwrap_or_else(Vec::new) - } else { - Vec::new() - }; - - let execution_status = Some(FunctionExecutionStatusV1 { - state: "Idle".to_string(), - has_active_run: false, - func_run_id: None, - action_id: None, - }); - - summary.action_functions.push(FunctionRelationshipV1 { - function_name: prototype.name.clone(), - execution_status, - depends_on: Vec::new(), - execution_history, - }); - } - } - } - } - - // Add management functions with execution state - if include_management_functions { - // Get management prototypes from the schema variant - let schema_variant = component.schema_variant(ctx).await?; - let schema_variant_id = schema_variant.id(); - - if let Ok(mgmt_prototypes) = - dal::management::prototype::ManagementPrototype::list_for_variant_id( - ctx, - schema_variant_id, - ) - .await - { - for mgmt_prototype in mgmt_prototypes { - // Get execution history for this management function - let execution_history = if include_execution_history { - management_history_map - .get(&(*component_id, mgmt_prototype.id())) - .cloned() - .unwrap_or_else(Vec::new) - } else { - Vec::new() - }; - - // Determine execution status based on most recent job state - let execution_status = if !execution_history.is_empty() { - let most_recent = &execution_history[0]; // Already sorted by most recent first - Some(FunctionExecutionStatusV1 { - state: match most_recent.state.as_str() { - "success" => "Succeeded".to_string(), - "failure" => "Failed".to_string(), - "running" => "Running".to_string(), - _ => most_recent.state.clone(), - }, - has_active_run: most_recent.state == "running", - func_run_id: Some(most_recent.func_run_id), - action_id: None, - }) - } else { - Some(FunctionExecutionStatusV1 { - state: "Available".to_string(), - has_active_run: false, - func_run_id: None, - action_id: None, - }) - }; - - summary.management_functions.push(FunctionRelationshipV1 { - function_name: mgmt_prototype.name.clone(), - execution_status, - depends_on: Vec::new(), // Management functions don't have action dependencies - execution_history, - }); - } - } - } - - // Add qualification functions with REAL status - if include_qualification_functions { - let qualification_avs = - Component::list_qualification_avs(ctx, *component_id).await?; - - for qualification_av in &qualification_avs { - if let Ok(Some(qualification)) = - dal::qualification::QualificationView::new(ctx, qualification_av.id()) - .await - { - let qual_func_run = ctx - .layer_db() - .func_run() - .get_last_qualification_for_attribute_value_id( - ctx.events_tenancy().workspace_pk, - qualification_av.id(), - ) - .await?; - - let func_run_id = qual_func_run.as_ref().map(|run| run.id()); - - let execution_status = if qualification.finalized { - if let Some(result) = &qualification.result { - match result.status { - dal::qualification::QualificationSubCheckStatus::Success => { - Some(FunctionExecutionStatusV1 { - state: "Succeeded".to_string(), - has_active_run: false, - func_run_id, - action_id: None, - }) - } - dal::qualification::QualificationSubCheckStatus::Failure => { - Some(FunctionExecutionStatusV1 { - state: "Failed".to_string(), - has_active_run: false, - func_run_id, - action_id: None, - }) - } - dal::qualification::QualificationSubCheckStatus::Warning => { - Some(FunctionExecutionStatusV1 { - state: "Warning".to_string(), - has_active_run: false, - func_run_id, - action_id: None, - }) - } - _ => { - Some(FunctionExecutionStatusV1 { - state: "Completed".to_string(), - has_active_run: false, - func_run_id, - action_id: None, - }) - } - } - } else { - Some(FunctionExecutionStatusV1 { - state: "Completed".to_string(), - has_active_run: false, - func_run_id, - action_id: None, - }) - } - } else { - Some(FunctionExecutionStatusV1 { - state: "Running".to_string(), - has_active_run: true, - func_run_id, - action_id: None, - }) - }; - - // Get execution history for this qualification function - let execution_history = if include_execution_history { - qualification_history_map - .get(&(*component_id, qualification_av.id())) - .cloned() - .unwrap_or_else(Vec::new) - } else { - Vec::new() - }; - - summary - .qualification_functions - .push(FunctionRelationshipV1 { - function_name: qualification.qualification_name, - execution_status, - depends_on: Vec::new(), // Qualification functions don't have action dependencies - execution_history, - }); - } - } - } - } - } - - debug!( - "Function relationships completed in {}ms", - functions_start.elapsed().as_millis() - ); - } - - info!( - "Graph summary completed in {}ms", - start_time.elapsed().as_millis() - ); - Ok(component_summaries) -} - -// (Hash-based component diff check already defined above) - #[utoipa::path( get, path = "/v1/w/{workspace_id}/change-sets/{change_set_id}/components", @@ -1089,6 +152,8 @@ pub async fn list_components( Query(params): Query, tracker: PosthogEventTracker, ) -> Result, ComponentsError> { + let maybe_summary_generator_config = SummaryGeneratorConfig::from_params(¶ms); + // Set default limit and enforce a max limit let limit = params .pagination @@ -1096,21 +161,46 @@ pub async fn list_components( .and_then(|s| s.parse::().ok()) .unwrap_or(50) .min(300) as usize; + let include_codegen = params.include_codegen; let cursor = params.pagination.cursor; - let mut comp_details = Vec::with_capacity(limit); + let (component_details, next_cursor) = list_components_inner( + ctx, + limit, + cursor, + include_codegen, + maybe_summary_generator_config, + ) + .await?; - // Get all component - let mut all_components = Component::list(ctx).await?; + tracker.track(ctx, "api_list_components", json!({})); - // Sort components for consistent pagination - all_components.sort_by_key(|c| c.id()); + Ok(Json(ListComponentsV1Response { + component_details, + next_cursor, + })) +} - // Find the start index by matching the stringified ComponentId +// NOTE(nick): we can instrument this if we need to +async fn list_components_inner( + ctx: &DalContext, + limit: usize, + cursor: Option, + include_codegen: Option, + maybe_summary_generator_config: Option, +) -> Result<(Vec, Option), ComponentsError> { + let mut component_details_vec = Vec::with_capacity(limit); + + // Get all component IDs. This ensures that we do not access CAS. Then, sort for consistent + // pagination. + let mut all_component_ids = Component::list_ids(ctx).await?; + all_component_ids.sort(); + + // Find the start index by matching the ID. let start_index = if let Some(ref cursor_str) = cursor { - match all_components + match all_component_ids .iter() - .position(|component| component.id().to_string() == *cursor_str) + .position(|id| id.to_string() == *cursor_str) { Some(index) => index + 1, // Start after the cursor None => 0, @@ -1120,27 +210,38 @@ pub async fn list_components( }; // Compute the end index and extract the paginated slice - let end_index = (start_index + limit).min(all_components.len()); - let paginated_components: Vec = all_components[start_index..end_index].to_vec(); + let end_index = (start_index + limit).min(all_component_ids.len()); + let paginated_component_ids: Vec = + all_component_ids[start_index..end_index].to_vec(); // Generate the next cursor from the last item's ID - let next_cursor = if end_index < all_components.len() && !paginated_components.is_empty() { - paginated_components - .last() - .map(|component| component.id().to_string()) + let next_cursor = if end_index < all_component_ids.len() && !paginated_component_ids.is_empty() + { + paginated_component_ids.last().map(|id| id.to_string()) } else { None }; - for component in &paginated_components { - let name = component.name(ctx).await?; - let schema_name = component.schema(ctx).await?.name; - - let mut comp_response = ComponentDetailsV1 { - component_id: component.id(), - name, - schema_name, - codegen: None, + for paginated_component_id in paginated_component_ids.iter().copied() { + component_details_vec.push(ComponentDetailsV1 { + component_id: paginated_component_id, + name: Component::name_by_id(ctx, paginated_component_id).await?, + schema_name: Component::schema_for_component_id(ctx, paginated_component_id) + .await? + .name, + + // Existed before graph summary fields + codegen: match include_codegen { + Some(codegen) if codegen => { + let code_map_av_id = + Component::find_code_map_attribute_value_id(ctx, paginated_component_id) + .await?; + AttributeValue::view(ctx, code_map_av_id) + .await? + .and_then(|view| view.get("awsCloudFormationLint").cloned()) + } + Some(_) | None => None, + }, // Initialize graph summary fields has_resource: None, @@ -1153,90 +254,259 @@ pub async fn list_components( action_functions: Vec::new(), management_functions: Vec::new(), qualification_functions: Vec::new(), - }; + }); + } - if let Some(codegen) = params.include_codegen { - if codegen { - let code_map_av_id = - Component::find_code_map_attribute_value_id(ctx, component.id()).await?; + // If any graph summary options are enabled (i.e. a "config" was provided to this function), + // populate the graph data. + if let Some(config) = maybe_summary_generator_config { + let generator = ComponentSummaryGenerator::new( + config.include_action_functions, + config.include_diff_status, + config.include_execution_history, + config.include_management_functions, + config.include_manages, + config.include_qualification_functions, + config.include_resource_info, + config.include_subscriptions, + ); - let view = AttributeValue::view(ctx, code_map_av_id).await?; - if let Some(v) = view { - let details = v.get("awsCloudFormationLint"); - comp_response.codegen = details.cloned(); - } + // Build graph summary for the components. Drop the HEAD context from scope as soon as we + // no longer need it. + let graph_summaries = { + let head_ctx = ctx.clone_with_head().await?; + generator + .generate(ctx, &head_ctx, paginated_component_ids.as_slice()) + .await? + }; + + // Merge graph summary data into the component details collection. + for component_details in &mut component_details_vec { + if let Some(graph_data) = + graph_summaries.get(&component_details.component_id.to_string()) + { + component_details.has_resource = graph_data.has_resource; + component_details.resource_id = graph_data.resource_id.clone(); + component_details.resource_status = graph_data.resource_status.clone(); + component_details.has_diff = graph_data.has_diff; + component_details.diff_status = graph_data.diff_status.clone(); + component_details.subscriptions = graph_data + .subscriptions + .iter() + .cloned() + .map(Into::into) + .collect(); + component_details.manages = + graph_data.manages.iter().cloned().map(Into::into).collect(); + component_details.action_functions = graph_data + .action_functions + .iter() + .cloned() + .map(Into::into) + .collect(); + component_details.management_functions = graph_data + .management_functions + .iter() + .cloned() + .map(Into::into) + .collect(); + component_details.qualification_functions = graph_data + .qualification_functions + .iter() + .cloned() + .map(Into::into) + .collect(); } } + } - comp_details.push(comp_response); + Ok((component_details_vec, next_cursor)) +} + +// Graph summary data structures +#[derive(Serialize, Debug, Clone, ToSchema)] +#[serde(rename_all = "camelCase")] +pub struct SubscriptionRelationshipV1 { + #[schema(value_type = String)] + pub to_component_id: ComponentId, + pub to_component_name: String, + pub from_path: String, + pub to_path: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub current_value: Option, +} + +#[derive(Serialize, Debug, Clone, ToSchema)] +#[serde(rename_all = "camelCase")] +pub struct ManagementRelationshipV1 { + #[schema(value_type = String)] + pub to_component_id: ComponentId, + pub to_component_name: String, +} + +#[derive(Serialize, Debug, Clone, ToSchema)] +#[serde(rename_all = "camelCase")] +pub struct FunctionRelationshipV1 { + pub function_name: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub execution_status: Option, + #[serde(skip_serializing_if = "Vec::is_empty")] + #[schema(value_type = Vec)] + pub depends_on: Vec, + #[serde(skip_serializing_if = "Vec::is_empty")] + pub execution_history: Vec, +} + +#[derive(Serialize, Debug, Clone, ToSchema)] +#[serde(rename_all = "camelCase")] +pub struct FunctionExecutionStatusV1 { + pub state: String, + pub has_active_run: bool, + #[serde(skip_serializing_if = "Option::is_none")] + #[schema(value_type = Option)] + pub func_run_id: Option, + #[serde(skip_serializing_if = "Option::is_none")] + #[schema(value_type = Option)] + pub action_id: Option, +} + +#[derive(Serialize, Debug, Clone, ToSchema)] +#[serde(rename_all = "camelCase")] +pub struct ExecutionHistoryEntry { + #[schema(value_type = String)] + pub func_run_id: si_id::FuncRunId, + pub state: String, + #[schema(value_type = String, format = DateTime)] + pub started_at: chrono::DateTime, +} + +impl From for SubscriptionRelationshipV1 { + fn from(value: dal_summary_generator::SubscriptionRelationship) -> Self { + Self { + to_component_id: value.to_component_id, + to_component_name: value.to_component_name, + from_path: value.from_path, + to_path: value.to_path, + current_value: value.current_value, + } } +} - // If any graph summary options are enabled, populate the graph data - let include_any_graph_data = params.include_all.unwrap_or(false) - || params.include_functions.unwrap_or(false) - || params.include_subscriptions.unwrap_or(false) - || params.include_manages.unwrap_or(false) - || params.include_action_functions.unwrap_or(false) - || params.include_management_functions.unwrap_or(false) - || params.include_qualification_functions.unwrap_or(false) - || params.include_resource_info.unwrap_or(false) - || params.include_diff_status.unwrap_or(false) - || params.include_execution_history.unwrap_or(false); +impl From for ManagementRelationshipV1 { + fn from(value: dal_summary_generator::ManagementRelationship) -> Self { + Self { + to_component_id: value.to_component_id, + to_component_name: value.to_component_name, + } + } +} - if include_any_graph_data { - // Use the existing graph summary function with the same parameter logic - let include_all = params.include_all.unwrap_or(false); - let include_functions = params.include_functions.unwrap_or(false); - let include_subscriptions = include_all || params.include_subscriptions.unwrap_or(false); - let include_manages = include_all || params.include_manages.unwrap_or(false); - let include_action_functions = - include_all || include_functions || params.include_action_functions.unwrap_or(false); - let include_management_functions = include_all - || include_functions - || params.include_management_functions.unwrap_or(false); - let include_qualification_functions = include_all - || include_functions - || params.include_qualification_functions.unwrap_or(false); - let include_resource_info = include_all || params.include_resource_info.unwrap_or(false); - let include_diff_status = include_all || params.include_diff_status.unwrap_or(false); - let include_execution_history = - include_all || params.include_execution_history.unwrap_or(false); +impl From for FunctionRelationshipV1 { + fn from(value: dal_summary_generator::FunctionRelationship) -> Self { + Self { + function_name: value.function_name, + execution_status: value.execution_status.map(Into::into), + depends_on: value.depends_on, + execution_history: value + .execution_history + .into_iter() + .map(Into::into) + .collect(), + } + } +} - // Build graph summary for the components - let graph_summaries = build_graph_summary( - ctx, - include_subscriptions, - include_manages, - include_action_functions, - include_management_functions, - include_qualification_functions, - include_resource_info, - include_diff_status, - include_execution_history, - ) - .await?; +impl From for FunctionExecutionStatusV1 { + fn from(value: dal_summary_generator::FunctionExecutionStatus) -> Self { + Self { + state: value.state, + has_active_run: value.has_active_run, + func_run_id: value.func_run_id, + action_id: value.action_id, + } + } +} - // Merge graph summary data into component details - for comp_detail in &mut comp_details { - if let Some(graph_data) = graph_summaries.get(&comp_detail.component_id.to_string()) { - comp_detail.has_resource = graph_data.has_resource; - comp_detail.resource_id = graph_data.resource_id.clone(); - comp_detail.resource_status = graph_data.resource_status.clone(); - comp_detail.has_diff = graph_data.has_diff; - comp_detail.diff_status = graph_data.diff_status.clone(); - comp_detail.subscriptions = graph_data.subscriptions.clone(); - comp_detail.manages = graph_data.manages.clone(); - comp_detail.action_functions = graph_data.action_functions.clone(); - comp_detail.management_functions = graph_data.management_functions.clone(); - comp_detail.qualification_functions = graph_data.qualification_functions.clone(); - } +impl From for ExecutionHistoryEntry { + fn from(value: dal_summary_generator::ExecutionHistoryEntry) -> Self { + Self { + func_run_id: value.func_run_id, + state: value.state, + started_at: value.started_at, } } +} - tracker.track(ctx, "api_list_components", json!({})); +#[derive(Debug)] +struct SummaryGeneratorConfig { + include_action_functions: bool, + include_diff_status: bool, + include_execution_history: bool, + include_management_functions: bool, + include_manages: bool, + include_qualification_functions: bool, + include_resource_info: bool, + include_subscriptions: bool, +} - Ok(Json(ListComponentsV1Response { - component_details: comp_details, - next_cursor, - })) +impl SummaryGeneratorConfig { + pub fn from_params(params: &ListComponentsParams) -> Option { + // Evaluate the parameters that cannot be overriden. + let include_all = params.include_all.unwrap_or(false); + let include_functions = params.include_functions.unwrap_or(false); + + // Evaluate the parameters that may be overriden. + let mut include_action_functions = params.include_action_functions.unwrap_or(false); + let mut include_diff_status = params.include_diff_status.unwrap_or(false); + let mut include_execution_history = params.include_execution_history.unwrap_or(false); + let mut include_management_functions = params.include_management_functions.unwrap_or(false); + let mut include_manages = params.include_manages.unwrap_or(false); + let mut include_qualification_functions = + params.include_qualification_functions.unwrap_or(false); + let mut include_resource_info = params.include_resource_info.unwrap_or(false); + let mut include_subscriptions = params.include_subscriptions.unwrap_or(false); + + // Check if we are including any graph data. + let include_any_graph_data = include_action_functions + || include_all + || include_diff_status + || include_execution_history + || include_functions + || include_management_functions + || include_manages + || include_qualification_functions + || include_resource_info + || include_subscriptions; + + // If we are including any graph data, we need to check if we need to override + // configuration options. + if include_any_graph_data { + // Check for function-related overrides. + include_action_functions = include_all || include_functions || include_action_functions; + include_management_functions = + include_all || include_functions || include_management_functions; + include_qualification_functions = + include_all || include_functions || include_qualification_functions; + + // Check for all other overrides. + include_diff_status = include_all || include_diff_status; + include_execution_history = include_all || include_execution_history; + include_manages = include_all || include_manages; + include_resource_info = include_all || include_resource_info; + include_subscriptions = include_all || include_subscriptions; + + Some(Self { + include_action_functions, + include_diff_status, + include_execution_history, + include_management_functions, + include_manages, + include_qualification_functions, + include_resource_info, + include_subscriptions, + }) + } else { + None + } + } } diff --git a/lib/luminork-server/src/service/v1/components/mod.rs b/lib/luminork-server/src/service/v1/components/mod.rs index ae0918e420..03043f9700 100644 --- a/lib/luminork-server/src/service/v1/components/mod.rs +++ b/lib/luminork-server/src/service/v1/components/mod.rs @@ -119,6 +119,8 @@ pub enum ComponentsError { ComponentNotRestorable(ComponentId), #[error("dal change set error: {0}")] DalChangeSet(#[from] dal::ChangeSetError), + #[error("dal summary generator error: {0}")] + DalSummaryGenerator(#[from] dal_summary_generator::Error), #[error("diagram error: {0}")] Diagram(#[from] dal::diagram::DiagramError), #[error(