8717503a9209db9f90db536264a6367af6f8c9ab
[folly.git] / folly / io / async / Request.h
1 /*
2  * Copyright 2016 Facebook, Inc.
3  *
4  * Licensed to the Apache Software Foundation (ASF) under one
5  * or more contributor license agreements. See the NOTICE file
6  * distributed with this work for additional information
7  * regarding copyright ownership. The ASF licenses this file
8  * to you under the Apache License, Version 2.0 (the
9  * "License"); you may not use this file except in compliance
10  * with the License. You may obtain a copy of the License at
11  *
12  *   http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing,
15  * software distributed under the License is distributed on an
16  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17  * KIND, either express or implied. See the License for the
18  * specific language governing permissions and limitations
19  * under the License.
20  */
21 #pragma once
22
23 #include <map>
24 #include <memory>
25 #include <glog/logging.h>
26 #include <folly/ThreadLocal.h>
27 #include <folly/RWSpinLock.h>
28 #include <folly/SingletonThreadLocal.h>
29
30 namespace folly {
31
32 // Some request context that follows an async request through a process
33 // Everything in the context must be thread safe
34
35 class RequestData {
36  public:
37   virtual ~RequestData() = default;
38 };
39
40 class RequestContext;
41
42 // If you do not call create() to create a unique request context,
43 // this default request context will always be returned, and is never
44 // copied between threads.
45 class RequestContext {
46  public:
47   // Create a unique requext context for this request.
48   // It will be passed between queues / threads (where implemented),
49   // so it should be valid for the lifetime of the request.
50   static void create() {
51     getStaticContext() = std::make_shared<RequestContext>();
52   }
53
54   // Get the current context.
55   static RequestContext* get() {
56     auto context = getStaticContext();
57     if (!context) {
58       static RequestContext defaultContext;
59       return std::addressof(defaultContext);
60     }
61     return context.get();
62   }
63
64   // The following API may be used to set per-request data in a thread-safe way.
65   // This access is still performance sensitive, so please ask if you need help
66   // profiling any use of these functions.
67   void setContextData(
68     const std::string& val, std::unique_ptr<RequestData> data) {
69     folly::RWSpinLock::WriteHolder guard(lock);
70     if (data_.find(val) != data_.end()) {
71       LOG_FIRST_N(WARNING, 1) <<
72         "Called RequestContext::setContextData with data already set";
73
74       data_[val] = nullptr;
75     } else {
76       data_[val] = std::move(data);
77     }
78   }
79
80   // Unlike setContextData, this method does not panic if the key is already
81   // present. Returns true iff the new value has been inserted.
82   bool setContextDataIfAbsent(const std::string& val,
83                               std::unique_ptr<RequestData> data) {
84     folly::RWSpinLock::UpgradedHolder guard(lock);
85     if (data_.find(val) != data_.end()) {
86       return false;
87     }
88
89     folly::RWSpinLock::WriteHolder writeGuard(std::move(guard));
90     data_[val] = std::move(data);
91     return true;
92   }
93
94   bool hasContextData(const std::string& val) {
95     folly::RWSpinLock::ReadHolder guard(lock);
96     return data_.find(val) != data_.end();
97   }
98
99   RequestData* getContextData(const std::string& val) {
100     folly::RWSpinLock::ReadHolder guard(lock);
101     auto r = data_.find(val);
102     if (r == data_.end()) {
103       return nullptr;
104     } else {
105       return r->second.get();
106     }
107   }
108
109   void clearContextData(const std::string& val) {
110     folly::RWSpinLock::WriteHolder guard(lock);
111     data_.erase(val);
112   }
113
114   // The following API is used to pass the context through queues / threads.
115   // saveContext is called to geta shared_ptr to the context, and
116   // setContext is used to reset it on the other side of the queue.
117   //
118   // A shared_ptr is used, because many request may fan out across
119   // multiple threads, or do post-send processing, etc.
120
121   static std::shared_ptr<RequestContext>
122   setContext(std::shared_ptr<RequestContext> ctx) {
123     using std::swap;
124     swap(ctx, getStaticContext());
125     return ctx;
126   }
127
128   static std::shared_ptr<RequestContext> saveContext() {
129     return getStaticContext();
130   }
131
132  private:
133   static std::shared_ptr<RequestContext>& getStaticContext() {
134     using SingletonT = SingletonThreadLocal<std::shared_ptr<RequestContext>>;
135     static SingletonT singleton;
136     return singleton.get();
137   }
138
139   folly::RWSpinLock lock;
140   std::map<std::string, std::unique_ptr<RequestData>> data_;
141 };
142
143 }