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

@jakearchibald, as a response to your [comment](https://github.com/w3c/ServiceWorker/issues/863#issuecomment-352828121), here is a still *raw* sketch of an API of a fictive `Cache.has(request, {options})` that would return a likewise fictive `CacheItem` object:

```javascript
// Create `CacheItem` foo at timestamp 1000
await cache.add('foo');

// Get statistics about the never matched `CacheItem`
await cache.has('foo');
// returns `{key: 'foo', timeCached: 1000, timeMatched: Infinity}`

// Get statistics about a non-existent `CacheItem`
await cache.has('bar');
// returns `undefined`

// Use `CacheItem` foo at timestamp 2000
await cache.match('foo');

// Get statistics about the now matched (=used) `CacheItem`
await cache.has('foo');
// returns `{key: 'foo', timeCached: 1000, timeMatched: 2000}`
```

This would allow for relatively simple to implement cache replacement policies that are independent of Indexed Database, like, for example, Least Recently Used: 

```javascript
const MAX_CACHE_ITEMS = 5;
const cache = await caches.open('lru-cache');

const addToCache = async (cache, url) => {
  const keys = await cache.keys();
  if (keys.length < MAX_CACHE_ITEMS) {
    return await cache.add(url);
  }
  const cacheItems = await Promise.all(
    keys.map(async key => await cache.has(key))
  );
  const lruCacheItem = cacheItems.sort(
    (a, b) => a.timeMatched - b.timeMatched
  )[0];
  await cache.delete(lruCacheItem.key);
  return await cache.add(url);
};
```

Something I'm unsure about is the appropriateness `Infinity` for never matched `CacheItem`s, but it makes the sorting easier. I'm definitely overlooking a number of corner cases, so looking for *your* thoughts. Thanks!

-- 
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-353070261

Received on Wednesday, 20 December 2017 14:01:12 UTC