use crate::error::{Error, Result};
use crate::workflow::command::RecordStepResultCommand;
use crate::workflow::WorkflowContext;
const CLOSURE_STEP_TYPE: i32 = 2;
use std::collections::HashMap;
pub fn extract_closure_commands(ctx: &WorkflowContext) -> Result<Vec<RecordStepResultCommand>> {
let (pending_results, step_type_map, step_attempt_counts) = {
let state = ctx.state.lock().map_err(|e| {
Error::Workflow(crate::error::WorkflowError::StateError(format!(
"Failed to lock workflow state: {}",
e
)))
})?;
(
state.pending_task_results.clone(),
state.step_type_map.clone(),
state.step_attempt_counts.clone(),
)
};
let mut commands = Vec::new();
for (step_id, result_bytes) in pending_results {
let step_type = step_type_map.get(&step_id).copied();
match step_type {
Some(0) => {
tracing::trace!(
step_id = %step_id,
"Skipping task step (handled via CompleteTaskExecution RPC)"
);
continue;
}
Some(1) => {
tracing::debug!(
step_id = %step_id,
result_size = result_bytes.len(),
"Extracting closure result for server persistence"
);
}
Some(_) => {
tracing::warn!(
step_id = %step_id,
step_type = ?step_type,
"Unknown step_type value - skipping to avoid incorrect recording"
);
continue;
}
None => {
tracing::warn!(
step_id = %step_id,
"Step has no type information in step_type_map - skipping to avoid incorrect recording"
);
continue;
}
}
let execution_attempt = step_attempt_counts.get(&step_id).copied().unwrap_or(1);
let command = RecordStepResultCommand {
step_name: step_id.clone(),
step_type: CLOSURE_STEP_TYPE,
result: result_bytes,
failure: None,
execution_attempt,
};
commands.push(command);
}
tracing::info!(
closure_count = commands.len(),
"Extracted closure commands for server persistence"
);
Ok(commands)
}
pub fn is_closure_step(step_id: &str) -> bool {
if let Some(last_underscore_pos) = step_id.rfind('_') {
let potential_sequence = &step_id[last_underscore_pos + 1..];
if !potential_sequence.is_empty() && potential_sequence.chars().all(|c| c.is_ascii_digit())
{
return true;
}
}
if step_id.contains("::") {
return false;
}
false
}
pub fn extract_failed_closure_commands(
ctx: &WorkflowContext,
) -> Result<Vec<RecordStepResultCommand>> {
let (pending_failures, step_attempt_counts): (
HashMap<String, crate::workflow::StepFailure>,
HashMap<String, i32>,
) = {
let state = ctx.state.lock().map_err(|e| {
Error::Workflow(crate::error::WorkflowError::StateError(format!(
"Failed to lock workflow state: {}",
e
)))
})?;
(
state.pending_task_failures.clone(),
state.step_attempt_counts.clone(),
)
};
let mut commands = Vec::new();
for (step_id, failure) in pending_failures {
let execution_attempt = step_attempt_counts.get(&step_id).copied().unwrap_or(1);
tracing::debug!(
step_id = %step_id,
attempt = execution_attempt,
error = %failure.message,
"Extracting failed closure command"
);
commands.push(RecordStepResultCommand {
step_name: step_id,
step_type: CLOSURE_STEP_TYPE,
result: vec![],
failure: Some(failure),
execution_attempt,
});
}
tracing::debug!(
failed_count = commands.len(),
"Extracted failed closure commands"
);
Ok(commands)
}
pub fn get_closure_stats(ctx: &WorkflowContext) -> Result<ClosureExecutionStats> {
let state = ctx.state.lock().map_err(|e| {
Error::Workflow(crate::error::WorkflowError::StateError(format!(
"Failed to lock workflow state: {}",
e
)))
})?;
let total_results = state.pending_task_results.len();
let closure_results = state
.pending_task_results
.keys()
.filter(|k| is_closure_step(k))
.count();
Ok(ClosureExecutionStats {
total_executions: closure_results,
results_pending: closure_results,
task_executions: total_results - closure_results,
})
}
#[derive(Debug, Clone)]
pub struct ClosureExecutionStats {
pub total_executions: usize,
pub results_pending: usize,
pub task_executions: usize,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_is_closure_step() {
assert!(is_closure_step("fetch_user_1"));
assert!(is_closure_step("query_orders_2"));
assert!(is_closure_step("external_api_call_10"));
assert!(!is_closure_step("EmailService::send_welcome"));
assert!(!is_closure_step("PaymentService::charge_card"));
assert!(is_closure_step("step_123"));
assert!(is_closure_step("_999")); }
#[test]
fn test_closure_step_format() {
assert!(is_closure_step("a_1"));
assert!(is_closure_step("my_step_name_42"));
assert!(!is_closure_step("no_sequence_here"));
assert!(!is_closure_step("Task::execute"));
}
}