1 /* 2 * Copyright (c) 2024 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 #ifndef CLOUD_SYNC_STATE_MACHINE_H 16 #define CLOUD_SYNC_STATE_MACHINE_H 17 18 #include "cloud/cloud_store_types.h" 19 20 #include <condition_variable> 21 #include <functional> 22 #include <map> 23 #include <memory> 24 #include <vector> 25 26 namespace DistributedDB { 27 using EventToState = std::map<uint8_t, uint8_t>; 28 using StateMappingHandler = std::function<uint8_t(void)>; 29 30 struct CloudStateSwitchTable { 31 uint32_t version = 0; 32 std::map<uint8_t, EventToState> switchTable; 33 }; 34 35 class CloudSyncStateMachine { 36 public: 37 CloudSyncStateMachine() = default; 38 39 ~CloudSyncStateMachine() = default; 40 41 // Init the CloudSyncStateMachine 42 static int Initialize(); 43 44 void SwitchStateAndStep(uint8_t event); 45 46 void RegisterFunc(CloudSyncState state, const std::function<uint8_t(void)> &function); 47 48 protected: 49 // Step the CloudSyncStateMachine 50 void SyncStep(); 51 52 private: 53 // Used to init sync state machine switchbables 54 static void InitCloudStateSwitchTables(); 55 56 // To generate the statemachine switchtable with the given version 57 static void InitCloudStateSwitchTable(const std::vector<std::vector<uint8_t>> &switchTable); 58 59 int SwitchMachineState(uint8_t event); 60 61 static std::mutex stateSwitchTableLock_; 62 static bool isStateSwitchTableInited_; 63 static std::vector<CloudStateSwitchTable> stateSwitchTables_; 64 std::map<uint8_t, StateMappingHandler> stateMapping_; 65 CloudSyncState currentState_ = CloudSyncState::IDLE; 66 }; 67 } // namespace DistributedDB 68 69 #endif // CLOUD_SYNC_STATE_MACHINE_H 70