-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
mod.rs
3642 lines (3268 loc) Β· 122 KB
/
mod.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
pub mod chunks;
pub mod index;
pub mod job;
pub mod listener;
pub mod partition;
pub mod schema;
pub mod table;
pub mod wal;
use async_trait::async_trait;
use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
use log::{error, info};
use rocksdb::{
DBIterator, Direction, IteratorMode, MergeOperands, Options, ReadOptions, Snapshot, WriteBatch,
WriteBatchIterator, DB,
};
use serde::{Deserialize, Deserializer, Serialize};
use std::hash::{Hash, Hasher};
use std::{collections::hash_map::DefaultHasher, env, io::Cursor, sync::Arc, time};
use tokio::fs;
use tokio::sync::{Notify, RwLock};
use crate::config::injection::DIService;
use crate::config::{Config, ConfigObj};
use crate::metastore::chunks::{ChunkIndexKey, ChunkRocksIndex};
use crate::metastore::index::IndexIndexKey;
use crate::metastore::job::{Job, JobIndexKey, JobRocksIndex, JobRocksTable, JobStatus};
use crate::metastore::partition::PartitionIndexKey;
use crate::metastore::table::{TableIndexKey, TablePath};
use crate::metastore::wal::{WALIndexKey, WALRocksIndex};
use crate::remotefs::{LocalDirRemoteFs, RemoteFs};
use crate::store::DataFrame;
use crate::table::{Row, TableValue};
use crate::util::lock::acquire_lock;
use crate::util::time_span::{warn_long, warn_long_fut};
use crate::util::WorkerLoop;
use crate::CubeError;
use arrow::datatypes::TimeUnit::Microsecond;
use arrow::datatypes::{DataType, Field};
use chrono::{DateTime, Utc};
use chunks::ChunkRocksTable;
use core::{fmt, mem};
use cubehll::HllSketch;
use cubezetasketch::HyperLogLogPlusPlus;
use datafusion::cube_ext;
use futures::future::join_all;
use futures_timer::Delay;
use index::{IndexRocksIndex, IndexRocksTable};
use itertools::Itertools;
use log::trace;
use parquet::basic::{ConvertedType, Repetition};
use parquet::{basic::Type, schema::types};
use partition::{PartitionRocksIndex, PartitionRocksTable};
use regex::Regex;
use rocksdb::backup::BackupEngineOptions;
use rocksdb::checkpoint::Checkpoint;
use schema::{SchemaRocksIndex, SchemaRocksTable};
use smallvec::alloc::fmt::Formatter;
use std::collections::HashMap;
use std::fmt::Debug;
use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::sync::Mutex;
use std::time::{Duration, SystemTime};
use table::Table;
use table::{TableRocksIndex, TableRocksTable};
use tokio::fs::File;
use tokio::sync::broadcast::Sender;
use wal::WALRocksTable;
#[macro_export]
macro_rules! format_table_value {
($row:expr, $field:ident, $tt:ty) => {
DataFrameValue::value(&$row.$field)
};
}
#[macro_export]
macro_rules! data_frame_from {
(
$( #[$struct_attr:meta] )*
pub struct $name:ident {
$( $( #[$field_attr:meta] )* $variant:ident : $tt:ty ),+
}
) => {
$( #[$struct_attr] )*
pub struct $name {
$( $( #[$field_attr] )* $variant : $tt ),+
}
impl From<Vec<IdRow<$name>>> for DataFrame {
fn from(rows: Vec<IdRow<$name>>) -> Self {
DataFrame::new(
vec![
Column::new("id".to_string(), ColumnType::Int, 0),
$( Column::new(std::stringify!($variant).to_string(), ColumnType::String, 1) ),+
],
rows.iter().map(|r|
Row::new(vec![
TableValue::Int(r.id as i64),
$(
TableValue::String(format_table_value!(r.row, $variant, $tt))
),+
])
).collect()
)
}
}
}
}
#[macro_export]
macro_rules! base_rocks_secondary_index {
($table: ty, $index: ty) => {
impl BaseRocksSecondaryIndex<$table> for $index {
fn index_key_by(&self, row: &$table) -> Vec<u8> {
self.key_to_bytes(&self.typed_key_by(row))
}
fn get_id(&self) -> u32 {
RocksSecondaryIndex::get_id(self)
}
fn is_unique(&self) -> bool {
RocksSecondaryIndex::is_unique(self)
}
}
};
}
#[macro_export]
macro_rules! rocks_table_impl {
($table: ty, $rocks_table: ident, $table_id: expr, $indexes: block) => {
pub(crate) struct $rocks_table<'a> {
db: crate::metastore::DbTableRef<'a>,
}
impl<'a> $rocks_table<'a> {
pub fn new(db: crate::metastore::DbTableRef<'a>) -> $rocks_table {
$rocks_table { db }
}
}
impl<'a> RocksTable for $rocks_table<'a> {
type T = $table;
fn db(&self) -> &DB {
self.db.db
}
fn snapshot(&self) -> &rocksdb::Snapshot {
self.db.snapshot
}
fn mem_seq(&self) -> &crate::metastore::MemorySequence {
&self.db.mem_seq
}
fn table_id(&self) -> TableId {
$table_id
}
fn index_id(&self, index_num: IndexId) -> IndexId {
if index_num > 99 {
panic!("Too big index id: {}", index_num);
}
$table_id as IndexId + index_num
}
fn deserialize_row<'de, D>(
&self,
deserializer: D,
) -> Result<$table, <D as Deserializer<'de>>::Error>
where
D: Deserializer<'de>,
{
<$table>::deserialize(deserializer)
}
fn indexes() -> Vec<Box<dyn BaseRocksSecondaryIndex<$table>>> {
$indexes
}
fn update_event(
&self,
old_row: IdRow<Self::T>,
new_row: IdRow<Self::T>,
) -> MetaStoreEvent {
paste::expr! { MetaStoreEvent::[<Update $table>](old_row, new_row) }
}
fn delete_event(&self, row: IdRow<Self::T>) -> MetaStoreEvent {
paste::expr! { MetaStoreEvent::[<Delete $table>](row) }
}
}
impl<'a> core::fmt::Debug for $rocks_table<'a> {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.write_fmt(format_args!("{}", stringify!($rocks_table)))?;
Ok(())
}
}
};
}
pub trait DataFrameValue<T> {
fn value(v: &Self) -> T;
}
impl DataFrameValue<String> for String {
fn value(v: &Self) -> String {
v.to_string()
}
}
impl DataFrameValue<String> for u64 {
fn value(v: &Self) -> String {
format!("{}", v)
}
}
impl DataFrameValue<String> for bool {
fn value(v: &Self) -> String {
format!("{}", v)
}
}
impl DataFrameValue<String> for Vec<Column> {
fn value(v: &Self) -> String {
serde_json::to_string(v).unwrap()
}
}
impl DataFrameValue<String> for Option<String> {
fn value(v: &Self) -> String {
v.as_ref()
.map(|s| s.to_string())
.unwrap_or("NULL".to_string())
}
}
impl DataFrameValue<String> for Option<Vec<String>> {
fn value(v: &Self) -> String {
v.as_ref()
.map(|s| format!("{:?}", s))
.unwrap_or("NULL".to_string())
}
}
impl DataFrameValue<String> for Option<DateTime<Utc>> {
fn value(v: &Self) -> String {
v.as_ref()
.map(|s| s.to_string())
.unwrap_or("NULL".to_string())
}
}
impl DataFrameValue<String> for Option<ImportFormat> {
fn value(v: &Self) -> String {
v.as_ref()
.map(|v| format!("{:?}", v))
.unwrap_or("NULL".to_string())
}
}
impl DataFrameValue<String> for Option<u64> {
fn value(v: &Self) -> String {
v.as_ref()
.map(|v| format!("{:?}", v))
.unwrap_or("NULL".to_string())
}
}
impl DataFrameValue<String> for Option<Row> {
fn value(v: &Self) -> String {
v.as_ref()
.map(|v| {
format!(
"({})",
v.values()
.iter()
.map(|tv| match tv {
TableValue::Null => "NULL".to_string(),
TableValue::String(s) => format!("\"{}\"", s),
TableValue::Int(i) => i.to_string(),
TableValue::Timestamp(t) => format!("{:?}", t),
TableValue::Bytes(b) => format!("{:?}", b),
TableValue::Boolean(b) => format!("{:?}", b),
TableValue::Decimal(v) => format!("{}", v.raw_value()),
TableValue::Float(v) => format!("{}", v),
})
.join(", ")
)
})
.unwrap_or("NULL".to_string())
}
}
#[derive(Clone, Copy, Serialize, Deserialize, Debug, Eq, PartialEq, Hash)]
pub enum HllFlavour {
Airlift, // Compatible with Presto, Athena, etc.
Snowflake, // Same storage as Airlift, imports from Snowflake JSON.
Postgres, // Same storage as Airlift, imports from HLL Storage Specification.
ZetaSketch, // Compatible with BigQuery.
}
pub fn is_valid_plain_binary_hll(data: &[u8], f: HllFlavour) -> Result<(), CubeError> {
// TODO: do no memory allocations for better performance, this is run on hot path.
match f {
HllFlavour::Airlift => {
HllSketch::read(data)?;
}
HllFlavour::ZetaSketch => {
HyperLogLogPlusPlus::read(data)?;
}
HllFlavour::Postgres | HllFlavour::Snowflake => {
panic!("string formats should be handled separately")
}
}
return Ok(());
}
#[derive(Clone, Serialize, Deserialize, Debug, Eq, PartialEq, Hash)]
pub enum ColumnType {
String,
Int,
Bytes,
HyperLogLog(HllFlavour), // HLL Sketches, compatible with presto.
Timestamp,
Decimal { scale: i32, precision: i32 },
Float,
Boolean,
}
impl ColumnType {
pub fn target_scale(&self) -> i32 {
match self {
ColumnType::Decimal { scale, .. } => {
if *scale > 5 {
10
} else {
*scale
}
}
x => panic!("target_scale called on {:?}", x),
}
}
}
impl From<&Column> for parquet::schema::types::Type {
fn from(column: &Column) -> Self {
match column.get_column_type() {
crate::metastore::ColumnType::String => {
types::Type::primitive_type_builder(&column.get_name(), Type::BYTE_ARRAY)
.with_converted_type(ConvertedType::UTF8)
.with_repetition(Repetition::OPTIONAL)
.build()
.unwrap()
}
crate::metastore::ColumnType::Int => {
types::Type::primitive_type_builder(&column.get_name(), Type::INT64)
.with_converted_type(ConvertedType::INT_64)
.with_repetition(Repetition::OPTIONAL)
.build()
.unwrap()
}
crate::metastore::ColumnType::Decimal { precision, .. } => {
types::Type::primitive_type_builder(&column.get_name(), Type::INT64)
.with_converted_type(ConvertedType::DECIMAL)
.with_precision(*precision)
.with_scale(column.get_column_type().target_scale())
.with_repetition(Repetition::OPTIONAL)
.build()
.unwrap()
}
crate::metastore::ColumnType::Bytes | ColumnType::HyperLogLog(_) => {
types::Type::primitive_type_builder(&column.get_name(), Type::BYTE_ARRAY)
.with_converted_type(ConvertedType::NONE)
.with_repetition(Repetition::OPTIONAL)
.build()
.unwrap()
}
crate::metastore::ColumnType::Timestamp => {
types::Type::primitive_type_builder(&column.get_name(), Type::INT64)
//TODO MICROS?
.with_converted_type(ConvertedType::TIMESTAMP_MICROS)
.with_repetition(Repetition::OPTIONAL)
.build()
.unwrap()
}
crate::metastore::ColumnType::Boolean => {
types::Type::primitive_type_builder(&column.get_name(), Type::BOOLEAN)
.with_repetition(Repetition::OPTIONAL)
.build()
.unwrap()
}
ColumnType::Float => {
types::Type::primitive_type_builder(&column.get_name(), Type::DOUBLE)
.with_repetition(Repetition::OPTIONAL)
.build()
.unwrap()
}
}
}
}
#[derive(Clone, Serialize, Deserialize, Debug, Eq, PartialEq, Hash)]
pub struct Column {
name: String,
column_type: ColumnType,
column_index: usize,
}
impl Into<Field> for Column {
fn into(self) -> Field {
Field::new(
self.name.as_str(),
match self.column_type {
ColumnType::String => DataType::Utf8,
ColumnType::Int => DataType::Int64,
ColumnType::Timestamp => DataType::Timestamp(Microsecond, None),
ColumnType::Boolean => DataType::Boolean,
ColumnType::Decimal { .. } => {
DataType::Int64Decimal(self.column_type.target_scale() as usize)
}
ColumnType::Bytes => DataType::Binary,
ColumnType::HyperLogLog(_) => DataType::Binary,
ColumnType::Float => DataType::Float64,
},
false,
)
}
}
impl fmt::Display for Column {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
let column_type = match &self.column_type {
ColumnType::String => "STRING".to_string(),
ColumnType::Int => "INT".to_string(),
ColumnType::Timestamp => "TIMESTAMP".to_string(),
ColumnType::Boolean => "BOOLEAN".to_string(),
ColumnType::Decimal { scale, precision } => {
format!("DECIMAL({}, {})", precision, scale)
}
ColumnType::Bytes => "BYTES".to_string(),
ColumnType::HyperLogLog(HllFlavour::Airlift) => "HYPERLOGLOG".to_string(),
ColumnType::HyperLogLog(HllFlavour::ZetaSketch) => "HYPERLOGLOGPP".to_string(),
ColumnType::HyperLogLog(HllFlavour::Postgres) => "HLL_POSTGRES".to_string(),
ColumnType::HyperLogLog(HllFlavour::Snowflake) => "HLL_SNOWFLAKE".to_string(),
ColumnType::Float => "FLOAT".to_string(),
};
f.write_fmt(format_args!("{} {}", self.name, column_type))
}
}
#[derive(Clone, Copy, Serialize, Deserialize, Debug, Eq, PartialEq, Hash)]
pub enum ImportFormat {
CSV,
}
data_frame_from! {
#[derive(Clone, Serialize, Deserialize, Debug, Eq, PartialEq, Hash)]
pub struct Schema {
name: String
}
}
data_frame_from! {
#[derive(Clone, Serialize, Deserialize, Debug, Eq, PartialEq, Hash)]
pub struct Index {
name: String,
table_id: u64,
columns: Vec<Column>,
sort_key_size: u64
}
}
#[derive(Clone, Serialize, Deserialize, Debug, Eq, PartialEq, Hash)]
pub struct IndexDef {
pub name: String,
pub columns: Vec<String>,
}
data_frame_from! {
#[derive(Clone, Serialize, Deserialize, Debug, Eq, PartialEq)]
pub struct Partition {
index_id: u64,
parent_partition_id: Option<u64>,
min_value: Option<Row>,
max_value: Option<Row>,
active: bool,
#[serde(default)]
warmed_up: bool,
main_table_row_count: u64,
/// Not used or updated anymore.
#[serde(default)]
last_used: Option<DateTime<Utc>>
}
}
data_frame_from! {
#[derive(Clone, Serialize, Deserialize, Debug, Eq, PartialEq, Hash)]
pub struct Chunk {
partition_id: u64,
row_count: u64,
uploaded: bool,
active: bool,
/// Not used or updated anymore.
#[serde(default)]
last_used: Option<DateTime<Utc>>
}
}
#[derive(Clone, Serialize, Deserialize, Debug, Eq, PartialEq, Hash)]
pub struct WAL {
table_id: u64,
row_count: u64,
uploaded: bool,
}
#[derive(Clone, Serialize, Deserialize, Debug, Eq, PartialEq)]
pub struct IdRow<T: Clone> {
id: u64,
row: T,
}
impl<T: Clone> IdRow<T> {
pub fn new(id: u64, row: T) -> IdRow<T> {
IdRow { id, row }
}
pub fn get_id(&self) -> u64 {
self.id
}
pub fn get_row(&self) -> &T {
&self.row
}
pub fn into_row(self) -> T {
self.row
}
}
struct KeyVal {
key: Vec<u8>,
val: Vec<u8>,
}
struct BatchPipe<'a> {
db: &'a DB,
write_batch: WriteBatch,
events: Vec<MetaStoreEvent>,
}
impl<'a> BatchPipe<'a> {
fn new(db: &'a DB) -> BatchPipe<'a> {
BatchPipe {
db,
write_batch: WriteBatch::default(),
events: Vec::new(),
}
}
fn batch(&mut self) -> &mut WriteBatch {
&mut self.write_batch
}
fn add_event(&mut self, event: MetaStoreEvent) {
self.events.push(event);
}
fn batch_write_rows(self) -> Result<Vec<MetaStoreEvent>, CubeError> {
let db = self.db;
db.write(self.write_batch)?;
Ok(self.events)
}
}
#[derive(Clone)]
pub struct DbTableRef<'a> {
pub db: &'a DB,
pub snapshot: &'a Snapshot<'a>,
pub mem_seq: MemorySequence,
}
#[async_trait]
pub trait MetaStoreTable: Send + Sync {
type T: Serialize + Clone + Debug + 'static;
async fn all_rows(&self) -> Result<Vec<IdRow<Self::T>>, CubeError>;
async fn row_by_id_or_not_found(&self, id: u64) -> Result<IdRow<Self::T>, CubeError>;
async fn delete(&self, id: u64) -> Result<IdRow<Self::T>, CubeError>;
}
#[macro_export]
macro_rules! meta_store_table_impl {
($name: ident, $table: ty, $rocks_table: ident) => {
pub struct $name {
rocks_meta_store: RocksMetaStore,
}
impl $name {
fn table<'a>(db: DbTableRef<'a>) -> $rocks_table<'a> {
<$rocks_table>::new(db)
}
}
#[async_trait]
impl MetaStoreTable for $name {
type T = $table;
async fn all_rows(&self) -> Result<Vec<IdRow<Self::T>>, CubeError> {
self.rocks_meta_store
.read_operation(move |db_ref| Ok(Self::table(db_ref).all_rows()?))
.await
}
async fn row_by_id_or_not_found(&self, id: u64) -> Result<IdRow<Self::T>, CubeError> {
self.rocks_meta_store
.read_operation(move |db_ref| Ok(Self::table(db_ref).get_row_or_not_found(id)?))
.await
}
async fn delete(&self, id: u64) -> Result<IdRow<Self::T>, CubeError> {
self.rocks_meta_store
.write_operation(
move |db_ref, batch| Ok(Self::table(db_ref).delete(id, batch)?),
)
.await
}
}
};
}
meta_store_table_impl!(SchemaMetaStoreTable, Schema, SchemaRocksTable);
meta_store_table_impl!(ChunkMetaStoreTable, Chunk, ChunkRocksTable);
meta_store_table_impl!(IndexMetaStoreTable, Index, IndexRocksTable);
meta_store_table_impl!(PartitionMetaStoreTable, Partition, PartitionRocksTable);
meta_store_table_impl!(TableMetaStoreTable, Table, TableRocksTable);
#[cuberpc::service]
pub trait MetaStore: DIService + Send + Sync {
async fn wait_for_current_seq_to_sync(&self) -> Result<(), CubeError>;
fn schemas_table(&self) -> SchemaMetaStoreTable;
async fn create_schema(
&self,
schema_name: String,
if_not_exists: bool,
) -> Result<IdRow<Schema>, CubeError>;
async fn get_schemas(&self) -> Result<Vec<IdRow<Schema>>, CubeError>;
async fn get_schema_by_id(&self, schema_id: u64) -> Result<IdRow<Schema>, CubeError>;
//TODO Option
async fn get_schema_id(&self, schema_name: String) -> Result<u64, CubeError>;
//TODO Option
async fn get_schema(&self, schema_name: String) -> Result<IdRow<Schema>, CubeError>;
async fn rename_schema(
&self,
old_schema_name: String,
new_schema_name: String,
) -> Result<IdRow<Schema>, CubeError>;
async fn rename_schema_by_id(
&self,
schema_id: u64,
new_schema_name: String,
) -> Result<IdRow<Schema>, CubeError>;
async fn delete_schema(&self, schema_name: String) -> Result<(), CubeError>;
async fn delete_schema_by_id(&self, schema_id: u64) -> Result<(), CubeError>;
fn tables_table(&self) -> TableMetaStoreTable;
async fn create_table(
&self,
schema_name: String,
table_name: String,
columns: Vec<Column>,
locations: Option<Vec<String>>,
import_format: Option<ImportFormat>,
indexes: Vec<IndexDef>,
is_ready: bool,
) -> Result<IdRow<Table>, CubeError>;
async fn table_ready(&self, id: u64, is_ready: bool) -> Result<IdRow<Table>, CubeError>;
async fn get_table(
&self,
schema_name: String,
table_name: String,
) -> Result<IdRow<Table>, CubeError>;
async fn get_table_by_id(&self, table_id: u64) -> Result<IdRow<Table>, CubeError>;
async fn get_tables(&self) -> Result<Vec<IdRow<Table>>, CubeError>;
async fn get_tables_with_path(&self) -> Result<Arc<Vec<TablePath>>, CubeError>;
async fn drop_table(&self, table_id: u64) -> Result<IdRow<Table>, CubeError>;
fn partition_table(&self) -> PartitionMetaStoreTable;
async fn create_partition(&self, partition: Partition) -> Result<IdRow<Partition>, CubeError>;
async fn get_partition(&self, partition_id: u64) -> Result<IdRow<Partition>, CubeError>;
async fn get_partition_for_compaction(
&self,
partition_id: u64,
) -> Result<(IdRow<Partition>, IdRow<Index>), CubeError>;
async fn get_partition_chunk_sizes(&self, partition_id: u64) -> Result<u64, CubeError>;
async fn swap_active_partitions(
&self,
current_active: Vec<u64>,
new_active: Vec<u64>,
compacted_chunk_ids: Vec<u64>,
new_active_min_max: Vec<(u64, (Option<Row>, Option<Row>))>,
) -> Result<(), CubeError>;
async fn delete_partition(&self, partition_id: u64) -> Result<IdRow<Partition>, CubeError>;
async fn mark_partition_warmed_up(&self, partition_id: u64) -> Result<(), CubeError>;
fn index_table(&self) -> IndexMetaStoreTable;
async fn create_index(
&self,
schema_name: String,
table_name: String,
index_def: IndexDef,
) -> Result<IdRow<Index>, CubeError>;
async fn get_default_index(&self, table_id: u64) -> Result<IdRow<Index>, CubeError>;
async fn get_table_indexes(&self, table_id: u64) -> Result<Vec<IdRow<Index>>, CubeError>;
async fn get_active_partitions_by_index_id(
&self,
index_id: u64,
) -> Result<Vec<IdRow<Partition>>, CubeError>;
async fn get_index(&self, index_id: u64) -> Result<IdRow<Index>, CubeError>;
async fn get_active_partitions_and_chunks_by_index_id_for_select(
&self,
index_id: Vec<u64>,
) -> Result<Vec<Vec<(IdRow<Partition>, Vec<IdRow<Chunk>>)>>, CubeError>;
async fn get_warmup_partitions(
&self,
) -> Result<Vec<(PartitionName, Vec</*chunk_id*/ u64>)>, CubeError>;
fn chunks_table(&self) -> ChunkMetaStoreTable;
async fn create_chunk(
&self,
partition_id: u64,
row_count: usize,
) -> Result<IdRow<Chunk>, CubeError>;
async fn get_chunk(&self, chunk_id: u64) -> Result<IdRow<Chunk>, CubeError>;
async fn get_chunks_by_partition(
&self,
partition_id: u64,
include_inactive: bool,
) -> Result<Vec<IdRow<Chunk>>, CubeError>;
async fn chunk_uploaded(&self, chunk_id: u64) -> Result<IdRow<Chunk>, CubeError>;
async fn deactivate_chunk(&self, chunk_id: u64) -> Result<(), CubeError>;
async fn swap_chunks(
&self,
deactivate_ids: Vec<u64>,
uploaded_ids: Vec<u64>,
) -> Result<(), CubeError>;
async fn activate_wal(
&self,
wal_id_to_delete: u64,
uploaded_ids: Vec<u64>,
index_count: u64,
) -> Result<(), CubeError>;
async fn activate_chunks(
&self,
table_id: u64,
uploaded_chunk_ids: Vec<u64>,
) -> Result<(), CubeError>;
async fn delete_chunk(&self, chunk_id: u64) -> Result<IdRow<Chunk>, CubeError>;
async fn create_wal(&self, table_id: u64, row_count: usize) -> Result<IdRow<WAL>, CubeError>;
async fn get_wal(&self, wal_id: u64) -> Result<IdRow<WAL>, CubeError>;
async fn delete_wal(&self, wal_id: u64) -> Result<(), CubeError>;
async fn wal_uploaded(&self, wal_id: u64) -> Result<IdRow<WAL>, CubeError>;
async fn get_wals_for_table(&self, table_id: u64) -> Result<Vec<IdRow<WAL>>, CubeError>;
async fn add_job(&self, job: Job) -> Result<Option<IdRow<Job>>, CubeError>;
async fn get_job(&self, job_id: u64) -> Result<IdRow<Job>, CubeError>;
async fn delete_job(&self, job_id: u64) -> Result<IdRow<Job>, CubeError>;
async fn start_processing_job(
&self,
server_name: String,
) -> Result<Option<IdRow<Job>>, CubeError>;
async fn update_status(&self, job_id: u64, status: JobStatus) -> Result<IdRow<Job>, CubeError>;
async fn update_heart_beat(&self, job_id: u64) -> Result<IdRow<Job>, CubeError>;
async fn get_tables_with_indexes(
&self,
table_name: Vec<(String, String)>,
) -> Result<Vec<(IdRow<Schema>, IdRow<Table>, Vec<IdRow<Index>>)>, CubeError>;
async fn debug_dump(&self, out_path: String) -> Result<(), CubeError>;
}
/// Information required to produce partition name on remote fs.
#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
pub struct PartitionName {
pub parent_partition_id: Option<u64>,
pub partition_id: u64,
}
crate::di_service!(RocksMetaStore, [MetaStore]);
crate::di_service!(MetaStoreRpcClient, [MetaStore]);
#[derive(Clone, Debug)]
pub enum MetaStoreEvent {
Insert(TableId, u64),
Update(TableId, u64),
Delete(TableId, u64),
UpdateChunk(IdRow<Chunk>, IdRow<Chunk>),
UpdateIndex(IdRow<Index>, IdRow<Index>),
UpdateJob(IdRow<Job>, IdRow<Job>),
UpdatePartition(IdRow<Partition>, IdRow<Partition>),
UpdateSchema(IdRow<Schema>, IdRow<Schema>),
UpdateTable(IdRow<Table>, IdRow<Table>),
UpdateWAL(IdRow<WAL>, IdRow<WAL>),
DeleteChunk(IdRow<Chunk>),
DeleteIndex(IdRow<Index>),
DeleteJob(IdRow<Job>),
DeletePartition(IdRow<Partition>),
DeleteSchema(IdRow<Schema>),
DeleteTable(IdRow<Table>),
DeleteWAL(IdRow<WAL>),
}
type SecondaryKey = Vec<u8>;
type IndexId = u32;
#[derive(Debug, Clone, Serialize, Deserialize, Hash, Eq, PartialEq)]
pub enum RowKey {
Table(TableId, u64),
Sequence(TableId),
SecondaryIndex(IndexId, SecondaryKey, u64),
}
pub fn get_fixed_prefix() -> usize {
13
}
impl RowKey {
fn from_bytes(bytes: &[u8]) -> RowKey {
let mut reader = Cursor::new(bytes);
match reader.read_u8().unwrap() {
1 => RowKey::Table(TableId::from(reader.read_u32::<BigEndian>().unwrap()), {
// skip zero for fixed key padding
reader.read_u64::<BigEndian>().unwrap();
reader.read_u64::<BigEndian>().unwrap()
}),
2 => RowKey::Sequence(TableId::from(reader.read_u32::<BigEndian>().unwrap())),
3 => {
let table_id = IndexId::from(reader.read_u32::<BigEndian>().unwrap());
let mut secondary_key: SecondaryKey = SecondaryKey::new();
let sc_length = bytes.len() - 13;
for _i in 0..sc_length {
secondary_key.push(reader.read_u8().unwrap());
}
let row_id = reader.read_u64::<BigEndian>().unwrap();
RowKey::SecondaryIndex(table_id, secondary_key, row_id)
}
v => panic!("Unknown key prefix: {}", v),
}
}
fn to_bytes(&self) -> Vec<u8> {
let mut wtr = vec![];
match self {
RowKey::Table(table_id, row_id) => {
wtr.write_u8(1).unwrap();
wtr.write_u32::<BigEndian>(*table_id as u32).unwrap();
wtr.write_u64::<BigEndian>(0).unwrap();
wtr.write_u64::<BigEndian>(row_id.clone()).unwrap();
}
RowKey::Sequence(table_id) => {
wtr.write_u8(2).unwrap();
wtr.write_u32::<BigEndian>(*table_id as u32).unwrap();
}
RowKey::SecondaryIndex(index_id, secondary_key, row_id) => {
wtr.write_u8(3).unwrap();
wtr.write_u32::<BigEndian>(*index_id as IndexId).unwrap();
for &n in secondary_key {
wtr.write_u8(n).unwrap();
}
wtr.write_u64::<BigEndian>(row_id.clone()).unwrap();
}
}
wtr
}
}
macro_rules! enum_from_primitive_impl {
($name:ident, $( $variant:ident )*) => {
impl From<u32> for $name {
fn from(n: u32) -> Self {
$( if n == $name::$variant as u32 {
$name::$variant
} else )* {
panic!("Unknown {}: {}", stringify!($name), n);
}
}
}
};
}
macro_rules! enum_from_primitive {
(
$( #[$enum_attr:meta] )*
pub enum $name:ident {
$( $( $( #[$variant_attr:meta] )* $variant:ident ),+ = $discriminator:expr ),*
}
) => {
$( #[$enum_attr] )*
pub enum $name {
$( $( $( #[$variant_attr] )* $variant ),+ = $discriminator ),*
}
enum_from_primitive_impl! { $name, $( $( $variant )+ )* }
};
}
enum_from_primitive! {
#[derive(Copy, Clone, Eq, PartialEq, Debug, Serialize, Deserialize, Hash)]
pub enum TableId {
Schemas = 0x0100,
Tables = 0x0200,
Indexes = 0x0300,
Partitions = 0x0400,
Chunks = 0x0500,
WALs = 0x0600,
Jobs = 0x0700
}
}
#[derive(Clone)]
pub struct MemorySequence {
seq_store: Arc<Mutex<HashMap<TableId, u64>>>,
}
impl MemorySequence {
pub fn next_seq(&self, table_id: TableId, snapshot_value: u64) -> Result<u64, CubeError> {
let mut store = self.seq_store.lock()?;
let mut current = *store.entry(table_id).or_insert(snapshot_value);
current += 1;
store.insert(table_id, current);
Ok(current)
}
}
#[derive(Clone)]
pub struct RocksMetaStore {
pub db: Arc<RwLock<Arc<DB>>>,
seq_store: Arc<Mutex<HashMap<TableId, u64>>>,
listeners: Arc<RwLock<Vec<Sender<MetaStoreEvent>>>>,
remote_fs: Arc<dyn RemoteFs>,
last_checkpoint_time: Arc<RwLock<SystemTime>>,
write_notify: Arc<Notify>,
write_completed_notify: Arc<Notify>,
last_upload_seq: Arc<RwLock<u64>>,
last_check_seq: Arc<RwLock<u64>>,
upload_loop: Arc<WorkerLoop>,
config: Arc<dyn ConfigObj>,
cached_tables: Arc<Mutex<Option<Arc<Vec<TablePath>>>>>,
}
trait BaseRocksSecondaryIndex<T>: Debug {
fn index_key_by(&self, row: &T) -> Vec<u8>;
fn get_id(&self) -> u32;
fn key_hash(&self, row: &T) -> u64 {
let key_bytes = self.index_key_by(row);
self.hash_bytes(&key_bytes)
}
fn hash_bytes(&self, key_bytes: &Vec<u8>) -> u64 {
let mut hasher = DefaultHasher::new();
key_bytes.hash(&mut hasher);
hasher.finish()
}
fn is_unique(&self) -> bool;
}
trait RocksSecondaryIndex<T, K: Hash>: BaseRocksSecondaryIndex<T> {
fn typed_key_by(&self, row: &T) -> K;
fn key_to_bytes(&self, key: &K) -> Vec<u8>;
fn typed_key_hash(&self, row_key: &K) -> u64 {
let key_bytes = self.key_to_bytes(row_key);
self.hash_bytes(&key_bytes)
}
fn index_key_by(&self, row: &T) -> Vec<u8> {
self.key_to_bytes(&self.typed_key_by(row))
}
fn get_id(&self) -> u32;
fn is_unique(&self) -> bool;
}
impl<T, I> BaseRocksSecondaryIndex<T> for I