/** * Presentation data service for workflow operations * * This service provides a high-level API for managing presentation data * within workflow contexts. It orchestrates database operations, handles * caching, manages data synchronization, and provides business logic * for presentation lifecycle management. */ import { WorkflowContext, PresentationConfig, PresentationState, ResourceRequirements, WorkflowExecution } from '../types/presentation-types.js'; import { SupabaseConnectionConfig, EnhancedSupabaseWorkflowContext, PresentationDataSyncOperation, createSupabaseWorkflowContext } from '../types/supabase-workflow-types.js'; import { DatabaseOperationsConnector, PresentationData, PresentationSession, ResourceAllocation, TransactionContext, createDatabaseOperationsConnector } from '../connectors/database-operations.js'; /** * Presentation lifecycle events */ export interface PresentationLifecycleEvent { id: string; presentationId: string; sessionId?: string; eventType: string; fromState?: PresentationState; toState: PresentationState; metadata: Record; timestamp: string; } /** * Data synchronization status */ export interface DataSyncStatus { syncId: string; presentationId: string; status: 'pending' | 'running' | 'completed' | 'failed'; progress: { totalRecords: number; processedRecords: number; errorCount: number; }; startedAt: string; completedAt?: string; error?: string; } /** * Cache entry structure */ interface CacheEntry { data: T; timestamp: number; ttl: number; // milliseconds } /** * Service configuration */ export interface PresentationDataServiceConfig { database: SupabaseConnectionConfig; cache: { enabled: boolean; defaultTtl: number; // milliseconds maxSize: number; }; sync: { batchSize: number; retryAttempts: number; retryDelay: number; // milliseconds }; monitoring: { enabled: boolean; metricsInterval: number; // milliseconds }; } /** * Main presentation data service */ export class PresentationDataService { private dbConnector: DatabaseOperationsConnector; private config: PresentationDataServiceConfig; private cache: Map> = new Map(); private activeSyncs: Map = new Map(); private metrics: { queries: number; mutations: number; cacheHits: number; cacheMisses: number; errors: number; } = { queries: 0, mutations: 0, cacheHits: 0, cacheMisses: 0, errors: 0 }; constructor(config: PresentationDataServiceConfig) { this.config = config; this.dbConnector = createDatabaseOperationsConnector(config.database); // Start cache cleanup interval if (config.cache.enabled) { setInterval(() => this.cleanupExpiredCache(), 60000); // Cleanup every minute } // Start metrics collection if enabled if (config.monitoring.enabled) { setInterval(() => this.collectMetrics(), config.monitoring.metricsInterval); } } /** * Create a new presentation */ async createPresentation( presentationConfig: PresentationConfig, context: WorkflowContext ): Promise { try { const enhancedContext = this.enhanceContext(context); const presentationData: Omit = { title: presentationConfig.title, description: presentationConfig.description, ownerId: presentationConfig.ownerId, state: PresentationState.DRAFT, config: presentationConfig.settings, metadata: presentationConfig.metadata }; const result = await this.dbConnector.createPresentation(presentationData, enhancedContext); this.metrics.mutations++; if (result.data && result.data.length > 0) { const presentation = result.data[0]; // Cache the new presentation this.setCacheEntry(`presentation:${presentation.id}`, presentation); // Log lifecycle event await this.logLifecycleEvent({ presentationId: presentation.id, eventType: 'presentation.created', toState: PresentationState.DRAFT, metadata: { config: presentationConfig }, context: enhancedContext }); return presentation; } throw new Error('Failed to create presentation - no data returned'); } catch (error) { this.metrics.errors++; throw new Error(`Create presentation failed: ${error instanceof Error ? error.message : 'Unknown error'}`); } } /** * Get presentation by ID */ async getPresentation( presentationId: string, context: WorkflowContext, useCache: boolean = true ): Promise { try { // Check cache first if (useCache && this.config.cache.enabled) { const cached = this.getCacheEntry(`presentation:${presentationId}`); if (cached) { this.metrics.cacheHits++; return cached; } this.metrics.cacheMisses++; } const enhancedContext = this.enhanceContext(context); const result = await this.dbConnector.getPresentation(presentationId, enhancedContext); this.metrics.queries++; if (result.data && result.data.length > 0) { const presentation = result.data[0]; // Cache the result if (this.config.cache.enabled) { this.setCacheEntry(`presentation:${presentationId}`, presentation); } return presentation; } return null; } catch (error) { this.metrics.errors++; throw new Error(`Get presentation failed: ${error instanceof Error ? error.message : 'Unknown error'}`); } } /** * Update presentation state and data */ async updatePresentation( presentationId: string, updates: Partial>, context: WorkflowContext ): Promise { try { const enhancedContext = this.enhanceContext(context); // Get current presentation for state transition logging const current = await this.getPresentation(presentationId, context); const fromState = current?.state as PresentationState; const result = await this.dbConnector.updatePresentation(presentationId, updates, enhancedContext); this.metrics.mutations++; if (result.data && result.data.length > 0) { const updated = result.data[0]; // Update cache if (this.config.cache.enabled) { this.setCacheEntry(`presentation:${presentationId}`, updated); // Invalidate related cache entries this.invalidateCachePattern(`presentation:${presentationId}:*`); } // Log state change if state was updated if (updates.state && fromState !== updates.state) { await this.logLifecycleEvent({ presentationId, eventType: 'presentation.state_changed', fromState, toState: updates.state as PresentationState, metadata: { updates }, context: enhancedContext }); } return updated; } throw new Error('Failed to update presentation - no data returned'); } catch (error) { this.metrics.errors++; throw new Error(`Update presentation failed: ${error instanceof Error ? error.message : 'Unknown error'}`); } } /** * Create a new presentation session */ async createSession( presentationId: string, userId: string, sessionConfig: Record, context: WorkflowContext ): Promise { try { const enhancedContext = this.enhanceContext(context); const sessionData: Omit = { presentationId, userId, state: 'created', resources: {}, settings: sessionConfig, metadata: { createdVia: 'workflow', workflowId: context.workflowId, executionId: context.executionId } }; const result = await this.dbConnector.createSession(sessionData, enhancedContext); this.metrics.mutations++; if (result.data && result.data.length > 0) { const session = result.data[0]; // Cache the session this.setCacheEntry(`session:${session.id}`, session); // Log lifecycle event await this.logLifecycleEvent({ presentationId, sessionId: session.id, eventType: 'session.created', toState: PresentationState.SCHEDULED, metadata: { sessionConfig }, context: enhancedContext }); return session; } throw new Error('Failed to create session - no data returned'); } catch (error) { this.metrics.errors++; throw new Error(`Create session failed: ${error instanceof Error ? error.message : 'Unknown error'}`); } } /** * Update session state */ async updateSessionState( sessionId: string, state: string, metadata?: Record, context?: WorkflowContext ): Promise { try { if (!context) { throw new Error('Context is required for session updates'); } const enhancedContext = this.enhanceContext(context); const result = await this.dbConnector.updateSessionState(sessionId, state, metadata, enhancedContext); this.metrics.mutations++; if (result.data && result.data.length > 0) { const session = result.data[0]; // Update cache this.setCacheEntry(`session:${sessionId}`, session); this.invalidateCacheEntry(`session:${sessionId}:state`); // Log state change await this.logLifecycleEvent({ presentationId: session.presentationId, sessionId, eventType: `session.${state}`, toState: this.mapSessionStateToPresentation(state), metadata: metadata || {}, context: enhancedContext }); return session; } throw new Error('Failed to update session state - no data returned'); } catch (error) { this.metrics.errors++; throw new Error(`Update session state failed: ${error instanceof Error ? error.message : 'Unknown error'}`); } } /** * Allocate resources for presentation */ async allocateResources( presentationId: string, sessionId: string, requirements: ResourceRequirements, context: WorkflowContext ): Promise { try { const enhancedContext = this.enhanceContext(context); const allocations: ResourceAllocation[] = []; // Allocate CPU resources if (requirements.cpu > 0) { const cpuAllocation: Omit = { presentationId, sessionId, resourceType: 'cpu', resourceId: `cpu-${crypto.randomUUID()}`, config: { cores: requirements.cpu } }; const result = await this.dbConnector.allocateResource(cpuAllocation, enhancedContext); if (result.data && result.data.length > 0) { allocations.push(result.data[0]); } } // Allocate memory resources if (requirements.memory > 0) { const memoryAllocation: Omit = { presentationId, sessionId, resourceType: 'memory', resourceId: `mem-${crypto.randomUUID()}`, config: { size: requirements.memory } }; const result = await this.dbConnector.allocateResource(memoryAllocation, enhancedContext); if (result.data && result.data.length > 0) { allocations.push(result.data[0]); } } // Allocate storage resources if (requirements.storage > 0) { const storageAllocation: Omit = { presentationId, sessionId, resourceType: 'storage', resourceId: `storage-${crypto.randomUUID()}`, config: { size: requirements.storage } }; const result = await this.dbConnector.allocateResource(storageAllocation, enhancedContext); if (result.data && result.data.length > 0) { allocations.push(result.data[0]); } } this.metrics.mutations += allocations.length; // Log resource allocation await this.logLifecycleEvent({ presentationId, sessionId, eventType: 'resources.allocated', toState: PresentationState.STARTING, metadata: { requirements, allocations: allocations.length }, context: enhancedContext }); return allocations; } catch (error) { this.metrics.errors++; throw new Error(`Allocate resources failed: ${error instanceof Error ? error.message : 'Unknown error'}`); } } /** * Release resources for presentation */ async releaseResources( presentationId: string, context: WorkflowContext ): Promise { try { const enhancedContext = this.enhanceContext(context); // Get active resources const activeResult = await this.dbConnector.getActiveResources(presentationId, enhancedContext); const activeResources = activeResult.data || []; let releasedCount = 0; // Release each resource for (const resource of activeResources) { try { await this.dbConnector.releaseResource(resource.id, enhancedContext); releasedCount++; } catch (error) { // Log error but continue releasing other resources console.error(`Failed to release resource ${resource.id}:`, error); } } this.metrics.mutations += releasedCount; // Log resource release if (releasedCount > 0) { await this.logLifecycleEvent({ presentationId, eventType: 'resources.released', toState: PresentationState.CLEANING_UP, metadata: { releasedCount, totalResources: activeResources.length }, context: enhancedContext }); } return releasedCount; } catch (error) { this.metrics.errors++; throw new Error(`Release resources failed: ${error instanceof Error ? error.message : 'Unknown error'}`); } } /** * Synchronize presentation data */ async syncPresentationData( presentationId: string, syncConfig: { tables: string[]; direction: 'push' | 'pull' | 'bidirectional'; batchSize?: number; }, context: WorkflowContext ): Promise { try { const syncId = `sync_${crypto.randomUUID()}`; const enhancedContext = this.enhanceContext(context); const syncStatus: DataSyncStatus = { syncId, presentationId, status: 'running', progress: { totalRecords: 0, processedRecords: 0, errorCount: 0 }, startedAt: new Date().toISOString() }; this.activeSyncs.set(syncId, syncStatus); // Log sync start await this.logLifecycleEvent({ presentationId, eventType: 'data.sync.started', toState: PresentationState.RUNNING, metadata: { syncId, syncConfig }, context: enhancedContext }); // Perform the actual sync (simplified implementation) try { // In a real implementation, you'd use the Supabase adapter's sync operations // For now, we'll simulate the sync process await new Promise(resolve => setTimeout(resolve, 1000)); // Simulate sync time syncStatus.status = 'completed'; syncStatus.completedAt = new Date().toISOString(); syncStatus.progress.totalRecords = 100; // Mock data syncStatus.progress.processedRecords = 100; // Log sync completion await this.logLifecycleEvent({ presentationId, eventType: 'data.sync.completed', toState: PresentationState.RUNNING, metadata: { syncId, progress: syncStatus.progress }, context: enhancedContext }); } catch (error) { syncStatus.status = 'failed'; syncStatus.error = error instanceof Error ? error.message : 'Unknown error'; syncStatus.completedAt = new Date().toISOString(); // Log sync failure await this.logLifecycleEvent({ presentationId, eventType: 'data.sync.failed', toState: PresentationState.FAILED, metadata: { syncId, error: syncStatus.error }, context: enhancedContext }); } this.activeSyncs.set(syncId, syncStatus); return syncStatus; } catch (error) { this.metrics.errors++; throw new Error(`Sync presentation data failed: ${error instanceof Error ? error.message : 'Unknown error'}`); } } /** * Get sync status */ getSyncStatus(syncId: string): DataSyncStatus | undefined { return this.activeSyncs.get(syncId); } /** * Get service metrics */ getMetrics() { return { ...this.metrics, cacheSize: this.cache.size, activeSyncs: this.activeSyncs.size, timestamp: new Date().toISOString() }; } /** * Cleanup resources and connections */ async cleanup(): Promise { // Clear caches this.cache.clear(); this.activeSyncs.clear(); // Cleanup database connector await this.dbConnector.cleanup(); } /** * Private: Enhance workflow context with Supabase integration */ private enhanceContext(context: WorkflowContext): WorkflowContext & { supabase: EnhancedSupabaseWorkflowContext } { return { ...context, supabase: { connectionId: `conn_${context.executionId}`, userId: context.userId, tablePermissions: { presentations: ['select', 'insert', 'update'], presentation_sessions: ['select', 'insert', 'update'], resource_allocations: ['select', 'insert', 'update'], presentation_events: ['select', 'insert'] }, rls: { enabled: true, policies: ['presentation_owner_policy', 'session_access_policy'] }, auth: { userId: context.userId, role: 'authenticated', permissions: { tables: { presentations: ['select', 'insert', 'update'], presentation_sessions: ['select', 'insert', 'update'], resource_allocations: ['select', 'insert', 'update'] }, functions: [], storage: {} }, rlsPolicies: [] }, monitoring: { metricsEnabled: this.config.monitoring.enabled, tracingEnabled: this.config.monitoring.enabled, logLevel: 'info' } } }; } /** * Private: Log presentation lifecycle events */ private async logLifecycleEvent({ presentationId, sessionId, eventType, fromState, toState, metadata, context }: { presentationId: string; sessionId?: string; eventType: string; fromState?: PresentationState; toState: PresentationState; metadata: Record; context: WorkflowContext & { supabase: EnhancedSupabaseWorkflowContext }; }): Promise { try { // In a real implementation, you'd store this in a lifecycle events table const event: PresentationLifecycleEvent = { id: crypto.randomUUID(), presentationId, sessionId, eventType, fromState, toState, metadata, timestamp: new Date().toISOString() }; // For now, we'll just log it console.log('Presentation Lifecycle Event:', event); } catch (error) { // Don't fail the main operation if logging fails console.error('Failed to log lifecycle event:', error); } } /** * Private: Map session state to presentation state */ private mapSessionStateToPresentation(sessionState: string): PresentationState { const stateMap: Record = { 'created': PresentationState.SCHEDULED, 'starting': PresentationState.STARTING, 'running': PresentationState.RUNNING, 'paused': PresentationState.PAUSED, 'ended': PresentationState.COMPLETED, 'failed': PresentationState.FAILED, 'cancelled': PresentationState.CANCELLED }; return stateMap[sessionState] || PresentationState.DRAFT; } /** * Private: Cache management methods */ private setCacheEntry(key: string, data: T, ttl?: number): void { if (!this.config.cache.enabled) return; const entry: CacheEntry = { data, timestamp: Date.now(), ttl: ttl || this.config.cache.defaultTtl }; // Remove oldest entries if cache is full if (this.cache.size >= this.config.cache.maxSize) { const oldestKey = this.findOldestCacheEntry(); if (oldestKey) { this.cache.delete(oldestKey); } } this.cache.set(key, entry); } private getCacheEntry(key: string): T | null { if (!this.config.cache.enabled) return null; const entry = this.cache.get(key) as CacheEntry | undefined; if (!entry) return null; // Check if expired if (Date.now() - entry.timestamp > entry.ttl) { this.cache.delete(key); return null; } return entry.data; } private invalidateCacheEntry(key: string): void { this.cache.delete(key); } private invalidateCachePattern(pattern: string): void { const regex = new RegExp(pattern.replace('*', '.*')); for (const key of this.cache.keys()) { if (regex.test(key)) { this.cache.delete(key); } } } private findOldestCacheEntry(): string | null { let oldestKey: string | null = null; let oldestTime: number = Infinity; for (const [key, entry] of this.cache.entries()) { if (entry.timestamp < oldestTime) { oldestTime = entry.timestamp; oldestKey = key; } } return oldestKey; } private cleanupExpiredCache(): void { const now = Date.now(); const expiredKeys: string[] = []; for (const [key, entry] of this.cache.entries()) { if (now - entry.timestamp > entry.ttl) { expiredKeys.push(key); } } for (const key of expiredKeys) { this.cache.delete(key); } } private collectMetrics(): void { // In a real implementation, you'd send these to a monitoring service const metrics = this.getMetrics(); console.log('PresentationDataService Metrics:', metrics); } } /** * Factory function to create presentation data service */ export function createPresentationDataService( config: PresentationDataServiceConfig ): PresentationDataService { return new PresentationDataService(config); } /** * Create default service configuration */ export function createDefaultServiceConfig( databaseConfig: SupabaseConnectionConfig ): PresentationDataServiceConfig { return { database: databaseConfig, cache: { enabled: true, defaultTtl: 300000, // 5 minutes maxSize: 1000 }, sync: { batchSize: 100, retryAttempts: 3, retryDelay: 1000 }, monitoring: { enabled: true, metricsInterval: 60000 // 1 minute } }; }