mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-03 09:38:54 +00:00
fix(offline): raster tiles a GL map fetches get a service worker cache of their own
Leaflet loads a tile as an image without CORS and the prefetch fetches it no-cors, so map-tiles holds opaque answers. A GL map reads tiles with a CORS fetch and cannot use one: once Leaflet had drawn an OpenTopoMap tile, the GL tour layer failed on the same URL, and a MapLibre template would fail the same way on every prefetched tile. A CORS request for a raster preset's tile now goes to map-tiles-gl, which keeps only readable answers, ahead of the Leaflet rules; images and the no-cors prefetch stay in map-tiles. The matcher is written into the service worker by its source text, so its host list is inline, and a test holds it to the hosts the CSP lets a GL map fetch. OpenHikingMap and CyclOSM stay out, their usage policies allow no offline copy. The prefetch takes exactly one way per user: a template MapLibre draws on such a host is fetched with CORS into map-tiles-gl, at the density the map asks for, everything else as before. Clearing offline maps drops both caches, and the iOS trim keeps both within its budget.
This commit is contained in:
@@ -0,0 +1,81 @@
|
||||
/**
|
||||
* The service worker rule for raster tiles a GL map fetches (FE-SYNC-GLTILECACHE-*).
|
||||
*/
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { resolve } from 'node:path';
|
||||
|
||||
import { RASTER_TILE_HOSTS } from '@trek/shared';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { GL_TILE_CACHE, isGlRasterTileRequest } from './glTileCache';
|
||||
import { MAX_TILES } from './tilePrefetcher';
|
||||
|
||||
function ask(match: typeof isGlRasterTileRequest, url: string, mode: RequestMode) {
|
||||
return match({ url: new URL(url), request: { mode } as Request });
|
||||
}
|
||||
|
||||
/** The function as the service worker gets it: its source text, evaluated with nothing around it. */
|
||||
const serialized = new Function(`return (${isGlRasterTileRequest.toString()})`)() as typeof isGlRasterTileRequest;
|
||||
|
||||
describe('isGlRasterTileRequest', () => {
|
||||
it('FE-SYNC-GLTILECACHE-001: takes the CORS fetches of the cached raster presets', () => {
|
||||
for (const url of [
|
||||
'https://a.basemaps.cartocdn.com/light_all/5/16/10@2x.png?key=k',
|
||||
'https://basemaps.cartocdn.com/light_all/5/16/10.png',
|
||||
'https://tile.openstreetmap.org/5/16/10.png',
|
||||
'https://tile.openstreetmap.de/5/16/10.png',
|
||||
'https://tiles.stadiamaps.com/tiles/alidade_smooth/5/16/10.png',
|
||||
// The GL tour layer that broke on Leaflet's opaque copies.
|
||||
'https://b.tile.opentopomap.org/5/16/10.png',
|
||||
]) {
|
||||
expect(ask(isGlRasterTileRequest, url, 'cors'), url).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it("FE-SYNC-GLTILECACHE-002: leaves Leaflet's images and the no-cors prefetch to map-tiles", () => {
|
||||
expect(ask(isGlRasterTileRequest, 'https://tile.openstreetmap.de/5/16/10.png', 'no-cors')).toBe(false);
|
||||
expect(ask(isGlRasterTileRequest, 'https://tile.openstreetmap.de/5/16/10.png', 'same-origin')).toBe(false);
|
||||
});
|
||||
|
||||
it('FE-SYNC-GLTILECACHE-003: never a host whose policy forbids an offline copy, a GCJ-02 host or a look-alike', () => {
|
||||
for (const url of [
|
||||
'https://tile.openmaps.fr/openhikingmap/5/16/10.png',
|
||||
'https://a.tile-cyclosm.openstreetmap.fr/cyclosm/5/16/10.png',
|
||||
'https://webrd01.is.autonavi.com/appmaptile?x=1&y=2&z=3',
|
||||
'https://tile.openstreetmap.de.example.com/5/16/10.png',
|
||||
'http://tile.openstreetmap.de/5/16/10.png',
|
||||
]) {
|
||||
expect(ask(isGlRasterTileRequest, url, 'cors'), url).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
it('FE-SYNC-GLTILECACHE-004: reaches nothing outside its body, so the copy in the service worker matches alike', () => {
|
||||
for (const url of ['https://tile.openstreetmap.de/5/16/10.png', 'https://tile.openmaps.fr/x/5/16/10.png']) {
|
||||
for (const mode of ['cors', 'no-cors'] as const) {
|
||||
expect(ask(serialized, url, mode)).toBe(ask(isGlRasterTileRequest, url, mode));
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it('FE-SYNC-GLTILECACHE-005: every host in the inline list is one the CSP lets a GL map fetch', () => {
|
||||
const inline = [...isGlRasterTileRequest.toString().matchAll(/'([^']+\.[a-z]+)'/g)].map((m) => m[1]);
|
||||
expect(inline.length).toBeGreaterThan(0);
|
||||
for (const host of inline) expect(RASTER_TILE_HOSTS, host).toContain(host);
|
||||
});
|
||||
});
|
||||
|
||||
describe('the map-tiles-gl rule in vite.config.js', () => {
|
||||
const config = readFileSync(resolve(process.cwd(), 'vite.config.js'), 'utf8');
|
||||
const rule = /urlPattern: isGlRasterTileRequest,[\s\S]*?cacheableResponse: \{ statuses: \[200\] \}/.exec(config)?.[0];
|
||||
|
||||
it('FE-SYNC-GLTILECACHE-006: keeps only readable answers, as many as the prefetch budget', () => {
|
||||
expect(GL_TILE_CACHE).toBe('map-tiles-gl');
|
||||
expect(rule).toBeDefined();
|
||||
expect(rule).toContain('cacheName: GL_TILE_CACHE');
|
||||
expect(rule).toContain(`maxEntries: ${MAX_TILES}`);
|
||||
});
|
||||
|
||||
it('FE-SYNC-GLTILECACHE-007: comes before the Leaflet rules for the same hosts, since the first match wins', () => {
|
||||
expect(config.indexOf('urlPattern: isGlRasterTileRequest')).toBeLessThan(config.indexOf('basemaps\\.cartocdn'));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,40 @@
|
||||
/**
|
||||
* The service worker cache for raster tiles a GL map fetches.
|
||||
*
|
||||
* Leaflet loads a tile as an `<img>` without CORS, and the offline prefetch
|
||||
* fetches tiles `no-cors` the same way, so `map-tiles` holds opaque responses.
|
||||
* A GL map reads a tile with a CORS fetch and cannot use an opaque answer: with
|
||||
* one in the cache under the same URL, every such tile failed, which is what
|
||||
* broke the OpenTopoMap layer of the GL tour maps once Leaflet had drawn it.
|
||||
* So a CORS request for a raster tile goes into a cache of its own that keeps
|
||||
* only readable answers, and Leaflet's requests stay where they were.
|
||||
*
|
||||
* The hosts are the raster presets whose tiles `map-tiles` keeps for Leaflet
|
||||
* (vite.config.js), apart from Amap, whose GCJ-02 tiles a GL map never draws.
|
||||
* OpenHikingMap and CyclOSM are left out on purpose: their usage policies allow
|
||||
* no offline copy, which is why `map-tiles` has no rule for them either.
|
||||
*/
|
||||
|
||||
/** Cache Storage name; vite.config.js names it in its rule, the prefetcher writes and clears it. */
|
||||
export const GL_TILE_CACHE = 'map-tiles-gl';
|
||||
|
||||
/**
|
||||
* Workbox `urlPattern` for that cache. Workbox writes this function into the
|
||||
* service worker by its source text, so it must not reach anything outside its
|
||||
* own body: the host list stays inline.
|
||||
*/
|
||||
export function isGlRasterTileRequest({ url, request }: { url: URL; request: Request }): boolean {
|
||||
if (request.mode !== 'cors' || url.protocol !== 'https:') return false;
|
||||
const hosts = [
|
||||
'basemaps.cartocdn.com',
|
||||
'*.basemaps.cartocdn.com',
|
||||
'tile.openstreetmap.org',
|
||||
'*.tile.openstreetmap.org',
|
||||
'tile.openstreetmap.de',
|
||||
'tiles.stadiamaps.com',
|
||||
'tile.opentopomap.org',
|
||||
'*.tile.opentopomap.org',
|
||||
];
|
||||
const host = url.hostname.toLowerCase();
|
||||
return hosts.some((entry) => (entry.startsWith('*.') ? host.endsWith(entry.slice(1)) : host === entry));
|
||||
}
|
||||
@@ -33,6 +33,9 @@ import { clearVectorCache, prefetchStyleAssets, prefetchVectorForPlaces } from '
|
||||
import { isNativeIos } from '../native/platform'
|
||||
import { isIosDevice } from '../utils/iosDevice'
|
||||
import { openCacheStorage } from './openCacheStorage'
|
||||
import { GL_TILE_CACHE, isGlRasterTileRequest } from './glTileCache'
|
||||
import { useSettingsStore } from '../store/settingsStore'
|
||||
import { MAPLIBRE_FROM_TEMPLATE } from '@trek/shared'
|
||||
|
||||
// ── Constants ─────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -292,8 +295,37 @@ function enumerateTiles(
|
||||
}
|
||||
|
||||
/** Open the tile cache, or null where Cache Storage isn't available. */
|
||||
async function openTileCache(): Promise<Cache | null> {
|
||||
return openCacheStorage(TILE_CACHE)
|
||||
async function openTileCache(cacheName: string = TILE_CACHE): Promise<Cache | null> {
|
||||
return openCacheStorage(cacheName)
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the user's map fetches this template as a GL map: MapLibre drawing it
|
||||
* through the `trek:template` keyword, from a host whose CORS answers the
|
||||
* service worker keeps (glTileCache.ts). Such tiles are fetched with CORS into
|
||||
* map-tiles-gl, every other template as Leaflet's images into map-tiles, never
|
||||
* both, so a trip's tiles count once against the one budget.
|
||||
*/
|
||||
function fetchedAsGl(template: string): boolean {
|
||||
const { map_provider: provider, maplibre_style: style } = useSettingsStore.getState().settings
|
||||
if (provider !== 'maplibre-gl' || style !== MAPLIBRE_FROM_TEMPLATE) return false
|
||||
try {
|
||||
const url = new URL(template.replace(/\{s\}/g, 'a'))
|
||||
// The service worker's own matcher, asked about a CORS request for this host.
|
||||
return isGlRasterTileRequest({ url, request: { mode: 'cors' } as Request })
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The URL a GL map requests for a tile: Leaflet's shard, since both pick it by
|
||||
* (x + y) modulo the shard count, and `{r}` as `@2x` on a dense screen, as the
|
||||
* map's raster style decides it (components/Map/basemapSpec.ts).
|
||||
*/
|
||||
function buildGlTileUrl(template: string, z: number, x: number, y: number, cartoKey?: string): string {
|
||||
const retina = typeof window !== 'undefined' && window.devicePixelRatio > 1
|
||||
return buildTileUrl(template.replace('{r}', retina ? '@2x' : ''), z, x, y, cartoKey)
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -325,10 +357,11 @@ export async function prefetchTiles(
|
||||
const coords = enumerateTiles(bbox, minZoom, maxZoom)
|
||||
if (coords.length === 0) return 0
|
||||
|
||||
const gl = fetchedAsGl(tileUrlTemplate)
|
||||
// Checking Cache Storage from here is far cheaper than letting the request
|
||||
// reach the SW's CacheFirst handler, so a resumed or repeated prefetch over a
|
||||
// warm cache costs almost nothing.
|
||||
const cache = await openTileCache()
|
||||
const cache = await openTileCache(gl ? GL_TILE_CACHE : TILE_CACHE)
|
||||
|
||||
let cursor = 0
|
||||
let fetched = 0
|
||||
@@ -339,7 +372,7 @@ export async function prefetchTiles(
|
||||
if (!navigator.onLine || !isAuthed()) return
|
||||
|
||||
const [z, x, y] = coords[cursor++]
|
||||
const url = buildTileUrl(tileUrlTemplate, z, x, y, cartoKey)
|
||||
const url = (gl ? buildGlTileUrl : buildTileUrl)(tileUrlTemplate, z, x, y, cartoKey)
|
||||
|
||||
if (cache && (await cache.match(url))) continue
|
||||
|
||||
@@ -347,7 +380,7 @@ export async function prefetchTiles(
|
||||
// refusal, a provider that is down, DNS) leaves nothing in the cache and
|
||||
// must not count towards the tally the caller logs as tiles cached: that
|
||||
// is what let a fully blocked prefetch still report success (#2180).
|
||||
const reached = await fetch(url, { mode: 'no-cors' }).then(() => true, () => false)
|
||||
const reached = await fetch(url, { mode: gl ? 'cors' : 'no-cors' }).then(() => true, () => false)
|
||||
if (reached) fetched++
|
||||
}
|
||||
}
|
||||
@@ -382,12 +415,17 @@ export async function trimTileCacheForIos(now = Date.now()): Promise<number> {
|
||||
return 0
|
||||
}
|
||||
try {
|
||||
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
|
||||
// Both tile caches: a template MapLibre draws fills map-tiles-gl instead.
|
||||
let removed = 0
|
||||
for (const name of [TILE_CACHE, GL_TILE_CACHE]) {
|
||||
const cache = await openTileCache(name)
|
||||
if (!cache) continue
|
||||
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)
|
||||
removed += surplus.length
|
||||
}
|
||||
return removed
|
||||
} catch {
|
||||
// Cache Storage refused: the tiles stay as they are and tomorrow tries again.
|
||||
return 0
|
||||
@@ -409,7 +447,10 @@ export function scheduleTileCacheTrim(delayMs = 15_000): void {
|
||||
*/
|
||||
export async function clearTileCache(): Promise<void> {
|
||||
try {
|
||||
if (typeof caches !== 'undefined') await caches.delete(TILE_CACHE)
|
||||
if (typeof caches !== 'undefined') {
|
||||
await caches.delete(TILE_CACHE)
|
||||
await caches.delete(GL_TILE_CACHE)
|
||||
}
|
||||
} catch {
|
||||
/* Cache Storage unavailable (no SW / private mode) — nothing to clear */
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user