gaugau
gaugau

Reputation: 896

How to handle 206 responses in Firefox service workers

While testing service workers for a project and using this example from google:

/*
 Copyright 2016 Google Inc. All Rights Reserved.
 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at
     http://www.apache.org/licenses/LICENSE-2.0
 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
*/

// Names of the two caches used in this version of the service worker.
// Change to v2, etc. when you update any of the local resources, which will
// in turn trigger the install event again.
const PRECACHE = 'precache-v1';
const RUNTIME = 'runtime';

// A list of local resources we always want to be cached.
const PRECACHE_URLS = [
  'index.html',
  './', // Alias for index.html
  'styles.css',
  '../../styles/main.css',
  'demo.js'
];

// The install handler takes care of precaching the resources we always need.
self.addEventListener('install', event => {
  event.waitUntil(
    caches.open(PRECACHE)
      .then(cache => cache.addAll(PRECACHE_URLS))
      .then(self.skipWaiting())
  );
});

// The activate handler takes care of cleaning up old caches.
self.addEventListener('activate', event => {
  const currentCaches = [PRECACHE, RUNTIME];
  event.waitUntil(
    caches.keys().then(cacheNames => {
      return cacheNames.filter(cacheName => !currentCaches.includes(cacheName));
    }).then(cachesToDelete => {
      return Promise.all(cachesToDelete.map(cacheToDelete => {
        return caches.delete(cacheToDelete);
      }));
    }).then(() => self.clients.claim())
  );
});

// The fetch handler serves responses for same-origin resources from a cache.
// If no response is found, it populates the runtime cache with the response
// from the network before returning it to the page.
self.addEventListener('fetch', event => {
  // Skip cross-origin requests, like those for Google Analytics.
  if (event.request.url.startsWith(self.location.origin)) {
    event.respondWith(
      caches.match(event.request).then(cachedResponse => {
        if (cachedResponse) {
          return cachedResponse;
        }

        return caches.open(RUNTIME).then(cache => {
          return fetch(event.request).then(response => {
            // Put a copy of the response in the runtime cache.
            return cache.put(event.request, response.clone()).then(() => {
              return response;
            });
          });
        });
      })
    );
  }
});

source: https://github.com/GoogleChrome/samples/blob/gh-pages/service-worker/basic/service-worker.js

I discovered that Firefox (in contrast to safari and chrome) throws errors within event.waitUntil() as well as event.respondWith() if something does not work with the fetch requests (even if its just a 206 partial content response):

Service worker event waitUntil() was passed a promise that rejected with 'TypeError: Cache got basic response with bad status 206 while trying to add request

That behaviour breaks the installer. If I add a .catch() to the installer like this

self.addEventListener('install', event => {
  event.waitUntil(
    caches.open(PRECACHE)
      .then(cache => cache.addAll(PRECACHE_URLS))
      .then(self.skipWaiting())
      .catch(function(err){
        console.log(err);
        self.skipWaiting();
      })
  );

});

I presume the first 206 will make the precache stop (?)

Also after that the sw gets installed but once in a while I get a

Service worker event respondWith() was passed a promise that rejected with 'TypeError: Cache got basic response with bad status 206 while trying to add request

and even if that does not happen, if I try to open the a link to the url that threw the 206 error while installation/precaching I get:

Failed to load ‘https://xxxx/yyyyy.mp3’. A ServiceWorker passed a promise to FetchEvent.respondWith() that rejected with ‘TypeError: Cache got basic response with bad status 206 while trying to add request https://xxxx/yyyyy.mp3’.

inside of the browser the error looks like the file is broken

how can I handle this kind of error properly? catching like above doesn't make much sense for it breaks the forced precaching. And even if that would be acceptable, it seems to interfere with every request happening from then on and might cause trouble later on.

Upvotes: 5

Views: 2586

Answers (1)

gaugau
gaugau

Reputation: 896

one half of the problem i could solve by moving the return statement from within the cache.put() function outside of it:

self.addEventListener('fetch', event => {
  // Skip cross-origin requests, like those for Google Analytics.
  if (event.request.url.startsWith(self.location.origin)) {
    event.respondWith(
      caches.match(event.request).then(cachedResponse => {
        if (cachedResponse) {
          return cachedResponse;
        }

        return caches.open(RUNTIME).then(cache => {
          return fetch(event.request).then(response => {
            // Put a copy of the response in the runtime cache.
            cache.put(event.request, response.clone()).then(() => {
              console.log("logged a file into RUNTIME:");
              console.log(response);
            });
            return response; // and return anyhow whatever came back
          });
        });
      })
    );
  }
});

this way the sw does not wait for the cache.put() to be successful and yet it gets cached most of the times.

this solves the most urgent issue but problems still are

a) forced precaching still gets cancelled by 206 responses b) in case I would want to make sure that requests are cached in runtime, i would still need to make some retry() function or sth.

Upvotes: 0

Related Questions