All files / app/core/services/ipfs ipfs-migration.service.ts

100% Statements 75/75
88.46% Branches 23/26
100% Functions 12/12
100% Lines 73/73

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                                                      1x 23x                 23x 23x 23x   23x     23x 23x                   17x 1x     16x 1x     15x 15x 15x             15x   15x   15x     15x 15x     15x                   15x   19x 1x 1x     18x 18x       15x 15x 12x   3x     15x   15x                         18x 39x     18x                       39x   39x     39x 3x 3x       36x     33x     29x 3x       29x     7x 7x               39x   39x 32x         7x                       1x 1x 1x 1x                       2x     2x                             2x 2x     2x 2x   2x 11x 11x 10x             2x 2x     2x   2x                     124x                   1x                           4x    
import { Injectable, Inject } from '@angular/core';
import { BehaviorSubject, Subject } from 'rxjs';
import { IStorageProvider } from '../../domain/interfaces/storage.interface';
import { IPFSStorageService } from './ipfs-storage.service';
import { HeliaStorageService } from '../helia/helia-storage.service';
import { STORAGE_PROVIDER, STORAGE_TYPE, StorageType } from '../storage-provider.factory';
 
export interface MigrationProgress {
  totalItems: number;
  processedItems: number;
  successfulItems: number;
  failedItems: number;
  currentItem?: string;
  status: 'idle' | 'preparing' | 'migrating' | 'completed' | 'failed';
  errors: Array<{ path: string; error: string }>;
}
 
export interface MigrationOptions {
  batchSize?: number;
  deleteAfterMigration?: boolean;
  skipExisting?: boolean;
  filter?: (path: string) => boolean;
}
 
@Injectable({
  providedIn: 'root'
})
export class IPFSMigrationService {
  private progressSubject = new BehaviorSubject<MigrationProgress>({
    totalItems: 0,
    processedItems: 0,
    successfulItems: 0,
    failedItems: 0,
    status: 'idle',
    errors: []
  });
 
  private cancelSubject = new Subject<void>();
  private isRunning = false;
  private isCancelled = false;
 
  progress$ = this.progressSubject.asObservable();
 
  constructor(
    @Inject(STORAGE_PROVIDER) private currentStorageProvider: IStorageProvider,
    @Inject(STORAGE_TYPE) private currentStorageType: StorageType
  ) {}
 
  /**
   * Migrate content from current storage provider to IPFS or Helia
   */
  async migrateToIPFS(
    targetProvider: IPFSStorageService | HeliaStorageService,
    options: MigrationOptions = {}
  ): Promise<MigrationProgress> {
    if (this.isRunning) {
      throw new Error('Migration is already in progress');
    }
 
    if (this.currentStorageProvider === targetProvider) {
      throw new Error('Cannot migrate to the same storage provider');
    }
 
    this.isRunning = true;
    this.isCancelled = false;
    this.cancelSubject = new Subject<void>();
 
    const {
      batchSize = 10,
      deleteAfterMigration = false,
      skipExisting = true,
      filter
    } = options;
 
    try {
      // Update status to preparing
      this.updateProgress({ status: 'preparing' });
 
      // Get list of all items to migrate
      const allPaths = await this.currentStorageProvider.list();
      const pathsToMigrate = filter ? allPaths.filter(filter) : allPaths;
 
      // Initialize progress
      this.updateProgress({
        totalItems: pathsToMigrate.length,
        processedItems: 0,
        successfulItems: 0,
        failedItems: 0,
        status: 'migrating',
        errors: []
      });
 
      // Process in batches
      for (let i = 0; i < pathsToMigrate.length; i += batchSize) {
        // Check for cancellation
        if (this.isCancelled) {
          this.updateProgress({ status: 'failed' });
          break;
        }
 
        const batch = pathsToMigrate.slice(i, i + batchSize);
        await this.processBatch(batch, targetProvider, skipExisting, deleteAfterMigration);
      }
 
      // Update final status
      const finalProgress = this.progressSubject.value;
      if (finalProgress.failedItems === 0) {
        this.updateProgress({ status: 'completed' });
      } else {
        this.updateProgress({ status: 'failed' });
      }
 
      return this.progressSubject.value;
    } finally {
      this.isRunning = false;
    }
  }
 
