ErisPulse 2.1.13rc2__py3-none-any.whl → 2.1.14.dev1__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.
- ErisPulse/Core/__init__.py +8 -6
- ErisPulse/Core/adapter.py +11 -5
- ErisPulse/Core/env.py +1 -32
- ErisPulse/Core/exceptions.py +136 -0
- ErisPulse/Core/{server.py → router.py} +51 -70
- ErisPulse/__init__.py +8 -5
- ErisPulse/__main__.py +70 -23
- {erispulse-2.1.13rc2.dist-info → erispulse-2.1.14.dev1.dist-info}/METADATA +1 -1
- erispulse-2.1.14.dev1.dist-info/RECORD +15 -0
- ErisPulse/Core/raiserr.py +0 -181
- ErisPulse/Core/util.py +0 -123
- erispulse-2.1.13rc2.dist-info/RECORD +0 -16
- {erispulse-2.1.13rc2.dist-info → erispulse-2.1.14.dev1.dist-info}/WHEEL +0 -0
- {erispulse-2.1.13rc2.dist-info → erispulse-2.1.14.dev1.dist-info}/entry_points.txt +0 -0
- {erispulse-2.1.13rc2.dist-info → erispulse-2.1.14.dev1.dist-info}/licenses/LICENSE +0 -0
ErisPulse/Core/__init__.py
CHANGED
|
@@ -2,20 +2,22 @@ from .adapter import AdapterFather, SendDSL, adapter
|
|
|
2
2
|
from .env import env
|
|
3
3
|
from .logger import logger
|
|
4
4
|
from .mods import mods
|
|
5
|
-
from .
|
|
6
|
-
from .
|
|
7
|
-
from .
|
|
5
|
+
from .exceptions import exceptions
|
|
6
|
+
from .router import router, adapter_server
|
|
7
|
+
from .config import config
|
|
8
8
|
BaseAdapter = AdapterFather
|
|
9
9
|
|
|
10
10
|
__all__ = [
|
|
11
11
|
'BaseAdapter',
|
|
12
12
|
'AdapterFather',
|
|
13
13
|
'SendDSL',
|
|
14
|
+
'exceptions',
|
|
14
15
|
'adapter',
|
|
15
16
|
'env',
|
|
16
17
|
'logger',
|
|
17
18
|
'mods',
|
|
18
|
-
'
|
|
19
|
-
'
|
|
20
|
-
'adapter_server'
|
|
19
|
+
'exceptions',
|
|
20
|
+
'router',
|
|
21
|
+
'adapter_server',
|
|
22
|
+
'config'
|
|
21
23
|
]
|
ErisPulse/Core/adapter.py
CHANGED
|
@@ -13,11 +13,9 @@ ErisPulse 适配器系统
|
|
|
13
13
|
|
|
14
14
|
import functools
|
|
15
15
|
import asyncio
|
|
16
|
-
import uuid
|
|
17
|
-
import time
|
|
18
16
|
from typing import (
|
|
19
17
|
Callable, Any, Dict, List, Type, Optional, Set,
|
|
20
|
-
Union, Awaitable
|
|
18
|
+
Union, Awaitable
|
|
21
19
|
)
|
|
22
20
|
from collections import defaultdict
|
|
23
21
|
|
|
@@ -401,8 +399,16 @@ class AdapterManager:
|
|
|
401
399
|
"""
|
|
402
400
|
if platforms is None:
|
|
403
401
|
platforms = list(self._adapters.keys())
|
|
402
|
+
if not isinstance(platforms, list):
|
|
403
|
+
platforms = [platforms]
|
|
404
|
+
for platform in platforms:
|
|
405
|
+
if platform not in self._adapters:
|
|
406
|
+
raise ValueError(f"平台 {platform} 未注册")
|
|
407
|
+
|
|
408
|
+
self.logger.info(f"启动适配器 {platforms}")
|
|
404
409
|
|
|
405
|
-
|
|
410
|
+
# 启动OneBot服务
|
|
411
|
+
from .router import adapter_server
|
|
406
412
|
from .config import get_server_config
|
|
407
413
|
server_config = get_server_config()
|
|
408
414
|
host = server_config["host"]
|
|
@@ -490,7 +496,7 @@ class AdapterManager:
|
|
|
490
496
|
for adapter in self._adapters.values():
|
|
491
497
|
await adapter.shutdown()
|
|
492
498
|
|
|
493
|
-
from .
|
|
499
|
+
from .router import adapter_server
|
|
494
500
|
await adapter_server.stop()
|
|
495
501
|
|
|
496
502
|
def get(self, platform: str) -> Optional[BaseAdapter]:
|
ErisPulse/Core/env.py
CHANGED
|
@@ -13,14 +13,10 @@ ErisPulse 环境配置模块
|
|
|
13
13
|
import os
|
|
14
14
|
import json
|
|
15
15
|
import sqlite3
|
|
16
|
-
import importlib.util
|
|
17
16
|
import shutil
|
|
18
17
|
import time
|
|
19
|
-
import toml
|
|
20
|
-
from pathlib import Path
|
|
21
18
|
from datetime import datetime
|
|
22
|
-
from
|
|
23
|
-
from typing import List, Dict, Optional, Any, Set, Tuple, Union, Type, FrozenSet
|
|
19
|
+
from typing import List, Dict, Optional, Any, Tuple, Type
|
|
24
20
|
|
|
25
21
|
class EnvManager:
|
|
26
22
|
"""
|
|
@@ -39,7 +35,6 @@ class EnvManager:
|
|
|
39
35
|
db_path = os.path.join(os.path.dirname(__file__), "../data/config.db")
|
|
40
36
|
SNAPSHOT_DIR = os.path.join(os.path.dirname(__file__), "../data/snapshots")
|
|
41
37
|
|
|
42
|
-
CONFIG_FILE = "config.toml"
|
|
43
38
|
|
|
44
39
|
def __new__(cls, *args, **kwargs):
|
|
45
40
|
if not cls._instance:
|
|
@@ -192,8 +187,6 @@ class EnvManager:
|
|
|
192
187
|
from .config import config
|
|
193
188
|
return config.getConfig(key, default)
|
|
194
189
|
except Exception as e:
|
|
195
|
-
from . import logger
|
|
196
|
-
logger.error(f"读取配置文件 {self.CONFIG_FILE} 失败: {e}")
|
|
197
190
|
return default
|
|
198
191
|
|
|
199
192
|
def setConfig(self, key: str, value: Any) -> bool:
|
|
@@ -207,8 +200,6 @@ class EnvManager:
|
|
|
207
200
|
from .config import config
|
|
208
201
|
return config.setConfig(key, value)
|
|
209
202
|
except Exception as e:
|
|
210
|
-
from . import logger
|
|
211
|
-
logger.error(f"写入配置文件 {self.CONFIG_FILE} 失败: {e}")
|
|
212
203
|
return False
|
|
213
204
|
|
|
214
205
|
def delete(self, key: str) -> bool:
|
|
@@ -385,29 +376,7 @@ class EnvManager:
|
|
|
385
376
|
return True
|
|
386
377
|
except Exception as e:
|
|
387
378
|
return False
|
|
388
|
-
|
|
389
|
-
def load_env_file(self) -> bool:
|
|
390
|
-
"""
|
|
391
|
-
加载env.py文件中的配置项
|
|
392
379
|
|
|
393
|
-
:return: 操作是否成功
|
|
394
|
-
|
|
395
|
-
:example:
|
|
396
|
-
>>> env.load_env_file() # 加载env.py中的配置
|
|
397
|
-
"""
|
|
398
|
-
try:
|
|
399
|
-
env_file = Path("env.py")
|
|
400
|
-
if env_file.exists():
|
|
401
|
-
spec = importlib.util.spec_from_file_location("env_module", env_file)
|
|
402
|
-
env_module = importlib.util.module_from_spec(spec)
|
|
403
|
-
spec.loader.exec_module(env_module)
|
|
404
|
-
for key, value in vars(env_module).items():
|
|
405
|
-
if not key.startswith("__") and isinstance(value, (dict, list, str, int, float, bool)):
|
|
406
|
-
self.set(key, value)
|
|
407
|
-
return True
|
|
408
|
-
except Exception as e:
|
|
409
|
-
return False
|
|
410
|
-
|
|
411
380
|
def __getattr__(self, key: str) -> Any:
|
|
412
381
|
"""
|
|
413
382
|
通过属性访问配置项
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
# exceptions.py (新文件名)
|
|
2
|
+
"""
|
|
3
|
+
ErisPulse 全局异常处理系统
|
|
4
|
+
|
|
5
|
+
提供统一的异常捕获和格式化功能,支持同步和异步代码的异常处理。
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import sys
|
|
9
|
+
import traceback
|
|
10
|
+
import asyncio
|
|
11
|
+
from typing import Dict, Any, Type
|
|
12
|
+
from .logger import logger
|
|
13
|
+
|
|
14
|
+
class ExceptionHandler:
|
|
15
|
+
"""异常处理器类"""
|
|
16
|
+
|
|
17
|
+
@staticmethod
|
|
18
|
+
def format_exception(exc_type: Type[Exception], exc_value: Exception, exc_traceback: Any) -> str:
|
|
19
|
+
"""
|
|
20
|
+
格式化异常信息
|
|
21
|
+
|
|
22
|
+
:param exc_type: 异常类型
|
|
23
|
+
:param exc_value: 异常值
|
|
24
|
+
:param exc_traceback: 追踪信息
|
|
25
|
+
:return: 格式化后的异常信息
|
|
26
|
+
"""
|
|
27
|
+
RED = '\033[91m'
|
|
28
|
+
YELLOW = '\033[93m'
|
|
29
|
+
BLUE = '\033[94m'
|
|
30
|
+
RESET = '\033[0m'
|
|
31
|
+
|
|
32
|
+
error_title = f"{RED}{exc_type.__name__}{RESET}: {YELLOW}{exc_value}{RESET}"
|
|
33
|
+
traceback_lines = traceback.format_exception(exc_type, exc_value, exc_traceback)
|
|
34
|
+
|
|
35
|
+
colored_traceback = []
|
|
36
|
+
for line in traceback_lines:
|
|
37
|
+
if "File " in line and ", line " in line:
|
|
38
|
+
parts = line.split(', line ')
|
|
39
|
+
colored_line = f"{BLUE}{parts[0]}{RESET}, line {parts[1]}"
|
|
40
|
+
colored_traceback.append(colored_line)
|
|
41
|
+
else:
|
|
42
|
+
colored_traceback.append(f"{RED}{line}{RESET}")
|
|
43
|
+
|
|
44
|
+
return f"""
|
|
45
|
+
{error_title}
|
|
46
|
+
{RED}Traceback:{RESET}
|
|
47
|
+
{''.join(colored_traceback)}"""
|
|
48
|
+
|
|
49
|
+
@staticmethod
|
|
50
|
+
def format_async_exception(exception: Exception) -> str:
|
|
51
|
+
"""
|
|
52
|
+
格式化异步异常信息
|
|
53
|
+
|
|
54
|
+
:param exception: 异常对象
|
|
55
|
+
:return: 格式化后的异常信息
|
|
56
|
+
"""
|
|
57
|
+
RED = '\033[91m'
|
|
58
|
+
YELLOW = '\033[93m'
|
|
59
|
+
BLUE = '\033[94m'
|
|
60
|
+
RESET = '\033[0m'
|
|
61
|
+
|
|
62
|
+
tb = ''.join(traceback.format_exception(type(exception), exception, exception.__traceback__))
|
|
63
|
+
|
|
64
|
+
colored_tb = []
|
|
65
|
+
for line in tb.split('\n'):
|
|
66
|
+
if "File " in line and ", line " in line:
|
|
67
|
+
parts = line.split(', line ')
|
|
68
|
+
colored_line = f"{BLUE}{parts[0]}{RESET}, line {parts[1]}"
|
|
69
|
+
colored_tb.append(colored_line)
|
|
70
|
+
else:
|
|
71
|
+
colored_tb.append(f"{RED}{line}{RESET}")
|
|
72
|
+
|
|
73
|
+
return f"""{RED}{type(exception).__name__}{RESET}: {YELLOW}{exception}{RESET}
|
|
74
|
+
{RED}Traceback:{RESET}
|
|
75
|
+
{''.join(colored_tb)}"""
|
|
76
|
+
|
|
77
|
+
def global_exception_handler(exc_type: Type[Exception], exc_value: Exception, exc_traceback: Any) -> None:
|
|
78
|
+
"""
|
|
79
|
+
全局异常处理器
|
|
80
|
+
|
|
81
|
+
:param exc_type: 异常类型
|
|
82
|
+
:param exc_value: 异常值
|
|
83
|
+
:param exc_traceback: 追踪信息
|
|
84
|
+
"""
|
|
85
|
+
try:
|
|
86
|
+
formatted_error = ExceptionHandler.format_exception(exc_type, exc_value, exc_traceback)
|
|
87
|
+
sys.stderr.write(formatted_error)
|
|
88
|
+
# 同时记录到日志系统
|
|
89
|
+
logger.error(f"未捕获异常: {exc_type.__name__}: {exc_value}")
|
|
90
|
+
except Exception:
|
|
91
|
+
# 防止异常处理过程中出现异常
|
|
92
|
+
sys.stderr.write(f"Uncaught exception: {exc_type.__name__}: {exc_value}\n")
|
|
93
|
+
|
|
94
|
+
def async_exception_handler(loop: asyncio.AbstractEventLoop, context: Dict[str, Any]) -> None:
|
|
95
|
+
"""
|
|
96
|
+
异步异常处理器
|
|
97
|
+
|
|
98
|
+
:param loop: 事件循环
|
|
99
|
+
:param context: 上下文字典
|
|
100
|
+
"""
|
|
101
|
+
RED = '\033[91m'
|
|
102
|
+
YELLOW = '\033[93m'
|
|
103
|
+
RESET = '\033[0m'
|
|
104
|
+
|
|
105
|
+
exception = context.get('exception')
|
|
106
|
+
if exception:
|
|
107
|
+
try:
|
|
108
|
+
formatted_error = ExceptionHandler.format_async_exception(exception)
|
|
109
|
+
sys.stderr.write(formatted_error)
|
|
110
|
+
# 同时记录到日志系统
|
|
111
|
+
logger.error(f"异步异常: {type(exception).__name__}: {exception}")
|
|
112
|
+
except Exception:
|
|
113
|
+
sys.stderr.write(f"{RED}Async Error{RESET}: {YELLOW}{exception}{RESET}\n")
|
|
114
|
+
else:
|
|
115
|
+
msg = context.get('message', 'Unknown async error')
|
|
116
|
+
sys.stderr.write(f"{RED}Async Error{RESET}: {YELLOW}{msg}{RESET}\n")
|
|
117
|
+
logger.error(f"异步错误: {msg}")
|
|
118
|
+
|
|
119
|
+
# 注册全局异常处理器
|
|
120
|
+
sys.excepthook = global_exception_handler
|
|
121
|
+
try:
|
|
122
|
+
asyncio.get_event_loop().set_exception_handler(async_exception_handler)
|
|
123
|
+
except RuntimeError:
|
|
124
|
+
# 如果还没有事件循环,则在创建时设置
|
|
125
|
+
pass
|
|
126
|
+
|
|
127
|
+
# 提供一个函数用于在创建新事件循环时设置异常处理器
|
|
128
|
+
def setup_async_exception_handler(loop: asyncio.AbstractEventLoop = None) -> None:
|
|
129
|
+
"""
|
|
130
|
+
设置异步异常处理器
|
|
131
|
+
|
|
132
|
+
:param loop: 事件循环,如果为None则使用当前事件循环
|
|
133
|
+
"""
|
|
134
|
+
if loop is None:
|
|
135
|
+
loop = asyncio.get_event_loop()
|
|
136
|
+
loop.set_exception_handler(async_exception_handler)
|
|
@@ -1,6 +1,8 @@
|
|
|
1
|
+
# router.py (新文件名)
|
|
1
2
|
"""
|
|
2
|
-
ErisPulse
|
|
3
|
-
|
|
3
|
+
ErisPulse 路由系统
|
|
4
|
+
|
|
5
|
+
提供统一的HTTP和WebSocket路由管理,支持多适配器路由注册和生命周期管理。
|
|
4
6
|
|
|
5
7
|
{!--< tips >!--}
|
|
6
8
|
1. 适配器只需注册路由,无需自行管理服务器
|
|
@@ -19,9 +21,9 @@ from hypercorn.config import Config
|
|
|
19
21
|
from hypercorn.asyncio import serve
|
|
20
22
|
|
|
21
23
|
|
|
22
|
-
class
|
|
24
|
+
class RouterManager:
|
|
23
25
|
"""
|
|
24
|
-
|
|
26
|
+
路由管理器
|
|
25
27
|
|
|
26
28
|
{!--< tips >!--}
|
|
27
29
|
核心功能:
|
|
@@ -33,18 +35,18 @@ class AdapterServer:
|
|
|
33
35
|
|
|
34
36
|
def __init__(self):
|
|
35
37
|
"""
|
|
36
|
-
|
|
38
|
+
初始化路由管理器
|
|
37
39
|
|
|
38
40
|
{!--< tips >!--}
|
|
39
41
|
会自动创建FastAPI实例并设置核心路由
|
|
40
42
|
{!--< /tips >!--}
|
|
41
43
|
"""
|
|
42
44
|
self.app = FastAPI(
|
|
43
|
-
title="ErisPulse
|
|
44
|
-
description="
|
|
45
|
+
title="ErisPulse Router",
|
|
46
|
+
description="统一路由管理入口点",
|
|
45
47
|
version="1.0.0"
|
|
46
48
|
)
|
|
47
|
-
self.
|
|
49
|
+
self._http_routes: Dict[str, Dict[str, Callable]] = defaultdict(dict)
|
|
48
50
|
self._websocket_routes: Dict[str, Dict[str, Tuple[Callable, Optional[Callable]]]] = defaultdict(dict)
|
|
49
51
|
self.base_url = ""
|
|
50
52
|
self._server_task: Optional[asyncio.Task] = None
|
|
@@ -66,7 +68,7 @@ class AdapterServer:
|
|
|
66
68
|
:return:
|
|
67
69
|
Dict[str, str]: 包含服务状态的字典
|
|
68
70
|
"""
|
|
69
|
-
return {"status": "ok", "service": "ErisPulse
|
|
71
|
+
return {"status": "ok", "service": "ErisPulse Router"}
|
|
70
72
|
|
|
71
73
|
@self.app.get("/routes")
|
|
72
74
|
async def list_routes() -> Dict[str, Any]:
|
|
@@ -74,36 +76,23 @@ class AdapterServer:
|
|
|
74
76
|
列出所有已注册路由
|
|
75
77
|
|
|
76
78
|
:return:
|
|
77
|
-
Dict[str, Any]:
|
|
78
|
-
{
|
|
79
|
-
"http_routes": [
|
|
80
|
-
{
|
|
81
|
-
"path": "/adapter1/route1",
|
|
82
|
-
"adapter": "adapter1",
|
|
83
|
-
"methods": ["POST"]
|
|
84
|
-
},
|
|
85
|
-
...
|
|
86
|
-
],
|
|
87
|
-
"websocket_routes": [
|
|
88
|
-
{
|
|
89
|
-
"path": "/adapter1/ws",
|
|
90
|
-
"adapter": "adapter1",
|
|
91
|
-
"requires_auth": true
|
|
92
|
-
},
|
|
93
|
-
...
|
|
94
|
-
],
|
|
95
|
-
"base_url": self.base_url
|
|
96
|
-
}
|
|
79
|
+
Dict[str, Any]: 包含所有路由信息的字典
|
|
97
80
|
"""
|
|
98
81
|
http_routes = []
|
|
99
|
-
for adapter, routes in self.
|
|
82
|
+
for adapter, routes in self._http_routes.items():
|
|
100
83
|
for path, handler in routes.items():
|
|
101
|
-
|
|
102
|
-
|
|
84
|
+
# 查找对应的路由对象
|
|
85
|
+
route_obj = None
|
|
86
|
+
for route in self.app.router.routes:
|
|
87
|
+
if isinstance(route, APIRoute) and route.path == path:
|
|
88
|
+
route_obj = route
|
|
89
|
+
break
|
|
90
|
+
|
|
91
|
+
if route_obj:
|
|
103
92
|
http_routes.append({
|
|
104
93
|
"path": path,
|
|
105
94
|
"adapter": adapter,
|
|
106
|
-
"methods":
|
|
95
|
+
"methods": list(route_obj.methods)
|
|
107
96
|
})
|
|
108
97
|
|
|
109
98
|
websocket_routes = []
|
|
@@ -121,9 +110,9 @@ class AdapterServer:
|
|
|
121
110
|
"base_url": self.base_url
|
|
122
111
|
}
|
|
123
112
|
|
|
124
|
-
def
|
|
113
|
+
def register_http_route(
|
|
125
114
|
self,
|
|
126
|
-
|
|
115
|
+
module_name: str,
|
|
127
116
|
path: str,
|
|
128
117
|
handler: Callable,
|
|
129
118
|
methods: List[str] = ["POST"]
|
|
@@ -131,35 +120,37 @@ class AdapterServer:
|
|
|
131
120
|
"""
|
|
132
121
|
注册HTTP路由
|
|
133
122
|
|
|
134
|
-
:param
|
|
135
|
-
:param path: str 路由路径
|
|
123
|
+
:param module_name: str 模块名称
|
|
124
|
+
:param path: str 路由路径
|
|
136
125
|
:param handler: Callable 处理函数
|
|
137
126
|
:param methods: List[str] HTTP方法列表(默认["POST"])
|
|
138
127
|
|
|
139
128
|
:raises ValueError: 当路径已注册时抛出
|
|
140
|
-
|
|
141
|
-
{!--< tips >!--}
|
|
142
|
-
路径会自动添加适配器前缀,如:/adapter_name/path
|
|
143
|
-
{!--< /tips >!--}
|
|
144
129
|
"""
|
|
145
|
-
full_path = f"/{
|
|
130
|
+
full_path = f"/{module_name}{path}"
|
|
146
131
|
|
|
147
|
-
if full_path in self.
|
|
132
|
+
if full_path in self._http_routes[module_name]:
|
|
148
133
|
raise ValueError(f"路径 {full_path} 已注册")
|
|
149
134
|
|
|
150
135
|
route = APIRoute(
|
|
151
136
|
path=full_path,
|
|
152
137
|
endpoint=handler,
|
|
153
138
|
methods=methods,
|
|
154
|
-
name=f"{
|
|
139
|
+
name=f"{module_name}_{path.replace('/', '_')}"
|
|
155
140
|
)
|
|
156
141
|
self.app.router.routes.append(route)
|
|
157
|
-
self.
|
|
142
|
+
self._http_routes[module_name][full_path] = handler
|
|
158
143
|
logger.info(f"注册HTTP路由: {self.base_url}{full_path} 方法: {methods}")
|
|
159
144
|
|
|
145
|
+
def register_webhook(self, *args, **kwargs) -> None:
|
|
146
|
+
"""
|
|
147
|
+
兼容性方法:注册HTTP路由(适配器旧接口)
|
|
148
|
+
"""
|
|
149
|
+
return self.register_http_route(*args, **kwargs)
|
|
150
|
+
|
|
160
151
|
def register_websocket(
|
|
161
152
|
self,
|
|
162
|
-
|
|
153
|
+
module_name: str,
|
|
163
154
|
path: str,
|
|
164
155
|
handler: Callable[[WebSocket], Awaitable[Any]],
|
|
165
156
|
auth_handler: Optional[Callable[[WebSocket], Awaitable[bool]]] = None,
|
|
@@ -167,29 +158,21 @@ class AdapterServer:
|
|
|
167
158
|
"""
|
|
168
159
|
注册WebSocket路由
|
|
169
160
|
|
|
170
|
-
:param
|
|
171
|
-
:param path: str WebSocket路径
|
|
161
|
+
:param module_name: str 模块名称
|
|
162
|
+
:param path: str WebSocket路径
|
|
172
163
|
:param handler: Callable[[WebSocket], Awaitable[Any]] 主处理函数
|
|
173
164
|
:param auth_handler: Optional[Callable[[WebSocket], Awaitable[bool]]] 认证函数
|
|
174
165
|
|
|
175
166
|
:raises ValueError: 当路径已注册时抛出
|
|
176
|
-
|
|
177
|
-
{!--< tips >!--}
|
|
178
|
-
认证函数应返回布尔值,False将拒绝连接
|
|
179
|
-
{!--< /tips >!--}
|
|
180
167
|
"""
|
|
181
|
-
full_path = f"/{
|
|
168
|
+
full_path = f"/{module_name}{path}"
|
|
182
169
|
|
|
183
|
-
if full_path in self._websocket_routes[
|
|
170
|
+
if full_path in self._websocket_routes[module_name]:
|
|
184
171
|
raise ValueError(f"WebSocket路径 {full_path} 已注册")
|
|
185
172
|
|
|
186
173
|
async def websocket_endpoint(websocket: WebSocket) -> None:
|
|
187
174
|
"""
|
|
188
175
|
WebSocket端点包装器
|
|
189
|
-
|
|
190
|
-
{!--< internal-use >!--}
|
|
191
|
-
处理连接生命周期和错误处理
|
|
192
|
-
{!--< /internal-use >!--}
|
|
193
176
|
"""
|
|
194
177
|
await websocket.accept()
|
|
195
178
|
|
|
@@ -209,17 +192,16 @@ class AdapterServer:
|
|
|
209
192
|
self.app.add_api_websocket_route(
|
|
210
193
|
path=full_path,
|
|
211
194
|
endpoint=websocket_endpoint,
|
|
212
|
-
name=f"{
|
|
195
|
+
name=f"{module_name}_{path.replace('/', '_')}"
|
|
213
196
|
)
|
|
214
|
-
self._websocket_routes[
|
|
197
|
+
self._websocket_routes[module_name][full_path] = (handler, auth_handler)
|
|
215
198
|
logger.info(f"注册WebSocket: {self.base_url}{full_path} {'(需认证)' if auth_handler else ''}")
|
|
216
199
|
|
|
217
200
|
def get_app(self) -> FastAPI:
|
|
218
201
|
"""
|
|
219
202
|
获取FastAPI应用实例
|
|
220
203
|
|
|
221
|
-
:return:
|
|
222
|
-
FastAPI: FastAPI应用实例
|
|
204
|
+
:return: FastAPI应用实例
|
|
223
205
|
"""
|
|
224
206
|
return self.app
|
|
225
207
|
|
|
@@ -231,7 +213,7 @@ class AdapterServer:
|
|
|
231
213
|
ssl_keyfile: Optional[str] = None
|
|
232
214
|
) -> None:
|
|
233
215
|
"""
|
|
234
|
-
|
|
216
|
+
启动路由服务器
|
|
235
217
|
|
|
236
218
|
:param host: str 监听地址(默认"0.0.0.0")
|
|
237
219
|
:param port: int 监听端口(默认8000)
|
|
@@ -252,25 +234,24 @@ class AdapterServer:
|
|
|
252
234
|
config.keyfile = ssl_keyfile
|
|
253
235
|
|
|
254
236
|
self.base_url = f"http{'s' if ssl_certfile else ''}://{host}:{port}"
|
|
255
|
-
logger.info(f"
|
|
237
|
+
logger.info(f"启动路由服务器 {self.base_url}")
|
|
256
238
|
|
|
257
239
|
self._server_task = asyncio.create_task(serve(self.app, config))
|
|
258
240
|
|
|
259
241
|
async def stop(self) -> None:
|
|
260
242
|
"""
|
|
261
243
|
停止服务器
|
|
262
|
-
|
|
263
|
-
{!--< tips >!--}
|
|
264
|
-
会等待所有连接正常关闭
|
|
265
|
-
{!--< /tips >!--}
|
|
266
244
|
"""
|
|
267
245
|
if self._server_task:
|
|
268
246
|
self._server_task.cancel()
|
|
269
247
|
try:
|
|
270
248
|
await self._server_task
|
|
271
249
|
except asyncio.CancelledError:
|
|
272
|
-
logger.info("
|
|
250
|
+
logger.info("路由服务器已停止")
|
|
273
251
|
self._server_task = None
|
|
274
252
|
|
|
253
|
+
# 主要实例
|
|
254
|
+
router = RouterManager()
|
|
275
255
|
|
|
276
|
-
|
|
256
|
+
# 兼容性实例
|
|
257
|
+
adapter_server = router
|
ErisPulse/__init__.py
CHANGED
|
@@ -10,6 +10,9 @@ ErisPulse SDK 主模块
|
|
|
10
10
|
{!--< /tips >!--}
|
|
11
11
|
"""
|
|
12
12
|
|
|
13
|
+
__version__ = "2.1.14dev1"
|
|
14
|
+
__author__ = "ErisPulse"
|
|
15
|
+
|
|
13
16
|
import os
|
|
14
17
|
import sys
|
|
15
18
|
import importlib
|
|
@@ -19,23 +22,23 @@ from typing import Dict, List, Tuple, Type, Any
|
|
|
19
22
|
from pathlib import Path
|
|
20
23
|
|
|
21
24
|
# BaseModules: SDK核心模块
|
|
22
|
-
from .Core import
|
|
23
|
-
from .Core import raiserr
|
|
25
|
+
from .Core import exceptions
|
|
24
26
|
from .Core import logger
|
|
25
27
|
from .Core import env
|
|
26
28
|
from .Core import mods
|
|
27
29
|
from .Core import adapter, AdapterFather, SendDSL
|
|
28
|
-
from .Core import adapter_server
|
|
30
|
+
from .Core import router, adapter_server
|
|
29
31
|
|
|
30
32
|
sdk = sys.modules[__name__]
|
|
31
33
|
|
|
32
34
|
BaseModules = {
|
|
33
|
-
"util": util,
|
|
34
35
|
"logger": logger,
|
|
35
|
-
"raiserr":
|
|
36
|
+
"raiserr": exceptions,
|
|
36
37
|
"env": env,
|
|
37
38
|
"mods": mods,
|
|
38
39
|
"adapter": adapter,
|
|
40
|
+
"router": router,
|
|
41
|
+
"adapter_server": adapter_server,
|
|
39
42
|
"SendDSL": SendDSL,
|
|
40
43
|
"AdapterFather": AdapterFather,
|
|
41
44
|
"BaseAdapter": AdapterFather
|
ErisPulse/__main__.py
CHANGED
|
@@ -19,7 +19,6 @@ import json
|
|
|
19
19
|
import asyncio
|
|
20
20
|
from urllib.parse import urlparse
|
|
21
21
|
from typing import List, Dict, Tuple, Optional, Callable, Any
|
|
22
|
-
from importlib.metadata import version, PackageNotFoundError
|
|
23
22
|
from watchdog.observers import Observer
|
|
24
23
|
from watchdog.events import FileSystemEventHandler
|
|
25
24
|
|
|
@@ -188,26 +187,38 @@ class PackageManager:
|
|
|
188
187
|
|
|
189
188
|
try:
|
|
190
189
|
# 查找模块和适配器
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
190
|
+
entry_points = importlib.metadata.entry_points()
|
|
191
|
+
|
|
192
|
+
# 处理模块
|
|
193
|
+
if hasattr(entry_points, 'select'):
|
|
194
|
+
module_entries = entry_points.select(group='erispulse.module')
|
|
195
|
+
else:
|
|
196
|
+
module_entries = entry_points.get('erispulse.module', [])
|
|
197
|
+
|
|
198
|
+
for entry in module_entries:
|
|
199
|
+
dist = entry.dist
|
|
200
|
+
packages["modules"][entry.name] = {
|
|
201
|
+
"package": dist.metadata["Name"],
|
|
202
|
+
"version": dist.version,
|
|
203
|
+
"summary": dist.metadata["Summary"],
|
|
204
|
+
"enabled": self._is_module_enabled(entry.name)
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
# 处理适配器
|
|
208
|
+
if hasattr(entry_points, 'select'):
|
|
209
|
+
adapter_entries = entry_points.select(group='erispulse.adapter')
|
|
210
|
+
else:
|
|
211
|
+
adapter_entries = entry_points.get('erispulse.adapter', [])
|
|
212
|
+
|
|
213
|
+
for entry in adapter_entries:
|
|
214
|
+
dist = entry.dist
|
|
215
|
+
packages["adapters"][entry.name] = {
|
|
216
|
+
"package": dist.metadata["Name"],
|
|
217
|
+
"version": dist.version,
|
|
218
|
+
"summary": dist.metadata["Summary"]
|
|
219
|
+
}
|
|
208
220
|
|
|
209
221
|
# 查找CLI扩展
|
|
210
|
-
entry_points = importlib.metadata.entry_points()
|
|
211
222
|
if hasattr(entry_points, 'select'):
|
|
212
223
|
cli_entries = entry_points.select(group='erispulse.cli')
|
|
213
224
|
else:
|
|
@@ -222,9 +233,9 @@ class PackageManager:
|
|
|
222
233
|
}
|
|
223
234
|
|
|
224
235
|
except Exception as e:
|
|
225
|
-
|
|
236
|
+
print(f"[error] 获取已安装包信息失败: {e}")
|
|
226
237
|
import traceback
|
|
227
|
-
|
|
238
|
+
print(traceback.format_exc())
|
|
228
239
|
|
|
229
240
|
return packages
|
|
230
241
|
|
|
@@ -329,7 +340,7 @@ class PackageManager:
|
|
|
329
340
|
|
|
330
341
|
:raises KeyboardInterrupt: 用户取消操作时抛出
|
|
331
342
|
"""
|
|
332
|
-
installed = self.
|
|
343
|
+
installed = self.get_installed_packages()
|
|
333
344
|
all_packages = set()
|
|
334
345
|
|
|
335
346
|
for pkg_type in ["modules", "adapters", "cli_extensions"]:
|
|
@@ -652,6 +663,22 @@ class CLI:
|
|
|
652
663
|
|
|
653
664
|
return parser
|
|
654
665
|
|
|
666
|
+
def _get_external_commands(self) -> List[str]:
|
|
667
|
+
"""
|
|
668
|
+
获取所有已注册的第三方命令名称
|
|
669
|
+
|
|
670
|
+
:return: 第三方命令名称列表
|
|
671
|
+
"""
|
|
672
|
+
try:
|
|
673
|
+
entry_points = importlib.metadata.entry_points()
|
|
674
|
+
if hasattr(entry_points, 'select'):
|
|
675
|
+
cli_entries = entry_points.select(group='erispulse.cli')
|
|
676
|
+
else:
|
|
677
|
+
cli_entries = entry_points.get('erispulse.cli', [])
|
|
678
|
+
return [entry.name for entry in cli_entries]
|
|
679
|
+
except Exception:
|
|
680
|
+
return []
|
|
681
|
+
|
|
655
682
|
def _load_external_commands(self, subparsers):
|
|
656
683
|
"""
|
|
657
684
|
加载第三方CLI命令
|
|
@@ -1027,9 +1054,29 @@ class CLI:
|
|
|
1027
1054
|
|
|
1028
1055
|
elif args.command == "init":
|
|
1029
1056
|
from ErisPulse import sdk
|
|
1030
|
-
sdk.init(
|
|
1057
|
+
sdk.init()
|
|
1031
1058
|
console.print("[success]ErisPulse项目初始化完成[/]")
|
|
1032
1059
|
|
|
1060
|
+
# 处理第三方命令
|
|
1061
|
+
elif args.command in self._get_external_commands():
|
|
1062
|
+
# 获取第三方命令的处理函数并执行
|
|
1063
|
+
entry_points = importlib.metadata.entry_points()
|
|
1064
|
+
if hasattr(entry_points, 'select'):
|
|
1065
|
+
cli_entries = entry_points.select(group='erispulse.cli')
|
|
1066
|
+
else:
|
|
1067
|
+
cli_entries = entry_points.get('erispulse.cli', [])
|
|
1068
|
+
|
|
1069
|
+
for entry in cli_entries:
|
|
1070
|
+
if entry.name == args.command:
|
|
1071
|
+
cli_func = entry.load()
|
|
1072
|
+
if callable(cli_func):
|
|
1073
|
+
# 创建一个新的解析器来解析第三方命令的参数
|
|
1074
|
+
subparser = self.parser._subparsers._group_actions[0].choices[args.command]
|
|
1075
|
+
parsed_args = subparser.parse_args(sys.argv[2:])
|
|
1076
|
+
# 调用第三方命令处理函数
|
|
1077
|
+
parsed_args.func(parsed_args)
|
|
1078
|
+
break
|
|
1079
|
+
|
|
1033
1080
|
except KeyboardInterrupt:
|
|
1034
1081
|
console.print("\n[warning]操作被用户中断[/]")
|
|
1035
1082
|
self._cleanup()
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
ErisPulse/__init__.py,sha256=gZ1ctwSS0Bi2XaTPa3WuR1PLEOZ2vu6zNEGSFrBU5b8,26186
|
|
2
|
+
ErisPulse/__main__.py,sha256=aDYN5_11PdL3tj2ruhNoXwNc9TmAUnBtFujQgnEf_sI,37573
|
|
3
|
+
ErisPulse/Core/__init__.py,sha256=rDl-UwJYnkS12rUTCpMqD--WNn4rmdIJalR04FFpsIg,464
|
|
4
|
+
ErisPulse/Core/adapter.py,sha256=_imdrQNoi8dxp5rVsKBx-IAheGLMaq3Nyf1I9A6jHS0,18353
|
|
5
|
+
ErisPulse/Core/config.py,sha256=ZmwGdtHSOE7K5uOGzLYcyl3ZF3sAmeWAntqcdfDzhpM,5027
|
|
6
|
+
ErisPulse/Core/env.py,sha256=U45f9WtriVyd3tW1N8to-ZvpzcF9gD8DJzNTC1jY2cM,17665
|
|
7
|
+
ErisPulse/Core/exceptions.py,sha256=9blt5cPVetV4XfbYo2uQ2vE_LaxT7cZmNOkJv4yGijI,4642
|
|
8
|
+
ErisPulse/Core/logger.py,sha256=cJzNXF-EmdWxwgiHg5Itmkwsva2Jhe9l9X4rXKiXHgc,8296
|
|
9
|
+
ErisPulse/Core/mods.py,sha256=2yIq8t9Ca9CBPRiZU0yr8Lc0XGmmkB7LlH-5FWqXjw4,7023
|
|
10
|
+
ErisPulse/Core/router.py,sha256=66hT8VC2dVNX-dANldoOPDcqQ94hidFkNnvKgAPemGQ,8491
|
|
11
|
+
erispulse-2.1.14.dev1.dist-info/METADATA,sha256=zgR3p8JZra9h7LWf09L0RTRT_2hswige2Kii8bApwi4,6264
|
|
12
|
+
erispulse-2.1.14.dev1.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
|
|
13
|
+
erispulse-2.1.14.dev1.dist-info/entry_points.txt,sha256=Jss71M6nEha0TA-DyVZugPYdcL14s9QpiOeIlgWxzOc,182
|
|
14
|
+
erispulse-2.1.14.dev1.dist-info/licenses/LICENSE,sha256=4jyqikiB0G0n06CEEMMTzTXjE4IShghSlB74skMSPQs,1464
|
|
15
|
+
erispulse-2.1.14.dev1.dist-info/RECORD,,
|
ErisPulse/Core/raiserr.py
DELETED
|
@@ -1,181 +0,0 @@
|
|
|
1
|
-
"""
|
|
2
|
-
ErisPulse 错误管理系统
|
|
3
|
-
|
|
4
|
-
提供全局异常捕获功能。不再推荐使用自定义错误注册功能。
|
|
5
|
-
|
|
6
|
-
{!--< tips >!--}
|
|
7
|
-
1. 请使用Python原生异常抛出方法
|
|
8
|
-
2. 系统会自动捕获并格式化所有未处理异常
|
|
9
|
-
3. 注册功能已标记为弃用,将在未来版本移除
|
|
10
|
-
{!--< /tips >!--}
|
|
11
|
-
"""
|
|
12
|
-
|
|
13
|
-
import sys
|
|
14
|
-
import traceback
|
|
15
|
-
import asyncio
|
|
16
|
-
from typing import Dict, Any, Optional, Type, Callable, List, Set, Tuple, Union
|
|
17
|
-
|
|
18
|
-
class Error:
|
|
19
|
-
"""
|
|
20
|
-
错误管理器
|
|
21
|
-
|
|
22
|
-
{!--< deprecated >!--} 请使用Python原生异常抛出方法 | 2025-07-18
|
|
23
|
-
|
|
24
|
-
{!--< tips >!--}
|
|
25
|
-
1. 注册功能将在未来版本移除
|
|
26
|
-
2. 请直接使用raise Exception("message")方式抛出异常
|
|
27
|
-
{!--< /tips >!--}
|
|
28
|
-
"""
|
|
29
|
-
|
|
30
|
-
def __init__(self):
|
|
31
|
-
self._types = {}
|
|
32
|
-
|
|
33
|
-
def register(self, name: str, doc: str = "", base: Type[Exception] = Exception) -> Type[Exception]:
|
|
34
|
-
"""
|
|
35
|
-
注册新的错误类型
|
|
36
|
-
|
|
37
|
-
{!--< deprecated >!--} 请使用Python原生异常抛出方法 | 2025-07-18
|
|
38
|
-
|
|
39
|
-
:param name: 错误类型名称
|
|
40
|
-
:param doc: 错误描述文档
|
|
41
|
-
:param base: 基础异常类
|
|
42
|
-
:return: 注册的错误类
|
|
43
|
-
"""
|
|
44
|
-
if name not in self._types:
|
|
45
|
-
err_cls = type(name, (base,), {"__doc__": doc})
|
|
46
|
-
self._types[name] = err_cls
|
|
47
|
-
return self._types[name]
|
|
48
|
-
|
|
49
|
-
def __getattr__(self, name: str) -> Callable[..., None]:
|
|
50
|
-
"""
|
|
51
|
-
动态获取错误抛出函数
|
|
52
|
-
|
|
53
|
-
{!--< deprecated >!--} 请使用Python原生异常抛出方法 | 2025-07-18
|
|
54
|
-
|
|
55
|
-
:param name: 错误类型名称
|
|
56
|
-
:return: 错误抛出函数
|
|
57
|
-
|
|
58
|
-
:raises AttributeError: 当错误类型未注册时抛出
|
|
59
|
-
"""
|
|
60
|
-
def raiser(msg: str, exit: bool = False) -> None:
|
|
61
|
-
"""
|
|
62
|
-
错误抛出函数
|
|
63
|
-
|
|
64
|
-
:param msg: 错误消息
|
|
65
|
-
:param exit: 是否退出程序
|
|
66
|
-
"""
|
|
67
|
-
from .logger import logger
|
|
68
|
-
err_cls = self._types.get(name) or self.register(name)
|
|
69
|
-
exc = err_cls(msg)
|
|
70
|
-
|
|
71
|
-
red = '\033[91m'
|
|
72
|
-
reset = '\033[0m'
|
|
73
|
-
|
|
74
|
-
logger.error(f"{red}{name}: {msg} | {err_cls.__doc__}{reset}")
|
|
75
|
-
logger.error(f"{red}{ ''.join(traceback.format_stack()) }{reset}")
|
|
76
|
-
|
|
77
|
-
if exit:
|
|
78
|
-
raise exc
|
|
79
|
-
return raiser
|
|
80
|
-
|
|
81
|
-
def info(self, name: Optional[str] = None) -> Dict[str, Any]:
|
|
82
|
-
"""
|
|
83
|
-
获取错误信息
|
|
84
|
-
|
|
85
|
-
{!--< deprecated >!--} 此功能将在未来版本移除 | 2025-07-18
|
|
86
|
-
|
|
87
|
-
:param name: 错误类型名称(可选)
|
|
88
|
-
:return: 错误信息字典
|
|
89
|
-
"""
|
|
90
|
-
result = {}
|
|
91
|
-
for err_name, err_cls in self._types.items():
|
|
92
|
-
result[err_name] = {
|
|
93
|
-
"type": err_name,
|
|
94
|
-
"doc": getattr(err_cls, "__doc__", ""),
|
|
95
|
-
"class": err_cls,
|
|
96
|
-
}
|
|
97
|
-
if name is None:
|
|
98
|
-
return result
|
|
99
|
-
err_cls = self._types.get(name)
|
|
100
|
-
if not err_cls:
|
|
101
|
-
return {
|
|
102
|
-
"type": None,
|
|
103
|
-
"doc": None,
|
|
104
|
-
"class": None,
|
|
105
|
-
}
|
|
106
|
-
return {
|
|
107
|
-
"type": name,
|
|
108
|
-
"doc": getattr(err_cls, "__doc__", ""),
|
|
109
|
-
"class": err_cls,
|
|
110
|
-
}
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
raiserr = Error()
|
|
114
|
-
|
|
115
|
-
def global_exception_handler(exc_type: Type[Exception], exc_value: Exception, exc_traceback: Any) -> None:
|
|
116
|
-
"""
|
|
117
|
-
全局异常处理器
|
|
118
|
-
|
|
119
|
-
:param exc_type: 异常类型
|
|
120
|
-
:param exc_value: 异常值
|
|
121
|
-
:param exc_traceback: 追踪信息
|
|
122
|
-
"""
|
|
123
|
-
RED = '\033[91m'
|
|
124
|
-
YELLOW = '\033[93m'
|
|
125
|
-
BLUE = '\033[94m'
|
|
126
|
-
RESET = '\033[0m'
|
|
127
|
-
|
|
128
|
-
error_title = f"{RED}{exc_type.__name__}{RESET}: {YELLOW}{exc_value}{RESET}"
|
|
129
|
-
traceback_lines = traceback.format_exception(exc_type, exc_value, exc_traceback)
|
|
130
|
-
|
|
131
|
-
colored_traceback = []
|
|
132
|
-
for line in traceback_lines:
|
|
133
|
-
if "File " in line and ", line " in line:
|
|
134
|
-
parts = line.split(', line ')
|
|
135
|
-
colored_line = f"{BLUE}{parts[0]}{RESET}, line {parts[1]}"
|
|
136
|
-
colored_traceback.append(colored_line)
|
|
137
|
-
else:
|
|
138
|
-
colored_traceback.append(f"{RED}{line}{RESET}")
|
|
139
|
-
|
|
140
|
-
full_error = f"""
|
|
141
|
-
{error_title}
|
|
142
|
-
{RED}Traceback:{RESET}
|
|
143
|
-
{colored_traceback}"""
|
|
144
|
-
|
|
145
|
-
sys.stderr.write(full_error)
|
|
146
|
-
|
|
147
|
-
def async_exception_handler(loop: asyncio.AbstractEventLoop, context: Dict[str, Any]) -> None:
|
|
148
|
-
"""
|
|
149
|
-
异步异常处理器
|
|
150
|
-
|
|
151
|
-
:param loop: 事件循环
|
|
152
|
-
:param context: 上下文字典
|
|
153
|
-
"""
|
|
154
|
-
RED = '\033[91m'
|
|
155
|
-
YELLOW = '\033[93m'
|
|
156
|
-
BLUE = '\033[94m'
|
|
157
|
-
RESET = '\033[0m'
|
|
158
|
-
|
|
159
|
-
exception = context.get('exception')
|
|
160
|
-
if exception:
|
|
161
|
-
tb = ''.join(traceback.format_exception(type(exception), exception, exception.__traceback__))
|
|
162
|
-
|
|
163
|
-
colored_tb = []
|
|
164
|
-
for line in tb.split('\n'):
|
|
165
|
-
if "File " in line and ", line " in line:
|
|
166
|
-
parts = line.split(', line ')
|
|
167
|
-
colored_line = f"{BLUE}{parts[0]}{RESET}, line {parts[1]}"
|
|
168
|
-
colored_tb.append(colored_line)
|
|
169
|
-
else:
|
|
170
|
-
colored_tb.append(f"{RED}{line}{RESET}")
|
|
171
|
-
|
|
172
|
-
error_msg = f"""{RED}{type(exception).__name__}{RESET}: {YELLOW}{exception}{RESET}
|
|
173
|
-
{RED}Traceback:{RESET}
|
|
174
|
-
{colored_tb}"""
|
|
175
|
-
sys.stderr.write(error_msg)
|
|
176
|
-
else:
|
|
177
|
-
msg = context.get('message', 'Unknown async error')
|
|
178
|
-
sys.stderr.write(f"{RED}Async Error{RESET}: {YELLOW}{msg}{RESET}")
|
|
179
|
-
|
|
180
|
-
sys.excepthook = global_exception_handler
|
|
181
|
-
asyncio.get_event_loop().set_exception_handler(async_exception_handler)
|
ErisPulse/Core/util.py
DELETED
|
@@ -1,123 +0,0 @@
|
|
|
1
|
-
"""
|
|
2
|
-
ErisPulse 工具函数集合
|
|
3
|
-
|
|
4
|
-
提供常用工具函数,包括拓扑排序、缓存装饰器、异步执行等实用功能。
|
|
5
|
-
|
|
6
|
-
{!--< tips >!--}
|
|
7
|
-
1. 使用@cache装饰器缓存函数结果
|
|
8
|
-
2. 使用@run_in_executor在独立线程中运行同步函数
|
|
9
|
-
3. 使用@retry实现自动重试机制
|
|
10
|
-
{!--< /tips >!--}
|
|
11
|
-
"""
|
|
12
|
-
|
|
13
|
-
import time
|
|
14
|
-
import asyncio
|
|
15
|
-
import functools
|
|
16
|
-
import traceback
|
|
17
|
-
from concurrent.futures import ThreadPoolExecutor
|
|
18
|
-
from collections import defaultdict, deque
|
|
19
|
-
from typing import List, Dict, Type, Callable, Any, Optional, Set
|
|
20
|
-
|
|
21
|
-
executor = ThreadPoolExecutor()
|
|
22
|
-
|
|
23
|
-
class Util:
|
|
24
|
-
"""
|
|
25
|
-
工具函数集合
|
|
26
|
-
|
|
27
|
-
提供各种实用功能,简化开发流程
|
|
28
|
-
|
|
29
|
-
{!--< tips >!--}
|
|
30
|
-
1. 拓扑排序用于解决依赖关系
|
|
31
|
-
2. 装饰器简化常见模式实现
|
|
32
|
-
3. 异步执行提升性能
|
|
33
|
-
{!--< /tips >!--}
|
|
34
|
-
"""
|
|
35
|
-
def ExecAsync(self, async_func: Callable, *args: Any, **kwargs: Any) -> Any:
|
|
36
|
-
"""
|
|
37
|
-
异步执行函数
|
|
38
|
-
|
|
39
|
-
:param async_func: 异步函数
|
|
40
|
-
:param args: 位置参数
|
|
41
|
-
:param kwargs: 关键字参数
|
|
42
|
-
:return: 函数执行结果
|
|
43
|
-
|
|
44
|
-
:example:
|
|
45
|
-
>>> result = util.ExecAsync(my_async_func, arg1, arg2)
|
|
46
|
-
"""
|
|
47
|
-
loop = asyncio.get_event_loop()
|
|
48
|
-
return loop.run_in_executor(executor, lambda: asyncio.run(async_func(*args, **kwargs)))
|
|
49
|
-
|
|
50
|
-
def cache(self, func: Callable) -> Callable:
|
|
51
|
-
"""
|
|
52
|
-
缓存装饰器
|
|
53
|
-
|
|
54
|
-
:param func: 被装饰函数
|
|
55
|
-
:return: 装饰后的函数
|
|
56
|
-
|
|
57
|
-
:example:
|
|
58
|
-
>>> @util.cache
|
|
59
|
-
>>> def expensive_operation(param):
|
|
60
|
-
>>> return heavy_computation(param)
|
|
61
|
-
"""
|
|
62
|
-
cache_dict = {}
|
|
63
|
-
@functools.wraps(func)
|
|
64
|
-
def wrapper(*args, **kwargs):
|
|
65
|
-
key = (args, tuple(sorted(kwargs.items())))
|
|
66
|
-
if key not in cache_dict:
|
|
67
|
-
cache_dict[key] = func(*args, **kwargs)
|
|
68
|
-
return cache_dict[key]
|
|
69
|
-
return wrapper
|
|
70
|
-
|
|
71
|
-
def run_in_executor(self, func: Callable) -> Callable:
|
|
72
|
-
"""
|
|
73
|
-
在独立线程中执行同步函数的装饰器
|
|
74
|
-
|
|
75
|
-
:param func: 被装饰的同步函数
|
|
76
|
-
:return: 可等待的协程函数
|
|
77
|
-
|
|
78
|
-
:example:
|
|
79
|
-
>>> @util.run_in_executor
|
|
80
|
-
>>> def blocking_io():
|
|
81
|
-
>>> # 执行阻塞IO操作
|
|
82
|
-
>>> return result
|
|
83
|
-
"""
|
|
84
|
-
@functools.wraps(func)
|
|
85
|
-
async def wrapper(*args, **kwargs):
|
|
86
|
-
loop = asyncio.get_event_loop()
|
|
87
|
-
try:
|
|
88
|
-
return await loop.run_in_executor(None, lambda: func(*args, **kwargs))
|
|
89
|
-
except Exception as e:
|
|
90
|
-
from . import logger
|
|
91
|
-
logger.error(f"线程内发生未处理异常:\n{''.join(traceback.format_exc())}")
|
|
92
|
-
return wrapper
|
|
93
|
-
|
|
94
|
-
def retry(self, max_attempts: int = 3, delay: int = 1) -> Callable:
|
|
95
|
-
"""
|
|
96
|
-
自动重试装饰器
|
|
97
|
-
|
|
98
|
-
:param max_attempts: 最大重试次数 (默认: 3)
|
|
99
|
-
:param delay: 重试间隔(秒) (默认: 1)
|
|
100
|
-
:return: 装饰器函数
|
|
101
|
-
|
|
102
|
-
:example:
|
|
103
|
-
>>> @util.retry(max_attempts=5, delay=2)
|
|
104
|
-
>>> def unreliable_operation():
|
|
105
|
-
>>> # 可能失败的操作
|
|
106
|
-
"""
|
|
107
|
-
def decorator(func: Callable) -> Callable:
|
|
108
|
-
@functools.wraps(func)
|
|
109
|
-
def wrapper(*args, **kwargs):
|
|
110
|
-
attempts = 0
|
|
111
|
-
while attempts < max_attempts:
|
|
112
|
-
try:
|
|
113
|
-
return func(*args, **kwargs)
|
|
114
|
-
except Exception as e:
|
|
115
|
-
attempts += 1
|
|
116
|
-
if attempts == max_attempts:
|
|
117
|
-
raise
|
|
118
|
-
time.sleep(delay)
|
|
119
|
-
return wrapper
|
|
120
|
-
return decorator
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
util = Util()
|
|
@@ -1,16 +0,0 @@
|
|
|
1
|
-
ErisPulse/__init__.py,sha256=T-N56UQyBmpvlqwH2wGi5ptPzaJpbgF5tKkJt0DlkaM,26099
|
|
2
|
-
ErisPulse/__main__.py,sha256=gizHkbu70K8wFhYE_3sWUyiZpaL1imuwQHHQ93XVbrQ,35773
|
|
3
|
-
ErisPulse/Core/__init__.py,sha256=tBYPahQ7-w7U6M69xy8DW0_ECa9ja-Q0y_SQqVswYBo,409
|
|
4
|
-
ErisPulse/Core/adapter.py,sha256=ZK81dibJ471FowL0MRXkS113iBcMgj_VzpTw0PzhAEo,18102
|
|
5
|
-
ErisPulse/Core/config.py,sha256=ZmwGdtHSOE7K5uOGzLYcyl3ZF3sAmeWAntqcdfDzhpM,5027
|
|
6
|
-
ErisPulse/Core/env.py,sha256=HGkzsdbxh8c1GSDJhnGP9B09Sz2ZeNbRxWieaFmAcug,18870
|
|
7
|
-
ErisPulse/Core/logger.py,sha256=cJzNXF-EmdWxwgiHg5Itmkwsva2Jhe9l9X4rXKiXHgc,8296
|
|
8
|
-
ErisPulse/Core/mods.py,sha256=2yIq8t9Ca9CBPRiZU0yr8Lc0XGmmkB7LlH-5FWqXjw4,7023
|
|
9
|
-
ErisPulse/Core/raiserr.py,sha256=vlyaaiOIYkyqm9dAqSW9E54JBzX-9roHDp5_r6I0yUU,5591
|
|
10
|
-
ErisPulse/Core/server.py,sha256=FkDTeLuHD5IBnWVxvYU8pHb6yCt8GzyvC1bpOiJ7G7I,9217
|
|
11
|
-
ErisPulse/Core/util.py,sha256=7rdMmn6sBFqYd4znxBCcJjuv2eyTExdeKyZopgds868,3796
|
|
12
|
-
erispulse-2.1.13rc2.dist-info/METADATA,sha256=XTCluJfTY1p3SYwCkN7Ji2-K8VysXzAgqM10hBlYar4,6262
|
|
13
|
-
erispulse-2.1.13rc2.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
|
|
14
|
-
erispulse-2.1.13rc2.dist-info/entry_points.txt,sha256=Jss71M6nEha0TA-DyVZugPYdcL14s9QpiOeIlgWxzOc,182
|
|
15
|
-
erispulse-2.1.13rc2.dist-info/licenses/LICENSE,sha256=4jyqikiB0G0n06CEEMMTzTXjE4IShghSlB74skMSPQs,1464
|
|
16
|
-
erispulse-2.1.13rc2.dist-info/RECORD,,
|
|
File without changes
|
|
File without changes
|
|
File without changes
|