From 201f7ccc86e588fbb59f930366b03c2e368387e6 Mon Sep 17 00:00:00 2001 From: Zakk Date: Sun, 27 Sep 2026 20:11:57 +1000 Subject: [PATCH] feat(mock): serve a healthy honk by default, faults on request The default demo showed a degraded datapath, unavailable nodes, dropped flow records, warning and error logs, a failed operation, config warnings, DNS upstream failures, and a rule on geosite:discord that the lite geodata files lack, so picking them made the update fail. Someone trying the demo read these as bugs. The default demo now has none of them. The chat rule becomes geosite:openai, which every preset carries. The seeded faults move to an opt-in scenario: localStorage doona-mock-scenario=faults, or createMockApi({faults: true}) for the specs' in-process backend. It also adds a geosite:category-ads-all rule so the lite preset still fails the way honk refuses it. Specs about those states use the scenario. --- e2e/activity.spec.ts | 98 ++++++++++++++------------ e2e/charts.spec.ts | 21 +++--- e2e/config.spec.ts | 41 ++++++----- e2e/fixtures.ts | 8 ++- e2e/flows.spec.ts | 53 +++++++------- e2e/geodata.spec.ts | 12 ++-- e2e/nodes.spec.ts | 4 +- e2e/rule-editor.spec.ts | 2 +- src/api/mock.test.ts | 35 +++++++-- src/api/mock/configuration.test.ts | 16 +++-- src/api/mock/configuration.ts | 12 ++-- src/api/mock/fixtures.ts | 2 +- src/api/mock/fixtures/configuration.ts | 11 ++- src/api/mock/fixtures/inventory.ts | 7 +- src/api/mock/fixtures/network.ts | 2 +- src/api/mock/fixtures/runtime.ts | 14 ++-- src/api/mock/flows.ts | 2 +- src/api/mock/geodata.ts | 6 +- src/api/mock/index.ts | 20 ++++-- src/api/mock/inventory.ts | 5 +- src/api/mock/lifecycle.ts | 20 ++++-- src/api/mock/network.ts | 16 +++-- src/api/mock/routing.ts | 2 +- src/api/mock/rules.ts | 4 +- src/api/mock/runtime.ts | 12 +++- src/features/activity/view.test.ts | 4 +- src/features/overview/view.test.ts | 10 ++- src/features/policies/view.test.ts | 2 +- 28 files changed, 270 insertions(+), 171 deletions(-) diff --git a/e2e/activity.spec.ts b/e2e/activity.spec.ts index fff7af15..01bdc8d3 100644 --- a/e2e/activity.spec.ts +++ b/e2e/activity.spec.ts @@ -1,4 +1,4 @@ -import {expect, mockBackend, test} from './fixtures'; +import {expect, faults, mockBackend, test} from './fixtures'; import {createMockApi} from '../src/api/mock'; import {test as browserTest, type Page} from '@playwright/test'; import {sha256} from '../src/api/hash'; @@ -170,54 +170,60 @@ test('notices hide housekeeping events while the Events page retains them', asyn await expect(page.getByRole('row').filter({hasText: 'Runtime updated'}).first()).toContainText('/api/v1/runtime'); }); -test('mock notices include distinct operations and the recording gap, not routine overflow', async ({page}) => { - await page.setViewportSize({width: 1440, height: 900}); - await page.goto('/#/activity'); - for (const lang of ['zh-TW', 'en']) { - for (const scheme of ['light', 'dark']) { - await page.evaluate( - ({lang, scheme}) => { - localStorage.setItem('doona-lang', lang); - localStorage.setItem('doona-scheme', scheme); - }, - {lang, scheme} - ); - await page.reload(); - const notices = page.locator('.rp-feed'); - await expect(notices.getByRole('listitem')).toHaveCount(5); - await expect(notices.locator('.rp-light.warn')).toHaveCount(1); - if (lang === 'en') { - await expect(notices.getByRole('listitem').filter({hasText: 'Configuration activated'})).toHaveCount(1); - await expect(notices.getByRole('listitem').filter({hasText: 'Operation updated'})).toHaveCount(2); - await expect(notices.getByRole('listitem').filter({hasText: 'Flow records lost'})).toHaveCount(1); - await expect(notices.getByRole('listitem').filter({hasText: 'records reached the retention limit'})).toHaveCount(0); +test.describe(() => { + test.use({storage: faults}); + test('mock notices include distinct operations and the recording gap, not routine overflow', async ({page}) => { + await page.setViewportSize({width: 1440, height: 900}); + await page.goto('/#/activity'); + for (const lang of ['zh-TW', 'en']) { + for (const scheme of ['light', 'dark']) { + await page.evaluate( + ({lang, scheme}) => { + localStorage.setItem('doona-lang', lang); + localStorage.setItem('doona-scheme', scheme); + }, + {lang, scheme} + ); + await page.reload(); + const notices = page.locator('.rp-feed'); + await expect(notices.getByRole('listitem')).toHaveCount(5); + await expect(notices.locator('.rp-light.warn')).toHaveCount(1); + if (lang === 'en') { + await expect(notices.getByRole('listitem').filter({hasText: 'Configuration activated'})).toHaveCount(1); + await expect(notices.getByRole('listitem').filter({hasText: 'Operation updated'})).toHaveCount(2); + await expect(notices.getByRole('listitem').filter({hasText: 'Flow records lost'})).toHaveCount(1); + await expect(notices.getByRole('listitem').filter({hasText: 'records reached the retention limit'})).toHaveCount(0); + } } } - } + }); }); -test('notice summaries start at one edge however wide their labels are', async ({page}) => { - await page.addInitScript(() => localStorage.setItem('doona-lang', 'en')); - // A phone's card is about as narrow as the card gets. - for (const width of [390, 1440]) { - await page.setViewportSize({width, height: 900}); - await page.goto('/#/activity'); - const notices = page.getByRole('region', {name: 'Notifications', exact: true}); - await expect(notices.locator('.rp-light.warn')).toHaveText('Warning'); - const edges = await notices.locator('[role=listitem] .rp-note').evaluateAll(notes => notes.map(note => note.getBoundingClientRect().left)); - expect(edges.length).toBeGreaterThan(1); - expect(new Set(edges).size).toBe(1); - // A label lines up with its summary's first line, also when the summary wraps. - const offsets = await notices.locator('[role=listitem]').evaluateAll(items => - items.map(item => { - const label = item.querySelector('.rp-light')!.getBoundingClientRect(); - const note = item.querySelector('.rp-note')!; - const line = parseFloat(getComputedStyle(note).lineHeight); - return Math.abs(label.top + label.height / 2 - (note.getBoundingClientRect().top + line / 2)); - }) - ); - for (const offset of offsets) expect(offset).toBeLessThan(4); - } +test.describe(() => { + test.use({storage: faults}); + test('notice summaries start at one edge however wide their labels are', async ({page}) => { + await page.addInitScript(() => localStorage.setItem('doona-lang', 'en')); + // A phone's card is about as narrow as the card gets. + for (const width of [390, 1440]) { + await page.setViewportSize({width, height: 900}); + await page.goto('/#/activity'); + const notices = page.getByRole('region', {name: 'Notifications', exact: true}); + await expect(notices.locator('.rp-light.warn')).toHaveText('Warning'); + const edges = await notices.locator('[role=listitem] .rp-note').evaluateAll(notes => notes.map(note => note.getBoundingClientRect().left)); + expect(edges.length).toBeGreaterThan(1); + expect(new Set(edges).size).toBe(1); + // A label lines up with its summary's first line, also when the summary wraps. + const offsets = await notices.locator('[role=listitem]').evaluateAll(items => + items.map(item => { + const label = item.querySelector('.rp-light')!.getBoundingClientRect(); + const note = item.querySelector('.rp-note')!; + const line = parseFloat(getComputedStyle(note).lineHeight); + return Math.abs(label.top + label.height / 2 - (note.getBoundingClientRect().top + line / 2)); + }) + ); + for (const offset of offsets) expect(offset).toBeLessThan(4); + } + }); }); test('housekeeping cannot evict notices while the page is hidden', async ({page}) => { @@ -450,7 +456,7 @@ test('staged mode changes require discard before navigation', async ({page}) => }); test('local traffic renders without history and duplicate node names retain independent latency', async ({page}) => { - const api = createMockApi(); + const api = createMockApi({faults: true}); const capabilities = await api.capabilities(); for (const resource of Object.values(capabilities.resources)) resource.available = false; capabilities.resources.nodes.available = true; diff --git a/e2e/charts.spec.ts b/e2e/charts.spec.ts index 836c52e9..ece7304d 100644 --- a/e2e/charts.spec.ts +++ b/e2e/charts.spec.ts @@ -1,4 +1,4 @@ -import {expect, mockBackend, test} from './fixtures'; +import {expect, faults, mockBackend, test} from './fixtures'; import {ApiError} from '../src/api/error'; test.use({storage: {'doona-lang': 'en'}}); @@ -152,14 +152,17 @@ test('a failed node read keeps the latency card with the reason and a retry', as await expect(nodeLatency(page).locator('.rp-swarm')).toBeVisible(); }); -test('the log heatmap sits above the list and sets the minimum level from a row', async ({page}) => { - await page.goto('/#/logs'); - await expect(fact(page, 'Errors')).toHaveText(/^\d+ records?$/); - await expect(fact(page, 'Most errors').locator('.rp-big')).toHaveText(/^\d\d:\d\d–\d\d:\d\d$/); - await expect(fact(page, 'Most errors').locator('.rp-fact-caption')).toHaveText(/^\d+ records?$/); - await page.getByRole('button', {name: 'Show Warning and above'}).click(); - await expect(page.getByRole('group', {name: 'Log activity over time'}).getByText('Info', {exact: true})).toHaveCount(0); - await expect(page.getByRole('button', {name: /Level$/})).toContainText('Warning'); +test.describe(() => { + test.use({storage: faults}); + test('the log heatmap sits above the list and sets the minimum level from a row', async ({page}) => { + await page.goto('/#/logs'); + await expect(fact(page, 'Errors')).toHaveText(/^\d+ records?$/); + await expect(fact(page, 'Most errors').locator('.rp-big')).toHaveText(/^\d\d:\d\d–\d\d:\d\d$/); + await expect(fact(page, 'Most errors').locator('.rp-fact-caption')).toHaveText(/^\d+ records?$/); + await page.getByRole('button', {name: 'Show Warning and above'}).click(); + await expect(page.getByRole('group', {name: 'Log activity over time'}).getByText('Info', {exact: true})).toHaveCount(0); + await expect(page.getByRole('button', {name: /Level$/})).toContainText('Warning'); + }); }); test('the DNS cache card reads usage from one entry and says only what the backend reports', async ({page}) => { diff --git a/e2e/config.spec.ts b/e2e/config.spec.ts index 90509950..f865da2c 100644 --- a/e2e/config.spec.ts +++ b/e2e/config.spec.ts @@ -1,7 +1,7 @@ import {test as httpTest, type Locator, type Page} from '@playwright/test'; import {createMockApi} from '../src/api/mock'; import {ApiError} from '../src/api/error'; -import {downloadText, expect, expectLoadFailures, test} from './fixtures'; +import {downloadText, expect, expectLoadFailures, faults, test} from './fixtures'; import {sha256} from '../src/api/hash'; test.use({viewport: {width: 1440, height: 1000}}); @@ -223,24 +223,27 @@ test('paste into a read-only source is refused with the read-only notice', async await expect(editor).toHaveText(original, {useInnerText: true}); }); -test('the validation tab lists kept diagnostics and opens the source at the line', async ({page}) => { - await page.goto('/#/config?tab=validate'); - await expect(page.locator('.rp-toolbar').nth(1)).toContainText('Passed with 2 warnings'); - const rows = page.locator('.rp-table [role=rowgroup]:last-child [role=row][data-key]'); - await expect(rows).toHaveCount(3); - await page.getByRole('radio', {name: 'Info 1', exact: true}).click(); - await expect(rows).toHaveCount(1); - await page.getByRole('radio', {name: 'All 3', exact: true}).click(); - await page.getByRole('button', {name: 'Validate again', exact: true}).click(); - await expect(page.locator('.rp-toolbar').nth(1)).toContainText('Last validation'); - await expect(rows).toHaveCount(0); - await page.reload(); - await rows.filter({hasText: 'rules.dae:3'}).click(); - await page.getByRole('button', {name: 'Open source: rules.dae:3', exact: true}).click(); - await expect(page).toHaveURL(/tab=source&source=src-rules&line=3$/); - await expect(page.locator('.cm-content[aria-label="/etc/honk/rules.dae"]')).toBeVisible(); - // An editable source marks the line with its caret; a read-only one with the focus line. - await expect(page.locator('.cm-activeLine')).toContainText('mac(aa:bb:cc:dd:ee:ff)'); +test.describe(() => { + test.use({storage: faults}); + test('the validation tab lists kept diagnostics and opens the source at the line', async ({page}) => { + await page.goto('/#/config?tab=validate'); + await expect(page.locator('.rp-toolbar').nth(1)).toContainText('Passed with 2 warnings'); + const rows = page.locator('.rp-table [role=rowgroup]:last-child [role=row][data-key]'); + await expect(rows).toHaveCount(3); + await page.getByRole('radio', {name: 'Info 1', exact: true}).click(); + await expect(rows).toHaveCount(1); + await page.getByRole('radio', {name: 'All 3', exact: true}).click(); + await page.getByRole('button', {name: 'Validate again', exact: true}).click(); + await expect(page.locator('.rp-toolbar').nth(1)).toContainText('Last validation'); + await expect(rows).toHaveCount(0); + await page.reload(); + await rows.filter({hasText: 'rules.dae:3'}).click(); + await page.getByRole('button', {name: 'Open source: rules.dae:3', exact: true}).click(); + await expect(page).toHaveURL(/tab=source&source=src-rules&line=3$/); + await expect(page.locator('.cm-content[aria-label="/etc/honk/rules.dae"]')).toBeVisible(); + // An editable source marks the line with its caret; a read-only one with the focus line. + await expect(page.locator('.cm-activeLine')).toContainText('mac(aa:bb:cc:dd:ee:ff)'); + }); }); test('identical diagnostics share one row with their count, and a known code keeps the backend words as detail', async ({page}) => { diff --git a/e2e/fixtures.ts b/e2e/fixtures.ts index 7328eec5..11c211da 100644 --- a/e2e/fixtures.ts +++ b/e2e/fixtures.ts @@ -67,6 +67,10 @@ export const test = base.extend<{storage: Record}>({ } }); +// The mock backend's faults scenario: a degraded datapath, unavailable nodes, dropped flow records, warnings and +// errors in the logs, a failed operation and a rule the lite geodata files cannot serve. The default demo has none. +export const faults = {'doona-mock-scenario': 'faults'}; + // The selected item's detail: an aside beside the list on wide screens, a drawer below 1200px. export const detail = (page: Page) => page.locator('.rp-panel, .rp-drawer'); @@ -103,8 +107,8 @@ const query = (request: Request) => { return params as never; }; -export async function mockBackend(page: Page) { - const api = createMockApi(); +export async function mockBackend(page: Page, options: {faults?: boolean} = {}) { + const api = createMockApi(options); const capabilities = await api.capabilities(); capabilities.resources.events.available = false; const requests: Request[] = []; diff --git a/e2e/flows.spec.ts b/e2e/flows.spec.ts index 7e6f3e3e..8607e4c6 100644 --- a/e2e/flows.spec.ts +++ b/e2e/flows.spec.ts @@ -1,30 +1,33 @@ -import {expect, mockBackend, test} from './fixtures'; +import {expect, faults, mockBackend, test} from './fixtures'; test.use({viewport: {width: 1440, height: 900}}); -test('a flow opens its trace beside the list and links to its connection', async ({page}) => { - await page.goto('/#/rules?tab=flows'); - const rows = page.locator('.rp-table [role=rowgroup]:last-child [role=row][data-key]'); - await expect(rows.first()).toBeVisible(); - const total = await rows.count(); - expect(total).toBeGreaterThan(1); - await expect(page.locator('.rp-panel')).toHaveCount(0); - await expect(page.getByRole('group', {name: 'Observation coverage'})).toContainText('3 dropped records'); - await rows.filter({hasText: 'api.telegram.org'}).first().click(); - await expect(page).toHaveURL(/#\/rules\?tab=flows&id=flow-1$/); - const panel = page.locator('.rp-panel'); - await expect(panel.getByRole('heading', {name: 'api.telegram.org'})).toBeVisible(); - await expect(panel.getByText('Complete', {exact: true})).toBeVisible(); - expect(await panel.locator('.rp-step').count()).toBeGreaterThan(3); - await expect(panel.locator('.rp-step').first()).toContainText('Input'); - await panel.getByRole('link', {name: 'View connection', exact: true}).click(); - await expect(page).toHaveURL(/#\/connections\?id=1$/); - await expect(page.locator('.rp-panel').getByRole('heading', {name: 'api.telegram.org'})).toBeVisible(); - await page.locator('.rp-panel').getByRole('button', {name: 'View flow', exact: true}).click(); - await expect(page).toHaveURL(/#\/rules\?tab=flows&id=flow-1$/); - await page.locator('.rp-panel').getByRole('button', {name: 'Close', exact: true}).click(); - await expect(page).toHaveURL(/#\/rules\?tab=flows$/); - await expect(page.locator('.rp-panel')).toHaveCount(0); +test.describe(() => { + test.use({storage: faults}); + test('a flow opens its trace beside the list and links to its connection', async ({page}) => { + await page.goto('/#/rules?tab=flows'); + const rows = page.locator('.rp-table [role=rowgroup]:last-child [role=row][data-key]'); + await expect(rows.first()).toBeVisible(); + const total = await rows.count(); + expect(total).toBeGreaterThan(1); + await expect(page.locator('.rp-panel')).toHaveCount(0); + await expect(page.getByRole('group', {name: 'Observation coverage'})).toContainText('3 dropped records'); + await rows.filter({hasText: 'api.telegram.org'}).first().click(); + await expect(page).toHaveURL(/#\/rules\?tab=flows&id=flow-1$/); + const panel = page.locator('.rp-panel'); + await expect(panel.getByRole('heading', {name: 'api.telegram.org'})).toBeVisible(); + await expect(panel.getByText('Complete', {exact: true})).toBeVisible(); + expect(await panel.locator('.rp-step').count()).toBeGreaterThan(3); + await expect(panel.locator('.rp-step').first()).toContainText('Input'); + await panel.getByRole('link', {name: 'View connection', exact: true}).click(); + await expect(page).toHaveURL(/#\/connections\?id=1$/); + await expect(page.locator('.rp-panel').getByRole('heading', {name: 'api.telegram.org'})).toBeVisible(); + await page.locator('.rp-panel').getByRole('button', {name: 'View flow', exact: true}).click(); + await expect(page).toHaveURL(/#\/rules\?tab=flows&id=flow-1$/); + await page.locator('.rp-panel').getByRole('button', {name: 'Close', exact: true}).click(); + await expect(page).toHaveURL(/#\/rules\?tab=flows$/); + await expect(page.locator('.rp-panel')).toHaveCount(0); + }); }); test('a pinned tree item carries into the records', async ({page}) => { @@ -33,7 +36,7 @@ test('a pinned tree item carries into the records', async ({page}) => { const rule = topology.locator('[data-stage="rule"]').filter({hasText: 'dip(geoip: private)'}); await rule.click(); // A rule is pinned by its id, so the address survives a rewording of the expression. - await expect(page).toHaveURL(/path=rule%3Ar3$/); + await expect(page).toHaveURL(/path=rule%3Ar2$/); await expect(rule).toHaveAttribute('aria-pressed', 'true'); const showFlows = page.getByRole('button', {name: /^Show the \d+ flows? on this path$/}); const matching = Number((await showFlows.innerText()).match(/\d+/)?.[0]); diff --git a/e2e/geodata.spec.ts b/e2e/geodata.spec.ts index 54a6af30..8dd71b6d 100644 --- a/e2e/geodata.spec.ts +++ b/e2e/geodata.spec.ts @@ -9,8 +9,8 @@ const t = (key: Parameters[1], params?: Parameters { @@ -57,20 +57,20 @@ test('choosing a preset saves it once and then updates once', async ({page}) => }); test('a failed update keeps the old files and shows the reason in the status row', async ({page}) => { - const {sent} = await traffic(page); + const {sent} = await traffic(page, {faults: true}); await page.goto('/#/settings'); await section(page) .getByRole('button', {name: t('settings.geodataSource')}) .first() .click(); - // The demo rules use geosite:discord, which the lite file lacks; the option says so before it is chosen. + // The faults scenario's rules use geosite:category-ads-all, which the lite file lacks; the option says so before it is chosen. const option = page.getByRole('option', {name: t('settings.geodataPreset.metacubexLite')}); - await expect(option).toContainText('geosite:discord'); + await expect(option).toContainText('geosite:category-ads-all'); await option.click(); // Choosing it asks first; cancelling stores nothing and keeps the source shown. const lite = t('settings.geodataPreset.metacubexLite'); const dialog = page.getByRole('dialog', {name: t('settings.geodataLackingTitle', {preset: lite})}); - await expect(dialog).toContainText(t('settings.geodataLackingHelp', {preset: lite, codes: 'geosite:discord'})); + await expect(dialog).toContainText(t('settings.geodataLackingHelp', {preset: lite, codes: 'geosite:category-ads-all'})); await dialog.getByRole('button', {name: t('ui.cancel'), exact: true}).click(); await expect(dialog).toHaveCount(0); await expect( diff --git a/e2e/nodes.spec.ts b/e2e/nodes.spec.ts index 6d205557..1026da1f 100644 --- a/e2e/nodes.spec.ts +++ b/e2e/nodes.spec.ts @@ -12,9 +12,9 @@ test('nodes sort by name, latency and protocol, and filter by group and protocol await expect(list.first()).toContainText('hk-01'); await table.getByRole('columnheader', {name: /^Latency/}).click(); await expect(list.first()).toContainText('sg-01'); - await expect(list.last()).toContainText('jp-01'); + await expect(list.last()).toContainText('us-01'); await table.getByRole('columnheader', {name: /^Latency/}).click(); - await expect(list.first()).toContainText('jp-01'); + await expect(list.first()).toContainText('us-01'); await table.getByRole('columnheader', {name: /^Node/}).click(); await expect(list.first()).toContainText('hk-01'); await page.getByRole('button', {name: /Group$/}).click(); diff --git a/e2e/rule-editor.spec.ts b/e2e/rule-editor.spec.ts index b8974774..ad298dbd 100644 --- a/e2e/rule-editor.spec.ts +++ b/e2e/rule-editor.spec.ts @@ -35,7 +35,7 @@ test('the rule list shows the dictionary in evaluation order with its source lin await page.goto('/#/rules?tab=list'); const list = rows(page); await expect(list).toHaveCount(9); - await expect(list.first()).toContainText('domain(suffix: doubleclick.net)'); + await expect(list.first()).toContainText('pname(NetworkManager, systemd-resolved)'); await expect(list.first()).toContainText('config.dae:40'); await expect(list.nth(5)).toContainText('rules.dae:3'); await expect(list.last()).toContainText('fallback: resilient'); diff --git a/src/api/mock.test.ts b/src/api/mock.test.ts index b4a24de9..8e3f079b 100644 --- a/src/api/mock.test.ts +++ b/src/api/mock.test.ts @@ -4,12 +4,16 @@ import {chainLabel, ipLiteral, outboundUsage, preferredHealth, sourceIp} from '. import {addU64} from './u64'; import type {ApiEvent} from './model'; import {connectionFixtures, trafficHistory} from './mock/fixtures'; +import {liteCategories} from '../dae/geodata'; afterEach(() => { vi.useRealTimers(); vi.unstubAllGlobals(); }); +// A mock backend in the faults scenario, which seeds the degraded states the default demo leaves out. +const faultsApi = () => createMockApi({faults: true}); + it('validates and enumerates quoted hashes without treating them as comments', async () => { vi.useFakeTimers(); const api = createMockApi(); @@ -70,8 +74,31 @@ it('serves cumulative outbound counters independently of live connection bytes', expect(near(runtime.traffic.rates!.upload_bytes_per_second, history.samples.at(-1)!.upload_bytes_per_second!)).toBe(true); }); +it('serves a healthy honk by default and the seeded faults only in the faults scenario', async () => { + const healthy = async (api: ReturnType) => { + const [datapath, nodes, flows, config, geodata] = await Promise.all([api.datapath(), api.nodes(), api.flows(), api.config(), api.geodata()]); + const levels = new Set(); + const controller = new AbortController(); + const stream = api.subscribeLogs({level: 'trace', signal: controller.signal, onRecord: record => levels.add(record.level)}); + controller.abort(); + await stream; + const lite = liteCategories.geosite; + return { + datapath: datapath.state === 'active' && datapath.errors.length === 0, + nodes: nodes.nodes.every(node => node.health.every(sample => sample.state === 'healthy')), + flows: flows.dropped_records === '0', + config: config.diagnostics.length === 0, + logs: !levels.has('warn') && !levels.has('error'), + geodata: geodata.required_codes!.geosite.every(code => lite.includes(code)) + }; + }; + const all = {datapath: true, nodes: true, flows: true, config: true, logs: true, geodata: true}; + expect(await healthy(createMockApi())).toEqual(all); + expect(await healthy(faultsApi())).toEqual(Object.fromEntries(Object.keys(all).map(key => [key, false]))); +}); + it('keeps the fuller demo history, cache and rankings internally consistent', async () => { - const api = createMockApi(); + const api = faultsApi(); const [dns, cache, nodes, flows, rules, memory] = await Promise.all([ api.dnsLog({limit: 500}), api.dnsCache(), @@ -214,7 +241,7 @@ it('finds a retained flow by connection ID when the live row has no flow ID', as }); it('omits unavailable summary input without losing retained detail evidence', async () => { - const api = createMockApi(); + const api = faultsApi(); const snapshot = await api.flows(); const summary = snapshot.flows.find(flow => flow.id === 'flow-unobserved')!; expect(summary).not.toHaveProperty('input'); @@ -289,7 +316,7 @@ it('pages the airport override without losing members', async () => { }); it('advances reload operations and emits invalidations until aborted', async () => { vi.useFakeTimers(); - const api = createMockApi(); + const api = faultsApi(); const accepted = await api.startReload(); expect(accepted.status).toBe('queued'); expect((await api.operation(accepted.operation_id)).status).toBe('running'); @@ -336,7 +363,7 @@ it('selects both networks with an independent revision and preserves configurati it('completes probes with fixture failures and publishes fresh health', async () => { vi.useFakeTimers(); - const api = createMockApi(); + const api = faultsApi(); const before = preferredHealth((await api.nodes()).nodes.find(n => n.id === 'hk-01')!)!; vi.setSystemTime(Date.parse(before.observed_at) + 1000); const accepted = await api.startProbe({ diff --git a/src/api/mock/configuration.test.ts b/src/api/mock/configuration.test.ts index cea11fbf..651b1f8d 100644 --- a/src/api/mock/configuration.test.ts +++ b/src/api/mock/configuration.test.ts @@ -182,13 +182,19 @@ routing { domain(geosite: category-ads-all@ads) -> block it('fails a geodata update whose file lacks a used category the way honk does, keeping the files', async () => { vi.useFakeTimers(); - const api = createMockApi(); const lite = geodataPreset('metacubex-lite'); + const update = async (api: ReturnType) => { + await api.patchRuntimeSettings({geodata: {geosite: {urls: [...lite.urls.geosite]}, geoip: {urls: [...lite.urls.geoip]}}}); + const accepted = await api.updateGeodata(); + await vi.advanceTimersByTimeAsync(1000); + return api.operation(accepted.operation_id); + }; + // The default demo's rules use only categories the lite files carry. + expect((await update(createMockApi())).status).toBe('succeeded'); + // The faults scenario adds a rule on geosite:category-ads-all, which they lack. + const api = createMockApi({faults: true}); const before = (await api.geodata()).assets; - await api.patchRuntimeSettings({geodata: {geosite: {urls: [...lite.urls.geosite]}, geoip: {urls: [...lite.urls.geoip]}}}); - const accepted = await api.updateGeodata(); - await vi.advanceTimersByTimeAsync(1000); - const operation = await api.operation(accepted.operation_id); + const operation = await update(api); expect(operation.status).toBe('failed'); expect(operation.error).toMatchObject({ code: 'geodata_update_failed', diff --git a/src/api/mock/configuration.ts b/src/api/mock/configuration.ts index eac40075..c11a32ab 100644 --- a/src/api/mock/configuration.ts +++ b/src/api/mock/configuration.ts @@ -7,6 +7,7 @@ import {diagnose, includedFiles, includePaths, resolveIncludePath, sectionLines, import {includedBy, includePatterns, newSourcePathProblem} from '../../dae/newSource'; import type {MockLifecycle} from './lifecycle'; import type {MockGeodataState} from './geodata'; +import {faultRules} from './rules'; type ConfigurationApi = Pick< Api, @@ -28,7 +29,8 @@ export function createConfiguration( {enqueue, log, publish, eventData, trimLogs}: Effects, groupNames: () => Set, activateInventory: (text: string, revision: string) => void, - geodata: MockGeodataState + geodata: MockGeodataState, + faults = false ) { const settings = structuredClone(fixtures.runtimeSettings); const withGeodata = () => { @@ -40,7 +42,7 @@ export function createConfiguration( let disk: (ConfigSource & {content: string})[] = []; let loading: Promise<(ConfigSource & {content: string})[]> | undefined; const loadSources = () => - (loading ??= Promise.all(fixtures.configSources.map(stored)).then(list => { + (loading ??= Promise.all((faults ? fixtures.faultSources : fixtures.configSources).map(stored)).then(list => { sources = list; disk = [...list]; return list; @@ -95,7 +97,9 @@ export function createConfiguration( // Preserve fixture IDs for unchanged rules; new rules use their source location. function routingOf(list: (ConfigSource & {content: string})[]): {rules: RuleList['rules']; fallback: RuleList['fallback'] | null} { const byPath = new Map(list.map(item => [resolveIncludePath(undefined, item.path), item])); - const known = new Map(fixtures.configRules.rules.map(rule => [rule.cond + ' -> ' + rule.target + (rule.must ? '(must)' : ''), rule.id])); + const known = new Map( + [...fixtures.configRules.rules, ...faultRules].map(rule => [rule.cond + ' -> ' + rule.target + (rule.must ? '(must)' : ''), rule.id]) + ); const entries: RuleList['rules'] = []; let fallback: RuleList['fallback'] | null = null; const visited = new Set(); @@ -164,7 +168,7 @@ export function createConfiguration( sources: list.map(source => (capabilities.resources.config.content ? {...source} : {...source, content: undefined})), diagnostics: [ ...list.filter(ruleFile).flatMap(source => diagnose(source.id, source.content, known, 'full').filter(item => item.level !== 'error')), - ...fixtures.configNotes + ...(faults ? fixtures.configNotes : []) ], secrets_redacted: true }; diff --git a/src/api/mock/fixtures.ts b/src/api/mock/fixtures.ts index 25c160c5..2875229f 100644 --- a/src/api/mock/fixtures.ts +++ b/src/api/mock/fixtures.ts @@ -3,5 +3,5 @@ export {capabilities, capabilitiesBase, capabilitiesM1} from './fixtures/capabil export {trafficHistory, runtimeOutbounds, version, runtime, datapath, runtimeMemory} from './fixtures/runtime'; export {nodeFixtures, policyPick, providers, linkSchemes, geodata} from './fixtures/inventory'; export {flows, connections, flowDroppedRecords, flowSummaryOmitsInput, connectionFixtures, dnsCache} from './fixtures/network'; -export {runtimeSettings, configRules, rules, configNotes, configSources} from './fixtures/configuration'; +export {runtimeSettings, configRules, rules, configNotes, configSources, faultSources} from './fixtures/configuration'; export {logSeed} from './fixtures/lifecycle'; diff --git a/src/api/mock/fixtures/configuration.ts b/src/api/mock/fixtures/configuration.ts index 99e9f358..8a0a5004 100644 --- a/src/api/mock/fixtures/configuration.ts +++ b/src/api/mock/fixtures/configuration.ts @@ -1,5 +1,5 @@ import type {Group, RuntimeSettings, ConfigDiagnostic, ConfigSource} from '../../model'; -import {rules, type ConfigRule} from '../rules'; +import {faultRules, rules, type ConfigRule} from '../rules'; import {ago, observedAt, generationId} from './clock'; export const groupPolicies = { proxy: {kind: 'selector', native: 'fixed(0)'}, @@ -83,8 +83,8 @@ const configRulesFile = `# Household exceptions, kept apart from config.dae. # The TV never leaves through a node. mac(aa:bb:cc:dd:ee:ff) && ipversion(4) -> direct -# Chat -domain(geosite: discord) -> proxy +# AI +domain(geosite: openai) -> proxy sip(10.0.0.0/24) && dport(25) -> block `; const configSubscription = `'香港 01 IPLC': 'vless://' @@ -95,6 +95,7 @@ const configSubscription = `'香港 01 IPLC': 'vless://' const configGenerated = `# Written by honk from the subscription; edits are lost on refresh. skylink { filter: subtag(sub-c) } `; +// The faults scenario's backend notes. export const configNotes: ConfigDiagnostic[] = [ { level: 'warning', @@ -139,3 +140,7 @@ export const configSources: Array + source.id === 'src-rules' ? {...source, content: source.content + '\n# Ads\n' + faultRules.map(rule => `${rule.cond} -> ${rule.target}\n`).join('')} : source +); diff --git a/src/api/mock/fixtures/inventory.ts b/src/api/mock/fixtures/inventory.ts index cefbfcff..6bced7ca 100644 --- a/src/api/mock/fixtures/inventory.ts +++ b/src/api/mock/fixtures/inventory.ts @@ -78,13 +78,14 @@ function group(name: keyof typeof groupPolicies, members: string[], leaf: string } }; } -export function nodeFixtures(count: number): {nodes: Node[]; groups: Group[]} { +// Every node answers its probes unless the faults scenario takes jp-01 and about one subscription node in sixteen down. +export function nodeFixtures(count: number, faults = false): {nodes: Node[]; groups: Group[]} { const nodes = [ // The inline nodes match the links in the mock's config.dae. node('hk-01', 84, 91, true, 'inline', 'vless'), node('hk-02', 91, 88, true, 'inline', 'vless'), node('sg-01', 63, 70, false, 'inline', 'trojan'), - node('jp-01', null, null, false, 'inline', 'vless'), + node('jp-01', faults ? null : 132, faults ? null : 139, false, 'inline', 'vless'), node('us-01', 188, 201, true, 'inline', 'anytls') ]; const groups = [ @@ -115,7 +116,7 @@ export function nodeFixtures(count: number): {nodes: Node[]; groups: Group[]} { const [region, base] = regions[i % regions.length]; const n = String(Math.floor(i / regions.length) + 1).padStart(2, '0'); const tag = tags[Math.floor(rnd() * tags.length)]; - const alive = rnd() > 0.06; + const alive = rnd() > 0.06 || !faults; const tcp = Math.round(base + rnd() * base * 0.8); const udp = alive ? tcp + Math.round(rnd() * 20) : null; airport.push(node(region + ' ' + n + (tag ? ' ' + tag : ''), alive ? tcp : null, udp, rnd() > 0.5, 'sub-c')); diff --git a/src/api/mock/fixtures/network.ts b/src/api/mock/fixtures/network.ts index a331896c..87e4960f 100644 --- a/src/api/mock/fixtures/network.ts +++ b/src/api/mock/fixtures/network.ts @@ -96,7 +96,7 @@ export const connections: ConnectionList = { connection('2', '120.92.78.14:443', '10.0.0.7', 'direct', '1200000000', '9400000', 'cdn.bilibili.com'), connection('3', '52.84.19.3:443', '10.0.0.7', 'proxy', '58000000', '12000'), connection('4', '142.250.66.46:443', '10.0.0.31', 'block', '0', '0', 'doubleclick.net'), - connection('6', '104.16.132.229:443', '10.0.0.31', 'proxy', '3400000', '210000', 'discord.com'), + connection('6', '104.16.132.229:443', '10.0.0.31', 'proxy', '3400000', '210000', 'chatgpt.com'), connection('7', '203.0.113.9:8443', '10.0.0.20', 'resilient', '96000', '40000') ], udp: [ diff --git a/src/api/mock/fixtures/runtime.ts b/src/api/mock/fixtures/runtime.ts index 94a36165..ba18df03 100644 --- a/src/api/mock/fixtures/runtime.ts +++ b/src/api/mock/fixtures/runtime.ts @@ -76,18 +76,18 @@ export const runtime: Runtime = { instance_id: instanceId, lifecycle: {state: 'running', started_at: ago(777600), uptime_seconds: '777600'}, generation: {active_id: generationId, config_revision: generationId, state: 'active', activated_at: ago(210)}, - // The same degraded datapath /datapath reports in full: one delayed map sample, everything else attached. + // The same healthy datapath /datapath reports in full. datapath: { kind: 'ebpf', - state: 'degraded', + state: 'active', visibility: 'full', ebpf: { backend: 'real', programs: 'loaded', hooks: 'attached', routing: {state: 'published', generation_id: '40'}, - health: 'degraded', - last_error: 'Routing map sample delayed', + health: 'healthy', + last_error: null, checked_at: observedAt } }, @@ -110,7 +110,7 @@ export const runtime: Runtime = { export const datapath: Datapath = { observed_at: observedAt, kind: 'ebpf', - state: 'degraded', + state: 'active', visibility: 'full', ebpf: { ...runtime.datapath.ebpf!, @@ -119,8 +119,10 @@ export const datapath: Datapath = { ), maps: {state: 'ready', conn_state: {occupancy: live.length, capacity: 65536, occupancy_known: true}} }, - errors: [{code: 'sample_delayed', message: 'Routing map sample delayed'}] + errors: [] }; +// The faults scenario's datapath: one delayed map sample, everything else attached. +export const datapathFault = {code: 'sample_delayed', message: 'Routing map sample delayed'}; export const runtimeMemory: RuntimeMemory = { observed_at: observedAt, process: {rss_bytes: '48234496'}, diff --git a/src/api/mock/flows.ts b/src/api/mock/flows.ts index c73030dc..9436b767 100644 --- a/src/api/mock/flows.ts +++ b/src/api/mock/flows.ts @@ -45,7 +45,7 @@ const ruleTable: Array<[string[], string]> = [ 'r4' ], [['telegram.org', 't.me'], 'r5'], - [['discord.com', 'discord.gg', 'discordapp.com'], 'r7'] + [['openai.com', 'chatgpt.com', 'oaistatic.com'], 'r7'] ]; const ruleOf = (id: string) => rules.find(rule => rule.id === id)!; function ruleFor(domain: string): {id: string; expression: string} | null { diff --git a/src/api/mock/geodata.ts b/src/api/mock/geodata.ts index 6991f320..5154b2ce 100644 --- a/src/api/mock/geodata.ts +++ b/src/api/mock/geodata.ts @@ -4,7 +4,7 @@ import {redactUrl} from './common'; import {defaultGeodataPreset, geodataIntervalRange, geodataPresets, maxGeodataUrls, validGeodataUrl} from '../../dae/geodata'; import {scanConfig} from '../../dae/text'; import * as fixtures from './fixtures/inventory'; -import {rules} from './rules'; +import {faultRules, rules} from './rules'; const kinds: GeoAssetKind[] = ['geosite', 'geoip']; // The categories the given rule conditions use, lowercase and without attribute suffixes, as honk reports them. @@ -23,13 +23,13 @@ const publishesChecksum = (url: string) => /^https:\/\/(raw\.githubusercontent\. const presetAt = (kind: GeoAssetKind, url: string) => geodataPresets.find(preset => preset.urls[kind].includes(url) || preset.mirrors[kind].includes(url)); // The stored geodata settings and update status: the backend keeps them across reloads, unlike the other runtime settings. -export function createGeodataState(capabilities: Capabilities, groupIds: () => Set) { +export function createGeodataState(capabilities: Capabilities, groupIds: () => Set, faults = false) { const configurable = capabilities.resources.geodata.configurable_sources === true; let stored: Record | null = null; const auto = {enabled: true, interval_hours: 24}; let download: GeoDataDownload = {route: 'routing', group_id: null}; const data = structuredClone(fixtures.geodata); - data.required_codes = requiredCodes(rules.map(rule => rule.cond)); + data.required_codes = requiredCodes([...rules, ...(faults ? faultRules : [])].map(rule => rule.cond)); const urls = () => stored ?? {geosite: [...defaultGeodataPreset.urls.geosite], geoip: [...defaultGeodataPreset.urls.geoip]}; const nextCheck = (from: number) => (auto.enabled ? new Date(from + auto.interval_hours * 3600_000 + 17 * 60_000).toISOString() : null); data.next_check_at = nextCheck(Date.parse(data.last_checked_at ?? '') || Date.now()); diff --git a/src/api/mock/index.ts b/src/api/mock/index.ts index 0b48b4b5..818a7aff 100644 --- a/src/api/mock/index.ts +++ b/src/api/mock/index.ts @@ -10,7 +10,8 @@ import {createGeodataState} from './geodata'; export type MockApi = Api & OperationReader; -export function createMockApi(): MockApi { +// `faults` selects the faults scenario where storage cannot, as for the specs' in-process backend. +export function createMockApi(options: {faults?: boolean} = {}): MockApi { let count = 120; let big = false; // A busy backend for tools/perf.mjs: byte counters move on every poll and logs arrive every 20 ms. @@ -25,15 +26,18 @@ export function createMockApi(): MockApi { } let capabilities = fullCapabilities; let profile: string | null = null; + // The default demo is a healthy honk; the faults scenario seeds the degraded states that specs need. + let faults = options.faults ?? false; try { + faults ||= localStorage.getItem('doona-mock-scenario') === 'faults'; profile = localStorage.getItem('doona-mock-profile'); if (profile === 'base') capabilities = capabilitiesBase; if (profile === 'm1') capabilities = capabilitiesM1; } catch { /* Storage can be unavailable. */ } - const runtime = createRuntime(capabilities, big); - const geodata = createGeodataState(capabilities, () => inventory.groupIds()); + const runtime = createRuntime(capabilities, big, faults); + const geodata = createGeodataState(capabilities, () => inventory.groupIds(), faults); const configuration = createConfiguration( capabilities, runtime.runtime, @@ -46,7 +50,8 @@ export function createMockApi(): MockApi { }, () => inventory.groupNames(), (text, revision) => inventory.activate(text, revision), - geodata + geodata, + faults ); const lifecycle = createLifecycle( capabilities.resources.logs, @@ -54,9 +59,10 @@ export function createMockApi(): MockApi { runtime.runtime, configuration.logSettings, configuration.revision, - busy ? 20 : 2500 + busy ? 20 : 2500, + faults ); - const network = createNetwork(capabilities, big, profile, runtime.outbounds, configuration.revision, configuration.ruleSnapshot, busy); - const inventory = createInventory(capabilities, count, lifecycle, configuration.advance, configuration.editMain, network.interrupt, geodata); + const network = createNetwork(capabilities, big, profile, runtime.outbounds, configuration.revision, configuration.ruleSnapshot, busy, faults); + const inventory = createInventory(capabilities, count, lifecycle, configuration.advance, configuration.editMain, network.interrupt, geodata, faults); return {...runtime.api, ...lifecycle.api, ...network.api, ...inventory.api, ...configuration.api}; } diff --git a/src/api/mock/inventory.ts b/src/api/mock/inventory.ts index c5f869a6..1c06d1e1 100644 --- a/src/api/mock/inventory.ts +++ b/src/api/mock/inventory.ts @@ -46,12 +46,13 @@ export function createInventory( advance: () => string, editMain: (edit: (text: string) => string) => Promise<() => string>, interrupt: (groupId: string, network: 'tcp' | 'udp') => boolean, - geodata: MockGeodataState + geodata: MockGeodataState, + faults = false ) { const nodePage = createPager('nodes'); const providerPage = createPager('providers'); const providers = structuredClone(fixtures.providers); - const {nodes, groups} = fixtures.nodeFixtures(Number.isFinite(count) ? count : 120); + const {nodes, groups} = fixtures.nodeFixtures(Number.isFinite(count) ? count : 120, faults); for (const provider of providers) provider.node_count = nodes.filter(n => n.provider_id === provider.id).length; const revisions = new Map(); const updating = new Set(); diff --git a/src/api/mock/lifecycle.ts b/src/api/mock/lifecycle.ts index 750cdf94..f8303e3e 100644 --- a/src/api/mock/lifecycle.ts +++ b/src/api/mock/lifecycle.ts @@ -36,7 +36,8 @@ export function createLifecycle( runtime: Pick, logSettings: () => RuntimeSettings['log'], revision: () => string, - trickleEvery = 2500 + trickleEvery = 2500, + faults = false ): MockLifecycle { const operations = new Map(); let sequence = 0; @@ -151,28 +152,35 @@ export function createLifecycle( () => log('info', 'honk::routing', 'Routing generation published.', {generation_id: revision()}), () => log('debug', 'honk::dns', 'Upstream answered.', {upstream: 'tls://1.1.1.1:853', elapsed_ms: 12}), () => log('info', 'honk::group', 'Health check finished.', {group: 'resilient', healthy: 3, unavailable: 0}), - () => log('warn', 'honk::subscription', 'Subscription served from cache.', {provider: 'sub-c', age_seconds: 1800}), + ...(faults ? [() => log('warn', 'honk::subscription', 'Subscription served from cache.', {provider: 'sub-c', age_seconds: 1800})] : []), () => log('trace', 'honk::datapath', 'Kernel map synced.', {entries: 4096}) ]; - // A four-hour ring has routine traffic, busy periods and a short health-check incident. + // A four-hour ring has routine traffic and busy periods; the faults scenario adds a stale subscription and a short + // health-check incident. const started = Date.now(); for (let minute = 240; minute > 0; minute -= 2) { const at = started - minute * 60000; - const trouble = minute >= 34 && minute <= 48; + const trouble = faults && minute >= 34 && minute <= 48; const busy = (minute >= 72 && minute <= 116) || (minute >= 164 && minute <= 188); log('info', 'honk::group', 'Health check finished.', {group: 'resilient', healthy: trouble ? 2 : 3, unavailable: trouble ? 1 : 0}, at); log('debug', 'honk::dns', 'Upstream answered.', {upstream: 'tls://1.1.1.1:853', elapsed_ms: 12 + (minute % 9)}, at + 20000); if (minute % 6 === 0) log('trace', 'honk::datapath', 'Kernel map synced.', {entries: 4096 + minute}, at + 10000); - if (minute % 14 === 0) log('warn', 'honk::subscription', 'Subscription served from cache.', {provider: 'sub-c', age_seconds: 1800}, at + 40000); + if (faults && minute % 14 === 0) log('warn', 'honk::subscription', 'Subscription served from cache.', {provider: 'sub-c', age_seconds: 1800}, at + 40000); if (busy) log('info', 'honk::dns', 'Query answered.', {queries: 12 + (minute % 15)}, at + 30000); if (trouble) { log('warn', 'honk::group', 'Health check slow.', {node: 'us-01', elapsed_ms: 2400}, at + 30000); log('error', 'honk::group', 'Health check failed.', {node: 'us-01', error: 'connect timeout'}, at + 50000); } } - for (const record of logSeed) log(record.level, record.target, record.message, record.fields ?? null); + for (const record of logSeed) + if (faults || (record.level !== 'warn' && record.level !== 'error')) log(record.level, record.target, record.message, record.fields ?? null); + // Recorder gaps and a failed operation belong to the faults scenario. for (let i = 28; i > 0; i--) { const data = {instance_id: instanceId, observed_at: new Date(started - i * 10000).toISOString()}; + if (!faults && i >= 4 && i <= 7) { + publish({id: '', event: 'runtime.updated', data: {...data, href: '/api/v1/runtime'}}); + continue; + } if (i === 21) publish({id: '', event: 'generation.changed', data: {...data, previous_generation_id: '39', generation_id: '40'}}); else if (i === 17) publish({id: '', event: 'operation.updated', data: {...data, resource_id: 'op-1182', status: 'succeeded', href: '/api/v1/operations/op-1182'}}); diff --git a/src/api/mock/network.ts b/src/api/mock/network.ts index 996ee073..dc9615fd 100644 --- a/src/api/mock/network.ts +++ b/src/api/mock/network.ts @@ -9,12 +9,13 @@ import {routingTrace} from './routing'; const dnsRings = new WeakMap(); // Derived once per flows array; a real backend keeps its ring, so the mock should not re-sort on every poll. -function dnsLogRecords(flows: FlowDetail[]): DnsLogRecord[] { +function dnsLogRecords(flows: FlowDetail[], faults: boolean): DnsLogRecord[] { let ring = dnsRings.get(flows); - if (!ring) dnsRings.set(flows, (ring = buildDnsLog(flows))); + if (!ring) dnsRings.set(flows, (ring = buildDnsLog(flows, faults))); return ring; } -function buildDnsLog(flows: FlowDetail[]): DnsLogRecord[] { +// Upstream timeouts and server failures belong to the faults scenario; NXDOMAIN and refused ad domains are answers. +function buildDnsLog(flows: FlowDetail[], faults: boolean): DnsLogRecord[] { let seed = 941; const next = () => (seed = (seed * 48271) % 2147483647) / 2147483647; const domains = [...new Set(flows.map(flow => flow.input.domain).filter((name): name is string => !!name))]; @@ -29,7 +30,7 @@ function buildDnsLog(flows: FlowDetail[]): DnsLogRecord[] { const type = i % 4 === 0 ? 'AAAA' : 'A'; const entry = fixtures.dnsCache.entries.find(row => row.domain === name && row.type === type); const cached = !denied && !!entry && i % 3 === 0; - const failed = !cached && !denied && i % 23 === 7; + const failed = faults && !cached && !denied && i % 23 === 7; const missing = !cached && !failed && !denied && i % 11 === 5; const status = denied ? 'REFUSED' : cached ? entry!.status : failed ? (i % 2 ? 'TIMEOUT' : 'SERVFAIL') : missing ? 'NXDOMAIN' : 'NOERROR'; const upstream = cached || denied ? null : i % 7 === 0 ? 'udp://223.5.5.5' : i % 4 === 0 ? 'https://dns.google/dns-query' : 'tls://1.1.1.1'; @@ -72,7 +73,8 @@ export function createNetwork( outbounds: RuntimeOutbounds, revision: () => string, ruleSnapshot: () => Promise, - busy = false + busy = false, + faults = false ) { const flowPage = createPager('flows'); const cachePage = createPager('dnsCache'); @@ -149,7 +151,7 @@ export function createNetwork( dns_intercept: 'partial', kernel_bypass: 'none' }, - dropped_records: big ? '0' : fixtures.flowDroppedRecords, + dropped_records: big || !faults ? '0' : fixtures.flowDroppedRecords, flows: result.items.map(({trace, input, ...summary}) => (fixtures.flowSummaryOmitsInput[summary.id] ? summary : {...summary, input})), next_cursor: result.next_cursor }; @@ -185,7 +187,7 @@ export function createNetwork( throw new ApiError(400, 'invalid_request', 'limit exceeds the advertised page size'); const needle = query?.name?.toLowerCase(); const src = query?.src === undefined ? undefined : ipLiteral(query.src); - const ring = dnsLogRecords(flows); + const ring = dnsLogRecords(flows, faults); const records = ring.filter( r => (!needle || r.question.name.toLowerCase().includes(needle)) && diff --git a/src/api/mock/routing.ts b/src/api/mock/routing.ts index 7c2bd9c2..2808a06c 100644 --- a/src/api/mock/routing.ts +++ b/src/api/mock/routing.ts @@ -7,7 +7,7 @@ type Condition = Evaluation['rules'][number]['conditions'][number]; const geosites: Record = { cn: ['cn', 'bilibili.com', 'baidu.com', 'qq.com'], telegram: ['telegram.org', 'telegram.me', 't.me', 'telegra.ph'], - discord: ['discord.com', 'discord.gg', 'discordapp.com'] + openai: ['openai.com', 'chatgpt.com', 'oaistatic.com'] }; const fields: Record = { domain: 'domain', diff --git a/src/api/mock/rules.ts b/src/api/mock/rules.ts index 331840d2..50cf19dd 100644 --- a/src/api/mock/rules.ts +++ b/src/api/mock/rules.ts @@ -6,6 +6,8 @@ export const rules: ConfigRule[] = [ {id: 'r4', cond: 'domain(geosite: cn)', target: 'direct', must: false}, {id: 'r5', cond: 'domain(geosite: telegram)', target: 'proxy', must: false}, {id: 'r6', cond: 'mac(aa:bb:cc:dd:ee:ff) && ipversion(4)', target: 'direct', must: false}, - {id: 'r7', cond: 'domain(geosite: discord)', target: 'proxy', must: false}, + {id: 'r7', cond: 'domain(geosite: openai)', target: 'proxy', must: false}, {id: 'r8', cond: 'sip(10.0.0.0/24) && dport(25)', target: 'block', must: false} ]; +// The faults scenario's extra rule uses a category the lite geodata files lack, so updating from them fails. +export const faultRules: ConfigRule[] = [{id: 'r9', cond: 'domain(geosite: category-ads-all)', target: 'block', must: false}]; diff --git a/src/api/mock/runtime.ts b/src/api/mock/runtime.ts index 0d808a31..58268dcd 100644 --- a/src/api/mock/runtime.ts +++ b/src/api/mock/runtime.ts @@ -15,8 +15,16 @@ function memoryValues(at: number) { cgroup_current_bytes: String(Math.round(Number(fixtures.runtimeMemory.cgroup!.current_bytes) * drift)) }; } -export function createRuntime(capabilities: Capabilities, big: boolean) { +export function createRuntime(capabilities: Capabilities, big: boolean, faults = false) { const runtime = structuredClone(fixtures.runtime); + const datapath = structuredClone(fixtures.datapath); + if (faults) { + for (const view of [runtime.datapath, datapath]) { + view.state = 'degraded'; + Object.assign(view.ebpf!, {health: 'degraded', last_error: fixtures.datapathFault.message}); + } + datapath.errors = [structuredClone(fixtures.datapathFault)]; + } const outbounds = structuredClone(fixtures.runtimeOutbounds); // A large deployment lists dozens of outbounds, most of them idle. if (big) @@ -151,7 +159,7 @@ export function createRuntime(capabilities: Capabilities, big: boolean) { }, datapath: async (detail, signal) => { signal?.throwIfAborted(); - const snapshot = structuredClone(fixtures.datapath); + const snapshot = structuredClone(datapath); if (detail !== 'full' && snapshot.ebpf) { delete snapshot.ebpf.attachments; delete snapshot.ebpf.maps; diff --git a/src/features/activity/view.test.ts b/src/features/activity/view.test.ts index 443c5634..970bd477 100644 --- a/src/features/activity/view.test.ts +++ b/src/features/activity/view.test.ts @@ -23,7 +23,7 @@ it('distinguishes missing metrics from zero and keeps block traffic separate fro }); it('chooses measured nodes and preserves an explicitly selected unavailable node', () => { - const {nodes} = nodeFixtures(0); + const {nodes} = nodeFixtures(0, true); expect(nodeView(nodes, '', t).name).toBe('hk-01'); const unavailable = nodeView(nodes, 'jp-01', t); expect(unavailable.tone).toBe('err'); @@ -59,7 +59,7 @@ it('localizes notice kinds and shortens UUIDs without changing event identity', }); it('selects duplicate node labels by ID and preserves independent health', () => { - const {nodes} = nodeFixtures(0); + const {nodes} = nodeFixtures(0, true); const first = {...nodes.find(node => node.name === 'hk-01')!, id: 'provider-a/hk', name: 'HK', provider_id: 'provider-a'}; const second = {...nodes.find(node => node.name === 'jp-01')!, id: 'provider-b/hk', name: 'HK', provider_id: 'provider-b'}; const view = nodeView([first, second], second.id, t); diff --git a/src/features/overview/view.test.ts b/src/features/overview/view.test.ts index ea91cfae..b72ccf1a 100644 --- a/src/features/overview/view.test.ts +++ b/src/features/overview/view.test.ts @@ -1,10 +1,18 @@ import {expect, it} from 'vitest'; -import {capabilities, datapath, runtime, runtimeMemory, version} from '../../api/mock/fixtures'; +import {capabilities, datapath as healthy, runtime, runtimeMemory, version} from '../../api/mock/fixtures'; +import {datapathFault} from '../../api/mock/fixtures/runtime'; import {translate, type Translator} from '../../i18n'; import {datapathFields, datapathValue, memoryFields, overviewExport, overviewView} from './view'; import {formatBytes} from '../../i18n/format'; import type {KvItem} from '../../ui/ui'; const t: Translator = (key, params) => translate('en', key, params); +// The faults scenario's datapath: its one error also stands as the eBPF last error. +const datapath = { + ...healthy, + state: 'degraded' as const, + ebpf: {...healthy.ebpf!, health: 'degraded' as const, last_error: datapathFault.message}, + errors: [datapathFault] +}; const loading = {capabilities: false, runtime: false, version: false, memory: false, datapath: false}; // The row with this label, as an object whichever form it has. const field = (items: KvItem[], label: string) => diff --git a/src/features/policies/view.test.ts b/src/features/policies/view.test.ts index 5e815e86..6147c20c 100644 --- a/src/features/policies/view.test.ts +++ b/src/features/policies/view.test.ts @@ -17,7 +17,7 @@ import { import {memberHealth} from './health'; const t: Translator = (key, params) => translate('en', key, params); it('projects nested, failed and unmeasured members without inventing latency', () => { - const {groups} = nodeFixtures(0); + const {groups} = nodeFixtures(0, true); const members = memberViews(memberHealth(groups[0], new Map()), t); expect(members.find(member => member.id === 'jp-01')).toMatchObject({unavailable: true, tcp: undefined, status: {text: t('ui.unavailable'), tone: 'err'}}); expect(members.find(member => member.id === 'resilient')).toMatchObject({