forked from mtusi2026/mtusi2026lab5
54 lines
12 KiB
JavaScript
54 lines
12 KiB
JavaScript
let token=null, epoch=0, panel, timer, abort, samples=[];
|
||
const $=selector=>panel.querySelector(selector);
|
||
const labels={queued:'В очереди',processing:'Обработка',ready:'Готово',failed:'Ошибка'};
|
||
const eventLabels={accepted:'Файл принят',published:'В очереди RabbitMQ',processing:'Обработчик начал работу',ready:'Результаты сохранены',retry_scheduled:'Назначен повтор',failed:'Ошибка обработки',lease_recovered:'Восстановлено после остановки',operator_replay:'Повторный запуск'};
|
||
function node(tag,text,cls){const e=document.createElement(tag);if(text!==undefined)e.textContent=text;if(cls)e.className=cls;return e;}
|
||
export async function operationsSession(value){
|
||
token=value;epoch++;panel?.close();clearTimeout(timer);abort?.abort();samples=[];
|
||
const button=document.getElementById('open-operations');button.hidden=true;
|
||
const version=epoch;if(!value)return;
|
||
try {const response=await fetch('/api/ui/operator',{headers:{Authorization:'Bearer '+value},cache:'no-store',signal:AbortSignal.timeout(8000)});const data=await response.json();if(version===epoch)button.hidden=!response.ok||!data.enabled;}catch{}
|
||
}
|
||
function init(){
|
||
panel=node('dialog',undefined,'ops-panel');panel.setAttribute('aria-label','Система мессенджера');
|
||
panel.innerHTML=`<div class="ops-shell"><header class="ops-header"><a href="#" class="ops-brand">n1k0der<span> / system</span></a><span class="ops-live">● Обновление каждые 3 с</span><button class="ops-close" type="button">Закрыть ×</button></header>
|
||
<main><section class="ops-intro"><div><span class="ops-eyebrow">Внутри мессенджера</span><h1>Каждое сообщение.<br><span>Всё на своих местах.</span></h1><p>От запроса в браузере до обработанного изображения.</p></div><svg class="ops-art" viewBox="0 0 240 160" aria-hidden="true"><path d="M35 80h170M120 25v110" stroke="#ffe135" stroke-opacity=".15"/><g fill="#262626" stroke="#ffe135" stroke-width="2"><rect x="18" y="54" width="50" height="50" rx="15"/><rect x="95" y="12" width="50" height="50" rx="15"/><rect x="95" y="96" width="50" height="50" rx="15"/><rect x="172" y="54" width="50" height="50" rx="15"/></g><path d="m35 78 6 6 12-12m57-34h20m-20 84h20m64-44h20" fill="none" stroke="#ffe135" stroke-width="3"/><circle class="ops-orbit" cx="120" cy="80" r="6" fill="#ffe135"/></svg></section>
|
||
<p class="ops-notice" role="status"></p><section class="ops-metrics" aria-label="Задания"></section>
|
||
<section class="ops-box ops-architecture"><div class="ops-section-head"><div><span class="ops-eyebrow">Архитектура</span><h2>Путь запроса</h2></div><span class="ops-checked">Проверяем…</span></div><div class="ops-flow"><div class="ops-node"><span>01 / клиент</span><strong>Браузер</strong><small>Сообщения и изображения</small></div><div class="ops-arrow">→</div><div class="ops-node" data-service="proxy"><span>02 / вход</span><strong>HAProxy</strong><small>Запрос прошёл через этот адрес</small></div><div class="ops-arrow">→</div><div class="ops-api-nodes"></div></div><div class="ops-services"></div><div class="ops-pipeline"><span>Загрузка</span><i>→</i><span>PostgreSQL + outbox</span><i>→</i><span>Dispatcher</span><i>→</i><span>RabbitMQ</span><i>→</i><span>Worker</span><i>→</i><span>S3: готовые файлы</span></div><p class="ops-footnote">API, worker и dispatcher: heartbeat. Redis, S3 и RabbitMQ: проверка соединения. HAProxy: доступность текущего адреса, без отдельной проверки процесса.</p></section>
|
||
<section class="ops-charts"><article class="ops-box"><div class="ops-section-head"><div><span class="ops-eyebrow">Очередь</span><h2>Задания в работе</h2></div><strong class="ops-queue-value">0</strong></div><div class="ops-queue-chart"></div><p class="ops-footnote">Ожидающие + выполняющиеся задания в PostgreSQL. Последние 60 замеров открытой панели.</p></article><article class="ops-box"><div class="ops-section-head"><div><span class="ops-eyebrow">Отклик</span><h2>Время проверки системы</h2></div><strong class="ops-latency-value">…</strong></div><div class="ops-latency-chart"></div><p class="ops-footnote">Время запроса этой панели, включая проверки зависимостей. Это не загрузка CPU.</p></article></section>
|
||
<section class="ops-bottom"><article class="ops-box"><div class="ops-section-head"><div><span class="ops-eyebrow">Обработка изображений</span><h2>Последние задания</h2></div><button class="ops-refresh" type="button">Обновить</button></div><div class="ops-jobs"></div></article><article class="ops-box"><span class="ops-eyebrow">События</span><h2>Что происходит</h2><ol class="ops-events"></ol></article></section></main><footer>Данные сервера · <span class="ops-cycle"></span></footer></div>`;
|
||
document.body.append(panel);$('.ops-close').onclick=()=>panel.close();$('.ops-brand').onclick=e=>e.preventDefault();$('.ops-refresh').onclick=()=>{clearTimeout(timer);void refresh();};
|
||
panel.addEventListener('close',()=>{clearTimeout(timer);abort?.abort();});
|
||
}
|
||
function chart(target,key,color){
|
||
const host=$(target);host.replaceChildren();const ns='http://www.w3.org/2000/svg';const svg=document.createElementNS(ns,'svg');svg.setAttribute('viewBox','0 0 600 150');svg.setAttribute('role','img');svg.setAttribute('aria-label',samples.length<2?'Ожидаем второй замер':'График последних '+samples.length+' замеров');
|
||
const values=samples.map(s=>s[key]),max=Math.max(1,...values);for(let i=0;i<4;i++){const line=document.createElementNS(ns,'path');line.setAttribute('d',`M0 ${10+i*40}H600`);line.setAttribute('stroke','#ffffff10');svg.append(line);}
|
||
const path=document.createElementNS(ns,'polyline');path.setAttribute('points',values.map((v,i)=>`${i*600/Math.max(1,values.length-1)},${135-v/max*120}`).join(' '));path.setAttribute('stroke',color);path.setAttribute('stroke-width','3');path.setAttribute('fill','none');svg.append(path);host.append(svg);
|
||
const caption=node('div',undefined,'ops-chart-caption');caption.append(node('span',samples.length?new Date(samples[0].at).toLocaleTimeString():'…'),node('span','Макс. '+Math.round(Math.max(0,...values))),node('span',samples.length?new Date(samples.at(-1).at).toLocaleTimeString():'…'));host.append(caption);
|
||
}
|
||
function service(name,up,detail){const card=node('div',undefined,'ops-service');card.dataset.state=up?'up':'down';card.append(node('span',up?'● На связи':'● Нет свежего ответа'),node('strong',name),node('small',detail));return card;}
|
||
function stale(message){$('.ops-notice').textContent=message;panel.classList.add('is-stale');$('.ops-live').textContent='● Нет свежих данных';for(const item of panel.querySelectorAll('[data-state]'))item.dataset.state='unknown';}
|
||
async function refresh(){
|
||
if(!panel?.open||!token)return;if(document.hidden){timer=setTimeout(refresh,3000);return;}
|
||
if(abort&&!abort.signal.aborted)abort.abort();abort=new AbortController();const version=epoch,session=token,signal=abort.signal;const started=performance.now();
|
||
try {
|
||
const response=await fetch('/api/ui/operations',{headers:{Authorization:'Bearer '+session},cache:'no-store',signal:AbortSignal.any([signal,AbortSignal.timeout(10000)])});
|
||
if(!response.ok)throw new Error(response.status===404?'Нет доступа к управлению системой':response.status===401?'Войдите снова':'Сервер временно не отвечает');const data=await response.json();
|
||
if(version!==epoch||!panel.open||signal.aborted)return;
|
||
const elapsed=Math.round(performance.now()-started);samples.push({queue:data.counts.queued+data.counts.processing,latency:elapsed,at:Date.now()});if(samples.length>60)samples.shift();
|
||
panel.classList.remove('is-stale');$('.ops-live').textContent='● Данные обновлены';$('.ops-notice').textContent='';$('.ops-checked').textContent='Проверено '+new Date(data.checked_at).toLocaleTimeString();
|
||
$('.ops-metrics').replaceChildren(...Object.entries(labels).map(([key,label])=>{const card=node('article');card.dataset.kind=key;card.append(node('span',label),node('strong',String(data.counts[key])));return card;}));
|
||
const apis=$('.ops-api-nodes');apis.replaceChildren(...data.instances.filter(n=>n.ready).map(n=>service('API · '+n.id.slice(0,8),true,'Heartbeat · '+new Date(n.last_seen).toLocaleTimeString())));if(!apis.childNodes.length)apis.append(service('API',false,'Нет свежего heartbeat'));
|
||
const current=response.headers.get('X-Instance-Id');for(const card of apis.children)card.classList.toggle('served',card.textContent.includes(current?.slice(0,8)||'never'));
|
||
const s=data.services;$('.ops-services').replaceChildren(service('PostgreSQL',s.postgres,'Пользователи, чаты, задания'),service('Redis',s.redis,'Кэш и heartbeat API'),service('S3',s.s3,'Оригиналы и варианты'),service('RabbitMQ',s.broker,`Сообщений: ${data.broker_messages??'?'} · подписчиков: ${data.broker_consumers??'?'}`),service('Dispatcher',s.dispatcher,'Доставка outbox в очередь'),service('Worker',s.worker,'Обработка изображений'));
|
||
$('.ops-queue-value').textContent=String(samples.at(-1).queue);$('.ops-latency-value').textContent=elapsed+' мс';chart('.ops-queue-chart','queue','#ffe135');chart('.ops-latency-chart','latency','#a6cf9a');
|
||
$('.ops-cycle').textContent=`Outbox: ${data.pending_outbox} · Средний цикл за 15 мин: ${data.average_cycle_seconds===null?'нет завершённых заданий':data.average_cycle_seconds.toFixed(2)+' с'}`;
|
||
const jobs=$('.ops-jobs');jobs.replaceChildren();if(!data.jobs.length)jobs.append(node('p','Загрузите изображение в чат. Здесь появится его задание.','ops-empty'));
|
||
for(const job of data.jobs){const row=node('div',undefined,'ops-job');const info=node('div');info.append(node('strong',job.filename),node('small',`${labels[job.state]} · попыток ${job.attempts}${job.error_code?' · '+job.error_code:''}`));row.append(info);if(job.can_replay){const button=node('button','Повторить');button.type='button';button.onclick=()=>replay(job.attachment_id,button);row.append(button);}jobs.append(row);}
|
||
const list=$('.ops-events');list.replaceChildren();for(const event of data.events){const item=node('li');item.append(node('time',new Date(event.at).toLocaleTimeString()),node('strong',eventLabels[event.name]||event.name),node('span',event.filename));list.append(item);}if(!data.events.length)list.append(node('li','Событий пока нет'));
|
||
}catch(error){if(version===epoch&&panel.open&&!signal.aborted)stale(error.message);}finally{if(version===epoch&&panel?.open){clearTimeout(timer);timer=setTimeout(refresh,3000);}}
|
||
}
|
||
async function replay(id,button){button.disabled=true;button.textContent='Запускаем…';try{const response=await fetch(`/api/ui/operations/attachments/${id}/replay`,{method:'POST',headers:{Authorization:'Bearer '+token},signal:AbortSignal.timeout(10000)});const data=await response.json();if(!response.ok)throw new Error(data.error?.message||'Повтор недоступен');clearTimeout(timer);await refresh();}catch(error){$('.ops-notice').textContent=error.message;button.disabled=false;button.textContent='Повторить';}}
|
||
document.getElementById('open-operations').addEventListener('click',()=>{if(!panel)init();panel.showModal();void refresh();});
|
||
document.addEventListener('visibilitychange',()=>{if(!document.hidden&&panel?.open){clearTimeout(timer);void refresh();}});
|