All files / agent/src/config loader.ts

97.24% Statements 282/290
94.02% Branches 63/67
100% Functions 9/9
97.24% Lines 282/290

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 2901x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 35x 35x 35x 35x 35x 35x 35x 35x 3x 3x 3x 3x 3x 15x 15x 15x 15x 15x 15x 5x 5x 15x 15x 15x 15x 15x 15x 15x 15x 1x 1x 1x 14x 14x 15x 3x 3x 3x 3x 3x 15x 55x 155x 155x 155x 155x 6x 6x 6x 6x 6x 6x 155x 1x 1x 155x 50x 10x 10x 10x 15x 3x 3x 3x 3x 3x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 1x 1x 1x 15x 15x       15x 15x       15x 15x 15x 1x 1x 15x 15x 1x 1x 15x 15x 15x 2x 2x 15x 15x 15x 2x 2x 2x 2x 2x 2x 1x 1x 1x 2x 1x 1x 1x 2x 2x 15x 15x 15x 15x 15x 1x 1x 1x 1x 1x 1x 1x 1x     1x 1x 1x 1x 1x 1x 1x 1x 1x 15x 15x 15x 1x 1x 1x 1x 1x 1x 1x 1x 15x 15x 15x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 15x 15x 15x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 20x 20x 20x 74x 74x 7x 7x 74x 67x 67x 74x 74x 20x 20x 20x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 1x 1x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 4x 4x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 4x 1x 1x 1x 1x 1x 4x 1x 1x 1x 1x 1x 20x 49x 121x 121x 13x 13x 121x 36x 7x 20x 1x
/**
 * Configuration Loader
 * 
 * Loads and merges configuration from files and environment variables
 * Requirements: 1.1, 1.2
 */
 
import * as fs from 'fs';
import * as path from 'path';
import * as os from 'os';
import { AgentConfig, DEFAULT_CONFIG, EnvironmentOverrides, AcceptanceRules, ResourceGovernance, ExecutionConfig, CacheConfig } from './types.js';
import { ConfigValidator } from './validation.js';
 
export class ConfigLoader {
  private static readonly CONFIG_FILE_NAMES = [
    'buildhive-agent.json',
    'buildhive-agent.config.json',
    '.buildhive-agent.json'
  ];
 
  private static getConfigSearchPaths(): string[] {
    return [
      process.cwd(),
      path.join(process.cwd(), 'config'),
      path.join(process.cwd(), '.config'),
      path.join(os.homedir(), '.buildhive'),
      '/etc/buildhive'
    ];
  }
 
  /**
   * Loads configuration from file and environment variables
   */
  static async load(): Promise<AgentConfig> {
    // Start with default configuration
    let config: Partial<AgentConfig> = { ...DEFAULT_CONFIG };
 
    // Load from configuration file
    const fileConfig = this.loadFromFile();
    if (fileConfig) {
      config = this.mergeConfigs(config, fileConfig);
    }
 
    // Apply environment variable overrides
    const envConfig = this.loadFromEnvironment();
    config = this.mergeConfigs(config, envConfig);
 
    // Validate the final configuration
    const validation = ConfigValidator.validate(config);
    if (!validation.isValid) {
      const errorMessages = validation.errors.map(err => `${err.field}: ${err.message}`).join('\n');
      throw new Error(`Configuration validation failed:\n${errorMessages}`);
    }
 
    return config as AgentConfig;
  }
 
  /**
   * Loads configuration from the first found configuration file
   */
  private static loadFromFile(): Partial<AgentConfig> | null {
    for (const searchPath of this.getConfigSearchPaths()) {
      for (const fileName of this.CONFIG_FILE_NAMES) {
        const filePath = path.join(searchPath, fileName);
        
        try {
          if (fs.existsSync(filePath)) {
            const fileContent = fs.readFileSync(filePath, 'utf8');
            const parsedConfig = JSON.parse(fileContent);
            
            console.log(`Loaded configuration from: ${filePath}`);
            return parsedConfig;
          }
        } catch (error) {
          console.warn(`Failed to load configuration from ${filePath}:`, error);
        }
      }
    }
 
    console.log('No configuration file found, using defaults and environment variables');
    return null;
  }
 
