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_TICK_MONITOR_H
17 #define TIME_TICK_MONITOR_H
18 
19 #include "db_types.h"
20 #include "macro_utils.h"
21 #include "runtime_context.h"
22 #include "platform_specific.h"
23 
24 namespace DistributedDB {
25 class TimeTickMonitor final {
26 public:
27     TimeTickMonitor();
28     ~TimeTickMonitor();
29 
30     DISABLE_COPY_ASSIGN_MOVE(TimeTickMonitor);
31 
32     // Start the TimeTickMonitor
33     int StartTimeTickMonitor();
34 
35     // Stop the TimeTickMonitor
36     void StopTimeTickMonitor();
37 
38     // Register a time changed lister, it will be callback when local time changed.
39     NotificationChain::Listener *RegisterTimeChangedLister(const TimeChangedAction &action,
40         const TimeFinalizeAction &finalize, int &errCode);
41 
42     // Notify TIME_CHANGE_EVENT.
43     void NotifyTimeChange(TimeOffset offset) const;
44 
45     bool EmptyListener() const;
46 
47     bool IsTimeChanged() const;
48 
49     void SetTimeChanged(bool timeChange);
50 private:
51     static constexpr  uint64_t MONITOR_INTERVAL = 1 * 1000; // 1s
52     static constexpr int64_t MAX_NOISE = 9 * 100 * 1000; // 900ms
53     static const EventType TIME_CHANGE_EVENT = 1;
54     static const uint64_t INVALID_TIMESTAMP = 0;
55 
56     // Get the current system time
57     static Timestamp GetSysCurrentTime();
58 
59     // Get the Monotonic time
60     static Timestamp GetMonotonicTime();
61 
62     // prepare notifier chain
63     int PrepareNotifierChain();
64 
65     // Callback for the Timer
66     int TimeTick(TimerId timerId);
67 
68     mutable std::mutex timeTickMonitorLock_;
69     NotificationChain *timeChangedNotifier_;
70     RuntimeContext *runtimeCxt_;
71     TimerId monitorTimerId_ = 0;
72     TimerAction monitorCallback_;
73     Timestamp lastMonotonicTime_ = 0;
74     Timestamp lastSystemTime_ = 0;
75     bool isStarted_ = false;
76     std::atomic<bool> timeChanged_ = false;
77 };
78 } // namespace DistributedDB
79 
80 #endif // TIME_TICK_MONITOR_H