Skip to content

use browser Cache interface to cache tiles - #8363

Merged
ansis merged 7 commits into
masterfrom
cache-api
Jun 21, 2019
Merged

ansis merged 7 commits into
masterfrom
cache-api

Conversation

@ansis

@ansis ansis commented Jun 18, 2019 •

Copy link
Copy Markdown
Contributor

The per-session token recently added to each tile request defeats the browser's caching. This adds caching that ignores the token using Cache interface.

  • push eviction improvements
  • write in-browser tests that can be run in all the browsers
  • document challenges encountered and potential future improvements

Launch Checklist

  • write tests for all new functionality
  • post benchmark scores
  • manually test the debug page

ansis added 2 commits June 13, 2019 13:29
Run eviction only on the workers so that jank introduced

@asheemmamoowala asheemmamoowala left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Looking at the current implementation, it seems that all raster and vector tiles will be cached. Some tile servers don't need the additional caching because the browser's HTTP cache should continue to work.

Should there be granular control to enable/disable this additional layer of caching? All Mapbox resources/tiles should be cached by default, but a mechanism to override this behavior for all resources would be useful - either as a global or per resource override.

cc @kkaefer @mourner @ryanhamley

Comment thread src/util/ajax.js Outdated

if (cachedResponse) {
// Then it isn't a simple CORS
// request.headers.set('If-None-Match', cachedResponse.headers.get('ETag'));

This comment was marked as outdated.

Comment thread src/util/tile_request_cache.js Outdated
return;
}
if (cacheControl['max-age']) {
options.headers.set('Expires', new Date(requestTime + cacheControl['max-age'] * 1000).toUTCString())

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Is there a lower bound of max-age before which we dont cache the resource. The Mapbox Traffic tileset sets a 5minute max-age. How valuable would it be to cache those resources if they are changing so frequently and not reusable for a long period of time.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Implemented in
d936bf7

@asheemmamoowala
asheemmamoowala requested a review from mourner June 18, 2019 22:04

@mourner mourner left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Aside from fixing Flow / lint / unit tests, this looks great. Added a few questions which it would be nice to explain in code comments because it's not obvious what's going on.

I also agree about needing control over custom caching that ignores query parameters — we should definitely not enforce it for non-Mapbox resources, because some servers will have query-based tile url scheme — e.g. example.com/tile?z=10&x=100&y=300. Perhaps let's only hardcode-enable this for Mapbox resources, and think about ways to explicitly turn this on for other sources programmatically later (e.g. in a different PR)?

Comment thread src/util/tile_request_cache.js Outdated
export function cacheEntryPossiblyAdded(dispatcher: Dispatcher) {
globalEntryCounter++;
if (globalEntryCounter > CACHE_CHECK_THRESHOLD) {
dispatcher.send('enforceCacheSizeLimit');

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Trying to follow the flow here... Is the cache shared between the main thread and the workers? If so, why do we need to send a signal to enforce the size limit to a random worker (through dispatcher)? Or is this because of cache operations blocking the main thread and affecting performance? If so, can we add a comment about this?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Yep, blocking. I'm not fully confident whether it is misleading profiling or a real issue but I think it's safer to do it on the worker for now. I'm seeing it sometimes and not seeing it other times. Added a comment 54ac863

Comment thread src/util/tile_request_cache.js Outdated
window.caches.open(CACHE_NAME)
.then(cache => {
cache.put(request, clonedResponse).then(() => {
});

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Leftover empty callback?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

removed in 9033e28

Comment thread src/util/tile_request_cache.js Outdated
.then(response => {
const fresh = isFresh(response);

// reinsert into cache so

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Unfinished comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

finished in 54ac863

}


let globalEntryCounter = Infinity;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Is this Infinity to enforce cache size limit on an initial page load (anticipating already existing cache)? Might need a comment too.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Added a comment in 54ac863

@ansis

ansis commented Jun 19, 2019

Copy link
Copy Markdown
Contributor Author

I also agree about needing control over custom caching that ignores query parameters — we should definitely not enforce it for non-Mapbox resources, because some servers will have query-based tile url scheme — e.g. example.com/tile?z=10&x=100&y=300. Perhaps let's only hardcode-enable this for Mapbox resources, and think about ways to explicitly turn this on for other sources programmatically later (e.g. in a different PR)?

Yep. I've changed this in de81a8e (messy commit with some other changes as well). It now runs the caching only when the url is both:

  • mapbox, and
  • contains sku=

- fix error when request aborted after added to cache
- skip tiles which expiry soon (traffic)
- skip tiles from non-mapbox sources
- skip resources that are not tiles
- expose clearStorage
- semi-expose cache size setting for debugging
- add browser tests (debug/cach_api.html)

@mourner mourner left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

🚢 pending a linting fix to make the build green

@ansis

ansis commented Jun 21, 2019

Copy link
Copy Markdown
Contributor Author

Some notes on things I've learned along the way:

  • If-None-Modified is not considered an allowed header for simple cors requests. Using it to revalidate expired tiles results in the cors with preflight requests which doesn't work for us.
  • Aborting requests after adding them to cache raises errors and crashes the firefox tab
  • Adding a key that already exists in the cache modifies the order in some browsers but no others

The current implementation only runs when the fetch api is used. Due to a limitation with aborting fetch requests in safari this doesn't run in safari. Mobile safari doesn't work on browserstack due to the same fetch api limitation. But mobile safari works on my device?! I'm not sure exactly what is going on.

This has been also tested to work correctly in browsers without support for this api.

@ansis
ansis merged commit 500320f into master Jun 21, 2019
@andrewharvey

Copy link
Copy Markdown
Collaborator

This is sneaky, but I understand why it's needed, it just had me pulling my hair out wondering why I couldn't see any network requests for tiles in Chrome's DevTools under Network... Until I realised this bypasses that entirely and uses the "Cache" interface.

ansis added a commit that referenced this pull request Jun 24, 2019
Recent pricing changes introduced a `sku=` query parameter that changes with every map load. This defeats the browser's ability to cache these tiles. We're working around that by implementing our own caching with the new `Cache` api.

- skips caching tiles that expire soon
- only caches mapbox tiles (no 3rd party tiles, styles, etc because the browser should cache these fine)
- does not work in IE, Safari

Browser tests can be found in debug/cache_api.html

mapboxgl.clearStorage added to provide a way to clear the cache.
ansis added a commit that referenced this pull request Jun 24, 2019
Recent pricing changes introduced a `sku=` query parameter that changes with every map load. This defeats the browser's ability to cache these tiles. We're working around that by implementing our own caching with the new `Cache` api.

- skips caching tiles that expire soon
- only caches mapbox tiles (no 3rd party tiles, styles, etc because the browser should cache these fine)
- does not work in IE, Safari

Browser tests can be found in debug/cache_api.html

mapboxgl.clearStorage added to provide a way to clear the cache.
@asheemmamoowala asheemmamoowala changed the title [WIP] use browser Cache interface to cache tiles use browser Cache interface to cache tiles Jun 27, 2019
peterqliu added a commit that referenced this pull request Jul 19, 2019
* [docs] adds docs-wide search component (#8349)

* update dr-ui, mr-ui

* add search component

* adjust columns to prevent overlap

* v1.1.0-beta.1 (#8353)

* Update CHANGELOG.md for v1.1.0-beta.1 release
* Bump package.json version to 1.1.0-beta.1

* [docs] updates to search component and layout (#8362)

* do not index /api sidebar

* exclude code snippets in examples from being indexed

* Update docs-page-shell

* update dr-ui, react, react-dom

* adjust columns to fit search and navigation better

* [docs] Replace example with a third-party raster source (#8274)

* remove Add a raster tile source example

* revert "remove Add a raster tile source example"

This reverts commit ea8bf28.

* add third-party tiles to map-tiles example

* fix attribution

* rm unused var

* Add mapbox-gl-framerate to plugins list (#8356)

* remove old plugins page and update reference to the maintained version (#8369)

* Add link to iOS SDK documentation (#8359)

* add ios sdk link per comment from stephen g

* add new link from minh and reword

* Include Hiragana and Katakana code blocks for local glyph generation (#8365) (#8378)

* document the tile size drawn with showTileBoundaries (#8379)

* use browser `Cache` interface to cache tiles (#8363)

Recent pricing changes introduced a `sku=` query parameter that changes with every map load. This defeats the browser's ability to cache these tiles. We're working around that by implementing our own caching with the new `Cache` api.

- skips caching tiles that expire soon
- only caches mapbox tiles (no 3rd party tiles, styles, etc because the browser should cache these fine)
- does not work in IE, Safari

Browser tests can be found in debug/cache_api.html

mapboxgl.clearStorage added to provide a way to clear the cache.

* fix cache support check for enforcing size limit

This was throwing errors in browsers that don't support the cache api
but wasn't previously noticed because it was not breaking anything.

* Fix background rotation hovering (#8367)

* update changelog

* [email protected] (#8297)

* [email protected]

* add one more file to  v4.4.0

* fix Response construction in Edge, fix #8391 (#8392) (#8394)

Edge does not support constructing responses with readable streams.

* v1.1.0-beta.2 (#8395)

* Add sdk support spec section for text-radial-offset (#8384) (#8401)

This PR also assigns SDK versions for the `text-variable-anchor`
property (both `text-variable-anchor` and `text-radial-offset`
are the parts of the variable text placement feature).

* fix #8411, fetch in case of cache error (#8415) (#8417)

* fix #8411, fetch in case of cache error

* Use warnOnce

* v1.1.0 & [email protected] (#8408)

* Update style-spec version & changelog for [email protected]

- Update style-spec/CHANGELOG.md to add bugfix items
- Bump style-spec/package.json version to 13.7.1 (patch)

* Update mapbox-gl package version to 1.1.0 for final release

* Add missing style-spec changelog entry

* Fix yarn.lock not installing under CI by auto-updating dependencies

* manually strip urls for faster cache matching (#8434) (#8449)

* update examples to use mapbox-gl-geocoder v4.4.1 (#8451)

* set antialias to true for custom layers and extrusion examples (#8474)

* swap map-tiles example to use https (#8482)

* fix race condition between caching and aborting (#8472)

fix #8470, continuous memory usage growth

* fix #8481, unbounded memory growth in IE (#8490)

Cancellable requests to workers should never call back after they have
been cancelled.

* v1.1.1

* [docs] fix SDK support for symbol-sort-key (#8501)
@mourner
mourner deleted the cache-api branch August 1, 2019 11:46
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants