[model-gateway] change sgl-router to sgl-model-gateway (#14312)
This commit is contained in:
@@ -0,0 +1,98 @@
|
||||
//! Workflow definition types
|
||||
|
||||
use std::{sync::Arc, time::Duration};
|
||||
|
||||
use super::{
|
||||
executor::StepExecutor,
|
||||
types::{FailureAction, RetryPolicy, StepId, WorkflowId},
|
||||
};
|
||||
|
||||
/// Definition of a single step within a workflow
|
||||
pub struct StepDefinition {
|
||||
pub id: StepId,
|
||||
pub name: String,
|
||||
pub executor: Arc<dyn StepExecutor>,
|
||||
pub retry_policy: Option<RetryPolicy>,
|
||||
pub timeout: Option<Duration>,
|
||||
pub on_failure: FailureAction,
|
||||
}
|
||||
|
||||
impl StepDefinition {
|
||||
pub fn new(
|
||||
id: impl Into<String>,
|
||||
name: impl Into<String>,
|
||||
executor: Arc<dyn StepExecutor>,
|
||||
) -> Self {
|
||||
Self {
|
||||
id: StepId::new(id.into()),
|
||||
name: name.into(),
|
||||
executor,
|
||||
retry_policy: None,
|
||||
timeout: None,
|
||||
on_failure: FailureAction::FailWorkflow,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_retry(mut self, policy: RetryPolicy) -> Self {
|
||||
self.retry_policy = Some(policy);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_timeout(mut self, timeout: Duration) -> Self {
|
||||
self.timeout = Some(timeout);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_failure_action(mut self, action: FailureAction) -> Self {
|
||||
self.on_failure = action;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// Complete workflow definition
|
||||
pub struct WorkflowDefinition {
|
||||
pub id: WorkflowId,
|
||||
pub name: String,
|
||||
pub steps: Vec<StepDefinition>,
|
||||
pub default_retry_policy: RetryPolicy,
|
||||
pub default_timeout: Duration,
|
||||
}
|
||||
|
||||
impl WorkflowDefinition {
|
||||
pub fn new(id: impl Into<String>, name: impl Into<String>) -> Self {
|
||||
Self {
|
||||
id: WorkflowId::new(id.into()),
|
||||
name: name.into(),
|
||||
steps: Vec::new(),
|
||||
default_retry_policy: RetryPolicy::default(),
|
||||
default_timeout: Duration::from_secs(300), // 5 minutes
|
||||
}
|
||||
}
|
||||
|
||||
pub fn add_step(mut self, step: StepDefinition) -> Self {
|
||||
self.steps.push(step);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_default_retry(mut self, policy: RetryPolicy) -> Self {
|
||||
self.default_retry_policy = policy;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_default_timeout(mut self, timeout: Duration) -> Self {
|
||||
self.default_timeout = timeout;
|
||||
self
|
||||
}
|
||||
|
||||
/// Get the retry policy for a step (step-specific or default)
|
||||
pub fn get_retry_policy<'a>(&'a self, step: &'a StepDefinition) -> &'a RetryPolicy {
|
||||
step.retry_policy
|
||||
.as_ref()
|
||||
.unwrap_or(&self.default_retry_policy)
|
||||
}
|
||||
|
||||
/// Get the timeout for a step (step-specific or default)
|
||||
pub fn get_timeout(&self, step: &StepDefinition) -> Duration {
|
||||
step.timeout.unwrap_or(self.default_timeout)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,484 @@
|
||||
//! Workflow execution engine
|
||||
|
||||
use std::{collections::HashMap, sync::Arc, time::Duration};
|
||||
|
||||
use backoff::{backoff::Backoff, ExponentialBackoffBuilder};
|
||||
use chrono::Utc;
|
||||
use parking_lot::RwLock;
|
||||
use tokio::time::timeout;
|
||||
|
||||
use super::{
|
||||
definition::{StepDefinition, WorkflowDefinition},
|
||||
event::{EventBus, WorkflowEvent},
|
||||
state::WorkflowStateStore,
|
||||
types::*,
|
||||
};
|
||||
|
||||
/// Linear backoff implementation that increases delay by a fixed amount each retry
|
||||
struct LinearBackoff {
|
||||
current: Duration,
|
||||
increment: Duration,
|
||||
max: Duration,
|
||||
}
|
||||
|
||||
impl LinearBackoff {
|
||||
fn new(increment: Duration, max: Duration) -> Self {
|
||||
Self {
|
||||
current: increment,
|
||||
increment,
|
||||
max,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Backoff for LinearBackoff {
|
||||
fn next_backoff(&mut self) -> Option<Duration> {
|
||||
let next = self.current;
|
||||
self.current = (self.current + self.increment).min(self.max);
|
||||
Some(next)
|
||||
}
|
||||
|
||||
fn reset(&mut self) {
|
||||
self.current = self.increment;
|
||||
}
|
||||
}
|
||||
|
||||
/// Main workflow execution engine
|
||||
pub struct WorkflowEngine {
|
||||
definitions: Arc<RwLock<HashMap<WorkflowId, Arc<WorkflowDefinition>>>>,
|
||||
state_store: WorkflowStateStore,
|
||||
event_bus: Arc<EventBus>,
|
||||
}
|
||||
|
||||
impl WorkflowEngine {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
definitions: Arc::new(RwLock::new(HashMap::new())),
|
||||
state_store: WorkflowStateStore::new(),
|
||||
event_bus: Arc::new(EventBus::new()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Start a background task to periodically clean up old workflow states
|
||||
///
|
||||
/// This prevents unbounded memory growth by removing completed/failed workflows
|
||||
/// that are older than the specified TTL.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `ttl` - Time-to-live for terminal workflows (default: 1 hour)
|
||||
/// * `interval` - How often to run cleanup (default: 5 minutes)
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// A join handle for the cleanup task that can be used to stop it.
|
||||
pub fn start_cleanup_task(
|
||||
&self,
|
||||
ttl: Option<Duration>,
|
||||
interval: Option<Duration>,
|
||||
) -> tokio::task::JoinHandle<()> {
|
||||
let state_store = self.state_store.clone();
|
||||
let ttl = ttl.unwrap_or(Duration::from_secs(3600)); // 1 hour default
|
||||
let interval = interval.unwrap_or(Duration::from_secs(300)); // 5 minutes default
|
||||
|
||||
tokio::spawn(async move {
|
||||
let mut ticker = tokio::time::interval(interval);
|
||||
ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
|
||||
|
||||
loop {
|
||||
ticker.tick().await;
|
||||
state_store.cleanup_old_workflows(ttl);
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Register a workflow definition
|
||||
pub fn register_workflow(&self, definition: WorkflowDefinition) {
|
||||
let id = definition.id.clone();
|
||||
self.definitions.write().insert(id, Arc::new(definition));
|
||||
}
|
||||
|
||||
/// Get the event bus for subscribing to workflow events
|
||||
pub fn event_bus(&self) -> Arc<EventBus> {
|
||||
Arc::clone(&self.event_bus)
|
||||
}
|
||||
|
||||
/// Get the state store
|
||||
pub fn state_store(&self) -> &WorkflowStateStore {
|
||||
&self.state_store
|
||||
}
|
||||
|
||||
/// Start a new workflow instance
|
||||
pub async fn start_workflow(
|
||||
&self,
|
||||
definition_id: WorkflowId,
|
||||
context: WorkflowContext,
|
||||
) -> WorkflowResult<WorkflowInstanceId> {
|
||||
// Get workflow definition
|
||||
let definition = {
|
||||
let definitions = self.definitions.read();
|
||||
definitions
|
||||
.get(&definition_id)
|
||||
.cloned()
|
||||
.ok_or_else(|| WorkflowError::DefinitionNotFound(definition_id.clone()))?
|
||||
};
|
||||
|
||||
// Create new workflow instance
|
||||
let instance_id = context.instance_id;
|
||||
let mut state = WorkflowState::new(instance_id, definition_id.clone());
|
||||
state.status = WorkflowStatus::Running;
|
||||
state.context = context;
|
||||
|
||||
// Initialize step states
|
||||
for step in &definition.steps {
|
||||
state
|
||||
.step_states
|
||||
.insert(step.id.clone(), StepState::default());
|
||||
}
|
||||
|
||||
// Save initial state
|
||||
self.state_store.save(state)?;
|
||||
|
||||
// Emit workflow started event
|
||||
self.event_bus
|
||||
.publish(WorkflowEvent::WorkflowStarted {
|
||||
instance_id,
|
||||
definition_id,
|
||||
})
|
||||
.await;
|
||||
|
||||
// Execute workflow in background
|
||||
let engine = self.clone_for_execution();
|
||||
let def = Arc::clone(&definition);
|
||||
tokio::spawn(async move {
|
||||
if let Err(e) = engine.execute_workflow(instance_id, def).await {
|
||||
tracing::error!(instance_id = %instance_id, error = ?e, "Workflow execution failed");
|
||||
}
|
||||
});
|
||||
|
||||
Ok(instance_id)
|
||||
}
|
||||
|
||||
/// Execute a workflow (internal)
|
||||
async fn execute_workflow(
|
||||
&self,
|
||||
instance_id: WorkflowInstanceId,
|
||||
definition: Arc<WorkflowDefinition>,
|
||||
) -> WorkflowResult<()> {
|
||||
let start_time = std::time::Instant::now();
|
||||
|
||||
for step in &definition.steps {
|
||||
// Check if workflow was cancelled
|
||||
let state = self.state_store.load(instance_id)?;
|
||||
if state.status == WorkflowStatus::Cancelled {
|
||||
self.event_bus
|
||||
.publish(WorkflowEvent::WorkflowCancelled { instance_id })
|
||||
.await;
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// Execute step with retry
|
||||
match self
|
||||
.execute_step_with_retry(instance_id, step, &definition)
|
||||
.await
|
||||
{
|
||||
Ok(StepResult::Success) => {
|
||||
// Continue to next step
|
||||
}
|
||||
Ok(StepResult::Skip) => {
|
||||
// Step was skipped, continue to next
|
||||
continue;
|
||||
}
|
||||
Ok(StepResult::Failure) | Err(_) => {
|
||||
// Handle failure based on failure action
|
||||
match step.on_failure {
|
||||
FailureAction::FailWorkflow => {
|
||||
let error_msg = format!("Step {} failed", step.id);
|
||||
self.state_store.update(instance_id, |s| {
|
||||
s.status = WorkflowStatus::Failed;
|
||||
})?;
|
||||
|
||||
self.event_bus
|
||||
.publish(WorkflowEvent::WorkflowFailed {
|
||||
instance_id,
|
||||
failed_step: step.id.clone(),
|
||||
error: error_msg,
|
||||
})
|
||||
.await;
|
||||
|
||||
return Ok(());
|
||||
}
|
||||
FailureAction::ContinueNextStep => {
|
||||
// Mark step as skipped and continue
|
||||
self.state_store.update(instance_id, |s| {
|
||||
if let Some(step_state) = s.step_states.get_mut(&step.id) {
|
||||
step_state.status = StepStatus::Skipped;
|
||||
}
|
||||
})?;
|
||||
continue;
|
||||
}
|
||||
FailureAction::RetryIndefinitely => {
|
||||
// This should not happen as execute_step_with_retry handles it
|
||||
unreachable!("RetryIndefinitely should be handled in retry logic");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Workflow completed successfully
|
||||
self.state_store.update(instance_id, |s| {
|
||||
s.status = WorkflowStatus::Completed;
|
||||
})?;
|
||||
|
||||
let duration = start_time.elapsed();
|
||||
self.event_bus
|
||||
.publish(WorkflowEvent::WorkflowCompleted {
|
||||
instance_id,
|
||||
duration,
|
||||
})
|
||||
.await;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Execute a step with retry logic
|
||||
async fn execute_step_with_retry(
|
||||
&self,
|
||||
instance_id: WorkflowInstanceId,
|
||||
step: &StepDefinition,
|
||||
definition: &WorkflowDefinition,
|
||||
) -> WorkflowResult<StepResult> {
|
||||
let retry_policy = definition.get_retry_policy(step);
|
||||
let step_timeout = definition.get_timeout(step);
|
||||
|
||||
let mut attempt = 1;
|
||||
let max_attempts = if matches!(step.on_failure, FailureAction::RetryIndefinitely) {
|
||||
u32::MAX
|
||||
} else {
|
||||
retry_policy.max_attempts
|
||||
};
|
||||
|
||||
let mut backoff = Self::create_backoff(&retry_policy.backoff);
|
||||
|
||||
loop {
|
||||
// Check for cancellation before starting/retrying step
|
||||
{
|
||||
let state = self.state_store.load(instance_id)?;
|
||||
if state.status == WorkflowStatus::Cancelled {
|
||||
return Err(WorkflowError::Cancelled(instance_id));
|
||||
}
|
||||
}
|
||||
|
||||
// Update step state
|
||||
self.state_store.update(instance_id, |s| {
|
||||
s.current_step = Some(step.id.clone());
|
||||
if let Some(step_state) = s.step_states.get_mut(&step.id) {
|
||||
step_state.status = if attempt == 1 {
|
||||
StepStatus::Running
|
||||
} else {
|
||||
StepStatus::Retrying
|
||||
};
|
||||
step_state.attempt = attempt;
|
||||
step_state.started_at = Some(Utc::now());
|
||||
}
|
||||
})?;
|
||||
|
||||
// Emit step started event
|
||||
self.event_bus
|
||||
.publish(WorkflowEvent::StepStarted {
|
||||
instance_id,
|
||||
step_id: step.id.clone(),
|
||||
attempt,
|
||||
})
|
||||
.await;
|
||||
|
||||
// Get current context
|
||||
let mut context = self.state_store.load(instance_id)?.context;
|
||||
|
||||
// Execute step with timeout
|
||||
let step_start = std::time::Instant::now();
|
||||
let result = timeout(step_timeout, step.executor.execute(&mut context)).await;
|
||||
|
||||
let step_duration = step_start.elapsed();
|
||||
|
||||
// Save updated context
|
||||
self.state_store.update(instance_id, |s| {
|
||||
s.context = context.clone();
|
||||
})?;
|
||||
|
||||
match result {
|
||||
Ok(Ok(StepResult::Success)) => {
|
||||
// Step succeeded
|
||||
self.state_store.update(instance_id, |s| {
|
||||
if let Some(step_state) = s.step_states.get_mut(&step.id) {
|
||||
step_state.status = StepStatus::Succeeded;
|
||||
step_state.completed_at = Some(Utc::now());
|
||||
}
|
||||
})?;
|
||||
|
||||
self.event_bus
|
||||
.publish(WorkflowEvent::StepSucceeded {
|
||||
instance_id,
|
||||
step_id: step.id.clone(),
|
||||
duration: step_duration,
|
||||
})
|
||||
.await;
|
||||
|
||||
// Call on_success hook
|
||||
if let Err(e) = step.executor.on_success(&context).await {
|
||||
tracing::warn!(step_id = %step.id, error = ?e, "on_success hook failed");
|
||||
}
|
||||
|
||||
return Ok(StepResult::Success);
|
||||
}
|
||||
Ok(Ok(StepResult::Skip)) => {
|
||||
return Ok(StepResult::Skip);
|
||||
}
|
||||
Ok(Ok(StepResult::Failure)) | Ok(Err(_)) | Err(_) => {
|
||||
let (error_msg, should_retry) = match result {
|
||||
Ok(Err(e)) => {
|
||||
let msg = format!("{}", e);
|
||||
let retryable = step.executor.is_retryable(&e);
|
||||
(msg, retryable)
|
||||
}
|
||||
Err(_) => (
|
||||
format!("Step timeout after {:?}", step_timeout),
|
||||
true, // Timeouts are retryable
|
||||
),
|
||||
_ => ("Step failed".to_string(), false),
|
||||
};
|
||||
|
||||
let will_retry = should_retry && attempt < max_attempts;
|
||||
|
||||
// Update step state
|
||||
self.state_store.update(instance_id, |s| {
|
||||
if let Some(step_state) = s.step_states.get_mut(&step.id) {
|
||||
step_state.status = if will_retry {
|
||||
StepStatus::Retrying
|
||||
} else {
|
||||
StepStatus::Failed
|
||||
};
|
||||
step_state.last_error = Some(error_msg.clone());
|
||||
if !will_retry {
|
||||
step_state.completed_at = Some(Utc::now());
|
||||
}
|
||||
}
|
||||
})?;
|
||||
|
||||
// Emit step failed event
|
||||
self.event_bus
|
||||
.publish(WorkflowEvent::StepFailed {
|
||||
instance_id,
|
||||
step_id: step.id.clone(),
|
||||
error: error_msg.clone(),
|
||||
will_retry,
|
||||
})
|
||||
.await;
|
||||
|
||||
if will_retry {
|
||||
// Calculate backoff delay
|
||||
let delay = backoff
|
||||
.next_backoff()
|
||||
.unwrap_or_else(|| Duration::from_secs(1));
|
||||
|
||||
self.event_bus
|
||||
.publish(WorkflowEvent::StepRetrying {
|
||||
instance_id,
|
||||
step_id: step.id.clone(),
|
||||
attempt: attempt + 1,
|
||||
delay,
|
||||
})
|
||||
.await;
|
||||
|
||||
tokio::time::sleep(delay).await;
|
||||
attempt += 1;
|
||||
} else {
|
||||
// No more retries, call on_failure hook
|
||||
// Create a generic error for the hook
|
||||
let hook_error = WorkflowError::StepFailed {
|
||||
step_id: step.id.clone(),
|
||||
message: error_msg,
|
||||
};
|
||||
if let Err(hook_err) = step.executor.on_failure(&context, &hook_error).await
|
||||
{
|
||||
tracing::warn!(step_id = %step.id, error = ?hook_err, "on_failure hook failed");
|
||||
}
|
||||
|
||||
return Ok(StepResult::Failure);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a backoff instance from strategy
|
||||
fn create_backoff(strategy: &BackoffStrategy) -> Box<dyn Backoff + Send> {
|
||||
match strategy {
|
||||
BackoffStrategy::Fixed(duration) => {
|
||||
// For fixed backoff, use exponential with multiplier 1.0
|
||||
let backoff = ExponentialBackoffBuilder::new()
|
||||
.with_initial_interval(*duration)
|
||||
.with_multiplier(1.0)
|
||||
.with_max_interval(*duration)
|
||||
.with_max_elapsed_time(None)
|
||||
.build();
|
||||
Box::new(backoff)
|
||||
}
|
||||
BackoffStrategy::Exponential { base, max } => {
|
||||
let backoff = ExponentialBackoffBuilder::new()
|
||||
.with_initial_interval(*base)
|
||||
.with_max_interval(*max)
|
||||
.with_max_elapsed_time(None)
|
||||
.build();
|
||||
Box::new(backoff)
|
||||
}
|
||||
BackoffStrategy::Linear { increment, max } => {
|
||||
// Use proper linear backoff: increment, 2*increment, 3*increment, ...
|
||||
Box::new(LinearBackoff::new(*increment, *max))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Cancel a running workflow
|
||||
pub async fn cancel_workflow(&self, instance_id: WorkflowInstanceId) -> WorkflowResult<()> {
|
||||
self.state_store.update(instance_id, |s| {
|
||||
s.status = WorkflowStatus::Cancelled;
|
||||
})?;
|
||||
|
||||
self.event_bus
|
||||
.publish(WorkflowEvent::WorkflowCancelled { instance_id })
|
||||
.await;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Get workflow status
|
||||
pub fn get_status(&self, instance_id: WorkflowInstanceId) -> WorkflowResult<WorkflowState> {
|
||||
self.state_store.load(instance_id)
|
||||
}
|
||||
|
||||
/// Clone engine for async execution
|
||||
fn clone_for_execution(&self) -> Self {
|
||||
Self {
|
||||
definitions: Arc::clone(&self.definitions),
|
||||
state_store: self.state_store.clone(),
|
||||
event_bus: Arc::clone(&self.event_bus),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for WorkflowEngine {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for WorkflowEngine {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("WorkflowEngine")
|
||||
.field("definitions_count", &self.definitions.read().len())
|
||||
.field("state_count", &self.state_store.count())
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
//! Workflow event system for observability and monitoring
|
||||
|
||||
use std::{sync::Arc, time::Duration};
|
||||
|
||||
use async_trait::async_trait;
|
||||
use tokio::sync::RwLock;
|
||||
use tracing::{error, info, warn};
|
||||
|
||||
use super::types::{StepId, WorkflowId, WorkflowInstanceId};
|
||||
|
||||
/// Events emitted by the workflow engine
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum WorkflowEvent {
|
||||
WorkflowStarted {
|
||||
instance_id: WorkflowInstanceId,
|
||||
definition_id: WorkflowId,
|
||||
},
|
||||
StepStarted {
|
||||
instance_id: WorkflowInstanceId,
|
||||
step_id: StepId,
|
||||
attempt: u32,
|
||||
},
|
||||
StepSucceeded {
|
||||
instance_id: WorkflowInstanceId,
|
||||
step_id: StepId,
|
||||
duration: Duration,
|
||||
},
|
||||
StepFailed {
|
||||
instance_id: WorkflowInstanceId,
|
||||
step_id: StepId,
|
||||
error: String,
|
||||
will_retry: bool,
|
||||
},
|
||||
StepRetrying {
|
||||
instance_id: WorkflowInstanceId,
|
||||
step_id: StepId,
|
||||
attempt: u32,
|
||||
delay: Duration,
|
||||
},
|
||||
WorkflowCompleted {
|
||||
instance_id: WorkflowInstanceId,
|
||||
duration: Duration,
|
||||
},
|
||||
WorkflowFailed {
|
||||
instance_id: WorkflowInstanceId,
|
||||
failed_step: StepId,
|
||||
error: String,
|
||||
},
|
||||
WorkflowCancelled {
|
||||
instance_id: WorkflowInstanceId,
|
||||
},
|
||||
}
|
||||
|
||||
/// Trait for subscribing to workflow events
|
||||
#[async_trait]
|
||||
pub trait EventSubscriber: Send + Sync {
|
||||
async fn on_event(&self, event: &WorkflowEvent);
|
||||
}
|
||||
|
||||
/// Event bus for publishing and subscribing to workflow events
|
||||
pub struct EventBus {
|
||||
subscribers: Arc<RwLock<Vec<Arc<dyn EventSubscriber>>>>,
|
||||
}
|
||||
|
||||
impl EventBus {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
subscribers: Arc::new(RwLock::new(Vec::new())),
|
||||
}
|
||||
}
|
||||
|
||||
/// Subscribe to workflow events
|
||||
pub async fn subscribe(&self, subscriber: Arc<dyn EventSubscriber>) {
|
||||
self.subscribers.write().await.push(subscriber);
|
||||
}
|
||||
|
||||
/// Publish an event to all subscribers
|
||||
pub async fn publish(&self, event: WorkflowEvent) {
|
||||
let subscribers = self.subscribers.read().await;
|
||||
for subscriber in subscribers.iter() {
|
||||
subscriber.on_event(&event).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for EventBus {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
/// Logging subscriber that logs events using tracing
|
||||
pub struct LoggingSubscriber;
|
||||
|
||||
#[async_trait]
|
||||
impl EventSubscriber for LoggingSubscriber {
|
||||
async fn on_event(&self, event: &WorkflowEvent) {
|
||||
match event {
|
||||
WorkflowEvent::WorkflowStarted {
|
||||
instance_id,
|
||||
definition_id,
|
||||
} => {
|
||||
info!(
|
||||
instance_id = %instance_id,
|
||||
definition_id = %definition_id,
|
||||
"Workflow started"
|
||||
);
|
||||
}
|
||||
WorkflowEvent::StepStarted {
|
||||
instance_id,
|
||||
step_id,
|
||||
attempt,
|
||||
} => {
|
||||
info!(
|
||||
instance_id = %instance_id,
|
||||
step_id = %step_id,
|
||||
attempt = attempt,
|
||||
"Step started"
|
||||
);
|
||||
}
|
||||
WorkflowEvent::StepSucceeded {
|
||||
instance_id,
|
||||
step_id,
|
||||
duration,
|
||||
} => {
|
||||
info!(
|
||||
instance_id = %instance_id,
|
||||
step_id = %step_id,
|
||||
duration_ms = duration.as_millis(),
|
||||
"Step succeeded"
|
||||
);
|
||||
}
|
||||
WorkflowEvent::StepFailed {
|
||||
instance_id,
|
||||
step_id,
|
||||
error,
|
||||
will_retry,
|
||||
} => {
|
||||
warn!(
|
||||
instance_id = %instance_id,
|
||||
step_id = %step_id,
|
||||
error = error,
|
||||
will_retry = will_retry,
|
||||
"Step failed"
|
||||
);
|
||||
}
|
||||
WorkflowEvent::StepRetrying {
|
||||
instance_id,
|
||||
step_id,
|
||||
attempt,
|
||||
delay,
|
||||
} => {
|
||||
info!(
|
||||
instance_id = %instance_id,
|
||||
step_id = %step_id,
|
||||
attempt = attempt,
|
||||
delay_ms = delay.as_millis(),
|
||||
"Step retrying"
|
||||
);
|
||||
}
|
||||
WorkflowEvent::WorkflowCompleted {
|
||||
instance_id,
|
||||
duration,
|
||||
} => {
|
||||
info!(
|
||||
instance_id = %instance_id,
|
||||
duration_ms = duration.as_millis(),
|
||||
"Workflow completed"
|
||||
);
|
||||
}
|
||||
WorkflowEvent::WorkflowFailed {
|
||||
instance_id,
|
||||
failed_step,
|
||||
error,
|
||||
} => {
|
||||
error!(
|
||||
instance_id = %instance_id,
|
||||
failed_step = %failed_step,
|
||||
error = error,
|
||||
"Workflow failed"
|
||||
);
|
||||
}
|
||||
WorkflowEvent::WorkflowCancelled { instance_id } => {
|
||||
info!(instance_id = %instance_id, "Workflow cancelled");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
//! Step executor trait and implementations
|
||||
|
||||
use async_trait::async_trait;
|
||||
|
||||
use super::types::{StepResult, WorkflowContext, WorkflowError, WorkflowResult};
|
||||
|
||||
/// Trait for executing individual workflow steps
|
||||
#[async_trait]
|
||||
pub trait StepExecutor: Send + Sync {
|
||||
/// Execute the step with the given context
|
||||
async fn execute(&self, context: &mut WorkflowContext) -> WorkflowResult<StepResult>;
|
||||
|
||||
/// Check if an error is retry-able
|
||||
///
|
||||
/// Override this method to customize which errors should trigger retries.
|
||||
/// By default, all errors are considered retry-able.
|
||||
fn is_retryable(&self, _error: &WorkflowError) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
/// Called when the step succeeds
|
||||
///
|
||||
/// This hook allows steps to perform cleanup or additional actions
|
||||
/// after successful execution.
|
||||
async fn on_success(&self, _context: &WorkflowContext) -> WorkflowResult<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Called when the step fails after all retries
|
||||
///
|
||||
/// This hook allows steps to perform cleanup or compensation logic
|
||||
/// when the step cannot complete successfully.
|
||||
async fn on_failure(
|
||||
&self,
|
||||
_context: &WorkflowContext,
|
||||
_error: &WorkflowError,
|
||||
) -> WorkflowResult<()> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Simple function-based step executor
|
||||
pub struct FunctionStep<F>
|
||||
where
|
||||
F: Fn(
|
||||
&mut WorkflowContext,
|
||||
) -> std::pin::Pin<
|
||||
Box<dyn std::future::Future<Output = WorkflowResult<StepResult>> + Send + '_>,
|
||||
> + Send
|
||||
+ Sync,
|
||||
{
|
||||
func: F,
|
||||
}
|
||||
|
||||
impl<F> FunctionStep<F>
|
||||
where
|
||||
F: Fn(
|
||||
&mut WorkflowContext,
|
||||
) -> std::pin::Pin<
|
||||
Box<dyn std::future::Future<Output = WorkflowResult<StepResult>> + Send + '_>,
|
||||
> + Send
|
||||
+ Sync,
|
||||
{
|
||||
pub fn new(func: F) -> Self {
|
||||
Self { func }
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<F> StepExecutor for FunctionStep<F>
|
||||
where
|
||||
F: Fn(
|
||||
&mut WorkflowContext,
|
||||
) -> std::pin::Pin<
|
||||
Box<dyn std::future::Future<Output = WorkflowResult<StepResult>> + Send + '_>,
|
||||
> + Send
|
||||
+ Sync,
|
||||
{
|
||||
async fn execute(&self, context: &mut WorkflowContext) -> WorkflowResult<StepResult> {
|
||||
(self.func)(context).await
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::core::workflow::types::WorkflowInstanceId;
|
||||
|
||||
struct TestStep {
|
||||
should_succeed: bool,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl StepExecutor for TestStep {
|
||||
async fn execute(&self, _context: &mut WorkflowContext) -> WorkflowResult<StepResult> {
|
||||
if self.should_succeed {
|
||||
Ok(StepResult::Success)
|
||||
} else {
|
||||
Err(WorkflowError::StepFailed {
|
||||
step_id: crate::core::workflow::types::StepId::new("test"),
|
||||
message: "test error".to_string(),
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_step_executor_success() {
|
||||
let step = TestStep {
|
||||
should_succeed: true,
|
||||
};
|
||||
let mut context = WorkflowContext::new(WorkflowInstanceId::new());
|
||||
|
||||
let result = step.execute(&mut context).await;
|
||||
assert!(result.is_ok());
|
||||
assert_eq!(result.unwrap(), StepResult::Success);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_step_executor_failure() {
|
||||
let step = TestStep {
|
||||
should_succeed: false,
|
||||
};
|
||||
let mut context = WorkflowContext::new(WorkflowInstanceId::new());
|
||||
|
||||
let result = step.execute(&mut context).await;
|
||||
assert!(result.is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
//! Workflow engine for managing multi-step operations
|
||||
|
||||
mod definition;
|
||||
mod engine;
|
||||
mod event;
|
||||
mod executor;
|
||||
mod state;
|
||||
pub mod steps;
|
||||
pub mod types;
|
||||
|
||||
// Re-export main types
|
||||
pub use definition::{StepDefinition, WorkflowDefinition};
|
||||
pub use engine::WorkflowEngine;
|
||||
pub use event::{EventBus, EventSubscriber, LoggingSubscriber, WorkflowEvent};
|
||||
pub use executor::{FunctionStep, StepExecutor};
|
||||
pub use state::WorkflowStateStore;
|
||||
pub use steps::{
|
||||
create_external_worker_registration_workflow, create_mcp_registration_workflow,
|
||||
create_wasm_module_registration_workflow, create_wasm_module_removal_workflow,
|
||||
create_worker_registration_workflow, create_worker_removal_workflow,
|
||||
};
|
||||
pub use types::*;
|
||||
@@ -0,0 +1,175 @@
|
||||
//! Workflow state management
|
||||
|
||||
use std::{collections::HashMap, sync::Arc};
|
||||
|
||||
use parking_lot::RwLock;
|
||||
|
||||
use super::types::{
|
||||
WorkflowError, WorkflowInstanceId, WorkflowResult, WorkflowState, WorkflowStatus,
|
||||
};
|
||||
|
||||
/// In-memory state storage for workflow instances
|
||||
#[derive(Clone)]
|
||||
pub struct WorkflowStateStore {
|
||||
states: Arc<RwLock<HashMap<WorkflowInstanceId, WorkflowState>>>,
|
||||
}
|
||||
|
||||
impl WorkflowStateStore {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
states: Arc::new(RwLock::new(HashMap::new())),
|
||||
}
|
||||
}
|
||||
|
||||
/// Save workflow state
|
||||
///
|
||||
/// # Warning
|
||||
///
|
||||
/// This emits a warning if the workflow context contains unserializable data,
|
||||
/// which would be lost if state persistence is later implemented.
|
||||
pub fn save(&self, state: WorkflowState) -> WorkflowResult<()> {
|
||||
if state.context.has_unserializable_data() {
|
||||
tracing::warn!(
|
||||
instance_id = %state.instance_id,
|
||||
data_count = state.context.data_len(),
|
||||
"Saving workflow state with {} unserializable context entries. \
|
||||
This data cannot be persisted and will be lost on restart.",
|
||||
state.context.data_len()
|
||||
);
|
||||
}
|
||||
self.states.write().insert(state.instance_id, state);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Load workflow state by instance ID
|
||||
pub fn load(&self, instance_id: WorkflowInstanceId) -> WorkflowResult<WorkflowState> {
|
||||
self.states
|
||||
.read()
|
||||
.get(&instance_id)
|
||||
.cloned()
|
||||
.ok_or(WorkflowError::NotFound(instance_id))
|
||||
}
|
||||
|
||||
/// List all active workflows (Running or Pending)
|
||||
pub fn list_active(&self) -> WorkflowResult<Vec<WorkflowState>> {
|
||||
let states = self.states.read();
|
||||
Ok(states
|
||||
.values()
|
||||
.filter(|s| matches!(s.status, WorkflowStatus::Running | WorkflowStatus::Pending))
|
||||
.cloned()
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// List all workflows
|
||||
pub fn list_all(&self) -> WorkflowResult<Vec<WorkflowState>> {
|
||||
let states = self.states.read();
|
||||
Ok(states.values().cloned().collect())
|
||||
}
|
||||
|
||||
/// Delete workflow state
|
||||
pub fn delete(&self, instance_id: WorkflowInstanceId) -> WorkflowResult<()> {
|
||||
self.states.write().remove(&instance_id);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Update workflow state using a closure
|
||||
pub fn update<F>(&self, instance_id: WorkflowInstanceId, f: F) -> WorkflowResult<()>
|
||||
where
|
||||
F: FnOnce(&mut WorkflowState),
|
||||
{
|
||||
let mut states = self.states.write();
|
||||
let state = states
|
||||
.get_mut(&instance_id)
|
||||
.ok_or(WorkflowError::NotFound(instance_id))?;
|
||||
f(state);
|
||||
state.updated_at = chrono::Utc::now();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Get count of workflows by status
|
||||
pub fn count_by_status(&self, status: WorkflowStatus) -> usize {
|
||||
self.states
|
||||
.read()
|
||||
.values()
|
||||
.filter(|s| s.status == status)
|
||||
.count()
|
||||
}
|
||||
|
||||
/// Get total count of all workflows
|
||||
pub fn count(&self) -> usize {
|
||||
self.states.read().len()
|
||||
}
|
||||
|
||||
/// Clean up old completed/failed/cancelled workflows beyond a time threshold
|
||||
///
|
||||
/// This prevents unbounded memory growth by removing workflow states that
|
||||
/// have been in a terminal state (Completed, Failed, Cancelled) for longer
|
||||
/// than the specified TTL (time-to-live).
|
||||
///
|
||||
/// Active workflows (Running, Pending, Paused) are never cleaned up.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `ttl` - Time-to-live for terminal workflows. Workflows in terminal states
|
||||
/// older than this will be removed.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// The number of workflow states removed.
|
||||
pub fn cleanup_old_workflows(&self, ttl: std::time::Duration) -> usize {
|
||||
let now = chrono::Utc::now();
|
||||
let mut states = self.states.write();
|
||||
let initial_count = states.len();
|
||||
|
||||
states.retain(|_, state| {
|
||||
// Keep active workflows
|
||||
if matches!(
|
||||
state.status,
|
||||
WorkflowStatus::Running | WorkflowStatus::Pending | WorkflowStatus::Paused
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// For terminal workflows, check age
|
||||
let age = now
|
||||
.signed_duration_since(state.updated_at)
|
||||
.to_std()
|
||||
.unwrap_or_default();
|
||||
age < ttl
|
||||
});
|
||||
|
||||
let removed_count = initial_count - states.len();
|
||||
if removed_count > 0 {
|
||||
tracing::info!(
|
||||
removed = removed_count,
|
||||
remaining = states.len(),
|
||||
"Cleaned up old workflow states"
|
||||
);
|
||||
}
|
||||
removed_count
|
||||
}
|
||||
|
||||
/// Clean up a specific completed workflow immediately
|
||||
///
|
||||
/// This is useful for cleaning up workflows right after they complete
|
||||
/// when you know they won't be queried again.
|
||||
pub fn cleanup_if_terminal(&self, instance_id: WorkflowInstanceId) -> bool {
|
||||
let mut states = self.states.write();
|
||||
if let Some(state) = states.get(&instance_id) {
|
||||
if matches!(
|
||||
state.status,
|
||||
WorkflowStatus::Completed | WorkflowStatus::Failed | WorkflowStatus::Cancelled
|
||||
) {
|
||||
states.remove(&instance_id);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for WorkflowStateStore {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,629 @@
|
||||
//! External worker registration workflow steps
|
||||
//!
|
||||
//! This workflow handles registration of external API endpoints (OpenAI, xAI, Anthropic, etc.)
|
||||
//!
|
||||
//! Key features:
|
||||
//! - Fetches models from /v1/models endpoint
|
||||
//! - Groups dated model variants under base model names (e.g., gpt-4o, gpt-4o-2024-08-06)
|
||||
//! - Infers ModelType from model ID patterns (LLM, embedding, image gen, audio, etc.)
|
||||
//!
|
||||
//! Workflow order:
|
||||
//! 1. DiscoverModels - Fetch available models from /v1/models endpoint
|
||||
//! 2. CreateExternalWorkers - Build worker objects for each discovered model
|
||||
//! 3. RegisterWorkers - Register workers in registry
|
||||
//! 4. UpdatePolicies - Update policy registry
|
||||
//! 5. ActivateWorkers - Mark workers as healthy
|
||||
|
||||
use std::{collections::HashMap, sync::Arc, time::Duration};
|
||||
|
||||
use async_trait::async_trait;
|
||||
use once_cell::sync::Lazy;
|
||||
use regex::Regex;
|
||||
use reqwest::Client;
|
||||
use serde::Deserialize;
|
||||
use tracing::{debug, info};
|
||||
|
||||
use crate::{
|
||||
app_context::AppContext,
|
||||
core::{
|
||||
model_card::{ModelCard, ProviderType},
|
||||
model_type::ModelType,
|
||||
workflow::*,
|
||||
BasicWorkerBuilder, CircuitBreakerConfig, ConnectionMode, HealthConfig, RuntimeType,
|
||||
Worker, WorkerType,
|
||||
},
|
||||
protocols::worker_spec::WorkerConfigRequest,
|
||||
};
|
||||
|
||||
// HTTP client for API calls
|
||||
static HTTP_CLIENT: Lazy<Client> = Lazy::new(|| {
|
||||
Client::builder()
|
||||
.timeout(Duration::from_secs(30))
|
||||
.build()
|
||||
.expect("Failed to create HTTP client")
|
||||
});
|
||||
|
||||
// Regex to strip date suffix: -YYYY-MM-DD or -YYYY-MM
|
||||
static DATE_SUFFIX_PATTERN: Lazy<Regex> =
|
||||
Lazy::new(|| Regex::new(r"-\d{4}-\d{2}(-\d{2})?$").expect("Invalid date regex"));
|
||||
|
||||
// ============================================================================
|
||||
// Model Discovery Types
|
||||
// ============================================================================
|
||||
|
||||
/// OpenAI /v1/models response format
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct ModelsResponse {
|
||||
pub data: Vec<ModelInfo>,
|
||||
#[serde(default)]
|
||||
pub object: String,
|
||||
}
|
||||
|
||||
/// Individual model information from /v1/models
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct ModelInfo {
|
||||
pub id: String,
|
||||
#[serde(default)]
|
||||
pub object: String,
|
||||
#[serde(default)]
|
||||
pub created: Option<u64>,
|
||||
#[serde(default)]
|
||||
pub owned_by: Option<String>,
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Model Discovery Functions
|
||||
// ============================================================================
|
||||
|
||||
/// Group models by base name (stripping date suffixes) and create ModelCards with aliases.
|
||||
///
|
||||
/// # Example
|
||||
/// Input: `["gpt-4o", "gpt-4o-2024-05-13", "gpt-4o-2024-08-06", "gpt-4o-2024-11-20"]`
|
||||
/// Output: `ModelCard { id: "gpt-4o", aliases: ["gpt-4o-2024-05-13", "gpt-4o-2024-08-06", "gpt-4o-2024-11-20"] }`
|
||||
pub fn group_models_into_cards(models: Vec<ModelInfo>) -> Vec<ModelCard> {
|
||||
// Group model IDs by base name (with date stripped)
|
||||
let mut groups: HashMap<String, Vec<String>> = HashMap::new();
|
||||
for model in &models {
|
||||
let base = DATE_SUFFIX_PATTERN.replace(&model.id, "").to_string();
|
||||
groups.entry(base).or_default().push(model.id.clone());
|
||||
}
|
||||
|
||||
// Create ModelCard for each group
|
||||
groups
|
||||
.into_values()
|
||||
.map(|mut variants| {
|
||||
// Sort: shortest first (base name), then alphabetically
|
||||
variants.sort_by(|a, b| a.len().cmp(&b.len()).then_with(|| a.cmp(b)));
|
||||
|
||||
let primary_id = variants.remove(0); // shortest = primary ID
|
||||
let aliases = variants; // rest = aliases
|
||||
|
||||
let model_type = infer_model_type_from_id(&primary_id);
|
||||
let provider = infer_provider_from_id(&primary_id);
|
||||
|
||||
let mut card = ModelCard::new(&primary_id)
|
||||
.with_aliases(aliases)
|
||||
.with_model_type(model_type);
|
||||
|
||||
if let Some(p) = provider {
|
||||
card = card.with_provider(p);
|
||||
}
|
||||
|
||||
card
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Infer ModelType from model ID string.
|
||||
///
|
||||
/// This function analyzes the model ID to determine what type of model it is
|
||||
/// (LLM, embedding, image generation, audio, etc.).
|
||||
pub fn infer_model_type_from_id(id: &str) -> ModelType {
|
||||
let id_lower = id.to_lowercase();
|
||||
|
||||
// Embedding models
|
||||
if id_lower.contains("embed") || id_lower.contains("ada-002") {
|
||||
return ModelType::EMBED_MODEL;
|
||||
}
|
||||
|
||||
// Rerank models
|
||||
if id_lower.contains("rerank") {
|
||||
return ModelType::RERANK_MODEL;
|
||||
}
|
||||
|
||||
// Image generation models (DALL-E, Sora, gpt-image)
|
||||
if id_lower.starts_with("dall-e")
|
||||
|| id_lower.starts_with("sora")
|
||||
|| (id_lower.contains("image") && !id_lower.contains("vision"))
|
||||
{
|
||||
return ModelType::IMAGE_MODEL;
|
||||
}
|
||||
|
||||
// Audio models (TTS, Whisper, realtime, audio)
|
||||
if id_lower.starts_with("tts")
|
||||
|| id_lower.starts_with("whisper")
|
||||
|| id_lower.contains("audio")
|
||||
|| id_lower.contains("realtime")
|
||||
|| id_lower.contains("transcribe")
|
||||
{
|
||||
return ModelType::AUDIO_MODEL;
|
||||
}
|
||||
|
||||
// Moderation models
|
||||
if id_lower.contains("moderation") {
|
||||
return ModelType::MODERATION_MODEL;
|
||||
}
|
||||
|
||||
// Vision LLM (models with vision capability)
|
||||
// gpt-4o, gpt-4-vision, etc.
|
||||
if id_lower.contains("vision") || id_lower.contains("4o") {
|
||||
return ModelType::VISION_LLM;
|
||||
}
|
||||
|
||||
// Reasoning models (o1, o3, etc.)
|
||||
if id_lower.starts_with("o1") || id_lower.starts_with("o3") {
|
||||
return ModelType::REASONING_LLM;
|
||||
}
|
||||
|
||||
// Default to standard LLM
|
||||
ModelType::LLM
|
||||
}
|
||||
|
||||
/// Infer provider type from model ID string.
|
||||
///
|
||||
/// Returns `None` for models that don't clearly indicate a provider.
|
||||
fn infer_provider_from_id(id: &str) -> Option<ProviderType> {
|
||||
let id_lower = id.to_lowercase();
|
||||
|
||||
// OpenAI models
|
||||
if id_lower.starts_with("gpt")
|
||||
|| id_lower.starts_with("o1")
|
||||
|| id_lower.starts_with("o3")
|
||||
|| id_lower.starts_with("dall-e")
|
||||
|| id_lower.starts_with("whisper")
|
||||
|| id_lower.starts_with("tts")
|
||||
|| id_lower.starts_with("text-embedding")
|
||||
|| id_lower.starts_with("babbage")
|
||||
|| id_lower.starts_with("davinci")
|
||||
|| id_lower.contains("omni")
|
||||
{
|
||||
return Some(ProviderType::OpenAI);
|
||||
}
|
||||
|
||||
// xAI/Grok models
|
||||
if id_lower.starts_with("grok") {
|
||||
return Some(ProviderType::XAI);
|
||||
}
|
||||
|
||||
// Anthropic Claude models
|
||||
if id_lower.starts_with("claude") {
|
||||
return Some(ProviderType::Anthropic);
|
||||
}
|
||||
|
||||
// Google Gemini models
|
||||
if id_lower.starts_with("gemini") {
|
||||
return Some(ProviderType::Gemini);
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Workflow Steps
|
||||
// ============================================================================
|
||||
|
||||
/// Step 1: Discover models from external /v1/models endpoint
|
||||
pub struct DiscoverModelsStep;
|
||||
|
||||
#[async_trait]
|
||||
impl StepExecutor for DiscoverModelsStep {
|
||||
async fn execute(&self, context: &mut WorkflowContext) -> WorkflowResult<StepResult> {
|
||||
let config: Arc<WorkerConfigRequest> = context
|
||||
.get("worker_config")
|
||||
.ok_or_else(|| WorkflowError::ContextValueNotFound("worker_config".to_string()))?;
|
||||
|
||||
// If no API key is provided, skip model discovery and use wildcard mode.
|
||||
if config.api_key.as_ref().is_none_or(|k| k.is_empty()) {
|
||||
info!(
|
||||
"No API key provided for {} - using wildcard mode (accepts any model). \
|
||||
User's Authorization header will be forwarded to backend.",
|
||||
config.url
|
||||
);
|
||||
context.set::<Vec<ModelCard>>("model_cards", vec![]);
|
||||
return Ok(StepResult::Success);
|
||||
}
|
||||
|
||||
debug!("Discovering models from external endpoint {}", config.url);
|
||||
|
||||
let model_cards = fetch_models(&config.url, config.api_key.as_deref())
|
||||
.await
|
||||
.map_err(|e| WorkflowError::StepFailed {
|
||||
step_id: StepId::new("discover_models"),
|
||||
message: format!("Failed to discover models from {}: {}", config.url, e),
|
||||
})?;
|
||||
|
||||
if model_cards.is_empty() {
|
||||
return Err(WorkflowError::StepFailed {
|
||||
step_id: StepId::new("discover_models"),
|
||||
message: format!("No models discovered from {}", config.url),
|
||||
});
|
||||
}
|
||||
|
||||
info!(
|
||||
"Discovered {} models from {}: {:?}",
|
||||
model_cards.len(),
|
||||
config.url,
|
||||
model_cards.iter().map(|c| &c.id).collect::<Vec<_>>()
|
||||
);
|
||||
|
||||
context.set("model_cards", model_cards);
|
||||
Ok(StepResult::Success)
|
||||
}
|
||||
|
||||
fn is_retryable(&self, _error: &WorkflowError) -> bool {
|
||||
true // Network issues are retryable
|
||||
}
|
||||
}
|
||||
|
||||
/// Fetch models from /v1/models endpoint
|
||||
async fn fetch_models(url: &str, api_key: Option<&str>) -> Result<Vec<ModelCard>, String> {
|
||||
let base_url = url.trim_end_matches('/');
|
||||
let models_url = format!("{}/v1/models", base_url);
|
||||
|
||||
let mut req = HTTP_CLIENT.get(&models_url);
|
||||
if let Some(key) = api_key {
|
||||
req = req.bearer_auth(key);
|
||||
}
|
||||
|
||||
let response = req
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| format!("Failed to connect to {}: {}", models_url, e))?;
|
||||
|
||||
if !response.status().is_success() {
|
||||
return Err(format!(
|
||||
"Server returned status {} from {}",
|
||||
response.status(),
|
||||
models_url
|
||||
));
|
||||
}
|
||||
|
||||
let models_response: ModelsResponse = response
|
||||
.json()
|
||||
.await
|
||||
.map_err(|e| format!("Failed to parse models response: {}", e))?;
|
||||
|
||||
debug!(
|
||||
"Fetched {} raw models from {}",
|
||||
models_response.data.len(),
|
||||
url
|
||||
);
|
||||
|
||||
// Group models into cards (e.g., gpt-4o-2024-08-06 → gpt-4o with aliases)
|
||||
let model_cards = group_models_into_cards(models_response.data);
|
||||
|
||||
debug!(
|
||||
"Grouped into {} model cards with aliases",
|
||||
model_cards.len()
|
||||
);
|
||||
|
||||
Ok(model_cards)
|
||||
}
|
||||
|
||||
/// Step 2: Create worker objects for each discovered model
|
||||
pub struct CreateExternalWorkersStep;
|
||||
|
||||
#[async_trait]
|
||||
impl StepExecutor for CreateExternalWorkersStep {
|
||||
async fn execute(&self, context: &mut WorkflowContext) -> WorkflowResult<StepResult> {
|
||||
let config: Arc<WorkerConfigRequest> = context
|
||||
.get("worker_config")
|
||||
.ok_or_else(|| WorkflowError::ContextValueNotFound("worker_config".to_string()))?;
|
||||
let app_context: Arc<AppContext> = context
|
||||
.get("app_context")
|
||||
.ok_or_else(|| WorkflowError::ContextValueNotFound("app_context".to_string()))?;
|
||||
let model_cards: Arc<Vec<ModelCard>> = context
|
||||
.get("model_cards")
|
||||
.ok_or_else(|| WorkflowError::ContextValueNotFound("model_cards".to_string()))?;
|
||||
|
||||
// Build configs from router settings
|
||||
let circuit_breaker_config = {
|
||||
let cfg = app_context.router_config.effective_circuit_breaker_config();
|
||||
CircuitBreakerConfig {
|
||||
failure_threshold: cfg.failure_threshold,
|
||||
success_threshold: cfg.success_threshold,
|
||||
timeout_duration: Duration::from_secs(cfg.timeout_duration_secs),
|
||||
window_duration: Duration::from_secs(cfg.window_duration_secs),
|
||||
}
|
||||
};
|
||||
|
||||
let health_config = {
|
||||
let cfg = &app_context.router_config.health_check;
|
||||
HealthConfig {
|
||||
timeout_secs: cfg.timeout_secs,
|
||||
check_interval_secs: cfg.check_interval_secs,
|
||||
endpoint: cfg.endpoint.clone(),
|
||||
failure_threshold: cfg.failure_threshold,
|
||||
success_threshold: cfg.success_threshold,
|
||||
}
|
||||
};
|
||||
|
||||
// Build labels
|
||||
let mut labels = config.labels.clone();
|
||||
if let Some(priority) = config.priority {
|
||||
labels.insert("priority".to_string(), priority.to_string());
|
||||
}
|
||||
if let Some(cost) = config.cost {
|
||||
labels.insert("cost".to_string(), cost.to_string());
|
||||
}
|
||||
|
||||
// Normalize URL (ensure https:// for external APIs)
|
||||
let normalized_url = normalize_external_url(&config.url);
|
||||
|
||||
let mut workers = Vec::new();
|
||||
|
||||
// Handle wildcard mode: create a single worker with empty models list
|
||||
if model_cards.is_empty() {
|
||||
debug!("Creating wildcard worker (no models) for {}", config.url);
|
||||
|
||||
let mut builder = BasicWorkerBuilder::new(normalized_url.clone())
|
||||
.models(vec![]) // Empty models = accepts any model
|
||||
.worker_type(WorkerType::Regular)
|
||||
.connection_mode(ConnectionMode::Http)
|
||||
.runtime_type(RuntimeType::External)
|
||||
.circuit_breaker_config(circuit_breaker_config.clone())
|
||||
.health_config(health_config.clone());
|
||||
|
||||
if let Some(ref api_key) = config.api_key {
|
||||
builder = builder.api_key(api_key.clone());
|
||||
}
|
||||
|
||||
if !labels.is_empty() {
|
||||
builder = builder.labels(labels.clone());
|
||||
}
|
||||
|
||||
let worker = Arc::new(builder.build()) as Arc<dyn Worker>;
|
||||
worker.set_healthy(false);
|
||||
|
||||
info!(
|
||||
"Created wildcard worker at {} (accepts any model, user auth forwarded)",
|
||||
normalized_url
|
||||
);
|
||||
|
||||
workers.push(worker);
|
||||
} else {
|
||||
debug!(
|
||||
"Creating {} external workers for {}",
|
||||
model_cards.len(),
|
||||
config.url
|
||||
);
|
||||
|
||||
// Create a worker for each model
|
||||
for model_card in model_cards.iter() {
|
||||
let mut builder = BasicWorkerBuilder::new(normalized_url.clone())
|
||||
.model(model_card.clone())
|
||||
.worker_type(WorkerType::Regular)
|
||||
.connection_mode(ConnectionMode::Http)
|
||||
.runtime_type(RuntimeType::External)
|
||||
.circuit_breaker_config(circuit_breaker_config.clone())
|
||||
.health_config(health_config.clone());
|
||||
|
||||
if let Some(ref api_key) = config.api_key {
|
||||
builder = builder.api_key(api_key.clone());
|
||||
}
|
||||
|
||||
if !labels.is_empty() {
|
||||
builder = builder.labels(labels.clone());
|
||||
}
|
||||
|
||||
let worker = Arc::new(builder.build()) as Arc<dyn Worker>;
|
||||
worker.set_healthy(false);
|
||||
|
||||
debug!(
|
||||
"Created external worker for model {} at {}",
|
||||
model_card.id, normalized_url
|
||||
);
|
||||
|
||||
workers.push(worker);
|
||||
}
|
||||
|
||||
info!(
|
||||
"Created {} external workers from {}",
|
||||
workers.len(),
|
||||
config.url
|
||||
);
|
||||
}
|
||||
|
||||
context.set("workers", workers);
|
||||
context.set("labels", labels);
|
||||
Ok(StepResult::Success)
|
||||
}
|
||||
|
||||
fn is_retryable(&self, _error: &WorkflowError) -> bool {
|
||||
false // Creation failures are config issues
|
||||
}
|
||||
}
|
||||
|
||||
/// Normalize URL for external APIs (ensure https://)
|
||||
fn normalize_external_url(url: &str) -> String {
|
||||
if url.starts_with("http://") || url.starts_with("https://") {
|
||||
url.to_string()
|
||||
} else {
|
||||
format!("https://{}", url)
|
||||
}
|
||||
}
|
||||
|
||||
/// Step 3: Register workers in registry
|
||||
pub struct RegisterExternalWorkersStep;
|
||||
|
||||
#[async_trait]
|
||||
impl StepExecutor for RegisterExternalWorkersStep {
|
||||
async fn execute(&self, context: &mut WorkflowContext) -> WorkflowResult<StepResult> {
|
||||
let config: Arc<WorkerConfigRequest> = context
|
||||
.get("worker_config")
|
||||
.ok_or_else(|| WorkflowError::ContextValueNotFound("worker_config".to_string()))?;
|
||||
let app_context: Arc<AppContext> = context
|
||||
.get("app_context")
|
||||
.ok_or_else(|| WorkflowError::ContextValueNotFound("app_context".to_string()))?;
|
||||
let workers: Arc<Vec<Arc<dyn Worker>>> = context
|
||||
.get("workers")
|
||||
.ok_or_else(|| WorkflowError::ContextValueNotFound("workers".to_string()))?;
|
||||
|
||||
let mut worker_ids = Vec::new();
|
||||
for worker in workers.iter() {
|
||||
let worker_id = app_context.worker_registry.register(Arc::clone(worker));
|
||||
worker_ids.push(worker_id.clone());
|
||||
debug!(
|
||||
"Registered external worker {} (model: {}) with ID {:?}",
|
||||
config.url,
|
||||
worker.model_id(),
|
||||
worker_id
|
||||
);
|
||||
}
|
||||
|
||||
context.set("worker_ids", worker_ids);
|
||||
Ok(StepResult::Success)
|
||||
}
|
||||
|
||||
fn is_retryable(&self, _error: &WorkflowError) -> bool {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/// Step 4: Update policy registry
|
||||
pub struct UpdateExternalPoliciesStep;
|
||||
|
||||
#[async_trait]
|
||||
impl StepExecutor for UpdateExternalPoliciesStep {
|
||||
async fn execute(&self, context: &mut WorkflowContext) -> WorkflowResult<StepResult> {
|
||||
let config: Arc<WorkerConfigRequest> = context
|
||||
.get("worker_config")
|
||||
.ok_or_else(|| WorkflowError::ContextValueNotFound("worker_config".to_string()))?;
|
||||
let labels: Arc<HashMap<String, String>> = context
|
||||
.get("labels")
|
||||
.ok_or_else(|| WorkflowError::ContextValueNotFound("labels".to_string()))?;
|
||||
let app_context: Arc<AppContext> = context
|
||||
.get("app_context")
|
||||
.ok_or_else(|| WorkflowError::ContextValueNotFound("app_context".to_string()))?;
|
||||
let workers: Arc<Vec<Arc<dyn Worker>>> = context
|
||||
.get("workers")
|
||||
.ok_or_else(|| WorkflowError::ContextValueNotFound("workers".to_string()))?;
|
||||
|
||||
let policy_hint = labels.get("policy").map(|s| s.as_str());
|
||||
|
||||
// Each external worker has a different model_id
|
||||
for worker in workers.iter() {
|
||||
let model_id = worker.model_id().to_string();
|
||||
app_context
|
||||
.policy_registry
|
||||
.on_worker_added(&model_id, policy_hint);
|
||||
}
|
||||
|
||||
debug!(
|
||||
"Updated policies for {} external workers from {}",
|
||||
workers.len(),
|
||||
config.url
|
||||
);
|
||||
|
||||
Ok(StepResult::Success)
|
||||
}
|
||||
|
||||
fn is_retryable(&self, _error: &WorkflowError) -> bool {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/// Step 5: Activate workers by marking them healthy
|
||||
pub struct ActivateExternalWorkersStep;
|
||||
|
||||
#[async_trait]
|
||||
impl StepExecutor for ActivateExternalWorkersStep {
|
||||
async fn execute(&self, context: &mut WorkflowContext) -> WorkflowResult<StepResult> {
|
||||
let config: Arc<WorkerConfigRequest> = context
|
||||
.get("worker_config")
|
||||
.ok_or_else(|| WorkflowError::ContextValueNotFound("worker_config".to_string()))?;
|
||||
let workers: Arc<Vec<Arc<dyn Worker>>> = context
|
||||
.get("workers")
|
||||
.ok_or_else(|| WorkflowError::ContextValueNotFound("workers".to_string()))?;
|
||||
|
||||
for worker in workers.iter() {
|
||||
worker.set_healthy(true);
|
||||
}
|
||||
|
||||
info!(
|
||||
"Activated {} external workers from {} (marked as healthy)",
|
||||
workers.len(),
|
||||
config.url
|
||||
);
|
||||
|
||||
Ok(StepResult::Success)
|
||||
}
|
||||
|
||||
fn is_retryable(&self, _error: &WorkflowError) -> bool {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Workflow Definition
|
||||
// ============================================================================
|
||||
|
||||
/// Create external worker registration workflow definition
|
||||
pub fn create_external_worker_registration_workflow() -> WorkflowDefinition {
|
||||
WorkflowDefinition::new(
|
||||
"external_worker_registration",
|
||||
"External Worker Registration",
|
||||
)
|
||||
.add_step(
|
||||
StepDefinition::new(
|
||||
"discover_models",
|
||||
"Discover Models",
|
||||
Arc::new(DiscoverModelsStep),
|
||||
)
|
||||
.with_retry(RetryPolicy {
|
||||
max_attempts: 3,
|
||||
backoff: BackoffStrategy::Exponential {
|
||||
base: Duration::from_secs(1),
|
||||
max: Duration::from_secs(10),
|
||||
},
|
||||
})
|
||||
.with_timeout(Duration::from_secs(30))
|
||||
.with_failure_action(FailureAction::FailWorkflow),
|
||||
)
|
||||
.add_step(
|
||||
StepDefinition::new(
|
||||
"create_workers",
|
||||
"Create Workers",
|
||||
Arc::new(CreateExternalWorkersStep),
|
||||
)
|
||||
.with_timeout(Duration::from_secs(5))
|
||||
.with_failure_action(FailureAction::FailWorkflow),
|
||||
)
|
||||
.add_step(
|
||||
StepDefinition::new(
|
||||
"register_workers",
|
||||
"Register Workers",
|
||||
Arc::new(RegisterExternalWorkersStep),
|
||||
)
|
||||
.with_timeout(Duration::from_secs(5))
|
||||
.with_failure_action(FailureAction::FailWorkflow),
|
||||
)
|
||||
.add_step(
|
||||
StepDefinition::new(
|
||||
"update_policies",
|
||||
"Update Policies",
|
||||
Arc::new(UpdateExternalPoliciesStep),
|
||||
)
|
||||
.with_timeout(Duration::from_secs(5))
|
||||
.with_failure_action(FailureAction::ContinueNextStep),
|
||||
)
|
||||
.add_step(
|
||||
StepDefinition::new(
|
||||
"activate_workers",
|
||||
"Activate Workers",
|
||||
Arc::new(ActivateExternalWorkersStep),
|
||||
)
|
||||
.with_timeout(Duration::from_secs(5))
|
||||
.with_failure_action(FailureAction::FailWorkflow),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,304 @@
|
||||
//! MCP server registration workflow steps
|
||||
//!
|
||||
//! Each step is atomic and performs a single operation in the MCP server registration process.
|
||||
//! Updated for flat manager architecture - single McpManager manages all clients directly.
|
||||
//!
|
||||
//! Workflow order:
|
||||
//! 1. ConnectMcpServer - Establish connection to MCP server using McpManager::connect_server()
|
||||
//! 2. DiscoverMcpInventory - Discover and cache inventory using McpManager::load_server_inventory()
|
||||
//! 3. RegisterMcpServer - Register McpClient in McpManager's client map
|
||||
|
||||
use std::{sync::Arc, time::Duration};
|
||||
|
||||
use async_trait::async_trait;
|
||||
use rmcp::{service::RunningService, RoleClient};
|
||||
use tracing::{debug, error, info, warn};
|
||||
|
||||
use crate::{
|
||||
app_context::AppContext,
|
||||
core::workflow::*,
|
||||
mcp::{config::McpServerConfig, manager::McpManager},
|
||||
};
|
||||
|
||||
/// MCP server connection configuration
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct McpServerConfigRequest {
|
||||
/// Server name (unique identifier)
|
||||
pub name: String,
|
||||
/// Server configuration (transport, proxy, etc.)
|
||||
pub config: McpServerConfig,
|
||||
}
|
||||
|
||||
impl McpServerConfigRequest {
|
||||
/// Check if this server is required for router startup
|
||||
pub fn is_required(&self) -> bool {
|
||||
self.config.required
|
||||
}
|
||||
}
|
||||
|
||||
/// Step 1: Connect to MCP server
|
||||
///
|
||||
/// This step establishes a connection to the MCP server using the flat manager architecture.
|
||||
/// The connection is retried aggressively (100 attempts) with a long timeout (2 hours)
|
||||
/// to handle slow-starting servers or network issues.
|
||||
pub struct ConnectMcpServerStep;
|
||||
|
||||
#[async_trait]
|
||||
impl StepExecutor for ConnectMcpServerStep {
|
||||
async fn execute(&self, context: &mut WorkflowContext) -> WorkflowResult<StepResult> {
|
||||
let config_request: Arc<McpServerConfigRequest> = context
|
||||
.get("mcp_server_config")
|
||||
.ok_or_else(|| WorkflowError::ContextValueNotFound("mcp_server_config".to_string()))?;
|
||||
let app_context: Arc<AppContext> = context
|
||||
.get("app_context")
|
||||
.ok_or_else(|| WorkflowError::ContextValueNotFound("app_context".to_string()))?;
|
||||
|
||||
debug!("Connecting to MCP server: {}", config_request.name);
|
||||
|
||||
// Get proxy config from router_config if available, otherwise fall back to env
|
||||
let proxy_config = app_context
|
||||
.router_config
|
||||
.mcp_config
|
||||
.as_ref()
|
||||
.and_then(|cfg| cfg.proxy.as_ref());
|
||||
|
||||
// Connect to MCP server
|
||||
let client = McpManager::connect_server(&config_request.config, proxy_config)
|
||||
.await
|
||||
.map_err(|e| WorkflowError::StepFailed {
|
||||
step_id: StepId::new("connect_mcp_server"),
|
||||
message: format!(
|
||||
"Failed to connect to MCP server {}: {}",
|
||||
config_request.name, e
|
||||
),
|
||||
})?;
|
||||
|
||||
info!(
|
||||
"Successfully connected to MCP server: {}",
|
||||
config_request.name
|
||||
);
|
||||
|
||||
// Store client in context (context.set() will wrap in Arc)
|
||||
context.set("mcp_client", client);
|
||||
|
||||
Ok(StepResult::Success)
|
||||
}
|
||||
|
||||
fn is_retryable(&self, _error: &WorkflowError) -> bool {
|
||||
true // Connection failures are retryable
|
||||
}
|
||||
}
|
||||
|
||||
/// Step 2: Discover MCP inventory (tools, prompts, resources)
|
||||
///
|
||||
/// This step queries the MCP server for its capabilities using McpManager::load_server_inventory().
|
||||
/// - Tools: Available function calls
|
||||
/// - Prompts: Reusable prompt templates
|
||||
/// - Resources: Accessible files/data
|
||||
pub struct DiscoverMcpInventoryStep;
|
||||
|
||||
#[async_trait]
|
||||
impl StepExecutor for DiscoverMcpInventoryStep {
|
||||
async fn execute(&self, context: &mut WorkflowContext) -> WorkflowResult<StepResult> {
|
||||
use rmcp::{service::RunningService, RoleClient};
|
||||
|
||||
let config_request: Arc<McpServerConfigRequest> = context
|
||||
.get("mcp_server_config")
|
||||
.ok_or_else(|| WorkflowError::ContextValueNotFound("mcp_server_config".to_string()))?;
|
||||
let app_context: Arc<AppContext> = context
|
||||
.get("app_context")
|
||||
.ok_or_else(|| WorkflowError::ContextValueNotFound("app_context".to_string()))?;
|
||||
let mcp_client: Arc<RunningService<RoleClient, ()>> = context
|
||||
.get("mcp_client")
|
||||
.ok_or_else(|| WorkflowError::ContextValueNotFound("mcp_client".to_string()))?;
|
||||
|
||||
debug!(
|
||||
"Discovering inventory for MCP server: {}",
|
||||
config_request.name
|
||||
);
|
||||
|
||||
// Get shared ToolInventory from McpManager
|
||||
let mcp_manager =
|
||||
app_context
|
||||
.mcp_manager
|
||||
.get()
|
||||
.ok_or_else(|| WorkflowError::StepFailed {
|
||||
step_id: StepId::new("discover_mcp_inventory"),
|
||||
message: "MCP manager not initialized".to_string(),
|
||||
})?;
|
||||
|
||||
let inventory = mcp_manager.inventory();
|
||||
|
||||
// Use the public load_server_inventory method
|
||||
McpManager::load_server_inventory(&inventory, &config_request.name, &mcp_client).await;
|
||||
|
||||
info!("Completed inventory discovery for {}", config_request.name);
|
||||
|
||||
Ok(StepResult::Success)
|
||||
}
|
||||
|
||||
fn is_retryable(&self, _error: &WorkflowError) -> bool {
|
||||
true // Discovery failures are retryable
|
||||
}
|
||||
}
|
||||
|
||||
/// Step 3: Register MCP server in manager
|
||||
///
|
||||
/// This step adds the MCP client to the McpManager's client map so it can be
|
||||
/// used for tool calls and inventory management.
|
||||
pub struct RegisterMcpServerStep;
|
||||
|
||||
#[async_trait]
|
||||
impl StepExecutor for RegisterMcpServerStep {
|
||||
async fn execute(&self, context: &mut WorkflowContext) -> WorkflowResult<StepResult> {
|
||||
use rmcp::{service::RunningService, RoleClient};
|
||||
|
||||
let config_request: Arc<McpServerConfigRequest> = context
|
||||
.get("mcp_server_config")
|
||||
.ok_or_else(|| WorkflowError::ContextValueNotFound("mcp_server_config".to_string()))?;
|
||||
let app_context: Arc<AppContext> = context
|
||||
.get("app_context")
|
||||
.ok_or_else(|| WorkflowError::ContextValueNotFound("app_context".to_string()))?;
|
||||
let mcp_client: Arc<RunningService<RoleClient, ()>> = context
|
||||
.get("mcp_client")
|
||||
.ok_or_else(|| WorkflowError::ContextValueNotFound("mcp_client".to_string()))?;
|
||||
|
||||
debug!("Registering MCP server: {}", config_request.name);
|
||||
|
||||
// Get MCP manager from app context
|
||||
let mcp_manager =
|
||||
app_context
|
||||
.mcp_manager
|
||||
.get()
|
||||
.ok_or_else(|| WorkflowError::StepFailed {
|
||||
step_id: StepId::new("register_mcp_server"),
|
||||
message: "MCP manager not initialized".to_string(),
|
||||
})?;
|
||||
|
||||
// Register the client in the manager's client map
|
||||
mcp_manager.register_static_server(config_request.name.clone(), mcp_client);
|
||||
|
||||
info!("Registered MCP server: {}", config_request.name);
|
||||
|
||||
Ok(StepResult::Success)
|
||||
}
|
||||
|
||||
fn is_retryable(&self, _error: &WorkflowError) -> bool {
|
||||
false // Registration is a simple operation, not retryable
|
||||
}
|
||||
}
|
||||
|
||||
/// Step 4: Validate registration based on required flag
|
||||
///
|
||||
/// This step checks if the server is marked as required. If the server is required
|
||||
/// but wasn't successfully registered (client not in context), this step fails the workflow.
|
||||
/// For optional servers, this step always succeeds, allowing the workflow to complete
|
||||
/// even if earlier steps failed.
|
||||
pub struct ValidateRegistrationStep;
|
||||
|
||||
#[async_trait]
|
||||
impl StepExecutor for ValidateRegistrationStep {
|
||||
async fn execute(&self, context: &mut WorkflowContext) -> WorkflowResult<StepResult> {
|
||||
let config_request: Arc<McpServerConfigRequest> = context
|
||||
.get("mcp_server_config")
|
||||
.ok_or_else(|| WorkflowError::ContextValueNotFound("mcp_server_config".to_string()))?;
|
||||
|
||||
let client_registered = context
|
||||
.get::<RunningService<RoleClient, ()>>("mcp_client")
|
||||
.is_some();
|
||||
|
||||
if client_registered {
|
||||
info!(
|
||||
"MCP server '{}' registered successfully",
|
||||
config_request.name
|
||||
);
|
||||
return Ok(StepResult::Success);
|
||||
}
|
||||
|
||||
if config_request.is_required() {
|
||||
error!(
|
||||
"Required MCP server '{}' failed to register",
|
||||
config_request.name
|
||||
);
|
||||
Err(WorkflowError::StepFailed {
|
||||
step_id: StepId::new("validate_registration"),
|
||||
message: format!(
|
||||
"Required MCP server '{}' failed to register",
|
||||
config_request.name
|
||||
),
|
||||
})
|
||||
} else {
|
||||
warn!(
|
||||
"Optional MCP server '{}' failed to register, continuing workflow",
|
||||
config_request.name
|
||||
);
|
||||
Ok(StepResult::Success)
|
||||
}
|
||||
}
|
||||
|
||||
fn is_retryable(&self, _error: &WorkflowError) -> bool {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/// Create MCP server registration workflow
|
||||
///
|
||||
/// This workflow adapts its failure behavior based on the `required` field in the server config:
|
||||
/// - If `required == true`: Uses FailWorkflow - router startup fails if server cannot be reached
|
||||
/// - If `required == false` (default): Uses ContinueNextStep - logs warning but continues
|
||||
///
|
||||
/// Workflow configuration:
|
||||
/// - ConnectMcpServer: 100 retries, 2hr timeout (aggressive retry for slow servers)
|
||||
/// - DiscoverMcpInventory: 3 retries, 10s timeout (discovery + caching)
|
||||
/// - RegisterMcpServer: No retry, 5s timeout (fast registration)
|
||||
/// - ValidateRegistration: Final validation step
|
||||
pub fn create_mcp_registration_workflow() -> WorkflowDefinition {
|
||||
WorkflowDefinition::new("mcp_registration", "MCP Server Registration")
|
||||
.add_step(
|
||||
StepDefinition::new(
|
||||
"connect_mcp_server",
|
||||
"Connect to MCP Server",
|
||||
Arc::new(ConnectMcpServerStep),
|
||||
)
|
||||
.with_retry(RetryPolicy {
|
||||
max_attempts: 100,
|
||||
backoff: BackoffStrategy::Linear {
|
||||
increment: Duration::from_secs(1),
|
||||
max: Duration::from_secs(5),
|
||||
},
|
||||
})
|
||||
.with_timeout(Duration::from_secs(7200)) // 2 hours
|
||||
.with_failure_action(FailureAction::ContinueNextStep),
|
||||
)
|
||||
.add_step(
|
||||
StepDefinition::new(
|
||||
"discover_mcp_inventory",
|
||||
"Discover and Cache MCP Inventory",
|
||||
Arc::new(DiscoverMcpInventoryStep),
|
||||
)
|
||||
.with_retry(RetryPolicy {
|
||||
max_attempts: 3,
|
||||
backoff: BackoffStrategy::Fixed(Duration::from_secs(1)),
|
||||
})
|
||||
.with_timeout(Duration::from_secs(10))
|
||||
.with_failure_action(FailureAction::ContinueNextStep),
|
||||
)
|
||||
.add_step(
|
||||
StepDefinition::new(
|
||||
"register_mcp_server",
|
||||
"Register MCP Server",
|
||||
Arc::new(RegisterMcpServerStep),
|
||||
)
|
||||
.with_timeout(Duration::from_secs(5))
|
||||
.with_failure_action(FailureAction::ContinueNextStep),
|
||||
)
|
||||
.add_step(
|
||||
StepDefinition::new(
|
||||
"validate_registration",
|
||||
"Validate MCP Registration",
|
||||
Arc::new(ValidateRegistrationStep),
|
||||
)
|
||||
.with_timeout(Duration::from_secs(1))
|
||||
.with_failure_action(FailureAction::FailWorkflow),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
//! Workflow step implementations
|
||||
//!
|
||||
//! This module contains concrete step implementations for various workflows:
|
||||
//! - Local worker registration (SGLang, vLLM - gRPC or HTTP modes)
|
||||
//! - External worker registration (OpenAI, xAI, Anthropic, etc. - HTTPS only)
|
||||
//! - Worker removal
|
||||
//! - MCP server registration
|
||||
//! - WASM module registration and removal
|
||||
//! - Future: Tokenizer fetching, LoRA updates, etc.
|
||||
|
||||
pub mod external_worker_registration;
|
||||
pub mod mcp_registration;
|
||||
pub mod wasm_module_registration;
|
||||
pub mod wasm_module_removal;
|
||||
pub mod worker_registration;
|
||||
pub mod worker_removal;
|
||||
|
||||
pub use external_worker_registration::{
|
||||
create_external_worker_registration_workflow, group_models_into_cards,
|
||||
infer_model_type_from_id, ActivateExternalWorkersStep, CreateExternalWorkersStep,
|
||||
DiscoverModelsStep, ModelInfo, ModelsResponse, RegisterExternalWorkersStep,
|
||||
UpdateExternalPoliciesStep,
|
||||
};
|
||||
pub use mcp_registration::{
|
||||
create_mcp_registration_workflow, ConnectMcpServerStep, DiscoverMcpInventoryStep,
|
||||
McpServerConfigRequest, RegisterMcpServerStep, ValidateRegistrationStep,
|
||||
};
|
||||
pub use wasm_module_registration::{
|
||||
create_wasm_module_registration_workflow, CalculateHashStep, CheckDuplicateStep,
|
||||
LoadWasmBytesStep, RegisterModuleStep, ValidateDescriptorStep, ValidateWasmComponentStep,
|
||||
WasmModuleConfigRequest,
|
||||
};
|
||||
pub use wasm_module_removal::{
|
||||
create_wasm_module_removal_workflow, FindModuleToRemoveStep, RemoveModuleStep,
|
||||
WasmModuleRemovalRequest,
|
||||
};
|
||||
pub use worker_registration::{
|
||||
create_worker_registration_workflow, ActivateWorkerStep, CreateWorkerStep,
|
||||
DetectConnectionModeStep, DiscoverDPInfoStep, DiscoverMetadataStep, RegisterWorkerStep,
|
||||
UpdatePoliciesStep,
|
||||
};
|
||||
pub use worker_removal::{
|
||||
create_worker_removal_workflow, FindWorkersToRemoveStep, RemoveFromPolicyRegistryStep,
|
||||
RemoveFromWorkerRegistryStep, UpdateRemainingPoliciesStep, WorkerRemovalRequest,
|
||||
};
|
||||
@@ -0,0 +1,474 @@
|
||||
//! WASM Module Registration Workflow Steps
|
||||
//!
|
||||
//! Each step is atomic and performs a single operation in the WASM module registration process.
|
||||
//!
|
||||
//! Workflow order:
|
||||
//! 1. ValidateDescriptor - Validate module descriptor (name, file_path, file existence)
|
||||
//! 2. CalculateHash - Calculate SHA256 hash of the module file
|
||||
//! 3. CheckDuplicate - Check for duplicate SHA256 hash
|
||||
//! 4. LoadWasmBytes - Load WASM bytes into memory
|
||||
//! 5. ValidateWasmComponent - Validate WASM component format
|
||||
//! 6. RegisterModule - Register module in WasmModuleManager
|
||||
|
||||
use std::{sync::Arc, time::Duration};
|
||||
|
||||
use async_trait::async_trait;
|
||||
use sha2::{Digest, Sha256};
|
||||
use tracing::{debug, info};
|
||||
use uuid::Uuid;
|
||||
use wasmtime::{component::Component, Config, Engine};
|
||||
|
||||
use crate::{
|
||||
app_context::AppContext,
|
||||
core::workflow::*,
|
||||
wasm::module::{WasmModule, WasmModuleDescriptor, WasmModuleMeta},
|
||||
};
|
||||
|
||||
/// WASM module registration request
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct WasmModuleConfigRequest {
|
||||
/// Module descriptor containing name, file_path, attach_points, etc.
|
||||
pub descriptor: WasmModuleDescriptor,
|
||||
}
|
||||
|
||||
/// Step 1: Validate module descriptor
|
||||
///
|
||||
/// Validates that the module descriptor has all required fields:
|
||||
/// - Module name is not empty
|
||||
/// - File path is not empty
|
||||
/// - File exists and is readable
|
||||
/// - File size is not zero
|
||||
pub struct ValidateDescriptorStep;
|
||||
|
||||
#[async_trait]
|
||||
impl StepExecutor for ValidateDescriptorStep {
|
||||
async fn execute(&self, context: &mut WorkflowContext) -> WorkflowResult<StepResult> {
|
||||
let config_request: Arc<WasmModuleConfigRequest> = context
|
||||
.get("wasm_module_config")
|
||||
.ok_or_else(|| WorkflowError::ContextValueNotFound("wasm_module_config".to_string()))?;
|
||||
|
||||
let descriptor = &config_request.descriptor;
|
||||
|
||||
debug!("Validating WASM module descriptor: {}", descriptor.name);
|
||||
|
||||
// Validate name
|
||||
if descriptor.name.is_empty() {
|
||||
return Err(WorkflowError::StepFailed {
|
||||
step_id: StepId::new("validate_descriptor"),
|
||||
message: "Module name cannot be empty".to_string(),
|
||||
});
|
||||
}
|
||||
|
||||
// Validate file path
|
||||
if descriptor.file_path.is_empty() {
|
||||
return Err(WorkflowError::StepFailed {
|
||||
step_id: StepId::new("validate_descriptor"),
|
||||
message: "Module file path cannot be empty".to_string(),
|
||||
});
|
||||
}
|
||||
|
||||
// Check if file exists and get size
|
||||
let metadata = tokio::fs::metadata(&descriptor.file_path)
|
||||
.await
|
||||
.map_err(|e| WorkflowError::StepFailed {
|
||||
step_id: StepId::new("validate_descriptor"),
|
||||
message: format!("Failed to access file {}: {}", descriptor.file_path, e),
|
||||
})?;
|
||||
|
||||
if metadata.len() == 0 {
|
||||
return Err(WorkflowError::StepFailed {
|
||||
step_id: StepId::new("validate_descriptor"),
|
||||
message: "Module file size cannot be 0".to_string(),
|
||||
});
|
||||
}
|
||||
|
||||
// Store file size in context for later steps
|
||||
context.set("file_size_bytes", metadata.len());
|
||||
|
||||
info!(
|
||||
"Descriptor validated successfully for module: {}",
|
||||
descriptor.name
|
||||
);
|
||||
Ok(StepResult::Success)
|
||||
}
|
||||
|
||||
fn is_retryable(&self, _error: &WorkflowError) -> bool {
|
||||
false // Validation errors are not retryable (invalid input)
|
||||
}
|
||||
}
|
||||
|
||||
/// Step 2: Calculate SHA256 hash of the module file
|
||||
///
|
||||
/// Reads the file and calculates its SHA256 hash for deduplication.
|
||||
/// This step is I/O intensive and may take time for large files.
|
||||
pub struct CalculateHashStep;
|
||||
|
||||
#[async_trait]
|
||||
impl StepExecutor for CalculateHashStep {
|
||||
async fn execute(&self, context: &mut WorkflowContext) -> WorkflowResult<StepResult> {
|
||||
let config_request: Arc<WasmModuleConfigRequest> = context
|
||||
.get("wasm_module_config")
|
||||
.ok_or_else(|| WorkflowError::ContextValueNotFound("wasm_module_config".to_string()))?;
|
||||
|
||||
let file_path = &config_request.descriptor.file_path;
|
||||
|
||||
debug!("Calculating SHA256 hash for: {}", file_path);
|
||||
|
||||
// Read file in chunks to handle large files efficiently
|
||||
let mut file =
|
||||
tokio::fs::File::open(file_path)
|
||||
.await
|
||||
.map_err(|e| WorkflowError::StepFailed {
|
||||
step_id: StepId::new("calculate_hash"),
|
||||
message: format!("Failed to open file {}: {}", file_path, e),
|
||||
})?;
|
||||
|
||||
let mut hasher = Sha256::new();
|
||||
let mut buffer = vec![0u8; 1024 * 1024]; // 1MB buffer
|
||||
|
||||
loop {
|
||||
use tokio::io::AsyncReadExt;
|
||||
let bytes_read =
|
||||
file.read(&mut buffer)
|
||||
.await
|
||||
.map_err(|e| WorkflowError::StepFailed {
|
||||
step_id: StepId::new("calculate_hash"),
|
||||
message: format!("Failed to read file {}: {}", file_path, e),
|
||||
})?;
|
||||
|
||||
if bytes_read == 0 {
|
||||
break;
|
||||
}
|
||||
|
||||
hasher.update(&buffer[..bytes_read]);
|
||||
}
|
||||
|
||||
let hash: [u8; 32] = hasher.finalize().into();
|
||||
|
||||
// Store hash in context
|
||||
context.set("sha256_hash", hash);
|
||||
|
||||
info!("SHA256 hash calculated for: {}", file_path);
|
||||
Ok(StepResult::Success)
|
||||
}
|
||||
|
||||
fn is_retryable(&self, _error: &WorkflowError) -> bool {
|
||||
true // File I/O errors are retryable (network filesystem, etc.)
|
||||
}
|
||||
}
|
||||
|
||||
/// Step 3: Check for duplicate SHA256 hash
|
||||
///
|
||||
/// Checks if a module with the same SHA256 hash already exists in the manager.
|
||||
/// This prevents duplicate modules from being registered.
|
||||
pub struct CheckDuplicateStep;
|
||||
|
||||
#[async_trait]
|
||||
impl StepExecutor for CheckDuplicateStep {
|
||||
async fn execute(&self, context: &mut WorkflowContext) -> WorkflowResult<StepResult> {
|
||||
let config_request: Arc<WasmModuleConfigRequest> = context
|
||||
.get("wasm_module_config")
|
||||
.ok_or_else(|| WorkflowError::ContextValueNotFound("wasm_module_config".to_string()))?;
|
||||
let app_context: Arc<AppContext> = context
|
||||
.get("app_context")
|
||||
.ok_or_else(|| WorkflowError::ContextValueNotFound("app_context".to_string()))?;
|
||||
let sha256_hash: Arc<[u8; 32]> = context
|
||||
.get("sha256_hash")
|
||||
.ok_or_else(|| WorkflowError::ContextValueNotFound("sha256_hash".to_string()))?;
|
||||
|
||||
debug!(
|
||||
"Checking for duplicate SHA256 hash for module: {}",
|
||||
config_request.descriptor.name
|
||||
);
|
||||
|
||||
// Get WASM module manager from app context
|
||||
let wasm_manager =
|
||||
app_context
|
||||
.wasm_manager
|
||||
.as_ref()
|
||||
.ok_or_else(|| WorkflowError::StepFailed {
|
||||
step_id: StepId::new("check_duplicate"),
|
||||
message: "WASM module manager not initialized".to_string(),
|
||||
})?;
|
||||
|
||||
// Check for duplicate hash using manager's internal method
|
||||
wasm_manager
|
||||
.check_duplicate_sha256_hash(sha256_hash.as_ref())
|
||||
.map_err(|e| WorkflowError::StepFailed {
|
||||
step_id: StepId::new("check_duplicate"),
|
||||
message: format!("Duplicate SHA256 hash detected: {}", e),
|
||||
})?;
|
||||
|
||||
info!(
|
||||
"No duplicate found for module: {}",
|
||||
config_request.descriptor.name
|
||||
);
|
||||
Ok(StepResult::Success)
|
||||
}
|
||||
|
||||
fn is_retryable(&self, _error: &WorkflowError) -> bool {
|
||||
false // Duplicate check failures are not retryable
|
||||
}
|
||||
}
|
||||
|
||||
/// Step 4: Load WASM bytes into memory
|
||||
///
|
||||
/// Reads the entire WASM file into memory for faster execution.
|
||||
/// This is an I/O operation that may take time for large files.
|
||||
pub struct LoadWasmBytesStep;
|
||||
|
||||
#[async_trait]
|
||||
impl StepExecutor for LoadWasmBytesStep {
|
||||
async fn execute(&self, context: &mut WorkflowContext) -> WorkflowResult<StepResult> {
|
||||
let config_request: Arc<WasmModuleConfigRequest> = context
|
||||
.get("wasm_module_config")
|
||||
.ok_or_else(|| WorkflowError::ContextValueNotFound("wasm_module_config".to_string()))?;
|
||||
|
||||
let file_path = &config_request.descriptor.file_path;
|
||||
|
||||
debug!("Loading WASM bytes from: {}", file_path);
|
||||
|
||||
let wasm_bytes =
|
||||
tokio::fs::read(file_path)
|
||||
.await
|
||||
.map_err(|e| WorkflowError::StepFailed {
|
||||
step_id: StepId::new("load_wasm_bytes"),
|
||||
message: format!("Failed to read WASM file {}: {}", file_path, e),
|
||||
})?;
|
||||
|
||||
// Store WASM bytes in context
|
||||
context.set("wasm_bytes", wasm_bytes);
|
||||
|
||||
info!("WASM bytes loaded from: {}", file_path);
|
||||
Ok(StepResult::Success)
|
||||
}
|
||||
|
||||
fn is_retryable(&self, _error: &WorkflowError) -> bool {
|
||||
true // File read errors are retryable
|
||||
}
|
||||
}
|
||||
|
||||
/// Step 5: Validate WASM component format
|
||||
///
|
||||
/// Validates that the loaded WASM bytes represent a valid component.
|
||||
/// This catches format errors early during registration rather than during execution.
|
||||
pub struct ValidateWasmComponentStep;
|
||||
|
||||
#[async_trait]
|
||||
impl StepExecutor for ValidateWasmComponentStep {
|
||||
async fn execute(&self, context: &mut WorkflowContext) -> WorkflowResult<StepResult> {
|
||||
let config_request: Arc<WasmModuleConfigRequest> = context
|
||||
.get("wasm_module_config")
|
||||
.ok_or_else(|| WorkflowError::ContextValueNotFound("wasm_module_config".to_string()))?;
|
||||
let wasm_bytes: Arc<Vec<u8>> = context
|
||||
.get("wasm_bytes")
|
||||
.ok_or_else(|| WorkflowError::ContextValueNotFound("wasm_bytes".to_string()))?;
|
||||
|
||||
debug!(
|
||||
"Validating WASM component format for module: {}",
|
||||
config_request.descriptor.name
|
||||
);
|
||||
|
||||
// Create a temporary engine to validate the component
|
||||
let mut config = Config::new();
|
||||
config.async_support(true);
|
||||
config.wasm_component_model(true);
|
||||
|
||||
let engine = Engine::new(&config).map_err(|e| WorkflowError::StepFailed {
|
||||
step_id: StepId::new("validate_wasm_component"),
|
||||
message: format!("Failed to create WASM engine: {}", e),
|
||||
})?;
|
||||
|
||||
// Attempt to compile the component to validate it
|
||||
Component::new(&engine, wasm_bytes.as_ref())
|
||||
.map_err(|e| WorkflowError::StepFailed {
|
||||
step_id: StepId::new("validate_wasm_component"),
|
||||
message: format!(
|
||||
"Invalid WASM component: {}. \
|
||||
Hint: The WASM file must be in component format. \
|
||||
If you're using wit-bindgen, use 'wasm-tools component new' to wrap the WASM module into a component.",
|
||||
e
|
||||
),
|
||||
})?;
|
||||
|
||||
info!(
|
||||
"WASM component validated successfully for module: {}",
|
||||
config_request.descriptor.name
|
||||
);
|
||||
Ok(StepResult::Success)
|
||||
}
|
||||
|
||||
fn is_retryable(&self, _error: &WorkflowError) -> bool {
|
||||
false // Validation errors are not retryable (invalid format)
|
||||
}
|
||||
}
|
||||
|
||||
/// Step 6: Register module in WasmModuleManager
|
||||
///
|
||||
/// Creates the WasmModule object and registers it in the manager's module map.
|
||||
/// This is the final step that makes the module available for execution.
|
||||
pub struct RegisterModuleStep;
|
||||
|
||||
#[async_trait]
|
||||
impl StepExecutor for RegisterModuleStep {
|
||||
async fn execute(&self, context: &mut WorkflowContext) -> WorkflowResult<StepResult> {
|
||||
let config_request: Arc<WasmModuleConfigRequest> = context
|
||||
.get("wasm_module_config")
|
||||
.ok_or_else(|| WorkflowError::ContextValueNotFound("wasm_module_config".to_string()))?;
|
||||
let app_context: Arc<AppContext> = context
|
||||
.get("app_context")
|
||||
.ok_or_else(|| WorkflowError::ContextValueNotFound("app_context".to_string()))?;
|
||||
let sha256_hash: Arc<[u8; 32]> = context
|
||||
.get("sha256_hash")
|
||||
.ok_or_else(|| WorkflowError::ContextValueNotFound("sha256_hash".to_string()))?;
|
||||
let file_size_bytes: Arc<u64> = context
|
||||
.get("file_size_bytes")
|
||||
.ok_or_else(|| WorkflowError::ContextValueNotFound("file_size_bytes".to_string()))?;
|
||||
let wasm_bytes: Arc<Vec<u8>> = context
|
||||
.get("wasm_bytes")
|
||||
.ok_or_else(|| WorkflowError::ContextValueNotFound("wasm_bytes".to_string()))?;
|
||||
|
||||
debug!(
|
||||
"Registering WASM module in manager: {}",
|
||||
config_request.descriptor.name
|
||||
);
|
||||
|
||||
// Get WASM module manager from app context
|
||||
let wasm_manager =
|
||||
app_context
|
||||
.wasm_manager
|
||||
.as_ref()
|
||||
.ok_or_else(|| WorkflowError::StepFailed {
|
||||
step_id: StepId::new("register_module"),
|
||||
message: "WASM module manager not initialized".to_string(),
|
||||
})?;
|
||||
|
||||
// Create module metadata
|
||||
let now = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap_or_else(|_| Duration::from_nanos(0))
|
||||
.as_nanos() as u64;
|
||||
|
||||
let module_uuid = Uuid::new_v4();
|
||||
|
||||
let module = WasmModule {
|
||||
module_uuid,
|
||||
module_meta: WasmModuleMeta {
|
||||
name: config_request.descriptor.name.clone(),
|
||||
file_path: config_request.descriptor.file_path.clone(),
|
||||
sha256_hash: *sha256_hash.as_ref(),
|
||||
size_bytes: *file_size_bytes.as_ref(),
|
||||
created_at: now,
|
||||
last_accessed_at: now,
|
||||
access_count: 0,
|
||||
attach_points: config_request.descriptor.attach_points.clone(),
|
||||
wasm_bytes: wasm_bytes.as_ref().clone(),
|
||||
},
|
||||
};
|
||||
|
||||
// Register module in manager
|
||||
wasm_manager
|
||||
.register_module_internal(module)
|
||||
.map_err(|e| WorkflowError::StepFailed {
|
||||
step_id: StepId::new("register_module"),
|
||||
message: format!("Failed to register module: {}", e),
|
||||
})?;
|
||||
|
||||
// Store module UUID in context for return value
|
||||
context.set("module_uuid", module_uuid);
|
||||
|
||||
info!(
|
||||
"WASM module registered successfully: {} (UUID: {})",
|
||||
config_request.descriptor.name, module_uuid
|
||||
);
|
||||
|
||||
Ok(StepResult::Success)
|
||||
}
|
||||
|
||||
fn is_retryable(&self, _error: &WorkflowError) -> bool {
|
||||
false // Registration is a simple operation, not retryable
|
||||
}
|
||||
}
|
||||
|
||||
/// Create WASM module registration workflow
|
||||
///
|
||||
/// This workflow handles the complete process of registering a WASM module:
|
||||
/// - Validates the module descriptor
|
||||
/// - Calculates SHA256 hash for deduplication
|
||||
/// - Checks for duplicates
|
||||
/// - Loads WASM bytes into memory
|
||||
/// - Validates WASM component format
|
||||
/// - Registers the module in the manager
|
||||
///
|
||||
/// Workflow configuration:
|
||||
/// - ValidateDescriptor: No retry, 5s timeout (fast validation)
|
||||
/// - CalculateHash: 3 retries, 60s timeout (I/O intensive, may need retry)
|
||||
/// - CheckDuplicate: No retry, 5s timeout (fast check)
|
||||
/// - LoadWasmBytes: 3 retries, 60s timeout (I/O intensive)
|
||||
/// - ValidateWasmComponent: No retry, 30s timeout (CPU intensive validation)
|
||||
/// - RegisterModule: No retry, 5s timeout (fast registration)
|
||||
pub fn create_wasm_module_registration_workflow() -> WorkflowDefinition {
|
||||
WorkflowDefinition::new("wasm_module_registration", "WASM Module Registration")
|
||||
.add_step(
|
||||
StepDefinition::new(
|
||||
"validate_descriptor",
|
||||
"Validate Descriptor",
|
||||
Arc::new(ValidateDescriptorStep),
|
||||
)
|
||||
.with_timeout(Duration::from_secs(5))
|
||||
.with_failure_action(FailureAction::FailWorkflow),
|
||||
)
|
||||
.add_step(
|
||||
StepDefinition::new(
|
||||
"calculate_hash",
|
||||
"Calculate SHA256 Hash",
|
||||
Arc::new(CalculateHashStep),
|
||||
)
|
||||
.with_retry(RetryPolicy {
|
||||
max_attempts: 3,
|
||||
backoff: BackoffStrategy::Fixed(Duration::from_secs(1)),
|
||||
})
|
||||
.with_timeout(Duration::from_secs(60))
|
||||
.with_failure_action(FailureAction::FailWorkflow),
|
||||
)
|
||||
.add_step(
|
||||
StepDefinition::new(
|
||||
"check_duplicate",
|
||||
"Check Duplicate Hash",
|
||||
Arc::new(CheckDuplicateStep),
|
||||
)
|
||||
.with_timeout(Duration::from_secs(5))
|
||||
.with_failure_action(FailureAction::FailWorkflow),
|
||||
)
|
||||
.add_step(
|
||||
StepDefinition::new(
|
||||
"load_wasm_bytes",
|
||||
"Load WASM Bytes",
|
||||
Arc::new(LoadWasmBytesStep),
|
||||
)
|
||||
.with_retry(RetryPolicy {
|
||||
max_attempts: 3,
|
||||
backoff: BackoffStrategy::Fixed(Duration::from_secs(1)),
|
||||
})
|
||||
.with_timeout(Duration::from_secs(60))
|
||||
.with_failure_action(FailureAction::FailWorkflow),
|
||||
)
|
||||
.add_step(
|
||||
StepDefinition::new(
|
||||
"validate_wasm_component",
|
||||
"Validate WASM Component",
|
||||
Arc::new(ValidateWasmComponentStep),
|
||||
)
|
||||
.with_timeout(Duration::from_secs(30))
|
||||
.with_failure_action(FailureAction::FailWorkflow),
|
||||
)
|
||||
.add_step(
|
||||
StepDefinition::new(
|
||||
"register_module",
|
||||
"Register Module",
|
||||
Arc::new(RegisterModuleStep),
|
||||
)
|
||||
.with_timeout(Duration::from_secs(5))
|
||||
.with_failure_action(FailureAction::FailWorkflow),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
//! WASM Module Removal Workflow Steps
|
||||
//!
|
||||
//! Each step is atomic and performs a single operation in the WASM module removal process.
|
||||
//!
|
||||
//! Workflow order:
|
||||
//! 1. FindModuleToRemove - Find the module to remove by UUID
|
||||
//! 2. RemoveModule - Remove module from WasmModuleManager
|
||||
|
||||
use std::{sync::Arc, time::Duration};
|
||||
|
||||
use async_trait::async_trait;
|
||||
use tracing::{debug, info};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::{app_context::AppContext, core::workflow::*};
|
||||
|
||||
/// WASM module removal request
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct WasmModuleRemovalRequest {
|
||||
/// Module UUID to remove
|
||||
pub module_uuid: Uuid,
|
||||
/// Cached UUID string for worker_url() method
|
||||
pub(crate) uuid_string: String,
|
||||
}
|
||||
|
||||
impl WasmModuleRemovalRequest {
|
||||
pub fn new(module_uuid: Uuid) -> Self {
|
||||
Self {
|
||||
module_uuid,
|
||||
uuid_string: module_uuid.to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Step 1: Find module to remove
|
||||
///
|
||||
/// Verifies that the module exists before attempting removal.
|
||||
pub struct FindModuleToRemoveStep;
|
||||
|
||||
#[async_trait]
|
||||
impl StepExecutor for FindModuleToRemoveStep {
|
||||
async fn execute(&self, context: &mut WorkflowContext) -> WorkflowResult<StepResult> {
|
||||
let removal_request: Arc<WasmModuleRemovalRequest> =
|
||||
context.get("wasm_module_removal_request").ok_or_else(|| {
|
||||
WorkflowError::ContextValueNotFound("wasm_module_removal_request".to_string())
|
||||
})?;
|
||||
let app_context: Arc<AppContext> = context
|
||||
.get("app_context")
|
||||
.ok_or_else(|| WorkflowError::ContextValueNotFound("app_context".to_string()))?;
|
||||
|
||||
debug!("Finding module to remove: {}", removal_request.module_uuid);
|
||||
|
||||
// Get WASM module manager from app context
|
||||
let wasm_manager =
|
||||
app_context
|
||||
.wasm_manager
|
||||
.as_ref()
|
||||
.ok_or_else(|| WorkflowError::StepFailed {
|
||||
step_id: StepId::new("find_module_to_remove"),
|
||||
message: "WASM module manager not initialized".to_string(),
|
||||
})?;
|
||||
|
||||
// Check if module exists
|
||||
let module = wasm_manager
|
||||
.get_module(removal_request.module_uuid)
|
||||
.map_err(|e| WorkflowError::StepFailed {
|
||||
step_id: StepId::new("find_module_to_remove"),
|
||||
message: format!("Failed to get module: {}", e),
|
||||
})?;
|
||||
|
||||
if module.is_none() {
|
||||
return Err(WorkflowError::StepFailed {
|
||||
step_id: StepId::new("find_module_to_remove"),
|
||||
message: format!("Module with UUID {} not found", removal_request.module_uuid),
|
||||
});
|
||||
}
|
||||
|
||||
info!("Module found for removal: {}", removal_request.module_uuid);
|
||||
Ok(StepResult::Success)
|
||||
}
|
||||
|
||||
fn is_retryable(&self, _error: &WorkflowError) -> bool {
|
||||
false // Module not found is not retryable
|
||||
}
|
||||
}
|
||||
|
||||
/// Step 2: Remove module from WasmModuleManager
|
||||
///
|
||||
/// Removes the module from the manager's module map.
|
||||
pub struct RemoveModuleStep;
|
||||
|
||||
#[async_trait]
|
||||
impl StepExecutor for RemoveModuleStep {
|
||||
async fn execute(&self, context: &mut WorkflowContext) -> WorkflowResult<StepResult> {
|
||||
let removal_request: Arc<WasmModuleRemovalRequest> =
|
||||
context.get("wasm_module_removal_request").ok_or_else(|| {
|
||||
WorkflowError::ContextValueNotFound("wasm_module_removal_request".to_string())
|
||||
})?;
|
||||
let app_context: Arc<AppContext> = context
|
||||
.get("app_context")
|
||||
.ok_or_else(|| WorkflowError::ContextValueNotFound("app_context".to_string()))?;
|
||||
|
||||
debug!("Removing WASM module: {}", removal_request.module_uuid);
|
||||
|
||||
// Get WASM module manager from app context
|
||||
let wasm_manager =
|
||||
app_context
|
||||
.wasm_manager
|
||||
.as_ref()
|
||||
.ok_or_else(|| WorkflowError::StepFailed {
|
||||
step_id: StepId::new("remove_module"),
|
||||
message: "WASM module manager not initialized".to_string(),
|
||||
})?;
|
||||
|
||||
// Remove module from manager
|
||||
wasm_manager
|
||||
.remove_module_internal(removal_request.module_uuid)
|
||||
.map_err(|e| WorkflowError::StepFailed {
|
||||
step_id: StepId::new("remove_module"),
|
||||
message: format!("Failed to remove module: {}", e),
|
||||
})?;
|
||||
|
||||
info!(
|
||||
"WASM module removed successfully: {}",
|
||||
removal_request.module_uuid
|
||||
);
|
||||
Ok(StepResult::Success)
|
||||
}
|
||||
|
||||
fn is_retryable(&self, _error: &WorkflowError) -> bool {
|
||||
false // Removal is not retryable
|
||||
}
|
||||
}
|
||||
|
||||
/// Create WASM module removal workflow
|
||||
///
|
||||
/// This workflow handles the process of removing a WASM module:
|
||||
/// - Finds the module to remove
|
||||
/// - Removes it from the manager
|
||||
///
|
||||
/// Workflow configuration:
|
||||
/// - FindModuleToRemove: No retry, 5s timeout (fast lookup)
|
||||
/// - RemoveModule: No retry, 5s timeout (fast removal)
|
||||
pub fn create_wasm_module_removal_workflow() -> WorkflowDefinition {
|
||||
WorkflowDefinition::new("wasm_module_removal", "WASM Module Removal")
|
||||
.add_step(
|
||||
StepDefinition::new(
|
||||
"find_module_to_remove",
|
||||
"Find Module to Remove",
|
||||
Arc::new(FindModuleToRemoveStep),
|
||||
)
|
||||
.with_timeout(Duration::from_secs(5))
|
||||
.with_failure_action(FailureAction::FailWorkflow),
|
||||
)
|
||||
.add_step(
|
||||
StepDefinition::new("remove_module", "Remove Module", Arc::new(RemoveModuleStep))
|
||||
.with_timeout(Duration::from_secs(5))
|
||||
.with_failure_action(FailureAction::FailWorkflow),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,993 @@
|
||||
//! Local worker registration workflow steps
|
||||
//!
|
||||
//! This workflow handles registration of local inference workers (SGLang, vLLM).
|
||||
//! For external API endpoints (OpenAI, xAI, etc.), see external_worker_registration.rs.
|
||||
//!
|
||||
//! Workflow order:
|
||||
//! 1. DetectConnectionMode - Probe HTTP and gRPC to determine connection mode
|
||||
//! 2. DiscoverMetadata - Fetch metadata from /server_info or gRPC
|
||||
//! 3. DiscoverDPInfo - Fetch DP (Data Parallel) information (only for DP-aware workers)
|
||||
//! 4. CreateWorker - Build worker object(s) with merged config + metadata
|
||||
//! 5. RegisterWorker - Register worker(s) in registry
|
||||
//! 6. UpdatePolicies - Update policy registry with worker information
|
||||
//! 7. ActivateWorker - Mark worker(s) as healthy
|
||||
|
||||
use std::{collections::HashMap, sync::Arc, time::Duration};
|
||||
|
||||
use async_trait::async_trait;
|
||||
use once_cell::sync::Lazy;
|
||||
use reqwest::Client;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
use tracing::{debug, info, warn};
|
||||
|
||||
use crate::{
|
||||
app_context::AppContext,
|
||||
core::{
|
||||
workflow::*, BasicWorkerBuilder, CircuitBreakerConfig, ConnectionMode,
|
||||
DPAwareWorkerBuilder, HealthConfig, ModelCard, RuntimeType, Worker, WorkerType,
|
||||
},
|
||||
protocols::worker_spec::WorkerConfigRequest,
|
||||
routers::grpc::client::GrpcClient,
|
||||
};
|
||||
|
||||
// HTTP client for metadata fetching
|
||||
static HTTP_CLIENT: Lazy<Client> = Lazy::new(|| {
|
||||
Client::builder()
|
||||
.timeout(Duration::from_secs(10))
|
||||
.build()
|
||||
.expect("Failed to create HTTP client")
|
||||
});
|
||||
|
||||
/// Server information returned from /server_info endpoint
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
struct ServerInfo {
|
||||
#[serde(alias = "model")]
|
||||
model_id: Option<String>,
|
||||
model_path: Option<String>,
|
||||
served_model_name: Option<String>,
|
||||
dp_size: Option<usize>,
|
||||
version: Option<String>,
|
||||
max_batch_size: Option<usize>,
|
||||
max_total_tokens: Option<usize>,
|
||||
max_prefill_tokens: Option<usize>,
|
||||
max_running_requests: Option<usize>,
|
||||
max_num_reqs: Option<usize>,
|
||||
}
|
||||
|
||||
/// Model information returned from /model_info endpoint
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
struct ModelInfo {
|
||||
model_path: Option<String>,
|
||||
tokenizer_path: Option<String>,
|
||||
is_generation: Option<bool>,
|
||||
/// HuggingFace model type string (e.g., "llama", "qwen2", "gpt_oss")
|
||||
model_type: Option<String>,
|
||||
/// Model architectures from HuggingFace config (e.g., ["LlamaForCausalLM"])
|
||||
architectures: Option<Vec<String>>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct DpInfo {
|
||||
pub dp_size: usize,
|
||||
pub model_id: String,
|
||||
}
|
||||
|
||||
/// Parse server info from JSON response
|
||||
fn parse_server_info(json: Value) -> Result<ServerInfo, String> {
|
||||
serde_json::from_value(json).map_err(|e| format!("Failed to parse server info: {}", e))
|
||||
}
|
||||
|
||||
/// Get server info from /server_info endpoint
|
||||
async fn get_server_info(url: &str, api_key: Option<&str>) -> Result<ServerInfo, String> {
|
||||
let base_url = url.trim_end_matches('/');
|
||||
let server_info_url = format!("{}/server_info", base_url);
|
||||
|
||||
let mut req = HTTP_CLIENT.get(&server_info_url);
|
||||
if let Some(key) = api_key {
|
||||
req = req.bearer_auth(key);
|
||||
}
|
||||
|
||||
let response = req
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| format!("Failed to connect to {}: {}", server_info_url, e))?;
|
||||
|
||||
if !response.status().is_success() {
|
||||
return Err(format!(
|
||||
"Server returned status {} from {}",
|
||||
response.status(),
|
||||
server_info_url
|
||||
));
|
||||
}
|
||||
|
||||
let json = response
|
||||
.json::<Value>()
|
||||
.await
|
||||
.map_err(|e| format!("Failed to parse response from {}: {}", server_info_url, e))?;
|
||||
|
||||
parse_server_info(json)
|
||||
}
|
||||
|
||||
/// Get model info from /model_info endpoint
|
||||
async fn get_model_info(url: &str, api_key: Option<&str>) -> Result<ModelInfo, String> {
|
||||
let base_url = url.trim_end_matches('/');
|
||||
let model_info_url = format!("{}/model_info", base_url);
|
||||
|
||||
let mut req = HTTP_CLIENT.get(&model_info_url);
|
||||
if let Some(key) = api_key {
|
||||
req = req.bearer_auth(key);
|
||||
}
|
||||
|
||||
let response = req
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| format!("Failed to connect to {}: {}", model_info_url, e))?;
|
||||
|
||||
if !response.status().is_success() {
|
||||
return Err(format!(
|
||||
"Server returned status {} from {}",
|
||||
response.status(),
|
||||
model_info_url
|
||||
));
|
||||
}
|
||||
|
||||
response
|
||||
.json::<ModelInfo>()
|
||||
.await
|
||||
.map_err(|e| format!("Failed to parse response from {}: {}", model_info_url, e))
|
||||
}
|
||||
|
||||
/// Get DP info for a worker URL
|
||||
async fn get_dp_info(url: &str, api_key: Option<&str>) -> Result<DpInfo, String> {
|
||||
let info = get_server_info(url, api_key).await?;
|
||||
|
||||
let dp_size = info
|
||||
.dp_size
|
||||
.ok_or_else(|| format!("No dp_size in response from {}", url))?;
|
||||
|
||||
let model_id = info
|
||||
.model_id
|
||||
.filter(|s| !s.is_empty())
|
||||
.or(info.served_model_name.filter(|s| !s.is_empty()))
|
||||
.or_else(|| {
|
||||
info.model_path
|
||||
.and_then(|path| path.split('/').next_back().map(|s| s.to_string()))
|
||||
})
|
||||
.unwrap_or_else(|| "unknown".to_string());
|
||||
|
||||
Ok(DpInfo { dp_size, model_id })
|
||||
}
|
||||
|
||||
/// Strip protocol prefix from URL
|
||||
fn strip_protocol(url: &str) -> String {
|
||||
url.trim_start_matches("http://")
|
||||
.trim_start_matches("https://")
|
||||
.trim_start_matches("grpc://")
|
||||
.to_string()
|
||||
}
|
||||
|
||||
/// Try HTTP health check
|
||||
async fn try_http_health_check(
|
||||
url: &str,
|
||||
timeout_secs: u64,
|
||||
client: &Client,
|
||||
) -> Result<(), String> {
|
||||
let is_https = url.starts_with("https://");
|
||||
let protocol = if is_https { "https" } else { "http" };
|
||||
let clean_url = strip_protocol(url);
|
||||
let health_url = format!("{}://{}/health", protocol, clean_url);
|
||||
|
||||
client
|
||||
.get(&health_url)
|
||||
.timeout(Duration::from_secs(timeout_secs))
|
||||
.send()
|
||||
.await
|
||||
.and_then(reqwest::Response::error_for_status)
|
||||
.map_err(|e| format!("Health check failed: {}", e))?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Perform gRPC health check with runtime type
|
||||
async fn do_grpc_health_check(
|
||||
grpc_url: &str,
|
||||
timeout_secs: u64,
|
||||
runtime_type: &str,
|
||||
) -> Result<(), String> {
|
||||
let connect_future = GrpcClient::connect(grpc_url, runtime_type);
|
||||
let client = tokio::time::timeout(Duration::from_secs(timeout_secs), connect_future)
|
||||
.await
|
||||
.map_err(|_| "gRPC connection timeout".to_string())?
|
||||
.map_err(|e| format!("gRPC connection failed: {}", e))?;
|
||||
|
||||
let health_future = client.health_check();
|
||||
tokio::time::timeout(Duration::from_secs(timeout_secs), health_future)
|
||||
.await
|
||||
.map_err(|_| "gRPC health check timeout".to_string())?
|
||||
.map_err(|e| format!("gRPC health check failed: {}", e))?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Try gRPC health check (tries SGLang first, then vLLM if not specified)
|
||||
async fn try_grpc_health_check(
|
||||
url: &str,
|
||||
timeout_secs: u64,
|
||||
runtime_type: Option<&str>,
|
||||
) -> Result<(), String> {
|
||||
let grpc_url = if url.starts_with("grpc://") {
|
||||
url.to_string()
|
||||
} else {
|
||||
format!("grpc://{}", strip_protocol(url))
|
||||
};
|
||||
|
||||
match runtime_type {
|
||||
Some(runtime) => do_grpc_health_check(&grpc_url, timeout_secs, runtime).await,
|
||||
None => {
|
||||
// Try SGLang first, then vLLM as fallback
|
||||
if let Ok(()) = do_grpc_health_check(&grpc_url, timeout_secs, "sglang").await {
|
||||
return Ok(());
|
||||
}
|
||||
do_grpc_health_check(&grpc_url, timeout_secs, "vllm")
|
||||
.await
|
||||
.map_err(|e| format!("gRPC failed (tried SGLang and vLLM): {}", e))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Fetch metadata from gRPC server
|
||||
async fn do_fetch_grpc_metadata(
|
||||
grpc_url: &str,
|
||||
runtime_type: &str,
|
||||
) -> Result<HashMap<String, String>, String> {
|
||||
let client = GrpcClient::connect(grpc_url, runtime_type)
|
||||
.await
|
||||
.map_err(|e| format!("Failed to connect to gRPC: {}", e))?;
|
||||
|
||||
let model_info = client
|
||||
.get_model_info()
|
||||
.await
|
||||
.map_err(|e| format!("Failed to fetch gRPC metadata: {}", e))?;
|
||||
|
||||
Ok(model_info.to_labels())
|
||||
}
|
||||
|
||||
/// Fetch gRPC metadata (returns labels and detected runtime type)
|
||||
async fn fetch_grpc_metadata(
|
||||
url: &str,
|
||||
runtime_type: Option<&str>,
|
||||
) -> Result<(HashMap<String, String>, String), String> {
|
||||
let grpc_url = if url.starts_with("grpc://") {
|
||||
url.to_string()
|
||||
} else {
|
||||
format!("grpc://{}", strip_protocol(url))
|
||||
};
|
||||
|
||||
match runtime_type {
|
||||
Some(runtime) => {
|
||||
let labels = do_fetch_grpc_metadata(&grpc_url, runtime).await?;
|
||||
Ok((labels, runtime.to_string()))
|
||||
}
|
||||
None => {
|
||||
// Try SGLang first, then vLLM as fallback
|
||||
if let Ok(labels) = do_fetch_grpc_metadata(&grpc_url, "sglang").await {
|
||||
return Ok((labels, "sglang".to_string()));
|
||||
}
|
||||
let labels = do_fetch_grpc_metadata(&grpc_url, "vllm")
|
||||
.await
|
||||
.map_err(|e| format!("gRPC metadata failed (tried SGLang and vLLM): {}", e))?;
|
||||
Ok((labels, "vllm".to_string()))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Step 1: Detect connection mode by probing HTTP and gRPC
|
||||
pub struct DetectConnectionModeStep;
|
||||
|
||||
#[async_trait]
|
||||
impl StepExecutor for DetectConnectionModeStep {
|
||||
async fn execute(&self, context: &mut WorkflowContext) -> WorkflowResult<StepResult> {
|
||||
let config: Arc<WorkerConfigRequest> = context
|
||||
.get("worker_config")
|
||||
.ok_or_else(|| WorkflowError::ContextValueNotFound("worker_config".to_string()))?;
|
||||
let app_context: Arc<AppContext> = context
|
||||
.get("app_context")
|
||||
.ok_or_else(|| WorkflowError::ContextValueNotFound("app_context".to_string()))?;
|
||||
|
||||
debug!(
|
||||
"Detecting connection mode for {} (timeout: {}s, max_attempts: {})",
|
||||
config.url, config.health_check_timeout_secs, config.max_connection_attempts
|
||||
);
|
||||
|
||||
// Try both protocols in parallel
|
||||
let url = config.url.clone();
|
||||
let timeout = config.health_check_timeout_secs;
|
||||
let client = &app_context.client;
|
||||
let runtime_type = config.runtime.as_deref();
|
||||
|
||||
let (http_result, grpc_result) = tokio::join!(
|
||||
try_http_health_check(&url, timeout, client),
|
||||
try_grpc_health_check(&url, timeout, runtime_type)
|
||||
);
|
||||
|
||||
let connection_mode = match (http_result, grpc_result) {
|
||||
(Ok(_), _) => {
|
||||
debug!("{} detected as HTTP", config.url);
|
||||
ConnectionMode::Http
|
||||
}
|
||||
(_, Ok(_)) => {
|
||||
debug!("{} detected as gRPC", config.url);
|
||||
ConnectionMode::Grpc { port: None }
|
||||
}
|
||||
(Err(http_err), Err(grpc_err)) => {
|
||||
return Err(WorkflowError::StepFailed {
|
||||
step_id: StepId::new("detect_connection_mode"),
|
||||
message: format!(
|
||||
"Both HTTP and gRPC health checks failed for {}: HTTP: {}, gRPC: {}",
|
||||
config.url, http_err, grpc_err
|
||||
),
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
context.set("connection_mode", connection_mode);
|
||||
Ok(StepResult::Success)
|
||||
}
|
||||
|
||||
fn is_retryable(&self, _error: &WorkflowError) -> bool {
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
/// Step 2: Discover metadata from worker
|
||||
pub struct DiscoverMetadataStep;
|
||||
|
||||
#[async_trait]
|
||||
impl StepExecutor for DiscoverMetadataStep {
|
||||
async fn execute(&self, context: &mut WorkflowContext) -> WorkflowResult<StepResult> {
|
||||
let config: Arc<WorkerConfigRequest> = context
|
||||
.get("worker_config")
|
||||
.ok_or_else(|| WorkflowError::ContextValueNotFound("worker_config".to_string()))?;
|
||||
let connection_mode: Arc<ConnectionMode> = context
|
||||
.get("connection_mode")
|
||||
.ok_or_else(|| WorkflowError::ContextValueNotFound("connection_mode".to_string()))?;
|
||||
|
||||
debug!(
|
||||
"Discovering metadata for {} ({:?})",
|
||||
config.url, *connection_mode
|
||||
);
|
||||
|
||||
let (discovered_labels, detected_runtime) = match connection_mode.as_ref() {
|
||||
ConnectionMode::Http => {
|
||||
let mut labels = HashMap::new();
|
||||
|
||||
// Fetch from /server_info for server-related metadata
|
||||
if let Ok(server_info) =
|
||||
get_server_info(&config.url, config.api_key.as_deref()).await
|
||||
{
|
||||
if let Some(model_path) = server_info.model_path.filter(|s| !s.is_empty()) {
|
||||
labels.insert("model_path".to_string(), model_path);
|
||||
}
|
||||
if let Some(served_model_name) =
|
||||
server_info.served_model_name.filter(|s| !s.is_empty())
|
||||
{
|
||||
labels.insert("served_model_name".to_string(), served_model_name);
|
||||
}
|
||||
}
|
||||
|
||||
// Fetch from /model_info for model-related metadata (model_type, architectures)
|
||||
if let Ok(model_info) = get_model_info(&config.url, config.api_key.as_deref()).await
|
||||
{
|
||||
if let Some(model_type) = model_info.model_type.filter(|s| !s.is_empty()) {
|
||||
labels.insert("model_type".to_string(), model_type);
|
||||
}
|
||||
if let Some(architectures) = model_info.architectures.filter(|a| !a.is_empty())
|
||||
{
|
||||
if let Ok(json_str) = serde_json::to_string(&architectures) {
|
||||
labels.insert("architectures".to_string(), json_str);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok((labels, None))
|
||||
}
|
||||
ConnectionMode::Grpc { .. } => {
|
||||
let runtime_type = config.runtime.as_deref();
|
||||
fetch_grpc_metadata(&config.url, runtime_type)
|
||||
.await
|
||||
.map(|(labels, runtime)| (labels, Some(runtime)))
|
||||
}
|
||||
}
|
||||
.unwrap_or_else(|e| {
|
||||
warn!("Failed to fetch metadata for {}: {}", config.url, e);
|
||||
(HashMap::new(), None)
|
||||
});
|
||||
|
||||
debug!(
|
||||
"Discovered {} metadata labels for {}",
|
||||
discovered_labels.len(),
|
||||
config.url
|
||||
);
|
||||
|
||||
context.set("discovered_labels", discovered_labels);
|
||||
if let Some(runtime) = detected_runtime {
|
||||
debug!("Detected runtime type: {}", runtime);
|
||||
context.set("detected_runtime_type", runtime);
|
||||
}
|
||||
|
||||
Ok(StepResult::Success)
|
||||
}
|
||||
|
||||
fn is_retryable(&self, _error: &WorkflowError) -> bool {
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
/// Step 2.5: Discover DP (Data Parallel) information (only for DP-aware workers)
|
||||
pub struct DiscoverDPInfoStep;
|
||||
|
||||
#[async_trait]
|
||||
impl StepExecutor for DiscoverDPInfoStep {
|
||||
async fn execute(&self, context: &mut WorkflowContext) -> WorkflowResult<StepResult> {
|
||||
let config: Arc<WorkerConfigRequest> = context
|
||||
.get("worker_config")
|
||||
.ok_or_else(|| WorkflowError::ContextValueNotFound("worker_config".to_string()))?;
|
||||
|
||||
if !config.dp_aware {
|
||||
debug!(
|
||||
"Worker {} is not DP-aware, skipping DP discovery",
|
||||
config.url
|
||||
);
|
||||
return Ok(StepResult::Success);
|
||||
}
|
||||
|
||||
debug!("Discovering DP info for {} (DP-aware)", config.url);
|
||||
|
||||
let dp_info = get_dp_info(&config.url, config.api_key.as_deref())
|
||||
.await
|
||||
.map_err(|e| WorkflowError::StepFailed {
|
||||
step_id: StepId::new("discover_dp_info"),
|
||||
message: format!("Failed to get DP info: {}", e),
|
||||
})?;
|
||||
|
||||
debug!(
|
||||
"Discovered DP size {} for {} (model: {})",
|
||||
dp_info.dp_size, config.url, dp_info.model_id
|
||||
);
|
||||
|
||||
context.set("dp_info", dp_info);
|
||||
Ok(StepResult::Success)
|
||||
}
|
||||
|
||||
fn is_retryable(&self, _error: &WorkflowError) -> bool {
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
/// Step 3: Create worker object with merged configuration + metadata
|
||||
pub struct CreateWorkerStep;
|
||||
|
||||
#[async_trait]
|
||||
impl StepExecutor for CreateWorkerStep {
|
||||
async fn execute(&self, context: &mut WorkflowContext) -> WorkflowResult<StepResult> {
|
||||
let config: Arc<WorkerConfigRequest> = context
|
||||
.get("worker_config")
|
||||
.ok_or_else(|| WorkflowError::ContextValueNotFound("worker_config".to_string()))?;
|
||||
let app_context: Arc<AppContext> = context
|
||||
.get("app_context")
|
||||
.ok_or_else(|| WorkflowError::ContextValueNotFound("app_context".to_string()))?;
|
||||
let connection_mode: Arc<ConnectionMode> = context
|
||||
.get("connection_mode")
|
||||
.ok_or_else(|| WorkflowError::ContextValueNotFound("connection_mode".to_string()))?;
|
||||
let discovered_labels: Arc<HashMap<String, String>> = context
|
||||
.get("discovered_labels")
|
||||
.ok_or_else(|| WorkflowError::ContextValueNotFound("discovered_labels".to_string()))?;
|
||||
|
||||
// Check if worker already exists
|
||||
if app_context
|
||||
.worker_registry
|
||||
.get_by_url(&config.url)
|
||||
.is_some()
|
||||
{
|
||||
return Err(WorkflowError::StepFailed {
|
||||
step_id: StepId::new("create_worker"),
|
||||
message: format!("Worker {} already exists", config.url),
|
||||
});
|
||||
}
|
||||
|
||||
// Build labels from config
|
||||
let mut config_labels = config.labels.clone();
|
||||
if let Some(priority) = config.priority {
|
||||
config_labels.insert("priority".to_string(), priority.to_string());
|
||||
}
|
||||
if let Some(cost) = config.cost {
|
||||
config_labels.insert("cost".to_string(), cost.to_string());
|
||||
}
|
||||
|
||||
// Merge: discovered labels first, then config labels (config takes precedence)
|
||||
let mut final_labels = discovered_labels.as_ref().clone();
|
||||
for (key, value) in &config_labels {
|
||||
final_labels.insert(key.clone(), value.clone());
|
||||
}
|
||||
|
||||
// Determine model_id: config > served_model_name > model_path > "unknown"
|
||||
let model_id = config
|
||||
.model_id
|
||||
.clone()
|
||||
.or_else(|| final_labels.get("served_model_name").cloned())
|
||||
.or_else(|| final_labels.get("model_path").cloned())
|
||||
.unwrap_or_else(|| "unknown".to_string());
|
||||
|
||||
if model_id != "unknown" {
|
||||
debug!("Using model_id: {}", model_id);
|
||||
}
|
||||
|
||||
// Create ModelCard
|
||||
let model_card = {
|
||||
let mut card = ModelCard::new(&model_id);
|
||||
if let Some(ref tokenizer_path) = config.tokenizer_path {
|
||||
card = card.with_tokenizer_path(tokenizer_path.clone());
|
||||
}
|
||||
if let Some(ref reasoning_parser) = config.reasoning_parser {
|
||||
card = card.with_reasoning_parser(reasoning_parser.clone());
|
||||
}
|
||||
if let Some(ref tool_parser) = config.tool_parser {
|
||||
card = card.with_tool_parser(tool_parser.clone());
|
||||
}
|
||||
if let Some(ref chat_template) = config.chat_template {
|
||||
card = card.with_chat_template(chat_template.clone());
|
||||
}
|
||||
// Set HuggingFace model type from discovered labels
|
||||
if let Some(model_type_str) = final_labels.get("model_type") {
|
||||
card = card.with_hf_model_type(model_type_str.clone());
|
||||
}
|
||||
// Set architectures from discovered labels (JSON array string)
|
||||
if let Some(architectures_json) = final_labels.get("architectures") {
|
||||
if let Ok(architectures) = serde_json::from_str::<Vec<String>>(architectures_json) {
|
||||
card = card.with_architectures(architectures);
|
||||
}
|
||||
}
|
||||
card
|
||||
};
|
||||
|
||||
debug!(
|
||||
"Creating worker {} with {} discovered + {} config = {} final labels",
|
||||
config.url,
|
||||
discovered_labels.len(),
|
||||
config_labels.len(),
|
||||
final_labels.len()
|
||||
);
|
||||
|
||||
// Parse worker type
|
||||
let worker_type = config
|
||||
.worker_type
|
||||
.as_ref()
|
||||
.map(|t| match t.as_str() {
|
||||
"prefill" => WorkerType::Prefill {
|
||||
bootstrap_port: config.bootstrap_port,
|
||||
},
|
||||
"decode" => WorkerType::Decode,
|
||||
_ => WorkerType::Regular,
|
||||
})
|
||||
.unwrap_or(WorkerType::Regular);
|
||||
|
||||
// Get runtime type (for gRPC workers)
|
||||
let runtime_type = if matches!(connection_mode.as_ref(), ConnectionMode::Grpc { .. }) {
|
||||
if let Some(detected_runtime) = context.get::<String>("detected_runtime_type") {
|
||||
match detected_runtime.as_str() {
|
||||
"vllm" => RuntimeType::Vllm,
|
||||
_ => RuntimeType::Sglang,
|
||||
}
|
||||
} else if let Some(ref runtime) = config.runtime {
|
||||
match runtime.as_str() {
|
||||
"vllm" => RuntimeType::Vllm,
|
||||
_ => RuntimeType::Sglang,
|
||||
}
|
||||
} else {
|
||||
RuntimeType::Sglang
|
||||
}
|
||||
} else {
|
||||
RuntimeType::Sglang
|
||||
};
|
||||
|
||||
// Build circuit breaker config
|
||||
let circuit_breaker_config = {
|
||||
let cfg = app_context.router_config.effective_circuit_breaker_config();
|
||||
CircuitBreakerConfig {
|
||||
failure_threshold: cfg.failure_threshold,
|
||||
success_threshold: cfg.success_threshold,
|
||||
timeout_duration: Duration::from_secs(cfg.timeout_duration_secs),
|
||||
window_duration: Duration::from_secs(cfg.window_duration_secs),
|
||||
}
|
||||
};
|
||||
|
||||
// Build health config
|
||||
let health_config = {
|
||||
let cfg = &app_context.router_config.health_check;
|
||||
HealthConfig {
|
||||
timeout_secs: cfg.timeout_secs,
|
||||
check_interval_secs: cfg.check_interval_secs,
|
||||
endpoint: cfg.endpoint.clone(),
|
||||
failure_threshold: cfg.failure_threshold,
|
||||
success_threshold: cfg.success_threshold,
|
||||
}
|
||||
};
|
||||
|
||||
// Normalize URL: add protocol prefix only if missing
|
||||
let normalized_url = if config.url.starts_with("http://")
|
||||
|| config.url.starts_with("https://")
|
||||
|| config.url.starts_with("grpc://")
|
||||
{
|
||||
config.url.clone()
|
||||
} else {
|
||||
match connection_mode.as_ref() {
|
||||
ConnectionMode::Http => format!("http://{}", config.url),
|
||||
ConnectionMode::Grpc { .. } => format!("grpc://{}", config.url),
|
||||
}
|
||||
};
|
||||
|
||||
if normalized_url != config.url {
|
||||
debug!(
|
||||
"Normalized worker URL: {} -> {} ({:?})",
|
||||
config.url,
|
||||
normalized_url,
|
||||
connection_mode.as_ref()
|
||||
);
|
||||
}
|
||||
|
||||
// Handle DP-aware vs non-DP-aware workers
|
||||
if config.dp_aware {
|
||||
let dp_info: Arc<DpInfo> = context
|
||||
.get("dp_info")
|
||||
.ok_or_else(|| WorkflowError::ContextValueNotFound("dp_info".to_string()))?;
|
||||
|
||||
debug!(
|
||||
"Creating {} DP-aware workers for {} (dp_size: {})",
|
||||
dp_info.dp_size, config.url, dp_info.dp_size
|
||||
);
|
||||
|
||||
let mut workers = Vec::new();
|
||||
for rank in 0..dp_info.dp_size {
|
||||
let mut builder =
|
||||
DPAwareWorkerBuilder::new(normalized_url.clone(), rank, dp_info.dp_size)
|
||||
.model(model_card.clone())
|
||||
.worker_type(worker_type.clone())
|
||||
.connection_mode(connection_mode.as_ref().clone())
|
||||
.runtime_type(runtime_type.clone())
|
||||
.circuit_breaker_config(circuit_breaker_config.clone())
|
||||
.health_config(health_config.clone());
|
||||
|
||||
if let Some(ref api_key) = config.api_key {
|
||||
builder = builder.api_key(api_key.clone());
|
||||
}
|
||||
if !final_labels.is_empty() {
|
||||
builder = builder.labels(final_labels.clone());
|
||||
}
|
||||
|
||||
let worker = Arc::new(builder.build()) as Arc<dyn Worker>;
|
||||
worker.set_healthy(false);
|
||||
workers.push(worker);
|
||||
|
||||
debug!(
|
||||
"Created DP-aware worker {}@{}/{} ({:?})",
|
||||
config.url,
|
||||
rank,
|
||||
dp_info.dp_size,
|
||||
connection_mode.as_ref()
|
||||
);
|
||||
}
|
||||
|
||||
context.set("workers", workers);
|
||||
context.set("labels", final_labels);
|
||||
} else {
|
||||
let mut builder = BasicWorkerBuilder::new(normalized_url.clone())
|
||||
.model(model_card)
|
||||
.worker_type(worker_type)
|
||||
.connection_mode(connection_mode.as_ref().clone())
|
||||
.runtime_type(runtime_type)
|
||||
.circuit_breaker_config(circuit_breaker_config)
|
||||
.health_config(health_config);
|
||||
|
||||
if let Some(ref api_key) = config.api_key {
|
||||
builder = builder.api_key(api_key.clone());
|
||||
}
|
||||
if !final_labels.is_empty() {
|
||||
builder = builder.labels(final_labels.clone());
|
||||
}
|
||||
|
||||
let worker = Arc::new(builder.build()) as Arc<dyn Worker>;
|
||||
worker.set_healthy(false);
|
||||
|
||||
debug!(
|
||||
"Created worker object for {} ({:?}) with {} labels",
|
||||
config.url,
|
||||
connection_mode.as_ref(),
|
||||
final_labels.len()
|
||||
);
|
||||
|
||||
context.set("worker", worker);
|
||||
context.set("labels", final_labels);
|
||||
}
|
||||
|
||||
Ok(StepResult::Success)
|
||||
}
|
||||
|
||||
fn is_retryable(&self, _error: &WorkflowError) -> bool {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/// Step 4: Register worker(s) in registry
|
||||
pub struct RegisterWorkerStep;
|
||||
|
||||
#[async_trait]
|
||||
impl StepExecutor for RegisterWorkerStep {
|
||||
async fn execute(&self, context: &mut WorkflowContext) -> WorkflowResult<StepResult> {
|
||||
let config: Arc<WorkerConfigRequest> = context
|
||||
.get("worker_config")
|
||||
.ok_or_else(|| WorkflowError::ContextValueNotFound("worker_config".to_string()))?;
|
||||
let app_context: Arc<AppContext> = context
|
||||
.get("app_context")
|
||||
.ok_or_else(|| WorkflowError::ContextValueNotFound("app_context".to_string()))?;
|
||||
|
||||
if config.dp_aware {
|
||||
let workers: Arc<Vec<Arc<dyn Worker>>> = context
|
||||
.get("workers")
|
||||
.ok_or_else(|| WorkflowError::ContextValueNotFound("workers".to_string()))?;
|
||||
|
||||
let mut worker_ids = Vec::new();
|
||||
for worker in workers.iter() {
|
||||
let worker_id = app_context.worker_registry.register(Arc::clone(worker));
|
||||
worker_ids.push(worker_id.clone());
|
||||
debug!(
|
||||
"Registered DP-aware worker {} with ID {:?}",
|
||||
config.url, worker_id
|
||||
);
|
||||
}
|
||||
|
||||
context.set("worker_ids", worker_ids);
|
||||
} else {
|
||||
let worker: Arc<Arc<dyn Worker>> = context
|
||||
.get("worker")
|
||||
.ok_or_else(|| WorkflowError::ContextValueNotFound("worker".to_string()))?;
|
||||
|
||||
let worker_id = app_context
|
||||
.worker_registry
|
||||
.register(Arc::clone(worker.as_ref()));
|
||||
debug!("Registered worker {} with ID {:?}", config.url, worker_id);
|
||||
context.set("worker_id", worker_id);
|
||||
}
|
||||
|
||||
Ok(StepResult::Success)
|
||||
}
|
||||
|
||||
fn is_retryable(&self, _error: &WorkflowError) -> bool {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/// Step 5: Update policy registry with worker information
|
||||
pub struct UpdatePoliciesStep;
|
||||
|
||||
#[async_trait]
|
||||
impl StepExecutor for UpdatePoliciesStep {
|
||||
async fn execute(&self, context: &mut WorkflowContext) -> WorkflowResult<StepResult> {
|
||||
let config: Arc<WorkerConfigRequest> = context
|
||||
.get("worker_config")
|
||||
.ok_or_else(|| WorkflowError::ContextValueNotFound("worker_config".to_string()))?;
|
||||
let labels: Arc<HashMap<String, String>> = context
|
||||
.get("labels")
|
||||
.ok_or_else(|| WorkflowError::ContextValueNotFound("labels".to_string()))?;
|
||||
let app_context: Arc<AppContext> = context
|
||||
.get("app_context")
|
||||
.ok_or_else(|| WorkflowError::ContextValueNotFound("app_context".to_string()))?;
|
||||
|
||||
let policy_hint = labels.get("policy").map(|s| s.as_str());
|
||||
|
||||
if config.dp_aware {
|
||||
let workers: Arc<Vec<Arc<dyn Worker>>> = context
|
||||
.get("workers")
|
||||
.ok_or_else(|| WorkflowError::ContextValueNotFound("workers".to_string()))?;
|
||||
|
||||
let model_id = workers[0].model_id().to_string();
|
||||
|
||||
for _ in 0..workers.len() {
|
||||
app_context
|
||||
.policy_registry
|
||||
.on_worker_added(&model_id, policy_hint);
|
||||
}
|
||||
|
||||
// Initialize cache-aware policy if needed
|
||||
let all_workers = app_context.worker_registry.get_by_model_fast(&model_id);
|
||||
if let Some(policy) = app_context.policy_registry.get_policy(&model_id) {
|
||||
if policy.name() == "cache_aware" {
|
||||
app_context
|
||||
.policy_registry
|
||||
.init_cache_aware_policy(&model_id, &all_workers);
|
||||
}
|
||||
}
|
||||
|
||||
debug!(
|
||||
"Updated policies for {} DP-aware workers {} (model: {})",
|
||||
workers.len(),
|
||||
config.url,
|
||||
model_id
|
||||
);
|
||||
} else {
|
||||
let worker: Arc<Arc<dyn Worker>> = context
|
||||
.get("worker")
|
||||
.ok_or_else(|| WorkflowError::ContextValueNotFound("worker".to_string()))?;
|
||||
|
||||
let model_id = worker.model_id().to_string();
|
||||
|
||||
app_context
|
||||
.policy_registry
|
||||
.on_worker_added(&model_id, policy_hint);
|
||||
|
||||
// Initialize cache-aware policy if needed
|
||||
let all_workers = app_context.worker_registry.get_by_model_fast(&model_id);
|
||||
if let Some(policy) = app_context.policy_registry.get_policy(&model_id) {
|
||||
if policy.name() == "cache_aware" {
|
||||
app_context
|
||||
.policy_registry
|
||||
.init_cache_aware_policy(&model_id, &all_workers);
|
||||
}
|
||||
}
|
||||
|
||||
// Initialize bucket policies for prefill workers
|
||||
let prefill_workers = app_context.worker_registry.get_prefill_workers();
|
||||
let policy = app_context.policy_registry.get_prefill_policy();
|
||||
if policy.name() == "bucket" {
|
||||
app_context
|
||||
.policy_registry
|
||||
.init_pd_bucket_policies(&prefill_workers);
|
||||
}
|
||||
|
||||
debug!(
|
||||
"Updated policies for worker {} (model: {})",
|
||||
config.url, model_id
|
||||
);
|
||||
}
|
||||
|
||||
Ok(StepResult::Success)
|
||||
}
|
||||
|
||||
fn is_retryable(&self, _error: &WorkflowError) -> bool {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/// Step 6: Activate worker(s) by marking them as healthy
|
||||
pub struct ActivateWorkerStep;
|
||||
|
||||
#[async_trait]
|
||||
impl StepExecutor for ActivateWorkerStep {
|
||||
async fn execute(&self, context: &mut WorkflowContext) -> WorkflowResult<StepResult> {
|
||||
let config: Arc<WorkerConfigRequest> = context
|
||||
.get("worker_config")
|
||||
.ok_or_else(|| WorkflowError::ContextValueNotFound("worker_config".to_string()))?;
|
||||
|
||||
if config.dp_aware {
|
||||
let workers: Arc<Vec<Arc<dyn Worker>>> = context
|
||||
.get("workers")
|
||||
.ok_or_else(|| WorkflowError::ContextValueNotFound("workers".to_string()))?;
|
||||
|
||||
for worker in workers.iter() {
|
||||
worker.set_healthy(true);
|
||||
}
|
||||
|
||||
info!(
|
||||
"Activated {} DP-aware workers from {} (marked as healthy)",
|
||||
workers.len(),
|
||||
config.url
|
||||
);
|
||||
} else {
|
||||
let worker: Arc<Arc<dyn Worker>> = context
|
||||
.get("worker")
|
||||
.ok_or_else(|| WorkflowError::ContextValueNotFound("worker".to_string()))?;
|
||||
|
||||
worker.set_healthy(true);
|
||||
|
||||
info!("Activated worker {} (marked as healthy)", config.url);
|
||||
}
|
||||
|
||||
Ok(StepResult::Success)
|
||||
}
|
||||
|
||||
fn is_retryable(&self, _error: &WorkflowError) -> bool {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/// Create local worker registration workflow definition
|
||||
pub fn create_worker_registration_workflow(
|
||||
router_config: &crate::config::RouterConfig,
|
||||
) -> WorkflowDefinition {
|
||||
let detect_timeout = Duration::from_secs(router_config.worker_startup_timeout_secs);
|
||||
|
||||
// Calculate max_attempts based on timeout
|
||||
let timeout_secs = detect_timeout.as_secs() as f64;
|
||||
let effective_timeout = timeout_secs * 0.9;
|
||||
let max_attempts = if effective_timeout > 10.0 {
|
||||
(5 + ((effective_timeout - 10.0) / 5.0).ceil() as u32).max(3)
|
||||
} else {
|
||||
3
|
||||
};
|
||||
|
||||
WorkflowDefinition::new("worker_registration", "Worker Registration")
|
||||
.add_step(
|
||||
StepDefinition::new(
|
||||
"detect_connection_mode",
|
||||
"Detect Connection Mode",
|
||||
Arc::new(DetectConnectionModeStep),
|
||||
)
|
||||
.with_retry(RetryPolicy {
|
||||
max_attempts,
|
||||
backoff: BackoffStrategy::Linear {
|
||||
increment: Duration::from_secs(1),
|
||||
max: Duration::from_secs(5),
|
||||
},
|
||||
})
|
||||
.with_timeout(detect_timeout)
|
||||
.with_failure_action(FailureAction::FailWorkflow),
|
||||
)
|
||||
.add_step(
|
||||
StepDefinition::new(
|
||||
"discover_metadata",
|
||||
"Discover Metadata",
|
||||
Arc::new(DiscoverMetadataStep),
|
||||
)
|
||||
.with_retry(RetryPolicy {
|
||||
max_attempts: 3,
|
||||
backoff: BackoffStrategy::Fixed(Duration::from_secs(1)),
|
||||
})
|
||||
.with_timeout(Duration::from_secs(10))
|
||||
.with_failure_action(FailureAction::ContinueNextStep),
|
||||
)
|
||||
.add_step(
|
||||
StepDefinition::new(
|
||||
"discover_dp_info",
|
||||
"Discover DP Info",
|
||||
Arc::new(DiscoverDPInfoStep),
|
||||
)
|
||||
.with_retry(RetryPolicy {
|
||||
max_attempts: 3,
|
||||
backoff: BackoffStrategy::Fixed(Duration::from_secs(1)),
|
||||
})
|
||||
.with_timeout(Duration::from_secs(10))
|
||||
.with_failure_action(FailureAction::FailWorkflow),
|
||||
)
|
||||
.add_step(
|
||||
StepDefinition::new("create_worker", "Create Worker", Arc::new(CreateWorkerStep))
|
||||
.with_timeout(Duration::from_secs(5))
|
||||
.with_failure_action(FailureAction::FailWorkflow),
|
||||
)
|
||||
.add_step(
|
||||
StepDefinition::new(
|
||||
"register_worker",
|
||||
"Register Worker",
|
||||
Arc::new(RegisterWorkerStep),
|
||||
)
|
||||
.with_timeout(Duration::from_secs(5))
|
||||
.with_failure_action(FailureAction::FailWorkflow),
|
||||
)
|
||||
.add_step(
|
||||
StepDefinition::new(
|
||||
"update_policies",
|
||||
"Update Policies",
|
||||
Arc::new(UpdatePoliciesStep),
|
||||
)
|
||||
.with_timeout(Duration::from_secs(5))
|
||||
.with_failure_action(FailureAction::ContinueNextStep),
|
||||
)
|
||||
.add_step(
|
||||
StepDefinition::new(
|
||||
"activate_worker",
|
||||
"Activate Worker",
|
||||
Arc::new(ActivateWorkerStep),
|
||||
)
|
||||
.with_timeout(Duration::from_secs(5))
|
||||
.with_failure_action(FailureAction::FailWorkflow),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,310 @@
|
||||
//! Worker Removal Workflow Steps
|
||||
//!
|
||||
//! This module implements the workflow steps for removing workers from the router.
|
||||
//! Handles both single worker removal and DP-aware worker removal with prefix matching.
|
||||
//!
|
||||
//! Steps:
|
||||
//! 1. FindWorkersToRemove - Identify workers to remove based on URL (handles DP-aware prefix matching)
|
||||
//! 2. RemoveFromPolicyRegistry - Remove workers from policy registry and cache-aware policies
|
||||
//! 3. RemoveFromWorkerRegistry - Remove workers from worker registry
|
||||
//! 4. UpdateRemainingPolicies - Update cache-aware policies for remaining workers
|
||||
|
||||
use std::{collections::HashSet, sync::Arc};
|
||||
|
||||
use async_trait::async_trait;
|
||||
use tracing::{debug, info};
|
||||
|
||||
use crate::{
|
||||
app_context::AppContext,
|
||||
core::{workflow::*, Worker},
|
||||
};
|
||||
|
||||
/// Request structure for worker removal
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct WorkerRemovalRequest {
|
||||
pub url: String,
|
||||
pub dp_aware: bool,
|
||||
}
|
||||
|
||||
/// Step 1: Find workers to remove based on URL
|
||||
pub struct FindWorkersToRemoveStep;
|
||||
|
||||
#[async_trait]
|
||||
impl StepExecutor for FindWorkersToRemoveStep {
|
||||
async fn execute(&self, context: &mut WorkflowContext) -> WorkflowResult<StepResult> {
|
||||
let request: Arc<WorkerRemovalRequest> = context
|
||||
.get("removal_request")
|
||||
.ok_or_else(|| WorkflowError::ContextValueNotFound("removal_request".to_string()))?;
|
||||
let app_context: Arc<AppContext> = context
|
||||
.get("app_context")
|
||||
.ok_or_else(|| WorkflowError::ContextValueNotFound("app_context".to_string()))?;
|
||||
|
||||
debug!(
|
||||
"Finding workers to remove for {} (dp_aware: {})",
|
||||
request.url, request.dp_aware
|
||||
);
|
||||
|
||||
let workers_to_remove: Vec<Arc<dyn Worker>> = if request.dp_aware {
|
||||
// DP-aware: Find all workers with matching prefix
|
||||
let worker_url_prefix = format!("{}@", request.url);
|
||||
let all_workers = app_context.worker_registry.get_all();
|
||||
|
||||
all_workers
|
||||
.iter()
|
||||
.filter(|worker| worker.url().starts_with(&worker_url_prefix))
|
||||
.cloned()
|
||||
.collect()
|
||||
} else {
|
||||
// Non-DP-aware: Find single worker by exact URL
|
||||
match app_context.worker_registry.get_by_url(&request.url) {
|
||||
Some(worker) => vec![worker],
|
||||
None => Vec::new(),
|
||||
}
|
||||
};
|
||||
|
||||
if workers_to_remove.is_empty() {
|
||||
let error_msg = if request.dp_aware {
|
||||
format!("No workers found with prefix {}@", request.url)
|
||||
} else {
|
||||
format!("Worker {} not found", request.url)
|
||||
};
|
||||
return Err(WorkflowError::StepFailed {
|
||||
step_id: StepId::new("find_workers_to_remove"),
|
||||
message: error_msg,
|
||||
});
|
||||
}
|
||||
|
||||
debug!(
|
||||
"Found {} worker(s) to remove for {}",
|
||||
workers_to_remove.len(),
|
||||
request.url
|
||||
);
|
||||
|
||||
// Store workers and their model IDs for subsequent steps
|
||||
let worker_urls: Vec<String> = workers_to_remove
|
||||
.iter()
|
||||
.map(|w| w.url().to_string())
|
||||
.collect();
|
||||
|
||||
let affected_models: HashSet<String> = workers_to_remove
|
||||
.iter()
|
||||
.map(|w| w.model_id().to_string())
|
||||
.collect();
|
||||
|
||||
context.set("workers_to_remove", workers_to_remove);
|
||||
context.set("worker_urls", worker_urls);
|
||||
context.set("affected_models", affected_models);
|
||||
|
||||
Ok(StepResult::Success)
|
||||
}
|
||||
|
||||
fn is_retryable(&self, _error: &WorkflowError) -> bool {
|
||||
false // Worker not found is not retryable
|
||||
}
|
||||
}
|
||||
|
||||
/// Step 2: Remove workers from policy registry
|
||||
pub struct RemoveFromPolicyRegistryStep;
|
||||
|
||||
#[async_trait]
|
||||
impl StepExecutor for RemoveFromPolicyRegistryStep {
|
||||
async fn execute(&self, context: &mut WorkflowContext) -> WorkflowResult<StepResult> {
|
||||
let app_context: Arc<AppContext> = context
|
||||
.get("app_context")
|
||||
.ok_or_else(|| WorkflowError::ContextValueNotFound("app_context".to_string()))?;
|
||||
let workers_to_remove: Arc<Vec<Arc<dyn Worker>>> = context
|
||||
.get("workers_to_remove")
|
||||
.ok_or_else(|| WorkflowError::ContextValueNotFound("workers_to_remove".to_string()))?;
|
||||
|
||||
debug!(
|
||||
"Removing {} worker(s) from policy registry",
|
||||
workers_to_remove.len()
|
||||
);
|
||||
|
||||
for worker in workers_to_remove.iter() {
|
||||
let model_id = worker.model_id().to_string();
|
||||
let worker_url = worker.url();
|
||||
|
||||
// Remove from cache-aware policy
|
||||
app_context
|
||||
.policy_registry
|
||||
.remove_worker_from_cache_aware(&model_id, worker_url);
|
||||
|
||||
// Notify policy registry
|
||||
app_context.policy_registry.on_worker_removed(&model_id);
|
||||
|
||||
debug!(
|
||||
"Removed worker {} from policy registry (model: {})",
|
||||
worker_url, model_id
|
||||
);
|
||||
}
|
||||
|
||||
Ok(StepResult::Success)
|
||||
}
|
||||
|
||||
fn is_retryable(&self, _error: &WorkflowError) -> bool {
|
||||
false // Policy removal is not retryable
|
||||
}
|
||||
}
|
||||
|
||||
/// Step 3: Remove workers from worker registry
|
||||
pub struct RemoveFromWorkerRegistryStep;
|
||||
|
||||
#[async_trait]
|
||||
impl StepExecutor for RemoveFromWorkerRegistryStep {
|
||||
async fn execute(&self, context: &mut WorkflowContext) -> WorkflowResult<StepResult> {
|
||||
let app_context: Arc<AppContext> = context
|
||||
.get("app_context")
|
||||
.ok_or_else(|| WorkflowError::ContextValueNotFound("app_context".to_string()))?;
|
||||
let worker_urls: Arc<Vec<String>> = context
|
||||
.get("worker_urls")
|
||||
.ok_or_else(|| WorkflowError::ContextValueNotFound("worker_urls".to_string()))?;
|
||||
|
||||
debug!(
|
||||
"Removing {} worker(s) from worker registry",
|
||||
worker_urls.len()
|
||||
);
|
||||
|
||||
let mut removed_count = 0;
|
||||
for worker_url in worker_urls.iter() {
|
||||
if app_context
|
||||
.worker_registry
|
||||
.remove_by_url(worker_url)
|
||||
.is_some()
|
||||
{
|
||||
removed_count += 1;
|
||||
debug!("Removed worker {} from registry", worker_url);
|
||||
}
|
||||
}
|
||||
|
||||
if removed_count != worker_urls.len() {
|
||||
return Err(WorkflowError::StepFailed {
|
||||
step_id: StepId::new("remove_from_worker_registry"),
|
||||
message: format!(
|
||||
"Expected to remove {} workers but only removed {}",
|
||||
worker_urls.len(),
|
||||
removed_count
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
Ok(StepResult::Success)
|
||||
}
|
||||
|
||||
fn is_retryable(&self, _error: &WorkflowError) -> bool {
|
||||
false // Worker removal is not retryable
|
||||
}
|
||||
}
|
||||
|
||||
/// Step 4: Update cache-aware policies for remaining workers
|
||||
pub struct UpdateRemainingPoliciesStep;
|
||||
|
||||
#[async_trait]
|
||||
impl StepExecutor for UpdateRemainingPoliciesStep {
|
||||
async fn execute(&self, context: &mut WorkflowContext) -> WorkflowResult<StepResult> {
|
||||
let app_context: Arc<AppContext> = context
|
||||
.get("app_context")
|
||||
.ok_or_else(|| WorkflowError::ContextValueNotFound("app_context".to_string()))?;
|
||||
let affected_models: Arc<HashSet<String>> = context
|
||||
.get("affected_models")
|
||||
.ok_or_else(|| WorkflowError::ContextValueNotFound("affected_models".to_string()))?;
|
||||
let worker_urls: Arc<Vec<String>> = context
|
||||
.get("worker_urls")
|
||||
.ok_or_else(|| WorkflowError::ContextValueNotFound("worker_urls".to_string()))?;
|
||||
|
||||
debug!(
|
||||
"Updating cache-aware policies for {} affected model(s)",
|
||||
affected_models.len()
|
||||
);
|
||||
|
||||
for model_id in affected_models.iter() {
|
||||
let remaining_workers = app_context.worker_registry.get_by_model_fast(model_id);
|
||||
|
||||
if let Some(policy) = app_context.policy_registry.get_policy(model_id) {
|
||||
if policy.name() == "cache_aware" && !remaining_workers.is_empty() {
|
||||
app_context
|
||||
.policy_registry
|
||||
.init_cache_aware_policy(model_id, &remaining_workers);
|
||||
|
||||
debug!(
|
||||
"Updated cache-aware policy for model {} ({} remaining workers)",
|
||||
model_id,
|
||||
remaining_workers.len()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Log final result at info level
|
||||
if worker_urls.len() == 1 {
|
||||
info!("Removed worker {}", worker_urls[0]);
|
||||
} else {
|
||||
info!(
|
||||
"Removed {} DP-aware workers: {:?}",
|
||||
worker_urls.len(),
|
||||
worker_urls
|
||||
);
|
||||
}
|
||||
|
||||
Ok(StepResult::Success)
|
||||
}
|
||||
|
||||
fn is_retryable(&self, _error: &WorkflowError) -> bool {
|
||||
false // Policy update is not retryable
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a worker removal workflow definition
|
||||
pub fn create_worker_removal_workflow() -> WorkflowDefinition {
|
||||
use std::time::Duration;
|
||||
|
||||
WorkflowDefinition::new("worker_removal", "Remove worker from router")
|
||||
.add_step(
|
||||
StepDefinition::new(
|
||||
"find_workers_to_remove",
|
||||
"Find workers to remove",
|
||||
Arc::new(FindWorkersToRemoveStep),
|
||||
)
|
||||
.with_timeout(Duration::from_secs(10))
|
||||
.with_retry(RetryPolicy {
|
||||
max_attempts: 1,
|
||||
backoff: BackoffStrategy::Fixed(Duration::from_secs(0)),
|
||||
}),
|
||||
)
|
||||
.add_step(
|
||||
StepDefinition::new(
|
||||
"remove_from_policy_registry",
|
||||
"Remove workers from policy registry",
|
||||
Arc::new(RemoveFromPolicyRegistryStep),
|
||||
)
|
||||
.with_timeout(Duration::from_secs(10))
|
||||
.with_retry(RetryPolicy {
|
||||
max_attempts: 1,
|
||||
backoff: BackoffStrategy::Fixed(Duration::from_secs(0)),
|
||||
}),
|
||||
)
|
||||
.add_step(
|
||||
StepDefinition::new(
|
||||
"remove_from_worker_registry",
|
||||
"Remove workers from worker registry",
|
||||
Arc::new(RemoveFromWorkerRegistryStep),
|
||||
)
|
||||
.with_timeout(Duration::from_secs(10))
|
||||
.with_retry(RetryPolicy {
|
||||
max_attempts: 1,
|
||||
backoff: BackoffStrategy::Fixed(Duration::from_secs(0)),
|
||||
}),
|
||||
)
|
||||
.add_step(
|
||||
StepDefinition::new(
|
||||
"update_remaining_policies",
|
||||
"Update cache-aware policies for remaining workers",
|
||||
Arc::new(UpdateRemainingPoliciesStep),
|
||||
)
|
||||
.with_timeout(Duration::from_secs(10))
|
||||
.with_retry(RetryPolicy {
|
||||
max_attempts: 1,
|
||||
backoff: BackoffStrategy::Fixed(Duration::from_secs(0)),
|
||||
}),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,271 @@
|
||||
//! Core workflow types and definitions
|
||||
|
||||
use std::{collections::HashMap, fmt, sync::Arc, time::Duration};
|
||||
|
||||
use chrono::{DateTime, Utc};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
/// Unique identifier for a workflow definition
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
pub struct WorkflowId(String);
|
||||
|
||||
impl WorkflowId {
|
||||
pub fn new(id: impl Into<String>) -> Self {
|
||||
Self(id.into())
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for WorkflowId {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "{}", self.0)
|
||||
}
|
||||
}
|
||||
|
||||
/// Unique identifier for a workflow instance
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
pub struct WorkflowInstanceId(Uuid);
|
||||
|
||||
impl WorkflowInstanceId {
|
||||
pub fn new() -> Self {
|
||||
Self(Uuid::new_v4())
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for WorkflowInstanceId {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for WorkflowInstanceId {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "{}", self.0)
|
||||
}
|
||||
}
|
||||
|
||||
/// Unique identifier for a workflow step
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
pub struct StepId(String);
|
||||
|
||||
impl StepId {
|
||||
pub fn new(id: impl Into<String>) -> Self {
|
||||
Self(id.into())
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for StepId {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "{}", self.0)
|
||||
}
|
||||
}
|
||||
|
||||
/// Retry policy configuration
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct RetryPolicy {
|
||||
pub max_attempts: u32,
|
||||
pub backoff: BackoffStrategy,
|
||||
}
|
||||
|
||||
impl Default for RetryPolicy {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
max_attempts: 3,
|
||||
backoff: BackoffStrategy::Exponential {
|
||||
base: Duration::from_secs(1),
|
||||
max: Duration::from_secs(30),
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Backoff strategy for retries
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub enum BackoffStrategy {
|
||||
/// Fixed delay between retries
|
||||
Fixed(Duration),
|
||||
/// Exponential backoff with base and max duration
|
||||
Exponential { base: Duration, max: Duration },
|
||||
/// Linear backoff with increment and max duration
|
||||
Linear { increment: Duration, max: Duration },
|
||||
}
|
||||
|
||||
/// Action to take when a step fails
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum FailureAction {
|
||||
/// Stop the entire workflow
|
||||
FailWorkflow,
|
||||
/// Skip this step and continue to the next
|
||||
ContinueNextStep,
|
||||
/// Keep retrying indefinitely until manual intervention
|
||||
RetryIndefinitely,
|
||||
}
|
||||
|
||||
/// Workflow execution status
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum WorkflowStatus {
|
||||
Pending,
|
||||
Running,
|
||||
Paused,
|
||||
Completed,
|
||||
Failed,
|
||||
Cancelled,
|
||||
}
|
||||
|
||||
/// Step execution status
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum StepStatus {
|
||||
Pending,
|
||||
Running,
|
||||
Succeeded,
|
||||
Failed,
|
||||
Retrying,
|
||||
Skipped,
|
||||
}
|
||||
|
||||
/// State of a workflow step
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct StepState {
|
||||
pub status: StepStatus,
|
||||
pub attempt: u32,
|
||||
pub last_error: Option<String>,
|
||||
pub started_at: Option<DateTime<Utc>>,
|
||||
pub completed_at: Option<DateTime<Utc>>,
|
||||
}
|
||||
|
||||
impl Default for StepState {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
status: StepStatus::Pending,
|
||||
attempt: 0,
|
||||
last_error: None,
|
||||
started_at: None,
|
||||
completed_at: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Workflow instance state
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct WorkflowState {
|
||||
pub instance_id: WorkflowInstanceId,
|
||||
pub definition_id: WorkflowId,
|
||||
pub status: WorkflowStatus,
|
||||
pub current_step: Option<StepId>,
|
||||
pub step_states: HashMap<StepId, StepState>,
|
||||
pub context: WorkflowContext,
|
||||
pub created_at: DateTime<Utc>,
|
||||
pub updated_at: DateTime<Utc>,
|
||||
}
|
||||
|
||||
impl WorkflowState {
|
||||
pub fn new(instance_id: WorkflowInstanceId, definition_id: WorkflowId) -> Self {
|
||||
let now = Utc::now();
|
||||
Self {
|
||||
instance_id,
|
||||
definition_id,
|
||||
status: WorkflowStatus::Pending,
|
||||
current_step: None,
|
||||
step_states: HashMap::new(),
|
||||
context: WorkflowContext::new(instance_id),
|
||||
created_at: now,
|
||||
updated_at: now,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Shared context passed between workflow steps
|
||||
///
|
||||
/// # Serialization Warning
|
||||
///
|
||||
/// The `data` field contains type-erased values that cannot be serialized.
|
||||
/// This means workflow context is **not preserved** across:
|
||||
/// - Process restarts
|
||||
/// - State persistence to disk
|
||||
/// - Network serialization
|
||||
///
|
||||
/// The workflow engine only supports **in-memory execution**. If you need
|
||||
/// durable workflows, consider implementing a custom serializable context type.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct WorkflowContext {
|
||||
pub instance_id: WorkflowInstanceId,
|
||||
#[serde(skip)]
|
||||
data: HashMap<String, Arc<dyn std::any::Any + Send + Sync>>,
|
||||
}
|
||||
|
||||
impl WorkflowContext {
|
||||
pub fn new(instance_id: WorkflowInstanceId) -> Self {
|
||||
Self {
|
||||
instance_id,
|
||||
data: HashMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Store a value in the context (will be wrapped in Arc)
|
||||
pub fn set<T: Send + Sync + 'static>(&mut self, key: impl Into<String>, value: T) {
|
||||
self.data.insert(key.into(), Arc::new(value));
|
||||
}
|
||||
|
||||
/// Store an Arc directly without double-wrapping
|
||||
pub fn set_arc<T: Send + Sync + 'static>(&mut self, key: impl Into<String>, value: Arc<T>) {
|
||||
self.data.insert(key.into(), value);
|
||||
}
|
||||
|
||||
/// Retrieve a value from the context
|
||||
pub fn get<T: Send + Sync + 'static>(&self, key: &str) -> Option<Arc<T>> {
|
||||
self.data
|
||||
.get(key)
|
||||
.and_then(|v| v.clone().downcast::<T>().ok())
|
||||
}
|
||||
|
||||
/// Check if the context has any data that would be lost during serialization
|
||||
pub fn has_unserializable_data(&self) -> bool {
|
||||
!self.data.is_empty()
|
||||
}
|
||||
|
||||
/// Get the number of context entries (useful for debugging)
|
||||
pub fn data_len(&self) -> usize {
|
||||
self.data.len()
|
||||
}
|
||||
}
|
||||
|
||||
/// Result returned by a step execution
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum StepResult {
|
||||
Success,
|
||||
Failure,
|
||||
Skip,
|
||||
}
|
||||
|
||||
/// Error kinds for workflow operations
|
||||
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
|
||||
pub enum WorkflowError {
|
||||
#[error("Workflow not found: {0}")]
|
||||
NotFound(WorkflowInstanceId),
|
||||
|
||||
#[error("Workflow definition not found: {0}")]
|
||||
DefinitionNotFound(WorkflowId),
|
||||
|
||||
#[error("Step failed: {step_id} - {message}")]
|
||||
StepFailed { step_id: StepId, message: String },
|
||||
|
||||
#[error("Step timeout: {step_id}")]
|
||||
StepTimeout { step_id: StepId },
|
||||
|
||||
#[error("Workflow cancelled: {0}")]
|
||||
Cancelled(WorkflowInstanceId),
|
||||
|
||||
#[error("Invalid state transition: {from:?} -> {to:?}")]
|
||||
InvalidStateTransition {
|
||||
from: WorkflowStatus,
|
||||
to: WorkflowStatus,
|
||||
},
|
||||
|
||||
#[error("Context value not found: {0}")]
|
||||
ContextValueNotFound(String),
|
||||
|
||||
#[error("Context value type mismatch: {0}")]
|
||||
ContextTypeMismatch(String),
|
||||
}
|
||||
|
||||
pub type WorkflowResult<T> = Result<T, WorkflowError>;
|
||||
Reference in New Issue
Block a user