Home | History | Annotate | Download | only in disk_cache
      1 // Copyright (c) 2006-2010 The Chromium Authors. All rights reserved.
      2 // Use of this source code is governed by a BSD-style license that can be
      3 // found in the LICENSE file.
      4 
      5 // Defines the public interface of the disk cache. For more details see
      6 // http://dev.chromium.org/developers/design-documents/disk-cache
      7 
      8 #ifndef NET_DISK_CACHE_DISK_CACHE_H_
      9 #define NET_DISK_CACHE_DISK_CACHE_H_
     10 #pragma once
     11 
     12 #include <string>
     13 #include <vector>
     14 
     15 #include "base/basictypes.h"
     16 #include "base/time.h"
     17 #include "net/base/cache_type.h"
     18 #include "net/base/completion_callback.h"
     19 
     20 class FilePath;
     21 
     22 namespace base {
     23 class MessageLoopProxy;
     24 }
     25 
     26 namespace net {
     27 class IOBuffer;
     28 class NetLog;
     29 }
     30 
     31 namespace disk_cache {
     32 
     33 class Entry;
     34 class Backend;
     35 typedef net::CompletionCallback CompletionCallback;
     36 
     37 // Returns an instance of a Backend of the given |type|. |path| points to a
     38 // folder where the cached data will be stored (if appropriate). This cache
     39 // instance must be the only object that will be reading or writing files to
     40 // that folder. The returned object should be deleted when not needed anymore.
     41 // If |force| is true, and there is a problem with the cache initialization, the
     42 // files will be deleted and a new set will be created. |max_bytes| is the
     43 // maximum size the cache can grow to. If zero is passed in as |max_bytes|, the
     44 // cache will determine the value to use. |thread| can be used to perform IO
     45 // operations if a dedicated thread is required; a valid value is expected for
     46 // any backend that performs operations on a disk. The returned pointer can be
     47 // NULL if a fatal error is found. The actual return value of the function is a
     48 // net error code. If this function returns ERR_IO_PENDING, the |callback| will
     49 // be invoked when a backend is available or a fatal error condition is reached.
     50 // The pointer to receive the |backend| must remain valid until the operation
     51 // completes (the callback is notified).
     52 int CreateCacheBackend(net::CacheType type, const FilePath& path, int max_bytes,
     53                        bool force, base::MessageLoopProxy* thread,
     54                        net::NetLog* net_log, Backend** backend,
     55                        CompletionCallback* callback);
     56 
     57 // The root interface for a disk cache instance.
     58 class Backend {
     59  public:
     60   // If the backend is destroyed when there are operations in progress (any
     61   // callback that has not been invoked yet), this method cancels said
     62   // operations so the callbacks are not invoked, possibly leaving the work
     63   // half way (for instance, dooming just a few entries). Note that pending IO
     64   // for a given Entry (as opposed to the Backend) will still generate a
     65   // callback from within this method.
     66   virtual ~Backend() {}
     67 
     68   // Returns the number of entries in the cache.
     69   virtual int32 GetEntryCount() const = 0;
     70 
     71   // Opens an existing entry. Upon success, |entry| holds a pointer to an Entry
     72   // object representing the specified disk cache entry. When the entry pointer
     73   // is no longer needed, its Close method should be called. The return value is
     74   // a net error code. If this method returns ERR_IO_PENDING, the |callback|
     75   // will be invoked when the entry is available. The pointer to receive the
     76   // |entry| must remain valid until the operation completes.
     77   virtual int OpenEntry(const std::string& key, Entry** entry,
     78                         CompletionCallback* callback) = 0;
     79 
     80   // Creates a new entry. Upon success, the out param holds a pointer to an
     81   // Entry object representing the newly created disk cache entry. When the
     82   // entry pointer is no longer needed, its Close method should be called. The
     83   // return value is a net error code. If this method returns ERR_IO_PENDING,
     84   // the |callback| will be invoked when the entry is available. The pointer to
     85   // receive the |entry| must remain valid until the operation completes.
     86   virtual int CreateEntry(const std::string& key, Entry** entry,
     87                           CompletionCallback* callback) = 0;
     88 
     89   // Marks the entry, specified by the given key, for deletion. The return value
     90   // is a net error code. If this method returns ERR_IO_PENDING, the |callback|
     91   // will be invoked after the entry is doomed.
     92   virtual int DoomEntry(const std::string& key,
     93                         CompletionCallback* callback) = 0;
     94 
     95   // Marks all entries for deletion. The return value is a net error code. If
     96   // this method returns ERR_IO_PENDING, the |callback| will be invoked when the
     97   // operation completes.
     98   virtual int DoomAllEntries(CompletionCallback* callback) = 0;
     99 
    100   // Marks a range of entries for deletion. This supports unbounded deletes in
    101   // either direction by using null Time values for either argument. The return
    102   // value is a net error code. If this method returns ERR_IO_PENDING, the
    103   // |callback| will be invoked when the operation completes.
    104   virtual int DoomEntriesBetween(const base::Time initial_time,
    105                                  const base::Time end_time,
    106                                  CompletionCallback* callback) = 0;
    107 
    108   // Marks all entries accessed since |initial_time| for deletion. The return
    109   // value is a net error code. If this method returns ERR_IO_PENDING, the
    110   // |callback| will be invoked when the operation completes.
    111   virtual int DoomEntriesSince(const base::Time initial_time,
    112                                CompletionCallback* callback) = 0;
    113 
    114   // Enumerates the cache. Initialize |iter| to NULL before calling this method
    115   // the first time. That will cause the enumeration to start at the head of
    116   // the cache. For subsequent calls, pass the same |iter| pointer again without
    117   // changing its value. This method returns ERR_FAILED when there are no more
    118   // entries to enumerate. When the entry pointer is no longer needed, its
    119   // Close method should be called. The return value is a net error code. If
    120   // this method returns ERR_IO_PENDING, the |callback| will be invoked when the
    121   // |next_entry| is available. The pointer to receive the |next_entry| must
    122   // remain valid until the operation completes.
    123   //
    124   // NOTE: This method does not modify the last_used field of the entry, and
    125   // therefore it does not impact the eviction ranking of the entry.
    126   virtual int OpenNextEntry(void** iter, Entry** next_entry,
    127                             CompletionCallback* callback) = 0;
    128 
    129   // Releases iter without returning the next entry. Whenever OpenNextEntry()
    130   // returns true, but the caller is not interested in continuing the
    131   // enumeration by calling OpenNextEntry() again, the enumeration must be
    132   // ended by calling this method with iter returned by OpenNextEntry().
    133   virtual void EndEnumeration(void** iter) = 0;
    134 
    135   // Return a list of cache statistics.
    136   virtual void GetStats(
    137       std::vector<std::pair<std::string, std::string> >* stats) = 0;
    138 };
    139 
    140 // This interface represents an entry in the disk cache.
    141 class Entry {
    142  public:
    143   // Marks this cache entry for deletion.
    144   virtual void Doom() = 0;
    145 
    146   // Releases this entry. Calling this method does not cancel pending IO
    147   // operations on this entry. Even after the last reference to this object has
    148   // been released, pending completion callbacks may be invoked.
    149   virtual void Close() = 0;
    150 
    151   // Returns the key associated with this cache entry.
    152   virtual std::string GetKey() const = 0;
    153 
    154   // Returns the time when this cache entry was last used.
    155   virtual base::Time GetLastUsed() const = 0;
    156 
    157   // Returns the time when this cache entry was last modified.
    158   virtual base::Time GetLastModified() const = 0;
    159 
    160   // Returns the size of the cache data with the given index.
    161   virtual int32 GetDataSize(int index) const = 0;
    162 
    163   // Copies cache data into the given buffer of length |buf_len|.  If
    164   // completion_callback is null, then this call blocks until the read
    165   // operation is complete.  Otherwise, completion_callback will be
    166   // called on the current thread once the read completes.  Returns the
    167   // number of bytes read or a network error code. If a completion callback is
    168   // provided then it will be called if this function returns ERR_IO_PENDING,
    169   // and a reference to |buf| will be retained until the callback is called.
    170   // Note that the callback will be invoked in any case, even after Close has
    171   // been called; in other words, the caller may close this entry without
    172   // having to wait for all the callbacks, and still rely on the cleanup
    173   // performed from the callback code.
    174   virtual int ReadData(int index, int offset, net::IOBuffer* buf, int buf_len,
    175                        CompletionCallback* completion_callback) = 0;
    176 
    177   // Copies cache data from the given buffer of length |buf_len|.  If
    178   // completion_callback is null, then this call blocks until the write
    179   // operation is complete.  Otherwise, completion_callback will be
    180   // called on the current thread once the write completes.  Returns the
    181   // number of bytes written or a network error code. If a completion callback
    182   // is provided then it will be called if this function returns ERR_IO_PENDING,
    183   // and a reference to |buf| will be retained until the callback is called.
    184   // Note that the callback will be invoked in any case, even after Close has
    185   // been called; in other words, the caller may close this entry without
    186   // having to wait for all the callbacks, and still rely on the cleanup
    187   // performed from the callback code.
    188   // If truncate is true, this call will truncate the stored data at the end of
    189   // what we are writing here.
    190   virtual int WriteData(int index, int offset, net::IOBuffer* buf, int buf_len,
    191                         CompletionCallback* completion_callback,
    192                         bool truncate) = 0;
    193 
    194   // Sparse entries support:
    195   //
    196   // A Backend implementation can support sparse entries, so the cache keeps
    197   // track of which parts of the entry have been written before. The backend
    198   // will never return data that was not written previously, so reading from
    199   // such region will return 0 bytes read (or actually the number of bytes read
    200   // before reaching that region).
    201   //
    202   // There are only two streams for sparse entries: a regular control stream
    203   // (index 0) that must be accessed through the regular API (ReadData and
    204   // WriteData), and one sparse stream that must me accessed through the sparse-
    205   // aware API that follows. Calling a non-sparse aware method with an index
    206   // argument other than 0 is a mistake that results in implementation specific
    207   // behavior. Using a sparse-aware method with an entry that was not stored
    208   // using the same API, or with a backend that doesn't support sparse entries
    209   // will return ERR_CACHE_OPERATION_NOT_SUPPORTED.
    210   //
    211   // The storage granularity of the implementation should be at least 1 KB. In
    212   // other words, storing less than 1 KB may result in an implementation
    213   // dropping the data completely, and writing at offsets not aligned with 1 KB,
    214   // or with lengths not a multiple of 1 KB may result in the first or last part
    215   // of the data being discarded. However, two consecutive writes should not
    216   // result in a hole in between the two parts as long as they are sequential
    217   // (the second one starts where the first one ended), and there is no other
    218   // write between them.
    219   //
    220   // The Backend implementation is free to evict any range from the cache at any
    221   // moment, so in practice, the previously stated granularity of 1 KB is not
    222   // as bad as it sounds.
    223   //
    224   // The sparse methods don't support multiple simultaneous IO operations to the
    225   // same physical entry, so in practice a single object should be instantiated
    226   // for a given key at any given time. Once an operation has been issued, the
    227   // caller should wait until it completes before starting another one. This
    228   // requirement includes the case when an entry is closed while some operation
    229   // is in progress and another object is instantiated; any IO operation will
    230   // fail while the previous operation is still in-flight. In order to deal with
    231   // this requirement, the caller could either wait until the operation
    232   // completes before closing the entry, or call CancelSparseIO() before closing
    233   // the entry, and call ReadyForSparseIO() on the new entry and wait for the
    234   // callback before issuing new operations.
    235 
    236   // Behaves like ReadData() except that this method is used to access sparse
    237   // entries.
    238   virtual int ReadSparseData(int64 offset, net::IOBuffer* buf, int buf_len,
    239                              CompletionCallback* completion_callback) = 0;
    240 
    241   // Behaves like WriteData() except that this method is used to access sparse
    242   // entries. |truncate| is not part of this interface because a sparse entry
    243   // is not expected to be reused with new data. To delete the old data and
    244   // start again, or to reduce the total size of the stream data (which implies
    245   // that the content has changed), the whole entry should be doomed and
    246   // re-created.
    247   virtual int WriteSparseData(int64 offset, net::IOBuffer* buf, int buf_len,
    248                               CompletionCallback* completion_callback) = 0;
    249 
    250   // Returns information about the currently stored portion of a sparse entry.
    251   // |offset| and |len| describe a particular range that should be scanned to
    252   // find out if it is stored or not. |start| will contain the offset of the
    253   // first byte that is stored within this range, and the return value is the
    254   // minimum number of consecutive stored bytes. Note that it is possible that
    255   // this entry has stored more than the returned value. This method returns a
    256   // net error code whenever the request cannot be completed successfully. If
    257   // this method returns ERR_IO_PENDING, the |callback| will be invoked when the
    258   // operation completes, and |start| must remain valid until that point.
    259   virtual int GetAvailableRange(int64 offset, int len, int64* start,
    260                                 CompletionCallback* callback) = 0;
    261 
    262   // Returns true if this entry could be a sparse entry or false otherwise. This
    263   // is a quick test that may return true even if the entry is not really
    264   // sparse. This method doesn't modify the state of this entry (it will not
    265   // create sparse tracking data). GetAvailableRange or ReadSparseData can be
    266   // used to perfom a definitive test of wether an existing entry is sparse or
    267   // not, but that method may modify the current state of the entry (making it
    268   // sparse, for instance). The purpose of this method is to test an existing
    269   // entry, but without generating actual IO to perform a thorough check.
    270   virtual bool CouldBeSparse() const = 0;
    271 
    272   // Cancels any pending sparse IO operation (if any). The completion callback
    273   // of the operation in question will still be called when the operation
    274   // finishes, but the operation will finish sooner when this method is used.
    275   virtual void CancelSparseIO() = 0;
    276 
    277   // Returns OK if this entry can be used immediately. If that is not the
    278   // case, returns ERR_IO_PENDING and invokes the provided callback when this
    279   // entry is ready to use. This method always returns OK for non-sparse
    280   // entries, and returns ERR_IO_PENDING when a previous operation was cancelled
    281   // (by calling CancelSparseIO), but the cache is still busy with it. If there
    282   // is a pending operation that has not been cancelled, this method will return
    283   // OK although another IO operation cannot be issued at this time; in this
    284   // case the caller should just wait for the regular callback to be invoked
    285   // instead of using this method to provide another callback.
    286   //
    287   // Note that CancelSparseIO may have been called on another instance of this
    288   // object that refers to the same physical disk entry.
    289   // Note: This method is deprecated.
    290   virtual int ReadyForSparseIO(CompletionCallback* completion_callback) = 0;
    291 
    292  protected:
    293   virtual ~Entry() {}
    294 };
    295 
    296 }  // namespace disk_cache
    297 
    298 #endif  // NET_DISK_CACHE_DISK_CACHE_H_
    299