1 /* 2 * Copyright (c) 2021 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16 #ifndef FOUNDATION_KVSTORE_FLOW_CTRL_MANAGER_H 17 #define FOUNDATION_KVSTORE_FLOW_CTRL_MANAGER_H 18 19 #include <atomic> 20 21 namespace OHOS { 22 namespace DistributedKv { 23 struct TokenBucket { 24 uint64_t tokenBucketRefreshTime = 0; // last time to refresh the bucket 25 26 uint64_t lastAccessTime = 0; // last time to access 27 28 volatile std::atomic<int> leftNumInTokenBucket {0}; // rest numbers of token in the bucket 29 30 int maxCapacity; // max capacity 31 32 uint64_t refreshTimeGap; // time gap between refreshing 33 }; 34 35 class KvStoreFlowCtrlManager { 36 public: 37 KvStoreFlowCtrlManager() = delete; 38 39 KvStoreFlowCtrlManager(const int burstCapacity, const int sustainedCapacity); 40 41 ~KvStoreFlowCtrlManager() = default; 42 43 bool IsTokenEnough(); 44 45 static const int BURST_REFRESH_TIME = 1000; 46 47 static const int SUSTAINED_REFRESH_TIME = 60000; 48 49 private: 50 void RefreshTokenBucket(TokenBucket &tokenBucket, uint64_t timestamp); 51 52 bool IsTokenEnoughSlice(TokenBucket &tokenBucket, uint64_t timestamp); 53 54 TokenBucket burstTokenBucket_; // token bucket to deal with events in a burst 55 56 TokenBucket sustainedTokenBucket_; // token bucket to deal with sustained events. 57 }; 58 } // namespace DistributedKv 59 } // namespace OHOS 60 61 #endif // FOUNDATION_KVSTORE_FLOW_CTRL_MANAGER_H 62