All files / app/core/services/helia helia-storage.service.ts

57.93% Statements 84/145
61.9% Branches 13/21
55% Functions 22/40
59.05% Lines 75/127

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                            1x     39x         39x 39x     39x             46x   29x         29x 29x                                                                                                             3x 3x   2x   2x     1x   1x   1x 1x         2x 2x   2x   2x 2x 1x       1x 1x                                 2x 2x         2x   2x 2x       1x     1x             2x 2x   1x 1x 1x 1x   1x 1x           2x   1x 1x 1x   1x           1x 1x         3x   2x 2x 2x 2x   2x 2x 2x   2x         2x   1x 1x 1x 1x   1x 1x                       1x   1x       1x                     3x 3x 1x   2x                                                                                                           43x 29x 2x         43x 27x      
import { Injectable, OnDestroy, Inject } from '@angular/core';
import { createHelia, type Helia } from 'helia';
import { unixfs, type UnixFS } from '@helia/unixfs';
import { IDBBlockstore } from 'blockstore-idb';
import { IDBDatastore } from 'datastore-idb';
import itAll from 'it-all';
import { IStorageProvider } from '../../domain/interfaces/storage.interface';
import { IPFSShareLinkService } from '../ipfs/ipfs-share-link.service';
import { IPFS_CONFIG } from '../ipfs/ipfs-storage.service';
import { IPFSConfig } from '../../domain/interfaces/ipfs.interface';
 
@Injectable({
  providedIn: 'root'
})
export class HeliaStorageService implements IStorageProvider, OnDestroy {
  private helia?: Helia;
  private fs?: UnixFS;
  private initialized = false;
  private initPromise?: Promise<void>;
  
  // Path to CID mapping stored in IndexedDB
  private pathToCidStore?: IDBDatabase;
  private readonly PATH_CID_DB = 'helia-path-mappings';
  private readonly PATH_CID_STORE = 'pathCidMappings';
 
  constructor(
    private shareLinkService: IPFSShareLinkService,
    @Inject(IPFS_CONFIG) _config: IPFSConfig
  ) {
    // Config is injected for potential future use
  }
 
  async ensureInitialized(): Promise<void> {
    if (this.initialized) return;
    
    Iif (this.initPromise) {
      await this.initPromise;
      return;
    }
 
    this.initPromise = this.initialize();
    await this.initPromise;
  }
 
  private async initialize(): Promise<void> {
    try {
      // Create separate IndexedDB stores for Helia
      const blockstore = new IDBBlockstore('helia-blocks');
      const datastore = new IDBDatastore('helia-data');
 
      // Open both stores
      await blockstore.open();
      await datastore.open();
 
      // Create Helia instance
      this.helia = await createHelia({
        blockstore,
        datastore
        // libp2p is optional and defaults to creating a new node
      });
 
      // Create UnixFS instance
      this.fs = unixfs(this.helia);
 
      // Initialize path-to-CID mapping database
      await this.initializePathCidStore();
 
      this.initialized = true;
    } catch (error) {
      console.error('Failed to initialize Helia:', error);
      throw new Error('Helia initialization failed');
    }
  }
 
  private async initializePathCidStore(): Promise<void> {
    return new Promise((resolve, reject) => {
      const request = indexedDB.open(this.PATH_CID_DB, 1);
      
      request.onerror = () => reject(request.error);
      request.onsuccess = () => {
        this.pathToCidStore = request.result;
        resolve();
      };
      
      request.onupgradeneeded = (event) => {
        const db = (event.target as IDBOpenDBRequest).result;
        Iif (!db.objectStoreNames.contains(this.PATH_CID_STORE)) {
          const store = db.createObjectStore(this.PATH_CID_STORE, { keyPath: 'path' });
          store.createIndex('cid', 'cid', { unique: false });
          store.createIndex('timestamp', 'timestamp', { unique: false });
        }
      };
    });
  }
 
  async write(path: string, data: Uint8Array): Promise<void> {
    await this.ensureInitialized();
    if (!this.fs) throw new Error('Helia not initialized');
 
    try {
      // Add content to Helia
      const cid = await this.fs.addBytes(data);
      
      // Store path-to-CID mapping
      await this.savePathCidMapping(path, cid.toString());
      
      console.log(`Stored ${path} in Helia with CID: ${cid}`);
    } catch (error) {
      console.error('Failed to write to Helia:', error);
      throw error;
    }
  }
 
  async read(path: string): Promise<Uint8Array> {
    await this.ensureInitialized();
    Iif (!this.fs) throw new Error('Helia not initialized');
 
    try {
      // Get CID from path mapping
      const cidString = await this.getCidForPathPrivate(path);
      if (!cidString) {
        throw new Error(`No content found for path: ${path}`);
      }
 
      // Convert string back to CID
      const { CID } = await import('multiformats/cid');
      const cid = CID.parse(cidString);
 
      // Read content from Helia
      const chunks = await itAll(this.fs.cat(cid));
      
      // Concatenate chunks into single Uint8Array
      const totalLength = chunks.reduce((sum: number, chunk: Uint8Array) => sum + chunk.length, 0);
      const result = new Uint8Array(totalLength);
      let offset = 0;
      
      for (const chunk of chunks) {
        result.set(chunk, offset);
        offset += chunk.length;
      }
      
      return result;
    } catch (error) {
      console.error('Failed to read from Helia:', error);
      throw error;
    }
  }
 
