-
Notifications
You must be signed in to change notification settings - Fork 236
/
manager.rs
1342 lines (1245 loc) · 44.5 KB
/
manager.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2021 - Nym Technologies SA <[email protected]>
// SPDX-License-Identifier: GPL-3.0-only
use crate::node_status_api::models::{HistoricalUptime as ApiHistoricalUptime, Uptime};
use crate::node_status_api::utils::{ActiveGatewayStatuses, ActiveMixnodeStatuses};
use crate::support::storage::models::{
ActiveGateway, ActiveMixnode, GatewayDetails, HistoricalUptime, MixnodeDetails, NodeStatus,
RewardingReport, TestedGatewayStatus, TestedMixnodeStatus, TestingRoute,
};
use nym_mixnet_contract_common::{EpochId, IdentityKey, NodeId};
use nym_types::monitoring::NodeResult;
use sqlx::FromRow;
use time::{Date, OffsetDateTime};
use tracing::info;
#[derive(Clone)]
pub(crate) struct StorageManager {
pub(crate) connection_pool: sqlx::SqlitePool,
}
pub struct AvgMixnodeReliability {
mix_id: NodeId,
value: Option<f32>,
}
impl AvgMixnodeReliability {
pub fn mix_id(&self) -> NodeId {
self.mix_id
}
pub fn value(&self) -> f32 {
self.value.unwrap_or_default()
}
}
#[derive(FromRow)]
pub struct AvgGatewayReliability {
node_id: NodeId,
value: Option<f32>,
}
impl AvgGatewayReliability {
pub fn node_id(&self) -> NodeId {
self.node_id
}
pub fn value(&self) -> f32 {
self.value.unwrap_or_default()
}
}
// all SQL goes here
impl StorageManager {
pub(crate) async fn get_mixnode_mix_ids_by_identity(
&self,
identity: &str,
) -> Result<Vec<NodeId>, sqlx::Error> {
let ids = sqlx::query!(
r#"SELECT mix_id as "mix_id: NodeId" FROM mixnode_details WHERE identity_key = ?"#,
identity
)
.fetch_all(&self.connection_pool)
.await?
.into_iter()
.map(|row| row.mix_id)
.collect();
Ok(ids)
}
pub(crate) async fn get_all_avg_mix_reliability_in_last_24hr(
&self,
end_ts_secs: i64,
) -> Result<Vec<AvgMixnodeReliability>, sqlx::Error> {
let start_ts_secs = end_ts_secs - 86400;
self.get_all_avg_mix_reliability_in_time_interval(start_ts_secs, end_ts_secs)
.await
}
pub(crate) async fn get_all_avg_gateway_reliability_in_last_24hr(
&self,
end_ts_secs: i64,
) -> Result<Vec<AvgGatewayReliability>, sqlx::Error> {
let start_ts_secs = end_ts_secs - 86400;
self.get_all_avg_gateway_reliability_in_interval(start_ts_secs, end_ts_secs)
.await
}
pub(crate) async fn get_all_avg_mix_reliability_in_time_interval(
&self,
start_ts_secs: i64,
end_ts_secs: i64,
) -> Result<Vec<AvgMixnodeReliability>, sqlx::Error> {
let result = sqlx::query_as!(
AvgMixnodeReliability,
r#"
SELECT
d.mix_id as "mix_id: NodeId",
AVG(s.reliability) as "value: f32"
FROM
mixnode_details d
JOIN
mixnode_status s on d.id = s.mixnode_details_id
WHERE
timestamp >= ? AND
timestamp <= ?
GROUP BY 1
"#,
start_ts_secs,
end_ts_secs
)
.fetch_all(&self.connection_pool)
.await?;
Ok(result)
}
pub(crate) async fn get_all_avg_gateway_reliability_in_interval(
&self,
start_ts_secs: i64,
end_ts_secs: i64,
) -> Result<Vec<AvgGatewayReliability>, sqlx::Error> {
// we can't use `query_as!` macro because we don't apply all required table changes during sqlx migrations.
// some (like v3 directory) happens at runtime
let result = sqlx::query_as(
r#"
SELECT
d.node_id as "node_id: NodeId",
CASE WHEN count(*) > 3 THEN AVG(reliability) ELSE 100 END as "value: f32"
FROM
gateway_details d
JOIN
gateway_status s on d.id = s.gateway_details_id
WHERE
timestamp >= ? AND
timestamp <= ?
GROUP BY 1
"#,
)
.bind(start_ts_secs)
.bind(end_ts_secs)
.fetch_all(&self.connection_pool)
.await?;
Ok(result)
}
/// Tries to obtain row id of given mixnode given its identity.
///
/// # Arguments
///
/// * `mix_id`: mix-id (as assigned by the smart contract) of the mixnode.
pub(crate) async fn get_mixnode_database_id(
&self,
mix_id: NodeId,
) -> Result<Option<i64>, sqlx::Error> {
let id = sqlx::query!("SELECT id FROM mixnode_details WHERE mix_id = ?", mix_id)
.fetch_optional(&self.connection_pool)
.await?
.map(|row| row.id);
Ok(id)
}
pub(crate) async fn get_gateway_database_id(
&self,
node_id: NodeId,
) -> Result<Option<i64>, sqlx::Error> {
let id = sqlx::query!("SELECT id FROM gateway_details WHERE node_id = ?", node_id)
.fetch_optional(&self.connection_pool)
.await?
.map(|row| row.id);
Ok(id)
}
/// Tries to obtain row id of given gateway given its identity
pub(crate) async fn get_gateway_database_id_by_identity(
&self,
identity: &str,
) -> Result<Option<i64>, sqlx::Error> {
let id = sqlx::query!(
"SELECT id FROM gateway_details WHERE identity = ?",
identity
)
.fetch_optional(&self.connection_pool)
.await?
.map(|row| row.id);
Ok(id)
}
pub(crate) async fn get_gateway_node_id_from_identity_key(
&self,
identity: &str,
) -> Result<Option<NodeId>, sqlx::Error> {
let node_id = sqlx::query!(
r#"SELECT node_id as "node_id: NodeId" FROM gateway_details WHERE identity = ?"#,
identity
)
.fetch_optional(&self.connection_pool)
.await?
.map(|row| row.node_id);
Ok(node_id)
}
pub(crate) async fn get_gateway_identity_key(
&self,
node_id: NodeId,
) -> Result<Option<IdentityKey>, sqlx::Error> {
let identity_key = sqlx::query!(
"SELECT identity FROM gateway_details WHERE node_id = ?",
node_id
)
.fetch_optional(&self.connection_pool)
.await?
.map(|row| row.identity);
Ok(identity_key)
}
/// Tries to obtain identity value of given mixnode given its mix_id
///
/// # Arguments
///
/// * `mix_id`: mix-id (as assigned by the smart contract) of the mixnode.
pub(crate) async fn get_mixnode_identity_key(
&self,
mix_id: NodeId,
) -> Result<Option<IdentityKey>, sqlx::Error> {
let identity_key = sqlx::query!(
"SELECT identity_key FROM mixnode_details WHERE mix_id = ?",
mix_id
)
.fetch_optional(&self.connection_pool)
.await?
.map(|row| row.identity_key);
Ok(identity_key)
}
/// Gets all reliability statuses for mixnode with particular identity that were inserted
/// into the database after the specified unix timestamp.
///
/// # Arguments
///
/// * `mix_id`: mix-id (as assigned by the smart contract) of the mixnode.
/// * `timestamp`: unix timestamp of the lower bound of the selection.
pub(crate) async fn get_mixnode_statuses_since(
&self,
mix_id: NodeId,
timestamp: i64,
) -> Result<Vec<NodeStatus>, sqlx::Error> {
sqlx::query_as!(
NodeStatus,
r#"
SELECT timestamp, reliability as "reliability: u8"
FROM mixnode_status
JOIN mixnode_details
ON mixnode_status.mixnode_details_id = mixnode_details.id
WHERE mixnode_details.mix_id=? AND mixnode_status.timestamp > ?;
"#,
mix_id,
timestamp,
)
.fetch_all(&self.connection_pool)
.await
}
/// Gets all reliability statuses for gateway with particular identity that were inserted
/// into the database after the specified unix timestamp.
///
/// # Arguments
///
/// * `identity`: identity (base58-encoded public key) of the gateway.
/// * `timestamp`: unix timestamp of the lower bound of the selection.
pub(crate) async fn get_gateway_statuses_since(
&self,
node_id: NodeId,
timestamp: i64,
) -> Result<Vec<NodeStatus>, sqlx::Error> {
sqlx::query_as!(
NodeStatus,
r#"
SELECT timestamp, reliability as "reliability: u8"
FROM gateway_status
JOIN gateway_details
ON gateway_status.gateway_details_id = gateway_details.id
WHERE gateway_details.node_id=? AND gateway_status.timestamp > ?;
"#,
node_id,
timestamp,
)
.fetch_all(&self.connection_pool)
.await
}
/// Gets the historical daily uptime associated with the particular mixnode
///
/// # Arguments
///
/// * `mix_id`: mix-id (as assigned by the smart contract) of the mixnode.
pub(crate) async fn get_mixnode_historical_uptimes(
&self,
mix_id: NodeId,
) -> Result<Vec<ApiHistoricalUptime>, sqlx::Error> {
let uptimes = sqlx::query!(
r#"
SELECT date, uptime
FROM mixnode_historical_uptime
JOIN mixnode_details
ON mixnode_historical_uptime.mixnode_details_id = mixnode_details.id
WHERE mixnode_details.mix_id = ?
ORDER BY date ASC
"#,
mix_id
)
.fetch_all(&self.connection_pool)
.await?
.into_iter()
// filter out nodes with valid uptime (in theory all should be 100% valid since we insert them ourselves, but
// better safe than sorry and not use an unwrap)
.filter_map(|row| {
Uptime::try_from(row.uptime.unwrap_or_default())
.map(|uptime| ApiHistoricalUptime {
date: row.date.unwrap_or_default(),
uptime,
})
.ok()
})
.collect();
Ok(uptimes)
}
/// Gets the historical daily uptime associated with the particular gateway
///
/// # Arguments
///
/// * `identity`: identity (base58-encoded public key) of the gateway.
pub(crate) async fn get_gateway_historical_uptimes(
&self,
node_id: NodeId,
) -> Result<Vec<ApiHistoricalUptime>, sqlx::Error> {
let uptimes = sqlx::query!(
r#"
SELECT date, uptime
FROM gateway_historical_uptime
JOIN gateway_details
ON gateway_historical_uptime.gateway_details_id = gateway_details.id
WHERE gateway_details.node_id = ?
ORDER BY date ASC
"#,
node_id
)
.fetch_all(&self.connection_pool)
.await?
.into_iter()
// filter out nodes with valid uptime (in theory all should be 100% valid since we insert them ourselves, but
// better safe than sorry and not use an unwrap)
.filter_map(|row| {
Uptime::try_from(row.uptime.unwrap_or_default())
.map(|uptime| ApiHistoricalUptime {
date: row.date.unwrap_or_default(),
uptime,
})
.ok()
})
.collect();
Ok(uptimes)
}
pub(crate) async fn get_historical_mix_uptime_on(
&self,
contract_node_id: i64,
date: Date,
) -> Result<Option<HistoricalUptime>, sqlx::Error> {
sqlx::query_as!(
HistoricalUptime,
r#"
SELECT date as "date!: Date", uptime as "uptime!"
FROM mixnode_historical_uptime
JOIN mixnode_details
ON mixnode_historical_uptime.mixnode_details_id = mixnode_details.id
WHERE
mixnode_details.mix_id = ?
AND
mixnode_historical_uptime.date = ?
"#,
contract_node_id,
date
)
.fetch_optional(&self.connection_pool)
.await
}
pub(crate) async fn get_historical_gateway_uptime_on(
&self,
contract_node_id: i64,
date: Date,
) -> Result<Option<HistoricalUptime>, sqlx::Error> {
sqlx::query_as!(
HistoricalUptime,
r#"
SELECT date as "date!: Date", uptime as "uptime!"
FROM gateway_historical_uptime
JOIN gateway_details
ON gateway_historical_uptime.gateway_details_id = gateway_details.id
WHERE
gateway_details.node_id = ?
AND
gateway_historical_uptime.date = ?
"#,
contract_node_id,
date
)
.fetch_optional(&self.connection_pool)
.await
}
/// Gets all reliability statuses for mixnode with particular id that were inserted
/// into the database within the specified time interval.
///
/// # Arguments
///
/// * `since`: unix timestamp indicating the lower bound interval of the selection.
/// * `until`: unix timestamp indicating the upper bound interval of the selection.
pub(crate) async fn get_mixnode_statuses_by_database_id(
&self,
id: i64,
since: i64,
until: i64,
) -> Result<Vec<NodeStatus>, sqlx::Error> {
sqlx::query_as!(
NodeStatus,
r#"
SELECT timestamp, reliability as "reliability: u8"
FROM mixnode_status
WHERE mixnode_details_id=? AND timestamp > ? AND timestamp < ?;
"#,
id,
since,
until,
)
.fetch_all(&self.connection_pool)
.await
}
pub(crate) async fn get_mixnode_average_reliability_in_interval(
&self,
id: i64,
start: i64,
end: i64,
) -> Result<Option<f32>, sqlx::Error> {
if cfg!(feature = "v2-performance") {
let result = sqlx::query!(
r#"
SELECT AVG(reliability) as "reliability: f32" FROM mixnode_status_v2
WHERE mixnode_details_id= ? AND timestamp >= ? AND timestamp <= ?
"#,
id,
start,
end
)
.fetch_one(&self.connection_pool)
.await?;
Ok(result.reliability)
} else {
let result = sqlx::query!(
r#"
SELECT AVG(reliability) as "reliability: f32" FROM mixnode_status
WHERE mixnode_details_id= ? AND timestamp >= ? AND timestamp <= ?
"#,
id,
start,
end
)
.fetch_one(&self.connection_pool)
.await?;
Ok(result.reliability)
}
}
pub(super) async fn get_gateway_average_reliability_in_interval(
&self,
id: i64,
start: i64,
end: i64,
) -> Result<Option<f32>, sqlx::Error> {
let result = sqlx::query!(
r#"
SELECT AVG(reliability) as "reliability: f32" FROM gateway_status
WHERE gateway_details_id= ? AND timestamp >= ? AND timestamp <= ?
"#,
id,
start,
end
)
.fetch_one(&self.connection_pool)
.await?;
Ok(result.reliability)
}
/// Gets all reliability statuses for gateway with particular id that were inserted
/// into the database within the specified time interval.
///
/// # Arguments
///
/// * `since`: unix timestamp indicating the lower bound interval of the selection.
/// * `until`: unix timestamp indicating the upper bound interval of the selection.
pub(crate) async fn get_gateway_statuses_by_database_id(
&self,
id: i64,
since: i64,
until: i64,
) -> Result<Vec<NodeStatus>, sqlx::Error> {
sqlx::query_as!(
NodeStatus,
r#"
SELECT timestamp, reliability as "reliability: u8"
FROM gateway_status
WHERE gateway_details_id=? AND timestamp > ? AND timestamp < ?;
"#,
id,
since,
until,
)
.fetch_all(&self.connection_pool)
.await
}
/// Tries to submit mixnode [`NodeResult`] from the network monitor to the database.
///
/// # Arguments
///
/// * `timestamp`: unix timestamp indicating when the measurements took place.
/// * `mixnode_results`: reliability results of each node that got tested.
pub(crate) async fn submit_mixnode_statuses(
&self,
timestamp: i64,
mixnode_results: Vec<NodeResult>,
) -> Result<(), sqlx::Error> {
// insert it all in a transaction to make sure all nodes are updated at the same time
// (plus it's a nice guard against new nodes)
let mut tx = self.connection_pool.begin().await?;
for mixnode_result in mixnode_results {
let mixnode_id = sqlx::query!(
r#"
INSERT OR IGNORE INTO mixnode_details(mix_id, identity_key) VALUES (?, ?);
SELECT id FROM mixnode_details WHERE mix_id = ?;
"#,
mixnode_result.node_id,
mixnode_result.identity,
mixnode_result.node_id,
)
.fetch_one(&mut *tx)
.await?
.id;
// insert the actual status
sqlx::query!(
r#"
INSERT INTO mixnode_status (mixnode_details_id, reliability, timestamp) VALUES (?, ?, ?);
"#,
mixnode_id,
mixnode_result.reliability,
timestamp
)
.execute(&mut *tx)
.await?;
}
// finally commit the transaction
tx.commit().await
}
pub(crate) async fn submit_mixnode_statuses_v2(
&self,
mixnode_results: &[NodeResult],
) -> Result<(), sqlx::Error> {
info!("Inserting {} mixnode statuses", mixnode_results.len());
let timestamp = OffsetDateTime::now_utc().unix_timestamp();
// insert it all in a transaction to make sure all nodes are updated at the same time
// (plus it's a nice guard against new nodes)
let mut tx = self.connection_pool.begin().await?;
for mixnode_result in mixnode_results {
let mixnode_id = sqlx::query!(
r#"
INSERT OR IGNORE INTO mixnode_details_v2(node_id, identity_key) VALUES (?, ?);
SELECT id FROM mixnode_details_v2 WHERE node_id = ?;
"#,
mixnode_result.node_id,
mixnode_result.identity,
mixnode_result.node_id,
)
.fetch_one(&mut *tx)
.await?
.id;
// insert the actual status
sqlx::query!(
r#"
INSERT INTO mixnode_status_v2 (mixnode_details_id, reliability, timestamp) VALUES (?, ?, ?);
"#,
mixnode_id,
mixnode_result.reliability,
timestamp
)
.execute(&mut *tx)
.await?;
}
// finally commit the transaction
tx.commit().await
}
/// Tries to submit gateway [`NodeResult`] from the network monitor to the database.
///
/// # Arguments
///
/// * `timestamp`: unix timestamp indicating when the measurements took place.
/// * `gateway_results`: reliability results of each node that got tested.
pub(crate) async fn submit_gateway_statuses(
&self,
timestamp: i64,
gateway_results: Vec<NodeResult>,
) -> Result<(), sqlx::Error> {
// insert it all in a transaction to make sure all nodes are updated at the same time
// (plus it's a nice guard against new nodes)
let mut tx = self.connection_pool.begin().await?;
for gateway_result in gateway_results {
// if gateway info doesn't exist, insert it and get its id
// same ID "problem" as described for mixnode insertion
let gateway_id = sqlx::query!(
r#"
INSERT OR IGNORE INTO gateway_details(node_id, identity) VALUES (?, ?);
SELECT id FROM gateway_details WHERE identity = ?;
"#,
gateway_result.node_id,
gateway_result.identity,
gateway_result.identity,
)
.fetch_one(&mut *tx)
.await?
.id;
// insert the actual status
sqlx::query!(
r#"
INSERT INTO gateway_status (gateway_details_id, reliability, timestamp) VALUES (?, ?, ?);
"#,
gateway_id,
gateway_result.reliability,
timestamp
)
.execute(&mut *tx)
.await?;
}
// finally commit the transaction
tx.commit().await
}
pub(crate) async fn submit_gateway_statuses_v2(
&self,
gateway_results: &[NodeResult],
) -> Result<(), sqlx::Error> {
info!("Inserting {} gateway statuses", gateway_results.len());
let timestamp = OffsetDateTime::now_utc().unix_timestamp();
// insert it all in a transaction to make sure all nodes are updated at the same time
// (plus it's a nice guard against new nodes)
let mut tx = self.connection_pool.begin().await?;
for gateway_result in gateway_results {
// if gateway info doesn't exist, insert it and get its id
// same ID "problem" as described for mixnode insertion
let gateway_id = sqlx::query!(
r#"
INSERT OR IGNORE INTO gateway_details_v2(identity, node_id) VALUES (?, ?);
SELECT id FROM gateway_details_v2 WHERE identity = ?;
"#,
gateway_result.identity,
gateway_result.node_id,
gateway_result.identity,
)
.fetch_one(&mut *tx)
.await?
.id;
// insert the actual status
sqlx::query!(
r#"
INSERT INTO gateway_status_v2 (gateway_details_id, reliability, timestamp) VALUES (?, ?, ?);
"#,
gateway_id,
gateway_result.reliability,
timestamp
)
.execute(&mut *tx)
.await?;
}
// finally commit the transaction
tx.commit().await
}
/// Saves the information about which nodes were used as core nodes during this particular
/// network monitor test run.
///
/// # Arguments
///
/// * `testing_route`: test route used for this particular network monitor run.
pub(crate) async fn submit_testing_route_used(
&self,
testing_route: TestingRoute,
) -> Result<(), sqlx::Error> {
sqlx::query!(
r#"
INSERT INTO testing_route
(gateway_id, layer1_mix_id, layer2_mix_id, layer3_mix_id, monitor_run_id)
VALUES (?, ?, ?, ?, ?);
"#,
testing_route.gateway_db_id,
testing_route.layer1_mix_db_id,
testing_route.layer2_mix_db_id,
testing_route.layer3_mix_db_id,
testing_route.monitor_run_db_id,
)
.execute(&self.connection_pool)
.await?;
Ok(())
}
/// Get the number of times mixnode with the particular id is present in any `testing_route`
/// since the provided unix timestamp.
///
/// # Arguments
///
/// * `db_mixnode_id`: id (as saved in the database) of the mixnode.
/// * `since`: unix timestamp indicating the lower bound interval of the selection.
pub(crate) async fn get_mixnode_testing_route_presence_count_since(
&self,
db_mixnode_id: i64,
since: i64,
) -> Result<i32, sqlx::Error> {
let count = sqlx::query!(
r#"
SELECT COUNT(*) as count FROM
(
SELECT monitor_run_id
FROM testing_route
WHERE testing_route.layer1_mix_id = ? OR testing_route.layer2_mix_id = ? OR testing_route.layer3_mix_id = ?
) testing_route
JOIN
(
SELECT id
FROM monitor_run
WHERE monitor_run.timestamp > ?
) monitor_run
ON monitor_run.id = testing_route.monitor_run_id;
"#,
db_mixnode_id,
db_mixnode_id,
db_mixnode_id,
since,
).fetch_one(&self.connection_pool)
.await?
.count;
Ok(count)
}
/// Get the number of times gateway with the particular id is present in any `testing_route`
/// since the provided unix timestamp.
///
/// # Arguments
///
/// * `gateway_id`: id (as saved in the database) of the gateway.
/// * `since`: unix timestamp indicating the lower bound interval of the selection.
pub(crate) async fn get_gateway_testing_route_presence_count_since(
&self,
gateway_id: i64,
since: i64,
) -> Result<i32, sqlx::Error> {
let count = sqlx::query!(
r#"
SELECT COUNT(*) as count FROM
(
SELECT monitor_run_id
FROM testing_route
WHERE testing_route.gateway_id = ?
) testing_route
JOIN
(
SELECT id
FROM monitor_run
WHERE monitor_run.timestamp > ?
) monitor_run
ON monitor_run.id = testing_route.monitor_run_id;
"#,
gateway_id,
since,
)
.fetch_one(&self.connection_pool)
.await?
.count;
Ok(count)
}
/// Checks whether there are already any historical uptimes with this particular date.
pub(crate) async fn check_for_historical_uptime_existence(
&self,
today_iso_8601: &str,
) -> Result<bool, sqlx::Error> {
sqlx::query!(
"SELECT EXISTS (SELECT 1 FROM mixnode_historical_uptime WHERE date = ?) AS 'exists'",
today_iso_8601
)
.fetch_one(&self.connection_pool)
.await
.map(|result| result.exists == Some(1))
}
/// Creates new entry for mixnode historical uptime
///
/// # Arguments
///
/// * `node_id`: id of the mixnode (as inserted in `mixnode_details_id` table).
/// * `date`: date associated with the uptime represented in ISO 8601, i.e. YYYY-MM-DD.
/// * `uptime`: the actual uptime of the node during the specified day.
pub(crate) async fn insert_mixnode_historical_uptime(
&self,
mix_id: i64,
date: &str,
uptime: u8,
) -> Result<(), sqlx::Error> {
sqlx::query!(
"INSERT INTO mixnode_historical_uptime(mixnode_details_id, date, uptime) VALUES (?, ?, ?)",
mix_id,
date,
uptime,
).execute(&self.connection_pool).await?;
Ok(())
}
/// Creates new entry for gateway historical uptime
///
/// # Arguments
///
/// * `node_id`: id of the gateway (as inserted in `gateway_details_id` table).
/// * `date`: date associated with the uptime represented in ISO 8601, i.e. YYYY-MM-DD.
/// * `uptime`: the actual uptime of the node during the specified day.
pub(crate) async fn insert_gateway_historical_uptime(
&self,
db_id: i64,
date: &str,
uptime: u8,
) -> Result<(), sqlx::Error> {
sqlx::query!(
"INSERT INTO gateway_historical_uptime(gateway_details_id, date, uptime) VALUES (?, ?, ?)",
db_id,
date,
uptime,
).execute(&self.connection_pool).await?;
Ok(())
}
/// Creates a database entry for a finished network monitor test run.
/// Returns id of the newly created entry.
///
/// # Arguments
///
/// * `timestamp`: unix timestamp at which the monitor test run has occurred
pub(crate) async fn insert_monitor_run(&self, timestamp: i64) -> Result<i64, sqlx::Error> {
let res = sqlx::query!("INSERT INTO monitor_run(timestamp) VALUES (?)", timestamp)
.execute(&self.connection_pool)
.await?;
Ok(res.last_insert_rowid())
}
/// Obtains number of network monitor test runs that have occurred within the specified interval.
///
/// # Arguments
///
/// * `since`: unix timestamp indicating the lower bound interval of the selection.
/// * `until`: unix timestamp indicating the upper bound interval of the selection.
pub(crate) async fn get_monitor_runs_count(
&self,
since: i64,
until: i64,
) -> Result<i32, sqlx::Error> {
let count = sqlx::query!(
"SELECT COUNT(*) as count FROM monitor_run WHERE timestamp > ? AND timestamp < ?",
since,
until,
)
.fetch_one(&self.connection_pool)
.await?
.count;
Ok(count)
}
/// Removes all statuses for all mixnodes that are older than the
/// provided timestamp. This method is indirectly called at every reward cycle.
///
/// # Arguments
///
/// * `until`: timestamp specifying the purge cutoff.
pub(crate) async fn purge_old_mixnode_statuses(
&self,
timestamp: i64,
) -> Result<(), sqlx::Error> {
sqlx::query!("DELETE FROM mixnode_status WHERE timestamp < ?", timestamp)
.execute(&self.connection_pool)
.await?;
Ok(())
}
/// Removes all statuses for all gateways that are older than the
/// provided timestamp. This method is indirectly called at every reward cycle.
///
/// # Arguments
///
/// * `until`: timestamp specifying the purge cutoff.
pub(crate) async fn purge_old_gateway_statuses(
&self,
timestamp: i64,
) -> Result<(), sqlx::Error> {
sqlx::query!("DELETE FROM gateway_status WHERE timestamp < ?", timestamp)
.execute(&self.connection_pool)
.await?;
Ok(())
}
/// Returns public key, owner and id of all mixnodes that have had any statuses submitted
/// within the provided time interval.
///
/// # Arguments
///
/// * `since`: indicates the lower bound timestamp for deciding whether given mixnode is active
/// * `until`: indicates the upper bound timestamp for deciding whether given mixnode is active
pub(crate) async fn get_all_active_mixnodes_in_interval(
&self,
since: i64,
until: i64,
) -> Result<Vec<ActiveMixnode>, sqlx::Error> {
// find mixnode details of all nodes that have had at least 1 status information since the provided
// timestamp
// TODO: I dont know if theres a potential issue of if we have a lot of inactive nodes that
// haven't mixed in ages, they might increase the query times?
sqlx::query_as!(
ActiveMixnode,
r#"
SELECT DISTINCT identity_key, mix_id as "mix_id: NodeId", id
FROM mixnode_details
JOIN mixnode_status
ON mixnode_details.id = mixnode_status.mixnode_details_id
WHERE EXISTS (
SELECT 1 FROM mixnode_status WHERE timestamp > ? AND timestamp < ?
)
"#,
since,
until
)
.fetch_all(&self.connection_pool)
.await
}
/// Returns public key, owner and id of all gateways that have had any statuses submitted
/// within the provided time interval.
///
/// # Arguments
///
/// * `since`: indicates the lower bound timestamp for deciding whether given gateway is active
/// * `until`: indicates the upper bound timestamp for deciding whether given gateway is active
pub(crate) async fn get_all_active_gateways_in_interval(
&self,
since: i64,
until: i64,
) -> Result<Vec<ActiveGateway>, sqlx::Error> {
sqlx::query_as(
r#"
SELECT DISTINCT identity, node_id as "node_id: NodeId", id
FROM gateway_details
JOIN gateway_status
ON gateway_details.id = gateway_status.gateway_details_id
WHERE EXISTS (
SELECT 1 FROM gateway_status WHERE timestamp > ? AND timestamp < ?
)
"#,
)
.bind(since)
.bind(until)
.fetch_all(&self.connection_pool)