yamlpyconfig 0.0.7__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,7 @@
1
+ from .config_manager import ConfigManager
2
+
3
+ __all__ = [
4
+ "ConfigManager",
5
+ ]
6
+
7
+ __version__ = "0.0.7"
@@ -0,0 +1,98 @@
1
+ import copy
2
+ from threading import RLock
3
+ from types import MappingProxyType
4
+ from typing import Dict, Any, Optional, Mapping, List, Iterator, Tuple
5
+
6
+ from yamlpyconfig.models import NacosConfigCacheItem
7
+ from yamlpyconfig.utils import ConfigMerge
8
+ from yamlpyconfig.utils.crypto import CryptoHelper
9
+
10
+
11
+ class ConfigCache:
12
+ """
13
+ 负责缓存本地配置 + Nacos 多个 dataId 的配置,并合并成最终配置。
14
+ - 写路径:加锁 + 重建 merged_config(copy-on-write)
15
+ - 读路径:读只读快照,不加锁(或极短锁)
16
+ """
17
+
18
+ def __init__(self, base_config: Optional[Dict[str, Any]] = None, crypto_helper: CryptoHelper = None) -> None:
19
+ self._lock = RLock()
20
+ # 对外暴露的最终配置快照(不可变)
21
+ self._merged_config: Mapping[str, Any] = MappingProxyType({})
22
+ self._base_config: dict[str, Any] = {}
23
+ self._crypto_helper: CryptoHelper|None = crypto_helper
24
+ self._order: List[str] = [] # imports 顺序
25
+ self._items: Dict[str, NacosConfigCacheItem] = {}
26
+ self.set_base_config(base_config)
27
+
28
+
29
+ def set_base_config(self, base_config: Dict[str, Any]) -> None:
30
+ """更新本地基础配置,并重建 merged_config。"""
31
+ with self._lock:
32
+ self._base_config = dict(base_config or {})
33
+ if self._crypto_helper:
34
+ self._crypto_helper.decrypt_config_value(self._base_config)
35
+ self._rebuild_merged_unlocked()
36
+
37
+ def set_config(self, data_id: str, config: Optional[Dict[str, Any]]) -> None:
38
+ """
39
+ 设置/更新某个 dataId 的配置。
40
+ - 若 data_id 不存在,则追加到顺序末尾;
41
+ - 若已存在,仅更新对应的 config。
42
+ """
43
+ with self._lock:
44
+ if self._crypto_helper:
45
+ self._crypto_helper.decrypt_config_value(config)
46
+ if data_id not in self._items:
47
+ self._order.append(data_id)
48
+ self._items[data_id] = NacosConfigCacheItem(data_id=data_id, config=config)
49
+ else:
50
+ # pydantic v2: 可以直接更新属性,也可以 model_copy(update=...)
51
+ item = self._items[data_id]
52
+ item.config = config
53
+
54
+ self._rebuild_merged_unlocked()
55
+
56
+ def _rebuild_merged_unlocked(self) -> None:
57
+ """
58
+ 在锁内重建 merged_config。
59
+ 合并策略(浅合并):
60
+ 1. 先拷贝 base_config;
61
+ 2. 按 _order 顺序应用每个 dataId 的 config,后者覆盖前者同名 key。
62
+ """
63
+ merged: Dict[str, Any] = copy.deepcopy(self._base_config)
64
+
65
+ for data_id in self._order:
66
+ item = self._items.get(data_id)
67
+ if not item or not item.config:
68
+ continue
69
+ cfg = item.config
70
+ if not isinstance(cfg, dict):
71
+ # 若配置不是 dict(比如 yaml 顶层不是映射),可以选择跳过或抛错
72
+ continue
73
+ ConfigMerge.deep_merge(merged, cfg)
74
+
75
+ # copy-on-write: 用新的 dict 替换旧引用,并加只读包装
76
+ self._merged_config = MappingProxyType(merged)
77
+
78
+ def get_nacos_configs(self) -> Iterator[Tuple[str, Optional[Dict[str, Any]]]]:
79
+ """
80
+ 按 imports 顺序依次返回 (dataId, config) 的只读快照。
81
+ 为了避免在长时间迭代时持有锁,这里使用“快照”:
82
+ - 在锁内复制 _order 和 _items 的当前状态;
83
+ - 解锁后再遍历快照。
84
+ """
85
+ with self._lock:
86
+ order_snapshot = tuple(self._order)
87
+ items_snapshot = {k: v.config for k, v in self._items.items()}
88
+
89
+ for data_id in order_snapshot:
90
+ yield data_id, items_snapshot.get(data_id)
91
+
92
+ def get_config(self) -> Mapping[str, Any]:
93
+ """
94
+ 返回最终合并后的配置快照(只读 Mapping)。
95
+ 注意:返回的是只读的 mappingproxy,对外修改会抛异常。
96
+ """
97
+
98
+ return self._merged_config
@@ -0,0 +1,57 @@
1
+ import logging
2
+ from typing import Optional
3
+
4
+ from .models import AlgorithmEnum
5
+ from yamlpyconfig.config_cache import ConfigCache
6
+ from yamlpyconfig.local_manage.local_config_manager import LocalConfigManager
7
+ from yamlpyconfig.models import NacosConfig
8
+ from yamlpyconfig.nacos_manage.nacos_config_manager import NacosConfigManager
9
+ from yamlpyconfig.utils.crypto.crypto_algorithm_factory import CryptoAlgorithmFactory
10
+ from .utils.crypto import CryptoHelper
11
+
12
+ logger = logging.getLogger(__name__)
13
+ class ConfigManager:
14
+ """
15
+ ConfigManager is a singleton class that manages the configuration of the application.
16
+ It provides methods to get and set configuration values.
17
+ """
18
+ def __init__(self, config_dir: Optional[str] = None,
19
+ crypto_algorithm: AlgorithmEnum|None = None, key: str = None):
20
+ """
21
+
22
+ :param config_dir: 本地配置文件的根目录,包含application.yaml和application-{profile}.yaml的目录
23
+ :param crypto_algorithm: 如果配置文件中包含{encrypted}加密数据,可以配置加密算法,用来解密
24
+ :param key: 如果是sm2则传递私钥,如果是sm4则传递对称密钥
25
+ """
26
+
27
+ self._base_config = LocalConfigManager(config_dir).load_config()
28
+ self._crypto_helper = None
29
+ if crypto_algorithm and key:
30
+ crypto_algorithm = CryptoAlgorithmFactory.create(crypto_algorithm, key_b64=key)
31
+ self._crypto_helper = CryptoHelper(crypto_algorithm)
32
+ self._cache = ConfigCache(base_config=self._base_config, crypto_helper=self._crypto_helper)
33
+ self._nacos_manager = None
34
+
35
+
36
+ async def start(self):
37
+ if self._nacos_manager is None:
38
+ try:
39
+ nacos_config: NacosConfig = NacosConfig.load_nacos_config(self._cache.get_config())
40
+ if nacos_config:
41
+ self._nacos_manager = NacosConfigManager(nacos_config, cache=self._cache)
42
+ await self._nacos_manager.start()
43
+ except Exception as e:
44
+ logger.error(f"Failed to connect to Nacos: {e}", exc_info=True)
45
+
46
+ async def __aenter__(self):
47
+ await self.start()
48
+ return self
49
+ async def stop(self):
50
+ if self._nacos_manager:
51
+ await self._nacos_manager.stop()
52
+
53
+ async def __aexit__(self, exc_type, exc_val, exc_tb):
54
+ await self.stop()
55
+
56
+ def get_config(self):
57
+ return self._cache.get_config()
@@ -0,0 +1,2 @@
1
+ from .local_config_loader import LocalConfigLoader
2
+
@@ -0,0 +1,66 @@
1
+ from __future__ import annotations
2
+
3
+ from pathlib import Path
4
+ from typing import Any, Dict, Iterable, Optional
5
+
6
+ import yaml
7
+
8
+
9
+ class LocalConfigLoader:
10
+ """Local YAML configuration file loader."""
11
+
12
+ def __init__(self, config_dir: Optional[str|Path] = None):
13
+ """
14
+ Initialize local_manage config loader.
15
+
16
+ Args:
17
+ config_dir: Directory containing config files. Defaults to current working directory.
18
+ """
19
+ if isinstance(config_dir, str):
20
+ self.config_dir = Path(config_dir) if config_dir else Path.cwd()
21
+ else:
22
+ self.config_dir = config_dir
23
+
24
+ @staticmethod
25
+ def _candidate_paths(base: Path, name: str) -> Iterable[Path]:
26
+ """Yield possible file paths for the given base directory and name.
27
+
28
+ If the provided name has no YAML extension, try common variants.
29
+ """
30
+ p = base / name
31
+ if p.suffix.lower() in {".yml", ".yaml"}:
32
+ yield p
33
+ return
34
+ # Try with typical YAML suffixes
35
+ yield p.with_suffix(".yaml")
36
+ yield p.with_suffix(".yml")
37
+
38
+
39
+ def load_local_yaml(self, filename: str) -> Dict[str, Any]:
40
+ """Load a local_manage YAML configuration file.
41
+
42
+ Parameters
43
+ - config_dir: The directory containing the configuration file.
44
+ - filename: The configuration file name, with or without .yaml/.yml.
45
+
46
+ Returns
47
+ - A dictionary with the parsed YAML content (empty dict if file is empty).
48
+
49
+ Raises
50
+ - FileNotFoundError: If no matching file is found.
51
+ - yaml.YAMLError: If the YAML content is invalid.
52
+ """
53
+ if not self.config_dir.exists() or not self.config_dir.is_dir():
54
+ raise FileNotFoundError(f"Config directory does not exist: {self.config_dir}")
55
+
56
+ for path in self._candidate_paths(self.config_dir, filename):
57
+ if path.exists() and path.is_file():
58
+ with path.open("r", encoding="utf-8") as f:
59
+ data = yaml.safe_load(f)
60
+ return data or {}
61
+
62
+ tried = ", ".join(str(p) for p in self._candidate_paths(self.config_dir, filename))
63
+ raise FileNotFoundError(
64
+ f"Config file not found. Tried: {tried}"
65
+ )
66
+
@@ -0,0 +1,62 @@
1
+ import logging
2
+ import os
3
+ from pathlib import Path
4
+ from typing import Optional, Dict, Any
5
+
6
+ from yamlpyconfig.utils import ExpressionHelper
7
+ from yamlpyconfig.local_manage import LocalConfigLoader
8
+ from yamlpyconfig.utils import ConfigMerge
9
+
10
+ logger = logging.getLogger(__name__)
11
+
12
+ class LocalConfigManager:
13
+ """
14
+ Local configuration manager.
15
+ 默认获取 config_dir / application.yaml 以及 config_dir / application-{profile}.yaml 的本地文件配置。
16
+ 其中 profile 的获取逻辑是:
17
+ 1. 首先获取APP_PROFILE作为环境变量的值,如果存在返回
18
+ 2. 然后获取SPRING_PROFILES_ACTIVE座位环境变量的值,如果存在返回
19
+ 3. 最后获取application.yaml配置文件中的profile的配置,如果存在则返回
20
+ 如果以上三处都未获取到有效的profile,则不再尝试获取application-{profile}.yaml的配置。
21
+ """
22
+
23
+ def __init__(self, config_dir: Optional[str] = None):
24
+ """
25
+ Initialize local config manager.
26
+
27
+ Args:
28
+ config_dir: Directory containing config files. Defaults to current working directory.
29
+ """
30
+ self.config_dir = Path(config_dir) if config_dir else Path.cwd()
31
+
32
+ def load_config(self) -> Dict[str, Any]:
33
+ """Load local configuration.
34
+
35
+ Args:
36
+ profile: Profile to load. Defaults to None.
37
+
38
+ Returns:
39
+ A dictionary with the loaded configuration.
40
+ """
41
+ config: dict[str, Any] = LocalConfigLoader(self.config_dir).load_local_yaml("application")
42
+ ExpressionHelper.resolve_config(config)
43
+
44
+ profile = self._detect_profile(config)
45
+ if profile:
46
+ logger.info(f"Using profile: {profile}")
47
+ config_profile = LocalConfigLoader(self.config_dir).load_local_yaml(f"application-{profile}")
48
+ ConfigMerge.deep_merge(config, config_profile, False)
49
+ ExpressionHelper.resolve_config(config)
50
+ return config
51
+
52
+ @staticmethod
53
+ def _detect_profile(config) -> Optional[str]:
54
+ """Detect profile from environment or config files."""
55
+ # Check environment variable
56
+ env_profile = os.getenv('APP_PROFILE', os.getenv('SPRING_PROFILES_ACTIVE'))
57
+ if env_profile:
58
+ return env_profile
59
+ # Try to extract from local loader
60
+ if "profile" in config:
61
+ return config["profile"]
62
+ return None
@@ -0,0 +1,8 @@
1
+ from .nacos_config import NacosConfig, ImportConfigItem
2
+ from .nacos_config_cache_item import NacosConfigCacheItem
3
+ from .algorithm_enum import AlgorithmEnum
4
+
5
+
6
+ __all__ = [
7
+ "AlgorithmEnum",
8
+ ]
@@ -0,0 +1,6 @@
1
+ from enum import Enum
2
+
3
+
4
+ class AlgorithmEnum(str, Enum):
5
+ SM2 = "sm2"
6
+ SM4 = "sm4"
@@ -0,0 +1,36 @@
1
+ from typing import Optional, Any
2
+
3
+ from pydantic import BaseModel, Field, field_validator
4
+ from typing import Self
5
+
6
+ class ImportConfigItem(BaseModel):
7
+ """Single import configuration item."""
8
+ data_id: str = Field(..., alias="data-id", description="Import data_id, e.g., 'gateway.yaml'")
9
+
10
+ @field_validator("data_id")
11
+ def validate_source(cls, v):
12
+ if not v or ('yaml' not in v and 'yml' not in v):
13
+ raise ValueError("data_id must be in format 'name.yaml', e.g., 'gateway.yaml'")
14
+ return v
15
+
16
+ class NacosConfig(BaseModel):
17
+ """Nacos configuration model."""
18
+ server_addr: str = Field(..., alias="server-addr", description="Nacos server address")
19
+ namespace: Optional[str] = Field(None, alias="namespace", description="Nacos namespace")
20
+ group: Optional[str] = Field("DEFAULT_GROUP", alias="group", description="Nacos group")
21
+ username: Optional[str] = Field(None, alias="username", description="Nacos username")
22
+ password: Optional[str] = Field(None, alias="password", description="Nacos password")
23
+ access_key: Optional[str] = Field(None, alias="access-key", description="Nacos access key")
24
+ secret_key: Optional[str] = Field(None, alias="secret-key", description="Nacos secret key")
25
+ endpoint: Optional[str] = Field(None, alias="endpoint", description="Nacos endpoint for ACM")
26
+ auto_refresh: bool = Field(True, alias="auto-refresh", description="Whether to auto refresh config")
27
+ imports: Optional[list[ImportConfigItem]] = Field(None, alias="imports", description="List of import configurations")
28
+
29
+ @classmethod
30
+ def load_nacos_config(cls, config: dict[str, Any]) -> Optional[Self]:
31
+ """Load Nacos configuration from a dict."""
32
+ if "config-sources" in config and "nacos" in config["config-sources"]:
33
+ return NacosConfig.model_validate(config["config-sources"]["nacos"])
34
+ return None
35
+
36
+
@@ -0,0 +1,9 @@
1
+ from typing import Optional, Any
2
+
3
+ from pydantic import BaseModel, Field
4
+
5
+
6
+ class NacosConfigCacheItem(BaseModel):
7
+ """Single Nacos configuration cache item."""
8
+ data_id: str = Field(..., description="nacos data ID")
9
+ config: Optional[dict[str, Any]] = Field(None, description="nacos configuration")
File without changes
@@ -0,0 +1,193 @@
1
+ # ========================
2
+ # 3. NacosConfigManager:连接/初始化/监听
3
+ # ========================
4
+ from __future__ import annotations
5
+
6
+ import asyncio
7
+ import logging
8
+ from asyncio import TaskGroup, Task
9
+ from typing import Optional, Any, Dict, Iterator, Tuple, Mapping
10
+
11
+ import yaml
12
+ from v2.nacos import ClientConfigBuilder, GRPCConfig, NacosConfigService, ConfigParam
13
+
14
+ from yamlpyconfig.config_cache import ConfigCache
15
+ from yamlpyconfig.models import NacosConfig
16
+
17
+ logger = logging.getLogger(__name__)
18
+ class NacosConfigManager:
19
+ """
20
+ 负责:
21
+ 1. 用 NacosConfig 初始化 NacosClient;
22
+ 2. 根据 imports 顺序拉取初始配置并填充 ConfigCache;
23
+ 3. 若 auto_refresh=True,则为每个 dataId 注册监听器,在配置变更时更新 Cache。
24
+ """
25
+
26
+ def __init__(
27
+ self,
28
+ nacos_config: NacosConfig,
29
+ cache: Optional[ConfigCache],
30
+ ) -> None:
31
+ self._cfg = nacos_config
32
+ self._group = nacos_config.group or "DEFAULT_GROUP"
33
+ self._cache = cache
34
+ self._client: Optional[NacosConfigService] = None
35
+
36
+ async def start(self):
37
+ if self._client is None:
38
+ # 初始化 Nacos 客户端
39
+ self._client = await self._create_client(self._cfg)
40
+ # 初始化配置
41
+ await self._init_import_configs()
42
+ # 如果需要自动刷新,则注册监听
43
+ if self._cfg.auto_refresh:
44
+ await self._register_listeners()
45
+
46
+
47
+ async def stop(self):
48
+ if self._client:
49
+ await self._client.shutdown()
50
+
51
+ async def __aenter__(self):
52
+ await self.start()
53
+ return self
54
+
55
+ async def __aexit__(self, exc_type, exc_val, exc_tb):
56
+ await self.stop()
57
+
58
+ @staticmethod
59
+ async def _create_client(cfg: NacosConfig) -> NacosConfigService:
60
+ """
61
+ 创建 NacosClient。
62
+ nacos-sdk-python 2.x 的参数名可能略有出入,可按实际 SDK 文档调整。
63
+ """
64
+ kwargs: Dict[str, Any] = {}
65
+ if cfg.namespace:
66
+ kwargs["namespace"] = cfg.namespace
67
+ if cfg.username and cfg.password:
68
+ kwargs["username"] = cfg.username
69
+ kwargs["password"] = cfg.password
70
+ if cfg.access_key and cfg.secret_key:
71
+ kwargs["ak"] = cfg.access_key
72
+ kwargs["sk"] = cfg.secret_key
73
+ if cfg.endpoint:
74
+ kwargs["endpoint"] = cfg.endpoint
75
+
76
+ client_config = (ClientConfigBuilder()
77
+ .server_address(cfg.server_addr)
78
+ .username(cfg.username)
79
+ .password(cfg.password)
80
+ .namespace_id(cfg.namespace)
81
+ .access_key(cfg.access_key)
82
+ .secret_key(cfg.secret_key)
83
+ .log_level("INFO")
84
+ .grpc_config(GRPCConfig(grpc_timeout=5000))
85
+ .build())
86
+ while True:
87
+ try:
88
+ config_client = await NacosConfigService.create_config_service(client_config)
89
+ return config_client
90
+ except Exception as e:
91
+ logger.error(f"Nacos client init failed: {e}", exc_info=True)
92
+ await asyncio.sleep(1)
93
+
94
+ # ---------- 配置解析 & 初始化 ----------
95
+
96
+ @staticmethod
97
+ def _parse_yaml_config(content: Optional[str]) -> Dict[str, Any]:
98
+ """
99
+ 解析 YAML 文本为 dict。
100
+ - 若 content 为空或解析失败,则返回空 dict。
101
+ - 若顶层不是 dict,则也返回空 dict(避免后续 merged.update 出问题)。
102
+ """
103
+ if not content:
104
+ return {}
105
+ try:
106
+ data = yaml.safe_load(content)
107
+ if isinstance(data, dict):
108
+ return data
109
+ return {}
110
+ except Exception:
111
+ # 这里按需选择:可以记录日志,或者抛自定义异常
112
+ return {}
113
+
114
+ async def _init_import_configs(self) -> None:
115
+ """
116
+ 初始化加载所有 imports 中的 dataId 配置到 Cache。
117
+ """
118
+ imports = self._cfg.imports or []
119
+ tasks: dict[str, Task] = {}
120
+ async with TaskGroup() as tg:
121
+ for item in imports:
122
+ data_id = item.data_id
123
+ task = tg.create_task(self._get_data_id_config(data_id))
124
+ tasks[data_id] = task
125
+ for item in imports:
126
+ data_id = item.data_id
127
+ raw = tasks[data_id].result()
128
+ cfg_dict = self._parse_yaml_config(raw)
129
+ await asyncio.to_thread(self._cache.set_config, data_id, cfg_dict)
130
+
131
+ async def _get_data_id_config(self, data_id: str):
132
+ while True:
133
+ try:
134
+ return await self._client.get_config(ConfigParam(data_id=data_id, group=self._group))
135
+ except Exception as e:
136
+ logger.error(f"Failed to get config for dataId: {data_id}: {e!r}", exc_info=True)
137
+ await asyncio.sleep(1)
138
+
139
+ # ---------- 监听配置变更 ----------
140
+
141
+ async def _register_listeners(self) -> None:
142
+ """
143
+ 为每个 imports.dataId 注册监听器。
144
+ 注意:具体监听 API 可能是 add_config_watcher 或 add_listener,
145
+ 这里用伪代码形式,使用时按实际 SDK 调整。
146
+ """
147
+ imports = self._cfg.imports or []
148
+ async with TaskGroup() as tg:
149
+ for item in imports:
150
+ data_id = item.data_id
151
+ tg.create_task(self._register_single_listener(data_id))
152
+
153
+ async def _register_single_listener(self, data_id: str) -> None:
154
+ group = self._group
155
+
156
+ async def _on_change(tenant, data_id, group, content) -> None:
157
+ """
158
+ Nacos 配置变化时的回调。
159
+ 只做两件事:
160
+ 1. 解析 YAML;
161
+ 2. 更新 Cache。
162
+ """
163
+ cfg_dict = None
164
+ if content:
165
+ cfg_dict = self._parse_yaml_config(content)
166
+ await asyncio.to_thread(self._cache.set_config, data_id, cfg_dict)
167
+
168
+ # 这里根据 nacos-sdk-python 的实际接口调用
169
+ # 官方 SDK 大致有类似 API:
170
+ # client.add_config_watcher(data_id, group, callback)
171
+ # 或者:
172
+ # client.add_listener(data_id, group, callback)
173
+ #
174
+ # 假设使用 add_config_watcher:
175
+ try:
176
+ await self._client.add_listener(data_id, group, _on_change) # 伪代码
177
+ except Exception as e:
178
+ logger.error(f"Failed to register Nacos listener (data_id={data_id}, group={group}): {e!r}", exc_info=True)
179
+
180
+ # ---------- 对外访问接口 ----------
181
+
182
+ @property
183
+ def cache(self) -> ConfigCache:
184
+ """暴露底层 Cache 对象(只读访问配置,写操作也可以)。"""
185
+ return self._cache
186
+
187
+ def get_config(self) -> Mapping[str, Any]:
188
+ """获取合并后的最终配置快照(只读)。"""
189
+ return self._cache.get_config()
190
+
191
+ def get_nacos_configs(self) -> Iterator[Tuple[str, Optional[Dict[str, Any]]]]:
192
+ """按 imports 顺序返回 (dataId, config)。"""
193
+ return self._cache.get_nacos_configs()
yamlpyconfig/py.typed ADDED
File without changes
@@ -0,0 +1,3 @@
1
+ from yamlpyconfig.utils.config_merge import ConfigMerge
2
+ from yamlpyconfig.utils.crypto.impl.SM4Algorithm import SM4Algorithm
3
+ from yamlpyconfig.utils.express_helper import ExpressionHelper
@@ -0,0 +1,28 @@
1
+ from typing import Dict, Any
2
+
3
+
4
+ class ConfigMerge:
5
+
6
+ @staticmethod
7
+ def deep_merge(base: Dict[str, Any], override: Dict[str, Any], list_merge: bool = False):
8
+ """
9
+ Deep merge two dictionaries.
10
+
11
+ Args:
12
+ base: Base dictionary (will be modified)
13
+ override: Override dictionary
14
+ """
15
+ for key, value in override.items():
16
+ if key in base:
17
+ if isinstance(base[key], dict) and isinstance(value, dict):
18
+ # Both are dicts, merge recursively
19
+ ConfigMerge.deep_merge(base[key], value)
20
+ elif isinstance(base[key], list) and isinstance(value, list) and list_merge:
21
+ # Both are lists, merge them
22
+ base[key] += value
23
+ else:
24
+ # Override with new value
25
+ base[key] = value
26
+ else:
27
+ # New key, add it
28
+ base[key] = value
@@ -0,0 +1,12 @@
1
+
2
+ from .crypto_helper import CryptoHelper
3
+ from .impl.SM2Algorithm import SM2Algorithm as __SM2Algorithm
4
+ from .impl.SM4Algorithm import SM4Algorithm as __SM4Algorithm
5
+ from .crypto_algorithm_factory import CryptoAlgorithmFactory as __CryptoAlgorithmFactory
6
+ from ...models import AlgorithmEnum
7
+
8
+ __CryptoAlgorithmFactory.register(AlgorithmEnum.SM4.value, __SM4Algorithm)
9
+ __CryptoAlgorithmFactory.register(AlgorithmEnum.SM2.value, __SM2Algorithm)
10
+
11
+
12
+
@@ -0,0 +1,28 @@
1
+ from __future__ import annotations
2
+
3
+ from abc import ABC, abstractmethod
4
+ from typing import Dict
5
+
6
+
7
+ class CryptoAlgorithm(ABC):
8
+ """加解密算法策略接口"""
9
+
10
+ @abstractmethod
11
+ def encrypt(self, plaintext: str) -> str:
12
+ """明文 -> 密文(不含 {encrypted} 前缀)"""
13
+ ...
14
+
15
+ @abstractmethod
16
+ def decrypt(self, ciphertext: str) -> str:
17
+ """密文 -> 明文(不含 {encrypted} 前缀)"""
18
+ ...
19
+
20
+ @classmethod
21
+ @abstractmethod
22
+ def generate_keys(cls) -> Dict[str, str]:
23
+ """
24
+ 生成该算法所需密钥。
25
+ 对称算法:{"key": "..."};
26
+ 非对称算法:{"public_key": "...", "private_key": "..."}。
27
+ """
28
+ ...
@@ -0,0 +1,30 @@
1
+ from typing import Any, Dict
2
+
3
+ from .crypto_algorithm import CryptoAlgorithm
4
+ from ...models import AlgorithmEnum
5
+
6
+
7
+ class CryptoAlgorithmFactory:
8
+ """算法策略工厂 + 注册表"""
9
+
10
+ _registry: Dict[str, type[CryptoAlgorithm]] = {}
11
+
12
+ @classmethod
13
+ def register(cls, name: str, algo_cls: type[CryptoAlgorithm]) -> None:
14
+ cls._registry[name.lower()] = algo_cls
15
+
16
+ @classmethod
17
+ def create(cls, name: AlgorithmEnum, **kwargs: Any) -> CryptoAlgorithm:
18
+ algo_cls = cls._registry.get(name.value.lower())
19
+ if algo_cls is None:
20
+ raise ValueError(f"Unsupported algorithm: {name}")
21
+ return algo_cls(**kwargs) # type: ignore[arg-type]
22
+
23
+ @classmethod
24
+ def get_algorithms_class(cls, name: AlgorithmEnum):
25
+ algo_cls = cls._registry.get(name.value.lower())
26
+ return algo_cls
27
+
28
+ @classmethod
29
+ def list_algorithms(cls) -> list[str]:
30
+ return list(cls._registry.keys())
@@ -0,0 +1,71 @@
1
+ from typing import Optional, Dict, Any, Self
2
+
3
+ from .crypto_algorithm import CryptoAlgorithm
4
+ from ...models import AlgorithmEnum
5
+ from .crypto_algorithm_factory import CryptoAlgorithmFactory
6
+
7
+
8
+ class CryptoHelper:
9
+ """
10
+ 业务层使用的加解密工具:
11
+ - 负责识别/封装 `{encrypted}` 前缀
12
+ - 持有一个具体的 CryptoAlgorithm 策略
13
+ """
14
+
15
+ ENCRYPTED_PREFIX = "{encrypted}"
16
+
17
+ def __init__(self, algorithm: CryptoAlgorithm):
18
+ self._algorithm = algorithm
19
+
20
+ @classmethod
21
+ def from_algorithm_name(cls, name: AlgorithmEnum, **kwargs: Any) -> Self:
22
+ """工厂式构造:通过算法名 + 参数创建 CryptoHelper"""
23
+ algo = CryptoAlgorithmFactory.create(name, **kwargs)
24
+ return cls(algo)
25
+
26
+ @staticmethod
27
+ def strip_prefix(value: str, prefix: str) -> Optional[str]:
28
+ """如果以 prefix 开头,返回去掉前缀后的内容,否则返回 None"""
29
+ if value.startswith(prefix):
30
+ return value[len(prefix):]
31
+ return None
32
+
33
+ def encrypt_value(self, value: str, with_prefix: bool = True) -> str:
34
+ """
35
+ 对传入的明文进行加密。
36
+ - 默认加 `{encrypted}` 前缀;
37
+ - 如果 value 已经是带前缀的密文,可以根据需要选择是否重复加密。
38
+ """
39
+ ciphertext = self._algorithm.encrypt(value)
40
+ if with_prefix:
41
+ return f"{self.ENCRYPTED_PREFIX}{ciphertext}"
42
+ return ciphertext
43
+
44
+ def decrypt_value(self, value: str) -> str:
45
+ """
46
+ 对传入的值进行解密:
47
+ - 如果以 `{encrypted}` 开头,则截取后面的内容进行解密;
48
+ - 否则认为是明文,直接返回。
49
+ """
50
+ inner = self.strip_prefix(value, self.ENCRYPTED_PREFIX)
51
+ if inner is None:
52
+ # 不带前缀,当作明文返回
53
+ return value
54
+ return self._algorithm.decrypt(inner)
55
+
56
+ @staticmethod
57
+ def generate_keys(algorithm_name: AlgorithmEnum) -> Dict[str, str]:
58
+ """统一的密钥生成入口"""
59
+ algo_cls = CryptoAlgorithmFactory.get_algorithms_class(algorithm_name)
60
+ if algo_cls is None:
61
+ raise ValueError(f"Unsupported algorithm: {algorithm_name}")
62
+ return algo_cls.generate_keys()
63
+
64
+ def decrypt_config_value(self, config: dict[str, Any] | None):
65
+ if config is None:
66
+ return
67
+ for k, v in config.items():
68
+ if isinstance(v, str):
69
+ config[k] = self.decrypt_value(v)
70
+ elif isinstance(v, dict):
71
+ self.decrypt_config_value(v)
@@ -0,0 +1,63 @@
1
+ import base64
2
+ from gmssl import sm2, func
3
+
4
+ from ..crypto_algorithm import CryptoAlgorithm
5
+
6
+
7
+ class SM2Algorithm(CryptoAlgorithm):
8
+ """
9
+ SM2 非对称加密算法
10
+ public_key_b64: Base64(HEX public key)
11
+ private_key_b64: Base64(HEX private key)
12
+ """
13
+
14
+ def __init__(self, key_b64: str | None, public_key_b64: str | None = None):
15
+ self.private_key_hex = base64.b64decode(key_b64).decode() if key_b64 else None
16
+ self.public_key_hex = base64.b64decode(public_key_b64).decode() if public_key_b64 else None
17
+
18
+ # 如果私钥存在但公钥不存在 → 自动推导
19
+ if self.private_key_hex and not self.public_key_hex:
20
+ sm2_crypt = sm2.CryptSM2(private_key=self.private_key_hex, public_key="")
21
+
22
+ self.public_key_hex = sm2_crypt._kg(int(self.private_key_hex, 16), sm2_crypt.ecc_table["g"])
23
+
24
+ self.sm2_crypt = sm2.CryptSM2(
25
+ private_key=self.private_key_hex,
26
+ public_key=self.public_key_hex
27
+ )
28
+
29
+ # ---------------- 加密(必须公钥) ---------------- #
30
+ def encrypt(self, plaintext: str) -> str:
31
+ if not self.public_key_hex:
32
+ raise ValueError("SM2 encryption requires public_key")
33
+
34
+ # encrypt 返回 bytes
35
+ cipher_bytes: bytes = self.sm2_crypt.encrypt(plaintext.encode("utf-8"))
36
+ # 统一封装成 Base64 字符串返回
37
+ return base64.b64encode(cipher_bytes).decode("ascii")
38
+
39
+ # ---------------- 解密(必须私钥) ---------------- #
40
+ def decrypt(self, ciphertext: str) -> str:
41
+ if not self.private_key_hex:
42
+ raise ValueError("SM2 decryption requires private_key")
43
+
44
+ # Base64 → bytes
45
+ cipher_bytes: bytes = base64.b64decode(ciphertext)
46
+ plain_bytes: bytes = self.sm2_crypt.decrypt(cipher_bytes)
47
+ return plain_bytes.decode("utf-8")
48
+
49
+ # ---------------- 密钥生成 ---------------- #
50
+ @classmethod
51
+ def generate_keys(cls) -> dict:
52
+ """
53
+ 返回 Base64(HEX) 的公私钥
54
+ """
55
+ private_key_hex = func.random_hex(64) # 256bit
56
+ sm2_crypt = sm2.CryptSM2(private_key=private_key_hex, public_key="")
57
+
58
+ public_key_hex = sm2_crypt._kg(int(private_key_hex, 16), sm2_crypt.ecc_table["g"])
59
+
60
+ return {
61
+ "private_key": base64.b64encode(private_key_hex.encode()).decode(),
62
+ "public_key": base64.b64encode(public_key_hex.encode()).decode(),
63
+ }
@@ -0,0 +1,66 @@
1
+ import base64
2
+ from gmssl.sm4 import CryptSM4, SM4_ENCRYPT, SM4_DECRYPT
3
+
4
+ from ..crypto_algorithm import CryptoAlgorithm
5
+
6
+
7
+ class SM4Algorithm(CryptoAlgorithm):
8
+ """
9
+ SM4 对称加密算法(默认 ECB 模式)
10
+ key: 128-bit(16字节)Base64 字符串
11
+ """
12
+ def __init__(self, key_b64: str, mode: str = "ECB", iv_b64: str | None = None):
13
+ self.key = base64.b64decode(key_b64)
14
+ self.mode = mode.upper()
15
+ self.iv = base64.b64decode(iv_b64) if iv_b64 else None
16
+
17
+ if len(self.key) != 16:
18
+ raise ValueError("SM4 key must be 16 bytes (128-bit).")
19
+
20
+ if self.mode not in ("ECB", "CBC"):
21
+ raise ValueError("SM4 mode must be ECB or CBC")
22
+
23
+ if self.mode == "CBC" and self.iv is None:
24
+ raise ValueError("CBC mode requires iv")
25
+
26
+ # ---------------- 加密 ---------------- #
27
+ def encrypt(self, plaintext: str) -> str:
28
+ crypt = CryptSM4()
29
+ crypt.set_key(self.key, SM4_ENCRYPT)
30
+
31
+ if self.mode == "ECB":
32
+ cipher_bytes = crypt.crypt_ecb(plaintext.encode())
33
+ else:
34
+ cipher_bytes = crypt.crypt_cbc(self.iv, plaintext.encode())
35
+
36
+ return base64.b64encode(cipher_bytes).decode()
37
+
38
+ # ---------------- 解密 ---------------- #
39
+ def decrypt(self, ciphertext: str) -> str:
40
+ crypt = CryptSM4()
41
+ crypt.set_key(self.key, SM4_DECRYPT)
42
+
43
+ cipher_bytes = base64.b64decode(ciphertext)
44
+
45
+ if self.mode == "ECB":
46
+ plain_bytes = crypt.crypt_ecb(cipher_bytes)
47
+ else:
48
+ plain_bytes = crypt.crypt_cbc(self.iv, cipher_bytes)
49
+
50
+ return plain_bytes.decode()
51
+
52
+ # ---------------- 密钥生成 ---------------- #
53
+ @classmethod
54
+ def generate_keys(cls) -> dict:
55
+ """
56
+ 生成 128bit SM4 密钥(Base64 字符串)
57
+ 若需要 CBC 模式,可额外生成16字节IV
58
+ """
59
+ import os
60
+ key = os.urandom(16)
61
+ iv = os.urandom(16)
62
+
63
+ return {
64
+ "key": base64.b64encode(key).decode(),
65
+ "iv": base64.b64encode(iv).decode(),
66
+ }
File without changes
@@ -0,0 +1,39 @@
1
+ import os
2
+ import re
3
+ from typing import Optional, Any
4
+
5
+
6
+ class ExpressionHelper:
7
+ """
8
+ 表达式处理类,用于解析字符串中的环境变量占位符。
9
+ """
10
+ @staticmethod
11
+ def _resolve_env_placeholder(s: str) -> Optional[str]:
12
+ """
13
+ 解析字符串,匹配 ${key[:default_value]} 格式的占位符。
14
+ 如果环境变量存在,则返回其值;
15
+ 如果不存在且有默认值,则返回默认值;
16
+ 如果两者都不存在,则返回 None。
17
+ """
18
+ # 匹配形如 ${key} 或 ${key:default_value}
19
+ pattern = re.compile(r"^\$\{([^:}]+)(?::(.*))?\}$")
20
+ match = pattern.match(s.strip())
21
+ if not match:
22
+ return s # 非占位符格式,原样返回(也可以返回 None 看你需求)
23
+
24
+ key, default = match.groups()
25
+ return os.getenv(key, default)
26
+
27
+ @staticmethod
28
+ def resolve_config(config: dict[str, Any]):
29
+ """
30
+ 解析字符串中的所有环境变量占位符。
31
+ """
32
+ for key, value in config.items():
33
+ if isinstance(value, str):
34
+ resolved_value = ExpressionHelper._resolve_env_placeholder(value)
35
+ if resolved_value is not None:
36
+ config[key] = resolved_value
37
+ elif isinstance(value, dict):
38
+ ExpressionHelper.resolve_config(value)
39
+
@@ -0,0 +1,158 @@
1
+ Metadata-Version: 2.4
2
+ Name: yamlpyconfig
3
+ Version: 0.0.7
4
+ Summary: A unified YAML configuration manager supporting local files and dynamic Nacos configuration with hot-reloading, environment variable substitution, and built-in encryption (SM2/SM4) support.
5
+ Author-email: ferdinand <gongjpa@gmail.com>
6
+ License-Expression: Apache-2.0 OR MIT
7
+ Keywords: aio,application,config,nacos,profile,yaml
8
+ Classifier: Development Status :: 4 - Beta
9
+ Classifier: Intended Audience :: Developers
10
+ Classifier: License :: OSI Approved :: Apache Software License
11
+ Classifier: License :: OSI Approved :: MIT License
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
16
+ Requires-Python: >=3.12
17
+ Requires-Dist: cryptography>=46.0.3
18
+ Requires-Dist: gmssl>=3.2.2
19
+ Requires-Dist: pydantic>=2.12.4
20
+ Requires-Dist: pyyaml>=6.0.3
21
+ Provides-Extra: nacos
22
+ Requires-Dist: nacos-sdk-python>=2.0.9; extra == 'nacos'
23
+ Description-Content-Type: text/markdown
24
+
25
+ # YAML Configuration Management: Local Files + Nacos Dynamic Configuration
26
+
27
+ This project provides a unified YAML configuration loading framework that supports both **local YAML files** and **Nacos configuration center**, with features such as hot updates, environment variable substitution, and encrypted value decoding.
28
+
29
+ Install the core package:
30
+
31
+ ```bash
32
+ pip install yamlpyconfig
33
+ ```
34
+
35
+ If you need Nacos support:
36
+
37
+ ```bash
38
+ pip install yamlpyconfig[nacos]
39
+ ```
40
+
41
+ ---
42
+
43
+ # 1. Local YAML Configuration
44
+
45
+ Your configuration folder (e.g., `/config`) must contain at least:
46
+
47
+ * `application.yaml`
48
+ * Optional: `application-{profile}.yaml`
49
+
50
+ ## 1.1 Profile Resolution Rules
51
+
52
+ The active profile is determined with the following priority (from highest to lowest):
53
+
54
+ 1. Environment variable: `APP_PROFILE`
55
+ 2. Environment variable: `SPRING_PROFILES_ACTIVE`
56
+ 3. The `profile` field inside `application.yaml`
57
+ 4. If none of the above exist → `application-{profile}.yaml` will NOT be loaded
58
+
59
+ ### Notes
60
+
61
+ 1. The configuration directory **must** contain `application.yaml`. Missing this file causes an error.
62
+ 2. If a profile is resolved but `application-{profile}.yaml` does not exist, an exception is raised.
63
+
64
+ ---
65
+
66
+ # 2. Loading Configuration from Nacos
67
+
68
+ To enable Nacos, declare the `config-sources.nacos` section inside your local configuration:
69
+
70
+ ```yaml
71
+ config-sources:
72
+ nacos:
73
+ server-addr: "192.168.30.36:9090"
74
+ namespace: "dev"
75
+ group: "DEFAULT_GROUP"
76
+ username: "nacos"
77
+ password: "{encrypted}VuFvNZOg/q7ZQoIUGWydBw=="
78
+ imports:
79
+ - data-id: "gateway.yaml"
80
+ - data-id: "application-ext.yaml"
81
+ ```
82
+
83
+ ## 2.1 Configuration Merge Priority (Low → High)
84
+
85
+ 1. Local `application.yaml`
86
+ 2. Local `application-{profile}.yaml`
87
+ 3. Nacos imports (following the order declared; later entries override earlier ones)
88
+
89
+ ---
90
+
91
+ # 3. Key Features and Usage Examples
92
+
93
+ ## 3.1 Basic Usage
94
+
95
+ Example: load configuration and print updates automatically:
96
+
97
+ ```python
98
+ @pytest.mark.asyncio
99
+ async def test_config_manager_with_nacos(self):
100
+ async with ConfigManager("./") as config_manager:
101
+ logger.info(config_manager.get_config())
102
+ while True:
103
+ await asyncio.sleep(5)
104
+ logger.info(config_manager.get_config())
105
+ ```
106
+
107
+ When entering the `async with` block:
108
+
109
+ * Local configuration is loaded first
110
+ * If Nacos is configured → it connects automatically and listens for real-time updates
111
+
112
+ ---
113
+
114
+ ## 3.2 Environment Variable Interpolation
115
+
116
+ Local YAML files support Spring-style placeholders:
117
+
118
+ ```yaml
119
+ key-with-default: ${KEY1:DEFAULT_VALUE}
120
+ key: ${KEY2}
121
+ ```
122
+
123
+ Behavior:
124
+
125
+ * If the environment variable exists → its value is used
126
+ * If it does not exist → use the default value after the colon
127
+ * If no default value is provided → `None` is returned
128
+
129
+ ---
130
+
131
+ ## 3.3 Encrypted Field Support (SM2 / SM4)
132
+
133
+ Sensitive fields (passwords, secret keys, etc.) can be encrypted and marked with the `{encrypted}` prefix:
134
+
135
+ ```yaml
136
+ password: "{encrypted}VuFvNZOg/q7ZQoIUGWydBw=="
137
+ ```
138
+
139
+ To enable automatic decryption, specify the algorithm and key when initializing `ConfigManager`:
140
+
141
+ ```python
142
+ @pytest.mark.asyncio
143
+ async def test_config_manager_with_nacos_decrypt(self):
144
+
145
+ # SM4 example — uses a symmetric key
146
+ async with ConfigManager(
147
+ "./",
148
+ crypto_algorithm=AlgorithmEnum.SM4,
149
+ key="lSU543Tes6wmjnb+PMVQNg=="
150
+ ) as config_manager:
151
+
152
+ logger.info(config_manager.get_config())
153
+ ```
154
+
155
+ Explanation:
156
+
157
+ * **SM4** → symmetric encryption (pass the secret key)
158
+ * **SM2** → asymmetric encryption (provide the private key; public key optional depending on use case)
@@ -0,0 +1,26 @@
1
+ yamlpyconfig/__init__.py,sha256=53NhWn8thrhHA8AR6cHbcJzwUeAo345lBRR2-r-8swU,108
2
+ yamlpyconfig/config_cache.py,sha256=MQM0HCcI1foxbHgUvzyb50mlFUeQGxCKkatu5fvB-jM,4121
3
+ yamlpyconfig/config_manager.py,sha256=7jL2NCNzuwkl5DN2qD-_NWd4uv_tlt_d8w3yYEV9xyw,2482
4
+ yamlpyconfig/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ yamlpyconfig/local_manage/__init__.py,sha256=qGkkOp54Uzqv6Fxnax8_lrBIWDnK1LbdPdlPogaT97U,54
6
+ yamlpyconfig/local_manage/local_config_loader.py,sha256=c9s_MhNqMSLduus10Eu-WBLqtkS1_aGQhfk3aAQ5tjw,2241
7
+ yamlpyconfig/local_manage/local_config_manager.py,sha256=NRFESm9UbzNi3rB3TOEZsilvQIQwH7RsjiD0aOf8I4I,2504
8
+ yamlpyconfig/models/__init__.py,sha256=fWKHu_9_tuLt_C5XakxA3QcrmusVUK_A6J18yLxBwGg,199
9
+ yamlpyconfig/models/algorithm_enum.py,sha256=_Yuy3vLuWIvNe3ZKXw84YN_YcDYfOQQVbIm9LIIGtOA,94
10
+ yamlpyconfig/models/nacos_config.py,sha256=RONIWG_4yfxBVqeUVwPvy5WvKg-rjSZttDFlCm_G8UA,1928
11
+ yamlpyconfig/models/nacos_config_cache_item.py,sha256=OVBCMDVrlVAmGO24Exxapr5EfQCcztRSPij80i8eSc4,314
12
+ yamlpyconfig/nacos_manage/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
13
+ yamlpyconfig/nacos_manage/nacos_config_manager.py,sha256=_XJfUFxaO1dMugs-AqmLdl9kj8KTTPuglPWh_HPgCmQ,7364
14
+ yamlpyconfig/utils/__init__.py,sha256=arwOejc4EI303ykHUYmiXQGHgh7Db-BnXFDCFAIpFMc,189
15
+ yamlpyconfig/utils/config_merge.py,sha256=ZPUCtI8x-xJMWWxXeabDKONeGWQB2ZNj8B-OZ8ZlAH4,998
16
+ yamlpyconfig/utils/express_helper.py,sha256=lKFgeLxF06sxwp0FjSqsoZS65OWlFpoX20q3lkYEO70,1421
17
+ yamlpyconfig/utils/crypto/__init__.py,sha256=yz0fg6LIBPknvqasE4_7xjxl_tvrxCe_57UPoRtlNdE,456
18
+ yamlpyconfig/utils/crypto/crypto_algorithm.py,sha256=roAJ-pPI9s4_doZ2GNcr3AxrnNKngO6Zx_hnry2Of_M,748
19
+ yamlpyconfig/utils/crypto/crypto_algorithm_factory.py,sha256=VUZlqWdcr4PuQY8dedSaQQpFSWikkCZMxpukDVtWlsc,970
20
+ yamlpyconfig/utils/crypto/crypto_helper.py,sha256=kUL4qmOjil2pKfSBkmbVjs32PyWGxpdmVOLZK-yZC9w,2662
21
+ yamlpyconfig/utils/crypto/impl/SM2Algorithm.py,sha256=G-lqn2iCCJciTRpD8uwhliGZOg6ipidF23Sonn7Ea-s,2492
22
+ yamlpyconfig/utils/crypto/impl/SM4Algorithm.py,sha256=GiouTWNeg1GmfKueusCwNMbT0OzuBgLFvp8ejWs1rHc,2152
23
+ yamlpyconfig/utils/crypto/impl/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
24
+ yamlpyconfig-0.0.7.dist-info/METADATA,sha256=Y-P3seLPmlFR_6o1BfNBFucinxTR173_UNHsDSC31hs,4665
25
+ yamlpyconfig-0.0.7.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
26
+ yamlpyconfig-0.0.7.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.27.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any