/** * Presentation Workflow Engine * * Specialized workflow engine for handling presentation-specific operations, * lifecycle management, and integration with presentation services while * maintaining compatibility with existing backup workflow patterns. */ import { EventEmitter } from 'events'; import { PresentationState, PresentationEventType, WorkflowPriority, PresentationWorkflow, WorkflowExecution, WorkflowContext, WorkflowStep, PresentationConfig, ResourceRequirements, PresentationStartOperation, PresentationStopOperation, ResourceCleanupOperation, WorkflowEventPayload, SupabaseWorkflowContext, BackupWorkflowContext, isPresentationOperation } from '../types/presentation-types'; /** * Presentation session state */ interface PresentationSession { id: string; presentationId: string; state: PresentationState; config: PresentationConfig; resourceAllocation: Record; startedAt?: string; endedAt?: string; participants: string[]; metadata: Record; } /** * Resource allocation tracking */ interface ResourceAllocation { id: string; presentationId: string; sessionId: string; type: string; allocation: Record; allocatedAt: string; releasedAt?: string; isActive: boolean; } /** * Workflow template for common presentation patterns */ interface WorkflowTemplate { id: string; name: string; description: string; category: 'lifecycle' | 'resource' | 'backup' | 'cleanup'; steps: Omit[]; defaultInputs: Record; metadata: Record; } /** * Presentation-specific workflow engine */ export class PresentationWorkflowEngine extends EventEmitter { private readonly activeSessions: Map = new Map(); private readonly resourceAllocations: Map = new Map(); private readonly workflowTemplates: Map = new Map(); private readonly eventQueue: WorkflowEventPayload[] = []; private isInitialized = false; constructor() { super(); this.initializeDefaultTemplates(); } /** * Initialize the workflow engine */ public async initialize(): Promise { if (this.isInitialized) { return; } this.setupEventHandlers(); this.isInitialized = true; this.emit('engine:initialized', { initializedAt: new Date().toISOString(), templates: Array.from(this.workflowTemplates.keys()) }); } /** * Create presentation lifecycle workflow */ public createPresentationLifecycleWorkflow( presentationConfig: PresentationConfig, resourceRequirements: ResourceRequirements, options?: { includeBackup?: boolean; customSteps?: WorkflowStep[]; priority?: WorkflowPriority; } ): PresentationWorkflow { const workflowId = `presentation-lifecycle-${presentationConfig.id}`; const steps: WorkflowStep[] = []; // Start step steps.push({ id: 'start-presentation', name: 'Start Presentation', type: 'presentation.start', operation: { id: crypto.randomUUID(), type: 'presentation.start', name: 'Start Presentation Operation', inputs: { presentationConfig, resourceRequirements, context: {} as WorkflowContext // Will be filled at execution time } } as PresentationStartOperation, dependencies: [], timeout: 30000, // 30 seconds retryPolicy: { maxAttempts: 3, backoffStrategy: 'exponential', baseDelay: 1000 } }); // Resource allocation step steps.push({ id: 'allocate-resources', name: 'Allocate Presentation Resources', type: 'resource.allocate', operation: { id: crypto.randomUUID(), type: 'resource.allocate', name: 'Allocate Resources Operation', inputs: { resourceRequirements, presentationId: presentationConfig.id } }, dependencies: ['start-presentation'], timeout: 60000 // 1 minute }); // Optional backup integration if (options?.includeBackup) { steps.push({ id: 'backup-presentation-state', name: 'Backup Presentation State', type: 'backup.create', operation: { id: crypto.randomUUID(), type: 'backup.create', name: 'Create Backup Operation', inputs: { presentationId: presentationConfig.id, backupType: 'presentation-state', includeResources: true } }, dependencies: ['allocate-resources'], timeout: 120000 // 2 minutes }); } // Add custom steps if provided if (options?.customSteps) { steps.push(...options.customSteps); } // Stop step (triggered separately) steps.push({ id: 'stop-presentation', name: 'Stop Presentation', type: 'presentation.stop', operation: { id: crypto.randomUUID(), type: 'presentation.stop', name: 'Stop Presentation Operation', inputs: { presentationId: presentationConfig.id, sessionId: '', // Will be filled from previous step outputs graceful: true, context: {} as WorkflowContext } } as PresentationStopOperation, dependencies: [], timeout: 30000 }); // Cleanup step steps.push({ id: 'cleanup-resources', name: 'Cleanup Presentation Resources', type: 'resource.cleanup', operation: { id: crypto.randomUUID(), type: 'resource.cleanup', name: 'Cleanup Resources Operation', inputs: { presentationId: presentationConfig.id, sessionId: '', resourceIds: [], context: {} as WorkflowContext } } as ResourceCleanupOperation, dependencies: ['stop-presentation'], timeout: 60000 }); return { id: workflowId, name: `Presentation Lifecycle - ${presentationConfig.title}`, description: `Complete lifecycle workflow for presentation: ${presentationConfig.title}`, version: '1.0.0', trigger: { events: [ PresentationEventType.PRESENTATION_CREATED, PresentationEventType.PRESENTATION_SCHEDULED, PresentationEventType.PRESENTATION_STARTED, PresentationEventType.PRESENTATION_STOPPED ] }, steps, outputs: { sessionId: 'start-presentation.sessionId', resourceAllocation: 'allocate-resources.allocation', finalState: 'stop-presentation.finalState' }, metadata: { presentationId: presentationConfig.id, category: 'lifecycle', priority: options?.priority || WorkflowPriority.NORMAL }, createdAt: new Date().toISOString(), updatedAt: new Date().toISOString() }; } /** * Create resource management workflow */ public createResourceManagementWorkflow( presentationId: string, operation: 'allocate' | 'scale' | 'cleanup', requirements?: ResourceRequirements ): PresentationWorkflow { const template = this.workflowTemplates.get(`resource-${operation}`); if (!template) { throw new Error(`No template found for resource operation: ${operation}`); } const workflowId = `resource-${operation}-${presentationId}`; const steps: WorkflowStep[] = template.steps.map((stepTemplate, index) => ({ ...stepTemplate, id: `${operation}-step-${index + 1}`, operation: { ...stepTemplate.operation, id: crypto.randomUUID(), inputs: { ...stepTemplate.operation.inputs, presentationId, requirements } } })); return { id: workflowId, name: `Resource ${operation.charAt(0).toUpperCase() + operation.slice(1)} - ${presentationId}`, description: template.description, version: '1.0.0', trigger: { events: [PresentationEventType.RESOURCE_ALLOCATED, PresentationEventType.RESOURCE_RELEASED] }, steps, outputs: {}, metadata: { presentationId, category: 'resource', operation }, createdAt: new Date().toISOString(), updatedAt: new Date().toISOString() }; } /** * Create backup integration workflow */ public createBackupIntegrationWorkflow( presentationId: string, backupContext: BackupWorkflowContext ): PresentationWorkflow { const workflowId = `backup-integration-${presentationId}`; const steps: WorkflowStep[] = [ { id: 'prepare-backup-context', name: 'Prepare Backup Context', type: 'backup.prepare', operation: { id: crypto.randomUUID(), type: 'backup.prepare', name: 'Prepare Backup Context Operation', inputs: { presentationId, backupContext, includeSessionData: true } }, dependencies: [], timeout: 30000 }, { id: 'execute-backup', name: 'Execute Presentation Backup', type: 'backup.execute', operation: { id: crypto.randomUUID(), type: 'backup.execute', name: 'Execute Backup Operation', inputs: { presentationId, backupType: backupContext.backupType || 'incremental', retentionDays: backupContext.retentionDays || 30 } }, dependencies: ['prepare-backup-context'], timeout: 300000 // 5 minutes }, { id: 'verify-backup', name: 'Verify Backup Integrity', type: 'backup.verify', operation: { id: crypto.randomUUID(), type: 'backup.verify', name: 'Verify Backup Operation', inputs: { backupId: '', // From previous step checksumValidation: true } }, dependencies: ['execute-backup'], timeout: 60000 } ]; return { id: workflowId, name: `Backup Integration - ${presentationId}`, description: 'Integrate presentation data with backup workflows', version: '1.0.0', trigger: { events: [ PresentationEventType.PRESENTATION_COMPLETED, PresentationEventType.CLEANUP_REQUESTED ] }, steps, outputs: { backupId: 'execute-backup.backupId', backupPath: 'execute-backup.backupPath', verified: 'verify-backup.isValid' }, metadata: { presentationId, category: 'backup', integration: true }, createdAt: new Date().toISOString(), updatedAt: new Date().toISOString() }; } /** * Handle presentation lifecycle events */ public async handlePresentationEvent(event: WorkflowEventPayload): Promise { this.eventQueue.push(event); switch (event.eventType) { case PresentationEventType.PRESENTATION_STARTED: await this.handlePresentationStarted(event); break; case PresentationEventType.PRESENTATION_STOPPED: await this.handlePresentationStopped(event); break; case PresentationEventType.PRESENTATION_FAILED: await this.handlePresentationFailed(event); break; case PresentationEventType.CLEANUP_REQUESTED: await this.handleCleanupRequested(event); break; default: this.emit('event:unhandled', event); } } /** * Get active presentation sessions */ public getActiveSessions(): PresentationSession[] { return Array.from(this.activeSessions.values()) .filter(session => [ PresentationState.STARTING, PresentationState.RUNNING, PresentationState.PAUSED ].includes(session.state)); } /** * Get resource allocations for a presentation */ public getResourceAllocations(presentationId: string): ResourceAllocation[] { return Array.from(this.resourceAllocations.values()) .filter(allocation => allocation.presentationId === presentationId); } /** * Get workflow template by ID */ public getWorkflowTemplate(templateId: string): WorkflowTemplate | undefined { return this.workflowTemplates.get(templateId); } /** * Register custom workflow template */ public registerWorkflowTemplate(template: WorkflowTemplate): void { this.workflowTemplates.set(template.id, template); this.emit('template:registered', { templateId: template.id, category: template.category, registeredAt: new Date().toISOString() }); } /** * Create Supabase integration context */ public createSupabaseWorkflowContext( userId: string, presentationId: string, permissions?: Record ): SupabaseWorkflowContext { return { connectionId: crypto.randomUUID(), userId, tablePermissions: permissions || { presentations: ['select', 'update'], presentation_sessions: ['select', 'insert', 'update'], presentation_resources: ['select', 'insert', 'update', 'delete'] }, rls: { enabled: true, policies: [`user_id = '${userId}'`] } }; } /** * Handle presentation started event */ private async handlePresentationStarted(event: WorkflowEventPayload): Promise { const session: PresentationSession = { id: event.sessionId || crypto.randomUUID(), presentationId: event.presentationId, state: PresentationState.STARTING, config: event.data.config as PresentationConfig, resourceAllocation: {}, participants: [], metadata: { startedAt: event.timestamp, eventData: event.data } }; this.activeSessions.set(session.id, session); this.emit('session:started', { sessionId: session.id, presentationId: session.presentationId, startedAt: event.timestamp }); // Transition to running state after initialization setTimeout(() => { session.state = PresentationState.RUNNING; session.startedAt = new Date().toISOString(); this.emit('session:running', { sessionId: session.id, presentationId: session.presentationId }); }, 1000); } /** * Handle presentation stopped event */ private async handlePresentationStopped(event: WorkflowEventPayload): Promise { const sessionId = event.sessionId; if (!sessionId) { return; } const session = this.activeSessions.get(sessionId); if (session) { session.state = PresentationState.STOPPING; session.endedAt = event.timestamp; this.emit('session:stopping', { sessionId: session.id, presentationId: session.presentationId, reason: event.data.reason }); // Clean up session after delay setTimeout(() => { session.state = PresentationState.COMPLETED; this.activeSessions.delete(sessionId); this.emit('session:completed', { sessionId: session.id, presentationId: session.presentationId, duration: session.startedAt && session.endedAt ? new Date(session.endedAt).getTime() - new Date(session.startedAt).getTime() : 0 }); }, 5000); } } /** * Handle presentation failed event */ private async handlePresentationFailed(event: WorkflowEventPayload): Promise { const sessionId = event.sessionId; if (!sessionId) { return; } const session = this.activeSessions.get(sessionId); if (session) { session.state = PresentationState.FAILED; session.endedAt = event.timestamp; session.metadata.error = event.data.error; this.emit('session:failed', { sessionId: session.id, presentationId: session.presentationId, error: event.data.error, failedAt: event.timestamp }); // Trigger cleanup workflow await this.triggerCleanupWorkflow(session.presentationId, sessionId); } } /** * Handle cleanup requested event */ private async handleCleanupRequested(event: WorkflowEventPayload): Promise { await this.triggerCleanupWorkflow( event.presentationId, event.sessionId, event.data.reason ); } /** * Trigger cleanup workflow */ private async triggerCleanupWorkflow( presentationId: string, sessionId?: string, reason?: string ): Promise { const allocations = this.getResourceAllocations(presentationId); const resourceIds = allocations.map(a => a.id); const cleanupWorkflow = this.createResourceManagementWorkflow( presentationId, 'cleanup' ); // Update cleanup operation inputs const cleanupStep = cleanupWorkflow.steps.find(s => s.type === 'resource.cleanup'); if (cleanupStep && cleanupStep.operation.type === 'resource.cleanup') { const operation = cleanupStep.operation as ResourceCleanupOperation; operation.inputs.sessionId = sessionId || ''; operation.inputs.resourceIds = resourceIds; } this.emit('cleanup:triggered', { presentationId, sessionId, resourceIds, reason, workflowId: cleanupWorkflow.id }); } /** * Setup event handlers */ private setupEventHandlers(): void { this.on('session:started', (event) => { console.log(`๐ŸŽฌ Presentation session started: ${event.sessionId} for ${event.presentationId}`); }); this.on('session:completed', (event) => { console.log(`โœ… Presentation session completed: ${event.sessionId} (${event.duration}ms)`); }); this.on('session:failed', (event) => { console.error(`โŒ Presentation session failed: ${event.sessionId} - ${event.error?.message}`); }); this.on('cleanup:triggered', (event) => { console.log(`๐Ÿงน Cleanup triggered for presentation: ${event.presentationId}`); }); } /** * Initialize default workflow templates */ private initializeDefaultTemplates(): void { // Resource allocation template this.workflowTemplates.set('resource-allocate', { id: 'resource-allocate', name: 'Resource Allocation', description: 'Allocate resources for presentation execution', category: 'resource', steps: [ { name: 'Calculate Resource Requirements', type: 'resource.calculate', operation: { id: '', type: 'resource.calculate', name: 'Calculate Resources', inputs: {} }, dependencies: [], timeout: 30000 }, { name: 'Reserve Resources', type: 'resource.reserve', operation: { id: '', type: 'resource.reserve', name: 'Reserve Resources', inputs: {} }, dependencies: ['calculate-requirements'], timeout: 60000 } ], defaultInputs: {}, metadata: {} }); // Resource cleanup template this.workflowTemplates.set('resource-cleanup', { id: 'resource-cleanup', name: 'Resource Cleanup', description: 'Clean up and release presentation resources', category: 'cleanup', steps: [ { name: 'Stop Running Processes', type: 'resource.stop', operation: { id: '', type: 'resource.stop', name: 'Stop Processes', inputs: {} }, dependencies: [], timeout: 30000 }, { name: 'Release Resources', type: 'resource.release', operation: { id: '', type: 'resource.release', name: 'Release Resources', inputs: {} }, dependencies: ['stop-processes'], timeout: 60000 } ], defaultInputs: {}, metadata: {} }); } } /** * Factory function for creating presentation workflow engine */ export function createPresentationWorkflowEngine(): PresentationWorkflowEngine { return new PresentationWorkflowEngine(); } /** * Singleton workflow engine instance */ let globalEngine: PresentationWorkflowEngine | null = null; export function getGlobalPresentationEngine(): PresentationWorkflowEngine { if (!globalEngine) { globalEngine = new PresentationWorkflowEngine(); } return globalEngine; }