From 7a48d046e6e712f685bdf285bde5f412fdc19c25 Mon Sep 17 00:00:00 2001 From: Zakk Date: Sat, 3 Oct 2026 04:07:23 +1000 Subject: [PATCH] fix(dns): start regex timeout after worker readiness --- CHANGELOG.md | 1 + e2e/dns-actions.spec.ts | 57 +++++++++++------- src/features/dns/match.worker.ts | 1 + src/features/dns/useCacheMatches.test.ts | 74 ++++++++++++++++++++++++ src/features/dns/useCacheMatches.ts | 13 +++-- 5 files changed, 120 insertions(+), 26 deletions(-) create mode 100644 src/features/dns/useCacheMatches.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index e31cfee2..e8f2f5f2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -46,6 +46,7 @@ This changelog follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) - Nested policy groups recover their probe options when refreshed node IDs arrive after the descendant group reads, without reopening Policies. (#334) - Nested policy groups recover their probe options when refreshed node IDs arrive after the descendant group reads, without reopening Policies. (#334) (#358) - Trojan, AnyTLS and VLESS retain DNS UDP probe choices when support depends on node configuration; backend admission failures remain visible instead of silently switching to HTTP. (#334) (#358) +- DNS cache regex matching no longer reports an execution timeout while its worker is still loading. (#355) - Renaming a node updates DNS upstream detours in its declaring source and is blocked while another source refers to it. (#353) - Add to group on Nodes keeps the shared Policies editor available for new and existing groups when the runtime groups API is unavailable. (#353) - Empty file providers remain visible on Nodes, including their status and removal action. (#353) diff --git a/e2e/dns-actions.spec.ts b/e2e/dns-actions.spec.ts index 70f37898..39a0d81f 100644 --- a/e2e/dns-actions.spec.ts +++ b/e2e/dns-actions.spec.ts @@ -238,28 +238,41 @@ test('pattern deletion shows how many entries match and deletes them one by one' expect(deletes(requests)).toHaveLength(matches.length); }); -test('a backtracking regex times out without blocking the cache controls or permitting partial deletion', async ({page}) => { - const {api, handlers, requests} = await mockBackend(page); - const cache = await api.dnsCache(); - const entries = [ - {...cache.entries[0], entry_id: 'safe', domain: 'example.com.', type: 'A'}, - {...cache.entries[0], entry_id: 'ptr', domain: 'a.'.repeat(32) + 'ip6.arpa.', type: 'PTR'} - ]; - handlers['GET dns/cache'] = async () => ({...cache, entries, next_cursor: null}); - await page.goto('/#/dns?tab=cache'); - await expect(page.getByRole('grid', {name: 'Cache', exact: true}).getByRole('rowheader')).toHaveCount(2); - await pick(page, 'Domain suffix', 'Match by', 'Domain regex'); - const pattern = page.getByRole('textbox', {name: 'Pattern', exact: true}); - const button = page.getByRole('button', {name: 'Delete matching', exact: true}); - await pattern.fill('^(.+\\.)*example\\.com$'); - await expect(page.getByText('Regex matching timed out. Use a simpler pattern.', {exact: true})).toBeVisible(); - await expect(button).toBeDisabled(); - expect(deletes(requests)).toHaveLength(0); - await pattern.fill('^example\\.com$'); - await button.click(); - const dialog = page.getByRole('alertdialog', {name: 'Delete matching', exact: true}); - expect(await listed(dialog)).toEqual(named([entries[0]])); - await dialog.getByRole('button', {name: 'Cancel', exact: true}).click(); +test.describe('regex worker', () => { + // Service-worker precaching bypasses request interception. + test.use({serviceWorkers: 'block'}); + + test('a backtracking regex times out without blocking the cache controls or permitting partial deletion', async ({page}) => { + const {api, handlers, requests} = await mockBackend(page); + const cache = await api.dnsCache(); + const entries = [ + {...cache.entries[0], entry_id: 'safe', domain: 'example.com.', type: 'A'}, + {...cache.entries[0], entry_id: 'ptr', domain: 'a.'.repeat(32) + 'ip6.arpa.', type: 'PTR'} + ]; + handlers['GET dns/cache'] = async () => ({...cache, entries, next_cursor: null}); + await page.goto('/#/dns?tab=cache'); + await expect(page.getByRole('grid', {name: 'Cache', exact: true}).getByRole('rowheader')).toHaveCount(2); + await pick(page, 'Domain suffix', 'Match by', 'Domain regex'); + const pattern = page.getByRole('textbox', {name: 'Pattern', exact: true}); + const button = page.getByRole('button', {name: 'Delete matching', exact: true}); + await pattern.fill('^(.+\\.)*example\\.com$'); + await expect(page.getByText('Regex matching timed out. Use a simpler pattern.', {exact: true})).toBeVisible(); + await expect(button).toBeDisabled(); + expect(deletes(requests)).toHaveLength(0); + let delayed = false; + await page.route('**/assets/match.worker-*.js', async route => { + // A slow chunk download must not consume the regex execution deadline. + await page.waitForTimeout(1500); + delayed = true; + await route.continue(); + }); + await pattern.fill('^example\\.com$'); + await button.click(); + const dialog = page.getByRole('alertdialog', {name: 'Delete matching', exact: true}); + expect(delayed).toBe(true); + expect(await listed(dialog)).toEqual(named([entries[0]])); + await dialog.getByRole('button', {name: 'Cancel', exact: true}).click(); + }); }); test('the confirmation lists at most 100 entries and counts the rest', async ({page}) => { diff --git a/src/features/dns/match.worker.ts b/src/features/dns/match.worker.ts index dc6b12ea..9fb50e9c 100644 --- a/src/features/dns/match.worker.ts +++ b/src/features/dns/match.worker.ts @@ -4,3 +4,4 @@ self.onmessage = (event: MessageEvent<{text: string; names: string[]}>) => { const matcher = dnsMatcher('regex', event.data.text); self.postMessage(matcher ? event.data.names.flatMap((name, index) => (matcher(name) ? [index] : [])) : null); }; +self.postMessage('ready'); diff --git a/src/features/dns/useCacheMatches.test.ts b/src/features/dns/useCacheMatches.test.ts new file mode 100644 index 00000000..a153c616 --- /dev/null +++ b/src/features/dns/useCacheMatches.test.ts @@ -0,0 +1,74 @@ +import {afterEach, beforeEach, expect, it, vi} from 'vitest'; +import type * as React from 'react'; +import {dnsCache} from '../../../mock/fixtures'; +import {hookHarness} from '../../store/testHelpers'; +import {useCacheMatches} from './useCacheMatches'; + +vi.mock('react', async original => ({ + ...(await original()), + ...hookHarness.hooks, + useMemo(read: () => T, deps: unknown[]) { + const ref = hookHarness.hooks.useRef<{value: T; deps: unknown[]} | null>(null); + if (!ref.current || deps.some((value, index) => !Object.is(value, ref.current?.deps[index]))) ref.current = {value: read(), deps}; + return ref.current.value; + } +})); + +class MatchWorker { + static current: MatchWorker; + onmessage?: (event: {data: 'ready' | number[] | null}) => void; + onerror?: (event: {preventDefault: () => void}) => void; + postMessage = vi.fn(); + terminate = vi.fn(); + constructor() { + MatchWorker.current = this; + } + emit(data: 'ready' | number[] | null) { + this.onmessage?.({data}); + } +} +const entries = dnsCache.entries.slice(0, 2); +const pattern = {kind: 'regex' as const, text: '^example\\.com$'}; +const read = () => hookHarness.render(() => useCacheMatches(entries, pattern, 'all')); + +beforeEach(() => { + hookHarness.reset(); + vi.useFakeTimers(); + vi.stubGlobal('Worker', MatchWorker); + vi.stubGlobal('window', globalThis); +}); +afterEach(() => { + hookHarness.unmount(); + vi.useRealTimers(); + vi.unstubAllGlobals(); +}); + +it('waits for worker loading before allowing a full second for regex execution', () => { + read(); + hookHarness.runEffects(); + const worker = MatchWorker.current; + vi.advanceTimersByTime(1500); + expect(read()).toMatchObject({pending: true, error: undefined, matches: []}); + expect(worker.terminate).not.toHaveBeenCalled(); + worker.emit('ready'); + vi.advanceTimersByTime(999); + expect(read()).toMatchObject({pending: true, error: undefined}); + vi.advanceTimersByTime(1); + expect(read()).toMatchObject({pending: false, error: 'dns.regexTimeout', matches: []}); + expect(worker.terminate).toHaveBeenCalledOnce(); + worker.emit([0]); + expect(read()).toMatchObject({error: 'dns.regexTimeout', matches: []}); +}); + +it.each([false, true])('cancels a worker on unmount with readiness %s and ignores late messages', ready => { + read(); + hookHarness.runEffects(); + const worker = MatchWorker.current; + if (ready) worker.emit('ready'); + hookHarness.unmount(); + worker.emit('ready'); + worker.emit([0]); + vi.advanceTimersByTime(2000); + expect(read()).toMatchObject({pending: true, error: undefined, matches: []}); + expect(worker.terminate).toHaveBeenCalledOnce(); +}); diff --git a/src/features/dns/useCacheMatches.ts b/src/features/dns/useCacheMatches.ts index dd277f1d..a0e27325 100644 --- a/src/features/dns/useCacheMatches.ts +++ b/src/features/dns/useCacheMatches.ts @@ -18,6 +18,7 @@ export function useCacheMatches(entries: Entries | undefined, pattern: {kind: Ma if (!asynchronous) return; const worker = new Worker(new URL('./match.worker.ts', import.meta.url), {type: 'module'}); let active = true; + let timer: number | undefined; const finish = (indices: number[] | null, error?: Key) => { if (!active) return; active = false; @@ -30,14 +31,18 @@ export function useCacheMatches(entries: Entries | undefined, pattern: {kind: Ma error: error ?? (indices === null ? 'dns.invalidRegex' : undefined) }); }; - // Termination bounds the entire batch, even when one name causes catastrophic backtracking. - const timer = setTimeout(() => finish([], 'dns.regexTimeout'), 1000); - worker.onmessage = (event: MessageEvent) => finish(event.data); + worker.onmessage = (event: MessageEvent<'ready' | number[] | null>) => { + if (!active) return; + if (event.data === 'ready') { + // Bound execution, not the time spent downloading and starting the worker. + timer = window.setTimeout(() => finish([], 'dns.regexTimeout'), 1000); + worker.postMessage({text: pattern.text, names: candidates.map(entry => entry.domain)}); + } else finish(event.data); + }; worker.onerror = event => { event.preventDefault(); finish([], 'dns.matchFailed'); }; - worker.postMessage({text: pattern.text, names: candidates.map(entry => entry.domain)}); return () => { active = false; clearTimeout(timer);