Improve failover controls and preserve manual switching state
This commit is contained in:
@@ -0,0 +1 @@
|
|||||||
|
{"gateway":"192.168.50.111","interface":"en0","mac":"","observedAt":"2026-08-28T08:14:27.401Z"}
|
||||||
+11
@@ -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);
|
||||||
|
}
|
||||||
@@ -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"}
|
||||||
+11
@@ -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);
|
||||||
|
}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
{"outbounds":[{"type":"vless","tag":"server-a","server":"a.example","server_port":443},{"type":"direct","tag":"direct"}],"route":{"final":"direct"}}
|
||||||
@@ -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"}
|
||||||
+11
@@ -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);
|
||||||
|
}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
{"outbounds":[{"type":"vless","tag":"server-b","server":"b.example","server_port":8443},{"type":"direct","tag":"direct"}],"route":{"final":"server-b"}}
|
||||||
@@ -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"}
|
||||||
+11
@@ -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);
|
||||||
|
}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
{"outbounds":[{"type":"vless","tag":"stale-server","server":"stale.example","server_port":443},{"type":"direct","tag":"direct"}],"route":{"final":"stale-server"}}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
{"schemaVersion":4,"revision":2,"connectionDesired":"running"}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
{broken
|
||||||
+11
@@ -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);
|
||||||
|
}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
{"outbounds":[{"type":"vless","tag":"server-a","server":"state.example","server_port":443},{"type":"direct","tag":"direct"}],"route":{"final":"server-a"}}
|
||||||
@@ -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"}
|
||||||
@@ -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}]}
|
||||||
@@ -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);
|
||||||
+209
@@ -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 аудита не запускались.
|
||||||
@@ -305,7 +305,7 @@ export function createFailoverService(dependencies: FailoverServiceDependencies)
|
|||||||
appliedServerId: target.serverId,
|
appliedServerId: target.serverId,
|
||||||
appliedServerSnapshot: server,
|
appliedServerSnapshot: server,
|
||||||
failoverPolicy: reason === 'manual'
|
failoverPolicy: reason === 'manual'
|
||||||
? { ...state.failoverPolicy, paused: true }
|
? state.failoverPolicy
|
||||||
: role === 'primary' ? { ...state.failoverPolicy, paused: false } : state.failoverPolicy,
|
: role === 'primary' ? { ...state.failoverPolicy, paused: false } : state.failoverPolicy,
|
||||||
failoverRuntimeState: {
|
failoverRuntimeState: {
|
||||||
...state.failoverRuntimeState,
|
...state.failoverRuntimeState,
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
export const HARBOR_VERSIONS = Object.freeze({
|
export const HARBOR_VERSIONS = Object.freeze({
|
||||||
macClient: '0.31.0',
|
macClient: '0.31.1',
|
||||||
gatewayClient: '0.32.0',
|
gatewayClient: '0.32.1',
|
||||||
gatewayBackend: '0.32.0',
|
gatewayBackend: '0.32.1',
|
||||||
});
|
});
|
||||||
|
|
||||||
export interface ParsedVersion {
|
export interface ParsedVersion {
|
||||||
|
|||||||
@@ -710,6 +710,7 @@ export function ClientOverviewPage({
|
|||||||
activeSwitch?.finish();
|
activeSwitch?.finish();
|
||||||
|
|
||||||
if (current === target) {
|
if (current === target) {
|
||||||
|
if (target === 'failover') failoverFeature.pendingTargetRef.current = null;
|
||||||
drawerControls[target].close();
|
drawerControls[target].close();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -717,7 +718,13 @@ export function ClientOverviewPage({
|
|||||||
routingFeature.requestClose();
|
routingFeature.requestClose();
|
||||||
return;
|
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) {
|
if (!current) {
|
||||||
drawerControls[target].show();
|
drawerControls[target].show();
|
||||||
return;
|
return;
|
||||||
|
|||||||
@@ -3,23 +3,31 @@ import { flushSync } from 'react-dom';
|
|||||||
import { CONNECTIVITY_SITES, MAX_CUSTOM_DIAGNOSTIC_SERVICES, type DiagnosticSettings } from '../../../shared/connectivityDiagnostics.js';
|
import { CONNECTIVITY_SITES, MAX_CUSTOM_DIAGNOSTIC_SERVICES, type DiagnosticSettings } from '../../../shared/connectivityDiagnostics.js';
|
||||||
import { normalizeFailoverPolicy, type FailoverPolicy, type FailoverSnapshot } from '../../../shared/failover.js';
|
import { normalizeFailoverPolicy, type FailoverPolicy, type FailoverSnapshot } from '../../../shared/failover.js';
|
||||||
import type { ProfileSnapshot } from '../../../shared/contracts/state.js';
|
import type { ProfileSnapshot } from '../../../shared/contracts/state.js';
|
||||||
|
import { ConfirmationDialog } from '../../ui/ConfirmationDialog.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';
|
||||||
|
import { Tooltip } from '../../ui/Tooltip.js';
|
||||||
import { saveCustomDiagnosticService } from '../diagnostics/index.js';
|
import { saveCustomDiagnosticService } from '../diagnostics/index.js';
|
||||||
|
|
||||||
export function useFailoverFeature() {
|
export function useFailoverFeature() {
|
||||||
const [isOpen, setIsOpen] = useState(false);
|
const [isOpen, setIsOpen] = useState(false);
|
||||||
const panelRef = useRef<HTMLElement>(null);
|
const panelRef = useRef<HTMLElement>(null);
|
||||||
const toggleRef = useRef<HTMLButtonElement>(null);
|
const toggleRef = useRef<HTMLButtonElement>(null);
|
||||||
const closeRef = useRef<HTMLButtonElement>(null);
|
const closeRef = useRef<HTMLButtonElement>(null);
|
||||||
const beforeCloseRef = useRef<() => boolean>(() => true);
|
const beforeCloseRef = useRef<() => boolean>(() => true);
|
||||||
|
const pendingTargetRef = useRef<(() => void) | null>(null);
|
||||||
const close = () => {
|
const close = () => {
|
||||||
if (beforeCloseRef.current()) setIsOpen(false);
|
if (beforeCloseRef.current()) {
|
||||||
|
pendingTargetRef.current = null;
|
||||||
|
setIsOpen(false);
|
||||||
|
}
|
||||||
};
|
};
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!isOpen) return undefined;
|
if (!isOpen) return undefined;
|
||||||
const frame = requestAnimationFrame(() => closeRef.current?.focus());
|
const frame = requestAnimationFrame(() => closeRef.current?.focus());
|
||||||
const handleClose = (event: PointerEvent | KeyboardEvent) => {
|
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' && (event as KeyboardEvent).key !== 'Escape') return;
|
||||||
if (event.type !== 'keydown' && (
|
if (event.type !== 'keydown' && (
|
||||||
panelRef.current?.contains(event.target as Node) || toggleRef.current?.contains(event.target as Node)
|
panelRef.current?.contains(event.target as Node) || toggleRef.current?.contains(event.target as Node)
|
||||||
@@ -38,7 +46,7 @@ export function useFailoverFeature() {
|
|||||||
};
|
};
|
||||||
}, [isOpen]);
|
}, [isOpen]);
|
||||||
return {
|
return {
|
||||||
isOpen, panelRef, toggleRef, closeRef, beforeCloseRef, close,
|
isOpen, panelRef, toggleRef, closeRef, beforeCloseRef, pendingTargetRef, close,
|
||||||
toggle: () => isOpen ? close() : setIsOpen(true),
|
toggle: () => isOpen ? close() : setIsOpen(true),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -67,6 +75,14 @@ export function FailoverToggle({ feature, open, onToggle }: {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const seconds = (milliseconds: number) => Math.round(milliseconds / 1000);
|
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<HTMLInputElement>) {
|
function pulseNumber(event: FormEvent<HTMLInputElement>) {
|
||||||
if (matchMedia('(prefers-reduced-motion: reduce)').matches) return;
|
if (matchMedia('(prefers-reduced-motion: reduce)').matches) return;
|
||||||
@@ -309,7 +325,7 @@ export function FailoverPanel({
|
|||||||
onCheck: () => Promise<unknown>;
|
onCheck: () => Promise<unknown>;
|
||||||
onUpdateDiagnostics: (settings: unknown) => Promise<unknown>;
|
onUpdateDiagnostics: (settings: unknown) => Promise<unknown>;
|
||||||
}) {
|
}) {
|
||||||
const [draft, setDraft] = useState(() => snapshot.policy);
|
const [draft, setDraft] = useState(() => normalizeFailoverDraft(snapshot.policy));
|
||||||
const [dirty, setDirty] = useState(false);
|
const [dirty, setDirty] = useState(false);
|
||||||
const [confirmDiscard, setConfirmDiscard] = useState(false);
|
const [confirmDiscard, setConfirmDiscard] = useState(false);
|
||||||
const [addingService, setAddingService] = useState(false);
|
const [addingService, setAddingService] = useState(false);
|
||||||
@@ -319,25 +335,35 @@ export function FailoverPanel({
|
|||||||
const [openPicker, setOpenPicker] = useState('');
|
const [openPicker, setOpenPicker] = useState('');
|
||||||
const [removingCheckId, setRemovingCheckId] = useState('');
|
const [removingCheckId, setRemovingCheckId] = useState('');
|
||||||
const [manualChecking, setManualChecking] = useState(false);
|
const [manualChecking, setManualChecking] = useState(false);
|
||||||
|
const discardContinuationFrameRef = useRef<number | null>(null);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!dirty) setDraft(snapshot.policy);
|
if (!dirty) setDraft(normalizeFailoverDraft(snapshot.policy));
|
||||||
}, [snapshot.policy, dirty]);
|
}, [snapshot.policy, dirty]);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
feature.beforeCloseRef.current = () => {
|
feature.beforeCloseRef.current = () => {
|
||||||
if (!dirty) return true;
|
if (!dirty) {
|
||||||
|
feature.pendingTargetRef.current = null;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
setConfirmDiscard(true);
|
setConfirmDiscard(true);
|
||||||
return false;
|
return false;
|
||||||
};
|
};
|
||||||
const beforeUnload = (event: BeforeUnloadEvent) => {
|
const beforeUnload = (event: BeforeUnloadEvent) => {
|
||||||
if (!dirty) return;
|
if (!dirty) return;
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
|
event.returnValue = '';
|
||||||
};
|
};
|
||||||
window.addEventListener('beforeunload', beforeUnload);
|
window.addEventListener('beforeunload', beforeUnload);
|
||||||
return () => {
|
return () => {
|
||||||
feature.beforeCloseRef.current = () => true;
|
feature.beforeCloseRef.current = () => true;
|
||||||
window.removeEventListener('beforeunload', beforeUnload);
|
window.removeEventListener('beforeunload', beforeUnload);
|
||||||
};
|
};
|
||||||
}, [dirty, feature.beforeCloseRef]);
|
}, [dirty, feature.beforeCloseRef, feature.pendingTargetRef]);
|
||||||
|
useEffect(() => () => {
|
||||||
|
if (discardContinuationFrameRef.current !== null) {
|
||||||
|
cancelAnimationFrame(discardContinuationFrameRef.current);
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
const services = useMemo(() => [
|
const services = useMemo(() => [
|
||||||
...CONNECTIVITY_SITES,
|
...CONNECTIVITY_SITES,
|
||||||
...diagnostics.customServices,
|
...diagnostics.customServices,
|
||||||
@@ -368,11 +394,11 @@ export function FailoverPanel({
|
|||||||
...(diagnostics.customServices.length < MAX_CUSTOM_DIAGNOSTIC_SERVICES ? [{ id: '__new-service', label: 'Новый HTTPS-сервис…' }] : []),
|
...(diagnostics.customServices.length < MAX_CUSTOM_DIAGNOSTIC_SERVICES ? [{ id: '__new-service', label: 'Новый HTTPS-сервис…' }] : []),
|
||||||
], [diagnostics.customServices.length, draft.checks, services]);
|
], [diagnostics.customServices.length, draft.checks, services]);
|
||||||
const update = (value: Partial<FailoverPolicy>) => {
|
const update = (value: Partial<FailoverPolicy>) => {
|
||||||
setDraft((current) => normalizeFailoverPolicy({ ...current, ...value }));
|
setDraft((current) => normalizeFailoverDraft({ ...current, ...value }));
|
||||||
setDirty(true);
|
setDirty(true);
|
||||||
};
|
};
|
||||||
const updateChecks = (change: (checks: FailoverPolicy['checks']) => FailoverPolicy['checks']) => {
|
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);
|
setDirty(true);
|
||||||
};
|
};
|
||||||
const updateTarget = (channel: 'primary' | 'reserve', optionId: string) => {
|
const updateTarget = (channel: 'primary' | 'reserve', optionId: string) => {
|
||||||
@@ -383,6 +409,7 @@ export function FailoverPanel({
|
|||||||
? snapshot.currentRole
|
? snapshot.currentRole
|
||||||
: null;
|
: null;
|
||||||
const switchRole = role === 'primary' ? 'reserve' : role === 'reserve' ? 'primary' : null;
|
const switchRole = role === 'primary' ? 'reserve' : role === 'reserve' ? 'primary' : null;
|
||||||
|
const checking = manualChecking || snapshot.reason === 'checking-channels';
|
||||||
const activity = snapshot.trafficActivity;
|
const activity = snapshot.trafficActivity;
|
||||||
const targetExists = (target: FailoverPolicy['primary']) => profiles
|
const targetExists = (target: FailoverPolicy['primary']) => profiles
|
||||||
.find(({ id }) => id === target.profileId)?.servers.some(({ id }) => id === target.serverId);
|
.find(({ id }) => id === target.profileId)?.servers.some(({ id }) => id === target.serverId);
|
||||||
@@ -437,6 +464,9 @@ export function FailoverPanel({
|
|||||||
<span>Gateway</span>
|
<span>Gateway</span>
|
||||||
<div className="client-failover-heading">
|
<div className="client-failover-heading">
|
||||||
<h2>Резервный канал</h2>
|
<h2>Резервный канал</h2>
|
||||||
|
<div className="client-failover-header-actions">
|
||||||
|
<div className="client-failover-switch-setting">
|
||||||
|
<span>Канал</span>
|
||||||
<HarborSwitch
|
<HarborSwitch
|
||||||
checked={draft.enabled}
|
checked={draft.enabled}
|
||||||
label={draft.enabled ? 'Выключить резервный канал' : 'Включить резервный канал'}
|
label={draft.enabled ? 'Выключить резервный канал' : 'Включить резервный канал'}
|
||||||
@@ -448,16 +478,34 @@ export function FailoverPanel({
|
|||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<p>Если основной канал перестанет работать, Harbor направит новые подключения через резервный канал. Уже открытые подключения продолжат работать через прежний канал.</p>
|
<div className="client-failover-switch-setting">
|
||||||
{snapshot.enabled && <div className="client-failover-global-actions">
|
<span>Автоматика</span>
|
||||||
<button type="button" disabled={blocked} onClick={() => void onPause(!snapshot.paused)}>{snapshot.paused ? 'Продолжить автоматическое переключение' : 'Приостановить автоматическое переключение'}</button>
|
<HarborSwitch
|
||||||
<small>{snapshot.paused ? 'Новые подключения продолжают идти через текущий канал.' : 'Harbor проверяет оба канала и при необходимости переключает новые подключения.'}</small>
|
checked={!snapshot.paused}
|
||||||
</div>}
|
label={snapshot.paused ? 'Включить автоматическое переключение' : 'Остановить автоматическое переключение'}
|
||||||
|
disabled={blocked || !snapshot.enabled}
|
||||||
|
onChange={(automatic) => void onPause(!automatic)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
className="client-failover-save"
|
||||||
|
type="submit"
|
||||||
|
form="client-failover-form"
|
||||||
|
disabled={blocked || !dirty || !draftValid}
|
||||||
|
>
|
||||||
|
Сохранить
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
</header>
|
</header>
|
||||||
|
<div className="client-failover-intro">
|
||||||
|
<p>Если основной канал перестанет работать, Harbor направит новые подключения через резервный канал. Уже открытые подключения продолжат работать через прежний канал.</p>
|
||||||
|
{snapshot.enabled && <small className="client-failover-pause-hint">{snapshot.paused ? 'Новые подключения продолжают идти через текущий канал.' : 'Harbor проверяет оба канала и при необходимости переключает новые подключения.'}</small>}
|
||||||
|
</div>
|
||||||
|
|
||||||
<form className="client-failover-form" onSubmit={(event) => {
|
<form id="client-failover-form" className="client-failover-form" onSubmit={(event) => {
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
void onSave(draft).then((result) => { if (result !== false) setDirty(false); });
|
void onSave(normalizeFailoverDraft(draft)).then((result) => { if (result !== false) setDirty(false); });
|
||||||
}}>
|
}}>
|
||||||
<section className="client-failover-channels" aria-label="Основной и резервный каналы">
|
<section className="client-failover-channels" aria-label="Основной и резервный каналы">
|
||||||
{(['primary', 'reserve'] as const).map((channel) => {
|
{(['primary', 'reserve'] as const).map((channel) => {
|
||||||
@@ -479,7 +527,7 @@ export function FailoverPanel({
|
|||||||
: channel === 'primary' && snapshot.currentRole === 'reserve' && health === 'healthy' && snapshot.reason === 'recovery-hold'
|
: channel === 'primary' && snapshot.currentRole === 'reserve' && health === 'healthy' && snapshot.reason === 'recovery-hold'
|
||||||
? 'Проверяем восстановление'
|
? 'Проверяем восстановление'
|
||||||
: health === 'healthy' ? 'Работает' : health === 'unhealthy' ? 'Недоступен' : health === 'not-monitoring' ? 'Проверка выключена' : 'Ждёт проверки';
|
: health === 'healthy' ? 'Работает' : health === 'unhealthy' ? 'Недоступен' : health === 'not-monitoring' ? 'Проверка выключена' : 'Ждёт проверки';
|
||||||
return <article className="client-failover-channel" data-channel={channel} key={channel}>
|
return <div className="client-failover-channel-slot" key={channel}><article className="client-failover-channel" data-channel={channel}>
|
||||||
<div className="client-failover-channel-title">
|
<div className="client-failover-channel-title">
|
||||||
<h3>{channel === 'primary' ? 'Основной' : 'Резервный'}</h3>
|
<h3>{channel === 'primary' ? 'Основной' : 'Резервный'}</h3>
|
||||||
<strong className={health === 'healthy' ? 'is-healthy' : health === 'unhealthy' || missing ? 'is-unhealthy' : ''}>{healthLabel}</strong>
|
<strong className={health === 'healthy' ? 'is-healthy' : health === 'unhealthy' || missing ? 'is-unhealthy' : ''}>{healthLabel}</strong>
|
||||||
@@ -494,13 +542,63 @@ export function FailoverPanel({
|
|||||||
onOpenChange={(open) => setOpenPicker(open ? channel : '')}
|
onOpenChange={(open) => setOpenPicker(open ? channel : '')}
|
||||||
onChange={(optionId) => updateTarget(channel, optionId)}
|
onChange={(optionId) => updateTarget(channel, optionId)}
|
||||||
/>
|
/>
|
||||||
</article>;
|
</article>{channel === 'primary' && <div className="client-failover-channel-actions" aria-label="Действия с каналами">
|
||||||
|
<button
|
||||||
|
className={`client-failover-check-action client-tooltip-anchor${checking ? ' is-running' : ''}`}
|
||||||
|
type="button"
|
||||||
|
aria-label="Проверить оба канала"
|
||||||
|
aria-busy={checking}
|
||||||
|
disabled={blocked || checking || !snapshot.enabled || snapshot.activation !== 'active'}
|
||||||
|
onClick={() => {
|
||||||
|
setManualChecking(true);
|
||||||
|
void onCheck().finally(() => setManualChecking(false));
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<svg viewBox="0 0 24 24" aria-hidden="true">
|
||||||
|
<path d="M20 11a8 8 0 1 0-2.3 6.7M20 5v6h-6" />
|
||||||
|
</svg>
|
||||||
|
<Tooltip>Проверить оба канала</Tooltip>
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
className="client-failover-direction-action client-tooltip-anchor"
|
||||||
|
type="button"
|
||||||
|
aria-label={switchRole ? `Переключить на ${switchRole === 'primary' ? 'основной' : 'резервный'} канал` : 'Переключить канал'}
|
||||||
|
disabled={blocked || !snapshot.enabled || snapshot.activation !== 'active' || !switchRole}
|
||||||
|
onClick={() => { if (switchRole) void onSwitch(switchRole); }}
|
||||||
|
>
|
||||||
|
<svg className={`client-failover-direction-icon ${switchRole === 'primary' ? 'is-primary' : 'is-reserve'}`} viewBox="0 0 24 24" aria-hidden="true">
|
||||||
|
<path d="M4 12h15M14 7l5 5-5 5" />
|
||||||
|
</svg>
|
||||||
|
<Tooltip>{switchRole ? `Переключить на ${switchRole === 'primary' ? 'основной' : 'резервный'} канал` : 'Переключение недоступно'}</Tooltip>
|
||||||
|
</button>
|
||||||
|
</div>}</div>;
|
||||||
})}
|
})}
|
||||||
<div className="client-failover-checking" role="status" aria-live="polite">
|
<div className="client-failover-checking" role="status" aria-live="polite">
|
||||||
{(manualChecking || snapshot.reason === 'checking-channels' ? ['primary', 'reserve'] as const : []).map((checkingRole) => <span key={checkingRole}>Проверяем {checkingRole === 'primary' ? 'основной' : 'резервный'} канал</span>)}
|
{(manualChecking || snapshot.reason === 'checking-channels' ? ['primary', 'reserve'] as const : []).map((checkingRole) => <span key={checkingRole}>Проверяем {checkingRole === 'primary' ? 'основной' : 'резервный'} канал</span>)}
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
|
<section className={`client-failover-runtime ${role === 'primary' ? 'is-primary' : role === 'reserve' ? 'is-reserve' : 'is-none'}`} aria-label="Текущее состояние каналов">
|
||||||
|
<span className="client-failover-runtime-label">Сейчас используется</span>
|
||||||
|
<strong role="status" aria-live="polite">{blocked
|
||||||
|
? 'Harbor завершает текущее действие'
|
||||||
|
: role === 'primary'
|
||||||
|
? 'Основной канал'
|
||||||
|
: role === 'reserve'
|
||||||
|
? 'Резервный канал'
|
||||||
|
: 'Канал пока не выбран'}</strong>
|
||||||
|
<span>{blocked ? 'Подождите…' : reasonLabel(snapshot.reason)}</span>
|
||||||
|
<span>{role
|
||||||
|
? `Новые подключения: ${targetLabel(profiles, snapshot[role].target)}`
|
||||||
|
: snapshot.reason === 'vpn-stopped'
|
||||||
|
? `При запуске VPN будет выбран: ${targetLabel(profiles, draft.primary)}`
|
||||||
|
: `После перезапуска VPN будет выбран: ${targetLabel(profiles, draft.primary)}`}</span>
|
||||||
|
{snapshot.nextDecisionAt && <span>Проверим каналы снова через {seconds(Math.max(0, Date.parse(snapshot.nextDecisionAt) - Date.now()))} с</span>}
|
||||||
|
{activity && <span>{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)} с` : 'Не удалось проверить передачу данных. Автоматическое переключение остановлено'}</span>}
|
||||||
|
{activity?.blockers.slice(0, 2).map((blocker) => <small key={`${blocker.device}:${blocker.service}`}>{blocker.device} · {blocker.service} · {Math.round((blocker.uploadBytesPerSecond + blocker.downloadBytesPerSecond) / 1024)} КБ/с</small>)}
|
||||||
|
{activity && activity.blockers.length > 2 && <small>Ещё {activity.blockers.length - 2}</small>}
|
||||||
|
</section>
|
||||||
|
|
||||||
<fieldset className="client-failover-services">
|
<fieldset className="client-failover-services">
|
||||||
<legend><span className="client-failover-section-header"><strong>Что проверять</strong><small>Harbor проверяет эти сайты через оба канала, чтобы понять, какой канал работает.</small></span></legend>
|
<legend><span className="client-failover-section-header"><strong>Что проверять</strong><small>Harbor проверяет эти сайты через оба канала, чтобы понять, какой канал работает.</small></span></legend>
|
||||||
{draft.checks.map((check) => {
|
{draft.checks.map((check) => {
|
||||||
@@ -595,42 +693,41 @@ export function FailoverPanel({
|
|||||||
<p>Если основной канал снова перестаёт работать, Harbor дольше оставляет новые подключения на резервном канале.</p>
|
<p>Если основной канал снова перестаёт работать, Harbor дольше оставляет новые подключения на резервном канале.</p>
|
||||||
</header>
|
</header>
|
||||||
<div className="client-failover-protection-options">
|
<div className="client-failover-protection-options">
|
||||||
<FailoverNumberSetting before="Оставаться на резервном канале не меньше" after="секунд" min={60} max={86400} ariaLabel="Минимальное время на резервном канале" value={seconds(draft.minimumReserveMs)} disabled={blocked || !draft.enabled} onChange={(value) => update({ minimumReserveMs: value * 1_000 })} />
|
<FailoverNumberSetting before="Оставаться на резервном канале не меньше" after="минут" min={1} max={1440} step={1} ariaLabel="Минимальное время на резервном канале" value={draft.minimumReserveMs / 60_000} disabled={blocked || !draft.enabled} onChange={(value) => update({ minimumReserveMs: Math.round(value) * 60_000 })} />
|
||||||
<FailoverNumberSetting before="Считать основной канал нестабильным после" after="повторных сбоев" min={2} max={10} step={1} ariaLabel="Количество повторных сбоев" value={draft.flapProtection.count} disabled={blocked || !draft.enabled} onChange={(value) => update({ flapProtection: { ...draft.flapProtection, count: value } })} />
|
<FailoverNumberSetting before="Считать основной канал нестабильным после" after="повторных сбоев" min={2} max={10} step={1} ariaLabel="Количество повторных сбоев" value={draft.flapProtection.count} disabled={blocked || !draft.enabled} onChange={(value) => update({ flapProtection: { ...draft.flapProtection, count: value } })} />
|
||||||
<FailoverNumberSetting before="Учитывать сбои, случившиеся не более" after="ч назад" min={1} max={72} step={1} ariaLabel="Период повторных сбоев" value={Math.round(draft.flapProtection.windowMs / 3_600_000)} disabled={blocked || !draft.enabled} onChange={(value) => update({ flapProtection: { ...draft.flapProtection, windowMs: value * 3_600_000 } })} />
|
<FailoverNumberSetting before="Учитывать сбои, случившиеся не более" after="ч назад" min={1} max={72} step={1} ariaLabel="Период повторных сбоев" value={Math.round(draft.flapProtection.windowMs / 3_600_000)} disabled={blocked || !draft.enabled} onChange={(value) => update({ flapProtection: { ...draft.flapProtection, windowMs: value * 3_600_000 } })} />
|
||||||
<FailoverNumberSetting before="После повторных сбоев не возвращаться на основной канал" after="минут" min={10} max={10080} ariaLabel="Длительность карантина основного канала" value={Math.round(draft.flapProtection.quarantineMs / 60_000)} disabled={blocked || !draft.enabled} onChange={(value) => update({ flapProtection: { ...draft.flapProtection, quarantineMs: value * 60_000 } })} />
|
<FailoverNumberSetting before="После повторных сбоев не возвращаться на основной канал" after="минут" min={10} max={10080} ariaLabel="Длительность карантина основного канала" value={Math.round(draft.flapProtection.quarantineMs / 60_000)} disabled={blocked || !draft.enabled} onChange={(value) => update({ flapProtection: { ...draft.flapProtection, quarantineMs: value * 60_000 } })} />
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<div className="client-failover-runtime">
|
|
||||||
<strong role="status" aria-live="polite">{blocked ? 'Подождите, Harbor завершает текущее действие…' : snapshot.activation === 'pending' ? 'Резервный канал включится при следующем запуске VPN' : reasonLabel(snapshot.reason)}</strong>
|
|
||||||
<span>{role
|
|
||||||
? `Новые подключения: ${targetLabel(profiles, snapshot[role].target)}`
|
|
||||||
: snapshot.reason === 'vpn-stopped'
|
|
||||||
? `При запуске VPN будет выбран: ${targetLabel(profiles, draft.primary)}`
|
|
||||||
: `После перезапуска VPN будет выбран: ${targetLabel(profiles, draft.primary)}`}</span>
|
|
||||||
{snapshot.nextDecisionAt && <span>Проверим каналы снова через {seconds(Math.max(0, Date.parse(snapshot.nextDecisionAt) - Date.now()))} с</span>}
|
|
||||||
{activity && <span>{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)} с` : 'Не удалось проверить передачу данных. Автоматическое переключение остановлено'}</span>}
|
|
||||||
{activity?.blockers.slice(0, 2).map((blocker) => <small key={`${blocker.device}:${blocker.service}`}>{blocker.device} · {blocker.service} · {Math.round((blocker.uploadBytesPerSecond + blocker.downloadBytesPerSecond) / 1024)} КБ/с</small>)}
|
|
||||||
{activity && activity.blockers.length > 2 && <small>Ещё {activity.blockers.length - 2}</small>}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{!draftValid && <p className="client-failover-validation">Выберите разные серверы для основного и резервного каналов и хотя бы один сайт для проверки.</p>}
|
{!draftValid && <p className="client-failover-validation">Выберите разные серверы для основного и резервного каналов и хотя бы один сайт для проверки.</p>}
|
||||||
{confirmDiscard && <div className="client-failover-discard" role="alert">
|
|
||||||
<span>Отменить несохранённые изменения?</span>
|
|
||||||
<button type="button" onClick={() => { setDraft(snapshot.policy); setDirty(false); setConfirmDiscard(false); feature.beforeCloseRef.current = () => true; feature.close(); }}>Отменить изменения</button>
|
|
||||||
<button type="button" onClick={() => setConfirmDiscard(false)}>Продолжить настройку</button>
|
|
||||||
</div>}
|
|
||||||
|
|
||||||
<div className="client-failover-actions">
|
|
||||||
<button type="button" disabled={blocked || manualChecking || !snapshot.enabled || snapshot.activation !== 'active'} onClick={() => {
|
|
||||||
setManualChecking(true);
|
|
||||||
void onCheck().finally(() => setManualChecking(false));
|
|
||||||
}}>Проверить оба канала</button>
|
|
||||||
<button type="submit" disabled={blocked || !dirty || !draftValid}>Сохранить</button>
|
|
||||||
{switchRole && snapshot.enabled && snapshot.activation === 'active' && <button type="button" disabled={blocked} onClick={() => void onSwitch(switchRole)}>Переключить новые подключения на {switchRole === 'reserve' ? 'резервный канал' : 'основной канал'}</button>}
|
|
||||||
{(snapshot.currentRole === 'primary' || snapshot.currentRole === 'reserve') && <small>Открытые подключения останутся на прежнем канале.</small>}
|
|
||||||
</div>
|
|
||||||
</form>
|
</form>
|
||||||
|
<ConfirmationDialog
|
||||||
|
open={confirmDiscard}
|
||||||
|
id="discard-failover"
|
||||||
|
title="Закрыть без сохранения?"
|
||||||
|
description="Несохранённые настройки резервного канала будут потеряны."
|
||||||
|
cancelLabel="Остаться"
|
||||||
|
confirmLabel="Закрыть без сохранения"
|
||||||
|
onCancel={() => {
|
||||||
|
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();
|
||||||
|
});
|
||||||
|
}}
|
||||||
|
/>
|
||||||
</Drawer>;
|
</Drawer>;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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-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 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-header-actions { min-width: 0; display: flex; flex-wrap: wrap; align-items: center; justify-content: flex-end; gap: 8px 16px; }
|
||||||
.client-failover-global-actions { min-height: 30px; display: flex; flex-wrap: wrap; align-items: baseline; gap: 3px 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-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-switch-setting .client-failover-switch { transform: scale(.78); }
|
||||||
.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-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-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 { 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); }
|
.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[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:disabled { cursor: default; opacity: .42; }
|
||||||
.client-failover-switch:focus-visible { outline: 2px solid var(--client-accent); outline-offset: 0; border-radius: 999px; }
|
.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 { 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 { 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); }
|
.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-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-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-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.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 { 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; }
|
.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-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-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 { 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 { display: grid; gap: 5px; margin: 0; padding: 0; border: 0; }
|
||||||
.client-failover-services legend { width: 100%; margin-bottom: 14px; padding: 0; }
|
.client-failover-services legend { width: 100%; margin-bottom: 14px; padding: 0; }
|
||||||
.client-failover-section-header { display: grid; gap: 4px; margin-bottom: 12px; }
|
.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-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 { display: grid; gap: 5px; }
|
||||||
.client-failover-protection-options { display: grid; gap: 0; }
|
.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 { display: grid; gap: 4px; margin-top: -10px; padding: 8px 0 2px; 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-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-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-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-pause-hint { color: var(--client-muted); font: var(--type-control); letter-spacing: var(--type-control-tracking); text-transform: var(--type-control-transform); }
|
||||||
.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-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-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-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-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); }
|
.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-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); } }
|
@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 (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 { transition: none; } .client-failover-service, .client-failover-service-editor { animation: none; } }
|
@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; } }
|
||||||
|
|||||||
@@ -514,12 +514,22 @@ test('selector acknowledgement precedes state commit and a failed commit rolls s
|
|||||||
assert.equal(state.appliedServerId, 'server-1');
|
assert.equal(state.appliedServerId, 'server-1');
|
||||||
});
|
});
|
||||||
|
|
||||||
test('manual selector and pause publish in one canonical commit', async () => {
|
test('manual switch preserves automation and starts the configured reserve hold', async () => {
|
||||||
const testHarness = harness(serviceState());
|
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');
|
await testHarness.service.manualSwitch('reserve');
|
||||||
assert.equal(testHarness.read().appliedServerId, 'server-2');
|
assert.equal(testHarness.read().appliedServerId, 'server-2');
|
||||||
assert.equal(testHarness.read().failoverPolicy.paused, true);
|
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);
|
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 () => {
|
test('post-commit monitoring failure does not report a committed pause as failed', async () => {
|
||||||
|
|||||||
@@ -46,12 +46,32 @@ test('failover settings use Harbor switches, a two-column channel table and plai
|
|||||||
assert.doesNotMatch(feature, /<details|<summary|Нет данных|текущий канал вне настроенной пары/);
|
assert.doesNotMatch(feature, /<details|<summary|Нет данных|текущий канал вне настроенной пары/);
|
||||||
assert.doesNotMatch(page, /Текущий канал вне резервной пары/);
|
assert.doesNotMatch(page, /Текущий канал вне резервной пары/);
|
||||||
assert.match(page, /Резерв применится после перезапуска VPN/);
|
assert.match(page, /Резерв применится после перезапуска VPN/);
|
||||||
assert.match(feature, /Приостановить автоматическое переключение[\s\S]*Проверить оба канала[\s\S]*Переключить новые подключения на/);
|
assert.match(feature, /client-failover-header-actions[\s\S]*Автоматика[\s\S]*checked=\{!snapshot\.paused\}[\s\S]*Включить автоматическое переключение[\s\S]*Остановить автоматическое переключение[\s\S]*className="client-failover-save"[\s\S]*type="submit"[\s\S]*form="client-failover-form"[\s\S]*Сохранить/);
|
||||||
assert.match(feature, /beforeunload/);
|
assert.match(feature, /onChange=\{\(automatic\) => 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' && <div className="client-failover-channel-actions"[\s\S]*client-failover-check-action client-tooltip-anchor[\s\S]*aria-label="Проверить оба канала"[\s\S]*aria-busy=\{checking\}[\s\S]*client-failover-direction-action client-tooltip-anchor[\s\S]*aria-label=\{switchRole \? `Переключить на \$\{switchRole === 'primary' \? 'основной' : 'резервный'\} канал`/);
|
||||||
|
assert.match(feature, /<Tooltip>Проверить оба канала<\/Tooltip>[\s\S]*<Tooltip>\{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, /<ConfirmationDialog[\s\S]*id="discard-failover"[\s\S]*Закрыть без сохранения\?[\s\S]*Несохранённые настройки резервного канала будут потеряны\.[\s\S]*Остаться[\s\S]*Закрыть без сохранения/);
|
||||||
|
assert.match(feature, /discardContinuationFrameRef[\s\S]*cancelAnimationFrame[\s\S]*requestAnimationFrame[\s\S]*continueNavigation[\s\S]*feature\.close\(\)/);
|
||||||
|
assert.match(page, /if \(!failoverFeature\.beforeCloseRef\.current\(\)\)[\s\S]*pendingTargetRef\.current = \(\) => 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-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.match(styles, /\.client-failover-heading \{[^}]*justify-content:\s*space-between[^}]*}/);
|
||||||
assert.doesNotMatch(styles, /\.client-failover-heading \{[^}]*padding-right/);
|
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, /@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, /\.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\)/);
|
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/);
|
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, /Ждём паузу в передаче данных/);
|
||||||
assert.match(feature, /Сейчас передаётся [\s\S]*Активных подключений:[\s\S]*transmittingConnections/);
|
assert.match(feature, /Сейчас передаётся [\s\S]*Активных подключений:[\s\S]*transmittingConnections/);
|
||||||
assert.match(feature, /activity\?\.blockers\.slice\(0, 2\)\.map/);
|
assert.match(feature, /activity\?\.blockers\.slice\(0, 2\)\.map/);
|
||||||
assert.match(feature, /Ещё \{activity\.blockers\.length - 2\}/);
|
assert.match(feature, /Ещё \{activity\.blockers\.length - 2\}/);
|
||||||
assert.match(feature, /Проверяем основной канал ·[\s\S]*Проверим каналы снова через/);
|
assert.match(feature, /Проверяем основной канал ·[\s\S]*Проверим каналы снова через/);
|
||||||
assert.match(feature, /switchRole && snapshot\.enabled && snapshot\.activation === 'active'/);
|
assert.match(feature, /client-failover-direction-action[\s\S]*disabled=\{blocked \|\| !snapshot.enabled \|\| snapshot.activation !== 'active' \|\| !switchRole\}/);
|
||||||
assert.match(styles, /\.client-failover-runtime \{[^}]*min-height:\s*132px/);
|
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/);
|
assert.match(styles, /@media \(prefers-reduced-motion: reduce\)[^{]*\{[^}]*\.client-failover-number-control:hover \.client-failover-number-steps[^}]*transition:\s*none/);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -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-secondary-menu \{[\s\S]*right:\s*8px/);
|
||||||
assert.match(mobile, /\.client-power-control > \.harbor-brand \{[\s\S]*scale\(1\.35\)/);
|
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(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(rule('.client-drawer'), /width:\s*min\(580px, 100vw\)/);
|
||||||
assert.match(styles, /\.client-confirmation-dialog\s*\{[\s\S]*width:\s*min\(430px, calc\(100vw - 48px\)\)/);
|
assert.match(styles, /\.client-confirmation-dialog\s*\{[\s\S]*width:\s*min\(430px, calc\(100vw - 48px\)\)/);
|
||||||
|
|
||||||
for (const viewport of [320, 390, 768]) {
|
for (const viewport of [320, 390, 768]) {
|
||||||
const pagePadding = viewport <= 560 ? 28 : 48;
|
const pagePadding = viewport <= 560 ? 28 : 48;
|
||||||
const panelPadding = 12;
|
const panelPadding = 12;
|
||||||
|
|||||||
@@ -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 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 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 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 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 copyButton = fs.readFileSync(path.join(root, 'src/web/ui/CopyButton.tsx'), 'utf8');
|
||||||
const styles = readStyleSource(root);
|
const styles = readStyleSource(root);
|
||||||
@@ -54,12 +55,14 @@ test('critical confirmations share one accessible blocking popup', () => {
|
|||||||
(component.match(/<ConfirmationDialog/g) || []).length
|
(component.match(/<ConfirmationDialog/g) || []).length
|
||||||
+ (connection.match(/<ConfirmationDialog/g) || []).length
|
+ (connection.match(/<ConfirmationDialog/g) || []).length
|
||||||
+ (subscription.match(/<ConfirmationDialog/g) || []).length
|
+ (subscription.match(/<ConfirmationDialog/g) || []).length
|
||||||
+ (routing.match(/<ConfirmationDialog/g) || []).length,
|
+ (routing.match(/<ConfirmationDialog/g) || []).length
|
||||||
3,
|
+ (failover.match(/<ConfirmationDialog/g) || []).length,
|
||||||
|
4,
|
||||||
);
|
);
|
||||||
assert.match(connection, /id="stop-connection"/);
|
assert.match(connection, /id="stop-connection"/);
|
||||||
assert.match(routing, /id="discard-local-rules"/);
|
assert.match(routing, /id="discard-local-rules"/);
|
||||||
assert.match(subscription, /id="delete-subscription"/);
|
assert.match(subscription, /id="delete-subscription"/);
|
||||||
|
assert.match(failover, /id="discard-failover"/);
|
||||||
assert.doesNotMatch(component, /client-local-rules-discard|client-delete-confirmation/);
|
assert.doesNotMatch(component, /client-local-rules-discard|client-delete-confirmation/);
|
||||||
assert.match(dialog, /role="alertdialog"/);
|
assert.match(dialog, /role="alertdialog"/);
|
||||||
assert.match(dialog, /aria-modal="true"/);
|
assert.match(dialog, /aria-modal="true"/);
|
||||||
|
|||||||
@@ -39,26 +39,26 @@ 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: 1058,
|
cascadeEdges: 1072,
|
||||||
customProperties: 111,
|
customProperties: 111,
|
||||||
declarations: 4131,
|
declarations: 4172,
|
||||||
important: 0,
|
important: 0,
|
||||||
keyframes: 50,
|
keyframes: 50,
|
||||||
media: 17,
|
media: 17,
|
||||||
rules: 1114,
|
rules: 1128,
|
||||||
variableReferences: 1055,
|
variableReferences: 1052,
|
||||||
},
|
},
|
||||||
hashes: {
|
hashes: {
|
||||||
cascadeEdges: '77b6f34b3bc07b326f477cc436926fb9c4c573e5da9bba840c9bf937542b4488',
|
cascadeEdges: '2a01e700f68f3aae944f48e14490abaf58dbb0fc5c7c798622d95537cfaefc5d',
|
||||||
customProperties: '42f9fa9f2caaab6e5d90ae7d224563355822fa270083ea3496cfe2caaaea50bf',
|
customProperties: '42f9fa9f2caaab6e5d90ae7d224563355822fa270083ea3496cfe2caaaea50bf',
|
||||||
declarations: 'ac1ac026d0c9d656fde9b28f78faea216a518a44bd2856b2005041f7cb4abd11',
|
declarations: '92af2ebf3ebcce46292f3ff4ab8ce687b0340f894fb122cb6c19a2f46dba2507',
|
||||||
duplicateKeyframes: '4f53cda18c2baa0c0354bb5f9a3ecbe5ed12ab4d8e11ba873c2f11161202b945',
|
duplicateKeyframes: '4f53cda18c2baa0c0354bb5f9a3ecbe5ed12ab4d8e11ba873c2f11161202b945',
|
||||||
duplicateSelectors: '8982145dba05b33bf1c93b2d54cfbe76305b276ff3c657aa020144016ada5848',
|
duplicateSelectors: '8982145dba05b33bf1c93b2d54cfbe76305b276ff3c657aa020144016ada5848',
|
||||||
keyframes: 'af4b9ae18d070fd2462a9b050293f3821bf5017c6e7cc53bbe18dc826f0fe3b9',
|
keyframes: 'af4b9ae18d070fd2462a9b050293f3821bf5017c6e7cc53bbe18dc826f0fe3b9',
|
||||||
ruleDeclarationSequences: '885efbe91db2ecb739f3c5aa42023576a849d28e639a1694ad13ed696bef77c5',
|
ruleDeclarationSequences: '415524da6346d9f93de0ef53cd82146f5781a7f304be7f90ee89202d81805939',
|
||||||
selectors: 'fbd8ac40b8d543a29b7140db906d1a3f7fc16a64ebbb380f358629f78657456a',
|
selectors: '0ff8c058c365d549c12c65153759007e59006d6f522d7545402408e811676e46',
|
||||||
variableReferences: '70cef326744490dbb615e83457cd42b81b6f2322b0e93e4de6661d53db97e14b',
|
variableReferences: '0fbcb39e235f068290e60ce52d92ae8f47f29fd11326d94ad9864b8c3051e92c',
|
||||||
witnesses: 'e9f8c6e640c19375635847dc064edd6752a8216c6acd3c2aad6ffd18c1a4aaa2',
|
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', () => {
|
test('accepted stylesheet has pinned declaration, selector, keyframe, variable, and cascade ledgers', () => {
|
||||||
const witnesses = readStyleWitnesses(root);
|
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);
|
assert.equal(witnesses.filter((witness) => witness.unknown || witness.ancestorUnknown).length, 0);
|
||||||
const ledger = createStyleLedger(readStyleSource(root), { witnesses });
|
const ledger = createStyleLedger(readStyleSource(root), { witnesses });
|
||||||
assert.deepEqual(ledger.counts, acceptedLedger.counts);
|
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);
|
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-3s7H6Y0X.css']);
|
assert.deepEqual(assets, ['index-CPDEnja7.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, 157874);
|
assert.equal(built.byteLength, 159016);
|
||||||
assert.equal(sha256(built), '99b874016cac6f1b617cd21d5a7ac957f491d8926fe78e8ba514d9313255488f');
|
assert.equal(sha256(built), '2c9cf378a317ea633b1006299856806dccc4270a3bfe3e0aea00ec7f0ab3385e');
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -32,7 +32,7 @@ test('all repeated client primitive consumers use the shared owners', () => {
|
|||||||
.map(({ source }) => source)
|
.map(({ source }) => source)
|
||||||
.join('\n');
|
.join('\n');
|
||||||
|
|
||||||
assert.equal((production.match(/<Tooltip\b/g) || []).length, 14);
|
assert.equal((production.match(/<Tooltip\b/g) || []).length, 16);
|
||||||
assert.equal((production.match(/<CopyButton\b/g) || []).length, 2);
|
assert.equal((production.match(/<CopyButton\b/g) || []).length, 2);
|
||||||
assert.equal((production.match(/<RailAction\b/g) || []).length, 7);
|
assert.equal((production.match(/<RailAction\b/g) || []).length, 7);
|
||||||
assert.equal((production.match(/<Drawer\b/g) || []).length, 7);
|
assert.equal((production.match(/<Drawer\b/g) || []).length, 7);
|
||||||
|
|||||||
Reference in New Issue
Block a user