feat(lab6): add observability and SLO burn-rate alerts

This commit is contained in:
2026-11-15 06:54:54 +03:00
parent 470d9d6f1e
commit 63c1f06b84
204 changed files with 25348 additions and 37 deletions
+163
View File
@@ -0,0 +1,163 @@
import type {
ApiErrorBody,
Chat,
CreateChatInput,
LoginInput,
Message,
Page,
RegisterInput,
Session,
User,
} from "./types";
const publicApi = "/api/v1";
const browserApi = "/web-api/v1";
export class ApiError extends Error {
readonly status: number;
readonly code?: string;
readonly requestId?: string;
constructor(status: number, body: ApiErrorBody) {
super(body.error?.message || `HTTP ${status}`);
this.name = "ApiError";
this.status = status;
this.code = body.error?.code;
this.requestId = body.error?.request_id;
}
}
type RequestOptions = Omit<RequestInit, "body"> & {
body?: unknown;
};
async function request<T>(path: string, options: RequestOptions = {}): Promise<T> {
const headers = new Headers(options.headers);
if (options.body !== undefined) {
headers.set("Content-Type", "application/json");
}
const response = await fetch(path, {
...options,
headers,
credentials: "same-origin",
body: options.body === undefined ? undefined : JSON.stringify(options.body),
});
if (!response.ok) {
let body: ApiErrorBody = {};
try {
body = (await response.json()) as ApiErrorBody;
} catch {
// Preserve a useful HTTP-level error when a proxy returned non-JSON.
}
throw new ApiError(response.status, body);
}
if (response.status === 204) {
return undefined as T;
}
return (await response.json()) as T;
}
function encodeBasic({ username, password }: LoginInput): string {
const bytes = new TextEncoder().encode(`${username}:${password}`);
let binary = "";
for (const byte of bytes) {
binary += String.fromCharCode(byte);
}
return btoa(binary);
}
async function collectPages<T>(path: string): Promise<T[]> {
const items: T[] = [];
let cursor: string | null = null;
for (let pageIndex = 0; pageIndex < 100; pageIndex += 1) {
const search = new URLSearchParams({ limit: "100" });
if (cursor) {
search.set("cursor", cursor);
}
const page = await request<Page<T>>(`${path}?${search.toString()}`);
items.push(...page.items);
cursor = page.next_cursor;
if (!cursor) {
return items;
}
}
throw new Error("pagination safety limit exceeded");
}
export const api = {
register(input: RegisterInput): Promise<User> {
return request<User>(`${publicApi}/users`, {
method: "POST",
body: {
username: input.username,
display_name: input.displayName,
password: input.password,
},
});
},
login(input: LoginInput): Promise<Session> {
return request<Session>(`${publicApi}/auth/sessions`, {
method: "POST",
headers: {
Authorization: `Basic ${encodeBasic(input)}`,
},
});
},
logout(): Promise<void> {
return request<void>(`${browserApi}/auth/sessions/current`, {
method: "DELETE",
});
},
me(): Promise<User> {
return request<User>(`${browserApi}/users/me`);
},
chats(): Promise<Chat[]> {
return collectPages<Chat>(`${browserApi}/chats`);
},
chat(chatID: string): Promise<Chat> {
return request<Chat>(`${browserApi}/chats/${encodeURIComponent(chatID)}`);
},
createChat(input: CreateChatInput): Promise<Chat> {
return request<Chat>(`${browserApi}/chats`, {
method: "POST",
body: {
title: input.title,
member_ids: input.memberIds,
},
});
},
messages(chatID: string): Promise<Message[]> {
return collectPages<Message>(
`${browserApi}/chats/${encodeURIComponent(chatID)}/messages`,
);
},
sendMessage(
chatID: string,
text: string,
idempotencyKey: string,
attachmentIDs: string[] = [],
): Promise<Message> {
return request<Message>(
`${browserApi}/chats/${encodeURIComponent(chatID)}/messages`,
{
method: "POST",
headers: {
"Idempotency-Key": idempotencyKey,
},
body: { text, attachment_ids: attachmentIDs },
},
);
},
};
+58
View File
@@ -0,0 +1,58 @@
export type User = {
id: string;
username: string;
display_name: string;
created_at: string;
};
export type Session = {
token: string;
token_type: "Bearer";
expires_at: string;
user: User;
};
export type Chat = {
id: string;
title: string;
member_ids: string[];
created_at: string;
};
export type Message = {
id: string;
chat_id: string;
sender_id: string;
text: string;
attachment_ids: string[];
created_at: string;
};
export type Page<T> = {
items: T[];
next_cursor: string | null;
};
export type ApiErrorBody = {
error?: {
code?: string;
message?: string;
request_id?: string;
};
};
export type RegisterInput = {
username: string;
displayName: string;
password: string;
};
export type CreateChatInput = {
title: string;
memberIds: string[];
};
export type LoginInput = {
username: string;
password: string;
};
+51
View File
@@ -0,0 +1,51 @@
import { Navigate, Outlet, Route, Routes, useLocation } from "react-router-dom";
import { useAuth } from "../auth/AuthProvider";
import { LoadingScreen } from "../components/LoadingScreen";
import { AuthPage } from "../pages/AuthPage";
import { MessengerPage } from "../pages/MessengerPage";
function ProtectedRoute() {
const { user, isLoading } = useAuth();
const location = useLocation();
if (isLoading) {
return <LoadingScreen />;
}
if (!user) {
return <Navigate to="/login" replace state={{ from: location.pathname }} />;
}
return <Outlet />;
}
function PublicOnlyRoute() {
const { user, isLoading } = useAuth();
if (isLoading) {
return <LoadingScreen />;
}
if (user) {
return <Navigate to="/app" replace />;
}
return <Outlet />;
}
export function App() {
return (
<Routes>
<Route element={<PublicOnlyRoute />}>
<Route path="/login" element={<AuthPage initialMode="login" />} />
<Route path="/register" element={<AuthPage initialMode="register" />} />
</Route>
<Route element={<ProtectedRoute />}>
<Route path="/app" element={<MessengerPage />} />
<Route path="/app/chats/:chatId" element={<MessengerPage />} />
<Route path="/app/profile" element={<MessengerPage profileOpen />} />
</Route>
<Route path="/" element={<Navigate to="/app" replace />} />
<Route path="*" element={<Navigate to="/app" replace />} />
</Routes>
);
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 540 KiB

+90
View File
@@ -0,0 +1,90 @@
import { useQuery, useQueryClient } from "@tanstack/react-query";
import {
createContext,
useCallback,
useContext,
type PropsWithChildren,
} from "react";
import { api, ApiError } from "../api/client";
import type { LoginInput, RegisterInput, User } from "../api/types";
type AuthContextValue = {
user: User | null;
isLoading: boolean;
login: (input: LoginInput) => Promise<void>;
register: (input: RegisterInput) => Promise<void>;
logout: () => Promise<void>;
};
const AuthContext = createContext<AuthContextValue | null>(null);
const meQueryKey = ["current-user"] as const;
async function loadCurrentUser(): Promise<User | null> {
try {
return await api.me();
} catch (error) {
if (error instanceof ApiError && error.status === 401) {
return null;
}
throw error;
}
}
export function AuthProvider({ children }: PropsWithChildren) {
const queryClient = useQueryClient();
const meQuery = useQuery({
queryKey: meQueryKey,
queryFn: loadCurrentUser,
retry: false,
staleTime: 30_000,
});
const login = useCallback(
async (input: LoginInput) => {
const session = await api.login(input);
queryClient.setQueryData(meQueryKey, session.user);
},
[queryClient],
);
const register = useCallback(
async (input: RegisterInput) => {
await api.register(input);
const session = await api.login({
username: input.username,
password: input.password,
});
queryClient.setQueryData(meQueryKey, session.user);
},
[queryClient],
);
const logout = useCallback(async () => {
await api.logout();
queryClient.setQueryData(meQueryKey, null);
queryClient.removeQueries({ queryKey: ["chats"] });
}, [queryClient]);
return (
<AuthContext.Provider
value={{
user: meQuery.data ?? null,
isLoading: meQuery.isLoading,
login,
register,
logout,
}}
>
{children}
</AuthContext.Provider>
);
}
export function useAuth(): AuthContextValue {
const context = useContext(AuthContext);
if (!context) {
throw new Error("useAuth must be used within AuthProvider");
}
return context;
}
+26
View File
@@ -0,0 +1,26 @@
import { initials } from "../lib/format";
type AvatarProps = {
label: string;
seed?: string;
size?: "small" | "medium" | "large";
};
function tone(seed: string): number {
let hash = 0;
for (const character of seed) {
hash = (hash * 31 + character.codePointAt(0)!) >>> 0;
}
return hash % 5;
}
export function Avatar({ label, seed = label, size = "medium" }: AvatarProps) {
return (
<span
aria-hidden="true"
className={`avatar avatar--${size} avatar--tone-${tone(seed)}`}
>
{initials(label)}
</span>
);
}
+121
View File
@@ -0,0 +1,121 @@
import { MessageSquarePlus, Search, UsersRound, X } from "lucide-react";
import { useMemo, useState } from "react";
import { useNavigate } from "react-router-dom";
import type { Chat, User } from "../api/types";
import { formatMemberCount } from "../lib/format";
import { Avatar } from "./Avatar";
type ChatListProps = {
chats: Chat[];
currentUser: User;
error: boolean;
isLoading: boolean;
selectedChatID?: string;
onCreateChat: () => void;
};
export function ChatList({
chats,
currentUser,
error,
isLoading,
selectedChatID,
onCreateChat,
}: ChatListProps) {
const navigate = useNavigate();
const [search, setSearch] = useState("");
const filteredChats = useMemo(() => {
const normalized = search.trim().toLocaleLowerCase("ru");
if (!normalized) {
return chats;
}
return chats.filter((chat) =>
chat.title.toLocaleLowerCase("ru").includes(normalized),
);
}, [chats, search]);
return (
<aside className="chat-sidebar">
<header className="chat-sidebar__header">
<div>
<p className="eyebrow">Сообщения</p>
<h1>Чаты</h1>
</div>
<button
aria-label="Создать чат"
className="soft-icon-button"
onClick={onCreateChat}
type="button"
>
<MessageSquarePlus aria-hidden="true" />
</button>
</header>
<div className="search-box">
<Search aria-hidden="true" />
<input
aria-label="Поиск чатов"
onChange={(event) => setSearch(event.target.value)}
placeholder="Поиск"
value={search}
/>
{search && (
<button aria-label="Очистить поиск" onClick={() => setSearch("")} type="button">
<X aria-hidden="true" />
</button>
)}
</div>
<div className="chat-list" aria-live="polite">
{isLoading && (
<div className="sidebar-state">
<span className="loading-line" />
<p>Загружаем чаты…</p>
</div>
)}
{error && (
<div className="sidebar-state sidebar-state--error">
<p>Не удалось загрузить список чатов.</p>
</div>
)}
{!isLoading && !error && filteredChats.length === 0 && (
<div className="sidebar-state">
<UsersRound aria-hidden="true" />
<p>{search ? "Ничего не найдено" : "У вас пока нет чатов"}</p>
{!search && (
<button className="text-button" onClick={onCreateChat} type="button">
Создать первый
</button>
)}
</div>
)}
{filteredChats.map((chat) => (
<button
className={`chat-row ${selectedChatID === chat.id ? "chat-row--active" : ""}`}
key={chat.id}
onClick={() => navigate(`/app/chats/${chat.id}`)}
type="button"
>
<Avatar label={chat.title} seed={chat.id} />
<span className="chat-row__body">
<strong>{chat.title}</strong>
<small>{formatMemberCount(chat.member_ids.length)}</small>
</span>
{chat.member_ids.includes(currentUser.id) && (
<span className="chat-row__status" title="Вы участник">
•
</span>
)}
</button>
))}
</div>
<footer className="sidebar-footer">
<span className="status-dot" />
API подключён
</footer>
</aside>
);
}
+236
View File
@@ -0,0 +1,236 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
ArrowLeft,
CheckCheck,
RefreshCcw,
Send,
ShieldCheck,
UsersRound,
} from "lucide-react";
import {
useEffect,
useMemo,
useRef,
useState,
type FormEvent,
type KeyboardEvent,
} from "react";
import { api } from "../api/client";
import type { Chat, Message, User } from "../api/types";
import {
dayKey,
formatDay,
formatMemberCount,
formatMessageTime,
shortID,
} from "../lib/format";
import { createIdempotencyKey } from "../lib/idempotency";
import { Avatar } from "./Avatar";
type ChatViewProps = {
chat: Chat;
currentUser: User;
onBack: () => void;
};
type SendEnvelope = {
text: string;
idempotencyKey: string;
};
export function ChatView({ chat, currentUser, onBack }: ChatViewProps) {
const queryClient = useQueryClient();
const messagesEnd = useRef<HTMLDivElement>(null);
const [draft, setDraft] = useState("");
const [failedEnvelope, setFailedEnvelope] = useState<SendEnvelope | null>(null);
const messagesQuery = useQuery({
queryKey: ["messages", chat.id],
queryFn: () => api.messages(chat.id),
refetchInterval: 3_000,
staleTime: 1_000,
});
const messages = messagesQuery.data ?? [];
useEffect(() => {
messagesEnd.current?.scrollIntoView({
behavior: messages.length > 1 ? "smooth" : "auto",
block: "end",
});
}, [chat.id, messages.length]);
const mutation = useMutation({
mutationFn: (envelope: SendEnvelope) =>
api.sendMessage(chat.id, envelope.text, envelope.idempotencyKey),
onSuccess: (message) => {
setFailedEnvelope(null);
queryClient.setQueryData<Message[]>(
["messages", chat.id],
(current = []) => {
if (current.some((item) => item.id === message.id)) {
return current;
}
return [...current, message];
},
);
},
onError: (_error, envelope) => {
setFailedEnvelope(envelope);
},
});
const groups = useMemo(() => {
const result: Array<{ key: string; label: string; messages: Message[] }> = [];
for (const message of messages) {
const key = dayKey(message.created_at);
const current = result.at(-1);
if (!current || current.key !== key) {
result.push({
key,
label: formatDay(message.created_at),
messages: [message],
});
} else {
current.messages.push(message);
}
}
return result;
}, [messages]);
function send(envelope: SendEnvelope) {
if (!mutation.isPending) {
mutation.mutate(envelope);
}
}
function submit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
const text = draft.trim();
if (!text || Array.from(text).length > 4_000) {
return;
}
const envelope = { text, idempotencyKey: createIdempotencyKey() };
setDraft("");
setFailedEnvelope(null);
send(envelope);
}
function handleKeyDown(event: KeyboardEvent<HTMLTextAreaElement>) {
if (event.key === "Enter" && !event.shiftKey) {
event.preventDefault();
event.currentTarget.form?.requestSubmit();
}
}
return (
<section className="conversation">
<header className="conversation-header">
<button
aria-label="Назад к списку чатов"
className="mobile-back-button"
onClick={onBack}
type="button"
>
<ArrowLeft aria-hidden="true" />
</button>
<Avatar label={chat.title} seed={chat.id} size="small" />
<div className="conversation-header__title">
<strong>{chat.title}</strong>
<span>{formatMemberCount(chat.member_ids.length)}</span>
</div>
<div className="conversation-header__security">
<ShieldCheck aria-hidden="true" />
<span>сессия защищена</span>
</div>
</header>
<div className="message-canvas">
<div className="message-canvas__shade" />
<div className="message-stream" aria-live="polite">
{messagesQuery.isLoading && (
<div className="floating-state">
<span className="loading-line" />
Загружаем историю
</div>
)}
{messagesQuery.isError && (
<div className="floating-state floating-state--error">
<p>История временно недоступна</p>
<button onClick={() => messagesQuery.refetch()} type="button">
<RefreshCcw aria-hidden="true" /> Повторить
</button>
</div>
)}
{!messagesQuery.isLoading && !messagesQuery.isError && messages.length === 0 && (
<div className="floating-state">
<UsersRound aria-hidden="true" />
<p>Сообщений пока нет. Начните разговор.</p>
</div>
)}
{groups.map((group) => (
<div className="message-day" key={group.key}>
<div className="date-divider"><span>{group.label}</span></div>
{group.messages.map((message) => {
const own = message.sender_id === currentUser.id;
return (
<article
className={`message-bubble ${own ? "message-bubble--own" : ""}`}
key={message.id}
>
<span className="message-bubble__sender">
{own ? "Вы" : shortID(message.sender_id)}
</span>
<p>{message.text}</p>
<span className="message-bubble__meta">
{formatMessageTime(message.created_at)}
{own && <CheckCheck aria-label="Доставлено серверу" />}
</span>
</article>
);
})}
</div>
))}
<div ref={messagesEnd} />
</div>
</div>
<footer className="composer">
{failedEnvelope && (
<div className="send-error" role="alert">
<span>Отправка не подтверждена.</span>
<button onClick={() => send(failedEnvelope)} type="button">
Повторить с тем же ключом
</button>
</div>
)}
<form onSubmit={submit}>
<textarea
aria-label="Текст сообщения"
maxLength={4_000}
onChange={(event) => setDraft(event.target.value)}
onKeyDown={handleKeyDown}
placeholder="Сообщение…"
rows={1}
value={draft}
/>
<span className="composer__counter">
{draft.length > 3_600 ? `${Array.from(draft).length}/4000` : ""}
</span>
<button
aria-label="Отправить"
className="send-button"
disabled={!draft.trim() || mutation.isPending}
type="submit"
>
<Send aria-hidden="true" />
</button>
</form>
</footer>
</section>
);
}
@@ -0,0 +1,148 @@
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { Plus, UserRoundPlus, X } from "lucide-react";
import { useEffect, useState, type FormEvent } from "react";
import { useNavigate } from "react-router-dom";
import { api, ApiError } from "../api/client";
import type { Chat, User } from "../api/types";
import { shortID } from "../lib/format";
type CreateChatDialogProps = {
currentUser: User;
onClose: () => void;
};
const uuidPattern =
/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
export function CreateChatDialog({
currentUser,
onClose,
}: CreateChatDialogProps) {
const navigate = useNavigate();
const queryClient = useQueryClient();
const [title, setTitle] = useState("");
const [memberInput, setMemberInput] = useState("");
const [validationError, setValidationError] = useState("");
useEffect(() => {
function closeOnEscape(event: KeyboardEvent) {
if (event.key === "Escape") {
onClose();
}
}
window.addEventListener("keydown", closeOnEscape);
return () => window.removeEventListener("keydown", closeOnEscape);
}, [onClose]);
const mutation = useMutation({
mutationFn: api.createChat,
onSuccess: (chat) => {
queryClient.setQueryData<Chat[]>(["chats"], (current = []) => [
...current,
chat,
]);
onClose();
navigate(`/app/chats/${chat.id}`);
},
});
function submit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
setValidationError("");
const enteredIDs = memberInput
.split(/[\s,;]+/)
.map((value) => value.trim())
.filter(Boolean);
const memberIds = Array.from(new Set([currentUser.id, ...enteredIDs]));
if (!title.trim() || Array.from(title.trim()).length > 100) {
setValidationError("Название должно содержать от 1 до 100 символов");
return;
}
const invalidID = enteredIDs.find((id) => !uuidPattern.test(id));
if (invalidID) {
setValidationError(`Некорректный UUID: ${invalidID}`);
return;
}
mutation.mutate({ title: title.trim(), memberIds });
}
const serverError =
mutation.error instanceof ApiError
? mutation.error.message
: mutation.error
? "Не удалось создать чат"
: "";
return (
<div className="dialog-backdrop" onMouseDown={onClose}>
<section
aria-labelledby="create-chat-title"
aria-modal="true"
className="dialog-card"
onMouseDown={(event) => event.stopPropagation()}
role="dialog"
>
<header className="dialog-card__header">
<div>
<p className="eyebrow">Новый разговор</p>
<h2 id="create-chat-title">Создать чат</h2>
</div>
<button
aria-label="Закрыть"
className="soft-icon-button"
onClick={onClose}
type="button"
>
<X aria-hidden="true" />
</button>
</header>
<form className="dialog-form" onSubmit={submit}>
<label>
<span>Название</span>
<div className="input-shell">
<Plus aria-hidden="true" />
<input
autoFocus
maxLength={100}
onChange={(event) => setTitle(event.target.value)}
placeholder="Например, Команда проекта"
required
value={title}
/>
</div>
</label>
<label>
<span>UUID участников</span>
<div className="textarea-shell">
<UserRoundPlus aria-hidden="true" />
<textarea
onChange={(event) => setMemberInput(event.target.value)}
placeholder="Вставьте UUID через пробел, запятую или с новой строки"
rows={4}
value={memberInput}
/>
</div>
<small>
Ваш ID добавлен автоматически: <code>{shortID(currentUser.id)}</code>
</small>
</label>
{(validationError || serverError) && (
<div className="form-error" role="alert">
{validationError || serverError}
</div>
)}
<button className="primary-button" disabled={mutation.isPending} type="submit">
{mutation.isPending ? "Создаём…" : "Создать чат"}
</button>
</form>
</section>
</div>
);
}
+29
View File
@@ -0,0 +1,29 @@
import { MessageSquarePlus } from "lucide-react";
type EmptyChatProps = {
hasChats: boolean;
onCreateChat: () => void;
};
export function EmptyChat({ hasChats, onCreateChat }: EmptyChatProps) {
return (
<section className="conversation conversation--empty">
<div className="empty-chat-card">
<span className="empty-chat-card__line" />
<p className="eyebrow">MTUCI Messenger</p>
<h2>{hasChats ? "Выберите чат" : "Начните разговор"}</h2>
<p>
{hasChats
? "История и новые сообщения появятся здесь."
: "Создайте первый чат и пригласите участников по UUID."}
</p>
{!hasChats && (
<button className="primary-button" onClick={onCreateChat} type="button">
<MessageSquarePlus aria-hidden="true" />
Создать чат
</button>
)}
</div>
</section>
);
}
+11
View File
@@ -0,0 +1,11 @@
export function LoadingScreen() {
return (
<main className="loading-screen" aria-live="polite">
<div className="brand-mark brand-mark--large" aria-hidden="true">
M
</div>
<p>Подключаемся к Messenger</p>
<span className="loading-line" />
</main>
);
}
@@ -0,0 +1,42 @@
import { MessagesSquare, UserRound } from "lucide-react";
import { Link } from "react-router-dom";
import type { User } from "../api/types";
import { Avatar } from "./Avatar";
type NavigationRailProps = {
user: User;
profileOpen: boolean;
};
export function NavigationRail({ user, profileOpen }: NavigationRailProps) {
return (
<nav className="navigation-rail" aria-label="Основная навигация">
<Link className="rail-brand" to="/app" aria-label="MTUCI Messenger">
M
</Link>
<div className="rail-actions">
<Link
className={`rail-action ${profileOpen ? "" : "rail-action--active"}`}
to="/app"
>
<MessagesSquare aria-hidden="true" />
<span>Чаты</span>
</Link>
<Link
className={`rail-action ${profileOpen ? "rail-action--active" : ""}`}
to="/app/profile"
>
<UserRound aria-hidden="true" />
<span>Профиль</span>
</Link>
</div>
<Link className="rail-profile" to="/app/profile" aria-label="Открыть профиль">
<Avatar label={user.display_name} seed={user.id} size="small" />
<span className="presence-dot" />
</Link>
</nav>
);
}
+123
View File
@@ -0,0 +1,123 @@
import {
CalendarDays,
Check,
Copy,
LogOut,
ShieldCheck,
UserRound,
X,
} from "lucide-react";
import { useState } from "react";
import { useNavigate } from "react-router-dom";
import type { User } from "../api/types";
import { useAuth } from "../auth/AuthProvider";
import { Avatar } from "./Avatar";
type ProfileDrawerProps = {
user: User;
};
const createdAtFormatter = new Intl.DateTimeFormat("ru-RU", {
day: "numeric",
month: "long",
year: "numeric",
});
export function ProfileDrawer({ user }: ProfileDrawerProps) {
const { logout } = useAuth();
const navigate = useNavigate();
const [copied, setCopied] = useState(false);
const [error, setError] = useState("");
const [isLoggingOut, setIsLoggingOut] = useState(false);
async function copyID() {
await navigator.clipboard.writeText(user.id);
setCopied(true);
window.setTimeout(() => setCopied(false), 1800);
}
async function submitLogout() {
setError("");
setIsLoggingOut(true);
try {
await logout();
navigate("/login", { replace: true });
} catch {
setError("Не удалось завершить сессию. Попробуйте ещё раз.");
setIsLoggingOut(false);
}
}
return (
<>
<button
aria-label="Закрыть профиль"
className="drawer-backdrop"
onClick={() => navigate("/app")}
type="button"
/>
<aside className="profile-drawer" aria-label="Профиль пользователя">
<header className="profile-drawer__header">
<p className="eyebrow">Ваш аккаунт</p>
<button
aria-label="Закрыть"
className="soft-icon-button"
onClick={() => navigate("/app")}
type="button"
>
<X aria-hidden="true" />
</button>
</header>
<div className="profile-identity">
<Avatar label={user.display_name} seed={user.id} size="large" />
<h2>{user.display_name}</h2>
<p>@{user.username}</p>
<span className="profile-badge">
<ShieldCheck aria-hidden="true" />
серверная сессия
</span>
</div>
<dl className="profile-details">
<div>
<dt><UserRound aria-hidden="true" /> ID аккаунта</dt>
<dd>
<code>{user.id}</code>
<button
aria-label="Скопировать ID"
className="copy-button"
onClick={copyID}
type="button"
>
{copied ? <Check /> : <Copy />}
</button>
</dd>
</div>
<div>
<dt><CalendarDays aria-hidden="true" /> Дата регистрации</dt>
<dd>{createdAtFormatter.format(new Date(user.created_at))}</dd>
</div>
</dl>
<div className="profile-roadmap">
<strong>Следующие версии</strong>
<p>Аватар, редактирование имени и смена пароля появятся после API-контрактов.</p>
</div>
{error && <div className="form-error" role="alert">{error}</div>}
<button
className="logout-button"
disabled={isLoggingOut}
onClick={submitLogout}
type="button"
>
<LogOut aria-hidden="true" />
{isLoggingOut ? "Завершаем…" : "Выйти из аккаунта"}
</button>
</aside>
</>
);
}
+58
View File
@@ -0,0 +1,58 @@
const timeFormatter = new Intl.DateTimeFormat("ru-RU", {
hour: "2-digit",
minute: "2-digit",
});
const dayFormatter = new Intl.DateTimeFormat("ru-RU", {
day: "numeric",
month: "long",
});
const fullDateFormatter = new Intl.DateTimeFormat("ru-RU", {
day: "numeric",
month: "long",
year: "numeric",
});
export function formatMessageTime(value: string): string {
return timeFormatter.format(new Date(value));
}
export function formatDay(value: string): string {
const date = new Date(value);
const now = new Date();
const sameYear = date.getFullYear() === now.getFullYear();
return (sameYear ? dayFormatter : fullDateFormatter).format(date);
}
export function dayKey(value: string): string {
const date = new Date(value);
return [date.getFullYear(), date.getMonth(), date.getDate()].join("-");
}
export function formatMemberCount(count: number): string {
const mod10 = count % 10;
const mod100 = count % 100;
if (mod10 === 1 && mod100 !== 11) {
return `${count} участник`;
}
if (mod10 >= 2 && mod10 <= 4 && (mod100 < 12 || mod100 > 14)) {
return `${count} участника`;
}
return `${count} участников`;
}
export function shortID(id: string): string {
return id.length > 12 ? `${id.slice(0, 8)}…` : id;
}
export function initials(value: string): string {
const parts = value.trim().split(/\s+/).filter(Boolean);
if (parts.length === 0) {
return "?";
}
return parts
.slice(0, 2)
.map((part) => Array.from(part)[0]?.toUpperCase() ?? "")
.join("");
}
+19
View File
@@ -0,0 +1,19 @@
import { describe, expect, it, vi } from "vitest";
import { createIdempotencyKey } from "./idempotency";
describe("createIdempotencyKey", () => {
it("creates an API-compatible unique key", () => {
vi.stubGlobal("crypto", {
randomUUID: () => "12345678-1234-1234-1234-123456789abc",
});
const key = createIdempotencyKey();
expect(key).toMatch(/^[A-Za-z0-9._:-]{1,128}$/);
expect(key).toContain("12345678123412341234123456789abc");
expect(key.length).toBeLessThanOrEqual(128);
vi.unstubAllGlobals();
});
});
+4
View File
@@ -0,0 +1,4 @@
export function createIdempotencyKey(): string {
const random = crypto.randomUUID().replaceAll("-", "");
return `web-${Date.now().toString(36)}-${random}`;
}
+32
View File
@@ -0,0 +1,32 @@
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { BrowserRouter } from "react-router-dom";
import { App } from "./app/App";
import { AuthProvider } from "./auth/AuthProvider";
import "./styles.css";
const queryClient = new QueryClient({
defaultOptions: {
queries: {
retry: 1,
refetchOnWindowFocus: true,
},
mutations: {
retry: false,
},
},
});
createRoot(document.getElementById("root")!).render(
<StrictMode>
<QueryClientProvider client={queryClient}>
<BrowserRouter>
<AuthProvider>
<App />
</AuthProvider>
</BrowserRouter>
</QueryClientProvider>
</StrictMode>,
);
+190
View File
@@ -0,0 +1,190 @@
import {
ArrowRight,
Eye,
EyeOff,
LockKeyhole,
MessageCircleMore,
UserRound,
} from "lucide-react";
import { useState, type FormEvent } from "react";
import { Link, useNavigate } from "react-router-dom";
import { ApiError } from "../api/client";
import { useAuth } from "../auth/AuthProvider";
type AuthMode = "login" | "register";
type AuthPageProps = {
initialMode: AuthMode;
};
function errorMessage(error: unknown): string {
if (error instanceof ApiError) {
if (error.status === 401) {
return "Неверный логин или пароль";
}
if (error.status === 409) {
return "Такой username уже занят";
}
return error.message;
}
return "Не удалось связаться с сервером. Попробуйте ещё раз.";
}
export function AuthPage({ initialMode }: AuthPageProps) {
const { login, register } = useAuth();
const navigate = useNavigate();
const [username, setUsername] = useState("");
const [displayName, setDisplayName] = useState("");
const [password, setPassword] = useState("");
const [showPassword, setShowPassword] = useState(false);
const [error, setError] = useState("");
const [isSubmitting, setIsSubmitting] = useState(false);
const isRegister = initialMode === "register";
async function submit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
setError("");
if (!/^[a-z0-9_]{3,32}$/.test(username)) {
setError("Username: 3–32 символа, только a–z, цифры и _");
return;
}
if (isRegister && displayName.trim().length === 0) {
setError("Укажите отображаемое имя");
return;
}
if (password.length < 12 || Array.from(password).length > 128) {
setError("Пароль должен содержать от 12 до 128 символов");
return;
}
setIsSubmitting(true);
try {
if (isRegister) {
await register({ username, displayName: displayName.trim(), password });
} else {
await login({ username, password });
}
navigate("/app", { replace: true });
} catch (submitError) {
setError(errorMessage(submitError));
} finally {
setIsSubmitting(false);
}
}
return (
<main className="auth-page">
<section className="auth-story" aria-label="О приложении">
<div className="auth-brand">
<div className="brand-mark" aria-hidden="true">
M
</div>
<span>MTUCI Messenger</span>
</div>
<div className="auth-copy">
<p className="eyebrow">Распределённый мессенджер</p>
<h1>Разговоры, которые остаются с вами.</h1>
<p>
Минималистичный клиент поверх отказоустойчивого Go API. Одна сессия,
несколько реплик, никаких лишних отвлечений.
</p>
<div className="auth-status">
<span className="status-dot" />
защищённая серверная сессия
</div>
</div>
</section>
<section className="auth-panel">
<div className="auth-card">
<MessageCircleMore className="auth-card__icon" aria-hidden="true" />
<p className="eyebrow">{isRegister ? "Новый аккаунт" : "С возвращением"}</p>
<h2>{isRegister ? "Создать профиль" : "Войти в Messenger"}</h2>
<p className="auth-card__lead">
{isRegister
? "Данные профиля можно будет расширить в следующих версиях."
: "Продолжите общение с того места, где остановились."}
</p>
<form className="auth-form" onSubmit={submit}>
{isRegister && (
<label>
<span>Отображаемое имя</span>
<div className="input-shell">
<UserRound aria-hidden="true" />
<input
autoComplete="name"
maxLength={100}
onChange={(event) => setDisplayName(event.target.value)}
placeholder="Как к вам обращаться"
required
value={displayName}
/>
</div>
</label>
)}
<label>
<span>Username</span>
<div className="input-shell">
<UserRound aria-hidden="true" />
<input
autoCapitalize="none"
autoComplete="username"
maxLength={32}
onChange={(event) => setUsername(event.target.value.toLowerCase())}
placeholder="username"
required
value={username}
/>
</div>
</label>
<label>
<span>Пароль</span>
<div className="input-shell">
<LockKeyhole aria-hidden="true" />
<input
autoComplete={isRegister ? "new-password" : "current-password"}
maxLength={128}
minLength={12}
onChange={(event) => setPassword(event.target.value)}
placeholder="Минимум 12 символов"
required
type={showPassword ? "text" : "password"}
value={password}
/>
<button
aria-label={showPassword ? "Скрыть пароль" : "Показать пароль"}
className="icon-button"
onClick={() => setShowPassword((value) => !value)}
type="button"
>
{showPassword ? <EyeOff /> : <Eye />}
</button>
</div>
</label>
{error && <div className="form-error" role="alert">{error}</div>}
<button className="primary-button" disabled={isSubmitting} type="submit">
<span>{isSubmitting ? "Подождите…" : isRegister ? "Создать аккаунт" : "Войти"}</span>
{!isSubmitting && <ArrowRight aria-hidden="true" />}
</button>
</form>
<p className="auth-switch">
{isRegister ? "Уже есть аккаунт?" : "Впервые здесь?"}{" "}
<Link to={isRegister ? "/login" : "/register"}>
{isRegister ? "Войти" : "Создать профиль"}
</Link>
</p>
</div>
</section>
</main>
);
}
+81
View File
@@ -0,0 +1,81 @@
import { useQuery } from "@tanstack/react-query";
import { useState } from "react";
import { useNavigate, useParams } from "react-router-dom";
import { api } from "../api/client";
import { useAuth } from "../auth/AuthProvider";
import { ChatList } from "../components/ChatList";
import { ChatView } from "../components/ChatView";
import { CreateChatDialog } from "../components/CreateChatDialog";
import { EmptyChat } from "../components/EmptyChat";
import { NavigationRail } from "../components/NavigationRail";
import { ProfileDrawer } from "../components/ProfileDrawer";
type MessengerPageProps = {
profileOpen?: boolean;
};
export function MessengerPage({ profileOpen = false }: MessengerPageProps) {
const { user } = useAuth();
const { chatId } = useParams();
const navigate = useNavigate();
const [createChatOpen, setCreateChatOpen] = useState(false);
const chatsQuery = useQuery({
queryKey: ["chats"],
queryFn: api.chats,
refetchInterval: 10_000,
staleTime: 5_000,
});
if (!user) {
return null;
}
const chats = chatsQuery.data ?? [];
const selectedChat = chatId
? chats.find((chat) => chat.id === chatId)
: undefined;
return (
<main
className={[
"messenger-shell",
chatId ? "messenger-shell--chat-open" : "",
profileOpen ? "messenger-shell--drawer-open" : "",
].join(" ")}
>
<NavigationRail profileOpen={profileOpen} user={user} />
<ChatList
chats={chats}
currentUser={user}
error={chatsQuery.isError}
isLoading={chatsQuery.isLoading}
onCreateChat={() => setCreateChatOpen(true)}
selectedChatID={chatId}
/>
{selectedChat ? (
<ChatView
chat={selectedChat}
currentUser={user}
onBack={() => navigate("/app")}
/>
) : (
<EmptyChat
hasChats={chats.length > 0}
onCreateChat={() => setCreateChatOpen(true)}
/>
)}
{profileOpen && <ProfileDrawer user={user} />}
{createChatOpen && (
<CreateChatDialog
currentUser={user}
onClose={() => setCreateChatOpen(false)}
/>
)}
</main>
);
}
File diff suppressed because it is too large Load Diff
+1
View File
@@ -0,0 +1 @@
/// <reference types="vite/client" />