  /**
   * Loads configuration overrides from environment variables
   */
  private static loadFromEnvironment(): Partial<AgentConfig> {
    const env = process.env as EnvironmentOverrides;
    const config: Partial<AgentConfig> = {};
 
    // String values
    if (env.BUILDHIVE_PLATFORM_URL) config.platformUrl = env.BUILDHIVE_PLATFORM_URL;
    if (env.BUILDHIVE_API_KEY) config.apiKey = env.BUILDHIVE_API_KEY;
    if (env.BUILDHIVE_AGENT_ID) config.agentId = env.BUILDHIVE_AGENT_ID;
    if (env.BUILDHIVE_AGENT_NAME) config.name = env.BUILDHIVE_AGENT_NAME;
    if (env.BUILDHIVE_LOG_LEVEL) config.logLevel = env.BUILDHIVE_LOG_LEVEL as any;
 
    // Numeric values
    if (env.BUILDHIVE_MAX_CONCURRENT_JOBS) {
      const value = parseInt(env.BUILDHIVE_MAX_CONCURRENT_JOBS, 10);
      if (!isNaN(value)) config.maxConcurrentJobs = value;
    }
 
    if (env.BUILDHIVE_HEARTBEAT_INTERVAL) {
      const value = parseInt(env.BUILDHIVE_HEARTBEAT_INTERVAL, 10);
      if (!isNaN(value)) config.heartbeatInterval = value;
    }
 
    if (env.BUILDHIVE_JOB_TIMEOUT_MINUTES) {
      const value = parseInt(env.BUILDHIVE_JOB_TIMEOUT_MINUTES, 10);
      if (!isNaN(value)) config.jobTimeoutMinutes = value;
    }
 
    // Boolean values
    if (env.BUILDHIVE_ENABLE_METRICS) {
      config.enableMetrics = env.BUILDHIVE_ENABLE_METRICS.toLowerCase() === 'true';
    }
 
    if (env.BUILDHIVE_ENABLE_AUTO_UPDATES) {
      config.enableAutoUpdates = env.BUILDHIVE_ENABLE_AUTO_UPDATES.toLowerCase() === 'true';
    }
 
    // Array values
    if (env.BUILDHIVE_TAGS) {
      config.tags = env.BUILDHIVE_TAGS.split(',').map(tag => tag.trim()).filter(tag => tag.length > 0);
    }
 
    // Resource governance overrides
    if (env.BUILDHIVE_MAX_CPU_PERCENT || env.BUILDHIVE_MAX_MEMORY_PERCENT || env.BUILDHIVE_RESERVED_DISK_GB) {
      const rg: Partial<ResourceGovernance> = {};
      if (env.BUILDHIVE_MAX_CPU_PERCENT) {
        const v = parseInt(env.BUILDHIVE_MAX_CPU_PERCENT, 10);
        if (!isNaN(v)) rg.maxCpuPercent = v;
      }
      if (env.BUILDHIVE_MAX_MEMORY_PERCENT) {
        const v = parseInt(env.BUILDHIVE_MAX_MEMORY_PERCENT, 10);
        if (!isNaN(v)) rg.maxMemoryPercent = v;
      }
      if (env.BUILDHIVE_RESERVED_DISK_GB) {
        const v = parseFloat(env.BUILDHIVE_RESERVED_DISK_GB);
        if (!isNaN(v)) rg.reservedDiskGB = v;
      }
      config.resourceGovernance = { ...DEFAULT_CONFIG.resourceGovernance!, ...rg };
    }
 
    // Acceptance rules overrides
    if (env.BUILDHIVE_ALLOWED_RECIPES || env.BUILDHIVE_BLOCKED_RECIPES ||
        env.BUILDHIVE_ALLOWED_REPOSITORIES || env.BUILDHIVE_MAX_JOB_DURATION_MINUTES ||
        env.BUILDHIVE_REQUIRE_DOCKER) {
      const ar: Partial<AcceptanceRules> = {};
      if (env.BUILDHIVE_ALLOWED_RECIPES) {
        ar.allowedRecipes = env.BUILDHIVE_ALLOWED_RECIPES.split(',').map(s => s.trim()).filter(s => s.length > 0);
      }
      if (env.BUILDHIVE_BLOCKED_RECIPES) {
        ar.blockedRecipes = env.BUILDHIVE_BLOCKED_RECIPES.split(',').map(s => s.trim()).filter(s => s.length > 0);
      }
      if (env.BUILDHIVE_ALLOWED_REPOSITORIES) {
        ar.allowedRepositories = env.BUILDHIVE_ALLOWED_REPOSITORIES.split(',').map(s => s.trim()).filter(s => s.length > 0);
      }
      if (env.BUILDHIVE_MAX_JOB_DURATION_MINUTES) {
        const v = parseInt(env.BUILDHIVE_MAX_JOB_DURATION_MINUTES, 10);
        if (!isNaN(v)) ar.maxJobDurationMinutes = v;
      }
      if (env.BUILDHIVE_REQUIRE_DOCKER) {
        ar.requireDocker = env.BUILDHIVE_REQUIRE_DOCKER.toLowerCase() === 'true';
      }
      config.acceptanceRules = { ...DEFAULT_CONFIG.acceptanceRules!, ...ar };
    }
 
    // Execution mode override
    if (env.BUILDHIVE_EXECUTION_MODE) {
      const mode = env.BUILDHIVE_EXECUTION_MODE as 'docker' | 'native' | 'auto';
      if (['docker', 'native', 'auto'].includes(mode)) {
        config.executionConfig = {
          ...DEFAULT_CONFIG.executionConfig!,
          defaultMode: mode
        };
      }
    }
 
    // Cache config overrides
    if (env.BUILDHIVE_CACHE_ENABLED || env.BUILDHIVE_CACHE_DIRECTORY || env.BUILDHIVE_CACHE_MAX_SIZE_GB) {
      const cc: Partial<CacheConfig> = {};
      if (env.BUILDHIVE_CACHE_ENABLED) {
        cc.enabled = env.BUILDHIVE_CACHE_ENABLED.toLowerCase() === 'true';
      }
      if (env.BUILDHIVE_CACHE_DIRECTORY) {
        cc.directory = env.BUILDHIVE_CACHE_DIRECTORY;
      }
      if (env.BUILDHIVE_CACHE_MAX_SIZE_GB) {
        const v = parseFloat(env.BUILDHIVE_CACHE_MAX_SIZE_GB);
        if (!isNaN(v)) cc.maxSizeGB = v;
      }
      config.cacheConfig = { ...DEFAULT_CONFIG.cacheConfig!, ...cc };
    }
 
    return config;
  }
 
