concurrency_limiter.h 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. // Licensed to the Apache Software Foundation (ASF) under one
  2. // or more contributor license agreements. See the NOTICE file
  3. // distributed with this work for additional information
  4. // regarding copyright ownership. The ASF licenses this file
  5. // to you under the Apache License, Version 2.0 (the
  6. // "License"); you may not use this file except in compliance
  7. // with the License. You may obtain a copy of the License at
  8. //
  9. // http://www.apache.org/licenses/LICENSE-2.0
  10. //
  11. // Unless required by applicable law or agreed to in writing,
  12. // software distributed under the License is distributed on an
  13. // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  14. // KIND, either express or implied. See the License for the
  15. // specific language governing permissions and limitations
  16. // under the License.
  17. #ifndef BRPC_CONCURRENCY_LIMITER_H
  18. #define BRPC_CONCURRENCY_LIMITER_H
  19. #include "brpc/describable.h"
  20. #include "brpc/destroyable.h"
  21. #include "brpc/extension.h" // Extension<T>
  22. #include "brpc/adaptive_max_concurrency.h" // AdaptiveMaxConcurrency
  23. namespace brpc {
  24. class ConcurrencyLimiter {
  25. public:
  26. virtual ~ConcurrencyLimiter() {}
  27. // This method should be called each time a request comes in. It returns
  28. // false when the concurrency reaches the upper limit, otherwise it
  29. // returns true. Normally, when OnRequested returns false, you should
  30. // return an ELIMIT error directly.
  31. virtual bool OnRequested(int current_concurrency) = 0;
  32. // Each request should call this method before responding.
  33. // `error_code' : Error code obtained from the controller, 0 means success.
  34. // `latency' : Microseconds taken by RPC.
  35. // NOTE: Even if OnRequested returns false, after sending ELIMIT, you
  36. // still need to call OnResponded.
  37. virtual void OnResponded(int error_code, int64_t latency_us) = 0;
  38. // Returns the latest max_concurrency.
  39. // The return value is only for logging.
  40. virtual int MaxConcurrency() = 0;
  41. // Create an instance from the amc
  42. // Caller is responsible for delete the instance after usage.
  43. virtual ConcurrencyLimiter* New(const AdaptiveMaxConcurrency& amc) const = 0;
  44. };
  45. inline Extension<const ConcurrencyLimiter>* ConcurrencyLimiterExtension() {
  46. return Extension<const ConcurrencyLimiter>::instance();
  47. }
  48. } // namespace brpc
  49. #endif // BRPC_CONCURRENCY_LIMITER_H