W3C home > Mailing lists > Public > whatwg@whatwg.org > December 2009

[whatwg] Supporting eviction in WebStorage

From: Kyle Scholz <kyle.scholz@gmail.com>
Date: Thu, 24 Dec 2009 14:39:57 -0800
Message-ID: <bdd2667d0912241439s3054edf1q98a7ce882de1284d@mail.gmail.com>
A common application of WebStorage will be clientside caching. Since
there are limits on store size, developers will be implementing
eviction schemes, but this is currently difficult because the
interface doesn't expose store size or get/set times for entries. Some
additions to the Storage interface would support most use cases:
totalSize() - Indicates the absolute size of the store.
availableSize() - Indicates available space in the store.
keysByAccessTime() - Returns a list of keys in ascending order by access time.
accessItem() - Sets the access time of an entry to now.

setItem() will always set the access time of an item. getItem() will
not set the access time of an item. This makes it possible for the
developer to determine whether they wish to enable a
least-recently-stored or least-recently-accessed eviction policy. A
developer should follow calls to getItem() with a call to accessItem()
if they wish eviction candidates to be ordered by access time.

A basic cache access / eviction implementation might look like this:

/**
 * Get an item from localStorage. Update it's access time.
 */
function getItem(key) {
 localStorage.getItem(key);
 localStorage.accessItem(key);
}

/**
 * Store an item in localStorage. Presumes arguments are stringified.
 */
function storeItem(key, value) {
  var entrySize = key.length + value.length;
  if (entrySize > localStorage.totalSize()) {
    throw "Entry exceeds total size.";
  }
  var spaceAfter = localStorage.availableSpace() - entrySize;
  if (spaceAfter < 0) {
    evictEvictEntries(spaceAfter * -1);
  }
 localStorage.setItem(key, value);
}

/**
 * Evict entries until needed space is available.
 */
function makeRoom(spaceNeeded) {
  while(localStorage.length && localStorage.spaceAvailable() < spaceNeeded) {
    var candidate = localStorage.keysByAccessTime()[0];
    // Insert any conditional logic to determine whether candidate
should be evicted.
    localStorage.removeItem(candidate);
  }
}

Thoughts? I'd considered whether Storage might implement cache
eviction internally, but that limits the developer's control over
which entries are candidates for eviction. In a given application, all
stored items may not be equal.
Received on Thursday, 24 December 2009 14:39:57 UTC

This archive was generated by hypermail 2.3.1 : Monday, 13 April 2015 23:08:54 UTC