From 392e2da2d17affe26fcad7bebc6cc963d2e6a1b6 Mon Sep 17 00:00:00 2001 From: Dragory <2606411+Dragory@users.noreply.github.com> Date: Tue, 5 Oct 2021 21:30:35 +0300 Subject: [PATCH] perf(automod): bundle automod regex patterns for potentially increased performance --- .../plugins/Automod/triggers/matchRegex.ts | 28 +++++++++++-------- 1 file changed, 17 insertions(+), 11 deletions(-) diff --git a/backend/src/plugins/Automod/triggers/matchRegex.ts b/backend/src/plugins/Automod/triggers/matchRegex.ts index 3e0b2e38..42951920 100644 --- a/backend/src/plugins/Automod/triggers/matchRegex.ts +++ b/backend/src/plugins/Automod/triggers/matchRegex.ts @@ -13,6 +13,8 @@ interface MatchResultType { type: MatchableTextType; } +const combinedRegexCache: WeakMap = new WeakMap(); + export const MatchRegexTrigger = automodTrigger()({ configType: t.type({ patterns: t.array(TRegex), @@ -53,17 +55,21 @@ export const MatchRegexTrigger = automodTrigger()({ str = normalizeText(str); } - for (const sourceRegex of trigger.patterns) { - const regex = new RegExp(sourceRegex.source, trigger.case_sensitive && !sourceRegex.ignoreCase ? "" : "i"); - const matches = await pluginData.state.regexRunner.exec(regex, str).catch(allowTimeout); - if (matches?.length) { - return { - extra: { - pattern: sourceRegex.source, - type, - }, - }; - } + if (!combinedRegexCache.has(trigger)) { + const combinedPattern = trigger.patterns.map((p) => `(?:${p.source})`).join("|"); + const combinedRegex = new RegExp(combinedPattern, trigger.case_sensitive ? "" : "i"); + combinedRegexCache.set(trigger, combinedRegex); + } + + const regex = combinedRegexCache.get(trigger)!; + const matches = await pluginData.state.regexRunner.exec(regex, str).catch(allowTimeout); + if (matches?.length) { + return { + extra: { + pattern: "