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 
16 #ifndef OHOS_DISTRIBUTED_DATA_SERVICES_CLOUD_CLOUD_SERVICE_IMPL_H
17 #define OHOS_DISTRIBUTED_DATA_SERVICES_CLOUD_CLOUD_SERVICE_IMPL_H
18 
19 #include <mutex>
20 #include <queue>
21 
22 #include "cloud/cloud_event.h"
23 #include "cloud/cloud_extra_data.h"
24 #include "cloud/cloud_info.h"
25 #include "cloud/schema_meta.h"
26 #include "cloud/sharing_center.h"
27 #include "cloud/subscription.h"
28 #include "cloud_service_stub.h"
29 #include "feature/static_acts.h"
30 #include "sync_manager.h"
31 #include "values_bucket.h"
32 namespace OHOS::CloudData {
33 class CloudServiceImpl : public CloudServiceStub {
34 public:
35     using StoreMetaData = DistributedData::StoreMetaData;
36     using StoreInfo = DistributedData::StoreInfo;
37     CloudServiceImpl();
38     ~CloudServiceImpl() = default;
39     int32_t EnableCloud(const std::string &id, const std::map<std::string, int32_t> &switches) override;
40     int32_t DisableCloud(const std::string &id) override;
41     int32_t ChangeAppSwitch(const std::string &id, const std::string &bundleName, int32_t appSwitch) override;
42     int32_t Clean(const std::string &id, const std::map<std::string, int32_t> &actions) override;
43     int32_t NotifyDataChange(const std::string &id, const std::string &bundleName) override;
44     int32_t NotifyDataChange(const std::string& eventId, const std::string& extraData, int32_t userId) override;
45     std::pair<int32_t, std::map<std::string, StatisticInfos>> QueryStatistics(const std::string &id,
46         const std::string &bundleName, const std::string &storeId) override;
47     std::pair<int32_t, QueryLastResults> QueryLastSyncInfo(const std::string &id, const std::string &bundleName,
48                                                            const std::string &storeId) override;
49     int32_t SetGlobalCloudStrategy(Strategy strategy, const std::vector<CommonType::Value>& values) override;
50 
51     std::pair<int32_t, std::vector<NativeRdb::ValuesBucket>> AllocResourceAndShare(const std::string& storeId,
52         const DistributedRdb::PredicatesMemo& predicates, const std::vector<std::string>& columns,
53         const Participants& participants) override;
54     int32_t Share(const std::string &sharingRes, const Participants &participants, Results &results) override;
55     int32_t Unshare(const std::string &sharingRes, const Participants &participants, Results &results) override;
56     int32_t Exit(const std::string &sharingRes, std::pair<int32_t, std::string> &result) override;
57     int32_t ChangePrivilege(
58         const std::string &sharingRes, const Participants &participants, Results &results) override;
59     int32_t Query(const std::string &sharingRes, QueryResults &results) override;
60     int32_t QueryByInvitation(const std::string &invitation, QueryResults &results) override;
61     int32_t ConfirmInvitation(const std::string &invitation, int32_t confirmation,
62         std::tuple<int32_t, std::string, std::string> &result) override;
63     int32_t ChangeConfirmation(
64         const std::string &sharingRes, int32_t confirmation, std::pair<int32_t, std::string> &result) override;
65 
66     int32_t SetCloudStrategy(Strategy strategy, const std::vector<CommonType::Value>& values) override;
67 
68     int32_t OnInitialize() override;
69     int32_t OnBind(const BindInfo &info) override;
70     int32_t OnUserChange(uint32_t code, const std::string &user, const std::string &account) override;
71     int32_t OnReady(const std::string &device) override;
72     int32_t Offline(const std::string &device) override;
73 
74 private:
75     using StaticActs = DistributedData::StaticActs;
76     class CloudStatic : public StaticActs {
77     public:
~CloudStatic()78         ~CloudStatic() override {};
79         int32_t OnAppUninstall(const std::string &bundleName, int32_t user, int32_t index) override;
80         int32_t OnAppInstall(const std::string &bundleName, int32_t user, int32_t index) override;
81     };
82     class Factory {
83     public:
84         Factory() noexcept;
85         ~Factory();
86     private:
87         std::shared_ptr<CloudServiceImpl> product_;
88         std::shared_ptr<CloudStatic> staticActs_;
89     };
90     static Factory factory_;
91 
92     using CloudInfo = DistributedData::CloudInfo;
93     using SchemaMeta = DistributedData::SchemaMeta;
94     using Event = DistributedData::Event;
95     using CloudEvent = DistributedData::CloudEvent;
96     using Subscription = DistributedData::Subscription;
97     using Handle = bool (CloudServiceImpl::*)(int32_t);
98     using Handles = std::deque<Handle>;
99     using Task = ExecutorPool::Task;
100     using TaskId = ExecutorPool::TaskId;
101     using Duration = ExecutorPool::Duration;
102     using AutoCache = DistributedData::AutoCache;
103 
104     struct HapInfo {
105         int32_t user;
106         int32_t instIndex;
107         std::string bundleName;
108     };
109 
110     static std::map<std::string, int32_t> ConvertAction(const std::map<std::string, int32_t> &actions);
111     static HapInfo GetHapInfo(uint32_t tokenId);
112 
113     static constexpr uint64_t INVALID_SUB_TIME = 0;
114     static constexpr int32_t RETRY_TIMES = 3;
115     static constexpr int32_t RETRY_INTERVAL = 60;
116     static constexpr int32_t EXPIRE_INTERVAL = 2 * 24; // 2 day
117     static constexpr int32_t WAIT_TIME = 30; // 30 seconds
118     static constexpr int32_t DEFAULT_USER = 0;
119     static constexpr int32_t TIME_BEFORE_SUB = 12 * 60 * 60 * 1000; // 12hours, ms
120     static constexpr int32_t SUBSCRIPTION_INTERVAL = 60 * 60 * 1000; // 1hours
121 
122     bool UpdateCloudInfo(int32_t user);
123     bool UpdateSchema(int32_t user);
124     bool DoSubscribe(int32_t user);
125     bool ReleaseUserInfo(int32_t user);
126     bool DoCloudSync(int32_t user);
127     bool StopCloudSync(int32_t user);
128 
129     static std::pair<int32_t, CloudInfo> GetCloudInfo(int32_t userId);
130     static std::pair<int32_t, CloudInfo> GetCloudInfoFromMeta(int32_t userId);
131     static std::pair<int32_t, CloudInfo> GetCloudInfoFromServer(int32_t userId);
132     static int32_t UpdateCloudInfoFromServer(int32_t user);
133 
134     std::pair<int32_t, SchemaMeta> GetSchemaMeta(int32_t userId, const std::string &bundleName, int32_t instanceId);
135     std::pair<int32_t, SchemaMeta> GetAppSchemaFromServer(int32_t user, const std::string &bundleName);
136     void UpgradeSchemaMeta(int32_t user, const SchemaMeta &schemaMeta);
137     std::map<std::string, StatisticInfos> ExecuteStatistics(const std::string &storeId, const CloudInfo &cloudInfo,
138         const SchemaMeta &schemaMeta);
139     StatisticInfos QueryStatistics(const StoreMetaData &storeMetaData, const DistributedData::Database &database);
140     std::pair<bool, StatisticInfo> QueryTableStatistic(const std::string &tableName, AutoCache::Store store);
141     std::string BuildStatisticSql(const std::string &tableName);
142 
143     void GetSchema(const Event &event);
144     void CloudShare(const Event &event);
145 
146     Task GenTask(int32_t retry, int32_t user, Handles handles = { WORK_SUB });
147     Task GenSubTask(Task task, int32_t user);
148     void InitSubTask(const Subscription &sub, uint64_t minInterval = 0);
149     void Execute(Task task);
150     void CleanSubscription(Subscription &sub);
151     int32_t DoClean(const CloudInfo &cloudInfo, const std::map<std::string, int32_t> &actions);
152     void DoClean(int32_t user, const SchemaMeta &schemaMeta, int32_t action);
153     std::pair<int32_t, std::shared_ptr<DistributedData::Cursor>> PreShare(const StoreInfo& storeInfo,
154         DistributedData::GenQuery& query);
155     std::vector<NativeRdb::ValuesBucket> ConvertCursor(std::shared_ptr<DistributedData::Cursor> cursor) const;
156     int32_t CheckNotifyConditions(const std::string &id, const std::string &bundleName, CloudInfo &cloudInfo);
157     std::map<std::string, std::vector<std::string>> GetDbInfoFromExtraData(
158         const DistributedData::ExtraData &extraData, const SchemaMeta &schemaMeta);
159     std::shared_ptr<DistributedData::SharingCenter> GetSharingHandle(const HapInfo& hapInfo);
160     bool GetStoreMetaData(StoreMetaData &meta);
161     bool DoKvCloudSync(int32_t userId, const std::string &bundleName = "", int32_t triggerMode = 0);
162 
163     using SaveStrategy = int32_t (*)(const std::vector<CommonType::Value> &values, const HapInfo &hapInfo);
164     static const SaveStrategy STRATEGY_SAVERS[Strategy::STRATEGY_BUTT];
165     static int32_t SaveNetworkStrategy(const std::vector<CommonType::Value> &values, const HapInfo &hapInfo);
166 
167     std::shared_ptr<ExecutorPool> executor_;
168     SyncManager syncManager_;
169     std::mutex mutex_;
170     std::mutex rwMetaMutex_;
171     TaskId subTask_ = ExecutorPool::INVALID_TASK_ID;
172     uint64_t expireTime_ = static_cast<uint64_t>(std::chrono::duration_cast<std::chrono::milliseconds>(
173         std::chrono::system_clock::now().time_since_epoch()).count());
174 
175     static constexpr Handle WORK_CLOUD_INFO_UPDATE = &CloudServiceImpl::UpdateCloudInfo;
176     static constexpr Handle WORK_SCHEMA_UPDATE = &CloudServiceImpl::UpdateSchema;
177     static constexpr Handle WORK_SUB = &CloudServiceImpl::DoSubscribe;
178     static constexpr Handle WORK_RELEASE = &CloudServiceImpl::ReleaseUserInfo;
179     static constexpr Handle WORK_DO_CLOUD_SYNC = &CloudServiceImpl::DoCloudSync;
180     static constexpr Handle WORK_STOP_CLOUD_SYNC = &CloudServiceImpl::StopCloudSync;
181 };
182 } // namespace OHOS::DistributedData
183 
184 #endif // OHOS_DISTRIBUTED_DATA_SERVICES_CLOUD_CLOUD_SERVICE_IMPL_H