proxygen
ExpiringFilter.h
Go to the documentation of this file.
1 /*
2  * Copyright 2017-present Facebook, 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 #pragma once
17 
18 #include <wangle/service/Service.h>
19 
20 namespace wangle {
27 template <typename Req, typename Resp = Req>
28 class ExpiringFilter : public ServiceFilter<Req, Resp> {
29  public:
30  explicit ExpiringFilter(std::shared_ptr<Service<Req, Resp>> service,
31  std::chrono::milliseconds idleTimeoutTime
32  = std::chrono::milliseconds(0),
33  std::chrono::milliseconds maxTime
34  = std::chrono::milliseconds(0),
35  folly::Timekeeper* timekeeper = nullptr)
36  : ServiceFilter<Req, Resp>(service)
37  , idleTimeoutTime_(idleTimeoutTime)
38  , maxTime_(maxTime)
39  , timekeeper_(timekeeper) {
40 
41  if (maxTime_ > std::chrono::milliseconds(0)) {
43  std::move(maxTimeout_).thenValue([this](auto&&) { this->close(); });
44  }
46  }
47 
48  ~ExpiringFilter() override {
49  if (!idleTimeout_.isReady()) {
50  idleTimeout_.cancel();
51  }
52  if (!maxTimeout_.isReady()) {
53  maxTimeout_.cancel();
54  }
55  }
56 
57  void startIdleTimer() {
58  if (requests_ != 0) {
59  return;
60  }
61  if (idleTimeoutTime_ > std::chrono::milliseconds(0)) {
63  std::move(idleTimeout_).thenValue([this](auto&&) { this->close(); });
64  }
65  }
66 
68  if (!idleTimeout_.isReady()) {
69  idleTimeout_.cancel();
70  }
71  requests_++;
72  return (*this->service_)(std::move(req)).ensure([this](){
73  requests_--;
75  });
76  }
77 
78  private:
81  std::chrono::milliseconds idleTimeoutTime_{0};
82  std::chrono::milliseconds maxTime_{0};
85 };
86 
87 } // namespace wangle
folly::Future< folly::Unit > close() override
Definition: Service.h:73
std::chrono::milliseconds maxTime_
Future< Unit > sleep(Duration dur, Timekeeper *tk)
Definition: Future.cpp:42
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
folly::Future< Resp > operator()(Req req) override
folly::Future< folly::Unit > idleTimeout_
std::shared_ptr< Service< Req, Resp > > service_
Definition: Service.h:82
folly::Timekeeper * timekeeper_
folly::Future< folly::Unit > maxTimeout_
ExpiringFilter(std::shared_ptr< Service< Req, Resp >> service, std::chrono::milliseconds idleTimeoutTime=std::chrono::milliseconds(0), std::chrono::milliseconds maxTime=std::chrono::milliseconds(0), folly::Timekeeper *timekeeper=nullptr)
std::chrono::milliseconds idleTimeoutTime_