Page Speed Optimization Libraries  1.13.35.1
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
rewrite_context.h
Go to the documentation of this file.
1 /*
2  * Copyright 2011 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_REWRITER_PUBLIC_REWRITE_CONTEXT_H_
20 #define NET_INSTAWEB_REWRITER_PUBLIC_REWRITE_CONTEXT_H_
21 
22 #include <set>
23 #include <vector>
24 
26 #include "net/instaweb/rewriter/cached_result.pb.h"
27 #include "net/instaweb/rewriter/input_info.pb.h"
44 
45 namespace net_instaweb {
46 
47 class AsyncFetch;
48 class MessageHandler;
49 class NamedLock;
50 class RequestTrace;
51 class RewriteDriver;
52 class RewriteOptions;
53 class Statistics;
54 class Variable;
55 class FreshenMetadataUpdateManager;
56 
57 enum class RenderOp {
58  kDontRender,
59  kRenderOnlyCspWarning,
60  kRender
61 };
62 
156  public:
157  typedef std::vector<InputInfo*> InputInfoStarVector;
158  static const char kNumRewritesAbandonedForLockContention[];
159  static const char kNumDeadlineAlarmInvocations[];
160  static const char kHashMismatchMessage[];
161 
166  : cache_ok(false),
167  can_revalidate(false),
168  useable_cache_content(false),
169  is_stale_rewrite(false),
170  partitions(new OutputPartitions) {}
171 
172  bool cache_ok;
173  bool can_revalidate;
174  bool useable_cache_content;
175  bool is_stale_rewrite;
176  InputInfoStarVector revalidate;
177  scoped_ptr<OutputPartitions> partitions;
178  };
179 
182  public:
184  virtual ~CacheLookupResultCallback();
185  virtual void Done(const GoogleString& cache_key,
186  CacheLookupResult* result) = 0;
187  private:
188 
189  };
190 
193  RewriteContext(RewriteDriver* driver,
195  ResourceContext* resource_context);
196  virtual ~RewriteContext();
197 
202  int num_slots() const { return slots_.size(); }
203  ResourceSlotPtr slot(int index) const { return slots_[index]; }
204 
207  int num_outputs() const { return outputs_.size(); }
208  OutputResourcePtr output(int i) const { return outputs_[i]; }
209 
212  int num_output_partitions() const;
213  const CachedResult* output_partition(int i) const;
214  CachedResult* mutable_output_partition(int i);
215 
218  bool chained() const { return chained_; }
219 
223  void AddSlot(const ResourceSlotPtr& slot);
224 
227  void RemoveLastSlot();
228 
234  void AddNestedContext(RewriteContext* context);
235 
236  void CallFetchInputs();
237  void CallLockFailed();
238  void CallStartFetchImpl();
239 
250  void Initiate();
251 
257  bool Fetch(const OutputResourcePtr& output_resource,
258  AsyncFetch* fetch,
259  MessageHandler* message_handler);
260 
263  bool slow() const { return slow_; }
264 
266  bool is_metadata_cache_miss() const { return is_metadata_cache_miss_; }
267 
269  bool has_parent() const { return parent_ != NULL; }
270 
273  bool IsNestedIn(StringPiece id) const;
274 
277  void CheckNotFrozen();
278 
280  RewriteContext* parent() { return parent_; }
281  const RewriteContext* parent() const { return parent_; }
282 
284  int num_nested() const { return nested_.size(); }
285  RewriteContext* nested(int i) const { return nested_[i]; }
286 
287  RewriteDriver* Driver() const {
288  return driver_;
289  }
290 
292  void set_force_rewrite(bool x) { force_rewrite_ = x; }
293 
294  bool rewrite_uncacheable() const { return rewrite_uncacheable_; }
295  void set_rewrite_uncacheable(bool rewrite_uncacheable) {
296  rewrite_uncacheable_ = rewrite_uncacheable;
297  }
298 
299  const ResourceContext* resource_context() const {
300  return resource_context_.get();
301  }
302 
304  GoogleString ToString() const;
305  GoogleString ToStringWithPrefix(StringPiece prefix) const;
306 
308  static void InitStats(Statistics* stats);
309 
310  protected:
311  typedef std::vector<GoogleUrl*> GoogleUrlStarVector;
312 
317 
321  ServerContext* FindServerContext() const;
322  const RewriteOptions* Options() const;
323 
324  OutputPartitions* partitions() { return partitions_.get(); }
325 
328  void AddRecheckDependency();
329 
333  virtual bool OptimizationOnly() const { return true; }
334 
352  virtual bool Partition(OutputPartitions* partitions,
353  OutputResourceVector* outputs);
354 
360  virtual void PartitionAsync(OutputPartitions* partitions,
361  OutputResourceVector* outputs);
362 
366  void PartitionDone(RewriteResult result);
367 
371 
390  virtual void Rewrite(int partition_index,
391  CachedResult* partition,
392  const OutputResourcePtr& output) = 0;
393 
398  void RewriteDone(RewriteResult result, int partition_index);
399 
409  virtual bool SendFallbackResponse(StringPiece output_url_base,
410  StringPiece contents,
412  MessageHandler* handler);
413 
417  void StartNestedTasks();
418 
423  virtual void Harvest();
424 
430  virtual bool PolicyPermitsRendering() const = 0;
431 
433  bool AreOutputsAllowedByCsp(CspDirective role) const;
434 
446  virtual void Render();
447 
458  virtual void WillNotRender();
459 
463  virtual void Cancel();
464 
467 
474  virtual const UrlSegmentEncoder* encoder() const;
475 
478  virtual GoogleString CacheKeySuffix() const;
479 
487  const ResourceContext* context) const {
488  return "";
489  }
490 
495  virtual void EncodeUserAgentIntoResourceContext(ResourceContext* context) {}
496 
498  virtual const char* id() const = 0;
499 
508  virtual OutputResourceKind kind() const = 0;
509 
513 
516  void AttachDependentRequestTrace(const StringPiece& label);
517 
521  RequestTrace* dependent_request_trace() { return dependent_request_trace_; }
522 
525  void TracePrintf(const char* fmt, ...);
526 
534 
544  virtual void StartFetchReconstruction();
545 
551  void DetachFetch();
552 
557  virtual bool DecodeFetchUrls(const OutputResourcePtr& output_resource,
558  MessageHandler* message_handler,
559  GoogleUrlStarVector* url_vector);
560 
565  virtual void FixFetchFallbackHeaders(const CachedResult& cached_result,
566  ResponseHeaders* headers);
567 
570  virtual void FetchCallbackDone(bool success);
571 
576  virtual void FetchTryFallback(const GoogleString& url,
577  const StringPiece& hash);
578 
580  void Freshen();
581 
582  bool notify_driver_on_fetch_done() const {
583  return notify_driver_on_fetch_done_;
584  }
585  void set_notify_driver_on_fetch_done(bool value) {
586  notify_driver_on_fetch_done_ = value;
587  }
588 
590  AsyncFetch* async_fetch();
591 
593  bool FetchContextDetached();
594 
596  MessageHandler* fetch_message_handler();
597 
599  bool stale_rewrite() const { return stale_rewrite_; }
600 
604  virtual int64 GetRewriteDeadlineAlarmMs() const;
605 
607  virtual bool CreationLockBeforeStartFetch() const;
608 
616  virtual bool FailOnHashMismatch() const { return false; }
617 
621  virtual bool ScheduleViaCentralController() { return false; }
622 
629  return false;
630  }
631 
634  void ObtainLockForCreation(ServerContext* server_context, Function* callback);
635 
640  void ReleaseCreationLock(bool succeeded);
641 
646  OutputResourcePtr output_resource,
647  const GoogleUrl& gurl,
648  RewriteContext* rewrite_context,
649  RewriteDriver* driver,
650  GoogleString* error_out,
651  CacheLookupResultCallback* callback);
652 
653  private:
654  class OutputCacheCallback;
655  class WriteIfChanged;
656  class LookupMetadataForOutputResourceCallback;
657  class HTTPCacheCallback;
658  class ResourceCallbackUtils;
659  class ResourceFetchCallback;
660  class ResourceReconstructCallback;
661  class ResourceRevalidateCallback;
662  class InvokeRewriteFunction;
663  class RewriteFreshenCallback;
664  class TryLockFunction;
665  friend class RewriteDriver;
666 
667  typedef std::set<RewriteContext*> ContextSet;
668 
672  enum FallbackCondition {
673  kFallbackDiscretional,
674  kFallbackEmergency
676  };
678 
680  void Start();
681  void SetPartitionKey();
682  void StartFetch();
683  void StartFetchImpl();
684  void CancelFetch();
685  void OutputCacheDone(CacheLookupResult* cache_result);
686  void OutputCacheHit(bool write_partitions);
687  void OutputCacheRevalidate(const InputInfoStarVector& to_revalidate);
688  void OutputCacheMiss();
689  void ResourceFetchDone(bool success, ResourcePtr resource, int slot_index);
690  void ResourceRevalidateDone(InputInfo* input_info, bool success);
691  void LogMetadataCacheInfo(bool cache_ok, bool can_revalidate);
692 
697  void RepeatedSuccess(const RewriteContext* primary);
698  void RepeatedFailure();
699 
708  void Finalize();
709 
711  NamedLock* Lock();
712 
715  GoogleString LockName() const;
716 
726  void FetchInputs();
727 
729  void LockFailed();
730 
733  bool CreateOutputResourceFromContent(const CachedResult& cached_result,
734  const ResponseHeaders& response_headers,
735  StringPiece content,
736  OutputResourcePtr* output_resource);
737 
740  bool IsFetchRewrite() const { return fetch_.get() != NULL; }
741 
746  void NestedRewriteDone(const RewriteContext* context);
747 
751  void Activate();
752 
776  void Propagate(RenderOp render_op);
777 
784  void StartRewriteForHtml();
785  void StartRewriteForFetch();
786 
793  bool ReadyToRewrite() const;
794 
799  void DetachSlots();
800 
803  void RunSuccessors();
804 
807  void WritePartition();
808 
818  void FinalizeRewriteForHtml();
819 
825  void RetireRewriteForHtml(RenderOp permit_render);
826 
829  void MarkSlow();
830 
833  void MarkTooBusy();
834 
838  void CollectDependentTopLevel(ContextSet* contexts);
839 
842  void RewriteDoneImpl(RewriteResult result, int partition_index);
843 
846  void StartNestedTasksImpl();
847 
851  void RenderPartitionOnDetach(int partition_index);
852 
855  bool PrepareFetch(
856  const OutputResourcePtr& output_resource,
857  AsyncFetch* fetch,
858  MessageHandler* message_handler);
859 
862  bool CreateOutputResourceForCachedOutput(const CachedResult* cached_result,
863  OutputResourcePtr* output_resource);
864 
866  void FetchCacheDone(CacheLookupResult* cache_result);
867 
870  void FetchFallbackCacheDone(HTTPCache::FindResult result,
871  HTTPCache::Callback* data);
872 
877  bool CanFetchFallbackToOriginal(FallbackCondition circumstance) const;
878 
881  bool HasDuplicateOtherDependency(const InputInfo& input);
882 
886  void CheckAndAddOtherDependency(const InputInfo& input);
887 
890  void CheckAndFreshenResource(const InputInfo& input_info,
891  ResourcePtr resource, int partition_index,
892  int input_index,
893  FreshenMetadataUpdateManager* freshen_manager);
894  ResourcePtr CreateUrlResource(const StringPiece& input_url);
895 
897  ResourceSlotVector slots_;
898 
902  std::vector<bool> render_slots_;
903 
914 
915  bool started_;
916 
920  AtomicBool frozen_;
921 
922  scoped_ptr<OutputPartitions> partitions_;
923  OutputResourceVector outputs_;
924  int outstanding_fetches_;
925  int outstanding_rewrites_;
926  scoped_ptr<ResourceContext> resource_context_;
927  GoogleString partition_key_;
928 
929  UrlSegmentEncoder default_encoder_;
930 
933  scoped_ptr<NamedLock> lock_;
934 
938  class FetchContext;
939  scoped_ptr<FetchContext> fetch_;
940 
943  std::vector<RewriteContext*> successors_;
944 
948  std::vector<RewriteContext*> repeated_;
949 
953  int num_pending_nested_;
954  std::vector<RewriteContext*> nested_;
955 
957  RewriteContext* parent_;
958 
967  RewriteDriver* driver_;
968 
970  int num_predecessors_;
971 
974  bool chained_;
975 
993 
995  bool rewrite_done_;
996 
1008  bool ok_to_write_output_partitions_;
1009 
1013  bool was_too_busy_;
1014 
1018  bool slow_;
1019 
1021  bool revalidate_ok_;
1022 
1025  bool notify_driver_on_fetch_done_;
1026 
1029  bool force_rewrite_;
1030 
1033  bool stale_rewrite_;
1034 
1037  bool is_metadata_cache_miss_;
1038 
1041  bool rewrite_uncacheable_;
1042 
1045  RequestTrace* dependent_request_trace_;
1046 
1048  StringIntMap other_dependency_map_;
1049 
1053  scoped_ptr<ScheduleRewriteContext> schedule_rewrite_context_;
1054 
1055  Variable* const num_rewrites_abandoned_for_lock_contention_;
1056 
1057 };
1058 
1059 }
1060 
1061 #endif
RewriteContext * parent()
Allows a nested rewriter to walk up its parent hierarchy.
Definition: rewrite_context.h:280
class GoogleUrl
Definition: google_url.h:58
virtual bool Partition(OutputPartitions *partitions, OutputResourceVector *outputs)
virtual bool ScheduleNestedContextViaCentalController() const
Definition: rewrite_context.h:628
bool stale_rewrite() const
Indicates whether we are serving a stale rewrite.
Definition: rewrite_context.h:599
int num_outputs() const
Definition: rewrite_context.h:207
static bool LookupMetadataForOutputResourceImpl(OutputResourcePtr output_resource, const GoogleUrl &gurl, RewriteContext *rewrite_context, RewriteDriver *driver, GoogleString *error_out, CacheLookupResultCallback *callback)
void AddNestedContext(RewriteContext *context)
void ReleaseCreationLock(bool succeeded)
virtual OutputResourceKind kind() const =0
void ObtainLockForCreation(ServerContext *server_context, Function *callback)
virtual bool ScheduleViaCentralController()
Definition: rewrite_context.h:621
static void InitStats(Statistics *stats)
Initializes statistics.
virtual const UrlSegmentEncoder * encoder() const
Definition: rewrite_context.h:164
virtual GoogleString UserAgentCacheKey(const ResourceContext *context) const
Definition: rewrite_context.h:486
void Freshen()
Freshens resources proactively to avoid expiration in the near future.
int num_output_partitions() const
void TracePrintf(const char *fmt,...)
virtual bool DecodeFetchUrls(const OutputResourcePtr &output_resource, MessageHandler *message_handler, GoogleUrlStarVector *url_vector)
Read/write API for HTTP response headers.
Definition: response_headers.h:37
Definition: ref_counted_ptr.h:69
CspDirective
Definition: csp_directive.h:37
bool IsNestedIn(StringPiece id) const
virtual bool FailOnHashMismatch() const
Definition: rewrite_context.h:616
void RewriteDone(RewriteResult result, int partition_index)
Definition: function.h:47
std::string GoogleString
PAGESPEED_KERNEL_BASE_STRING_H_.
Definition: string.h:24
void PartitionDone(RewriteResult result)
bool Fetch(const OutputResourcePtr &output_resource, AsyncFetch *fetch, MessageHandler *message_handler)
ServerContext * FindServerContext() const
void CrossThreadPartitionDone(RewriteResult result)
Used for LookupMetadataForOutputResource.
Definition: rewrite_context.h:181
virtual const char * id() const =0
Returns the filter ID.
virtual bool OptimizationOnly() const
Definition: rewrite_context.h:333
Definition: async_fetch.h:53
virtual void StartFetchReconstruction()
int num_nested() const
Accessors for the nested rewrites.
Definition: rewrite_context.h:284
virtual void FixFetchFallbackHeaders(const CachedResult &cached_result, ResponseHeaders *headers)
RequestTrace * dependent_request_trace()
Definition: rewrite_context.h:521
Definition: rewrite_driver.h:100
virtual bool SendFallbackResponse(StringPiece output_url_base, StringPiece contents, AsyncFetch *async_fetch, MessageHandler *handler)
Definition: server_context.h:99
RewriteResult
Definition: rewrite_result.h:27
virtual GoogleString CacheKeySuffix() const
bool chained() const
Definition: rewrite_context.h:218
Definition: rewrite_context.h:155
int num_slots() const
Definition: rewrite_context.h:202
virtual bool CreationLockBeforeStartFetch() const
Should the context call LockForCreation before checking the cache?
virtual bool PolicyPermitsRendering() const =0
virtual void Rewrite(int partition_index, CachedResult *partition, const OutputResourcePtr &output)=0
Definition: url_segment_encoder.h:33
virtual void FetchCallbackDone(bool success)
virtual void EncodeUserAgentIntoResourceContext(ResourceContext *context)
Definition: rewrite_context.h:495
Definition: message_handler.h:39
GoogleString ToString() const
Returns debug information about this RewriteContext.
Definition: request_trace.h:31
virtual int64 GetRewriteDeadlineAlarmMs() const
bool slow() const
Definition: rewrite_context.h:263
bool is_metadata_cache_miss() const
This particular rewrite was a metadata cache miss.
Definition: rewrite_context.h:266
MessageHandler * fetch_message_handler()
The message handler for the fetch.
virtual void PartitionAsync(OutputPartitions *partitions, OutputResourceVector *outputs)
bool FetchContextDetached()
Is fetch_ detached? Only call this in the fetch flow.
RewriteContext(RewriteDriver *driver, RewriteContext *parent, ResourceContext *resource_context)
void AddSlot(const ResourceSlotPtr &slot)
virtual void FetchTryFallback(const GoogleString &url, const StringPiece &hash)
bool has_parent() const
Returns true if this is a nested rewriter.
Definition: rewrite_context.h:269
void set_force_rewrite(bool x)
If called with true, forces a rewrite and re-generates the output.
Definition: rewrite_context.h:292
bool AreOutputsAllowedByCsp(CspDirective role) const
Helper that checks that all output resources are OK with CSP as given role.
void AttachDependentRequestTrace(const StringPiece &label)
OutputResourceKind
Definition: output_resource_kind.h:26
AsyncFetch * async_fetch()
Note that the following must only be called in the fetch flow.