#208 - Added a time limits for regex matchers

This commit is contained in:
Simon Cambier
2023-03-12 11:30:56 +01:00
parent 2b2709d9ab
commit 23640f4b0b
3 changed files with 37 additions and 14 deletions

View File

@@ -14,6 +14,7 @@ import {
splitCamelCase,
stringsToRegex,
stripMarkdownCharacters,
warnDebug,
} from '../tools/utils'
import { Notice } from 'obsidian'
import type { Query } from './query'
@@ -304,11 +305,16 @@ export class Omnisearch {
}
public getMatches(text: string, reg: RegExp, query: Query): SearchMatch[] {
const startTime = new Date().getTime()
let match: RegExpExecArray | null = null
const matches: SearchMatch[] = []
let count = 0
while ((match = reg.exec(text)) !== null) {
if (++count >= 100) break // Avoid infinite loops, stop looking after 100 matches
// Avoid infinite loops, stop looking after 100 matches or if we're taking too much time
if (++count >= 100 || new Date().getTime() - startTime > 50) {
warnDebug('Stopped getMatches at', count, 'results')
break
}
const m = match[0]
if (m) matches.push({ match: m, offset: match.index })
}

View File

@@ -325,8 +325,18 @@ export function splitCamelCase(text: string): string[] {
return text.replace(/([a-z](?=[A-Z]))/g, '$1 ').split(' ')
}
export function logDebug(...attr: any[]): void {
export function logDebug(...args: any[]): void {
printDebug(console.log, ...args)
}
export function warnDebug(...args: any[]): void {
printDebug(console.warn, ...args)
}
function printDebug(fn: (...args: any[]) => any, ...args: any[]): void {
if (settings.verboseLogging) {
console.log(...['Omnisearch -', ...attr])
const t = new Date()
const ts = `${t.getMinutes()}:${t.getSeconds()}:${t.getMilliseconds()}`
fn(...['Omnisearch -', ts + ' -', ...args])
}
}

View File

@@ -6,6 +6,8 @@
* MIT Licensed
*/
import { warnDebug } from "../tools/utils";
interface SearchParserOptions {
offsets?: boolean
tokenize: true
@@ -43,7 +45,7 @@ interface SearchParserResult extends ISearchParserDictionary {
export function parseQuery(
string: string,
options: SearchParserOptions
options: SearchParserOptions,
): SearchParserResult {
// Set a default options object when none is provided
if (!options) {
@@ -74,9 +76,14 @@ export function parseQuery(
const regex =
/(\S+:'(?:[^'\\]|\\.)*')|(\S+:"(?:[^"\\]|\\.)*")|(-?"(?:[^"\\]|\\.)*")|(-?'(?:[^'\\]|\\.)*')|\S+|\S+:\S+/g
let match
let count = 0 // TODO: FIXME: this is a hack to avoid infinite loops
let count = 0
const startTime = new Date().getTime()
while ((match = regex.exec(string)) !== null) {
if (++count >= 100) break
if (++count >= 100 || new Date().getTime() - startTime > 50) {
warnDebug('Stopped SearchParserResult at', count, 'results')
break
}
let term = match[0]
const sepIndex = term.indexOf(':')