All files / app/core/services/ipfs ipfs-upload-queue.service.ts

97.59% Statements 81/83
84.61% Branches 11/13
95.65% Functions 22/23
97.53% Lines 79/81

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                                                    1x 15x 15x 15x               15x 15x 15x 15x   15x 15x 15x   15x           4x 4x 2x               20x 20x                 20x 20x 20x 19x     20x             3x 1x             2x 2x 1x 1x               1x 3x 3x     1x             1x 1x 1x 1x 1x     1x 1x                 4x       29x 2x     27x 42x     27x 9x     18x 18x       18x 18x 18x 18x 18x 18x     18x 78x 69x 69x       18x   16x   16x 16x 16x 16x     2x 2x 2x   18x 18x     18x         59x 59x   59x   110x 110x 110x 110x     59x       20x    
import { Injectable } from '@angular/core';
import { Subject, BehaviorSubject } from 'rxjs';
import { IPFSStorageService } from './ipfs-storage.service';
 
export interface UploadQueueItem {
  id: string;
  path: string;
  data: Uint8Array;
  status: 'pending' | 'uploading' | 'completed' | 'failed';
  progress: number;
  cid?: string;
  error?: string;
  timestamp: Date;
}
 
export interface UploadQueueStatus {
  total: number;
  pending: number;
  uploading: number;
  completed: number;
  failed: number;
}
 
@Injectable({
  providedIn: 'root'
})
export class IPFSUploadQueueService {
  private queue: Map<string, UploadQueueItem> = new Map();
  private queueSubject = new BehaviorSubject<UploadQueueItem[]>([]);
  private statusSubject = new BehaviorSubject<UploadQueueStatus>({
    total: 0,
    pending: 0,
    uploading: 0,
    completed: 0,
    failed: 0
  });
  
  private uploadProgressSubject = new Subject<UploadQueueItem>();
  private maxConcurrentUploads = 3;
  private activeUploads = 0;
  private autoProcess = true;
  
  queue$ = this.queueSubject.asObservable();
  status$ = this.statusSubject.asObservable();
  uploadProgress$ = this.uploadProgressSubject.asObservable();
 
  constructor(private ipfsStorage: IPFSStorageService) {}
 
  /**
   * Enable or disable automatic processing (useful for testing)
   */
  setAutoProcess(enabled: boolean): void {
    this.autoProcess = enabled;
    if (enabled) {
      this.processQueue();
    }
  }
 
  /**
   * Add a file to the upload queue
   */
  addToQueue(path: string, data: Uint8Array): string {
    const id = this.generateId();
    const item: UploadQueueItem = {
      id,
      path,
      data,
      status: 'pending',
      progress: 0,
      timestamp: new Date()
    };
    
    this.queue.set(id, item);
    this.updateQueueState();
    if (this.autoProcess) {
      this.processQueue();
    }
    
    return id;
  }
 
  /**
   * Add multiple files to the queue
   */
  addMultipleToQueue(files: Array<{ path: string; data: Uint8Array }>): string[] {
    const ids = files.map(file => this.addToQueue(file.path, file.data));
    return ids;
  }
 
  /**
   * Cancel an upload
   */
  cancelUpload(id: string): void {
    const item = this.queue.get(id);
    if (item && item.status === 'pending') {
      this.queue.delete(id);
      this.updateQueueState();
    }
  }
 
  /**
   * Clear completed uploads from the queue
   */
  clearCompleted(): void {
    Array.from(this.queue.entries()).forEach(([id, item]) => {
      if (item.status === 'completed') {
        this.queue.delete(id);
      }
    });
    this.updateQueueState();
  }
 
  /**
   * Retry failed uploads
   */
  retryFailed(): void {
    Array.from(this.queue.values()).forEach(item => {
      if (item.status === 'failed') {
        item.status = 'pending';
        item.progress = 0;
        delete item.error;
      }
    });
    this.updateQueueState();
    Iif (this.autoProcess) {
      this.processQueue();
    }
  }
 
  /**
   * Get upload item by ID
   */
  getUpload(id: string): UploadQueueItem | undefined {
    return this.queue.get(id);
  }
 
  private async processQueue(): Promise<void> {
    if (this.activeUploads >= this.maxConcurrentUploads) {
      return;
    }
 
    const pendingItems = Array.from(this.queue.values())
      .filter(item => item.status === 'pending')
      .sort((a, b) => a.timestamp.getTime() - b.timestamp.getTime());
 
    if (pendingItems.length === 0) {
      return;
    }
 
    const item = pendingItems[0];
    await this.uploadItem(item);
  }
 
  private async uploadItem(item: UploadQueueItem): Promise<void> {
    try {
      this.activeUploads++;
      item.status = 'uploading';
      item.progress = 0;
      this.updateQueueState();
      this.uploadProgressSubject.next(item);
 
      // Simulate progress updates
      const progressInterval = setInterval(() => {
        if (item.progress < 90) {
          item.progress += Math.random() * 20;
          this.uploadProgressSubject.next(item);
        }
      }, 500);
 
      await this.ipfsStorage.write(item.path, item.data);
      
      clearInterval(progressInterval);
      
      item.status = 'completed';
      item.progress = 100;
      item.cid = this.ipfsStorage.getCidForPath(item.path);
      this.uploadProgressSubject.next(item);
      
    } catch (error) {
      item.status = 'failed';
      item.error = error instanceof Error ? error.message : 'Upload failed';
      this.uploadProgressSubject.next(item);
    } finally {
      this.activeUploads--;
      this.updateQueueState();
      
      // Process next item in queue
      setTimeout(() => this.processQueue(), 100);
    }
  }
 
  private updateQueueState(): void {
    const items = Array.from(this.queue.values());
    this.queueSubject.next(items);
    
    const status: UploadQueueStatus = {
      total: items.length,
      pending: items.filter(i => i.status === 'pending').length,
      uploading: items.filter(i => i.status === 'uploading').length,
      completed: items.filter(i => i.status === 'completed').length,
      failed: items.filter(i => i.status === 'failed').length
    };
    
    this.statusSubject.next(status);
  }
 
  private generateId(): string {
    return `upload-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
  }
}