All files ScanCommand.js

91.66% Statements 165/180
73.77% Branches 45/61
100% Functions 4/4
91.62% Lines 164/179

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 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524                                        25x 25x                 19x   19x   19x     17x     17x   17x   17x   17x 17x 17x 17x 17x     17x 17x       17x         17x 17x 17x     22x   22x           21x   21x     21x             16x 16x 1x 1x 1x       16x 16x             16x 21x 21x               21x           21x 21x 21x 21x     16x 16x   16x 16x 16x 16x     16x     16x     16x 16x 16x 16x 16x 21x     16x   21x       3x 3x                                     17x 17x   17x   15x   18x   18x 18x         2x 2x   2x 2x     2x     2x 3x 4x   2x     2x     2x 2x 2x   2x     2x                                 2x                         5x 5x   5x   3x 3x     2x 2x   2x 4x 3x 3x           3x       2x               1x 1x   1x 1x 1x           1x             1x                           21x 21x   21x 21x 21x 21x 21x     21x   21x   21x               21x   9x 9x     9x 1x 1x       8x 8x             8x             8x 8x 8x     8x       8x 8x 8x       8x 2x 2x 2x               21x 4x 4x     21x   21x                         6x 6x       5x   1x 1x                   8x 8x     8x     8x 8x   8x                                 9x   9x   7x         7x 7x 1x       8x               21x                                 21x                 21x 21x 21x                 16x   4x 4x 4x   4x          
import cliProgress from 'cli-progress';
import { globbyStream } from 'globby';
import path from 'path';
import { Transform } from 'stream';
import { pipeline } from 'stream/promises';
 
import logger from '../services/LoggingService.js';
 
import appConfig from '../config/config.js';
import ErrorHandler from '../errors/ErrorHandler.js';
import { ConfigurationError } from '../errors/ErrorTypes.js';
import FileOperations from '../utils/FileOperations.js';
import PathNormalizer from '../utils/PathNormalizer.js';
 
/**
 * Scan Command Handler
 * Handles the optimized arela scan command with streaming support
 */
export class ScanCommand {
  constructor() {
    this.errorHandler = new ErrorHandler(logger);
    this.scanApiService = null; // Will be initialized in execute
  }
 
  /**
   * Execute the scan command
   * @param {Object} options - Command options
   * @param {boolean} options.countFirst - Count files first for percentage-based progress
   */
  async execute(options = {}) {
    const startTime = Date.now();
 
    try {
      // Validate scan configuration
      appConfig.validateScanConfig();
 
      // Import ScanApiService dynamically
      const { default: ScanApiService } = await import(
        '../services/ScanApiService.js'
      );
      this.scanApiService = new ScanApiService();
 
      const scanConfig = appConfig.getScanConfig();
      // Ensure basePath is absolute for scan operations
      const basePath = PathNormalizer.toAbsolutePath(appConfig.getBasePath());
 
      logger.info('šŸ” Starting arela scan command');
      logger.info(`šŸ“¦ Company: ${scanConfig.companySlug}`);
      logger.info(`šŸ–„ļø  Server: ${scanConfig.serverId}`);
      logger.info(`šŸ“‚ Base Path: ${basePath}`);
      logger.info(`šŸ“Š Directory Level: ${scanConfig.directoryLevel}`);
 
      // Step 1: Discover directories at specified level
      logger.info('\nšŸ” Discovering directories...');
      const directories = await this.#discoverDirectories(
        basePath,
        scanConfig.directoryLevel,
      );
      logger.info(
        `šŸ“ Found ${directories.length} director${directories.length === 1 ? 'y' : 'ies'} to scan`,
      );
 
      // Step 2: Register instances for each directory
      logger.info('\nšŸ“ Registering scan instances...');
      const registrations = [];
      for (const dir of directories) {
        // dir.path is already absolute from #discoverDirectories
        // Use the absolute path as basePathLabel (simplifies everything!)
        const absolutePath = dir.path;
 
        const registration = await this.scanApiService.registerInstance({
          companySlug: scanConfig.companySlug,
          serverId: scanConfig.serverId,
          basePathFull: absolutePath,
        });
 
        registrations.push({ ...registration, directory: dir });
 
        Iif (registration.existed) {
          logger.info(`  āœ“ ${dir.label || 'root'}: ${registration.tableName}`);
        } else {
          logger.success(
            `  āœ“ ${dir.label || 'root'}: ${registration.tableName} (new)`,
          );
        }
      }
 
      // Optional: Count files first for percentage-based progress
      let totalFiles = null;
      if (options.countFirst) {
        logger.info('\nšŸ”¢ Counting files...');
        totalFiles = await this.#countFiles(basePath, scanConfig);
        logger.info(`šŸ“Š Found ${totalFiles.toLocaleString()} files to scan`);
      }
 
      // Step 3: Stream files and upload stats for each directory
      logger.info('\nšŸš€ Starting file scan...');
      let totalStats = {
        filesScanned: 0,
        filesInserted: 0,
        filesSkipped: 0,
        totalSize: 0,
      };
 
      for (const reg of registrations) {
        logger.info(`\nšŸ“‚ Scanning: ${reg.directory.label || 'root'}`);
        const stats = await this.#streamScanDirectory(
          reg.directory.path,
          scanConfig,
          reg.tableName,
          null, // Don't use percentage for individual directories
        );
 
        // Step 4: Complete scan for this directory
        await this.scanApiService.completeScan({
          tableName: reg.tableName,
          totalFiles: stats.filesScanned,
          totalSizeBytes: stats.totalSize,
        });
 
        totalStats.filesScanned += stats.filesScanned;
        totalStats.filesInserted += stats.filesInserted;
        totalStats.filesSkipped += stats.filesSkipped;
        totalStats.totalSize += stats.totalSize;
      }
 
