Coverage for src/xrayradar/config.py: 100%
71 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-14 15:56 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-14 15:56 +0000
1"""
2Configuration management for xrayradar
3"""
5import os
6from typing import Any, Dict, Optional, Union
9class Config:
10 """Configuration class for error tracker settings"""
12 def __init__(self, **kwargs):
13 """
14 Initialize configuration
16 Args can include:
17 - dsn: Data Source Name
18 - debug: Enable debug mode
19 - environment: Environment name
20 - release: Release version
21 - server_name: Server name
22 - sample_rate: Sampling rate (0.0 to 1.0)
23 - max_breadcrumbs: Maximum number of breadcrumbs
24 - timeout: HTTP timeout
25 - verify_ssl: Whether to verify SSL certificates
26 - max_payload_size: Maximum payload size in bytes
27 """
28 # Set defaults
29 self.dsn = kwargs.get('dsn') or os.getenv('XRAYRADAR_DSN')
30 self.debug = kwargs.get('debug', False) or os.getenv(
31 'XRAYRADAR_DEBUG', '').lower() in ('true', '1', 'yes')
32 self.environment = kwargs.get('environment') or os.getenv(
33 'XRAYRADAR_ENVIRONMENT', 'development')
34 self.release = kwargs.get('release') or os.getenv(
35 'XRAYRADAR_RELEASE')
36 self.server_name = kwargs.get('server_name') or os.getenv(
37 'XRAYRADAR_SERVER_NAME', self._get_default_server_name())
38 if 'sample_rate' in kwargs:
39 self.sample_rate = float(kwargs.get('sample_rate'))
40 else:
41 self.sample_rate = float(os.getenv('XRAYRADAR_SAMPLE_RATE', 1.0))
43 if 'max_breadcrumbs' in kwargs:
44 self.max_breadcrumbs = int(kwargs.get('max_breadcrumbs'))
45 else:
46 self.max_breadcrumbs = int(
47 os.getenv('XRAYRADAR_MAX_BREADCRUMBS', 100))
49 # Transport settings
50 if 'timeout' in kwargs:
51 self.timeout = float(kwargs.get('timeout'))
52 else:
53 self.timeout = float(os.getenv('XRAYRADAR_TIMEOUT', 10.0))
55 if 'verify_ssl' in kwargs:
56 self.verify_ssl = bool(kwargs.get('verify_ssl'))
57 else:
58 self.verify_ssl = os.getenv(
59 'XRAYRADAR_VERIFY_SSL', '').lower() not in ('false', '0', 'no')
61 if 'max_payload_size' in kwargs:
62 self.max_payload_size = int(kwargs.get('max_payload_size'))
63 else:
64 self.max_payload_size = int(
65 os.getenv('XRAYRADAR_MAX_PAYLOAD_SIZE', 100 * 1024))
67 # Validate configuration
68 self._validate()
70 def _get_default_server_name(self) -> str:
71 """Get default server name"""
72 try:
73 import socket
74 return socket.gethostname()
75 except Exception:
76 return 'unknown'
78 def _validate(self):
79 """Validate configuration values"""
80 if self.sample_rate < 0.0 or self.sample_rate > 1.0:
81 raise ValueError(
82 f"sample_rate must be between 0.0 and 1.0, got {self.sample_rate}. "
83 f"Use 0.0 to disable sampling, 1.0 to capture all events, or a value "
84 f"in between (e.g., 0.5 for 50% sampling).")
86 if self.max_breadcrumbs < 0:
87 raise ValueError(
88 f"max_breadcrumbs must be non-negative, got {self.max_breadcrumbs}. "
89 f"Use a positive integer to limit the number of breadcrumbs stored.")
91 if self.timeout <= 0:
92 raise ValueError(
93 f"timeout must be positive, got {self.timeout}. "
94 f"Specify timeout in seconds (e.g., 10.0 for 10 seconds).")
96 if self.max_payload_size <= 0:
97 raise ValueError(
98 f"max_payload_size must be positive, got {self.max_payload_size}. "
99 f"Specify size in bytes (e.g., 102400 for 100KB).")
101 def to_dict(self) -> Dict[str, Any]:
102 """Convert configuration to dictionary"""
103 return {
104 'dsn': self.dsn,
105 'debug': self.debug,
106 'environment': self.environment,
107 'release': self.release,
108 'server_name': self.server_name,
109 'sample_rate': self.sample_rate,
110 'max_breadcrumbs': self.max_breadcrumbs,
111 'timeout': self.timeout,
112 'verify_ssl': self.verify_ssl,
113 'max_payload_size': self.max_payload_size,
114 }
116 @classmethod
117 def from_dict(cls, config_dict: Dict[str, Any]) -> "Config":
118 """Create configuration from dictionary"""
119 return cls(**config_dict)
121 @classmethod
122 def from_env(cls) -> "Config":
123 """Create configuration from environment variables"""
124 return cls()
127def load_config(config_source: Optional[Union[Dict[str, Any], str, Config]] = None) -> Config:
128 """
129 Load configuration from various sources
131 Args:
132 config_source: Configuration source - can be:
133 - Dict[str, Any]: Configuration dictionary
134 - str: Path to configuration file (JSON/YAML)
135 - Config: Existing Config instance
136 - None: Load from environment variables
138 Returns:
139 Config instance
140 """
141 if config_source is None:
142 return Config.from_env()
143 elif isinstance(config_source, Config):
144 return config_source
145 elif isinstance(config_source, dict):
146 return Config.from_dict(config_source)
147 elif isinstance(config_source, str):
148 # Load from file
149 return _load_config_from_file(config_source)
150 else:
151 raise TypeError(
152 f"Unsupported config source type: {type(config_source).__name__}. "
153 f"Expected one of: dict, str (file path), Config instance, or None (environment variables). "
154 f"Please provide a valid configuration source.")
157def _load_config_from_file(file_path: str) -> Config:
158 """Load configuration from file"""
159 import json
160 import yaml
162 if not os.path.exists(file_path):
163 raise FileNotFoundError(
164 f"Configuration file not found: {file_path}. "
165 f"Please ensure the file exists and the path is correct. "
166 f"You can create a configuration file or use environment variables instead.")
168 with open(file_path, 'r') as f:
169 if file_path.endswith('.json'):
170 config_dict = json.load(f)
171 elif file_path.endswith(('.yml', '.yaml')):
172 config_dict = yaml.safe_load(f)
173 else:
174 ext = os.path.splitext(file_path)[1]
175 raise ValueError(
176 f"Unsupported configuration file format: '{ext}'. "
177 f"Supported formats are: .json, .yaml, .yml. "
178 f"Please use one of these formats or load configuration programmatically.")
180 return Config.from_dict(config_dict)