From 373a0ad3211e30903668a49f7d49e6422200c59f Mon Sep 17 00:00:00 2001 From: Cohee <18619528+Cohee1207@users.noreply.github.com> Date: Thu, 5 Dec 2024 12:59:03 +0000 Subject: [PATCH] Add config.yaml value for cards cache capacity. --- default/config.yaml | 2 ++ src/endpoints/characters.js | 7 ++++--- src/util.js | 5 +++-- 3 files changed, 9 insertions(+), 5 deletions(-) diff --git a/default/config.yaml b/default/config.yaml index 6f174e523..730ffa967 100644 --- a/default/config.yaml +++ b/default/config.yaml @@ -1,6 +1,8 @@ # -- DATA CONFIGURATION -- # Root directory for user data storage dataRoot: ./data +# The maximum amount of memory that parsed character cards can use in MB +cardsCacheCapacity: 100 # -- SERVER CONFIGURATION -- # Listen for incoming connections listen: false diff --git a/src/endpoints/characters.js b/src/endpoints/characters.js index b3be9d6f4..9c117cb31 100644 --- a/src/endpoints/characters.js +++ b/src/endpoints/characters.js @@ -14,7 +14,7 @@ import jimp from 'jimp'; import { AVATAR_WIDTH, AVATAR_HEIGHT } from '../constants.js'; import { jsonParser, urlencodedParser } from '../express-common.js'; -import { deepMerge, humanizedISO8601DateTime, tryParse, extractFileFromZipBuffer, MemoryLimitedMap } from '../util.js'; +import { deepMerge, humanizedISO8601DateTime, tryParse, extractFileFromZipBuffer, MemoryLimitedMap, getConfigValue } from '../util.js'; import { TavernCardValidator } from '../validator/TavernCardValidator.js'; import { parse, write } from '../character-card-parser.js'; import { readWorldInfoFile } from './worldinfo.js'; @@ -23,8 +23,9 @@ import { importRisuSprites } from './sprites.js'; const defaultAvatarPath = './public/img/ai4.png'; // KV-store for parsed character data -// 100 MB limit. Would take roughly 3000 characters to reach this limit -const characterDataCache = new MemoryLimitedMap(1024 * 1024 * 100); +const cacheCapacity = Number(getConfigValue('cardsCacheCapacity', 100)); // MB +// With 100 MB limit it would take roughly 3000 characters to reach this limit +const characterDataCache = new MemoryLimitedMap(1024 * 1024 * cacheCapacity); // Some Android devices require tighter memory management const isAndroid = process.platform === 'android'; diff --git a/src/util.js b/src/util.js index 623626d3d..7b8445453 100644 --- a/src/util.js +++ b/src/util.js @@ -680,8 +680,9 @@ export class MemoryLimitedMap { * @param {number} maxMemoryInBytes - The maximum allowed memory in bytes for string values. */ constructor(maxMemoryInBytes) { - if (typeof maxMemoryInBytes !== 'number' || maxMemoryInBytes <= 0) { - throw new Error('maxMemoryInBytes must be a positive number'); + if (typeof maxMemoryInBytes !== 'number' || maxMemoryInBytes <= 0 || isNaN(maxMemoryInBytes)) { + console.warn('Invalid maxMemoryInBytes, using a fallback value of 1 GB.'); + maxMemoryInBytes = 1024 * 1024 * 1024; // 1 GB } this.maxMemory = maxMemoryInBytes; this.currentMemory = 0;