diff --git a/client/src/main.tsx b/client/src/main.tsx index 573a80997..1d198abfa 100644 --- a/client/src/main.tsx +++ b/client/src/main.tsx @@ -42,6 +42,7 @@ import { maybeInstallTouchDragPolyfill } from './utils/touchDragPolyfill' import { startConnectivityProbe } from './sync/connectivity' import { startNativeApp } from './native/nativeApp' import { requestPersistentStorage } from './sync/persistentStorage' +import { isIosDevice } from './utils/iosDevice' import ErrorBoundary, { RootErrorFallback } from './components/shared/ErrorBoundary' import { installGlobalErrorHandlers } from './utils/globalErrorHandlers' import { schedulePrecacheRepair } from './utils/serviceWorkerShell' @@ -52,6 +53,9 @@ startConnectivityProbe() startNativeApp() // Keep offline data (map tiles, file blobs, IndexedDB) exempt from eviction. void requestPersistentStorage() +// A tile cache past the iOS budget slows every cold start of the home screen app (#3008). +// Loaded on iOS only, so the prefetcher stays out of everyone's first chunk. +if (isIosDevice()) void import('./sync/tilePrefetcher').then((m) => m.scheduleTileCacheTrim()) // Event handlers and async code never reach a boundary; this is where they land. installGlobalErrorHandlers() // A page the precache keeps under a stylesheet's or a script's name would be diff --git a/client/src/sync/tilePrefetcher.ts b/client/src/sync/tilePrefetcher.ts index 226be9b06..45f3ff0a5 100644 --- a/client/src/sync/tilePrefetcher.ts +++ b/client/src/sync/tilePrefetcher.ts @@ -31,6 +31,7 @@ import { isOfflineForbiddenTemplate, isVectorStyle, normalizeTileUrl, resolveTil import { OFM_DARK, OFM_POSITRON } from '../constants/mapDefaults' import { clearVectorCache, prefetchStyleAssets, prefetchVectorForPlaces } from './glPrefetcher' import { isNativeIos } from '../native/platform' +import { isIosDevice } from '../utils/iosDevice' import { openCacheStorage } from './openCacheStorage' // ── Constants ───────────────────────────────────────────────────────────────── @@ -48,6 +49,21 @@ const AVG_TILE_KB = 15 */ export const MAX_TILES = Math.floor((180 * 1024) / AVG_TILE_KB) // = 12288 +/** + * The tile budget on an iPhone or iPad. WebKit reads the origin's Cache Storage + * before the service worker can answer the app's first request, and that read + * grows with the number of entries: a full cache of 12,288 tiles held a home + * screen app on a black screen for about 8 s on every cold start, about 0.7 ms + * an entry (#3008). 2,048 keeps that near a second and still covers the zooms a + * trip map opens at. + */ +export const IOS_MAX_TILES = 2048 + +/** How many tiles a prefetch may hold here: the iOS budget in Safari and its home screen apps. */ +export function tileBudget(): number { + return isIosDevice() && !isNativeIos() ? IOS_MAX_TILES : MAX_TILES +} + /** * Tile requests in flight at once. * @@ -224,7 +240,7 @@ export function countTiles(bbox: TileBbox, minZoom: number, maxZoom: number): nu for (let z = minZoom; z <= maxZoom; z++) { const { minX, maxX, minY, maxY } = tileRange(bbox, z) total += (maxX - minX + 1) * (maxY - minY + 1) - if (total > MAX_TILES) return total + if (total > tileBudget()) return total } return total } @@ -252,7 +268,7 @@ export function buildTileUrl(template: string, z: number, x: number, y: number, /** * Enumerate the tile coordinates to prefetch, lowest zoom first, stopping at - * the zoom level whose tiles would push the total past MAX_TILES. + * the zoom level whose tiles would push the total past the budget (tileBudget). */ function enumerateTiles( bbox: TileBbox, @@ -260,11 +276,12 @@ function enumerateTiles( maxZoom: number, ): Array<[z: number, x: number, y: number]> { const coords: Array<[number, number, number]> = [] + const budget = tileBudget() for (let z = minZoom; z <= maxZoom; z++) { const { minX, maxX, minY, maxY } = tileRange(bbox, z) - if (coords.length + (maxX - minX + 1) * (maxY - minY + 1) > MAX_TILES) break + if (coords.length + (maxX - minX + 1) * (maxY - minY + 1) > budget) break for (let x = minX; x <= maxX; x++) { for (let y = minY; y <= maxY; y++) coords.push([z, x, y]) @@ -342,6 +359,46 @@ export async function prefetchTiles( return fetched } +const TRIM_KEY = 'trek_tile_trim_at' +const TRIM_EVERY_MS = 24 * 60 * 60 * 1000 + +/** + * Brings a tile cache on an iPhone or iPad back within IOS_MAX_TILES, oldest + * tiles first (Cache Storage lists keys in the order they were stored). The + * service worker's own limit is the same on every platform, so a cache filled + * before this budget, or by browsing, still grows past it there (#3008). + * + * Reading the keys of a large cache is itself slow on iOS, so this runs at most + * once a day and only when called after the app is up. Returns how many tiles + * it removed. + */ +export async function trimTileCacheForIos(now = Date.now()): Promise { + if (!isIosDevice() || isNativeIos()) return 0 + try { + const last = Number(localStorage.getItem(TRIM_KEY) || 0) + if (now - last < TRIM_EVERY_MS) return 0 + localStorage.setItem(TRIM_KEY, String(now)) + } catch { + return 0 + } + const cache = await openTileCache() + if (!cache) return 0 + const keys = await cache.keys() + const surplus = keys.slice(0, Math.max(0, keys.length - IOS_MAX_TILES)) + for (const request of surplus) await cache.delete(request) + return surplus.length +} + +/** Trims the iOS tile cache once the app has started, never in the way of its first screens. */ +export function scheduleTileCacheTrim(delayMs = 15_000): void { + if (!isIosDevice() || isNativeIos()) return + window.setTimeout(() => { + trimTileCacheForIos().catch(() => { + /* Cache Storage unavailable: nothing to trim */ + }) + }, delayMs) +} + /** * Drop the pre-downloaded map-tile cache. Called when the user turns off * "store map tiles offline" (#1135 ask 2) so the bulk tile storage — the real diff --git a/client/tests/unit/sync/tilePrefetcher.test.ts b/client/tests/unit/sync/tilePrefetcher.test.ts index 012fd8d02..01f61cc5d 100644 --- a/client/tests/unit/sync/tilePrefetcher.test.ts +++ b/client/tests/unit/sync/tilePrefetcher.test.ts @@ -19,9 +19,13 @@ import { UNPERSISTED_MAX_ZOOM, clearTileCache, MAX_TILES, + IOS_MAX_TILES, TILE_CONCURRENCY, + tileBudget, + trimTileCacheForIos, type TileBbox, } from '../../../src/sync/tilePrefetcher'; +import { isIosDevice } from '../../../src/utils/iosDevice'; import { offlineDb, clearAll, upsertSyncMeta } from '../../../src/db/offlineDb'; import { requestPersistentStorage, _resetPersistentStorage } from '../../../src/sync/persistentStorage'; import { setAuthed } from '../../../src/sync/authGate'; @@ -37,6 +41,10 @@ vi.mock('../../../src/sync/glPrefetcher', async importOriginal => ({ prefetchVectorForPlaces: vi.fn(async () => ({ tiles: 0, template: null })), prefetchStyleAssets: vi.fn(async () => null), })); +vi.mock('../../../src/utils/iosDevice', async importOriginal => ({ + ...(await importOriginal()), + isIosDevice: vi.fn(() => false), +})); vi.mock('../../../src/native/platform', async importOriginal => ({ ...(await importOriginal()), isNativeIos: vi.fn(() => false), @@ -47,6 +55,7 @@ beforeEach(async () => { setAuthed(true); // restoreAllMocks leaves a vi.fn's return value as a test set it; the iOS case below sets true. vi.mocked(isNativeIos).mockReturnValue(false); + vi.mocked(isIosDevice).mockReturnValue(false); Object.defineProperty(navigator, 'onLine', { value: true, writable: true, configurable: true }); // Stub fetch + serviceWorker so prefetch path is exercised vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: true })); @@ -731,3 +740,50 @@ describe('prefetchTiles: a refused tile is not a cached tile (#2180)', () => { expect(fetched).toBeLessThan(calls); }); }); + +// ── iOS tile budget (#3008) ─────────────────────────────────────────────────── + +describe('the iOS tile budget', () => { + const tileKeys = (n: number) => Array.from({ length: n }, (_, i) => ({ url: `https://tile.example.com/${i}.png` })); + + beforeEach(() => localStorage.clear()); + + it('holds a prefetch on an iPhone or iPad to IOS_MAX_TILES, and nowhere else', () => { + expect(tileBudget()).toBe(MAX_TILES); + vi.mocked(isIosDevice).mockReturnValue(true); + expect(tileBudget()).toBe(IOS_MAX_TILES); + // Inside the iOS app tiles never go through Cache Storage at all. + vi.mocked(isNativeIos).mockReturnValue(true); + expect(tileBudget()).toBe(MAX_TILES); + }); + + it('stops counting a large area at the iOS budget', () => { + vi.mocked(isIosDevice).mockReturnValue(true); + const europe: TileBbox = { minLat: 36, maxLat: 60, minLng: -10, maxLng: 30 }; + const total = countTiles(europe, 0, 16); + expect(total).toBeGreaterThan(IOS_MAX_TILES); + expect(total).toBeLessThan(MAX_TILES); + }); + + it('trims a full cache down to the budget, oldest tiles first, once a day', async () => { + vi.mocked(isIosDevice).mockReturnValue(true); + const keys = tileKeys(IOS_MAX_TILES + 5); + const del = vi.fn().mockResolvedValue(true); + vi.stubGlobal('caches', { open: vi.fn().mockResolvedValue({ keys: vi.fn().mockResolvedValue(keys), delete: del }) }); + + const now = Date.UTC(2026, 10, 8, 12); + expect(await trimTileCacheForIos(now)).toBe(5); + expect(del.mock.calls.map(([k]) => k)).toEqual(keys.slice(0, 5)); + + // Reading a large cache's keys is slow on iOS: not again the same day. + expect(await trimTileCacheForIos(now + 60 * 60 * 1000)).toBe(0); + expect(del).toHaveBeenCalledTimes(5); + }); + + it('leaves the cache alone off iOS', async () => { + const open = vi.fn(); + vi.stubGlobal('caches', { open }); + expect(await trimTileCacheForIos()).toBe(0); + expect(open).not.toHaveBeenCalled(); + }); +});