362 lines
11 KiB
JavaScript
362 lines
11 KiB
JavaScript
import { EtagMismatch } from "pmtiles";
|
|
|
|
const BOUNDARY_CACHE_DB_NAME = "planet-earth-boundary-cache";
|
|
const BOUNDARY_CACHE_DB_VERSION = 1;
|
|
const META_STORE = "meta";
|
|
const RANGE_STORE = "ranges";
|
|
const ACTIVE_VERSION_KEY = "activeAssetVersion";
|
|
const DEFAULT_MAX_CACHE_BYTES = 80 * 1024 * 1024;
|
|
const PRUNE_TARGET_RATIO = 0.8;
|
|
|
|
let _dbPromise = null;
|
|
|
|
function openBoundaryCacheDb() {
|
|
if (typeof indexedDB === "undefined") {
|
|
return Promise.resolve(null);
|
|
}
|
|
if (_dbPromise) return _dbPromise;
|
|
_dbPromise = new Promise((resolve) => {
|
|
try {
|
|
const request = indexedDB.open(BOUNDARY_CACHE_DB_NAME, BOUNDARY_CACHE_DB_VERSION);
|
|
request.onupgradeneeded = () => {
|
|
const db = request.result;
|
|
if (!db.objectStoreNames.contains(META_STORE)) {
|
|
db.createObjectStore(META_STORE);
|
|
}
|
|
if (!db.objectStoreNames.contains(RANGE_STORE)) {
|
|
const store = db.createObjectStore(RANGE_STORE, { keyPath: "key" });
|
|
store.createIndex("lastUsed", "lastUsed", { unique: false });
|
|
store.createIndex("assetVersion", "assetVersion", { unique: false });
|
|
}
|
|
};
|
|
request.onsuccess = () => resolve(request.result);
|
|
request.onerror = () => {
|
|
_dbPromise = null;
|
|
resolve(null);
|
|
};
|
|
} catch {
|
|
_dbPromise = null;
|
|
resolve(null);
|
|
}
|
|
});
|
|
return _dbPromise;
|
|
}
|
|
|
|
function idbGet(store, key) {
|
|
return new Promise((resolve) => {
|
|
try {
|
|
const req = store.get(key);
|
|
req.onsuccess = () => resolve(req.result ?? null);
|
|
req.onerror = () => resolve(null);
|
|
} catch {
|
|
resolve(null);
|
|
}
|
|
});
|
|
}
|
|
|
|
function txDone(tx) {
|
|
return new Promise((resolve) => {
|
|
tx.oncomplete = () => resolve(true);
|
|
tx.onerror = () => resolve(false);
|
|
tx.onabort = () => resolve(false);
|
|
});
|
|
}
|
|
|
|
export async function syncBoundaryCacheVersion(assetVersion) {
|
|
const version = String(assetVersion || "").trim();
|
|
if (!version) return false;
|
|
const db = await openBoundaryCacheDb();
|
|
if (!db) return false;
|
|
|
|
try {
|
|
const readTx = db.transaction(META_STORE, "readonly");
|
|
const active = await idbGet(readTx.objectStore(META_STORE), ACTIVE_VERSION_KEY);
|
|
if (active === version) return true;
|
|
|
|
const writeTx = db.transaction([META_STORE, RANGE_STORE], "readwrite");
|
|
const metaStore = writeTx.objectStore(META_STORE);
|
|
const rangeStore = writeTx.objectStore(RANGE_STORE);
|
|
metaStore.clear();
|
|
metaStore.put(version, ACTIVE_VERSION_KEY);
|
|
rangeStore.clear();
|
|
await txDone(writeTx);
|
|
return true;
|
|
} catch {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
export async function readHoverIndexCache(assetVersion) {
|
|
const version = String(assetVersion || "").trim();
|
|
if (!version) return null;
|
|
const db = await openBoundaryCacheDb();
|
|
if (!db) return null;
|
|
try {
|
|
const tx = db.transaction(META_STORE, "readonly");
|
|
const entry = await idbGet(tx.objectStore(META_STORE), `hoverIndex:${version}`);
|
|
return entry && typeof entry === "object" && Array.isArray(entry.features) ? entry : null;
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
export async function writeHoverIndexCache(assetVersion, payload) {
|
|
const version = String(assetVersion || "").trim();
|
|
if (!version || !payload || typeof payload !== "object") return false;
|
|
const db = await openBoundaryCacheDb();
|
|
if (!db) return false;
|
|
try {
|
|
const tx = db.transaction(META_STORE, "readwrite");
|
|
tx.objectStore(META_STORE).put(payload, `hoverIndex:${version}`);
|
|
return await txDone(tx);
|
|
} catch {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
export async function readGeoLabelsCache(assetVersion) {
|
|
const version = String(assetVersion || "").trim();
|
|
if (!version) return null;
|
|
const db = await openBoundaryCacheDb();
|
|
if (!db) return null;
|
|
try {
|
|
const tx = db.transaction(META_STORE, "readonly");
|
|
const entry = await idbGet(tx.objectStore(META_STORE), `geoLabels:${version}`);
|
|
return entry && typeof entry === "object" && Array.isArray(entry.places) ? entry : null;
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
export async function writeGeoLabelsCache(assetVersion, payload) {
|
|
const version = String(assetVersion || "").trim();
|
|
if (!version || !payload || typeof payload !== "object") return false;
|
|
const db = await openBoundaryCacheDb();
|
|
if (!db) return false;
|
|
try {
|
|
const tx = db.transaction(META_STORE, "readwrite");
|
|
tx.objectStore(META_STORE).put(payload, `geoLabels:${version}`);
|
|
return await txDone(tx);
|
|
} catch {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
let _pendingPrune = null;
|
|
|
|
async function pruneRangeCacheIfNeeded(db, maxBytes = DEFAULT_MAX_CACHE_BYTES) {
|
|
if (_pendingPrune) return _pendingPrune;
|
|
_pendingPrune = (async () => {
|
|
try {
|
|
const tx = db.transaction(RANGE_STORE, "readonly");
|
|
const store = tx.objectStore(RANGE_STORE);
|
|
const index = store.index("lastUsed");
|
|
const entries = [];
|
|
let totalBytes = 0;
|
|
|
|
await new Promise((resolve) => {
|
|
const cursorReq = index.openCursor();
|
|
cursorReq.onsuccess = () => {
|
|
const cursor = cursorReq.result;
|
|
if (!cursor) {
|
|
resolve();
|
|
return;
|
|
}
|
|
const val = cursor.value;
|
|
const bytes = Number(val?.byteLength) || val?.data?.byteLength || 0;
|
|
totalBytes += bytes;
|
|
entries.push({ key: val.key, bytes });
|
|
cursor.continue();
|
|
};
|
|
cursorReq.onerror = () => resolve();
|
|
});
|
|
|
|
if (totalBytes <= maxBytes) return;
|
|
const targetBytes = Math.floor(maxBytes * PRUNE_TARGET_RATIO);
|
|
const writeTx = db.transaction(RANGE_STORE, "readwrite");
|
|
const writeStore = writeTx.objectStore(RANGE_STORE);
|
|
for (const item of entries) {
|
|
if (totalBytes <= targetBytes) break;
|
|
writeStore.delete(item.key);
|
|
totalBytes -= item.bytes;
|
|
}
|
|
await txDone(writeTx);
|
|
} catch {
|
|
// Cache pruning failures never block rendering.
|
|
} finally {
|
|
_pendingPrune = null;
|
|
}
|
|
})();
|
|
return _pendingPrune;
|
|
}
|
|
|
|
async function readCachedRange(assetVersion, offset, length, expectedEtag) {
|
|
const db = await openBoundaryCacheDb();
|
|
if (!db) return null;
|
|
const key = `${assetVersion}|${offset}|${length}`;
|
|
try {
|
|
const tx = db.transaction(RANGE_STORE, "readonly");
|
|
const entry = await idbGet(tx.objectStore(RANGE_STORE), key);
|
|
if (!entry || !(entry.data instanceof ArrayBuffer)) return null;
|
|
if (expectedEtag && entry.etag && entry.etag !== expectedEtag) return null;
|
|
|
|
// Best-effort LRU timestamp refresh without blocking cache hit return.
|
|
try {
|
|
const touchTx = db.transaction(RANGE_STORE, "readwrite");
|
|
touchTx.objectStore(RANGE_STORE).put({
|
|
...entry,
|
|
lastUsed: Date.now(),
|
|
});
|
|
} catch {
|
|
// Ignore touch failures in restricted browsing modes.
|
|
}
|
|
|
|
return {
|
|
data: entry.data.slice(0),
|
|
etag: entry.etag || undefined,
|
|
};
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
async function writeCachedRange(assetVersion, offset, length, data, etag, maxCacheBytes) {
|
|
if (!assetVersion || !(data instanceof ArrayBuffer)) return;
|
|
const db = await openBoundaryCacheDb();
|
|
if (!db) return;
|
|
const key = `${assetVersion}|${offset}|${length}`;
|
|
try {
|
|
const tx = db.transaction(RANGE_STORE, "readwrite");
|
|
tx.objectStore(RANGE_STORE).put({
|
|
key,
|
|
assetVersion,
|
|
data: data.slice(0),
|
|
etag: etag || null,
|
|
byteLength: data.byteLength,
|
|
lastUsed: Date.now(),
|
|
});
|
|
await txDone(tx);
|
|
void pruneRangeCacheIfNeeded(db, maxCacheBytes);
|
|
} catch {
|
|
// Quota errors leave runtime functioning purely in memory.
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Persistent IndexedDB-backed PMTiles Source.
|
|
* Uses `cache: "force-cache"` instead of pmtiles's default FetchSource (which forces
|
|
* `cache: "no-store"` on Windows Chromium/Electron) so immutable Range tiles survive
|
|
* reloads and desktop restarts with zero redundant network requests.
|
|
*/
|
|
export class IndexedDbPmtilesSource {
|
|
constructor(url, assetVersion = "", { fetchImpl = null, maxCacheBytes = DEFAULT_MAX_CACHE_BYTES } = {}) {
|
|
this.url = url;
|
|
this.assetVersion = String(assetVersion || url || "");
|
|
this.fetchImpl = fetchImpl || ((input, init) => fetch(input, init));
|
|
this.maxCacheBytes = maxCacheBytes;
|
|
this.mustReload = false;
|
|
}
|
|
|
|
getKey() {
|
|
return this.url;
|
|
}
|
|
|
|
async getBytes(offset, length, signal, etag) {
|
|
const cached = await readCachedRange(this.assetVersion, offset, length, etag);
|
|
if (cached) {
|
|
return cached;
|
|
}
|
|
|
|
let controller = null;
|
|
let activeSignal = signal;
|
|
if (!activeSignal && typeof AbortController !== "undefined") {
|
|
controller = new AbortController();
|
|
activeSignal = controller.signal;
|
|
}
|
|
|
|
const headers = new Headers();
|
|
headers.set("range", `bytes=${offset}-${offset + length - 1}`);
|
|
const cacheMode = this.mustReload ? "reload" : "force-cache";
|
|
|
|
let resp = await this.fetchImpl(this.url, {
|
|
signal: activeSignal,
|
|
cache: cacheMode,
|
|
headers,
|
|
credentials: "same-origin",
|
|
});
|
|
|
|
if (offset === 0 && resp.status === 416) {
|
|
const contentRange = resp.headers.get("Content-Range");
|
|
if (!contentRange || !contentRange.startsWith("bytes */")) {
|
|
throw new Error("Missing content-length on 416 response");
|
|
}
|
|
const totalSize = Number(contentRange.slice(8));
|
|
headers.set("range", `bytes=0-${totalSize - 1}`);
|
|
resp = await this.fetchImpl(this.url, {
|
|
signal: activeSignal,
|
|
cache: "reload",
|
|
headers,
|
|
credentials: "same-origin",
|
|
});
|
|
}
|
|
|
|
let respEtag = resp.headers.get("Etag");
|
|
if (respEtag && respEtag.startsWith("W/")) {
|
|
respEtag = null;
|
|
}
|
|
if (resp.status === 416 || (etag && respEtag && respEtag !== etag)) {
|
|
this.mustReload = true;
|
|
throw new EtagMismatch(
|
|
`Server returned non-matching ETag ${etag} after one retry.`,
|
|
);
|
|
}
|
|
if (resp.status >= 300) {
|
|
throw new Error(`Bad response code: ${resp.status}`);
|
|
}
|
|
|
|
const contentLength = resp.headers.get("Content-Length");
|
|
if (resp.status === 200 && (!contentLength || Number(contentLength) > length)) {
|
|
controller?.abort();
|
|
throw new Error(
|
|
"Server returned unexpected full response for PMTiles byte range.",
|
|
);
|
|
}
|
|
|
|
const data = await resp.arrayBuffer();
|
|
void writeCachedRange(
|
|
this.assetVersion,
|
|
offset,
|
|
length,
|
|
data,
|
|
respEtag || undefined,
|
|
this.maxCacheBytes,
|
|
);
|
|
|
|
return {
|
|
data,
|
|
etag: respEtag || undefined,
|
|
cacheControl: resp.headers.get("Cache-Control") || undefined,
|
|
expires: resp.headers.get("Expires") || undefined,
|
|
};
|
|
}
|
|
}
|
|
|
|
export async function resetBoundaryCacheForTests() {
|
|
if (typeof indexedDB === "undefined") return;
|
|
try {
|
|
if (_dbPromise) {
|
|
const db = await _dbPromise;
|
|
db?.close?.();
|
|
_dbPromise = null;
|
|
}
|
|
await new Promise((resolve) => {
|
|
const req = indexedDB.deleteDatabase(BOUNDARY_CACHE_DB_NAME);
|
|
req.onsuccess = () => resolve();
|
|
req.onerror = () => resolve();
|
|
req.onblocked = () => resolve();
|
|
});
|
|
} catch {
|
|
_dbPromise = null;
|
|
}
|
|
}
|