2 * Copyright 2017 Facebook, Inc.
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
12 * http://www.apache.org/licenses/LICENSE-2.0
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
22 #include <folly/io/async/Request.h>
23 #include <folly/tracing/StaticTracepoint.h>
25 #include <glog/logging.h>
27 #include <folly/MapUtil.h>
28 #include <folly/SingletonThreadLocal.h>
32 void RequestContext::setContextData(
33 const std::string& val,
34 std::unique_ptr<RequestData> data) {
35 auto wlock = data_.wlock();
36 if (wlock->count(val)) {
37 LOG_FIRST_N(WARNING, 1)
38 << "Called RequestContext::setContextData with data already set";
40 (*wlock)[val] = nullptr;
42 (*wlock)[val] = std::move(data);
46 bool RequestContext::setContextDataIfAbsent(
47 const std::string& val,
48 std::unique_ptr<RequestData> data) {
49 auto ulock = data_.ulock();
50 if (ulock->count(val)) {
54 auto wlock = ulock.moveFromUpgradeToWrite();
55 (*wlock)[val] = std::move(data);
59 bool RequestContext::hasContextData(const std::string& val) const {
60 return data_.rlock()->count(val);
63 RequestData* RequestContext::getContextData(const std::string& val) {
64 return get_ref_default(*data_.rlock(), val, nullptr).get();
67 const RequestData* RequestContext::getContextData(
68 const std::string& val) const {
69 return get_ref_default(*data_.rlock(), val, nullptr).get();
72 void RequestContext::onSet() {
73 auto rlock = data_.rlock();
74 for (auto const& ent : *rlock) {
75 if (auto& data = ent.second) {
81 void RequestContext::onUnset() {
82 auto rlock = data_.rlock();
83 for (auto const& ent : *rlock) {
84 if (auto& data = ent.second) {
90 void RequestContext::clearContextData(const std::string& val) {
91 data_.wlock()->erase(val);
94 std::shared_ptr<RequestContext> RequestContext::setContext(
95 std::shared_ptr<RequestContext> ctx) {
96 auto& curCtx = getStaticContext();
98 FOLLY_SDT(folly, request_context_switch_before, curCtx.get(), ctx.get());
111 std::shared_ptr<RequestContext>& RequestContext::getStaticContext() {
112 using SingletonT = SingletonThreadLocal<std::shared_ptr<RequestContext>>;
113 static SingletonT singleton;
115 return singleton.get();
118 RequestContext* RequestContext::get() {
119 auto context = getStaticContext();
121 static RequestContext defaultContext;
122 return std::addressof(defaultContext);
124 return context.get();