Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[INV-3771] Speed up maptile caching #3775

Merged
merged 3 commits into from
Jan 7, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 6 additions & 4 deletions app/src/UI/Overlay/TileCache/TileCacheDownloadProgress.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,12 @@ const TileCacheDownloadProgress = () => {
<section>
<table>
<thead>
<th>Cache Name</th>
<th>Download Status</th>
<th>Progress</th>
<th>Cancel</th>
<tr>
<th>Cache Name</th>
<th>Download Status</th>
<th>Progress</th>
<th>Cancel</th>
</tr>
</thead>
<tbody>
{Object.keys(downloadProgress).map((k) => (
Expand Down
2 changes: 1 addition & 1 deletion app/src/UI/Overlay/TileCache/TileCacheListRow.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ const TileCacheListRow = ({ metadata, visible }) => {
</td>
<td>{metadata.description || metadata.id}</td>
<td>{metadata.status}</td>
<td>{stats?.tileCount}</td>
<td>{stats?.tileCount?.toLocaleString()}</td>
<td>{stats && convertBytesToReadableString(stats.sizeInBytes)}</td>
<td>
<IconButton color={'primary'} onClick={handleEditCacheDescription}>
Expand Down
130 changes: 84 additions & 46 deletions app/src/utils/tile-cache/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,13 @@ enum RepositoryStatus {
UNKNOWN = 'UNKNOWN'
}

interface TilePromise {
id: string;
url: string;
x: number;
y: number;
z: number;
}
export interface TileCacheProgressCallbackParameters {
repository: string;
message: string;
Expand Down Expand Up @@ -107,75 +114,106 @@ abstract class TileCacheService {

abstract setRepositoryStatus(repository: string, status: RepositoryStatus): Promise<void>;

private async downloadTile(tileDetails: TilePromise): Promise<void> {
const { id, url, x, y, z } = tileDetails;
const responseData = await fetch(url).then(async (r) => await r.arrayBuffer());
await this.setTile(id, z, x, y, new Uint8Array(responseData));
}

async download(
spec: RepositoryDownloadRequestSpec,
progressCallback?: (currentProgress: TileCacheProgressCallbackParameters) => void
): Promise<void> {
await this.addRepository({
id: spec.id,
status: RepositoryStatus.DOWNLOADING,
maxZoom: spec.maxZoom,
bounds: spec.bounds,
description: spec.description
});
const processNext = async (promiseFn) => {
const promise = promiseFn();
executing.add(promise);
try {
await promise;
} catch (e) {
console.error(e);
try {
await promise;
} catch (e) {
console.error('Failed second attempt at fetching tile');
}
} finally {
executing.delete(promise);
}
};

const CONCURRENCY_LIMIT = 10;
const totalTiles = TileCacheService.computeTileCount(spec.bounds, spec.maxZoom);

let abort = false;

let processedTiles = 0;
let lastProgressCallback: null | number = null;
let lastProgressCallbackTimestamp: number | null = null;
const tileUrls: TilePromise[] = [];
const executing = new Set();

try {
await this.addRepository({
id: spec.id,
status: RepositoryStatus.DOWNLOADING,
maxZoom: spec.maxZoom,
bounds: spec.bounds,
description: spec.description
});

for (let z = 0; z <= spec.maxZoom && !abort; z++) {
const startTileLat = lat2tile(spec.bounds.minLatitude, z);
const startTileLng = long2tile(spec.bounds.minLongitude, z);

const endTileLat = lat2tile(spec.bounds.maxLatitude, z);
const endTileLng = long2tile(spec.bounds.maxLongitude, z);

for (let x = Math.min(startTileLng, endTileLng); x <= Math.max(startTileLng, endTileLng) && !abort; x++) {
for (let y = Math.min(startTileLat, endTileLat); y <= Math.max(startTileLat, endTileLat) && !abort; y++) {
const url = spec.tileURL(x, y, z);
const response = await fetch(url);
const data = await response.arrayBuffer();

await this.setTile(spec.id, z, x, y, new Uint8Array(data));
processedTiles++;

const currentProgress = processedTiles / totalTiles;
// trigger a callback on the first run, on the last run, every 1%, and every 200ms
if (
lastProgressCallback == null ||
lastProgressCallbackTimestamp == null ||
currentProgress - lastProgressCallback > 0.01 ||
processedTiles == totalTiles ||
Date.now() - lastProgressCallbackTimestamp > 200
) {
// take advantage of the periodic callback to check if we should abort (because the repo was concurrently deleted)
const updatedRepositoryState = await this.getRepository(spec.id);
if (updatedRepositoryState == null || updatedRepositoryState.status == RepositoryStatus.DELETING) {
abort = true;
}

lastProgressCallback = currentProgress;
lastProgressCallbackTimestamp = Date.now();

if (progressCallback) {
progressCallback({
repository: spec.id,
message: abort ? `Aborting` : `Zoom ${z}/${spec.maxZoom}, ${processedTiles}/${totalTiles} Tiles`,
aborted: abort,
normalizedProgress: processedTiles / totalTiles,
processedTiles,
totalTiles
});
}
}
tileUrls.push({ id: spec.id, url: spec.tileURL(x, y, z), x, y, z });
}
}
}
const promises = tileUrls.map((config) => () => this.downloadTile(config));
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nice


for (let i = 0; i < promises.length && !abort; i++) {
if (executing.size >= CONCURRENCY_LIMIT) {
await Promise.race(executing);
}

processNext(promises[i]);
processedTiles++;
const currentProgress = processedTiles / totalTiles;
const currTime = Date.now();

// trigger a callback on the first run, on the last run, every 1%, and every 200ms
if (
lastProgressCallback == null ||
lastProgressCallbackTimestamp == null ||
currentProgress - lastProgressCallback > 0.01 ||
processedTiles == totalTiles ||
currTime - lastProgressCallbackTimestamp > 500
) {
// take advantage of the periodic callback to check if we should abort (because the repo was concurrently deleted)
const updatedRepositoryState = await this.getRepository(spec.id);
if (updatedRepositoryState == null || updatedRepositoryState.status == RepositoryStatus.DELETING) {
abort = true;
}

lastProgressCallback = currentProgress;
lastProgressCallbackTimestamp = currTime;

if (progressCallback) {
progressCallback({
repository: spec.id,
message: abort ? `Aborting` : `${processedTiles.toLocaleString()}/${totalTiles.toLocaleString()} Tiles`,
aborted: abort,
normalizedProgress: processedTiles / totalTiles,
processedTiles,
totalTiles
});
}
}
}

await Promise.all(executing);
await this.setRepositoryStatus(spec.id, RepositoryStatus.READY);
} catch (e) {
try {
Expand Down
Loading