/
util.rs
1634 lines (1442 loc) · 59.2 KB
/
util.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
//! Agent utility functions that don't have an obvious place in
//! another module
//!
//! Any set of functions that can create a coherent module (i.e. have
//! a similar API facade, handle the same kinds of data, etc) should
//! be pulled out of this file in future.
use std::{
cmp,
collections::{BTreeMap, BTreeSet, HashMap, HashSet},
convert::Infallible,
net::SocketAddr,
ops::RangeInclusive,
sync::{atomic::AtomicI64, Arc},
time::{Duration, Instant},
};
use crate::{
agent::{
handlers, CountedExecutor, CHECK_EMPTIES_TO_INSERT_AFTER, MAX_SYNC_BACKOFF, TO_CLEAR_COUNT,
},
api::public::{
api_v1_db_schema, api_v1_queries, api_v1_table_stats, api_v1_transactions,
pubsub::{api_v1_sub_by_id, api_v1_subs},
},
transport::Transport,
};
use corro_types::{
actor::{Actor, ActorId},
agent::{
Agent, Bookie, ChangeError, CurrentVersion, KnownDbVersion, PartialVersion, SplitPool,
},
base::{CrsqlDbVersion, CrsqlSeq, Version},
broadcast::{ChangeSource, ChangeV1, Changeset, ChangesetParts, FocaCmd, FocaInput},
channel::CorroReceiver,
config::AuthzConfig,
pubsub::SubsManager,
};
use axum::{
error_handling::HandleErrorLayer,
extract::DefaultBodyLimit,
headers::{authorization::Bearer, Authorization},
routing::{get, post},
BoxError, Extension, Router, TypedHeader,
};
use foca::Member;
use futures::{FutureExt, TryFutureExt};
use hyper::{server::conn::AddrIncoming, StatusCode};
use itertools::Itertools;
use metrics::{counter, histogram};
use rangemap::{RangeInclusiveMap, RangeInclusiveSet};
use rusqlite::{
named_params, params, params_from_iter, Connection, OptionalExtension, ToSql, Transaction,
};
use spawn::spawn_counted;
use tokio::{
net::TcpListener,
sync::mpsc::Sender,
task::block_in_place,
time::{sleep, timeout},
};
use tower::{limit::ConcurrencyLimitLayer, load_shed::LoadShedLayer};
use tower_http::trace::TraceLayer;
use tracing::{debug, error, info, trace, warn};
use tripwire::{PreemptibleFutureExt, Tripwire};
use super::BcastCache;
pub async fn initialise_foca(agent: &Agent) {
let states = load_member_states(agent).await;
if !states.is_empty() {
let mut foca_states = BTreeMap::<SocketAddr, Member<Actor>>::new();
{
// block to drop the members write lock
let mut members = agent.members().write();
for (address, foca_state) in states {
members.by_addr.insert(address, foca_state.id().id());
if matches!(foca_state.state(), foca::State::Suspect) {
continue;
}
// Add to the foca_states if the member doesn't yet
// exist in the map, or if we are replacing an older
// timestamp
match foca_states.get(&address) {
Some(state) if state.id().ts() < foca_state.id().ts() => {
foca_states.insert(address, foca_state);
}
None => {
foca_states.insert(address, foca_state);
}
_ => {}
}
}
}
if let Err(e) = agent
.tx_foca()
.send(FocaInput::ApplyMany(
foca_states.into_iter().map(|(_, v)| v).collect(),
))
.await
{
error!("Failed to queue initial foca state: {e:?}, cluster membership states will be broken!");
}
let agent = agent.clone();
tokio::task::spawn(async move {
// Add some random scatter to the task sleep so that
// restarted nodes don't all rejoin at once
let scatter = rand::random::<u64>() % 15;
tokio::time::sleep(Duration::from_secs(25 + scatter)).await;
async fn apply_rejoin(agent: &Agent) -> eyre::Result<()> {
let (cb_tx, cb_rx) = tokio::sync::oneshot::channel();
agent
.tx_foca()
.send(FocaInput::Cmd(FocaCmd::Rejoin(cb_tx)))
.await?;
cb_rx.await??;
Ok(())
}
if let Err(e) = apply_rejoin(&agent).await {
error!("failed to execute cluster rejoin: {e:?}");
}
});
} else {
warn!("No existing cluster member state to load! This seems sus");
}
}
pub async fn clear_overwritten_versions_loop(agent: Agent, bookie: Bookie, sleep_in_secs: u64) {
let pool = agent.pool();
let sleep_duration = Duration::from_secs(sleep_in_secs);
loop {
sleep(sleep_duration).await;
info!("Starting compaction...");
if clear_overwritten_versions(&agent, &bookie, pool, None)
.await
.is_err()
{
continue;
}
}
}
/// Prune the database
pub async fn clear_overwritten_versions(
agent: &Agent,
bookie: &Bookie,
pool: &SplitPool,
feedback: Option<Sender<String>>,
) -> Result<(), String> {
let start = Instant::now();
let bookie_clone = {
bookie
.read("gather_booked_for_compaction")
.await
.iter()
.map(|(actor_id, booked)| (*actor_id, booked.clone()))
.collect::<HashMap<ActorId, _>>()
};
let mut inserted = 0;
let mut deleted = 0;
let mut db_elapsed = Duration::new(0, 0);
if let Some(ref tx) = feedback {
tx.send(format!(
"Compacting changes for {} actors",
bookie_clone.len()
))
.await
.map_err(|e| format!("{e}"))?;
}
for (actor_id, booked) in bookie_clone {
if let Some(ref tx) = feedback {
tx.send(format!("Starting change compaction for {actor_id}"))
.await
.map_err(|e| format!("{e}"))?;
}
// pull the current db version -> version map at the present time
// these are only updated _after_ a transaction has been committed, via a write lock
// so it should be representative of the current state.
let mut versions = {
match timeout(
Duration::from_secs(1),
booked.read(format!(
"clear_overwritten_versions:{}",
actor_id.as_simple()
)),
)
.await
{
Ok(booked) => booked.current_versions(),
Err(_) => {
info!(%actor_id, "timed out acquiring read lock on bookkeeping, skipping for now");
if let Some(ref tx) = feedback {
tx.send("timed out acquiring read lock on bookkeeping".into())
.await
.map_err(|e| format!("{e}"))?;
}
return Err("Timed out acquiring read lock on bookkeeping".into());
}
}
};
if versions.is_empty() {
if let Some(ref tx) = feedback {
tx.send("No versions to compact".into())
.await
.map_err(|e| format!("{e}"))?;
}
continue;
}
// we're using a read connection here, starting a read-only transaction
// this should be representative of the state of current versions from the actor
let cleared_versions = match pool.read().await {
Ok(mut conn) => {
let start = Instant::now();
let res = block_in_place(|| {
let tx = conn.transaction()?;
find_cleared_db_versions(&tx, &actor_id)
});
db_elapsed += start.elapsed();
match res {
Ok(cleared) => {
debug!(
actor_id = %actor_id,
"Aggregated {} DB versions to clear in {:?}",
cleared.len(),
start.elapsed()
);
if let Some(ref tx) = feedback {
tx.send(format!("Aggregated {} DB versions to clear", cleared.len()))
.await
.map_err(|e| format!("{e}"))?;
}
cleared
}
Err(e) => {
error!("could not get cleared versions: {e}");
if let Some(ref tx) = feedback {
tx.send(format!("failed to get cleared versions: {e}"))
.await
.map_err(|e| format!("{e}"))?;
}
return Err("failed to cleared versions".into());
}
}
}
Err(e) => {
error!("could not get read connection: {e}");
if let Some(ref tx) = feedback {
tx.send(format!("failed to get read connection: {e}"))
.await
.map_err(|e| format!("{e}"))?;
}
return Err("could not get read connection".into());
}
};
if !cleared_versions.is_empty() {
let mut to_clear = Vec::new();
for db_v in cleared_versions {
if let Some(v) = versions.remove(&db_v) {
to_clear.push((db_v, v))
}
}
if !to_clear.is_empty() {
// use a write lock here so we can mutate the bookkept state
let mut bookedw = booked
.write(format!("clearing:{}", actor_id.as_simple()))
.await;
for (_db_v, v) in to_clear.iter() {
// only remove when confirming that version is still considered "current"
if bookedw.contains_current(v) {
// set it as cleared right away
bookedw.insert(*v, KnownDbVersion::Cleared);
deleted += 1;
}
}
// find any affected cleared ranges
for range in to_clear
.iter()
.filter_map(|(_, v)| bookedw.cleared.get(v))
.dedup()
{
// schedule for clearing in the background task
if let Err(e) = agent.tx_empty().send((actor_id, range.clone())).await {
error!("could not schedule version to be cleared: {e}");
if let Some(ref tx) = feedback {
tx.send(format!("failed to get queue compaction set: {e}"))
.await
.map_err(|e| format!("{e}"))?;
}
} else {
inserted += 1;
}
tokio::task::yield_now().await;
}
if let Some(ref tx) = feedback {
tx.send(format!("Queued {inserted} empty versions to compact"))
.await
.map_err(|e| format!("{e}"))?;
}
}
}
if let Some(ref tx) = feedback {
tx.send(format!("Finshed compacting changes for {actor_id}"))
.await
.map_err(|e| format!("{e}"))?;
}
tokio::time::sleep(Duration::from_secs(1)).await;
}
info!(
"Compaction done, cleared {} DB bookkeeping table rows (wall time: {:?}, db time: {db_elapsed:?})",
deleted - inserted,
start.elapsed()
);
Ok(())
}
/// Load the existing known member state and addresses
pub async fn load_member_states(agent: &Agent) -> Vec<(SocketAddr, Member<Actor>)> {
match agent.pool().read().await {
Ok(conn) => block_in_place(|| {
match conn.prepare("SELECT address,foca_state FROM __corro_members") {
Ok(mut prepped) => {
match prepped
.query_map([], |row| Ok((
row.get::<_, String>(0)?.parse().map_err(|e| rusqlite::Error::FromSqlConversionFailure(0, rusqlite::types::Type::Text, Box::new(e)))?,
row.get::<_, String>(1)?
))
)
.and_then(|rows| rows.collect::<rusqlite::Result<Vec<(SocketAddr, String)>>>())
{
Ok(members) => {
members.into_iter().filter_map(|(address, state)| match serde_json::from_str::<foca::Member<Actor>>(state.as_str()) {
Ok(fs) => Some((address, fs)),
Err(e) => {
error!("could not deserialize foca member state: {e} (json: {state})");
None
}
}).collect::<Vec<(SocketAddr, Member<Actor>)>>()
}
Err(e) => {
error!("could not query for foca member states: {e}");
vec![]
},
}
}
Err(e) => {
error!("could not prepare query for foca member states: {e}");
vec![]
}
}
}),
Err(e) => {
error!("could not acquire conn for foca member states: {e}");
vec![]
}
}
}
pub async fn setup_http_api_handler(
agent: &Agent,
tripwire: &Tripwire,
subs_bcast_cache: BcastCache,
subs_manager: &SubsManager,
api_listener: TcpListener,
) -> eyre::Result<()> {
let api = Router::new()
// transactions
.route(
"/v1/transactions",
post(api_v1_transactions).route_layer(
tower::ServiceBuilder::new()
.layer(HandleErrorLayer::new(|_error: BoxError| async {
Ok::<_, Infallible>((
StatusCode::SERVICE_UNAVAILABLE,
"max concurrency limit reached".to_string(),
))
}))
.layer(LoadShedLayer::new())
.layer(ConcurrencyLimitLayer::new(128)),
),
)
// queries
.route(
"/v1/queries",
post(api_v1_queries).route_layer(
tower::ServiceBuilder::new()
.layer(HandleErrorLayer::new(|_error: BoxError| async {
Ok::<_, Infallible>((
StatusCode::SERVICE_UNAVAILABLE,
"max concurrency limit reached".to_string(),
))
}))
.layer(LoadShedLayer::new())
.layer(ConcurrencyLimitLayer::new(128)),
),
)
.route(
"/v1/subscriptions",
post(api_v1_subs).route_layer(
tower::ServiceBuilder::new()
.layer(HandleErrorLayer::new(|_error: BoxError| async {
Ok::<_, Infallible>((
StatusCode::SERVICE_UNAVAILABLE,
"max concurrency limit reached".to_string(),
))
}))
.layer(LoadShedLayer::new())
.layer(ConcurrencyLimitLayer::new(128)),
),
)
.route(
"/v1/subscriptions/:id",
get(api_v1_sub_by_id).route_layer(
tower::ServiceBuilder::new()
.layer(HandleErrorLayer::new(|_error: BoxError| async {
Ok::<_, Infallible>((
StatusCode::SERVICE_UNAVAILABLE,
"max concurrency limit reached".to_string(),
))
}))
.layer(LoadShedLayer::new())
.layer(ConcurrencyLimitLayer::new(128)),
),
)
.route(
"/v1/migrations",
post(api_v1_db_schema).route_layer(
tower::ServiceBuilder::new()
.layer(HandleErrorLayer::new(|_error: BoxError| async {
Ok::<_, Infallible>((
StatusCode::SERVICE_UNAVAILABLE,
"max concurrency limit reached".to_string(),
))
}))
.layer(LoadShedLayer::new())
.layer(ConcurrencyLimitLayer::new(4)),
),
)
.route(
"/v1/table_stats",
post(api_v1_table_stats).route_layer(
tower::ServiceBuilder::new()
.layer(HandleErrorLayer::new(|_error: BoxError| async {
Ok::<_, Infallible>((
StatusCode::SERVICE_UNAVAILABLE,
"max concurrency limit reached".to_string(),
))
}))
.layer(LoadShedLayer::new())
.layer(ConcurrencyLimitLayer::new(4)),
),
)
.layer(axum::middleware::from_fn(require_authz))
.layer(
tower::ServiceBuilder::new()
.layer(Extension(Arc::new(AtomicI64::new(0))))
.layer(Extension(agent.clone()))
.layer(Extension(subs_bcast_cache))
.layer(Extension(subs_manager.clone()))
.layer(Extension(tripwire.clone())),
)
.layer(DefaultBodyLimit::disable())
.layer(TraceLayer::new_for_http());
let api_addr = api_listener.local_addr()?;
info!("Starting public API server on tcp/{api_addr}");
let mut incoming = AddrIncoming::from_listener(api_listener)?;
incoming.set_nodelay(true);
spawn_counted(
axum::Server::builder(incoming)
.executor(CountedExecutor)
.serve(
api.clone()
.into_make_service_with_connect_info::<SocketAddr>(),
)
.with_graceful_shutdown(
tripwire
.clone()
.inspect(move |_| info!("corrosion api http tripped {api_addr}")),
)
.inspect(|_| info!("corrosion api is done")),
);
Ok(())
}
async fn require_authz<B>(
Extension(agent): Extension<Agent>,
maybe_authz_header: Option<TypedHeader<Authorization<Bearer>>>,
request: axum::http::Request<B>,
next: axum::middleware::Next<B>,
) -> Result<axum::response::Response, axum::http::StatusCode> {
let passed = if let Some(ref authz) = agent.config().api.authorization {
match authz {
AuthzConfig::BearerToken(token) => maybe_authz_header
.map(|h| h.token() == token)
.unwrap_or(false),
}
} else {
true
};
if !passed {
return Err(axum::http::StatusCode::UNAUTHORIZED);
}
Ok(next.run(request).await)
}
// DOCME: provide some context for this function
// TODO: move to a more appropriate module?
#[tracing::instrument(skip_all)]
pub fn find_cleared_db_versions(
tx: &Transaction,
actor_id: &ActorId,
) -> rusqlite::Result<BTreeSet<CrsqlDbVersion>> {
let clock_site_id: Option<u64> = match tx
.prepare_cached("SELECT ordinal FROM crsql_site_id WHERE site_id = ?")?
.query_row([actor_id], |row| row.get(0))
.optional()?
{
Some(ordinal) => Some(ordinal),
None => {
warn!(actor_id = %actor_id, "could not find crsql ordinal for actor");
return Ok(Default::default());
}
};
let tables = tx
.prepare_cached(
"SELECT name FROM sqlite_schema WHERE type = 'table' AND name LIKE '%__crsql_clock'",
)?
.query_map([], |row| row.get(0))?
.collect::<Result<BTreeSet<String>, _>>()?;
if tables.is_empty() {
// means there's no schema trakced by cr-sqlite or corrosion.
return Ok(BTreeSet::new());
}
let mut params: Vec<&dyn ToSql> = vec![actor_id];
let to_clear_query = format!(
"SELECT DISTINCT db_version FROM __corro_bookkeeping WHERE actor_id = ? AND db_version IS NOT NULL
EXCEPT SELECT db_version FROM ({});",
tables
.iter()
.map(|table| {
params.push(&clock_site_id);
format!("SELECT DISTINCT db_version FROM {table} WHERE site_id = ?")
})
.collect::<Vec<_>>()
.join(" UNION ")
);
let cleared_db_versions: BTreeSet<CrsqlDbVersion> = tx
.prepare_cached(&to_clear_query)?
.query_map(params_from_iter(params.into_iter()), |row| row.get(0))?
.collect::<rusqlite::Result<_>>()?;
Ok(cleared_db_versions)
}
/// Periodically initiate a sync with many other nodes. Before we do
/// though, apply buffered/ partial changesets to avoid having to sync
/// things we should already know about.
///
/// Actual sync logic is handled by
/// [`handle_sync`](crate::agent::handlers::handle_sync).
pub async fn sync_loop(
agent: Agent,
bookie: Bookie,
transport: Transport,
mut rx_apply: CorroReceiver<(ActorId, Version)>,
mut tripwire: Tripwire,
) {
let mut sync_backoff = backoff::Backoff::new(0)
.timeout_range(Duration::from_secs(1), MAX_SYNC_BACKOFF)
.iter();
let next_sync_at = tokio::time::sleep(sync_backoff.next().unwrap());
tokio::pin!(next_sync_at);
loop {
enum Branch {
Tick,
BackgroundApply { actor_id: ActorId, version: Version },
}
let branch = tokio::select! {
biased;
maybe_item = rx_apply.recv() => match maybe_item {
Some((actor_id, version)) => Branch::BackgroundApply{actor_id, version},
None => {
debug!("background applies queue is closed, breaking out of loop");
break;
}
},
_ = &mut next_sync_at => {
Branch::Tick
},
_ = &mut tripwire => {
break;
}
};
match branch {
Branch::Tick => {
// ignoring here, there is trying and logging going on inside
match handlers::handle_sync(&agent, &bookie, &transport)
.preemptible(&mut tripwire)
.await
{
tripwire::Outcome::Preempted(_) => {
warn!("aborted sync by tripwire");
break;
}
tripwire::Outcome::Completed(res) => {
if let Err(e) = res {
error!("could not sync: {e}");
// keep syncing until we successfully sync
continue;
}
}
}
next_sync_at
.as_mut()
.reset(tokio::time::Instant::now() + sync_backoff.next().unwrap());
}
Branch::BackgroundApply { actor_id, version } => {
debug!(%actor_id, %version, "picked up background apply of buffered changes");
match process_fully_buffered_changes(&agent, &bookie, actor_id, version).await {
Ok(false) => {
warn!(%actor_id, %version, "did not apply buffered changes");
}
Ok(true) => {
debug!(%actor_id, %version, "succesfully applied buffered changes");
}
Err(e) => {
error!(%actor_id, %version, "could not apply fully buffered changes: {e}");
}
}
}
}
}
}
/// Compact the database by finding cleared versions
pub async fn clear_buffered_meta_loop(
agent: Agent,
mut rx_partials: CorroReceiver<(ActorId, RangeInclusive<Version>)>,
) {
while let Some((actor_id, versions)) = rx_partials.recv().await {
let pool = agent.pool().clone();
let self_actor_id = agent.actor_id();
tokio::spawn(async move {
loop {
let res = {
let mut conn = pool.write_low().await?;
block_in_place(|| {
let tx = conn.immediate_transaction()?;
// TODO: delete buffered changes from deleted sequences only (maybe, it's kind of hard and may not be necessary)
// sub query required due to DELETE and LIMIT interaction
let seq_count = tx
.prepare_cached("DELETE FROM __corro_seq_bookkeeping WHERE (site_id, version, start_seq) IN (SELECT site_id, version, start_seq FROM __corro_seq_bookkeeping WHERE site_id = ? AND version >= ? AND version <= ? LIMIT ?)")?
.execute(params![actor_id, versions.start(), versions.end(), TO_CLEAR_COUNT])?;
// sub query required due to DELETE and LIMIT interaction
let buf_count = tx
.prepare_cached("DELETE FROM __corro_buffered_changes WHERE (site_id, db_version, version, seq) IN (SELECT site_id, db_version, version, seq FROM __corro_buffered_changes WHERE site_id = ? AND version >= ? AND version <= ? LIMIT ?)")?
.execute(params![actor_id, versions.start(), versions.end(), TO_CLEAR_COUNT])?;
tx.commit()?;
Ok::<_, rusqlite::Error>((buf_count, seq_count))
})
};
match res {
Ok((buf_count, seq_count)) => {
if buf_count + seq_count > 0 {
info!(%actor_id, %self_actor_id, "cleared {} buffered meta rows for versions {versions:?}", buf_count + seq_count);
}
if buf_count < TO_CLEAR_COUNT && seq_count < TO_CLEAR_COUNT {
break;
}
}
Err(e) => {
error!(%actor_id, "could not clear buffered meta for versions {versions:?}: {e}");
}
}
tokio::time::sleep(Duration::from_secs(2)).await;
}
Ok::<_, eyre::Report>(())
});
}
}
const MAX_EMPTIES_BATCH_SIZE: u64 = 40;
/// Clear empty versions from the database in chunks to avoid locking
/// the database for too long.
///
/// We are given versions to clear either by receiving empty
/// changesets, or when calling
/// [`find_cleared_db_versions`](self::find_cleared_db_versions)
/// periodically.
pub async fn write_empties_loop(
agent: Agent,
mut rx_empty: CorroReceiver<(ActorId, RangeInclusive<Version>)>,
mut tripwire: Tripwire,
) {
let mut empties: BTreeMap<ActorId, RangeInclusiveSet<Version>> = BTreeMap::new();
let next_empties_check = tokio::time::sleep(CHECK_EMPTIES_TO_INSERT_AFTER);
tokio::pin!(next_empties_check);
let mut count = 0;
loop {
tokio::select! {
maybe_empty = rx_empty.recv() => match maybe_empty {
Some((actor_id, versions)) => {
empties.entry(actor_id).or_default().insert(versions);
count += 1;
if count < MAX_EMPTIES_BATCH_SIZE {
continue;
}
},
None => {
debug!("empties queue is done");
break;
}
},
_ = &mut next_empties_check => {
next_empties_check.as_mut().reset(tokio::time::Instant::now() + CHECK_EMPTIES_TO_INSERT_AFTER);
if empties.is_empty() {
continue;
}
},
_ = &mut tripwire => break
}
let empties_to_process = std::mem::take(&mut empties);
// TODO: replace with a JoinSet and max concurrency
spawn_counted(
process_completed_empties(agent.clone(), empties_to_process)
.inspect_err(|e| error!("could not process empties: {e}")),
);
count = 0;
}
info!("Draining empty versions to process...");
// drain empties channel
while let Ok((actor_id, versions)) = rx_empty.try_recv() {
empties.entry(actor_id).or_default().insert(versions);
}
if !empties.is_empty() {
info!("Inserting last unprocessed empties before shut down");
if let Err(e) = process_completed_empties(agent, empties).await {
error!("could not process empties: {e}");
}
}
}
#[tracing::instrument(skip_all, err)]
pub async fn process_completed_empties(
agent: Agent,
empties: BTreeMap<ActorId, RangeInclusiveSet<Version>>,
) -> eyre::Result<()> {
debug!(
"processing empty versions (count: {})",
empties.values().map(RangeInclusiveSet::len).sum::<usize>()
);
let mut inserted = 0;
let start = Instant::now();
for (actor_id, empties) in empties {
let v = empties.into_iter().collect::<Vec<_>>();
for ranges in v.chunks(25) {
let mut conn = agent.pool().write_low().await?;
block_in_place(|| {
let mut tx = conn.immediate_transaction()?;
for range in ranges {
let mut sp = tx.savepoint()?;
match store_empty_changeset(&sp, actor_id, range.clone()) {
Ok(count) => {
inserted += count;
sp.commit()?;
}
Err(e) => {
error!(%actor_id, "could not store empty changeset for versions {range:?}: {e}");
sp.rollback()?;
continue;
}
}
if let Err(e) = agent.tx_clear_buf().try_send((actor_id, range.clone())) {
error!(%actor_id, "could not schedule buffered meta clear: {e}");
}
}
tx.commit()?;
Ok::<_, eyre::Report>(())
})?;
}
}
let elapsed = start.elapsed();
debug!("upserted {inserted} empty version ranges in {elapsed:?}");
counter!("corro.agent.empties.committed").increment(inserted as u64);
histogram!("corro.agent.empties.commit.second").record(elapsed);
Ok(())
}
#[tracing::instrument(skip_all, err)]
pub fn process_single_version(
agent: &Agent,
tx: &Transaction,
last_db_version: Option<CrsqlDbVersion>,
change: ChangeV1,
) -> rusqlite::Result<(KnownDbVersion, Changeset)> {
let ChangeV1 {
actor_id,
changeset,
} = change;
let versions = changeset.versions();
let (known, changeset) = if changeset.is_complete() {
let (known, changeset) = process_complete_version(
tx,
actor_id,
last_db_version,
versions,
changeset
.into_parts()
.expect("no changeset parts, this shouldn't be happening!"),
)?;
if check_buffered_meta_to_clear(tx, actor_id, changeset.versions())? {
if let Err(e) = agent
.tx_clear_buf()
.try_send((actor_id, changeset.versions()))
{
error!("could not schedule buffered meta clear: {e}");
}
}
(known, changeset)
} else {
let parts = changeset.into_parts().unwrap();
let known = process_incomplete_version(tx, actor_id, &parts)?;
(known, parts.into())
};
Ok((known, changeset))
}
pub fn store_empty_changeset(
conn: &Connection,
actor_id: ActorId,
versions: RangeInclusive<Version>,
) -> eyre::Result<usize> {
// first, delete "current" versions, they're now gone!
let deleted: Vec<RangeInclusive<Version>> = conn
.prepare_cached(
"
DELETE FROM __corro_bookkeeping
WHERE
actor_id = :actor_id AND
(
-- start_version is between start and end of range AND no end_version
( start_version BETWEEN :start AND :end AND end_version IS NULL ) OR
-- start_version and end_version are within the range
( start_version >= :start AND end_version <= :end ) OR
-- range being inserted is partially contained within another
( start_version <= :end AND end_version >= :end ) OR
-- start_version = end + 1 (to collapse ranges)
( start_version = :end + 1 AND end_version IS NOT NULL ) OR
-- end_version = start - 1 (to collapse ranges)
( end_version = :start - 1 )
)
RETURNING start_version, end_version",
)?
.query_map(
named_params![
":actor_id": actor_id,
":start": versions.start(),
":end": versions.end(),
],
|row| {
let start = row.get(0)?;
Ok(start..=row.get::<_, Option<Version>>(1)?.unwrap_or(start))
},
)
.and_then(|rows| rows.collect::<rusqlite::Result<Vec<_>>>())?;
if !deleted.is_empty() {
debug!(
"deleted {} still-live versions from database's bookkeeping",
deleted.len()
);
}
// re-compute the ranges
let mut new_ranges = RangeInclusiveSet::from_iter(deleted);
new_ranges.insert(versions);
// we should never have deleted non-contiguous ranges, abort!
if new_ranges.len() > 1 {
warn!("deleted non-contiguous ranges! {new_ranges:?}");
// this serves as a failsafe
eyre::bail!("deleted non-contiguous ranges: {new_ranges:?}");
}
let mut inserted = 0;
for range in new_ranges {
// insert cleared versions
inserted += conn
.prepare_cached(
"
INSERT INTO __corro_bookkeeping (actor_id, start_version, end_version, db_version, last_seq, ts)
VALUES (?, ?, ?, NULL, NULL, NULL);
",
)?
.execute(params![actor_id, range.start(), range.end()])?;
}
Ok(inserted)
}
#[tracing::instrument(skip(agent, bookie), err)]
pub async fn process_fully_buffered_changes(
agent: &Agent,
bookie: &Bookie,
actor_id: ActorId,
version: Version,
) -> Result<bool, ChangeError> {
let mut conn = agent.pool().write_normal().await?;
debug!(%actor_id, %version, "acquired write (normal) connection to process fully buffered changes");
let booked = {
bookie
.write(format!(
"process_fully_buffered(ensure):{}",
actor_id.as_simple()
))