Page Speed Optimization Libraries  1.13.35.1
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
http_cache.h
Go to the documentation of this file.
1 /*
2  * Copyright 2010 Google Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http:///www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
18 
19 #ifndef NET_INSTAWEB_HTTP_PUBLIC_HTTP_CACHE_H_
20 #define NET_INSTAWEB_HTTP_PUBLIC_HTTP_CACHE_H_
21 
22 #include "base/logging.h"
25 #include "net/instaweb/http/public/request_context.h"
32 #include "pagespeed/kernel/cache/cache_interface.h"
37 
38 namespace net_instaweb {
39 
40 class Hasher;
41 class MessageHandler;
42 class Statistics;
43 class Timer;
44 class Variable;
45 
67 class HTTPCache {
68  public:
70  static const char kCacheTimeUs[];
71  static const char kCacheHits[];
72  static const char kCacheMisses[];
73  static const char kCacheBackendHits[];
74  static const char kCacheBackendMisses[];
75  static const char kCacheFallbacks[];
76  static const char kCacheExpirations[];
77  static const char kCacheInserts[];
78  static const char kCacheDeletes[];
79 
81  static const char kEtagPrefix[];
82 
84  static GoogleString FormatEtag(StringPiece hash);
85 
87  HTTPCache(CacheInterface* cache, Timer* timer, Hasher* hasher,
88  Statistics* stats);
89  ~HTTPCache();
90 
91  enum FindResultClassification {
92  kFound,
93  kNotFound,
94  kRecentFailure,
95  };
96 
98  struct FindResult {
99  FindResult()
100  : status(kNotFound), failure_details(kFetchStatusNotSet) {}
101 
102  FindResult(FindResultClassification in_status,
103  FetchResponseStatus in_failure_details)
104  : status(in_status), failure_details(in_failure_details) {}
105 
106  bool operator==(const FindResult& other) const {
107  return status == other.status &&
109  }
110 
111  bool operator!=(const FindResult& other) const {
112  return !(*this == other);
113  }
114 
115  FindResultClassification status;
116 
123  };
124 
125  void set_hasher(Hasher* hasher) { hasher_ = hasher; }
126 
132  class Callback {
133  public:
141  explicit Callback(const RequestContextPtr& request_ctx)
142  : response_headers_(NULL),
143  owns_response_headers_(false),
144  request_ctx_(request_ctx),
145  cache_level_(0),
146  is_background_(false) {
147  }
148 
151  Callback(const RequestContextPtr& request_ctx,
152  RequestHeaders::Properties req_properties)
153  : response_headers_(NULL),
154  req_properties_(req_properties),
155  owns_response_headers_(false),
156  request_ctx_(request_ctx),
157  cache_level_(0),
158  is_background_(false) {
159  }
160 
161  virtual ~Callback();
162  virtual void Done(FindResult find_result) = 0;
172  virtual bool IsCacheValid(const GoogleString& key,
173  const ResponseHeaders& headers) {
174  return true;
175  }
176 
184  virtual bool IsFresh(const ResponseHeaders& headers) { return true; }
185 
189  virtual int64 OverrideCacheTtlMs(const GoogleString& key) { return -1; }
190 
196  void ReportLatencyMs(int64 latency_ms);
197 
206  virtual ResponseHeaders::VaryOption RespectVaryOnResources() const = 0;
207 
210  HTTPValue* http_value() { return &http_value_; }
211  ResponseHeaders* response_headers() {
212  if (response_headers_ == NULL) {
213  response_headers_ = new ResponseHeaders(request_ctx_->options());
214  owns_response_headers_ = true;
215  }
216  return response_headers_;
217  }
218  const ResponseHeaders* response_headers() const {
219  return const_cast<Callback*>(this)->response_headers();
220  }
221  void set_response_headers(ResponseHeaders* headers) {
222  DCHECK(!owns_response_headers_);
223  if (owns_response_headers_) {
224  delete response_headers_;
225  }
226  response_headers_ = headers;
227  owns_response_headers_ = false;
228  }
229  HTTPValue* fallback_http_value() { return &fallback_http_value_; }
230 
231  const RequestContextPtr& request_context() { return request_ctx_; }
232  void set_is_background(bool is_background) {
233  is_background_ = is_background;
234  }
235 
236  RequestHeaders::Properties req_properties() const {
237  return req_properties_;
238  }
239 
240  private:
241  HTTPValue http_value_;
244  HTTPValue fallback_http_value_;
245  ResponseHeaders* response_headers_;
246  RequestHeaders::Properties req_properties_;
247  bool owns_response_headers_;
248  RequestContextPtr request_ctx_;
249  int cache_level_;
250  bool is_background_;
251 
252 
253  };
254 
256  void SetIgnoreFailurePuts();
257 
260  void Find(const GoogleString& key,
261  const GoogleString& fragment,
262  MessageHandler* handler,
263  Callback* callback);
264 
267  void Put(const GoogleString& key,
268  const GoogleString& fragment,
269  RequestHeaders::Properties req_properties,
270  const HttpOptions& http_options,
271  HTTPValue* value,
272  MessageHandler* handler);
273 
278  void Put(const GoogleString& key,
279  const GoogleString& fragment,
280  RequestHeaders::Properties req_properties,
282  ResponseHeaders::VaryOption respect_vary_on_resources,
283  ResponseHeaders* headers,
284  const StringPiece& content, MessageHandler* handler);
285 
287  void Delete(const GoogleString& key, const GoogleString& fragment);
288 
289  void set_force_caching(bool force) { force_caching_ = force; }
290  bool force_caching() const { return force_caching_; }
291  void set_disable_html_caching_on_https(bool x) {
292  disable_html_caching_on_https_ = x;
293  }
294  Timer* timer() const { return timer_; }
295  CacheInterface* cache() { return cache_; }
296 
301  void RememberFailure(const GoogleString& key,
302  const GoogleString& fragment,
303  FetchResponseStatus the_failure,
304  MessageHandler* handler);
305 
310  bool IsCacheableContentLength(ResponseHeaders* headers) const;
315  bool IsCacheableBodySize(int64 body_size) const;
316 
318  static void InitStats(Statistics* statistics);
319 
327  bool IsExpired(const ResponseHeaders& headers);
328  bool IsExpired(const ResponseHeaders& headers, int64 now_ms);
329 
331  Variable* cache_time_us() { return cache_time_us_; }
332  Variable* cache_hits() { return cache_hits_; }
333  Variable* cache_misses() { return cache_misses_; }
334  Variable* cache_fallbacks() { return cache_fallbacks_; }
335  Variable* cache_expirations() { return cache_expirations_; }
336  Variable* cache_inserts() { return cache_inserts_; }
337  Variable* cache_deletes() { return cache_deletes_; }
338 
339  int failure_caching_ttl_sec(FetchResponseStatus kind) const {
340  return remember_failure_policy_.ttl_sec_for_status[kind];
341  }
342 
343  void set_failure_caching_ttl_sec(FetchResponseStatus kind, int ttl_sec) {
344  remember_failure_policy_.ttl_sec_for_status[kind] = ttl_sec;
345  }
346 
347  int max_cacheable_response_content_length() {
348  return max_cacheable_response_content_length_;
349  }
350 
351  void set_max_cacheable_response_content_length(int64 value);
352 
355  void set_cache_levels(int levels) { cache_levels_ = levels; }
356  int cache_levels() const { return cache_levels_; }
357 
360  void SetCompressionLevel(int level) {
361  if (level >= -1 && level <= 9) {
362  compression_level_ = level;
363  } else {
364  LOG(INFO) << "Invalid compression level specified, defaulting to -1";
365  compression_level_ = -1;
366  }
367  }
368  int compression_level() const { return compression_level_; }
369 
370  GoogleString Name() const { return FormatName(cache_->Name()); }
371  static GoogleString FormatName(StringPiece cache);
372 
373  GoogleString CompositeKey(StringPiece key, StringPiece fragment) const {
374  DCHECK(fragment.find("/") == StringPiece::npos);
375 
378  return StrCat(version_prefix_, fragment, fragment.empty() ? "" : "/", key);
379  }
380 
381  private:
382  friend class HTTPCacheCallback;
383  FRIEND_TEST(HTTPCacheTest, UpdateVersion);
384 
387  void PutInternal(bool preserve_response_headers,
388  const GoogleString& key,
389  const GoogleString& fragment,
390  int64 start_us,
391  HTTPValue* value,
392  ResponseHeaders* headers,
393  MessageHandler* handler);
394  void DeleteInternal(const GoogleString& key_fragment);
395 
397  void SetVersion(int version_number);
398  void set_version_prefix(StringPiece version_prefix) {
399  version_prefix.CopyToString(&version_prefix_);
400  }
401 
402  bool MayCacheUrl(const GoogleString& url, const ResponseHeaders& headers);
407  HTTPValue* ApplyHeaderChangesForPut(
408  int64 start_us, const StringPiece* content, ResponseHeaders* headers,
409  HTTPValue* value, MessageHandler* handler);
410  void UpdateStats(const GoogleString& key, const GoogleString& fragment,
411  CacheInterface::KeyState backend_state, FindResult result,
412  bool has_fallback, bool is_expired, MessageHandler* handler);
413  void RememberFetchFailedOrNotCacheableHelper(
414  const GoogleString& key, const GoogleString& fragment,
415  MessageHandler* handler, HttpStatus::Code code, int64 ttl_sec);
416 
417  CacheInterface* cache_;
418  Timer* timer_;
419  Hasher* hasher_;
420  bool force_caching_;
422  bool disable_html_caching_on_https_;
423 
424  int cache_levels_;
425  int compression_level_;
426 
428  Variable* cache_time_us_;
430  Variable* cache_hits_;
432  Variable* cache_misses_;
435  Variable* cache_backend_hits_;
437  Variable* cache_backend_misses_;
438  Variable* cache_fallbacks_;
439  Variable* cache_expirations_;
440  Variable* cache_inserts_;
441  Variable* cache_deletes_;
442 
443  GoogleString name_;
444  HttpCacheFailurePolicy remember_failure_policy_;
445  int64 max_cacheable_response_content_length_;
446  AtomicBool ignore_failure_puts_;
447 
448  GoogleString version_prefix_;
449 
450 
451 };
452 
453 }
454 
455 #endif
Callback(const RequestContextPtr &request_ctx, RequestHeaders::Properties req_properties)
Definition: http_cache.h:151
Callback(const RequestContextPtr &request_ctx)
Definition: http_cache.h:141
virtual bool IsFresh(const ResponseHeaders &headers)
Definition: http_cache.h:184
Abstract interface for a cache.
Definition: cache_interface.h:32
When a lookup is done in the HTTP Cache, it returns one of these values.
Definition: http_cache.h:98
Definition: http_value.h:38
static const char kEtagPrefix[]
The prefix used for Etags.
Definition: http_cache.h:81
Definition: request_headers.h:43
Definition: statistics.h:43
void SetCompressionLevel(int level)
Definition: http_cache.h:360
void RememberFailure(const GoogleString &key, const GoogleString &fragment, FetchResponseStatus the_failure, MessageHandler *handler)
Base class for implementations of monitoring statistics.
Definition: statistics.h:342
Variable * cache_time_us()
Stats for the HTTP cache.
Definition: http_cache.h:331
GoogleString CompositeKey(StringPiece key, StringPiece fragment) const
Definition: http_cache.h:373
FetchResponseStatus failure_details
Definition: http_cache.h:122
Read/write API for HTTP response headers.
Definition: response_headers.h:37
void SetIgnoreFailurePuts()
Makes the cache ignore put requests that do not record successes.
void Find(const GoogleString &key, const GoogleString &fragment, MessageHandler *handler, Callback *callback)
static const char kCacheTimeUs[]
Names of statistics variables: exported for tests.
Definition: http_cache.h:70
bool IsCacheableBodySize(int64 body_size) const
KeyState
Definition: cache_interface.h:34
bool IsExpired(const ResponseHeaders &headers)
std::string GoogleString
PAGESPEED_KERNEL_BASE_STRING_H_.
Definition: string.h:24
int ttl_sec_for_status[8]
Definition: http_cache_failure.h:51
void Delete(const GoogleString &key, const GoogleString &fragment)
Deletes an element in the cache.
virtual bool IsCacheValid(const GoogleString &key, const ResponseHeaders &headers)
Definition: http_cache.h:172
static void InitStats(Statistics *statistics)
Initialize statistics variables for the cache.
bool IsCacheableContentLength(ResponseHeaders *headers) const
void ReportLatencyMs(int64 latency_ms)
void Put(const GoogleString &key, const GoogleString &fragment, RequestHeaders::Properties req_properties, const HttpOptions &http_options, HTTPValue *value, MessageHandler *handler)
HTTPValue * http_value()
Definition: http_cache.h:210
HTTPCache(CacheInterface *cache, Timer *timer, Hasher *hasher, Statistics *stats)
Does not take ownership of any inputs.
Definition: message_handler.h:39
Definition: http_cache.h:132
FetchResponseStatus
Definition: http_cache_failure.h:33
virtual GoogleString Name() const =0
virtual int64 OverrideCacheTtlMs(const GoogleString &key)
Definition: http_cache.h:189
void set_cache_levels(int levels)
Definition: http_cache.h:355
virtual ResponseHeaders::VaryOption RespectVaryOnResources() const =0
Timer interface, made virtual so it can be mocked for tests.
Definition: timer.h:27
Definition: hasher.h:30
Definition: http_cache.h:67
static GoogleString FormatEtag(StringPiece hash)
Function to format etags.