  /**
   * Process a batch of items for migration
   */
  private async processBatch(
    paths: string[],
    targetProvider: IPFSStorageService | HeliaStorageService,
    skipExisting: boolean,
    deleteAfterMigration: boolean
  ): Promise<void> {
    const promises = paths.map(path => 
      this.migrateItem(path, targetProvider, skipExisting, deleteAfterMigration)
    );
 
    await Promise.all(promises);
  }
 
  /**
   * Migrate a single item
   */
  private async migrateItem(
    path: string,
    targetProvider: IPFSStorageService | HeliaStorageService,
    skipExisting: boolean,
    deleteAfterMigration: boolean
  ): Promise<void> {
    try {
      // Update current item
      this.updateProgress({ currentItem: path });
 
      // Check if already exists in target
      if (skipExisting && await targetProvider.exists(path)) {
        this.incrementProgress(true);
        return;
      }
 
      // Read from source
      const data = await this.currentStorageProvider.read(path);
 
      // Write to target
      await targetProvider.write(path, data);
 
      // Delete from source if requested
      if (deleteAfterMigration) {
        await this.currentStorageProvider.delete(path);
      }
 
      // Update progress with success
      this.incrementProgress(true);
    } catch (error) {
      // Update progress with error
      const errorMessage = error instanceof Error ? error.message : 'Unknown error';
      this.incrementProgress(false, { path, error: errorMessage });
    }
  }
 
  /**
   * Increment progress counters atomically
   */
  private incrementProgress(success: boolean, error?: { path: string; error: string }): void {
    const currentProgress = this.progressSubject.value;
    
    if (success) {
      this.updateProgress({
        processedItems: currentProgress.processedItems + 1,
        successfulItems: currentProgress.successfulItems + 1
      });
    } else {
      this.updateProgress({
        processedItems: currentProgress.processedItems + 1,
        failedItems: currentProgress.failedItems + 1,
        errors: error ? [...currentProgress.errors, error] : currentProgress.errors
      });
    }
  }
 
  /**
   * Cancel ongoing migration
   */
  cancelMigration(): void {
    if (this.isRunning) {
      this.isCancelled = true;
      this.cancelSubject.next();
      this.cancelSubject.complete();
    }
  }
 
  /**
   * Get migration statistics
   */
  getMigrationStats(): {
    canMigrate: boolean;
    currentStorageType: StorageType;
    estimatedItems?: number;
  } {
    const canMigrate = this.currentStorageType !== StorageType.IPFS && 
                      this.currentStorageType !== StorageType.HELIA;
 
    return {
      canMigrate,
      currentStorageType: this.currentStorageType,
      estimatedItems: undefined // This would require an async call to list()
    };
  }
 
  /**
   * Estimate migration size
   */
  async estimateMigrationSize(): Promise<{
    itemCount: number;
    totalSize: number;
    estimatedTime: number;
  }> {
    const paths = await this.currentStorageProvider.list();
    let totalSize = 0;
 
    // Sample first 10 items to estimate average size
    const sampleSize = Math.min(10, paths.length);
    let sampleTotalSize = 0;
 
    for (let i = 0; i < sampleSize; i++) {
      try {
        const data = await this.currentStorageProvider.read(paths[i]);
        sampleTotalSize += data.length;
      } catch {
        // Skip items that fail to read
      }
    }
 
    // Estimate total size based on sample
    const averageSize = sampleSize > 0 ? sampleTotalSize / sampleSize : 0;
    totalSize = Math.round(averageSize * paths.length);
 
    // Estimate time (assuming 1MB/s upload speed)
    const estimatedTime = Math.round(totalSize / (1024 * 1024));
 
    return {
      itemCount: paths.length,
      totalSize,
      estimatedTime
    };
  }
 
  /**
   * Update migration progress
   */
  private updateProgress(update: Partial<MigrationProgress>): void {
    this.progressSubject.next({
      ...this.progressSubject.value,
      ...update
    });
  }
 
  /**
   * Reset migration state
   */
  reset(): void {
    this.progressSubject.next({
      totalItems: 0,
      processedItems: 0,
      successfulItems: 0,
      failedItems: 0,
      status: 'idle',
      errors: []
    });
  }
 
  /**
   * Check if migration is running
   */
  isMigrationRunning(): boolean {
    return this.isRunning;
  }
}