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