yamlpyconfig 0.0.7__tar.gz
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.
- yamlpyconfig-0.0.7/.gitignore +58 -0
- yamlpyconfig-0.0.7/PKG-INFO +158 -0
- yamlpyconfig-0.0.7/README.md +134 -0
- yamlpyconfig-0.0.7/pyproject.toml +77 -0
- yamlpyconfig-0.0.7/src/yamlpyconfig/__init__.py +7 -0
- yamlpyconfig-0.0.7/src/yamlpyconfig/config_cache.py +98 -0
- yamlpyconfig-0.0.7/src/yamlpyconfig/config_manager.py +57 -0
- yamlpyconfig-0.0.7/src/yamlpyconfig/local_manage/__init__.py +2 -0
- yamlpyconfig-0.0.7/src/yamlpyconfig/local_manage/local_config_loader.py +66 -0
- yamlpyconfig-0.0.7/src/yamlpyconfig/local_manage/local_config_manager.py +62 -0
- yamlpyconfig-0.0.7/src/yamlpyconfig/models/__init__.py +8 -0
- yamlpyconfig-0.0.7/src/yamlpyconfig/models/algorithm_enum.py +6 -0
- yamlpyconfig-0.0.7/src/yamlpyconfig/models/nacos_config.py +36 -0
- yamlpyconfig-0.0.7/src/yamlpyconfig/models/nacos_config_cache_item.py +9 -0
- yamlpyconfig-0.0.7/src/yamlpyconfig/nacos_manage/__init__.py +0 -0
- yamlpyconfig-0.0.7/src/yamlpyconfig/nacos_manage/nacos_config_manager.py +193 -0
- yamlpyconfig-0.0.7/src/yamlpyconfig/py.typed +0 -0
- yamlpyconfig-0.0.7/src/yamlpyconfig/utils/__init__.py +3 -0
- yamlpyconfig-0.0.7/src/yamlpyconfig/utils/config_merge.py +28 -0
- yamlpyconfig-0.0.7/src/yamlpyconfig/utils/crypto/__init__.py +12 -0
- yamlpyconfig-0.0.7/src/yamlpyconfig/utils/crypto/crypto_algorithm.py +28 -0
- yamlpyconfig-0.0.7/src/yamlpyconfig/utils/crypto/crypto_algorithm_factory.py +30 -0
- yamlpyconfig-0.0.7/src/yamlpyconfig/utils/crypto/crypto_helper.py +71 -0
- yamlpyconfig-0.0.7/src/yamlpyconfig/utils/crypto/impl/SM2Algorithm.py +63 -0
- yamlpyconfig-0.0.7/src/yamlpyconfig/utils/crypto/impl/SM4Algorithm.py +66 -0
- yamlpyconfig-0.0.7/src/yamlpyconfig/utils/crypto/impl/__init__.py +0 -0
- yamlpyconfig-0.0.7/src/yamlpyconfig/utils/express_helper.py +39 -0
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
# Compiled class file
|
|
2
|
+
*.class
|
|
3
|
+
|
|
4
|
+
# Log file
|
|
5
|
+
*.log
|
|
6
|
+
|
|
7
|
+
# BlueJ files
|
|
8
|
+
*.ctxt
|
|
9
|
+
|
|
10
|
+
*.ini
|
|
11
|
+
|
|
12
|
+
# Mobile Tools for Java (J2ME)
|
|
13
|
+
.mtj.tmp/
|
|
14
|
+
|
|
15
|
+
# Package Files #
|
|
16
|
+
*.jar
|
|
17
|
+
*.war
|
|
18
|
+
|
|
19
|
+
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
|
|
20
|
+
hs_err_pid*
|
|
21
|
+
|
|
22
|
+
# IDEA or eclipse files #
|
|
23
|
+
.settings/
|
|
24
|
+
.project
|
|
25
|
+
.classpath
|
|
26
|
+
.factorypath
|
|
27
|
+
.idea/
|
|
28
|
+
*.iml
|
|
29
|
+
|
|
30
|
+
# mvn target
|
|
31
|
+
target/
|
|
32
|
+
.mvn/
|
|
33
|
+
|
|
34
|
+
# log files
|
|
35
|
+
logs/
|
|
36
|
+
|
|
37
|
+
# npm files
|
|
38
|
+
node_modules/
|
|
39
|
+
rebel.xml
|
|
40
|
+
|
|
41
|
+
# mac os
|
|
42
|
+
.DS_Store
|
|
43
|
+
|
|
44
|
+
docker-compose/
|
|
45
|
+
finalshell/
|
|
46
|
+
__pycache__/
|
|
47
|
+
nlb-nginx/
|
|
48
|
+
build/
|
|
49
|
+
dist/
|
|
50
|
+
.pytest_cache/
|
|
51
|
+
/royal_tsx/
|
|
52
|
+
deploy_python/
|
|
53
|
+
inis-*/
|
|
54
|
+
logs/
|
|
55
|
+
*.c
|
|
56
|
+
*.key
|
|
57
|
+
*.pem
|
|
58
|
+
nacos-data
|
|
@@ -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,134 @@
|
|
|
1
|
+
# YAML Configuration Management: Local Files + Nacos Dynamic Configuration
|
|
2
|
+
|
|
3
|
+
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.
|
|
4
|
+
|
|
5
|
+
Install the core package:
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
pip install yamlpyconfig
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
If you need Nacos support:
|
|
12
|
+
|
|
13
|
+
```bash
|
|
14
|
+
pip install yamlpyconfig[nacos]
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
---
|
|
18
|
+
|
|
19
|
+
# 1. Local YAML Configuration
|
|
20
|
+
|
|
21
|
+
Your configuration folder (e.g., `/config`) must contain at least:
|
|
22
|
+
|
|
23
|
+
* `application.yaml`
|
|
24
|
+
* Optional: `application-{profile}.yaml`
|
|
25
|
+
|
|
26
|
+
## 1.1 Profile Resolution Rules
|
|
27
|
+
|
|
28
|
+
The active profile is determined with the following priority (from highest to lowest):
|
|
29
|
+
|
|
30
|
+
1. Environment variable: `APP_PROFILE`
|
|
31
|
+
2. Environment variable: `SPRING_PROFILES_ACTIVE`
|
|
32
|
+
3. The `profile` field inside `application.yaml`
|
|
33
|
+
4. If none of the above exist → `application-{profile}.yaml` will NOT be loaded
|
|
34
|
+
|
|
35
|
+
### Notes
|
|
36
|
+
|
|
37
|
+
1. The configuration directory **must** contain `application.yaml`. Missing this file causes an error.
|
|
38
|
+
2. If a profile is resolved but `application-{profile}.yaml` does not exist, an exception is raised.
|
|
39
|
+
|
|
40
|
+
---
|
|
41
|
+
|
|
42
|
+
# 2. Loading Configuration from Nacos
|
|
43
|
+
|
|
44
|
+
To enable Nacos, declare the `config-sources.nacos` section inside your local configuration:
|
|
45
|
+
|
|
46
|
+
```yaml
|
|
47
|
+
config-sources:
|
|
48
|
+
nacos:
|
|
49
|
+
server-addr: "192.168.30.36:9090"
|
|
50
|
+
namespace: "dev"
|
|
51
|
+
group: "DEFAULT_GROUP"
|
|
52
|
+
username: "nacos"
|
|
53
|
+
password: "{encrypted}VuFvNZOg/q7ZQoIUGWydBw=="
|
|
54
|
+
imports:
|
|
55
|
+
- data-id: "gateway.yaml"
|
|
56
|
+
- data-id: "application-ext.yaml"
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
## 2.1 Configuration Merge Priority (Low → High)
|
|
60
|
+
|
|
61
|
+
1. Local `application.yaml`
|
|
62
|
+
2. Local `application-{profile}.yaml`
|
|
63
|
+
3. Nacos imports (following the order declared; later entries override earlier ones)
|
|
64
|
+
|
|
65
|
+
---
|
|
66
|
+
|
|
67
|
+
# 3. Key Features and Usage Examples
|
|
68
|
+
|
|
69
|
+
## 3.1 Basic Usage
|
|
70
|
+
|
|
71
|
+
Example: load configuration and print updates automatically:
|
|
72
|
+
|
|
73
|
+
```python
|
|
74
|
+
@pytest.mark.asyncio
|
|
75
|
+
async def test_config_manager_with_nacos(self):
|
|
76
|
+
async with ConfigManager("./") as config_manager:
|
|
77
|
+
logger.info(config_manager.get_config())
|
|
78
|
+
while True:
|
|
79
|
+
await asyncio.sleep(5)
|
|
80
|
+
logger.info(config_manager.get_config())
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
When entering the `async with` block:
|
|
84
|
+
|
|
85
|
+
* Local configuration is loaded first
|
|
86
|
+
* If Nacos is configured → it connects automatically and listens for real-time updates
|
|
87
|
+
|
|
88
|
+
---
|
|
89
|
+
|
|
90
|
+
## 3.2 Environment Variable Interpolation
|
|
91
|
+
|
|
92
|
+
Local YAML files support Spring-style placeholders:
|
|
93
|
+
|
|
94
|
+
```yaml
|
|
95
|
+
key-with-default: ${KEY1:DEFAULT_VALUE}
|
|
96
|
+
key: ${KEY2}
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
Behavior:
|
|
100
|
+
|
|
101
|
+
* If the environment variable exists → its value is used
|
|
102
|
+
* If it does not exist → use the default value after the colon
|
|
103
|
+
* If no default value is provided → `None` is returned
|
|
104
|
+
|
|
105
|
+
---
|
|
106
|
+
|
|
107
|
+
## 3.3 Encrypted Field Support (SM2 / SM4)
|
|
108
|
+
|
|
109
|
+
Sensitive fields (passwords, secret keys, etc.) can be encrypted and marked with the `{encrypted}` prefix:
|
|
110
|
+
|
|
111
|
+
```yaml
|
|
112
|
+
password: "{encrypted}VuFvNZOg/q7ZQoIUGWydBw=="
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
To enable automatic decryption, specify the algorithm and key when initializing `ConfigManager`:
|
|
116
|
+
|
|
117
|
+
```python
|
|
118
|
+
@pytest.mark.asyncio
|
|
119
|
+
async def test_config_manager_with_nacos_decrypt(self):
|
|
120
|
+
|
|
121
|
+
# SM4 example — uses a symmetric key
|
|
122
|
+
async with ConfigManager(
|
|
123
|
+
"./",
|
|
124
|
+
crypto_algorithm=AlgorithmEnum.SM4,
|
|
125
|
+
key="lSU543Tes6wmjnb+PMVQNg=="
|
|
126
|
+
) as config_manager:
|
|
127
|
+
|
|
128
|
+
logger.info(config_manager.get_config())
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
Explanation:
|
|
132
|
+
|
|
133
|
+
* **SM4** → symmetric encryption (pass the secret key)
|
|
134
|
+
* **SM2** → asymmetric encryption (provide the private key; public key optional depending on use case)
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "yamlpyconfig"
|
|
3
|
+
dynamic = ["version"]
|
|
4
|
+
description = "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
|
+
requires-python = ">=3.12"
|
|
6
|
+
dependencies = [
|
|
7
|
+
"cryptography>=46.0.3",
|
|
8
|
+
"gmssl>=3.2.2",
|
|
9
|
+
"pydantic>=2.12.4",
|
|
10
|
+
"pyyaml>=6.0.3",
|
|
11
|
+
]
|
|
12
|
+
|
|
13
|
+
# 协议信息
|
|
14
|
+
license = "Apache-2.0 OR MIT"
|
|
15
|
+
authors = [
|
|
16
|
+
{ name = "ferdinand", email = "gongjpa@gmail.com" },
|
|
17
|
+
]
|
|
18
|
+
# 关键字方便快速检索
|
|
19
|
+
keywords = [
|
|
20
|
+
"yaml", "config", "nacos", "aio", "application", "profile"
|
|
21
|
+
]
|
|
22
|
+
readme = "README.md"
|
|
23
|
+
|
|
24
|
+
# 可以到网站https://pypi.org/classifiers/查找合适的classifiers
|
|
25
|
+
classifiers = [
|
|
26
|
+
"Development Status :: 4 - Beta",
|
|
27
|
+
"Intended Audience :: Developers",
|
|
28
|
+
"License :: OSI Approved :: Apache Software License",
|
|
29
|
+
"License :: OSI Approved :: MIT License",
|
|
30
|
+
"Operating System :: OS Independent",
|
|
31
|
+
"Programming Language :: Python :: 3",
|
|
32
|
+
"Programming Language :: Python :: 3.12",
|
|
33
|
+
"Topic :: Software Development :: Libraries :: Python Modules",
|
|
34
|
+
]
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
[project.optional-dependencies]
|
|
38
|
+
nacos = [
|
|
39
|
+
"nacos-sdk-python>=2.0.9",
|
|
40
|
+
]
|
|
41
|
+
|
|
42
|
+
[dependency-groups]
|
|
43
|
+
dev = [
|
|
44
|
+
"pytest>=9.0.1",
|
|
45
|
+
"pytest-asyncio>=1.3.0",
|
|
46
|
+
]
|
|
47
|
+
|
|
48
|
+
[tool.uv]
|
|
49
|
+
default-groups = ["dev"]
|
|
50
|
+
|
|
51
|
+
[build-system]
|
|
52
|
+
requires = ["hatchling"]
|
|
53
|
+
build-backend = "hatchling.build"
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
# === 关键配置: 指定包的位置 ===
|
|
57
|
+
# 告诉 hatchling,真正得包代码在 src 目录下
|
|
58
|
+
[tool.hatch.build.targets.wheel]
|
|
59
|
+
packages = ["src/yamlpyconfig"]
|
|
60
|
+
|
|
61
|
+
[tool.hatch.build.targets.sdist]
|
|
62
|
+
# 明确指定 sdist 只包含 src 目录,排除 test 目录等其他根目录文件
|
|
63
|
+
include = [
|
|
64
|
+
"src",
|
|
65
|
+
# 建议也包含 README 和 LICENSE,否则 pip 安装有时会发出警告
|
|
66
|
+
"README.md",
|
|
67
|
+
"pyproject.toml"
|
|
68
|
+
]
|
|
69
|
+
|
|
70
|
+
[tool.hatch.version]
|
|
71
|
+
path = "src/yamlpyconfig/__init__.py"
|
|
72
|
+
|
|
73
|
+
[[tool.uv.index]]
|
|
74
|
+
name = "testpypi"
|
|
75
|
+
url = "https://test.pypi.org/simple/"
|
|
76
|
+
publish-url = "https://test.pypi.org/legacy/"
|
|
77
|
+
explicit = true
|
|
@@ -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,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
|
+
|