-
Notifications
You must be signed in to change notification settings - Fork 15
/
datastore.rs
5833 lines (5518 loc) · 223 KB
/
datastore.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
//! Janus datastore (durable storage) implementation.
use self::models::{
AcquiredAggregationJob, AcquiredCollectionJob, AggregateShareJob, AggregationJob,
AggregatorRole, AuthenticationTokenType, BatchAggregation, BatchAggregationState,
BatchAggregationStateCode, CollectionJob, CollectionJobState, CollectionJobStateCode,
HpkeKeyState, HpkeKeypair, LeaderStoredReport, Lease, LeaseToken, OutstandingBatch,
ReportAggregation, ReportAggregationMetadata, ReportAggregationMetadataState,
ReportAggregationState, ReportAggregationStateCode, SqlInterval, TaskAggregationCounter,
TaskUploadCounter,
};
#[cfg(feature = "test-util")]
use crate::VdafHasAggregationParameter;
use crate::{
batch_mode::{AccumulableBatchMode, CollectableBatchMode},
task::{self, AggregatorTask, AggregatorTaskParameters},
taskprov::PeerAggregator,
SecretBytes,
};
use chrono::NaiveDateTime;
use futures::future::try_join_all;
use janus_core::{
auth_tokens::AuthenticationToken,
hpke::{self, HpkePrivateKey},
time::{Clock, TimeExt},
vdaf::VdafInstance,
};
use janus_messages::{
batch_mode::{BatchMode, LeaderSelected, TimeInterval},
AggregationJobId, BatchId, CollectionJobId, Duration, Extension, HpkeCiphertext, HpkeConfig,
HpkeConfigId, Interval, PrepareResp, Query, ReportId, ReportIdChecksum, ReportMetadata,
ReportShare, Role, TaskId, Time,
};
use opentelemetry::{
metrics::{Counter, Histogram, Meter},
KeyValue,
};
use postgres_types::{FromSql, Json, Timestamp, ToSql};
use prio::{
codec::{decode_u16_items, encode_u16_items, CodecError, Decode, Encode, ParameterizedDecode},
topology::ping_pong::PingPongTransition,
vdaf,
};
use rand::random;
use ring::aead::{self, LessSafeKey, AES_128_GCM};
use std::{
collections::HashMap,
convert::TryFrom,
fmt::{Debug, Display},
future::Future,
io::Cursor,
mem::size_of,
ops::RangeInclusive,
pin::Pin,
sync::{
atomic::{AtomicBool, Ordering},
Arc, Mutex,
},
time::{Duration as StdDuration, Instant},
};
use tokio::{sync::Barrier, try_join};
use tokio_postgres::{error::SqlState, row::RowIndex, IsolationLevel, Row, Statement, ToStatement};
use tracing::{error, Level};
use url::Url;
pub mod models;
#[cfg(feature = "test-util")]
#[cfg_attr(docsrs, doc(cfg(feature = "test-util")))]
pub mod test_util;
#[cfg(test)]
mod tests;
/// This macro stamps out an array of schema versions supported by this version of Janus and an
/// [`rstest_reuse`][1] template that can be applied to tests to have them run against all supported
/// schema versions.
///
/// [1]: https://docs.rs/rstest_reuse/latest/rstest_reuse/
macro_rules! supported_schema_versions {
( $i_latest:literal $(,)? $( $i:literal ),* ) => {
const SUPPORTED_SCHEMA_VERSIONS: &[i64] = &[$i_latest, $($i),*];
#[cfg(test)]
#[rstest_reuse::template]
#[rstest::rstest]
// Test the latest supported schema version.
#[case(ephemeral_datastore_schema_version($i_latest))]
// Test the remaining supported schema versions.
$(#[case(ephemeral_datastore_schema_version($i))])*
// Test the remaining supported schema versions by taking a
// database at the latest schema and downgrading it.
$(#[case(ephemeral_datastore_schema_version_by_downgrade($i))])*
async fn schema_versions_template(
#[future(awt)]
#[case]
ephemeral_datastore: EphemeralDatastore,
) {
// This is an rstest template and never gets run.
}
}
}
// List of schema versions that this version of Janus can safely run on. If any other schema
// version is seen, [`Datastore::new`] fails.
//
// Note that the latest supported version must be first in the list.
supported_schema_versions!(1);
/// Datastore represents a datastore for Janus, with support for transactional reads and writes.
/// In practice, Datastore instances are currently backed by a PostgreSQL database.
pub struct Datastore<C: Clock> {
pool: deadpool_postgres::Pool,
crypter: Crypter,
clock: C,
task_infos: Arc<Mutex<HashMap<TaskId, TaskInfo>>>,
transaction_status_counter: Counter<u64>,
transaction_retry_histogram: Histogram<u64>,
rollback_error_counter: Counter<u64>,
transaction_duration_histogram: Histogram<f64>,
transaction_pool_wait_histogram: Histogram<f64>,
max_transaction_retries: u64,
}
impl<C: Clock> Debug for Datastore<C> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Datastore")
}
}
impl<C: Clock> Datastore<C> {
/// `new` creates a new Datastore using the provided connection pool. An error is returned if
/// the current database migration version is not supported by this version of Janus.
pub async fn new(
pool: deadpool_postgres::Pool,
crypter: Crypter,
clock: C,
meter: &Meter,
max_transaction_retries: u64,
) -> Result<Datastore<C>, Error> {
Self::new_with_supported_versions(
pool,
crypter,
clock,
meter,
SUPPORTED_SCHEMA_VERSIONS,
max_transaction_retries,
)
.await
}
async fn new_with_supported_versions(
pool: deadpool_postgres::Pool,
crypter: Crypter,
clock: C,
meter: &Meter,
supported_schema_versions: &[i64],
max_transaction_retries: u64,
) -> Result<Datastore<C>, Error> {
let datastore = Self::new_without_supported_versions(
pool,
crypter,
clock,
meter,
max_transaction_retries,
)
.await;
let (current_version, migration_description) = datastore
.run_tx("check schema version", |tx| {
Box::pin(async move { tx.get_current_schema_migration_version().await })
})
.await?;
if !supported_schema_versions.contains(¤t_version) {
return Err(Error::DbState(format!(
"unsupported schema version {current_version} / {migration_description}"
)));
}
Ok(datastore)
}
/// Creates a new datastore using the provided connection pool.
pub async fn new_without_supported_versions(
pool: deadpool_postgres::Pool,
crypter: Crypter,
clock: C,
meter: &Meter,
max_transaction_retries: u64,
) -> Datastore<C> {
let transaction_status_counter = meter
.u64_counter(TRANSACTION_METER_NAME)
.with_description("Count of database transactions run, with their status.")
.with_unit("{transaction}")
.init();
let rollback_error_counter = meter
.u64_counter(TRANSACTION_ROLLBACK_METER_NAME)
.with_description(concat!(
"Count of errors received when rolling back a database transaction, ",
"with their PostgreSQL error code.",
))
.with_unit("{error}")
.init();
let transaction_retry_histogram = meter
.u64_histogram(TRANSACTION_RETRIES_METER_NAME)
.with_description("The number of retries before a transaction is committed or aborted.")
.with_unit("{retry}")
.init();
let transaction_duration_histogram = meter
.f64_histogram(TRANSACTION_DURATION_METER_NAME)
.with_description(concat!(
"Duration of database transactions. This counts only the time spent between the ",
"BEGIN and COMMIT/ROLLBACK statements."
))
.with_unit("s")
.init();
let transaction_pool_wait_histogram = meter
.f64_histogram(TRANSACTION_POOL_WAIT_METER_NAME)
.with_description(concat!(
"Time spent waiting for a transaction to BEGIN, because it is waiting for a ",
"slot to become available in the connection pooler."
))
.with_unit("s")
.init();
Self {
pool,
crypter,
clock,
task_infos: Default::default(),
transaction_status_counter,
transaction_retry_histogram,
rollback_error_counter,
transaction_duration_histogram,
transaction_pool_wait_histogram,
max_transaction_retries,
}
}
/// run_tx runs a transaction, whose body is determined by the given function. The transaction
/// is committed if the body returns a successful value, and rolled back if the body returns an
/// error value.
///
/// The datastore will automatically retry some failures (e.g. serialization failures) by
/// rolling back & retrying with a new transaction, so the given function should support being
/// called multiple times. Values read from the transaction should not be considered as
/// "finalized" until the transaction is committed, i.e. after `run_tx` is run to completion.
///
/// This method requires a transaction name for use in database metrics.
#[tracing::instrument(level = "trace", skip(self, f))]
pub async fn run_tx<F, T>(&self, name: &'static str, f: F) -> Result<T, Error>
where
for<'a> F:
Fn(&'a Transaction<C>) -> Pin<Box<dyn Future<Output = Result<T, Error>> + Send + 'a>>,
{
let mut retry_count = 0;
loop {
let (mut rslt, retry) = self.run_tx_once(name, &f).await;
let retries_exceeded = retry_count + 1 > self.max_transaction_retries;
let status = match (rslt.as_ref(), retry) {
(_, true) => {
if retries_exceeded {
"error_too_many_retries"
} else {
"retry"
}
}
(Ok(_), _) | (Err(Error::User(_)), _) => "success",
(Err(Error::Db(_)), _) | (Err(Error::Pool(_)), _) => "error_db",
(Err(_), _) => "error_other",
};
self.transaction_status_counter.add(
1,
&[KeyValue::new("status", status), KeyValue::new("tx", name)],
);
if retry {
if retries_exceeded {
let err = rslt.err();
error!(
retry_count,
last_err = ?err,
"too many retries, aborting transaction"
);
rslt = Err(Error::TooManyRetries {
source: err.map(Box::new),
});
} else {
retry_count += 1;
continue;
}
}
self.transaction_retry_histogram
.record(retry_count, &[KeyValue::new("tx", name)]);
return rslt;
}
}
#[tracing::instrument(level = "trace", skip(self, f))]
async fn run_tx_once<F, T>(&self, name: &'static str, f: &F) -> (Result<T, Error>, bool)
where
for<'a> F:
Fn(&'a Transaction<C>) -> Pin<Box<dyn Future<Output = Result<T, Error>> + Send + 'a>>,
{
// Acquire connection from the connection pooler.
let before = Instant::now();
let result = self.pool.get().await;
let elapsed = before.elapsed();
// We don't record the transaction name for this metric, since it's not particularly
// interesting. All transactions should get FIFO access to connections.
self.transaction_pool_wait_histogram.record(
elapsed.as_secs_f64(),
&[KeyValue::new(
"status",
if result.is_err() { "error" } else { "success" },
)],
);
let mut client = match result {
Ok(client) => client,
Err(err) => return (Err(err.into()), false),
};
// Open transaction.
let before = Instant::now();
let raw_tx = match client
.build_transaction()
.isolation_level(IsolationLevel::RepeatableRead)
.start()
.await
{
Ok(raw_tx) => raw_tx,
Err(err) => return (Err(err.into()), false),
};
let tx = Transaction {
raw_tx,
crypter: &self.crypter,
clock: &self.clock,
name,
task_infos: Arc::clone(&self.task_infos),
retry: AtomicBool::new(false),
op_group: Mutex::new(Arc::new(Mutex::new(OperationGroup::Running(0)))),
};
// Run user-provided function with the transaction, then commit/rollback based on result.
let rslt = f(&tx).await;
let (raw_tx, retry) = (tx.raw_tx, tx.retry);
let rslt = match (rslt, retry.load(Ordering::Relaxed)) {
// Commit.
(Ok(val), false) => match check_error(&retry, raw_tx.commit().await) {
Ok(()) => Ok(val),
Err(err) => Err(err.into()),
},
// Rollback.
(rslt, _) => {
if let Err(rollback_err) = check_error(&retry, raw_tx.rollback().await) {
error!("Couldn't roll back transaction: {rollback_err}");
self.rollback_error_counter.add(
1,
&[KeyValue::new(
"code",
rollback_err
.code()
.map(SqlState::code)
.unwrap_or("N/A")
.to_string(),
)],
);
};
// We return `rslt` unconditionally here: it will either be an error, or we have the
// retry flag set so that even if `rslt` is a success we will be retrying the entire
// transaction & the result of this attempt doesn't matter.
rslt
}
};
let elapsed = before.elapsed();
self.transaction_duration_histogram
.record(elapsed.as_secs_f64(), &[KeyValue::new("tx", name)]);
(rslt, retry.load(Ordering::Relaxed))
}
/// See [`Datastore::run_tx`]. This method provides a placeholder transaction name. It is useful
/// for tests where the transaction name is not important.
#[cfg(feature = "test-util")]
#[cfg_attr(docsrs, doc(cfg(feature = "test-util")))]
#[tracing::instrument(level = "trace", skip(self, f))]
pub fn run_unnamed_tx<'s, F, T>(&'s self, f: F) -> impl Future<Output = Result<T, Error>> + 's
where
F: 's,
T: 's,
for<'a> F:
Fn(&'a Transaction<C>) -> Pin<Box<dyn Future<Output = Result<T, Error>> + Send + 'a>>,
{
self.run_tx("default", f)
}
/// Write a task into the datastore.
#[cfg(feature = "test-util")]
#[cfg_attr(docsrs, doc(cfg(feature = "test-util")))]
pub async fn put_aggregator_task(&self, task: &AggregatorTask) -> Result<(), Error> {
self.run_tx("test-put-task", |tx| {
let task = task.clone();
Box::pin(async move { tx.put_aggregator_task(&task).await })
})
.await
}
/// Write an arbitrary HPKE key to the datastore and place it in the [`HpkeKeyState::Active`]
/// state.
#[cfg(feature = "test-util")]
#[cfg_attr(docsrs, doc(cfg(feature = "test-util")))]
pub async fn put_hpke_key(&self) -> Result<hpke::HpkeKeypair, Error> {
let keypair = hpke::HpkeKeypair::test();
self.run_tx("test-put-hpke-key", |tx| {
let keypair = keypair.clone();
Box::pin(async move {
tx.put_hpke_keypair(&keypair).await?;
tx.set_hpke_keypair_state(keypair.config().id(), &HpkeKeyState::Active)
.await
})
})
.await?;
Ok(keypair)
}
}
fn check_error<T>(
retry: &AtomicBool,
rslt: Result<T, tokio_postgres::Error>,
) -> Result<T, tokio_postgres::Error> {
if let Err(err) = &rslt {
if is_retryable_error(err) {
retry.store(true, Ordering::Relaxed);
}
}
rslt
}
fn is_retryable_error(err: &tokio_postgres::Error) -> bool {
err.code().map_or(false, |code| {
code == &SqlState::T_R_SERIALIZATION_FAILURE || code == &SqlState::T_R_DEADLOCK_DETECTED
})
}
fn is_transaction_abort_error(err: &tokio_postgres::Error) -> bool {
err.code()
.map_or(false, |code| code == &SqlState::IN_FAILED_SQL_TRANSACTION)
}
pub const TRANSACTION_METER_NAME: &str = "janus_database_transactions";
pub const TRANSACTION_ROLLBACK_METER_NAME: &str = "janus_database_rollback_errors";
pub const TRANSACTION_RETRIES_METER_NAME: &str = "janus_database_transaction_retries";
pub const TRANSACTION_DURATION_METER_NAME: &str = "janus_database_transaction_duration";
pub const TRANSACTION_POOL_WAIT_METER_NAME: &str = "janus_database_pool_wait_duration";
/// Transaction represents an ongoing datastore transaction.
pub struct Transaction<'a, C: Clock> {
raw_tx: deadpool_postgres::Transaction<'a>,
crypter: &'a Crypter,
clock: &'a C,
name: &'a str,
task_infos: Arc<Mutex<HashMap<TaskId, TaskInfo>>>,
retry: AtomicBool,
op_group: Mutex<Arc<Mutex<OperationGroup>>>, // locking discipline: outer lock before inner lock
}
enum OperationGroup {
Running(usize), // current operation count
Draining(Arc<Barrier>), // barrier to wait upon to complete drain
}
impl<C: Clock> Transaction<'_, C> {
// For some error modes, Postgres will return an error to the caller & then fail all future
// statements within the same transaction with an "in failed SQL transaction" error. This
// effectively means one statement will receive a "root cause" error and then all later
// statements will receive an "in failed SQL transaction" error. In a pipelined scenario, if our
// code is processing the results of these statements concurrently--e.g. because they are part
// of a `try_join!`/`try_join_all` group--we might receive & handle one of the "in failed SQL
// transaction" errors before we handle the "root cause" error, which might cause the "root
// cause" error's future to be cancelled before we evaluate it. If the "root cause" error would
// trigger a retry, this would mean we would skip a DB-based retry when one was warranted.
//
// To fix this problem, we (internally) wrap all direct DB operations in `run_op`. This function
// groups concurrent database operations into "operation groups", which allow us to wait for all
// operations in the group to complete (this waiting operation is called "draining"). If we ever
// observe an "in failed SQL transaction" error, we drain the operation group before returning.
// Under the assumption that the "root cause" error is concurrent with the "in failed SQL
// transactions" errors, this guarantees we will evaluate the "root cause" error for retry
// before any errors make their way out of the transaction code.
async fn run_op<T>(
&self,
op: impl Future<Output = Result<T, tokio_postgres::Error>>,
) -> Result<T, tokio_postgres::Error> {
// Enter.
//
// Before we can run the operation, we need to join this operation into an operation group.
// Retrieve the current operation group & join it.
let op_group = {
let mut tx_op_group = self.op_group.lock().unwrap();
let new_tx_op_group = {
let mut op_group = tx_op_group.lock().unwrap();
match &*op_group {
OperationGroup::Running(op_count) => {
// If the current op group is running, join it by incrementing the operation
// count.
*op_group = OperationGroup::Running(*op_count + 1);
None
}
OperationGroup::Draining { .. } => {
// If the current op group is draining, we can't join it; instead, create a
// new op group to join, and store it as the transaction's current operation
// group.
Some(Arc::new(Mutex::new(OperationGroup::Running(1))))
}
}
};
if let Some(new_tx_op_group) = new_tx_op_group {
*tx_op_group = new_tx_op_group;
}
Arc::clone(&tx_op_group)
};
// Run operation, and check if error triggers a retry or requires a drain.
let rslt = check_error(&self.retry, op.await);
let needs_drain = rslt
.as_ref()
.err()
.map_or(false, is_transaction_abort_error);
// Exit.
//
// Before we are done running the operation, we have to leave the operation group. If the
// operation group is running, we just need to decrement the count. If the operation group
// is draining (because this or another operation encountered an error which requires a
// drain), we have to wait until all operations in the group are ready to finish.
let barrier = {
let mut op_group = op_group.lock().unwrap();
match &*op_group {
OperationGroup::Running(op_count) => {
if needs_drain {
// If the operation group is running & we have determined we need to drain
// the operation group, change the operation group to Draining & wait on the
// barrier.
let barrier = Arc::new(Barrier::new(*op_count));
*op_group = OperationGroup::Draining(Arc::clone(&barrier));
Some(barrier)
} else {
// If the operation group is running & we don't need a drain, just decrement
// the operation count.
*op_group = OperationGroup::Running(op_count - 1);
None
}
}
// If the operation group is already draining, wait on the barrier.
OperationGroup::Draining(barrier) => Some(Arc::clone(barrier)),
}
};
if let Some(barrier) = barrier {
barrier.wait().await;
}
rslt
}
async fn execute<T>(
&self,
statement: &T,
params: &[&(dyn ToSql + Sync)],
) -> Result<u64, tokio_postgres::Error>
where
T: ?Sized + ToStatement,
{
self.run_op(self.raw_tx.execute(statement, params)).await
}
async fn prepare_cached(&self, query: &str) -> Result<Statement, tokio_postgres::Error> {
self.run_op(self.raw_tx.prepare_cached(query)).await
}
async fn query<T>(
&self,
statement: &T,
params: &[&(dyn ToSql + Sync)],
) -> Result<Vec<Row>, tokio_postgres::Error>
where
T: ?Sized + ToStatement,
{
self.run_op(self.raw_tx.query(statement, params)).await
}
async fn query_one<T>(
&self,
statement: &T,
params: &[&(dyn ToSql + Sync)],
) -> Result<Row, tokio_postgres::Error>
where
T: ?Sized + ToStatement,
{
self.run_op(self.raw_tx.query_one(statement, params)).await
}
async fn query_opt<T>(
&self,
statement: &T,
params: &[&(dyn ToSql + Sync)],
) -> Result<Option<Row>, tokio_postgres::Error>
where
T: ?Sized + ToStatement,
{
self.run_op(self.raw_tx.query_opt(statement, params)).await
}
/// Returns the current schema version of the datastore and the description of the migration
/// script that applied it.
async fn get_current_schema_migration_version(&self) -> Result<(i64, String), Error> {
let stmt = self
.prepare_cached(
"-- get_current_schema_migration_version()
SELECT version, description FROM _sqlx_migrations
WHERE success = TRUE ORDER BY version DESC LIMIT(1)",
)
.await?;
let row = self.query_one(&stmt, &[]).await?;
let version = row.get("version");
let description = row.get("description");
Ok((version, description))
}
/// Returns the clock used by this transaction.
pub fn clock(&self) -> &C {
self.clock
}
/// Writes a task into the datastore.
#[tracing::instrument(skip(self, task), fields(task_id = ?task.id()), err)]
pub async fn put_aggregator_task(&self, task: &AggregatorTask) -> Result<(), Error> {
let now = self.clock.now().as_naive_date_time()?;
// Main task insert.
let stmt = self
.prepare_cached(
"-- put_aggregator_task()
INSERT INTO tasks (
task_id, aggregator_role, peer_aggregator_endpoint, batch_mode, vdaf,
task_expiration, report_expiry_age, min_batch_size, time_precision,
tolerable_clock_skew, collector_hpke_config, vdaf_verify_key,
taskprov_task_info, aggregator_auth_token_type, aggregator_auth_token,
aggregator_auth_token_hash, collector_auth_token_type,
collector_auth_token_hash, created_at, updated_at, updated_by)
VALUES (
$1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18,
$19, $20, $21
)
ON CONFLICT DO NOTHING",
)
.await?;
check_insert(
self.execute(
&stmt,
&[
/* task_id */ &task.id().as_ref(),
/* aggregator_role */ &AggregatorRole::from_role(*task.role())?,
/* peer_aggregator_endpoint */
&task.peer_aggregator_endpoint().as_str(),
/* batch_mode */ &Json(task.batch_mode()),
/* vdaf */ &Json(task.vdaf()),
/* task_expiration */
&task
.task_expiration()
.map(Time::as_naive_date_time)
.transpose()?,
/* report_expiry_age */
&task
.report_expiry_age()
.map(Duration::as_seconds)
.map(i64::try_from)
.transpose()?,
/* min_batch_size */ &i64::try_from(task.min_batch_size())?,
/* time_precision */
&i64::try_from(task.time_precision().as_seconds())?,
/* tolerable_clock_skew */
&i64::try_from(task.tolerable_clock_skew().as_seconds())?,
/* collector_hpke_config */
&task
.collector_hpke_config()
.map(|cfg| cfg.get_encoded())
.transpose()?,
/* vdaf_verify_key */
&self.crypter.encrypt(
"tasks",
task.id().as_ref(),
"vdaf_verify_key",
task.opaque_vdaf_verify_key().as_ref(),
)?,
/* taskprov_task_info */
&task.taskprov_task_info(),
/* aggregator_auth_token_type */
&task
.aggregator_auth_token()
.map(AuthenticationTokenType::from)
.or_else(|| {
task.aggregator_auth_token_hash()
.map(AuthenticationTokenType::from)
}),
/* aggregator_auth_token */
&task
.aggregator_auth_token()
.map(|token| {
self.crypter.encrypt(
"tasks",
task.id().as_ref(),
"aggregator_auth_token",
token.as_ref(),
)
})
.transpose()?,
/* aggregator_auth_token_hash */
&task
.aggregator_auth_token_hash()
.map(|token_hash| token_hash.as_ref()),
/* collector_auth_token_type */
&task
.collector_auth_token_hash()
.map(AuthenticationTokenType::from),
/* collector_auth_token */
&task
.collector_auth_token_hash()
.map(|token_hash| token_hash.as_ref()),
/* created_at */ &now,
/* updated_at */ &now,
/* updated_by */ &self.name,
],
)
.await?,
)?;
Ok(())
}
/// Deletes a task from the datastore, along with all related data (client reports,
/// aggregations, etc).
#[tracing::instrument(skip(self), err(level = Level::DEBUG))]
pub async fn delete_task(&self, task_id: &TaskId) -> Result<(), Error> {
// Deletion of other data implemented via ON DELETE CASCADE.
let stmt = self
.prepare_cached(
"-- delete_task()
DELETE FROM tasks WHERE task_id = $1",
)
.await?;
check_single_row_mutation(
self.execute(&stmt, &[/* task_id */ &task_id.as_ref()])
.await?,
)?;
Ok(())
}
/// Sets or unsets the expiration date of a task.
#[tracing::instrument(skip(self), err(level = Level::DEBUG))]
pub async fn update_task_expiration(
&self,
task_id: &TaskId,
task_expiration: Option<&Time>,
) -> Result<(), Error> {
let stmt = self
.prepare_cached(
"-- update_task_expiration()
UPDATE tasks SET task_expiration = $1, updated_at = $2, updated_by = $3
WHERE task_id = $4",
)
.await?;
check_single_row_mutation(
self.execute(
&stmt,
&[
/* task_expiration */
&task_expiration.map(Time::as_naive_date_time).transpose()?,
/* updated_at */ &self.clock.now().as_naive_date_time()?,
/* updated_by */ &self.name,
/* task_id */ &task_id.as_ref(),
],
)
.await?,
)
}
/// Fetch the task parameters corresponing to the provided `task_id`.
#[tracing::instrument(skip(self), err(level = Level::DEBUG))]
pub async fn get_aggregator_task(
&self,
task_id: &TaskId,
) -> Result<Option<AggregatorTask>, Error> {
let params: &[&(dyn ToSql + Sync)] = &[&task_id.as_ref()];
let stmt = self
.prepare_cached(
"-- get_aggregator_task()
SELECT aggregator_role, peer_aggregator_endpoint, batch_mode, vdaf,
task_expiration, report_expiry_age, min_batch_size, time_precision,
tolerable_clock_skew, collector_hpke_config, vdaf_verify_key,
taskprov_task_info, aggregator_auth_token_type, aggregator_auth_token,
aggregator_auth_token_hash, collector_auth_token_type, collector_auth_token_hash
FROM tasks WHERE task_id = $1",
)
.await?;
let task_row = self.query_opt(&stmt, params).await?;
task_row
.map(|task_row| self.task_from_row(task_id, &task_row))
.transpose()
}
/// Fetch all the tasks in the database.
#[tracing::instrument(skip(self), err(level = Level::DEBUG))]
pub async fn get_aggregator_tasks(&self) -> Result<Vec<AggregatorTask>, Error> {
let stmt = self
.prepare_cached(
"-- get_aggregator_tasks()
SELECT task_id, aggregator_role, peer_aggregator_endpoint, batch_mode, vdaf,
task_expiration, report_expiry_age, min_batch_size, time_precision,
tolerable_clock_skew, collector_hpke_config, vdaf_verify_key,
taskprov_task_info, aggregator_auth_token_type, aggregator_auth_token,
aggregator_auth_token_hash, collector_auth_token_type, collector_auth_token_hash
FROM tasks",
)
.await?;
let task_rows = self.query(&stmt, &[]).await?;
task_rows
.into_iter()
.map(|row| self.task_from_row(&TaskId::get_decoded(row.get("task_id"))?, &row))
.collect::<Result<_, _>>()
}
/// Construct an [`AggregatorTask`] from the contents of the provided (tasks) `Row`.
fn task_from_row(&self, task_id: &TaskId, row: &Row) -> Result<AggregatorTask, Error> {
// Scalar task parameters.
let aggregator_role: AggregatorRole = row.get("aggregator_role");
let peer_aggregator_endpoint = row.get::<_, String>("peer_aggregator_endpoint").parse()?;
let batch_mode = row.try_get::<_, Json<task::BatchMode>>("batch_mode")?.0;
let vdaf = row.try_get::<_, Json<VdafInstance>>("vdaf")?.0;
let task_expiration = row
.get::<_, Option<NaiveDateTime>>("task_expiration")
.as_ref()
.map(Time::from_naive_date_time);
let report_expiry_age = row
.get_nullable_bigint_and_convert("report_expiry_age")?
.map(Duration::from_seconds);
let min_batch_size = row.get_bigint_and_convert("min_batch_size")?;
let time_precision = Duration::from_seconds(row.get_bigint_and_convert("time_precision")?);
let tolerable_clock_skew =
Duration::from_seconds(row.get_bigint_and_convert("tolerable_clock_skew")?);
let collector_hpke_config = row
.get::<_, Option<Vec<u8>>>("collector_hpke_config")
.map(|config| HpkeConfig::get_decoded(&config))
.transpose()?;
let encrypted_vdaf_verify_key: Vec<u8> = row.get::<_, Vec<u8>>("vdaf_verify_key");
let vdaf_verify_key = self
.crypter
.decrypt(
"tasks",
task_id.as_ref(),
"vdaf_verify_key",
&encrypted_vdaf_verify_key,
)
.map(SecretBytes::new)?;
let taskprov_task_info: Option<Vec<u8>> = row.get("taskprov_task_info");
let aggregator_auth_token_type: Option<AuthenticationTokenType> =
row.get("aggregator_auth_token_type");
let aggregator_auth_token = row
.get::<_, Option<Vec<u8>>>("aggregator_auth_token")
.zip(aggregator_auth_token_type)
.map(|(encrypted_token, token_type)| {
token_type.as_authentication(&self.crypter.decrypt(
"tasks",
task_id.as_ref(),
"aggregator_auth_token",
&encrypted_token,
)?)
})
.transpose()?;
let aggregator_auth_token_hash = row
.get::<_, Option<Vec<u8>>>("aggregator_auth_token_hash")
.zip(aggregator_auth_token_type)
.map(|(token_hash, token_type)| token_type.as_authentication_token_hash(&token_hash))
.transpose()?;
let collector_auth_token_hash = row
.get::<_, Option<Vec<u8>>>("collector_auth_token_hash")
.zip(row.get::<_, Option<AuthenticationTokenType>>("collector_auth_token_type"))
.map(|(token_hash, token_type)| token_type.as_authentication_token_hash(&token_hash))
.transpose()?;
let aggregator_parameters = match (
aggregator_role,
aggregator_auth_token,
aggregator_auth_token_hash,
collector_auth_token_hash,
collector_hpke_config,
) {
(
AggregatorRole::Leader,
Some(aggregator_auth_token),
None,
Some(collector_auth_token_hash),
Some(collector_hpke_config),
) => AggregatorTaskParameters::Leader {
aggregator_auth_token,
collector_auth_token_hash,
collector_hpke_config,
},
(
AggregatorRole::Helper,
None,
Some(aggregator_auth_token_hash),
None,
Some(collector_hpke_config),
) => AggregatorTaskParameters::Helper {
aggregator_auth_token_hash,
collector_hpke_config,
},
(AggregatorRole::Helper, None, None, None, None) => {
AggregatorTaskParameters::TaskprovHelper
}
values => {
return Err(Error::DbState(format!(
"found task row with unexpected combination of values {values:?}",
)));
}
};
let mut task = AggregatorTask::new(
*task_id,
peer_aggregator_endpoint,
batch_mode,
vdaf,
vdaf_verify_key,
task_expiration,
report_expiry_age,
min_batch_size,
time_precision,
tolerable_clock_skew,
aggregator_parameters,
)?;
if let Some(taskprov_task_info) = taskprov_task_info {
task = task.with_taskprov_task_info(taskprov_task_info);
}
Ok(task)
}
/// Retrieves task IDs, optionally after some specified lower bound. This method returns tasks
/// IDs in lexicographic order, but may not retrieve the IDs of all tasks in a single call. To
/// retrieve additional task IDs, make additional calls to this method while specifying the
/// `lower_bound` parameter to be the last task ID retrieved from the previous call.
#[tracing::instrument(skip(self), err(level = Level::DEBUG))]
pub async fn get_task_ids(&self, lower_bound: Option<TaskId>) -> Result<Vec<TaskId>, Error> {
let lower_bound = lower_bound.map(|task_id| task_id.as_ref().to_vec());
let stmt = self
.prepare_cached(
"-- get_task_ids()
SELECT task_id FROM tasks
WHERE task_id > $1 OR $1 IS NULL
ORDER BY task_id
LIMIT 5000",
)
.await?;
self.query(&stmt, &[/* task_id */ &lower_bound])
.await?
.into_iter()
.map(|row| Ok(TaskId::get_decoded(row.get("task_id"))?))
.collect()
}
/// get_client_report retrieves a client report by ID.
#[tracing::instrument(skip(self), err(level = Level::DEBUG))]
pub async fn get_client_report<const SEED_SIZE: usize, A>(
&self,
vdaf: &A,
task_id: &TaskId,
report_id: &ReportId,
) -> Result<Option<LeaderStoredReport<SEED_SIZE, A>>, Error>
where
A: vdaf::Aggregator<SEED_SIZE, 16>,
A::InputShare: PartialEq,
A::PublicShare: PartialEq,
{
let task_info = match self.task_info_for(task_id).await? {
Some(task_info) => task_info,
None => return Ok(None),
};
let stmt = self
.prepare_cached(