  async exists(path: string): Promise<boolean> {
    await this.ensureInitialized();
    
    const cidString = await this.getCidForPathPrivate(path);
    return cidString !== null;
  }
 
  async delete(path: string): Promise<void> {
    await this.ensureInitialized();
    
    // Remove path mapping
    await this.deletePathCidMapping(path);
    
    // Note: We don't delete the actual block from Helia
    // as it might be referenced by other paths or needed for deduplication
  }
 
  async list(): Promise<string[]> {
    await this.ensureInitialized();
    if (!this.pathToCidStore) return [];
 
    return new Promise((resolve, reject) => {
      const transaction = this.pathToCidStore!.transaction([this.PATH_CID_STORE], 'readonly');
      const store = transaction.objectStore(this.PATH_CID_STORE);
      const request = store.getAllKeys();
      
      request.onsuccess = () => resolve(request.result as string[]);
      request.onerror = () => reject(request.error);
    });
  }
 
  // Path-to-CID mapping methods
  private async savePathCidMapping(path: string, cid: string): Promise<void> {
    if (!this.pathToCidStore) throw new Error('Path-CID store not initialized');
 
    return new Promise((resolve, reject) => {
      const transaction = this.pathToCidStore!.transaction([this.PATH_CID_STORE], 'readwrite');
      const store = transaction.objectStore(this.PATH_CID_STORE);
      
      const request = store.put({
        path,
        cid,
        timestamp: new Date().toISOString()
      });
      
      request.onsuccess = () => resolve();
      request.onerror = () => reject(request.error);
    });
  }
 
  private async getCidForPathPrivate(path: string): Promise<string | null> {
    if (!this.pathToCidStore) throw new Error('Path-CID store not initialized');
 
    return new Promise((resolve, reject) => {
      const transaction = this.pathToCidStore!.transaction([this.PATH_CID_STORE], 'readonly');
      const store = transaction.objectStore(this.PATH_CID_STORE);
      const request = store.get(path);
      
      request.onsuccess = () => {
        const result = request.result;
        resolve(result ? result.cid : null);
      };
      request.onerror = () => reject(request.error);
    });
  }
 
  private async deletePathCidMapping(path: string): Promise<void> {
    if (!this.pathToCidStore) throw new Error('Path-CID store not initialized');
 
    return new Promise((resolve, reject) => {
      const transaction = this.pathToCidStore!.transaction([this.PATH_CID_STORE], 'readwrite');
      const store = transaction.objectStore(this.PATH_CID_STORE);
      const request = store.delete(path);
      
      request.onsuccess = () => resolve();
      request.onerror = () => reject(request.error);
    });
  }
 
  /**
   * Get storage statistics
   */
  async getStats(): Promise<{
    blockCount: number;
    totalSize: number;
    pathCount: number;
  }> {
    await this.ensureInitialized();
    
    const pathCount = (await this.list()).length;
    
    // Note: Getting accurate block count and size from Helia/IDB is complex
    // This is a simplified version
    return {
      blockCount: 0, // Would need to query IDB blockstore
      totalSize: 0,  // Would need to sum all block sizes
      pathCount
    };
  }
 
  /**
   * Check if Helia is healthy
   */
  async isHealthy(): Promise<boolean> {
    try {
      await this.ensureInitialized();
      return this.initialized && this.helia !== undefined;
    } catch {
      return false;
    }
  }
 
  /**
   * Generate a shareable link for content
   */
  async generateShareLink(path: string, filename?: string): Promise<string | null> {
    const cid = await this.getCidForPath(path);
    Iif (!cid) {
      return null;
    }
    
    return this.shareLinkService.generateShareLink(cid, { filename });
  }
 
  /**
   * Generate multiple share links for different gateways
   */
  async generateMultipleShareLinks(path: string, filename?: string): Promise<string[]> {
    const cid = await this.getCidForPath(path);
    Iif (!cid) {
      return [];
    }
    
    return this.shareLinkService.generateMultipleShareLinks(cid, { filename });
  }
 
  /**
   * Get CID for a given path
   */
  async getCidForPath(path: string): Promise<string | null> {
    await this.ensureInitialized();
    return await this.getCidForPathInternal(path);
  }
 
  private async getCidForPathInternal(path: string): Promise<string | null> {
    Iif (!this.pathToCidStore) throw new Error('Path-CID store not initialized');
 
    return new Promise((resolve, reject) => {
      const transaction = this.pathToCidStore!.transaction([this.PATH_CID_STORE], 'readonly');
      const store = transaction.objectStore(this.PATH_CID_STORE);
      const request = store.get(path);
      
      request.onsuccess = () => {
        const result = request.result;
        resolve(result ? result.cid : null);
      };
      request.onerror = () => reject(request.error);
    });
  }
 
  ngOnDestroy(): void {
    // Close Helia node when service is destroyed
    if (this.helia) {
      this.helia.stop().catch(error => {
        console.error('Error stopping Helia:', error);
      });
    }
    
    // Close path-CID database
    if (this.pathToCidStore) {
      this.pathToCidStore.close();
    }
  }
}