feat:非大内存模式下主动gc

This commit is contained in:
jxxghp
2025-06-27 09:44:47 +08:00
parent 0baf6e5fe7
commit bb4438ac42
5 changed files with 545 additions and 498 deletions
+37 -8
View File
@@ -136,6 +136,7 @@ class MessageChain(ChainBase):
logger.info(f'收到用户消息内容,用户:{userid},内容:{text}') logger.info(f'收到用户消息内容,用户:{userid},内容:{text}')
# 加载缓存 # 加载缓存
user_cache: Dict[str, dict] = self.load_cache(self._cache_file) or {} user_cache: Dict[str, dict] = self.load_cache(self._cache_file) or {}
try:
# 保存消息 # 保存消息
if not text.startswith('CALLBACK:'): if not text.startswith('CALLBACK:'):
self.messagehelper.put( self.messagehelper.put(
@@ -173,7 +174,6 @@ class MessageChain(ChainBase):
"source": source "source": source
} }
) )
elif text.isdigit(): elif text.isdigit():
# 用户选择了具体的条目 # 用户选择了具体的条目
# 缓存 # 缓存
@@ -185,6 +185,7 @@ class MessageChain(ChainBase):
# 发送消息 # 发送消息
self.post_message(Notification(channel=channel, source=source, title="输入有误!", userid=userid)) self.post_message(Notification(channel=channel, source=source, title="输入有误!", userid=userid))
return return
try:
# 选择的序号 # 选择的序号
_choice = int(text) + _current_page * self._page_size - 1 _choice = int(text) + _current_page * self._page_size - 1
# 缓存类型 # 缓存类型
@@ -192,6 +193,7 @@ class MessageChain(ChainBase):
# 缓存列表 # 缓存列表
cache_list: list = cache_data.get('items').copy() cache_list: list = cache_data.get('items').copy()
# 选择 # 选择
try:
if cache_type in ["Search", "ReSearch"]: if cache_type in ["Search", "ReSearch"]:
# 当前媒体信息 # 当前媒体信息
mediainfo: MediaInfo = cache_list[_choice] mediainfo: MediaInfo = cache_list[_choice]
@@ -251,6 +253,7 @@ class MessageChain(ChainBase):
return return
# 搜索结果排序 # 搜索结果排序
contexts = TorrentHelper().sort_torrents(contexts) contexts = TorrentHelper().sort_torrents(contexts)
try:
# 判断是否设置自动下载 # 判断是否设置自动下载
auto_download_user = settings.AUTO_DOWNLOAD_USER auto_download_user = settings.AUTO_DOWNLOAD_USER
# 匹配到自动下载用户 # 匹配到自动下载用户
@@ -291,7 +294,9 @@ class MessageChain(ChainBase):
items=contexts[:self._page_size], items=contexts[:self._page_size],
userid=userid, userid=userid,
total=len(contexts)) total=len(contexts))
finally:
contexts.clear()
del contexts
elif cache_type in ["Subscribe", "ReSubscribe"]: elif cache_type in ["Subscribe", "ReSubscribe"]:
# 订阅或洗版媒体 # 订阅或洗版媒体
mediainfo: MediaInfo = cache_list[_choice] mediainfo: MediaInfo = cache_list[_choice]
@@ -338,7 +343,12 @@ class MessageChain(ChainBase):
# 下载 # 下载
DownloadChain().download_single(context, channel=channel, source=source, DownloadChain().download_single(context, channel=channel, source=source,
userid=userid, username=username) userid=userid, username=username)
finally:
cache_list.clear()
del cache_list
finally:
cache_data.clear()
del cache_data
elif text.lower() == "p": elif text.lower() == "p":
# 上一页 # 上一页
cache_data: dict = user_cache.get(userid).copy() cache_data: dict = user_cache.get(userid).copy()
@@ -347,7 +357,7 @@ class MessageChain(ChainBase):
self.post_message(Notification( self.post_message(Notification(
channel=channel, source=source, title="输入有误!", userid=userid)) channel=channel, source=source, title="输入有误!", userid=userid))
return return
try:
if _current_page == 0: if _current_page == 0:
# 第一页 # 第一页
self.post_message(Notification( self.post_message(Notification(
@@ -358,6 +368,7 @@ class MessageChain(ChainBase):
cache_type: str = cache_data.get('type') cache_type: str = cache_data.get('type')
# 产生副本,避免修改原值 # 产生副本,避免修改原值
cache_list: list = cache_data.get('items').copy() cache_list: list = cache_data.get('items').copy()
try:
if _current_page == 0: if _current_page == 0:
start = 0 start = 0
end = self._page_size end = self._page_size
@@ -384,7 +395,12 @@ class MessageChain(ChainBase):
total=len(cache_list), total=len(cache_list),
original_message_id=original_message_id, original_message_id=original_message_id,
original_chat_id=original_chat_id) original_chat_id=original_chat_id)
finally:
cache_list.clear()
del cache_list
finally:
cache_data.clear()
del cache_data
elif text.lower() == "n": elif text.lower() == "n":
# 下一页 # 下一页
cache_data: dict = user_cache.get(userid).copy() cache_data: dict = user_cache.get(userid).copy()
@@ -393,19 +409,20 @@ class MessageChain(ChainBase):
self.post_message(Notification( self.post_message(Notification(
channel=channel, source=source, title="输入有误!", userid=userid)) channel=channel, source=source, title="输入有误!", userid=userid))
return return
try:
cache_type: str = cache_data.get('type') cache_type: str = cache_data.get('type')
# 产生副本,避免修改原值 # 产生副本,避免修改原值
cache_list: list = cache_data.get('items').copy() cache_list: list = cache_data.get('items').copy()
total = len(cache_list) total = len(cache_list)
# 加一页 # 加一页
cache_list = cache_list[ cache_list = cache_list[(_current_page + 1) * self._page_size:(_current_page + 2) * self._page_size]
(_current_page + 1) * self._page_size:(_current_page + 2) * self._page_size]
if not cache_list: if not cache_list:
# 没有数据 # 没有数据
self.post_message(Notification( self.post_message(Notification(
channel=channel, source=source, title="已经是最后一页了!", userid=userid)) channel=channel, source=source, title="已经是最后一页了!", userid=userid))
return return
else: else:
try:
# 加一页 # 加一页
_current_page += 1 _current_page += 1
if cache_type == "Torrent": if cache_type == "Torrent":
@@ -428,7 +445,12 @@ class MessageChain(ChainBase):
total=total, total=total,
original_message_id=original_message_id, original_message_id=original_message_id,
original_chat_id=original_chat_id) original_chat_id=original_chat_id)
finally:
cache_list.clear()
del cache_list
finally:
cache_data.clear()
del cache_data
else: else:
# 搜索或订阅 # 搜索或订阅
if text.startswith("订阅"): if text.startswith("订阅"):
@@ -474,6 +496,7 @@ class MessageChain(ChainBase):
channel=channel, source=source, title=f"{meta.name} 没有找到对应的媒体信息!", userid=userid)) channel=channel, source=source, title=f"{meta.name} 没有找到对应的媒体信息!", userid=userid))
return return
logger.info(f"搜索到 {len(medias)} 条相关媒体信息") logger.info(f"搜索到 {len(medias)} 条相关媒体信息")
try:
# 记录当前状态 # 记录当前状态
_current_meta = meta _current_meta = meta
# 保存缓存 # 保存缓存
@@ -490,6 +513,9 @@ class MessageChain(ChainBase):
title=meta.name, title=meta.name,
items=medias[:self._page_size], items=medias[:self._page_size],
userid=userid, total=len(medias)) userid=userid, total=len(medias))
finally:
medias.clear()
del medias
else: else:
# 广播事件 # 广播事件
self.eventmanager.send_event( self.eventmanager.send_event(
@@ -501,6 +527,9 @@ class MessageChain(ChainBase):
"source": source "source": source
} }
) )
finally:
user_cache.clear()
del user_cache
def _handle_callback(self, text: str, channel: MessageChannel, source: str, def _handle_callback(self, text: str, channel: MessageChannel, source: str,
userid: Union[str, int], username: str, userid: Union[str, int], username: str,
+1
View File
@@ -365,6 +365,7 @@ class SearchChain(ChainBase):
logger.info(f"站点搜索完成,有效资源数:{len(results)},总耗时 {(end_time - start_time).seconds}") logger.info(f"站点搜索完成,有效资源数:{len(results)},总耗时 {(end_time - start_time).seconds}")
# 结束进度 # 结束进度
progress.end(ProgressKey.Search) progress.end(ProgressKey.Search)
# 返回 # 返回
return results return results
+6
View File
@@ -1,4 +1,5 @@
import base64 import base64
import gc
import re import re
from datetime import datetime from datetime import datetime
from typing import Optional, Tuple, Union, Dict from typing import Optional, Tuple, Union, Dict
@@ -106,6 +107,11 @@ class SiteChain(ChainBase):
EventManager().send_event(EventType.SiteRefreshed, { EventManager().send_event(EventType.SiteRefreshed, {
"site_id": "*" "site_id": "*"
}) })
# 如果不是大内存模式,进行垃圾回收
if not settings.BIG_MEMORY_MODE:
gc.collect()
return result return result
def is_special_site(self, domain: str) -> bool: def is_special_site(self, domain: str) -> bool:
+10 -4
View File
@@ -1,4 +1,5 @@
import copy import copy
import gc
import json import json
import random import random
import threading import threading
@@ -438,6 +439,10 @@ class SubscribeChain(ChainBase):
subscribes.clear() subscribes.clear()
del subscribes del subscribes
# 如果不是大内存模式,进行垃圾回收
if not settings.BIG_MEMORY_MODE:
gc.collect()
def update_subscribe_priority(self, subscribe: Subscribe, meta: MetaBase, def update_subscribe_priority(self, subscribe: Subscribe, meta: MetaBase,
mediainfo: MediaInfo, downloads: Optional[List[Context]]): mediainfo: MediaInfo, downloads: Optional[List[Context]]):
""" """
@@ -509,6 +514,9 @@ class SubscribeChain(ChainBase):
self.match( self.match(
TorrentsChain().refresh(sites=sites) TorrentsChain().refresh(sites=sites)
) )
# 如果不是大内存模式,进行垃圾回收
if not settings.BIG_MEMORY_MODE:
gc.collect()
@staticmethod @staticmethod
def get_sub_sites(subscribe: Subscribe) -> List[int]: def get_sub_sites(subscribe: Subscribe) -> List[int]:
@@ -633,7 +641,6 @@ class SubscribeChain(ChainBase):
torrenthelper = TorrentHelper() torrenthelper = TorrentHelper()
systemconfig = SystemConfigOper() systemconfig = SystemConfigOper()
wordsmatcher = WordsMatcher() wordsmatcher = WordsMatcher()
try:
for domain, contexts in processed_torrents.items(): for domain, contexts in processed_torrents.items():
if global_vars.is_system_stopped: if global_vars.is_system_stopped:
break break
@@ -787,9 +794,6 @@ class SubscribeChain(ChainBase):
finally: finally:
contexts.clear() contexts.clear()
del contexts del contexts
finally:
processed_torrents.clear()
del processed_torrents
if not _match_context: if not _match_context:
# 未匹配到资源 # 未匹配到资源
@@ -816,6 +820,8 @@ class SubscribeChain(ChainBase):
self.finish_subscribe_or_not(subscribe=subscribe, meta=meta, mediainfo=mediainfo, self.finish_subscribe_or_not(subscribe=subscribe, meta=meta, mediainfo=mediainfo,
downloads=downloads, lefts=lefts) downloads=downloads, lefts=lefts)
finally: finally:
processed_torrents.clear()
del processed_torrents
subscribes.clear() subscribes.clear()
del subscribes del subscribes
+5
View File
@@ -1,3 +1,4 @@
import gc
import queue import queue
import re import re
import threading import threading
@@ -866,6 +867,10 @@ class TransferChain(ChainBase, metaclass=Singleton):
torrents.clear() torrents.clear()
del torrents del torrents
# 如果不是大内存模式,进行垃圾回收
if not settings.BIG_MEMORY_MODE:
gc.collect()
# 结束 # 结束
logger.info("所有下载器中下载完成的文件已整理完成") logger.info("所有下载器中下载完成的文件已整理完成")
return True return True