[ServiceWorker] Can caches store and retrieve results that are still being written to the cache? (#573)

At the moment cache-adding methods resolve when the full body of the response if written to the cache. That means we can reject if the body stream looks like a failure, which can be suggested by content-length https://github.com/slightlyoff/ServiceWorker/issues/362#issuecomment-49011736. This is a must due to `installEvent.waitUntil(addStuffToCaches)` - we can't have that resolve but ultimately fail.

However, if you have code that tries the cache, falls back to the network and adds to the cache, you can end up with multiple pages doing this with the same resource, as `cache.match` won't return items until it's fully cached.

Shall we change this so items are added to the underlying cache as soon as we have headers? So for `cache.add(request)`:

1. Fetch request
1. If fetch fails, reject & abort
1. Add (request, response) to RequestToResponseMap
1. Wait for body to stream into cache
1. If body writing fails, remove (request, response) from RequestToResponseMap, reject the promise & abort these steps
1. Remove other entries in RequestToResponseMap that match request (`.match` can no longer reach them)
1. Resolve promise

If you call `.match(request)` and there's already a match fully-written in the cache, you'll get that rather than the in-progress one. This seems sensible to me, but we *could* favour the in-progress one.

If you get an in-progress response back from `.match(request)`, that goes back to the page, it may arrive slowly, it may ultimately fail. But hey, that's the same with the network.

Questions:

* Does this sound like a good idea?
* It is universally a good idea, or should it be an option to `.match()`. I don't think it needs to be optional.

Related: #361 #362

/cc Cache-warriors @wanderview @gavinp @sicking 

---
Reply to this email directly or view it on GitHub:
https://github.com/slightlyoff/ServiceWorker/issues/573

Received on Thursday, 4 December 2014 12:14:35 UTC