Files
doona/src/api/selectors.test.ts
T
Zakk 8eb50d63f4 feat(connections): identify devices by MAC
In dual-stack LANs one device showed up as separate IPv4 and IPv6 entries
(daeuniverse/honk#446). honk is adding Connection.src_mac and a `mac` query
to listing and closing connections; the vendored contract carries both ahead
of that change, and the mock reports MAC addresses for its devices, one of
them also over IPv6 and one without a MAC address.

A device is now its MAC address when the backend knows it, otherwise its
source address. The device ranking, the dashboard ranking widget and the
connections grouped by device key on it, so one device's IPv4 and IPv6
traffic merge. An unnamed device keeps the address it showed before: its
latest IPv4 address, else its first one. A MAC device links to and filters
its connections with `?mac=`; a link in dash, dotted, bare or upper-case
form reads as the colon form, one honk cannot read is still sent so its
refusal shows, and a MAC address replaces any `src` in the same link, so
bulk close never goes out wider than the list.

The connection details show the source MAC address as a link that names
the device. Names are kept in this browser only, re-read before each save
and synced across tabs, and replace the address in the ranking, the groups
and the device picker. Search matches the MAC address and its name. With
no MAC addresses reported the pages render as before.
2026-12-04 20:46:02 +11:00

153 lines
7.3 KiB
TypeScript

import {expect, it} from 'vitest';
import type {ApiEvent, Connection, ConnectionList, GroupSummary} from './model';
import {
addressPort,
connectionRows,
eventKindLabels,
eventKinds,
eventSummary,
logLevelLabels,
logLevels,
macLiteral,
memoryTone,
noNodeSources,
nodeOwner,
resolveSelectedLeaf,
routineGap,
shortId
} from './selectors';
import {formatNumber, LOCALE, readLang, translate} from '../i18n';
import {createMockApi} from '../../mock';
const gap = (reason: string, resource_id: string | null): ApiEvent =>
({
id: 'x',
event: 'flow.gap',
data: {instance_id: 'i', observed_at: '2026-09-19T00:00:00Z', resource_id, reason, dropped_records: '1'}
}) as ApiEvent;
it('treats the ring making room as housekeeping and a record losing its history as a gap', () => {
expect(routineGap(gap('evicted', null))).toBe(true);
expect(routineGap(gap('sampled', null))).toBe(true);
expect(routineGap(gap('buffer_overflow', null))).toBe(true);
expect(routineGap(gap('buffer_overflow', 'flow-1'))).toBe(true);
expect(routineGap(gap('recording_changed', null))).toBe(false);
expect(routineGap({id: 'y', event: 'stream.ready', data: {instance_id: 'i', observed_at: ''}} as ApiEvent)).toBe(false);
});
it('shortens a UUID to its first block and leaves other ids alone', () => {
expect(shortId('e5af7786-442b-4f06-8ba5-ffa47f7dec70')).toBe('e5af7786');
expect(shortId('gen-41')).toBe('gen-41');
expect(shortId('—')).toBe('—');
});
it('resolves deep group chains and stops at an actual cycle', async () => {
const api = createMockApi();
const node = (await api.nodes()).nodes[0];
const template = (await api.groups())[0];
const groups: GroupSummary[] = Array.from({length: 12}, (_, index) => ({
...template,
id: `g${index}`,
name: `g${index}`,
selection: {tcp_member_id: index === 11 ? node.id : `g${index + 1}`, udp_member_id: null}
}));
const byId = new Map(groups.map(group => [group.id, group]));
const nodes = new Map([[node.id, node]]);
expect(resolveSelectedLeaf('g0', 'tcp', byId, byId, nodes)).toEqual({groups, member: node.id, node});
groups[11].selection.tcp_member_id = 'g0';
expect(resolveSelectedLeaf('g0', 'tcp', byId, byId, nodes)).toEqual({groups, member: null, node: null});
});
it('groups dropped counts in gap summaries without rounding a large UInt64', () => {
const dropped = (dropped_records: string | null) => {
const event = gap('buffer_overflow', null) as Extract<ApiEvent, {event: 'flow.gap'}>;
return eventSummary({...event, data: {...event.data, dropped_records}} as ApiEvent);
};
expect(translate('en', 'event.gap', dropped('12345').params)).toContain('12,345');
expect(dropped('18446744073709551615').params?.n).toBe(formatNumber(18446744073709551615n, LOCALE[readLang()]));
expect(dropped(null).params?.n).toBe('—');
});
it('starts a gap summary at its reason when the gap names no record', () => {
const unscoped = eventSummary(gap('recording_changed', null));
expect(translate('en', unscoped.key, unscoped.params)).toBe('reason: recording_changed, records dropped since recording started: 1');
const scoped = eventSummary(gap('buffer_overflow', 'flow-r03'));
expect(translate('en', scoped.key, scoped.params)).toMatch(/^flow-r03, reason: /);
});
it('leaves the count out of a gap that dropped no records, but keeps an unknown one', () => {
const summary = (resource_id: string | null, dropped_records: string | null) => {
const event = gap('recording_changed', resource_id) as Extract<ApiEvent, {event: 'flow.gap'}>;
const {key, params} = eventSummary({...event, data: {...event.data, dropped_records}} as ApiEvent);
return translate('en', key, params);
};
expect(summary(null, '0')).toBe('reason: recording_changed');
expect(summary('flow-r03', '0')).toBe('flow-r03, reason: recording_changed');
expect(summary(null, null)).toBe('reason: recording_changed, records dropped since recording started: —');
});
it('files a node under its provider, or under the built-in or unattributed owner the nodes page lists', () => {
expect(nodeOwner({provider_id: 'sub', protocol: 'vmess'}, [])).toBe('sub');
expect(nodeOwner({provider_id: null, protocol: 'direct'}, [])).toBe('builtin');
expect(nodeOwner({provider_id: null, protocol: 'vmess'}, [])).toBe('unattributed');
// A real provider that happens to use the pseudo owner's id keeps it; the pseudo owner moves aside.
expect(nodeOwner({provider_id: null, protocol: 'block'}, [{id: 'builtin'}, {id: 'builtin-'}])).toBe('builtin--');
});
it('tones memory use by its share of the limit', () => {
expect([0, 75, 75.5, 90, 90.5].map(memoryTone)).toEqual(['ok', 'ok', 'warn', 'warn', 'err']);
});
it('reads the port of an address, including a bracketed IPv6 one', () => {
expect(addressPort('149.154.167.220:443')).toBe('443');
expect(addressPort('[2001:db8::1]:8443')).toBe('8443');
expect(addressPort('2001:db8::1')).toBeUndefined();
expect(addressPort('10.0.0.2')).toBeUndefined();
expect(addressPort(undefined)).toBeUndefined();
});
it('reads a MAC address in each form the backend accepts and writes it in lower case with colons', () => {
for (const text of ['00:00:5E:00:53:07', '00-00-5e-00-53-07', '0000.5e00.5307', '00005E005307']) expect(macLiteral(text)).toBe('00:00:5e:00:53:07');
for (const text of ['', '00:00:5e-00:53:07', '00:00:5e:00:53', '0000.5e00.530g', '10.0.0.7']) expect(macLiteral(text)).toBeUndefined();
});
it('names every operation status, queued included, and shows an unknown one as sent', () => {
const t = (key: Parameters<typeof translate>[1], params?: Parameters<typeof translate>[2]) => translate('en', key, params);
const summary = (status: string) => eventSummary({event: 'operation.updated', data: {resource_id: 'op-1', status}} as unknown as ApiEvent, t).params?.status;
expect(summary('queued')).toBe('Queued');
expect(summary('running')).toBe('Running');
expect(summary('paused')).toBe('paused');
});
it('lists every log level once, least severe first as the contract orders them', () => {
expect(logLevels).toEqual(['trace', 'debug', 'info', 'warn', 'error']);
expect([...logLevels].sort()).toEqual(Object.keys(logLevelLabels).sort());
});
it('lists every labelled event kind', () => {
expect(eventKinds).toEqual(Object.keys(eventKindLabels));
expect(eventKinds).toEqual(['stream.ready', 'runtime.updated', 'flow.updated', 'flow.gap', 'operation.updated', 'generation.changed']);
});
it.each([
[undefined, [], false],
[[], undefined, false],
[[], [{protocol: 'direct'}], true],
[[{kind: 'inline'}], [{protocol: 'direct'}], true],
[[{kind: 'subscription'}], [], false],
[[{kind: 'file'}], [{protocol: 'direct'}, {protocol: 'block'}], false],
[[], [{protocol: 'direct'}, {protocol: 'vless'}], false]
] as const)('detects node sources after both inventories load: %j, %j', (providers, nodes, expected) => {
expect(noNodeSources(providers, nodes)).toBe(expected);
});
it("keeps a connection row's identity across snapshots that re-read it unchanged", () => {
const tcp = {id: 'a'} as Connection;
const udp = {id: 'b'} as Connection;
const first = connectionRows({tcp: [tcp], udp: [udp]} as ConnectionList);
const next = connectionRows({tcp: [tcp, {id: 'c'} as Connection], udp: [udp]} as ConnectionList);
expect(first.map(row => row.network)).toEqual(['tcp', 'udp']);
expect(next[0]).toBe(first[0]);
expect(next[2]).toBe(first[1]);
expect(next[1]).not.toBe(first[1]);
});