import { promises as fs } from 'fs'; import * as path from 'path'; // Utility functions to replace fs-extra const pathExists = async (filepath: string): Promise => { try { await fs.access(filepath); return true; } catch { return false; } }; const readJSON = async (filepath: string): Promise => { const content = await fs.readFile(filepath, 'utf8'); return JSON.parse(content); }; const writeJSON = async (filepath: string, data: unknown, options?: { spaces?: number }): Promise => { const content = JSON.stringify(data, null, options?.spaces || 0); await fs.writeFile(filepath, content, 'utf8'); }; const ensureDir = async (dirpath: string): Promise => { try { await fs.mkdir(dirpath, { recursive: true }); } catch (error: unknown) { if (error && typeof error === 'object' && 'code' in error && error.code !== 'EEXIST') { throw error; } } }; const removeDir = async (dirpath: string): Promise => { await fs.rm(dirpath, { recursive: true, force: true }); }; export interface BackupMetadata { backup_id: string; customer_id: string; customer_name: string; service: string; backup_type: string; created_at: string; file_size: number; file_path: string; checksum?: string; metadata?: unknown; } export interface CustomerInfo { customer_id: string; customer_name: string; environment: string; apiKey?: string; } export interface TavusBackupData { account_info: { id: string; name: string; apiKey?: string; environment: string; }; backup_timestamp: string; personas: { persona_id: string; persona_name: string; pipeline_mode?: string; system_prompt?: string; context?: string; layers?: unknown; objectives_id?: string | null; guardrails_id?: string | null; greeting?: string; default_replica_id?: string; document_ids?: string[]; document_tags?: string[]; created_at?: string; updated_at?: string; }[]; conversations?: unknown[]; replicas?: unknown[]; objectives?: unknown[]; guardrails?: unknown[]; } export class FileBackupStorage { private baseBackupPath: string; constructor(backupPath = './backup-data') { this.baseBackupPath = path.resolve(backupPath); } /** * Get all available backups by scanning the file system */ async getAllBackups(): Promise { const backups: BackupMetadata[] = []; const customersPath = path.join(this.baseBackupPath, 'customers'); if (!await pathExists(customersPath)) { return backups; } const customerDirs = await fs.readdir(customersPath); for (const customerDir of customerDirs) { const customerPath = path.join(customersPath, customerDir); const stat = await fs.stat(customerPath); if (!stat.isDirectory()) continue; const timestampDirs = await fs.readdir(customerPath); for (const timestampDir of timestampDirs) { const backupPath = path.join(customerPath, timestampDir); const backupStat = await fs.stat(backupPath); if (!backupStat.isDirectory()) continue; // Check for tavus-data.json const tavusDataPath = path.join(backupPath, 'tavus-data.json'); if (await pathExists(tavusDataPath)) { const fileStats = await fs.stat(tavusDataPath); const backupData = await this.loadTavusBackupData(customerDir, timestampDir); if (backupData) { backups.push({ backup_id: `${customerDir}-${timestampDir}`, customer_id: customerDir, customer_name: backupData.account_info.name, service: 'tavus', backup_type: 'full', created_at: backupData.backup_timestamp, file_size: fileStats.size, file_path: tavusDataPath, metadata: { environment: backupData.account_info.environment, personas_count: backupData.personas?.length || 0, conversations_count: backupData.conversations?.length || 0, replicas_count: backupData.replicas?.length || 0, objectives_count: backupData.objectives?.length || 0, guardrails_count: backupData.guardrails?.length || 0, api_status: 'active' } }); } } // Check for customer-data.json const customerDataPath = path.join(backupPath, 'customer-data.json'); if (await pathExists(customerDataPath)) { const fileStats = await fs.stat(customerDataPath); const customerData = await readJSON(customerDataPath); backups.push({ backup_id: `${customerDir}-${timestampDir}-customer`, customer_id: customerDir, customer_name: (customerData as { customer_info?: unknown })?.customer_info?.customer_name || customerDir, service: 'customer', backup_type: customerData.backup_type || 'full', created_at: customerData.backup_timestamp, file_size: fileStats.size, file_path: customerDataPath, metadata: { environment: 'unknown', customer_info: (customerData as { customer_info?: unknown })?.customer_info } }); } } } return backups.sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime()); } /** * Load Tavus backup data from file */ async loadTavusBackupData(customerId: string, timestamp: string): Promise { const filePath = path.join(this.baseBackupPath, 'customers', customerId, timestamp, 'tavus-data.json'); if (!await pathExists(filePath)) { return null; } try { return await readJSON(filePath) as TavusBackupData | null; } catch (error) { console.error(`Failed to load Tavus backup data from ${filePath}:`, error); return null; } } /** * Get backup data by backup ID */ async getBackupData(backupId: string): Promise { // Parse backup ID (format: customer-id-timestamp or customer-id-timestamp-customer) const parts = backupId.split('-'); if (parts.length < 3) { throw new Error(`Invalid backup ID format: ${backupId}`); } // Handle different backup ID formats let customerId: string; let timestamp: string; let isCustomerData = false; if (backupId.endsWith('-customer')) { // customer-demo-001-2025-09-02T15-38-13-283Z-customer isCustomerData = true; const withoutCustomer = backupId.replace('-customer', ''); const lastDashIndex = withoutCustomer.lastIndexOf('-'); customerId = withoutCustomer.substring(0, lastDashIndex); timestamp = withoutCustomer.substring(lastDashIndex + 1); } else { // customer-prod1-2025-09-09T17-37-39-541Z const lastDashIndex = backupId.lastIndexOf('-'); customerId = backupId.substring(0, lastDashIndex); timestamp = backupId.substring(lastDashIndex + 1); } if (isCustomerData) { const filePath = path.join(this.baseBackupPath, 'customers', customerId, timestamp, 'customer-data.json'); if (await pathExists(filePath)) { return await readJSON(filePath) as TavusBackupData | null; } } else { const tavusData = await this.loadTavusBackupData(customerId, timestamp); if (tavusData) { return { personas: tavusData.personas || [], conversations: tavusData.conversations || [], replicas: tavusData.replicas || [], objectives: tavusData.objectives || [], guardrails: tavusData.guardrails || [], api_status: 'active', backup_timestamp: tavusData.backup_timestamp, account_info: tavusData.account_info }; } } throw new Error(`Backup not found: ${backupId}`); } /** * Save new Tavus backup data */ async saveTavusBackup(customerId: string, customerName: string, environment: string, data: TavusBackupData): Promise { const timestamp = new Date().toISOString().replace(/:/g, '-').replace(/\./g, '-'); const backupDir = path.join(this.baseBackupPath, 'customers', customerId, timestamp); await ensureDir(backupDir); const filePath = path.join(backupDir, 'tavus-data.json'); await writeJSON(filePath, data, { spaces: 2 }); const fileStats = await fs.stat(filePath); return { backup_id: `${customerId}-${timestamp}`, customer_id: customerId, customer_name: customerName, service: 'tavus', backup_type: 'full', created_at: data.backup_timestamp, file_size: fileStats.size, file_path: filePath, metadata: { environment, personas_count: data.personas?.length || 0, conversations_count: data.conversations?.length || 0, replicas_count: data.replicas?.length || 0, objectives_count: data.objectives?.length || 0, guardrails_count: data.guardrails?.length || 0, api_status: 'active' } }; } /** * Get available customers from backup directories */ async getAvailableCustomers(): Promise<{ customer_id: string; customer_name: string; backup_count: number }[]> { const customersPath = path.join(this.baseBackupPath, 'customers'); if (!await pathExists(customersPath)) { return []; } const customerDirs = await fs.readdir(customersPath); const customers: { customer_id: string; customer_name: string; backup_count: number }[] = []; for (const customerDir of customerDirs) { const customerPath = path.join(customersPath, customerDir); const stat = await fs.stat(customerPath); if (!stat.isDirectory()) continue; const timestampDirs = await fs.readdir(customerPath); let customerName = customerDir; // Try to get customer name from the latest backup for (const timestampDir of timestampDirs.reverse()) { const backupData = await this.loadTavusBackupData(customerDir, timestampDir); if (backupData?.account_info?.name) { customerName = backupData.account_info.name; break; } } customers.push({ customer_id: customerDir, customer_name: customerName, backup_count: timestampDirs.length }); } return customers.sort((a, b) => a.customer_name.localeCompare(b.customer_name)); } /** * Get backups for a specific customer */ async getCustomerBackups(customerId: string): Promise { const allBackups = await this.getAllBackups(); return allBackups.filter(backup => backup.customer_id === customerId); } /** * Get backups by service */ async getBackupsByService(service: string): Promise { const allBackups = await this.getAllBackups(); return allBackups.filter(backup => backup.service === service); } /** * Delete old backups based on retention policy */ async cleanupOldBackups(customerId: string, retentionDays: number): Promise { const cutoffDate = new Date(); cutoffDate.setDate(cutoffDate.getDate() - retentionDays); const customerBackups = await this.getCustomerBackups(customerId); let deletedCount = 0; for (const backup of customerBackups) { const backupDate = new Date(backup.created_at); if (backupDate < cutoffDate) { try { const backupDir = path.dirname(backup.file_path); await removeDir(backupDir); deletedCount++; } catch (error) { console.error(`Failed to delete backup ${backup.backup_id}:`, error); } } } return deletedCount; } }