| |
| |
| |
| |
| |
| |
|
|
| import logger from './logger.js'; |
|
|
| |
| const POOL_SIZES = { chunk: 30, toolCall: 15, lineBuffer: 5 }; |
|
|
| class MemoryManager { |
| constructor() { |
| |
| this.cleanupCallbacks = new Set(); |
| |
| this.timer = null; |
| |
| this.cleanupIntervalMs = 30 * 60 * 1000; |
| this.isShuttingDown = false; |
| } |
|
|
| |
| |
| |
| |
| start(cleanupIntervalMs = 30 * 60 * 1000) { |
| if (this.timer) return; |
| this.setCleanupInterval(cleanupIntervalMs); |
| this.isShuttingDown = false; |
| logger.info(`内存清理器已启动(间隔: ${Math.round(this.cleanupIntervalMs / 1000)}秒)`); |
| } |
|
|
| |
| |
| |
| |
| setCleanupInterval(cleanupIntervalMs) { |
| if (Number.isFinite(cleanupIntervalMs) && cleanupIntervalMs > 0) { |
| this.cleanupIntervalMs = Math.floor(cleanupIntervalMs); |
| } |
|
|
| if (this.timer) { |
| clearInterval(this.timer); |
| this.timer = null; |
| } |
|
|
| this.timer = setInterval(() => { |
| if (!this.isShuttingDown) this.cleanup('timer'); |
| }, this.cleanupIntervalMs); |
|
|
| this.timer.unref?.(); |
| } |
|
|
| |
| |
| |
| stop() { |
| this.isShuttingDown = true; |
| if (this.timer) { |
| clearInterval(this.timer); |
| this.timer = null; |
| } |
| this.cleanupCallbacks.clear(); |
| logger.info('内存清理器已停止'); |
| } |
|
|
| |
| |
| |
| |
| registerCleanup(callback) { |
| this.cleanupCallbacks.add(callback); |
| } |
|
|
| |
| |
| |
| |
| unregisterCleanup(callback) { |
| this.cleanupCallbacks.delete(callback); |
| } |
|
|
| |
| |
| |
| |
| cleanup(reason = 'manual') { |
| for (const callback of this.cleanupCallbacks) { |
| try { |
| callback(reason); |
| } catch (error) { |
| logger.error('清理回调执行失败:', error.message); |
| } |
| } |
| } |
|
|
| |
| |
| |
| getPoolSizes() { |
| return POOL_SIZES; |
| } |
| } |
|
|
| const memoryManager = new MemoryManager(); |
| export default memoryManager; |
|
|
| |
| export function registerMemoryPoolCleanup(pool, getMaxSize) { |
| memoryManager.registerCleanup(() => { |
| const maxSize = getMaxSize(); |
| while (pool.length > maxSize) pool.pop(); |
| }); |
| } |
|
|