reference-api-buddy 0.4.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,171 @@
1
+ """Configuration management for Reference API Buddy."""
2
+
3
+ import copy
4
+ from typing import Any, List, Tuple
5
+
6
+ # Default configuration schema
7
+ DEFAULT_CONFIG = {
8
+ "server": {"host": "127.0.0.1", "request_timeout": 30},
9
+ "security": {"require_secure_key": False, "log_security_events": True},
10
+ "cache": {
11
+ "database_path": ":memory:",
12
+ "max_cache_response_size": 10485760, # 10MB
13
+ "default_ttl_seconds": 86400, # 1 day = 24 * 3600 seconds
14
+ },
15
+ "throttling": {"default_requests_per_hour": 1000, "progressive_max_delay": 300},
16
+ "logging": {
17
+ "level": "INFO",
18
+ "parent_logger": None,
19
+ "format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s",
20
+ "date_format": "%Y-%m-%d %H:%M:%S",
21
+ "enable_console": True,
22
+ "enable_file": False,
23
+ "file_path": None,
24
+ "max_file_size": 10485760, # 10MB
25
+ "backup_count": 5,
26
+ },
27
+ "domain_mappings": {},
28
+ "callbacks": {},
29
+ "admin": {
30
+ "enabled": True,
31
+ "rate_limit_per_minute": 10,
32
+ "include_sensitive_config": False,
33
+ "log_access": True,
34
+ },
35
+ }
36
+
37
+
38
+ def deep_merge(base: dict, override: dict) -> dict:
39
+ """Recursively merge two dictionaries."""
40
+ result = copy.deepcopy(base)
41
+ for k, v in override.items():
42
+ if k in result and isinstance(result[k], dict) and isinstance(v, dict):
43
+ result[k] = deep_merge(result[k], v)
44
+ else:
45
+ result[k] = copy.deepcopy(v)
46
+ return result
47
+
48
+
49
+ class ConfigurationValidator:
50
+ """Validates configuration and provides error reporting."""
51
+
52
+ @staticmethod
53
+ def validate_config(config: dict) -> Tuple[bool, List[str]]:
54
+ errors = []
55
+ # Basic validation for required keys and types
56
+ if not isinstance(config, dict):
57
+ errors.append("Config must be a dictionary.")
58
+ return False, errors
59
+ # Validate server
60
+ server = config.get("server", {})
61
+ if not isinstance(server.get("host", None), str):
62
+ errors.append("server.host must be a string.")
63
+ if not isinstance(server.get("request_timeout", None), int):
64
+ errors.append("server.request_timeout must be an integer.")
65
+ # Validate security
66
+ security = config.get("security", {})
67
+ if not isinstance(security.get("require_secure_key", None), bool):
68
+ errors.append("security.require_secure_key must be a boolean.")
69
+ if not isinstance(security.get("log_security_events", None), bool):
70
+ errors.append("security.log_security_events must be a boolean.")
71
+ # Validate cache
72
+ cache = config.get("cache", {})
73
+ if not isinstance(cache.get("database_path", None), str):
74
+ errors.append("cache.database_path must be a string.")
75
+ if not isinstance(cache.get("max_cache_response_size", None), int):
76
+ errors.append("cache.max_cache_response_size must be an integer.")
77
+
78
+ # Validate cache TTL
79
+ default_ttl = cache.get("default_ttl_seconds")
80
+ if default_ttl is not None and (not isinstance(default_ttl, int) or default_ttl <= 0):
81
+ errors.append("cache.default_ttl_seconds must be a positive integer.")
82
+
83
+ # Validate throttling
84
+ throttling = config.get("throttling", {})
85
+ if not isinstance(throttling.get("default_requests_per_hour", None), int):
86
+ errors.append("throttling.default_requests_per_hour must be an integer.")
87
+ if not isinstance(throttling.get("progressive_max_delay", None), int):
88
+ errors.append("throttling.progressive_max_delay must be an integer.")
89
+ # Validate logging
90
+ logging_cfg = config.get("logging", {})
91
+ if not isinstance(logging_cfg.get("level", None), str):
92
+ errors.append("logging.level must be a string.")
93
+ if logging_cfg.get("parent_logger") is not None and not isinstance(logging_cfg.get("parent_logger"), str):
94
+ errors.append("logging.parent_logger must be a string or None.")
95
+ if not isinstance(logging_cfg.get("format", None), str):
96
+ errors.append("logging.format must be a string.")
97
+ if not isinstance(logging_cfg.get("date_format", None), str):
98
+ errors.append("logging.date_format must be a string.")
99
+ if not isinstance(logging_cfg.get("enable_console", None), bool):
100
+ errors.append("logging.enable_console must be a boolean.")
101
+ if not isinstance(logging_cfg.get("enable_file", None), bool):
102
+ errors.append("logging.enable_file must be a boolean.")
103
+ if logging_cfg.get("file_path") is not None and not isinstance(logging_cfg.get("file_path"), str):
104
+ errors.append("logging.file_path must be a string or None.")
105
+ if not isinstance(logging_cfg.get("max_file_size", None), int):
106
+ errors.append("logging.max_file_size must be an integer.")
107
+ if not isinstance(logging_cfg.get("backup_count", None), int):
108
+ errors.append("logging.backup_count must be an integer.")
109
+
110
+ # Validate domain-specific TTL
111
+ domain_mappings = config.get("domain_mappings", {})
112
+ for domain_key, mapping in domain_mappings.items():
113
+ if isinstance(mapping, dict):
114
+ ttl = mapping.get("ttl_seconds")
115
+ if ttl is not None and (not isinstance(ttl, int) or ttl <= 0):
116
+ errors.append(f"domain_mappings.{domain_key}.ttl_seconds must be a positive integer.")
117
+
118
+ # Validate admin configuration
119
+ admin = config.get("admin", {})
120
+ if not isinstance(admin.get("enabled", None), bool):
121
+ errors.append("admin.enabled must be a boolean.")
122
+ if not isinstance(admin.get("rate_limit_per_minute", None), int):
123
+ errors.append("admin.rate_limit_per_minute must be an integer.")
124
+ if not isinstance(admin.get("include_sensitive_config", None), bool):
125
+ errors.append("admin.include_sensitive_config must be a boolean.")
126
+ if not isinstance(admin.get("log_access", None), bool):
127
+ errors.append("admin.log_access must be a boolean.")
128
+
129
+ # domain_mappings and callbacks can be empty dicts
130
+ return len(errors) == 0, errors
131
+
132
+ @staticmethod
133
+ def merge_with_defaults(user_config: dict) -> dict:
134
+ return deep_merge(DEFAULT_CONFIG, user_config)
135
+
136
+
137
+ class ConfigurationManager:
138
+ """Manages configuration, validation, merging, and runtime updates."""
139
+
140
+ def __init__(self, user_config: dict = None):
141
+ if user_config is None:
142
+ user_config = {}
143
+ self._config = self.load_config(user_config)
144
+
145
+ def load_config(self, user_config: dict) -> dict:
146
+ merged = ConfigurationValidator.merge_with_defaults(user_config)
147
+ valid, errors = ConfigurationValidator.validate_config(merged)
148
+ if not valid:
149
+ raise ValueError(f"Invalid configuration: {errors}")
150
+ return merged
151
+
152
+ @property
153
+ def config(self) -> dict:
154
+ return self._config
155
+
156
+ def update(self, key_path: str, value: Any) -> None:
157
+ """Update a config value at a dotted key path (e.g., 'server.host')."""
158
+ keys = key_path.split(".")
159
+ d = self._config
160
+ for k in keys[:-1]:
161
+ if k not in d or not isinstance(d[k], dict):
162
+ d[k] = {}
163
+ d = d[k]
164
+ d[keys[-1]] = value
165
+ # Re-validate after update
166
+ valid, errors = ConfigurationValidator.validate_config(self._config)
167
+ if not valid:
168
+ raise ValueError(f"Invalid configuration after update: {errors}")
169
+
170
+ def reload(self, new_config: dict) -> None:
171
+ self._config = self.load_config(new_config)