diff --git a/REPORT.md b/REPORT.md index 4f8db26..869bee8 100644 --- a/REPORT.md +++ b/REPORT.md @@ -283,3 +283,23 @@ operations.css и operations.js. Добавлены 16 SVG на общей се В браузере проверены реальные состояния восьми карточек API/зависимостей. SVG разобраны XML-парсером, все новые asset URL отвечают 200. make check, make validate и публичный smoke-сценарий прошли после изменений. + +## Удобство и устойчивость интерфейса + +В чате добавлены копирование текста, вставка PNG/JPEG из буфера и перенос файла +мышью. Поиск чатов открывается сочетанием ⌘K/Ctrl+K, результаты можно очистить +кнопкой или Escape. В панели задания фильтруются среди последних 30 записей; +состояние кнопки повтора не перерисовывается без изменения данных. При смене +пользователя содержимое панели удаляется из страницы. Анимации уважают настройку +уменьшения движения. + +Формы входа и регистрации ожидают загрузки скриптов; их резервный метод POST не +помещает поля в адрес страницы. HAProxy проверяет API с тайм-аутом 2 секунды и +интервалом 1 секунда. Docker healthcheck RabbitMQ проверяет TCP-порт 5672 без +запуска Erlang-процесса на каждый опрос; проверка панели дополнительно выполняет +AMQP-запрос. Лимит RabbitMQ по умолчанию 512 МиБ, настраивается BROKER_MEMORY. +При прежней проверке регулярные Erlang-процессы исчерпывали лимит при запуске. + +Результаты повторных проверок и переключения API: evidence/ui-reliability.txt. +Предыдущие измерения нагрузки относятся к настройкам и версии, указанным в их +исходных результатах; повторный эксперимент для новых параметров не проводился. diff --git a/compose.yaml b/compose.yaml index a31dfad..0e417f0 100644 --- a/compose.yaml +++ b/compose.yaml @@ -141,10 +141,10 @@ services: volumes: - broker_data:/var/lib/rabbitmq cpus: 0.5 - mem_limit: 384m + mem_limit: ${BROKER_MEMORY:-512m} restart: unless-stopped healthcheck: - test: ["CMD", "rabbitmq-diagnostics", "-q", "ping"] + test: ["CMD-SHELL", "bash -c 'exec 3<>/dev/tcp/127.0.0.1/5672'"] interval: 3s timeout: 5s retries: 30 diff --git a/evidence/ui-reliability.txt b/evidence/ui-reliability.txt new file mode 100644 index 0000000..6c11808 --- /dev/null +++ b/evidence/ui-reliability.txt @@ -0,0 +1,19 @@ +Проверка после изменений интерфейса и настроек сервисов: + +make check: PASS +make validate: PASS +make test: PASS +student-tests/chunked_login.py: PASS +student-tests/processing_panel.py: PASS +make operations-test: PASS (повторное задание обработано worker) +make test-failover ACTION_SCRIPT=scripts/stop-one.sh: + observed_instances_before: 2 + successful_writes: 109 + failed_attempts: 1 + first_recovery_seconds: 2.756 + PASS: подтверждённые данные и сессия сохранены. + +Первый запуск failover остановился до сценария из-за тайм-аута регистрации, +пока RabbitMQ запускался. После готовности сервисов повторный запуск прошёл. +В браузере проверены поиск, копирование сообщения, вставка PNG, превью и удаление +черновика, фильтр ошибок и отображение состояний сервисов. diff --git a/infra/haproxy.cfg b/infra/haproxy.cfg index 752b053..24823f9 100644 --- a/infra/haproxy.cfg +++ b/infra/haproxy.cfg @@ -5,8 +5,8 @@ global defaults mode http - timeout connect 500ms - timeout check 500ms + timeout connect 2s + timeout check 2s timeout client 15s timeout server 12s timeout http-request 5s @@ -36,5 +36,5 @@ backend messenger option httpchk http-check send meth GET uri /health/ready ver HTTP/1.1 hdr Host localhost http-check expect status 200 - default-server check inter 500ms fastinter 250ms downinter 500ms fall 2 rise 2 + default-server check inter 1s fastinter 500ms downinter 1s fall 2 rise 2 server-template api 1-8 api:8080 resolvers docker resolve-prefer ipv4 init-addr none diff --git a/src/Messenger.Api/wwwroot/app.js b/src/Messenger.Api/wwwroot/app.js index d48fad9..e0dc161 100644 --- a/src/Messenger.Api/wwwroot/app.js +++ b/src/Messenger.Api/wwwroot/app.js @@ -94,6 +94,9 @@ function selectAuthTab(register) { function setFormBusy(form, busy) { form.querySelectorAll("input, textarea, button").forEach(element => { element.disabled = busy; }); + form.setAttribute("aria-busy", String(busy)); + const label = form.querySelector(".button-label"); + if (label) label.textContent = busy ? label.dataset.busy : label.dataset.label; } function persistSession(session) { @@ -131,6 +134,7 @@ async function enterSession(session) { $("profile-username").textContent = "@" + session.user.username; paintAvatar($("profile-avatar"), session.user.id, session.user.display_name); $("chat-search").value = ""; + $("clear-chat-search").hidden = true; renderChats(); try { await loadChats(false, true); } catch (error) { if (state.session?.token === session.token) { $("welcome").hidden = true; $("workspace-error").hidden = false; } @@ -221,6 +225,9 @@ $("register-form").addEventListener("submit", async event => { } finally { setFormBusy(form, false); } }); +$("login-submit").disabled = false; +$("register-submit").disabled = false; + function memberCount(count) { const n = count % 100, d = count % 10; return count + " " + (n >= 11 && n <= 14 ? "участников" : d === 1 ? "участник" : d >= 2 && d <= 4 ? "участника" : "участников"); } function chatActivity(chat) { return chat.last_message?.created_at || chat.created_at; } function chatTime(value) { @@ -333,12 +340,29 @@ $("retry-messages").addEventListener("click", async () => { finally { button.disabled = false; } }); -$("chat-search").addEventListener("input", renderChats); +$("chat-search").addEventListener("input", () => { + $("clear-chat-search").hidden = !$("chat-search").value; + renderChats(); +}); +$("clear-chat-search").addEventListener("click", () => { + $("chat-search").value = ""; $("clear-chat-search").hidden = true; renderChats(); $("chat-search").focus(); +}); +$("chat-search").addEventListener("keydown", event => { + if (event.key === "Escape" && event.currentTarget.value) { event.stopPropagation(); $("clear-chat-search").click(); } +}); +document.addEventListener("keydown", event => { + if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === "k" && state.session && !document.querySelector("dialog[open]")) { + event.preventDefault(); + if (matchMedia("(max-width: 720px)").matches && $("app-screen").classList.contains("chat-open")) $("back-to-chats").click(); + $("chat-search").focus(); + } +}); +$("message-list").addEventListener("messagecopy", event => toast(event.detail.success ? "Текст скопирован" : "Не удалось скопировать текст", !event.detail.success)); $("refresh-chats").addEventListener("click", async () => { try { await loadChats(); } catch (error) { toast(error.message, true); } }); $("more-chats").addEventListener("click", async () => { try { await loadChats(true); } catch (error) { toast(error.message, true); } }); async function selectChat(chat) { - if (state.current?.id === chat.id) { $("app-screen").classList.add("chat-open"); return; } + if (state.current?.id === chat.id) { $("app-screen").classList.add("chat-open"); if(matchMedia("(min-width: 721px)").matches) $("message-input").focus({preventScroll:true}); return; } if (state.current) state.drafts.set(state.current.id, $("message-input").value); state.epoch++; reactions.clear(); reactionBusy.clear(); reactionVersion++; @@ -369,6 +393,7 @@ async function selectChat(chat) { $("older-messages").hidden = true; $("messages-loading").hidden = false; $("message-list").setAttribute("aria-busy", "true"); + if(matchMedia("(min-width: 721px)").matches) $("message-input").focus({preventScroll:true}); if (!matchMedia("(prefers-reduced-motion: reduce)").matches) $("conversation").animate([{ opacity: 0, transform: "translateY(5px)" }, { opacity: 1, transform: "none" }], { duration: 180, easing: "ease-out" }); try { await Promise.all([syncRecent(true), loadMembers(state.epoch, chat.id)]); } catch (error) { if (state.historyReady) toast(error.message, true); } @@ -583,7 +608,10 @@ $("new-chat-form").addEventListener("submit", async event => { else { const username=entry.replace(/^@/,'').toLowerCase(); if(!/^[a-z0-9_]{3,32}$/.test(username))throw new Error('Введите логин или полный ID участника.'); - const user=await request('/api/ui/users/'+encodeURIComponent(username));ids.push(user.id); + let user; + try { user=await request('/api/ui/users/'+encodeURIComponent(username)); } + catch(error) { if(error.status===404)throw new Error('Пользователь @'+username+' не найден.');throw error; } + ids.push(user.id); } } if(token!==state.session?.token)return; @@ -621,7 +649,11 @@ $("logout").addEventListener("click", async () => { catch (error) { if (error.status !== 401) toast(error.message, true); } finally { $("logout").disabled = false; } }); -$("back-to-chats").addEventListener("click", () => $("app-screen").classList.remove("chat-open")); +$("back-to-chats").addEventListener("click", () => { + $("app-screen").classList.remove("chat-open"); + const row=chatRows.get(state.current?.id)?.button; + if(row?.isConnected)row.focus({preventScroll:true}); +}); $("refresh-messages").addEventListener("click", async () => { try { await syncRecent(); } catch (error) { toast(error.message, true); } }); @@ -691,18 +723,21 @@ function renderAttachedDrafts() { } } $("pick-file").addEventListener("click",()=>$("image-file").click()); -$("image-file").addEventListener("change",async()=>{ - const file=$("image-file").files[0];$("image-file").value=""; +$("image-file").addEventListener("change",()=>{ + const file=$("image-file").files[0];$("image-file").value="";void attachImage(file); +}); +async function attachImage(file) { if(!file || !state.current || uploadBusy || state.sending) return; - if(file.size>10485760) {toast("Максимум 10 MiB",true);return;} + if(file.size>10485760) {toast("Максимум 10 МБ",true);return;} if(!["image/png","image/jpeg"].includes(file.type)) {toast("Выберите PNG или JPEG",true);return;} if((attachedDrafts.get(state.current.id)||[]).length>=10) {toast("Максимум 10 вложений",true);return;} const chat=state.current.id, session=state.session.token; - const draft={filename:file.name,previewUrl:URL.createObjectURL(file),id:null,removed:false}; + const filename=file.name && !/[\/\\\x00-\x1f]/.test(file.name) ? file.name : (file.type === "image/png" ? "image.png" : "image.jpg"); + const draft={filename,previewUrl:URL.createObjectURL(file),id:null,removed:false}; attachedDrafts.set(chat,[...(attachedDrafts.get(chat)||[]),draft]);renderAttachedDrafts(); uploadBusy=true;$("pick-file").disabled=true;updateComposer(); try { - const attachment=await request(`/api/v1/chats/${chat}/attachments?filename=${encodeURIComponent(file.name)}`,{method:"POST",raw:file,headers:{"Content-Type":file.type}}); + const attachment=await request(`/api/v1/chats/${chat}/attachments?filename=${encodeURIComponent(filename)}`,{method:"POST",raw:file,headers:{"Content-Type":file.type}}); if(state.session?.token!==session || draft.removed) return; Object.assign(draft,attachment);renderAttachedDrafts(); }catch(error){ @@ -713,4 +748,38 @@ $("image-file").addEventListener("change",async()=>{ if(state.session?.token===session) toast(error.message,true); } finally {uploadBusy=false;$("pick-file").disabled=state.sending;updateComposer();} +} + +const dropArea = $("conversation"); +let dragDepth = 0; +function resetDrag() { dragDepth = 0; dropArea.classList.remove("is-dragging-file"); } +for (const type of ["dragenter", "dragover"]) dropArea.addEventListener(type, event => { + if (!event.dataTransfer?.types.includes("Files") || !state.current || state.sending) return; + event.preventDefault(); + if (type === "dragenter") dragDepth++; + event.dataTransfer.dropEffect = "copy"; + dropArea.classList.add("is-dragging-file"); }); +dropArea.addEventListener("dragleave", event => { + if (!event.dataTransfer?.types.includes("Files")) return; + dragDepth = Math.max(0, dragDepth - 1); + if (!dragDepth) resetDrag(); +}); +dropArea.addEventListener("drop", event => { + if (!event.dataTransfer?.types.includes("Files")) return; + event.preventDefault(); resetDrag(); + if (uploadBusy || state.sending) { toast("Дождитесь завершения загрузки", true); return; } + const files = [...event.dataTransfer.files]; + if (files.length > 1) { toast("Добавляйте изображения по одному", true); return; } + void attachImage(files[0]); +}); +$("message-input").addEventListener("paste", event => { + const file = [...(event.clipboardData?.files || [])].find(item => item.type.startsWith("image/")); + if (!file) return; + event.preventDefault(); + if (uploadBusy || state.sending) { toast("Дождитесь завершения загрузки", true); return; } + void attachImage(file); +}); + +window.addEventListener("dragend", resetDrag); +window.addEventListener("drop", resetDrag); diff --git a/src/Messenger.Api/wwwroot/design.css b/src/Messenger.Api/wwwroot/design.css index 498d124..c59bdf1 100644 --- a/src/Messenger.Api/wwwroot/design.css +++ b/src/Messenger.Api/wwwroot/design.css @@ -107,3 +107,28 @@ dialog::backdrop {background:#10130db3;} @keyframes dialog-appear{from{opacity:0;transform:translateY(8px) scale(.985);}to{opacity:1;transform:none;}} @keyframes welcome-appear{from{opacity:0;transform:translateY(9px);}to{opacity:1;transform:none;}} @media(prefers-reduced-motion:reduce){.chat-row,.button,.icon-button,.processing-results a,.auth-switch button{transition:none;}.chat-row:hover{transform:none;}} +.search-field {position:relative;} +.search-field input[type=search]::-webkit-search-cancel-button {-webkit-appearance:none;} +.search-clear {display:grid;place-items:center;width:24px;height:24px;padding:0;border:0;border-radius:7px;background:#ffffff0b;color:#aeb8a3;font-size:18px;line-height:1;flex-shrink:0;} +.search-clear:hover {background:#ffe13518;color:#ffe135;} +.message {position:relative;} +.message-copy {position:absolute;right:-34px;bottom:2px;display:grid;place-items:center;width:28px;height:28px;border:1px solid #ffffff10;border-radius:8px;background:#2b2e27;color:#b2bca5;opacity:0;pointer-events:none;transition:opacity .18s,background .18s;} +.message-copy svg {width:15px;height:15px;fill:none;stroke:currentColor;stroke-width:1.7;stroke-linecap:round;stroke-linejoin:round;} +.message.mine .message-copy {right:auto;left:-34px;} +.message:hover .message-copy,.message:focus-within .message-copy {opacity:1;pointer-events:auto;} +.message-copy:hover {color:#ffe135;background:#353a2d;} +.conversation {position:relative;} +.conversation.is-dragging-file::after {content:'Отпустите изображение';position:absolute;z-index:6;inset:12px;display:grid;place-items:center;border:2px dashed #ffe13599;border-radius:16px;background:#20231def;color:#ffe135;font-size:16px;font-weight:550;pointer-events:none;} +@media(hover:none) {.message-copy {opacity:.8;pointer-events:auto;} .reaction-picker {opacity:.75;}} +@media(max-width:720px) {.message {max-width:calc(100% - 36px);}.message-copy {opacity:.8;pointer-events:auto;}} +@media(prefers-reduced-motion:reduce) {.message-copy {transition:none;}} +.auth-card .wide > .button-label {font-size:13px;line-height:1.4;} +.message-copy.is-copied {color:#ffe135;border-color:#ffe13550;background:#ffe1350d;} +@media(prefers-reduced-motion:no-preference) { + .messages-loading i {animation:message-loading 1.5s ease-in-out infinite alternate;} + .messages-loading i:nth-child(2) {animation-delay:.18s;} + .messages-loading i:nth-child(3) {animation-delay:.36s;} + .attachment-preview img {transition:opacity .28s ease;} + .draft-image {animation:dialog-appear .22s ease-out;} +} +@keyframes message-loading {from{opacity:.45}to{opacity:1}} diff --git a/src/Messenger.Api/wwwroot/index.html b/src/Messenger.Api/wwwroot/index.html index 48a61df..2aa5eed 100644 --- a/src/Messenger.Api/wwwroot/index.html +++ b/src/Messenger.Api/wwwroot/index.html @@ -109,10 +109,10 @@
Присоединяйтесь к разговору.
- +
@@ -125,7 +125,7 @@