diff --git a/VERSION b/VERSION index 8cbf02c..43b2961 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.0.12 +0.0.13 diff --git a/tests/metrics-ui.test.cjs b/tests/metrics-ui.test.cjs index 11b1a14..632c27c 100644 --- a/tests/metrics-ui.test.cjs +++ b/tests/metrics-ui.test.cjs @@ -39,6 +39,41 @@ function payload() { } const flush = () => new Promise(resolve => setImmediate(resolve)); +test('null response is a data error and preserves previous readings', async () => { + let data = null; + const ui = setup(async () => ({ ok: true, json: async () => data })); + await flush(); + assert.equal(ui.elements.get('.metrics-panel').dataset.state, 'error'); + assert.match(ui.elements.get('#metrics-note').textContent, /Некорректные данные/); + data = payload(); + await vm.runInContext('pollMetrics()', ui.context); + data = null; + await vm.runInContext('pollMetrics()', ui.context); + assert.equal(ui.elements.get('.metrics-panel').dataset.state, 'stale'); + assert.equal(ui.elements.get('#cpu-value').textContent, '15%'); + assert.match(ui.elements.get('#metrics-note').textContent, /Некорректные данные/); +}); + +test('invalid JSON is reported as a data error', async () => { + const ui = setup(async () => ({ ok: true, json: async () => { throw new SyntaxError('Invalid JSON'); } })); + await flush(); + assert.equal(ui.elements.get('.metrics-panel').dataset.state, 'error'); + assert.match(ui.elements.get('#metrics-note').textContent, /Некорректные данные/); +}); + +test('network and body transfer failures are reported as connection errors', async () => { + for (const fetch of [ + async () => { throw new TypeError('Failed to fetch'); }, + async () => ({ ok: true, json: async () => { throw new TypeError('Connection lost'); } }), + async () => ({ ok: true, json: async () => { throw new DOMException('Aborted', 'AbortError'); } }), + ]) { + const ui = setup(fetch); + await flush(); + assert.equal(ui.elements.get('.metrics-panel').dataset.state, 'error'); + assert.match(ui.elements.get('#metrics-note').textContent, /Нет связи/); + } +}); + test('live → stale → recovered preserves the last readings', async () => { let online = true; const ui = setup(async () => ({ ok: online, json: async () => online ? payload() : { error: 'metrics_unavailable' } })); diff --git a/web/app.js b/web/app.js index 6bf370a..d98f9bc 100644 --- a/web/app.js +++ b/web/app.js @@ -30,13 +30,26 @@ async function pollMetrics() { const controller = new AbortController(); const timeout = setTimeout(() => controller.abort(), 4000); try { - const response = await fetch('/api/metrics', { signal: controller.signal, cache: 'no-store' }); + let response; + try { + response = await fetch('/api/metrics', { signal: controller.signal, cache: 'no-store' }); + } catch { + throw new Error('Нет связи со сборщиком метрик.'); + } if (!response.ok) { let error; try { error = (await response.json()).error; } catch { /* Static-only hosting may return HTML. */ } throw new Error(error === 'metrics_not_configured' ? 'Сборщик метрик не настроен.' : 'Сборщик метрик недоступен.'); } - const data = await response.json(); + let data; + try { + data = await response.json(); + } catch (error) { + throw new Error(error.name === 'SyntaxError' ? 'Некорректные данные метрик.' : 'Нет связи со сборщиком метрик.'); + } + if (data === null || typeof data !== 'object' || Array.isArray(data)) { + throw new Error('Некорректные данные метрик.'); + } const sample = new Date(data.sampled_at); if (!Number.isFinite(sample.getTime()) || Date.now() - sample.getTime() > 20000 || sample.getTime() - Date.now() > 5000) { throw new Error('Свежий замер не получен.'); @@ -61,7 +74,7 @@ async function pollMetrics() { metricsState.textContent = 'Подключено'; metricsNote.textContent = `Последний замер: ${sample.toLocaleTimeString('ru-RU')}`; } catch (error) { - showMetricsError(error instanceof TypeError || error.name === 'AbortError' ? 'Нет связи со сборщиком метрик.' : error.message); + showMetricsError(error.message); } finally { clearTimeout(timeout); polling = false; diff --git a/web/index.html b/web/index.html index b48b42e..f9aba54 100644 --- a/web/index.html +++ b/web/index.html @@ -44,7 +44,7 @@
Метрики хоста · обновление каждые 5 секунд
+Метрики хоста · пауза между запросами — 5 секунд