Switch Logger from Arc to Deref.
[rapid-gossip-sync-server] / src / persistence.rs
1 use std::fs::OpenOptions;
2 use std::io::{BufWriter, Write};
3 use std::ops::Deref;
4 use std::sync::Arc;
5 use std::time::{Duration, Instant};
6 use lightning::routing::gossip::NetworkGraph;
7 use lightning::util::logger::Logger;
8 use lightning::util::ser::Writeable;
9 use tokio::sync::mpsc;
10 use tokio_postgres::NoTls;
11
12 use crate::config;
13 use crate::types::GossipMessage;
14
15 const POSTGRES_INSERT_TIMEOUT: Duration = Duration::from_secs(15);
16
17 pub(crate) struct GossipPersister<L: Deref> where L::Target: Logger {
18         gossip_persistence_receiver: mpsc::Receiver<GossipMessage>,
19         network_graph: Arc<NetworkGraph<L>>,
20 }
21
22 impl<L: Deref> GossipPersister<L> where L::Target: Logger {
23         pub fn new(network_graph: Arc<NetworkGraph<L>>) -> (Self, mpsc::Sender<GossipMessage>) {
24                 let (gossip_persistence_sender, gossip_persistence_receiver) =
25                         mpsc::channel::<GossipMessage>(100);
26                 (GossipPersister {
27                         gossip_persistence_receiver,
28                         network_graph
29                 }, gossip_persistence_sender)
30         }
31
32         pub(crate) async fn persist_gossip(&mut self) {
33                 let connection_config = config::db_connection_config();
34                 let (mut client, connection) =
35                         connection_config.connect(NoTls).await.unwrap();
36
37                 tokio::spawn(async move {
38                         if let Err(e) = connection.await {
39                                 panic!("connection error: {}", e);
40                         }
41                 });
42
43                 {
44                         // initialize the database
45                         let initialization = client
46                                 .execute(config::db_config_table_creation_query(), &[])
47                                 .await;
48                         if let Err(initialization_error) = initialization {
49                                 panic!("db init error: {}", initialization_error);
50                         }
51
52                         let cur_schema = client.query("SELECT db_schema FROM config WHERE id = $1", &[&1]).await.unwrap();
53                         if !cur_schema.is_empty() {
54                                 config::upgrade_db(cur_schema[0].get(0), &mut client).await;
55                         }
56
57                         let initialization = client
58                                 .execute(
59                                         // TODO: figure out a way to fix the id value without Postgres complaining about
60                                         // its value not being default
61                                         "INSERT INTO config (id, db_schema) VALUES ($1, $2) ON CONFLICT (id) DO NOTHING",
62                                         &[&1, &config::SCHEMA_VERSION]
63                                 ).await;
64                         if let Err(initialization_error) = initialization {
65                                 panic!("db init error: {}", initialization_error);
66                         }
67
68                         let initialization = client
69                                 .execute(config::db_announcement_table_creation_query(), &[])
70                                 .await;
71                         if let Err(initialization_error) = initialization {
72                                 panic!("db init error: {}", initialization_error);
73                         }
74
75                         let initialization = client
76                                 .execute(
77                                         config::db_channel_update_table_creation_query(),
78                                         &[],
79                                 )
80                                 .await;
81                         if let Err(initialization_error) = initialization {
82                                 panic!("db init error: {}", initialization_error);
83                         }
84
85                         let initialization = client
86                                 .batch_execute(config::db_index_creation_query())
87                                 .await;
88                         if let Err(initialization_error) = initialization {
89                                 panic!("db init error: {}", initialization_error);
90                         }
91                 }
92
93                 // print log statement every minute
94                 let mut latest_persistence_log = Instant::now() - Duration::from_secs(60);
95                 let mut i = 0u32;
96                 let mut latest_graph_cache_time = Instant::now();
97                 // TODO: it would be nice to have some sort of timeout here so after 10 seconds of
98                 // inactivity, some sort of message could be broadcast signaling the activation of request
99                 // processing
100                 while let Some(gossip_message) = &self.gossip_persistence_receiver.recv().await {
101                         i += 1; // count the persisted gossip messages
102
103                         if latest_persistence_log.elapsed().as_secs() >= 60 {
104                                 println!("Persisting gossip message #{}", i);
105                                 latest_persistence_log = Instant::now();
106                         }
107
108                         // has it been ten minutes? Just cache it
109                         if latest_graph_cache_time.elapsed().as_secs() >= 600 {
110                                 self.persist_network_graph();
111                                 latest_graph_cache_time = Instant::now();
112                         }
113
114                         match &gossip_message {
115                                 GossipMessage::ChannelAnnouncement(announcement) => {
116                                         let scid = announcement.contents.short_channel_id as i64;
117
118                                         // start with the type prefix, which is already known a priori
119                                         let mut announcement_signed = Vec::new();
120                                         announcement.write(&mut announcement_signed).unwrap();
121
122                                         tokio::time::timeout(POSTGRES_INSERT_TIMEOUT, client
123                                                 .execute("INSERT INTO channel_announcements (\
124                                                         short_channel_id, \
125                                                         announcement_signed \
126                                                 ) VALUES ($1, $2) ON CONFLICT (short_channel_id) DO NOTHING", &[
127                                                         &scid,
128                                                         &announcement_signed
129                                                 ])).await.unwrap().unwrap();
130                                 }
131                                 GossipMessage::ChannelUpdate(update) => {
132                                         let scid = update.contents.short_channel_id as i64;
133
134                                         let timestamp = update.contents.timestamp as i64;
135
136                                         let direction = (update.contents.flags & 1) == 1;
137                                         let disable = (update.contents.flags & 2) > 0;
138
139                                         let cltv_expiry_delta = update.contents.cltv_expiry_delta as i32;
140                                         let htlc_minimum_msat = update.contents.htlc_minimum_msat as i64;
141                                         let fee_base_msat = update.contents.fee_base_msat as i32;
142                                         let fee_proportional_millionths =
143                                                 update.contents.fee_proportional_millionths as i32;
144                                         let htlc_maximum_msat = update.contents.htlc_maximum_msat as i64;
145
146                                         // start with the type prefix, which is already known a priori
147                                         let mut update_signed = Vec::new();
148                                         update.write(&mut update_signed).unwrap();
149
150                                         tokio::time::timeout(POSTGRES_INSERT_TIMEOUT, client
151                                                 .execute("INSERT INTO channel_updates (\
152                                                         short_channel_id, \
153                                                         timestamp, \
154                                                         channel_flags, \
155                                                         direction, \
156                                                         disable, \
157                                                         cltv_expiry_delta, \
158                                                         htlc_minimum_msat, \
159                                                         fee_base_msat, \
160                                                         fee_proportional_millionths, \
161                                                         htlc_maximum_msat, \
162                                                         blob_signed \
163                                                 ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)  ON CONFLICT DO NOTHING", &[
164                                                         &scid,
165                                                         &timestamp,
166                                                         &(update.contents.flags as i16),
167                                                         &direction,
168                                                         &disable,
169                                                         &cltv_expiry_delta,
170                                                         &htlc_minimum_msat,
171                                                         &fee_base_msat,
172                                                         &fee_proportional_millionths,
173                                                         &htlc_maximum_msat,
174                                                         &update_signed
175                                                 ])).await.unwrap().unwrap();
176                                 }
177                         }
178                 }
179         }
180
181         fn persist_network_graph(&self) {
182                 println!("Caching network graph…");
183                 let cache_path = config::network_graph_cache_path();
184                 let file = OpenOptions::new()
185                         .create(true)
186                         .write(true)
187                         .truncate(true)
188                         .open(&cache_path)
189                         .unwrap();
190                 self.network_graph.remove_stale_channels_and_tracking();
191                 let mut writer = BufWriter::new(file);
192                 self.network_graph.write(&mut writer).unwrap();
193                 writer.flush().unwrap();
194                 println!("Cached network graph!");
195         }
196 }