1 /* 2 * Copyright (c) 2021 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16 #ifndef TIME_HELPER_H 17 #define TIME_HELPER_H 18 19 #include <mutex> 20 21 #include "icommunicator.h" 22 #include "meta_data.h" 23 #include "runtime_context.h" 24 25 namespace DistributedDB { 26 class TimeHelper { 27 public: 28 constexpr static int64_t BASE_OFFSET = 10000LL * 365LL * 24LL * 3600LL * 1000LL * 1000LL * 10L; // 10000year 100ns 29 30 constexpr static int64_t BUFFER_VALID_TIME = BASE_OFFSET * 2; // 20000 year 200ns 31 32 constexpr static int64_t MAX_VALID_TIME = INT64_MAX; // sqlite only support int64 as integer 33 34 static const uint64_t TO_100_NS = 10; // 1us to 100ns 35 36 static const uint64_t MS_TO_100_NS = 10000; // 1ms to 100ns 37 38 static const Timestamp INVALID_TIMESTAMP = 0; 39 40 // Get current system time 41 static Timestamp GetSysCurrentTime(); 42 static int GetSysCurrentRawTime(uint64_t &curTime); 43 44 TimeHelper(); 45 ~TimeHelper(); 46 47 // Init the TimeHelper 48 int Initialize(const ISyncInterface *inStorage, const std::shared_ptr<Metadata> &inMetadata); 49 50 // Get Timestamp when write data into db, export interface; 51 Timestamp GetTime(); 52 53 // Get max data time from db 54 Timestamp GetMaxDataItemTime(); 55 56 // Get local time offset 57 TimeOffset GetLocalTimeOffset() const; 58 59 // Get local time 60 int SaveLocalTimeOffset(TimeOffset offset); 61 62 void SetSendConfig(const std::string &dstTarget, bool nonBlock, uint32_t timeout, SendConfig &sendConf); 63 64 static Timestamp GetMonotonicTime(); 65 66 private: 67 static std::mutex systemTimeLock_; 68 static Timestamp lastSystemTimeUs_; 69 static Timestamp currentIncCount_; 70 static const uint64_t MAX_INC_COUNT = 9; // last bit from 0-9 71 static std::atomic<Timestamp> lastMonotonicTime_; 72 const ISyncInterface *storage_; 73 std::shared_ptr<Metadata> metadata_; 74 }; 75 } // namespace DistributedDB 76 77 #endif // TIME_HELPER_H 78