diff --git a/.tmp-tests/harbor-route-TN4fdZ/network.json b/.tmp-tests/harbor-route-TN4fdZ/network.json new file mode 100644 index 0000000..e12bb6b --- /dev/null +++ b/.tmp-tests/harbor-route-TN4fdZ/network.json @@ -0,0 +1 @@ +{"gateway":"192.168.50.111","interface":"en0","mac":"","observedAt":"2026-08-28T08:14:27.401Z"} \ No newline at end of file diff --git a/.tmp-tests/harbor-startup-recovery-FQjZCa/bin/sing-box b/.tmp-tests/harbor-startup-recovery-FQjZCa/bin/sing-box new file mode 100755 index 0000000..6685254 --- /dev/null +++ b/.tmp-tests/harbor-startup-recovery-FQjZCa/bin/sing-box @@ -0,0 +1,11 @@ +#!/usr/bin/env node +const fs = require('node:fs'); +if (process.argv[2] === 'check') process.exit(0); +if (process.argv[2] === 'version') { + console.log('sing-box version 1.13.18'); + process.exit(0); +} +if (process.argv[2] === 'run') { + fs.appendFileSync(process.env.HARBOR_TEST_RUN_MARKER, 'run\n'); + setInterval(() => {}, 60_000); +} diff --git a/.tmp-tests/harbor-startup-recovery-FQjZCa/state.json b/.tmp-tests/harbor-startup-recovery-FQjZCa/state.json new file mode 100644 index 0000000..3b3161d --- /dev/null +++ b/.tmp-tests/harbor-startup-recovery-FQjZCa/state.json @@ -0,0 +1 @@ +{"schemaVersion":6,"revision":4,"profiles":[{"id":"profile-a","label":"Основной","subscriptionUrl":"https://provider.example/0123456789abcdef0123456789abcdef","subscriptionConfig":{"outbounds":[{"type":"vless","tag":"srv_56f1cee6a72c8e7c","server":"boot.example","server_port":443,"uuid":"00000000-0000-4000-8000-000000000000"}]},"servers":[{"id":"srv_56f1cee6a72c8e7c","label":"Boot VPN","host":"boot.example","port":443,"protocol":"vless","tag":"Boot VPN","server":"boot.example","server_port":443,"type":"vless"}],"userInfo":{},"fetchedAt":null,"desiredServerId":"srv_56f1cee6a72c8e7c","lastRefreshAttemptAt":null,"lastRefreshErrorCode":null}],"desiredProfileId":"profile-a","appliedProfileId":"profile-a","appliedServerId":"srv_56f1cee6a72c8e7c","appliedServerSnapshot":{"id":"srv_56f1cee6a72c8e7c","label":"Boot VPN","host":"boot.example","port":443,"protocol":"vless","tag":"Boot VPN","server":"boot.example","server_port":443,"type":"vless"},"routeRules":[{"type":"domain","value":"api.example.com","enabled":true,"outbound":"vpn"},{"type":"domain_suffix","value":"example.com","enabled":true,"outbound":"direct"}],"appliedRouteRules":[],"routeRulesRevision":0,"connectionDesired":"running"} \ No newline at end of file diff --git a/.tmp-tests/harbor-startup-recovery-IRHjjF/bin/sing-box b/.tmp-tests/harbor-startup-recovery-IRHjjF/bin/sing-box new file mode 100755 index 0000000..6685254 --- /dev/null +++ b/.tmp-tests/harbor-startup-recovery-IRHjjF/bin/sing-box @@ -0,0 +1,11 @@ +#!/usr/bin/env node +const fs = require('node:fs'); +if (process.argv[2] === 'check') process.exit(0); +if (process.argv[2] === 'version') { + console.log('sing-box version 1.13.18'); + process.exit(0); +} +if (process.argv[2] === 'run') { + fs.appendFileSync(process.env.HARBOR_TEST_RUN_MARKER, 'run\n'); + setInterval(() => {}, 60_000); +} diff --git a/.tmp-tests/harbor-startup-recovery-IRHjjF/sing-box-config.json b/.tmp-tests/harbor-startup-recovery-IRHjjF/sing-box-config.json new file mode 100644 index 0000000..277b1b1 --- /dev/null +++ b/.tmp-tests/harbor-startup-recovery-IRHjjF/sing-box-config.json @@ -0,0 +1 @@ +{"outbounds":[{"type":"vless","tag":"server-a","server":"a.example","server_port":443},{"type":"direct","tag":"direct"}],"route":{"final":"direct"}} \ No newline at end of file diff --git a/.tmp-tests/harbor-startup-recovery-IRHjjF/state.json b/.tmp-tests/harbor-startup-recovery-IRHjjF/state.json new file mode 100644 index 0000000..1321207 --- /dev/null +++ b/.tmp-tests/harbor-startup-recovery-IRHjjF/state.json @@ -0,0 +1 @@ +{"schemaVersion":6,"revision":4,"profiles":[{"id":"profile-a","label":"Основной","subscriptionUrl":"https://provider.example/subscription-a","subscriptionConfig":null,"servers":[{"id":"server-a","label":"Server A","host":"a.example","port":443,"protocol":"vless"}],"userInfo":{},"fetchedAt":null,"desiredServerId":"server-a","lastRefreshAttemptAt":null,"lastRefreshErrorCode":null}],"desiredProfileId":"profile-a","appliedProfileId":"profile-a","appliedServerId":"server-a","appliedServerSnapshot":{"id":"server-a","label":"Server A","host":"a.example","port":443,"protocol":"vless"},"routeRules":[],"appliedRouteRules":[],"routeRulesRevision":0,"connectionDesired":"running"} \ No newline at end of file diff --git a/.tmp-tests/harbor-startup-recovery-KP1brk/bin/sing-box b/.tmp-tests/harbor-startup-recovery-KP1brk/bin/sing-box new file mode 100755 index 0000000..6685254 --- /dev/null +++ b/.tmp-tests/harbor-startup-recovery-KP1brk/bin/sing-box @@ -0,0 +1,11 @@ +#!/usr/bin/env node +const fs = require('node:fs'); +if (process.argv[2] === 'check') process.exit(0); +if (process.argv[2] === 'version') { + console.log('sing-box version 1.13.18'); + process.exit(0); +} +if (process.argv[2] === 'run') { + fs.appendFileSync(process.env.HARBOR_TEST_RUN_MARKER, 'run\n'); + setInterval(() => {}, 60_000); +} diff --git a/.tmp-tests/harbor-startup-recovery-KP1brk/sing-box-config.json b/.tmp-tests/harbor-startup-recovery-KP1brk/sing-box-config.json new file mode 100644 index 0000000..75959ac --- /dev/null +++ b/.tmp-tests/harbor-startup-recovery-KP1brk/sing-box-config.json @@ -0,0 +1 @@ +{"outbounds":[{"type":"vless","tag":"server-b","server":"b.example","server_port":8443},{"type":"direct","tag":"direct"}],"route":{"final":"server-b"}} \ No newline at end of file diff --git a/.tmp-tests/harbor-startup-recovery-KP1brk/state.json b/.tmp-tests/harbor-startup-recovery-KP1brk/state.json new file mode 100644 index 0000000..1321207 --- /dev/null +++ b/.tmp-tests/harbor-startup-recovery-KP1brk/state.json @@ -0,0 +1 @@ +{"schemaVersion":6,"revision":4,"profiles":[{"id":"profile-a","label":"Основной","subscriptionUrl":"https://provider.example/subscription-a","subscriptionConfig":null,"servers":[{"id":"server-a","label":"Server A","host":"a.example","port":443,"protocol":"vless"}],"userInfo":{},"fetchedAt":null,"desiredServerId":"server-a","lastRefreshAttemptAt":null,"lastRefreshErrorCode":null}],"desiredProfileId":"profile-a","appliedProfileId":"profile-a","appliedServerId":"server-a","appliedServerSnapshot":{"id":"server-a","label":"Server A","host":"a.example","port":443,"protocol":"vless"},"routeRules":[],"appliedRouteRules":[],"routeRulesRevision":0,"connectionDesired":"running"} \ No newline at end of file diff --git a/.tmp-tests/harbor-startup-recovery-ZiMrHv/bin/sing-box b/.tmp-tests/harbor-startup-recovery-ZiMrHv/bin/sing-box new file mode 100755 index 0000000..6685254 --- /dev/null +++ b/.tmp-tests/harbor-startup-recovery-ZiMrHv/bin/sing-box @@ -0,0 +1,11 @@ +#!/usr/bin/env node +const fs = require('node:fs'); +if (process.argv[2] === 'check') process.exit(0); +if (process.argv[2] === 'version') { + console.log('sing-box version 1.13.18'); + process.exit(0); +} +if (process.argv[2] === 'run') { + fs.appendFileSync(process.env.HARBOR_TEST_RUN_MARKER, 'run\n'); + setInterval(() => {}, 60_000); +} diff --git a/.tmp-tests/harbor-startup-recovery-ZiMrHv/sing-box-config.json b/.tmp-tests/harbor-startup-recovery-ZiMrHv/sing-box-config.json new file mode 100644 index 0000000..6026e30 --- /dev/null +++ b/.tmp-tests/harbor-startup-recovery-ZiMrHv/sing-box-config.json @@ -0,0 +1 @@ +{"outbounds":[{"type":"vless","tag":"stale-server","server":"stale.example","server_port":443},{"type":"direct","tag":"direct"}],"route":{"final":"stale-server"}} \ No newline at end of file diff --git a/.tmp-tests/harbor-startup-recovery-ZiMrHv/state.json b/.tmp-tests/harbor-startup-recovery-ZiMrHv/state.json new file mode 100644 index 0000000..6be72f5 --- /dev/null +++ b/.tmp-tests/harbor-startup-recovery-ZiMrHv/state.json @@ -0,0 +1 @@ +{"schemaVersion":4,"revision":2,"connectionDesired":"running"} \ No newline at end of file diff --git a/.tmp-tests/harbor-startup-recovery-ZiMrHv/subscription-cache.json b/.tmp-tests/harbor-startup-recovery-ZiMrHv/subscription-cache.json new file mode 100644 index 0000000..d7a98f7 --- /dev/null +++ b/.tmp-tests/harbor-startup-recovery-ZiMrHv/subscription-cache.json @@ -0,0 +1 @@ +{broken \ No newline at end of file diff --git a/.tmp-tests/harbor-startup-recovery-xqwmBz/bin/sing-box b/.tmp-tests/harbor-startup-recovery-xqwmBz/bin/sing-box new file mode 100755 index 0000000..6685254 --- /dev/null +++ b/.tmp-tests/harbor-startup-recovery-xqwmBz/bin/sing-box @@ -0,0 +1,11 @@ +#!/usr/bin/env node +const fs = require('node:fs'); +if (process.argv[2] === 'check') process.exit(0); +if (process.argv[2] === 'version') { + console.log('sing-box version 1.13.18'); + process.exit(0); +} +if (process.argv[2] === 'run') { + fs.appendFileSync(process.env.HARBOR_TEST_RUN_MARKER, 'run\n'); + setInterval(() => {}, 60_000); +} diff --git a/.tmp-tests/harbor-startup-recovery-xqwmBz/sing-box-config.json b/.tmp-tests/harbor-startup-recovery-xqwmBz/sing-box-config.json new file mode 100644 index 0000000..f18e4ec --- /dev/null +++ b/.tmp-tests/harbor-startup-recovery-xqwmBz/sing-box-config.json @@ -0,0 +1 @@ +{"outbounds":[{"type":"vless","tag":"server-a","server":"state.example","server_port":443},{"type":"direct","tag":"direct"}],"route":{"final":"server-a"}} \ No newline at end of file diff --git a/.tmp-tests/harbor-startup-recovery-xqwmBz/state.json b/.tmp-tests/harbor-startup-recovery-xqwmBz/state.json new file mode 100644 index 0000000..69fad3e --- /dev/null +++ b/.tmp-tests/harbor-startup-recovery-xqwmBz/state.json @@ -0,0 +1 @@ +{"schemaVersion":4,"revision":2,"subscriptionUrl":"https://state.example/subscription-a","servers":[{"id":"server-a","label":"State server","host":"state.example","port":443,"protocol":"vless"}],"selectedServerId":"server-a","appliedServerId":"server-a","connectionDesired":"running"} \ No newline at end of file diff --git a/.tmp-tests/harbor-startup-recovery-xqwmBz/subscription-cache.json b/.tmp-tests/harbor-startup-recovery-xqwmBz/subscription-cache.json new file mode 100644 index 0000000..c0b05da --- /dev/null +++ b/.tmp-tests/harbor-startup-recovery-xqwmBz/subscription-cache.json @@ -0,0 +1 @@ +{"url":"https://cache.example/subscription-b","config":{"outbounds":[{"id":"server-b","label":"Cache server","host":"cache.example","port":8443,"protocol":"vless","type":"vless","tag":"Cache server","server":"cache.example","server_port":8443}]},"servers":[{"id":"server-b","label":"Cache server","host":"cache.example","port":8443,"protocol":"vless","type":"vless","tag":"Cache server","server":"cache.example","server_port":8443}]} \ No newline at end of file diff --git a/.tmp-tests/harbor-state-contract-mDfxUH/bin/sing-box b/.tmp-tests/harbor-state-contract-mDfxUH/bin/sing-box new file mode 100755 index 0000000..8d3d334 --- /dev/null +++ b/.tmp-tests/harbor-state-contract-mDfxUH/bin/sing-box @@ -0,0 +1,8 @@ +#!/usr/bin/env node +if (process.argv[2] === 'check') process.exit(0); +if (process.argv[2] === 'version') { + console.log('sing-box version 1.12.13'); + process.exit(0); +} +process.on('SIGTERM', () => process.exit(0)); +setInterval(() => {}, 60_000); diff --git a/context.md b/context.md new file mode 100644 index 0000000..3718b2c --- /dev/null +++ b/context.md @@ -0,0 +1,209 @@ +# Read-only аудит failover/failback + +## Короткий вывод + +Штатное переключение между `primary` и `reserve` меняет маршрут **только для новых соединений**. Уже установленные TCP/UDP-соединения не переносятся и не закрываются самим Harbor. + +Поэтому: + +- здоровая загрузка, игра или поток продолжаются через старый канал; +- если старый канал действительно умер, существующая сессия может оборваться независимо от переключения; +- после переключения новые соединения идут через новый канал; +- бесшовной миграции уже открытого TCP/UDP-сеанса на другой внешний адрес нет. + +## 1. Точный механизм + +### Конфигурация + +Gateway собирает один dual-channel `sing-box` config: + +- `channel-primary`; +- `channel-reserve`; +- selector `channel-selector`; +- стабильные `tproxy-in` и `mixed-in`; +- отдельные diagnostic inbounds для проверки каждого канала. + +Пользовательский трафик направляется в selector, а selector настроен с: + +```text +interrupt_exist_connections: false +``` + +См. `src/server/singbox.ts:204-247`. + +Роль меняется через localhost Clash API: + +- `PUT /proxies/channel-selector`; +- затем Harbor читает selector обратно и подтверждает выбранную роль. + +См. `src/server/services/singboxSelectorService.ts:29-81`. + +Failover API доступен только в Gateway: + +- `PUT /api/failover`; +- `POST /api/failover/pause`; +- `POST /api/failover/switch`; +- `POST /api/failover/check`. + +См. `src/server/http/routes/failoverRoute.ts:18-39`. + +Переключение selector не вызывает `sing-box` restart/apply/stop. + +### Автоматический failover + +`FailoverService`: + +1. Проверяет оба канала через отдельные diagnostic inbound и выбранные HTTPS-сервисы. +2. Считает канал healthy только если все проверки успешны; неизвестный результат даёт `unknown`. +3. При сбое primary ждёт `failureWindowMs`. +4. Переключается на reserve только если reserve healthy. +5. При включённом traffic guard ждёт свежий quiet-window. +6. Перед самой сменой повторно проверяет здоровье и активность. +7. Выполняет selector PUT, read-back и только после этого обновляет canonical applied state. + +См. `src/server/features/failover/failoverService.ts:225-245`, `:320-514`; state machine — `src/shared/failover.ts:278-354`. + +Дефолты: + +- проверка каждые 60 секунд; +- сбой primary — 120 секунд; +- восстановление primary — 15 минут; +- quiet-window — 30 секунд; +- активный трафик — выше 32 КБ/с; +- минимум на reserve — 10 минут; +- после 3 failover за 24 часа — карантин primary на 6 часов. + +См. `src/shared/failover.ts:137-148`. + +### Автоматический failback + +Отдельной реализации нет: это обратная ветка той же state machine. + +Из reserve Harbor возвращается на primary только после: + +- полного `recoveryWindowMs`; +- `minimumReserveMs`; +- окончания quarantine, если он действует; +- quiet-window при включённом traffic guard; +- подтверждения, что primary healthy. + +Причина переключения публикуется как `primary-recovered`. См. `src/shared/failover.ts:311-354`. + +## 2. Судьба существующих соединений + +| Событие | Уже открытый TCP/UDP flow | Новые соединения | +|---|---|---| +| Автоматический failover primary → reserve | Остаётся на прежнем outbound; Harbor его не закрывает и не мигрирует | Идут через reserve | +| Автоматический failback reserve → primary | Остаётся на reserve | Идут через primary | +| Ручной selector switch | Не закрывается, если старый outbound ещё работает | Сразу идёт через выбранную роль | +| Pause | Ничего не меняет | Идут через текущую роль | +| Disable failover | Selector и текущий маршрут не меняются; dual config временно остаётся загруженным | Идут через текущую роль | +| Обычный stop/restart/config replacement | Процесс `sing-box` останавливается, поэтому TCP/UDP-сессии прерываются | После запуска — по новой конфигурации | +| Реальная авария primary | Уже существующий flow может оборваться сам; Harbor не может перенести его на другой внешний IP | После selector switch новые flow идут через reserve | + +Проверка `interrupt_exist_connections: false` непосредственно подтверждена TCP- и UDP-fixture-тестом: существующие TCP socket и UDP association продолжают обмен после switch, а новые идут через reserve. См. `test/server/singbox-selector-capability.test.js:141-142`, `:237-356`. + +## 3. Отличия режимов + +### Ручное переключение + +`POST /api/failover/switch` вызывает selector напрямую: + +- traffic guard не проверяется; +- состояние здоровья целевого канала backend не проверяет; +- после успешного ручного переключения `failoverPolicy.paused` становится `true`; +- автоматический failback не произойдёт, пока пользователь не возобновит автоматическое переключение. + +См. `src/server/features/failover/failoverService.ts:248-317`, `:614-631`. + +Это означает, что ручной switch может быть выполнен даже на канал, который сейчас не подтверждён healthy. Это важная оговорка. + +### Автоматический failover + +Автоматическое переключение: + +- ждёт failure window; +- требует healthy reserve; +- при включённом guard блокируется активным или неизвестным трафиком; +- повторно валидирует условия непосредственно перед selector mutation; +- не перезапускает `sing-box`. + +### Восстановление primary + +Восстановившийся primary не получает новые соединения сразу. Сначала выдерживаются recovery/hold/quarantine условия и quiet-window. Пока они не выполнены, новые подключения остаются на reserve. + +### Pause и Disable + +`pause` приостанавливает решения, но dual config и наблюдение остаются активными. + +`disable` останавливает scheduler, probes и failover activity collector, но не переключает selector и не перезапускает процесс. После обычного stop/следующего запуска собирается single-channel config. + +См. `README.md:78-84`, `docs/product/application-state.md:102-110`. + +## 4. Практические сценарии + +- **Загрузка файла:** при обычном автоматическом failover активная передача по умолчанию задерживает switch. Если primary всё же упал, текущая TCP-загрузка не переносится на reserve; она может завершиться ошибкой. Возобновление или новый HTTP-запрос после switch пойдёт через reserve. +- **Игровая сессия:** существующий TCP-сеанс остаётся на старом канале. TCP-сессия оборвётся, если primary реально недоступен. UDP-flow также не мигрирует и может начать терять пакеты или истечь по timeout; новая сессия после switch пойдёт через reserve. +- **Стрим:** активный поток обычно блокирует автоматический switch при включённом guard. Ручной switch может быть выполнен сразу, но существующий TCP/QUIC-поток остаётся на старом outbound. При аварии старого канала плеер должен переподключиться. +- **WebSocket/долгий polling:** действующий flow не переносится; новые подключения после switch используют новую роль. +- **Молчащее соединение:** наличие открытого socket само по себе не считается активностью. Guard смотрит на дельты переданных байтов. + +## 5. Условия и оговорки + +- Failover реализован только для **Gateway**, не для локального Connect или `gateway-direct`. +- Активность собирается существующим `/connections` observer каждые 2 секунды, с bounded окном до 10 секунд. См. `src/server/index.ts:311-333`, `src/server/services/domainTrafficService.ts:323-416`, `:437-495`. +- Короткое соединение, полностью завершившееся между двумя снимками, может не попасть в activity guard. +- Неизвестная или устаревшая activity-информация блокирует автоматический switch; ручной switch остаётся доступен. +- Отключение traffic guard разрешает автоматический switch без ожидания тишины, но `interrupt_exist_connections: false` всё равно защищает уже открытые connections от закрытия самим selector. +- При изменении policy во время работающего single-channel VPN dual config становится `pending`; скрытого restart нет. См. `src/server/features/connection/connectionService.ts:140-201`, `:288-361`. +- Явный stop/restart или обычная смена сервера вне активного failover уже является disruptive operation: `sing-box` получает SIGTERM и текущие сессии прекращаются. См. `src/server/singboxRuntime.ts:39-62`, `:65-122`. +- Оба канала находятся в одном процессе `sing-box`; process-wide crash не защищён selector-механизмом. + +## 6. Основные файлы + +- `src/server/singbox.ts:204-247` — dual config, selector, inbound routing. +- `src/server/services/singboxSelectorService.ts:29-81` — selector PUT/read-back. +- `src/server/features/failover/failoverService.ts:225-245` — проверки каналов. +- `src/server/features/failover/failoverService.ts:248-317` — selector switch, commit и rollback. +- `src/server/features/failover/failoverService.ts:320-514` — автоматический раунд и traffic guard. +- `src/server/features/failover/failoverService.ts:614-631` — ручное переключение. +- `src/shared/failover.ts:137-148`, `:278-354` — дефолты и state machine. +- `src/server/services/domainTrafficService.ts:129-160`, `:323-416`, `:437-495` — классификация и activity. +- `src/server/features/connection/connectionService.ts:140-201`, `:243-361` — обычный apply/stop/restart. +- `src/server/singboxRuntime.ts:39-122` — фактическая остановка и перезапуск процесса. +- `README.md:78-84` — пользовательская документация. +- `docs/product/application-state.md:102-110` — контракт состояния. +- `workpack/tasks/TASK-021-auto-server-selection-failover.md:93-106`, `:187-204` — относящийся план и ограничения; задача не выбиралась и не изменялась. + +## 7. Тесты, подтверждающие выводы + +- `test/server/singbox-selector-capability.test.js:141-356` + Интеграционная TCP/UDP-проверка: активный трафик задерживает failover, существующие TCP/UDP продолжают работать после switch, новые соединения идут через reserve, PID процесса не меняется. Тест opt-in и пропускается без `HARBOR_SINGBOX_IMAGE`. +- `test/server/singbox-gateway-mode.test.js:69-110` + Проверяет selector, `interrupt_exist_connections: false`, отдельные diagnostic routes и primary/reserve outbounds. +- `test/server/failover-service.test.js:83-200` + Failure window, traffic guard, both-unhealthy и failback recovery/hold/quarantine. +- `test/server/failover-service.test.js:255-420` + Disabled zero-work, отмена устаревших наблюдений и непосредственная revalidation активности. +- `test/server/failover-service.test.js:423-520` + Selector rollback, commit ordering и ручной switch с pause. +- `test/server/domain-traffic.test.js:209-239` + Activity считается по пользовательскому VPN traffic, diagnostic connection не блокирует switch. +- `test/server/connection-service.test.js:265-310`, `:340-390` + Restart dual config и rollback; pending edits для работающего single-channel. +- `test/server/singbox-runtime.test.js:16-50` + При изменении config runtime запускает новый процесс. +- `test/server/failover-route.test.js:10-53` + Gateway-only API и маршруты ручного switch/pause/check. +- `test/web/failover-feature-contract.test.js:19-76` + UI явно сообщает: новые подключения переключаются, открытые остаются на прежнем канале. + +## Review findings и residual risks + +- **medium — `src/server/features/failover/failoverService.ts:614-620`:** ручной switch не проверяет health целевого канала и не применяет traffic guard; он сразу меняет selector и ставит automation на pause. +- **medium — `test/server/singbox-selector-capability.test.js:141-356`:** capability test opt-in и использует deterministic `direct` outbounds, а не реальный VLESS/Trojan outage. +- **medium — `src/server/services/domainTrafficService.ts:414-416`, `:451-479`:** activity основана на polling и byte deltas; короткие или очень малые потоки могут не блокировать автоматическое решение. +- **info — `src/server/singboxRuntime.ts:39-122`:** явный stop/restart отличается от selector switch и прерывает существующие соединения. +- **info — архитектура одного процесса:** падение всего `sing-box` не компенсируется selector failover. + +Файлы не изменялись. Тесты и live Gateway в рамках read-only аудита не запускались. \ No newline at end of file diff --git a/src/server/features/failover/failoverService.ts b/src/server/features/failover/failoverService.ts index 3566eb3..d314d72 100644 --- a/src/server/features/failover/failoverService.ts +++ b/src/server/features/failover/failoverService.ts @@ -305,7 +305,7 @@ export function createFailoverService(dependencies: FailoverServiceDependencies) appliedServerId: target.serverId, appliedServerSnapshot: server, failoverPolicy: reason === 'manual' - ? { ...state.failoverPolicy, paused: true } + ? state.failoverPolicy : role === 'primary' ? { ...state.failoverPolicy, paused: false } : state.failoverPolicy, failoverRuntimeState: { ...state.failoverRuntimeState, diff --git a/src/shared/versions.ts b/src/shared/versions.ts index 6341aa4..2d27cbf 100644 --- a/src/shared/versions.ts +++ b/src/shared/versions.ts @@ -1,7 +1,7 @@ export const HARBOR_VERSIONS = Object.freeze({ - macClient: '0.31.0', - gatewayClient: '0.32.0', - gatewayBackend: '0.32.0', + macClient: '0.31.1', + gatewayClient: '0.32.1', + gatewayBackend: '0.32.1', }); export interface ParsedVersion { diff --git a/src/web/components/ClientOverviewPage.tsx b/src/web/components/ClientOverviewPage.tsx index b48e70d..bead913 100644 --- a/src/web/components/ClientOverviewPage.tsx +++ b/src/web/components/ClientOverviewPage.tsx @@ -710,6 +710,7 @@ export function ClientOverviewPage({ activeSwitch?.finish(); if (current === target) { + if (target === 'failover') failoverFeature.pendingTargetRef.current = null; drawerControls[target].close(); return; } @@ -717,7 +718,13 @@ export function ClientOverviewPage({ routingFeature.requestClose(); return; } - if (current === 'failover' && !failoverFeature.beforeCloseRef.current()) return; + if (current === 'failover') { + if (!failoverFeature.beforeCloseRef.current()) { + failoverFeature.pendingTargetRef.current = () => switchDrawer(target); + return; + } + failoverFeature.pendingTargetRef.current = null; + } if (!current) { drawerControls[target].show(); return; diff --git a/src/web/features/failover/FailoverFeature.tsx b/src/web/features/failover/FailoverFeature.tsx index 291765b..ad55b60 100644 --- a/src/web/features/failover/FailoverFeature.tsx +++ b/src/web/features/failover/FailoverFeature.tsx @@ -3,23 +3,31 @@ 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'; +import { ConfirmationDialog } from '../../ui/ConfirmationDialog.js'; import { Drawer } from '../../ui/Drawer.js'; import { RailAction } from '../../ui/RailAction.js'; +import { Tooltip } from '../../ui/Tooltip.js'; import { saveCustomDiagnosticService } from '../diagnostics/index.js'; - export function useFailoverFeature() { const [isOpen, setIsOpen] = useState(false); const panelRef = useRef(null); const toggleRef = useRef(null); const closeRef = useRef(null); const beforeCloseRef = useRef<() => boolean>(() => true); + const pendingTargetRef = useRef<(() => void) | null>(null); const close = () => { - if (beforeCloseRef.current()) setIsOpen(false); + if (beforeCloseRef.current()) { + pendingTargetRef.current = null; + setIsOpen(false); + } }; useEffect(() => { if (!isOpen) return undefined; const frame = requestAnimationFrame(() => closeRef.current?.focus()); const handleClose = (event: PointerEvent | KeyboardEvent) => { + if (event.defaultPrevented) return; + const target = event.target; + if (target instanceof Element && target.closest('.client-confirmation-popup')) return; if (event.type === 'keydown' && (event as KeyboardEvent).key !== 'Escape') return; if (event.type !== 'keydown' && ( panelRef.current?.contains(event.target as Node) || toggleRef.current?.contains(event.target as Node) @@ -38,7 +46,7 @@ export function useFailoverFeature() { }; }, [isOpen]); return { - isOpen, panelRef, toggleRef, closeRef, beforeCloseRef, close, + isOpen, panelRef, toggleRef, closeRef, beforeCloseRef, pendingTargetRef, close, toggle: () => isOpen ? close() : setIsOpen(true), }; } @@ -67,6 +75,14 @@ export function FailoverToggle({ feature, open, onToggle }: { } const seconds = (milliseconds: number) => Math.round(milliseconds / 1000); +const normalizeFailoverDraft = (policy: FailoverPolicy) => { + const normalized = normalizeFailoverPolicy(policy); + return { + ...normalized, + minimumReserveMs: Math.round(normalized.minimumReserveMs / 60_000) * 60_000, + }; +}; + function pulseNumber(event: FormEvent) { if (matchMedia('(prefers-reduced-motion: reduce)').matches) return; @@ -309,7 +325,7 @@ export function FailoverPanel({ onCheck: () => Promise; onUpdateDiagnostics: (settings: unknown) => Promise; }) { - const [draft, setDraft] = useState(() => snapshot.policy); + const [draft, setDraft] = useState(() => normalizeFailoverDraft(snapshot.policy)); const [dirty, setDirty] = useState(false); const [confirmDiscard, setConfirmDiscard] = useState(false); const [addingService, setAddingService] = useState(false); @@ -319,25 +335,35 @@ export function FailoverPanel({ const [openPicker, setOpenPicker] = useState(''); const [removingCheckId, setRemovingCheckId] = useState(''); const [manualChecking, setManualChecking] = useState(false); + const discardContinuationFrameRef = useRef(null); useEffect(() => { - if (!dirty) setDraft(snapshot.policy); + if (!dirty) setDraft(normalizeFailoverDraft(snapshot.policy)); }, [snapshot.policy, dirty]); useEffect(() => { feature.beforeCloseRef.current = () => { - if (!dirty) return true; + if (!dirty) { + feature.pendingTargetRef.current = null; + return true; + } setConfirmDiscard(true); return false; }; const beforeUnload = (event: BeforeUnloadEvent) => { if (!dirty) return; event.preventDefault(); + event.returnValue = ''; }; window.addEventListener('beforeunload', beforeUnload); return () => { feature.beforeCloseRef.current = () => true; window.removeEventListener('beforeunload', beforeUnload); }; - }, [dirty, feature.beforeCloseRef]); + }, [dirty, feature.beforeCloseRef, feature.pendingTargetRef]); + useEffect(() => () => { + if (discardContinuationFrameRef.current !== null) { + cancelAnimationFrame(discardContinuationFrameRef.current); + } + }, []); const services = useMemo(() => [ ...CONNECTIVITY_SITES, ...diagnostics.customServices, @@ -368,11 +394,11 @@ export function FailoverPanel({ ...(diagnostics.customServices.length < MAX_CUSTOM_DIAGNOSTIC_SERVICES ? [{ id: '__new-service', label: 'Новый HTTPS-сервис…' }] : []), ], [diagnostics.customServices.length, draft.checks, services]); const update = (value: Partial) => { - setDraft((current) => normalizeFailoverPolicy({ ...current, ...value })); + setDraft((current) => normalizeFailoverDraft({ ...current, ...value })); setDirty(true); }; const updateChecks = (change: (checks: FailoverPolicy['checks']) => FailoverPolicy['checks']) => { - setDraft((current) => normalizeFailoverPolicy({ ...current, checks: change(current.checks) })); + setDraft((current) => normalizeFailoverDraft({ ...current, checks: change(current.checks) })); setDirty(true); }; const updateTarget = (channel: 'primary' | 'reserve', optionId: string) => { @@ -383,6 +409,7 @@ export function FailoverPanel({ ? snapshot.currentRole : null; const switchRole = role === 'primary' ? 'reserve' : role === 'reserve' ? 'primary' : null; + const checking = manualChecking || snapshot.reason === 'checking-channels'; const activity = snapshot.trafficActivity; const targetExists = (target: FailoverPolicy['primary']) => profiles .find(({ id }) => id === target.profileId)?.servers.some(({ id }) => id === target.serverId); @@ -437,27 +464,48 @@ export function FailoverPanel({ Gateway

