-
Notifications
You must be signed in to change notification settings - Fork 2.5k
Expand file tree
/
Copy pathwriter.rs
More file actions
2023 lines (1845 loc) · 75.8 KB
/
Copy pathwriter.rs
File metadata and controls
2023 lines (1845 loc) · 75.8 KB
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
use std::future::Future;
use std::iter::Iterator;
use std::sync::atomic::AtomicBool;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant, SystemTime};
use arrow::array::{ArrayRef, BinaryArray, RecordBatch, UInt64Array};
use chroma_storage::{GetOptions, StorageError};
use chroma_types::Cmek;
use opentelemetry::trace::TraceContextExt;
use parquet::arrow::ArrowWriter;
use parquet::basic::Compression;
use parquet::file::properties::{EnabledStatistics, WriterProperties};
use parquet::schema::types::ColumnPath;
use setsum::Setsum;
use tracing::{Instrument, Level};
use tracing_opentelemetry::OpenTelemetrySpanExt;
use crate::interfaces::s3::fragment_uploader::S3FragmentUploader;
use crate::interfaces::{
FragmentManagerFactory, FragmentPointer, FragmentPublisher, ManifestManagerFactory,
ManifestPublisher,
};
use crate::{
parse_fragment_path, AppendOptions, AppendWork, BatchManager, CursorStore, CursorStoreOptions,
Error, ExponentialBackoff, Fragment, FragmentSeqNo, FragmentUuid, Garbage,
GarbageCollectionOptions, GarbageCollectionState, LogPosition, LogReader, LogReaderOptions,
LogWriterOptions, Manifest, ManifestAndWitness, ManifestManager,
};
/// The epoch writer is a counting writer. Every epoch exists. An epoch goes
/// unused->used->discarded. The epoch of a writer is used to determine if and when log contention
/// indicates that a new writer should be created. The epoch is incremented when a new writer is
/// created and checked before creating a new writer.
#[derive(Clone)]
pub struct EpochWriter<
P: FragmentPointer = (FragmentSeqNo, LogPosition),
FP: FragmentPublisher<FragmentPointer = P> = BatchManager<P, S3FragmentUploader>,
MP: ManifestPublisher<P> = ManifestManager,
> {
epoch: u64,
writer: Option<Arc<OnceLogWriter<P, FP, MP>>>,
}
impl<P: FragmentPointer, FP: FragmentPublisher<FragmentPointer = P>, MP: ManifestPublisher<P>>
Default for EpochWriter<P, FP, MP>
{
fn default() -> Self {
Self {
epoch: 0,
writer: None,
}
}
}
///////////////////////////////////////////// MarkDirty ////////////////////////////////////////////
#[async_trait::async_trait]
pub trait MarkDirty: Send + Sync + 'static {
async fn mark_dirty(&self, log_position: LogPosition, num_records: usize) -> Result<(), Error>;
}
#[async_trait::async_trait]
impl MarkDirty for () {
async fn mark_dirty(&self, _: LogPosition, _: usize) -> Result<(), Error> {
Ok(())
}
}
///////////////////////////////////////////// LogWriter ////////////////////////////////////////////
pub struct LogWriter<
P: FragmentPointer,
FP: FragmentManagerFactory<FragmentPointer = P>,
MP: ManifestManagerFactory<FragmentPointer = P>,
> {
options: LogWriterOptions,
writer: String,
new_fragment_publisher: FP,
new_manifest_publisher: MP,
_phantom_p: std::marker::PhantomData<P>,
inner: Mutex<EpochWriter<P, FP::Publisher, MP::Publisher>>,
reopen_protection: tokio::sync::Mutex<()>,
cmek: Option<Cmek>,
}
impl<
P: FragmentPointer,
FP: FragmentManagerFactory<FragmentPointer = P>,
MP: ManifestManagerFactory<FragmentPointer = P>,
> LogWriter<P, FP, MP>
{
pub async fn initialize(new_manifest_publisher: &MP, writer: &str) -> Result<(), Error> {
new_manifest_publisher
.init_manifest(&Manifest::new_empty(writer))
.await
}
/// Open the log, possibly writing a new manifest to recover it.
#[allow(clippy::too_many_arguments)]
pub async fn open(
options: LogWriterOptions,
writer: &str,
new_fragment_publisher: FP,
new_manifest_publisher: MP,
cmek: Option<Cmek>,
) -> Result<Self, Error> {
let inner = EpochWriter::default();
let writer = writer.to_string();
let reopen_protection = tokio::sync::Mutex::new(());
let this = Self {
options,
writer,
new_fragment_publisher,
new_manifest_publisher,
_phantom_p: std::marker::PhantomData,
inner: Mutex::new(inner),
reopen_protection,
cmek,
};
this.ensure_open().await?;
Ok(this)
}
/// Open or try once to initialize the log.
#[allow(clippy::too_many_arguments)]
pub async fn open_or_initialize(
options: LogWriterOptions,
writer: &str,
new_fragment_publisher: FP,
new_manifest_publisher: MP,
cmek: Option<Cmek>,
) -> Result<Self, Error> {
let inner = EpochWriter::default();
let writer = writer.to_string();
let reopen_protection = tokio::sync::Mutex::new(());
let this = Self {
options,
writer,
new_fragment_publisher,
new_manifest_publisher,
_phantom_p: std::marker::PhantomData,
inner: Mutex::new(inner),
reopen_protection,
cmek,
};
let mut last_err = None;
for _ in 0..3 {
match this.ensure_open().await {
Ok(_) => return Ok(this),
Err(Error::UninitializedLog) => {
last_err = Some(Error::UninitializedLog);
match Self::initialize(&this.new_manifest_publisher, &this.writer).await {
Ok(_) | Err(Error::AlreadyInitialized) => {}
Err(err) => return Err(err),
};
}
Err(Error::LogContentionRetry) => {
last_err = Some(Error::LogContentionRetry);
}
Err(err) => {
return Err(err);
}
}
}
Err(last_err.unwrap_or(Error::LogContentionRetry))
}
/// Given a contiguous subset of data from some other location (preferably another log),
/// construct a new log under storage/prefix using the provided options.
///
/// This function is safe to run again on failure and will not bootstrap over a partially
/// bootstrapped collection.
///
/// It is my intention to make this more robust as time goes on. Concretely, that means that
/// as we encounter partial failures left by the tool we fix them. There are 3 failure points
/// and I'd prefer to manually inspect failures than get the automation right to do it always
/// automatically. Bootstrap is intended only to last as long as there is a migration from the
/// go to the rust log services.
#[allow(clippy::too_many_arguments)]
pub async fn bootstrap<D: MarkDirty>(
_options: &LogWriterOptions,
writer: &str,
mark_dirty: D,
new_fragment_publisher: FP,
new_manifest_publisher: MP,
first_record_offset: LogPosition,
messages: Vec<Vec<u8>>,
cmek: Option<Cmek>,
) -> Result<(), Error> {
let num_records = messages.len();
let start = first_record_offset;
let limit = first_record_offset + num_records;
// NOTE(rescrv): There was once a speculative load to narrow the window in which we would
// see a race between writers. That's been eliminated via other tuning, I think (re gc),
// so that check has been removed.
// SAFETY(rescrv): This will only succeed if the file doesn't exist. Technically the log
// could be initialized and garbage collected to leave a prefix hole, but our timing
// assumption is that every op happens in less than 1/2 the GC interval, so there's no way
// for that to happen.
//
// If the file exists, this will fail with LogContention, which fails us with
// LogContention. Other errors fail transparently, too.
if num_records > 0 {
let fragment_publisher = new_fragment_publisher.make_publisher().await?;
let pointer = P::bootstrap(first_record_offset);
let epoch_micros = now_micros();
let upload_result = fragment_publisher
.upload_parquet(&pointer, messages, cmek, epoch_micros)
.await?;
let num_bytes = upload_result.num_bytes as u64;
let frag = Fragment {
path: upload_result.path,
seq_no: pointer.identifier(),
start,
limit,
num_bytes,
setsum: upload_result.setsum,
};
let empty_manifest = Manifest::new_empty(writer);
let mut new_manifest = empty_manifest.clone();
new_manifest.initial_offset = Some(start);
// SAFETY(rescrv): This is unit tested to never happen. If it happens, add more tests.
if !new_manifest.can_apply_fragment(&frag) {
tracing::error!("Cannot apply frag to a clean manifest.");
return Err(Error::internal(file!(), line!()));
}
new_manifest.apply_fragment(frag);
// SAFETY(rescrv): If this fails, there's nothing left to do.
new_manifest_publisher.init_manifest(&new_manifest).await?;
// Not Safety:
// We mark dirty, but if we lose that we lose that.
// Failure to mark dirty fails the bootstrap.
mark_dirty.mark_dirty(start, num_records).await?;
} else {
let empty_manifest = Manifest::new_empty("bootstrap");
let mut new_manifest = empty_manifest.clone();
new_manifest.initial_offset = Some(start);
// SAFETY(rescrv): If this fails, there's nothing left to do.
new_manifest_publisher.init_manifest(&new_manifest).await?;
// No need to mark dirty as the manifest is empty.
}
Ok(())
}
/// This will close the log.
pub async fn close(self) -> Result<(), Error> {
// SAFETY(rescrv): Mutex poisoning.
let writer = { self.inner.lock().unwrap().writer.take() };
if let Some(writer) = writer {
writer.close().await
} else {
Ok(())
}
}
/// Append a message to a log.
pub async fn append(&self, message: Vec<u8>) -> Result<LogPosition, Error> {
self.append_with_options(message, None).await
}
/// Append a message to a log with options.
pub async fn append_with_options(
&self,
message: Vec<u8>,
options: Option<AppendOptions>,
) -> Result<LogPosition, Error> {
self.append_many_with_options(vec![message], options).await
}
#[tracing::instrument(skip(self, messages))]
pub async fn append_many(&self, messages: Vec<Vec<u8>>) -> Result<LogPosition, Error> {
self.append_many_with_options(messages, None).await
}
#[tracing::instrument(skip(self, messages, options))]
pub async fn append_many_with_options(
&self,
messages: Vec<Vec<u8>>,
options: Option<AppendOptions>,
) -> Result<LogPosition, Error> {
let retry_contention_internally = match options.as_ref() {
Some(options) => options.required_fragment_start.is_none(),
None => true,
};
let once_log_append_many =
move |log: &Arc<OnceLogWriter<P, FP::Publisher, MP::Publisher>>| {
let messages = messages.clone();
let options = options.clone();
let log = Arc::clone(log);
async move { log.append(messages, options).await }
};
self.handle_errors_and_contention(once_log_append_many, retry_contention_internally)
.await
}
pub async fn reader(
&self,
options: LogReaderOptions,
) -> Option<LogReader<P, FP::Consumer, MP::Consumer>> {
let fragment_consumer = self.new_fragment_publisher.make_consumer().await.ok()?;
let manifest_consumer = self.new_manifest_publisher.make_consumer().await.ok()?;
Some(LogReader::new(
options,
fragment_consumer,
manifest_consumer,
))
}
pub async fn manifest_and_witness(&self) -> Result<ManifestAndWitness, Error> {
let inner = {
// SAFETY(rescrv): Mutex poisoning.
let inner = self.inner.lock().unwrap();
Arc::clone(inner.writer.as_ref().ok_or_else(|| Error::LogClosed)?)
};
inner.manifest_and_witness().await
}
pub async fn garbage_collect_phase1_compute_garbage(
&self,
options: &GarbageCollectionOptions,
keep_at_least: Option<LogPosition>,
) -> Result<Option<GarbageCollectionState>, Error> {
let once_log_garbage_collect =
move |log: &Arc<OnceLogWriter<P, FP::Publisher, MP::Publisher>>| {
let options = options.clone();
let log = Arc::clone(log);
async move {
log.garbage_collect_phase1_compute_garbage(&options, keep_at_least)
.await
}
};
self.handle_errors_and_contention(once_log_garbage_collect, true)
.await
}
pub async fn garbage_collect_phase2_update_manifest(
&self,
options: &GarbageCollectionOptions,
) -> Result<(), Error> {
let once_log_garbage_collect =
move |log: &Arc<OnceLogWriter<P, FP::Publisher, MP::Publisher>>| {
let options = options.clone();
let log = Arc::clone(log);
async move { log.garbage_collect_phase2_update_manifest(&options).await }
};
self.handle_errors_and_contention(once_log_garbage_collect, true)
.await
}
pub async fn garbage_collect_phase3_delete_garbage(
&self,
options: &GarbageCollectionOptions,
gc_state: &GarbageCollectionState,
) -> Result<(), Error> {
let gc_state = gc_state.clone();
let once_log_garbage_collect =
move |log: &Arc<OnceLogWriter<P, FP::Publisher, MP::Publisher>>| {
let options = options.clone();
let gc_state = gc_state.clone();
let log = Arc::clone(log);
async move {
log.garbage_collect_phase3_delete_garbage(&options, &gc_state)
.await
}
};
self.handle_errors_and_contention(once_log_garbage_collect, true)
.await
}
pub async fn garbage_collect(
&self,
options: &GarbageCollectionOptions,
keep_at_least: Option<LogPosition>,
) -> Result<(), Error> {
let once_log_garbage_collect =
move |log: &Arc<OnceLogWriter<P, FP::Publisher, MP::Publisher>>| {
let options = options.clone();
let log = Arc::clone(log);
async move { log.garbage_collect(&options, keep_at_least).await }
};
self.handle_errors_and_contention(once_log_garbage_collect, true)
.await
}
async fn handle_errors_and_contention<O, F: Future<Output = Result<O, Error>>>(
&self,
f: impl Fn(&Arc<OnceLogWriter<P, FP::Publisher, MP::Publisher>>) -> F,
retry_contention_internally: bool,
) -> Result<O, Error> {
for _ in 0..3 {
let (writer, epoch) = self.ensure_open().await?;
match f(&writer).await {
Ok(out) => {
return Ok(out);
}
Err(Error::LogContentionDurable) => {
{
// SAFETY(rescrv): Mutex poisoning.
let mut inner = self.inner.lock().unwrap();
if inner.epoch == epoch {
if let Some(writer) = inner.writer.take() {
writer.shutdown();
}
}
}
// Silence this error in favor of the one we got from f.
if self.ensure_open().await.is_ok() {
return Err(Error::LogContentionDurable);
} else {
return Err(Error::LogContentionFailure);
}
}
Err(Error::LogContentionFailure) => {
// SAFETY(rescrv): Mutex poisoning.
let mut inner = self.inner.lock().unwrap();
if inner.epoch == epoch {
if let Some(writer) = inner.writer.take() {
writer.shutdown();
}
}
return Err(Error::LogContentionFailure);
}
Err(Error::LogContentionRetry) => {
// SAFETY(rescrv): Mutex poisoning.
let mut inner = self.inner.lock().unwrap();
if inner.epoch == epoch {
if let Some(writer) = inner.writer.take() {
writer.shutdown();
}
}
if !retry_contention_internally {
return Err(Error::LogContentionRetry);
}
}
Err(Error::Backoff) => {
return Err(Error::Backoff);
}
Err(err) => {
let mut inner = self.inner.lock().unwrap();
if inner.epoch == epoch {
if let Some(writer) = inner.writer.take() {
writer.shutdown();
}
}
return Err(err);
}
}
}
Err(Error::LogContentionFailure)
}
async fn ensure_open(
&self,
) -> Result<(Arc<OnceLogWriter<P, FP::Publisher, MP::Publisher>>, u64), Error> {
let _guard = self.reopen_protection.lock().await;
for _ in 0..3 {
let epoch = {
// SAFETY(rescrv): Mutex poisoning.
let mut inner = self.inner.lock().unwrap();
if let Some(writer) = inner.writer.as_ref() {
if !writer.done.load(std::sync::atomic::Ordering::Relaxed) {
return Ok((Arc::clone(writer), inner.epoch));
} else {
writer.shutdown();
inner.writer.take();
inner.epoch += 1;
continue;
}
}
inner.epoch
};
let batch_manager = self.new_fragment_publisher.make_publisher().await?;
let manifest_manager = self.new_manifest_publisher.open_publisher().await?;
let writer = match OnceLogWriter::open(
self.options.clone(),
batch_manager,
manifest_manager,
self.cmek.clone(),
)
.await
{
Ok(writer) => writer,
Err(Error::LogContentionRetry) => continue,
Err(err) => return Err(err),
};
// SAFETY(rescrv): Mutex poisoning.
let mut inner = self.inner.lock().unwrap();
if inner.epoch == epoch && inner.writer.is_none() {
inner.epoch += 1;
if let Some(writer) = inner.writer.take() {
writer.shutdown();
}
inner.writer = Some(Arc::clone(&writer));
return Ok((writer, inner.epoch));
}
}
Err(Error::LogContentionRetry)
}
}
impl<
P: FragmentPointer,
FP: FragmentManagerFactory<FragmentPointer = P>,
MP: ManifestManagerFactory<FragmentPointer = P>,
> std::fmt::Debug for LogWriter<P, FP, MP>
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("LogWriter")
.field("writer", &self.writer)
.finish()
}
}
impl<
P: FragmentPointer,
FP: FragmentManagerFactory<FragmentPointer = P>,
MP: ManifestManagerFactory<FragmentPointer = P>,
> Drop for LogWriter<P, FP, MP>
{
fn drop(&mut self) {
let mut inner = self.inner.lock().unwrap();
if let Some(writer) = inner.writer.as_mut() {
writer.shutdown();
}
}
}
/////////////////////////////////////////// OnceLogWriter //////////////////////////////////////////
/// OnceLogWriter writes to a log once until contention is discovered. It must then be thrown away
/// and recovered. Because throw-away and recovery have the exact same network round-trip
/// structure as the recovery procedure does, this allows us to re-use exactly one code path for
/// both. That code path can then be well-tested because any contention state gets exercised from
/// the perspective of initialization.
pub(crate) struct OnceLogWriter<
P: FragmentPointer = (FragmentSeqNo, LogPosition),
FP: FragmentPublisher<FragmentPointer = P> = BatchManager<P, S3FragmentUploader>,
MP: ManifestPublisher<P> = ManifestManager,
> {
/// LogWriterOptions are fixed at log creation time.
/// LogWriter is intentionally cheap to construct and destroy.
/// Reopen the log to change the options.
options: LogWriterOptions,
/// True iff the log is done.
done: AtomicBool,
/// ManifestManager coordinates updates to the manifest.
manifest_manager: MP,
/// BatchManager coordinates batching writes to the log.
batch_manager: FP,
/// Customer-managed encryption key for encrypting log fragments.
cmek: Option<Cmek>,
}
impl<P: FragmentPointer, FP: FragmentPublisher<FragmentPointer = P>, MP: ManifestPublisher<P>>
OnceLogWriter<P, FP, MP>
{
async fn open(
options: LogWriterOptions,
batch_manager: FP,
mut manifest_manager: MP,
cmek: Option<Cmek>,
) -> Result<Arc<Self>, Error> {
let done = AtomicBool::new(false);
manifest_manager.recover().await?;
let this = Arc::new(Self {
options,
done,
manifest_manager,
batch_manager,
cmek,
});
let that = Arc::downgrade(&this);
let _flusher = tokio::task::spawn(async move {
loop {
let Some(that) = that.upgrade() else {
break;
};
if !that.done.load(std::sync::atomic::Ordering::Relaxed) {
that.batch_manager.wait_for_writable().await;
match that.batch_manager.take_work(&that.manifest_manager).await {
Ok(Some((pointer, required_fragment_start, work))) => {
Arc::clone(&that)
.append_batch(pointer, required_fragment_start, work)
.await;
}
Ok(None) => {
let sleep_for = that.batch_manager.until_next_time();
drop(that);
tokio::time::sleep(sleep_for).await;
}
Err(err) => {
let sleep_for = that.batch_manager.until_next_time();
drop(that);
tracing::error!("batch_manager.take_work: {:?}", err);
tokio::time::sleep(sleep_for).await;
}
}
} else {
break;
}
}
});
Ok(this)
}
pub(crate) async fn open_for_read_only_and_stale_ops(
options: LogWriterOptions,
batch_manager: FP,
manifest_manager: MP,
) -> Result<Arc<Self>, Error> {
let done = AtomicBool::new(false);
Ok(Arc::new(Self {
options,
done,
manifest_manager,
batch_manager,
cmek: None, // Read-only operations don't need CMEK
}))
}
async fn manifest_and_witness(&self) -> Result<ManifestAndWitness, Error> {
self.manifest_manager.manifest_and_witness().await
}
fn shutdown(&self) {
self.batch_manager.shutdown_prepare();
self.manifest_manager.shutdown();
self.done.store(true, std::sync::atomic::Ordering::Relaxed);
self.batch_manager.shutdown_finish();
}
async fn close(mut self: Arc<Self>) -> Result<(), Error> {
self.shutdown();
loop {
match Arc::try_unwrap(self) {
Ok(_) => {
break;
}
Err(arc) => {
std::thread::sleep(Duration::from_millis(100));
self = arc;
}
}
}
Ok(())
}
async fn append(
self: &Arc<Self>,
messages: Vec<Vec<u8>>,
options: Option<AppendOptions>,
) -> Result<LogPosition, Error> {
if messages.is_empty() {
return Err(Error::EmptyBatch);
}
let append_span = tracing::info_span!("append_span");
let append_span_clone = append_span.clone();
async move {
let (tx, rx) = tokio::sync::oneshot::channel();
self.batch_manager
.push_work(AppendWork::new(messages, options, tx, append_span))
.await;
match self.batch_manager.take_work(&self.manifest_manager).await {
Ok(Some(work)) => {
let (pointer, required_fragment_start, work) = work;
{
tokio::task::spawn(Arc::clone(self).append_batch(
pointer,
required_fragment_start,
work,
));
}
}
Ok(None) => {}
Err(err) => {
tracing::error!(error = %err, "batch manager failed");
}
}
let span = tracing::info_span!("wait_for_durability");
rx.instrument(span)
.await
.map_err(|_| Error::internal(file!(), line!()))?
}
.instrument(append_span_clone)
.await
}
async fn append_batch(
self: Arc<Self>,
pointer: P,
required_fragment_start: Option<LogPosition>,
work: Vec<AppendWork>,
) {
let append_batch_span = tracing::info_span!("append_batch");
let mut messages = Vec::with_capacity(work.len());
let mut notifies = Vec::with_capacity(work.len());
for work in work.into_iter() {
let AppendWork {
messages: work_messages,
options: _,
tx,
span,
} = work;
notifies.push((work_messages.len(), tx));
messages.extend(work_messages);
// NOTE(rescrv): This returns a context that returns a reference to the span, from
// which we get a span context that we clone. My initial read of this was to interpret
// it as creating a span and that is not the case.
span.add_link(append_batch_span.context().span().span_context().clone());
}
async move {
if notifies.is_empty() {
tracing::error!("somehow got empty messages");
return;
}
match self
.append_batch_internal(pointer, required_fragment_start, messages)
.await
{
Ok(mut log_position) => {
for (num_messages, notify) in notifies.into_iter() {
if notify.send(Ok(log_position)).is_err() {
// TODO(rescrv): Counter this.
}
log_position += num_messages;
}
}
Err(e) => {
for (_, notify) in notifies.into_iter() {
if notify.send(Err(e.clone())).is_err() {
// TODO(rescrv): Counter this.
}
}
}
}
}
.instrument(append_batch_span)
.await
}
#[tracing::instrument(skip(self, pointer, messages))]
async fn append_batch_internal(
&self,
pointer: P,
required_fragment_start: Option<LogPosition>,
messages: Vec<Vec<u8>>,
) -> Result<LogPosition, Error> {
assert!(!messages.is_empty());
let messages_len = messages.len();
let epoch_micros = now_micros();
let upload_result = self
.batch_manager
.upload_parquet(&pointer, messages, self.cmek.clone(), epoch_micros)
.await
.inspect_err(|_| {
self.shutdown();
})?;
let log_position = self
.manifest_manager
.publish_fragment(
&pointer,
&upload_result.path,
messages_len as u64,
upload_result.num_bytes as u64,
upload_result.setsum,
required_fragment_start,
&upload_result.successful_regions,
)
.await
.inspect_err(|_| {
self.shutdown();
})?;
// Record the records/batches written.
self.batch_manager.finish_write().await;
Ok(log_position)
}
/// Perform phase 0 of garbage collection.
///
/// Transition any existing gc/GARBAGE state back to empty without deleting queued garbage.
///
#[tracing::instrument(skip(self, _options))]
pub(crate) async fn garbage_collect_phase0_reset_garbage(
&self,
_options: &GarbageCollectionOptions,
) -> Result<(), Error> {
let Some((garbage, e_tag)) =
Garbage::load(&self.options.throttle_manifest, &self.batch_manager).await?
else {
return Ok(());
};
if garbage.is_empty() {
return Ok(());
}
let Some(e_tag) = e_tag.as_ref() else {
return Err(Error::GarbageCollection(
"loaded garbage without e_tag".to_string(),
));
};
self.batch_manager
.reset_garbage(&self.options.throttle_manifest, e_tag)
.await
}
/// Perform phase 1 of garbage collection.
///
/// Pre-condition: manifest/MANIFEST exists.
///
/// Post-condition:
/// - gc/GARBAGE exists as a non-empty file.
/// - snapshots created by gc/GARBAGE get created.
///
/// Returns the GarbageCollectionState token that must be passed to phase 3.
/// The state carries the set of affirmatively collected UUID fragments so that phase 3 can
/// delete them unconditionally, while applying a grace period to unlisted orphans.
///
/// Returns Ok(None) if there is no garbage to act upon.
/// Returns Ok(Some(state)) if there is garbage to act upon.
#[tracing::instrument(skip(self, options))]
pub(crate) async fn garbage_collect_phase1_compute_garbage(
&self,
options: &GarbageCollectionOptions,
keep_at_least: Option<LogPosition>,
) -> Result<Option<GarbageCollectionState>, Error> {
let cutoff = self.garbage_collection_cutoff().await?;
let cutoff = if let Some(keep_at_least) = keep_at_least {
keep_at_least.min(cutoff)
} else {
cutoff
};
let mut attempts = 0;
loop {
attempts += 1;
if attempts > 3 {
return Err(Error::LogContentionFailure);
}
let garbage_and_e_tag = match Garbage::load(
&self.options.throttle_manifest,
&self.batch_manager,
)
.await
{
Ok(Some((garbage, e_tag))) => {
if garbage.is_empty()
|| self
.manifest_manager
.garbage_applies_cleanly(&garbage)
.await?
{
Some((garbage, e_tag))
} else if let Some(e_tag) = e_tag {
tracing::info!("resetting garbage because a concurrent snapshot write invalidated prior garbage");
self.batch_manager
.reset_garbage(&self.options.throttle_manifest, &e_tag)
.await?;
continue;
} else {
return Err(Error::GarbageCollection(
"non-empty garbage without ETag".to_string(),
));
}
}
Ok(None) => None,
Err(err) => {
tracing::error!(error =% err, "could not install garbage");
return Err(err);
}
};
let e_tag = if let Some((garbage, e_tag)) = garbage_and_e_tag {
if !garbage.is_empty() {
let maw = self.manifest_manager.manifest_and_witness().await?;
let state =
GarbageCollectionState::from_manifest_and_garbage(&maw.manifest, &garbage);
return Ok(Some(state));
}
e_tag
} else {
None
};
let garbage = self
.manifest_manager
.compute_garbage(options, cutoff)
.await?;
let Some(garbage) = garbage else {
return Ok(None);
};
let maw = self.manifest_manager.manifest_and_witness().await?;
let state = GarbageCollectionState::from_manifest_and_garbage(&maw.manifest, &garbage);
match garbage
.install(
&self.manifest_manager,
&self.batch_manager,
&self.options.throttle_manifest,
e_tag.as_ref(),
)
.await
{
Ok(_) => return Ok(Some(state)),
Err(Error::LogContentionFailure)
| Err(Error::LogContentionRetry)
| Err(Error::LogContentionDurable) => {}
Err(err) => {
tracing::error!(error =% err, "could not install garbage");
return Err(err);
}
};
}
}
/// Perform phase 2 of grabage collection.
///
/// Pre-conditions:
/// - manifest/MANIFEST exists.
/// - gc/GARBAGE exists.
///
/// Post-condition:
/// - contents of gc/GARBAGE are removed from manifest/MANIFEST.
#[tracing::instrument(skip(self, _options))]
pub(crate) async fn garbage_collect_phase2_update_manifest(
&self,
_options: &GarbageCollectionOptions,
) -> Result<(), Error> {
let (garbage, _) =
match Garbage::load(&self.options.throttle_manifest, &self.batch_manager).await {
Ok(Some((garbage, e_tag))) => (garbage, e_tag),
Ok(None) => return Ok(()),
Err(err) => {
return Err(err);
}
};
if !garbage.is_empty() {
self.manifest_manager.apply_garbage(garbage.clone()).await.inspect_err(|err| {
if let Error::GarbageCollectionPrecondition(err) = err {
tracing::event!(Level::ERROR, name = "garbage collection precondition failed", error =? err, garbage =? garbage);
}
})?;
}
Ok(())
}
/// Perform phase 3 of garbage collection.
///
/// Pre-conditions:
/// - manifest/MANIFEST exists
/// - gc/GARBAGE exists
/// - manifest/MANIFEST does not reference any part of gc/GARBAGE
///
/// Post-condition:
/// - gc/GARBAGE and the files it references get deleted.
#[tracing::instrument(skip(self, options, gc_state))]
pub(crate) async fn garbage_collect_phase3_delete_garbage(
&self,
options: &GarbageCollectionOptions,
gc_state: &GarbageCollectionState,
) -> Result<(), Error> {
async fn delete_paths_in_batches<I, F, Fut>(
paths: I,
batch_size: usize,
exp_backoff: ExponentialBackoff,
delete_batch: F,
) -> Result<(), Error>
where
I: IntoIterator<Item = String>,
F: Fn(Vec<String>, ExponentialBackoff) -> Fut,
Fut: Future<Output = Result<(), Error>>,
{
let mut batch = vec![];
for path in paths {
batch.push(path);
if batch.len() >= batch_size {
let batch = std::mem::take(&mut batch);
delete_batch(batch, exp_backoff.clone()).await?;
}
}
if !batch.is_empty() {
delete_batch(batch, exp_backoff).await?;
}
Ok(())
}
let exp_backoff: ExponentialBackoff = options.throttle.into();
let start = Instant::now();
let (garbage, e_tag) =
match Garbage::load(&self.options.throttle_manifest, &self.batch_manager).await {
Ok(Some((garbage, e_tag))) => (garbage, e_tag),
Ok(None) => return Ok(()),
Err(err) => {
return Err(err);
}
};
let Some(e_tag) = e_tag.as_ref() else {
return Err(Error::GarbageCollection(
"loaded garbage without e_tag".to_string(),
));
};
let storage = self.batch_manager.preferred_storage().await;
let delete_batch = |batch: Vec<String>, exp_backoff: ExponentialBackoff| {
let storage = storage.clone();
async move {