All files / src/config loadOptionalConfig.ts

94.56% Statements 87/92
82.14% Branches 23/28
100% Functions 19/19
95.34% Lines 82/86

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                2x                                                     2x                                   2x         2x 8x 8x           2x 3x           2x 26x           2x 46x             23x 22x     20x 4x   2x             23x 23x   23x 8x 8x 5x   8x 8x       23x 23x 23x               4x 4x       4x                 44x 44x     44x 4x 4x                 44x                   44x 44x 44x                           44x   44x 506x 504x 23x 23x   23x                 42x 15x       42x 16x 16x 27x       42x             6x             1x   1x 12x     1x               2x 37x 37x 37x     1x             2x       4x 4x 4x 3x   3x     1x             2x 5x   5x 12x 11x 11x 11x 11x 2x   9x             5x  
/*
Copyright (c) 2025 Bernier LLC
 
This file is licensed to the client under a limited-use license.
The client may use and modify this code *only within the scope of the project it was delivered for*.
Redistribution or use in other products or commercial offerings is not permitted without written consent from Bernier LLC.
*/
 
import { cosmiconfigSync } from 'cosmiconfig';
import { RetryPolicyOptions, BackoffConfig } from '../types';
 
/**
 * Runtime configuration interface for retry policy
 * Extends the base types with optional configuration
 */
export interface RetryPolicyRuntimeConfig extends Partial<RetryPolicyOptions> {
  /** Backoff configuration */
  backoff?: Partial<BackoffConfig>;
  /** Enable/disable retry functionality globally */
  enabled?: boolean;
}
 
/**
 * Configuration source tracking for transparency
 */
export interface ConfigurationSource {
  key: string;
  value: any;
  source: 'default' | 'file' | 'environment' | 'global' | 'override';
  description: string;
}
 
/**
 * Environment variable mappings for retry policy
 */
const ENV_MAPPINGS = {
  maxRetries: 'RETRY_MAX_RETRIES',
  initialDelayMs: 'RETRY_INITIAL_DELAY',
  maxDelayMs: 'RETRY_MAX_DELAY', 
  backoffFactor: 'RETRY_BACKOFF_FACTOR',
  jitter: 'RETRY_JITTER',
  enabled: 'RETRY_ENABLED',
  'backoff.type': 'RETRY_BACKOFF_TYPE',
  'backoff.baseDelay': 'RETRY_BACKOFF_BASE_DELAY',
  'backoff.maxDelay': 'RETRY_BACKOFF_MAX_DELAY',
  'backoff.factor': 'RETRY_BACKOFF_MULTIPLIER',
  'backoff.jitter.type': 'RETRY_JITTER_TYPE',
  'backoff.jitter.factor': 'RETRY_JITTER_FACTOR'
};
 
/**
 * Global configuration storage for dependency injection
 */
let globalRetryPolicyConfig: Partial<RetryPolicyRuntimeConfig> = {};
 
/**
 * Set global configuration for dependency injection from service packages
 */
export function setGlobalRetryPolicyConfig(config: Partial<RetryPolicyRuntimeConfig>): void {
  globalRetryPolicyConfig = { ...globalRetryPolicyConfig, ...config };
  console.log('⚙️ Retry Policy: Global configuration updated');
}
 
/**
 * Get global configuration
 */
export function getGlobalRetryPolicyConfig(): Partial<RetryPolicyRuntimeConfig> {
  return { ...globalRetryPolicyConfig };
}
 
/**
 * Clear global configuration
 */
export function clearGlobalRetryPolicyConfig(): void {
  globalRetryPolicyConfig = {};
}
 
/**
 * Configuration loader with source tracking
 */
export class RetryPolicyConfigurationLoader {
  private sources: ConfigurationSource[] = [];
 
  /**
   * Parse environment variable value to appropriate type
   */
  private parseEnvironmentValue(value: string): any {
    // Boolean values
    if (value === 'true') return true;
    if (value === 'false') return false;
    
    // Number values
    if (/^\d+$/.test(value)) return parseInt(value);
    if (/^\d+\.\d+$/.test(value)) return parseFloat(value);
    
    return value;
  }
 
  /**
   * Set nested object value using dot notation
   */
  private setNestedValue(obj: any, path: string, value: any): void {
    const keys = path.split('.');
    let current = obj;
    
    for (let i = 0; i < keys.length - 1; i++) {
      const key = keys[i];
      if (key && !(key in current)) {
        current[key] = {};
      }
      if (key) {
        current = current[key];
      }
    }
    
    const lastKey = keys[keys.length - 1];
    if (lastKey) {
      current[lastKey] = value;
    }
  }
 
