-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathdata_store_service_client.cpp
More file actions
5272 lines (4781 loc) · 193 KB
/
data_store_service_client.cpp
File metadata and controls
5272 lines (4781 loc) · 193 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
/**
* Copyright (C) 2025 EloqData Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under either of the following two licenses:
* 1. GNU Affero General Public License, version 3, as published by the Free
* Software Foundation.
* 2. GNU General Public License as published by the Free Software
* Foundation; version 2 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License or GNU General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License
* and GNU General Public License V2 along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*
*/
#include "data_store_service_client.h"
#include <glog/logging.h>
#include <boost/lexical_cast.hpp>
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <boost/uuid/uuid_io.hpp>
#include <cstdint>
#include <memory>
#include <random>
#include <string>
#include <string_view>
#include <unordered_map>
#include <utility>
#include <vector>
#include "cc_req_misc.h"
#include "data_store_service_client_closure.h"
#include "data_store_service_config.h"
#include "data_store_service_scanner.h"
#include "eloq_data_store_service/object_pool.h" // ObjectPool
#include "eloq_data_store_service/thread_worker_pool.h"
#include "metrics.h"
#include "sharder.h"
#include "store_util.h" // host_to_big_endian
#include "tx_key.h"
#include "tx_service/include/cc/local_cc_shards.h"
#include "tx_service/include/error_messages.h"
#include "tx_service/include/sequences/sequences.h"
namespace EloqDS
{
thread_local ObjectPool<BatchWriteRecordsClosure> batch_write_closure_pool_;
thread_local ObjectPool<FlushDataClosure> flush_data_closure_pool_;
thread_local ObjectPool<DeleteRangeClosure> delete_range_closure_pool_;
thread_local ObjectPool<ReadClosure> read_closure_pool_;
thread_local ObjectPool<DropTableClosure> drop_table_closure_pool_;
thread_local ObjectPool<ScanNextClosure> scan_next_closure_pool_;
thread_local ObjectPool<CreateSnapshotForBackupClosure>
create_snapshot_for_backup_closure_pool_;
thread_local ObjectPool<CreateSnapshotForBackupCallbackData>
create_snapshot_for_backup_callback_data_pool_;
thread_local ObjectPool<SyncCallbackData> sync_callback_data_pool_;
thread_local ObjectPool<FetchTableCallbackData> fetch_table_callback_data_pool_;
thread_local ObjectPool<FetchDatabaseCallbackData> fetch_db_callback_data_pool_;
thread_local ObjectPool<FetchAllDatabaseCallbackData>
fetch_all_dbs_callback_data_pool_;
thread_local ObjectPool<DiscoverAllTableNamesCallbackData>
discover_all_tables_callback_data_pool_;
thread_local ObjectPool<SyncPutAllData> sync_putall_data_pool_;
thread_local ObjectPool<SyncConcurrentRequest> sync_concurrent_request_pool_;
thread_local ObjectPool<PartitionFlushState> partition_flush_state_pool_;
thread_local ObjectPool<PartitionCallbackData> partition_callback_data_pool_;
static const uint64_t MAX_WRITE_BATCH_SIZE = 64 * 1024 * 1024; // 64MB
static const std::string_view kv_table_catalogs_name("table_catalogs");
static const std::string_view kv_database_catalogs_name("db_catalogs");
static const std::string_view kv_range_table_name("table_ranges");
static const std::string_view kv_range_slices_table_name("table_range_slices");
static const std::string_view kv_last_range_id_name(
"table_last_range_partition_id");
static const std::string_view kv_table_statistics_name("table_statistics");
static const std::string_view kv_table_statistics_version_name(
"table_statistics_version");
static const std::string_view kv_mvcc_archive_name("mvcc_archives");
static const std::string_view KEY_SEPARATOR("\\");
DataStoreServiceClient::~DataStoreServiceClient()
{
upsert_table_worker_.Shutdown();
}
/**
* @brief Configures the data store service client with cluster manager
* information.
*
* Initializes the client with cluster configuration including node hostnames
* and ports. Logs all node information for debugging purposes and stores the
* cluster manager reference for future use.
*
* @param cluster_manager Reference to the cluster manager containing shard and
* node information.
*/
void DataStoreServiceClient::SetupConfig(
const DataStoreServiceClusterManager &cluster_manager)
{
auto current_version =
dss_topology_version_.load(std::memory_order_acquire);
auto new_version = cluster_manager.GetTopologyVersion();
if (current_version <= cluster_manager.GetTopologyVersion() &&
dss_topology_version_.compare_exchange_strong(current_version,
new_version))
{
for (const auto &[_, group] : cluster_manager.GetAllShards())
{
for (const auto &node : group.nodes_)
{
LOG(INFO) << "Node Hostname: " << node.host_name_
<< ", Port: " << node.port_;
}
// The first node is the owner of shard.
assert(group.nodes_.size() > 0);
while (!UpgradeShardVersion(group.shard_id_,
group.version_,
group.nodes_[0].host_name_,
group.nodes_[0].port_))
{
LOG(INFO) << "UpgradeShardVersion failed, retry";
bthread_usleep(1000000);
}
LOG(INFO) << "DataStoreServiceCliet UpgradeShardVersion success, "
"shard_id:"
<< group.shard_id_ << ", version:" << group.version_
<< ", owner_node:" << group.nodes_[0].host_name_ << ":"
<< group.nodes_[0].port_;
}
}
else
{
LOG(INFO)
<< "DataStoreServiceCliet SetupConfig skipped, current_version:"
<< current_version << ", new_version:" << new_version;
}
}
void DataStoreServiceClient::TxConfigsToDssClusterConfig(
uint32_t node_id,
const std::unordered_map<uint32_t, std::vector<txservice::NodeConfig>>
&ng_configs,
const std::unordered_map<uint32_t, uint32_t> &ng_leaders,
DataStoreServiceClusterManager &cluster_manager)
{
std::unordered_map<uint32_t, DSSNode> nodes_map;
for (auto &[ng_id, ng_members] : ng_configs)
{
for (auto &node_config : ng_members)
{
nodes_map.try_emplace(node_config.node_id_,
node_config.host_name_,
TxPort2DssPort(node_config.port_));
}
}
for (auto &[ng_id, ng_members] : ng_configs)
{
// add nodes
bool contain_this_node = false;
for (auto &node_config : ng_members)
{
if (node_config.is_candidate_)
{
if (node_config.node_id_ == node_id)
{
contain_this_node = true;
}
cluster_manager.AddShardMember(
ng_id, nodes_map.at(node_config.node_id_));
}
}
// set primary node
if (ng_leaders.find(ng_id) != ng_leaders.end())
{
uint32_t leader_id = ng_leaders.at(ng_id);
assert(nodes_map.find(leader_id) != nodes_map.end());
if (nodes_map.find(leader_id) != nodes_map.end())
{
cluster_manager.UpdatePrimaryNode(ng_id,
nodes_map.at(leader_id));
}
if (leader_id == node_id)
{
contain_this_node = true;
cluster_manager.SwitchShardToReadWrite(ng_id,
DSShardStatus::Closed);
}
}
// set this node
if (contain_this_node && nodes_map.find(node_id) != nodes_map.end())
{
auto &this_node_config = nodes_map.at(node_id);
cluster_manager.SetThisNode(this_node_config.host_name_,
this_node_config.port_);
}
}
}
/**
* @brief Establishes connection to the data store service.
*
* Attempts to connect to the data store service with retry logic. Initializes
* pre-built tables and retries up to 5 times with 1-second delays between
* attempts. Returns true if connection succeeds, false otherwise.
*
* @return true if connection is successful, false if all retry attempts fail.
*/
bool DataStoreServiceClient::Connect()
{
if (!need_bootstrap_)
{
return true;
}
bool succeed = false;
for (int retry = 1; retry <= 5 && !succeed; retry++)
{
if (!InitPreBuiltTables())
{
succeed = false;
bthread_usleep(1000000);
}
else
{
succeed = true;
}
}
return succeed;
}
/**
* @brief Schedules timer-based tasks for the data store service.
*
* Currently not implemented. This method is a placeholder for future
* timer-based functionality such as periodic cleanup, health checks, or
* maintenance tasks. Will assert and log an error if called.
*/
void DataStoreServiceClient::ScheduleTimerTasks()
{
LOG(WARNING) << "ScheduleTimerTasks not implemented (noop)";
}
/**
* @brief Batch-writes a set of flush tasks into KV tables using concurrent
* partition processing.
*
* Processes the provided flush tasks grouped by table and partition, serializes
* each record (object tables use raw encoded blobs; non-object tables encode
* tx-records with unpack info), and issues batched PUT/DELETE operations via
* BatchWriteRecords. The method uses a concurrent approach where different
* partitions can flush simultaneously, but each partition maintains
* serialization (only one request in-flight per partition at a time).
*
* Key features:
* - Concurrent processing across different partitions
* - Per-partition serialization to respect KV store constraints
* - Automatic batching based on MAX_WRITE_BATCH_SIZE (64MB)
* - Chained callbacks within each partition for sequential processing
* - Global coordination to wait for all partitions to complete
*
* The function distinguishes hash- and range-partitioned tables, computes
* per-partition batches, and updates per-record timestamps/TTLs and operation
* types. On any partition-level error, the function logs the failure and
* returns false.
*
* @param flush_task Mapping from KV table name to a vector of flush task
* entries containing the records to write. Each entry's
* data_sync_vec_ provides the sequence of records for that
* flush task.
* @return true if all partitions completed successfully; false if any partition
* reported an error.
*/
bool DataStoreServiceClient::PutAll(
std::unordered_map<std::string_view,
std::vector<std::unique_ptr<txservice::FlushTaskEntry>>>
&flush_task)
{
DLOG(INFO) << "DataStoreServiceClient::PutAll called with "
<< flush_task.size() << " tables to flush.";
uint64_t now = txservice::LocalCcShards::ClockTsInMillseconds();
// Process each table
for (auto &[kv_table_name, entries] : flush_task)
{
size_t records_count = 0;
auto &table_name = entries.front()->data_sync_task_->table_name_;
// Group records by partition
std::unordered_map<uint32_t, std::vector<std::pair<size_t, size_t>>>
hash_partitions_map;
std::unordered_map<uint32_t, std::vector<size_t>> range_partitions_map;
size_t flush_task_entry_idx = 0;
for (auto &entry : entries)
{
auto &batch = *entry->data_sync_vec_;
if (batch.empty())
{
continue;
}
records_count += batch.size();
if (table_name.IsHashPartitioned())
{
for (size_t i = 0; i < batch.size(); ++i)
{
int32_t kv_partition_id =
KvPartitionIdOf(batch[i].partition_id_, false);
auto [it, inserted] =
hash_partitions_map.try_emplace(kv_partition_id);
if (inserted)
{
it->second.reserve(batch.size() / 1024 * 2 *
entries.size());
}
it->second.emplace_back(
std::make_pair(flush_task_entry_idx, i));
}
}
else
{
// All records in the batch are in the same partition for range
// table
int32_t partition_id =
KvPartitionIdOf(batch[0].partition_id_, true);
auto [it, inserted] =
range_partitions_map.try_emplace(partition_id);
it->second.emplace_back(flush_task_entry_idx);
}
flush_task_entry_idx++;
}
// Create global coordinator
SyncPutAllData *sync_putall = sync_putall_data_pool_.NextObject();
PoolableGuard sync_putall_guard(sync_putall);
sync_putall->Reset();
uint16_t parts_cnt_per_key = 1;
uint16_t parts_cnt_per_record = 5;
if (table_name.IsHashPartitioned() && table_name.IsObjectTable())
{
parts_cnt_per_record = 1;
}
// Create partition states and prepare batches
std::vector<PartitionCallbackData *> callback_data_list;
// Process hash partitions
for (auto &[partition_id, flush_recs] : hash_partitions_map)
{
auto partition_state = partition_flush_state_pool_.NextObject();
partition_state->Reset(partition_id);
auto callback_data = partition_callback_data_pool_.NextObject();
callback_data->Reset(partition_state, sync_putall, kv_table_name);
// Prepare batches for this partition
PreparePartitionBatches(*partition_state,
flush_recs,
entries,
table_name,
parts_cnt_per_key,
parts_cnt_per_record,
now);
sync_putall->partition_states_.push_back(partition_state);
callback_data_list.push_back(callback_data);
}
// Process range partitions
for (auto &[partition_id, flush_recs] : range_partitions_map)
{
auto partition_state = partition_flush_state_pool_.NextObject();
partition_state->Reset(partition_id);
auto callback_data = partition_callback_data_pool_.NextObject();
callback_data->Reset(partition_state, sync_putall, kv_table_name);
// Prepare batches for this partition
PrepareRangePartitionBatches(*partition_state,
flush_recs,
entries,
table_name,
parts_cnt_per_key,
parts_cnt_per_record,
now);
sync_putall->partition_states_.push_back(partition_state);
callback_data_list.push_back(callback_data);
}
// Set up global coordinator
sync_putall->total_partitions_ = sync_putall->partition_states_.size();
bool is_range_partitioned = !table_name.IsHashPartitioned();
// Start concurrent processing for each partition
for (size_t i = 0; i < callback_data_list.size(); ++i)
{
auto *partition_state = sync_putall->partition_states_[i];
auto *callback_data = callback_data_list[i];
// Start the first batch for this partition
auto &first_batch = callback_data->inflight_batch;
if (partition_state->GetNextBatch(first_batch))
{
BatchWriteRecords(
callback_data->table_name,
partition_state->partition_id,
GetShardIdByPartitionId(partition_state->partition_id,
is_range_partitioned),
std::move(first_batch.key_parts),
std::move(first_batch.record_parts),
std::move(first_batch.records_ts),
std::move(first_batch.records_ttl),
std::move(first_batch.op_types),
true, // skip_wal
callback_data,
PartitionBatchCallback,
first_batch.parts_cnt_per_key,
first_batch.parts_cnt_per_record);
}
else
{
// No batches for this partition, mark as completed
sync_putall->OnPartitionCompleted();
}
}
// Wait for all partitions to complete
{
std::unique_lock<bthread::Mutex> lk(sync_putall->mux_);
while (sync_putall->completed_partitions_ <
sync_putall->total_partitions_)
{
sync_putall->cv_.wait(lk);
}
}
// Check for errors
for (auto &partition_state : sync_putall->partition_states_)
{
if (partition_state->IsFailed())
{
LOG(ERROR) << "PutAll failed for partition "
<< partition_state->partition_id << " with error: "
<< partition_state->result.error_msg();
for (auto &callback_data : callback_data_list)
{
callback_data->Clear();
callback_data->Free();
}
return false;
}
}
for (auto &callback_data : callback_data_list)
{
callback_data->Clear();
callback_data->Free();
}
if (metrics::enable_kv_metrics)
{
metrics::kv_meter->Collect(
metrics::NAME_KV_FLUSH_ROWS_TOTAL, records_count, "base");
}
}
return true;
}
/**
* @brief Persists data from specified KV tables to storage.
*
* Flushes data from the provided KV table names to persistent storage using
* asynchronous flush operations. Waits for completion and returns
* success/failure status. Logs warnings on failure and debug info on success.
*
* @param kv_table_names Vector of KV table names to persist.
* @return true if all tables are persisted successfully, false if any operation
* fails.
*/
bool DataStoreServiceClient::PersistKV(
const std::vector<std::string> &kv_table_names)
{
SyncCallbackData *callback_data = sync_callback_data_pool_.NextObject();
PoolableGuard guard(callback_data);
callback_data->Reset();
FlushData(kv_table_names, callback_data, &SyncCallback);
callback_data->Wait();
if (callback_data->Result().error_code() !=
EloqDS::remote::DataStoreError::NO_ERROR)
{
LOG(WARNING) << "DataStoreHandler: Failed to do PersistKV. Error: "
<< callback_data->Result().error_msg();
return false;
}
LOG(INFO) << "DataStoreHandler::PersistKV success.";
return true;
}
/**
* @brief Upserts table schema information to the data store.
*
* Handles table creation, modification, and deletion operations by updating
* table schema information in the data store. Validates leadership, processes
* the operation asynchronously, and sets appropriate error codes on failure.
* Supports various operation types including CREATE, DROP, and ALTER
* operations.
*
* @param old_table_schema Pointer to the existing table schema (nullptr for
* CREATE).
* @param new_table_schema Pointer to the new table schema.
* @param op_type Type of operation (CREATE, DROP, ALTER, etc.).
* @param commit_ts Commit timestamp for the operation.
* @param ng_id Node group ID for the operation.
* @param tx_term Transaction term for consistency.
* @param hd_res Handler result object to store operation outcome.
* @param alter_table_info Information about table alterations (nullptr if not
* applicable).
* @param cc_req CC request base object.
* @param ccs CC shard reference.
* @param err_code Error code output parameter.
*/
void DataStoreServiceClient::UpsertTable(
const txservice::TableSchema *old_table_schema,
const txservice::TableSchema *new_table_schema,
txservice::OperationType op_type,
uint64_t commit_ts,
txservice::NodeGroupId ng_id,
int64_t tx_term,
txservice::CcHandlerResult<txservice::Void> *hd_res,
const txservice::AlterTableInfo *alter_table_info,
txservice::CcRequestBase *cc_req,
txservice::CcShard *ccs,
txservice::CcErrorCode *err_code)
{
int64_t leader_term =
txservice::Sharder::Instance().TryPinNodeGroupData(ng_id);
if (leader_term < 0)
{
hd_res->SetError(txservice::CcErrorCode::TX_NODE_NOT_LEADER);
return;
}
std::shared_ptr<void> defer_unpin(
nullptr,
[ng_id](void *)
{ txservice::Sharder::Instance().UnpinNodeGroupData(ng_id); });
if (leader_term != tx_term)
{
hd_res->SetError(txservice::CcErrorCode::NG_TERM_CHANGED);
return;
}
// Use old schema for drop table as the new schema would be null.
UpsertTableData *table_data = new UpsertTableData(old_table_schema,
new_table_schema,
op_type,
commit_ts,
defer_unpin,
ng_id,
tx_term,
hd_res,
alter_table_info,
cc_req,
ccs,
err_code);
upsert_table_worker_.SubmitWork([this, table_data]()
{ this->UpsertTable(table_data); });
}
/**
* @brief Fetches table catalog information from the data store.
*
* Retrieves catalog information for the specified table by reading from the
* KV table catalogs storage. Uses partition ID 0 and the catalog name as the
* key. The operation is performed asynchronously with a callback for completion
* handling.
*
* @param ccm_table_name The table name to fetch catalog information for.
* @param fetch_cc Fetch catalog CC object to store the result and handle
* completion.
*/
void DataStoreServiceClient::FetchTableCatalog(
const txservice::TableName &ccm_table_name,
txservice::FetchCatalogCc *fetch_cc)
{
int32_t kv_partition_id = 0;
uint32_t shard_id = GetShardIdByPartitionId(kv_partition_id, false);
std::string_view key = fetch_cc->CatalogName().StringView();
Read(kv_table_catalogs_name,
kv_partition_id,
shard_id,
key,
fetch_cc,
&FetchTableCatalogCallback);
}
/**
* @brief Fetches current table statistics from the data store.
*
* Retrieves the current version of table statistics for the specified table.
* Determines the appropriate KV partition ID and reads from the table
* statistics version storage. The operation is performed asynchronously with
* callback handling.
*
* @param ccm_table_name The table name to fetch statistics for.
* @param fetch_cc Fetch table statistics CC object to store the result and
* handle completion.
*/
void DataStoreServiceClient::FetchCurrentTableStatistics(
const txservice::TableName &ccm_table_name,
txservice::FetchTableStatisticsCc *fetch_cc)
{
std::string_view sv = ccm_table_name.StringView();
fetch_cc->kv_partition_id_ = KvPartitionIdOf(ccm_table_name);
uint32_t shard_id =
GetShardIdByPartitionId(fetch_cc->kv_partition_id_, false);
fetch_cc->SetStoreHandler(this);
Read(kv_table_statistics_version_name,
fetch_cc->kv_partition_id_,
shard_id,
sv,
fetch_cc,
&FetchCurrentTableStatsCallback);
}
/**
* @brief Fetches table statistics for a specific version from the data store.
*
* Retrieves table statistics for a specific version by constructing key ranges
* based on the table name and version number. Clears previous key ranges and
* session information, then constructs start and end keys for the
* version-specific statistics. The operation is performed asynchronously with
* callback handling.
*
* @param ccm_table_name The table name to fetch statistics for.
* @param fetch_cc Fetch table statistics CC object containing version
* information and result storage.
*/
void DataStoreServiceClient::FetchTableStatistics(
const txservice::TableName &ccm_table_name,
txservice::FetchTableStatisticsCc *fetch_cc)
{
fetch_cc->kv_start_key_.clear();
fetch_cc->kv_end_key_.clear();
fetch_cc->kv_session_id_.clear();
uint64_t version = fetch_cc->CurrentVersion();
uint64_t be_version = EloqShare::host_to_big_endian(version);
fetch_cc->kv_start_key_.append(ccm_table_name.StringView());
fetch_cc->kv_start_key_.append(reinterpret_cast<const char *>(&be_version),
sizeof(uint64_t));
fetch_cc->kv_end_key_ = fetch_cc->kv_start_key_;
fetch_cc->kv_end_key_.back()++;
fetch_cc->kv_partition_id_ = KvPartitionIdOf(ccm_table_name);
uint32_t data_shard_id =
GetShardIdByPartitionId(fetch_cc->kv_partition_id_, false);
// NOTICE: here batch_size is 1, because the size of item in
// {kv_table_statistics_name} may be more than MAX_WRITE_BATCH_SIZE.
ScanNext(kv_table_statistics_name,
fetch_cc->kv_partition_id_,
data_shard_id,
fetch_cc->kv_start_key_,
fetch_cc->kv_end_key_,
fetch_cc->kv_session_id_,
true,
false,
false,
true,
1,
nullptr,
fetch_cc,
&FetchTableStatsCallback);
}
// Each node group contains a sample pool, when write them to storage,
// we merge them together. The merged sample pool may be too large to store
// in one row. Therefore, we have to store table statistics segmentally.
//
// (1) We store sample keys of table statistics in
// {kv_table_statistics_name} table using the following format:
//
// segment_key: [table_name + version + segment_id + index_name];
// segment_record: [index_type + records_count + (key_size +
// key) + (key_size + key) + ... ];
//
// (2) We store the ckpt version of each table statistics version in
// {kv_table_statistics_version_name} table using the following format:
//
// key: [table_name]; record: [ckpt_version];
std::string EncodeTableStatsKey(const txservice::TableName &base_table_name,
const txservice::TableName &index_name,
uint64_t version,
uint32_t segment_id)
{
std::string key;
std::string_view table_sv = base_table_name.StringView();
std::string_view index_sv = index_name.StringView();
uint64_t be_version = EloqShare::host_to_big_endian(version);
uint32_t be_segment_id = EloqShare::host_to_big_endian(segment_id);
key.reserve(table_sv.size() + sizeof(be_version) + sizeof(be_segment_id) +
index_sv.size());
key.append(table_sv);
key.append(reinterpret_cast<const char *>(&be_version), sizeof(uint64_t));
key.append(reinterpret_cast<const char *>(&be_segment_id),
sizeof(uint32_t));
key.append(index_sv);
return key;
}
/**
* @brief Upserts table statistics to the data store.
*
* Stores table statistics by splitting sample keys into segments and writing
* them to the KV storage. Each segment contains index type, record count, and
* sample keys. Also updates the checkpoint version for the table statistics.
* Uses batch write operations for efficiency and handles both local and remote
* storage paths.
*
* @param ccm_table_name The table name to store statistics for.
* @param sample_pool_map Map of index names to sample pools containing record
* counts and sample keys.
* @param version The version number for the statistics.
* @return true if all statistics are stored successfully, false if any
* operation fails.
*/
bool DataStoreServiceClient::UpsertTableStatistics(
const txservice::TableName &ccm_table_name,
const std::unordered_map<txservice::TableName,
std::pair<uint64_t, std::vector<txservice::TxKey>>>
&sample_pool_map,
uint64_t version)
{
// 1- split the sample keys into segments
std::vector<std::string> segment_keys;
std::vector<std::string> segment_records;
for (const auto &[indexname, sample_pool] : sample_pool_map)
{
uint64_t records_count = sample_pool.first;
auto &sample_keys = sample_pool.second;
uint32_t segment_id = 0;
std::string segment_key =
EncodeTableStatsKey(ccm_table_name, indexname, version, segment_id);
size_t batch_size = segment_key.size();
std::string segment_record;
segment_record.reserve(MAX_WRITE_BATCH_SIZE - batch_size);
// index-type
uint8_t index_type_int = static_cast<uint8_t>(indexname.Type());
segment_record.append(reinterpret_cast<const char *>(&index_type_int),
sizeof(uint8_t));
// records-count
segment_record.append(reinterpret_cast<const char *>(&records_count),
sizeof(uint64_t));
for (size_t i = 0; i < sample_keys.size(); ++i)
{
uint32_t key_size = sample_keys[i].Size();
segment_record.append(reinterpret_cast<const char *>(&key_size),
sizeof(uint32_t));
batch_size += sizeof(uint32_t);
segment_record.append(sample_keys[i].Data(), sample_keys[i].Size());
batch_size += key_size;
if (batch_size >= MAX_WRITE_BATCH_SIZE)
{
segment_keys.emplace_back(std::move(segment_key));
segment_records.emplace_back(std::move(segment_record));
// segment_size = 0;
++segment_id;
segment_key = EncodeTableStatsKey(
ccm_table_name, indexname, version, segment_id);
batch_size = segment_key.size();
segment_record.clear();
segment_record.reserve(MAX_WRITE_BATCH_SIZE - batch_size);
// index-type
uint8_t index_type_int = static_cast<uint8_t>(indexname.Type());
segment_record.append(
reinterpret_cast<const char *>(&index_type_int),
sizeof(uint8_t));
// records-count
segment_record.append(
reinterpret_cast<const char *>(&records_count),
sizeof(uint64_t));
}
}
if (segment_record.size() > 0)
{
segment_keys.emplace_back(std::move(segment_key));
segment_records.emplace_back(std::move(segment_record));
}
}
// 2- write the segments to storage
int32_t kv_partition_id = KvPartitionIdOf(ccm_table_name);
uint32_t data_shard_id = GetShardIdByPartitionId(kv_partition_id, false);
std::vector<std::string_view> keys;
std::vector<std::string_view> records;
std::vector<uint64_t> records_ts;
std::vector<uint64_t> records_ttl;
std::vector<WriteOpType> op_types;
SyncCallbackData *callback_data = sync_callback_data_pool_.NextObject();
PoolableGuard guard(callback_data);
callback_data->Reset();
for (size_t i = 0; i < segment_keys.size(); ++i)
{
keys.emplace_back(segment_keys[i]);
records.emplace_back(segment_records[i]);
records_ts.emplace_back(version);
records_ttl.emplace_back(0); // no ttl
op_types.emplace_back(WriteOpType::PUT);
// For segments are splitted based on MAX_WRITE_BATCH_SIZE, execute
// one write request for each segment record.
callback_data->Reset();
BatchWriteRecords(kv_table_statistics_name,
kv_partition_id,
data_shard_id,
std::move(keys),
std::move(records),
std::move(records_ts),
std::move(records_ttl),
std::move(op_types),
true,
callback_data,
&SyncCallback);
callback_data->Wait();
if (callback_data->Result().error_code() !=
EloqDS::remote::DataStoreError::NO_ERROR)
{
LOG(WARNING) << "UpdatetableStatistics: Failed to write segments.";
return false;
}
}
// 3- Update the ckpt version of the table statistics
callback_data->Reset();
keys.emplace_back(ccm_table_name.StringView());
std::string version_str = std::to_string(version);
records.emplace_back(version_str);
records_ts.emplace_back(version);
records_ttl.emplace_back(0); // no ttl
op_types.emplace_back(WriteOpType::PUT);
BatchWriteRecords(kv_table_statistics_version_name,
kv_partition_id,
data_shard_id,
std::move(keys),
std::move(records),
std::move(records_ts),
std::move(records_ttl),
std::move(op_types),
true,
callback_data,
&SyncCallback);
callback_data->Wait();
if (callback_data->Result().error_code() !=
EloqDS::remote::DataStoreError::NO_ERROR)
{
LOG(WARNING) << "UpdatetableStatistics: Failed to write segments.";
return false;
}
// 4- Delete old version data of the table statistics
uint64_t version0 = 0;
std::string start_key = ccm_table_name.String();
// The big endian and small endian encoding of 0 is same.
start_key.append(reinterpret_cast<const char *>(&version0),
sizeof(uint64_t));
std::string end_key = ccm_table_name.String();
uint64_t be_version = EloqShare::host_to_big_endian(version);
end_key.append(reinterpret_cast<const char *>(&be_version),
sizeof(uint64_t));
callback_data->Reset();
DeleteRange(kv_table_statistics_name,
kv_partition_id,
data_shard_id,
start_key,
end_key,
true,
callback_data,
&SyncCallback);
callback_data->Wait();
if (callback_data->Result().error_code() !=
EloqDS::remote::DataStoreError::NO_ERROR)
{
LOG(WARNING) << "UpdatetableStatistics: Failed to write ckpt version.";
return false;
}
return true;
}
/**
* @brief Fetches table ranges from the data store.
*
* Retrieves range information for the specified table by scanning the range
* table storage. Constructs start and end keys based on the table name and
* performs a scan operation with pagination support. The operation is performed
* asynchronously with callback handling for completion.
*
* @param fetch_cc Fetch table ranges CC object containing table name and result
* storage.
*/
void DataStoreServiceClient::FetchTableRanges(
txservice::FetchTableRangesCc *fetch_cc)
{
fetch_cc->kv_partition_id_ = KvPartitionIdOf(fetch_cc->table_name_);
uint32_t data_shard_id =
GetShardIdByPartitionId(fetch_cc->kv_partition_id_, false);
fetch_cc->kv_start_key_ = fetch_cc->table_name_.String();
fetch_cc->kv_end_key_ = fetch_cc->table_name_.String();
fetch_cc->kv_end_key_.back()++;
fetch_cc->kv_session_id_.clear();
ScanNext(kv_range_table_name,
fetch_cc->kv_partition_id_,
data_shard_id,
fetch_cc->kv_start_key_,
fetch_cc->kv_end_key_,
fetch_cc->kv_session_id_,
true,
true,
false,
true,
100,
nullptr,
fetch_cc,
&FetchTableRangesCallback);
}
/**
* @brief Fetches range slices from the data store.
*
* Retrieves range slice information for the specified table and range entry.
* Validates node group term consistency and constructs the appropriate key
* for reading range information. The operation is performed asynchronously
* with callback handling for completion.
*
* @param fetch_cc Fetch range slices request object containing table name,
* range entry, and result storage.
*/
void DataStoreServiceClient::FetchRangeSlices(
txservice::FetchRangeSlicesReq *fetch_cc)
{
// 1- fetch range info from {kv_range_table_name}
// 2- fetch range slices from {kv_range_slices_table_name}
if (txservice::Sharder::Instance().TryPinNodeGroupData(
fetch_cc->cc_ng_id_) != fetch_cc->cc_ng_term_)
{
fetch_cc->SetFinish(txservice::CcErrorCode::NG_TERM_CHANGED);
return;
}
fetch_cc->kv_partition_id_ = KvPartitionIdOf(fetch_cc->table_name_);
uint32_t shard_id =
GetShardIdByPartitionId(fetch_cc->kv_partition_id_, false);
// Also use segment_cnt to identify the step is fetch range or fetch slices.
fetch_cc->SetSegmentCnt(0);
txservice::TxKey start_key =
fetch_cc->range_entry_->GetRangeInfo()->StartTxKey();