Make RequestContext provider overridable in order to save cost of setContext() on...
[folly.git] / folly / io / async / Request.h
index a4b7a23a17d78aadd340ede0b697fa7bf10b7be2..78762cf930400ce9da14011c2e5dccb831b0bd76 100644 (file)
@@ -19,6 +19,7 @@
 #include <map>
 #include <memory>
 
+#include <folly/Function.h>
 #include <folly/SharedMutex.h>
 #include <folly/Synchronized.h>
 
@@ -45,6 +46,8 @@ class RequestContext;
 // copied between threads.
 class RequestContext {
  public:
+  using Provider = folly::Function<std::shared_ptr<RequestContext>&()>;
+
   // Create a unique request context for this request.
   // It will be passed between queues / threads (where implemented),
   // so it should be valid for the lifetime of the request.
@@ -95,8 +98,22 @@ class RequestContext {
     return getStaticContext();
   }
 
+  // This API allows one to override the default behavior of getStaticContext()
+  // by providing a custom RequestContext provider. The old provider is
+  // returned, and the user must restore the old provider via a subsequent call
+  // to setRequestContextProvider() once the new provider is no longer needed.
+  //
+  // Using custom RequestContext providers can be more efficient than having to
+  // setContext() whenever context must be switched. This is especially true in
+  // applications that do not actually use RequestContext, but where library
+  // code must still support RequestContext for other use cases.  See
+  // FiberManager for an example of how a custom RequestContext provider can
+  // reduce calls to setContext().
+  static Provider setRequestContextProvider(Provider f);
+
  private:
   static std::shared_ptr<RequestContext>& getStaticContext();
+  static Provider& requestContextProvider();
 
   using Data = std::map<std::string, std::unique_ptr<RequestData>>;
   folly::Synchronized<Data, folly::SharedMutex> data_;