Add Gateway traffic totals and dashboard chart
Build and Deploy Gateway / build-and-push (push) Successful in 14s
Build and Deploy Gateway / deploy (push) Successful in 6s

This commit is contained in:
2026-08-08 00:23:55 +03:00
parent 39f3467f9b
commit 4c61a04dc7
10 changed files with 815 additions and 271 deletions
+75 -3
View File
@@ -196,6 +196,15 @@ test('device traffic totals persist exact deltas across polls and process epochs
error: null,
proxy: { lastObservedAt: observedAt, error: null },
});
assert.deepEqual(snapshot.traffic, {
gatewayBytes: '9007199254741093',
proxyBytes: '3000',
totalBytes: '9007199254744093',
gatewayObservedAt: observedAt,
proxyObservedAt: observedAt,
observedAt,
history: [],
});
snapshot = await service.refresh();
assert.equal(snapshot.devices[0].uploadBytes, '9007199254740993');
@@ -216,6 +225,8 @@ test('device traffic totals persist exact deltas across polls and process epochs
assert.equal(snapshot.devices[0].downloadBytes, '150');
assert.equal(snapshot.devices[0].proxyUploadBytes, '1010');
assert.equal(snapshot.devices[0].proxyDownloadBytes, '2050');
assert.equal(snapshot.traffic.gatewayBytes, '9007199254741145');
assert.equal(snapshot.traffic.proxyBytes, '3060');
service = createService();
snapshot = await service.refresh();
@@ -239,6 +250,7 @@ test('device traffic totals persist exact deltas across polls and process epochs
assert.equal(snapshot.devices[0].downloadBytes, '170');
assert.equal(snapshot.devices[0].proxyUploadBytes, '1013');
assert.equal(snapshot.devices[0].proxyDownloadBytes, '2054');
assert.equal(snapshot.traffic.totalBytes, '9007199254744242');
traffic = {
...traffic,
@@ -250,6 +262,7 @@ test('device traffic totals persist exact deltas across polls and process epochs
traffic = {
...traffic,
observedAt: '2026-08-07T12:00:15.000Z',
devices: [{
...traffic.devices[0],
uploadBytes: '12',
@@ -265,12 +278,17 @@ test('device traffic totals persist exact deltas across polls and process epochs
assert.equal(snapshot.devices[0].proxyDownloadBytes, '2054');
assert.equal(snapshot.source.traffic.error, null);
assert.match(snapshot.source.traffic.proxy.error, /уменьшился/);
assert.equal(snapshot.traffic.proxyBytes, '3067');
assert.equal(snapshot.traffic.gatewayObservedAt, '2026-08-07T12:00:15.000Z');
assert.equal(snapshot.traffic.proxyObservedAt, observedAt);
assert.equal(snapshot.traffic.observedAt, observedAt);
trafficError = new Error('traffic unavailable');
snapshot = await service.refresh();
assert.equal(snapshot.devices[0].uploadBytes, '9007199254741007');
assert.equal(snapshot.source.traffic.lastObservedAt, observedAt);
assert.equal(snapshot.source.traffic.lastObservedAt, '2026-08-07T12:00:15.000Z');
assert.equal(snapshot.source.traffic.error, 'traffic unavailable');
assert.equal(snapshot.traffic.totalBytes, '9007199254744249');
});
test('device traffic history stays in bounded service memory and survives client snapshots', async (t) => {
@@ -313,9 +331,55 @@ test('device traffic history stays in bounded service memory and survives client
gatewayBytes: '30',
proxyBytes: '5',
}]);
assert.deepEqual(snapshot.traffic.history, [{
observedAt,
gatewayBytes: '30',
proxyBytes: '5',
}]);
assert.deepEqual(service.snapshot().devices[0].trafficHistory, snapshot.devices[0].trafficHistory);
assert.doesNotMatch(fs.readFileSync(filePath, 'utf8'), /trafficHistory/);
assert.deepEqual(createService().snapshot().devices[0].trafficHistory, []);
assert.deepEqual(createService().snapshot().traffic.history, []);
});
test('global traffic stays monotonic when a device expires and returns in the same epoch', async (t) => {
const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'harbor-global-traffic-retention-'));
t.after(() => fs.rmSync(directory, { recursive: true, force: true }));
const store = createJsonStore({
filePath: path.join(directory, 'devices.json'),
defaultValue: {},
migrate: migrateDeviceInventoryState,
});
const mac = '00:11:22:33:44:55';
let observedAt = '2026-07-01T12:00:00.000Z';
let present = true;
let uploadBytes = '100';
const service = createDeviceInventoryService({
store,
observe: () => ({
observedAt,
error: null,
observations: present
? [{ ip: '192.168.50.7', mac, interface: 'eth0', observedAt, active: true }]
: [],
}),
observeTraffic: () => ({
epoch: 'epoch-a', generation: 'rules-a', observedAt, source: { error: null },
devices: [{ mac, uploadBytes, downloadBytes: '0' }],
}),
});
assert.equal((await service.refresh()).traffic.totalBytes, '100');
present = false;
observedAt = '2026-08-07T12:00:00.000Z';
let snapshot = await service.refresh();
assert.equal(snapshot.devices.length, 0);
assert.equal(snapshot.traffic.totalBytes, '100');
present = true;
snapshot = await service.refresh();
assert.equal(snapshot.traffic.totalBytes, '100');
uploadBytes = '110';
assert.equal((await service.refresh()).traffic.totalBytes, '110');
});
test('legacy dataplane samples preserve saved proxy totals while Gateway totals keep advancing', async (t) => {
@@ -462,7 +526,7 @@ test('device policy is independent from pinning, persists, and keeps the last ap
assert.equal(snapshot.devices[0].desiredPolicy, 'direct');
assert.equal(snapshot.devices[0].appliedPolicy, 'direct');
assert.equal(snapshot.devices[0].policyStatus, 'applied');
assert.equal(store.read().schemaVersion, 2);
assert.equal(store.read().schemaVersion, DEVICE_INVENTORY_SCHEMA_VERSION);
assert.equal(store.read().policy.schemaVersion, 1);
service = createService();
@@ -585,7 +649,7 @@ test('device inventory backs up and normalizes a malformed additive policy check
});
const migrated = store.read();
assert.equal(migrated.schemaVersion, 2);
assert.equal(migrated.schemaVersion, DEVICE_INVENTORY_SCHEMA_VERSION);
assert.equal(migrated.policy.schemaVersion, 1);
assert.equal(migrated.policy.dataplaneEpoch, null);
assert.deepEqual(migrated.policy.byMac, {});
@@ -666,6 +730,12 @@ test('device inventory backs up malformed v2 traffic and re-baselines without do
new Set(migrated.traffic.rebaselineMacs),
new Set([firstMac, secondMac, missingBaselineMac, missingTotalMac, expiredMac]),
);
assert.equal(migrated.traffic.global.gateway.uploadBytes, '1300');
assert.equal(migrated.traffic.global.gateway.downloadBytes, '1500');
assert.deepEqual(
new Set(migrated.traffic.global.gateway.rebaselineMacs),
new Set([firstMac, secondMac, missingBaselineMac, missingTotalMac, expiredMac]),
);
let counters = [
{ mac: firstMac, uploadBytes: '200', downloadBytes: '300' },
@@ -703,6 +773,7 @@ test('device inventory backs up malformed v2 traffic and re-baselines without do
assert.equal(byMac.get(missingBaselineMac).uploadBytes, '800');
assert.equal(byMac.get(missingTotalMac).uploadBytes, '0');
assert.equal(byMac.has(expiredMac), false);
assert.equal(snapshot.traffic.totalBytes, '2800');
assert.deepEqual(store.read().traffic.rebaselineMacs, []);
assert.equal(snapshot.source.traffic.error, null);
counters = [
@@ -721,6 +792,7 @@ test('device inventory backs up malformed v2 traffic and re-baselines without do
assert.equal(byMac.get(missingBaselineMac).downloadBytes, '905');
assert.equal(byMac.get(missingTotalMac).uploadBytes, '20');
assert.equal(byMac.get(missingTotalMac).downloadBytes, '20');
assert.equal(snapshot.traffic.totalBytes, '2945');
});
test('malformed proxy totals are backed up and an expired recovery marker is cleared', async (t) => {
+44 -15
View File
@@ -16,14 +16,19 @@ import {
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..');
const overview = fs.readFileSync(path.join(root, 'src/web/components/ClientOverviewPage.jsx'), 'utf8');
const panel = fs.readFileSync(path.join(root, 'src/web/components/DevicesPanel.jsx'), 'utf8');
const chart = fs.readFileSync(path.join(root, 'src/web/components/TrafficChart.jsx'), 'utf8');
const api = fs.readFileSync(path.join(root, 'src/web/api.js'), 'utf8');
const server = fs.readFileSync(path.join(root, 'src/server/index.js'), 'utf8');
const styles = fs.readFileSync(path.join(root, 'src/web/styles.css'), 'utf8');
test('Gateway device inventory uses the existing accessible responsive drawer', () => {
assert.match(overview, /isGateway && <button[\s\S]*client-devices-toggle/);
assert.match(panel, /api\.devices\.list\(\)/);
assert.match(panel, /api\.devices\.refresh\(\)/);
assert.match(overview, /api\.devices\.list\(\)/);
assert.match(overview, /api\.devices\.refresh\(\)/);
assert.match(overview, /DEVICE_AUTO_REFRESH_MS = 15_000/);
assert.match(overview, /setDeviceSnapshot\(\(current\) => !current \|\| next\.revision > current\.revision/);
assert.match(overview, /snapshot=\{deviceSnapshot\}[\s\S]*onSnapshot=\{setDeviceSnapshot\}/);
assert.doesNotMatch(panel, /AUTO_REFRESH_MS|const \[snapshot, setSnapshot\]|setTimeout\(\(\) => load\(true\),/);
assert.match(panel, /api\.devices\.update\(device\.id, patch, snapshot\.revision\)/);
assert.match(panel, /requestError\.code !== 'STATE_CONFLICT'[\s\S]*api\.devices\.list\(\)[\s\S]*Object\.keys\(patch\)\.some\(\(key\) => latestDevice\[key\] !== device\[key\]\)[\s\S]*api\.devices\.update\(device\.id, patch, latest\.revision\)/);
assert.match(panel, /deviceNodes\.current\.get\(id\)\?\.animate/);
@@ -75,21 +80,21 @@ test('Gateway device inventory uses the existing accessible responsive drawer',
assert.match(panel, /TrafficChart[\s\S]*samples=\{device\.trafficHistory \|\| \[\]\}[\s\S]*scale=\{trafficScale\}[\s\S]*capacity=\{snapshot\.trafficHistoryCapacity/);
assert.doesNotMatch(panel, /setTrafficHistory|TRAFFIC_HISTORY_LIMIT/);
assert.match(panel, /aria-pressed=\{trafficScale === 'linear'\}[\s\S]*aria-pressed=\{trafficScale === 'log'\}/);
assert.match(panel, /previousScale\.current !== scale[\s\S]*attributeName="d"[\s\S]*dur="520ms"/);
assert.match(panel, /function smoothTrafficPath[\s\S]*const midX = \(previous\.x \+ point\.x\) \/ 2[\s\S]* C /);
assert.match(panel, /TRAFFIC_CHART_HEADROOM = 10[\s\S]*trafficChartY = \(ratio\) => 100 - ratio \* \(100 - TRAFFIC_CHART_HEADROOM\)/);
assert.match(panel, /gatewayY: trafficChartY\(trafficScaleRatio\(gateway, max, scale\)\)[\s\S]*proxyY: trafficChartY\(trafficScaleRatio\(proxy, max, scale\)\)/);
assert.match(panel, /client-device-traffic-grid[\s\S]*y1=\{TRAFFIC_CHART_HEADROOM\}[\s\S]*y1=\{\(100 \+ TRAFFIC_CHART_HEADROOM\) \/ 2\}/);
assert.match(panel, /client-device-traffic-cursor[\s\S]*y1=\{TRAFFIC_CHART_HEADROOM\} y2="100"/);
assert.match(chart, /previousScale\.current !== scale[\s\S]*attributeName="d"[\s\S]*dur="520ms"/);
assert.match(chart, /function smoothTrafficPath[\s\S]*const midX = \(previous\.x \+ point\.x\) \/ 2[\s\S]* C /);
assert.match(chart, /TRAFFIC_CHART_HEADROOM = 10[\s\S]*trafficChartY = \(ratio\) => 100 - ratio \* \(100 - TRAFFIC_CHART_HEADROOM\)/);
assert.match(chart, /gatewayY: trafficChartY\(trafficScaleRatio\(gateway, max, scale\)\)[\s\S]*proxyY: trafficChartY\(trafficScaleRatio\(proxy, max, scale\)\)/);
assert.match(chart, /client-device-traffic-grid[\s\S]*y1=\{TRAFFIC_CHART_HEADROOM\}[\s\S]*y1=\{\(100 \+ TRAFFIC_CHART_HEADROOM\) \/ 2\}/);
assert.match(chart, /client-device-traffic-cursor[\s\S]*y1=\{TRAFFIC_CHART_HEADROOM\} y2="100"/);
assert.doesNotMatch(panel, /key=\{latest\}/);
assert.match(panel, /createPortal\([\s\S]*client-device-traffic-point-tooltip[\s\S]*document\.body/);
assert.match(panel, /onPointerMove=\{trackPointer\}/);
assert.match(panel, /pinned && max > 0n && <span className="client-device-traffic-axis"[\s\S]*is-max[\s\S]*is-mid[\s\S]*is-zero/);
assert.match(panel, /client-device-traffic-grid[\s\S]*path className="is-gateway"[\s\S]*path className="is-proxy"/);
assert.match(panel, /client-device-traffic-cursor[\s\S]*className="is-point is-gateway"[\s\S]*className="is-point is-proxy"/);
assert.match(chart, /createPortal\([\s\S]*client-device-traffic-point-tooltip[\s\S]*document\.body/);
assert.match(chart, /onPointerMove=\{trackPointer\}/);
assert.match(chart, /pinned && max > 0n && <span className="client-device-traffic-axis"[\s\S]*is-max[\s\S]*is-mid[\s\S]*is-zero/);
assert.match(chart, /client-device-traffic-grid[\s\S]*path className="is-gateway"[\s\S]*path className="is-proxy"/);
assert.match(chart, /client-device-traffic-cursor[\s\S]*className="is-point is-gateway"[\s\S]*className="is-point is-proxy"/);
assert.match(panel, /routeLabel=\{device\.appliedPolicy === 'direct' \? 'Напрямую' : 'Gateway'\}/);
assert.match(panel, /\{hovered\.proxy > 0n && <span className="is-proxy">Proxy \{formatByteString\(hovered\.proxy\)\}<\/span>\}/);
assert.match(panel, /<time dateTime=\{samples\[0\]\.observedAt\}>[\s\S]*<span>15 с<\/span>/);
assert.match(chart, /\{hovered\.proxy > 0n && <span className="is-proxy">Proxy \{formatByteString\(hovered\.proxy\)\}<\/span>\}/);
assert.match(chart, /<time dateTime=\{samples\[0\]\.observedAt\}>[\s\S]*<span>15 с<\/span>/);
assert.match(panel, /positiveByteDelta\(previous\.gateway, gateway\)[\s\S]*positiveByteDelta\(previous\.proxy, proxy\)/);
assert.match(panel, /setTimeout\(\(\) => setTrafficDeltas\(\{\}\), TRAFFIC_DELTA_MS\)/);
assert.doesNotMatch(panel, /client-device-traffic client-tooltip-anchor|<Tooltip>\{trafficLabel\}<\/Tooltip>/);
@@ -160,6 +165,30 @@ test('Gateway device inventory uses the existing accessible responsive drawer',
assert.match(styles, /\.harbor-versions \{[\s\S]*z-index: 40/);
});
test('Gateway Home reuses the canonical device snapshot for applied route and global traffic', () => {
assert.match(overview, /const appliedServerId = state\?\.selection\?\.appliedServerId \|\| ''/);
assert.match(overview, /appliedServer\?\.label \|\| 'VPN-сервер не используется'/);
assert.match(overview, /selectedServerId !== appliedServerId[\s\S]*Переключаем на \{desiredServer\.label\}/);
assert.match(overview, /formatByteString\(globalTraffic\?\.totalBytes \|\| '0'\)/);
assert.match(overview, /samples=\{globalTraffic\?\.history \|\| \[\]\}[\s\S]*capacity=\{deviceSnapshot\?\.trafficHistoryCapacity \|\| 120\}[\s\S]*routeLabel="Gateway"/);
assert.doesNotMatch(overview, /<TrafficChart[\s\S]{0,240}scale=/);
assert.match(overview, /deviceStatus === 'error' \? deviceError : null/);
assert.match(overview, /if \(!isGateway && \(!connected \|\| !state\?\.singboxStartedAt\)\) return undefined/);
assert.match(overview, /trafficSourceError[\s\S]*Трафик не обновляется · последние данные/);
assert.match(overview, /client-subscription-drawer\$\{subscriptionOpen \? ' is-open' : ''\}/);
assert.match(overview, /const confirmingDeleteRef = useRef\(confirmingDelete\)[\s\S]*if \(confirmingDeleteRef\.current\) return/);
assert.match(overview, /onClick=\{\(\) => setConfirmingDelete\(true\)\}[\s\S]*open=\{confirmingDelete\}[\s\S]*onCancel=\{\(\) => setConfirmingDelete\(false\)\}/);
assert.match(overview, /aria-label=\{isGateway[\s\S]*Остановить Harbor Connect[\s\S]*Запустить Harbor Connect/);
assert.match(overview, /className="client-power-control client-tooltip-anchor"[\s\S]*aria-describedby=\{powerUnavailable \? 'gateway-power-unavailable'[\s\S]*Сначала добавьте подписку и выберите сервер/);
assert.match(overview, /const powerButton = <button[\s\S]*className="client-power"[\s\S]*\{isGateway \? <span[\s\S]*<\/span> : powerButton\}/);
assert.match(overview, /isGateway && <DevicesPanel[\s\S]*snapshot=\{deviceSnapshot\}/);
assert.doesNotMatch(panel, /const \[snapshot, setSnapshot\]|setTimeout\(\(\) => load\(true\),/);
});
test('traffic chart scale compares Gateway and Proxy before choosing the maximum', () => {
assert.match(chart, /function trafficSeriesMax[\s\S]*proxy > gateway \? proxy : gateway[\s\S]*proxy > largest \? proxy : largest/);
});
test('device last-seen copy is compact with precise accessible and relative forms', () => {
const lastSeen = new Date(2026, 7, 7, 13, 15);
const now = new Date(2026, 7, 7, 13, 27);
@@ -30,6 +30,10 @@ test('desktop layout keeps the power control on a symmetric center axis', () =>
assert.match(styles, /\.client-panel\.has-subscription \{[\s\S]*transform:\s*translateY\(-9vh\)/);
assert.match(styles, /\.client-panel\.has-subscription \.client-power-section \{[\s\S]*height:\s*var\(--client-work-height\);[\s\S]*padding-top:\s*var\(--client-power-top\)/);
assert.match(styles, /\.client-panel\.has-subscription \.client-form-content \{[\s\S]*padding-top:\s*var\(--client-power-top\)/);
assert.match(rule('.client-gateway-summary'), /grid-column:\s*1/);
assert.match(rule('.client-gateway-summary'), /justify-self:\s*end/);
assert.match(component, /client-panel\$\{showPower \? '' : ' is-setup'\}[\s\S]*is-gateway-home/);
assert.match(component, /const showPower = isGateway \|\| \(hasSubscription && Boolean\(selectedServerId\)\)/);
});
test('page reload plays one stable startup sequence', () => {
@@ -68,6 +72,9 @@ test('tablet and mobile regions use normal flow with viewport-safe widths', () =
assert.match(responsive, /grid-template-columns:\s*minmax\(0, 1fr\)/);
assert.match(responsive, /\.client-power-section,[\s\S]*\.client-form,[\s\S]*grid-column:\s*1/);
assert.match(responsive, /\.client-gateway-summary/);
assert.match(responsive, /\.client-power-section \{[\s\S]*order:\s*1/);
assert.match(responsive, /\.client-gateway-summary \{[\s\S]*order:\s*2/);
assert.match(responsive, /width:\s*min\(100%, 380px\)/);
assert.match(responsive, /max-height:\s*none/);
assert.match(responsive, /overflow-y:\s*visible/);
@@ -81,6 +88,7 @@ test('tablet and mobile regions use normal flow with viewport-safe widths', () =
assert.match(styles, /\.client-instructions\s*\{[\s\S]*width:\s*min\(470px, 100vw\)/);
assert.match(styles, /\.client-local-rules\s*\{[\s\S]*width:\s*min\(480px, 100vw\)/);
assert.match(styles, /\.client-instructions\.client-diagnostics\s*\{[\s\S]*width:\s*min\(580px, 100vw\)/);
assert.match(styles, /\.client-subscription-drawer\s*\{[\s\S]*width:\s*min\(480px, 100vw\)/);
assert.match(styles, /\.client-confirmation-dialog\s*\{[\s\S]*width:\s*min\(430px, calc\(100vw - 48px\)\)/);
for (const viewport of [320, 390, 768]) {
@@ -100,6 +108,8 @@ test('secondary menus share one right rail and both drawers open from the right'
const zIndex = (selector) => Number(/z-index:\s*(\d+)/.exec(rule(selector))?.[1]);
assert.match(component, /<nav className="client-secondary-menu" aria-label="Дополнительные меню">/);
assert.match(component, /client-subscription-toggle[\s\S]*client-instructions-toggle[\s\S]*client-devices-toggle/);
assert.match(component, /aria-controls="client-subscription-drawer"/);
assert.match(component, /client-instructions-toggle[\s\S]*client-local-rules-toggle/);
assert.match(component, /client-instructions-toggle[\s\S]*client-devices-toggle[\s\S]*client-diagnostics-toggle[\s\S]*client-local-rules-toggle/);
assert.match(component, /client-diagnostics-toggle/);
@@ -132,6 +142,8 @@ test('secondary menus share one right rail and both drawers open from the right'
assert.match(rule('.client-local-rules'), /width:\s*min\(480px, 100vw\)/);
assert.match(component, /className={`client-drawer client-instructions/);
assert.match(component, /className={`client-drawer client-local-rules/);
assert.match(component, /client-drawer client-subscription-drawer/);
assert.match(component, /setSubscriptionOpen\(false\)[\s\S]*setDevicesOpen\(false\)[\s\S]*setDiagnosticsOpen\(false\)/);
});
test('connectivity diagnostics render stable compact tables before the first run', () => {