Skip to content

Commit 5b81898

Browse files
committed
💥 move meta-config $prefix to plugin
1 parent 0427e63 commit 5b81898

9 files changed

Lines changed: 325 additions & 196 deletions

File tree

‎arclet/entari/config/file.py‎

Lines changed: 42 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,12 @@
22
import os
33
import re
44
import warnings
5+
from collections import defaultdict
56
from collections.abc import Callable, MutableMapping
67
from dataclasses import dataclass, field
78
from importlib import import_module
89
from io import StringIO
10+
from itertools import chain
911
from pathlib import Path
1012
from typing import TYPE_CHECKING, Any, ClassVar, TypeVar
1113

@@ -43,14 +45,17 @@ class EntariConfig:
4345
path: Path
4446
basic: BasicConfig = field(default_factory=BasicConfig, init=False)
4547
plugin: dict[str, dict] = field(default_factory=dict, init=False)
48+
plugin_prefixes: dict[str, list[str]] = field(default_factory=dict, init=False)
4649
prelude_plugin: list[str] = field(default_factory=list, init=False)
4750
plugin_extra_files: list[str] = field(default_factory=list, init=False)
4851
save_flag: bool = field(default=False)
4952
env_vars: dict[str, str] = field(default_factory=dict)
53+
_plugin_names: dict[str, list[str]] = field(default_factory=dict, init=False)
5054
_origin_data: dict[str, Any] = field(init=False)
5155
_env_replaced: dict[str, dict[int, tuple[str, int]]] = field(default_factory=dict, init=False)
5256

5357
instance: ClassVar["EntariConfig"]
58+
_inited: ClassVar[bool] = False
5459

