-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathlib.rs
2137 lines (1856 loc) · 66.3 KB
/
lib.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2018 10x Genomics, Inc. All rights reserved.
//! Serialize large streams of `Serialize`-able structs to disk from multiple threads, with a customizable on-disk sort order.
//! Data is written to sorted chunks. When reading shardio will merge the data on the fly into a single sorted view. You can
//! also procss disjoint subsets of sorted data.
//!
//! Additionally, you can also iterate through the data in the order they are written to disk. The items will not
//! in general follow the sort order. Such an iterator does not involve the merge sort step and hence does not
//! have the memory overhead associated with keeping multiple items in memory to perform the merge sort.
//!
//! ```rust
//! use serde::{Deserialize, Serialize};
//! use shardio::*;
//! use std::fs::File;
//! use anyhow::Error;
//!
//! #[derive(Clone, Eq, PartialEq, Serialize, Deserialize, PartialOrd, Ord, Debug)]
//! struct DataStruct {
//! a: u64,
//! b: u32,
//! }
//!
//! fn main() -> Result<(), Error>
//! {
//! let filename = "test.shardio";
//! {
//! // Open a shardio output file
//! // Parameters here control buffering, and the size of disk chunks
//! // which affect how many disk chunks need to be read to
//! // satisfy a range query when reading.
//! // In this example the 'built-in' sort order given by #[derive(Ord)]
//! // is used.
//! let mut writer: ShardWriter<DataStruct> =
//! ShardWriter::new(filename, 64, 256, 1<<16)?;
//!
//! // Get a handle to send data to the file
//! let mut sender = writer.get_sender();
//!
//! // Generate some test data
//! for i in 0..(2 << 16) {
//! sender.send(DataStruct { a: (i%25) as u64, b: (i%100) as u32 });
//! }
//!
//! // done sending items
//! sender.finished();
//!
//! // Write errors are accessible by calling the finish() method
//! writer.finish()?;
//! }
//!
//! // Open finished file & test chunked reads
//! let reader = ShardReader::<DataStruct>::open(filename)?;
//!
//!
//! let mut all_items = Vec::new();
//!
//! // Shardio will divide the key space into 5 roughly equally sized chunks.
//! // These chunks can be processed serially, in parallel in different threads,
//! // or on different machines.
//! let chunks = reader.make_chunks(5, &Range::all());
//!
//! for c in chunks {
//! // Iterate over all the data in chunk c.
//! let mut range_iter = reader.iter_range(&c)?;
//! for i in range_iter {
//! all_items.push(i?);
//! }
//! }
//!
//! // Data will be return in sorted order
//! let mut all_items_sorted = all_items.clone();
//! all_items.sort();
//! assert_eq!(all_items, all_items_sorted);
//!
//! // If you want to iterate through the items in unsorted order.
//! let unsorted_items: Vec<_> = UnsortedShardReader::<DataStruct>::open(filename).collect();
//! // You will get the items in the order they are written to disk.
//! assert_eq!(unsorted_items.len(), all_items.len());
//!
//! std::fs::remove_file(filename)?;
//! Ok(())
//! }
//! ```
#![deny(warnings)]
#![deny(missing_docs)]
use std::any::type_name;
use std::borrow::Cow;
use std::collections::BTreeSet;
use std::fs::File;
use std::io::{self, Seek, SeekFrom};
use std::marker::PhantomData;
use std::ops::DerefMut;
use std::os::unix::fs::FileExt;
use std::path::Path;
use std::sync::{atomic::AtomicBool, Arc, Mutex};
use std::thread;
use anyhow::{format_err, Error};
use bincode::{deserialize_from, serialize_into};
use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
use log::warn;
use min_max_heap::MinMaxHeap;
use serde::{de::DeserializeOwned, Deserialize, Serialize};
/// Represent a range of key space
pub mod range;
/// Helper methods
pub mod helper;
pub use crate::range::Range;
use range::Rorder;
mod unsorted;
pub use unsorted::*;
/// The size (in bytes) of a ShardIter object (mostly buffers)
// ? sizeof(T)
// + 8 usize items_remaining
// + 8 &bincode::Config
// + 8KB BufReader
// + 32KB of lz4-rs internal buffer
// + 64KB of lz4-sys default blockSize (x2)
// + 128KB lz4-sys default blockLinked
// + 4 lz4-sys checksum
pub const SHARD_ITER_SZ: usize = 8 + 8 + 8_192 + 32_768 + 65_536 * 2 + 131_072 + 4;
// this number is chosen such that, for the expected size of a ShardIter above,
// represents at least 1GiB of memory (1024^3 / 303124 =~ 3542.3)
const WARN_ACTIVE_SHARDS: usize = 3_543;
#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Eq, PartialOrd, Ord)]
/// A group of `len_items` items, from shard `shard`, stored at position `offset`, using `block_size` bytes on-disk,
/// with sort keys covering the interval [`start_key`, `end_key`]
struct ShardRecord<K> {
start_key: K,
end_key: K,
offset: usize,
len_bytes: usize,
len_items: usize,
}
/// Specify a key function from data items of type `T` to a sort key of type `Key`.
/// Impelment this trait to create a custom sort order.
/// The function `sort_key` returns a `Cow` so that we abstract over Owned or
/// Borrowed data.
/// ```rust
///
/// extern crate shardio;
/// use shardio::*;
/// use std::borrow::Cow;
///
/// // The default sort order for DataStruct will be by field1.
/// #[derive(Ord, PartialOrd, Eq, PartialEq)]
/// struct DataStruct {
/// field1: usize,
/// field2: String,
/// }
///
/// // Define a marker struct for your new sort order
/// struct Field2SortKey;
///
/// // Define the new sort key by extracting field2 from DataStruct
/// impl SortKey<DataStruct> for Field2SortKey {
/// type Key = String;
///
/// fn sort_key(t: &DataStruct) -> Cow<String> {
/// Cow::Borrowed(&t.field2)
/// }
/// }
/// ```
pub trait SortKey<T> {
/// The type of the key that will be sorted.
type Key: Ord + Clone;
/// Compute the sort key for value `t`.
fn sort_key(t: &T) -> Cow<'_, Self::Key>;
}
/// Marker struct for sorting types that implement `Ord` in the order defined by their `Ord` impl.
/// This sort order is used by default when writing, unless an alternative sort order is provided.
pub struct DefaultSort;
impl<T> SortKey<T> for DefaultSort
where
T: Ord + Clone,
{
type Key = T;
fn sort_key(t: &T) -> Cow<'_, T> {
Cow::Borrowed(t)
}
}
/// Write a stream data items of type `T` to disk, in the sort order defined by `S`.
///
/// Data is buffered up to `item_buffer_size` items, then sorted, block compressed and written to disk.
/// When the ShardWriter is dropped or has `finish()` called on it, it will
/// flush remaining items to disk, write an index of the chunk data and close the file.
///
/// The `get_sender()` methods returns a `ShardSender` that must be used to send items to the writer.
/// You must close each ShardSender by dropping it or calling its `finish()` method, or data may be lost.
/// The `ShardSender` must be dropped/finished prior to callinng `SharWriter::finish` or dropping the shard writer.
///
/// # Sorting
/// Items are sorted according to the `Ord` implementation of type `S::Key`. Type `S`, implementing the `SortKey` trait
/// maps items of type `T` to their sort key of type `S::Key`. By default the sort key is the data item itself, and the
/// the `DefaultSort` implementation of `SortKey` is the identity function.
pub struct ShardWriter<T, S = DefaultSort>
where
T: 'static + Send + Serialize,
S: SortKey<T>,
<S as SortKey<T>>::Key: 'static + Send + Ord + Serialize + Clone,
{
inner: Option<Arc<ShardWriterInner<T, S>>>,
sort: PhantomData<S>,
}
impl<T, S> ShardWriter<T, S>
where
T: 'static + Send + Serialize,
S: SortKey<T>,
<S as SortKey<T>>::Key: 'static + Send + Ord + Serialize + Clone,
{
/// Create a writer for storing data items of type `T`.
/// # Arguments
/// * `path` - Path to newly created output file
/// * `sender_buffer_size` - number of items to buffer on the sending thread before transferring data to the writer.
/// Each transfer to the writer requires one channel send, and one allocation.
/// Set to ~16 or 32 it you're sending items very rapidly (>100k/s).
/// * `disk_chunk_size` - Number of items to store in each chunk on disk. Controls the tradeoff between indexing overhead and the granularity
/// of reads into the sorted dataset. When reading, shardio must iterate from the start of a chunk to access an item.
/// * `item_buffer_size` - Number of items to buffer before sorting, chunking and writing items to disk. More buffering causes each chunk
/// to cover a smaller interval of key space (allowing for more efficient reading), but requires more memory.
pub fn new<P: AsRef<Path>>(
path: P,
sender_buffer_size: usize,
disk_chunk_size: usize,
item_buffer_size: usize,
) -> Result<ShardWriter<T, S>, Error> {
assert!(disk_chunk_size >= 1);
assert!(item_buffer_size >= 1);
assert!(sender_buffer_size >= 1);
assert!(item_buffer_size >= sender_buffer_size);
let inner =
ShardWriterInner::new(disk_chunk_size, item_buffer_size, sender_buffer_size, path)?;
Ok(ShardWriter {
inner: Some(Arc::new(inner)),
sort: PhantomData,
})
}
/// Get a `ShardSender`. It can be sent to another thread that is generating data.
pub fn get_sender(&self) -> ShardSender<T, S> {
ShardSender::new(self.inner.as_ref().unwrap().clone())
}
/// Call finish if you want to detect errors in the writer IO.
pub fn finish(&mut self) -> Result<usize, Error> {
if let Some(inner_arc) = self.inner.take() {
match Arc::try_unwrap(inner_arc) {
Ok(inner) => inner.close(),
Err(_) => {
if !std::thread::panicking() {
panic!("ShardSenders are still active. They must all be out of scope or finished() before ShardWriter is closed");
} else {
Ok(0)
}
}
}
} else {
Ok(0)
}
}
}
impl<T, S> Drop for ShardWriter<T, S>
where
S: SortKey<T>,
<S as SortKey<T>>::Key: 'static + Send + Ord + Serialize + Clone,
T: Send + Serialize,
{
fn drop(&mut self) {
let _e = self.finish();
}
}
/// Coordinate a pair of buffers that need to added to from multiple threads and processed/flushed when full.
/// Coordinates acces to `buffer_state`, passing full buffers to `handler` when they are full.
struct BufferStateMachine<T, H> {
sender_buffer_size: usize,
buffer_state: Mutex<BufStates<T>>,
handler: Mutex<H>,
closed: AtomicBool,
}
/// There are always two item buffers held by a ShardWriter. A buffer can be in the process of being filled,
/// waiting for use, or being processed & written to disk. In the first two states, the buffer will be held
/// by this enum. In the processing state it will be held on the stack of the thread processing the buffer.
#[derive(PartialEq, Eq)]
enum BufStates<T> {
/// Fill the first buffer, using the second as backup
FillAndWait(Vec<T>, Vec<T>),
/// Fill the buffer, the other buffer is being written out
FillAndBusy(Vec<T>),
/// Both buffers are busy, try again later
BothBusy,
/// Placeholder variable, should never be observed.
Dummy,
}
/// Outcome of trying to add items to the buffer.
enum BufAddOutcome<T> {
/// Items added successfully
Done,
/// No free buffers, operation must be re-tried
Retry,
/// Items added, but a buffer was filled and must be processed.
/// Buffer to be processed is attached.
Process(Vec<T>),
}
use BufAddOutcome::{Done, Process, Retry};
use BufStates::{BothBusy, Dummy, FillAndBusy, FillAndWait};
use std::fmt;
impl<T> fmt::Debug for BufStates<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
BufStates::FillAndWait(a, b) => write!(f, "FillAndWait({}, {})", a.len(), b.len()),
BufStates::FillAndBusy(a) => write!(f, "FillAndBusy({})", a.len()),
BufStates::BothBusy => write!(f, "BothBusy"),
BufStates::Dummy => write!(f, "Dummy"),
}
}
}
impl<T, H: BufHandler<T>> BufferStateMachine<T, H> {
/// Move `items` into the buffer & it. If a buffer is filled by this operation
/// then the calling thread will be used to process the full buffer.
fn add_items(&self, items: &mut Vec<T>) -> Result<(), Error> {
if self.closed.load(std::sync::atomic::Ordering::Relaxed) {
panic!("tried to add items to ShardSender after ShardWriter was closed");
}
loop {
// get mutex on buffers
let mut buffer_state = self.buffer_state.lock().unwrap();
let mut current_state = Dummy;
std::mem::swap(buffer_state.deref_mut(), &mut current_state);
// determine new state and any follow-up work
let (mut new_state, outcome) = match current_state {
FillAndWait(mut f, w) => {
f.append(items);
if f.len() + self.sender_buffer_size > f.capacity() {
(FillAndBusy(w), Process(f))
} else {
(FillAndWait(f, w), Done)
}
}
FillAndBusy(mut f) => {
f.append(items);
if f.len() + self.sender_buffer_size > f.capacity() {
(BothBusy, Process(f))
} else {
(FillAndBusy(f), Done)
}
}
BothBusy => (BothBusy, Retry),
Dummy => unreachable!(),
};
// Fill in the new state.
std::mem::swap(buffer_state.deref_mut(), &mut new_state);
// drop the mutex
drop(buffer_state);
// outcome could be to process a full vec, retry, or be done.
match outcome {
Process(mut buf_to_process) => {
// process the buffer & return it to the pool.
self.process_buffer(&mut buf_to_process)?;
self.return_buffer(buf_to_process);
break;
}
Retry => {
// take a break before trying again.
thread::yield_now();
continue;
}
Done => break,
}
}
Ok(())
}
/// shut down the buffer machinery, processing any remaining items.
/// calls to `add_items` after `close` will panic.
pub fn close(self) -> Result<H, Error> {
self.closed.store(true, std::sync::atomic::Ordering::SeqCst);
let mut bufs_processed = 0;
loop {
if bufs_processed == 2 {
break;
}
let mut buffer_state = self.buffer_state.lock().unwrap();
let mut current_state = BufStates::Dummy;
std::mem::swap(buffer_state.deref_mut(), &mut current_state);
let (mut new_state, to_process) = match current_state {
BufStates::FillAndWait(f, w) => (BufStates::FillAndBusy(w), Some(f)),
BufStates::FillAndBusy(f) => (BufStates::BothBusy, Some(f)),
// if both buffers are busy, we yield and try again.
BufStates::BothBusy => {
// don't leave a BufStates::Dummy in circulation.
*buffer_state.deref_mut() = BufStates::BothBusy;
thread::yield_now();
continue;
}
BufStates::Dummy => unreachable!(),
};
// fill in the new state.
std::mem::swap(buffer_state.deref_mut(), &mut new_state);
if let Some(mut buf) = to_process {
bufs_processed += 1;
self.process_buffer(&mut buf)?;
} else {
unreachable!();
}
}
Ok(self.handler.into_inner().unwrap())
}
/// put a buffer back into service after processing
fn return_buffer(&self, buf: Vec<T>) {
let mut buffer_state = self.buffer_state.lock().unwrap();
let mut current_state = BufStates::Dummy;
std::mem::swap(buffer_state.deref_mut(), &mut current_state);
let mut new_state = match current_state {
BufStates::FillAndWait(_, _) => panic!("there are 3 buffers in use!!"),
BufStates::FillAndBusy(f) => BufStates::FillAndWait(f, buf),
BufStates::BothBusy => BufStates::FillAndBusy(buf),
BufStates::Dummy => unreachable!(),
};
std::mem::swap(buffer_state.deref_mut(), &mut new_state);
}
/// process `buf`
pub fn process_buffer(&self, buf: &mut Vec<T>) -> Result<(), Error> {
// prepare the buffer for process - this doesn't require
// a lock on handler
H::prepare_buf(buf);
// process the buf -- this requires the handler mutex
let mut handler = self.handler.lock().unwrap();
handler.process_buf(buf)?;
buf.clear();
Ok(())
}
}
/// Two-part handler for a buffer needing processing.
/// `prepare_buf` is generic and needs no state. Used for sorting.
/// `process_buf` needs exclusive access to the handler, so can do IO.
pub trait BufHandler<T> {
/// Sort the provided buffer.
fn prepare_buf(v: &mut Vec<T>);
/// Process the provided buffer.
fn process_buf(&mut self, v: &mut Vec<T>) -> Result<(), Error>;
}
/// Provide the base implementation for sorting chunks and writing shards.
pub struct SortAndWriteHandler<T, S>
where
T: Send + Serialize,
S: SortKey<T>,
<S as SortKey<T>>::Key: Ord + Clone + Serialize,
{
// Current start position of next chunk
cursor: usize,
// Record of chunks written
regions: Vec<ShardRecord<<S as SortKey<T>>::Key>>,
// File handle
file: File,
// Size of disk chunks
chunk_size: usize,
// Buffers for use when writing
serialize_buffer: Vec<u8>,
compress_buffer: Vec<u8>,
}
impl<T, S> BufHandler<T> for SortAndWriteHandler<T, S>
where
T: Send + Serialize,
S: SortKey<T>,
<S as SortKey<T>>::Key: Ord + Clone + Serialize,
{
/// Sort items according to `S`.
fn prepare_buf(buf: &mut Vec<T>) {
buf.sort_by(|x, y| S::sort_key(x).cmp(&S::sort_key(y)));
}
/// Write items to disk chunks
fn process_buf(&mut self, buf: &mut Vec<T>) -> Result<(), Error> {
// Write out the buffer chunks
for c in buf.chunks(self.chunk_size) {
self.write_chunk(c)?;
}
Ok(())
}
}
impl<T, S> SortAndWriteHandler<T, S>
where
T: Send + Serialize,
S: SortKey<T>,
<S as SortKey<T>>::Key: Ord + Clone + Serialize,
{
/// Create a new handler using the provided chunk size, writing to path.
pub fn new<P: AsRef<Path>>(
chunk_size: usize,
path: P,
) -> Result<SortAndWriteHandler<T, S>, Error> {
let file = File::create(path)?;
Ok(SortAndWriteHandler {
cursor: 4096,
regions: Vec::new(),
file,
serialize_buffer: Vec::new(),
compress_buffer: Vec::new(),
chunk_size,
})
// FIXME: write a magic string to the start of the file,
// and maybe some metadata about the types being stored and the
// compression scheme.
// FIXME: write to a TempFile that will be destroyed unless
// writing completes successfully.
}
fn write_chunk(&mut self, items: &[T]) -> Result<(), Error> {
self.serialize_buffer.clear();
self.compress_buffer.clear();
assert!(!items.is_empty());
let bounds = (
S::sort_key(&items[0]).into_owned(),
S::sort_key(&items[items.len() - 1]).into_owned(),
);
for item in items {
serialize_into(&mut self.serialize_buffer, item)?;
}
{
use std::io::Write;
let mut encoder = lz4::EncoderBuilder::new()
.level(2) // this appears to be a good general trad-off of speed and compression ratio.
// note see these benchmarks for useful numers:
// http://quixdb.github.io/squash-benchmark/#ratio-vs-compression
// important note: lz4f (not lz4) is the relevant mode in those charts.
.build(&mut self.compress_buffer)?;
encoder.write_all(&self.serialize_buffer)?;
let (_, result) = encoder.finish();
result?;
}
let cur_offset = self.cursor;
let reg = ShardRecord {
offset: self.cursor,
start_key: bounds.0,
end_key: bounds.1,
len_bytes: self.compress_buffer.len(),
len_items: items.len(),
};
self.regions.push(reg);
self.cursor += self.compress_buffer.len();
self.file
.write_all_at(&self.compress_buffer, cur_offset as u64)?;
Ok(())
}
/// Write out the shard positioning data
pub fn write_index(&mut self) -> Result<(), Error> {
let mut buf = Vec::new();
serialize_into(&mut buf, &(type_name::<T>(), type_name::<S>()))?;
serialize_into(&mut buf, &self.regions)?;
let index_block_position = self.cursor;
let index_block_size = buf.len();
self.file
.write_all_at(buf.as_slice(), index_block_position as u64)?;
self.file.seek(SeekFrom::Start(
(index_block_position + index_block_size) as u64,
))?;
self.file.write_u64::<BigEndian>(0_u64)?;
self.file
.write_u64::<BigEndian>(index_block_position as u64)?;
self.file.write_u64::<BigEndian>(index_block_size as u64)?;
Ok(())
}
}
/// Sort buffered items, break large buffer into chunks.
/// Serialize, compress and write the each chunk. The
/// file manager maintains the index data.
struct ShardWriterInner<T, S>
where
T: Send + Serialize,
S: SortKey<T>,
<S as SortKey<T>>::Key: Ord + Clone + Serialize,
{
sender_buffer_size: usize,
state_machine: BufferStateMachine<T, SortAndWriteHandler<T, S>>,
}
impl<T, S> ShardWriterInner<T, S>
where
T: Send + Serialize,
S: SortKey<T>,
<S as SortKey<T>>::Key: Ord + Clone + Serialize,
{
fn new(
chunk_size: usize,
buf_size: usize,
sender_buffer_size: usize,
path: impl AsRef<Path>,
) -> Result<ShardWriterInner<T, S>, Error> {
let handler = SortAndWriteHandler::new(chunk_size, path)?;
let bufs = BufStates::FillAndWait(
Vec::with_capacity(buf_size / 2),
Vec::with_capacity(buf_size / 2),
);
let state_machine = BufferStateMachine {
buffer_state: Mutex::new(bufs),
handler: Mutex::new(handler),
closed: AtomicBool::new(false),
sender_buffer_size,
};
Ok(ShardWriterInner {
sender_buffer_size,
state_machine,
})
}
fn send_items(&self, items: &mut Vec<T>) -> Result<(), Error> {
self.state_machine.add_items(items)
}
fn close(self) -> Result<usize, Error> {
let mut handler = self.state_machine.close()?;
let nitems = handler.regions.iter().map(|r| r.len_items).sum();
handler.write_index()?;
Ok(nitems)
}
}
/// A handle that is used to send data to a `ShardWriter`. Each thread that is producing data
/// needs it's own ShardSender. A `ShardSender` can be obtained with the `get_sender` method of
/// `ShardWriter`. ShardSender implement clone.
pub struct ShardSender<T, S = DefaultSort>
where
T: Send + Serialize,
S: SortKey<T>,
<S as SortKey<T>>::Key: Ord + Clone + Serialize,
{
writer: Option<Arc<ShardWriterInner<T, S>>>,
buffer: Vec<T>,
buf_size: usize,
}
impl<T: Send, S> ShardSender<T, S>
where
T: Send + Serialize,
S: SortKey<T>,
<S as SortKey<T>>::Key: Ord + Clone + Serialize,
{
fn new(writer: Arc<ShardWriterInner<T, S>>) -> ShardSender<T, S> {
let buffer = Vec::with_capacity(writer.sender_buffer_size);
let buf_size = writer.sender_buffer_size;
ShardSender {
writer: Some(writer),
buffer,
buf_size,
}
}
/// Send an item to the shard file
pub fn send(&mut self, item: T) -> Result<(), Error> {
let send = {
self.buffer.push(item);
self.buffer.len() == self.buf_size
};
if send {
self.writer
.as_ref()
.expect("ShardSender is already closed")
.send_items(&mut self.buffer)?;
}
Ok(())
}
/// Signal that you've finished sending items to this `ShardSender`. `finished` will called
/// if the `ShardSender` is dropped. You must call `finished()` or drop the `ShardSender`
/// prior to calling `ShardWriter::finish` or dropping the ShardWriter, or you will get a panic.
pub fn finished(&mut self) -> Result<(), Error> {
// send any remaining items and drop the Arc<ShardWriterInner>
if let Some(inner) = self.writer.take() {
if !self.buffer.is_empty() {
inner.send_items(&mut self.buffer)?;
}
}
assert!(self.writer.is_none());
Ok(())
}
}
impl<T, S> Clone for ShardSender<T, S>
where
T: Send + Serialize,
S: SortKey<T>,
<S as SortKey<T>>::Key: Ord + Clone + Serialize,
{
fn clone(&self) -> Self {
let buffer = Vec::with_capacity(self.buf_size);
ShardSender {
writer: self.writer.clone(),
buffer,
buf_size: self.buf_size,
}
}
}
impl<T: Send, S: SortKey<T>> Drop for ShardSender<T, S>
where
T: Send + Serialize,
S: SortKey<T>,
<S as SortKey<T>>::Key: Ord + Clone + Serialize,
{
fn drop(&mut self) {
let _e = self.finished();
}
}
/// Read a shardio file
struct ShardReaderSingle<T, S = DefaultSort>
where
S: SortKey<T>,
{
file: File,
index: Vec<ShardRecord<<S as SortKey<T>>::Key>>,
p1: PhantomData<T>,
}
type ShardRecordVec<T, S> = Vec<ShardRecord<<S as SortKey<T>>::Key>>;
impl<T, S> ShardReaderSingle<T, S>
where
T: DeserializeOwned,
S: SortKey<T>,
<S as SortKey<T>>::Key: Clone + Ord + DeserializeOwned,
{
/// Open a shard file that stores `T` items.
fn open<P: AsRef<Path>>(path: P) -> Result<ShardReaderSingle<T, S>, Error> {
let f = File::open(path)?;
let (mut index, f) = Self::read_index_block(f)?;
index.sort();
Ok(ShardReaderSingle {
file: f,
index,
p1: PhantomData,
})
}
/// Read shard index
fn read_index_block(mut file: File) -> Result<(ShardRecordVec<T, S>, File), Error> {
let _ = file.seek(SeekFrom::End(-24))?;
let _num_shards = file.read_u64::<BigEndian>()? as usize;
let index_block_position = file.read_u64::<BigEndian>()?;
let _ = file.read_u64::<BigEndian>()?;
file.seek(SeekFrom::Start(index_block_position))?;
let (t_typ, s_typ): (String, String) = deserialize_from(&mut file)?;
// if compiler version is the same, type misnaming is an error
if t_typ != type_name::<T>() || s_typ != type_name::<S>() {
return Err(format_err!(
"Expected type {} with sort order {}, but got type {} with sort order {}",
type_name::<T>(),
type_name::<S>(),
t_typ,
s_typ,
));
}
let recs = deserialize_from(&mut file)?;
Ok((recs, file))
}
/// Return an iterator over the items in the given `range` of keys.
pub fn iter_range(
&self,
range: &Range<<S as SortKey<T>>::Key>,
) -> Result<RangeIter<'_, T, S>, Error> {
RangeIter::new(self, range.clone())
}
/// Return an iterator over the items in one disk shard (corresponding to one index entry)
fn iter_shard(
&self,
rec: &ShardRecord<<S as SortKey<T>>::Key>,
) -> Result<ShardIter<'_, T, S>, Error> {
ShardIter::new(self, rec.clone())
}
/// Total number of values held by this reader
pub fn len(&self) -> usize {
self.index.iter().map(|x| x.len_items).sum()
}
// Returns true if there are no values held by this reader.
pub fn is_empty(&self) -> bool {
self.index.iter().all(|x| x.len_items == 0)
}
/// Estimate an upper bound on the total number of values held by a range
pub fn est_len_range(&self, range: &Range<<S as SortKey<T>>::Key>) -> usize {
self.index
.iter()
.map(|x| {
if range.intersects_shard(x) {
x.len_items
} else {
0
}
})
.sum::<usize>()
}
}
use std::borrow::Borrow;
use std::io::BufReader;
use std::io::Read;
struct ReadAdapter<T: Borrow<F>, F: FileExt> {
file: T,
offset: usize,
bytes_remaining: usize,
phantom: PhantomData<F>,
}
impl<T: Borrow<F>, F: FileExt> ReadAdapter<T, F> {
fn new(file: T, offset: usize, len: usize) -> Self {
ReadAdapter {
file,
offset,
bytes_remaining: len,
phantom: PhantomData,
}
}
}
impl<T: Borrow<F>, F: FileExt> Read for ReadAdapter<T, F> {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
let read_len = std::cmp::min(buf.len(), self.bytes_remaining);
let buf_slice = &mut buf[0..read_len];
self.file
.borrow()
.read_exact_at(buf_slice, self.offset as u64)?;
self.offset += read_len;
self.bytes_remaining -= read_len;
Ok(read_len)
}
}
struct ShardIter<'a, T, S>
where
S: SortKey<T>,
{
next_item: Option<(T, S::Key)>,
decoder: lz4::Decoder<BufReader<ReadAdapter<&'a File, File>>>,
items_remaining: usize,
phantom_s: PhantomData<S>,
}
impl<'a, T, S> ShardIter<'a, T, S>
where
T: DeserializeOwned,
S: SortKey<T>,
<S as SortKey<T>>::Key: Ord + Clone,
{
pub(crate) fn new(
reader: &'a ShardReaderSingle<T, S>,
rec: ShardRecord<<S as SortKey<T>>::Key>,
) -> Result<Self, Error> {
let adp_reader = ReadAdapter::new(&reader.file, rec.offset, rec.len_bytes);
let buf_reader = BufReader::new(adp_reader);
let mut lz4_reader = lz4::Decoder::new(buf_reader)?;
let first_item: T = deserialize_from(&mut lz4_reader)?;
let first_key = S::sort_key(&first_item).into_owned();
let items_remaining = rec.len_items - 1;
Ok(ShardIter {
next_item: Some((first_item, first_key)),
decoder: lz4_reader,
items_remaining,
phantom_s: PhantomData,
})
}
/// Return the key of the next item in the iterator
pub(crate) fn current_key(&self) -> &<S as SortKey<T>>::Key {
self.next_item.as_ref().map(|a| &a.1).unwrap()
}
/// Return the next item in the iterator
pub(crate) fn pop(mut self) -> Result<(T, Option<Self>), Error> {
let item = self.next_item.unwrap();
if self.items_remaining == 0 {
Ok((item.0, None))
} else {
let next_item = deserialize_from(&mut self.decoder)?;
let next_key = S::sort_key(&next_item).into_owned();
self.next_item = Some((next_item, next_key));
self.items_remaining -= 1;
Ok((item.0, Some(self)))
}
}
}
use std::cmp::Ordering;
impl<'a, T, S> Ord for ShardIter<'a, T, S>
where
S: SortKey<T>,
<S as SortKey<T>>::Key: Ord + Clone,
{
fn cmp(&self, other: &ShardIter<'a, T, S>) -> Ordering {
let key_self = self.next_item.as_ref().map(|a| &a.1);
let key_other = other.next_item.as_ref().map(|b| &b.1);
key_self.cmp(&key_other)
}
}
impl<'a, T, S> Eq for ShardIter<'a, T, S>
where
S: SortKey<T>,
<S as SortKey<T>>::Key: Ord + Clone,
{
}
impl<'a, T, S> PartialOrd for ShardIter<'a, T, S>
where
S: SortKey<T>,
<S as SortKey<T>>::Key: Ord + Clone,
{
fn partial_cmp(&self, other: &ShardIter<'a, T, S>) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl<'a, T, S> PartialEq for ShardIter<'a, T, S>
where
S: SortKey<T>,
<S as SortKey<T>>::Key: Ord + Clone,
{
fn eq(&self, other: &ShardIter<'a, T, S>) -> bool {
let key_self = self.next_item.as_ref().map(|a| &a.1);
let key_other = other.next_item.as_ref().map(|b| &b.1);