diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 50fc291c7..c3375cd92 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -159,6 +159,24 @@ open a second one for a new topic. Fatal and handled errors forward to the `CrashSink` set on `Log` — Crashlytics, in a prerelease build (see [Logging](#logging)). +Redundancy is a property of the **tier**, not of the feature: `lbApi`, +`lbStatic`, `coreApi` and `coreStatic` name both regions and fail over, the +`*Exclusive` tiers and `legacyApi` name one origin. Which family lives where is +the backend's decision and changes without a client release, so the tier is +chosen per datasource from what the endpoint actually does — an endpoint that +speaks SSE stays on `lbApi` (only the `lb-*` nodes terminate it), the archive +and static families follow whichever regions have a copy (see +`api.md#curl-可用性2026-11-20-實測http-狀態碼` and the multi-active table). + +Two requests fall outside that model and must not be forced into it: the +basemap/OSM/terrain tiles are fetched by MapLibre, not `ApiClient`, so they are +**pinned to the selected region** (`staticLbOrigin(regions.lb)` — a pin, no +failover, which is why `etag_interceptor.dart` keeps recognising the bare host +of rows cached before the pin existed); and notify/location are primary on +tnn1 with tyo1 as a **hot standby** that answers `307` back to the primary +while it is healthy, so they stay `coreExclusiveApi` and rely on Dio following +the redirect. + ## Data & errors models are `@freezed` value types with generated @@ -233,16 +251,21 @@ the `ServerClock` corrects device time via real **SNTP** timezone change can't move it (only a resync does). When both SNTP hosts fail, `fallback_time_source.dart` drops to -`https://api.lb.exptech.dev/ntp` (`http_time_source.dart`; the iOS widget -mirrors it in `WidgetHTTPTimeSource.swift`) — corporate Wi-Fi, hotel and campus -networks block UDP/123, and there the alternative is no calibration at all. The -order is precision, not preference: SNTP resolves "now" to about a millisecond, -one HTTPS round trip only to ±RTT/2. This is the one bare host the repository -requests, because a clock reading has no region to pin; the body is never -trusted on its own but checked against the Cloudflare-stamped `Date` header of -the same response, which is what catches a backend whose own clock is wrong — -see [api.md](api.md) for the 15.7-second measurement that made the check -necessary. +`https://api.lb-.exptech.dev/ntp` (`http_time_source.dart`; the iOS +widget mirrors it in `WidgetHTTPTimeSource.swift`) — corporate Wi-Fi, hotel and +campus networks block UDP/123, and there the alternative is no calibration at +all. The order is precision, not preference: SNTP resolves "now" to about a +millisecond, one HTTPS round trip only to ±RTT/2. + +The hosts are the app's own region pair, its own region first +(`HttpTimeSource.hostsFor(regions.lbOrder)`), so the fallback follows the region +the user picked instead of leaving the choice to Cloudflare — that bare name +was retired because the `lb-*` pool it hides contains backends 15.7 seconds +slow. It is not an `ApiTier`: no `ApiClient`, no tier failover, and a per-host +retry of its own when the body disagrees with the response's `Date` header. The +body is never trusted on its own but checked against that header, which +Cloudflare stamps at the edge and which is what catches a backend whose clock +is wrong — see [api.md](api.md) for the measurement. `RealtimeService` resyncs it every 60s (paused in background, resynced on resume). Read corrected time anywhere via the global `AppTime` facade (`AppTime.utc` / `AppTime.utc8`, the fixed-offset Taipei wall clock) — never diff --git a/api.md b/api.md index a4699c120..6efcda5f4 100644 --- a/api.md +++ b/api.md @@ -6,9 +6,10 @@ - **區域:** LB = `tpe1`(台北)、`khh1`(高雄);Core = `tyo1`(東京)、 `tnn1`(台南)。 - **路徑前綴:** 所有路徑都是 `/api/...`。 -- **層級(Tier):** `lbApi` = LB(多活)、`coreApi` = Core(多活)、 - `coreExclusiveApi` = 僅 `api.core-tnn1`、`coreStaticExclusive` = - 僅 `static.core-tnn1`、`legacyApi` = 舊 server `api-1`(逐步淘汰中)。 +- **層級(Tier):** `lbApi` = LB(多活)、`lbStatic` = LB static(多活,但只有 + MapLibre 直接抓的圖磚在用)、`coreApi` = Core(多活)、`coreStatic` = Core + static(多活)、`coreExclusiveApi` = 僅 `api.core-tnn1`、`coreStaticExclusive` + = 僅 `static.core-tnn1`、`legacyApi` = 舊 server `api-1`(逐步淘汰中)。 > 沒有 `lib/api/` 巨石檔:每個端點在其所屬 feature 的 `data/`(基礎設施則在 > `core/`)裡,各自建成一個輕薄的 datasource,並帶著自己的 `ApiTier` @@ -25,21 +26,21 @@ > `time.apple.com`(備)—— 見 `core/realtime/ntp_time_source.dart` 與 > `app_time.dart`(`AppTime.utc` / `AppTime.utc8`)。 > -> 兩台都失敗才改打 **`https://api.lb.exptech.dev/ntp`** +> 兩台都失敗才改打 **`https://api.lb-{tpe1,khh1}.exptech.dev/ntp`** > (`core/realtime/http_time_source.dart`,iOS widget 的對應實作是 > `WidgetHTTPTimeSource.swift`),因為企業 Wi-Fi、飯店與校園網路常擋掉 > UDP/123,而那時唯一的替代品是完全不校時。順序是精度而非偏好:SNTP 的 > RFC 5905 交換約到毫秒,單趟 HTTPS 只到 ±RTT/2(實測 ±150 ms)。 > -> **這是全 repo 唯一使用 bare host 的地方。** `ApiTier` 流量刻意不用(見下方 -> 「多活備援」與 `api_region.dart`),因為區域選擇與容錯要由 App 掌握;但對時 -> 沒有區域可選,沒有東西要 pin、也沒有 per-region 容錯要保留,而 bare name 正 -> 是 Cloudflare 用**有效憑證**(`CN=*.lb.exptech.dev`,Google Trust Services) -> 終結的那一個。 +> **它是逐台的應用層容錯,跟 `ApiTier` 無關。** 主機清單來自區域選擇 +> (`hostsFor(regions.lbOrder)`,選定區域先打),所以這條退路跟著 App 的區域 +> 走;沒有 `ApiClient` 的 tier 換台,也沒有一份會過 `EtagInterceptor` 的絕對 +> URL。以前那個 bare `api.lb.exptech.dev` 已經不用了 —— 它把選擇權交給 +> Cloudflare,而那個池子裡有慢的後端。 > > **`/ntp` 的 body 不可盲信,要用它自己的 `Date` header 驗證。** body 是後端的 -> 時鐘,而後端的時鐘不一定對:這個名字後面的四台 `lb-*` 當中,撰寫時 `lb-2` -> 與 `lb-4` 都慢 15.7 秒,而且兩台數值一致 —— 跨主機取多數也抓不到。 +> 時鐘,而後端的時鐘不一定對:`lb-*` 這一池有四台,撰寫時 `lb-2` 與 `lb-4` 都 +> 慢 15.7 秒,而且兩台數值一致 —— 跨主機取多數也抓不到。 > > 能抓到的是同一個回應的 `Date` header:這台在 Cloudflare 後面,`Date` 由 > **edge** 蓋,跟哪一台後端回應無關,所以每個回應都能自我檢查 —— body 與自己的 @@ -65,6 +66,14 @@ | `TremStationRepositoryImpl.refresh` | `/resource/station` | `coreStatic` | `static.core-{tyo1,tnn1}.exptech.dev` | | `EarthquakeApi.getReportList` | `/api/v2/eq/report` | `coreApi` | `api.core-{tyo1,tnn1}.exptech.dev` | | `EarthquakeApi.getReport` | `/api/v2/eq/report/{id}` | `coreApi` | `api.core-{tyo1,tnn1}.exptech.dev` | +| `FrameTileApi.getFrames` | `/api/v2/tiles/radar/list` | `coreApi` | `api.core-{tyo1,tnn1}.exptech.dev` | +| `FrameTileApi.tileUrl` | `/api/v2/tiles/radar/{sec}/{z}/{x}/{y}.webp` | `coreStatic` | `static.core-{tyo1,tnn1}.exptech.dev` | +| `FrameTileApi.getFrames` | `/api/v2/tiles/qpesums/list` | `coreApi` | `api.core-{tyo1,tnn1}.exptech.dev` | +| `FrameTileApi.tileUrl` | `/api/v2/tiles/qpesums/{ms}/{z}/{x}/{y}.webp` | `coreStatic` | `static.core-{tyo1,tnn1}.exptech.dev` | +| `DisasterMapApi.tileUrl` | `/api/v2/tiles/dpm/{layer}/{z}/{x}/{y}.mvt` | `coreStatic` | `static.core-{tyo1,tnn1}.exptech.dev` | +| `DisasterMapApi.getAedDetail` | `/api/v2/tiles/dpm/aed/{id}` | `coreStatic` | `static.core-{tyo1,tnn1}.exptech.dev` | +| `DisasterMapApi.getRestroomDetail` | `/api/v2/tiles/dpm/restroom/{id}` | `coreStatic` | `static.core-{tyo1,tnn1}.exptech.dev` | +| `DisasterMapApi.getShelterDetail` | `/api/v2/tiles/dpm/shelter/{id}` | `coreStatic` | `static.core-{tyo1,tnn1}.exptech.dev` | > **地震報告 list(v2)query:** `limit`/`page`、`sort`/`order` > (`time`\|`intensity`\|`magnitude`\|`depth` × `asc`\|`desc`)、震度/規模/深度 @@ -101,23 +110,126 @@ > 生命週期都不變。EEW 是**突發型**(地震之間靜默 → 存活判定用「連線開著」); > RTS live 時是**連續型**(約 2 Hz → 「最近有事件」),睡眠時靜默就是「平靜」。 +### 雷達(v2)—— Core 雙區多活 + +時間清單是差量編碼的 Unix 秒(`[baseSec, Δ, …]`),在 API 主機上帶 ETag/304; +tile 是 WebP,放在 **static** 主機(由 MapLibre 直接抓取,`Cache-Control: +max-age=300`)。`{sec}` 就是解出清單後的 10 位數秒,直接使用。 + +**有效觀測範圍不是宣告網格。** 宣告的是 115–126.5°E、18–29°N(921 × 881 格, +0.0125°),但實際只有四座雷達測距圓的聯集裁到該網格內才有觀測;其餘是空的。 +空白代表「未觀測」而非「無降水」,所以地圖的「顯示掃描範圍」外框畫的是那個聯集, +幾何與推導在 `radar_scan_range.dart`。 + +| 類別.方法 | 路徑 | 層級 | 主機 | +|---|---|---|---| +| `FrameTileApi.getFrames` | `/api/v2/tiles/radar/list` | `coreApi` | `api.core-{tyo1,tnn1}.exptech.dev` | +| `FrameTileApi.tileUrl` | `/api/v2/tiles/radar/{sec}/{z}/{x}/{y}.webp` | `coreStatic` | `static.core-{tyo1,tnn1}.exptech.dev` | + + +> **tile 由 MapLibre 直接抓,所以換台是「選定區域優先的一台」,不是逐塊 tile 的 +> 重試**:那一台不回話,那幾塊圖磚就是空的,直到下次換區或重畫。list 與詳情才 +> 經 `ApiClient`,會跟著 `coreApi` / `coreStatic` 的順序換。 +### 未來1小時降水預報 QPESUMS(v2)—— Core 雙區多活 + +QPESUMS 定量降水預報 XYZ WebP。時間清單是差量編碼的 Unix **毫秒** +(`[baseMs, Δ, …]`);tile 在 **static** 主機。`{ms}` 就是解出清單後的 13 位數 +毫秒,直接使用(時間軸解析已同時支援秒與毫秒)。 + +**覆蓋範圍是方形,整塊都有資料**:441 × 561 格,每格 0.0125° +(與雷達同解析度);118.0–123.5125°E、20.0–27.0125°N 是整塊格網的外緣, +不是格心座標。 + +這**不是**雷達的有效範圍。預報發布在自己的網格上,雷達的是測距圓聯集,兩者在 +方形四角(預報有、圓弧無)與圓弧外凸處(圓弧有、方形無)都不一致。「顯示掃描 +範圍」外框因此各畫各的幾何,QPESUMS 的在 `qpesums_scan_range.dart`。 + +| 類別.方法 | 路徑 | 層級 | 主機 | +|---|---|---|---| +| `FrameTileApi.getFrames` | `/api/v2/tiles/qpesums/list` | `coreApi` | `api.core-{tyo1,tnn1}.exptech.dev` | +| `FrameTileApi.tileUrl` | `/api/v2/tiles/qpesums/{ms}/{z}/{x}/{y}.webp` | `coreStatic` | `static.core-{tyo1,tnn1}.exptech.dev` | + +### 防災地圖 DPM(v2)—— Core 雙區多活 + +MapLibre **vector tiles**(gzip MVT)+ 點位詳情 JSON。目前有 **AED / 無障礙廁所 / +避難所**三層;其他類型走同一路徑形狀 `/api/v2/tiles/dpm/{layer}/…`。Tile 與詳情都 +在 **static** 主機(`Cache-Control: max-age=60, must-revalidate` + ETag); +tile 由 MapLibre 直接抓,詳情經 `ApiClient`。Source-layer 名 = `{layer}` +(AED 為 `aed`)。單點有 `id`(內部 PK,打詳情用,非 `aed_id`);低 zoom 的 +cluster 帶 `point_count`。 + +| 類別.方法 | 路徑 | 層級 | 主機 | +|---|---|---|---| +| `DisasterMapApi.tileUrl` | `/api/v2/tiles/dpm/{layer}/{z}/{x}/{y}.mvt` | `coreStatic` | `static.core-{tyo1,tnn1}.exptech.dev` | +| `DisasterMapApi.getAedDetail` | `/api/v2/tiles/dpm/aed/{id}` | `coreStatic` | `static.core-{tyo1,tnn1}.exptech.dev` | +| `DisasterMapApi.getRestroomDetail` | `/api/v2/tiles/dpm/restroom/{id}` | `coreStatic` | `static.core-{tyo1,tnn1}.exptech.dev` | +| `DisasterMapApi.getShelterDetail` | `/api/v2/tiles/dpm/shelter/{id}` | `coreStatic` | `static.core-{tyo1,tnn1}.exptech.dev` | + + +> **tile 由 MapLibre 直接抓,所以換台是「選定區域優先的一台」,不是逐塊 tile 的 +> 重試**:那一台不回話,那幾塊圖磚就是空的,直到下次換區或重畫。list 與詳情才 +> 經 `ApiClient`,會跟著 `coreApi` / `coreStatic` 的順序換。 +### 海嘯 CWA tsunami —— Core 雙區多活 + +兩支端點都是**索引 + 詳情**:索引只有事件摘要與 `id`,詳情才是內文與 +`data.area`。**時間單位是 Unix 毫秒**(`sent`、`validUntil`、以及 area 內各自的 +時間),與氣象家族的秒不同、也不經差量編碼 —— 直接當 13 位數毫秒用。 + +**`data.area` 是位置式陣列,欄位數隨 `data.type` 改變**:`predict` 五欄 +`[地區, 沿岸範圍, 預估浪高, 抵達時間, 顏色]`、`observe` 六欄 +`[測站代碼, 測站名, 觀測浪高, 觀測時間, 經度, 緯度]`。用錯分支不會拋錯,只會把 +海岸範圍當成測站名;`observe` 的經緯度**可以整組是 `null`**(2024-04-03 的 +臺中港就是),所以地圖只畫有座標的那幾筆。解碼與判斷都在 +`TsunamiReport.decode`。 + +**索引 `reports` 是最新在前,且會混入往年事件** —— `no`(`113003`)才是同一個 +事件的鍵,`rep`(`第3報`)是該事件內的第幾報。事件的**最後一報通常是「海嘯警報 +解除」**(`observe`、只有實測),所以「只读最新一報」等於看不到預估;列表與報告 +選擇器因此都以**最新事件的整個事件**為單位(`TsunamiBulletin.newestEvent`)。 + +| 類別.方法 | 路徑 | 層級 | +|---|---|---| +| `TsunamiApi.getReports` | `/api/v1/cwa/tsunami` | `coreApi` | +| `TsunamiApi.getReport` | `/api/v1/cwa/tsunami/{id}` | `coreApi` | + +> `coreApi`(多活)而非 `coreApi`:`core-tyo1` 與 `core-tnn1` 實測都回 +> 200(索引與詳情皆然,2026-10-05),所以它跟著區域容錯,沒有理由只釘在 tnn1。 +> 沒有 ETag,因此每次都由 App 重新抓取 —— 只在圖層開啟時抓,索引與內文都小。 + + +> **`FrameTileApi` 的層級看 `path`:** `radar`/`qpesums` 走多活層,`satellite`/ +> `wind` 仍釘 tnn1(後端只有 Core 兩區複製了前兩者)。`DisasterMapApi` 一律 +> `coreStatic`。這是後端能力的差異,不是偏好 —— 衛星與風場在 tyo1 仍是 404。 + ## 沒多活備援 (single host, no failover) -### Basemap / OSM / Terrain(全域 static LB,無區域) +留下來的是衛星、風場、氣象 v5(後端還沒複製到 tyo1)、notify/location(熱備援, +備援節點平常把寫入導回主節點)、事件家族(只在 `api-1`,而那台本身就是 +`core-tnn1`),以及兩個不走 `ApiTier` 的請求:basemap 的三張圖層依選定區域**釘 +一台**,`/ntp` 則是逐台嘗試。 + +### Basemap / OSM / Terrain(`lbStatic`,依選定區域釘一台) Basemap、OSM 詳細街道建築與 terrain 都由 MapLibre 直接抓(app 的 tile bridge -會以 URL 為鍵快取),不經 `ApiClient` 的區域 failover。OSM 是可選疊圖,只覆蓋 +會以 URL 為鍵快取),不經 `ApiClient` 的區域 failover。主機由區域選擇決定 +(`staticLbOrigin(RegionSelection.lb)`):選台北抓 `static.lb-tpe1`、選高雄抓 +`static.lb-khh1`,換區時 style 一起換。OSM 是可選疊圖,只覆蓋 臺灣資料範圍;一般 basemap 始終保留,因此資料範圍外不會變成空白。 | 用途 | 路徑 | 主機 | |---|---|---| -| basemap | `/api/v1/map/tiles/{z}/{x}/{y}.pbf` | `static.lb.exptech.dev` | -| OSM 詳細圖資 | `/api/v1/map/gsi/{z}/{x}/{y}.pbf` | `static.lb.exptech.dev` | -| terrain | `/api/v1/map/terrain/{z}/{x}/{y}.png` | `static.lb.exptech.dev` | +| basemap | `/api/v1/map/tiles/{z}/{x}/{y}.pbf` | `static.lb-{tpe1,khh1}.exptech.dev` | +| OSM 詳細圖資 | `/api/v1/map/gsi/{z}/{x}/{y}.pbf` | `static.lb-{tpe1,khh1}.exptech.dev` | +| terrain | `/api/v1/map/terrain/{z}/{x}/{y}.png` | `static.lb-{tpe1,khh1}.exptech.dev` | + +> **釘選沒有自動換台。** MapLibre 自己抓 tile,`ApiClient` 的容錯碰不到;選定的 +> 那一台不回話,底圖就是空的。要換,得在設定裡換區域 —— 那會讓 style 與 tile +> URL 一起換到另一台(`BaseMap` 以 `watch()` 重建 style 字串)。 > **App 內附一份 basemap,給沒有網路時用。** 臺灣(含離島)z0–9 加全球 z0–2, > 共 122 塊、1.05 MiB(`assets/map/basemap_seed/`),由 `tool/gen/basemap_seed.sh` -> 從上表的 basemap 路徑抓下來產生。啟動時種進 tile store,但只是**退路**: +> 從上表的 basemap 路徑抓下來產生。啟動時種進 tile store(種在**選定區域**的 +主機名下,否則換成 `static.lb-` 之後那些列永遠不會被讀到),但只是**退路**: > MapLibre 要到其中一塊時一律先問網路,網路答不出來才交出內附版本,第一次下載 > 成功就永久取代它;server 給過的列(含 404)永遠不會被它蓋掉。 @@ -129,22 +241,6 @@ Basemap、OSM 詳細街道建築與 terrain 都由 MapLibre 直接抓(app 的 > 註冊 `raster-dem` source,疊半透明 `hillshade` layer 呈現立體感;`bounds` > 刻意大於真實 DEM bbox,讓 hillshade 邊緣永遠不會在畫面上碰到純背景。 -### 雷達(v2)—— `core-tnn1` - -時間清單是差量編碼的 Unix 秒(`[baseSec, Δ, …]`),在 API 主機上帶 ETag/304; -tile 是 WebP,放在 **static** 主機(由 MapLibre 直接抓取,`Cache-Control: -max-age=300`)。`{sec}` 就是解出清單後的 10 位數秒,直接使用。 - -**有效觀測範圍不是宣告網格。** 宣告的是 115–126.5°E、18–29°N(921 × 881 格, -0.0125°),但實際只有四座雷達測距圓的聯集裁到該網格內才有觀測;其餘是空的。 -空白代表「未觀測」而非「無降水」,所以地圖的「顯示掃描範圍」外框畫的是那個聯集, -幾何與推導在 `radar_scan_range.dart`。 - -| 類別.方法 | 路徑 | 層級 | 主機 | -|---|---|---|---| -| `FrameTileApi.getFrames` | `/api/v2/tiles/radar/list` | `coreExclusiveApi` | `api.core-tnn1.exptech.dev` | -| `FrameTileApi.tileUrl` | `/api/v2/tiles/radar/{sec}/{z}/{x}/{y}.webp` | `coreStaticExclusive` | `static.core-tnn1.exptech.dev` | - ### 衛星雲圖(v2)—— `core-tnn1` Himawari-9 AHI 的 XYZ WebP,預設是 Band-13 IR。時間清單是差量編碼的 @@ -168,41 +264,6 @@ App 的圖層選擇器為每個 channel 註冊一個獨立圖層(`satellite` | `FrameTileApi.getFrames` | `/api/v2/tiles/satellite/{channel}/list` | `coreExclusiveApi` | `api.core-tnn1.exptech.dev` | | `FrameTileApi.tileUrl` | `/api/v2/tiles/satellite/{channel}/{style}/{sec}/{z}/{x}/{y}.webp` | `coreStaticExclusive` | `static.core-tnn1.exptech.dev` | -### 未來1小時降水預報 QPESUMS(v2)—— `core-tnn1` - -QPESUMS 定量降水預報 XYZ WebP。時間清單是差量編碼的 Unix **毫秒** -(`[baseMs, Δ, …]`);tile 在 **static** 主機。`{ms}` 就是解出清單後的 13 位數 -毫秒,直接使用(時間軸解析已同時支援秒與毫秒)。 - -**覆蓋範圍是方形,整塊都有資料**:441 × 561 格,每格 0.0125° -(與雷達同解析度);118.0–123.5125°E、20.0–27.0125°N 是整塊格網的外緣, -不是格心座標。 - -這**不是**雷達的有效範圍。預報發布在自己的網格上,雷達的是測距圓聯集,兩者在 -方形四角(預報有、圓弧無)與圓弧外凸處(圓弧有、方形無)都不一致。「顯示掃描 -範圍」外框因此各畫各的幾何,QPESUMS 的在 `qpesums_scan_range.dart`。 - -| 類別.方法 | 路徑 | 層級 | 主機 | -|---|---|---|---| -| `FrameTileApi.getFrames` | `/api/v2/tiles/qpesums/list` | `coreExclusiveApi` | `api.core-tnn1.exptech.dev` | -| `FrameTileApi.tileUrl` | `/api/v2/tiles/qpesums/{ms}/{z}/{x}/{y}.webp` | `coreStaticExclusive` | `static.core-tnn1.exptech.dev` | - -### 防災地圖 DPM(v2)—— `core-tnn1` - -MapLibre **vector tiles**(gzip MVT)+ 點位詳情 JSON。目前有 **AED / 無障礙廁所 / -避難所**三層;其他類型走同一路徑形狀 `/api/v2/tiles/dpm/{layer}/…`。Tile 與詳情都 -在 **static** 主機(`Cache-Control: max-age=60, must-revalidate` + ETag); -tile 由 MapLibre 直接抓,詳情經 `ApiClient`。Source-layer 名 = `{layer}` -(AED 為 `aed`)。單點有 `id`(內部 PK,打詳情用,非 `aed_id`);低 zoom 的 -cluster 帶 `point_count`。 - -| 類別.方法 | 路徑 | 層級 | 主機 | -|---|---|---|---| -| `DisasterMapApi.tileUrl` | `/api/v2/tiles/dpm/{layer}/{z}/{x}/{y}.mvt` | `coreStaticExclusive` | `static.core-tnn1.exptech.dev` | -| `DisasterMapApi.getAedDetail` | `/api/v2/tiles/dpm/aed/{id}` | `coreStaticExclusive` | `static.core-tnn1.exptech.dev` | -| `DisasterMapApi.getRestroomDetail` | `/api/v2/tiles/dpm/restroom/{id}` | `coreStaticExclusive` | `static.core-tnn1.exptech.dev` | -| `DisasterMapApi.getShelterDetail` | `/api/v2/tiles/dpm/shelter/{id}` | `coreStaticExclusive` | `static.core-tnn1.exptech.dev` | - ### 風場 Wind(v2 / v1)—— `core-tnn1` 風場 overlay:XYZ WebP 圖層 + 低 zoom 的 **`.bin` 向量風場**(`WND1` 格式, @@ -265,33 +326,6 @@ lightning 沒有測站,也沒有 `trend`)。`{kind}` = `track` \| `potential > 乃至完全不帶參數,回應一律是 `"range":"24h"` 且為 24 筆逐時資料。App 送出的參數 > 是對的,是後端尚未實作 —— 在後端補上之前,「7 天」等同 24 小時。 -### 海嘯 CWA tsunami —— core 雙區 - -兩支端點都是**索引 + 詳情**:索引只有事件摘要與 `id`,詳情才是內文與 -`data.area`。**時間單位是 Unix 毫秒**(`sent`、`validUntil`、以及 area 內各自的 -時間),與氣象家族的秒不同、也不經差量編碼 —— 直接當 13 位數毫秒用。 - -**`data.area` 是位置式陣列,欄位數隨 `data.type` 改變**:`predict` 五欄 -`[地區, 沿岸範圍, 預估浪高, 抵達時間, 顏色]`、`observe` 六欄 -`[測站代碼, 測站名, 觀測浪高, 觀測時間, 經度, 緯度]`。用錯分支不會拋錯,只會把 -海岸範圍當成測站名;`observe` 的經緯度**可以整組是 `null`**(2024-04-03 的 -臺中港就是),所以地圖只畫有座標的那幾筆。解碼與判斷都在 -`TsunamiReport.decode`。 - -**索引 `reports` 是最新在前,且會混入往年事件** —— `no`(`113003`)才是同一個 -事件的鍵,`rep`(`第3報`)是該事件內的第幾報。事件的**最後一報通常是「海嘯警報 -解除」**(`observe`、只有實測),所以「只读最新一報」等於看不到預估;列表與報告 -選擇器因此都以**最新事件的整個事件**為單位(`TsunamiBulletin.newestEvent`)。 - -| 類別.方法 | 路徑 | 層級 | -|---|---|---| -| `TsunamiApi.getReports` | `/api/v1/cwa/tsunami` | `coreApi` | -| `TsunamiApi.getReport` | `/api/v1/cwa/tsunami/{id}` | `coreApi` | - -> `coreApi`(多活)而非 `coreExclusiveApi`:`core-tyo1` 與 `core-tnn1` 實測都回 -> 200(索引與詳情皆然,2026-10-05),所以它跟著區域容錯,沒有理由只釘在 tnn1。 -> 沒有 ETag,因此每次都由 App 重新抓取 —— 只在圖層開啟時抓,索引與內文都小。 - ### 裝置與通知 —— `core-tnn1` | 類別.方法 | 路徑 | 層級 | @@ -300,6 +334,13 @@ lightning 沒有測站,也沒有 `trend`)。`{kind}` = `track` \| `potential | `NotifyApi.getNotify` | `/api/v2/notify/{token}` | `coreExclusiveApi` | | `NotifyApi.setNotify` | `/api/v2/notify/{token}/{channel}/{status}` | `coreExclusiveApi` | +> **熱備援,不是多活。** tnn1 是 primary、tyo1 是 standby:寫入仍然只落在 tnn1, +> 而 tyo1 在健康時對同一條路徑回 **`307`** 加 +> `location: https://api.core-tnn1.exptech.dev/…`(2026-11-20 實測),把請求導回 +> 主節點 —— 備援只在 primary 出事時接手,平常不承載業務流量。Dio 預設跟隨 +> redirect(`followRedirects: true`、`maxRedirects: 5`),所以 tier 維持 +> `coreExclusiveApi`:沒有第二個 origin 可以換,只有一個指回主節點的導向。 + ### 舊 server `api-1`(逐步淘汰中) 後端會把端點陸續搬到 `core-tnn1`,這裡會隨之縮減。以下**仍只在 `api-1` 上**, @@ -319,14 +360,16 @@ lightning 沒有測站,也沒有 `trend`)。`{kind}` = `track` \| `potential | 路徑 | 主機 | 回應 | |---|---|---| -| `/ntp` | `api.lb.exptech.dev`(**HTTPS only**;全 repo 唯一的 bare host) | Unix **毫秒**純文字,帶小數(`1791607233513.399`) | +| `/ntp` | `api.lb-{tpe1,khh1}.exptech.dev`(**HTTPS only**) | Unix **毫秒**純文字,帶小數(`1791607233513.399`) | -不是 `ApiTier`,所以沒有區域容錯;也刻意不經過 `ApiClient` —— 它的 -absolute-URL 路徑都會過 `EtagInterceptor`,而快取一個對時回應比不對時更糟。 -Dart 用裸 `HttpClient`、Swift 用 `URLSession` + +主機清單是 `HttpTimeSource.hostsFor(regions.lbOrder)`:選定區域先打,答不出來 +(連不上、body 與自己的 `Date` 差超過 2 秒)才換另一區。不是 `ApiTier`,所以不 +經 `ApiClient` 的 tier 容錯 —— 它的 absolute-URL 路徑都會過 `EtagInterceptor`, +而快取一個對時回應比不對時更糟。Dart 用裸 `HttpClient`、Swift 用 `URLSession` + `reloadIgnoringLocalAndRemoteCacheData`,兩邊都送 `Cache-Control: no-store`。 -為何用 bare host、以及為何每個回應都要拿 `Date` header 驗證,見上方「對時」段落。 +iOS 的 widget 沒有區域設定,所以固定 `tpe1 → khh1`(`WidgetHTTPTimeSource.swift`)。 +為何每個回應都要拿 `Date` header 驗證,見上方「對時」段落。 ## 外部(第三方,無區域) @@ -352,41 +395,58 @@ ETag 重新驗證。 > **衛星 TLE 目前不打網路。** `TleSource` 有一條遠端更新路徑(`TleFetcher`), > 但正式碼沒有接線(`fetch` 為 null),實際只讀打包在 `assets/astro/` 的元素集。 -## curl 可用性(2026-08-02 實測,HTTP 狀態碼) +## curl 可用性(2026-11-20 實測,HTTP 狀態碼) + +### API 主機 | 端點 | lb-tpe1 | lb-khh1 | core-tyo1 | core-tnn1 | api-1 | |---|:--:|:--:|:--:|:--:|:--:| -| `/api/v2/trem/rts` | 200 | 200 | 404 | 401 | 200 | | `/api/v2/eq/eew` | 200 | 200 | 200 | 200 | 404 | | `/api/v2/eq/report` | 404 | 404 | 200 | 200 | 404 | -| `/api/v1/trem/station` | 404 | 404 | 404 | 404 | 200 | -| `/api/v2/tiles/radar/list` | 404 | 404 | 404 | 200 | 404 | -| `/api/v5/meteor/weather/station` | 404 | 404 | 404 | **200** | 404 | -| `/api/v5/meteor/weather/list` | 404 | 404 | 404 | **200** | 404 | -| `/api/v5/meteor/rain/station` | 404 | 404 | 404 | **200** | 404 | -| `/api/v5/meteor/rain/list` | 404 | 404 | 404 | **200** | 404 | -| `/api/v5/meteor/lightning/list` | 404 | 404 | 404 | **200** | 404 | -| `/api/v5/meteor/typhoon/geojson` | 404 | 404 | 404 | **200** | 404 | -| `/api/v2/meteor/weather/list`(舊) | 404 | 404 | 404 | 404 | 200 | -| `/api/v2/meteor/rain/list`(舊) | 404 | 404 | 404 | 404 | 200 | -| `/api/v2/meteor/lightning/list`(舊) | 404 | 404 | 404 | 404 | 200 | -| `/api/v2/meteor/typhoon/geojson`(舊) | 404 | 404 | 404 | 404 | 200 | +| `/api/v3/trem/rts/{now−300}` | 404 | 404 | 200 | 200 | 404 | +| `/api/v1/cwa/tsunami` | 404 | 404 | 200 | 200 | 404 | +| `/api/v2/tiles/radar/list` | 404 | 404 | **200** | 200 | 404 | +| `/api/v2/tiles/qpesums/list` | 404 | 404 | **200** | 200 | 404 | +| `/api/v2/tiles/satellite/13/list` | 404 | 404 | 404 | 200 | 404 | +| `/api/v2/tiles/wind/gfs/list` | 404 | 404 | 404 | 200 | 404 | +| `/api/v5/meteor/weather/list` | 404 | 404 | 404 | 200 | 404 | +| `/api/v2/notify/{token}` | 404 | 404 | **307** → tnn1 | 401 | 429 | | `/api/v1/dpip/history/list` | 404 | 404 | 404 | 404 | 200 | -| `/api/v1/dpip/realtime/list` | 404 | 404 | 404 | 404 | 200 | -| `/api/v2/notify/{token}` | 404 | 404 | 404 | 401 | 429 | - -v5 氣象家族與其 static 快照(`static.core-tnn1` 的 -`/api/v5/meteor/{weather,rain,lightning}/{sec}`)實測皆為 200。舊的 v2 路徑在 -`api-1` 上仍然存活,所以遷移是**新增而非切換** —— 但 App 只走 v5。 - -雷達 **tile** 不在這張表裡 —— 它們由 `static.core-tnn1.exptech.dev` 提供 -(`/api/v2/tiles/radar/{sec}/{z}/{x}/{y}.webp`,`image/webp`),和上面的時間清單 -是不同主機。 +| `/api/v1/sse?topics=…` | 200 | 200 | 200(JSON) | 401 | 404 | + +### static 主機 + +| 端點 | static lb-tpe1 | static lb-khh1 | static core-tyo1 | static core-tnn1 | +|---|:--:|:--:|:--:|:--:| +| `basemap {z}/{x}/{y}.pbf` | 200 | 200 | — | — | +| `/resource/station` | — | — | 200 | 200 | +| `radar/{sec}/…webp` | — | — | 200 | 200 | +| `qpesums/{ms}/…webp` | — | — | 200 | 200 | +| `dpm/{layer}/…mvt`、`dpm/aed/{id}` | — | — | 200 | 200 | +| `satellite/13/…webp` | — | — | 404 | 200 | +| `wind/…webp`、`…bin` | — | — | 404 | 200 | +| `v5/meteor/{family}/{sec}` | — | — | 404 | 200 | + +### 與 2026-08-02 的差異 + +- **雷達 list 與 QPESUMS list 在 `core-tyo1` 從 404 變成 200**,tile 與 DPM 也是; + App 的 tier 因此從 `coreExclusiveApi`/`coreStaticExclusive` 換成 + `coreApi`/`coreStatic`(`FrameTileApi` 依 `path` 決定)。 +- **`/api/v2/trem/rts` 換成 `/api/v3/trem/rts/{sec}`**(v2 是即時 SSE、v3 才是 + 歷史),SSE 改由 `SseMux` 的 `/api/v1/sse` 承擔。 +- **`/api/v1/trem/station` 不存在了**,測站清單是 `/resource/station`(CSV,在 + `static.core-*` 上)。 +- **notify/location 在 `core-tyo1` 回 307 導回 tnn1**,而不是 404;那是熱備援 + 的導向,不是備援自己在服務。 +- **`api-1` 的每一條回應 `x-served-by` 都是 `core-tnn1`** —— 它已經是同一個 + origin 的另一個名字,不構成備援。 + +`/api/v2/tiles/radar/list` 在 tyo1 與 tnn1 都 200,但 **tile 仍在各自區域的 +static 主機**上,所以「list 有」與「tile 有」要分開看。 只有 `lb-tpe1` / `lb-khh1` 對 `?sse=1` 回傳真正的 `text/event-stream`; -`core-tyo1` 之於 `eew?sse=1`、`api-1` 之於 `rts?sse=1` 都是 HTTP 200 但 -`application/json`(旗標被忽略)。`core-tnn1` 對兩者都回 401。這就是 SSE -串流固定用 `lbApi` 的原因。 +`core-tyo1` 回 200 但 `application/json`(旗標被忽略),`core-tnn1` 回 401。 +這就是即時串流固定用 `lbApi` 的原因 —— 跨國的 core 兩區再穩,也接不住 SSE。 --- diff --git a/ios/DPIPWidgets/WidgetHTTPTimeSource.swift b/ios/DPIPWidgets/WidgetHTTPTimeSource.swift index faddd233c..74cf416c9 100644 --- a/ios/DPIPWidgets/WidgetHTTPTimeSource.swift +++ b/ios/DPIPWidgets/WidgetHTTPTimeSource.swift @@ -26,9 +26,9 @@ enum WidgetHTTPTimeError: Error, Equatable { case responseTooLarge } -/// `WidgetServerTimeSource` over `https://api.lb.exptech.dev/ntp`, for networks -/// that block SNTP's UDP/123 — corporate Wi-Fi, hotel and campus networks, some -/// carriers. +/// `WidgetServerTimeSource` over `https://api.lb-.exptech.dev/ntp`, for +/// networks that block SNTP's UDP/123 — corporate Wi-Fi, hotel and campus +/// networks, some carriers. /// /// Strictly a fallback behind `WidgetSNTPClient`: one HTTPS round trip resolves /// "now" to roughly ±RTT/2 (±150 ms measured), where the SNTP exchange resolves @@ -39,31 +39,38 @@ enum WidgetHTTPTimeError: Error, Equatable { /// ## Why the `Date` header is checked /// /// The body is the *origin's* clock, and not every origin's clock is right: of -/// the four `lb-*` nodes behind this name, two were 15.7 seconds behind at the -/// time of writing — consistently, and in agreement with each other, so a -/// quorum across them would not have caught it either. +/// the four `lb-*` nodes, two were 15.7 seconds behind at the time of writing — +/// consistently, and in agreement with each other, so a quorum across them would +/// not have caught it either. /// -/// What does catch it is the `Date` header of the very same response. This host -/// sits behind Cloudflare, so `Date` is stamped at the edge, independently of -/// whichever backend answered — which makes every response self-checking: a body -/// more than `maximumDateSkew` from its own `Date` is a bad backend (or a frozen -/// cache), and is discarded without needing to know which node it came from. +/// What does catch it is the `Date` header of the very same response. Every +/// `lb-*` name sits behind Cloudflare, so `Date` is stamped at the edge, +/// independently of whichever backend answered — which makes every response +/// self-checking: a body more than `maximumDateSkew` from its own `Date` is a bad +/// backend (or a frozen cache), and is discarded without needing to know which +/// node it came from. /// /// Every guard fails closed: installing a wrong offset is worse than not /// calibrating, so a rejected response throws and `WidgetServerClock` keeps its /// last anchor. struct WidgetHTTPTimeSource: WidgetServerTimeSource { - /// The DNS-balanced LB name — the one place the repository uses a bare - /// host. + /// The region-pinned LB names, `tpe1` first. /// - /// Region-pinned API traffic deliberately never does, because region - /// selection and failover belong to the app. A clock reading has no region - /// to select, and the bare name is what Cloudflare terminates with a valid + /// These used to be the DNS-balanced bare `api.lb.exptech.dev`, on the + /// reasoning that a clock reading has no region to select. The bare name is + /// balanced without regard for which region the app's other traffic picked, + /// so the sample could come from a machine whose clock disagrees with the + /// edge the app is talking to. The widget extension has no region setting + /// to read, so it takes the app's default order: `tpe1` first, `khh1` as the + /// fallback. The bare name is what Cloudflare terminates with a valid /// certificate — `time.exptech.com.tw`, SNTP's own primary, serves `/ntp` /// too but presents an expired certificate for the wrong name, and its /// `Date` comes from the same machine as its body, so it can neither be /// reached over HTTPS nor check itself. - static let defaultHosts = ["api.lb.exptech.dev"] + static let defaultHosts = [ + "api.lb-tpe1.exptech.dev", + "api.lb-khh1.exptech.dev", + ] /// How far the body may sit from its own `Date` header. /// diff --git a/ios/RunnerTests/WidgetHTTPTimeSourceTests.swift b/ios/RunnerTests/WidgetHTTPTimeSourceTests.swift index 79d669324..1085fa8b6 100644 --- a/ios/RunnerTests/WidgetHTTPTimeSourceTests.swift +++ b/ios/RunnerTests/WidgetHTTPTimeSourceTests.swift @@ -225,18 +225,22 @@ final class WidgetHTTPTimeSourceTests: XCTestCase { ) } - func testAsksTheDNSBalancedLBNameOverHTTPS() { - // The one bare host the repository uses: a clock reading has no region - // to pin, and this is the name Cloudflare terminates with a valid cert. + func testAsksTheRegionPinnedLBNamesOverHTTPS() { + // No bare host: the reading comes from the same edge the app talks to, + // and the widget has no region setting, so it takes the app's default + // order with the other region as the fallback. XCTAssertEqual( WidgetHTTPTimeSource.defaultHosts, - ["api.lb.exptech.dev"] + [ + "api.lb-tpe1.exptech.dev", + "api.lb-khh1.exptech.dev", + ] ) XCTAssertEqual( WidgetHTTPTimeSource.url( - host: "api.lb.exptech.dev" + host: WidgetHTTPTimeSource.defaultHosts[0] )?.absoluteString, - "https://api.lb.exptech.dev/ntp" + "https://api.lb-tpe1.exptech.dev/ntp" ) } diff --git a/lib/bootstrap.dart b/lib/bootstrap.dart index 1ee66c3bf..ce76fc655 100644 --- a/lib/bootstrap.dart +++ b/lib/bootstrap.dart @@ -285,7 +285,12 @@ Future bootstrap() async { // one query and no asset reads. The tile cache holds its first answers until // this lands, so a fresh install offline still draws. if (cache != null) { - mapTileCache?.servesAfter(BasemapSeeder(cache.etag).run()); + // Seeded under the region-pinned template the style asks for: the tiles + // are the same everywhere, but a row keyed by another host would never be + // read, and a first launch offline would draw nothing. + mapTileCache?.servesAfter( + BasemapSeeder(cache.etag, region: regions.lb).run(), + ); } // Turn off the OS-level disk HTTP cache (iOS NSURLCache) and drop its // residue: every cached byte now lives in the app's own SQLite, so a second @@ -311,7 +316,12 @@ Future bootstrap() async { final serverClock = ServerClock( const SystemClock(), SystemElapsed(), - FallbackServerTimeSource([NtpTimeSource(), HttpTimeSource()]), + FallbackServerTimeSource([ + NtpTimeSource(), + // The HTTP fallback asks the region the user picked, its own region + // first — see [HttpTimeSource.hostsFor]. + HttpTimeSource(hosts: HttpTimeSource.hostsFor(regions.lbOrder)), + ]), ); AppTime.install(serverClock); AppTime.sync().ignore(); diff --git a/lib/core/geo/location_api.dart b/lib/core/geo/location_api.dart index 207028147..945adf768 100644 --- a/lib/core/geo/location_api.dart +++ b/lib/core/geo/location_api.dart @@ -5,7 +5,13 @@ import 'package:dpip/core/network/api_region.dart'; /// Device-location endpoint on the region-aware [ApiClient]. /// /// Migrated from the legacy `api-1` host to `api.core-tnn1` -/// ([ApiTier.coreExclusiveApi]). +/// ([ApiTier.coreExclusiveApi]). tnn1 is the **primary**: the tyo1 copy is a hot +/// standby, so a healthy tyo1 answers `307` back to tnn1 rather than serving the +/// write itself — it takes the traffic only when the primary is gone. That is +/// why the tier stays exclusive instead of becoming region-redundant: there is +/// no second origin to fail over to, only a redirect that names the first one. +/// Dio follows it (the default `followRedirects`), and the redirect never +/// reaches `validateStatus`, which accepts 2xx and 304 only. class LocationApi { const LocationApi(this._client); diff --git a/lib/core/network/api_client.dart b/lib/core/network/api_client.dart index b6c0ce457..a29470b68 100644 --- a/lib/core/network/api_client.dart +++ b/lib/core/network/api_client.dart @@ -77,9 +77,9 @@ class ApiClient { /// Absolute-URL GET as bytes with ETag (no region failover). /// - /// For hosts already baked into the MapLibre style (basemap - /// `static.lb.exptech.dev`, glyphs CDN) that are not an [ApiTier]. Prefer - /// [getBytes] for region-pinned ExpTech paths. + /// For hosts already baked into the MapLibre style (the region-pinned basemap + /// host from `staticLbOrigin`, the glyphs CDN) that are not an [ApiTier]. + /// Prefer [getBytes] for region-pinned ExpTech paths. Future getBytesAbsolute( String url, { CancelToken? cancelToken, diff --git a/lib/core/network/api_region.dart b/lib/core/network/api_region.dart index 8515cf930..30430f028 100644 --- a/lib/core/network/api_region.dart +++ b/lib/core/network/api_region.dart @@ -38,19 +38,31 @@ enum CoreRegion { final String label; } +/// The origin for the region-pinned LB static host — `static.lb-`. +/// +/// Not an [ApiTier]: nothing here goes through `ApiClient`, because these are +/// tiles MapLibre fetches itself. What is left is the pinning — basemap, terrain +/// and OSM used to come from the bare `static.lb.exptech.dev`, which balances +/// without regard for the region the rest of the app selected, so a client could +/// draw every tile from the far end while its API traffic came from the near +/// one. Both hosts carry the same dataset; the pin is about one honest +/// selection, not about which copy exists. +String staticLbOrigin(LbRegion region) => + 'https://static.lb-${region.code}.exptech.dev'; + /// The host family and redundancy a request targets. /// /// Only concrete, region-pinned hosts are ever used; the DNS-balanced bare -/// hosts (`api.lb.exptech.dev`, `api.core.exptech.dev`) are deliberately never -/// requested **for tiered traffic**, so region selection and failover stay -/// under app control. +/// hosts (`api.lb.exptech.dev`, `api.core.exptech.dev`) are never requested, so +/// region selection and failover stay under app control. /// -/// One request outside this enum does use a bare host: the HTTP time fallback -/// in `core/realtime/http_time_source.dart` asks -/// `https://api.lb.exptech.dev/ntp`. It is not an [ApiTier] request at all — -/// a clock reading has no region to select, so there is nothing for the app to -/// pin and no per-region failover to preserve, and the bare name is the one -/// Cloudflare terminates with a valid certificate. +/// Two requests fall outside this enum, and both are pinned by region too: the +/// map host from [staticLbOrigin], and the HTTP time fallback in +/// `core/realtime/http_time_source.dart`, which builds its hosts from the +/// selected region's order. Neither is an [ApiTier] request — a clock reading +/// and a MapLibre tile have no `ApiClient` between them and the network — but +/// neither goes to a bare name either, because a bare name is balanced without +/// regard for the region the rest of the app selected. enum ApiTier { /// LB API — multi-active across [LbRegion]s (`api.lb-{tpe1,khh1}`). lbApi, diff --git a/lib/core/network/dio_client.dart b/lib/core/network/dio_client.dart index 64a20916d..3ec4c703b 100644 --- a/lib/core/network/dio_client.dart +++ b/lib/core/network/dio_client.dart @@ -28,6 +28,13 @@ Dio createDio({EtagCacheStore? etagCache, NetworkUsageStore? usage}) { // If-None-Match, so this is inert without a cache. validateStatus: (status) => status != null && ((status >= 200 && status < 300) || status == 304), + // Redirects are followed by the adapter (`followRedirects` defaults to + // true, `maxRedirects` to 5), which matters for one endpoint family: + // notify/location are primary-on-tnn1 with a hot standby, and a standby + // that is up while the primary is not answers `307` at the *interim* + // node, not at tnn1. Following it means the write lands on tnn1, where it + // belongs. A 3xx never reaches [validateStatus] — by the time the status + // is checked the chain has already settled on its final response. ), ); if (etagCache != null) { diff --git a/lib/core/network/endpoint_health.dart b/lib/core/network/endpoint_health.dart index c3cfb50a6..c11d16946 100644 --- a/lib/core/network/endpoint_health.dart +++ b/lib/core/network/endpoint_health.dart @@ -9,9 +9,9 @@ /// /// Outcomes are bucketed by **service × tier × host**: the same region carries /// different services (EEW/RTS on `lbApi` — one shared stream feeding both -/// rows, see [EndpointService.allOfPath] — radar lists on -/// `coreExclusiveApi` → `api.core-tnn1`), and one service's dead host may be -/// another's healthy one. The More → 伺服器狀態 screen renders this map as a +/// rows, see [EndpointService.allOfPath] — radar lists on `coreApi` and radar +/// tiles on `coreStatic`), and one service's dead host may be another's +/// healthy one. The More → 伺服器狀態 screen renders this map as a /// table — rows are services, columns are tier groups, cells are the regions /// each service was observed on. library; @@ -45,7 +45,12 @@ enum EndpointService { /// path after `/api/` decides; the families share the `ApiPaths` constants. static EndpointService ofPath(String path) { if (path.startsWith('/api/v2/eq/eew')) return eew; - if (path.startsWith('/api/v2/trem/rts')) return rts; + // Both the live v2 topic and the v3 archive are the same family: the + // status table should not care which generation a caller used. + if (path.startsWith('/api/v3/trem/rts') || + path.startsWith('/api/v2/trem/rts')) { + return rts; + } if (path.contains('/tiles/radar')) return radar; if (path.contains('/tiles/satellite')) return satellite; if (path.contains('/tiles/qpesums')) return qpesums; @@ -58,7 +63,13 @@ enum EndpointService { if (path.startsWith('/api/v5/meteor/lightning')) return lightning; if (path.startsWith('/api/v5/meteor/typhoon')) return typhoon; if (path.startsWith('/api/v2/eq/report')) return report; - if (path.startsWith('/api/v1/trem/')) return tremStation; + // The station directory is a static CSV (`/resource/station`); the + // legacy `/api/v1/trem/*` spelling is kept only so old call sites still + // land on the same row. + if (path.startsWith('/resource/station') || + path.startsWith('/api/v1/trem/')) { + return tremStation; + } if (path.startsWith('/api/v1/dpip')) return event; if (path.startsWith('/api/v2/location')) return location; if (path.startsWith('/api/v2/notify')) return notify; diff --git a/lib/core/network/etag_interceptor.dart b/lib/core/network/etag_interceptor.dart index f82cdb817..fe3d4417c 100644 --- a/lib/core/network/etag_interceptor.dart +++ b/lib/core/network/etag_interceptor.dart @@ -90,9 +90,17 @@ class EtagInterceptor extends Interceptor { static bool _isBytes(RequestOptions o) => o.responseType == ResponseType.bytes; - /// Bare-host static map vector tiles (no server ETag). + /// Region-pinned static map vector tiles (no server ETag). + /// + /// The basemap/OSM copy is pinned to one LB host per session — + /// `static.lb-.exptech.dev` — so this matches the family, not one + /// name. The bare `static.lb.exptech.dev` is still accepted: cached tile + /// entries written before the pin hold those URLs, and a store lookup has to + /// recognise what is already in it. static bool isBasemapPbf(Uri uri) => - uri.host == 'static.lb.exptech.dev' && + (uri.host == 'static.lb.exptech.dev' || + (uri.host.startsWith('static.lb-') && + uri.host.endsWith('.exptech.dev'))) && (uri.path.contains(ApiPaths.mapTilesV1) || uri.path.contains(ApiPaths.mapOsmV1)) && uri.path.endsWith('.pbf'); diff --git a/lib/core/realtime/http_time_source.dart b/lib/core/realtime/http_time_source.dart index 3b5ec830a..330e18e7c 100644 --- a/lib/core/realtime/http_time_source.dart +++ b/lib/core/realtime/http_time_source.dart @@ -4,6 +4,7 @@ import 'dart:io'; import 'package:dpip/core/error/failure.dart'; import 'package:dpip/core/error/result.dart'; import 'package:dpip/core/logging/log.dart'; +import 'package:dpip/core/network/api_region.dart'; import 'package:dpip/core/realtime/clock.dart'; import 'package:dpip/core/realtime/ntp_time_source.dart'; import 'package:dpip/core/realtime/server_time_source.dart'; @@ -20,9 +21,9 @@ typedef HttpTimeProbe = ({ int receivedAtMs, }); -/// [ServerTimeSource] over `https://api.lb.exptech.dev/ntp`, for networks that -/// block SNTP's UDP/123 — corporate Wi-Fi, hotel and campus networks, some -/// carriers. +/// [ServerTimeSource] over `https://api.lb-.exptech.dev/ntp`, for +/// networks that block SNTP's UDP/123 — corporate Wi-Fi, hotel and campus +/// networks, some carriers. /// /// Strictly a fallback behind [NtpTimeSource]: one HTTPS round trip resolves /// "now" to roughly ±RTT/2 (±150 ms measured), where SNTP's RFC 5905 exchange @@ -32,18 +33,18 @@ typedef HttpTimeProbe = ({ /// ## Why the `Date` header is checked /// /// The body is the *origin's* clock, and not every origin's clock is right: of -/// the four `lb-*` nodes behind this name, two were 15.7 seconds behind at the -/// time of writing — consistently, and in agreement with each other, so a -/// quorum across them would not have caught it either. +/// the four `lb-*` nodes, two were 15.7 seconds behind at the time of writing — +/// consistently, and in agreement with each other, so a quorum across them +/// would not have caught it either. /// -/// What does catch it is the `Date` header of the very same response. This host -/// sits behind Cloudflare, so `Date` is stamped at the edge, independently of -/// whichever backend answered — which makes every response self-checking: a -/// body more than [maximumDateSkew] from its own `Date` is a bad backend (or a -/// frozen cache), and is discarded without needing to know which node it came -/// from. Thirty consecutive samples stayed inside 910 ms of their header, so -/// this name does route to healthy backends today; the check is what keeps that -/// from being a thing the app has to assume. +/// What does catch it is the `Date` header of the very same response. Every +/// `lb-*` name sits behind Cloudflare, so `Date` is stamped at the edge, +/// independently of whichever backend answered — which makes every response +/// self-checking: a body more than [maximumDateSkew] from its own `Date` is a +/// bad backend (or a frozen cache), and is discarded without needing to know +/// which node it came from. Thirty consecutive samples stayed inside 910 ms of +/// their header, so these names do route to healthy backends today; the check is +/// what keeps that from being a thing the app has to assume. /// /// Every guard fails closed: installing a wrong offset is worse than not /// calibrating, so a rejected response yields a [Failure] and `ServerClock` @@ -53,23 +54,41 @@ typedef HttpTimeProbe = ({ /// production uses [_httpProbe]. class HttpTimeSource implements ServerTimeSource { HttpTimeSource({ - this._hosts = defaultHosts, + List? hosts, this._timeout = const Duration(seconds: 2), this._clock = const SystemClock(), Future Function(Uri url, Duration timeout)? probe, - }) : _probe = probe ?? _httpProbe; + }) : _hosts = hosts ?? defaultHosts, + _probe = probe ?? _httpProbe; - /// The DNS-balanced LB name — the one place the repository uses a bare host. + /// The region-pinned LB names, `tpe1` first. /// - /// `ApiTier` traffic deliberately never does (see `api_region.dart`), because - /// region selection and failover belong to the app. A clock reading has no - /// region to select: there is nothing to pin and no per-region failover to - /// preserve, and the bare name is what Cloudflare terminates with a valid - /// certificate — `time.exptech.com.tw`, SNTP's own primary, serves `/ntp` too - /// but presents an expired certificate for the wrong name, and its `Date` - /// comes from the same machine as its body, so it can neither be reached over - /// HTTPS nor check itself. - static const List defaultHosts = ['api.lb.exptech.dev']; + /// These used to be the DNS-balanced bare `api.lb.exptech.dev` — the only + /// bare host this repository used — on the reasoning that a clock reading has + /// no region to select. The bare name is balanced without regard for which + /// region the rest of the app's traffic picked, so the sample could come from + /// a machine on the far side of the island whose clock disagrees with the + /// edge the app is otherwise talking to (see below for why that is not + /// hypothetical). The app passes [hostsFor]`(RegionSelection.lbOrder)`, so the + /// order follows the user's selection and the other region is the fallback. + /// + /// `time.exptech.com.tw`, SNTP's own primary, serves `/ntp` too but presents + /// an expired certificate for the wrong name, and its `Date` comes from the + /// same machine as its body, so it can neither be reached over HTTPS nor + /// check itself. + static List get defaultHosts => hostsFor(_defaultOrder); + + /// Region codes behind [defaultHosts]. + static const List _defaultOrder = [LbRegion.tpe1, LbRegion.khh1]; + + /// Bare `/ntp` host names for [order], tried in the order given. + /// + /// The `api.lb-` shape is written here once, for the same reason + /// `ApiClient.hostsFor` writes the `ApiTier` hosts once: a host name spelled + /// by hand somewhere else is one that goes stale silently. + static List hostsFor(Iterable order) => [ + for (final region in order) 'api.lb-${region.code}.exptech.dev', + ]; /// How far the body may sit from its own `Date` header. /// @@ -168,8 +187,11 @@ class HttpTimeSource implements ServerTimeSource { /// /// Deliberately not `ApiClient`: every absolute-URL path there runs through /// `EtagInterceptor`, and a cached clock reading is worse than no reading. - /// [HttpClient] also hands back `Date` already parsed, and this request is - /// not `ApiTier` traffic, so region failover would not apply to it either. + /// [HttpClient] also hands back `Date` already parsed. The request is not + /// `ApiTier` traffic either — the host list does come from the region + /// selection, but the retry a reading needs is not a failed request's: one + /// that contradicts its own `Date` is rejected and [serverTimeMs] moves on to + /// the next region. static Future _httpProbe(Uri url, Duration timeout) async { final client = HttpClient() ..connectionTimeout = timeout diff --git a/lib/features/disaster_map/data/disaster_map_api.dart b/lib/features/disaster_map/data/disaster_map_api.dart index 77031f7dc..7decd5a47 100644 --- a/lib/features/disaster_map/data/disaster_map_api.dart +++ b/lib/features/disaster_map/data/disaster_map_api.dart @@ -1,4 +1,4 @@ -/// Disaster-prevention map (DPM) HTTP surface on `static.core-tnn1`. +/// Disaster-prevention map (DPM) HTTP surface on `static.core-{tyo1,tnn1}`. library; import 'package:dpip/core/network/api_client.dart'; @@ -16,9 +16,14 @@ class DisasterMapApi { final ApiClient _client; - static const ApiTier _tier = ApiTier.coreStaticExclusive; + /// The DPM backend is copied to both core regions, so tiles and details + /// follow the region selection. + static const ApiTier _tier = ApiTier.coreStatic; - /// `https://static.core-tnn1.exptech.dev/api/v2/tiles/dpm/{layer}/{z}/{x}/{y}.mvt` + /// `https://static.core-.exptech.dev/api/v2/tiles/dpm/{layer}/{z}/{x}/{y}.mvt` + /// + /// Only the selected region's host is used: MapLibre fetches every tile + /// itself, so a tile request cannot fail over per request. String tileUrl(String layer) => '${_client.hostsFor(_tier).first}' '${ApiPaths.dpm}/$layer/{z}/{x}/{y}.mvt'; diff --git a/lib/features/disaster_map/data/dpm_tile_prefetcher.dart b/lib/features/disaster_map/data/dpm_tile_prefetcher.dart index 45a650d7a..8f29bb2b0 100644 --- a/lib/features/disaster_map/data/dpm_tile_prefetcher.dart +++ b/lib/features/disaster_map/data/dpm_tile_prefetcher.dart @@ -14,7 +14,9 @@ class DpmTilePrefetcher { final ApiClient _client; final MapTileWarmer _warmer; - static const ApiTier _tier = ApiTier.coreStaticExclusive; + /// Both core regions carry the DPM backend, so warming follows the region + /// selection like the style's tile template does. + static const ApiTier _tier = ApiTier.coreStatic; void cancel() => _warmer.cancel(); diff --git a/lib/features/earthquake/presentation/pages/report_detail_page.dart b/lib/features/earthquake/presentation/pages/report_detail_page.dart index 731bee9d2..64141cfe4 100644 --- a/lib/features/earthquake/presentation/pages/report_detail_page.dart +++ b/lib/features/earthquake/presentation/pages/report_detail_page.dart @@ -15,6 +15,7 @@ import 'package:dpip/core/geo/town_directory.dart'; import 'package:dpip/core/logging/log.dart'; import 'package:dpip/core/models/lat_lng.dart' as geo; import 'package:dpip/core/network/api_client.dart'; +import 'package:dpip/core/network/region_selection.dart'; import 'package:dpip/core/permissions/system_settings.dart'; import 'package:dpip/core/platform/image_saver.dart'; import 'package:dpip/core/realtime/app_time.dart'; @@ -392,12 +393,16 @@ class _ReportMapDetailState extends State<_ReportMapDetail> { final controller = _controller; if (!mounted || controller == null || !_styleLoaded) return; final brightness = Theme.of(context).brightness; + // Pinned to the LB region the user picked, so the OSM/DEM copies come from + // the same host as the basemap style (see [staticLbOrigin]). + final region = context.read().lb; _syncChain = _syncChain.then( (_) => _basemapSync.sync( controller, showTerrain: () => _showTerrain.value, gsi: _gsi, brightness: brightness, + region: region, stillCurrent: () => mounted && identical(controller, _controller) && _styleLoaded, ), diff --git a/lib/features/earthquake/presentation/pages/report_replay_page.dart b/lib/features/earthquake/presentation/pages/report_replay_page.dart index 29aec1495..ef576b6d4 100644 --- a/lib/features/earthquake/presentation/pages/report_replay_page.dart +++ b/lib/features/earthquake/presentation/pages/report_replay_page.dart @@ -20,6 +20,7 @@ import 'package:dpip/core/logging/log.dart'; import 'package:dpip/core/models/lat_lng.dart' as geo; import 'package:dpip/core/platform/render_tier.dart'; import 'package:dpip/core/network/api_client.dart'; +import 'package:dpip/core/network/region_selection.dart'; import 'package:dpip/core/settings/eew_cwa_only_settings.dart'; import 'package:dpip/core/settings/setting_keys.dart'; import 'package:dpip/core/settings/settings_store.dart'; @@ -839,12 +840,16 @@ class _ReplayMapState extends State<_ReplayMap> { final controller = _controller; if (!mounted || controller == null || !_styleLoaded) return; final brightness = Theme.of(context).brightness; + // Pinned to the LB region the user picked, so the OSM/DEM copies come from + // the same host as the basemap style (see [staticLbOrigin]). + final region = context.read().lb; _syncChain = _syncChain.then( (_) => _basemapSync.sync( controller, showTerrain: () => _showTerrain.value, gsi: _gsi, brightness: brightness, + region: region, stillCurrent: () => mounted && identical(controller, _controller) && _styleLoaded, ), diff --git a/lib/features/notification/data/notify_api.dart b/lib/features/notification/data/notify_api.dart index dcddd84bf..76a47eff5 100644 --- a/lib/features/notification/data/notify_api.dart +++ b/lib/features/notification/data/notify_api.dart @@ -8,6 +8,15 @@ import 'package:dpip/core/network/api_region.dart'; /// The `notify` endpoints, migrated from the legacy `api-1` host to /// `api.core-tnn1` ([ApiTier.coreExclusiveApi]). Both return the settings as a /// flat integer list (one per channel); the repository maps it to a model. +/// +/// tnn1 is the **primary**: the tyo1 copy is a hot standby, so a healthy tyo1 +/// answers `307` back to tnn1 instead of serving the request itself — settings +/// are written in one place, and the standby only takes traffic while the +/// primary is unavailable. That is why the tier stays exclusive rather than +/// region-redundant: a redundant tier would treat the standby as an equal and +/// split writes across two origins. Dio follows the redirect (its default +/// `followRedirects`), so no request here ever sees the 307 itself, and it never +/// reaches `validateStatus`, which accepts 2xx and 304 only. class NotifyApi { const NotifyApi(this._client); diff --git a/lib/features/status/presentation/pages/server_status_page.dart b/lib/features/status/presentation/pages/server_status_page.dart index f6506af26..a9a9f6279 100644 --- a/lib/features/status/presentation/pages/server_status_page.dart +++ b/lib/features/status/presentation/pages/server_status_page.dart @@ -229,7 +229,9 @@ class _WebDashboardCard extends StatelessWidget { /// Each table lists **all** the services and region columns its category can /// ever carry (per api.md and who actually calls what). The probe is passive — /// a cell shows that host's icon only when a request has actually touched it; -/// an untouched cell is an em-dash, not a hidden row. +/// an untouched cell is either 未探測 (a host that should answer), 不支援 (this +/// region has no such host at all) or 熱備援 (the region only answers with a +/// redirect to the one that owns the service). /// /// The four categories are judged by host name: an `api.*` host is API, a /// `static.*` host is Static; LB is the `lb-*` family, Core is the `core-*` @@ -275,10 +277,10 @@ class _ClientEndpoints extends StatelessWidget { isCore: true, regions: ['TYO1', 'TNN1', 'API-1'], services: [ - // Historical replay + reports are multi-active across tyo1/tnn1; the - // meteor family, location, notify and the TNN1-exclusive list endpoints - // only answer on api.core-tnn1; trem-station/events/RTS history only - // on the legacy api-1 host. + // Historical replay + reports + radar/QPESUMS lists are multi-active + // across tyo1/tnn1; the meteor family, satellite/wind lists and the + // hot-standby writes (location, notify) only answer on + // api.core-tnn1; the event feed only on the legacy api-1 host. EndpointService.eew, EndpointService.report, EndpointService.radar, @@ -291,14 +293,21 @@ class _ClientEndpoints extends StatelessWidget { EndpointService.typhoon, EndpointService.location, EndpointService.notify, - EndpointService.tremStation, EndpointService.event, EndpointService.rts, + // The station directory is a static CSV (`/resource/station`), so it + // has no row here — it lives in the Core Static table. ], supported: { - 'TYO1': [EndpointService.eew, EndpointService.report], - // The exclusive api.core-tnn1 family (meteor, tiles lists, location, - // notify) has no tyo1 sibling. + 'TYO1': [ + EndpointService.eew, + EndpointService.report, + EndpointService.radar, + EndpointService.qpesums, + EndpointService.rts, + ], + // The TNN1-exclusive api.core-tnn1 family (meteor, satellite/wind + // lists) has no tyo1 sibling. 'TNN1': [ EndpointService.eew, EndpointService.report, @@ -312,14 +321,17 @@ class _ClientEndpoints extends StatelessWidget { EndpointService.typhoon, EndpointService.location, EndpointService.notify, - ], - // The legacy api-1 host only carries the old strong-motion/event/history - // endpoints. - 'API-1': [ - EndpointService.tremStation, - EndpointService.event, EndpointService.rts, ], + // The legacy api-1 host only carries the old event feed. + 'API-1': [EndpointService.event], + }, + // The hot standby: tnn1 owns the service and takes all traffic; tyo1 + // answers with a 301 back to it and only takes over when tnn1 is gone. + // A redirect is not a second origin, so it must not read as 不支援 + // either. + standby: { + 'TYO1': [EndpointService.location, EndpointService.notify], }, ), _Group( @@ -338,11 +350,19 @@ class _ClientEndpoints extends StatelessWidget { EndpointService.rain, EndpointService.lightning, EndpointService.typhoon, + EndpointService.tremStation, ], - // api.md: every static host is core-tnn1. TYO1 has no static side at all, - // so its whole column is 不支援 rather than an em-dash that implies a - // host we simply have not probed yet. + // api.md: radar/QPESUMS/DPM tiles, the station CSV and satellite/wind/ + // meteor assets all live under `static.core-*`. Radar, QPESUMS, DPM and + // the station directory are multi-active; satellite tiles, wind `.bin` + // and the v5 meteor snapshots only exist on tnn1's static host. supported: { + 'TYO1': [ + EndpointService.radar, + EndpointService.qpesums, + EndpointService.dpm, + EndpointService.tremStation, + ], 'TNN1': [ EndpointService.radar, EndpointService.satellite, @@ -353,6 +373,7 @@ class _ClientEndpoints extends StatelessWidget { EndpointService.rain, EndpointService.lightning, EndpointService.typhoon, + EndpointService.tremStation, ], }, ), @@ -419,6 +440,11 @@ class _Legend extends StatelessWidget { Theme.of(context).colorScheme.outline, l10n.statusLegendUnprobed, ), + ( + Icons.swap_horiz, + Theme.of(context).colorScheme.tertiary, + l10n.statusLegendStandby, + ), ( Icons.block, Theme.of(context).colorScheme.outlineVariant, @@ -460,6 +486,7 @@ class _Group { required this.regions, required this.services, required this.supported, + this.standby = const {}, }); final String titleKey; @@ -480,10 +507,19 @@ class _Group { /// missing from [supported] means that region does not carry that service. final Map> supported; + /// Services whose backup region answers with a redirect to the primary + /// instead of serving them — tnn1 owns the write path and tyo1 only takes + /// over when tnn1 is gone. + final Map> standby; + /// Whether [region] actually runs [service] on this tier family. bool supports(EndpointService service, String region) => supported[region]?.contains(service) ?? false; + /// Whether [region] only holds a hot standby for [service]. + bool holdsStandby(EndpointService service, String region) => + standby[region]?.contains(service) ?? false; + /// Whether [h] belongs in this group, judged by its host. bool matches(EndpointHealth h) { final host = h.host.toLowerCase(); @@ -547,17 +583,24 @@ class _ServiceTable extends StatelessWidget { for (final r in group.regions) _headerCell(context, r), ]); - // A cell with no hit is one of two honest answers depending on whether the - // region actually serves this service: 未探測 when it should (a host exists - // the probe simply has not touched), 不支援 when it should not (api.md says - // the region has no such host at all — e.g. every TYO1 static cell). + // A cell with no hit is one of three honest answers depending on whether + // the region actually serves this service: 未探測 when it should (a host + // exists the probe simply has not touched), 熱備援 when the region only + // redirects back to the region that owns it, 不支援 when it should not + // (api.md says the region has no such host at all — e.g. every TYO1 + // static cell for a satellite tile). for (final s in group.services) { rows.add([ _serviceCell(context, s), for (final r in group.regions) - group.supports(s, r) - ? _probeCell(context, cell[(s, r)]) - : _unsupportedCell(context), + switch ((cell[(s, r)], group.supports(s, r))) { + (final hit?, _) => _probeCell(context, hit), + (null, true) => _probeCell(context, null), + (null, false) when group.holdsStandby(s, r) => _standbyCell( + context, + ), + (null, false) => _unsupportedCell(context), + }, ]); } @@ -659,6 +702,24 @@ class _ServiceTable extends StatelessWidget { ), ); + /// A cell for the standby region of a write path: a redirect arrow rather + /// than a tick, because that host answers with a 301 back to the primary + /// and never serves the request itself. + Widget _standbyCell(BuildContext context) => Padding( + padding: const EdgeInsets.symmetric(vertical: AppSpacing.xs), + child: Tooltip( + message: context.l10n.statusLegendStandby, + child: SizedBox( + height: 24, + child: Icon( + Icons.swap_horiz, + size: 18, + color: Theme.of(context).colorScheme.tertiary, + ), + ), + ), + ); + String _serviceLabel(BuildContext context, EndpointService s) { final l10n = context.l10n; return switch (s) { diff --git a/lib/features/weather/data/frame_tile_api.dart b/lib/features/weather/data/frame_tile_api.dart index 6d85e9558..1fe1eb312 100644 --- a/lib/features/weather/data/frame_tile_api.dart +++ b/lib/features/weather/data/frame_tile_api.dart @@ -39,11 +39,20 @@ class FrameTileApi { /// radar / satellite / QPESUMS never set it. final String? model; - /// The v2 frame list lives on `api.core-tnn1` (no region failover). - static const ApiTier _listTier = ApiTier.coreExclusiveApi; + /// Radar and QPESUMS are copied to both core regions, so their list and + /// tiles follow the region selection; satellite and wind exist only on + /// `core-tnn1` and keep the exclusive tiers. + bool get _multiRegion => path == 'radar' || path == 'qpesums'; - /// v2 tiles live on `static.core-tnn1` (no region failover). - static const ApiTier _tileTier = ApiTier.coreStaticExclusive; + /// The v2 frame list: `api.core-{tyo1,tnn1}` for radar and QPESUMS, + /// `api.core-tnn1` for the rest. + ApiTier get _listTier => + _multiRegion ? ApiTier.coreApi : ApiTier.coreExclusiveApi; + + /// v2 tiles: `static.core-{tyo1,tnn1}` for radar and QPESUMS, + /// `static.core-tnn1` for the rest. + ApiTier get _tileTier => + _multiRegion ? ApiTier.coreStatic : ApiTier.coreStaticExclusive; /// Available opaque frame ids, **newest valid time first**. Future> getFrames() async { @@ -58,6 +67,10 @@ class FrameTileApi { }; /// XYZ WebP raster tile URL template for [frame]. + /// + /// Only the selected region's host is used: MapLibre fetches every tile + /// itself, so a tile request cannot fail over per request — the style's + /// source URL is what a region change replaces. String tileUrl(String frame) { final host = _client.hostsFor(_tileTier).first; if (path == 'satellite') { diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 32a97bb94..b0390b2fa 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -4007,6 +4007,7 @@ }, "statusLegendUnprobed": "Not yet probed", "statusLegendUnsupported": "Not offered", + "statusLegendStandby": "Hot standby", "rainScaleSection": "Colour scale", "rainScaleFine": "Fine", "rainScaleCoarse": "Coarse", diff --git a/lib/l10n/app_fil.arb b/lib/l10n/app_fil.arb index c2d5c0d45..dc7a42035 100644 --- a/lib/l10n/app_fil.arb +++ b/lib/l10n/app_fil.arb @@ -1990,6 +1990,7 @@ "dumpUploadFailed": "Nabigong mag-upload", "statusLegendUnprobed": "Hindi pa nasuri", "statusLegendUnsupported": "Hindi suportado", + "statusLegendStandby": "Hot standby", "rainScaleSection": "Antas ng kulay", "rainScaleFine": "Pino", "rainScaleCoarse": "Magaspang", diff --git a/lib/l10n/app_id.arb b/lib/l10n/app_id.arb index ac95fb5d9..8c1753208 100644 --- a/lib/l10n/app_id.arb +++ b/lib/l10n/app_id.arb @@ -1990,6 +1990,7 @@ "dumpUploadFailed": "Gagal mengunggah", "statusLegendUnprobed": "Belum diperiksa", "statusLegendUnsupported": "Tidak tersedia", + "statusLegendStandby": "Siaga panas", "rainScaleSection": "Skala warna", "rainScaleFine": "Halus", "rainScaleCoarse": "Kasar", diff --git a/lib/l10n/app_ja.arb b/lib/l10n/app_ja.arb index 68d6e3688..d2b7bcadf 100644 --- a/lib/l10n/app_ja.arb +++ b/lib/l10n/app_ja.arb @@ -1990,6 +1990,7 @@ "dumpUploadFailed": "アップロードに失敗しました", "statusLegendUnprobed": "未探知", "statusLegendUnsupported": "非対応", + "statusLegendStandby": "ホットスタンバイ", "rainScaleSection": "色階の間隔", "rainScaleFine": "細かい", "rainScaleCoarse": "粗い", diff --git a/lib/l10n/app_ko.arb b/lib/l10n/app_ko.arb index 78ff85bb3..04d19f6f7 100644 --- a/lib/l10n/app_ko.arb +++ b/lib/l10n/app_ko.arb @@ -1990,6 +1990,7 @@ "dumpUploadFailed": "업로드하지 못했습니다", "statusLegendUnprobed": "탐지 안 됨", "statusLegendUnsupported": "미지원", + "statusLegendStandby": "핫 스탠바이", "rainScaleSection": "색상 간격", "rainScaleFine": "좁게", "rainScaleCoarse": "넓게", diff --git a/lib/l10n/app_th.arb b/lib/l10n/app_th.arb index 65eb0abf8..736284278 100644 --- a/lib/l10n/app_th.arb +++ b/lib/l10n/app_th.arb @@ -1990,6 +1990,7 @@ "dumpUploadFailed": "อัปโหลดไม่สำเร็จ", "statusLegendUnprobed": "ยังไม่ตรวจ", "statusLegendUnsupported": "ไม่รองรับ", + "statusLegendStandby": "สแตนด์บายพร้อมใช้", "rainScaleSection": "ช่วงระดับสี", "rainScaleFine": "ละเอียด", "rainScaleCoarse": "หยาบ", diff --git a/lib/l10n/app_vi.arb b/lib/l10n/app_vi.arb index 8b66d3657..4de1a0641 100644 --- a/lib/l10n/app_vi.arb +++ b/lib/l10n/app_vi.arb @@ -1990,6 +1990,7 @@ "dumpUploadFailed": "Tải lên thất bại", "statusLegendUnprobed": "Chưa dò", "statusLegendUnsupported": "Không có", + "statusLegendStandby": "Dự phòng nóng", "rainScaleSection": "Thang màu", "rainScaleFine": "Mịn", "rainScaleCoarse": "Thô", diff --git a/lib/l10n/app_yue.arb b/lib/l10n/app_yue.arb index 0ea250dae..ca3d531ca 100644 --- a/lib/l10n/app_yue.arb +++ b/lib/l10n/app_yue.arb @@ -1990,6 +1990,7 @@ "dumpUploadFailed": "上載失敗,請稍後再試", "statusLegendUnprobed": "未探測", "statusLegendUnsupported": "唔支援", + "statusLegendStandby": "熱備援", "rainScaleSection": "色階間距", "rainScaleFine": "小間距", "rainScaleCoarse": "大間距", diff --git a/lib/l10n/app_zh.arb b/lib/l10n/app_zh.arb index 6e511473c..0dfb018df 100644 --- a/lib/l10n/app_zh.arb +++ b/lib/l10n/app_zh.arb @@ -1982,6 +1982,7 @@ "dumpUploadFailed": "上傳失敗,請稍後再試", "statusLegendUnprobed": "未探測", "statusLegendUnsupported": "不支援", + "statusLegendStandby": "熱備援", "rainScaleSection": "色階間距", "rainScaleFine": "小間距", "rainScaleCoarse": "大間距", diff --git a/lib/l10n/app_zh_Hans.arb b/lib/l10n/app_zh_Hans.arb index a3b453ef7..a6196347b 100644 --- a/lib/l10n/app_zh_Hans.arb +++ b/lib/l10n/app_zh_Hans.arb @@ -1990,6 +1990,7 @@ "dumpUploadFailed": "上传失败,请稍后再试", "statusLegendUnprobed": "未探测", "statusLegendUnsupported": "不支持", + "statusLegendStandby": "热备援", "rainScaleSection": "色阶间距", "rainScaleFine": "小间距", "rainScaleCoarse": "大间距", diff --git a/lib/l10n/app_zh_Hant_HK.arb b/lib/l10n/app_zh_Hant_HK.arb index 0decca079..57d729d7d 100644 --- a/lib/l10n/app_zh_Hant_HK.arb +++ b/lib/l10n/app_zh_Hant_HK.arb @@ -1990,6 +1990,7 @@ "dumpUploadFailed": "上載失敗,請稍後再試", "statusLegendUnprobed": "未探測", "statusLegendUnsupported": "不支援", + "statusLegendStandby": "熱備援", "rainScaleSection": "色階間距", "rainScaleFine": "小間距", "rainScaleCoarse": "大間距", diff --git a/lib/l10n/app_zh_TW.arb b/lib/l10n/app_zh_TW.arb index b2452a8fc..1e6da214c 100644 --- a/lib/l10n/app_zh_TW.arb +++ b/lib/l10n/app_zh_TW.arb @@ -1990,6 +1990,7 @@ "dumpUploadFailed": "上傳失敗,請稍後再試", "statusLegendUnprobed": "未探測", "statusLegendUnsupported": "不支援", + "statusLegendStandby": "熱備援", "rainScaleSection": "色階間距", "rainScaleFine": "小間距", "rainScaleCoarse": "大間距", diff --git a/lib/l10n/gen/app_localizations.dart b/lib/l10n/gen/app_localizations.dart index 2554f1abb..bd2c99743 100644 --- a/lib/l10n/gen/app_localizations.dart +++ b/lib/l10n/gen/app_localizations.dart @@ -6318,6 +6318,12 @@ abstract class AppLocalizations { /// **'Not offered'** String get statusLegendUnsupported; + /// No description provided for @statusLegendStandby. + /// + /// In en, this message translates to: + /// **'Hot standby'** + String get statusLegendStandby; + /// Menu section header for the rainfall colour-scale interval choice /// /// In en, this message translates to: diff --git a/lib/l10n/gen/app_localizations_en.dart b/lib/l10n/gen/app_localizations_en.dart index 3e8da7f9f..9de6d9c50 100644 --- a/lib/l10n/gen/app_localizations_en.dart +++ b/lib/l10n/gen/app_localizations_en.dart @@ -3351,6 +3351,9 @@ class AppLocalizationsEn extends AppLocalizations { @override String get statusLegendUnsupported => 'Not offered'; + @override + String get statusLegendStandby => 'Hot standby'; + @override String get rainScaleSection => 'Colour scale'; diff --git a/lib/l10n/gen/app_localizations_fil.dart b/lib/l10n/gen/app_localizations_fil.dart index 4cafad404..c0fade1f0 100644 --- a/lib/l10n/gen/app_localizations_fil.dart +++ b/lib/l10n/gen/app_localizations_fil.dart @@ -3368,6 +3368,9 @@ class AppLocalizationsFil extends AppLocalizations { @override String get statusLegendUnsupported => 'Hindi suportado'; + @override + String get statusLegendStandby => 'Hot standby'; + @override String get rainScaleSection => 'Antas ng kulay'; diff --git a/lib/l10n/gen/app_localizations_id.dart b/lib/l10n/gen/app_localizations_id.dart index fef76ac2e..9cdc8d437 100644 --- a/lib/l10n/gen/app_localizations_id.dart +++ b/lib/l10n/gen/app_localizations_id.dart @@ -3360,6 +3360,9 @@ class AppLocalizationsId extends AppLocalizations { @override String get statusLegendUnsupported => 'Tidak tersedia'; + @override + String get statusLegendStandby => 'Siaga panas'; + @override String get rainScaleSection => 'Skala warna'; diff --git a/lib/l10n/gen/app_localizations_ja.dart b/lib/l10n/gen/app_localizations_ja.dart index 09cb50396..d5e5e5de7 100644 --- a/lib/l10n/gen/app_localizations_ja.dart +++ b/lib/l10n/gen/app_localizations_ja.dart @@ -3290,6 +3290,9 @@ class AppLocalizationsJa extends AppLocalizations { @override String get statusLegendUnsupported => '非対応'; + @override + String get statusLegendStandby => 'ホットスタンバイ'; + @override String get rainScaleSection => '色階の間隔'; diff --git a/lib/l10n/gen/app_localizations_ko.dart b/lib/l10n/gen/app_localizations_ko.dart index c5fb075bb..6d16ba954 100644 --- a/lib/l10n/gen/app_localizations_ko.dart +++ b/lib/l10n/gen/app_localizations_ko.dart @@ -3290,6 +3290,9 @@ class AppLocalizationsKo extends AppLocalizations { @override String get statusLegendUnsupported => '미지원'; + @override + String get statusLegendStandby => '핫 스탠바이'; + @override String get rainScaleSection => '색상 간격'; diff --git a/lib/l10n/gen/app_localizations_th.dart b/lib/l10n/gen/app_localizations_th.dart index 46a4b9bc0..2a7499207 100644 --- a/lib/l10n/gen/app_localizations_th.dart +++ b/lib/l10n/gen/app_localizations_th.dart @@ -3341,6 +3341,9 @@ class AppLocalizationsTh extends AppLocalizations { @override String get statusLegendUnsupported => 'ไม่รองรับ'; + @override + String get statusLegendStandby => 'สแตนด์บายพร้อมใช้'; + @override String get rainScaleSection => 'ช่วงระดับสี'; diff --git a/lib/l10n/gen/app_localizations_vi.dart b/lib/l10n/gen/app_localizations_vi.dart index ab2a86dd5..c0e674221 100644 --- a/lib/l10n/gen/app_localizations_vi.dart +++ b/lib/l10n/gen/app_localizations_vi.dart @@ -3351,6 +3351,9 @@ class AppLocalizationsVi extends AppLocalizations { @override String get statusLegendUnsupported => 'Không có'; + @override + String get statusLegendStandby => 'Dự phòng nóng'; + @override String get rainScaleSection => 'Thang màu'; diff --git a/lib/l10n/gen/app_localizations_yue.dart b/lib/l10n/gen/app_localizations_yue.dart index 9129a7ba9..805ebb212 100644 --- a/lib/l10n/gen/app_localizations_yue.dart +++ b/lib/l10n/gen/app_localizations_yue.dart @@ -3274,6 +3274,9 @@ class AppLocalizationsYue extends AppLocalizations { @override String get statusLegendUnsupported => '唔支援'; + @override + String get statusLegendStandby => '熱備援'; + @override String get rainScaleSection => '色階間距'; diff --git a/lib/l10n/gen/app_localizations_zh.dart b/lib/l10n/gen/app_localizations_zh.dart index 4aad366ca..ecf68f09f 100644 --- a/lib/l10n/gen/app_localizations_zh.dart +++ b/lib/l10n/gen/app_localizations_zh.dart @@ -3274,6 +3274,9 @@ class AppLocalizationsZh extends AppLocalizations { @override String get statusLegendUnsupported => '不支援'; + @override + String get statusLegendStandby => '熱備援'; + @override String get rainScaleSection => '色階間距'; @@ -6887,6 +6890,9 @@ class AppLocalizationsZhHans extends AppLocalizationsZh { @override String get statusLegendUnsupported => '不支持'; + @override + String get statusLegendStandby => '热备援'; + @override String get rainScaleSection => '色阶间距'; @@ -10499,6 +10505,9 @@ class AppLocalizationsZhHantHk extends AppLocalizationsZh { @override String get statusLegendUnsupported => '不支援'; + @override + String get statusLegendStandby => '熱備援'; + @override String get rainScaleSection => '色階間距'; @@ -14112,6 +14121,9 @@ class AppLocalizationsZhTw extends AppLocalizationsZh { @override String get statusLegendUnsupported => '不支援'; + @override + String get statusLegendStandby => '熱備援'; + @override String get rainScaleSection => '色階間距'; diff --git a/lib/shared/map/base_map.dart b/lib/shared/map/base_map.dart index ce95d97ab..5a68cf5a3 100644 --- a/lib/shared/map/base_map.dart +++ b/lib/shared/map/base_map.dart @@ -5,6 +5,8 @@ import 'package:dpip/app/theme/app_spacing.dart'; import 'package:dpip/core/geo/town_directory.dart'; import 'package:dpip/core/logging/log.dart'; import 'package:dpip/core/platform/render_tier.dart'; +import 'package:dpip/core/network/api_region.dart'; +import 'package:dpip/core/network/region_selection.dart'; import 'package:dpip/shared/map/map_connectivity.dart'; import 'package:dpip/shared/map/map_frame_cap.dart'; import 'package:dpip/shared/map/map_style.dart'; @@ -503,23 +505,25 @@ class _BaseMapState extends State with WidgetsBindingObserver { }); } - /// Style string memoised per palette — all other inputs are const, and - /// Every [build] used to re-interpolate the full style JSON — the string only - /// varies by palette, town-label directory, and terrain presence, so it is - /// memoised on that tuple. - static final Map<(MapPalette, String, bool), String> _styleCache = {}; + /// Style string memoised per palette — the town-label directory, terrain + /// presence and the pinned LB region are the other inputs. Every [build] used + /// to re-interpolate the full style JSON — the string only varies by that + /// tuple, so it is memoised on it. + static final Map<(MapPalette, String, bool, LbRegion), String> _styleCache = + {}; static String _styleString( MapPalette palette, String townLabelData, bool includeTerrain, + LbRegion region, ) => _styleCache.putIfAbsent( - (palette, townLabelData, includeTerrain), + (palette, townLabelData, includeTerrain, region), () => exptechVectorStyle( palette, - basemapTileUrl: basemapOriginTileUrl, + basemapTileUrl: basemapOriginTileUrl(region), glyphsUrl: glyphsOriginUrl, - terrainTileUrl: includeTerrain ? terrainOriginTileUrl : null, + terrainTileUrl: includeTerrain ? terrainOriginTileUrl(region) : null, townLabelData: townLabelData, ), ); @@ -528,6 +532,10 @@ class _BaseMapState extends State with WidgetsBindingObserver { Widget build(BuildContext context) { final mountAttempt = _mountAttempt; final brightness = Theme.of(context).brightness; + // The basemap's own copy comes from the LB region the user picked, pinned by + // host rather than left to the bare CDN's balance (see [staticLbOrigin]). + // `watch`, so a region change reloads the style onto the other host. + final lbRegion = context.watch().lb; final palette = brightness == Brightness.light && widget.lightPalette != null ? widget.lightPalette! @@ -560,6 +568,7 @@ class _BaseMapState extends State with WidgetsBindingObserver { palette, townLabelGeoJson(context.read()), widget.includeTerrainInStyle, + lbRegion, ), // A remount gets a fresh id, so a collided first attempt recovers (see // [_scheduleReadinessRetry]). diff --git a/lib/shared/map/basemap_overlay_sync.dart b/lib/shared/map/basemap_overlay_sync.dart index 3ccbd7490..493d8f4cc 100644 --- a/lib/shared/map/basemap_overlay_sync.dart +++ b/lib/shared/map/basemap_overlay_sync.dart @@ -4,6 +4,7 @@ library; import 'package:dpip/core/logging/log.dart'; +import 'package:dpip/core/network/api_region.dart'; import 'package:dpip/shared/map/map_gsi_overlay.dart'; import 'package:dpip/shared/map/map_style.dart'; import 'package:flutter/material.dart' show Brightness; @@ -12,14 +13,15 @@ import 'package:maplibre_gl/maplibre_gl.dart'; /// Runtime DEM source — identical to what the baked style declares (see /// [exptechVectorStyle]), so a surface can rebuild the relief after removing /// it, with no drift between the two descriptions. -const RasterDemSourceProperties terrainSourceProps = RasterDemSourceProperties( - tiles: [terrainOriginTileUrl], - bounds: [110.0, 10.0, 132.0, 35.0], - minzoom: 0, - maxzoom: terrainSourceMaxZoom, - tileSize: 512, - encoding: 'mapbox', -); +RasterDemSourceProperties terrainSourceProps(LbRegion region) => + RasterDemSourceProperties( + tiles: [terrainOriginTileUrl(region)], + bounds: [110.0, 10.0, 132.0, 35.0], + minzoom: 0, + maxzoom: terrainSourceMaxZoom, + tileSize: 512, + encoding: 'mapbox', + ); /// Runtime hillshade layer — same id, same paint as the baked style. const HillshadeLayerProperties terrainLayerProps = HillshadeLayerProperties( @@ -60,6 +62,7 @@ class BasemapOverlaySync { required bool Function() showTerrain, required GsiOverlayController gsi, required Brightness brightness, + required LbRegion region, required bool Function() stillCurrent, }) async { while (stillCurrent()) { @@ -84,7 +87,10 @@ class BasemapOverlaySync { } if (effectiveTerrain && !_terrainOnMap) { - await controller.addSource(terrainSourceId, terrainSourceProps); + await controller.addSource( + terrainSourceId, + terrainSourceProps(region), + ); if (!stillCurrent()) return; await controller.addHillshadeLayer( terrainSourceId, @@ -101,6 +107,7 @@ class BasemapOverlaySync { selection: gsi, belowLayerId: townOutlineLayerId, groundBelowLayerId: townFillLayerId, + region: region, ); if (!stillCurrent()) return; _gsiOnMap = true; diff --git a/lib/shared/map/basemap_seeder.dart b/lib/shared/map/basemap_seeder.dart index 45d3bac30..89bdab048 100644 --- a/lib/shared/map/basemap_seeder.dart +++ b/lib/shared/map/basemap_seeder.dart @@ -3,9 +3,11 @@ library; import 'package:dpip/core/logging/log.dart'; +import 'package:dpip/core/network/api_region.dart'; import 'package:dpip/core/network/etag_cache_store.dart'; import 'package:dpip/shared/map/basemap_seed.g.dart'; import 'package:dpip/shared/map/basemap_seed_format.dart'; +import 'package:dpip/shared/map/map_style.dart'; import 'package:flutter/services.dart'; /// What one [BasemapSeeder.run] did: rows [planted], asset parts it had to @@ -51,6 +53,7 @@ class BasemapSeeder { // fields must stay private. BasemapSeeder( this._store, { + required this.region, AssetBundle? bundle, BasemapSeedIndex index = bundledBasemapSeed, }) : _bundle = bundle ?? rootBundle, @@ -58,6 +61,16 @@ class BasemapSeeder { _index = index; final EtagCacheStore _store; + + /// Which LB region's map host the tiles are planted under. + /// + /// The style names a region-pinned host (`static.lb-tpe1`, `static.lb-khh1`), + /// and the tile store keys rows by URL, so a row planted under any other + /// host is a row MapLibre never asks for. Switching region leaves the other + /// host's rows to the eviction policy; the network fills them in as it does + /// on a map that has never had them. + final LbRegion region; + final AssetBundle _bundle; final BasemapSeedIndex _index; @@ -141,7 +154,7 @@ class BasemapSeeder { } String _url(BasemapSeedTile tile) => - basemapSeedUrl(_index.source, tile.z, tile.x, tile.y); + basemapSeedUrl(basemapOriginTileUrl(region), tile.z, tile.x, tile.y); static Uint8List _copy(Uint8List bytes, int start, int end) => start == end ? Uint8List(0) : bytes.sublist(start, end); diff --git a/lib/shared/map/map_gsi_overlay.dart b/lib/shared/map/map_gsi_overlay.dart index b1d5df738..8c8b74f00 100644 --- a/lib/shared/map/map_gsi_overlay.dart +++ b/lib/shared/map/map_gsi_overlay.dart @@ -13,6 +13,7 @@ import 'package:dpip/app/theme/app_radius.dart'; import 'package:dpip/app/theme/app_spacing.dart'; import 'package:dpip/core/a11y/color_vision.dart'; import 'package:dpip/core/network/api_paths.dart'; +import 'package:dpip/core/network/api_region.dart'; import 'package:dpip/core/settings/setting_keys.dart'; import 'package:dpip/core/settings/settings_store.dart'; import 'package:dpip/l10n/gen/app_localizations.dart'; @@ -23,19 +24,24 @@ import 'package:flutter/material.dart'; import 'package:maplibre_gl/maplibre_gl.dart'; const String gsiSourceId = 'gsi'; -const String gsiOriginTileUrl = - 'https://static.lb.exptech.dev${ApiPaths.mapOsmV1}{z}/{x}/{y}.pbf'; + +/// OSM detailed-tile origin for [region] (static LB CDN), pinned the same way +/// as the basemap and terrain — see [staticLbOrigin]. +String gsiOriginTileUrl(LbRegion region) => + '${staticLbOrigin(region)}${ApiPaths.mapOsmV1}{z}/{x}/{y}.pbf'; + const double gsiSourceMaxZoom = 14; const double gsiDisplayMaxZoom = 18; const List gsiBounds = [114.28579, 10.32677, 122.3283, 26.43722]; -const VectorSourceProperties gsiSourceProperties = VectorSourceProperties( - tiles: [gsiOriginTileUrl], - bounds: gsiBounds, - minzoom: 0, - maxzoom: gsiSourceMaxZoom, - attribution: '© OpenStreetMap contributors © OpenMapTiles', -); +VectorSourceProperties gsiSourceProperties(LbRegion region) => + VectorSourceProperties( + tiles: [gsiOriginTileUrl(region)], + bounds: gsiBounds, + minzoom: 0, + maxzoom: gsiSourceMaxZoom, + attribution: '© OpenStreetMap contributors © OpenMapTiles', + ); /// User-facing groups from the reference implementation. Some groups own two /// MapLibre layers (fill + outline, or road casing + road body), but expose one @@ -707,10 +713,11 @@ Future addGsiOverlay( required GsiOverlayController selection, required String belowLayerId, required String groundBelowLayerId, + required LbRegion region, }) async { final layers = gsiStyleLayers(brightness); final added = []; - await controller.addSource(gsiSourceId, gsiSourceProperties); + await controller.addSource(gsiSourceId, gsiSourceProperties(region)); try { for (final layer in layers) { final properties = layer.propertiesWithVisibility( diff --git a/lib/shared/map/map_scaffold.dart b/lib/shared/map/map_scaffold.dart index 20d5c9989..9b6e6c235 100644 --- a/lib/shared/map/map_scaffold.dart +++ b/lib/shared/map/map_scaffold.dart @@ -4,6 +4,8 @@ import 'package:dpip/app/theme/app_radius.dart'; import 'package:dpip/app/theme/app_spacing.dart'; import 'package:dpip/core/error/failure.dart'; import 'package:dpip/core/logging/log.dart'; +import 'package:dpip/core/network/api_region.dart'; +import 'package:dpip/core/network/region_selection.dart'; import 'package:dpip/core/realtime/app_time.dart'; import 'package:dpip/core/settings/map_layer_visibility_controller.dart'; import 'package:dpip/core/settings/setting_keys.dart'; @@ -38,10 +40,6 @@ import 'package:flutter/material.dart'; import 'package:maplibre_gl/maplibre_gl.dart'; import 'package:provider/provider.dart'; -/// Basemap XYZ origin — warmed from the app's tile store into MapLibre's tile -/// memory on camera idle. LB has no ETag; the store keys these by URL hash. -const String _basemapTileUrl = basemapOriginTileUrl; - /// The reusable map surface — a base map with a switchable, time-scrubbable /// overlay layer. /// @@ -786,12 +784,16 @@ class _MapScaffoldState extends State with WidgetsBindingObserver { final controller = _controller; if (!mounted || controller == null || !_styleLoaded) return; final brightness = Theme.of(context).brightness; + // The pinned LB region, so the DEM and OSM sources point at the same host + // copy as the basemap style that [BaseMap] built (see [staticLbOrigin]). + final region = context.read().lb; _queue( () => _basemapSync.sync( controller, showTerrain: () => _showTerrain.value, gsi: _gsi, brightness: brightness, + region: region, stillCurrent: () => mounted && identical(controller, _controller) && _styleLoaded, ), @@ -817,15 +819,19 @@ class _MapScaffoldState extends State with WidgetsBindingObserver { Future _warmBasemap(MapLibreMapController controller) async { await _tileCacheReady; final warmer = _basemapWarmer; - if (warmer == null) return; + if (warmer == null || !mounted) return; + // Warm exactly what the style will be reading: the region-pinned host, not + // a bare CDN name that balances somewhere else (see [staticLbOrigin]). + final region = context.read().lb; try { final bounds = await controller.getVisibleRegion(); final zoom = controller.cameraPosition?.zoom ?? 8; await warmer.warmViewportAbsolute( - urlFor: (z, x, y) => _basemapTileUrl - .replaceAll('{z}', '$z') - .replaceAll('{x}', '$x') - .replaceAll('{y}', '$y'), + urlFor: (z, x, y) => + basemapOriginTileUrl(region) + .replaceAll('{z}', '$z') + .replaceAll('{x}', '$x') + .replaceAll('{y}', '$y'), south: bounds.southwest.latitude, west: bounds.southwest.longitude, north: bounds.northeast.latitude, @@ -837,7 +843,7 @@ class _MapScaffoldState extends State with WidgetsBindingObserver { immediate: true, ); if (_gsi.enabled) { - await _warmGsiViewport(warmer, bounds, zoom); + await _warmGsiViewport(warmer, bounds, zoom, region); } // DEM tiles too — the relief renders at every zoom, so warm them the // same way as the basemap. Native downloads a hillshade viewport as one @@ -851,10 +857,11 @@ class _MapScaffoldState extends State with WidgetsBindingObserver { // applier's on-map flag, which is transiently wrong mid style-reload. if (_showTerrain.value) { await warmer.warmViewportAbsolute( - urlFor: (z, x, y) => terrainOriginTileUrl - .replaceAll('{z}', '$z') - .replaceAll('{x}', '$x') - .replaceAll('{y}', '$y'), + urlFor: (z, x, y) => + terrainOriginTileUrl(region) + .replaceAll('{z}', '$z') + .replaceAll('{x}', '$x') + .replaceAll('{y}', '$y'), south: bounds.southwest.latitude, west: bounds.southwest.longitude, north: bounds.northeast.latitude, @@ -881,11 +888,14 @@ class _MapScaffoldState extends State with WidgetsBindingObserver { } try { final bounds = await controller.getVisibleRegion(); - if (!_gsi.enabled || !identical(controller, _controller)) return; + if (!_gsi.enabled || !identical(controller, _controller) || !mounted) { + return; + } await _warmGsiViewport( warmer, bounds, controller.cameraPosition?.zoom ?? 8, + context.read().lb, ); } catch (error, stackTrace) { Log.handle(error, stackTrace, 'OSM viewport warm'); @@ -896,11 +906,13 @@ class _MapScaffoldState extends State with WidgetsBindingObserver { MapTileWarmer warmer, LatLngBounds bounds, double zoom, + LbRegion region, ) => warmer.warmViewportAbsolute( - urlFor: (z, x, y) => gsiOriginTileUrl - .replaceAll('{z}', '$z') - .replaceAll('{x}', '$x') - .replaceAll('{y}', '$y'), + urlFor: (z, x, y) => + gsiOriginTileUrl(region) + .replaceAll('{z}', '$z') + .replaceAll('{x}', '$x') + .replaceAll('{y}', '$y'), south: bounds.southwest.latitude, west: bounds.southwest.longitude, north: bounds.northeast.latitude, diff --git a/lib/shared/map/map_style.dart b/lib/shared/map/map_style.dart index 0a8c0c4b9..e76f886b0 100644 --- a/lib/shared/map/map_style.dart +++ b/lib/shared/map/map_style.dart @@ -11,6 +11,7 @@ import 'package:dpip/core/a11y/color_vision.dart'; import 'package:dpip/core/geo/town_directory.dart'; import 'package:dpip/shared/map/town_label_points.g.dart'; import 'package:dpip/core/network/api_paths.dart'; +import 'package:dpip/core/network/api_region.dart'; /// Highest source levels that add useful visual information. The map's camera /// may continue past these; MapLibre then overzooms the final native tile. @@ -236,19 +237,19 @@ const String dpmRestroomPointsLayerId = 'dpm-restroom-points'; const String dpmShelterSourceId = 'dpm-shelter-src'; const String dpmShelterPointsLayerId = 'dpm-shelter-points'; -/// Origin basemap XYZ (static LB CDN). Fetched by MapLibre, served from the -/// app's tile store through the Dart bridge, and warmed by `MapTileWarmer` — -/// the same three tiers as every other ExpTech tile. -const String basemapOriginTileUrl = - 'https://static.lb.exptech.dev${ApiPaths.mapTilesV1}{z}/{x}/{y}.pbf'; +/// Origin basemap XYZ for [region] (static LB CDN). Fetched by MapLibre, served +/// from the app's tile store through the Dart bridge, and warmed by +/// `MapTileWarmer` — the same three tiers as every other ExpTech tile. +String basemapOriginTileUrl(LbRegion region) => + '${staticLbOrigin(region)}${ApiPaths.mapTilesV1}{z}/{x}/{y}.pbf'; -/// Origin terrain XYZ (static LB CDN) — the elevation mesh backing the -/// base map's hillshade relief. +/// Origin terrain XYZ for [region] (static LB CDN) — the elevation mesh backing +/// the base map's hillshade relief. /// /// The tiles are **Mapbox.com terrain-RGB PNGs**, which MapLibre's /// `encoding: 'mapbox'` decodes natively — no app-side rewrite. -const String terrainOriginTileUrl = - 'https://static.lb.exptech.dev${ApiPaths.mapTerrainV1}{z}/{x}/{y}.png'; +String terrainOriginTileUrl(LbRegion region) => + '${staticLbOrigin(region)}${ApiPaths.mapTerrainV1}{z}/{x}/{y}.png'; /// Origin glyph template — MapLibre HTTPS. const String glyphsOriginUrl = diff --git a/test/core/network/dio_redirect_test.dart b/test/core/network/dio_redirect_test.dart new file mode 100644 index 000000000..c6147d6c5 --- /dev/null +++ b/test/core/network/dio_redirect_test.dart @@ -0,0 +1,53 @@ +/// The one place a 3xx has to be followed rather than surfaced. +/// +/// notify/location are primary-on-`core-tnn1` with a **hot standby**: tyo1 +/// answers **307** to the primary on every live request, not only when the +/// primary is gone — the standby carries no ordinary traffic, so the redirect +/// is the normal path, not the exception. Following that redirect is +/// therefore not cosmetic — a client that treated it as an error would report a +/// settings write as failed while the write it never made was still missing. +/// +/// The behaviour lives in Dio's defaults (`followRedirects: true`, +/// `maxRedirects: 5`), which is exactly the kind of thing that is silently +/// changed later, so it is pinned here against a real server rather than +/// asserted about the options object. +library; + +import 'dart:io'; + +import 'package:dpip/core/network/dio_client.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + test('follows the hot-standby redirect to the primary', () async { + final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0); + addTearDown(() => server.close(force: true)); + final origin = 'http://${server.address.address}:${server.port}'; + var primaryHits = 0; + + server.listen((request) async { + if (request.uri.path == '/notify/standby') { + request.response + ..statusCode = HttpStatus.temporaryRedirect + ..headers.set(HttpHeaders.locationHeader, '$origin/notify/primary') + ..close(); + return; + } + primaryHits++; + request.response + ..statusCode = HttpStatus.ok + ..write('[1,0]') + ..close(); + }); + + final response = await createDio().get('$origin/notify/standby'); + + expect(response.statusCode, HttpStatus.ok); + expect(response.data, '[1,0]'); + expect( + primaryHits, + 1, + reason: 'the redirect must be followed, not reported', + ); + }); +} diff --git a/test/core/network/endpoint_health_test.dart b/test/core/network/endpoint_health_test.dart index 93d2e6cbb..94d869faf 100644 --- a/test/core/network/endpoint_health_test.dart +++ b/test/core/network/endpoint_health_test.dart @@ -208,4 +208,36 @@ void main() { expect(m.summary, EndpointState.down); }); }); + + test('ofPath follows the families that moved off the exclusive tiers', () { + // RTS history is v3; the live topic is v2 — both are the RTS row. + expect( + EndpointService.ofPath('/api/v3/trem/rts/1783360200'), + EndpointService.rts, + ); + expect( + EndpointService.ofPath('/api/v2/trem/rts?sse=1'), + EndpointService.rts, + ); + // The station directory is a static CSV, not an `/api/v1/trem/*` path. + expect( + EndpointService.ofPath('/resource/station'), + EndpointService.tremStation, + ); + for (final path in [ + '/api/v2/tiles/radar/list', + '/api/v2/tiles/radar/1783360200/7/1/1.webp', + '/api/v2/tiles/qpesums/list', + '/api/v2/tiles/dpm/shelter/10/5/3.mvt', + ]) { + expect( + EndpointService.ofPath(path), + anyOf( + EndpointService.radar, + EndpointService.qpesums, + EndpointService.dpm, + ), + ); + } + }); } diff --git a/test/core/realtime/http_time_source_test.dart b/test/core/realtime/http_time_source_test.dart index 705a1bd3f..d7451a1f1 100644 --- a/test/core/realtime/http_time_source_test.dart +++ b/test/core/realtime/http_time_source_test.dart @@ -1,3 +1,4 @@ +import 'package:dpip/core/network/api_region.dart'; import 'package:dpip/core/realtime/clock.dart'; import 'package:dpip/core/realtime/http_time_source.dart'; import 'package:flutter_test/flutter_test.dart'; @@ -175,16 +176,27 @@ void main() { expect(result.isOk, isFalse); }); - test('asks the DNS-balanced LB name over HTTPS', () { - // The one bare host the repository uses: a clock reading has no region to - // pin, and this is the name Cloudflare terminates with a valid cert. - expect(HttpTimeSource.defaultHosts, ['api.lb.exptech.dev']); + test('asks the region-pinned LB names over HTTPS, tpe1 first', () { + // No bare host: the reading comes from the same edge the rest of the app + // talks to, and the second name is a fallback rather than a load-sharing + // peer — serverTimeMs stops at the first reading its own Date accepts. + expect(HttpTimeSource.defaultHosts, [ + 'api.lb-tpe1.exptech.dev', + 'api.lb-khh1.exptech.dev', + ]); expect( - HttpTimeSource.urlFor(HttpTimeSource.defaultHosts.single).toString(), - 'https://api.lb.exptech.dev/ntp', + HttpTimeSource.urlFor(HttpTimeSource.defaultHosts.first).toString(), + 'https://api.lb-tpe1.exptech.dev/ntp', ); }); + test('orders the hosts by the selected region', () { + expect(HttpTimeSource.hostsFor(const [LbRegion.khh1, LbRegion.tpe1]), [ + 'api.lb-khh1.exptech.dev', + 'api.lb-tpe1.exptech.dev', + ]); + }); + test('never builds a cleartext url', () { // A cleartext time source is one any network in the path can rewrite — // including the captive portals that block UDP/123 in the first place. diff --git a/test/features/disaster_map/data/disaster_map_api_test.dart b/test/features/disaster_map/data/disaster_map_api_test.dart index 499ccc3b3..9ddb29958 100644 --- a/test/features/disaster_map/data/disaster_map_api_test.dart +++ b/test/features/disaster_map/data/disaster_map_api_test.dart @@ -14,9 +14,9 @@ /// venue's data. /// /// So this pins the exact URL each of the four methods builds, on the -/// `static.core-tnn1` host ([ApiTier.coreStaticExclusive] — single host, no -/// region failover), and that a detail response's JSON object is handed back -/// as a plain `Map`. +/// selected region's `static.core-` host ([ApiTier.coreStatic] — both +/// core regions carry the DPM backend), and that a detail response's JSON +/// object is handed back as a plain `Map`. library; import 'dart:typed_data'; diff --git a/test/features/disaster_map/data/dpm_tile_prefetcher_test.dart b/test/features/disaster_map/data/dpm_tile_prefetcher_test.dart index 6ab32e749..ec4865e9a 100644 --- a/test/features/disaster_map/data/dpm_tile_prefetcher_test.dart +++ b/test/features/disaster_map/data/dpm_tile_prefetcher_test.dart @@ -93,35 +93,32 @@ void main() { client = ApiClient(Dio(), RegionSelection(SettingsStore.inMemory({}))); }); - test( - 'prefetch targets the static-exclusive tier and the dpm mvt path template', - () async { - final warmer = _RecordingWarmer(); - final prefetcher = DpmTilePrefetcher(client, warmer); - - await prefetcher.prefetch( - layer: 'shelter', - south: 21.9, - west: 120.0, - north: 25.3, - east: 122.0, - zoom: 12, - ); - - expect(warmer.warmViewportCalls, hasLength(1)); - final call = warmer.warmViewportCalls.single; - expect(call.tier, ApiTier.coreStaticExclusive); - expect(call.pathFor(10, 5, 3), '/api/v2/tiles/dpm/shelter/10/5/3.mvt'); - expect(call.south, 21.9); - expect(call.west, 120.0); - expect(call.north, 25.3); - expect(call.east, 122.0); - expect(call.zoom, 12.0); - expect(call.maxZoom, dpmSourceMaxZoom.toInt()); - expect(call.logLabel, 'dpm-shelter'); - expect(call.workingSet, 'dpm-shelter'); - }, - ); + test('prefetch targets the region-pinned static tier and the dpm mvt path template', () async { + final warmer = _RecordingWarmer(); + final prefetcher = DpmTilePrefetcher(client, warmer); + + await prefetcher.prefetch( + layer: 'shelter', + south: 21.9, + west: 120.0, + north: 25.3, + east: 122.0, + zoom: 12, + ); + + expect(warmer.warmViewportCalls, hasLength(1)); + final call = warmer.warmViewportCalls.single; + expect(call.tier, ApiTier.coreStatic); + expect(call.pathFor(10, 5, 3), '/api/v2/tiles/dpm/shelter/10/5/3.mvt'); + expect(call.south, 21.9); + expect(call.west, 120.0); + expect(call.north, 25.3); + expect(call.east, 122.0); + expect(call.zoom, 12.0); + expect(call.maxZoom, dpmSourceMaxZoom.toInt()); + expect(call.logLabel, 'dpm-shelter'); + expect(call.workingSet, 'dpm-shelter'); + }); test('each layer gets its own working set, log label and path — one layer ' 'never collides with another', () async { diff --git a/test/features/earthquake/presentation/pages/report_detail_page_test.dart b/test/features/earthquake/presentation/pages/report_detail_page_test.dart index 652d7605b..de6806e01 100644 --- a/test/features/earthquake/presentation/pages/report_detail_page_test.dart +++ b/test/features/earthquake/presentation/pages/report_detail_page_test.dart @@ -364,6 +364,10 @@ void main() { Provider.value(value: settings), ChangeNotifierProvider.value(value: regions), Provider.value(value: towns), + // The basemap host is pinned to the selected LB region. + ChangeNotifierProvider.value( + value: RegionSelection(settings), + ), ], child: MaterialApp.router( theme: theme, diff --git a/test/features/earthquake/presentation/pages/report_replay_page_test.dart b/test/features/earthquake/presentation/pages/report_replay_page_test.dart index c64d718bd..479bb3bad 100644 --- a/test/features/earthquake/presentation/pages/report_replay_page_test.dart +++ b/test/features/earthquake/presentation/pages/report_replay_page_test.dart @@ -507,6 +507,10 @@ void main() { Provider>.value(value: Future.value(grid)), Provider.value(value: towns), Provider.value(value: settings), + // The basemap host is pinned to the selected LB region. + ChangeNotifierProvider.value( + value: RegionSelection(settings), + ), ChangeNotifierProvider.value( value: RegionStore(settings), ), @@ -724,6 +728,10 @@ void main() { ), Provider.value(value: const TownDirectory({})), Provider.value(value: settings), + // The basemap host is pinned to the selected LB region. + ChangeNotifierProvider.value( + value: RegionSelection(settings), + ), ChangeNotifierProvider.value( value: RegionStore(settings), ), @@ -812,6 +820,10 @@ void main() { ), Provider.value(value: const TownDirectory({})), Provider.value(value: settings), + // The basemap host is pinned to the selected LB region. + ChangeNotifierProvider.value( + value: RegionSelection(settings), + ), ChangeNotifierProvider.value( value: RegionStore(settings), ), @@ -907,6 +919,10 @@ void main() { ), Provider.value(value: const TownDirectory({})), Provider.value(value: settings), + // The basemap host is pinned to the selected LB region. + ChangeNotifierProvider.value( + value: RegionSelection(settings), + ), ChangeNotifierProvider.value( value: RegionStore(settings), ), diff --git a/test/features/home/presentation/pages/home_page_test.dart b/test/features/home/presentation/pages/home_page_test.dart index 23ba63bed..891e3cab6 100644 --- a/test/features/home/presentation/pages/home_page_test.dart +++ b/test/features/home/presentation/pages/home_page_test.dart @@ -18,6 +18,7 @@ import 'package:dpip/core/realtime/ticker.dart'; import 'package:dpip/core/settings/experimental_settings.dart'; import 'package:dpip/core/settings/home_area.dart'; import 'package:dpip/core/settings/region_store.dart'; +import 'package:dpip/core/network/region_selection.dart'; import 'package:dpip/core/settings/settings_store.dart'; import 'package:dpip/core/settings/sky_time_mode.dart'; import 'package:dpip/core/settings/weather_mode.dart'; @@ -388,6 +389,7 @@ List _providers({ required HomeResetSignal reset, required MapCameraHandoff handoff, TownDirectory directory = const TownDirectory({}), + SettingsStore? settings, MeteorWeatherRepository weather = const _Weather(), RainHourTrendRepository? hours, }) { @@ -401,6 +403,10 @@ List _providers({ ChangeNotifierProvider.value(value: handoff), ChangeNotifierProvider(create: (_) => MapStationHandoff()), Provider.value(value: directory), + // The basemap host is pinned to the selected LB region. + ChangeNotifierProvider.value( + value: RegionSelection(settings ?? SettingsStore.inMemory()), + ), Provider.value( value: LocationService( directory, diff --git a/test/features/home/presentation/widgets/home_map_backdrop_widget_test.dart b/test/features/home/presentation/widgets/home_map_backdrop_widget_test.dart index 9992e4827..f3269b1c5 100644 --- a/test/features/home/presentation/widgets/home_map_backdrop_widget_test.dart +++ b/test/features/home/presentation/widgets/home_map_backdrop_widget_test.dart @@ -12,6 +12,7 @@ import 'package:dpip/core/geo/location_service.dart'; import 'package:dpip/core/geo/location_status.dart'; import 'package:dpip/core/geo/town_boundaries.dart'; import 'package:dpip/core/geo/town_directory.dart'; +import 'package:dpip/core/network/region_selection.dart'; import 'package:dpip/core/settings/region_store.dart'; import 'package:dpip/core/settings/settings_store.dart'; import 'package:dpip/features/home/presentation/home_reset_signal.dart'; @@ -208,6 +209,10 @@ Widget _host({ Provider>.value(value: boundaries), Provider.value(value: radar), Provider.value(value: const TownDirectory({})), + // The basemap host is pinned to the selected LB region. + ChangeNotifierProvider.value( + value: RegionSelection(SettingsStore.inMemory(const {})), + ), ], child: child, ), @@ -311,6 +316,7 @@ class _Platform extends MapLibrePlatform { bool throwMove = false; bool includeLocation = false; int moves = 0; + bool _viewCreated = false; Completer? gate; @override @@ -324,7 +330,14 @@ class _Platform extends MapLibrePlatform { OnPlatformViewCreatedCallback onPlatformViewCreated, Set>? gestureRecognizers, ) { - onPlatformViewCreated(1); + // A native view is created once; a widget rebuild does not create another. + // The map subtree does rebuild here (its style string now depends on the + // selected LB region), and calling this per build would complete the map's + // ready future twice. + if (!_viewCreated) { + _viewCreated = true; + onPlatformViewCreated(1); + } return const SizedBox.shrink(); } diff --git a/test/features/map/basemap_overlay_sync_test.dart b/test/features/map/basemap_overlay_sync_test.dart index c4e1cd117..ca5b7d2e5 100644 --- a/test/features/map/basemap_overlay_sync_test.dart +++ b/test/features/map/basemap_overlay_sync_test.dart @@ -1,3 +1,4 @@ +import 'package:dpip/core/network/api_region.dart'; import 'package:dpip/core/settings/settings_store.dart'; import 'package:dpip/shared/map/basemap_overlay_sync.dart'; import 'package:dpip/shared/map/map_gsi_overlay.dart'; @@ -28,6 +29,7 @@ void main() { showTerrain: () => showTerrain, gsi: gsi, brightness: Brightness.dark, + region: LbRegion.tpe1, stillCurrent: () => current, ); diff --git a/test/features/map/presentation/map_scaffold_test.dart b/test/features/map/presentation/map_scaffold_test.dart index 9aee4b68e..0d24fe8bd 100644 --- a/test/features/map/presentation/map_scaffold_test.dart +++ b/test/features/map/presentation/map_scaffold_test.dart @@ -9,6 +9,7 @@ import 'dart:math' show Point; import 'package:dpip/core/error/failure.dart'; import 'package:dpip/core/error/result.dart'; import 'package:dpip/core/geo/town_directory.dart'; +import 'package:dpip/core/network/region_selection.dart'; import 'package:dpip/core/settings/map_layer_order_controller.dart'; import 'package:dpip/core/settings/map_layer_visibility_controller.dart'; import 'package:dpip/core/settings/setting_keys.dart'; @@ -367,6 +368,10 @@ void main() { value: TownDirectory.fromJson(const {}), ), Provider.value(value: null), + // The basemap host is pinned to the selected LB region. + ChangeNotifierProvider.value( + value: RegionSelection(settings), + ), ], child: MaterialApp( locale: const Locale('en'), diff --git a/test/features/map/presentation/pages/map_page_test.dart b/test/features/map/presentation/pages/map_page_test.dart index f8bcd2ab0..706d4c943 100644 --- a/test/features/map/presentation/pages/map_page_test.dart +++ b/test/features/map/presentation/pages/map_page_test.dart @@ -8,6 +8,7 @@ import 'package:dpip/core/error/result.dart'; import 'package:dpip/core/geo/town_directory.dart'; import 'package:dpip/core/meshtastic/domain/meshtastic_service.dart'; import 'package:dpip/core/meshtastic/mesh_node_store.dart'; +import 'package:dpip/core/network/region_selection.dart'; import 'package:dpip/core/platform/background_location.dart'; import 'package:dpip/core/realtime/clock.dart'; import 'package:dpip/core/realtime/elapsed.dart'; @@ -268,6 +269,10 @@ void main() { Provider.value( value: TownDirectory.fromJson(const {}), ), + // The basemap host is pinned to the selected LB region. + ChangeNotifierProvider.value( + value: RegionSelection(settings), + ), Provider.value(value: RtsLiveDemand()), Provider.value(value: _NoEncoder()), Provider.value(value: _Ml()), diff --git a/test/features/status/server_status_page_test.dart b/test/features/status/server_status_page_test.dart index dcc7c88d7..e360a597a 100644 --- a/test/features/status/server_status_page_test.dart +++ b/test/features/status/server_status_page_test.dart @@ -218,7 +218,7 @@ void main() { expect(find.text(l10n.endpointHealthUnknown), findsOneWidget); }); - testWidgets('local status legend spells out the four cell states', ( + testWidgets('local status legend spells out the five cell states', ( tester, ) async { final repo = _FakeRepository(Ok(okStatus())); @@ -235,10 +235,13 @@ void main() { expect(find.text(l10n.endpointStateOk), findsWidgets); expect(find.text(l10n.endpointStateDown), findsWidgets); expect(find.text(l10n.statusLegendUnprobed), findsOneWidget); + // A standby region redirects to the primary instead of serving — neither + // a probe state nor 不支援. + expect(find.text(l10n.statusLegendStandby), findsOneWidget); expect(find.text(l10n.statusLegendUnsupported), findsOneWidget); }); - testWidgets('core static tyo1 column is unsupported, not unprobed', ( + testWidgets('core static tyo1 offers only the families it copied', ( tester, ) async { final repo = _FakeRepository(Ok(okStatus())); @@ -275,16 +278,44 @@ void main() { // Icon-based cells: a healthy check and a down error are both present. expect(find.byIcon(Icons.check_circle), findsWidgets); expect(find.byIcon(Icons.error), findsWidgets); - // The Core Static table's TYO1 column is entirely 不支援 — no static host - // exists for tyo1, so not even the radar row shows a probe state. + // The Core Static table's TYO1 column supports radar, QPESUMS, DPM and + // the station CSV; satellite, wind and the v5 meteor snapshots are the + // 不支援 cells there. expect(find.byIcon(Icons.block), findsWidgets); // The unprobed question-marks outnumber everything: the LB API rows and // Core API rows for every service/region the probe did not touch. expect(find.byIcon(Icons.help_outline), findsWidgets); - // Radar rows exist in both Core tables; TYO1's radar cell is 不支援. + // Radar rows exist in both Core tables; TYO1's radar cells are now + // probeable (未探測) rather than 不支援, because tyo1 runs the backend. expect(find.text(l10n.endpointServiceRadar), findsNWidgets(2)); }); + testWidgets('core api tyo1 shows hot standby for the write paths', ( + tester, + ) async { + final repo = _FakeRepository(Ok(okStatus())); + final health = EndpointHealthMonitor(); + // EEW history on tyo1 is a real second origin; notify/location on tyo1 + // only redirect back to tnn1, so their cells must not read as 不支援. + health.success( + ApiTier.coreApi, + 'https://api.core-tyo1.exptech.dev', + '/api/v2/eq/eew/1700000000', + ); + + tester.view.physicalSize = const Size(800, 5000); + tester.view.devicePixelRatio = 1.0; + addTearDown(tester.view.reset); + await tester.pumpWidget(wrap(repo, health: health)); + await tester.pumpAndSettle(); + + final l10n = l10nOf(tester); + // One cell for location and one for notify, both under TYO1. + expect(find.byTooltip(l10n.statusLegendStandby), findsNWidgets(2)); + // The legend names the state once, next to the other four. + expect(find.text(l10n.statusLegendStandby), findsOneWidget); + }); + testWidgets('a high error rate is degraded, and a blank host is a dash', ( tester, ) async { diff --git a/test/features/weather/frame_tile_api_test.dart b/test/features/weather/frame_tile_api_test.dart index ec15e25b4..ecc415598 100644 --- a/test/features/weather/frame_tile_api_test.dart +++ b/test/features/weather/frame_tile_api_test.dart @@ -2,6 +2,7 @@ import 'dart:typed_data'; import 'package:dio/dio.dart'; import 'package:dpip/core/network/api_client.dart'; +import 'package:dpip/core/network/api_region.dart'; import 'package:dpip/core/network/region_selection.dart'; import 'package:dpip/core/settings/settings_store.dart'; import 'package:dpip/features/weather/data/frame_tile_api.dart'; @@ -273,4 +274,54 @@ void main() { ); }); }); + + group('tier by path', () { + test('radar and QPESUMS follow the selected core region', () async { + final adapter = _RecordingAdapter(); + final regions = RegionSelection(SettingsStore.inMemory({})) + ..core = CoreRegion.tyo1; + final client = ApiClient(Dio()..httpClientAdapter = adapter, regions); + + final radar = FrameTileApi(client, 'radar'); + await radar.getFrames(); + expect( + adapter.urls.single, + startsWith('https://api.core-tyo1.exptech.dev/'), + ); + expect( + radar.tileUrl('1783360200'), + startsWith('https://static.core-tyo1.exptech.dev/'), + ); + + final qpesums = FrameTileApi(client, 'qpesums'); + expect( + qpesums.tileUrl('1783360200'), + startsWith('https://static.core-tyo1.exptech.dev/'), + ); + }); + + test('satellite and wind have no second region and stay on tnn1', () async { + final adapter = _RecordingAdapter(); + final regions = RegionSelection(SettingsStore.inMemory({})) + ..core = CoreRegion.tyo1; + final client = ApiClient(Dio()..httpClientAdapter = adapter, regions); + + final satellite = FrameTileApi(client, 'satellite', channel: '13'); + await satellite.getFrames(); + expect( + adapter.urls.single, + startsWith('https://api.core-tnn1.exptech.dev/'), + ); + expect( + satellite.tileUrl('1783360200'), + startsWith('https://static.core-tnn1.exptech.dev/'), + ); + + final wind = FrameTileApi(client, 'wind', model: 'gfs'); + expect( + wind.tileUrl('1783360200@1783339200'), + startsWith('https://static.core-tnn1.exptech.dev/'), + ); + }); + }); } diff --git a/test/shared/map/base_map_tab_test.dart b/test/shared/map/base_map_tab_test.dart index 081bd394f..2228f65bc 100644 --- a/test/shared/map/base_map_tab_test.dart +++ b/test/shared/map/base_map_tab_test.dart @@ -1,4 +1,6 @@ import 'package:dpip/core/geo/town_directory.dart'; +import 'package:dpip/core/network/region_selection.dart'; +import 'package:dpip/core/settings/settings_store.dart'; import 'package:dpip/shared/map/base_map.dart'; import 'package:dpip/shared/navigation/refresh_on_appear.dart'; import 'package:flutter/foundation.dart'; @@ -61,10 +63,19 @@ void main() { Future pump(WidgetTester tester, Widget child) async { await tester.pumpWidget( MaterialApp( - home: Provider.value( - // The style string needs a (empty) directory for its town labels — - // a real one is the app bootstrap's job. - value: TownDirectory.fromJson(const {}), + home: MultiProvider( + providers: [ + Provider.value( + // The style string needs a (empty) directory for its town labels — + // a real one is the app bootstrap's job. + value: TownDirectory.fromJson(const {}), + ), + // The basemap host is pinned to the selected LB region (see + // [staticLbOrigin]), so the map needs a selection to read. + ChangeNotifierProvider.value( + value: RegionSelection(SettingsStore.inMemory(const {})), + ), + ], child: child, ), ), diff --git a/test/shared/map/basemap_seed_test.dart b/test/shared/map/basemap_seed_test.dart index 348d80117..6c9ea509c 100644 --- a/test/shared/map/basemap_seed_test.dart +++ b/test/shared/map/basemap_seed_test.dart @@ -9,6 +9,7 @@ library; import 'dart:io'; import 'dart:typed_data'; +import 'package:dpip/core/network/api_region.dart'; import 'package:dpip/shared/map/basemap_seed.g.dart'; import 'package:dpip/shared/map/basemap_seed_format.dart'; import 'package:dpip/shared/map/map_style.dart'; @@ -52,11 +53,16 @@ void main() { group('the committed bundle', () { test('was fetched from the URL the style requests', () { + // The host is pinned per LB region at run time, so the template's host + // is not what has to match — the path is. `BasemapSeeder` builds each + // planted URL from the selected region's template, and this asserts the + // bundle was fetched from that same path, or it would plant rows nothing + // asks for. expect( - seed.source, - basemapOriginTileUrl, + Uri.parse(seed.source).path, + Uri.parse(basemapOriginTileUrl(LbRegion.tpe1)).path, reason: - 'the tiles are stored under these URLs; a mismatch plants rows ' + 'the tiles are stored under these paths; a mismatch plants rows ' 'MapLibre never asks for', ); expect(seed.maxZoom, basemapSourceMaxZoom.toInt()); diff --git a/test/shared/map/basemap_seeder_test.dart b/test/shared/map/basemap_seeder_test.dart index 4fa80dbae..83d2b1df9 100644 --- a/test/shared/map/basemap_seeder_test.dart +++ b/test/shared/map/basemap_seeder_test.dart @@ -5,11 +5,13 @@ library; import 'dart:io'; +import 'package:dpip/core/network/api_region.dart'; import 'package:dpip/core/network/etag_cache_store.dart'; import 'package:dpip/core/network/etag_interceptor.dart'; import 'package:dpip/shared/map/basemap_seed.g.dart'; import 'package:dpip/shared/map/basemap_seed_format.dart'; import 'package:dpip/shared/map/basemap_seeder.dart'; +import 'package:dpip/shared/map/map_style.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:sqlite_async/sqlite_async.dart'; @@ -49,7 +51,12 @@ void main() { final allUrls = [ for (final part in seed.parts) for (final tile in part.tiles) - basemapSeedUrl(seed.source, tile.z, tile.x, tile.y), + basemapSeedUrl( + basemapOriginTileUrl(LbRegion.tpe1), + tile.z, + tile.x, + tile.y, + ), ]; final tileCount = allUrls.length; @@ -66,7 +73,8 @@ void main() { tearDown(() async => db.close()); - BasemapSeeder seeder() => BasemapSeeder(store, bundle: bundle); + BasemapSeeder seeder() => + BasemapSeeder(store, region: LbRegion.tpe1, bundle: bundle); test( 'a fresh install plants every bundled tile, one part at a time', @@ -92,7 +100,12 @@ void main() { asset.sublist(tile.offset, tile.offset + tile.length), ); final row = await store.readBytes( - basemapSeedUrl(seed.source, tile.z, tile.x, tile.y), + basemapSeedUrl( + basemapOriginTileUrl(LbRegion.tpe1), + tile.z, + tile.x, + tile.y, + ), ); expect(row?.bytes, expected); expect(row?.etag, etag); @@ -109,7 +122,12 @@ void main() { expect(empty, isNotEmpty, reason: 'open sea at z8–9'); final tile = empty.first; final row = await store.readBytes( - basemapSeedUrl(seed.source, tile.z, tile.x, tile.y), + basemapSeedUrl( + basemapOriginTileUrl(LbRegion.tpe1), + tile.z, + tile.x, + tile.y, + ), ); expect(row?.bytes, isEmpty); }); @@ -152,7 +170,12 @@ void main() { test('a part whose tiles are all downloaded is not even loaded', () async { final first = seed.parts.first; for (final tile in first.tiles) { - final url = basemapSeedUrl(seed.source, tile.z, tile.x, tile.y); + final url = basemapSeedUrl( + basemapOriginTileUrl(LbRegion.tpe1), + tile.z, + tile.x, + tile.y, + ); await store.writeBytes( url, etag: EtagInterceptor.etagFromUrl(Uri.parse(url)), @@ -201,7 +224,12 @@ void main() { expect(report.planted, tileCount - bad.tiles.length); final etags = await store.etagsFor([ for (final tile in bad.tiles) - basemapSeedUrl(seed.source, tile.z, tile.x, tile.y), + basemapSeedUrl( + basemapOriginTileUrl(LbRegion.tpe1), + tile.z, + tile.x, + tile.y, + ), ]); expect(etags, isEmpty); }); diff --git a/test/shared/map/map_gsi_overlay_test.dart b/test/shared/map/map_gsi_overlay_test.dart index 4e7cdce9e..8d4be2c5c 100644 --- a/test/shared/map/map_gsi_overlay_test.dart +++ b/test/shared/map/map_gsi_overlay_test.dart @@ -1,4 +1,5 @@ import 'package:dpip/core/network/api_paths.dart'; +import 'package:dpip/core/network/api_region.dart'; import 'package:dpip/core/network/etag_interceptor.dart'; import 'package:dpip/core/settings/setting_keys.dart'; import 'package:dpip/core/settings/settings_store.dart'; @@ -11,9 +12,11 @@ import '../../features/map/raster_timeline_harness.dart'; void main() { test('OSM source follows the documented endpoint and zoom contract', () { - expect(gsiOriginTileUrl, contains(ApiPaths.mapOsmV1)); - expect(gsiSourceProperties.tiles, [gsiOriginTileUrl]); - expect(gsiSourceProperties.maxzoom, gsiSourceMaxZoom); + expect(gsiOriginTileUrl(LbRegion.tpe1), contains(ApiPaths.mapOsmV1)); + expect(gsiSourceProperties(LbRegion.tpe1).tiles, [ + gsiOriginTileUrl(LbRegion.tpe1), + ]); + expect(gsiSourceProperties(LbRegion.tpe1).maxzoom, gsiSourceMaxZoom); expect(gsiDisplayMaxZoom, greaterThan(gsiSourceMaxZoom)); expect(gsiBounds, [114.28579, 10.32677, 122.3283, 26.43722]); }); @@ -200,6 +203,7 @@ void main() { selection: selection, belowLayerId: townOutlineLayerId, groundBelowLayerId: townFillLayerId, + region: LbRegion.tpe1, ); expect(map.calls.first, 'addSource:$gsiSourceId'); @@ -251,6 +255,7 @@ void main() { selection: selection, belowLayerId: townOutlineLayerId, groundBelowLayerId: townFillLayerId, + region: LbRegion.tpe1, ); for (final layer in gsiStyleLayers(Brightness.dark)) {