All files / accounts-backup/src/storage file-backup-storage.ts

0% Statements 0/125
0% Branches 0/56
0% Functions 0/18
0% Lines 0/118

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             
import { promises as fs } from 'fs';
import * as path from 'path';
import { v7 as uuidv7 } from 'uuid';
 
// Utility functions to replace fs-extra
const pathExists = async (filepath: string): Promise<boolean> => {
  try {
    await fs.access(filepath);
    return true;
  } catch {
    return false;
  }
};
 
const readJSON = async (filepath: string): Promise<any> => {
  const content = await fs.readFile(filepath, 'utf8');
  return JSON.parse(content);
};
 
const writeJSON = async (filepath: string, data: any, options?: { spaces?: number }): Promise<void> => {
  const content = JSON.stringify(data, null, options?.spaces || 0);
  await fs.writeFile(filepath, content, 'utf8');
};
 
const ensureDir = async (dirpath: string): Promise<void> => {
  try {
    await fs.mkdir(dirpath, { recursive: true });
  } catch (error: any) {
    Iif (error.code !== 'EEXIST') {
      throw error;
    }
  }
};
 
const removeDir = async (dirpath: string): Promise<void> => {
  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?: any;
}
 
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?: any;
    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?: any[];
  replicas?: any[];
  objectives?: any[];
  guardrails?: any[];
}
 
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<BackupMetadata[]> {
    const backups: BackupMetadata[] = [];
    const customersPath = path.join(this.baseBackupPath, 'customers');
 
    Iif (!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);
 
      Iif (!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);
 
        Iif (!backupStat.isDirectory()) continue;
 
        // Check for tavus-data.json
        const tavusDataPath = path.join(backupPath, 'tavus-data.json');
        Iif (await pathExists(tavusDataPath)) {
          const fileStats = await fs.stat(tavusDataPath);
          const backupData = await this.loadTavusBackupData(customerDir, timestampDir);
          
          Iif (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');
        Iif (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.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.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<TavusBackupData | null> {
    const filePath = path.join(this.baseBackupPath, 'customers', customerId, timestamp, 'tavus-data.json');
    
    Iif (!await pathExists(filePath)) {
      return null;
    }
 
    try {
      return await readJSON(filePath);
    } 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<any> {
    // Parse backup ID (format: customer-id-timestamp or customer-id-timestamp-customer)
    const parts = backupId.split('-');
    Iif (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');
      Iif (await pathExists(filePath)) {
        return await readJSON(filePath);
      }
    } else {
      const tavusData = await this.loadTavusBackupData(customerId, timestamp);
      Iif (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<BackupMetadata> {
    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');
    
    Iif (!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);
 
      Iif (!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);
        Iif (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<BackupMetadata[]> {
    const allBackups = await this.getAllBackups();
    return allBackups.filter(backup => backup.customer_id === customerId);
  }
 
  /**
   * Get backups by service
   */
  async getBackupsByService(service: string): Promise<BackupMetadata[]> {
    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<number> {
    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);
      Iif (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;
  }
}