1 /*
2  * Copyright (c) 2022 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 NETWORK_LATENCY_CONTROLLER_H
17 #define NETWORK_LATENCY_CONTROLLER_H
18 
19 #include <chrono>
20 #include <memory>
21 #include <mutex>
22 #include <string>
23 #include <utility>
24 #include <unordered_set>
25 
26 #include "inner_event.h"
27 #include "ffrt.h"
28 
29 #include "inetwork_latency_switcher.h"
30 
31 namespace OHOS::ResourceSchedule {
32 class NetworkLatencyController {
33 public:
34     void Init();
35     void Init(std::unique_ptr<INetworkLatencySwitcher> switcher);
36     void HandleRequest(long long value, const std::string &identity);
37 
38     static const long long NETWORK_LATENCY_REQUEST_LOW = 0;
39     static const long long NETWORK_LATENCY_REQUEST_NORMAL = 1;
40 
41 private:
42     void HandleAddRequest(const std::string &identity);
43     void HandleDelRequest(const std::string &identity);
44     void AddRequest(const std::string &identity);
45     void DelRequest(const std::string &identity);
46     void AutoDisableTask(const std::string &identity);
47 
48     std::mutex mtx;
49     std::shared_ptr<ffrt::queue> ffrtQueue_{nullptr};
50     ffrt::mutex latencyFfrtMutex_;
51     int32_t switchToFfrt_ = 1000;
52     std::unique_ptr<INetworkLatencySwitcher> switcher;
53     std::unordered_set<std::string> requests;
54     std::unordered_map<std::string, ffrt::task_handle> taskHandlerMap_;
55 };
56 } // namespace OHOS::ResourceSchedule
57 
58 #endif // NETWORK_LATENCY_CONTROLLER_H
59