Skip to content

Commit 203754e

Browse files
authored
✨feat(core): 优化数据库调用表现 (#2089)
1 parent 7890b39 commit 203754e

10 files changed

Lines changed: 342 additions & 45 deletions

File tree

zhenxun/builtin_plugins/admin/plugin_switch/_data_source.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
from zhenxun.models.plugin_info import PluginInfo
55
from zhenxun.models.task_info import TaskInfo
66
from zhenxun.services.cache import CacheRoot
7+
from zhenxun.services.cache.runtime_cache import TaskInfoMemoryCache
78
from zhenxun.utils.common_utils import CommonUtils
89
from zhenxun.utils.enum import BlockType, CacheType, PluginType
910
from zhenxun.utils.exception import GroupInfoNotFound
@@ -338,9 +339,11 @@ async def block_global_all_task(cls, is_default: bool) -> str:
338339
"""
339340
if is_default:
340341
await TaskInfo.all().update(default_status=False)
342+
await TaskInfoMemoryCache.refresh()
341343
return "已禁用所有被动进群默认状态"
342344
else:
343345
await TaskInfo.all().update(status=False)
346+
await TaskInfoMemoryCache.refresh()
344347
return "已全局禁用所有被动状态"
345348

346349
@classmethod
@@ -355,9 +358,11 @@ async def block_global_task(cls, name: str, is_default: bool = False) -> str:
355358
"""
356359
if is_default:
357360
await TaskInfo.filter(name=name).update(default_status=False)
361+
await TaskInfoMemoryCache.refresh()
358362
return f"已禁用被动进群默认状态 {name}"
359363
else:
360364
await TaskInfo.filter(name=name).update(status=False)
365+
await TaskInfoMemoryCache.refresh()
361366
return f"已全局禁用被动状态 {name}"
362367

363368
@classmethod
@@ -372,9 +377,11 @@ async def unblock_global_all_task(cls, is_default: bool) -> str:
372377
"""
373378
if is_default:
374379
await TaskInfo.all().update(default_status=True)
380+
await TaskInfoMemoryCache.refresh()
375381
return "已开启所有被动进群默认状态"
376382
else:
377383
await TaskInfo.all().update(status=True)
384+
await TaskInfoMemoryCache.refresh()
378385
return "已全局开启所有被动状态"
379386

380387
@classmethod
@@ -390,9 +397,11 @@ async def unblock_global_task(cls, name: str, is_default: bool = False) -> str:
390397
"""
391398
if is_default:
392399
await TaskInfo.filter(name=name).update(default_status=True)
400+
await TaskInfoMemoryCache.refresh()
393401
return f"已开启被动进群默认状态 {name}"
394402
else:
395403
await TaskInfo.filter(name=name).update(status=True)
404+
await TaskInfoMemoryCache.refresh()
396405
return f"已全局开启被动状态 {name}"
397406

398407
@classmethod

zhenxun/builtin_plugins/init/init_plugin.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
from zhenxun.models.plugin_info import PluginInfo
1515
from zhenxun.models.plugin_limit import PluginLimit
1616
from zhenxun.models.task_info import TaskInfo
17+
from zhenxun.services.cache.runtime_cache import TaskInfoMemoryCache
1718
from zhenxun.services.log import logger
1819
from zhenxun.utils.enum import (
1920
BlockType,
@@ -379,6 +380,7 @@ async def group_migration():
379380
if close_task := data["close_task"]:
380381
"""全局被动关闭"""
381382
await TaskInfo.filter(module__in=close_task).update(status=False)
383+
await TaskInfoMemoryCache.refresh()
382384
group_list = await GroupConsole.filter(
383385
group_id__in=old_group_list.keys()
384386
)

zhenxun/builtin_plugins/init/init_task.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
from zhenxun.configs.utils import PluginExtraData, Task
99
from zhenxun.models.group_console import GroupConsole
1010
from zhenxun.models.task_info import TaskInfo
11+
from zhenxun.services.cache.runtime_cache import TaskInfoMemoryCache
1112
from zhenxun.services.log import logger
1213
from zhenxun.utils.common_utils import CommonUtils
1314
from zhenxun.utils.manager.priority_manager import PriorityLifecycle
@@ -89,6 +90,8 @@ async def to_db(
8990
if load_task:
9091
await TaskInfo.filter(module__in=load_task).update(load_status=True)
9192
await TaskInfo.filter(module__not_in=load_task).update(load_status=False)
93+
if create_list or update_list or load_task:
94+
await TaskInfoMemoryCache.refresh()
9295

9396

9497
async def get_run_task(task: Task, *args, **kwargs):
@@ -144,6 +147,7 @@ async def _():
144147
await _handle_setting(plugin, task_info_list, task_list)
145148
if not task_info_list:
146149
await TaskInfo.all().update(load_status=False)
150+
await TaskInfoMemoryCache.refresh()
147151
return
148152
module_dict = {t[1]: t[0] for t in await TaskInfo.all().values_list("id", "module")}
149153
load_task = []

zhenxun/builtin_plugins/statistics/statistics_hook.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
from zhenxun.configs.utils import PluginExtraData
1212
from zhenxun.models.plugin_info import PluginInfo
1313
from zhenxun.models.statistics import Statistics
14+
from zhenxun.services.cache.runtime_cache import PluginInfoMemoryCache
1415
from zhenxun.services.log import logger
1516
from zhenxun.services.message_load import should_pause_tasks
1617
from zhenxun.utils.enum import PluginType
@@ -39,7 +40,11 @@ async def _(
3940
"""过滤除poke外的notice"""
4041
return
4142
if session.id1 and matcher.plugin:
42-
plugin = await PluginInfo.get_plugin(module_path=matcher.plugin.module_name)
43+
plugin = PluginInfoMemoryCache.get_by_module_path(matcher.plugin.module_name)
44+
if not plugin:
45+
plugin = await PluginInfo.get_plugin(module_path=matcher.plugin.module_name)
46+
if plugin:
47+
PluginInfoMemoryCache.set_plugin(plugin)
4348
plugin_type = plugin.plugin_type if plugin else None
4449
if plugin_type == PluginType.NORMAL:
4550
logger.debug(f"提交调用记录: {matcher.plugin_name}...", session=session)

zhenxun/models/bot_console.py

Lines changed: 24 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -62,8 +62,9 @@ async def get_bot_status(
6262
list[tuple[str, bool]] | bool: bot状态
6363
"""
6464
if not bot_id:
65-
return await cls.all().values_list("bot_id", "status")
66-
result = await cls.get_or_none(bot_id=bot_id)
65+
data = await BotMemoryCache.get_all()
66+
return [(bot_id, snapshot.status) for bot_id, snapshot in data.items()]
67+
result = await BotMemoryCache.get(bot_id)
6768
return result.status if result else False
6869

6970
@overload
@@ -95,12 +96,13 @@ async def get_tasks(cls, bot_id: str | None = None, status: bool | None = True):
9596
list[tuple[str, str]] | str: 被动技能
9697
"""
9798
if not bot_id:
98-
task_field: Literal["available_tasks", "block_tasks"] = (
99-
"available_tasks" if status else "block_tasks"
100-
)
101-
data_list = await cls.all().values_list("bot_id", task_field)
102-
return {k: cls.convert_module_format(v) for k, v in data_list}
103-
result = await cls.get_or_none(bot_id=bot_id)
99+
data = await BotMemoryCache.get_all()
100+
task_attr = "available_tasks" if status else "block_tasks"
101+
return {
102+
bot_id: cls.convert_module_format(getattr(snapshot, task_attr))
103+
for bot_id, snapshot in data.items()
104+
}
105+
result = await BotMemoryCache.get(bot_id)
104106
if result:
105107
tasks = result.available_tasks if status else result.block_tasks
106108
return cls.convert_module_format(tasks)
@@ -135,11 +137,14 @@ async def get_plugins(cls, bot_id: str | None = None, status: bool = True):
135137
list[tuple[str, str]] | str: 插件
136138
"""
137139
if not bot_id:
138-
plugin_field = "available_plugins" if status else "block_plugins"
139-
data_list = await cls.all().values_list("bot_id", plugin_field)
140-
return {k: cls.convert_module_format(v) for k, v in data_list}
141-
142-
result = await cls.get_or_none(bot_id=bot_id)
140+
data = await BotMemoryCache.get_all()
141+
plugin_attr = "available_plugins" if status else "block_plugins"
142+
return {
143+
bot_id: cls.convert_module_format(getattr(snapshot, plugin_attr))
144+
for bot_id, snapshot in data.items()
145+
}
146+
147+
result = await BotMemoryCache.get(bot_id)
143148
if result:
144149
plugins = result.available_plugins if status else result.block_plugins
145150
return cls.convert_module_format(plugins)
@@ -419,7 +424,9 @@ async def is_block_plugin(cls, bot_id: str, plugin_name: str) -> bool:
419424
返回:
420425
bool: 是否被禁用
421426
"""
422-
bot_data, _ = await cls.get_or_create(bot_id=bot_id)
427+
bot_data = await BotMemoryCache.get(bot_id)
428+
if not bot_data:
429+
return False
423430
return cls.format(plugin_name) in bot_data.block_plugins
424431

425432
@classmethod
@@ -434,7 +441,9 @@ async def is_block_task(cls, bot_id: str, task_name: str) -> bool:
434441
返回:
435442
bool: 是否被禁用
436443
"""
437-
bot_data, _ = await cls.get_or_create(bot_id=bot_id)
444+
bot_data = await BotMemoryCache.get(bot_id)
445+
if not bot_data:
446+
return False
438447
return cls.format(task_name) in bot_data.block_tasks
439448

440449
@classmethod

zhenxun/models/level_user.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ async def get_user_level(cls, user_id: str, group_id: str | None) -> int:
4040
"""
4141
if not group_id:
4242
return 0
43-
if user := await cls.get_or_none(user_id=user_id, group_id=group_id):
43+
if user := await LevelUserMemoryCache.get(user_id, group_id):
4444
return user.user_level
4545
return 0
4646

@@ -103,11 +103,11 @@ async def check_level(cls, user_id: str, group_id: str | None, level: int) -> bo
103103
if level == 0:
104104
return True
105105
if group_id:
106-
if user := await cls.get_or_none(user_id=user_id, group_id=group_id):
106+
if user := await LevelUserMemoryCache.get(user_id, group_id):
107107
return user.user_level >= level
108-
elif user_list := await cls.filter(user_id=user_id).all():
109-
user = max(user_list, key=lambda x: x.user_level)
110-
return user.user_level >= level
108+
return False
109+
max_level = await LevelUserMemoryCache.get_max_level(user_id)
110+
return max_level >= level
111111
return False
112112

113113
@classmethod
@@ -121,7 +121,7 @@ async def is_group_flag(cls, user_id: str, group_id: str) -> bool:
121121
返回:
122122
bool: 是否会被自动更新权限刷新
123123
"""
124-
if user := await cls.get_or_none(user_id=user_id, group_id=group_id):
124+
if user := await LevelUserMemoryCache.get(user_id, group_id):
125125
return user.group_flag == 1
126126
return False
127127

zhenxun/models/task_info.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
from tortoise import fields
22

3+
from zhenxun.services.cache.runtime_cache import TaskInfoMemoryCache
34
from zhenxun.services.db_context import Model
45

56

@@ -25,6 +26,27 @@ class Meta: # pyright: ignore [reportIncompatibleVariableOverride]
2526
table = "task_info"
2627
table_description = "被动技能基本信息"
2728

29+
@classmethod
30+
async def create(cls, *args, **kwargs):
31+
result = await super().create(*args, **kwargs)
32+
await TaskInfoMemoryCache.upsert_from_model(result)
33+
return result
34+
35+
@classmethod
36+
async def update_or_create(cls, *args, **kwargs):
37+
result = await super().update_or_create(*args, **kwargs)
38+
await TaskInfoMemoryCache.upsert_from_model(result[0])
39+
return result
40+
41+
async def save(self, *args, **kwargs):
42+
await super().save(*args, **kwargs)
43+
await TaskInfoMemoryCache.upsert_from_model(self)
44+
45+
async def delete(self, *args, **kwargs):
46+
module = self.module
47+
await super().delete(*args, **kwargs)
48+
await TaskInfoMemoryCache.remove(module)
49+
2850
@classmethod
2951
async def _run_script(cls):
3052
return [

zhenxun/services/cache/__init__.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1092,8 +1092,11 @@ async def clear(self) -> bool:
10921092

10931093
@driver.on_startup
10941094
async def _():
1095-
CacheRoot.enabled = True
1096-
logger.info("缓存系统已启用", LOG_COMMAND)
1095+
CacheRoot.enabled = cache_config.cache_mode != CacheMode.NONE
1096+
if CacheRoot.enabled:
1097+
logger.info("缓存系统已启用", LOG_COMMAND)
1098+
else:
1099+
logger.info("缓存系统已禁用", LOG_COMMAND)
10971100

10981101

10991102
@driver.on_shutdown

0 commit comments

Comments
 (0)