Update Harbor client implementation
Build and Deploy Gateway / build-and-push (push) Successful in 34s
Build and Deploy Gateway / deploy (push) Successful in 13s

This commit is contained in:
2026-09-10 21:54:18 +03:00
parent 1ae23d848b
commit 74c5b66482
11 changed files with 868 additions and 806 deletions
@@ -7,13 +7,13 @@ import {
type TrafficHistorySnapshot,
} from '../../../shared/trafficHistory.js';
import { formatByteString } from '../../utils/format.js';
import { TrafficColumns, TrafficMenu, TrafficReveal } from './TrafficControls.js';
export type LoadTrafficHistory = (query: TrafficHistoryQuery, signal?: AbortSignal) => Promise<unknown>;
const nextLevel: Record<TrafficHistoryLevel, TrafficHistoryLevel | null> = {
service: 'domain', domain: 'hostname', hostname: 'ip', ip: null,
};
const levelLabels = { service: 'Сервис', domain: 'Домен', hostname: 'Полное имя', ip: 'IP' };
const routes = { vpn: 'VPN', direct: 'Direct', other: 'Другое', mixed: 'Разные' };
function useHistory(active: boolean, query: TrafficHistoryQuery, load: LoadTrafficHistory) {
const key = JSON.stringify(query);
@@ -43,7 +43,7 @@ function useHistory(active: boolean, query: TrafficHistoryQuery, load: LoadTraff
return result.key === key ? result : { key, snapshot: null, status: 'loading' as const };
}
function HistoryRows({ snapshot, active, load }: { snapshot: TrafficHistorySnapshot; active: boolean; load: LoadTrafficHistory }) {
export function HistoryRows({ snapshot, active, load }: { snapshot: TrafficHistorySnapshot; active: boolean; load: LoadTrafficHistory }) {
const [expanded, setExpanded] = useState<string | null>(null);
const detailsId = useId();
const { query } = snapshot;
@@ -58,18 +58,15 @@ function HistoryRows({ snapshot, active, load }: { snapshot: TrafficHistorySnaps
disabled={!childLevel}
onClick={() => setExpanded((current) => current === row.key ? null : row.key)}
>
<span className="client-traffic-identity"><strong title={row.label}>{row.label}</strong><small>{levelLabels[query.level]}</small></span>
<span className="client-traffic-route" data-route={row.route}>{routes[row.route]}</span>
<span className="client-traffic-values"><strong>
<span> {formatByteString(row.downloadBytes)}</span><span> {formatByteString(row.uploadBytes)}</span>
</strong></span>
{childLevel && <svg className="client-traffic-chevron" viewBox="0 0 16 16" aria-hidden="true"><path d="m5 6 3 3 3-3" /></svg>}
<span className="client-traffic-identity"><strong title={row.label}>{row.label}</strong></span>
<span className="client-traffic-download" aria-label={`Скачивание: ${formatByteString(row.downloadBytes)}`}>{formatByteString(row.downloadBytes)}</span>
<span className="client-traffic-upload" aria-label={`Отправка: ${formatByteString(row.uploadBytes)}`}>{formatByteString(row.uploadBytes)}</span>
</button>
{childLevel && expanded === row.key && <div id={`${detailsId}-${index}`} className="client-traffic-history-children">
<HistoryBranch key={row.key} active={active} load={load} query={{
{childLevel && <TrafficReveal open={expanded === row.key} id={`${detailsId}-${index}`} className="client-traffic-history-children">
<HistoryBranch key={row.key} active={active && expanded === row.key} load={load} query={{
...query, level: childLevel, [query.level]: row.key, offset: 0,
}} />
</div>}
</TrafficReveal>}
</div>)}
</div>;
}
@@ -79,8 +76,9 @@ function HistoryBranch({ active, query, load }: { active: boolean; query: Traffi
const requested = useMemo(() => ({ ...query, offset }), [query, offset]);
const result = useHistory(active, requested, load);
return <>
<p className="client-traffic-history-status" role="status">{result.status === 'loading' ? 'Загружаем…'
: result.status === 'error' ? 'Данные временно недоступны.' : '\u00a0'}</p>
{result.status !== 'ready' && <p className="client-traffic-history-status" role="status">
{result.status === 'loading' ? 'Загружаем…' : 'Данные временно недоступны.'}
</p>}
{result.snapshot && <>
<HistoryRows snapshot={result.snapshot} active={active} load={load} />
<HistoryPages snapshot={result.snapshot} offset={offset} change={setOffset} />
@@ -96,77 +94,84 @@ function HistoryPages({ snapshot, offset, change }: { snapshot: TrafficHistorySn
</div>;
}
export function TrafficHistoryPanel({ active, isGateway, load }: { active: boolean; isGateway: boolean; load: LoadTrafficHistory }) {
export function TrafficHistoryPanel({ active, paused = false, isGateway, load }: {
active: boolean; paused?: boolean; isGateway: boolean; load: LoadTrafficHistory;
}) {
const [query, setQuery] = useState(() => parseTrafficHistoryQuery(new URLSearchParams()));
const [deviceSearch, setDeviceSearch] = useState('');
const [devicesExpanded, setDevicesExpanded] = useState(false);
const result = useHistory(active, query, load);
const snapshot = result.snapshot;
const origins = (snapshot?.origins || []).filter((origin) => origin.label.toLocaleLowerCase('ru').includes(deviceSearch.toLocaleLowerCase('ru')));
function change(patch: Partial<TrafficHistoryQuery>) { setQuery((current) => ({ ...current, ...patch, offset: 0, until: null })); }
const status = paused ? 'История на паузе.'
: result.status === 'loading' ? 'Загружаем историю…'
: result.status === 'error' ? `История временно недоступна.${snapshot ? ' Показаны последние данные.' : ''}`
: snapshot?.source === 'disabled' ? 'Сбор выключен. Показана сохранённая история.'
: snapshot?.source === 'stopped' ? 'VPN остановлен. Показана сохранённая история.'
: snapshot?.source === 'connecting' ? 'Сборщик подключается. Показана сохранённая история.'
: snapshot?.coverage.partial ? 'В периоде есть пропуски.' : '';
return <>
<div className="client-traffic-tools">
<div className="client-traffic-option-row"><span>Период</span>
<div className="client-traffic-filters" role="group" aria-label="Период истории">
{([['24h', '24 часа'], ['7d', '7 дней'], ['30d', '30 дней'], ['90d', '90 дней']] as const).map(([value, label]) => <button
type="button" key={value} aria-pressed={query.range === value} onClick={() => change({ range: value })}
>{label}</button>)}
</div>
<div className="client-traffic-toolbar">
<div className="client-traffic-filters client-traffic-periods" role="group" aria-label="Период истории">
{([['24h', '24 часа'], ['7d', '7 дней'], ['30d', '30 дней'], ['90d', '90 дней']] as const).map(([value, label]) => <button
type="button" key={value} aria-pressed={query.range === value} onClick={() => change({ range: value })}
>{label}</button>)}
</div>
<div className="client-traffic-option-row"><span>Маршрут</span>
<div className="client-traffic-filters" role="group" aria-label="Маршрут в истории">
{([['all', 'Все'], ['vpn', 'VPN'], ['direct', 'Direct'], ['other', 'Другое']] as const).map(([value, label]) => <button
type="button" key={value} aria-pressed={query.route === value} onClick={() => change({ route: value })}
>{label}</button>)}
{isGateway && <TrafficMenu
label={snapshot?.origins.find((origin) => origin.id === query.originId)?.label || (query.originId ? 'Выбрано устройство' : 'Все устройства')}
active={Boolean(query.originId)} closeOnSelect
>
<label className="client-traffic-search">
<input type="search" value={deviceSearch} aria-label="Найти устройство в истории" placeholder="Найти устройство"
onChange={(event) => setDeviceSearch(event.target.value)} />
</label>
<div className="client-traffic-device-list">
<button type="button" aria-pressed={!query.originId} onClick={() => change({ originId: '' })}>Все устройства</button>
{origins.map((origin) => <button type="button" key={origin.id} aria-pressed={query.originId === origin.id}
onClick={() => change({ originId: origin.id })}
>{origin.label}</button>)}
</div>
</div>
{!origins.length && <p className="client-traffic-notice">Устройства не найдены.</p>}
{snapshot?.originsTruncated && <p className="client-traffic-notice">Показаны первые 256 устройств.</p>}
</TrafficMenu>}
<TrafficMenu label="Фильтры" active={Boolean(query.search) || query.route !== 'all'}>
<label className="client-traffic-search">
<input type="search" value={query.search} maxLength={200} aria-label="Найти сайт, IP или сервис в истории" placeholder="Найти сайт"
onChange={(event) => change({ search: event.target.value })} />
</label>
<div className="client-traffic-option-row"><span>Маршрут</span>
<div className="client-traffic-filters" role="group" aria-label="Маршрут в истории">
{([['all', 'Все'], ['vpn', 'VPN'], ['direct', 'Direct'], ['other', 'Другое']] as const).map(([value, label]) => <button
type="button" key={value} aria-pressed={query.route === value} onClick={() => change({ route: value })}
>{label}</button>)}
</div>
</div>
{snapshot && <>
<div className="client-traffic-summary" aria-label="Расход за выбранный период">
<span>Скачано {formatByteString(snapshot.totals.downloadBytes)}</span>
<span>Отправлено {formatByteString(snapshot.totals.uploadBytes)}</span>
</div>
<p className="client-traffic-honesty">
{`Данные до ${new Date(snapshot.period.to).toLocaleString('ru-RU')}.`}
{snapshot.period.availableFrom && ` Сбор с ${new Date(snapshot.period.availableFrom).toLocaleString('ru-RU')}.`}
{snapshot.coverage.lastObservedAt && ` Обновлено ${new Date(snapshot.coverage.lastObservedAt).toLocaleString('ru-RU')}.`}
{' '}IP без домена не означает распознанный сайт.
</p>
</>}
</TrafficMenu>
</div>
<TrafficColumns />
<div className="client-traffic-scroll">
{status && <p className="client-traffic-history-status" role="status">{status}
{snapshot && (paused || result.status === 'error') && ` Обновлено ${new Date(snapshot.generatedAt).toLocaleTimeString('ru-RU')}.`}
</p>}
{snapshot && <>
{snapshot.rows.length ? <HistoryRows key={JSON.stringify(query)} snapshot={snapshot} active={active} load={load} />
: <p className="client-traffic-state">{query.search || query.originId || query.route !== 'all'
? 'По выбранным фильтрам ничего не найдено.' : 'История пока пуста.'}</p>}
<HistoryPages snapshot={snapshot} offset={query.offset}
change={(offset) => setQuery((current) => ({ ...current, offset, until: snapshot.query.until }))} />
</>}
</div>
{isGateway && <section className="client-traffic-devices" aria-label="Устройства в истории">
<div className="client-traffic-devices-heading"><h3>Устройства</h3>
<button type="button" aria-pressed={!query.originId} onClick={() => change({ originId: '' })}>Все устройства</button>
</div>
<label className="client-traffic-search is-device-search">
<span aria-hidden="true" /><span className="client-live-region">Найти устройство</span>
<input type="search" value={deviceSearch} aria-label="Найти устройство в истории" placeholder="Найти устройство" onChange={(e) => setDeviceSearch(e.target.value)} />
</label>
<div className="client-traffic-device-list" id="client-history-devices">
{(devicesExpanded ? origins : origins.slice(0, 3)).map((origin) => <button type="button" key={origin.id}
aria-pressed={query.originId === origin.id} onClick={() => change({ originId: query.originId === origin.id ? '' : origin.id })}
><strong>{origin.label}</strong></button>)}
</div>
{origins.length > 3 && <button type="button" className="client-traffic-devices-more" aria-expanded={devicesExpanded}
aria-controls="client-history-devices" onClick={() => setDevicesExpanded((value) => !value)}
>{devicesExpanded ? 'Свернуть устройства' : `Ещё ${origins.length - 3} устройств`}</button>}
{snapshot?.originsTruncated && <p className="client-traffic-notice">Показаны первые 256 устройств.</p>}
</section>}
<label className="client-traffic-search client-traffic-list-search">
<svg viewBox="0 0 24 24" aria-hidden="true"><circle cx="10.5" cy="10.5" r="6" /><path d="m15 15 5 5" /></svg>
<span className="client-live-region">Поиск истории</span>
<input type="search" value={query.search} aria-label="Найти сайт, IP или сервис в истории" placeholder="Найти сайт, IP или сервис"
onChange={(event) => change({ search: event.target.value })} />
</label>
<p className="client-traffic-history-status" role="status">{result.status === 'loading' ? 'Загружаем историю…'
: result.status === 'error' ? `История временно недоступна.${snapshot ? ' Показаны последние полученные данные.' : ''}`
: snapshot?.source === 'disabled' ? 'Сбор истории выключен; сохранённые данные доступны.'
: snapshot?.source === 'stopped' ? 'VPN остановлен; показана сохранённая история.'
: snapshot?.source === 'connecting' ? 'Сборщик подключается; показана сохранённая история.'
: snapshot?.coverage.partial ? 'В выбранном периоде есть пропуски или неточное распределение по времени.' : '\u00a0'}</p>
{snapshot && <>
<div className="client-traffic-summary" aria-label="Расход за выбранный период">
<span><b>Скачано</b>{formatByteString(snapshot.totals.downloadBytes)}</span>
<span><b>Отправлено</b>{formatByteString(snapshot.totals.uploadBytes)}</span>
</div>
{snapshot.rows.length ? <HistoryRows key={JSON.stringify(query)} snapshot={snapshot} active={active} load={load} />
: <p className="client-traffic-state">{query.search || query.originId || query.route !== 'all'
? 'По выбранным фильтрам ничего не найдено.' : 'История пока пуста. Данные появятся после начала сбора трафика.'}</p>}
<HistoryPages snapshot={snapshot} offset={query.offset} change={(offset) => setQuery((current) => ({ ...current, offset, until: snapshot.query.until }))} />
<p className="client-traffic-honesty">
Локальная история за 90 дней: завершённые минуты за последние 7 дней, ранее по часам.
{` Данные до ${new Date(snapshot.period.to).toLocaleString('ru-RU')}.`}
{snapshot.period.availableFrom && ` Сбор с ${new Date(snapshot.period.availableFrom).toLocaleString('ru-RU')}.`}
{snapshot.coverage.lastObservedAt && ` Обновлено ${new Date(snapshot.coverage.lastObservedAt).toLocaleString('ru-RU')}.`}
{' '}Внешний Prometheus не требуется. IP без домена не означает распознанный сайт.
</p>
</>}
</>;
}