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