-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathlib.rs
More file actions
2364 lines (2108 loc) · 78 KB
/
lib.rs
File metadata and controls
2364 lines (2108 loc) · 78 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
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
mod types;
use std::sync::{Arc, LazyLock};
use std::time::Duration;
use fluss as fcore;
use fluss::PartitionId;
static RUNTIME: LazyLock<tokio::runtime::Runtime> = LazyLock::new(|| {
tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()
.unwrap()
});
#[cxx::bridge(namespace = "fluss::ffi")]
mod ffi {
struct HashMapValue {
key: String,
value: String,
}
struct FfiConfig {
bootstrap_servers: String,
writer_request_max_size: i32,
writer_acks: String,
writer_retries: i32,
writer_batch_size: i32,
writer_bucket_no_key_assigner: String,
scanner_remote_log_prefetch_num: usize,
remote_file_download_thread_num: usize,
scanner_remote_log_read_concurrency: usize,
scanner_log_max_poll_records: usize,
scanner_log_fetch_max_bytes: i32,
scanner_log_fetch_min_bytes: i32,
scanner_log_fetch_wait_max_time_ms: i32,
scanner_log_fetch_max_bytes_for_bucket: i32,
writer_batch_timeout_ms: i64,
connect_timeout_ms: u64,
request_timeout_ms: u64,
security_protocol: String,
security_sasl_mechanism: String,
security_sasl_username: String,
security_sasl_password: String,
}
struct FfiResult {
error_code: i32,
error_message: String,
}
struct FfiTablePath {
database_name: String,
table_name: String,
}
struct FfiColumn {
name: String,
data_type: i32,
comment: String,
precision: i32,
scale: i32,
}
struct FfiSchema {
columns: Vec<FfiColumn>,
primary_keys: Vec<String>,
}
struct FfiTableDescriptor {
schema: FfiSchema,
partition_keys: Vec<String>,
bucket_count: i32,
bucket_keys: Vec<String>,
properties: Vec<HashMapValue>,
custom_properties: Vec<HashMapValue>,
comment: String,
}
struct FfiTableInfo {
table_id: i64,
schema_id: i32,
table_path: FfiTablePath,
created_time: i64,
modified_time: i64,
primary_keys: Vec<String>,
bucket_keys: Vec<String>,
partition_keys: Vec<String>,
num_buckets: i32,
has_primary_key: bool,
is_partitioned: bool,
properties: Vec<HashMapValue>,
custom_properties: Vec<HashMapValue>,
comment: String,
schema: FfiSchema,
}
struct FfiTableInfoResult {
result: FfiResult,
table_info: FfiTableInfo,
}
// NOTE: FfiDatum, FfiGenericRow, FfiScanRecord, FfiScanRecords, FfiScanRecordsResult
// have been replaced by opaque types below (ScanResultInner, GenericRowInner, LookupResultInner).
struct FfiArrowRecordBatch {
array_ptr: usize,
schema_ptr: usize,
table_id: i64,
partition_id: i64,
bucket_id: i32,
base_offset: i64,
}
struct FfiArrowRecordBatches {
batches: Vec<FfiArrowRecordBatch>,
}
struct FfiArrowRecordBatchesResult {
result: FfiResult,
arrow_batches: FfiArrowRecordBatches,
}
struct FfiLakeSnapshot {
snapshot_id: i64,
bucket_offsets: Vec<FfiBucketOffset>,
}
struct FfiBucketOffset {
table_id: i64,
partition_id: i64,
bucket_id: i32,
offset: i64,
}
struct FfiOffsetQuery {
offset_type: i32,
timestamp: i64,
}
struct FfiBucketInfo {
table_id: i64,
bucket_id: i32,
has_partition_id: bool,
partition_id: i64,
record_count: usize,
}
struct FfiBucketSubscription {
bucket_id: i32,
offset: i64,
}
struct FfiPartitionBucketSubscription {
partition_id: i64,
bucket_id: i32,
offset: i64,
}
struct FfiBucketOffsetPair {
bucket_id: i32,
offset: i64,
}
struct FfiListOffsetsResult {
result: FfiResult,
bucket_offsets: Vec<FfiBucketOffsetPair>,
}
// NOTE: FfiLookupResult replaced by opaque LookupResultInner below.
struct FfiLakeSnapshotResult {
result: FfiResult,
lake_snapshot: FfiLakeSnapshot,
}
struct FfiPartitionKeyValue {
key: String,
value: String,
}
struct FfiPartitionInfo {
partition_id: i64,
partition_name: String,
}
struct FfiListPartitionInfosResult {
result: FfiResult,
partition_infos: Vec<FfiPartitionInfo>,
}
struct FfiDatabaseDescriptor {
comment: String,
properties: Vec<HashMapValue>,
}
struct FfiDatabaseInfo {
database_name: String,
comment: String,
properties: Vec<HashMapValue>,
created_time: i64,
modified_time: i64,
}
struct FfiDatabaseInfoResult {
result: FfiResult,
database_info: FfiDatabaseInfo,
}
struct FfiListDatabasesResult {
result: FfiResult,
database_names: Vec<String>,
}
struct FfiListTablesResult {
result: FfiResult,
table_names: Vec<String>,
}
struct FfiBoolResult {
result: FfiResult,
value: bool,
}
struct FfiServerNode {
node_id: i32,
host: String,
port: u32,
server_type: String,
uid: String,
}
struct FfiServerNodesResult {
result: FfiResult,
server_nodes: Vec<FfiServerNode>,
}
struct FfiPtrResult {
result: FfiResult,
ptr: usize,
}
extern "Rust" {
type Connection;
type Admin;
type Table;
type AppendWriter;
type WriteResult;
type LogScanner;
type UpsertWriter;
type Lookuper;
// Opaque types for optimized FFI
type ScanResultInner;
type GenericRowInner;
type LookupResultInner;
// Connection
fn new_connection(config: &FfiConfig) -> FfiPtrResult;
unsafe fn delete_connection(conn: *mut Connection);
fn get_admin(self: &Connection) -> FfiPtrResult;
fn get_table(self: &Connection, table_path: &FfiTablePath) -> FfiPtrResult;
// Admin
unsafe fn delete_admin(admin: *mut Admin);
fn create_table(
self: &Admin,
table_path: &FfiTablePath,
descriptor: &FfiTableDescriptor,
ignore_if_exists: bool,
) -> FfiResult;
fn drop_table(
self: &Admin,
table_path: &FfiTablePath,
ignore_if_not_exists: bool,
) -> FfiResult;
fn get_table_info(self: &Admin, table_path: &FfiTablePath) -> FfiTableInfoResult;
fn get_latest_lake_snapshot(
self: &Admin,
table_path: &FfiTablePath,
) -> FfiLakeSnapshotResult;
fn list_offsets(
self: &Admin,
table_path: &FfiTablePath,
bucket_ids: Vec<i32>,
offset_query: &FfiOffsetQuery,
) -> FfiListOffsetsResult;
fn list_partition_offsets(
self: &Admin,
table_path: &FfiTablePath,
partition_name: String,
bucket_ids: Vec<i32>,
offset_query: &FfiOffsetQuery,
) -> FfiListOffsetsResult;
fn list_partition_infos(
self: &Admin,
table_path: &FfiTablePath,
) -> FfiListPartitionInfosResult;
fn list_partition_infos_with_spec(
self: &Admin,
table_path: &FfiTablePath,
partition_spec: Vec<FfiPartitionKeyValue>,
) -> FfiListPartitionInfosResult;
fn create_partition(
self: &Admin,
table_path: &FfiTablePath,
partition_spec: Vec<FfiPartitionKeyValue>,
ignore_if_exists: bool,
) -> FfiResult;
fn drop_partition(
self: &Admin,
table_path: &FfiTablePath,
partition_spec: Vec<FfiPartitionKeyValue>,
ignore_if_not_exists: bool,
) -> FfiResult;
fn create_database(
self: &Admin,
database_name: &str,
descriptor: &FfiDatabaseDescriptor,
ignore_if_exists: bool,
) -> FfiResult;
fn drop_database(
self: &Admin,
database_name: &str,
ignore_if_not_exists: bool,
cascade: bool,
) -> FfiResult;
fn list_databases(self: &Admin) -> FfiListDatabasesResult;
fn database_exists(self: &Admin, database_name: &str) -> FfiBoolResult;
fn get_database_info(self: &Admin, database_name: &str) -> FfiDatabaseInfoResult;
fn list_tables(self: &Admin, database_name: &str) -> FfiListTablesResult;
fn table_exists(self: &Admin, table_path: &FfiTablePath) -> FfiBoolResult;
fn get_server_nodes(self: &Admin) -> FfiServerNodesResult;
// Table
unsafe fn delete_table(table: *mut Table);
fn new_append_writer(self: &Table) -> FfiPtrResult;
fn create_scanner(self: &Table, column_indices: Vec<usize>, batch: bool) -> FfiPtrResult;
fn get_table_info_from_table(self: &Table) -> FfiTableInfo;
fn get_table_path(self: &Table) -> FfiTablePath;
fn has_primary_key(self: &Table) -> bool;
fn create_upsert_writer(self: &Table, column_indices: Vec<usize>) -> FfiPtrResult;
fn new_lookuper(self: &Table) -> FfiPtrResult;
// GenericRowInner — opaque row for writes
fn new_generic_row(field_count: usize) -> Box<GenericRowInner>;
fn gr_reset(self: &mut GenericRowInner);
fn gr_set_null(self: &mut GenericRowInner, idx: usize);
fn gr_set_bool(self: &mut GenericRowInner, idx: usize, val: bool);
fn gr_set_i32(self: &mut GenericRowInner, idx: usize, val: i32);
fn gr_set_i64(self: &mut GenericRowInner, idx: usize, val: i64);
fn gr_set_f32(self: &mut GenericRowInner, idx: usize, val: f32);
fn gr_set_f64(self: &mut GenericRowInner, idx: usize, val: f64);
fn gr_set_str(self: &mut GenericRowInner, idx: usize, val: &str);
fn gr_set_bytes(self: &mut GenericRowInner, idx: usize, val: &[u8]);
fn gr_set_date(self: &mut GenericRowInner, idx: usize, days: i32);
fn gr_set_time(self: &mut GenericRowInner, idx: usize, millis: i32);
fn gr_set_ts_ntz(self: &mut GenericRowInner, idx: usize, millis: i64, nanos: i32);
fn gr_set_ts_ltz(self: &mut GenericRowInner, idx: usize, millis: i64, nanos: i32);
fn gr_set_decimal_str(self: &mut GenericRowInner, idx: usize, val: &str);
// AppendWriter
unsafe fn delete_append_writer(writer: *mut AppendWriter);
fn append(self: &mut AppendWriter, row: &GenericRowInner) -> FfiPtrResult;
fn append_arrow_batch(
self: &mut AppendWriter,
array_ptr: usize,
schema_ptr: usize,
) -> FfiPtrResult;
fn flush(self: &mut AppendWriter) -> FfiResult;
// WriteResult
unsafe fn delete_write_result(wr: *mut WriteResult);
fn wait(self: &mut WriteResult) -> FfiResult;
// UpsertWriter
unsafe fn delete_upsert_writer(writer: *mut UpsertWriter);
fn upsert(self: &mut UpsertWriter, row: &GenericRowInner) -> FfiPtrResult;
fn delete_row(self: &mut UpsertWriter, row: &GenericRowInner) -> FfiPtrResult;
fn upsert_flush(self: &mut UpsertWriter) -> FfiResult;
// Lookuper
unsafe fn delete_lookuper(lookuper: *mut Lookuper);
fn lookup(self: &mut Lookuper, pk_row: &GenericRowInner) -> Box<LookupResultInner>;
// LookupResultInner accessors
fn lv_has_error(self: &LookupResultInner) -> bool;
fn lv_error_code(self: &LookupResultInner) -> i32;
fn lv_error_message(self: &LookupResultInner) -> &str;
fn lv_found(self: &LookupResultInner) -> bool;
fn lv_field_count(self: &LookupResultInner) -> usize;
fn lv_column_name(self: &LookupResultInner, field: usize) -> Result<&str>;
fn lv_column_type(self: &LookupResultInner, field: usize) -> Result<i32>;
fn lv_is_null(self: &LookupResultInner, field: usize) -> Result<bool>;
fn lv_get_bool(self: &LookupResultInner, field: usize) -> Result<bool>;
fn lv_get_i32(self: &LookupResultInner, field: usize) -> Result<i32>;
fn lv_get_i64(self: &LookupResultInner, field: usize) -> Result<i64>;
fn lv_get_f32(self: &LookupResultInner, field: usize) -> Result<f32>;
fn lv_get_f64(self: &LookupResultInner, field: usize) -> Result<f64>;
fn lv_get_str(self: &LookupResultInner, field: usize) -> Result<&str>;
fn lv_get_bytes(self: &LookupResultInner, field: usize) -> Result<&[u8]>;
fn lv_get_date_days(self: &LookupResultInner, field: usize) -> Result<i32>;
fn lv_get_time_millis(self: &LookupResultInner, field: usize) -> Result<i32>;
fn lv_get_ts_millis(self: &LookupResultInner, field: usize) -> Result<i64>;
fn lv_get_ts_nanos(self: &LookupResultInner, field: usize) -> Result<i32>;
fn lv_is_ts_ltz(self: &LookupResultInner, field: usize) -> Result<bool>;
fn lv_get_decimal_str(self: &LookupResultInner, field: usize) -> Result<String>;
// LogScanner
unsafe fn delete_log_scanner(scanner: *mut LogScanner);
fn subscribe(self: &LogScanner, bucket_id: i32, start_offset: i64) -> FfiResult;
fn subscribe_buckets(
self: &LogScanner,
subscriptions: Vec<FfiBucketSubscription>,
) -> FfiResult;
fn subscribe_partition(
self: &LogScanner,
partition_id: i64,
bucket_id: i32,
start_offset: i64,
) -> FfiResult;
fn subscribe_partition_buckets(
self: &LogScanner,
subscriptions: Vec<FfiPartitionBucketSubscription>,
) -> FfiResult;
fn unsubscribe(self: &LogScanner, bucket_id: i32) -> FfiResult;
fn unsubscribe_partition(self: &LogScanner, partition_id: i64, bucket_id: i32)
-> FfiResult;
fn poll(self: &LogScanner, timeout_ms: i64) -> Box<ScanResultInner>;
fn poll_record_batch(self: &LogScanner, timeout_ms: i64) -> FfiArrowRecordBatchesResult;
fn free_arrow_ffi_structures(array_ptr: usize, schema_ptr: usize);
// ScanResultInner accessors
fn sv_has_error(self: &ScanResultInner) -> bool;
fn sv_error_code(self: &ScanResultInner) -> i32;
fn sv_error_message(self: &ScanResultInner) -> &str;
fn sv_record_count(self: &ScanResultInner) -> usize;
fn sv_column_count(self: &ScanResultInner) -> usize;
fn sv_column_name(self: &ScanResultInner, field: usize) -> Result<&str>;
fn sv_column_type(self: &ScanResultInner, field: usize) -> Result<i32>;
fn sv_offset(self: &ScanResultInner, bucket: usize, rec: usize) -> i64;
fn sv_timestamp(self: &ScanResultInner, bucket: usize, rec: usize) -> i64;
fn sv_change_type(self: &ScanResultInner, bucket: usize, rec: usize) -> i32;
fn sv_field_count(self: &ScanResultInner) -> usize;
fn sv_is_null(
self: &ScanResultInner,
bucket: usize,
rec: usize,
field: usize,
) -> Result<bool>;
fn sv_get_bool(
self: &ScanResultInner,
bucket: usize,
rec: usize,
field: usize,
) -> Result<bool>;
fn sv_get_i32(
self: &ScanResultInner,
bucket: usize,
rec: usize,
field: usize,
) -> Result<i32>;
fn sv_get_i64(
self: &ScanResultInner,
bucket: usize,
rec: usize,
field: usize,
) -> Result<i64>;
fn sv_get_f32(
self: &ScanResultInner,
bucket: usize,
rec: usize,
field: usize,
) -> Result<f32>;
fn sv_get_f64(
self: &ScanResultInner,
bucket: usize,
rec: usize,
field: usize,
) -> Result<f64>;
fn sv_get_str(
self: &ScanResultInner,
bucket: usize,
rec: usize,
field: usize,
) -> Result<&str>;
fn sv_get_bytes(
self: &ScanResultInner,
bucket: usize,
rec: usize,
field: usize,
) -> Result<&[u8]>;
fn sv_get_date_days(
self: &ScanResultInner,
bucket: usize,
rec: usize,
field: usize,
) -> Result<i32>;
fn sv_get_time_millis(
self: &ScanResultInner,
bucket: usize,
rec: usize,
field: usize,
) -> Result<i32>;
fn sv_get_ts_millis(
self: &ScanResultInner,
bucket: usize,
rec: usize,
field: usize,
) -> Result<i64>;
fn sv_get_ts_nanos(
self: &ScanResultInner,
bucket: usize,
rec: usize,
field: usize,
) -> Result<i32>;
fn sv_is_ts_ltz(
self: &ScanResultInner,
bucket: usize,
rec: usize,
field: usize,
) -> Result<bool>;
fn sv_get_decimal_str(
self: &ScanResultInner,
bucket: usize,
rec: usize,
field: usize,
) -> Result<String>;
fn sv_bucket_infos(self: &ScanResultInner) -> &Vec<FfiBucketInfo>;
}
}
pub struct Connection {
inner: Arc<fcore::client::FlussConnection>,
}
pub struct Admin {
inner: fcore::client::FlussAdmin,
}
pub struct Table {
connection: Arc<fcore::client::FlussConnection>,
metadata: Arc<fcore::client::Metadata>,
table_info: fcore::metadata::TableInfo,
table_path: fcore::metadata::TablePath,
has_pk: bool,
}
pub struct AppendWriter {
inner: fcore::client::AppendWriter,
table_info: fcore::metadata::TableInfo,
}
pub struct WriteResult {
inner: Option<fcore::client::WriteResultFuture>,
}
enum ScannerKind {
Record(fcore::client::LogScanner),
Batch(fcore::client::RecordBatchLogScanner),
}
pub struct LogScanner {
scanner: ScannerKind,
/// Fluss columns matching the projected Arrow fields (1:1 by index).
/// For non-projected scanners this is the full table schema columns.
projected_columns: Vec<fcore::metadata::Column>,
}
pub struct UpsertWriter {
inner: fcore::client::UpsertWriter,
table_info: fcore::metadata::TableInfo,
}
pub struct Lookuper {
inner: fcore::client::Lookuper,
table_info: fcore::metadata::TableInfo,
}
/// Error code for client-side errors that did not originate from the server API protocol.
/// Must be non-zero so that CPP `Result::Ok()` (which checks `error_code == 0`) correctly
/// detects client-side errors as failures. The value -2 is outside the server API error
/// code range (-1 .. 57+), so it will never collide with current or future API codes.
const CLIENT_ERROR_CODE: i32 = -2;
fn ok_result() -> ffi::FfiResult {
ffi::FfiResult {
error_code: 0,
error_message: String::new(),
}
}
fn err_result(code: i32, msg: String) -> ffi::FfiResult {
ffi::FfiResult {
error_code: code,
error_message: msg,
}
}
/// Create a client-side error result (not from server API).
fn client_err(msg: String) -> ffi::FfiResult {
err_result(CLIENT_ERROR_CODE, msg)
}
/// Convert a core Error to FfiResult.
/// `FlussAPIError` variants carry the server protocol error code directly.
/// All other error kinds are client-side and use CLIENT_ERROR_CODE.
fn err_from_core_error(e: &fcore::error::Error) -> ffi::FfiResult {
use fcore::error::Error;
match e {
Error::FlussAPIError { api_error } => err_result(api_error.code, api_error.message.clone()),
_ => client_err(e.to_string()),
}
}
fn ok_ptr(ptr: usize) -> ffi::FfiPtrResult {
ffi::FfiPtrResult {
result: ok_result(),
ptr,
}
}
fn client_err_ptr(msg: String) -> ffi::FfiPtrResult {
ffi::FfiPtrResult {
result: client_err(msg),
ptr: 0usize,
}
}
fn err_ptr_from_core(e: &fcore::error::Error) -> ffi::FfiPtrResult {
ffi::FfiPtrResult {
result: err_from_core_error(e),
ptr: 0usize,
}
}
// Connection implementation
fn new_connection(config: &ffi::FfiConfig) -> ffi::FfiPtrResult {
let assigner_type = match config
.writer_bucket_no_key_assigner
.parse::<fluss::config::NoKeyAssigner>()
{
Ok(v) => v,
Err(e) => return client_err_ptr(format!("Invalid bucket assigner type: {e}")),
};
let config_core = fluss::config::Config {
bootstrap_servers: config.bootstrap_servers.to_string(),
writer_request_max_size: config.writer_request_max_size,
writer_acks: config.writer_acks.to_string(),
writer_retries: config.writer_retries,
writer_batch_size: config.writer_batch_size,
writer_batch_timeout_ms: config.writer_batch_timeout_ms,
writer_bucket_no_key_assigner: assigner_type,
scanner_remote_log_prefetch_num: config.scanner_remote_log_prefetch_num,
remote_file_download_thread_num: config.remote_file_download_thread_num,
scanner_remote_log_read_concurrency: config.scanner_remote_log_read_concurrency,
scanner_log_max_poll_records: config.scanner_log_max_poll_records,
scanner_log_fetch_max_bytes: config.scanner_log_fetch_max_bytes,
scanner_log_fetch_min_bytes: config.scanner_log_fetch_min_bytes,
scanner_log_fetch_wait_max_time_ms: config.scanner_log_fetch_wait_max_time_ms,
scanner_log_fetch_max_bytes_for_bucket: config.scanner_log_fetch_max_bytes_for_bucket,
connect_timeout_ms: config.connect_timeout_ms,
request_timeout_ms: config.request_timeout_ms,
security_protocol: config.security_protocol.to_string(),
security_sasl_mechanism: config.security_sasl_mechanism.to_string(),
security_sasl_username: config.security_sasl_username.to_string(),
security_sasl_password: config.security_sasl_password.to_string(),
};
let conn = RUNTIME.block_on(async { fcore::client::FlussConnection::new(config_core).await });
match conn {
Ok(c) => {
let ptr = Box::into_raw(Box::new(Connection { inner: Arc::new(c) }));
ok_ptr(ptr as usize)
}
Err(e) => err_ptr_from_core(&e),
}
}
unsafe fn delete_connection(conn: *mut Connection) {
if !conn.is_null() {
unsafe {
drop(Box::from_raw(conn));
}
}
}
impl Connection {
fn get_admin(&self) -> ffi::FfiPtrResult {
let admin_result = RUNTIME.block_on(async { self.inner.get_admin().await });
match admin_result {
Ok(admin) => {
let ptr = Box::into_raw(Box::new(Admin { inner: admin }));
ok_ptr(ptr as usize)
}
Err(e) => err_ptr_from_core(&e),
}
}
fn get_table(&self, table_path: &ffi::FfiTablePath) -> ffi::FfiPtrResult {
let path = fcore::metadata::TablePath::new(
table_path.database_name.clone(),
table_path.table_name.clone(),
);
let table_result = RUNTIME.block_on(async { self.inner.get_table(&path).await });
match table_result {
Ok(t) => {
let ptr = Box::into_raw(Box::new(Table {
connection: self.inner.clone(),
metadata: t.metadata().clone(),
table_info: t.get_table_info().clone(),
table_path: t.table_path().clone(),
has_pk: t.has_primary_key(),
}));
ok_ptr(ptr as usize)
}
Err(e) => err_ptr_from_core(&e),
}
}
}
// Admin implementation
unsafe fn delete_admin(admin: *mut Admin) {
if !admin.is_null() {
unsafe {
drop(Box::from_raw(admin));
}
}
}
impl Admin {
fn create_table(
&self,
table_path: &ffi::FfiTablePath,
descriptor: &ffi::FfiTableDescriptor,
ignore_if_exists: bool,
) -> ffi::FfiResult {
let path = fcore::metadata::TablePath::new(
table_path.database_name.clone(),
table_path.table_name.clone(),
);
let core_descriptor = match types::ffi_descriptor_to_core(descriptor) {
Ok(d) => d,
Err(e) => return client_err(e.to_string()),
};
let result = RUNTIME.block_on(async {
self.inner
.create_table(&path, &core_descriptor, ignore_if_exists)
.await
});
match result {
Ok(_) => ok_result(),
Err(e) => err_from_core_error(&e),
}
}
fn drop_table(
&self,
table_path: &ffi::FfiTablePath,
ignore_if_not_exists: bool,
) -> ffi::FfiResult {
let path = fcore::metadata::TablePath::new(
table_path.database_name.clone(),
table_path.table_name.clone(),
);
let result =
RUNTIME.block_on(async { self.inner.drop_table(&path, ignore_if_not_exists).await });
match result {
Ok(_) => ok_result(),
Err(e) => err_from_core_error(&e),
}
}
fn get_table_info(&self, table_path: &ffi::FfiTablePath) -> ffi::FfiTableInfoResult {
let path = fcore::metadata::TablePath::new(
table_path.database_name.clone(),
table_path.table_name.clone(),
);
let result = RUNTIME.block_on(async { self.inner.get_table_info(&path).await });
match result {
Ok(info) => ffi::FfiTableInfoResult {
result: ok_result(),
table_info: types::core_table_info_to_ffi(&info),
},
Err(e) => ffi::FfiTableInfoResult {
result: err_from_core_error(&e),
table_info: types::empty_table_info(),
},
}
}
fn get_latest_lake_snapshot(
&self,
table_path: &ffi::FfiTablePath,
) -> ffi::FfiLakeSnapshotResult {
let path = fcore::metadata::TablePath::new(
table_path.database_name.clone(),
table_path.table_name.clone(),
);
let result = RUNTIME.block_on(async { self.inner.get_latest_lake_snapshot(&path).await });
match result {
Ok(snapshot) => ffi::FfiLakeSnapshotResult {
result: ok_result(),
lake_snapshot: types::core_lake_snapshot_to_ffi(&snapshot),
},
Err(e) => ffi::FfiLakeSnapshotResult {
result: err_from_core_error(&e),
lake_snapshot: ffi::FfiLakeSnapshot {
snapshot_id: -1,
bucket_offsets: vec![],
},
},
}
}
// Helper function for common list offsets functionality
fn do_list_offsets(
&self,
table_path: &ffi::FfiTablePath,
partition_name: Option<&str>,
bucket_ids: Vec<i32>,
offset_query: &ffi::FfiOffsetQuery,
) -> ffi::FfiListOffsetsResult {
use fcore::rpc::message::OffsetSpec;
let path = fcore::metadata::TablePath::new(
table_path.database_name.clone(),
table_path.table_name.clone(),
);
let offset_spec = match offset_query.offset_type {
0 => OffsetSpec::Earliest,
1 => OffsetSpec::Latest,
2 => OffsetSpec::Timestamp(offset_query.timestamp),
_ => {
return ffi::FfiListOffsetsResult {
result: client_err(format!(
"Invalid offset_type: {}",
offset_query.offset_type
)),
bucket_offsets: vec![],
};
}
};
let result = RUNTIME.block_on(async {
if let Some(part_name) = partition_name {
self.inner
.list_partition_offsets(&path, part_name, &bucket_ids, offset_spec)
.await
} else {
self.inner
.list_offsets(&path, &bucket_ids, offset_spec)
.await
}
});
match result {
Ok(offsets) => {
let bucket_offsets: Vec<ffi::FfiBucketOffsetPair> = offsets
.into_iter()
.map(|(bucket_id, offset)| ffi::FfiBucketOffsetPair { bucket_id, offset })
.collect();
ffi::FfiListOffsetsResult {
result: ok_result(),
bucket_offsets,
}
}
Err(e) => ffi::FfiListOffsetsResult {
result: err_from_core_error(&e),
bucket_offsets: vec![],
},
}
}
fn list_offsets(
&self,
table_path: &ffi::FfiTablePath,
bucket_ids: Vec<i32>,
offset_query: &ffi::FfiOffsetQuery,
) -> ffi::FfiListOffsetsResult {
self.do_list_offsets(table_path, None, bucket_ids, offset_query)
}
fn list_partition_offsets(
&self,
table_path: &ffi::FfiTablePath,
partition_name: String,
bucket_ids: Vec<i32>,
offset_query: &ffi::FfiOffsetQuery,
) -> ffi::FfiListOffsetsResult {
self.do_list_offsets(table_path, Some(&partition_name), bucket_ids, offset_query)
}
fn list_partition_infos(
&self,
table_path: &ffi::FfiTablePath,
) -> ffi::FfiListPartitionInfosResult {
self.do_list_partition_infos(table_path, None)
}
fn list_partition_infos_with_spec(
&self,
table_path: &ffi::FfiTablePath,
partition_spec: Vec<ffi::FfiPartitionKeyValue>,
) -> ffi::FfiListPartitionInfosResult {
let spec_map: std::collections::HashMap<String, String> = partition_spec
.into_iter()
.map(|kv| (kv.key, kv.value))
.collect();
let spec = fcore::metadata::PartitionSpec::new(spec_map);
self.do_list_partition_infos(table_path, Some(&spec))
}
fn create_partition(
&self,
table_path: &ffi::FfiTablePath,
partition_spec: Vec<ffi::FfiPartitionKeyValue>,
ignore_if_exists: bool,
) -> ffi::FfiResult {
let path = fcore::metadata::TablePath::new(
table_path.database_name.clone(),
table_path.table_name.clone(),
);
let spec_map: std::collections::HashMap<String, String> = partition_spec
.into_iter()
.map(|kv| (kv.key, kv.value))
.collect();
let partition_spec = fcore::metadata::PartitionSpec::new(spec_map);
let result = RUNTIME.block_on(async {
self.inner
.create_partition(&path, &partition_spec, ignore_if_exists)
.await
});
match result {
Ok(_) => ok_result(),
Err(e) => err_from_core_error(&e),
}
}
fn drop_partition(
&self,
table_path: &ffi::FfiTablePath,
partition_spec: Vec<ffi::FfiPartitionKeyValue>,
ignore_if_not_exists: bool,
) -> ffi::FfiResult {
let path = fcore::metadata::TablePath::new(
table_path.database_name.clone(),
table_path.table_name.clone(),
);
let spec_map: std::collections::HashMap<String, String> = partition_spec
.into_iter()
.map(|kv| (kv.key, kv.value))
.collect();
let partition_spec = fcore::metadata::PartitionSpec::new(spec_map);
let result = RUNTIME.block_on(async {
self.inner
.drop_partition(&path, &partition_spec, ignore_if_not_exists)
.await
});
match result {
Ok(_) => ok_result(),
Err(e) => err_from_core_error(&e),
}
}