windsurf-memory-optimization
Version:
Memory optimization tools for Windsurf AI
217 lines • 9.02 kB
JavaScript
;
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.OptimizationManager = void 0;
const node_persist_1 = __importDefault(require("node-persist"));
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
class OptimizationManager {
constructor() {
this.initialized = false;
}
async init() {
if (this.initialized)
return;
try {
// Sử dụng một thư mục tạm thời mới để tránh xung đột
const baseDir = process.env.WINDSURF_MEMORY_DIR || '.windsurf';
const optimizationStorageDir = path.join(baseDir, 'optimization-storage');
console.log(`Will use optimization storage directory: ${optimizationStorageDir}`);
// Xóa và tạo lại thư mục nếu đã tồn tại
if (!fs.existsSync(baseDir)) {
console.log(`Creating base directory: ${baseDir}`);
fs.mkdirSync(baseDir, { recursive: true });
}
if (!fs.existsSync(optimizationStorageDir)) {
console.log(`Creating optimization storage directory: ${optimizationStorageDir}`);
fs.mkdirSync(optimizationStorageDir, { recursive: true });
}
// Kiểm tra xem optimizationStorageDir có phải là thư mục không
const stats = fs.statSync(optimizationStorageDir);
if (!stats.isDirectory()) {
console.error(`Optimization storage path exists but is not a directory: ${optimizationStorageDir}`);
// Xóa file và tạo thư mục
fs.unlinkSync(optimizationStorageDir);
fs.mkdirSync(optimizationStorageDir, { recursive: true });
}
// Tạo và khởi tạo storage
console.log(`Initializing optimization storage in: ${optimizationStorageDir}`);
this.storage = await node_persist_1.default.create({
dir: optimizationStorageDir,
logging: true,
ttl: true
});
console.log('Initializing optimization storage...');
await this.storage.init();
console.log('Optimization storage initialized successfully');
this.initialized = true;
}
catch (error) {
console.error('Error initializing optimization storage:', error instanceof Error ? error.message : String(error));
throw error;
}
}
async optimize() {
// TODO: Implement optimization logic
const config = {
disableLivePreview: true,
maxParallelTasks: 2,
batchCompletions: true,
optimizeMemory: true
};
// TODO: Apply optimization settings
}
async checkPerformance() {
// TODO: Implement performance checking
}
/**
* Dọn dẹp các memory pins đã hết hạn
* @returns Số lượng pins đã được dọn dẹp
*/
async cleanupExpiredPins() {
if (!this.initialized) {
await this.init();
}
try {
// Lấy tất cả các keys trong storage
const keys = await this.storage.keys();
let cleanedCount = 0;
for (const key of keys) {
const item = await this.storage.getItem(key);
// Kiểm tra xem item có phải là memory pin không
if (item && item.metadata && item.metadata.ttl) {
// Kiểm tra xem pin đã hết hạn chưa
const ttl = item.metadata.ttl;
const expired = this.isPinExpired(ttl, item.metadata.createdAt);
if (expired) {
await this.storage.removeItem(key);
cleanedCount++;
console.log(`Removed expired pin: ${key}`);
}
}
}
console.log(`Cleaned up ${cleanedCount} expired pins`);
return cleanedCount;
}
catch (error) {
console.error('Error cleaning up expired pins:', error instanceof Error ? error.message : String(error));
throw error;
}
}
/**
* Kiểm tra xem một pin đã hết hạn chưa dựa trên TTL
* @param ttl Thời gian sống của pin (ví dụ: '24h', '7d')
* @param createdAt Thời gian tạo pin (nếu không có sẽ sử dụng thời gian hiện tại)
* @returns true nếu pin đã hết hạn, false nếu chưa
*/
isPinExpired(ttl, createdAt) {
if (!ttl)
return false;
// Phân tích TTL (ví dụ: '24h', '7d')
const ttlValue = parseInt(ttl);
const ttlUnit = ttl.replace(/[0-9]/g, '');
if (isNaN(ttlValue) || ttlValue <= 0)
return false;
// Tính thời gian hết hạn
const created = createdAt ? new Date(createdAt) : new Date();
const now = new Date();
let expiryTime = new Date(created);
switch (ttlUnit) {
case 'h': // giờ
expiryTime.setHours(expiryTime.getHours() + ttlValue);
break;
case 'd': // ngày
expiryTime.setDate(expiryTime.getDate() + ttlValue);
break;
case 'w': // tuần
expiryTime.setDate(expiryTime.getDate() + (ttlValue * 7));
break;
case 'm': // tháng
expiryTime.setMonth(expiryTime.getMonth() + ttlValue);
break;
default: // mặc định là giờ
expiryTime.setHours(expiryTime.getHours() + ttlValue);
}
return now > expiryTime;
}
/**
* Tối ưu hóa storage bằng cách nén và tổ chức lại dữ liệu
* @returns Thông tin về quá trình tối ưu hóa
*/
async optimizeStorage() {
if (!this.initialized) {
await this.init();
}
try {
// Lấy kích thước trước khi tối ưu hóa
const beforeSize = await this.getStorageSize();
// Thực hiện tối ưu hóa (compact storage)
await this.storage.clear();
await this.storage.init();
// Lấy kích thước sau khi tối ưu hóa
const afterSize = await this.getStorageSize();
return {
compacted: true,
size: {
before: beforeSize,
after: afterSize
}
};
}
catch (error) {
console.error('Error optimizing storage:', error instanceof Error ? error.message : String(error));
throw error;
}
}
/**
* Lấy kích thước hiện tại của storage
* @returns Kích thước tính bằng bytes
*/
async getStorageSize() {
try {
const baseDir = process.env.WINDSURF_MEMORY_DIR || '.windsurf';
const optimizationStorageDir = path.join(baseDir, 'optimization-storage');
let totalSize = 0;
const files = fs.readdirSync(optimizationStorageDir);
for (const file of files) {
const filePath = path.join(optimizationStorageDir, file);
const stats = fs.statSync(filePath);
if (stats.isFile()) {
totalSize += stats.size;
}
}
return totalSize;
}
catch (error) {
console.error('Error getting storage size:', error instanceof Error ? error.message : String(error));
return 0;
}
}
}
exports.OptimizationManager = OptimizationManager;
//# sourceMappingURL=optimization-manager.js.map