Re: [w3c/ServiceWorker] Allow caches to opt-in to granular cleanup (#863)

```Cache.keys()``` returns results [in insertion order](https://w3c.github.io/ServiceWorker/#cache-keys), so the cache replacement policies [FIFO](https://en.wikipedia.org/wiki/Cache_replacement_policies#First_In_First_Out_(FIFO)) and [LIFO](https://en.wikipedia.org/wiki/Cache_replacement_policies#Last_In_First_Out_(LIFO)) are straightforward.

It would, however, be convenient if there was a direct way to get the "last accessed time" (and maybe even the "added time") in a fictive ```Cache.has(request, option)``` method (that would *not* return a ```Response``` like ```Cache.match(request, option)```, but rather a likewise fictive ```CacheItem``` object with the ```timeAdded``` and ```timeLastAccessed``` timestamps and a ```matches``` boolean) for more straightforward [LRU](https://en.wikipedia.org/wiki/Cache_replacement_policies#Least_Recently_Used_(LRU))/[MRU](https://en.wikipedia.org/wiki/Cache_replacement_policies#Most_Recently_Used_(MRU)).

Note that this is already possible now, but there is quite some overhead—via @wanderview's [comment](https://github.com/w3c/ServiceWorker/issues/587#issue-51615947):

```javascript
var cache;
cache.open('foo').then(function(foo) {
  cache = foo;
  return cache.match(request);
}).then(function(response) {
  if (response) {
    // update order of entries in keys()
    cache.put(request, response.clone());  // <== overhead happens here
    return response;
  }

  var maxItems = 100;
  return addToLRU(cache, maxItems, request);
});

function addToLRU(cache, maxItems, request) {
  return cache.keys().then(function(keys) {
    if (keys.length < maxItems) {
      return cache.add(request);
    }

    return cache.delete(keys[0]).then(function() {
      return cache.add(request);
    });
  });
}
```

This would not take care of eviction ([why no eviction](https://wiki.whatwg.org/wiki/Storage#Why_no_eviction_event.3F)), but simplify common cache replacement policies, without having to [resort to ```IndexedDB```](https://github.com/GoogleChrome/workbox/blob/09f6340fc6f9bd511e1fc160a2e71bde65c549de/packages/workbox-cache-expiration/models/CacheTimestampsModel.mjs). What do you think?

-- 
You are receiving this because you are subscribed to this thread.
Reply to this email directly or view it on GitHub:
https://github.com/w3c/ServiceWorker/issues/863#issuecomment-349319261

Received on Tuesday, 5 December 2017 14:26:38 UTC