Colota - Android GPS Location tracker
fix(map): stop offline area bounds being lost on a failed read (#644)
Max Dietrichc83b8b1a82d4
diff --git a/apps/mobile/src/components/features/map/OfflinePackManager.ts b/apps/mobile/src/components/features/map/OfflinePackManager.tsindex f816580d..febeb81f 100644--- a/apps/mobile/src/components/features/map/OfflinePackManager.ts+++ b/apps/mobile/src/components/features/map/OfflinePackManager.ts@@ -6,6 +6,8 @@import { OfflineManager, type OfflinePack } from "@maplibre/maplibre-react-native"import { MAP_STYLE_URL_LIGHT as MAP_STYLE_URL } from "../../../constants"import NativeLocationService from "../../../services/NativeLocationService"+import { logger } from "../../../utils/logger"+import { formatBytes } from "../../../utils/format"const MIN_ZOOM = 8const MAX_ZOOM = 14 // mxd.codes / OpenFreeMap caps vector tiles at z14@@ -116,6 +118,8 @@ export async function createOfflinePack(OfflineManager.setTileCountLimit(TILE_COUNT_LIMIT)+ logger.info(`[OfflinePackManager] Downloading '${name}': z${MIN_ZOOM}-${MAX_ZOOM}, ${estimateSizeLabel(ne, sw)}`)+await OfflineManager.createPack({mapStyle,@@ -124,7 +128,14 @@ export async function createOfflinePack(bounds: [sw[0], sw[1], ne[0], ne[1]],metadata: { name }},- (_pack, status) => onProgress(status as OfflinePackStatus),+ (_pack, status) => {+ const s = status as OfflinePackStatus+ // Progress fires continuously, so only the terminal state is worth a line.+ if (s.state === DOWNLOAD_STATE.COMPLETE) {+ logger.info(`[OfflinePackManager] Download complete: '${name}', ${formatBytes(s.completedResourceSize ?? 0)}`)+ }+ onProgress(s)+ },(_pack, err) => onError(err))}@@ -144,7 +155,8 @@ export async function loadOfflineAreas(): Promise<OfflineAreaInfo[]> {isComplete: status?.state === DOWNLOAD_STATE.COMPLETE,isActive: status?.state === DOWNLOAD_STATE.ACTIVE}- } catch {+ } catch (err) {+ logger.warn(`[OfflinePackManager] Status unreadable for pack '${name}':`, err)return { name, sizeBytes: null, isComplete: false, isActive: false }}})@@ -163,6 +175,9 @@ export async function deleteOfflineArea(name: string): Promise<void> {// pack may already be inactive - proceed to delete}await OfflineManager.deletePack(pack.id)+ logger.info(`[OfflinePackManager] Deleted offline area '${name}'`)+ } else {+ logger.debug(`[OfflinePackManager] No pack named '${name}' to delete`)}// SQLite does not shrink the database file when rows are deleted - freed pages@@ -170,6 +185,7 @@ export async function deleteOfflineArea(name: string): Promise<void> {// reset the database so the OS reclaims the storage space.const remaining = await OfflineManager.getPacks()if (remaining.length === 0) {+ logger.info("[OfflinePackManager] Last area removed, resetting the tile database to reclaim space")await OfflineManager.resetDatabase()}}@@ -193,33 +209,64 @@ export interface OfflineAreaBounds {downloadedAt?: number // Unix ms timestamp set when download starts}+/** Reads the stored list. Throws when it cannot be read, so a writer can tell empty from failed. */+async function readOfflineAreaBoundsOrThrow(): Promise<OfflineAreaBounds[]> {+ // A rejection here means the value is intact but unreachable, so a writer must not overwrite it.+ const json = await NativeLocationService.getSetting(BOUNDS_KEY, "[]")++ let parsed: unknown[]+ try {+ parsed = JSON.parse(json ?? "[]") as unknown[]+ } catch (err) {+ // Unrecoverable either way, so refusing would leave the key unwritable for good. Repair it.+ logger.warn("[OfflinePackManager] Stored area bounds are malformed, starting a fresh list:", err)+ return []+ }+ // Filter out entries from the old schema (lat/lon/radiusMeters) that lack ne/sw+ return parsed.filter(+ (b): b is OfflineAreaBounds =>+ typeof b === "object" &&+ b !== null &&+ "ne" in b &&+ "sw" in b &&+ Array.isArray((b as OfflineAreaBounds).ne) &&+ Array.isArray((b as OfflineAreaBounds).sw)+ )+}++/** Display path: an unreadable list shows as empty, since there is nothing to render either way. */export async function loadOfflineAreaBounds(): Promise<OfflineAreaBounds[]> {try {- const json = await NativeLocationService.getSetting(BOUNDS_KEY, "[]")- const parsed = JSON.parse(json ?? "[]") as unknown[]- // Filter out entries from the old schema (lat/lon/radiusMeters) that lack ne/sw- return parsed.filter(- (b): b is OfflineAreaBounds =>- typeof b === "object" &&- b !== null &&- "ne" in b &&- "sw" in b &&- Array.isArray((b as OfflineAreaBounds).ne) &&- Array.isArray((b as OfflineAreaBounds).sw)- )- } catch {+ return await readOfflineAreaBoundsOrThrow()+ } catch (err) {+ logger.error("[OfflinePackManager] Failed to read saved area bounds:", err)return []}}export async function saveOfflineAreaBounds(entry: OfflineAreaBounds): Promise<void> {- const existing = await loadOfflineAreaBounds()+ let existing: OfflineAreaBounds[]+ try {+ existing = await readOfflineAreaBoundsOrThrow()+ } catch (err) {+ logger.error(+ `[OfflinePackManager] Not saving bounds for '${entry.name}': stored list unreadable, so the area will not be re-downloadable after a restart:`,+ err+ )+ return+ }const updated = [...existing.filter((b) => b.name !== entry.name), entry]await NativeLocationService.saveSetting(BOUNDS_KEY, JSON.stringify(updated))}export async function removeOfflineAreaBounds(name: string): Promise<void> {- const existing = await loadOfflineAreaBounds()+ let existing: OfflineAreaBounds[]+ try {+ existing = await readOfflineAreaBoundsOrThrow()+ } catch (err) {+ logger.error(`[OfflinePackManager] Not removing bounds for '${name}', stored list unreadable:`, err)+ return+ }const updated = existing.filter((b) => b.name !== name)await NativeLocationService.saveSetting(BOUNDS_KEY, JSON.stringify(updated))}diff --git a/apps/mobile/src/components/features/map/__tests__/OfflinePackManager.test.ts b/apps/mobile/src/components/features/map/__tests__/OfflinePackManager.test.tsindex 68e08535..e08be548 100644--- a/apps/mobile/src/components/features/map/__tests__/OfflinePackManager.test.ts+++ b/apps/mobile/src/components/features/map/__tests__/OfflinePackManager.test.ts@@ -500,6 +500,28 @@ describe("saveOfflineAreaBounds", () => {expect(mockSaveSetting).toHaveBeenCalledWith("offline_area_bounds", expect.any(String))})++ it("does not write when the stored list cannot be read", async () => {+ // Both writers rebuild the whole list, so one built on a failed read persists the new entry+ // and drops every other area.+ mockGetSetting.mockRejectedValueOnce(new Error("db error"))++ await saveOfflineAreaBounds({ name: "new", ne: [0.1, 0.1], sw: [-0.1, -0.1] })++ expect(mockSaveSetting).not.toHaveBeenCalled()+ })++ it("repairs the stored list when it is malformed rather than refusing forever", async () => {+ // Only an unreachable read blocks the write. Malformed input is repaired, not refused.+ mockGetSetting.mockResolvedValueOnce("{invalid json")++ await saveOfflineAreaBounds({ name: "new", ne: [0.1, 0.1], sw: [-0.1, -0.1] })++ expect(mockSaveSetting).toHaveBeenCalledWith(+ "offline_area_bounds",+ JSON.stringify([{ name: "new", ne: [0.1, 0.1], sw: [-0.1, -0.1] }])+ )+ })})// ============================================================================@@ -542,4 +564,12 @@ describe("removeOfflineAreaBounds", () => {expect(JSON.parse(mockSaveSetting.mock.calls[0][1])).toEqual([])})+ it("does not write when the stored list cannot be read", async () => {+ // A failed read here would otherwise save [], wiping every area rather than the named one.+ mockGetSetting.mockRejectedValueOnce(new Error("db error"))++ await removeOfflineAreaBounds("home")++ expect(mockSaveSetting).not.toHaveBeenCalled()+ })})diff --git a/apps/mobile/src/screens/OfflineMapsScreen.tsx b/apps/mobile/src/screens/OfflineMapsScreen.tsxindex 418fa99c..54ed3ac3 100644--- a/apps/mobile/src/screens/OfflineMapsScreen.tsx+++ b/apps/mobile/src/screens/OfflineMapsScreen.tsx@@ -343,7 +343,19 @@ export function OfflineMapsScreen({}: ScreenProps) {activePackNameRef.current = nameconst attempt = (retriesLeft: number) => {+ let tileErrors = 0+ let lastTileError: unknown = null+ const reportTileErrors = () => {+ if (tileErrors === 0) return+ logger.warn(+ `[OfflineMapsScreen] ${tileErrors} tile error(s) total downloading '${name}', last:`,+ lastTileError+ )+ tileErrors = 0+ }+const onFailure = (message: string) => {+ reportTileErrors()if (retriesLeft > 0) {const attempt_num = MAX_RETRIES - retriesLeft + 1logger.warn(`[OfflineMapsScreen] Download failed, retrying (${attempt_num}/${MAX_RETRIES})...`)@@ -373,6 +385,7 @@ export function OfflineMapsScreen({}: ScreenProps) {setDownloadProgress(status)setDownloadError(null)if (status.state === DOWNLOAD_STATE.COMPLETE) {+ reportTileErrors()activePackNameRef.current = nullsetDownloading(false)setDownloadBounds(null)@@ -381,11 +394,15 @@ export function OfflineMapsScreen({}: ScreenProps) {}},(err: unknown) => {- logger.warn("[OfflineMapsScreen] Tile error (may retry):", err)+ tileErrors += 1+ lastTileError = err+ if (tileErrors === 1) logger.warn(`[OfflineMapsScreen] Tile error downloading '${name}':`, err)}).catch(() => {onFailure("Failed to start download. Please try again.")- deleteOfflineArea(name).catch(() => {})+ deleteOfflineArea(name).catch((err) => {+ logger.error(`[OfflineMapsScreen] Failed to clean up pack '${name}':`, err)+ })})}diff --git a/apps/mobile/src/screens/__tests__/OfflineMapsScreen.test.tsx b/apps/mobile/src/screens/__tests__/OfflineMapsScreen.test.tsxindex b2e1393b..fa7462f8 100644--- a/apps/mobile/src/screens/__tests__/OfflineMapsScreen.test.tsx+++ b/apps/mobile/src/screens/__tests__/OfflineMapsScreen.test.tsx@@ -4,8 +4,9 @@*/import React from "react"-import { render, fireEvent, waitFor } from "@testing-library/react-native"+import { render, fireEvent, waitFor, act } from "@testing-library/react-native"import { OfflineMapsScreen } from "../OfflineMapsScreen"+import { logger } from "../../utils/logger"// --- MapLibre ---jest.mock("@maplibre/maplibre-react-native", () => ({@@ -262,6 +263,31 @@ describe("OfflineMapsScreen", () => {})})+ it("logs the first tile error and then only a total, not one line per tile", async () => {+ // One line up front so a stalled download is not silent, one total at the end.+ const warn = jest.spyOn(logger, "warn").mockImplementation(() => {})+ mockShowConfirm.mockResolvedValue(true)+ const { findByText, getByTestId, getByPlaceholderText } = renderScreen()+ await waitForMapReady(findByText)+ fireEvent.changeText(getByPlaceholderText("Home area, Trail..."), "flooded")+ fireEvent.press(getByTestId("download-btn"))+ await waitFor(() => expect(mockCreateOfflinePack).toHaveBeenCalled())++ const [, , , onProgress, onError] = mockCreateOfflinePack.mock.calls[0]+ for (let i = 0; i < 50; i++) onError({ message: "HTTP status code 429" })++ const tileLines = () => warn.mock.calls.filter((c) => String(c[0]).includes("Tile error"))+ expect(tileLines()).toHaveLength(1)++ await act(async () => {+ onProgress({ state: "complete", percentage: 100, completedResourceSize: 1000 })+ })++ const totals = warn.mock.calls.filter((c) => String(c[0]).includes("50 tile error(s) total"))+ expect(totals).toHaveLength(1)+ warn.mockRestore()+ })+it("does not call createOfflinePack when user cancels the confirmation", async () => {mockShowConfirm.mockResolvedValue(false)const { findByText, getByTestId, getByPlaceholderText } = renderScreen()diff --git a/fastlane/metadata/android/en-US/changelogs/48.txt b/fastlane/metadata/android/en-US/changelogs/48.txtindex 0d082afd..dc385c9b 100644--- a/fastlane/metadata/android/en-US/changelogs/48.txt+++ b/fastlane/metadata/android/en-US/changelogs/48.txt@@ -9,3 +9,4 @@- A local server that moves off your network is no longer trusted for unencrypted uploads- The location privacy indicator no longer lights up when GPS is not running- Subscribe to new releases with the RSS feed at colota.app/releases.xml+- Downloaded offline map areas no longer lose their saved extents when the stored list cannot be read