use std::future::Future;
use std::sync::Arc;
use parking_lot::Mutex;
use serde_json::{Map, Value};
use crate::workflow::Node;
use crate::workflow::graph::Graph;
use crate::workflow::nodes::WorkflowNode;
use crate::workflow::persistence::WORKFLOW_FAILED_CHILD_PATHS_KEY;
use crate::workflow::scheduler::node_key;
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub(crate) struct FailureInventory {
pub(crate) known: bool,
pub(crate) paths: Vec<String>,
}
pub(crate) struct FailureInventoryRecorder {
producer: usize,
state: Mutex<RecorderState>,
}
#[derive(Default)]
struct RecorderState {
published: bool,
inventory: FailureInventory,
}
impl FailureInventoryRecorder {
pub(crate) fn snapshot(&self) -> FailureInventory {
self.state.lock().inventory.clone()
}
}
tokio::task_local! {
static FAILURE_INVENTORY: Arc<FailureInventoryRecorder>;
}
pub(crate) fn graph_key(g: &Arc<Graph>) -> usize {
Arc::as_ptr(g) as usize
}
pub(crate) fn node_producer_key(node: &Arc<dyn Node>) -> usize {
match node.as_any().downcast_ref::<WorkflowNode>() {
Some(w) => graph_key(&w.sub_workflow.graph),
None => node_key(node),
}
}
pub(crate) fn with_failure_inventory(node: &Arc<dyn Node>) -> Arc<FailureInventoryRecorder> {
Arc::new(FailureInventoryRecorder {
producer: node_producer_key(node),
state: Mutex::default(),
})
}
pub(crate) async fn scope<F: Future>(recorder: Arc<FailureInventoryRecorder>, f: F) -> F::Output {
FAILURE_INVENTORY.scope(recorder, f).await
}
pub(crate) fn publish_failure_inventory(producer: usize, inventory: &FailureInventory) {
let _ = FAILURE_INVENTORY.try_with(|r| {
if r.producer != producer {
return;
}
let mut st = r.state.lock();
st.inventory = if st.published {
FailureInventory::default()
} else {
inventory.clone()
};
st.published = true;
});
}
pub(crate) fn record_failed_child_paths(
metadata: &mut Map<String, Value>,
inventory: &FailureInventory,
) {
if !inventory.known {
return;
}
let mut seen = std::collections::HashSet::new();
let paths: Vec<Value> = inventory
.paths
.iter()
.filter(|p| !p.is_empty() && seen.insert(p.as_str()))
.map(|p| Value::String(p.clone()))
.collect();
metadata.insert(
WORKFLOW_FAILED_CHILD_PATHS_KEY.to_string(),
Value::Array(paths),
);
}