Резервный канал

- { - setOpenPicker(''); - if (!enabled) setAddingService(false); - update({ enabled }); - }} - /> +
+
+ Канал + { + setOpenPicker(''); + if (!enabled) setAddingService(false); + update({ enabled }); + }} + /> +
+
+ Автоматика + void onPause(!automatic)} + /> +
+ +
-

Если основной канал перестанет работать, Harbor направит новые подключения через резервный канал. Уже открытые подключения продолжат работать через прежний канал.

- {snapshot.enabled &&
- - {snapshot.paused ? 'Новые подключения продолжают идти через текущий канал.' : 'Harbor проверяет оба канала и при необходимости переключает новые подключения.'} -
} +
+

Если основной канал перестанет работать, Harbor направит новые подключения через резервный канал. Уже открытые подключения продолжат работать через прежний канал.

+ {snapshot.enabled && {snapshot.paused ? 'Новые подключения продолжают идти через текущий канал.' : 'Harbor проверяет оба канала и при необходимости переключает новые подключения.'}} +
-
{ + { event.preventDefault(); - void onSave(draft).then((result) => { if (result !== false) setDirty(false); }); + void onSave(normalizeFailoverDraft(draft)).then((result) => { if (result !== false) setDirty(false); }); }}>
{(['primary', 'reserve'] as const).map((channel) => { @@ -479,7 +527,7 @@ export function FailoverPanel({ : channel === 'primary' && snapshot.currentRole === 'reserve' && health === 'healthy' && snapshot.reason === 'recovery-hold' ? 'Проверяем восстановление' : health === 'healthy' ? 'Работает' : health === 'unhealthy' ? 'Недоступен' : health === 'not-monitoring' ? 'Проверка выключена' : 'Ждёт проверки'; - return
+ return

{channel === 'primary' ? 'Основной' : 'Резервный'}

{healthLabel} @@ -494,13 +542,63 @@ export function FailoverPanel({ onOpenChange={(open) => setOpenPicker(open ? channel : '')} onChange={(optionId) => updateTarget(channel, optionId)} /> -
; +
{channel === 'primary' &&
+ + +
}; })}
{(manualChecking || snapshot.reason === 'checking-channels' ? ['primary', 'reserve'] as const : []).map((checkingRole) => Проверяем {checkingRole === 'primary' ? 'основной' : 'резервный'} канал)}
+
+ Сейчас используется + {blocked + ? 'Harbor завершает текущее действие' + : role === 'primary' + ? 'Основной канал' + : role === 'reserve' + ? 'Резервный канал' + : 'Канал пока не выбран'} + {blocked ? 'Подождите…' : reasonLabel(snapshot.reason)} + {role + ? `Новые подключения: ${targetLabel(profiles, snapshot[role].target)}` + : snapshot.reason === 'vpn-stopped' + ? `При запуске VPN будет выбран: ${targetLabel(profiles, draft.primary)}` + : `После перезапуска VPN будет выбран: ${targetLabel(profiles, draft.primary)}`} + {snapshot.nextDecisionAt && Проверим каналы снова через {seconds(Math.max(0, Date.parse(snapshot.nextDecisionAt) - Date.now()))} с} + {activity && {activity.state === 'active' ? `Сейчас передаётся ${Math.round(activity.totalBytesPerSecond / 1024)} КБ/с. Активных подключений: ${activity.transmittingConnections}` : activity.state === 'quiet' ? `Передачи данных нет: ${Math.min(seconds(quietElapsed), seconds(draft.trafficGuard.quietWindowMs))} из ${seconds(draft.trafficGuard.quietWindowMs)} с` : 'Не удалось проверить передачу данных. Автоматическое переключение остановлено'}} + {activity?.blockers.slice(0, 2).map((blocker) => {blocker.device} · {blocker.service} · {Math.round((blocker.uploadBytesPerSecond + blocker.downloadBytesPerSecond) / 1024)} КБ/с)} + {activity && activity.blockers.length > 2 && Ещё {activity.blockers.length - 2}} +
+
Что проверятьHarbor проверяет эти сайты через оба канала, чтобы понять, какой канал работает. {draft.checks.map((check) => { @@ -595,42 +693,41 @@ export function FailoverPanel({

Если основной канал снова перестаёт работать, Harbor дольше оставляет новые подключения на резервном канале.

- update({ minimumReserveMs: value * 1_000 })} /> + update({ minimumReserveMs: Math.round(value) * 60_000 })} /> update({ flapProtection: { ...draft.flapProtection, count: value } })} /> update({ flapProtection: { ...draft.flapProtection, windowMs: value * 3_600_000 } })} /> update({ flapProtection: { ...draft.flapProtection, quarantineMs: value * 60_000 } })} />
-
- {blocked ? 'Подождите, Harbor завершает текущее действие…' : snapshot.activation === 'pending' ? 'Резервный канал включится при следующем запуске VPN' : reasonLabel(snapshot.reason)} - {role - ? `Новые подключения: ${targetLabel(profiles, snapshot[role].target)}` - : snapshot.reason === 'vpn-stopped' - ? `При запуске VPN будет выбран: ${targetLabel(profiles, draft.primary)}` - : `После перезапуска VPN будет выбран: ${targetLabel(profiles, draft.primary)}`} - {snapshot.nextDecisionAt && Проверим каналы снова через {seconds(Math.max(0, Date.parse(snapshot.nextDecisionAt) - Date.now()))} с} - {activity && {activity.state === 'active' ? `Сейчас передаётся ${Math.round(activity.totalBytesPerSecond / 1024)} КБ/с. Активных подключений: ${activity.transmittingConnections}` : activity.state === 'quiet' ? `Передачи данных нет: ${Math.min(seconds(quietElapsed), seconds(draft.trafficGuard.quietWindowMs))} из ${seconds(draft.trafficGuard.quietWindowMs)} с` : 'Не удалось проверить передачу данных. Автоматическое переключение остановлено'}} - {activity?.blockers.slice(0, 2).map((blocker) => {blocker.device} · {blocker.service} · {Math.round((blocker.uploadBytesPerSecond + blocker.downloadBytesPerSecond) / 1024)} КБ/с)} - {activity && activity.blockers.length > 2 && Ещё {activity.blockers.length - 2}} -
- {!draftValid &&

Выберите разные серверы для основного и резервного каналов и хотя бы один сайт для проверки.

} - {confirmDiscard &&
- Отменить несохранённые изменения? - - -
} - -
- - - {switchRole && snapshot.enabled && snapshot.activation === 'active' && } - {(snapshot.currentRole === 'primary' || snapshot.currentRole === 'reserve') && Открытые подключения останутся на прежнем канале.} -
+ { + feature.pendingTargetRef.current = null; + setConfirmDiscard(false); + }} + onConfirm={() => { + const continueNavigation = feature.pendingTargetRef.current; + feature.pendingTargetRef.current = null; + feature.beforeCloseRef.current = () => true; + flushSync(() => { + setDraft(normalizeFailoverDraft(snapshot.policy)); + setDirty(false); + setConfirmDiscard(false); + }); + discardContinuationFrameRef.current = requestAnimationFrame(() => { + discardContinuationFrameRef.current = null; + if (continueNavigation) continueNavigation(); + else feature.close(); + }); + }} + /> ; } diff --git a/src/web/styles/features/failover.css b/src/web/styles/features/failover.css index 38ef63b..be2f12d 100644 --- a/src/web/styles/features/failover.css +++ b/src/web/styles/features/failover.css @@ -1,11 +1,14 @@ -.client-failover-header { display: grid; gap: 8px; margin: 0 8px 30px; } +.client-failover-header { position: sticky; top: 0; z-index: 7; display: grid; gap: 8px; margin: -18px -8px 0; padding: 18px 16px 14px; background: color-mix(in oklch, var(--client-bg) 99%, var(--client-panel)); } .client-failover-header > span { color: var(--client-muted); font: var(--type-label); letter-spacing: var(--type-label-tracking); text-transform: var(--type-label-transform); } -.client-failover-heading { min-height: 44px; display: flex; align-items: center; justify-content: space-between; gap: 20px; } +.client-failover-heading { min-height: 44px; display: flex; align-items: center; justify-content: space-between; gap: 16px; min-width: 0; } .client-failover-header h2 { margin: 0; font: var(--type-drawer-title); letter-spacing: var(--type-drawer-title-tracking); text-transform: var(--type-drawer-title-transform); } -.client-failover-header p { margin: 0; color: var(--client-muted); font: var(--type-data); font-variant-numeric: var(--numeric-tabular); letter-spacing: var(--type-data-tracking); text-transform: var(--type-data-transform); } -.client-failover-global-actions { min-height: 30px; display: flex; flex-wrap: wrap; align-items: baseline; gap: 3px 16px; } -.client-failover-global-actions > button { padding: 6px 0; border: 0; background: transparent; color: var(--client-accent); font: var(--type-control); letter-spacing: var(--type-control-tracking); text-transform: var(--type-control-transform); cursor: pointer; } -.client-failover-global-actions > small { color: var(--client-muted); font: var(--type-control); letter-spacing: var(--type-control-tracking); text-transform: var(--type-control-transform); } +.client-failover-header-actions { min-width: 0; display: flex; flex-wrap: wrap; align-items: center; justify-content: flex-end; gap: 8px 16px; } +.client-failover-switch-setting { display: flex; align-items: center; gap: 5px; color: var(--client-muted); font: var(--type-control); letter-spacing: var(--type-control-tracking); text-transform: var(--type-control-transform); } +.client-failover-switch-setting .client-failover-switch { transform: scale(.78); } +.client-failover-save { min-height: 36px; max-width: 100%; padding: 7px 0; border: 0; background: transparent; color: var(--client-accent); font: var(--type-control); letter-spacing: var(--type-control-tracking); text-transform: var(--type-control-transform); cursor: pointer; } +.client-failover-save:disabled { color: var(--client-muted); cursor: default; opacity: .45; } +.client-failover-intro { display: grid; gap: 8px; margin: 14px 8px 30px; } +.client-failover-intro p { margin: 0; color: var(--client-muted); font: var(--type-data); font-variant-numeric: var(--numeric-tabular); letter-spacing: var(--type-data-tracking); text-transform: var(--type-data-transform); } .client-failover-form { display: grid; gap: 24px; margin: 0 8px; } .client-failover-switch { position: relative; flex: 0 0 auto; width: 44px; height: 44px; padding: 0; border: 0; background: transparent; color: var(--client-muted); cursor: pointer; } .client-failover-switch::before { content: ''; position: absolute; inset: 11px 1px; border-radius: 999px; background: color-mix(in oklch, var(--client-muted) 24%, transparent); box-shadow: inset 0 0 0 1px color-mix(in oklch, var(--client-muted) 24%, transparent); transition: background 240ms cubic-bezier(0.16, 1, 0.3, 1), box-shadow 240ms cubic-bezier(0.16, 1, 0.3, 1); } @@ -14,7 +17,8 @@ .client-failover-switch[aria-checked='true'] > span { background: var(--client-text); box-shadow: 0 0 10px color-mix(in oklch, var(--client-accent) 46%, transparent); transform: translateX(22px); } .client-failover-switch:disabled { cursor: default; opacity: .42; } .client-failover-switch:focus-visible { outline: 2px solid var(--client-accent); outline-offset: 0; border-radius: 999px; } -.client-failover-channels { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px 32px; } +.client-failover-channels { display: grid; grid-template-columns: minmax(0, 1fr) 52px minmax(0, 1fr); gap: 12px; } +.client-failover-channel-slot { display: contents; } .client-failover-channel { position: relative; display: grid; align-content: start; gap: 7px; min-width: 0; } .client-failover-channel-title { min-height: 24px; display: flex; align-items: baseline; justify-content: space-between; gap: 12px; } .client-failover-channel-title h3 { margin: 0; font: var(--type-data); font-variant-numeric: var(--numeric-tabular); letter-spacing: var(--type-data-tracking); text-transform: var(--type-data-transform); } @@ -25,6 +29,14 @@ .client-failover-channel-title strong.is-unhealthy { color: oklch(0.68 0.15 28); } .client-failover-picker { position: relative; min-width: 0; z-index: 1; } .client-failover-checking { grid-column: 1 / -1; min-height: 22px; display: flex; flex-wrap: wrap; gap: 6px 22px; color: var(--client-muted); font: var(--type-control); letter-spacing: var(--type-control-tracking); text-transform: var(--type-control-transform); } +.client-failover-channel-actions { grid-column: 2; grid-row: 1; min-height: 66px; display: grid; place-content: center; gap: 2px; } +.client-failover-check-action, .client-failover-direction-action { width: 44px; height: 44px; display: grid; place-items: center; padding: 0; border: 0; background: transparent; color: var(--client-accent); cursor: pointer; } +.client-failover-check-action:disabled, .client-failover-direction-action:disabled { color: var(--client-muted); cursor: default; opacity: .45; } +.client-failover-save:focus-visible { outline: 2px solid var(--client-accent); outline-offset: 2px; } +.client-failover-check-action svg { flex: 0 0 auto; width: 17px; height: 17px; fill: none; stroke: currentColor; stroke-width: 1.7; stroke-linecap: round; stroke-linejoin: round; } +.client-failover-check-action.is-running svg { animation: client-spin 900ms linear infinite; } +.client-failover-direction-action svg { flex: 0 0 auto; width: 20px; height: 20px; fill: none; stroke: currentColor; stroke-width: 1.7; stroke-linecap: round; stroke-linejoin: round; transform: rotate(0deg); transition: transform 260ms cubic-bezier(0.16, 1, 0.3, 1); } +.client-failover-direction-action svg.is-primary { transform: rotate(180deg); } .client-failover-picker.is-open { z-index: 6; } .client-failover-picker-trigger { width: 100%; min-height: 42px; display: flex; align-items: center; justify-content: space-between; gap: 12px; padding: 0 2px; border: 0; border-bottom: 1px solid var(--client-border); background: transparent; 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); text-align: left; box-shadow: 0 1px 0 transparent; cursor: pointer; transition: color 220ms ease, box-shadow 300ms ease, text-shadow 300ms ease; } .client-failover-picker-trigger span { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } @@ -47,7 +59,7 @@ .client-failover-number-steps { position: absolute; left: 50%; bottom: 0; width: 44px; display: flex; justify-content: space-between; opacity: 0; filter: blur(3px); transform: translate(-50%, -2px); pointer-events: none; transition: opacity 260ms ease 80ms, filter 260ms ease 80ms, transform 260ms cubic-bezier(0.16, 1, 0.3, 1) 80ms; } .client-failover-number-control:hover .client-failover-number-steps, .client-failover-number-control:focus-within .client-failover-number-steps { opacity: 1; filter: blur(0); transform: translate(-50%, 0); pointer-events: auto; transition: opacity 180ms ease, filter 180ms ease, transform 220ms cubic-bezier(0.16, 1, 0.3, 1); } .client-failover-number-steps button { width: 20px; height: 18px; display: grid; place-items: center; padding: 0; border: 0; background: transparent; color: var(--client-accent); font: var(--type-control); letter-spacing: var(--type-control-tracking); text-transform: var(--type-control-transform); cursor: pointer; } -.client-failover-number-steps button:disabled, .client-failover-global-actions > button:disabled { color: var(--client-muted); cursor: default; opacity: .42; } +.client-failover-number-steps button:disabled { color: var(--client-muted); cursor: default; opacity: .42; } .client-failover-services { display: grid; gap: 5px; margin: 0; padding: 0; border: 0; } .client-failover-services legend { width: 100%; margin-bottom: 14px; padding: 0; } .client-failover-section-header { display: grid; gap: 4px; margin-bottom: 12px; } @@ -79,21 +91,18 @@ .client-failover-traffic-switch small { color: var(--client-muted); font: var(--type-control); letter-spacing: var(--type-control-tracking); text-transform: var(--type-control-transform); } .client-failover-protection { display: grid; gap: 5px; } .client-failover-protection-options { display: grid; gap: 0; } -.client-failover-runtime { min-height: 132px; display: grid; align-content: center; gap: 5px; padding: 14px 0; border-top: 1px solid color-mix(in oklch, var(--client-border) 48%, transparent); border-bottom: 1px solid color-mix(in oklch, var(--client-border) 48%, transparent); font-variant-numeric: var(--numeric-tabular); } -.client-failover-runtime strong { font: var(--type-data); font-variant-numeric: var(--numeric-tabular); letter-spacing: var(--type-data-tracking); text-transform: var(--type-data-transform); } +.client-failover-runtime { display: grid; gap: 4px; margin-top: -10px; padding: 8px 0 2px; font-variant-numeric: var(--numeric-tabular); } +.client-failover-runtime-label { color: var(--client-muted); font: var(--type-label); letter-spacing: var(--type-label-tracking); text-transform: var(--type-label-transform); } +.client-failover-runtime strong { color: var(--client-muted); font: var(--type-item-title); font-variant-numeric: var(--numeric-tabular); letter-spacing: var(--type-item-title-tracking); text-transform: var(--type-item-title-transform); } +.client-failover-runtime.is-primary strong { color: var(--harbor-connect); text-shadow: 0 0 9px color-mix(in oklch, var(--harbor-connect) 30%, transparent); } +.client-failover-runtime.is-reserve strong { color: var(--harbor-gateway); text-shadow: 0 0 9px color-mix(in oklch, var(--harbor-gateway) 30%, transparent); } .client-failover-runtime span, .client-failover-runtime small { color: var(--client-muted); font: var(--type-control); letter-spacing: var(--type-control-tracking); text-transform: var(--type-control-transform); } .client-failover-validation { margin: -12px 0 0; color: oklch(0.68 0.15 28); font: var(--type-control); letter-spacing: var(--type-control-tracking); text-transform: var(--type-control-transform); } -.client-failover-discard { min-height: 74px; display: flex; flex-wrap: wrap; align-items: center; gap: 8px 16px; padding: 10px 0; border-top: 1px solid var(--client-border); border-bottom: 1px solid var(--client-border); } -.client-failover-discard span { flex-basis: 100%; 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-failover-discard button { padding: 4px 0; border: 0; background: transparent; color: var(--client-accent); font: var(--type-control); letter-spacing: var(--type-control-tracking); text-transform: var(--type-control-transform); cursor: pointer; } -.client-failover-actions { min-height: 42px; display: flex; flex-wrap: wrap; gap: 18px; } -.client-failover-actions button { padding: 7px 0; border: 0; background: transparent; color: var(--client-accent); font: var(--type-control); letter-spacing: var(--type-control-tracking); text-transform: var(--type-control-transform); cursor: pointer; } -.client-failover-actions small { flex-basis: 100%; margin-top: -14px; color: var(--client-muted); font: var(--type-control); letter-spacing: var(--type-control-tracking); text-transform: var(--type-control-transform); } -.client-failover-actions button:disabled { color: var(--client-muted); cursor: default; opacity: .45; } -.client-failover-actions button:focus-visible, .client-failover-service-editor button:focus-visible, .client-failover-discard button:focus-visible, .client-failover-global-actions > button:focus-visible, .client-failover-number-steps button:focus-visible { outline: 2px solid var(--client-accent); outline-offset: 2px; } +.client-failover-pause-hint { color: var(--client-muted); font: var(--type-control); letter-spacing: var(--type-control-tracking); text-transform: var(--type-control-transform); } +.client-failover-check-action:focus-visible, .client-failover-direction-action:focus-visible, .client-failover-service-editor button:focus-visible, .client-failover-number-steps button:focus-visible { outline: 2px solid var(--client-accent); outline-offset: 2px; } .client-failover-form input:not(.client-failover-number-input):focus-visible { outline: 0; border-bottom-color: var(--client-accent); box-shadow: 0 1px 0 color-mix(in oklch, var(--client-accent) 60%, transparent); text-shadow: 0 0 9px color-mix(in oklch, var(--client-accent) 34%, transparent); } .client-failover-number-input:focus-visible { outline: 0; color: var(--client-accent); text-shadow: 0 0 9px color-mix(in oklch, var(--client-accent) 38%, transparent); } @keyframes failover-service-in { from { opacity: 0; filter: blur(5px); transform: translateY(-4px); } to { opacity: 1; filter: blur(0); transform: translateY(0); } } @keyframes failover-service-out { from { opacity: 1; filter: blur(0); transform: translateX(0) scale(1); } to { opacity: 0; filter: blur(6px); transform: translateX(16px) scale(.96); } } -@media (max-width: 560px) { .client-failover-channels { grid-template-columns: minmax(0, 1fr); gap: 18px; } .client-failover-checking { grid-column: 1; margin-top: -6px; } .client-failover-service { grid-template-columns: minmax(0, 1fr) 32px; gap: 6px 10px; } .client-failover-service > .client-failover-number-setting { grid-column: 1; grid-row: 2; } .client-failover-remove-service { grid-column: 2; grid-row: 1 / span 2; } .client-failover-service-editor { grid-template-columns: 1fr; gap: 2px; } } -@media (prefers-reduced-motion: reduce) { .client-failover-channel-title strong, .client-failover-switch::before, .client-failover-switch > span, .client-failover-picker-trigger, .client-failover-picker-trigger::before, .client-failover-picker-trigger svg, .client-failover-picker-list, .client-failover-picker-list button, .client-failover-number-steps, .client-failover-number-control:hover .client-failover-number-steps, .client-failover-number-control:focus-within .client-failover-number-steps, .client-failover-remove-service, .client-failover-remove-lid { transition: none; } .client-failover-service, .client-failover-service-editor { animation: none; } } +@media (max-width: 560px) { .client-failover-heading { align-items: flex-start; flex-wrap: wrap; } .client-failover-heading > h2 { min-width: 0; flex: 1 1 auto; } .client-failover-header-actions { flex: 1 1 100%; justify-content: flex-start; gap: 4px 10px; } .client-failover-channels { grid-template-columns: minmax(0, 1fr); gap: 12px; } .client-failover-checking { grid-column: 1; margin-top: -6px; } .client-failover-channel-actions { grid-column: 1; grid-row: auto; min-height: 44px; display: flex; justify-content: center; gap: 8px; } .client-failover-service { grid-template-columns: minmax(0, 1fr) 32px; gap: 6px 10px; } .client-failover-service > .client-failover-number-setting { grid-column: 1; grid-row: 2; } .client-failover-remove-service { grid-column: 2; grid-row: 1 / span 2; } .client-failover-service-editor { grid-template-columns: 1fr; gap: 2px; } } +@media (prefers-reduced-motion: reduce) { .client-failover-channel-title strong, .client-failover-switch::before, .client-failover-switch > span, .client-failover-picker-trigger, .client-failover-picker-trigger::before, .client-failover-picker-trigger svg, .client-failover-picker-list, .client-failover-picker-list button, .client-failover-number-steps, .client-failover-number-control:hover .client-failover-number-steps, .client-failover-number-control:focus-within .client-failover-number-steps, .client-failover-remove-service, .client-failover-remove-lid, .client-failover-direction-action svg { transition: none; } .client-failover-check-action.is-running svg { animation: none; } .client-failover-service, .client-failover-service-editor { animation: none; } } diff --git a/test/server/failover-service.test.js b/test/server/failover-service.test.js index aff9a99..2f15c68 100644 --- a/test/server/failover-service.test.js +++ b/test/server/failover-service.test.js @@ -514,12 +514,22 @@ test('selector acknowledgement precedes state commit and a failed commit rolls s assert.equal(state.appliedServerId, 'server-1'); }); -test('manual selector and pause publish in one canonical commit', async () => { - const testHarness = harness(serviceState()); - await testHarness.service.manualSwitch('reserve'); - assert.equal(testHarness.read().appliedServerId, 'server-2'); - assert.equal(testHarness.read().failoverPolicy.paused, true); - assert.equal(testHarness.calls.filter((call) => call === 'state:update').length, 1); +test('manual switch preserves automation and starts the configured reserve hold', async () => { + const now = new Date('2026-08-27T12:00:00.000Z'); + for (const paused of [false, true]) { + const state = serviceState(normalizeFailoverPolicy({ + ...enabled, + paused, + minimumReserveMs: 300_000, + })); + const testHarness = harness(state, { now: () => now }); + await testHarness.service.manualSwitch('reserve'); + assert.equal(testHarness.read().appliedServerId, 'server-2'); + assert.equal(testHarness.read().failoverPolicy.enabled, true); + assert.equal(testHarness.read().failoverPolicy.paused, paused); + assert.equal(testHarness.read().failoverRuntimeState.holdUntil, new Date(now.getTime() + 300_000).toISOString()); + assert.equal(testHarness.calls.filter((call) => call === 'state:update').length, 1); + } }); test('post-commit monitoring failure does not report a committed pause as failed', async () => { diff --git a/test/web/failover-feature-contract.test.js b/test/web/failover-feature-contract.test.js index 5dc66f0..0c18373 100644 --- a/test/web/failover-feature-contract.test.js +++ b/test/web/failover-feature-contract.test.js @@ -46,12 +46,32 @@ test('failover settings use Harbor switches, a two-column channel table and plai assert.doesNotMatch(feature, / void onPause\(!automatic\)\}/); + assert.match(feature, /checked=\{!snapshot\.paused\}[\s\S]*disabled=\{blocked \|\| !snapshot.enabled\}/); + assert.match(feature, /client-failover-check-action[\s\S]*disabled=\{blocked \|\| checking \|\| !snapshot.enabled \|\| snapshot.activation !== 'active'\}/); + assert.doesNotMatch(feature, /client-failover-actions|client-failover-global-actions|client-failover-discard/); + assert.match(feature, /channel === 'primary' &&
Проверить оба канала<\/Tooltip>[\s\S]*\{switchRole \? `Переключить на/); + assert.match(feature, /M20 11a8 8 0 1 0-2\.3 6\.7M20 5v6h-6/); + assert.match(feature, /M4 12h15M14 7l5 5-5 5/); + assert.match(feature, /normalizeFailoverDraft = \(policy: FailoverPolicy\)[\s\S]*minimumReserveMs: Math\.round\(normalized\.minimumReserveMs \/ 60_000\) \* 60_000/); + assert.match(feature, /before="Оставаться на резервном канале не меньше" after="минут" min=\{1\} max=\{1440\} step=\{1\}[\s\S]*value=\{draft\.minimumReserveMs \/ 60_000\}[\s\S]*minimumReserveMs: Math\.round\(value\) \* 60_000/); + assert.doesNotMatch(feature, /className="client-failover-number-input"[\s\S]*max=\{max\}[\s\S]*step=\{step\}/); + assert.match(feature, / switchDrawer\(target\)[\s\S]*pendingTargetRef\.current = null/); + assert.match(styles, /\.client-failover-check-action\.is-running svg \{ animation: client-spin 900ms linear infinite; \}/); + assert.match(styles, /\.client-failover-direction-action svg \{[^}]*transition: transform 260ms cubic-bezier\(0\.16, 1, 0\.3, 1\)/); + assert.match(styles, /\.client-failover-direction-action svg\.is-primary \{ transform: rotate\(180deg\); \}/); + assert.match(styles, /@media \(prefers-reduced-motion: reduce\)[\s\S]*client-failover-direction-action svg[\s\S]*transition: none[\s\S]*client-failover-check-action\.is-running svg[\s\S]*animation: none/); assert.match(styles, /\.client-failover-switch\[aria-checked='true'\][\s\S]*translateX\(22px\)/); + assert.match(styles, /\.client-failover-header \{[^}]*position:\s*sticky[^}]*top:\s*0[^}]*background:/); assert.match(styles, /\.client-failover-heading \{[^}]*justify-content:\s*space-between[^}]*}/); assert.doesNotMatch(styles, /\.client-failover-heading \{[^}]*padding-right/); - assert.match(styles, /\.client-failover-channels \{[^}]*grid-template-columns:\s*repeat\(2, minmax\(0, 1fr\)\)/); + assert.match(styles, /\.client-failover-channels \{[^}]*grid-template-columns:\s*minmax\(0, 1fr\) 52px minmax\(0, 1fr\)/); + assert.match(styles, /\.client-failover-channel-actions \{[^}]*grid-column:\s*2[^}]*grid-row:\s*1/); + assert.match(styles, /\.client-failover-check-action, \.client-failover-direction-action \{[^}]*width:\s*44px[^}]*height:\s*44px/); assert.match(styles, /@media \(max-width: 560px\)[\s\S]*\.client-failover-channels \{ grid-template-columns:\s*minmax\(0, 1fr\)/); assert.match(styles, /\.client-failover-picker-list[\s\S]*opacity:\s*0[\s\S]*\.client-failover-picker\.is-open[\s\S]*opacity:\s*1/); assert.match(styles, /failover-service-out 300ms[\s\S]*@media \(prefers-reduced-motion: reduce\)/); @@ -67,13 +87,17 @@ test('failover settings use Harbor switches, a two-column channel table and plai assert.doesNotMatch(styles, /client-failover-advanced|failover-advanced-in|failover-advanced-out/); }); -test('runtime status keeps fixed geometry and explains active traffic without motion dependence', () => { +test('runtime status sits beside the channel controls and explains active traffic without motion dependence', () => { assert.match(feature, /Ждём паузу в передаче данных/); assert.match(feature, /Сейчас передаётся [\s\S]*Активных подключений:[\s\S]*transmittingConnections/); assert.match(feature, /activity\?\.blockers\.slice\(0, 2\)\.map/); assert.match(feature, /Ещё \{activity\.blockers\.length - 2\}/); assert.match(feature, /Проверяем основной канал ·[\s\S]*Проверим каналы снова через/); - assert.match(feature, /switchRole && snapshot\.enabled && snapshot\.activation === 'active'/); - assert.match(styles, /\.client-failover-runtime \{[^}]*min-height:\s*132px/); + assert.match(feature, /client-failover-direction-action[\s\S]*disabled=\{blocked \|\| !snapshot.enabled \|\| snapshot.activation !== 'active' \|\| !switchRole\}/); + assert.match(feature, /client-failover-channels[\s\S]*client-failover-runtime[\s\S]*Что проверять/); + assert.match(feature, /Сейчас используется[\s\S]*Основной канал[\s\S]*Резервный канал[\s\S]*Новые подключения:/); + assert.match(styles, /\.client-failover-runtime\.is-primary strong \{[^}]*var\(--harbor-connect\)/); + assert.match(styles, /\.client-failover-runtime\.is-reserve strong \{[^}]*var\(--harbor-gateway\)/); + assert.doesNotMatch(styles, /\.client-failover-runtime \{[^}]*min-height:\s*132px/); assert.match(styles, /@media \(prefers-reduced-motion: reduce\)[^{]*\{[^}]*\.client-failover-number-control:hover \.client-failover-number-steps[^}]*transition:\s*none/); }); diff --git a/test/web/responsive-layout-contract.test.js b/test/web/responsive-layout-contract.test.js index fd57892..ed768a5 100644 --- a/test/web/responsive-layout-contract.test.js +++ b/test/web/responsive-layout-contract.test.js @@ -104,9 +104,10 @@ test('tablet and mobile regions use normal flow with viewport-safe widths', () = assert.match(mobile, /\.client-secondary-menu \{[\s\S]*right:\s*8px/); assert.match(mobile, /\.client-power-control > \.harbor-brand \{[\s\S]*scale\(1\.35\)/); assert.match(mobile, /\.client-server-check \{[\s\S]*width:\s*44px/); + assert.match(styles, /@media \(max-width: 560px\)[\s\S]*\.client-failover-heading \{[\s\S]*flex-wrap:\s*wrap[\s\S]*\.client-failover-channel-actions \{[\s\S]*grid-column:\s*1[\s\S]*grid-row:\s*auto[\s\S]*display:\s*flex[\s\S]*justify-content:\s*center/); + assert.match(styles, /\.client-failover-channel-actions \{[^}]*grid-column:\s*2[^}]*display:\s*grid/); assert.match(rule('.client-drawer'), /width:\s*min\(580px, 100vw\)/); assert.match(styles, /\.client-confirmation-dialog\s*\{[\s\S]*width:\s*min\(430px, calc\(100vw - 48px\)\)/); - for (const viewport of [320, 390, 768]) { const pagePadding = viewport <= 560 ? 28 : 48; const panelPadding = 12; diff --git a/test/web/rule-editor-contract.test.js b/test/web/rule-editor-contract.test.js index 82507e3..7447d7f 100644 --- a/test/web/rule-editor-contract.test.js +++ b/test/web/rule-editor-contract.test.js @@ -11,6 +11,7 @@ const connection = fs.readFileSync(path.join(root, 'src/web/features/connection/ const subscription = fs.readFileSync(path.join(root, 'src/web/features/subscription/SubscriptionFeature.tsx'), 'utf8'); const routing = fs.readFileSync(path.join(root, 'src/web/features/routing/RoutingFeature.tsx'), 'utf8'); const instructions = fs.readFileSync(path.join(root, 'src/web/features/instructions/InstructionsFeature.tsx'), 'utf8'); +const failover = fs.readFileSync(path.join(root, 'src/web/features/failover/FailoverFeature.tsx'), 'utf8'); const dialog = fs.readFileSync(path.join(root, 'src/web/ui/ConfirmationDialog.tsx'), 'utf8'); const copyButton = fs.readFileSync(path.join(root, 'src/web/ui/CopyButton.tsx'), 'utf8'); const styles = readStyleSource(root); @@ -54,12 +55,14 @@ test('critical confirmations share one accessible blocking popup', () => { (component.match(/ crypto.createHash('sha256').update(value).digest('hex'); const acceptedLedger = { counts: { - cascadeEdges: 1058, + cascadeEdges: 1072, customProperties: 111, - declarations: 4131, + declarations: 4172, important: 0, keyframes: 50, media: 17, - rules: 1114, - variableReferences: 1055, + rules: 1128, + variableReferences: 1052, }, hashes: { - cascadeEdges: '77b6f34b3bc07b326f477cc436926fb9c4c573e5da9bba840c9bf937542b4488', + cascadeEdges: '2a01e700f68f3aae944f48e14490abaf58dbb0fc5c7c798622d95537cfaefc5d', customProperties: '42f9fa9f2caaab6e5d90ae7d224563355822fa270083ea3496cfe2caaaea50bf', - declarations: 'ac1ac026d0c9d656fde9b28f78faea216a518a44bd2856b2005041f7cb4abd11', + declarations: '92af2ebf3ebcce46292f3ff4ab8ce687b0340f894fb122cb6c19a2f46dba2507', duplicateKeyframes: '4f53cda18c2baa0c0354bb5f9a3ecbe5ed12ab4d8e11ba873c2f11161202b945', duplicateSelectors: '8982145dba05b33bf1c93b2d54cfbe76305b276ff3c657aa020144016ada5848', keyframes: 'af4b9ae18d070fd2462a9b050293f3821bf5017c6e7cc53bbe18dc826f0fe3b9', - ruleDeclarationSequences: '885efbe91db2ecb739f3c5aa42023576a849d28e639a1694ad13ed696bef77c5', - selectors: 'fbd8ac40b8d543a29b7140db906d1a3f7fc16a64ebbb380f358629f78657456a', - variableReferences: '70cef326744490dbb615e83457cd42b81b6f2322b0e93e4de6661d53db97e14b', - witnesses: 'e9f8c6e640c19375635847dc064edd6752a8216c6acd3c2aad6ffd18c1a4aaa2', + ruleDeclarationSequences: '415524da6346d9f93de0ef53cd82146f5781a7f304be7f90ee89202d81805939', + selectors: '0ff8c058c365d549c12c65153759007e59006d6f522d7545402408e811676e46', + variableReferences: '0fbcb39e235f068290e60ce52d92ae8f47f29fd11326d94ad9864b8c3051e92c', + witnesses: '78a56eafce572ab39538f6d3778fd0300da84e934cc8dacaacd8e789180fe543', }, }; @@ -211,7 +211,7 @@ test('client typography uses the shared semantic scale outside the token owner', test('accepted stylesheet has pinned declaration, selector, keyframe, variable, and cascade ledgers', () => { const witnesses = readStyleWitnesses(root); - assert.equal(witnesses.length, 1090); + assert.equal(witnesses.length, 1116); assert.equal(witnesses.filter((witness) => witness.unknown || witness.ancestorUnknown).length, 0); const ledger = createStyleLedger(readStyleSource(root), { witnesses }); assert.deepEqual(ledger.counts, acceptedLedger.counts); @@ -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); const assets = fs.readdirSync(path.join(root, 'dist/assets')).filter((file) => file.endsWith('.css')); - assert.deepEqual(assets, ['index-3s7H6Y0X.css']); + assert.deepEqual(assets, ['index-CPDEnja7.css']); const built = fs.readFileSync(path.join(root, 'dist/assets', assets[0])); - assert.equal(built.byteLength, 157874); - assert.equal(sha256(built), '99b874016cac6f1b617cd21d5a7ac957f491d8926fe78e8ba514d9313255488f'); + assert.equal(built.byteLength, 159016); + assert.equal(sha256(built), '2c9cf378a317ea633b1006299856806dccc4270a3bfe3e0aea00ec7f0ab3385e'); }); diff --git a/test/web/ui-foundations-contract.test.js b/test/web/ui-foundations-contract.test.js index 7c19fe6..e0f3833 100644 --- a/test/web/ui-foundations-contract.test.js +++ b/test/web/ui-foundations-contract.test.js @@ -32,7 +32,7 @@ test('all repeated client primitive consumers use the shared owners', () => { .map(({ source }) => source) .join('\n'); - assert.equal((production.match(/