/** * Workflow Registry * * Central registry for managing presentation and backup workflows, * providing registration, discovery, versioning, and lifecycle management * while maintaining backward compatibility with existing backup workflows. */ import { EventEmitter } from 'events'; import { PresentationWorkflow, WorkflowRegistryEntry, PresentationEventType, WorkflowPriority, WorkflowTrigger, WorkflowExecution, BackupWorkflowContext } from '../types/presentation-types'; /** * Workflow category for organization */ export enum WorkflowCategory { PRESENTATION = 'presentation', BACKUP = 'backup', RESOURCE = 'resource', CLEANUP = 'cleanup', INTEGRATION = 'integration', MONITORING = 'monitoring' } /** * Workflow compatibility level */ export enum CompatibilityLevel { FULL = 'full', // Fully compatible with existing systems PARTIAL = 'partial', // Some limitations or adaptations needed LEGACY = 'legacy', // Maintained for backward compatibility EXPERIMENTAL = 'experimental' // New features, may change } /** * Registry configuration */ interface RegistryConfig { enableVersioning: boolean; enableMetrics: boolean; enableValidation: boolean; maxWorkflowHistory: number; autoCleanupDays: number; compatibilityMode: 'strict' | 'relaxed'; } /** * Workflow metadata for registry management */ interface WorkflowMetadata { category: WorkflowCategory; compatibility: CompatibilityLevel; version: string; author?: string; description?: string; tags: string[]; dependencies: string[]; deprecatedBy?: string; experimental?: boolean; minEngineVersion?: string; maxEngineVersion?: string; } /** * Extended registry entry with metadata */ interface ExtendedWorkflowRegistryEntry extends WorkflowRegistryEntry { metadata: WorkflowMetadata; triggers: WorkflowTrigger[]; isDeprecated: boolean; deprecationReason?: string; migrationPath?: string; } /** * Workflow search criteria */ interface WorkflowSearchCriteria { category?: WorkflowCategory; compatibility?: CompatibilityLevel; tags?: string[]; eventTypes?: PresentationEventType[]; isActive?: boolean; isDeprecated?: boolean; version?: string; author?: string; } /** * Registry statistics */ interface RegistryStats { totalWorkflows: number; activeWorkflows: number; deprecatedWorkflows: number; categoryCounts: Record; compatibilityCounts: Record; executionStats: { totalExecutions: number; successfulExecutions: number; failedExecutions: number; averageExecutionTime: number; }; } /** * Central workflow registry */ export class WorkflowRegistry extends EventEmitter { private readonly workflows: Map = new Map(); private readonly workflowVersions: Map = new Map(); private readonly triggers: Map = new Map(); private readonly config: RegistryConfig; constructor(config?: Partial) { super(); this.config = { enableVersioning: true, enableMetrics: true, enableValidation: true, maxWorkflowHistory: 10, autoCleanupDays: 90, compatibilityMode: 'relaxed', ...config }; this.initializeBuiltinWorkflows(); } /** * Register a new workflow */ public async registerWorkflow( workflow: PresentationWorkflow, metadata: Partial = {}, triggers: WorkflowTrigger[] = [] ): Promise { if (this.config.enableValidation) { this.validateWorkflow(workflow); } const fullMetadata: WorkflowMetadata = { category: WorkflowCategory.PRESENTATION, compatibility: CompatibilityLevel.FULL, version: workflow.version, tags: [], dependencies: [], ...metadata }; const entry: ExtendedWorkflowRegistryEntry = { workflow, metadata: fullMetadata, triggers, isActive: true, isDeprecated: false, registeredAt: new Date().toISOString(), executionCount: 0 }; // Handle versioning if (this.config.enableVersioning) { await this.handleWorkflowVersioning(workflow.id, entry); } this.workflows.set(workflow.id, entry); this.updateTriggers(workflow.id, triggers); this.emit('workflow:registered', { workflowId: workflow.id, version: workflow.version, category: fullMetadata.category, registeredAt: entry.registeredAt }); } /** * Unregister a workflow */ public async unregisterWorkflow(workflowId: string, reason?: string): Promise { const entry = this.workflows.get(workflowId); if (!entry) { return false; } entry.isActive = false; this.triggers.delete(workflowId); this.emit('workflow:unregistered', { workflowId, reason, unregisteredAt: new Date().toISOString() }); return true; } /** * Deprecate a workflow */ public async deprecateWorkflow( workflowId: string, reason: string, migrationPath?: string ): Promise { const entry = this.workflows.get(workflowId); if (!entry) { return false; } entry.isDeprecated = true; entry.deprecationReason = reason; entry.migrationPath = migrationPath; this.emit('workflow:deprecated', { workflowId, reason, migrationPath, deprecatedAt: new Date().toISOString() }); return true; } /** * Get workflow by ID */ public getWorkflow(workflowId: string): ExtendedWorkflowRegistryEntry | null { return this.workflows.get(workflowId) || null; } /** * Get workflow by ID and version */ public getWorkflowVersion(workflowId: string, version: string): ExtendedWorkflowRegistryEntry | null { const versions = this.workflowVersions.get(workflowId); if (!versions) { return null; } return versions.find(entry => entry.workflow.version === version) || null; } /** * Search workflows by criteria */ public searchWorkflows(criteria: WorkflowSearchCriteria): ExtendedWorkflowRegistryEntry[] { const results: ExtendedWorkflowRegistryEntry[] = []; for (const entry of this.workflows.values()) { if (this.matchesCriteria(entry, criteria)) { results.push(entry); } } // Sort by relevance (active, non-deprecated, recent first) return results.sort((a, b) => { if (a.isActive !== b.isActive) return a.isActive ? -1 : 1; if (a.isDeprecated !== b.isDeprecated) return a.isDeprecated ? 1 : -1; return new Date(b.registeredAt).getTime() - new Date(a.registeredAt).getTime(); }); } /** * Get workflows by category */ public getWorkflowsByCategory(category: WorkflowCategory): ExtendedWorkflowRegistryEntry[] { return this.searchWorkflows({ category, isActive: true }); } /** * Get workflows triggered by event type */ public getWorkflowsTriggeredBy(eventType: PresentationEventType): ExtendedWorkflowRegistryEntry[] { const triggeredWorkflows: ExtendedWorkflowRegistryEntry[] = []; for (const [workflowId, triggers] of this.triggers.entries()) { if (triggers.some(trigger => trigger.events.includes(eventType) && trigger.isActive)) { const entry = this.workflows.get(workflowId); if (entry && entry.isActive && !entry.isDeprecated) { triggeredWorkflows.push(entry); } } } // Sort by priority return triggeredWorkflows.sort((a, b) => { const aPriority = this.getHighestTriggerPriority(a.workflow.id, eventType); const bPriority = this.getHighestTriggerPriority(b.workflow.id, eventType); return bPriority - aPriority; }); } /** * Update workflow execution statistics */ public updateExecutionStats( workflowId: string, execution: WorkflowExecution, success: boolean, executionTime: number ): void { const entry = this.workflows.get(workflowId); if (!entry) { return; } entry.executionCount++; entry.lastExecuted = new Date().toISOString(); if (entry.averageExecutionTime) { entry.averageExecutionTime = (entry.averageExecutionTime + executionTime) / 2; } else { entry.averageExecutionTime = executionTime; } if (entry.successRate !== undefined) { const totalExecutions = entry.executionCount; const successfulExecutions = success ? Math.round(entry.successRate * (totalExecutions - 1)) + 1 : Math.round(entry.successRate * (totalExecutions - 1)); entry.successRate = successfulExecutions / totalExecutions; } else { entry.successRate = success ? 1 : 0; } this.emit('execution:updated', { workflowId, executionId: execution.id, success, executionTime, totalExecutions: entry.executionCount }); } /** * Get registry statistics */ public getStats(): RegistryStats { const categoryCounts = Object.values(WorkflowCategory).reduce((acc, category) => { acc[category] = 0; return acc; }, {} as Record); const compatibilityCounts = Object.values(CompatibilityLevel).reduce((acc, level) => { acc[level] = 0; return acc; }, {} as Record); let totalExecutions = 0; let successfulExecutions = 0; let totalExecutionTime = 0; let activeWorkflows = 0; let deprecatedWorkflows = 0; for (const entry of this.workflows.values()) { categoryCounts[entry.metadata.category]++; compatibilityCounts[entry.metadata.compatibility]++; if (entry.isActive) activeWorkflows++; if (entry.isDeprecated) deprecatedWorkflows++; totalExecutions += entry.executionCount; if (entry.successRate !== undefined && entry.averageExecutionTime !== undefined) { successfulExecutions += Math.round(entry.successRate * entry.executionCount); totalExecutionTime += entry.averageExecutionTime * entry.executionCount; } } return { totalWorkflows: this.workflows.size, activeWorkflows, deprecatedWorkflows, categoryCounts, compatibilityCounts, executionStats: { totalExecutions, successfulExecutions, failedExecutions: totalExecutions - successfulExecutions, averageExecutionTime: totalExecutions > 0 ? totalExecutionTime / totalExecutions : 0 } }; } /** * Export workflow registry for backup/migration */ public exportRegistry(): { workflows: Record; triggers: Record; exportedAt: string; version: string; } { const workflowsObj: Record = {}; const triggersObj: Record = {}; for (const [id, entry] of this.workflows.entries()) { workflowsObj[id] = entry; } for (const [id, triggers] of this.triggers.entries()) { triggersObj[id] = triggers; } return { workflows: workflowsObj, triggers: triggersObj, exportedAt: new Date().toISOString(), version: '1.0.0' }; } /** * Import workflow registry from backup */ public async importRegistry(data: { workflows: Record; triggers: Record; }): Promise { for (const [id, entry] of Object.entries(data.workflows)) { this.workflows.set(id, entry); } for (const [id, triggers] of Object.entries(data.triggers)) { this.triggers.set(id, triggers); } this.emit('registry:imported', { workflowCount: Object.keys(data.workflows).length, triggerCount: Object.keys(data.triggers).length, importedAt: new Date().toISOString() }); } /** * Create workflow from template for backward compatibility */ public createBackupCompatibilityWorkflow( backupContext: BackupWorkflowContext, integrationMode: 'full' | 'minimal' = 'minimal' ): PresentationWorkflow { const workflowId = `backup-compat-${backupContext.backupId || crypto.randomUUID()}`; const workflow: PresentationWorkflow = { id: workflowId, name: 'Backup Compatibility Workflow', description: 'Compatibility layer for existing backup workflows', version: '1.0.0', trigger: { events: [PresentationEventType.CLEANUP_REQUESTED] }, steps: [ { id: 'prepare-backup-context', name: 'Prepare Backup Context', type: 'backup.prepare', operation: { id: crypto.randomUUID(), type: 'backup.prepare', name: 'Prepare Backup Operation', inputs: { backupContext } }, dependencies: [], timeout: 30000 } ], outputs: {}, metadata: { category: 'backup', compatibility: 'legacy', backupContext }, createdAt: new Date().toISOString(), updatedAt: new Date().toISOString() }; if (integrationMode === 'full') { workflow.steps.push({ id: 'execute-legacy-backup', name: 'Execute Legacy Backup', type: 'backup.legacy', operation: { id: crypto.randomUUID(), type: 'backup.legacy', name: 'Legacy Backup Operation', inputs: { backupType: backupContext.backupType, retentionDays: backupContext.retentionDays, storageProvider: backupContext.storageProvider } }, dependencies: ['prepare-backup-context'], timeout: 300000 }); } return workflow; } /** * Validate workflow definition */ private validateWorkflow(workflow: PresentationWorkflow): void { if (!workflow.id || !workflow.name || !workflow.version) { throw new Error('Workflow must have id, name, and version'); } if (!workflow.steps || workflow.steps.length === 0) { throw new Error('Workflow must have at least one step'); } // Validate step dependencies const stepIds = new Set(workflow.steps.map(s => s.id)); for (const step of workflow.steps) { for (const depId of step.dependencies) { if (!stepIds.has(depId)) { throw new Error(`Step ${step.id} depends on non-existent step: ${depId}`); } } } // Check for circular dependencies this.detectCircularDependencies(workflow.steps); } /** * Detect circular dependencies in workflow steps */ private detectCircularDependencies(steps: any[]): void { const visited = new Set(); const recursionStack = new Set(); const stepMap = new Map(steps.map(step => [step.id, step])); const hasCycle = (stepId: string): boolean => { if (recursionStack.has(stepId)) { return true; } if (visited.has(stepId)) { return false; } visited.add(stepId); recursionStack.add(stepId); const step = stepMap.get(stepId); if (step) { for (const depId of step.dependencies) { if (hasCycle(depId)) { return true; } } } recursionStack.delete(stepId); return false; }; for (const step of steps) { if (hasCycle(step.id)) { throw new Error(`Circular dependency detected involving step: ${step.id}`); } } } /** * Handle workflow versioning */ private async handleWorkflowVersioning( workflowId: string, newEntry: ExtendedWorkflowRegistryEntry ): Promise { const existingVersions = this.workflowVersions.get(workflowId) || []; // Check if version already exists const versionExists = existingVersions.some( entry => entry.workflow.version === newEntry.workflow.version ); if (versionExists && this.config.compatibilityMode === 'strict') { throw new Error(`Workflow version ${newEntry.workflow.version} already exists for ${workflowId}`); } // Add to version history existingVersions.push(newEntry); // Keep only recent versions if (existingVersions.length > this.config.maxWorkflowHistory) { existingVersions.splice(0, existingVersions.length - this.config.maxWorkflowHistory); } this.workflowVersions.set(workflowId, existingVersions); } /** * Update triggers for a workflow */ private updateTriggers(workflowId: string, triggers: WorkflowTrigger[]): void { this.triggers.set(workflowId, triggers); } /** * Check if workflow entry matches search criteria */ private matchesCriteria( entry: ExtendedWorkflowRegistryEntry, criteria: WorkflowSearchCriteria ): boolean { if (criteria.category && entry.metadata.category !== criteria.category) { return false; } if (criteria.compatibility && entry.metadata.compatibility !== criteria.compatibility) { return false; } if (criteria.isActive !== undefined && entry.isActive !== criteria.isActive) { return false; } if (criteria.isDeprecated !== undefined && entry.isDeprecated !== criteria.isDeprecated) { return false; } if (criteria.version && entry.workflow.version !== criteria.version) { return false; } if (criteria.author && entry.metadata.author !== criteria.author) { return false; } if (criteria.tags && criteria.tags.length > 0) { const hasMatchingTag = criteria.tags.some(tag => entry.metadata.tags.includes(tag)); if (!hasMatchingTag) { return false; } } if (criteria.eventTypes && criteria.eventTypes.length > 0) { const workflowTriggers = this.triggers.get(entry.workflow.id) || []; const hasMatchingEvent = criteria.eventTypes.some(eventType => workflowTriggers.some(trigger => trigger.events.includes(eventType)) ); if (!hasMatchingEvent) { return false; } } return true; } /** * Get highest trigger priority for a workflow and event type */ private getHighestTriggerPriority(workflowId: string, eventType: PresentationEventType): number { const triggers = this.triggers.get(workflowId) || []; const matchingTriggers = triggers.filter(trigger => trigger.events.includes(eventType) && trigger.isActive ); if (matchingTriggers.length === 0) { return 0; } return Math.max(...matchingTriggers.map(trigger => trigger.priority)); } /** * Initialize built-in workflows for system functionality */ private initializeBuiltinWorkflows(): void { // This would typically load core system workflows // For now, we'll emit an event to indicate readiness this.emit('registry:initialized', { initializedAt: new Date().toISOString(), builtinWorkflows: 0 }); } } /** * Factory function for creating workflow registry */ export function createWorkflowRegistry(config?: Partial): WorkflowRegistry { return new WorkflowRegistry(config); } /** * Singleton registry instance */ let globalRegistry: WorkflowRegistry | null = null; export function getGlobalRegistry(config?: Partial): WorkflowRegistry { if (!globalRegistry) { globalRegistry = new WorkflowRegistry(config); } return globalRegistry; }