1 /*
2  * Copyright (c) 2023 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 #define LOG_TAG "AppConnectManager"
16 
17 #include "app_connect_manager.h"
18 
19 #include "datashare_radar_reporter.h"
20 #include "extension_ability_manager.h"
21 #include "log_print.h"
22 
23 namespace OHOS::DataShare {
24 ConcurrentMap<std::string, BlockData<bool> *> AppConnectManager::blockCache_;
Wait(const std::string & bundleName,int maxWaitTime,std::function<bool ()> connect,std::function<void ()> disconnect)25 bool AppConnectManager::Wait(const std::string &bundleName,
26     int maxWaitTime, std::function<bool()> connect, std::function<void()> disconnect)
27 {
28     BlockData<bool> block(maxWaitTime, false);
29     auto result = blockCache_.ComputeIfAbsent(bundleName, [&block](const std::string &key) {
30         return &block;
31     });
32     if (!result) {
33         ZLOGE("is running %{public}s", bundleName.c_str());
34         return false;
35     }
36     ZLOGI("start connect %{public}s", bundleName.c_str());
37     result = connect();
38     if (!result) {
39         RADAR_REPORT(__FUNCTION__, RadarReporter::SILENT_ACCESS, RadarReporter::PROXY_CONNECT_EXT,
40             RadarReporter::FAILED, RadarReporter::ERROR_CODE, RadarReporter::CONNECT_EXTENSION_ERROR);
41         ZLOGE("connect failed %{public}s", bundleName.c_str());
42         blockCache_.Erase(bundleName);
43         return false;
44     }
45     result = block.GetValue();
46     ZLOGI("end wait %{public}s", bundleName.c_str());
47     blockCache_.Erase(bundleName);
48     disconnect();
49     return result;
50 }
51 
Notify(const std::string & bundleName)52 void AppConnectManager::Notify(const std::string &bundleName)
53 {
54     ZLOGI("notify %{public}s", bundleName.c_str());
55     blockCache_.ComputeIfPresent(bundleName, [&bundleName](const std::string &key, BlockData<bool> *value) {
56         if (value == nullptr) {
57             ZLOGI("nullptr %{public}s", bundleName.c_str());
58             return false;
59         }
60         value->SetValue(true);
61         return true;
62     });
63     ExtensionAbilityManager::GetInstance().DelayDisconnect(bundleName);
64 }
65 } // namespace OHOS::DataShare