From e56ebfc04612dab9220d09d78b40f4685f46e9df Mon Sep 17 00:00:00 2001 From: wuchunbo Date: Sat, 12 Feb 2022 22:52:04 +0800 Subject: [PATCH 1/6] add rdb sync Signed-off-by: wuchunbo --- .../distributeddatafwk/include/itypes_util.h | 11 +- .../src/ikvstore_data_service.cpp | 12 +- .../distributeddatafwk/src/itypes_util.cpp | 143 +++++++ .../rdb/{src => include}/irdb_service.h | 26 +- .../innerkitsimpl/rdb/include/rdb_manager.h | 13 +- .../innerkitsimpl/rdb/include/rdb_notifier.h | 83 ++++ .../innerkitsimpl/rdb/include/rdb_service.h | 54 +-- .../innerkitsimpl/rdb/include/rdb_syncer.h | 28 -- .../innerkitsimpl/rdb/include/rdb_types.h | 51 ++- .../innerkitsimpl/rdb/src/irdb_syncer.h | 36 -- .../rdb/src/rdb_client_death_recipient.cpp | 48 --- .../rdb/src/rdb_client_death_recipient.h | 45 --- .../innerkitsimpl/rdb/src/rdb_manager.cpp | 13 +- .../rdb/src/rdb_manager_impl.cpp | 133 +++--- .../innerkitsimpl/rdb/src/rdb_manager_impl.h | 35 +- .../innerkitsimpl/rdb/src/rdb_notifier.cpp | 167 ++++++++ .../rdb/src/rdb_service_proxy.cpp | 379 +++++++++++++++++- .../innerkitsimpl/rdb/src/rdb_service_proxy.h | 56 ++- .../rdb/src/rdb_service_stub.cpp | 64 --- .../rdb/src/rdb_syncer_proxy.cpp | 50 --- .../innerkitsimpl/rdb/src/rdb_syncer_stub.cpp | 53 --- .../innerkitsimpl/rdb/src/rdb_syncer_stub.h | 38 -- interfaces/innerkits/distributeddata/BUILD.gn | 5 +- .../src/communication_provider_impl.cpp | 2 +- .../src/softbus_adapter_standard.cpp | 5 +- services/distributeddataservice/app/BUILD.gn | 10 +- .../app/src/kvstore_data_service.cpp | 12 +- .../app/src/kvstore_data_service.h | 2 +- .../app/src/kvstore_meta_manager.cpp | 9 +- .../app/src/kvstore_meta_manager.h | 6 +- .../service/rdb/rdb_service_impl.cpp | 351 ++++++++++++++++ .../service}/rdb/rdb_service_impl.h | 71 +++- .../service/rdb/rdb_service_stub.cpp | 202 ++++++++++ .../service/rdb}/rdb_service_stub.h | 54 ++- .../service/rdb/rdb_store_observer_impl.cpp | 36 +- .../service/rdb/rdb_store_observer_impl.h | 23 +- .../service/rdb/rdb_syncer.cpp | 302 ++++++++++++++ .../service/rdb/rdb_syncer.h | 97 +++++ services/rdb/rdb_device_syncer.cpp | 105 ----- services/rdb/rdb_device_syncer.h | 55 --- services/rdb/rdb_service_impl.cpp | 125 ------ services/rdb/rdb_syncer_factory.cpp | 53 --- services/rdb/rdb_syncer_factory.h | 76 ---- services/rdb/rdb_syncer_impl.cpp | 76 ---- 44 files changed, 2115 insertions(+), 1100 deletions(-) rename frameworks/innerkitsimpl/rdb/{src => include}/irdb_service.h (52%) create mode 100644 frameworks/innerkitsimpl/rdb/include/rdb_notifier.h rename services/rdb/rdb_syncer_impl.h => frameworks/innerkitsimpl/rdb/include/rdb_service.h (43%) delete mode 100644 frameworks/innerkitsimpl/rdb/include/rdb_syncer.h delete mode 100644 frameworks/innerkitsimpl/rdb/src/irdb_syncer.h delete mode 100644 frameworks/innerkitsimpl/rdb/src/rdb_client_death_recipient.cpp delete mode 100644 frameworks/innerkitsimpl/rdb/src/rdb_client_death_recipient.h create mode 100644 frameworks/innerkitsimpl/rdb/src/rdb_notifier.cpp delete mode 100644 frameworks/innerkitsimpl/rdb/src/rdb_service_stub.cpp delete mode 100644 frameworks/innerkitsimpl/rdb/src/rdb_syncer_proxy.cpp delete mode 100644 frameworks/innerkitsimpl/rdb/src/rdb_syncer_stub.cpp delete mode 100644 frameworks/innerkitsimpl/rdb/src/rdb_syncer_stub.h create mode 100644 services/distributeddataservice/service/rdb/rdb_service_impl.cpp rename services/{ => distributeddataservice/service}/rdb/rdb_service_impl.h (30%) create mode 100644 services/distributeddataservice/service/rdb/rdb_service_stub.cpp rename {frameworks/innerkitsimpl/rdb/src => services/distributeddataservice/service/rdb}/rdb_service_stub.h (34%) rename frameworks/innerkitsimpl/rdb/src/rdb_service.h => services/distributeddataservice/service/rdb/rdb_store_observer_impl.cpp (55%) rename frameworks/innerkitsimpl/rdb/src/rdb_syncer_proxy.h => services/distributeddataservice/service/rdb/rdb_store_observer_impl.h (59%) create mode 100644 services/distributeddataservice/service/rdb/rdb_syncer.cpp create mode 100644 services/distributeddataservice/service/rdb/rdb_syncer.h delete mode 100644 services/rdb/rdb_device_syncer.cpp delete mode 100644 services/rdb/rdb_device_syncer.h delete mode 100644 services/rdb/rdb_service_impl.cpp delete mode 100644 services/rdb/rdb_syncer_factory.cpp delete mode 100644 services/rdb/rdb_syncer_factory.h delete mode 100644 services/rdb/rdb_syncer_impl.cpp diff --git a/frameworks/innerkitsimpl/distributeddatafwk/include/itypes_util.h b/frameworks/innerkitsimpl/distributeddatafwk/include/itypes_util.h index d55c2b534..1bca607e6 100644 --- a/frameworks/innerkitsimpl/distributeddatafwk/include/itypes_util.h +++ b/frameworks/innerkitsimpl/distributeddatafwk/include/itypes_util.h @@ -48,7 +48,16 @@ public: static bool Marshalling(const DistributedRdb::RdbSyncerParam& param, MessageParcel& parcel); static bool UnMarshalling(MessageParcel& parcel, DistributedRdb::RdbSyncerParam& param); - + + static bool Marshalling(const DistributedRdb::SyncResult& result, MessageParcel& parcel); + static bool UnMarshalling(MessageParcel& parcel, DistributedRdb::SyncResult& result); + + static bool Marshalling(const DistributedRdb::SyncOption& option, MessageParcel& parcel); + static bool UnMarshalling(MessageParcel& parcel, DistributedRdb::SyncOption& option); + + static bool Marshalling(const DistributedRdb::RdbPredicates& predicates, MessageParcel& parcel); + static bool UnMarshalling(MessageParcel& parcel, DistributedRdb::RdbPredicates& predicates); + static int64_t GetTotalSize(const std::vector &entries); static int64_t GetTotalSize(const std::vector &entries); diff --git a/frameworks/innerkitsimpl/distributeddatafwk/src/ikvstore_data_service.cpp b/frameworks/innerkitsimpl/distributeddatafwk/src/ikvstore_data_service.cpp index 426b784cb..18cd0fee4 100755 --- a/frameworks/innerkitsimpl/distributeddatafwk/src/ikvstore_data_service.cpp +++ b/frameworks/innerkitsimpl/distributeddatafwk/src/ikvstore_data_service.cpp @@ -18,6 +18,8 @@ #include "ikvstore_data_service.h" #include "constant.h" #include "irdb_service.h" +#include "rdb_service_proxy.h" +#include "itypes_util.h" #include "message_parcel.h" #include "types.h" #include "log_print.h" @@ -392,20 +394,26 @@ Status KvStoreDataServiceProxy::StopWatchDeviceChange(sptr KvStoreDataServiceProxy::GetRdbService() { + ZLOGI("enter"); MessageParcel data; if (!data.WriteInterfaceToken(KvStoreDataServiceProxy::GetDescriptor())) { ZLOGE("write descriptor failed"); return nullptr; } + MessageParcel reply; MessageOption mo { MessageOption::TF_SYNC }; int32_t error = Remote()->SendRequest(GET_RDB_SERVICE, data, reply, mo); if (error != 0) { - ZLOGW("SendRequest returned %{public}d", error); + ZLOGE("SendRequest returned %{public}d", error); return nullptr; } auto remoteObject = reply.ReadRemoteObject(); - return iface_cast(remoteObject); + if (remoteObject == nullptr) { + ZLOGE("remote object is nullptr"); + return nullptr; + } + return iface_cast(remoteObject); } int32_t KvStoreDataServiceStub::GetKvStoreOnRemote(MessageParcel &data, MessageParcel &reply) diff --git a/frameworks/innerkitsimpl/distributeddatafwk/src/itypes_util.cpp b/frameworks/innerkitsimpl/distributeddatafwk/src/itypes_util.cpp index f7801e5fd..7651ca90c 100644 --- a/frameworks/innerkitsimpl/distributeddatafwk/src/itypes_util.cpp +++ b/frameworks/innerkitsimpl/distributeddatafwk/src/itypes_util.cpp @@ -200,6 +200,149 @@ bool ITypesUtil::UnMarshalling(MessageParcel& parcel, DistributedRdb::RdbSyncerP return true; } +bool ITypesUtil::Marshalling(const DistributedRdb::SyncResult &result, MessageParcel &parcel) +{ + if (!parcel.WriteInt32(static_cast(result.size()))) { + ZLOGE("SyncResult write size failed"); + return false; + } + + for (const auto& entry : result) { + if (!parcel.WriteString(entry.first)) { + ZLOGE("SyncResult write device failed"); + return false; + } + if (!parcel.WriteInt32(entry.second)) { + ZLOGE("SyncResult write int failed"); + return false; + } + } + return true; +} + +bool ITypesUtil::UnMarshalling(MessageParcel &parcel, DistributedRdb::SyncResult &result) +{ + int32_t size = 0; + if (!parcel.ReadInt32(size)) { + ZLOGE("SyncResult read size failed"); + return false; + } + if (size <= 0) { + ZLOGE("SyncResult size invalid"); + return false; + } + + for (int32_t i = 0; i < size; i++) { + std::string device; + if (!parcel.ReadString(device)) { + ZLOGE("SyncResult read device failed"); + return false; + } + int32_t error; + if (!parcel.ReadInt32(error)) { + ZLOGE("SyncResult read int failed"); + return false; + } + result.insert( { device, error } ); + } + return true; +} + +bool ITypesUtil::Marshalling(const DistributedRdb::SyncOption &option, MessageParcel &parcel) +{ + if (!parcel.WriteInt32(option.mode)) { + ZLOGE("SyncOption write mode failed"); + return false; + } + if (!parcel.WriteBool(option.isBlock)) { + ZLOGE("SyncOption write isBlock failed"); + return false; + } + return true; +} + +bool ITypesUtil::UnMarshalling(MessageParcel &parcel, DistributedRdb::SyncOption &option) +{ + int32_t mode; + if (!parcel.ReadInt32(mode)) { + ZLOGE("SyncOption read mode failed"); + return false; + } + option.mode = static_cast(mode); + if (!parcel.ReadBool(option.isBlock)) { + ZLOGE("SyncOption read isBlock failed"); + return false; + } + return true; +} + +bool ITypesUtil::Marshalling(const DistributedRdb::RdbPredicates &predicates, MessageParcel &parcel) +{ + if (!parcel.WriteString(predicates.table_)) { + ZLOGE("predicate write table failed"); + return false; + } + if (!parcel.WriteStringVector(predicates.devices_)) { + ZLOGE("predicate write devices failed"); + return false; + } + if (!parcel.WriteUint32(predicates.operations_.size())) { + ZLOGE("predicate write operation size failed"); + return false; + } + for (const auto& operation : predicates.operations_) { + if (!parcel.WriteInt32(operation.operator_)) { + ZLOGE("predicate write operator failed"); + return false; + } + if (!parcel.WriteString(operation.field_)) { + ZLOGE("predicate write field failed"); + return false; + } + if (!parcel.WriteStringVector(operation.values_)) { + ZLOGE("predicate write values failed"); + return false; + } + } + return true; +} + +bool ITypesUtil::UnMarshalling(MessageParcel &parcel, DistributedRdb::RdbPredicates &predicates) +{ + if (!parcel.ReadString(predicates.table_)) { + ZLOGE("predicate read table failed"); + return false; + } + if (!parcel.ReadStringVector(&predicates.devices_)) { + ZLOGE("predicate read devices failed"); + return false; + } + uint32_t size = 0; + if (!parcel.ReadUint32(size)) { + ZLOGE("predicate read operation size failed"); + return false; + } + for (uint32_t i = 0; i < size; i++) { + int32_t op; + if (!parcel.ReadInt32(op)) { + ZLOGE("predicate read operator failed"); + return false; + } + DistributedRdb::RdbPredicateOperation operation; + operation.operator_ = static_cast(op); + if (!parcel.ReadString(operation.field_)) { + ZLOGE("predicate read field failed"); + return false; + } + if (!parcel.ReadStringVector(&operation.values_)) { + ZLOGE("predicate read values failed"); + return false; + } + predicates.operations_.push_back(std::move(operation)); + } + return true; +} + template std::vector ITypesUtil::Convert2Vector(const std::list &entries) { diff --git a/frameworks/innerkitsimpl/rdb/src/irdb_service.h b/frameworks/innerkitsimpl/rdb/include/irdb_service.h similarity index 52% rename from frameworks/innerkitsimpl/rdb/src/irdb_service.h rename to frameworks/innerkitsimpl/rdb/include/irdb_service.h index a7cbc707e..c4dcc718b 100644 --- a/frameworks/innerkitsimpl/rdb/src/irdb_service.h +++ b/frameworks/innerkitsimpl/rdb/include/irdb_service.h @@ -20,20 +20,38 @@ #include #include "rdb_service.h" -#include "irdb_syncer.h" #include "rdb_types.h" -#include "rdb_client_death_recipient.h" namespace OHOS::DistributedRdb { class IRdbService : public RdbService, public IRemoteBroker { public: enum { - RDB_SERVICE_CMD_GET_SYNCER, - RDB_SERVICE_CMD_REGISTER_CLIENT_DEATH, + RDB_SERVICE_CMD_OBTAIN_TABLE, + RDB_SERVICE_CMD_GET_DEVICES, + RDB_SERVICE_CMD_INIT_NOTIFIER, + RDB_SERVICE_CMD_SET_DIST_TABLE, + RDB_SERVICE_CMD_SYNC, + RDB_SERVICE_CMD_ASYNC, + RDB_SERVICE_CMD_SUBSCRIBE, + RDB_SERVICE_CMD_UNSUBSCRIBE, RDB_SERVICE_CMD_MAX }; DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.DistributedRdb.IRdbService"); + + virtual std::vector GetConnectDevices() = 0; + + virtual int32_t InitNotifier(const RdbSyncerParam& param, const sptr notifier) = 0; + + virtual int32_t DoSync(const RdbSyncerParam& param, const SyncOption& option, + const RdbPredicates& predicates, SyncResult& result) = 0; + + virtual int32_t DoAsync(const RdbSyncerParam& param, uint32_t seqNum, + const SyncOption& option, const RdbPredicates& predicates) = 0; + + virtual int32_t DoSubscribe(const RdbSyncerParam& param) = 0; + + virtual int32_t DoUnSubscribe(const RdbSyncerParam& param) = 0; }; } #endif diff --git a/frameworks/innerkitsimpl/rdb/include/rdb_manager.h b/frameworks/innerkitsimpl/rdb/include/rdb_manager.h index 8f3b6882b..fe1d95307 100644 --- a/frameworks/innerkitsimpl/rdb/include/rdb_manager.h +++ b/frameworks/innerkitsimpl/rdb/include/rdb_manager.h @@ -20,18 +20,15 @@ #include #include +#include "rdb_service.h" +#include "rdb_types.h" namespace OHOS::DistributedRdb { -struct RdbSyncerParam; -class RdbSyncer; - class RdbManager { public: - static std::shared_ptr GetRdbSyncer(const RdbSyncerParam& param); - - static int RegisterRdbServiceDeathObserver(const std::string &storeName, const std::function& observer); - - static int UnRegisterRdbServiceDeathObserver(const std::string &storeName); + static std::vector GetConnectDevices(); + + static std::shared_ptr GetRdbService(const RdbSyncerParam& param); }; } #endif diff --git a/frameworks/innerkitsimpl/rdb/include/rdb_notifier.h b/frameworks/innerkitsimpl/rdb/include/rdb_notifier.h new file mode 100644 index 000000000..ee037bce4 --- /dev/null +++ b/frameworks/innerkitsimpl/rdb/include/rdb_notifier.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 DISTRIBUTED_RDB_NOTIFIER_H +#define DISTRIBUTED_RDB_NOTIFIER_H + +#include +#include +#include + +#include "rdb_types.h" + +namespace OHOS::DistributedRdb { +class IRdbNotifier: public IRemoteBroker { +public: + enum { + RDB_NOTIFIER_CMD_SYNC_COMPLETE, + RDB_NOTIFIER_CMD_DATA_CHANGE, + RDB_NOTIFIER_CMD_MAX + }; + + virtual int32_t OnComplete(uint32_t seqNum, const SyncResult& result) = 0; + + virtual int32_t OnChange(const std::string& storeName, const std::vector& devices) = 0; + + DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.DistributedRdb.IRdbNotifier"); +}; + +class RdbNotifierProxy : public IRemoteProxy { +public: + explicit RdbNotifierProxy(const sptr& object); + virtual ~RdbNotifierProxy() noexcept; + + int32_t OnComplete(uint32_t seqNum, const SyncResult& result) override; + + int32_t OnChange(const std::string& storeName, const std::vector& devices) override; + +private: + static inline BrokerDelegator delegator_; +}; + +using RdbSyncCompleteNotifier = std::function; +using RdbDataChangeNotifier = std::function&)>; + +class RdbNotifierStub : public IRemoteStub { +public: + RdbNotifierStub(const RdbSyncCompleteNotifier&, const RdbDataChangeNotifier&); + virtual ~RdbNotifierStub() noexcept; + + int OnRemoteRequest(uint32_t code, MessageParcel& data, MessageParcel& reply, MessageOption& option) override; + + int32_t OnCompleteInner(MessageParcel& data, MessageParcel& reply); + int32_t OnComplete(uint32_t seqNum, const SyncResult& result) override; + + int32_t OnChangeInner(MessageParcel&data, MessageParcel& reply); + int32_t OnChange(const std::string& storeName, const std::vector& devices) override; + +private: + bool CheckInterfaceToken(MessageParcel& data); + + using RequestHandle = int32_t (RdbNotifierStub::*)(MessageParcel&, MessageParcel&); + static constexpr RequestHandle HANDLES[RDB_NOTIFIER_CMD_MAX] = { + [RDB_NOTIFIER_CMD_SYNC_COMPLETE] = &RdbNotifierStub::OnCompleteInner, + [RDB_NOTIFIER_CMD_DATA_CHANGE] = &RdbNotifierStub::OnChangeInner, + }; + + RdbSyncCompleteNotifier completeNotifier_; + RdbDataChangeNotifier changeNotifier_; +}; +} +#endif diff --git a/services/rdb/rdb_syncer_impl.h b/frameworks/innerkitsimpl/rdb/include/rdb_service.h similarity index 43% rename from services/rdb/rdb_syncer_impl.h rename to frameworks/innerkitsimpl/rdb/include/rdb_service.h index 76ec6e7a4..2cb69fcbe 100644 --- a/services/rdb/rdb_syncer_impl.h +++ b/frameworks/innerkitsimpl/rdb/include/rdb_service.h @@ -13,47 +13,31 @@ * limitations under the License. */ -#ifndef DISTRIBUTED_RDB_SYNCER_IMPL_H -#define DISTRIBUTED_RDB_SYNCER_IMPL_H +#ifndef DISTRIBUTED_RDB_SERVICE_H +#define DISTRIBUTED_RDB_SERVICE_H -#include "rdb_syncer_stub.h" +#include +#include + +#include #include "rdb_types.h" namespace OHOS::DistributedRdb { -class RdbSyncerImpl : public RdbSyncerStub { +class RdbService { public: - explicit RdbSyncerImpl(const RdbSyncerParam& param, pid_t uid); - - RdbSyncerImpl() = delete; - RdbSyncerImpl(const RdbSyncerImpl&) = delete; - RdbSyncerImpl& operator=(const RdbSyncerImpl&) = delete; - - virtual ~RdbSyncerImpl(); - - virtual int Init() = 0; - - bool operator==(const RdbSyncerImpl& rhs) const; - - std::string GetBundleName() const; - - std::string GetAppId() const; - - std::string GetUserId() const; - - std::string GetStoreId() const; - - std::string GetIdentifier() const; - - std::string GetPath() const; + virtual std::string ObtainDistributedTableName(const std::string& device, const std::string& table) = 0; + + virtual int32_t SetDistributedTables(const RdbSyncerParam& param, + const std::vector& tables) = 0; -private: - int type_; - std::string bundleName_; - std::string path_; - std::string storeId_; - std::string appId_; - std::string userId_; - std::string identifier_; + virtual int32_t Sync(const RdbSyncerParam& param, const SyncOption& option, + const RdbPredicates& predicates, const SyncCallback& callback) = 0; + + virtual int32_t Subscribe(const RdbSyncerParam& param, const SubscribeOption& option, + const RdbStoreObserver& observer) = 0; + + virtual int32_t UnSubscribe(const RdbSyncerParam& param, const SubscribeOption& option, + const RdbStoreObserver& observer) = 0; }; } #endif diff --git a/frameworks/innerkitsimpl/rdb/include/rdb_syncer.h b/frameworks/innerkitsimpl/rdb/include/rdb_syncer.h deleted file mode 100644 index 890be3105..000000000 --- a/frameworks/innerkitsimpl/rdb/include/rdb_syncer.h +++ /dev/null @@ -1,28 +0,0 @@ -/* - * 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 DISTRIBUTED_RDB_SYNCER_H -#define DISTRIBUTED_RDB_SYNCER_H - -#include -#include - -namespace OHOS::DistributedRdb { -class RdbSyncer { -public: - virtual int SetDistributedTables(const std::vector& tables) = 0; -}; -} -#endif diff --git a/frameworks/innerkitsimpl/rdb/include/rdb_types.h b/frameworks/innerkitsimpl/rdb/include/rdb_types.h index c6c5b5375..79bf343fe 100644 --- a/frameworks/innerkitsimpl/rdb/include/rdb_types.h +++ b/frameworks/innerkitsimpl/rdb/include/rdb_types.h @@ -19,10 +19,16 @@ #include #include #include +#include namespace OHOS::DistributedRdb { +enum RdbStatus { + RDB_OK, + RDB_ERROR, +}; + enum RdbDistributedType { - RDB_DEVICE_COLLABORATION, + RDB_DEVICE_COLLABORATION = 10, RDB_DISTRIBUTED_TYPE_MAX }; @@ -45,18 +51,55 @@ struct SyncOption { }; using SyncResult = std::map; // networkId -using SyncCallback = std::function; +using SyncCallback = std::function; + +enum RdbPredicateOperator { + EQUAL_TO, + NOT_EQUAL_TO, + AND, + OR, + ORDER_BY, + LIMIT, + OPERATOR_MAX +}; + +struct RdbPredicateOperation { + RdbPredicateOperator operator_; + std::string field_; + std::vector values_; +}; + +struct RdbPredicates { + inline void AddOperation(const RdbPredicateOperator op, const std::string& field, + const std::string& value) + { + operations_.push_back({op, field, {value}}); + } + inline void AddOperation(const RdbPredicateOperator op, const std::string& field, + const std::vector& values) + { + operations_.push_back({op, field, values}); + } + + std::string table_; + std::vector devices_; + std::vector operations_; +}; enum SubscribeMode { - LOCAL, REMOTE, - LOCAL_AND_REMOTE, + SUBSCRIBE_MODE_MAX }; struct SubscribeOption { SubscribeMode mode; }; +class RdbStoreObserver { +public: + virtual void OnChange(const std::vector& devices) = 0; // networkid +}; + struct DropOption { }; } diff --git a/frameworks/innerkitsimpl/rdb/src/irdb_syncer.h b/frameworks/innerkitsimpl/rdb/src/irdb_syncer.h deleted file mode 100644 index 68cf35947..000000000 --- a/frameworks/innerkitsimpl/rdb/src/irdb_syncer.h +++ /dev/null @@ -1,36 +0,0 @@ -/* - * 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 DISTRUBTED_IRDB_SYNCER_H -#define DISTRUBTED_IRDB_SYNCER_H - -#include -#include "rdb_types.h" -#include "rdb_syncer.h" - -namespace OHOS::DistributedRdb { -class IRdbSyncer : public RdbSyncer, public IRemoteBroker { -public: - enum { - RDB_SYNCER_CMD_SET_DIST_TABLES, - RDB_SYNCER_CMD_SYNC, - RDB_SYNCER_CMD_SUBSCRIBE, - RDB_SYNCER_CMD_REMOVE_DEVICE_DATA, - RDB_SYNCER_CMD_MAX - }; - DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.DistributedRdb.IRdbSyncer"); -}; -} -#endif diff --git a/frameworks/innerkitsimpl/rdb/src/rdb_client_death_recipient.cpp b/frameworks/innerkitsimpl/rdb/src/rdb_client_death_recipient.cpp deleted file mode 100644 index c61fdc1a5..000000000 --- a/frameworks/innerkitsimpl/rdb/src/rdb_client_death_recipient.cpp +++ /dev/null @@ -1,48 +0,0 @@ -/* - * 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 "RdbClientDeathRecipientProxy" - -#include "rdb_client_death_recipient.h" -#include "log_print.h" - -namespace OHOS::DistributedRdb { -RdbClientDeathRecipientProxy::RdbClientDeathRecipientProxy(const sptr &object) - : IRemoteProxy(object) -{ - ZLOGI("construct"); -} - -RdbClientDeathRecipientProxy::~RdbClientDeathRecipientProxy() -{ - ZLOGI("deconstruct"); -} - -RdbClientDeathRecipientStub::RdbClientDeathRecipientStub() -{ - ZLOGI("construct"); -} - -RdbClientDeathRecipientStub::~RdbClientDeathRecipientStub() -{ - ZLOGI("deconstruct"); -} - -int RdbClientDeathRecipientStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, - MessageOption &option) -{ - return IPCObjectStub::OnRemoteRequest(code, data, reply, option); -} -} diff --git a/frameworks/innerkitsimpl/rdb/src/rdb_client_death_recipient.h b/frameworks/innerkitsimpl/rdb/src/rdb_client_death_recipient.h deleted file mode 100644 index b9e45fd7b..000000000 --- a/frameworks/innerkitsimpl/rdb/src/rdb_client_death_recipient.h +++ /dev/null @@ -1,45 +0,0 @@ -/* - * 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 IRDB_CLIENT_DEATH_RECIPIENT_H -#define IRDB_CLIENT_DEATH_RECIPIENT_H - -#include -#include -#include - -namespace OHOS::DistributedRdb { -class IRdbClientDeathRecipient : public IRemoteBroker { -public: - DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.DistributedRdb.IRdbClientDeathRecipient"); -}; - -class RdbClientDeathRecipientProxy : public IRemoteProxy { -public: - explicit RdbClientDeathRecipientProxy(const sptr& object); - virtual ~RdbClientDeathRecipientProxy(); - -private: - static inline BrokerDelegator delegator_; -}; - -class RdbClientDeathRecipientStub : public IRemoteStub { -public: - RdbClientDeathRecipientStub(); - virtual ~RdbClientDeathRecipientStub(); - int OnRemoteRequest(uint32_t code, MessageParcel& data, MessageParcel& reply, MessageOption& option) override; -}; -} -#endif diff --git a/frameworks/innerkitsimpl/rdb/src/rdb_manager.cpp b/frameworks/innerkitsimpl/rdb/src/rdb_manager.cpp index 671169f97..7a438892c 100644 --- a/frameworks/innerkitsimpl/rdb/src/rdb_manager.cpp +++ b/frameworks/innerkitsimpl/rdb/src/rdb_manager.cpp @@ -17,18 +17,13 @@ #include "rdb_manager_impl.h" namespace OHOS::DistributedRdb { -std::shared_ptr RdbManager::GetRdbSyncer(const RdbSyncerParam ¶m) +std::vector RdbManager::GetConnectDevices() { - return RdbManagerImpl::GetInstance().GetRdbSyncer(param); + return RdbManagerImpl::GetInstance().GetConnectDevices(); } -int RdbManager::RegisterRdbServiceDeathObserver(const std::string &storeName, const std::function& observer) +std::shared_ptr RdbManager::GetRdbService(const RdbSyncerParam& param) { - return RdbManagerImpl::GetInstance().RegisterRdbServiceDeathObserver(storeName, observer); -} - -int RdbManager::UnRegisterRdbServiceDeathObserver(const std::string &storeName) -{ - return RdbManagerImpl::GetInstance().UnRegisterRdbServiceDeathObserver(storeName); + return RdbManagerImpl::GetInstance().GetRdbService(param); } } \ No newline at end of file diff --git a/frameworks/innerkitsimpl/rdb/src/rdb_manager_impl.cpp b/frameworks/innerkitsimpl/rdb/src/rdb_manager_impl.cpp index a12c6f4b7..a92324706 100644 --- a/frameworks/innerkitsimpl/rdb/src/rdb_manager_impl.cpp +++ b/frameworks/innerkitsimpl/rdb/src/rdb_manager_impl.cpp @@ -17,6 +17,7 @@ #include "rdb_manager_impl.h" +#include #include "iservice_registry.h" #include "ipc_skeleton.h" #include "system_ability_definition.h" @@ -24,18 +25,30 @@ #include "log_print.h" #include "ikvstore_data_service.h" #include "irdb_service.h" +#include "rdb_service_proxy.h" namespace OHOS::DistributedRdb { -static sptr GetDistributedDataManager() +static sptr GetDistributedDataManager() { - auto manager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); - if (manager == nullptr) { - ZLOGE("get system ability manager failed"); - return nullptr; + int retry = 0; + while (++retry <= RdbManagerImpl::GET_DDMS_RETRY_TIMES) { + auto manager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (manager == nullptr) { + ZLOGE("get system ability manager failed"); + return nullptr; + } + ZLOGI("get distributed data manager %{public}d", retry); + auto remoteObject = manager->CheckSystemAbility(DISTRIBUTED_KV_DATA_SERVICE_ABILITY_ID); + if (remoteObject == nullptr) { + std::this_thread::sleep_for(std::chrono::seconds(RdbManagerImpl::RETRY_INTERVAL)); + continue; + } + ZLOGI("get distributed data manager success"); + return iface_cast(remoteObject); } - ZLOGI("get distributed data manager"); - auto remoteObject = manager->CheckSystemAbility(DISTRIBUTED_KV_DATA_SERVICE_ABILITY_ID); - return iface_cast(remoteObject); + + ZLOGE("get distributed data manager failed"); + return nullptr; } static void LinkToDeath(const sptr& remote) @@ -56,7 +69,7 @@ RdbManagerImpl::RdbManagerImpl() RdbManagerImpl::~RdbManagerImpl() { - ZLOGI("deconstruct"); + ZLOGI("destroy"); } RdbManagerImpl& RdbManagerImpl::GetInstance() @@ -65,13 +78,20 @@ RdbManagerImpl& RdbManagerImpl::GetInstance() return manager; } -std::shared_ptr RdbManagerImpl::GetRdbService() +std::vector RdbManagerImpl::GetConnectDevices() { std::lock_guard lock(mutex_); - if (rdbService_ != nullptr) { - return rdbService_; + auto service = GetRdbService(); + if (service == nullptr) { + ZLOGE("get service failed"); + return std::vector(); } - + + return ((RdbServiceProxy *)service.GetRefPtr())->GetConnectDevices(); +} + +sptr RdbManagerImpl::GetRdbService() +{ if (distributedDataMgr_ == nullptr) { distributedDataMgr_ = GetDistributedDataManager(); } @@ -79,50 +99,55 @@ std::shared_ptr RdbManagerImpl::GetRdbService() ZLOGE("get distributed data manager failed"); return nullptr; } - - auto serviceObject = distributedDataMgr_->GetRdbService(); - if (serviceObject == nullptr) { + + auto service = distributedDataMgr_->GetRdbService(); + if (service == nullptr) { ZLOGE("get rdb service failed"); return nullptr; } - LinkToDeath(serviceObject->AsObject()); - rdbService_ = std::shared_ptr(serviceObject.GetRefPtr(), [holder = serviceObject] (const auto*) {}); - return rdbService_; + return service; } -std::shared_ptr RdbManagerImpl::GetRdbSyncer(const RdbSyncerParam ¶m) +std::shared_ptr RdbManagerImpl::GetRdbService(const RdbSyncerParam& param) { - if (param.bundleName_.empty() || param.path_.empty() || param.storeName_.empty()) { - ZLOGE("param is invalid"); - return nullptr; + std::lock_guard lock(mutex_); + if (rdbService_ != nullptr) { + return rdbService_; } auto service = GetRdbService(); if (service == nullptr) { return nullptr; } - RegisterClientDeathRecipient(param.bundleName_); - return service->GetRdbSyncer(param); -} - -int RdbManagerImpl::RegisterRdbServiceDeathObserver(const std::string& storeName, - const std::function& observer) -{ - serviceDeathObservers_.Insert(storeName, observer); - return 0; -} - -int RdbManagerImpl::UnRegisterRdbServiceDeathObserver(const std::string& storeName) -{ - std::lock_guard lock(mutex_); - serviceDeathObservers_.Erase(storeName); - return 0; + if (((RdbServiceProxy *)service.GetRefPtr())->InitNotifier(param) != RDB_OK) { + ZLOGE("init notifier failed"); + return nullptr; + } + LinkToDeath(service->AsObject()); + rdbService_ = std::shared_ptr(service.GetRefPtr(), [holder = service] (const auto*) {}); + bundleName_ = param.bundleName_; + return rdbService_; } void RdbManagerImpl::OnRemoteDied() { ZLOGI("rdb service has dead!!"); - NotifyServiceDeath(); + auto proxy = std::static_pointer_cast(rdbService_); + auto observers = proxy->ExportObservers(); ResetServiceHandle(); + + std::this_thread::sleep_for(std::chrono::seconds(2)); // sleep two second + RdbSyncerParam param; + param.bundleName_ = bundleName_; + auto service = GetRdbService(param); + if (service == nullptr) { + return; + } + proxy = std::static_pointer_cast(service); + if (proxy == nullptr) { + return; + } + ZLOGI("restore observer"); + proxy->ImportObservers(observers); } void RdbManagerImpl::ResetServiceHandle() @@ -131,33 +156,5 @@ void RdbManagerImpl::ResetServiceHandle() std::lock_guard lock(mutex_); distributedDataMgr_ = nullptr; rdbService_ = nullptr; - clientDeathObject_ = nullptr; -} - -void RdbManagerImpl::NotifyServiceDeath() -{ - ZLOGI("enter"); - serviceDeathObservers_.ForEach([] (const auto& key, const auto& value) { - if (value != nullptr) { - value(); - } - return false; - }); -} - -void RdbManagerImpl::RegisterClientDeathRecipient(const std::string& bundleName) -{ - std::lock_guard lock(mutex_); - if (clientDeathObject_ != nullptr) { - return; - } - if (rdbService_ != nullptr) { - sptr object = new(std::nothrow) RdbClientDeathRecipientStub(); - if (rdbService_->RegisterClientDeathRecipient(bundleName, object) != 0) { - ZLOGE("register client death recipient failed"); - } else { - clientDeathObject_ = object; - } - } } } diff --git a/frameworks/innerkitsimpl/rdb/src/rdb_manager_impl.h b/frameworks/innerkitsimpl/rdb/src/rdb_manager_impl.h index cf7298ed3..6f3fc9bbe 100644 --- a/frameworks/innerkitsimpl/rdb/src/rdb_manager_impl.h +++ b/frameworks/innerkitsimpl/rdb/src/rdb_manager_impl.h @@ -24,23 +24,24 @@ #include "iremote_object.h" #include "concurrent_map.h" #include "rdb_types.h" -#include "rdb_syncer.h" namespace OHOS::DistributedKv { -class IKvStoreDataService; +class KvStoreDataServiceProxy; } namespace OHOS::DistributedRdb { class RdbService; +class IRdbService; class RdbManagerImpl { public: + static constexpr int GET_DDMS_RETRY_TIMES = 3; + static constexpr int RETRY_INTERVAL = 1; + static RdbManagerImpl &GetInstance(); - - std::shared_ptr GetRdbSyncer(const RdbSyncerParam& param); - - int RegisterRdbServiceDeathObserver(const std::string &storeName, const std::function& callback); - - int UnRegisterRdbServiceDeathObserver(const std::string &storeName); + + std::vector GetConnectDevices(); + + std::shared_ptr GetRdbService(const RdbSyncerParam& param); void OnRemoteDied(); @@ -61,21 +62,15 @@ private: RdbManagerImpl(); ~RdbManagerImpl(); - - std::shared_ptr GetRdbService(); - + + sptr GetRdbService(); + void ResetServiceHandle(); - - void NotifyServiceDeath(); - - void RegisterClientDeathRecipient(const std::string &bundleName); - + std::mutex mutex_; - sptr distributedDataMgr_; + sptr distributedDataMgr_; std::shared_ptr rdbService_; - sptr clientDeathObject_; - - ConcurrentMap> serviceDeathObservers_; + std::string bundleName_; }; } #endif diff --git a/frameworks/innerkitsimpl/rdb/src/rdb_notifier.cpp b/frameworks/innerkitsimpl/rdb/src/rdb_notifier.cpp new file mode 100644 index 000000000..0893214aa --- /dev/null +++ b/frameworks/innerkitsimpl/rdb/src/rdb_notifier.cpp @@ -0,0 +1,167 @@ +/* + * 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 "RdbNotifier" + +#include "rdb_notifier.h" +#include "itypes_util.h" +#include "log_print.h" + + +namespace OHOS::DistributedRdb { +RdbNotifierProxy::RdbNotifierProxy(const sptr &object) + : IRemoteProxy(object) +{ + ZLOGI("construct"); +} + +RdbNotifierProxy::~RdbNotifierProxy() noexcept +{ + ZLOGI("destroy"); +} + +int32_t RdbNotifierProxy::OnComplete(uint32_t seqNum, const SyncResult &result) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(IRdbNotifier::GetDescriptor())) { + ZLOGE("write descriptor failed"); + return RDB_ERROR; + } + if (!data.WriteUint32(seqNum)) { + ZLOGE("write seq num failed"); + return RDB_ERROR; + } + if (!DistributedKv::ITypesUtil::Marshalling(result, data)) { + return RDB_ERROR; + } + + MessageParcel reply; + MessageOption option(MessageOption::TF_ASYNC); + if (Remote()->SendRequest(RDB_NOTIFIER_CMD_SYNC_COMPLETE, data, reply, option) != 0) { + ZLOGE("send request failed"); + return RDB_ERROR; + } + return RDB_OK; +} + +int RdbNotifierProxy::OnChange(const std::string& storeName, const std::vector &devices) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(IRdbNotifier::GetDescriptor())) { + ZLOGE("write descriptor failed"); + return RDB_ERROR; + } + if (!data.WriteString(storeName)) { + ZLOGE("write store name failed"); + return RDB_ERROR; + } + if (!data.WriteStringVector(devices)) { + ZLOGE("write devices failed"); + return RDB_ERROR; + } + + MessageParcel reply; + MessageOption option(MessageOption::TF_ASYNC); + if (Remote()->SendRequest(RDB_NOTIFIER_CMD_DATA_CHANGE, data, reply, option) != 0) { + ZLOGE("send request failed"); + return RDB_ERROR; + } + return RDB_OK; +} + +RdbNotifierStub::RdbNotifierStub(const RdbSyncCompleteNotifier& completeNotifier, + const RdbDataChangeNotifier& changeNotifier) + : IRemoteStub(), completeNotifier_(completeNotifier), changeNotifier_(changeNotifier) +{ + ZLOGI("construct"); +} + +RdbNotifierStub::~RdbNotifierStub() noexcept +{ + ZLOGI("destroy"); +} + +bool RdbNotifierStub::CheckInterfaceToken(MessageParcel& data) +{ + auto localDescriptor = IRdbNotifier::GetDescriptor(); + auto remoteDescriptor = data.ReadInterfaceToken(); + if (remoteDescriptor != localDescriptor) { + ZLOGE("interface token is not equal"); + return false; + } + return true; +} + +int RdbNotifierStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, + MessageOption &option) +{ + ZLOGI("code=%{public}u", code); + if (!CheckInterfaceToken(data)) { + return RDB_ERROR; + } + + if (code >= 0 && code < RDB_NOTIFIER_CMD_MAX) { + return (this->*HANDLES[code])(data, reply); + } + + return IPCObjectStub::OnRemoteRequest(code, data, reply, option); +} + +int32_t RdbNotifierStub::OnCompleteInner(MessageParcel &data, MessageParcel &reply) +{ + uint32_t seqNum; + if (!data.ReadUint32(seqNum)) { + ZLOGI("read seq num failed"); + return RDB_ERROR; + } + SyncResult result; + if (!DistributedKv::ITypesUtil::UnMarshalling(data, result)) { + ZLOGE("read sync result failed"); + return RDB_ERROR; + } + return OnComplete(seqNum, result); +} + +int32_t RdbNotifierStub::OnComplete(uint32_t seqNum, const SyncResult &result) +{ + if (completeNotifier_) { + completeNotifier_(seqNum, result); + } + return RDB_OK; +} + +int32_t RdbNotifierStub::OnChangeInner(MessageParcel &data, MessageParcel &reply) +{ + std::string storeName; + if (!data.ReadString(storeName)) { + ZLOGE("read store name failed"); + return RDB_ERROR; + } + std::vector devices; + if (!data.ReadStringVector(&devices)) { + ZLOGE("read devices faield"); + return RDB_ERROR; + } + return OnChange(storeName, devices); +} + +int32_t RdbNotifierStub::OnChange(const std::string& storeName, const std::vector &devices) +{ + if (changeNotifier_) { + changeNotifier_(storeName, devices); + } + return RDB_OK; +} +} \ No newline at end of file diff --git a/frameworks/innerkitsimpl/rdb/src/rdb_service_proxy.cpp b/frameworks/innerkitsimpl/rdb/src/rdb_service_proxy.cpp index ce63bdee0..46f845148 100644 --- a/frameworks/innerkitsimpl/rdb/src/rdb_service_proxy.cpp +++ b/frameworks/innerkitsimpl/rdb/src/rdb_service_proxy.cpp @@ -16,7 +16,6 @@ #define LOG_TAG "RdbServiceProxy" #include "rdb_service_proxy.h" -#include "rdb_syncer.h" #include "itypes_util.h" #include "log_print.h" @@ -24,53 +23,389 @@ namespace OHOS::DistributedRdb { RdbServiceProxy::RdbServiceProxy(const sptr &object) : IRemoteProxy(object) { + ZLOGI("construct"); } -std::shared_ptr RdbServiceProxy::GetRdbSyncer(const RdbSyncerParam& param) +void RdbServiceProxy::OnSyncComplete(uint32_t seqNum, const SyncResult &result) +{ + syncCallbacks_.ComputeIfPresent(seqNum, [&result] (const auto& key, const SyncCallback& callback) { + callback(result); + }); + syncCallbacks_.Erase(seqNum); +} + +void RdbServiceProxy::OnDataChange(const std::string& storeName, const std::vector &devices) +{ + ZLOGI("%{public}s", storeName.c_str()); + remoteObservers_.ComputeIfPresent( + storeName, [&devices] (const auto& key, const ObserverMapValue& value) { + for (const auto& observer : value.first) { + observer->OnChange(devices); + } + }); +} + +std::string RdbServiceProxy::ObtainDistributedTableName(const std::string &device, const std::string &table) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(IRdbService::GetDescriptor())) { + ZLOGE("write descriptor failed"); + return ""; + } + if (!data.WriteString(device)) { + ZLOGE("write device failed"); + return ""; + } + if (!data.WriteString(table)) { + ZLOGE("write table failed"); + return ""; + } + + MessageParcel reply; + MessageOption option; + if (Remote()->SendRequest(RDB_SERVICE_CMD_OBTAIN_TABLE, data, reply, option) != 0) { + ZLOGE("send request failed"); + return ""; + } + return reply.ReadString(); +} + +int32_t RdbServiceProxy::InitNotifier(const RdbSyncerParam& param) +{ + notifier_ = new (std::nothrow) RdbNotifierStub( + [this] (uint32_t seqNum, const SyncResult& result) { + OnSyncComplete(seqNum, result); + }, + [this] (const std::string& storeName, const std::vector& devices) { + OnDataChange(storeName, devices); + } + ); + if (notifier_ == nullptr) { + ZLOGE("create notifier failed"); + return RDB_ERROR; + } + + if (InitNotifier(param, notifier_->AsObject()) != RDB_OK) { + notifier_ = nullptr; + return RDB_ERROR; + } + + ZLOGI("success"); + return RDB_OK; +} + +int32_t RdbServiceProxy::InitNotifier(const RdbSyncerParam ¶m, const sptr notifier) { MessageParcel data; if (!data.WriteInterfaceToken(IRdbService::GetDescriptor())) { ZLOGE("write descriptor failed"); - return nullptr; + return RDB_ERROR; } if (!DistributedKv::ITypesUtil::Marshalling(param, data)) { - return nullptr; + ZLOGE("write param failed"); + return RDB_ERROR; } - + if (!data.WriteRemoteObject(notifier)) { + ZLOGE("write notifier failed"); + return RDB_ERROR; + } + MessageParcel reply; MessageOption option; - if (Remote()->SendRequest(RDB_SERVICE_CMD_GET_SYNCER, data, reply, option) != 0) { + if (Remote()->SendRequest(RDB_SERVICE_CMD_INIT_NOTIFIER, data, reply, option) != 0) { ZLOGE("send request failed"); - return nullptr; + return RDB_ERROR; + } + + int32_t res = RDB_ERROR; + return reply.ReadInt32(res) ? res : RDB_ERROR; +} + +uint32_t RdbServiceProxy::GetSeqNum() +{ + return seqNum_.fetch_add(1); +} + +int32_t RdbServiceProxy::DoSync(const RdbSyncerParam& param, const SyncOption &option, + const RdbPredicates &predicates, SyncResult& result) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(IRdbService::GetDescriptor())) { + ZLOGE("write descriptor failed"); + return RDB_ERROR; + } + if (!DistributedKv::ITypesUtil::Marshalling(param, data)) { + ZLOGE("write param failed"); + return RDB_ERROR; + } + if (!DistributedKv::ITypesUtil::Marshalling(option, data)) { + ZLOGE("write option failed"); + return RDB_ERROR; + } + if (!DistributedKv::ITypesUtil::Marshalling(predicates, data)) { + ZLOGE("write predicates failed"); } - auto remoteObject = reply.ReadRemoteObject(); - auto syncer = iface_cast(remoteObject); - return std::shared_ptr(syncer.GetRefPtr(), [holder = syncer] (const auto*) {}); + MessageParcel reply; + MessageOption opt; + if (Remote()->SendRequest(RDB_SERVICE_CMD_SYNC, data, reply, opt) != 0) { + ZLOGE("send request failed"); + return RDB_ERROR; + } + + if (!DistributedKv::ITypesUtil::UnMarshalling(reply, result)) { + ZLOGE("read result failed"); + return RDB_ERROR; + } + return RDB_OK; } -int RdbServiceProxy::RegisterClientDeathRecipient(const std::string& bundleName, sptr object) +int32_t RdbServiceProxy::DoSync(const RdbSyncerParam& param, const SyncOption &option, + const RdbPredicates &predicates, const SyncCallback& callback) +{ + SyncResult result; + if (DoSync(param, option, predicates, result) != RDB_OK) { + ZLOGI("failed"); + return RDB_ERROR; + } + ZLOGI("success"); + + if (callback != nullptr) { + callback(result); + } + return RDB_OK; +} + +int32_t RdbServiceProxy::DoAsync(const RdbSyncerParam& param, uint32_t seqNum, const SyncOption &option, + const RdbPredicates &predicates) { MessageParcel data; if (!data.WriteInterfaceToken(IRdbService::GetDescriptor())) { ZLOGE("write descriptor failed"); - return -1; + return RDB_ERROR; } - if (!data.WriteString(bundleName)) { - ZLOGE("write bundle name failed"); - return -1; + if (!DistributedKv::ITypesUtil::Marshalling(param, data)) { + ZLOGE("write param failed"); + return RDB_ERROR; } - if (!data.WriteRemoteObject(object)) { - ZLOGE("write remote object failed"); - return -1; + if (!data.WriteInt32(seqNum)) { + ZLOGE("write seq num failed"); + return RDB_ERROR; } + if (!DistributedKv::ITypesUtil::Marshalling(option, data)) { + ZLOGE("write option failed"); + return RDB_ERROR; + } + if (!DistributedKv::ITypesUtil::Marshalling(predicates, data)) { + ZLOGE("write predicates failed"); + } + + MessageParcel reply; + MessageOption opt; + if (Remote()->SendRequest(RDB_SERVICE_CMD_ASYNC, data, reply, opt) != 0) { + ZLOGE("send request failed"); + return RDB_ERROR; + } + + int32_t res = RDB_ERROR; + return reply.ReadInt32(res) ? res : RDB_ERROR; +} + +int32_t RdbServiceProxy::DoAsync(const RdbSyncerParam& param, const SyncOption &option, + const RdbPredicates &predicates, const SyncCallback& callback) +{ + uint32_t num = GetSeqNum(); + if (!syncCallbacks_.Insert(num, callback)) { + ZLOGI("insert callback failed"); + return RDB_ERROR; + } + ZLOGI("num=%{public}u", num); + + if (DoAsync(param, num, option, predicates) != RDB_OK) { + ZLOGE("failed"); + syncCallbacks_.Erase(num); + return RDB_ERROR; + } + + ZLOGI("success"); + return RDB_OK; +} + +std::vector RdbServiceProxy::GetConnectDevices() +{ + MessageParcel data; + if (!data.WriteInterfaceToken(IRdbService::GetDescriptor())) { + ZLOGE("write descriptor failed"); + return {}; + } + + MessageParcel reply; + MessageOption option; + if (Remote()->SendRequest(RDB_SERVICE_CMD_GET_DEVICES, data, reply, option) != 0) { + ZLOGE("send request failed"); + return {}; + } + + std::vector devices; + if (!reply.ReadStringVector(&devices)) { + ZLOGE("read devices failed"); + return {}; + } + + ZLOGI("success"); + return devices; +} + +int32_t RdbServiceProxy::SetDistributedTables(const RdbSyncerParam& param, const std::vector &tables) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(IRdbService::GetDescriptor())) { + ZLOGE("write descriptor failed"); + return RDB_ERROR; + } + if (!DistributedKv::ITypesUtil::Marshalling(param, data)) { + ZLOGE("write param failed"); + return RDB_ERROR; + } + if (!data.WriteStringVector(tables)) { + ZLOGE("write tables failed"); + return RDB_ERROR; + } + + MessageParcel reply; + MessageOption option; + if (Remote()->SendRequest(RDB_SERVICE_CMD_SET_DIST_TABLE, data, reply, option) != 0) { + ZLOGE("send request failed"); + return RDB_ERROR; + } + + int32_t res = RDB_ERROR; + return reply.ReadInt32(res) ? res : RDB_ERROR; +} + +int32_t RdbServiceProxy::Sync(const RdbSyncerParam& param, const SyncOption &option, + const RdbPredicates &predicates, const SyncCallback &callback) +{ + if (option.isBlock) { + return DoSync(param, option, predicates, callback); + } + return DoAsync(param, option, predicates, callback); +} + +int32_t RdbServiceProxy::Subscribe(const RdbSyncerParam ¶m, const SubscribeOption &option, + const RdbStoreObserver &observer) +{ + if (option.mode != SubscribeMode::REMOTE) { + ZLOGE("subscribe mode invalid"); + return RDB_ERROR; + } + if (DoSubscribe(param) != RDB_OK) { + ZLOGI("communicate to server failed"); + return RDB_ERROR; + } + bool present = remoteObservers_.ComputeIfPresent( + param.storeName_, [&observer] (const auto& key, ObserverMapValue& value) { + for (const auto& element : value.first) { + if (element == &observer) { + ZLOGE("duplicate observer"); + return; + } + } + value.first.push_back(const_cast(&observer)); + }); + if (!present) { + remoteObservers_.ComputeIfAbsent( + param.storeName_, [&observer, ¶m] (const auto& key) -> ObserverMapValue { + std::list list; + list.push_back(const_cast(&observer)); + return {list, param}; + }); + } + return RDB_OK; +} + +int32_t RdbServiceProxy::DoSubscribe(const RdbSyncerParam ¶m) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(IRdbService::GetDescriptor())) { + ZLOGE("write descriptor failed"); + return RDB_ERROR; + } + if (!DistributedKv::ITypesUtil::Marshalling(param, data)) { + ZLOGE("write param failed"); + return RDB_ERROR; + } + MessageParcel reply; MessageOption option; - if (Remote()->SendRequest(RDB_SERVICE_CMD_REGISTER_CLIENT_DEATH, data, reply, option) != 0) { + if (Remote()->SendRequest(RDB_SERVICE_CMD_SUBSCRIBE, data, reply, option) != 0) { ZLOGE("send request failed"); - return -1; + return RDB_ERROR; } - int32_t res = -1; - return reply.ReadInt32(res) ? res : -1; + + int32_t res = RDB_ERROR; + return reply.ReadInt32(res) ? res : RDB_ERROR; +} + +int32_t RdbServiceProxy::UnSubscribe(const RdbSyncerParam ¶m, const SubscribeOption &option, + const RdbStoreObserver &observer) +{ + DoUnSubscribe(param); + bool canErase = false; + auto* const observerPtr = const_cast(&observer); + remoteObservers_.ComputeIfPresent( + param.storeName_, [observerPtr, &canErase](const auto& key, ObserverMapValue& value) { + ZLOGI("before remove size=%{public}d", static_cast(value.first.size())); + value.first.remove(observerPtr); + ZLOGI("after remove size=%{public}d", static_cast(value.first.size())); + if (value.first.empty()) { + canErase = true; + } + }); + + if(canErase) { + remoteObservers_.Erase(param.storeName_); + } + return RDB_OK; +} + +int32_t RdbServiceProxy::DoUnSubscribe(const RdbSyncerParam ¶m) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(IRdbService::GetDescriptor())) { + ZLOGE("write descriptor failed"); + return RDB_ERROR; + } + if (!DistributedKv::ITypesUtil::Marshalling(param, data)) { + ZLOGE("write param failed"); + return RDB_ERROR; + } + + MessageParcel reply; + MessageOption option; + if (Remote()->SendRequest(RDB_SERVICE_CMD_UNSUBSCRIBE, data, reply, option) != 0) { + ZLOGE("send request failed"); + return RDB_ERROR; + } + + int32_t res = RDB_ERROR; + return reply.ReadInt32(res) ? res : RDB_ERROR; +} + +RdbServiceProxy::ObserverMap RdbServiceProxy::ExportObservers() +{ + return remoteObservers_; +} + +void RdbServiceProxy::ImportObservers(ObserverMap &observers) +{ + ZLOGI("enter"); + SubscribeOption option {SubscribeMode::REMOTE}; + observers.ForEach([this, &option](const std::string& key, const ObserverMapValue& value) { + for (const auto& observer : value.first) { + Subscribe(value.second, option, *observer); + } + return false; + }); } } \ No newline at end of file diff --git a/frameworks/innerkitsimpl/rdb/src/rdb_service_proxy.h b/frameworks/innerkitsimpl/rdb/src/rdb_service_proxy.h index 5dab528a8..df203e112 100644 --- a/frameworks/innerkitsimpl/rdb/src/rdb_service_proxy.h +++ b/frameworks/innerkitsimpl/rdb/src/rdb_service_proxy.h @@ -16,20 +16,72 @@ #ifndef DISTRIBUTED_RDB_SERVICE_PROXY_H #define DISTRIBUTED_RDB_SERVICE_PROXY_H +#include +#include #include #include "irdb_service.h" +#include "rdb_notifier.h" +#include "concurrent_map.h" namespace OHOS::DistributedRdb { class RdbServiceProxy : public IRemoteProxy { public: + using ObserverMapValue = std::pair, RdbSyncerParam>; + using ObserverMap = ConcurrentMap; + explicit RdbServiceProxy(const sptr& object); + + std::string ObtainDistributedTableName(const std::string& device, const std::string& table) override; + + std::vector GetConnectDevices() override; + + int32_t InitNotifier(const RdbSyncerParam& param); + int32_t InitNotifier(const RdbSyncerParam& param, const sptr notifier) override; - std::shared_ptr GetRdbSyncer(const RdbSyncerParam& param) override; + int32_t SetDistributedTables(const RdbSyncerParam& param, const std::vector& tables) override; - int RegisterClientDeathRecipient(const std::string& bundleName, sptr object) override; + int32_t Sync(const RdbSyncerParam& param, const SyncOption& option, + const RdbPredicates& predicates, const SyncCallback& callback) override; + + int32_t DoSync(const RdbSyncerParam& param, const SyncOption& option, + const RdbPredicates& predicates, SyncResult& result) override; + + int32_t DoAsync(const RdbSyncerParam& param, uint32_t seqNum, const SyncOption& option, + const RdbPredicates& predicates) override; + + int32_t Subscribe(const RdbSyncerParam& param, const SubscribeOption& option, + const RdbStoreObserver& observer) override; + + int32_t DoSubscribe(const RdbSyncerParam& param) override; + + int32_t UnSubscribe(const RdbSyncerParam& param, const SubscribeOption& option, + const RdbStoreObserver& observer) override; + + int32_t DoUnSubscribe(const RdbSyncerParam& param) override; + + ObserverMap ExportObservers(); + + void ImportObservers(ObserverMap& observers); private: + uint32_t GetSeqNum(); + int32_t DoSync(const RdbSyncerParam& param, const SyncOption& option, + const RdbPredicates& predicates, const SyncCallback& callback); + + int32_t DoAsync(const RdbSyncerParam& param, const SyncOption& option, + const RdbPredicates& predicates, const SyncCallback& callback); + + void OnSyncComplete(uint32_t seqNum, const SyncResult& result); + + void OnDataChange(const std::string& storeName, const std::vector& devices); + + std::atomic seqNum_ {}; + + ConcurrentMap syncCallbacks_; + ObserverMap remoteObservers_; + sptr notifier_; + static inline BrokerDelegator delegator_; }; } diff --git a/frameworks/innerkitsimpl/rdb/src/rdb_service_stub.cpp b/frameworks/innerkitsimpl/rdb/src/rdb_service_stub.cpp deleted file mode 100644 index 17808369f..000000000 --- a/frameworks/innerkitsimpl/rdb/src/rdb_service_stub.cpp +++ /dev/null @@ -1,64 +0,0 @@ -/* - * 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 "RdbServiceStub" - -#include "rdb_service_stub.h" -#include "log_print.h" -#include "irdb_syncer.h" -#include "itypes_util.h" - -namespace OHOS::DistributedRdb { -int RdbServiceStub::OnRemoteGetRdbSyncer(MessageParcel& data, MessageParcel& reply) -{ - RdbSyncerParam param; - sptr store; - if (DistributedKv::ITypesUtil::UnMarshalling(data, param)) { - store = GetRdbSyncerInner(param); - } - reply.WriteRemoteObject(store->AsObject().GetRefPtr()); - return 0; -} - -int RdbServiceStub::OnRemoteRegisterClientDeathRecipient(MessageParcel &data, MessageParcel &reply) -{ - std::string bundleName = data.ReadString(); - auto remoteObject = data.ReadRemoteObject(); - reply.WriteInt32(RegisterClientDeathRecipient(bundleName, remoteObject)); - return 0; -} - -bool RdbServiceStub::CheckInterfaceToken(MessageParcel& data) -{ - auto localDescriptor = IRdbService::GetDescriptor(); - auto remoteDescriptor = data.ReadInterfaceToken(); - if (remoteDescriptor != localDescriptor) { - ZLOGE("interface token is not equal"); - return false; - } - return true; -} -int RdbServiceStub::OnRemoteRequest(uint32_t code, MessageParcel& data, MessageParcel& reply, MessageOption& option) -{ - ZLOGI("code=%{public}d", code); - if (!CheckInterfaceToken(data)) { - return -1; - } - if (code >= 0 && code < RDB_SERVICE_CMD_MAX) { - return (this->*HANDLES[code])(data, reply); - } - return IPCObjectStub::OnRemoteRequest(code, data, reply, option); -} -} \ No newline at end of file diff --git a/frameworks/innerkitsimpl/rdb/src/rdb_syncer_proxy.cpp b/frameworks/innerkitsimpl/rdb/src/rdb_syncer_proxy.cpp deleted file mode 100644 index ede9735a8..000000000 --- a/frameworks/innerkitsimpl/rdb/src/rdb_syncer_proxy.cpp +++ /dev/null @@ -1,50 +0,0 @@ -/* - * 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 "rdb_syncer_proxy.h" - -#define LOG_TAG "RdbSyncerProxy" -#include "log_print.h" - -namespace OHOS::DistributedRdb { -RdbSyncerProxy::RdbSyncerProxy(const sptr &object) - : IRemoteProxy(object) -{ -} - -int RdbSyncerProxy::SetDistributedTables(const std::vector &tables) -{ - MessageParcel data; - if (!data.WriteInterfaceToken(IRdbSyncer::GetDescriptor())) { - ZLOGE("write descriptor failed"); - return -1; - } - if (!data.WriteStringVector(tables)) { - ZLOGE("write tables failed"); - return -1; - } - - MessageParcel reply; - MessageOption option; - if (Remote()->SendRequest(RDB_SYNCER_CMD_SET_DIST_TABLES, data, reply, option) != 0) { - ZLOGE("send request failed"); - return -1; - } - - int32_t res = -1; - return reply.ReadInt32(res) ? res : -1; -} -} - diff --git a/frameworks/innerkitsimpl/rdb/src/rdb_syncer_stub.cpp b/frameworks/innerkitsimpl/rdb/src/rdb_syncer_stub.cpp deleted file mode 100644 index 001a4cc5f..000000000 --- a/frameworks/innerkitsimpl/rdb/src/rdb_syncer_stub.cpp +++ /dev/null @@ -1,53 +0,0 @@ -/* - * 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 "RdbSyncerStub" - -#include "rdb_syncer_stub.h" -#include "log_print.h" - -namespace OHOS::DistributedRdb { -int RdbSyncerStub::OnRemoteSetDistributedTables(MessageParcel &data, MessageParcel &reply) -{ - std::vector tables; - data.ReadStringVector(&tables); - reply.WriteInt32(SetDistributedTables(tables)); - return 0; -} - -bool RdbSyncerStub::CheckInterfaceToken(MessageParcel& data) -{ - auto localDescriptor = IRdbSyncer::GetDescriptor(); - auto remoteDescriptor = data.ReadInterfaceToken(); - if (remoteDescriptor != localDescriptor) { - ZLOGE("interface token is not equal"); - return false; - } - return true; -} - -int RdbSyncerStub::OnRemoteRequest(uint32_t code, MessageParcel& data, MessageParcel& reply, MessageOption& option) -{ - ZLOGI("%{public}d", code); - if (!CheckInterfaceToken(data)) { - return -1; - } - if (code >= 0 && code < RDB_SYNCER_CMD_MAX) { - return (this->*HANDLERS[code])(data, reply); - } - return IPCObjectStub::OnRemoteRequest(code, data, reply, option); -} -} - diff --git a/frameworks/innerkitsimpl/rdb/src/rdb_syncer_stub.h b/frameworks/innerkitsimpl/rdb/src/rdb_syncer_stub.h deleted file mode 100644 index 8c72560fc..000000000 --- a/frameworks/innerkitsimpl/rdb/src/rdb_syncer_stub.h +++ /dev/null @@ -1,38 +0,0 @@ -/* - * 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 DISTRIBUTED_RDB_SYNCER_STUB_H -#define DISTRIBUTED_RDB_SYNCER_STUB_H - -#include -#include "irdb_syncer.h" - -namespace OHOS::DistributedRdb { -class RdbSyncerStub : public IRemoteStub { -public: - int OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override; - -private: - static bool CheckInterfaceToken(MessageParcel& data); - - int OnRemoteSetDistributedTables(MessageParcel &data, MessageParcel &reply); - - using RequestHandle = int (RdbSyncerStub::*)(MessageParcel &, MessageParcel &); - static constexpr RequestHandle HANDLERS[RDB_SYNCER_CMD_MAX] = { - [RDB_SYNCER_CMD_SET_DIST_TABLES] = &RdbSyncerStub::OnRemoteSetDistributedTables, - }; -}; -} -#endif diff --git a/interfaces/innerkits/distributeddata/BUILD.gn b/interfaces/innerkits/distributeddata/BUILD.gn index 9e3943606..3a255b7b6 100755 --- a/interfaces/innerkits/distributeddata/BUILD.gn +++ b/interfaces/innerkits/distributeddata/BUILD.gn @@ -76,13 +76,10 @@ ohos_shared_library("distributeddata_inner") { ] rdb_sources = [ - "../../../frameworks/innerkitsimpl/rdb/src/rdb_client_death_recipient.cpp", "../../../frameworks/innerkitsimpl/rdb/src/rdb_manager.cpp", "../../../frameworks/innerkitsimpl/rdb/src/rdb_manager_impl.cpp", + "../../../frameworks/innerkitsimpl/rdb/src/rdb_notifier.cpp", "../../../frameworks/innerkitsimpl/rdb/src/rdb_service_proxy.cpp", - "../../../frameworks/innerkitsimpl/rdb/src/rdb_service_stub.cpp", - "../../../frameworks/innerkitsimpl/rdb/src/rdb_syncer_proxy.cpp", - "../../../frameworks/innerkitsimpl/rdb/src/rdb_syncer_stub.cpp", ] sources = kvdb_sources + rdb_sources diff --git a/services/distributeddataservice/adapter/communicator/src/communication_provider_impl.cpp b/services/distributeddataservice/adapter/communicator/src/communication_provider_impl.cpp index 259fdb2b0..54d2fb31f 100755 --- a/services/distributeddataservice/adapter/communicator/src/communication_provider_impl.cpp +++ b/services/distributeddataservice/adapter/communicator/src/communication_provider_impl.cpp @@ -108,7 +108,7 @@ std::vector CommunicationProviderImpl::GetRemoteNodesBasicInfo() con std::string CommunicationProviderImpl::ToNodeId(const std::string &id) const { - std::string ret = appDeviceHandler_.ToNodeID(id, ""); + std::string ret = appDeviceHandler_.ToNodeID("", id); if (ret.empty()) { ZLOGD("toNodeId failed."); } diff --git a/services/distributeddataservice/adapter/communicator/src/softbus_adapter_standard.cpp b/services/distributeddataservice/adapter/communicator/src/softbus_adapter_standard.cpp index 758bcb121..b180c516c 100755 --- a/services/distributeddataservice/adapter/communicator/src/softbus_adapter_standard.cpp +++ b/services/distributeddataservice/adapter/communicator/src/softbus_adapter_standard.cpp @@ -404,6 +404,7 @@ std::string SoftBusAdapter::ToUUID(const std::string& id) const return ""; } +// id is return of default value std::string SoftBusAdapter::ToNodeID(const std::string& id, const std::string &nodeId) const { { @@ -413,7 +414,7 @@ std::string SoftBusAdapter::ToNodeID(const std::string& id, const std::string &n if (nodeId == (std::get<0>(tup))) { // id is uuid return e.first; } - if (id == (std::get<1>(tup))) { // id is udid + if (nodeId == (std::get<1>(tup))) { // id is udid return e.first; } } @@ -423,7 +424,7 @@ std::string SoftBusAdapter::ToNodeID(const std::string& id, const std::string &n std::vector devices; NodeBasicInfo *info = nullptr; int32_t infoNum = 0; - std::string networkId; + std::string networkId = id; int32_t ret = GetAllNodeDeviceInfo("ohos.distributeddata", &info, &infoNum); if (ret == SOFTBUS_OK) { lock_guard lock(networkMutex_); diff --git a/services/distributeddataservice/app/BUILD.gn b/services/distributeddataservice/app/BUILD.gn index 6e830702a..09bf27e27 100755 --- a/services/distributeddataservice/app/BUILD.gn +++ b/services/distributeddataservice/app/BUILD.gn @@ -45,7 +45,7 @@ config("module_private_config") { "//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/rdb", + "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/service/rdb", "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/app_distributeddata/include", "//utils/system/safwk/native/include", "../adapter/include/account", @@ -93,10 +93,10 @@ ohos_shared_library("distributeddataservice") { ] rdb_sources = [ - "../../rdb/rdb_device_syncer.cpp", - "../../rdb/rdb_service_impl.cpp", - "../../rdb/rdb_syncer_factory.cpp", - "../../rdb/rdb_syncer_impl.cpp", + "../service/rdb/rdb_service_impl.cpp", + "../service/rdb/rdb_service_stub.cpp", + "../service/rdb/rdb_store_observer_impl.cpp", + "../service/rdb/rdb_syncer.cpp", ] sources += rdb_sources diff --git a/services/distributeddataservice/app/src/kvstore_data_service.cpp b/services/distributeddataservice/app/src/kvstore_data_service.cpp index b59f3ea40..51b44b9fd 100644 --- a/services/distributeddataservice/app/src/kvstore_data_service.cpp +++ b/services/distributeddataservice/app/src/kvstore_data_service.cpp @@ -859,8 +859,7 @@ void KvStoreDataService::StartService() ZLOGI("autoLaunchRequestCallback start"); auto autoLaunchRequestCallback = [this](const std::string &identifier, DistributedDB::AutoLaunchParam ¶m) -> bool { - ResolveAutoLaunchParamByIdentifier(identifier, param); - return true; + return ResolveAutoLaunchParamByIdentifier(identifier, param); }; KvStoreDelegateManager::SetAutoLaunchRequestCallback(autoLaunchRequestCallback); @@ -875,7 +874,7 @@ void KvStoreDataService::StartService() ZLOGI("Publish ret: %d", static_cast(ret)); } -void KvStoreDataService::ResolveAutoLaunchParamByIdentifier(const std::string &identifier, +bool KvStoreDataService::ResolveAutoLaunchParamByIdentifier(const std::string &identifier, DistributedDB::AutoLaunchParam ¶m) { ZLOGI("start"); @@ -906,16 +905,19 @@ void KvStoreDataService::ResolveAutoLaunchParamByIdentifier(const std::string &i param.appId = entry.second.kvStoreMetaData.appId; param.storeId = entry.second.kvStoreMetaData.storeId; param.option = option; + return true; } } } + ZLOGI("not find identifier"); + return false; } bool KvStoreDataService::CheckPermissions(const std::string &userId, const std::string &appId, const std::string &storeId, const std::string &deviceId, uint8_t flag) const { - ZLOGI("userId=%.6s appId=%s storeId=%s flag=%d deviceId=%.4s", userId.c_str(), appId.c_str(), storeId.c_str(), flag, - deviceId.c_str()); // only print 4 chars of device id + ZLOGI("userId=%{public}.6s appId=%{public}s storeId=%{public}s flag=%{public}d deviceId=%{public}.4s", + userId.c_str(), appId.c_str(), storeId.c_str(), flag, deviceId.c_str()); // only print 4 chars of device id auto &instance = KvStoreMetaManager::GetInstance(); KvStoreMetaData metaData; auto localDevId = DeviceKvStoreImpl::GetLocalDeviceId(); diff --git a/services/distributeddataservice/app/src/kvstore_data_service.h b/services/distributeddataservice/app/src/kvstore_data_service.h index 0ec6dcdaf..9be5cf34f 100755 --- a/services/distributeddataservice/app/src/kvstore_data_service.h +++ b/services/distributeddataservice/app/src/kvstore_data_service.h @@ -157,7 +157,7 @@ private: bool CheckPermissions(const std::string &userId, const std::string &appId, const std::string &storeId, const std::string &deviceId, uint8_t flag) const; - void ResolveAutoLaunchParamByIdentifier(const std::string &identifier, DistributedDB::AutoLaunchParam ¶m); + bool ResolveAutoLaunchParamByIdentifier(const std::string &identifier, DistributedDB::AutoLaunchParam ¶m); bool CheckOptions(const Options &options, const std::vector &metaKey) const; diff --git a/services/distributeddataservice/app/src/kvstore_meta_manager.cpp b/services/distributeddataservice/app/src/kvstore_meta_manager.cpp index 046808d08..9318b9363 100755 --- a/services/distributeddataservice/app/src/kvstore_meta_manager.cpp +++ b/services/distributeddataservice/app/src/kvstore_meta_manager.cpp @@ -34,6 +34,7 @@ #include "directory_utils.h" #include "kvstore_app_manager.h" #include "utils/crypto.h" +#include "rdb_types.h" namespace OHOS { namespace DistributedKv { @@ -1032,7 +1033,7 @@ Status KvStoreMetaManager::QueryKvStoreMetaDataByDeviceIdAndAppId(const std::str } } - ZLOGW("find meta failed id:%s.", appId.c_str()); + ZLOGW("find meta failed id: %{public}s", appId.c_str()); return Status::ERROR; } @@ -1155,7 +1156,7 @@ void SecretKeyMetaData::Unmarshal(const nlohmann::json &jObject) kvStoreType = Serializable::GetVal(jObject, KVSTORE_TYPE, json::value_t::number_unsigned, kvStoreType); } -bool KvStoreMetaManager::GetFullMetaData(std::map &entries) +bool KvStoreMetaManager::GetFullMetaData(std::map &entries, enum DatabaseType type) { ZLOGI("start"); auto &metaDelegate = GetMetaKvStore(); @@ -1177,8 +1178,8 @@ bool KvStoreMetaManager::GetFullMetaData(std::map &entrie auto metaObj = Serializable::ToJson(jsonStr); MetaData metaData {0}; metaData.kvStoreType = MetaData::GetKvStoreType(metaObj); - if (metaData.kvStoreType == KvStoreType::INVALID_TYPE) { - ZLOGE("Failed to find KVSTORE_TYPE in jsonStr."); + if (!(type == KVDB && metaData.kvStoreType < KvStoreType::INVALID_TYPE) && + !(type == RDB && metaData.kvStoreType >= DistributedRdb::RdbDistributedType::RDB_DEVICE_COLLABORATION)) { continue; } diff --git a/services/distributeddataservice/app/src/kvstore_meta_manager.h b/services/distributeddataservice/app/src/kvstore_meta_manager.h index 413910b6c..c67d6b70c 100755 --- a/services/distributeddataservice/app/src/kvstore_meta_manager.h +++ b/services/distributeddataservice/app/src/kvstore_meta_manager.h @@ -146,6 +146,10 @@ private: class KvStoreMetaManager { public: static constexpr uint32_t META_STORE_VERSION = 0x03000001; + enum DatabaseType { + KVDB, + RDB, + }; using NbDelegate = std::unique_ptr>; @@ -228,7 +232,7 @@ public: bool GetKvStoreMetaDataByAppId(const std::string &appId, KvStoreMetaData &metaData); - bool GetFullMetaData(std::map &entries); + bool GetFullMetaData(std::map &entries, enum DatabaseType type = KVDB); private: NbDelegate CreateMetaKvStore(); diff --git a/services/distributeddataservice/service/rdb/rdb_service_impl.cpp b/services/distributeddataservice/service/rdb/rdb_service_impl.cpp new file mode 100644 index 000000000..2de44649f --- /dev/null +++ b/services/distributeddataservice/service/rdb/rdb_service_impl.cpp @@ -0,0 +1,351 @@ +/* + * 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 "RdbServiceImpl" + +#include "rdb_service_impl.h" +#include "account_delegate.h" +#include "checker/checker_manager.h" +#include "communication_provider.h" +#include "kvstore_utils.h" +#include "log_print.h" +#include "kvstore_meta_manager.h" + +using OHOS::DistributedKv::AccountDelegate; +using OHOS::DistributedKv::KvStoreMetaManager; +using OHOS::DistributedKv::MetaData; +using OHOS::AppDistributedKv::CommunicationProvider; +using OHOS::DistributedData::CheckerManager; +using DistributedDB::RelationalStoreManager; + +namespace OHOS::DistributedRdb { +RdbServiceImpl::DeathRecipientImpl::DeathRecipientImpl(const DeathCallback& callback) + : callback_(callback) +{ + ZLOGI("construct"); +} + +RdbServiceImpl::DeathRecipientImpl::~DeathRecipientImpl() +{ + ZLOGI("destroy"); +} + +void RdbServiceImpl::DeathRecipientImpl::OnRemoteDied(const wptr &object) +{ + ZLOGI("enter"); + if (callback_) { + callback_(); + } +} + +RdbServiceImpl::RdbServiceImpl() + : timer_("SyncerTimer", -1), autoLaunchObserver_(this) +{ + ZLOGI("construct"); + timer_.Setup(); + DistributedDB::RelationalStoreManager::SetAutoLaunchRequestCallback( + [this](const std::string& identifier, DistributedDB::AutoLaunchParam ¶m) { + return ResolveAutoLaunch(identifier, param); + }); +} + +bool RdbServiceImpl::ResolveAutoLaunch(const std::string &identifier, DistributedDB::AutoLaunchParam ¶m) +{ + std::string identifierHex = TransferStringToHex(identifier); + ZLOGI("%{public}.6s", identifierHex.c_str()); + std::map entries; + if (!KvStoreMetaManager::GetInstance().GetFullMetaData(entries, KvStoreMetaManager::RDB)) { + ZLOGE("get meta failed"); + return false; + } + ZLOGI("size=%{public}d", static_cast(entries.size())); + + for (const auto& [key, entry] : entries) { + auto aIdentifier = DistributedDB::RelationalStoreManager::GetRelationalStoreIdentifier( + entry.kvStoreMetaData.deviceAccountId, entry.kvStoreMetaData.appId, entry.kvStoreMetaData.storeId); + ZLOGI("%{public}s %{public}s %{public}s", entry.kvStoreMetaData.deviceAccountId.c_str(), + entry.kvStoreMetaData.appId.c_str(), entry.kvStoreMetaData.storeId.c_str()); + if (aIdentifier != identifier) { + continue; + } + ZLOGI("find identifier %{public}s", entry.kvStoreMetaData.storeId.c_str()); + param.userId = entry.kvStoreMetaData.deviceAccountId; + param.appId = entry.kvStoreMetaData.appId; + param.storeId = entry.kvStoreMetaData.storeId; + param.path = entry.kvStoreMetaData.dataDir; + param.option.storeObserver = &autoLaunchObserver_; + return true; + } + + ZLOGE("not find identifier"); + return false; +} + +void RdbServiceImpl::OnClientDied(pid_t pid) +{ + ZLOGI("client dead pid=%{public}d", pid); + syncers_.ComputeIfPresent(pid, [this](const auto& key, StoreSyncersType& syncers) { + syncerNum_ -= static_cast(syncers.size()); + for (const auto& [name, syncer] : syncers) { + timer_.Unregister(syncer->GetTimerId()); + } + syncers_.Erase(key); + }); + notifiers_.Erase(pid); + identifiers_.EraseIf([pid](const auto& key, pid_t& value) { + return pid == value; + }); +} + +bool RdbServiceImpl::CheckAccess(const RdbSyncerParam ¶m) +{ + return !CheckerManager::GetInstance().GetAppId(param.bundleName_, GetCallingUid()).empty(); +} + +std::string RdbServiceImpl::ObtainDistributedTableName(const std::string &device, const std::string &table) +{ + ZLOGI("device=%{public}.6s table=%{public}s", device.c_str(), table.c_str()); + auto uuid = AppDistributedKv::CommunicationProvider::GetInstance().GetUuidByNodeId(device); + if (uuid.empty()) { + ZLOGE("get uuid failed"); + return ""; + } + return DistributedDB::RelationalStoreManager::GetDistributedTableName(uuid, table); +} + +std::vector RdbServiceImpl::GetConnectDevices() +{ + auto deviceInfos = AppDistributedKv::CommunicationProvider::GetInstance().GetRemoteNodesBasicInfo(); + std::vector devices; + for (const auto& deviceInfo : deviceInfos) { + devices.push_back(deviceInfo.deviceId); + } + ZLOGI("size=%{public}u", static_cast(devices.size())); + for (const auto& device: devices) { + ZLOGI("%{public}.6s", device.c_str()); + } + return devices; +} + +int32_t RdbServiceImpl::InitNotifier(const RdbSyncerParam& param, const sptr notifier) +{ + if (!CheckAccess(param)) { + ZLOGE("permission error"); + return RDB_ERROR; + } + + pid_t pid = GetCallingPid(); + auto recipient = new(std::nothrow) DeathRecipientImpl([this, pid] { + OnClientDied(pid); + }); + if (recipient == nullptr) { + ZLOGE("malloc recipient failed"); + return RDB_ERROR; + } + + if (!notifier->AddDeathRecipient(recipient)) { + ZLOGE("link to death failed"); + return RDB_ERROR; + } + notifiers_.Insert(pid, iface_cast(notifier)); + ZLOGI("success pid=%{public}d", pid); + + return RDB_OK; +} + +void RdbServiceImpl::OnDataChange(pid_t pid, const DistributedDB::StoreChangedData &data) +{ + DistributedDB::StoreProperty property; + data.GetStoreProperty(property); + ZLOGI("%{public}d %{public}s", pid, property.storeId.c_str()); + if (pid == 0) { + auto identifier = RelationalStoreManager::GetRelationalStoreIdentifier(property.userId, property.appId, + property.storeId); + auto pair = identifiers_.Find(TransferStringToHex(identifier)); + if (!pair.first) { + ZLOGI("client doesn't subscribe"); + return; + } + pid = pair.second; + ZLOGI("fixed pid=%{public}d", pid); + } + notifiers_.ComputeIfPresent(pid, [&data, &property] (const auto& key, const sptr& value) { + std::string device = data.GetDataChangeDevice(); + auto networkId = CommunicationProvider::GetInstance().ToNodeId(device); + value->OnChange(property.storeId, { networkId }); + }); +} + +void RdbServiceImpl::SyncerTimeout(std::shared_ptr syncer) +{ + ZLOGI("%{public}s", syncer->GetStoreId().c_str()); + syncers_.ComputeIfPresent(syncer->GetPid(), [this, &syncer](const auto& key, StoreSyncersType& syncers) { + syncers.erase(syncer->GetStoreId()); + syncerNum_--; + }); +} + +std::shared_ptr RdbServiceImpl::GetRdbSyncer(const RdbSyncerParam ¶m) +{ + if (!CheckAccess(param)) { + ZLOGE("permission error"); + return nullptr; + } + + pid_t pid = GetCallingPid(); + pid_t uid = GetCallingUid(); + std::shared_ptr syncer; + + bool present = syncers_.ComputeIfPresent(pid, + [this, ¶m, pid, uid, &syncer] (const auto& key, StoreSyncersType& syncers) { + auto it = syncers.find(param.storeName_); + if (it != syncers.end()) { + syncer = it->second; + timer_.Unregister(syncer->GetTimerId()); + uint32_t timerId = timer_.Register([this, syncer]() { SyncerTimeout(syncer); }, SYNCER_TIMEOUT, true); + syncer->SetTimerId(timerId); + return; + } + if (syncers.size() >= MAX_PROCESS_SYNCER_NUM) { + ZLOGE("%{public}d exceed MAX_PROCESS_SYNCER_NUM", pid); + return; + } + if (syncerNum_ >= MAX_SYNCER_NUM) { + ZLOGE("no available syncer"); + return; + } + auto syncer_ = std::make_shared(param, new (std::nothrow) RdbStoreObserverImpl(this, pid)); + if (syncer_->Init(pid, uid) != 0) { + return; + } + syncers[param.storeName_] = syncer_; + syncer = syncer_; + syncerNum_++; + uint32_t timerId = timer_.Register([this, syncer]() { SyncerTimeout(syncer); }, SYNCER_TIMEOUT, true); + syncer->SetTimerId(timerId); + }); + + if (!present) { + syncers_.ComputeIfAbsent(pid, [this, ¶m, pid, uid, &syncer] (const auto& key) { + StoreSyncersType syncers; + if (syncerNum_ >= MAX_SYNCER_NUM) { + ZLOGE("no available syncer"); + return syncers; + } + auto syncer_ = std::make_shared(param, new (std::nothrow) RdbStoreObserverImpl(this, pid)); + if (syncer_->Init(pid, uid) != 0) { + return syncers; + } + syncers[param.storeName_] = syncer_; + syncer = syncer_; + syncerNum_++; + uint32_t timerId = timer_.Register([this, syncer]() { SyncerTimeout(syncer); }, SYNCER_TIMEOUT, true); + syncer->SetTimerId(timerId); + return syncers; + }); + } + + if (syncer != nullptr) { + identifiers_.Insert(syncer->GetIdentifier(), pid); + } + if (syncer == nullptr) { + ZLOGE("syncer is nullptr"); + } + return syncer; +} + +int32_t RdbServiceImpl::SetDistributedTables(const RdbSyncerParam ¶m, const std::vector &tables) +{ + ZLOGI("enter"); + auto syncer = GetRdbSyncer(param); + if (syncer == nullptr) { + return RDB_ERROR; + } + return syncer->SetDistributedTables(tables); +} + +int32_t RdbServiceImpl::DoSync(const RdbSyncerParam ¶m, const SyncOption &option, + const RdbPredicates &predicates, SyncResult &result) +{ + auto syncer = GetRdbSyncer(param); + if (syncer == nullptr) { + return RDB_ERROR; + } + return syncer->DoSync(option, predicates, result); +} + +void RdbServiceImpl::OnAsyncComplete(pid_t pid, uint32_t seqNum, const SyncResult &result) +{ + ZLOGI("pid=%{public}d seqnum=%{public}u", pid, seqNum); + notifiers_.ComputeIfPresent(pid, [seqNum, &result] (const auto& key, const sptr& value) { + value->OnComplete(seqNum, result); + }); +} + +int32_t RdbServiceImpl::DoAsync(const RdbSyncerParam ¶m, uint32_t seqNum, const SyncOption &option, + const RdbPredicates &predicates) +{ + pid_t pid = GetCallingPid(); + ZLOGI("seq num=%{public}u", seqNum); + auto syncer = GetRdbSyncer(param); + if (syncer == nullptr) { + return RDB_ERROR; + } + return syncer->DoAsync(option, predicates, [this, pid, seqNum] (const SyncResult& result) { + OnAsyncComplete(pid, seqNum, result); + }); +} + +std::string RdbServiceImpl::TransferStringToHex(const std::string &origStr) +{ + if (origStr.empty()) { + return ""; + } + const char *hex = "0123456789abcdef"; + std::string tmp; + for (auto item : origStr) { + auto currentByte = static_cast(item); + tmp.push_back(hex[currentByte >> 4]); // high 4 bit to one hex. + tmp.push_back(hex[currentByte & 0x0F]); // low 4 bit to one hex. + } + return tmp; +} + +std::string RdbServiceImpl::GenIdentifier(const RdbSyncerParam ¶m) +{ + pid_t uid = GetCallingUid(); + std::string userId = AccountDelegate::GetInstance()->GetDeviceAccountIdByUID(uid); + std::string appId = CheckerManager::GetInstance().GetAppId(param.bundleName_, uid); + std::string identifier = RelationalStoreManager::GetRelationalStoreIdentifier(userId, appId, param.storeName_); + return TransferStringToHex(identifier); +} + +int32_t RdbServiceImpl::DoSubscribe(const RdbSyncerParam& param) +{ + pid_t pid = GetCallingPid(); + auto identifier = GenIdentifier(param); + ZLOGI("%{public}s %{public}.6s %{public}d", param.storeName_.c_str(), identifier.c_str(), pid); + identifiers_.Insert(identifier, pid); + return RDB_OK; +} + +int32_t RdbServiceImpl::DoUnSubscribe(const RdbSyncerParam& param) +{ + auto identifier = GenIdentifier(param); + ZLOGI("%{public}s %{public}.6s", param.storeName_.c_str(), identifier.c_str()); + identifiers_.Erase(identifier); + return RDB_OK; +} +} \ No newline at end of file diff --git a/services/rdb/rdb_service_impl.h b/services/distributeddataservice/service/rdb/rdb_service_impl.h similarity index 30% rename from services/rdb/rdb_service_impl.h rename to services/distributeddataservice/service/rdb/rdb_service_impl.h index 42b9bf1ef..f9e1f6abe 100644 --- a/services/rdb/rdb_service_impl.h +++ b/services/distributeddataservice/service/rdb/rdb_service_impl.h @@ -21,36 +21,75 @@ #include #include #include -#include "rdb_syncer_impl.h" +#include "rdb_syncer.h" #include "concurrent_map.h" +#include "store_observer.h" +#include "timer.h" namespace OHOS::DistributedRdb { class RdbServiceImpl : public RdbServiceStub { public: - sptr GetRdbSyncerInner(const RdbSyncerParam& param) override; - - int RegisterClientDeathRecipient(const std::string& bundleName, sptr proxy) override; + RdbServiceImpl(); + + void OnClientDied(pid_t pid); - void OnClientDied(pid_t pid, sptr& proxy); + /* IPC interface */ + std::string ObtainDistributedTableName(const std::string& device, const std::string& table) override; -private: - sptr CreateSyncer(const RdbSyncerParam& param, pid_t uid, pid_t pid); + std::vector GetConnectDevices() override; + + int32_t InitNotifier(const RdbSyncerParam& param, const sptr notifier) override; - void ClearClientRecipient(sptr& proxy); + int32_t SetDistributedTables(const RdbSyncerParam& param, const std::vector& tables) override; - void ClearClientSyncers(pid_t pid); + int32_t DoSync(const RdbSyncerParam& param, const SyncOption& option, + const RdbPredicates& predicates, SyncResult& result) override; - class ClientDeathRecipient : public DeathRecipient { + int32_t DoAsync(const RdbSyncerParam& param, uint32_t seqNum, const SyncOption& option, + const RdbPredicates& predicates) override; + + int32_t DoSubscribe(const RdbSyncerParam& param) override; + + int32_t DoUnSubscribe(const RdbSyncerParam& param) override; + + void OnDataChange(pid_t pid, const DistributedDB::StoreChangedData& data); + +private: + std::string GenIdentifier(const RdbSyncerParam& param); + + bool CheckAccess(const RdbSyncerParam& param); + + bool ResolveAutoLaunch(const std::string &identifier, DistributedDB::AutoLaunchParam ¶m); + + void SyncerTimeout(std::shared_ptr syncer); + + std::shared_ptr GetRdbSyncer(const RdbSyncerParam& param); + + void OnAsyncComplete(pid_t pid, uint32_t seqNum, const SyncResult& result); + + class DeathRecipientImpl : public DeathRecipient { public: - explicit ClientDeathRecipient(std::function&)> callback); - ~ClientDeathRecipient() override; + using DeathCallback = std::function; + explicit DeathRecipientImpl(const DeathCallback& callback); + ~DeathRecipientImpl() override; void OnRemoteDied(const wptr &object) override; private: - std::function&)> callback_; + const DeathCallback callback_; }; - - ConcurrentMap>> syncers_; // identifier - ConcurrentMap, sptr> recipients_; + + using StoreSyncersType = std::map>; + int32_t syncerNum_ {}; + ConcurrentMap syncers_; + ConcurrentMap> notifiers_; + ConcurrentMap identifiers_; + Utils::Timer timer_; + RdbStoreObserverImpl autoLaunchObserver_; + + static std::string TransferStringToHex(const std::string& origStr); + + static constexpr int32_t MAX_SYNCER_NUM = 50; + static constexpr int32_t MAX_PROCESS_SYNCER_NUM = 10; + static constexpr int32_t SYNCER_TIMEOUT = 60 * 1000; // ms }; } #endif diff --git a/services/distributeddataservice/service/rdb/rdb_service_stub.cpp b/services/distributeddataservice/service/rdb/rdb_service_stub.cpp new file mode 100644 index 000000000..797d532f8 --- /dev/null +++ b/services/distributeddataservice/service/rdb/rdb_service_stub.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. + */ + +#define LOG_TAG "RdbServiceStub" + +#include "rdb_service_stub.h" +#include "log_print.h" +#include "itypes_util.h" + +namespace OHOS::DistributedRdb { +int32_t RdbServiceStub::OnRemoteObtainDistributedTableName(MessageParcel &data, MessageParcel &reply) +{ + std::string device; + if (!data.ReadString(device)) { + ZLOGE("read device failed"); + reply.WriteString(""); + return RDB_OK; + } + + std::string table; + if (!data.ReadString(table)) { + ZLOGE("read table failed"); + reply.WriteString(""); + return RDB_OK; + } + + reply.WriteString(ObtainDistributedTableName(device, table)); + return RDB_OK; +} + +int32_t RdbServiceStub::OnRemoteGetConnectDevices(MessageParcel& data, MessageParcel& reply) +{ + std::vector devices = GetConnectDevices(); + if (!reply.WriteStringVector(devices)) { + ZLOGE("write devices failed"); + } + + return RDB_OK; +} + +int32_t RdbServiceStub::OnRemoteInitNotifier(MessageParcel &data, MessageParcel &reply) +{ + int32_t error = RDB_ERROR; + RdbSyncerParam param; + if (!DistributedKv::ITypesUtil::UnMarshalling(data, param)) { + ZLOGE("read param failed"); + reply.WriteInt32(RDB_ERROR); + return RDB_OK; + } + auto notifier = data.ReadRemoteObject(); + if (notifier == nullptr) { + ZLOGE("read object failed"); + reply.WriteInt32(error); + return RDB_OK; + } + if (InitNotifier(param, notifier) != RDB_OK) { + ZLOGE("init notifier failed"); + reply.WriteInt32(error); + return RDB_OK; + } + ZLOGI("success"); + reply.WriteInt32(RDB_OK); + return RDB_OK; +} + +int32_t RdbServiceStub::OnRemoteSetDistributedTables(MessageParcel &data, MessageParcel &reply) +{ + RdbSyncerParam param; + if (!DistributedKv::ITypesUtil::UnMarshalling(data, param)) { + ZLOGE("read param failed"); + reply.WriteInt32(RDB_ERROR); + return RDB_OK; + } + std::vector tables; + data.ReadStringVector(&tables); + reply.WriteInt32(SetDistributedTables(param, tables)); + return RDB_OK; +} + +int32_t RdbServiceStub::OnRemoteDoSync(MessageParcel &data, MessageParcel &reply) +{ + RdbSyncerParam param; + if (!DistributedKv::ITypesUtil::UnMarshalling(data, param)) { + ZLOGE("read param failed"); + reply.WriteInt32(RDB_ERROR); + return RDB_OK; + } + SyncOption option {}; + if (!DistributedKv::ITypesUtil::UnMarshalling(data, option)) { + ZLOGE("read option failed"); + reply.WriteInt32(RDB_ERROR); + return RDB_OK; + } + RdbPredicates predicates; + if (!DistributedKv::ITypesUtil::UnMarshalling(data, predicates)) { + ZLOGE("read predicates failed"); + reply.WriteInt32(RDB_ERROR); + return RDB_OK; + } + + SyncResult result; + if (DoSync(param, option, predicates, result) != RDB_OK) { + reply.WriteInt32(RDB_ERROR); + return RDB_OK; + } + if (!DistributedKv::ITypesUtil::Marshalling(result, reply)) { + reply.WriteInt32(RDB_ERROR); + return RDB_OK; + } + return RDB_OK; +} + +int32_t RdbServiceStub::OnRemoteDoAsync(MessageParcel &data, MessageParcel &reply) +{ + RdbSyncerParam param; + if (!DistributedKv::ITypesUtil::UnMarshalling(data, param)) { + ZLOGE("read param failed"); + reply.WriteInt32(RDB_ERROR); + return RDB_OK; + } + uint32_t seqNum; + if (!data.ReadUint32(seqNum)) { + ZLOGI("read seq num failed"); + reply.WriteInt32(RDB_ERROR); + return RDB_OK; + } + SyncOption option {}; + if (!DistributedKv::ITypesUtil::UnMarshalling(data, option)) { + ZLOGE("read option failed"); + reply.WriteInt32(RDB_ERROR); + return RDB_OK; + } + RdbPredicates predicates; + if (!DistributedKv::ITypesUtil::UnMarshalling(data, predicates)) { + ZLOGE("read predicates failed"); + reply.WriteInt32(RDB_ERROR); + return RDB_OK; + } + + reply.WriteInt32(DoAsync(param, seqNum, option, predicates)); + return RDB_OK; +} + +int32_t RdbServiceStub::OnRemoteDoSubscribe(MessageParcel &data, MessageParcel &reply) +{ + RdbSyncerParam param; + if (!DistributedKv::ITypesUtil::UnMarshalling(data, param)) { + ZLOGE("read param failed"); + reply.WriteInt32(RDB_ERROR); + return RDB_OK; + } + reply.WriteInt32(DoSubscribe(param)); + return RDB_OK; +} + +int32_t RdbServiceStub::OnRemoteDoUnSubscribe(MessageParcel &data, MessageParcel &reply) +{ + RdbSyncerParam param; + if (!DistributedKv::ITypesUtil::UnMarshalling(data, param)) { + ZLOGE("read param failed"); + reply.WriteInt32(RDB_ERROR); + return RDB_OK; + } + reply.WriteInt32(DoUnSubscribe(param)); + return RDB_OK; +} + +bool RdbServiceStub::CheckInterfaceToken(MessageParcel& data) +{ + auto localDescriptor = IRdbService::GetDescriptor(); + auto remoteDescriptor = data.ReadInterfaceToken(); + if (remoteDescriptor != localDescriptor) { + ZLOGE("interface token is not equal"); + return false; + } + return true; +} + +int RdbServiceStub::OnRemoteRequest(uint32_t code, MessageParcel& data, MessageParcel& reply, MessageOption& option) +{ + ZLOGI("code=%{public}d", code); + if (!CheckInterfaceToken(data)) { + return RDB_ERROR; + } + if (code >= 0 && code < RDB_SERVICE_CMD_MAX) { + return (this->*HANDLERS[code])(data, reply); + } + return IPCObjectStub::OnRemoteRequest(code, data, reply, option); +} +} \ No newline at end of file diff --git a/frameworks/innerkitsimpl/rdb/src/rdb_service_stub.h b/services/distributeddataservice/service/rdb/rdb_service_stub.h similarity index 34% rename from frameworks/innerkitsimpl/rdb/src/rdb_service_stub.h rename to services/distributeddataservice/service/rdb/rdb_service_stub.h index 3eeab5ce4..1416fbe0d 100644 --- a/frameworks/innerkitsimpl/rdb/src/rdb_service_stub.h +++ b/services/distributeddataservice/service/rdb/rdb_service_stub.h @@ -18,26 +18,60 @@ #include #include "irdb_service.h" +#include "rdb_notifier.h" namespace OHOS::DistributedRdb { class RdbServiceStub : public IRemoteStub { public: int OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override; - - std::shared_ptr GetRdbSyncer(const RdbSyncerParam& param) override { return nullptr; }; - virtual sptr GetRdbSyncerInner(const RdbSyncerParam& param) = 0; - + + int32_t Sync(const RdbSyncerParam& param, const SyncOption& option, + const RdbPredicates& predicates, const SyncCallback& callback) override + { + return 0; + } + + int32_t Subscribe(const RdbSyncerParam& param, const SubscribeOption& option, + const RdbStoreObserver& observer) override + { + return 0; + } + + int32_t UnSubscribe(const RdbSyncerParam& param, const SubscribeOption& option, + const RdbStoreObserver& observer) override + { + return 0; + } + private: static bool CheckInterfaceToken(MessageParcel& data); + + int32_t OnRemoteObtainDistributedTableName(MessageParcel& data, MessageParcel& reply); + + int32_t OnRemoteGetConnectDevices(MessageParcel& data, MessageParcel& reply); + + int32_t OnRemoteInitNotifier(MessageParcel&data, MessageParcel& reply); - int OnRemoteGetRdbSyncer(MessageParcel& data, MessageParcel& reply); + int32_t OnRemoteSetDistributedTables(MessageParcel &data, MessageParcel &reply); - int OnRemoteRegisterClientDeathRecipient(MessageParcel& data, MessageParcel& reply); + int32_t OnRemoteDoSync(MessageParcel& data, MessageParcel& reply); - using RequestHandle = int (RdbServiceStub::*)(MessageParcel&, MessageParcel&); - static constexpr RequestHandle HANDLES[RDB_SERVICE_CMD_MAX] = { - [RDB_SERVICE_CMD_GET_SYNCER] = &RdbServiceStub::OnRemoteGetRdbSyncer, - [RDB_SERVICE_CMD_REGISTER_CLIENT_DEATH] = &RdbServiceStub::OnRemoteRegisterClientDeathRecipient, + int32_t OnRemoteDoAsync(MessageParcel& data, MessageParcel& reply); + + int32_t OnRemoteDoSubscribe(MessageParcel& data, MessageParcel& reply); + + int32_t OnRemoteDoUnSubscribe(MessageParcel& data, MessageParcel& reply); + + using RequestHandle = int (RdbServiceStub::*)(MessageParcel &, MessageParcel &); + static constexpr RequestHandle HANDLERS[RDB_SERVICE_CMD_MAX] = { + [RDB_SERVICE_CMD_OBTAIN_TABLE] = &RdbServiceStub::OnRemoteObtainDistributedTableName, + [RDB_SERVICE_CMD_GET_DEVICES] = &RdbServiceStub::OnRemoteGetConnectDevices, + [RDB_SERVICE_CMD_INIT_NOTIFIER] = &RdbServiceStub::OnRemoteInitNotifier, + [RDB_SERVICE_CMD_SET_DIST_TABLE] = &RdbServiceStub::OnRemoteSetDistributedTables, + [RDB_SERVICE_CMD_SYNC] = &RdbServiceStub::OnRemoteDoSync, + [RDB_SERVICE_CMD_ASYNC] = &RdbServiceStub::OnRemoteDoAsync, + [RDB_SERVICE_CMD_SUBSCRIBE] = &RdbServiceStub::OnRemoteDoSubscribe, + [RDB_SERVICE_CMD_UNSUBSCRIBE] = &RdbServiceStub::OnRemoteDoUnSubscribe, }; }; } diff --git a/frameworks/innerkitsimpl/rdb/src/rdb_service.h b/services/distributeddataservice/service/rdb/rdb_store_observer_impl.cpp similarity index 55% rename from frameworks/innerkitsimpl/rdb/src/rdb_service.h rename to services/distributeddataservice/service/rdb/rdb_store_observer_impl.cpp index 7168c9b74..bc5a16f56 100644 --- a/frameworks/innerkitsimpl/rdb/src/rdb_service.h +++ b/services/distributeddataservice/service/rdb/rdb_store_observer_impl.cpp @@ -13,23 +13,29 @@ * limitations under the License. */ -#ifndef DISTRIBUTED_RDB_SERVICE_H -#define DISTRIBUTED_RDB_SERVICE_H +#define LOG_TAG "RdbStoreObserverImpl" -#include -#include - -#include +#include "rdb_store_observer_impl.h" +#include "rdb_service_impl.h" +#include "log_print.h" namespace OHOS::DistributedRdb { -struct RdbSyncerParam; -class RdbSyncer; +RdbStoreObserverImpl::RdbStoreObserverImpl(RdbServiceImpl* owner, pid_t pid) + : pid_(pid), owner_(owner) +{ + ZLOGI("construct"); +} -class RdbService { -public: - virtual std::shared_ptr GetRdbSyncer(const RdbSyncerParam& param) = 0; - - virtual int RegisterClientDeathRecipient(const std::string& bundleName, sptr object) = 0; -}; +RdbStoreObserverImpl::~RdbStoreObserverImpl() +{ + ZLOGI("destroy"); +} + +void RdbStoreObserverImpl::OnChange(const DistributedDB::StoreChangedData &data) +{ + ZLOGI("enter"); + if (owner_ != nullptr) { + owner_->OnDataChange(pid_, data); + } +} } -#endif diff --git a/frameworks/innerkitsimpl/rdb/src/rdb_syncer_proxy.h b/services/distributeddataservice/service/rdb/rdb_store_observer_impl.h similarity index 59% rename from frameworks/innerkitsimpl/rdb/src/rdb_syncer_proxy.h rename to services/distributeddataservice/service/rdb/rdb_store_observer_impl.h index eff2a15ae..7a48831d4 100644 --- a/frameworks/innerkitsimpl/rdb/src/rdb_syncer_proxy.h +++ b/services/distributeddataservice/service/rdb/rdb_store_observer_impl.h @@ -13,21 +13,26 @@ * limitations under the License. */ -#ifndef DISTRIBUTED_RDB_STORE_PROXY_H -#define DISTRIBUTED_RDB_STORE_PROXY_H +#ifndef DISTRIBUTED_RDB_STORE_OBSERVER_H +#define DISTRIBUTED_RDB_STORE_OBSERVER_H -#include -#include "irdb_syncer.h" +#include +#include "store_observer.h" namespace OHOS::DistributedRdb { -class RdbSyncerProxy : public IRemoteProxy { +class RdbServiceImpl; +class RdbStoreObserverImpl : public DistributedDB::StoreObserver { public: - explicit RdbSyncerProxy(const sptr& object); - - int SetDistributedTables(const std::vector& tables) override; + explicit RdbStoreObserverImpl(RdbServiceImpl* owner, pid_t pid = 0); + + ~RdbStoreObserverImpl() override; + + void OnChange(const DistributedDB::StoreChangedData &data) override; private: - static inline BrokerDelegator delegator_; + pid_t pid_ {}; + RdbServiceImpl* owner_ {}; }; + } #endif diff --git a/services/distributeddataservice/service/rdb/rdb_syncer.cpp b/services/distributeddataservice/service/rdb/rdb_syncer.cpp new file mode 100644 index 000000000..38450e8e6 --- /dev/null +++ b/services/distributeddataservice/service/rdb/rdb_syncer.cpp @@ -0,0 +1,302 @@ +/* + * 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 "RdbSyncer" + +#include "rdb_syncer.h" + +#include "account_delegate.h" +#include "checker/checker_manager.h" +#include "log_print.h" +#include "kvstore_utils.h" +#include "kvstore_meta_manager.h" + +using OHOS::DistributedKv::AccountDelegate; +using OHOS::DistributedKv::KvStoreMetaManager; +using OHOS::AppDistributedKv::CommunicationProvider; + +namespace OHOS::DistributedRdb { +RdbSyncer::RdbSyncer(const RdbSyncerParam& param, RdbStoreObserverImpl* observer) + : param_(param), observer_(observer) +{ + ZLOGI("construct %{public}s", param_.storeName_.c_str()); +} + +RdbSyncer::~RdbSyncer() noexcept +{ + ZLOGI("destroy %{public}s", param_.storeName_.c_str()); + if (manager_ != nullptr & delegate_ != nullptr) { + manager_->CloseStore(delegate_); + } + delete manager_; + if (observer_ != nullptr) { + delete observer_; + } +} + +void RdbSyncer::SetTimerId(uint32_t timerId) +{ + timerId_ = timerId; +} + +uint32_t RdbSyncer::GetTimerId() const +{ + return timerId_; +} + +pid_t RdbSyncer::GetPid() const +{ + return pid_; +} + +std::string RdbSyncer::GetIdentifier() const +{ + return DistributedDB::RelationalStoreManager::GetRelationalStoreIdentifier(GetUserId(), GetAppId(), GetStoreId()); +} + +std::string RdbSyncer::GetUserId() const +{ + return AccountDelegate::GetInstance()->GetDeviceAccountIdByUID(uid_); +} + +std::string RdbSyncer::GetBundleName() const +{ + return param_.bundleName_; +} + +std::string RdbSyncer::GetAppId() const +{ + return DistributedData::CheckerManager::GetInstance().GetAppId(param_.bundleName_, uid_); +} + +std::string RdbSyncer::GetPath() const +{ + return param_.path_; +} + +std::string RdbSyncer::GetStoreId() const +{ + return param_.storeName_; +} + +int32_t RdbSyncer::Init(pid_t pid, pid_t uid) +{ + ZLOGI("enter"); + pid_ = pid; + uid_ = uid; + if (CreateMetaData() != RDB_OK) { + ZLOGE("create meta data failed"); + return RDB_ERROR; + } + ZLOGI("success"); + return RDB_OK; +} + +int32_t RdbSyncer::CreateMetaData() +{ + DistributedKv::KvStoreMetaData meta; + meta.kvStoreType =static_cast(RDB_DEVICE_COLLABORATION); + meta.appId = GetAppId(); + meta.appType = "harmony"; + meta.bundleName = GetBundleName(); + meta.deviceId = CommunicationProvider::GetInstance().GetLocalDevice().deviceId; + meta.storeId = GetStoreId(); + meta.userId = AccountDelegate::GetInstance()->GetCurrentAccountId(GetBundleName()); + meta.uid = uid_; + meta.deviceAccountId = AccountDelegate::GetInstance()->GetDeviceAccountIdByUID(uid_); + meta.dataDir = GetPath(); + + std::string metaString = meta.Marshal(); + std::vector metaValue(metaString.begin(), metaString.end()); + auto metaKey = KvStoreMetaManager::GetMetaKey(meta.deviceAccountId, "default", meta.bundleName, meta.storeId); + DistributedKv::KvStoreMetaData oldMeta; + if (KvStoreMetaManager::GetInstance().GetKvStoreMeta(metaKey, oldMeta) == DistributedKv::Status::SUCCESS) { + if (metaString == oldMeta.Marshal()) { + ZLOGI("ignore same meta"); + return RDB_OK; + } + } + auto status = KvStoreMetaManager::GetInstance().CheckUpdateServiceMeta(metaKey, DistributedKv::UPDATE, metaValue); + return static_cast(status); +} + +DistributedDB::RelationalStoreDelegate* RdbSyncer::GetDelegate() +{ + std::lock_guard lock(mutex_); + if (manager_ == nullptr) { + manager_ = new(std::nothrow) DistributedDB::RelationalStoreManager(GetAppId(), GetUserId()); + } + if (manager_ == nullptr) { + ZLOGE("malloc manager failed"); + return nullptr; + } + + if (delegate_ == nullptr) { + DistributedDB::RelationalStoreDelegate::Option option; + option.observer = observer_; + ZLOGI("path=%{public}s storeId=%{public}s", GetPath().c_str(), GetStoreId().c_str()); + DistributedDB::DBStatus status = manager_->OpenStore(GetPath(), GetStoreId(), option, delegate_); + if (status != DistributedDB::DBStatus::OK) { + ZLOGE("open store failed status=%{public}d", status); + return nullptr; + } + ZLOGI("open store success"); + } + + return delegate_; +} + +int32_t RdbSyncer::SetDistributedTables(const std::vector &tables) +{ + auto* delegate = GetDelegate(); + if (delegate == nullptr) { + ZLOGE("delegate is nullptr"); + return RDB_ERROR; + } + + for (const auto& table : tables) { + ZLOGI("%{public}s", table.c_str()); + if (delegate->CreateDistributedTable(table) != DistributedDB::DBStatus::OK) { + ZLOGE("create distributed table failed"); + return RDB_ERROR; + } + } + ZLOGE("create distributed table success"); + return RDB_OK; +} + +std::vector RdbSyncer::NetworkIdToUUID(const std::vector &networkIds) +{ + std::vector uuids; + for (const auto& networkId : networkIds) { + auto uuid = CommunicationProvider::GetInstance().GetUuidByNodeId(networkId); + if (uuid.empty()) { + ZLOGE("%{public}.6s failed", networkId.c_str()); + continue; + } + uuids.push_back(uuid); + } + return uuids; +} + +void RdbSyncer::HandleSyncStatus(const std::map> &syncStatus, + SyncResult &result) +{ + for (const auto& status : syncStatus) { + auto res = DistributedDB::DBStatus::OK; + for (const auto& tableStatus : status.second) { + if (tableStatus.status != DistributedDB::DBStatus::OK) { + res = tableStatus.status; + break; + } + } + std::string uuid = CommunicationProvider::GetInstance().ToNodeId(status.first); + if (uuid.empty()) { + ZLOGE("%{public}.6s failed", status.first.c_str()); + continue; + } + ZLOGI("%{public}.6s=%{public}d", uuid.c_str(), res); + result[uuid] = res; + } +} +void RdbSyncer::EqualTo(const RdbPredicateOperation &operation, DistributedDB::Query &query) +{ + query.EqualTo(operation.field_, operation.values_[0]); + ZLOGI("field=%{public}s value=%{public}s", operation.field_.c_str(), operation.values_[0].c_str()); +} + +void RdbSyncer::NotEqualTo(const RdbPredicateOperation &operation, DistributedDB::Query &query) +{ + query.NotEqualTo(operation.field_, operation.values_[0]); + ZLOGI("field=%{public}s value=%{public}s", operation.field_.c_str(), operation.values_[0].c_str()); +} + +void RdbSyncer::And(const RdbPredicateOperation &operation, DistributedDB::Query &query) +{ + query.And(); + ZLOGI(""); +} + +void RdbSyncer::Or(const RdbPredicateOperation &operation, DistributedDB::Query &query) +{ + query.Or(); + ZLOGI(""); +} + +void RdbSyncer::OrderBy(const RdbPredicateOperation &operation, DistributedDB::Query &query) +{ + bool isAsc = operation.values_[0] == "true"; + query.OrderBy(operation.field_, isAsc); + ZLOGI("field=%{public}s isAsc=%{public}s", operation.field_.c_str(), operation.values_[0].c_str()); +} + +void RdbSyncer::Limit(const RdbPredicateOperation &operation, DistributedDB::Query &query) +{ + char *end = nullptr; + int limit = static_cast(strtol(operation.field_.c_str(), &end, 10)); // 10 base number + int offset = static_cast(strtol(operation.values_[0].c_str(), &end, 10)); // 10 base number + query.Limit(limit, offset); + ZLOGI("limit=%{public}d offset=%{public}d", limit, offset); +} + +DistributedDB::Query RdbSyncer::MakeQuery(const RdbPredicates &predicates) +{ + ZLOGI("table=%{public}s", predicates.table_.c_str()); + auto query = DistributedDB::Query::Select(predicates.table_); + for (const auto& device : predicates.devices_) { + ZLOGI("device=%{public}.6s", device.c_str()); + } + for (const auto& operation : predicates.operations_) { + if (operation.operator_ >= 0 && operation.operator_ < OPERATOR_MAX) { + HANDLES[operation.operator_](operation, query); + } + } + return query; +} + +int32_t RdbSyncer::DoSync(const SyncOption &option, const RdbPredicates &predicates, SyncResult &result) +{ + ZLOGI("enter"); + auto* delegate = GetDelegate(); + if (delegate == nullptr) { + ZLOGE("delegate is nullptr"); + return RDB_ERROR; + } + + auto devices = NetworkIdToUUID(predicates.devices_); + ZLOGI("delegate sync"); + return delegate->Sync(devices, static_cast(option.mode), + MakeQuery(predicates), [&result] (const auto& syncStatus) { + HandleSyncStatus(syncStatus, result); + }, true); +} + +int32_t RdbSyncer::DoAsync(const SyncOption &option, const RdbPredicates &predicates, const SyncCallback& callback) +{ + auto* delegate = GetDelegate(); + if (delegate == nullptr) { + ZLOGE("delegate is nullptr"); + return RDB_ERROR; + } + auto devices = NetworkIdToUUID(predicates.devices_); + ZLOGI("delegate sync"); + return delegate->Sync(devices, static_cast(option.mode), + MakeQuery(predicates), [callback] (const auto& syncStatus) { + SyncResult result; + HandleSyncStatus(syncStatus, result); + callback(result); + }, false); +} +} \ No newline at end of file diff --git a/services/distributeddataservice/service/rdb/rdb_syncer.h b/services/distributeddataservice/service/rdb/rdb_syncer.h new file mode 100644 index 000000000..a02479b8f --- /dev/null +++ b/services/distributeddataservice/service/rdb/rdb_syncer.h @@ -0,0 +1,97 @@ +/* + * 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 DISTRIBUTED_RDB_SYNCER_H +#define DISTRIBUTED_RDB_SYNCER_H + +#include "rdb_types.h" +#include +#include + +#include "rdb_notifier.h" +#include "rdb_store_observer_impl.h" +#include "relational_store_manager.h" +#include "relational_store_delegate.h" + +namespace OHOS::DistributedRdb { +class RdbSyncer { +public: + RdbSyncer(const RdbSyncerParam& param, RdbStoreObserverImpl* observer); + ~RdbSyncer() noexcept; + + int32_t Init(pid_t pid, pid_t uid); + + pid_t GetPid() const ; + + void SetTimerId(uint32_t timerId); + + uint32_t GetTimerId() const; + + std::string GetStoreId() const; + + std::string GetIdentifier() const; + + int32_t SetDistributedTables(const std::vector& tables); + + int32_t DoSync(const SyncOption& option, const RdbPredicates& predicates, SyncResult& result); + + int32_t DoAsync(const SyncOption& option, const RdbPredicates& predicates, const SyncCallback& callback); + +private: + std::string GetUserId() const; + + std::string GetBundleName() const; + + std::string GetAppId() const; + + std::string GetPath() const; + + int32_t CreateMetaData(); + + DistributedDB::RelationalStoreDelegate* GetDelegate(); + + std::mutex mutex_; + DistributedDB::RelationalStoreManager* manager_ {}; + DistributedDB::RelationalStoreDelegate* delegate_ {}; + RdbSyncerParam param_; + RdbStoreObserverImpl *observer_ {}; + pid_t pid_ {}; + pid_t uid_ {}; + uint32_t timerId_ {}; + + static std::vector NetworkIdToUUID(const std::vector& networkIds); + + static void HandleSyncStatus(const std::map>& SyncStatus, + SyncResult& result); + static DistributedDB::Query MakeQuery(const RdbPredicates& predicates); + static void EqualTo(const RdbPredicateOperation& operation, DistributedDB::Query& query); + static void NotEqualTo(const RdbPredicateOperation& operation, DistributedDB::Query& query); + static void And(const RdbPredicateOperation& operation, DistributedDB::Query& query); + static void Or(const RdbPredicateOperation& operation, DistributedDB::Query& query); + static void OrderBy(const RdbPredicateOperation& operation, DistributedDB::Query& query); + static void Limit(const RdbPredicateOperation& operation, DistributedDB::Query& query); + + using PredicateHandle = void(*)(const RdbPredicateOperation& operation, DistributedDB::Query& query); + static inline PredicateHandle HANDLES[OPERATOR_MAX] = { + [EQUAL_TO] = &RdbSyncer::EqualTo, + [NOT_EQUAL_TO] = &RdbSyncer::NotEqualTo, + [AND] = &RdbSyncer::And, + [OR] = &RdbSyncer::Or, + [ORDER_BY] = &RdbSyncer::OrderBy, + [LIMIT] = &RdbSyncer::Limit, + }; +}; +} +#endif diff --git a/services/rdb/rdb_device_syncer.cpp b/services/rdb/rdb_device_syncer.cpp deleted file mode 100644 index 8a5da35db..000000000 --- a/services/rdb/rdb_device_syncer.cpp +++ /dev/null @@ -1,105 +0,0 @@ -/* - * 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 "RdbDeviceSyncer" - -#include "rdb_device_syncer.h" -#include "log_print.h" -#include "rdb_syncer_factory.h" -#include "relational_store_manager.h" -#include "relational_store_delegate.h" - -namespace OHOS::DistributedRdb { -RdbDeviceSyncer::RdbDeviceSyncer(const RdbSyncerParam ¶m, pid_t uid) - : RdbSyncerImpl(param, uid), isInit_(false), manager_(nullptr), delegate_(nullptr) -{ - ZLOGI("construct %{public}s", param.storeName_.c_str()); -} - -RdbDeviceSyncer::~RdbDeviceSyncer() -{ - ZLOGI("destroy"); - if (manager_ != nullptr & delegate_ != nullptr) { - manager_->CloseStore(delegate_); - } - delete manager_; -} - -int RdbDeviceSyncer::Init() -{ - ZLOGI("enter"); - if (isInit_) { - return 0; - } - manager_ = new(std::nothrow) DistributedDB::RelationalStoreManager(GetAppId(), GetUserId()); - if (manager_ == nullptr) { - ZLOGE("malloc manager failed"); - return -1; - } - if (CreateMetaData() != 0) { - ZLOGE("create meta data failed"); - return -1; - } - isInit_ = true; - ZLOGI("success"); - return 0; -} - -int RdbDeviceSyncer::CreateMetaData() -{ - ZLOGI("enter"); - return 0; -} - -int RdbDeviceSyncer::SetDistributedTables(const std::vector &tables) -{ - auto delegate = GetDelegate(); - if (delegate == nullptr) { - return -1; - } - - for (const auto& table : tables) { - ZLOGI("%{public}s", table.c_str()); - if (delegate->CreateDistributedTable(table) != DistributedDB::DBStatus::OK) { - ZLOGE("create distributed table failed"); - return -1; - } - } - ZLOGE("create distributed table success"); - return 0; -} - -DistributedDB::RelationalStoreDelegate* RdbDeviceSyncer::GetDelegate() -{ - if (manager_ == nullptr) { - ZLOGE("manager_ is nullptr"); - return nullptr; - } - - std::lock_guard lock(mutex_); - if (delegate_ == nullptr) { - ZLOGI("create delegate"); - DistributedDB::RelationalStoreDelegate::Option option; - DistributedDB::DBStatus status = manager_->OpenStore(GetPath(), GetStoreId(), option, delegate_); - if (status != DistributedDB::DBStatus::OK) { - ZLOGE("open store failed status=%{public}d", status); - return nullptr; - } - ZLOGI("open store success"); - } - return delegate_; -} -} - diff --git a/services/rdb/rdb_device_syncer.h b/services/rdb/rdb_device_syncer.h deleted file mode 100644 index aa5f37eb4..000000000 --- a/services/rdb/rdb_device_syncer.h +++ /dev/null @@ -1,55 +0,0 @@ -/* - * 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 DISTRIBUTED_RDB_DEVICE_SYNCER_H -#define DISTRIBUTED_RDB_DEVICE_SYNCER_H - -#include "rdb_syncer_impl.h" -#include "rdb_syncer_stub.h" -#include "rdb_types.h" -#include "rdb_syncer_factory.h" - -namespace DistributedDB { -class RelationalStoreManager; -class RelationalStoreDelegate; -} - -namespace OHOS::DistributedRdb { -class RdbDeviceSyncer : public RdbSyncerImpl { -public: - explicit RdbDeviceSyncer(const RdbSyncerParam& param, pid_t uid); - - ~RdbDeviceSyncer() override; - - /* IPC interface */ - int SetDistributedTables(const std::vector& tables) override; - - /* RdbStore interface */ - int Init() override; - -private: - int CreateMetaData(); - - DistributedDB::RelationalStoreDelegate* GetDelegate(); - - std::mutex mutex_; - bool isInit_; - DistributedDB::RelationalStoreManager* manager_; - DistributedDB::RelationalStoreDelegate* delegate_; - - static inline RdbSyncerRegistration registration_; -}; -} -#endif diff --git a/services/rdb/rdb_service_impl.cpp b/services/rdb/rdb_service_impl.cpp deleted file mode 100644 index 7cae2f860..000000000 --- a/services/rdb/rdb_service_impl.cpp +++ /dev/null @@ -1,125 +0,0 @@ -/* - * 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 "RdbServiceImpl" - -#include "rdb_service_impl.h" -#include "checker/checker_manager.h" -#include "ipc_skeleton.h" -#include "log_print.h" -#include "rdb_syncer_impl.h" -#include "rdb_syncer_factory.h" - -namespace OHOS::DistributedRdb { -using namespace OHOS::DistributedData; -RdbServiceImpl::ClientDeathRecipient::ClientDeathRecipient(std::function&)> callback) - : callback_(std::move(callback)) -{ - ZLOGI("construct"); -} - -RdbServiceImpl::ClientDeathRecipient::~ClientDeathRecipient() -{ - ZLOGI("deconstruct"); -} - -void RdbServiceImpl::ClientDeathRecipient::OnRemoteDied(const wptr& object) -{ - auto objectSptr = object.promote(); - if (objectSptr != nullptr && callback_ != nullptr) { - callback_(objectSptr); - } -} - -void RdbServiceImpl::ClearClientRecipient(sptr& proxy) -{ - recipients_.Erase(proxy); -} - -void RdbServiceImpl::ClearClientSyncers(pid_t pid) -{ - ZLOGI("enter"); - auto count = syncers_.Erase(pid); - ZLOGI("remove %{public}d", static_cast(count)); -} - -void RdbServiceImpl::OnClientDied(pid_t pid, sptr& proxy) -{ - ClearClientRecipient(proxy); - ClearClientSyncers(pid); -} - -sptr RdbServiceImpl::CreateSyncer(const RdbSyncerParam& param, pid_t uid, pid_t pid) -{ - sptr syncer; - syncers_.Compute(pid, [¶m, uid, &syncer] (const auto &key, auto &syncers) -> bool { - ZLOGI("create new syncer %{public}d", key); - auto it = syncers.find(param.storeName_); - if (it != syncers.end()) { - syncer = it->second; - return true; - } - syncer = RdbSyncerFactory::GetInstance().CreateSyncer(param, uid); - if (syncer == nullptr) { - return false; - } - syncer->Init(); - syncers.insert({param.storeName_, syncer}); - return true; - }); - return syncer; -} - -sptr RdbServiceImpl::GetRdbSyncerInner(const RdbSyncerParam& param) -{ - pid_t uid = IPCSkeleton::GetCallingUid(); - pid_t pid = IPCSkeleton::GetCallingPid(); - ZLOGI("%{public}s %{public}s %{public}s", param.bundleName_.c_str(), - param.path_.c_str(), param.storeName_.c_str()); - if (!CheckerManager::GetInstance().IsValid(param.bundleName_, uid)) { - ZLOGI("check access failed"); - return nullptr; - } - return CreateSyncer(param, uid, pid); -} - -int RdbServiceImpl::RegisterClientDeathRecipient(const std::string& bundleName, sptr proxy) -{ - if (proxy == nullptr) { - ZLOGE("recipient is nullptr"); - return -1; - } - - pid_t pid = IPCSkeleton::GetCallingPid(); - sptr recipient = new(std::nothrow) ClientDeathRecipient( - [this, pid](sptr& object) { - OnClientDied(pid, object); - }); - if (recipient == nullptr) { - ZLOGE("malloc failed"); - return -1; - } - if (!proxy->AddDeathRecipient(recipient)) { - ZLOGE("add death recipient failed"); - return -1; - } - if (!recipients_.Insert(proxy, recipient)) { - ZLOGE("insert failed"); - return -1; - } - ZLOGI("success"); - return 0; -} -} diff --git a/services/rdb/rdb_syncer_factory.cpp b/services/rdb/rdb_syncer_factory.cpp deleted file mode 100644 index dd57b7d30..000000000 --- a/services/rdb/rdb_syncer_factory.cpp +++ /dev/null @@ -1,53 +0,0 @@ -/* - * 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 "RdbSyncerFactory" - -#include "rdb_syncer_factory.h" -#include "log_print.h" -#include "rdb_types.h" - -namespace OHOS::DistributedRdb { -RdbSyncerFactory& RdbSyncerFactory::GetInstance() -{ - static RdbSyncerFactory factory; - return factory; -} - -void RdbSyncerFactory::Register(int type, const Creator &creator) -{ - if (creator == nullptr) { - ZLOGE("creator is empty"); - return; - } - ZLOGI("add creator for store type %{public}d", type); - creators_.insert({ type, creator }); -} - -void RdbSyncerFactory::UnRegister(int type) -{ - creators_.erase(type); -} - -RdbSyncerImpl* RdbSyncerFactory::CreateSyncer(const RdbSyncerParam& param, pid_t uid) -{ - auto it = creators_.find(param.type_); - if (it == creators_.end()) { - return nullptr; - } - return it->second(param, uid); -} -} - diff --git a/services/rdb/rdb_syncer_factory.h b/services/rdb/rdb_syncer_factory.h deleted file mode 100644 index ba47258ad..000000000 --- a/services/rdb/rdb_syncer_factory.h +++ /dev/null @@ -1,76 +0,0 @@ -/* - * 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 DISTRIBUTED_RDB_STORE_FACTORY_H -#define DISTRIBUTED_RDB_STORE_FACTORY_H - -#include -#include -#include -#include -namespace OHOS::DistributedRdb { -class RdbSyncerImpl; -struct RdbSyncerParam; -class RdbSyncerFactory { -public: - using Creator = std::function; - - static RdbSyncerFactory& GetInstance(); - - void Register(int type, const Creator& creator); - - void UnRegister(int type); - - RdbSyncerImpl* CreateSyncer(const RdbSyncerParam& param, pid_t uid); - -private: - std::map creators_; -}; - -template -class RdbSyncerCreator { -public: - RdbSyncerImpl* operator()(const RdbSyncerParam& param, pid_t uid) - { - return static_cast(new(std::nothrow) T(param, uid)); - } -}; - -template -class RdbSyncerRegistration { -public: - RdbSyncerRegistration(); - - ~RdbSyncerRegistration(); - - RdbSyncerRegistration(const RdbSyncerRegistration&) = delete; - RdbSyncerRegistration(RdbSyncerRegistration&&) = delete; - RdbSyncerRegistration& operator=(const RdbSyncerRegistration&) = delete; - RdbSyncerRegistration& operator=(RdbSyncerRegistration&&) = delete; -}; - -template -RdbSyncerRegistration::RdbSyncerRegistration() -{ - RdbSyncerFactory::GetInstance().Register(type, RdbSyncerCreator()); -} - -template -RdbSyncerRegistration::~RdbSyncerRegistration() -{ - RdbSyncerFactory::GetInstance().UnRegister(type); -} -} -#endif diff --git a/services/rdb/rdb_syncer_impl.cpp b/services/rdb/rdb_syncer_impl.cpp deleted file mode 100644 index 062c4c1f8..000000000 --- a/services/rdb/rdb_syncer_impl.cpp +++ /dev/null @@ -1,76 +0,0 @@ -/* - * 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 "RdbSyncerImpl" - -#include "rdb_syncer_impl.h" -#include "account_delegate.h" -#include "checker/checker_manager.h" -#include "log_print.h" - -namespace OHOS::DistributedRdb { -using namespace OHOS::DistributedData; -using namespace OHOS::DistributedKv; -RdbSyncerImpl::RdbSyncerImpl(const RdbSyncerParam ¶m, pid_t uid) - : type_(param.type_), bundleName_(param.bundleName_), path_(param.path_), - storeId_(param.storeName_) -{ - ZLOGI("construct %{public}s %{public}s %{public}s %{public}d", - bundleName_.c_str(), userId_.c_str(), storeId_.c_str(), type_); - appId_ = CheckerManager::GetInstance().GetAppId(param.bundleName_, uid); - userId_ = AccountDelegate::GetInstance()->GetDeviceAccountIdByUID(uid); - identifier_ = std::to_string(type_) + "-" + appId_ + "-" + userId_ + "-" + storeId_; -} - -RdbSyncerImpl::~RdbSyncerImpl() -{ - ZLOGI("destroy %{public}s", storeId_.c_str()); -} - -bool RdbSyncerImpl::operator==(const RdbSyncerImpl& rhs) const -{ - return identifier_ == rhs.identifier_; -} - -std::string RdbSyncerImpl::GetBundleName() const -{ - return bundleName_; -} - -std::string RdbSyncerImpl::GetAppId() const -{ - return appId_; -} - -std::string RdbSyncerImpl::GetUserId() const -{ - return userId_; -} - -std::string RdbSyncerImpl::GetStoreId() const -{ - return storeId_; -} - -std::string RdbSyncerImpl::GetIdentifier() const -{ - return identifier_; -} - -std::string RdbSyncerImpl::GetPath() const -{ - return path_; -} -} \ No newline at end of file -- Gitee From f46d8929b480a25431964e4195f8644c1c5ba30f Mon Sep 17 00:00:00 2001 From: wuchunbo Date: Mon, 14 Feb 2022 20:37:46 +0800 Subject: [PATCH 2/6] fix some misc problem Signed-off-by: wuchunbo --- .../innerkitsimpl/rdb/include/irdb_service.h | 3 ++- .../rdb/src/rdb_service_proxy.cpp | 14 +++++------ .../innerkitsimpl/rdb/src/rdb_service_proxy.h | 23 ++++++++++--------- .../service/rdb/rdb_service_impl.h | 7 +++--- 4 files changed, 25 insertions(+), 22 deletions(-) diff --git a/frameworks/innerkitsimpl/rdb/include/irdb_service.h b/frameworks/innerkitsimpl/rdb/include/irdb_service.h index c4dcc718b..399be4fe0 100644 --- a/frameworks/innerkitsimpl/rdb/include/irdb_service.h +++ b/frameworks/innerkitsimpl/rdb/include/irdb_service.h @@ -42,7 +42,8 @@ public: virtual std::vector GetConnectDevices() = 0; virtual int32_t InitNotifier(const RdbSyncerParam& param, const sptr notifier) = 0; - + +protected: virtual int32_t DoSync(const RdbSyncerParam& param, const SyncOption& option, const RdbPredicates& predicates, SyncResult& result) = 0; diff --git a/frameworks/innerkitsimpl/rdb/src/rdb_service_proxy.cpp b/frameworks/innerkitsimpl/rdb/src/rdb_service_proxy.cpp index 46f845148..126009fca 100644 --- a/frameworks/innerkitsimpl/rdb/src/rdb_service_proxy.cpp +++ b/frameworks/innerkitsimpl/rdb/src/rdb_service_proxy.cpp @@ -37,7 +37,7 @@ void RdbServiceProxy::OnSyncComplete(uint32_t seqNum, const SyncResult &result) void RdbServiceProxy::OnDataChange(const std::string& storeName, const std::vector &devices) { ZLOGI("%{public}s", storeName.c_str()); - remoteObservers_.ComputeIfPresent( + observers_.ComputeIfPresent( storeName, [&devices] (const auto& key, const ObserverMapValue& value) { for (const auto& observer : value.first) { observer->OnChange(devices); @@ -123,7 +123,7 @@ int32_t RdbServiceProxy::InitNotifier(const RdbSyncerParam ¶m, const sptr(&observer)); }); if (!present) { - remoteObservers_.ComputeIfAbsent( + observers_.ComputeIfAbsent( param.storeName_, [&observer, ¶m] (const auto& key) -> ObserverMapValue { std::list list; list.push_back(const_cast(&observer)); @@ -353,7 +353,7 @@ int32_t RdbServiceProxy::UnSubscribe(const RdbSyncerParam ¶m, const Subscrib DoUnSubscribe(param); bool canErase = false; auto* const observerPtr = const_cast(&observer); - remoteObservers_.ComputeIfPresent( + observers_.ComputeIfPresent( param.storeName_, [observerPtr, &canErase](const auto& key, ObserverMapValue& value) { ZLOGI("before remove size=%{public}d", static_cast(value.first.size())); value.first.remove(observerPtr); @@ -364,7 +364,7 @@ int32_t RdbServiceProxy::UnSubscribe(const RdbSyncerParam ¶m, const Subscrib }); if(canErase) { - remoteObservers_.Erase(param.storeName_); + observers_.Erase(param.storeName_); } return RDB_OK; } @@ -394,7 +394,7 @@ int32_t RdbServiceProxy::DoUnSubscribe(const RdbSyncerParam ¶m) RdbServiceProxy::ObserverMap RdbServiceProxy::ExportObservers() { - return remoteObservers_; + return observers_; } void RdbServiceProxy::ImportObservers(ObserverMap &observers) diff --git a/frameworks/innerkitsimpl/rdb/src/rdb_service_proxy.h b/frameworks/innerkitsimpl/rdb/src/rdb_service_proxy.h index df203e112..7d2356875 100644 --- a/frameworks/innerkitsimpl/rdb/src/rdb_service_proxy.h +++ b/frameworks/innerkitsimpl/rdb/src/rdb_service_proxy.h @@ -43,26 +43,27 @@ public: int32_t Sync(const RdbSyncerParam& param, const SyncOption& option, const RdbPredicates& predicates, const SyncCallback& callback) override; - int32_t DoSync(const RdbSyncerParam& param, const SyncOption& option, - const RdbPredicates& predicates, SyncResult& result) override; - - int32_t DoAsync(const RdbSyncerParam& param, uint32_t seqNum, const SyncOption& option, - const RdbPredicates& predicates) override; - int32_t Subscribe(const RdbSyncerParam& param, const SubscribeOption& option, const RdbStoreObserver& observer) override; - int32_t DoSubscribe(const RdbSyncerParam& param) override; - int32_t UnSubscribe(const RdbSyncerParam& param, const SubscribeOption& option, const RdbStoreObserver& observer) override; - int32_t DoUnSubscribe(const RdbSyncerParam& param) override; - ObserverMap ExportObservers(); void ImportObservers(ObserverMap& observers); +protected: + int32_t DoSync(const RdbSyncerParam& param, const SyncOption& option, + const RdbPredicates& predicates, SyncResult& result) override; + + int32_t DoAsync(const RdbSyncerParam& param, uint32_t seqNum, const SyncOption& option, + const RdbPredicates& predicates) override; + + int32_t DoSubscribe(const RdbSyncerParam& param) override; + + int32_t DoUnSubscribe(const RdbSyncerParam& param) override; + private: uint32_t GetSeqNum(); @@ -79,7 +80,7 @@ private: std::atomic seqNum_ {}; ConcurrentMap syncCallbacks_; - ObserverMap remoteObservers_; + ObserverMap observers_; sptr notifier_; static inline BrokerDelegator delegator_; diff --git a/services/distributeddataservice/service/rdb/rdb_service_impl.h b/services/distributeddataservice/service/rdb/rdb_service_impl.h index f9e1f6abe..da8ee33c2 100644 --- a/services/distributeddataservice/service/rdb/rdb_service_impl.h +++ b/services/distributeddataservice/service/rdb/rdb_service_impl.h @@ -42,9 +42,12 @@ public: int32_t SetDistributedTables(const RdbSyncerParam& param, const std::vector& tables) override; + void OnDataChange(pid_t pid, const DistributedDB::StoreChangedData& data); + +protected: int32_t DoSync(const RdbSyncerParam& param, const SyncOption& option, const RdbPredicates& predicates, SyncResult& result) override; - + int32_t DoAsync(const RdbSyncerParam& param, uint32_t seqNum, const SyncOption& option, const RdbPredicates& predicates) override; @@ -52,8 +55,6 @@ public: int32_t DoUnSubscribe(const RdbSyncerParam& param) override; - void OnDataChange(pid_t pid, const DistributedDB::StoreChangedData& data); - private: std::string GenIdentifier(const RdbSyncerParam& param); -- Gitee From 64bd686e03f81da9761812ab03c011c2eadc0642 Mon Sep 17 00:00:00 2001 From: wuchunbo Date: Mon, 14 Feb 2022 21:49:40 +0800 Subject: [PATCH 3/6] fix codecheck Signed-off-by: wuchunbo --- .../distributeddatafwk/src/itypes_util.cpp | 2 +- .../innerkitsimpl/rdb/include/rdb_notifier.h | 2 +- .../innerkitsimpl/rdb/include/rdb_service.h | 1 - .../innerkitsimpl/rdb/include/rdb_types.h | 4 +- .../rdb/src/rdb_manager_impl.cpp | 4 +- .../innerkitsimpl/rdb/src/rdb_manager_impl.h | 3 +- .../rdb/src/rdb_service_proxy.cpp | 28 +++---- .../service/rdb/rdb_service_impl.cpp | 75 +++++++------------ .../service/rdb/rdb_service_impl.h | 2 +- .../service/rdb/rdb_store_observer_impl.h | 1 - .../service/rdb/rdb_syncer.cpp | 6 +- .../service/rdb/rdb_syncer.h | 4 +- 12 files changed, 56 insertions(+), 76 deletions(-) diff --git a/frameworks/innerkitsimpl/distributeddatafwk/src/itypes_util.cpp b/frameworks/innerkitsimpl/distributeddatafwk/src/itypes_util.cpp index 7651ca90c..2f084d300 100644 --- a/frameworks/innerkitsimpl/distributeddatafwk/src/itypes_util.cpp +++ b/frameworks/innerkitsimpl/distributeddatafwk/src/itypes_util.cpp @@ -243,7 +243,7 @@ bool ITypesUtil::UnMarshalling(MessageParcel &parcel, DistributedRdb::SyncResult ZLOGE("SyncResult read int failed"); return false; } - result.insert( { device, error } ); + result.insert({ device, error }); } return true; } diff --git a/frameworks/innerkitsimpl/rdb/include/rdb_notifier.h b/frameworks/innerkitsimpl/rdb/include/rdb_notifier.h index ee037bce4..81aa43373 100644 --- a/frameworks/innerkitsimpl/rdb/include/rdb_notifier.h +++ b/frameworks/innerkitsimpl/rdb/include/rdb_notifier.h @@ -23,7 +23,7 @@ #include "rdb_types.h" namespace OHOS::DistributedRdb { -class IRdbNotifier: public IRemoteBroker { +class IRdbNotifier : public IRemoteBroker { public: enum { RDB_NOTIFIER_CMD_SYNC_COMPLETE, diff --git a/frameworks/innerkitsimpl/rdb/include/rdb_service.h b/frameworks/innerkitsimpl/rdb/include/rdb_service.h index 2cb69fcbe..80e52a179 100644 --- a/frameworks/innerkitsimpl/rdb/include/rdb_service.h +++ b/frameworks/innerkitsimpl/rdb/include/rdb_service.h @@ -19,7 +19,6 @@ #include #include -#include #include "rdb_types.h" namespace OHOS::DistributedRdb { diff --git a/frameworks/innerkitsimpl/rdb/include/rdb_types.h b/frameworks/innerkitsimpl/rdb/include/rdb_types.h index 79bf343fe..6874093c0 100644 --- a/frameworks/innerkitsimpl/rdb/include/rdb_types.h +++ b/frameworks/innerkitsimpl/rdb/include/rdb_types.h @@ -73,12 +73,12 @@ struct RdbPredicates { inline void AddOperation(const RdbPredicateOperator op, const std::string& field, const std::string& value) { - operations_.push_back({op, field, {value}}); + operations_.push_back({ op, field, { value } }); } inline void AddOperation(const RdbPredicateOperator op, const std::string& field, const std::vector& values) { - operations_.push_back({op, field, values}); + operations_.push_back({ op, field, values }); } std::string table_; diff --git a/frameworks/innerkitsimpl/rdb/src/rdb_manager_impl.cpp b/frameworks/innerkitsimpl/rdb/src/rdb_manager_impl.cpp index a92324706..b0c55b370 100644 --- a/frameworks/innerkitsimpl/rdb/src/rdb_manager_impl.cpp +++ b/frameworks/innerkitsimpl/rdb/src/rdb_manager_impl.cpp @@ -31,7 +31,7 @@ namespace OHOS::DistributedRdb { static sptr GetDistributedDataManager() { int retry = 0; - while (++retry <= RdbManagerImpl::GET_DDMS_RETRY_TIMES) { + while (++retry <= RdbManagerImpl::GET_SA_RETRY_TIMES) { auto manager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); if (manager == nullptr) { ZLOGE("get system ability manager failed"); @@ -135,7 +135,7 @@ void RdbManagerImpl::OnRemoteDied() auto observers = proxy->ExportObservers(); ResetServiceHandle(); - std::this_thread::sleep_for(std::chrono::seconds(2)); // sleep two second + std::this_thread::sleep_for(std::chrono::seconds(WAIT_TIME)); RdbSyncerParam param; param.bundleName_ = bundleName_; auto service = GetRdbService(param); diff --git a/frameworks/innerkitsimpl/rdb/src/rdb_manager_impl.h b/frameworks/innerkitsimpl/rdb/src/rdb_manager_impl.h index 6f3fc9bbe..95ea174c5 100644 --- a/frameworks/innerkitsimpl/rdb/src/rdb_manager_impl.h +++ b/frameworks/innerkitsimpl/rdb/src/rdb_manager_impl.h @@ -34,8 +34,9 @@ class RdbService; class IRdbService; class RdbManagerImpl { public: - static constexpr int GET_DDMS_RETRY_TIMES = 3; + static constexpr int GET_SA_RETRY_TIMES = 3; static constexpr int RETRY_INTERVAL = 1; + static constexpr int WAIT_TIME = 2; static RdbManagerImpl &GetInstance(); diff --git a/frameworks/innerkitsimpl/rdb/src/rdb_service_proxy.cpp b/frameworks/innerkitsimpl/rdb/src/rdb_service_proxy.cpp index 126009fca..522519f2e 100644 --- a/frameworks/innerkitsimpl/rdb/src/rdb_service_proxy.cpp +++ b/frameworks/innerkitsimpl/rdb/src/rdb_service_proxy.cpp @@ -304,22 +304,22 @@ int32_t RdbServiceProxy::Subscribe(const RdbSyncerParam ¶m, const SubscribeO return RDB_ERROR; } bool present = observers_.ComputeIfPresent( - param.storeName_, [&observer] (const auto& key, ObserverMapValue& value) { - for (const auto& element : value.first) { - if (element == &observer) { - ZLOGE("duplicate observer"); - return; - } + param.storeName_, [&observer] (const auto& key, ObserverMapValue& value) { + for (const auto& element : value.first) { + if (element == &observer) { + ZLOGE("duplicate observer"); + return; } - value.first.push_back(const_cast(&observer)); - }); + } + value.first.push_back(const_cast(&observer)); + }); if (!present) { observers_.ComputeIfAbsent( param.storeName_, [&observer, ¶m] (const auto& key) -> ObserverMapValue { - std::list list; - list.push_back(const_cast(&observer)); - return {list, param}; - }); + std::list list; + list.push_back(const_cast(&observer)); + return {list, param}; + }); } return RDB_OK; } @@ -352,7 +352,7 @@ int32_t RdbServiceProxy::UnSubscribe(const RdbSyncerParam ¶m, const Subscrib { DoUnSubscribe(param); bool canErase = false; - auto* const observerPtr = const_cast(&observer); + RdbStoreObserver* const observerPtr = const_cast(&observer); observers_.ComputeIfPresent( param.storeName_, [observerPtr, &canErase](const auto& key, ObserverMapValue& value) { ZLOGI("before remove size=%{public}d", static_cast(value.first.size())); @@ -363,7 +363,7 @@ int32_t RdbServiceProxy::UnSubscribe(const RdbSyncerParam ¶m, const Subscrib } }); - if(canErase) { + if (canErase) { observers_.Erase(param.storeName_); } return RDB_OK; diff --git a/services/distributeddataservice/service/rdb/rdb_service_impl.cpp b/services/distributeddataservice/service/rdb/rdb_service_impl.cpp index 2de44649f..eb74d2077 100644 --- a/services/distributeddataservice/service/rdb/rdb_service_impl.cpp +++ b/services/distributeddataservice/service/rdb/rdb_service_impl.cpp @@ -208,59 +208,38 @@ std::shared_ptr RdbServiceImpl::GetRdbSyncer(const RdbSyncerParam &pa pid_t uid = GetCallingUid(); std::shared_ptr syncer; - bool present = syncers_.ComputeIfPresent(pid, - [this, ¶m, pid, uid, &syncer] (const auto& key, StoreSyncersType& syncers) { - auto it = syncers.find(param.storeName_); - if (it != syncers.end()) { - syncer = it->second; - timer_.Unregister(syncer->GetTimerId()); - uint32_t timerId = timer_.Register([this, syncer]() { SyncerTimeout(syncer); }, SYNCER_TIMEOUT, true); - syncer->SetTimerId(timerId); - return; - } - if (syncers.size() >= MAX_PROCESS_SYNCER_NUM) { - ZLOGE("%{public}d exceed MAX_PROCESS_SYNCER_NUM", pid); - return; - } - if (syncerNum_ >= MAX_SYNCER_NUM) { - ZLOGE("no available syncer"); - return; - } - auto syncer_ = std::make_shared(param, new (std::nothrow) RdbStoreObserverImpl(this, pid)); - if (syncer_->Init(pid, uid) != 0) { - return; - } - syncers[param.storeName_] = syncer_; - syncer = syncer_; - syncerNum_++; + syncers_.Compute(pid, [this, ¶m, pid, uid, &syncer] (const auto& key, StoreSyncersType& syncers) { + auto it = syncers.find(param.storeName_); + if (it != syncers.end()) { + syncer = it->second; + timer_.Unregister(syncer->GetTimerId()); uint32_t timerId = timer_.Register([this, syncer]() { SyncerTimeout(syncer); }, SYNCER_TIMEOUT, true); syncer->SetTimerId(timerId); + return true; + } + if (syncers.size() >= MAX_SYNCER_PER_PROCESS) { + ZLOGE("%{public}d exceed MAX_PROCESS_SYNCER_NUM", pid); + return false; + } + if (syncerNum_ >= MAX_SYNCER_NUM) { + ZLOGE("no available syncer"); + return false; + } + auto syncer_ = std::make_shared(param, new (std::nothrow) RdbStoreObserverImpl(this, pid)); + if (syncer_->Init(pid, uid) != 0) { + return false; + } + syncers[param.storeName_] = syncer_; + syncer = syncer_; + syncerNum_++; + uint32_t timerId = timer_.Register([this, syncer]() { SyncerTimeout(syncer); }, SYNCER_TIMEOUT, true); + syncer->SetTimerId(timerId); + return true; }); - if (!present) { - syncers_.ComputeIfAbsent(pid, [this, ¶m, pid, uid, &syncer] (const auto& key) { - StoreSyncersType syncers; - if (syncerNum_ >= MAX_SYNCER_NUM) { - ZLOGE("no available syncer"); - return syncers; - } - auto syncer_ = std::make_shared(param, new (std::nothrow) RdbStoreObserverImpl(this, pid)); - if (syncer_->Init(pid, uid) != 0) { - return syncers; - } - syncers[param.storeName_] = syncer_; - syncer = syncer_; - syncerNum_++; - uint32_t timerId = timer_.Register([this, syncer]() { SyncerTimeout(syncer); }, SYNCER_TIMEOUT, true); - syncer->SetTimerId(timerId); - return syncers; - }); - } - if (syncer != nullptr) { identifiers_.Insert(syncer->GetIdentifier(), pid); - } - if (syncer == nullptr) { + } else { ZLOGE("syncer is nullptr"); } return syncer; @@ -295,7 +274,7 @@ void RdbServiceImpl::OnAsyncComplete(pid_t pid, uint32_t seqNum, const SyncResul } int32_t RdbServiceImpl::DoAsync(const RdbSyncerParam ¶m, uint32_t seqNum, const SyncOption &option, - const RdbPredicates &predicates) + const RdbPredicates &predicates) { pid_t pid = GetCallingPid(); ZLOGI("seq num=%{public}u", seqNum); diff --git a/services/distributeddataservice/service/rdb/rdb_service_impl.h b/services/distributeddataservice/service/rdb/rdb_service_impl.h index da8ee33c2..31a96de64 100644 --- a/services/distributeddataservice/service/rdb/rdb_service_impl.h +++ b/services/distributeddataservice/service/rdb/rdb_service_impl.h @@ -89,7 +89,7 @@ private: static std::string TransferStringToHex(const std::string& origStr); static constexpr int32_t MAX_SYNCER_NUM = 50; - static constexpr int32_t MAX_PROCESS_SYNCER_NUM = 10; + static constexpr int32_t MAX_SYNCER_PER_PROCESS = 10; static constexpr int32_t SYNCER_TIMEOUT = 60 * 1000; // ms }; } diff --git a/services/distributeddataservice/service/rdb/rdb_store_observer_impl.h b/services/distributeddataservice/service/rdb/rdb_store_observer_impl.h index 7a48831d4..87615d1d5 100644 --- a/services/distributeddataservice/service/rdb/rdb_store_observer_impl.h +++ b/services/distributeddataservice/service/rdb/rdb_store_observer_impl.h @@ -33,6 +33,5 @@ private: pid_t pid_ {}; RdbServiceImpl* owner_ {}; }; - } #endif diff --git a/services/distributeddataservice/service/rdb/rdb_syncer.cpp b/services/distributeddataservice/service/rdb/rdb_syncer.cpp index 38450e8e6..4feef5482 100644 --- a/services/distributeddataservice/service/rdb/rdb_syncer.cpp +++ b/services/distributeddataservice/service/rdb/rdb_syncer.cpp @@ -37,7 +37,7 @@ RdbSyncer::RdbSyncer(const RdbSyncerParam& param, RdbStoreObserverImpl* observer RdbSyncer::~RdbSyncer() noexcept { ZLOGI("destroy %{public}s", param_.storeName_.c_str()); - if (manager_ != nullptr & delegate_ != nullptr) { + if ((manager_ != nullptr) && (delegate_ != nullptr)) { manager_->CloseStore(delegate_); } delete manager_; @@ -245,8 +245,8 @@ void RdbSyncer::OrderBy(const RdbPredicateOperation &operation, DistributedDB::Q void RdbSyncer::Limit(const RdbPredicateOperation &operation, DistributedDB::Query &query) { char *end = nullptr; - int limit = static_cast(strtol(operation.field_.c_str(), &end, 10)); // 10 base number - int offset = static_cast(strtol(operation.values_[0].c_str(), &end, 10)); // 10 base number + int limit = static_cast(strtol(operation.field_.c_str(), &end, DECIMAL_BASE)); + int offset = static_cast(strtol(operation.values_[0].c_str(), &end, DECIMAL_BASE)); query.Limit(limit, offset); ZLOGI("limit=%{public}d offset=%{public}d", limit, offset); } diff --git a/services/distributeddataservice/service/rdb/rdb_syncer.h b/services/distributeddataservice/service/rdb/rdb_syncer.h index a02479b8f..b31adfb86 100644 --- a/services/distributeddataservice/service/rdb/rdb_syncer.h +++ b/services/distributeddataservice/service/rdb/rdb_syncer.h @@ -16,10 +16,10 @@ #ifndef DISTRIBUTED_RDB_SYNCER_H #define DISTRIBUTED_RDB_SYNCER_H -#include "rdb_types.h" #include #include +#include "rdb_types.h" #include "rdb_notifier.h" #include "rdb_store_observer_impl.h" #include "relational_store_manager.h" @@ -92,6 +92,8 @@ private: [ORDER_BY] = &RdbSyncer::OrderBy, [LIMIT] = &RdbSyncer::Limit, }; + + static constexpr int DECIMAL_BASE = 10; }; } #endif -- Gitee From e87383675adf4833dc58ffc3864ac5e700eb647d Mon Sep 17 00:00:00 2001 From: wuchunbo Date: Tue, 15 Feb 2022 11:13:19 +0800 Subject: [PATCH 4/6] fix codecheck Signed-off-by: wuchunbo --- services/distributeddataservice/service/rdb/rdb_syncer.cpp | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/services/distributeddataservice/service/rdb/rdb_syncer.cpp b/services/distributeddataservice/service/rdb/rdb_syncer.cpp index 4feef5482..1c48d44cb 100644 --- a/services/distributeddataservice/service/rdb/rdb_syncer.cpp +++ b/services/distributeddataservice/service/rdb/rdb_syncer.cpp @@ -247,6 +247,12 @@ void RdbSyncer::Limit(const RdbPredicateOperation &operation, DistributedDB::Que char *end = nullptr; int limit = static_cast(strtol(operation.field_.c_str(), &end, DECIMAL_BASE)); int offset = static_cast(strtol(operation.values_[0].c_str(), &end, DECIMAL_BASE)); + if (limit < 0) { + limit = 0; + } + if (offset < 0) { + offset = 0; + } query.Limit(limit, offset); ZLOGI("limit=%{public}d offset=%{public}d", limit, offset); } -- Gitee From f0812dec797ba9f72faadcca9b8f74d82c1b65f7 Mon Sep 17 00:00:00 2001 From: wuchunbo Date: Tue, 15 Feb 2022 12:19:03 +0800 Subject: [PATCH 5/6] change subscribe interface Signed-off-by: wuchunbo --- .../innerkitsimpl/rdb/include/rdb_service.h | 4 +-- .../rdb/src/rdb_service_proxy.cpp | 32 +++++++------------ .../innerkitsimpl/rdb/src/rdb_service_proxy.h | 4 +-- .../service/rdb/rdb_service_stub.h | 4 +-- 4 files changed, 18 insertions(+), 26 deletions(-) diff --git a/frameworks/innerkitsimpl/rdb/include/rdb_service.h b/frameworks/innerkitsimpl/rdb/include/rdb_service.h index 80e52a179..b5dff6d33 100644 --- a/frameworks/innerkitsimpl/rdb/include/rdb_service.h +++ b/frameworks/innerkitsimpl/rdb/include/rdb_service.h @@ -33,10 +33,10 @@ public: const RdbPredicates& predicates, const SyncCallback& callback) = 0; virtual int32_t Subscribe(const RdbSyncerParam& param, const SubscribeOption& option, - const RdbStoreObserver& observer) = 0; + RdbStoreObserver *observer) = 0; virtual int32_t UnSubscribe(const RdbSyncerParam& param, const SubscribeOption& option, - const RdbStoreObserver& observer) = 0; + RdbStoreObserver *observer) = 0; }; } #endif diff --git a/frameworks/innerkitsimpl/rdb/src/rdb_service_proxy.cpp b/frameworks/innerkitsimpl/rdb/src/rdb_service_proxy.cpp index 522519f2e..d6ab29f8c 100644 --- a/frameworks/innerkitsimpl/rdb/src/rdb_service_proxy.cpp +++ b/frameworks/innerkitsimpl/rdb/src/rdb_service_proxy.cpp @@ -293,7 +293,7 @@ int32_t RdbServiceProxy::Sync(const RdbSyncerParam& param, const SyncOption &opt } int32_t RdbServiceProxy::Subscribe(const RdbSyncerParam ¶m, const SubscribeOption &option, - const RdbStoreObserver &observer) + RdbStoreObserver *observer) { if (option.mode != SubscribeMode::REMOTE) { ZLOGE("subscribe mode invalid"); @@ -303,24 +303,17 @@ int32_t RdbServiceProxy::Subscribe(const RdbSyncerParam ¶m, const SubscribeO ZLOGI("communicate to server failed"); return RDB_ERROR; } - bool present = observers_.ComputeIfPresent( - param.storeName_, [&observer] (const auto& key, ObserverMapValue& value) { + observers_.Compute( + param.storeName_, [observer] (const auto& key, ObserverMapValue& value) { for (const auto& element : value.first) { - if (element == &observer) { + if (element == observer) { ZLOGE("duplicate observer"); - return; + return false; } } - value.first.push_back(const_cast(&observer)); + value.first.push_back(observer); + return true; }); - if (!present) { - observers_.ComputeIfAbsent( - param.storeName_, [&observer, ¶m] (const auto& key) -> ObserverMapValue { - std::list list; - list.push_back(const_cast(&observer)); - return {list, param}; - }); - } return RDB_OK; } @@ -348,15 +341,14 @@ int32_t RdbServiceProxy::DoSubscribe(const RdbSyncerParam ¶m) } int32_t RdbServiceProxy::UnSubscribe(const RdbSyncerParam ¶m, const SubscribeOption &option, - const RdbStoreObserver &observer) + RdbStoreObserver *observer) { DoUnSubscribe(param); bool canErase = false; - RdbStoreObserver* const observerPtr = const_cast(&observer); observers_.ComputeIfPresent( - param.storeName_, [observerPtr, &canErase](const auto& key, ObserverMapValue& value) { + param.storeName_, [observer , &canErase](const auto& key, ObserverMapValue& value) { ZLOGI("before remove size=%{public}d", static_cast(value.first.size())); - value.first.remove(observerPtr); + value.first.remove(observer); ZLOGI("after remove size=%{public}d", static_cast(value.first.size())); if (value.first.empty()) { canErase = true; @@ -402,8 +394,8 @@ void RdbServiceProxy::ImportObservers(ObserverMap &observers) ZLOGI("enter"); SubscribeOption option {SubscribeMode::REMOTE}; observers.ForEach([this, &option](const std::string& key, const ObserverMapValue& value) { - for (const auto& observer : value.first) { - Subscribe(value.second, option, *observer); + for (auto& observer : value.first) { + Subscribe(value.second, option, observer); } return false; }); diff --git a/frameworks/innerkitsimpl/rdb/src/rdb_service_proxy.h b/frameworks/innerkitsimpl/rdb/src/rdb_service_proxy.h index 7d2356875..29dab88f9 100644 --- a/frameworks/innerkitsimpl/rdb/src/rdb_service_proxy.h +++ b/frameworks/innerkitsimpl/rdb/src/rdb_service_proxy.h @@ -44,10 +44,10 @@ public: const RdbPredicates& predicates, const SyncCallback& callback) override; int32_t Subscribe(const RdbSyncerParam& param, const SubscribeOption& option, - const RdbStoreObserver& observer) override; + RdbStoreObserver *observer) override; int32_t UnSubscribe(const RdbSyncerParam& param, const SubscribeOption& option, - const RdbStoreObserver& observer) override; + RdbStoreObserver *observer) override; ObserverMap ExportObservers(); diff --git a/services/distributeddataservice/service/rdb/rdb_service_stub.h b/services/distributeddataservice/service/rdb/rdb_service_stub.h index 1416fbe0d..c520bc490 100644 --- a/services/distributeddataservice/service/rdb/rdb_service_stub.h +++ b/services/distributeddataservice/service/rdb/rdb_service_stub.h @@ -32,13 +32,13 @@ public: } int32_t Subscribe(const RdbSyncerParam& param, const SubscribeOption& option, - const RdbStoreObserver& observer) override + RdbStoreObserver *observer) override { return 0; } int32_t UnSubscribe(const RdbSyncerParam& param, const SubscribeOption& option, - const RdbStoreObserver& observer) override + RdbStoreObserver *observer) override { return 0; } -- Gitee From e9ac5abc77623ba532c0180f5f30ce933c5a48f5 Mon Sep 17 00:00:00 2001 From: wuchunbo Date: Tue, 15 Feb 2022 16:14:21 +0800 Subject: [PATCH 6/6] fix codecheck Signed-off-by: wuchunbo --- frameworks/innerkitsimpl/rdb/src/rdb_service_proxy.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/frameworks/innerkitsimpl/rdb/src/rdb_service_proxy.cpp b/frameworks/innerkitsimpl/rdb/src/rdb_service_proxy.cpp index d6ab29f8c..3f1e9ec24 100644 --- a/frameworks/innerkitsimpl/rdb/src/rdb_service_proxy.cpp +++ b/frameworks/innerkitsimpl/rdb/src/rdb_service_proxy.cpp @@ -346,7 +346,7 @@ int32_t RdbServiceProxy::UnSubscribe(const RdbSyncerParam ¶m, const Subscrib DoUnSubscribe(param); bool canErase = false; observers_.ComputeIfPresent( - param.storeName_, [observer , &canErase](const auto& key, ObserverMapValue& value) { + param.storeName_, [observer, &canErase](const auto& key, ObserverMapValue& value) { ZLOGI("before remove size=%{public}d", static_cast(value.first.size())); value.first.remove(observer); ZLOGI("after remove size=%{public}d", static_cast(value.first.size())); -- Gitee