Skip to content

Commit 0a369c8

Browse files
committed
✨ 监控QPS (#180)
1 parent 432ed64 commit 0a369c8

File tree

6 files changed

+81
-4
lines changed

6 files changed

+81
-4
lines changed

gsuid_core/bot.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616
markdown_to_template_markdown,
1717
)
1818
from gsuid_core.gs_logger import GsLogger
19-
from gsuid_core.global_val import get_global_val
19+
from gsuid_core.global_val import bot_traffic, get_global_val
2020
from gsuid_core.load_template import (
2121
parse_button,
2222
custom_buttons,
@@ -55,7 +55,7 @@ def __init__(self, _id: str, ws: Optional[WebSocket] = None):
5555
self.queue = asyncio.queues.Queue()
5656
self.send_dict = {}
5757
self.bg_tasks = set()
58-
self.sem = asyncio.Semaphore(4)
58+
self.sem = asyncio.Semaphore(10)
5959

6060
async def target_send(
6161
self,
@@ -182,12 +182,16 @@ async def _safe_run(self, coro: Coroutine):
182182
async with self.sem:
183183
try:
184184
await coro
185+
186+
bot_traffic["max_qps"] = max(bot_traffic["max_qps"], bot_traffic["req"])
187+
bot_traffic["req"] -= 1
185188
except Exception:
186189
logger.exception("[核心执行异常] 插件执行发生未捕获异常")
187190

188191
async def _process(self):
189192
while True:
190193
coro = await self.queue.get()
194+
bot_traffic["req"] += 1
191195
asyncio.create_task(self._safe_run(coro))
192196
self.queue.task_done()
193197

gsuid_core/buildin_plugins/core_command/core_status/__init__.py

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,13 @@
66
from gsuid_core.bot import Bot
77
from gsuid_core.logger import logger
88
from gsuid_core.models import Event
9-
from gsuid_core.global_val import save_all_global_val
9+
from gsuid_core.global_val import bot_traffic, save_bot_max_qps, save_all_global_val
1010
from gsuid_core.status.draw_status import draw_status
11+
from gsuid_core.status.plugin_status import register_status
1112
from gsuid_core.utils.database.models import CoreUser, CoreGroup
1213

14+
from ..utils import get_ICON
15+
1316
sv_core_status = SV("Core状态", pm=0)
1417

1518
template = """收:{}
@@ -38,9 +41,16 @@ async def count_group_user():
3841
async def _u_clear_and_save_global_val_all():
3942
"""每天凌晨0点执行,清空全局状态"""
4043

44+
global bot_traffic
45+
4146
await save_all_global_val(1)
4247
gv.bot_val = {}
48+
49+
await save_bot_max_qps()
50+
bot_traffic = {"req": 0, "max_qps": 0}
51+
4352
logger.success("[早柚核心] 状态已清空!")
53+
4454
await count_group_user()
4555
logger.success("[早柚核心] 状态已保存!")
4656

@@ -51,6 +61,7 @@ async def _scheduled_save_global_val_all():
5161
"""每隔10分钟执行一次,同步全局状态"""
5262

5363
await save_all_global_val(0)
64+
await save_bot_max_qps()
5465
logger.success("[早柚核心] 状态已同步!")
5566

5667

@@ -96,3 +107,21 @@ async def send_core_status_msg(bot: Bot, ev: Event):
96107
)
97108
else:
98109
await bot.send("暂未存在当天的记录...")
110+
111+
112+
async def get_now_req():
113+
return bot_traffic["req"]
114+
115+
116+
async def get_max_qps():
117+
return bot_traffic["max_qps"]
118+
119+
120+
register_status(
121+
get_ICON(),
122+
"Status",
123+
{
124+
"当前请求量": get_now_req,
125+
"最大QPS": get_max_qps,
126+
},
127+
)
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
from pathlib import Path
2+
3+
from PIL import Image
4+
5+
ICON = Path(__file__).parent.parent.parent.parent / "ICON.png"
6+
7+
8+
def get_ICON() -> Image.Image:
9+
return Image.open(ICON)

gsuid_core/global_val.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
from gsuid_core.data_store import get_res_path
1212
from gsuid_core.utils.database.global_val_models import (
1313
DataType,
14+
CoreTraffic,
1415
CoreDataSummary,
1516
CoreDataAnalysis,
1617
)
@@ -45,6 +46,27 @@ class PlatformVal(TypedDict):
4546
}
4647

4748
bot_val: BotVal = {}
49+
bot_traffic: Dict[str, int] = {
50+
"req": 0,
51+
"max_qps": 0,
52+
}
53+
54+
55+
async def save_bot_max_qps():
56+
logger.info(f"🔒️ 开始保存流量统计! {bot_traffic}")
57+
today = datetime.date.today()
58+
59+
await CoreTraffic.batch_insert_data_with_update(
60+
[
61+
CoreTraffic(
62+
max_qps=bot_traffic["max_qps"],
63+
date=today,
64+
)
65+
],
66+
["max_qps"],
67+
["date"],
68+
)
69+
logger.success("🔒️ 流量统计保存完成!")
4870

4971

5072
def merge_dict(dict1: PlatformVal, dict2: PlatformVal) -> PlatformVal:

gsuid_core/utils/database/global_val_models.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,19 @@ class DataType(enum.Enum):
1414
USER = "user"
1515

1616

17+
class CoreTraffic(BaseIDModel, table=True):
18+
__table_args__ = (
19+
UniqueConstraint(
20+
"date",
21+
name="record_traffic",
22+
),
23+
{"extend_existing": True},
24+
)
25+
26+
max_qps: int = Field(title="最大QPS", default=0)
27+
date: ymddate = Field(title="日期")
28+
29+
1730
class CoreDataSummary(BaseIDModel, table=True):
1831
__table_args__ = (
1932
UniqueConstraint(

gsuid_core/webconsole/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ async def start_check():
3434

3535
if HOST == "localhost" or HOST == "127.0.0.1":
3636
_host = "localhost"
37-
logger.warning("💻 WebConsole挂载于本地, 如想外网访问请修改config.json中host为0.0.0.0!")
37+
logger.warning("💻 WebConsole挂载于本地, 如想外网访问请修改data/config.json中host为0.0.0.0!")
3838
else:
3939
_host = HOST
4040

0 commit comments

Comments
 (0)