Remove unused `consider_intermediate_updates` flag..optimizing query
[rapid-gossip-sync-server] / src / snapshot.rs
1 use std::collections::HashMap;
2 use std::fs;
3 use std::os::unix::fs::symlink;
4 use std::sync::Arc;
5 use std::time::{Duration, SystemTime, UNIX_EPOCH};
6
7 use lightning::routing::gossip::NetworkGraph;
8
9 use crate::{config, TestLogger};
10 use crate::config::cache_path;
11
12 pub(crate) struct Snapshotter {
13         network_graph: Arc<NetworkGraph<TestLogger>>,
14 }
15
16 impl Snapshotter {
17         pub fn new(network_graph: Arc<NetworkGraph<TestLogger>>) -> Self {
18                 Self { network_graph }
19         }
20
21         pub(crate) async fn snapshot_gossip(&self) {
22                 println!("Initiating snapshotting service");
23
24                 let snapshot_sync_day_factors = [1, 2, 3, 4, 5, 6, 7, 14, 21, u64::MAX];
25                 let round_day_seconds = config::SNAPSHOT_CALCULATION_INTERVAL as u64;
26
27                 let pending_snapshot_directory = format!("{}/snapshots_pending", cache_path());
28                 let pending_symlink_directory = format!("{}/symlinks_pending", cache_path());
29                 let finalized_snapshot_directory = format!("{}/snapshots", cache_path());
30                 let finalized_symlink_directory = format!("{}/symlinks", cache_path());
31                 let relative_symlink_to_snapshot_path = "../snapshots";
32
33                 // this is gonna be a never-ending background job
34                 loop {
35                         // 1. get the current timestamp
36                         let snapshot_generation_timestamp = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs();
37                         let reference_timestamp = Self::round_down_to_nearest_multiple(snapshot_generation_timestamp, round_day_seconds);
38                         println!("Capturing snapshots at {} for: {}", snapshot_generation_timestamp, reference_timestamp);
39
40                         // 2. sleep until the next round 24 hours
41                         // 3. refresh all snapshots
42
43                         // the stored snapshots should adhere to the following format
44                         // from one day ago
45                         // from two days ago
46                         // …
47                         // from a week ago
48                         // from two weeks ago
49                         // from three weeks ago
50                         // full
51                         // That means that at any given moment, there should only ever be
52                         // 6 (daily) + 3 (weekly) + 1 (total) = 10 cached snapshots
53                         // The snapshots, unlike dynamic updates, should account for all intermediate
54                         // channel updates
55
56                         // purge and recreate the pending directories
57                         if fs::metadata(&pending_snapshot_directory).is_ok(){
58                                 fs::remove_dir_all(&pending_snapshot_directory).expect("Failed to remove pending snapshot directory.");
59                         }
60                         if fs::metadata(&pending_symlink_directory).is_ok(){
61                                 fs::remove_dir_all(&pending_symlink_directory).expect("Failed to remove pending symlink directory.");
62                         }
63                         fs::create_dir_all(&pending_snapshot_directory).expect("Failed to create pending snapshot directory");
64                         fs::create_dir_all(&pending_symlink_directory).expect("Failed to create pending symlink directory");
65
66                         let mut snapshot_sync_timestamps: Vec<(u64, u64)> = Vec::new();
67                         for factor in &snapshot_sync_day_factors {
68                                 // basically timestamp - day_seconds * factor
69                                 let timestamp = reference_timestamp.saturating_sub(round_day_seconds.saturating_mul(factor.clone()));
70                                 snapshot_sync_timestamps.push((factor.clone(), timestamp));
71                         };
72
73                         let mut snapshot_filenames_by_day_range: HashMap<u64, String> = HashMap::with_capacity(10);
74
75                         for (day_range, current_last_sync_timestamp) in &snapshot_sync_timestamps {
76                                 let network_graph_clone = self.network_graph.clone();
77                                 {
78                                         println!("Calculating {}-day snapshot", day_range);
79                                         // calculate the snapshot
80                                         let snapshot = super::serialize_delta(network_graph_clone, current_last_sync_timestamp.clone() as u32).await;
81
82                                         // persist the snapshot and update the symlink
83                                         let snapshot_filename = format!("snapshot__calculated-at:{}__range:{}-days__previous-sync:{}.lngossip", reference_timestamp, day_range, current_last_sync_timestamp);
84                                         let snapshot_path = format!("{}/{}", pending_snapshot_directory, snapshot_filename);
85                                         println!("Persisting {}-day snapshot: {} ({} messages, {} announcements, {} updates ({} full, {} incremental))", day_range, snapshot_filename, snapshot.message_count, snapshot.announcement_count, snapshot.update_count, snapshot.update_count_full, snapshot.update_count_incremental);
86                                         fs::write(&snapshot_path, snapshot.data).unwrap();
87                                         snapshot_filenames_by_day_range.insert(day_range.clone(), snapshot_filename);
88                                 }
89                         }
90
91                         {
92                                 // create dummy symlink
93                                 let dummy_filename = "empty_delta.lngossip";
94                                 let dummy_snapshot = super::serialize_empty_blob(reference_timestamp);
95                                 let dummy_snapshot_path = format!("{}/{}", pending_snapshot_directory, dummy_filename);
96                                 fs::write(&dummy_snapshot_path, dummy_snapshot).unwrap();
97
98                                 let dummy_symlink_path = format!("{}/{}.bin", pending_symlink_directory, reference_timestamp);
99                                 let relative_dummy_snapshot_path = format!("{}/{}", relative_symlink_to_snapshot_path, dummy_filename);
100                                 println!("Symlinking dummy: {} -> {}", dummy_symlink_path, relative_dummy_snapshot_path);
101                                 symlink(&relative_dummy_snapshot_path, &dummy_symlink_path).unwrap();
102                         }
103
104                         for i in 0..10_001u64 {
105                                 // let's create non-dummy-symlinks
106
107                                 // first, determine which snapshot range should be referenced
108                                 let referenced_day_range = if i == 0 {
109                                         // special-case 0 to always refer to a full/initial sync
110                                         u64::MAX
111                                 } else {
112                                         // find min(x) in snapshot_sync_day_factors where x >= i
113                                         snapshot_sync_day_factors.iter().find(|x| {
114                                                 x >= &&i
115                                         }).unwrap().clone()
116                                 };
117
118                                 let snapshot_filename = snapshot_filenames_by_day_range.get(&referenced_day_range).unwrap();
119                                 let relative_snapshot_path = format!("{}/{}", relative_symlink_to_snapshot_path, snapshot_filename);
120
121                                 let canonical_last_sync_timestamp = if i == 0 {
122                                         // special-case 0 to always refer to a full/initial sync
123                                         0
124                                 } else {
125                                         reference_timestamp.saturating_sub(round_day_seconds.saturating_mul(i))
126                                 };
127                                 let symlink_path = format!("{}/{}.bin", pending_symlink_directory, canonical_last_sync_timestamp);
128
129                                 println!("Symlinking: {} -> {} ({} -> {}", i, referenced_day_range, symlink_path, relative_snapshot_path);
130                                 symlink(&relative_snapshot_path, &symlink_path).unwrap();
131                         }
132
133                         let update_time_path = format!("{}/update_time.txt", pending_symlink_directory);
134                         let update_time = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs();
135                         fs::write(&update_time_path, format!("{}", update_time)).unwrap();
136
137                         if fs::metadata(&finalized_snapshot_directory).is_ok(){
138                                 fs::remove_dir_all(&finalized_snapshot_directory).expect("Failed to remove finalized snapshot directory.");
139                         }
140                         if fs::metadata(&finalized_symlink_directory).is_ok(){
141                                 fs::remove_dir_all(&finalized_symlink_directory).expect("Failed to remove pending symlink directory.");
142                         }
143                         fs::rename(&pending_snapshot_directory, &finalized_snapshot_directory).expect("Failed to finalize snapshot directory.");
144                         fs::rename(&pending_symlink_directory, &finalized_symlink_directory).expect("Failed to finalize symlink directory.");
145
146                         // constructing the snapshots may have taken a while
147                         let current_time = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs();
148                         let remainder = current_time % round_day_seconds;
149                         let time_until_next_day = round_day_seconds - remainder;
150
151                         println!("Sleeping until next snapshot capture: {}s", time_until_next_day);
152                         // add in an extra five seconds to assure the rounding down works correctly
153                         let sleep = tokio::time::sleep(Duration::from_secs(time_until_next_day + 5));
154                         sleep.await;
155                 }
156         }
157
158         pub(super) fn round_down_to_nearest_multiple(number: u64, multiple: u64) -> u64 {
159                 let round_multiple_delta = number % multiple;
160                 number - round_multiple_delta
161         }
162 }