/** * Supabase adapter for workflow integration * * This adapter provides a bridge between the workflow engine and Supabase, * handling database operations, connection management, and transaction * coordination within workflow execution contexts. */ import { createClient, SupabaseClient, PostgrestResponse } from '@supabase/supabase-js'; import { WorkflowContext, WorkflowExecution, StepExecutionResult } from '../types/presentation-types.js'; import { SupabaseConnectionConfig, SupabaseWorkflowError, SupabaseErrorType, EnhancedSupabaseWorkflowContext, SupabasePresentationQueryOperation, SupabasePresentationMutationOperation, SupabaseStorageOperation, SupabaseBatchOperation, TransactionOptions, DatabaseOperationMetadata, ConnectionPoolStatus, DatabaseHealthCheck, SupabaseAuthContext } from '../types/supabase-workflow-types.js'; /** * Connection pool manager for Supabase connections */ class SupabaseConnectionPool { private connections: Map = new Map(); private connectionCount: Map = new Map(); private lastActivity: Map = new Map(); private config: SupabaseConnectionConfig; constructor(config: SupabaseConnectionConfig) { this.config = config; } async getConnection(poolId: string): Promise { if (this.connections.has(poolId)) { this.lastActivity.set(poolId, new Date()); return this.connections.get(poolId)!; } if (this.connections.size >= this.config.poolConfig.maxConnections) { // Find and close oldest idle connection const oldestConnection = this.findOldestIdleConnection(); if (oldestConnection) { this.closeConnection(oldestConnection); } else { throw new Error('Connection pool exhausted and no idle connections available'); } } const client = createClient(this.config.url, this.config.anonKey, { auth: { persistSession: false, autoRefreshToken: false }, realtime: { params: { eventsPerSecond: 10 } } }); this.connections.set(poolId, client); this.connectionCount.set(poolId, 0); this.lastActivity.set(poolId, new Date()); return client; } private findOldestIdleConnection(): string | null { let oldestPoolId: string | null = null; let oldestTime: Date | null = null; for (const [poolId, lastActivity] of this.lastActivity.entries()) { const count = this.connectionCount.get(poolId) || 0; if (count === 0 && (!oldestTime || lastActivity < oldestTime)) { oldestTime = lastActivity; oldestPoolId = poolId; } } return oldestPoolId; } private closeConnection(poolId: string): void { const client = this.connections.get(poolId); if (client) { // Supabase client doesn't have explicit close method // Connection will be garbage collected this.connections.delete(poolId); this.connectionCount.delete(poolId); this.lastActivity.delete(poolId); } } incrementUsage(poolId: string): void { const current = this.connectionCount.get(poolId) || 0; this.connectionCount.set(poolId, current + 1); } decrementUsage(poolId: string): void { const current = this.connectionCount.get(poolId) || 0; this.connectionCount.set(poolId, Math.max(0, current - 1)); this.lastActivity.set(poolId, new Date()); } getStatus(): ConnectionPoolStatus { const totalConnections = this.connections.size; const activeConnections = Array.from(this.connectionCount.values()) .filter(count => count > 0).length; const idleConnections = totalConnections - activeConnections; return { poolId: 'main', totalConnections, activeConnections, idleConnections, waitingClients: 0, // Not tracked in this simple implementation config: this.config.poolConfig, metrics: { totalQueries: 0, // Would need to be tracked separately avgQueryTime: 0, // Would need to be tracked separately errorRate: 0, // Would need to be tracked separately lastActivity: new Date().toISOString() } }; } async healthCheck(): Promise { const startTime = Date.now(); const poolId = 'health-check'; try { const client = await this.getConnection(poolId); const { data, error } = await client.from('_health_check').select('*').limit(1); const responseTime = Date.now() - startTime; return { status: error ? 'unhealthy' : 'healthy', responseTime, connectionPool: this.getStatus(), activeTransactions: 0, // Not available from Supabase client locksWaiting: 0, // Not available from Supabase client timestamp: new Date().toISOString() }; } catch (error) { return { status: 'unhealthy', responseTime: Date.now() - startTime, connectionPool: this.getStatus(), activeTransactions: 0, locksWaiting: 0, timestamp: new Date().toISOString() }; } finally { this.decrementUsage(poolId); } } async cleanup(): Promise { for (const poolId of this.connections.keys()) { this.closeConnection(poolId); } } } /** * Main Supabase adapter class */ export class SupabaseWorkflowAdapter { private connectionPool: SupabaseConnectionPool; private config: SupabaseConnectionConfig; private activeTransactions: Map = new Map(); // executionId -> transactionId constructor(config: SupabaseConnectionConfig) { this.config = config; this.connectionPool = new SupabaseConnectionPool(config); } /** * Execute a query operation within workflow context */ async executeQuery( operation: SupabasePresentationQueryOperation, context: WorkflowContext ): Promise { const startTime = Date.now(); const connectionId = operation.inputs.context.supabase.connectionId; try { this.connectionPool.incrementUsage(connectionId); const client = await this.connectionPool.getConnection(connectionId); // Apply authentication context if present if (operation.inputs.context.supabase.userId) { // Set RLS context - in a real implementation, you'd set auth context // client.auth.setAuth(operation.inputs.context.supabase.userId); } let query = client.from(operation.inputs.query.table); // Apply select if (operation.inputs.query.select) { query = query.select(operation.inputs.query.select.join(',')); } else { query = query.select('*'); } // Apply filters if (operation.inputs.query.filter) { for (const [key, value] of Object.entries(operation.inputs.query.filter)) { query = query.eq(key, value); } } // Apply ordering if (operation.inputs.query.orderBy) { for (const order of operation.inputs.query.orderBy) { query = query.order(order.column, { ascending: order.ascending }); } } // Apply pagination if (operation.inputs.query.limit) { query = query.limit(operation.inputs.query.limit); } if (operation.inputs.query.offset) { query = query.range( operation.inputs.query.offset, operation.inputs.query.offset + (operation.inputs.query.limit || 1000) - 1 ); } const response = await query; const executionTime = Date.now() - startTime; if (response.error) { throw this.createSupabaseError(response.error, 'query', operation.inputs.query.table); } const metadata: DatabaseOperationMetadata = { operationId: operation.id, table: operation.inputs.query.table, operation: 'select', rowCount: response.data?.length || 0, executionTime }; return { stepId: operation.id, status: 'success', outputs: { data: response.data || [], count: response.count, metadata }, duration: executionTime, executedAt: new Date().toISOString() }; } catch (error) { const executionTime = Date.now() - startTime; return { stepId: operation.id, status: 'failure', error: { message: error instanceof Error ? error.message : 'Unknown error', code: (error as any)?.code, stack: error instanceof Error ? error.stack : undefined }, duration: executionTime, executedAt: new Date().toISOString() }; } finally { this.connectionPool.decrementUsage(connectionId); } } /** * Execute a mutation operation within workflow context */ async executeMutation( operation: SupabasePresentationMutationOperation, context: WorkflowContext ): Promise { const startTime = Date.now(); const connectionId = operation.inputs.context.supabase.connectionId; const transactionId = `tx_${context.executionId}_${operation.id}`; try { this.connectionPool.incrementUsage(connectionId); const client = await this.connectionPool.getConnection(connectionId); // Apply authentication context if present if (operation.inputs.context.supabase.userId) { // Set RLS context - in a real implementation, you'd set auth context } // Start transaction tracking if (operation.inputs.transactionOptions) { this.activeTransactions.set(context.executionId, transactionId); } let query; const { table, operation: op, data, filter, returning } = operation.inputs.mutation; switch (op) { case 'insert': query = client.from(table).insert(data); break; case 'update': query = client.from(table).update(data); if (filter) { for (const [key, value] of Object.entries(filter)) { query = query.eq(key, value); } } break; case 'delete': query = client.from(table).delete(); if (filter) { for (const [key, value] of Object.entries(filter)) { query = query.eq(key, value); } } break; case 'upsert': query = client.from(table).upsert(data); break; default: throw new Error(`Unsupported mutation operation: ${op}`); } // Apply returning clause if (returning && returning.length > 0) { query = query.select(returning.join(',')); } const response = await query; const executionTime = Date.now() - startTime; if (response.error) { throw this.createSupabaseError(response.error, op, table); } const metadata: DatabaseOperationMetadata = { operationId: operation.id, table, operation: op, rowCount: response.data?.length || 0, executionTime }; return { stepId: operation.id, status: 'success', outputs: { data: response.data || [], count: response.data?.length || 0, metadata }, duration: executionTime, executedAt: new Date().toISOString() }; } catch (error) { const executionTime = Date.now() - startTime; // Rollback transaction if needed if (operation.inputs.transactionOptions?.rollbackOnError) { this.activeTransactions.delete(context.executionId); // In a real implementation, you'd rollback the transaction } return { stepId: operation.id, status: 'failure', error: { message: error instanceof Error ? error.message : 'Unknown error', code: (error as any)?.code, stack: error instanceof Error ? error.stack : undefined }, duration: executionTime, executedAt: new Date().toISOString() }; } finally { this.connectionPool.decrementUsage(connectionId); } } /** * Execute storage operations */ async executeStorageOperation( operation: SupabaseStorageOperation, context: WorkflowContext ): Promise { const startTime = Date.now(); const connectionId = operation.inputs.context.supabase.connectionId; try { this.connectionPool.incrementUsage(connectionId); const client = await this.connectionPool.getConnection(connectionId); const { bucket, operation: op, path, data, options } = operation.inputs.storage; const storage = client.storage.from(bucket); let response: any; switch (op) { case 'upload': if (!data) throw new Error('Data is required for upload operation'); response = await storage.upload(path, data, options); break; case 'download': response = await storage.download(path); break; case 'delete': response = await storage.remove([path]); break; case 'move': // Move operation would need additional parameters throw new Error('Move operation not implemented'); case 'copy': // Copy operation would need additional parameters throw new Error('Copy operation not implemented'); default: throw new Error(`Unsupported storage operation: ${op}`); } const executionTime = Date.now() - startTime; if (response.error) { throw this.createSupabaseError(response.error, op, bucket); } let outputs: any = {}; if (op === 'upload') { outputs.path = response.data?.path; const { data: publicUrlData } = storage.getPublicUrl(path); outputs.publicUrl = publicUrlData.publicUrl; } else if (op === 'download') { outputs.data = response.data; } return { stepId: operation.id, status: 'success', outputs, duration: executionTime, executedAt: new Date().toISOString() }; } catch (error) { const executionTime = Date.now() - startTime; return { stepId: operation.id, status: 'failure', error: { message: error instanceof Error ? error.message : 'Unknown error', code: (error as any)?.code, stack: error instanceof Error ? error.stack : undefined }, duration: executionTime, executedAt: new Date().toISOString() }; } finally { this.connectionPool.decrementUsage(connectionId); } } /** * Execute batch operations in a transaction */ async executeBatch( operation: SupabaseBatchOperation, context: WorkflowContext ): Promise { const startTime = Date.now(); const connectionId = operation.inputs.context.supabase.connectionId; const transactionId = `batch_tx_${context.executionId}_${operation.id}`; try { this.connectionPool.incrementUsage(connectionId); const client = await this.connectionPool.getConnection(connectionId); // Track transaction this.activeTransactions.set(context.executionId, transactionId); const results = []; let hasError = false; // Execute operations sequentially // In a real implementation, you'd use database transactions for (const batchOp of operation.inputs.operations) { const opStartTime = Date.now(); try { let query; switch (batchOp.operation) { case 'insert': query = client.from(batchOp.table).insert(batchOp.data); break; case 'update': query = client.from(batchOp.table).update(batchOp.data); if (batchOp.filter) { for (const [key, value] of Object.entries(batchOp.filter)) { query = query.eq(key, value); } } break; case 'delete': query = client.from(batchOp.table).delete(); if (batchOp.filter) { for (const [key, value] of Object.entries(batchOp.filter)) { query = query.eq(key, value); } } break; case 'upsert': query = client.from(batchOp.table).upsert(batchOp.data); break; } if (batchOp.returning && batchOp.returning.length > 0) { query = query.select(batchOp.returning.join(',')); } const response = await query; const opExecutionTime = Date.now() - opStartTime; if (response.error) { hasError = true; results.push({ id: batchOp.id, success: false, error: response.error.message, metadata: { operationId: batchOp.id, table: batchOp.table, operation: batchOp.operation, executionTime: opExecutionTime } }); if (operation.inputs.transactionOptions.rollbackOnError) { break; // Stop processing on first error } } else { results.push({ id: batchOp.id, success: true, data: response.data, metadata: { operationId: batchOp.id, table: batchOp.table, operation: batchOp.operation, rowCount: response.data?.length || 0, executionTime: opExecutionTime } }); } } catch (error) { hasError = true; results.push({ id: batchOp.id, success: false, error: error instanceof Error ? error.message : 'Unknown error', metadata: { operationId: batchOp.id, table: batchOp.table, operation: batchOp.operation, executionTime: Date.now() - opStartTime } }); if (operation.inputs.transactionOptions.rollbackOnError) { break; } } } const totalExecutionTime = Date.now() - startTime; // Clean up transaction this.activeTransactions.delete(context.executionId); return { stepId: operation.id, status: hasError && operation.inputs.transactionOptions.rollbackOnError ? 'failure' : 'success', outputs: { results, transactionId, totalExecutionTime }, duration: totalExecutionTime, executedAt: new Date().toISOString() }; } catch (error) { const executionTime = Date.now() - startTime; this.activeTransactions.delete(context.executionId); return { stepId: operation.id, status: 'failure', error: { message: error instanceof Error ? error.message : 'Unknown error', code: (error as any)?.code, stack: error instanceof Error ? error.stack : undefined }, duration: executionTime, executedAt: new Date().toISOString() }; } finally { this.connectionPool.decrementUsage(connectionId); } } /** * Get connection pool status */ getConnectionPoolStatus(): ConnectionPoolStatus { return this.connectionPool.getStatus(); } /** * Perform health check */ async healthCheck(): Promise { return this.connectionPool.healthCheck(); } /** * Clean up resources */ async cleanup(): Promise { await this.connectionPool.cleanup(); this.activeTransactions.clear(); } /** * Create a standardized Supabase error */ private createSupabaseError(error: any, operation: string, table: string): SupabaseWorkflowError { let errorType: SupabaseErrorType; // Map common Supabase error codes to our error types switch (error.code) { case '23505': // unique_violation errorType = SupabaseErrorType.CONSTRAINT_VIOLATION; break; case '42501': // insufficient_privilege errorType = SupabaseErrorType.AUTHORIZATION_FAILED; break; case '08003': // connection_does_not_exist errorType = SupabaseErrorType.CONNECTION_FAILED; break; case '57014': // query_canceled (timeout) errorType = SupabaseErrorType.QUERY_TIMEOUT; break; default: errorType = SupabaseErrorType.QUERY_TIMEOUT; // Default fallback } return { type: errorType, message: error.message || 'Unknown Supabase error', code: error.code, details: error.details || {}, operation, table, retryable: this.isRetryableError(errorType), timestamp: new Date().toISOString() }; } /** * Determine if an error is retryable */ private isRetryableError(errorType: SupabaseErrorType): boolean { const retryableErrors = [ SupabaseErrorType.CONNECTION_FAILED, SupabaseErrorType.QUERY_TIMEOUT, SupabaseErrorType.TRANSACTION_CONFLICT, SupabaseErrorType.RATE_LIMIT_EXCEEDED ]; return retryableErrors.includes(errorType); } } /** * Factory function to create Supabase adapter instances */ export function createSupabaseAdapter(config: SupabaseConnectionConfig): SupabaseWorkflowAdapter { return new SupabaseWorkflowAdapter(config); } /** * Default Supabase adapter configuration */ export function createDefaultSupabaseAdapter(url: string, anonKey: string): SupabaseWorkflowAdapter { const config: SupabaseConnectionConfig = { url, anonKey, projectId: extractProjectId(url), poolConfig: { minConnections: 1, maxConnections: 10, acquireTimeoutMillis: 30000, idleTimeoutMillis: 300000, reapIntervalMillis: 60000 }, ssl: { enabled: true, rejectUnauthorized: true } }; return new SupabaseWorkflowAdapter(config); } function extractProjectId(url: string): string { const match = url.match(/https:\/\/([a-z0-9]+)\.supabase\.co/); return match?.[1] || 'unknown'; }