      const duration = ((Date.now() - startTime) / 1000).toFixed(2);
      const filesPerSec = (totalStats.filesScanned / duration).toFixed(2);
 
      logger.success('\nāœ… Scan completed successfully!');
      logger.info(`\nšŸ“Š Scan Statistics:`);
      logger.info(`   Directories scanned: ${registrations.length}`);
      logger.info(
        `   Files scanned: ${totalStats.filesScanned.toLocaleString()}`,
      );
      logger.info(
        `   Files inserted: ${totalStats.filesInserted.toLocaleString()}`,
      );
      logger.info(
        `   Files skipped: ${totalStats.filesSkipped.toLocaleString()} (excluded patterns)`,
      );
      logger.info(`   Total size: ${this.#formatBytes(totalStats.totalSize)}`);
      logger.info(`   Duration: ${duration}s`);
      logger.info(`   Throughput: ${filesPerSec} files/sec`);
      logger.info(`\nšŸ“‹ Tables created:`);
      for (const reg of registrations) {
        logger.info(`   - ${reg.tableName}`);
      }
 
      return {
        success: true,
        tables: registrations.map((r) => r.tableName),
        stats: totalStats,
      };
    } catch (error) {
      this.errorHandler.handleError(error, 'scan');
      return {
        success: false,
        error: error.message,
        stats: {
          filesScanned: 0,
          filesInserted: 0,
          filesSkipped: 0,
          totalSize: 0,
        },
      };
    }
  }
 
  /**
   * Discover directories at specified level
   * @private
   */
  async #discoverDirectories(basePath, level) {
    // Get sources, defaults to ['.'] if not configured
    const sources = appConfig.getUploadSources();
    const isDefaultSource = sources.length === 1 && sources[0] === '.';
 
    if (level === 0) {
      // Level 0: Create one entry per source
      return sources.map((source) => {
        const sourcePath =
          source === '.' ? basePath : path.resolve(basePath, source);
        // Label is relative path for display purposes only
        const label = source === '.' ? '' : source;
        return { path: sourcePath, label };
      });
    }
 
    // For level > 0: First discover directories at the base path, then combine with sources
    const fs = await import('fs/promises');
    const directories = [];
 
    try {
      const fs = await import('fs/promises');
 
      // Step 1: Discover directories at the specified level from base path
      const levelDirs = await this.#getDirectoriesAtLevel(basePath, level, '');
 
      // Step 2: For each discovered directory, create entries for each source
      for (const levelDir of levelDirs) {
        for (const source of sources) {
          if (source === '.') {
            // Source is current directory, use discovered path as-is
            directories.push(levelDir);
          } else {
            // Append source to path
            const combinedPath = path.resolve(levelDir.path, source);
 
            // Only add if the combined path actually exists
            try {
              const stats = await fs.stat(combinedPath);
              if (stats.isDirectory()) {
                // Label for display
                const label = levelDir.label
                  ? `${levelDir.label}/${source}`
                  : source;
                directories.push({
                  path: combinedPath,
                  label,
                });
              } else E{
                logger.debug(`ā­ļø Skipping ${combinedPath} (not a directory)`);
              }
            } catch (error) {
              logger.debug(`ā­ļø Skipping ${combinedPath} (does not exist)`);
            }
          }
        }
      }
    } catch (error) {
      logger.warn(`āš ļø Could not discover directories: ${error.message}`);
    }
 
    return directories;
  }
 
  /**
   * Recursively get directories at specified level
   * @private
   */
  async #getDirectoriesAtLevel(
    basePath,
    targetLevel,
    currentPath,
    currentLevel = 0,
  ) {
    const fs = await import('fs/promises');
    const fullPath = path.join(basePath, currentPath);
 
    if (currentLevel === targetLevel) {
      // Label is the relative path for display
      const label = currentPath || '';
      return [{ path: fullPath, label }];
    }
 
    const directories = [];
    const entries = await fs.readdir(fullPath, { withFileTypes: true });
 
    for (const entry of entries) {
      if (entry.isDirectory()) {
        const subPath = path.join(currentPath, entry.name);
        const subDirs = await this.#getDirectoriesAtLevel(
          basePath,
          targetLevel,
          subPath,
          currentLevel + 1,
        );
        directories.push(...subDirs);
      }
    }
 
    return directories;
  }
 
  /**
   * Count files for percentage-based progress
   * @private
   */
  async #countFiles(basePath, scanConfig) {
    const sources = appConfig.getUploadSources();
    let totalCount = 0;
 
    for (const source of sources) {
      const sourcePath = path.resolve(basePath, source);
      const files = await globbyStream('**/*', {
        cwd: sourcePath,
        onlyFiles: true,
        absolute: true,
      });
 
      for await (const file of files) {
        if (!this.#shouldExcludeFile(file, scanConfig.excludePatterns)) {
          totalCount++;
        }
      }
    }
 
    return totalCount;
  }
 
  /**
   * Stream files from a single directory and upload stats in batches
   * @private
   */
  async #streamScanDirectory(
    dirPath,
    scanConfig,
    tableName,
    totalFiles = null,
  ) {
    // For directory-level scanning, we scan the directory directly
    const batchSize = scanConfig.batchSize || 2000;
    const scanTimestamp = new Date().toISOString();
 
    let filesScanned = 0;
    let filesInserted = 0;
    let filesSkipped = 0;
    let totalSize = 0;
    let currentBatch = [];
 
    // Create progress bar
    const progressBar = this.#createProgressBar(totalFiles);
 
    try {
      // Create stream with stats option
      const fileStream = globbyStream('**/*', {
        cwd: dirPath,
        onlyFiles: true,
        absolute: true,
        stats: true, // Get file stats during discovery
      });
 
      // Process each file from stream
      for await (const entry of fileStream) {
        // globby with stats:true returns {path, stats} objects
        const filePath = typeof entry === 'string' ? entry : entry.path;
        const stats = typeof entry === 'object' ? entry.stats : null;
 
        // Check if file should be excluded
        if (this.#shouldExcludeFile(filePath, scanConfig.excludePatterns)) {
          filesSkipped++;
          continue;
        }
 
        // Get file stats (use from globby or fetch manually)
        const fileStats = stats || FileOperations.getFileStats(filePath);
        Iif (!fileStats) {
          logger.debug(`āš ļø Could not read stats: ${filePath}`);
          filesSkipped++;
          continue;
        }
 
        // Normalize file record
        const record = this.#normalizeFileRecord(
          filePath,
          fileStats,
          dirPath,
          scanTimestamp,
        );
 
        currentBatch.push(record);
        filesScanned++;
        totalSize += record.sizeBytes;
 
        // Update progress
        Iif (totalFiles) {
          progressBar.update(filesScanned);
        } else {
          // Show throughput instead of percentage
          const elapsed = (Date.now() - progressBar.startTime) / 1000;
          const rate = (filesScanned / elapsed).toFixed(1);
          progressBar.update(filesScanned, { rate });
        }
 
        // Upload batch when full
        if (currentBatch.length >= batchSize) {
          const inserted = await this.#uploadBatch(tableName, currentBatch);
          filesInserted += inserted;
          currentBatch = [];
        }
      }
    } catch (error) {
      logger.error(`āŒ Error scanning directory: ${error.message}`);
    }
 
    // Upload remaining files
    if (currentBatch.length > 0) {
      const inserted = await this.#uploadBatch(tableName, currentBatch);
      filesInserted += inserted;
    }
 
    progressBar.stop();
 
    return {
      filesScanned,
      filesInserted,
      filesSkipped,
      totalSize,
    };
  }
 
  /**
   * Upload a batch of file records
   * @private
   */
  async #uploadBatch(tableName, records) {
    try {
      const result = await this.scanApiService.batchInsertStats(
        tableName,
        records,
      );
      return result.inserted;
    } catch (error) {
      logger.error(`āŒ Failed to upload batch: ${error.message}`);
      return 0;
    }
  }
 
  /**
   * Normalize file record for database insertion
   * Stores paths with forward slashes for consistency but keeps them absolute
   * @private
   */
  #normalizeFileRecord(filePath, fileStats, basePath, scanTimestamp) {
    const fileName = path.basename(filePath);
    const fileExtension = path.extname(filePath).toLowerCase().replace('.', '');
 
    // Normalize separators to forward slashes for consistency
    const directoryPath = PathNormalizer.normalizeSeparators(
      path.dirname(filePath),
    );
    const relativePath = PathNormalizer.getRelativePath(filePath, basePath);
    const absolutePath = PathNormalizer.normalizeSeparators(filePath);
 
    return {
      fileName,
      fileExtension,
      directoryPath,
      relativePath,
      absolutePath,
      sizeBytes: Number(fileStats.size),
      modifiedAt: fileStats.mtime.toISOString(),
      scanTimestamp,
    };
  }
 
  /**
   * Check if file should be excluded based on patterns
   * @private
   */
  #shouldExcludeFile(filePath, excludePatterns) {
    const fileName = path.basename(filePath);
 
    for (const pattern of excludePatterns) {
      // Convert glob pattern to regex
      const regexPattern = pattern
        .replace(/\./g, '\\.') // Escape dots
        .replace(/\*/g, '.*') // * to .*
        .replace(/\?/g, '.'); // ? to .
 
      const regex = new RegExp(`^${regexPattern}$`, 'i');
      if (regex.test(fileName)) {
        return true;
      }
    }
 
    return false;
  }
 
  /**
   * Create progress bar
   * @private
   */
  #createProgressBar(totalFiles) {
    Iif (totalFiles) {
      // Percentage-based progress
      const bar = new cliProgress.SingleBar(
        {
          format:
            'šŸ“Š Scanning |{bar}| {percentage}% | {value}/{total} files | {rate} files/sec',
          barCompleteChar: '\u2588',
          barIncompleteChar: '\u2591',
          hideCursor: true,
        },
        cliProgress.Presets.shades_classic,
      );
      bar.start(totalFiles, 0, { rate: '0.0' });
      bar.startTime = Date.now();
      return bar;
    } else {
      // Throughput-based progress
      const bar = new cliProgress.SingleBar(
        {
          format: 'šŸ“Š Scanning | {value} files | {rate} files/sec',
          hideCursor: true,
          clearOnComplete: false,
          stopOnComplete: false,
        },
        cliProgress.Presets.legacy,
      );
      bar.start(0, 0, { rate: '0.0' });
      bar.startTime = Date.now();
      return bar;
    }
  }
 
  /**
   * Format bytes to human-readable size
   * @private
   */
  #formatBytes(bytes) {
    if (bytes === 0) return '0 Bytes';
 
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
 
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  }
}
 
export default new ScanCommand();