Add failover channel events to activity journal
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-27 14:36:08 +03:00
parent 4a566e082a
commit 8f2f418569
11 changed files with 388 additions and 77 deletions
+64 -14
View File
@@ -91,7 +91,42 @@ export function createFailoverService(dependencies: FailoverServiceDependencies)
let timer: NodeJS.Timeout | null = null; let timer: NodeJS.Timeout | null = null;
let collectorEnabled: boolean | null = null; let collectorEnabled: boolean | null = null;
let roundPromise: Promise<void> | null = null; let roundPromise: Promise<void> | null = null;
let roundGeneration: number | null = null;
let decisionMemory: FailoverDecisionMemory | undefined; let decisionMemory: FailoverDecisionMemory | undefined;
const healthMemory: Record<FailoverRole, 'healthy' | 'unhealthy' | undefined> = {
primary: undefined,
reserve: undefined,
};
function clearHealthMemory() {
healthMemory.primary = undefined;
healthMemory.reserve = undefined;
}
function recordHealthTransition(
role: FailoverRole,
health: FailoverHealth,
capturedGeneration?: number,
) {
if (capturedGeneration !== undefined && capturedGeneration !== generation) return;
if (health !== 'healthy' && health !== 'unhealthy') return;
const previous = healthMemory[role];
healthMemory[role] = health;
if (previous === health) return;
if (previous === undefined && health === 'healthy') return;
const type = health === 'unhealthy'
? role === 'primary' ? 'failover.primary_unavailable' : 'failover.reserve_unavailable'
: role === 'primary' ? 'failover.primary_recovered' : 'failover.reserve_recovered';
dependencies.onEvent?.({
type,
severity: health === 'unhealthy' ? 'warning' : 'info',
source: 'failover',
dedupeKey: null,
data: {
role,
reason: health === 'unhealthy' ? 'probe-failed' : 'probe-recovered',
},
});
}
let snapshot = createIdleFailoverSnapshot(dependencies.state.read().failoverPolicy, epoch, sequence); let snapshot = createIdleFailoverSnapshot(dependencies.state.read().failoverPolicy, epoch, sequence);
function appliedMatchesDesired(state: StoredState) { function appliedMatchesDesired(state: StoredState) {
@@ -133,6 +168,7 @@ export function createFailoverService(dependencies: FailoverServiceDependencies)
generation += 1; generation += 1;
clearTimer(); clearTimer();
decisionMemory = undefined; decisionMemory = undefined;
clearHealthMemory();
await disableCollector(); await disableCollector();
const idle = createIdleFailoverSnapshot(policy, epoch, sequence); const idle = createIdleFailoverSnapshot(policy, epoch, sequence);
if (passiveRole) { if (passiveRole) {
@@ -181,6 +217,7 @@ export function createFailoverService(dependencies: FailoverServiceDependencies)
const running = await dependencies.runtime.isRunning(); const running = await dependencies.runtime.isRunning();
if (!running || !state.appliedFailoverPolicy || !currentRole(state)) { if (!running || !state.appliedFailoverPolicy || !currentRole(state)) {
generation += 1; generation += 1;
clearHealthMemory();
clearTimer(); clearTimer();
await disableCollector(); await disableCollector();
const pending = activeSnapshot(state, 'idle'); const pending = activeSnapshot(state, 'idle');
@@ -355,6 +392,8 @@ export function createFailoverService(dependencies: FailoverServiceDependencies)
reserve = { health: 'unknown' as const, failingServiceIds: [] }; reserve = { health: 'unknown' as const, failingServiceIds: [] };
} }
if (capturedGeneration !== generation || !dependencies.state.read().failoverPolicy.enabled) return; if (capturedGeneration !== generation || !dependencies.state.read().failoverPolicy.enabled) return;
recordHealthTransition('primary', primary.health, capturedGeneration);
recordHealthTransition('reserve', reserve.health, capturedGeneration);
const activityResponse = record(await dependencies.dataplane.readFailoverActivity( const activityResponse = record(await dependencies.dataplane.readFailoverActivity(
policy.trafficGuard.thresholdBytesPerSecond, policy.trafficGuard.thresholdBytesPerSecond,
)); ));
@@ -437,15 +476,6 @@ export function createFailoverService(dependencies: FailoverServiceDependencies)
data: { reason: decision.reason }, data: { reason: decision.reason },
}); });
} }
if (primary.health === 'healthy' && previousSnapshot.primary.health === 'unhealthy') {
dependencies.onEvent?.({
type: 'failover.recovered',
severity: 'info',
source: 'failover',
dedupeKey: `failover.recovered:${state.revision}:primary`,
data: { role: 'primary', reason: decision.reason },
});
}
if (decision.switchTo) { if (decision.switchTo) {
try { try {
const switched = await dependencies.serialize(async () => { const switched = await dependencies.serialize(async () => {
@@ -522,11 +552,25 @@ export function createFailoverService(dependencies: FailoverServiceDependencies)
} }
} }
async function runRound() { async function runRound(): Promise<void> {
if (roundPromise) return roundPromise; if (roundPromise) {
const pending = roundPromise;
if (roundGeneration === generation) return pending;
try {
await pending;
} catch {
// The original caller owns the stale round error; continue with current-generation work.
}
if (roundPromise && roundPromise !== pending) return roundPromise;
return runRound();
}
const capturedGeneration = generation; const capturedGeneration = generation;
roundPromise = performRound(capturedGeneration).finally(() => { let trackedPromise: Promise<void>;
trackedPromise = performRound(capturedGeneration).finally(() => {
if (roundPromise === trackedPromise) {
roundPromise = null; roundPromise = null;
roundGeneration = null;
}
if (capturedGeneration === generation && snapshot.reason === 'checking-channels') { if (capturedGeneration === generation && snapshot.reason === 'checking-channels') {
const failed = activeSnapshot(dependencies.state.read(), 'error'); const failed = activeSnapshot(dependencies.state.read(), 'error');
failed.reason = 'health-unknown'; failed.reason = 'health-unknown';
@@ -541,7 +585,9 @@ export function createFailoverService(dependencies: FailoverServiceDependencies)
schedule(Math.min(policy.intervalMs, decisionDelay)); schedule(Math.min(policy.intervalMs, decisionDelay));
} }
}); });
return roundPromise; roundPromise = trackedPromise;
roundGeneration = capturedGeneration;
return trackedPromise;
} }
function save(value: unknown) { function save(value: unknown) {
@@ -574,6 +620,7 @@ export function createFailoverService(dependencies: FailoverServiceDependencies)
}; };
}); });
decisionMemory = undefined; decisionMemory = undefined;
if (before.failoverPolicy.enabled !== policy.enabled) clearHealthMemory();
if (before.failoverPolicy.enabled !== policy.enabled) { if (before.failoverPolicy.enabled !== policy.enabled) {
dependencies.onEvent?.({ dependencies.onEvent?.({
type: policy.enabled ? 'failover.enabled' : 'failover.disabled', type: policy.enabled ? 'failover.enabled' : 'failover.disabled',
@@ -637,7 +684,7 @@ export function createFailoverService(dependencies: FailoverServiceDependencies)
if (!state.failoverPolicy.enabled || !state.appliedFailoverPolicy || !currentRole(state)) { if (!state.failoverPolicy.enabled || !state.appliedFailoverPolicy || !currentRole(state)) {
throw new HarborError('REQUEST_INVALID'); throw new HarborError('REQUEST_INVALID');
} }
generation += 1; const capturedGeneration = ++generation;
clearTimer(); clearTimer();
const checkedAt = now().toISOString(); const checkedAt = now().toISOString();
publish({ ...snapshot, reason: 'checking-channels' }); publish({ ...snapshot, reason: 'checking-channels' });
@@ -652,6 +699,9 @@ export function createFailoverService(dependencies: FailoverServiceDependencies)
primary = { health: 'unknown' as const, failingServiceIds: [] }; primary = { health: 'unknown' as const, failingServiceIds: [] };
reserve = { health: 'unknown' as const, failingServiceIds: [] }; reserve = { health: 'unknown' as const, failingServiceIds: [] };
} }
if (capturedGeneration !== generation || !dependencies.state.read().failoverPolicy.enabled) return;
recordHealthTransition('primary', primary.health, capturedGeneration);
recordHealthTransition('reserve', reserve.health, capturedGeneration);
const next = activeSnapshot(dependencies.state.read(), 'observing'); const next = activeSnapshot(dependencies.state.read(), 'observing');
next.primary = { ...next.primary, ...primary, checkedAt, stateSince: checkedAt }; next.primary = { ...next.primary, ...primary, checkedAt, stateSince: checkedAt };
next.reserve = { ...next.reserve, ...reserve, checkedAt, stateSince: checkedAt }; next.reserve = { ...next.reserve, ...reserve, checkedAt, stateSince: checkedAt };
+8 -1
View File
@@ -6,7 +6,10 @@ export const ACTIVITY_EVENT_TYPES = [
'subscription.added', 'subscription.refreshed', 'subscription.refresh_failed', 'subscription.deleted', 'subscription.added', 'subscription.refreshed', 'subscription.refresh_failed', 'subscription.deleted',
'failover.enabled', 'failover.disabled', 'failover.paused', 'failover.resumed', 'failover.enabled', 'failover.disabled', 'failover.paused', 'failover.resumed',
'failover.waiting_for_idle', 'failover.switched', 'failover.switch_failed', 'failover.waiting_for_idle', 'failover.switched', 'failover.switch_failed',
'failover.both_unhealthy', 'failover.recovered', 'journal.recovered', 'failover.both_unhealthy',
'failover.primary_unavailable', 'failover.primary_recovered',
'failover.reserve_unavailable', 'failover.reserve_recovered',
'failover.recovered', 'journal.recovered',
] as const; ] as const;
export type ActivityEventType = typeof ACTIVITY_EVENT_TYPES[number]; export type ActivityEventType = typeof ACTIVITY_EVENT_TYPES[number];
@@ -49,6 +52,10 @@ const ALLOWED_DATA_KEYS: Record<ActivityEventType, readonly string[]> = {
'failover.switched': ['fromRole', 'toRole', 'primaryLabel', 'reserveLabel', 'reason', 'manual'], 'failover.switched': ['fromRole', 'toRole', 'primaryLabel', 'reserveLabel', 'reason', 'manual'],
'failover.switch_failed': ['fromRole', 'toRole', 'reason', 'errorCode'], 'failover.switch_failed': ['fromRole', 'toRole', 'reason', 'errorCode'],
'failover.both_unhealthy': ['reason'], 'failover.both_unhealthy': ['reason'],
'failover.primary_unavailable': ['role', 'reason'],
'failover.primary_recovered': ['role', 'reason'],
'failover.reserve_unavailable': ['role', 'reason'],
'failover.reserve_recovered': ['role', 'reason'],
'failover.recovered': ['role', 'reason'], 'failover.recovered': ['role', 'reason'],
'journal.recovered': [], 'journal.recovered': [],
}; };
+3 -3
View File
@@ -1,7 +1,7 @@
export const HARBOR_VERSIONS = Object.freeze({ export const HARBOR_VERSIONS = Object.freeze({
macClient: '0.30.6', macClient: '0.31.0',
gatewayClient: '0.31.6', gatewayClient: '0.32.0',
gatewayBackend: '0.31.0', gatewayBackend: '0.32.0',
}); });
export interface ParsedVersion { export interface ParsedVersion {
@@ -1,6 +1,6 @@
import { useEffect, useRef, useState } from 'react'; import { useEffect, useRef, useState } from 'react';
import { assertActivityJournalPage, type ActivityJournalEvent } from '../../../shared/activityJournal.js'; import { assertActivityJournalPage, type ActivityJournalEvent } from '../../../shared/activityJournal.js';
import { compactActivityJournalEvents, refreshStreakCopy, type ActivityJournalDisplayItem } from './activityJournalModel.js'; import { compactActivityJournalEvents, activityJournalEventCopy, refreshStreakCopy, type ActivityJournalDisplayItem } from './activityJournalModel.js';
import { Drawer } from '../../ui/Drawer.js'; import { Drawer } from '../../ui/Drawer.js';
import { RailAction } from '../../ui/RailAction.js'; import { RailAction } from '../../ui/RailAction.js';
@@ -56,28 +56,19 @@ export function ActivityJournalToggle({ feature, open, onToggle }: {
</RailAction>; </RailAction>;
} }
function eventCopy(event: ActivityJournalEvent) { function eventTargetRole(event: ActivityJournalEvent) {
const value = event.data; if (event.type === 'failover.switched') return event.data.toRole;
const copies: Record<string, [string, string]> = { if (
'connection.started': ['VPN включён', [value.profileLabel, value.serverLabel].filter(Boolean).join(' · ')], event.type === 'failover.reserve_unavailable'
'connection.stopped': ['VPN выключен', 'Остановлен пользователем'], || event.type === 'failover.reserve_recovered'
'connection.failed': ['VPN не запущен', String(value.errorCode || '')], || (event.type === 'failover.recovered' && event.data.role === 'reserve')
'subscription.added': ['Подписка добавлена', `${value.profileLabel || ''} · серверов: ${value.serverCount || 0}`], ) return 'reserve';
'subscription.refreshed': ['Подписка обновлена', `${value.profileLabel || ''} · серверов: ${value.serverCount || 0} · +${value.added || 0} / ${value.removed || 0}`], if (
'subscription.refresh_failed': ['Подписка не обновлена', `${value.profileLabel || ''} · ${value.errorCode || ''}`], event.type === 'failover.primary_unavailable'
'subscription.deleted': ['Подписка удалена', String(value.profileLabel || '')], || event.type === 'failover.primary_recovered'
'failover.enabled': ['Резервный канал включён', 'Мониторинг начнётся после активации dual-config'], || (event.type === 'failover.recovered' && event.data.role === 'primary')
'failover.disabled': ['Резервный канал выключен', 'Автоматика полностью остановлена'], ) return 'primary';
'failover.paused': ['Автопереключение на паузе', 'Проверки продолжаются'], return undefined;
'failover.resumed': ['Автопереключение возобновлено', ''],
'failover.waiting_for_idle': ['Переключение отложено', 'Обнаружен активный трафик'],
'failover.switched': ['Новые соединения переключены', `${value.fromRole || ''}${value.toRole || ''} · ${value.reason || ''}`],
'failover.switch_failed': ['Переключение не выполнено', String(value.errorCode || '')],
'failover.both_unhealthy': ['Оба канала недоступны', 'Текущий маршрут сохранён'],
'failover.recovered': ['Основной канал восстановлен', String(value.reason || '')],
'journal.recovered': ['Журнал восстановлен', 'Повреждённый файл сохранён отдельно'],
};
return copies[event.type] || ['Системное событие', ''];
} }
function dayLabel(value: string) { function dayLabel(value: string) {
@@ -155,13 +146,13 @@ export function ActivityJournalPanel({ feature, loadPage }: {
<h3>{group.label}</h3> <h3>{group.label}</h3>
<ol>{group.items.map((item) => { <ol>{group.items.map((item) => {
const { event } = item; const { event } = item;
const [title, details] = refreshStreakCopy(item) || eventCopy(event); const [title, details] = refreshStreakCopy(item) || activityJournalEventCopy(event);
return <li return <li
key={event.id} key={event.id}
className="client-journal-event" className="client-journal-event"
data-event-type={event.type} data-event-type={event.type}
data-severity={event.severity} data-severity={event.severity}
data-target-role={event.type === 'failover.switched' ? event.data.toRole : undefined} data-target-role={eventTargetRole(event)}
> >
<div className="client-journal-time"><time dateTime={event.occurredAt}>{new Intl.DateTimeFormat('ru-RU', { hour: '2-digit', minute: '2-digit' }).format(new Date(event.occurredAt))}</time><span>{event.source}</span></div> <div className="client-journal-time"><time dateTime={event.occurredAt}>{new Intl.DateTimeFormat('ru-RU', { hour: '2-digit', minute: '2-digit' }).format(new Date(event.occurredAt))}</time><span>{event.source}</span></div>
<div><strong>{title}</strong>{details && <span>{details}</span>}{event.severity !== 'info' && <em>{event.severity === 'error' ? 'Ошибка' : 'Внимание'}</em>}</div> <div><strong>{title}</strong>{details && <span>{details}</span>}{event.severity !== 'info' && <em>{event.severity === 'error' ? 'Ошибка' : 'Внимание'}</em>}</div>
@@ -87,3 +87,35 @@ export function refreshStreakCopy(item: ActivityJournalDisplayItem): [string, st
`${formatObservedDuration(streak.firstOccurredAt, item.event.occurredAt)} всё хорошо · ${updates} · ${profile}`, `${formatObservedDuration(streak.firstOccurredAt, item.event.occurredAt)} всё хорошо · ${updates} · ${profile}`,
]; ];
} }
export function activityJournalEventCopy(event: ActivityJournalEvent): [string, string] {
const value = event.data;
const copies: Record<string, [string, string]> = {
'connection.started': ['VPN включён', [value.profileLabel, value.serverLabel].filter(Boolean).join(' · ')],
'connection.stopped': ['VPN выключен', 'Остановлен пользователем'],
'connection.failed': ['VPN не запущен', String(value.errorCode || '')],
'subscription.added': ['Подписка добавлена', `${value.profileLabel || ''} · серверов: ${value.serverCount || 0}`],
'subscription.refreshed': ['Подписка обновлена', `${value.profileLabel || ''} · серверов: ${value.serverCount || 0} · +${value.added || 0} / ${value.removed || 0}`],
'subscription.refresh_failed': ['Подписка не обновлена', `${value.profileLabel || ''} · ${value.errorCode || ''}`],
'subscription.deleted': ['Подписка удалена', String(value.profileLabel || '')],
'failover.enabled': ['Резервный канал включён', 'Мониторинг начнётся после активации dual-config'],
'failover.disabled': ['Резервный канал выключен', 'Автоматика полностью остановлена'],
'failover.paused': ['Автопереключение на паузе', 'Проверки продолжаются'],
'failover.resumed': ['Автопереключение возобновлено', ''],
'failover.waiting_for_idle': ['Переключение отложено', 'Обнаружен активный трафик'],
'failover.switched': ['Новые соединения переключены', `${value.fromRole || ''}${value.toRole || ''}`],
'failover.switch_failed': ['Переключение не выполнено', String(value.errorCode || '')],
'failover.both_unhealthy': ['Оба канала недоступны', 'Текущий маршрут сохранён'],
'failover.primary_unavailable': ['Основной канал недоступен', 'Проверки канала не пройдены'],
'failover.reserve_unavailable': ['Резервный канал недоступен', 'Проверки канала не пройдены'],
'failover.primary_recovered': ['Основной канал восстановлен', 'Проверки канала снова проходят успешно'],
'failover.reserve_recovered': ['Резервный канал восстановлен', 'Проверки канала снова проходят успешно'],
'journal.recovered': ['Журнал восстановлен', 'Повреждённый файл сохранён отдельно'],
};
if (event.type === 'failover.recovered') {
return value.role === 'reserve'
? ['Резервный канал восстановлен', 'Проверки канала снова проходят успешно']
: ['Основной канал восстановлен', 'Проверки канала снова проходят успешно'];
}
return copies[event.type] || ['Системное событие', ''];
}
+7 -3
View File
@@ -9,8 +9,9 @@
.client-journal-groups { display: grid; gap: 26px; margin: 0 8px; } .client-journal-groups { display: grid; gap: 26px; margin: 0 8px; }
.client-journal-groups section { display: grid; gap: 7px; } .client-journal-groups section { display: grid; gap: 7px; }
.client-journal-groups h3 { margin: 0; } .client-journal-groups h3 { margin: 0; }
.client-journal-groups ol { display: grid; margin: 0; padding: 0; } .client-journal-groups ol { position: relative; display: grid; margin: 0; padding: 0; }
.client-journal-groups li { position: relative; min-height: 58px; display: grid; grid-template-columns: 52px minmax(0, 1fr); gap: 14px; align-items: start; padding: 10px 0; border-top: 1px solid color-mix(in oklch, var(--client-border) 48%, transparent); } .client-journal-groups ol::before { content: ''; position: absolute; inset: 0 auto 0 -8px; z-index: 0; width: 1px; background: color-mix(in oklch, var(--client-border) 48%, transparent); }
.client-journal-groups li { position: relative; min-height: 58px; display: grid; grid-template-columns: 52px minmax(0, 1fr); gap: 14px; align-items: start; padding: 10px 0; }
.client-journal-time, .client-journal-groups li > div:last-child { min-width: 0; display: grid; gap: 3px; } .client-journal-time, .client-journal-groups li > div:last-child { min-width: 0; display: grid; gap: 3px; }
.client-journal-time time { color: var(--client-text); font: var(--type-data); font-variant-numeric: var(--numeric-tabular); letter-spacing: var(--type-data-tracking); text-transform: var(--type-data-transform); } .client-journal-time time { color: var(--client-text); font: var(--type-data); font-variant-numeric: var(--numeric-tabular); letter-spacing: var(--type-data-tracking); text-transform: var(--type-data-transform); }
.client-journal-time span, .client-journal-groups li span { color: var(--client-muted); font: var(--type-label); letter-spacing: var(--type-label-tracking); text-transform: var(--type-label-transform); overflow-wrap: anywhere; } .client-journal-time span, .client-journal-groups li span { color: var(--client-muted); font: var(--type-label); letter-spacing: var(--type-label-tracking); text-transform: var(--type-label-transform); overflow-wrap: anywhere; }
@@ -18,15 +19,18 @@
.client-journal-groups li strong { font: var(--type-body); letter-spacing: var(--type-body-tracking); text-transform: var(--type-body-transform); } .client-journal-groups li strong { font: var(--type-body); letter-spacing: var(--type-body-tracking); text-transform: var(--type-body-transform); }
.client-journal-groups li em { width: fit-content; color: var(--client-journal-tone); font: var(--type-label); font-style: normal; letter-spacing: var(--type-label-tracking); text-transform: var(--type-label-transform); } .client-journal-groups li em { width: fit-content; color: var(--client-journal-tone); font: var(--type-label); font-style: normal; letter-spacing: var(--type-label-tracking); text-transform: var(--type-label-transform); }
.client-journal-event { --client-journal-tone: var(--client-muted); } .client-journal-event { --client-journal-tone: var(--client-muted); }
.client-journal-event::before { content: ''; position: absolute; inset: 9px auto 9px -8px; width: 3px; border-radius: 999px; background: var(--client-journal-tone); } .client-journal-event::before { content: ''; position: absolute; inset: 15px auto auto -11.5px; z-index: 1; width: 8px; height: 8px; border-radius: 50%; background: var(--client-journal-tone); }
.client-journal-event .client-journal-time span { color: var(--client-journal-tone); } .client-journal-event .client-journal-time span { color: var(--client-journal-tone); }
.client-journal-event[data-event-type='connection.started'], .client-journal-event[data-event-type='connection.started'],
.client-journal-event[data-event-type='subscription.added'], .client-journal-event[data-event-type='subscription.added'],
.client-journal-event[data-event-type='subscription.refreshed'], .client-journal-event[data-event-type='subscription.refreshed'],
.client-journal-event[data-event-type='failover.enabled'], .client-journal-event[data-event-type='failover.enabled'],
.client-journal-event[data-event-type='failover.resumed'], .client-journal-event[data-event-type='failover.resumed'],
.client-journal-event[data-event-type='failover.primary_recovered'],
.client-journal-event[data-event-type='failover.recovered'], .client-journal-event[data-event-type='failover.recovered'],
.client-journal-event[data-event-type='failover.switched'][data-target-role='primary'] { --client-journal-tone: var(--harbor-connect); } .client-journal-event[data-event-type='failover.switched'][data-target-role='primary'] { --client-journal-tone: var(--harbor-connect); }
.client-journal-event[data-event-type='failover.reserve_recovered'],
.client-journal-event[data-event-type='failover.recovered'][data-target-role='reserve'],
.client-journal-event[data-event-type='failover.switched'][data-target-role='reserve'] { --client-journal-tone: var(--harbor-gateway); } .client-journal-event[data-event-type='failover.switched'][data-target-role='reserve'] { --client-journal-tone: var(--harbor-gateway); }
.client-journal-event[data-event-type='failover.waiting_for_idle'], .client-journal-event[data-event-type='failover.waiting_for_idle'],
.client-journal-event[data-event-type='failover.paused'], .client-journal-event[data-event-type='failover.paused'],
@@ -128,6 +128,53 @@ test('journal exposes a latched write failure until a later append succeeds', (t
assert.equal(service.page().storage.status, 'ready'); assert.equal(service.page().storage.status, 'ready');
}); });
test('schema version 1 keeps legacy recovery and accepts per-channel health events', (t) => {
const filePath = fixture(t);
const occurredAt = '2026-08-19T09:00:00.000Z';
fs.writeFileSync(filePath, JSON.stringify({
schemaVersion: 1,
events: [{
id: '00000000-0000-4000-8000-000000000001',
occurredAt,
type: 'failover.recovered',
severity: 'info',
source: 'failover',
dedupeKey: null,
data: { role: 'primary', reason: 'primary-recovered' },
}],
}));
let clock = new Date('2026-08-19T10:00:00.000Z');
const service = createActivityJournalService({ filePath, now: () => clock });
const inputs = [
['failover.primary_unavailable', 'primary', 'warning', 'probe-failed'],
['failover.primary_recovered', 'primary', 'info', 'probe-recovered'],
['failover.reserve_unavailable', 'reserve', 'warning', 'probe-failed'],
['failover.reserve_recovered', 'reserve', 'info', 'probe-recovered'],
];
for (const [type, role, severity, reason] of inputs) {
service.append({
type,
severity,
source: 'failover',
dedupeKey: null,
data: { role, reason },
});
clock = new Date(clock.getTime() + 1_000);
}
const page = service.page();
assert.deepEqual(page.events.map(({ type }) => type), [
'failover.reserve_recovered',
'failover.reserve_unavailable',
'failover.primary_recovered',
'failover.primary_unavailable',
'failover.recovered',
]);
assert.deepEqual(page.events.at(-1).data, { role: 'primary', reason: 'primary-recovered' });
assert.equal(page.retentionDays, 30);
assert.equal(JSON.parse(fs.readFileSync(filePath, 'utf8')).schemaVersion, 1);
});
test('journal page parser rejects malformed wire data and strips unknown event fields', (t) => { test('journal page parser rejects malformed wire data and strips unknown event fields', (t) => {
const service = createActivityJournalService({ filePath: fixture(t) }); const service = createActivityJournalService({ filePath: fixture(t) });
service.append(event('wire')); service.append(event('wire'));
+145 -12
View File
@@ -282,7 +282,9 @@ test('runtime rollback restores the role from applied truth even while disabled'
test('an in-flight observation is discarded after failover is disabled', async () => { test('an in-flight observation is discarded after failover is disabled', async () => {
const pending = []; const pending = [];
const events = [];
const testHarness = harness(serviceState(), { const testHarness = harness(serviceState(), {
onEvent: (event) => events.push(event),
dataplane: { dataplane: {
checkConfig: async () => ({}), checkConfig: async () => ({}),
runFailoverProbe: (role) => new Promise((resolve) => pending.push({ role, resolve })), runFailoverProbe: (role) => new Promise((resolve) => pending.push({ role, resolve })),
@@ -302,6 +304,7 @@ test('an in-flight observation is discarded after failover is disabled', async (
assert.equal(testHarness.read().failoverPolicy.enabled, false); assert.equal(testHarness.read().failoverPolicy.enabled, false);
assert.equal(testHarness.calls.some((call) => call.startsWith('select:reserve')), false); assert.equal(testHarness.calls.some((call) => call.startsWith('select:reserve')), false);
assert.deepEqual(testHarness.calls.filter((call) => call.startsWith('activity:')), ['activity:true', 'activity:true', 'activity:false']); assert.deepEqual(testHarness.calls.filter((call) => call.startsWith('activity:')), ['activity:true', 'activity:true', 'activity:false']);
assert.deepEqual(events.filter(({ type }) => /_(?:unavailable|recovered)$/.test(type)), []);
}); });
test('one channel probe failure does not erase the other channel health', async () => { test('one channel probe failure does not erase the other channel health', async () => {
@@ -595,7 +598,7 @@ test('disabling on reserve preserves it as the next ordinary single-channel targ
assert.equal(testHarness.service.snapshot().activation, 'passive-loaded'); assert.equal(testHarness.service.snapshot().activation, 'passive-loaded');
}); });
test('significant health states append once without logging every observation', async () => { test('background health transitions cover both channels without duplicate observations', async () => {
let clock = 0; let clock = 0;
const health = { primary: 'unavailable', reserve: 'available' }; const health = { primary: 'unavailable', reserve: 'available' };
const events = []; const events = [];
@@ -611,23 +614,153 @@ test('significant health states append once without logging every observation',
readFailoverActivity: async () => ({ activity: { state: 'quiet', observedAt: new Date(clock).toISOString() } }), readFailoverActivity: async () => ({ activity: { state: 'quiet', observedAt: new Date(clock).toISOString() } }),
}, },
}); });
await testHarness.service.reconcile(); const healthEvents = () => events.filter(({ type }) => /_(?:unavailable|recovered)$/.test(type));
const round = async () => {
await testHarness.service.runRound(); await testHarness.service.runRound();
clock = 30_000; clock += 1_000;
};
await testHarness.service.reconcile();
await round();
await round();
health.reserve = 'unavailable';
await round();
await round();
health.primary = 'available';
await round();
health.primary = 'unavailable';
await round();
health.reserve = 'available';
await round();
health.reserve = 'unavailable';
await round();
assert.deepEqual(healthEvents().map(({ type, severity, data }) => ({ type, severity, role: data.role })), [
{ type: 'failover.primary_unavailable', severity: 'warning', role: 'primary' },
{ type: 'failover.reserve_unavailable', severity: 'warning', role: 'reserve' },
{ type: 'failover.primary_recovered', severity: 'info', role: 'primary' },
{ type: 'failover.primary_unavailable', severity: 'warning', role: 'primary' },
{ type: 'failover.reserve_recovered', severity: 'info', role: 'reserve' },
{ type: 'failover.reserve_unavailable', severity: 'warning', role: 'reserve' },
]);
assert.ok(healthEvents().every(({ dedupeKey }) => dedupeKey === null));
assert.equal(events.some(({ type }) => type === 'failover.recovered'), false);
assert.equal(events.filter(({ type }) => type === 'failover.both_unhealthy').length, 3);
});
test('activity read failure does not hide completed channel health transitions', async () => {
const events = [];
const testHarness = harness(serviceState(), {
onEvent: (event) => events.push(event),
dataplane: {
checkConfig: async () => ({}),
runFailoverProbe: async (role) => ({
vpn: { sites: [{ status: role === 'primary' ? 'unavailable' : 'available' }] },
}),
readFailoverSelector: async () => ({ role: 'primary' }),
selectFailoverRole: async (role) => ({ role }),
setFailoverActivityEnabled: async () => {},
readFailoverActivity: async () => { throw new Error('activity unavailable'); },
},
});
await testHarness.service.reconcile();
await assert.rejects(testHarness.service.runRound(), /activity unavailable/);
assert.deepEqual(events.map(({ type }) => type), ['failover.primary_unavailable']);
assert.equal(events.some(({ type }) => ['failover.waiting_for_idle', 'failover.both_unhealthy', 'failover.switched', 'failover.switch_failed'].includes(type)), false);
});
test('manual check does not strand monitoring behind a stale background round', async () => {
const pending = [];
const scheduled = [];
let holdBackground = true;
let probeCalls = 0;
const testHarness = harness(serviceState(), {
scheduler: {
setTimeout: (callback) => {
scheduled.push(callback);
return { unref() {} };
},
clearTimeout: () => {},
},
dataplane: {
checkConfig: async () => ({}),
runFailoverProbe: (role) => {
probeCalls += 1;
if (holdBackground) {
return new Promise((resolve) => pending.push({ role, resolve }));
}
return Promise.resolve({ vpn: { sites: [{ status: 'available' }] } });
},
readFailoverSelector: async () => ({ role: 'primary' }),
selectFailoverRole: async (role) => ({ role }),
setFailoverActivityEnabled: async () => {},
readFailoverActivity: async () => ({ activity: { state: 'quiet', observedAt: new Date().toISOString() } }),
},
});
await testHarness.service.reconcile();
const oldRound = testHarness.service.runRound();
await new Promise(setImmediate);
assert.equal(pending.length, 4);
holdBackground = false;
await testHarness.service.checkNow();
assert.equal(probeCalls, 8);
scheduled.at(-1)();
for (const probe of pending) {
probe.resolve({ vpn: { sites: [{ status: 'available' }] } });
}
await oldRound;
await new Promise(setImmediate);
await new Promise(setImmediate);
assert.equal(probeCalls, 12);
});
test('manual and background checks share channel transition memory', async () => {
const health = { primary: 'available', reserve: 'available' };
const events = [];
const testHarness = harness(serviceState(), {
onEvent: (event) => events.push(event),
dataplane: {
checkConfig: async () => ({}),
runFailoverProbe: async (role) => ({ vpn: { sites: [{ status: health[role] }] } }),
readFailoverSelector: async () => ({ role: 'primary' }),
selectFailoverRole: async (role) => ({ role }),
setFailoverActivityEnabled: async () => {},
readFailoverActivity: async () => ({ activity: { state: 'quiet', observedAt: new Date().toISOString() } }),
},
});
const healthTypes = () => events
.filter(({ type }) => /_(?:unavailable|recovered)$/.test(type))
.map(({ type }) => type);
await testHarness.service.reconcile();
await testHarness.service.checkNow();
assert.deepEqual(healthTypes(), []);
health.primary = 'unavailable';
await testHarness.service.checkNow();
assert.deepEqual(healthTypes(), ['failover.primary_unavailable']);
await testHarness.service.runRound();
assert.deepEqual(healthTypes(), ['failover.primary_unavailable']);
health.primary = 'available';
await testHarness.service.checkNow();
health.primary = 'unavailable';
await testHarness.service.runRound(); await testHarness.service.runRound();
health.reserve = 'unavailable'; health.reserve = 'unavailable';
clock = 31_000; await testHarness.service.checkNow();
await testHarness.service.runRound(); await testHarness.service.runRound();
clock = 32_000; health.reserve = 'available';
await testHarness.service.runRound(); await testHarness.service.checkNow();
health.primary = 'available'; health.reserve = 'unavailable';
clock = 33_000;
await testHarness.service.runRound(); await testHarness.service.runRound();
assert.deepEqual(events.map(({ type }) => type), [ assert.deepEqual(healthTypes(), [
'failover.waiting_for_idle', 'failover.primary_unavailable',
'failover.both_unhealthy', 'failover.primary_recovered',
'failover.recovered', 'failover.primary_unavailable',
'failover.reserve_unavailable',
'failover.reserve_recovered',
'failover.reserve_unavailable',
]); ]);
}); });
@@ -16,22 +16,40 @@ test('journal is the last Gateway-only drawer and refreshes whenever it opens',
assert.match(feature, /assertActivityJournalPage\(await loadPage\(cursor\)\)/); assert.match(feature, /assertActivityJournalPage\(await loadPage\(cursor\)\)/);
}); });
test('journal presents 30-day grouped history with refresh, pagination and stable states', () => { test('journal presents a semantic responsive timeline with stable states', () => {
assert.match(feature, /Важные события хранятся 30 дней/); assert.match(feature, /Важные события хранятся 30 дней/);
assert.match(feature, /Сегодня[\s\S]*Вчера/); assert.match(feature, /Сегодня[\s\S]*Вчера/);
assert.match(feature, /Обновить журнал/); assert.match(feature, /Обновить журнал/);
assert.match(feature, /M5 8V4m0 4h4/);
assert.match(feature, /Показать ещё/); assert.match(feature, /Показать ещё/);
assert.match(feature, /Журнал временно недоступен[\s\S]*Повторить/); assert.match(feature, /Журнал временно недоступен[\s\S]*Повторить/);
assert.match(styles, /\.client-journal-skeleton/); assert.match(styles, /\.client-journal-skeleton/);
assert.match(styles, /@media \(prefers-reduced-motion: reduce\)/);
assert.match(feature, /compactActivityJournalEvents\(events\)/); assert.match(feature, /compactActivityJournalEvents\(events\)/);
assert.match(model, /Подписки обновлялись без ошибок/); assert.match(model, /Подписки обновлялись без ошибок/);
assert.match(feature, /<ol>[\s\S]*<li[\s\S]*<time dateTime=\{event\.occurredAt\}/);
assert.match(feature, /data-event-type=\{event\.type\}[\s\S]*data-severity=\{event\.severity\}[\s\S]*data-target-role=/); assert.match(feature, /data-event-type=\{event\.type\}[\s\S]*data-severity=\{event\.severity\}[\s\S]*data-target-role=/);
assert.match(styles, /\.client-journal-event::before \{[^}]*background: var\(--client-journal-tone\); \}/);
const rowRule = styles.match(/\.client-journal-groups li \{[^}]*\}/)?.[0] || '';
const lineRule = styles.match(/\.client-journal-groups ol::before \{[^}]*\}/)?.[0] || '';
const dotRule = styles.match(/\.client-journal-event::before \{[^}]*\}/)?.[0] || '';
assert.match(rowRule, /min-height: 58px/);
assert.match(rowRule, /grid-template-columns: 52px minmax\(0, 1fr\)/);
assert.doesNotMatch(rowRule, /border-top/);
assert.match(lineRule, /width: 1px/);
assert.match(lineRule, /inset: 0 auto 0 -8px/);
assert.match(lineRule, /background: color-mix\(in oklch, var\(--client-border\) 48%, transparent\)/);
assert.doesNotMatch(lineRule, /--client-journal-tone|animation|transition/);
assert.match(dotRule, /width: 8px/);
assert.match(dotRule, /height: 8px/);
assert.match(dotRule, /border-radius: 50%/);
assert.match(dotRule, /inset: 15px auto auto -11\.5px/);
assert.match(dotRule, /background: var\(--client-journal-tone\)/);
assert.doesNotMatch(dotRule, /animation|transition/);
assert.match(styles, /\.client-journal-event \.client-journal-time span \{ color: var\(--client-journal-tone\); \}/); assert.match(styles, /\.client-journal-event \.client-journal-time span \{ color: var\(--client-journal-tone\); \}/);
assert.match(styles, /\[data-event-type='subscription\.refreshed'\][\s\S]*\[data-event-type='failover\.recovered'\][\s\S]*--client-journal-tone: var\(--harbor-connect\)/); assert.match(styles, /\[data-event-type='failover\.primary_recovered'\][\s\S]*--client-journal-tone: var\(--harbor-connect\)/);
assert.match(styles, /\[data-target-role='reserve'\] \{ --client-journal-tone: var\(--harbor-gateway\); \}/); assert.match(styles, /\[data-event-type='failover\.reserve_recovered'\][\s\S]*--client-journal-tone: var\(--harbor-gateway\)/);
assert.match(styles, /\[data-event-type='failover\.waiting_for_idle'\][\s\S]*\[data-severity='warning'\] \{ --client-journal-tone: oklch\(0\.68 0\.14 72\); \}/); assert.match(styles, /\[data-severity='warning'\] \{ --client-journal-tone: oklch\(0\.68 0\.14 72\); \}/);
assert.match(styles, /\[data-severity='error'\] \{ --client-journal-tone: oklch\(0\.68 0\.15 28\); \}/); assert.match(styles, /\[data-severity='error'\] \{ --client-journal-tone: oklch\(0\.68 0\.15 28\); \}/);
assert.match(styles, /@media \(max-width: 560px\) \{[\s\S]*?\.client-journal-groups li \{[^}]*grid-template-columns: 1fr;[^}]*\}[\s\S]*?\.client-journal-time \{[^}]*display: flex;/);
assert.match(styles, /@media \(prefers-reduced-motion: reduce\) \{[^}]*animation: none;/);
}); });
+29
View File
@@ -2,6 +2,7 @@ import assert from 'node:assert/strict';
import test from 'node:test'; import test from 'node:test';
import { import {
activityJournalEventCopy,
compactActivityJournalEvents, compactActivityJournalEvents,
refreshStreakCopy, refreshStreakCopy,
} from '../../.test-dist/src/web/features/activity-journal/activityJournalModel.js'; } from '../../.test-dist/src/web/features/activity-journal/activityJournalModel.js';
@@ -75,3 +76,31 @@ test('one-profile streak names the profile and keeps the latest event identity',
'15 мин всё хорошо · 2 обновления · Дом', '15 мин всё хорошо · 2 обновления · Дом',
]); ]);
}); });
test('channel health events use role-specific copy without raw reason codes', () => {
const cases = [
['failover.primary_unavailable', 'primary', 'probe-failed', ['Основной канал недоступен', 'Проверки канала не пройдены']],
['failover.reserve_unavailable', 'reserve', 'probe-failed', ['Резервный канал недоступен', 'Проверки канала не пройдены']],
['failover.primary_recovered', 'primary', 'probe-recovered', ['Основной канал восстановлен', 'Проверки канала снова проходят успешно']],
['failover.reserve_recovered', 'reserve', 'probe-recovered', ['Резервный канал восстановлен', 'Проверки канала снова проходят успешно']],
['failover.recovered', 'primary', 'primary-recovered', ['Основной канал восстановлен', 'Проверки канала снова проходят успешно']],
['failover.recovered', 'reserve', 'reserve-recovered', ['Резервный канал восстановлен', 'Проверки канала снова проходят успешно']],
];
for (const [type, role, reason, copy] of cases) {
const item = event(`event-${type}-${role}`, '2026-08-27T10:00:00.000Z', type, { role, reason });
assert.deepEqual(activityJournalEventCopy(item), copy);
assert.equal(activityJournalEventCopy(item).join(' ').includes(reason), false);
}
const switched = event('switched', '2026-08-27T10:01:00.000Z', 'failover.switched', {
fromRole: 'primary',
toRole: 'reserve',
reason: 'failure-window',
});
assert.deepEqual(activityJournalEventCopy(switched), [
'Новые соединения переключены',
'primary → reserve',
]);
assert.equal(activityJournalEventCopy(switched).join(' ').includes('failure-window'), false);
});
+12 -12
View File
@@ -39,25 +39,25 @@ const expectedImports = [
const sha256 = (value) => crypto.createHash('sha256').update(value).digest('hex'); const sha256 = (value) => crypto.createHash('sha256').update(value).digest('hex');
const acceptedLedger = { const acceptedLedger = {
counts: { counts: {
cascadeEdges: 1054, cascadeEdges: 1058,
customProperties: 111, customProperties: 111,
declarations: 4123, declarations: 4131,
important: 0, important: 0,
keyframes: 50, keyframes: 50,
media: 17, media: 17,
rules: 1113, rules: 1114,
variableReferences: 1055, variableReferences: 1055,
}, },
hashes: { hashes: {
cascadeEdges: 'c3b2ebc3f49891437122b19af5e9a42e7db11a311ecb4c2c76446c1541fe1023', cascadeEdges: '77b6f34b3bc07b326f477cc436926fb9c4c573e5da9bba840c9bf937542b4488',
customProperties: '14fb162f1c6d754e69dd355fefb1a3a192a191324468f85d7a5d811665ce35b4', customProperties: '42f9fa9f2caaab6e5d90ae7d224563355822fa270083ea3496cfe2caaaea50bf',
declarations: '37b2f9f3ace795a826ad5eca6e6c4ba98ab6bb893aac87938bdeef826c383d63', declarations: 'ac1ac026d0c9d656fde9b28f78faea216a518a44bd2856b2005041f7cb4abd11',
duplicateKeyframes: '4f53cda18c2baa0c0354bb5f9a3ecbe5ed12ab4d8e11ba873c2f11161202b945', duplicateKeyframes: '4f53cda18c2baa0c0354bb5f9a3ecbe5ed12ab4d8e11ba873c2f11161202b945',
duplicateSelectors: '8982145dba05b33bf1c93b2d54cfbe76305b276ff3c657aa020144016ada5848', duplicateSelectors: '8982145dba05b33bf1c93b2d54cfbe76305b276ff3c657aa020144016ada5848',
keyframes: 'af4b9ae18d070fd2462a9b050293f3821bf5017c6e7cc53bbe18dc826f0fe3b9', keyframes: 'af4b9ae18d070fd2462a9b050293f3821bf5017c6e7cc53bbe18dc826f0fe3b9',
ruleDeclarationSequences: '24377c2c29079886b62124688c2f858142913247426728c9b81f4b0a79e559e6', ruleDeclarationSequences: '885efbe91db2ecb739f3c5aa42023576a849d28e639a1694ad13ed696bef77c5',
selectors: '0b7624b5064d514a267e9bb45c40c445ce10f3e6998a34af7e1b604e4c0445b9', selectors: 'fbd8ac40b8d543a29b7140db906d1a3f7fc16a64ebbb380f358629f78657456a',
variableReferences: '56dbfff5943b1ddd09d31b9d6699ff6680d07e5e562285f5f8268cc7566dca59', variableReferences: '70cef326744490dbb615e83457cd42b81b6f2322b0e93e4de6661d53db97e14b',
witnesses: 'e9f8c6e640c19375635847dc064edd6752a8216c6acd3c2aad6ffd18c1a4aaa2', witnesses: 'e9f8c6e640c19375635847dc064edd6752a8216c6acd3c2aad6ffd18c1a4aaa2',
}, },
}; };
@@ -408,8 +408,8 @@ test('main owns one public stylesheet and the regrouped production CSS is determ
assert.equal((main.match(/import ['"][^'"]+\.css['"]/g) || []).length, 1); assert.equal((main.match(/import ['"][^'"]+\.css['"]/g) || []).length, 1);
const assets = fs.readdirSync(path.join(root, 'dist/assets')).filter((file) => file.endsWith('.css')); const assets = fs.readdirSync(path.join(root, 'dist/assets')).filter((file) => file.endsWith('.css'));
assert.deepEqual(assets, ['index-Dng8HPUW.css']); assert.deepEqual(assets, ['index-3s7H6Y0X.css']);
const built = fs.readFileSync(path.join(root, 'dist/assets', assets[0])); const built = fs.readFileSync(path.join(root, 'dist/assets', assets[0]));
assert.equal(built.byteLength, 157518); assert.equal(built.byteLength, 157874);
assert.equal(sha256(built), '4fbc6c3e73a497101cacc456b580c6c4b8a58a44870856689719f2ada5b92bd7'); assert.equal(sha256(built), '99b874016cac6f1b617cd21d5a7ac957f491d8926fe78e8ba514d9313255488f');
}); });