nya-proxy 0.2.3__tar.gz → 0.2.5__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.
- {nya_proxy-0.2.3 → nya_proxy-0.2.5}/PKG-INFO +10 -13
- {nya_proxy-0.2.3 → nya_proxy-0.2.5}/README.md +5 -9
- {nya_proxy-0.2.3 → nya_proxy-0.2.5}/nya/__init__.py +28 -6
- nya_proxy-0.2.5/nya/_version.py +1 -0
- {nya_proxy-0.2.3 → nya_proxy-0.2.5}/nya/common/constants.py +14 -0
- {nya_proxy-0.2.3 → nya_proxy-0.2.5}/nya/common/models.py +4 -14
- nya_proxy-0.2.5/nya/config/__init__.py +5 -0
- {nya_proxy-0.2.3 → nya_proxy-0.2.5}/nya/config/manager.py +60 -106
- {nya_proxy-0.2.3 → nya_proxy-0.2.5}/nya/config.yaml +3 -9
- {nya_proxy-0.2.3 → nya_proxy-0.2.5}/nya/core/factory.py +12 -20
- {nya_proxy-0.2.3 → nya_proxy-0.2.5}/nya/core/handler.py +14 -14
- {nya_proxy-0.2.3 → nya_proxy-0.2.5}/nya/core/proxy.py +21 -27
- {nya_proxy-0.2.3 → nya_proxy-0.2.5}/nya/core/request.py +33 -75
- {nya_proxy-0.2.3 → nya_proxy-0.2.5}/nya/core/response.py +14 -31
- nya_proxy-0.2.5/nya/core/streaming.py +123 -0
- {nya_proxy-0.2.3 → nya_proxy-0.2.5}/nya/dashboard/api.py +13 -17
- {nya_proxy-0.2.3 → nya_proxy-0.2.5}/nya/html/login.html +46 -100
- {nya_proxy-0.2.3 → nya_proxy-0.2.5}/nya/schema.json +3 -39
- {nya_proxy-0.2.3 → nya_proxy-0.2.5}/nya/server/app.py +106 -100
- {nya_proxy-0.2.3 → nya_proxy-0.2.5}/nya/server/auth.py +2 -4
- {nya_proxy-0.2.3 → nya_proxy-0.2.5}/nya/services/key.py +9 -10
- {nya_proxy-0.2.3 → nya_proxy-0.2.5}/nya/services/lb.py +5 -11
- {nya_proxy-0.2.3 → nya_proxy-0.2.5}/nya/services/limit.py +32 -21
- {nya_proxy-0.2.3 → nya_proxy-0.2.5}/nya/services/metrics.py +6 -4
- {nya_proxy-0.2.3 → nya_proxy-0.2.5}/nya/services/queue.py +26 -33
- {nya_proxy-0.2.3 → nya_proxy-0.2.5}/nya/utils/header.py +2 -5
- {nya_proxy-0.2.3 → nya_proxy-0.2.5}/nya_proxy.egg-info/PKG-INFO +10 -13
- {nya_proxy-0.2.3 → nya_proxy-0.2.5}/nya_proxy.egg-info/SOURCES.txt +0 -6
- {nya_proxy-0.2.3 → nya_proxy-0.2.5}/nya_proxy.egg-info/requires.txt +2 -2
- {nya_proxy-0.2.3 → nya_proxy-0.2.5}/pyproject.toml +5 -4
- nya_proxy-0.2.3/nya/_version.py +0 -1
- nya_proxy-0.2.3/nya/common/logger.py +0 -173
- nya_proxy-0.2.3/nya/config/__init__.py +0 -6
- nya_proxy-0.2.3/nya/core/streaming.py +0 -271
- nya_proxy-0.2.3/nya/integrations/openai.py +0 -193
- nya_proxy-0.2.3/nya/utils/__init__.py +0 -0
- {nya_proxy-0.2.3 → nya_proxy-0.2.5}/LICENSE +0 -0
- {nya_proxy-0.2.3 → nya_proxy-0.2.5}/nya/common/__init__.py +0 -0
- {nya_proxy-0.2.3 → nya_proxy-0.2.5}/nya/common/exceptions.py +0 -0
- {nya_proxy-0.2.3 → nya_proxy-0.2.5}/nya/core/__init__.py +0 -0
- {nya_proxy-0.2.3 → nya_proxy-0.2.5}/nya/dashboard/__init__.py +0 -0
- {nya_proxy-0.2.3 → nya_proxy-0.2.5}/nya/html/favicon.ico +0 -0
- {nya_proxy-0.2.3 → nya_proxy-0.2.5}/nya/html/index.html +0 -0
- {nya_proxy-0.2.3 → nya_proxy-0.2.5}/nya/html/static/css/styles.css +0 -0
- {nya_proxy-0.2.3 → nya_proxy-0.2.5}/nya/html/static/js/dashboard.js +0 -0
- {nya_proxy-0.2.3 → nya_proxy-0.2.5}/nya/html/static/logo.svg +0 -0
- {nya_proxy-0.2.3/nya/integrations → nya_proxy-0.2.5/nya/server}/__init__.py +0 -0
- {nya_proxy-0.2.3/nya/server → nya_proxy-0.2.5/nya/services}/__init__.py +0 -0
- {nya_proxy-0.2.3/nya/services → nya_proxy-0.2.5/nya/utils}/__init__.py +0 -0
- {nya_proxy-0.2.3 → nya_proxy-0.2.5}/nya/utils/helper.py +0 -0
- {nya_proxy-0.2.3 → nya_proxy-0.2.5}/nya_proxy.egg-info/dependency_links.txt +0 -0
- {nya_proxy-0.2.3 → nya_proxy-0.2.5}/nya_proxy.egg-info/entry_points.txt +0 -0
- {nya_proxy-0.2.3 → nya_proxy-0.2.5}/nya_proxy.egg-info/top_level.txt +0 -0
- {nya_proxy-0.2.3 → nya_proxy-0.2.5}/setup.cfg +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: nya-proxy
|
|
3
|
-
Version: 0.2.
|
|
3
|
+
Version: 0.2.5
|
|
4
4
|
Summary: A lightweight, flexible API proxy with dynamic token rotation, load balancing, and rate limiting capabilities.
|
|
5
5
|
Author-email: "Nya Foundation Team (k3scat)" <k3scat@gmail.com>
|
|
6
6
|
License-Expression: MIT
|
|
@@ -9,10 +9,11 @@ Project-URL: Bug Tracker, https://github.com/Nya-Foundation/nyaproxy/issues
|
|
|
9
9
|
Classifier: Development Status :: 4 - Beta
|
|
10
10
|
Classifier: Intended Audience :: Developers
|
|
11
11
|
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
12
13
|
Classifier: Programming Language :: Python :: 3.11
|
|
13
14
|
Classifier: Programming Language :: Python :: 3.12
|
|
14
15
|
Classifier: Programming Language :: Python :: 3.13
|
|
15
|
-
Requires-Python: >=3.
|
|
16
|
+
Requires-Python: >=3.10
|
|
16
17
|
Description-Content-Type: text/markdown
|
|
17
18
|
License-File: LICENSE
|
|
18
19
|
Requires-Dist: fastapi>=0.95.0
|
|
@@ -24,9 +25,9 @@ Requires-Dist: setuptools>=42.0.0
|
|
|
24
25
|
Requires-Dist: watchfiles>=0.18.0
|
|
25
26
|
Requires-Dist: brotli>=1.0.9
|
|
26
27
|
Requires-Dist: jmespath>=1.0.1
|
|
27
|
-
Requires-Dist: colorlog>=6.9.0
|
|
28
28
|
Requires-Dist: orjson<4,>=3.10
|
|
29
|
-
Requires-Dist:
|
|
29
|
+
Requires-Dist: loguru>=0.7.0
|
|
30
|
+
Requires-Dist: nekoconf[remote,schema,server]==1.1.1
|
|
30
31
|
Provides-Extra: dev
|
|
31
32
|
Requires-Dist: pytest>=7.0.0; extra == "dev"
|
|
32
33
|
Requires-Dist: pytest-asyncio>=0.21.0; extra == "dev"
|
|
@@ -83,8 +84,6 @@ Here's how NyaProxy can help:
|
|
|
83
84
|
| 🕵️ Request Masking | Dynamic header substitution across multiple identity providers | `headers` + `variables` |
|
|
84
85
|
| 📊 Real-time Metrics | Interactive dashboard with request analytics and system health | `dashboard` |
|
|
85
86
|
| 🔧 Body Substitution | Dynamic JSON payload transformation using JSONPath | `request_body_substitution` |
|
|
86
|
-
| 🔄 Simulated Streaming | Stream chunked responses for better UX | `simulated_streaming` |
|
|
87
|
-
|
|
88
87
|
|
|
89
88
|
## 📥 Quick Start
|
|
90
89
|
|
|
@@ -204,6 +203,11 @@ server:
|
|
|
204
203
|
enabled: true
|
|
205
204
|
max_size: 200
|
|
206
205
|
expiry_seconds: 300
|
|
206
|
+
cors:
|
|
207
|
+
allow_origins: ["*"] # Set to "*" to allow all origins, however, when allow_credentials is true, this must be set to a specific origin
|
|
208
|
+
allow_credentials: true
|
|
209
|
+
allow_methods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"]
|
|
210
|
+
allow_headers: ["*"]
|
|
207
211
|
|
|
208
212
|
# Default settings for the all apis if not specified
|
|
209
213
|
default_settings:
|
|
@@ -223,13 +227,6 @@ default_settings:
|
|
|
223
227
|
retry_status_codes: [ 429, 500, 502, 503, 504 ]
|
|
224
228
|
timeouts:
|
|
225
229
|
request_timeout_seconds: 300
|
|
226
|
-
# Simulated streaming settings
|
|
227
|
-
simulated_streaming:
|
|
228
|
-
enabled: false
|
|
229
|
-
delay_seconds: 0.2 # Delay between chunks in seconds
|
|
230
|
-
init_delay_seconds: 0.5 # Initial delay before starting streaming in seconds
|
|
231
|
-
chunk_size_bytes: 256 # Size of each chunk in bytes
|
|
232
|
-
apply_to: ["application/json", "application/xml", "text/plain", "image/png", "image/jpeg"] # Response content types to apply simulated streaming to
|
|
233
230
|
|
|
234
231
|
# API configurations, each API can have its own settings, but will inherit from default_settings if not specified
|
|
235
232
|
apis:
|
|
@@ -42,8 +42,6 @@ Here's how NyaProxy can help:
|
|
|
42
42
|
| 🕵️ Request Masking | Dynamic header substitution across multiple identity providers | `headers` + `variables` |
|
|
43
43
|
| 📊 Real-time Metrics | Interactive dashboard with request analytics and system health | `dashboard` |
|
|
44
44
|
| 🔧 Body Substitution | Dynamic JSON payload transformation using JSONPath | `request_body_substitution` |
|
|
45
|
-
| 🔄 Simulated Streaming | Stream chunked responses for better UX | `simulated_streaming` |
|
|
46
|
-
|
|
47
45
|
|
|
48
46
|
## 📥 Quick Start
|
|
49
47
|
|
|
@@ -163,6 +161,11 @@ server:
|
|
|
163
161
|
enabled: true
|
|
164
162
|
max_size: 200
|
|
165
163
|
expiry_seconds: 300
|
|
164
|
+
cors:
|
|
165
|
+
allow_origins: ["*"] # Set to "*" to allow all origins, however, when allow_credentials is true, this must be set to a specific origin
|
|
166
|
+
allow_credentials: true
|
|
167
|
+
allow_methods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"]
|
|
168
|
+
allow_headers: ["*"]
|
|
166
169
|
|
|
167
170
|
# Default settings for the all apis if not specified
|
|
168
171
|
default_settings:
|
|
@@ -182,13 +185,6 @@ default_settings:
|
|
|
182
185
|
retry_status_codes: [ 429, 500, 502, 503, 504 ]
|
|
183
186
|
timeouts:
|
|
184
187
|
request_timeout_seconds: 300
|
|
185
|
-
# Simulated streaming settings
|
|
186
|
-
simulated_streaming:
|
|
187
|
-
enabled: false
|
|
188
|
-
delay_seconds: 0.2 # Delay between chunks in seconds
|
|
189
|
-
init_delay_seconds: 0.5 # Initial delay before starting streaming in seconds
|
|
190
|
-
chunk_size_bytes: 256 # Size of each chunk in bytes
|
|
191
|
-
apply_to: ["application/json", "application/xml", "text/plain", "image/png", "image/jpeg"] # Response content types to apply simulated streaming to
|
|
192
188
|
|
|
193
189
|
# API configurations, each API can have its own settings, but will inherit from default_settings if not specified
|
|
194
190
|
apis:
|
|
@@ -3,11 +3,23 @@ NyaProxy - A cute and simple low-level API proxy with dynamic token rotation.
|
|
|
3
3
|
"""
|
|
4
4
|
|
|
5
5
|
from ._version import __version__
|
|
6
|
-
from .common.
|
|
7
|
-
|
|
6
|
+
from .common.exceptions import (
|
|
7
|
+
APIConfigError,
|
|
8
|
+
APIKeyExhaustedError,
|
|
9
|
+
ConfigurationError,
|
|
10
|
+
ConnectionError,
|
|
11
|
+
EndpointRateLimitExceededError,
|
|
12
|
+
NyaProxyError,
|
|
13
|
+
QueueFullError,
|
|
14
|
+
RequestExpiredError,
|
|
15
|
+
TimeoutError,
|
|
16
|
+
UnknownAPIError,
|
|
17
|
+
VariablesConfigurationError,
|
|
18
|
+
)
|
|
19
|
+
from .common.models import ProxyRequest
|
|
8
20
|
|
|
9
21
|
# Import key components for easier access
|
|
10
|
-
from .config.manager import
|
|
22
|
+
from .config.manager import ConfigManager
|
|
11
23
|
from .core.proxy import NyaProxyCore
|
|
12
24
|
from .core.request import RequestExecutor
|
|
13
25
|
from .core.response import ResponseProcessor
|
|
@@ -24,13 +36,12 @@ from .utils.helper import format_elapsed_time
|
|
|
24
36
|
__all__ = [
|
|
25
37
|
# Core application
|
|
26
38
|
"ConfigManager",
|
|
27
|
-
"ConfigError",
|
|
28
39
|
"DashboardAPI",
|
|
29
40
|
"HeaderUtils",
|
|
30
41
|
"KeyManager",
|
|
31
42
|
"LoadBalancer",
|
|
32
43
|
"MetricsCollector",
|
|
33
|
-
"
|
|
44
|
+
"ProxyRequest",
|
|
34
45
|
"NyaProxyCore",
|
|
35
46
|
"RateLimiter",
|
|
36
47
|
"RequestExecutor",
|
|
@@ -38,7 +49,18 @@ __all__ = [
|
|
|
38
49
|
"ResponseProcessor",
|
|
39
50
|
# Utilities
|
|
40
51
|
"format_elapsed_time",
|
|
41
|
-
|
|
52
|
+
# Exceptions
|
|
53
|
+
"NyaProxyError",
|
|
54
|
+
"ConfigurationError",
|
|
55
|
+
"VariablesConfigurationError",
|
|
56
|
+
"EndpointRateLimitExceededError",
|
|
57
|
+
"QueueFullError",
|
|
58
|
+
"RequestExpiredError",
|
|
59
|
+
"APIKeyExhaustedError",
|
|
60
|
+
"APIConfigError",
|
|
61
|
+
"UnknownAPIError",
|
|
62
|
+
"ConnectionError",
|
|
63
|
+
"TimeoutError",
|
|
42
64
|
# Version
|
|
43
65
|
"__version__",
|
|
44
66
|
]
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.2.5"
|
|
@@ -28,7 +28,21 @@ EXCLUDED_REQUEST_HEADERS = {
|
|
|
28
28
|
"x-forwarded-port",
|
|
29
29
|
"x-forwarded-server",
|
|
30
30
|
"x-real-ip",
|
|
31
|
+
# Cloudflare headers
|
|
32
|
+
"cf-connecting-ip",
|
|
33
|
+
"cf-connecting-ipv6",
|
|
34
|
+
"cf-ew-via",
|
|
35
|
+
"cf-pseudo-ipv4",
|
|
36
|
+
"true-client-ip",
|
|
37
|
+
"cf-ray",
|
|
38
|
+
"cf-ipcountry",
|
|
39
|
+
"cf-visitor",
|
|
40
|
+
"cdn-loop",
|
|
41
|
+
"cf-worker",
|
|
31
42
|
}
|
|
32
43
|
|
|
33
44
|
# Metrics
|
|
34
45
|
MAX_QUEUE_SIZE = 200
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
WATCH_FILE = "watch_file.txt"
|
|
@@ -22,21 +22,13 @@ class AdvancedConfig:
|
|
|
22
22
|
response.
|
|
23
23
|
"""
|
|
24
24
|
|
|
25
|
-
# Simulated Streaming
|
|
26
|
-
simulated_stream_enabled: bool = False
|
|
27
|
-
delay_seconds: float = 0.2
|
|
28
|
-
init_delay_seconds: float = 0.5
|
|
29
|
-
chunk_size_bytes: int = 256
|
|
30
|
-
# List of response content types to apply simulated streaming to
|
|
31
|
-
apply_to: List[str] = field(default_factory=lambda: ["application/json"])
|
|
32
|
-
|
|
33
25
|
# Request Body Substitution
|
|
34
26
|
req_body_subst_enabled: bool = False
|
|
35
27
|
subst_rules: List[Dict[str, Any]] = field(default_factory=list)
|
|
36
28
|
|
|
37
29
|
|
|
38
30
|
@dataclass
|
|
39
|
-
class
|
|
31
|
+
class ProxyRequest:
|
|
40
32
|
"""
|
|
41
33
|
Structured representation of an API request for processing.
|
|
42
34
|
|
|
@@ -72,17 +64,15 @@ class NyaRequest:
|
|
|
72
64
|
# Whether to apply rate limiting for this request
|
|
73
65
|
_apply_rate_limit: bool = True
|
|
74
66
|
|
|
75
|
-
# Whether the original request ask for a streaming response (openai)
|
|
76
|
-
_is_streaming: bool = False
|
|
77
67
|
_config: AdvancedConfig = field(default_factory=AdvancedConfig)
|
|
78
68
|
|
|
79
69
|
@staticmethod
|
|
80
|
-
async def from_request(request: "Request") -> "
|
|
70
|
+
async def from_request(request: "Request") -> "ProxyRequest":
|
|
81
71
|
"""
|
|
82
|
-
Create a
|
|
72
|
+
Create a ProxyRequest instance from a FastAPI Request object.
|
|
83
73
|
"""
|
|
84
74
|
|
|
85
|
-
return
|
|
75
|
+
return ProxyRequest(
|
|
86
76
|
method=request.method,
|
|
87
77
|
_url=request.url,
|
|
88
78
|
headers=dict(request.headers),
|
|
@@ -2,18 +2,14 @@
|
|
|
2
2
|
Configuration manager for NyaProxy using NekoConf.
|
|
3
3
|
"""
|
|
4
4
|
|
|
5
|
-
import logging
|
|
6
5
|
import os
|
|
7
6
|
from typing import Any, Callable, Dict, Generic, List, Optional, TypeVar, Union, cast
|
|
8
7
|
|
|
9
|
-
from
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
class ConfigError(Exception):
|
|
13
|
-
"""Exception raised for configuration errors."""
|
|
14
|
-
|
|
15
|
-
pass
|
|
8
|
+
from loguru import logger
|
|
9
|
+
from nekoconf import NekoConf, NekoConfOrchestrator
|
|
10
|
+
from nekoconf.storage import FileStorageBackend, RemoteStorageBackend
|
|
16
11
|
|
|
12
|
+
from nya.common.exceptions import ConfigurationError
|
|
17
13
|
|
|
18
14
|
T = TypeVar("T")
|
|
19
15
|
|
|
@@ -82,7 +78,8 @@ class ConfigManager:
|
|
|
82
78
|
schema_path: Optional[str] = None,
|
|
83
79
|
remote_url: Optional[str] = None,
|
|
84
80
|
remote_api_key: Optional[str] = None,
|
|
85
|
-
|
|
81
|
+
remote_app_name: Optional[str] = None,
|
|
82
|
+
callback: Optional[Callable] = None,
|
|
86
83
|
):
|
|
87
84
|
"""
|
|
88
85
|
Initialize the configuration manager (once).
|
|
@@ -92,27 +89,29 @@ class ConfigManager:
|
|
|
92
89
|
schema_file: Path to the schema file for validation (optional)
|
|
93
90
|
remote_url: URL for remote configuration (optional)
|
|
94
91
|
remote_api_key: API key for remote configuration (optional)
|
|
95
|
-
|
|
92
|
+
remote_app_name: Name of the application for remote configuration (optional)
|
|
93
|
+
callback: Callback function to call after configuraiton is updated (optional)
|
|
96
94
|
"""
|
|
97
95
|
# Skip initialization if already initialized
|
|
98
96
|
if self._initialized:
|
|
99
97
|
return
|
|
100
98
|
|
|
101
|
-
self.config:
|
|
102
|
-
self.server:
|
|
99
|
+
self.config: NekoConf = None
|
|
100
|
+
self.server: NekoConfOrchestrator = None
|
|
103
101
|
|
|
104
102
|
self.config_path = config_path
|
|
105
103
|
self.schema_path = schema_path
|
|
106
104
|
self.remote_url = remote_url
|
|
107
105
|
self.remote_api_key = remote_api_key
|
|
106
|
+
self.remote_app_name = remote_app_name
|
|
108
107
|
|
|
109
|
-
self.
|
|
108
|
+
self.callback = callback
|
|
110
109
|
|
|
111
110
|
if config_path and not os.path.exists(config_path):
|
|
112
|
-
raise
|
|
111
|
+
raise ConfigurationError(f"Configuration file not found: {config_path}")
|
|
113
112
|
|
|
114
|
-
self.config = self.
|
|
115
|
-
self.server = self.
|
|
113
|
+
self.config = self.init_config_client()
|
|
114
|
+
self.server = self.init_config_server()
|
|
116
115
|
|
|
117
116
|
# Mark as initialized
|
|
118
117
|
ConfigManager._initialized = True
|
|
@@ -130,46 +129,64 @@ class ConfigManager:
|
|
|
130
129
|
cls._instance = ConfigManager()
|
|
131
130
|
return cls._instance
|
|
132
131
|
|
|
133
|
-
def
|
|
134
|
-
"""Initialize the
|
|
135
|
-
|
|
136
|
-
|
|
132
|
+
def init_config_client(self) -> NekoConf:
|
|
133
|
+
"""Initialize the NekoConf."""
|
|
134
|
+
|
|
135
|
+
storage: Union[FileStorageBackend, RemoteStorageBackend, None] = None
|
|
136
|
+
|
|
137
|
+
if self.remote_url:
|
|
138
|
+
storage = RemoteStorageBackend(
|
|
139
|
+
remote_url=self.remote_url,
|
|
140
|
+
api_key=self.remote_api_key,
|
|
141
|
+
app_name=self.remote_app_name or "default",
|
|
142
|
+
logger=logger,
|
|
143
|
+
)
|
|
144
|
+
|
|
145
|
+
else:
|
|
146
|
+
storage = FileStorageBackend(config_path=self.config_path, logger=logger)
|
|
147
|
+
|
|
148
|
+
storage.set_change_callback(self.callback)
|
|
149
|
+
|
|
150
|
+
if not storage:
|
|
151
|
+
raise ConfigurationError(
|
|
152
|
+
"No storage backend configured. Please set a config path or remote URL."
|
|
153
|
+
)
|
|
154
|
+
|
|
155
|
+
client = NekoConf(
|
|
156
|
+
storage=storage,
|
|
137
157
|
schema_path=self.schema_path,
|
|
158
|
+
logger=logger,
|
|
138
159
|
env_override_enabled=True,
|
|
139
160
|
env_prefix="NYA",
|
|
140
|
-
remote_url=self.remote_url,
|
|
141
|
-
remote_api_key=self.remote_api_key,
|
|
142
|
-
logger=self.logger,
|
|
143
161
|
)
|
|
144
162
|
|
|
145
163
|
# Validate against the schema
|
|
146
164
|
results = client.validate()
|
|
147
165
|
if results:
|
|
148
|
-
raise
|
|
166
|
+
raise ConfigurationError(f"Configuration validation failed: {results}")
|
|
149
167
|
|
|
150
|
-
|
|
168
|
+
logger.info("Configuration loaded and validated successfully")
|
|
151
169
|
return client
|
|
152
170
|
|
|
153
|
-
def
|
|
171
|
+
def init_config_server(self) -> NekoConfOrchestrator:
|
|
154
172
|
|
|
155
173
|
if self.remote_url is not None:
|
|
156
|
-
|
|
157
|
-
"Remote Config URL is set.
|
|
174
|
+
logger.warning(
|
|
175
|
+
"Remote Config URL is set. NekoConfOrchestrator will not be initialized on this local instance."
|
|
158
176
|
)
|
|
159
177
|
return None
|
|
160
178
|
|
|
161
179
|
if self.config is None:
|
|
162
|
-
|
|
180
|
+
logger.debug("ConfigManager is not initialized. skipping server init.")
|
|
163
181
|
return None
|
|
164
182
|
|
|
165
183
|
try:
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
)
|
|
184
|
+
nya_app = {"NyaProxy": self.config}
|
|
185
|
+
server = NekoConfOrchestrator(apps=nya_app, logger=logger)
|
|
169
186
|
except Exception as e:
|
|
170
|
-
error_msg = f"Failed to load configuration
|
|
171
|
-
|
|
172
|
-
raise
|
|
187
|
+
error_msg = f"Failed to load configuration: {str(e)}"
|
|
188
|
+
logger.error(error_msg)
|
|
189
|
+
raise ConfigurationError(error_msg)
|
|
173
190
|
|
|
174
191
|
return server
|
|
175
192
|
|
|
@@ -236,7 +253,7 @@ class ConfigManager:
|
|
|
236
253
|
"""
|
|
237
254
|
apis = self.config.get_dict("apis", {})
|
|
238
255
|
if not apis:
|
|
239
|
-
raise
|
|
256
|
+
raise ConfigurationError("No APIs configured. Please add at least one API.")
|
|
240
257
|
|
|
241
258
|
return apis
|
|
242
259
|
|
|
@@ -351,62 +368,6 @@ class ConfigManager:
|
|
|
351
368
|
else: # Default to string
|
|
352
369
|
return self.config.get_str(f"apis.{api_name}.{setting_path}", default_value)
|
|
353
370
|
|
|
354
|
-
# API Setting Descriptors
|
|
355
|
-
get_api_simulated_streaming_enabled = ApiSettingDescriptor[bool](
|
|
356
|
-
"simulated_streaming.enabled",
|
|
357
|
-
"bool",
|
|
358
|
-
"""Get simulated streaming enabled status for an API.
|
|
359
|
-
Args:
|
|
360
|
-
api_name: Name of the API
|
|
361
|
-
Returns:
|
|
362
|
-
Boolean indicating if simulated streaming is enabled
|
|
363
|
-
""",
|
|
364
|
-
)
|
|
365
|
-
|
|
366
|
-
get_api_simulated_streaming_delay = ApiSettingDescriptor[int](
|
|
367
|
-
"simulated_streaming.delay_seconds",
|
|
368
|
-
"int",
|
|
369
|
-
"""Get simulated streaming delay in seconds.
|
|
370
|
-
Args:
|
|
371
|
-
api_name: Name of the API
|
|
372
|
-
Returns:
|
|
373
|
-
Delay in seconds
|
|
374
|
-
""",
|
|
375
|
-
)
|
|
376
|
-
|
|
377
|
-
get_api_simulated_streaming_init_delay = ApiSettingDescriptor[int](
|
|
378
|
-
"simulated_streaming.init_delay_seconds",
|
|
379
|
-
"int",
|
|
380
|
-
"""Get initial delay for simulated streaming.
|
|
381
|
-
Args:
|
|
382
|
-
api_name: Name of the API
|
|
383
|
-
Returns:
|
|
384
|
-
Initial delay in seconds
|
|
385
|
-
""",
|
|
386
|
-
)
|
|
387
|
-
|
|
388
|
-
get_api_simulated_streaming_chunk_size = ApiSettingDescriptor[int](
|
|
389
|
-
"simulated_streaming.chunk_size_bytes",
|
|
390
|
-
"int",
|
|
391
|
-
"""Get chunk size for simulated streaming.
|
|
392
|
-
Args:
|
|
393
|
-
api_name: Name of the API
|
|
394
|
-
Returns:
|
|
395
|
-
Chunk size in bytes
|
|
396
|
-
""",
|
|
397
|
-
)
|
|
398
|
-
|
|
399
|
-
get_api_simulated_streaming_apply_to = ApiSettingDescriptor[List[str]](
|
|
400
|
-
"simulated_streaming.apply_to",
|
|
401
|
-
"list",
|
|
402
|
-
"""Get endpoints for simulated streaming.
|
|
403
|
-
Args:
|
|
404
|
-
api_name: Name of the API
|
|
405
|
-
Returns:
|
|
406
|
-
List of endpoint paths
|
|
407
|
-
""",
|
|
408
|
-
)
|
|
409
|
-
|
|
410
371
|
get_api_request_body_substitution_enabled = ApiSettingDescriptor[bool](
|
|
411
372
|
"request_body_substitution.enabled",
|
|
412
373
|
"bool",
|
|
@@ -659,13 +620,6 @@ class ConfigManager:
|
|
|
659
620
|
Dictionary of advanced settings or empty dict if not specified
|
|
660
621
|
"""
|
|
661
622
|
return {
|
|
662
|
-
"simulated_stream_enabled": self.get_api_simulated_streaming_enabled(
|
|
663
|
-
api_name
|
|
664
|
-
),
|
|
665
|
-
"delay_seconds": self.get_api_simulated_streaming_delay(api_name),
|
|
666
|
-
"init_delay_seconds": self.get_api_simulated_streaming_init_delay(api_name),
|
|
667
|
-
"chunk_size_bytes": self.get_api_simulated_streaming_chunk_size(api_name),
|
|
668
|
-
"apply_to": self.get_api_simulated_streaming_apply_to(api_name),
|
|
669
623
|
"req_body_subst_enabled": self.get_api_request_body_substitution_enabled(
|
|
670
624
|
api_name
|
|
671
625
|
),
|
|
@@ -675,12 +629,12 @@ class ConfigManager:
|
|
|
675
629
|
def reload(self) -> None:
|
|
676
630
|
"""Reload the configuration from disk."""
|
|
677
631
|
try:
|
|
678
|
-
self.config = self.
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
)
|
|
632
|
+
self.config = self.init_config_client()
|
|
633
|
+
|
|
634
|
+
nya_app = [{"NyaProxy": self.config}]
|
|
635
|
+
self.server = NekoConfOrchestrator(apps=nya_app, logger=logger)
|
|
682
636
|
|
|
683
|
-
|
|
637
|
+
logger.info("Configuration reloaded successfully")
|
|
684
638
|
except Exception as e:
|
|
685
|
-
|
|
686
|
-
raise
|
|
639
|
+
logger.error(f"Failed to reload configuration: {str(e)}")
|
|
640
|
+
raise ConfigurationError(f"Failed to reload configuration: {str(e)}")
|
|
@@ -40,13 +40,7 @@ default_settings:
|
|
|
40
40
|
retry_status_codes: [ 429, 500, 502, 503, 504 ]
|
|
41
41
|
timeouts:
|
|
42
42
|
request_timeout_seconds: 300
|
|
43
|
-
|
|
44
|
-
simulated_streaming:
|
|
45
|
-
enabled: false
|
|
46
|
-
delay_seconds: 0.2 # Delay between chunks in seconds
|
|
47
|
-
init_delay_seconds: 0.5 # Initial delay before starting streaming in seconds
|
|
48
|
-
chunk_size_bytes: 256 # Size of each chunk in bytes
|
|
49
|
-
apply_to: ["application/json", "application/xml", "text/plain", "image/png", "image/jpeg"] # Response content types to apply simulated streaming to
|
|
43
|
+
|
|
50
44
|
# Request body substitution settings
|
|
51
45
|
request_body_substitution:
|
|
52
46
|
enabled: false
|
|
@@ -100,7 +94,7 @@ apis:
|
|
|
100
94
|
|
|
101
95
|
test:
|
|
102
96
|
name: Test API
|
|
103
|
-
endpoint: http://127.0.0.1:
|
|
97
|
+
endpoint: http://127.0.0.1:8082
|
|
104
98
|
key_variable: keys
|
|
105
99
|
headers:
|
|
106
100
|
Authorization: 'Bearer ${{keys}}'
|
|
@@ -117,6 +111,6 @@ apis:
|
|
|
117
111
|
load_balancing_strategy: least_requests
|
|
118
112
|
rate_limit:
|
|
119
113
|
endpoint_rate_limit: 20/m
|
|
120
|
-
key_rate_limit:
|
|
114
|
+
key_rate_limit: 1/10s
|
|
121
115
|
rate_limit_paths:
|
|
122
116
|
- "/v1/*"
|
|
@@ -5,6 +5,8 @@ Service factory for creating and managing NyaProxy components.
|
|
|
5
5
|
import logging
|
|
6
6
|
from typing import Any, Dict, Optional, Type
|
|
7
7
|
|
|
8
|
+
from loguru import logger
|
|
9
|
+
|
|
8
10
|
from ..common.exceptions import VariablesConfigurationError
|
|
9
11
|
from ..config.manager import ConfigManager
|
|
10
12
|
from ..services.key import KeyManager
|
|
@@ -27,17 +29,15 @@ class ServiceFactory:
|
|
|
27
29
|
def __init__(
|
|
28
30
|
self,
|
|
29
31
|
config_manager: Optional[ConfigManager] = None,
|
|
30
|
-
logger: Optional[logging.Logger] = None,
|
|
31
32
|
):
|
|
32
33
|
"""
|
|
33
34
|
Initialize the service factory.
|
|
34
35
|
|
|
35
36
|
Args:
|
|
36
37
|
config_manager: Configuration manager instance
|
|
37
|
-
|
|
38
|
+
|
|
38
39
|
"""
|
|
39
40
|
self.config = config_manager or ConfigManager.get_instance()
|
|
40
|
-
self.logger = logger or logging.getLogger(__name__)
|
|
41
41
|
self._components = {}
|
|
42
42
|
# Track component dependencies
|
|
43
43
|
self._dependencies = {}
|
|
@@ -47,7 +47,6 @@ class ServiceFactory:
|
|
|
47
47
|
return self._get_or_create_component(
|
|
48
48
|
"metrics_collector",
|
|
49
49
|
MetricsCollector,
|
|
50
|
-
constructor_args={"logger": self.logger},
|
|
51
50
|
)
|
|
52
51
|
|
|
53
52
|
def create_load_balancers(self) -> Dict[str, LoadBalancer]:
|
|
@@ -68,7 +67,7 @@ class ServiceFactory:
|
|
|
68
67
|
)
|
|
69
68
|
|
|
70
69
|
# Initialize load balancer on the key variable
|
|
71
|
-
load_balancers[api_name] = LoadBalancer(keys, strategy
|
|
70
|
+
load_balancers[api_name] = LoadBalancer(keys, strategy)
|
|
72
71
|
|
|
73
72
|
# Initialize load balancers for other variables if they exist
|
|
74
73
|
variables = self.config.get_api_variables(api_name)
|
|
@@ -89,11 +88,11 @@ class ServiceFactory:
|
|
|
89
88
|
)
|
|
90
89
|
|
|
91
90
|
load_balancers[f"{api_name}_{variable_name}"] = LoadBalancer(
|
|
92
|
-
values, strategy
|
|
91
|
+
values, strategy
|
|
93
92
|
)
|
|
94
93
|
|
|
95
94
|
self._components["load_balancers"] = load_balancers
|
|
96
|
-
|
|
95
|
+
logger.debug(f"Created {len(load_balancers)} load balancers")
|
|
97
96
|
|
|
98
97
|
return self._components["load_balancers"]
|
|
99
98
|
|
|
@@ -109,9 +108,7 @@ class ServiceFactory:
|
|
|
109
108
|
key_limit = self.config.get_api_key_rate_limit(api_name)
|
|
110
109
|
|
|
111
110
|
# Create endpoint rate limiter
|
|
112
|
-
rate_limiters[f"{api_name}_endpoint"] = RateLimiter(
|
|
113
|
-
endpoint_limit, logger=self.logger
|
|
114
|
-
)
|
|
111
|
+
rate_limiters[f"{api_name}_endpoint"] = RateLimiter(endpoint_limit)
|
|
115
112
|
|
|
116
113
|
# Create rate limiter for each key
|
|
117
114
|
key_variable = self.config.get_api_key_variable(api_name)
|
|
@@ -119,10 +116,10 @@ class ServiceFactory:
|
|
|
119
116
|
|
|
120
117
|
for key in keys:
|
|
121
118
|
key_id = f"{api_name}_{key}"
|
|
122
|
-
rate_limiters[key_id] = RateLimiter(key_limit
|
|
119
|
+
rate_limiters[key_id] = RateLimiter(key_limit)
|
|
123
120
|
|
|
124
121
|
self._components["rate_limiters"] = rate_limiters
|
|
125
|
-
|
|
122
|
+
logger.debug(f"Created {len(rate_limiters)} rate limiters")
|
|
126
123
|
|
|
127
124
|
return self._components["rate_limiters"]
|
|
128
125
|
|
|
@@ -132,7 +129,6 @@ class ServiceFactory:
|
|
|
132
129
|
dependencies = {
|
|
133
130
|
"load_balancers": self.create_load_balancers(),
|
|
134
131
|
"rate_limiters": self.create_rate_limiters(),
|
|
135
|
-
"logger": self.logger,
|
|
136
132
|
}
|
|
137
133
|
|
|
138
134
|
return self._get_or_create_component(
|
|
@@ -142,7 +138,7 @@ class ServiceFactory:
|
|
|
142
138
|
def create_request_queue(self) -> Optional[RequestQueue]:
|
|
143
139
|
"""Create a request queue if enabled in configuration."""
|
|
144
140
|
if not self.config.get_queue_enabled():
|
|
145
|
-
|
|
141
|
+
logger.debug("Request queue disabled in configuration")
|
|
146
142
|
self._components["request_queue"] = None
|
|
147
143
|
return None
|
|
148
144
|
|
|
@@ -152,7 +148,6 @@ class ServiceFactory:
|
|
|
152
148
|
|
|
153
149
|
dependencies = {
|
|
154
150
|
"key_manager": key_manager,
|
|
155
|
-
"logger": self.logger,
|
|
156
151
|
"max_size": queue_size,
|
|
157
152
|
"expiry_seconds": queue_expiry,
|
|
158
153
|
}
|
|
@@ -167,7 +162,6 @@ class ServiceFactory:
|
|
|
167
162
|
"config": self.config,
|
|
168
163
|
"metrics_collector": self.create_metrics_collector(),
|
|
169
164
|
"key_manager": self.create_key_manager(),
|
|
170
|
-
"logger": self.logger,
|
|
171
165
|
}
|
|
172
166
|
|
|
173
167
|
return self._get_or_create_component(
|
|
@@ -179,7 +173,6 @@ class ServiceFactory:
|
|
|
179
173
|
dependencies = {
|
|
180
174
|
"metrics_collector": self.create_metrics_collector(),
|
|
181
175
|
"load_balancer": self.create_load_balancers(),
|
|
182
|
-
"logger": self.logger,
|
|
183
176
|
}
|
|
184
177
|
|
|
185
178
|
return self._get_or_create_component(
|
|
@@ -199,7 +192,7 @@ class ServiceFactory:
|
|
|
199
192
|
"response_processor"
|
|
200
193
|
]
|
|
201
194
|
|
|
202
|
-
|
|
195
|
+
logger.debug("Connected request executor to response processor")
|
|
203
196
|
|
|
204
197
|
def _get_or_create_component(
|
|
205
198
|
self, name: str, cls_type: Type, constructor_args: Dict[str, Any] = None
|
|
@@ -221,7 +214,6 @@ class ServiceFactory:
|
|
|
221
214
|
|
|
222
215
|
self._components[name] = cls_type(**constructor_args)
|
|
223
216
|
self._dependencies[name] = list(constructor_args.keys())
|
|
224
|
-
self.logger.debug(f"Created new {cls_type.__name__}")
|
|
225
217
|
|
|
226
218
|
return self._components[name]
|
|
227
219
|
|
|
@@ -232,7 +224,7 @@ class ServiceFactory:
|
|
|
232
224
|
def register_component(self, name: str, component: Any) -> None:
|
|
233
225
|
"""Register an external component."""
|
|
234
226
|
self._components[name] = component
|
|
235
|
-
|
|
227
|
+
logger.debug(f"Registered external component: {name}")
|
|
236
228
|
|
|
237
229
|
def get_component_dependencies(self, name: str) -> list:
|
|
238
230
|
"""Get component dependencies."""
|