Refine failover controls and bump Harbor versions
Build and Deploy Gateway / build-and-push (push) Successful in 24s
Build and Deploy Gateway / deploy (push) Successful in 7s

This commit is contained in:
2026-08-19 19:23:16 +03:00
parent d4f228284e
commit cedd31cc16
5 changed files with 362 additions and 96 deletions
+277 -54
View File
@@ -1,4 +1,5 @@
import { useEffect, useMemo, useRef, useState } from 'react';
import { useEffect, useMemo, useRef, useState, type KeyboardEvent as ReactKeyboardEvent } from 'react';
import { flushSync } from 'react-dom';
import { CONNECTIVITY_SITES, MAX_CUSTOM_DIAGNOSTIC_SERVICES, type DiagnosticSettings } from '../../../shared/connectivityDiagnostics.js';
import { normalizeFailoverPolicy, type FailoverPolicy, type FailoverSnapshot } from '../../../shared/failover.js';
import type { ProfileSnapshot } from '../../../shared/contracts/state.js';
@@ -101,6 +102,142 @@ function targetLabel(profiles: ProfileSnapshot[], target: { profileId: string; s
return profile && server ? `${profile.label} · ${server.label}` : 'Не выбран';
}
function HarborSwitch({ checked, label, disabled, onChange }: {
checked: boolean;
label: string;
disabled?: boolean;
onChange: (checked: boolean) => void;
}) {
return <button
className="client-failover-switch"
type="button"
role="switch"
aria-checked={checked}
aria-label={label}
disabled={disabled}
onClick={() => onChange(!checked)}
><span aria-hidden="true" /></button>;
}
interface PickerOption {
id: string;
label: string;
disabled?: boolean;
}
function FailoverPicker({ id, label, value, options, open, disabled, onOpenChange, onChange }: {
id: string;
label: string;
value: string;
options: PickerOption[];
open: boolean;
disabled?: boolean;
onOpenChange: (open: boolean) => void;
onChange: (id: string) => void;
}) {
const rootRef = useRef<HTMLDivElement>(null);
const triggerRef = useRef<HTMLButtonElement>(null);
const optionRefs = useRef<Array<HTMLButtonElement | null>>([]);
const onOpenChangeRef = useRef(onOpenChange);
onOpenChangeRef.current = onOpenChange;
const enabledIndexes = useMemo(
() => options.flatMap((option, index) => option.disabled ? [] : [index]),
[options],
);
const selectedIndex = options.findIndex((option) => option.id === value && !option.disabled);
useEffect(() => {
if (!open) return undefined;
const frame = requestAnimationFrame(() => {
optionRefs.current[selectedIndex >= 0 ? selectedIndex : enabledIndexes[0]]?.focus();
});
const close = (event: PointerEvent | globalThis.KeyboardEvent) => {
if (event.type === 'keydown') {
if ((event as globalThis.KeyboardEvent).key !== 'Escape') return;
event.preventDefault();
onOpenChangeRef.current(false);
triggerRef.current?.focus();
return;
}
if (rootRef.current?.contains(event.target as Node)) return;
onOpenChangeRef.current(false);
};
document.addEventListener('pointerdown', close);
document.addEventListener('keydown', close);
return () => {
cancelAnimationFrame(frame);
document.removeEventListener('pointerdown', close);
document.removeEventListener('keydown', close);
};
}, [enabledIndexes, open, selectedIndex]);
const move = (event: ReactKeyboardEvent<HTMLButtonElement>, offset: number) => {
if (!['ArrowDown', 'ArrowUp', 'Home', 'End', 'Escape'].includes(event.key)) return;
event.preventDefault();
if (event.key === 'Escape') {
event.stopPropagation();
onOpenChangeRef.current(false);
triggerRef.current?.focus();
return;
}
const current = optionRefs.current.indexOf(document.activeElement as HTMLButtonElement);
const position = Math.max(0, enabledIndexes.indexOf(current));
const next = event.key === 'Home'
? enabledIndexes[0]
: event.key === 'End'
? enabledIndexes.at(-1)
: enabledIndexes[(position + offset + enabledIndexes.length) % enabledIndexes.length];
if (next !== undefined) optionRefs.current[next]?.focus();
};
return <div className={`client-failover-picker${open ? ' is-open' : ''}`} ref={rootRef}>
<button
ref={triggerRef}
className="client-failover-picker-trigger"
type="button"
aria-label={label}
aria-haspopup="listbox"
aria-expanded={open}
aria-controls={id}
disabled={disabled}
onClick={() => onOpenChange(!open)}
onKeyDown={(event) => {
if (event.key === 'Escape' && open) {
event.preventDefault();
event.stopPropagation();
onOpenChange(false);
return;
}
if (!['ArrowDown', 'ArrowUp'].includes(event.key)) return;
event.preventDefault();
onOpenChange(true);
}}
>
<span>{value ? options.find((option) => option.id === value)?.label || label : label}</span>
<svg viewBox="0 0 12 8" aria-hidden="true"><path d="m1 1 5 5 5-5" /></svg>
</button>
<div className="client-failover-picker-list" id={id} role="listbox" aria-hidden={!open} inert={!open ? true : undefined}>
{options.map((option, index) => <button
ref={(node) => { optionRefs.current[index] = node; }}
type="button"
role="option"
aria-selected={option.id === value}
aria-disabled={option.disabled || undefined}
tabIndex={open && !option.disabled ? 0 : -1}
key={option.id}
style={{ '--picker-index': Math.min(index, 5) } as React.CSSProperties}
onClick={() => {
if (option.disabled) return;
onChange(option.id);
onOpenChange(false);
triggerRef.current?.focus();
}}
onKeyDown={(event) => move(event, event.key === 'ArrowUp' ? -1 : 1)}
>{option.label}</button>)}
</div>
</div>;
}
export function FailoverPanel({
feature,
snapshot,
@@ -131,6 +268,8 @@ export function FailoverPanel({
const [serviceName, setServiceName] = useState('');
const [serviceUrl, setServiceUrl] = useState('');
const [serviceError, setServiceError] = useState('');
const [openPicker, setOpenPicker] = useState('');
const [removingCheckId, setRemovingCheckId] = useState('');
useEffect(() => {
if (!dirty) setDraft(snapshot.policy);
}, [snapshot.policy, dirty]);
@@ -154,15 +293,42 @@ export function FailoverPanel({
...CONNECTIVITY_SITES,
...diagnostics.customServices,
], [diagnostics.customServices]);
const channelOptions = useMemo(() => profiles.flatMap((profile) => profile.servers.map((server) => ({
id: `${profile.id}\u001f${server.id}`,
label: `${profile.label} · ${server.label}`,
target: { profileId: profile.id, serverId: server.id },
}))), [profiles]);
const channelPickerOptions = useMemo(() => ({
primary: channelOptions.map((option) => {
const duplicate = option.target.profileId === draft.reserve.profileId && option.target.serverId === draft.reserve.serverId;
return { id: option.id, label: `${option.label}${duplicate ? ' · уже выбран' : ''}`, disabled: duplicate };
}),
reserve: channelOptions.map((option) => {
const duplicate = option.target.profileId === draft.primary.profileId && option.target.serverId === draft.primary.serverId;
return { id: option.id, label: `${option.label}${duplicate ? ' · уже выбран' : ''}`, disabled: duplicate };
}),
}), [
channelOptions,
draft.primary.profileId,
draft.primary.serverId,
draft.reserve.profileId,
draft.reserve.serverId,
]);
const servicePickerOptions = useMemo(() => [
...services.filter((service) => !draft.checks.some(({ serviceId }) => serviceId === service.id)).map((service) => ({ id: service.id, label: service.label })),
...(diagnostics.customServices.length < MAX_CUSTOM_DIAGNOSTIC_SERVICES ? [{ id: '__new-service', label: 'Новый HTTPS-сервис…' }] : []),
], [diagnostics.customServices.length, draft.checks, services]);
const update = (value: Partial<FailoverPolicy>) => {
setDraft((current) => normalizeFailoverPolicy({ ...current, ...value }));
setDirty(true);
};
const updateTarget = (role: 'primary' | 'reserve', patch: Partial<FailoverPolicy[typeof role]>) => {
const next = { ...draft[role], ...patch };
const profile = profiles.find(({ id }) => id === next.profileId);
if (patch.profileId !== undefined) next.serverId = profile?.desiredServerId || profile?.servers[0]?.id || '';
update({ [role]: next } as Partial<FailoverPolicy>);
const updateChecks = (change: (checks: FailoverPolicy['checks']) => FailoverPolicy['checks']) => {
setDraft((current) => normalizeFailoverPolicy({ ...current, checks: change(current.checks) }));
setDirty(true);
};
const updateTarget = (channel: 'primary' | 'reserve', optionId: string) => {
const target = channelOptions.find(({ id }) => id === optionId)?.target;
if (target) update({ [channel]: target } as Partial<FailoverPolicy>);
};
const role = snapshot.currentRole === 'primary' || snapshot.currentRole === 'reserve'
? snapshot.currentRole
@@ -173,7 +339,7 @@ export function FailoverPanel({
.find(({ id }) => id === target.profileId)?.servers.some(({ id }) => id === target.serverId);
const targetsValid = targetExists(draft.primary) && targetExists(draft.reserve)
&& (draft.primary.profileId !== draft.reserve.profileId || draft.primary.serverId !== draft.reserve.serverId);
const draftValid = Boolean(targetsValid && draft.checks.length);
const draftValid = !draft.enabled || Boolean(targetsValid && draft.checks.length);
const quietElapsed = activity?.quietSince
? Math.max(0, Date.now() - Date.parse(activity.quietSince))
: 0;
@@ -195,6 +361,19 @@ export function FailoverPanel({
setServiceError(error instanceof Error ? error.message : 'Проверьте адрес.');
}
};
const removeCheck = (serviceId: string) => {
const finish = () => updateChecks((checks) => checks.filter((check) => check.serviceId !== serviceId));
if (matchMedia('(prefers-reduced-motion: reduce)').matches) finish();
else setRemovingCheckId(serviceId);
};
const finishRemoveCheck = (serviceId: string) => {
const finish = () => flushSync(() => {
setRemovingCheckId('');
updateChecks((checks) => checks.filter((check) => check.serviceId !== serviceId));
});
if (!document.startViewTransition || matchMedia('(prefers-reduced-motion: reduce)').matches) finish();
else document.startViewTransition(finish);
};
return <Drawer
panelRef={feature.panelRef}
@@ -208,7 +387,19 @@ export function FailoverPanel({
>
<header className="client-failover-header">
<span>Gateway</span>
<h2>Резервный канал</h2>
<div className="client-failover-heading">
<h2>Резервный канал</h2>
<HarborSwitch
checked={draft.enabled}
label={draft.enabled ? 'Выключить резервный канал' : 'Включить резервный канал'}
disabled={blocked}
onChange={(enabled) => {
setOpenPicker('');
if (!enabled) setAddingService(false);
update({ enabled });
}}
/>
</div>
<p>Переключает только новые соединения. Уже открытые соединения Harbor не закрывает.</p>
</header>
@@ -216,15 +407,12 @@ export function FailoverPanel({
event.preventDefault();
void onSave(draft).then((result) => { if (result !== false) setDirty(false); });
}}>
<label className="client-failover-master">
<span><strong>Использовать резерв</strong><small>{draft.enabled ? 'Мониторинг включён' : 'Полностью пассивен'}</small></span>
<input type="checkbox" checked={draft.enabled} onChange={(event) => update({ enabled: event.target.checked })} />
</label>
{(['primary', 'reserve'] as const).map((channel) => {
const profile = profiles.find(({ id }) => id === draft[channel].profileId);
const health = snapshot[channel].health;
const missing = Boolean(snapshot[channel].target.profileId) && !targetExists(snapshot[channel].target);
const selectedId = channelOptions.find(({ target }) => (
target.profileId === draft[channel].profileId && target.serverId === draft[channel].serverId
))?.id || '';
const healthLabel = missing
? 'Цель недоступна'
: channel === 'primary' && snapshot.reason === 'failure-window'
@@ -237,69 +425,104 @@ export function FailoverPanel({
<span>{channel === 'primary' ? 'Основной' : 'Резервный'}</span>
<strong className={health === 'healthy' ? 'is-healthy' : health === 'unhealthy' || missing ? 'is-unhealthy' : ''}>{healthLabel}</strong>
</div>
<label><span>Подписка</span><select value={draft[channel].profileId} onChange={(event) => updateTarget(channel, { profileId: event.target.value })}>
<option value="">Не выбрана</option>
{profiles.map((item) => <option value={item.id} key={item.id}>{item.label}</option>)}
</select></label>
<label><span>Сервер</span><select value={draft[channel].serverId} onChange={(event) => updateTarget(channel, { serverId: event.target.value })} disabled={!profile}>
<option value="">Не выбран</option>
{profile?.servers.map((server) => <option value={server.id} key={server.id}>{server.label}</option>)}
</select></label>
<FailoverPicker
id={`client-failover-${channel}-options`}
label={draft[channel].profileId ? 'Цель недоступна' : 'Выбрать канал'}
value={selectedId}
options={channelPickerOptions[channel]}
open={openPicker === channel && !blocked && draft.enabled}
disabled={blocked || !draft.enabled || channelOptions.length === 0}
onOpenChange={(open) => setOpenPicker(open ? channel : '')}
onChange={(optionId) => updateTarget(channel, optionId)}
/>
</section>;
})}
<fieldset className="client-failover-services">
<legend>Что проверять</legend>
{services.map((service) => {
const check = draft.checks.find(({ serviceId }) => serviceId === service.id);
return <div className="client-failover-service" key={service.id}>
<label>
<input type="checkbox" checked={Boolean(check)} onChange={(event) => update({
checks: event.target.checked
? [...draft.checks, { serviceId: service.id, timeoutMs: 6_000 }]
: draft.checks.filter(({ serviceId }) => serviceId !== service.id),
})} />
<span>{service.label}</span>
</label>
{check && <label className="client-failover-service-timeout">
{draft.checks.map((check) => {
const service = services.find(({ id }) => check.serviceId === id);
const removing = removingCheckId === check.serviceId;
return <div
className={`client-failover-service${removing ? ' is-removing' : ''}`}
key={check.serviceId}
inert={removing ? true : undefined}
style={{ viewTransitionName: removing ? 'none' : `failover-check-${check.serviceId}` }}
onAnimationEnd={(event) => {
if (removing && event.target === event.currentTarget) finishRemoveCheck(check.serviceId);
}}
>
<span className="client-failover-service-name">{service?.label || 'Сервис недоступен'}</span>
<label className="client-failover-service-timeout">
<span>таймаут, сек</span>
<input
type="number"
min="2"
max="30"
aria-label={`Таймаут проверки: ${service.label}`}
aria-label={`Таймаут проверки: ${service?.label || 'сервис недоступен'}`}
value={seconds(check.timeoutMs)}
onChange={(event) => update({ checks: draft.checks.map((item) => item.serviceId === service.id
disabled={blocked || !draft.enabled}
onChange={(event) => updateChecks((checks) => checks.map((item) => item.serviceId === check.serviceId
? { ...item, timeoutMs: milliseconds(event.target.value, item.timeoutMs) }
: item) })}
: item))}
/>
</label>}
</label>
<button
className="client-failover-remove-service"
type="button"
aria-label={`Убрать проверку: ${service?.label || 'сервис недоступен'}`}
disabled={blocked || !draft.enabled || draft.checks.length === 1 || Boolean(removingCheckId)}
onClick={() => removeCheck(check.serviceId)}
>×</button>
</div>;
})}
{!addingService && <button type="button" className="client-failover-add-service" disabled={diagnostics.customServices.length >= MAX_CUSTOM_DIAGNOSTIC_SERVICES} onClick={() => setAddingService(true)}>+ Добавить HTTPS-сервис</button>}
{!addingService && <FailoverPicker
id="client-failover-service-options"
label="+ Добавить проверку"
value=""
options={servicePickerOptions}
open={openPicker === 'services' && !blocked && draft.enabled}
disabled={blocked || !draft.enabled || (
services.every((service) => draft.checks.some(({ serviceId }) => serviceId === service.id))
&& diagnostics.customServices.length >= MAX_CUSTOM_DIAGNOSTIC_SERVICES
)}
onOpenChange={(open) => setOpenPicker(open ? 'services' : '')}
onChange={(serviceId) => {
if (serviceId === '__new-service') setAddingService(true);
else updateChecks((checks) => [...checks, { serviceId, timeoutMs: 6_000 }]);
}}
/>}
{addingService && <div className="client-failover-service-editor">
<input aria-label="Название HTTPS-сервиса" placeholder="Название" value={serviceName} onChange={(event) => setServiceName(event.target.value)} />
<input aria-label="HTTPS-адрес сервиса" placeholder="https://example.com/health" value={serviceUrl} onChange={(event) => setServiceUrl(event.target.value)} />
<input aria-label="Название HTTPS-сервиса" placeholder="Название" disabled={blocked || !draft.enabled} value={serviceName} onChange={(event) => setServiceName(event.target.value)} />
<input aria-label="HTTPS-адрес сервиса" placeholder="https://example.com/health" disabled={blocked || !draft.enabled} value={serviceUrl} onChange={(event) => setServiceUrl(event.target.value)} />
{serviceError && <span role="alert">{serviceError}</span>}
<button type="button" onClick={() => void addService()}>Добавить</button>
<button type="button" onClick={() => { setAddingService(false); setServiceError(''); }}>Отмена</button>
<button type="button" disabled={blocked || !draft.enabled || !serviceUrl.trim()} onClick={() => void addService()}>Добавить</button>
<button type="button" disabled={blocked || !draft.enabled} onClick={() => { setAddingService(false); setServiceError(''); }}>Отмена</button>
</div>}
</fieldset>
<section className="client-failover-timing" aria-label="Пороги переключения">
<label><span>Проверять каждые, сек</span><input type="number" min="15" max="900" value={seconds(draft.intervalMs)} onChange={(event) => update({ intervalMs: milliseconds(event.target.value, draft.intervalMs) })} /></label>
<label><span>Сбой должен длиться, сек</span><input type="number" min={seconds(draft.intervalMs * 2)} max="1800" value={seconds(draft.failureWindowMs)} onChange={(event) => update({ failureWindowMs: milliseconds(event.target.value, draft.failureWindowMs) })} /></label>
<label><span>Восстановление, сек</span><input type="number" min="60" max="86400" value={seconds(draft.recoveryWindowMs)} onChange={(event) => update({ recoveryWindowMs: milliseconds(event.target.value, draft.recoveryWindowMs) })} /></label>
<label><span>Не переключать во время работы</span><input type="checkbox" checked={draft.trafficGuard.enabled} onChange={(event) => update({ trafficGuard: { ...draft.trafficGuard, enabled: event.target.checked } })} /></label>
<label><span>Тишина перед переключением, сек</span><input type="number" min="5" max="600" value={seconds(draft.trafficGuard.quietWindowMs)} onChange={(event) => update({ trafficGuard: { ...draft.trafficGuard, quietWindowMs: milliseconds(event.target.value, draft.trafficGuard.quietWindowMs) } })} /></label>
<label><span>Активный трафик, КБ/с</span><input type="number" min="1" max="102400" value={Math.round(draft.trafficGuard.thresholdBytesPerSecond / 1024)} onChange={(event) => update({ trafficGuard: { ...draft.trafficGuard, thresholdBytesPerSecond: Number(event.target.value) * 1024 } })} /></label>
<label><span>Проверять каждые, сек</span><input type="number" min="15" max="900" disabled={blocked || !draft.enabled} value={seconds(draft.intervalMs)} onChange={(event) => update({ intervalMs: milliseconds(event.target.value, draft.intervalMs) })} /></label>
<label><span>Сбой должен длиться, сек</span><input type="number" min={seconds(draft.intervalMs * 2)} max="1800" disabled={blocked || !draft.enabled} value={seconds(draft.failureWindowMs)} onChange={(event) => update({ failureWindowMs: milliseconds(event.target.value, draft.failureWindowMs) })} /></label>
<label><span>Восстановление, сек</span><input type="number" min="60" max="86400" disabled={blocked || !draft.enabled} value={seconds(draft.recoveryWindowMs)} onChange={(event) => update({ recoveryWindowMs: milliseconds(event.target.value, draft.recoveryWindowMs) })} /></label>
<div className="client-failover-traffic-switch">
<span><strong>Переключение во время работы</strong><small>{draft.trafficGuard.enabled ? 'Ждать тишины перед автоматическим переключением' : 'Переключать сразу после подтверждённого сбоя'}</small></span>
<HarborSwitch
checked={draft.trafficGuard.enabled}
label={draft.trafficGuard.enabled ? 'Не ждать завершения активной работы' : 'Ждать завершения активной работы'}
disabled={blocked || !draft.enabled}
onChange={(enabled) => update({ trafficGuard: { ...draft.trafficGuard, enabled } })}
/>
</div>
<label><span>Тишина перед переключением, сек</span><input type="number" min="5" max="600" disabled={blocked || !draft.enabled || !draft.trafficGuard.enabled} value={seconds(draft.trafficGuard.quietWindowMs)} onChange={(event) => update({ trafficGuard: { ...draft.trafficGuard, quietWindowMs: milliseconds(event.target.value, draft.trafficGuard.quietWindowMs) } })} /></label>
<label><span>Активный трафик, КБ/с</span><input type="number" min="1" max="102400" disabled={blocked || !draft.enabled || !draft.trafficGuard.enabled} value={Math.round(draft.trafficGuard.thresholdBytesPerSecond / 1024)} onChange={(event) => update({ trafficGuard: { ...draft.trafficGuard, thresholdBytesPerSecond: Number(event.target.value) * 1024 } })} /></label>
</section>
<details className="client-failover-advanced"><summary>Защита от повторных сбоев</summary>
<label><span>Минимум на резерве, сек</span><input type="number" min="60" max="86400" value={seconds(draft.minimumReserveMs)} onChange={(event) => update({ minimumReserveMs: milliseconds(event.target.value, draft.minimumReserveMs) })} /></label>
<label><span>Падений до карантина</span><input type="number" min="2" max="10" value={draft.flapProtection.count} onChange={(event) => update({ flapProtection: { ...draft.flapProtection, count: Number(event.target.value) } })} /></label>
<label><span>Окно повторных сбоев, ч</span><input type="number" min="1" max="72" value={Math.round(draft.flapProtection.windowMs / 3_600_000)} onChange={(event) => update({ flapProtection: { ...draft.flapProtection, windowMs: Number(event.target.value) * 3_600_000 } })} /></label>
<label><span>Карантин основного, мин</span><input type="number" min="10" max="10080" value={Math.round(draft.flapProtection.quarantineMs / 60_000)} onChange={(event) => update({ flapProtection: { ...draft.flapProtection, quarantineMs: Number(event.target.value) * 60_000 } })} /></label>
<label><span>Минимум на резерве, сек</span><input type="number" min="60" max="86400" disabled={blocked || !draft.enabled} value={seconds(draft.minimumReserveMs)} onChange={(event) => update({ minimumReserveMs: milliseconds(event.target.value, draft.minimumReserveMs) })} /></label>
<label><span>Падений до карантина</span><input type="number" min="2" max="10" disabled={blocked || !draft.enabled} value={draft.flapProtection.count} onChange={(event) => update({ flapProtection: { ...draft.flapProtection, count: Number(event.target.value) } })} /></label>
<label><span>Окно повторных сбоев, ч</span><input type="number" min="1" max="72" disabled={blocked || !draft.enabled} value={Math.round(draft.flapProtection.windowMs / 3_600_000)} onChange={(event) => update({ flapProtection: { ...draft.flapProtection, windowMs: Number(event.target.value) * 3_600_000 } })} /></label>
<label><span>Карантин основного, мин</span><input type="number" min="10" max="10080" disabled={blocked || !draft.enabled} value={Math.round(draft.flapProtection.quarantineMs / 60_000)} onChange={(event) => update({ flapProtection: { ...draft.flapProtection, quarantineMs: Number(event.target.value) * 60_000 } })} /></label>
</details>
<div className="client-failover-runtime">
@@ -312,7 +535,7 @@ export function FailoverPanel({
{activity && activity.blockers.length > 2 && <small>Ещё {activity.blockers.length - 2}</small>}
</div>
{!draftValid && <p className="client-failover-validation">Выберите два разных сервера. Они могут быть из одной подписки.</p>}
{!draftValid && <p className="client-failover-validation">Выберите два разных сервера и хотя бы одну проверку.</p>}
{confirmDiscard && <div className="client-failover-discard" role="alert">
<span>Отменить несохранённые изменения?</span>
<button type="button" onClick={() => { setDraft(snapshot.policy); setDirty(false); setConfirmDiscard(false); feature.beforeCloseRef.current = () => true; feature.close(); }}>Отменить изменения</button>