5560
def loader(self, path: Path):
5661
if not path.exists():
@@ -103,6 +108,7 @@ def dumper(self, path: Path, save_path: Path, data: dict, indent: int, apply_sch
103108

104109
def __post_init__(self):
105110
self.__class__.instance = self
111+
self.__class__._inited = True
106112
self.reload()
107113

108114
@property
@@ -111,21 +117,26 @@ def data(self) -> dict[str, Any]:
111117

112118
@property
113119
def prelude_plugin_names(self) -> list[str]:
114-
return [name for name in self.plugin_names if name in self.prelude_plugin]
120+
return [
121+
name
122+
for key, names in self._plugin_names.items()
123+
for name in names
124+
if key in self.prelude_plugin or name in self.prelude_plugin
125+
]
115126

116127
@property
117128
def plugin_names(self) -> list[str]:
118-
slots = [
119-
(name, self.plugin[name].get("$priority", 16))
120-
for name in self.plugin
121-
if not name.startswith("$") and not self.plugin[name].get("$optional", False)
122-
]
123-
slots.sort(key=lambda x: x[1])
124-
return [name for name, _ in slots]
129+
return list(chain.from_iterable(self._plugin_names.values()))
125130

126131
def _reload_plugins(self):
127132
self.plugin_extra_files: list[str] = self.plugin.get("$files", []) # type: ignore
128133
self.prelude_plugin = self.plugin.get("$prelude", []) # type: ignore
134+
plugin_prefixes = {item["key"]: item["plugins"] for item in self.plugin.get("$prefix", [])} # type: ignore
135+
inverted = defaultdict(list)
136+
for key, plugs in plugin_prefixes.items():
137+
for plug in plugs:
138+
inverted[plug].append(key)
139+
self.plugin_prefixes = dict(inverted)
129140
for key in list(self.plugin.keys()):
130141
if key.startswith("$"):
131142
continue
@@ -150,6 +161,22 @@ def _reload_plugins(self):
150161
elif path.name.endswith(".schema.json"):
151162
self.plugin[path.stem] = self.loader(path)
152163

164+
slots = [
165+
(name, self.plugin[name].get("$priority", 16))
166+
for name in self.plugin
167+
if not name.startswith("$") and not self.plugin[name].get("$optional", False)
168+
]
169+
slots.sort(key=lambda x: x[1])
170+
ans: defaultdict[str, list[str]] = defaultdict(list)
171+
for name, _ in slots:
172+
if (prefixes := self.plugin_prefixes.get(name)) is not None:
173+
ans[name].extend((f"{prefix}{name}" if prefix else name) for prefix in prefixes)
174+
elif name.count(".") or name.startswith("::") or name.startswith("entari_plugin_"):
175+
ans[name].append(name)
176+
else:
177+
ans[name].append(f"entari_plugin_{name}")
178+
self._plugin_names = dict(ans)
179+
153180
def reload(self):
154181
if self.save_flag:
155182
self.save_flag = False
@@ -242,7 +269,11 @@ def bind(self, key: str, plugin: dict, obj: T) -> T:
242269
Bind the plugin object to the config, allowing the config to be updated when the object changes.
243270
"""
244271
if key not in self.plugin:
245-
raise KeyError(f"Plugin Config {key} not found in config")
272+
for _, names in self._plugin_names.items():
273+
if key in names:
274+
break
275+
else:
276+
raise KeyError(f"Plugin Config {key} not found in config")
246277

247278
def updater(target):
248279
nest_dict_update(plugin, config_model_dump(target))
@@ -256,7 +287,7 @@ def updater(target):
256287
def generate_schema(self, plugins: list["Plugin"]):
257288
plugins_properties = {}
258289
# fmt: off
259-
plugin_meta_properties = {"$disable": {"type": "string", "description": "Expression for whether disable this plugin"}, "$prefix": {"type": "string", "description": "Plugin name prefix"}, "$priority": {"type": "integer", "description": "Plugin loading priority, lower value means higher priority (default: 16)"}, "$filter": {"type": "string", "description": "Plugin filter expression, which will be evaluated in the context of the plugin"}} # noqa: E501
290+
plugin_meta_properties = {"$disable": {"type": "string", "description": "Expression for whether disable this plugin"}, "$priority": {"type": "integer", "description": "Plugin loading priority, lower value means higher priority (default: 16)"}, "$filter": {"type": "string", "description": "Plugin filter expression, which will be evaluated in the context of the plugin"}} # noqa: E501
260291
# Build a mapping from plugin config key to plugin object for $files schema generation
261292
plugin_map: dict[str, "Plugin"] = {} # noqa: UP037
262293
for plug in plugins:
@@ -271,7 +302,7 @@ def generate_schema(self, plugins: list["Plugin"]):
271302
else:
272303
plugins_properties[plug._config_key] = {"type": "object", "description": "No configuration required", "additionalProperties": True, "properties": plugin_meta_properties} # noqa: E501
273304
schemas = {
274-
"basic": config_model_schema(BasicConfig, ref_root="/properties/basic/"), "plugins": {"type": "object", "description": "Plugin configurations", "properties": {"$prelude": {"type": "array", "items": {"type": "string", "description": "Plugin name"}, "description": "List of prelude plugins to load", "default": [], "uniqueItems": True}, "$files": {"type": "array", "items": {"type": "string", "description": "File path"}, "description": "List of configuration files to load", "default": [], "uniqueItems": True}, **plugins_properties}}, "adapters": {"type": "array", "description": "Adapter configurations", "items": {"type": "object", "description": "Adapter configuration", "properties": {"$path": {"type": "string", "description": "Adapter Module Path"}}, "required": ["$path"], "additionalProperties": True}} # noqa: E501
305+
"basic": config_model_schema(BasicConfig, ref_root="/properties/basic/"), "plugins": {"type": "object", "description": "Plugin configurations", "properties": {"$prefix": {"description": "List of prefix config", "items": {"properties": {"key": {"description": "Prefix key", "title": "Key", "type": "string"}, "plugins": {"description": "List of plugins under the prefix", "items": {"type": "string", "description": "Plugin name"}, "title": "Plugins", "type": "array", "uniqueItems": True}}, "required": ["key"], "title": "Prefix Config", "type": "object"}, "type": "array"}, "$prelude": {"type": "array", "items": {"type": "string", "description": "Plugin name"}, "description": "List of prelude plugins to load", "default": [], "uniqueItems": True}, "$files": {"type": "array", "items": {"type": "string", "description": "File path"}, "description": "List of configuration files to load", "default": [], "uniqueItems": True}, **plugins_properties}}, "adapters": {"type": "array", "description": "Adapter configurations", "items": {"type": "object", "description": "Adapter configuration", "properties": {"$path": {"type": "string", "description": "Adapter Module Path"}}, "required": ["$path"], "additionalProperties": True}} # noqa: E501
275306
}
276307
with open(f"{self.path.stem}.schema.json", "w", encoding="utf-8") as f:
277308
json.dump({"$schema": "https://json-schema.org/draft/2020-12/schema", "type": "object", "properties": schemas, "additionalProperties": False, "required": ["basic"]}, f, indent=2, ensure_ascii=False) # noqa: E501

‎arclet/entari/config/model.py‎

Lines changed: 49 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -5,68 +5,74 @@
55

66

77
class WebsocketsInfo(BasicConfModel):
8-
"""Satori Server WebSocket Configuration"""
8+
"""Satori 服务器 WebSocket 配置"""
99

10-
type: Literal["websocket", "websockets", "ws"]
11-
host: str = model_field(default="localhost", description="WebSocket server host")
12-
port: int = model_field(default=5140, description="WebSocket server port")
13-
path: str = model_field(default="", description="WebSocket server endpoint path")
14-
secure: bool = model_field(default=False, description="Whether to use HTTPS and WSS for the server connection")
15-
token: str | None = model_field(default=None, description="Authentication token for the WebSocket server")
16-
timeout: float | None = model_field(default=None, description="Connection timeout in seconds")
10+
type: Literal["websocket", "websockets", "ws"] = model_field(
11+
description="连接类型,必须是 'websocket'、'websockets' 或 'ws'"
12+
)
13+
host: str = model_field(default="localhost", description="服务器主机地址")
14+
port: int = model_field(default=5140, description="服务器端口")
15+
path: str = model_field(default="", description="服务器路径")
16+
secure: bool = model_field(default=False, description="是否使用安全连接(wss 和 https)")
17+
token: str | None = model_field(default=None, description="连接的鉴权令牌")
18+
timeout: float | None = model_field(default=None, description="连接超时时间(秒)")
1719

1820

1921
class WebhookInfo(BasicConfModel):
20-
"""Satori Server Webhook Configuration"""
22+
"""Satori 服务器 Webhook 配置"""
2123

22-
type: Literal["webhook", "wh", "http"]
23-
host: str = model_field(default="127.0.0.1", description="Webhook self-server host")
24-
port: int = model_field(default=8080, description="Webhook self-server port")
25-
path: str = model_field(default="v1/events", description="Webhook self-server endpoint path")
26-
secure: bool = model_field(default=False, description="Whether to use HTTPS for the server connection")
27-
token: str | None = model_field(default=None, description="Authentication token for the webhook")
28-
server_host: str = model_field(default="localhost", description="Target server host")
29-
server_port: int = model_field(default=5140, description="Target server port")
30-
server_path: str = model_field(default="", description="Target server endpoint path")
31-
timeout: float | None = model_field(default=None, description="Connection timeout in seconds")
24+
type: Literal["webhook", "wh", "http"] = model_field(description="连接类型,必须是 'webhook'、'wh' 或 'http'")
25+
host: str = model_field(default="127.0.0.1", description="本机 Webhook 服务器主机地址")
26+
port: int = model_field(default=8080, description="本机 Webhook 服务器端口")
27+
path: str = model_field(default="v1/events", description="本机 Webhook 服务器路径")
28+
secure: bool = model_field(default=False, description="是否使用安全连接(wss 和 https)")
29+
token: str | None = model_field(default=None, description="连接的鉴权令牌")
30+
server_host: str = model_field(default="localhost", description="发送请求的目标服务器主机地址")
31+
server_port: int = model_field(default=5140, description="发送请求的目标服务器端口")
32+
server_path: str = model_field(default="", description="发送请求的目标服务器路径")
33+
timeout: float | None = model_field(default=None, description="连接超时时间(秒)")
3234

3335

3436
class LogSaveInfo(BasicConfModel):
35-
"""Configuration for saving logs to a file"""
37+
"""日志保存相关配置"""
3638

37-
rotation: str = model_field(default="00:00", description="Log rotation time, e.g., '00:00' for daily rotation")
38-
compression: str | None = model_field(default=None, description="Compression format for log saving, e.g., 'zip'")
39-
colorize: bool = model_field(default=True, description="Whether to colorize the log output")
39+
rotation: str = model_field(
40+
default="00:00",
41+
description="日志轮转时间,支持时间字符串(如 '00:00' 表示每天午夜轮转)或文件大小(如 '10 MB')",
42+
)
43+
compression: str | None = model_field(default=None, description="日志压缩格式,支持 'zip'、'tar'、'gz' 等常见格式")
44+
colorize: bool = model_field(default=True, description="是否在保存的日志中保留颜色信息")
4045

4146

4247
class LogInfo(BasicConfModel):
43-
"""Configuration for the application logs"""
48+
"""日志相关配置"""
4449

45-
level: int | str = model_field(default="INFO", description="Log level for the application")
46-
ignores: list[str] = model_field(default_factory=list, description="Log ignores for the application")
50+
level: int | str = model_field(default="INFO", description="日志级别")
51+
ignores: list[str] = model_field(
52+
default_factory=list, description="日志过滤器,指定要忽略的日志记录器名称列表(可以使用通配符)"
53+
)
4754
save: LogSaveInfo | bool | None = model_field(
4855
default=None,
49-
description="Log saving configuration, if None or False, logs will not be saved",
56+
description="日志保存配置,设置为 False 或 None 则不保存日志",
5057
)
51-
rich_error: bool = model_field(default=False, description="Whether enable rich traceback for exceptions")
52-
short_level: bool = model_field(default=False, description="Whether use short log level names")
58+
rich_error: bool = model_field(default=False, description="是否使用 Rich 库美化错误日志")
59+
short_level: bool = model_field(default=False, description="是否在日志中使用简短的级别名称(如 'I' 代替 'INFO')")
5360

5461

5562
class BasicConfig(BasicConfModel):
56-
"""Basic configuration for the Entari application"""
57-
58-
network: list[WebsocketsInfo | WebhookInfo] = model_field(default_factory=list, description="Network configuration")
59-
ignore_self_message: bool = model_field(default=True, description="Whether ignore self-send message event")
60-
skip_req_missing: bool = model_field(
61-
default=False, description="Whether skip Event Handler if requirement is missing"
62-
)
63-
log: LogInfo = model_field(default_factory=LogInfo, description="Log configuration")
64-
prefix: list[str] = model_field(default_factory=list, description="Command prefix for the application")
65-
nickname: str = model_field(default="", description="Bot nickname for the application (used in command matching)")
66-
cmd_count: int = model_field(default=4096, description="Command count limit for the application")
67-
external_dirs: list[str] = model_field(default_factory=list, description="External directories to look for plugins")
68-
schema: bool = model_field(
69-
default=False, description="Whether generate JSON schema for the configuration (after application start)"
63+
"""Entari 应用的基础配置"""
64+
65+
network: list[WebsocketsInfo | WebhookInfo] = model_field(default_factory=list, description="网络相关配置")
66+
ignore_self_message: bool = model_field(default=True, description="是否忽略自己发送的消息事件")
67+
skip_req_missing: bool = model_field(default=False, description="是否跳过无法执行的事件监听器")
68+
log: LogInfo = model_field(default_factory=LogInfo, description="日志相关配置")
69+
prefix: list[str] = model_field(default_factory=list, description="命令前缀列表,支持多个前缀(如 ['/', '!'])")
70+
nickname: str = model_field(default="", description="Bot 昵称,主要用于命令匹配")
71+
cmd_count: int = model_field(default=4096, description="命令数量限制,超过该数量的命令将无法注册")
72+
external_dirs: list[str] = model_field(default_factory=list, description="用来查找插件的外部目录列表,支持多个目录")
73+
schema: bool = model_field(default=False, description="是否为配置文件生成 JSON Schema(会在启动时生成)")
74+
check_metadata: bool = model_field(
75+
default=False, description="是否利用元数据进行插件导入检测(可能会增加启动时间)"
7076
)
7177

7278
def __post_init__(self):

‎arclet/entari/core.py‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import sys
55
from collections.abc import Iterable, Sequence
66
from dataclasses import asdict
7+
from importlib.metadata import entry_points
78
from pathlib import Path
89
from typing import get_args
910

@@ -419,6 +420,7 @@ def ensure_manager(self, manager: Launart):
419420
manager.add_component(plugin_service)
420421
manager.add_component(MemcacheService())
421422

423+
requires(*(entry.module for entry in entry_points(group="entari.plugin")))
422424
requires(*EntariConfig.instance.prelude_plugin)
423425
for plug in EntariConfig.instance.prelude_plugin_names:
424426
load_plugin(plug, prelude=True)
@@ -430,6 +432,10 @@ def ensure_manager(self, manager: Launart):
430432
for plug in plugins:
431433
load_plugin(plug)
432434

435+
for entry in entry_points(group="entari.plugin"):
436+
if entry.name not in plugins and entry.module not in plugin_service.plugins:
437+
load_plugin(entry.module)
438+
433439
if self.gen_schema and EntariConfig.instance.path.exists():
434440
EntariConfig.instance.generate_schema(get_plugins())
435441

‎arclet/entari/exceptions.py‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,11 @@
1+
from types import FunctionType
2+
13
from .utils import escape_tag
24

35

46
class RegisterNotInPluginError(Exception):
57
def __init__(self, func, mod, pid):
8+
self.func: FunctionType = func
69
self.msg = f"""\
710
Handler `{escape_tag(func.__qualname__)}` from {func.__module__!r}\
811
should define in the same module as the plugin: {mod.__name__!r}.

‎arclet/entari/plugin/__init__.py‎

Lines changed: 19 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -160,9 +160,16 @@ def load_plugin(
160160
recursive_guard (set[str]): 递归保护
161161
prelude (bool): 是否为前置插件
162162
"""
163-
if config is None:
164-
config = EntariConfig.instance.plugin.get(path, {})
165-
config["$path"] = path
163+
if config is not None:
164+
config["$path"] = path
165+
else:
166+
for k, names in EntariConfig.instance._plugin_names.items():
167+
if path in names:
168+
config = EntariConfig.instance.plugin.get(k, {})
169+
config["$path"] = k
170+
break
171+
else:
172+
config = {"$path": path}
166173
if prelude:
167174
config["$static"] = True
168175
if recursive_guard is None:
@@ -177,12 +184,12 @@ def load_plugin(
177184
plugin_service._direct_plugins.add(plug.path)
178185
return plug
179186
try:
180-
if pref := config.get("$prefix"):
181-
path = f"{pref if isinstance(pref, str) else 'entari_plugin_'}{path}"
182187
mod = import_plugin(path, config=config)
183-
if not pref and not mod and not path.count("."):
184-
path1 = f"entari_plugin_{path}"
185-
mod = import_plugin(path1, config=config)
188+
if not mod:
189+
mod = next(
190+
(import_plugin(_path, config=config) for _path in EntariConfig.instance._plugin_names.get(path, [])),
191+
None,
192+
)
186193
if not mod:
187194
log.plugin.error(f"cannot found plugin <blue>{path!r}</blue>")
188195
publish(PluginLoadedFailed(path))
@@ -339,6 +346,10 @@ def find_plugin(name: str) -> Plugin | None:
339346
"""根据插件名称查找插件"""
340347
if name in plugin_service.plugins:
341348
return plugin_service.plugins[name]
349+
if name in EntariConfig.instance.plugin_prefixes:
350+
for prefix in EntariConfig.instance.plugin_prefixes[name]:
351+
if f"{prefix}{name}" in plugin_service.plugins:
352+
return plugin_service.plugins[f"{prefix}{name}"]
342353
if not name.count(".") and f"entari_plugin_{name}" in plugin_service.plugins:
343354
return plugin_service.plugins[f"entari_plugin_{name}"]
344355

0 commit comments

Comments
 (0)