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 SYNC_ABLE_ENGINE_H
17 #define SYNC_ABLE_ENGINE_H
18 
19 #include <memory.h>
20 
21 #include "notification_chain.h"
22 #include "ref_object.h"
23 #include "syncer_proxy.h"
24 
25 namespace DistributedDB {
26 class SyncAbleEngine final {
27 public:
28     explicit SyncAbleEngine(ISyncInterface *store);
29     ~SyncAbleEngine();
30 
31     // Start a sync action.
32     int Sync(const ISyncer::SyncParma &parm, uint64_t connectionId);
33 
34     void WakeUpSyncer();
35     void Close();
36 
37     // Get The current virtual timestamp
38     uint64_t GetTimestamp();
39 
40     int EraseDeviceWaterMark(const std::string &deviceId, bool isNeedHash, const std::string &tableName = "");
41 
42     int GetLocalIdentity(std::string &outTarget);
43 
44     // Stop a sync action in progress
45     void StopSync(uint64_t connectionId);
46 
47     void Dump(int fd);
48 
49     int RemoteQuery(const std::string &device, const RemoteCondition &condition, uint64_t timeout,
50         uint64_t connectionId, std::shared_ptr<ResultSet> &result);
51 
52     int GetHashDeviceId(const std::string &clientId, std::string &hashDevId);
53 private:
54     // Start syncer
55     int StartSyncer(bool isCheckSyncActive = false, bool isNeedActive = true);
56 
57     int StartSyncerWithNoLock(bool isCheckSyncActive, bool isNeedActive);
58 
59     // Stop syncer
60     void StopSyncer();
61 
62     void StopSyncerWithNoLock(bool isClosedOperation = false);
63 
64     void SetSyncModuleActive();
65 
66     bool GetSyncModuleActive();
67 
68     void ReSetSyncModuleActive();
69 
70     void UserChangeHandle();
71 
72     void ChangeUserListener();
73 
74     bool NeedStartSyncer() const;
75 
76     SyncerProxy syncer_; // use for sync Interactive
77     std::atomic<bool> started_;
78     std::atomic<bool> closed_;
79     std::atomic<bool> isSyncModuleActiveCheck_;
80     std::atomic<bool> isSyncNeedActive_;
81     ISyncInterface *store_;
82 
83     mutable std::mutex syncerOperateLock_;
84     NotificationChain::Listener *userChangeListener_;
85 };
86 }  // namespace DistributedDB
87 #endif // SYNC_ABLE_ENGINE_H