  /**
   * Merge configuration objects recursively
   */
  private mergeConfiguration(target: any, source: any): void {
    Object.keys(source).forEach(key => {
      Iif (source[key] && typeof source[key] === 'object' && !Array.isArray(source[key])) {
        Iif (!target[key]) target[key] = {};
        this.mergeConfiguration(target[key], source[key]);
      } else {
        target[key] = source[key];
      }
    });
  }
 
  /**
   * Load optional configuration from all sources
   */
  loadOptionalConfiguration(): RetryPolicyRuntimeConfig {
    const config: RetryPolicyRuntimeConfig = {};
    this.sources = [];
 
    // Load global configuration (from service packages)
    if (Object.keys(globalRetryPolicyConfig).length > 0) {
      this.mergeConfiguration(config, globalRetryPolicyConfig);
      this.sources.push({
        key: 'global',
        value: globalRetryPolicyConfig,
        source: 'global',
        description: 'Global configuration from service packages'
      });
    }
 
    // Load configuration file if it exists
    const explorer = cosmiconfigSync('retry-policy', {
      searchPlaces: [
        'retry-policy.config.js',
        'retry-policy.config.json',
        '.retry-policyrc',
        '.retry-policyrc.js',
        '.retry-policyrc.json'
      ]
    });
 
    try {
      const result = explorer.search();
      Iif (result && result.config) {
        this.mergeConfiguration(config, result.config);
        this.sources.push({
          key: 'file',
          value: result.config,
          source: 'file',
          description: `Configuration file: ${result.filepath}`
        });
      }
    } catch {
      // Fail silently - configuration is optional
    }
 
    // Apply environment variable overrides
    const envOverrides: ConfigurationSource[] = [];
    
    Object.entries(ENV_MAPPINGS).forEach(([configPath, envVar]) => {
      const envValue = process.env[envVar];
      if (envValue !== undefined) {
        const parsedValue = this.parseEnvironmentValue(envValue);
        this.setNestedValue(config, configPath, parsedValue);
        
        envOverrides.push({
          key: configPath,
          value: parsedValue,
          source: 'environment',
          description: `Environment variable: ${envVar}=${envValue}`
        });
      }
    });
 
    if (envOverrides.length > 0) {
      this.sources.push(...envOverrides);
    }
 
    // Log configuration sources for transparency
    if (this.sources.length > 0) {
      console.log('⚙️ Retry Policy: Runtime configuration loaded');
      this.sources.forEach(source => {
        console.log(`   └── ${source.source}: ${source.description}`);
      });
    }
 
    return config;
  }
 
  /**
   * Get configuration sources for transparency
   */
  getConfigurationSources(): ConfigurationSource[] {
    return [...this.sources];
  }
 
  /**
   * Get environment variable documentation
   */
  getEnvironmentVariableDocumentation(): Record<string, string> {
    const docs: Record<string, string> = {};
    
    Object.entries(ENV_MAPPINGS).forEach(([configPath, envVar]) => {
      docs[envVar] = `Controls ${configPath} configuration`;
    });
 
    return docs;
  }
}
 
/**
 * Load optional retry policy configuration
 * This function fails gracefully and returns empty config if loading fails
 */
export function loadOptionalRetryPolicyConfig(): RetryPolicyRuntimeConfig {
  try {
    const loader = new RetryPolicyConfigurationLoader();
    return loader.loadOptionalConfiguration();
  } catch {
    // Fail silently - configuration is optional for core packages
    return {};
  }
}
 
/**
 * Load configuration with source tracking
 */
export function loadOptionalRetryPolicyConfigWithSources(): {
  config: RetryPolicyRuntimeConfig;
  sources: ConfigurationSource[];
} {
  try {
    const loader = new RetryPolicyConfigurationLoader();
    const config = loader.loadOptionalConfiguration();
    const sources = loader.getConfigurationSources();
 
    return { config, sources };
  } catch {
    // Fail silently - return empty config and sources
    return { config: {}, sources: [] };
  }
}
 
/**
 * Merge configuration with precedence: defaults < global < file < environment < constructor
 */
export function mergeConfigurations(...configs: Partial<RetryPolicyRuntimeConfig>[]): RetryPolicyRuntimeConfig {
  const result: RetryPolicyRuntimeConfig = {};
  
  configs.forEach(config => {
    if (config) {
      (Object.keys(config) as Array<keyof RetryPolicyRuntimeConfig>).forEach(key => {
        const value = config[key];
        if (value !== undefined) {
          if (key === 'backoff' && typeof value === 'object') {
            result.backoff = { ...result.backoff, ...value };
          } else {
            (result as any)[key] = value;
          }
        }
      });
    }
  });
  
  return result;
}