diff --git a/bundle.json b/bundle.json index 17d1e1431d0c6bf442a782d698384883eaaa8df8..b3497759464a21e396602c83802f5d1371f78fd4 100644 --- a/bundle.json +++ b/bundle.json @@ -38,7 +38,9 @@ "name": "distributeddatamgr", "subsystem": "distributeddatamgr", "syscap": [ - "SystemCapability.Data.DATA_DISTRIBUTEDDATAMGR" + "SystemCapability.DistributedDataManager.KVStore.Core", + "SystemCapability.DistributedDataManager.KVStore.Lite", + "SystemCapability.DistributedDataManager.KVStore.DistributedKVStore" ], "features": [], "adapted_system_type": [ @@ -49,14 +51,12 @@ "deps": { "components": [ "ability_base", - "ability_runtime", "libhilog", "ipc_core", "utils", "samgr_proxy", "ace_napi", "base", - "intent", "appexecfwk_base", "appexecfwk_core", "batterysrv_client", diff --git a/distributeddatamgr.gni b/distributeddatamgr.gni new file mode 100644 index 0000000000000000000000000000000000000000..839074222e56c6629960698e2d4725a34482ce20 --- /dev/null +++ b/distributeddatamgr.gni @@ -0,0 +1,20 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +declare_args() { + distributeddatamgr_power = true + if (!defined(global_parts_info.power_manager_native_powermgr_client) || + !defined(global_parts_info.battery_manager_native_batterysrv_client)) { + distributeddatamgr_power = false + } +} diff --git a/figures/en-us_image_0000001162536643.png b/figures/distributed-datamgr-subsystem-architecture.png similarity index 100% rename from figures/en-us_image_0000001162536643.png rename to figures/distributed-datamgr-subsystem-architecture.png diff --git a/figures/zh-cn_image_0000001162536643.png "b/figures/\345\210\206\345\270\203\345\274\217\346\225\260\346\215\256\347\256\241\347\220\206\345\255\220\347\263\273\347\273\237_\346\236\266\346\236\204\345\233\276.png" similarity index 100% rename from figures/zh-cn_image_0000001162536643.png rename to "figures/\345\210\206\345\270\203\345\274\217\346\225\260\346\215\256\347\256\241\347\220\206\345\255\220\347\263\273\347\273\237_\346\236\266\346\236\204\345\233\276.png" diff --git a/frameworks/innerkitsimpl/distributeddatafwk/include/ikvstore.h b/frameworks/innerkitsimpl/distributeddatafwk/include/ikvstore.h index 5b79c239d93928e2fc3633e6383d32dc5bab5192..ffd926a6df4b2171bba15e3a971075c36fb56ade 100644 --- a/frameworks/innerkitsimpl/distributeddatafwk/include/ikvstore.h +++ b/frameworks/innerkitsimpl/distributeddatafwk/include/ikvstore.h @@ -26,7 +26,6 @@ namespace OHOS { namespace DistributedKv { - class IKvStoreImpl : public IRemoteBroker { public: DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.DistributedKv.IKvStoreImpl") diff --git a/frameworks/innerkitsimpl/distributeddatafwk/include/ikvstore_client_death_observer.h b/frameworks/innerkitsimpl/distributeddatafwk/include/ikvstore_client_death_observer.h index 15a83f10ddb3ff226af808d350081a825659fe9e..2d391111b63d5aae5b430645f1769e8b9b102642 100644 --- a/frameworks/innerkitsimpl/distributeddatafwk/include/ikvstore_client_death_observer.h +++ b/frameworks/innerkitsimpl/distributeddatafwk/include/ikvstore_client_death_observer.h @@ -22,7 +22,6 @@ namespace OHOS { namespace DistributedKv { - class IKvStoreClientDeathObserver : public IRemoteBroker { public: DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.DistributedKv.IKvStoreClientDeathObserver"); @@ -30,8 +29,6 @@ public: class KvStoreClientDeathObserverStub : public IRemoteStub { public: - virtual int OnRemoteRequest(uint32_t code, MessageParcel &data, - MessageParcel &reply, MessageOption &option) override; }; class KvStoreClientDeathObserverProxy : public IRemoteProxy { @@ -41,7 +38,6 @@ public: private: static inline BrokerDelegator delegator_; }; - } // namespace DistributedKv } // namespace OHOS diff --git a/frameworks/innerkitsimpl/distributeddatafwk/include/ikvstore_data_service.h b/frameworks/innerkitsimpl/distributeddatafwk/include/ikvstore_data_service.h index a58f7742a5aae1be21cb32fbab6cf367257ce7bb..60fcad4e89d2dcdc61c31ea7ba9cb9f1f89dfc7a 100755 --- a/frameworks/innerkitsimpl/distributeddatafwk/include/ikvstore_data_service.h +++ b/frameworks/innerkitsimpl/distributeddatafwk/include/ikvstore_data_service.h @@ -40,7 +40,7 @@ namespace OHOS::DistributedKv { struct OptionsIpc { bool createIfMissing; bool encrypt; - bool persistant; + bool persistent; bool backup; bool autoSync; int securityLevel; diff --git a/frameworks/innerkitsimpl/distributeddatafwk/include/ikvstore_observer.h b/frameworks/innerkitsimpl/distributeddatafwk/include/ikvstore_observer.h index b04d53cede89f172394f473c19277e1ac68b584b..14b195f78bc0e120a4418dc0318fe415e7676633 100644 --- a/frameworks/innerkitsimpl/distributeddatafwk/include/ikvstore_observer.h +++ b/frameworks/innerkitsimpl/distributeddatafwk/include/ikvstore_observer.h @@ -25,7 +25,6 @@ namespace OHOS { namespace DistributedKv { - class IKvStoreObserver : public IRemoteBroker { public: DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.DistributedKv.IKvStoreObserver"); @@ -46,7 +45,6 @@ public: private: static inline BrokerDelegator delegator_; }; - } // namespace DistributedKv } // namespace OHOS diff --git a/frameworks/innerkitsimpl/distributeddatafwk/include/ikvstore_single.h b/frameworks/innerkitsimpl/distributeddatafwk/include/ikvstore_single.h index 2d333cb63e4d03f551265c3e90c2191153824664..67e710e88fa0c0e5b88076b1745d5d50be21abf0 100755 --- a/frameworks/innerkitsimpl/distributeddatafwk/include/ikvstore_single.h +++ b/frameworks/innerkitsimpl/distributeddatafwk/include/ikvstore_single.h @@ -206,7 +206,6 @@ public: private: static inline BrokerDelegator delegator_; }; - } // namespace DistributedKv } // namespace OHOS diff --git a/frameworks/innerkitsimpl/distributeddatafwk/include/ikvstore_snapshot.h b/frameworks/innerkitsimpl/distributeddatafwk/include/ikvstore_snapshot.h index 843d163580fa724ee811b175a0da049a433b9a83..31268126d2bb985bbae3744e9804916bc9b612c8 100644 --- a/frameworks/innerkitsimpl/distributeddatafwk/include/ikvstore_snapshot.h +++ b/frameworks/innerkitsimpl/distributeddatafwk/include/ikvstore_snapshot.h @@ -24,7 +24,6 @@ namespace OHOS { namespace DistributedKv { - class IKvStoreSnapshotImpl : public IRemoteBroker { public: DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.DistributedKv.IKvStoreSnapshotImpl") diff --git a/frameworks/innerkitsimpl/distributeddatafwk/include/ikvstore_sync_callback.h b/frameworks/innerkitsimpl/distributeddatafwk/include/ikvstore_sync_callback.h index 343760a8cfab008fb9d22ccedeaa962aa2604561..7761fdfc71521096335dcdf582392811f275b5c4 100644 --- a/frameworks/innerkitsimpl/distributeddatafwk/include/ikvstore_sync_callback.h +++ b/frameworks/innerkitsimpl/distributeddatafwk/include/ikvstore_sync_callback.h @@ -24,7 +24,6 @@ namespace OHOS { namespace DistributedKv { - class IKvStoreSyncCallback : public IRemoteBroker { public: DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.DistributedKv.IKvStoreSyncCallback"); @@ -45,7 +44,6 @@ public: private: static inline BrokerDelegator delegator_; }; - } // namespace DistributedKv } // namespace OHOS diff --git a/frameworks/innerkitsimpl/distributeddatafwk/include/inner_types.h b/frameworks/innerkitsimpl/distributeddatafwk/include/inner_types.h index add36329c6d1c78e033b4786ac17f1f321355af6..192338f77fdb0d655f8de7d267977a3d5c00bfd1 100644 --- a/frameworks/innerkitsimpl/distributeddatafwk/include/inner_types.h +++ b/frameworks/innerkitsimpl/distributeddatafwk/include/inner_types.h @@ -18,13 +18,11 @@ namespace OHOS { namespace DistributedKv { - enum class InnerStatus { SUCCESS = 0, DECREASE_REFCOUNT, ERROR, }; - } } #endif diff --git a/frameworks/innerkitsimpl/distributeddatafwk/src/app_distributed_kv_data_manager_impl.cpp b/frameworks/innerkitsimpl/distributeddatafwk/src/app_distributed_kv_data_manager_impl.cpp index a464c22eec65ac3998f7382df0da657833974d79..afa655fa4867caf76799aa03ecb9088f9edab853 100755 --- a/frameworks/innerkitsimpl/distributeddatafwk/src/app_distributed_kv_data_manager_impl.cpp +++ b/frameworks/innerkitsimpl/distributeddatafwk/src/app_distributed_kv_data_manager_impl.cpp @@ -141,7 +141,7 @@ Status AppDistributedKvDataManagerImpl::GetKvStore( Status status = Status::ERROR; DistributedDB::KvStoreNbDelegate::Option dbOption; dbOption.createIfNecessary = options.createIfMissing; - dbOption.isMemoryDb = !options.persistant; + dbOption.isMemoryDb = !options.persistent; dbOption.secOption = ConvertSecurityLevel(options.securityLevel); kvStoreDelegateManager_->GetKvStore( trimmedStoreId, dbOption, diff --git a/frameworks/innerkitsimpl/distributeddatafwk/src/data_query.cpp b/frameworks/innerkitsimpl/distributeddatafwk/src/data_query.cpp index c8fd4ea18ff8ce071900e85c15ed6fc1b12d1a1c..22dd33299f6be910ed7bb3fb0af7a3de29b0a2f2 100755 --- a/frameworks/innerkitsimpl/distributeddatafwk/src/data_query.cpp +++ b/frameworks/innerkitsimpl/distributeddatafwk/src/data_query.cpp @@ -60,7 +60,8 @@ const std::string DataQuery::IN_KEYS = "^IN_KEYS"; constexpr int MAX_QUERY_LENGTH = 5 * 1024; // Max query string length 5k DataQuery::DataQuery() -{} +{ +} DataQuery& DataQuery::Reset() { diff --git a/frameworks/innerkitsimpl/distributeddatafwk/src/ikvstore_client_death_observer.cpp b/frameworks/innerkitsimpl/distributeddatafwk/src/ikvstore_client_death_observer.cpp index 4299647b2863ea3e9329315af833727f6665a95b..2c6616444ed7decd8c7a45782871c41f0163efc6 100644 --- a/frameworks/innerkitsimpl/distributeddatafwk/src/ikvstore_client_death_observer.cpp +++ b/frameworks/innerkitsimpl/distributeddatafwk/src/ikvstore_client_death_observer.cpp @@ -20,11 +20,5 @@ namespace DistributedKv { KvStoreClientDeathObserverProxy::KvStoreClientDeathObserverProxy(const sptr &impl) : IRemoteProxy(impl) {} - -int32_t KvStoreClientDeathObserverStub::OnRemoteRequest(uint32_t code, MessageParcel &data, - MessageParcel &reply, MessageOption &option) -{ - return IPCObjectStub::OnRemoteRequest(code, data, reply, option); -} } // namespace DistributedKv } // namespace OHOS diff --git a/frameworks/innerkitsimpl/distributeddatafwk/src/ikvstore_data_service.cpp b/frameworks/innerkitsimpl/distributeddatafwk/src/ikvstore_data_service.cpp index 18cd0fee44960ec383ebf630abb21aa26d040ee6..068c6a147bff04ddb55a80c1a124e20bbcf8def8 100755 --- a/frameworks/innerkitsimpl/distributeddatafwk/src/ikvstore_data_service.cpp +++ b/frameworks/innerkitsimpl/distributeddatafwk/src/ikvstore_data_service.cpp @@ -49,7 +49,7 @@ Status KvStoreDataServiceProxy::GetKvStore(const Options &options, const AppId & OptionsIpc optionsIpc; optionsIpc.createIfMissing = options.createIfMissing; optionsIpc.encrypt = options.encrypt; - optionsIpc.persistant = options.persistant; + optionsIpc.persistent = options.persistent; optionsIpc.backup = options.backup; optionsIpc.autoSync = options.autoSync; optionsIpc.securityLevel = options.securityLevel; @@ -101,7 +101,7 @@ Status KvStoreDataServiceProxy::GetSingleKvStore(const Options &options, const A OptionsIpc optionsIpc; optionsIpc.createIfMissing = options.createIfMissing; optionsIpc.encrypt = options.encrypt; - optionsIpc.persistant = options.persistant; + optionsIpc.persistent = options.persistent; optionsIpc.backup = options.backup; optionsIpc.autoSync = options.autoSync; optionsIpc.securityLevel = options.securityLevel; @@ -430,7 +430,7 @@ int32_t KvStoreDataServiceStub::GetKvStoreOnRemote(MessageParcel &data, MessageP Options options; options.createIfMissing = optionsIpc.createIfMissing; options.encrypt = optionsIpc.encrypt; - options.persistant = optionsIpc.persistant; + options.persistent = optionsIpc.persistent; options.backup = optionsIpc.backup; options.autoSync = optionsIpc.autoSync; options.securityLevel = optionsIpc.securityLevel; @@ -549,7 +549,7 @@ int32_t KvStoreDataServiceStub::GetSingleKvStoreOnRemote(MessageParcel &data, Me Options options; options.createIfMissing = optionsIpc.createIfMissing; options.encrypt = optionsIpc.encrypt; - options.persistant = optionsIpc.persistant; + options.persistent = optionsIpc.persistent; options.backup = optionsIpc.backup; options.autoSync = optionsIpc.autoSync; options.securityLevel = optionsIpc.securityLevel; diff --git a/frameworks/innerkitsimpl/distributeddatafwk/src/ikvstore_snapshot.cpp b/frameworks/innerkitsimpl/distributeddatafwk/src/ikvstore_snapshot.cpp index 8b8c4aaa48731cb1b2f719864bc1bdc51e97e7f9..9674351ebe935a156ade1c26b85b86f5e5827c38 100755 --- a/frameworks/innerkitsimpl/distributeddatafwk/src/ikvstore_snapshot.cpp +++ b/frameworks/innerkitsimpl/distributeddatafwk/src/ikvstore_snapshot.cpp @@ -64,7 +64,6 @@ void KvStoreSnapshotImplProxy::GetEntries(const Key &prefixKey, const Key &nextK // buffer: | status | entryLength | rawdatasize | (sptr)nextkey | // rawData: ( | keyLen | key | valueLen | value | ){entryLength} int32_t error = Remote()->SendRequest(GETENTRIES, data, reply, mo); - if (error != 0) { ZLOGW("Transact failed"); callback(Status::IPC_ERROR, entries, Key()); @@ -306,7 +305,6 @@ int32_t KvStoreSnapshotImplStub::GetEntriesOnRemote(MessageParcel &data, Message // buffer: | status | entryLength | rawdatasize | (sptr)nextkey | // rawData: ( | keyLen | key | valueLen | value | ){entryLength} sptr keyPrefix = data.ReadParcelable(); - sptr nextKey = data.ReadParcelable(); if (keyPrefix == nullptr) { ZLOGW("keyPrefix is null. return."); if (!reply.WriteInt32(static_cast(Status::INVALID_ARGUMENT))) { @@ -314,6 +312,7 @@ int32_t KvStoreSnapshotImplStub::GetEntriesOnRemote(MessageParcel &data, Message } return 0; } + sptr nextKey = data.ReadParcelable(); if (nextKey == nullptr) { ZLOGW("nextKey is null. return."); if (!reply.WriteInt32(static_cast(Status::INVALID_ARGUMENT))) { @@ -409,7 +408,6 @@ int32_t KvStoreSnapshotImplStub::GetKeysRemote(MessageParcel &data, MessageParce nxtKey = key; }); int bufferSize = GetTotalkeysSize(keyList); - if (bufferSize < Constant::SWITCH_RAW_DATA_SIZE) { return WritekeysParcelable(reply, statusTmp, keyList, bufferSize, nxtKey); } diff --git a/frameworks/innerkitsimpl/distributeddatafwk/src/kvstore_client.h b/frameworks/innerkitsimpl/distributeddatafwk/src/kvstore_client.h index bc964eb2455f27877a5ea8ec6391a5c92ba49f0d..2c8a0abc1d4d70b7a53a670df58fa60fedcb4613 100644 --- a/frameworks/innerkitsimpl/distributeddatafwk/src/kvstore_client.h +++ b/frameworks/innerkitsimpl/distributeddatafwk/src/kvstore_client.h @@ -25,7 +25,6 @@ namespace OHOS { namespace DistributedKv { - class KvStoreClient final : public KvStore { public: explicit KvStoreClient(sptr kvStoreProxy, const std::string &storeId); @@ -65,7 +64,6 @@ private: std::mutex observerMapMutex_; std::string storeId_; }; - } // namespace DistributedKv } // namespace OHOS diff --git a/frameworks/innerkitsimpl/distributeddatafwk/src/kvstore_death_recipient_impl.h b/frameworks/innerkitsimpl/distributeddatafwk/src/kvstore_death_recipient_impl.h index 5e334cde673716964cdc46c5ac3a5ad02c6f87f4..a8deafec2d70e600679fd667d818f24ea53c98ab 100644 --- a/frameworks/innerkitsimpl/distributeddatafwk/src/kvstore_death_recipient_impl.h +++ b/frameworks/innerkitsimpl/distributeddatafwk/src/kvstore_death_recipient_impl.h @@ -21,7 +21,6 @@ namespace OHOS { namespace DistributedKv { - class KvStoreDeathRecipientImpl { public: explicit KvStoreDeathRecipientImpl(std::shared_ptr kvStoreDeathRecipient); @@ -31,7 +30,6 @@ private: std::shared_ptr kvStoreDeathRecipient_; friend struct KvStoreDeathRecipientImplCompare; }; - } // namespace DistributedKv } // namespace OHOS diff --git a/frameworks/innerkitsimpl/distributeddatafwk/src/kvstore_observer_client.h b/frameworks/innerkitsimpl/distributeddatafwk/src/kvstore_observer_client.h index 6e242912a8cd2bc919886c8efde8843433bf7cc0..d7a3340b6b8c11220a83aebb1328aeb140400aa8 100644 --- a/frameworks/innerkitsimpl/distributeddatafwk/src/kvstore_observer_client.h +++ b/frameworks/innerkitsimpl/distributeddatafwk/src/kvstore_observer_client.h @@ -25,7 +25,6 @@ namespace OHOS { namespace DistributedKv { - class KvStoreObserverClient : public KvStoreObserverStub { public: KvStoreObserverClient(const StoreId &storeId, SubscribeType subscribeType, diff --git a/frameworks/innerkitsimpl/distributeddatafwk/src/kvstore_sync_callback_client.h b/frameworks/innerkitsimpl/distributeddatafwk/src/kvstore_sync_callback_client.h index 52ac38e68695ba2b55957339089298c2b99e25af..c738b58bb4b1249d8a073551a91687e90d284f73 100644 --- a/frameworks/innerkitsimpl/distributeddatafwk/src/kvstore_sync_callback_client.h +++ b/frameworks/innerkitsimpl/distributeddatafwk/src/kvstore_sync_callback_client.h @@ -23,7 +23,6 @@ namespace OHOS { namespace DistributedKv { - class KvStoreSyncCallbackClient : public KvStoreSyncCallbackStub { public: KvStoreSyncCallbackClient() = default; diff --git a/frameworks/innerkitsimpl/distributeddatafwk/test/unittest/app_conflict_test.cpp b/frameworks/innerkitsimpl/distributeddatafwk/test/unittest/app_conflict_test.cpp index aaa929001631c855a6aec664ed3666aef1999118..51dda6eb7cd54a2eb7e63e16131a2db8c0e458de 100755 --- a/frameworks/innerkitsimpl/distributeddatafwk/test/unittest/app_conflict_test.cpp +++ b/frameworks/innerkitsimpl/distributeddatafwk/test/unittest/app_conflict_test.cpp @@ -112,7 +112,7 @@ void AppConflictTest::SetUp(void) Options options; options.createIfMissing = true; options.encrypt = false; // not supported yet. - options.persistant = true; // not supported yet. + options.persistent = true; // not supported yet. std::string appId = "odmf"; // define app name. std::string storeId = "conflictdb"; // define kvstore(database) name. diff --git a/frameworks/innerkitsimpl/distributeddatafwk/test/unittest/app_distributed_kv_data_manager_test.cpp b/frameworks/innerkitsimpl/distributeddatafwk/test/unittest/app_distributed_kv_data_manager_test.cpp index 83005769c49c91840e9ea3ffaaa27b99de32b789..09bf431871345404089ead071c5a208ddcb209d1 100755 --- a/frameworks/innerkitsimpl/distributeddatafwk/test/unittest/app_distributed_kv_data_manager_test.cpp +++ b/frameworks/innerkitsimpl/distributeddatafwk/test/unittest/app_distributed_kv_data_manager_test.cpp @@ -63,11 +63,11 @@ void AppDistributedKvDataManagerTest::SetUpTestCase(void) { create.createIfMissing = true; create.encrypt = false; - create.persistant = true; + create.persistent = true; noCreate.createIfMissing = false; noCreate.encrypt = false; - noCreate.persistant = true; + noCreate.persistent = true; appId = "com.ohos.nb.service"; std::string dataDir = "data/misc_ce/0/com.ohos.nb.service"; @@ -325,7 +325,7 @@ HWTEST_F(AppDistributedKvDataManagerTest, AppManagerDeleteKvStore001, TestSize.L /** * @tc.name: AppManagerDeleteKvStore002 - * @tc.desc: Delete a opened KvStore, and the callback should return ILLEGAL_STATE. + * @tc.desc: Delete an opened KvStore, and the callback should return ILLEGAL_STATE. * @tc.type: FUNC * @tc.require: AR000CCPOJ * @tc.author: liqiao diff --git a/frameworks/innerkitsimpl/distributeddatafwk/test/unittest/app_distributed_kv_store_test.cpp b/frameworks/innerkitsimpl/distributeddatafwk/test/unittest/app_distributed_kv_store_test.cpp index 5cb1421db11b3cf2c11756fc2a3e9ba59c42b7fd..36091ec719044a33bc8c713b418ba8ae94f349fb 100755 --- a/frameworks/innerkitsimpl/distributeddatafwk/test/unittest/app_distributed_kv_store_test.cpp +++ b/frameworks/innerkitsimpl/distributeddatafwk/test/unittest/app_distributed_kv_store_test.cpp @@ -76,7 +76,7 @@ void AppDistributedKvStoreTest::SetUpTestCase(void) syncWrite.local = false; options.createIfMissing = true; options.encrypt = false; - options.persistant = true; + options.persistent = true; } void AppDistributedKvStoreTest::TearDownTestCase(void) @@ -419,13 +419,13 @@ HWTEST_F(AppDistributedKvStoreTest, AppKvstorePut007, TestSize.Level1) status = appKvStorePtr->Get(localRead, Key("teacher_name_wanger"), ret); EXPECT_EQ(status, Status::SUCCESS); ASSERT_EQ(ret.Size(), val.size()); - for(unsigned long i = 0; i < ret.Size(); i++) { + for (unsigned long i = 0; i < ret.Size(); i++) { EXPECT_EQ(ret.Data()[i], val[i]); } status = appKvStorePtr->Get(syncRead, Key("teacher_name_wanger"), ret); EXPECT_EQ(status, Status::SUCCESS); ASSERT_EQ(ret.Size(), val.size()); - for(unsigned long i = 0; i < ret.Size(); i++) { + for (unsigned long i = 0; i < ret.Size(); i++) { EXPECT_EQ(ret.Data()[i], val[i]); } @@ -582,8 +582,9 @@ HWTEST_F(AppDistributedKvStoreTest, AppKvstorePut011, TestSize.Level1) std::string Generate1025KeyLen() { // Generate key and the length is more than 1024; + constexpr int KEY_MAX_LENGTH = 1024; std::string str("prefix"); - for (int i = 0; i < 1024; i++) { + for (int i = 0; i < KEY_MAX_LENGTH; i++) { str += "a"; } return str; diff --git a/frameworks/innerkitsimpl/distributeddatafwk/test/unittest/distributed_kv_data_manager_test.cpp b/frameworks/innerkitsimpl/distributeddatafwk/test/unittest/distributed_kv_data_manager_test.cpp index a7937ddf2b33460f603916772ae2c0efabc81776..bd6aa922c28ea4e53235719097f49be1a51a7c2f 100755 --- a/frameworks/innerkitsimpl/distributeddatafwk/test/unittest/distributed_kv_data_manager_test.cpp +++ b/frameworks/innerkitsimpl/distributeddatafwk/test/unittest/distributed_kv_data_manager_test.cpp @@ -799,9 +799,6 @@ HWTEST_F(DistributedKvDataManagerTest, GetDevice001, TestSize.Level1) std::vector infos; status = manager.GetDeviceList(infos, DeviceFilterStrategy::FILTER); - // EXPECT_EQ(Status::SUCCESS, status) << "expected GetDeviceList true"; - // EXPECT_TRUE(infos.size() == 0) << "expected GetDeviceList exist"; - auto listener = std::make_shared(); status = manager.StartWatchDeviceChange(listener); EXPECT_EQ(Status::SUCCESS, status) << "expected StartWatchDeviceChange true"; diff --git a/frameworks/innerkitsimpl/distributeddatafwk/test/unittest/single_kvstore_client_query_test.cpp b/frameworks/innerkitsimpl/distributeddatafwk/test/unittest/single_kvstore_client_query_test.cpp index ae6fff015f673e5b44e0741ce79ac86442520320..5ffa3fb5e133005241ae522490397dedf0ecb1d7 100755 --- a/frameworks/innerkitsimpl/distributeddatafwk/test/unittest/single_kvstore_client_query_test.cpp +++ b/frameworks/innerkitsimpl/distributeddatafwk/test/unittest/single_kvstore_client_query_test.cpp @@ -279,7 +279,7 @@ HWTEST_F(SingleKvStoreClientQueryTest, TestQueryC009, TestSize.Level1) query.InLong("$.test_field_name", vectLong); EXPECT_TRUE(query.ToString().length() > 0); query.Reset(); - std::vector vectDouble{ 1.23, 2.23, 3.23 }; + std::vector vectDouble{1.23, 2.23, 3.23}; query.InDouble("$.test_field_name", vectDouble); EXPECT_TRUE(query.ToString().length() > 0); query.Reset(); diff --git a/frameworks/innerkitsimpl/rdb/src/rdb_notifier.cpp b/frameworks/innerkitsimpl/rdb/src/rdb_notifier.cpp index 0893214aa8028df547b90ae6e809641f439533a1..dba5a48a5db4b19e2a94807036cfa7f15aac6da2 100644 --- a/frameworks/innerkitsimpl/rdb/src/rdb_notifier.cpp +++ b/frameworks/innerkitsimpl/rdb/src/rdb_notifier.cpp @@ -151,7 +151,7 @@ int32_t RdbNotifierStub::OnChangeInner(MessageParcel &data, MessageParcel &reply } std::vector devices; if (!data.ReadStringVector(&devices)) { - ZLOGE("read devices faield"); + ZLOGE("read devices failed"); return RDB_ERROR; } return OnChange(storeName, devices); diff --git a/frameworks/jskitsimpl/distributeddata/include/js_field_node.h b/frameworks/jskitsimpl/distributeddata/include/js_field_node.h index 693c499a72900903842bcfa2eea268be820b9887..3b0e382701cfc9b9d7cf46ad298f5842d960a9fa 100644 --- a/frameworks/jskitsimpl/distributeddata/include/js_field_node.h +++ b/frameworks/jskitsimpl/distributeddata/include/js_field_node.h @@ -42,7 +42,12 @@ private: static napi_value SetNullable(napi_env env, napi_callback_info info); static napi_value GetValueType(napi_env env, napi_callback_info info); static napi_value SetValueType(napi_env env, napi_callback_info info); - + static std::map valueTypeToString_; + + template + static napi_value GetContextValue(napi_env env, std::shared_ptr &ctxt, T &value); + static JsFieldNode* GetFieldNode(napi_env env, napi_callback_info info, std::shared_ptr &ctxt); + std::string ValueToString(JSUtil::KvStoreVariant value); std::string ValueTypeToString(uint32_t type); diff --git a/frameworks/jskitsimpl/distributeddata/include/js_schema.h b/frameworks/jskitsimpl/distributeddata/include/js_schema.h index 961de71b0dabc3befb4e8cbecf54aa85392408d4..2396bf8ab3bdce7c3686fdae27321ef791dbf4a0 100644 --- a/frameworks/jskitsimpl/distributeddata/include/js_schema.h +++ b/frameworks/jskitsimpl/distributeddata/include/js_schema.h @@ -42,6 +42,11 @@ private: static napi_value GetIndexes(napi_env env, napi_callback_info info); static napi_value SetIndexes(napi_env env, napi_callback_info info); + template + static napi_value GetContextValue(napi_env env, std::shared_ptr& ctxt, T &value); + + static JsSchema* GetSchema(napi_env env, napi_callback_info info, std::shared_ptr &ctxt); + enum { SCHEMA_MODE_SLOPPY, SCHEMA_MODE_STRICT, diff --git a/frameworks/jskitsimpl/distributeddata/include/napi_queue.h b/frameworks/jskitsimpl/distributeddata/include/napi_queue.h index afb65f967eaf26cffef7697213c01c69c1720867..0febdaf3dbe6f6df5238fec07f1d15370007c43f 100644 --- a/frameworks/jskitsimpl/distributeddata/include/napi_queue.h +++ b/frameworks/jskitsimpl/distributeddata/include/napi_queue.h @@ -62,7 +62,7 @@ private: }; /* check condition related to argc/argv, return and logging. */ -#define CHECK_ARGS(ctxt, condition, message) \ +#define CHECK_ARGS_RETURN_VOID(ctxt, condition, message) \ do { \ if (!(condition)) { \ (ctxt)->status = napi_invalid_arg; \ @@ -72,7 +72,7 @@ private: } \ } while (0) -#define CHECK_STATUS(ctxt, message) \ +#define CHECK_STATUS_RETURN_VOID(ctxt, message) \ do { \ if ((ctxt)->status != napi_ok) { \ (ctxt)->error = std::string(message); \ diff --git a/frameworks/jskitsimpl/distributeddata/src/js_device_kv_store.cpp b/frameworks/jskitsimpl/distributeddata/src/js_device_kv_store.cpp index 15e513ff39b18620547a3a0bade600735fd437d9..7034d5883b2a0c7ca555d661e3ead15484ff6684 100644 --- a/frameworks/jskitsimpl/distributeddata/src/js_device_kv_store.cpp +++ b/frameworks/jskitsimpl/distributeddata/src/js_device_kv_store.cpp @@ -86,11 +86,11 @@ napi_value JsDeviceKVStore::Get(napi_env env, napi_callback_info info) auto ctxt = std::make_shared(); auto input = [env, ctxt](size_t argc, napi_value* argv) { // number 2 means: required 2 arguments, + - CHECK_ARGS(ctxt, argc == 2, "invalid arguments!"); + CHECK_ARGS_RETURN_VOID(ctxt, argc == 2, "invalid arguments!"); ctxt->status = JSUtil::GetValue(env, argv[0], ctxt->deviceId); - CHECK_STATUS(ctxt, "invalid arg[0], i.e. invalid deviceId!"); + CHECK_STATUS_RETURN_VOID(ctxt, "invalid arg[0], i.e. invalid deviceId!"); ctxt->status = JSUtil::GetValue(env, argv[1], ctxt->key); - CHECK_STATUS(ctxt, "invalid arg[1], i.e. invalid key!"); + CHECK_STATUS_RETURN_VOID(ctxt, "invalid arg[1], i.e. invalid key!"); }; ctxt->GetCbInfo(env, info, input); @@ -103,11 +103,11 @@ napi_value JsDeviceKVStore::Get(napi_env env, napi_callback_info info) ZLOGD("kvStore->Get return %{public}d", status); ctxt->value = JSUtil::Blob2VariantValue(value); ctxt->status = (status == Status::SUCCESS) ? napi_ok : napi_generic_failure; - CHECK_STATUS(ctxt, "kvStore->Get() failed!"); + CHECK_STATUS_RETURN_VOID(ctxt, "kvStore->Get() failed!"); }; auto output = [env, ctxt](napi_value& result) { ctxt->status = JSUtil::SetValue(env, ctxt->value, result); - CHECK_STATUS(ctxt, "output failed"); + CHECK_STATUS_RETURN_VOID(ctxt, "output failed"); }; return NapiQueue::AsyncWork(env, ctxt, std::string(__FUNCTION__), execute, output); } @@ -181,7 +181,7 @@ napi_value JsDeviceKVStore::GetEntries(napi_env env, napi_callback_info info) auto ctxt = std::make_shared(); auto input = [env, ctxt](size_t argc, napi_value* argv) { ctxt->status = GetVariantArgs(env, argc, argv, ctxt->va); - CHECK_STATUS(ctxt, "invalid arguments!"); + CHECK_STATUS_RETURN_VOID(ctxt, "invalid arguments!"); }; ctxt->GetCbInfo(env, info, input); @@ -204,11 +204,11 @@ napi_value JsDeviceKVStore::GetEntries(napi_env env, napi_callback_info info) ZLOGD("kvStore->GetEntriesWithQuery() return %{public}d", status); } ctxt->status = (status == Status::SUCCESS) ? napi_ok : napi_generic_failure; - CHECK_STATUS(ctxt, "kvStore->GetEntries() failed!"); + CHECK_STATUS_RETURN_VOID(ctxt, "kvStore->GetEntries() failed!"); }; auto output = [env, ctxt](napi_value& result) { ctxt->status = JSUtil::SetValue(env, ctxt->entries, result); - CHECK_STATUS(ctxt, "output failed!"); + CHECK_STATUS_RETURN_VOID(ctxt, "output failed!"); }; return NapiQueue::AsyncWork(env, ctxt, std::string(__FUNCTION__), execute, output); } @@ -235,10 +235,10 @@ napi_value JsDeviceKVStore::GetResultSet(napi_env env, napi_callback_info info) auto ctxt = std::make_shared(); auto input = [env, ctxt](size_t argc, napi_value* argv) { ctxt->status = GetVariantArgs(env, argc, argv, ctxt->va); - CHECK_STATUS(ctxt, "invalid arguments!"); + CHECK_STATUS_RETURN_VOID(ctxt, "invalid arguments!"); ctxt->ref = JSUtil::NewWithRef(env, 0, nullptr, (void**)(&ctxt->resultSet), JsKVStoreResultSet::Constructor(env)); - CHECK_ARGS(ctxt, ctxt->resultSet != nullptr, "KVStoreResultSet::New failed!"); + CHECK_ARGS_RETURN_VOID(ctxt, ctxt->resultSet != nullptr, "KVStoreResultSet::New failed!"); }; ctxt->GetCbInfo(env, info, input); @@ -262,13 +262,13 @@ napi_value JsDeviceKVStore::GetResultSet(napi_env env, napi_callback_info info) ZLOGD("kvStore->GetEntriesWithQuery() return %{public}d", status); } ctxt->status = (status == Status::SUCCESS) ? napi_ok : napi_generic_failure; - CHECK_STATUS(ctxt, "kvStore->GetResultSet() failed!"); + CHECK_STATUS_RETURN_VOID(ctxt, "kvStore->GetResultSet() failed!"); ctxt->resultSet->SetNative(kvResultSet); }; auto output = [env, ctxt](napi_value& result) { ctxt->status = napi_get_reference_value(env, ctxt->ref, &result); napi_delete_reference(env, ctxt->ref); - CHECK_STATUS(ctxt, "output KvResultSet failed"); + CHECK_STATUS_RETURN_VOID(ctxt, "output KvResultSet failed"); }; return NapiQueue::AsyncWork(env, ctxt, std::string(__FUNCTION__), execute, output); } @@ -287,13 +287,13 @@ napi_value JsDeviceKVStore::CloseResultSet(napi_env env, napi_callback_info info auto ctxt = std::make_shared(); auto input = [env, ctxt](size_t argc, napi_value* argv) { // required 1 arguments :: - CHECK_ARGS(ctxt, argc == 1, "invalid arguments!"); + CHECK_ARGS_RETURN_VOID(ctxt, argc == 1, "invalid arguments!"); napi_valuetype type = napi_undefined; ctxt->status = napi_typeof(env, argv[0], &type); - CHECK_ARGS(ctxt, type == napi_object, "invalid arg[0], i.e. invalid resultSet!"); + CHECK_ARGS_RETURN_VOID(ctxt, type == napi_object, "invalid arg[0], i.e. invalid resultSet!"); ctxt->status = JSUtil::Unwrap(env, argv[0], (void**)(&ctxt->resultSet), JsKVStoreResultSet::Constructor(env)); - CHECK_ARGS(ctxt, ctxt->resultSet != nullptr, "invalid arg[0], i.e. invalid resultSet!"); + CHECK_ARGS_RETURN_VOID(ctxt, ctxt->resultSet != nullptr, "invalid arg[0], i.e. invalid resultSet!"); }; ctxt->GetCbInfo(env, info, input); @@ -302,7 +302,7 @@ napi_value JsDeviceKVStore::CloseResultSet(napi_env env, napi_callback_info info Status status = kvStore->CloseResultSet(ctxt->resultSet->GetNative()); ZLOGD("kvStore->CloseResultSet return %{public}d", status); ctxt->status = (status == Status::SUCCESS) ? napi_ok : napi_generic_failure; - CHECK_STATUS(ctxt, "kvStore->CloseResultSet failed!"); + CHECK_STATUS_RETURN_VOID(ctxt, "kvStore->CloseResultSet failed!"); }; return NapiQueue::AsyncWork(env, ctxt, std::string(__FUNCTION__), execute); } @@ -325,9 +325,9 @@ napi_value JsDeviceKVStore::GetResultSize(napi_env env, napi_callback_info info) auto ctxt = std::make_shared(); auto input = [env, ctxt](size_t argc, napi_value* argv) { ctxt->status = GetVariantArgs(env, argc, argv, ctxt->va); - CHECK_ARGS(ctxt, (ctxt->va.type == ArgsType::DEVICEID_QUERY) || (ctxt->va.type == ArgsType::QUERY), + CHECK_ARGS_RETURN_VOID(ctxt, (ctxt->va.type == ArgsType::DEVICEID_QUERY) || (ctxt->va.type == ArgsType::QUERY), "invalid arguments!"); - CHECK_STATUS(ctxt, "invalid arguments!"); + CHECK_STATUS_RETURN_VOID(ctxt, "invalid arguments!"); }; ctxt->GetCbInfo(env, info, input); @@ -340,11 +340,11 @@ napi_value JsDeviceKVStore::GetResultSize(napi_env env, napi_callback_info info) Status status = kvStore->GetCountWithQuery(query.ToString(), ctxt->resultSize); ZLOGD("kvStore->GetCountWithQuery() return %{public}d", status); ctxt->status = (status == Status::SUCCESS) ? napi_ok : napi_generic_failure; - CHECK_STATUS(ctxt, "kvStore->GetCountWithQuery() failed!"); + CHECK_STATUS_RETURN_VOID(ctxt, "kvStore->GetCountWithQuery() failed!"); }; auto output = [env, ctxt](napi_value& result) { ctxt->status = JSUtil::SetValue(env, static_cast(ctxt->resultSize), result); - CHECK_STATUS(ctxt, "output resultSize failed!"); + CHECK_STATUS_RETURN_VOID(ctxt, "output resultSize failed!"); }; return NapiQueue::AsyncWork(env, ctxt, std::string(__FUNCTION__), execute, output); } @@ -363,9 +363,9 @@ napi_value JsDeviceKVStore::RemoveDeviceData(napi_env env, napi_callback_info in auto ctxt = std::make_shared(); auto input = [env, ctxt](size_t argc, napi_value* argv) { // required 1 arguments :: - CHECK_ARGS(ctxt, argc == 1, "invalid arguments!"); + CHECK_ARGS_RETURN_VOID(ctxt, argc == 1, "invalid arguments!"); ctxt->status = JSUtil::GetValue(env, argv[0], ctxt->deviceId); - CHECK_STATUS(ctxt, "invalid arg[0], i.e. invalid deviceId!"); + CHECK_STATUS_RETURN_VOID(ctxt, "invalid arg[0], i.e. invalid deviceId!"); }; ctxt->GetCbInfo(env, info, input); @@ -374,7 +374,7 @@ napi_value JsDeviceKVStore::RemoveDeviceData(napi_env env, napi_callback_info in Status status = kvStore->RemoveDeviceData(ctxt->deviceId); ZLOGD("kvStore->RemoveDeviceData return %{public}d", status); ctxt->status = (status == Status::SUCCESS) ? napi_ok : napi_generic_failure; - CHECK_STATUS(ctxt, "kvStore->RemoveDeviceData() failed!"); + CHECK_STATUS_RETURN_VOID(ctxt, "kvStore->RemoveDeviceData() failed!"); }; return NapiQueue::AsyncWork(env, ctxt, std::string(__FUNCTION__), execute); } @@ -392,12 +392,12 @@ napi_value JsDeviceKVStore::Sync(napi_env env, napi_callback_info info) auto ctxt = std::make_shared(); auto input = [env, ctxt](size_t argc, napi_value* argv) { // required 2 arguments :: + - CHECK_ARGS(ctxt, argc == 2, "invalid arguments!"); + CHECK_ARGS_RETURN_VOID(ctxt, argc == 2, "invalid arguments!"); ctxt->status = JSUtil::GetValue(env, argv[0], ctxt->deviceIdList); - CHECK_STATUS(ctxt, "invalid arg[0], i.e. invalid deviceIdList!"); + CHECK_STATUS_RETURN_VOID(ctxt, "invalid arg[0], i.e. invalid deviceIdList!"); ctxt->status = JSUtil::GetValue(env, argv[1], ctxt->mode); - CHECK_STATUS(ctxt, "invalid arg[1], i.e. invalid mode!"); - CHECK_ARGS(ctxt, ctxt->mode <= uint32_t(SyncMode::PUSH_PULL), "invalid arg[1], i.e. invalid mode!"); + CHECK_STATUS_RETURN_VOID(ctxt, "invalid arg[1], i.e. invalid mode!"); + CHECK_ARGS_RETURN_VOID(ctxt, ctxt->mode <= uint32_t(SyncMode::PUSH_PULL), "invalid arg[1], i.e. invalid mode!"); }; ctxt->GetCbInfoSync(env, info, input); NAPI_ASSERT(env, ctxt->status == napi_ok, "invalid arguments!"); @@ -416,10 +416,10 @@ napi_value JsDeviceKVStore::New(napi_env env, napi_callback_info info) auto ctxt = std::make_shared(); auto input = [env, ctxt, &storeId](size_t argc, napi_value* argv) { // required 2 arguments :: - CHECK_ARGS(ctxt, argc == 2, "invalid arguments!"); + CHECK_ARGS_RETURN_VOID(ctxt, argc == 2, "invalid arguments!"); ctxt->status = JSUtil::GetValue(env, argv[0], storeId); - CHECK_STATUS(ctxt, "invalid arg[0], i.e. invalid storeId!"); - CHECK_ARGS(ctxt, !storeId.empty(), "invalid arg[0], i.e. invalid storeId!"); + CHECK_STATUS_RETURN_VOID(ctxt, "invalid arg[0], i.e. invalid storeId!"); + CHECK_ARGS_RETURN_VOID(ctxt, !storeId.empty(), "invalid arg[0], i.e. invalid storeId!"); }; ctxt->GetCbInfoSync(env, info, input); NAPI_ASSERT(env, ctxt->status == napi_ok, "invalid arguments!"); diff --git a/frameworks/jskitsimpl/distributeddata/src/js_field_node.cpp b/frameworks/jskitsimpl/distributeddata/src/js_field_node.cpp index ea5b8b230dcbd3bac9488f6944826b8f4c360c40..c18072280a2c22449e46e005b3a664f48d710f18 100644 --- a/frameworks/jskitsimpl/distributeddata/src/js_field_node.cpp +++ b/frameworks/jskitsimpl/distributeddata/src/js_field_node.cpp @@ -22,13 +22,22 @@ using namespace OHOS::DistributedKv; namespace OHOS::DistributedData { -static std::string FIELDNAME = "FIELDNAME"; -static std::string VALUETYPE = "VALUETYPE"; -static std::string DEFAULTVALUE = "DEFAULTVALUE"; -static std::string ISWITHDEFAULTVALUE = "ISWITHDEFAULTVALUE"; -static std::string ISNULLABLE = "ISNULLABLE"; +static std::string FIELD_NAME = "FIELD_NAME"; +static std::string VALUE_TYPE = "VALUE_TYPE"; +static std::string DEFAULT_VALUE = "DEFAULT_VALUE"; +static std::string IS_DEFAULT_VALUE = "IS_DEFAULT_VALUE"; +static std::string IS_NULLABLE = "IS_NULLABLE"; static std::string CHILDREN = "CHILDREN"; +std::map JsFieldNode::valueTypeToString_ = { + { JSUtil::STRING, std::string("STRING") }, + { JSUtil::INTEGER, std::string("INTEGER") }, + { JSUtil::FLOAT, std::string("FLOAT") }, + { JSUtil::BYTE_ARRAY, std::string("BYTE_ARRAY") }, + { JSUtil::BOOLEAN, std::string("BOOLEAN") }, + { JSUtil::DOUBLE, std::string("DOUBLE") } +}; + JsFieldNode::JsFieldNode(const std::string& fName) : fieldName(fName) { @@ -41,20 +50,15 @@ std::string JsFieldNode::GetFieldName() JsFieldNode::json JsFieldNode::GetValueForJson() { - if (!fields.empty()) { - /* example: - { "field_root": { - "field_child1": "LONG, NOT NULL, DEFAULT 88", - "field_child2": "LONG, NOT NULL, DEFAULT 88" } } */ - json jsFields; - for (auto fld : fields) { - jsFields[fld->fieldName] = fld->GetValueForJson(); - } - return jsFields; + if (fields.empty()) { + return ValueTypeToString(valueType) + "," + (isNullable ? "NULL" : "NOT NULL"); } - /* example: { "field_name": "LONG, NOT NULL, DEFAULT 88" } */ - return ValueTypeToString(valueType) + "," + (isNullable ? "NULL" : "NOT NULL"); + json jsFields; + for (auto fld : fields) { + jsFields[fld->fieldName] = fld->GetValueForJson(); + } + return jsFields; } napi_value JsFieldNode::Constructor(napi_env env) @@ -76,10 +80,10 @@ napi_value JsFieldNode::New(napi_env env, napi_callback_info info) auto ctxt = std::make_shared(); auto input = [env, ctxt, &fieldName](size_t argc, napi_value* argv) { // required 1 arguments :: - CHECK_ARGS(ctxt, argc == 1, "invalid arguments!"); + CHECK_ARGS_RETURN_VOID(ctxt, argc == 1, "invalid arguments!"); ctxt->status = JSUtil::GetValue(env, argv[0], fieldName); - CHECK_STATUS(ctxt, "invalid arg[0], i.e. invalid fieldName!"); - CHECK_ARGS(ctxt, !fieldName.empty(), "invalid arg[0], i.e. invalid fieldName!"); + CHECK_STATUS_RETURN_VOID(ctxt, "invalid arg[0], i.e. invalid fieldName!"); + CHECK_ARGS_RETURN_VOID(ctxt, !fieldName.empty(), "invalid arg[0], i.e. invalid fieldName!"); }; ctxt->GetCbInfoSync(env, info, input); NAPI_ASSERT(env, ctxt->status == napi_ok, "invalid arguments!"); @@ -104,10 +108,10 @@ napi_value JsFieldNode::AppendChild(napi_env env, napi_callback_info info) auto ctxt = std::make_shared(); auto input = [env, ctxt, &child](size_t argc, napi_value* argv) { // required 1 arguments :: - CHECK_ARGS(ctxt, argc == 1, "invalid arguments!"); + CHECK_ARGS_RETURN_VOID(ctxt, argc == 1, "invalid arguments!"); ctxt->status = JSUtil::Unwrap(env, argv[0], (void**)(&child), JsFieldNode::Constructor(env)); - CHECK_STATUS(ctxt, "napi_unwrap to FieldNode failed"); - CHECK_ARGS(ctxt, child != nullptr, "invalid arg[0], i.e. invalid FieldNode!"); + CHECK_STATUS_RETURN_VOID(ctxt, "napi_unwrap to FieldNode failed"); + CHECK_ARGS_RETURN_VOID(ctxt, child != nullptr, "invalid arg[0], i.e. invalid FieldNode!"); }; ctxt->GetCbInfoSync(env, info, input); NAPI_ASSERT(env, ctxt->status == napi_ok, "invalid arguments!"); @@ -119,18 +123,28 @@ napi_value JsFieldNode::AppendChild(napi_env env, napi_callback_info info) return ctxt->output; } -napi_value JsFieldNode::GetDefaultValue(napi_env env, napi_callback_info info) +JsFieldNode* JsFieldNode::GetFieldNode(napi_env env, napi_callback_info info, std::shared_ptr& ctxt) { - ZLOGD("FieldNode::GetDefaultValue"); - auto ctxt = std::make_shared(); ctxt->GetCbInfoSync(env, info); NAPI_ASSERT(env, ctxt->status == napi_ok, "invalid arguments!"); + return reinterpret_cast(ctxt->native); +} - auto fieldNode = reinterpret_cast(ctxt->native); - JSUtil::SetValue(env, fieldNode->defaultValue, ctxt->output); +template +napi_value JsFieldNode::GetContextValue(napi_env env, std::shared_ptr &ctxt, T &value) +{ + JSUtil::SetValue(env, value, ctxt->output); return ctxt->output; } +napi_value JsFieldNode::GetDefaultValue(napi_env env, napi_callback_info info) +{ + ZLOGD("FieldNode::GetDefaultValue"); + auto ctxt = std::make_shared(); + auto fieldNode = GetFieldNode(env, info, ctxt); + return GetContextValue(env, ctxt, fieldNode->defaultValue); +} + napi_value JsFieldNode::SetDefaultValue(napi_env env, napi_callback_info info) { ZLOGD("FieldNode::SetDefaultValue"); @@ -138,9 +152,9 @@ napi_value JsFieldNode::SetDefaultValue(napi_env env, napi_callback_info info) JSUtil::KvStoreVariant vv; auto input = [env, ctxt, &vv](size_t argc, napi_value* argv) { // required 1 arguments :: - CHECK_ARGS(ctxt, argc == 1, "invalid arguments!"); + CHECK_ARGS_RETURN_VOID(ctxt, argc == 1, "invalid arguments!"); ctxt->status = JSUtil::GetValue(env, argv[0], vv); - CHECK_STATUS(ctxt, "invalid arg[0], i.e. invalid defaultValue!"); + CHECK_STATUS_RETURN_VOID(ctxt, "invalid arg[0], i.e. invalid defaultValue!"); }; ctxt->GetCbInfoSync(env, info, input); NAPI_ASSERT(env, ctxt->status == napi_ok, "invalid arguments!"); @@ -154,12 +168,8 @@ napi_value JsFieldNode::GetNullable(napi_env env, napi_callback_info info) { ZLOGD("FieldNode::GetNullable"); auto ctxt = std::make_shared(); - ctxt->GetCbInfoSync(env, info); - NAPI_ASSERT(env, ctxt->status == napi_ok, "invalid arguments!"); - - auto fieldNode = reinterpret_cast(ctxt->native); - JSUtil::SetValue(env, fieldNode->isNullable, ctxt->output); - return ctxt->output; + auto fieldNode = GetFieldNode(env, info, ctxt); + return GetContextValue(env, ctxt, fieldNode->isNullable); } napi_value JsFieldNode::SetNullable(napi_env env, napi_callback_info info) @@ -169,9 +179,9 @@ napi_value JsFieldNode::SetNullable(napi_env env, napi_callback_info info) bool isNullable = false; auto input = [env, ctxt, &isNullable](size_t argc, napi_value* argv) { // required 1 arguments :: - CHECK_ARGS(ctxt, argc == 1, "invalid arguments!"); + CHECK_ARGS_RETURN_VOID(ctxt, argc == 1, "invalid arguments!"); ctxt->status = JSUtil::GetValue(env, argv[0], isNullable); - CHECK_STATUS(ctxt, "invalid arg[0], i.e. invalid isNullable!"); + CHECK_STATUS_RETURN_VOID(ctxt, "invalid arg[0], i.e. invalid isNullable!"); }; ctxt->GetCbInfoSync(env, info, input); NAPI_ASSERT(env, ctxt->status == napi_ok, "invalid arguments!"); @@ -183,14 +193,10 @@ napi_value JsFieldNode::SetNullable(napi_env env, napi_callback_info info) napi_value JsFieldNode::GetValueType(napi_env env, napi_callback_info info) { - ZLOGD("FieldNode::New"); + ZLOGD("FieldNode::GetValueType"); auto ctxt = std::make_shared(); - ctxt->GetCbInfoSync(env, info); - NAPI_ASSERT(env, ctxt->status == napi_ok, "invalid arguments!"); - - auto fieldNode = reinterpret_cast(ctxt->native); - JSUtil::SetValue(env, fieldNode->valueType, ctxt->output); - return ctxt->output; + auto fieldNode = GetFieldNode(env, info, ctxt); + return GetContextValue(env, ctxt, fieldNode->valueType); } napi_value JsFieldNode::SetValueType(napi_env env, napi_callback_info info) @@ -200,10 +206,10 @@ napi_value JsFieldNode::SetValueType(napi_env env, napi_callback_info info) uint32_t type = 0; auto input = [env, ctxt, &type](size_t argc, napi_value* argv) { // required 1 arguments :: - CHECK_ARGS(ctxt, argc == 1, "invalid arguments!"); + CHECK_ARGS_RETURN_VOID(ctxt, argc == 1, "invalid arguments!"); ctxt->status = JSUtil::GetValue(env, argv[0], type); - CHECK_STATUS(ctxt, "invalid arg[0], i.e. invalid valueType!"); - CHECK_ARGS(ctxt, (JSUtil::STRING <= type) && (type <= JSUtil::DOUBLE), + CHECK_STATUS_RETURN_VOID(ctxt, "invalid arg[0], i.e. invalid valueType!"); + CHECK_ARGS_RETURN_VOID(ctxt, (JSUtil::STRING <= type) && (type <= JSUtil::DOUBLE), "invalid arg[0], i.e. invalid valueType!"); }; ctxt->GetCbInfoSync(env, info, input); @@ -243,25 +249,14 @@ std::string JsFieldNode::ValueToString(JSUtil::KvStoreVariant value) std::string JsFieldNode::ValueTypeToString(uint32_t type) { // DistributedDB::FieldType - switch (type) { - case JSUtil::STRING: - return std::string("STRING"); - case JSUtil::INTEGER: - return std::string("INTEGER"); - case JSUtil::FLOAT: - return std::string("FLOAT"); - case JSUtil::BYTE_ARRAY: - return std::string("BYTE_ARRAY"); - case JSUtil::BOOLEAN: - return std::string("BOOLEAN"); - case JSUtil::DOUBLE: - return std::string("DOUBLE"); - default: - ZLOGE("ValueType is INVALID"); - break; + auto it = valueTypeToString_.find(type); + if (valueTypeToString_.find(type) != valueTypeToString_.end()) { + return it->second; + } else { + return std::string(); } - return std::string(); } + std::string JsFieldNode::Dump() { json jsFields; @@ -270,11 +265,11 @@ std::string JsFieldNode::Dump() } json jsNode = { - { FIELDNAME, fieldName }, - { VALUETYPE, ValueTypeToString(valueType) }, - { DEFAULTVALUE, ValueToString(defaultValue) }, - { ISWITHDEFAULTVALUE, isWithDefaultValue }, - { ISNULLABLE, isNullable }, + { FIELD_NAME, fieldName }, + { VALUE_TYPE, ValueTypeToString(valueType) }, + { DEFAULT_VALUE, ValueToString(defaultValue) }, + { IS_DEFAULT_VALUE, isWithDefaultValue }, + { IS_NULLABLE, isNullable }, { CHILDREN, jsFields.dump() } }; return jsNode.dump(); diff --git a/frameworks/jskitsimpl/distributeddata/src/js_kv_manager.cpp b/frameworks/jskitsimpl/distributeddata/src/js_kv_manager.cpp index 5073d5c1b7cb918719c809e1a1d2ee7e87908ed9..75964896209cad8ef30ebdbee72dfdff682ed265 100644 --- a/frameworks/jskitsimpl/distributeddata/src/js_kv_manager.cpp +++ b/frameworks/jskitsimpl/distributeddata/src/js_kv_manager.cpp @@ -60,13 +60,13 @@ napi_value JsKVManager::CreateKVManager(napi_env env, napi_callback_info info) auto ctxt = std::make_shared(); auto input = [env, ctxt](size_t argc, napi_value* argv) { // required 1 arguments :: - CHECK_ARGS(ctxt, argc == 1, "invalid arguments!"); + CHECK_ARGS_RETURN_VOID(ctxt, argc == 1, "invalid arguments!"); std::string bundleName; ctxt->status = JSUtil::GetNamedProperty(env, argv[0], "bundleName", bundleName); - CHECK_ARGS(ctxt, (ctxt->status == napi_ok) && !bundleName.empty(), "invalid bundleName!"); + CHECK_ARGS_RETURN_VOID(ctxt, (ctxt->status == napi_ok) && !bundleName.empty(), "invalid bundleName!"); ctxt->ref = JSUtil::NewWithRef(env, argc, argv, (void**)&ctxt->kvManger, JsKVManager::Constructor(env)); - CHECK_ARGS(ctxt, ctxt->kvManger != nullptr, "KVManager::New failed!"); + CHECK_ARGS_RETURN_VOID(ctxt, ctxt->kvManger != nullptr, "KVManager::New failed!"); }; ctxt->GetCbInfo(env, info, input); @@ -74,7 +74,7 @@ napi_value JsKVManager::CreateKVManager(napi_env env, napi_callback_info info) auto output = [env, ctxt](napi_value& result) { ctxt->status = napi_get_reference_value(env, ctxt->ref, &result); napi_delete_reference(env, ctxt->ref); - CHECK_STATUS(ctxt, "output KVManager failed"); + CHECK_STATUS_RETURN_VOID(ctxt, "output KVManager failed"); }; return NapiQueue::AsyncWork(env, ctxt, std::string(__FUNCTION__), noExecute, output); } @@ -89,12 +89,12 @@ struct GetKVStoreContext : public ContextBase { { auto input = [env, this](size_t argc, napi_value* argv) { // required 2 arguments :: - CHECK_ARGS(this, argc == 2, "invalid arguments!"); + CHECK_ARGS_RETURN_VOID(this, argc == 2, "invalid arguments!"); status = JSUtil::GetValue(env, argv[0], storeId); - CHECK_ARGS(this, (status == napi_ok) && !storeId.empty(), "invalid storeId!"); + CHECK_ARGS_RETURN_VOID(this, (status == napi_ok) && !storeId.empty(), "invalid storeId!"); status = JSUtil::GetValue(env, argv[1], options); - CHECK_STATUS(this, "invalid options!"); - CHECK_ARGS(this, IsStoreTypeSupported(options), "invalid options.KvStoreType"); + CHECK_STATUS_RETURN_VOID(this, "invalid options!"); + CHECK_ARGS_RETURN_VOID(this, IsStoreTypeSupported(options), "invalid options.KvStoreType"); ZLOGD("GetKVStore kvStoreType=%{public}d", options.kvStoreType); if (options.kvStoreType == KvStoreType::DEVICE_COLLABORATION) { ref = JSUtil::NewWithRef(env, argc, argv, (void**)&kvStore, JsDeviceKVStore::Constructor(env)); @@ -121,20 +121,20 @@ napi_value JsKVManager::GetKVStore(napi_env env, napi_callback_info info) auto execute = [ctxt]() { auto kvm = reinterpret_cast(ctxt->native); - CHECK_ARGS(ctxt, kvm != nullptr, "KVManager is null, failed!"); + CHECK_ARGS_RETURN_VOID(ctxt, kvm != nullptr, "KVManager is null, failed!"); AppId appId = { kvm->bundleName_ }; StoreId storeId = { ctxt->storeId }; std::shared_ptr kvStore; Status status = kvm->kvDataManager_.GetSingleKvStore(ctxt->options, appId, storeId, kvStore); ZLOGD("GetSingleKvStore return status:%{public}d", status); ctxt->status = (status == Status::SUCCESS) ? napi_ok : napi_generic_failure; - CHECK_STATUS(ctxt, "KVManager->GetSingleKvStore() failed!"); + CHECK_STATUS_RETURN_VOID(ctxt, "KVManager->GetSingleKvStore() failed!"); ctxt->kvStore->SetNative(kvStore); }; auto output = [env, ctxt](napi_value& result) { ctxt->status = napi_get_reference_value(env, ctxt->ref, &result); napi_delete_reference(env, ctxt->ref); - CHECK_STATUS(ctxt, "output KvStore failed"); + CHECK_STATUS_RETURN_VOID(ctxt, "output KvStore failed"); }; return NapiQueue::AsyncWork(env, ctxt, std::string(__FUNCTION__), execute, output); } @@ -155,15 +155,15 @@ napi_value JsKVManager::CloseKVStore(napi_env env, napi_callback_info info) auto ctxt = std::make_shared(); auto input = [env, ctxt](size_t argc, napi_value* argv) { // required 3 arguments :: - CHECK_ARGS(ctxt, argc == 3, "invalid arguments!"); + CHECK_ARGS_RETURN_VOID(ctxt, argc == 3, "invalid arguments!"); ctxt->status = JSUtil::GetValue(env, argv[0], ctxt->appId); - CHECK_ARGS(ctxt, (ctxt->status == napi_ok) && !ctxt->appId.empty(), "invalid appId!"); + CHECK_ARGS_RETURN_VOID(ctxt, (ctxt->status == napi_ok) && !ctxt->appId.empty(), "invalid appId!"); ctxt->status = JSUtil::GetValue(env, argv[1], ctxt->storeId); - CHECK_ARGS(ctxt, (ctxt->status == napi_ok) && !ctxt->storeId.empty(), "invalid storeId!"); - CHECK_ARGS(ctxt, argv[2] != nullptr, "kvStore is nullptr!"); + CHECK_ARGS_RETURN_VOID(ctxt, (ctxt->status == napi_ok) && !ctxt->storeId.empty(), "invalid storeId!"); + CHECK_ARGS_RETURN_VOID(ctxt, argv[2] != nullptr, "kvStore is nullptr!"); bool isSingle = JsKVStore::IsInstanceOf(env, argv[2], ctxt->storeId, JsSingleKVStore::Constructor(env)); bool isDevice = JsKVStore::IsInstanceOf(env, argv[2], ctxt->storeId, JsDeviceKVStore::Constructor(env)); - CHECK_ARGS(ctxt, isSingle || isDevice, "kvStore unmatch to storeId!"); + CHECK_ARGS_RETURN_VOID(ctxt, isSingle || isDevice, "kvStore unmatch to storeId!"); }; ctxt->GetCbInfo(env, info, input); @@ -195,12 +195,12 @@ napi_value JsKVManager::DeleteKVStore(napi_env env, napi_callback_info info) auto ctxt = std::make_shared(); auto input = [env, ctxt](size_t argc, napi_value* argv) { // required 2 arguments :: - CHECK_ARGS(ctxt, argc >= 2, "invalid arguments!"); + CHECK_ARGS_RETURN_VOID(ctxt, argc >= 2, "invalid arguments!"); size_t index = 0; ctxt->status = JSUtil::GetValue(env, argv[index++], ctxt->appId); - CHECK_ARGS(ctxt, !ctxt->appId.empty(), "invalid appId"); + CHECK_ARGS_RETURN_VOID(ctxt, !ctxt->appId.empty(), "invalid appId"); ctxt->status = JSUtil::GetValue(env, argv[index++], ctxt->storeId); - CHECK_ARGS(ctxt, !ctxt->storeId.empty(), "invalid storeId"); + CHECK_ARGS_RETURN_VOID(ctxt, !ctxt->storeId.empty(), "invalid storeId"); }; ctxt->GetCbInfo(env, info, input); @@ -230,15 +230,15 @@ napi_value JsKVManager::GetAllKVStoreId(napi_env env, napi_callback_info info) auto ctxt = std::make_shared(); auto input = [env, ctxt](size_t argc, napi_value* argv) { // required 1 arguments :: - CHECK_ARGS(ctxt, argc == 1, "invalid arguments!"); + CHECK_ARGS_RETURN_VOID(ctxt, argc == 1, "invalid arguments!"); ctxt->status = JSUtil::GetValue(env, argv[0], ctxt->appId); - CHECK_ARGS(ctxt, !ctxt->appId.empty(), "invalid appId!"); + CHECK_ARGS_RETURN_VOID(ctxt, !ctxt->appId.empty(), "invalid appId!"); }; ctxt->GetCbInfo(env, info, input); auto execute = [ctxt]() { auto kvm = reinterpret_cast(ctxt->native); - CHECK_ARGS(ctxt, kvm != nullptr, "KVManager is null, failed!"); + CHECK_ARGS_RETURN_VOID(ctxt, kvm != nullptr, "KVManager is null, failed!"); AppId appId { ctxt->appId }; Status status = kvm->kvDataManager_.GetAllKvStoreId(appId, ctxt->storeIdList); ZLOGD("execute status:%{public}d", status); @@ -256,19 +256,19 @@ napi_value JsKVManager::On(napi_env env, napi_callback_info info) auto ctxt = std::make_shared(); auto input = [env, ctxt](size_t argc, napi_value* argv) { // required 2 arguments :: - CHECK_ARGS(ctxt, argc == 2, "invalid arguments!"); + CHECK_ARGS_RETURN_VOID(ctxt, argc == 2, "invalid arguments!"); std::string event; ctxt->status = JSUtil::GetValue(env, argv[0], event); ZLOGI("subscribe to event:%{public}s", event.c_str()); - CHECK_ARGS(ctxt, event == "distributedDataServiceDie", "invalid arg[0], i.e. invalid event!"); + CHECK_ARGS_RETURN_VOID(ctxt, event == "distributedDataServiceDie", "invalid arg[0], i.e. invalid event!"); napi_valuetype valueType = napi_undefined; ctxt->status = napi_typeof(env, argv[1], &valueType); - CHECK_STATUS(ctxt, "napi_typeof failed!"); - CHECK_ARGS(ctxt, valueType == napi_function, "callback is not a function"); + CHECK_STATUS_RETURN_VOID(ctxt, "napi_typeof failed!"); + CHECK_ARGS_RETURN_VOID(ctxt, valueType == napi_function, "callback is not a function"); JsKVManager* proxy = reinterpret_cast(ctxt->native); - CHECK_ARGS(ctxt, proxy != nullptr, "there is no native kv manager"); + CHECK_ARGS_RETURN_VOID(ctxt, proxy != nullptr, "there is no native kv manager"); std::lock_guard lck(proxy->deathMutex_); for (auto& it : proxy->deathRecipient_) { @@ -294,18 +294,18 @@ napi_value JsKVManager::Off(napi_env env, napi_callback_info info) auto ctxt = std::make_shared(); auto input = [env, ctxt](size_t argc, napi_value* argv) { // required 1 or 2 arguments :: [callback] - CHECK_ARGS(ctxt, (argc == 1) || (argc == 2), "invalid arguments!"); + CHECK_ARGS_RETURN_VOID(ctxt, (argc == 1) || (argc == 2), "invalid arguments!"); std::string event; ctxt->status = JSUtil::GetValue(env, argv[0], event); // required 1 arguments :: ZLOGI("unsubscribe to event:%{public}s %{public}s specified", event.c_str(), (argc == 1) ? "without": "with"); - CHECK_ARGS(ctxt, event == "distributedDataServiceDie", "invalid arg[0], i.e. invalid event!"); + CHECK_ARGS_RETURN_VOID(ctxt, event == "distributedDataServiceDie", "invalid arg[0], i.e. invalid event!"); // have 2 arguments :: have the [callback] if (argc == 2) { napi_valuetype valueType = napi_undefined; ctxt->status = napi_typeof(env, argv[1], &valueType); - CHECK_STATUS(ctxt, "napi_typeof failed!"); - CHECK_ARGS(ctxt, valueType == napi_function, "callback is not a function"); + CHECK_STATUS_RETURN_VOID(ctxt, "napi_typeof failed!"); + CHECK_ARGS_RETURN_VOID(ctxt, valueType == napi_function, "callback is not a function"); } JsKVManager* proxy = reinterpret_cast(ctxt->native); std::lock_guard lck(proxy->deathMutex_); @@ -348,10 +348,10 @@ napi_value JsKVManager::New(napi_env env, napi_callback_info info) auto ctxt = std::make_shared(); auto input = [env, ctxt, &bundleName](size_t argc, napi_value* argv) { // required 1 arguments :: - CHECK_ARGS(ctxt, argc == 1, "invalid arguments!"); + CHECK_ARGS_RETURN_VOID(ctxt, argc == 1, "invalid arguments!"); ctxt->status = JSUtil::GetNamedProperty(env, argv[0], "bundleName", bundleName); - CHECK_STATUS(ctxt, "invalid arg[0], i.e. invalid bundleName!"); - CHECK_ARGS(ctxt, !bundleName.empty(), "invalid arg[0], i.e. invalid bundleName!"); + CHECK_STATUS_RETURN_VOID(ctxt, "invalid arg[0], i.e. invalid bundleName!"); + CHECK_ARGS_RETURN_VOID(ctxt, !bundleName.empty(), "invalid arg[0], i.e. invalid bundleName!"); }; ctxt->GetCbInfoSync(env, info, input); NAPI_ASSERT(env, ctxt->status == napi_ok, "invalid arguments!"); diff --git a/frameworks/jskitsimpl/distributeddata/src/js_kv_store.cpp b/frameworks/jskitsimpl/distributeddata/src/js_kv_store.cpp index a11488768d70d6d73b90182569a37fec0c66ecd9..3cee8d1fc15fe685c4dd7aa9c004232e579b5fa1 100644 --- a/frameworks/jskitsimpl/distributeddata/src/js_kv_store.cpp +++ b/frameworks/jskitsimpl/distributeddata/src/js_kv_store.cpp @@ -111,12 +111,12 @@ napi_value JsKVStore::Put(napi_env env, napi_callback_info info) ctxt->GetCbInfo(env, info, [env, ctxt](size_t argc, napi_value* argv) { // required 2 arguments :: - CHECK_ARGS(ctxt, argc == 2, "invalid arguments!"); + CHECK_ARGS_RETURN_VOID(ctxt, argc == 2, "invalid arguments!"); ctxt->status = JSUtil::GetValue(env, argv[0], ctxt->key); - CHECK_STATUS(ctxt, "invalid arg[0], i.e. invalid key!"); + CHECK_STATUS_RETURN_VOID(ctxt, "invalid arg[0], i.e. invalid key!"); JSUtil::KvStoreVariant vv; ctxt->status = JSUtil::GetValue(env, argv[1], vv); - CHECK_STATUS(ctxt, "invalid arg[1], i.e. invalid value!"); + CHECK_STATUS_RETURN_VOID(ctxt, "invalid arg[1], i.e. invalid value!"); DistributedKv::Blob blob = JSUtil::VariantValue2Blob(vv); ctxt->value = blob.Data(); }); @@ -128,7 +128,7 @@ napi_value JsKVStore::Put(napi_env env, napi_callback_info info) Status status = kvStore->Put(key, value); ZLOGD("kvStore->Put return %{public}d", status); ctxt->status = (status == Status::SUCCESS) ? napi_ok : napi_generic_failure; - CHECK_STATUS(ctxt, "kvStore->Put() failed!"); + CHECK_STATUS_RETURN_VOID(ctxt, "kvStore->Put() failed!"); }; return NapiQueue::AsyncWork(env, ctxt, std::string(__FUNCTION__), execute); } @@ -150,9 +150,9 @@ napi_value JsKVStore::Delete(napi_env env, napi_callback_info info) ctxt->GetCbInfo(env, info, [env, ctxt](size_t argc, napi_value* argv) { // required 1 arguments :: - CHECK_ARGS(ctxt, argc == 1, "invalid arguments!"); + CHECK_ARGS_RETURN_VOID(ctxt, argc == 1, "invalid arguments!"); ctxt->status = JSUtil::GetValue(env, argv[0], ctxt->key); - CHECK_STATUS(ctxt, "invalid arg[0], i.e. invalid key!"); + CHECK_STATUS_RETURN_VOID(ctxt, "invalid arg[0], i.e. invalid key!"); }); return NapiQueue::AsyncWork(env, ctxt, std::string(__FUNCTION__), [ctxt]() { @@ -161,7 +161,7 @@ napi_value JsKVStore::Delete(napi_env env, napi_callback_info info) Status status = kvStore->Delete(key); ZLOGD("kvStore->Put return %{public}d", status); ctxt->status = (status == Status::SUCCESS) ? napi_ok : napi_generic_failure; - CHECK_STATUS(ctxt, "kvStore->Delete() failed!"); + CHECK_STATUS_RETURN_VOID(ctxt, "kvStore->Delete() failed!"); }); } @@ -177,12 +177,12 @@ napi_value JsKVStore::OnEvent(napi_env env, napi_callback_info info) auto ctxt = std::make_shared(); auto input = [env, ctxt](size_t argc, napi_value* argv) { // required 2 arguments :: [...] - CHECK_ARGS(ctxt, argc >= 2, "invalid arguments!"); + CHECK_ARGS_RETURN_VOID(ctxt, argc >= 2, "invalid arguments!"); std::string event; ctxt->status = JSUtil::GetValue(env, argv[0], event); ZLOGI("subscribe to event:%{public}s", event.c_str()); auto handle = onEventHandlers_.find(event); - CHECK_ARGS(ctxt, handle != onEventHandlers_.end(), "invalid arg[0], i.e. unsupported event"); + CHECK_ARGS_RETURN_VOID(ctxt, handle != onEventHandlers_.end(), "invalid arg[0], i.e. unsupported event"); // shift 1 argument, for JsKVStore::Exec. handle->second(env, argc - 1, &argv[1], ctxt); }; @@ -203,12 +203,12 @@ napi_value JsKVStore::OffEvent(napi_env env, napi_callback_info info) auto ctxt = std::make_shared(); auto input = [env, ctxt](size_t argc, napi_value* argv) { // required 1 arguments :: [callback] - CHECK_ARGS(ctxt, argc >= 1, "invalid arguments!"); + CHECK_ARGS_RETURN_VOID(ctxt, argc >= 1, "invalid arguments!"); std::string event; ctxt->status = JSUtil::GetValue(env, argv[0], event); ZLOGI("unsubscribe to event:%{public}s", event.c_str()); auto handle = offEventHandlers_.find(event); - CHECK_ARGS(ctxt, handle != offEventHandlers_.end(), "invalid arg[0], i.e. unsupported event"); + CHECK_ARGS_RETURN_VOID(ctxt, handle != offEventHandlers_.end(), "invalid arg[0], i.e. unsupported event"); // shift 1 argument, for JsKVStore::Exec. handle->second(env, argc - 1, &argv[1], ctxt); }; @@ -233,9 +233,9 @@ napi_value JsKVStore::PutBatch(napi_env env, napi_callback_info info) ctxt->GetCbInfo(env, info, [env, ctxt](size_t argc, napi_value* argv) { // required 1 arguments :: - CHECK_ARGS(ctxt, argc == 1, "invalid arguments!"); + CHECK_ARGS_RETURN_VOID(ctxt, argc == 1, "invalid arguments!"); ctxt->status = JSUtil::GetValue(env, argv[0], ctxt->entries); - CHECK_STATUS(ctxt, "invalid arg[0], i.e. invalid entries!"); + CHECK_STATUS_RETURN_VOID(ctxt, "invalid arg[0], i.e. invalid entries!"); }); auto execute = [ctxt]() { @@ -243,7 +243,7 @@ napi_value JsKVStore::PutBatch(napi_env env, napi_callback_info info) Status status = kvStore->PutBatch(ctxt->entries); ZLOGD("kvStore->DeleteBatch return %{public}d", status); ctxt->status = (status == Status::SUCCESS) ? napi_ok : napi_generic_failure; - CHECK_STATUS(ctxt, "kvStore->PutBatch() failed!"); + CHECK_STATUS_RETURN_VOID(ctxt, "kvStore->PutBatch() failed!"); }; return NapiQueue::AsyncWork(env, ctxt, std::string(__FUNCTION__), execute); } @@ -263,9 +263,9 @@ napi_value JsKVStore::DeleteBatch(napi_env env, napi_callback_info info) auto ctxt = std::make_shared(); auto input = [env, ctxt](size_t argc, napi_value* argv) { // required 1 arguments :: - CHECK_ARGS(ctxt, argc == 1, "invalid arguments!"); + CHECK_ARGS_RETURN_VOID(ctxt, argc == 1, "invalid arguments!"); JSUtil::GetValue(env, argv[0], ctxt->keys); - CHECK_STATUS(ctxt, "invalid arg[0], i.e. invalid keys!"); + CHECK_STATUS_RETURN_VOID(ctxt, "invalid arg[0], i.e. invalid keys!"); }; ctxt->GetCbInfo(env, info, input); @@ -279,7 +279,7 @@ napi_value JsKVStore::DeleteBatch(napi_env env, napi_callback_info info) Status status = kvStore->DeleteBatch(keys); ZLOGD("kvStore->DeleteBatch return %{public}d", status); ctxt->status = (status == Status::SUCCESS) ? napi_ok : napi_generic_failure; - CHECK_STATUS(ctxt, "kvStore->DeleteBatch failed!"); + CHECK_STATUS_RETURN_VOID(ctxt, "kvStore->DeleteBatch failed!"); }; return NapiQueue::AsyncWork(env, ctxt, std::string(__FUNCTION__), execute); } @@ -301,7 +301,7 @@ napi_value JsKVStore::StartTransaction(napi_env env, napi_callback_info info) Status status = kvStore->StartTransaction(); ZLOGD("kvStore->StartTransaction return %{public}d", status); ctxt->status = (status == Status::SUCCESS) ? napi_ok : napi_generic_failure; - CHECK_STATUS(ctxt, "kvStore->StartTransaction() failed!"); + CHECK_STATUS_RETURN_VOID(ctxt, "kvStore->StartTransaction() failed!"); }; return NapiQueue::AsyncWork(env, ctxt, std::string(__FUNCTION__), execute); } @@ -323,7 +323,7 @@ napi_value JsKVStore::Commit(napi_env env, napi_callback_info info) Status status = kvStore->Commit(); ZLOGD("kvStore->Commit return %{public}d", status); ctxt->status = (status == Status::SUCCESS) ? napi_ok : napi_generic_failure; - CHECK_STATUS(ctxt, "kvStore->Commit() failed!"); + CHECK_STATUS_RETURN_VOID(ctxt, "kvStore->Commit() failed!"); }; return NapiQueue::AsyncWork(env, ctxt, std::string(__FUNCTION__), execute); } @@ -345,7 +345,7 @@ napi_value JsKVStore::Rollback(napi_env env, napi_callback_info info) Status status = kvStore->Rollback(); ZLOGD("kvStore->Commit return %{public}d", status); ctxt->status = (status == Status::SUCCESS) ? napi_ok : napi_generic_failure; - CHECK_STATUS(ctxt, "kvStore->Rollback() failed!"); + CHECK_STATUS_RETURN_VOID(ctxt, "kvStore->Rollback() failed!"); }; return NapiQueue::AsyncWork(env, ctxt, std::string(__FUNCTION__), execute); } @@ -365,9 +365,9 @@ napi_value JsKVStore::EnableSync(napi_env env, napi_callback_info info) auto ctxt = std::make_shared(); auto input = [env, ctxt](size_t argc, napi_value* argv) { // required 1 arguments :: - CHECK_ARGS(ctxt, argc == 1, "invalid arguments!"); + CHECK_ARGS_RETURN_VOID(ctxt, argc == 1, "invalid arguments!"); ctxt->status = napi_get_value_bool(env, argv[0], &ctxt->enable); - CHECK_STATUS(ctxt, "invalid arg[0], i.e. invalid enabled!"); + CHECK_STATUS_RETURN_VOID(ctxt, "invalid arg[0], i.e. invalid enabled!"); }; ctxt->GetCbInfo(env, info, input); @@ -376,7 +376,7 @@ napi_value JsKVStore::EnableSync(napi_env env, napi_callback_info info) Status status = kvStore->SetCapabilityEnabled(ctxt->enable); ZLOGD("kvStore->SetCapabilityEnabled return %{public}d", status); ctxt->status = (status == Status::SUCCESS) ? napi_ok : napi_generic_failure; - CHECK_STATUS(ctxt, "kvStore->SetCapabilityEnabled() failed!"); + CHECK_STATUS_RETURN_VOID(ctxt, "kvStore->SetCapabilityEnabled() failed!"); }; return NapiQueue::AsyncWork(env, ctxt, std::string(__FUNCTION__), execute); } @@ -397,11 +397,11 @@ napi_value JsKVStore::SetSyncRange(napi_env env, napi_callback_info info) auto ctxt = std::make_shared(); auto input = [env, ctxt](size_t argc, napi_value* argv) { // required 2 arguments :: - CHECK_ARGS(ctxt, argc == 2, "invalid arguments!"); + CHECK_ARGS_RETURN_VOID(ctxt, argc == 2, "invalid arguments!"); ctxt->status = JSUtil::GetValue(env, argv[0], ctxt->localLabels); - CHECK_STATUS(ctxt, "invalid arg[0], i.e. invalid localLabels!"); + CHECK_STATUS_RETURN_VOID(ctxt, "invalid arg[0], i.e. invalid localLabels!"); ctxt->status = JSUtil::GetValue(env, argv[1], ctxt->remoteSupportLabels); - CHECK_STATUS(ctxt, "invalid arg[1], i.e. invalid remoteSupportLabels!"); + CHECK_STATUS_RETURN_VOID(ctxt, "invalid arg[1], i.e. invalid remoteSupportLabels!"); }; ctxt->GetCbInfo(env, info, input); @@ -410,7 +410,7 @@ napi_value JsKVStore::SetSyncRange(napi_env env, napi_callback_info info) Status status = kvStore->SetCapabilityRange(ctxt->localLabels, ctxt->remoteSupportLabels); ZLOGD("kvStore->SetCapabilityRange return %{public}d", status); ctxt->status = (status == Status::SUCCESS) ? napi_ok : napi_generic_failure; - CHECK_STATUS(ctxt, "kvStore->SetCapabilityRange() failed!"); + CHECK_STATUS_RETURN_VOID(ctxt, "kvStore->SetCapabilityRange() failed!"); }; return NapiQueue::AsyncWork(env, ctxt, std::string(__FUNCTION__), execute); } @@ -423,17 +423,17 @@ napi_value JsKVStore::SetSyncRange(napi_env env, napi_callback_info info) void JsKVStore::OnDataChange(napi_env env, size_t argc, napi_value* argv, std::shared_ptr ctxt) { // required 2 arguments :: - CHECK_ARGS(ctxt, argc == 2, "invalid arguments on dataChange!"); + CHECK_ARGS_RETURN_VOID(ctxt, argc == 2, "invalid arguments on dataChange!"); int32_t type = SUBSCRIBE_COUNT; ctxt->status = napi_get_value_int32(env, argv[0], &type); - CHECK_STATUS(ctxt, "napi_get_value_int32 failed!"); - CHECK_ARGS(ctxt, ValidSubscribeType(type), "invalid arg[1], i.e. invalid subscribeType"); + CHECK_STATUS_RETURN_VOID(ctxt, "napi_get_value_int32 failed!"); + CHECK_ARGS_RETURN_VOID(ctxt, ValidSubscribeType(type), "invalid arg[1], i.e. invalid subscribeType"); napi_valuetype valueType = napi_undefined; ctxt->status = napi_typeof(env, argv[1], &valueType); - CHECK_STATUS(ctxt, "napi_typeof failed!"); - CHECK_ARGS(ctxt, valueType == napi_function, "invalid arg[2], i.e. invalid callback"); + CHECK_STATUS_RETURN_VOID(ctxt, "napi_typeof failed!"); + CHECK_ARGS_RETURN_VOID(ctxt, valueType == napi_function, "invalid arg[2], i.e. invalid callback"); ZLOGI("subscribe data change type %{public}d", type); auto proxy = reinterpret_cast(ctxt->native); @@ -448,7 +448,7 @@ void JsKVStore::OnDataChange(napi_env env, size_t argc, napi_value* argv, std::s std::shared_ptr observer = std::make_shared(env, argv[1]); ctxt->status = proxy->Subscribe(type, observer); - CHECK_STATUS(ctxt, "Subscribe failed!"); + CHECK_STATUS_RETURN_VOID(ctxt, "Subscribe failed!"); } /* @@ -461,13 +461,13 @@ void JsKVStore::OnDataChange(napi_env env, size_t argc, napi_value* argv, std::s void JsKVStore::OffDataChange(napi_env env, size_t argc, napi_value* argv, std::shared_ptr ctxt) { // required 1 arguments :: [callback] - CHECK_ARGS(ctxt, argc <= 1, "invalid arguments off dataChange!"); + CHECK_ARGS_RETURN_VOID(ctxt, argc <= 1, "invalid arguments off dataChange!"); // have 1 arguments :: have the callback if (argc == 1) { napi_valuetype valueType = napi_undefined; ctxt->status = napi_typeof(env, argv[0], &valueType); - CHECK_STATUS(ctxt, "napi_typeof failed!"); - CHECK_ARGS(ctxt, valueType == napi_function, "invalid arg[1], i.e. invalid callback"); + CHECK_STATUS_RETURN_VOID(ctxt, "napi_typeof failed!"); + CHECK_ARGS_RETURN_VOID(ctxt, valueType == napi_function, "invalid arg[1], i.e. invalid callback"); } ZLOGI("unsubscribe dataChange, %{public}s specified observer.", (argc == 0) ? "without": "with"); @@ -498,8 +498,8 @@ void JsKVStore::OffDataChange(napi_env env, size_t argc, napi_value* argv, std:: break; // stop on fail. } } - found |= (argc == 0); // no specified observer, don't care about found or not. - CHECK_ARGS(ctxt, found, "not Subscribed!"); + found = (argc == 0) || found; // no specified observer, don't care about found or not. + CHECK_ARGS_RETURN_VOID(ctxt, found, "not Subscribed!"); } /* @@ -510,16 +510,16 @@ void JsKVStore::OffDataChange(napi_env env, size_t argc, napi_value* argv, std:: void JsKVStore::OnSyncComplete(napi_env env, size_t argc, napi_value* argv, std::shared_ptr ctxt) { // required 1 arguments :: - CHECK_ARGS(ctxt, argc == 1, "invalid arguments on syncComplete!"); + CHECK_ARGS_RETURN_VOID(ctxt, argc == 1, "invalid arguments on syncComplete!"); napi_valuetype valueType = napi_undefined; ctxt->status = napi_typeof(env, argv[0], &valueType); - CHECK_STATUS(ctxt, "napi_typeof failed!"); - CHECK_ARGS(ctxt, valueType == napi_function, "invalid arg[1], i.e. invalid callback"); + CHECK_STATUS_RETURN_VOID(ctxt, "napi_typeof failed!"); + CHECK_ARGS_RETURN_VOID(ctxt, valueType == napi_function, "invalid arg[1], i.e. invalid callback"); std::shared_ptr callback = std::make_shared(env, argv[0]); auto proxy = reinterpret_cast(ctxt->native); ctxt->status = proxy->RegisterSyncCallback(callback); - CHECK_STATUS(ctxt, "RegisterSyncCallback failed!"); + CHECK_STATUS_RETURN_VOID(ctxt, "RegisterSyncCallback failed!"); } /* @@ -530,21 +530,21 @@ void JsKVStore::OnSyncComplete(napi_env env, size_t argc, napi_value* argv, std: void JsKVStore::OffSyncComplete(napi_env env, size_t argc, napi_value* argv, std::shared_ptr ctxt) { // required 1 arguments :: [callback] - CHECK_ARGS(ctxt, argc <= 1, "invalid arguments off syncComplete!"); + CHECK_ARGS_RETURN_VOID(ctxt, argc <= 1, "invalid arguments off syncComplete!"); auto proxy = reinterpret_cast(ctxt->native); // have 1 arguments :: have the callback if (argc == 1) { napi_valuetype valueType = napi_undefined; ctxt->status = napi_typeof(env, argv[0], &valueType); - CHECK_STATUS(ctxt, "napi_typeof failed!"); - CHECK_ARGS(ctxt, valueType == napi_function, "invalid arg[1], i.e. invalid callback"); + CHECK_STATUS_RETURN_VOID(ctxt, "napi_typeof failed!"); + CHECK_ARGS_RETURN_VOID(ctxt, valueType == napi_function, "invalid arg[1], i.e. invalid callback"); auto observer = std::static_pointer_cast(proxy->syncObserver_); - CHECK_ARGS(ctxt, *observer == argv[0], "invalid arg[1], not Subscribed"); + CHECK_ARGS_RETURN_VOID(ctxt, *observer == argv[0], "invalid arg[1], not Subscribed"); } ZLOGI("unsubscribe syncComplete, %{public}s specified observer.", (argc == 0) ? "without": "with"); ctxt->status = proxy->UnRegisterSyncCallback(); - CHECK_STATUS(ctxt, "UnRegisterSyncCallback failed!"); + CHECK_STATUS_RETURN_VOID(ctxt, "UnRegisterSyncCallback failed!"); } /* diff --git a/frameworks/jskitsimpl/distributeddata/src/js_kv_store_resultset.cpp b/frameworks/jskitsimpl/distributeddata/src/js_kv_store_resultset.cpp index c3c5e76ce064394615a91028b4f95123398c512e..4605d44c74ff711455705107e650588f2a9f53a5 100644 --- a/frameworks/jskitsimpl/distributeddata/src/js_kv_store_resultset.cpp +++ b/frameworks/jskitsimpl/distributeddata/src/js_kv_store_resultset.cpp @@ -164,7 +164,7 @@ napi_value JsKVStoreResultSet::Move(napi_env env, napi_callback_info info) /* bo auto ctxt = std::make_shared(); auto input = [env, ctxt, &offset](size_t argc, napi_value* argv) { // required 1 arguments :: - CHECK_ARGS(ctxt, argc == 1, "invalid arguments!"); + CHECK_ARGS_RETURN_VOID(ctxt, argc == 1, "invalid arguments!"); ctxt->status = napi_get_value_int32(env, argv[0], (int32_t*)&offset); }; ctxt->GetCbInfoSync(env, info, input); @@ -183,7 +183,7 @@ napi_value JsKVStoreResultSet::MoveToPosition(napi_env env, napi_callback_info i auto ctxt = std::make_shared(); auto input = [env, ctxt, &position](size_t argc, napi_value* argv) { // required 1 arguments :: - CHECK_ARGS(ctxt, argc == 1, "invalid arguments!"); + CHECK_ARGS_RETURN_VOID(ctxt, argc == 1, "invalid arguments!"); ctxt->status = napi_get_value_int32(env, argv[0], (int32_t*)&position); }; ctxt->GetCbInfoSync(env, info, input); diff --git a/frameworks/jskitsimpl/distributeddata/src/js_query.cpp b/frameworks/jskitsimpl/distributeddata/src/js_query.cpp index 5791a96593d55bf180e682aa08ad86a02e5d2347..7f59047edac5293c1857f4d410ca055ec01bbb14 100644 --- a/frameworks/jskitsimpl/distributeddata/src/js_query.cpp +++ b/frameworks/jskitsimpl/distributeddata/src/js_query.cpp @@ -104,11 +104,11 @@ struct ValueContext : public ContextBase { { auto input = [this, env](size_t argc, napi_value* argv) { // required 2 arguments :: - CHECK_ARGS(this, argc == 2, "invalid arguments!"); + CHECK_ARGS_RETURN_VOID(this, argc == 2, "invalid arguments!"); status = JSUtil::GetValue(env, argv[0], field); - CHECK_STATUS(this, "invalid arg[0], i.e. invalid field!"); + CHECK_STATUS_RETURN_VOID(this, "invalid arg[0], i.e. invalid field!"); status = JSUtil::GetValue(env, argv[1], vv); - CHECK_STATUS(this, "invalid arg[1], i.e. invalid value!"); + CHECK_STATUS_RETURN_VOID(this, "invalid arg[1], i.e. invalid value!"); }; GetCbInfoSync(env, info, input); } @@ -271,9 +271,9 @@ napi_value JsQuery::IsNull(napi_env env, napi_callback_info info) auto ctxt = std::make_shared(); auto input = [env, ctxt, &field](size_t argc, napi_value* argv) { // required 1 arguments :: - CHECK_ARGS(ctxt, argc == 1, "invalid arguments!"); + CHECK_ARGS_RETURN_VOID(ctxt, argc == 1, "invalid arguments!"); ctxt->status = JSUtil::GetValue(env, argv[0], field); - CHECK_STATUS(ctxt, "invalid arg[0], i.e. invalid field!"); + CHECK_STATUS_RETURN_VOID(ctxt, "invalid arg[0], i.e. invalid field!"); }; ctxt->GetCbInfoSync(env, info, input); NAPI_ASSERT(env, ctxt->status == napi_ok, "invalid arguments!"); @@ -305,9 +305,9 @@ struct NumbersContext : public ContextBase { { auto input = [this, env](size_t argc, napi_value* argv) { // required 2 arguments :: - CHECK_ARGS(this, argc == 2, "invalid arguments!"); + CHECK_ARGS_RETURN_VOID(this, argc == 2, "invalid arguments!"); status = JSUtil::GetValue(env, argv[0], field); - CHECK_STATUS(this, "invalid arg[0], i.e. invalid field!"); + CHECK_STATUS_RETURN_VOID(this, "invalid arg[0], i.e. invalid field!"); bool isTypedArray = false; status = napi_is_typedarray(env, argv[1], &isTypedArray); @@ -319,7 +319,7 @@ struct NumbersContext : public ContextBase { size_t offset = 0; void* data = nullptr; status = napi_get_typedarray_info(env, argv[1], &type, &length, &data, &buffer, &offset); - CHECK_STATUS(this, "invalid arg[1], i.e. invalid number array!"); + CHECK_STATUS_RETURN_VOID(this, "invalid arg[1], i.e. invalid number array!"); if (type < napi_uint32_array) { status = JSUtil::GetValue(env, argv[1], intList); innerType = NumberType::NUMBER_INT; @@ -333,10 +333,10 @@ struct NumbersContext : public ContextBase { } else { bool isArray = false; status = napi_is_array(env, argv[1], &isArray); - CHECK_ARGS(this, isArray, "invalid arg[1], i.e. invalid number array!"); + CHECK_ARGS_RETURN_VOID(this, isArray, "invalid arg[1], i.e. invalid number array!"); ZLOGD("arg[1] %{public}s a Array, treat as array of double.", isTypedArray ? "is" : "is not"); status = JSUtil::GetValue(env, argv[1], doubleList); - CHECK_STATUS(this, "invalid arg[1], i.e. invalid number array!"); + CHECK_STATUS_RETURN_VOID(this, "invalid arg[1], i.e. invalid number array!"); innerType = NumberType::NUMBER_DOUBLE; }; }; @@ -370,11 +370,11 @@ napi_value JsQuery::InString(napi_env env, napi_callback_info info) auto ctxt = std::make_shared(); auto input = [env, ctxt](size_t argc, napi_value* argv) { // required 2 arguments :: - CHECK_ARGS(ctxt, argc == 2, "invalid arguments!"); + CHECK_ARGS_RETURN_VOID(ctxt, argc == 2, "invalid arguments!"); ctxt->status = JSUtil::GetValue(env, argv[0], ctxt->field); - CHECK_STATUS(ctxt, "invalid arg[0], i.e. invalid field!"); + CHECK_STATUS_RETURN_VOID(ctxt, "invalid arg[0], i.e. invalid field!"); ctxt->status = JSUtil::GetValue(env, argv[1], ctxt->valueList); - CHECK_STATUS(ctxt, "invalid arg[1], i.e. invalid valueList!"); + CHECK_STATUS_RETURN_VOID(ctxt, "invalid arg[1], i.e. invalid valueList!"); }; ctxt->GetCbInfoSync(env, info, input); NAPI_ASSERT(env, ctxt->status == napi_ok, "invalid arguments!"); @@ -411,11 +411,11 @@ napi_value JsQuery::NotInString(napi_env env, napi_callback_info info) auto ctxt = std::make_shared(); auto input = [env, ctxt](size_t argc, napi_value* argv) { // required 2 arguments :: - CHECK_ARGS(ctxt, argc == 2, "invalid arguments!"); + CHECK_ARGS_RETURN_VOID(ctxt, argc == 2, "invalid arguments!"); ctxt->status = JSUtil::GetValue(env, argv[0], ctxt->field); - CHECK_STATUS(ctxt, "invalid arg[0], i.e. invalid field!"); + CHECK_STATUS_RETURN_VOID(ctxt, "invalid arg[0], i.e. invalid field!"); ctxt->status = JSUtil::GetValue(env, argv[1], ctxt->valueList); - CHECK_STATUS(ctxt, "invalid arg[1], i.e. invalid valueList!"); + CHECK_STATUS_RETURN_VOID(ctxt, "invalid arg[1], i.e. invalid valueList!"); }; ctxt->GetCbInfoSync(env, info, input); NAPI_ASSERT(env, ctxt->status == napi_ok, "invalid arguments!"); @@ -435,11 +435,11 @@ napi_value JsQuery::Like(napi_env env, napi_callback_info info) auto ctxt = std::make_shared(); auto input = [env, ctxt](size_t argc, napi_value* argv) { // required 2 arguments :: - CHECK_ARGS(ctxt, argc == 2, "invalid arguments!"); + CHECK_ARGS_RETURN_VOID(ctxt, argc == 2, "invalid arguments!"); ctxt->status = JSUtil::GetValue(env, argv[0], ctxt->field); - CHECK_STATUS(ctxt, "invalid arg[0], i.e. invalid field!"); + CHECK_STATUS_RETURN_VOID(ctxt, "invalid arg[0], i.e. invalid field!"); ctxt->status = JSUtil::GetValue(env, argv[1], ctxt->value); - CHECK_STATUS(ctxt, "invalid arg[1], i.e. invalid value!"); + CHECK_STATUS_RETURN_VOID(ctxt, "invalid arg[1], i.e. invalid value!"); }; ctxt->GetCbInfoSync(env, info, input); NAPI_ASSERT(env, ctxt->status == napi_ok, "invalid arguments!"); @@ -459,11 +459,11 @@ napi_value JsQuery::Unlike(napi_env env, napi_callback_info info) auto ctxt = std::make_shared(); auto input = [env, ctxt](size_t argc, napi_value* argv) { // required 2 arguments :: - CHECK_ARGS(ctxt, argc == 2, "invalid arguments!"); + CHECK_ARGS_RETURN_VOID(ctxt, argc == 2, "invalid arguments!"); ctxt->status = JSUtil::GetValue(env, argv[0], ctxt->field); - CHECK_STATUS(ctxt, "invalid arg[0], i.e. invalid field!"); + CHECK_STATUS_RETURN_VOID(ctxt, "invalid arg[0], i.e. invalid field!"); ctxt->status = JSUtil::GetValue(env, argv[1], ctxt->value); - CHECK_STATUS(ctxt, "invalid arg[1], i.e. invalid value!"); + CHECK_STATUS_RETURN_VOID(ctxt, "invalid arg[1], i.e. invalid value!"); }; ctxt->GetCbInfoSync(env, info, input); NAPI_ASSERT(env, ctxt->status == napi_ok, "invalid arguments!"); @@ -504,9 +504,9 @@ napi_value JsQuery::OrderByAsc(napi_env env, napi_callback_info info) auto ctxt = std::make_shared(); auto input = [env, ctxt, &field](size_t argc, napi_value* argv) { // required 1 arguments :: - CHECK_ARGS(ctxt, argc == 1, "invalid arguments!"); + CHECK_ARGS_RETURN_VOID(ctxt, argc == 1, "invalid arguments!"); ctxt->status = JSUtil::GetValue(env, argv[0], field); - CHECK_STATUS(ctxt, "invalid arg[0], i.e. invalid field!"); + CHECK_STATUS_RETURN_VOID(ctxt, "invalid arg[0], i.e. invalid field!"); }; ctxt->GetCbInfoSync(env, info, input); NAPI_ASSERT(env, ctxt->status == napi_ok, "invalid arguments!"); @@ -523,9 +523,9 @@ napi_value JsQuery::OrderByDesc(napi_env env, napi_callback_info info) auto ctxt = std::make_shared(); auto input = [env, ctxt, &field](size_t argc, napi_value* argv) { // required 1 arguments :: - CHECK_ARGS(ctxt, argc == 1, "invalid arguments!"); + CHECK_ARGS_RETURN_VOID(ctxt, argc == 1, "invalid arguments!"); ctxt->status = JSUtil::GetValue(env, argv[0], field); - CHECK_STATUS(ctxt, "invalid arg[0], i.e. invalid field!"); + CHECK_STATUS_RETURN_VOID(ctxt, "invalid arg[0], i.e. invalid field!"); }; ctxt->GetCbInfoSync(env, info, input); NAPI_ASSERT(env, ctxt->status == napi_ok, "invalid arguments!"); @@ -544,11 +544,11 @@ napi_value JsQuery::Limit(napi_env env, napi_callback_info info) auto ctxt = std::make_shared(); auto input = [env, ctxt](size_t argc, napi_value* argv) { // required 2 arguments :: - CHECK_ARGS(ctxt, argc == 2, "invalid arguments!"); + CHECK_ARGS_RETURN_VOID(ctxt, argc == 2, "invalid arguments!"); ctxt->status = napi_get_value_int32(env, argv[0], &ctxt->number); - CHECK_STATUS(ctxt, "invalid arg[0], i.e. invalid number!"); + CHECK_STATUS_RETURN_VOID(ctxt, "invalid arg[0], i.e. invalid number!"); ctxt->status = napi_get_value_int32(env, argv[1], &ctxt->offset); - CHECK_STATUS(ctxt, "invalid arg[1], i.e. invalid offset!"); + CHECK_STATUS_RETURN_VOID(ctxt, "invalid arg[1], i.e. invalid offset!"); }; ctxt->GetCbInfoSync(env, info, input); NAPI_ASSERT(env, ctxt->status == napi_ok, "invalid arguments!"); @@ -564,9 +564,9 @@ napi_value JsQuery::IsNotNull(napi_env env, napi_callback_info info) auto ctxt = std::make_shared(); auto input = [env, ctxt, &field](size_t argc, napi_value* argv) { // required 1 arguments :: - CHECK_ARGS(ctxt, argc == 1, "invalid arguments!"); + CHECK_ARGS_RETURN_VOID(ctxt, argc == 1, "invalid arguments!"); ctxt->status = JSUtil::GetValue(env, argv[0], field); - CHECK_STATUS(ctxt, "invalid arg[0], i.e. invalid field!"); + CHECK_STATUS_RETURN_VOID(ctxt, "invalid arg[0], i.e. invalid field!"); }; ctxt->GetCbInfoSync(env, info, input); NAPI_ASSERT(env, ctxt->status == napi_ok, "invalid arguments!"); @@ -605,9 +605,9 @@ napi_value JsQuery::PrefixKey(napi_env env, napi_callback_info info) auto ctxt = std::make_shared(); auto input = [env, ctxt, &prefix](size_t argc, napi_value* argv) { // required 1 arguments :: - CHECK_ARGS(ctxt, argc == 1, "invalid arguments!"); + CHECK_ARGS_RETURN_VOID(ctxt, argc == 1, "invalid arguments!"); ctxt->status = JSUtil::GetValue(env, argv[0], prefix); - CHECK_STATUS(ctxt, "invalid arg[0], i.e. invalid prefix!"); + CHECK_STATUS_RETURN_VOID(ctxt, "invalid arg[0], i.e. invalid prefix!"); }; ctxt->GetCbInfoSync(env, info, input); NAPI_ASSERT(env, ctxt->status == napi_ok, "invalid arguments!"); @@ -623,9 +623,9 @@ napi_value JsQuery::SetSuggestIndex(napi_env env, napi_callback_info info) auto ctxt = std::make_shared(); auto input = [env, ctxt, &suggestIndex](size_t argc, napi_value* argv) { // required 1 arguments :: - CHECK_ARGS(ctxt, argc == 1, "invalid arguments!"); + CHECK_ARGS_RETURN_VOID(ctxt, argc == 1, "invalid arguments!"); ctxt->status = JSUtil::GetValue(env, argv[0], suggestIndex); - CHECK_STATUS(ctxt, "invalid arg[0], i.e. invalid suggestIndex!"); + CHECK_STATUS_RETURN_VOID(ctxt, "invalid arg[0], i.e. invalid suggestIndex!"); }; ctxt->GetCbInfoSync(env, info, input); NAPI_ASSERT(env, ctxt->status == napi_ok, "invalid arguments!"); @@ -641,9 +641,9 @@ napi_value JsQuery::DeviceId(napi_env env, napi_callback_info info) auto ctxt = std::make_shared(); auto input = [env, ctxt, &deviceId](size_t argc, napi_value* argv) { // required 1 arguments :: - CHECK_ARGS(ctxt, argc == 1, "invalid arguments!"); + CHECK_ARGS_RETURN_VOID(ctxt, argc == 1, "invalid arguments!"); ctxt->status = JSUtil::GetValue(env, argv[0], deviceId); - CHECK_STATUS(ctxt, "invalid arg[0], i.e. invalid deviceId!"); + CHECK_STATUS_RETURN_VOID(ctxt, "invalid arg[0], i.e. invalid deviceId!"); }; ctxt->GetCbInfoSync(env, info, input); NAPI_ASSERT(env, ctxt->status == napi_ok, "invalid arguments!"); diff --git a/frameworks/jskitsimpl/distributeddata/src/js_schema.cpp b/frameworks/jskitsimpl/distributeddata/src/js_schema.cpp index 1aaeef14361c616c41109e38901dc7c2e0201b1b..5a457bb065273113e29029408e853284d7e4a27d 100644 --- a/frameworks/jskitsimpl/distributeddata/src/js_schema.cpp +++ b/frameworks/jskitsimpl/distributeddata/src/js_schema.cpp @@ -85,14 +85,25 @@ napi_status JsSchema::ToJson(napi_env env, napi_value inner, JsSchema*& out) return JSUtil::Unwrap(env, inner, (void**)(&out), JsSchema::Constructor(env)); } -napi_value JsSchema::GetRootNode(napi_env env, napi_callback_info info) +JsSchema* JsSchema::GetSchema(napi_env env, napi_callback_info info, std::shared_ptr& ctxt) { - ZLOGD("Schema::GetRootNode"); - auto ctxt = std::make_shared(); ctxt->GetCbInfoSync(env, info); NAPI_ASSERT(env, ctxt->status == napi_ok, "invalid arguments!"); + return reinterpret_cast(ctxt->native); +} - auto schema = reinterpret_cast(ctxt->native); +template +napi_value JsSchema::GetContextValue(napi_env env, std::shared_ptr& ctxt, T& value) +{ + JSUtil::SetValue(env, value, ctxt->output); + return ctxt->output; +} + +napi_value JsSchema::GetRootNode(napi_env env, napi_callback_info info) +{ + ZLOGD("Schema::GetRootNode"); + auto ctxt = std::make_shared(); + auto schema = GetSchema(env, info, ctxt); if (schema->rootNode == nullptr) { int argc = 1; napi_value argv[1] = { nullptr }; @@ -112,18 +123,18 @@ napi_value JsSchema::SetRootNode(napi_env env, napi_callback_info info) auto ctxt = std::make_shared(); auto input = [env, ctxt](size_t argc, napi_value* argv) { // required 2 arguments :: - CHECK_ARGS(ctxt, argc == 1, "invalid arguments!"); + CHECK_ARGS_RETURN_VOID(ctxt, argc == 1, "invalid arguments!"); JsFieldNode* node = nullptr; ctxt->status = JSUtil::Unwrap(env, argv[0], (void**)(&node), JsFieldNode::Constructor(env)); - CHECK_STATUS(ctxt, "napi_unwrap to FieldNode failed"); - CHECK_ARGS(ctxt, node != nullptr, "invalid arg[0], i.e. invalid node!"); + CHECK_STATUS_RETURN_VOID(ctxt, "napi_unwrap to FieldNode failed"); + CHECK_ARGS_RETURN_VOID(ctxt, node != nullptr, "invalid arg[0], i.e. invalid node!"); auto schema = reinterpret_cast(ctxt->native); if (schema->ref != nullptr) { napi_delete_reference(env, schema->ref); } ctxt->status = napi_create_reference(env, argv[0], 1, &schema->ref); - CHECK_STATUS(ctxt, "napi_create_reference to FieldNode failed"); + CHECK_STATUS_RETURN_VOID(ctxt, "napi_create_reference to FieldNode failed"); schema->rootNode = node; }; ctxt->GetCbInfoSync(env, info, input); @@ -133,13 +144,10 @@ napi_value JsSchema::SetRootNode(napi_env env, napi_callback_info info) napi_value JsSchema::GetMode(napi_env env, napi_callback_info info) { + ZLOGD("Schema::GetMode"); auto ctxt = std::make_shared(); - ctxt->GetCbInfoSync(env, info); - NAPI_ASSERT(env, ctxt->status == napi_ok, "invalid arguments!"); - - auto schema = reinterpret_cast(ctxt->native); - JSUtil::SetValue(env, schema->mode, ctxt->output); - return ctxt->output; + auto schema = GetSchema(env, info, ctxt); + return GetContextValue(env, ctxt, schema->mode); } napi_value JsSchema::SetMode(napi_env env, napi_callback_info info) @@ -148,9 +156,9 @@ napi_value JsSchema::SetMode(napi_env env, napi_callback_info info) uint32_t mode = false; auto input = [env, ctxt, &mode](size_t argc, napi_value* argv) { // required 1 arguments :: - CHECK_ARGS(ctxt, argc == 1, "invalid arguments!"); + CHECK_ARGS_RETURN_VOID(ctxt, argc == 1, "invalid arguments!"); ctxt->status = JSUtil::GetValue(env, argv[0], mode); - CHECK_STATUS(ctxt, "invalid arg[0], i.e. invalid mode!"); + CHECK_STATUS_RETURN_VOID(ctxt, "invalid arg[0], i.e. invalid mode!"); }; ctxt->GetCbInfoSync(env, info, input); NAPI_ASSERT(env, ctxt->status == napi_ok, "invalid arguments!"); @@ -162,13 +170,10 @@ napi_value JsSchema::SetMode(napi_env env, napi_callback_info info) napi_value JsSchema::GetSkip(napi_env env, napi_callback_info info) { + ZLOGD("Schema::GetSkip"); auto ctxt = std::make_shared(); - ctxt->GetCbInfoSync(env, info); - NAPI_ASSERT(env, ctxt->status == napi_ok, "invalid arguments!"); - - auto schema = reinterpret_cast(ctxt->native); - JSUtil::SetValue(env, schema->skip, ctxt->output); - return ctxt->output; + auto schema = GetSchema(env, info, ctxt); + return GetContextValue(env, ctxt, schema->skip); } napi_value JsSchema::SetSkip(napi_env env, napi_callback_info info) @@ -177,9 +182,9 @@ napi_value JsSchema::SetSkip(napi_env env, napi_callback_info info) uint32_t skip = false; auto input = [env, ctxt, &skip](size_t argc, napi_value* argv) { // required 1 arguments :: - CHECK_ARGS(ctxt, argc == 1, "invalid arguments!"); + CHECK_ARGS_RETURN_VOID(ctxt, argc == 1, "invalid arguments!"); ctxt->status = JSUtil::GetValue(env, argv[0], skip); - CHECK_STATUS(ctxt, "invalid arg[0], i.e. invalid skip size!"); + CHECK_STATUS_RETURN_VOID(ctxt, "invalid arg[0], i.e. invalid skip size!"); }; ctxt->GetCbInfoSync(env, info, input); NAPI_ASSERT(env, ctxt->status == napi_ok, "invalid arguments!"); @@ -191,13 +196,10 @@ napi_value JsSchema::SetSkip(napi_env env, napi_callback_info info) napi_value JsSchema::GetIndexes(napi_env env, napi_callback_info info) { + ZLOGD("Schema::GetIndexes"); auto ctxt = std::make_shared(); - ctxt->GetCbInfoSync(env, info); - NAPI_ASSERT(env, ctxt->status == napi_ok, "invalid arguments!"); - - auto schema = reinterpret_cast(ctxt->native); - JSUtil::SetValue(env, schema->indexes, ctxt->output); - return ctxt->output; + auto schema = GetSchema(env, info, ctxt); + return GetContextValue(env, ctxt, schema->indexes); } napi_value JsSchema::SetIndexes(napi_env env, napi_callback_info info) @@ -206,9 +208,9 @@ napi_value JsSchema::SetIndexes(napi_env env, napi_callback_info info) std::vector indexes; auto input = [env, ctxt, &indexes](size_t argc, napi_value* argv) { // required 1 arguments :: - CHECK_ARGS(ctxt, argc == 1, "invalid arguments!"); + CHECK_ARGS_RETURN_VOID(ctxt, argc == 1, "invalid arguments!"); ctxt->status = JSUtil::GetValue(env, argv[0], indexes); - CHECK_STATUS(ctxt, "invalid arg[0], i.e. invalid indexes!"); + CHECK_STATUS_RETURN_VOID(ctxt, "invalid arg[0], i.e. invalid indexes!"); }; ctxt->GetCbInfoSync(env, info, input); NAPI_ASSERT(env, ctxt->status == napi_ok, "invalid arguments!"); diff --git a/frameworks/jskitsimpl/distributeddata/src/js_single_kv_store.cpp b/frameworks/jskitsimpl/distributeddata/src/js_single_kv_store.cpp index 71f2fc1f3a0ef0fd6b45e70a6c99f5223828589f..1444f488b5975671b6cf2cb6a8bed187f499c467 100644 --- a/frameworks/jskitsimpl/distributeddata/src/js_single_kv_store.cpp +++ b/frameworks/jskitsimpl/distributeddata/src/js_single_kv_store.cpp @@ -75,10 +75,10 @@ napi_value JsSingleKVStore::Get(napi_env env, napi_callback_info info) auto ctxt = std::make_shared(); auto input = [env, ctxt](size_t argc, napi_value* argv) { // required 1 arguments :: - CHECK_ARGS(ctxt, argc == 1, "invalid arguments!"); + CHECK_ARGS_RETURN_VOID(ctxt, argc == 1, "invalid arguments!"); ctxt->status = JSUtil::GetValue(env, argv[0], ctxt->key); - CHECK_STATUS(ctxt, "invalid arg[0], i.e. invalid key!"); + CHECK_STATUS_RETURN_VOID(ctxt, "invalid arg[0], i.e. invalid key!"); }; ctxt->GetCbInfo(env, info, input); ZLOGD("key=%{public}.8s", ctxt->key.c_str()); @@ -91,11 +91,11 @@ napi_value JsSingleKVStore::Get(napi_env env, napi_callback_info info) ZLOGD("kvStore->Get return %{public}d", status); ctxt->value = JSUtil::Blob2VariantValue(value); ctxt->status = (status == Status::SUCCESS) ? napi_ok : napi_generic_failure; - CHECK_STATUS(ctxt, "kvStore->Get() failed!"); + CHECK_STATUS_RETURN_VOID(ctxt, "kvStore->Get() failed!"); }; auto output = [env, ctxt](napi_value& result) { ctxt->status = JSUtil::SetValue(env, ctxt->value, result); - CHECK_STATUS(ctxt, "output failed"); + CHECK_STATUS_RETURN_VOID(ctxt, "output failed"); }; return NapiQueue::AsyncWork(env, ctxt, std::string(__FUNCTION__), execute, output); } @@ -150,9 +150,9 @@ napi_value JsSingleKVStore::GetEntries(napi_env env, napi_callback_info info) auto ctxt = std::make_shared(); auto input = [env, ctxt](size_t argc, napi_value* argv) { // required 1 arguments :: - CHECK_ARGS(ctxt, argc == 1, "invalid arguments!"); + CHECK_ARGS_RETURN_VOID(ctxt, argc == 1, "invalid arguments!"); ctxt->status = GetVariantArgs(env, argc, argv, ctxt->va); - CHECK_STATUS(ctxt, "invalid arguments!"); + CHECK_STATUS_RETURN_VOID(ctxt, "invalid arguments!"); }; ctxt->GetCbInfo(env, info, input); @@ -169,11 +169,11 @@ napi_value JsSingleKVStore::GetEntries(napi_env env, napi_callback_info info) ZLOGD("kvStore->GetEntriesWithQuery() return %{public}d", status); } ctxt->status = (status == Status::SUCCESS) ? napi_ok : napi_generic_failure; - CHECK_STATUS(ctxt, "kvStore->GetEntries() failed"); + CHECK_STATUS_RETURN_VOID(ctxt, "kvStore->GetEntries() failed"); }; auto output = [env, ctxt](napi_value& result) { ctxt->status = JSUtil::SetValue(env, ctxt->entries, result); - CHECK_STATUS(ctxt, "output failed!"); + CHECK_STATUS_RETURN_VOID(ctxt, "output failed!"); }; return NapiQueue::AsyncWork(env, ctxt, std::string(__FUNCTION__), execute, output); } @@ -197,13 +197,13 @@ napi_value JsSingleKVStore::GetResultSet(napi_env env, napi_callback_info info) auto ctxt = std::make_shared(); auto input = [env, ctxt](size_t argc, napi_value* argv) { // required 1 arguments :: - CHECK_ARGS(ctxt, argc == 1, "invalid arguments!"); + CHECK_ARGS_RETURN_VOID(ctxt, argc == 1, "invalid arguments!"); ctxt->status = GetVariantArgs(env, argc, argv, ctxt->va); - CHECK_STATUS(ctxt, "invalid arguments!"); + CHECK_STATUS_RETURN_VOID(ctxt, "invalid arguments!"); ctxt->ref = JSUtil::NewWithRef(env, 0, nullptr, (void**)(&ctxt->resultSet), JsKVStoreResultSet::Constructor(env)); - CHECK_ARGS(ctxt, ctxt->resultSet != nullptr, "KVStoreResultSet::New failed!"); - CHECK_ARGS(ctxt, ctxt->ref != nullptr, "KVStoreResultSet::New failed!"); + CHECK_ARGS_RETURN_VOID(ctxt, ctxt->resultSet != nullptr, "KVStoreResultSet::New failed!"); + CHECK_ARGS_RETURN_VOID(ctxt, ctxt->ref != nullptr, "KVStoreResultSet::New failed!"); }; ctxt->GetCbInfo(env, info, input); @@ -221,13 +221,13 @@ napi_value JsSingleKVStore::GetResultSet(napi_env env, napi_callback_info info) ZLOGD("kvStore->GetEntriesWithQuery() return %{public}d", status); } ctxt->status = (status == Status::SUCCESS) ? napi_ok : napi_generic_failure; - CHECK_STATUS(ctxt, "kvStore->GetResultSet() failed!"); + CHECK_STATUS_RETURN_VOID(ctxt, "kvStore->GetResultSet() failed!"); ctxt->resultSet->SetNative(kvResultSet); }; auto output = [env, ctxt](napi_value& result) { ctxt->status = napi_get_reference_value(env, ctxt->ref, &result); napi_delete_reference(env, ctxt->ref); - CHECK_STATUS(ctxt, "output kvResultSet failed"); + CHECK_STATUS_RETURN_VOID(ctxt, "output kvResultSet failed"); }; return NapiQueue::AsyncWork(env, ctxt, std::string(__FUNCTION__), execute, output); } @@ -246,13 +246,13 @@ napi_value JsSingleKVStore::CloseResultSet(napi_env env, napi_callback_info info auto ctxt = std::make_shared(); auto input = [env, ctxt](size_t argc, napi_value* argv) { // required 1 arguments :: - CHECK_ARGS(ctxt, argc == 1, "invalid arguments!"); + CHECK_ARGS_RETURN_VOID(ctxt, argc == 1, "invalid arguments!"); napi_valuetype type = napi_undefined; ctxt->status = napi_typeof(env, argv[0], &type); - CHECK_ARGS(ctxt, type == napi_object, "invalid arg[0], i.e. invalid resultSet!"); + CHECK_ARGS_RETURN_VOID(ctxt, type == napi_object, "invalid arg[0], i.e. invalid resultSet!"); ctxt->status = JSUtil::Unwrap(env, argv[0], (void**)(&ctxt->resultSet), JsKVStoreResultSet::Constructor(env)); - CHECK_ARGS(ctxt, ctxt->resultSet != nullptr, "invalid arg[0], i.e. invalid resultSet!"); + CHECK_ARGS_RETURN_VOID(ctxt, ctxt->resultSet != nullptr, "invalid arg[0], i.e. invalid resultSet!"); }; ctxt->GetCbInfo(env, info, input); @@ -261,7 +261,7 @@ napi_value JsSingleKVStore::CloseResultSet(napi_env env, napi_callback_info info Status status = kvStore->CloseResultSet(ctxt->resultSet->GetNative()); ZLOGD("kvStore->CloseResultSet return %{public}d", status); ctxt->status = (status == Status::SUCCESS) ? napi_ok : napi_generic_failure; - CHECK_STATUS(ctxt, "kvStore->CloseResultSet failed!"); + CHECK_STATUS_RETURN_VOID(ctxt, "kvStore->CloseResultSet failed!"); }; return NapiQueue::AsyncWork(env, ctxt, std::string(__FUNCTION__), execute); } @@ -280,12 +280,12 @@ napi_value JsSingleKVStore::GetResultSize(napi_env env, napi_callback_info info) auto ctxt = std::make_shared(); auto input = [env, ctxt](size_t argc, napi_value* argv) { // required 1 arguments :: - CHECK_ARGS(ctxt, argc == 1, "invalid arguments!"); + CHECK_ARGS_RETURN_VOID(ctxt, argc == 1, "invalid arguments!"); napi_valuetype type = napi_undefined; ctxt->status = napi_typeof(env, argv[0], &type); - CHECK_ARGS(ctxt, type == napi_object, "invalid arg[0], i.e. invalid query!"); + CHECK_ARGS_RETURN_VOID(ctxt, type == napi_object, "invalid arg[0], i.e. invalid query!"); ctxt->status = JSUtil::Unwrap(env, argv[0], (void**)(&ctxt->query), JsQuery::Constructor(env)); - CHECK_ARGS(ctxt, ctxt->query != nullptr, "invalid arg[0], i.e. invalid query!"); + CHECK_ARGS_RETURN_VOID(ctxt, ctxt->query != nullptr, "invalid arg[0], i.e. invalid query!"); }; ctxt->GetCbInfo(env, info, input); @@ -295,11 +295,11 @@ napi_value JsSingleKVStore::GetResultSize(napi_env env, napi_callback_info info) Status status = kvStore->GetCountWithQuery(query.ToString(), ctxt->resultSize); ZLOGD("kvStore->GetCountWithQuery() return %{public}d", status); ctxt->status = (status == Status::SUCCESS) ? napi_ok : napi_generic_failure; - CHECK_STATUS(ctxt, "kvStore->GetCountWithQuery() failed!"); + CHECK_STATUS_RETURN_VOID(ctxt, "kvStore->GetCountWithQuery() failed!"); }; auto output = [env, ctxt](napi_value& result) { ctxt->status = JSUtil::SetValue(env, static_cast(ctxt->resultSize), result); - CHECK_STATUS(ctxt, "output resultSize failed!"); + CHECK_STATUS_RETURN_VOID(ctxt, "output resultSize failed!"); }; return NapiQueue::AsyncWork(env, ctxt, std::string(__FUNCTION__), execute, output); } @@ -318,9 +318,9 @@ napi_value JsSingleKVStore::RemoveDeviceData(napi_env env, napi_callback_info in auto ctxt = std::make_shared(); auto input = [env, ctxt](size_t argc, napi_value* argv) { // required 1 arguments :: - CHECK_ARGS(ctxt, argc == 1, "invalid arguments!"); + CHECK_ARGS_RETURN_VOID(ctxt, argc == 1, "invalid arguments!"); ctxt->status = JSUtil::GetValue(env, argv[0], ctxt->deviceId); - CHECK_STATUS(ctxt, "invalid arg[0], i.e. invalid deviceId!"); + CHECK_STATUS_RETURN_VOID(ctxt, "invalid arg[0], i.e. invalid deviceId!"); }; ctxt->GetCbInfo(env, info, input); @@ -329,7 +329,7 @@ napi_value JsSingleKVStore::RemoveDeviceData(napi_env env, napi_callback_info in Status status = kvStore->RemoveDeviceData(ctxt->deviceId); ZLOGD("kvStore->RemoveDeviceData return %{public}d", status); ctxt->status = (status == Status::SUCCESS) ? napi_ok : napi_generic_failure; - CHECK_STATUS(ctxt, "kvStore->RemoveDeviceData failed!"); + CHECK_STATUS_RETURN_VOID(ctxt, "kvStore->RemoveDeviceData failed!"); }; return NapiQueue::AsyncWork(env, ctxt, std::string(__FUNCTION__), execute); } @@ -348,16 +348,16 @@ napi_value JsSingleKVStore::Sync(napi_env env, napi_callback_info info) auto ctxt = std::make_shared(); auto input = [env, ctxt](size_t argc, napi_value* argv) { // required 3 arguments :: [allowedDelayMs] - CHECK_ARGS(ctxt, (argc == 2) || (argc == 3), "invalid arguments!"); + CHECK_ARGS_RETURN_VOID(ctxt, (argc == 2) || (argc == 3), "invalid arguments!"); ctxt->status = JSUtil::GetValue(env, argv[0], ctxt->deviceIdList); - CHECK_STATUS(ctxt, "invalid arg[0], i.e. invalid deviceIdList!"); + CHECK_STATUS_RETURN_VOID(ctxt, "invalid arg[0], i.e. invalid deviceIdList!"); ctxt->status = JSUtil::GetValue(env, argv[1], ctxt->mode); - CHECK_STATUS(ctxt, "invalid arg[1], i.e. invalid mode!"); - CHECK_ARGS(ctxt, ctxt->mode <= uint32_t(SyncMode::PUSH_PULL), "invalid arg[1], i.e. invalid mode!"); + CHECK_STATUS_RETURN_VOID(ctxt, "invalid arg[1], i.e. invalid mode!"); + CHECK_ARGS_RETURN_VOID(ctxt, ctxt->mode <= uint32_t(SyncMode::PUSH_PULL), "invalid arg[1], i.e. invalid mode!"); // have 3 arguments :: have the allowedDelayMs if (argc == 3) { ctxt->status = JSUtil::GetValue(env, argv[2], ctxt->allowedDelayMs); - CHECK_STATUS(ctxt, "invalid arg[1], i.e. invalid allowedDelayMs!"); + CHECK_STATUS_RETURN_VOID(ctxt, "invalid arg[1], i.e. invalid allowedDelayMs!"); } }; ctxt->GetCbInfoSync(env, info, input); @@ -386,9 +386,9 @@ napi_value JsSingleKVStore::SetSyncParam(napi_env env, napi_callback_info info) auto ctxt = std::make_shared(); auto input = [env, ctxt](size_t argc, napi_value* argv) { // required 1 arguments :: - CHECK_ARGS(ctxt, argc == 1, "invalid arguments!"); + CHECK_ARGS_RETURN_VOID(ctxt, argc == 1, "invalid arguments!"); ctxt->status = JSUtil::GetValue(env, argv[0], ctxt->allowedDelayMs); - CHECK_STATUS(ctxt, "get allowedDelayMs failed!"); + CHECK_STATUS_RETURN_VOID(ctxt, "get allowedDelayMs failed!"); }; ctxt->GetCbInfo(env, info, input); @@ -398,7 +398,7 @@ napi_value JsSingleKVStore::SetSyncParam(napi_env env, napi_callback_info info) Status status = kvStore->SetSyncParam(syncParam); ZLOGD("kvStore->SetSyncParam return %{public}d", status); ctxt->status = (status == Status::SUCCESS) ? napi_ok : napi_generic_failure; - CHECK_STATUS(ctxt, "output failed!"); + CHECK_STATUS_RETURN_VOID(ctxt, "output failed!"); }; return NapiQueue::AsyncWork(env, ctxt, std::string(__FUNCTION__), execute); } @@ -422,11 +422,11 @@ napi_value JsSingleKVStore::GetSecurityLevel(napi_env env, napi_callback_info in Status status = kvStore->GetSecurityLevel(ctxt->securityLevel); ZLOGD("kvStore->GetSecurityLevel return %{public}d", status); ctxt->status = (status == Status::SUCCESS) ? napi_ok : napi_generic_failure; - CHECK_STATUS(ctxt, "GetSecurityLevel failed!"); + CHECK_STATUS_RETURN_VOID(ctxt, "GetSecurityLevel failed!"); }; auto output = [env, ctxt](napi_value& result) { ctxt->status = JSUtil::SetValue(env, static_cast(ctxt->securityLevel), result); - CHECK_STATUS(ctxt, "output failed!"); + CHECK_STATUS_RETURN_VOID(ctxt, "output failed!"); }; return NapiQueue::AsyncWork(env, ctxt, std::string(__FUNCTION__), execute, output); } @@ -438,10 +438,10 @@ napi_value JsSingleKVStore::New(napi_env env, napi_callback_info info) auto ctxt = std::make_shared(); auto input = [env, ctxt, &storeId](size_t argc, napi_value* argv) { // required 2 arguments :: - CHECK_ARGS(ctxt, argc == 2, "invalid arguments!"); + CHECK_ARGS_RETURN_VOID(ctxt, argc == 2, "invalid arguments!"); ctxt->status = JSUtil::GetValue(env, argv[0], storeId); - CHECK_STATUS(ctxt, "invalid arg[0], i.e. invalid storeId!"); - CHECK_ARGS(ctxt, !storeId.empty(), "invalid arg[0], i.e. invalid storeId!"); + CHECK_STATUS_RETURN_VOID(ctxt, "invalid arg[0], i.e. invalid storeId!"); + CHECK_ARGS_RETURN_VOID(ctxt, !storeId.empty(), "invalid arg[0], i.e. invalid storeId!"); }; ctxt->GetCbInfoSync(env, info, input); NAPI_ASSERT(env, ctxt->status == napi_ok, "invalid arguments!"); diff --git a/frameworks/jskitsimpl/distributeddata/src/napi_queue.cpp b/frameworks/jskitsimpl/distributeddata/src/napi_queue.cpp index fa51b8906d69eed27621074a2d19db55f8df567c..e09d7ac179b5a76a23be0266756cbe08ddaa4326 100644 --- a/frameworks/jskitsimpl/distributeddata/src/napi_queue.cpp +++ b/frameworks/jskitsimpl/distributeddata/src/napi_queue.cpp @@ -39,12 +39,12 @@ void ContextBase::GetCbInfo(napi_env envi, napi_callback_info info, NapiCbInfoPa size_t argc = ARGC_MAX; napi_value argv[ARGC_MAX] = { nullptr }; status = napi_get_cb_info(env, info, &argc, argv, &self, nullptr); - CHECK_STATUS(this, "napi_get_cb_info failed!"); - CHECK_ARGS(this, argc <= ARGC_MAX, "too many arguments!"); - CHECK_ARGS(this, self != nullptr, "no JavaScript this argument!"); + CHECK_STATUS_RETURN_VOID(this, "napi_get_cb_info failed!"); + CHECK_ARGS_RETURN_VOID(this, argc <= ARGC_MAX, "too many arguments!"); + CHECK_ARGS_RETURN_VOID(this, self != nullptr, "no JavaScript this argument!"); napi_create_reference(env, self, 1, &selfRef); status = napi_unwrap(env, self, &native); - CHECK_STATUS(this, "self unwrap failed!"); + CHECK_STATUS_RETURN_VOID(this, "self unwrap failed!"); if (!sync && (argc > 0)) { // get the last arguments :: @@ -53,7 +53,7 @@ void ContextBase::GetCbInfo(napi_env envi, napi_callback_info info, NapiCbInfoPa napi_status tyst = napi_typeof(env, argv[index], &type); if ((tyst == napi_ok) && (type == napi_function)) { status = napi_create_reference(env, argv[index], 1, &callbackRef); - CHECK_STATUS(this, "ref callback failed!"); + CHECK_STATUS_RETURN_VOID(this, "ref callback failed!"); argc = index; ZLOGD("async callback, no promise"); } else { @@ -64,7 +64,7 @@ void ContextBase::GetCbInfo(napi_env envi, napi_callback_info info, NapiCbInfoPa if (parse) { parse(argc, argv); } else { - CHECK_ARGS(this, argc == 0, "required no arguments!"); + CHECK_ARGS_RETURN_VOID(this, argc == 0, "required no arguments!"); } } diff --git a/interfaces/innerkits/app_distributeddata/include/app_kvstore_observer.h b/interfaces/innerkits/app_distributeddata/include/app_kvstore_observer.h index b536e50564d07ef505727b8e2a3828f0f5500175..94b91d6d4282e21ccd7ca4877fedebd9ec04222f 100644 --- a/interfaces/innerkits/app_distributeddata/include/app_kvstore_observer.h +++ b/interfaces/innerkits/app_distributeddata/include/app_kvstore_observer.h @@ -20,7 +20,7 @@ namespace OHOS { namespace AppDistributedKv { -// This is a abstract classes. Client needs to implement this class by self. +// This is an abstract classes. Client needs to implement this class by self. class AppKvStoreObserver { public: KVSTORE_API AppKvStoreObserver() = default; diff --git a/interfaces/innerkits/app_distributeddata/include/app_types.h b/interfaces/innerkits/app_distributeddata/include/app_types.h index c36bd26f00629c6939e41c60e4532d0ae89a110f..abe748384ceb0e1ccf41d355b16c870ef5b3d063 100755 --- a/interfaces/innerkits/app_distributeddata/include/app_types.h +++ b/interfaces/innerkits/app_distributeddata/include/app_types.h @@ -130,7 +130,7 @@ enum SecurityLevel : int { struct Options { bool createIfMissing = false; bool encrypt = false; - bool persistant = false; + bool persistent = false; int conflictResolvePolicy = LAST_WIN; int securityLevel = SecurityLevel::NO_LABEL; }; diff --git a/interfaces/innerkits/distributeddata/include/blob.h b/interfaces/innerkits/distributeddata/include/blob.h index da9b9c2bf308f978ac5fcac77363731760727e40..d89c29d8c5cefa44a599b60af56d151d53879676 100644 --- a/interfaces/innerkits/distributeddata/include/blob.h +++ b/interfaces/innerkits/distributeddata/include/blob.h @@ -104,7 +104,6 @@ public: private: std::vector blob_; }; - } // namespace DistributedKv } // namespace OHOS diff --git a/interfaces/innerkits/distributeddata/include/kvstore.h b/interfaces/innerkits/distributeddata/include/kvstore.h index 6d450568225ed103327ec6409c078acfcc1bc134..5f74f659caaa68ae5befe58bfe9bdc40e6a7a94b 100644 --- a/interfaces/innerkits/distributeddata/include/kvstore.h +++ b/interfaces/innerkits/distributeddata/include/kvstore.h @@ -72,7 +72,7 @@ public: // delete a list of entries in the kvstore, // delete key not exist still return success, // key length should not be greater than 256, and can not be empty. - // if keys contains invaid key, all delete will fail. + // if keys contains invalid key, all delete will fail. // keys memory size should not be greater than IPC transport limit, and can not be empty. KVSTORE_API virtual Status DeleteBatch(const std::vector &keys) = 0; diff --git a/interfaces/innerkits/distributeddata/include/types.h b/interfaces/innerkits/distributeddata/include/types.h index 4e2b0fe1f588131de98bd2659596f2455a36f8a7..28f644f7b89311aad459d86561ee0252053548da 100755 --- a/interfaces/innerkits/distributeddata/include/types.h +++ b/interfaces/innerkits/distributeddata/include/types.h @@ -25,7 +25,6 @@ namespace OHOS { namespace DistributedKv { - // key set by client, can be any non-empty bytes array, and less than 1024 size. using Key = OHOS::DistributedKv::Blob; @@ -265,7 +264,7 @@ enum class DeviceFilterStrategy { struct Options { bool createIfMissing = true; bool encrypt = false; - bool persistant = false; + bool persistent = false; bool backup = true; bool autoSync = true; int securityLevel = SecurityLevel::NO_LABEL; diff --git a/interfaces/innerkits/distributeddata/include/visibility.h b/interfaces/innerkits/distributeddata/include/visibility.h index 502eda59b754c3eac45274429ec4f0cac1d31206..1438f876c623e8458aa22133162b8b37eee2d76d 100644 --- a/interfaces/innerkits/distributeddata/include/visibility.h +++ b/interfaces/innerkits/distributeddata/include/visibility.h @@ -13,10 +13,14 @@ * limitations under the License. */ +#ifndef OHOS_DISTRIBUTED_DATA_INTERFACE_DISTRIBUTEDDATA_INCLUDE_COMMON_VISIBILITY_H +#define OHOS_DISTRIBUTED_DATA_INTERFACE_DISTRIBUTEDDATA_INCLUDE_COMMON_VISIBILITY_H + +#ifndef API_EXPORT +#define API_EXPORT __attribute__((visibility("default"))) +#endif #ifndef KVSTORE_API -#define KVSTORE_API __attribute__ ((visibility ("default"))) +#define KVSTORE_API API_EXPORT #endif -#ifndef API_EXPORT -#define API_EXPORT __attribute__((visibility ("default"))) -#endif \ No newline at end of file +#endif // OHOS_DISTRIBUTED_DATA_INTERFACE_DISTRIBUTEDDATA_INCLUDE_COMMON_VISIBILITY_H \ No newline at end of file diff --git a/services/distributeddataservice/adapter/LICENSE b/services/distributeddataservice/adapter/LICENSE deleted file mode 100644 index 4947287f7b5ccb5d1e8b7b2d3aa5d89f322c160d..0000000000000000000000000000000000000000 --- a/services/distributeddataservice/adapter/LICENSE +++ /dev/null @@ -1,177 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS \ No newline at end of file diff --git a/services/distributeddataservice/adapter/account/BUILD.gn b/services/distributeddataservice/adapter/account/BUILD.gn index ec49f1aa7b88ca9d4e4e43589aa2c76b3aa97db3..a42f278132ab2bcd562958159e0c8331fe9ea002 100755 --- a/services/distributeddataservice/adapter/account/BUILD.gn +++ b/services/distributeddataservice/adapter/account/BUILD.gn @@ -19,6 +19,7 @@ ohos_static_library("distributeddata_account_static") { ] include_dirs = [ + "../include/log", "../include/account", "../include/permission", "../include/utils", @@ -37,7 +38,6 @@ ohos_static_library("distributeddata_account_static") { deps = [ "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter:distributeddata_adapter", - "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/framework:distributeddatasvcfwk", "//utils/native/base:utils", ] @@ -50,5 +50,8 @@ ohos_static_library("distributeddata_account_static") { "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", "os_account_standard:libaccountkits", + "os_account_standard:os_account_innerkits", ] + subsystem_name = "distributeddatamgr" + part_name = "distributeddatamgr" } diff --git a/services/distributeddataservice/adapter/account/src/account_delegate_impl.cpp b/services/distributeddataservice/adapter/account/src/account_delegate_impl.cpp index 4c0dab823571ad38c4ecc0338aae6a7dc0293936..61c6ec96be0d61c6cffa306b159dd4fde50c5441 100755 --- a/services/distributeddataservice/adapter/account/src/account_delegate_impl.cpp +++ b/services/distributeddataservice/adapter/account/src/account_delegate_impl.cpp @@ -24,6 +24,7 @@ #include #include "constant.h" #include "ohos_account_kits.h" +#include "os_account_manager.h" #include "permission_validator.h" #include "utils/crypto.h" @@ -42,19 +43,17 @@ void EventSubscriber::OnReceiveEvent(const CommonEventData &event) std::string action = want.GetAction(); ZLOGI("Want Action is %s", action.c_str()); - if (action == CommonEventSupport::COMMON_EVENT_HWID_LOGIN) { - accountEventInfo.status = AccountStatus::HARMONY_ACCOUNT_LOGIN; - } else if (action == CommonEventSupport::COMMON_EVENT_HWID_LOGOUT) { - accountEventInfo.status = AccountStatus::HARMONY_ACCOUNT_LOGOUT; - } else if (action == CommonEventSupport::COMMON_EVENT_HWID_TOKEN_INVALID) { - accountEventInfo.status = AccountStatus::HARMONY_ACCOUNT_DELETE; - } else if (action == CommonEventSupport::COMMON_EVENT_USER_REMOVED) { + if (action == CommonEventSupport::COMMON_EVENT_USER_REMOVED) { accountEventInfo.status = AccountStatus::DEVICE_ACCOUNT_DELETE; accountEventInfo.deviceAccountId = std::to_string(want.GetIntParam(CommonEventSupport::COMMON_EVENT_USER_REMOVED, -1)); if (accountEventInfo.deviceAccountId == "-1") { return; } + } else if (action == CommonEventSupport::COMMON_EVENT_USER_SWITCHED) { + accountEventInfo.status = AccountStatus::DEVICE_ACCOUNT_SWITCHED; + accountEventInfo.deviceAccountId = + std::to_string(want.GetIntParam(CommonEventSupport::COMMON_EVENT_USER_SWITCHED, -1)); } else { return; } @@ -93,10 +92,8 @@ void AccountDelegateImpl::SubscribeAccountEvent() { ZLOGI("Subscribe account event listener start."); MatchingSkills matchingSkills; - matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_HWID_LOGIN); - matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_HWID_LOGOUT); - matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_HWID_TOKEN_INVALID); matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_USER_REMOVED); + matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_USER_SWITCHED); CommonEventSubscribeInfo info(matchingSkills); eventSubscriber_ = std::make_shared(info); eventSubscriber_->SetEventCallback([&](AccountEventInfo &account) { @@ -149,7 +146,13 @@ std::string AccountDelegateImpl::GetCurrentAccountId(const std::string &bundleNa std::string AccountDelegateImpl::GetDeviceAccountIdByUID(int32_t uid) const { - return std::to_string(AccountSA::OhosAccountKits::GetInstance().GetDeviceAccountIdByUID(uid)); + int userId = 0; + auto ret = AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(uid, userId); + if (ret != 0) { + ZLOGE("failed get os account local id from uid, ret:%{public}d", ret); + return {}; + } + return std::to_string(userId); } void AccountDelegateImpl::NotifyAccountChanged(const AccountEventInfo &accountEventInfo) diff --git a/services/distributeddataservice/adapter/account/test/BUILD.gn b/services/distributeddataservice/adapter/account/test/BUILD.gn index 68606e0b07c5405f9389ee33222cd1d6c90a078c..d19e880f9a1fb4e889f420396329a1335177b57a 100755 --- a/services/distributeddataservice/adapter/account/test/BUILD.gn +++ b/services/distributeddataservice/adapter/account/test/BUILD.gn @@ -38,7 +38,7 @@ ohos_unittest("DistributeddataAccountTest") { external_deps = [ "ability_base:base", - "ability_runtime:intent", + "ability_base:want", "bundle_framework:appexecfwk_base", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", diff --git a/services/distributeddataservice/adapter/auth/BUILD.gn b/services/distributeddataservice/adapter/auth/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..df2d81bec824f84116f837535a582fa2678ee7e0 --- /dev/null +++ b/services/distributeddataservice/adapter/auth/BUILD.gn @@ -0,0 +1,42 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") + +ohos_static_library("distributeddata_auth_static") { + sources = [ "src/auth_delegate.cpp" ] + + include_dirs = [ + "../include", + "../include/autils", + "../include/communicator", + "../include/log", + "//third_party/json/single_include", + "//utils/native/base/include", + "//foundation/distributeddatamgr/distributeddatamgr/frameworks/common", + "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/app_distributeddata/include", + "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/framework/include", + ] + + cflags_cc = [ "-fvisibility=hidden" ] + + deps = [ + "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/framework:distributeddatasvcfwk", + "//utils/native/base:utils", + ] + + external_deps = [ + "deviceauth_standard:deviceauth_sdk", + "hiviewdfx_hilog_native:libhilog", + ] +} diff --git a/services/distributeddataservice/adapter/auth/src/auth_delegate.cpp b/services/distributeddataservice/adapter/auth/src/auth_delegate.cpp new file mode 100644 index 0000000000000000000000000000000000000000..062c5b4c4ca41af8158593ca9915cec1d2dd5a63 --- /dev/null +++ b/services/distributeddataservice/adapter/auth/src/auth_delegate.cpp @@ -0,0 +1,158 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#define LOG_TAG "AuthHandler" +#include "auth/auth_delegate.h" + +#include "checker/checker_manager.h" +#include "communication_provider.h" +#include "device_auth.h" +#include "device_auth_defines.h" +#include "log_print.h" + +namespace OHOS::DistributedData { +bool AuthHandler::CheckAccess( + int localUserId, int peerUserId, const std::string &peerDeviceId, const std::string &appId) +{ + auto group = GetGroupInfo(localUserId, appId, peerDeviceId); + if (group.groupType < GroupType::ALL_GROUP) { + ZLOGE("failed to parse group %{public}s)", group.groupId.c_str()); + return false; + } + auto groupManager = GetGmInstance(); + if (groupManager == nullptr || groupManager->checkAccessToGroup == nullptr) { + ZLOGE("failed to get group manager"); + return false; + } + auto ret = groupManager->checkAccessToGroup(localUserId, appId.c_str(), group.groupId.c_str()); + ZLOGD("check access to group ret:%{public}d", ret); + return ret == HC_SUCCESS; +} + +int32_t AuthHandler::GetGroupType( + int localUserId, int peerUserId, const std::string &peerDeviceId, const std::string &appId) +{ + auto group = GetGroupInfo(localUserId, appId, peerDeviceId); + if (group.groupType < GroupType::ALL_GROUP) { + ZLOGE("failed to parse group json(%{public}d)", group.groupType); + } + return group.groupType; +} + +AuthHandler::RelatedGroup AuthHandler::GetGroupInfo( + int32_t localUserId, const std::string &appId, const std::string &peerDeviceId) +{ + auto groupManager = GetGmInstance(); + if (groupManager == nullptr || groupManager->getRelatedGroups == nullptr || groupManager->destroyInfo == nullptr) { + ZLOGE("failed to get group manager"); + return {}; + } + char *groupInfo = nullptr; + uint32_t groupNum = 0; + ZLOGI("get related groups, user:%{public}d, app:%{public}s", localUserId, appId.c_str()); + auto ret = groupManager->getRelatedGroups(localUserId, appId.c_str(), peerDeviceId.c_str(), &groupInfo, &groupNum); + if (groupInfo == nullptr) { + ZLOGE("failed to get related groups, ret:%{public}d", ret); + return {}; + } + ZLOGI("get related group json :%{public}s", groupInfo); + std::vector groups; + RelatedGroup::Unmarshall(groupInfo, groups); + groupManager->destroyInfo(&groupInfo); + + // same account has priority + std::sort(groups.begin(), groups.end(), + [](const RelatedGroup &group1, const RelatedGroup &group2) { return group1.groupType < group2.groupType; }); + if (!groups.empty()) { + ZLOGI("get group type:%{public}d", groups.front().groupType); + return groups.front(); + } + ZLOGD("there is no group to access to peer device:%{public}.10s", peerDeviceId.c_str()); + return {}; +} + +std::vector AuthHandler::GetTrustedDevicesByType( + AUTH_GROUP_TYPE type, int32_t localUserId, const std::string &appId) +{ + auto groupManager = GetGmInstance(); + if (groupManager == nullptr || groupManager->getRelatedGroups == nullptr + || groupManager->getTrustedDevices == nullptr || groupManager->destroyInfo == nullptr) { + ZLOGE("failed to get group manager"); + return {}; + } + + char *groupsJson = nullptr; + uint32_t groupNum = 0; + ZLOGI("get joined groups, user:%{public}d, app:%{public}s, type:%{public}d", localUserId, appId.c_str(), type); + auto ret = groupManager->getJoinedGroups(localUserId, appId.c_str(), type, &groupsJson, &groupNum); + if (groupsJson == nullptr) { + ZLOGE("failed to get joined groups, ret:%{public}d", ret); + return {}; + } + ZLOGI("get joined group json :%{public}s", groupsJson); + std::vector groups; + RelatedGroup::Unmarshall(groupsJson, groups); + groupManager->destroyInfo(&groupsJson); + + std::vector trustedDevices; + for (const auto &group : groups) { + if (group.groupType != type) { + continue; + } + char *devicesJson = nullptr; + uint32_t devNum = 0; + ret = groupManager->getTrustedDevices(localUserId, appId.c_str(), group.groupId.c_str(), &devicesJson, &devNum); + if (devicesJson == nullptr) { + ZLOGE("failed to get trusted devicesJson, ret:%{public}d", ret); + return {}; + } + ZLOGI("get trusted device json:%{public}s", devicesJson); + std::vector devices; + TrustDevice::Unmarshall(devicesJson, devices); + groupManager->destroyInfo(&devicesJson); + for (const auto &item : devices) { + auto &provider = AppDistributedKv::CommunicationProvider::GetInstance(); + auto networkId = provider.ToNodeId(item.authId); + auto uuid = provider.GetUuidByNodeId(networkId); + trustedDevices.push_back(uuid); + } + } + + return trustedDevices; +} + +bool AuthHandlerStub::CheckAccess( + int localUserId, int peerUserId, const std::string &peerDeviceId, const std::string &appId) +{ + auto checker = CheckerManager::GetInstance().GetChecker("SystemChecker"); + if (checker == nullptr) { + ZLOGE("get system checker failed"); + return false; + } + bool isSystemApp = checker->IsValid(UID_CAPACITY * localUserId, appId); + if (isSystemApp) { + ZLOGE("system app:%{public}s", appId.c_str()); + return peerUserId == SYSTEM_USER; + } + return peerUserId != SYSTEM_USER; +} + +AuthHandler *AuthDelegate::GetInstance() +{ + // change auth way in the future + static AuthHandlerStub instance; + return &instance; +} +} // namespace OHOS::DistributedData \ No newline at end of file diff --git a/services/distributeddataservice/adapter/autils/BUILD.gn b/services/distributeddataservice/adapter/autils/BUILD.gn index b51d7a4a1bd482c0efe4708570a0749984ca2438..39b59fe835928fb3ca980aa05d5cbae3ad3156fd 100755 --- a/services/distributeddataservice/adapter/autils/BUILD.gn +++ b/services/distributeddataservice/adapter/autils/BUILD.gn @@ -32,12 +32,12 @@ ohos_static_library("distributeddata_autils_static") { cflags_cc = [ "-fvisibility=hidden" ] - deps = [ - "//utils/native/base:utils", - ] + deps = [ "//utils/native/base:utils" ] external_deps = [ "bytrace_standard:bytrace_core", "hiviewdfx_hilog_native:libhilog", ] + subsystem_name = "distributeddatamgr" + part_name = "distributeddatamgr" } diff --git a/services/distributeddataservice/adapter/autils/src/thread_pool/kv_store_thread.cpp b/services/distributeddataservice/adapter/autils/src/thread_pool/kv_store_thread.cpp index db78730f587dfa28aa1442a7585bacc115456a6d..6f9874a9534af5a8e448161791eebb50f0e2c133 100755 --- a/services/distributeddataservice/adapter/autils/src/thread_pool/kv_store_thread.cpp +++ b/services/distributeddataservice/adapter/autils/src/thread_pool/kv_store_thread.cpp @@ -31,8 +31,7 @@ KvStoreThread::KvStoreThread(KvStoreThreadPool *threadPool) }); } -KvStoreThread::KvStoreThread(KvStoreThread &&thread) - : pool_(thread.pool_) +KvStoreThread::KvStoreThread(KvStoreThread &&thread) : pool_(thread.pool_) { realThread_ = std::move(thread.realThread_); } diff --git a/services/distributeddataservice/adapter/autils/src/thread_pool/kv_store_thread_pool_impl.cpp b/services/distributeddataservice/adapter/autils/src/thread_pool/kv_store_thread_pool_impl.cpp index 06a2035efaeccac0468b368ac7190ad3bacabee1..731881dc3bfe530bdc3991b8f8b3dc29894d5d38 100755 --- a/services/distributeddataservice/adapter/autils/src/thread_pool/kv_store_thread_pool_impl.cpp +++ b/services/distributeddataservice/adapter/autils/src/thread_pool/kv_store_thread_pool_impl.cpp @@ -30,7 +30,7 @@ void KvStoreThreadPoolImpl::Start() ZLOGI("start"); running = true; for (int i = 0; i < threadNum; i++) { - threadList.push_back(KvStoreThread(this)); + threadList.emplace_back(this); } } diff --git a/services/distributeddataservice/adapter/autils/test/BUILD.gn b/services/distributeddataservice/adapter/autils/test/BUILD.gn index 0012bb19be913cbde557d050cb92cf10711a895d..42d22679d44b341d2b6c206c452ab07bdaf7f779 100755 --- a/services/distributeddataservice/adapter/autils/test/BUILD.gn +++ b/services/distributeddataservice/adapter/autils/test/BUILD.gn @@ -34,7 +34,7 @@ ohos_unittest("KvStoreThreadPoolTest") { deps = [ "../../autils:distributeddata_autils_static", "//third_party/googletest:gtest_main", - ] + ] } group("unittest") { diff --git a/services/distributeddataservice/adapter/broadcaster/BUILD.gn b/services/distributeddataservice/adapter/broadcaster/BUILD.gn index 772b7444dc25a4b18d53d9d3a2e5c1cab829a6f4..cf9a693af197c47359bcdaafbd58aa85a00c0dc5 100755 --- a/services/distributeddataservice/adapter/broadcaster/BUILD.gn +++ b/services/distributeddataservice/adapter/broadcaster/BUILD.gn @@ -38,4 +38,6 @@ ohos_static_library("distributeddata_broadcaster_static") { "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", ] + subsystem_name = "distributeddatamgr" + part_name = "distributeddatamgr" } diff --git a/services/distributeddataservice/adapter/communicator/BUILD.gn b/services/distributeddataservice/adapter/communicator/BUILD.gn index 6ff2901f8d322bcbd562936f2c4232269c9dc246..1b4a50999cf1462b1ac56eb0caf19d7858250287 100755 --- a/services/distributeddataservice/adapter/communicator/BUILD.gn +++ b/services/distributeddataservice/adapter/communicator/BUILD.gn @@ -43,8 +43,8 @@ ohos_static_library("distributeddata_communicator_static") { cflags_cc = [ "-fvisibility=hidden" ] deps = [ - "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/libs/distributeddb:distributeddb", "../dfx:distributeddata_dfx_static", + "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/libs/distributeddb:distributeddb", "//utils/native/base:utils", ] diff --git a/services/distributeddataservice/adapter/communicator/src/app_pipe_mgr.cpp b/services/distributeddataservice/adapter/communicator/src/app_pipe_mgr.cpp index 26fa9ea2df37b1e0ea711b14edabc5cf1f02c02a..3f0391b68561cdbe4429977fb478e0de43678629 100755 --- a/services/distributeddataservice/adapter/communicator/src/app_pipe_mgr.cpp +++ b/services/distributeddataservice/adapter/communicator/src/app_pipe_mgr.cpp @@ -61,9 +61,9 @@ Status AppPipeMgr::StopWatchDataChange(const AppDataChangeListener *observer, co Status AppPipeMgr::SendData(const PipeInfo &pipeInfo, const DeviceId &deviceId, const uint8_t *ptr, int size, const MessageInfo &info) { - if (size > MAX_TRANSFER_SIZE || size <= 0 || ptr == nullptr || + if (size > DataBuffer::MAX_TRANSFER_SIZE || size <= 0 || ptr == nullptr || pipeInfo.pipeId.empty() || deviceId.deviceId.empty()) { - ZLOGW("Input is invalid, maxSize:%d, current size:%d", MAX_TRANSFER_SIZE, size); + ZLOGW("Input is invalid, maxSize:%d, current size:%d", DataBuffer::MAX_TRANSFER_SIZE, size); return Status::ERROR; } ZLOGD("pipeInfo:%s ,size:%d", pipeInfo.pipeId.c_str(), size); diff --git a/services/distributeddataservice/adapter/communicator/src/data_buffer.cpp b/services/distributeddataservice/adapter/communicator/src/data_buffer.cpp index 13d89ada356b7673105314125a9ab6df82e3d1fa..c52686eb6df915ea715eb2591c3b274124528af5 100755 --- a/services/distributeddataservice/adapter/communicator/src/data_buffer.cpp +++ b/services/distributeddataservice/adapter/communicator/src/data_buffer.cpp @@ -17,6 +17,8 @@ namespace OHOS { namespace AppDistributedKv { +int DataBuffer::sequence_ = 0; + DataBuffer::DataBuffer() : buf_(nullptr), size_(0), used_(0) {} diff --git a/services/distributeddataservice/adapter/communicator/src/data_buffer.h b/services/distributeddataservice/adapter/communicator/src/data_buffer.h index 1503036fa396949e61c5bf8a5f24999d39e473d7..d3bed25507a10a1ac04d30861d315028053085a1 100644 --- a/services/distributeddataservice/adapter/communicator/src/data_buffer.h +++ b/services/distributeddataservice/adapter/communicator/src/data_buffer.h @@ -28,26 +28,6 @@ struct HeaderInfo { uint32_t sequence; } __attribute__((packed)); -// header length -static const int HEADER_LEN = sizeof(HeaderInfo); - -// max size for transferring data using pipe is 5M -static const size_t MAX_DATA_LEN = 1024 * 1024 * 5; - -// 5M; max size for transfer using pipe (12 is header length, rest is data wait for transferring) -static const int MAX_TRANSFER_SIZE = 1024 * 1024 * 5 - HEADER_LEN; - -static const uint32_t VERSION = 0; - -static const uint32_t TYPE = 0; - -static int g_sequence = 0; - -union Head { - HeaderInfo headerInfo; - uint8_t headArray[HEADER_LEN]; -} __attribute__((packed)); - class DataBuffer { public: DataBuffer(); @@ -63,11 +43,31 @@ public: void SetBufUsed(size_t used); size_t GetBufUsed() const; + + // header length + static const int HEADER_LEN = sizeof(HeaderInfo); + +// max size for transferring data using pipe is 5M + static const size_t MAX_DATA_LEN = 1024 * 1024 * 5; + +// 5M; max size for transfer using pipe (12 is header length, rest is data wait for transferring) + static const int MAX_TRANSFER_SIZE = 1024 * 1024 * 5 - HEADER_LEN; + + static const uint32_t VERSION = 0; + + static const uint32_t TYPE = 0; + private: char *buf_; size_t size_; size_t used_; + static int sequence_; }; + +union Head { + HeaderInfo headerInfo; + uint8_t headArray[DataBuffer::HEADER_LEN]; +} __attribute__((packed)); } } #endif // DISTRIBUTEDDATAMGR_DATA_BUFFER_H diff --git a/services/distributeddataservice/adapter/communicator/src/process_communicator_impl.cpp b/services/distributeddataservice/adapter/communicator/src/process_communicator_impl.cpp index 797a27f766985362f7052bd9608b8fc95503765d..993e1fa43f2eb3ebf06a31655a4b958968722f13 100755 --- a/services/distributeddataservice/adapter/communicator/src/process_communicator_impl.cpp +++ b/services/distributeddataservice/adapter/communicator/src/process_communicator_impl.cpp @@ -26,6 +26,11 @@ ProcessCommunicatorImpl::ProcessCommunicatorImpl() { } +ProcessCommunicatorImpl::ProcessCommunicatorImpl(RouteHeadHandlerCreator handlerCreator) + : routeHeadHandlerCreator_(std::move(handlerCreator)) +{ +} + ProcessCommunicatorImpl::~ProcessCommunicatorImpl() { ZLOGE("destructor."); @@ -120,6 +125,7 @@ DBStatus ProcessCommunicatorImpl::SendData(const DeviceInfos &dstDevInfo, const uint32_t ProcessCommunicatorImpl::GetMtuSize() { + ZLOGI("GetMtuSize mtu=%{public}u",MTU_SIZE); return MTU_SIZE; } @@ -134,6 +140,7 @@ uint32_t ProcessCommunicatorImpl::GetMtuSize(const DeviceInfos &devInfo) return MTU_SIZE_WATCH; } } + ZLOGI("GetMtuSize mtu=%{public}u",MTU_SIZE); return MTU_SIZE; } DeviceInfos ProcessCommunicatorImpl::GetLocalDeviceInfos() @@ -187,5 +194,39 @@ void ProcessCommunicatorImpl::OnDeviceChanged(const DeviceInfo &info, const Devi devInfo.identifier = info.deviceId; onDeviceChangeHandler_(devInfo, (type == DeviceChangeType::DEVICE_ONLINE)); } -} // namespace AppDistributedKv -} // namespace OHOS + +std::shared_ptr ProcessCommunicatorImpl::GetExtendHeaderHandle(const ExtendInfo &info) +{ + if (routeHeadHandlerCreator_ != nullptr) { + return routeHeadHandlerCreator_(info); + } + return {}; +} + +DBStatus ProcessCommunicatorImpl::CheckAndGetDataHeadInfo( + const uint8_t *data, uint32_t dataLen, uint32_t &headLen, std::vector &users) +{ + ZLOGD("begin"); + if (routeHeadHandlerCreator_ == nullptr) { + ZLOGE("header handler creator not registered"); + return DBStatus::DB_ERROR; + } + auto handler = routeHeadHandlerCreator_({}); + if (handler == nullptr) { + ZLOGE("failed to get header handler"); + return DBStatus::DB_ERROR; + } + auto ret = handler->ParseHeadData(data, dataLen, headLen, users); + if (!ret) { + ZLOGD("illegal head format"); + return DBStatus::INVALID_FORMAT; + } + if (users.empty()) { + ZLOGW("no valid user"); + return DBStatus::NO_PERMISSION; + } + ZLOGD("ok, result:%{public}u, user:%{public}s", users.size(), users.front().c_str()); + return DBStatus::OK; +} +} // namespace AppDistributedKv +} // namespace OHOS diff --git a/services/distributeddataservice/adapter/communicator/src/softbus_adapter_standard.cpp b/services/distributeddataservice/adapter/communicator/src/softbus_adapter_standard.cpp index e7969ce505b004cec08f6844335542fcc4859a5c..44504483f5aaa1e5d1529484094e6fdc4a55edd8 100755 --- a/services/distributeddataservice/adapter/communicator/src/softbus_adapter_standard.cpp +++ b/services/distributeddataservice/adapter/communicator/src/softbus_adapter_standard.cpp @@ -265,7 +265,7 @@ std::vector SoftBusAdapter::GetDeviceList() const DeviceInfo deviceInfo = {uuid, std::string(info[i].deviceName), std::to_string(info[i].deviceTypeId)}; dis.push_back(deviceInfo); } - if (info != NULL) { + if (info != nullptr) { FreeNodeInfo(info); } return dis; @@ -347,9 +347,9 @@ std::vector SoftBusAdapter::GetRemoteNodesBasicInfo() const for (int i = 0; i < infoNum; i++) { dis.push_back({std::string(info[i].networkId), std::string(info[i].deviceName), - std::to_string(info[i].deviceTypeId)}); + std::to_string(info[i].deviceTypeId)}); } - if (info != NULL) { + if (info != nullptr) { FreeNodeInfo(info); } return dis; @@ -440,7 +440,7 @@ std::string SoftBusAdapter::ToNodeID(const std::string& id, const std::string &n } } } - if (info != NULL) { + if (info != nullptr) { FreeNodeInfo(info); } return networkId; @@ -515,8 +515,7 @@ Status SoftBusAdapter::SendData(const PipeInfo &pipeInfo, const DeviceId &device ZLOGE("OpenSession callback result error"); return Status::CREATE_SESSION_ERROR; } - ZLOGD("[SendBytes] start,sessionId is %{public}d, size is %{public}d, session type is %{public}d.", - sessionId, size, attr.dataType); + ZLOGD("[SendBytes] start, size is %{public}d, session type is %{public}d.", size, attr.dataType); int32_t ret = SendBytes(sessionId, (void*)ptr, size); if (ret != SOFTBUS_OK) { ZLOGE("[SendBytes] to %{public}d failed, ret:%{public}d.", sessionId, ret); @@ -602,7 +601,7 @@ int SoftBusAdapter::RemoveSessionServerAdapter(const std::string &sessionName) c void SoftBusAdapter::InsertSession(const std::string &sessionName) { - lock_guard lock(busSessionMutex_); + lock_guard lock(busSessionMutex_); busSessionMap_.insert({sessionName, true}); } @@ -728,8 +727,8 @@ void AppDataListenerWrap::OnMessageReceived(int sessionId, const void *data, uns return; } std::string peerUuid = softBusAdapter_->GetUuidByNodeId(std::string(peerDevId)); - ZLOGD("[MessageReceived] sessionId:%{public}d, peerSessionName:%{public}s, peerDevId:%{public}s", - sessionId, peerSessionName, SoftBusAdapter::ToBeAnonymous(peerUuid).c_str()); + ZLOGD("[MessageReceived] peerSessionName:%{public}s, peerDevId:%{public}s", peerSessionName, + SoftBusAdapter::ToBeAnonymous(peerUuid).c_str()); NotifyDataListeners(reinterpret_cast(data), dataLen, peerUuid, {std::string(peerSessionName), ""}); } @@ -752,8 +751,8 @@ void AppDataListenerWrap::OnBytesReceived(int sessionId, const void *data, unsig return; } std::string peerUuid = softBusAdapter_->GetUuidByNodeId(std::string(peerDevId)); - ZLOGD("[BytesReceived] sessionId:%{public}d, peerSessionName:%{public}s, peerDevId:%{public}s", - sessionId, peerSessionName, SoftBusAdapter::ToBeAnonymous(peerUuid).c_str()); + ZLOGD("[BytesReceived] peerSessionName:%{public}s, peerDevId:%{public}s", peerSessionName, + SoftBusAdapter::ToBeAnonymous(peerUuid).c_str()); NotifyDataListeners(reinterpret_cast(data), dataLen, peerUuid, {std::string(peerSessionName), ""}); } diff --git a/services/distributeddataservice/adapter/communicator/test/BUILD.gn b/services/distributeddataservice/adapter/communicator/test/BUILD.gn index 919d221671da3b0e647245a084673204ea9a32e8..448e992298d75fd0f47fc4943ce4fe3c30c62aa1 100755 --- a/services/distributeddataservice/adapter/communicator/test/BUILD.gn +++ b/services/distributeddataservice/adapter/communicator/test/BUILD.gn @@ -29,9 +29,9 @@ ohos_unittest("CommunicationProviderTest") { "../src", ] external_deps = [ + "dsoftbus_standard:softbus_client", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", - "dsoftbus_standard:softbus_client", ] deps = [ "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/communicator:distributeddata_communicator_static", @@ -61,8 +61,6 @@ group("unittest") { deps = [] - deps += [ - ":CommunicationProviderTest", - ] + deps += [ ":CommunicationProviderTest" ] } ############################################################################### diff --git a/services/distributeddataservice/adapter/dfx/BUILD.gn b/services/distributeddataservice/adapter/dfx/BUILD.gn index 16dc7d4440d4fa8fdf18fd5fc7140fc3c42f5d04..bcf1f84452f6873dd8cc3cdc8a5c2c12b6e878e7 100755 --- a/services/distributeddataservice/adapter/dfx/BUILD.gn +++ b/services/distributeddataservice/adapter/dfx/BUILD.gn @@ -50,4 +50,6 @@ ohos_static_library("distributeddata_dfx_static") { "hisysevent_native:libhisysevent", "hiviewdfx_hilog_native:libhilog", ] + subsystem_name = "distributeddatamgr" + part_name = "distributeddatamgr" } diff --git a/services/distributeddataservice/adapter/dfx/src/hiview_adapter.cpp b/services/distributeddataservice/adapter/dfx/src/hiview_adapter.cpp index 8889d728a9e354a8b5a4d3bc7d1865a06e51ee82..39e22568eba319c518459394313c19b319a628df 100755 --- a/services/distributeddataservice/adapter/dfx/src/hiview_adapter.cpp +++ b/services/distributeddataservice/adapter/dfx/src/hiview_adapter.cpp @@ -242,11 +242,12 @@ void HiViewAdapter::StartTimerThread() auto fun = [=]() { while (true) { time_t current = time(nullptr); - tm *localTime = localtime(¤t); - if (localTime == nullptr) { + tm localTime = { 0 }; + tm *result = localtime_r(¤t, &localTime); + if (result == nullptr) { continue; } - int currentHour = localTime->tm_hour; + int currentHour = localTime.tm_hour; if (currentHour < EXEC_TIME) { sleep((EXEC_TIME - currentHour) * SIXTY_SEC * SIXTY_SEC); InvokeDbSize(); diff --git a/services/distributeddataservice/adapter/dfx/test/BUILD.gn b/services/distributeddataservice/adapter/dfx/test/BUILD.gn index 0f939e1ee0735ca72e07052d366357da808dd5a4..feb3251a59fafe099e36ee8b30c3adbf2f584325 100755 --- a/services/distributeddataservice/adapter/dfx/test/BUILD.gn +++ b/services/distributeddataservice/adapter/dfx/test/BUILD.gn @@ -46,9 +46,9 @@ ohos_unittest("DistributeddataDfxMSTTest") { ldflags = [ "-Wl,--exclude-libs,ALL" ] deps = [ "../../autils:distributeddata_autils_static", - "//third_party/openssl:libcrypto_static", "../../dfx:distributeddata_dfx_static", "//third_party/googletest:gtest_main", + "//third_party/openssl:libcrypto_static", "//utils/native/base:utils", ] } @@ -102,8 +102,8 @@ ohos_unittest("DistributeddataDfxUTTest") { ldflags = [ "-Wl,--exclude-libs,ALL" ] deps = [ "../../autils:distributeddata_autils_static", - "//third_party/openssl:libcrypto_static", "//third_party/googletest:gtest_main", + "//third_party/openssl:libcrypto_static", "//utils/native/base:utils", ] } diff --git a/services/distributeddataservice/adapter/include/account/account_delegate.h b/services/distributeddataservice/adapter/include/account/account_delegate.h index 617e56f56dd4eb7263eb12daa47fbb36a40f0a88..e3e17b339f965bd637304e22b502856674bf4d10 100755 --- a/services/distributeddataservice/adapter/include/account/account_delegate.h +++ b/services/distributeddataservice/adapter/include/account/account_delegate.h @@ -28,6 +28,7 @@ enum class AccountStatus { HARMONY_ACCOUNT_LOGOUT, // the openHarmony account is logged out HARMONY_ACCOUNT_DELETE, // the openHarmony account is deleted DEVICE_ACCOUNT_DELETE, // the device account is deleted + DEVICE_ACCOUNT_SWITCHED, // the device account is switched }; struct AccountEventInfo { @@ -53,6 +54,7 @@ public: KVSTORE_API virtual std::string GetDeviceAccountIdByUID(int32_t uid) const = 0; KVSTORE_API virtual void SubscribeAccountEvent() = 0; KVSTORE_API static AccountDelegate *GetInstance(); + private: using BaseInstance = AccountDelegate *(*)(); static BaseInstance getInstance_; diff --git a/services/distributeddataservice/adapter/include/account/visibility.h b/services/distributeddataservice/adapter/include/account/visibility.h index 2ffb65244c7345fa10aa830da1476e09e4d9fef8..50f688ff91d39432d1fcd305f91320b9c22cf183 100644 --- a/services/distributeddataservice/adapter/include/account/visibility.h +++ b/services/distributeddataservice/adapter/include/account/visibility.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -12,16 +12,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - -#ifndef KVSTORE_API -#ifdef _WIN32 - #ifdef DB_DLL_EXPORT - #define KVSTORE_API __declspec(dllexport) - #else - #define KVSTORE_API - #endif -#else - #define KVSTORE_API __attribute__ ((visibility ("default"))) +#ifndef DISTRIBUTEDDATAMGR_ACCOUNT_VISIBILITY_H +#define DISTRIBUTEDDATAMGR_ACCOUNT_VISIBILITY_H +#ifndef API_EXPORT +#define API_EXPORT __attribute__((visibility("default"))) #endif +#ifndef KVSTORE_API +#define KVSTORE_API API_EXPORT #endif - +#endif // DISTRIBUTEDDATAMGR_ACCOUNT_VISIBILITY_H diff --git a/services/distributeddataservice/adapter/include/auth/auth_delegate.h b/services/distributeddataservice/adapter/include/auth/auth_delegate.h new file mode 100644 index 0000000000000000000000000000000000000000..b4af68d9e55ff1e5b7df362fcff305117ae47aea --- /dev/null +++ b/services/distributeddataservice/adapter/include/auth/auth_delegate.h @@ -0,0 +1,103 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef DISTRIBUTEDDATAMGR_AUTH_DELEGATE_H +#define DISTRIBUTEDDATAMGR_AUTH_DELEGATE_H + +#include + +#include "serializable/serializable.h" +namespace OHOS::DistributedData { +enum AUTH_GROUP_TYPE { + ALL_GROUP = 0, + IDENTICAL_ACCOUNT_GROUP = 1, + PEER_TO_PEER_GROUP = 256, + COMPATIBLE_GROUP = 512, + ACROSS_ACCOUNT_AUTHORIZE_GROUP = 1282 +}; + +class AuthHandler { +public: + virtual bool CheckAccess( + int localUserId, int peerUserId, const std::string &peerDeviceId, const std::string &appId); + virtual int32_t GetGroupType( + int localUserId, int peerUserId, const std::string &peerDeviceId, const std::string &appId); + virtual std::vector GetTrustedDevicesByType( + AUTH_GROUP_TYPE type, int32_t localUserId, const std::string &appId); + +private: + struct RelatedGroup final : public Serializable { + int32_t groupType = -1; + std::string groupId; + RelatedGroup() + { + } + ~RelatedGroup() + { + } + RelatedGroup(const RelatedGroup &) = default; + RelatedGroup &operator=(const RelatedGroup &) = default; + bool Marshal(json &node) const override + { + SetValue(node[GET_NAME(groupType)], groupType); + SetValue(node[GET_NAME(groupId)], groupId); + return true; + } + + bool Unmarshal(const json &node) override + { + GetValue(node, GET_NAME(groupType), groupType); + GetValue(node, GET_NAME(groupId), groupId); + return true; + } + }; + + struct TrustDevice final : public Serializable { + std::string authId; // udid + TrustDevice() = default; + TrustDevice(const TrustDevice &) = default; + TrustDevice &operator=(const TrustDevice &) = default; + bool Marshal(json &node) const override + { + SetValue(node[GET_NAME(authId)], authId); + return true; + } + + bool Unmarshal(const json &node) override + { + GetValue(node, GET_NAME(authId), authId); + return true; + } + }; + static RelatedGroup GetGroupInfo(int32_t localUserId, const std::string &appId, const std::string &peerDeviceId); +}; + +class AuthHandlerStub : public AuthHandler { +public: + // override for mock auth in current version, need remove in the future + bool CheckAccess( + int localUserId, int peerUserId, const std::string &peerDeviceId, const std::string &appId) override; + +private: + static constexpr pid_t UID_CAPACITY = 10000; + static constexpr int SYSTEM_USER = 0; +}; + +class AuthDelegate { +public: + API_EXPORT static AuthHandler *GetInstance(); +}; +} // namespace OHOS::DistributedData +#endif // DISTRIBUTEDDATAMGR_AUTH_DELEGATE_H diff --git a/services/distributeddataservice/adapter/include/autils/visibility.h b/services/distributeddataservice/adapter/include/autils/visibility.h index 10bc02f92195c1ee906e43cd314c51eb4717a08a..92575c65d55c0d45304ab15d8c55afd8ef30bf84 100644 --- a/services/distributeddataservice/adapter/include/autils/visibility.h +++ b/services/distributeddataservice/adapter/include/autils/visibility.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -12,8 +12,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - +#ifndef DISTRIBUTEDDATAMGR_AUTILS_VISIBILITY_H +#define DISTRIBUTEDDATAMGR_AUTILS_VISIBILITY_H +#ifndef API_EXPORT +#define API_EXPORT __attribute__((visibility("default"))) +#endif #ifndef KVSTORE_API -#define KVSTORE_API __attribute__ ((visibility ("default"))) +#define KVSTORE_API API_EXPORT #endif - +#endif // DISTRIBUTEDDATAMGR_AUTILS_VISIBILITY_H \ No newline at end of file diff --git a/services/distributeddataservice/adapter/include/broadcaster/visibility.h b/services/distributeddataservice/adapter/include/broadcaster/visibility.h index 10bc02f92195c1ee906e43cd314c51eb4717a08a..babdec0b11723616d2689c8b8ed0d363c6bfdf84 100644 --- a/services/distributeddataservice/adapter/include/broadcaster/visibility.h +++ b/services/distributeddataservice/adapter/include/broadcaster/visibility.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -12,8 +12,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - +#ifndef DISTRIBUTEDDATAMGR_BROADCAST_VISIBILITY_H +#define DISTRIBUTEDDATAMGR_BROADCAST_VISIBILITY_H +#ifndef API_EXPORT +#define API_EXPORT __attribute__((visibility("default"))) +#endif #ifndef KVSTORE_API -#define KVSTORE_API __attribute__ ((visibility ("default"))) +#define KVSTORE_API API_EXPORT #endif - +#endif // DISTRIBUTEDDATAMGR_BROADCAST_VISIBILITY_H diff --git a/services/distributeddataservice/adapter/include/communicator/process_communicator_impl.h b/services/distributeddataservice/adapter/include/communicator/process_communicator_impl.h index a4bee389d0228a0ec2ef47d1bf5fa44c27caf868..c56b1c1af9d292fb00425365f00a2fac90a67b24 100755 --- a/services/distributeddataservice/adapter/include/communicator/process_communicator_impl.h +++ b/services/distributeddataservice/adapter/include/communicator/process_communicator_impl.h @@ -17,8 +17,10 @@ #define PROCESS_COMMUNICATOR_IMPL_H #include -#include "iprocess_communicator.h" + #include "communication_provider.h" +#include "iprocess_communicator.h" +#include "route_head_handler.h" namespace OHOS { namespace AppDistributedKv { @@ -30,7 +32,11 @@ public: using OnDeviceChange = DistributedDB::OnDeviceChange; using OnDataReceive = DistributedDB::OnDataReceive; using DeviceInfos = DistributedDB::DeviceInfos; + using RouteHeadHandlerCreator = + std::function(const DistributedDB::ExtendInfo &info)>; + KVSTORE_API ProcessCommunicatorImpl(); + KVSTORE_API explicit ProcessCommunicatorImpl(RouteHeadHandlerCreator handlerCreator); KVSTORE_API ~ProcessCommunicatorImpl() override; KVSTORE_API DBStatus Start(const std::string &processLabel) override; @@ -45,6 +51,12 @@ public: KVSTORE_API DeviceInfos GetLocalDeviceInfos() override; KVSTORE_API std::vector GetRemoteOnlineDeviceInfosList() override; KVSTORE_API bool IsSameProcessLabelStartedOnPeerDevice(const DeviceInfos &peerDevInfo) override; + + API_EXPORT std::shared_ptr GetExtendHeaderHandle( + const DistributedDB::ExtendInfo &info) override; + API_EXPORT DBStatus CheckAndGetDataHeadInfo( + const uint8_t *data, uint32_t dataLen, uint32_t &headLen, std::vector &users) override; + private: void OnMessage(const DeviceInfo &info, const uint8_t *ptr, const int size, const PipeInfo &pipeInfo) const override; @@ -53,6 +65,8 @@ private: std::string thisProcessLabel_; OnDeviceChange onDeviceChangeHandler_; OnDataReceive onDataReceiveHandler_; + RouteHeadHandlerCreator routeHeadHandlerCreator_; // route header handler creator + mutable std::mutex onDeviceChangeMutex_; mutable std::mutex onDataReceiveMutex_; diff --git a/services/distributeddataservice/adapter/include/communicator/route_head_handler.h b/services/distributeddataservice/adapter/include/communicator/route_head_handler.h new file mode 100644 index 0000000000000000000000000000000000000000..f31eea2db267e3d48b87bed4d392c7cc38bb9408 --- /dev/null +++ b/services/distributeddataservice/adapter/include/communicator/route_head_handler.h @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef DISTRIBUTEDDATAMGR_EXTEND_HEAD_HANDLER_H +#define DISTRIBUTEDDATAMGR_EXTEND_HEAD_HANDLER_H +#include + +#include "iprocess_communicator.h" + +namespace OHOS::DistributedData { +class RouteHeadHandler : public DistributedDB::ExtendHeaderHandle { +public: + using ExtendInfo = DistributedDB::ExtendInfo; + using DBStatus = DistributedDB::DBStatus; + + virtual bool ParseHeadData( + const uint8_t *data, uint32_t totalLen, uint32_t &headSize, std::vector &users) = 0; +}; +} // namespace OHOS::DistributedData +#endif // DISTRIBUTEDDATAMGR_EXTEND_HEAD_HANDLER_H diff --git a/services/distributeddataservice/adapter/include/dfx/visibility.h b/services/distributeddataservice/adapter/include/dfx/visibility.h index 10bc02f92195c1ee906e43cd314c51eb4717a08a..b58fa139ad40ec8781ded4af32fb2bb7a691fb78 100644 --- a/services/distributeddataservice/adapter/include/dfx/visibility.h +++ b/services/distributeddataservice/adapter/include/dfx/visibility.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -12,8 +12,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - +#ifndef DISTRIBUTEDDATAMGR_DFX_VISIBILITY_H +#define DISTRIBUTEDDATAMGR_DFX_VISIBILITY_H +#ifndef API_EXPORT +#define API_EXPORT __attribute__((visibility("default"))) +#endif #ifndef KVSTORE_API -#define KVSTORE_API __attribute__ ((visibility ("default"))) +#define KVSTORE_API API_EXPORT #endif - +#endif // DISTRIBUTEDDATAMGR_DFX_VISIBILITY_H \ No newline at end of file diff --git a/services/distributeddataservice/adapter/include/log/visibility.h b/services/distributeddataservice/adapter/include/log/visibility.h index 10bc02f92195c1ee906e43cd314c51eb4717a08a..49ddb4b2bbb4db865cf1d8bab12746dc50ee7e46 100644 --- a/services/distributeddataservice/adapter/include/log/visibility.h +++ b/services/distributeddataservice/adapter/include/log/visibility.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -12,8 +12,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - +#ifndef DISTRIBUTEDDATAMGR_LOG_VISIBILITY_H +#define DISTRIBUTEDDATAMGR_LOG_VISIBILITY_H +#ifndef API_EXPORT +#define API_EXPORT __attribute__((visibility("default"))) +#endif #ifndef KVSTORE_API -#define KVSTORE_API __attribute__ ((visibility ("default"))) +#define KVSTORE_API API_EXPORT #endif - +#endif // DISTRIBUTEDDATAMGR_LOG_VISIBILITY_H diff --git a/services/distributeddataservice/adapter/permission/BUILD.gn b/services/distributeddataservice/adapter/permission/BUILD.gn index 3c08ce4e88d5730445a6cfb7edaf674d924a45f1..93b38d8c855cfaf1d05f35ed648b24a1daaee2b7 100755 --- a/services/distributeddataservice/adapter/permission/BUILD.gn +++ b/services/distributeddataservice/adapter/permission/BUILD.gn @@ -44,11 +44,13 @@ ohos_static_library("distributeddata_permission_static") { external_deps = [ "ability_base:base", - "ability_runtime:intent", + "ability_base:want", "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", "samgr_standard:samgr_proxy", ] + subsystem_name = "distributeddatamgr" + part_name = "distributeddatamgr" } diff --git a/services/distributeddataservice/adapter/permission/src/client_permission_validator.cpp b/services/distributeddataservice/adapter/permission/src/client_permission_validator.cpp index b004c93763da4fd39a23dd70aa300a1158589af2..6781b1b16458261fc9bb40bdf69c404cf3b735d1 100755 --- a/services/distributeddataservice/adapter/permission/src/client_permission_validator.cpp +++ b/services/distributeddataservice/adapter/permission/src/client_permission_validator.cpp @@ -21,7 +21,6 @@ namespace OHOS { namespace DistributedKv { - ClientPermissionChangedCallback::ClientPermissionChangedCallback(std::int32_t pid, std::int32_t uid) { this->pid_ = pid; diff --git a/services/distributeddataservice/adapter/test/BUILD.gn b/services/distributeddataservice/adapter/test/BUILD.gn index 631b8bab2c52f1ae5908509775b432acc451ed4a..b716360d7b795f9b46b48331f44193708d313a68 100755 --- a/services/distributeddataservice/adapter/test/BUILD.gn +++ b/services/distributeddataservice/adapter/test/BUILD.gn @@ -21,7 +21,7 @@ group("unittest") { "../account/test:unittest", "../autils/test:unittest", "../communicator/test:unittest", - "../permission/test:unittest", "../dfx/test:unittest", + "../permission/test:unittest", ] } diff --git a/services/distributeddataservice/adapter/utils/BUILD.gn b/services/distributeddataservice/adapter/utils/BUILD.gn index ef6f6d676e6aded40f07e000cf8cdfb73006d8c1..b463607dab1597fe629a0496c0b43d435499dcdf 100755 --- a/services/distributeddataservice/adapter/utils/BUILD.gn +++ b/services/distributeddataservice/adapter/utils/BUILD.gn @@ -38,7 +38,7 @@ ohos_static_library("distributeddata_utils_static") { external_deps = [ "ability_base:base", - "ability_runtime:intent", + "ability_base:want", "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", "bytrace_standard:bytrace_core", @@ -46,4 +46,6 @@ ohos_static_library("distributeddata_utils_static") { "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", ] + subsystem_name = "distributeddatamgr" + part_name = "distributeddatamgr" } diff --git a/services/distributeddataservice/app/BUILD.gn b/services/distributeddataservice/app/BUILD.gn old mode 100755 new mode 100644 index b344d3f3da78f7b269ec070e5675eec942bf7a3c..39c36f7fa55db7bf3ecf9b6279d4b497b3be2f46 --- a/services/distributeddataservice/app/BUILD.gn +++ b/services/distributeddataservice/app/BUILD.gn @@ -12,6 +12,8 @@ # limitations under the License. import("//build/ohos.gni") import("//build/ohos_var.gni") +import( + "//foundation/distributeddatamgr/distributeddatamgr/distributeddatamgr.gni") group("build_module") { deps = [ ":distributeddataservice" ] @@ -42,10 +44,12 @@ config("module_private_config") { "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/service/bootstrap/include", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/service/config/include", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/service/directory/include", + "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/app/src/session_manager", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/framework/include", "//foundation/distributeddatamgr/distributeddatamgr/frameworks/innerkitsimpl/rdb/include", "//foundation/distributeddatamgr/distributeddatamgr/frameworks/innerkitsimpl/rdb/src", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/service/rdb", + "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/service/kv", "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/app_distributeddata/include", "//foundation/distributeddatamgr/distributedfile/interfaces/kits/js/src/mod_securitylabel", "//utils/system/safwk/native/include", @@ -78,10 +82,12 @@ ohos_shared_library("distributeddataservice") { "src/device_kvstore_impl.cpp", "src/device_kvstore_observer_impl.cpp", "src/device_kvstore_resultset_impl.cpp", + "src/executor_factory.cpp", "src/kvstore_account_observer.cpp", "src/kvstore_app_accessor.cpp", "src/kvstore_app_manager.cpp", "src/kvstore_data_service.cpp", + "src/kvstore_device_listener.cpp", "src/kvstore_impl.cpp", "src/kvstore_meta_manager.cpp", "src/kvstore_observer_impl.cpp", @@ -92,6 +98,9 @@ ohos_shared_library("distributeddataservice") { "src/query_helper.cpp", "src/security/security.cpp", "src/security/sensitive.cpp", + "src/session_manager/route_head_handler_impl.cpp", + "src/session_manager/session_manager.cpp", + "src/session_manager/upgrade_manager.cpp", "src/single_kvstore_impl.cpp", ] @@ -102,6 +111,9 @@ ohos_shared_library("distributeddataservice") { "../service/rdb/rdb_syncer.cpp", ] + kv_sources = [ "../service/kv/user_delegate.cpp" ] + + sources += kv_sources sources += rdb_sources configs = [ ":module_private_config" ] @@ -110,6 +122,7 @@ ohos_shared_library("distributeddataservice") { "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata:distributeddata_inner", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter:distributeddata_adapter", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/account:distributeddata_account_static", + "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/auth:distributeddata_auth_static", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/broadcaster:distributeddata_broadcaster_static", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/permission:distributeddata_permission_static", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/utils:distributeddata_utils_static", @@ -123,20 +136,27 @@ ohos_shared_library("distributeddataservice") { external_deps = [ "ability_base:base", - "ability_runtime:intent", - "battery_manager_native:batterysrv_client", + "ability_base:want", "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", "dataclassification:data_transit_mgr", "hiviewdfx_hilog_native:libhilog", "huks:libhukssdk", "ipc:ipc_core", + "os_account_standard:os_account_innerkits", "permission_standard:libpermissionsdk_standard", - "power_manager_native:powermgr_client", "safwk:system_ability_fwk", "samgr_standard:samgr_proxy", "startup_l2:syspara", ] + if (distributeddatamgr_power) { + external_deps += [ + "battery_manager_native:batterysrv_client", + "power_manager_native:powermgr_client", + ] + defines = [ "SUPPORT_POWER" ] + } + subsystem_name = "distributeddatamgr" } diff --git a/services/distributeddataservice/app/src/backup_handler.cpp b/services/distributeddataservice/app/src/backup_handler.cpp index 80202b83e684f922f096c204f5a1ed9773d997b7..ac0eae47cf4690f10e7e8179bdb21067a16bb936 100755 --- a/services/distributeddataservice/app/src/backup_handler.cpp +++ b/services/distributeddataservice/app/src/backup_handler.cpp @@ -21,15 +21,17 @@ #include #include #include "account_delegate.h" +#ifdef SUPPORT_POWER #include "battery_info.h" #include "battery_srv_client.h" +#include "power_mgr_client.h" +#endif #include "constant.h" #include "kv_store_delegate_manager.h" #include "kv_scheduler.h" #include "kvstore_data_service.h" #include "log_print.h" #include "kvstore_meta_manager.h" -#include "power_mgr_client.h" #include "time_utils.h" #include "utils/crypto.h" @@ -246,10 +248,9 @@ bool BackupHandler::SingleKvStoreRecover(MetaData &metaData, DistributedDB::KvSt std::string backupName = Constant::Concatenate( {metaData.kvStoreMetaData.userId, "_", metaData.kvStoreMetaData.appId, "_", metaData.kvStoreMetaData.storeId}); - auto backupFullName = Constant::Concatenate({ - BackupHandler::GetBackupPath(metaData.kvStoreMetaData.deviceAccountId, pathType), "/", - GetHashedBackupName(backupName) - }); + auto backupFullName = Constant::Concatenate( + {BackupHandler::GetBackupPath(metaData.kvStoreMetaData.deviceAccountId, pathType), "/", + GetHashedBackupName(backupName)}); DistributedDB::DBStatus dbStatus = delegate->Import(backupFullName, password); if (dbStatus == DistributedDB::DBStatus::OK) { ZLOGI("SingleKvStoreRecover success."); @@ -304,16 +305,16 @@ const std::string &BackupHandler::GetBackupPath(const std::string &deviceAccount { if (pathType == KvStoreAppManager::PATH_DE) { if (backupDirDe_.empty()) { - backupDirDe_ = Constant::Concatenate({ Constant::ROOT_PATH_DE, "/", Constant::SERVICE_NAME, "/", - deviceAccountId, "/", Constant::GetDefaultHarmonyAccountName(), - "/", "backup" }); + backupDirDe_ = Constant::Concatenate({Constant::ROOT_PATH_DE, "/", Constant::SERVICE_NAME, "/", + deviceAccountId, "/", Constant::GetDefaultHarmonyAccountName(), + "/", "backup"}); } return backupDirDe_; } else { if (backupDirCe_.empty()) { - backupDirCe_ = Constant::Concatenate({ Constant::ROOT_PATH_CE, "/", Constant::SERVICE_NAME, "/", - deviceAccountId, "/", Constant::GetDefaultHarmonyAccountName(), - "/", "backup" }); + backupDirCe_ = Constant::Concatenate({Constant::ROOT_PATH_CE, "/", Constant::SERVICE_NAME, "/", + deviceAccountId, "/", Constant::GetDefaultHarmonyAccountName(), + "/", "backup"}); } return backupDirCe_; } @@ -366,6 +367,7 @@ bool BackupHandler::FileExists(const std::string &path) bool BackupHandler::CheckNeedBackup() { +#ifdef SUPPORT_POWER auto &batterySrvClient = PowerMgr::BatterySrvClient::GetInstance(); auto chargingStatus = batterySrvClient.GetChargingStatus(); if (chargingStatus != PowerMgr::BatteryChargeState::CHARGE_STATE_ENABLE) { @@ -386,11 +388,12 @@ bool BackupHandler::CheckNeedBackup() ZLOGE("the device screen is on."); return false; } - int64_t currentTime = TimeUtils::CurrentTimeMicros(); + uint64_t currentTime = TimeUtils::CurrentTimeMicros(); if (currentTime - backupSuccessTime_ < 36000000 && backupSuccessTime_ > 0) { // 36000000 is 10 hours ZLOGE("no more than 10 hours since the last backup success."); return false; } +#endif return true; } diff --git a/services/distributeddataservice/app/src/executor_factory.cpp b/services/distributeddataservice/app/src/executor_factory.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b87fe785bbe003cfe1e1037dc5c1f1c0700ced60 --- /dev/null +++ b/services/distributeddataservice/app/src/executor_factory.cpp @@ -0,0 +1,46 @@ +/* +* Copyright (c) 2022 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +#include "executor_factory.h" + +namespace OHOS::DistributedData { +using namespace OHOS::DistributedKv; +ExecutorFactory &ExecutorFactory::GetInstance() +{ + static ExecutorFactory instance; + return instance; +} + +bool ExecutorFactory::Execute(KvStoreTask &&task) +{ + if (threadPool_ == nullptr) { + return false; + } + threadPool_->AddTask(std::move(task)); + return true; +} + +ExecutorFactory::ExecutorFactory() +{ + threadPool_ = KvStoreThreadPool::GetPool(POOL_SIZE, true); +} + +ExecutorFactory::~ExecutorFactory() +{ + if (threadPool_ != nullptr) { + threadPool_->Stop(); + threadPool_ = nullptr; + } +} +} // namespace OHOS::DistributedData \ No newline at end of file diff --git a/services/distributeddataservice/app/src/executor_factory.h b/services/distributeddataservice/app/src/executor_factory.h new file mode 100644 index 0000000000000000000000000000000000000000..c91e2839a190d19e71ca91d72caf713f95a19b6e --- /dev/null +++ b/services/distributeddataservice/app/src/executor_factory.h @@ -0,0 +1,36 @@ +/* +* Copyright (c) 2022 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +#ifndef DISTRIBUTEDDATAMGR_DATAMGR_EXECUTOR_FACTORY_H +#define DISTRIBUTEDDATAMGR_DATAMGR_EXECUTOR_FACTORY_H + +#include "kv_store_thread_pool.h" +namespace OHOS::DistributedData { +using OHOS::DistributedKv::KvStoreTask; +using OHOS::DistributedKv::KvStoreThreadPool; +class ExecutorFactory { +public: + static ExecutorFactory &GetInstance(); + bool Execute(KvStoreTask &&task); + +private: + ExecutorFactory(); + ~ExecutorFactory(); + + static constexpr int POOL_SIZE = 4; + + std::shared_ptr threadPool_; +}; +} // namespace OHOS::DistributedData +#endif // DISTRIBUTEDDATAMGR_DATAMGR_EXECUTOR_FACTORY_H diff --git a/services/distributeddataservice/app/src/flowctrl_manager/BUILD.gn b/services/distributeddataservice/app/src/flowctrl_manager/BUILD.gn index d760897529d0335bca678383e535600568352053..c794b70b6d9d39b447453700cdb990d22e0470cd 100755 --- a/services/distributeddataservice/app/src/flowctrl_manager/BUILD.gn +++ b/services/distributeddataservice/app/src/flowctrl_manager/BUILD.gn @@ -29,4 +29,7 @@ ohos_static_library("distributeddata_flowctrl_static") { cflags_cc = [ "-fvisibility=hidden" ] deps = [ "//utils/native/base:utils" ] + + subsystem_name = "distributeddatamgr" + part_name = "distributeddatamgr" } diff --git a/services/distributeddataservice/app/src/flowctrl_manager/kvstore_flowctrl_manager.cpp b/services/distributeddataservice/app/src/flowctrl_manager/kvstore_flowctrl_manager.cpp index d3ef0d7dcf8fcdf5850103dc839d4134b10b33ff..178b5bf0d0e72731ba69015d2227b925b23eb7d0 100755 --- a/services/distributeddataservice/app/src/flowctrl_manager/kvstore_flowctrl_manager.cpp +++ b/services/distributeddataservice/app/src/flowctrl_manager/kvstore_flowctrl_manager.cpp @@ -45,7 +45,7 @@ void KvStoreFlowCtrlManager::RefreshTokenBucket(TokenBucket &tokenBucket, uint64 bool KvStoreFlowCtrlManager::IsTokenEnough() { - int curTime = CurrentTimeMicros(); + uint64_t curTime = CurrentTimeMicros(); if (IsTokenEnoughSlice(burstTokenBucket_, curTime) && IsTokenEnoughSlice(sustainedTokenBucket_, curTime)) { burstTokenBucket_.lastAccessTime = curTime; burstTokenBucket_.leftNumInTokenBucket--; diff --git a/services/distributeddataservice/app/src/kvstore_account_observer.cpp b/services/distributeddataservice/app/src/kvstore_account_observer.cpp index 0e8991ad95ba51d115b60f21bdad19999e4c273f..ae25f382f965bc96f2d38aca3a6d6fe7f21b6032 100755 --- a/services/distributeddataservice/app/src/kvstore_account_observer.cpp +++ b/services/distributeddataservice/app/src/kvstore_account_observer.cpp @@ -17,6 +17,7 @@ #include "kvstore_account_observer.h" #include +#include "executor_factory.h" #include "kvstore_data_service.h" #include "log_print.h" @@ -26,7 +27,11 @@ std::atomic g_kvStoreAccountEventStatus {0}; void KvStoreAccountObserver::OnAccountChanged(const AccountEventInfo &eventInfo) { ZLOGI("account event %d, begin.", eventInfo.status); - kvStoreDataService_.AccountEventChanged(eventInfo); + KvStoreTask task([this, eventInfo]() { + ZLOGI("account event processing in thread"); + kvStoreDataService_.AccountEventChanged(eventInfo); + }); + DistributedData::ExecutorFactory::GetInstance().Execute(std::move(task)); ZLOGI("account event %d, end.", eventInfo.status); } } // namespace DistributedKv diff --git a/services/distributeddataservice/app/src/kvstore_app_manager.cpp b/services/distributeddataservice/app/src/kvstore_app_manager.cpp index 44f68e690b0d7b43fd8fd86b4b0eae470ffd4e1e..d46d3649493c81adc319396861dd74aa2bdde6e8 100755 --- a/services/distributeddataservice/app/src/kvstore_app_manager.cpp +++ b/services/distributeddataservice/app/src/kvstore_app_manager.cpp @@ -16,17 +16,20 @@ #define LOG_TAG "KvStoreAppManager" #include "kvstore_app_manager.h" + #include #include #include #include + #include + #include "account_delegate.h" #include "broadcast_sender.h" #include "checker/checker_manager.h" #include "constant.h" -#include "directory_utils.h" #include "device_kvstore_impl.h" +#include "directory_utils.h" #include "ikvstore.h" #include "kv_store_delegate.h" #include "kvstore_app_accessor.h" @@ -34,6 +37,7 @@ #include "log_print.h" #include "permission_validator.h" #include "reporter.h" +#include "route_head_handler_impl.h" #include "types.h" namespace OHOS { @@ -228,6 +232,7 @@ Status KvStoreAppManager::GetKvStore(const Options &options, const std::string & kvStore = nullptr; return Status::ERROR; } + kvStore->SetCompatibleIdentify(); auto result = singleStores_[type].emplace(storeId, kvStore); if (!result.second) { ZLOGE("emplace failed."); @@ -388,6 +393,7 @@ Status KvStoreAppManager::InitNbDbOption(const Options &options, const std::vect return Status::DB_ERROR; } + dbOption.syncDualTupleMode = true; // tuple of (appid+storeid) dbOption.createIfNecessary = options.createIfMissing; dbOption.isEncryptedDb = options.encrypt; if (options.encrypt) { @@ -462,8 +468,8 @@ DistributedDB::KvStoreDelegateManager *KvStoreAppManager::GetDelegateManager(Pat } userId_ = AccountDelegate::GetInstance()->GetCurrentAccountId(bundleName_); - ZLOGD("accountId: %s bundleName: %s", KvStoreUtils::ToBeAnonymous(userId_).c_str(), bundleName_.c_str()); - delegateManagers_[type] = new (std::nothrow) DistributedDB::KvStoreDelegateManager(trueAppId_, userId_); + ZLOGD("accountId: %{public}s bundleName: %{public}s", deviceAccountId_.c_str(), bundleName_.c_str()); + delegateManagers_[type] = new (std::nothrow) DistributedDB::KvStoreDelegateManager(trueAppId_, deviceAccountId_); if (delegateManagers_[type] == nullptr) { ZLOGE("delegateManagers_[%d] is nullptr.", type); return nullptr; @@ -690,10 +696,9 @@ std::string KvStoreAppManager::GetDataStoragePath(const std::string &userId, con PathType type) { std::string miscPath = (type == PATH_DE) ? Constant::ROOT_PATH_DE : Constant::ROOT_PATH_CE; - return Constant::Concatenate({ - miscPath, "/", Constant::SERVICE_NAME, "/", userId, "/", Constant::GetDefaultHarmonyAccountName(), - "/", bundleName, "/" - }); + return Constant::Concatenate( + {miscPath, "/", Constant::SERVICE_NAME, "/", userId, "/", Constant::GetDefaultHarmonyAccountName(), + "/", bundleName, "/"}); } DistributedDB::SecurityOption KvStoreAppManager::ConvertSecurity(int securityLevel) @@ -729,5 +734,23 @@ void KvStoreAppManager::Dump(int fd) const } } } + +bool KvStoreAppManager::IsStoreOpened(const std::string &storeId) const +{ + return (!singleStores_[PATH_DE].empty() && singleStores_->find(storeId) != singleStores_->end()) + || (!singleStores_[PATH_CE].empty() && singleStores_->find(storeId) != singleStores_->end()); +} + +void KvStoreAppManager::SetCompatibleIdentify(const std::string &deviceId) const +{ + for (const auto &storeType : singleStores_) { + for (const auto &item : storeType) { + if (item.second == nullptr) { + continue; + } + item.second->SetCompatibleIdentify(deviceId); + } + } +} } // namespace DistributedKv } // namespace OHOS diff --git a/services/distributeddataservice/app/src/kvstore_app_manager.h b/services/distributeddataservice/app/src/kvstore_app_manager.h index ca356d949f9d156a101b528ce56e5214cd1747b1..e1960c608f3dc2750945fc1b6ceb975abe144b69 100755 --- a/services/distributeddataservice/app/src/kvstore_app_manager.h +++ b/services/distributeddataservice/app/src/kvstore_app_manager.h @@ -75,6 +75,9 @@ public: static DistributedDB::SecurityOption ConvertSecurity(int securityLevel); size_t GetTotalKvStoreNum() const; + + bool IsStoreOpened(const std::string &storeId) const; + void SetCompatibleIdentify(const std::string &deviceId) const; private: DISALLOW_COPY_AND_MOVE(KvStoreAppManager); Status ConvertErrorStatus(DistributedDB::DBStatus dbStatus, bool createIfMissing); diff --git a/services/distributeddataservice/app/src/kvstore_data_service.cpp b/services/distributeddataservice/app/src/kvstore_data_service.cpp index 57ec67c977cb1be21d0aab081e3abdb42b17b79d..366e338844500a5e74387ccf099235202bcd96de 100644 --- a/services/distributeddataservice/app/src/kvstore_data_service.cpp +++ b/services/distributeddataservice/app/src/kvstore_data_service.cpp @@ -21,9 +21,11 @@ #include #include #include + #include #include +#include "auth/auth_delegate.h" #include "auto_launch_export.h" #include "bootstrap.h" #include "checker/checker_manager.h" @@ -32,10 +34,12 @@ #include "constant.h" #include "dds_trace.h" #include "device_kvstore_impl.h" +#include "executor_factory.h" #include "if_system_ability_manager.h" #include "iservice_registry.h" #include "kvstore_account_observer.h" #include "kvstore_app_accessor.h" +#include "kvstore_device_listener.h" #include "kvstore_meta_manager.h" #include "kvstore_utils.h" #include "log_print.h" @@ -45,8 +49,11 @@ #include "process_communicator_impl.h" #include "rdb_service_impl.h" #include "reporter.h" +#include "route_head_handler_impl.h" #include "system_ability_definition.h" #include "uninstaller/uninstaller.h" +#include "upgrade_manager.h" +#include "user_delegate.h" #include "utils/block_integer.h" #include "utils/crypto.h" @@ -93,9 +100,16 @@ void KvStoreDataService::Initialize() #ifndef UT_TEST KvStoreDelegateManager::SetProcessLabel(Bootstrap::GetInstance().GetProcessLabel(), "default"); #endif - auto communicator = std::make_shared(); + auto communicator = std::make_shared(RouteHeadHandlerImpl::Create); auto ret = KvStoreDelegateManager::SetProcessCommunicator(communicator); - ZLOGI("set communicator ret:%d.", static_cast(ret)); + ZLOGI("set communicator ret:%{public}d.", static_cast(ret)); + auto syncActivationCheck = [this](const std::string &userId, const std::string &appId, + const std::string &storeId) -> bool { + return CheckSyncActivation(userId, appId, storeId); + }; + ret = DistributedDB::KvStoreDelegateManager::SetSyncActivationCheckCallback(syncActivationCheck); + ZLOGI("set sync activation check callback ret:%{public}d.", static_cast(ret)); + InitSecurityAdapter(); KvStoreMetaManager::GetInstance().InitMetaParameter(); std::thread th = std::thread([]() { @@ -119,6 +133,8 @@ void KvStoreDataService::Initialize() accountEventObserver_ = std::make_shared(*this); AccountDelegate::GetInstance()->Subscribe(accountEventObserver_); + deviceInnerListener_ = std::make_unique(*this); + KvStoreUtils::GetProviderInstance().StartWatchDeviceChange(deviceInnerListener_.get(), { "innerListener" }); } Status KvStoreDataService::GetKvStore(const Options &options, const AppId &appId, const StoreId &storeId, @@ -186,26 +202,16 @@ Status KvStoreDataService::GetSingleKvStore(const Options &options, const AppId { DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__)); ZLOGI("begin."); - if (!appId.IsValid() || !storeId.IsValid() || !options.IsValidType() - || options.kvStoreType == KvStoreType::MULTI_VERSION) { - ZLOGE("invalid argument type."); - return Status::INVALID_ARGUMENT; - } - KVSTORE_ACCOUNT_EVENT_PROCESSING_CHECKER(Status::SYSTEM_ACCOUNT_EVENT_PROCESSING); KvStoreParam param; - param.bundleName = appId.appId; - param.storeId = storeId.storeId; - const int32_t uid = IPCSkeleton::GetCallingUid(); - param.trueAppId = CheckerManager::GetInstance().GetAppId(appId.appId, uid); - if (param.trueAppId.empty()) { - ZLOGW("appId:%{public}s, uid:%{public}d, PERMISSION_DENIED", appId.appId.c_str(), uid); - return Status::PERMISSION_DENIED; + Status status = FillStoreParam(options, appId, storeId, param); + if (status != Status::SUCCESS) { + callback(nullptr); + return status; } - param.userId = AccountDelegate::GetInstance()->GetDeviceAccountIdByUID(uid); SecretKeyPara keyPara; - Status status = KvStoreDataService::GetSecretKey(options, param, keyPara); + status = KvStoreDataService::GetSecretKey(options, param, keyPara); if (status != Status::SUCCESS) { callback(nullptr); return status; @@ -223,14 +229,21 @@ Status KvStoreDataService::GetSingleKvStore(const Options &options, const AppId it = result.first; } sptr store; - param.status = (it->second).GetKvStore(options, param.bundleName, param.storeId, uid, keyPara.secretKey, store); + param.status = + (it->second).GetKvStore(options, param.bundleName, param.storeId, param.uid, keyPara.secretKey, store); if (keyPara.outdated) { KvStoreMetaManager::GetInstance().ReKey(param.userId, param.bundleName, param.storeId, KvStoreAppManager::ConvertPathType(param.uid, param.bundleName, options.securityLevel), store); } if (param.status == Status::SUCCESS) { + status = UpdateMetaData(options, param, keyPara.metaKey, it->second); + if (status != Status::SUCCESS) { + ZLOGE("failed to write meta"); + callback(nullptr); + return status; + } callback(std::move(store)); - return UpdateMetaData(options, param, keyPara.metaKey, it->second); + return status; } param.status = GetSingleKvStoreFailDo(options, param, keyPara, it->second, store); @@ -238,6 +251,28 @@ Status KvStoreDataService::GetSingleKvStore(const Options &options, const AppId return param.status; } +Status KvStoreDataService::FillStoreParam( + const Options &options, const AppId &appId, const StoreId &storeId, KvStoreParam ¶m) +{ + if (!appId.IsValid() || !storeId.IsValid() || !options.IsValidType() + || options.kvStoreType == KvStoreType::MULTI_VERSION) { + ZLOGE("invalid argument type."); + return Status::INVALID_ARGUMENT; + } + param.bundleName = appId.appId; + param.storeId = storeId.storeId; + param.uid = IPCSkeleton::GetCallingUid(); + param.trueAppId = CheckerManager::GetInstance().GetAppId(appId.appId, param.uid); + ZLOGI("%{public}s, %{public}s", param.trueAppId.c_str(), param.bundleName.c_str()); + if (param.trueAppId.empty()) { + ZLOGW("appId:%{public}s, uid:%{public}d, PERMISSION_DENIED", appId.appId.c_str(), param.uid); + return PERMISSION_DENIED; + } + + param.userId = AccountDelegate::GetInstance()->GetDeviceAccountIdByUID(param.uid); + return SUCCESS; +} + Status KvStoreDataService::GetSecretKey(const Options &options, const KvStoreParam &kvParas, SecretKeyPara &secretKeyParas) { @@ -323,12 +358,17 @@ Status KvStoreDataService::RecoverSecretKey(const Status &alreadyCreated, bool & Status KvStoreDataService::UpdateMetaData(const Options &options, const KvStoreParam &kvParas, const std::vector &metaKey, KvStoreUserManager &kvStoreUserManager) { + auto localDeviceId = DeviceKvStoreImpl::GetLocalDeviceId(); + if (localDeviceId.empty()) { + ZLOGE("failed to get local device id"); + return Status::ERROR; + } KvStoreMetaData metaData; metaData.appId = kvParas.trueAppId; metaData.appType = "harmony"; metaData.bundleName = kvParas.bundleName; metaData.deviceAccountId = kvParas.userId; - metaData.deviceId = DeviceKvStoreImpl::GetLocalDeviceId(); + metaData.deviceId = localDeviceId; metaData.isAutoSync = options.autoSync; metaData.isBackup = options.backup; metaData.isEncrypt = options.encrypt; @@ -737,9 +777,9 @@ Status KvStoreDataService::AppExit(const AppId &appId, pid_t uid) ZLOGI("map size: %zu.", clientDeathObserverMap_.size()); } - std::string trueAppId = CheckerManager::GetInstance().GetAppId(appId.appId, uid); + std::string trueAppId = CheckerManager::GetInstance().GetAppId(appIdTmp.appId, uid); if (trueAppId.empty()) { - ZLOGW("check appId:%{public}s uid:%{public}d failed.", appId.appId.c_str(), uid); + ZLOGW("check appId:%{public}s uid:%{public}d failed.", appIdTmp.appId.c_str(), uid); return Status::PERMISSION_DENIED; } const std::string userId = AccountDelegate::GetInstance()->GetCurrentAccountId(appIdTmp.appId); @@ -816,12 +856,12 @@ void KvStoreDataService::OnStart() void KvStoreDataService::StartService() { static constexpr int32_t RETRY_TIMES = 10; - static constexpr int32_t RETRY_INTERVAL = 500; // unit is ms + static constexpr int32_t RETRY_INTERVAL = 500 * 1000; // unit is ms for (BlockInteger retry(RETRY_INTERVAL); retry < RETRY_TIMES; ++retry) { if (!DeviceKvStoreImpl::GetLocalDeviceId().empty()) { break; } - ZLOGE("GetLocalDeviceId failed, reties: %{public}d", static_cast(retry)); + ZLOGE("GetLocalDeviceId failed, retry count:%{public}d", static_cast(retry)); } // register this to ServiceManager. @@ -842,18 +882,12 @@ void KvStoreDataService::StartService() ZLOGE("backup create directory failed"); } // Initialize meta db delegate manager. - KvStoreMetaManager::GetInstance().InitMetaListener([this](const KvStoreMetaData &metaData) { - if (!metaData.isDirty) { - return; - } - - AppId appId; - appId.appId = metaData.bundleName; - StoreId storeId; - storeId.storeId = metaData.storeId; - CloseKvStore(appId, storeId); - DeleteKvStore(appId, storeId); - }); + KvStoreMetaManager::GetInstance().InitMetaListener(); + KvStoreMetaManager::GetInstance().SubscribeMeta( + KvStoreMetaRow::KEY_PREFIX, [this](const std::vector &key, const std::vector &value, + CHANGE_FLAG flag) { OnStoreMetaChanged(key, value, flag); }); + UpgradeManager::GetInstance().Init(); + UserDelegate::GetInstance().Init(); // subscribe account event listener to EventNotificationMgr AccountDelegate::GetInstance()->SubscribeAccountEvent(); @@ -883,48 +917,131 @@ void KvStoreDataService::StartService() KvStoreAppAccessor::GetInstance().EnableKvStoreAutoLaunch(); }); th.detach(); - ZLOGI("Publish ret: %d", static_cast(ret)); + ZLOGI("Publish ret: %{public}d", static_cast(ret)); } -bool KvStoreDataService::ResolveAutoLaunchParamByIdentifier(const std::string &identifier, - DistributedDB::AutoLaunchParam ¶m) +void KvStoreDataService::OnStoreMetaChanged( + const std::vector &key, const std::vector &value, CHANGE_FLAG flag) +{ + if (flag != CHANGE_FLAG::UPDATE) { + return; + } + StoreMetaData metaData; + metaData.Unmarshall({ value.begin(), value.end() }); + ZLOGD("meta data info appType:%{public}s, storeId:%{public}s isDirty:%{public}d", metaData.appType.c_str(), + metaData.storeId.c_str(), metaData.isDirty); + if (metaData.deviceId != DeviceKvStoreImpl::GetLocalDeviceId() || metaData.deviceId.empty()) { + ZLOGD("ignore other device change or invalid meta device"); + return; + } + static constexpr const char *HARMONY_APP = "harmony"; + if (!metaData.isDirty || metaData.appType != HARMONY_APP) { + return; + } + ZLOGI("dirty kv store. storeId:%{public}s", metaData.storeId.c_str()); + CloseKvStore({ metaData.bundleName }, { metaData.storeId }); + DeleteKvStore({ metaData.bundleName }, { metaData.storeId }); +} + +bool KvStoreDataService::ResolveAutoLaunchParamByIdentifier( + const std::string &identifier, DistributedDB::AutoLaunchParam ¶m) { ZLOGI("start"); std::map entries; - if (KvStoreMetaManager::GetInstance().GetFullMetaData(entries)) { - for (const auto &entry : entries) { - const std::string userId = AccountDelegate::GetInstance()->GetCurrentAccountId( - entry.second.kvStoreMetaData.bundleName); - const std::string &curIdentifier = KvStoreDelegateManager::GetKvStoreIdentifier(userId, - entry.second.kvStoreMetaData.appId, entry.second.kvStoreMetaData.storeId); - if (identifier == curIdentifier) { - ZLOGI("identifier find"); - DistributedDB::AutoLaunchOption option; - option.createIfNecessary = false; - option.isEncryptedDb = entry.second.kvStoreMetaData.isEncrypt; - DistributedDB::CipherPassword password; - const std::vector &secretKey = entry.second.secretKeyMetaData.secretKey; - if (password.SetValue(secretKey.data(), secretKey.size()) != DistributedDB::CipherPassword::OK) { - ZLOGE("Get secret key failed."); - } - option.passwd = password; - option.schema = entry.second.kvStoreMetaData.schema; - option.createDirByStoreIdOnly = true; - option.dataDir = entry.second.kvStoreMetaData.dataDir; - option.secOption = KvStoreAppManager::ConvertSecurity(entry.second.kvStoreMetaData.securityLevel); - option.isAutoSync = entry.second.kvStoreMetaData.isAutoSync; - param.userId = userId; - param.appId = entry.second.kvStoreMetaData.appId; - param.storeId = entry.second.kvStoreMetaData.storeId; - param.option = option; - return true; + if (!KvStoreMetaManager::GetInstance().GetFullMetaData(entries)) { + ZLOGE("get full meta failed"); + return false; + } + std::string localDeviceId = DeviceKvStoreImpl::GetLocalDeviceId(); + for (const auto &entry : entries) { + auto &storeMeta = entry.second.kvStoreMetaData; + if ((!param.userId.empty() && (param.userId != storeMeta.deviceAccountId)) + || (localDeviceId != storeMeta.deviceId)) { + // judge local userid and local meta + continue; + } + const std::string &itemTripleIdentifier = DistributedDB::KvStoreDelegateManager::GetKvStoreIdentifier( + storeMeta.userId, storeMeta.appId, storeMeta.storeId, false); + const std::string &itemDualIdentifier = + DistributedDB::KvStoreDelegateManager::GetKvStoreIdentifier("", storeMeta.appId, storeMeta.storeId, true); + if (identifier == itemTripleIdentifier) { + // old triple tuple identifier, should SetEqualIdentifier + ResolveAutoLaunchCompatible(entry.second, identifier); + } + if (identifier == itemDualIdentifier || identifier == itemTripleIdentifier) { + ZLOGI("identifier find"); + DistributedDB::AutoLaunchOption option; + option.createIfNecessary = false; + option.isEncryptedDb = storeMeta.isEncrypt; + DistributedDB::CipherPassword password; + const std::vector &secretKey = entry.second.secretKeyMetaData.secretKey; + if (password.SetValue(secretKey.data(), secretKey.size()) != DistributedDB::CipherPassword::OK) { + ZLOGE("Get secret key failed."); } + option.passwd = password; + option.schema = storeMeta.schema; + option.createDirByStoreIdOnly = true; + option.dataDir = storeMeta.dataDir; + option.secOption = KvStoreAppManager::ConvertSecurity(storeMeta.securityLevel); + option.isAutoSync = storeMeta.isAutoSync; + option.syncDualTupleMode = true; // dual tuple flag + param.appId = storeMeta.appId; + param.storeId = storeMeta.storeId; + param.option = option; + return true; } } ZLOGI("not find identifier"); return false; } +void KvStoreDataService::ResolveAutoLaunchCompatible(const MetaData &meta, const std::string &identifier) +{ + ZLOGI("AutoLaunch:peer device is old tuple, begin to open store"); + if (meta.kvStoreType >= KvStoreType::MULTI_VERSION) { + ZLOGW("no longer support multi or higher version store type"); + return; + } + + // open store and SetEqualIdentifier, then close store after 60s + auto &storeMeta = meta.kvStoreMetaData; + auto *delegateManager = new (std::nothrow) + DistributedDB::KvStoreDelegateManager(storeMeta.appId, storeMeta.deviceAccountId); + if (delegateManager == nullptr) { + ZLOGE("get store delegate manager failed"); + return; + } + delegateManager->SetKvStoreConfig({ storeMeta.dataDir }); + Options options = { + .encrypt = storeMeta.isEncrypt, + .autoSync = storeMeta.isAutoSync, + .securityLevel = storeMeta.securityLevel, + .kvStoreType = static_cast(storeMeta.kvStoreType), + .dataOwnership = true, + }; + DistributedDB::KvStoreNbDelegate::Option dbOptions; + KvStoreAppManager::InitNbDbOption(options, meta.secretKeyMetaData.secretKey, dbOptions); + DistributedDB::KvStoreNbDelegate *store = nullptr; + delegateManager->GetKvStore(storeMeta.storeId, dbOptions, + [&identifier, &store, &storeMeta](int status, DistributedDB::KvStoreNbDelegate *delegate) { + ZLOGI("temporary open db for equal identifier, ret:%{public}d", status); + if (delegate != nullptr) { + KvStoreTuple tuple = { storeMeta.deviceAccountId, storeMeta.appId, storeMeta.storeId }; + UpgradeManager::SetCompatibleIdentifyByType(delegate, tuple, IDENTICAL_ACCOUNT_GROUP); + UpgradeManager::SetCompatibleIdentifyByType(delegate, tuple, PEER_TO_PEER_GROUP); + store = delegate; + } + }); + KvStoreTask delayTask([delegateManager, store]() { + constexpr const int CLOSE_STORE_DELAY_TIME = 60; // unit: seconds + std::this_thread::sleep_for(std::chrono::seconds(CLOSE_STORE_DELAY_TIME)); + ZLOGI("AutoLaunch:close store after 60s while autolaunch finishied"); + delegateManager->CloseKvStore(store); + delete delegateManager; + }); + ExecutorFactory::GetInstance().Execute(std::move(delayTask)); +} + bool KvStoreDataService::CheckPermissions(const std::string &userId, const std::string &appId, const std::string &storeId, const std::string &deviceId, uint8_t flag) const { @@ -960,7 +1077,7 @@ bool KvStoreDataService::CheckPermissions(const std::string &userId, const std:: return true; } bool ret = PermissionValidator::CheckSyncPermission(userId, appId, metaData.uid); - ZLOGD("checking sync permission ret:%d.", ret); + ZLOGD("checking sync permission ret:%{public}d.", ret); return ret; } @@ -1068,19 +1185,9 @@ Status KvStoreDataService::DeleteKvStoreOnly(const std::string &bundleName, pid_ void KvStoreDataService::AccountEventChanged(const AccountEventInfo &eventInfo) { - ZLOGI("account event %d changed process, begin.", eventInfo.status); + ZLOGI("account event %{public}d changed process, begin.", eventInfo.status); std::lock_guard lg(accountMutex_); switch (eventInfo.status) { - case AccountStatus::HARMONY_ACCOUNT_LOGIN: - case AccountStatus::HARMONY_ACCOUNT_LOGOUT: { - g_kvStoreAccountEventStatus = 1; - // migrate all kvstore belong to this device account - for (auto &it : deviceAccountMap_) { - (it.second).MigrateAllKvStore(eventInfo.harmonyAccountId); - } - g_kvStoreAccountEventStatus = 0; - break; - } case AccountStatus::DEVICE_ACCOUNT_DELETE: { g_kvStoreAccountEventStatus = 1; // delete all kvstore belong to this device account @@ -1101,11 +1208,16 @@ void KvStoreDataService::AccountEventChanged(const AccountEventInfo &eventInfo) g_kvStoreAccountEventStatus = 0; break; } + case AccountStatus::DEVICE_ACCOUNT_SWITCHED: { + auto ret = DistributedDB::KvStoreDelegateManager::NotifyUserChanged(); + ZLOGI("notify delegate manager result:%{public}d", ret); + break; + } default: { break; } } - ZLOGI("account event %d changed process, end.", eventInfo.status); + ZLOGI("account event %{public}d changed process, end.", eventInfo.status); } Status KvStoreDataService::GetLocalDevice(DeviceInfo &device) @@ -1122,7 +1234,7 @@ Status KvStoreDataService::GetDeviceList(std::vector &deviceInfoList DeviceInfo deviceInfo = {device.deviceId, device.deviceName, device.deviceType}; deviceInfoList.push_back(deviceInfo); } - ZLOGD("strategy is %d.", strategy); + ZLOGD("strategy is %{public}d.", strategy); return Status::SUCCESS; } @@ -1160,7 +1272,7 @@ Status KvStoreDataService::StartWatchDeviceChange(sptrAsObject().GetRefPtr(); auto listenerPair = std::make_pair(objectPtr, observer); deviceListeners_.insert(listenerPair); - ZLOGD("strategy is %d.", strategy); + ZLOGD("strategy is %{public}d.", strategy); return Status::SUCCESS; } @@ -1180,6 +1292,43 @@ Status KvStoreDataService::StopWatchDeviceChange(sptrsecond.IsStoreOpened(appId, storeId); +} + +void KvStoreDataService::SetCompatibleIdentify(const AppDistributedKv::DeviceInfo &info) const +{ + for (const auto &item : deviceAccountMap_) { + item.second.SetCompatibleIdentify(info.deviceId); + } +} + +bool KvStoreDataService::CheckSyncActivation( + const std::string &userId, const std::string &appId, const std::string &storeId) +{ + ZLOGD("user:%{public}s, app:%{public}s, store:%{public}s", userId.c_str(), appId.c_str(), storeId.c_str()); + std::vector users = UserDelegate::GetInstance().GetLocalUserStatus(); + // active sync feature with single active user + for (const auto &user : users) { + if (userId == std::to_string(user.id)) { + if (!user.isActive) { + ZLOGD("the store is not in active user"); + return false; + } + // check store in other active user + continue; + } + if (IsStoreOpened(std::to_string(user.id), appId, storeId)) { + ZLOGD("the store already opened in user %{public}d", user.id); + return false; + } + } + ZLOGD("sync permitted"); + return true; +} + void KvStoreDataService::CreateRdbService() { rdbService_ = new(std::nothrow) DistributedRdb::RdbServiceImpl(); @@ -1239,4 +1388,4 @@ void DbMetaCallbackDelegateMgr::GetKvStoreKeys(std::vector &dbStats) } delegate_->CloseKvStore(kvStoreNbDelegatePtr); } -} +} // namespace OHOS::DistributedKv \ No newline at end of file diff --git a/services/distributeddataservice/app/src/kvstore_data_service.h b/services/distributeddataservice/app/src/kvstore_data_service.h index f627154430bc5d64977208ecb470e69aa7e4d147..1f7fbc0beaeca3c4be450f65f37d7a3eb2ed7541 100755 --- a/services/distributeddataservice/app/src/kvstore_data_service.h +++ b/services/distributeddataservice/app/src/kvstore_data_service.h @@ -17,20 +17,22 @@ #define KVSTORE_DATASERVICE_H #include -#include #include +#include + +#include "account_delegate.h" +#include "backup_handler.h" #include "constant.h" +#include "device_change_listener_impl.h" #include "ikvstore_data_service.h" +#include "kvstore_device_listener.h" #include "kvstore_impl.h" #include "kvstore_user_manager.h" +#include "reporter.h" +#include "security/security.h" #include "single_kvstore_impl.h" #include "system_ability.h" -#include "reporter.h" #include "types.h" -#include "account_delegate.h" -#include "backup_handler.h" -#include "device_change_listener_impl.h" -#include "security/security.h" namespace OHOS::DistributedRdb { class IRdbService; @@ -39,7 +41,9 @@ class RdbServiceImpl; namespace OHOS::DistributedKv { class KvStoreAccountObserver; -class KvStoreDataService : public SystemAbility, public KvStoreDataServiceStub { +class KvStoreDataService + : public SystemAbility + , public KvStoreDataServiceStub { DECLARE_SYSTEM_ABILITY(KvStoreDataService); public: @@ -86,6 +90,8 @@ public: void AccountEventChanged(const AccountEventInfo &eventInfo); + void SetCompatibleIdentify(const AppDistributedKv::DeviceInfo &info) const; + bool CheckBackupFileExist(const std::string &userId, const std::string &bundleName, const std::string &storeId, int pathType); @@ -105,6 +111,7 @@ public: Status alreadyCreated = Status::SUCCESS; bool outdated = false; }; + private: class KvStoreClientDeathObserverImpl { public: @@ -152,6 +159,8 @@ private: Status UpdateMetaData(const Options &options, const KvStoreParam &kvParas, const std::vector &metaKey, KvStoreUserManager &kvStoreUserManager); + void OnStoreMetaChanged(const std::vector &key, const std::vector &value, CHANGE_FLAG flag); + Status GetKvStoreFailDo(const Options &options, const KvStoreParam &kvParas, SecretKeyPara &secKeyParas, KvStoreUserManager &kvUserManager, sptr &kvStore); @@ -163,10 +172,14 @@ private: bool CheckPermissions(const std::string &userId, const std::string &appId, const std::string &storeId, const std::string &deviceId, uint8_t flag) const; bool ResolveAutoLaunchParamByIdentifier(const std::string &identifier, DistributedDB::AutoLaunchParam ¶m); + static void ResolveAutoLaunchCompatible(const MetaData &meta, const std::string &identifier); + bool CheckSyncActivation(const std::string &userId, const std::string &appId, const std::string &storeId); bool CheckOptions(const Options &options, const std::vector &metaKey) const; - void CreateRdbService(); + bool IsStoreOpened(const std::string &userId, const std::string &appId, const std::string &storeId); + static Status FillStoreParam( + const Options &options, const AppId &appId, const StoreId &storeId, KvStoreParam ¶m); static constexpr int TEN_SEC = 10; @@ -182,6 +195,7 @@ private: std::shared_ptr security_; sptr rdbService_; + std::shared_ptr deviceInnerListener_; }; class DbMetaCallbackDelegateMgr : public DbMetaCallbackDelegate { diff --git a/services/distributeddataservice/app/src/kvstore_device_listener.cpp b/services/distributeddataservice/app/src/kvstore_device_listener.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2462c7da6d9fe5ff36526a057fd84630887fff60 --- /dev/null +++ b/services/distributeddataservice/app/src/kvstore_device_listener.cpp @@ -0,0 +1,37 @@ +/* +* Copyright (c) 2022 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +#define LOG_TAG "KvStoreDeviceListener" +#include "kvstore_device_listener.h" + +#include "kvstore_data_service.h" +#include "log_print.h" + +namespace OHOS::DistributedKv { +void KvStoreDeviceListener::OnDeviceChanged( + const AppDistributedKv::DeviceInfo &info, const AppDistributedKv::DeviceChangeType &type) const +{ + if (type == AppDistributedKv::DeviceChangeType::DEVICE_OFFLINE) { + ZLOGE("ignore device offline"); + return; + } + kvStoreDataService_.SetCompatibleIdentify(info); +} + +KvStoreDeviceListener::KvStoreDeviceListener(KvStoreDataService &kvStoreDataService) + : kvStoreDataService_(kvStoreDataService) +{ +} +} // namespace OHOS::DistributedKv \ No newline at end of file diff --git a/services/distributeddataservice/app/src/kvstore_device_listener.h b/services/distributeddataservice/app/src/kvstore_device_listener.h new file mode 100644 index 0000000000000000000000000000000000000000..2c1eee2b3c2fac9afb497c6997ca104536338b79 --- /dev/null +++ b/services/distributeddataservice/app/src/kvstore_device_listener.h @@ -0,0 +1,33 @@ +/* +* Copyright (c) 2022 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +#ifndef DISTRIBUTEDDATAMGR_KVSTORE_DEVICE_LISTENER_H +#define DISTRIBUTEDDATAMGR_KVSTORE_DEVICE_LISTENER_H +#include "app_device_status_change_listener.h" + +namespace OHOS::DistributedKv { +using AppDeviceStatusChangeListener = AppDistributedKv::AppDeviceStatusChangeListener; +class KvStoreDataService; +class KvStoreDeviceListener : public AppDeviceStatusChangeListener { +public: + explicit KvStoreDeviceListener(KvStoreDataService &kvStoreDataService); + void OnDeviceChanged( + const AppDistributedKv::DeviceInfo &info, const AppDistributedKv::DeviceChangeType &type) const override; + +private: + KvStoreDataService &kvStoreDataService_; +}; +} // namespace OHOS::DistributedKv +#endif // DISTRIBUTEDDATAMGR_KVSTORE_DEVICE_LISTENER_H diff --git a/services/distributeddataservice/app/src/kvstore_impl.h b/services/distributeddataservice/app/src/kvstore_impl.h index d399045e9a86404957222fc685522de012bd7069..657a0a0fa24c4edfd41323abb37fdd03193adb04 100755 --- a/services/distributeddataservice/app/src/kvstore_impl.h +++ b/services/distributeddataservice/app/src/kvstore_impl.h @@ -126,7 +126,7 @@ private: // distributeddb is responsible for free kvStoreDelegate_, // by calling CloseKvStore in KvStoreAppManager, // can not free it in KvStoreImpl's destructor. - mutable std::shared_mutex storeDelegateMutex_{}; + mutable std::shared_mutex storeDelegateMutex_ {}; DistributedDB::KvStoreDelegate *kvStoreDelegate_; std::mutex storeObserverMutex_; std::set observerSet_; diff --git a/services/distributeddataservice/app/src/kvstore_meta_manager.cpp b/services/distributeddataservice/app/src/kvstore_meta_manager.cpp index 5cba848d37ed69940e6942f2605ab67e7246169c..7a01c97154f75ab40e7ad864001bb6681a6d2687 100755 --- a/services/distributeddataservice/app/src/kvstore_meta_manager.cpp +++ b/services/distributeddataservice/app/src/kvstore_meta_manager.cpp @@ -15,25 +15,33 @@ #define LOG_TAG "KvStoreMetaManager" #include "kvstore_meta_manager.h" -#include -#include + #include #include -#include #include -#include "hks_api.h" -#include "hks_param.h" + +#include +#include +#include + #include "account_delegate.h" #include "constant.h" -#include "kvstore_utils.h" #include "device_kvstore_impl.h" +#include "directory_utils.h" +#include "executor_factory.h" +#include "hks_api.h" +#include "hks_param.h" +#include "kvstore_app_manager.h" #include "kvstore_data_service.h" +#include "kvstore_utils.h" #include "log_print.h" +#include "metadata/capability_meta_data.h" +#include "metadata/user_meta_data.h" +#include "rdb_types.h" #include "reporter.h" -#include "directory_utils.h" -#include "kvstore_app_manager.h" +#include "serializable/serializable.h" +#include "user_delegate.h" #include "utils/crypto.h" -#include "rdb_types.h" namespace OHOS { namespace DistributedKv { @@ -76,17 +84,21 @@ KvStoreMetaManager &KvStoreMetaManager::GetInstance() return instance; } -void KvStoreMetaManager::InitMetaListener(std::function observer) +void KvStoreMetaManager::SubscribeMeta(const std::string &keyPrefix, const ChangeObserver &observer) { - metaObserver_.notify_ = observer; + metaObserver_.handlerMap_[keyPrefix] = observer; +} +void KvStoreMetaManager::InitMetaListener() +{ InitMetaData(); - auto status = KvStoreUtils::GetProviderInstance().StartWatchDeviceChange(&listener_, {"metaMgr"}); + auto status = KvStoreUtils::GetProviderInstance().StartWatchDeviceChange(&listener_, { "metaMgr" }); if (status != AppDistributedKv::Status::SUCCESS) { ZLOGW("register failed."); + return; } ZLOGI("register meta device change success."); - GetInstance().SubscribeMetaKvStore(); + SubscribeMetaKvStore(); } void KvStoreMetaManager::InitMetaData() @@ -124,6 +136,7 @@ void KvStoreMetaManager::InitMetaData() if (CheckUpdateServiceMeta(metaKey, UPDATE, value) != Status::SUCCESS) { ZLOGW("CheckUpdateServiceMeta database failed."); } + ZLOGI("end."); } @@ -291,7 +304,7 @@ Status KvStoreMetaManager::CheckUpdateServiceMeta(const std::vector &me default: break; } - ZLOGI("Flag: %d status: %d", static_cast(flag), static_cast(dbStatus)); + ZLOGI("Flag: %{public}d status: %{public}d", static_cast(flag), static_cast(dbStatus)); SyncMeta(); return (dbStatus != DistributedDB::DBStatus::OK) ? Status::DB_ERROR : Status::SUCCESS; } @@ -833,10 +846,10 @@ void KvStoreMetaManager::SubscribeMetaKvStore() return; } - int mode = DistributedDB::OBSERVER_CHANGES_NATIVE; + int mode = DistributedDB::OBSERVER_CHANGES_NATIVE | DistributedDB::OBSERVER_CHANGES_FOREIGN; auto dbStatus = metaDelegate->RegisterObserver(DistributedDB::Key(), mode, &metaObserver_); if (dbStatus != DistributedDB::DBStatus::OK) { - ZLOGW("register meta observer failed :%d.", dbStatus); + ZLOGW("register meta observer failed :%{public}d.", dbStatus); } } @@ -934,7 +947,7 @@ Status KvStoreMetaManager::GetStategyMeta(const std::string &key, if (local != range->end()) { json obj = *local; if (obj.is_array()) { - std::vector v; + std::vector v; obj.get_to(v); strategies.insert({LOCAL_LABEL, v}); } @@ -943,7 +956,7 @@ Status KvStoreMetaManager::GetStategyMeta(const std::string &key, if (remote != range->end()) { json obj = *remote; if (obj.is_array()) { - std::vector v; + std::vector v; obj.get_to(v); strategies.insert({REMOTE_LABEL, v}); } @@ -959,27 +972,24 @@ KvStoreMetaManager::KvStoreMetaObserver::~KvStoreMetaObserver() void KvStoreMetaManager::KvStoreMetaObserver::OnChange(const DistributedDB::KvStoreChangedData &data) { ZLOGD("on data change."); - if (notify_ != nullptr) { - auto &updated = data.GetEntriesUpdated(); - for (const auto &entry : updated) { - std::string key(entry.key.begin(), entry.key.end()); - if (key.find(KvStoreMetaRow::KEY_PREFIX) != 0) { - continue; - } + HandleChanges(CHANGE_FLAG::INSERT, data.GetEntriesInserted()); + HandleChanges(CHANGE_FLAG::UPDATE, data.GetEntriesUpdated()); + HandleChanges(CHANGE_FLAG::DELETE, data.GetEntriesDeleted()); + KvStoreMetaManager::GetInstance().SyncMeta(); +} - KvStoreMetaData metaData; - std::string json(entry.value.begin(), entry.value.end()); - metaData.Unmarshal(Serializable::ToJson(json)); - ZLOGD("meta data info appType:%s, storeId:%s isDirty:%d", - metaData.appType.c_str(), metaData.storeId.c_str(), metaData.isDirty); - if (!metaData.isDirty || metaData.appType != HARMONY_APP) { - continue; +void KvStoreMetaManager::KvStoreMetaObserver::HandleChanges( + CHANGE_FLAG flag, const std::list &entries) +{ + for (const auto &entry : entries) { + std::string key(entry.key.begin(), entry.key.end()); + for (const auto &item : handlerMap_) { + ZLOGI("flag:%{public}d, key:%{public}s", flag, key.c_str()); + if (key.find(item.first) == 0) { + item.second(entry.key, entry.value, flag); } - ZLOGI("dirty kv store. storeId:%s", metaData.storeId.c_str()); - notify_(metaData); } } - KvStoreMetaManager::GetInstance().SyncMeta(); } void KvStoreMetaManager::MetaDeviceChangeListenerImpl::OnDeviceChanged( @@ -1046,7 +1056,7 @@ Status KvStoreMetaManager::GetKvStoreMeta(const std::vector &metaKey, K } DistributedDB::Value dbValue; DistributedDB::DBStatus dbStatus = metaDelegate->Get(metaKey, dbValue); - ZLOGI("status: %d", static_cast(dbStatus)); + ZLOGI("status: %{public}d", static_cast(dbStatus)); if (dbStatus == DistributedDB::DBStatus::NOT_FOUND) { ZLOGI("key not found."); return Status::KEY_NOT_FOUND; @@ -1250,5 +1260,5 @@ bool KvStoreMetaManager::GetKvStoreMetaDataByAppId(const std::string &appId, KvS { return GetKvStoreMetaByType(KvStoreMetaData::APP_ID, appId, metaData); } -} // namespace DistributedKv -} // namespace OHOS +} // namespace DistributedKv +} // namespace OHOS diff --git a/services/distributeddataservice/app/src/kvstore_meta_manager.h b/services/distributeddataservice/app/src/kvstore_meta_manager.h index c67d6b70cfe92e9831b4372e533f02a9d69b1c24..20925958c362f50684a10577d002c6a195196613 100755 --- a/services/distributeddataservice/app/src/kvstore_meta_manager.h +++ b/services/distributeddataservice/app/src/kvstore_meta_manager.h @@ -19,12 +19,13 @@ #include #include "app_device_status_change_listener.h" -#include "types.h" -#include "system_ability.h" #include "kv_store_delegate.h" #include "kv_store_delegate_manager.h" +#include "kv_store_task.h" #include "kvstore_impl.h" #include "single_kvstore_impl.h" +#include "system_ability.h" +#include "types.h" namespace OHOS { namespace DistributedKv { @@ -37,6 +38,12 @@ enum FLAG { CHECK_EXIST_LOCAL, }; +enum class CHANGE_FLAG { + INSERT, + UPDATE, + DELETE +}; + struct Serializable { using json = nlohmann::json; template @@ -146,12 +153,14 @@ private: class KvStoreMetaManager { public: static constexpr uint32_t META_STORE_VERSION = 0x03000001; + static const inline std::string META_DB_APP_ID = "distributeddata"; enum DatabaseType { KVDB, RDB, }; using NbDelegate = std::unique_ptr>; + using ChangeObserver = std::function &, const std::vector &, CHANGE_FLAG)>; class MetaDeviceChangeListenerImpl : public AppDistributedKv::AppDeviceStatusChangeListener { void OnDeviceChanged(const AppDistributedKv::DeviceInfo &info, @@ -165,9 +174,8 @@ public: static KvStoreMetaManager &GetInstance(); void InitMetaParameter(); - - void InitMetaListener(std::function observer); - + void InitMetaListener(); + void SubscribeMeta(const std::string &keyPrefix, const ChangeObserver &observer); const NbDelegate &GetMetaKvStore(); Status CheckUpdateServiceMeta(const std::vector &metaKey, FLAG flag, const std::vector &val = {}); @@ -256,10 +264,11 @@ private: // Database change callback void OnChange(const DistributedDB::KvStoreChangedData &data) override; - std::function notify_ = nullptr; + std::map handlerMap_; + private: + void HandleChanges(CHANGE_FLAG flag, const std::list &list); }; - static const inline std::string META_DB_APP_ID = "distributeddata"; static constexpr const char *ROOT_KEY_ALIAS = "distributed_db_root_key"; static constexpr const char *STRATEGY_META_PREFIX = "StrategyMetaData"; static constexpr const char *CAPABILITY_ENABLED = "capabilityEnabled"; diff --git a/services/distributeddataservice/app/src/kvstore_observer_impl.h b/services/distributeddataservice/app/src/kvstore_observer_impl.h index 7887c2c42894a5cdb221709d93ef4bc0fa61c5d3..55c9d792aa20dafd8a4ba114283e2b8139efc28e 100644 --- a/services/distributeddataservice/app/src/kvstore_observer_impl.h +++ b/services/distributeddataservice/app/src/kvstore_observer_impl.h @@ -23,7 +23,6 @@ namespace OHOS { namespace DistributedKv { - class KvStoreObserverImpl : public DistributedDB::KvStoreObserver { public: KvStoreObserverImpl(SubscribeType subscribeType, sptr observerProxy); @@ -40,7 +39,6 @@ private: SubscribeType subscribeType_; sptr observerProxy_; }; - } // namespace DistributedKv } // namespace OHOS diff --git a/services/distributeddataservice/app/src/kvstore_snapshot_impl.h b/services/distributeddataservice/app/src/kvstore_snapshot_impl.h index d806f1a44a6a297a9dfa0e6bffefbe2c16ac162f..74f385f57561049ea8729d98ba6c37c8e611abe3 100644 --- a/services/distributeddataservice/app/src/kvstore_snapshot_impl.h +++ b/services/distributeddataservice/app/src/kvstore_snapshot_impl.h @@ -30,7 +30,6 @@ namespace OHOS { namespace DistributedKv { - class KvStoreSnapshotImpl : public KvStoreSnapshotImplStub { public: explicit KvStoreSnapshotImpl(DistributedDB::KvStoreSnapshotDelegate *kvStoreSnapshotDelegate, @@ -79,7 +78,6 @@ private: void GetKeysFromDelegateLocked(const Key &prefixKey, const Key &nextKey, std::function &, const Key &)> callback); }; - } // namespace DistributedKv } // namespace OHOS diff --git a/services/distributeddataservice/app/src/kvstore_user_manager.cpp b/services/distributeddataservice/app/src/kvstore_user_manager.cpp index 98ef5cad67a699b83d1d8969f1b01b0983d3a692..0e472bc0c63b23c41c366aa145c208cccaadc99f 100755 --- a/services/distributeddataservice/app/src/kvstore_user_manager.cpp +++ b/services/distributeddataservice/app/src/kvstore_user_manager.cpp @@ -143,5 +143,18 @@ void KvStoreUserManager::Dump(int fd) const pair.second.Dump(fd); } } + +bool KvStoreUserManager::IsStoreOpened(const std::string &appId, const std::string &storeId) +{ + auto it = appMap_.find(appId); + return it != appMap_.end() && it->second.IsStoreOpened(storeId); +} + +void KvStoreUserManager::SetCompatibleIdentify(const std::string &deviceId) const +{ + for (const auto &item : appMap_) { + item.second.SetCompatibleIdentify(deviceId); + } +} } // namespace DistributedKv } // namespace OHOS diff --git a/services/distributeddataservice/app/src/kvstore_user_manager.h b/services/distributeddataservice/app/src/kvstore_user_manager.h index d445ae7e6059803e2619e5ff9d307b16bc06e861..184c9b9814032c58ba4b14b0f5b36fb153eb0da9 100755 --- a/services/distributeddataservice/app/src/kvstore_user_manager.h +++ b/services/distributeddataservice/app/src/kvstore_user_manager.h @@ -66,6 +66,9 @@ public: void Dump(int fd) const; + bool IsStoreOpened(const std::string &appId, const std::string &storeId); + void SetCompatibleIdentify(const std::string &deviceId) const; + private: std::mutex appMutex_; std::map appMap_; diff --git a/services/distributeddataservice/app/src/session_manager/route_head_handler_impl.cpp b/services/distributeddataservice/app/src/session_manager/route_head_handler_impl.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f763d20d34a47f6b3353ddac5bfa727bc3f798eb --- /dev/null +++ b/services/distributeddataservice/app/src/session_manager/route_head_handler_impl.cpp @@ -0,0 +1,269 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "route_head_handler_impl.h" + +#define LOG_TAG "RouteHeadHandler" + +#include "auth/auth_delegate.h" +#include "device_kvstore_impl.h" +#include "kvstore_meta_manager.h" +#include "log_print.h" +#include "securec.h" +#include "upgrade_manager.h" + +namespace OHOS::DistributedData { +using namespace OHOS::DistributedKv; +constexpr const int ALIGN_WIDTH = 8; +std::shared_ptr RouteHeadHandlerImpl::Create(const ExtendInfo &info) +{ + auto handler = std::make_shared(info); + if (handler == nullptr) { + ZLOGE("new instance failed"); + return nullptr; + } + handler->Init(); + return handler; +} + +RouteHeadHandlerImpl::RouteHeadHandlerImpl(const ExtendInfo &info) + : userId_(info.userId), appId_(info.appId), storeId_(info.storeId), deviceId_(info.dstTarget), headSize_(0) +{ + ZLOGI("init route handler, app:%{public}s, user:%{public}s, peer:%{public}s", appId_.c_str(), userId_.c_str(), + deviceId_.c_str()); +} + +void RouteHeadHandlerImpl::Init() +{ + ZLOGD("begin"); + if (deviceId_.empty()) { + return; + } + SessionPoint localPoint { DeviceKvStoreImpl::GetLocalDeviceId(), std::stoi(userId_), appId_ }; + session_ = SessionManager::GetInstance().GetSession(localPoint, deviceId_); + ZLOGD("valid session:%{public}s", Serializable::Marshall(session_).c_str()); +} + +DistributedDB::DBStatus RouteHeadHandlerImpl::GetHeadDataSize(uint32_t &headSize) +{ + ZLOGD("begin"); + headSize = 0; + if (appId_ == DistributedKv::KvStoreMetaManager::META_DB_APP_ID) { + ZLOGI("meta data permitted"); + return DistributedDB::OK; + } + bool flag = false; + auto peerCap = UpgradeManager::GetInstance().GetCapability(session_.targetDeviceId, flag); + if (!flag) { + ZLOGI("get peer cap failed"); + return DistributedDB::DB_ERROR; + } + if (peerCap.version == CapMetaData::INVALID_VERSION) { + // older versions ignore pack extend head + ZLOGI("ignore older version device"); + return DistributedDB::OK; + } + if (!session_.IsValid()) { + ZLOGI("no valid session to peer device"); + return DistributedDB::DB_ERROR; + } + size_t expectSize = sizeof(RouteHead) + sizeof(SessionDevicePair) + sizeof(SessionUserPair) + + session_.targetUserIds.size() * sizeof(int) + sizeof(SessionAppId) + session_.appId.size(); + + // align message uint width + headSize = GET_ALIGNED_SIZE(expectSize, ALIGN_WIDTH); + ZLOGI("packed size:%{public}u", headSize); + headSize_ = headSize; + return DistributedDB::OK; +} + +DistributedDB::DBStatus RouteHeadHandlerImpl::FillHeadData(uint8_t *data, uint32_t headSize, uint32_t totalLen) +{ + ZLOGD("begin"); + if (headSize != headSize_) { + ZLOGI("size not match"); + return DistributedDB::DB_ERROR; + } + if (headSize_ == 0) { + ZLOGI("ignore older version device"); + return DistributedDB::OK; + } + auto packRet = PackData(data, headSize); + ZLOGD("pack result:%{public}d", packRet); + return packRet ? DistributedDB::OK : DistributedDB::DB_ERROR; +} + +bool RouteHeadHandlerImpl::PackData(uint8_t *data, uint32_t totalLen) +{ + if (headSize_ > totalLen) { + ZLOGE("the buffer size is not enough"); + return false; + } + + auto isOk = PackDataHead(data, headSize_); + if (isOk) { + return PackDataBody(data + sizeof(RouteHead), headSize_ - sizeof(RouteHead)); + } + return false; +} + +bool RouteHeadHandlerImpl::PackDataHead(uint8_t *data, uint32_t totalLen) +{ + uint8_t *ptr = data; + if (headSize_ < sizeof(RouteHead)) { + return false; + } + RouteHead *head = reinterpret_cast(ptr); + head->magic = RouteHead::MAGIC_NUMBER; + head->version = RouteHead::VERSION; + head->checkSum = 0; + head->dataLen = static_cast(totalLen - sizeof(RouteHead)); + return true; +} + +bool RouteHeadHandlerImpl::PackDataBody(uint8_t *data, uint32_t totalLen) +{ + uint8_t *ptr = data; + SessionDevicePair *devicePair = reinterpret_cast(ptr); + auto ret = strcpy_s(devicePair->sourceDeviceId, DEVICE_ID_SIZE_MAX, session_.sourceDeviceId.c_str()); + if (ret != 0) { + ZLOGE("strcpy for source device id failed"); + return false; + } + ret = strcpy_s(devicePair->targetDeviceId, DEVICE_ID_SIZE_MAX, session_.targetDeviceId.c_str()); + if (ret != 0) { + ZLOGE("strcpy for target device id failed"); + return false; + } + ptr += sizeof(SessionDevicePair); + + SessionUserPair *userPair = reinterpret_cast(ptr); + userPair->sourceUserId = session_.sourceUserId; + userPair->targetUserCount = session_.targetUserIds.size(); + for (size_t i = 0; i < session_.targetUserIds.size(); ++i) { + *(userPair->targetUserIds + i) = session_.targetUserIds[i]; + } + ptr += (sizeof(SessionUserPair) + session_.targetUserIds.size() * sizeof(int)); + + SessionAppId *appPair = reinterpret_cast(ptr); + appPair->len = data + totalLen - ptr; // left size + ret = strcpy_s(appPair->appId, data + totalLen - ptr, session_.appId.c_str()); + if (ret != 0) { + ZLOGE("strcpy for app id failed"); + return false; + } + return true; +} + +bool RouteHeadHandlerImpl::ParseHeadData( + const uint8_t *data, uint32_t len, uint32_t &headSize, std::vector &users) +{ + auto ret = UnPackData(data, len, headSize); + if (!ret) { + headSize = 0; + ZLOGE("unpack data head failed"); + return false; + } + ZLOGI("unpacked size:%{public}u", headSize); + // flip the local and peer ends + SessionPoint local { .deviceId = session_.targetDeviceId, .appId = session_.appId }; + SessionPoint peer { .deviceId = session_.sourceDeviceId, .userId = session_.sourceUserId, .appId = session_.appId }; + ZLOGI("validSession:%{public}s", Serializable::Marshall(session_).c_str()); + for (const auto &item : session_.targetUserIds) { + local.userId = item; + if (SessionManager::GetInstance().CheckSession(local, peer)) { + users.emplace_back(std::to_string(item)); + } + } + return true; +} + +bool RouteHeadHandlerImpl::UnPackData(const uint8_t *data, uint32_t totalLen, uint32_t &unpackedSize) +{ + if (data == nullptr || totalLen < sizeof(RouteHead)) { + ZLOGE("invalid input data"); + return false; + } + unpackedSize = 0; + const RouteHead *head = UnPackHeadHead(data, totalLen); + if (head != nullptr && head->version == RouteHead::VERSION) { + auto isOk = UnPackHeadBody(data + sizeof(RouteHead), totalLen - sizeof(RouteHead)); + if (isOk) { + unpackedSize = sizeof(RouteHead) + head->dataLen; + } + return isOk; + } + return false; +} + +const RouteHead *RouteHeadHandlerImpl::UnPackHeadHead(const uint8_t *data, uint32_t totalLen) +{ + const uint8_t *ptr = data; + const RouteHead *head = reinterpret_cast(ptr); + if (head->magic != RouteHead::MAGIC_NUMBER) { + ZLOGW("not route head data"); + return nullptr; + } + if (head->dataLen + sizeof(RouteHead) > totalLen) { + ZLOGE("invalid route head len"); + return nullptr; + } + return head; +} + +bool RouteHeadHandlerImpl::UnPackHeadBody(const uint8_t *data, uint32_t totalLen) +{ + const uint8_t *ptr = data; + uint32_t leftSize = totalLen; + + if (leftSize < sizeof(SessionDevicePair)) { + ZLOGE("failed to parse device pair"); + return false; + } + const SessionDevicePair *devicePair = reinterpret_cast(ptr); + session_.sourceDeviceId.append(devicePair->sourceDeviceId, DEVICE_ID_SIZE_MAX); + session_.targetDeviceId.append(devicePair->targetDeviceId, DEVICE_ID_SIZE_MAX); + ptr += sizeof(SessionDevicePair); + leftSize -= sizeof(SessionDevicePair); + + if (leftSize < sizeof(SessionUserPair)) { + ZLOGE("failed to parse user pair"); + return false; + } + const SessionUserPair *userPair = reinterpret_cast(ptr); + session_.sourceUserId = userPair->sourceUserId; + + if (leftSize < sizeof(SessionUserPair) + userPair->targetUserCount * sizeof(int)) { + ZLOGE("failed to parse user pair, target user"); + return false; + } + for (int i = 0; i < userPair->targetUserCount; ++i) { + session_.targetUserIds.push_back(*(userPair->targetUserIds + i)); + } + ptr += sizeof(SessionUserPair) + userPair->targetUserCount * sizeof(int); + + if (leftSize < sizeof(SessionAppId)) { + ZLOGE("failed to parse app id len"); + return false; + } + const SessionAppId *appId = reinterpret_cast(ptr); + + if (leftSize < sizeof(SessionAppId) + appId->len) { + ZLOGE("failed to parse app id"); + return false; + } + session_.appId.append(appId->appId, appId->len); + return true; +} +} // namespace OHOS::DistributedData \ No newline at end of file diff --git a/services/distributeddataservice/app/src/session_manager/route_head_handler_impl.h b/services/distributeddataservice/app/src/session_manager/route_head_handler_impl.h new file mode 100644 index 0000000000000000000000000000000000000000..395e4d3361a2adf6963ff5305cc281bc8aaedd02 --- /dev/null +++ b/services/distributeddataservice/app/src/session_manager/route_head_handler_impl.h @@ -0,0 +1,83 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef DISTRIBUTEDDATAMGR_ROUTE_HEAD_HANDLER_H +#define DISTRIBUTEDDATAMGR_ROUTE_HEAD_HANDLER_H +#include "process_communicator_impl.h" +#include "route_head_handler.h" +#include "serializable/serializable.h" +#include "session_manager.h" + +namespace OHOS::DistributedData { +template constexpr T GET_ALIGNED_SIZE(T x, int alignWidth) +{ + return (x + (alignWidth - 1)) & ~(alignWidth - 1); +} + +#pragma pack(1) +// format: head + device pair + user pair + appid +struct RouteHead { + static constexpr uint16_t MAGIC_NUMBER = 0x8421; + static constexpr uint16_t VERSION = 0x1; + uint16_t magic = MAGIC_NUMBER; + uint16_t version = VERSION; + uint64_t checkSum; + uint32_t dataLen; +}; + +constexpr const int32_t DEVICE_ID_SIZE_MAX = 65; +struct SessionDevicePair { + char sourceDeviceId[DEVICE_ID_SIZE_MAX]; + char targetDeviceId[DEVICE_ID_SIZE_MAX]; +}; + +struct SessionUserPair { + int sourceUserId; + uint8_t targetUserCount; + int targetUserIds[0]; +}; + +struct SessionAppId { + uint32_t len; + char appId[0]; +}; +#pragma pack() + +class RouteHeadHandlerImpl : public DistributedData::RouteHeadHandler { +public: + static std::shared_ptr Create(const ExtendInfo &info); + explicit RouteHeadHandlerImpl(const ExtendInfo &info); + DBStatus GetHeadDataSize(uint32_t &headSize) override; + DBStatus FillHeadData(uint8_t *data, uint32_t headSize, uint32_t totalLen) override; + bool ParseHeadData(const uint8_t *data, uint32_t len, uint32_t &headSize, std::vector &users) override; + +private: + void Init(); + bool PackData(uint8_t *data, uint32_t totalLen); + bool PackDataHead(uint8_t *data, uint32_t totalLen); + bool PackDataBody(uint8_t *data, uint32_t totalLen); + bool UnPackData(const uint8_t *data, uint32_t totalLen, uint32_t &unpackedSize); + const RouteHead *UnPackHeadHead(const uint8_t *data, uint32_t totalLen); + bool UnPackHeadBody(const uint8_t *data, uint32_t totalLen); + + std::string userId_; + std::string appId_; + std::string storeId_; + std::string deviceId_; + Session session_; + uint32_t headSize_; +}; +} // namespace OHOS::DistributedData +#endif // DISTRIBUTEDDATAMGR_ROUTE_HEAD_HANDLER_H diff --git a/services/distributeddataservice/app/src/session_manager/session_manager.cpp b/services/distributeddataservice/app/src/session_manager/session_manager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1f54406b000676710ed9864d7efe5561cd170a61 --- /dev/null +++ b/services/distributeddataservice/app/src/session_manager/session_manager.cpp @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "session_manager.h" + +#define LOG_TAG "SessionManager" + +#include "auth/auth_delegate.h" +#include "checker/checker_manager.h" +#include "log/log_print.h" +#include "user_delegate.h" + +namespace OHOS::DistributedData { +using namespace OHOS::DistributedKv; +SessionManager &SessionManager::GetInstance() +{ + static SessionManager instance; + return instance; +} + +Session SessionManager::GetSession(const SessionPoint &from, const std::string &targetDeviceId) const +{ + ZLOGD("begin. peer device:%{public}.10s", targetDeviceId.c_str()); + auto users = UserDelegate::GetInstance().GetRemoteUserStatus(targetDeviceId); + Session session; + session.appId = from.appId; + session.sourceUserId = from.userId; + session.sourceDeviceId = from.deviceId; + session.targetDeviceId = targetDeviceId; + for (const auto &user : users) { + bool isPermitted = AuthDelegate::GetInstance()->CheckAccess(from.userId, user.id, targetDeviceId, from.appId); + ZLOGD("access to peer user %{public}d is %{public}d", user.id, isPermitted); + if (isPermitted) { + session.targetUserIds.push_back(user.id); + } + } + ZLOGD("end"); + return session; +} +bool SessionManager::CheckSession(const SessionPoint &from, const SessionPoint &to) const +{ + return AuthDelegate::GetInstance()->CheckAccess(from.userId, to.userId, to.deviceId, from.appId); +} + +bool Session::Marshal(json &node) const +{ + bool ret = true; + ret = SetValue(node[GET_NAME(sourceDeviceId)], sourceDeviceId) && ret; + ret = SetValue(node[GET_NAME(targetDeviceId)], targetDeviceId) && ret; + ret = SetValue(node[GET_NAME(sourceUserId)], sourceUserId) && ret; + ret = SetValue(node[GET_NAME(targetUserIds)], targetUserIds) && ret; + ret = SetValue(node[GET_NAME(appId)], appId) && ret; + return ret; +} + +bool Session::Unmarshal(const json &node) +{ + bool ret = true; + ret = GetValue(node, GET_NAME(sourceDeviceId), sourceDeviceId) && ret; + ret = GetValue(node, GET_NAME(targetDeviceId), targetDeviceId) && ret; + ret = GetValue(node, GET_NAME(sourceUserId), sourceUserId) && ret; + ret = GetValue(node, GET_NAME(targetUserIds), targetUserIds) && ret; + ret = GetValue(node, GET_NAME(appId), appId) && ret; + return ret; +} +} // namespace OHOS::DistributedData diff --git a/services/distributeddataservice/app/src/session_manager/session_manager.h b/services/distributeddataservice/app/src/session_manager/session_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..35553973825be8bb6434d8068199a2adafb2c718 --- /dev/null +++ b/services/distributeddataservice/app/src/session_manager/session_manager.h @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef DISTRIBUTEDDATAMGR_SESSIONMANAGER_H +#define DISTRIBUTEDDATAMGR_SESSIONMANAGER_H + +#include +#include + +#include "serializable/serializable.h" + +namespace OHOS::DistributedData { +struct SessionPoint { + std::string deviceId; + int userId; + std::string appId; +}; + +class Session : public Serializable { +public: + std::string sourceDeviceId; + std::string targetDeviceId; + int32_t sourceUserId; + std::vector targetUserIds; + std::string appId; + bool Marshal(json &node) const override; + bool Unmarshal(const json &node) override; + inline bool IsValid() + { + return !targetUserIds.empty(); + } +}; + +class SessionManager { +public: + static SessionManager &GetInstance(); + Session GetSession(const SessionPoint &from, const std::string &targetDeviceId) const; + bool CheckSession(const SessionPoint &from, const SessionPoint &to) const; +}; +} // namespace OHOS::DistributedData + +#endif // DISTRIBUTEDDATAMGR_SESSIONMANAGER_H diff --git a/services/distributeddataservice/app/src/session_manager/upgrade_manager.cpp b/services/distributeddataservice/app/src/session_manager/upgrade_manager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e96a6a4aa20abc59b987d0df136ea15220c19a89 --- /dev/null +++ b/services/distributeddataservice/app/src/session_manager/upgrade_manager.cpp @@ -0,0 +1,148 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#define LOG_TAG "UpgradeManager" + +#include "upgrade_manager.h" + +#include "account_delegate.h" +#include "device_kvstore_impl.h" +#include "executor_factory.h" +#include "log_print.h" +#include "utils/constant.h" + +namespace OHOS::DistributedData { +using namespace OHOS::DistributedKv; +UpgradeManager &UpgradeManager::GetInstance() +{ + static UpgradeManager instance; + return instance; +} + +void UpgradeManager::Init() +{ + OHOS::DistributedKv::KvStoreTask retryTask([this]() { + do { + if (InitLocalCapability()) { + break; + } + static constexpr int RETRY_INTERVAL = 500; // millisecond + std::this_thread::sleep_for(std::chrono::milliseconds(RETRY_INTERVAL)); + } while (true); + }); + ExecutorFactory::GetInstance().Execute(std::move(retryTask)); +} + +CapMetaData UpgradeManager::GetCapability(const std::string &deviceId, bool &status) +{ + status = true; + if (capabilityMap_.Contains(deviceId)) { + return capabilityMap_.Find(deviceId).second; + } + ZLOGI("load capability from meta"); + CapMetaData capMetaData; + auto &metaDelegate = KvStoreMetaManager::GetInstance().GetMetaKvStore(); + if (metaDelegate == nullptr) { + ZLOGE("GetMetaKvStore return nullptr."); + status = false; + return capMetaData; + } + auto dbKey = CapMetaRow::GetKeyFor(deviceId); + ZLOGD("cap key:%{public}s", std::string(dbKey.begin(), dbKey.end()).c_str()); + DistributedDB::Value dbValue; + auto ret = metaDelegate->Get(dbKey, dbValue); + if (ret != DistributedDB::DBStatus::OK) { + ZLOGE("get cap meta failed, ret:%{public}d", ret); + status = false; + return capMetaData; + } + capMetaData.Unmarshall({ dbValue.begin(), dbValue.end() }); + bool isOk = capabilityMap_.Insert(deviceId, capMetaData); + ZLOGI("device:%{public}.10s, version:%{public}d, insert:%{public}d", deviceId.c_str(), capMetaData.version, isOk); + return capMetaData; +} + +bool UpgradeManager::InitLocalCapability() +{ + auto &metaDelegate = KvStoreMetaManager::GetInstance().GetMetaKvStore(); + if (metaDelegate == nullptr) { + ZLOGE("GetMetaKvStore return nullptr."); + return false; + } + auto localDeviceId = DeviceKvStoreImpl::GetLocalDeviceId(); + CapMetaData capMetaData; + capMetaData.version = CapMetaData::CURRENT_VERSION; + auto dbKey = CapMetaRow::GetKeyFor(localDeviceId); + std::string jsonData = CapMetaData::Marshall(capMetaData); + DistributedDB::Value dbValue { jsonData.begin(), jsonData.end() }; + auto ret = metaDelegate->Put(dbKey, dbValue); + ZLOGI("put capability meta data ret %{public}d", ret); + bool isOk = capabilityMap_.Insert(localDeviceId, capMetaData); + return ret == DistributedDB::DBStatus::OK && isOk; +} + +void UpgradeManager::SetCompatibleIdentifyByType(DistributedDB::KvStoreNbDelegate *storeDelegate, + const KvStoreTuple &tuple, DistributedData::AUTH_GROUP_TYPE groupType) +{ + if (storeDelegate == nullptr) { + ZLOGE("null store delegate"); + return; + } + auto localDevice = DeviceKvStoreImpl::GetLocalDeviceId(); + auto devices = + AuthDelegate::GetInstance()->GetTrustedDevicesByType(groupType, std::stoi(tuple.userId), tuple.appId); + auto result = std::remove_if(devices.begin(), devices.end(), [&localDevice](const std::string &device) { + if (localDevice == device) { + return true; + } + bool flag = false; + auto capability = DistributedData::UpgradeManager::GetInstance().GetCapability(device, flag); + return !flag || capability.version >= DistributedData::CapMetaData::CURRENT_VERSION; + }); + devices.erase(result, devices.end()); + + bool isSuccess = false; + auto compatibleUser = UpgradeManager::GetIdentifierByType(groupType, isSuccess); + if (!isSuccess) { + ZLOGW("get identifier by type failed"); + return; + } + + auto syncIdentifier = + DistributedDB::KvStoreDelegateManager::GetKvStoreIdentifier(compatibleUser, tuple.appId, tuple.storeId); + ZLOGI("set compatible identifier, store:%{public}s, user:%{public}s, device:%{public}.10s", tuple.storeId.c_str(), + compatibleUser.c_str(), DistributedData::Serializable::Marshall(devices).c_str()); + storeDelegate->SetEqualIdentifier(syncIdentifier, devices); +} + +std::string UpgradeManager::GetIdentifierByType(int32_t groupType, bool &isSuccess) +{ + isSuccess = true; + if (groupType == PEER_TO_PEER_GROUP) { + return "default"; + } else if (groupType == IDENTICAL_ACCOUNT_GROUP) { + auto accountId = AccountDelegate::GetInstance()->GetCurrentAccountId(); + if (accountId.empty()) { + ZLOGE("failed to get current account id"); + isSuccess = false; + return {}; + } + return accountId; + } else { + ZLOGW("not supported group type:%{public}d", groupType); + isSuccess = false; + return {}; + } +} +} // namespace OHOS::DistributedData diff --git a/services/distributeddataservice/app/src/session_manager/upgrade_manager.h b/services/distributeddataservice/app/src/session_manager/upgrade_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..44c67c94a94cce80dcf3d645028501e133262c77 --- /dev/null +++ b/services/distributeddataservice/app/src/session_manager/upgrade_manager.h @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef DISTRIBUTEDDATAMGR_UPGRADE_MANAGER_H +#define DISTRIBUTEDDATAMGR_UPGRADE_MANAGER_H +#include + +#include "concurrent_map.h" +#include "kvstore_meta_manager.h" +#include "metadata/capability_meta_data.h" +#include "types.h" +namespace OHOS::DistributedData { +using DistributedDB::KvStoreNbDelegate; +using OHOS::DistributedKv::KvStoreTuple; + +class UpgradeManager { +public: + static UpgradeManager &GetInstance(); + void Init(); + CapMetaData GetCapability(const std::string &deviceId, bool &status); + static void SetCompatibleIdentifyByType( + KvStoreNbDelegate *storeDelegate, const KvStoreTuple &tuple, AUTH_GROUP_TYPE groupType); + static std::string GetIdentifierByType(int32_t groupType, bool &isSuccess); + +private: + bool InitLocalCapability(); + ConcurrentMap capabilityMap_ {}; +}; +} // namespace OHOS::DistributedData +#endif // DISTRIBUTEDDATAMGR_UPGRADE_MANAGER_H diff --git a/services/distributeddataservice/app/src/single_kvstore_impl.cpp b/services/distributeddataservice/app/src/single_kvstore_impl.cpp index 984fe07bccf7a11a3e3c48d106bcc121f1f70e32..3fd7506153f690c87d1ca01f04db33e0b6300cf9 100755 --- a/services/distributeddataservice/app/src/single_kvstore_impl.cpp +++ b/services/distributeddataservice/app/src/single_kvstore_impl.cpp @@ -23,6 +23,7 @@ #include "constant.h" #include "dds_trace.h" #include "device_kvstore_impl.h" +#include "auth/auth_delegate.h" #include "kvstore_data_service.h" #include "kvstore_utils.h" #include "ipc_skeleton.h" @@ -30,6 +31,7 @@ #include "permission_validator.h" #include "query_helper.h" #include "reporter.h" +#include "upgrade_manager.h" namespace OHOS::DistributedKv { using namespace OHOS::DistributedData; @@ -1601,7 +1603,7 @@ void SingleKvStoreImpl::OnDump(int fd) const dprintf(fd, "%s backup : %d\n", prefix.c_str(), static_cast(options_.backup)); dprintf(fd, "%s encrypt : %d\n", prefix.c_str(), static_cast(options_.encrypt)); dprintf(fd, "%s autoSync : %d\n", prefix.c_str(), static_cast(options_.autoSync)); - dprintf(fd, "%s persistant : %d\n", prefix.c_str(), static_cast(options_.persistant)); + dprintf(fd, "%s persistent : %d\n", prefix.c_str(), static_cast(options_.persistent)); dprintf(fd, "%s kvStoreType : %d\n", prefix.c_str(), static_cast(options_.kvStoreType)); dprintf(fd, "%s createIfMissing : %d\n", prefix.c_str(), static_cast(options_.createIfMissing)); dprintf(fd, "%s schema : %s\n", prefix.c_str(), options_.schema.c_str()); @@ -1610,4 +1612,36 @@ std::string SingleKvStoreImpl::GetStoreId() { return storeId_; } + +void SingleKvStoreImpl::SetCompatibleIdentify(const std::string &changedDevice) +{ + bool flag = false; + auto capability = UpgradeManager::GetInstance().GetCapability(changedDevice, flag); + if (!flag || capability.version >= CapMetaData::CURRENT_VERSION) { + ZLOGE("get peer capability %{public}d, or not older version", flag); + return; + } + + auto peerUserId = 0; // peer user id reversed here + auto groupType = + AuthDelegate::GetInstance()->GetGroupType(std::stoi(deviceAccountId_), peerUserId, changedDevice, appId_); + flag = false; + std::string compatibleUserId = UpgradeManager::GetIdentifierByType(groupType, flag); + if (!flag) { + ZLOGE("failed to get identifier by group type %{public}d", groupType); + return; + } + // older version use bound account syncIdentifier instead of user syncIdentifier + ZLOGI("compatible user:%{public}s", compatibleUserId.c_str()); + auto syncIdentifier = + DistributedDB::KvStoreDelegateManager::GetKvStoreIdentifier(compatibleUserId, appId_, storeId_); + kvStoreNbDelegate_->SetEqualIdentifier(syncIdentifier, { changedDevice }); +} + +void SingleKvStoreImpl::SetCompatibleIdentify() +{ + KvStoreTuple tuple = { deviceAccountId_, appId_, storeId_ }; + UpgradeManager::SetCompatibleIdentifyByType(kvStoreNbDelegate_, tuple, IDENTICAL_ACCOUNT_GROUP); + UpgradeManager::SetCompatibleIdentifyByType(kvStoreNbDelegate_, tuple, PEER_TO_PEER_GROUP); +} } // namespace OHOS::DistributedKv diff --git a/services/distributeddataservice/app/src/single_kvstore_impl.h b/services/distributeddataservice/app/src/single_kvstore_impl.h index e1c2d5179572a71a1bbf0d238842924f222df14e..76787224802d23fbfd21114cf69c91bc23a301c8 100755 --- a/services/distributeddataservice/app/src/single_kvstore_impl.h +++ b/services/distributeddataservice/app/src/single_kvstore_impl.h @@ -20,6 +20,8 @@ #include #include #include + +#include "auth/auth_delegate.h" #include "flowctrl_manager/kvstore_flowctrl_manager.h" #include "ikvstore_observer.h" #include "ikvstore_single.h" @@ -77,6 +79,8 @@ public: Status GetSecurityLevel(SecurityLevel &securityLevel) override; bool Import(const std::string &bundleName) const; void OnDump(int fd) const; + void SetCompatibleIdentify(const std::string &changedDevice); + void SetCompatibleIdentify(); protected: virtual KvStoreObserverImpl *CreateObserver(const SubscribeType subscribeType, sptr observer); diff --git a/services/distributeddataservice/app/src/uninstaller/BUILD.gn b/services/distributeddataservice/app/src/uninstaller/BUILD.gn index 86458e3888bd05bc0bdf85aa18dc2ae8bb2aee38..a73e9cdf96d28da2bc7b63e970030a7138f90553 100755 --- a/services/distributeddataservice/app/src/uninstaller/BUILD.gn +++ b/services/distributeddataservice/app/src/uninstaller/BUILD.gn @@ -25,6 +25,7 @@ ohos_static_library("distributeddata_uninstaller_static") { "//foundation/distributeddatamgr/distributeddatamgr/frameworks/innerkitsimpl/distributeddatafwk/include", "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata/include", "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/app_distributeddata/include", + "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/framework/include", "//third_party/json/single_include", "//utils/native/base/include", "//base/security/huks/interfaces/innerkits/huks_standard/main/include", @@ -34,6 +35,7 @@ ohos_static_library("distributeddata_uninstaller_static") { deps = [ "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter:distributeddata_adapter", + "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/framework:distributeddatasvcfwk", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/libs/distributeddb:distributeddb", "//utils/native/base:utils", ] @@ -50,4 +52,6 @@ ohos_static_library("distributeddata_uninstaller_static") { "safwk:system_ability_fwk", "samgr_standard:samgr_proxy", ] + subsystem_name = "distributeddatamgr" + part_name = "distributeddatamgr" } diff --git a/services/distributeddataservice/app/test/BUILD.gn b/services/distributeddataservice/app/test/BUILD.gn old mode 100755 new mode 100644 index c9dfe3160cf12623d86320d086edd2f10e1cc84c..58b52c113d646bcb5e2e06ee3629cddb0ed32bcc --- a/services/distributeddataservice/app/test/BUILD.gn +++ b/services/distributeddataservice/app/test/BUILD.gn @@ -11,6 +11,8 @@ # See the License for the specific language governing permissions and # limitations under the License. import("//build/test.gni") +import( + "//foundation/distributeddatamgr/distributeddatamgr/distributeddatamgr.gni") module_output_path = "distributeddatamgr/distributeddataservice" @@ -31,6 +33,8 @@ config("module_private_config") { "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/service/bootstrap/include", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/service/config/include", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/service/directory/include", + "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/app/src/session_manager", + "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/service/kv", "//foundation/distributeddatamgr/distributedfile/interfaces/kits/js/src/mod_securitylabel", "//utils/native/base/include", "//utils/system/safwk/native/include", @@ -42,8 +46,12 @@ config("module_private_config") { "../src/flowctrl_manager", "../../../../interfaces/innerkits/distributeddata", "//third_party/json/single_include", - "//base/powermgr/power_manager/interfaces/innerkits/native/include", ] + + if (distributeddatamgr_power) { + include_dirs += + [ "//base/powermgr/power_manager/interfaces/innerkits/native/include" ] + } } ohos_unittest("KvStoreImplLogicalIsolationTest") { @@ -54,10 +62,12 @@ ohos_unittest("KvStoreImplLogicalIsolationTest") { "../src/device_kvstore_impl.cpp", "../src/device_kvstore_observer_impl.cpp", "../src/device_kvstore_resultset_impl.cpp", + "../src/executor_factory.cpp", "../src/kvstore_account_observer.cpp", "../src/kvstore_app_accessor.cpp", "../src/kvstore_app_manager.cpp", "../src/kvstore_data_service.cpp", + "../src/kvstore_device_listener.cpp", "../src/kvstore_impl.cpp", "../src/kvstore_meta_manager.cpp", "../src/kvstore_observer_impl.cpp", @@ -68,6 +78,9 @@ ohos_unittest("KvStoreImplLogicalIsolationTest") { "../src/query_helper.cpp", "../src/security/security.cpp", "../src/security/sensitive.cpp", + "../src/session_manager/route_head_handler_impl.cpp", + "../src/session_manager/session_manager.cpp", + "../src/session_manager/upgrade_manager.cpp", "../src/single_kvstore_impl.cpp", "unittest/kvstore_impl_logical_isolation_test.cpp", ] @@ -75,21 +88,31 @@ ohos_unittest("KvStoreImplLogicalIsolationTest") { configs = [ ":module_private_config" ] external_deps = [ - "battery_manager_native:batterysrv_client", "dataclassification:data_transit_mgr", "hiviewdfx_hilog_native:libhilog", "huks:libhukssdk", "ipc:ipc_core", + "os_account_standard:os_account_innerkits", "permission_standard:libpermissionsdk_standard", - "power_manager_native:powermgr_client", "safwk:system_ability_fwk", "samgr_standard:samgr_proxy", ] + if (distributeddatamgr_power) { + external_deps += [ + "battery_manager_native:batterysrv_client", + "power_manager_native:powermgr_client", + ] + } + + kv_sources = [ "../../service/kv/user_delegate.cpp" ] + + sources += kv_sources deps = [ "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata:distributeddata_inner", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter:distributeddata_adapter", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/account:distributeddata_account_static", + "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/auth:distributeddata_auth_static", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/broadcaster:distributeddata_broadcaster_static", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/permission:distributeddata_permission_static", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/utils:distributeddata_utils_static", @@ -112,10 +135,12 @@ ohos_unittest("KvStoreImplPhysicalIsolationTest") { "../src/device_kvstore_impl.cpp", "../src/device_kvstore_observer_impl.cpp", "../src/device_kvstore_resultset_impl.cpp", + "../src/executor_factory.cpp", "../src/kvstore_account_observer.cpp", "../src/kvstore_app_accessor.cpp", "../src/kvstore_app_manager.cpp", "../src/kvstore_data_service.cpp", + "../src/kvstore_device_listener.cpp", "../src/kvstore_impl.cpp", "../src/kvstore_meta_manager.cpp", "../src/kvstore_observer_impl.cpp", @@ -126,28 +151,41 @@ ohos_unittest("KvStoreImplPhysicalIsolationTest") { "../src/query_helper.cpp", "../src/security/security.cpp", "../src/security/sensitive.cpp", + "../src/session_manager/route_head_handler_impl.cpp", + "../src/session_manager/session_manager.cpp", + "../src/session_manager/upgrade_manager.cpp", "../src/single_kvstore_impl.cpp", "unittest/kvstore_impl_physical_isolation_test.cpp", ] + kv_sources = [ "../../service/kv/user_delegate.cpp" ] + + sources += kv_sources configs = [ ":module_private_config" ] external_deps = [ - "battery_manager_native:batterysrv_client", "dataclassification:data_transit_mgr", "hiviewdfx_hilog_native:libhilog", "huks:libhukssdk", "ipc:ipc_core", + "os_account_standard:os_account_innerkits", "permission_standard:libpermissionsdk_standard", - "power_manager_native:powermgr_client", "safwk:system_ability_fwk", "samgr_standard:samgr_proxy", ] + if (distributeddatamgr_power) { + external_deps += [ + "battery_manager_native:batterysrv_client", + "power_manager_native:powermgr_client", + ] + } + deps = [ "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata:distributeddata_inner", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter:distributeddata_adapter", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/account:distributeddata_account_static", + "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/auth:distributeddata_auth_static", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/broadcaster:distributeddata_broadcaster_static", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/permission:distributeddata_permission_static", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/utils:distributeddata_utils_static", @@ -170,10 +208,12 @@ ohos_unittest("KvStoreDataServiceTest") { "../src/device_kvstore_impl.cpp", "../src/device_kvstore_observer_impl.cpp", "../src/device_kvstore_resultset_impl.cpp", + "../src/executor_factory.cpp", "../src/kvstore_account_observer.cpp", "../src/kvstore_app_accessor.cpp", "../src/kvstore_app_manager.cpp", "../src/kvstore_data_service.cpp", + "../src/kvstore_device_listener.cpp", "../src/kvstore_impl.cpp", "../src/kvstore_meta_manager.cpp", "../src/kvstore_observer_impl.cpp", @@ -184,28 +224,40 @@ ohos_unittest("KvStoreDataServiceTest") { "../src/query_helper.cpp", "../src/security/security.cpp", "../src/security/sensitive.cpp", + "../src/session_manager/route_head_handler_impl.cpp", + "../src/session_manager/session_manager.cpp", + "../src/session_manager/upgrade_manager.cpp", "../src/single_kvstore_impl.cpp", "unittest/kvstore_data_service_test.cpp", ] + kv_sources = [ "../../service/kv/user_delegate.cpp" ] + sources += kv_sources configs = [ ":module_private_config" ] external_deps = [ - "battery_manager_native:batterysrv_client", "dataclassification:data_transit_mgr", "hiviewdfx_hilog_native:libhilog", "huks:libhukssdk", "ipc:ipc_core", + "os_account_standard:os_account_innerkits", "permission_standard:libpermissionsdk_standard", - "power_manager_native:powermgr_client", "safwk:system_ability_fwk", "samgr_standard:samgr_proxy", ] + if (distributeddatamgr_power) { + external_deps += [ + "battery_manager_native:batterysrv_client", + "power_manager_native:powermgr_client", + ] + } + deps = [ "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata:distributeddata_inner", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter:distributeddata_adapter", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/account:distributeddata_account_static", + "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/auth:distributeddata_auth_static", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/broadcaster:distributeddata_broadcaster_static", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/permission:distributeddata_permission_static", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/utils:distributeddata_utils_static", @@ -228,10 +280,12 @@ ohos_unittest("KvStoreBackupTest") { "../src/device_kvstore_impl.cpp", "../src/device_kvstore_observer_impl.cpp", "../src/device_kvstore_resultset_impl.cpp", + "../src/executor_factory.cpp", "../src/kvstore_account_observer.cpp", "../src/kvstore_app_accessor.cpp", "../src/kvstore_app_manager.cpp", "../src/kvstore_data_service.cpp", + "../src/kvstore_device_listener.cpp", "../src/kvstore_impl.cpp", "../src/kvstore_meta_manager.cpp", "../src/kvstore_observer_impl.cpp", @@ -242,29 +296,41 @@ ohos_unittest("KvStoreBackupTest") { "../src/query_helper.cpp", "../src/security/security.cpp", "../src/security/sensitive.cpp", + "../src/session_manager/route_head_handler_impl.cpp", + "../src/session_manager/session_manager.cpp", + "../src/session_manager/upgrade_manager.cpp", "../src/single_kvstore_impl.cpp", "unittest/kvstore_backup_test.cpp", ] + kv_sources = [ "../../service/kv/user_delegate.cpp" ] + sources += kv_sources cflags_cc = [ "-DUT_TEST" ] configs = [ ":module_private_config" ] external_deps = [ - "battery_manager_native:batterysrv_client", "dataclassification:data_transit_mgr", "hiviewdfx_hilog_native:libhilog", "huks:libhukssdk", "ipc:ipc_core", + "os_account_standard:os_account_innerkits", "permission_standard:libpermissionsdk_standard", - "power_manager_native:powermgr_client", "safwk:system_ability_fwk", "samgr_standard:samgr_proxy", ] + if (distributeddatamgr_power) { + external_deps += [ + "battery_manager_native:batterysrv_client", + "power_manager_native:powermgr_client", + ] + } + deps = [ "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata:distributeddata_inner", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter:distributeddata_adapter", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/account:distributeddata_account_static", + "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/auth:distributeddata_auth_static", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/broadcaster:distributeddata_broadcaster_static", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/permission:distributeddata_permission_static", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/utils:distributeddata_utils_static", @@ -288,17 +354,23 @@ ohos_unittest("KvStoreFlowCtrlManagerTest") { configs = [ ":module_private_config" ] external_deps = [ - "battery_manager_native:batterysrv_client", "dataclassification:data_transit_mgr", "hiviewdfx_hilog_native:libhilog", "huks:libhukssdk", "ipc:ipc_core", + "os_account_standard:os_account_innerkits", "permission_standard:libpermissionsdk_standard", - "power_manager_native:powermgr_client", "safwk:system_ability_fwk", "samgr_standard:samgr_proxy", ] + if (distributeddatamgr_power) { + external_deps += [ + "battery_manager_native:batterysrv_client", + "power_manager_native:powermgr_client", + ] + } + deps = [ "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata:distributeddata_inner", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter:distributeddata_adapter", @@ -319,10 +391,12 @@ ohos_unittest("KvStoreSyncManagerTest") { "../src/device_kvstore_impl.cpp", "../src/device_kvstore_observer_impl.cpp", "../src/device_kvstore_resultset_impl.cpp", + "../src/executor_factory.cpp", "../src/kvstore_account_observer.cpp", "../src/kvstore_app_accessor.cpp", "../src/kvstore_app_manager.cpp", "../src/kvstore_data_service.cpp", + "../src/kvstore_device_listener.cpp", "../src/kvstore_impl.cpp", "../src/kvstore_meta_manager.cpp", "../src/kvstore_observer_impl.cpp", @@ -333,27 +407,39 @@ ohos_unittest("KvStoreSyncManagerTest") { "../src/query_helper.cpp", "../src/security/security.cpp", "../src/security/sensitive.cpp", + "../src/session_manager/route_head_handler_impl.cpp", + "../src/session_manager/session_manager.cpp", + "../src/session_manager/upgrade_manager.cpp", "../src/single_kvstore_impl.cpp", ] + kv_sources = [ "../../service/kv/user_delegate.cpp" ] + sources += kv_sources configs = [ ":module_private_config" ] external_deps = [ - "battery_manager_native:batterysrv_client", "dataclassification:data_transit_mgr", "hiviewdfx_hilog_native:libhilog", "huks:libhukssdk", "ipc:ipc_core", + "os_account_standard:os_account_innerkits", "permission_standard:libpermissionsdk_standard", - "power_manager_native:powermgr_client", "safwk:system_ability_fwk", "samgr_standard:samgr_proxy", ] + if (distributeddatamgr_power) { + external_deps += [ + "battery_manager_native:batterysrv_client", + "power_manager_native:powermgr_client", + ] + } + deps = [ "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata:distributeddata_inner", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter:distributeddata_adapter", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/account:distributeddata_account_static", + "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/auth:distributeddata_auth_static", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/broadcaster:distributeddata_broadcaster_static", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/permission:distributeddata_permission_static", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/utils:distributeddata_utils_static", @@ -376,10 +462,12 @@ ohos_unittest("KvStoreUninstallerTest") { "../src/device_kvstore_impl.cpp", "../src/device_kvstore_observer_impl.cpp", "../src/device_kvstore_resultset_impl.cpp", + "../src/executor_factory.cpp", "../src/kvstore_account_observer.cpp", "../src/kvstore_app_accessor.cpp", "../src/kvstore_app_manager.cpp", "../src/kvstore_data_service.cpp", + "../src/kvstore_device_listener.cpp", "../src/kvstore_impl.cpp", "../src/kvstore_meta_manager.cpp", "../src/kvstore_observer_impl.cpp", @@ -390,16 +478,22 @@ ohos_unittest("KvStoreUninstallerTest") { "../src/query_helper.cpp", "../src/security/security.cpp", "../src/security/sensitive.cpp", + "../src/session_manager/route_head_handler_impl.cpp", + "../src/session_manager/session_manager.cpp", + "../src/session_manager/upgrade_manager.cpp", "../src/single_kvstore_impl.cpp", "unittest/uninstaller_test.cpp", ] + kv_sources = [ "../../service/kv/user_delegate.cpp" ] + sources += kv_sources configs = [ ":module_private_config" ] deps = [ "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata:distributeddata_inner", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter:distributeddata_adapter", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/account:distributeddata_account_static", + "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/auth:distributeddata_auth_static", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/broadcaster:distributeddata_broadcaster_static", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/permission:distributeddata_permission_static", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/utils:distributeddata_utils_static", @@ -414,17 +508,23 @@ ohos_unittest("KvStoreUninstallerTest") { external_deps = [ "ability_base:base", - "ability_runtime:intent", - "battery_manager_native:batterysrv_client", + "ability_base:want", "dataclassification:data_transit_mgr", "hiviewdfx_hilog_native:libhilog", "huks:libhukssdk", "ipc:ipc_core", + "os_account_standard:os_account_innerkits", "permission_standard:libpermissionsdk_standard", - "power_manager_native:powermgr_client", "safwk:system_ability_fwk", "samgr_standard:samgr_proxy", ] + + if (distributeddatamgr_power) { + external_deps += [ + "battery_manager_native:batterysrv_client", + "power_manager_native:powermgr_client", + ] + } } ############################################################################### diff --git a/services/distributeddataservice/app/test/moduletest/distributeddata_account_event_test.cpp b/services/distributeddataservice/app/test/moduletest/distributeddata_account_event_test.cpp index ef9bf94be7bef9ce8161b3bc3ac9c73798d53818..2009d3cd4d5e2e71a5b482e6bf633ee2ae75493e 100644 --- a/services/distributeddataservice/app/test/moduletest/distributeddata_account_event_test.cpp +++ b/services/distributeddataservice/app/test/moduletest/distributeddata_account_event_test.cpp @@ -32,7 +32,7 @@ #include "common_event_subscriber.h" #include "common_event_support.h" #include "common_event_manager.h" -#include "ohos/aafwk/content/intent.h" +#include "ohos/aafwk/content/want.h" #include "ohos_account_kits.h" #include "gtest/gtest.h" using namespace testing::ext; diff --git a/services/distributeddataservice/app/test/unittest/kvstore_backup_test.cpp b/services/distributeddataservice/app/test/unittest/kvstore_backup_test.cpp index 89b2aa042f0da06640c4f7e90326d6b9e0919b68..bdb97cf7ba9902481403f1b1fccb780ec56efc2d 100755 --- a/services/distributeddataservice/app/test/unittest/kvstore_backup_test.cpp +++ b/services/distributeddataservice/app/test/unittest/kvstore_backup_test.cpp @@ -119,7 +119,7 @@ HWTEST_F(KvStoreBackupTest, KvStoreBackupTest002, TestSize.Level1) auto trueAppId = CheckerManager::GetInstance().GetAppId(appId.appId, 1000); auto backupHandler = std::make_unique(); - MetaData metaData{0}; + MetaData metaData; metaData.kvStoreMetaData.deviceAccountId = "0"; metaData.kvStoreMetaData.userId = AccountDelegate::GetInstance()->GetCurrentAccountId(); metaData.kvStoreMetaData.appId = trueAppId; @@ -172,7 +172,7 @@ HWTEST_F(KvStoreBackupTest, KvStoreBackupTest003, TestSize.Level1) auto trueAppId = CheckerManager::GetInstance().GetAppId(appId.appId, 1000); auto backupHandler = std::make_unique(); - MetaData metaData{0}; + MetaData metaData; metaData.kvStoreMetaData.deviceAccountId = "0"; metaData.kvStoreMetaData.userId = AccountDelegate::GetInstance()->GetCurrentAccountId(); metaData.kvStoreMetaData.appId = trueAppId; @@ -234,7 +234,7 @@ HWTEST_F(KvStoreBackupTest, KvStoreBackupTest004, TestSize.Level1) auto trueAppId = CheckerManager::GetInstance().GetAppId(appId.appId, 1000); auto backupHandler = std::make_unique(); - MetaData metaData{0}; + MetaData metaData; metaData.kvStoreMetaData.deviceAccountId = "0"; metaData.kvStoreMetaData.userId = AccountDelegate::GetInstance()->GetCurrentAccountId(); metaData.kvStoreMetaData.appId = trueAppId; @@ -291,7 +291,7 @@ HWTEST_F(KvStoreBackupTest, KvStoreBackupTest005, TestSize.Level1) auto trueAppId = CheckerManager::GetInstance().GetAppId(appId.appId, 1000); auto backupHandler = std::make_unique(); - MetaData metaData{0}; + MetaData metaData; metaData.kvStoreMetaData.deviceAccountId = "0"; metaData.kvStoreMetaData.userId = AccountDelegate::GetInstance()->GetCurrentAccountId(); metaData.kvStoreMetaData.appId = trueAppId; @@ -344,7 +344,7 @@ HWTEST_F(KvStoreBackupTest, KvStoreBackupTest006, TestSize.Level1) auto trueAppId = CheckerManager::GetInstance().GetAppId(appId.appId, 1000); auto backupHandler = std::make_unique(); - MetaData metaData{0}; + MetaData metaData; metaData.kvStoreMetaData.deviceAccountId = "0"; metaData.kvStoreMetaData.userId = AccountDelegate::GetInstance()->GetCurrentAccountId(); metaData.kvStoreMetaData.appId = trueAppId; @@ -397,7 +397,7 @@ HWTEST_F(KvStoreBackupTest, KvStoreBackupTest007, TestSize.Level1) auto trueAppId = CheckerManager::GetInstance().GetAppId(appId.appId, 1000); auto backupHandler = std::make_unique(); - MetaData metaData{0}; + MetaData metaData; metaData.kvStoreMetaData.deviceAccountId = "0"; metaData.kvStoreMetaData.userId = AccountDelegate::GetInstance()->GetCurrentAccountId(); metaData.kvStoreMetaData.appId = trueAppId; diff --git a/services/distributeddataservice/app/test/unittest/session_manager/session_manager_test.cpp b/services/distributeddataservice/app/test/unittest/session_manager/session_manager_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..17c39f31a83225817645602ff7ee2a1508786083 --- /dev/null +++ b/services/distributeddataservice/app/test/unittest/session_manager/session_manager_test.cpp @@ -0,0 +1,79 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#include "gmock/gmock.h" +#include "route_head_handler_impl.h" +#include "upgrade_manager.h" +#include "user_delegate.h" + +namespace OHOS::DistributedData { +using namespace testing::ext; +class SessionManagerTest : public testing::Test { +public: + static void SetUpTestCase() + { + // init peer device + UserMetaData userMetaData; + userMetaData.deviceId = "PEER_DEVICE_ID"; + + UserStatus status; + status.isActive = true; + constexpr const int MOCK_PEER_USER = 101; + status.id = MOCK_PEER_USER; + userMetaData.users = { status }; + + CapMetaData capMetaData; + capMetaData.version = CapMetaData::CURRENT_VERSION; + UpgradeManager::GetInstance().Init(); + } + static void TearDownTestCase() + { + } + void SetUp() + { + } + void TearDown() + { + } +}; + +/** +* @tc.name: PackAndUnPack01 +* @tc.desc: test get db dir +* @tc.type: FUNC +* @tc.require: +* @tc.author: illybyy +*/ +HWTEST_F(SessionManagerTest, PackAndUnPack01, TestSize.Level0) +{ + const DistributedDB::ExtendInfo info = { + .userId = "100", .appId = "com.sample.helloworld", .storeId = "test_store", .deviceId = "PEER_DEVICE_ID" + }; + auto sendHandler = RouteHeadHandlerImpl::Create(info); + ASSERT_NE(sendHandler, nullptr); + auto size = sendHandler->GetHeadDataSize(); + ASSERT_GT(size, 0); + std::unique_ptr data = std::make_unique(size); + sendHandler->FillHeadData(data.get(), size, size); + + std::vector users; + auto recvHandler = RouteHeadHandlerImpl::Create({}); + recvHandler->ParseHeadData(data.get(), size, size, users); + EXPECT_EQ(users.size(), 1); + EXPECT_EQ(users[0], "101"); +} +} // namespace OHOS::DistributedData \ No newline at end of file diff --git a/services/distributeddataservice/framework/BUILD.gn b/services/distributeddataservice/framework/BUILD.gn index 2c2032bdfcd44e7c431b3ebd520914e9c1bfc43a..fcffaf669e9f7d74e8d4467be99c078081c8483d 100644 --- a/services/distributeddataservice/framework/BUILD.gn +++ b/services/distributeddataservice/framework/BUILD.gn @@ -23,6 +23,7 @@ config("module_public_config") { "//third_party/json/single_include", "//third_party/openssl/include/", "//foundation/distributeddatamgr/distributeddatamgr/frameworks/common", + "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata/include", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/include", ] } @@ -34,9 +35,12 @@ ohos_shared_library("distributeddatasvcfwk") { "checker/default/system_checker.cpp", "eventcenter/event.cpp", "eventcenter/event_center.cpp", + "metadata/capability_meta_data.cpp", "metadata/meta_data.cpp", "metadata/secret_key_meta_data.cpp", "metadata/store_meta_data.cpp", + "metadata/strategy_meta_data.cpp", + "metadata/user_meta_data.cpp", "serializable/serializable.cpp", "utils/anonymous.cpp", "utils/block_integer.cpp", @@ -58,7 +62,6 @@ ohos_shared_library("distributeddatasvcfwk") { external_deps = [ "ability_base:base", "ability_base:want", - "ability_runtime:intent", "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", "hiviewdfx_hilog_native:libhilog", diff --git a/services/distributeddataservice/framework/include/metadata/capability_meta_data.h b/services/distributeddataservice/framework/include/metadata/capability_meta_data.h new file mode 100644 index 0000000000000000000000000000000000000000..f2dadaf3c558b8c94ca65aa6aee8d72c918ee926 --- /dev/null +++ b/services/distributeddataservice/framework/include/metadata/capability_meta_data.h @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef DISTRIBUTEDDATAMGR_CAPABILITY_META_DATA_H +#define DISTRIBUTEDDATAMGR_CAPABILITY_META_DATA_H +#include "serializable/serializable.h" + +namespace OHOS::DistributedData { +class API_EXPORT CapMetaData final : public Serializable { +public: + const static int32_t CURRENT_VERSION = 1; + const static int32_t INVALID_VERSION = -1; + int32_t version = INVALID_VERSION; + + API_EXPORT bool Marshal(json &node) const override; + API_EXPORT bool Unmarshal(const json &node) override; +}; + +class CapMetaRow { +public: + static const std::string KEY_PREFIX; + API_EXPORT static std::vector GetKeyFor(const std::string &key); +}; +} // namespace OHOS::DistributedData +#endif // DISTRIBUTEDDATAMGR_CAPABILITY_META_DATA_H diff --git a/services/distributeddataservice/framework/include/metadata/secret_key_meta_data.h b/services/distributeddataservice/framework/include/metadata/secret_key_meta_data.h index 2b93aa5fa028ed336b6431e9e4981a17b997cd88..768c2ce6a0832b8cae42b831e55ee903842c34e3 100644 --- a/services/distributeddataservice/framework/include/metadata/secret_key_meta_data.h +++ b/services/distributeddataservice/framework/include/metadata/secret_key_meta_data.h @@ -22,9 +22,10 @@ struct SecretKeyMetaData final : public Serializable { std::vector time {}; std::vector sKey {}; int32_t kvStoreType = 0; - ~SecretKeyMetaData(); - bool Marshal(json &node) const override; - bool Unmarshal(const json &node) override; + API_EXPORT SecretKeyMetaData(); + API_EXPORT ~SecretKeyMetaData(); + API_EXPORT bool Marshal(json &node) const override; + API_EXPORT bool Unmarshal(const json &node) override; }; } } diff --git a/services/distributeddataservice/framework/include/metadata/store_meta_data.h b/services/distributeddataservice/framework/include/metadata/store_meta_data.h index 2000d6c93e07d40f57fc4573cd9a7f778465e212..c216bbde8ea25ce9fa3a3f5a9a71e856ae258a81 100644 --- a/services/distributeddataservice/framework/include/metadata/store_meta_data.h +++ b/services/distributeddataservice/framework/include/metadata/store_meta_data.h @@ -14,10 +14,16 @@ */ #ifndef OHOS_DISTRIBUTED_DATA_SERVICES_FRAMEWORK_METADATA_STORE_META_DATA_H #define OHOS_DISTRIBUTED_DATA_SERVICES_FRAMEWORK_METADATA_STORE_META_DATA_H + +#include + #include "serializable/serializable.h" -namespace OHOS { -namespace DistributedData { + +namespace OHOS::DistributedData { struct StoreMetaData final : public Serializable { + // record kvstore meta version for compatible, should update when modify kvstore meta structure. + static constexpr uint32_t META_VERSION_SUPPORT_MULTIUSER = 0x03000002; + static constexpr uint32_t META_VERSION_SUPPORT_MULTIUSER_HOS = 0x03000001; bool isAutoSync = false; bool isBackup = false; bool isDirty = false; @@ -29,16 +35,31 @@ struct StoreMetaData final : public Serializable { std::string appType = ""; std::string bundleName = ""; std::string dataDir = ""; - std::string deviceAccountId = ""; // todo change to userId + std::string deviceAccountId = ""; std::string deviceId = ""; std::string schema = ""; std::string storeId = ""; std::string userId = ""; - uint32_t version = 0; + uint32_t version = META_VERSION_SUPPORT_MULTIUSER; + + API_EXPORT ~StoreMetaData(); + API_EXPORT StoreMetaData(); + API_EXPORT StoreMetaData(const std::string &appId, const std::string &storeId, const std::string &userId); + API_EXPORT bool Marshal(json &node) const override; + API_EXPORT bool Unmarshal(const json &node) override; +}; +class KvStoreMetaRow { +public: + KVSTORE_API static const std::string KEY_PREFIX; + + KVSTORE_API static std::vector GetKeyFor(const std::string &key); +}; + +class SecretMetaRow { +public: + KVSTORE_API static const std::string KEY_PREFIX; - bool Marshal(json &node) const override; - bool Unmarshal(const json &node) override; + KVSTORE_API static std::vector GetKeyFor(const std::string &key); }; -} -} +} // namespace OHOS::DistributedData #endif // OHOS_DISTRIBUTED_DATA_SERVICES_FRAMEWORK_METADATA_STORE_META_DATA_H diff --git a/services/distributeddataservice/framework/include/metadata/strategy_meta_data.h b/services/distributeddataservice/framework/include/metadata/strategy_meta_data.h new file mode 100644 index 0000000000000000000000000000000000000000..437c7ef2c76dc7d998e647dd765f0c7b177f9760 --- /dev/null +++ b/services/distributeddataservice/framework/include/metadata/strategy_meta_data.h @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef DISTRIBUTEDDATAMGR_STRATEGY_META_DATA_H +#define DISTRIBUTEDDATAMGR_STRATEGY_META_DATA_H +#include "serializable/serializable.h" +namespace OHOS::DistributedData { +struct StrategyMeta final : public Serializable { + std::string devId; + std::string devAccId; + std::string grpId; + std::string bundleName; + std::string storeId; + + API_EXPORT StrategyMeta(const std::string &devId, const std::string &devAccId, const std::string &grpId, + const std::string &bundleName, const std::string &storeId); + API_EXPORT ~StrategyMeta() {}; + API_EXPORT bool Marshal(json &node) const override; + API_EXPORT bool Unmarshal(const json &node) override; +}; +} // namespace OHOS::DistributedData +#endif // DISTRIBUTEDDATAMGR_STRATEGY_META_DATA_H diff --git a/services/distributeddataservice/framework/include/metadata/user_meta_data.h b/services/distributeddataservice/framework/include/metadata/user_meta_data.h new file mode 100644 index 0000000000000000000000000000000000000000..7ed2b61a2568ee2bcd9f076d85988bbcd42c7977 --- /dev/null +++ b/services/distributeddataservice/framework/include/metadata/user_meta_data.h @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef DISTRIBUTEDDATAMGR_USER_META_DATA_H +#define DISTRIBUTEDDATAMGR_USER_META_DATA_H +#include +#include + +#include "serializable/serializable.h" +namespace OHOS::DistributedData { +class API_EXPORT UserStatus final : public Serializable { +public: + int id; + bool isActive; + API_EXPORT UserStatus() = default; + API_EXPORT ~UserStatus() = default; + API_EXPORT UserStatus(int id, bool isActive); + API_EXPORT bool Marshal(json &node) const override; + API_EXPORT bool Unmarshal(const json &node) override; +}; + +class API_EXPORT UserMetaData final : public Serializable { +public: + std::string deviceId; + std::vector users; + + API_EXPORT bool Marshal(json &node) const override; + API_EXPORT bool Unmarshal(const json &node) override; +}; + +class UserMetaRow { +public: + API_EXPORT static const std::string KEY_PREFIX; + API_EXPORT static std::vector GetKeyFor(const std::string &key); +}; +} // namespace OHOS::DistributedData + +#endif // DISTRIBUTEDDATAMGR_USER_META_DATA_H diff --git a/services/distributeddataservice/framework/include/serializable/serializable.h b/services/distributeddataservice/framework/include/serializable/serializable.h index 1bd6790fc3e2283017084a665572fb68be52f96a..6387e19aadd19639cbdd28f54b3f9d83d4c8c6e0 100644 --- a/services/distributeddataservice/framework/include/serializable/serializable.h +++ b/services/distributeddataservice/framework/include/serializable/serializable.h @@ -16,6 +16,7 @@ #ifndef OHOS_DISTRIBUTED_DATA_FRAMEWORKS_COMMON_SERIALIZABLE_H #define OHOS_DISTRIBUTED_DATA_FRAMEWORKS_COMMON_SERIALIZABLE_H #include +#include #include "visibility.h" #ifndef JSON_NOEXCEPTION #define JSON_NOEXCEPTION @@ -30,8 +31,22 @@ struct Serializable { public: using json = nlohmann::json; using size_type= nlohmann::json::size_type; + using error_handler_t = nlohmann::detail::error_handler_t; API_EXPORT json Marshall() const; + template + static std::string Marshall(T &values) + { + json root; + SetValue(root, values); + return root.dump(-1, ' ', false, error_handler_t::replace); + } + API_EXPORT bool Unmarshall(const std::string &jsonStr); + template + static bool Unmarshall(const std::string &body, T &values) + { + return GetValue(ToJson(body), "", values); + } API_EXPORT static json ToJson(const std::string &jsonStr); virtual bool Marshal(json &node) const = 0; virtual bool Unmarshal(const json &node) = 0; @@ -77,7 +92,7 @@ protected: bool result = true; values.resize(subNode.size()); for (size_type i = 0; i < subNode.size(); ++i) { - result &= GetValue(subNode[i], "", values[i]); + result = GetValue(subNode[i], "", values[i]) && result; } return result; } @@ -89,7 +104,7 @@ protected: size_type i = 0; node = json::value_t::array; for (const auto &value : values) { - result &= SetValue(node[i], value); + result = SetValue(node[i], value) && result; i++; } return result; diff --git a/services/distributeddataservice/framework/metadata/capability_meta_data.cpp b/services/distributeddataservice/framework/metadata/capability_meta_data.cpp new file mode 100644 index 0000000000000000000000000000000000000000..624c0b7a9e148378cab028106f553bc13d2a7e94 --- /dev/null +++ b/services/distributeddataservice/framework/metadata/capability_meta_data.cpp @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "metadata/capability_meta_data.h" + +#include "utils/constant.h" +namespace OHOS::DistributedData { +using namespace OHOS::DistributedKv; + +bool CapMetaData::Marshal(json &node) const +{ + bool ret = true; + ret = SetValue(node[GET_NAME(version)], version) && ret; + return ret; +} + +bool CapMetaData::Unmarshal(const json &node) +{ + bool ret = true; + ret = GetValue(node, GET_NAME(version), version) && ret; + return ret; +} + +const std::string CapMetaRow::KEY_PREFIX = "CapabilityMeta"; +std::vector CapMetaRow::GetKeyFor(const std::string &key) +{ + std::string str = Constant::Concatenate({ KEY_PREFIX, Constant::KEY_SEPARATOR, key }); + return { str.begin(), str.end() }; +} +} // namespace OHOS::DistributedData \ No newline at end of file diff --git a/services/distributeddataservice/framework/metadata/secret_key_meta_data.cpp b/services/distributeddataservice/framework/metadata/secret_key_meta_data.cpp index b844394a23a43535db14c6d60c49fbf5d5945232..9ea3a7e32eb422a979eaf0e4f851b8cbc639a183 100644 --- a/services/distributeddataservice/framework/metadata/secret_key_meta_data.cpp +++ b/services/distributeddataservice/framework/metadata/secret_key_meta_data.cpp @@ -15,6 +15,9 @@ #include "metadata/secret_key_meta_data.h" namespace OHOS { namespace DistributedData { +SecretKeyMetaData::SecretKeyMetaData() +{ +} SecretKeyMetaData::~SecretKeyMetaData() { sKey.assign(sKey.size(), 0); diff --git a/services/distributeddataservice/framework/metadata/store_meta_data.cpp b/services/distributeddataservice/framework/metadata/store_meta_data.cpp index a730149dd242750ac9ff806200cb6a7d70236980..3069a3a914e1db753064caadc9eb55eca0bfa918 100644 --- a/services/distributeddataservice/framework/metadata/store_meta_data.cpp +++ b/services/distributeddataservice/framework/metadata/store_meta_data.cpp @@ -14,15 +14,18 @@ */ #include "metadata/store_meta_data.h" + +#include "utils/constant.h" namespace OHOS { namespace DistributedData { -bool StoreMetaData::Marshal(Serializable::json &node) const +using namespace OHOS::DistributedKv; +bool StoreMetaData::Marshal(json &node) const { SetValue(node[GET_NAME(appId)], appId); SetValue(node[GET_NAME(appType)], appType); SetValue(node[GET_NAME(bundleName)], bundleName); SetValue(node[GET_NAME(dataDir)], dataDir); - SetValue(node[GET_NAME(deviceAccountId)], deviceAccountId); + SetValue(node[GET_NAME(deviceAccountID)], deviceAccountId); SetValue(node[GET_NAME(deviceId)], deviceId); SetValue(node[GET_NAME(isAutoSync)], isAutoSync); SetValue(node[GET_NAME(isBackup)], isBackup); @@ -30,19 +33,20 @@ bool StoreMetaData::Marshal(Serializable::json &node) const SetValue(node[GET_NAME(kvStoreType)], kvStoreType); SetValue(node[GET_NAME(schema)], schema); SetValue(node[GET_NAME(storeId)], storeId); - SetValue(node[GET_NAME(uid)], uid); + SetValue(node[GET_NAME(UID)], uid); + SetValue(node[GET_NAME(userId)], userId); SetValue(node[GET_NAME(version)], version); SetValue(node[GET_NAME(securityLevel)], securityLevel); SetValue(node[GET_NAME(isDirty)], isDirty); return true; } -bool StoreMetaData::Unmarshal(const Serializable::json &node) +bool StoreMetaData::Unmarshal(const json &node) { GetValue(node, GET_NAME(appId), appId); GetValue(node, GET_NAME(appType), appType); GetValue(node, GET_NAME(bundleName), bundleName); GetValue(node, GET_NAME(dataDir), dataDir); - GetValue(node, GET_NAME(deviceAccountId), deviceAccountId); + GetValue(node, GET_NAME(deviceAccountID), deviceAccountId); GetValue(node, GET_NAME(deviceId), deviceId); GetValue(node, GET_NAME(isAutoSync), isAutoSync); GetValue(node, GET_NAME(isBackup), isBackup); @@ -50,11 +54,37 @@ bool StoreMetaData::Unmarshal(const Serializable::json &node) GetValue(node, GET_NAME(kvStoreType), kvStoreType); GetValue(node, GET_NAME(schema), schema); GetValue(node, GET_NAME(storeId), storeId); - GetValue(node, GET_NAME(uid), uid); + GetValue(node, GET_NAME(UID), uid); + GetValue(node, GET_NAME(userId), userId); GetValue(node, GET_NAME(version), version); GetValue(node, GET_NAME(securityLevel), securityLevel); GetValue(node, GET_NAME(isDirty), isDirty); return true; } +StoreMetaData::StoreMetaData() +{ +} +StoreMetaData::~StoreMetaData() +{ +} +StoreMetaData::StoreMetaData(const std::string &appId, const std::string &storeId, const std::string &userId) + : appId(appId), storeId(storeId), userId(userId) +{ +} + +// the Key Prefix for Meta data of KvStore. +const std::string KvStoreMetaRow::KEY_PREFIX = "KvStoreMetaData"; +std::vector KvStoreMetaRow::GetKeyFor(const std::string &key) +{ + std::string str = Constant::Concatenate({ KvStoreMetaRow::KEY_PREFIX, Constant::KEY_SEPARATOR, key }); + return { str.begin(), str.end() }; +} + +const std::string SecretMetaRow::KEY_PREFIX = "SecretKey"; +std::vector SecretMetaRow::GetKeyFor(const std::string &key) +{ + std::string str = Constant::Concatenate({ SecretMetaRow::KEY_PREFIX, Constant::KEY_SEPARATOR, key }); + return { str.begin(), str.end() }; } -} \ No newline at end of file +} // namespace DistributedData +} // namespace OHOS \ No newline at end of file diff --git a/services/distributeddataservice/framework/metadata/strategy_meta_data.cpp b/services/distributeddataservice/framework/metadata/strategy_meta_data.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2cb49d40eeb5347adb085a75aa0b108db3f186bd --- /dev/null +++ b/services/distributeddataservice/framework/metadata/strategy_meta_data.cpp @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "metadata/strategy_meta_data.h" +namespace OHOS::DistributedData { +bool StrategyMeta::Marshal(json &node) const +{ + bool ret = true; + ret = SetValue(node[GET_NAME(devId)], devId) && ret; + ret = SetValue(node[GET_NAME(devAccId)], devAccId) && ret; + ret = SetValue(node[GET_NAME(grpId)], grpId) && ret; + ret = SetValue(node[GET_NAME(bundleName)], bundleName) && ret; + ret = SetValue(node[GET_NAME(storeId)], storeId) && ret; + return ret; +} + +bool StrategyMeta::Unmarshal(const json &node) +{ + bool ret = true; + ret = GetValue(node, GET_NAME(devId), devId) && ret; + ret = GetValue(node, GET_NAME(devAccId), devAccId) && ret; + ret = GetValue(node, GET_NAME(grpId), grpId) && ret; + ret = GetValue(node, GET_NAME(bundleName), bundleName) && ret; + ret = GetValue(node, GET_NAME(storeId), storeId) && ret; + return ret; +} +StrategyMeta::StrategyMeta(const std::string &devId, const std::string &devAccId, const std::string &grpId, + const std::string &bundleName, const std::string &storeId) + : devId(devId), devAccId(devAccId), grpId(grpId), bundleName(bundleName), storeId(storeId) +{ +} +} // namespace OHOS::DistributedData \ No newline at end of file diff --git a/services/distributeddataservice/framework/metadata/user_meta_data.cpp b/services/distributeddataservice/framework/metadata/user_meta_data.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c556e99dc38695f9163bd7b257c41b9be73e6ebb --- /dev/null +++ b/services/distributeddataservice/framework/metadata/user_meta_data.cpp @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "metadata/user_meta_data.h" + +#include "utils/constant.h" + +namespace OHOS::DistributedData { +using namespace OHOS::DistributedKv; +bool UserMetaData::Marshal(json &node) const +{ + bool ret = true; + ret = SetValue(node[GET_NAME(deviceId)], deviceId) && ret; + ret = SetValue(node[GET_NAME(users)], users) && ret; + + return ret; +} + +bool UserMetaData::Unmarshal(const json &node) +{ + bool ret = true; + ret = GetValue(node, GET_NAME(deviceId), deviceId) && ret; + ret = GetValue(node, GET_NAME(users), users) && ret; + + return ret; +} + +bool UserStatus::Marshal(json &node) const +{ + bool ret = true; + ret = SetValue(node[GET_NAME(id)], id) && ret; + ret = SetValue(node[GET_NAME(isActive)], isActive) && ret; + return ret; +} + +bool UserStatus::Unmarshal(const json &node) +{ + bool ret = true; + ret = GetValue(node, GET_NAME(id), id) && ret; + ret = GetValue(node, GET_NAME(isActive), isActive) && ret; + return ret; +} +UserStatus::UserStatus(int id, bool isActive) : id(id), isActive(isActive) +{ +} + +const std::string UserMetaRow::KEY_PREFIX = "UserMeta"; +std::vector UserMetaRow::GetKeyFor(const std::string &key) +{ + std::string str = Constant::Concatenate({ KEY_PREFIX, Constant::KEY_SEPARATOR, key }); + return { str.begin(), str.end() }; +} +} // namespace OHOS::DistributedData diff --git a/services/distributeddataservice/libs/distributeddb/BUILD.gn b/services/distributeddataservice/libs/distributeddb/BUILD.gn old mode 100755 new mode 100644 index c363fd7c787f6819bbb3797fcf5cd8b6de4b3f02..ed3a74a38a910cbd78c2a25319207dd0028a1296 --- a/services/distributeddataservice/libs/distributeddb/BUILD.gn +++ b/services/distributeddataservice/libs/distributeddb/BUILD.gn @@ -93,6 +93,7 @@ ohos_shared_library("distributeddb") { "common/src/runtime_context.cpp", "common/src/runtime_context_impl.cpp", "common/src/schema_constant.cpp", + "common/src/schema_negotiate.cpp", "common/src/schema_object.cpp", "common/src/schema_utils.cpp", "common/src/semaphore_utils.cpp", diff --git a/services/distributeddataservice/libs/distributeddb/common/include/auto_launch.h b/services/distributeddataservice/libs/distributeddb/common/include/auto_launch.h old mode 100755 new mode 100644 index 9d61867b4d76b8fe414ac58691bf747102831c8e..6debcc82f8d9ad7097fe95b125c4fc36d26aaa29 --- a/services/distributeddataservice/libs/distributeddb/common/include/auto_launch.h +++ b/services/distributeddataservice/libs/distributeddb/common/include/auto_launch.h @@ -53,7 +53,7 @@ struct AutoLaunchItem { KvStoreNbConflictNotifier conflictNotifier; void *conn = nullptr; KvDBObserverHandle *observerHandle = nullptr; - bool isWriteOpenNotifiered = false; + bool isWriteOpenNotified = false; AutoLaunchItemState state = AutoLaunchItemState::UN_INITIAL; bool isDisable = false; bool inObserver = false; @@ -64,6 +64,9 @@ struct AutoLaunchItem { class AutoLaunch { public: + static int GetAutoLaunchProperties(const AutoLaunchParam ¶m, const DBType &openType, bool checkDir, + std::shared_ptr &propertiesPtr); + AutoLaunch() = default; virtual ~AutoLaunch(); @@ -82,21 +85,33 @@ public: void SetAutoLaunchRequestCallback(const AutoLaunchRequestCallback &callback, DBType type); - static int GetAutoLaunchProperties(const AutoLaunchParam ¶m, const DBType &openType, - std::shared_ptr &propertiesPtr); - protected: + static int OpenOneConnection(AutoLaunchItem &autoLaunchItem); + + // we will return errCode, if errCode != E_OK + static int CloseConnectionStrict(AutoLaunchItem &autoLaunchItem); + + static void CloseNotifier(const AutoLaunchItem &autoLaunchItem); + + static int SetConflictNotifier(AutoLaunchItem &autoLaunchItem); + + static int GetAutoLaunchKVProperties(const AutoLaunchParam ¶m, + const std::shared_ptr &propertiesPtr, bool checkDir); + + static int GetAutoLaunchRelationProperties(const AutoLaunchParam ¶m, + const std::shared_ptr &propertiesPtr); + + static int OpenKvConnection(AutoLaunchItem &autoLaunchItem); + + static int OpenRelationalConnection(AutoLaunchItem &autoLaunchItem); + + static int PragmaAutoSync(AutoLaunchItem &autoLaunchItem); int EnableKvStoreAutoLaunchParmCheck(AutoLaunchItem &autoLaunchItem, const std::string &normalIdentifier, const std::string &dualTupleIdentifier, bool isDualTupleMode); int GetKVConnectionInEnable(AutoLaunchItem &autoLaunchItem, const std::string &identifier); - static int OpenOneConnection(AutoLaunchItem &autoLaunchItem); - - // we will return errCode, if errCode != E_OK - static int CloseConnectionStrict(AutoLaunchItem &autoLaunchItem); - // before ReleaseDatabaseConnection, if errCode != E_OK, we not return, we try close more virtual void TryCloseConnection(AutoLaunchItem &autoLaunchItem); @@ -120,8 +135,6 @@ protected: void ReceiveUnknownIdentifierCallBackTask(const std::string &identifier, const std::string userId); - static void CloseNotifier(const AutoLaunchItem &autoLaunchItem); - void ConnectionLifeCycleCallback(const std::string &identifier, const std::string &userId); void OnlineCallBack(const std::string &device, bool isConnect); @@ -139,25 +152,11 @@ protected: void ExtConnectionLifeCycleCallbackTask(const std::string &identifier, const std::string &userId); - static int SetConflictNotifier(AutoLaunchItem &autoLaunchItem); - int ExtAutoLaunchRequestCallBack(const std::string &identifier, AutoLaunchParam ¶m, DBType &openType); - static int GetAutoLaunchKVProperties(const AutoLaunchParam ¶m, - const std::shared_ptr &propertiesPtr); - - static int GetAutoLaunchRelationProperties(const AutoLaunchParam ¶m, - const std::shared_ptr &propertiesPtr); - - static int OpenKvConnection(AutoLaunchItem &autoLaunchItem); - - static int OpenRelationalConnection(AutoLaunchItem &autoLaunchItem); - int RegisterLifeCycleCallback(AutoLaunchItem &autoLaunchItem, const std::string &identifier, bool isExt); - static int PragmaAutoSync(AutoLaunchItem &autoLaunchItem); - void TryCloseKvConnection(AutoLaunchItem &autoLaunchItem); void TryCloseRelationConnection(AutoLaunchItem &autoLaunchItem); diff --git a/services/distributeddataservice/libs/distributeddb/common/include/data_value.h b/services/distributeddataservice/libs/distributeddb/common/include/data_value.h index 336a6257ce6599852669b91ae5e326b371a48d46..f355f7f55c2e251a10f49246c23c4fd406632cfa 100644 --- a/services/distributeddataservice/libs/distributeddb/common/include/data_value.h +++ b/services/distributeddataservice/libs/distributeddb/common/include/data_value.h @@ -25,7 +25,6 @@ namespace DistributedDB { enum class StorageType { STORAGE_TYPE_NONE = 0, STORAGE_TYPE_NULL, - STORAGE_TYPE_BOOL, STORAGE_TYPE_INTEGER, STORAGE_TYPE_REAL, STORAGE_TYPE_TEXT, @@ -63,7 +62,6 @@ public: // move constructor DataValue(DataValue &&dataValue) noexcept; DataValue &operator=(DataValue &&dataValue) noexcept; - DataValue &operator=(bool boolVal); DataValue &operator=(int64_t intVal); DataValue &operator=(double doubleVal); DataValue &operator=(const Blob &blob); @@ -75,7 +73,6 @@ public: bool operator!=(const DataValue &dataValue) const; StorageType GetType() const; - int GetBool(bool &outVal) const; int GetInt64(int64_t &outVal) const; int GetDouble(double &outVal) const; int GetBlob(Blob *&outVal) const; @@ -92,7 +89,6 @@ private: StorageType type_ = StorageType::STORAGE_TYPE_NULL; union { void* zeroMem; - bool bValue; Blob* blobPtr; double dValue; int64_t iValue; diff --git a/services/distributeddataservice/libs/distributeddb/common/include/db_ability.h b/services/distributeddataservice/libs/distributeddb/common/include/db_ability.h index 75466cfec6779b7ec1f742e3c1469a243446e0e9..16c5abcb58d30d6768c4420a684ffc8a8b0e9290 100644 --- a/services/distributeddataservice/libs/distributeddb/common/include/db_ability.h +++ b/services/distributeddataservice/libs/distributeddb/common/include/db_ability.h @@ -45,7 +45,7 @@ public: uint32_t GetAbilityBitsLen() const; - uint8_t GetAbilityItem(const AbilityItem abilityType) const; + uint8_t GetAbilityItem(const AbilityItem &abilityType) const; int SetAbilityItem(const AbilityItem &abilityType, uint8_t data); private: diff --git a/services/distributeddataservice/libs/distributeddb/common/include/db_common.h b/services/distributeddataservice/libs/distributeddb/common/include/db_common.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/common/include/db_constant.h b/services/distributeddataservice/libs/distributeddb/common/include/db_constant.h old mode 100755 new mode 100644 index 2356e34dd53b889a769c1075f589013e4cec5bc2..a94051de65f4c06c8c2354fd00f6a60d7b492a01 --- a/services/distributeddataservice/libs/distributeddb/common/include/db_constant.h +++ b/services/distributeddataservice/libs/distributeddb/common/include/db_constant.h @@ -29,6 +29,8 @@ public: static constexpr size_t MAX_DATA_DIR_LENGTH = 512; + static constexpr size_t MAX_INKEYS_SIZE = 128; + static constexpr int DB_TYPE_LOCAL = 1; static constexpr int DB_TYPE_MULTI_VER = 2; static constexpr int DB_TYPE_SINGLE_VER = 3; diff --git a/services/distributeddataservice/libs/distributeddb/common/include/db_errno.h b/services/distributeddataservice/libs/distributeddb/common/include/db_errno.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/common/include/db_types.h b/services/distributeddataservice/libs/distributeddb/common/include/db_types.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/common/include/endian_convert.h b/services/distributeddataservice/libs/distributeddb/common/include/endian_convert.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/common/include/hash.h b/services/distributeddataservice/libs/distributeddb/common/include/hash.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/common/include/schema.h b/services/distributeddataservice/libs/distributeddb/common/include/ischema.h similarity index 84% rename from services/distributeddataservice/libs/distributeddb/common/include/schema.h rename to services/distributeddataservice/libs/distributeddb/common/include/ischema.h index dffc432ba1880bbee764011c259c03ecaa4c6bd1..f4413b25c8a98f86b96c0216239e5f372cd16217 100644 --- a/services/distributeddataservice/libs/distributeddb/common/include/schema.h +++ b/services/distributeddataservice/libs/distributeddb/common/include/ischema.h @@ -13,11 +13,13 @@ * limitations under the License. */ -#ifndef SCHEMA_H -#define SCHEMA_H +#ifndef I_SCHEMA_H +#define I_SCHEMA_H #include +#include "db_types.h" + namespace DistributedDB { // SchemaType::NONE represent for KV database which do not have schema. Only invalid SchemaObject is NONE type. // Enum value must not be changed except SchemaType::UNRECOGNIZED. @@ -37,19 +39,6 @@ inline SchemaType ReadSchemaType(uint8_t inType) return static_cast(inType); } -struct SyncOpinion { - bool permitSync = false; - bool requirePeerConvert = false; - bool checkOnReceive = false; -}; - -struct SyncStrategy { - bool permitSync = false; - bool convertOnSend = false; - bool convertOnReceive = false; - bool checkOnReceive = false; -}; - struct SchemaAttribute { FieldType type = FieldType::LEAF_FIELD_NULL; bool isIndexable = false; @@ -69,4 +58,4 @@ public: virtual std::string ToSchemaString() const = 0; }; } -#endif // SCHEMA_H \ No newline at end of file +#endif // I_SCHEMA_H \ No newline at end of file diff --git a/services/distributeddataservice/libs/distributeddb/common/include/json_object.h b/services/distributeddataservice/libs/distributeddb/common/include/json_object.h old mode 100755 new mode 100644 index ddad4bb797cc9e06032753286abf2a70f83c287e..3d79c31acb5c8fa1b80cce393e44eb69c0bb329f --- a/services/distributeddataservice/libs/distributeddb/common/include/json_object.h +++ b/services/distributeddataservice/libs/distributeddb/common/include/json_object.h @@ -34,8 +34,8 @@ public: static uint32_t SetMaxNestDepth(uint32_t nestDepth); // Calculate nest depth when json string is legal or estimate depth by legal part from illegal json. - static uint32_t CalculateNestDepth(const std::string &inString); - static uint32_t CalculateNestDepth(const uint8_t *dataBegin, const uint8_t *dataEnd); + static uint32_t CalculateNestDepth(const std::string &inString, int &errCode); + static uint32_t CalculateNestDepth(const uint8_t *dataBegin, const uint8_t *dataEnd, int &errCode); // Support default constructor, copy constructor and copy assignment JsonObject() = default; diff --git a/services/distributeddataservice/libs/distributeddb/common/include/macro_utils.h b/services/distributeddataservice/libs/distributeddb/common/include/macro_utils.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/common/include/notification_chain.h b/services/distributeddataservice/libs/distributeddb/common/include/notification_chain.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/common/include/param_check_utils.h b/services/distributeddataservice/libs/distributeddb/common/include/param_check_utils.h old mode 100755 new mode 100644 index 2c522e9cb103f226e9d3ed3988dcbff3961cfe08..f55e66a4622c7aa372859ffb9835c318dceda1f7 --- a/services/distributeddataservice/libs/distributeddb/common/include/param_check_utils.h +++ b/services/distributeddataservice/libs/distributeddb/common/include/param_check_utils.h @@ -46,7 +46,7 @@ public: static bool IsS3SECEOpt(const SecurityOption &secOpt); - static int CheckAndTransferAutoLaunchParam(const AutoLaunchParam ¶m, + static int CheckAndTransferAutoLaunchParam(const AutoLaunchParam ¶m, bool checkDir, SchemaObject &schemaObject, std::string &canonicalDir); static uint8_t GetValidCompressionRate(uint8_t compressionRate); diff --git a/services/distributeddataservice/libs/distributeddb/common/include/parcel.h b/services/distributeddataservice/libs/distributeddb/common/include/parcel.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/common/include/platform_specific.h b/services/distributeddataservice/libs/distributeddb/common/include/platform_specific.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/common/include/relational/relational_schema_object.h b/services/distributeddataservice/libs/distributeddb/common/include/relational/relational_schema_object.h index fa8a5d18268fdc5f1b39a09bebf26786ed3a335a..884dcd4cee5db6bf490633d1b35e326ac55bc500 100644 --- a/services/distributeddataservice/libs/distributeddb/common/include/relational/relational_schema_object.h +++ b/services/distributeddataservice/libs/distributeddb/common/include/relational/relational_schema_object.h @@ -19,7 +19,7 @@ #include "data_value.h" #include "json_object.h" #include "parcel.h" -#include "schema.h" +#include "ischema.h" namespace DistributedDB { using CompositeFields = std::vector; @@ -63,23 +63,16 @@ public: bool GetAutoIncrement() const; const std::string &GetCreateTableSql() const; const std::map &GetFields() const; // - const std::vector &GetUniqueDefine() const; const std::map &GetIndexDefine() const; const FieldName &GetPrimaryKey() const; - const std::vector &GetTriggers() const; - const std::string &GetDevId() const; void SetTableName(const std::string &tableName); void SetAutoIncrement(bool autoInc); void SetCreateTableSql(std::string sql); // set 'autoInc_' flag when set sql void AddField(const FieldInfo &field); - void AddUniqueDefine(const CompositeFields &uniqueDefine); - void SetUniqueDefines(const std::vector &uniqueDefines); void AddIndexDefine(const std::string &indexName, const CompositeFields &indexDefine); void SetPrimaryKey(const FieldName &fieldName); // not support composite index now - void AddTrigger(const std::string &triggerName); std::string ToTableInfoString() const; - void SetDevId(const std::string &devId); int CompareWithTable(const TableInfo &inTableInfo) const; std::map GetSchemaDefine() const; @@ -89,59 +82,25 @@ public: private: void AddFieldDefineString(std::string &attrStr) const; - void AddUniqueDefineString(std::string &attrStr) const; void AddIndexDefineString(std::string &attrStr) const; int CompareWithTableFields(const std::map &inTableFields) const; int CompareWithTableIndex(const std::map &inTableIndex) const; std::string tableName_; - std::string devId_; bool autoInc_ = false; // only 'INTEGER PRIMARY KEY' could be defined as 'AUTOINCREMENT' std::string sql_; std::map fields_; FieldName primaryKey_; - std::vector uniqueDefines_; std::map indexDefines_; - std::vector triggers_; - JsonObject ToJsonObject() const; mutable std::vector fieldInfos_; }; -class RelationalSyncOpinion { -public: - uint32_t CalculateParcelLen(uint32_t softWareVersion) const; - int SerializeData(Parcel &parcel, uint32_t softWareVersion) const; - static int DeserializeData(Parcel &parcel, RelationalSyncOpinion &opinion); - SyncOpinion GetTableOpinion(const std::string& tableName) const; - const std::map &GetOpinions() const; - void AddSyncOpinion(const std::string &tableName, const SyncOpinion &opinion); -private: - std::map opinions_; - static const uint32_t SYNC_OPINION_VERSION = 1; -}; - -class RelationalSyncStrategy { -public: - SyncStrategy GetTableStrategy(const std::string &tableName) const; - void AddSyncStrategy(const std::string &tableName, const SyncStrategy &strategy); - const std::map &GetStrategies() const; -private: - std::map strategies_; -}; - class RelationalSchemaObject : public ISchema { public: RelationalSchemaObject() = default; ~RelationalSchemaObject() override = default; - static RelationalSyncOpinion MakeLocalSyncOpinion(const RelationalSchemaObject &localSchema, - const std::string &remoteSchema, uint8_t remoteSchemaType); - - // The remoteOpinion.checkOnReceive is ignored - static RelationalSyncStrategy ConcludeSyncStrategy(const RelationalSyncOpinion &localOpinion, - const RelationalSyncOpinion &remoteOpinion); - bool IsSchemaValid() const override; SchemaType GetSchemaType() const override; @@ -169,14 +128,13 @@ private: int ParseRelationalSchema(const JsonObject &inJsonObject); int ParseCheckSchemaType(const JsonObject &inJsonObject); - int ParseCheckSchemaVersionMode(const JsonObject &inJsonObject); + int ParseCheckSchemaVersion(const JsonObject &inJsonObject); int ParseCheckSchemaTableDefine(const JsonObject &inJsonObject); int ParseCheckTableInfo(const JsonObject &inJsonObject); int ParseCheckTableName(const JsonObject &inJsonObject, TableInfo &resultTable); int ParseCheckTableDefine(const JsonObject &inJsonObject, TableInfo &resultTable); int ParseCheckTableFieldInfo(const JsonObject &inJsonObject, const FieldPath &path, FieldInfo &table); int ParseCheckTableAutoInc(const JsonObject &inJsonObject, TableInfo &resultTable); - int ParseCheckTableUnique(const JsonObject &inJsonObject, TableInfo &resultTable); int ParseCheckTableIndex(const JsonObject &inJsonObject, TableInfo &resultTable); int ParseCheckTablePrimaryKey(const JsonObject &inJsonObject, TableInfo &resultTable); diff --git a/services/distributeddataservice/libs/distributeddb/common/include/res_finalizer.h b/services/distributeddataservice/libs/distributeddb/common/include/res_finalizer.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/common/include/runtime_context.h b/services/distributeddataservice/libs/distributeddb/common/include/runtime_context.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/common/include/schema_negotiate.h b/services/distributeddataservice/libs/distributeddb/common/include/schema_negotiate.h new file mode 100644 index 0000000000000000000000000000000000000000..cddb6d6c85da7001fea32e53ecb7b6711a1a2ade --- /dev/null +++ b/services/distributeddataservice/libs/distributeddb/common/include/schema_negotiate.h @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef SCHEMA_NEGOTIATE_H +#define SCHEMA_NEGOTIATE_H + +#include "schema_object.h" +#include "relational_schema_object.h" + +namespace DistributedDB { +struct SyncOpinion { + bool permitSync = false; + bool requirePeerConvert = false; + bool checkOnReceive = false; +}; + +struct SyncStrategy { + bool permitSync = false; + bool convertOnSend = false; + bool convertOnReceive = false; + bool checkOnReceive = false; +}; + +using RelationalSyncOpinion = std::map; +using RelationalSyncStrategy = std::map; + +class SchemaNegotiate { +public: + // The remoteSchemaType may beyond local SchemaType definition + static SyncOpinion MakeLocalSyncOpinion(const SchemaObject &localSchema, const std::string &remoteSchema, + uint8_t remoteSchemaType); + + // The remoteOpinion.checkOnReceive is ignored + static SyncStrategy ConcludeSyncStrategy(const SyncOpinion &localOpinion, const SyncOpinion &remoteOpinion); + + static RelationalSyncOpinion MakeLocalSyncOpinion(const RelationalSchemaObject &localSchema, + const std::string &remoteSchema, uint8_t remoteSchemaType); + + // The remoteOpinion.checkOnReceive is ignored + static RelationalSyncStrategy ConcludeSyncStrategy(const RelationalSyncOpinion &localOpinion, + const RelationalSyncOpinion &remoteOpinion); + + static uint32_t CalculateParcelLen(const RelationalSyncOpinion &opinions); + static int SerializeData(const RelationalSyncOpinion &opinions, Parcel &parcel); + static int DeserializeData(Parcel &parcel, RelationalSyncOpinion &opinion); + +private: + SchemaNegotiate() = default; + ~SchemaNegotiate() = default; +}; +} + +#endif // SCHEMA_NEGOTIATE_H \ No newline at end of file diff --git a/services/distributeddataservice/libs/distributeddb/common/include/schema_object.h b/services/distributeddataservice/libs/distributeddb/common/include/schema_object.h old mode 100755 new mode 100644 index 2049882e1626f16f4316d5c1af7c60a4214ce042..b788def45e1a3aa46eaeff1a60da3a2a3d6dfc45 --- a/services/distributeddataservice/libs/distributeddb/common/include/schema_object.h +++ b/services/distributeddataservice/libs/distributeddb/common/include/schema_object.h @@ -24,7 +24,7 @@ #include "db_types.h" #include "macro_utils.h" #include "relational_schema_object.h" -#include "schema.h" +#include "ischema.h" #include "value_object.h" namespace DistributedDB { @@ -45,13 +45,6 @@ public: static std::string GenerateExtractSQL(SchemaType inSchemaType, const FieldPath &inFieldpath, FieldType inFieldType, uint32_t skipSize, const std::string &accessStr = ""); - // The remoteSchemaType may beyond local SchemaType definition - static SyncOpinion MakeLocalSyncOpinion(const SchemaObject &localSchema, const std::string &remoteSchema, - uint8_t remoteSchemaType); - - // The remoteOpinion.checkOnReceive is ignored - static SyncStrategy ConcludeSyncStrategy(const SyncOpinion &localOpinion, const SyncOpinion &remoteOpinion); - // Support default constructor, copy constructor and copy assignment SchemaObject(); ~SchemaObject() = default; @@ -215,4 +208,3 @@ private: } // namespace DistributedDB #endif // SCHEMA_OBJECT_H - diff --git a/services/distributeddataservice/libs/distributeddb/common/include/schema_utils.h b/services/distributeddataservice/libs/distributeddb/common/include/schema_utils.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/common/include/value_hash_calc.h b/services/distributeddataservice/libs/distributeddb/common/include/value_hash_calc.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/common/include/value_object.h b/services/distributeddataservice/libs/distributeddb/common/include/value_object.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/common/include/version.h b/services/distributeddataservice/libs/distributeddb/common/include/version.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/common/src/auto_launch.cpp b/services/distributeddataservice/libs/distributeddb/common/src/auto_launch.cpp old mode 100755 new mode 100644 index c2f7138ae3e3dfdc313909161c1e5c2d5ef0c6fd..979b3dd4fc1cfb9221ee7bb2f4f16fb0c5565884 --- a/services/distributeddataservice/libs/distributeddb/common/src/auto_launch.cpp +++ b/services/distributeddataservice/libs/distributeddb/common/src/auto_launch.cpp @@ -384,9 +384,9 @@ void AutoLaunch::ObserverFunc(const KvDBCommitNotifyData ¬ifyData, const std: } autoLaunchItemMap_[identifier][userId].inObserver = true; autoLaunchItem.observer = autoLaunchItemMap_[identifier][userId].observer; - autoLaunchItem.isWriteOpenNotifiered = autoLaunchItemMap_[identifier][userId].isWriteOpenNotifiered; + autoLaunchItem.isWriteOpenNotified = autoLaunchItemMap_[identifier][userId].isWriteOpenNotified; autoLaunchItem.notifier = autoLaunchItemMap_[identifier][userId].notifier; - + std::shared_ptr properties = std::static_pointer_cast(autoLaunchItemMap_[identifier][userId].propertiesPtr); appId = properties->GetStringProp(KvDBProperties::APP_ID, ""); @@ -397,12 +397,12 @@ void AutoLaunch::ObserverFunc(const KvDBCommitNotifyData ¬ifyData, const std: KvStoreChangedDataImpl data(¬ifyData); (autoLaunchItem.observer)->OnChange(data); } - LOGI("[AutoLaunch] in observer autoLaunchItem.isWriteOpenNotifiered:%d", autoLaunchItem.isWriteOpenNotifiered); + LOGI("[AutoLaunch] in observer autoLaunchItem.isWriteOpenNotified:%d", autoLaunchItem.isWriteOpenNotified); - if (!autoLaunchItem.isWriteOpenNotifiered && autoLaunchItem.notifier != nullptr) { + if (!autoLaunchItem.isWriteOpenNotified && autoLaunchItem.notifier != nullptr) { { std::lock_guard autoLock(dataLock_); - autoLaunchItemMap_[identifier][userId].isWriteOpenNotifiered = true; + autoLaunchItemMap_[identifier][userId].isWriteOpenNotified = true; } AutoLaunchNotifier notifier = autoLaunchItem.notifier; int retCode = RuntimeContext::GetInstance()->ScheduleTask([notifier, userId, appId, storeId] { @@ -464,7 +464,7 @@ int AutoLaunch::DisableKvStoreAutoLaunch(const std::string &normalIdentifier, co cv_.notify_all(); return errCode; } - if (autoLaunchItem.isWriteOpenNotifiered && autoLaunchItem.notifier) { + if (autoLaunchItem.isWriteOpenNotified && autoLaunchItem.notifier) { RuntimeContext::GetInstance()->ScheduleTask([autoLaunchItem] { CloseNotifier(autoLaunchItem); }); } LOGI("[AutoLaunch] DisableKvStoreAutoLaunch ok"); @@ -522,17 +522,17 @@ void AutoLaunch::ConnectionLifeCycleCallbackTask(const std::string &identifier, autoLaunchItem = autoLaunchItemMap_[identifier][userId]; } LOGI("[AutoLaunch] ConnectionLifeCycleCallbackTask do CloseConnection"); - TryCloseConnection(autoLaunchItem); // do onthing if failed + TryCloseConnection(autoLaunchItem); // do nothing if failed LOGI("[AutoLaunch] ConnectionLifeCycleCallback do CloseConnection finished"); { std::lock_guard lock(dataLock_); autoLaunchItemMap_[identifier][userId].state = AutoLaunchItemState::IDLE; autoLaunchItemMap_[identifier][userId].conn = nullptr; - autoLaunchItemMap_[identifier][userId].isWriteOpenNotifiered = false; + autoLaunchItemMap_[identifier][userId].isWriteOpenNotified = false; cv_.notify_all(); LOGI("[AutoLaunch] ConnectionLifeCycleCallback notify_all"); } - if (autoLaunchItem.isWriteOpenNotifiered) { + if (autoLaunchItem.isWriteOpenNotified) { CloseNotifier(autoLaunchItem); } } @@ -670,7 +670,7 @@ void AutoLaunch::UpdateGlobalMap(std::map autoLock(dataLock_); autoLaunchItemMap_[identifier][userId].conn = autoLaunchItem.conn; autoLaunchItemMap_[identifier][userId].observerHandle = autoLaunchItem.observerHandle; - autoLaunchItemMap_[identifier][userId].isWriteOpenNotifiered = false; + autoLaunchItemMap_[identifier][userId].isWriteOpenNotified = false; autoLaunchItemMap_[identifier][userId].state = AutoLaunchItemState::IDLE; cv_.notify_all(); LOGI("[AutoLaunch] ReceiveUnknownIdentifierCallBackTask conn opened set state IDLE"); @@ -791,7 +791,7 @@ int AutoLaunch::AutoLaunchExt(const std::string &identifier, const std::string & } std::shared_ptr ptr; - errCode = AutoLaunch::GetAutoLaunchProperties(param, openType, ptr); + errCode = AutoLaunch::GetAutoLaunchProperties(param, openType, false, ptr); if (errCode != E_OK) { LOGE("[AutoLaunch] AutoLaunchExt param check fail errCode:%d", errCode); if (!param.notifier) { @@ -854,7 +854,7 @@ void AutoLaunch::AutoLaunchExtTask(const std::string identifier, const std::stri std::lock_guard autoLock(extLock_); extItemMap_[identifier][userId].conn = autoLaunchItem.conn; extItemMap_[identifier][userId].observerHandle = autoLaunchItem.observerHandle; - extItemMap_[identifier][userId].isWriteOpenNotifiered = false; + extItemMap_[identifier][userId].isWriteOpenNotified = false; LOGI("[AutoLaunch] AutoLaunchExtTask ok"); } @@ -881,9 +881,9 @@ void AutoLaunch::ExtObserverFunc(const KvDBCommitNotifyData ¬ifyData, const s { std::lock_guard autoLock(extLock_); if (extItemMap_.count(identifier) != 0 && extItemMap_[identifier].count(userId) != 0 && - !extItemMap_[identifier][userId].isWriteOpenNotifiered && + !extItemMap_[identifier][userId].isWriteOpenNotified && autoLaunchItem.notifier != nullptr) { - extItemMap_[identifier][userId].isWriteOpenNotifiered = true; + extItemMap_[identifier][userId].isWriteOpenNotified = true; notifier = autoLaunchItem.notifier; } else { return; @@ -929,7 +929,7 @@ void AutoLaunch::ExtConnectionLifeCycleCallbackTask(const std::string &identifie } LOGI("[AutoLaunch] ExtConnectionLifeCycleCallbackTask do CloseConnection"); TryCloseConnection(autoLaunchItem); // do nothing if failed - if (autoLaunchItem.isWriteOpenNotifiered) { + if (autoLaunchItem.isWriteOpenNotified) { CloseNotifier(autoLaunchItem); } } @@ -981,14 +981,14 @@ END: return errCode; } -int AutoLaunch::GetAutoLaunchProperties(const AutoLaunchParam ¶m, const DBType &openType, +int AutoLaunch::GetAutoLaunchProperties(const AutoLaunchParam ¶m, const DBType &openType, bool checkDir, std::shared_ptr &propertiesPtr) { switch (openType) { case DBType::DB_KV: { propertiesPtr = std::make_shared(); std::shared_ptr kvPtr = std::static_pointer_cast(propertiesPtr); - return GetAutoLaunchKVProperties(param, kvPtr); + return GetAutoLaunchKVProperties(param, kvPtr, checkDir); } case DBType::DB_RELATION: { propertiesPtr = std::make_shared(); @@ -1002,11 +1002,11 @@ int AutoLaunch::GetAutoLaunchProperties(const AutoLaunchParam ¶m, const DBTy } int AutoLaunch::GetAutoLaunchKVProperties(const AutoLaunchParam ¶m, - const std::shared_ptr &propertiesPtr) + const std::shared_ptr &propertiesPtr, bool checkDir) { SchemaObject schemaObject; std::string canonicalDir; - int errCode = ParamCheckUtils::CheckAndTransferAutoLaunchParam(param, schemaObject, canonicalDir); + int errCode = ParamCheckUtils::CheckAndTransferAutoLaunchParam(param, checkDir, schemaObject, canonicalDir); if (errCode != E_OK) { return errCode; } @@ -1081,6 +1081,14 @@ int AutoLaunch::OpenKvConnection(AutoLaunchItem &autoLaunchItem) std::shared_ptr properties = std::static_pointer_cast(autoLaunchItem.propertiesPtr); int errCode = E_OK; + std::string canonicalDir; + std::string dataDir; + properties->GetStringProp(KvDBProperties::DATA_DIR, dataDir); + if (!ParamCheckUtils::CheckDataDir(dataDir, canonicalDir)) { + LOGE("[AutoLaunch] CheckDataDir is invalid Auto Launch failed."); + return -E_INVALID_ARGS; + } + properties->SetStringProp(KvDBProperties::DATA_DIR, canonicalDir); IKvDBConnection *conn = KvDBManager::GetDatabaseConnection(*properties, errCode, false); if (errCode == -E_ALREADY_OPENED) { LOGI("[AutoLaunch] GetOneConnection user already getkvstore by self"); diff --git a/services/distributeddataservice/libs/distributeddb/common/src/data_value.cpp b/services/distributeddataservice/libs/distributeddb/common/src/data_value.cpp index ffd6fc7b607ba02699901d6891b7cc7cb562b045..81929ae3405816518ed0d603f7cede662d08df98 100644 --- a/services/distributeddataservice/libs/distributeddb/common/src/data_value.cpp +++ b/services/distributeddataservice/libs/distributeddb/common/src/data_value.cpp @@ -41,7 +41,7 @@ Blob::Blob(Blob &&blob) : ptr_(blob.ptr_), size_(blob.size_) Blob &Blob::operator=(Blob &&blob) noexcept { - if (this != &blob) { + if (&blob != this) { delete[] ptr_; ptr_ = blob.ptr_; size_ = blob.size_; @@ -104,14 +104,11 @@ DataValue::DataValue(DataValue &&dataValue) noexcept DataValue &DataValue::operator=(const DataValue &dataValue) { - if (this == &dataValue) { + if (&dataValue == this) { return *this; } ResetValue(); switch (dataValue.type_) { - case StorageType::STORAGE_TYPE_BOOL: - (void)dataValue.GetBool(this->value_.bValue); - break; case StorageType::STORAGE_TYPE_INTEGER: (void)dataValue.GetInt64(this->value_.iValue); break; @@ -131,7 +128,7 @@ DataValue &DataValue::operator=(const DataValue &dataValue) DataValue &DataValue::operator=(DataValue &&dataValue) noexcept { - if (this == &dataValue) { + if (&dataValue == this) { return *this; } ResetValue(); @@ -148,14 +145,6 @@ DataValue &DataValue::operator=(DataValue &&dataValue) noexcept return *this; } -DataValue &DataValue::operator=(bool boolVal) -{ - ResetValue(); - type_ = StorageType::STORAGE_TYPE_BOOL; - value_.bValue = boolVal; - return *this; -} - DataValue &DataValue::operator=(int64_t intVal) { ResetValue(); @@ -203,8 +192,6 @@ bool DataValue::operator==(const DataValue &dataValue) const return false; } switch (type_) { - case StorageType::STORAGE_TYPE_BOOL: - return dataValue.value_.bValue == value_.bValue; case StorageType::STORAGE_TYPE_INTEGER: return dataValue.value_.iValue == value_.iValue; case StorageType::STORAGE_TYPE_REAL: @@ -230,15 +217,6 @@ bool DataValue::operator!=(const DataValue &dataValue) const return !(*this == dataValue); } -int DataValue::GetBool(bool &outVal) const -{ - if (type_ != StorageType::STORAGE_TYPE_BOOL) { - return -E_NOT_SUPPORT; - } - outVal = value_.bValue; - return E_OK; -} - int DataValue::GetDouble(double &outVal) const { if (type_ != StorageType::STORAGE_TYPE_REAL) { @@ -299,7 +277,7 @@ int DataValue::GetBlob(Blob &outVal) const int DataValue::SetText(const std::string &val) { - return SetText(reinterpret_cast(val.c_str()), val.length()); + return SetText(reinterpret_cast(val.c_str()), val.length()); } int DataValue::SetText(const uint8_t *val, uint32_t length) @@ -352,7 +330,6 @@ void DataValue::ResetValue() value_.blobPtr = nullptr; break; case StorageType::STORAGE_TYPE_NULL: - case StorageType::STORAGE_TYPE_BOOL: case StorageType::STORAGE_TYPE_INTEGER: case StorageType::STORAGE_TYPE_REAL: default: @@ -375,9 +352,6 @@ std::string DataValue::ToString() const case StorageType::STORAGE_TYPE_NULL: res = "null"; break; - case StorageType::STORAGE_TYPE_BOOL: - res = std::to_string(value_.bValue); - break; case StorageType::STORAGE_TYPE_INTEGER: res = std::to_string(value_.iValue); break; diff --git a/services/distributeddataservice/libs/distributeddb/common/src/db_ability.cpp b/services/distributeddataservice/libs/distributeddb/common/src/db_ability.cpp index 673191fdcca0753ec532cc1e350894d961959cd0..87d0ca7eb8fa63e520e67b2ebf1c0374d4449d54 100644 --- a/services/distributeddataservice/libs/distributeddb/common/src/db_ability.cpp +++ b/services/distributeddataservice/libs/distributeddb/common/src/db_ability.cpp @@ -125,7 +125,7 @@ uint32_t DbAbility::GetAbilityBitsLen() const return dbAbility_.size(); } -uint8_t DbAbility::GetAbilityItem(const AbilityItem abilityType) const +uint8_t DbAbility::GetAbilityItem(const AbilityItem &abilityType) const { uint8_t data = 0; auto iter = dbAbilityItemSet_.find(abilityType); diff --git a/services/distributeddataservice/libs/distributeddb/common/src/db_common.cpp b/services/distributeddataservice/libs/distributeddb/common/src/db_common.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/common/src/db_constant.cpp b/services/distributeddataservice/libs/distributeddb/common/src/db_constant.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/common/src/evloop/include/event_fd.h b/services/distributeddataservice/libs/distributeddb/common/src/evloop/include/event_fd.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/common/src/evloop/include/ievent.h b/services/distributeddataservice/libs/distributeddb/common/src/evloop/include/ievent.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/common/src/evloop/include/ievent_loop.h b/services/distributeddataservice/libs/distributeddb/common/src/evloop/include/ievent_loop.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/common/src/evloop/src/event_impl.cpp b/services/distributeddataservice/libs/distributeddb/common/src/evloop/src/event_impl.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/common/src/evloop/src/event_impl.h b/services/distributeddataservice/libs/distributeddb/common/src/evloop/src/event_impl.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/common/src/evloop/src/event_loop_epoll.cpp b/services/distributeddataservice/libs/distributeddb/common/src/evloop/src/event_loop_epoll.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/common/src/evloop/src/event_loop_epoll.h b/services/distributeddataservice/libs/distributeddb/common/src/evloop/src/event_loop_epoll.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/common/src/evloop/src/event_loop_impl.cpp b/services/distributeddataservice/libs/distributeddb/common/src/evloop/src/event_loop_impl.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/common/src/evloop/src/event_loop_impl.h b/services/distributeddataservice/libs/distributeddb/common/src/evloop/src/event_loop_impl.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/common/src/evloop/src/event_loop_select.cpp b/services/distributeddataservice/libs/distributeddb/common/src/evloop/src/event_loop_select.cpp old mode 100755 new mode 100644 index 21b0a7301d7444718c56e7b1d0ccf50cfe5c4a0d..a9ba7c3119ad0bccdd52c3abaa8e22e780990bb3 --- a/services/distributeddataservice/libs/distributeddb/common/src/evloop/src/event_loop_select.cpp +++ b/services/distributeddataservice/libs/distributeddb/common/src/evloop/src/event_loop_select.cpp @@ -36,6 +36,7 @@ int EventLoopSelect::Initialize() int EventLoopSelect::Prepare(const std::set &polling) { + (void)polling; return E_OK; } @@ -56,21 +57,27 @@ int EventLoopSelect::WakeUp() int EventLoopSelect::Exit(const std::set &polling) { + (void)polling; return E_OK; } int EventLoopSelect::AddEvent(EventImpl *event) { + (void)event; return E_OK; } int EventLoopSelect::RemoveEvent(EventImpl *event) { + (void)event; return E_OK; } int EventLoopSelect::ModifyEvent(EventImpl *event, bool isAdd, EventsMask events) { + (void)event; + (void)isAdd; + (void)events; return E_OK; } diff --git a/services/distributeddataservice/libs/distributeddb/common/src/evloop/src/event_loop_select.h b/services/distributeddataservice/libs/distributeddb/common/src/evloop/src/event_loop_select.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/common/src/evloop/src/ievent.cpp b/services/distributeddataservice/libs/distributeddb/common/src/evloop/src/ievent.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/common/src/evloop/src/ievent_loop.cpp b/services/distributeddataservice/libs/distributeddb/common/src/evloop/src/ievent_loop.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/common/src/flatbuffer_schema.cpp b/services/distributeddataservice/libs/distributeddb/common/src/flatbuffer_schema.cpp old mode 100755 new mode 100644 index d1eb269e4b3aeed4631b777cb1a1c7bf41c76a9d..ae197fb64f536ad0281322e3c2b1149d06e74582 --- a/services/distributeddataservice/libs/distributeddb/common/src/flatbuffer_schema.cpp +++ b/services/distributeddataservice/libs/distributeddb/common/src/flatbuffer_schema.cpp @@ -55,7 +55,7 @@ bool SchemaObject::FlatBufferSchema::IsFlatBufferSchema(const std::string &inOri LOGE("[FBSchema][Is] OriSchema empty."); return false; } - if (inOriginal.size() >= SchemaConstant::SCHEMA_STRING_SIZE_LIMIT * 2) { + if (inOriginal.size() >= SchemaConstant::SCHEMA_STRING_SIZE_LIMIT * 2) { // 2 :Maximum base64 encode size multiple // Base64 encode will not exceed 2 times original binary LOGE("[FBSchema][Is] OriSchemaSize=%zu too large even after base64 encode.", inOriginal.size()); return false; @@ -72,7 +72,7 @@ bool SchemaObject::FlatBufferSchema::IsFlatBufferSchema(const std::string &inOri // A macro check pointer get from flatbuffer that won't be nullptr(required field) in fact after verified by flatbuffer #define CHECK_NULL_UNLIKELY_RETURN_ERROR(pointer) \ - if (pointer == nullptr) { \ + if ((pointer) == nullptr) { \ return -E_INTERNAL_ERROR; \ } diff --git a/services/distributeddataservice/libs/distributeddb/common/src/hash.cpp b/services/distributeddataservice/libs/distributeddb/common/src/hash.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/common/src/json_object.cpp b/services/distributeddataservice/libs/distributeddb/common/src/json_object.cpp old mode 100755 new mode 100644 index 595dde63ae4c30ed7b985198c5b6281d7071797e..53b53e0eac4e5a65fed67bcd170640804688ac4a --- a/services/distributeddataservice/libs/distributeddb/common/src/json_object.cpp +++ b/services/distributeddataservice/libs/distributeddb/common/src/json_object.cpp @@ -41,17 +41,18 @@ uint32_t JsonObject::SetMaxNestDepth(uint32_t nestDepth) return preValue; } -uint32_t JsonObject::CalculateNestDepth(const std::string &inString) +uint32_t JsonObject::CalculateNestDepth(const std::string &inString, int &errCode) { auto begin = reinterpret_cast(inString.c_str()); auto end = begin + inString.size(); - return CalculateNestDepth(begin, end); + return CalculateNestDepth(begin, end, errCode); } -uint32_t JsonObject::CalculateNestDepth(const uint8_t *dataBegin, const uint8_t *dataEnd) +uint32_t JsonObject::CalculateNestDepth(const uint8_t *dataBegin, const uint8_t *dataEnd, int &errCode) { if (dataBegin == nullptr || dataEnd == nullptr || dataBegin >= dataEnd) { - return -E_INVALID_ARGS; + errCode = -E_INVALID_ARGS; + return maxNestDepth_ + 1; // return a invalid depth } bool isInString = false; uint32_t maxDepth = 0; @@ -111,9 +112,11 @@ int JsonObject::Parse(const std::string &inString) LOGE("[Json][Parse] Already Valid."); return -E_NOT_PERMIT; } - uint32_t nestDepth = CalculateNestDepth(inString); - if (nestDepth > maxNestDepth_) { - LOGE("[Json][Parse] Json nest depth=%u exceed max allowed=%u.", nestDepth, maxNestDepth_); + int errCode = E_OK; + uint32_t nestDepth = CalculateNestDepth(inString, errCode); + if (errCode != E_OK || nestDepth > maxNestDepth_) { + LOGE("[Json][Parse] Json calculate nest depth failed %d, depth=%u exceed max allowed=%u.", errCode, nestDepth, + maxNestDepth_); return -E_JSON_PARSE_FAIL; } #ifdef JSONCPP_USE_BUILDER @@ -165,9 +168,11 @@ int JsonObject::Parse(const uint8_t *dataBegin, const uint8_t *dataEnd) if (dataBegin == nullptr || dataEnd == nullptr || dataBegin >= dataEnd) { return -E_INVALID_ARGS; } - uint32_t nestDepth = CalculateNestDepth(dataBegin, dataEnd); - if (nestDepth > maxNestDepth_) { - LOGE("[Json][Parse] Json nest depth=%u exceed max allowed=%u.", nestDepth, maxNestDepth_); + int errCode = E_OK; + uint32_t nestDepth = CalculateNestDepth(dataBegin, dataEnd, errCode); + if (errCode != E_OK || nestDepth > maxNestDepth_) { + LOGE("[Json][Parse] Json calculate nest depth failed %d, depth=%u exceed max allowed=%u.", errCode, nestDepth, + maxNestDepth_); return -E_JSON_PARSE_FAIL; } #ifdef JSONCPP_USE_BUILDER @@ -781,16 +786,22 @@ int JsonObject::GetStringArrayByFieldPath(const FieldPath &inPath, std::vector &inData) { + (void)inData; LOGW("[Json][Parse] Json Omit From Compile."); return -E_NOT_PERMIT; } int JsonObject::Parse(const uint8_t *dataBegin, const uint8_t *dataEnd) { + (void)dataBegin; + (void)dataEnd; LOGW("[Json][Parse] Json Omit From Compile."); return -E_NOT_PERMIT; } @@ -828,68 +843,94 @@ std::string JsonObject::ToString() const bool JsonObject::IsFieldPathExist(const FieldPath &inPath) const { + (void)inPath; return false; } int JsonObject::GetFieldTypeByFieldPath(const FieldPath &inPath, FieldType &outType) const { + (void)inPath; + (void)outType; return -E_NOT_PERMIT; } int JsonObject::GetFieldValueByFieldPath(const FieldPath &inPath, FieldValue &outValue) const { + (void)inPath; + (void)outValue; return -E_NOT_PERMIT; } int JsonObject::GetSubFieldPath(const FieldPath &inPath, std::set &outSubPath) const { + (void)inPath; + (void)outSubPath; return -E_NOT_PERMIT; } int JsonObject::GetSubFieldPath(const std::set &inPath, std::set &outSubPath) const { + (void)inPath; + (void)outSubPath; return -E_NOT_PERMIT; } int JsonObject::GetSubFieldPathAndType(const FieldPath &inPath, std::map &outSubPathType) const { + (void)inPath; + (void)outSubPathType; return -E_NOT_PERMIT; } int JsonObject::GetSubFieldPathAndType(const std::set &inPath, std::map &outSubPathType) const { + (void)inPath; + (void)outSubPathType; return -E_NOT_PERMIT; } int JsonObject::GetArraySize(const FieldPath &inPath, uint32_t &outSize) const { + (void)inPath; + (void)outSize; return -E_NOT_PERMIT; } int JsonObject::GetArrayContentOfStringOrStringArray(const FieldPath &inPath, std::vector> &outContent) const { + (void)inPath; + (void)outContent; return -E_NOT_PERMIT; } int JsonObject::InsertField(const FieldPath &inPath, FieldType inType, const FieldValue &inValue) { + (void)inPath; + (void)inType; + (void)inValue; return -E_NOT_PERMIT; } int JsonObject::InsertField(const FieldPath &inPath, const JsonObject &inValue, bool isAppend = false) { + (void)inPath; + (void)inValue; + (void)isAppend; return -E_NOT_PERMIT; } int JsonObject::DeleteField(const FieldPath &inPath) { + (void)inPath; return -E_NOT_PERMIT; } int JsonObject::GetArrayValueByFieldPath(const FieldPath &inPath, JsonObject &outArray) const { + (void)inPath; + (void)outArray; return -E_NOT_PERMIT; } #endif // OMIT_JSON diff --git a/services/distributeddataservice/libs/distributeddb/common/src/lock_status_observer.cpp b/services/distributeddataservice/libs/distributeddb/common/src/lock_status_observer.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/common/src/lock_status_observer.h b/services/distributeddataservice/libs/distributeddb/common/src/lock_status_observer.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/common/src/log_print.cpp b/services/distributeddataservice/libs/distributeddb/common/src/log_print.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/common/src/notification_chain.cpp b/services/distributeddataservice/libs/distributeddb/common/src/notification_chain.cpp old mode 100755 new mode 100644 index 8db202781cf2bce26c7a4d9751db6a6a37499f2d..4b7daea5f425dff783deaf42f27804722629680d --- a/services/distributeddataservice/libs/distributeddb/common/src/notification_chain.cpp +++ b/services/distributeddataservice/libs/distributeddb/common/src/notification_chain.cpp @@ -273,7 +273,7 @@ void NotificationChain::Listener::KillWait() return; } - LOGW("[NotificationChain] Try to kill a active event listener, now wait."); + LOGW("[NotificationChain] Try to kill an active event listener, now wait."); bool noDeadLock = WaitLockedUntil(safeKill_, [this]() { if (eventRunningThread_ == std::thread::id()) { return true; diff --git a/services/distributeddataservice/libs/distributeddb/common/src/param_check_utils.cpp b/services/distributeddataservice/libs/distributeddb/common/src/param_check_utils.cpp old mode 100755 new mode 100644 index e9ad559b0cb222cbc927461ae24e849a6008c338..1d498a370fa2a124a733401cfc6c5b37999c61d9 --- a/services/distributeddataservice/libs/distributeddb/common/src/param_check_utils.cpp +++ b/services/distributeddataservice/libs/distributeddb/common/src/param_check_utils.cpp @@ -145,7 +145,7 @@ bool ParamCheckUtils::IsS3SECEOpt(const SecurityOption &secOpt) return (secOpt == S3SeceOpt); } -int ParamCheckUtils::CheckAndTransferAutoLaunchParam(const AutoLaunchParam ¶m, +int ParamCheckUtils::CheckAndTransferAutoLaunchParam(const AutoLaunchParam ¶m, bool checkDir, SchemaObject &schemaObject, std::string &canonicalDir) { if ((param.option.notifier && !ParamCheckUtils::CheckConflictNotifierType(param.option.conflictType)) || @@ -179,6 +179,11 @@ int ParamCheckUtils::CheckAndTransferAutoLaunchParam(const AutoLaunchParam ¶ } } + if (!checkDir) { + canonicalDir = param.option.dataDir; + return E_OK; + } + if (!ParamCheckUtils::CheckDataDir(param.option.dataDir, canonicalDir)) { LOGE("[AutoLaunch] CheckDataDir is invalid."); return -E_INVALID_ARGS; diff --git a/services/distributeddataservice/libs/distributeddb/common/src/parcel.cpp b/services/distributeddataservice/libs/distributeddb/common/src/parcel.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/common/src/performance_analysis.cpp b/services/distributeddataservice/libs/distributeddb/common/src/performance_analysis.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/common/src/platform_specific.cpp b/services/distributeddataservice/libs/distributeddb/common/src/platform_specific.cpp old mode 100755 new mode 100644 index 264842e879ff00187a26e9b72c5f728b5b2594e4..01f32ea65deb4b915b1ea3c6c0e0e1e608540356 --- a/services/distributeddataservice/libs/distributeddb/common/src/platform_specific.cpp +++ b/services/distributeddataservice/libs/distributeddb/common/src/platform_specific.cpp @@ -78,7 +78,7 @@ int CalFileSize(const std::string &fileUrl, uint64_t &size) return errCode; } - size = fileStat.st_size; + size = static_cast(fileStat.st_size); return E_OK; } @@ -138,7 +138,11 @@ int GetRealPath(const std::string &inOriPath, std::string &outRealPath) if (realPath == nullptr) { return -E_OUT_OF_MEMORY; } - (void)memset_s(realPath, MAX_PATH_LENGTH + 1, 0, MAX_PATH_LENGTH + 1); + if (memset_s(realPath, MAX_PATH_LENGTH + 1, 0, MAX_PATH_LENGTH + 1) != EOK) { + delete []realPath; + return -E_SECUREC_ERROR; + } + if (realpath(inOriPath.c_str(), realPath) == nullptr) { LOGE("[RealPath] Get realpath for inOriPath fail:%d.", errno); delete []realPath; @@ -217,7 +221,7 @@ static int GetFilePathAttr(const std::string &topPath, const std::string &relati if (isNeedAllPath) { file.fileName = fileAbsName; } - file.fileLen = fileStat.st_size; + file.fileLen = static_cast(fileStat.st_size); files.push_back(file); if (file.fileType == PATH) { errCode = GetFilePathAttr(fileAbsName, relativePath + fileDirInfo->d_name + "/", files, isNeedAllPath); diff --git a/services/distributeddataservice/libs/distributeddb/common/src/query.cpp b/services/distributeddataservice/libs/distributeddb/common/src/query.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/common/src/query_expression.cpp b/services/distributeddataservice/libs/distributeddb/common/src/query_expression.cpp old mode 100755 new mode 100644 index 26f5ee403d79789a21007298cf6202184d2e8a96..6de2914eaf437ac7e2ad64bea23a9a2ac73f9b4e --- a/services/distributeddataservice/libs/distributeddb/common/src/query_expression.cpp +++ b/services/distributeddataservice/libs/distributeddb/common/src/query_expression.cpp @@ -18,8 +18,7 @@ #include "db_errno.h" namespace DistributedDB { -namespace -{ +namespace { const int MAX_OPR_TIMES = 256; } // namespace diff --git a/services/distributeddataservice/libs/distributeddb/common/src/ref_object.cpp b/services/distributeddataservice/libs/distributeddb/common/src/ref_object.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/common/src/relational/relational_schema_object.cpp b/services/distributeddataservice/libs/distributeddb/common/src/relational/relational_schema_object.cpp index 099d0c899f4400446abfebc8d0a00e9732437c53..c087a3a537f1972d13e2b05651030ac3d3a1ff62 100644 --- a/services/distributeddataservice/libs/distributeddb/common/src/relational/relational_schema_object.cpp +++ b/services/distributeddataservice/libs/distributeddb/common/src/relational/relational_schema_object.cpp @@ -202,21 +202,6 @@ void TableInfo::AddField(const FieldInfo &field) fields_[field.GetFieldName()] = field; } -const std::vector &TableInfo::GetUniqueDefine() const -{ - return uniqueDefines_; -} - -void TableInfo::AddUniqueDefine(const CompositeFields &uniqueDefine) -{ - uniqueDefines_.push_back(uniqueDefine); -} - -void TableInfo::SetUniqueDefines(const std::vector &uniqueDefines) -{ - uniqueDefines_ = uniqueDefines; -} - const std::map &TableInfo::GetIndexDefine() const { return indexDefines_; @@ -237,16 +222,6 @@ void TableInfo::SetPrimaryKey(const FieldName &fieldName) primaryKey_ = fieldName; } -void TableInfo::AddTrigger(const std::string &triggerName) -{ - triggers_.push_back(triggerName); -} - -const std::vector &TableInfo::GetTriggers() const -{ - return triggers_; -} - void TableInfo::AddFieldDefineString(std::string &attrStr) const { if (fields_.empty()) { @@ -262,28 +237,6 @@ void TableInfo::AddFieldDefineString(std::string &attrStr) const attrStr += "},"; } -void TableInfo::AddUniqueDefineString(std::string &attrStr) const -{ - if (uniqueDefines_.empty()) { - return; - } - attrStr += R"("UNIQUE": [)"; - for (auto itUniqueDefine = uniqueDefines_.begin(); itUniqueDefine != uniqueDefines_.end(); ++itUniqueDefine) { - attrStr += "[\""; - for (auto itField = (*itUniqueDefine).begin(); itField != (*itUniqueDefine).end(); ++itField) { - attrStr += *itField; - if (itField != (*itUniqueDefine).end() - 1) { - attrStr += "\",\""; - } - } - attrStr += "\"]"; - if (itUniqueDefine != uniqueDefines_.end() - 1) { - attrStr += ","; - } - } - attrStr += "],"; -} - void TableInfo::AddIndexDefineString(std::string &attrStr) const { if (indexDefines_.empty()) { @@ -306,16 +259,6 @@ void TableInfo::AddIndexDefineString(std::string &attrStr) const attrStr += "}"; } -const std::string &TableInfo::GetDevId() const -{ - return devId_; -} - -void TableInfo::SetDevId(const std::string &devId) -{ - devId_ = devId; -} - int TableInfo::CompareWithTable(const TableInfo &inTableInfo) const { if (tableName_ != inTableInfo.GetTableName()) { @@ -395,39 +338,6 @@ int TableInfo::CompareWithTableIndex(const std::map UINT32_MAX) { - return 0; - } - return static_cast(len); -} - -int RelationalSyncOpinion::SerializeData(Parcel &parcel, uint32_t softWareVersion) const -{ - (void)parcel.WriteString(MAGIC); - (void)parcel.WriteUInt32(SYNC_OPINION_VERSION); - (void)parcel.WriteUInt32(static_cast(opinions_.size())); - (void)parcel.EightByteAlign(); - for (const auto &it : opinions_) { - (void)parcel.WriteString(it.first); - (void)parcel.WriteUInt32(it.second.permitSync); - (void)parcel.WriteUInt32(it.second.requirePeerConvert); - (void)parcel.EightByteAlign(); - } - return parcel.IsError() ? -E_INVALID_ARGS : E_OK; -} - -int RelationalSyncOpinion::DeserializeData(Parcel &parcel, RelationalSyncOpinion &opinion) -{ - if (!parcel.IsContinueRead()) { - return E_OK; - } - std::string magicStr; - (void)parcel.ReadString(magicStr); - if (magicStr != MAGIC) { - LOGE("Deserialize sync opinion failed while read MAGIC string [%s]", magicStr.c_str()); - return -E_INVALID_ARGS; - } - uint32_t version; - (void)parcel.ReadUInt32(version); - if (version != SYNC_OPINION_VERSION) { - LOGE("Not support sync opinion version: %u", version); - return -E_NOT_SUPPORT; - } - uint32_t opinionSize; - (void)parcel.ReadUInt32(opinionSize); - (void)parcel.EightByteAlign(); - for (uint32_t i = 0; i < opinionSize; i++) { - std::string tableName; - SyncOpinion tableOpinion; - (void)parcel.ReadString(tableName); - uint32_t permitSync; - (void)parcel.ReadUInt32(permitSync); - tableOpinion.permitSync = static_cast(permitSync); - uint32_t requirePeerConvert; - (void)parcel.ReadUInt32(requirePeerConvert); - tableOpinion.requirePeerConvert = static_cast(requirePeerConvert); - (void)parcel.EightByteAlign(); - opinion.AddSyncOpinion(tableName, tableOpinion); - } - return parcel.IsError() ? -E_INVALID_ARGS : E_OK; -} - -SyncOpinion RelationalSyncOpinion::GetTableOpinion(const std::string &tableName) const -{ - auto it = opinions_.find(tableName); - if (it == opinions_.end()) { - return {}; - } - return it->second; -} - -const std::map &RelationalSyncOpinion::GetOpinions() const -{ - return opinions_; -} - -void RelationalSyncOpinion::AddSyncOpinion(const std::string &tableName, const SyncOpinion &opinion) -{ - opinions_[tableName] = opinion; -} - -SyncStrategy RelationalSyncStrategy::GetTableStrategy(const std::string &tableName) const -{ - auto it = strategies_.find(tableName); - if (it == strategies_.end()) { - return {}; - } - return it->second; -} - -void RelationalSyncStrategy::AddSyncStrategy(const std::string &tableName, const SyncStrategy &strategy) -{ - strategies_[tableName] = strategy; -} - -const std::map &RelationalSyncStrategy::GetStrategies() const -{ - return strategies_; -} - -RelationalSyncOpinion RelationalSchemaObject::MakeLocalSyncOpinion(const RelationalSchemaObject &localSchema, - const std::string &remoteSchema, uint8_t remoteSchemaType) -{ - SchemaType localType = localSchema.GetSchemaType(); - SchemaType remoteType = ReadSchemaType(remoteSchemaType); - - if (remoteType == SchemaType::UNRECOGNIZED) { - LOGW("[RelationalSchema][opinion] Remote schema type %d is unrecognized.", remoteSchemaType); - return {}; - } - - if (remoteType != SchemaType::RELATIVE) { - LOGW("[RelationalSchema][opinion] Not support sync with schema type: local-type=[%s] remote-type=[%s]", - SchemaUtils::SchemaTypeString(localType).c_str(), SchemaUtils::SchemaTypeString(remoteType).c_str()); - return {}; - } - - if (!localSchema.IsSchemaValid()) { - LOGW("[RelationalSchema][opinion] Local schema is not valid"); - return {}; - } - - RelationalSchemaObject remoteSchemaObj; - int errCode = remoteSchemaObj.ParseFromSchemaString(remoteSchema); - if (errCode != E_OK) { - LOGW("[RelationalSchema][opinion] Parse remote schema failed %d, remote schema type %s", errCode, - SchemaUtils::SchemaTypeString(remoteType).c_str()); - return {}; - } - - RelationalSyncOpinion opinion; - for (const auto &it : localSchema.GetTables()) { - if (remoteSchemaObj.GetTable(it.first).GetTableName() != it.first) { - LOGW("[RelationalSchema][opinion] Table was missing in remote schema"); - continue; - } - // remote table is compatible(equal or upgrade) based on local table, permit sync and don't need check - errCode = it.second.CompareWithTable(remoteSchemaObj.GetTable(it.first)); - if (errCode != -E_RELATIONAL_TABLE_INCOMPATIBLE) { - opinion.AddSyncOpinion(it.first, {true, false, false}); - continue; - } - // local table is compatible upgrade based on remote table, permit sync and need check - errCode = remoteSchemaObj.GetTable(it.first).CompareWithTable(it.second); - if (errCode != -E_RELATIONAL_TABLE_INCOMPATIBLE) { - opinion.AddSyncOpinion(it.first, {true, false, true}); - continue; - } - // local table is incompatible with remote table mutually, don't permit sync and need check - LOGW("[RelationalSchema][opinion] Local table is incompatible with remote table mutually."); - opinion.AddSyncOpinion(it.first, {false, true, true}); - } - - return opinion; -} - -RelationalSyncStrategy RelationalSchemaObject::ConcludeSyncStrategy(const RelationalSyncOpinion &localOpinion, - const RelationalSyncOpinion &remoteOpinion) -{ - RelationalSyncStrategy syncStrategy; - for (const auto &itLocal : localOpinion.GetOpinions()) { - if (remoteOpinion.GetOpinions().find(itLocal.first) == remoteOpinion.GetOpinions().end()) { - LOGW("[RelationalSchema][Strategy] Table opinion is not found from remote."); - continue; - } - - SyncStrategy strategy; - SyncOpinion localTableOpinion = itLocal.second; - SyncOpinion remoteTableOpinion = remoteOpinion.GetTableOpinion(itLocal.first); - - strategy.permitSync = (localTableOpinion.permitSync || remoteTableOpinion.permitSync); - - bool convertConflict = (localTableOpinion.requirePeerConvert && remoteTableOpinion.requirePeerConvert); - if (convertConflict) { - // Should not both need peer convert - strategy.permitSync = false; - } - // No peer convert required means local side has convert capability, convert locally takes precedence - strategy.convertOnSend = (!localTableOpinion.requirePeerConvert); - strategy.convertOnReceive = remoteTableOpinion.requirePeerConvert; - - strategy.checkOnReceive = localTableOpinion.checkOnReceive; - LOGI("[RelationalSchema][Strategy] PermitSync=%d, SendConvert=%d, ReceiveConvert=%d, ReceiveCheck=%d.", - strategy.permitSync, strategy.convertOnSend, strategy.convertOnReceive, strategy.checkOnReceive); - syncStrategy.AddSyncStrategy(itLocal.first, strategy); - } - - return syncStrategy; -} - bool RelationalSchemaObject::IsSchemaValid() const { return isValid_; @@ -689,8 +401,8 @@ int RelationalSchemaObject::ParseFromSchemaString(const std::string &inSchemaStr return -E_NOT_PERMIT; } - if (inSchemaString.size() > SchemaConstant::SCHEMA_STRING_SIZE_LIMIT) { - LOGE("[RelationalSchema][Parse] SchemaSize=%zu Too Large.", inSchemaString.size()); + if (inSchemaString.empty() || inSchemaString.size() > SchemaConstant::SCHEMA_STRING_SIZE_LIMIT) { + LOGE("[RelationalSchema][Parse] SchemaSize=%zu is invalid.", inSchemaString.size()); return -E_INVALID_ARGS; } JsonObject schemaObj; @@ -813,7 +525,7 @@ int GetMemberFromJsonObject(const JsonObject &inJsonObject, const std::string &f int RelationalSchemaObject::ParseRelationalSchema(const JsonObject &inJsonObject) { - int errCode = ParseCheckSchemaVersionMode(inJsonObject); + int errCode = ParseCheckSchemaVersion(inJsonObject); if (errCode != E_OK) { return errCode; } @@ -824,7 +536,7 @@ int RelationalSchemaObject::ParseRelationalSchema(const JsonObject &inJsonObject return ParseCheckSchemaTableDefine(inJsonObject); } -int RelationalSchemaObject::ParseCheckSchemaVersionMode(const JsonObject &inJsonObject) +int RelationalSchemaObject::ParseCheckSchemaVersion(const JsonObject &inJsonObject) { FieldValue fieldValue; int errCode = GetMemberFromJsonObject(inJsonObject, SchemaConstant::KEYWORD_SCHEMA_VERSION, @@ -902,10 +614,6 @@ int RelationalSchemaObject::ParseCheckTableInfo(const JsonObject &inJsonObject) if (errCode != E_OK) { return errCode; } - errCode = ParseCheckTableUnique(inJsonObject, resultTable); - if (errCode != E_OK) { - return errCode; - } errCode = ParseCheckTablePrimaryKey(inJsonObject, resultTable); if (errCode != E_OK) { return errCode; @@ -1008,21 +716,6 @@ int RelationalSchemaObject::ParseCheckTableAutoInc(const JsonObject &inJsonObjec return E_OK; } -int RelationalSchemaObject::ParseCheckTableUnique(const JsonObject &inJsonObject, TableInfo &resultTable) -{ - if (!inJsonObject.IsFieldPathExist(FieldPath {"UNIQUE"})) { // UNIQUE is not necessary - return E_OK; - } - std::vector uniqueArray; - int errCode = inJsonObject.GetArrayContentOfStringOrStringArray(FieldPath {"UNIQUE"}, uniqueArray); - if (errCode != E_OK) { - LOGE("[RelationalSchema][Parse] Get unique array failed: %d.", errCode); - return -E_SCHEMA_PARSE_FAIL; - } - resultTable.SetUniqueDefines(uniqueArray); - return E_OK; -} - int RelationalSchemaObject::ParseCheckTablePrimaryKey(const JsonObject &inJsonObject, TableInfo &resultTable) { FieldValue fieldValue; diff --git a/services/distributeddataservice/libs/distributeddb/common/src/runtime_context.cpp b/services/distributeddataservice/libs/distributeddb/common/src/runtime_context.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/common/src/runtime_context_impl.cpp b/services/distributeddataservice/libs/distributeddb/common/src/runtime_context_impl.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/common/src/runtime_context_impl.h b/services/distributeddataservice/libs/distributeddb/common/src/runtime_context_impl.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/common/src/schema_negotiate.cpp b/services/distributeddataservice/libs/distributeddb/common/src/schema_negotiate.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3bd78a2e4d8f2fa4eab13f49e065b4ed0da4f17b --- /dev/null +++ b/services/distributeddataservice/libs/distributeddb/common/src/schema_negotiate.cpp @@ -0,0 +1,243 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "schema_negotiate.h" + +#include "log_print.h" +#include "schema_utils.h" + +namespace DistributedDB { +// Some principle in current version describe below. (Relative-type will be introduced in future but not involved now) +// 1. PermitSync: Be false may because schemaType-unrecognized, schemaType-different, schema-unparsable, +// schemaVersion-unrecognized, schema-incompatible, and so on. +// 2. RequirePeerConvert: Be true normally when permitSync false, for future possible sync and convert(by remote). +// 3. checkOnReceive: Be false when local is KV-DB, or when local is not KV-DB only if schema type equal as well as +// define equal or remote is the upgradation of local. +SyncOpinion SchemaNegotiate::MakeLocalSyncOpinion(const SchemaObject &localSchema, const std::string &remoteSchema, + uint8_t remoteSchemaType) +{ + SchemaType localType = localSchema.GetSchemaType(); // An invalid schemaObject will return SchemaType::NONE + SchemaType remoteType = ReadSchemaType(remoteSchemaType); + // Logic below only be correct in current version, should be redesigned if new type added in the future + // 1. If remote-type unrecognized(Include Relative-type), Do not permit sync. + if (remoteType == SchemaType::UNRECOGNIZED) { + LOGE("[Schema][Opinion] Remote-type=%u unrecognized.", remoteSchemaType); + return SyncOpinion{false, true, true}; + } + // 2. If local-type is KV(Here remote-type is within recognized), Always permit sync. + if (localType == SchemaType::NONE) { + LOGI("[Schema][Opinion] Local-type KV."); + return SyncOpinion{true, false, false}; + } + // 3. If remote-type is KV(Here local-type can only be JSON or FLATBUFFER), Always permit sync but need check. + if (remoteType == SchemaType::NONE) { + LOGI("[Schema][Opinion] Remote-type KV."); + return SyncOpinion{true, false, true}; + } + // 4. If local-type differ with remote-type(Here both type can only be JSON or FLATBUFFER), Do not permit sync. + if (localType != remoteType) { + LOGE("[Schema][Opinion] Local-type=%s differ remote-type=%s.", SchemaUtils::SchemaTypeString(localType).c_str(), + SchemaUtils::SchemaTypeString(remoteType).c_str()); + return SyncOpinion{false, true, true}; + } + // 5. If schema parse fail, Do not permit sync. + SchemaObject remoteSchemaObj; + int errCode = remoteSchemaObj.ParseFromSchemaString(remoteSchema); + if (errCode != E_OK) { + LOGE("[Schema][Opinion] Parse remote-schema fail, errCode=%d, remote-type=%s.", errCode, + SchemaUtils::SchemaTypeString(remoteType).c_str()); + return SyncOpinion{false, true, true}; + } + // 6. If remote-schema is not incompatible based on local-schema(SchemaDefine Equal), Permit sync and don't check. + errCode = localSchema.CompareAgainstSchemaObject(remoteSchemaObj); + if (errCode != -E_SCHEMA_UNEQUAL_INCOMPATIBLE) { + return SyncOpinion{true, false, false}; + } + // 7. If local-schema is not incompatible based on remote-schema(Can only be COMPATIBLE_UPGRADE), Sync and check. + errCode = remoteSchemaObj.CompareAgainstSchemaObject(localSchema); + if (errCode != -E_SCHEMA_UNEQUAL_INCOMPATIBLE) { + return SyncOpinion{true, false, true}; + } + // 8. Local-schema incompatible with remote-schema mutually. + LOGE("[Schema][Opinion] Local-schema incompatible with remote-schema mutually."); + return SyncOpinion{false, true, true}; +} + +SyncStrategy SchemaNegotiate::ConcludeSyncStrategy(const SyncOpinion &localOpinion, const SyncOpinion &remoteOpinion) +{ + SyncStrategy outStrategy; + // Any side permit sync, the final conclusion is permit sync. + outStrategy.permitSync = (localOpinion.permitSync || remoteOpinion.permitSync); + bool convertConflict = (localOpinion.requirePeerConvert && remoteOpinion.requirePeerConvert); + if (convertConflict) { + outStrategy.permitSync = false; + } + // Responsible for conversion on send now that local do not require remote to do conversion + outStrategy.convertOnSend = (!localOpinion.requirePeerConvert); + // Responsible for conversion on receive since remote will not do conversion on send and require local to convert + outStrategy.convertOnReceive = remoteOpinion.requirePeerConvert; + // Only depend on local opinion + outStrategy.checkOnReceive = localOpinion.checkOnReceive; + LOGI("[Schema][Strategy] PermitSync=%d, SendConvert=%d, ReceiveConvert=%d, ReceiveCheck=%d.", + outStrategy.permitSync, outStrategy.convertOnSend, outStrategy.convertOnReceive, outStrategy.checkOnReceive); + return outStrategy; +} + +RelationalSyncOpinion SchemaNegotiate::MakeLocalSyncOpinion(const RelationalSchemaObject &localSchema, + const std::string &remoteSchema, uint8_t remoteSchemaType) +{ + SchemaType localType = localSchema.GetSchemaType(); + SchemaType remoteType = ReadSchemaType(remoteSchemaType); + if (remoteType == SchemaType::UNRECOGNIZED) { + LOGW("[RelationalSchema][opinion] Remote schema type %d is unrecognized.", remoteSchemaType); + return {}; + } + + if (remoteType != SchemaType::RELATIVE) { + LOGW("[RelationalSchema][opinion] Not support sync with schema type: local-type=[%s] remote-type=[%s]", + SchemaUtils::SchemaTypeString(localType).c_str(), SchemaUtils::SchemaTypeString(remoteType).c_str()); + return {}; + } + + if (!localSchema.IsSchemaValid()) { + LOGW("[RelationalSchema][opinion] Local schema is not valid"); + return {}; + } + + RelationalSchemaObject remoteSchemaObj; + int errCode = remoteSchemaObj.ParseFromSchemaString(remoteSchema); + if (errCode != E_OK) { + LOGW("[RelationalSchema][opinion] Parse remote schema failed %d, remote schema type %s", errCode, + SchemaUtils::SchemaTypeString(remoteType).c_str()); + return {}; + } + + RelationalSyncOpinion opinion; + for (const auto &it : localSchema.GetTables()) { + if (remoteSchemaObj.GetTable(it.first).GetTableName() != it.first) { + LOGW("[RelationalSchema][opinion] Table was missing in remote schema"); + continue; + } + // remote table is compatible(equal or upgrade) based on local table, permit sync and don't need check + errCode = it.second.CompareWithTable(remoteSchemaObj.GetTable(it.first)); + if (errCode != -E_RELATIONAL_TABLE_INCOMPATIBLE) { + opinion[it.first] = {true, false, false}; + continue; + } + // local table is compatible upgrade based on remote table, permit sync and need check + errCode = remoteSchemaObj.GetTable(it.first).CompareWithTable(it.second); + if (errCode != -E_RELATIONAL_TABLE_INCOMPATIBLE) { + opinion[it.first] = {true, false, true}; + continue; + } + // local table is incompatible with remote table mutually, don't permit sync and need check + LOGW("[RelationalSchema][opinion] Local table is incompatible with remote table mutually."); + opinion[it.first] = {false, true, true}; + } + + return opinion; +} + +RelationalSyncStrategy SchemaNegotiate::ConcludeSyncStrategy(const RelationalSyncOpinion &localOpinion, + const RelationalSyncOpinion &remoteOpinion) +{ + RelationalSyncStrategy syncStrategy; + for (const auto &itLocal : localOpinion) { + if (remoteOpinion.find(itLocal.first) == remoteOpinion.end()) { + LOGW("[RelationalSchema][Strategy] Table opinion is not found from remote."); + continue; + } + SyncOpinion localTableOpinion = itLocal.second; + SyncOpinion remoteTableOpinion = remoteOpinion.at(itLocal.first); + syncStrategy[itLocal.first] = ConcludeSyncStrategy(localTableOpinion, remoteTableOpinion); + } + + return syncStrategy; +} + +namespace { + const std::string MAGIC = "relational_opinion"; + const uint32_t SYNC_OPINION_VERSION = 1; +} // namespace + + +uint32_t SchemaNegotiate::CalculateParcelLen(const RelationalSyncOpinion &opinions) +{ + uint64_t len = Parcel::GetStringLen(MAGIC); + len += Parcel::GetUInt32Len(); + len += Parcel::GetUInt32Len(); + len = Parcel::GetEightByteAlign(len); + for (const auto &it : opinions) { + len += Parcel::GetStringLen(it.first); + len += Parcel::GetUInt32Len(); + len += Parcel::GetUInt32Len(); + len = Parcel::GetEightByteAlign(len); + } + if (len > UINT32_MAX) { + return 0; + } + return static_cast(len); +} + +int SchemaNegotiate::SerializeData(const RelationalSyncOpinion &opinions, Parcel &parcel) +{ + (void)parcel.WriteString(MAGIC); + (void)parcel.WriteUInt32(SYNC_OPINION_VERSION); + (void)parcel.WriteUInt32(static_cast(opinions.size())); + (void)parcel.EightByteAlign(); + for (const auto &it : opinions) { + (void)parcel.WriteString(it.first); + (void)parcel.WriteUInt32(it.second.permitSync); + (void)parcel.WriteUInt32(it.second.requirePeerConvert); + (void)parcel.EightByteAlign(); + } + return parcel.IsError() ? -E_INVALID_ARGS : E_OK; +} + +int SchemaNegotiate::DeserializeData(Parcel &parcel, RelationalSyncOpinion &opinion) +{ + if (!parcel.IsContinueRead()) { + return E_OK; + } + std::string magicStr; + (void)parcel.ReadString(magicStr); + if (magicStr != MAGIC) { + LOGE("Deserialize sync opinion failed while read MAGIC string [%s]", magicStr.c_str()); + return -E_INVALID_ARGS; + } + uint32_t version; + (void)parcel.ReadUInt32(version); + if (version != SYNC_OPINION_VERSION) { + LOGE("Not support sync opinion version: %u", version); + return -E_NOT_SUPPORT; + } + uint32_t opinionSize; + (void)parcel.ReadUInt32(opinionSize); + (void)parcel.EightByteAlign(); + for (uint32_t i = 0; i < opinionSize; i++) { + std::string tableName; + SyncOpinion tableOpinion; + (void)parcel.ReadString(tableName); + uint32_t permitSync; + (void)parcel.ReadUInt32(permitSync); + tableOpinion.permitSync = static_cast(permitSync); + uint32_t requirePeerConvert; + (void)parcel.ReadUInt32(requirePeerConvert); + tableOpinion.requirePeerConvert = static_cast(requirePeerConvert); + (void)parcel.EightByteAlign(); + opinion[tableName] = tableOpinion; + } + return parcel.IsError() ? -E_INVALID_ARGS : E_OK; +} +} \ No newline at end of file diff --git a/services/distributeddataservice/libs/distributeddb/common/src/schema_object.cpp b/services/distributeddataservice/libs/distributeddb/common/src/schema_object.cpp old mode 100755 new mode 100644 index 8dc67aa172f69f4d1cdec27e09d7887c7ad973f9..07565295a5f1d193b3640b54492843cd99c0ae47 --- a/services/distributeddataservice/libs/distributeddb/common/src/schema_object.cpp +++ b/services/distributeddataservice/libs/distributeddb/common/src/schema_object.cpp @@ -81,82 +81,6 @@ std::string SchemaObject::GenerateExtractSQL(SchemaType inSchemaType, const Fiel return resultSql; } -// Some principle in current version describe below. (Relative-type will be introduced in future but not involved now) -// 1. PermitSync: Be false may because schemaType-unrecognized, schemaType-different, schema-unparsable, -// schemaVersion-unrecognized, schema-incompatible, and so on. -// 2. RequirePeerConvert: Be true normally when permitSync false, for future possible sync and convert(by remote). -// 3. checkOnReceive: Be false when local is KV-DB, or when local is not KV-DB only if schema type equal as well as -// define equal or remote is the upgradation of local. -SyncOpinion SchemaObject::MakeLocalSyncOpinion(const SchemaObject &localSchema, const std::string &remoteSchema, - uint8_t remoteSchemaType) -{ - SchemaType localType = localSchema.GetSchemaType(); // An invalid schemaObject will return SchemaType::NONE - SchemaType remoteType = ReadSchemaType(remoteSchemaType); - // Logic below only be correct in current version, should be redesigned if new type added in the future - // 1. If remote-type unrecognized(Include Relative-type), Do not permit sync. - if (remoteType == SchemaType::UNRECOGNIZED) { - LOGE("[Schema][Opinion] Remote-type=%u unrecognized.", remoteSchemaType); - return SyncOpinion{false, true, true}; - } - // 2. If local-type is KV(Here remote-type is within recognized), Always permit sync. - if (localType == SchemaType::NONE) { - LOGI("[Schema][Opinion] Local-type KV."); - return SyncOpinion{true, false, false}; - } - // 3. If remote-type is KV(Here local-type can only be JSON or FLATBUFFER), Always permit sync but need check. - if (remoteType == SchemaType::NONE) { - LOGI("[Schema][Opinion] Remote-type KV."); - return SyncOpinion{true, false, true}; - } - // 4. If local-type differ with remote-type(Here both type can only be JSON or FLATBUFFER), Do not permit sync. - if (localType != remoteType) { - LOGE("[Schema][Opinion] Local-type=%s differ remote-type=%s.", SchemaUtils::SchemaTypeString(localType).c_str(), - SchemaUtils::SchemaTypeString(remoteType).c_str()); - return SyncOpinion{false, true, true}; - } - // 5. If schema parse fail, Do not permit sync. - SchemaObject remoteSchemaObj; - int errCode = remoteSchemaObj.ParseFromSchemaString(remoteSchema); - if (errCode != E_OK) { - LOGE("[Schema][Opinion] Parse remote-schema fail, errCode=%d, remote-type=%s.", errCode, - SchemaUtils::SchemaTypeString(remoteType).c_str()); - return SyncOpinion{false, true, true}; - } - // 6. If remote-schema is not incompatible based on local-schema(SchemaDefine Equal), Permit sync and don't check. - errCode = localSchema.CompareAgainstSchemaObject(remoteSchemaObj); - if (errCode != -E_SCHEMA_UNEQUAL_INCOMPATIBLE) { - return SyncOpinion{true, false, false}; - } - // 7. If local-schema is not incompatible based on remote-schema(Can only be COMPATIBLE_UPGRADE), Sync and check. - errCode = remoteSchemaObj.CompareAgainstSchemaObject(localSchema); - if (errCode != -E_SCHEMA_UNEQUAL_INCOMPATIBLE) { - return SyncOpinion{true, false, true}; - } - // 8. Local-schema incompatible with remote-schema mutually. - LOGE("[Schema][Opinion] Local-schema incompatible with remote-schema mutually."); - return SyncOpinion{false, true, true}; -} - -SyncStrategy SchemaObject::ConcludeSyncStrategy(const SyncOpinion &localOpinion, const SyncOpinion &remoteOpinion) -{ - SyncStrategy outStrategy; - // Any side permit sync, the final conclusion is permit sync. - outStrategy.permitSync = (localOpinion.permitSync || remoteOpinion.permitSync); - bool convertConflict = (localOpinion.requirePeerConvert && remoteOpinion.requirePeerConvert); - if (convertConflict) { - outStrategy.permitSync = false; - } - // Responsible for conversion on send now that local do not require remote to do conversion - outStrategy.convertOnSend = (!localOpinion.requirePeerConvert); - // Responsible for conversion on receive since remote will not do conversion on send and require local to convert - outStrategy.convertOnReceive = remoteOpinion.requirePeerConvert; - // Only depend on local opinion - outStrategy.checkOnReceive = localOpinion.checkOnReceive; - LOGI("[Schema][Strategy] PermitSync=%d, SendConvert=%d, ReceiveConvert=%d, ReceiveCheck=%d.", - outStrategy.permitSync, outStrategy.convertOnSend, outStrategy.convertOnReceive, outStrategy.checkOnReceive); - return outStrategy; -} - SchemaObject::SchemaObject() : flatbufferSchema_(*this) {}; SchemaObject::SchemaObject(const SchemaObject &other) @@ -718,7 +642,8 @@ int SchemaObject::ParseCheckSchemaIndexes(const JsonObject& inJsonObject) // The type of SCHEMA_INDEXES field has been checked in CheckMetaFieldCountAndType to be an array // If not all members of the array are string type or string-array, this call will return error std::vector> oriIndexArray; - int errCode = inJsonObject.GetArrayContentOfStringOrStringArray(FieldPath{SchemaConstant::KEYWORD_SCHEMA_INDEXES}, oriIndexArray); + int errCode = inJsonObject.GetArrayContentOfStringOrStringArray(FieldPath{SchemaConstant::KEYWORD_SCHEMA_INDEXES}, + oriIndexArray); if (errCode != E_OK) { LOGE("[Schema][ParseIndex] GetArrayContent Fail, errCode=%d.", errCode); return -E_SCHEMA_PARSE_FAIL; @@ -745,7 +670,8 @@ int SchemaObject::ParseCheckSchemaSkipSize(const JsonObject& inJsonObject) } // The type of SCHEMA_SKIPSIZE field has been checked in CheckMetaFieldCountAndType to be an INTEGER FieldValue skipSizeValue; - int errCode = inJsonObject.GetFieldValueByFieldPath(FieldPath{SchemaConstant::KEYWORD_SCHEMA_SKIPSIZE}, skipSizeValue); + int errCode = inJsonObject.GetFieldValueByFieldPath(FieldPath {SchemaConstant::KEYWORD_SCHEMA_SKIPSIZE}, + skipSizeValue); if (errCode != E_OK) { return -E_INTERNAL_ERROR; } diff --git a/services/distributeddataservice/libs/distributeddb/common/src/schema_utils.cpp b/services/distributeddataservice/libs/distributeddb/common/src/schema_utils.cpp old mode 100755 new mode 100644 index dc18309d5583132253f79ad6f1f91307cd4906e9..802d9f6ade2152111591aed5d563c6371d17ce34 --- a/services/distributeddataservice/libs/distributeddb/common/src/schema_utils.cpp +++ b/services/distributeddataservice/libs/distributeddb/common/src/schema_utils.cpp @@ -23,8 +23,7 @@ #include "schema_constant.h" namespace DistributedDB { -namespace -{ +namespace { bool IsLegalFieldCharacter(char character) { return (std::isalnum(character) || character == '_'); diff --git a/services/distributeddataservice/libs/distributeddb/common/src/task_pool.cpp b/services/distributeddataservice/libs/distributeddb/common/src/task_pool.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/common/src/task_pool_impl.cpp b/services/distributeddataservice/libs/distributeddb/common/src/task_pool_impl.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/common/src/task_queue.cpp b/services/distributeddataservice/libs/distributeddb/common/src/task_queue.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/common/src/task_queue.h b/services/distributeddataservice/libs/distributeddb/common/src/task_queue.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/common/src/time_tick_monitor.cpp b/services/distributeddataservice/libs/distributeddb/common/src/time_tick_monitor.cpp old mode 100755 new mode 100644 index ff8df05c25058b49dd86b669cb1814622bc39d0f..82a8a606a7ef3a8c9780cca7819cd6c36e6293c4 --- a/services/distributeddataservice/libs/distributeddb/common/src/time_tick_monitor.cpp +++ b/services/distributeddataservice/libs/distributeddb/common/src/time_tick_monitor.cpp @@ -116,8 +116,8 @@ int TimeTickMonitor::TimeTick(TimerId timerId) uint64_t monotonicTime = GetMonotonicTime(); uint64_t systemTime = GetSysCurrentTime(); - int64_t monotonicOffset = monotonicTime - lastMonotonicTime_; - int64_t systemOffset = systemTime - lastSystemTime_; + int64_t monotonicOffset = static_cast(monotonicTime - lastMonotonicTime_); + int64_t systemOffset = static_cast(systemTime - lastSystemTime_); lastMonotonicTime_ = monotonicTime; lastSystemTime_ = systemTime; int64_t changedOffset = systemOffset - monotonicOffset; diff --git a/services/distributeddataservice/libs/distributeddb/common/src/time_tick_monitor.h b/services/distributeddataservice/libs/distributeddb/common/src/time_tick_monitor.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/common/src/types_export.cpp b/services/distributeddataservice/libs/distributeddb/common/src/types_export.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/common/src/value_object.cpp b/services/distributeddataservice/libs/distributeddb/common/src/value_object.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/communicator/include/combine_status.h b/services/distributeddataservice/libs/distributeddb/communicator/include/combine_status.h index 017243e3a94db6ac425fe4ca1c4bf17b9f18fcc2..931f84ce0558198ac6feb18fe54a4abe1f812901 100644 --- a/services/distributeddataservice/libs/distributeddb/communicator/include/combine_status.h +++ b/services/distributeddataservice/libs/distributeddb/communicator/include/combine_status.h @@ -17,7 +17,6 @@ #define COMBINE_STATUS_H #include -#include #include namespace DistributedDB { diff --git a/services/distributeddataservice/libs/distributeddb/communicator/include/communicator_type_define.h b/services/distributeddataservice/libs/distributeddb/communicator/include/communicator_type_define.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/communicator/include/frame_combiner.h b/services/distributeddataservice/libs/distributeddb/communicator/include/frame_combiner.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/communicator/include/frame_retainer.h b/services/distributeddataservice/libs/distributeddb/communicator/include/frame_retainer.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/communicator/include/icommunicator.h b/services/distributeddataservice/libs/distributeddb/communicator/include/icommunicator.h index 9d23e31c15802a88a3b9428fce89a92e2014523c..84fbed366dda2158fd198e6d0aa15e18cea05bb0 100644 --- a/services/distributeddataservice/libs/distributeddb/communicator/include/icommunicator.h +++ b/services/distributeddataservice/libs/distributeddb/communicator/include/icommunicator.h @@ -26,11 +26,13 @@ namespace DistributedDB { // inMsg is heap memory, its ownership transfers by calling OnMessageCallback using OnMessageCallback = std::function; +constexpr uint32_t SEND_TIME_OUT = 3000; // 3s + struct SendConfig { - bool nonBlock; - uint32_t timeout; - ExtendInfo paramInfo; + bool nonBlock = false; bool isNeedExtendHead = false; + uint32_t timeout = SEND_TIME_OUT; + ExtendInfo paramInfo; }; class ICommunicator : public virtual RefObject { diff --git a/services/distributeddataservice/libs/distributeddb/communicator/include/message.h b/services/distributeddataservice/libs/distributeddb/communicator/include/message.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/communicator/include/message_transform.h b/services/distributeddataservice/libs/distributeddb/communicator/include/message_transform.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/communicator/include/parse_result.h b/services/distributeddataservice/libs/distributeddb/communicator/include/parse_result.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/communicator/include/send_task_scheduler.h b/services/distributeddataservice/libs/distributeddb/communicator/include/send_task_scheduler.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/communicator/src/combine_status.cpp b/services/distributeddataservice/libs/distributeddb/communicator/src/combine_status.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/communicator/src/communicator.cpp b/services/distributeddataservice/libs/distributeddb/communicator/src/communicator.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/communicator/src/communicator_aggregator.cpp b/services/distributeddataservice/libs/distributeddb/communicator/src/communicator_aggregator.cpp old mode 100755 new mode 100644 index 019153c6a824a7aca70f9ea2cf11daf5b0848f53..5614b31a905da62f74f870aadb72e8e10998e508 --- a/services/distributeddataservice/libs/distributeddb/communicator/src/communicator_aggregator.cpp +++ b/services/distributeddataservice/libs/distributeddb/communicator/src/communicator_aggregator.cpp @@ -417,7 +417,7 @@ int CommunicatorAggregator::RetryUntilTimeout(SendTask &inTask, uint32_t timeout int errCode = scheduler_.AddSendTaskIntoSchedule(inTask, inPrio); if (errCode != E_OK) { bool notTimeout = true; - auto retryFunc = [this, inPrio, &inTask]()->bool{ + auto retryFunc = [this, inPrio, &inTask]()->bool { if (this->shutdown_) { delete inTask.buffer; inTask.buffer = nullptr; diff --git a/services/distributeddataservice/libs/distributeddb/communicator/src/communicator_linker.cpp b/services/distributeddataservice/libs/distributeddb/communicator/src/communicator_linker.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/communicator/src/communicator_linker.h b/services/distributeddataservice/libs/distributeddb/communicator/src/communicator_linker.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/communicator/src/frame_combiner.cpp b/services/distributeddataservice/libs/distributeddb/communicator/src/frame_combiner.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/communicator/src/frame_retainer.cpp b/services/distributeddataservice/libs/distributeddb/communicator/src/frame_retainer.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/communicator/src/header_converter.cpp b/services/distributeddataservice/libs/distributeddb/communicator/src/header_converter.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/communicator/src/message_transform.cpp b/services/distributeddataservice/libs/distributeddb/communicator/src/message_transform.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/communicator/src/network_adapter.cpp b/services/distributeddataservice/libs/distributeddb/communicator/src/network_adapter.cpp old mode 100755 new mode 100644 index 7862b8cdc4c771cac22543c602e7b9315e2f9dbc..964676f36fdaab3c5850bf89a44b0b031a81c139 --- a/services/distributeddataservice/libs/distributeddb/communicator/src/network_adapter.cpp +++ b/services/distributeddataservice/libs/distributeddb/communicator/src/network_adapter.cpp @@ -209,7 +209,7 @@ int NetworkAdapter::SendBytes(const std::string &dstTarget, const uint8_t *bytes if (bytes == nullptr || length == 0) { return -E_INVALID_ARGS; } - LOGI("[NAdapt][SendBytes] Enter, to=%s{private}, length=%d", dstTarget.c_str(), length); + LOGI("[NAdapt][SendBytes] Enter, to=%s{private}, length=%u", dstTarget.c_str(), length); DeviceInfos dstDevInfo; dstDevInfo.identifier = dstTarget; DBStatus errCode = processCommunicator_->SendData(dstDevInfo, bytes, length); diff --git a/services/distributeddataservice/libs/distributeddb/communicator/src/protocol_proto.cpp b/services/distributeddataservice/libs/distributeddb/communicator/src/protocol_proto.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/communicator/src/send_task_scheduler.cpp b/services/distributeddataservice/libs/distributeddb/communicator/src/send_task_scheduler.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/communicator/src/serial_buffer.cpp b/services/distributeddataservice/libs/distributeddb/communicator/src/serial_buffer.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/include/auto_launch_export.h b/services/distributeddataservice/libs/distributeddb/include/auto_launch_export.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/include/query.h b/services/distributeddataservice/libs/distributeddb/include/query.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/include/query_expression.h b/services/distributeddataservice/libs/distributeddb/include/query_expression.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/include/types_export.h b/services/distributeddataservice/libs/distributeddb/include/types_export.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/interfaces/include/iprocess_communicator.h b/services/distributeddataservice/libs/distributeddb/interfaces/include/iprocess_communicator.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/interfaces/include/iprocess_system_api_adapter.h b/services/distributeddataservice/libs/distributeddb/interfaces/include/iprocess_system_api_adapter.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/interfaces/include/kv_store_delegate.h b/services/distributeddataservice/libs/distributeddb/interfaces/include/kv_store_delegate.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/interfaces/include/kv_store_delegate_manager.h b/services/distributeddataservice/libs/distributeddb/interfaces/include/kv_store_delegate_manager.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/interfaces/include/kv_store_nb_delegate.h b/services/distributeddataservice/libs/distributeddb/interfaces/include/kv_store_nb_delegate.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/interfaces/include/kv_store_snapshot_delegate.h b/services/distributeddataservice/libs/distributeddb/interfaces/include/kv_store_snapshot_delegate.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/interfaces/include/store_types.h b/services/distributeddataservice/libs/distributeddb/interfaces/include/store_types.h old mode 100755 new mode 100644 index 1633151772f24a12c72e7c4c5da859b8a0152bb3..2fb7194923415a40b858193ed830d13883c7a045 --- a/services/distributeddataservice/libs/distributeddb/interfaces/include/store_types.h +++ b/services/distributeddataservice/libs/distributeddb/interfaces/include/store_types.h @@ -61,6 +61,7 @@ enum DBStatus { DISTRIBUTED_SCHEMA_CHANGED, // the schema was changed MODE_MISMATCH, NOT_ACTIVE, + USER_CHANGED, }; struct KvStoreConfig { diff --git a/services/distributeddataservice/libs/distributeddb/interfaces/src/kv_store_changed_data_impl.cpp b/services/distributeddataservice/libs/distributeddb/interfaces/src/kv_store_changed_data_impl.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/interfaces/src/kv_store_delegate_impl.cpp b/services/distributeddataservice/libs/distributeddb/interfaces/src/kv_store_delegate_impl.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/interfaces/src/kv_store_delegate_impl.h b/services/distributeddataservice/libs/distributeddb/interfaces/src/kv_store_delegate_impl.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/interfaces/src/kv_store_delegate_manager.cpp b/services/distributeddataservice/libs/distributeddb/interfaces/src/kv_store_delegate_manager.cpp old mode 100755 new mode 100644 index 6dff4d5e7ec2abd8483b4953a7e5ab1a676ff1b9..b9afb3c96d16ddf3a1e103684a68a247047686f4 --- a/services/distributeddataservice/libs/distributeddb/interfaces/src/kv_store_delegate_manager.cpp +++ b/services/distributeddataservice/libs/distributeddb/interfaces/src/kv_store_delegate_manager.cpp @@ -528,7 +528,7 @@ DBStatus KvStoreDelegateManager::EnableKvStoreAutoLaunch(const std::string &user } AutoLaunchParam param{ userId, appId, storeId, option, notifier, {}}; std::shared_ptr ptr = std::make_shared(); - int errCode = AutoLaunch::GetAutoLaunchProperties(param, DBType::DB_KV, ptr); + int errCode = AutoLaunch::GetAutoLaunchProperties(param, DBType::DB_KV, true, ptr); if (errCode != E_OK) { LOGE("[KvStoreManager] Enable auto launch failed:%d", errCode); return TransferDBErrno(errCode); diff --git a/services/distributeddataservice/libs/distributeddb/interfaces/src/kv_store_errno.cpp b/services/distributeddataservice/libs/distributeddb/interfaces/src/kv_store_errno.cpp old mode 100755 new mode 100644 index a8aa97a481d107fa2adb05eaf4da4f8722ca245c..77384a55e36436b0c7bb41285492a2a197b9d417 --- a/services/distributeddataservice/libs/distributeddb/interfaces/src/kv_store_errno.cpp +++ b/services/distributeddataservice/libs/distributeddb/interfaces/src/kv_store_errno.cpp @@ -56,7 +56,7 @@ namespace { { -E_DISTRIBUTED_SCHEMA_NOT_FOUND, DISTRIBUTED_SCHEMA_NOT_FOUND}, { -E_DISTRIBUTED_SCHEMA_CHANGED, DISTRIBUTED_SCHEMA_CHANGED}, { -E_MODE_MISMATCH, MODE_MISMATCH}, - { -E_NOT_INIT, NOT_ACTIVE}, + { -E_NO_NEED_ACTIVE, NOT_ACTIVE}, }; } diff --git a/services/distributeddataservice/libs/distributeddb/interfaces/src/kv_store_nb_conflict_data_impl.cpp b/services/distributeddataservice/libs/distributeddb/interfaces/src/kv_store_nb_conflict_data_impl.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/interfaces/src/kv_store_nb_delegate_impl.cpp b/services/distributeddataservice/libs/distributeddb/interfaces/src/kv_store_nb_delegate_impl.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/interfaces/src/kv_store_nb_delegate_impl.h b/services/distributeddataservice/libs/distributeddb/interfaces/src/kv_store_nb_delegate_impl.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/interfaces/src/kv_store_result_set_impl.cpp b/services/distributeddataservice/libs/distributeddb/interfaces/src/kv_store_result_set_impl.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/interfaces/src/kv_store_snapshot_delegate_impl.cpp b/services/distributeddataservice/libs/distributeddb/interfaces/src/kv_store_snapshot_delegate_impl.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/interfaces/src/kv_store_snapshot_delegate_impl.h b/services/distributeddataservice/libs/distributeddb/interfaces/src/kv_store_snapshot_delegate_impl.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/interfaces/src/relational/relational_store_delegate_impl.cpp b/services/distributeddataservice/libs/distributeddb/interfaces/src/relational/relational_store_delegate_impl.cpp index cc526ccd9d5ced5c1b3cc6936023bc0d4115c702..2d44ee6c7057aa3251ebfa873171973f4913771a 100644 --- a/services/distributeddataservice/libs/distributeddb/interfaces/src/relational/relational_store_delegate_impl.cpp +++ b/services/distributeddataservice/libs/distributeddb/interfaces/src/relational/relational_store_delegate_impl.cpp @@ -90,7 +90,7 @@ DBStatus RelationalStoreDelegateImpl::RemoveDeviceData(const std::string &device if (device.empty() || device.length() > DBConstant::MAX_DEV_LENGTH || !ParamCheckUtils::CheckRelationalTableName(tableName)) { - LOGE("[RelationalStore Delegate] Remove device data with invald device name or table name."); + LOGE("[RelationalStore Delegate] Remove device data with invalid device name or table name."); return INVALID_ARGS; } diff --git a/services/distributeddataservice/libs/distributeddb/interfaces/src/relational/relational_store_instance.h b/services/distributeddataservice/libs/distributeddb/interfaces/src/relational/relational_store_instance.h index 0bdc2aa93c1f0c9bec8163b136f871c4d1728a1c..5d9733a567da3352a7d3fad80ebc15278c43819e 100644 --- a/services/distributeddataservice/libs/distributeddb/interfaces/src/relational/relational_store_instance.h +++ b/services/distributeddataservice/libs/distributeddb/interfaces/src/relational/relational_store_instance.h @@ -42,7 +42,7 @@ private: IRelationalStore *OpenDatabase(const RelationalDBProperties &properties, int &errCode); void RemoveKvDBFromCache(const RelationalDBProperties &properties); - void SaveKvDBToCache(IRelationalStore *store, const RelationalDBProperties &properties); + void SaveRelationalDBToCache(IRelationalStore *store, const RelationalDBProperties &properties); void EnterDBOpenCloseProcess(const std::string &identifier); void ExitDBOpenCloseProcess(const std::string &identifier); diff --git a/services/distributeddataservice/libs/distributeddb/interfaces/src/relational/relational_store_sqlite_ext.cpp b/services/distributeddataservice/libs/distributeddb/interfaces/src/relational/relational_store_sqlite_ext.cpp index b22eb7479bae4c9d187f5044a672a2fb3aeaff21..d66f4b93dc7d1183a316c44a5383a530f8d2789a 100644 --- a/services/distributeddataservice/libs/distributeddb/interfaces/src/relational/relational_store_sqlite_ext.cpp +++ b/services/distributeddataservice/libs/distributeddb/interfaces/src/relational/relational_store_sqlite_ext.cpp @@ -132,10 +132,10 @@ public: } } - static TimeStamp GetTime(TimeOffset TimeOffset) + static TimeStamp GetTime(TimeOffset timeOffset) { TimeStamp currentSysTime = GetSysCurrentTime(); - TimeStamp currentLocalTime = currentSysTime + TimeOffset; + TimeStamp currentLocalTime = currentSysTime + timeOffset; std::lock_guard lock(lastLocalTimeLock_); if (currentLocalTime <= lastLocalTime_ || currentLocalTime > MAX_VALID_TIME) { lastLocalTime_++; diff --git a/services/distributeddataservice/libs/distributeddb/interfaces/src/relational/relational_sync_able_storage.h b/services/distributeddataservice/libs/distributeddb/interfaces/src/relational/relational_sync_able_storage.h index 66fec6748fc9c6dae10f19a1eac9d96f87a35577..7cc8317458d0306bf88c4b39aa71f39342a995ec 100644 --- a/services/distributeddataservice/libs/distributeddb/interfaces/src/relational/relational_sync_able_storage.h +++ b/services/distributeddataservice/libs/distributeddb/interfaces/src/relational/relational_sync_able_storage.h @@ -130,7 +130,7 @@ private: // data SQLiteSingleRelationalStorageEngine *storageEngine_ = nullptr; TimeStamp currentMaxTimeStamp_ = 0; - KvDBProperties properties; + KvDBProperties properties_; mutable std::mutex maxTimeStampMutex_; std::function onSchemaChanged_; diff --git a/services/distributeddataservice/libs/distributeddb/storage/include/db_properties.h b/services/distributeddataservice/libs/distributeddb/storage/include/db_properties.h index 32b4d57724673415cf4500459ea7f0ffc029401b..6b7be4a0bd3ff3d25c4bed2591067cc5fe8e472c 100644 --- a/services/distributeddataservice/libs/distributeddb/storage/include/db_properties.h +++ b/services/distributeddataservice/libs/distributeddb/storage/include/db_properties.h @@ -17,7 +17,6 @@ #include #include -#include namespace DistributedDB { class DBProperties { diff --git a/services/distributeddataservice/libs/distributeddb/storage/include/ikvdb_connection.h b/services/distributeddataservice/libs/distributeddb/storage/include/ikvdb_connection.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/storage/include/ikvdb_factory.h b/services/distributeddataservice/libs/distributeddb/storage/include/ikvdb_factory.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/storage/include/ikvdb_result_set.h b/services/distributeddataservice/libs/distributeddb/storage/include/ikvdb_result_set.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/storage/include/kvdb_manager.h b/services/distributeddataservice/libs/distributeddb/storage/include/kvdb_manager.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/storage/include/kvdb_pragma.h b/services/distributeddataservice/libs/distributeddb/storage/include/kvdb_pragma.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/storage/include/kvdb_properties.h b/services/distributeddataservice/libs/distributeddb/storage/include/kvdb_properties.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/storage/include/multi_ver_kvdb_sync_interface.h b/services/distributeddataservice/libs/distributeddb/storage/include/multi_ver_kvdb_sync_interface.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/storage/include/multi_ver_vacuum.h b/services/distributeddataservice/libs/distributeddb/storage/include/multi_ver_vacuum.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/storage/include/relational_db_sync_interface.h b/services/distributeddataservice/libs/distributeddb/storage/include/relational_db_sync_interface.h index 81e8fb3d84133d6fecf6b28575b3f77d19f146d4..4f82e6e313c396c02f2a8b246efefd32e3507eab 100644 --- a/services/distributeddataservice/libs/distributeddb/storage/include/relational_db_sync_interface.h +++ b/services/distributeddataservice/libs/distributeddb/storage/include/relational_db_sync_interface.h @@ -20,6 +20,7 @@ #include "relational_schema_object.h" #include "single_ver_kv_entry.h" #include "sync_generic_interface.h" +#include "schema_negotiate.h" namespace DistributedDB { class RelationalDBSyncInterface : public SyncGenericInterface { diff --git a/services/distributeddataservice/libs/distributeddb/storage/include/single_ver_kvdb_sync_interface.h b/services/distributeddataservice/libs/distributeddb/storage/include/single_ver_kvdb_sync_interface.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/storage/include/storage_engine_manager.h b/services/distributeddataservice/libs/distributeddb/storage/include/storage_engine_manager.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/data_transformer.cpp b/services/distributeddataservice/libs/distributeddb/storage/src/data_transformer.cpp index 657d5a8b4e605951afa1315765783c3b1d7289b8..a019cbda930a9440ac411e103138c12b558a1cba 100644 --- a/services/distributeddataservice/libs/distributeddb/storage/src/data_transformer.cpp +++ b/services/distributeddataservice/libs/distributeddb/storage/src/data_transformer.cpp @@ -47,10 +47,10 @@ int DataTransformer::TransformDataItem(const std::vector &dataItems, return E_OK; } std::vector indexMapping; - ReduceMapping(remoteFieldInfo, localFieldInfo, indexMapping); + ReduceMapping(remoteFieldInfo, localFieldInfo); for (const DataItem &dataItem : dataItems) { OptRowDataWithLog dataWithLog; - int errCode = DeSerializeDataItem(dataItem, dataWithLog, remoteFieldInfo, indexMapping); + int errCode = DeSerializeDataItem(dataItem, dataWithLog, remoteFieldInfo); if (errCode != E_OK) { return errCode; } @@ -77,11 +77,11 @@ int DataTransformer::SerializeDataItem(const RowDataWithLog &data, } int DataTransformer::DeSerializeDataItem(const DataItem &dataItem, OptRowDataWithLog &data, - const std::vector &remoteFieldInfo, std::vector &indexMapping) + const std::vector &remoteFieldInfo) { - int errCode; - if ((dataItem.flag & DataItem::DELETE_FLAG) == 0) { - errCode = DeSerializeValue(dataItem.value, data.optionalData, remoteFieldInfo, indexMapping); + if ((dataItem.flag & DataItem::DELETE_FLAG) == 0 && + (dataItem.flag & DataItem::REMOTE_DEVICE_DATA_MISS_QUERY) == 0) { + int errCode = DeSerializeValue(dataItem.value, data.optionalData, remoteFieldInfo); if (errCode != E_OK) { return errCode; } @@ -101,7 +101,6 @@ uint32_t DataTransformer::CalDataValueLength(const DataValue &dataValue) { static std::map lengthMap = { { StorageType::STORAGE_TYPE_NULL, Parcel::GetUInt32Len()}, - { StorageType::STORAGE_TYPE_BOOL, Parcel::GetBoolLen()}, { StorageType::STORAGE_TYPE_INTEGER, Parcel::GetInt64Len()}, { StorageType::STORAGE_TYPE_REAL, Parcel::GetDoubleLen()} }; @@ -127,20 +126,13 @@ uint32_t DataTransformer::CalDataValueLength(const DataValue &dataValue) } void DataTransformer::ReduceMapping(const std::vector &remoteFieldInfo, - const std::vector &localFieldInfo, std::vector &indexMapping) + const std::vector &localFieldInfo) { std::map fieldMap; for (int i = 0; i < static_cast(remoteFieldInfo.size()); ++i) { const auto &fieldInfo = remoteFieldInfo[i]; fieldMap[fieldInfo.GetFieldName()] = i; } - for (const auto &fieldInfo : localFieldInfo) { - if (fieldMap.find(fieldInfo.GetFieldName()) == fieldMap.end()) { - indexMapping.push_back(-E_NOT_FOUND); - continue; - } - indexMapping.push_back(fieldMap[fieldInfo.GetFieldName()]); - } } namespace { @@ -160,24 +152,6 @@ int DeSerializeNullValue(DataValue &dataValue, Parcel &parcel) return E_OK; } -int SerializeBoolValue(const DataValue &dataValue, Parcel &parcel) -{ - bool val = false; - (void)dataValue.GetBool(val); - return parcel.WriteBool(val); -} - -int DeSerializeBoolValue(DataValue &dataValue, Parcel &parcel) -{ - bool val = false; - (void)parcel.ReadBool(val); - if (parcel.IsError()) { - return -E_PARSE_FAIL; - } - dataValue = val; - return E_OK; -} - int SerializeIntValue(const DataValue &dataValue, Parcel &parcel) { int64_t val = 0; @@ -281,7 +255,7 @@ int DeSerializeTextValue(DataValue &dataValue, Parcel &parcel) int SerializeDataValue(const DataValue &dataValue, Parcel &parcel) { static const std::function funcs[] = { - SerializeNullValue, SerializeBoolValue, SerializeIntValue, + SerializeNullValue, SerializeIntValue, SerializeDoubleValue, SerializeTextValue, SerializeBlobValue, }; StorageType type = dataValue.GetType(); @@ -296,7 +270,7 @@ int SerializeDataValue(const DataValue &dataValue, Parcel &parcel) int DeserializeDataValue(DataValue &dataValue, Parcel &parcel) { static const std::function funcs[] = { - DeSerializeNullValue, DeSerializeBoolValue, DeSerializeIntValue, + DeSerializeNullValue, DeSerializeIntValue, DeSerializeDoubleValue, DeSerializeTextValue, DeSerializeBlobValue, }; uint32_t type = 0; @@ -341,9 +315,8 @@ int DataTransformer::SerializeValue(Value &value, const RowData &rowData, const } int DataTransformer::DeSerializeValue(const Value &value, OptRowData &optionalData, - const std::vector &remoteFieldInfo, std::vector &indexMapping) + const std::vector &remoteFieldInfo) { - (void)indexMapping; Parcel parcel(const_cast(value.data()), value.size()); uint64_t fieldCount = 0; (void)parcel.ReadUInt64(fieldCount); diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/data_transformer.h b/services/distributeddataservice/libs/distributeddb/storage/src/data_transformer.h index 4d190e39db9a2cbf888ae41e0c553c5057b4ce18..92774ce5bbcefdd7178c3ce0323e825bb64a66c2 100644 --- a/services/distributeddataservice/libs/distributeddb/storage/src/data_transformer.h +++ b/services/distributeddataservice/libs/distributeddb/storage/src/data_transformer.h @@ -27,7 +27,7 @@ using RowData = std::vector; using OptRowData = std::vector; struct LogInfo { - int dataKey = -1; + int64_t dataKey = -1; std::string device; std::string originDev; TimeStamp timestamp = 0; @@ -66,14 +66,14 @@ public: static int SerializeDataItem(const RowDataWithLog &data, const std::vector &fieldInfo, DataItem &dataItem); static int DeSerializeDataItem(const DataItem &dataItem, OptRowDataWithLog &data, - const std::vector &remoteFieldInfo, std::vector &indexMapping); + const std::vector &remoteFieldInfo); static void ReduceMapping(const std::vector &remoteFieldInfo, - const std::vector &localFieldInfo, std::vector &indexMapping); + const std::vector &localFieldInfo); private: static int SerializeValue(Value &value, const RowData &rowData, const std::vector &fieldInfoList); static int DeSerializeValue(const Value &value, OptRowData &optionalData, - const std::vector &remoteFieldInfo, std::vector &indexMapping); + const std::vector &remoteFieldInfo); static uint32_t CalDataValueLength(const DataValue &dataValue); }; diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/default_factory.cpp b/services/distributeddataservice/libs/distributeddb/storage/src/default_factory.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/default_factory.h b/services/distributeddataservice/libs/distributeddb/storage/src/default_factory.h old mode 100755 new mode 100644 index fa3b4f73c0dd6d70bb5c45c4ab00af21e118d6f0..975a00679db774a778bfa0f504085b6ba216185c --- a/services/distributeddataservice/libs/distributeddb/storage/src/default_factory.h +++ b/services/distributeddataservice/libs/distributeddb/storage/src/default_factory.h @@ -22,7 +22,7 @@ namespace DistributedDB { class DefaultFactory final : public IKvDBFactory { public: - DefaultFactory() {} + DefaultFactory() noexcept {} ~DefaultFactory() override {} DISABLE_COPY_ASSIGN_MOVE(DefaultFactory); diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/generic_kvdb.cpp b/services/distributeddataservice/libs/distributeddb/storage/src/generic_kvdb.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/generic_kvdb.h b/services/distributeddataservice/libs/distributeddb/storage/src/generic_kvdb.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/generic_kvdb_connection.cpp b/services/distributeddataservice/libs/distributeddb/storage/src/generic_kvdb_connection.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/generic_kvdb_connection.h b/services/distributeddataservice/libs/distributeddb/storage/src/generic_kvdb_connection.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/generic_single_ver_kv_entry.cpp b/services/distributeddataservice/libs/distributeddb/storage/src/generic_single_ver_kv_entry.cpp old mode 100755 new mode 100644 index b1359bf7c1dc05686e1d1530ad8c83659240cf1c..7b0a111552ebe10f5395f694be5abc379640b8b1 --- a/services/distributeddataservice/libs/distributeddb/storage/src/generic_single_ver_kv_entry.cpp +++ b/services/distributeddataservice/libs/distributeddb/storage/src/generic_single_ver_kv_entry.cpp @@ -22,14 +22,6 @@ #include "version.h" namespace DistributedDB { -namespace { - enum OperType { - SERIALIZE, - DESERIALIZE, - CAL_LEN, - }; -} // namespace - GenericSingleVerKvEntry::GenericSingleVerKvEntry() { } @@ -126,7 +118,7 @@ int GenericSingleVerKvEntry::SerializeData(Parcel &parcel, uint32_t targetVersio if (errCode != E_OK) { return errCode; } - errCode = AdaptToVersion(SERIALIZE, targetVersion, parcel, len); + errCode = AdaptToVersion(OperType::SERIALIZE, targetVersion, parcel, len); if (errCode != E_OK) { return errCode; } @@ -160,7 +152,7 @@ int GenericSingleVerKvEntry::SerializeDatas(const std::vector INT32_MAX) || (errCode != E_OK)) { return 0; } @@ -193,7 +185,7 @@ int GenericSingleVerKvEntry::DeSerializeData(Parcel &parcel) if (parcel.IsError()) { return 0; } - int errCode = AdaptToVersion(DESERIALIZE, version, parcel, len); + int errCode = AdaptToVersion(OperType::DESERIALIZE, version, parcel, len); if (errCode != E_OK) { len = 0; } @@ -231,17 +223,18 @@ END: return len; } -int GenericSingleVerKvEntry::AdaptToVersion(int operType, uint32_t targetVersion, Parcel &parcel, uint64_t &datalen) +int GenericSingleVerKvEntry::AdaptToVersion(OperType operType, uint32_t targetVersion, Parcel &parcel, + uint64_t &datalen) { if (targetVersion < SOFTWARE_VERSION_EARLIEST || targetVersion > SOFTWARE_VERSION_CURRENT) { return -E_VERSION_NOT_SUPPORT; } int errCode = E_OK; switch (operType) { - case SERIALIZE: + case OperType::SERIALIZE: errCode = SerializeDataByVersion(targetVersion, parcel); break; - case DESERIALIZE: + case OperType::DESERIALIZE: errCode = DeSerializeByVersion(targetVersion, parcel, datalen); break; default: @@ -251,13 +244,13 @@ int GenericSingleVerKvEntry::AdaptToVersion(int operType, uint32_t targetVersion return errCode; } -int GenericSingleVerKvEntry::AdaptToVersion(int operType, uint32_t targetVersion, uint64_t &datalen) +int GenericSingleVerKvEntry::AdaptToVersion(OperType operType, uint32_t targetVersion, uint64_t &datalen) { if (targetVersion < SOFTWARE_VERSION_EARLIEST || targetVersion > SOFTWARE_VERSION_CURRENT) { return -E_VERSION_NOT_SUPPORT; } - if (operType == CAL_LEN) { + if (operType == OperType::CAL_LEN) { return CalLenByVersion(targetVersion, datalen); } else { LOGE("Unknown upgrade serialize oper!"); diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/generic_single_ver_kv_entry.h b/services/distributeddataservice/libs/distributeddb/storage/src/generic_single_ver_kv_entry.h index 67c036e17baf91552a9b932f8251723bf8559cc6..1bf10395b81b014257bdf80e3a90bf6e4a9144da 100644 --- a/services/distributeddataservice/libs/distributeddb/storage/src/generic_single_ver_kv_entry.h +++ b/services/distributeddataservice/libs/distributeddb/storage/src/generic_single_ver_kv_entry.h @@ -84,8 +84,13 @@ public: static int DeSerializeCompressedDatas(std::vector &kvEntries, Parcel &parcel); private: - int AdaptToVersion(int operType, uint32_t targetVersion, Parcel &parcel, uint64_t &datalen); - int AdaptToVersion(int operType, uint32_t targetVersion, uint64_t &datalen); + enum class OperType { + SERIALIZE, + DESERIALIZE, + CAL_LEN, + }; + int AdaptToVersion(OperType operType, uint32_t targetVersion, Parcel &parcel, uint64_t &datalen); + int AdaptToVersion(OperType operType, uint32_t targetVersion, uint64_t &datalen); int SerializeDataByVersion(uint32_t targetVersion, Parcel &parcel) const; int SerializeDataByFirstVersion(Parcel &parcel) const; diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/ikvdb_factory.cpp b/services/distributeddataservice/libs/distributeddb/storage/src/ikvdb_factory.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/kvdb_commit_notify_filterable_data.cpp b/services/distributeddataservice/libs/distributeddb/storage/src/kvdb_commit_notify_filterable_data.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/kvdb_commit_notify_filterable_data.h b/services/distributeddataservice/libs/distributeddb/storage/src/kvdb_commit_notify_filterable_data.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/kvdb_manager.cpp b/services/distributeddataservice/libs/distributeddb/storage/src/kvdb_manager.cpp old mode 100755 new mode 100644 index 0814b865d96366f2e86e7aaef593d5fe3645fe33..b6b589db49d6b190e9c2b3454c2d6b6668b1a101 --- a/services/distributeddataservice/libs/distributeddb/storage/src/kvdb_manager.cpp +++ b/services/distributeddataservice/libs/distributeddb/storage/src/kvdb_manager.cpp @@ -566,7 +566,7 @@ int KvDBManager::RemoveDatabase(const KvDBProperties &properties) if (errCode != E_OK) { LOGE("[KvDBManager] Remove database failed:%d", errCode); } - int err = KvDBManager::UnlockDB(properties); // unlock and delete lock file befor delete dir + int err = KvDBManager::UnlockDB(properties); // unlock and delete lock file before delete dir if (err != E_OK) { LOGE("[KvDBManager][RemoveDatabase] UnlockDB failed:%d, errno:%d", err, errno); errCode = err; diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/kvdb_observer_handle.cpp b/services/distributeddataservice/libs/distributeddb/storage/src/kvdb_observer_handle.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/kvdb_properties.cpp b/services/distributeddataservice/libs/distributeddb/storage/src/kvdb_properties.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/kvdb_utils.cpp b/services/distributeddataservice/libs/distributeddb/storage/src/kvdb_utils.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/kvdb_windowed_result_set.cpp b/services/distributeddataservice/libs/distributeddb/storage/src/kvdb_windowed_result_set.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/kvdb_windowed_result_set.h b/services/distributeddataservice/libs/distributeddb/storage/src/kvdb_windowed_result_set.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/multiver/generic_multi_ver_kv_entry.cpp b/services/distributeddataservice/libs/distributeddb/storage/src/multiver/generic_multi_ver_kv_entry.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/multiver/generic_multi_ver_kv_entry.h b/services/distributeddataservice/libs/distributeddb/storage/src/multiver/generic_multi_ver_kv_entry.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/multiver/ikvdb_multi_ver_data_storage.h b/services/distributeddataservice/libs/distributeddb/storage/src/multiver/ikvdb_multi_ver_data_storage.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/multiver/ikvdb_multi_ver_transaction.h b/services/distributeddataservice/libs/distributeddb/storage/src/multiver/ikvdb_multi_ver_transaction.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/multiver/multi_ver_commit.cpp b/services/distributeddataservice/libs/distributeddb/storage/src/multiver/multi_ver_commit.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/multiver/multi_ver_commit.h b/services/distributeddataservice/libs/distributeddb/storage/src/multiver/multi_ver_commit.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/multiver/multi_ver_kv_entry.h b/services/distributeddataservice/libs/distributeddb/storage/src/multiver/multi_ver_kv_entry.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/multiver/multi_ver_kvdata_storage.cpp b/services/distributeddataservice/libs/distributeddb/storage/src/multiver/multi_ver_kvdata_storage.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/multiver/multi_ver_kvdata_storage.h b/services/distributeddataservice/libs/distributeddb/storage/src/multiver/multi_ver_kvdata_storage.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/multiver/multi_ver_natural_store.cpp b/services/distributeddataservice/libs/distributeddb/storage/src/multiver/multi_ver_natural_store.cpp old mode 100755 new mode 100644 index 49e082efb1cb031d72b76f79861e71cdf2b54225..a492db363ed7d3b8acb50fb338744585017befd2 --- a/services/distributeddataservice/libs/distributeddb/storage/src/multiver/multi_ver_natural_store.cpp +++ b/services/distributeddataservice/libs/distributeddb/storage/src/multiver/multi_ver_natural_store.cpp @@ -902,7 +902,7 @@ int MultiVerNaturalStore::CompareVerDataAndLog(IKvDBMultiVerTransaction *transac return errCode; } - // compare the version; + // compare the version if (commitHead->GetCommitVersion() < maxLocalVersion) { LOGD("Delete entries"); errCode = transaction->ClearEntriesByVersion(maxLocalVersion); @@ -934,7 +934,7 @@ MultiVerStorageExecutor *MultiVerNaturalStore::GetHandle(bool isWrite, int &errC } if (isWrite && !isTrimming) { - // stop the trimming; + // stop the trimming shadowTrimmer_.Pause(GetStringIdentifier()); } StorageExecutor *handle = nullptr; @@ -946,7 +946,7 @@ MultiVerStorageExecutor *MultiVerNaturalStore::GetHandle(bool isWrite, int &errC if (handle == nullptr) { if (isWrite && !isTrimming) { - // restart the trimming; + // restart the trimming shadowTrimmer_.Continue(GetStringIdentifier(), false); } } else { @@ -1184,11 +1184,13 @@ int MultiVerNaturalStore::GetVersionFilePath(const KvDBProperties &kvDBProp, std int MultiVerNaturalStore::DeleteMetaDataByPrefixKey(const Key &keyPrefix) const { + (void)keyPrefix; return -E_NOT_SUPPORT; } void MultiVerNaturalStore::SetDataInterceptor(const PushDataInterceptor &interceptor) { + (void)interceptor; return; } diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/multiver/multi_ver_natural_store.h b/services/distributeddataservice/libs/distributeddb/storage/src/multiver/multi_ver_natural_store.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/multiver/multi_ver_natural_store_commit_notify_data.cpp b/services/distributeddataservice/libs/distributeddb/storage/src/multiver/multi_ver_natural_store_commit_notify_data.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/multiver/multi_ver_natural_store_commit_notify_data.h b/services/distributeddataservice/libs/distributeddb/storage/src/multiver/multi_ver_natural_store_commit_notify_data.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/multiver/multi_ver_natural_store_commit_storage.cpp b/services/distributeddataservice/libs/distributeddb/storage/src/multiver/multi_ver_natural_store_commit_storage.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/multiver/multi_ver_natural_store_commit_storage.h b/services/distributeddataservice/libs/distributeddb/storage/src/multiver/multi_ver_natural_store_commit_storage.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/multiver/multi_ver_natural_store_connection.cpp b/services/distributeddataservice/libs/distributeddb/storage/src/multiver/multi_ver_natural_store_connection.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/multiver/multi_ver_natural_store_connection.h b/services/distributeddataservice/libs/distributeddb/storage/src/multiver/multi_ver_natural_store_connection.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/multiver/multi_ver_natural_store_snapshot.cpp b/services/distributeddataservice/libs/distributeddb/storage/src/multiver/multi_ver_natural_store_snapshot.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/multiver/multi_ver_natural_store_snapshot.h b/services/distributeddataservice/libs/distributeddb/storage/src/multiver/multi_ver_natural_store_snapshot.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/multiver/multi_ver_natural_store_transfer_data.cpp b/services/distributeddataservice/libs/distributeddb/storage/src/multiver/multi_ver_natural_store_transfer_data.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/multiver/multi_ver_natural_store_transfer_data.h b/services/distributeddataservice/libs/distributeddb/storage/src/multiver/multi_ver_natural_store_transfer_data.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/multiver/multi_ver_storage_engine.cpp b/services/distributeddataservice/libs/distributeddb/storage/src/multiver/multi_ver_storage_engine.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/multiver/multi_ver_storage_engine.h b/services/distributeddataservice/libs/distributeddb/storage/src/multiver/multi_ver_storage_engine.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/multiver/multi_ver_storage_executor.cpp b/services/distributeddataservice/libs/distributeddb/storage/src/multiver/multi_ver_storage_executor.cpp old mode 100755 new mode 100644 index 048c953e8e943bb2ddabb9052b8f4f9c47fdbe51..6f52d8e3024075184084f6391d5e096cf789485e --- a/services/distributeddataservice/libs/distributeddb/storage/src/multiver/multi_ver_storage_executor.cpp +++ b/services/distributeddataservice/libs/distributeddb/storage/src/multiver/multi_ver_storage_executor.cpp @@ -1489,11 +1489,14 @@ int MultiVerStorageExecutor::DeleteEntriesByHashKey(Version version, const Key & int MultiVerStorageExecutor::UpdateTrimedFlag(Version version, const Key &hashKey) { + (void)version; + (void)hashKey; return E_OK; } int MultiVerStorageExecutor::UpdateTrimedFlag(const CommitID &commit) { + (void)commit; return E_OK; } } // namespace DistributedDB diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/multiver/multi_ver_storage_executor.h b/services/distributeddataservice/libs/distributeddb/storage/src/multiver/multi_ver_storage_executor.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/multiver/multi_ver_vacuum.cpp b/services/distributeddataservice/libs/distributeddb/storage/src/multiver/multi_ver_vacuum.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/multiver/multi_ver_vacuum_executor_impl.cpp b/services/distributeddataservice/libs/distributeddb/storage/src/multiver/multi_ver_vacuum_executor_impl.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/multiver/multi_ver_vacuum_executor_impl.h b/services/distributeddataservice/libs/distributeddb/storage/src/multiver/multi_ver_vacuum_executor_impl.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/multiver/multi_ver_value_object.cpp b/services/distributeddataservice/libs/distributeddb/storage/src/multiver/multi_ver_value_object.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/multiver/multi_ver_value_object.h b/services/distributeddataservice/libs/distributeddb/storage/src/multiver/multi_ver_value_object.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/operation/database_oper.cpp b/services/distributeddataservice/libs/distributeddb/storage/src/operation/database_oper.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/operation/database_oper.h b/services/distributeddataservice/libs/distributeddb/storage/src/operation/database_oper.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/operation/local_database_oper.cpp b/services/distributeddataservice/libs/distributeddb/storage/src/operation/local_database_oper.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/operation/local_database_oper.h b/services/distributeddataservice/libs/distributeddb/storage/src/operation/local_database_oper.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/operation/multi_ver_database_oper.cpp b/services/distributeddataservice/libs/distributeddb/storage/src/operation/multi_ver_database_oper.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/operation/multi_ver_database_oper.h b/services/distributeddataservice/libs/distributeddb/storage/src/operation/multi_ver_database_oper.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/operation/single_ver_database_oper.cpp b/services/distributeddataservice/libs/distributeddb/storage/src/operation/single_ver_database_oper.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/operation/single_ver_database_oper.h b/services/distributeddataservice/libs/distributeddb/storage/src/operation/single_ver_database_oper.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/package_file.cpp b/services/distributeddataservice/libs/distributeddb/storage/src/package_file.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/package_file.h b/services/distributeddataservice/libs/distributeddb/storage/src/package_file.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/relational_store_instance.cpp b/services/distributeddataservice/libs/distributeddb/storage/src/relational_store_instance.cpp index de1dedeb30c131803cd291375531860b72f434d5..cb44f6fbb7b923c10aead3dd23ded92d8e4fe661 100644 --- a/services/distributeddataservice/libs/distributeddb/storage/src/relational_store_instance.cpp +++ b/services/distributeddataservice/libs/distributeddb/storage/src/relational_store_instance.cpp @@ -103,7 +103,7 @@ void RelationalStoreInstance::RemoveKvDBFromCache(const RelationalDBProperties & dbs_.erase(identifier); } -void RelationalStoreInstance::SaveKvDBToCache(IRelationalStore *store, const RelationalDBProperties &properties) +void RelationalStoreInstance::SaveRelationalDBToCache(IRelationalStore *store, const RelationalDBProperties &properties) { if (store == nullptr) { return; @@ -122,6 +122,7 @@ IRelationalStore *RelationalStoreInstance::OpenDatabase(const RelationalDBProper { auto db = new (std::nothrow) SQLiteRelationalStore(); if (db == nullptr) { + errCode = -E_OUT_OF_MEMORY; LOGE("Failed to get relational store! err:%d", errCode); return nullptr; } @@ -138,7 +139,7 @@ IRelationalStore *RelationalStoreInstance::OpenDatabase(const RelationalDBProper return nullptr; } - SaveKvDBToCache(db, properties); + SaveRelationalDBToCache(db, properties); return db; } diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/relational_sync_able_storage.cpp b/services/distributeddataservice/libs/distributeddb/storage/src/relational_sync_able_storage.cpp index cf5b70167d91bd2bb9e976701e2bd11abd77cc07..419b4afed9576f10774e4494b61b3173ea71f130 100644 --- a/services/distributeddataservice/libs/distributeddb/storage/src/relational_sync_able_storage.cpp +++ b/services/distributeddataservice/libs/distributeddb/storage/src/relational_sync_able_storage.cpp @@ -206,7 +206,7 @@ int RelationalSyncAbleStorage::GetAllMetaKeys(std::vector &keys) const const KvDBProperties &RelationalSyncAbleStorage::GetDbProperties() const { - return properties; + return properties_; } static int GetKvEntriesByDataItems(std::vector &entries, std::vector &dataItems) @@ -397,7 +397,7 @@ int RelationalSyncAbleStorage::SaveSyncDataItems(const QueryObject &object, std: storageEngine_->GetSchemaRef().GetTable(object.GetTableName()), maxTimestamp); if (errCode == E_OK) { (void)SetMaxTimeStamp(maxTimestamp); - // dataItems size > 0 now because already check befor + // dataItems size > 0 now because already check before // all dataItems will write into db now, so need to observer notify here // if some dataItems will not write into db in the future, observer notify here need change TriggerObserverAction(deviceName); @@ -478,7 +478,15 @@ int RelationalSyncAbleStorage::CreateDistributedDeviceTable(const std::string &d if (handle == nullptr) { return errCode; } - for (const auto &[table, strategy] : syncStrategy.GetStrategies()) { + + errCode = handle->StartTransaction(TransactType::IMMEDIATE); + if (errCode != E_OK) { + LOGE("Start transaction failed:%d", errCode); + ReleaseHandle(handle); + return errCode; + } + + for (const auto &[table, strategy] : syncStrategy) { if (!strategy.permitSync) { continue; } @@ -490,6 +498,12 @@ int RelationalSyncAbleStorage::CreateDistributedDeviceTable(const std::string &d } } + if (errCode == E_OK) { + errCode = handle->Commit(); + } else { + (void)handle->Rollback(); + } + ReleaseHandle(handle); return errCode; } diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/result_entries_window.cpp b/services/distributeddataservice/libs/distributeddb/storage/src/result_entries_window.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/single_ver_natural_store_commit_notify_data.cpp b/services/distributeddataservice/libs/distributeddb/storage/src/single_ver_natural_store_commit_notify_data.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/single_ver_natural_store_commit_notify_data.h b/services/distributeddataservice/libs/distributeddb/storage/src/single_ver_natural_store_commit_notify_data.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/query_object.cpp b/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/query_object.cpp old mode 100755 new mode 100644 index ba7e8cff2384068683dcbeca9c412e9fbecde775..bc77775f8d1645e9e86661b39c9a5650f4546307 --- a/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/query_object.cpp +++ b/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/query_object.cpp @@ -415,7 +415,7 @@ int QueryObject::CheckInKeys() const LOGE("Inkeys cannot be empty."); return -E_INVALID_ARGS; } - if (keys_.size() > DBConstant::MAX_BATCH_SIZE) { + if (keys_.size() > DBConstant::MAX_INKEYS_SIZE) { LOGE("Inkeys cannot be over 128."); return -E_MAX_LIMITS; } diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/query_object.h b/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/query_object.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/query_sync_object.cpp b/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/query_sync_object.cpp index 603f713626c351023b28cc804b0d7b475d189722..cd4492dc3b5c2451da6359f579a38122ef354bcf 100644 --- a/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/query_sync_object.cpp +++ b/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/query_sync_object.cpp @@ -140,8 +140,7 @@ std::string QuerySyncObject::GetIdentify() const len += isTableNameSpecified_ ? Parcel::GetStringLen(tableName_) : 0; for (const auto &key : keys_) { len += Parcel::GetVectorCharLen(key); - } - // QUERY_SYNC_OBJECT_VERSION_1 end. + } // QUERY_SYNC_OBJECT_VERSION_1 end. std::vector buff(len, 0); // It will affect the hash result, the default value cannot be modified Parcel parcel(buff.data(), len); @@ -168,8 +167,7 @@ std::string QuerySyncObject::GetIdentify() const } for (const auto &key : keys_) { (void)parcel.WriteVectorChar(key); - } - // QUERY_SYNC_OBJECT_VERSION_1 end. + } // QUERY_SYNC_OBJECT_VERSION_1 end. if (parcel.IsError()) { return std::string(); @@ -225,8 +223,7 @@ int QuerySyncObject::SerializeData(Parcel &parcel, uint32_t softWareVersion) for (const auto &key : keys_) { (void)parcel.WriteVectorChar(key); } - } - // QUERY_SYNC_OBJECT_VERSION_1 end. + } // QUERY_SYNC_OBJECT_VERSION_1 end. if (parcel.IsError()) { // parcel almost success return -E_INVALID_ARGS; @@ -246,7 +243,7 @@ int DeSerializeVersion1Data(uint32_t version, Parcel &parcel, std::string &table } uint32_t keysSize = 0; (void)parcel.ReadUInt32(keysSize); - if (keysSize > DBConstant::MAX_BATCH_SIZE) { + if (keysSize > DBConstant::MAX_INKEYS_SIZE) { return -E_PARSE_FAIL; } for (uint32_t i = 0; i < keysSize; ++i) { @@ -298,8 +295,7 @@ int QuerySyncObject::DeSerializeData(Parcel &parcel, QuerySyncObject &queryObj) int errCode = DeSerializeVersion1Data(context.version, parcel, tableName, keys); if (errCode != E_OK) { return errCode; - } - // QUERY_SYNC_OBJECT_VERSION_1 end. + } // QUERY_SYNC_OBJECT_VERSION_1 end. if (parcel.IsError()) { // almost success return -E_INVALID_ARGS; @@ -342,8 +338,7 @@ uint32_t QuerySyncObject::CalculateLen() const len += Parcel::GetUInt32Len(); // size of keys_ for (const auto &key : keys_) { len += Parcel::GetVectorCharLen(key); - } - // QUERY_SYNC_OBJECT_VERSION_1 end. + } // QUERY_SYNC_OBJECT_VERSION_1 end. len = Parcel::GetEightByteAlign(len); if (len > INT32_MAX) { diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/relational/sqlite_relational_store_connection.cpp b/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/relational/sqlite_relational_store_connection.cpp index ff9965c3996b6570e432f4f0da2381a254ddc23f..be2cc3b9ebc1416db64234521ad1bf5afecd7b3a 100644 --- a/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/relational/sqlite_relational_store_connection.cpp +++ b/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/relational/sqlite_relational_store_connection.cpp @@ -95,7 +95,6 @@ int SQLiteRelationalStoreConnection::StartTransaction() LOGD("[RelationalConnection] Start transaction finish."); writeHandle_ = handle; - transactingFlag_.store(true); return E_OK; } @@ -110,9 +109,6 @@ int SQLiteRelationalStoreConnection::Commit() int errCode = writeHandle_->Commit(); ReleaseExecutor(writeHandle_); - if (errCode == E_OK) { - transactingFlag_.store(false); - } LOGD("connection commit transaction!"); return errCode; } @@ -128,9 +124,6 @@ int SQLiteRelationalStoreConnection::RollBack() int errCode = writeHandle_->Rollback(); ReleaseExecutor(writeHandle_); - if (errCode == E_OK) { - transactingFlag_.store(false); - } LOGI("connection rollback transaction!"); return errCode; } diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/relational/sqlite_relational_store_connection.h b/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/relational/sqlite_relational_store_connection.h index 6094af02239baa89db721c9519dedf3e6f49d6d4..13b2dbd264a5b333f8ac36ba3cc6f1d16a423ba2 100644 --- a/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/relational/sqlite_relational_store_connection.h +++ b/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/relational/sqlite_relational_store_connection.h @@ -60,7 +60,6 @@ private: SQLiteSingleVerRelationalStorageExecutor *writeHandle_ = nullptr; mutable std::mutex transactionMutex_; // used for transaction - std::atomic transactingFlag_; }; } // namespace DistributedDB #endif diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/relational/sqlite_single_relational_storage_engine.cpp b/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/relational/sqlite_single_relational_storage_engine.cpp index 0a3de8d6c055b8970e17c3c944506c26e67d0f23..3040d91e9a27ed88e604e39bfbdfc879d5e476d6 100644 --- a/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/relational/sqlite_single_relational_storage_engine.cpp +++ b/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/relational/sqlite_single_relational_storage_engine.cpp @@ -17,6 +17,7 @@ #include "db_common.h" #include "db_errno.h" +#include "res_finalizer.h" #include "sqlite_single_ver_relational_storage_executor.h" @@ -156,10 +157,10 @@ int SQLiteSingleRelationalStorageEngine::CreateDistributedTable(const std::strin if (handle == nullptr) { return errCode; } + ResFinalizer finalizer([&handle, this] { this->ReleaseExecutor(handle); }); errCode = handle->StartTransaction(TransactType::IMMEDIATE); if (errCode != E_OK) { - ReleaseExecutor(handle); return errCode; } @@ -168,7 +169,6 @@ int SQLiteSingleRelationalStorageEngine::CreateDistributedTable(const std::strin if (errCode != E_OK) { LOGE("create distributed table failed. %d", errCode); (void)handle->Rollback(); - ReleaseExecutor(handle); return errCode; } @@ -177,7 +177,6 @@ int SQLiteSingleRelationalStorageEngine::CreateDistributedTable(const std::strin if (errCode != E_OK) { LOGE("Save schema to meta table for create distributed table failed. %d", errCode); (void)handle->Rollback(); - ReleaseExecutor(handle); return errCode; } @@ -186,7 +185,6 @@ int SQLiteSingleRelationalStorageEngine::CreateDistributedTable(const std::strin schema_ = tmpSchema; schemaChanged = true; } - ReleaseExecutor(handle); return errCode; } diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/sqlite_import.h b/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/sqlite_import.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/sqlite_local_kvdb.cpp b/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/sqlite_local_kvdb.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/sqlite_local_kvdb_connection.cpp b/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/sqlite_local_kvdb_connection.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/sqlite_local_kvdb_snapshot.cpp b/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/sqlite_local_kvdb_snapshot.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/sqlite_local_storage_engine.cpp b/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/sqlite_local_storage_engine.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/sqlite_local_storage_executor.cpp b/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/sqlite_local_storage_executor.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/sqlite_local_storage_executor.h b/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/sqlite_local_storage_executor.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/sqlite_multi_ver_data_storage.cpp b/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/sqlite_multi_ver_data_storage.cpp old mode 100755 new mode 100644 index 762b4ab4badf1ee93f5e03421acd4889eccf8671..568ea7a6d12191fbead2dbe97ec310b5391ba16a --- a/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/sqlite_multi_ver_data_storage.cpp +++ b/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/sqlite_multi_ver_data_storage.cpp @@ -233,6 +233,7 @@ int SQLiteMultiVerDataStorage::RollbackWrite(IKvDBMultiVerTransaction *transacti void SQLiteMultiVerDataStorage::CommitWritePhaseTwo(IKvDBMultiVerTransaction *transaction) { // just change the head version? + (void)transaction; } // Get one start transaction. diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/sqlite_multi_ver_data_storage.h b/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/sqlite_multi_ver_data_storage.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/sqlite_multi_ver_transaction.cpp b/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/sqlite_multi_ver_transaction.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/sqlite_multi_ver_transaction.h b/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/sqlite_multi_ver_transaction.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/sqlite_query_helper.cpp b/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/sqlite_query_helper.cpp index 5b19ce55d9ea1416d5d5502b402c13f2c3674dd9..49dd55f1bc084559e3d30d773c1639fb63a35669 100644 --- a/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/sqlite_query_helper.cpp +++ b/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/sqlite_query_helper.cpp @@ -351,6 +351,13 @@ int SqliteQueryHelper::BindSyncDataCheckStmt(sqlite3_stmt *statement, const Key } index += 2; // prefixKey takes 2 position } + + errCode = BindKeysToStmt(keys_, statement, index); + if (errCode != E_OK) { + SQLiteUtils::ResetStatement(statement, true, errCode); + return errCode; + } + for (const QueryObjNode &objNode : queryObjNodes_) { errCode = BindFieldValue(statement, objNode, index); if (errCode != E_OK) { @@ -1042,7 +1049,7 @@ std::string SqliteQueryHelper::MapKeysInToSql(size_t keysNum) const return resultSql; } -int SqliteQueryHelper::BindKeysToStmt(std::set &keys, sqlite3_stmt *&statement, int &index) const +int SqliteQueryHelper::BindKeysToStmt(const std::set &keys, sqlite3_stmt *&statement, int &index) const { if (!keys_.empty()) { int errCode = E_OK; diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/sqlite_query_helper.h b/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/sqlite_query_helper.h index fbfcc9820c83f662298f1cb16518967256cf9203..1d719b8c244e0648abb37a4395b5b0b8469f8653 100644 --- a/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/sqlite_query_helper.h +++ b/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/sqlite_query_helper.h @@ -121,7 +121,7 @@ private: int BindObjNodes(sqlite3_stmt *&statement, int &index) const; int GetSubscribeCondition(const std::string &accessStr, std::string &conditionStr); std::string MapKeysInToSql(size_t keysNum) const; - int BindKeysToStmt(std::set &keys, sqlite3_stmt *&countStmt, int &index) const; + int BindKeysToStmt(const std::set &keys, sqlite3_stmt *&countStmt, int &index) const; std::string MapKeysInSubCondition(const std::string &accessStr) const; // For InKeys. // Return the left string of symbol in compare clause. diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/sqlite_single_ver_database_upgrader.cpp b/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/sqlite_single_ver_database_upgrader.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/sqlite_single_ver_database_upgrader.h b/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/sqlite_single_ver_database_upgrader.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/sqlite_single_ver_forward_cursor.cpp b/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/sqlite_single_ver_forward_cursor.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/sqlite_single_ver_natural_store.cpp b/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/sqlite_single_ver_natural_store.cpp old mode 100755 new mode 100644 index 9856f72fed29686cbe1dff1b8ef4053ebfffbfab..7a75c080783077bb220d2e9ddeab92576d8cce7a --- a/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/sqlite_single_ver_natural_store.cpp +++ b/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/sqlite_single_ver_natural_store.cpp @@ -35,12 +35,6 @@ #include "value_hash_calc.h" namespace DistributedDB { -#define CHECK_STORAGE_ENGINE do { \ - if (storageEngine_ == nullptr) { \ - return -E_INVALID_DB; \ - } \ -} while (0) - namespace { constexpr int WAIT_DELEGATE_CALLBACK_TIME = 100; @@ -545,7 +539,9 @@ IKvDBSyncInterface *SQLiteSingleVerNaturalStore::GetSyncInterface() int SQLiteSingleVerNaturalStore::GetMetaData(const Key &key, Value &value) const { - CHECK_STORAGE_ENGINE; + if (storageEngine_ == nullptr) { + return -E_INVALID_DB; + } if (key.size() > DBConstant::MAX_KEY_SIZE) { return -E_INVALID_ARGS; } @@ -615,7 +611,9 @@ int SQLiteSingleVerNaturalStore::DeleteMetaData(const std::vector &keys) int SQLiteSingleVerNaturalStore::GetAllMetaKeys(std::vector &keys) const { - CHECK_STORAGE_ENGINE; + if (storageEngine_ == nullptr) { + return -E_INVALID_DB; + } int errCode = E_OK; SQLiteSingleVerStorageExecutor *handle = GetHandle(true, errCode); if (handle == nullptr) { @@ -1185,7 +1183,9 @@ int SQLiteSingleVerNaturalStore::SaveSyncDataItems(const QueryObject &query, std const DeviceInfo &deviceInfo, bool checkValueContent) { // Sync procedure does not care readOnly Flag - CHECK_STORAGE_ENGINE; + if (storageEngine_ == nullptr) { + return -E_INVALID_DB; + } int errCode = E_OK; for (const auto &item : dataItems) { // Check only the key and value size @@ -1346,7 +1346,7 @@ int SQLiteSingleVerNaturalStore::Rekey(const CipherPassword &passwd) std::unique_ptr operation; - // stop the syncer; + // stop the syncer int errCode = storageEngine_->TryToDisable(false, OperatePerm::REKEY_MONOPOLIZE_PERM); if (errCode != E_OK) { return errCode; @@ -1384,7 +1384,9 @@ END: int SQLiteSingleVerNaturalStore::Export(const std::string &filePath, const CipherPassword &passwd) { - CHECK_STORAGE_ENGINE; + if (storageEngine_ == nullptr) { + return -E_INVALID_DB; + } if (MyProp().GetBoolProp(KvDBProperties::MEMORY_MODE, false)) { return -E_NOT_SUPPORT; } @@ -1422,7 +1424,9 @@ int SQLiteSingleVerNaturalStore::Export(const std::string &filePath, const Ciphe int SQLiteSingleVerNaturalStore::Import(const std::string &filePath, const CipherPassword &passwd) { - CHECK_STORAGE_ENGINE; + if (storageEngine_ == nullptr) { + return -E_INVALID_DB; + } if (MyProp().GetBoolProp(KvDBProperties::MEMORY_MODE, false)) { return -E_NOT_SUPPORT; } @@ -1434,7 +1438,7 @@ int SQLiteSingleVerNaturalStore::Import(const std::string &filePath, const Ciphe localDev.resize(0); } - // stop the syncer; + // stop the syncer errCode = storageEngine_->TryToDisable(false, OperatePerm::IMPORT_MONOPOLIZE_PERM); if (errCode != E_OK) { return errCode; diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/sqlite_single_ver_natural_store.h b/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/sqlite_single_ver_natural_store.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/sqlite_single_ver_natural_store_connection.cpp b/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/sqlite_single_ver_natural_store_connection.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/sqlite_single_ver_natural_store_connection.h b/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/sqlite_single_ver_natural_store_connection.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/sqlite_single_ver_relational_storage_executor.cpp b/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/sqlite_single_ver_relational_storage_executor.cpp index ad66f016aef6fa85226955bacfcc79c166aa8cdc..7d85f0743f3c8e00665f5a9bf78cdf71ae1ae6e9 100644 --- a/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/sqlite_single_ver_relational_storage_executor.cpp +++ b/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/sqlite_single_ver_relational_storage_executor.cpp @@ -389,13 +389,6 @@ static int BindDataValueByType(sqlite3_stmt *statement, const std::optional dev; int errCode = SQLiteUtils::GetColumnBlobValue(logStatement, 1, dev); // 1 means dev index @@ -669,11 +662,11 @@ int SQLiteSingleVerRelationalStorageExecutor::PrepareForSavingData(const QueryOb int SQLiteSingleVerRelationalStorageExecutor::SaveSyncLog(sqlite3_stmt *statement, sqlite3_stmt *queryStmt, const DataItem &dataItem, TimeStamp &maxTimestamp, int64_t rowid) { - int errCode = SQLiteUtils::BindBlobToStatement(queryStmt, 1, dataItem.hashKey); + int errCode = SQLiteUtils::BindBlobToStatement(queryStmt, 1, dataItem.hashKey); // 1 means hashkey index. if (errCode != E_OK) { return errCode; } - errCode = SQLiteUtils::BindTextToStatement(queryStmt, 2, dataItem.dev); + errCode = SQLiteUtils::BindTextToStatement(queryStmt, 2, dataItem.dev); // 2 means device index. if (errCode != E_OK) { return errCode; } @@ -755,9 +748,8 @@ int SQLiteSingleVerRelationalStorageExecutor::SaveSyncDataItem(const DataItem &d return DeleteSyncDataItem(dataItem, rmDataStmt); } - std::vector indexMapping; OptRowDataWithLog data; - int errCode = DataTransformer::DeSerializeDataItem(dataItem, data, fieldInfos, indexMapping); + int errCode = DataTransformer::DeSerializeDataItem(dataItem, data, fieldInfos); if (errCode != E_OK) { LOGE("[RelationalStorageExecutor] DeSerialize dataItem failed! errCode = [%d]", errCode); return errCode; @@ -1099,9 +1091,8 @@ int SQLiteSingleVerRelationalStorageExecutor::GetSyncDataByQuery(std::vector(handle); singleVerHandle->SetAttachMetaMode(isAttachMeta); } diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/sqlite_single_ver_storage_engine.h b/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/sqlite_single_ver_storage_engine.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/sqlite_single_ver_storage_executor.cpp b/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/sqlite_single_ver_storage_executor.cpp old mode 100755 new mode 100644 index dd637aaed09630bfa908fedce1f312402a38c794..ae9970dd0b63ea1d5972d24eca46138ca1dc96b2 --- a/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/sqlite_single_ver_storage_executor.cpp +++ b/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/sqlite_single_ver_storage_executor.cpp @@ -1530,7 +1530,7 @@ void SQLiteSingleVerStorageExecutor::PutConflictData(const DataItem &itemPut, co } if (dataStatus.preStatus == DataStatus::NOEXISTED || - ((dataStatus.preStatus == DataStatus::DELETED) && (dataStatus.isDeleted == true))) { + ((dataStatus.preStatus == DataStatus::DELETED) && dataStatus.isDeleted)) { return; } diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/sqlite_single_ver_storage_executor.h b/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/sqlite_single_ver_storage_executor.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/sqlite_single_ver_storage_executor_cache.cpp b/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/sqlite_single_ver_storage_executor_cache.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/sqlite_single_ver_storage_executor_sql.h b/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/sqlite_single_ver_storage_executor_sql.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/sqlite_storage_engine.cpp b/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/sqlite_storage_engine.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/sqlite_storage_engine.h b/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/sqlite_storage_engine.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/sqlite_storage_executor.cpp b/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/sqlite_storage_executor.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/sqlite_storage_executor.h b/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/sqlite_storage_executor.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/sqlite_utils.cpp b/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/sqlite_utils.cpp old mode 100755 new mode 100644 index 5a77599c93139b953e32505c7fe6f41ea2268863..60f5911d15275ac5f15d2d2f4c465b49e0e0343f --- a/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/sqlite_utils.cpp +++ b/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/sqlite_utils.cpp @@ -86,6 +86,20 @@ namespace { LOGE("[SQLite] Error[%d], sys[%d]", err, errno); } } + + // statement must not be null + std::string GetColString(sqlite3_stmt *statement, int nCol) + { + std::string rowString; + for (int i = 0; i < nCol; i++) { + if (sqlite3_column_name(statement, i) != nullptr) { + rowString += sqlite3_column_name(statement, i); + } + int blankFill = (i + 1) * 16 - rowString.size(); // each column width 16 + rowString.append(static_cast((blankFill > 0) ? blankFill : 0), ' '); + } + return rowString; + } } namespace TriggerMode { @@ -458,7 +472,6 @@ int SQLiteUtils::GetColumnBlobValue(sqlite3_stmt *statement, int index, std::vec int keySize = sqlite3_column_bytes(statement, index); auto keyRead = static_cast(sqlite3_column_blob(statement, index)); - if (keySize < 0) { LOGE("[SQLiteUtils][Column blob] size:%d", keySize); return -E_INVALID_DATA; @@ -501,8 +514,8 @@ int SQLiteUtils::AttachNewDatabase(sqlite3 *db, CipherType type, const CipherPas goto END; } // Passwords do not allow vector operations, so we can not use function BindBlobToStatement here. - errCode = sqlite3_bind_blob(statement, 2, static_cast(password.GetData()), - password.GetSize(), SQLITE_TRANSIENT); // 2nd para is password. + errCode = sqlite3_bind_blob(statement, 2, static_cast(password.GetData()), // 2 means password index. + password.GetSize(), SQLITE_TRANSIENT); if (errCode != SQLITE_OK) { LOGE("Bind the attached key failed:%d", errCode); errCode = SQLiteUtils::MapSQLiteErrno(errCode); @@ -580,7 +593,7 @@ int SQLiteUtils::CheckIntegrity(sqlite3 *db, const std::string &sql) namespace { // anonymous namespace for schema analysis int AnalysisSchemaSqlAndTrigger(sqlite3 *db, const std::string &tableName, TableInfo &table) { - std::string sql = "select type, name, tbl_name, rootpage, sql from sqlite_master where tbl_name = ?"; + std::string sql = "select type, sql from sqlite_master where tbl_name = ?"; sqlite3_stmt *statement = nullptr; int errCode = SQLiteUtils::GetStatement(db, sql, statement); if (errCode != E_OK) { @@ -606,12 +619,8 @@ int AnalysisSchemaSqlAndTrigger(sqlite3 *db, const std::string &tableName, Table (void) SQLiteUtils::GetColumnTextValue(statement, 0, type); if (type == "table") { std::string createTableSql; - (void) SQLiteUtils::GetColumnTextValue(statement, 4, createTableSql); // 4 means create table sql + (void) SQLiteUtils::GetColumnTextValue(statement, 1, createTableSql); // 1 means create table sql table.SetCreateTableSql(createTableSql); - } else if (type == "trigger") { - std::string triggerName; - (void) SQLiteUtils::GetColumnTextValue(statement, 1, triggerName); // 1 means trigger name - table.AddTrigger(triggerName); } } else { LOGE("[AnalysisSchema] Step for the analysis create table sql and trigger failed:%d", err); @@ -623,8 +632,7 @@ int AnalysisSchemaSqlAndTrigger(sqlite3 *db, const std::string &tableName, Table return errCode; } -int GetSchemaIndexList(sqlite3 *db, const std::string &tableName, std::vector &indexList, - std::vector &uniqueList) +int GetSchemaIndexList(sqlite3 *db, const std::string &tableName, std::vector &indexList) { std::string sql = "pragma index_list(" + tableName + ")"; sqlite3_stmt *statement = nullptr; @@ -644,9 +652,7 @@ int GetSchemaIndexList(sqlite3 *db, const std::string &tableName, std::vector indexList; - std::vector uniqueList; - int errCode = GetSchemaIndexList(db, tableName, indexList, uniqueList); + int errCode = GetSchemaIndexList(db, tableName, indexList); if (errCode != E_OK) { LOGE("[AnalysisSchema] get schema index list failed."); return errCode; @@ -706,17 +711,6 @@ int AnalysisSchemaIndexAndUnique(sqlite3 *db, const std::string &tableName, Tabl } table.AddIndexDefine(indexName, indexDefine); } - - for (const auto &uniqueName : uniqueList) { - CompositeFields uniqueDefine; - errCode = AnalysisSchemaIndexDefine(db, uniqueName, uniqueDefine); - if (errCode != E_OK) { - LOGE("[AnalysisSchema] analysis schema unique columns failed."); - return errCode; - } - table.AddUniqueDefine(uniqueDefine); - } - return E_OK; } @@ -795,7 +789,7 @@ int SQLiteUtils::AnalysisSchema(sqlite3 *db, const std::string &tableName, Table return errCode; } - errCode = AnalysisSchemaIndexAndUnique(db, tableName, table); + errCode = AnalysisSchemaIndex(db, tableName, table); if (errCode != E_OK) { LOGE("[AnalysisSchema] Analysis index failed."); return errCode; @@ -857,11 +851,17 @@ int SQLiteUtils::Rekey(sqlite3 *db, const CipherPassword &passwd) int SQLiteUtils::ExportDatabase(sqlite3 *db, CipherType type, const CipherPassword &passwd, const std::string &newDbName) { + (void)db; + (void)type; + (void)passwd; + (void)newDbName; return -E_NOT_SUPPORT; } int SQLiteUtils::Rekey(sqlite3 *db, const CipherPassword &passwd) { + (void)db; + (void)passwd; return -E_NOT_SUPPORT; } #endif @@ -934,21 +934,20 @@ int SQLiteUtils::GetJournalMode(sqlite3 *db, std::string &mode) std::string sql = "PRAGMA journal_mode;"; sqlite3_stmt *statement = nullptr; - int errCode = sqlite3_prepare(db, sql.c_str(), -1, &statement, nullptr); - if (errCode != SQLITE_OK || statement == nullptr) { - errCode = SQLiteUtils::MapSQLiteErrno(errCode); + int errCode = SQLiteUtils::GetStatement(db, sql, statement); + if (errCode != E_OK || statement == nullptr) { return errCode; } - if (sqlite3_step(statement) == SQLITE_ROW) { + errCode = SQLiteUtils::StepWithRetry(statement); + if (errCode == SQLiteUtils::MapSQLiteErrno(SQLITE_ROW)) { errCode = SQLiteUtils::GetColumnTextValue(statement, 0, mode); } else { LOGE("[SqlUtil][GetJournal] Get db journal_mode failed."); - errCode = SQLiteUtils::MapSQLiteErrno(SQLITE_ERROR); } SQLiteUtils::ResetStatement(statement, true, errCode); - return E_OK; + return errCode; } int SQLiteUtils::SetUserVer(const OpenDbProperties &properties, int version) @@ -1046,6 +1045,11 @@ int SQLiteUtils::ExportDatabase(const std::string &srcFile, CipherType type, con int SQLiteUtils::ExportDatabase(const std::string &srcFile, CipherType type, const CipherPassword &srcPasswd, const std::string &targetFile, const CipherPassword &passwd) { + (void)srcFile; + (void)type; + (void)srcPasswd; + (void)targetFile; + (void)passwd; return -E_NOT_SUPPORT; } #endif @@ -1338,7 +1342,7 @@ int SQLiteUtils::CreateRelationalLogTable(sqlite3 *db, const std::string &oriTab } namespace { -std::string GetInsertTrigger(const TableInfo table) +std::string GetInsertTrigger(const TableInfo &table) { std::string insertTrigger = "CREATE TRIGGER IF NOT EXISTS "; insertTrigger += "naturalbase_rdb_" + table.GetTableName() + "_ON_INSERT AFTER INSERT \n"; @@ -1347,27 +1351,27 @@ std::string GetInsertTrigger(const TableInfo table) insertTrigger += "\t INSERT OR REPLACE INTO "; insertTrigger += DBConstant::RELATIONAL_PREFIX + table.GetTableName() + "_log"; insertTrigger += " (data_key, device, ori_device, timestamp, wtimestamp, flag, hash_key)"; - insertTrigger += " VALUES (new.rowid, '" + table.GetDevId() + "', '" + table.GetDevId() + "',"; + insertTrigger += " VALUES (new.rowid, '', '',"; insertTrigger += " get_sys_time(0), get_sys_time(0), 0x02,"; insertTrigger += " calc_hash(new." + table.GetPrimaryKey() + "));\n"; insertTrigger += "END;"; return insertTrigger; } -std::string GetUpdateTrigger(const TableInfo table) +std::string GetUpdateTrigger(const TableInfo &table) { std::string updateTrigger = "CREATE TRIGGER IF NOT EXISTS "; updateTrigger += "naturalbase_rdb_" + table.GetTableName() + "_ON_UPDATE AFTER UPDATE \n"; updateTrigger += "ON " + table.GetTableName() + "\n"; updateTrigger += "BEGIN\n"; updateTrigger += "\t UPDATE " + DBConstant::RELATIONAL_PREFIX + table.GetTableName() + "_log"; - updateTrigger += " SET timestamp=get_sys_time(0), device='" + table.GetDevId() + "', flag=0x22"; + updateTrigger += " SET timestamp=get_sys_time(0), device='', flag=0x22"; updateTrigger += " where hash_key=calc_hash(old." + table.GetPrimaryKey() + ") and flag&0x02=0x02;\n"; updateTrigger += "END;"; return updateTrigger; } -std::string GetDeleteTrigger(const TableInfo table) +std::string GetDeleteTrigger(const TableInfo &table) { std::string deleteTrigger = "CREATE TRIGGER IF NOT EXISTS "; deleteTrigger += "naturalbase_rdb_" + table.GetTableName() + "_ON_DELETE BEFORE DELETE \n"; @@ -1907,15 +1911,7 @@ int SQLiteUtils::ExplainPlan(sqlite3 *db, const std::string &execSql, bool isQue nCol = std::min(nCol, 8); // Read 8 column at most if (isFirst) { - std::string rowString; - for (int i = 0; i < nCol; i++) { - if (sqlite3_column_name(statement, i) != nullptr) { - rowString += sqlite3_column_name(statement, i); - } - int blankFill = (i + 1) * 16 - rowString.size(); // each column width 16 - rowString.append(static_cast((blankFill > 0) ? blankFill : 0), ' '); - } - LOGD("#### %s", rowString.c_str()); + LOGD("#### %s", GetColString(statement, nCol).c_str()); isFirst = false; } diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/sqlite_utils.h b/services/distributeddataservice/libs/distributeddb/storage/src/sqlite/sqlite_utils.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/storage_engine.cpp b/services/distributeddataservice/libs/distributeddb/storage/src/storage_engine.cpp old mode 100755 new mode 100644 index 674bb975fdb57d278e66be8fc8a780f098f7f9d6..a45b782b9c2811ac35b8785ce50d579227ae7c0e --- a/services/distributeddataservice/libs/distributeddb/storage/src/storage_engine.cpp +++ b/services/distributeddataservice/libs/distributeddb/storage/src/storage_engine.cpp @@ -396,12 +396,13 @@ StorageExecutor *StorageEngine::FetchStorageExecutor(bool isWrite, std::list lock(syncerOperateLock_); - StartSyncerWithNoLock(isCheckSyncActive, isNeedActive); + int errCode = StartSyncerWithNoLock(isCheckSyncActive, isNeedActive); closed_ = false; + return errCode; } -void SyncAbleKvDB::StartSyncerWithNoLock(bool isCheckSyncActive, bool isNeedActive) +int SyncAbleKvDB::StartSyncerWithNoLock(bool isCheckSyncActive, bool isNeedActive) { IKvDBSyncInterface *syncInterface = GetSyncInterface(); if (syncInterface == nullptr) { LOGF("KvDB got null sync interface."); - return; + return -E_INVALID_ARGS; } if (!isCheckSyncActive) { SetSyncModuleActive(); @@ -180,28 +181,29 @@ void SyncAbleKvDB::StartSyncerWithNoLock(bool isCheckSyncActive, bool isNeedActi userChangeListerner_ = RuntimeContext::GetInstance()->RegisterUserChangedListerner( std::bind(&SyncAbleKvDB::ChangeUserListerner, this), UserChangeMonitor::USER_ACTIVE_TO_NON_ACTIVE_EVENT); } else if (isSyncDualTupleMode && (userChangeListerner_ == nullptr)) { - EventType event = started_? + EventType event = isNeedActive ? UserChangeMonitor::USER_ACTIVE_EVENT : UserChangeMonitor::USER_NON_ACTIVE_EVENT; userChangeListerner_ = RuntimeContext::GetInstance()->RegisterUserChangedListerner( std::bind(&SyncAbleKvDB::UserChangeHandle, this), event); } + return errCode; } // Stop syncer -void SyncAbleKvDB::StopSyncer(bool isClosed) +void SyncAbleKvDB::StopSyncer(bool isClosedOperation) { std::unique_lock lock(syncerOperateLock_); - StopSyncerWithNoLock(isClosed); + StopSyncerWithNoLock(isClosedOperation); } -void SyncAbleKvDB::StopSyncerWithNoLock(bool isClosed) +void SyncAbleKvDB::StopSyncerWithNoLock(bool isClosedOperation) { ReSetSyncModuleActive(); - syncer_.Close(); + syncer_.Close(isClosedOperation); if (started_) { started_ = false; } - closed_ = isClosed; + closed_ = isClosedOperation; if (userChangeListerner_ != nullptr) { userChangeListerner_->Drop(false); userChangeListerner_ = nullptr; diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/sync_able_kvdb.h b/services/distributeddataservice/libs/distributeddb/storage/src/sync_able_kvdb.h old mode 100755 new mode 100644 index 14b0bcd75a03b2ffed80c51d4c399c4079bbc267..06912bafe72560e0e3e54411bb4c5b704ad27009 --- a/services/distributeddataservice/libs/distributeddb/storage/src/sync_able_kvdb.h +++ b/services/distributeddataservice/libs/distributeddb/storage/src/sync_able_kvdb.h @@ -92,14 +92,14 @@ protected: void ReSetSyncModuleActive(); // Start syncer - void StartSyncer(bool isCheckSyncActive = false, bool isNeedActive = true); + int StartSyncer(bool isCheckSyncActive = false, bool isNeedActive = true); - void StartSyncerWithNoLock(bool isCheckSyncActive, bool isNeedActive); + int StartSyncerWithNoLock(bool isCheckSyncActive, bool isNeedActive); // Stop syncer - void StopSyncer(bool isClosed = false); + void StopSyncer(bool isClosedOperation = false); - void StopSyncerWithNoLock(bool isClosed = false); + void StopSyncerWithNoLock(bool isClosedOperation = false); void UserChangeHandle(); diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/sync_able_kvdb_connection.cpp b/services/distributeddataservice/libs/distributeddb/storage/src/sync_able_kvdb_connection.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/sync_able_kvdb_connection.h b/services/distributeddataservice/libs/distributeddb/storage/src/sync_able_kvdb_connection.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/upgrader/single_ver_database_upgrader.cpp b/services/distributeddataservice/libs/distributeddb/storage/src/upgrader/single_ver_database_upgrader.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/upgrader/single_ver_schema_database_upgrader.cpp b/services/distributeddataservice/libs/distributeddb/storage/src/upgrader/single_ver_schema_database_upgrader.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/storage/src/upgrader/single_ver_schema_database_upgrader.h b/services/distributeddataservice/libs/distributeddb/storage/src/upgrader/single_ver_schema_database_upgrader.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/syncer/include/isyncer.h b/services/distributeddataservice/libs/distributeddb/syncer/include/isyncer.h old mode 100755 new mode 100644 index ea0f7d45cae5570a330f7dbff01cdbc1f780be50..131f43f5b11bead354860910c8e2be47e0cf24a7 --- a/services/distributeddataservice/libs/distributeddb/syncer/include/isyncer.h +++ b/services/distributeddataservice/libs/distributeddb/syncer/include/isyncer.h @@ -1,3 +1,4 @@ + /* * Copyright (c) 2021 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); @@ -48,7 +49,7 @@ public: } // Close - virtual int Close() = 0; + virtual int Close(bool isClosedOperation) = 0; // Sync function. // param devices: The device id list. @@ -60,7 +61,7 @@ public: const std::function &)> &onComplete, const std::function &onFinalize, bool wait) = 0; - // Sync function. use SyncParma to reduce paramter. + // Sync function. use SyncParma to reduce parameter. virtual int Sync(const SyncParma ¶m) = 0; // Remove the operation, with the given syncId, used to clean resource if sync finished or failed. @@ -76,7 +77,7 @@ public: // delete specified device's watermark virtual int EraseDeviceWaterMark(const std::string &deviceId, bool isNeedHash) = 0; - + // delete specified device's and table's watermark virtual int EraseDeviceWaterMark(const std::string &deviceId, bool isNeedHash, const std::string &tableName) = 0; diff --git a/services/distributeddataservice/libs/distributeddb/syncer/include/syncer_proxy.h b/services/distributeddataservice/libs/distributeddb/syncer/include/syncer_proxy.h old mode 100755 new mode 100644 index 64ebfd05a404e43be1199aff3e4e65cb2a05a969..caf30d763812b14ae264c9f52081879190e9c270 --- a/services/distributeddataservice/libs/distributeddb/syncer/include/syncer_proxy.h +++ b/services/distributeddataservice/libs/distributeddb/syncer/include/syncer_proxy.h @@ -33,7 +33,7 @@ public: int Initialize(ISyncInterface *syncInterface, bool isNeedActive) override; // Close the syncer - int Close() override; + int Close(bool isClosedOperation) override; // Sync function. // param devices: The device id list. @@ -45,7 +45,7 @@ public: const std::function &)> &onComplete, const std::function &onFinalize, bool wait) override; - // Sync function. use SyncParma to reduce paramter. + // Sync function. use SyncParma to reduce parameter. int Sync(const SyncParma ¶m) override; // Remove the operation, with the given syncId, used to clean resource if sync finished or failed. diff --git a/services/distributeddataservice/libs/distributeddb/syncer/src/ability_sync.cpp b/services/distributeddataservice/libs/distributeddb/syncer/src/ability_sync.cpp old mode 100755 new mode 100644 index d8389548d632273dab3b2b404f2959c877e66bca..514a79354efaf2d1a85ecb2efca223fd77a26c2c --- a/services/distributeddataservice/libs/distributeddb/syncer/src/ability_sync.cpp +++ b/services/distributeddataservice/libs/distributeddb/syncer/src/ability_sync.cpp @@ -297,7 +297,7 @@ uint32_t AbilitySyncAckPacket::CalculateLen() const len += Parcel::GetUInt32Len(); // requirePeerConvert_ len += Parcel::GetUInt64Len(); // dbCreateTime_ len += DbAbility::CalculateLen(dbAbility_); // dbAbility_ - len += relationalSyncOpinion_.CalculateParcelLen(softwareVersion_); + len += SchemaNegotiate::CalculateParcelLen(relationalSyncOpinion_); if (len > INT32_MAX) { LOGE("[AbilitySyncAckPacket][CalculateLen] err len:%llu", len); return 0; @@ -709,7 +709,7 @@ int AbilitySync::AckPacketSerialization(uint8_t *buffer, uint32_t length, const if (parcel.IsError() || errCode != E_OK) { return -E_PARSE_FAIL; } - errCode = packet->GetRelationalSyncOpinion().SerializeData(parcel, SOFTWARE_VERSION_CURRENT); + errCode = SchemaNegotiate::SerializeData(packet->GetRelationalSyncOpinion(), parcel); if (parcel.IsError() || errCode != E_OK) { return -E_PARSE_FAIL; } @@ -826,7 +826,7 @@ int AbilitySync::AckPacketDeSerializationTailPart(Parcel &parcel, AbilitySyncAck } packet->SetDbAbility(remoteDbAbility); RelationalSyncOpinion relationalSyncOpinion; - errCode = RelationalSyncOpinion::DeserializeData(parcel, relationalSyncOpinion); + errCode = SchemaNegotiate::DeserializeData(parcel, relationalSyncOpinion); if (errCode != E_OK) { LOGE("[AbilitySync] ack packet DeSerializ RelationalSyncOpinion failed."); return errCode; @@ -1010,7 +1010,7 @@ int AbilitySync::AckMsgCheck(const Message *message, ISyncTaskContext *context) } int ackCode = packet->GetAckCode(); if (ackCode != E_OK) { - LOGE("[AbilitySync][AckMsgCheck] received a errCode %d", ackCode); + LOGE("[AbilitySync][AckMsgCheck] received an errCode %d", ackCode); context->SetTaskErrCode(ackCode); return ackCode; } @@ -1125,7 +1125,7 @@ SyncOpinion AbilitySync::MakeKvSyncOpnion(const AbilitySyncRequestPacket *packet { uint8_t remoteSchemaType = packet->GetSchemaType(); SchemaObject localSchema = (static_cast(storageInterface_))->GetSchemaInfo(); - SyncOpinion localSyncOpinion = SchemaObject::MakeLocalSyncOpinion(localSchema, remoteSchema, remoteSchemaType); + SyncOpinion localSyncOpinion = SchemaNegotiate::MakeLocalSyncOpinion(localSchema, remoteSchema, remoteSchemaType); return localSyncOpinion; } @@ -1134,7 +1134,7 @@ RelationalSyncOpinion AbilitySync::MakeRelationSyncOpnion(const AbilitySyncReque { uint8_t remoteSchemaType = packet->GetSchemaType(); RelationalSchemaObject localSchema = (static_cast(storageInterface_))->GetSchemaInfo(); - return RelationalSchemaObject::MakeLocalSyncOpinion(localSchema, remoteSchema, remoteSchemaType); + return SchemaNegotiate::MakeLocalSyncOpinion(localSchema, remoteSchema, remoteSchemaType); } void AbilitySync::HandleKvAckSchemaParam(const AbilitySyncAckPacket *recvPacket, @@ -1146,8 +1146,8 @@ void AbilitySync::HandleKvAckSchemaParam(const AbilitySyncAckPacket *recvPacket, bool requirePeerConvert = static_cast(recvPacket->GetRequirePeerConvert()); SyncOpinion remoteOpinion = {permitSync, requirePeerConvert, true}; SchemaObject localSchema = (static_cast(storageInterface_))->GetSchemaInfo(); - SyncOpinion syncOpinion = SchemaObject::MakeLocalSyncOpinion(localSchema, remoteSchema, remoteSchemaType); - SyncStrategy localStrategy = SchemaObject::ConcludeSyncStrategy(syncOpinion, remoteOpinion); + SyncOpinion syncOpinion = SchemaNegotiate::MakeLocalSyncOpinion(localSchema, remoteSchema, remoteSchemaType); + SyncStrategy localStrategy = SchemaNegotiate::ConcludeSyncStrategy(syncOpinion, remoteOpinion); SetAbilityAckSyncOpinionInfo(sendPacket, syncOpinion); (static_cast(context))->SetSyncStrategy(localStrategy); } @@ -1158,8 +1158,8 @@ int AbilitySync::HandleRelationAckSchemaParam(const AbilitySyncAckPacket *recvPa std::string remoteSchema = recvPacket->GetSchema(); uint8_t remoteSchemaType = recvPacket->GetSchemaType(); auto localSchema = (static_cast(storageInterface_))->GetSchemaInfo(); - auto localOpinion = RelationalSchemaObject::MakeLocalSyncOpinion(localSchema, remoteSchema, remoteSchemaType); - auto localStrategy = RelationalSchemaObject::ConcludeSyncStrategy(localOpinion, + auto localOpinion = SchemaNegotiate::MakeLocalSyncOpinion(localSchema, remoteSchema, remoteSchemaType); + auto localStrategy = SchemaNegotiate::ConcludeSyncStrategy(localOpinion, recvPacket->GetRelationalSyncOpinion()); (static_cast(context))->SetRelationalSyncStrategy(localStrategy); int errCode = (static_cast(storageInterface_))-> diff --git a/services/distributeddataservice/libs/distributeddb/syncer/src/ability_sync.h b/services/distributeddataservice/libs/distributeddb/syncer/src/ability_sync.h old mode 100755 new mode 100644 index 956f5d0c5698e6fae5f976f3af3cdc920ead946d..4e2f4d968bf1a6fd56b2e84d4cb02045f32129b3 --- a/services/distributeddataservice/libs/distributeddb/syncer/src/ability_sync.h +++ b/services/distributeddataservice/libs/distributeddb/syncer/src/ability_sync.h @@ -25,8 +25,9 @@ #include "isync_task_context.h" #include "parcel.h" #ifdef RELATIONAL_STORE -#include "schema.h" +#include "ischema.h" #endif +#include "schema_negotiate.h" namespace DistributedDB { class AbilitySyncRequestPacket { diff --git a/services/distributeddataservice/libs/distributeddb/syncer/src/commit_history_sync.cpp b/services/distributeddataservice/libs/distributeddb/syncer/src/commit_history_sync.cpp old mode 100755 new mode 100644 index b8c0ad86e3765f0a2b1b28e15c3a88935ba700dd..325431dcf579442ef0356079469f90dd9125bc3f --- a/services/distributeddataservice/libs/distributeddb/syncer/src/commit_history_sync.cpp +++ b/services/distributeddataservice/libs/distributeddb/syncer/src/commit_history_sync.cpp @@ -219,6 +219,8 @@ int CommitHistorySync::Initialize(MultiVerKvDBSyncInterface *storagePtr, ICommun void CommitHistorySync::TimeOutCallback(MultiVerSyncTaskContext *context, const Message *message) const { + (void)context; + (void)message; return; } @@ -536,7 +538,7 @@ bool CommitHistorySync::IsPacketValid(const Message *inMsg, uint16_t messageType int CommitHistorySync::Send(const DeviceID &deviceId, const Message *inMsg) { - SendConfig conf = {false, SEND_TIME_OUT}; + SendConfig conf = {false, false, SEND_TIME_OUT}; int errCode = communicateHandle_->SendMessage(deviceId, inMsg, conf); if (errCode != E_OK) { LOGE("CommitHistorySync::Send ERR! err = %d", errCode); diff --git a/services/distributeddataservice/libs/distributeddb/syncer/src/communicator_proxy.cpp b/services/distributeddataservice/libs/distributeddb/syncer/src/communicator_proxy.cpp index 25cc48bb1ba6683819f09d12fb9a3e65a2d2331f..3eef85f248770abb4704a31e432b58767aca2fbe 100644 --- a/services/distributeddataservice/libs/distributeddb/syncer/src/communicator_proxy.cpp +++ b/services/distributeddataservice/libs/distributeddb/syncer/src/communicator_proxy.cpp @@ -30,7 +30,7 @@ CommunicatorProxy::~CommunicatorProxy() std::lock_guard lock(devCommMapLock_); for (const auto &iter : devCommMap_) { - RefObject::DecObjRef(devCommMap_[iter.first]); + RefObject::DecObjRef(devCommMap_[iter.first].second); } devCommMap_.clear(); } @@ -43,7 +43,7 @@ int CommunicatorProxy::RegOnMessageCallback(const OnMessageCallback &onMessage, std::lock_guard lock(devCommMapLock_); for (const auto &iter : devCommMap_) { - (void) devCommMap_[iter.first]->RegOnMessageCallback(onMessage, inOper); + (void) devCommMap_[iter.first].second->RegOnMessageCallback(onMessage, inOper); } return E_OK; } @@ -56,7 +56,7 @@ int CommunicatorProxy::RegOnConnectCallback(const OnConnectCallback &onConnect, std::lock_guard lock(devCommMapLock_); for (const auto &iter : devCommMap_) { - (void) devCommMap_[iter.first]->RegOnConnectCallback(onConnect, inOper); + (void) devCommMap_[iter.first].second->RegOnConnectCallback(onConnect, inOper); } return E_OK; @@ -70,7 +70,7 @@ int CommunicatorProxy::RegOnSendableCallback(const std::function &on std::lock_guard lock(devCommMapLock_); for (const auto &iter : devCommMap_) { - (void) devCommMap_[iter.first]->RegOnSendableCallback(onSendable, inOper); + (void) devCommMap_[iter.first].second->RegOnSendableCallback(onSendable, inOper); } return E_OK; @@ -87,8 +87,8 @@ void CommunicatorProxy::Activate() { std::lock_guard lock(devCommMapLock_); for (const auto &iter : devCommMap_) { - tempMap[iter.first] = devCommMap_[iter.first]; - RefObject::IncObjRef(devCommMap_[iter.first]); + tempMap[iter.first] = devCommMap_[iter.first].second; + RefObject::IncObjRef(devCommMap_[iter.first].second); } } @@ -112,7 +112,7 @@ uint32_t CommunicatorProxy::GetCommunicatorMtuSize(const std::string &target) co { std::lock_guard lock(devCommMapLock_); if (devCommMap_.count(target) != 0) { - targetCommunicator = devCommMap_.at(target); + targetCommunicator = devCommMap_.at(target).second; RefObject::IncObjRef(targetCommunicator); } } @@ -143,7 +143,7 @@ uint32_t CommunicatorProxy::GetTimeout(const std::string &target) const { std::lock_guard lock(devCommMapLock_); if (devCommMap_.count(target) != 0) { - targetCommunicator = devCommMap_.at(target); + targetCommunicator = devCommMap_.at(target).second; RefObject::IncObjRef(targetCommunicator); } } @@ -176,7 +176,7 @@ int CommunicatorProxy::GetRemoteCommunicatorVersion(const std::string &target, u { std::lock_guard lock(devCommMapLock_); if (devCommMap_.count(target) != 0) { - targetCommunicator = devCommMap_.at(target); + targetCommunicator = devCommMap_.at(target).second; RefObject::IncObjRef(targetCommunicator); } } @@ -205,7 +205,7 @@ int CommunicatorProxy::SendMessage(const std::string &dstTarget, const Message * { std::lock_guard lock(devCommMapLock_); if (devCommMap_.count(dstTarget) != 0) { - targetCommunicator = devCommMap_[dstTarget]; + targetCommunicator = devCommMap_[dstTarget].second; RefObject::IncObjRef(targetCommunicator); } } @@ -229,17 +229,22 @@ void CommunicatorProxy::SetMainCommunicator(ICommunicator *communicator) RefObject::IncObjRef(mainComm_); } -void CommunicatorProxy::SetEqualCommunicator(ICommunicator *communicator, const std::vector &targets) +void CommunicatorProxy::SetEqualCommunicator(ICommunicator *communicator, const std::string &identifier, + const std::vector &targets) { std::lock_guard lock(devCommMapLock_); // Clear offline target for (auto dev = devCommMap_.begin(); dev != devCommMap_.end();) { + if (identifier != dev->second.first) { + dev++; + continue; + } auto iter = std::find_if(targets.begin(), targets.end(), [&dev](const std::string &target) { return target == dev->first; }); if (iter == targets.end()) { - RefObject::DecObjRef(devCommMap_[dev->first]); + RefObject::DecObjRef(devCommMap_[dev->first].second); dev = devCommMap_.erase(dev); continue; } @@ -250,10 +255,10 @@ void CommunicatorProxy::SetEqualCommunicator(ICommunicator *communicator, const for (const auto &target : targets) { if (devCommMap_.count(target) != 0) { // change the identifier and dev relation - RefObject::DecObjRef(devCommMap_[target]); + RefObject::DecObjRef(devCommMap_[target].second); } RefObject::IncObjRef(communicator); - devCommMap_[target] = communicator; + devCommMap_[target] = {identifier, communicator}; } } } // namespace DistributedDB \ No newline at end of file diff --git a/services/distributeddataservice/libs/distributeddb/syncer/src/communicator_proxy.h b/services/distributeddataservice/libs/distributeddb/syncer/src/communicator_proxy.h index a106a7e2926b3073fc13e181c647a164b995c5cd..055bffcb56e154ace6298a46ca1c599e88c7a1d1 100644 --- a/services/distributeddataservice/libs/distributeddb/syncer/src/communicator_proxy.h +++ b/services/distributeddataservice/libs/distributeddb/syncer/src/communicator_proxy.h @@ -50,12 +50,14 @@ public: void SetMainCommunicator(ICommunicator *communicator); // Set an equal communicator for this database, After this called, send msg to the target will use this communicator - void SetEqualCommunicator(ICommunicator *communicator, const std::vector &targets); + void SetEqualCommunicator(ICommunicator *communicator, const std::string &identifier, + const std::vector &targets); private: ICommunicator *mainComm_; mutable std::mutex devCommMapLock_; - std::map devCommMap_; + // key: device value: + std::map> devCommMap_; }; } // namespace DistributedDB #endif // COMMUNICATOR_PROXY_H diff --git a/services/distributeddataservice/libs/distributeddb/syncer/src/device_manager.cpp b/services/distributeddataservice/libs/distributeddb/syncer/src/device_manager.cpp old mode 100755 new mode 100644 index 46ee72b121922c1a9993595f1e1968c104b9d9e6..a45011979975b054fb1c1ef405f5d78716925eb6 --- a/services/distributeddataservice/libs/distributeddb/syncer/src/device_manager.cpp +++ b/services/distributeddataservice/libs/distributeddb/syncer/src/device_manager.cpp @@ -115,7 +115,7 @@ int DeviceManager::SendBroadCast(uint32_t msgId) if (msgId == LOCAL_DATA_CHANGED) { return SendLocalDataChanged(); } - LOGE("[DeviceManager] invalid BroadCast msgId:%d", msgId); + LOGE("[DeviceManager] invalid BroadCast msgId:%u", msgId); return -E_INVALID_ARGS; } @@ -138,7 +138,7 @@ int DeviceManager::SendLocalDataChanged() } msg->SetMessageId(LOCAL_DATA_CHANGED); msg->SetTarget(deviceId); - SendConfig conf = {false, SEND_TIME_OUT}; + SendConfig conf = {false, false, SEND_TIME_OUT}; int errCode = communicator_->SendMessage(deviceId, msg, conf); if (errCode != E_OK) { LOGE("[DeviceManager] SendLocalDataChanged to dev %s{private} failed. err %d", @@ -153,7 +153,7 @@ int DeviceManager::SendLocalDataChanged() bool DeviceManager::IsDeviceOnline(const std::string &deviceId) const { std::lock_guard lock(devicesLock_); - auto iter = std::find(devices_.begin(), devices_.end(), deviceId); + auto iter = std::find(devices_.begin(), devices_.end(), deviceId); return (iter != devices_.end()); } } // namespace DistributedDB \ No newline at end of file diff --git a/services/distributeddataservice/libs/distributeddb/syncer/src/generic_syncer.cpp b/services/distributeddataservice/libs/distributeddb/syncer/src/generic_syncer.cpp old mode 100755 new mode 100644 index 56c577a9c817fc7873923c592d646241a1cb44a7..b91f2549feb21a72aab96a25f5018226496b3c92 --- a/services/distributeddataservice/libs/distributeddb/syncer/src/generic_syncer.cpp +++ b/services/distributeddataservice/libs/distributeddb/syncer/src/generic_syncer.cpp @@ -46,7 +46,8 @@ GenericSyncer::GenericSyncer() queuedManualSyncSize_(0), queuedManualSyncLimit_(DBConstant::QUEUED_SYNC_LIMIT_DEFAULT), manualSyncEnable_(true), - closing_(false) + closing_(false), + engineFinalize_(false) { } @@ -56,6 +57,14 @@ GenericSyncer::~GenericSyncer() if (syncEngine_ != nullptr) { syncEngine_->OnKill([this]() { this->syncEngine_->Close(); }); RefObject::KillAndDecObjRef(syncEngine_); + // waiting all thread exist + std::mutex engineMutex; + std::unique_lock cvLock(engineMutex); + bool engineFinalize = engineFinalizeCv_.wait_for(cvLock, std::chrono::milliseconds(DBConstant::MIN_TIMEOUT), + [this]() { return engineFinalize_; }); + if (!engineFinalize) { + LOGW("syncer finalize before engine finalize!"); + } syncEngine_ = nullptr; } timeHelper_ = nullptr; @@ -117,12 +126,12 @@ int GenericSyncer::Initialize(ISyncInterface *syncInterface, bool isNeedActive) initialized_ = true; } - // RegConnectCallback may start a auto sync, this function can not in syncerLock_ + // RegConnectCallback may start an auto sync, this function can not in syncerLock_ syncEngine_->RegConnectCallback(); return E_OK; } -int GenericSyncer::Close() +int GenericSyncer::Close(bool isClosedOperation) { { std::lock_guard lock(syncerLock_); @@ -139,7 +148,7 @@ int GenericSyncer::Close() } closing_ = true; } - ClearSyncOperations(); + ClearSyncOperations(isClosedOperation); if (syncEngine_ != nullptr) { syncEngine_->Close(); LOGD("[Syncer] Close SyncEngine!"); @@ -273,6 +282,7 @@ uint64_t GenericSyncer::GetTimeStamp() void GenericSyncer::QueryAutoSync(const InternalSyncParma ¶m) { + (void)param; } void GenericSyncer::AddSyncOperation(SyncOperation *operation) @@ -343,21 +353,17 @@ int GenericSyncer::InitSyncEngine(ISyncInterface *syncInterface) LOGI("[Syncer] syncEngine is active"); return E_OK; } - if (syncEngine_ == nullptr) { - syncEngine_ = CreateSyncEngine(); - if (syncEngine_ == nullptr) { - return -E_OUT_OF_MEMORY; - } + int errCode = BuildSyncEngine(); + if (errCode != E_OK) { + return errCode; } - - syncEngine_->OnLastRef([]() { LOGD("[Syncer] SyncEngine finalized"); }); const std::function onlineFunc = std::bind(&GenericSyncer::RemoteDataChanged, this, std::placeholders::_1); const std::function offlineFunc = std::bind(&GenericSyncer::RemoteDeviceOffline, this, std::placeholders::_1); const std::function queryAutoSyncFunc = std::bind(&GenericSyncer::QueryAutoSync, this, std::placeholders::_1); - int errCode = syncEngine_->Initialize(syncInterface, metadata_, onlineFunc, offlineFunc, queryAutoSyncFunc); + errCode = syncEngine_->Initialize(syncInterface, metadata_, onlineFunc, offlineFunc, queryAutoSyncFunc); if (errCode == E_OK) { syncInterface_ = syncInterface; syncInterface->IncRefCount(); @@ -381,11 +387,9 @@ int GenericSyncer::CheckSyncActive(ISyncInterface *syncInterface, bool isNeedAct return E_OK; } LOGI("[Syncer] syncer no need to active"); - if (syncEngine_ == nullptr) { - syncEngine_ = CreateSyncEngine(); - if (syncEngine_ == nullptr) { - return -E_OUT_OF_MEMORY; - } + int errCode = BuildSyncEngine(); + if (errCode != E_OK) { + return errCode; } return -E_NO_NEED_ACTIVE; } @@ -413,6 +417,10 @@ bool GenericSyncer::IsValidMode(int mode) const int GenericSyncer::SyncConditionCheck(QuerySyncObject &query, int mode, bool isQuerySync, const std::vector &devices) const { + (void)query; + (void)mode; + (void)isQuerySync; + (void)(devices); return E_OK; } @@ -425,14 +433,43 @@ bool GenericSyncer::IsValidDevices(const std::vector &devices) cons return true; } -void GenericSyncer::ClearSyncOperations() +void GenericSyncer::ClearSyncOperations(bool isClosedOperation) { - std::lock_guard lock(operationMapLock_); - for (auto &iter : syncOperationMap_) { - RefObject::KillAndDecObjRef(iter.second); - iter.second = nullptr; + std::vector syncOperation; + { + std::lock_guard lock(operationMapLock_); + for (auto &item : syncOperationMap_) { + bool isBlockSync = item.second->IsBlockSync(); + if (isBlockSync || !isClosedOperation) { + int status = (!isClosedOperation) ? SyncOperation::OP_USER_CHANGED : SyncOperation::OP_FAILED; + item.second->SetUnfinishedDevStatus(status); + RefObject::IncObjRef(item.second); + syncOperation.push_back(item.second); + } + } + } + for (auto &operation : syncOperation) { + // block sync operation or userChange will trigger remove sync operation + // caller won't blocked for block sync + // caller won't blocked for userChange operation no mater it is block or non-block sync + TriggerSyncFinished(operation); + RefObject::DecObjRef(operation); + } + { + std::lock_guard lock(operationMapLock_); + for (auto &iter : syncOperationMap_) { + RefObject::KillAndDecObjRef(iter.second); + iter.second = nullptr; + } + syncOperationMap_.clear(); + } +} + +void GenericSyncer::TriggerSyncFinished(SyncOperation *operation) +{ + if (operation != nullptr && operation->CheckIsAllFinished()) { + operation->Finished(); } - syncOperationMap_.clear(); } void GenericSyncer::OnSyncFinished(int syncId) @@ -723,4 +760,21 @@ void GenericSyncer::InitSyncOperation(SyncOperation *operation, const SyncParma operation->SetQuery(param.syncQuery); } } + +int GenericSyncer::BuildSyncEngine() +{ + if (syncEngine_ != nullptr) { + return E_OK; + } + syncEngine_ = CreateSyncEngine(); + if (syncEngine_ == nullptr) { + return -E_OUT_OF_MEMORY; + } + syncEngine_->OnLastRef([this]() { + LOGD("[Syncer] SyncEngine finalized"); + engineFinalize_ = true; + engineFinalizeCv_.notify_all(); + }); + return E_OK; +} } // namespace DistributedDB diff --git a/services/distributeddataservice/libs/distributeddb/syncer/src/generic_syncer.h b/services/distributeddataservice/libs/distributeddb/syncer/src/generic_syncer.h old mode 100755 new mode 100644 index 2d080840648b7eedddfc44401f3939981258cbea..9612b8cada4a63b5afcc0459a3357bc18f67d2b3 --- a/services/distributeddataservice/libs/distributeddb/syncer/src/generic_syncer.h +++ b/services/distributeddataservice/libs/distributeddb/syncer/src/generic_syncer.h @@ -38,7 +38,7 @@ public: int Initialize(ISyncInterface *syncInterface, bool isNeedActive) override; // Close - int Close() override; + int Close(bool isClosedOperation) override; // Sync function. // param devices: The device id list. @@ -50,7 +50,7 @@ public: const std::function &)> &onComplete, const std::function &onFinalize, bool wait) override; - // Sync function. use SyncParma to reduce paramter. + // Sync function. use SyncParma to reduce parameter. int Sync(const SyncParma ¶m) override; // Remove the operation, with the given syncId, used to clean resource if sync finished or failed. @@ -139,7 +139,10 @@ protected: bool IsValidDevices(const std::vector &devices) const; // Used Clear all SyncOperations. - void ClearSyncOperations(); + // isClosedOperation is false while userChanged + void ClearSyncOperations(bool isClosedOperation); + + void TriggerSyncFinished(SyncOperation *operation); // Callback when the special sync finished. void OnSyncFinished(int syncId); @@ -162,6 +165,8 @@ protected: int SyncParamCheck(const SyncParma ¶m) const; + int BuildSyncEngine(); + static int SyncModuleInit(); static int SyncResourceInit(); @@ -189,6 +194,8 @@ protected: mutable std::mutex queuedManualSyncLock_; mutable std::mutex syncerLock_; std::string label_; + bool engineFinalize_; + std::condition_variable engineFinalizeCv_; }; } // namespace DistributedDB diff --git a/services/distributeddataservice/libs/distributeddb/syncer/src/isync_engine.h b/services/distributeddataservice/libs/distributeddb/syncer/src/isync_engine.h index 3bc748449068ccf64b7794a0aa2387cf89ce6bfc..007fb13159d162ab70ced43d94d35020e175d66e 100644 --- a/services/distributeddataservice/libs/distributeddb/syncer/src/isync_engine.h +++ b/services/distributeddataservice/libs/distributeddb/syncer/src/isync_engine.h @@ -78,7 +78,7 @@ public: // Check if the Sync Engine is active, some times synchronization is not allowed virtual bool IsEngineActive() const = 0; - virtual void ResetAbilitySync() = 0; + virtual void SchemaChange() = 0; protected: virtual ~ISyncEngine() {}; diff --git a/services/distributeddataservice/libs/distributeddb/syncer/src/isync_target.h b/services/distributeddataservice/libs/distributeddb/syncer/src/isync_target.h index 36ca06578170a11c18415ce89a342a79d87a4e3e..e8fd05cf24eb47d490a88420c5722dfd54817ace 100644 --- a/services/distributeddataservice/libs/distributeddb/syncer/src/isync_target.h +++ b/services/distributeddataservice/libs/distributeddb/syncer/src/isync_target.h @@ -49,7 +49,7 @@ public: // Get a SyncOperation virtual void GetSyncOperation(SyncOperation *&operation) const = 0; - // Is this target is a auto sync + // Is this target is an auto sync virtual bool IsAutoSync() const = 0; virtual uint32_t GetResponseSessionId() const = 0; diff --git a/services/distributeddataservice/libs/distributeddb/syncer/src/isync_task_context.h b/services/distributeddataservice/libs/distributeddb/syncer/src/isync_task_context.h index a2477a14d0b82f45cef43e36df3afa47de7f7034..7577cce3d4143b5050628b7d0657a4c10b63248c 100644 --- a/services/distributeddataservice/libs/distributeddb/syncer/src/isync_task_context.h +++ b/services/distributeddataservice/libs/distributeddb/syncer/src/isync_task_context.h @@ -172,6 +172,8 @@ public: virtual bool IsCurrentSyncTaskCanBeSkipped() const = 0; virtual void SetIsNeedResetAbilitySync(bool isNeedReset) = 0; + + virtual void SchemaChange() = 0; protected: virtual ~ISyncTaskContext() {}; }; diff --git a/services/distributeddataservice/libs/distributeddb/syncer/src/meta_data.cpp b/services/distributeddataservice/libs/distributeddb/syncer/src/meta_data.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/syncer/src/multi_ver_data_sync.cpp b/services/distributeddataservice/libs/distributeddb/syncer/src/multi_ver_data_sync.cpp old mode 100755 new mode 100644 index b08fe0da9736d7c09875923833d88561d2ee12f7..49c8cac8af5a2d73cd3c548764e5d4ab8604fba2 --- a/services/distributeddataservice/libs/distributeddb/syncer/src/multi_ver_data_sync.cpp +++ b/services/distributeddataservice/libs/distributeddb/syncer/src/multi_ver_data_sync.cpp @@ -576,7 +576,7 @@ bool MultiVerDataSync::IsCommitExisted(const MultiVerCommitNode &commit) int MultiVerDataSync::Send(const DeviceID &deviceId, const Message *inMsg) { - SendConfig conf = {false, SEND_TIME_OUT}; + SendConfig conf = {false, false, SEND_TIME_OUT}; int errCode = communicateHandle_->SendMessage(deviceId, inMsg, conf); if (errCode != E_OK) { LOGE("MultiVerDataSync::Send ERR! ERR = %d", errCode); diff --git a/services/distributeddataservice/libs/distributeddb/syncer/src/multi_ver_sync_engine.cpp b/services/distributeddataservice/libs/distributeddb/syncer/src/multi_ver_sync_engine.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/syncer/src/multi_ver_sync_engine.h b/services/distributeddataservice/libs/distributeddb/syncer/src/multi_ver_sync_engine.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/syncer/src/multi_ver_sync_state_machine.cpp b/services/distributeddataservice/libs/distributeddb/syncer/src/multi_ver_sync_state_machine.cpp old mode 100755 new mode 100644 index 3f2890cfb5657ab1f08fca0938112db0061bf1d7..8e7fe90a5577ba9e199305e596baaaef58509664 --- a/services/distributeddataservice/libs/distributeddb/syncer/src/multi_ver_sync_state_machine.cpp +++ b/services/distributeddataservice/libs/distributeddb/syncer/src/multi_ver_sync_state_machine.cpp @@ -472,16 +472,10 @@ int MultiVerSyncStateMachine::OneCommitSyncFinish() // Due to time sync error, commit timestamp may bigger than currentLocalTime, we need to fix the timestamp TimeOffset timefixOffset = (commit.timestamp < currentLocalTime) ? 0 : (commit.timestamp - static_cast(currentLocalTime)); - ChangeEntriesTimeStamp(entries, outOffset, timefixOffset); LOGD("MultiVerSyncStateMachine::OneCommitSyncFinish src=%s, timefixOffset = %lld", STR_MASK(context_->GetDeviceId()), timefixOffset); commit.timestamp -= static_cast(timefixOffset); - for (MultiVerKvEntry *entry : entries) { - TimeStamp timeStamp; - entry->GetTimestamp(timeStamp); - timeStamp = timeStamp - outOffset - timefixOffset; - entry->SetTimestamp(timeStamp); - } + ChangeEntriesTimeStamp(entries, outOffset, timefixOffset); PerformanceAnalysis *performance = PerformanceAnalysis::GetInstance(); if (performance != nullptr) { performance->StepTimeRecordStart(MV_TEST_RECORDS::RECORD_PUT_COMMIT_DATA); diff --git a/services/distributeddataservice/libs/distributeddb/syncer/src/multi_ver_sync_state_machine.h b/services/distributeddataservice/libs/distributeddb/syncer/src/multi_ver_sync_state_machine.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/syncer/src/multi_ver_sync_task_context.cpp b/services/distributeddataservice/libs/distributeddb/syncer/src/multi_ver_sync_task_context.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/syncer/src/multi_ver_sync_task_context.h b/services/distributeddataservice/libs/distributeddb/syncer/src/multi_ver_sync_task_context.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/syncer/src/multi_ver_syncer.cpp b/services/distributeddataservice/libs/distributeddb/syncer/src/multi_ver_syncer.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/syncer/src/multi_ver_syncer.h b/services/distributeddataservice/libs/distributeddb/syncer/src/multi_ver_syncer.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/syncer/src/single_ver_data_message_schedule.h b/services/distributeddataservice/libs/distributeddb/syncer/src/single_ver_data_message_schedule.h index bbd274eaa07b8ec0d1f67390537914599af2a549..4bdcf6670f7fcb10ab6234df779cfb99a35788e4 100644 --- a/services/distributeddataservice/libs/distributeddb/syncer/src/single_ver_data_message_schedule.h +++ b/services/distributeddataservice/libs/distributeddb/syncer/src/single_ver_data_message_schedule.h @@ -47,7 +47,7 @@ private: void StopTimer(); void ResetTimer(SingleVerSyncTaskContext *context); // when timeout queue size is 0 because thread can move queue msg to map if isNeedReload which is - // actived when queue has new msg is true + // activated when queue has new msg is true // so only need clear map msg int TimeOut(TimerId timerId); diff --git a/services/distributeddataservice/libs/distributeddb/syncer/src/single_ver_data_sync.cpp b/services/distributeddataservice/libs/distributeddb/syncer/src/single_ver_data_sync.cpp old mode 100755 new mode 100644 index 185253f0a6541881d0df77696822bc89771eb6ac..21cb9852e6995060f22a45fde6dca0e8d038d65d --- a/services/distributeddataservice/libs/distributeddb/syncer/src/single_ver_data_sync.cpp +++ b/services/distributeddataservice/libs/distributeddb/syncer/src/single_ver_data_sync.cpp @@ -338,7 +338,7 @@ int SingleVerDataSync::GetUnsyncData(SingleVerSyncTaskContext *context, std::vec GetLocalDeleteSyncWaterMark(context, deletedStartMark); TimeStamp lastQueryTimeStamp = 0; errCode = metadata_->GetLastQueryTime(context->GetQuerySyncId(), - context->GetDeleteSyncId(), lastQueryTimeStamp); + context->GetDeviceId(), lastQueryTimeStamp); if (errCode == E_OK) { QuerySyncObject queryObj = context->GetQuery(); errCode = storage_->GetSyncData(queryObj, @@ -1181,7 +1181,7 @@ void SingleVerDataSync::SendSaveDataNotifyPacket(SingleVerSyncTaskContext *conte uint32_t sessionId, uint32_t sequenceId, uint32_t inMsgId) { if (inMsgId != DATA_SYNC_MESSAGE && inMsgId != QUERY_SYNC_MESSAGE) { - LOGE("[SingleVerDataSync] messageId not avaiable."); + LOGE("[SingleVerDataSync] messageId not available."); return; } Message *ackMessage = new (std::nothrow) Message(inMsgId); diff --git a/services/distributeddataservice/libs/distributeddb/syncer/src/single_ver_data_sync.h b/services/distributeddataservice/libs/distributeddb/syncer/src/single_ver_data_sync.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/syncer/src/single_ver_relational_sync_task_context.cpp b/services/distributeddataservice/libs/distributeddb/syncer/src/single_ver_relational_sync_task_context.cpp index 4403fea361b70c25a0c56bd633d623dc063a6637..ef556385f0ccca1947d16daaa1097bcf9745eb62 100644 --- a/services/distributeddataservice/libs/distributeddb/syncer/src/single_ver_relational_sync_task_context.cpp +++ b/services/distributeddataservice/libs/distributeddb/syncer/src/single_ver_relational_sync_task_context.cpp @@ -61,7 +61,11 @@ void SingleVerRelationalSyncTaskContext::SetRelationalSyncStrategy(RelationalSyn SyncStrategy SingleVerRelationalSyncTaskContext::GetSyncStrategy(QuerySyncObject &querySyncObject) const { std::lock_guard autoLock(syncStrategyMutex_); - return relationalSyncStrategy_.GetTableStrategy(querySyncObject.GetRelationTableName()); + auto it = relationalSyncStrategy_.find(querySyncObject.GetRelationTableName()); + if (it == relationalSyncStrategy_.end()) { + return {}; + } + return it->second; } void SingleVerRelationalSyncTaskContext::SetIsNeedResetAbilitySync(bool isNeedReset) @@ -70,6 +74,11 @@ void SingleVerRelationalSyncTaskContext::SetIsNeedResetAbilitySync(bool isNeedRe if (isNeedResetAbilitySync_) { SetIsSchemaSync(false); } +} + +void SingleVerRelationalSyncTaskContext::SchemaChange() +{ + SetIsNeedResetAbilitySync(true); std::lock_guard autoLock(syncStrategyMutex_); relationalSyncStrategy_ = {}; } diff --git a/services/distributeddataservice/libs/distributeddb/syncer/src/single_ver_relational_sync_task_context.h b/services/distributeddataservice/libs/distributeddb/syncer/src/single_ver_relational_sync_task_context.h index 3334ad90a05cbab3b72e00a7574f8364420831f1..0146c42bf84c14b5f841439c644bbea02e805d9d 100644 --- a/services/distributeddataservice/libs/distributeddb/syncer/src/single_ver_relational_sync_task_context.h +++ b/services/distributeddataservice/libs/distributeddb/syncer/src/single_ver_relational_sync_task_context.h @@ -35,6 +35,8 @@ public: SyncStrategy GetSyncStrategy(QuerySyncObject &querySyncObject) const override; void SetIsNeedResetAbilitySync(bool isNeedReset) override; + + void SchemaChange() override; protected: ~SingleVerRelationalSyncTaskContext() override; void CopyTargetData(const ISyncTarget *target, const TaskParam &taskParam) override; diff --git a/services/distributeddataservice/libs/distributeddb/syncer/src/single_ver_relational_syncer.cpp b/services/distributeddataservice/libs/distributeddb/syncer/src/single_ver_relational_syncer.cpp index aa274c10041a710d3d3e1d281017d1015d017bda..3b40c6627559318676adc4a44f29653d3f17dbbe 100644 --- a/services/distributeddataservice/libs/distributeddb/syncer/src/single_ver_relational_syncer.cpp +++ b/services/distributeddataservice/libs/distributeddb/syncer/src/single_ver_relational_syncer.cpp @@ -156,7 +156,7 @@ void SingleVerRelationalSyncer::LocalDataChanged(int notifyEvent) void SingleVerRelationalSyncer::SchemaChangeCallback() { if (syncEngine_ != nullptr) { - syncEngine_->ResetAbilitySync(); + syncEngine_->SchemaChange(); } } diff --git a/services/distributeddataservice/libs/distributeddb/syncer/src/single_ver_relational_syncer.h b/services/distributeddataservice/libs/distributeddb/syncer/src/single_ver_relational_syncer.h index 18f42a48a90cdf07635a03ca3e6c4e5f170b149f..cd54e6d4ff2ac07a1a08222070df54e25c92b24e 100644 --- a/services/distributeddataservice/libs/distributeddb/syncer/src/single_ver_relational_syncer.h +++ b/services/distributeddataservice/libs/distributeddb/syncer/src/single_ver_relational_syncer.h @@ -24,7 +24,7 @@ public: int Initialize(ISyncInterface *syncInterface, bool isNeedActive) override; - // Sync function. use SyncParma to reduce paramter. + // Sync function. use SyncParma to reduce parameter. int Sync(const SyncParma ¶m) override; void EnableAutoSync(bool enable) override; diff --git a/services/distributeddataservice/libs/distributeddb/syncer/src/single_ver_serialize_manager.cpp b/services/distributeddataservice/libs/distributeddb/syncer/src/single_ver_serialize_manager.cpp index 41f410fe606a95699f1093960ee1febf24b29f4b..c5c6bf99311237edf455d4be54a0fff1a10cd4ef 100644 --- a/services/distributeddataservice/libs/distributeddb/syncer/src/single_ver_serialize_manager.cpp +++ b/services/distributeddataservice/libs/distributeddb/syncer/src/single_ver_serialize_manager.cpp @@ -346,17 +346,17 @@ int SingleVerSerializeManager::DataPacketDeSerialization(const uint8_t *buffer, return -E_VERSION_NOT_SUPPORT; } + packLen += static_cast(GenericSingleVerKvEntry::DeSerializeDatas(dataItems, parcel)); + if (parcel.IsError()) { + return -E_PARSE_FAIL; + } + auto packet = new (std::nothrow) DataRequestPacket(); if (packet == nullptr) { return -E_OUT_OF_MEMORY; } packet->SetVersion(version); - packLen += static_cast(GenericSingleVerKvEntry::DeSerializeDatas(dataItems, parcel)); - if (parcel.IsError()) { - return -E_PARSE_FAIL; - } - packet->SetData(dataItems); int errCode = DataPacketSyncerPartDeSerialization(parcel, packet, packLen, length, version); if (errCode != E_OK) { diff --git a/services/distributeddataservice/libs/distributeddb/syncer/src/single_ver_sync_engine.cpp b/services/distributeddataservice/libs/distributeddb/syncer/src/single_ver_sync_engine.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/syncer/src/single_ver_sync_state_machine.cpp b/services/distributeddataservice/libs/distributeddb/syncer/src/single_ver_sync_state_machine.cpp old mode 100755 new mode 100644 index c92ca4f48ee53116c9d9ad2f5f929fc98069708e..aef40cbe56fb53417ac9c0f0ec3100c116300eca --- a/services/distributeddataservice/libs/distributeddb/syncer/src/single_ver_sync_state_machine.cpp +++ b/services/distributeddataservice/libs/distributeddb/syncer/src/single_ver_sync_state_machine.cpp @@ -32,6 +32,8 @@ #include "single_ver_data_sync_utils.h" namespace DistributedDB { +using Event = SingleVerSyncStateMachine::Event; +using State = SingleVerSyncStateMachine::State; namespace { // used for state switch table const int CURRENT_STATE_INDEX = 0; @@ -41,54 +43,54 @@ namespace { // drop v1 and v2 table by one optimize, dataSend mode in all version go with slide window mode. // State switch table v3, has three columns, CurrentState, Event, and OutSate const std::vector> STATE_SWITCH_TABLE_V3 = { - {IDLE, START_SYNC_EVENT, TIME_SYNC}, + {State::IDLE, Event::START_SYNC_EVENT, State::TIME_SYNC}, // In TIME_SYNC state - {TIME_SYNC, TIME_SYNC_FINISHED_EVENT, ABILITY_SYNC}, - {TIME_SYNC, TIME_OUT_EVENT, SYNC_TIME_OUT}, - {TIME_SYNC, INNER_ERR_EVENT, INNER_ERR}, + {State::TIME_SYNC, Event::TIME_SYNC_FINISHED_EVENT, State::ABILITY_SYNC}, + {State::TIME_SYNC, Event::TIME_OUT_EVENT, State::SYNC_TIME_OUT}, + {State::TIME_SYNC, Event::INNER_ERR_EVENT, State::INNER_ERR}, // In ABILITY_SYNC state, compare version num and schema - {ABILITY_SYNC, VERSION_NOT_SUPPOR_EVENT, INNER_ERR}, - {ABILITY_SYNC, ABILITY_SYNC_FINISHED_EVENT, START_INITIACTIVE_DATA_SYNC}, - {ABILITY_SYNC, TIME_OUT_EVENT, SYNC_TIME_OUT}, - {ABILITY_SYNC, INNER_ERR_EVENT, INNER_ERR}, - {ABILITY_SYNC, CONTROL_CMD_EVENT, SYNC_CONTROL_CMD}, + {State::ABILITY_SYNC, Event::VERSION_NOT_SUPPOR_EVENT, State::INNER_ERR}, + {State::ABILITY_SYNC, Event::ABILITY_SYNC_FINISHED_EVENT, State::START_INITIACTIVE_DATA_SYNC}, + {State::ABILITY_SYNC, Event::TIME_OUT_EVENT, State::SYNC_TIME_OUT}, + {State::ABILITY_SYNC, Event::INNER_ERR_EVENT, State::INNER_ERR}, + {State::ABILITY_SYNC, Event::CONTROL_CMD_EVENT, State::SYNC_CONTROL_CMD}, // In START_INITIACTIVE_DATA_SYNC state, send a sync request, and send first packt of data sync - {START_INITIACTIVE_DATA_SYNC, NEED_ABILITY_SYNC_EVENT, ABILITY_SYNC}, - {START_INITIACTIVE_DATA_SYNC, TIME_OUT_EVENT, SYNC_TIME_OUT}, - {START_INITIACTIVE_DATA_SYNC, INNER_ERR_EVENT, INNER_ERR}, - {START_INITIACTIVE_DATA_SYNC, SEND_FINISHED_EVENT, START_PASSIVE_DATA_SYNC}, - {START_INITIACTIVE_DATA_SYNC, RE_SEND_DATA_EVENT, START_INITIACTIVE_DATA_SYNC}, + {State::START_INITIACTIVE_DATA_SYNC, Event::NEED_ABILITY_SYNC_EVENT, State::ABILITY_SYNC}, + {State::START_INITIACTIVE_DATA_SYNC, Event::TIME_OUT_EVENT, State::SYNC_TIME_OUT}, + {State::START_INITIACTIVE_DATA_SYNC, Event::INNER_ERR_EVENT, State::INNER_ERR}, + {State::START_INITIACTIVE_DATA_SYNC, Event::SEND_FINISHED_EVENT, State::START_PASSIVE_DATA_SYNC}, + {State::START_INITIACTIVE_DATA_SYNC, Event::RE_SEND_DATA_EVENT, State::START_INITIACTIVE_DATA_SYNC}, // In START_PASSIVE_DATA_SYNC state, do response pull request, and send first packt of data sync - {START_PASSIVE_DATA_SYNC, SEND_FINISHED_EVENT, START_PASSIVE_DATA_SYNC}, - {START_PASSIVE_DATA_SYNC, RESPONSE_TASK_FINISHED_EVENT, WAIT_FOR_RECEIVE_DATA_FINISH}, - {START_PASSIVE_DATA_SYNC, TIME_OUT_EVENT, SYNC_TIME_OUT}, - {START_PASSIVE_DATA_SYNC, INNER_ERR_EVENT, INNER_ERR}, - {START_PASSIVE_DATA_SYNC, NEED_ABILITY_SYNC_EVENT, ABILITY_SYNC}, - {START_PASSIVE_DATA_SYNC, RE_SEND_DATA_EVENT, START_PASSIVE_DATA_SYNC}, + {State::START_PASSIVE_DATA_SYNC, Event::SEND_FINISHED_EVENT, State::START_PASSIVE_DATA_SYNC}, + {State::START_PASSIVE_DATA_SYNC, Event::RESPONSE_TASK_FINISHED_EVENT, State::WAIT_FOR_RECEIVE_DATA_FINISH}, + {State::START_PASSIVE_DATA_SYNC, Event::TIME_OUT_EVENT, State::SYNC_TIME_OUT}, + {State::START_PASSIVE_DATA_SYNC, Event::INNER_ERR_EVENT, State::INNER_ERR}, + {State::START_PASSIVE_DATA_SYNC, Event::NEED_ABILITY_SYNC_EVENT, State::ABILITY_SYNC}, + {State::START_PASSIVE_DATA_SYNC, Event::RE_SEND_DATA_EVENT, State::START_PASSIVE_DATA_SYNC}, // In WAIT_FOR_RECEIVE_DATA_FINISH, - {WAIT_FOR_RECEIVE_DATA_FINISH, RECV_FINISHED_EVENT, SYNC_TASK_FINISHED}, - {WAIT_FOR_RECEIVE_DATA_FINISH, START_PULL_RESPONSE_EVENT, START_PASSIVE_DATA_SYNC}, - {WAIT_FOR_RECEIVE_DATA_FINISH, TIME_OUT_EVENT, SYNC_TIME_OUT}, - {WAIT_FOR_RECEIVE_DATA_FINISH, INNER_ERR_EVENT, INNER_ERR}, - {WAIT_FOR_RECEIVE_DATA_FINISH, NEED_ABILITY_SYNC_EVENT, ABILITY_SYNC}, + {State::WAIT_FOR_RECEIVE_DATA_FINISH, Event::RECV_FINISHED_EVENT, State::SYNC_TASK_FINISHED}, + {State::WAIT_FOR_RECEIVE_DATA_FINISH, Event::START_PULL_RESPONSE_EVENT, State::START_PASSIVE_DATA_SYNC}, + {State::WAIT_FOR_RECEIVE_DATA_FINISH, Event::TIME_OUT_EVENT, State::SYNC_TIME_OUT}, + {State::WAIT_FOR_RECEIVE_DATA_FINISH, Event::INNER_ERR_EVENT, State::INNER_ERR}, + {State::WAIT_FOR_RECEIVE_DATA_FINISH, Event::NEED_ABILITY_SYNC_EVENT, State::ABILITY_SYNC}, - {SYNC_CONTROL_CMD, SEND_FINISHED_EVENT, SYNC_TASK_FINISHED}, - {SYNC_CONTROL_CMD, TIME_OUT_EVENT, SYNC_TIME_OUT}, - {SYNC_CONTROL_CMD, INNER_ERR_EVENT, INNER_ERR}, - {SYNC_CONTROL_CMD, NEED_ABILITY_SYNC_EVENT, ABILITY_SYNC}, + {State::SYNC_CONTROL_CMD, Event::SEND_FINISHED_EVENT, State::SYNC_TASK_FINISHED}, + {State::SYNC_CONTROL_CMD, Event::TIME_OUT_EVENT, State::SYNC_TIME_OUT}, + {State::SYNC_CONTROL_CMD, Event::INNER_ERR_EVENT, State::INNER_ERR}, + {State::SYNC_CONTROL_CMD, Event::NEED_ABILITY_SYNC_EVENT, State::ABILITY_SYNC}, // In SYNC_TASK_FINISHED, - {SYNC_TASK_FINISHED, ALL_TASK_FINISHED_EVENT, IDLE}, - {SYNC_TASK_FINISHED, START_SYNC_EVENT, TIME_SYNC}, + {State::SYNC_TASK_FINISHED, Event::ALL_TASK_FINISHED_EVENT, State::IDLE}, + {State::SYNC_TASK_FINISHED, Event::START_SYNC_EVENT, State::TIME_SYNC}, // SYNC_TIME_OUT and INNE_ERR state, just do some exception resolve - {SYNC_TIME_OUT, ANY_EVENT, SYNC_TASK_FINISHED}, - {INNER_ERR, ANY_EVENT, SYNC_TASK_FINISHED}, + {State::SYNC_TIME_OUT, Event::ANY_EVENT, State::SYNC_TASK_FINISHED}, + {State::INNER_ERR, Event::ANY_EVENT, State::SYNC_TASK_FINISHED}, }; } diff --git a/services/distributeddataservice/libs/distributeddb/syncer/src/single_ver_sync_state_machine.h b/services/distributeddataservice/libs/distributeddb/syncer/src/single_ver_sync_state_machine.h old mode 100755 new mode 100644 index 44aca53fd788b587f7484d0eb566e80f39956658..6fcc994bd1d1922fac8b7b48a8c1549dbe36521b --- a/services/distributeddataservice/libs/distributeddb/syncer/src/single_ver_sync_state_machine.h +++ b/services/distributeddataservice/libs/distributeddb/syncer/src/single_ver_sync_state_machine.h @@ -32,7 +32,9 @@ #include "time_helper.h" namespace DistributedDB { -namespace { +using stateMappingHandler = std::function; +class SingleVerSyncStateMachine : public SyncStateMachine { +public: enum State { IDLE = 0, TIME_SYNC, @@ -66,12 +68,6 @@ namespace { CONTROL_CMD_EVENT, ANY_EVENT }; -} - -using stateMappingHandler = std::function; -class SingleVerSyncStateMachine : public SyncStateMachine { -public: - SingleVerSyncStateMachine(); ~SingleVerSyncStateMachine() override; diff --git a/services/distributeddataservice/libs/distributeddb/syncer/src/single_ver_sync_target.cpp b/services/distributeddataservice/libs/distributeddb/syncer/src/single_ver_sync_target.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/syncer/src/single_ver_sync_task_context.cpp b/services/distributeddataservice/libs/distributeddb/syncer/src/single_ver_sync_task_context.cpp old mode 100755 new mode 100644 index 2235ded7a5b87fcf9b6a7e074bc7ffc7d5ad3a2d..456a03d709fe54283713385e03d255555ac13f95 --- a/services/distributeddataservice/libs/distributeddb/syncer/src/single_ver_sync_task_context.cpp +++ b/services/distributeddataservice/libs/distributeddb/syncer/src/single_ver_sync_task_context.cpp @@ -484,6 +484,9 @@ bool SingleVerSyncTaskContext::IsCurrentSyncTaskCanBeSkipped() const return false; } } else if (mode_ == SyncModeType::QUERY_PUSH) { + if (syncOperation_ == nullptr) { + return true; + } auto it = lastQuerySyncTaskStatusMap_.find(syncOperation_->GetQueryId()); if (it == lastQuerySyncTaskStatusMap_.end()) { // no last query_push and push diff --git a/services/distributeddataservice/libs/distributeddb/syncer/src/single_ver_sync_task_context.h b/services/distributeddataservice/libs/distributeddb/syncer/src/single_ver_sync_task_context.h old mode 100755 new mode 100644 index 303ba4a408ce737718b319e6fcebee93864a8a90..f0619a41087daf8e063edc5cc4de81b50ff63262 --- a/services/distributeddataservice/libs/distributeddb/syncer/src/single_ver_sync_task_context.h +++ b/services/distributeddataservice/libs/distributeddb/syncer/src/single_ver_sync_task_context.h @@ -23,7 +23,7 @@ #include "db_ability.h" #include "query_sync_object.h" -#include "schema.h" +#include "schema_negotiate.h" #include "single_ver_kvdb_sync_interface.h" #include "single_ver_sync_target.h" #include "subscribe_manager.h" diff --git a/services/distributeddataservice/libs/distributeddb/syncer/src/single_ver_syncer.cpp b/services/distributeddataservice/libs/distributeddb/syncer/src/single_ver_syncer.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/syncer/src/single_ver_syncer.h b/services/distributeddataservice/libs/distributeddb/syncer/src/single_ver_syncer.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/syncer/src/sync_engine.cpp b/services/distributeddataservice/libs/distributeddb/syncer/src/sync_engine.cpp old mode 100755 new mode 100644 index f86e196379492f5f0613a78dd20da9ae939adde9..f2bbb15018fa4e3f3cfffcca96125b5ba390d355 --- a/services/distributeddataservice/libs/distributeddb/syncer/src/sync_engine.cpp +++ b/services/distributeddataservice/libs/distributeddb/syncer/src/sync_engine.cpp @@ -749,7 +749,7 @@ int SyncEngine::SetEqualIdentifier(const std::string &identifier, const std::vec LOGI("[SyncEngine] set equal identifier=%s, original=%s, targetDevices=%s", DBCommon::TransferStringToHex(identifier).c_str(), label_.c_str(), targetDevices.substr(0, targetDevices.size() - 1).c_str()); - communicatorProxy_->SetEqualCommunicator(communicator, targets); + communicatorProxy_->SetEqualCommunicator(communicator, identifier, targets); communicator->Activate(); return E_OK; } @@ -771,6 +771,13 @@ void SyncEngine::SetEqualIdentifier() void SyncEngine::SetEqualIdentifierMap(const std::string &identifier, const std::vector &targets) { + for (auto iter = equalIdentifierMap_.begin(); iter != equalIdentifierMap_.end();) { + if (identifier == iter->second) { + iter = equalIdentifierMap_.erase(iter); + continue; + } + iter++; + } for (auto &device : targets) { equalIdentifierMap_[device] = identifier; } @@ -1000,7 +1007,7 @@ bool SyncEngine::IsEngineActive() const return isActive_; } -void SyncEngine::ResetAbilitySync() +void SyncEngine::SchemaChange() { std::lock_guard lock(contextMapLock_); for (auto &enrty : syncTaskContextMap_) { @@ -1009,9 +1016,7 @@ void SyncEngine::ResetAbilitySync() continue; } // IncRef for SyncEngine to make sure context is valid, to avoid a big lock - RefObject::IncObjRef(context); - context->SetIsNeedResetAbilitySync(true); - RefObject::DecObjRef(context); + context->SchemaChange(); } } } // namespace DistributedDB diff --git a/services/distributeddataservice/libs/distributeddb/syncer/src/sync_engine.h b/services/distributeddataservice/libs/distributeddb/syncer/src/sync_engine.h old mode 100755 new mode 100644 index 280c7cc2147af7a4ea1afd83914a022c56c05209..f942302f3c5f14db8a1b5c55db0b9b3c39e97403 --- a/services/distributeddataservice/libs/distributeddb/syncer/src/sync_engine.h +++ b/services/distributeddataservice/libs/distributeddb/syncer/src/sync_engine.h @@ -107,7 +107,7 @@ public: bool IsEngineActive() const override; - void ResetAbilitySync() override; + void SchemaChange() override; protected: // Create a context diff --git a/services/distributeddataservice/libs/distributeddb/syncer/src/sync_operation.cpp b/services/distributeddataservice/libs/distributeddb/syncer/src/sync_operation.cpp old mode 100755 new mode 100644 index 8bb39a2e9b361aaf082d44bf0de534b2680d1fb8..48c7fc7e19c8fdd35530e996578d51c275f45c16 --- a/services/distributeddataservice/libs/distributeddb/syncer/src/sync_operation.cpp +++ b/services/distributeddataservice/libs/distributeddb/syncer/src/sync_operation.cpp @@ -99,6 +99,26 @@ void SyncOperation::SetStatus(const std::string &deviceId, int status) } } +void SyncOperation::SetUnfinishedDevStatus(int status) +{ + LOGD("[SyncOperation] SetUnfinishedDevStatus status %d", status); + AutoLock lockGuard(this); + if (IsKilled()) { + LOGE("[SyncOperation] SetUnfinishedDevStatus failed, the SyncOperation has been killed!"); + return; + } + if (isFinished_) { + LOGI("[SyncOperation] SetUnfinishedDevStatus already finished"); + return; + } + for (auto &item : statuses_) { + if (item.second >= OP_FINISHED_ALL) { + continue; + } + item.second = status; + } +} + int SyncOperation::GetStatus(const std::string &deviceId) const { AutoLock lockGuard(this); @@ -258,7 +278,7 @@ SyncType SyncOperation::GetSyncType(int mode) int SyncOperation::TransferSyncMode(int mode) { // AUTO_PUSH and AUTO_PULL mode is used before sync, RESPONSE_PULL is regarded as push or query push mode. - // so for the three mode, it is no need to transfered. + // so for the three mode, it is no need to transferred. if (mode >= SyncModeType::QUERY_PUSH && mode <= SyncModeType::QUERY_PUSH_PULL) { return (mode - QUERY_SYNC_MODE_BASE); } @@ -288,6 +308,7 @@ const std::map &SyncOperation::DBStatusTransMap() { static_cast(OP_MAX_LIMITS), OVER_MAX_LIMITS }, { static_cast(OP_SCHEMA_CHANGED), DISTRIBUTED_SCHEMA_CHANGED }, { static_cast(OP_INVALID_ARGS), INVALID_ARGS }, + { static_cast(OP_USER_CHANGED), USER_CHANGED}, }; return transMap; } diff --git a/services/distributeddataservice/libs/distributeddb/syncer/src/sync_operation.h b/services/distributeddataservice/libs/distributeddb/syncer/src/sync_operation.h index 46510a772122f193bb7eb956a3431a4ea387750e..229c8320b9c557d00ae4935f52154c185d63ffa8 100644 --- a/services/distributeddataservice/libs/distributeddb/syncer/src/sync_operation.h +++ b/services/distributeddataservice/libs/distributeddb/syncer/src/sync_operation.h @@ -53,7 +53,8 @@ public: OP_INTERCEPT_DATA_FAIL, OP_MAX_LIMITS, OP_SCHEMA_CHANGED, - OP_INVALID_ARGS + OP_INVALID_ARGS, + OP_USER_CHANGED }; using UserCallback = std::function)>; @@ -77,6 +78,9 @@ public: // Set the sync status, running or finished void SetStatus(const std::string &deviceId, int status); + // Set the unfinished devices sync status, running or finished + void SetUnfinishedDevStatus(int status); + // Set the identifier, used in SyncOperation::Finished void SetIdentifier(const std::vector &identifier); @@ -159,7 +163,7 @@ private: // Is this operation is a block sync bool isBlockSync_; - // Is this operation is a auto sync + // Is this operation is an auto sync bool isAutoSync_; // Is this operation has finished diff --git a/services/distributeddataservice/libs/distributeddb/syncer/src/sync_state_machine.cpp b/services/distributeddataservice/libs/distributeddb/syncer/src/sync_state_machine.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/syncer/src/sync_state_machine.h b/services/distributeddataservice/libs/distributeddb/syncer/src/sync_state_machine.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/syncer/src/sync_target.cpp b/services/distributeddataservice/libs/distributeddb/syncer/src/sync_target.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/syncer/src/sync_target.h b/services/distributeddataservice/libs/distributeddb/syncer/src/sync_target.h old mode 100755 new mode 100644 index 23efcd763dd91db4bb526265764721b24db9e3fd..11df7813e03996f62ceb7a890f6b68a5d5d8f41c --- a/services/distributeddataservice/libs/distributeddb/syncer/src/sync_target.h +++ b/services/distributeddataservice/libs/distributeddb/syncer/src/sync_target.h @@ -45,7 +45,7 @@ public: // Get a SyncOperation void GetSyncOperation(SyncOperation *&operation) const override; - // Is this target is a auto sync + // Is this target is an auto sync bool IsAutoSync() const override; uint32_t GetResponseSessionId() const override; diff --git a/services/distributeddataservice/libs/distributeddb/syncer/src/sync_task_context.cpp b/services/distributeddataservice/libs/distributeddb/syncer/src/sync_task_context.cpp old mode 100755 new mode 100644 index 123310d0c7095d02ca256370254cb8fedee53eef..d714dd9520dd3034c5ffd2054ff134fcb4e964cf --- a/services/distributeddataservice/libs/distributeddb/syncer/src/sync_task_context.cpp +++ b/services/distributeddataservice/libs/distributeddb/syncer/src/sync_task_context.cpp @@ -696,4 +696,9 @@ bool SyncTaskContext::IsCurrentSyncTaskCanBeSkipped() const void SyncTaskContext::ResetLastPushTaskStatus() { } + +void SyncTaskContext::SchemaChange() +{ + SetIsNeedResetAbilitySync(true); +} } // namespace DistributedDB diff --git a/services/distributeddataservice/libs/distributeddb/syncer/src/sync_task_context.h b/services/distributeddataservice/libs/distributeddb/syncer/src/sync_task_context.h old mode 100755 new mode 100644 index e7ed88459b3a4d664d145ff965a4561682ad9756..a1df059924dce09dc8e64a7fe75b808a72d7cdc5 --- a/services/distributeddataservice/libs/distributeddb/syncer/src/sync_task_context.h +++ b/services/distributeddataservice/libs/distributeddb/syncer/src/sync_task_context.h @@ -200,8 +200,11 @@ public: virtual void ResetLastPushTaskStatus(); bool GetIsNeedResetAbilitySync() const; + void SetIsNeedResetAbilitySync(bool isNeedReset) override; + void SchemaChange() override; + protected: const static int KILL_WAIT_SECONDS = INT32_MAX; diff --git a/services/distributeddataservice/libs/distributeddb/syncer/src/sync_types.h b/services/distributeddataservice/libs/distributeddb/syncer/src/sync_types.h index ab36e40b2cc912b75cf63aca6ba3103c17e50615..3af5663de665b1c554c9e938a222068acdac03bf 100644 --- a/services/distributeddataservice/libs/distributeddb/syncer/src/sync_types.h +++ b/services/distributeddataservice/libs/distributeddb/syncer/src/sync_types.h @@ -75,7 +75,6 @@ struct InternalSyncParma { QuerySyncObject syncQuery; }; -constexpr uint32_t SEND_TIME_OUT = 3000; // 3s constexpr int NOT_SURPPORT_SEC_CLASSIFICATION = 0xff; constexpr uint8_t QUERY_SYNC_MODE_BASE = SyncModeType::QUERY_PUSH; constexpr int AUTO_RETRY_TIMES = 3; diff --git a/services/distributeddataservice/libs/distributeddb/syncer/src/syncer_factory.cpp b/services/distributeddataservice/libs/distributeddb/syncer/src/syncer_factory.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/syncer/src/syncer_proxy.cpp b/services/distributeddataservice/libs/distributeddb/syncer/src/syncer_proxy.cpp old mode 100755 new mode 100644 index fbe0cb5bef0d1367312b514bc30d2d4b6a82c62a..71a9fbe2450f38227d3c1bb13bf20d01b1081f0c --- a/services/distributeddataservice/libs/distributeddb/syncer/src/syncer_proxy.cpp +++ b/services/distributeddataservice/libs/distributeddb/syncer/src/syncer_proxy.cpp @@ -46,12 +46,12 @@ int SyncerProxy::Initialize(ISyncInterface *syncInterface, bool isNeedActive) return syncer_->Initialize(syncInterface, isNeedActive); } -int SyncerProxy::Close() +int SyncerProxy::Close(bool isClosedOperation) { if (syncer_ == nullptr) { return -E_NOT_INIT; } - return syncer_->Close(); + return syncer_->Close(isClosedOperation); } int SyncerProxy::Sync(const std::vector &devices, int mode, diff --git a/services/distributeddataservice/libs/distributeddb/syncer/src/time_helper.cpp b/services/distributeddataservice/libs/distributeddb/syncer/src/time_helper.cpp old mode 100755 new mode 100644 index 963ee284c364bed850cdf0f9f9aec5709f2ad8fb..a0374f7be001036709cade2f205fdf924f2fb819 --- a/services/distributeddataservice/libs/distributeddb/syncer/src/time_helper.cpp +++ b/services/distributeddataservice/libs/distributeddb/syncer/src/time_helper.cpp @@ -72,7 +72,7 @@ int TimeHelper::Initialize(const ISyncInterface *inStorage, std::shared_ptr(maxItemTime - currentSysTime + MS_TO_100_NS); // 1ms + localTimeOffset = static_cast(maxItemTime - currentSysTime + MS_TO_100_NS); // 1ms int errCode = SaveLocalTimeOffset(localTimeOffset); if (errCode != E_OK) { LOGE("[TimeHelper] save local time offset faield,err=%d", errCode); diff --git a/services/distributeddataservice/libs/distributeddb/syncer/src/time_sync.cpp b/services/distributeddataservice/libs/distributeddb/syncer/src/time_sync.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/syncer/src/time_sync.h b/services/distributeddataservice/libs/distributeddb/syncer/src/time_sync.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/syncer/src/value_slice_sync.cpp b/services/distributeddataservice/libs/distributeddb/syncer/src/value_slice_sync.cpp old mode 100755 new mode 100644 index 7582cd3d9bb6fafd9d63bf05f2d55b95a7bd905d..f6e9ecce9afbe2e31b2893303fc843a20250a825 --- a/services/distributeddataservice/libs/distributeddb/syncer/src/value_slice_sync.cpp +++ b/services/distributeddataservice/libs/distributeddb/syncer/src/value_slice_sync.cpp @@ -521,7 +521,7 @@ int ValueSliceSync::GetValidValueSliceHashNode(MultiVerSyncTaskContext *context, int ValueSliceSync::Send(const DeviceID &deviceId, const Message *inMsg) { - SendConfig conf = {false, SEND_TIME_OUT}; + SendConfig conf = {false, false, SEND_TIME_OUT}; int errCode = communicateHandle_->SendMessage(deviceId, inMsg, conf); if (errCode != E_OK) { LOGE("ValueSliceSync::Send ERR! err = %d", errCode); diff --git a/services/distributeddataservice/libs/distributeddb/test/BUILD.gn b/services/distributeddataservice/libs/distributeddb/test/BUILD.gn old mode 100755 new mode 100644 index c29b5c53ac48729da63998e5f9cac51bc5752735..7185d447e7aee41a5fdf283aab23b330c7599eb0 --- a/services/distributeddataservice/libs/distributeddb/test/BUILD.gn +++ b/services/distributeddataservice/libs/distributeddb/test/BUILD.gn @@ -96,6 +96,7 @@ ohos_source_set("src_file") { "../common/src/runtime_context.cpp", "../common/src/runtime_context_impl.cpp", "../common/src/schema_constant.cpp", + "../common/src/schema_negotiate.cpp", "../common/src/schema_object.cpp", "../common/src/schema_utils.cpp", "../common/src/semaphore_utils.cpp", diff --git a/services/distributeddataservice/libs/distributeddb/test/unittest/common/common/distributeddb_auto_launch_test.cpp b/services/distributeddataservice/libs/distributeddb/test/unittest/common/common/distributeddb_auto_launch_test.cpp old mode 100755 new mode 100644 index 21c729bedda94a3f7b4fa5d803b1f0bfc2c6c2a9..2a355eb7e6e355b59c1810a997c0383c4b5c3d6e --- a/services/distributeddataservice/libs/distributeddb/test/unittest/common/common/distributeddb_auto_launch_test.cpp +++ b/services/distributeddataservice/libs/distributeddb/test/unittest/common/common/distributeddb_auto_launch_test.cpp @@ -564,22 +564,22 @@ HWTEST_F(DistributedDBAutoLaunchUnitTest, AutoLaunch006, TestSize.Level3) std::mutex cvLock; std::condition_variable cv; bool threadIsWorking = true; - thread thread([&cvLock, &cv, &threadIsWorking](){ - LabelType label(g_identifierA.begin(), g_identifierA.end()); - for (int i = 0; i < TEST_ONLINE_CNT; i++) { - g_communicatorAggregator->RunOnConnectCallback(REMOTE_DEVICE_ID, true); - std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_SHORT_TIME)); - g_communicatorAggregator->RunOnConnectCallback(REMOTE_DEVICE_ID, false); - std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_SHORT_TIME)); - g_communicatorAggregator->RunCommunicatorLackCallback(label); - std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_SHORT_TIME)); - LOGD("AutoLaunch006 thread i:%d", i); - } - std::unique_lock lock(cvLock); - threadIsWorking = false; - cv.notify_one(); - }); - thread.detach(); + thread aggregatorThread([&cvLock, &cv, &threadIsWorking]() { + LabelType label(g_identifierA.begin(), g_identifierA.end()); + for (int i = 0; i < TEST_ONLINE_CNT; i++) { + g_communicatorAggregator->RunOnConnectCallback(REMOTE_DEVICE_ID, true); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_SHORT_TIME)); + g_communicatorAggregator->RunOnConnectCallback(REMOTE_DEVICE_ID, false); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_SHORT_TIME)); + g_communicatorAggregator->RunCommunicatorLackCallback(label); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_SHORT_TIME)); + LOGD("AutoLaunch006 thread i:%d", i); + } + std::unique_lock lock(cvLock); + threadIsWorking = false; + cv.notify_one(); + }); + aggregatorThread.detach(); AutoLaunchOption option; option.notifier = nullptr; option.observer = observer; @@ -596,7 +596,7 @@ HWTEST_F(DistributedDBAutoLaunchUnitTest, AutoLaunch006, TestSize.Level3) LOGD("AutoLaunch006 disable i:%d", i); } std::unique_lock lock(cvLock); - cv.wait(lock, [&threadIsWorking]{return threadIsWorking == false;}); + cv.wait(lock, [&threadIsWorking] { return !threadIsWorking; }); delete observer; g_communicatorAggregator->RunOnConnectCallback(REMOTE_DEVICE_ID, false); diff --git a/services/distributeddataservice/libs/distributeddb/test/unittest/common/common/distributeddb_data_generate_unit_test.cpp b/services/distributeddataservice/libs/distributeddb/test/unittest/common/common/distributeddb_data_generate_unit_test.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/test/unittest/common/common/distributeddb_data_generate_unit_test.h b/services/distributeddataservice/libs/distributeddb/test/unittest/common/common/distributeddb_data_generate_unit_test.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/test/unittest/common/common/distributeddb_json_precheck_unit_test.cpp b/services/distributeddataservice/libs/distributeddb/test/unittest/common/common/distributeddb_json_precheck_unit_test.cpp old mode 100755 new mode 100644 index 835a27d50e702acc254e5496d31caad032420718..ffae09ca33fcd98fbb9ef472887a69d6454cbcda --- a/services/distributeddataservice/libs/distributeddb/test/unittest/common/common/distributeddb_json_precheck_unit_test.cpp +++ b/services/distributeddataservice/libs/distributeddb/test/unittest/common/common/distributeddb_json_precheck_unit_test.cpp @@ -101,7 +101,9 @@ HWTEST_F(DistributedDBJsonPrecheckUnitTest, ParseValidString001, TestSize.Level1 * @tc.steps: step1. Check legal json string with nesting depth of 12. * @tc.expected: step1. return value = 12. */ - int stepOne = JsonObject::CalculateNestDepth(JSON_STRING1); + int errCode = E_OK; + int stepOne = JsonObject::CalculateNestDepth(JSON_STRING1, errCode); + EXPECT_TRUE(errCode == E_OK); EXPECT_TRUE(stepOne == STRING1_DEPTH); /** @@ -126,7 +128,9 @@ HWTEST_F(DistributedDBJsonPrecheckUnitTest, ParseValidString002, TestSize.Level1 * @tc.steps: step1. Check legal json string with nesting depth of 6. * @tc.expected: step1. return value = 6. */ - int stepOne = JsonObject::CalculateNestDepth(JSON_STRING3); + int errCode = E_OK; + int stepOne = JsonObject::CalculateNestDepth(JSON_STRING3, errCode); + EXPECT_TRUE(errCode == E_OK); EXPECT_TRUE(stepOne == STRING3_DEPTH); /** @@ -187,7 +191,9 @@ HWTEST_F(DistributedDBJsonPrecheckUnitTest, ParseInvalidString003, TestSize.Leve * @tc.steps: step1. Detect illegal json string with nesting depth greater than 10. * @tc.expected: step1. return value > 10. */ - int stepOne = JsonObject::CalculateNestDepth(JSON_STRING5); + int errCode = E_OK; + int stepOne = JsonObject::CalculateNestDepth(JSON_STRING5, errCode); + EXPECT_TRUE(errCode == E_OK); EXPECT_TRUE(stepOne > MAX_DEPTH_FOR_TEST); /** diff --git a/services/distributeddataservice/libs/distributeddb/test/unittest/common/common/distributeddb_notification_chain_test.cpp b/services/distributeddataservice/libs/distributeddb/test/unittest/common/common/distributeddb_notification_chain_test.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/test/unittest/common/common/distributeddb_parcel_unit_test.cpp b/services/distributeddataservice/libs/distributeddb/test/unittest/common/common/distributeddb_parcel_unit_test.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/test/unittest/common/common/distributeddb_relational_schema_object_test.cpp b/services/distributeddataservice/libs/distributeddb/test/unittest/common/common/distributeddb_relational_schema_object_test.cpp index 6a7ac034ad3c1aeb8038e64b50f21d6e655ed0c1..c26c2943c90ff83687a991a53678a942c4ae6c7b 100644 --- a/services/distributeddataservice/libs/distributeddb/test/unittest/common/common/distributeddb_relational_schema_object_test.cpp +++ b/services/distributeddataservice/libs/distributeddb/test/unittest/common/common/distributeddb_relational_schema_object_test.cpp @@ -23,6 +23,7 @@ #include "relational_schema_object.h" #include "schema_utils.h" #include "schema_constant.h" +#include "schema_negotiate.h" using namespace std; using namespace testing::ext; @@ -312,6 +313,9 @@ HWTEST_F(DistributedDBRelationalSchemaObjectTest, RelationalSchemaParseTest003, TABLE_DEFINE_STR_KEY_INVALID + "}"; errCode = schemaObj.ParseFromSchemaString(GenerateFromTableStr("[" + invalidTableStr05 + "]")); EXPECT_EQ(errCode, -E_SCHEMA_PARSE_FAIL); + + errCode = schemaObj.ParseFromSchemaString(""); + EXPECT_EQ(errCode, -E_INVALID_ARGS); } /** @@ -327,11 +331,11 @@ HWTEST_F(DistributedDBRelationalSchemaObjectTest, RelationalSchemaCompareTest001 int errCode = schemaObj.ParseFromSchemaString(NORMAL_SCHEMA); EXPECT_EQ(errCode, E_OK); - RelationalSyncOpinion opinion = RelationalSchemaObject::MakeLocalSyncOpinion(schemaObj, NORMAL_SCHEMA, + RelationalSyncOpinion opinion = SchemaNegotiate::MakeLocalSyncOpinion(schemaObj, NORMAL_SCHEMA, static_cast(SchemaType::RELATIVE)); - EXPECT_EQ(opinion.GetTableOpinion("FIRST").permitSync, true); - EXPECT_EQ(opinion.GetTableOpinion("FIRST").checkOnReceive, false); - EXPECT_EQ(opinion.GetTableOpinion("FIRST").requirePeerConvert, false); + EXPECT_EQ(opinion.at("FIRST").permitSync, true); + EXPECT_EQ(opinion.at("FIRST").checkOnReceive, false); + EXPECT_EQ(opinion.at("FIRST").requirePeerConvert, false); } /** @@ -374,26 +378,25 @@ HWTEST_F(DistributedDBRelationalSchemaObjectTest, RelationalTableCompareTest001, */ HWTEST_F(DistributedDBRelationalSchemaObjectTest, RelationalSchemaOpinionTest001, TestSize.Level1) { - const uint32_t softWareVersion = 106; RelationalSyncOpinion opinion; - opinion.AddSyncOpinion("table_1", SyncOpinion {true, false, false}); - opinion.AddSyncOpinion("table_2", SyncOpinion {false, true, false}); - opinion.AddSyncOpinion("table_3", SyncOpinion {false, false, true}); + opinion["table_1"] = SyncOpinion {true, false, false}; + opinion["table_2"] = SyncOpinion {false, true, false}; + opinion["table_3"] = SyncOpinion {false, false, true}; - uint32_t len = opinion.CalculateParcelLen(softWareVersion); + uint32_t len = SchemaNegotiate::CalculateParcelLen(opinion); std::vector buff(len, 0); Parcel writeParcel(buff.data(), len); - int errCode = opinion.SerializeData(writeParcel, softWareVersion); + int errCode = SchemaNegotiate::SerializeData(opinion, writeParcel); EXPECT_EQ(errCode, E_OK); Parcel readParcel(buff.data(), len); RelationalSyncOpinion opinionRecv; - errCode = RelationalSyncOpinion::DeserializeData(readParcel, opinionRecv); + errCode = SchemaNegotiate::DeserializeData(readParcel, opinionRecv); EXPECT_EQ(errCode, E_OK); - EXPECT_EQ(opinion.GetOpinions().size(), opinionRecv.GetOpinions().size()); - for (const auto &it : opinion.GetOpinions()) { - SyncOpinion tableOpinionRecv = opinionRecv.GetTableOpinion(it.first); + EXPECT_EQ(opinion.size(), opinionRecv.size()); + for (const auto &it : opinion) { + SyncOpinion tableOpinionRecv = opinionRecv.at(it.first); EXPECT_EQ(it.second.permitSync, tableOpinionRecv.permitSync); EXPECT_EQ(it.second.requirePeerConvert, tableOpinionRecv.requirePeerConvert); } @@ -409,19 +412,19 @@ HWTEST_F(DistributedDBRelationalSchemaObjectTest, RelationalSchemaOpinionTest001 HWTEST_F(DistributedDBRelationalSchemaObjectTest, RelationalSchemaNegotiateTest001, TestSize.Level1) { RelationalSyncOpinion localOpinion; - localOpinion.AddSyncOpinion("table_1", SyncOpinion {true, false, false}); - localOpinion.AddSyncOpinion("table_2", SyncOpinion {false, true, false}); - localOpinion.AddSyncOpinion("table_3", SyncOpinion {false, false, true}); + localOpinion["table_1"] = SyncOpinion {true, false, false}; + localOpinion["table_2"] = SyncOpinion {false, true, false}; + localOpinion["table_3"] = SyncOpinion {false, false, true}; RelationalSyncOpinion remoteOpinion; - remoteOpinion.AddSyncOpinion("table_2", SyncOpinion {true, false, false}); - remoteOpinion.AddSyncOpinion("table_3", SyncOpinion {false, true, false}); - remoteOpinion.AddSyncOpinion("table_4", SyncOpinion {false, false, true}); - RelationalSyncStrategy strategy = RelationalSchemaObject::ConcludeSyncStrategy(localOpinion, remoteOpinion); - - EXPECT_EQ(strategy.GetStrategies().size(), 2); - EXPECT_EQ(strategy.GetTableStrategy("table_2").permitSync, true); - EXPECT_EQ(strategy.GetTableStrategy("table_3").permitSync, false); + remoteOpinion["table_2"] = SyncOpinion {true, false, false}; + remoteOpinion["table_3"] = SyncOpinion {false, true, false}; + remoteOpinion["table_4"] = SyncOpinion {false, false, true}; + RelationalSyncStrategy strategy = SchemaNegotiate::ConcludeSyncStrategy(localOpinion, remoteOpinion); + + EXPECT_EQ(strategy.size(), 2u); + EXPECT_EQ(strategy.at("table_2").permitSync, true); + EXPECT_EQ(strategy.at("table_3").permitSync, false); } /** diff --git a/services/distributeddataservice/libs/distributeddb/test/unittest/common/common/distributeddb_schema_object_test.cpp b/services/distributeddataservice/libs/distributeddb/test/unittest/common/common/distributeddb_schema_object_test.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/test/unittest/common/common/distributeddb_schema_unit_test.cpp b/services/distributeddataservice/libs/distributeddb/test/unittest/common/common/distributeddb_schema_unit_test.cpp old mode 100755 new mode 100644 index 3284cb84392a6f178ac9e1988cd17e0a13f335cf..8f6a58261172e60d48abd2c5cf24efba22edff52 --- a/services/distributeddataservice/libs/distributeddb/test/unittest/common/common/distributeddb_schema_unit_test.cpp +++ b/services/distributeddataservice/libs/distributeddb/test/unittest/common/common/distributeddb_schema_unit_test.cpp @@ -132,14 +132,14 @@ void PreDoubleDataForParseAndCheckSchemaAttribute003() SchemaAttribute attributeRes9; attributeRes9.type = FieldType::LEAF_FIELD_DOUBLE; attributeRes9.hasDefaultValue = true; - attributeRes9.defaultValue.doubleValue = 0.1; // test data + attributeRes9.defaultValue.doubleValue = 0.1; // 0.1 as test data g_schemaAttrDefTestDataDir["DOUBLE,DEFAULT 0.1"] = attributeRes9; SchemaAttribute attributeRes10; attributeRes10.type = FieldType::LEAF_FIELD_DOUBLE; attributeRes10.hasNotNullConstraint = true; attributeRes10.hasDefaultValue = true; - attributeRes10.defaultValue.doubleValue = -0.123456; // test data + attributeRes10.defaultValue.doubleValue = -0.123456; // -0.123456 as test data g_schemaAttrDefTestDataDir["DOUBLE, NOT NULL,DEFAULT -0.123456"] = attributeRes10; SchemaAttribute attributeRes11; @@ -410,7 +410,6 @@ HWTEST_F(DistributedDBSchemalTest, CheckFieldName002, TestSize.Level1) for (auto &iter : preData) { EXPECT_EQ(SchemaUtils::CheckFieldName(iter), -E_SCHEMA_PARSE_FAIL); } - } /** diff --git a/services/distributeddataservice/libs/distributeddb/test/unittest/common/common/distributeddb_tools_unit_test.cpp b/services/distributeddataservice/libs/distributeddb/test/unittest/common/common/distributeddb_tools_unit_test.cpp old mode 100755 new mode 100644 index 68a2711d14b06584c495f683929b0e20632ef685..cb4d16398bf14aff6ad861a9e844a067e9bfa119 --- a/services/distributeddataservice/libs/distributeddb/test/unittest/common/common/distributeddb_tools_unit_test.cpp +++ b/services/distributeddataservice/libs/distributeddb/test/unittest/common/common/distributeddb_tools_unit_test.cpp @@ -760,12 +760,12 @@ DBStatus DistributedDBToolsUnitTest::SyncTest(KvStoreNbDelegate* delegate, }, query, false); std::unique_lock lock(syncLock_); - syncCondVar_.wait(lock, [callStatus, &statuses](){ - if (callStatus != OK) { - return true; - } - return !statuses.empty(); - }); + syncCondVar_.wait(lock, [callStatus, &statuses]() { + if (callStatus != OK) { + return true; + } + return !statuses.empty(); + }); return callStatus; } @@ -782,16 +782,16 @@ DBStatus DistributedDBToolsUnitTest::SyncTest(KvStoreNbDelegate* delegate, }, wait); if (!wait) { std::unique_lock lock(syncLock_); - syncCondVar_.wait(lock, [callStatus, &statuses](){ - if (callStatus != OK) { - return true; - } - if (statuses.size() != 0) { - return true; - } - return false; - }); - } + syncCondVar_.wait(lock, [callStatus, &statuses]() { + if (callStatus != OK) { + return true; + } + if (statuses.size() != 0) { + return true; + } + return false; + }); + } return callStatus; } diff --git a/services/distributeddataservice/libs/distributeddb/test/unittest/common/common/distributeddb_tools_unit_test.h b/services/distributeddataservice/libs/distributeddb/test/unittest/common/common/distributeddb_tools_unit_test.h old mode 100755 new mode 100644 index d87bdcc5b7b0939a727cb90f2fe3214cb391181d..02686a85ece08346c375c12aee5964200e0b1d27 --- a/services/distributeddataservice/libs/distributeddb/test/unittest/common/common/distributeddb_tools_unit_test.h +++ b/services/distributeddataservice/libs/distributeddb/test/unittest/common/common/distributeddb_tools_unit_test.h @@ -45,8 +45,6 @@ #include "sync_types.h" #include "store_types.h" namespace DistributedDBUnitTest { -static const int DIR_PERMISSION = 0750; - struct DatabaseInfo { std::string appId{}; std::string userId{}; diff --git a/services/distributeddataservice/libs/distributeddb/test/unittest/common/common/evloop_timer_unit_test.cpp b/services/distributeddataservice/libs/distributeddb/test/unittest/common/common/evloop_timer_unit_test.cpp old mode 100755 new mode 100644 index 038ddbb9564b757d6dd2b96fdcf95a576ca4dbbf..b9e48b9d5155b775086ae251c1f5dc535dbaf0a5 --- a/services/distributeddataservice/libs/distributeddb/test/unittest/common/common/evloop_timer_unit_test.cpp +++ b/services/distributeddataservice/libs/distributeddb/test/unittest/common/common/evloop_timer_unit_test.cpp @@ -53,7 +53,7 @@ EventTime TimerTester::GetCurrentTime() LOGE("Get current time failed."); return 0; } - return now / 1000; // microsecond to millisecond. + return now / 1000; // 1 ms equals to 1000 us } class DistributedDBEventLoopTimerTest : public testing::Test { @@ -116,7 +116,7 @@ HWTEST_F(DistributedDBEventLoopTimerTest, EventLoopTimerTest001, TestSize.Level0 * @tc.expected: step2. destroy successfully. */ bool finalized = false; - loop->OnLastRef([&finalized](){ finalized = true; }); + loop->OnLastRef([&finalized]() { finalized = true; }); loop->DecObjRef(loop); loop = nullptr; EXPECT_EQ(finalized, true); @@ -140,7 +140,7 @@ HWTEST_F(DistributedDBEventLoopTimerTest, EventLoopTimerTest002, TestSize.Level1 */ std::atomic running(false); EventTime delta = 0; - std::thread loopThread([&running, &delta](){ + std::thread loopThread([&running, &delta]() { running = true; EventTime start = TimerTester::GetCurrentTime(); g_loop->Run(); @@ -180,7 +180,7 @@ HWTEST_F(DistributedDBEventLoopTimerTest, EventLoopTimerTest003, TestSize.Level0 bool finalized = false; errCode = timer->SetAction([](EventsMask revents) -> int { return E_OK; - }, [&finalized](){ + }, [&finalized]() { finalized = true; }); EXPECT_EQ(errCode, E_OK); @@ -206,7 +206,7 @@ HWTEST_F(DistributedDBEventLoopTimerTest, EventLoopTimerTest004, TestSize.Level1 * @tc.expected: step1. start successfully. */ std::atomic running(false); - std::thread loopThread([&running](){ + std::thread loopThread([&running]() { running = true; g_loop->Run(); }); @@ -258,7 +258,7 @@ HWTEST_F(DistributedDBEventLoopTimerTest, EventLoopTimerTest005, TestSize.Level1 * @tc.expected: step1. start successfully. */ std::atomic running(false); - std::thread loopThread([&running](){ + std::thread loopThread([&running]() { running = true; g_loop->Run(); }); @@ -282,7 +282,7 @@ HWTEST_F(DistributedDBEventLoopTimerTest, EventLoopTimerTest005, TestSize.Level1 [&counter](EventsMask revents) -> int { ++counter; return E_OK; - }, [&finalize](){ finalize = true; }); + }, [&finalize]() { finalize = true; }); EXPECT_EQ(errCode, E_OK); errCode = g_loop->Add(timer); EXPECT_EQ(errCode, E_OK); @@ -317,7 +317,7 @@ HWTEST_F(DistributedDBEventLoopTimerTest, EventLoopTimerTest006, TestSize.Level1 * @tc.expected: step1. start successfully. */ std::atomic running(false); - std::thread loopThread([&running](){ + std::thread loopThread([&running]() { running = true; g_loop->Run(); }); @@ -338,7 +338,7 @@ HWTEST_F(DistributedDBEventLoopTimerTest, EventLoopTimerTest006, TestSize.Level1 std::atomic counter(0); std::atomic finalize(false); errCode = timer->SetAction([&counter](EventsMask revents) -> int { ++counter; return -E_STALE; }, - [&finalize](){ finalize = true; }); + [&finalize]() { finalize = true; }); EXPECT_EQ(errCode, E_OK); errCode = g_loop->Add(timer); EXPECT_EQ(errCode, E_OK); @@ -373,7 +373,7 @@ HWTEST_F(DistributedDBEventLoopTimerTest, EventLoopTimerTest007, TestSize.Level2 * @tc.expected: step1. start successfully. */ std::atomic running(false); - std::thread loopThread([&running](){ + std::thread loopThread([&running]() { running = true; g_loop->Run(); }); diff --git a/services/distributeddataservice/libs/distributeddb/test/unittest/common/communicator/adapter_stub.cpp b/services/distributeddataservice/libs/distributeddb/test/unittest/common/communicator/adapter_stub.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/test/unittest/common/communicator/adapter_stub.h b/services/distributeddataservice/libs/distributeddb/test/unittest/common/communicator/adapter_stub.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/test/unittest/common/communicator/distributeddb_communicator_common.cpp b/services/distributeddataservice/libs/distributeddb/test/unittest/common/communicator/distributeddb_communicator_common.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/test/unittest/common/communicator/distributeddb_communicator_common.h b/services/distributeddataservice/libs/distributeddb/test/unittest/common/communicator/distributeddb_communicator_common.h index da8823946957063de7936830d5443e96510947d6..35e5b048c0a22f9b6f3a81d661dedbfe75cbb5c1 100644 --- a/services/distributeddataservice/libs/distributeddb/test/unittest/common/communicator/distributeddb_communicator_common.h +++ b/services/distributeddataservice/libs/distributeddb/test/unittest/common/communicator/distributeddb_communicator_common.h @@ -141,7 +141,7 @@ DistributedDB::Message *BuildUnRegedTinyMessage(); #define ASSERT_NOT_NULL_AND_ACTIVATE(communicator) \ { \ ASSERT_NE(communicator, nullptr); \ - communicator->Activate(); \ + (communicator)->Activate(); \ } #endif // DISTRIBUTEDDB_COMMUNICATOR_COMMON_H \ No newline at end of file diff --git a/services/distributeddataservice/libs/distributeddb/test/unittest/common/communicator/distributeddb_communicator_deep_test.cpp b/services/distributeddataservice/libs/distributeddb/test/unittest/common/communicator/distributeddb_communicator_deep_test.cpp old mode 100755 new mode 100644 index c7447567c172c7b9a072715d351fddb27949a30d..5bf3155565c5cc42d5278a3fdb2ef3ac7bb19ca6 --- a/services/distributeddataservice/libs/distributeddb/test/unittest/common/communicator/distributeddb_communicator_deep_test.cpp +++ b/services/distributeddataservice/libs/distributeddb/test/unittest/common/communicator/distributeddb_communicator_deep_test.cpp @@ -140,7 +140,7 @@ HWTEST_F(DistributedDBCommunicatorDeepTest, WaitAndRetrySend001, TestSize.Level2 { // Preset Message *msgForBB = nullptr; - g_commBB->RegOnMessageCallback([&msgForBB](const std::string &srcTarget, Message *inMsg){ + g_commBB->RegOnMessageCallback([&msgForBB](const std::string &srcTarget, Message *inMsg) { msgForBB = inMsg; }, nullptr); @@ -161,7 +161,7 @@ HWTEST_F(DistributedDBCommunicatorDeepTest, WaitAndRetrySend001, TestSize.Level2 */ Message *msgForAB = BuildRegedTinyMessage(); ASSERT_NE(msgForAB, nullptr); - SendConfig conf = {true, 0}; + SendConfig conf = {true, false, 0}; int errCode = g_commAB->SendMessage(DEVICE_NAME_B, msgForAB, conf); EXPECT_EQ(errCode, E_OK); std::this_thread::sleep_for(std::chrono::milliseconds(100)); // Wait 100 ms @@ -312,7 +312,7 @@ HWTEST_F(DistributedDBCommunicatorDeepTest, Fragment001, TestSize.Level2) { // Preset Message *recvMsgForBB = nullptr; - g_commBB->RegOnMessageCallback([&recvMsgForBB](const std::string &srcTarget, Message *inMsg){ + g_commBB->RegOnMessageCallback([&recvMsgForBB](const std::string &srcTarget, Message *inMsg) { recvMsgForBB = inMsg; }, nullptr); @@ -328,7 +328,7 @@ HWTEST_F(DistributedDBCommunicatorDeepTest, Fragment001, TestSize.Level2) const uint32_t dataLength = 13 * 1024 * 1024; // 13 MB, 1024 is scale Message *sendMsgForAB = BuildRegedGiantMessage(dataLength); ASSERT_NE(sendMsgForAB, nullptr); - SendConfig conf = {false, 0}; + SendConfig conf = {false, false, 0}; int errCode = g_commAB->SendMessage(DEVICE_NAME_B, sendMsgForAB, conf); EXPECT_EQ(errCode, E_OK); std::this_thread::sleep_for(std::chrono::milliseconds(2600)); // Wait 2600 ms to make sure send done @@ -367,7 +367,7 @@ HWTEST_F(DistributedDBCommunicatorDeepTest, Fragment002, TestSize.Level2) { // Preset Message *recvMsgForCC = nullptr; - g_commCC->RegOnMessageCallback([&recvMsgForCC](const std::string &srcTarget, Message *inMsg){ + g_commCC->RegOnMessageCallback([&recvMsgForCC](const std::string &srcTarget, Message *inMsg) { recvMsgForCC = inMsg; }, nullptr); @@ -389,7 +389,7 @@ HWTEST_F(DistributedDBCommunicatorDeepTest, Fragment002, TestSize.Level2) uint32_t dataLength = 13 * 1024 * 1024; // 13 MB, 1024 is scale Message *sendMsgForBC = BuildRegedGiantMessage(dataLength); ASSERT_NE(sendMsgForBC, nullptr); - SendConfig conf = {false, 0}; + SendConfig conf = {false, false, 0}; int errCode = g_commBC->SendMessage(DEVICE_NAME_C, sendMsgForBC, conf); EXPECT_EQ(errCode, E_OK); std::this_thread::sleep_for(std::chrono::milliseconds(2600)); // Wait 2600 ms to make sure send done @@ -432,7 +432,7 @@ HWTEST_F(DistributedDBCommunicatorDeepTest, Fragment002, TestSize.Level2) HWTEST_F(DistributedDBCommunicatorDeepTest, Fragment003, TestSize.Level3) { // Preset - std::atomic count{0}; + std::atomic count {0}; OnMessageCallback callback = [&count](const std::string &srcTarget, Message *inMsg) { delete inMsg; inMsg = nullptr; @@ -460,7 +460,7 @@ HWTEST_F(DistributedDBCommunicatorDeepTest, Fragment003, TestSize.Level3) uint32_t dataLength = 23 * 1024 * 1024; // 23 MB, 1024 is scale Message *sendMsgForAB = BuildRegedGiantMessage(dataLength); ASSERT_NE(sendMsgForAB, nullptr); - SendConfig conf = {false, 0}; + SendConfig conf = {false, false, 0}; int errCode = g_commAB->SendMessage(DEVICE_NAME_B, sendMsgForAB, conf); EXPECT_EQ(errCode, E_OK); @@ -512,7 +512,7 @@ HWTEST_F(DistributedDBCommunicatorDeepTest, ReliableOnline001, TestSize.Level2) { // Preset ClearPreviousTestCaseInfluence(); - std::atomic count{0}; + std::atomic count {0}; OnConnectCallback callback = [&count](const std::string &target, bool isConnect) { if (isConnect) { count.fetch_add(1, std::memory_order_seq_cst); diff --git a/services/distributeddataservice/libs/distributeddb/test/unittest/common/communicator/distributeddb_communicator_send_receive_test.cpp b/services/distributeddataservice/libs/distributeddb/test/unittest/common/communicator/distributeddb_communicator_send_receive_test.cpp old mode 100755 new mode 100644 index 204e08876f77e4661c782543a7a89317141b8078..ea0d11a237dac22b7561606c59a140ab770e6631 --- a/services/distributeddataservice/libs/distributeddb/test/unittest/common/communicator/distributeddb_communicator_send_receive_test.cpp +++ b/services/distributeddataservice/libs/distributeddb/test/unittest/common/communicator/distributeddb_communicator_send_receive_test.cpp @@ -134,15 +134,15 @@ HWTEST_F(DistributedDBCommunicatorSendReceiveTest, SendAndReceive001, TestSize.L Message *recvMsgForBA = nullptr; string srcTargetForBB; Message *recvMsgForBB = nullptr; - g_commAA->RegOnMessageCallback([&srcTargetForAA, &recvMsgForAA](const std::string &srcTarget, Message *inMsg){ + g_commAA->RegOnMessageCallback([&srcTargetForAA, &recvMsgForAA](const std::string &srcTarget, Message *inMsg) { srcTargetForAA = srcTarget; recvMsgForAA = inMsg; }, nullptr); - g_commBA->RegOnMessageCallback([&srcTargetForBA, &recvMsgForBA](const std::string &srcTarget, Message *inMsg){ + g_commBA->RegOnMessageCallback([&srcTargetForBA, &recvMsgForBA](const std::string &srcTarget, Message *inMsg) { srcTargetForBA = srcTarget; recvMsgForBA = inMsg; }, nullptr); - g_commBB->RegOnMessageCallback([&srcTargetForBB, &recvMsgForBB](const std::string &srcTarget, Message *inMsg){ + g_commBB->RegOnMessageCallback([&srcTargetForBB, &recvMsgForBB](const std::string &srcTarget, Message *inMsg) { srcTargetForBB = srcTarget; recvMsgForBB = inMsg; }, nullptr); @@ -158,7 +158,7 @@ HWTEST_F(DistributedDBCommunicatorSendReceiveTest, SendAndReceive001, TestSize.L */ Message *msgForAA = BuildRegedTinyMessage(); ASSERT_NE(msgForAA, nullptr); - SendConfig conf = {false, 0}; + SendConfig conf = {false, false, 0}; int errCode = g_commAA->SendMessage(DEVICE_NAME_B, msgForAA, conf); EXPECT_EQ(errCode, E_OK); std::this_thread::sleep_for(std::chrono::milliseconds(200)); // sleep 200 ms @@ -209,7 +209,7 @@ HWTEST_F(DistributedDBCommunicatorSendReceiveTest, SendAndReceive002, TestSize.L */ Message *msgForAA = BuildRegedOverSizeMessage(); ASSERT_NE(msgForAA, nullptr); - SendConfig conf = {true, 0}; + SendConfig conf = {true, false, 0}; int errCode = g_commAA->SendMessage(DEVICE_NAME_B, msgForAA, conf); EXPECT_NE(errCode, E_OK); delete msgForAA; @@ -239,7 +239,7 @@ HWTEST_F(DistributedDBCommunicatorSendReceiveTest, SendAndReceive003, TestSize.L */ Message *msgForAA = BuildUnRegedTinyMessage(); ASSERT_NE(msgForAA, nullptr); - SendConfig conf = {true, 0}; + SendConfig conf = {true, false, 0}; int errCode = g_commAA->SendMessage(DEVICE_NAME_B, msgForAA, conf); EXPECT_NE(errCode, E_OK); delete msgForAA; @@ -261,8 +261,8 @@ HWTEST_F(DistributedDBCommunicatorSendReceiveTest, SendFlowControl001, TestSize. // Preset int countForBA = 0; int countForBB = 0; - g_commBA->RegOnSendableCallback([&countForBA](){countForBA++;}, nullptr); - g_commBB->RegOnSendableCallback([&countForBB](){countForBB++;}, nullptr); + g_commBA->RegOnSendableCallback([&countForBA](){ countForBA++; }, nullptr); + g_commBB->RegOnSendableCallback([&countForBB](){ countForBB++; }, nullptr); /** * @tc.steps: step1. connect device A with device B @@ -286,7 +286,7 @@ HWTEST_F(DistributedDBCommunicatorSendReceiveTest, SendFlowControl001, TestSize. while (true) { Message *msgForBA = BuildRegedHugeMessage(); ASSERT_NE(msgForBA, nullptr); - SendConfig conf = {true, 0}; + SendConfig conf = {true, false, 0}; int errCode = g_commBA->SendMessage(DEVICE_NAME_A, msgForBA, conf); if (errCode == E_OK) { sendCount++; @@ -325,8 +325,8 @@ HWTEST_F(DistributedDBCommunicatorSendReceiveTest, SendFlowControl002, TestSize. // Preset int cntForBA = 0; int cntForBB = 0; - g_commBA->RegOnSendableCallback([&cntForBA](){cntForBA++;}, nullptr); - g_commBB->RegOnSendableCallback([&cntForBB](){cntForBB++;}, nullptr); + g_commBA->RegOnSendableCallback([&cntForBA](){ cntForBA++; }, nullptr); + g_commBB->RegOnSendableCallback([&cntForBB](){ cntForBB++; }, nullptr); /** * @tc.steps: step1. connect device A with device B @@ -347,11 +347,11 @@ HWTEST_F(DistributedDBCommunicatorSendReceiveTest, SendFlowControl002, TestSize. */ int sendCount = 0; int sendFailCount = 0; - std::thread sendThread([&sendCount, &sendFailCount](){ + std::thread sendThread([&sendCount, &sendFailCount]() { while (sendCount < SEND_COUNT_GOAL) { Message *msgForBA = BuildRegedHugeMessage(); ASSERT_NE(msgForBA, nullptr); - SendConfig conf = {false, 0}; + SendConfig conf = {false, false, 0}; int errCode = g_commBA->SendMessage(DEVICE_NAME_A, msgForBA, conf); if (errCode != E_OK) { delete msgForBA; @@ -391,8 +391,8 @@ HWTEST_F(DistributedDBCommunicatorSendReceiveTest, SendFlowControl003, TestSize. // Preset int cntsForBA = 0; int cntsForBB = 0; - g_commBA->RegOnSendableCallback([&cntsForBA](){cntsForBA++;}, nullptr); - g_commBB->RegOnSendableCallback([&cntsForBB](){cntsForBB++;}, nullptr); + g_commBA->RegOnSendableCallback([&cntsForBA](){ cntsForBA++; }, nullptr); + g_commBB->RegOnSendableCallback([&cntsForBB](){ cntsForBB++; }, nullptr); /** * @tc.steps: step1. connect device A with device B @@ -413,11 +413,11 @@ HWTEST_F(DistributedDBCommunicatorSendReceiveTest, SendFlowControl003, TestSize. */ int sendCnt = 0; int sendFailCnt = 0; - std::thread sendThread([&sendCnt, &sendFailCnt](){ + std::thread sendThread([&sendCnt, &sendFailCnt]() { while (sendCnt < SEND_COUNT_GOAL) { Message *msgForBA = BuildRegedHugeMessage(); ASSERT_NE(msgForBA, nullptr); - SendConfig conf = {false, 100}; + SendConfig conf = {false, false, 100}; int errCode = g_commBA->SendMessage(DEVICE_NAME_A, msgForBA, conf); // 100 ms timeout if (errCode != E_OK) { delete msgForBA; @@ -456,7 +456,7 @@ HWTEST_F(DistributedDBCommunicatorSendReceiveTest, ReceiveCheck001, TestSize.Lev { // Preset int recvCount = 0; - g_commAA->RegOnMessageCallback([&recvCount](const std::string &srcTarget, Message *inMsg){ + g_commAA->RegOnMessageCallback([&recvCount](const std::string &srcTarget, Message *inMsg) { recvCount++; if (inMsg != nullptr) { delete inMsg; @@ -471,7 +471,7 @@ HWTEST_F(DistributedDBCommunicatorSendReceiveTest, ReceiveCheck001, TestSize.Lev */ g_envDeviceB.adapterHandle->SimulateSendBitErrorInMagicField(true, 0xFFFF); Message *msgForBA = BuildRegedTinyMessage(); - SendConfig conf = {true, 0}; + SendConfig conf = {true, false, 0}; int errCode = g_commBA->SendMessage(DEVICE_NAME_A, msgForBA, conf); EXPECT_EQ(errCode, E_OK); std::this_thread::sleep_for(std::chrono::milliseconds(100)); @@ -517,7 +517,7 @@ HWTEST_F(DistributedDBCommunicatorSendReceiveTest, ReceiveCheck002, TestSize.Lev { // Preset int recvCount = 0; - g_commAA->RegOnMessageCallback([&recvCount](const std::string &srcTarget, Message *inMsg){ + g_commAA->RegOnMessageCallback([&recvCount](const std::string &srcTarget, Message *inMsg) { recvCount++; if (inMsg != nullptr) { delete inMsg; @@ -532,7 +532,7 @@ HWTEST_F(DistributedDBCommunicatorSendReceiveTest, ReceiveCheck002, TestSize.Lev */ g_envDeviceB.adapterHandle->SimulateSendBitErrorInPacketLenField(true, 0xFFFF); Message *msgForBA = BuildRegedTinyMessage(); - SendConfig conf = {true, 0}; + SendConfig conf = {true, false, 0}; int errCode = g_commBA->SendMessage(DEVICE_NAME_A, msgForBA, conf); EXPECT_EQ(errCode, E_OK); std::this_thread::sleep_for(std::chrono::milliseconds(100)); @@ -593,7 +593,7 @@ HWTEST_F(DistributedDBCommunicatorSendReceiveTest, SendResultNotify001, TestSize */ Message *msgForAA = BuildRegedTinyMessage(); ASSERT_NE(msgForAA, nullptr); - SendConfig conf = {false, 0}; + SendConfig conf = {false, false, 0}; int errCode = g_commAA->SendMessage(DEVICE_NAME_B, msgForAA, conf, sendResultNotifier); EXPECT_EQ(errCode, E_OK); std::this_thread::sleep_for(std::chrono::milliseconds(100)); // Sleep 100 ms @@ -653,7 +653,7 @@ HWTEST_F(DistributedDBCommunicatorSendReceiveTest, MessageFeedback001, TestSize. */ Message *msgForBB = BuildRegedTinyMessage(); ASSERT_NE(msgForBB, nullptr); - SendConfig conf = {false, 0}; + SendConfig conf = {false, false, 0}; int errCode = g_commBB->SendMessage(DEVICE_NAME_A, msgForBB, conf); EXPECT_EQ(errCode, E_OK); std::this_thread::sleep_for(std::chrono::milliseconds(100)); // Sleep 100 ms @@ -714,11 +714,11 @@ HWTEST_F(DistributedDBCommunicatorSendReceiveTest, SendAndReceiveWithExtendHead0 string srcTargetForBA; Message *recvMsgForBA = nullptr; TimeSync::RegisterTransformFunc(); - g_commAA->RegOnMessageCallback([&srcTargetForAA, &recvMsgForAA](const std::string &srcTarget, Message *inMsg){ + g_commAA->RegOnMessageCallback([&srcTargetForAA, &recvMsgForAA](const std::string &srcTarget, Message *inMsg) { srcTargetForAA = srcTarget; recvMsgForAA = inMsg; }, nullptr); - g_commBA->RegOnMessageCallback([&srcTargetForBA, &recvMsgForBA](const std::string &srcTarget, Message *inMsg){ + g_commBA->RegOnMessageCallback([&srcTargetForBA, &recvMsgForBA](const std::string &srcTarget, Message *inMsg) { srcTargetForBA = srcTarget; recvMsgForBA = inMsg; }, nullptr); @@ -734,7 +734,7 @@ HWTEST_F(DistributedDBCommunicatorSendReceiveTest, SendAndReceiveWithExtendHead0 */ Message *msgForAA = BuildAppLayerFrameMessage(); ASSERT_NE(msgForAA, nullptr); - SendConfig conf = {false, 0, {"appId", "storeId", "userId", "deviceB"}, true}; + SendConfig conf = {false, true, 0, {"appId", "storeId", "userId", "deviceB"}}; int errCode = g_commAA->SendMessage(DEVICE_NAME_B, msgForAA, conf); EXPECT_EQ(errCode, E_OK); std::this_thread::sleep_for(std::chrono::milliseconds(200)); // sleep 200 ms diff --git a/services/distributeddataservice/libs/distributeddb/test/unittest/common/communicator/distributeddb_communicator_test.cpp b/services/distributeddataservice/libs/distributeddb/test/unittest/common/communicator/distributeddb_communicator_test.cpp old mode 100755 new mode 100644 index 8407d33843047e2727445c8639086bad81e64bbc..ab7e1b0163b0d2aad04c800b4c5331c0023af985 --- a/services/distributeddataservice/libs/distributeddb/test/unittest/common/communicator/distributeddb_communicator_test.cpp +++ b/services/distributeddataservice/libs/distributeddb/test/unittest/common/communicator/distributeddb_communicator_test.cpp @@ -175,7 +175,7 @@ HWTEST_F(DistributedDBCommunicatorTest, OnlineAndOffline001, TestSize.Level1) ICommunicator *commAA = g_envDeviceA.commAggrHandle->AllocCommunicator(LABEL_A, errorNo); ASSERT_NOT_NULL_AND_ACTIVATE(commAA); OnOfflineDevice onlineForAA; - commAA->RegOnConnectCallback([&onlineForAA](const std::string &target, bool isConnect){ + commAA->RegOnConnectCallback([&onlineForAA](const std::string &target, bool isConnect) { HandleConnectChange(onlineForAA, target, isConnect);}, nullptr); EXPECT_EQ(onlineForAA.onlineDevices.size(), static_cast(0)); @@ -193,7 +193,7 @@ HWTEST_F(DistributedDBCommunicatorTest, OnlineAndOffline001, TestSize.Level1) ICommunicator *commBB = g_envDeviceB.commAggrHandle->AllocCommunicator(LABEL_B, errorNo); ASSERT_NOT_NULL_AND_ACTIVATE(commBB); OnOfflineDevice onlineForBB; - commBB->RegOnConnectCallback([&onlineForBB](const std::string &target, bool isConnect){ + commBB->RegOnConnectCallback([&onlineForBB](const std::string &target, bool isConnect) { HandleConnectChange(onlineForBB, target, isConnect);}, nullptr); EXPECT_EQ(onlineForAA.onlineDevices.size(), static_cast(0)); EXPECT_EQ(onlineForBB.onlineDevices.size(), static_cast(0)); @@ -213,7 +213,7 @@ HWTEST_F(DistributedDBCommunicatorTest, OnlineAndOffline001, TestSize.Level1) ICommunicator *commBA = g_envDeviceB.commAggrHandle->AllocCommunicator(LABEL_A, errorNo); ASSERT_NOT_NULL_AND_ACTIVATE(commBA); OnOfflineDevice onlineForBA; - commBA->RegOnConnectCallback([&onlineForBA](const std::string &target, bool isConnect){ + commBA->RegOnConnectCallback([&onlineForBA](const std::string &target, bool isConnect) { HandleConnectChange(onlineForBA, target, isConnect);}, nullptr); EXPECT_EQ(onlineForAA.onlineDevices.size(), static_cast(0)); EXPECT_EQ(onlineForBB.onlineDevices.size(), static_cast(0)); @@ -467,7 +467,7 @@ HWTEST_F(DistributedDBCommunicatorTest, ReportCommunicatorNotFound001, TestSize. ASSERT_NOT_NULL_AND_ACTIVATE(commAA); Message *msgForAA = BuildRegedTinyMessage(); ASSERT_NE(msgForAA, nullptr); - SendConfig conf = {true, 0}; + SendConfig conf = {true, false, 0}; errCode = commAA->SendMessage(DEVICE_NAME_B, msgForAA, conf); EXPECT_EQ(errCode, E_OK); std::this_thread::sleep_for(std::chrono::milliseconds(100)); // Sleep 100 ms @@ -500,7 +500,7 @@ HWTEST_F(DistributedDBCommunicatorTest, ReportCommunicatorNotFound001, TestSize. Message *msgFor##src##label = BuildRegedTinyMessage(); \ ASSERT_NE(msgFor##src##label, nullptr); \ msgFor##src##label->SetSessionId(session); \ - SendConfig conf = {true, 0}; \ + SendConfig conf = {true, false, 0}; \ errCode = comm##src##label->SendMessage(DEVICE_NAME_##dst, msgFor##src##label, conf); \ EXPECT_EQ(errCode, E_OK); \ } @@ -509,7 +509,7 @@ HWTEST_F(DistributedDBCommunicatorTest, ReportCommunicatorNotFound001, TestSize. { \ Message *msgFor##src##label = BuildRegedGiantMessage(size); \ ASSERT_NE(msgFor##src##label, nullptr); \ - SendConfig conf = {false, 0}; \ + SendConfig conf = {false, false, 0}; \ errCode = comm##src##label->SendMessage(DEVICE_NAME_##dst, msgFor##src##label, conf); \ EXPECT_EQ(errCode, E_OK); \ } diff --git a/services/distributeddataservice/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_auto_launch_test.cpp b/services/distributeddataservice/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_auto_launch_test.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_data_operation_syncdb_test.cpp b/services/distributeddataservice/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_data_operation_syncdb_test.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_data_operation_test.cpp b/services/distributeddataservice/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_data_operation_test.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_data_value_test.cpp b/services/distributeddataservice/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_data_value_test.cpp index 661203e8479b864431796eff04d1f9feb94ed585..570d23d8fd831af89b00a7d61f2126daaba2cbde 100644 --- a/services/distributeddataservice/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_data_value_test.cpp +++ b/services/distributeddataservice/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_data_value_test.cpp @@ -35,33 +35,6 @@ void DataValueDefaultNullCheck(DataValue &dataValue) EXPECT_EQ(dataValue.GetType(), StorageType::STORAGE_TYPE_NULL); } -void DataValueBoolCheck(DataValue &dataValue) -{ - /** - * @tc.steps: step1. create a dataValue and set true - * @tc.expected: dataValue type is bool. - */ - bool targetVal = true; - dataValue = targetVal; - EXPECT_EQ(dataValue.GetType(), StorageType::STORAGE_TYPE_BOOL); - /** - * @tc.steps: step2. get a value from dataValue - * @tc.expected: get ok and value is true. - */ - bool val = false; - EXPECT_EQ(dataValue.GetBool(val), E_OK); - EXPECT_EQ(val, targetVal); - /** - * @tc.steps: step3. set false and then get it from dataValue. - * @tc.expected: get ok and value is false. - */ - targetVal = false; - dataValue = targetVal; - EXPECT_EQ(dataValue.GetType(), StorageType::STORAGE_TYPE_BOOL); - EXPECT_EQ(dataValue.GetBool(val), E_OK); - EXPECT_EQ(targetVal, val); -} - void DataValueDoubleCheck(DataValue &dataValue) { /** @@ -138,7 +111,7 @@ void DataValueBlobCheck(DataValue &dataValue) } const std::vector g_checkFuncList = { - &DataValueDefaultNullCheck, &DataValueBoolCheck, &DataValueInt64Check, + &DataValueDefaultNullCheck, &DataValueInt64Check, &DataValueDoubleCheck, &DataValueStringCheck, &DataValueBlobCheck }; diff --git a/services/distributeddataservice/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_database_corrupt_test.cpp b/services/distributeddataservice/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_database_corrupt_test.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_database_test.cpp b/services/distributeddataservice/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_database_test.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_device_identifier_test.cpp b/services/distributeddataservice/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_device_identifier_test.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_encrypt_database_test.cpp b/services/distributeddataservice/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_encrypt_database_test.cpp old mode 100755 new mode 100644 index 31c815784ffd8399c0073e7621901a5edf32a94b..645b3c7c2398144cc6b6166907c1ddc04fb91ef1 --- a/services/distributeddataservice/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_encrypt_database_test.cpp +++ b/services/distributeddataservice/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_encrypt_database_test.cpp @@ -95,7 +95,7 @@ void DistributedDBInterfacesEncryptDatabaseTest::CheckRekeyWithMultiKvStore(bool * @tc.expected: step3. return BUSY. */ CipherPassword passwd; // random password - vector passwdBuffer(10, 45); + vector passwdBuffer(10, 45); // 10 and 45 as random password. int errCode = passwd.SetValue(passwdBuffer.data(), passwdBuffer.size()); ASSERT_EQ(errCode, CipherPassword::ErrorCode::OK); EXPECT_EQ(kvStore1->Rekey(passwd), BUSY); @@ -138,7 +138,7 @@ void DistributedDBInterfacesEncryptDatabaseTest::CheckRekeyWithExistedSnapshot(b * @tc.expected: step3. return BUSY. */ CipherPassword passwd; // random password - vector passwdBuffer(10, 45); + vector passwdBuffer(10, 45); // 10 and 45 as random password. int errCode = passwd.SetValue(passwdBuffer.data(), passwdBuffer.size()); ASSERT_EQ(errCode, CipherPassword::ErrorCode::OK); EXPECT_EQ(kvStore->Rekey(passwd), BUSY); @@ -178,7 +178,7 @@ void DistributedDBInterfacesEncryptDatabaseTest::CheckRekeyWithExistedObserver(b * @tc.expected: step3. return BUSY. */ CipherPassword passwd; // random password - vector passwdBuffer(10, 45); + vector passwdBuffer(10, 45); // 10 and 45 as random password. int errCode = passwd.SetValue(passwdBuffer.data(), passwdBuffer.size()); ASSERT_EQ(errCode, CipherPassword::ErrorCode::OK); EXPECT_EQ(kvStore->Rekey(passwd), BUSY); diff --git a/services/distributeddataservice/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_encrypt_delegate_test.cpp b/services/distributeddataservice/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_encrypt_delegate_test.cpp old mode 100755 new mode 100644 index 75d4f009017d19bac70e2d272eb91eaebce38f50..f2d9b53f2569aef0134f02f25396a9665086bc31 --- a/services/distributeddataservice/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_encrypt_delegate_test.cpp +++ b/services/distributeddataservice/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_encrypt_delegate_test.cpp @@ -110,13 +110,13 @@ void DistributedDBInterfacesEncryptDelegateTest::SetUpTestCase(void) DistributedDBToolsUnitTest::TestDirInit(g_testDir); g_config.dataDir = g_testDir; g_mgr.SetKvStoreConfig(g_config); - vector passwdBuffer1(5, 1); + vector passwdBuffer1(5, 1); // 5 and 1 as random password. int errCode = g_passwd1.SetValue(passwdBuffer1.data(), passwdBuffer1.size()); ASSERT_EQ(errCode, CipherPassword::ErrorCode::OK); - vector passwdBuffer2(5, 2); + vector passwdBuffer2(5, 2); // 5 and 2 as random password. errCode = g_passwd2.SetValue(passwdBuffer2.data(), passwdBuffer2.size()); ASSERT_EQ(errCode, CipherPassword::ErrorCode::OK); - vector passwdBuffer3(5, 3); + vector passwdBuffer3(5, 3); // 5 and 3 as random password. errCode = g_passwd3.SetValue(passwdBuffer3.data(), passwdBuffer3.size()); ASSERT_EQ(errCode, CipherPassword::ErrorCode::OK); } diff --git a/services/distributeddataservice/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_import_and_export_test.cpp b/services/distributeddataservice/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_import_and_export_test.cpp old mode 100755 new mode 100644 index f0e38770f37755d184b3cc7c580f9a97ca563db3..28279b62036f9dea8df70f89930ee824beef4fb7 --- a/services/distributeddataservice/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_import_and_export_test.cpp +++ b/services/distributeddataservice/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_import_and_export_test.cpp @@ -96,16 +96,16 @@ void DistributedDBInterfacesImportAndExportTest::SetUpTestCase(void) g_exportFileDir = g_testDir + "/ExportDir"; OS::MakeDBDirectory(g_exportFileDir); - vector passwdBuffer1(5, 1); + vector passwdBuffer1(5, 1); // 5 and 1 as random password. int errCode = g_passwd1.SetValue(passwdBuffer1.data(), passwdBuffer1.size()); ASSERT_EQ(errCode, CipherPassword::ErrorCode::OK); - vector passwdBuffer2(5, 2); + vector passwdBuffer2(5, 2); // 5 and 2 as random password. errCode = g_passwd2.SetValue(passwdBuffer2.data(), passwdBuffer2.size()); ASSERT_EQ(errCode, CipherPassword::ErrorCode::OK); - vector passwdBuffer3(5, 3); + vector passwdBuffer3(5, 3); // 5 and 3 as random password. errCode = g_passwd3.SetValue(passwdBuffer3.data(), passwdBuffer3.size()); ASSERT_EQ(errCode, CipherPassword::ErrorCode::OK); - vector passwdBuffer4(5, 4); + vector passwdBuffer4(5, 4); // 5 and 4 as random password. errCode = g_passwd4.SetValue(passwdBuffer4.data(), passwdBuffer4.size()); ASSERT_EQ(errCode, CipherPassword::ErrorCode::OK); } diff --git a/services/distributeddataservice/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_index_unit_test.cpp b/services/distributeddataservice/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_index_unit_test.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_nb_delegate_local_batch_test.cpp b/services/distributeddataservice/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_nb_delegate_local_batch_test.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_nb_delegate_schema_put_test.cpp b/services/distributeddataservice/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_nb_delegate_schema_put_test.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_nb_delegate_test.cpp b/services/distributeddataservice/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_nb_delegate_test.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_nb_publish_test.cpp b/services/distributeddataservice/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_nb_publish_test.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_nb_transaction_test.cpp b/services/distributeddataservice/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_nb_transaction_test.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_nb_unpublish_test.cpp b/services/distributeddataservice/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_nb_unpublish_test.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_query_test.cpp b/services/distributeddataservice/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_query_test.cpp old mode 100755 new mode 100644 index e0f097a5832d7a642a0bad7a7658ecb0da65aeef..c59b1713e0f283109159a4678ba73446851b0121 --- a/services/distributeddataservice/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_query_test.cpp +++ b/services/distributeddataservice/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_query_test.cpp @@ -109,7 +109,7 @@ namespace { } } -class DistributedDBInterfacesQueryDBTest : public testing::Test { +class DistributedDBInterfacesQueryTest : public testing::Test { public: static void SetUpTestCase(void); static void TearDownTestCase(void); @@ -117,20 +117,20 @@ public: void TearDown(); }; -void DistributedDBInterfacesQueryDBTest::SetUpTestCase(void) +void DistributedDBInterfacesQueryTest::SetUpTestCase(void) { } -void DistributedDBInterfacesQueryDBTest::TearDownTestCase(void) +void DistributedDBInterfacesQueryTest::TearDownTestCase(void) { } -void DistributedDBInterfacesQueryDBTest::SetUp(void) +void DistributedDBInterfacesQueryTest::SetUp(void) { DistributedDBUnitTest::DistributedDBToolsUnitTest::PrintTestCaseInfo(); } -void DistributedDBInterfacesQueryDBTest::TearDown(void) +void DistributedDBInterfacesQueryTest::TearDown(void) { } @@ -141,7 +141,7 @@ void DistributedDBInterfacesQueryDBTest::TearDown(void) * @tc.require: AR000DR9K6 * @tc.author: sunpeng */ -HWTEST_F(DistributedDBInterfacesQueryDBTest, Query001, TestSize.Level1) +HWTEST_F(DistributedDBInterfacesQueryTest, Query001, TestSize.Level1) { Query query = Query::Select(); Query queryCopy = query; @@ -196,7 +196,7 @@ HWTEST_F(DistributedDBInterfacesQueryDBTest, Query001, TestSize.Level1) * @tc.require: AR000DR9K6 * @tc.author: sunpeng */ -HWTEST_F(DistributedDBInterfacesQueryDBTest, Query002, TestSize.Level1) +HWTEST_F(DistributedDBInterfacesQueryTest, Query002, TestSize.Level1) { float testValue = 1.1; Query query = Query::Select().NotEqualTo(".test", testValue); @@ -214,7 +214,7 @@ HWTEST_F(DistributedDBInterfacesQueryDBTest, Query002, TestSize.Level1) * @tc.require: AR000DR9K6 * @tc.author: sunpeng */ -HWTEST_F(DistributedDBInterfacesQueryDBTest, Query003, TestSize.Level1) +HWTEST_F(DistributedDBInterfacesQueryTest, Query003, TestSize.Level1) { Query query = Query::Select().EqualTo(TEST_FIELD_NAME, true).And().GreaterThan(TEST_FIELD_NAME, 1); QueryExpression queryExpression = GetQueryInfo::GetQueryExpression(query); diff --git a/services/distributeddataservice/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_register_syncdb_test.cpp b/services/distributeddataservice/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_register_syncdb_test.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_relational_sync_test.cpp b/services/distributeddataservice/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_relational_sync_test.cpp index 704741e11fdf122c73f4e4dd6d08609e77e0cf98..6ca71a9a47368e1bb886a928391e117277426770 100644 --- a/services/distributeddataservice/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_relational_sync_test.cpp +++ b/services/distributeddataservice/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_relational_sync_test.cpp @@ -57,7 +57,7 @@ namespace { class DistributedDBInterfacesRelationalSyncTest : public testing::Test { public: static void SetUpTestCase(void); - static void TearDownTestCase(void) {}; + static void TearDownTestCase(void); void SetUp() override ; void TearDown() override; protected: @@ -76,6 +76,11 @@ void DistributedDBInterfacesRelationalSyncTest::SetUpTestCase(void) RuntimeContext::GetInstance()->SetCommunicatorAggregator(g_communicatorAggregator); } +void DistributedDBInterfacesRelationalSyncTest::TearDownTestCase(void) +{ + RuntimeContext::GetInstance()->SetCommunicatorAggregator(nullptr); +} + void DistributedDBInterfacesRelationalSyncTest::SetUp() { DistributedDBToolsUnitTest::PrintTestCaseInfo(); diff --git a/services/distributeddataservice/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_relational_test.cpp b/services/distributeddataservice/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_relational_test.cpp index 7f9d9be34e8a3982afca516d42a58b93743a1f16..d153709b53b2243b87f1d13658f96c73a832bd7b 100644 --- a/services/distributeddataservice/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_relational_test.cpp +++ b/services/distributeddataservice/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_relational_test.cpp @@ -318,7 +318,7 @@ HWTEST_F(DistributedDBInterfacesRelationalTest, RelationalStoreTest005, TestSize ASSERT_NE(delegate, nullptr); /** - * @tc.steps:step3. Create distributed table with invald table name + * @tc.steps:step3. Create distributed table with invalid table name * @tc.expected: step3. Create distributed table failed. */ EXPECT_NE(delegate->CreateDistributedTable(DBConstant::SYSTEM_TABLE_PREFIX + "_tmp"), OK); @@ -362,7 +362,7 @@ HWTEST_F(DistributedDBInterfacesRelationalTest, RelationalStoreTest006, TestSize ASSERT_NE(delegate, nullptr); /** - * @tc.steps:step3. Create distributed table with invald table name + * @tc.steps:step3. Create distributed table with invalid table name * @tc.expected: step3. Create distributed table failed. */ EXPECT_EQ(delegate->CreateDistributedTable("sync_data"), OK); @@ -611,7 +611,7 @@ HWTEST_F(DistributedDBInterfacesRelationalTest, RelationalRemoveDeviceDataTest00 EXPECT_EQ(delegate->RemoveDeviceData("DEVICE_C", "sync_data"), OK); /** - * @tc.steps:step4. Remove device data with invald args + * @tc.steps:step4. Remove device data with invalid args * @tc.expected: step4. invalid */ EXPECT_EQ(delegate->RemoveDeviceData(""), INVALID_ARGS); @@ -679,6 +679,7 @@ HWTEST_F(DistributedDBInterfacesRelationalTest, RelationalOpenStorePressureTest0 ASSERT_NE(db, nullptr); EXPECT_EQ(RelationalTestUtils::ExecSql(db, "PRAGMA journal_mode=WAL;"), SQLITE_OK); EXPECT_EQ(RelationalTestUtils::ExecSql(db, NORMAL_CREATE_TABLE_SQL), SQLITE_OK); + EXPECT_EQ(sqlite3_close_v2(db), SQLITE_OK); DBStatus status = OK; for (int i = 0; i < 1000; i++) { @@ -703,10 +704,12 @@ HWTEST_F(DistributedDBInterfacesRelationalTest, RelationalOpenStorePressureTest0 ASSERT_NE(db, nullptr); EXPECT_EQ(RelationalTestUtils::ExecSql(db, "PRAGMA journal_mode=WAL;"), SQLITE_OK); EXPECT_EQ(RelationalTestUtils::ExecSql(db, NORMAL_CREATE_TABLE_SQL), SQLITE_OK); + EXPECT_EQ(sqlite3_close_v2(db), SQLITE_OK); std::queue delegateQueue; - std::mutex queuelock; - default_random_engine e; + std::mutex queueLock; + std::random_device rd; + default_random_engine e(rd()); uniform_int_distribution u(0, 9); std::thread openStoreThread([&, this]() { @@ -717,7 +720,7 @@ HWTEST_F(DistributedDBInterfacesRelationalTest, RelationalOpenStorePressureTest0 EXPECT_EQ(status, OK); ASSERT_NE(delegate, nullptr); { - std::lock_guard lock(queuelock); + std::lock_guard lock(queueLock); delegateQueue.push(delegate); } LOGD("++++< open store delegate: %d", i); @@ -728,7 +731,7 @@ HWTEST_F(DistributedDBInterfacesRelationalTest, RelationalOpenStorePressureTest0 while (cnt < 1000) { RelationalStoreDelegate *delegate = nullptr; { - std::lock_guard lock(queuelock); + std::lock_guard lock(queueLock); if (delegateQueue.empty()) { std::this_thread::sleep_for(std::chrono::microseconds(100)); continue; diff --git a/services/distributeddataservice/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_resultset_performance.cpp b/services/distributeddataservice/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_resultset_performance.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_schema_database_upgrade_test.cpp b/services/distributeddataservice/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_schema_database_upgrade_test.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_single_version_result_set_test.cpp b/services/distributeddataservice/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_single_version_result_set_test.cpp old mode 100755 new mode 100644 index 87b8e8d31ea858459b69e4a289bae951c1e9f6f6..a4bd33648244fcbcb7590d42ff8342dd0a0ae609 --- a/services/distributeddataservice/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_single_version_result_set_test.cpp +++ b/services/distributeddataservice/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_single_version_result_set_test.cpp @@ -58,7 +58,7 @@ namespace { const Key LOCAL_KEY_4 = {'K', '4'}; } -class DistributedDBSingleVersionResultSetTest : public testing::Test { +class DistributedDBInterfacesSingleVersionResultSetTest : public testing::Test { public: static void SetUpTestCase(void); static void TearDownTestCase(void); @@ -66,7 +66,7 @@ public: void TearDown(); }; -void DistributedDBSingleVersionResultSetTest::SetUpTestCase(void) +void DistributedDBInterfacesSingleVersionResultSetTest::SetUpTestCase(void) { DistributedDBToolsUnitTest::TestDirInit(g_testDir); g_config.dataDir = g_testDir; @@ -83,7 +83,7 @@ void DistributedDBSingleVersionResultSetTest::SetUpTestCase(void) } } -void DistributedDBSingleVersionResultSetTest::TearDownTestCase(void) +void DistributedDBInterfacesSingleVersionResultSetTest::TearDownTestCase(void) { if (DistributedDBToolsUnitTest::RemoveTestDbFiles(g_testDir + STORE_ID + "/" + DBConstant::SINGLE_SUB_DIR) != 0) { LOGE("rm test db files error!"); @@ -92,7 +92,7 @@ void DistributedDBSingleVersionResultSetTest::TearDownTestCase(void) std::this_thread::sleep_for(std::chrono::milliseconds(TIME_LAG)); } -void DistributedDBSingleVersionResultSetTest::SetUp(void) +void DistributedDBInterfacesSingleVersionResultSetTest::SetUp(void) { DistributedDBToolsUnitTest::PrintTestCaseInfo(); KvStoreNbDelegate::Option delegateOption = {true}; @@ -132,7 +132,7 @@ void DistributedDBSingleVersionResultSetTest::SetUp(void) ASSERT_NE(g_rawCursor, nullptr); } -void DistributedDBSingleVersionResultSetTest::TearDown(void) +void DistributedDBInterfacesSingleVersionResultSetTest::TearDown(void) { if (g_connection != nullptr) { g_connection->Close(); @@ -162,7 +162,7 @@ void DistributedDBSingleVersionResultSetTest::TearDown(void) * @tc.require: AR000D08KT * @tc.author: maokeheng */ -HWTEST_F(DistributedDBSingleVersionResultSetTest, SingleVersionResultSetTest001, TestSize.Level1) +HWTEST_F(DistributedDBInterfacesSingleVersionResultSetTest, SingleVersionResultSetTest001, TestSize.Level1) { /** * @tc.steps:step1. Let the WindowSize be INT_MAX, which is larger than the upper limit. @@ -181,7 +181,7 @@ HWTEST_F(DistributedDBSingleVersionResultSetTest, SingleVersionResultSetTest001, * @tc.require: AR000D08KT * @tc.author: maokeheng */ -HWTEST_F(DistributedDBSingleVersionResultSetTest, SingleVersionResultSetTest002, TestSize.Level1) +HWTEST_F(DistributedDBInterfacesSingleVersionResultSetTest, SingleVersionResultSetTest002, TestSize.Level1) { /** * @tc.steps:step1. Let the WindowSize be -1. @@ -200,7 +200,7 @@ HWTEST_F(DistributedDBSingleVersionResultSetTest, SingleVersionResultSetTest002, * @tc.require: AR000D08KT * @tc.author: maokeheng */ -HWTEST_F(DistributedDBSingleVersionResultSetTest, SingleVersionResultSetTest003, TestSize.Level1) +HWTEST_F(DistributedDBInterfacesSingleVersionResultSetTest, SingleVersionResultSetTest003, TestSize.Level1) { /** * @tc.steps:step1. Let the WindowSize be 0. @@ -219,7 +219,7 @@ HWTEST_F(DistributedDBSingleVersionResultSetTest, SingleVersionResultSetTest003, * @tc.require: AR000D08KT * @tc.author: maokeheng */ -HWTEST_F(DistributedDBSingleVersionResultSetTest, SingleVersionResultSetTest004, TestSize.Level1) +HWTEST_F(DistributedDBInterfacesSingleVersionResultSetTest, SingleVersionResultSetTest004, TestSize.Level1) { /** * @tc.steps:step1. Let the WindowSize be 100, which is smaller than the upper limit. @@ -238,7 +238,7 @@ HWTEST_F(DistributedDBSingleVersionResultSetTest, SingleVersionResultSetTest004, * @tc.require: AR000D08KT * @tc.author: maokeheng */ -HWTEST_F(DistributedDBSingleVersionResultSetTest, SingleVersionResultSetTest005, TestSize.Level1) +HWTEST_F(DistributedDBInterfacesSingleVersionResultSetTest, SingleVersionResultSetTest005, TestSize.Level1) { /** * @tc.steps:step1. Let the WindowSize be 100, and window scale to be negative (-1). @@ -257,7 +257,7 @@ HWTEST_F(DistributedDBSingleVersionResultSetTest, SingleVersionResultSetTest005, * @tc.require: AR000D08KT * @tc.author: maokeheng */ -HWTEST_F(DistributedDBSingleVersionResultSetTest, SingleVersionResultSetTest006, TestSize.Level1) +HWTEST_F(DistributedDBInterfacesSingleVersionResultSetTest, SingleVersionResultSetTest006, TestSize.Level1) { /** * @tc.steps:step1. Let the WindowSize be 100, and window scale to be 2. @@ -276,7 +276,7 @@ HWTEST_F(DistributedDBSingleVersionResultSetTest, SingleVersionResultSetTest006, * @tc.require: AR000D08KT * @tc.author: maokeheng */ -HWTEST_F(DistributedDBSingleVersionResultSetTest, SingleVersionResultSetTest007, TestSize.Level1) +HWTEST_F(DistributedDBInterfacesSingleVersionResultSetTest, SingleVersionResultSetTest007, TestSize.Level1) { /** * @tc.steps:step1. Let the WindowSize be 100, and window scale to be 0. @@ -295,7 +295,7 @@ HWTEST_F(DistributedDBSingleVersionResultSetTest, SingleVersionResultSetTest007, * @tc.require: AR000D08KT * @tc.author: maokeheng */ -HWTEST_F(DistributedDBSingleVersionResultSetTest, SingleVersionResultSetTest008, TestSize.Level1) +HWTEST_F(DistributedDBInterfacesSingleVersionResultSetTest, SingleVersionResultSetTest008, TestSize.Level1) { /** * @tc.steps:step1. Let the WindowSize be 100, and window scale to be 0.5. @@ -314,7 +314,7 @@ HWTEST_F(DistributedDBSingleVersionResultSetTest, SingleVersionResultSetTest008, * @tc.require: AR000D08KT * @tc.author: maokeheng */ -HWTEST_F(DistributedDBSingleVersionResultSetTest, SingleVersionResultSetTest009, TestSize.Level1) +HWTEST_F(DistributedDBInterfacesSingleVersionResultSetTest, SingleVersionResultSetTest009, TestSize.Level1) { /** * @tc.steps:step1. Let the WindowSize be 100, and window scale to be 1 and resultWindow be null pointer. @@ -334,7 +334,7 @@ HWTEST_F(DistributedDBSingleVersionResultSetTest, SingleVersionResultSetTest009, * @tc.require: AR000D08KT * @tc.author: maokeheng */ -HWTEST_F(DistributedDBSingleVersionResultSetTest, SingleVersionResultSetTest010, TestSize.Level1) +HWTEST_F(DistributedDBInterfacesSingleVersionResultSetTest, SingleVersionResultSetTest010, TestSize.Level1) { /** * @tc.steps:step1. Let the WindowSize be 100, and window scale to be 1 and resultWindow be null pointer. @@ -360,7 +360,7 @@ HWTEST_F(DistributedDBSingleVersionResultSetTest, SingleVersionResultSetTest010, * @tc.require: AR000D08KT * @tc.author: maokeheng */ -HWTEST_F(DistributedDBSingleVersionResultSetTest, SingleVersionResultSetTest011, TestSize.Level1) +HWTEST_F(DistributedDBInterfacesSingleVersionResultSetTest, SingleVersionResultSetTest011, TestSize.Level1) { /** * @tc.steps:step1. Let the WindowSize be 100, and window scale to be 1 and resultWindow be null pointer. @@ -399,7 +399,7 @@ HWTEST_F(DistributedDBSingleVersionResultSetTest, SingleVersionResultSetTest011, * @tc.require: AR000D08KT * @tc.author: maokeheng */ -HWTEST_F(DistributedDBSingleVersionResultSetTest, SingleVersionResultSetTest012, TestSize.Level1) +HWTEST_F(DistributedDBInterfacesSingleVersionResultSetTest, SingleVersionResultSetTest012, TestSize.Level1) { /** * @tc.steps:step1. Let the WindowSize be 100, and window scale to be 1 and resultWindow be null pointer. @@ -433,7 +433,7 @@ HWTEST_F(DistributedDBSingleVersionResultSetTest, SingleVersionResultSetTest012, * @tc.require: AR000D08KT * @tc.author: maokeheng */ -HWTEST_F(DistributedDBSingleVersionResultSetTest, SingleVersionResultSetTest013, TestSize.Level1) +HWTEST_F(DistributedDBInterfacesSingleVersionResultSetTest, SingleVersionResultSetTest013, TestSize.Level1) { /** * @tc.steps:step1. Let the WindowSize be 100, and window scale to be 1 and resultWindow be null pointer. @@ -468,7 +468,7 @@ HWTEST_F(DistributedDBSingleVersionResultSetTest, SingleVersionResultSetTest013, * @tc.require: AR000D08KT * @tc.author: maokeheng */ -HWTEST_F(DistributedDBSingleVersionResultSetTest, SingleVersionResultSetTest014, TestSize.Level1) +HWTEST_F(DistributedDBInterfacesSingleVersionResultSetTest, SingleVersionResultSetTest014, TestSize.Level1) { /** * @tc.steps:step1. Let the WindowSize be 100, and window scale to be 1 and resultWindow be null pointer. @@ -504,7 +504,7 @@ HWTEST_F(DistributedDBSingleVersionResultSetTest, SingleVersionResultSetTest014, * @tc.require: AR000D08KT * @tc.author: maokeheng */ -HWTEST_F(DistributedDBSingleVersionResultSetTest, SingleVersionResultSetTest015, TestSize.Level1) +HWTEST_F(DistributedDBInterfacesSingleVersionResultSetTest, SingleVersionResultSetTest015, TestSize.Level1) { /** * @tc.steps:step1. Let the WindowSize be 100, and window scale to be 1 and resultWindow be null pointer. diff --git a/services/distributeddataservice/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_space_management_test.cpp b/services/distributeddataservice/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_space_management_test.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_transaction_optimization_test.cpp b/services/distributeddataservice/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_transaction_optimization_test.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_transaction_syncdb_test.cpp b/services/distributeddataservice/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_transaction_syncdb_test.cpp old mode 100755 new mode 100644 index 765fab83fe861f2532ad5598bca4b752dbdbcc3f..1b8779f8e504e28307a7aac7b121a125ff1988a4 --- a/services/distributeddataservice/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_transaction_syncdb_test.cpp +++ b/services/distributeddataservice/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_transaction_syncdb_test.cpp @@ -508,7 +508,7 @@ HWTEST_F(DistributedDBInterfacesTransactionSyncDBTest, RollBack004, TestSize.Lev /** * @tc.name: RollBack005 - * @tc.desc: delete a exist data and rollback + * @tc.desc: delete an exist data and rollback * @tc.type: FUNC * @tc.require: AR000BVRNM AR000CQDTQ * @tc.author: huangnaigu diff --git a/services/distributeddataservice/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_transaction_test.cpp b/services/distributeddataservice/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_transaction_test.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_transaction_testcase.cpp b/services/distributeddataservice/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_transaction_testcase.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/test/unittest/common/interfaces/process_system_api_adapter_impl.cpp b/services/distributeddataservice/libs/distributeddb/test/unittest/common/interfaces/process_system_api_adapter_impl.cpp old mode 100755 new mode 100644 index 8b451b370eb38da4f1cdc1ae2de49de8d5af829b..821801545619d4db4f201a938fdea3bd0360fa57 --- a/services/distributeddataservice/libs/distributeddb/test/unittest/common/interfaces/process_system_api_adapter_impl.cpp +++ b/services/distributeddataservice/libs/distributeddb/test/unittest/common/interfaces/process_system_api_adapter_impl.cpp @@ -72,7 +72,6 @@ DBStatus ProcessSystemApiAdapterImpl::SetSecurityOption(const std::string &fileP if (dirPtr == nullptr) { LOGD("set path secOpt![%s] [%d] [%d]", filePath.c_str(), option.securityFlag, option.securityLabel); pathSecOptDic_[filePath] = option; - closedir(dirPtr); return OK; } diff --git a/services/distributeddataservice/libs/distributeddb/test/unittest/common/interfaces/process_system_api_adapter_impl.h b/services/distributeddataservice/libs/distributeddb/test/unittest/common/interfaces/process_system_api_adapter_impl.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/test/unittest/common/interfaces/runtime_context_process_system_api_adapter_impl_test.cpp b/services/distributeddataservice/libs/distributeddb/test/unittest/common/interfaces/runtime_context_process_system_api_adapter_impl_test.cpp old mode 100755 new mode 100644 index 39c9935e583d1bb3d82025745db0f623137387a0..373f325d62d1d6dc38bcad4030592e0f9cf3c3d3 --- a/services/distributeddataservice/libs/distributeddb/test/unittest/common/interfaces/runtime_context_process_system_api_adapter_impl_test.cpp +++ b/services/distributeddataservice/libs/distributeddb/test/unittest/common/interfaces/runtime_context_process_system_api_adapter_impl_test.cpp @@ -54,7 +54,7 @@ public: void RuntimeContextProcessSystemApiAdapterImplTest::SetUpTestCase(void) { /** - * @tc.setup: Get a adapter + * @tc.setup: Get an adapter */ g_adapter = std::make_shared(); EXPECT_TRUE(g_adapter != nullptr); diff --git a/services/distributeddataservice/libs/distributeddb/test/unittest/common/storage/distributeddb_data_transformer_test.cpp b/services/distributeddataservice/libs/distributeddb/test/unittest/common/storage/distributeddb_data_transformer_test.cpp index 5c9b4d5d87d2399a720ae7316af99d162009e65a..f1e605a0533fac5426fb73b12b09706e11758c19 100644 --- a/services/distributeddataservice/libs/distributeddb/test/unittest/common/storage/distributeddb_data_transformer_test.cpp +++ b/services/distributeddataservice/libs/distributeddb/test/unittest/common/storage/distributeddb_data_transformer_test.cpp @@ -28,11 +28,6 @@ void SetNull(DataValue &dataValue) dataValue.ResetValue(); } -void SetBool(DataValue &dataValue) -{ - dataValue = false; -} - void SetInt64(DataValue &dataValue) { dataValue = INT64_MAX; @@ -57,7 +52,6 @@ void SetBlob(DataValue &dataValue) std::map g_typeMapFunction = { {StorageType::STORAGE_TYPE_NULL, &SetNull}, - {StorageType::STORAGE_TYPE_BOOL, &SetBool}, {StorageType::STORAGE_TYPE_INTEGER, &SetInt64}, {StorageType::STORAGE_TYPE_REAL, &SetDouble}, {StorageType::STORAGE_TYPE_TEXT, &SetText}, @@ -197,7 +191,7 @@ HWTEST_F(DistributedDBDataTransformerTest, DataTransformerCheck001, TestSize.Lev } /** - * @tc.steps: step2. generate a originData by fieldInfoLiist. + * @tc.steps: step2. generate an originData by fieldInfoLiist. */ TableDataWithLog originData; GenerateTableDataWithLog(fieldInfoList, originData); diff --git a/services/distributeddataservice/libs/distributeddb/test/unittest/common/storage/distributeddb_file_package_test.cpp b/services/distributeddataservice/libs/distributeddb/test/unittest/common/storage/distributeddb_file_package_test.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/test/unittest/common/storage/distributeddb_multi_ver_vacuum_test.cpp b/services/distributeddataservice/libs/distributeddb/test/unittest/common/storage/distributeddb_multi_ver_vacuum_test.cpp old mode 100755 new mode 100644 index 55df49607945e0fa349941a9b55e1660bedf75e3..0e0618a83f50acf1653ba4a4123837e494821c18 --- a/services/distributeddataservice/libs/distributeddb/test/unittest/common/storage/distributeddb_multi_ver_vacuum_test.cpp +++ b/services/distributeddataservice/libs/distributeddb/test/unittest/common/storage/distributeddb_multi_ver_vacuum_test.cpp @@ -96,7 +96,7 @@ HWTEST_F(DistributedDBMultiVerVacuumTest, SingleTaskNormalStatusSwitch001, TestS { // Preset MultiVerVacuum vacuum; - MultiVerVacuumExecutorStub databaseA(DbScale{1, 1, 2, 2}, 100); // 1, 2 For Scale, 100 For TimeCost, 1.7s in Total + MultiVerVacuumExecutorStub databaseA(DbScale {1, 1, 2, 2}, 100); // 1, 2 For Scale, 100 For TimeCost, 1.7s in Total /** * @tc.steps: step1. launch dbTaskA for databaseA @@ -163,7 +163,7 @@ HWTEST_F(DistributedDBMultiVerVacuumTest, SingleTaskNormalStatusSwitch002, TestS { // Preset MultiVerVacuum vacuum; - MultiVerVacuumExecutorStub databaseB(DbScale{1, 1, 2, 2}, 100); // 1, 2 For Scale, 100 For TimeCost, 1.7s in Total + MultiVerVacuumExecutorStub databaseB(DbScale {1, 1, 2, 2}, 100); // 1, 2 For Scale, 100 For TimeCost, 1.7s in Total /** * @tc.steps: step1. launch dbTaskB for databaseB, then wait for some time @@ -230,7 +230,7 @@ HWTEST_F(DistributedDBMultiVerVacuumTest, SingleTaskNormalStatusSwitch003, TestS { // Preset MultiVerVacuum vacuum; - MultiVerVacuumExecutorStub databaseC(DbScale{1, 1, 2, 2}, 100); // 1, 2 For Scale, 100 For TimeCost, 1.7s in Total + MultiVerVacuumExecutorStub databaseC(DbScale {1, 1, 2, 2}, 100); // 1, 2 For Scale, 100 For TimeCost, 1.7s in Total /** * @tc.steps: step1. launch dbTaskC for databaseC, then wait for some time @@ -296,7 +296,7 @@ HWTEST_F(DistributedDBMultiVerVacuumTest, SingleTaskNormalStatusSwitch004, TestS { // Preset MultiVerVacuum vacuum; - MultiVerVacuumExecutorStub databaseA(DbScale{1, 1, 2, 2}, 100); // 1, 2 For Scale, 100 For TimeCost, 1.7s in Total + MultiVerVacuumExecutorStub databaseA(DbScale {1, 1, 2, 2}, 100); // 1, 2 For Scale, 100 For TimeCost, 1.7s in Total /** * @tc.steps: step1. launch dbTaskA for databaseA, then wait for some time @@ -354,7 +354,7 @@ HWTEST_F(DistributedDBMultiVerVacuumTest, SingleTaskAbnormalStatusSwitch001, Tes { // Preset MultiVerVacuum vacuum; - MultiVerVacuumExecutorStub databaseB(DbScale{1, 1, 2, 2}, 100); // 1, 2 For Scale, 100 For TimeCost, 1.7s in Total + MultiVerVacuumExecutorStub databaseB(DbScale {1, 1, 2, 2}, 100); // 1, 2 For Scale, 100 For TimeCost, 1.7s in Total /** * @tc.steps: step1. launch dbTaskB for databaseB @@ -493,7 +493,7 @@ HWTEST_F(DistributedDBMultiVerVacuumTest, SingleTaskConcurrentStatusSwitch001, T { // Preset MultiVerVacuum vacuum; - MultiVerVacuumExecutorStub databaseC(DbScale{1, 1, 1, 1}, 1000); // 1 For Scale, 1000 For TimeCost, 11s in Total + MultiVerVacuumExecutorStub databaseC(DbScale {1, 1, 1, 1}, 1000); // 1 For Scale, 1000 For TimeCost, 11s in Total /** * @tc.steps: step1. launch dbTaskC for databaseC, databaseC is timecost @@ -549,7 +549,7 @@ HWTEST_F(DistributedDBMultiVerVacuumTest, SingleTaskWriteHandleOccupy001, TestSi { // Preset MultiVerVacuum vacuum; - MultiVerVacuumExecutorStub databaseA(DbScale{1, 1, 2, 2}, 100); // 1, 2 For Scale, 100 For TimeCost, 1.7s in Total + MultiVerVacuumExecutorStub databaseA(DbScale {1, 1, 2, 2}, 100); // 1, 2 For Scale, 100 For TimeCost, 1.7s in Total /** * @tc.steps: step1. launch dbTaskA for databaseA @@ -559,7 +559,7 @@ HWTEST_F(DistributedDBMultiVerVacuumTest, SingleTaskWriteHandleOccupy001, TestSi EXPECT_EQ(errCode, E_OK); bool stepOne = CheckVacuumTaskStatus(vacuum, DB_IDENTITY_A, VacuumTaskStatus::RUN_NING); EXPECT_EQ(stepOne, true); - stepOne = RepeatCheckAsyncResult([&databaseA]()->bool{ + stepOne = RepeatCheckAsyncResult([&databaseA]()->bool { return databaseA.IsTransactionOccupied() == true; }, 5, 100); // 5 times, 100 ms EXPECT_EQ(stepOne, true); @@ -582,7 +582,7 @@ HWTEST_F(DistributedDBMultiVerVacuumTest, SingleTaskWriteHandleOccupy001, TestSi EXPECT_EQ(errCode, E_OK); bool stepThree = CheckVacuumTaskStatus(vacuum, DB_IDENTITY_A, VacuumTaskStatus::RUN_NING); EXPECT_EQ(stepThree, true); - stepThree = RepeatCheckAsyncResult([&databaseA]()->bool{ + stepThree = RepeatCheckAsyncResult([&databaseA]()->bool { return databaseA.IsTransactionOccupied() == true; }, 5, 100); // 5 times, 100 ms EXPECT_EQ(stepThree, true); @@ -609,8 +609,8 @@ HWTEST_F(DistributedDBMultiVerVacuumTest, MultipleTaskNormalStatusSwitch001, Tes { // Preset MultiVerVacuum vacuum; - MultiVerVacuumExecutorStub databaseA(DbScale{1, 1, 2, 2}, 100); // 1, 2 For Scale, 100 For TimeCost, 1.7s in Total - MultiVerVacuumExecutorStub databaseB(DbScale{1, 1, 2, 2}, 100); // 1, 2 For Scale, 100 For TimeCost, 1.7s in Total + MultiVerVacuumExecutorStub databaseA(DbScale {1, 1, 2, 2}, 100); // 1, 2 For Scale, 100 For TimeCost, 1.7s in Total + MultiVerVacuumExecutorStub databaseB(DbScale {1, 1, 2, 2}, 100); // 1, 2 For Scale, 100 For TimeCost, 1.7s in Total /** * @tc.steps: step1. launch dbTaskA for databaseA and dbTaskB for databaseB @@ -680,9 +680,9 @@ HWTEST_F(DistributedDBMultiVerVacuumTest, MultipleTaskNormalStatusSwitch002, Tes { // Preset MultiVerVacuum vacuum; - MultiVerVacuumExecutorStub databaseA(DbScale{1, 1, 1, 1}, 30); // 1 For Scale, 30 For TimeCost, 330ms in Total - MultiVerVacuumExecutorStub databaseB(DbScale{1, 1, 2, 2}, 100); // 1, 2 For Scale, 100 For TimeCost, 1.7s in Total - MultiVerVacuumExecutorStub databaseC(DbScale{1, 1, 2, 2}, 100); // 1, 2 For Scale, 100 For TimeCost, 1.7s in Total + MultiVerVacuumExecutorStub databaseA(DbScale {1, 1, 1, 1}, 30); // 1 For Scale, 30 For TimeCost, 330ms in Total + MultiVerVacuumExecutorStub databaseB(DbScale {1, 1, 2, 2}, 100); // 1, 2 For Scale, 100 For TimeCost, 1.7s in Total + MultiVerVacuumExecutorStub databaseC(DbScale {1, 1, 2, 2}, 100); // 1, 2 For Scale, 100 For TimeCost, 1.7s in Total /** * @tc.steps: step1. launch dbTaskA,B,C for databaseA,B,C and wait dbTaskA,B FINISH diff --git a/services/distributeddataservice/libs/distributeddb/test/unittest/common/storage/distributeddb_sqlite_register_test.cpp b/services/distributeddataservice/libs/distributeddb/test/unittest/common/storage/distributeddb_sqlite_register_test.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/test/unittest/common/storage/distributeddb_storage_commit_storage_test.cpp b/services/distributeddataservice/libs/distributeddb/test/unittest/common/storage/distributeddb_storage_commit_storage_test.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/test/unittest/common/storage/distributeddb_storage_data_operation_test.cpp b/services/distributeddataservice/libs/distributeddb/test/unittest/common/storage/distributeddb_storage_data_operation_test.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/test/unittest/common/storage/distributeddb_storage_encrypt_test.cpp b/services/distributeddataservice/libs/distributeddb/test/unittest/common/storage/distributeddb_storage_encrypt_test.cpp old mode 100755 new mode 100644 index 5edc49d514a5faa7e60c14fa8cb0f8b6b6e15118..8b3a0b7e456a03b29f222ffeb1d125df63112095 --- a/services/distributeddataservice/libs/distributeddb/test/unittest/common/storage/distributeddb_storage_encrypt_test.cpp +++ b/services/distributeddataservice/libs/distributeddb/test/unittest/common/storage/distributeddb_storage_encrypt_test.cpp @@ -336,8 +336,12 @@ void DistributedDBStorageEncryptTest::SetUp(void) /** * @tc.Clean DB files created from every test case. */ - remove((STORE_ID + ".db").c_str()); - remove((STORE_ID2 + ".db").c_str()); + if (remove((STORE_ID + ".db").c_str()) != 0) { + LOGE("remove db failed, errno:%d", errno); + } + if (remove((STORE_ID2 + ".db").c_str()) != 0) { + LOGE("remove db failed, errno:%d", errno); + } } void DistributedDBStorageEncryptTest::TearDown(void) @@ -351,8 +355,12 @@ void DistributedDBStorageEncryptTest::TearDown(void) /** * @tc.Clean DB files created from every test case. */ - remove((STORE_ID + ".db").c_str()); - remove((STORE_ID2 + ".db").c_str()); + if (remove((STORE_ID + ".db").c_str()) != 0) { + LOGE("remove db failed, errno:%d", errno); + } + if (remove((STORE_ID2 + ".db").c_str()) != 0) { + LOGE("remove db failed, errno:%d", errno); + } /** * @tc.Wait a number of SLEEP_TIME until remove done. */ diff --git a/services/distributeddataservice/libs/distributeddb/test/unittest/common/storage/distributeddb_storage_index_optimize_test.cpp b/services/distributeddataservice/libs/distributeddb/test/unittest/common/storage/distributeddb_storage_index_optimize_test.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/test/unittest/common/storage/distributeddb_storage_memory_single_ver_naturall_store_test.cpp b/services/distributeddataservice/libs/distributeddb/test/unittest/common/storage/distributeddb_storage_memory_single_ver_naturall_store_test.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/test/unittest/common/storage/distributeddb_storage_register_conflict_test.cpp b/services/distributeddataservice/libs/distributeddb/test/unittest/common/storage/distributeddb_storage_register_conflict_test.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/test/unittest/common/storage/distributeddb_storage_register_observer_test.cpp b/services/distributeddataservice/libs/distributeddb/test/unittest/common/storage/distributeddb_storage_register_observer_test.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/test/unittest/common/storage/distributeddb_storage_resultset_and_json_optimize.cpp b/services/distributeddataservice/libs/distributeddb/test/unittest/common/storage/distributeddb_storage_resultset_and_json_optimize.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/test/unittest/common/storage/distributeddb_storage_single_ver_natural_store_testcase.cpp b/services/distributeddataservice/libs/distributeddb/test/unittest/common/storage/distributeddb_storage_single_ver_natural_store_testcase.cpp old mode 100755 new mode 100644 index ebe1e5420802b21286a92379db4efb0914fcecb2..bdaf46efb1054bf9e778d47b8ab976deb7a16539 --- a/services/distributeddataservice/libs/distributeddb/test/unittest/common/storage/distributeddb_storage_single_ver_natural_store_testcase.cpp +++ b/services/distributeddataservice/libs/distributeddb/test/unittest/common/storage/distributeddb_storage_single_ver_natural_store_testcase.cpp @@ -739,7 +739,7 @@ void DistributedDBStorageSingleVerNaturalStoreTestCase::SyncDatabaseOperate002(S DataItem dataItem1; DistributedDBToolsUnitTest::GetRandomKeyValue(dataItem1.key); DistributedDBToolsUnitTest::GetRandomKeyValue(dataItem1.value); - dataItem1.timeStamp = 1001; // random timestamp + dataItem1.timeStamp = 1001; // 1001 as random timestamp dataItem1.writeTimeStamp = dataItem1.timeStamp; dataItem1.flag = 0; @@ -804,7 +804,7 @@ void DistributedDBStorageSingleVerNaturalStoreTestCase::SyncDatabaseOperate004(S DataItem dataItem1; DistributedDBToolsUnitTest::GetRandomKeyValue(dataItem1.key); DistributedDBToolsUnitTest::GetRandomKeyValue(dataItem1.value); - dataItem1.timeStamp = 1997; // random timestamp + dataItem1.timeStamp = 1997; // 1997 as random timestamp dataItem1.writeTimeStamp = dataItem1.timeStamp; dataItem1.flag = 0; @@ -873,13 +873,13 @@ void DistributedDBStorageSingleVerNaturalStoreTestCase::SyncDatabaseOperate006(S * Insert the data of key length=keyPrefix length - 1, value3. * @tc.expected: step2/3/4. Return E_NOT_FOUND. */ - DistributedDBToolsUnitTest::GetRandomKeyValue(key1, 30); // random size + DistributedDBToolsUnitTest::GetRandomKeyValue(key1, 30); // 30 as random size key3 = key2 = key1; key2.push_back('C'); key3.pop_back(); - DistributedDBToolsUnitTest::GetRandomKeyValue(value1, 84); // random size - DistributedDBToolsUnitTest::GetRandomKeyValue(value2, 101); // random size - DistributedDBToolsUnitTest::GetRandomKeyValue(value3, 37); // random size + DistributedDBToolsUnitTest::GetRandomKeyValue(value1, 84); // 84 as random size + DistributedDBToolsUnitTest::GetRandomKeyValue(value2, 101); // 101 as random size + DistributedDBToolsUnitTest::GetRandomKeyValue(value3, 37); // 37 as random size EXPECT_EQ(connection->Put(option, key1, value1), E_OK); EXPECT_EQ(connection->Put(option, key2, value2), E_OK); EXPECT_EQ(connection->Put(option, key3, value3), E_OK); @@ -924,14 +924,14 @@ void DistributedDBStorageSingleVerNaturalStoreTestCase::ClearRemoteData001(SQLit DataItem dataItem1; DistributedDBToolsUnitTest::GetRandomKeyValue(dataItem1.key); DistributedDBToolsUnitTest::GetRandomKeyValue(dataItem1.value); - dataItem1.timeStamp = 1997; // random timestamp + dataItem1.timeStamp = 1997; // 1997 as random timestamp dataItem1.writeTimeStamp = dataItem1.timeStamp; dataItem1.flag = 0; DataItem dataItem2; DistributedDBToolsUnitTest::GetRandomKeyValue(dataItem2.key, dataItem1.key.size() + 1); DistributedDBToolsUnitTest::GetRandomKeyValue(dataItem2.value); - dataItem2.timeStamp = 2019; // random timestamp + dataItem2.timeStamp = 2019; // 2019 as random timestamp dataItem2.writeTimeStamp = dataItem2.timeStamp; dataItem2.flag = 0; @@ -1013,7 +1013,7 @@ void DistributedDBStorageSingleVerNaturalStoreTestCase::DeleteUserKeyValue001(SQ int numSelect = GetRawSyncData(url, SYNC_DATA_DEFAULT_SQL, vecSyncData); bool isFound = false; - EXPECT_EQ(numSelect, 2); + EXPECT_EQ(numSelect, 2); // 2 as entry size isFound = IsSqlinteExistKey(vecSyncData, KEY_1); EXPECT_EQ(isFound, false); isFound = IsSqlinteExistKey(vecSyncData, KEY_2); @@ -1052,7 +1052,7 @@ void DistributedDBStorageSingleVerNaturalStoreTestCase::MemoryDbDeleteUserKeyVal int numSelect = GetRawSyncData(url, SYNC_DATA_DEFAULT_SQL, vecSyncData); bool isFound = false; - EXPECT_EQ(numSelect, 2); + EXPECT_EQ(numSelect, 2); // 2 as entry size isFound = IsSqlinteExistKey(vecSyncData, KEY_1); EXPECT_EQ(isFound, false); isFound = IsSqlinteExistKey(vecSyncData, KEY_2); @@ -1108,7 +1108,7 @@ void DistributedDBStorageSingleVerNaturalStoreTestCase::DeleteUserKeyValue002(SQ std::vector vecSyncData; int numSelect = GetRawSyncData(url, SYNC_DATA_DEFAULT_SQL, vecSyncData); - EXPECT_EQ(numSelect, 2); + EXPECT_EQ(numSelect, 2); // 2 as entry size } /** @@ -1341,7 +1341,7 @@ void DistributedDBStorageSingleVerNaturalStoreTestCase::DeleteUserKeyValue005(SQ std::vector vecSyncData; int numSelect = GetRawSyncData(url, SYNC_DATA_DEFAULT_SQL, vecSyncData); - EXPECT_EQ(numSelect, 2); + EXPECT_EQ(numSelect, 2); // 2 as entry size bool isFound = IsSqlinteExistKey(vecSyncData, KEY_1); EXPECT_EQ(isFound, true); } @@ -1391,7 +1391,7 @@ void DistributedDBStorageSingleVerNaturalStoreTestCase::MemoryDbDeleteUserKeyVal std::vector vecSyncData; int numSelect = GetRawSyncData(url, SYNC_DATA_DEFAULT_SQL, vecSyncData); - EXPECT_EQ(numSelect, 2); + EXPECT_EQ(numSelect, 2); // 2 as entry size bool isFound = IsSqlinteExistKey(vecSyncData, KEY_1); EXPECT_EQ(isFound, true); @@ -1606,7 +1606,7 @@ void DistributedDBStorageSingleVerNaturalStoreTestCase::TestMetaDataPutAndGet(SQ EXPECT_EQ(store->GetMetaData(key1, valueRead), E_OK); EXPECT_EQ(DistributedDBToolsUnitTest::IsValueEqual(valueRead, value1), true); Value value2; - DistributedDBToolsUnitTest::GetRandomKeyValue(value2, static_cast(value1.size() + 3)); // random size + DistributedDBToolsUnitTest::GetRandomKeyValue(value2, static_cast(value1.size() + 3)); // 3 as random size /** * @tc.steps:step3. The key value is key1, the value is not empty, @@ -1663,10 +1663,10 @@ void DistributedDBStorageSingleVerNaturalStoreTestCase::TestMetaDataPutAndGet(SQ * or value size greater than 4Mb through PutMetaData of NaturalStore. * @tc.expected: step9/10. Return E_INVALID_ARGS. */ - sizeKey.push_back(249); // random + sizeKey.push_back(249); // 249 as random size EXPECT_EQ(store->PutMetaData(sizeKey, sizeValue), -E_INVALID_ARGS); sizeKey.pop_back(); - sizeValue.push_back(174); // random + sizeValue.push_back(174); // 174 as random size EXPECT_EQ(store->PutMetaData(sizeKey, sizeValue), -E_INVALID_ARGS); /** @@ -1765,7 +1765,7 @@ void DistributedDBStorageSingleVerNaturalStoreTestCase::DataBaseCommonPutOperate sizeKey.push_back(std::rand()); // random size EXPECT_EQ(connection->Put(option, sizeKey, sizeValue), -E_INVALID_ARGS); sizeKey.pop_back(); - sizeValue.push_back(174); // random size + sizeValue.push_back(174); // 174 as random size EXPECT_EQ(connection->Put(option, sizeKey, sizeValue), -E_INVALID_ARGS); } diff --git a/services/distributeddataservice/libs/distributeddb/test/unittest/common/storage/distributeddb_storage_single_ver_natural_store_testcase.h b/services/distributeddataservice/libs/distributeddb/test/unittest/common/storage/distributeddb_storage_single_ver_natural_store_testcase.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/test/unittest/common/storage/distributeddb_storage_single_ver_upgrade_test.cpp b/services/distributeddataservice/libs/distributeddb/test/unittest/common/storage/distributeddb_storage_single_ver_upgrade_test.cpp old mode 100755 new mode 100644 index 3068c1332b6a4dd20dfebeeeb7819c470d4bbef0..55a31af7e92ac63725e91e7b9dd8c60dd0451984 --- a/services/distributeddataservice/libs/distributeddb/test/unittest/common/storage/distributeddb_storage_single_ver_upgrade_test.cpp +++ b/services/distributeddataservice/libs/distributeddb/test/unittest/common/storage/distributeddb_storage_single_ver_upgrade_test.cpp @@ -246,10 +246,10 @@ namespace { g_mgr.GetKvStore("TestUpgradeNb", option, g_kvNbDelegateCallback); ASSERT_TRUE(g_kvNbDelegatePtr != nullptr); EXPECT_TRUE(g_kvDelegateStatus == OK); - if (secOptCheck == true) { + if (secOptCheck) { CheckSecOpt(secopt); } - if (putCheck == true) { + if (putCheck) { EXPECT_TRUE(g_kvNbDelegatePtr->Put(keyTmp, value) == OK); EXPECT_TRUE(g_kvNbDelegatePtr->Get(keyTmp, valueRead) == OK); } diff --git a/services/distributeddataservice/libs/distributeddb/test/unittest/common/storage/distributeddb_storage_sqlite_single_ver_natural_store_test.cpp b/services/distributeddataservice/libs/distributeddb/test/unittest/common/storage/distributeddb_storage_sqlite_single_ver_natural_store_test.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/test/unittest/common/storage/distributeddb_storage_subscribe_query_test.cpp b/services/distributeddataservice/libs/distributeddb/test/unittest/common/storage/distributeddb_storage_subscribe_query_test.cpp index 80318eef5028f32a6e181545a432456541548884..c44b497b6cee385ed63e5bf7fedd7ed40c18f322 100644 --- a/services/distributeddataservice/libs/distributeddb/test/unittest/common/storage/distributeddb_storage_subscribe_query_test.cpp +++ b/services/distributeddataservice/libs/distributeddb/test/unittest/common/storage/distributeddb_storage_subscribe_query_test.cpp @@ -133,6 +133,7 @@ void CreateAndGetStore(const std::string &storeId, const std::string &schemaStri ASSERT_NE(store, nullptr); } +#ifndef OMIT_FLATBUFFER std::string FbfFileToSchemaString(const std::string &fileName) { std::string filePath = g_resourceDir + "fbs_files_for_ut/" + fileName; @@ -152,6 +153,7 @@ std::string FbfFileToSchemaString(const std::string &fileName) LOGE("[FbfFileToSchemaString] read file failed path : %s", filePath.c_str()); return ""; } +#endif void CheckDataNumByKey(const std::string &storeId, const Key& key, size_t expSize) { @@ -273,6 +275,7 @@ HWTEST_F(DistributedDBStorageSubscribeQueryTest, CheckAndInitQueryCondition001, KvDBManager::ReleaseDatabaseConnection(conn); } +#ifndef OMIT_FLATBUFFER /** * @tc.name: CheckAndInitQueryCondition002 * @tc.desc: Check the condition always illegal with flatbuffer schema @@ -309,6 +312,7 @@ HWTEST_F(DistributedDBStorageSubscribeQueryTest, CheckAndInitQueryCondition002, RefObject::KillAndDecObjRef(store); KvDBManager::ReleaseDatabaseConnection(conn); } +#endif /** * @tc.name: CheckAndInitQueryCondition003 diff --git a/services/distributeddataservice/libs/distributeddb/test/unittest/common/storage/distributeddb_storage_transaction_data_test.cpp b/services/distributeddataservice/libs/distributeddb/test/unittest/common/storage/distributeddb_storage_transaction_data_test.cpp old mode 100755 new mode 100644 index ab414c0d204e1d00f4b239257447153c0ccf4a86..f595b4d2f4621f408a42dd63054447aff1ef9d7b --- a/services/distributeddataservice/libs/distributeddb/test/unittest/common/storage/distributeddb_storage_transaction_data_test.cpp +++ b/services/distributeddataservice/libs/distributeddb/test/unittest/common/storage/distributeddb_storage_transaction_data_test.cpp @@ -95,7 +95,7 @@ static void ValueEqual(const Value &read, const Value &origin) static int RunSyncMergeForOneCommit(std::vector &entries) { MultiVerCommitNode multiVerCommit; - multiVerCommit.commitId.resize(20); // commit id size + multiVerCommit.commitId.resize(20); // 20 as commit id size RAND_bytes(multiVerCommit.commitId.data(), 20); multiVerCommit.deviceInfo = DBCommon::TransferHashString("deviceB") + "deviceB1"; diff --git a/services/distributeddataservice/libs/distributeddb/test/unittest/common/storage/distributeddb_storage_transaction_record_test.cpp b/services/distributeddataservice/libs/distributeddb/test/unittest/common/storage/distributeddb_storage_transaction_record_test.cpp old mode 100755 new mode 100644 index 2b25f36625397b1b2f20975f67a33bde33ddef94..4d0814b1a2bffa06326746137aef188af94e0b1e --- a/services/distributeddataservice/libs/distributeddb/test/unittest/common/storage/distributeddb_storage_transaction_record_test.cpp +++ b/services/distributeddataservice/libs/distributeddb/test/unittest/common/storage/distributeddb_storage_transaction_record_test.cpp @@ -73,7 +73,9 @@ void DistributedDBStorageTransactionRecordTest::TearDown(void) g_transaction = nullptr; } - remove(g_storeDir.c_str()); + if (remove(g_storeDir.c_str()) != 0) { + LOGE("remove db failed, errno:%d", errno); + } } /** diff --git a/services/distributeddataservice/libs/distributeddb/test/unittest/common/storage/multi_ver_vacuum_executor_stub.cpp b/services/distributeddataservice/libs/distributeddb/test/unittest/common/storage/multi_ver_vacuum_executor_stub.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/test/unittest/common/storage/multi_ver_vacuum_executor_stub.h b/services/distributeddataservice/libs/distributeddb/test/unittest/common/storage/multi_ver_vacuum_executor_stub.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/test/unittest/common/syncer/distributeddb_ability_sync_test.cpp b/services/distributeddataservice/libs/distributeddb/test/unittest/common/syncer/distributeddb_ability_sync_test.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/test/unittest/common/syncer/distributeddb_anti_dos_sync_test.cpp b/services/distributeddataservice/libs/distributeddb/test/unittest/common/syncer/distributeddb_anti_dos_sync_test.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/test/unittest/common/syncer/distributeddb_communicator_proxy_test.cpp b/services/distributeddataservice/libs/distributeddb/test/unittest/common/syncer/distributeddb_communicator_proxy_test.cpp index b3590ba985ea1154d4baa87130d6cebc52297703..2706f6154fb7f7371a16da051c8cceea5d41a7b8 100644 --- a/services/distributeddataservice/libs/distributeddb/test/unittest/common/syncer/distributeddb_communicator_proxy_test.cpp +++ b/services/distributeddataservice/libs/distributeddb/test/unittest/common/syncer/distributeddb_communicator_proxy_test.cpp @@ -104,12 +104,13 @@ void DistributedDBCommunicatorProxyTest::SetUp(void) */ KvStoreNbDelegate::Option option; g_mgr.GetKvStore(STORE_ID, option, g_kvDelegateCallback); + std::string identifier = g_mgr.GetKvStoreIdentifier(USER_ID, APP_ID, STORE_ID); ASSERT_TRUE(g_kvDelegateStatus == OK); ASSERT_TRUE(g_kvDelegatePtr != nullptr); commProxy_ = new (std::nothrow) CommunicatorProxy(); ASSERT_TRUE(commProxy_ != nullptr); commProxy_->SetMainCommunicator(&mainComm_); - commProxy_->SetEqualCommunicator(&extComm_, { DEVICE_C }); + commProxy_->SetEqualCommunicator(&extComm_, identifier, { DEVICE_C }); } void DistributedDBCommunicatorProxyTest::TearDown(void) @@ -309,7 +310,7 @@ HWTEST_F(DistributedDBCommunicatorProxyTest, SendMessage001, TestSize.Level1) * @tc.steps: step1. Call SendMessage from CommProxy with param DEVICE_B. * @tc.expected: step1. MainComm's SendMessage willed called and return E_OK. */ - SendConfig conf = {true, 0}; + SendConfig conf = {true, false, 0}; EXPECT_CALL(mainComm_, SendMessage(DEVICE_B, _, _, _)).WillOnce(Return(E_OK)); EXPECT_EQ(commProxy_->SendMessage(DEVICE_B, nullptr, conf, nullptr), E_OK); @@ -323,7 +324,7 @@ HWTEST_F(DistributedDBCommunicatorProxyTest, SendMessage001, TestSize.Level1) /** * @tc.name: Get timeout time 001 - * @tc.desc: Test get timout called from CommunicatorProxy. + * @tc.desc: Test get timeout called from CommunicatorProxy. * @tc.type: FUNC * @tc.require: AR000F4GVG * @tc.author: xushaohua diff --git a/services/distributeddataservice/libs/distributeddb/test/unittest/common/syncer/distributeddb_mock_sync_module_test.cpp b/services/distributeddataservice/libs/distributeddb/test/unittest/common/syncer/distributeddb_mock_sync_module_test.cpp index f292d7878737ea4d62c618cbe35066de84a88c82..82478d8fdf5664b420dc00d0c0eda8cbe099ba4e 100644 --- a/services/distributeddataservice/libs/distributeddb/test/unittest/common/syncer/distributeddb_mock_sync_module_test.cpp +++ b/services/distributeddataservice/libs/distributeddb/test/unittest/common/syncer/distributeddb_mock_sync_module_test.cpp @@ -23,6 +23,9 @@ #include "mock_single_ver_data_sync.h" #include "mock_single_ver_state_machine.h" #include "mock_sync_task_context.h" +#include "single_ver_kv_syncer.h" +#include "single_ver_relational_sync_task_context.h" +#include "virtual_communicator_aggregator.h" #include "virtual_single_ver_sync_db_Interface.h" #ifdef DATA_SYNC_CHECK_003 #include "virtual_relational_ver_sync_db_interface.h" @@ -194,6 +197,34 @@ HWTEST_F(DistributedDBMockSyncModuleTest, StateMachineCheck005, TestSize.Level1) } } +/** + * @tc.name: StateMachineCheck006 + * @tc.desc: Test machine exec next task when queue not empty to empty. + * @tc.type: FUNC + * @tc.require: AR000CCPOM + * @tc.author: zhangqiquan + */ +HWTEST_F(DistributedDBMockSyncModuleTest, StateMachineCheck006, TestSize.Level1) +{ + MockSingleVerStateMachine stateMachine; + MockSyncTaskContext syncTaskContext; + MockCommunicator communicator; + VirtualSingleVerSyncDBInterface dbSyncInterface; + Init(stateMachine, syncTaskContext, communicator, dbSyncInterface); + + EXPECT_CALL(syncTaskContext, IsTargetQueueEmpty()) + .WillOnce(Return(false)) + .WillOnce(Return(true)); + EXPECT_CALL(syncTaskContext, IsCurrentSyncTaskCanBeSkipped()) + .WillRepeatedly(Return(syncTaskContext.CallIsCurrentSyncTaskCanBeSkipped())); + EXPECT_CALL(syncTaskContext, MoveToNextTarget()).WillOnce(Return()); + // we expect machine dont change context status when queue not empty + EXPECT_CALL(syncTaskContext, SetOperationStatus(_)).WillOnce(Return()); + EXPECT_CALL(syncTaskContext, SetTaskExecStatus(_)).WillOnce(Return()); + + EXPECT_EQ(stateMachine.CallExecNextTask(), -E_NO_SYNC_TASK); +} + /** * @tc.name: DataSyncCheck001 * @tc.desc: Test dataSync recv error ack. @@ -247,7 +278,7 @@ HWTEST_F(DistributedDBMockSyncModuleTest, DataSyncCheck003, TestSize.Level1) MockCommunicator communicator; std::shared_ptr metadata = std::static_pointer_cast(mockMetadata); mockDataSync.Initialize(&storage, &communicator, metadata, "deviceId"); - + DistributedDB::Message *message = new(std::nothrow) DistributedDB::Message(); ASSERT_TRUE(message != nullptr); DataAckPacket packet; @@ -285,7 +316,7 @@ HWTEST_F(DistributedDBMockSyncModuleTest, AutoLaunchCheck001, TestSize.Level1) mockAutoLaunch.SetAutoLaunchItem(id, userId, item); EXPECT_CALL(mockAutoLaunch, TryCloseConnection(_)).WillOnce(Return()); /** - * @tc.steps: step2. send close singal to simulate a connection was unused in 1 min + * @tc.steps: step2. send close signal to simulate a connection was unused in 1 min * @tc.expected: 10 thread try to close the connection and one thread close success */ const int loopCount = 10; @@ -354,7 +385,7 @@ HWTEST_F(DistributedDBMockSyncModuleTest, AbilitySync001, TestSize.Level1) { MockSyncTaskContext syncTaskContext; AbilitySync abilitySync; - + DistributedDB::Message *message = new(std::nothrow) DistributedDB::Message(); ASSERT_TRUE(message != nullptr); AbilitySyncAckPacket packet; @@ -381,7 +412,7 @@ HWTEST_F(DistributedDBMockSyncModuleTest, AbilitySync002, TestSize.Level1) std::shared_ptr metaData = std::make_shared(); metaData->Initialize(&syncDBInterface); abilitySync.Initialize(&comunicator, &syncDBInterface, metaData, "deviceId"); - + /** * @tc.steps: step1. set AbilitySyncAckPacket ackCode is E_OK for pass the ack check */ @@ -392,7 +423,7 @@ HWTEST_F(DistributedDBMockSyncModuleTest, AbilitySync002, TestSize.Level1) packet.SetSoftwareVersion(SOFTWARE_VERSION_CURRENT); message->SetCopiedObject(packet); /** - * @tc.steps: step1. set syncDBInterface busy for save data return -E_BUSY + * @tc.steps: step2. set syncDBInterface busy for save data return -E_BUSY */ syncDBInterface.SetBusy(true); SyncStrategy mockStrategy = {true, false, false}; @@ -400,4 +431,60 @@ HWTEST_F(DistributedDBMockSyncModuleTest, AbilitySync002, TestSize.Level1) EXPECT_EQ(abilitySync.AckRecv(message, &syncTaskContext), -E_BUSY); delete message; EXPECT_EQ(syncTaskContext.GetTaskErrCode(), -E_BUSY); +} + +/** + * @tc.name: AbilitySync002 + * @tc.desc: Test abilitySync when offline. + * @tc.type: FUNC + * @tc.require: AR000CCPOM + * @tc.author: zhangqiquan + */ +HWTEST_F(DistributedDBMockSyncModuleTest, AbilitySync003, TestSize.Level1) +{ + /** + * @tc.steps: step1. set table TEST is permitSync + */ + SingleVerRelationalSyncTaskContext *context = new (std::nothrow) SingleVerRelationalSyncTaskContext(); + ASSERT_NE(context, nullptr); + RelationalSyncStrategy strategy; + const std::string tableName = "TEST"; + strategy[tableName] = {true, true, true}; + context->SetRelationalSyncStrategy(strategy); + QuerySyncObject query; + query.SetTableName(tableName); + /** + * @tc.steps: step2. set table is need reset ability sync but it still permit sync + */ + context->SetIsNeedResetAbilitySync(true); + EXPECT_EQ(context->GetSyncStrategy(query).permitSync, true); + /** + * @tc.steps: step3. set table is schema change now it dont permit sync + */ + context->SchemaChange(); + EXPECT_EQ(context->GetSyncStrategy(query).permitSync, false); + RefObject::KillAndDecObjRef(context); +} + +/** + * @tc.name: SyncLifeTest001 + * @tc.desc: Test syncer alive when thread still exist. + * @tc.type: FUNC + * @tc.require: AR000CCPOM + * @tc.author: zhangqiquan + */ +HWTEST_F(DistributedDBMockSyncModuleTest, SyncLifeTest001, TestSize.Level3) +{ + std::shared_ptr syncer = std::make_shared(); + VirtualCommunicatorAggregator *virtualCommunicatorAggregator = new VirtualCommunicatorAggregator(); + RuntimeContext::GetInstance()->SetCommunicatorAggregator(virtualCommunicatorAggregator); + VirtualSingleVerSyncDBInterface *syncDBInterface = new VirtualSingleVerSyncDBInterface(); + syncer->Initialize(syncDBInterface, true); + syncer->EnableAutoSync(true); + for (int i = 0; i < 1000; i++) { // trigger 1000 times auto sync check + syncer->LocalDataChanged(SQLITE_GENERAL_NS_PUT_EVENT); + } + syncer = nullptr; + RuntimeContext::GetInstance()->SetCommunicatorAggregator(nullptr); + delete syncDBInterface; } \ No newline at end of file diff --git a/services/distributeddataservice/libs/distributeddb/test/unittest/common/syncer/distributeddb_multi_ver_p2p_sync_test.cpp b/services/distributeddataservice/libs/distributeddb/test/unittest/common/syncer/distributeddb_multi_ver_p2p_sync_test.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/test/unittest/common/syncer/distributeddb_relational_ver_p2p_sync_test.cpp b/services/distributeddataservice/libs/distributeddb/test/unittest/common/syncer/distributeddb_relational_ver_p2p_sync_test.cpp index 69693babb9f83d77148a3ac70b7912ce981321fe..37d41afcf67ee78e652152097c2613668edd7883 100644 --- a/services/distributeddataservice/libs/distributeddb/test/unittest/common/syncer/distributeddb_relational_ver_p2p_sync_test.cpp +++ b/services/distributeddataservice/libs/distributeddb/test/unittest/common/syncer/distributeddb_relational_ver_p2p_sync_test.cpp @@ -91,7 +91,6 @@ namespace { { static std::map typeMap = { {StorageType::STORAGE_TYPE_INTEGER, "INT"}, - {StorageType::STORAGE_TYPE_BOOL, "BOOL"}, {StorageType::STORAGE_TYPE_REAL, "DOUBLE"}, {StorageType::STORAGE_TYPE_TEXT, "TEXT"}, {StorageType::STORAGE_TYPE_BLOB, "BLOB"} @@ -166,13 +165,6 @@ namespace { void BindValue(const DataValue &item, sqlite3_stmt *stmt, int col) { switch (item.GetType()) { - case StorageType::STORAGE_TYPE_BOOL: { - bool boolData = false; - (void)item.GetBool(boolData); - EXPECT_EQ(sqlite3_bind_int(stmt, col, boolData), SQLITE_OK); - break; - } - case StorageType::STORAGE_TYPE_INTEGER: { int64_t intData = 0; (void)item.GetInt64(intData); @@ -238,11 +230,6 @@ namespace { dataValue.ResetValue(); } - void SetBool(DataValue &dataValue) - { - dataValue = false; - } - void SetInt64(DataValue &dataValue) { dataValue = INT64_MAX; @@ -269,7 +256,6 @@ namespace { { static std::map typeMapFunction = { {StorageType::STORAGE_TYPE_NULL, &SetNull}, - {StorageType::STORAGE_TYPE_BOOL, &SetBool}, {StorageType::STORAGE_TYPE_INTEGER, &SetInt64}, {StorageType::STORAGE_TYPE_REAL, &SetDouble}, {StorageType::STORAGE_TYPE_TEXT, &SetText}, @@ -305,10 +291,9 @@ namespace { fieldInfoList.push_back(columnThird); } - void BlockSync(const std::string &tableName, SyncMode syncMode, DBStatus exceptStatus, + void BlockSync(const Query &query, SyncMode syncMode, DBStatus exceptStatus, const std::vector &devices) { - Query query = Query::Select(tableName); std::map> statusMap; SyncStatusCallback callBack = [&statusMap]( const std::map> &devicesMap) { @@ -323,6 +308,13 @@ namespace { } } + void BlockSync(const std::string &tableName, SyncMode syncMode, DBStatus exceptStatus, + const std::vector &devices) + { + Query query = Query::Select(tableName); + BlockSync(query, syncMode, exceptStatus, devices); + } + void BlockSync(SyncMode syncMode, DBStatus exceptStatus, const std::vector &devices) { BlockSync(g_tableName, syncMode, exceptStatus, devices); @@ -404,7 +396,7 @@ namespace { } void PrepareBasicTable(const std::string &tableName, std::vector &fieldInfoList, - std::vector remoteDeviceVec) + std::vector &remoteDeviceVec, bool createDistributedTable = true) { sqlite3 *db = nullptr; EXPECT_EQ(GetDB(db), SQLITE_OK); @@ -420,8 +412,9 @@ namespace { for (auto &dev : remoteDeviceVec) { dev->SetTableInfo(tableInfo); } - - EXPECT_EQ(g_rdbDelegatePtr->CreateDistributedTable(tableName), OK); + if (createDistributedTable) { + EXPECT_EQ(g_rdbDelegatePtr->CreateDistributedTable(tableName), OK); + } sqlite3_close(db); } @@ -435,9 +428,10 @@ namespace { } void PrepareVirtualEnvironment(std::map &dataMap, const std::string &tableName, - std::vector &fieldInfoList, std::vector remoteDeviceVec) + std::vector &fieldInfoList, std::vector remoteDeviceVec, + bool createDistributedTable = true) { - PrepareBasicTable(tableName, fieldInfoList, remoteDeviceVec); + PrepareBasicTable(tableName, fieldInfoList, remoteDeviceVec, createDistributedTable); GenerateValue(dataMap, fieldInfoList); VirtualRowData virtualRowData; for (const auto &item : dataMap) { @@ -448,9 +442,9 @@ namespace { } void PrepareVirtualEnvironment(std::map &dataMap, - std::vector remoteDeviceVec) + std::vector remoteDeviceVec, bool createDistributedTable = true) { - PrepareVirtualEnvironment(dataMap, g_tableName, g_fieldInfoList, remoteDeviceVec); + PrepareVirtualEnvironment(dataMap, g_tableName, g_fieldInfoList, remoteDeviceVec, createDistributedTable); } void CheckData(std::map &targetMap, const std::string &tableName, @@ -767,6 +761,39 @@ HWTEST_F(DistributedDBRelationalVerP2PSyncTest, NormalSync005, TestSize.Level0) CheckData(dataMap); } +/** +* @tc.name: Normal Sync 007 +* @tc.desc: Test normal sync for miss query data. +* @tc.type: FUNC +* @tc.require: AR000GK58N +* @tc.author: zhangqiquan +*/ +HWTEST_F(DistributedDBRelationalVerP2PSyncTest, NormalSync007, TestSize.Level1) +{ + std::map dataMap; + PrepareEnvironment(dataMap, {g_deviceB}); + + Query query = Query::Select(g_tableName).EqualTo("NAME", DEFAULT_TEXT); + BlockSync(query, SyncMode::SYNC_MODE_PUSH_ONLY, OK, {DEVICE_B}); + + CheckVirtualData(dataMap); + + sqlite3 *db = nullptr; + EXPECT_EQ(GetDB(db), SQLITE_OK); + std::string sql = "UPDATE TEST_TABLE SET NAME = '' WHERE 1 = 1"; + EXPECT_EQ(SQLiteUtils::ExecuteRawSQL(db, sql), E_OK); + sqlite3_close(db); + + BlockSync(query, SyncMode::SYNC_MODE_PUSH_ONLY, OK, {DEVICE_B}); + + std::vector dataList; + EXPECT_EQ(g_deviceB->GetAllSyncData(g_tableName, dataList), E_OK); + EXPECT_EQ(static_cast(dataList.size()), 1); + for (const auto &item : dataList) { + EXPECT_EQ(item.logInfo.flag, DataItem::REMOTE_DEVICE_DATA_MISS_QUERY); + } +} + /** * @tc.name: Normal Sync 006 * @tc.desc: Test normal pull sync for add data. @@ -1002,7 +1029,7 @@ HWTEST_F(DistributedDBRelationalVerP2PSyncTest, AbilitySync003, TestSize.Level1) * @tc.steps: step2. create table and insert data */ PrepareEnvironment(dataMap, schema, schema, {g_deviceB}); - + /** * @tc.steps: step3. change local table to (BOOL, INTEGER, REAL, TEXT, BLOB) * @tc.expected: sync fail @@ -1019,7 +1046,7 @@ HWTEST_F(DistributedDBRelationalVerP2PSyncTest, AbilitySync003, TestSize.Level1) ASSERT_NE(db, nullptr); std::string alterSql = "ALTER TABLE " + g_tableName + " ADD COLUMN NEW_COLUMN TEXT DEFAULT 'DEFAULT_TEXT'"; EXPECT_EQ(sqlite3_exec(db, alterSql.c_str(), nullptr, nullptr, nullptr), SQLITE_OK); - + EXPECT_EQ(sqlite3_close(db), SQLITE_OK); EXPECT_EQ(g_rdbDelegatePtr->CreateDistributedTable(g_tableName), OK); }); @@ -1028,6 +1055,29 @@ HWTEST_F(DistributedDBRelationalVerP2PSyncTest, AbilitySync003, TestSize.Level1) g_communicatorAggregator->RegOnDispatch(nullptr); } +/** +* @tc.name: Ability Sync 004 +* @tc.desc: Test ability sync failed when one device hasn't distributed table. +* @tc.type: FUNC +* @tc.require: AR000GK58N +* @tc.author: zhangqiquan +*/ +HWTEST_F(DistributedDBRelationalVerP2PSyncTest, AbilitySync004, TestSize.Level1) +{ + std::map dataMap; + PrepareVirtualEnvironment(dataMap, {g_deviceB}, false); + + Query query = Query::Select(g_tableName); + int res = DB_ERROR; + auto callBack = [&res](std::map resMap) { + if (resMap.find("real_device") != resMap.end()) { + res = resMap["real_device"]; + } + }; + EXPECT_EQ(g_deviceB->GenericVirtualDevice::Sync(DistributedDB::SYNC_MODE_PULL_ONLY, query, callBack, true), E_OK); + EXPECT_EQ(res, static_cast(SyncOperation::Status::OP_SCHEMA_INCOMPATIBLE)); +} + /** * @tc.name: WaterMark 001 * @tc.desc: Test sync success after erase waterMark. diff --git a/services/distributeddataservice/libs/distributeddb/test/unittest/common/syncer/distributeddb_single_ver_msg_schedule_test.cpp b/services/distributeddataservice/libs/distributeddb/test/unittest/common/syncer/distributeddb_single_ver_msg_schedule_test.cpp index fabb61c5fda06a98b091df92c7dd5bad9c48fcde..9df55d1bb65c8d80ba25eaa61aa9549aa421e17e 100644 --- a/services/distributeddataservice/libs/distributeddb/test/unittest/common/syncer/distributeddb_single_ver_msg_schedule_test.cpp +++ b/services/distributeddataservice/libs/distributeddb/test/unittest/common/syncer/distributeddb_single_ver_msg_schedule_test.cpp @@ -54,7 +54,7 @@ void DistributedDBSingleVerMsgScheduleTest::TearDown(void) /** * @tc.name: MsgSchedule001 - * @tc.desc: Test MsgSchedule funtion with normal sequenceId + * @tc.desc: Test MsgSchedule function with normal sequenceId * @tc.type: FUNC * @tc.require: * @tc.author: zhuwentao @@ -104,7 +104,7 @@ HWTEST_F(DistributedDBSingleVerMsgScheduleTest, MsgSchedule001, TestSize.Level0) /** * @tc.name: MsgSchedule002 - * @tc.desc: Test MsgSchedule funtion with by low version + * @tc.desc: Test MsgSchedule function with by low version * @tc.type: FUNC * @tc.require: * @tc.author: zhuwentao @@ -147,7 +147,7 @@ HWTEST_F(DistributedDBSingleVerMsgScheduleTest, MsgSchedule002, TestSize.Level0) /** * @tc.name: MsgSchedule003 - * @tc.desc: Test MsgSchedule funtion with cross sessionId + * @tc.desc: Test MsgSchedule function with cross sessionId * @tc.type: FUNC * @tc.require: * @tc.author: zhuwentao @@ -214,7 +214,7 @@ HWTEST_F(DistributedDBSingleVerMsgScheduleTest, MsgSchedule003, TestSize.Level0) /** * @tc.name: MsgSchedule004 - * @tc.desc: Test MsgSchedule funtion with same sessionId with different packetId + * @tc.desc: Test MsgSchedule function with same sessionId with different packetId * @tc.type: FUNC * @tc.require: * @tc.author: zhuwentao @@ -273,7 +273,7 @@ HWTEST_F(DistributedDBSingleVerMsgScheduleTest, MsgSchedule004, TestSize.Level0) /** * @tc.name: MsgSchedule005 - * @tc.desc: Test MsgSchedule funtion with same sessionId with different packetId + * @tc.desc: Test MsgSchedule function with same sessionId with different packetId * @tc.type: FUNC * @tc.require: * @tc.author: zhuwentao @@ -330,7 +330,7 @@ HWTEST_F(DistributedDBSingleVerMsgScheduleTest, MsgSchedule005, TestSize.Level0) /** * @tc.name: MsgSchedule006 - * @tc.desc: Test MsgSchedule funtion with same sessionId and same sequenceId and packetId + * @tc.desc: Test MsgSchedule function with same sessionId and same sequenceId and packetId * @tc.type: FUNC * @tc.require: * @tc.author: zhuwentao @@ -396,7 +396,7 @@ HWTEST_F(DistributedDBSingleVerMsgScheduleTest, MsgSchedule006, TestSize.Level0) /** * @tc.name: MsgSchedule007 - * @tc.desc: Test MsgSchedule funtion with same sessionId and duplicate sequenceId and low packetId + * @tc.desc: Test MsgSchedule function with same sessionId and duplicate sequenceId and low packetId * @tc.type: FUNC * @tc.require: * @tc.author: zhuwentao diff --git a/services/distributeddataservice/libs/distributeddb/test/unittest/common/syncer/distributeddb_single_ver_multi_user_test.cpp b/services/distributeddataservice/libs/distributeddb/test/unittest/common/syncer/distributeddb_single_ver_multi_user_test.cpp index 4e8f7c454cebb7e4e6a8f9543d38579fee6d1397..a0276873a07a6bb25de8216e33dca4bf5ed4047d 100644 --- a/services/distributeddataservice/libs/distributeddb/test/unittest/common/syncer/distributeddb_single_ver_multi_user_test.cpp +++ b/services/distributeddataservice/libs/distributeddb/test/unittest/common/syncer/distributeddb_single_ver_multi_user_test.cpp @@ -37,6 +37,7 @@ namespace { const std::string DEVICE_B = "deviceB"; const std::string DEVICE_C = "deviceC"; const int WAIT_TIME = 1000; // 1000ms + const int WAIT_3_SECONDS = 3000; KvStoreDelegateManager g_mgr1(APP_ID, USER_ID_1); KvStoreDelegateManager g_mgr2(APP_ID, USER_ID_2); @@ -624,4 +625,186 @@ HWTEST_F(DistributedDBSingleVerMultiUserTest, MultiUser007, TestSize.Level0) std::this_thread::sleep_for(std::chrono::milliseconds(1)); EXPECT_TRUE(g_kvDelegatePtr1->Rekey(passwd) == OK); CloseStore(); +} + +/** + * @tc.name: MultiUser008 + * @tc.desc: test NotifyUserChanged and block sync concurrently + * @tc.type: FUNC + * @tc.require: AR000E8S2T + * @tc.author: zhuwentao + */ +HWTEST_F(DistributedDBSingleVerMultiUserTest, MultiUser008, TestSize.Level0) +{ + /** + * @tc.steps: step1. set SyncActivationCheckCallback and only userId1 can active + */ + g_mgr1.SetSyncActivationCheckCallback(g_syncActivationCheckCallback2); + /** + * @tc.steps: step2. openstore1 in dual tuple sync mode and openstore2 in normal sync mode + * @tc.expected: step2. only user2 sync mode is active + */ + + OpenStore1(true); + OpenStore2(true); + /** + * @tc.steps: step3. set SyncActivationCheckCallback and only userId2 can active + */ + g_mgr1.SetSyncActivationCheckCallback(g_syncActivationCheckCallback1); + + /** + * @tc.steps: step4. call NotifyUserChanged and block sync db concurrently + * @tc.expected: step4. return OK + */ + CipherPassword passwd; + thread subThread([&]() { + std::this_thread::sleep_for(std::chrono::milliseconds(5)); + EXPECT_TRUE(KvStoreDelegateManager::NotifyUserChanged() == OK); + }); + subThread.detach(); + /** + * @tc.steps: step5. deviceA call sync and wait + * @tc.expected: step5. sync should return OK. + */ + std::map result; + std::vector devices; + devices.push_back(g_deviceB->GetDeviceId()); + DBStatus status = g_tool.SyncTest(g_kvDelegatePtr1, devices, SYNC_MODE_PUSH_ONLY, result, true); + ASSERT_TRUE(status == OK); + + /** + * @tc.expected: step6. onComplete should be called, and status is USER_CHANGED + */ + ASSERT_TRUE(result.size() == devices.size()); + for (const auto &pair : result) { + LOGD("dev %s, status %d", pair.first.c_str(), pair.second); + EXPECT_TRUE(pair.second == USER_CHANGED); + } + CloseStore(); +} + +/** + * @tc.name: MultiUser009 + * @tc.desc: test NotifyUserChanged and non-block sync concurrently + * @tc.type: FUNC + * @tc.require: AR000E8S2T + * @tc.author: zhuwentao + */ +HWTEST_F(DistributedDBSingleVerMultiUserTest, MultiUser009, TestSize.Level0) +{ + /** + * @tc.steps: step1. set SyncActivationCheckCallback and only userId1 can active + */ + g_mgr1.SetSyncActivationCheckCallback(g_syncActivationCheckCallback2); + /** + * @tc.steps: step2. openstore1 in dual tuple sync mode and openstore2 in normal sync mode + * @tc.expected: step2. only user2 sync mode is active + */ + + OpenStore1(true); + OpenStore2(true); + /** + * @tc.steps: step3. set SyncActivationCheckCallback and only userId2 can active + */ + g_mgr1.SetSyncActivationCheckCallback(g_syncActivationCheckCallback1); + + /** + * @tc.steps: step4. call NotifyUserChanged and block sync db concurrently + * @tc.expected: step4. return OK + */ + CipherPassword passwd; + thread subThread([&]() { + std::this_thread::sleep_for(std::chrono::milliseconds(5)); + EXPECT_TRUE(KvStoreDelegateManager::NotifyUserChanged() == OK); + }); + subThread.detach(); + /** + * @tc.steps: step5. deviceA call sync and wait + * @tc.expected: step5. sync should return OK. + */ + std::map result; + std::vector devices; + devices.push_back(g_deviceB->GetDeviceId()); + DBStatus status = g_tool.SyncTest(g_kvDelegatePtr1, devices, SYNC_MODE_PUSH_ONLY, result, false); + ASSERT_TRUE(status == OK); + + /** + * @tc.expected: step6. onComplete should be called, and status is USER_CHANGED + */ + ASSERT_TRUE(result.size() == devices.size()); + for (const auto &pair : result) { + LOGD("dev %s, status %d", pair.first.c_str(), pair.second); + EXPECT_TRUE(pair.second == USER_CHANGED); + } + CloseStore(); +} + +/** + * @tc.name: MultiUser010 + * @tc.desc: test NotifyUserChanged and non-block sync with multi devices concurrently + * @tc.type: FUNC + * @tc.require: AR000E8S2T + * @tc.author: zhuwentao + */ +HWTEST_F(DistributedDBSingleVerMultiUserTest, MultiUser010, TestSize.Level3) +{ + /** + * @tc.steps: step1. set SyncActivationCheckCallback and only userId1 can active + */ + g_mgr1.SetSyncActivationCheckCallback(g_syncActivationCheckCallback2); + /** + * @tc.steps: step2. openstore1 and openstore2 in dual tuple sync mode + * @tc.expected: step2. only userId1 sync mode is active + */ + + OpenStore1(true); + OpenStore2(true); + /** + * @tc.steps: step3. set SyncActivationCheckCallback and only userId2 can active + */ + g_mgr1.SetSyncActivationCheckCallback(g_syncActivationCheckCallback1); + /** + * @tc.steps: step4. deviceA put {k1, v1} + */ + Key key = {'1'}; + Value value = {'1'}; + ASSERT_TRUE(g_kvDelegatePtr1->Put(key, value) == OK); + + /** + * @tc.steps: step5. deviceB set sava data dely 5s + */ + g_deviceC->SetSaveDataDelayTime(WAIT_3_SECONDS); + /** + * @tc.steps: step6. call NotifyUserChanged and block sync db concurrently + * @tc.expected: step6. return OK + */ + CipherPassword passwd; + thread subThread([&]() { + std::this_thread::sleep_for(std::chrono::milliseconds(1000)); + EXPECT_TRUE(KvStoreDelegateManager::NotifyUserChanged() == OK); + }); + subThread.detach(); + /** + * @tc.steps: step7. deviceA call sync and wait + * @tc.expected: step7. sync should return OK. + */ + std::map result; + std::vector devices = {g_deviceB->GetDeviceId(), g_deviceC->GetDeviceId()}; + DBStatus status = g_tool.SyncTest(g_kvDelegatePtr1, devices, SYNC_MODE_PUSH_ONLY, result, false); + ASSERT_TRUE(status == OK); + + /** + * @tc.expected: step8. onComplete should be called, and status is USER_CHANGED + */ + ASSERT_TRUE(result.size() == devices.size()); + for (const auto &pair : result) { + LOGD("dev %s, status %d", pair.first.c_str(), pair.second); + if (pair.first == g_deviceB->GetDeviceId()) { + EXPECT_TRUE(pair.second == OK); + } else { + EXPECT_TRUE(pair.second == USER_CHANGED); + } + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_3_SECONDS)); + CloseStore(); } \ No newline at end of file diff --git a/services/distributeddataservice/libs/distributeddb/test/unittest/common/syncer/distributeddb_single_ver_p2p_sync_check_test.cpp b/services/distributeddataservice/libs/distributeddb/test/unittest/common/syncer/distributeddb_single_ver_p2p_sync_check_test.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/test/unittest/common/syncer/distributeddb_single_ver_p2p_sync_test.cpp b/services/distributeddataservice/libs/distributeddb/test/unittest/common/syncer/distributeddb_single_ver_p2p_sync_test.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/test/unittest/common/syncer/distributeddb_syncer_device_manager_test.cpp b/services/distributeddataservice/libs/distributeddb/test/unittest/common/syncer/distributeddb_syncer_device_manager_test.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/test/unittest/common/syncer/distributeddb_time_sync_test.cpp b/services/distributeddataservice/libs/distributeddb/test/unittest/common/syncer/distributeddb_time_sync_test.cpp old mode 100755 new mode 100644 index 42bec439f926a01dbef620f35b549ceb673cbe1a..293d95c0420283e3b6dd63c7df02616dedb4207a --- a/services/distributeddataservice/libs/distributeddb/test/unittest/common/syncer/distributeddb_time_sync_test.cpp +++ b/services/distributeddataservice/libs/distributeddb/test/unittest/common/syncer/distributeddb_time_sync_test.cpp @@ -346,7 +346,7 @@ HWTEST_F(DistributedDBTimeSyncTest, InvalidMessgeTest001, TestSize.Level0) */ msg->SetMessageId(TIME_SYNC_MESSAGE); msg->SetMessageType(TYPE_REQUEST); - SendConfig conf = {false, 0}; + SendConfig conf = {false, false, 0}; errCode = g_virtualCommunicator->SendMessage(DEVICE_B, msg, conf); EXPECT_TRUE(errCode == -E_INVALID_ARGS); @@ -417,7 +417,7 @@ HWTEST_F(DistributedDBTimeSyncTest, InvalidMessgeTest002, TestSize.Level0) */ msg->SetMessageId(TIME_SYNC_MESSAGE); msg->SetMessageType(TYPE_RESPONSE); - SendConfig conf = {false, 0}; + SendConfig conf = {false, false, 0}; errCode = g_virtualCommunicator->SendMessage(DEVICE_A, msg, conf); EXPECT_TRUE(errCode == -E_INVALID_ARGS); diff --git a/services/distributeddataservice/libs/distributeddb/test/unittest/common/syncer/mock_sync_task_context.h b/services/distributeddataservice/libs/distributeddb/test/unittest/common/syncer/mock_sync_task_context.h index 5b650bc635468bd6f1266cf53af2feda5f18987e..1dfca14ffd500c9f4fc9f5cc1888c0829416cffe 100644 --- a/services/distributeddataservice/libs/distributeddb/test/unittest/common/syncer/mock_sync_task_context.h +++ b/services/distributeddataservice/libs/distributeddb/test/unittest/common/syncer/mock_sync_task_context.h @@ -22,6 +22,11 @@ namespace DistributedDB { class MockSyncTaskContext : public SingleVerKvSyncTaskContext { public: + bool CallIsCurrentSyncTaskCanBeSkipped() + { + return SingleVerKvSyncTaskContext::IsCurrentSyncTaskCanBeSkipped(); + } + MOCK_CONST_METHOD0(GetTimerId, TimerId(void)); MOCK_CONST_METHOD0(IsTargetQueueEmpty, bool(void)); diff --git a/services/distributeddataservice/libs/distributeddb/test/unittest/common/syncer/virtual_multi_ver_sync_db_interface.cpp b/services/distributeddataservice/libs/distributeddb/test/unittest/common/syncer/virtual_multi_ver_sync_db_interface.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/test/unittest/common/syncer/virtual_multi_ver_sync_db_interface.h b/services/distributeddataservice/libs/distributeddb/test/unittest/common/syncer/virtual_multi_ver_sync_db_interface.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/test/unittest/common/syncer/virtual_single_ver_sync_db_Interface.cpp b/services/distributeddataservice/libs/distributeddb/test/unittest/common/syncer/virtual_single_ver_sync_db_Interface.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/test/unittest/common/syncer/virtual_single_ver_sync_db_Interface.h b/services/distributeddataservice/libs/distributeddb/test/unittest/common/syncer/virtual_single_ver_sync_db_Interface.h old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/libs/distributeddb/test/unittest/common/syncer/virtual_time_sync_communicator.cpp b/services/distributeddataservice/libs/distributeddb/test/unittest/common/syncer/virtual_time_sync_communicator.cpp old mode 100755 new mode 100644 diff --git a/services/distributeddataservice/service/config/src/model/directory_config.cpp b/services/distributeddataservice/service/config/src/model/directory_config.cpp index 5cde0ec352d71b1271e79cfa910fc4f464c57b3a..97152be9a27a828f4c17de51707ac8af5561d886 100644 --- a/services/distributeddataservice/service/config/src/model/directory_config.cpp +++ b/services/distributeddataservice/service/config/src/model/directory_config.cpp @@ -44,8 +44,8 @@ bool DirectoryConfig::Marshal(json &node) const bool DirectoryConfig::Unmarshal(const json &node) { bool ret = true; - ret &= GetValue(node, GET_NAME(currentStrategyVersion), currentStrategyVersion); - ret &= GetValue(node, GET_NAME(strategy), strategy); + ret = GetValue(node, GET_NAME(currentStrategyVersion), currentStrategyVersion) && ret; + ret = GetValue(node, GET_NAME(strategy), strategy) && ret; return ret; } } diff --git a/services/distributeddataservice/service/directory/include/directory_manager.h b/services/distributeddataservice/service/directory/include/directory_manager.h index 433089578a5950aa8f346078ceca8f8a65cb71d9..3227244e89c40c7028908183e100144d875aec8d 100644 --- a/services/distributeddataservice/service/directory/include/directory_manager.h +++ b/services/distributeddataservice/service/directory/include/directory_manager.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef SDB_DIRECTORY_MANAGER_H -#define SDB_DIRECTORY_MANAGER_H +#ifndef DISTRIBUTEDDATAMGR_DIRECTORY_MANAGER_H +#define DISTRIBUTEDDATAMGR_DIRECTORY_MANAGER_H #include #include @@ -91,4 +91,4 @@ private: std::string version_; }; } // namespace OHOS::DistributedKv -#endif // SDB_DIRECTORY_MANAGER_H +#endif // DISTRIBUTEDDATAMGR_DIRECTORY_MANAGER_H diff --git a/services/distributeddataservice/service/directory/include/kvstore_context.h b/services/distributeddataservice/service/directory/include/kvstore_context.h index 27135bd3b8eaa99692e71f3a6cb5741eda2aa55b..c42bb7f217930b659d9c585a9afed3e4046e01c5 100644 --- a/services/distributeddataservice/service/directory/include/kvstore_context.h +++ b/services/distributeddataservice/service/directory/include/kvstore_context.h @@ -13,15 +13,16 @@ * limitations under the License. */ +#ifndef DISTRIBUTEDDATAMGR_KVSTORE_CONTEXT_H +#define DISTRIBUTEDDATAMGR_KVSTORE_CONTEXT_H #include -#ifndef SDB_KVSTORE_CONTEXT_H -#define SDB_KVSTORE_CONTEXT_H +#include "types.h" namespace OHOS::DistributedData { struct ClientContext { std::string userId {}; std::string bundleName {}; std::string dataDir {}; }; -} -#endif // SDB_KVSTORE_CONTEXT_H \ No newline at end of file +} // namespace OHOS::DistributedData +#endif // DISTRIBUTEDDATAMGR_KVSTORE_CONTEXT_H \ No newline at end of file diff --git a/services/distributeddataservice/service/kv/user_delegate.cpp b/services/distributeddataservice/service/kv/user_delegate.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3f35b4ed8ff2721b303e673077689b62cece7829 --- /dev/null +++ b/services/distributeddataservice/service/kv/user_delegate.cpp @@ -0,0 +1,202 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "user_delegate.h" + +#define LOG_TAG "UserDelegate" + +#include "account_delegate.h" +#include "communication_provider.h" +#include "device_kvstore_impl.h" +#include "executor_factory.h" +#include "kvstore_meta_manager.h" +#include "log_print.h" +#include "os_account_manager.h" + +namespace OHOS::DistributedData { +using OHOS::AppDistributedKv::CommunicationProvider; +using namespace OHOS::DistributedKv; +using namespace OHOS::AccountSA; +std::vector UserDelegate::GetLocalUserStatus() +{ + ZLOGI("begin"); + auto deviceInfo = CommunicationProvider::GetInstance().GetLocalDevice(); + if (deviceInfo.deviceId.empty()) { + ZLOGE("failed to get local device id"); + return {}; + } + return GetUsers(deviceInfo.deviceId); +} + +std::vector UserDelegate::GetRemoteUserStatus(const std::string &deviceId) +{ + if (deviceId.empty()) { + ZLOGE("error input device id"); + return {}; + } + return GetUsers(deviceId); +} + +std::vector UserDelegate::GetUsers(const std::string &deviceId) +{ + std::vector userStatus; + if (!deviceUserMap_.Contains(deviceId)) { + LoadFromMeta(deviceId); + } + for (const auto &entry : deviceUserMap_[deviceId]) { + userStatus.emplace_back(entry.first, entry.second); + } + ZLOGI("device:%{public}.10s, users:%{public}s", deviceId.c_str(), Serializable::Marshall(userStatus).c_str()); + return userStatus; +} + +void UserDelegate::DeleteUsers(const std::string &deviceId) +{ + deviceUserMap_.Erase(deviceId); +} + +void UserDelegate::UpdateUsers(const std::string &deviceId, const std::vector &userStatus) +{ + ZLOGI("begin, device:%{public}.10s, users:%{public}u", deviceId.c_str(), userStatus.size()); + deviceUserMap_.ComputeIfPresent(deviceId, [](const auto &key, std::map &userMap) { + for (auto &user : userMap) { + user.second = false; + } + }); + for (auto &user : userStatus) { + deviceUserMap_[deviceId][user.id] = user.isActive; + } + ZLOGI("end, device:%{public}.10s, users:%{public}u", deviceId.c_str(), deviceUserMap_[deviceId].size()); +} + +bool UserDelegate::InitLocalUserMeta() +{ + std::vector osAccountIds = { { 0, true } }; // system user default + auto ret = OsAccountManager::QueryActiveOsAccountIds(osAccountIds); + if (ret != 0 || osAccountIds.empty()) { + ZLOGE("failed to query os accounts, ret:%{public}d", ret); + return false; + } + std::vector userStatus = { { 0, true } }; + for (const auto &user : osAccountIds) { + userStatus.emplace_back(user, true); + } + UserMetaData userMetaData; + userMetaData.deviceId = DeviceKvStoreImpl::GetLocalDeviceId(); + UpdateUsers(userMetaData.deviceId, userStatus); + for (auto &pair : deviceUserMap_[userMetaData.deviceId]) { + userMetaData.users.emplace_back(pair.first, pair.second); + } + + auto &metaDelegate = KvStoreMetaManager::GetInstance().GetMetaKvStore(); + if (metaDelegate == nullptr) { + ZLOGE("GetMetaKvStore return nullptr."); + return false; + } + auto dbKey = UserMetaRow::GetKeyFor(userMetaData.deviceId); + std::string jsonData = UserMetaData::Marshall(userMetaData); + DistributedDB::Value dbValue{ jsonData.begin(), jsonData.end() }; + ret = metaDelegate->Put(dbKey, dbValue); + ZLOGI("put user meta data ret %{public}d", ret); + return ret == DistributedDB::DBStatus::OK; +} + +void UserDelegate::LoadFromMeta(const std::string &deviceId) +{ + auto &metaDelegate = KvStoreMetaManager::GetInstance().GetMetaKvStore(); + if (metaDelegate == nullptr) { + ZLOGE("GetMetaKvStore return nullptr."); + return; + } + + auto dbKey = UserMetaRow::GetKeyFor(deviceId); + DistributedDB::Value dbValue; + auto ret = metaDelegate->Get(dbKey, dbValue); + UserMetaData userMetaData; + ZLOGI("get user meta data ret %{public}d", ret); + if (ret != DistributedDB::DBStatus::OK) { + return; + } + userMetaData.Unmarshall({ dbValue.begin(), dbValue.end() }); + std::map userMap; + for (const auto &user : userMetaData.users) { + userMap[user.id] = user.isActive; + } + deviceUserMap_[deviceId] = userMap; +} + +UserDelegate &UserDelegate::GetInstance() +{ + static UserDelegate instance; + return instance; +} + +void UserDelegate::Init() +{ + KvStoreTask retryTask([this]() { + do { + static constexpr int RETRY_INTERVAL = 500; // millisecond + std::this_thread::sleep_for(std::chrono::milliseconds(RETRY_INTERVAL)); + if (!InitLocalUserMeta()) { + continue; + } + break; + } while (true); + ZLOGI("update user meta ok"); + }); + ExecutorFactory::GetInstance().Execute(std::move(retryTask)); + auto ret = AccountDelegate::GetInstance()->Subscribe(std::make_shared(*this)); + // subscribe user meta in other devices + KvStoreMetaManager::GetInstance().SubscribeMeta(UserMetaRow::KEY_PREFIX, + [this](const std::vector &key, const std::vector &value, CHANGE_FLAG flag) { + UserMetaData metaData; + metaData.Unmarshall({ value.begin(), value.end() }); + ZLOGD("flag:%{public}d, value:%{public}.10s", flag, metaData.deviceId.c_str()); + if (metaData.deviceId == DeviceKvStoreImpl::GetLocalDeviceId()) { + ZLOGD("ignore local device user meta change"); + return; + } + if (flag == CHANGE_FLAG::INSERT || flag == CHANGE_FLAG::UPDATE) { + UpdateUsers(metaData.deviceId, metaData.users); + } else if (flag == CHANGE_FLAG::DELETE) { + DeleteUsers(metaData.deviceId); + } else { + ZLOGD("ignored operation"); + } + }); + ZLOGD("subscribe os account ret:%{public}d", ret); +} + +bool UserDelegate::NotifyUserEvent(const UserDelegate::UserEvent &userEvent) +{ + // update all local user status + return InitLocalUserMeta(); +} + +UserDelegate::LocalUserObserver::LocalUserObserver(UserDelegate &userDelegate) : userDelegate_(userDelegate) +{ +} + +void UserDelegate::LocalUserObserver::OnAccountChanged(const DistributedKv::AccountEventInfo &eventInfo) +{ + ZLOGI("event info:%{public}s, %{public}d", eventInfo.deviceAccountId.c_str(), eventInfo.status); + userDelegate_.NotifyUserEvent({}); // just notify +} + +std::string UserDelegate::LocalUserObserver::Name() +{ + return "user_delegate"; +} +} // namespace OHOS::DistributedData diff --git a/services/distributeddataservice/service/kv/user_delegate.h b/services/distributeddataservice/service/kv/user_delegate.h new file mode 100644 index 0000000000000000000000000000000000000000..75d90a54d68af924548118439df61186af5eeb27 --- /dev/null +++ b/services/distributeddataservice/service/kv/user_delegate.h @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef DISTRIBUTEDDATAMGR_USER_DELEGATE_H +#define DISTRIBUTEDDATAMGR_USER_DELEGATE_H + +#include + +#include "account_delegate.h" +#include "concurrent_map.h" +#include "metadata/user_meta_data.h" +#include "visibility.h" + +namespace OHOS::DistributedData { +using AccountDelegate = DistributedKv::AccountDelegate; +using DistributedData::UserStatus; +class UserDelegate { +public: + struct UserEvent { + int id; + bool isActive; + }; + static UserDelegate &GetInstance(); + + void Init(); + std::vector GetLocalUserStatus(); + std::vector GetRemoteUserStatus(const std::string &deviceId); + bool InitLocalUserMeta(); + +private: + class LocalUserObserver : public AccountDelegate::Observer { + public: + explicit LocalUserObserver(UserDelegate &userDelegate); + void OnAccountChanged(const DistributedKv::AccountEventInfo &eventInfo) override; + std::string Name() override; + + private: + UserDelegate &userDelegate_; + }; + std::vector GetUsers(const std::string &deviceId); + void LoadFromMeta(const std::string &deviceId); + void UpdateUsers(const std::string &deviceId, const std::vector &userStatus); + void DeleteUsers(const std::string &deviceId); + bool NotifyUserEvent(const UserEvent &userEvent); + + // device : { user : isActive } + ConcurrentMap> deviceUserMap_; +}; +} // namespace OHOS::DistributedData + +#endif // DISTRIBUTEDDATAMGR_USER_DELEGATE_H diff --git a/services/distributeddataservice/test/common/distributeddb/include/distributeddb_log_print.h b/services/distributeddataservice/test/common/distributeddb/include/distributeddb_log_print.h index ff00a8f26d5a7a3894799842997e9a8b79e36ae3..7f8a56d2a25090ca91fc86257d7440f79c373f80 100755 --- a/services/distributeddataservice/test/common/distributeddb/include/distributeddb_log_print.h +++ b/services/distributeddataservice/test/common/distributeddb/include/distributeddb_log_print.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -25,25 +25,9 @@ #endif #endif -#if defined USING_LOGCAT_LOGGER - #include -#elif defined _WIN32 - #define USING_PRINTF_LOGGER - #include -#elif defined USING_HILOG_LOGGER - #include "hilog/log.h" -#endif +#include "hilog/log.h" -#if defined USING_LOGCAT_LOGGER - #define MST_LOG(fmt, ...) \ - (void)(__android_log_print(static_cast(ANDROID_LOG_INFO), "DistributedDB[TEST]", \ - "%s: " fmt, __FUNCTION__, ##__VA_ARGS__)) -#elif defined USING_PRINTF_LOGGER - #define MST_LOG(fmt, ...) \ - (void)(std::printf(fmt"\n", ##__VA_ARGS__)) -#elif defined USING_HILOG_LOGGER - static constexpr OHOS::HiviewDFX::HiLogLabel LOG_LABEL = { LOG_CORE, 0xD001630, "DistributedDB[TEST]" }; - #define MST_LOG(fmt, ...) \ - OHOS::HiviewDFX::HiLog::Info(LOG_LABEL, "%s: " fmt, __FUNCTION__, ##__VA_ARGS__) -#endif +static constexpr OHOS::HiviewDFX::HiLogLabel LOG_LABEL = { LOG_CORE, 0xD001630, "DistributedDB[TEST]" }; +#define MST_LOG(fmt, ...) \ + OHOS::HiviewDFX::HiLog::Info(LOG_LABEL, "%s: " fmt, __FUNCTION__, ##__VA_ARGS__) #endif diff --git a/services/distributeddataservice/test/common/distributeddb/include/distributeddb_schema_test_tools.h b/services/distributeddataservice/test/common/distributeddb/include/distributeddb_schema_test_tools.h index 696dfbefea88109f232b013b8abef30b13fccdc0..4ee1bcb1c971e1d90a24b6ee94b7c52fc0536c88 100755 --- a/services/distributeddataservice/test/common/distributeddb/include/distributeddb_schema_test_tools.h +++ b/services/distributeddataservice/test/common/distributeddb/include/distributeddb_schema_test_tools.h @@ -258,10 +258,10 @@ public: ~DistributedDBSchemaTestTools() {} // Delete the copy and assign constructors - DistributedDBSchemaTestTools(const DistributedDBSchemaTestTools &DistributedDBSchemaTestTools) = delete; - DistributedDBSchemaTestTools& operator=(const DistributedDBSchemaTestTools &DistributedDBSchemaTestTools) = delete; - DistributedDBSchemaTestTools(DistributedDBSchemaTestTools &&DistributedDBSchemaTestTools) = delete; - DistributedDBSchemaTestTools& operator=(DistributedDBSchemaTestTools &&DistributedDBSchemaTestTools) = delete; + DistributedDBSchemaTestTools(const DistributedDBSchemaTestTools &testTool) = delete; + DistributedDBSchemaTestTools& operator=(const DistributedDBSchemaTestTools &testTool) = delete; + DistributedDBSchemaTestTools(DistributedDBSchemaTestTools &&testTool) = delete; + DistributedDBSchemaTestTools& operator=(DistributedDBSchemaTestTools &&testTool) = delete; static DistributedDB::Entry GenerateFixedLenJsonSchemaRecord(const unsigned long serialNo, const EntrySize &entrySize, const uint8_t keyFilledChr, const uint8_t valueFilledChr); static std::vector GenerateFixedJsonSchemaRecords( diff --git a/services/distributeddataservice/test/common/distributeddb/src/distributed_rdb_tools.cpp b/services/distributeddataservice/test/common/distributeddb/src/distributed_rdb_tools.cpp index fae08163e170eaa7eca056e45d3285a89e15a562..91d6dc8bebdb5943e65cf5c361f6cfb9f5013491 100644 --- a/services/distributeddataservice/test/common/distributeddb/src/distributed_rdb_tools.cpp +++ b/services/distributeddataservice/test/common/distributeddb/src/distributed_rdb_tools.cpp @@ -99,7 +99,7 @@ DBStatus DistributedRdbTools::GetOpenStoreStatus(const RelatetionalStoreManager if (delegate == nullptr) { MST_LOG("%s GetRdbStore failed! delegate nullptr.", TAG.c_str()); } - retrun status; + return status; } DBStatus DistributedRdbTools::GetCreateDistributedTableStatus(const RelatetionalStoreDelegate *&delegate, @@ -110,7 +110,7 @@ DBStatus DistributedRdbTools::GetCreateDistributedTableStatus(const Relatetional return DBStatus::DB_ERROR; } DBStatus status = delegate->CreateDistributedTable(tableName); - retrun status; + return status; } DBStatus DistributedRdbTools::CloseStore(const RelatetionalStoreDelegate *&delegate) diff --git a/services/distributeddataservice/test/common/distributeddb/src/distributed_test_sysinfo.cpp b/services/distributeddataservice/test/common/distributeddb/src/distributed_test_sysinfo.cpp index aa924ab9e8b8a30be8c53b8cbda2dc8174298418..e5be30527f0368d1a649267cfe26491e01516268 100755 --- a/services/distributeddataservice/test/common/distributeddb/src/distributed_test_sysinfo.cpp +++ b/services/distributeddataservice/test/common/distributeddb/src/distributed_test_sysinfo.cpp @@ -223,24 +223,34 @@ uint64_t DistributedTestSysInfo::GetSecondMemFree() const #elif defined RUNNING_ON_WIN void DistributedTestSysInfo::GetSysMemOccpy(SeqNo seqNo) { + (void)seqNo; } void DistributedTestSysInfo::GetSysCpuUsage(SeqNo seqNo, uint64_t microSeconds) { + (void)seqNo; + (void)microSeconds; } float DistributedTestSysInfo::ReadSysValFromFile(const std::string &filePath) { + (void)filePath; return 0.0f; } float DistributedTestSysInfo::GetSysMeanCurrentVal( const std::string &filePath, int totalCount, uint64_t microSeconds) { + (void)filePath; + (void)totalCount; + (void)microSeconds; return 0.0f; } void DistributedTestSysInfo::GetSysCurrentPower(SeqNo seqNo, int totalCount, uint64_t microSeconds) { + (void)seqNo; + (void)totalCount; + (void)microSeconds; } uint64_t DistributedTestSysInfo::GetFirstMemFree() const diff --git a/services/distributeddataservice/test/common/distributeddb/src/distributed_test_tools.cpp b/services/distributeddataservice/test/common/distributeddb/src/distributed_test_tools.cpp index f65e798239e93a8de7b506edde277f0d330e1131..64f7a30056025ab4aef93eda65e278f0fbbf213c 100755 --- a/services/distributeddataservice/test/common/distributeddb/src/distributed_test_tools.cpp +++ b/services/distributeddataservice/test/common/distributeddb/src/distributed_test_tools.cpp @@ -414,6 +414,7 @@ void CopyFile(const string &srcFile, const string &destFile) FILE *pOut = fopen(destFile.c_str(), "w"); if (pOut == nullptr) { perror("pOut"); + fclose(pIn); return; } @@ -435,6 +436,8 @@ void CopyDir(const string &srcDir, const string &destDir, const int authRight) MST_LOG("[CopyDir] SetDir(%s) failed(%d)!", destFullDir.c_str(), errno); return; } + } else { + closedir(dpDest); } string path = srcFullDir; if (srcFullDir.back() != '/') { @@ -446,7 +449,6 @@ void CopyDir(const string &srcDir, const string &destDir, const int authRight) DIR *dpSrc = opendir(path.c_str()); if (dpSrc == nullptr) { - closedir(dpDest); MST_LOG("[CopyDir] please make sure srcDir(%s) is valid.", srcDir.c_str()); return; } @@ -466,7 +468,6 @@ void CopyDir(const string &srcDir, const string &destDir, const int authRight) } } closedir(dpSrc); - closedir(dpDest); MST_LOG("[CopyDir] copy file from %s to %s successfully.", srcDir.c_str(), destDir.c_str()); } diff --git a/services/distributeddataservice/test/common/distributeddb/src/kv_store_observer_impl.cpp b/services/distributeddataservice/test/common/distributeddb/src/kv_store_observer_impl.cpp index 60bf9f9ba605f1bc9df5f65370aea0dfa88da48e..ecc20842564bbb66e4790712772533ec6f38e836 100644 --- a/services/distributeddataservice/test/common/distributeddb/src/kv_store_observer_impl.cpp +++ b/services/distributeddataservice/test/common/distributeddb/src/kv_store_observer_impl.cpp @@ -114,7 +114,7 @@ void KvStoreObserverImpl::WaitUntilReachChangeCount(unsigned int countGoal, uint } // Change count has not reach countGoal auto waitChangeFunc = [this, countGoal]()->bool { - MST_LOG("############################ realChanged=%d, countGoal=%d", this->changed_, countGoal); + MST_LOG("############################ realChanged=%d, countGoal=%u", this->changed_, countGoal); return this->changed_ >= countGoal; }; MST_LOG("############################ BEGIN ############################"); diff --git a/services/distributeddataservice/test/moduletest/common/distributeddb/src/distributeddb_kv_crud_test.cpp b/services/distributeddataservice/test/moduletest/common/distributeddb/src/distributeddb_kv_crud_test.cpp index dd0441762e0d37db9ce8657ec4ad87c36f1e6d70..16b064a468f176ef4e67f18562db2bd0d3ff9a89 100755 --- a/services/distributeddataservice/test/moduletest/common/distributeddb/src/distributeddb_kv_crud_test.cpp +++ b/services/distributeddataservice/test/moduletest/common/distributeddb/src/distributeddb_kv_crud_test.cpp @@ -458,7 +458,7 @@ HWTEST_F(DistributeddbKvCrudTest, ComplexDataTest002, TestSize.Level1) /* * @tc.name: ComplexDataTest 003 - * @tc.desc: Verify that can operate a alphanum string key. + * @tc.desc: Verify that can operate an alphanum string key. * @tc.type: FUNC * @tc.require: SR000BUH3J * @tc.author: luqianfu diff --git a/services/distributeddataservice/test/moduletest/common/distributeddb/src/distributeddb_nb_autolaunch_test.cpp b/services/distributeddataservice/test/moduletest/common/distributeddb/src/distributeddb_nb_autolaunch_test.cpp index 7b5901e5fc853d74956f51c26a18eabb1d032164..bfb03d708f148b23f09c619e6c2e6cf310437957 100644 --- a/services/distributeddataservice/test/moduletest/common/distributeddb/src/distributeddb_nb_autolaunch_test.cpp +++ b/services/distributeddataservice/test/moduletest/common/distributeddb/src/distributeddb_nb_autolaunch_test.cpp @@ -423,7 +423,7 @@ HWTEST_F(DistributeddbNbAutolaunchTest, ParamCheck006, TestSize.Level0) EXPECT_EQ(manager->SetKvStoreConfig({ .dataDir = DistributedDBConstant::NB_DIRECTOR }), OK); /** * @tc.steps: step1. call EnableKvStoreAutoLaunch use the option with which createIfNecessary is true, - * isEncryptedDb = false, and different dataDir that include many special charaters; + * isEncryptedDb = false, and different dataDir that include many special characters; * @tc.expected: step1. enable success, and return OK. */ string middlePath = "ddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd/" @@ -646,7 +646,7 @@ HWTEST_F(DistributeddbNbAutolaunchTest, ClosedSyncPressure001, TestSize.Level0) * @tc.name: SyncCommErr 001 * @tc.desc: Test Sync return Code, when Communicator get some error. * @tc.type: FUNC - * @tc.require: DTS2020052001231 + * @tc.require: * @tc.author: xushaohua */ HWTEST_F(DistributeddbNbAutolaunchTest, SyncCommErr001, TestSize.Level1)