/** * Presentation Workflow Orchestrator * * Core orchestration engine that manages presentation workflow execution, * resource allocation, and lifecycle management while maintaining compatibility * with existing backup workflows. */ import { EventEmitter } from 'events'; import { PresentationState, PresentationEventType, WorkflowPriority, PresentationWorkflow, WorkflowExecution, WorkflowContext, WorkflowStep, StepExecutionResult, OrchestratorConfig, WorkflowEventPayload, createDefaultOrchestratorConfig, isWorkflowExecution } from '../types/presentation-types'; /** * Orchestrator execution statistics */ interface OrchestratorStats { totalExecutions: number; activeExecutions: number; completedExecutions: number; failedExecutions: number; averageExecutionTime: number; uptime: number; startedAt: string; } /** * Priority queue item for workflow execution */ interface QueuedWorkflow { execution: WorkflowExecution; workflow: PresentationWorkflow; priority: WorkflowPriority; queuedAt: string; } /** * Main orchestrator class for managing presentation workflows */ export class PresentationOrchestrator extends EventEmitter { private readonly config: OrchestratorConfig; private readonly activeExecutions: Map = new Map(); private readonly executionHistory: Map = new Map(); private readonly executionQueue: QueuedWorkflow[] = []; private readonly stats: OrchestratorStats; private isRunning = false; private processingInterval?: NodeJS.Timeout; constructor(config?: Partial) { super(); this.config = { ...createDefaultOrchestratorConfig(), ...config }; this.stats = { totalExecutions: 0, activeExecutions: 0, completedExecutions: 0, failedExecutions: 0, averageExecutionTime: 0, uptime: 0, startedAt: new Date().toISOString() }; this.setupEventHandlers(); } /** * Initialize and start the orchestrator */ public async start(): Promise { if (this.isRunning) { throw new Error('Orchestrator is already running'); } this.isRunning = true; this.emit('orchestrator:started', { startedAt: new Date().toISOString() }); // Start processing queue this.processingInterval = setInterval( () => this.processQueue(), 1000 // Process every second ); // Start metrics collection if enabled if (this.config.monitoring.enableMetrics) { this.startMetricsCollection(); } } /** * Stop the orchestrator gracefully */ public async stop(): Promise { if (!this.isRunning) { return; } this.isRunning = false; // Stop processing new workflows if (this.processingInterval) { clearInterval(this.processingInterval); this.processingInterval = undefined; } // Wait for active executions to complete or timeout const activeExecutionIds = Array.from(this.activeExecutions.keys()); if (activeExecutionIds.length > 0) { await this.waitForExecutionsToComplete(activeExecutionIds, 30000); // 30 second timeout } this.emit('orchestrator:stopped', { stoppedAt: new Date().toISOString(), remainingActiveExecutions: this.activeExecutions.size }); } /** * Execute a presentation workflow */ public async executeWorkflow( workflow: PresentationWorkflow, context: WorkflowContext, priority: WorkflowPriority = WorkflowPriority.NORMAL ): Promise { // Create workflow execution const execution: WorkflowExecution = { id: crypto.randomUUID(), workflowId: workflow.id, presentationId: context.presentationId, state: 'pending', context: { ...context, executionId: crypto.randomUUID() }, metadata: { createdAt: new Date().toISOString(), priority, workflowVersion: workflow.version } }; // Add to queue this.executionQueue.push({ execution, workflow, priority, queuedAt: new Date().toISOString() }); // Sort queue by priority (higher priority first) this.executionQueue.sort((a, b) => b.priority - a.priority); this.emit('workflow:queued', { executionId: execution.id, workflowId: workflow.id, presentationId: context.presentationId, priority, queuePosition: this.executionQueue.findIndex(item => item.execution.id === execution.id) }); return execution.id; } /** * Cancel a workflow execution */ public async cancelExecution(executionId: string): Promise { // Check if execution is in queue const queueIndex = this.executionQueue.findIndex(item => item.execution.id === executionId); if (queueIndex !== -1) { const removed = this.executionQueue.splice(queueIndex, 1)[0]; removed.execution.state = 'cancelled'; removed.execution.completedAt = new Date().toISOString(); this.executionHistory.set(executionId, removed.execution); this.emit('workflow:cancelled', { executionId, reason: 'cancelled_before_execution', cancelledAt: new Date().toISOString() }); return true; } // Check if execution is active const activeExecution = this.activeExecutions.get(executionId); if (activeExecution) { activeExecution.state = 'cancelled'; activeExecution.completedAt = new Date().toISOString(); this.activeExecutions.delete(executionId); this.executionHistory.set(executionId, activeExecution); this.stats.activeExecutions--; this.emit('workflow:cancelled', { executionId, reason: 'cancelled_during_execution', cancelledAt: new Date().toISOString() }); return true; } return false; } /** * Get execution status */ public getExecutionStatus(executionId: string): WorkflowExecution | null { return this.activeExecutions.get(executionId) || this.executionHistory.get(executionId) || null; } /** * Get all active executions */ public getActiveExecutions(): WorkflowExecution[] { return Array.from(this.activeExecutions.values()); } /** * Get orchestrator statistics */ public getStats(): OrchestratorStats { return { ...this.stats, uptime: Date.now() - new Date(this.stats.startedAt).getTime(), activeExecutions: this.activeExecutions.size }; } /** * Process the workflow execution queue */ private async processQueue(): Promise { if (!this.isRunning || this.executionQueue.length === 0) { return; } // Check if we can start new executions if (this.activeExecutions.size >= this.config.maxConcurrentWorkflows) { return; } // Get next workflow from queue const queuedWorkflow = this.executionQueue.shift(); if (!queuedWorkflow) { return; } // Start execution try { await this.startExecution(queuedWorkflow); } catch (error) { console.error('Failed to start workflow execution:', error); this.handleExecutionFailure(queuedWorkflow.execution, error as Error); } } /** * Start workflow execution */ private async startExecution(queuedWorkflow: QueuedWorkflow): Promise { const { execution, workflow } = queuedWorkflow; execution.state = 'running'; execution.startedAt = new Date().toISOString(); this.activeExecutions.set(execution.id, execution); this.stats.activeExecutions++; this.stats.totalExecutions++; this.emit('workflow:started', { executionId: execution.id, workflowId: workflow.id, presentationId: execution.presentationId, startedAt: execution.startedAt }); // Execute workflow steps try { const results = await this.executeWorkflowSteps(workflow, execution); await this.handleExecutionSuccess(execution, results); } catch (error) { await this.handleExecutionFailure(execution, error as Error); } } /** * Execute workflow steps sequentially */ private async executeWorkflowSteps( workflow: PresentationWorkflow, execution: WorkflowExecution ): Promise { const results: StepExecutionResult[] = []; const stepOutputs: Record = {}; for (const step of workflow.steps) { // Check dependencies const dependenciesCompleted = step.dependencies.every(depId => results.find(r => r.stepId === depId && r.status === 'success') ); if (!dependenciesCompleted) { results.push({ stepId: step.id, status: 'skipped', duration: 0, executedAt: new Date().toISOString(), metadata: { reason: 'dependencies_not_met' } }); continue; } // Execute step with timeout const stepStartTime = Date.now(); execution.currentStep = step.id; try { const stepResult = await this.executeStep(step, execution, stepOutputs); stepResult.duration = Date.now() - stepStartTime; stepResult.executedAt = new Date().toISOString(); results.push(stepResult); if (stepResult.outputs) { Object.assign(stepOutputs, stepResult.outputs); } // Handle step failure if (stepResult.status === 'failure') { if (step.onFailure && step.onFailure.length > 0) { // Execute failure steps for (const failureStep of step.onFailure) { const failureResult = await this.executeStep(failureStep, execution, stepOutputs); results.push(failureResult); } } else if (!this.config.enableRetries) { throw new Error(`Step ${step.id} failed: ${stepResult.error?.message}`); } } } catch (error) { results.push({ stepId: step.id, status: 'failure', error: { message: (error as Error).message, stack: (error as Error).stack }, duration: Date.now() - stepStartTime, executedAt: new Date().toISOString() }); // Stop execution on critical failure if (!step.onFailure) { throw error; } } } return results; } /** * Execute a single workflow step */ private async executeStep( step: WorkflowStep, execution: WorkflowExecution, previousOutputs: Record ): Promise { // Create step context const stepContext = { ...execution.context, stepId: step.id, previousOutputs, metadata: step.operation.metadata || {} }; // TODO: This is where we'd integrate with the actual step execution engine // For now, we'll simulate step execution based on operation type return this.simulateStepExecution(step, stepContext); } /** * Simulate step execution (placeholder for actual implementation) */ private async simulateStepExecution( step: WorkflowStep, context: WorkflowContext & { stepId: string; previousOutputs: Record } ): Promise { // Simulate execution time await new Promise(resolve => setTimeout(resolve, Math.random() * 100 + 50)); const operationType = step.operation.type; switch (operationType) { case 'presentation.start': return { stepId: step.id, status: 'success', outputs: { sessionId: crypto.randomUUID(), resourceAllocation: { cpu: 1, memory: 1024 }, startedAt: new Date().toISOString() }, duration: 0, executedAt: '' }; case 'presentation.stop': return { stepId: step.id, status: 'success', outputs: { stoppedAt: new Date().toISOString(), finalState: PresentationState.COMPLETED, resourcesReleased: true }, duration: 0, executedAt: '' }; case 'resource.cleanup': return { stepId: step.id, status: 'success', outputs: { cleanedResources: ['resource-1', 'resource-2'], cleanupCompletedAt: new Date().toISOString() }, duration: 0, executedAt: '' }; default: return { stepId: step.id, status: 'success', outputs: {}, duration: 0, executedAt: '' }; } } /** * Handle successful workflow execution */ private async handleExecutionSuccess( execution: WorkflowExecution, results: StepExecutionResult[] ): Promise { execution.state = 'completed'; execution.completedAt = new Date().toISOString(); execution.outputs = results.reduce((acc, result) => { if (result.outputs) { Object.assign(acc, result.outputs); } return acc; }, {}); this.activeExecutions.delete(execution.id); this.executionHistory.set(execution.id, execution); this.stats.activeExecutions--; this.stats.completedExecutions++; // Update average execution time const executionTime = new Date(execution.completedAt).getTime() - new Date(execution.startedAt!).getTime(); this.updateAverageExecutionTime(executionTime); this.emit('workflow:completed', { executionId: execution.id, workflowId: execution.workflowId, presentationId: execution.presentationId, completedAt: execution.completedAt, duration: executionTime, outputs: execution.outputs }); } /** * Handle failed workflow execution */ private async handleExecutionFailure( execution: WorkflowExecution, error: Error ): Promise { execution.state = 'failed'; execution.completedAt = new Date().toISOString(); execution.error = { message: error.message, stack: error.stack, step: execution.currentStep }; this.activeExecutions.delete(execution.id); this.executionHistory.set(execution.id, execution); this.stats.activeExecutions--; this.stats.failedExecutions++; this.emit('workflow:failed', { executionId: execution.id, workflowId: execution.workflowId, presentationId: execution.presentationId, failedAt: execution.completedAt, error: execution.error }); } /** * Setup event handlers for orchestrator lifecycle */ private setupEventHandlers(): void { this.on('workflow:started', (event) => { if (this.config.monitoring.enableLogging) { console.log(`🚀 Workflow started: ${event.executionId} for presentation: ${event.presentationId}`); } }); this.on('workflow:completed', (event) => { if (this.config.monitoring.enableLogging) { console.log(`✅ Workflow completed: ${event.executionId} in ${event.duration}ms`); } }); this.on('workflow:failed', (event) => { if (this.config.monitoring.enableLogging) { console.error(`❌ Workflow failed: ${event.executionId} - ${event.error.message}`); } }); } /** * Start metrics collection */ private startMetricsCollection(): void { setInterval(() => { this.emit('orchestrator:metrics', this.getStats()); }, this.config.monitoring.metricsInterval); } /** * Update average execution time */ private updateAverageExecutionTime(newExecutionTime: number): void { const totalCompleted = this.stats.completedExecutions; if (totalCompleted === 1) { this.stats.averageExecutionTime = newExecutionTime; } else { this.stats.averageExecutionTime = ((this.stats.averageExecutionTime * (totalCompleted - 1)) + newExecutionTime) / totalCompleted; } } /** * Wait for specific executions to complete */ private async waitForExecutionsToComplete( executionIds: string[], timeoutMs: number ): Promise { const startTime = Date.now(); while (executionIds.some(id => this.activeExecutions.has(id))) { if (Date.now() - startTime > timeoutMs) { break; } await new Promise(resolve => setTimeout(resolve, 100)); } } } /** * Factory function for creating orchestrator instances */ export function createPresentationOrchestrator( config?: Partial ): PresentationOrchestrator { return new PresentationOrchestrator(config); } /** * Singleton orchestrator instance for global use */ let globalOrchestrator: PresentationOrchestrator | null = null; export function getGlobalOrchestrator( config?: Partial ): PresentationOrchestrator { if (!globalOrchestrator) { globalOrchestrator = new PresentationOrchestrator(config); } return globalOrchestrator; }