Page Speed Optimization Libraries  1.13.35.1
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
server_context.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 
19 
20 #ifndef NET_INSTAWEB_REWRITER_PUBLIC_SERVER_CONTEXT_H_
21 #define NET_INSTAWEB_REWRITER_PUBLIC_SERVER_CONTEXT_H_
22 
23 #include <cstddef>
24 #include <set>
25 #include <utility>
26 #include <vector>
27 
30 #include "net/instaweb/http/public/request_context.h"
34 #include "net/instaweb/util/public/property_cache.h"
54 
55 namespace pagespeed { namespace js { struct JsTokenizerPatterns; } }
56 
57 namespace net_instaweb {
58 
59 class AsyncFetch;
60 class CachePropertyStore;
61 class CriticalImagesFinder;
62 class CriticalSelectorFinder;
63 class RequestProperties;
64 class ExperimentMatcher;
65 class FileSystem;
66 class GoogleUrl;
67 class MessageHandler;
68 class NamedLock;
69 class NamedLockManager;
70 class PropertyStore;
71 class RewriteDriver;
72 class RewriteDriverFactory;
73 class RewriteDriverPool;
74 class RewriteFilter;
75 class RewriteOptions;
76 class RewriteOptionsManager;
77 class RewriteQuery;
78 class RewriteStats;
79 class SHA1Signature;
80 class Scheduler;
81 class StaticAssetManager;
82 class Statistics;
83 class ThreadSynchronizer;
84 class Timer;
85 class UrlNamer;
86 class UsageDataReporter;
87 class UserAgentMatcher;
88 
89 typedef RefCountedPtr<OutputResource> OutputResourcePtr;
90 typedef std::vector<OutputResourcePtr> OutputResourceVector;
91 
100  public:
101  typedef std::pair<RewriteOptions*, bool> OptionsBoolPair;
102 
104  static const int64 kGeneratedMaxAgeMs;
107 
111  static const char kResourceEtagValue[];
112  static const char kCacheKeyResourceNamePrefix[];
113 
114  explicit ServerContext(RewriteDriverFactory* factory);
115  virtual ~ServerContext();
116 
127  const ContentType* content_type, StringPiece charset,
128  StringPiece cache_control_suffix, ResponseHeaders* header) const;
129 
130  void set_filename_prefix(const StringPiece& file_prefix);
131  void set_statistics(Statistics* x) { statistics_ = x; }
132  void set_rewrite_stats(RewriteStats* x) { rewrite_stats_ = x; }
133  void set_lock_manager(NamedLockManager* x) { lock_manager_ = x; }
134  void set_enable_property_cache(bool enabled);
135  void set_message_handler(MessageHandler* x) { message_handler_ = x; }
136 
137  StringPiece filename_prefix() const { return file_prefix_; }
138  Statistics* statistics() const { return statistics_; }
139  NamedLockManager* lock_manager() const { return lock_manager_; }
140  RewriteDriverFactory* factory() const { return factory_; }
141  ThreadSynchronizer* thread_synchronizer() {
142  return thread_synchronizer_.get();
143  }
144  ExperimentMatcher* experiment_matcher() { return experiment_matcher_.get(); }
145 
154  void ApplyInputCacheControl(const ResourceVector& inputs,
155  ResponseHeaders* headers);
156 
158  bool IsPagespeedResource(const GoogleUrl& url) const;
159 
162  const RewriteFilter* FindFilterForDecoding(const StringPiece& id) const;
163 
165  bool DecodeUrlGivenOptions(const GoogleUrl& url,
166  const RewriteOptions* options,
167  const UrlNamer* url_namer,
168  StringVector* decoded_urls) const;
169 
170  void ComputeSignature(RewriteOptions* rewrite_options) const;
171 
173  Hasher* hasher() const { return hasher_; }
174  const Hasher* lock_hasher() const { return &lock_hasher_; }
175  const Hasher* contents_hasher() const { return &contents_hasher_; }
176  FileSystem* file_system() { return file_system_; }
177  void set_file_system(FileSystem* fs ) { file_system_ = fs; }
178  UrlNamer* url_namer() const { return url_namer_; }
179  void set_url_namer(UrlNamer* n) { url_namer_ = n; }
180  RewriteOptionsManager* rewrite_options_manager() const {
181  return rewrite_options_manager_.get();
182  }
183  SHA1Signature* signature() const { return signature_; }
185  void SetRewriteOptionsManager(RewriteOptionsManager* rom);
186  StaticAssetManager* static_asset_manager() const {
187  return static_asset_manager_;
188  }
189  void set_static_asset_manager(StaticAssetManager* manager) {
190  static_asset_manager_ = manager;
191  }
192  Scheduler* scheduler() const { return scheduler_; }
193  void set_scheduler(Scheduler* s) { scheduler_ = s; }
194  bool has_default_system_fetcher() const {
195  return default_system_fetcher_ != NULL;
196  }
199  UrlAsyncFetcher* DefaultSystemFetcher() { return default_system_fetcher_; }
200 
205  const RewriteOptions* options, const GoogleString& fragment,
207 
208  Timer* timer() const { return timer_; }
209 
211  void set_timer(Timer* timer) { timer_ = timer; }
212 
213  HTTPCache* http_cache() const { return http_cache_.get(); }
214  void set_http_cache(HTTPCache* x) { http_cache_.reset(x); }
215 
217  void MakePagePropertyCache(PropertyStore* property_store);
218 
219  PropertyCache* page_property_cache() const {
220  return page_property_cache_.get();
221  }
222 
223  const PropertyCache::Cohort* dom_cohort() const { return dom_cohort_; }
224  void set_dom_cohort(const PropertyCache::Cohort* c) { dom_cohort_ = c; }
225 
226  const PropertyCache::Cohort* beacon_cohort() const { return beacon_cohort_; }
227  void set_beacon_cohort(const PropertyCache::Cohort* c) { beacon_cohort_ = c; }
228 
229  const PropertyCache::Cohort* dependencies_cohort() const {
230  return dependencies_cohort_;
231  }
232  void set_dependencies_cohort(const PropertyCache::Cohort* c) {
233  dependencies_cohort_ = c;
234  }
235 
236  const PropertyCache::Cohort* fix_reflow_cohort() const {
237  return fix_reflow_cohort_;
238  }
239  void set_fix_reflow_cohort(const PropertyCache::Cohort* c) {
240  fix_reflow_cohort_ = c;
241  }
242 
248  return filesystem_metadata_cache_;
249  }
250  void set_filesystem_metadata_cache(CacheInterface* x) {
251  filesystem_metadata_cache_ = x;
252  }
253 
258  CacheInterface* metadata_cache() const { return metadata_cache_; }
259  void set_metadata_cache(CacheInterface* x) { metadata_cache_ = x; }
260 
261  CriticalImagesFinder* critical_images_finder() const {
262  return critical_images_finder_.get();
263  }
264  void set_critical_images_finder(CriticalImagesFinder* finder);
265 
266  CriticalSelectorFinder* critical_selector_finder() const {
267  return critical_selector_finder_.get();
268  }
269  void set_critical_selector_finder(CriticalSelectorFinder* finder);
270 
271  UserAgentMatcher* user_agent_matcher() const {
272  return user_agent_matcher_;
273  }
274  void set_user_agent_matcher(UserAgentMatcher* n) { user_agent_matcher_ = n; }
275 
276  SimpleRandom* simple_random() {
277  return &simple_random_;
278  }
279 
282  bool store_outputs_in_file_system() { return store_outputs_in_file_system_; }
283  void set_store_outputs_in_file_system(bool store) {
284  store_outputs_in_file_system_ = store;
285  }
286 
287  RewriteStats* rewrite_stats() const { return rewrite_stats_; }
288  MessageHandler* message_handler() const { return message_handler_; }
289 
294  NamedLock* MakeCreationLock(const GoogleString& name);
295 
297  void TryLockForCreation(NamedLock* creation_lock, Function* callback);
298 
302  void LockForCreation(NamedLock* creation_lock,
303  Sequence* worker, Function* callback);
304 
306  void set_hasher(Hasher* hasher) { hasher_ = hasher; }
307  void set_signature(SHA1Signature* signature) { signature_ = signature; }
308  void set_default_system_fetcher(UrlAsyncFetcher* fetcher) {
309  default_system_fetcher_ = fetcher;
310  }
311 
318  bool HandleBeacon(StringPiece body,
319  StringPiece user_agent,
320  const RequestContextPtr& request_context);
321 
327  RewriteOptions* global_options();
328 
331  const RewriteOptions* global_options() const;
332 
336  void reset_global_options(RewriteOptions* options);
337 
339  RewriteOptions* NewOptions();
340 
360  bool GetQueryOptions(const RequestContextPtr& request_context,
361  const RewriteOptions* domain_options,
362  GoogleUrl* request_url,
363  RequestHeaders* request_headers,
364  ResponseHeaders* response_headers,
365  RewriteQuery* rewrite_query);
366 
377  void GetRemoteOptions(RewriteOptions* remote_options, bool on_startup);
378 
383  RewriteOptions* GetCustomOptions(RequestHeaders* request_headers,
384  RewriteOptions* domain_options,
385  RewriteOptions* query_options);
386 
389  GoogleString GetRewriteOptionsSignatureHash(const RewriteOptions* options);
390 
399  RewriteDriver* NewRewriteDriver(const RequestContextPtr& request_ctx);
400 
403  RewriteDriver* NewRewriteDriverFromPool(
404  RewriteDriverPool* pool, const RequestContextPtr& request_ctx);
405 
419  RewriteDriver* NewUnmanagedRewriteDriver(
420  RewriteDriverPool* pool, RewriteOptions* options,
421  const RequestContextPtr& request_ctx);
422 
433  RewriteDriver* NewCustomRewriteDriver(
434  RewriteOptions* custom_options, const RequestContextPtr& request_ctx);
435 
448  void ReleaseRewriteDriver(RewriteDriver* rewrite_driver);
449 
450  ThreadSystem* thread_system() { return thread_system_; }
451  UsageDataReporter* usage_data_reporter() { return usage_data_reporter_; }
452 
456  shutting_down_.set_value(true);
457  }
458 
459  bool shutting_down() const {
460  return shutting_down_.value();
461  }
462 
472  void ShutDownDrivers(int64 cutoff_time_ms);
473 
495  const OutputResourcePtr& output) {
496  MergeNonCachingResponseHeaders(*input->response_headers(),
497  output->response_headers());
498  }
499 
501  void MergeNonCachingResponseHeaders(const ResponseHeaders& input_headers,
502  ResponseHeaders* output_headers);
503 
505  QueuedWorkerPool* html_workers() { return html_workers_; }
506 
508  QueuedWorkerPool* rewrite_workers() { return rewrite_workers_; }
509 
513  return low_priority_rewrite_workers_;
514  }
515 
520 
523  void InitWorkers();
524 
526  virtual void PostInitHook();
527 
530  static bool IsExcludedAttribute(const char* attribute);
531 
540  return response_headers_finalized_;
541  }
542  void set_response_headers_finalized(bool x) {
543  response_headers_finalized_ = x;
544  }
545 
550  return available_rewrite_drivers_.get();
551  }
552 
554  const GoogleString& hostname() const {
555  return hostname_;
556  }
557  void set_hostname(const GoogleString& x) {
558  hostname_ = x;
559  }
560 
561  void set_central_controller(std::shared_ptr<CentralController> controller) {
562  central_controller_ = controller;
563  }
564 
565  CentralController* central_controller() {
566  return central_controller_.get();
567  }
568 
571  void AddOriginalContentLengthHeader(const ResourceVector& inputs,
572  ResponseHeaders* headers);
573 
576  virtual void ApplySessionFetchers(const RequestContextPtr& req,
577  RewriteDriver* driver);
578 
589  virtual bool ProxiesHtml() const = 0;
590 
592  RequestProperties* NewRequestProperties();
593 
596  void DeleteCacheOnDestruction(CacheInterface* cache);
597 
598  void set_cache_property_store(CachePropertyStore* p);
599 
602  void set_decoding_driver(RewriteDriver* rd) { decoding_driver_ = rd; }
603 
605  virtual PropertyStore* CreatePropertyStore(CacheInterface* cache_backend);
606 
611  const GoogleString& cohort_name,
612  PropertyCache* pcache);
613 
619  const GoogleString& cohort_name,
620  CacheInterface* cache,
621  PropertyCache* pcache);
622 
626 
627  const pagespeed::js::JsTokenizerPatterns* js_tokenizer_patterns() const {
628  return js_tokenizer_patterns_;
629  }
630 
631  enum Format {
632  kFormatAsHtml,
633  kFormatAsJson
634  };
635 
638  void ShowCacheHandler(Format format, StringPiece url, StringPiece ua,
639  bool should_delete, AsyncFetch* fetch,
640  RewriteOptions* options);
641 
645  static GoogleString ShowCacheForm(StringPiece user_agent);
646 
652  virtual GoogleString FormatOption(StringPiece option_name, StringPiece args);
653 
654  protected:
658  additional_driver_pools_.push_back(pool);
659  }
660 
661  private:
662  friend class ServerContextTest;
663  typedef std::set<RewriteDriver*> RewriteDriverSet;
664 
666  void ReleaseRewriteDriverImpl(RewriteDriver* rewrite_driver);
667 
670  void ApplyRemoteConfig(const GoogleString& config, RewriteOptions* options);
672  void ApplyConfigLine(StringPiece linesp, RewriteOptions* options);
677  GoogleString FetchRemoteConfig(const GoogleString& url, int64 timeout_ms,
678  bool on_startup,
679  RequestContextPtr request_ctx);
680 
682  ThreadSystem* thread_system_;
683  RewriteStats* rewrite_stats_;
684  GoogleString file_prefix_;
685  FileSystem* file_system_;
686  UrlNamer* url_namer_;
687  scoped_ptr<RewriteOptionsManager> rewrite_options_manager_;
688  UserAgentMatcher* user_agent_matcher_;
689  Scheduler* scheduler_;
690  UrlAsyncFetcher* default_system_fetcher_;
691  Hasher* hasher_;
692  SHA1Signature* signature_;
693  scoped_ptr<CriticalImagesFinder> critical_images_finder_;
694  scoped_ptr<CriticalSelectorFinder> critical_selector_finder_;
695 
699  MD5Hasher lock_hasher_;
700 
703  MD5Hasher contents_hasher_;
704 
705  Statistics* statistics_;
706 
707  Timer* timer_;
708  scoped_ptr<HTTPCache> http_cache_;
709  scoped_ptr<PropertyCache> page_property_cache_;
710  CacheInterface* filesystem_metadata_cache_;
711  CacheInterface* metadata_cache_;
712 
713  bool store_outputs_in_file_system_;
714  bool response_headers_finalized_;
715  bool enable_property_cache_;
716 
717  NamedLockManager* lock_manager_;
718  MessageHandler* message_handler_;
719 
720  const PropertyCache::Cohort* dom_cohort_;
721  const PropertyCache::Cohort* beacon_cohort_;
722  const PropertyCache::Cohort* dependencies_cohort_;
723  const PropertyCache::Cohort* fix_reflow_cohort_;
724 
730  scoped_ptr<RewriteDriverPool> available_rewrite_drivers_;
731 
733  std::vector<RewriteDriverPool*> additional_driver_pools_;
734 
740  RewriteDriverSet active_rewrite_drivers_;
741 
749  bool trying_to_cleanup_rewrite_drivers_;
750  RewriteDriverSet deferred_release_rewrite_drivers_;
751  bool shutdown_drivers_called_;
752 
755  RewriteDriverFactory* factory_;
756 
757  scoped_ptr<AbstractMutex> rewrite_drivers_mutex_;
758 
761  scoped_ptr<RewriteOptions> base_class_options_;
762 
766  RewriteDriver* decoding_driver_;
767 
768  QueuedWorkerPool* html_workers_;
769  QueuedWorkerPool* rewrite_workers_;
770  QueuedWorkerPool* low_priority_rewrite_workers_;
771 
772  AtomicBool shutting_down_;
773 
775  StaticAssetManager* static_asset_manager_;
776 
779  scoped_ptr<ThreadSynchronizer> thread_synchronizer_;
780 
782  scoped_ptr<ExperimentMatcher> experiment_matcher_;
783 
784  UsageDataReporter* usage_data_reporter_;
785 
787  GoogleString hostname_;
788 
791  SimpleRandom simple_random_;
793  const pagespeed::js::JsTokenizerPatterns* js_tokenizer_patterns_;
794 
795  scoped_ptr<CachePropertyStore> cache_property_store_;
796 
797  std::shared_ptr<CentralController> central_controller_;
798 
799 
800 };
801 
802 }
803 
804 #endif
Definition: url_namer.h:38
const PropertyCache::Cohort * AddCohort(const GoogleString &cohort_name, PropertyCache *pcache)
Definition: atomic_bool.h:31
Definition: md5_hasher.h:28
Abstract interface for a cache.
Definition: cache_interface.h:32
Implementation class of Signature, using HMAC-SHA1 for signing.
Definition: sha1_signature.h:32
const CacheInterface * pcache_cache_backend()
void MergeNonCachingResponseHeaders(const ResourcePtr &input, const OutputResourcePtr &output)
Definition: server_context.h:494
void SetDefaultLongCacheHeaders(const ContentType *content_type, StringPiece charset, StringPiece cache_control_suffix, ResponseHeaders *header) const
Definition: property_cache.h:186
bool GetQueryOptions(const RequestContextPtr &request_context, const RewriteOptions *domain_options, GoogleUrl *request_url, RequestHeaders *request_headers, ResponseHeaders *response_headers, RewriteQuery *rewrite_query)
Adds property-semantics to a raw cache API.
Definition: property_cache.h:180
Definition: static_asset_manager.h:48
Definition: property_store.h:41
RewriteOptions * GetCustomOptions(RequestHeaders *request_headers, RewriteOptions *domain_options, RewriteOptions *query_options)
virtual void ApplySessionFetchers(const RequestContextPtr &req, RewriteDriver *driver)
Definition: named_lock_manager.h:82
virtual bool ProxiesHtml() const =0
Base class for implementations of monitoring statistics.
Definition: statistics.h:342
Definition: user_agent_matcher.h:43
void set_shutting_down()
Definition: server_context.h:455
Definition: simple_random.h:35
RewriteDriver * NewRewriteDriverFromPool(RewriteDriverPool *pool, const RequestContextPtr &request_ctx)
RewriteDriverPool * standard_rewrite_driver_pool()
Definition: server_context.h:549
virtual CacheUrlAsyncFetcher * CreateCustomCacheFetcher(const RewriteOptions *options, const GoogleString &fragment, CacheUrlAsyncFetcher::AsyncOpHooks *hooks, UrlAsyncFetcher *fetcher)
void set_decoding_driver(RewriteDriver *rd)
Definition: server_context.h:602
bool IsPagespeedResource(const GoogleUrl &url) const
Is this URL a ref to a Pagespeed resource?
Read/write API for HTTP response headers.
Definition: response_headers.h:37
void TryLockForCreation(NamedLock *creation_lock, Function *callback)
Attempt to obtain a named lock without blocking. Return true if we do so.
void set_timer(Timer *timer)
Note: doesn't take ownership.
Definition: server_context.h:211
void ShowCacheHandler(Format format, StringPiece url, StringPiece ua, bool should_delete, AsyncFetch *fetch, RewriteOptions *options)
void LockForCreation(NamedLock *creation_lock, Sequence *worker, Function *callback)
NamedLock * MakeCreationLock(const GoogleString &name)
const RewriteFilter * FindFilterForDecoding(const StringPiece &id) const
RewriteDriver * NewUnmanagedRewriteDriver(RewriteDriverPool *pool, RewriteOptions *options, const RequestContextPtr &request_ctx)
virtual void PostInitHook()
To set up AdminSite for SystemServerContext.
Definition: rewrite_driver_pool.h:34
Definition: scoped_ptr.h:30
QueuedWorkerPool * html_workers()
Pool of worker-threads that can be used to handle html-parsing.
Definition: server_context.h:505
static const char kResourceEtagValue[]
Definition: server_context.h:111
static GoogleString ShowCacheForm(StringPiece user_agent)
virtual GoogleString FormatOption(StringPiece option_name, StringPiece args)
bool DecodeUrlGivenOptions(const GoogleUrl &url, const RewriteOptions *options, const UrlNamer *url_namer, StringVector *decoded_urls) const
See RewriteDriver::DecodeUrl.
static const int64 kCacheTtlForMismatchedContentMs
Short lifetime for generated resources fetched with mismatching hash.
Definition: server_context.h:106
std::string GoogleString
PAGESPEED_KERNEL_BASE_STRING_H_.
Definition: string.h:24
RequestProperties * NewRequestProperties()
Makes a new RequestProperties.
void SetRewriteOptionsManager(RewriteOptionsManager *rom)
Takes ownership of RewriteOptionsManager.
void GetRemoteOptions(RewriteOptions *remote_options, bool on_startup)
static bool IsExcludedAttribute(const char *attribute)
Definition: queued_worker_pool.h:50
QueuedWorkerPool * low_priority_rewrite_workers()
Definition: server_context.h:512
Definition: js_tokenizer.h:194
GoogleString GetRewriteOptionsSignatureHash(const RewriteOptions *options)
bool store_outputs_in_file_system()
Definition: server_context.h:282
bool response_headers_finalized() const
Definition: server_context.h:539
Definition: cache_url_async_fetcher.h:61
void reset_global_options(RewriteOptions *options)
Definition: file_system.h:76
void MakePagePropertyCache(PropertyStore *property_store)
Creates PagePropertyCache object with the provided PropertyStore object.
RewriteOptions * NewOptions()
Makes a new, empty set of RewriteOptions.
Definition: rewrite_driver.h:100
void ManageRewriteDriverPool(RewriteDriverPool *pool)
Definition: server_context.h:657
Definition: cache_url_async_fetcher.h:65
Definition: server_context.h:99
void ApplyInputCacheControl(const ResourceVector &inputs, ResponseHeaders *headers)
void DeleteCacheOnDestruction(CacheInterface *cache)
Definition: content_type.h:31
QueuedWorkerPool * rewrite_workers()
Pool of worker-threads that can be used to handle resource rewriting.
Definition: server_context.h:508
CacheInterface * metadata_cache() const
Definition: server_context.h:258
Definition: usage_data_reporter.h:35
const GoogleString & hostname() const
Returns the current server hostname.
Definition: server_context.h:554
Definition: thread_system.h:40
Definition: message_handler.h:39
void ReleaseRewriteDriver(RewriteDriver *rewrite_driver)
Hasher * hasher() const
Definition: server_context.h:173
bool HandleBeacon(StringPiece body, StringPiece user_agent, const RequestContextPtr &request_context)
Definition: scheduler.h:47
CacheInterface * filesystem_metadata_cache() const
Definition: server_context.h:247
UrlAsyncFetcher * DefaultSystemFetcher()
Definition: server_context.h:199
void AddOriginalContentLengthHeader(const ResourceVector &inputs, ResponseHeaders *headers)
Collects a few specific statistics variables related to Rewriting.
Definition: rewrite_stats.h:35
Definition: rewrite_options.h:84
void ShutDownDrivers(int64 cutoff_time_ms)
RewriteOptions * global_options()
Timer interface, made virtual so it can be mocked for tests.
Definition: timer.h:27
static const int64 kGeneratedMaxAgeMs
The lifetime for cache-extended generated resources, in milliseconds.
Definition: server_context.h:104
RewriteDriver * NewCustomRewriteDriver(RewriteOptions *custom_options, const RequestContextPtr &request_ctx)
Definition: hasher.h:30
void set_hasher(Hasher *hasher)
Setters should probably only be used in testing.
Definition: server_context.h:306
RewriteDriver * NewRewriteDriver(const RequestContextPtr &request_ctx)
Definition: url_async_fetcher.h:33
virtual PropertyStore * CreatePropertyStore(CacheInterface *cache_backend)
Creates CachePropertyStore object which will be used by PagePropertyCache.
Definition: http_cache.h:67
const PropertyCache::Cohort * AddCohortWithCache(const GoogleString &cohort_name, CacheInterface *cache, PropertyCache *pcache)
Definition: rewrite_driver_factory.h:70