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 43 TimeHelper(); 44 ~TimeHelper(); 45 46 // Init the TimeHelper 47 int Initialize(const ISyncInterface *inStorage, std::shared_ptr<Metadata> &inMetadata); 48 49 // Get Timestamp when write data into db, export interface; 50 Timestamp GetTime(); 51 52 // Get max data time from db 53 Timestamp GetMaxDataItemTime(); 54 55 // Get local time offset 56 TimeOffset GetLocalTimeOffset() const; 57 58 // Get local time 59 int SaveLocalTimeOffset(TimeOffset offset); 60 61 void SetSendConfig(const std::string &dstTarget, bool nonBlock, uint32_t timeout, SendConfig &sendConf); 62 63 static Timestamp GetMonotonicTime(); 64 65 private: 66 static std::mutex systemTimeLock_; 67 static Timestamp lastSystemTimeUs_; 68 static Timestamp currentIncCount_; 69 static const uint64_t MAX_INC_COUNT = 9; // last bit from 0-9 70 static std::atomic<Timestamp> lastMonotonicTime_; 71 const ISyncInterface *storage_; 72 std::shared_ptr<Metadata> metadata_; 73 }; 74 } // namespace DistributedDB 75 76 #endif // TIME_HELPER_H 77