  /**
   * Merges two configuration objects, with the second taking precedence
   */
  /** Keys that should be deep-merged (object-type sub-configs) */
  private static readonly DEEP_MERGE_KEYS: Set<string> = new Set([
    'dockerConfig',
    'securityConfig',
    'storageConfig',
    'acceptanceRules',
    'resourceGovernance',
    'executionConfig',
    'cacheConfig'
  ]);
 
  private static mergeConfigs(base: Partial<AgentConfig>, override: Partial<AgentConfig>): Partial<AgentConfig> {
    const merged = { ...base };
 
    for (const [key, value] of Object.entries(override)) {
      if (value !== undefined && value !== null) {
        if (this.DEEP_MERGE_KEYS.has(key) && typeof value === 'object' && typeof (merged as any)[key] === 'object') {
          // Deep merge nested configuration objects
          (merged as any)[key] = { ...(merged as any)[key], ...value };
        } else {
          (merged as any)[key] = value;
        }
      }
    }
 
    return merged;
  }
 
  /**
   * Saves configuration to a file
   */
  static async save(config: AgentConfig, filePath?: string): Promise<void> {
    const targetPath = filePath || path.join(process.cwd(), 'buildhive-agent.json');
    
    // Create directory if it doesn't exist
    const dir = path.dirname(targetPath);
    if (!fs.existsSync(dir)) {
      fs.mkdirSync(dir, { recursive: true });
    }
 
    // Write configuration file
    const configJson = JSON.stringify(config, null, 2);
    fs.writeFileSync(targetPath, configJson, 'utf8');
    
    console.log(`Configuration saved to: ${targetPath}`);
  }
 
  /**
   * Validates a configuration file without loading it
   */
  static validateFile(filePath: string): { isValid: boolean; errors: string[] } {
    try {
      if (!fs.existsSync(filePath)) {
        return { isValid: false, errors: ['Configuration file does not exist'] };
      }
 
      const fileContent = fs.readFileSync(filePath, 'utf8');
      const config = JSON.parse(fileContent);
      
      const validation = ConfigValidator.validate(config);
      
      return {
        isValid: validation.isValid,
        errors: validation.errors.map(err => `${err.field}: ${err.message}`)
      };
    } catch (error) {
      return {
        isValid: false,
        errors: [`Failed to validate configuration file: ${error}`]
      };
    }
  }
 
  /**
   * Gets the path of the currently loaded configuration file
   */
  static findConfigFile(): string | null {
    for (const searchPath of this.getConfigSearchPaths()) {
      for (const fileName of this.CONFIG_FILE_NAMES) {
        const filePath = path.join(searchPath, fileName);
        if (fs.existsSync(filePath)) {
          return filePath;
        }
      }
    }
    return null;
  }
}