Skip to content

Commit c41347f

Browse files
authored
Merge pull request #53 from arik-so/2023/08/query-timestamp-fix
Switch timestamp queries to use f64
2 parents 2079fc9 + a631bfd commit c41347f

File tree

1 file changed

+33
-22
lines changed

1 file changed

+33
-22
lines changed

src/lookup.rs

Lines changed: 33 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
use std::collections::{BTreeMap, HashSet};
22
use std::io::Cursor;
3-
use std::ops::{Add, Deref};
3+
use std::ops::Deref;
44
use std::sync::Arc;
5-
use std::time::{Duration, Instant, SystemTime};
5+
use std::time::{Instant, SystemTime, UNIX_EPOCH};
66

77
use lightning::ln::msgs::{ChannelAnnouncement, ChannelUpdate, UnsignedChannelAnnouncement, UnsignedChannelUpdate};
88
use lightning::routing::gossip::NetworkGraph;
@@ -79,7 +79,6 @@ pub(super) async fn connect_to_db() -> (Client, Connection<Socket, NoTlsStream>)
7979
/// after `last_sync_timestamp`
8080
pub(super) async fn fetch_channel_announcements<L: Deref>(delta_set: &mut DeltaSet, network_graph: Arc<NetworkGraph<L>>, client: &Client, last_sync_timestamp: u32, logger: L) where L::Target: Logger {
8181
log_info!(logger, "Obtaining channel ids from network graph");
82-
let last_sync_timestamp_object = SystemTime::UNIX_EPOCH.add(Duration::from_secs(last_sync_timestamp as u64));
8382
let channel_ids = {
8483
let read_only_graph = network_graph.read_only();
8584
log_info!(logger, "Retrieved read-only network graph copy");
@@ -89,28 +88,35 @@ pub(super) async fn fetch_channel_announcements<L: Deref>(delta_set: &mut DeltaS
8988
.map(|c| c.1.announcement_message.as_ref().unwrap().contents.short_channel_id as i64)
9089
.collect::<Vec<_>>()
9190
};
91+
#[cfg(test)]
92+
log_info!(logger, "Channel IDs: {:?}", channel_ids);
93+
log_info!(logger, "Last sync timestamp: {}", last_sync_timestamp);
94+
let last_sync_timestamp_float = last_sync_timestamp as f64;
9295

9396
log_info!(logger, "Obtaining corresponding database entries");
9497
// get all the channel announcements that are currently in the network graph
95-
let announcement_rows = client.query_raw("SELECT announcement_signed, seen FROM channel_announcements WHERE short_channel_id = any($1) ORDER BY short_channel_id ASC", [&channel_ids]).await.unwrap();
98+
let announcement_rows = client.query_raw("SELECT announcement_signed, CAST(EXTRACT('epoch' from seen) AS BIGINT) AS seen FROM channel_announcements WHERE short_channel_id = any($1) ORDER BY short_channel_id ASC", [&channel_ids]).await.unwrap();
9699
let mut pinned_rows = Box::pin(announcement_rows);
97100

101+
let mut announcement_count = 0;
98102
while let Some(row_res) = pinned_rows.next().await {
99103
let current_announcement_row = row_res.unwrap();
100104
let blob: Vec<u8> = current_announcement_row.get("announcement_signed");
101105
let mut readable = Cursor::new(blob);
102106
let unsigned_announcement = ChannelAnnouncement::read(&mut readable).unwrap().contents;
103107

104108
let scid = unsigned_announcement.short_channel_id;
105-
let current_seen_timestamp_object: SystemTime = current_announcement_row.get("seen");
106-
let current_seen_timestamp: u32 = current_seen_timestamp_object.duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs() as u32;
109+
let current_seen_timestamp = current_announcement_row.get::<_, i64>("seen") as u32;
107110

108111
let current_channel_delta = delta_set.entry(scid).or_insert(ChannelDelta::default());
109112
(*current_channel_delta).announcement = Some(AnnouncementDelta {
110113
announcement: unsigned_announcement,
111114
seen: current_seen_timestamp,
112115
});
116+
117+
announcement_count += 1;
113118
}
119+
log_info!(logger, "Fetched {} announcement rows", announcement_count);
114120

115121
{
116122
// THIS STEP IS USED TO DETERMINE IF A CHANNEL SHOULD BE OMITTED FROM THE DELTA
@@ -124,9 +130,9 @@ pub(super) async fn fetch_channel_announcements<L: Deref>(delta_set: &mut DeltaS
124130
// here is where the channels whose first update in either direction occurred after
125131
// `last_seen_timestamp` are added to the selection
126132
let params: [&(dyn tokio_postgres::types::ToSql + Sync); 2] =
127-
[&channel_ids, &last_sync_timestamp_object];
133+
[&channel_ids, &last_sync_timestamp_float];
128134
let newer_oldest_directional_updates = client.query_raw("
129-
SELECT * FROM (
135+
SELECT short_channel_id, CAST(EXTRACT('epoch' from distinct_chans.seen) AS BIGINT) AS seen FROM (
130136
SELECT DISTINCT ON (short_channel_id) *
131137
FROM (
132138
SELECT DISTINCT ON (short_channel_id, direction) short_channel_id, seen
@@ -136,22 +142,25 @@ pub(super) async fn fetch_channel_announcements<L: Deref>(delta_set: &mut DeltaS
136142
) AS directional_last_seens
137143
ORDER BY short_channel_id ASC, seen DESC
138144
) AS distinct_chans
139-
WHERE distinct_chans.seen >= $2
145+
WHERE distinct_chans.seen >= TO_TIMESTAMP($2)
140146
", params).await.unwrap();
141147
let mut pinned_updates = Box::pin(newer_oldest_directional_updates);
142148

149+
let mut newer_oldest_directional_update_count = 0;
143150
while let Some(row_res) = pinned_updates.next().await {
144151
let current_row = row_res.unwrap();
145152

146153
let scid: i64 = current_row.get("short_channel_id");
147-
let current_seen_timestamp_object: SystemTime = current_row.get("seen");
148-
let current_seen_timestamp: u32 = current_seen_timestamp_object.duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs() as u32;
154+
let current_seen_timestamp = current_row.get::<_, i64>("seen") as u32;
149155

150156
// the newer of the two oldest seen directional updates came after last sync timestamp
151157
let current_channel_delta = delta_set.entry(scid as u64).or_insert(ChannelDelta::default());
152158
// first time a channel was seen in both directions
153159
(*current_channel_delta).first_bidirectional_updates_seen = Some(current_seen_timestamp);
160+
161+
newer_oldest_directional_update_count += 1;
154162
}
163+
log_info!(logger, "Fetched {} update rows of the first update in a new direction", newer_oldest_directional_update_count);
155164
}
156165

157166
{
@@ -161,7 +170,7 @@ pub(super) async fn fetch_channel_announcements<L: Deref>(delta_set: &mut DeltaS
161170
// Steps:
162171
// — Obtain all updates, distinct by (scid, direction), ordered by seen DESC
163172
// — From those updates, select distinct by (scid), ordered by seen ASC (to obtain the older one per direction)
164-
let reminder_threshold_timestamp = SystemTime::now().checked_sub(config::CHANNEL_REMINDER_AGE).unwrap();
173+
let reminder_threshold_timestamp = SystemTime::now().checked_sub(config::CHANNEL_REMINDER_AGE).unwrap().duration_since(UNIX_EPOCH).unwrap().as_secs() as f64;
165174

166175
let params: [&(dyn tokio_postgres::types::ToSql + Sync); 2] =
167176
[&channel_ids, &reminder_threshold_timestamp];
@@ -176,10 +185,11 @@ pub(super) async fn fetch_channel_announcements<L: Deref>(delta_set: &mut DeltaS
176185
) AS directional_last_seens
177186
ORDER BY short_channel_id ASC, seen ASC
178187
) AS distinct_chans
179-
WHERE distinct_chans.seen <= $2
188+
WHERE distinct_chans.seen <= TO_TIMESTAMP($2)
180189
", params).await.unwrap();
181190
let mut pinned_updates = Box::pin(older_latest_directional_updates);
182191

192+
let mut older_latest_directional_update_count = 0;
183193
while let Some(row_res) = pinned_updates.next().await {
184194
let current_row = row_res.unwrap();
185195
let scid: i64 = current_row.get("short_channel_id");
@@ -211,13 +221,15 @@ pub(super) async fn fetch_channel_announcements<L: Deref>(delta_set: &mut DeltaS
211221
// we don't send reminders if we don't have the channel
212222
continue;
213223
}
224+
older_latest_directional_update_count += 1;
214225
}
226+
log_info!(logger, "Fetched {} update rows of the latest update in the less recently updated direction", older_latest_directional_update_count);
215227
}
216228
}
217229

218230
pub(super) async fn fetch_channel_updates<L: Deref>(delta_set: &mut DeltaSet, client: &Client, last_sync_timestamp: u32, logger: L) where L::Target: Logger {
219231
let start = Instant::now();
220-
let last_sync_timestamp_object = SystemTime::UNIX_EPOCH.add(Duration::from_secs(last_sync_timestamp as u64));
232+
let last_sync_timestamp_float = last_sync_timestamp as f64;
221233

222234
// get the latest channel update in each direction prior to last_sync_timestamp, provided
223235
// there was an update in either direction that happened after the last sync (to avoid
@@ -227,14 +239,14 @@ pub(super) async fn fetch_channel_updates<L: Deref>(delta_set: &mut DeltaSet, cl
227239
WHERE id IN (
228240
SELECT DISTINCT ON (short_channel_id, direction) id
229241
FROM channel_updates
230-
WHERE seen < $1 AND short_channel_id IN (
242+
WHERE seen < TO_TIMESTAMP($1) AND short_channel_id IN (
231243
SELECT DISTINCT ON (short_channel_id) short_channel_id
232244
FROM channel_updates
233-
WHERE seen >= $1
245+
WHERE seen >= TO_TIMESTAMP($1)
234246
)
235247
ORDER BY short_channel_id ASC, direction ASC, seen DESC
236248
)
237-
", [last_sync_timestamp_object]).await.unwrap();
249+
", [last_sync_timestamp_float]).await.unwrap();
238250
let mut pinned_rows = Box::pin(reference_rows);
239251

240252
log_info!(logger, "Fetched reference rows in {:?}", start.elapsed());
@@ -273,10 +285,10 @@ pub(super) async fn fetch_channel_updates<L: Deref>(delta_set: &mut DeltaSet, cl
273285
// have been omitted)
274286

275287
let intermediate_updates = client.query_raw("
276-
SELECT id, direction, blob_signed, seen
288+
SELECT id, direction, blob_signed, CAST(EXTRACT('epoch' from seen) AS BIGINT) AS seen
277289
FROM channel_updates
278-
WHERE seen >= $1
279-
", [last_sync_timestamp_object]).await.unwrap();
290+
WHERE seen >= TO_TIMESTAMP($1)
291+
", [last_sync_timestamp_float]).await.unwrap();
280292
let mut pinned_updates = Box::pin(intermediate_updates);
281293
log_info!(logger, "Fetched intermediate rows in {:?}", start.elapsed());
282294

@@ -294,8 +306,7 @@ pub(super) async fn fetch_channel_updates<L: Deref>(delta_set: &mut DeltaSet, cl
294306
intermediate_update_count += 1;
295307

296308
let direction: bool = intermediate_update.get("direction");
297-
let current_seen_timestamp_object: SystemTime = intermediate_update.get("seen");
298-
let current_seen_timestamp: u32 = current_seen_timestamp_object.duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs() as u32;
309+
let current_seen_timestamp = intermediate_update.get::<_, i64>("seen") as u32;
299310
let blob: Vec<u8> = intermediate_update.get("blob_signed");
300311
let mut readable = Cursor::new(blob);
301312
let unsigned_channel_update = ChannelUpdate::read(&mut readable).unwrap().contents;

0 commit comments

Comments
 (0)