You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@kvrocks.apache.org by hu...@apache.org on 2023/04/14 03:30:08 UTC
[incubator-kvrocks] branch unstable updated: Fix member name convension for readability-identifier-naming (#1385)
This is an automated email from the ASF dual-hosted git repository.
hulk pushed a commit to branch unstable
in repository https://gitbox.apache.org/repos/asf/incubator-kvrocks.git
The following commit(s) were added to refs/heads/unstable by this push:
new 8d4c31ff Fix member name convension for readability-identifier-naming (#1385)
8d4c31ff is described below
commit 8d4c31ff501ba57ed4d0d1c74366c35fdd1b2372
Author: Twice <tw...@gmail.com>
AuthorDate: Fri Apr 14 11:30:01 2023 +0800
Fix member name convension for readability-identifier-naming (#1385)
---
.clang-tidy | 6 +-
src/cluster/cluster.cc | 10 +-
src/cluster/cluster.h | 14 +-
src/cluster/replication.cc | 56 +-
src/cluster/replication.h | 7 +-
src/cluster/slot_migrate.cc | 30 +-
src/commands/cmd_cluster.cc | 20 +-
src/commands/cmd_geo.cc | 12 +-
src/commands/cmd_hash.cc | 24 +-
src/commands/cmd_list.cc | 2 +-
src/commands/cmd_pubsub.cc | 4 +-
src/commands/cmd_replication.cc | 34 +-
src/commands/cmd_server.cc | 28 +-
src/commands/cmd_set.cc | 2 +-
src/commands/cmd_sortedint.cc | 8 +-
src/commands/cmd_stream.cc | 144 +--
src/commands/cmd_string.cc | 4 +-
src/commands/cmd_zset.cc | 36 +-
src/commands/command_parser.h | 18 +-
src/commands/commander.cc | 24 +-
src/commands/commander.h | 30 +-
src/commands/scan_base.h | 32 +-
src/common/cron.cc | 20 +-
src/common/cron.h | 10 +-
src/common/event_util.h | 4 +-
src/common/io_util.cc | 2 +-
src/common/range_spec.cc | 16 +-
src/common/range_spec.h | 18 +-
src/common/sha1.cc | 34 +-
src/common/sha1.h | 6 +-
src/config/config.cc | 442 ++++----
src/config/config.h | 262 ++---
src/config/config_type.h | 24 +-
src/main.cc | 28 +-
src/server/redis_connection.cc | 38 +-
src/server/redis_reply.h | 5 +-
src/server/redis_request.cc | 20 +-
src/server/server.cc | 184 ++--
src/server/server.h | 26 +-
src/server/tls_util.cc | 35 +-
src/server/worker.cc | 24 +-
src/server/worker.h | 2 +-
src/stats/disk_stats.cc | 6 +-
src/stats/log_collector.cc | 24 +-
src/stats/log_collector.h | 20 +-
src/stats/stats.cc | 32 +-
src/stats/stats.h | 38 +-
src/storage/batch_debugger.h | 64 +-
src/storage/batch_extractor.cc | 22 +-
src/storage/compact_filter.cc | 2 +-
src/storage/compaction_checker.cc | 4 +-
src/storage/redis_db.cc | 36 +-
src/storage/redis_metadata.cc | 120 +-
src/storage/redis_metadata.h | 32 +-
src/storage/scripting.cc | 14 +-
src/storage/storage.cc | 180 +--
src/storage/storage.h | 24 +-
src/types/geohash.cc | 170 +--
src/types/geohash.h | 46 +-
src/types/redis_bitmap.cc | 46 +-
src/types/redis_geo.cc | 72 +-
src/types/redis_geo.h | 10 +-
src/types/redis_hash.cc | 66 +-
src/types/redis_hash.h | 6 +-
src/types/redis_list.cc | 176 +--
src/types/redis_set.cc | 28 +-
src/types/redis_sortedint.cc | 56 +-
src/types/redis_sortedint.h | 8 +-
src/types/redis_stream.cc | 274 ++---
src/types/redis_stream_base.cc | 46 +-
src/types/redis_stream_base.h | 94 +-
src/types/redis_string.cc | 26 +-
src/types/redis_string.h | 4 +-
src/types/redis_zset.cc | 242 ++--
src/types/redis_zset.h | 36 +-
tests/cppunit/cluster_test.cc | 30 +-
tests/cppunit/compact_test.cc | 8 +-
tests/cppunit/config_test.cc | 18 +-
tests/cppunit/cron_test.cc | 12 +-
tests/cppunit/disk_test.cc | 8 +-
tests/cppunit/status_test.cc | 20 +-
tests/cppunit/test_base.h | 12 +-
tests/cppunit/types/bitmap_test.cc | 32 +-
tests/cppunit/types/geo_test.cc | 66 +-
tests/cppunit/types/hash_test.cc | 226 ++--
tests/cppunit/types/list_test.cc | 248 ++---
tests/cppunit/types/metadata_test.cc | 60 +-
tests/cppunit/types/set_test.cc | 128 +--
tests/cppunit/types/sortedint_test.cc | 22 +-
tests/cppunit/types/stream_test.cc | 1938 ++++++++++++++++-----------------
tests/cppunit/types/string_test.cc | 164 +--
tests/cppunit/types/zset_test.cc | 204 ++--
utils/kvrocks2redis/config.cc | 52 +-
utils/kvrocks2redis/config.h | 36 +-
utils/kvrocks2redis/main.cc | 30 +-
utils/kvrocks2redis/parser.cc | 10 +-
utils/kvrocks2redis/redis_writer.cc | 8 +-
utils/kvrocks2redis/sync.cc | 16 +-
utils/kvrocks2redis/writer.cc | 2 +-
x.py | 6 +-
100 files changed, 3569 insertions(+), 3556 deletions(-)
diff --git a/.clang-tidy b/.clang-tidy
index 4ef46a40..a7eec5d0 100644
--- a/.clang-tidy
+++ b/.clang-tidy
@@ -29,9 +29,7 @@ CheckOptions:
# value: camelBack
- key: readability-identifier-naming.LocalConstantCase
value: aNy_CasE # FIXME: use a more strictly case
- - key: readability-identifier-naming.ClassMemberCase
+ - key: readability-identifier-naming.MemberCase
value: lower_case
- - key: readability-identifier-naming.ClassMemberSuffix
+ - key: readability-identifier-naming.MemberSuffix
value: _
- - key: readability-identifier-naming.ClassConstantCase
- value: aNy_CasE # FIXME: use a more strictly case
diff --git a/src/cluster/cluster.cc b/src/cluster/cluster.cc
index ae2eecb1..2d7d1494 100644
--- a/src/cluster/cluster.cc
+++ b/src/cluster/cluster.cc
@@ -197,7 +197,7 @@ Status Cluster::SetClusterNodes(const std::string &nodes_str, int64_t version, b
for (auto &n : nodes_) {
if (n.second->role_ == kClusterSlave) {
if (nodes_.find(n.second->master_id_) != nodes_.end()) {
- nodes_[n.second->master_id_]->replicas.push_back(n.first);
+ nodes_[n.second->master_id_]->replicas_.push_back(n.first);
}
}
if (n.second->role_ == kClusterMaster && n.second->slots_.count() > 0) {
@@ -323,8 +323,8 @@ Status Cluster::MigrateSlot(int slot, const std::string &dst_node_id) {
const auto dst = nodes_[dst_node_id];
Status s = svr_->slot_migrator_->PerformSlotMigration(
- dst_node_id, dst->host_, dst->port_, slot, svr_->GetConfig()->migrate_speed, svr_->GetConfig()->pipeline_size,
- svr_->GetConfig()->sequence_gap);
+ dst_node_id, dst->host_, dst->port_, slot, svr_->GetConfig()->migrate_speed_, svr_->GetConfig()->pipeline_size_,
+ svr_->GetConfig()->sequence_gap_);
return s;
}
@@ -470,7 +470,7 @@ SlotInfo Cluster::GenSlotNodeInfo(int start, int end, const std::shared_ptr<Clus
std::vector<SlotInfo::NodeInfo> vn;
vn.push_back({n->host_, n->port_, n->id_}); // itself
- for (const auto &id : n->replicas) { // replicas
+ for (const auto &id : n->replicas_) { // replicas
if (nodes_.find(id) == nodes_.end()) continue;
vn.push_back({nodes_[id]->host_, nodes_[id]->port_, nodes_[id]->id_});
}
@@ -763,7 +763,7 @@ bool Cluster::IsWriteForbiddenSlot(int slot) { return svr_->slot_migrator_->GetF
Status Cluster::CanExecByMySelf(const Redis::CommandAttributes *attributes, const std::vector<std::string> &cmd_tokens,
Redis::Connection *conn) {
std::vector<int> keys_indexes;
- auto s = Redis::GetKeysFromCommand(attributes->name, static_cast<int>(cmd_tokens.size()), &keys_indexes);
+ auto s = Redis::GetKeysFromCommand(attributes->name_, static_cast<int>(cmd_tokens.size()), &keys_indexes);
// No keys
if (!s.IsOK()) return Status::OK();
diff --git a/src/cluster/cluster.h b/src/cluster/cluster.h
index 6807be9e..1a3b6897 100644
--- a/src/cluster/cluster.h
+++ b/src/cluster/cluster.h
@@ -53,19 +53,19 @@ class ClusterNode {
std::string master_id_;
std::string slots_info_;
std::bitset<kClusterSlots> slots_;
- std::vector<std::string> replicas;
+ std::vector<std::string> replicas_;
int importing_slot_ = -1;
};
struct SlotInfo {
- int start;
- int end;
+ int start_;
+ int end_;
struct NodeInfo {
- std::string host;
- int port;
- std::string id;
+ std::string host_;
+ int port_;
+ std::string id_;
};
- std::vector<NodeInfo> nodes;
+ std::vector<NodeInfo> nodes_;
};
using ClusterNodes = std::unordered_map<std::string, std::shared_ptr<ClusterNode>>;
diff --git a/src/cluster/replication.cc b/src/cluster/replication.cc
index 1d633444..0828712e 100644
--- a/src/cluster/replication.cc
+++ b/src/cluster/replication.cc
@@ -83,7 +83,7 @@ void FeedSlaveThread::Join() {
}
void FeedSlaveThread::checkLivenessIfNeed() {
- if (++interval % 1000) return;
+ if (++interval_ % 1000) return;
const auto ping_command = Redis::BulkString("ping");
auto s = Util::SockSend(conn_->GetFD(), ping_command);
if (!s.IsOK()) {
@@ -242,7 +242,7 @@ void ReplicationThread::CallbacksStateMachine::Start() {
// Note: It may cause data races to use 'masterauth' directly.
// It is acceptable because password change is a low frequency operation.
- if (!repl_->srv_->GetConfig()->masterauth.empty()) {
+ if (!repl_->srv_->GetConfig()->masterauth_.empty()) {
handlers_.emplace_front(CallbacksStateMachine::READ, "auth read", authReadCB);
handlers_.emplace_front(CallbacksStateMachine::WRITE, "auth write", authWriteCB);
}
@@ -316,7 +316,7 @@ Status ReplicationThread::Start(std::function<void()> &&pre_fullsync_cb, std::fu
post_fullsync_cb_ = std::move(post_fullsync_cb);
// Clean synced checkpoint from old master because replica starts to follow new master
- auto s = rocksdb::DestroyDB(srv_->GetConfig()->sync_checkpoint_dir, rocksdb::Options());
+ auto s = rocksdb::DestroyDB(srv_->GetConfig()->sync_checkpoint_dir_, rocksdb::Options());
if (!s.ok()) {
LOG(WARNING) << "Can't clean synced checkpoint from master, error: " << s.ToString();
} else {
@@ -372,7 +372,7 @@ void ReplicationThread::run() {
ReplicationThread::CBState ReplicationThread::authWriteCB(bufferevent *bev, void *ctx) {
auto self = static_cast<ReplicationThread *>(ctx);
- send_string(bev, Redis::MultiBulkString({"AUTH", self->srv_->GetConfig()->masterauth}));
+ send_string(bev, Redis::MultiBulkString({"AUTH", self->srv_->GetConfig()->masterauth_}));
LOG(INFO) << "[replication] Auth request was sent, waiting for response";
self->repl_state_.store(kReplSendAuth, std::memory_order_relaxed);
return CBState::NEXT;
@@ -414,7 +414,7 @@ ReplicationThread::CBState ReplicationThread::checkDBNameReadCB(bufferevent *bev
}
auto self = static_cast<ReplicationThread *>(ctx);
std::string db_name = self->storage_->GetName();
- if (line.length == db_name.size() && !strncmp(line.get(), db_name.data(), line.length)) {
+ if (line.length_ == db_name.size() && !strncmp(line.get(), db_name.data(), line.length_)) {
// DB name match, we should continue to next step: TryPsync
LOG(INFO) << "[replication] DB name is valid, continue...";
return CBState::NEXT;
@@ -427,11 +427,11 @@ ReplicationThread::CBState ReplicationThread::replConfWriteCB(bufferevent *bev,
auto self = static_cast<ReplicationThread *>(ctx);
auto config = self->srv_->GetConfig();
- auto port = config->replica_announce_port > 0 ? config->replica_announce_port : config->port;
+ auto port = config->replica_announce_port_ > 0 ? config->replica_announce_port_ : config->port_;
std::vector<std::string> data_to_send{"replconf", "listening-port", std::to_string(port)};
- if (!self->next_try_without_announce_ip_address_ && !config->replica_announce_ip.empty()) {
+ if (!self->next_try_without_announce_ip_address_ && !config->replica_announce_ip_.empty()) {
data_to_send.emplace_back("ip-address");
- data_to_send.emplace_back(config->replica_announce_ip);
+ data_to_send.emplace_back(config->replica_announce_ip_);
}
send_string(bev, Redis::MultiBulkString(data_to_send));
self->repl_state_.store(kReplReplConf, std::memory_order_relaxed);
@@ -490,7 +490,7 @@ ReplicationThread::CBState ReplicationThread::tryPSyncWriteCB(bufferevent *bev,
// To adapt to old master using old PSYNC, i.e. only use next sequence id.
// Also use old PSYNC if replica can't find replication id from WAL and DB.
- if (!self->srv_->GetConfig()->use_rsid_psync || self->next_try_old_psync_ || replid.length() != kReplIdLength) {
+ if (!self->srv_->GetConfig()->use_rsid_psync_ || self->next_try_old_psync_ || replid.length() != kReplIdLength) {
self->next_try_old_psync_ = false; // Reset next_try_old_psync_
send_string(bev, Redis::MultiBulkString({"PSYNC", std::to_string(next_seq)}));
LOG(INFO) << "[replication] Try to use psync, next seq: " << next_seq;
@@ -547,7 +547,7 @@ ReplicationThread::CBState ReplicationThread::incrementBatchLoopCB(bufferevent *
// Read bulk length
UniqueEvbufReadln line(input, EVBUFFER_EOL_CRLF_STRICT);
if (!line) return CBState::AGAIN;
- self->incr_bulk_len_ = line.length > 0 ? std::strtoull(line.get() + 1, nullptr, 10) : 0;
+ self->incr_bulk_len_ = line.length_ > 0 ? std::strtoull(line.get() + 1, nullptr, 10) : 0;
if (self->incr_bulk_len_ == 0) {
LOG(ERROR) << "[replication] Invalid increment data size";
return CBState::RESTART;
@@ -601,7 +601,7 @@ ReplicationThread::CBState ReplicationThread::fullSyncReadCB(bufferevent *bev, v
switch (self->fullsync_state_) {
case kFetchMetaID: {
// New version master only sends meta file content
- if (!self->srv_->GetConfig()->master_use_repl_port) {
+ if (!self->srv_->GetConfig()->master_use_repl_port_) {
self->fullsync_state_ = kFetchMetaContent;
return CBState::AGAIN;
}
@@ -612,7 +612,7 @@ ReplicationThread::CBState ReplicationThread::fullSyncReadCB(bufferevent *bev, v
return CBState::RESTART;
}
self->fullsync_meta_id_ =
- static_cast<rocksdb::BackupID>(line.length > 0 ? std::strtoul(line.get(), nullptr, 10) : 0);
+ static_cast<rocksdb::BackupID>(line.length_ > 0 ? std::strtoul(line.get(), nullptr, 10) : 0);
if (self->fullsync_meta_id_ == 0) {
LOG(ERROR) << "[replication] Invalid meta id received";
return CBState::RESTART;
@@ -627,7 +627,7 @@ ReplicationThread::CBState ReplicationThread::fullSyncReadCB(bufferevent *bev, v
LOG(ERROR) << "[replication] Failed to fetch meta size: " << line.get();
return CBState::RESTART;
}
- self->fullsync_filesize_ = line.length > 0 ? std::strtoull(line.get(), nullptr, 10) : 0;
+ self->fullsync_filesize_ = line.length_ > 0 ? std::strtoull(line.get(), nullptr, 10) : 0;
if (self->fullsync_filesize_ == 0) {
LOG(ERROR) << "[replication] Invalid meta file size received";
return CBState::RESTART;
@@ -639,7 +639,7 @@ ReplicationThread::CBState ReplicationThread::fullSyncReadCB(bufferevent *bev, v
std::string target_dir;
Engine::Storage::ReplDataManager::MetaInfo meta;
// Master using old version
- if (self->srv_->GetConfig()->master_use_repl_port) {
+ if (self->srv_->GetConfig()->master_use_repl_port_) {
if (evbuffer_get_length(input) < self->fullsync_filesize_) {
return CBState::AGAIN;
}
@@ -649,7 +649,7 @@ ReplicationThread::CBState ReplicationThread::fullSyncReadCB(bufferevent *bev, v
LOG(ERROR) << "[replication] Failed to parse meta and save: " << s.Msg();
return CBState::AGAIN;
}
- target_dir = self->srv_->GetConfig()->backup_sync_dir;
+ target_dir = self->srv_->GetConfig()->backup_sync_dir_;
} else {
// Master using new version
UniqueEvbufReadln line(input, EVBUFFER_EOL_CRLF_STRICT);
@@ -660,10 +660,10 @@ ReplicationThread::CBState ReplicationThread::fullSyncReadCB(bufferevent *bev, v
}
std::vector<std::string> need_files = Util::Split(std::string(line.get()), ",");
for (const auto &f : need_files) {
- meta.files.emplace_back(f, 0);
+ meta.files_.emplace_back(f, 0);
}
- target_dir = self->srv_->GetConfig()->sync_checkpoint_dir;
+ target_dir = self->srv_->GetConfig()->sync_checkpoint_dir_;
// Clean invalid files of checkpoint, "CURRENT" file must be invalid
// because we identify one file by its file number but only "CURRENT"
// file doesn't have number.
@@ -687,13 +687,13 @@ ReplicationThread::CBState ReplicationThread::fullSyncReadCB(bufferevent *bev, v
// If 'slave-empty-db-before-fullsync' is yes, we call 'pre_fullsync_cb_'
// just like reloading database. And we don't want slave to occupy too much
// disk space, so we just empty entire database rudely.
- if (self->srv_->GetConfig()->slave_empty_db_before_fullsync) {
+ if (self->srv_->GetConfig()->slave_empty_db_before_fullsync_) {
self->pre_fullsync_cb_();
self->storage_->EmptyDB();
}
self->repl_state_.store(kReplFetchSST, std::memory_order_relaxed);
- auto s = self->parallelFetchFile(target_dir, meta.files);
+ auto s = self->parallelFetchFile(target_dir, meta.files_);
if (!s.IsOK()) {
LOG(ERROR) << "[replication] Failed to parallel fetch files while " + s.Msg();
return CBState::RESTART;
@@ -702,9 +702,9 @@ ReplicationThread::CBState ReplicationThread::fullSyncReadCB(bufferevent *bev, v
// Restore DB from backup
// We already call 'pre_fullsync_cb_' if 'slave-empty-db-before-fullsync' is yes
- if (!self->srv_->GetConfig()->slave_empty_db_before_fullsync) self->pre_fullsync_cb_();
+ if (!self->srv_->GetConfig()->slave_empty_db_before_fullsync_) self->pre_fullsync_cb_();
// For old version, master uses rocksdb backup to implement data snapshot
- if (self->srv_->GetConfig()->master_use_repl_port) {
+ if (self->srv_->GetConfig()->master_use_repl_port_) {
s = self->storage_->RestoreFromBackup();
} else {
s = self->storage_->RestoreFromCheckpoint();
@@ -783,7 +783,7 @@ Status ReplicationThread::parallelFetchFile(const std::string &dir,
};
// For master using old version, it only supports to fetch a single file by one
// command, so we need to fetch all files by multiple command interactions.
- if (srv_->GetConfig()->master_use_repl_port) {
+ if (srv_->GetConfig()->master_use_repl_port_) {
for (unsigned i = 0; i < fetch_files.size(); i++) {
s = this->fetchFiles(sock_fd, dir, {fetch_files[i]}, {crcs[i]}, fn);
if (!s.IsOK()) break;
@@ -807,7 +807,7 @@ Status ReplicationThread::parallelFetchFile(const std::string &dir,
Status ReplicationThread::sendAuth(int sock_fd) {
// Send auth when needed
- std::string auth = srv_->GetConfig()->masterauth;
+ std::string auth = srv_->GetConfig()->masterauth_;
if (!auth.empty()) {
UniqueEvbuf evbuf;
const auto auth_command = Redis::MultiBulkString({"AUTH", auth});
@@ -845,7 +845,7 @@ Status ReplicationThread::fetchFile(int sock_fd, evbuffer *evbuf, const std::str
std::string msg(line.get());
return {Status::NotOK, msg};
}
- file_size = line.length > 0 ? std::strtoull(line.get(), nullptr, 10) : 0;
+ file_size = line.length_ > 0 ? std::strtoull(line.get(), nullptr, 10) : 0;
break;
}
@@ -912,8 +912,8 @@ Status ReplicationThread::fetchFiles(int sock_fd, const std::string &dir, const
DLOG(INFO) << "[fetch] Succeed fetching file " << files[i];
// Just for tests
- if (srv_->GetConfig()->fullsync_recv_file_delay) {
- sleep(srv_->GetConfig()->fullsync_recv_file_delay);
+ if (srv_->GetConfig()->fullsync_recv_file_delay_) {
+ sleep(srv_->GetConfig()->fullsync_recv_file_delay_);
}
}
return s;
@@ -958,8 +958,8 @@ Status ReplicationThread::ParseWriteBatch(const std::string &batch_string) {
InternalKey ikey(key, storage_->IsSlotIdEncoded());
Slice entry_id = ikey.GetSubKey();
Redis::StreamEntryID id;
- GetFixed64(&entry_id, &id.ms);
- GetFixed64(&entry_id, &id.seq);
+ GetFixed64(&entry_id, &id.ms_);
+ GetFixed64(&entry_id, &id.seq_);
srv_->OnEntryAddedToStream(ikey.GetNamespace().ToString(), ikey.GetKey().ToString(), id);
break;
}
diff --git a/src/cluster/replication.h b/src/cluster/replication.h
index 16818ce2..87b3dcc6 100644
--- a/src/cluster/replication.h
+++ b/src/cluster/replication.h
@@ -75,15 +75,16 @@ class FeedSlaveThread {
}
private:
- uint64_t interval = 0;
+ uint64_t interval_ = 0;
std::atomic<bool> stop_ = false;
Server *srv_ = nullptr;
std::unique_ptr<Redis::Connection> conn_ = nullptr;
std::atomic<rocksdb::SequenceNumber> next_repl_seq_ = 0;
std::thread t_;
std::unique_ptr<rocksdb::TransactionLogIterator> iter_ = nullptr;
- const size_t kMaxDelayUpdates = 16;
- const size_t kMaxDelayBytes = 16 * 1024;
+
+ static const size_t kMaxDelayUpdates = 16;
+ static const size_t kMaxDelayBytes = 16 * 1024;
void loop();
void checkLivenessIfNeed();
diff --git a/src/cluster/slot_migrate.cc b/src/cluster/slot_migrate.cc
index 9c8305f4..5be8fea3 100644
--- a/src/cluster/slot_migrate.cc
+++ b/src/cluster/slot_migrate.cc
@@ -263,7 +263,7 @@ Status SlotMigrator::StartMigration() {
dst_fd_.Reset(*result);
// Auth first
- std::string pass = svr_->GetConfig()->requirepass;
+ std::string pass = svr_->GetConfig()->requirepass_;
if (!pass.empty()) {
auto s = AuthOnDstNode(*dst_fd_, pass);
if (!s.IsOK()) {
@@ -520,9 +520,9 @@ Status SlotMigrator::CheckMultipleResponses(int sock_fd, int total) {
}
if (line[0] == '-') {
- return {Status::NotOK, fmt::format("got invalid response of length {}: {}", line.length, line.get())};
+ return {Status::NotOK, fmt::format("got invalid response of length {}: {}", line.length_, line.get())};
} else if (line[0] == '$') {
- auto parse_result = ParseInt<uint64_t>(std::string(line.get() + 1, line.length - 1), 10);
+ auto parse_result = ParseInt<uint64_t>(std::string(line.get() + 1, line.length_ - 1), 10);
if (!parse_result) {
return {Status::NotOK, "protocol error: expected integer value"};
}
@@ -532,7 +532,7 @@ Status SlotMigrator::CheckMultipleResponses(int sock_fd, int total) {
} else if (line[0] == '+' || line[0] == ':') {
parser_state_ = ParserState::OneRspEnd;
} else {
- return {Status::NotOK, fmt::format("got unexpected response of length {}: {}", line.length, line.get())};
+ return {Status::NotOK, fmt::format("got unexpected response of length {}: {}", line.length_, line.get())};
}
break;
@@ -573,7 +573,7 @@ StatusOr<KeyMigrationResult> SlotMigrator::MigrateOneKey(const rocksdb::Slice &k
Metadata metadata(kRedisNone, false);
metadata.Decode(bytes);
- if (metadata.Type() != kRedisString && metadata.Type() != kRedisStream && metadata.size == 0) {
+ if (metadata.Type() != kRedisString && metadata.Type() != kRedisStream && metadata.size_ == 0) {
return KeyMigrationResult::kUnderlyingStructEmpty;
}
@@ -622,9 +622,9 @@ StatusOr<KeyMigrationResult> SlotMigrator::MigrateOneKey(const rocksdb::Slice &k
Status SlotMigrator::MigrateSimpleKey(const rocksdb::Slice &key, const Metadata &metadata, const std::string &bytes,
std::string *restore_cmds) {
std::vector<std::string> command = {"SET", key.ToString(), bytes.substr(Metadata::GetOffsetAfterExpire(bytes[0]))};
- if (metadata.expire > 0) {
+ if (metadata.expire_ > 0) {
command.emplace_back("PXAT");
- command.emplace_back(std::to_string(metadata.expire));
+ command.emplace_back(std::to_string(metadata.expire_));
}
*restore_cmds += Redis::MultiBulkString(command, false);
current_pipeline_size_++;
@@ -653,7 +653,7 @@ Status SlotMigrator::MigrateComplexKey(const rocksdb::Slice &key, const Metadata
// Construct key prefix to iterate values of the complex type user key
std::string slot_key, prefix_subkey;
AppendNamespacePrefix(key, &slot_key);
- InternalKey(slot_key, "", metadata.version, true).Encode(&prefix_subkey);
+ InternalKey(slot_key, "", metadata.version_, true).Encode(&prefix_subkey);
int item_count = 0;
for (iter->Seek(prefix_subkey); iter->Valid(); iter->Next()) {
@@ -731,8 +731,8 @@ Status SlotMigrator::MigrateComplexKey(const rocksdb::Slice &key, const Metadata
}
// Add TTL for complex key
- if (metadata.expire > 0) {
- *restore_cmds += Redis::MultiBulkString({"PEXPIREAT", key.ToString(), std::to_string(metadata.expire)}, false);
+ if (metadata.expire_ > 0) {
+ *restore_cmds += Redis::MultiBulkString({"PEXPIREAT", key.ToString(), std::to_string(metadata.expire_)}, false);
current_pipeline_size_++;
}
@@ -757,7 +757,7 @@ Status SlotMigrator::MigrateStream(const Slice &key, const StreamMetadata &metad
AppendNamespacePrefix(key, &ns_key);
// Construct key prefix to iterate values of the stream
std::string prefix_key;
- InternalKey(ns_key, "", metadata.version, true).Encode(&prefix_key);
+ InternalKey(ns_key, "", metadata.version_, true).Encode(&prefix_key);
std::vector<std::string> user_cmd = {type_to_cmd[metadata.Type()], key.ToString()};
@@ -788,14 +788,14 @@ Status SlotMigrator::MigrateStream(const Slice &key, const StreamMetadata &metad
// commands like XTRIM and XDEL affect stream's metadata, but we use only XADD for a slot migration
// XSETID is used to adjust stream's info on the destination node according to the current values on the source
*restore_cmds += Redis::MultiBulkString(
- {"XSETID", key.ToString(), metadata.last_generated_id.ToString(), "ENTRIESADDED",
- std::to_string(metadata.entries_added), "MAXDELETEDID", metadata.max_deleted_entry_id.ToString()},
+ {"XSETID", key.ToString(), metadata.last_generated_id_.ToString(), "ENTRIESADDED",
+ std::to_string(metadata.entries_added_), "MAXDELETEDID", metadata.max_deleted_entry_id_.ToString()},
false);
current_pipeline_size_++;
// Add TTL
- if (metadata.expire > 0) {
- *restore_cmds += Redis::MultiBulkString({"PEXPIREAT", key.ToString(), std::to_string(metadata.expire)}, false);
+ if (metadata.expire_ > 0) {
+ *restore_cmds += Redis::MultiBulkString({"PEXPIREAT", key.ToString(), std::to_string(metadata.expire_)}, false);
current_pipeline_size_++;
}
diff --git a/src/commands/cmd_cluster.cc b/src/commands/cmd_cluster.cc
index 682c0c40..fb1c0dee 100644
--- a/src/commands/cmd_cluster.cc
+++ b/src/commands/cmd_cluster.cc
@@ -49,7 +49,7 @@ class CommandCluster : public Commander {
}
Status Execute(Server *svr, Connection *conn, std::string *output) override {
- if (!svr->GetConfig()->cluster_enabled) {
+ if (!svr->GetConfig()->cluster_enabled_) {
*output = Redis::Error("Cluster mode is not enabled");
return Status::OK();
}
@@ -68,14 +68,14 @@ class CommandCluster : public Commander {
if (s.IsOK()) {
output->append(Redis::MultiLen(infos.size()));
for (const auto &info : infos) {
- output->append(Redis::MultiLen(info.nodes.size() + 2));
- output->append(Redis::Integer(info.start));
- output->append(Redis::Integer(info.end));
- for (const auto &n : info.nodes) {
+ output->append(Redis::MultiLen(info.nodes_.size() + 2));
+ output->append(Redis::Integer(info.start_));
+ output->append(Redis::Integer(info.end_));
+ for (const auto &n : info.nodes_) {
output->append(Redis::MultiLen(3));
- output->append(Redis::BulkString(n.host));
- output->append(Redis::Integer(n.port));
- output->append(Redis::BulkString(n.id));
+ output->append(Redis::BulkString(n.host_));
+ output->append(Redis::Integer(n.port_));
+ output->append(Redis::BulkString(n.id_));
}
}
} else {
@@ -191,7 +191,7 @@ class CommandClusterX : public Commander {
}
Status Execute(Server *svr, Connection *conn, std::string *output) override {
- if (!svr->GetConfig()->cluster_enabled) {
+ if (!svr->GetConfig()->cluster_enabled_) {
*output = Redis::Error("Cluster mode is not enabled");
return Status::OK();
}
@@ -239,7 +239,7 @@ class CommandClusterX : public Commander {
} else {
*output = Redis::Error("Invalid cluster command options");
}
- if (need_persist_nodes_info && svr->GetConfig()->persist_cluster_nodes_enabled) {
+ if (need_persist_nodes_info && svr->GetConfig()->persist_cluster_nodes_enabled_) {
return svr->cluster_->DumpClusterNodes(svr->GetConfig()->NodesFilePath());
}
return Status::OK();
diff --git a/src/commands/cmd_geo.cc b/src/commands/cmd_geo.cc
index ae919145..1be874a8 100644
--- a/src/commands/cmd_geo.cc
+++ b/src/commands/cmd_geo.cc
@@ -199,7 +199,7 @@ class CommandGeoPos : public Commander {
list.emplace_back(Redis::NilString());
} else {
list.emplace_back(Redis::MultiBulkString(
- {Util::Float2String(iter->second.longitude), Util::Float2String(iter->second.latitude)}));
+ {Util::Float2String(iter->second.longitude_), Util::Float2String(iter->second.latitude_)}));
}
}
*output = Redis::Array(list);
@@ -309,19 +309,19 @@ class CommandGeoRadius : public CommandGeoBase {
for (int i = 0; i < returned_items_count; i++) {
auto geo_point = geo_points[i];
if (!with_coord_ && !with_hash_ && !with_dist_) {
- list.emplace_back(Redis::BulkString(geo_point.member));
+ list.emplace_back(Redis::BulkString(geo_point.member_));
} else {
std::vector<std::string> one;
- one.emplace_back(Redis::BulkString(geo_point.member));
+ one.emplace_back(Redis::BulkString(geo_point.member_));
if (with_dist_) {
- one.emplace_back(Redis::BulkString(Util::Float2String(GetDistanceByUnit(geo_point.dist))));
+ one.emplace_back(Redis::BulkString(Util::Float2String(GetDistanceByUnit(geo_point.dist_))));
}
if (with_hash_) {
- one.emplace_back(Redis::BulkString(Util::Float2String(geo_point.score)));
+ one.emplace_back(Redis::BulkString(Util::Float2String(geo_point.score_)));
}
if (with_coord_) {
one.emplace_back(Redis::MultiBulkString(
- {Util::Float2String(geo_point.longitude), Util::Float2String(geo_point.latitude)}));
+ {Util::Float2String(geo_point.longitude_), Util::Float2String(geo_point.latitude_)}));
}
list.emplace_back(Redis::Array(one));
}
diff --git a/src/commands/cmd_hash.cc b/src/commands/cmd_hash.cc
index 6f1810b2..b3717f6e 100644
--- a/src/commands/cmd_hash.cc
+++ b/src/commands/cmd_hash.cc
@@ -236,7 +236,7 @@ class CommandHMSet : public Commander {
return {Status::RedisExecErr, s.ToString()};
}
- if (GetAttributes()->name == "hset") {
+ if (GetAttributes()->name_ == "hset") {
*output = Redis::Integer(ret);
} else {
*output = Redis::SimpleString("OK");
@@ -261,7 +261,7 @@ class CommandHKeys : public Commander {
std::vector<std::string> keys;
keys.reserve(field_values.size());
for (const auto &fv : field_values) {
- keys.emplace_back(fv.field);
+ keys.emplace_back(fv.field_);
}
*output = Redis::MultiBulkString(keys);
@@ -282,7 +282,7 @@ class CommandHVals : public Commander {
std::vector<std::string> values;
values.reserve(field_values.size());
for (const auto &p : field_values) {
- values.emplace_back(p.value);
+ values.emplace_back(p.value_);
}
*output = MultiBulkString(values, false);
@@ -303,8 +303,8 @@ class CommandHGetAll : public Commander {
std::vector<std::string> kv_pairs;
kv_pairs.reserve(field_values.size());
for (const auto &p : field_values) {
- kv_pairs.emplace_back(p.field);
- kv_pairs.emplace_back(p.value);
+ kv_pairs.emplace_back(p.field_);
+ kv_pairs.emplace_back(p.value_);
}
*output = MultiBulkString(kv_pairs, false);
@@ -318,16 +318,16 @@ class CommandHRangeByLex : public Commander {
CommandParser parser(args, 4);
while (parser.Good()) {
if (parser.EatEqICase("REV")) {
- spec_.reversed = true;
+ spec_.reversed_ = true;
} else if (parser.EatEqICase("LIMIT")) {
- spec_.offset = GET_OR_RET(parser.TakeInt());
- spec_.count = GET_OR_RET(parser.TakeInt());
+ spec_.offset_ = GET_OR_RET(parser.TakeInt());
+ spec_.count_ = GET_OR_RET(parser.TakeInt());
} else {
return parser.InvalidSyntax();
}
}
Status s;
- if (spec_.reversed) {
+ if (spec_.reversed_) {
s = ParseRangeLexSpec(args[3], args[2], &spec_);
} else {
s = ParseRangeLexSpec(args[2], args[3], &spec_);
@@ -347,8 +347,8 @@ class CommandHRangeByLex : public Commander {
}
std::vector<std::string> kv_pairs;
for (const auto &p : field_values) {
- kv_pairs.emplace_back(p.field);
- kv_pairs.emplace_back(p.value);
+ kv_pairs.emplace_back(p.field_);
+ kv_pairs.emplace_back(p.value_);
}
*output = MultiBulkString(kv_pairs, false);
@@ -366,7 +366,7 @@ class CommandHScan : public CommandSubkeyScanBase {
Redis::Hash hash_db(svr->storage_, conn->GetNamespace());
std::vector<std::string> fields;
std::vector<std::string> values;
- auto s = hash_db.Scan(key, cursor, limit, prefix, &fields, &values);
+ auto s = hash_db.Scan(key_, cursor_, limit_, prefix_, &fields, &values);
if (!s.ok() && !s.IsNotFound()) {
return {Status::RedisExecErr, s.ToString()};
}
diff --git a/src/commands/cmd_list.cc b/src/commands/cmd_list.cc
index 3fc33cfa..a7ebf3f2 100644
--- a/src/commands/cmd_list.cc
+++ b/src/commands/cmd_list.cc
@@ -234,7 +234,7 @@ class CommandBPop : public Commander {
}
} else if (!s.IsNotFound()) {
conn_->Reply(Redis::Error("ERR " + s.ToString()));
- LOG(ERROR) << "Failed to execute redis command: " << conn_->current_cmd_->GetAttributes()->name
+ LOG(ERROR) << "Failed to execute redis command: " << conn_->current_cmd_->GetAttributes()->name_
<< ", err: " << s.ToString();
}
diff --git a/src/commands/cmd_pubsub.cc b/src/commands/cmd_pubsub.cc
index 89931ae8..139d63b6 100644
--- a/src/commands/cmd_pubsub.cc
+++ b/src/commands/cmd_pubsub.cc
@@ -147,8 +147,8 @@ class CommandPubSub : public Commander {
output->append(Redis::MultiLen(channel_subscribe_nums.size() * 2));
for (const auto &chan_subscribe_num : channel_subscribe_nums) {
- output->append(Redis::BulkString(chan_subscribe_num.channel));
- output->append(Redis::Integer(chan_subscribe_num.subscribe_num));
+ output->append(Redis::BulkString(chan_subscribe_num.channel_));
+ output->append(Redis::Integer(chan_subscribe_num.subscribe_num_));
}
return Status::OK();
diff --git a/src/commands/cmd_replication.cc b/src/commands/cmd_replication.cc
index 0c1bff21..fb7ddbd0 100644
--- a/src/commands/cmd_replication.cc
+++ b/src/commands/cmd_replication.cc
@@ -35,7 +35,7 @@ class CommandPSync : public Commander {
size_t seq_arg = 1;
if (args.size() == 3) {
seq_arg = 2;
- new_psync = true;
+ new_psync_ = true;
}
auto parse_result = ParseInt<uint64_t>(args[seq_arg], 10);
@@ -43,11 +43,11 @@ class CommandPSync : public Commander {
return {Status::RedisParseErr, "value is not an unsigned long long or out of range"};
}
- next_repl_seq = static_cast<rocksdb::SequenceNumber>(*parse_result);
- if (new_psync) {
+ next_repl_seq_ = static_cast<rocksdb::SequenceNumber>(*parse_result);
+ if (new_psync_) {
assert(args.size() == 3);
- replica_replid = args[1];
- if (replica_replid.size() != kReplIdLength) {
+ replica_replid_ = args[1];
+ if (replica_replid_.size() != kReplIdLength) {
return {Status::RedisParseErr, "Wrong replication id length"};
}
}
@@ -58,27 +58,27 @@ class CommandPSync : public Commander {
Status Execute(Server *svr, Connection *conn, std::string *output) override {
LOG(INFO) << "Slave " << conn->GetAddr() << ", listening port: " << conn->GetListeningPort()
<< ", announce ip: " << conn->GetAnnounceIP() << " asks for synchronization"
- << " with next sequence: " << next_repl_seq
- << " replication id: " << (replica_replid.length() ? replica_replid : "not supported")
+ << " with next sequence: " << next_repl_seq_
+ << " replication id: " << (replica_replid_.length() ? replica_replid_ : "not supported")
<< ", and local sequence: " << svr->storage_->LatestSeqNumber();
bool need_full_sync = false;
// Check replication id of the last sequence log
- if (new_psync && svr->GetConfig()->use_rsid_psync) {
- std::string replid_in_wal = svr->storage_->GetReplIdFromWalBySeq(next_repl_seq - 1);
+ if (new_psync_ && svr->GetConfig()->use_rsid_psync_) {
+ std::string replid_in_wal = svr->storage_->GetReplIdFromWalBySeq(next_repl_seq_ - 1);
LOG(INFO) << "Replication id in WAL: " << replid_in_wal;
// We check replication id only when WAL has this sequence, since there may be no WAL,
// Or WAL may have nothing when starting from db of old version kvrocks.
- if (replid_in_wal.length() == kReplIdLength && replid_in_wal != replica_replid) {
+ if (replid_in_wal.length() == kReplIdLength && replid_in_wal != replica_replid_) {
*output = "wrong replication id of the last log";
need_full_sync = true;
}
}
// Check Log sequence
- if (!need_full_sync && !checkWALBoundary(svr->storage_, next_repl_seq).IsOK()) {
+ if (!need_full_sync && !checkWALBoundary(svr->storage_, next_repl_seq_).IsOK()) {
*output = "sequence out of range, please use fullsync";
need_full_sync = true;
}
@@ -99,7 +99,7 @@ class CommandPSync : public Commander {
}
svr->stats_.IncrPSyncOKCounter();
- s = svr->AddSlave(conn, next_repl_seq);
+ s = svr->AddSlave(conn, next_repl_seq_);
if (!s.IsOK()) {
std::string err = "-ERR " + s.Msg() + "\r\n";
s = Util::SockSend(conn->GetFD(), err);
@@ -115,9 +115,9 @@ class CommandPSync : public Commander {
}
private:
- rocksdb::SequenceNumber next_repl_seq = 0;
- bool new_psync = false;
- std::string replica_replid;
+ rocksdb::SequenceNumber next_repl_seq_ = 0;
+ bool new_psync_ = false;
+ std::string replica_replid_;
// Return OK if the seq is in the range of the current WAL
static Status checkWALBoundary(Engine::Storage *storage, rocksdb::SequenceNumber seq) {
@@ -283,8 +283,8 @@ class CommandFetchFile : public Commander {
if (svr->IsStopped()) break;
uint64_t file_size = 0, max_replication_bytes = 0;
- if (svr->GetConfig()->max_replication_mb > 0) {
- max_replication_bytes = (svr->GetConfig()->max_replication_mb * MiB) / svr->GetFetchFileThreadNum();
+ if (svr->GetConfig()->max_replication_mb_ > 0) {
+ max_replication_bytes = (svr->GetConfig()->max_replication_mb_ * MiB) / svr->GetFetchFileThreadNum();
}
auto start = std::chrono::high_resolution_clock::now();
auto fd = UniqueFD(Engine::Storage::ReplDataManager::OpenDataFile(svr->storage_, file, &file_size));
diff --git a/src/commands/cmd_server.cc b/src/commands/cmd_server.cc
index 9e1ca8e4..fc12f181 100644
--- a/src/commands/cmd_server.cc
+++ b/src/commands/cmd_server.cc
@@ -35,14 +35,14 @@ enum class AuthResult {
};
AuthResult AuthenticateUser(Connection *conn, Config *config, const std::string &user_password) {
- auto iter = config->tokens.find(user_password);
- if (iter != config->tokens.end()) {
+ auto iter = config->tokens_.find(user_password);
+ if (iter != config->tokens_.end()) {
conn->SetNamespace(iter->second);
conn->BecomeUser();
return AuthResult::OK;
}
- const auto &requirepass = config->requirepass;
+ const auto &requirepass = config->requirepass_;
if (!requirepass.empty() && user_password != requirepass) {
return AuthResult::INVALID_PASSWORD;
}
@@ -90,13 +90,13 @@ class CommandNamespace : public Commander {
if (args_.size() == 3 && sub_command == "get") {
if (args_[2] == "*") {
std::vector<std::string> namespaces;
- auto tokens = config->tokens;
+ auto tokens = config->tokens_;
for (auto &token : tokens) {
namespaces.emplace_back(token.second); // namespace
namespaces.emplace_back(token.first); // token
}
namespaces.emplace_back(kDefaultNamespace);
- namespaces.emplace_back(config->requirepass);
+ namespaces.emplace_back(config->requirepass_);
*output = Redis::MultiBulkString(namespaces, false);
} else {
std::string token;
@@ -152,7 +152,7 @@ class CommandKeys : public Commander {
class CommandFlushDB : public Commander {
public:
Status Execute(Server *svr, Connection *conn, std::string *output) override {
- if (svr->GetConfig()->cluster_enabled) {
+ if (svr->GetConfig()->cluster_enabled_) {
if (svr->slot_migrator_->IsMigrationInProgress()) {
svr->slot_migrator_->SetStopMigrationFlag(true);
LOG(INFO) << "Stop migration task for flushdb";
@@ -178,7 +178,7 @@ class CommandFlushAll : public Commander {
return Status::OK();
}
- if (svr->GetConfig()->cluster_enabled) {
+ if (svr->GetConfig()->cluster_enabled_) {
if (svr->slot_migrator_->IsMigrationInProgress()) {
svr->slot_migrator_->SetStopMigrationFlag(true);
LOG(INFO) << "Stop migration task for flushall";
@@ -313,7 +313,7 @@ class CommandDBSize : public Commander {
if (args_.size() == 1) {
KeyNumStats stats;
svr->GetLatestKeyNumStats(ns, &stats);
- *output = Redis::Integer(stats.n_key);
+ *output = Redis::Integer(stats.n_key_);
} else if (args_.size() == 2 && args_[1] == "scan") {
Status s = svr->AsyncScanDBSize(ns);
if (s.IsOK()) {
@@ -697,7 +697,7 @@ class CommandHello final : public Commander {
output_list.push_back(Redis::BulkString("mode"));
// Note: sentinel is not supported in kvrocks.
- if (svr->GetConfig()->cluster_enabled) {
+ if (svr->GetConfig()->cluster_enabled_) {
output_list.push_back(Redis::BulkString("cluster"));
} else {
output_list.push_back(Redis::BulkString("standalone"));
@@ -751,7 +751,7 @@ class CommandScan : public CommandScanBase {
Redis::Database redis_db(svr->storage_, conn->GetNamespace());
std::vector<std::string> keys;
std::string end_cursor;
- auto s = redis_db.Scan(cursor, limit, prefix, &keys, &end_cursor);
+ auto s = redis_db.Scan(cursor_, limit_, prefix_, &keys, &end_cursor);
if (!s.ok()) {
return {Status::RedisExecErr, s.ToString()};
}
@@ -859,11 +859,11 @@ class CommandSlaveOf : public Commander {
}
Status Execute(Server *svr, Connection *conn, std::string *output) override {
- if (svr->GetConfig()->cluster_enabled) {
+ if (svr->GetConfig()->cluster_enabled_) {
return {Status::RedisExecErr, "can't change to slave in cluster mode"};
}
- if (svr->GetConfig()->RocksDB.write_options.disable_WAL) {
+ if (svr->GetConfig()->rocks_db_.write_options_.disable_wal_) {
return {Status::RedisExecErr, "slaveof doesn't work with disable_wal option"};
}
@@ -880,7 +880,7 @@ class CommandSlaveOf : public Commander {
*output = Redis::SimpleString("OK");
LOG(WARNING) << "MASTER MODE enabled (user request from '" << conn->GetAddr() << "')";
- if (svr->GetConfig()->cluster_enabled) {
+ if (svr->GetConfig()->cluster_enabled_) {
svr->slot_migrator_->SetStopMigrationFlag(false);
LOG(INFO) << "Change server role to master, restart migration task";
}
@@ -893,7 +893,7 @@ class CommandSlaveOf : public Commander {
*output = Redis::SimpleString("OK");
LOG(WARNING) << "SLAVE OF " << host_ << ":" << port_ << " enabled (user request from '" << conn->GetAddr()
<< "')";
- if (svr->GetConfig()->cluster_enabled) {
+ if (svr->GetConfig()->cluster_enabled_) {
svr->slot_migrator_->SetStopMigrationFlag(true);
LOG(INFO) << "Change server role to slave, stop migration task";
}
diff --git a/src/commands/cmd_set.cc b/src/commands/cmd_set.cc
index 73787c22..842493e7 100644
--- a/src/commands/cmd_set.cc
+++ b/src/commands/cmd_set.cc
@@ -349,7 +349,7 @@ class CommandSScan : public CommandSubkeyScanBase {
Status Execute(Server *svr, Connection *conn, std::string *output) override {
Redis::Set set_db(svr->storage_, conn->GetNamespace());
std::vector<std::string> members;
- auto s = set_db.Scan(key, cursor, limit, prefix, &members);
+ auto s = set_db.Scan(key_, cursor_, limit_, prefix_, &members);
if (!s.ok() && !s.IsNotFound()) {
return {Status::RedisExecErr, s.ToString()};
}
diff --git a/src/commands/cmd_sortedint.cc b/src/commands/cmd_sortedint.cc
index 5e8166d9..51ef127c 100644
--- a/src/commands/cmd_sortedint.cc
+++ b/src/commands/cmd_sortedint.cc
@@ -192,11 +192,11 @@ class CommandSortedintRevRange : public CommandSortedintRange {
class CommandSortedintRangeByValue : public Commander {
public:
- explicit CommandSortedintRangeByValue(bool reversed = false) { spec_.reversed = reversed; }
+ explicit CommandSortedintRangeByValue(bool reversed = false) { spec_.reversed_ = reversed; }
Status Parse(const std::vector<std::string> &args) override {
Status s;
- if (spec_.reversed) {
+ if (spec_.reversed_) {
s = Redis::Sortedint::ParseRangeSpec(args[3], args[2], &spec_);
} else {
s = Redis::Sortedint::ParseRangeSpec(args[2], args[3], &spec_);
@@ -216,8 +216,8 @@ class CommandSortedintRangeByValue : public Commander {
return {Status::RedisParseErr, errValueNotInteger};
}
- spec_.offset = *parse_offset;
- spec_.count = *parse_count;
+ spec_.offset_ = *parse_offset;
+ spec_.count_ = *parse_count;
}
return Commander::Parse(args);
diff --git a/src/commands/cmd_stream.cc b/src/commands/cmd_stream.cc
index 44047199..8e04cdc3 100644
--- a/src/commands/cmd_stream.cc
+++ b/src/commands/cmd_stream.cc
@@ -133,18 +133,18 @@ class CommandXAdd : public Commander {
Status Execute(Server *svr, Connection *conn, std::string *output) override {
Redis::StreamAddOptions options;
- options.nomkstream = nomkstream_;
+ options.nomkstream_ = nomkstream_;
if (with_max_len_) {
- options.trim_options.strategy = StreamTrimStrategy::MaxLen;
- options.trim_options.max_len = max_len_;
+ options.trim_options_.strategy_ = StreamTrimStrategy::MaxLen;
+ options.trim_options_.max_len_ = max_len_;
}
if (with_min_id_) {
- options.trim_options.strategy = StreamTrimStrategy::MinID;
- options.trim_options.min_id = min_id_;
+ options.trim_options_.strategy_ = StreamTrimStrategy::MinID;
+ options.trim_options_.min_id_ = min_id_;
}
if (with_entry_id_) {
- options.with_entry_id = true;
- options.entry_id = entry_id_;
+ options.with_entry_id_ = true;
+ options.entry_id_ = entry_id_;
}
Redis::Stream stream_db(svr->storage_, conn->GetNamespace());
@@ -218,12 +218,12 @@ class CommandXLen : public Commander {
auto s = Redis::ParseStreamEntryID(args[2], &id);
if (!s.IsOK()) return s;
- options_.with_entry_id = true;
- options_.entry_id = id;
+ options_.with_entry_id_ = true;
+ options_.entry_id_ = id;
if (args.size() > 3) {
if (args[3] == "-") {
- options_.to_first = true;
+ options_.to_first_ = true;
} else if (args[3] != "+") {
return {Status::RedisParseErr, errInvalidSyntax};
}
@@ -303,39 +303,39 @@ class CommandXInfo : public Commander {
output->append(Redis::MultiLen(12));
}
output->append(Redis::BulkString("length"));
- output->append(Redis::Integer(info.size));
+ output->append(Redis::Integer(info.size_));
output->append(Redis::BulkString("last-generated-id"));
- output->append(Redis::BulkString(info.last_generated_id.ToString()));
+ output->append(Redis::BulkString(info.last_generated_id_.ToString()));
output->append(Redis::BulkString("max-deleted-entry-id"));
- output->append(Redis::BulkString(info.max_deleted_entry_id.ToString()));
+ output->append(Redis::BulkString(info.max_deleted_entry_id_.ToString()));
output->append(Redis::BulkString("entries-added"));
- output->append(Redis::Integer(info.entries_added));
+ output->append(Redis::Integer(info.entries_added_));
output->append(Redis::BulkString("recorded-first-entry-id"));
- output->append(Redis::BulkString(info.recorded_first_entry_id.ToString()));
+ output->append(Redis::BulkString(info.recorded_first_entry_id_.ToString()));
if (!full_) {
output->append(Redis::BulkString("first-entry"));
- if (info.first_entry) {
+ if (info.first_entry_) {
output->append(Redis::MultiLen(2));
- output->append(Redis::BulkString(info.first_entry->key));
- output->append(Redis::MultiBulkString(info.first_entry->values));
+ output->append(Redis::BulkString(info.first_entry_->key_));
+ output->append(Redis::MultiBulkString(info.first_entry_->values_));
} else {
output->append(Redis::NilString());
}
output->append(Redis::BulkString("last-entry"));
- if (info.last_entry) {
+ if (info.last_entry_) {
output->append(Redis::MultiLen(2));
- output->append(Redis::BulkString(info.last_entry->key));
- output->append(Redis::MultiBulkString(info.last_entry->values));
+ output->append(Redis::BulkString(info.last_entry_->key_));
+ output->append(Redis::MultiBulkString(info.last_entry_->values_));
} else {
output->append(Redis::NilString());
}
} else {
output->append(Redis::BulkString("entries"));
- output->append(Redis::MultiLen(info.entries.size()));
- for (const auto &e : info.entries) {
+ output->append(Redis::MultiLen(info.entries_.size()));
+ for (const auto &e : info.entries_) {
output->append(Redis::MultiLen(2));
- output->append(Redis::BulkString(e.key));
- output->append(Redis::MultiBulkString(e.values));
+ output->append(Redis::BulkString(e.key_));
+ output->append(Redis::MultiBulkString(e.values_));
}
}
@@ -401,13 +401,13 @@ class CommandXRange : public Commander {
Redis::Stream stream_db(svr->storage_, conn->GetNamespace());
Redis::StreamRangeOptions options;
- options.reverse = false;
- options.start = start_;
- options.end = end_;
- options.with_count = with_count_;
- options.count = count_;
- options.exclude_start = exclude_start_;
- options.exclude_end = exclude_end_;
+ options.reverse_ = false;
+ options.start_ = start_;
+ options.end_ = end_;
+ options.with_count_ = with_count_;
+ options.count_ = count_;
+ options.exclude_start_ = exclude_start_;
+ options.exclude_end_ = exclude_end_;
std::vector<StreamEntry> result;
auto s = stream_db.Range(stream_name_, options, &result);
@@ -419,8 +419,8 @@ class CommandXRange : public Commander {
for (const auto &e : result) {
output->append(Redis::MultiLen(2));
- output->append(Redis::BulkString(e.key));
- output->append(Redis::MultiBulkString(e.values));
+ output->append(Redis::BulkString(e.key_));
+ output->append(Redis::MultiBulkString(e.values_));
}
return Status::OK();
@@ -494,13 +494,13 @@ class CommandXRevRange : public Commander {
Redis::Stream stream_db(svr->storage_, conn->GetNamespace());
Redis::StreamRangeOptions options;
- options.reverse = true;
- options.start = start_;
- options.end = end_;
- options.with_count = with_count_;
- options.count = count_;
- options.exclude_start = exclude_start_;
- options.exclude_end = exclude_end_;
+ options.reverse_ = true;
+ options.start_ = start_;
+ options.end_ = end_;
+ options.with_count_ = with_count_;
+ options.count_ = count_;
+ options.exclude_start_ = exclude_start_;
+ options.exclude_end_ = exclude_end_;
std::vector<StreamEntry> result;
auto s = stream_db.Range(stream_name_, options, &result);
@@ -512,8 +512,8 @@ class CommandXRevRange : public Commander {
for (const auto &e : result) {
output->append(Redis::MultiLen(2));
- output->append(Redis::BulkString(e.key));
- output->append(Redis::MultiBulkString(e.values));
+ output->append(Redis::BulkString(e.key_));
+ output->append(Redis::MultiBulkString(e.values_));
}
return Status::OK();
@@ -622,13 +622,13 @@ class CommandXRead : public Commander {
}
Redis::StreamRangeOptions options;
- options.reverse = false;
- options.start = ids_[i];
- options.end = StreamEntryID{UINT64_MAX, UINT64_MAX};
- options.with_count = with_count_;
- options.count = count_;
- options.exclude_start = true;
- options.exclude_end = false;
+ options.reverse_ = false;
+ options.start_ = ids_[i];
+ options.end_ = StreamEntryID{UINT64_MAX, UINT64_MAX};
+ options.with_count_ = with_count_;
+ options.count_ = count_;
+ options.exclude_start_ = true;
+ options.exclude_end_ = false;
std::vector<StreamEntry> result;
auto s = stream_db.Range(streams_[i], options, &result);
@@ -663,12 +663,12 @@ class CommandXRead : public Commander {
for (const auto &result : results) {
output->append(Redis::MultiLen(2));
- output->append(Redis::BulkString(result.name));
- output->append(Redis::MultiLen(result.entries.size()));
- for (const auto &entry : result.entries) {
+ output->append(Redis::BulkString(result.name_));
+ output->append(Redis::MultiLen(result.entries_.size()));
+ for (const auto &entry : result.entries_) {
output->append(Redis::MultiLen(2));
- output->append(Redis::BulkString(entry.key));
- output->append(Redis::MultiBulkString(entry.values));
+ output->append(Redis::BulkString(entry.key_));
+ output->append(Redis::MultiBulkString(entry.values_));
}
}
@@ -737,20 +737,20 @@ class CommandXRead : public Commander {
for (size_t i = 0; i < command->streams_.size(); ++i) {
Redis::StreamRangeOptions options;
- options.reverse = false;
- options.start = command->ids_[i];
- options.end = StreamEntryID{UINT64_MAX, UINT64_MAX};
- options.with_count = command->with_count_;
- options.count = command->count_;
- options.exclude_start = true;
- options.exclude_end = false;
+ options.reverse_ = false;
+ options.start_ = command->ids_[i];
+ options.end_ = StreamEntryID{UINT64_MAX, UINT64_MAX};
+ options.with_count_ = command->with_count_;
+ options.count_ = command->count_;
+ options.exclude_start_ = true;
+ options.exclude_end_ = false;
std::vector<StreamEntry> result;
auto s = stream_db.Range(command->streams_[i], options, &result);
if (!s.ok()) {
command->conn_->Reply(Redis::MultiLen(-1));
LOG(ERROR) << "ERR executing XRANGE for stream " << command->streams_[i] << " from "
- << command->ids_[i].ToString() << " to " << options.end.ToString() << " with count "
+ << command->ids_[i].ToString() << " to " << options.end_.ToString() << " with count "
<< command->count_ << ": " << s.ToString();
}
@@ -773,12 +773,12 @@ class CommandXRead : public Commander {
for (const auto &result : results) {
output.append(Redis::MultiLen(2));
- output.append(Redis::BulkString(result.name));
- output.append(Redis::MultiLen(result.entries.size()));
- for (const auto &entry : result.entries) {
+ output.append(Redis::BulkString(result.name_));
+ output.append(Redis::MultiLen(result.entries_.size()));
+ for (const auto &entry : result.entries_) {
output.append(Redis::MultiLen(2));
- output.append(Redis::BulkString(entry.key));
- output.append(Redis::MultiBulkString(entry.values));
+ output.append(Redis::BulkString(entry.key_));
+ output.append(Redis::MultiBulkString(entry.values_));
}
}
@@ -902,9 +902,9 @@ class CommandXTrim : public Commander {
Redis::Stream stream_db(svr->storage_, conn->GetNamespace());
StreamTrimOptions options;
- options.strategy = strategy_;
- options.max_len = max_len_;
- options.min_id = min_id_;
+ options.strategy_ = strategy_;
+ options.max_len_ = max_len_;
+ options.min_id_ = min_id_;
uint64_t removed = 0;
auto s = stream_db.Trim(args_[1], options, &removed);
@@ -953,7 +953,7 @@ class CommandXSetId : public Commander {
return {Status::RedisParseErr, s.Msg()};
}
- max_deleted_id_ = std::make_optional<StreamEntryID>(id.ms, id.seq);
+ max_deleted_id_ = std::make_optional<StreamEntryID>(id.ms_, id.seq_);
i += 2;
} else {
return {Status::RedisParseErr, errInvalidSyntax};
diff --git a/src/commands/cmd_string.cc b/src/commands/cmd_string.cc
index 92d8d555..a86b8542 100644
--- a/src/commands/cmd_string.cc
+++ b/src/commands/cmd_string.cc
@@ -43,7 +43,7 @@ class CommandGet : public Commander {
// to the `max-bitmap-to-string-mb` configuration.
if (s.IsInvalidArgument()) {
Config *config = svr->GetConfig();
- uint32_t max_btos_size = static_cast<uint32_t>(config->max_bitmap_to_string_mb) * MiB;
+ uint32_t max_btos_size = static_cast<uint32_t>(config->max_bitmap_to_string_mb_) * MiB;
Redis::Bitmap bitmap_db(svr->storage_, conn->GetNamespace());
s = bitmap_db.GetString(args_[1], max_btos_size, &value);
}
@@ -83,7 +83,7 @@ class CommandGetEx : public Commander {
// to the `max-bitmap-to-string-mb` configuration.
if (s.IsInvalidArgument()) {
Config *config = svr->GetConfig();
- uint32_t max_btos_size = static_cast<uint32_t>(config->max_bitmap_to_string_mb) * MiB;
+ uint32_t max_btos_size = static_cast<uint32_t>(config->max_bitmap_to_string_mb_) * MiB;
Redis::Bitmap bitmap_db(svr->storage_, conn->GetNamespace());
s = bitmap_db.GetString(args_[1], max_btos_size, &value);
}
diff --git a/src/commands/cmd_zset.cc b/src/commands/cmd_zset.cc
index ce375b1e..4c446b30 100644
--- a/src/commands/cmd_zset.cc
+++ b/src/commands/cmd_zset.cc
@@ -62,7 +62,7 @@ class CommandZAdd : public Commander {
Status Execute(Server *svr, Connection *conn, std::string *output) override {
int ret = 0;
- double old_score = member_scores_[0].score;
+ double old_score = member_scores_[0].score_;
Redis::ZSet zset_db(svr->storage_, conn->GetNamespace());
auto s = zset_db.Add(args_[1], flags_, &member_scores_, &ret);
if (!s.ok()) {
@@ -70,7 +70,7 @@ class CommandZAdd : public Commander {
}
if (flags_.HasIncr()) {
- auto new_score = member_scores_[0].score;
+ auto new_score = member_scores_[0].score_;
if ((flags_.HasNX() || flags_.HasXX() || flags_.HasLT() || flags_.HasGT()) && old_score == new_score &&
ret == 0) { // not the first time using incr && score not changed
*output = Redis::NilString();
@@ -243,8 +243,8 @@ class CommandZPop : public Commander {
output->append(Redis::MultiLen(member_scores.size() * 2));
for (const auto &ms : member_scores) {
- output->append(Redis::BulkString(ms.member));
- output->append(Redis::BulkString(Util::Float2String(ms.score)));
+ output->append(Redis::BulkString(ms.member_));
+ output->append(Redis::BulkString(Util::Float2String(ms.score_)));
}
return Status::OK();
@@ -301,8 +301,8 @@ class CommandZRange : public Commander {
}
for (const auto &ms : member_scores) {
- output->append(Redis::BulkString(ms.member));
- if (with_scores_) output->append(Redis::BulkString(Util::Float2String(ms.score)));
+ output->append(Redis::BulkString(ms.member_));
+ if (with_scores_) output->append(Redis::BulkString(Util::Float2String(ms.score_)));
}
return Status::OK();
@@ -322,11 +322,11 @@ class CommandZRevRange : public CommandZRange {
class CommandZRangeByLex : public Commander {
public:
- explicit CommandZRangeByLex(bool reversed = false) { spec_.reversed = reversed; }
+ explicit CommandZRangeByLex(bool reversed = false) { spec_.reversed_ = reversed; }
Status Parse(const std::vector<std::string> &args) override {
Status s;
- if (spec_.reversed) {
+ if (spec_.reversed_) {
s = ParseRangeLexSpec(args[3], args[2], &spec_);
} else {
s = ParseRangeLexSpec(args[2], args[3], &spec_);
@@ -343,8 +343,8 @@ class CommandZRangeByLex : public Commander {
return {Status::RedisParseErr, errValueNotInteger};
}
- spec_.offset = *parse_offset;
- spec_.count = *parse_count;
+ spec_.offset_ = *parse_offset;
+ spec_.count_ = *parse_count;
}
return Commander::Parse(args);
}
@@ -368,10 +368,10 @@ class CommandZRangeByLex : public Commander {
class CommandZRangeByScore : public Commander {
public:
- explicit CommandZRangeByScore(bool reversed = false) { spec_.reversed = reversed; }
+ explicit CommandZRangeByScore(bool reversed = false) { spec_.reversed_ = reversed; }
Status Parse(const std::vector<std::string> &args) override {
Status s;
- if (spec_.reversed) {
+ if (spec_.reversed_) {
s = Redis::ZSet::ParseRangeSpec(args[3], args[2], &spec_);
} else {
s = Redis::ZSet::ParseRangeSpec(args[2], args[3], &spec_);
@@ -393,8 +393,8 @@ class CommandZRangeByScore : public Commander {
return {Status::RedisParseErr, errValueNotInteger};
}
- spec_.offset = *parse_offset;
- spec_.count = *parse_count;
+ spec_.offset_ = *parse_offset;
+ spec_.count_ = *parse_count;
i += 3;
} else {
return {Status::RedisParseErr, errInvalidSyntax};
@@ -419,8 +419,8 @@ class CommandZRangeByScore : public Commander {
}
for (const auto &ms : member_scores) {
- output->append(Redis::BulkString(ms.member));
- if (with_scores_) output->append(Redis::BulkString(Util::Float2String(ms.score)));
+ output->append(Redis::BulkString(ms.member_));
+ if (with_scores_) output->append(Redis::BulkString(Util::Float2String(ms.score_)));
}
return Status::OK();
@@ -663,7 +663,7 @@ class CommandZUnionStore : public Commander {
if (!weight || std::isnan(*weight)) {
return {Status::RedisParseErr, "weight is not a double or out of range"};
}
- keys_weights_[k].weight = *weight;
+ keys_weights_[k].weight_ = *weight;
k++;
}
@@ -718,7 +718,7 @@ class CommandZScan : public CommandSubkeyScanBase {
Redis::ZSet zset_db(svr->storage_, conn->GetNamespace());
std::vector<std::string> members;
std::vector<double> scores;
- auto s = zset_db.Scan(key, cursor, limit, prefix, &members, &scores);
+ auto s = zset_db.Scan(key_, cursor_, limit_, prefix_, &members, &scores);
if (!s.ok() && !s.IsNotFound()) {
return {Status::RedisExecErr, s.ToString()};
}
diff --git a/src/commands/command_parser.h b/src/commands/command_parser.h
index 07d58cd9..e66cad98 100644
--- a/src/commands/command_parser.h
+++ b/src/commands/command_parser.h
@@ -41,26 +41,26 @@ struct CommandParser {
public:
using value_type = typename Iter::value_type;
- CommandParser(Iter begin, Iter end) : begin(std::move(begin)), end(std::move(end)) {}
+ CommandParser(Iter begin, Iter end) : begin_(std::move(begin)), end_(std::move(end)) {}
template <typename Container>
explicit CommandParser(const Container& con, size_t skip_num = 0) : CommandParser(std::begin(con), std::end(con)) {
- std::advance(begin, skip_num);
+ std::advance(begin_, skip_num);
}
template <typename Container>
explicit CommandParser(Container&& con, size_t skip_num = 0)
: CommandParser(MoveIterator(std::begin(con)), MoveIterator(std::end(con))) {
- std::advance(begin, skip_num);
+ std::advance(begin_, skip_num);
}
- decltype(auto) RawPeek() const { return *begin; }
+ decltype(auto) RawPeek() const { return *begin_; }
- decltype(auto) RawTake() { return *begin++; }
+ decltype(auto) RawTake() { return *begin_++; }
- decltype(auto) RawNext() { ++begin; }
+ decltype(auto) RawNext() { ++begin_; }
- bool Good() const { return begin != end; }
+ bool Good() const { return begin_ != end_; }
template <typename Pred>
bool EatPred(Pred&& pred) {
@@ -109,8 +109,8 @@ struct CommandParser {
static Status InvalidSyntax() { return {Status::RedisParseErr, "syntax error"}; }
private:
- Iter begin;
- Iter end;
+ Iter begin_;
+ Iter end_;
};
template <typename Container>
diff --git a/src/commands/commander.cc b/src/commands/commander.cc
index a3302c80..67afa546 100644
--- a/src/commands/commander.cc
+++ b/src/commands/commander.cc
@@ -25,8 +25,8 @@ namespace Redis {
RegisterToCommandTable::RegisterToCommandTable(std::initializer_list<CommandAttributes> list) {
for (const auto &attr : list) {
command_details::redis_command_table.emplace_back(attr);
- command_details::original_commands[attr.name] = &command_details::redis_command_table.back();
- command_details::commands[attr.name] = &command_details::redis_command_table.back();
+ command_details::original_commands[attr.name_] = &command_details::redis_command_table.back();
+ command_details::commands[attr.name_] = &command_details::redis_command_table.back();
}
}
@@ -41,14 +41,14 @@ void ResetCommands() { command_details::commands = command_details::original_com
std::string GetCommandInfo(const CommandAttributes *command_attributes) {
std::string command, command_flags;
command.append(Redis::MultiLen(6));
- command.append(Redis::BulkString(command_attributes->name));
- command.append(Redis::Integer(command_attributes->arity));
+ command.append(Redis::BulkString(command_attributes->name_));
+ command.append(Redis::Integer(command_attributes->arity_));
command_flags.append(Redis::MultiLen(1));
command_flags.append(Redis::BulkString(command_attributes->is_write() ? "write" : "readonly"));
command.append(command_flags);
- command.append(Redis::Integer(command_attributes->key_range.first_key));
- command.append(Redis::Integer(command_attributes->key_range.last_key));
- command.append(Redis::Integer(command_attributes->key_range.key_step));
+ command.append(Redis::Integer(command_attributes->key_range_.first_key_));
+ command.append(Redis::Integer(command_attributes->key_range_.last_key_));
+ command.append(Redis::Integer(command_attributes->key_range_.key_step_));
return command;
}
@@ -82,22 +82,22 @@ Status GetKeysFromCommand(const std::string &cmd_name, int argc, std::vector<int
}
auto command_attribute = cmd_iter->second;
- if (command_attribute->key_range.first_key == 0) {
+ if (command_attribute->key_range_.first_key_ == 0) {
return {Status::NotOK, "The command has no key arguments"};
}
- if (command_attribute->key_range.first_key < 0) {
+ if (command_attribute->key_range_.first_key_ < 0) {
return {Status::NotOK, "The command has dynamic positions of key arguments"};
}
- if ((command_attribute->arity > 0 && command_attribute->arity != argc) || argc < -command_attribute->arity) {
+ if ((command_attribute->arity_ > 0 && command_attribute->arity_ != argc) || argc < -command_attribute->arity_) {
return {Status::NotOK, "Invalid number of arguments specified for command"};
}
- auto last = command_attribute->key_range.last_key;
+ auto last = command_attribute->key_range_.last_key_;
if (last < 0) last = argc + last;
- for (int j = command_attribute->key_range.first_key; j <= last; j += command_attribute->key_range.key_step) {
+ for (int j = command_attribute->key_range_.first_key_; j <= last; j += command_attribute->key_range_.key_step_) {
keys_indexes->emplace_back(j);
}
diff --git a/src/commands/commander.h b/src/commands/commander.h
index 29d0435b..f2c144f6 100644
--- a/src/commands/commander.h
+++ b/src/commands/commander.h
@@ -92,43 +92,43 @@ using CommanderFactory = std::function<std::unique_ptr<Commander>()>;
struct CommandKeyRange {
// index of the first key in command tokens
// 0 stands for no key, since the first index of command arguments is command name
- int first_key;
+ int first_key_;
// index of the last key in command tokens
// in normal one-key commands, first key and last key index are both 1
// -n stands for the n-th last index of the sequence, i.e. args.size() - n
- int last_key;
+ int last_key_;
// step length of key position
// e.g. key step 2 means "key other key other ..." sequence
- int key_step;
+ int key_step_;
};
using CommandKeyRangeGen = std::function<CommandKeyRange(const std::vector<std::string> &)>;
struct CommandAttributes {
- std::string name;
+ std::string name_;
// number of command arguments
// positive number n means number of arguments is equal to n
// negative number -n means number of arguments is equal to or large than n
- int arity;
+ int arity_;
- std::string description;
- uint64_t flags;
+ std::string description_;
+ uint64_t flags_;
- CommandKeyRange key_range;
+ CommandKeyRange key_range_;
// if key_range.first_key == -1, key_range_gen is used instead
- CommandKeyRangeGen key_range_gen;
+ CommandKeyRangeGen key_range_gen_;
- CommanderFactory factory;
+ CommanderFactory factory_;
- bool is_write() const { return (flags & kCmdWrite) != 0; }
- bool is_ok_loading() const { return (flags & kCmdLoading) != 0; }
- bool is_exclusive() const { return (flags & kCmdExclusive) != 0; }
- bool is_multi() const { return (flags & kCmdMulti) != 0; }
- bool is_no_multi() const { return (flags & kCmdNoMulti) != 0; }
+ bool is_write() const { return (flags_ & kCmdWrite) != 0; }
+ bool is_ok_loading() const { return (flags_ & kCmdLoading) != 0; }
+ bool is_exclusive() const { return (flags_ & kCmdExclusive) != 0; }
+ bool is_multi() const { return (flags_ & kCmdMulti) != 0; }
+ bool is_no_multi() const { return (flags_ & kCmdNoMulti) != 0; }
};
using CommandMap = std::map<std::string, const CommandAttributes *>;
diff --git a/src/commands/scan_base.h b/src/commands/scan_base.h
index 1e5f520f..b36112eb 100644
--- a/src/commands/scan_base.h
+++ b/src/commands/scan_base.h
@@ -32,9 +32,9 @@ class CommandScanBase : public Commander {
public:
Status ParseMatchAndCountParam(const std::string &type, std::string value) {
if (type == "match") {
- prefix = std::move(value);
- if (!prefix.empty() && prefix[prefix.size() - 1] == '*') {
- prefix = prefix.substr(0, prefix.size() - 1);
+ prefix_ = std::move(value);
+ if (!prefix_.empty() && prefix_[prefix_.size() - 1] == '*') {
+ prefix_ = prefix_.substr(0, prefix_.size() - 1);
return Status::OK();
}
@@ -45,8 +45,8 @@ class CommandScanBase : public Commander {
return {Status::RedisParseErr, "count param should be type int"};
}
- limit = *parse_result;
- if (limit <= 0) {
+ limit_ = *parse_result;
+ if (limit_ <= 0) {
return {Status::RedisParseErr, errInvalidSyntax};
}
}
@@ -55,17 +55,17 @@ class CommandScanBase : public Commander {
}
void ParseCursor(const std::string ¶m) {
- cursor = param;
- if (cursor == "0") {
- cursor = std::string();
+ cursor_ = param;
+ if (cursor_ == "0") {
+ cursor_ = std::string();
} else {
- cursor = cursor.find(kCursorPrefix) == 0 ? cursor.substr(strlen(kCursorPrefix)) : cursor;
+ cursor_ = cursor_.find(kCursorPrefix) == 0 ? cursor_.substr(strlen(kCursorPrefix)) : cursor_;
}
}
std::string GenerateOutput(const std::vector<std::string> &keys) const {
std::vector<std::string> list;
- if (keys.size() == static_cast<size_t>(limit)) {
+ if (keys.size() == static_cast<size_t>(limit_)) {
list.emplace_back(Redis::BulkString(keys.back()));
} else {
list.emplace_back(Redis::BulkString("0"));
@@ -77,9 +77,9 @@ class CommandScanBase : public Commander {
}
protected:
- std::string cursor;
- std::string prefix;
- int limit = 20;
+ std::string cursor_;
+ std::string prefix_;
+ int limit_ = 20;
};
class CommandSubkeyScanBase : public CommandScanBase {
@@ -91,7 +91,7 @@ class CommandSubkeyScanBase : public CommandScanBase {
return {Status::RedisParseErr, errWrongNumOfArguments};
}
- key = args[1];
+ key_ = args[1];
ParseCursor(args[2]);
if (args.size() >= 5) {
Status s = ParseMatchAndCountParam(Util::ToLower(args[3]), args_[4]);
@@ -112,7 +112,7 @@ class CommandSubkeyScanBase : public CommandScanBase {
std::string GenerateOutput(const std::vector<std::string> &fields, const std::vector<std::string> &values) {
std::vector<std::string> list;
auto items_count = fields.size();
- if (items_count == static_cast<size_t>(limit)) {
+ if (items_count == static_cast<size_t>(limit_)) {
list.emplace_back(Redis::BulkString(fields.back()));
} else {
list.emplace_back(Redis::BulkString("0"));
@@ -129,7 +129,7 @@ class CommandSubkeyScanBase : public CommandScanBase {
}
protected:
- std::string key;
+ std::string key_;
};
} // namespace Redis
diff --git a/src/common/cron.cc b/src/common/cron.cc
index c3dbf526..4f23e2ba 100644
--- a/src/common/cron.cc
+++ b/src/common/cron.cc
@@ -27,8 +27,8 @@
std::string Scheduler::ToString() const {
auto param2string = [](int n) -> std::string { return n == -1 ? "*" : std::to_string(n); };
- return param2string(minute) + " " + param2string(hour) + " " + param2string(mday) + " " + param2string(month) + " " +
- param2string(wday);
+ return param2string(minute_) + " " + param2string(hour_) + " " + param2string(mday_) + " " + param2string(month_) +
+ " " + param2string(wday_);
}
Status Cron::SetScheduleTime(const std::vector<std::string> &args) {
@@ -58,9 +58,9 @@ bool Cron::IsTimeMatch(struct tm *tm) {
return false;
}
for (const auto &st : schedulers_) {
- if ((st.minute == -1 || tm->tm_min == st.minute) && (st.hour == -1 || tm->tm_hour == st.hour) &&
- (st.mday == -1 || tm->tm_mday == st.mday) && (st.month == -1 || (tm->tm_mon + 1) == st.month) &&
- (st.wday == -1 || tm->tm_wday == st.wday)) {
+ if ((st.minute_ == -1 || tm->tm_min == st.minute_) && (st.hour_ == -1 || tm->tm_hour == st.hour_) &&
+ (st.mday_ == -1 || tm->tm_mday == st.mday_) && (st.month_ == -1 || (tm->tm_mon + 1) == st.month_) &&
+ (st.wday_ == -1 || tm->tm_wday == st.wday_)) {
last_tm_ = *tm;
return true;
}
@@ -84,11 +84,11 @@ StatusOr<Scheduler> Cron::convertToScheduleTime(const std::string &minute, const
const std::string &wday) {
Scheduler st;
- st.minute = GET_OR_RET(convertParam(minute, 0, 59));
- st.hour = GET_OR_RET(convertParam(hour, 0, 23));
- st.mday = GET_OR_RET(convertParam(mday, 1, 31));
- st.month = GET_OR_RET(convertParam(month, 1, 12));
- st.wday = GET_OR_RET(convertParam(wday, 0, 6));
+ st.minute_ = GET_OR_RET(convertParam(minute, 0, 59));
+ st.hour_ = GET_OR_RET(convertParam(hour, 0, 23));
+ st.mday_ = GET_OR_RET(convertParam(mday, 1, 31));
+ st.month_ = GET_OR_RET(convertParam(month, 1, 12));
+ st.wday_ = GET_OR_RET(convertParam(wday, 0, 6));
return st;
}
diff --git a/src/common/cron.h b/src/common/cron.h
index 27fdf3c6..20291caf 100644
--- a/src/common/cron.h
+++ b/src/common/cron.h
@@ -28,11 +28,11 @@
#include "status.h"
struct Scheduler {
- int minute;
- int hour;
- int mday;
- int month;
- int wday;
+ int minute_;
+ int hour_;
+ int mday_;
+ int month_;
+ int wday_;
std::string ToString() const;
};
diff --git a/src/common/event_util.h b/src/common/event_util.h
index 3b757e18..bca4e887 100644
--- a/src/common/event_util.h
+++ b/src/common/event_util.h
@@ -45,9 +45,9 @@ struct UniqueFreePtr : std::unique_ptr<T, StaticFree> {
struct UniqueEvbufReadln : UniqueFreePtr<char[]> {
UniqueEvbufReadln(evbuffer *buffer, evbuffer_eol_style eol_style)
- : UniqueFreePtr(evbuffer_readln(buffer, &length, eol_style)) {}
+ : UniqueFreePtr(evbuffer_readln(buffer, &length_, eol_style)) {}
- size_t length;
+ size_t length_;
};
using StaticEvbufFree = StaticFunction<decltype(evbuffer_free), evbuffer_free>;
diff --git a/src/common/io_util.cc b/src/common/io_util.cc
index c4eb51be..8064ab28 100644
--- a/src/common/io_util.cc
+++ b/src/common/io_util.cc
@@ -241,7 +241,7 @@ StatusOr<std::string> SockReadLine(int fd) {
return Status::FromErrno("read response err(empty)");
}
- return std::string(line.get(), line.length);
+ return std::string(line.get(), line.length_);
}
int GetPeerAddr(int fd, std::string *addr, uint32_t *port) {
diff --git a/src/common/range_spec.cc b/src/common/range_spec.cc
index b6ccdbb8..48e67387 100644
--- a/src/common/range_spec.cc
+++ b/src/common/range_spec.cc
@@ -26,29 +26,29 @@ Status ParseRangeLexSpec(const std::string &min, const std::string &max, CommonR
}
if (min == "-") {
- spec->min = "";
+ spec->min_ = "";
} else {
if (min[0] == '(') {
- spec->minex = true;
+ spec->minex_ = true;
} else if (min[0] == '[') {
- spec->minex = false;
+ spec->minex_ = false;
} else {
return {Status::NotOK, "the min is illegal"};
}
- spec->min = min.substr(1);
+ spec->min_ = min.substr(1);
}
if (max == "+") {
- spec->max_infinite = true;
+ spec->max_infinite_ = true;
} else {
if (max[0] == '(') {
- spec->maxex = true;
+ spec->maxex_ = true;
} else if (max[0] == '[') {
- spec->maxex = false;
+ spec->maxex_ = false;
} else {
return {Status::NotOK, "the max is illegal"};
}
- spec->max = max.substr(1);
+ spec->max_ = max.substr(1);
}
return Status::OK();
}
diff --git a/src/common/range_spec.h b/src/common/range_spec.h
index 9d4e236c..d92a0199 100644
--- a/src/common/range_spec.h
+++ b/src/common/range_spec.h
@@ -25,13 +25,19 @@
#include "status.h"
struct CommonRangeLexSpec {
- std::string min, max;
- bool minex, maxex; /* are min or max exclusive */
- bool max_infinite; /* are max infinite */
- int64_t offset, count;
- bool removed, reversed;
+ std::string min_, max_;
+ bool minex_, maxex_; /* are min or max exclusive */
+ bool max_infinite_; /* are max infinite */
+ int64_t offset_, count_;
+ bool removed_, reversed_;
CommonRangeLexSpec()
- : minex(false), maxex(false), max_infinite(false), offset(-1), count(-1), removed(false), reversed(false) {}
+ : minex_(false),
+ maxex_(false),
+ max_infinite_(false),
+ offset_(-1),
+ count_(-1),
+ removed_(false),
+ reversed_(false) {}
};
Status ParseRangeLexSpec(const std::string &min, const std::string &max, CommonRangeLexSpec *spec);
diff --git a/src/common/sha1.cc b/src/common/sha1.cc
index 97182cfd..f8a386b3 100644
--- a/src/common/sha1.cc
+++ b/src/common/sha1.cc
@@ -67,7 +67,7 @@ A million repetitions of "a"
void SHA1Transform(uint32_t state[5], const unsigned char buffer[64]) {
uint32_t a = 0, b = 0, c = 0, d = 0, e = 0;
union CHAR64LONG16 {
- unsigned char c[64];
+ unsigned char c_[64];
uint32_t l[16];
};
#ifdef SHA1HANDSOFF
@@ -185,12 +185,12 @@ void SHA1Transform(uint32_t state[5], const unsigned char buffer[64]) {
void SHA1Init(SHA1_CTX* context) {
/* SHA1 initialization constants */
- context->state[0] = 0x67452301;
- context->state[1] = 0xEFCDAB89;
- context->state[2] = 0x98BADCFE;
- context->state[3] = 0x10325476;
- context->state[4] = 0xC3D2E1F0;
- context->count[0] = context->count[1] = 0;
+ context->state_[0] = 0x67452301;
+ context->state_[1] = 0xEFCDAB89;
+ context->state_[2] = 0x98BADCFE;
+ context->state_[3] = 0x10325476;
+ context->state_[4] = 0xC3D2E1F0;
+ context->count_[0] = context->count_[1] = 0;
}
/* Run your data through this. */
@@ -198,21 +198,21 @@ void SHA1Init(SHA1_CTX* context) {
void SHA1Update(SHA1_CTX* context, const unsigned char* data, uint32_t len) {
uint32_t i = 0, j = 0;
- j = context->count[0];
- if ((context->count[0] += len << 3) < j) context->count[1]++;
- context->count[1] += (len >> 29);
+ j = context->count_[0];
+ if ((context->count_[0] += len << 3) < j) context->count_[1]++;
+ context->count_[1] += (len >> 29);
j = (j >> 3) & 63;
if ((j + len) > 63) {
- memcpy(&context->buffer[j], data, (i = 64 - j));
- SHA1Transform(context->state, context->buffer);
+ memcpy(&context->buffer_[j], data, (i = 64 - j));
+ SHA1Transform(context->state_, context->buffer_);
for (; i + 63 < len; i += 64) {
- SHA1Transform(context->state, &data[i]);
+ SHA1Transform(context->state_, &data[i]);
}
j = 0;
} else {
i = 0;
}
- memcpy(&context->buffer[j], &data[i], len - i);
+ memcpy(&context->buffer_[j], &data[i], len - i);
}
/* Add padding and return the message digest. */
@@ -223,17 +223,17 @@ void SHA1Final(unsigned char digest[20], SHA1_CTX* context) {
for (i = 0; i < 8; i++) {
finalcount[i] =
- (unsigned char)((context->count[(i >= 4 ? 0 : 1)] >> ((3 - (i & 3)) * 8)) & 255); /* Endian independent */
+ (unsigned char)((context->count_[(i >= 4 ? 0 : 1)] >> ((3 - (i & 3)) * 8)) & 255); /* Endian independent */
}
c = 0200;
SHA1Update(context, &c, 1);
- while ((context->count[0] & 504) != 448) {
+ while ((context->count_[0] & 504) != 448) {
c = 0000;
SHA1Update(context, &c, 1);
}
SHA1Update(context, finalcount, 8); /* Should cause a SHA1Transform() */
for (i = 0; i < 20; i++) {
- digest[i] = (unsigned char)((context->state[i >> 2] >> ((3 - (i & 3)) * 8)) & 255);
+ digest[i] = (unsigned char)((context->state_[i >> 2] >> ((3 - (i & 3)) * 8)) & 255);
}
/* Wipe variables */
memset(context, '\0', sizeof(*context));
diff --git a/src/common/sha1.h b/src/common/sha1.h
index 07f195b5..fc13e1b7 100644
--- a/src/common/sha1.h
+++ b/src/common/sha1.h
@@ -10,9 +10,9 @@ By Steve Reid <st...@edmweb.com>
#include <cstdint>
struct SHA1_CTX { // NOLINT
- uint32_t state[5];
- uint32_t count[2];
- unsigned char buffer[64];
+ uint32_t state_[5];
+ uint32_t count_[2];
+ unsigned char buffer_[64];
};
void SHA1Transform(uint32_t state[5], const unsigned char buffer[64]);
diff --git a/src/config/config.cc b/src/config/config.cc
index 9e6dcdf6..7f807d80 100644
--- a/src/config/config.cc
+++ b/src/config/config.cc
@@ -68,16 +68,16 @@ std::string trimRocksDBPrefix(std::string s) {
}
int configEnumGetValue(ConfigEnum *ce, const char *name) {
- while (ce->name != nullptr) {
- if (strcasecmp(ce->name, name) == 0) return ce->val;
+ while (ce->name_ != nullptr) {
+ if (strcasecmp(ce->name_, name) == 0) return ce->val_;
ce++;
}
return INT_MIN;
}
const char *configEnumGetName(ConfigEnum *ce, int val) {
- while (ce->name != nullptr) {
- if (ce->val == val) return ce->name;
+ while (ce->name_ != nullptr) {
+ if (ce->val_ == val) return ce->name_;
ce++;
}
return nullptr;
@@ -85,147 +85,149 @@ const char *configEnumGetName(ConfigEnum *ce, int val) {
Config::Config() {
struct FieldWrapper {
- std::string name;
- bool readonly;
- std::unique_ptr<ConfigField> field;
+ std::string name_;
+ bool readonly_;
+ std::unique_ptr<ConfigField> field_;
FieldWrapper(std::string name, bool readonly, ConfigField *field)
- : name(std::move(name)), readonly(readonly), field(field) {}
+ : name_(std::move(name)), readonly_(readonly), field_(field) {}
};
FieldWrapper fields[] = {
- {"daemonize", true, new YesNoField(&daemonize, false)},
- {"bind", true, new StringField(&binds_, "")},
- {"port", true, new UInt32Field(&port, kDefaultPort, 1, PORT_LIMIT)},
+ {"daemonize", true, new YesNoField(&daemonize_, false)},
+ {"bind", true, new StringField(&binds_str_, "")},
+ {"port", true, new UInt32Field(&port_, kDefaultPort, 1, PORT_LIMIT)},
#ifdef ENABLE_OPENSSL
- {"tls-port", true, new UInt32Field(&tls_port, 0, 0, PORT_LIMIT)},
- {"tls-cert-file", false, new StringField(&tls_cert_file, "")},
- {"tls-key-file", false, new StringField(&tls_key_file, "")},
- {"tls-key-file-pass", false, new StringField(&tls_key_file_pass, "")},
- {"tls-ca-cert-file", false, new StringField(&tls_ca_cert_file, "")},
- {"tls-ca-cert-dir", false, new StringField(&tls_ca_cert_dir, "")},
- {"tls-protocols", false, new StringField(&tls_protocols, "")},
- {"tls-auth-clients", false, new StringField(&tls_auth_clients, "")},
- {"tls-ciphers", false, new StringField(&tls_ciphers, "")},
- {"tls-ciphersuites", false, new StringField(&tls_ciphersuites, "")},
- {"tls-prefer-server-ciphers", false, new YesNoField(&tls_prefer_server_ciphers, false)},
- {"tls-session-caching", false, new YesNoField(&tls_session_caching, true)},
- {"tls-session-cache-size", false, new IntField(&tls_session_cache_size, 1024 * 20, 0, INT_MAX)},
- {"tls-session-cache-timeout", false, new IntField(&tls_session_cache_timeout, 300, 0, INT_MAX)},
+ {"tls-port", true, new UInt32Field(&tls_port_, 0, 0, PORT_LIMIT)},
+ {"tls-cert-file", false, new StringField(&tls_cert_file_, "")},
+ {"tls-key-file", false, new StringField(&tls_key_file_, "")},
+ {"tls-key-file-pass", false, new StringField(&tls_key_file_pass_, "")},
+ {"tls-ca-cert-file", false, new StringField(&tls_ca_cert_file_, "")},
+ {"tls-ca-cert-dir", false, new StringField(&tls_ca_cert_dir_, "")},
+ {"tls-protocols", false, new StringField(&tls_protocols_, "")},
+ {"tls-auth-clients", false, new StringField(&tls_auth_clients_, "")},
+ {"tls-ciphers", false, new StringField(&tls_ciphers_, "")},
+ {"tls-ciphersuites", false, new StringField(&tls_ciphersuites_, "")},
+ {"tls-prefer-server-ciphers", false, new YesNoField(&tls_prefer_server_ciphers_, false)},
+ {"tls-session-caching", false, new YesNoField(&tls_session_caching_, true)},
+ {"tls-session-cache-size", false, new IntField(&tls_session_cache_size_, 1024 * 20, 0, INT_MAX)},
+ {"tls-session-cache-timeout", false, new IntField(&tls_session_cache_timeout_, 300, 0, INT_MAX)},
#endif
- {"workers", true, new IntField(&workers, 8, 1, 256)},
- {"timeout", false, new IntField(&timeout, 0, 0, INT_MAX)},
- {"tcp-backlog", true, new IntField(&backlog, 511, 0, INT_MAX)},
- {"maxclients", false, new IntField(&maxclients, 10240, 0, INT_MAX)},
- {"max-backup-to-keep", false, new IntField(&max_backup_to_keep, 1, 0, 1)},
- {"max-backup-keep-hours", false, new IntField(&max_backup_keep_hours, 0, 0, INT_MAX)},
- {"master-use-repl-port", false, new YesNoField(&master_use_repl_port, false)},
- {"requirepass", false, new StringField(&requirepass, "")},
- {"masterauth", false, new StringField(&masterauth, "")},
+ {"workers", true, new IntField(&workers_, 8, 1, 256)},
+ {"timeout", false, new IntField(&timeout_, 0, 0, INT_MAX)},
+ {"tcp-backlog", true, new IntField(&backlog_, 511, 0, INT_MAX)},
+ {"maxclients", false, new IntField(&maxclients_, 10240, 0, INT_MAX)},
+ {"max-backup-to-keep", false, new IntField(&max_backup_to_keep_, 1, 0, 1)},
+ {"max-backup-keep-hours", false, new IntField(&max_backup_keep_hours_, 0, 0, INT_MAX)},
+ {"master-use-repl-port", false, new YesNoField(&master_use_repl_port_, false)},
+ {"requirepass", false, new StringField(&requirepass_, "")},
+ {"masterauth", false, new StringField(&masterauth_, "")},
{"slaveof", true, new StringField(&slaveof_, "")},
- {"compact-cron", false, new StringField(&compact_cron_, "")},
- {"bgsave-cron", false, new StringField(&bgsave_cron_, "")},
- {"replica-announce-ip", false, new StringField(&replica_announce_ip, "")},
- {"replica-announce-port", false, new UInt32Field(&replica_announce_port, 0, 0, PORT_LIMIT)},
- {"compaction-checker-range", false, new StringField(&compaction_checker_range_, "")},
- {"force-compact-file-age", false, new Int64Field(&force_compact_file_age, 2 * 24 * 3600, 60, INT64_MAX)},
+ {"compact-cron", false, new StringField(&compact_cron_str_, "")},
+ {"bgsave-cron", false, new StringField(&bgsave_cron_str_, "")},
+ {"replica-announce-ip", false, new StringField(&replica_announce_ip_, "")},
+ {"replica-announce-port", false, new UInt32Field(&replica_announce_port_, 0, 0, PORT_LIMIT)},
+ {"compaction-checker-range", false, new StringField(&compaction_checker_range_str_, "")},
+ {"force-compact-file-age", false, new Int64Field(&force_compact_file_age_, 2 * 24 * 3600, 60, INT64_MAX)},
{"force-compact-file-min-deleted-percentage", false,
- new IntField(&force_compact_file_min_deleted_percentage, 10, 1, 100)},
- {"db-name", true, new StringField(&db_name, "change.me.db")},
- {"dir", true, new StringField(&dir, "/tmp/kvrocks")},
- {"backup-dir", false, new StringField(&backup_dir, "")},
- {"log-dir", true, new StringField(&log_dir, "")},
- {"log-level", true, new EnumField(&log_level, log_levels, google::INFO)},
- {"pidfile", true, new StringField(&pidfile, "")},
- {"max-io-mb", false, new IntField(&max_io_mb, 500, 0, INT_MAX)},
- {"max-bitmap-to-string-mb", false, new IntField(&max_bitmap_to_string_mb, 16, 0, INT_MAX)},
- {"max-db-size", false, new IntField(&max_db_size, 0, 0, INT_MAX)},
- {"max-replication-mb", false, new IntField(&max_replication_mb, 0, 0, INT_MAX)},
- {"supervised", true, new EnumField(&supervised_mode, supervised_modes, kSupervisedNone)},
- {"slave-serve-stale-data", false, new YesNoField(&slave_serve_stale_data, true)},
- {"slave-empty-db-before-fullsync", false, new YesNoField(&slave_empty_db_before_fullsync, false)},
- {"slave-priority", false, new IntField(&slave_priority, 100, 0, INT_MAX)},
- {"slave-read-only", false, new YesNoField(&slave_readonly, true)},
- {"use-rsid-psync", true, new YesNoField(&use_rsid_psync, false)},
- {"profiling-sample-ratio", false, new IntField(&profiling_sample_ratio, 0, 0, 100)},
- {"profiling-sample-record-max-len", false, new IntField(&profiling_sample_record_max_len, 256, 0, INT_MAX)},
+ new IntField(&force_compact_file_min_deleted_percentage_, 10, 1, 100)},
+ {"db-name", true, new StringField(&db_name_, "change.me.db")},
+ {"dir", true, new StringField(&dir_, "/tmp/kvrocks")},
+ {"backup-dir", false, new StringField(&backup_dir_, "")},
+ {"log-dir", true, new StringField(&log_dir_, "")},
+ {"log-level", true, new EnumField(&log_level_, log_levels, google::INFO)},
+ {"pidfile", true, new StringField(&pidfile_, "")},
+ {"max-io-mb", false, new IntField(&max_io_mb_, 500, 0, INT_MAX)},
+ {"max-bitmap-to-string-mb", false, new IntField(&max_bitmap_to_string_mb_, 16, 0, INT_MAX)},
+ {"max-db-size", false, new IntField(&max_db_size_, 0, 0, INT_MAX)},
+ {"max-replication-mb", false, new IntField(&max_replication_mb_, 0, 0, INT_MAX)},
+ {"supervised", true, new EnumField(&supervised_mode_, supervised_modes, kSupervisedNone)},
+ {"slave-serve-stale-data", false, new YesNoField(&slave_serve_stale_data_, true)},
+ {"slave-empty-db-before-fullsync", false, new YesNoField(&slave_empty_db_before_fullsync_, false)},
+ {"slave-priority", false, new IntField(&slave_priority_, 100, 0, INT_MAX)},
+ {"slave-read-only", false, new YesNoField(&slave_readonly_, true)},
+ {"use-rsid-psync", true, new YesNoField(&use_rsid_psync_, false)},
+ {"profiling-sample-ratio", false, new IntField(&profiling_sample_ratio_, 0, 0, 100)},
+ {"profiling-sample-record-max-len", false, new IntField(&profiling_sample_record_max_len_, 256, 0, INT_MAX)},
{"profiling-sample-record-threshold-ms", false,
- new IntField(&profiling_sample_record_threshold_ms, 100, 0, INT_MAX)},
- {"slowlog-log-slower-than", false, new IntField(&slowlog_log_slower_than, 200000, -1, INT_MAX)},
- {"profiling-sample-commands", false, new StringField(&profiling_sample_commands_, "")},
- {"slowlog-max-len", false, new IntField(&slowlog_max_len, 128, 0, INT_MAX)},
- {"purge-backup-on-fullsync", false, new YesNoField(&purge_backup_on_fullsync, false)},
+ new IntField(&profiling_sample_record_threshold_ms_, 100, 0, INT_MAX)},
+ {"slowlog-log-slower-than", false, new IntField(&slowlog_log_slower_than_, 200000, -1, INT_MAX)},
+ {"profiling-sample-commands", false, new StringField(&profiling_sample_commands_str_, "")},
+ {"slowlog-max-len", false, new IntField(&slowlog_max_len_, 128, 0, INT_MAX)},
+ {"purge-backup-on-fullsync", false, new YesNoField(&purge_backup_on_fullsync_, false)},
{"rename-command", true, new MultiStringField(&rename_command_, std::vector<std::string>{})},
- {"auto-resize-block-and-sst", false, new YesNoField(&auto_resize_block_and_sst, true)},
- {"fullsync-recv-file-delay", false, new IntField(&fullsync_recv_file_delay, 0, 0, INT_MAX)},
- {"cluster-enabled", true, new YesNoField(&cluster_enabled, false)},
- {"migrate-speed", false, new IntField(&migrate_speed, 4096, 0, INT_MAX)},
- {"migrate-pipeline-size", false, new IntField(&pipeline_size, 16, 1, INT_MAX)},
- {"migrate-sequence-gap", false, new IntField(&sequence_gap, 10000, 1, INT_MAX)},
- {"unixsocket", true, new StringField(&unixsocket, "")},
- {"unixsocketperm", true, new OctalField(&unixsocketperm, 0777, 1, INT_MAX)},
- {"log-retention-days", false, new IntField(&log_retention_days, -1, -1, INT_MAX)},
- {"persist-cluster-nodes-enabled", false, new YesNoField(&persist_cluster_nodes_enabled, true)},
+ {"auto-resize-block-and-sst", false, new YesNoField(&auto_resize_block_and_sst_, true)},
+ {"fullsync-recv-file-delay", false, new IntField(&fullsync_recv_file_delay_, 0, 0, INT_MAX)},
+ {"cluster-enabled", true, new YesNoField(&cluster_enabled_, false)},
+ {"migrate-speed", false, new IntField(&migrate_speed_, 4096, 0, INT_MAX)},
+ {"migrate-pipeline-size", false, new IntField(&pipeline_size_, 16, 1, INT_MAX)},
+ {"migrate-sequence-gap", false, new IntField(&sequence_gap_, 10000, 1, INT_MAX)},
+ {"unixsocket", true, new StringField(&unixsocket_, "")},
+ {"unixsocketperm", true, new OctalField(&unixsocketperm_, 0777, 1, INT_MAX)},
+ {"log-retention-days", false, new IntField(&log_retention_days_, -1, -1, INT_MAX)},
+ {"persist-cluster-nodes-enabled", false, new YesNoField(&persist_cluster_nodes_enabled_, true)},
/* rocksdb options */
{"rocksdb.compression", false,
- new EnumField(&RocksDB.compression, compression_types, rocksdb::CompressionType::kNoCompression)},
- {"rocksdb.block_size", true, new IntField(&RocksDB.block_size, 4096, 0, INT_MAX)},
- {"rocksdb.max_open_files", false, new IntField(&RocksDB.max_open_files, 4096, -1, INT_MAX)},
- {"rocksdb.write_buffer_size", false, new IntField(&RocksDB.write_buffer_size, 64, 0, 4096)},
- {"rocksdb.max_write_buffer_number", false, new IntField(&RocksDB.max_write_buffer_number, 4, 0, 256)},
- {"rocksdb.target_file_size_base", false, new IntField(&RocksDB.target_file_size_base, 128, 1, 1024)},
- {"rocksdb.max_background_compactions", false, new IntField(&RocksDB.max_background_compactions, 2, -1, 32)},
- {"rocksdb.max_background_flushes", true, new IntField(&RocksDB.max_background_flushes, 2, -1, 32)},
- {"rocksdb.max_sub_compactions", false, new IntField(&RocksDB.max_sub_compactions, 1, 0, 16)},
- {"rocksdb.delayed_write_rate", false, new Int64Field(&RocksDB.delayed_write_rate, 0, 0, INT64_MAX)},
- {"rocksdb.wal_ttl_seconds", true, new IntField(&RocksDB.WAL_ttl_seconds, 3 * 3600, 0, INT_MAX)},
- {"rocksdb.wal_size_limit_mb", true, new IntField(&RocksDB.WAL_size_limit_MB, 16384, 0, INT_MAX)},
- {"rocksdb.max_total_wal_size", false, new IntField(&RocksDB.max_total_wal_size, 64 * 4 * 2, 0, INT_MAX)},
- {"rocksdb.disable_auto_compactions", false, new YesNoField(&RocksDB.disable_auto_compactions, false)},
- {"rocksdb.enable_pipelined_write", true, new YesNoField(&RocksDB.enable_pipelined_write, false)},
- {"rocksdb.stats_dump_period_sec", false, new IntField(&RocksDB.stats_dump_period_sec, 0, 0, INT_MAX)},
- {"rocksdb.cache_index_and_filter_blocks", true, new YesNoField(&RocksDB.cache_index_and_filter_blocks, false)},
- {"rocksdb.subkey_block_cache_size", true, new IntField(&RocksDB.subkey_block_cache_size, 2048, 0, INT_MAX)},
- {"rocksdb.metadata_block_cache_size", true, new IntField(&RocksDB.metadata_block_cache_size, 2048, 0, INT_MAX)},
+ new EnumField(&rocks_db_.compression_, compression_types, rocksdb::CompressionType::kNoCompression)},
+ {"rocksdb.block_size", true, new IntField(&rocks_db_.block_size_, 4096, 0, INT_MAX)},
+ {"rocksdb.max_open_files", false, new IntField(&rocks_db_.max_open_files_, 4096, -1, INT_MAX)},
+ {"rocksdb.write_buffer_size", false, new IntField(&rocks_db_.write_buffer_size_, 64, 0, 4096)},
+ {"rocksdb.max_write_buffer_number", false, new IntField(&rocks_db_.max_write_buffer_number_, 4, 0, 256)},
+ {"rocksdb.target_file_size_base", false, new IntField(&rocks_db_.target_file_size_base_, 128, 1, 1024)},
+ {"rocksdb.max_background_compactions", false, new IntField(&rocks_db_.max_background_compactions_, 2, -1, 32)},
+ {"rocksdb.max_background_flushes", true, new IntField(&rocks_db_.max_background_flushes_, 2, -1, 32)},
+ {"rocksdb.max_sub_compactions", false, new IntField(&rocks_db_.max_sub_compactions_, 1, 0, 16)},
+ {"rocksdb.delayed_write_rate", false, new Int64Field(&rocks_db_.delayed_write_rate_, 0, 0, INT64_MAX)},
+ {"rocksdb.wal_ttl_seconds", true, new IntField(&rocks_db_.wal_ttl_seconds_, 3 * 3600, 0, INT_MAX)},
+ {"rocksdb.wal_size_limit_mb", true, new IntField(&rocks_db_.wal_size_limit_mb_, 16384, 0, INT_MAX)},
+ {"rocksdb.max_total_wal_size", false, new IntField(&rocks_db_.max_total_wal_size_, 64 * 4 * 2, 0, INT_MAX)},
+ {"rocksdb.disable_auto_compactions", false, new YesNoField(&rocks_db_.disable_auto_compactions_, false)},
+ {"rocksdb.enable_pipelined_write", true, new YesNoField(&rocks_db_.enable_pipelined_write_, false)},
+ {"rocksdb.stats_dump_period_sec", false, new IntField(&rocks_db_.stats_dump_period_sec_, 0, 0, INT_MAX)},
+ {"rocksdb.cache_index_and_filter_blocks", true, new YesNoField(&rocks_db_.cache_index_and_filter_blocks_, false)},
+ {"rocksdb.subkey_block_cache_size", true, new IntField(&rocks_db_.subkey_block_cache_size_, 2048, 0, INT_MAX)},
+ {"rocksdb.metadata_block_cache_size", true,
+ new IntField(&rocks_db_.metadata_block_cache_size_, 2048, 0, INT_MAX)},
{"rocksdb.share_metadata_and_subkey_block_cache", true,
- new YesNoField(&RocksDB.share_metadata_and_subkey_block_cache, true)},
- {"rocksdb.row_cache_size", true, new IntField(&RocksDB.row_cache_size, 0, 0, INT_MAX)},
+ new YesNoField(&rocks_db_.share_metadata_and_subkey_block_cache_, true)},
+ {"rocksdb.row_cache_size", true, new IntField(&rocks_db_.row_cache_size_, 0, 0, INT_MAX)},
{"rocksdb.compaction_readahead_size", false,
- new IntField(&RocksDB.compaction_readahead_size, 2 * MiB, 0, 64 * MiB)},
+ new IntField(&rocks_db_.compaction_readahead_size_, 2 * MiB, 0, 64 * MiB)},
{"rocksdb.level0_slowdown_writes_trigger", false,
- new IntField(&RocksDB.level0_slowdown_writes_trigger, 20, 1, 1024)},
- {"rocksdb.level0_stop_writes_trigger", false, new IntField(&RocksDB.level0_stop_writes_trigger, 40, 1, 1024)},
+ new IntField(&rocks_db_.level0_slowdown_writes_trigger_, 20, 1, 1024)},
+ {"rocksdb.level0_stop_writes_trigger", false, new IntField(&rocks_db_.level0_stop_writes_trigger_, 40, 1, 1024)},
{"rocksdb.level0_file_num_compaction_trigger", false,
- new IntField(&RocksDB.level0_file_num_compaction_trigger, 4, 1, 1024)},
- {"rocksdb.enable_blob_files", false, new YesNoField(&RocksDB.enable_blob_files, false)},
- {"rocksdb.min_blob_size", false, new IntField(&RocksDB.min_blob_size, 4096, 0, INT_MAX)},
- {"rocksdb.blob_file_size", false, new IntField(&RocksDB.blob_file_size, 268435456, 0, INT_MAX)},
- {"rocksdb.enable_blob_garbage_collection", false, new YesNoField(&RocksDB.enable_blob_garbage_collection, true)},
+ new IntField(&rocks_db_.level0_file_num_compaction_trigger_, 4, 1, 1024)},
+ {"rocksdb.enable_blob_files", false, new YesNoField(&rocks_db_.enable_blob_files_, false)},
+ {"rocksdb.min_blob_size", false, new IntField(&rocks_db_.min_blob_size_, 4096, 0, INT_MAX)},
+ {"rocksdb.blob_file_size", false, new IntField(&rocks_db_.blob_file_size_, 268435456, 0, INT_MAX)},
+ {"rocksdb.enable_blob_garbage_collection", false,
+ new YesNoField(&rocks_db_.enable_blob_garbage_collection_, true)},
{"rocksdb.blob_garbage_collection_age_cutoff", false,
- new IntField(&RocksDB.blob_garbage_collection_age_cutoff, 25, 0, 100)},
+ new IntField(&rocks_db_.blob_garbage_collection_age_cutoff_, 25, 0, 100)},
{"rocksdb.max_bytes_for_level_base", false,
- new IntField(&RocksDB.max_bytes_for_level_base, 268435456, 0, INT_MAX)},
+ new IntField(&rocks_db_.max_bytes_for_level_base_, 268435456, 0, INT_MAX)},
{"rocksdb.max_bytes_for_level_multiplier", false,
- new IntField(&RocksDB.max_bytes_for_level_multiplier, 10, 1, 100)},
+ new IntField(&rocks_db_.max_bytes_for_level_multiplier_, 10, 1, 100)},
{"rocksdb.level_compaction_dynamic_level_bytes", false,
- new YesNoField(&RocksDB.level_compaction_dynamic_level_bytes, false)},
- {"rocksdb.max_background_jobs", false, new IntField(&RocksDB.max_background_jobs, 4, 0, 32)},
+ new YesNoField(&rocks_db_.level_compaction_dynamic_level_bytes_, false)},
+ {"rocksdb.max_background_jobs", false, new IntField(&rocks_db_.max_background_jobs_, 4, 0, 32)},
/* rocksdb write options */
- {"rocksdb.write_options.sync", true, new YesNoField(&RocksDB.write_options.sync, false)},
- {"rocksdb.write_options.disable_wal", true, new YesNoField(&RocksDB.write_options.disable_WAL, false)},
- {"rocksdb.write_options.no_slowdown", true, new YesNoField(&RocksDB.write_options.no_slowdown, false)},
- {"rocksdb.write_options.low_pri", true, new YesNoField(&RocksDB.write_options.low_pri, false)},
+ {"rocksdb.write_options.sync", true, new YesNoField(&rocks_db_.write_options_.sync_, false)},
+ {"rocksdb.write_options.disable_wal", true, new YesNoField(&rocks_db_.write_options_.disable_wal_, false)},
+ {"rocksdb.write_options.no_slowdown", true, new YesNoField(&rocks_db_.write_options_.no_slowdown_, false)},
+ {"rocksdb.write_options.low_pri", true, new YesNoField(&rocks_db_.write_options_.low_pri_, false)},
{"rocksdb.write_options.memtable_insert_hint_per_batch", true,
- new YesNoField(&RocksDB.write_options.memtable_insert_hint_per_batch, false)},
+ new YesNoField(&rocks_db_.write_options_.memtable_insert_hint_per_batch_, false)},
/* rocksdb read options */
- {"rocksdb.read_options.async_io", false, new YesNoField(&RocksDB.read_options.async_io, false)},
+ {"rocksdb.read_options.async_io", false, new YesNoField(&rocks_db_.read_options_.async_io_, false)},
};
for (auto &wrapper : fields) {
- auto &field = wrapper.field;
- field->readonly = wrapper.readonly;
- fields_.emplace(std::move(wrapper.name), std::move(field));
+ auto &field = wrapper.field_;
+ field->readonly_ = wrapper.readonly_;
+ fields_.emplace(std::move(wrapper.name_), std::move(field));
}
initFieldValidator();
initFieldCallback();
@@ -237,17 +239,17 @@ void Config::initFieldValidator() {
std::map<std::string, validate_fn> validators = {
{"requirepass",
[this](const std::string &k, const std::string &v) -> Status {
- if (v.empty() && !tokens.empty()) {
+ if (v.empty() && !tokens_.empty()) {
return {Status::NotOK, "requirepass empty not allowed while the namespace exists"};
}
- if (tokens.find(v) != tokens.end()) {
+ if (tokens_.find(v) != tokens_.end()) {
return {Status::NotOK, "requirepass is duplicated with namespace tokens"};
}
return Status::OK();
}},
{"masterauth",
[this](const std::string &k, const std::string &v) -> Status {
- if (tokens.find(v) != tokens.end()) {
+ if (tokens_.find(v) != tokens_.end()) {
return {Status::NotOK, "masterauth is duplicated with namespace tokens"};
}
return Status::OK();
@@ -255,18 +257,18 @@ void Config::initFieldValidator() {
{"compact-cron",
[this](const std::string &k, const std::string &v) -> Status {
std::vector<std::string> args = Util::Split(v, " \t");
- return compact_cron.SetScheduleTime(args);
+ return compact_cron_.SetScheduleTime(args);
}},
{"bgsave-cron",
[this](const std::string &k, const std::string &v) -> Status {
std::vector<std::string> args = Util::Split(v, " \t");
- return bgsave_cron.SetScheduleTime(args);
+ return bgsave_cron_.SetScheduleTime(args);
}},
{"compaction-checker-range",
[this](const std::string &k, const std::string &v) -> Status {
if (v.empty()) {
- compaction_checker_range.Start = -1;
- compaction_checker_range.Stop = -1;
+ compaction_checker_range_.start_ = -1;
+ compaction_checker_range_.stop_ = -1;
return Status::OK();
}
std::vector<std::string> args = Util::Split(v, "-");
@@ -276,8 +278,8 @@ void Config::initFieldValidator() {
auto start = GET_OR_RET(ParseInt<int>(args[0], {0, 24}, 10)),
stop = GET_OR_RET(ParseInt<int>(args[1], {0, 24}, 10));
if (start > stop) return {Status::NotOK, "invalid range format, start should be smaller than stop"};
- compaction_checker_range.Start = start;
- compaction_checker_range.Stop = stop;
+ compaction_checker_range_.start_ = start;
+ compaction_checker_range_.stop_ = stop;
return Status::OK();
}},
{"rename-command",
@@ -308,7 +310,7 @@ void Config::initFieldValidator() {
for (const auto &iter : validators) {
auto field_iter = fields_.find(iter.first);
if (field_iter != fields_.end()) {
- field_iter->second->validate = iter.second;
+ field_iter->second->validate_ = iter.second;
}
}
}
@@ -340,17 +342,17 @@ void Config::initFieldCallback() {
std::map<std::string, callback_fn> callbacks = {
{"dir",
[this](Server *srv, const std::string &k, const std::string &v) -> Status {
- db_dir = dir + "/db";
+ db_dir_ = dir_ + "/db";
{
std::lock_guard<std::mutex> lg(this->backup_mu_);
- if (backup_dir.empty()) {
- backup_dir = dir + "/backup";
+ if (backup_dir_.empty()) {
+ backup_dir_ = dir_ + "/backup";
}
}
- if (log_dir.empty()) log_dir = dir;
- checkpoint_dir = dir + "/checkpoint";
- sync_checkpoint_dir = dir + "/sync_checkpoint";
- backup_sync_dir = dir + "/backup_for_sync";
+ if (log_dir_.empty()) log_dir_ = dir_;
+ checkpoint_dir_ = dir_ + "/checkpoint";
+ sync_checkpoint_dir_ = dir_ + "/sync_checkpoint";
+ backup_sync_dir_ = dir_ + "/backup_for_sync";
return Status::OK();
}},
{"backup-dir",
@@ -360,8 +362,8 @@ void Config::initFieldCallback() {
// Note: currently, backup_mu_ may block by backing up or purging,
// the command may wait for seconds.
std::lock_guard<std::mutex> lg(this->backup_mu_);
- previous_backup = std::move(backup_dir);
- backup_dir = v;
+ previous_backup = std::move(backup_dir_);
+ backup_dir_ = v;
}
if (!previous_backup.empty() && srv != nullptr && !srv->IsLoading()) {
// LOG(INFO) should be called after log is initialized and server is loaded.
@@ -371,13 +373,13 @@ void Config::initFieldCallback() {
}},
{"cluster-enabled",
[this](Server *srv, const std::string &k, const std::string &v) -> Status {
- if (cluster_enabled) slot_id_encoded = true;
+ if (cluster_enabled_) slot_id_encoded_ = true;
return Status::OK();
}},
{"bind",
[this](Server *srv, const std::string &k, const std::string &v) -> Status {
std::vector<std::string> args = Util::Split(v, " \t");
- binds = std::move(args);
+ binds_ = std::move(args);
return Status::OK();
}},
{"maxclients",
@@ -394,38 +396,38 @@ void Config::initFieldCallback() {
std::vector<std::string> args = Util::Split(v, " \t");
if (args.size() != 2) return {Status::NotOK, "wrong number of arguments"};
if (args[0] != "no" && args[1] != "one") {
- master_host = args[0];
+ master_host_ = args[0];
auto parse_result = ParseInt<int>(args[1], NumericRange<int>{1, PORT_LIMIT - 1}, 10);
if (!parse_result) {
return {Status::NotOK, "should be between 0 and 65535"};
}
- master_port = *parse_result;
+ master_port_ = *parse_result;
}
return Status::OK();
}},
{"profiling-sample-commands",
[this](Server *srv, const std::string &k, const std::string &v) -> Status {
std::vector<std::string> cmds = Util::Split(v, ",");
- profiling_sample_all_commands = false;
- profiling_sample_commands.clear();
+ profiling_sample_all_commands_ = false;
+ profiling_sample_commands_.clear();
for (auto const &cmd : cmds) {
if (cmd == "*") {
- profiling_sample_all_commands = true;
- profiling_sample_commands.clear();
+ profiling_sample_all_commands_ = true;
+ profiling_sample_commands_.clear();
return Status::OK();
}
if (!Redis::IsCommandExists(cmd)) {
return {Status::NotOK, cmd + " is not Kvrocks supported command"};
}
// profiling_sample_commands use command's original name, regardless of rename-command directive
- profiling_sample_commands.insert(cmd);
+ profiling_sample_commands_.insert(cmd);
}
return Status::OK();
}},
{"slowlog-max-len",
[this](Server *srv, const std::string &k, const std::string &v) -> Status {
if (!srv) return Status::OK();
- srv->GetSlowLog()->SetMaxEntries(slowlog_max_len);
+ srv->GetSlowLog()->SetMaxEntries(slowlog_max_len_);
return Status::OK();
}},
{"max-db-size",
@@ -437,42 +439,42 @@ void Config::initFieldCallback() {
{"max-io-mb",
[this](Server *srv, const std::string &k, const std::string &v) -> Status {
if (!srv) return Status::OK();
- srv->storage_->SetIORateLimit(max_io_mb);
+ srv->storage_->SetIORateLimit(max_io_mb_);
return Status::OK();
}},
{"profiling-sample-record-max-len",
[this](Server *srv, const std::string &k, const std::string &v) -> Status {
if (!srv) return Status::OK();
- srv->GetPerfLog()->SetMaxEntries(profiling_sample_record_max_len);
+ srv->GetPerfLog()->SetMaxEntries(profiling_sample_record_max_len_);
return Status::OK();
}},
{"migrate-speed",
[this](Server *srv, const std::string &k, const std::string &v) -> Status {
if (!srv) return Status::OK();
- if (cluster_enabled) srv->slot_migrator_->SetMaxMigrationSpeed(migrate_speed);
+ if (cluster_enabled_) srv->slot_migrator_->SetMaxMigrationSpeed(migrate_speed_);
return Status::OK();
}},
{"migrate-pipeline-size",
[this](Server *srv, const std::string &k, const std::string &v) -> Status {
if (!srv) return Status::OK();
- if (cluster_enabled) srv->slot_migrator_->SetMaxPipelineSize(pipeline_size);
+ if (cluster_enabled_) srv->slot_migrator_->SetMaxPipelineSize(pipeline_size_);
return Status::OK();
}},
{"migrate-sequence-gap",
[this](Server *srv, const std::string &k, const std::string &v) -> Status {
if (!srv) return Status::OK();
- if (cluster_enabled) srv->slot_migrator_->SetSequenceGapLimit(sequence_gap);
+ if (cluster_enabled_) srv->slot_migrator_->SetSequenceGapLimit(sequence_gap_);
return Status::OK();
}},
{"log-retention-days",
[this](Server *srv, const std::string &k, const std::string &v) -> Status {
if (!srv) return Status::OK();
- if (Util::ToLower(log_dir) == "stdout") {
+ if (Util::ToLower(log_dir_) == "stdout") {
return {Status::NotOK, "can't set the 'log-retention-days' when the log dir is stdout"};
}
- if (log_retention_days != -1) {
- google::EnableLogCleaner(log_retention_days);
+ if (log_retention_days_ != -1) {
+ google::EnableLogCleaner(log_retention_days_);
} else {
google::DisableLogCleaner();
}
@@ -480,7 +482,7 @@ void Config::initFieldCallback() {
}},
{"persist-cluster-nodes-enabled",
[this](Server *srv, const std::string &k, const std::string &v) -> Status {
- if (!srv || !cluster_enabled) return Status::OK();
+ if (!srv || !cluster_enabled_) return Status::OK();
auto nodes_file_path = NodesFilePath();
if (v == "yes") {
return srv->cluster_->DumpClusterNodes(nodes_file_path);
@@ -493,13 +495,13 @@ void Config::initFieldCallback() {
[this](Server *srv, const std::string &k, const std::string &v) -> Status {
if (!srv) return Status::OK();
return srv->storage_->SetOptionForAllColumnFamilies(trimRocksDBPrefix(k),
- std::to_string(RocksDB.target_file_size_base * MiB));
+ std::to_string(rocks_db_.target_file_size_base_ * MiB));
}},
{"rocksdb.write_buffer_size",
[this](Server *srv, const std::string &k, const std::string &v) -> Status {
if (!srv) return Status::OK();
return srv->storage_->SetOptionForAllColumnFamilies(trimRocksDBPrefix(k),
- std::to_string(RocksDB.write_buffer_size * MiB));
+ std::to_string(rocks_db_.write_buffer_size_ * MiB));
}},
{"rocksdb.disable_auto_compactions",
[](Server *srv, const std::string &k, const std::string &v) -> Status {
@@ -510,18 +512,18 @@ void Config::initFieldCallback() {
{"rocksdb.max_total_wal_size",
[this](Server *srv, const std::string &k, const std::string &v) -> Status {
if (!srv) return Status::OK();
- return srv->storage_->SetDBOption(trimRocksDBPrefix(k), std::to_string(RocksDB.max_total_wal_size * MiB));
+ return srv->storage_->SetDBOption(trimRocksDBPrefix(k), std::to_string(rocks_db_.max_total_wal_size_ * MiB));
}},
{"rocksdb.enable_blob_files",
[this](Server *srv, const std::string &k, const std::string &v) -> Status {
if (!srv) return Status::OK();
- std::string enable_blob_files = RocksDB.enable_blob_files ? "true" : "false";
+ std::string enable_blob_files = rocks_db_.enable_blob_files_ ? "true" : "false";
return srv->storage_->SetOptionForAllColumnFamilies(trimRocksDBPrefix(k), enable_blob_files);
}},
{"rocksdb.min_blob_size",
[this](Server *srv, const std::string &k, const std::string &v) -> Status {
if (!srv) return Status::OK();
- if (!RocksDB.enable_blob_files) {
+ if (!rocks_db_.enable_blob_files_) {
return {Status::NotOK, errBlobDbNotEnabled};
}
return srv->storage_->SetOptionForAllColumnFamilies(trimRocksDBPrefix(k), v);
@@ -529,16 +531,16 @@ void Config::initFieldCallback() {
{"rocksdb.blob_file_size",
[this](Server *srv, const std::string &k, const std::string &v) -> Status {
if (!srv) return Status::OK();
- if (!RocksDB.enable_blob_files) {
+ if (!rocks_db_.enable_blob_files_) {
return {Status::NotOK, errBlobDbNotEnabled};
}
return srv->storage_->SetOptionForAllColumnFamilies(trimRocksDBPrefix(k),
- std::to_string(RocksDB.blob_file_size));
+ std::to_string(rocks_db_.blob_file_size_));
}},
{"rocksdb.enable_blob_garbage_collection",
[this](Server *srv, const std::string &k, const std::string &v) -> Status {
if (!srv) return Status::OK();
- if (!RocksDB.enable_blob_files) {
+ if (!rocks_db_.enable_blob_files_) {
return {Status::NotOK, errBlobDbNotEnabled};
}
std::string enable_blob_garbage_collection = v == "yes" ? "true" : "false";
@@ -547,7 +549,7 @@ void Config::initFieldCallback() {
{"rocksdb.blob_garbage_collection_age_cutoff",
[this](Server *srv, const std::string &k, const std::string &v) -> Status {
if (!srv) return Status::OK();
- if (!RocksDB.enable_blob_files) {
+ if (!rocks_db_.enable_blob_files_) {
return {Status::NotOK, errBlobDbNotEnabled};
}
int val = 0;
@@ -572,16 +574,16 @@ void Config::initFieldCallback() {
{"rocksdb.max_bytes_for_level_base",
[this](Server *srv, const std::string &k, const std::string &v) -> Status {
if (!srv) return Status::OK();
- if (!RocksDB.level_compaction_dynamic_level_bytes) {
+ if (!rocks_db_.level_compaction_dynamic_level_bytes_) {
return {Status::NotOK, errLevelCompactionDynamicLevelBytesNotSet};
}
return srv->storage_->SetOptionForAllColumnFamilies(trimRocksDBPrefix(k),
- std::to_string(RocksDB.max_bytes_for_level_base));
+ std::to_string(rocks_db_.max_bytes_for_level_base_));
}},
{"rocksdb.max_bytes_for_level_multiplier",
[this](Server *srv, const std::string &k, const std::string &v) -> Status {
if (!srv) return Status::OK();
- if (!RocksDB.level_compaction_dynamic_level_bytes) {
+ if (!rocks_db_.level_compaction_dynamic_level_bytes_) {
return {Status::NotOK, errLevelCompactionDynamicLevelBytesNotSet};
}
return srv->storage_->SetOptionForAllColumnFamilies(trimRocksDBPrefix(k), v);
@@ -617,19 +619,19 @@ void Config::initFieldCallback() {
for (const auto &iter : callbacks) {
auto field_iter = fields_.find(iter.first);
if (field_iter != fields_.end()) {
- field_iter->second->callback = iter.second;
+ field_iter->second->callback_ = iter.second;
}
}
}
-std::string Config::NodesFilePath() const { return dir + "/nodes.conf"; }
+std::string Config::NodesFilePath() const { return dir_ + "/nodes.conf"; }
void Config::SetMaster(const std::string &host, uint32_t port) {
- master_host = host;
- master_port = port;
+ master_host_ = host;
+ master_port_ = port;
auto iter = fields_.find("slaveof");
if (iter != fields_.end()) {
- auto s = iter->second->Set(master_host + " " + std::to_string(master_port));
+ auto s = iter->second->Set(master_host_ + " " + std::to_string(master_port_));
if (!s.IsOK()) {
LOG(ERROR) << "Failed to set the value of 'slaveof' setting: " << s.Msg();
}
@@ -637,8 +639,8 @@ void Config::SetMaster(const std::string &host, uint32_t port) {
}
void Config::ClearMaster() {
- master_host.clear();
- master_port = 0;
+ master_host_.clear();
+ master_port_ = 0;
auto iter = fields_.find("slaveof");
if (iter != fields_.end()) {
auto s = iter->second->Set("no one");
@@ -655,12 +657,12 @@ Status Config::parseConfigFromPair(const std::pair<std::string, std::string> &in
if (strncasecmp(input.first.data(), ns_str, ns_str_size) == 0) {
// namespace should keep key case-sensitive
field_key = input.first;
- tokens[input.second] = input.first.substr(ns_str_size);
+ tokens_[input.second] = input.first.substr(ns_str_size);
}
auto iter = fields_.find(field_key);
if (iter != fields_.end()) {
auto &field = iter->second;
- field->line_number = line_number;
+ field->line_number_ = line_number;
auto s = field->Set(input.second);
if (!s.IsOK()) return s.Prefixed(fmt::format("failed to set value of field '{}'", field_key));
}
@@ -679,28 +681,28 @@ Status Config::parseConfigFromString(const std::string &input, int line_number)
}
Status Config::finish() {
- if (requirepass.empty() && !tokens.empty()) {
+ if (requirepass_.empty() && !tokens_.empty()) {
return {Status::NotOK, "requirepass empty wasn't allowed while the namespace exists"};
}
- if ((cluster_enabled) && !tokens.empty()) {
+ if ((cluster_enabled_) && !tokens_.empty()) {
return {Status::NotOK, "enabled cluster mode wasn't allowed while the namespace exists"};
}
- if (unixsocket.empty() && binds.size() == 0) {
- binds.emplace_back(kDefaultBindAddress);
+ if (unixsocket_.empty() && binds_.size() == 0) {
+ binds_.emplace_back(kDefaultBindAddress);
}
- if (cluster_enabled && binds.size() == 0) {
+ if (cluster_enabled_ && binds_.size() == 0) {
return {Status::NotOK,
"node is in cluster mode, but TCP listen address "
"wasn't specified via configuration file"};
}
- if (master_port != 0 && binds.size() == 0) {
+ if (master_port_ != 0 && binds_.size() == 0) {
return {Status::NotOK, "replication doesn't support unix socket"};
}
- if (db_dir.empty()) db_dir = dir + "/db";
- if (backup_dir.empty()) backup_dir = dir + "/backup";
- if (log_dir.empty()) log_dir = dir;
- if (pidfile.empty()) pidfile = dir + "/kvrocks.pid";
- std::vector<std::string> create_dirs = {dir};
+ if (db_dir_.empty()) db_dir_ = dir_ + "/db";
+ if (backup_dir_.empty()) backup_dir_ = dir_ + "/backup";
+ if (log_dir_.empty()) log_dir_ = dir_;
+ if (pidfile_.empty()) pidfile_ = dir_ + "/kvrocks.pid";
+ std::vector<std::string> create_dirs = {dir_};
for (const auto &name : create_dirs) {
auto s = rocksdb::Env::Default()->CreateDirIfMissing(name);
if (!s.ok()) return {Status::NotOK, s.ToString()};
@@ -709,13 +711,13 @@ Status Config::finish() {
}
Status Config::Load(const CLIOptions &opts) {
- if (!opts.conf_file.empty()) {
+ if (!opts.conf_file_.empty()) {
std::ifstream file;
std::istream *in = nullptr;
- if (opts.conf_file == "-") {
+ if (opts.conf_file_ == "-") {
in = &std::cin;
} else {
- path_ = opts.conf_file;
+ path_ = opts.conf_file_;
file.open(path_);
if (!file.is_open()) {
return {Status::NotOK, fmt::format("failed to open file '{}': {}", path_, strerror(errno))};
@@ -739,24 +741,24 @@ Status Config::Load(const CLIOptions &opts) {
<< "In order to specify a config file use 'kvrocks -c /path/to/kvrocks.conf'" << std::endl;
}
- for (const auto &opt : opts.cli_options) {
+ for (const auto &opt : opts.cli_options_) {
GET_OR_RET(parseConfigFromPair(opt, -1).Prefixed("CLI config option error"));
}
for (const auto &iter : fields_) {
// line_number = 0 means the user didn't specify the field value
// on config file and would use default value, so won't validate here.
- if (iter.second->line_number != 0 && iter.second->validate) {
- auto s = iter.second->validate(iter.first, iter.second->ToString());
+ if (iter.second->line_number_ != 0 && iter.second->validate_) {
+ auto s = iter.second->validate_(iter.first, iter.second->ToString());
if (!s.IsOK()) {
- return s.Prefixed(fmt::format("at line #L{}: {} is invalid", iter.second->line_number, iter.first));
+ return s.Prefixed(fmt::format("at line #L{}: {} is invalid", iter.second->line_number_, iter.first));
}
}
}
for (const auto &iter : fields_) {
- if (iter.second->callback) {
- auto s = iter.second->callback(nullptr, iter.first, iter.second->ToString());
+ if (iter.second->callback_) {
+ auto s = iter.second->callback_(nullptr, iter.first, iter.second->ToString());
if (!s.IsOK()) {
return s.Prefixed(fmt::format("while changing key '{}'", iter.first));
}
@@ -785,21 +787,21 @@ void Config::Get(const std::string &key, std::vector<std::string> *values) {
Status Config::Set(Server *svr, std::string key, const std::string &value) {
key = Util::ToLower(key);
auto iter = fields_.find(key);
- if (iter == fields_.end() || iter->second->readonly) {
+ if (iter == fields_.end() || iter->second->readonly_) {
return {Status::NotOK, "Unsupported CONFIG parameter: " + key};
}
auto &field = iter->second;
- if (field->validate) {
- auto s = field->validate(key, value);
+ if (field->validate_) {
+ auto s = field->validate_(key, value);
if (!s.IsOK()) return s.Prefixed("invalid value");
}
auto s = field->Set(value);
if (!s.IsOK()) return s.Prefixed("failed to set new value");
- if (field->callback) {
- return field->callback(svr, key, value);
+ if (field->callback_) {
+ return field->callback_(svr, key, value);
}
return Status::OK();
@@ -822,7 +824,7 @@ Status Config::Rewrite() {
}
std::string namespace_prefix = "namespace.";
- for (const auto &iter : tokens) {
+ for (const auto &iter : tokens_) {
new_config[namespace_prefix + iter.second] = iter.first;
}
@@ -873,7 +875,7 @@ Status Config::Rewrite() {
Status Config::GetNamespace(const std::string &ns, std::string *token) {
token->clear();
- for (const auto &iter : tokens) {
+ for (const auto &iter : tokens_) {
if (iter.second == ns) {
*token = iter.first;
return Status::OK();
@@ -886,23 +888,23 @@ Status Config::SetNamespace(const std::string &ns, const std::string &token) {
if (ns == kDefaultNamespace) {
return {Status::NotOK, "forbidden to update the default namespace"};
}
- if (tokens.find(token) != tokens.end()) {
+ if (tokens_.find(token) != tokens_.end()) {
return {Status::NotOK, "the token has already exists"};
}
- if (token == requirepass || token == masterauth) {
+ if (token == requirepass_ || token == masterauth_) {
return {Status::NotOK, "the token is duplicated with requirepass or masterauth"};
}
- for (const auto &iter : tokens) {
+ for (const auto &iter : tokens_) {
if (iter.second == ns) {
- tokens.erase(iter.first);
- tokens[token] = ns;
+ tokens_.erase(iter.first);
+ tokens_[token] = ns;
auto s = Rewrite();
if (!s.IsOK()) {
// Need to roll back the old token if fails to rewrite the config
- tokens.erase(token);
- tokens[iter.first] = ns;
+ tokens_.erase(token);
+ tokens_[iter.first] = ns;
}
return s;
}
@@ -911,10 +913,10 @@ Status Config::SetNamespace(const std::string &ns, const std::string &token) {
}
Status Config::AddNamespace(const std::string &ns, const std::string &token) {
- if (requirepass.empty()) {
+ if (requirepass_.empty()) {
return {Status::NotOK, "forbidden to add namespace when requirepass was empty"};
}
- if (cluster_enabled) {
+ if (cluster_enabled_) {
return {Status::NotOK, "forbidden to add namespace when cluster mode was enabled"};
}
if (ns == kDefaultNamespace) {
@@ -922,24 +924,24 @@ Status Config::AddNamespace(const std::string &ns, const std::string &token) {
}
auto s = isNamespaceLegal(ns);
if (!s.IsOK()) return s;
- if (tokens.find(token) != tokens.end()) {
+ if (tokens_.find(token) != tokens_.end()) {
return {Status::NotOK, "the token has already exists"};
}
- if (token == requirepass || token == masterauth) {
+ if (token == requirepass_ || token == masterauth_) {
return {Status::NotOK, "the token is duplicated with requirepass or masterauth"};
}
- for (const auto &iter : tokens) {
+ for (const auto &iter : tokens_) {
if (iter.second == ns) {
return {Status::NotOK, "the namespace has already exists"};
}
}
- tokens[token] = ns;
+ tokens_[token] = ns;
s = Rewrite();
if (!s.IsOK()) {
- tokens.erase(token);
+ tokens_.erase(token);
}
return s;
}
@@ -948,12 +950,12 @@ Status Config::DelNamespace(const std::string &ns) {
if (ns == kDefaultNamespace) {
return {Status::NotOK, "forbidden to delete the default namespace"};
}
- for (const auto &iter : tokens) {
+ for (const auto &iter : tokens_) {
if (iter.second == ns) {
- tokens.erase(iter.first);
+ tokens_.erase(iter.first);
auto s = Rewrite();
if (!s.IsOK()) {
- tokens[iter.first] = ns;
+ tokens_[iter.first] = ns;
}
return s;
}
diff --git a/src/config/config.h b/src/config/config.h
index 6496f14e..31386cf4 100644
--- a/src/config/config.h
+++ b/src/config/config.h
@@ -55,151 +55,151 @@ constexpr const char *kDefaultNamespace = "__namespace";
struct CompactionCheckerRange {
public:
- int Start;
- int Stop;
+ int start_;
+ int stop_;
- bool Enabled() const { return Start != -1 || Stop != -1; }
+ bool Enabled() const { return start_ != -1 || stop_ != -1; }
};
struct CLIOptions {
- std::string conf_file;
- std::vector<std::pair<std::string, std::string>> cli_options;
+ std::string conf_file_;
+ std::vector<std::pair<std::string, std::string>> cli_options_;
CLIOptions() = default;
- explicit CLIOptions(std::string_view file) : conf_file(file) {}
+ explicit CLIOptions(std::string_view file) : conf_file_(file) {}
};
struct Config {
public:
Config();
~Config() = default;
- uint32_t port = 0;
- uint32_t tls_port = 0;
- std::string tls_cert_file;
- std::string tls_key_file;
- std::string tls_key_file_pass;
- std::string tls_ca_cert_file;
- std::string tls_ca_cert_dir;
- std::string tls_auth_clients;
- bool tls_prefer_server_ciphers = false;
- std::string tls_ciphers;
- std::string tls_ciphersuites;
- std::string tls_protocols;
- bool tls_session_caching = true;
- int tls_session_cache_size = 1024 * 20;
- int tls_session_cache_timeout = 300;
- int workers = 0;
- int timeout = 0;
- int log_level = 0;
- int backlog = 511;
- int maxclients = 10000;
- int max_backup_to_keep = 1;
- int max_backup_keep_hours = 24;
- int slowlog_log_slower_than = 100000;
- int slowlog_max_len = 128;
- bool daemonize = false;
- int supervised_mode = kSupervisedNone;
- bool slave_readonly = true;
- bool slave_serve_stale_data = true;
- bool slave_empty_db_before_fullsync = false;
- int slave_priority = 100;
- int max_db_size = 0;
- int max_replication_mb = 0;
- int max_io_mb = 0;
- int max_bitmap_to_string_mb = 16;
- bool master_use_repl_port = false;
- bool purge_backup_on_fullsync = false;
- bool auto_resize_block_and_sst = true;
- int fullsync_recv_file_delay = 0;
- bool use_rsid_psync = false;
- std::vector<std::string> binds;
- std::string dir;
- std::string db_dir;
- std::string backup_dir; // GUARD_BY(backup_mu_)
- std::string backup_sync_dir;
- std::string checkpoint_dir;
- std::string sync_checkpoint_dir;
- std::string log_dir;
- std::string pidfile;
- std::string db_name;
- std::string masterauth;
- std::string requirepass;
- std::string master_host;
- std::string unixsocket;
- int unixsocketperm = 0777;
- uint32_t master_port = 0;
- Cron compact_cron;
- Cron bgsave_cron;
- CompactionCheckerRange compaction_checker_range{-1, -1};
- int64_t force_compact_file_age;
- int force_compact_file_min_deleted_percentage;
- std::map<std::string, std::string> tokens;
- std::string replica_announce_ip;
- uint32_t replica_announce_port = 0;
-
- bool persist_cluster_nodes_enabled = true;
- bool slot_id_encoded = false;
- bool cluster_enabled = false;
- int migrate_speed;
- int pipeline_size;
- int sequence_gap;
-
- int log_retention_days;
+ uint32_t port_ = 0;
+ uint32_t tls_port_ = 0;
+ std::string tls_cert_file_;
+ std::string tls_key_file_;
+ std::string tls_key_file_pass_;
+ std::string tls_ca_cert_file_;
+ std::string tls_ca_cert_dir_;
+ std::string tls_auth_clients_;
+ bool tls_prefer_server_ciphers_ = false;
+ std::string tls_ciphers_;
+ std::string tls_ciphersuites_;
+ std::string tls_protocols_;
+ bool tls_session_caching_ = true;
+ int tls_session_cache_size_ = 1024 * 20;
+ int tls_session_cache_timeout_ = 300;
+ int workers_ = 0;
+ int timeout_ = 0;
+ int log_level_ = 0;
+ int backlog_ = 511;
+ int maxclients_ = 10000;
+ int max_backup_to_keep_ = 1;
+ int max_backup_keep_hours_ = 24;
+ int slowlog_log_slower_than_ = 100000;
+ int slowlog_max_len_ = 128;
+ bool daemonize_ = false;
+ int supervised_mode_ = kSupervisedNone;
+ bool slave_readonly_ = true;
+ bool slave_serve_stale_data_ = true;
+ bool slave_empty_db_before_fullsync_ = false;
+ int slave_priority_ = 100;
+ int max_db_size_ = 0;
+ int max_replication_mb_ = 0;
+ int max_io_mb_ = 0;
+ int max_bitmap_to_string_mb_ = 16;
+ bool master_use_repl_port_ = false;
+ bool purge_backup_on_fullsync_ = false;
+ bool auto_resize_block_and_sst_ = true;
+ int fullsync_recv_file_delay_ = 0;
+ bool use_rsid_psync_ = false;
+ std::vector<std::string> binds_;
+ std::string dir_;
+ std::string db_dir_;
+ std::string backup_dir_; // GUARD_BY(backup_mu_)
+ std::string backup_sync_dir_;
+ std::string checkpoint_dir_;
+ std::string sync_checkpoint_dir_;
+ std::string log_dir_;
+ std::string pidfile_;
+ std::string db_name_;
+ std::string masterauth_;
+ std::string requirepass_;
+ std::string master_host_;
+ std::string unixsocket_;
+ int unixsocketperm_ = 0777;
+ uint32_t master_port_ = 0;
+ Cron compact_cron_;
+ Cron bgsave_cron_;
+ CompactionCheckerRange compaction_checker_range_{-1, -1};
+ int64_t force_compact_file_age_;
+ int force_compact_file_min_deleted_percentage_;
+ std::map<std::string, std::string> tokens_;
+ std::string replica_announce_ip_;
+ uint32_t replica_announce_port_ = 0;
+
+ bool persist_cluster_nodes_enabled_ = true;
+ bool slot_id_encoded_ = false;
+ bool cluster_enabled_ = false;
+ int migrate_speed_;
+ int pipeline_size_;
+ int sequence_gap_;
+
+ int log_retention_days_;
// profiling
- int profiling_sample_ratio = 0;
- int profiling_sample_record_threshold_ms = 0;
- int profiling_sample_record_max_len = 128;
- std::set<std::string> profiling_sample_commands;
- bool profiling_sample_all_commands = false;
+ int profiling_sample_ratio_ = 0;
+ int profiling_sample_record_threshold_ms_ = 0;
+ int profiling_sample_record_max_len_ = 128;
+ std::set<std::string> profiling_sample_commands_;
+ bool profiling_sample_all_commands_ = false;
struct RocksDB {
- int block_size;
- bool cache_index_and_filter_blocks;
- int metadata_block_cache_size;
- int subkey_block_cache_size;
- bool share_metadata_and_subkey_block_cache;
- int row_cache_size;
- int max_open_files;
- int write_buffer_size;
- int max_write_buffer_number;
- int max_background_compactions;
- int max_background_flushes;
- int max_sub_compactions;
- int stats_dump_period_sec;
- bool enable_pipelined_write;
- int64_t delayed_write_rate;
- int compaction_readahead_size;
- int target_file_size_base;
- int WAL_ttl_seconds;
- int WAL_size_limit_MB;
- int max_total_wal_size;
- int level0_slowdown_writes_trigger;
- int level0_stop_writes_trigger;
- int level0_file_num_compaction_trigger;
- int compression;
- bool disable_auto_compactions;
- bool enable_blob_files;
- int min_blob_size;
- int blob_file_size;
- bool enable_blob_garbage_collection;
- int blob_garbage_collection_age_cutoff;
- int max_bytes_for_level_base;
- int max_bytes_for_level_multiplier;
- bool level_compaction_dynamic_level_bytes;
- int max_background_jobs;
+ int block_size_;
+ bool cache_index_and_filter_blocks_;
+ int metadata_block_cache_size_;
+ int subkey_block_cache_size_;
+ bool share_metadata_and_subkey_block_cache_;
+ int row_cache_size_;
+ int max_open_files_;
+ int write_buffer_size_;
+ int max_write_buffer_number_;
+ int max_background_compactions_;
+ int max_background_flushes_;
+ int max_sub_compactions_;
+ int stats_dump_period_sec_;
+ bool enable_pipelined_write_;
+ int64_t delayed_write_rate_;
+ int compaction_readahead_size_;
+ int target_file_size_base_;
+ int wal_ttl_seconds_;
+ int wal_size_limit_mb_;
+ int max_total_wal_size_;
+ int level0_slowdown_writes_trigger_;
+ int level0_stop_writes_trigger_;
+ int level0_file_num_compaction_trigger_;
+ int compression_;
+ bool disable_auto_compactions_;
+ bool enable_blob_files_;
+ int min_blob_size_;
+ int blob_file_size_;
+ bool enable_blob_garbage_collection_;
+ int blob_garbage_collection_age_cutoff_;
+ int max_bytes_for_level_base_;
+ int max_bytes_for_level_multiplier_;
+ bool level_compaction_dynamic_level_bytes_;
+ int max_background_jobs_;
struct WriteOptions {
- bool sync;
- bool disable_WAL;
- bool no_slowdown;
- bool low_pri;
- bool memtable_insert_hint_per_batch;
- } write_options;
+ bool sync_;
+ bool disable_wal_;
+ bool no_slowdown_;
+ bool low_pri_;
+ bool memtable_insert_hint_per_batch_;
+ } write_options_;
struct ReadOptions {
- bool async_io;
- } read_options;
- } RocksDB;
+ bool async_io_;
+ } read_options_;
+ } rocks_db_;
mutable std::mutex backup_mu_;
@@ -217,12 +217,12 @@ struct Config {
private:
std::string path_;
- std::string binds_;
+ std::string binds_str_;
std::string slaveof_;
- std::string compact_cron_;
- std::string bgsave_cron_;
- std::string compaction_checker_range_;
- std::string profiling_sample_commands_;
+ std::string compact_cron_str_;
+ std::string bgsave_cron_str_;
+ std::string compaction_checker_range_str_;
+ std::string profiling_sample_commands_str_;
std::map<std::string, std::unique_ptr<ConfigField>> fields_;
std::vector<std::string> rename_command_;
diff --git a/src/config/config_type.h b/src/config/config_type.h
index 7d39e0d9..82c40d6b 100644
--- a/src/config/config_type.h
+++ b/src/config/config_type.h
@@ -47,8 +47,8 @@ using UInt32Field = IntegerField<uint32_t>;
using Int64Field = IntegerField<int64_t>;
struct ConfigEnum {
- const char *name;
- const int val;
+ const char *name_;
+ const int val_;
};
enum configType { SingleConfig, MultiConfig };
@@ -64,15 +64,15 @@ class ConfigField {
virtual Status Set(const std::string &v) = 0;
virtual Status ToNumber(int64_t *n) { return {Status::NotOK, "not supported"}; }
virtual Status ToBool(bool *b) { return {Status::NotOK, "not supported"}; }
- virtual configType GetConfigType() { return config_type; }
- virtual bool IsMultiConfig() { return config_type == configType::MultiConfig; }
- virtual bool IsSingleConfig() { return config_type == configType::SingleConfig; }
-
- int line_number = 0;
- bool readonly = true;
- validate_fn validate = nullptr;
- callback_fn callback = nullptr;
- configType config_type = configType::SingleConfig;
+ virtual configType GetConfigType() { return config_type_; }
+ virtual bool IsMultiConfig() { return config_type_ == configType::MultiConfig; }
+ virtual bool IsSingleConfig() { return config_type_ == configType::SingleConfig; }
+
+ int line_number_ = 0;
+ bool readonly_ = true;
+ validate_fn validate_ = nullptr;
+ callback_fn callback_ = nullptr;
+ configType config_type_ = configType::SingleConfig;
};
class StringField : public ConfigField {
@@ -93,7 +93,7 @@ class MultiStringField : public ConfigField {
public:
MultiStringField(std::vector<std::string> *receiver, std::vector<std::string> input) : receiver_(receiver) {
*receiver_ = std::move(input);
- this->config_type = configType::MultiConfig;
+ this->config_type_ = configType::MultiConfig;
}
~MultiStringField() override = default;
std::string ToString() override {
diff --git a/src/main.cc b/src/main.cc
index 01565614..cbafd519 100644
--- a/src/main.cc
+++ b/src/main.cc
@@ -161,7 +161,7 @@ static CLIOptions parseCommandLineOptions(int argc, char **argv) {
for (int i = 1; i < argc; ++i) {
if ((argv[i] == "-c"sv || argv[i] == "--config"sv) && i + 1 < argc) {
- opts.conf_file = argv[++i];
+ opts.conf_file_ = argv[++i];
} else if (argv[i] == "-v"sv || argv[i] == "--version"sv) {
std::cout << printVersion << std::endl;
std::exit(0);
@@ -170,7 +170,7 @@ static CLIOptions parseCommandLineOptions(int argc, char **argv) {
std::exit(0);
} else if (std::string_view(argv[i], 2) == "--" && std::string_view(argv[i]).size() > 2 && i + 1 < argc) {
auto key = std::string_view(argv[i] + 2);
- opts.cli_options.emplace_back(key, argv[++i]);
+ opts.cli_options_.emplace_back(key, argv[++i]);
} else {
printUsage(*argv);
std::exit(1);
@@ -181,20 +181,20 @@ static CLIOptions parseCommandLineOptions(int argc, char **argv) {
}
static void initGoogleLog(const Config *config) {
- FLAGS_minloglevel = config->log_level;
+ FLAGS_minloglevel = config->log_level_;
FLAGS_max_log_size = 100;
FLAGS_logbufsecs = 0;
- if (Util::ToLower(config->log_dir) == "stdout") {
+ if (Util::ToLower(config->log_dir_) == "stdout") {
for (int level = google::INFO; level <= google::FATAL; level++) {
google::SetLogDestination(level, "");
}
FLAGS_stderrthreshold = google::ERROR;
FLAGS_logtostdout = true;
} else {
- FLAGS_log_dir = config->log_dir + "/";
- if (config->log_retention_days != -1) {
- google::EnableLogCleaner(config->log_retention_days);
+ FLAGS_log_dir = config->log_dir_ + "/";
+ if (config->log_retention_days_ != -1) {
+ google::EnableLogCleaner(config->log_retention_days_);
}
}
}
@@ -331,8 +331,8 @@ int main(int argc, char *argv[]) {
// Tricky: We don't expect that different instances running on the same port,
// but the server use REUSE_PORT to support the multi listeners. So we connect
// the listen port to check if the port has already listened or not.
- if (!config.binds.empty()) {
- uint32_t ports[] = {config.port, config.tls_port, 0};
+ if (!config.binds_.empty()) {
+ uint32_t ports[] = {config.port_, config.tls_port_, 0};
for (uint32_t *port = ports; *port; ++port) {
if (Util::IsPortInUse(*port)) {
LOG(ERROR) << "Could not create server TCP since the specified port[" << *port << "] is already in use";
@@ -340,18 +340,18 @@ int main(int argc, char *argv[]) {
}
}
}
- bool is_supervised = isSupervisedMode(config.supervised_mode);
- if (config.daemonize && !is_supervised) daemonize();
- s = createPidFile(config.pidfile);
+ bool is_supervised = isSupervisedMode(config.supervised_mode_);
+ if (config.daemonize_ && !is_supervised) daemonize();
+ s = createPidFile(config.pidfile_);
if (!s.IsOK()) {
LOG(ERROR) << "Failed to create pidfile: " << s.Msg();
return 1;
}
- auto pidfile_exit = MakeScopeExit([&config] { removePidFile(config.pidfile); });
+ auto pidfile_exit = MakeScopeExit([&config] { removePidFile(config.pidfile_); });
#ifdef ENABLE_OPENSSL
// initialize OpenSSL
- if (config.tls_port) {
+ if (config.tls_port_) {
InitSSL();
}
#endif
diff --git a/src/server/redis_connection.cc b/src/server/redis_connection.cc
index f79cd97c..6171195b 100644
--- a/src/server/redis_connection.cc
+++ b/src/server/redis_connection.cc
@@ -255,14 +255,14 @@ int Connection::PSubscriptionsCount() { return static_cast<int>(subscribe_patter
bool Connection::isProfilingEnabled(const std::string &cmd) {
auto config = svr_->GetConfig();
- if (config->profiling_sample_ratio == 0) return false;
+ if (config->profiling_sample_ratio_ == 0) return false;
- if (!config->profiling_sample_all_commands &&
- config->profiling_sample_commands.find(cmd) == config->profiling_sample_commands.end()) {
+ if (!config->profiling_sample_all_commands_ &&
+ config->profiling_sample_commands_.find(cmd) == config->profiling_sample_commands_.end()) {
return false;
}
- if (config->profiling_sample_ratio == 100 || std::rand() % 100 <= config->profiling_sample_ratio) {
+ if (config->profiling_sample_ratio_ == 100 || std::rand() % 100 <= config->profiling_sample_ratio_) {
rocksdb::SetPerfLevel(rocksdb::PerfLevel::kEnableTimeExceptForMutex);
rocksdb::get_perf_context()->Reset();
rocksdb::get_iostats_context()->Reset();
@@ -273,7 +273,7 @@ bool Connection::isProfilingEnabled(const std::string &cmd) {
}
void Connection::recordProfilingSampleIfNeed(const std::string &cmd, uint64_t duration) {
- int threshold = svr_->GetConfig()->profiling_sample_record_threshold_ms;
+ int threshold = svr_->GetConfig()->profiling_sample_record_threshold_ms_;
if (threshold > 0 && static_cast<int>(duration / 1000) < threshold) {
rocksdb::SetPerfLevel(rocksdb::PerfLevel::kDisable);
return;
@@ -285,16 +285,16 @@ void Connection::recordProfilingSampleIfNeed(const std::string &cmd, uint64_t du
if (perf_context.empty()) return; // request without db operation
auto entry = std::unique_ptr<PerfEntry>();
- entry->cmd_name = cmd;
- entry->duration = duration;
- entry->iostats_context = std::move(iostats_context);
- entry->perf_context = std::move(perf_context);
+ entry->cmd_name_ = cmd;
+ entry->duration_ = duration;
+ entry->iostats_context_ = std::move(iostats_context);
+ entry->perf_context_ = std::move(perf_context);
svr_->GetPerfLog()->PushEntry(std::move(entry));
}
void Connection::ExecuteCommands(std::deque<CommandTokens> *to_process_cmds) {
Config *config = svr_->GetConfig();
- std::string reply, password = config->requirepass;
+ std::string reply, password = config->requirepass_;
while (!to_process_cmds->empty()) {
auto cmd_tokens = to_process_cmds->front();
@@ -323,7 +323,7 @@ void Connection::ExecuteCommands(std::deque<CommandTokens> *to_process_cmds) {
}
const auto attributes = current_cmd_->GetAttributes();
- auto cmd_name = attributes->name;
+ auto cmd_name = attributes->name_;
std::shared_lock<std::shared_mutex> concurrency; // Allow concurrency
std::unique_lock<std::shared_mutex> exclusivity; // Need exclusivity
@@ -331,11 +331,11 @@ void Connection::ExecuteCommands(std::deque<CommandTokens> *to_process_cmds) {
// that can guarantee other threads can't come into critical zone, such as DEBUG,
// CLUSTER subcommand, CONFIG SET, MULTI, LUA (in the immediate future).
// Otherwise, we just use 'ConcurrencyGuard' to allow all workers to execute commands at the same time.
- if (IsFlagEnabled(Connection::kMultiExec) && attributes->name != "exec") {
+ if (IsFlagEnabled(Connection::kMultiExec) && attributes->name_ != "exec") {
// No lock guard, because 'exec' command has acquired 'WorkExclusivityGuard'
} else if (attributes->is_exclusive() ||
(cmd_name == "config" && cmd_tokens.size() == 2 && !strcasecmp(cmd_tokens[1].c_str(), "set")) ||
- (config->cluster_enabled && (cmd_name == "clusterx" || cmd_name == "cluster") &&
+ (config->cluster_enabled_ && (cmd_name == "clusterx" || cmd_name == "cluster") &&
cmd_tokens.size() >= 2 && Cluster::SubCommandIsExecExclusive(cmd_tokens[1]))) {
exclusivity = svr_->WorkExclusivityGuard();
@@ -346,7 +346,7 @@ void Connection::ExecuteCommands(std::deque<CommandTokens> *to_process_cmds) {
concurrency = svr_->WorkConcurrencyGuard();
}
- if (attributes->flags & kCmdROScript) {
+ if (attributes->flags_ & kCmdROScript) {
// if executing read only lua script commands, set current connection.
svr_->SetCurrentConnection(this);
}
@@ -357,7 +357,7 @@ void Connection::ExecuteCommands(std::deque<CommandTokens> *to_process_cmds) {
continue;
}
- int arity = attributes->arity;
+ int arity = attributes->arity_;
int tokens = static_cast<int>(cmd_tokens.size());
if ((arity > 0 && tokens != arity) || (arity < 0 && tokens < -arity)) {
if (IsFlagEnabled(Connection::kMultiExec)) multi_error_ = true;
@@ -374,13 +374,13 @@ void Connection::ExecuteCommands(std::deque<CommandTokens> *to_process_cmds) {
}
if (IsFlagEnabled(Connection::kMultiExec) && attributes->is_no_multi()) {
- std::string no_multi_err = "Err Can't execute " + attributes->name + " in MULTI";
+ std::string no_multi_err = "Err Can't execute " + attributes->name_ + " in MULTI";
Reply(Redis::Error(no_multi_err));
multi_error_ = true;
continue;
}
- if (config->cluster_enabled) {
+ if (config->cluster_enabled_) {
s = svr_->cluster_->CanExecByMySelf(attributes, cmd_tokens, this);
if (!s.IsOK()) {
if (IsFlagEnabled(Connection::kMultiExec)) multi_error_ = true;
@@ -396,12 +396,12 @@ void Connection::ExecuteCommands(std::deque<CommandTokens> *to_process_cmds) {
continue;
}
- if (config->slave_readonly && svr_->IsSlave() && attributes->is_write()) {
+ if (config->slave_readonly_ && svr_->IsSlave() && attributes->is_write()) {
Reply(Redis::Error("READONLY You can't write against a read only slave."));
continue;
}
- if (!config->slave_serve_stale_data && svr_->IsSlave() && cmd_name != "info" && cmd_name != "slaveof" &&
+ if (!config->slave_serve_stale_data_ && svr_->IsSlave() && cmd_name != "info" && cmd_name != "slaveof" &&
svr_->GetReplicationState() != kReplConnected) {
Reply(
Redis::Error("MASTERDOWN Link with MASTER is down "
diff --git a/src/server/redis_reply.h b/src/server/redis_reply.h
index acbb78c7..7926b1b5 100644
--- a/src/server/redis_reply.h
+++ b/src/server/redis_reply.h
@@ -24,6 +24,7 @@
#include <rocksdb/status.h>
#include <string>
+#include <type_traits>
#include <vector>
#define CRLF "\r\n" // NOLINT
@@ -34,8 +35,8 @@ void Reply(evbuffer *output, const std::string &data);
std::string SimpleString(const std::string &data);
std::string Error(const std::string &err);
-template <typename IntegerType>
-std::string Integer(IntegerType data) {
+template <typename T, std::enable_if_t<std::is_integral_v<T>, int> = 0>
+std::string Integer(T data) {
return ":" + std::to_string(data) + CRLF;
}
diff --git a/src/server/redis_request.cc b/src/server/redis_request.cc
index 44766abf..2ceed64f 100644
--- a/src/server/redis_request.cc
+++ b/src/server/redis_request.cc
@@ -50,13 +50,13 @@ Status Request::Tokenize(evbuffer *input) {
// We don't use the `EVBUFFER_EOL_CRLF_STRICT` here since only LF is allowed in INLINE protocol.
// So we need to search LF EOL and figure out current line has CR or not.
UniqueEvbufReadln line(input, EVBUFFER_EOL_LF);
- if (line && line.length > 0 && line[line.length - 1] == '\r') {
+ if (line && line.length_ > 0 && line[line.length_ - 1] == '\r') {
// remove `\r` if exists
- --line.length;
+ --line.length_;
is_only_lf = false;
}
- if (!line || line.length <= 0) {
+ if (!line || line.length_ <= 0) {
if (pipeline_size > 128) {
LOG(INFO) << "Large pipeline detected: " << pipeline_size;
}
@@ -67,9 +67,9 @@ Status Request::Tokenize(evbuffer *input) {
}
pipeline_size++;
- svr_->stats_.IncrInbondBytes(line.length);
+ svr_->stats_.IncrInbondBytes(line.length_);
if (line[0] == '*') {
- auto parse_result = ParseInt<int64_t>(std::string(line.get() + 1, line.length - 1), 10);
+ auto parse_result = ParseInt<int64_t>(std::string(line.get() + 1, line.length_ - 1), 10);
if (!parse_result) {
return {Status::NotOK, "Protocol error: invalid multibulk length"};
}
@@ -86,11 +86,11 @@ Status Request::Tokenize(evbuffer *input) {
state_ = BulkLen;
} else {
- if (line.length > PROTO_INLINE_MAX_SIZE) {
+ if (line.length_ > PROTO_INLINE_MAX_SIZE) {
return {Status::NotOK, "Protocol error: invalid bulk length"};
}
- tokens_ = Util::Split(std::string(line.get(), line.length), " \t");
+ tokens_ = Util::Split(std::string(line.get(), line.length_), " \t");
commands_.emplace_back(std::move(tokens_));
state_ = ArrayLen;
}
@@ -98,14 +98,14 @@ Status Request::Tokenize(evbuffer *input) {
}
case BulkLen: {
UniqueEvbufReadln line(input, EVBUFFER_EOL_CRLF_STRICT);
- if (!line || line.length <= 0) return Status::OK();
+ if (!line || line.length_ <= 0) return Status::OK();
- svr_->stats_.IncrInbondBytes(line.length);
+ svr_->stats_.IncrInbondBytes(line.length_);
if (line[0] != '$') {
return {Status::NotOK, "Protocol error: expected '$'"};
}
- auto parse_result = ParseInt<uint64_t>(std::string(line.get() + 1, line.length - 1), 10);
+ auto parse_result = ParseInt<uint64_t>(std::string(line.get() + 1, line.length_ - 1), 10);
if (!parse_result) {
return {Status::NotOK, "Protocol error: invalid bulk length"};
}
diff --git a/src/server/server.cc b/src/server/server.cc
index fb2b59e7..93ca387a 100644
--- a/src/server/server.cc
+++ b/src/server/server.cc
@@ -60,13 +60,13 @@ Server::Server(Engine::Storage *storage, Config *config)
// init commands stats here to prevent concurrent insert, and cause core
auto commands = Redis::GetOriginalCommands();
for (const auto &iter : *commands) {
- stats_.commands_stats[iter.first].calls = 0;
- stats_.commands_stats[iter.first].latency = 0;
+ stats_.commands_stats_[iter.first].calls_ = 0;
+ stats_.commands_stats_[iter.first].latency_ = 0;
}
#ifdef ENABLE_OPENSSL
// init ssl context
- if (config->tls_port) {
+ if (config->tls_port_) {
ssl_ctx_ = CreateSSLContext(config);
if (!ssl_ctx_) {
exit(1);
@@ -75,26 +75,26 @@ Server::Server(Engine::Storage *storage, Config *config)
#endif
// Init cluster
- cluster_ = std::make_unique<Cluster>(this, config_->binds, config_->port);
+ cluster_ = std::make_unique<Cluster>(this, config_->binds_, config_->port_);
- for (int i = 0; i < config->workers; i++) {
+ for (int i = 0; i < config->workers_; i++) {
auto worker = std::make_unique<Worker>(this, config);
// multiple workers can't listen to the same unix socket, so
// listen unix socket only from a single worker - the first one
- if (!config->unixsocket.empty() && i == 0) {
- Status s = worker->ListenUnixSocket(config->unixsocket, config->unixsocketperm, config->backlog);
+ if (!config->unixsocket_.empty() && i == 0) {
+ Status s = worker->ListenUnixSocket(config->unixsocket_, config->unixsocketperm_, config->backlog_);
if (!s.IsOK()) {
- LOG(ERROR) << "[server] Failed to listen on unix socket: " << config->unixsocket << ". Error: " << s.Msg();
+ LOG(ERROR) << "[server] Failed to listen on unix socket: " << config->unixsocket_ << ". Error: " << s.Msg();
exit(1);
}
- LOG(INFO) << "[server] Listening on unix socket: " << config->unixsocket;
+ LOG(INFO) << "[server] Listening on unix socket: " << config->unixsocket_;
}
worker_threads_.emplace_back(std::make_unique<WorkerThread>(std::move(worker)));
}
AdjustOpenFilesLimit();
- slow_log_.SetMaxEntries(config->slowlog_max_len);
- perf_log_.SetMaxEntries(config->profiling_sample_record_max_len);
+ slow_log_.SetMaxEntries(config->slowlog_max_len_);
+ perf_log_.SetMaxEntries(config->profiling_sample_record_max_len_);
lua_ = Lua::CreateState();
}
@@ -136,8 +136,8 @@ Server::~Server() {
// - feed-replica-data-info: generate checkpoint and send files list when full sync
// - feed-replica-file: send SST files when slaves ask for full sync
Status Server::Start() {
- if (!config_->master_host.empty()) {
- Status s = AddMaster(config_->master_host, static_cast<uint32_t>(config_->master_port), false);
+ if (!config_->master_host_.empty()) {
+ Status s = AddMaster(config_->master_host_, static_cast<uint32_t>(config_->master_port_), false);
if (!s.IsOK()) return s;
} else {
// Generate new replication id if not a replica
@@ -147,14 +147,14 @@ Status Server::Start() {
}
}
- if (config_->cluster_enabled && config_->persist_cluster_nodes_enabled) {
+ if (config_->cluster_enabled_ && config_->persist_cluster_nodes_enabled_) {
auto s = cluster_->LoadClusterNodes(config_->NodesFilePath());
if (!s.IsOK()) {
return s.Prefixed("failed to load cluster nodes info");
}
// Create objects used for slot migration
slot_migrator_ =
- std::make_unique<SlotMigrator>(this, config_->migrate_speed, config_->pipeline_size, config_->sequence_gap);
+ std::make_unique<SlotMigrator>(this, config_->migrate_speed_, config_->pipeline_size_, config_->sequence_gap_);
s = slot_migrator_->CreateMigrationThread();
if (!s.IsOK()) {
return s.Prefixed("failed to create migration thread");
@@ -187,12 +187,12 @@ Status Server::Start() {
if (storage_->IsClosing()) continue;
if (!is_loading_ && ++counter % 600 == 0 // check every minute
- && config_->compaction_checker_range.Enabled()) {
+ && config_->compaction_checker_range_.Enabled()) {
auto now = static_cast<time_t>(Util::GetTimeStamp());
std::tm local_time{};
localtime_r(&now, &local_time);
- if (local_time.tm_hour >= config_->compaction_checker_range.Start &&
- local_time.tm_hour <= config_->compaction_checker_range.Stop) {
+ if (local_time.tm_hour >= config_->compaction_checker_range_.start_ &&
+ local_time.tm_hour <= config_->compaction_checker_range_.stop_) {
std::vector<std::string> cf_names = {Engine::kMetadataColumnFamilyName, Engine::kSubkeyColumnFamilyName,
Engine::kZSetScoreColumnFamilyName, Engine::kStreamColumnFamilyName};
for (const auto &cf_name : cf_names) {
@@ -262,7 +262,7 @@ Status Server::AddMaster(const std::string &host, uint32_t port, bool force_reco
// For master using old version, it uses replication thread to implement
// replication, and uses 'listen-port + 1' as thread listening port.
uint32_t master_listen_port = port;
- if (GetConfig()->master_use_repl_port) master_listen_port += 1;
+ if (GetConfig()->master_use_repl_port_) master_listen_port += 1;
replication_thread_ = std::make_unique<ReplicationThread>(host, master_listen_port, this);
auto s = replication_thread_->Start([this]() { PrepareRestoreDB(); },
@@ -379,7 +379,7 @@ int Server::PublishMessage(const std::string &channel, const std::string &msg) {
channel_reply.append(Redis::BulkString(channel));
channel_reply.append(Redis::BulkString(msg));
for (const auto &conn_ctx : to_publish_conn_ctxs) {
- auto s = conn_ctx.owner->Reply(conn_ctx.fd, channel_reply);
+ auto s = conn_ctx.owner_->Reply(conn_ctx.fd_, channel_reply);
if (s.IsOK()) {
cnt++;
}
@@ -393,7 +393,7 @@ int Server::PublishMessage(const std::string &channel, const std::string &msg) {
pattern_reply.append(Redis::BulkString(patterns[index++]));
pattern_reply.append(Redis::BulkString(channel));
pattern_reply.append(Redis::BulkString(msg));
- auto s = conn_ctx.owner->Reply(conn_ctx.fd, pattern_reply);
+ auto s = conn_ctx.owner_->Reply(conn_ctx.fd_, pattern_reply);
if (s.IsOK()) {
cnt++;
}
@@ -424,7 +424,7 @@ void Server::UnsubscribeChannel(const std::string &channel, Redis::Connection *c
}
for (const auto &conn_ctx : iter->second) {
- if (conn->GetFD() == conn_ctx->fd && conn->Owner() == conn_ctx->owner) {
+ if (conn->GetFD() == conn_ctx->fd_ && conn->Owner() == conn_ctx->owner_) {
delConnContext(conn_ctx);
iter->second.remove(conn_ctx);
if (iter->second.empty()) {
@@ -480,7 +480,7 @@ void Server::PUnsubscribeChannel(const std::string &pattern, Redis::Connection *
}
for (const auto &conn_ctx : iter->second) {
- if (conn->GetFD() == conn_ctx->fd && conn->Owner() == conn_ctx->owner) {
+ if (conn->GetFD() == conn_ctx->fd_ && conn->Owner() == conn_ctx->owner_) {
delConnContext(conn_ctx);
iter->second.remove(conn_ctx);
if (iter->second.empty()) {
@@ -515,7 +515,7 @@ void Server::UnblockOnKey(const std::string &key, Redis::Connection *conn) {
}
for (const auto &conn_ctx : iter->second) {
- if (conn->GetFD() == conn_ctx->fd && conn->Owner() == conn_ctx->owner) {
+ if (conn->GetFD() == conn_ctx->fd_ && conn->Owner() == conn_ctx->owner_) {
delConnContext(conn_ctx);
iter->second.remove(conn_ctx);
if (iter->second.empty()) {
@@ -559,7 +559,7 @@ void Server::UnblockOnStreams(const std::vector<std::string> &keys, Redis::Conne
for (auto it = iter->second.begin(); it != iter->second.end();) {
const auto &consumer = *it;
- if (conn->GetFD() == consumer->fd && conn->Owner() == consumer->owner) {
+ if (conn->GetFD() == consumer->fd_ && conn->Owner() == consumer->owner_) {
iter->second.erase(it);
if (iter->second.empty()) {
blocked_stream_consumers_.erase(iter);
@@ -581,9 +581,9 @@ void Server::WakeupBlockingConns(const std::string &key, size_t n_conns) {
while (n_conns-- && !iter->second.empty()) {
auto conn_ctx = iter->second.front();
- auto s = conn_ctx->owner->EnableWriteEvent(conn_ctx->fd);
+ auto s = conn_ctx->owner_->EnableWriteEvent(conn_ctx->fd_);
if (!s.IsOK()) {
- LOG(ERROR) << "[server] Failed to enable write event on blocked client " << conn_ctx->fd << ": " << s.Msg();
+ LOG(ERROR) << "[server] Failed to enable write event on blocked client " << conn_ctx->fd_ << ": " << s.Msg();
}
delConnContext(conn_ctx);
iter->second.pop_front();
@@ -600,10 +600,10 @@ void Server::OnEntryAddedToStream(const std::string &ns, const std::string &key,
for (auto it = iter->second.begin(); it != iter->second.end();) {
auto consumer = *it;
- if (consumer->ns == ns && entry_id > consumer->last_consumed_id) {
- auto s = consumer->owner->EnableWriteEvent(consumer->fd);
+ if (consumer->ns_ == ns && entry_id > consumer->last_consumed_id_) {
+ auto s = consumer->owner_->EnableWriteEvent(consumer->fd_);
if (!s.IsOK()) {
- LOG(ERROR) << "[server] Failed to enable write event on blocked stream consumer " << consumer->fd << ": "
+ LOG(ERROR) << "[server] Failed to enable write event on blocked stream consumer " << consumer->fd_ << ": "
<< s.Msg();
}
it = iter->second.erase(it);
@@ -653,9 +653,9 @@ uint64_t Server::GetClientID() { return client_id_.fetch_add(1, std::memory_orde
void Server::recordInstantaneousMetrics() {
auto rocksdb_stats = storage_->GetDB()->GetDBOptions().statistics;
- stats_.TrackInstantaneousMetric(STATS_METRIC_COMMAND, stats_.total_calls);
- stats_.TrackInstantaneousMetric(STATS_METRIC_NET_INPUT, stats_.in_bytes);
- stats_.TrackInstantaneousMetric(STATS_METRIC_NET_OUTPUT, stats_.out_bytes);
+ stats_.TrackInstantaneousMetric(STATS_METRIC_COMMAND, stats_.total_calls_);
+ stats_.TrackInstantaneousMetric(STATS_METRIC_NET_INPUT, stats_.in_bytes_);
+ stats_.TrackInstantaneousMetric(STATS_METRIC_NET_OUTPUT, stats_.out_bytes_);
stats_.TrackInstantaneousMetric(STATS_METRIC_ROCKSDB_PUT,
rocksdb_stats->getTickerCount(rocksdb::Tickers::NUMBER_KEYS_WRITTEN));
stats_.TrackInstantaneousMetric(STATS_METRIC_ROCKSDB_GET,
@@ -696,23 +696,23 @@ void Server::cron() {
std::tm now{};
localtime_r(&t, &now);
// disable compaction cron when the compaction checker was enabled
- if (!config_->compaction_checker_range.Enabled() && config_->compact_cron.IsEnabled() &&
- config_->compact_cron.IsTimeMatch(&now)) {
+ if (!config_->compaction_checker_range_.Enabled() && config_->compact_cron_.IsEnabled() &&
+ config_->compact_cron_.IsTimeMatch(&now)) {
Status s = AsyncCompactDB();
LOG(INFO) << "[server] Schedule to compact the db, result: " << s.Msg();
}
- if (config_->bgsave_cron.IsEnabled() && config_->bgsave_cron.IsTimeMatch(&now)) {
+ if (config_->bgsave_cron_.IsEnabled() && config_->bgsave_cron_.IsTimeMatch(&now)) {
Status s = AsyncBgSaveDB();
LOG(INFO) << "[server] Schedule to bgsave the db, result: " << s.Msg();
}
}
// check every 10s
if (counter != 0 && counter % 100 == 0) {
- Status s = AsyncPurgeOldBackups(config_->max_backup_to_keep, config_->max_backup_keep_hours);
+ Status s = AsyncPurgeOldBackups(config_->max_backup_to_keep_, config_->max_backup_keep_hours_);
// Purge backup if needed, it will cost much disk space if we keep backup and full sync
// checkpoints at the same time
- if (config_->purge_backup_on_fullsync && (storage_->ExistCheckpoint() || storage_->ExistSyncCheckpoint())) {
+ if (config_->purge_backup_on_fullsync_ && (storage_->ExistCheckpoint() || storage_->ExistSyncCheckpoint())) {
s = AsyncPurgeOldBackups(0, 0);
}
}
@@ -726,7 +726,7 @@ void Server::cron() {
// TODO(shooterit): support to config the alive time of checkpoint
auto now = static_cast<time_t>(Util::GetTimeStamp());
if ((GetFetchFileThreadNum() == 0 && now - access_time > 30) || (now - create_time > 24 * 60 * 60)) {
- auto s = rocksdb::DestroyDB(config_->checkpoint_dir, rocksdb::Options());
+ auto s = rocksdb::DestroyDB(config_->checkpoint_dir_, rocksdb::Options());
if (!s.ok()) {
LOG(WARNING) << "[server] Fail to clean checkpoint, error: " << s.ToString();
} else {
@@ -854,7 +854,7 @@ void Server::GetServerInfo(std::string *info) {
#endif
string_stream << "arch_bits:" << sizeof(void *) * 8 << "\r\n";
string_stream << "process_id:" << getpid() << "\r\n";
- string_stream << "tcp_port:" << config_->port << "\r\n";
+ string_stream << "tcp_port:" << config_->port_ << "\r\n";
int64_t now = Util::GetTimeStamp();
string_stream << "uptime_in_seconds:" << now - start_time_ << "\r\n";
string_stream << "uptime_in_days:" << (now - start_time_) / 86400 << "\r\n";
@@ -864,7 +864,7 @@ void Server::GetServerInfo(std::string *info) {
void Server::GetClientsInfo(std::string *info) {
std::ostringstream string_stream;
string_stream << "# Clients\r\n";
- string_stream << "maxclients:" << config_->maxclients << "\r\n";
+ string_stream << "maxclients:" << config_->maxclients_ << "\r\n";
string_stream << "connected_clients:" << connected_clients_ << "\r\n";
string_stream << "monitor_clients:" << monitor_clients_ << "\r\n";
string_stream << "blocked_clients:" << blocked_clients_ << "\r\n";
@@ -901,7 +901,7 @@ void Server::GetReplicationInfo(std::string *info) {
string_stream << "master_sync_in_progress:" << (state == kReplFetchMeta || state == kReplFetchSST) << "\r\n";
string_stream << "master_last_io_seconds_ago:" << now - replication_thread_->LastIOTime() << "\r\n";
string_stream << "slave_repl_offset:" << storage_->LatestSeqNumber() << "\r\n";
- string_stream << "slave_priority:" << config_->slave_priority << "\r\n";
+ string_stream << "slave_priority:" << config_->slave_priority_ << "\r\n";
}
int idx = 0;
@@ -993,17 +993,17 @@ void Server::GetStatsInfo(std::string *info) {
std::ostringstream string_stream;
string_stream << "# Stats\r\n";
string_stream << "total_connections_received:" << total_clients_ << "\r\n";
- string_stream << "total_commands_processed:" << stats_.total_calls << "\r\n";
+ string_stream << "total_commands_processed:" << stats_.total_calls_ << "\r\n";
string_stream << "instantaneous_ops_per_sec:" << stats_.GetInstantaneousMetric(STATS_METRIC_COMMAND) << "\r\n";
- string_stream << "total_net_input_bytes:" << stats_.in_bytes << "\r\n";
- string_stream << "total_net_output_bytes:" << stats_.out_bytes << "\r\n";
+ string_stream << "total_net_input_bytes:" << stats_.in_bytes_ << "\r\n";
+ string_stream << "total_net_output_bytes:" << stats_.out_bytes_ << "\r\n";
string_stream << "instantaneous_input_kbps:"
<< static_cast<float>(stats_.GetInstantaneousMetric(STATS_METRIC_NET_INPUT) / 1024) << "\r\n";
string_stream << "instantaneous_output_kbps:"
<< static_cast<float>(stats_.GetInstantaneousMetric(STATS_METRIC_NET_OUTPUT) / 1024) << "\r\n";
- string_stream << "sync_full:" << stats_.fullsync_counter << "\r\n";
- string_stream << "sync_partial_ok:" << stats_.psync_ok_counter << "\r\n";
- string_stream << "sync_partial_err:" << stats_.psync_err_counter << "\r\n";
+ string_stream << "sync_full:" << stats_.fullsync_counter_ << "\r\n";
+ string_stream << "sync_partial_ok:" << stats_.psync_ok_counter_ << "\r\n";
+ string_stream << "sync_partial_err:" << stats_.psync_err_counter_ << "\r\n";
{
std::lock_guard<std::mutex> lg(pubsub_channels_mu_);
string_stream << "pubsub_channels:" << pubsub_channels_.size() << "\r\n";
@@ -1017,11 +1017,11 @@ void Server::GetCommandsStatsInfo(std::string *info) {
std::ostringstream string_stream;
string_stream << "# Commandstats\r\n";
- for (const auto &cmd_stat : stats_.commands_stats) {
- auto calls = cmd_stat.second.calls.load();
+ for (const auto &cmd_stat : stats_.commands_stats_) {
+ auto calls = cmd_stat.second.calls_.load();
if (calls == 0) continue;
- auto latency = cmd_stat.second.latency.load();
+ auto latency = cmd_stat.second.latency_.load();
string_stream << "cmdstat_" << cmd_stat.first << ":calls=" << calls << ",usec=" << latency
<< ",usec_per_call=" << ((calls == 0) ? 0 : static_cast<float>(latency / calls)) << "\r\n";
}
@@ -1033,7 +1033,7 @@ void Server::GetClusterInfo(std::string *info) {
std::ostringstream string_stream;
string_stream << "# Cluster\r\n";
- string_stream << "cluster_enabled:" << config_->cluster_enabled << "\r\n";
+ string_stream << "cluster_enabled:" << config_->cluster_enabled_ << "\r\n";
*info = string_stream.str();
}
@@ -1138,18 +1138,18 @@ void Server::GetInfo(const std::string &ns, const std::string §ion, std::str
if (section_cnt++) string_stream << "\r\n";
string_stream << "# Keyspace\r\n";
string_stream << "# Last scan db time: " << std::put_time(&last_scan_tm, "%a %b %e %H:%M:%S %Y") << "\r\n";
- string_stream << "db0:keys=" << stats.n_key << ",expires=" << stats.n_expires << ",avg_ttl=" << stats.avg_ttl
- << ",expired=" << stats.n_expired << "\r\n";
+ string_stream << "db0:keys=" << stats.n_key_ << ",expires=" << stats.n_expires_ << ",avg_ttl=" << stats.avg_ttl_
+ << ",expired=" << stats.n_expired_ << "\r\n";
string_stream << "sequence:" << storage_->GetDB()->GetLatestSequenceNumber() << "\r\n";
string_stream << "used_db_size:" << storage_->GetTotalSize(ns) << "\r\n";
- string_stream << "max_db_size:" << config_->max_db_size * GiB << "\r\n";
- double used_percent = config_->max_db_size ? static_cast<double>(storage_->GetTotalSize() * 100) /
- static_cast<double>(config_->max_db_size * GiB)
- : 0;
+ string_stream << "max_db_size:" << config_->max_db_size_ * GiB << "\r\n";
+ double used_percent = config_->max_db_size_ ? static_cast<double>(storage_->GetTotalSize() * 100) /
+ static_cast<double>(config_->max_db_size_ * GiB)
+ : 0;
string_stream << "used_percent: " << used_percent << "%\r\n";
struct statvfs stat;
- if (statvfs(config_->db_dir.c_str(), &stat) == 0) {
+ if (statvfs(config_->db_dir_.c_str(), &stat) == 0) {
auto disk_capacity = stat.f_blocks * stat.f_frsize;
auto used_disk_size = (stat.f_blocks - stat.f_bavail) * stat.f_frsize;
string_stream << "disk_capacity:" << disk_capacity << "\r\n";
@@ -1226,7 +1226,7 @@ void Server::PrepareRestoreDB() {
}
void Server::WaitNoMigrateProcessing() {
- if (config_->cluster_enabled) {
+ if (config_->cluster_enabled_) {
LOG(INFO) << "[server] Waiting until no migration task is running...";
slot_migrator_->SetStopMigrationFlag(true);
while (slot_migrator_->GetCurrentSlotMigrationStage() != SlotMigrationStage::kNone) {
@@ -1292,11 +1292,11 @@ Status Server::AsyncScanDBSize(const std::string &ns) {
db_scan_infos_[ns] = DBScanInfo{};
}
- if (db_scan_infos_[ns].is_scanning) {
+ if (db_scan_infos_[ns].is_scanning_) {
return {Status::NotOK, "scanning the db now"};
}
- db_scan_infos_[ns].is_scanning = true;
+ db_scan_infos_[ns].is_scanning_ = true;
return task_runner_.TryPublish([ns, this] {
Redis::Database db(storage_, ns);
@@ -1305,9 +1305,9 @@ Status Server::AsyncScanDBSize(const std::string &ns) {
std::lock_guard<std::mutex> lg(db_job_mu_);
- db_scan_infos_[ns].key_num_stats = stats;
- db_scan_infos_[ns].last_scan_time = Util::GetTimeStamp();
- db_scan_infos_[ns].is_scanning = false;
+ db_scan_infos_[ns].key_num_stats_ = stats;
+ db_scan_infos_[ns].last_scan_time_ = Util::GetTimeStamp();
+ db_scan_infos_[ns].is_scanning_ = false;
});
}
@@ -1346,13 +1346,13 @@ Status Server::autoResizeBlockAndSST() {
block_size = 2 * KiB;
}
- if (target_file_size_base == config_->RocksDB.target_file_size_base &&
- target_file_size_base == config_->RocksDB.write_buffer_size && block_size == config_->RocksDB.block_size) {
+ if (target_file_size_base == config_->rocks_db_.target_file_size_base_ &&
+ target_file_size_base == config_->rocks_db_.write_buffer_size_ && block_size == config_->rocks_db_.block_size_) {
return Status::OK();
}
- if (target_file_size_base != config_->RocksDB.target_file_size_base) {
- auto old_target_file_size_base = config_->RocksDB.target_file_size_base;
+ if (target_file_size_base != config_->rocks_db_.target_file_size_base_) {
+ auto old_target_file_size_base = config_->rocks_db_.target_file_size_base_;
auto s = config_->Set(this, "rocksdb.target_file_size_base", std::to_string(target_file_size_base));
LOG(INFO) << "[server] Resize rocksdb.target_file_size_base from " << old_target_file_size_base << " to "
<< target_file_size_base << ", average_kv_size: " << average_kv_size << ", total_size: " << total_size
@@ -1362,8 +1362,8 @@ Status Server::autoResizeBlockAndSST() {
}
}
- if (target_file_size_base != config_->RocksDB.write_buffer_size) {
- auto old_write_buffer_size = config_->RocksDB.write_buffer_size;
+ if (target_file_size_base != config_->rocks_db_.write_buffer_size_) {
+ auto old_write_buffer_size = config_->rocks_db_.write_buffer_size_;
auto s = config_->Set(this, "rocksdb.write_buffer_size", std::to_string(target_file_size_base));
LOG(INFO) << "[server] Resize rocksdb.write_buffer_size from " << old_write_buffer_size << " to "
<< target_file_size_base << ", average_kv_size: " << average_kv_size << ", total_size: " << total_size
@@ -1373,16 +1373,16 @@ Status Server::autoResizeBlockAndSST() {
}
}
- if (block_size != config_->RocksDB.block_size) {
+ if (block_size != config_->rocks_db_.block_size_) {
auto s = storage_->SetOptionForAllColumnFamilies("table_factory.block_size", std::to_string(block_size));
- LOG(INFO) << "[server] Resize rocksdb.block_size from " << config_->RocksDB.block_size << " to " << block_size
+ LOG(INFO) << "[server] Resize rocksdb.block_size from " << config_->rocks_db_.block_size_ << " to " << block_size
<< ", average_kv_size: " << average_kv_size << ", total_size: " << total_size
<< ", total_keys: " << total_keys << ", result: " << s.Msg();
if (!s.IsOK()) {
return s;
}
- config_->RocksDB.block_size = block_size;
+ config_->rocks_db_.block_size_ = block_size;
}
auto s = config_->Rewrite();
@@ -1395,39 +1395,39 @@ void Server::GetLatestKeyNumStats(const std::string &ns, KeyNumStats *stats) {
auto iter = db_scan_infos_.find(ns);
if (iter != db_scan_infos_.end()) {
std::lock_guard<std::mutex> lg(db_job_mu_);
- *stats = iter->second.key_num_stats;
+ *stats = iter->second.key_num_stats_;
}
}
time_t Server::GetLastScanTime(const std::string &ns) {
auto iter = db_scan_infos_.find(ns);
if (iter != db_scan_infos_.end()) {
- return iter->second.last_scan_time;
+ return iter->second.last_scan_time_;
}
return 0;
}
void Server::SlowlogPushEntryIfNeeded(const std::vector<std::string> *args, uint64_t duration) {
- int64_t threshold = config_->slowlog_log_slower_than;
+ int64_t threshold = config_->slowlog_log_slower_than_;
if (threshold < 0 || static_cast<int64_t>(duration) < threshold) return;
auto entry = std::make_unique<SlowEntry>();
size_t argc = args->size() > kSlowLogMaxArgc ? kSlowLogMaxArgc : args->size();
for (size_t i = 0; i < argc; i++) {
if (argc != args->size() && i == argc - 1) {
- entry->args.emplace_back(fmt::format("... ({} more arguments)", args->size() - argc + 1));
+ entry->args_.emplace_back(fmt::format("... ({} more arguments)", args->size() - argc + 1));
break;
}
if ((*args)[i].length() <= kSlowLogMaxString) {
- entry->args.emplace_back((*args)[i]);
+ entry->args_.emplace_back((*args)[i]);
} else {
- entry->args.emplace_back(fmt::format("{}... ({} more bytes)", (*args)[i].substr(0, kSlowLogMaxString),
- (*args)[i].length() - kSlowLogMaxString));
+ entry->args_.emplace_back(fmt::format("{}... ({} more bytes)", (*args)[i].substr(0, kSlowLogMaxString),
+ (*args)[i].length() - kSlowLogMaxString));
}
}
- entry->duration = duration;
+ entry->duration_ = duration;
slow_log_.PushEntry(std::move(entry));
}
@@ -1499,7 +1499,7 @@ Status Server::LookupAndCreateCommand(const std::string &cmd_name, std::unique_p
}
auto redis_cmd = cmd_iter->second;
- *cmd = redis_cmd->factory();
+ *cmd = redis_cmd->factory_();
(*cmd)->SetAttributes(redis_cmd);
return Status::OK();
@@ -1580,8 +1580,8 @@ Status Server::ExecPropagatedCommand(const std::vector<std::string> &tokens) {
// log files and so forth.
void Server::AdjustOpenFilesLimit() {
const int min_reserved_fds = 128;
- auto rocksdb_max_open_file = static_cast<rlim_t>(config_->RocksDB.max_open_files);
- auto max_clients = static_cast<rlim_t>(config_->maxclients);
+ auto rocksdb_max_open_file = static_cast<rlim_t>(config_->rocks_db_.max_open_files_);
+ auto max_clients = static_cast<rlim_t>(config_->maxclients_);
auto max_files = max_clients + rocksdb_max_open_file + min_reserved_fds;
struct rlimit limit;
@@ -1658,8 +1658,8 @@ Status ServerLogData::Decode(const rocksdb::Slice &blob) {
void Server::updateWatchedKeysFromRange(const std::vector<std::string> &args, const Redis::CommandKeyRange &range) {
std::shared_lock lock(watched_key_mutex_);
- for (size_t i = range.first_key; range.last_key > 0 ? i <= size_t(range.last_key) : i <= args.size() + range.last_key;
- i += range.key_step) {
+ for (size_t i = range.first_key_;
+ range.last_key_ > 0 ? i <= size_t(range.last_key_) : i <= args.size() + range.last_key_; i += range.key_step_) {
if (auto iter = watched_key_map_.find(args[i]); iter != watched_key_map_.end()) {
for (auto *conn : iter->second) {
conn->watched_keys_modified_ = true;
@@ -1680,12 +1680,12 @@ void Server::updateAllWatchedKeys() {
void Server::UpdateWatchedKeysFromArgs(const std::vector<std::string> &args, const Redis::CommandAttributes &attr) {
if (attr.is_write() && watched_key_size_ > 0) {
- if (attr.key_range.first_key > 0) {
- updateWatchedKeysFromRange(args, attr.key_range);
- } else if (attr.key_range.first_key < 0) {
- Redis::CommandKeyRange range = attr.key_range_gen(args);
+ if (attr.key_range_.first_key_ > 0) {
+ updateWatchedKeysFromRange(args, attr.key_range_);
+ } else if (attr.key_range_.first_key_ < 0) {
+ Redis::CommandKeyRange range = attr.key_range_gen_(args);
- if (range.first_key > 0) {
+ if (range.first_key_ > 0) {
updateWatchedKeysFromRange(args, range);
}
} else {
diff --git a/src/server/server.h b/src/server/server.h
index 395d5e50..32c32168 100644
--- a/src/server/server.h
+++ b/src/server/server.h
@@ -48,29 +48,29 @@
#include "worker.h"
struct DBScanInfo {
- time_t last_scan_time = 0;
- KeyNumStats key_num_stats;
- bool is_scanning = false;
+ time_t last_scan_time_ = 0;
+ KeyNumStats key_num_stats_;
+ bool is_scanning_ = false;
};
struct ConnContext {
- Worker *owner;
- int fd;
- ConnContext(Worker *w, int fd) : owner(w), fd(fd) {}
+ Worker *owner_;
+ int fd_;
+ ConnContext(Worker *w, int fd) : owner_(w), fd_(fd) {}
};
struct StreamConsumer {
- Worker *owner;
- int fd;
- std::string ns;
- Redis::StreamEntryID last_consumed_id;
+ Worker *owner_;
+ int fd_;
+ std::string ns_;
+ Redis::StreamEntryID last_consumed_id_;
StreamConsumer(Worker *w, int fd, std::string ns, Redis::StreamEntryID id)
- : owner(w), fd(fd), ns(std::move(ns)), last_consumed_id(id) {}
+ : owner_(w), fd_(fd), ns_(std::move(ns)), last_consumed_id_(id) {}
};
struct ChannelSubscribeNum {
- std::string channel;
- size_t subscribe_num;
+ std::string channel_;
+ size_t subscribe_num_;
};
enum SlowLog {
diff --git a/src/server/tls_util.cc b/src/server/tls_util.cc
index 1fa6efc8..c5fd4284 100644
--- a/src/server/tls_util.cc
+++ b/src/server/tls_util.cc
@@ -116,7 +116,7 @@ StatusOr<unsigned long> ParseSSLProtocols(const std::string &protocols) { // NO
}
UniqueSSLContext CreateSSLContext(const Config *config, const SSL_METHOD *method) {
- if (config->tls_cert_file.empty() || config->tls_key_file.empty()) {
+ if (config->tls_cert_file_.empty() || config->tls_key_file_.empty()) {
LOG(ERROR) << "Both tls-cert-file and tls-key-file must be specified while TLS is enabled";
return nullptr;
}
@@ -127,7 +127,7 @@ UniqueSSLContext CreateSSLContext(const Config *config, const SSL_METHOD *method
return nullptr;
}
- auto proto_status = ParseSSLProtocols(config->tls_protocols);
+ auto proto_status = ParseSSLProtocols(config->tls_protocols_);
if (!proto_status) {
LOG(ERROR) << proto_status.Msg();
return nullptr;
@@ -145,7 +145,7 @@ UniqueSSLContext CreateSSLContext(const Config *config, const SSL_METHOD *method
ctx_options |= SSL_OP_NO_CLIENT_RENEGOTIATION;
#endif
- if (config->tls_prefer_server_ciphers) {
+ if (config->tls_prefer_server_ciphers_) {
ctx_options |= SSL_OP_CIPHER_SERVER_PREFERENCE;
}
@@ -153,10 +153,10 @@ UniqueSSLContext CreateSSLContext(const Config *config, const SSL_METHOD *method
SSL_CTX_set_mode(ssl_ctx.get(), SSL_MODE_ENABLE_PARTIAL_WRITE | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
- if (config->tls_session_caching) {
+ if (config->tls_session_caching_) {
SSL_CTX_set_session_cache_mode(ssl_ctx.get(), SSL_SESS_CACHE_SERVER);
- SSL_CTX_set_timeout(ssl_ctx.get(), config->tls_session_cache_timeout);
- SSL_CTX_sess_set_cache_size(ssl_ctx.get(), config->tls_session_cache_size);
+ SSL_CTX_set_timeout(ssl_ctx.get(), config->tls_session_cache_timeout_);
+ SSL_CTX_sess_set_cache_size(ssl_ctx.get(), config->tls_session_cache_size_);
const char *session_id = "kvrocks";
SSL_CTX_set_session_id_context(ssl_ctx.get(), (const unsigned char *)session_id, strlen(session_id));
@@ -164,41 +164,41 @@ UniqueSSLContext CreateSSLContext(const Config *config, const SSL_METHOD *method
SSL_CTX_set_session_cache_mode(ssl_ctx.get(), SSL_SESS_CACHE_OFF);
}
- if (config->tls_auth_clients == TLS_AUTH_CLIENTS_NO) {
+ if (config->tls_auth_clients_ == TLS_AUTH_CLIENTS_NO) {
SSL_CTX_set_verify(ssl_ctx.get(), SSL_VERIFY_NONE, nullptr);
- } else if (config->tls_auth_clients == TLS_AUTH_CLIENTS_OPTIONAL) {
+ } else if (config->tls_auth_clients_ == TLS_AUTH_CLIENTS_OPTIONAL) {
SSL_CTX_set_verify(ssl_ctx.get(), SSL_VERIFY_PEER, nullptr);
} else {
SSL_CTX_set_verify(ssl_ctx.get(), SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, nullptr);
}
- auto ca_file = config->tls_ca_cert_file.empty() ? nullptr : config->tls_ca_cert_file.c_str();
- auto ca_dir = config->tls_ca_cert_dir.empty() ? nullptr : config->tls_ca_cert_dir.c_str();
+ auto ca_file = config->tls_ca_cert_file_.empty() ? nullptr : config->tls_ca_cert_file_.c_str();
+ auto ca_dir = config->tls_ca_cert_dir_.empty() ? nullptr : config->tls_ca_cert_dir_.c_str();
if (ca_file || ca_dir) {
if (SSL_CTX_load_verify_locations(ssl_ctx.get(), ca_file, ca_dir) != 1) {
LOG(ERROR) << "Failed to load CA certificates: " << SSLErrors{};
return nullptr;
}
- } else if (config->tls_auth_clients != TLS_AUTH_CLIENTS_NO) {
+ } else if (config->tls_auth_clients_ != TLS_AUTH_CLIENTS_NO) {
LOG(ERROR) << "Either tls-ca-cert-file or tls-ca-cert-dir must be specified while tls-auth-clients is enabled";
return nullptr;
}
- if (SSL_CTX_use_certificate_chain_file(ssl_ctx.get(), config->tls_cert_file.c_str()) != 1) {
+ if (SSL_CTX_use_certificate_chain_file(ssl_ctx.get(), config->tls_cert_file_.c_str()) != 1) {
LOG(ERROR) << "Failed to load SSL certificate file: " << SSLErrors{};
return nullptr;
}
- if (!config->tls_key_file_pass.empty()) {
+ if (!config->tls_key_file_pass_.empty()) {
SSL_CTX_set_default_passwd_cb_userdata(ssl_ctx.get(), static_cast<void *>(const_cast<Config *>(config)));
SSL_CTX_set_default_passwd_cb(ssl_ctx.get(), [](char *buf, int size, int, void *cfg) -> int {
- strncpy(buf, static_cast<const Config *>(cfg)->tls_key_file_pass.c_str(), size);
+ strncpy(buf, static_cast<const Config *>(cfg)->tls_key_file_pass_.c_str(), size);
buf[size - 1] = '\0';
return static_cast<int>(strlen(buf));
});
}
- if (SSL_CTX_use_PrivateKey_file(ssl_ctx.get(), config->tls_key_file.c_str(), SSL_FILETYPE_PEM) != 1) {
+ if (SSL_CTX_use_PrivateKey_file(ssl_ctx.get(), config->tls_key_file_.c_str(), SSL_FILETYPE_PEM) != 1) {
LOG(ERROR) << "Failed to load SSL private key file: " << SSLErrors{};
return nullptr;
}
@@ -208,13 +208,14 @@ UniqueSSLContext CreateSSLContext(const Config *config, const SSL_METHOD *method
return nullptr;
}
- if (!config->tls_ciphers.empty() && !SSL_CTX_set_cipher_list(ssl_ctx.get(), config->tls_ciphers.c_str())) {
+ if (!config->tls_ciphers_.empty() && !SSL_CTX_set_cipher_list(ssl_ctx.get(), config->tls_ciphers_.c_str())) {
LOG(ERROR) << "Failed to set SSL ciphers: " << SSLErrors{};
return nullptr;
}
#ifdef SSL_OP_NO_TLSv1_3
- if (!config->tls_ciphersuites.empty() && !SSL_CTX_set_ciphersuites(ssl_ctx.get(), config->tls_ciphersuites.c_str())) {
+ if (!config->tls_ciphersuites_.empty() &&
+ !SSL_CTX_set_ciphersuites(ssl_ctx.get(), config->tls_ciphersuites_.c_str())) {
LOG(ERROR) << "Failed to set SSL ciphersuites: " << SSLErrors{};
return nullptr;
}
diff --git a/src/server/worker.cc b/src/server/worker.cc
index 967f59d3..44f52fe2 100644
--- a/src/server/worker.cc
+++ b/src/server/worker.cc
@@ -58,12 +58,12 @@ Worker::Worker(Server *svr, Config *config) : svr_(svr), base_(event_base_new())
timeval tm = {10, 0};
evtimer_add(timer_, &tm);
- uint32_t ports[3] = {config->port, config->tls_port, 0};
- auto binds = config->binds;
+ uint32_t ports[3] = {config->port_, config->tls_port_, 0};
+ auto binds = config->binds_;
for (uint32_t *port = ports; *port; ++port) {
for (const auto &bind : binds) {
- Status s = listenTCP(bind, *port, config->backlog);
+ Status s = listenTCP(bind, *port, config->backlog_);
if (!s.IsOK()) {
LOG(ERROR) << "[worker] Failed to listen on: " << bind << ":" << *port << ". Error: " << s.Msg();
exit(1);
@@ -102,8 +102,8 @@ Worker::~Worker() {
void Worker::TimerCB(int, int16_t events, void *ctx) {
auto worker = static_cast<Worker *>(ctx);
auto config = worker->svr_->GetConfig();
- if (config->timeout == 0) return;
- worker->KickoutIdleClients(config->timeout);
+ if (config->timeout_ == 0) return;
+ worker->KickoutIdleClients(config->timeout_);
}
void Worker::newTCPConnection(evconnlistener *listener, evutil_socket_t fd, sockaddr *address, int socklen, void *ctx) {
@@ -132,7 +132,7 @@ void Worker::newTCPConnection(evconnlistener *listener, evutil_socket_t fd, sock
bufferevent *bev = nullptr;
#ifdef ENABLE_OPENSSL
SSL *ssl = nullptr;
- if (uint32_t(local_port) == worker->svr_->GetConfig()->tls_port) {
+ if (uint32_t(local_port) == worker->svr_->GetConfig()->tls_port_) {
ssl = SSL_new(worker->svr_->ssl_ctx_.get());
if (!ssl) {
LOG(ERROR) << "Failed to construct SSL structure for new connection: " << SSLErrors{};
@@ -158,7 +158,7 @@ void Worker::newTCPConnection(evconnlistener *listener, evutil_socket_t fd, sock
return;
}
#ifdef ENABLE_OPENSSL
- if (uint32_t(local_port) == worker->svr_->GetConfig()->tls_port) {
+ if (uint32_t(local_port) == worker->svr_->GetConfig()->tls_port_) {
bufferevent_openssl_set_allow_dirty_shutdown(bev, 1);
}
#endif
@@ -191,7 +191,7 @@ void Worker::newTCPConnection(evconnlistener *listener, evutil_socket_t fd, sock
void Worker::newUnixSocketConnection(evconnlistener *listener, evutil_socket_t fd, sockaddr *address, int socklen,
void *ctx) {
auto worker = static_cast<Worker *>(ctx);
- DLOG(INFO) << "[worker] New connection: fd=" << fd << " from unixsocket: " << worker->svr_->GetConfig()->unixsocket
+ DLOG(INFO) << "[worker] New connection: fd=" << fd << " from unixsocket: " << worker->svr_->GetConfig()->unixsocket_
<< " thread #" << worker->tid_;
event_base *base = evconnlistener_get_base(listener);
auto ev_thread_safe_flags =
@@ -213,7 +213,7 @@ void Worker::newUnixSocketConnection(evconnlistener *listener, evutil_socket_t f
return;
}
- conn->SetAddr(worker->svr_->GetConfig()->unixsocket, 0);
+ conn->SetAddr(worker->svr_->GetConfig()->unixsocket_, 0);
if (worker->rate_limit_group_) {
bufferevent_add_to_rate_limit_group(bev, worker->rate_limit_group_);
}
@@ -319,7 +319,7 @@ Status Worker::AddConnection(Redis::Connection *c) {
return {Status::NotOK, "connection was exists"};
}
- int max_clients = svr_->GetConfig()->maxclients;
+ int max_clients = svr_->GetConfig()->maxclients_;
if (svr_->IncrClientNum() >= max_clients) {
svr_->DecrClientNum();
return {Status::NotOK, "max number of clients reached"};
@@ -504,7 +504,7 @@ void Worker::KickoutIdleClients(int timeout) {
}
int iterations = std::min(static_cast<int>(conns_.size()), 50);
- auto iter = conns_.upper_bound(last_iter_conn_fd);
+ auto iter = conns_.upper_bound(last_iter_conn_fd_);
while (iterations--) {
if (iter == conns_.end()) iter = conns_.begin();
if (static_cast<int>(iter->second->GetIdleTime()) >= timeout) {
@@ -513,7 +513,7 @@ void Worker::KickoutIdleClients(int timeout) {
iter++;
}
iter--;
- last_iter_conn_fd = iter->first;
+ last_iter_conn_fd_ = iter->first;
}
for (const auto &conn : to_be_killed_conns) {
diff --git a/src/server/worker.h b/src/server/worker.h
index ef1bf0f5..36642114 100644
--- a/src/server/worker.h
+++ b/src/server/worker.h
@@ -86,7 +86,7 @@ class Worker {
std::mutex conns_mu_;
std::map<int, Redis::Connection *> conns_;
std::map<int, Redis::Connection *> monitor_conns_;
- int last_iter_conn_fd = 0; // fd of last processed connection in previous cron
+ int last_iter_conn_fd_ = 0; // fd of last processed connection in previous cron
struct bufferevent_rate_limit_group *rate_limit_group_ = nullptr;
struct ev_token_bucket_cfg *rate_limit_group_cfg_ = nullptr;
diff --git a/src/stats/disk_stats.cc b/src/stats/disk_stats.cc
index d17b842a..7bbea04d 100644
--- a/src/stats/disk_stats.cc
+++ b/src/stats/disk_stats.cc
@@ -34,8 +34,8 @@ rocksdb::Status Disk::GetApproximateSizes(const Metadata &metadata, const Slice
rocksdb::ColumnFamilyHandle *column_family, uint64_t *key_size,
Slice subkeyleft, Slice subkeyright) {
std::string prefix_key, next_version_prefix_key;
- InternalKey(ns_key, subkeyleft, metadata.version, storage_->IsSlotIdEncoded()).Encode(&prefix_key);
- InternalKey(ns_key, subkeyright, metadata.version + 1, storage_->IsSlotIdEncoded()).Encode(&next_version_prefix_key);
+ InternalKey(ns_key, subkeyleft, metadata.version_, storage_->IsSlotIdEncoded()).Encode(&prefix_key);
+ InternalKey(ns_key, subkeyright, metadata.version_ + 1, storage_->IsSlotIdEncoded()).Encode(&next_version_prefix_key);
auto key_range = rocksdb::Range(prefix_key, next_version_prefix_key);
uint64_t tmp_size = 0;
rocksdb::Status s = storage_->GetDB()->GetApproximateSizes(option_, column_family, &key_range, 1, &tmp_size);
@@ -95,7 +95,7 @@ rocksdb::Status Disk::GetListSize(const Slice &ns_key, uint64_t *key_size) {
rocksdb::Status s = Database::GetMetadata(kRedisList, ns_key, &metadata);
if (!s.ok()) return s.IsNotFound() ? rocksdb::Status::OK() : s;
std::string buf;
- PutFixed64(&buf, metadata.head);
+ PutFixed64(&buf, metadata.head_);
return GetApproximateSizes(metadata, ns_key, storage_->GetCFHandle(Engine::kSubkeyColumnFamilyName), key_size, buf);
}
diff --git a/src/stats/log_collector.cc b/src/stats/log_collector.cc
index 82808c53..1f58ea2d 100644
--- a/src/stats/log_collector.cc
+++ b/src/stats/log_collector.cc
@@ -28,22 +28,22 @@
std::string SlowEntry::ToRedisString() const {
std::string output;
output.append(Redis::MultiLen(4));
- output.append(Redis::Integer(id));
- output.append(Redis::Integer(time));
- output.append(Redis::Integer(duration));
- output.append(Redis::MultiBulkString(args));
+ output.append(Redis::Integer(id_));
+ output.append(Redis::Integer(time_));
+ output.append(Redis::Integer(duration_));
+ output.append(Redis::MultiBulkString(args_));
return output;
}
std::string PerfEntry::ToRedisString() const {
std::string output;
output.append(Redis::MultiLen(6));
- output.append(Redis::Integer(id));
- output.append(Redis::Integer(time));
- output.append(Redis::BulkString(cmd_name));
- output.append(Redis::Integer(duration));
- output.append(Redis::BulkString(perf_context));
- output.append(Redis::BulkString(iostats_context));
+ output.append(Redis::Integer(id_));
+ output.append(Redis::Integer(time_));
+ output.append(Redis::BulkString(cmd_name_));
+ output.append(Redis::Integer(duration_));
+ output.append(Redis::BulkString(perf_context_));
+ output.append(Redis::BulkString(iostats_context_));
return output;
}
@@ -79,8 +79,8 @@ void LogCollector<T>::SetMaxEntries(int64_t max_entries) {
template <class T>
void LogCollector<T>::PushEntry(std::unique_ptr<T> &&entry) {
std::lock_guard<std::mutex> guard(mu_);
- entry->id = ++id_;
- entry->time = Util::GetTimeStamp();
+ entry->id_ = ++id_;
+ entry->time_ = Util::GetTimeStamp();
if (max_entries_ > 0 && !entries_.empty() && entries_.size() >= static_cast<size_t>(max_entries_)) {
entries_.pop_back();
}
diff --git a/src/stats/log_collector.h b/src/stats/log_collector.h
index 14bcea48..b0844b4f 100644
--- a/src/stats/log_collector.h
+++ b/src/stats/log_collector.h
@@ -32,22 +32,22 @@
class SlowEntry {
public:
- uint64_t id;
- time_t time;
- uint64_t duration;
- std::vector<std::string> args;
+ uint64_t id_;
+ time_t time_;
+ uint64_t duration_;
+ std::vector<std::string> args_;
std::string ToRedisString() const;
};
class PerfEntry {
public:
- uint64_t id;
- time_t time;
- uint64_t duration;
- std::string cmd_name;
- std::string perf_context;
- std::string iostats_context;
+ uint64_t id_;
+ time_t time_;
+ uint64_t duration_;
+ std::string cmd_name_;
+ std::string perf_context_;
+ std::string iostats_context_;
std::string ToRedisString() const;
};
diff --git a/src/stats/stats.cc b/src/stats/stats.cc
index d8aa2b9d..b41c5349 100644
--- a/src/stats/stats.cc
+++ b/src/stats/stats.cc
@@ -28,13 +28,13 @@
Stats::Stats() {
for (int i = 0; i < STATS_METRIC_COUNT; i++) {
struct InstMetric im;
- im.last_sample_time = 0;
- im.last_sample_count = 0;
- im.idx = 0;
- for (uint64_t &sample : im.samples) {
+ im.last_sample_time_ = 0;
+ im.last_sample_count_ = 0;
+ im.idx_ = 0;
+ for (uint64_t &sample : im.samples_) {
sample = 0;
}
- inst_metrics.push_back(im);
+ inst_metrics_.push_back(im);
}
}
@@ -83,28 +83,28 @@ int64_t Stats::GetMemoryRSS() {
#endif
void Stats::IncrCalls(const std::string &command_name) {
- total_calls.fetch_add(1, std::memory_order_relaxed);
- commands_stats[command_name].calls.fetch_add(1, std::memory_order_relaxed);
+ total_calls_.fetch_add(1, std::memory_order_relaxed);
+ commands_stats_[command_name].calls_.fetch_add(1, std::memory_order_relaxed);
}
void Stats::IncrLatency(uint64_t latency, const std::string &command_name) {
- commands_stats[command_name].latency.fetch_add(latency, std::memory_order_relaxed);
+ commands_stats_[command_name].latency_.fetch_add(latency, std::memory_order_relaxed);
}
void Stats::TrackInstantaneousMetric(int metric, uint64_t current_reading) {
uint64_t curr_time = Util::GetTimeStampMS();
- uint64_t t = curr_time - inst_metrics[metric].last_sample_time;
- uint64_t ops = current_reading - inst_metrics[metric].last_sample_count;
+ uint64_t t = curr_time - inst_metrics_[metric].last_sample_time_;
+ uint64_t ops = current_reading - inst_metrics_[metric].last_sample_count_;
uint64_t ops_sec = t > 0 ? (ops * 1000 / t) : 0;
- inst_metrics[metric].samples[inst_metrics[metric].idx] = ops_sec;
- inst_metrics[metric].idx++;
- inst_metrics[metric].idx %= STATS_METRIC_SAMPLES;
- inst_metrics[metric].last_sample_time = curr_time;
- inst_metrics[metric].last_sample_count = current_reading;
+ inst_metrics_[metric].samples_[inst_metrics_[metric].idx_] = ops_sec;
+ inst_metrics_[metric].idx_++;
+ inst_metrics_[metric].idx_ %= STATS_METRIC_SAMPLES;
+ inst_metrics_[metric].last_sample_time_ = curr_time;
+ inst_metrics_[metric].last_sample_count_ = current_reading;
}
uint64_t Stats::GetInstantaneousMetric(int metric) {
uint64_t sum = 0;
- for (uint64_t sample : inst_metrics[metric].samples) sum += sample;
+ for (uint64_t sample : inst_metrics_[metric].samples_) sum += sample;
return sum / STATS_METRIC_SAMPLES;
}
diff --git a/src/stats/stats.h b/src/stats/stats.h
index 50e58110..5e53e042 100644
--- a/src/stats/stats.h
+++ b/src/stats/stats.h
@@ -43,37 +43,37 @@ enum StatsMetricFlags {
const int STATS_METRIC_SAMPLES = 16; // Number of samples per metric
struct CommandStat {
- std::atomic<uint64_t> calls;
- std::atomic<uint64_t> latency;
+ std::atomic<uint64_t> calls_;
+ std::atomic<uint64_t> latency_;
};
struct InstMetric {
- uint64_t last_sample_time; // Timestamp of the last sample in ms
- uint64_t last_sample_count; // Count in the last sample
- uint64_t samples[STATS_METRIC_SAMPLES];
- int idx;
+ uint64_t last_sample_time_; // Timestamp of the last sample in ms
+ uint64_t last_sample_count_; // Count in the last sample
+ uint64_t samples_[STATS_METRIC_SAMPLES];
+ int idx_;
};
class Stats {
public:
- std::atomic<uint64_t> total_calls = {0};
- std::atomic<uint64_t> in_bytes = {0};
- std::atomic<uint64_t> out_bytes = {0};
- std::vector<struct InstMetric> inst_metrics;
+ std::atomic<uint64_t> total_calls_ = {0};
+ std::atomic<uint64_t> in_bytes_ = {0};
+ std::atomic<uint64_t> out_bytes_ = {0};
+ std::vector<struct InstMetric> inst_metrics_;
- std::atomic<uint64_t> fullsync_counter = {0};
- std::atomic<uint64_t> psync_err_counter = {0};
- std::atomic<uint64_t> psync_ok_counter = {0};
- std::map<std::string, CommandStat> commands_stats;
+ std::atomic<uint64_t> fullsync_counter_ = {0};
+ std::atomic<uint64_t> psync_err_counter_ = {0};
+ std::atomic<uint64_t> psync_ok_counter_ = {0};
+ std::map<std::string, CommandStat> commands_stats_;
Stats();
void IncrCalls(const std::string &command_name);
void IncrLatency(uint64_t latency, const std::string &command_name);
- void IncrInbondBytes(uint64_t bytes) { in_bytes.fetch_add(bytes, std::memory_order_relaxed); }
- void IncrOutbondBytes(uint64_t bytes) { out_bytes.fetch_add(bytes, std::memory_order_relaxed); }
- void IncrFullSyncCounter() { fullsync_counter.fetch_add(1, std::memory_order_relaxed); }
- void IncrPSyncErrCounter() { psync_err_counter.fetch_add(1, std::memory_order_relaxed); }
- void IncrPSyncOKCounter() { psync_ok_counter.fetch_add(1, std::memory_order_relaxed); }
+ void IncrInbondBytes(uint64_t bytes) { in_bytes_.fetch_add(bytes, std::memory_order_relaxed); }
+ void IncrOutbondBytes(uint64_t bytes) { out_bytes_.fetch_add(bytes, std::memory_order_relaxed); }
+ void IncrFullSyncCounter() { fullsync_counter_.fetch_add(1, std::memory_order_relaxed); }
+ void IncrPSyncErrCounter() { psync_err_counter_.fetch_add(1, std::memory_order_relaxed); }
+ void IncrPSyncOKCounter() { psync_ok_counter_.fetch_add(1, std::memory_order_relaxed); }
static int64_t GetMemoryRSS();
void TrackInstantaneousMetric(int metric, uint64_t current_reading);
uint64_t GetInstantaneousMetric(int metric);
diff --git a/src/storage/batch_debugger.h b/src/storage/batch_debugger.h
index 39e98e3f..b2e0cac4 100644
--- a/src/storage/batch_debugger.h
+++ b/src/storage/batch_debugger.h
@@ -31,87 +31,87 @@
/// LOG(INFO) << inspector.seen << ", cnt: " << inspector.cnt;
/// ```
struct WriteBatchInspector : public rocksdb::WriteBatch::Handler {
- std::string seen;
- int cnt = 0;
+ std::string seen_;
+ int cnt_ = 0;
rocksdb::Status PutCF(uint32_t column_family_id, const rocksdb::Slice& key, const rocksdb::Slice& value) override {
- ++cnt;
+ ++cnt_;
if (column_family_id == 0) {
- seen += "Put(" + key.ToString() + ", " + value.ToString() + ")";
+ seen_ += "Put(" + key.ToString() + ", " + value.ToString() + ")";
} else {
- seen += "PutCF(" + std::to_string(column_family_id) + ", " + key.ToString() + ", " + value.ToString() + ")";
+ seen_ += "PutCF(" + std::to_string(column_family_id) + ", " + key.ToString() + ", " + value.ToString() + ")";
}
return rocksdb::Status::OK();
}
rocksdb::Status DeleteCF(uint32_t column_family_id, const rocksdb::Slice& key) override {
- ++cnt;
+ ++cnt_;
if (column_family_id == 0) {
- seen += "Delete(" + key.ToString() + ")";
+ seen_ += "Delete(" + key.ToString() + ")";
} else {
- seen += "DeleteCF(" + std::to_string(column_family_id) + ", " + key.ToString() + ")";
+ seen_ += "DeleteCF(" + std::to_string(column_family_id) + ", " + key.ToString() + ")";
}
return rocksdb::Status::OK();
}
rocksdb::Status SingleDeleteCF(uint32_t column_family_id, const rocksdb::Slice& key) override {
- ++cnt;
+ ++cnt_;
if (column_family_id == 0) {
- seen += "SingleDelete(" + key.ToString() + ")";
+ seen_ += "SingleDelete(" + key.ToString() + ")";
} else {
- seen += "SingleDeleteCF(" + std::to_string(column_family_id) + ", " + key.ToString() + ")";
+ seen_ += "SingleDeleteCF(" + std::to_string(column_family_id) + ", " + key.ToString() + ")";
}
return rocksdb::Status::OK();
}
rocksdb::Status DeleteRangeCF(uint32_t column_family_id, const rocksdb::Slice& begin_key,
const rocksdb::Slice& end_key) override {
- ++cnt;
+ ++cnt_;
if (column_family_id == 0) {
- seen += "DeleteRange(" + begin_key.ToString() + ", " + end_key.ToString() + ")";
+ seen_ += "DeleteRange(" + begin_key.ToString() + ", " + end_key.ToString() + ")";
} else {
- seen += "DeleteRangeCF(" + std::to_string(column_family_id) + ", " + begin_key.ToString() + ", " +
- end_key.ToString() + ")";
+ seen_ += "DeleteRangeCF(" + std::to_string(column_family_id) + ", " + begin_key.ToString() + ", " +
+ end_key.ToString() + ")";
}
return rocksdb::Status::OK();
}
rocksdb::Status MergeCF(uint32_t column_family_id, const rocksdb::Slice& key, const rocksdb::Slice& value) override {
- ++cnt;
+ ++cnt_;
if (column_family_id == 0) {
- seen += "Merge(" + key.ToString() + ", " + value.ToString() + ")";
+ seen_ += "Merge(" + key.ToString() + ", " + value.ToString() + ")";
} else {
- seen += "MergeCF(" + std::to_string(column_family_id) + ", " + key.ToString() + ", " + value.ToString() + ")";
+ seen_ += "MergeCF(" + std::to_string(column_family_id) + ", " + key.ToString() + ", " + value.ToString() + ")";
}
return rocksdb::Status::OK();
}
void LogData(const rocksdb::Slice& blob) override {
- ++cnt;
- seen += "LogData(" + blob.ToString() + ")";
+ ++cnt_;
+ seen_ += "LogData(" + blob.ToString() + ")";
}
rocksdb::Status MarkBeginPrepare(bool unprepare) override {
- ++cnt;
- seen += "MarkBeginPrepare(" + std::string(unprepare ? "true" : "false") + ")";
+ ++cnt_;
+ seen_ += "MarkBeginPrepare(" + std::string(unprepare ? "true" : "false") + ")";
return rocksdb::Status::OK();
}
rocksdb::Status MarkEndPrepare(const rocksdb::Slice& xid) override {
- ++cnt;
- seen += "MarkEndPrepare(" + xid.ToString() + ")";
+ ++cnt_;
+ seen_ += "MarkEndPrepare(" + xid.ToString() + ")";
return rocksdb::Status::OK();
}
rocksdb::Status MarkNoop(bool empty_batch) override {
- ++cnt;
- seen += "MarkNoop(" + std::string(empty_batch ? "true" : "false") + ")";
+ ++cnt_;
+ seen_ += "MarkNoop(" + std::string(empty_batch ? "true" : "false") + ")";
return rocksdb::Status::OK();
}
rocksdb::Status MarkCommit(const rocksdb::Slice& xid) override {
- ++cnt;
- seen += "MarkCommit(" + xid.ToString() + ")";
+ ++cnt_;
+ seen_ += "MarkCommit(" + xid.ToString() + ")";
return rocksdb::Status::OK();
}
rocksdb::Status MarkCommitWithTimestamp(const rocksdb::Slice& xid, const rocksdb::Slice& ts) override {
- ++cnt;
- seen += "MarkCommitWithTimestamp(" + xid.ToString() + ", " + ts.ToString(true) + ")";
+ ++cnt_;
+ seen_ += "MarkCommitWithTimestamp(" + xid.ToString() + ", " + ts.ToString(true) + ")";
return rocksdb::Status::OK();
}
rocksdb::Status MarkRollback(const rocksdb::Slice& xid) override {
- ++cnt;
- seen += "MarkRollback(" + xid.ToString() + ")";
+ ++cnt_;
+ seen_ += "MarkRollback(" + xid.ToString() + ")";
return rocksdb::Status::OK();
}
};
diff --git a/src/storage/batch_extractor.cc b/src/storage/batch_extractor.cc
index 17984309..6b3611af 100644
--- a/src/storage/batch_extractor.cc
+++ b/src/storage/batch_extractor.cc
@@ -63,11 +63,11 @@ rocksdb::Status WriteBatchExtractor::PutCF(uint32_t column_family_id, const Slic
if (metadata.Type() == kRedisString) {
command_args = {"SET", user_key, value.ToString().substr(Metadata::GetOffsetAfterExpire(value[0]))};
resp_commands_[ns].emplace_back(Redis::Command2RESP(command_args));
- if (metadata.expire > 0) {
- command_args = {"PEXPIREAT", user_key, std::to_string(metadata.expire)};
+ if (metadata.expire_ > 0) {
+ command_args = {"PEXPIREAT", user_key, std::to_string(metadata.expire_)};
resp_commands_[ns].emplace_back(Redis::Command2RESP(command_args));
}
- } else if (metadata.expire > 0) {
+ } else if (metadata.expire_ > 0) {
auto args = log_data_.GetArguments();
if (args->size() > 0) {
auto parse_result = ParseInt<int>((*args)[0], 10);
@@ -78,7 +78,7 @@ rocksdb::Status WriteBatchExtractor::PutCF(uint32_t column_family_id, const Slic
auto cmd = static_cast<RedisCommand>(*parse_result);
if (cmd == kRedisCmdExpire) {
- command_args = {"PEXPIREAT", user_key, std::to_string(metadata.expire)};
+ command_args = {"PEXPIREAT", user_key, std::to_string(metadata.expire_)};
resp_commands_[ns].emplace_back(Redis::Command2RESP(command_args));
}
}
@@ -97,11 +97,11 @@ rocksdb::Status WriteBatchExtractor::PutCF(uint32_t column_family_id, const Slic
command_args = {"XSETID",
user_key,
- stream_metadata.last_entry_id.ToString(),
+ stream_metadata.last_entry_id_.ToString(),
"ENTRIESADDED",
- std::to_string(stream_metadata.entries_added),
+ std::to_string(stream_metadata.entries_added_),
"MAXDELETEDID",
- stream_metadata.max_deleted_entry_id.ToString()};
+ stream_metadata.max_deleted_entry_id_.ToString()};
resp_commands_[ns].emplace_back(Redis::Command2RESP(command_args));
}
@@ -375,8 +375,8 @@ rocksdb::Status WriteBatchExtractor::DeleteCF(uint32_t column_family_id, const S
InternalKey ikey(key, is_slot_id_encoded_);
Slice encoded_id = ikey.GetSubKey();
Redis::StreamEntryID entry_id;
- GetFixed64(&encoded_id, &entry_id.ms);
- GetFixed64(&encoded_id, &entry_id.seq);
+ GetFixed64(&encoded_id, &entry_id.ms_);
+ GetFixed64(&encoded_id, &entry_id.seq_);
command_args = {"XDEL", ikey.GetKey().ToString(), entry_id.ToString()};
}
@@ -407,8 +407,8 @@ Status WriteBatchExtractor::ExtractStreamAddCommand(bool is_slot_id_encoded, con
Slice encoded_id = ikey.GetSubKey();
Redis::StreamEntryID entry_id;
- GetFixed64(&encoded_id, &entry_id.ms);
- GetFixed64(&encoded_id, &entry_id.seq);
+ GetFixed64(&encoded_id, &entry_id.ms_);
+ GetFixed64(&encoded_id, &entry_id.seq_);
command_args->emplace_back(entry_id.ToString());
command_args->insert(command_args->end(), values.begin(), values.end());
diff --git a/src/storage/compact_filter.cc b/src/storage/compact_filter.cc
index f9e1f000..47d0359f 100644
--- a/src/storage/compact_filter.cc
+++ b/src/storage/compact_filter.cc
@@ -94,7 +94,7 @@ bool SubKeyFilter::IsMetadataExpired(const InternalKey &ikey, const Metadata &me
// to prevent them from being recycled once they reach the expiration time.
uint64_t lazy_expired_ts = Util::GetTimeStampMS() - 300000;
return metadata.Type() == kRedisString // metadata key was overwrite by set command
- || metadata.ExpireAt(lazy_expired_ts) || ikey.GetVersion() != metadata.version;
+ || metadata.ExpireAt(lazy_expired_ts) || ikey.GetVersion() != metadata.version_;
}
rocksdb::CompactionFilter::Decision SubKeyFilter::FilterBlobByKey(int level, const Slice &key, std::string *new_value,
diff --git a/src/storage/compaction_checker.cc b/src/storage/compaction_checker.cc
index 8fb753ec..b3c72b73 100644
--- a/src/storage/compaction_checker.cc
+++ b/src/storage/compaction_checker.cc
@@ -57,9 +57,9 @@ void CompactionChecker::PickCompactionFiles(const std::string &cf_name) {
}
int64_t now = Util::GetTimeStamp();
- auto force_compact_file_age = storage_->GetConfig()->force_compact_file_age;
+ auto force_compact_file_age = storage_->GetConfig()->force_compact_file_age_;
auto force_compact_min_ratio =
- static_cast<double>(storage_->GetConfig()->force_compact_file_min_deleted_percentage / 100);
+ static_cast<double>(storage_->GetConfig()->force_compact_file_min_deleted_percentage_ / 100);
std::string best_filename;
double best_delete_ratio = 0;
diff --git a/src/storage/redis_db.cc b/src/storage/redis_db.cc
index f383fc01..5c015391 100644
--- a/src/storage/redis_db.cc
+++ b/src/storage/redis_db.cc
@@ -51,11 +51,11 @@ rocksdb::Status Database::GetMetadata(RedisType type, const Slice &ns_key, Metad
return rocksdb::Status::NotFound(kErrMsgKeyExpired);
}
if (metadata->Type() != type &&
- (metadata->size > 0 || metadata->Type() == kRedisString || metadata->Type() == kRedisStream)) {
+ (metadata->size_ > 0 || metadata->Type() == kRedisString || metadata->Type() == kRedisStream)) {
metadata->Decode(old_metadata);
return rocksdb::Status::InvalidArgument(kErrMsgWrongType);
}
- if (metadata->size == 0 && type != kRedisStream) { // stream is allowed to be empty
+ if (metadata->size_ == 0 && type != kRedisStream) { // stream is allowed to be empty
metadata->Decode(old_metadata);
return rocksdb::Status::NotFound("no elements");
}
@@ -88,10 +88,10 @@ rocksdb::Status Database::Expire(const Slice &user_key, uint64_t timestamp) {
if (metadata.Expired()) {
return rocksdb::Status::NotFound(kErrMsgKeyExpired);
}
- if (metadata.Type() != kRedisString && metadata.size == 0) {
+ if (metadata.Type() != kRedisString && metadata.size_ == 0) {
return rocksdb::Status::NotFound("no elements");
}
- if (metadata.expire == timestamp) return rocksdb::Status::OK();
+ if (metadata.expire_ == timestamp) return rocksdb::Status::OK();
// +1 to skip the flags
if (metadata.Is64BitEncoded()) {
@@ -196,14 +196,14 @@ void Database::Keys(const std::string &prefix, std::vector<std::string> *keys, K
value = iter->value().ToString();
metadata.Decode(value);
if (metadata.Expired()) {
- if (stats) stats->n_expired++;
+ if (stats) stats->n_expired_++;
continue;
}
if (stats) {
int64_t ttl = metadata.TTL();
- stats->n_key++;
+ stats->n_key_++;
if (ttl != -1) {
- stats->n_expires++;
+ stats->n_expires_++;
if (ttl > 0) ttl_sum += ttl;
}
}
@@ -222,8 +222,8 @@ void Database::Keys(const std::string &prefix, std::vector<std::string> *keys, K
ns_prefix.append(prefix);
}
- if (stats && stats->n_expires > 0) {
- stats->avg_ttl = ttl_sum / stats->n_expires / 1000;
+ if (stats && stats->n_expires_ > 0) {
+ stats->avg_ttl_ = ttl_sum / stats->n_expires_ / 1000;
}
}
@@ -401,13 +401,13 @@ rocksdb::Status Database::Dump(const Slice &user_key, std::vector<std::string> *
infos->emplace_back("type");
infos->emplace_back(RedisTypeNames[metadata.Type()]);
infos->emplace_back("version");
- infos->emplace_back(std::to_string(metadata.version));
+ infos->emplace_back(std::to_string(metadata.version_));
infos->emplace_back("expire");
- infos->emplace_back(std::to_string(Metadata::ExpireMsToS(metadata.expire)));
+ infos->emplace_back(std::to_string(Metadata::ExpireMsToS(metadata.expire_)));
infos->emplace_back("pexpire");
- infos->emplace_back(std::to_string(metadata.expire));
+ infos->emplace_back(std::to_string(metadata.expire_));
infos->emplace_back("size");
- infos->emplace_back(std::to_string(metadata.size));
+ infos->emplace_back(std::to_string(metadata.size_));
infos->emplace_back("is_64bit_common_field");
infos->emplace_back(std::to_string(metadata.Is64BitEncoded()));
@@ -426,9 +426,9 @@ rocksdb::Status Database::Dump(const Slice &user_key, std::vector<std::string> *
GetMetadata(kRedisList, ns_key, &list_metadata);
if (!s.ok()) return s.IsNotFound() ? rocksdb::Status::OK() : s;
infos->emplace_back("head");
- infos->emplace_back(std::to_string(list_metadata.head));
+ infos->emplace_back(std::to_string(list_metadata.head_));
infos->emplace_back("tail");
- infos->emplace_back(std::to_string(list_metadata.tail));
+ infos->emplace_back(std::to_string(list_metadata.tail_));
}
return rocksdb::Status::OK();
@@ -581,14 +581,14 @@ rocksdb::Status SubKeyScanner::Scan(RedisType type, const Slice &user_key, const
auto iter = DBUtil::UniqueIterator(storage_, read_options);
std::string match_prefix_key;
if (!subkey_prefix.empty()) {
- InternalKey(ns_key, subkey_prefix, metadata.version, storage_->IsSlotIdEncoded()).Encode(&match_prefix_key);
+ InternalKey(ns_key, subkey_prefix, metadata.version_, storage_->IsSlotIdEncoded()).Encode(&match_prefix_key);
} else {
- InternalKey(ns_key, "", metadata.version, storage_->IsSlotIdEncoded()).Encode(&match_prefix_key);
+ InternalKey(ns_key, "", metadata.version_, storage_->IsSlotIdEncoded()).Encode(&match_prefix_key);
}
std::string start_key;
if (!cursor.empty()) {
- InternalKey(ns_key, cursor, metadata.version, storage_->IsSlotIdEncoded()).Encode(&start_key);
+ InternalKey(ns_key, cursor, metadata.version_, storage_->IsSlotIdEncoded()).Encode(&start_key);
} else {
start_key = match_prefix_key;
}
diff --git a/src/storage/redis_metadata.cc b/src/storage/redis_metadata.cc
index 8a9c564a..2cf45424 100644
--- a/src/storage/redis_metadata.cc
+++ b/src/storage/redis_metadata.cc
@@ -148,14 +148,14 @@ void ComposeSlotKeyPrefix(const Slice &ns, int slotid, std::string *output) {
}
Metadata::Metadata(RedisType type, bool generate_version, bool use_64bit_common_field)
- : flags((use_64bit_common_field ? METADATA_64BIT_ENCODING_MASK : 0) | (METADATA_TYPE_MASK & type)),
- expire(0),
- version(generate_version ? generateVersion() : 0),
- size(0) {}
+ : flags_((use_64bit_common_field ? METADATA_64BIT_ENCODING_MASK : 0) | (METADATA_TYPE_MASK & type)),
+ expire_(0),
+ version_(generate_version ? generateVersion() : 0),
+ size_(0) {}
rocksdb::Status Metadata::Decode(const std::string &bytes) {
Slice input(bytes);
- if (!GetFixed8(&input, &flags)) {
+ if (!GetFixed8(&input, &flags_)) {
return rocksdb::Status::InvalidArgument(kErrMetadataTooShort);
}
@@ -167,19 +167,19 @@ rocksdb::Status Metadata::Decode(const std::string &bytes) {
if (input.size() < 8 + CommonEncodedSize()) {
return rocksdb::Status::InvalidArgument(kErrMetadataTooShort);
}
- GetFixed64(&input, &version);
- GetFixedCommon(&input, &size);
+ GetFixed64(&input, &version_);
+ GetFixedCommon(&input, &size_);
}
return rocksdb::Status::OK();
}
void Metadata::Encode(std::string *dst) {
- PutFixed8(dst, flags);
+ PutFixed8(dst, flags_);
PutExpire(dst);
if (Type() != kRedisString) {
- PutFixed64(dst, version);
- PutFixedCommon(dst, size);
+ PutFixed64(dst, version_);
+ PutFixedCommon(dst, size_);
}
}
@@ -196,16 +196,16 @@ uint64_t Metadata::generateVersion() {
}
bool Metadata::operator==(const Metadata &that) const {
- if (flags != that.flags) return false;
- if (expire != that.expire) return false;
+ if (flags_ != that.flags_) return false;
+ if (expire_ != that.expire_) return false;
if (Type() != kRedisString) {
- if (size != that.size) return false;
- if (version != that.version) return false;
+ if (size_ != that.size_) return false;
+ if (version_ != that.version_) return false;
}
return true;
}
-RedisType Metadata::Type() const { return static_cast<RedisType>(flags & METADATA_TYPE_MASK); }
+RedisType Metadata::Type() const { return static_cast<RedisType>(flags_ & METADATA_TYPE_MASK); }
size_t Metadata::GetOffsetAfterExpire(uint8_t flags) {
if (flags & METADATA_64BIT_ENCODING_MASK) {
@@ -236,7 +236,7 @@ uint64_t Metadata::ExpireMsToS(uint64_t ms) {
return (ms + 499) / 1000;
}
-bool Metadata::Is64BitEncoded() const { return flags & METADATA_64BIT_ENCODING_MASK; }
+bool Metadata::Is64BitEncoded() const { return flags_ & METADATA_64BIT_ENCODING_MASK; }
size_t Metadata::CommonEncodedSize() const { return Is64BitEncoded() ? 8 : 4; }
@@ -259,9 +259,9 @@ bool Metadata::GetExpire(rocksdb::Slice *input) {
}
if (Is64BitEncoded()) {
- expire = v;
+ expire_ = v;
} else {
- expire = v * 1000;
+ expire_ = v * 1000;
}
return true;
@@ -277,27 +277,27 @@ void Metadata::PutFixedCommon(std::string *dst, uint64_t value) const {
void Metadata::PutExpire(std::string *dst) const {
if (Is64BitEncoded()) {
- PutFixed64(dst, expire);
+ PutFixed64(dst, expire_);
} else {
- PutFixed32(dst, ExpireMsToS(expire));
+ PutFixed32(dst, ExpireMsToS(expire_));
}
}
int64_t Metadata::TTL() const {
- if (expire == 0) {
+ if (expire_ == 0) {
return -1;
}
auto now = Util::GetTimeStampMS();
- if (expire < now) {
+ if (expire_ < now) {
return -2;
}
- return int64_t(expire - now);
+ return int64_t(expire_ - now);
}
timeval Metadata::Time() const {
- auto t = version >> VersionCounterBits;
+ auto t = version_ >> VersionCounterBits;
struct timeval created_at {
static_cast<uint32_t>(t / 1000000), static_cast<int32_t>(t % 1000000)
};
@@ -305,40 +305,40 @@ timeval Metadata::Time() const {
}
bool Metadata::ExpireAt(uint64_t expired_ts) const {
- if (Type() != kRedisString && Type() != kRedisStream && size == 0) {
+ if (Type() != kRedisString && Type() != kRedisStream && size_ == 0) {
return true;
}
- if (expire == 0) {
+ if (expire_ == 0) {
return false;
}
- return expire < expired_ts;
+ return expire_ < expired_ts;
}
bool Metadata::Expired() const { return ExpireAt(Util::GetTimeStampMS()); }
ListMetadata::ListMetadata(bool generate_version)
- : Metadata(kRedisList, generate_version), head(UINT64_MAX / 2), tail(head) {}
+ : Metadata(kRedisList, generate_version), head_(UINT64_MAX / 2), tail_(head_) {}
void ListMetadata::Encode(std::string *dst) {
Metadata::Encode(dst);
- PutFixed64(dst, head);
- PutFixed64(dst, tail);
+ PutFixed64(dst, head_);
+ PutFixed64(dst, tail_);
}
rocksdb::Status ListMetadata::Decode(const std::string &bytes) {
Slice input(bytes);
- GetFixed8(&input, &flags);
+ GetFixed8(&input, &flags_);
GetExpire(&input);
if (Type() != kRedisString) {
if (input.size() < 8 + CommonEncodedSize()) return rocksdb::Status::InvalidArgument(kErrMetadataTooShort);
- GetFixed64(&input, &version);
- GetFixedCommon(&input, &size);
+ GetFixed64(&input, &version_);
+ GetFixedCommon(&input, &size_);
}
if (Type() == kRedisList) {
if (input.size() < 8 + 8) return rocksdb::Status::InvalidArgument(kErrMetadataTooShort);
- GetFixed64(&input, &head);
- GetFixed64(&input, &tail);
+ GetFixed64(&input, &head_);
+ GetFixed64(&input, &tail_);
}
return rocksdb::Status::OK();
}
@@ -346,27 +346,27 @@ rocksdb::Status ListMetadata::Decode(const std::string &bytes) {
void StreamMetadata::Encode(std::string *dst) {
Metadata::Encode(dst);
- PutFixed64(dst, last_generated_id.ms);
- PutFixed64(dst, last_generated_id.seq);
+ PutFixed64(dst, last_generated_id_.ms_);
+ PutFixed64(dst, last_generated_id_.seq_);
- PutFixed64(dst, recorded_first_entry_id.ms);
- PutFixed64(dst, recorded_first_entry_id.seq);
+ PutFixed64(dst, recorded_first_entry_id_.ms_);
+ PutFixed64(dst, recorded_first_entry_id_.seq_);
- PutFixed64(dst, max_deleted_entry_id.ms);
- PutFixed64(dst, max_deleted_entry_id.seq);
+ PutFixed64(dst, max_deleted_entry_id_.ms_);
+ PutFixed64(dst, max_deleted_entry_id_.seq_);
- PutFixed64(dst, first_entry_id.ms);
- PutFixed64(dst, first_entry_id.seq);
+ PutFixed64(dst, first_entry_id_.ms_);
+ PutFixed64(dst, first_entry_id_.seq_);
- PutFixed64(dst, last_entry_id.ms);
- PutFixed64(dst, last_entry_id.seq);
+ PutFixed64(dst, last_entry_id_.ms_);
+ PutFixed64(dst, last_entry_id_.seq_);
- PutFixed64(dst, entries_added);
+ PutFixed64(dst, entries_added_);
}
rocksdb::Status StreamMetadata::Decode(const std::string &bytes) {
Slice input(bytes);
- if (!GetFixed8(&input, &flags)) {
+ if (!GetFixed8(&input, &flags_)) {
return rocksdb::Status::InvalidArgument(kErrMetadataTooShort);
}
if (!GetExpire(&input)) {
@@ -377,29 +377,29 @@ rocksdb::Status StreamMetadata::Decode(const std::string &bytes) {
return rocksdb::Status::InvalidArgument(kErrMetadataTooShort);
}
- GetFixed64(&input, &version);
- GetFixedCommon(&input, &size);
+ GetFixed64(&input, &version_);
+ GetFixedCommon(&input, &size_);
if (input.size() < 88) {
return rocksdb::Status::InvalidArgument(kErrMetadataTooShort);
}
- GetFixed64(&input, &last_generated_id.ms);
- GetFixed64(&input, &last_generated_id.seq);
+ GetFixed64(&input, &last_generated_id_.ms_);
+ GetFixed64(&input, &last_generated_id_.seq_);
- GetFixed64(&input, &recorded_first_entry_id.ms);
- GetFixed64(&input, &recorded_first_entry_id.seq);
+ GetFixed64(&input, &recorded_first_entry_id_.ms_);
+ GetFixed64(&input, &recorded_first_entry_id_.seq_);
- GetFixed64(&input, &max_deleted_entry_id.ms);
- GetFixed64(&input, &max_deleted_entry_id.seq);
+ GetFixed64(&input, &max_deleted_entry_id_.ms_);
+ GetFixed64(&input, &max_deleted_entry_id_.seq_);
- GetFixed64(&input, &first_entry_id.ms);
- GetFixed64(&input, &first_entry_id.seq);
+ GetFixed64(&input, &first_entry_id_.ms_);
+ GetFixed64(&input, &first_entry_id_.seq_);
- GetFixed64(&input, &last_entry_id.ms);
- GetFixed64(&input, &last_entry_id.seq);
+ GetFixed64(&input, &last_entry_id_.ms_);
+ GetFixed64(&input, &last_entry_id_.seq_);
- GetFixed64(&input, &entries_added);
+ GetFixed64(&input, &entries_added_);
return rocksdb::Status::OK();
}
diff --git a/src/storage/redis_metadata.h b/src/storage/redis_metadata.h
index f85094d0..0bbcf2ee 100644
--- a/src/storage/redis_metadata.h
+++ b/src/storage/redis_metadata.h
@@ -73,10 +73,10 @@ constexpr const char *kErrMsgKeyExpired = "the key was expired";
using rocksdb::Slice;
struct KeyNumStats {
- uint64_t n_key = 0;
- uint64_t n_expires = 0;
- uint64_t n_expired = 0;
- uint64_t avg_ttl = 0;
+ uint64_t n_key_ = 0;
+ uint64_t n_expires_ = 0;
+ uint64_t n_expired_ = 0;
+ uint64_t avg_ttl_ = 0;
};
void ExtractNamespaceKey(Slice ns_key, std::string *ns, std::string *key, bool slot_id_encoded);
@@ -115,16 +115,16 @@ class Metadata {
// 64bit-common-field-indicator: make `expire` and `size` 64bit instead of 32bit
// NOTE: `expire` is stored in milliseconds for 64bit, seconds for 32bit
// redis-type: RedisType for the key-value
- uint8_t flags;
+ uint8_t flags_;
// expire timestamp, in milliseconds
- uint64_t expire;
+ uint64_t expire_;
// the current version: 53bit timestamp + 11bit counter
- uint64_t version;
+ uint64_t version_;
// element size of the key-value
- uint64_t size;
+ uint64_t size_;
explicit Metadata(RedisType type, bool generate_version = true,
bool use_64bit_common_field = USE_64BIT_COMMON_FIELD_DEFAULT);
@@ -181,8 +181,8 @@ class SortedintMetadata : public Metadata {
class ListMetadata : public Metadata {
public:
- uint64_t head;
- uint64_t tail;
+ uint64_t head_;
+ uint64_t tail_;
explicit ListMetadata(bool generate_version = true);
void Encode(std::string *dst) override;
@@ -191,12 +191,12 @@ class ListMetadata : public Metadata {
class StreamMetadata : public Metadata {
public:
- Redis::StreamEntryID last_generated_id;
- Redis::StreamEntryID recorded_first_entry_id;
- Redis::StreamEntryID max_deleted_entry_id;
- Redis::StreamEntryID first_entry_id;
- Redis::StreamEntryID last_entry_id;
- uint64_t entries_added = 0;
+ Redis::StreamEntryID last_generated_id_;
+ Redis::StreamEntryID recorded_first_entry_id_;
+ Redis::StreamEntryID max_deleted_entry_id_;
+ Redis::StreamEntryID first_entry_id_;
+ Redis::StreamEntryID last_entry_id_;
+ uint64_t entries_added_ = 0;
explicit StreamMetadata(bool generate_version = true) : Metadata(kRedisStream, generate_version) {}
diff --git a/src/storage/scripting.cc b/src/storage/scripting.cc
index 06cce2ad..d7a23c29 100644
--- a/src/storage/scripting.cc
+++ b/src/storage/scripting.cc
@@ -330,22 +330,22 @@ int redisGenericCommand(lua_State *lua, int raise_error) {
}
auto redis_cmd = cmd_iter->second;
- if (read_only && !(redis_cmd->flags & Redis::kCmdReadOnly)) {
+ if (read_only && !(redis_cmd->flags_ & Redis::kCmdReadOnly)) {
pushError(lua, "Write commands are not allowed from read-only scripts");
return raise_error ? raiseError(lua) : 1;
}
- auto cmd = redis_cmd->factory();
+ auto cmd = redis_cmd->factory_();
cmd->SetAttributes(redis_cmd);
cmd->SetArgs(args);
- int arity = cmd->GetAttributes()->arity;
+ int arity = cmd->GetAttributes()->arity_;
if (((arity > 0 && argc != arity) || (arity < 0 && argc < -arity))) {
pushError(lua, "Wrong number of args calling Redis command From Lua script");
return raise_error ? raiseError(lua) : 1;
}
auto attributes = cmd->GetAttributes();
- if (attributes->flags & Redis::kCmdNoScript) {
+ if (attributes->flags_ & Redis::kCmdNoScript) {
pushError(lua, "This Redis command is not allowed from scripts");
return raise_error ? raiseError(lua) : 1;
}
@@ -355,7 +355,7 @@ int redisGenericCommand(lua_State *lua, int raise_error) {
Config *config = srv->GetConfig();
Redis::Connection *conn = srv->GetCurrentConnection();
- if (config->cluster_enabled) {
+ if (config->cluster_enabled_) {
auto s = srv->cluster_->CanExecByMySelf(attributes, args, conn);
if (!s.IsOK()) {
pushError(lua, s.Msg().c_str());
@@ -363,12 +363,12 @@ int redisGenericCommand(lua_State *lua, int raise_error) {
}
}
- if (config->slave_readonly && srv->IsSlave() && attributes->is_write()) {
+ if (config->slave_readonly_ && srv->IsSlave() && attributes->is_write()) {
pushError(lua, "READONLY You can't write against a read only slave.");
return raise_error ? raiseError(lua) : 1;
}
- if (!config->slave_serve_stale_data && srv->IsSlave() && cmd_name != "info" && cmd_name != "slaveof" &&
+ if (!config->slave_serve_stale_data_ && srv->IsSlave() && cmd_name != "info" && cmd_name != "slaveof" &&
srv->GetReplicationState() != kReplConnected) {
pushError(lua,
"MASTERDOWN Link with MASTER is down "
diff --git a/src/storage/storage.cc b/src/storage/storage.cc
index 6e5c5714..aa8db691 100644
--- a/src/storage/storage.cc
+++ b/src/storage/storage.cc
@@ -58,7 +58,7 @@ using rocksdb::Slice;
Storage::Storage(Config *config)
: backup_creating_time_(Util::GetTimeStamp()), env_(rocksdb::Env::Default()), config_(config), lock_mgr_(16) {
Metadata::InitVersionCounter();
- SetWriteOptions(config->RocksDB.write_options);
+ SetWriteOptions(config->rocks_db_.write_options_);
}
Storage::~Storage() {
@@ -79,16 +79,16 @@ void Storage::CloseDB() {
}
void Storage::SetWriteOptions(const Config::RocksDB::WriteOptions &config) {
- write_opts_.sync = config.sync;
- write_opts_.disableWAL = config.disable_WAL;
- write_opts_.no_slowdown = config.no_slowdown;
- write_opts_.low_pri = config.low_pri;
- write_opts_.memtable_insert_hint_per_batch = config.memtable_insert_hint_per_batch;
+ write_opts_.sync = config.sync_;
+ write_opts_.disableWAL = config.disable_wal_;
+ write_opts_.no_slowdown = config.no_slowdown_;
+ write_opts_.low_pri = config.low_pri_;
+ write_opts_.memtable_insert_hint_per_batch = config.memtable_insert_hint_per_batch_;
}
void Storage::SetReadOptions(rocksdb::ReadOptions &read_options) {
read_options.fill_cache = false;
- read_options.async_io = config_->RocksDB.read_options.async_io;
+ read_options.async_io = config_->rocks_db_.read_options_.async_io_;
}
rocksdb::BlockBasedTableOptions Storage::InitTableOptions() {
@@ -101,18 +101,18 @@ rocksdb::BlockBasedTableOptions Storage::InitTableOptions() {
table_options.metadata_block_size = 4096;
table_options.data_block_index_type = rocksdb::BlockBasedTableOptions::DataBlockIndexType::kDataBlockBinaryAndHash;
table_options.data_block_hash_table_util_ratio = 0.75;
- table_options.block_size = static_cast<size_t>(config_->RocksDB.block_size);
+ table_options.block_size = static_cast<size_t>(config_->rocks_db_.block_size_);
return table_options;
}
void Storage::SetBlobDB(rocksdb::ColumnFamilyOptions *cf_options) {
- cf_options->enable_blob_files = config_->RocksDB.enable_blob_files;
- cf_options->min_blob_size = config_->RocksDB.min_blob_size;
- cf_options->blob_file_size = config_->RocksDB.blob_file_size;
- cf_options->blob_compression_type = static_cast<rocksdb::CompressionType>(config_->RocksDB.compression);
- cf_options->enable_blob_garbage_collection = config_->RocksDB.enable_blob_garbage_collection;
+ cf_options->enable_blob_files = config_->rocks_db_.enable_blob_files_;
+ cf_options->min_blob_size = config_->rocks_db_.min_blob_size_;
+ cf_options->blob_file_size = config_->rocks_db_.blob_file_size_;
+ cf_options->blob_compression_type = static_cast<rocksdb::CompressionType>(config_->rocks_db_.compression_);
+ cf_options->enable_blob_garbage_collection = config_->rocks_db_.enable_blob_garbage_collection_;
// Use 100.0 to force converting blob_garbage_collection_age_cutoff to double
- cf_options->blob_garbage_collection_age_cutoff = config_->RocksDB.blob_garbage_collection_age_cutoff / 100.0;
+ cf_options->blob_garbage_collection_age_cutoff = config_->rocks_db_.blob_garbage_collection_age_cutoff_ / 100.0;
}
rocksdb::Options Storage::InitRocksDBOptions() {
@@ -123,15 +123,15 @@ rocksdb::Options Storage::InitRocksDBOptions() {
// NOTE: the overhead of statistics is 5%-10%, so it should be configurable in prod env
// See: https://github.com/facebook/rocksdb/wiki/Statistics
options.statistics = rocksdb::CreateDBStatistics();
- options.stats_dump_period_sec = config_->RocksDB.stats_dump_period_sec;
- options.max_open_files = config_->RocksDB.max_open_files;
+ options.stats_dump_period_sec = config_->rocks_db_.stats_dump_period_sec_;
+ options.max_open_files = config_->rocks_db_.max_open_files_;
options.compaction_style = rocksdb::CompactionStyle::kCompactionStyleLevel;
- options.max_subcompactions = static_cast<uint32_t>(config_->RocksDB.max_sub_compactions);
- options.max_background_flushes = config_->RocksDB.max_background_flushes;
- options.max_background_compactions = config_->RocksDB.max_background_compactions;
- options.max_write_buffer_number = config_->RocksDB.max_write_buffer_number;
+ options.max_subcompactions = static_cast<uint32_t>(config_->rocks_db_.max_sub_compactions_);
+ options.max_background_flushes = config_->rocks_db_.max_background_flushes_;
+ options.max_background_compactions = config_->rocks_db_.max_background_compactions_;
+ options.max_write_buffer_number = config_->rocks_db_.max_write_buffer_number_;
options.min_write_buffer_number_to_merge = 2;
- options.write_buffer_size = config_->RocksDB.write_buffer_size * MiB;
+ options.write_buffer_size = config_->rocks_db_.write_buffer_size_ * MiB;
options.num_levels = 7;
options.compression_per_level.resize(options.num_levels);
// only compress levels >= 2
@@ -139,38 +139,38 @@ rocksdb::Options Storage::InitRocksDBOptions() {
if (i < 2) {
options.compression_per_level[i] = rocksdb::CompressionType::kNoCompression;
} else {
- options.compression_per_level[i] = static_cast<rocksdb::CompressionType>(config_->RocksDB.compression);
+ options.compression_per_level[i] = static_cast<rocksdb::CompressionType>(config_->rocks_db_.compression_);
}
}
- if (config_->RocksDB.row_cache_size) {
- options.row_cache = rocksdb::NewLRUCache(config_->RocksDB.row_cache_size * MiB);
+ if (config_->rocks_db_.row_cache_size_) {
+ options.row_cache = rocksdb::NewLRUCache(config_->rocks_db_.row_cache_size_ * MiB);
}
- options.enable_pipelined_write = config_->RocksDB.enable_pipelined_write;
- options.target_file_size_base = config_->RocksDB.target_file_size_base * MiB;
+ options.enable_pipelined_write = config_->rocks_db_.enable_pipelined_write_;
+ options.target_file_size_base = config_->rocks_db_.target_file_size_base_ * MiB;
options.max_manifest_file_size = 64 * MiB;
options.max_log_file_size = 256 * MiB;
options.keep_log_file_num = 12;
- options.WAL_ttl_seconds = static_cast<uint64_t>(config_->RocksDB.WAL_ttl_seconds);
- options.WAL_size_limit_MB = static_cast<uint64_t>(config_->RocksDB.WAL_size_limit_MB);
- options.max_total_wal_size = static_cast<uint64_t>(config_->RocksDB.max_total_wal_size * MiB);
+ options.WAL_ttl_seconds = static_cast<uint64_t>(config_->rocks_db_.wal_ttl_seconds_);
+ options.WAL_size_limit_MB = static_cast<uint64_t>(config_->rocks_db_.wal_size_limit_mb_);
+ options.max_total_wal_size = static_cast<uint64_t>(config_->rocks_db_.max_total_wal_size_ * MiB);
options.listeners.emplace_back(new EventListener(this));
options.dump_malloc_stats = true;
sst_file_manager_ = std::shared_ptr<rocksdb::SstFileManager>(rocksdb::NewSstFileManager(rocksdb::Env::Default()));
options.sst_file_manager = sst_file_manager_;
int64_t max_io_mb = kIORateLimitMaxMb;
- if (config_->max_io_mb > 0) max_io_mb = config_->max_io_mb;
+ if (config_->max_io_mb_ > 0) max_io_mb = config_->max_io_mb_;
rate_limiter_ =
std::shared_ptr<rocksdb::RateLimiter>(rocksdb::NewGenericRateLimiter(max_io_mb * static_cast<int64_t>(MiB)));
options.rate_limiter = rate_limiter_;
- options.delayed_write_rate = static_cast<uint64_t>(config_->RocksDB.delayed_write_rate);
- options.compaction_readahead_size = static_cast<size_t>(config_->RocksDB.compaction_readahead_size);
- options.level0_slowdown_writes_trigger = config_->RocksDB.level0_slowdown_writes_trigger;
- options.level0_stop_writes_trigger = config_->RocksDB.level0_stop_writes_trigger;
- options.level0_file_num_compaction_trigger = config_->RocksDB.level0_file_num_compaction_trigger;
- options.max_bytes_for_level_base = config_->RocksDB.max_bytes_for_level_base;
- options.max_bytes_for_level_multiplier = config_->RocksDB.max_bytes_for_level_multiplier;
- options.level_compaction_dynamic_level_bytes = config_->RocksDB.level_compaction_dynamic_level_bytes;
- options.max_background_jobs = config_->RocksDB.max_background_jobs;
+ options.delayed_write_rate = static_cast<uint64_t>(config_->rocks_db_.delayed_write_rate_);
+ options.compaction_readahead_size = static_cast<size_t>(config_->rocks_db_.compaction_readahead_size_);
+ options.level0_slowdown_writes_trigger = config_->rocks_db_.level0_slowdown_writes_trigger_;
+ options.level0_stop_writes_trigger = config_->rocks_db_.level0_stop_writes_trigger_;
+ options.level0_file_num_compaction_trigger = config_->rocks_db_.level0_file_num_compaction_trigger_;
+ options.max_bytes_for_level_base = config_->rocks_db_.max_bytes_for_level_base_;
+ options.max_bytes_for_level_multiplier = config_->rocks_db_.max_bytes_for_level_multiplier_;
+ options.level_compaction_dynamic_level_bytes = config_->rocks_db_.level_compaction_dynamic_level_bytes_;
+ options.max_background_jobs = config_->rocks_db_.max_background_jobs_;
return options;
}
@@ -198,7 +198,7 @@ Status Storage::SetDBOption(const std::string &key, const std::string &value) {
Status Storage::CreateColumnFamilies(const rocksdb::Options &options) {
rocksdb::DB *tmp_db = nullptr;
rocksdb::ColumnFamilyOptions cf_options(options);
- rocksdb::Status s = rocksdb::DB::Open(options, config_->db_dir, &tmp_db);
+ rocksdb::Status s = rocksdb::DB::Open(options, config_->db_dir_, &tmp_db);
if (s.ok()) {
std::vector<std::string> cf_names = {kMetadataColumnFamilyName, kZSetScoreColumnFamilyName, kPubSubColumnFamilyName,
kPropagateColumnFamilyName, kStreamColumnFamilyName};
@@ -235,9 +235,9 @@ Status Storage::Open(bool read_only) {
auto guard = WriteLockGuard();
db_closing_ = false;
- bool cache_index_and_filter_blocks = config_->RocksDB.cache_index_and_filter_blocks;
- size_t metadata_block_cache_size = config_->RocksDB.metadata_block_cache_size * MiB;
- size_t subkey_block_cache_size = config_->RocksDB.subkey_block_cache_size * MiB;
+ bool cache_index_and_filter_blocks = config_->rocks_db_.cache_index_and_filter_blocks_;
+ size_t metadata_block_cache_size = config_->rocks_db_.metadata_block_cache_size_ * MiB;
+ size_t subkey_block_cache_size = config_->rocks_db_.subkey_block_cache_size_ * MiB;
rocksdb::Options options = InitRocksDBOptions();
if (auto s = CreateColumnFamilies(options); !s.IsOK()) {
@@ -245,7 +245,7 @@ Status Storage::Open(bool read_only) {
}
std::shared_ptr<rocksdb::Cache> shared_block_cache;
- if (config_->RocksDB.share_metadata_and_subkey_block_cache) {
+ if (config_->rocks_db_.share_metadata_and_subkey_block_cache_) {
size_t shared_block_cache_size = metadata_block_cache_size + subkey_block_cache_size;
shared_block_cache = rocksdb::NewLRUCache(shared_block_cache_size, -1, false, 0.75);
}
@@ -260,7 +260,7 @@ Status Storage::Open(bool read_only) {
rocksdb::ColumnFamilyOptions metadata_opts(options);
metadata_opts.table_factory.reset(rocksdb::NewBlockBasedTableFactory(metadata_table_opts));
metadata_opts.compaction_filter_factory = std::make_shared<MetadataFilterFactory>(this);
- metadata_opts.disable_auto_compactions = config_->RocksDB.disable_auto_compactions;
+ metadata_opts.disable_auto_compactions = config_->rocks_db_.disable_auto_compactions_;
// Enable whole key bloom filter in memtable
metadata_opts.memtable_whole_key_filtering = true;
metadata_opts.memtable_prefix_bloom_size_ratio = 0.1;
@@ -277,7 +277,7 @@ Status Storage::Open(bool read_only) {
rocksdb::ColumnFamilyOptions subkey_opts(options);
subkey_opts.table_factory.reset(rocksdb::NewBlockBasedTableFactory(subkey_table_opts));
subkey_opts.compaction_filter_factory = std::make_shared<SubKeyFilterFactory>(this);
- subkey_opts.disable_auto_compactions = config_->RocksDB.disable_auto_compactions;
+ subkey_opts.disable_auto_compactions = config_->rocks_db_.disable_auto_compactions_;
subkey_opts.table_properties_collector_factories.emplace_back(
NewCompactOnExpiredTableCollectorFactory(kSubkeyColumnFamilyName, 0.3));
SetBlobDB(&subkey_opts);
@@ -286,14 +286,14 @@ Status Storage::Open(bool read_only) {
rocksdb::ColumnFamilyOptions pubsub_opts(options);
pubsub_opts.table_factory.reset(rocksdb::NewBlockBasedTableFactory(pubsub_table_opts));
pubsub_opts.compaction_filter_factory = std::make_shared<PubSubFilterFactory>();
- pubsub_opts.disable_auto_compactions = config_->RocksDB.disable_auto_compactions;
+ pubsub_opts.disable_auto_compactions = config_->rocks_db_.disable_auto_compactions_;
SetBlobDB(&pubsub_opts);
rocksdb::BlockBasedTableOptions propagate_table_opts = InitTableOptions();
rocksdb::ColumnFamilyOptions propagate_opts(options);
propagate_opts.table_factory.reset(rocksdb::NewBlockBasedTableFactory(propagate_table_opts));
propagate_opts.compaction_filter_factory = std::make_shared<PropagateFilterFactory>();
- propagate_opts.disable_auto_compactions = config_->RocksDB.disable_auto_compactions;
+ propagate_opts.disable_auto_compactions = config_->rocks_db_.disable_auto_compactions_;
SetBlobDB(&propagate_opts);
std::vector<rocksdb::ColumnFamilyDescriptor> column_families;
@@ -306,14 +306,14 @@ Status Storage::Open(bool read_only) {
column_families.emplace_back(kStreamColumnFamilyName, subkey_opts);
std::vector<std::string> old_column_families;
- auto s = rocksdb::DB::ListColumnFamilies(options, config_->db_dir, &old_column_families);
+ auto s = rocksdb::DB::ListColumnFamilies(options, config_->db_dir_, &old_column_families);
if (!s.ok()) return {Status::NotOK, s.ToString()};
auto start = std::chrono::high_resolution_clock::now();
if (read_only) {
- s = rocksdb::DB::OpenForReadOnly(options, config_->db_dir, column_families, &cf_handles_, &db_);
+ s = rocksdb::DB::OpenForReadOnly(options, config_->db_dir_, column_families, &cf_handles_, &db_);
} else {
- s = rocksdb::DB::Open(options, config_->db_dir, column_families, &cf_handles_, &db_);
+ s = rocksdb::DB::Open(options, config_->db_dir_, column_families, &cf_handles_, &db_);
}
auto end = std::chrono::high_resolution_clock::now();
int64_t duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();
@@ -329,7 +329,7 @@ Status Storage::Open(bool read_only) {
Status Storage::CreateBackup() {
LOG(INFO) << "[storage] Start to create new backup";
std::lock_guard<std::mutex> lg(config_->backup_mu_);
- std::string task_backup_dir = config_->backup_dir;
+ std::string task_backup_dir = config_->backup_dir_;
std::string tmpdir = task_backup_dir + ".tmp";
// Maybe there is a dirty tmp checkpoint, try to clean it
@@ -344,7 +344,7 @@ Status Storage::CreateBackup() {
}
std::unique_ptr<rocksdb::Checkpoint> checkpoint_guard(checkpoint);
- s = checkpoint->CreateCheckpoint(tmpdir, config_->RocksDB.write_buffer_size * MiB);
+ s = checkpoint->CreateCheckpoint(tmpdir, config_->rocks_db_.write_buffer_size_ * MiB);
if (!s.ok()) {
LOG(WARNING) << "Failed to create checkpoint (snapshot) for backup. Error: " << s.ToString();
return {Status::DBBackupErr, s.ToString()};
@@ -385,11 +385,11 @@ void Storage::DestroyBackup() {
Status Storage::RestoreFromBackup() {
// TODO(@ruoshan): assert role to be slave
// We must reopen the backup engine every time, as the files is changed
- rocksdb::BackupEngineOptions bk_option(config_->backup_sync_dir);
+ rocksdb::BackupEngineOptions bk_option(config_->backup_sync_dir_);
auto s = rocksdb::BackupEngine::Open(db_->GetEnv(), bk_option, &backup_);
if (!s.ok()) return {Status::DBBackupErr, s.ToString()};
- s = backup_->RestoreDBFromLatestBackup(config_->db_dir, config_->db_dir);
+ s = backup_->RestoreDBFromLatestBackup(config_->db_dir_, config_->db_dir_);
if (!s.ok()) {
LOG(ERROR) << "[storage] Failed to restore database from the latest backup. Error: " << s.ToString();
} else {
@@ -411,47 +411,47 @@ Status Storage::RestoreFromBackup() {
}
Status Storage::RestoreFromCheckpoint() {
- std::string checkpoint_dir = config_->sync_checkpoint_dir;
- std::string tmp_dir = config_->db_dir + ".tmp";
+ std::string checkpoint_dir = config_->sync_checkpoint_dir_;
+ std::string tmp_dir = config_->db_dir_ + ".tmp";
// Clean old backups and checkpoints because server will work on the new db
PurgeOldBackups(0, 0);
- rocksdb::DestroyDB(config_->checkpoint_dir, rocksdb::Options());
+ rocksdb::DestroyDB(config_->checkpoint_dir_, rocksdb::Options());
// Maybe there is no database directory
- auto s = env_->CreateDirIfMissing(config_->db_dir);
+ auto s = env_->CreateDirIfMissing(config_->db_dir_);
if (!s.ok()) {
return {Status::NotOK,
- fmt::format("Failed to create database directory '{}'. Error: {}", config_->db_dir, s.ToString())};
+ fmt::format("Failed to create database directory '{}'. Error: {}", config_->db_dir_, s.ToString())};
}
// Rename database directory to tmp, so we can restore if replica fails to load the checkpoint from master.
// But only try best effort to make data safe
- s = env_->RenameFile(config_->db_dir, tmp_dir);
+ s = env_->RenameFile(config_->db_dir_, tmp_dir);
if (!s.ok()) {
if (auto s1 = Open(); !s1.IsOK()) {
LOG(ERROR) << "[storage] Failed to reopen database. Error: " << s1.Msg();
}
- return {Status::NotOK, fmt::format("Failed to rename database directory '{}' to '{}'. Error: {}", config_->db_dir,
+ return {Status::NotOK, fmt::format("Failed to rename database directory '{}' to '{}'. Error: {}", config_->db_dir_,
tmp_dir, s.ToString())};
}
// Rename checkpoint directory to database directory
- if (s = env_->RenameFile(checkpoint_dir, config_->db_dir); !s.ok()) {
- env_->RenameFile(tmp_dir, config_->db_dir);
+ if (s = env_->RenameFile(checkpoint_dir, config_->db_dir_); !s.ok()) {
+ env_->RenameFile(tmp_dir, config_->db_dir_);
if (auto s1 = Open(); !s1.IsOK()) {
LOG(ERROR) << "[storage] Failed to reopen database. Error: " << s1.Msg();
}
return {Status::NotOK, fmt::format("Failed to rename checkpoint directory '{}' to '{}'. Error: {}", checkpoint_dir,
- config_->db_dir, s.ToString())};
+ config_->db_dir_, s.ToString())};
}
// Open the new database, restore if replica fails to open
auto s2 = Open();
if (!s2.IsOK()) {
LOG(WARNING) << "[storage] Failed to open master checkpoint. Error: " << s2.Msg();
- rocksdb::DestroyDB(config_->db_dir, rocksdb::Options());
- env_->RenameFile(tmp_dir, config_->db_dir);
+ rocksdb::DestroyDB(config_->db_dir_, rocksdb::Options());
+ env_->RenameFile(tmp_dir, config_->db_dir_);
if (auto s1 = Open(); !s1.IsOK()) {
LOG(ERROR) << "[storage] Failed to reopen database. Error: " << s1.Msg();
}
@@ -468,9 +468,9 @@ Status Storage::RestoreFromCheckpoint() {
void Storage::EmptyDB() {
// Clean old backups and checkpoints
PurgeOldBackups(0, 0);
- rocksdb::DestroyDB(config_->checkpoint_dir, rocksdb::Options());
+ rocksdb::DestroyDB(config_->checkpoint_dir_, rocksdb::Options());
- auto s = rocksdb::DestroyDB(config_->db_dir, rocksdb::Options());
+ auto s = rocksdb::DestroyDB(config_->db_dir_, rocksdb::Options());
if (!s.ok()) {
LOG(ERROR) << "[storage] Failed to destroy database. Error: " << s.ToString();
}
@@ -479,7 +479,7 @@ void Storage::EmptyDB() {
void Storage::PurgeOldBackups(uint32_t num_backups_to_keep, uint32_t backup_max_keep_hours) {
time_t now = Util::GetTimeStamp();
std::lock_guard<std::mutex> lg(config_->backup_mu_);
- std::string task_backup_dir = config_->backup_dir;
+ std::string task_backup_dir = config_->backup_dir_;
// Return if there is no backup
auto s = env_->FileExists(task_backup_dir);
@@ -673,8 +673,8 @@ uint64_t Storage::GetTotalSize(const std::string &ns) {
void Storage::CheckDBSizeLimit() {
bool limit_reached = false;
- if (config_->max_db_size > 0) {
- limit_reached = GetTotalSize() >= config_->max_db_size * GiB;
+ if (config_->max_db_size_ > 0) {
+ limit_reached = GetTotalSize() >= config_->max_db_size_ * GiB;
}
if (db_size_limit_reached_ == limit_reached) {
@@ -683,7 +683,7 @@ void Storage::CheckDBSizeLimit() {
db_size_limit_reached_ = limit_reached;
if (db_size_limit_reached_) {
- LOG(WARNING) << "[storage] ENABLE db_size limit " << config_->max_db_size << " GB."
+ LOG(WARNING) << "[storage] ENABLE db_size limit " << config_->max_db_size_ << " GB."
<< "Switch kvrocks to read-only mode.";
} else {
LOG(WARNING) << "[storage] DISABLE db_size limit. Switch kvrocks to read-write mode.";
@@ -748,7 +748,7 @@ Status Storage::ShiftReplId() {
const int charset_len = static_cast<int>(strlen(charset));
// Do nothing if rsid psync is not enabled
- if (!config_->use_rsid_psync) return Status::OK();
+ if (!config_->use_rsid_psync_) return Status::OK();
std::random_device rd;
std::mt19937 gen(rd() + getpid());
@@ -824,7 +824,7 @@ Status Storage::ReplDataManager::GetFullReplDataInfo(Storage *storage, std::stri
auto guard = storage->ReadLockGuard();
if (storage->IsClosing()) return {Status::NotOK, "DB is closing"};
- std::string data_files_dir = storage->config_->checkpoint_dir;
+ std::string data_files_dir = storage->config_->checkpoint_dir_;
std::unique_lock<std::mutex> ulm(storage->checkpoint_mu_);
// Create checkpoint if not exist
@@ -840,12 +840,12 @@ Status Storage::ReplDataManager::GetFullReplDataInfo(Storage *storage, std::stri
// Create checkpoint of rocksdb
uint64_t checkpoint_latest_seq = 0;
- s = checkpoint->CreateCheckpoint(data_files_dir, storage->config_->RocksDB.write_buffer_size * MiB,
+ s = checkpoint->CreateCheckpoint(data_files_dir, storage->config_->rocks_db_.write_buffer_size_ * MiB,
&checkpoint_latest_seq);
auto now = static_cast<time_t>(Util::GetTimeStamp());
- storage->checkpoint_info_.create_time = now;
- storage->checkpoint_info_.access_time = now;
- storage->checkpoint_info_.latest_seq = checkpoint_latest_seq;
+ storage->checkpoint_info_.create_time_ = now;
+ storage->checkpoint_info_.access_time_ = now;
+ storage->checkpoint_info_.latest_seq_ = checkpoint_latest_seq;
if (!s.ok()) {
LOG(WARNING) << "[storage] Failed to create checkpoint (snapshot). Error: " << s.ToString();
return {Status::NotOK, s.ToString()};
@@ -854,7 +854,7 @@ Status Storage::ReplDataManager::GetFullReplDataInfo(Storage *storage, std::stri
LOG(INFO) << "[storage] Create checkpoint successfully";
} else {
// Replicas can share checkpoint to replication if the checkpoint existing time is less than a half of WAL TTL.
- int64_t can_shared_time = storage->config_->RocksDB.WAL_ttl_seconds / 2;
+ int64_t can_shared_time = storage->config_->rocks_db_.wal_ttl_seconds_ / 2;
if (can_shared_time > 60 * 60) can_shared_time = 60 * 60;
if (can_shared_time < 10 * 60) can_shared_time = 10 * 60;
@@ -866,7 +866,7 @@ Status Storage::ReplDataManager::GetFullReplDataInfo(Storage *storage, std::stri
// Should not use current checkpoint if its latest sequence was out of the WAL boundary,
// or the slave will fall into the full sync loop since it won't create new checkpoint.
- auto s = storage->InWALBoundary(storage->checkpoint_info_.latest_seq);
+ auto s = storage->InWALBoundary(storage->checkpoint_info_.latest_seq_);
if (!s.IsOK()) {
LOG(WARNING) << "[storage] Can't use current checkpoint, error: " << s.Msg();
return {Status::NotOK, fmt::format("Can't use current checkpoint, error: {}", s.Msg())};
@@ -892,10 +892,10 @@ Status Storage::ReplDataManager::GetFullReplDataInfo(Storage *storage, std::stri
bool Storage::ExistCheckpoint() {
std::lock_guard<std::mutex> lg(checkpoint_mu_);
- return env_->FileExists(config_->checkpoint_dir).ok();
+ return env_->FileExists(config_->checkpoint_dir_).ok();
}
-bool Storage::ExistSyncCheckpoint() { return env_->FileExists(config_->sync_checkpoint_dir).ok(); }
+bool Storage::ExistSyncCheckpoint() { return env_->FileExists(config_->sync_checkpoint_dir_).ok(); }
Status Storage::InWALBoundary(rocksdb::SequenceNumber seq) {
std::unique_ptr<rocksdb::TransactionLogIterator> iter;
@@ -944,7 +944,7 @@ Status Storage::ReplDataManager::CleanInvalidFiles(Storage *storage, const std::
}
int Storage::ReplDataManager::OpenDataFile(Storage *storage, const std::string &repl_file, uint64_t *file_size) {
- std::string abs_path = storage->config_->checkpoint_dir + "/" + repl_file;
+ std::string abs_path = storage->config_->checkpoint_dir_ + "/" + repl_file;
auto s = storage->env_->FileExists(abs_path);
if (!s.ok()) {
LOG(ERROR) << "[storage] Data file [" << abs_path << "] not found";
@@ -966,7 +966,7 @@ Status Storage::ReplDataManager::ParseMetaAndSave(Storage *storage, rocksdb::Bac
DLOG(INFO) << "[meta] id: " << meta_id;
// Save the meta to tmp file
- auto wf = NewTmpFile(storage, storage->config_->backup_sync_dir, meta_file);
+ auto wf = NewTmpFile(storage, storage->config_->backup_sync_dir_, meta_file);
auto data = evbuffer_pullup(evbuf, -1);
wf->Append(rocksdb::Slice(reinterpret_cast<char *>(data), evbuffer_get_length(evbuf)));
wf->Close();
@@ -974,16 +974,16 @@ Status Storage::ReplDataManager::ParseMetaAndSave(Storage *storage, rocksdb::Bac
// timestamp;
UniqueEvbufReadln line(evbuf, EVBUFFER_EOL_LF);
DLOG(INFO) << "[meta] timestamp: " << line.get();
- meta->timestamp = std::strtoll(line.get(), nullptr, 10);
+ meta->timestamp_ = std::strtoll(line.get(), nullptr, 10);
// sequence
line = UniqueEvbufReadln(evbuf, EVBUFFER_EOL_LF);
DLOG(INFO) << "[meta] seq:" << line.get();
- meta->seq = std::strtoull(line.get(), nullptr, 10);
+ meta->seq_ = std::strtoull(line.get(), nullptr, 10);
// optional metadata
line = UniqueEvbufReadln(evbuf, EVBUFFER_EOL_LF);
if (strncmp(line.get(), "metadata", 8) == 0) {
DLOG(INFO) << "[meta] meta: " << line.get();
- meta->meta_data = std::string(line.get(), line.length);
+ meta->meta_data_ = std::string(line.get(), line.length_);
line = UniqueEvbufReadln(evbuf, EVBUFFER_EOL_LF);
}
DLOG(INFO) << "[meta] file count: " << line.get();
@@ -1004,10 +1004,10 @@ Status Storage::ReplDataManager::ParseMetaAndSave(Storage *storage, rocksdb::Bac
}
auto crc32 = std::strtoul(cptr, nullptr, 10);
- meta->files.emplace_back(filename, crc32);
+ meta->files_.emplace_back(filename, crc32);
}
- return SwapTmpFile(storage, storage->config_->backup_sync_dir, meta_file);
+ return SwapTmpFile(storage, storage->config_->backup_sync_dir_, meta_file);
}
Status MkdirRecursively(rocksdb::Env *env, const std::string &dir) {
diff --git a/src/storage/storage.h b/src/storage/storage.h
index ca953f87..fddb1016 100644
--- a/src/storage/storage.h
+++ b/src/storage/storage.h
@@ -110,7 +110,7 @@ class Storage {
rocksdb::Status Compact(const rocksdb::Slice *begin, const rocksdb::Slice *end);
rocksdb::DB *GetDB();
bool IsClosing() const { return db_closing_; }
- std::string GetName() { return config_->db_name; }
+ std::string GetName() { return config_->db_name_; }
rocksdb::ColumnFamilyHandle *GetCFHandle(const std::string &name);
std::vector<rocksdb::ColumnFamilyHandle *> *GetCFHandles() { return &cf_handles_; }
LockManager *GetLockManager() { return &lock_mgr_; }
@@ -126,7 +126,7 @@ class Storage {
void IncrFlushCount(uint64_t n) { flush_count_.fetch_add(n); }
uint64_t GetCompactionCount() { return compaction_count_; }
void IncrCompactionCount(uint64_t n) { compaction_count_.fetch_add(n); }
- bool IsSlotIdEncoded() { return config_->slot_id_encoded; }
+ bool IsSlotIdEncoded() { return config_->slot_id_encoded_; }
const Config *GetConfig() { return config_; }
Status BeginTxn();
@@ -144,18 +144,18 @@ class Storage {
static int OpenDataFile(Storage *storage, const std::string &rel_file, uint64_t *file_size);
static Status CleanInvalidFiles(Storage *storage, const std::string &dir, std::vector<std::string> valid_files);
struct CheckpointInfo {
- std::atomic<time_t> create_time = 0;
- std::atomic<time_t> access_time = 0;
- uint64_t latest_seq = 0;
+ std::atomic<time_t> create_time_ = 0;
+ std::atomic<time_t> access_time_ = 0;
+ uint64_t latest_seq_ = 0;
};
// Slave side
struct MetaInfo {
- int64_t timestamp;
- rocksdb::SequenceNumber seq;
- std::string meta_data;
+ int64_t timestamp_;
+ rocksdb::SequenceNumber seq_;
+ std::string meta_data_;
// [[filename, checksum]...]
- std::vector<std::pair<std::string, uint32_t>> files;
+ std::vector<std::pair<std::string, uint32_t>> files_;
};
static Status ParseMetaAndSave(Storage *storage, rocksdb::BackupID meta_id, evbuffer *evbuf,
Storage::ReplDataManager::MetaInfo *meta);
@@ -167,9 +167,9 @@ class Storage {
bool ExistCheckpoint();
bool ExistSyncCheckpoint();
- time_t GetCheckpointCreateTime() { return checkpoint_info_.create_time; }
- void SetCheckpointAccessTime(time_t t) { checkpoint_info_.access_time = t; }
- time_t GetCheckpointAccessTime() { return checkpoint_info_.access_time; }
+ time_t GetCheckpointCreateTime() { return checkpoint_info_.create_time_; }
+ void SetCheckpointAccessTime(time_t t) { checkpoint_info_.access_time_ = t; }
+ time_t GetCheckpointAccessTime() { return checkpoint_info_.access_time_; }
void SetDBInRetryableIOError(bool yes_or_no) { db_in_retryable_io_error_ = yes_or_no; }
bool IsDBInRetryableIOError() { return db_in_retryable_io_error_; }
diff --git a/src/types/geohash.cc b/src/types/geohash.cc
index b5ac26d5..5bef33b1 100644
--- a/src/types/geohash.cc
+++ b/src/types/geohash.cc
@@ -132,10 +132,10 @@ static inline uint64_t deinterleave64(uint64_t interleaved) {
void geohashGetCoordRange(GeoHashRange *long_range, GeoHashRange *lat_range) {
/* These are constraints from EPSG:900913 / EPSG:3785 / OSGEO:41001 */
/* We can't geocode at the north/south pole. */
- long_range->max = GEO_LONG_MAX;
- long_range->min = GEO_LONG_MIN;
- lat_range->max = GEO_LAT_MAX;
- lat_range->min = GEO_LAT_MIN;
+ long_range->max_ = GEO_LONG_MAX;
+ long_range->min_ = GEO_LONG_MIN;
+ lat_range->max_ = GEO_LAT_MAX;
+ lat_range->min_ = GEO_LAT_MIN;
}
int geohashEncode(const GeoHashRange *long_range, const GeoHashRange *lat_range, double longitude, double latitude,
@@ -148,21 +148,21 @@ int geohashEncode(const GeoHashRange *long_range, const GeoHashRange *lat_range,
if (longitude > GEO_LONG_MAX || longitude < GEO_LONG_MIN || latitude > GEO_LAT_MAX || latitude < GEO_LAT_MIN)
return 0;
- hash->bits = 0;
- hash->step = step;
+ hash->bits_ = 0;
+ hash->step_ = step;
- if (latitude < lat_range->min || latitude > lat_range->max || longitude < long_range->min ||
- longitude > long_range->max) {
+ if (latitude < lat_range->min_ || latitude > lat_range->max_ || longitude < long_range->min_ ||
+ longitude > long_range->max_) {
return 0;
}
- double lat_offset = (latitude - lat_range->min) / (lat_range->max - lat_range->min);
- double long_offset = (longitude - long_range->min) / (long_range->max - long_range->min);
+ double lat_offset = (latitude - lat_range->min_) / (lat_range->max_ - lat_range->min_);
+ double long_offset = (longitude - long_range->min_) / (long_range->max_ - long_range->min_);
/* convert to fixed point based on the step size */
lat_offset *= static_cast<double>(1ULL << step);
long_offset *= static_cast<double>(1ULL << step);
- hash->bits = interleave64(static_cast<uint32_t>(lat_offset), static_cast<uint32_t>(long_offset));
+ hash->bits_ = interleave64(static_cast<uint32_t>(lat_offset), static_cast<uint32_t>(long_offset));
return 1;
}
@@ -182,12 +182,12 @@ int geohashDecode(const GeoHashRange &long_range, const GeoHashRange &lat_range,
return 0;
}
- area->hash = hash;
- uint8_t step = hash.step;
- uint64_t hash_sep = deinterleave64(hash.bits); /* hash = [LAT][LONG] */
+ area->hash_ = hash;
+ uint8_t step = hash.step_;
+ uint64_t hash_sep = deinterleave64(hash.bits_); /* hash = [LAT][LONG] */
- double lat_scale = lat_range.max - lat_range.min;
- double long_scale = long_range.max - long_range.min;
+ double lat_scale = lat_range.max_ - lat_range.min_;
+ double long_scale = long_range.max_ - long_range.min_;
uint32_t ilato = hash_sep; /* get lat part of deinterleaved hash */
uint32_t ilono = hash_sep >> 32; /* shift over to get long part of hash */
@@ -195,10 +195,10 @@ int geohashDecode(const GeoHashRange &long_range, const GeoHashRange &lat_range,
/* divide by 2**step.
* Then, for 0-1 coordinate, multiply times scale and add
to the min to get the absolute coordinate. */
- area->latitude.min = lat_range.min + (ilato * 1.0 / static_cast<double>(1ull << step)) * lat_scale;
- area->latitude.max = lat_range.min + ((ilato + 1) * 1.0 / static_cast<double>(1ull << step)) * lat_scale;
- area->longitude.min = long_range.min + (ilono * 1.0 / static_cast<double>(1ull << step)) * long_scale;
- area->longitude.max = long_range.min + ((ilono + 1) * 1.0 / static_cast<double>(1ull << step)) * long_scale;
+ area->latitude_.min_ = lat_range.min_ + (ilato * 1.0 / static_cast<double>(1ull << step)) * lat_scale;
+ area->latitude_.max_ = lat_range.min_ + ((ilato + 1) * 1.0 / static_cast<double>(1ull << step)) * lat_scale;
+ area->longitude_.min_ = long_range.min_ + (ilono * 1.0 / static_cast<double>(1ull << step)) * long_scale;
+ area->longitude_.max_ = long_range.min_ + ((ilono + 1) * 1.0 / static_cast<double>(1ull << step)) * long_scale;
return 1;
}
@@ -213,10 +213,10 @@ int geohashDecodeWGS84(const GeoHashBits &hash, GeoHashArea *area) { return geoh
int geohashDecodeAreaToLongLat(const GeoHashArea *area, double *xy) {
if (!xy) return 0;
- xy[0] = (area->longitude.min + area->longitude.max) / 2;
+ xy[0] = (area->longitude_.min_ + area->longitude_.max_) / 2;
if (xy[0] > GEO_LONG_MAX) xy[0] = GEO_LONG_MAX;
if (xy[0] < GEO_LONG_MIN) xy[0] = GEO_LONG_MIN;
- xy[1] = (area->latitude.min + area->latitude.max) / 2;
+ xy[1] = (area->latitude_.min_ + area->latitude_.max_) / 2;
if (xy[1] > GEO_LAT_MAX) xy[1] = GEO_LAT_MAX;
if (xy[1] < GEO_LAT_MIN) xy[1] = GEO_LAT_MIN;
return 1;
@@ -233,10 +233,10 @@ int geohashDecodeToLongLatWGS84(const GeoHashBits &hash, double *xy) { return ge
static void geohash_move_x(GeoHashBits *hash, int8_t d) {
if (d == 0) return;
- uint64_t x = hash->bits & 0xaaaaaaaaaaaaaaaaULL;
- uint64_t y = hash->bits & 0x5555555555555555ULL;
+ uint64_t x = hash->bits_ & 0xaaaaaaaaaaaaaaaaULL;
+ uint64_t y = hash->bits_ & 0x5555555555555555ULL;
- uint64_t zz = 0x5555555555555555ULL >> (64 - hash->step * 2); // NOLINT
+ uint64_t zz = 0x5555555555555555ULL >> (64 - hash->step_ * 2); // NOLINT
if (d > 0) {
x = x + (zz + 1);
@@ -245,60 +245,60 @@ static void geohash_move_x(GeoHashBits *hash, int8_t d) {
x = x - (zz + 1);
}
- x &= (0xaaaaaaaaaaaaaaaaULL >> (64 - hash->step * 2)); // NOLINT
- hash->bits = (x | y);
+ x &= (0xaaaaaaaaaaaaaaaaULL >> (64 - hash->step_ * 2)); // NOLINT
+ hash->bits_ = (x | y);
}
static void geohash_move_y(GeoHashBits *hash, int8_t d) {
if (d == 0) return;
- uint64_t x = hash->bits & 0xaaaaaaaaaaaaaaaaULL;
- uint64_t y = hash->bits & 0x5555555555555555ULL;
+ uint64_t x = hash->bits_ & 0xaaaaaaaaaaaaaaaaULL;
+ uint64_t y = hash->bits_ & 0x5555555555555555ULL;
- uint64_t zz = 0xaaaaaaaaaaaaaaaaULL >> (64 - hash->step * 2);
+ uint64_t zz = 0xaaaaaaaaaaaaaaaaULL >> (64 - hash->step_ * 2);
if (d > 0) {
y = y + (zz + 1);
} else {
y = y | zz;
y = y - (zz + 1);
}
- y &= (0x5555555555555555ULL >> (64 - hash->step * 2));
- hash->bits = (x | y);
+ y &= (0x5555555555555555ULL >> (64 - hash->step_ * 2));
+ hash->bits_ = (x | y);
}
void geohashNeighbors(const GeoHashBits *hash, GeoHashNeighbors *neighbors) {
- neighbors->east = *hash;
- neighbors->west = *hash;
- neighbors->north = *hash;
- neighbors->south = *hash;
- neighbors->south_east = *hash;
- neighbors->south_west = *hash;
- neighbors->north_east = *hash;
- neighbors->north_west = *hash;
+ neighbors->east_ = *hash;
+ neighbors->west_ = *hash;
+ neighbors->north_ = *hash;
+ neighbors->south_ = *hash;
+ neighbors->south_east_ = *hash;
+ neighbors->south_west_ = *hash;
+ neighbors->north_east_ = *hash;
+ neighbors->north_west_ = *hash;
- geohash_move_x(&neighbors->east, 1);
- geohash_move_y(&neighbors->east, 0);
+ geohash_move_x(&neighbors->east_, 1);
+ geohash_move_y(&neighbors->east_, 0);
- geohash_move_x(&neighbors->west, -1);
- geohash_move_y(&neighbors->west, 0);
+ geohash_move_x(&neighbors->west_, -1);
+ geohash_move_y(&neighbors->west_, 0);
- geohash_move_x(&neighbors->south, 0);
- geohash_move_y(&neighbors->south, -1);
+ geohash_move_x(&neighbors->south_, 0);
+ geohash_move_y(&neighbors->south_, -1);
- geohash_move_x(&neighbors->north, 0);
- geohash_move_y(&neighbors->north, 1);
+ geohash_move_x(&neighbors->north_, 0);
+ geohash_move_y(&neighbors->north_, 1);
- geohash_move_x(&neighbors->north_west, -1);
- geohash_move_y(&neighbors->north_west, 1);
+ geohash_move_x(&neighbors->north_west_, -1);
+ geohash_move_y(&neighbors->north_west_, 1);
- geohash_move_x(&neighbors->north_east, 1);
- geohash_move_y(&neighbors->north_east, 1);
+ geohash_move_x(&neighbors->north_east_, 1);
+ geohash_move_y(&neighbors->north_east_, 1);
- geohash_move_x(&neighbors->south_east, 1);
- geohash_move_y(&neighbors->south_east, -1);
+ geohash_move_x(&neighbors->south_east_, 1);
+ geohash_move_y(&neighbors->south_east_, -1);
- geohash_move_x(&neighbors->south_west, -1);
- geohash_move_y(&neighbors->south_west, -1);
+ geohash_move_x(&neighbors->south_west_, -1);
+ geohash_move_y(&neighbors->south_west_, -1);
}
/* This function is used in order to estimate the step (bits precision)
@@ -387,15 +387,15 @@ GeoHashRadius GeoHashHelper::GetAreasByRadius(double longitude, double latitude,
{
GeoHashArea north, south, east, west;
- geohashDecode(long_range, lat_range, neighbors.north, &north);
- geohashDecode(long_range, lat_range, neighbors.south, &south);
- geohashDecode(long_range, lat_range, neighbors.east, &east);
- geohashDecode(long_range, lat_range, neighbors.west, &west);
+ geohashDecode(long_range, lat_range, neighbors.north_, &north);
+ geohashDecode(long_range, lat_range, neighbors.south_, &south);
+ geohashDecode(long_range, lat_range, neighbors.east_, &east);
+ geohashDecode(long_range, lat_range, neighbors.west_, &west);
- if (GetDistance(longitude, latitude, longitude, north.latitude.max) < radius_meters) decrease_step = 1;
- if (GetDistance(longitude, latitude, longitude, south.latitude.min) < radius_meters) decrease_step = 1;
- if (GetDistance(longitude, latitude, east.longitude.max, latitude) < radius_meters) decrease_step = 1;
- if (GetDistance(longitude, latitude, west.longitude.min, latitude) < radius_meters) decrease_step = 1;
+ if (GetDistance(longitude, latitude, longitude, north.latitude_.max_) < radius_meters) decrease_step = 1;
+ if (GetDistance(longitude, latitude, longitude, south.latitude_.min_) < radius_meters) decrease_step = 1;
+ if (GetDistance(longitude, latitude, east.longitude_.max_, latitude) < radius_meters) decrease_step = 1;
+ if (GetDistance(longitude, latitude, west.longitude_.min_, latitude) < radius_meters) decrease_step = 1;
}
if (steps > 1 && decrease_step) {
@@ -407,30 +407,30 @@ GeoHashRadius GeoHashHelper::GetAreasByRadius(double longitude, double latitude,
/* Exclude the search areas that are useless. */
if (steps >= 2) {
- if (area.latitude.min < min_lat) {
- GZERO(neighbors.south);
- GZERO(neighbors.south_west);
- GZERO(neighbors.south_east);
+ if (area.latitude_.min_ < min_lat) {
+ GZERO(neighbors.south_);
+ GZERO(neighbors.south_west_);
+ GZERO(neighbors.south_east_);
}
- if (area.latitude.max > max_lat) {
- GZERO(neighbors.north);
- GZERO(neighbors.north_east);
- GZERO(neighbors.north_west);
+ if (area.latitude_.max_ > max_lat) {
+ GZERO(neighbors.north_);
+ GZERO(neighbors.north_east_);
+ GZERO(neighbors.north_west_);
}
- if (area.longitude.min < min_lon) {
- GZERO(neighbors.west);
- GZERO(neighbors.south_west);
- GZERO(neighbors.north_west);
+ if (area.longitude_.min_ < min_lon) {
+ GZERO(neighbors.west_);
+ GZERO(neighbors.south_west_);
+ GZERO(neighbors.north_west_);
}
- if (area.longitude.max > max_lon) {
- GZERO(neighbors.east);
- GZERO(neighbors.south_east);
- GZERO(neighbors.north_east);
+ if (area.longitude_.max_ > max_lon) {
+ GZERO(neighbors.east_);
+ GZERO(neighbors.south_east_);
+ GZERO(neighbors.north_east_);
}
}
- radius.hash = hash;
- radius.neighbors = neighbors;
- radius.area = area;
+ radius.hash_ = hash;
+ radius.neighbors_ = neighbors;
+ radius.area_ = area;
return radius;
}
@@ -439,8 +439,8 @@ GeoHashRadius GeoHashHelper::GetAreasByRadiusWGS84(double longitude, double lati
}
GeoHashFix52Bits GeoHashHelper::Align52Bits(const GeoHashBits &hash) {
- uint64_t bits = hash.bits;
- bits <<= (52 - hash.step * 2);
+ uint64_t bits = hash.bits_;
+ bits <<= (52 - hash.step_ * 2);
return bits;
}
diff --git a/src/types/geohash.h b/src/types/geohash.h
index 6c18ae7b..87f7fc83 100644
--- a/src/types/geohash.h
+++ b/src/types/geohash.h
@@ -60,47 +60,47 @@ enum GeoDirection {
};
struct GeoHashBits {
- uint64_t bits = 0;
- uint8_t step = 0;
+ uint64_t bits_ = 0;
+ uint8_t step_ = 0;
};
struct GeoHashRange {
- double min = 0;
- double max = 0;
+ double min_ = 0;
+ double max_ = 0;
};
struct GeoHashArea {
- GeoHashBits hash;
- GeoHashRange longitude;
- GeoHashRange latitude;
+ GeoHashBits hash_;
+ GeoHashRange longitude_;
+ GeoHashRange latitude_;
};
struct GeoHashNeighbors {
- GeoHashBits north;
- GeoHashBits east;
- GeoHashBits west;
- GeoHashBits south;
- GeoHashBits north_east;
- GeoHashBits south_east;
- GeoHashBits north_west;
- GeoHashBits south_west;
+ GeoHashBits north_;
+ GeoHashBits east_;
+ GeoHashBits west_;
+ GeoHashBits south_;
+ GeoHashBits north_east_;
+ GeoHashBits south_east_;
+ GeoHashBits north_west_;
+ GeoHashBits south_west_;
};
using GeoHashFix52Bits = uint64_t;
struct GeoHashRadius {
- GeoHashBits hash;
- GeoHashArea area;
- GeoHashNeighbors neighbors;
+ GeoHashBits hash_;
+ GeoHashArea area_;
+ GeoHashNeighbors neighbors_;
};
-inline constexpr bool HASHISZERO(const GeoHashBits &r) { return !r.bits && !r.step; }
-inline constexpr bool RANGEISZERO(const GeoHashRange &r) { return !bool(r.max) && !bool(r.min); }
+inline constexpr bool HASHISZERO(const GeoHashBits &r) { return !r.bits_ && !r.step_; }
+inline constexpr bool RANGEISZERO(const GeoHashRange &r) { return !bool(r.max_) && !bool(r.min_); }
inline constexpr bool RANGEPISZERO(const GeoHashRange *r) { return !r || RANGEISZERO(*r); }
-inline constexpr void GZERO(GeoHashBits &s) { s.bits = s.step = 0; }
-inline constexpr bool GISZERO(const GeoHashBits &s) { return (!s.bits && !s.step); }
-inline constexpr bool GISNOTZERO(const GeoHashBits &s) { return (s.bits || s.step); }
+inline constexpr void GZERO(GeoHashBits &s) { s.bits_ = s.step_ = 0; }
+inline constexpr bool GISZERO(const GeoHashBits &s) { return (!s.bits_ && !s.step_); }
+inline constexpr bool GISNOTZERO(const GeoHashBits &s) { return (s.bits_ || s.step_); }
/*
* 0:success
diff --git a/src/types/redis_bitmap.cc b/src/types/redis_bitmap.cc
index 8684ac54..0ed31b05 100644
--- a/src/types/redis_bitmap.cc
+++ b/src/types/redis_bitmap.cc
@@ -50,11 +50,11 @@ rocksdb::Status Bitmap::GetMetadata(const Slice &ns_key, BitmapMetadata *metadat
return rocksdb::Status::NotFound(kErrMsgKeyExpired);
}
if (metadata->Type() == kRedisString) return s;
- if (metadata->Type() != kRedisBitmap && metadata->size > 0) {
+ if (metadata->Type() != kRedisBitmap && metadata->size_ > 0) {
metadata->Decode(old_metadata);
return rocksdb::Status::InvalidArgument(kErrMsgWrongType);
}
- if (metadata->size == 0) {
+ if (metadata->size_ == 0) {
metadata->Decode(old_metadata);
return rocksdb::Status::NotFound("no elements");
}
@@ -80,7 +80,7 @@ rocksdb::Status Bitmap::GetBit(const Slice &user_key, uint32_t offset, bool *bit
read_options.snapshot = ss.GetSnapShot();
uint32_t index = (offset / kBitmapSegmentBits) * kBitmapSegmentBytes;
std::string sub_key, value;
- InternalKey(ns_key, std::to_string(index), metadata.version, storage_->IsSlotIdEncoded()).Encode(&sub_key);
+ InternalKey(ns_key, std::to_string(index), metadata.version_, storage_->IsSlotIdEncoded()).Encode(&sub_key);
s = storage_->Get(read_options, sub_key, &value);
if (!s.ok()) return s.IsNotFound() ? rocksdb::Status::OK() : s;
uint32_t byte_index = (offset / 8) % kBitmapSegmentBytes;
@@ -100,14 +100,14 @@ rocksdb::Status Bitmap::GetString(const Slice &user_key, const uint32_t max_btos
BitmapMetadata metadata(false);
rocksdb::Status s = GetMetadata(ns_key, &metadata, &raw_value);
if (!s.ok()) return s;
- if (metadata.size > max_btos_size) {
+ if (metadata.size_ > max_btos_size) {
return rocksdb::Status::Aborted(kErrBitmapStringOutOfRange);
}
- value->assign(metadata.size, 0);
+ value->assign(metadata.size_, 0);
std::string fragment, prefix_key;
fragment.reserve(kBitmapSegmentBytes * 2);
- InternalKey(ns_key, "", metadata.version, storage_->IsSlotIdEncoded()).Encode(&prefix_key);
+ InternalKey(ns_key, "", metadata.version_, storage_->IsSlotIdEncoded()).Encode(&prefix_key);
rocksdb::ReadOptions read_options;
LatestSnapShot ss(storage_);
@@ -126,7 +126,7 @@ rocksdb::Status Bitmap::GetString(const Slice &user_key, const uint32_t max_btos
// To be compatible with data written before the commit d603b0e(#338)
// and avoid returning extra null char after expansion.
uint32_t valid_size = std::min(
- {fragment.size(), static_cast<size_t>(kBitmapSegmentBytes), static_cast<size_t>(metadata.size - frag_index)});
+ {fragment.size(), static_cast<size_t>(kBitmapSegmentBytes), static_cast<size_t>(metadata.size_ - frag_index)});
/*
* If you setbit bit 0 1, the value is stored as 0x01 in Kvrocks but 0x80 in Redis.
@@ -178,14 +178,14 @@ rocksdb::Status Bitmap::SetBit(const Slice &user_key, uint32_t offset, bool new_
std::string sub_key, value;
uint32_t index = (offset / kBitmapSegmentBits) * kBitmapSegmentBytes;
- InternalKey(ns_key, std::to_string(index), metadata.version, storage_->IsSlotIdEncoded()).Encode(&sub_key);
+ InternalKey(ns_key, std::to_string(index), metadata.version_, storage_->IsSlotIdEncoded()).Encode(&sub_key);
if (s.ok()) {
s = storage_->Get(rocksdb::ReadOptions(), sub_key, &value);
if (!s.ok() && !s.IsNotFound()) return s;
}
uint32_t byte_index = (offset / 8) % kBitmapSegmentBytes;
uint64_t used_size = index + byte_index + 1;
- uint64_t bitmap_size = std::max(used_size, metadata.size);
+ uint64_t bitmap_size = std::max(used_size, metadata.size_);
if (byte_index >= value.size()) { // expand the bitmap
size_t expand_size = 0;
if (byte_index >= value.size() * 2) {
@@ -208,8 +208,8 @@ rocksdb::Status Bitmap::SetBit(const Slice &user_key, uint32_t offset, bool new_
WriteBatchLogData log_data(kRedisBitmap, {std::to_string(kRedisCmdSetBit), std::to_string(offset)});
batch->PutLogData(log_data.Encode());
batch->Put(sub_key, value);
- if (metadata.size != bitmap_size) {
- metadata.size = bitmap_size;
+ if (metadata.size_ != bitmap_size) {
+ metadata.size_ = bitmap_size;
std::string bytes;
metadata.Encode(&bytes);
batch->Put(metadata_cf_handle_, ns_key, bytes);
@@ -231,9 +231,9 @@ rocksdb::Status Bitmap::BitCount(const Slice &user_key, int64_t start, int64_t s
return bitmap_string_db.BitCount(raw_value, start, stop, cnt);
}
- if (start < 0) start += static_cast<int64_t>(metadata.size) + 1;
- if (stop < 0) stop += static_cast<int64_t>(metadata.size) + 1;
- if (stop > static_cast<int64_t>(metadata.size)) stop = static_cast<int64_t>(metadata.size);
+ if (start < 0) start += static_cast<int64_t>(metadata.size_) + 1;
+ if (stop < 0) stop += static_cast<int64_t>(metadata.size_) + 1;
+ if (stop > static_cast<int64_t>(metadata.size_)) stop = static_cast<int64_t>(metadata.size_);
if (start < 0 || stop <= 0 || start >= stop) return rocksdb::Status::OK();
auto u_start = static_cast<uint32_t>(start);
@@ -247,7 +247,7 @@ rocksdb::Status Bitmap::BitCount(const Slice &user_key, int64_t start, int64_t s
// Don't use multi get to prevent large range query, and take too much memory
std::string sub_key, value;
for (uint32_t i = start_index; i <= stop_index; i++) {
- InternalKey(ns_key, std::to_string(i * kBitmapSegmentBytes), metadata.version, storage_->IsSlotIdEncoded())
+ InternalKey(ns_key, std::to_string(i * kBitmapSegmentBytes), metadata.version_, storage_->IsSlotIdEncoded())
.Encode(&sub_key);
s = storage_->Get(read_options, sub_key, &value);
if (!s.ok() && !s.IsNotFound()) return s;
@@ -279,8 +279,8 @@ rocksdb::Status Bitmap::BitPos(const Slice &user_key, bool bit, int64_t start, i
return bitmap_string_db.BitPos(raw_value, bit, start, stop, stop_given, pos);
}
- if (start < 0) start += static_cast<int64_t>(metadata.size) + 1;
- if (stop < 0) stop += static_cast<int64_t>(metadata.size) + 1;
+ if (start < 0) start += static_cast<int64_t>(metadata.size_) + 1;
+ if (stop < 0) stop += static_cast<int64_t>(metadata.size_) + 1;
if (start < 0 || stop < 0 || start > stop) {
*pos = -1;
return rocksdb::Status::OK();
@@ -304,7 +304,7 @@ rocksdb::Status Bitmap::BitPos(const Slice &user_key, bool bit, int64_t start, i
// Don't use multi get to prevent large range query, and take too much memory
std::string sub_key, value;
for (uint32_t i = start_index; i <= stop_index; i++) {
- InternalKey(ns_key, std::to_string(i * kBitmapSegmentBytes), metadata.version, storage_->IsSlotIdEncoded())
+ InternalKey(ns_key, std::to_string(i * kBitmapSegmentBytes), metadata.version_, storage_->IsSlotIdEncoded())
.Encode(&sub_key);
s = storage_->Get(read_options, sub_key, &value);
if (!s.ok() && !s.IsNotFound()) return s;
@@ -330,7 +330,7 @@ rocksdb::Status Bitmap::BitPos(const Slice &user_key, bool bit, int64_t start, i
}
}
// bit was not found
- *pos = bit ? -1 : static_cast<int64_t>(metadata.size * 8);
+ *pos = bit ? -1 : static_cast<int64_t>(metadata.size_ * 8);
return rocksdb::Status::OK();
}
@@ -357,7 +357,7 @@ rocksdb::Status Bitmap::BitOp(BitOpFlags op_flag, const std::string &op_name, co
if (metadata.Type() == kRedisString) {
return rocksdb::Status::InvalidArgument(kErrMsgWrongType);
}
- if (metadata.size > max_size) max_size = metadata.size;
+ if (metadata.size_ > max_size) max_size = metadata.size_;
meta_pairs.emplace_back(ns_op_key, metadata);
}
@@ -387,7 +387,7 @@ rocksdb::Status Bitmap::BitOp(BitOpFlags op_flag, const std::string &op_name, co
read_options.snapshot = ss.GetSnapShot();
for (uint64_t frag_index = 0; frag_index <= stop_index; frag_index++) {
for (const auto &meta_pair : meta_pairs) {
- InternalKey(meta_pair.first, std::to_string(frag_index * kBitmapSegmentBytes), meta_pair.second.version,
+ InternalKey(meta_pair.first, std::to_string(frag_index * kBitmapSegmentBytes), meta_pair.second.version_,
storage_->IsSlotIdEncoded())
.Encode(&sub_key);
auto s = storage_->Get(read_options, sub_key, &fragment);
@@ -506,7 +506,7 @@ rocksdb::Status Bitmap::BitOp(BitOpFlags op_flag, const std::string &op_name, co
frag_maxlen = kBitmapSegmentBytes;
}
}
- InternalKey(ns_key, std::to_string(frag_index * kBitmapSegmentBytes), res_metadata.version,
+ InternalKey(ns_key, std::to_string(frag_index * kBitmapSegmentBytes), res_metadata.version_,
storage_->IsSlotIdEncoded())
.Encode(&sub_key);
batch->Put(sub_key, Slice(reinterpret_cast<char *>(frag_res.get()), frag_maxlen));
@@ -520,7 +520,7 @@ rocksdb::Status Bitmap::BitOp(BitOpFlags op_flag, const std::string &op_name, co
}
std::string bytes;
- res_metadata.size = max_size;
+ res_metadata.size_ = max_size;
res_metadata.Encode(&bytes);
batch->Put(metadata_cf_handle_, ns_key, bytes);
*len = static_cast<int64_t>(max_size);
diff --git a/src/types/redis_geo.cc b/src/types/redis_geo.cc
index 8df7ddae..87591dee 100644
--- a/src/types/redis_geo.cc
+++ b/src/types/redis_geo.cc
@@ -29,9 +29,9 @@ rocksdb::Status Geo::Add(const Slice &user_key, std::vector<GeoPoint> *geo_point
for (const auto &geo_point : *geo_points) {
/* Turn the coordinates into the score of the element. */
GeoHashBits hash;
- geohashEncodeWGS84(geo_point.longitude, geo_point.latitude, GEO_STEP_MAX, &hash);
+ geohashEncodeWGS84(geo_point.longitude_, geo_point.latitude_, GEO_STEP_MAX, &hash);
GeoHashFix52Bits bits = GeoHashHelper::Align52Bits(hash);
- member_scores.emplace_back(MemberScore{geo_point.member, static_cast<double>(bits)});
+ member_scores.emplace_back(MemberScore{geo_point.member_, static_cast<double>(bits)});
}
return ZSet::Add(user_key, ZAddFlags::Default(), &member_scores, ret);
}
@@ -48,8 +48,8 @@ rocksdb::Status Geo::Dist(const Slice &user_key, const Slice &member_1, const Sl
}
}
*dist =
- GeoHashHelper::GetDistance(geo_points[member_1.ToString()].longitude, geo_points[member_1.ToString()].latitude,
- geo_points[member_2.ToString()].longitude, geo_points[member_2.ToString()].latitude);
+ GeoHashHelper::GetDistance(geo_points[member_1.ToString()].longitude_, geo_points[member_1.ToString()].latitude_,
+ geo_points[member_2.ToString()].longitude_, geo_points[member_2.ToString()].latitude_);
return rocksdb::Status::OK();
}
@@ -65,7 +65,7 @@ rocksdb::Status Geo::Hash(const Slice &user_key, const std::vector<Slice> &membe
geo_hashes->emplace_back(std::string());
continue;
}
- geo_hashes->emplace_back(EncodeGeoHash(iter->second.longitude, iter->second.latitude));
+ geo_hashes->emplace_back(EncodeGeoHash(iter->second.longitude_, iter->second.latitude_));
}
return rocksdb::Status::OK();
@@ -114,8 +114,8 @@ rocksdb::Status Geo::Radius(const Slice &user_key, double longitude, double lati
if (returned_items_count-- <= 0) {
break;
}
- double score = store_distance ? geo_point.dist / unit_conversion : geo_point.score;
- member_scores.emplace_back(MemberScore{geo_point.member, score});
+ double score = store_distance ? geo_point.dist_ / unit_conversion : geo_point.score_;
+ member_scores.emplace_back(MemberScore{geo_point.member_, score});
}
int ret = 0;
ZSet::Add(store_key, ZAddFlags::Default(), &member_scores, &ret);
@@ -132,7 +132,7 @@ rocksdb::Status Geo::RadiusByMember(const Slice &user_key, const Slice &member,
auto s = Get(user_key, member, &geo_point);
if (!s.ok()) return s;
- return Radius(user_key, geo_point.longitude, geo_point.latitude, radius_meters, count, sort, store_key,
+ return Radius(user_key, geo_point.longitude_, geo_point.latitude_, radius_meters, count, sort, store_key,
store_distance, unit_conversion, geo_points);
}
@@ -180,10 +180,10 @@ std::string Geo::EncodeGeoHash(double longitude, double latitude) {
/* Re-encode */
GeoHashRange r[2];
GeoHashBits hash;
- r[0].min = -180;
- r[0].max = 180;
- r[1].min = -90;
- r[1].max = 90;
+ r[0].min_ = -180;
+ r[0].max_ = 180;
+ r[1].min_ = -90;
+ r[1].max_ = 90;
geohashEncode(&r[0], &r[1], longitude, latitude, 26, &hash);
std::string geo_hash;
@@ -195,7 +195,7 @@ std::string Geo::EncodeGeoHash(double longitude, double latitude) {
* zero. */
idx = 0;
} else {
- idx = static_cast<int>((hash.bits >> (52 - ((i + 1) * 5))) & 0x1f);
+ idx = static_cast<int>((hash.bits_ >> (52 - ((i + 1) * 5))) & 0x1f);
}
geo_hash += geoalphabet[idx];
}
@@ -214,15 +214,15 @@ int Geo::membersOfAllNeighbors(const Slice &user_key, GeoHashRadius n, double lo
unsigned int last_processed = 0;
int count = 0;
- neighbors[0] = n.hash;
- neighbors[1] = n.neighbors.north;
- neighbors[2] = n.neighbors.south;
- neighbors[3] = n.neighbors.east;
- neighbors[4] = n.neighbors.west;
- neighbors[5] = n.neighbors.north_east;
- neighbors[6] = n.neighbors.north_west;
- neighbors[7] = n.neighbors.south_east;
- neighbors[8] = n.neighbors.south_west;
+ neighbors[0] = n.hash_;
+ neighbors[1] = n.neighbors_.north_;
+ neighbors[2] = n.neighbors_.south_;
+ neighbors[3] = n.neighbors_.east_;
+ neighbors[4] = n.neighbors_.west_;
+ neighbors[5] = n.neighbors_.north_east_;
+ neighbors[6] = n.neighbors_.north_west_;
+ neighbors[7] = n.neighbors_.south_east_;
+ neighbors[8] = n.neighbors_.south_west_;
/* For each neighbor (*and* our own hashbox), get all the matching
* members and add them to the potential result list. */
@@ -235,8 +235,8 @@ int Geo::membersOfAllNeighbors(const Slice &user_key, GeoHashRadius n, double lo
* adjacent neighbors can be the same, leading to duplicated
* elements. Skip every range which is the same as the one
* processed previously. */
- if (last_processed && neighbors[i].bits == neighbors[last_processed].bits &&
- neighbors[i].step == neighbors[last_processed].step) {
+ if (last_processed && neighbors[i].bits_ == neighbors[last_processed].bits_ &&
+ neighbors[i].step_ == neighbors[last_processed].step_) {
continue;
}
count += membersOfGeoHashBox(user_key, neighbors[i], geo_points, lon, lat, radius);
@@ -281,7 +281,7 @@ void Geo::scoresOfGeoHashBox(GeoHashBits hash, GeoHashFix52Bits *min, GeoHashFix
* 1010110000000000000000000000000000000000000000000000 (excluded).
*/
*min = GeoHashHelper::Align52Bits(hash);
- hash.bits++;
+ hash.bits_++;
*max = GeoHashHelper::Align52Bits(hash);
}
@@ -302,16 +302,16 @@ int Geo::getPointsInRange(const Slice &user_key, double min, double max, double
/* include min in range; exclude max in range */
/* That's: min <= val < max */
ZRangeSpec spec;
- spec.min = min;
- spec.max = max;
- spec.maxex = true;
+ spec.min_ = min;
+ spec.max_ = max;
+ spec.maxex_ = true;
int size = 0;
std::vector<MemberScore> member_scores;
rocksdb::Status s = ZSet::RangeByScore(user_key, spec, &member_scores, &size);
if (!s.ok()) return 0;
for (const auto &member_score : member_scores) {
- appendIfWithinRadius(geo_points, lon, lat, radius, member_score.score, member_score.member);
+ appendIfWithinRadius(geo_points, lon, lat, radius, member_score.score_, member_score.member_);
}
return 0;
}
@@ -335,17 +335,17 @@ bool Geo::appendIfWithinRadius(std::vector<GeoPoint> *geo_points, double lon, do
/* Append the new element. */
GeoPoint geo_point;
- geo_point.longitude = xy[0];
- geo_point.latitude = xy[1];
- geo_point.dist = distance;
- geo_point.member = member;
- geo_point.score = score;
+ geo_point.longitude_ = xy[0];
+ geo_point.latitude_ = xy[1];
+ geo_point.dist_ = distance;
+ geo_point.member_ = member;
+ geo_point.score_ = score;
geo_points->emplace_back(geo_point);
return true;
}
-bool Geo::sortGeoPointASC(const GeoPoint &gp1, const GeoPoint &gp2) { return gp1.dist < gp2.dist; }
+bool Geo::sortGeoPointASC(const GeoPoint &gp1, const GeoPoint &gp2) { return gp1.dist_ < gp2.dist_; }
-bool Geo::sortGeoPointDESC(const GeoPoint &gp1, const GeoPoint &gp2) { return gp1.dist >= gp2.dist; }
+bool Geo::sortGeoPointDESC(const GeoPoint &gp1, const GeoPoint &gp2) { return gp1.dist_ >= gp2.dist_; }
} // namespace Redis
diff --git a/src/types/redis_geo.h b/src/types/redis_geo.h
index 234719aa..f23525f1 100644
--- a/src/types/redis_geo.h
+++ b/src/types/redis_geo.h
@@ -45,11 +45,11 @@ enum DistanceSort {
// Structures represent points and array of points on the earth.
struct GeoPoint {
- double longitude;
- double latitude;
- std::string member;
- double dist;
- double score;
+ double longitude_;
+ double latitude_;
+ std::string member_;
+ double dist_;
+ double score_;
};
namespace Redis {
diff --git a/src/types/redis_hash.cc b/src/types/redis_hash.cc
index f82204f1..b3ccda98 100644
--- a/src/types/redis_hash.cc
+++ b/src/types/redis_hash.cc
@@ -44,7 +44,7 @@ rocksdb::Status Hash::Size(const Slice &user_key, uint32_t *ret) {
HashMetadata metadata(false);
rocksdb::Status s = GetMetadata(ns_key, &metadata);
if (!s.ok()) return s;
- *ret = metadata.size;
+ *ret = metadata.size_;
return rocksdb::Status::OK();
}
@@ -58,7 +58,7 @@ rocksdb::Status Hash::Get(const Slice &user_key, const Slice &field, std::string
rocksdb::ReadOptions read_options;
read_options.snapshot = ss.GetSnapShot();
std::string sub_key;
- InternalKey(ns_key, field, metadata.version, storage_->IsSlotIdEncoded()).Encode(&sub_key);
+ InternalKey(ns_key, field, metadata.version_, storage_->IsSlotIdEncoded()).Encode(&sub_key);
return storage_->Get(read_options, sub_key, value);
}
@@ -75,7 +75,7 @@ rocksdb::Status Hash::IncrBy(const Slice &user_key, const Slice &field, int64_t
if (!s.ok() && !s.IsNotFound()) return s;
std::string sub_key;
- InternalKey(ns_key, field, metadata.version, storage_->IsSlotIdEncoded()).Encode(&sub_key);
+ InternalKey(ns_key, field, metadata.version_, storage_->IsSlotIdEncoded()).Encode(&sub_key);
if (s.ok()) {
std::string value_bytes;
s = storage_->Get(rocksdb::ReadOptions(), sub_key, &value_bytes);
@@ -103,7 +103,7 @@ rocksdb::Status Hash::IncrBy(const Slice &user_key, const Slice &field, int64_t
batch->PutLogData(log_data.Encode());
batch->Put(sub_key, std::to_string(*ret));
if (!exists) {
- metadata.size += 1;
+ metadata.size_ += 1;
std::string bytes;
metadata.Encode(&bytes);
batch->Put(metadata_cf_handle_, ns_key, bytes);
@@ -124,7 +124,7 @@ rocksdb::Status Hash::IncrByFloat(const Slice &user_key, const Slice &field, dou
if (!s.ok() && !s.IsNotFound()) return s;
std::string sub_key;
- InternalKey(ns_key, field, metadata.version, storage_->IsSlotIdEncoded()).Encode(&sub_key);
+ InternalKey(ns_key, field, metadata.version_, storage_->IsSlotIdEncoded()).Encode(&sub_key);
if (s.ok()) {
std::string value_bytes;
s = storage_->Get(rocksdb::ReadOptions(), sub_key, &value_bytes);
@@ -149,7 +149,7 @@ rocksdb::Status Hash::IncrByFloat(const Slice &user_key, const Slice &field, dou
batch->PutLogData(log_data.Encode());
batch->Put(sub_key, std::to_string(*ret));
if (!exists) {
- metadata.size += 1;
+ metadata.size_ += 1;
std::string bytes;
metadata.Encode(&bytes);
batch->Put(metadata_cf_handle_, ns_key, bytes);
@@ -177,7 +177,7 @@ rocksdb::Status Hash::MGet(const Slice &user_key, const std::vector<Slice> &fiel
std::string sub_key, value;
for (const auto &field : fields) {
- InternalKey(ns_key, field, metadata.version, storage_->IsSlotIdEncoded()).Encode(&sub_key);
+ InternalKey(ns_key, field, metadata.version_, storage_->IsSlotIdEncoded()).Encode(&sub_key);
value.clear();
s = storage_->Get(read_options, sub_key, &value);
if (!s.ok() && !s.IsNotFound()) return s;
@@ -207,7 +207,7 @@ rocksdb::Status Hash::Delete(const Slice &user_key, const std::vector<Slice> &fi
std::string sub_key, value;
for (const auto &field : fields) {
- InternalKey(ns_key, field, metadata.version, storage_->IsSlotIdEncoded()).Encode(&sub_key);
+ InternalKey(ns_key, field, metadata.version_, storage_->IsSlotIdEncoded()).Encode(&sub_key);
s = storage_->Get(rocksdb::ReadOptions(), sub_key, &value);
if (s.ok()) {
*ret += 1;
@@ -217,7 +217,7 @@ rocksdb::Status Hash::Delete(const Slice &user_key, const std::vector<Slice> &fi
if (*ret == 0) {
return rocksdb::Status::OK();
}
- metadata.size -= *ret;
+ metadata.size_ -= *ret;
std::string bytes;
metadata.Encode(&bytes);
batch->Put(metadata_cf_handle_, ns_key, bytes);
@@ -243,15 +243,15 @@ rocksdb::Status Hash::MSet(const Slice &user_key, const std::vector<FieldValue>
bool exists = false;
std::string sub_key;
- InternalKey(ns_key, fv.field, metadata.version, storage_->IsSlotIdEncoded()).Encode(&sub_key);
+ InternalKey(ns_key, fv.field_, metadata.version_, storage_->IsSlotIdEncoded()).Encode(&sub_key);
- if (metadata.size > 0) {
+ if (metadata.size_ > 0) {
std::string field_value;
s = storage_->Get(rocksdb::ReadOptions(), sub_key, &field_value);
if (!s.ok() && !s.IsNotFound()) return s;
if (s.ok()) {
- if (nx || field_value == fv.value) continue;
+ if (nx || field_value == fv.value_) continue;
exists = true;
}
@@ -259,12 +259,12 @@ rocksdb::Status Hash::MSet(const Slice &user_key, const std::vector<FieldValue>
if (!exists) added++;
- batch->Put(sub_key, fv.value);
+ batch->Put(sub_key, fv.value_);
}
if (added > 0) {
*ret = added;
- metadata.size += added;
+ metadata.size_ += added;
std::string bytes;
metadata.Encode(&bytes);
batch->Put(metadata_cf_handle_, ns_key, bytes);
@@ -276,7 +276,7 @@ rocksdb::Status Hash::MSet(const Slice &user_key, const std::vector<FieldValue>
rocksdb::Status Hash::RangeByLex(const Slice &user_key, const CommonRangeLexSpec &spec,
std::vector<FieldValue> *field_values) {
field_values->clear();
- if (spec.count == 0) {
+ if (spec.count_ == 0) {
return rocksdb::Status::OK();
}
std::string ns_key;
@@ -285,11 +285,11 @@ rocksdb::Status Hash::RangeByLex(const Slice &user_key, const CommonRangeLexSpec
rocksdb::Status s = GetMetadata(ns_key, &metadata);
if (!s.ok()) return s.IsNotFound() ? rocksdb::Status::OK() : s;
- std::string start_member = spec.reversed ? spec.max : spec.min;
+ std::string start_member = spec.reversed_ ? spec.max_ : spec.min_;
std::string start_key, prefix_key, next_version_prefix_key;
- InternalKey(ns_key, start_member, metadata.version, storage_->IsSlotIdEncoded()).Encode(&start_key);
- InternalKey(ns_key, "", metadata.version, storage_->IsSlotIdEncoded()).Encode(&prefix_key);
- InternalKey(ns_key, "", metadata.version + 1, storage_->IsSlotIdEncoded()).Encode(&next_version_prefix_key);
+ InternalKey(ns_key, start_member, metadata.version_, storage_->IsSlotIdEncoded()).Encode(&start_key);
+ InternalKey(ns_key, "", metadata.version_, storage_->IsSlotIdEncoded()).Encode(&prefix_key);
+ InternalKey(ns_key, "", metadata.version_ + 1, storage_->IsSlotIdEncoded()).Encode(&next_version_prefix_key);
rocksdb::ReadOptions read_options;
LatestSnapShot ss(storage_);
read_options.snapshot = ss.GetSnapShot();
@@ -300,36 +300,36 @@ rocksdb::Status Hash::RangeByLex(const Slice &user_key, const CommonRangeLexSpec
storage_->SetReadOptions(read_options);
auto iter = DBUtil::UniqueIterator(storage_, read_options);
- if (!spec.reversed) {
+ if (!spec.reversed_) {
iter->Seek(start_key);
} else {
- if (spec.max_infinite) {
+ if (spec.max_infinite_) {
iter->SeekToLast();
} else {
iter->SeekForPrev(start_key);
}
}
int64_t pos = 0;
- for (; iter->Valid() && iter->key().starts_with(prefix_key); (!spec.reversed ? iter->Next() : iter->Prev())) {
+ for (; iter->Valid() && iter->key().starts_with(prefix_key); (!spec.reversed_ ? iter->Next() : iter->Prev())) {
InternalKey ikey(iter->key(), storage_->IsSlotIdEncoded());
- if (spec.reversed) {
- if (ikey.GetSubKey().ToString() < spec.min || (spec.minex && ikey.GetSubKey().ToString() == spec.min)) {
+ if (spec.reversed_) {
+ if (ikey.GetSubKey().ToString() < spec.min_ || (spec.minex_ && ikey.GetSubKey().ToString() == spec.min_)) {
break;
}
- if ((spec.maxex && ikey.GetSubKey().ToString() == spec.max) ||
- (!spec.max_infinite && ikey.GetSubKey().ToString() > spec.max)) {
+ if ((spec.maxex_ && ikey.GetSubKey().ToString() == spec.max_) ||
+ (!spec.max_infinite_ && ikey.GetSubKey().ToString() > spec.max_)) {
continue;
}
} else {
- if (spec.minex && ikey.GetSubKey().ToString() == spec.min) continue; // the min member was exclusive
- if ((spec.maxex && ikey.GetSubKey().ToString() == spec.max) ||
- (!spec.max_infinite && ikey.GetSubKey().ToString() > spec.max))
+ if (spec.minex_ && ikey.GetSubKey().ToString() == spec.min_) continue; // the min member was exclusive
+ if ((spec.maxex_ && ikey.GetSubKey().ToString() == spec.max_) ||
+ (!spec.max_infinite_ && ikey.GetSubKey().ToString() > spec.max_))
break;
}
- if (spec.offset >= 0 && pos++ < spec.offset) continue;
+ if (spec.offset_ >= 0 && pos++ < spec.offset_) continue;
field_values->emplace_back(ikey.GetSubKey().ToString(), iter->value().ToString());
- if (spec.count > 0 && field_values->size() >= static_cast<unsigned>(spec.count)) break;
+ if (spec.count_ > 0 && field_values->size() >= static_cast<unsigned>(spec.count_)) break;
}
return rocksdb::Status::OK();
}
@@ -344,8 +344,8 @@ rocksdb::Status Hash::GetAll(const Slice &user_key, std::vector<FieldValue> *fie
if (!s.ok()) return s.IsNotFound() ? rocksdb::Status::OK() : s;
std::string prefix_key, next_version_prefix_key;
- InternalKey(ns_key, "", metadata.version, storage_->IsSlotIdEncoded()).Encode(&prefix_key);
- InternalKey(ns_key, "", metadata.version + 1, storage_->IsSlotIdEncoded()).Encode(&next_version_prefix_key);
+ InternalKey(ns_key, "", metadata.version_, storage_->IsSlotIdEncoded()).Encode(&prefix_key);
+ InternalKey(ns_key, "", metadata.version_ + 1, storage_->IsSlotIdEncoded()).Encode(&next_version_prefix_key);
rocksdb::ReadOptions read_options;
LatestSnapShot ss(storage_);
diff --git a/src/types/redis_hash.h b/src/types/redis_hash.h
index 15710e42..1f66149a 100644
--- a/src/types/redis_hash.h
+++ b/src/types/redis_hash.h
@@ -31,10 +31,10 @@
#include "storage/redis_metadata.h"
struct FieldValue {
- std::string field;
- std::string value;
+ std::string field_;
+ std::string value_;
- FieldValue(std::string f, std::string v) : field(std::move(f)), value(std::move(v)) {}
+ FieldValue(std::string f, std::string v) : field_(std::move(f)), value_(std::move(v)) {}
};
enum class HashFetchType { kAll = 0, kOnlyKey = 1, kOnlyValue = 2 };
diff --git a/src/types/redis_list.cc b/src/types/redis_list.cc
index ebe0ba85..102627be 100644
--- a/src/types/redis_list.cc
+++ b/src/types/redis_list.cc
@@ -39,7 +39,7 @@ rocksdb::Status List::Size(const Slice &user_key, uint32_t *ret) {
ListMetadata metadata(false);
rocksdb::Status s = GetMetadata(ns_key, &metadata);
if (!s.ok()) return s.IsNotFound() ? rocksdb::Status::OK() : s;
- *ret = metadata.size;
+ *ret = metadata.size_;
return rocksdb::Status::OK();
}
@@ -67,24 +67,24 @@ rocksdb::Status List::push(const Slice &user_key, const std::vector<Slice> &elem
if (!s.ok() && !(create_if_missing && s.IsNotFound())) {
return s.IsNotFound() ? rocksdb::Status::OK() : s;
}
- uint64_t index = left ? metadata.head - 1 : metadata.tail;
+ uint64_t index = left ? metadata.head_ - 1 : metadata.tail_;
for (const auto &elem : elems) {
std::string index_buf, sub_key;
PutFixed64(&index_buf, index);
- InternalKey(ns_key, index_buf, metadata.version, storage_->IsSlotIdEncoded()).Encode(&sub_key);
+ InternalKey(ns_key, index_buf, metadata.version_, storage_->IsSlotIdEncoded()).Encode(&sub_key);
batch->Put(sub_key, elem);
left ? --index : ++index;
}
if (left) {
- metadata.head -= elems.size();
+ metadata.head_ -= elems.size();
} else {
- metadata.tail += elems.size();
+ metadata.tail_ += elems.size();
}
std::string bytes;
- metadata.size += elems.size();
+ metadata.size_ += elems.size();
metadata.Encode(&bytes);
batch->Put(metadata_cf_handle_, ns_key, bytes);
- *ret = static_cast<int>(metadata.size);
+ *ret = static_cast<int>(metadata.size_);
return storage_->Write(storage_->DefaultWriteOptions(), batch->GetWriteBatch());
}
@@ -116,12 +116,12 @@ rocksdb::Status List::PopMulti(const rocksdb::Slice &user_key, bool left, uint32
WriteBatchLogData log_data(kRedisList, {std::to_string(cmd)});
batch->PutLogData(log_data.Encode());
- while (metadata.size > 0 && count > 0) {
- uint64_t index = left ? metadata.head : metadata.tail - 1;
+ while (metadata.size_ > 0 && count > 0) {
+ uint64_t index = left ? metadata.head_ : metadata.tail_ - 1;
std::string buf;
PutFixed64(&buf, index);
std::string sub_key;
- InternalKey(ns_key, buf, metadata.version, storage_->IsSlotIdEncoded()).Encode(&sub_key);
+ InternalKey(ns_key, buf, metadata.version_, storage_->IsSlotIdEncoded()).Encode(&sub_key);
std::string elem;
s = storage_->Get(rocksdb::ReadOptions(), sub_key, &elem);
if (!s.ok()) {
@@ -131,12 +131,12 @@ rocksdb::Status List::PopMulti(const rocksdb::Slice &user_key, bool left, uint32
elems->push_back(elem);
batch->Delete(sub_key);
- metadata.size -= 1;
- left ? ++metadata.head : --metadata.tail;
+ metadata.size_ -= 1;
+ left ? ++metadata.head_ : --metadata.tail_;
--count;
}
- if (metadata.size == 0) {
+ if (metadata.size_ == 0) {
batch->Delete(metadata_cf_handle_, ns_key);
} else {
std::string bytes;
@@ -177,12 +177,12 @@ rocksdb::Status List::Rem(const Slice &user_key, int count, const Slice &elem, i
rocksdb::Status s = GetMetadata(ns_key, &metadata);
if (!s.ok()) return s;
- uint64_t index = count >= 0 ? metadata.head : metadata.tail - 1;
+ uint64_t index = count >= 0 ? metadata.head_ : metadata.tail_ - 1;
std::string buf, start_key, prefix, next_version_prefix;
PutFixed64(&buf, index);
- InternalKey(ns_key, buf, metadata.version, storage_->IsSlotIdEncoded()).Encode(&start_key);
- InternalKey(ns_key, "", metadata.version, storage_->IsSlotIdEncoded()).Encode(&prefix);
- InternalKey(ns_key, "", metadata.version + 1, storage_->IsSlotIdEncoded()).Encode(&next_version_prefix);
+ InternalKey(ns_key, buf, metadata.version_, storage_->IsSlotIdEncoded()).Encode(&start_key);
+ InternalKey(ns_key, "", metadata.version_, storage_->IsSlotIdEncoded()).Encode(&prefix);
+ InternalKey(ns_key, "", metadata.version_ + 1, storage_->IsSlotIdEncoded()).Encode(&next_version_prefix);
bool reversed = count < 0;
std::vector<uint64_t> to_delete_indexes;
@@ -214,25 +214,25 @@ rocksdb::Status List::Rem(const Slice &user_key, int count, const Slice &elem, i
WriteBatchLogData log_data(kRedisList, {std::to_string(kRedisCmdLRem), std::to_string(count), elem.ToString()});
batch->PutLogData(log_data.Encode());
- if (to_delete_indexes.size() == metadata.size) {
+ if (to_delete_indexes.size() == metadata.size_) {
batch->Delete(metadata_cf_handle_, ns_key);
} else {
std::string to_update_key, to_delete_key;
uint64_t min_to_delete_index = !reversed ? to_delete_indexes[0] : to_delete_indexes[to_delete_indexes.size() - 1];
uint64_t max_to_delete_index = !reversed ? to_delete_indexes[to_delete_indexes.size() - 1] : to_delete_indexes[0];
- uint64_t left_part_len = max_to_delete_index - metadata.head;
- uint64_t right_part_len = metadata.tail - 1 - min_to_delete_index;
+ uint64_t left_part_len = max_to_delete_index - metadata.head_;
+ uint64_t right_part_len = metadata.tail_ - 1 - min_to_delete_index;
reversed = left_part_len <= right_part_len;
buf.clear();
PutFixed64(&buf, reversed ? max_to_delete_index : min_to_delete_index);
- InternalKey(ns_key, buf, metadata.version, storage_->IsSlotIdEncoded()).Encode(&start_key);
+ InternalKey(ns_key, buf, metadata.version_, storage_->IsSlotIdEncoded()).Encode(&start_key);
size_t processed = 0;
for (iter->Seek(start_key); iter->Valid() && iter->key().starts_with(prefix);
!reversed ? iter->Next() : iter->Prev()) {
if (iter->value() != elem || processed >= to_delete_indexes.size()) {
buf.clear();
PutFixed64(&buf, reversed ? max_to_delete_index-- : min_to_delete_index++);
- InternalKey(ns_key, buf, metadata.version, storage_->IsSlotIdEncoded()).Encode(&to_update_key);
+ InternalKey(ns_key, buf, metadata.version_, storage_->IsSlotIdEncoded()).Encode(&to_update_key);
batch->Put(to_update_key, iter->value());
} else {
processed++;
@@ -241,16 +241,16 @@ rocksdb::Status List::Rem(const Slice &user_key, int count, const Slice &elem, i
for (uint64_t idx = 0; idx < to_delete_indexes.size(); ++idx) {
buf.clear();
- PutFixed64(&buf, reversed ? (metadata.head + idx) : (metadata.tail - 1 - idx));
- InternalKey(ns_key, buf, metadata.version, storage_->IsSlotIdEncoded()).Encode(&to_delete_key);
+ PutFixed64(&buf, reversed ? (metadata.head_ + idx) : (metadata.tail_ - 1 - idx));
+ InternalKey(ns_key, buf, metadata.version_, storage_->IsSlotIdEncoded()).Encode(&to_delete_key);
batch->Delete(to_delete_key);
}
if (reversed) {
- metadata.head += to_delete_indexes.size();
+ metadata.head_ += to_delete_indexes.size();
} else {
- metadata.tail -= to_delete_indexes.size();
+ metadata.tail_ -= to_delete_indexes.size();
}
- metadata.size -= to_delete_indexes.size();
+ metadata.size_ -= to_delete_indexes.size();
std::string bytes;
metadata.Encode(&bytes);
batch->Put(metadata_cf_handle_, ns_key, bytes);
@@ -271,11 +271,11 @@ rocksdb::Status List::Insert(const Slice &user_key, const Slice &pivot, const Sl
if (!s.ok()) return s;
std::string buf, start_key, prefix, next_version_prefix;
- uint64_t pivot_index = metadata.head - 1;
- PutFixed64(&buf, metadata.head);
- InternalKey(ns_key, buf, metadata.version, storage_->IsSlotIdEncoded()).Encode(&start_key);
- InternalKey(ns_key, "", metadata.version, storage_->IsSlotIdEncoded()).Encode(&prefix);
- InternalKey(ns_key, "", metadata.version + 1, storage_->IsSlotIdEncoded()).Encode(&next_version_prefix);
+ uint64_t pivot_index = metadata.head_ - 1;
+ PutFixed64(&buf, metadata.head_);
+ InternalKey(ns_key, buf, metadata.version_, storage_->IsSlotIdEncoded()).Encode(&start_key);
+ InternalKey(ns_key, "", metadata.version_, storage_->IsSlotIdEncoded()).Encode(&prefix);
+ InternalKey(ns_key, "", metadata.version_ + 1, storage_->IsSlotIdEncoded()).Encode(&next_version_prefix);
rocksdb::ReadOptions read_options;
LatestSnapShot ss(storage_);
@@ -293,7 +293,7 @@ rocksdb::Status List::Insert(const Slice &user_key, const Slice &pivot, const Sl
break;
}
}
- if (pivot_index == (metadata.head - 1)) {
+ if (pivot_index == (metadata.head_ - 1)) {
*ret = -1;
return rocksdb::Status::NotFound();
}
@@ -304,8 +304,8 @@ rocksdb::Status List::Insert(const Slice &user_key, const Slice &pivot, const Sl
batch->PutLogData(log_data.Encode());
std::string to_update_key;
- uint64_t left_part_len = pivot_index - metadata.head + (before ? 0 : 1);
- uint64_t right_part_len = metadata.tail - 1 - pivot_index + (before ? 1 : 0);
+ uint64_t left_part_len = pivot_index - metadata.head_ + (before ? 0 : 1);
+ uint64_t right_part_len = metadata.tail_ - 1 - pivot_index + (before ? 1 : 0);
bool reversed = left_part_len <= right_part_len;
uint64_t new_elem_index = 0;
if ((reversed && !before) || (!reversed && before)) {
@@ -317,25 +317,25 @@ rocksdb::Status List::Insert(const Slice &user_key, const Slice &pivot, const Sl
for (; iter->Valid() && iter->key().starts_with(prefix); !reversed ? iter->Next() : iter->Prev()) {
buf.clear();
PutFixed64(&buf, reversed ? --pivot_index : ++pivot_index);
- InternalKey(ns_key, buf, metadata.version, storage_->IsSlotIdEncoded()).Encode(&to_update_key);
+ InternalKey(ns_key, buf, metadata.version_, storage_->IsSlotIdEncoded()).Encode(&to_update_key);
batch->Put(to_update_key, iter->value());
}
buf.clear();
PutFixed64(&buf, new_elem_index);
- InternalKey(ns_key, buf, metadata.version, storage_->IsSlotIdEncoded()).Encode(&to_update_key);
+ InternalKey(ns_key, buf, metadata.version_, storage_->IsSlotIdEncoded()).Encode(&to_update_key);
batch->Put(to_update_key, elem);
if (reversed) {
- metadata.head--;
+ metadata.head_--;
} else {
- metadata.tail++;
+ metadata.tail_++;
}
- metadata.size++;
+ metadata.size_++;
std::string bytes;
metadata.Encode(&bytes);
batch->Put(metadata_cf_handle_, ns_key, bytes);
- *ret = static_cast<int>(metadata.size);
+ *ret = static_cast<int>(metadata.size_);
return storage_->Write(storage_->DefaultWriteOptions(), batch->GetWriteBatch());
}
@@ -348,16 +348,16 @@ rocksdb::Status List::Index(const Slice &user_key, int index, std::string *elem)
rocksdb::Status s = GetMetadata(ns_key, &metadata);
if (!s.ok()) return s;
- if (index < 0) index += static_cast<int>(metadata.size);
- if (index < 0 || index >= static_cast<int>(metadata.size)) return rocksdb::Status::NotFound();
+ if (index < 0) index += static_cast<int>(metadata.size_);
+ if (index < 0 || index >= static_cast<int>(metadata.size_)) return rocksdb::Status::NotFound();
rocksdb::ReadOptions read_options;
LatestSnapShot ss(storage_);
read_options.snapshot = ss.GetSnapShot();
std::string buf;
- PutFixed64(&buf, metadata.head + index);
+ PutFixed64(&buf, metadata.head_ + index);
std::string sub_key;
- InternalKey(ns_key, buf, metadata.version, storage_->IsSlotIdEncoded()).Encode(&sub_key);
+ InternalKey(ns_key, buf, metadata.version_, storage_->IsSlotIdEncoded()).Encode(&sub_key);
return storage_->Get(read_options, sub_key, elem);
}
@@ -375,17 +375,17 @@ rocksdb::Status List::Range(const Slice &user_key, int start, int stop, std::vec
rocksdb::Status s = GetMetadata(ns_key, &metadata);
if (!s.ok()) return s.IsNotFound() ? rocksdb::Status::OK() : s;
- if (start < 0) start = static_cast<int>(metadata.size) + start;
- if (stop < 0) stop = static_cast<int>(metadata.size) + stop;
- if (start > static_cast<int>(metadata.size) || stop < 0 || start > stop) return rocksdb::Status::OK();
+ if (start < 0) start = static_cast<int>(metadata.size_) + start;
+ if (stop < 0) stop = static_cast<int>(metadata.size_) + stop;
+ if (start > static_cast<int>(metadata.size_) || stop < 0 || start > stop) return rocksdb::Status::OK();
if (start < 0) start = 0;
std::string buf;
- PutFixed64(&buf, metadata.head + start);
+ PutFixed64(&buf, metadata.head_ + start);
std::string start_key, prefix, next_version_prefix;
- InternalKey(ns_key, buf, metadata.version, storage_->IsSlotIdEncoded()).Encode(&start_key);
- InternalKey(ns_key, "", metadata.version, storage_->IsSlotIdEncoded()).Encode(&prefix);
- InternalKey(ns_key, "", metadata.version + 1, storage_->IsSlotIdEncoded()).Encode(&next_version_prefix);
+ InternalKey(ns_key, buf, metadata.version_, storage_->IsSlotIdEncoded()).Encode(&start_key);
+ InternalKey(ns_key, "", metadata.version_, storage_->IsSlotIdEncoded()).Encode(&prefix);
+ InternalKey(ns_key, "", metadata.version_ + 1, storage_->IsSlotIdEncoded()).Encode(&next_version_prefix);
rocksdb::ReadOptions read_options;
LatestSnapShot ss(storage_);
@@ -401,7 +401,7 @@ rocksdb::Status List::Range(const Slice &user_key, int start, int stop, std::vec
uint64_t index = 0;
GetFixed64(&sub_key, &index);
// index should be always >= start
- if (index > metadata.head + stop) break;
+ if (index > metadata.head_ + stop) break;
elems->push_back(iter->value().ToString());
}
return rocksdb::Status::OK();
@@ -415,14 +415,14 @@ rocksdb::Status List::Set(const Slice &user_key, int index, Slice elem) {
ListMetadata metadata(false);
rocksdb::Status s = GetMetadata(ns_key, &metadata);
if (!s.ok()) return s;
- if (index < 0) index += static_cast<int>(metadata.size);
- if (index < 0 || index >= static_cast<int>(metadata.size)) {
+ if (index < 0) index += static_cast<int>(metadata.size_);
+ if (index < 0 || index >= static_cast<int>(metadata.size_)) {
return rocksdb::Status::InvalidArgument("index out of range");
}
std::string buf, value, sub_key;
- PutFixed64(&buf, metadata.head + index);
- InternalKey(ns_key, buf, metadata.version, storage_->IsSlotIdEncoded()).Encode(&sub_key);
+ PutFixed64(&buf, metadata.head_ + index);
+ InternalKey(ns_key, buf, metadata.version_, storage_->IsSlotIdEncoded()).Encode(&sub_key);
s = storage_->Get(rocksdb::ReadOptions(), sub_key, &value);
if (!s.ok()) {
return s;
@@ -475,11 +475,11 @@ rocksdb::Status List::lmoveOnSingleList(const rocksdb::Slice &src, bool src_left
elem->clear();
- uint64_t curr_index = src_left ? metadata.head : metadata.tail - 1;
+ uint64_t curr_index = src_left ? metadata.head_ : metadata.tail_ - 1;
std::string curr_index_buf;
PutFixed64(&curr_index_buf, curr_index);
std::string curr_sub_key;
- InternalKey(ns_key, curr_index_buf, metadata.version, storage_->IsSlotIdEncoded()).Encode(&curr_sub_key);
+ InternalKey(ns_key, curr_index_buf, metadata.version_, storage_->IsSlotIdEncoded()).Encode(&curr_sub_key);
s = storage_->Get(rocksdb::ReadOptions(), curr_sub_key, elem);
if (!s.ok()) {
return s;
@@ -490,7 +490,7 @@ rocksdb::Status List::lmoveOnSingleList(const rocksdb::Slice &src, bool src_left
return rocksdb::Status::OK();
}
- if (metadata.size == 1) {
+ if (metadata.size_ == 1) {
// if there is only one element in the list - do nothing, just get it
return rocksdb::Status::OK();
}
@@ -503,18 +503,18 @@ rocksdb::Status List::lmoveOnSingleList(const rocksdb::Slice &src, bool src_left
batch->Delete(curr_sub_key);
if (src_left) {
- ++metadata.head;
- ++metadata.tail;
+ ++metadata.head_;
+ ++metadata.tail_;
} else {
- --metadata.head;
- --metadata.tail;
+ --metadata.head_;
+ --metadata.tail_;
}
- uint64_t new_index = src_left ? metadata.tail - 1 : metadata.head;
+ uint64_t new_index = src_left ? metadata.tail_ - 1 : metadata.head_;
std::string new_index_buf;
PutFixed64(&new_index_buf, new_index);
std::string new_sub_key;
- InternalKey(ns_key, new_index_buf, metadata.version, storage_->IsSlotIdEncoded()).Encode(&new_sub_key);
+ InternalKey(ns_key, new_index_buf, metadata.version_, storage_->IsSlotIdEncoded()).Encode(&new_sub_key);
batch->Put(new_sub_key, *elem);
std::string bytes;
@@ -552,37 +552,37 @@ rocksdb::Status List::lmoveOnTwoLists(const rocksdb::Slice &src, const rocksdb::
src_left ? "left" : "right", dst_left ? "left" : "right"});
batch->PutLogData(log_data.Encode());
- uint64_t src_index = src_left ? src_metadata.head : src_metadata.tail - 1;
+ uint64_t src_index = src_left ? src_metadata.head_ : src_metadata.tail_ - 1;
std::string src_buf;
PutFixed64(&src_buf, src_index);
std::string src_sub_key;
- InternalKey(src_ns_key, src_buf, src_metadata.version, storage_->IsSlotIdEncoded()).Encode(&src_sub_key);
+ InternalKey(src_ns_key, src_buf, src_metadata.version_, storage_->IsSlotIdEncoded()).Encode(&src_sub_key);
s = storage_->Get(rocksdb::ReadOptions(), src_sub_key, elem);
if (!s.ok()) {
return s;
}
batch->Delete(src_sub_key);
- if (src_metadata.size == 1) {
+ if (src_metadata.size_ == 1) {
batch->Delete(metadata_cf_handle_, src_ns_key);
} else {
std::string bytes;
- src_metadata.size -= 1;
- src_left ? ++src_metadata.head : --src_metadata.tail;
+ src_metadata.size_ -= 1;
+ src_left ? ++src_metadata.head_ : --src_metadata.tail_;
src_metadata.Encode(&bytes);
batch->Put(metadata_cf_handle_, src_ns_key, bytes);
}
- uint64_t dst_index = dst_left ? dst_metadata.head - 1 : dst_metadata.tail;
+ uint64_t dst_index = dst_left ? dst_metadata.head_ - 1 : dst_metadata.tail_;
std::string dst_buf;
PutFixed64(&dst_buf, dst_index);
std::string dst_sub_key;
- InternalKey(dst_ns_key, dst_buf, dst_metadata.version, storage_->IsSlotIdEncoded()).Encode(&dst_sub_key);
+ InternalKey(dst_ns_key, dst_buf, dst_metadata.version_, storage_->IsSlotIdEncoded()).Encode(&dst_sub_key);
batch->Put(dst_sub_key, *elem);
- dst_left ? --dst_metadata.head : ++dst_metadata.tail;
+ dst_left ? --dst_metadata.head_ : ++dst_metadata.tail_;
std::string bytes;
- dst_metadata.size += 1;
+ dst_metadata.size_ += 1;
dst_metadata.Encode(&bytes);
batch->Put(metadata_cf_handle_, dst_ns_key, bytes);
@@ -600,8 +600,8 @@ rocksdb::Status List::Trim(const Slice &user_key, int start, int stop) {
rocksdb::Status s = GetMetadata(ns_key, &metadata);
if (!s.ok()) return s.IsNotFound() ? rocksdb::Status::OK() : s;
- if (start < 0) start += static_cast<int>(metadata.size);
- if (stop < 0) stop = static_cast<int>(metadata.size) >= -1 * stop ? static_cast<int>(metadata.size) + stop : -1;
+ if (start < 0) start += static_cast<int>(metadata.size_);
+ if (stop < 0) stop = static_cast<int>(metadata.size_) >= -1 * stop ? static_cast<int>(metadata.size_) + stop : -1;
// the result will be empty list when start > stop,
// or start is larger than the end of list
if (start > stop) {
@@ -613,31 +613,31 @@ rocksdb::Status List::Trim(const Slice &user_key, int start, int stop) {
WriteBatchLogData log_data(kRedisList, std::vector<std::string>{std::to_string(kRedisCmdLTrim), std::to_string(start),
std::to_string(stop)});
batch->PutLogData(log_data.Encode());
- uint64_t left_index = metadata.head + start;
- uint64_t right_index = metadata.head + stop + 1;
- for (uint64_t i = metadata.head; i < left_index; i++) {
+ uint64_t left_index = metadata.head_ + start;
+ uint64_t right_index = metadata.head_ + stop + 1;
+ for (uint64_t i = metadata.head_; i < left_index; i++) {
std::string buf;
PutFixed64(&buf, i);
std::string sub_key;
- InternalKey(ns_key, buf, metadata.version, storage_->IsSlotIdEncoded()).Encode(&sub_key);
+ InternalKey(ns_key, buf, metadata.version_, storage_->IsSlotIdEncoded()).Encode(&sub_key);
batch->Delete(sub_key);
- metadata.head++;
+ metadata.head_++;
trim_cnt++;
}
- auto tail = metadata.tail;
+ auto tail = metadata.tail_;
for (uint64_t i = right_index; i < tail; i++) {
std::string buf;
PutFixed64(&buf, i);
std::string sub_key;
- InternalKey(ns_key, buf, metadata.version, storage_->IsSlotIdEncoded()).Encode(&sub_key);
+ InternalKey(ns_key, buf, metadata.version_, storage_->IsSlotIdEncoded()).Encode(&sub_key);
batch->Delete(sub_key);
- metadata.tail--;
+ metadata.tail_--;
trim_cnt++;
}
- if (metadata.size >= trim_cnt) {
- metadata.size -= trim_cnt;
+ if (metadata.size_ >= trim_cnt) {
+ metadata.size_ -= trim_cnt;
} else {
- metadata.size = 0;
+ metadata.size_ = 0;
}
std::string bytes;
metadata.Encode(&bytes);
diff --git a/src/types/redis_set.cc b/src/types/redis_set.cc
index e7ff397f..de2fadac 100644
--- a/src/types/redis_set.cc
+++ b/src/types/redis_set.cc
@@ -43,10 +43,10 @@ rocksdb::Status Set::Overwrite(Slice user_key, const std::vector<std::string> &m
batch->PutLogData(log_data.Encode());
std::string sub_key;
for (const auto &member : members) {
- InternalKey(ns_key, member, metadata.version, storage_->IsSlotIdEncoded()).Encode(&sub_key);
+ InternalKey(ns_key, member, metadata.version_, storage_->IsSlotIdEncoded()).Encode(&sub_key);
batch->Put(sub_key, Slice());
}
- metadata.size = static_cast<uint32_t>(members.size());
+ metadata.size_ = static_cast<uint32_t>(members.size());
std::string bytes;
metadata.Encode(&bytes);
batch->Put(metadata_cf_handle_, ns_key, bytes);
@@ -70,14 +70,14 @@ rocksdb::Status Set::Add(const Slice &user_key, const std::vector<Slice> &member
batch->PutLogData(log_data.Encode());
std::string sub_key;
for (const auto &member : members) {
- InternalKey(ns_key, member, metadata.version, storage_->IsSlotIdEncoded()).Encode(&sub_key);
+ InternalKey(ns_key, member, metadata.version_, storage_->IsSlotIdEncoded()).Encode(&sub_key);
s = storage_->Get(rocksdb::ReadOptions(), sub_key, &value);
if (s.ok()) continue;
batch->Put(sub_key, Slice());
*ret += 1;
}
if (*ret > 0) {
- metadata.size += *ret;
+ metadata.size_ += *ret;
std::string bytes;
metadata.Encode(&bytes);
batch->Put(metadata_cf_handle_, ns_key, bytes);
@@ -101,15 +101,15 @@ rocksdb::Status Set::Remove(const Slice &user_key, const std::vector<Slice> &mem
WriteBatchLogData log_data(kRedisSet);
batch->PutLogData(log_data.Encode());
for (const auto &member : members) {
- InternalKey(ns_key, member, metadata.version, storage_->IsSlotIdEncoded()).Encode(&sub_key);
+ InternalKey(ns_key, member, metadata.version_, storage_->IsSlotIdEncoded()).Encode(&sub_key);
s = storage_->Get(rocksdb::ReadOptions(), sub_key, &value);
if (!s.ok()) continue;
batch->Delete(sub_key);
*ret += 1;
}
if (*ret > 0) {
- if (static_cast<int>(metadata.size) != *ret) {
- metadata.size -= *ret;
+ if (static_cast<int>(metadata.size_) != *ret) {
+ metadata.size_ -= *ret;
std::string bytes;
metadata.Encode(&bytes);
batch->Put(metadata_cf_handle_, ns_key, bytes);
@@ -128,7 +128,7 @@ rocksdb::Status Set::Card(const Slice &user_key, int *ret) {
SetMetadata metadata(false);
rocksdb::Status s = GetMetadata(ns_key, &metadata);
if (!s.ok()) return s.IsNotFound() ? rocksdb::Status::OK() : s;
- *ret = static_cast<int>(metadata.size);
+ *ret = static_cast<int>(metadata.size_);
return rocksdb::Status::OK();
}
@@ -143,8 +143,8 @@ rocksdb::Status Set::Members(const Slice &user_key, std::vector<std::string> *me
if (!s.ok()) return s.IsNotFound() ? rocksdb::Status::OK() : s;
std::string prefix, next_version_prefix;
- InternalKey(ns_key, "", metadata.version, storage_->IsSlotIdEncoded()).Encode(&prefix);
- InternalKey(ns_key, "", metadata.version + 1, storage_->IsSlotIdEncoded()).Encode(&next_version_prefix);
+ InternalKey(ns_key, "", metadata.version_, storage_->IsSlotIdEncoded()).Encode(&prefix);
+ InternalKey(ns_key, "", metadata.version_ + 1, storage_->IsSlotIdEncoded()).Encode(&next_version_prefix);
rocksdb::ReadOptions read_options;
LatestSnapShot ss(storage_);
@@ -184,7 +184,7 @@ rocksdb::Status Set::MIsMember(const Slice &user_key, const std::vector<Slice> &
read_options.snapshot = ss.GetSnapShot();
std::string sub_key, value;
for (const auto &member : members) {
- InternalKey(ns_key, member, metadata.version, storage_->IsSlotIdEncoded()).Encode(&sub_key);
+ InternalKey(ns_key, member, metadata.version_, storage_->IsSlotIdEncoded()).Encode(&sub_key);
s = storage_->Get(read_options, sub_key, &value);
if (!s.ok() && !s.IsNotFound()) return s;
if (s.IsNotFound()) {
@@ -216,8 +216,8 @@ rocksdb::Status Set::Take(const Slice &user_key, std::vector<std::string> *membe
batch->PutLogData(log_data.Encode());
std::string prefix, next_version_prefix;
- InternalKey(ns_key, "", metadata.version, storage_->IsSlotIdEncoded()).Encode(&prefix);
- InternalKey(ns_key, "", metadata.version + 1, storage_->IsSlotIdEncoded()).Encode(&next_version_prefix);
+ InternalKey(ns_key, "", metadata.version_, storage_->IsSlotIdEncoded()).Encode(&prefix);
+ InternalKey(ns_key, "", metadata.version_ + 1, storage_->IsSlotIdEncoded()).Encode(&next_version_prefix);
rocksdb::ReadOptions read_options;
LatestSnapShot ss(storage_);
@@ -234,7 +234,7 @@ rocksdb::Status Set::Take(const Slice &user_key, std::vector<std::string> *membe
if (++n >= count) break;
}
if (pop && n > 0) {
- metadata.size -= n;
+ metadata.size_ -= n;
std::string bytes;
metadata.Encode(&bytes);
batch->Put(metadata_cf_handle_, ns_key, bytes);
diff --git a/src/types/redis_sortedint.cc b/src/types/redis_sortedint.cc
index 208a4da8..cd1ed37b 100644
--- a/src/types/redis_sortedint.cc
+++ b/src/types/redis_sortedint.cc
@@ -51,14 +51,14 @@ rocksdb::Status Sortedint::Add(const Slice &user_key, const std::vector<uint64_t
for (const auto id : ids) {
std::string id_buf;
PutFixed64(&id_buf, id);
- InternalKey(ns_key, id_buf, metadata.version, storage_->IsSlotIdEncoded()).Encode(&sub_key);
+ InternalKey(ns_key, id_buf, metadata.version_, storage_->IsSlotIdEncoded()).Encode(&sub_key);
s = storage_->Get(rocksdb::ReadOptions(), sub_key, &value);
if (s.ok()) continue;
batch->Put(sub_key, Slice());
*ret += 1;
}
if (*ret > 0) {
- metadata.size += *ret;
+ metadata.size_ += *ret;
std::string bytes;
metadata.Encode(&bytes);
batch->Put(metadata_cf_handle_, ns_key, bytes);
@@ -84,14 +84,14 @@ rocksdb::Status Sortedint::Remove(const Slice &user_key, const std::vector<uint6
for (const auto id : ids) {
std::string id_buf;
PutFixed64(&id_buf, id);
- InternalKey(ns_key, id_buf, metadata.version, storage_->IsSlotIdEncoded()).Encode(&sub_key);
+ InternalKey(ns_key, id_buf, metadata.version_, storage_->IsSlotIdEncoded()).Encode(&sub_key);
s = storage_->Get(rocksdb::ReadOptions(), sub_key, &value);
if (!s.ok()) continue;
batch->Delete(sub_key);
*ret += 1;
}
if (*ret == 0) return rocksdb::Status::OK();
- metadata.size -= *ret;
+ metadata.size_ -= *ret;
std::string bytes;
metadata.Encode(&bytes);
batch->Put(metadata_cf_handle_, ns_key, bytes);
@@ -106,7 +106,7 @@ rocksdb::Status Sortedint::Card(const Slice &user_key, int *ret) {
SortedintMetadata metadata(false);
rocksdb::Status s = GetMetadata(ns_key, &metadata);
if (!s.ok()) return s.IsNotFound() ? rocksdb::Status::OK() : s;
- *ret = static_cast<int>(metadata.size);
+ *ret = static_cast<int>(metadata.size_);
return rocksdb::Status::OK();
}
@@ -127,9 +127,9 @@ rocksdb::Status Sortedint::Range(const Slice &user_key, uint64_t cursor_id, uint
start_id = std::numeric_limits<uint64_t>::max();
}
PutFixed64(&start_buf, start_id);
- InternalKey(ns_key, start_buf, metadata.version, storage_->IsSlotIdEncoded()).Encode(&start_key);
- InternalKey(ns_key, "", metadata.version, storage_->IsSlotIdEncoded()).Encode(&prefix);
- InternalKey(ns_key, "", metadata.version + 1, storage_->IsSlotIdEncoded()).Encode(&next_version_prefix);
+ InternalKey(ns_key, start_buf, metadata.version_, storage_->IsSlotIdEncoded()).Encode(&start_key);
+ InternalKey(ns_key, "", metadata.version_, storage_->IsSlotIdEncoded()).Encode(&prefix);
+ InternalKey(ns_key, "", metadata.version_ + 1, storage_->IsSlotIdEncoded()).Encode(&next_version_prefix);
rocksdb::ReadOptions read_options;
LatestSnapShot ss(storage_);
@@ -167,10 +167,10 @@ rocksdb::Status Sortedint::RangeByValue(const Slice &user_key, SortedintRangeSpe
if (!s.ok()) return s.IsNotFound() ? rocksdb::Status::OK() : s;
std::string start_buf, start_key, prefix_key, next_version_prefix_key;
- PutFixed64(&start_buf, spec.reversed ? spec.max : spec.min);
- InternalKey(ns_key, start_buf, metadata.version, storage_->IsSlotIdEncoded()).Encode(&start_key);
- InternalKey(ns_key, "", metadata.version, storage_->IsSlotIdEncoded()).Encode(&prefix_key);
- InternalKey(ns_key, "", metadata.version + 1, storage_->IsSlotIdEncoded()).Encode(&next_version_prefix_key);
+ PutFixed64(&start_buf, spec.reversed_ ? spec.max_ : spec.min_);
+ InternalKey(ns_key, start_buf, metadata.version_, storage_->IsSlotIdEncoded()).Encode(&start_key);
+ InternalKey(ns_key, "", metadata.version_, storage_->IsSlotIdEncoded()).Encode(&prefix_key);
+ InternalKey(ns_key, "", metadata.version_ + 1, storage_->IsSlotIdEncoded()).Encode(&next_version_prefix_key);
rocksdb::ReadOptions read_options;
LatestSnapShot ss(storage_);
@@ -183,28 +183,28 @@ rocksdb::Status Sortedint::RangeByValue(const Slice &user_key, SortedintRangeSpe
int pos = 0;
auto iter = DBUtil::UniqueIterator(storage_, read_options);
- if (!spec.reversed) {
+ if (!spec.reversed_) {
iter->Seek(start_key);
} else {
iter->SeekForPrev(start_key);
}
uint64_t id = 0;
- for (; iter->Valid() && iter->key().starts_with(prefix_key); !spec.reversed ? iter->Next() : iter->Prev()) {
+ for (; iter->Valid() && iter->key().starts_with(prefix_key); !spec.reversed_ ? iter->Next() : iter->Prev()) {
InternalKey ikey(iter->key(), storage_->IsSlotIdEncoded());
Slice sub_key = ikey.GetSubKey();
GetFixed64(&sub_key, &id);
- if (spec.reversed) {
- if ((spec.minex && id == spec.min) || id < spec.min) break;
- if ((spec.maxex && id == spec.max) || id > spec.max) continue;
+ if (spec.reversed_) {
+ if ((spec.minex_ && id == spec.min_) || id < spec.min_) break;
+ if ((spec.maxex_ && id == spec.max_) || id > spec.max_) continue;
} else {
- if ((spec.minex && id == spec.min) || id < spec.min) continue;
- if ((spec.maxex && id == spec.max) || id > spec.max) break;
+ if ((spec.minex_ && id == spec.min_) || id < spec.min_) continue;
+ if ((spec.maxex_ && id == spec.max_) || id > spec.max_) break;
}
- if (spec.offset >= 0 && pos++ < spec.offset) continue;
+ if (spec.offset_ >= 0 && pos++ < spec.offset_) continue;
if (ids) ids->emplace_back(id);
if (size) *size += 1;
- if (spec.count > 0 && ids && ids->size() >= static_cast<unsigned>(spec.count)) break;
+ if (spec.count_ > 0 && ids && ids->size() >= static_cast<unsigned>(spec.count_)) break;
}
return rocksdb::Status::OK();
}
@@ -224,7 +224,7 @@ rocksdb::Status Sortedint::MExist(const Slice &user_key, const std::vector<uint6
for (const auto id : ids) {
std::string id_buf;
PutFixed64(&id_buf, id);
- InternalKey(ns_key, id_buf, metadata.version, storage_->IsSlotIdEncoded()).Encode(&sub_key);
+ InternalKey(ns_key, id_buf, metadata.version_, storage_->IsSlotIdEncoded()).Encode(&sub_key);
s = storage_->Get(read_options, sub_key, &value);
if (!s.ok() && !s.IsNotFound()) return s;
if (s.IsNotFound()) {
@@ -242,33 +242,33 @@ Status Sortedint::ParseRangeSpec(const std::string &min, const std::string &max,
}
if (min == "-inf") {
- spec->min = std::numeric_limits<uint64_t>::lowest();
+ spec->min_ = std::numeric_limits<uint64_t>::lowest();
} else {
const char *sptr = min.data();
if (!min.empty() && min[0] == '(') {
- spec->minex = true;
+ spec->minex_ = true;
sptr++;
}
auto parse_result = ParseInt<uint64_t>(sptr, 10);
if (!parse_result) {
return {Status::NotOK, "the min isn't integer"};
}
- spec->min = *parse_result;
+ spec->min_ = *parse_result;
}
if (max == "+inf") {
- spec->max = std::numeric_limits<uint64_t>::max();
+ spec->max_ = std::numeric_limits<uint64_t>::max();
} else {
const char *sptr = max.data();
if (!max.empty() && max[0] == '(') {
- spec->maxex = true;
+ spec->maxex_ = true;
sptr++;
}
auto parse_result = ParseInt<uint64_t>(sptr, 10);
if (!parse_result) {
return {Status::NotOK, "the max isn't integer"};
}
- spec->max = *parse_result;
+ spec->max_ = *parse_result;
}
return Status::OK();
}
diff --git a/src/types/redis_sortedint.h b/src/types/redis_sortedint.h
index 7011bbbe..e6eb538f 100644
--- a/src/types/redis_sortedint.h
+++ b/src/types/redis_sortedint.h
@@ -28,10 +28,10 @@
#include "storage/redis_metadata.h"
struct SortedintRangeSpec {
- uint64_t min = std::numeric_limits<uint64_t>::lowest(), max = std::numeric_limits<uint64_t>::max();
- bool minex = false, maxex = false; /* are min or max exclusive */
- int offset = -1, count = -1;
- bool reversed = false;
+ uint64_t min_ = std::numeric_limits<uint64_t>::lowest(), max_ = std::numeric_limits<uint64_t>::max();
+ bool minex_ = false, maxex_ = false; /* are min or max exclusive */
+ int offset_ = -1, count_ = -1;
+ bool reversed_ = false;
SortedintRangeSpec() = default;
};
diff --git a/src/types/redis_stream.cc b/src/types/redis_stream.cc
index 4bd128af..2621004c 100644
--- a/src/types/redis_stream.cc
+++ b/src/types/redis_stream.cc
@@ -58,10 +58,10 @@ rocksdb::Status Stream::GetLastGeneratedID(const Slice &stream_name, StreamEntry
}
if (s.IsNotFound()) {
- id->ms = 0;
- id->seq = 0;
+ id->ms_ = 0;
+ id->seq_ = 0;
} else {
- *id = metadata.last_generated_id;
+ *id = metadata.last_generated_id_;
}
return rocksdb::Status::OK();
@@ -71,18 +71,18 @@ StreamEntryID Stream::entryIDFromInternalKey(const rocksdb::Slice &key) const {
InternalKey ikey(key, storage_->IsSlotIdEncoded());
Slice entry_id = ikey.GetSubKey();
StreamEntryID id;
- GetFixed64(&entry_id, &id.ms);
- GetFixed64(&entry_id, &id.seq);
+ GetFixed64(&entry_id, &id.ms_);
+ GetFixed64(&entry_id, &id.seq_);
return id;
}
std::string Stream::internalKeyFromEntryID(const std::string &ns_key, const StreamMetadata &metadata,
const StreamEntryID &id) const {
std::string sub_key;
- PutFixed64(&sub_key, id.ms);
- PutFixed64(&sub_key, id.seq);
+ PutFixed64(&sub_key, id.ms_);
+ PutFixed64(&sub_key, id.seq_);
std::string entry_key;
- InternalKey(ns_key, sub_key, metadata.version, storage_->IsSlotIdEncoded()).Encode(&entry_key);
+ InternalKey(ns_key, sub_key, metadata.version_, storage_->IsSlotIdEncoded()).Encode(&entry_key);
return entry_key;
}
@@ -104,7 +104,7 @@ rocksdb::Status Stream::Add(const Slice &stream_name, const StreamAddOptions &op
rocksdb::Status s = GetMetadata(ns_key, &metadata);
if (!s.ok() && !s.IsNotFound()) return s;
- if (s.IsNotFound() && options.nomkstream) {
+ if (s.IsNotFound() && options.nomkstream_) {
return s;
}
@@ -121,21 +121,21 @@ rocksdb::Status Stream::Add(const Slice &stream_name, const StreamAddOptions &op
bool should_add = true;
// trim the stream before adding a new entry to provide atomic XADD + XTRIM
- if (options.trim_options.strategy != StreamTrimStrategy::None) {
- StreamTrimOptions trim_options = options.trim_options;
- if (trim_options.strategy == StreamTrimStrategy::MaxLen) {
+ if (options.trim_options_.strategy_ != StreamTrimStrategy::None) {
+ StreamTrimOptions trim_options = options.trim_options_;
+ if (trim_options.strategy_ == StreamTrimStrategy::MaxLen) {
// because one entry will be added, we can trim up to (MAXLEN-1) if MAXLEN was specified
- trim_options.max_len = options.trim_options.max_len > 0 ? options.trim_options.max_len - 1 : 0;
+ trim_options.max_len_ = options.trim_options_.max_len_ > 0 ? options.trim_options_.max_len_ - 1 : 0;
}
trim(ns_key, trim_options, &metadata, batch->GetWriteBatch());
- if (trim_options.strategy == StreamTrimStrategy::MinID && next_entry_id < trim_options.min_id) {
+ if (trim_options.strategy_ == StreamTrimStrategy::MinID && next_entry_id < trim_options.min_id_) {
// there is no sense to add this element because it would be removed, so just modify metadata and return it's ID
should_add = false;
}
- if (trim_options.strategy == StreamTrimStrategy::MaxLen && options.trim_options.max_len == 0) {
+ if (trim_options.strategy_ == StreamTrimStrategy::MaxLen && options.trim_options_.max_len_ == 0) {
// there is no sense to add this element because it would be removed, so just modify metadata and return it's ID
should_add = false;
}
@@ -145,20 +145,20 @@ rocksdb::Status Stream::Add(const Slice &stream_name, const StreamAddOptions &op
std::string entry_key = internalKeyFromEntryID(ns_key, metadata, next_entry_id);
batch->Put(stream_cf_handle_, entry_key, entry_value);
- metadata.last_generated_id = next_entry_id;
- metadata.last_entry_id = next_entry_id;
- metadata.size += 1;
+ metadata.last_generated_id_ = next_entry_id;
+ metadata.last_entry_id_ = next_entry_id;
+ metadata.size_ += 1;
- if (metadata.size == 1) {
- metadata.first_entry_id = next_entry_id;
- metadata.recorded_first_entry_id = next_entry_id;
+ if (metadata.size_ == 1) {
+ metadata.first_entry_id_ = next_entry_id;
+ metadata.recorded_first_entry_id_ = next_entry_id;
}
} else {
- metadata.last_generated_id = next_entry_id;
- metadata.max_deleted_entry_id = next_entry_id;
+ metadata.last_generated_id_ = next_entry_id;
+ metadata.max_deleted_entry_id_ = next_entry_id;
}
- metadata.entries_added += 1;
+ metadata.entries_added_ += 1;
std::string metadata_bytes;
metadata.Encode(&metadata_bytes);
@@ -171,51 +171,51 @@ rocksdb::Status Stream::Add(const Slice &stream_name, const StreamAddOptions &op
rocksdb::Status Stream::getNextEntryID(const StreamMetadata &metadata, const StreamAddOptions &options,
bool first_entry, StreamEntryID *next_entry_id) {
- if (options.with_entry_id) {
- if (options.entry_id.ms == 0 && !options.entry_id.any_seq_number && options.entry_id.seq == 0) {
+ if (options.with_entry_id_) {
+ if (options.entry_id_.ms_ == 0 && !options.entry_id_.any_seq_number_ && options.entry_id_.seq_ == 0) {
return rocksdb::Status::InvalidArgument(errEntryIdOutOfRange);
}
- if (metadata.last_generated_id.ms == UINT64_MAX && metadata.last_generated_id.seq == UINT64_MAX) {
+ if (metadata.last_generated_id_.ms_ == UINT64_MAX && metadata.last_generated_id_.seq_ == UINT64_MAX) {
return rocksdb::Status::InvalidArgument(errStreamExhaustedEntryId);
}
if (!first_entry) {
- if (metadata.last_generated_id.ms > options.entry_id.ms) {
+ if (metadata.last_generated_id_.ms_ > options.entry_id_.ms_) {
return rocksdb::Status::InvalidArgument(errAddEntryIdSmallerThanLastGenerated);
}
- if (metadata.last_generated_id.ms == options.entry_id.ms) {
- if (!options.entry_id.any_seq_number && metadata.last_generated_id.seq >= options.entry_id.seq) {
+ if (metadata.last_generated_id_.ms_ == options.entry_id_.ms_) {
+ if (!options.entry_id_.any_seq_number_ && metadata.last_generated_id_.seq_ >= options.entry_id_.seq_) {
return rocksdb::Status::InvalidArgument(errAddEntryIdSmallerThanLastGenerated);
}
- if (options.entry_id.any_seq_number && metadata.last_generated_id.seq == UINT64_MAX) {
+ if (options.entry_id_.any_seq_number_ && metadata.last_generated_id_.seq_ == UINT64_MAX) {
return rocksdb::Status::InvalidArgument(
"Elements are too large to be stored"); // Redis responds with exactly this message
}
}
- if (options.entry_id.any_seq_number) {
- if (options.entry_id.ms == metadata.last_generated_id.ms) {
- next_entry_id->seq = metadata.last_generated_id.seq + 1;
+ if (options.entry_id_.any_seq_number_) {
+ if (options.entry_id_.ms_ == metadata.last_generated_id_.ms_) {
+ next_entry_id->seq_ = metadata.last_generated_id_.seq_ + 1;
} else {
- next_entry_id->seq = 0;
+ next_entry_id->seq_ = 0;
}
} else {
- next_entry_id->seq = options.entry_id.seq;
+ next_entry_id->seq_ = options.entry_id_.seq_;
}
} else {
- if (options.entry_id.any_seq_number) {
- next_entry_id->seq = options.entry_id.ms != 0 ? 0 : 1;
+ if (options.entry_id_.any_seq_number_) {
+ next_entry_id->seq_ = options.entry_id_.ms_ != 0 ? 0 : 1;
} else {
- next_entry_id->seq = options.entry_id.seq;
+ next_entry_id->seq_ = options.entry_id_.seq_;
}
}
- next_entry_id->ms = options.entry_id.ms;
+ next_entry_id->ms_ = options.entry_id_.ms_;
return rocksdb::Status::OK();
} else {
- return GetNextStreamEntryID(metadata.last_generated_id, next_entry_id);
+ return GetNextStreamEntryID(metadata.last_generated_id_, next_entry_id);
}
}
@@ -238,9 +238,9 @@ rocksdb::Status Stream::DeleteEntries(const rocksdb::Slice &stream_name, const s
batch->PutLogData(log_data.Encode());
std::string next_version_prefix_key;
- InternalKey(ns_key, "", metadata.version + 1, storage_->IsSlotIdEncoded()).Encode(&next_version_prefix_key);
+ InternalKey(ns_key, "", metadata.version_ + 1, storage_->IsSlotIdEncoded()).Encode(&next_version_prefix_key);
std::string prefix_key;
- InternalKey(ns_key, "", metadata.version, storage_->IsSlotIdEncoded()).Encode(&prefix_key);
+ InternalKey(ns_key, "", metadata.version_, storage_->IsSlotIdEncoded()).Encode(&prefix_key);
rocksdb::ReadOptions read_options;
LatestSnapShot ss(storage_);
@@ -261,43 +261,43 @@ rocksdb::Status Stream::DeleteEntries(const rocksdb::Slice &stream_name, const s
*ret += 1;
batch->Delete(stream_cf_handle_, entry_key);
- if (metadata.max_deleted_entry_id < id) {
- metadata.max_deleted_entry_id = id;
+ if (metadata.max_deleted_entry_id_ < id) {
+ metadata.max_deleted_entry_id_ = id;
}
- if (*ret == metadata.size) {
- metadata.first_entry_id.Clear();
- metadata.last_entry_id.Clear();
- metadata.recorded_first_entry_id.Clear();
+ if (*ret == metadata.size_) {
+ metadata.first_entry_id_.Clear();
+ metadata.last_entry_id_.Clear();
+ metadata.recorded_first_entry_id_.Clear();
break;
}
- if (id == metadata.first_entry_id) {
+ if (id == metadata.first_entry_id_) {
iter->Seek(entry_key);
iter->Next();
if (iter->Valid()) {
- metadata.first_entry_id = entryIDFromInternalKey(iter->key());
- metadata.recorded_first_entry_id = metadata.first_entry_id;
+ metadata.first_entry_id_ = entryIDFromInternalKey(iter->key());
+ metadata.recorded_first_entry_id_ = metadata.first_entry_id_;
} else {
- metadata.first_entry_id.Clear();
- metadata.recorded_first_entry_id.Clear();
+ metadata.first_entry_id_.Clear();
+ metadata.recorded_first_entry_id_.Clear();
}
}
- if (id == metadata.last_entry_id) {
+ if (id == metadata.last_entry_id_) {
iter->Seek(entry_key);
iter->Prev();
if (iter->Valid()) {
- metadata.last_entry_id = entryIDFromInternalKey(iter->key());
+ metadata.last_entry_id_ = entryIDFromInternalKey(iter->key());
} else {
- metadata.last_entry_id.Clear();
+ metadata.last_entry_id_.Clear();
}
}
}
}
if (*ret > 0) {
- metadata.size -= *ret;
+ metadata.size_ -= *ret;
std::string bytes;
metadata.Encode(&bytes);
@@ -325,31 +325,31 @@ rocksdb::Status Stream::Len(const rocksdb::Slice &stream_name, const StreamLenOp
return s.IsNotFound() ? rocksdb::Status::OK() : s;
}
- if (!options.with_entry_id) {
- *ret = metadata.size;
+ if (!options.with_entry_id_) {
+ *ret = metadata.size_;
return rocksdb::Status::OK();
}
- if (options.entry_id > metadata.last_entry_id) {
- *ret = options.to_first ? metadata.size : 0;
+ if (options.entry_id_ > metadata.last_entry_id_) {
+ *ret = options.to_first_ ? metadata.size_ : 0;
return rocksdb::Status::OK();
}
- if (options.entry_id < metadata.first_entry_id) {
- *ret = options.to_first ? 0 : metadata.size;
+ if (options.entry_id_ < metadata.first_entry_id_) {
+ *ret = options.to_first_ ? 0 : metadata.size_;
return rocksdb::Status::OK();
}
- if ((!options.to_first && options.entry_id == metadata.first_entry_id) ||
- (options.to_first && options.entry_id == metadata.last_entry_id)) {
- *ret = metadata.size - 1;
+ if ((!options.to_first_ && options.entry_id_ == metadata.first_entry_id_) ||
+ (options.to_first_ && options.entry_id_ == metadata.last_entry_id_)) {
+ *ret = metadata.size_ - 1;
return rocksdb::Status::OK();
}
std::string prefix_key;
- InternalKey(ns_key, "", metadata.version, storage_->IsSlotIdEncoded()).Encode(&prefix_key);
+ InternalKey(ns_key, "", metadata.version_, storage_->IsSlotIdEncoded()).Encode(&prefix_key);
std::string next_version_prefix_key;
- InternalKey(ns_key, "", metadata.version + 1, storage_->IsSlotIdEncoded()).Encode(&next_version_prefix_key);
+ InternalKey(ns_key, "", metadata.version_ + 1, storage_->IsSlotIdEncoded()).Encode(&next_version_prefix_key);
rocksdb::ReadOptions read_options;
LatestSnapShot ss(storage_);
@@ -361,20 +361,20 @@ rocksdb::Status Stream::Len(const rocksdb::Slice &stream_name, const StreamLenOp
storage_->SetReadOptions(read_options);
auto iter = DBUtil::UniqueIterator(storage_, read_options, stream_cf_handle_);
- std::string start_key = internalKeyFromEntryID(ns_key, metadata, options.entry_id);
+ std::string start_key = internalKeyFromEntryID(ns_key, metadata, options.entry_id_);
iter->Seek(start_key);
if (!iter->Valid()) {
return rocksdb::Status::OK();
}
- if (options.to_first) {
+ if (options.to_first_) {
iter->Prev();
} else if (iter->key().ToString() == start_key) {
iter->Next();
}
- for (; iter->Valid(); options.to_first ? iter->Prev() : iter->Next()) {
+ for (; iter->Valid(); options.to_first_ ? iter->Prev() : iter->Next()) {
*ret += 1;
}
@@ -383,11 +383,11 @@ rocksdb::Status Stream::Len(const rocksdb::Slice &stream_name, const StreamLenOp
rocksdb::Status Stream::range(const std::string &ns_key, const StreamMetadata &metadata,
const StreamRangeOptions &options, std::vector<StreamEntry> *entries) const {
- std::string start_key = internalKeyFromEntryID(ns_key, metadata, options.start);
- std::string end_key = internalKeyFromEntryID(ns_key, metadata, options.end);
+ std::string start_key = internalKeyFromEntryID(ns_key, metadata, options.start_);
+ std::string end_key = internalKeyFromEntryID(ns_key, metadata, options.end_);
if (start_key == end_key) {
- if (options.exclude_start || options.exclude_end) {
+ if (options.exclude_start_ || options.exclude_end_) {
return rocksdb::Status::OK();
}
@@ -403,18 +403,18 @@ rocksdb::Status Stream::range(const std::string &ns_key, const StreamMetadata &m
return rocksdb::Status::InvalidArgument(rv.Msg());
}
- entries->emplace_back(options.start.ToString(), std::move(values));
+ entries->emplace_back(options.start_.ToString(), std::move(values));
return rocksdb::Status::OK();
}
- if ((!options.reverse && options.end < options.start) || (options.reverse && options.start < options.end)) {
+ if ((!options.reverse_ && options.end_ < options.start_) || (options.reverse_ && options.start_ < options.end_)) {
return rocksdb::Status::OK();
}
std::string next_version_prefix_key;
- InternalKey(ns_key, "", metadata.version + 1, storage_->IsSlotIdEncoded()).Encode(&next_version_prefix_key);
+ InternalKey(ns_key, "", metadata.version_ + 1, storage_->IsSlotIdEncoded()).Encode(&next_version_prefix_key);
std::string prefix_key;
- InternalKey(ns_key, "", metadata.version, storage_->IsSlotIdEncoded()).Encode(&prefix_key);
+ InternalKey(ns_key, "", metadata.version_, storage_->IsSlotIdEncoded()).Encode(&prefix_key);
rocksdb::ReadOptions read_options;
LatestSnapShot ss(storage_);
@@ -427,17 +427,17 @@ rocksdb::Status Stream::range(const std::string &ns_key, const StreamMetadata &m
auto iter = DBUtil::UniqueIterator(storage_, read_options, stream_cf_handle_);
iter->Seek(start_key);
- if (options.reverse && (!iter->Valid() || iter->key().ToString() != start_key)) {
+ if (options.reverse_ && (!iter->Valid() || iter->key().ToString() != start_key)) {
iter->SeekForPrev(start_key);
}
- for (; iter->Valid() && (options.reverse ? iter->key().ToString() >= end_key : iter->key().ToString() <= end_key);
- options.reverse ? iter->Prev() : iter->Next()) {
- if (options.exclude_start && iter->key().ToString() == start_key) {
+ for (; iter->Valid() && (options.reverse_ ? iter->key().ToString() >= end_key : iter->key().ToString() <= end_key);
+ options.reverse_ ? iter->Prev() : iter->Next()) {
+ if (options.exclude_start_ && iter->key().ToString() == start_key) {
continue;
}
- if (options.exclude_end && iter->key().ToString() == end_key) {
+ if (options.exclude_end_ && iter->key().ToString() == end_key) {
break;
}
@@ -449,7 +449,7 @@ rocksdb::Status Stream::range(const std::string &ns_key, const StreamMetadata &m
entries->emplace_back(entryIDFromInternalKey(iter->key()).ToString(), std::move(values));
- if (options.with_count && entries->size() == options.count) {
+ if (options.with_count_ && entries->size() == options.count_) {
break;
}
}
@@ -472,40 +472,40 @@ rocksdb::Status Stream::GetStreamInfo(const rocksdb::Slice &stream_name, bool fu
rocksdb::Status s = GetMetadata(ns_key, &metadata);
if (!s.ok()) return s;
- info->size = metadata.size;
- info->entries_added = metadata.entries_added;
- info->last_generated_id = metadata.last_generated_id;
- info->max_deleted_entry_id = metadata.max_deleted_entry_id;
- info->recorded_first_entry_id = metadata.recorded_first_entry_id;
+ info->size_ = metadata.size_;
+ info->entries_added_ = metadata.entries_added_;
+ info->last_generated_id_ = metadata.last_generated_id_;
+ info->max_deleted_entry_id_ = metadata.max_deleted_entry_id_;
+ info->recorded_first_entry_id_ = metadata.recorded_first_entry_id_;
- if (metadata.size == 0) {
+ if (metadata.size_ == 0) {
return rocksdb::Status::OK();
}
if (full) {
- uint64_t need_entries = metadata.size;
- if (count != 0 && count < metadata.size) {
+ uint64_t need_entries = metadata.size_;
+ if (count != 0 && count < metadata.size_) {
need_entries = count;
}
- info->entries.reserve(need_entries);
+ info->entries_.reserve(need_entries);
StreamRangeOptions options;
- options.start = metadata.first_entry_id;
- options.end = metadata.last_entry_id;
- options.with_count = true;
- options.count = need_entries;
- options.reverse = false;
- options.exclude_start = false;
- options.exclude_end = false;
-
- s = range(ns_key, metadata, options, &info->entries);
+ options.start_ = metadata.first_entry_id_;
+ options.end_ = metadata.last_entry_id_;
+ options.with_count_ = true;
+ options.count_ = need_entries;
+ options.reverse_ = false;
+ options.exclude_start_ = false;
+ options.exclude_end_ = false;
+
+ s = range(ns_key, metadata, options, &info->entries_);
if (!s.ok()) {
return s;
}
} else {
std::string first_value;
- s = getEntryRawValue(ns_key, metadata, metadata.first_entry_id, &first_value);
+ s = getEntryRawValue(ns_key, metadata, metadata.first_entry_id_, &first_value);
if (!s.ok()) {
return s;
}
@@ -516,10 +516,10 @@ rocksdb::Status Stream::GetStreamInfo(const rocksdb::Slice &stream_name, bool fu
return rocksdb::Status::InvalidArgument(rv.Msg());
}
- info->first_entry = std::make_unique<StreamEntry>(metadata.first_entry_id.ToString(), std::move(values));
+ info->first_entry_ = std::make_unique<StreamEntry>(metadata.first_entry_id_.ToString(), std::move(values));
std::string last_value;
- s = getEntryRawValue(ns_key, metadata, metadata.last_entry_id, &last_value);
+ s = getEntryRawValue(ns_key, metadata, metadata.last_entry_id_, &last_value);
if (!s.ok()) {
return s;
}
@@ -529,7 +529,7 @@ rocksdb::Status Stream::GetStreamInfo(const rocksdb::Slice &stream_name, bool fu
return rocksdb::Status::InvalidArgument(rv.Msg());
}
- info->last_entry = std::make_unique<StreamEntry>(metadata.last_entry_id.ToString(), std::move(values));
+ info->last_entry_ = std::make_unique<StreamEntry>(metadata.last_entry_id_.ToString(), std::move(values));
}
return rocksdb::Status::OK();
@@ -539,15 +539,15 @@ rocksdb::Status Stream::Range(const Slice &stream_name, const StreamRangeOptions
std::vector<StreamEntry> *entries) {
entries->clear();
- if (options.with_count && options.count == 0) {
+ if (options.with_count_ && options.count_ == 0) {
return rocksdb::Status::OK();
}
- if (options.exclude_start && options.start.IsMaximum()) {
+ if (options.exclude_start_ && options.start_.IsMaximum()) {
return rocksdb::Status::InvalidArgument("invalid start ID for the interval");
}
- if (options.exclude_end && options.end.IsMinimum()) {
+ if (options.exclude_end_ && options.end_.IsMinimum()) {
return rocksdb::Status::InvalidArgument("invalid end ID for the interval");
}
@@ -566,7 +566,7 @@ rocksdb::Status Stream::Range(const Slice &stream_name, const StreamRangeOptions
rocksdb::Status Stream::Trim(const rocksdb::Slice &stream_name, const StreamTrimOptions &options, uint64_t *ret) {
*ret = 0;
- if (options.strategy == StreamTrimStrategy::None) {
+ if (options.strategy_ == StreamTrimStrategy::None) {
return rocksdb::Status::OK();
}
@@ -600,24 +600,24 @@ rocksdb::Status Stream::Trim(const rocksdb::Slice &stream_name, const StreamTrim
uint64_t Stream::trim(const std::string &ns_key, const StreamTrimOptions &options, StreamMetadata *metadata,
rocksdb::WriteBatch *batch) {
- if (metadata->size == 0) {
+ if (metadata->size_ == 0) {
return 0;
}
- if (options.strategy == StreamTrimStrategy::MaxLen && metadata->size <= options.max_len) {
+ if (options.strategy_ == StreamTrimStrategy::MaxLen && metadata->size_ <= options.max_len_) {
return 0;
}
- if (options.strategy == StreamTrimStrategy::MinID && metadata->first_entry_id >= options.min_id) {
+ if (options.strategy_ == StreamTrimStrategy::MinID && metadata->first_entry_id_ >= options.min_id_) {
return 0;
}
uint64_t ret = 0;
std::string next_version_prefix_key;
- InternalKey(ns_key, "", metadata->version + 1, storage_->IsSlotIdEncoded()).Encode(&next_version_prefix_key);
+ InternalKey(ns_key, "", metadata->version_ + 1, storage_->IsSlotIdEncoded()).Encode(&next_version_prefix_key);
std::string prefix_key;
- InternalKey(ns_key, "", metadata->version, storage_->IsSlotIdEncoded()).Encode(&prefix_key);
+ InternalKey(ns_key, "", metadata->version_, storage_->IsSlotIdEncoded()).Encode(&prefix_key);
rocksdb::ReadOptions read_options;
LatestSnapShot ss(storage_);
@@ -629,44 +629,44 @@ uint64_t Stream::trim(const std::string &ns_key, const StreamTrimOptions &option
storage_->SetReadOptions(read_options);
auto iter = DBUtil::UniqueIterator(storage_, read_options, stream_cf_handle_);
- std::string start_key = internalKeyFromEntryID(ns_key, *metadata, metadata->first_entry_id);
+ std::string start_key = internalKeyFromEntryID(ns_key, *metadata, metadata->first_entry_id_);
iter->Seek(start_key);
std::string last_deleted;
- while (iter->Valid() && metadata->size > 0) {
- if (options.strategy == StreamTrimStrategy::MaxLen && metadata->size <= options.max_len) {
+ while (iter->Valid() && metadata->size_ > 0) {
+ if (options.strategy_ == StreamTrimStrategy::MaxLen && metadata->size_ <= options.max_len_) {
break;
}
- if (options.strategy == StreamTrimStrategy::MinID && metadata->first_entry_id >= options.min_id) {
+ if (options.strategy_ == StreamTrimStrategy::MinID && metadata->first_entry_id_ >= options.min_id_) {
break;
}
batch->Delete(stream_cf_handle_, iter->key());
ret += 1;
- metadata->size -= 1;
+ metadata->size_ -= 1;
last_deleted = iter->key().ToString();
iter->Next();
if (iter->Valid()) {
- metadata->first_entry_id = entryIDFromInternalKey(iter->key());
- metadata->recorded_first_entry_id = metadata->first_entry_id;
+ metadata->first_entry_id_ = entryIDFromInternalKey(iter->key());
+ metadata->recorded_first_entry_id_ = metadata->first_entry_id_;
} else {
- metadata->first_entry_id.Clear();
- metadata->recorded_first_entry_id.Clear();
+ metadata->first_entry_id_.Clear();
+ metadata->recorded_first_entry_id_.Clear();
}
}
- if (metadata->size == 0) {
- metadata->first_entry_id.Clear();
- metadata->last_entry_id.Clear();
- metadata->recorded_first_entry_id.Clear();
+ if (metadata->size_ == 0) {
+ metadata->first_entry_id_.Clear();
+ metadata->last_entry_id_.Clear();
+ metadata->recorded_first_entry_id_.Clear();
}
if (ret > 0) {
- metadata->max_deleted_entry_id = entryIDFromInternalKey(last_deleted);
+ metadata->max_deleted_entry_id_ = entryIDFromInternalKey(last_deleted);
}
return ret;
@@ -694,7 +694,7 @@ rocksdb::Status Stream::SetId(const Slice &stream_name, const StreamEntryID &las
return rocksdb::Status::InvalidArgument(errEntriesAddedNotSpecifiedForEmptyStream);
}
- if (!max_deleted_id || (max_deleted_id->ms == 0 && max_deleted_id->seq == 0)) {
+ if (!max_deleted_id || (max_deleted_id->ms_ == 0 && max_deleted_id->seq_ == 0)) {
return rocksdb::Status::InvalidArgument(errMaxDeletedIdNotSpecifiedForEmptyStream);
}
@@ -702,20 +702,20 @@ rocksdb::Status Stream::SetId(const Slice &stream_name, const StreamEntryID &las
metadata = StreamMetadata();
}
- if (metadata.size > 0 && last_generated_id < metadata.last_generated_id) {
+ if (metadata.size_ > 0 && last_generated_id < metadata.last_generated_id_) {
return rocksdb::Status::InvalidArgument(errSetEntryIdSmallerThanLastGenerated);
}
- if (metadata.size > 0 && entries_added && entries_added < metadata.size) {
+ if (metadata.size_ > 0 && entries_added && entries_added < metadata.size_) {
return rocksdb::Status::InvalidArgument(errEntriesAddedSmallerThanStreamSize);
}
- metadata.last_generated_id = last_generated_id;
+ metadata.last_generated_id_ = last_generated_id;
if (entries_added) {
- metadata.entries_added = *entries_added;
+ metadata.entries_added_ = *entries_added;
}
- if (max_deleted_id && (max_deleted_id->ms != 0 || max_deleted_id->seq != 0)) {
- metadata.max_deleted_entry_id = *max_deleted_id;
+ if (max_deleted_id && (max_deleted_id->ms_ != 0 || max_deleted_id->seq_ != 0)) {
+ metadata.max_deleted_entry_id_ = *max_deleted_id;
}
auto batch = storage_->GetWriteBatchBase();
diff --git a/src/types/redis_stream_base.cc b/src/types/redis_stream_base.cc
index 507a0cae..4933c868 100644
--- a/src/types/redis_stream_base.cc
+++ b/src/types/redis_stream_base.cc
@@ -31,18 +31,18 @@ const char *kErrInvalidEntryIdSpecified = "Invalid stream ID specified as stream
const char *kErrDecodingStreamEntryValueFailure = "failed to decode stream entry value";
rocksdb::Status IncrementStreamEntryID(StreamEntryID *id) {
- if (id->seq == UINT64_MAX) {
- if (id->ms == UINT64_MAX) {
+ if (id->seq_ == UINT64_MAX) {
+ if (id->ms_ == UINT64_MAX) {
// special case where 'id' is the last possible entry ID
- id->ms = 0;
- id->seq = 0;
+ id->ms_ = 0;
+ id->seq_ = 0;
return rocksdb::Status::InvalidArgument(kErrLastEntryIdReached);
} else {
- id->ms++;
- id->seq = 0;
+ id->ms_++;
+ id->seq_ = 0;
}
} else {
- id->seq++;
+ id->seq_++;
}
return rocksdb::Status::OK();
@@ -50,9 +50,9 @@ rocksdb::Status IncrementStreamEntryID(StreamEntryID *id) {
rocksdb::Status GetNextStreamEntryID(const StreamEntryID &last_id, StreamEntryID *new_id) {
uint64_t ms = Util::GetTimeStampMS();
- if (ms > last_id.ms) {
- new_id->ms = ms;
- new_id->seq = 0;
+ if (ms > last_id.ms_) {
+ new_id->ms_ = ms;
+ new_id->seq_ = 0;
return rocksdb::Status::OK();
} else {
*new_id = last_id;
@@ -71,16 +71,16 @@ Status ParseStreamEntryID(const std::string &input, StreamEntryID *id) {
return {Status::RedisParseErr, kErrInvalidEntryIdSpecified};
}
- id->ms = *parse_ms;
- id->seq = *parse_seq;
+ id->ms_ = *parse_ms;
+ id->seq_ = *parse_seq;
} else {
auto parse_input = ParseInt<uint64_t>(input, 10);
if (!parse_input) {
return {Status::RedisParseErr, kErrInvalidEntryIdSpecified};
}
- id->ms = *parse_input;
- id->seq = 0;
+ id->ms_ = *parse_input;
+ id->seq_ = 0;
}
return Status::OK();
}
@@ -95,17 +95,17 @@ Status ParseNewStreamEntryID(const std::string &input, NewStreamEntryID *id) {
return {Status::RedisParseErr, kErrInvalidEntryIdSpecified};
}
- id->ms = *parse_ms;
+ id->ms_ = *parse_ms;
if (seq_str == "*") {
- id->any_seq_number = true;
+ id->any_seq_number_ = true;
} else {
auto parse_seq = ParseInt<uint64_t>(seq_str, 10);
if (!parse_seq) {
return {Status::RedisParseErr, kErrInvalidEntryIdSpecified};
}
- id->seq = *parse_seq;
+ id->seq_ = *parse_seq;
}
} else {
auto parse_input = ParseInt<uint64_t>(input, 10);
@@ -113,8 +113,8 @@ Status ParseNewStreamEntryID(const std::string &input, NewStreamEntryID *id) {
return {Status::RedisParseErr, kErrInvalidEntryIdSpecified};
}
- id->ms = *parse_input;
- id->seq = 0;
+ id->ms_ = *parse_input;
+ id->seq_ = 0;
}
return Status::OK();
@@ -133,16 +133,16 @@ Status ParseRangeEnd(const std::string &input, StreamEntryID *id) {
return {Status::RedisParseErr, kErrInvalidEntryIdSpecified};
}
- id->ms = *parse_ms;
- id->seq = *parse_seq;
+ id->ms_ = *parse_ms;
+ id->seq_ = *parse_seq;
} else {
auto parse_input = ParseInt<uint64_t>(input, 10);
if (!parse_input) {
return {Status::RedisParseErr, kErrInvalidEntryIdSpecified};
}
- id->ms = *parse_input;
- id->seq = UINT64_MAX;
+ id->ms_ = *parse_input;
+ id->seq_ = UINT64_MAX;
}
return Status::OK();
diff --git a/src/types/redis_stream_base.h b/src/types/redis_stream_base.h
index fe109077..c6653beb 100644
--- a/src/types/redis_stream_base.h
+++ b/src/types/redis_stream_base.h
@@ -39,23 +39,23 @@ enum class StreamTrimStrategy {
};
struct StreamEntryID {
- uint64_t ms = 0;
- uint64_t seq = 0;
+ uint64_t ms_ = 0;
+ uint64_t seq_ = 0;
StreamEntryID() = default;
- StreamEntryID(uint64_t ms, uint64_t seq) : ms(ms), seq(seq) {}
+ StreamEntryID(uint64_t ms, uint64_t seq) : ms_(ms), seq_(seq) {}
void Clear() {
- ms = 0;
- seq = 0;
+ ms_ = 0;
+ seq_ = 0;
}
- bool IsMaximum() const { return ms == UINT64_MAX && seq == UINT64_MAX; }
- bool IsMinimum() const { return ms == 0 && seq == 0; }
+ bool IsMaximum() const { return ms_ == UINT64_MAX && seq_ == UINT64_MAX; }
+ bool IsMinimum() const { return ms_ == 0 && seq_ == 0; }
bool operator<(const StreamEntryID &rhs) const {
- if (ms < rhs.ms) return true;
- if (ms == rhs.ms) return seq < rhs.seq;
+ if (ms_ < rhs.ms_) return true;
+ if (ms_ == rhs.ms_) return seq_ < rhs.seq_;
return false;
}
@@ -65,77 +65,77 @@ struct StreamEntryID {
bool operator<=(const StreamEntryID &rhs) const { return !(rhs < *this); }
- bool operator==(const StreamEntryID &rhs) const { return ms == rhs.ms && seq == rhs.seq; }
+ bool operator==(const StreamEntryID &rhs) const { return ms_ == rhs.ms_ && seq_ == rhs.seq_; }
- std::string ToString() const { return fmt::format("{}-{}", ms, seq); }
+ std::string ToString() const { return fmt::format("{}-{}", ms_, seq_); }
static StreamEntryID Minimum() { return StreamEntryID{0, 0}; }
static StreamEntryID Maximum() { return StreamEntryID{UINT64_MAX, UINT64_MAX}; }
};
struct NewStreamEntryID {
- uint64_t ms = 0;
- uint64_t seq = 0;
- bool any_seq_number = false;
+ uint64_t ms_ = 0;
+ uint64_t seq_ = 0;
+ bool any_seq_number_ = false;
NewStreamEntryID() = default;
- explicit NewStreamEntryID(uint64_t ms) : ms(ms), any_seq_number(true) {}
- NewStreamEntryID(uint64_t ms, uint64_t seq) : ms(ms), seq(seq) {}
+ explicit NewStreamEntryID(uint64_t ms) : ms_(ms), any_seq_number_(true) {}
+ NewStreamEntryID(uint64_t ms, uint64_t seq) : ms_(ms), seq_(seq) {}
};
struct StreamEntry {
- std::string key;
- std::vector<std::string> values;
+ std::string key_;
+ std::vector<std::string> values_;
- StreamEntry(std::string k, std::vector<std::string> vv) : key(std::move(k)), values(std::move(vv)) {}
+ StreamEntry(std::string k, std::vector<std::string> vv) : key_(std::move(k)), values_(std::move(vv)) {}
};
struct StreamTrimOptions {
- uint64_t max_len;
- StreamEntryID min_id;
- StreamTrimStrategy strategy = StreamTrimStrategy::None;
+ uint64_t max_len_;
+ StreamEntryID min_id_;
+ StreamTrimStrategy strategy_ = StreamTrimStrategy::None;
};
struct StreamAddOptions {
- NewStreamEntryID entry_id;
- StreamTrimOptions trim_options;
- bool nomkstream = false;
- bool with_entry_id = false;
+ NewStreamEntryID entry_id_;
+ StreamTrimOptions trim_options_;
+ bool nomkstream_ = false;
+ bool with_entry_id_ = false;
};
struct StreamRangeOptions {
- StreamEntryID start;
- StreamEntryID end;
- uint64_t count;
- bool with_count = false;
- bool reverse = false;
- bool exclude_start = false;
- bool exclude_end = false;
+ StreamEntryID start_;
+ StreamEntryID end_;
+ uint64_t count_;
+ bool with_count_ = false;
+ bool reverse_ = false;
+ bool exclude_start_ = false;
+ bool exclude_end_ = false;
};
struct StreamLenOptions {
- StreamEntryID entry_id;
- bool with_entry_id = false;
- bool to_first = false;
+ StreamEntryID entry_id_;
+ bool with_entry_id_ = false;
+ bool to_first_ = false;
};
struct StreamInfo {
- uint64_t size;
- uint64_t entries_added;
- StreamEntryID last_generated_id;
- StreamEntryID max_deleted_entry_id;
- StreamEntryID recorded_first_entry_id;
- std::unique_ptr<StreamEntry> first_entry;
- std::unique_ptr<StreamEntry> last_entry;
- std::vector<StreamEntry> entries;
+ uint64_t size_;
+ uint64_t entries_added_;
+ StreamEntryID last_generated_id_;
+ StreamEntryID max_deleted_entry_id_;
+ StreamEntryID recorded_first_entry_id_;
+ std::unique_ptr<StreamEntry> first_entry_;
+ std::unique_ptr<StreamEntry> last_entry_;
+ std::vector<StreamEntry> entries_;
};
struct StreamReadResult {
- std::string name;
- std::vector<StreamEntry> entries;
+ std::string name_;
+ std::vector<StreamEntry> entries_;
StreamReadResult(std::string name, std::vector<StreamEntry> result)
- : name(std::move(name)), entries(std::move(result)) {}
+ : name_(std::move(name)), entries_(std::move(result)) {}
};
rocksdb::Status IncrementStreamEntryID(StreamEntryID *id);
diff --git a/src/types/redis_string.cc b/src/types/redis_string.cc
index edb04c8e..d31a3f63 100644
--- a/src/types/redis_string.cc
+++ b/src/types/redis_string.cc
@@ -53,7 +53,7 @@ std::vector<rocksdb::Status> String::getRawValues(const std::vector<Slice> &keys
statuses[i] = rocksdb::Status::NotFound(kErrMsgKeyExpired);
continue;
}
- if (metadata.Type() != kRedisString && metadata.size > 0) {
+ if (metadata.Type() != kRedisString && metadata.size_ > 0) {
(*raw_values)[i].clear();
statuses[i] = rocksdb::Status::InvalidArgument(kErrMsgWrongType);
continue;
@@ -77,7 +77,7 @@ rocksdb::Status String::getRawValue(const std::string &ns_key, std::string *raw_
raw_value->clear();
return rocksdb::Status::NotFound(kErrMsgKeyExpired);
}
- if (metadata.Type() != kRedisString && metadata.size > 0) {
+ if (metadata.Type() != kRedisString && metadata.size_ > 0) {
return rocksdb::Status::InvalidArgument(kErrMsgWrongType);
}
return rocksdb::Status::OK();
@@ -167,7 +167,7 @@ rocksdb::Status String::GetEx(const std::string &user_key, std::string *value, u
std::string raw_data;
Metadata metadata(kRedisString, false);
- metadata.expire = expire;
+ metadata.expire_ = expire;
metadata.Encode(&raw_data);
raw_data.append(value->data(), value->size());
auto batch = storage_->GetWriteBatchBase();
@@ -239,7 +239,7 @@ rocksdb::Status String::SetXX(const std::string &user_key, const std::string &va
*ret = 1;
std::string raw_value;
Metadata metadata(kRedisString, false);
- metadata.expire = expire;
+ metadata.expire_ = expire;
metadata.Encode(&raw_value);
raw_value.append(value);
return updateRawValue(ns_key, raw_value);
@@ -370,13 +370,13 @@ rocksdb::Status String::MSet(const std::vector<StringPair> &pairs, uint64_t ttl)
for (const auto &pair : pairs) {
std::string bytes;
Metadata metadata(kRedisString, false);
- metadata.expire = expire;
+ metadata.expire_ = expire;
metadata.Encode(&bytes);
- bytes.append(pair.value.data(), pair.value.size());
+ bytes.append(pair.value_.data(), pair.value_.size());
auto batch = storage_->GetWriteBatchBase();
WriteBatchLogData log_data(kRedisString);
batch->PutLogData(log_data.Encode());
- AppendNamespacePrefix(pair.key, &ns_key);
+ AppendNamespacePrefix(pair.key_, &ns_key);
batch->Put(metadata_cf_handle_, ns_key, bytes);
LockGuard guard(storage_->GetLockManager(), ns_key);
auto s = storage_->Write(storage_->DefaultWriteOptions(), batch->GetWriteBatch());
@@ -398,7 +398,7 @@ rocksdb::Status String::MSetNX(const std::vector<StringPair> &pairs, uint64_t tt
std::vector<Slice> keys;
keys.reserve(pairs.size());
for (StringPair pair : pairs) {
- keys.emplace_back(pair.key);
+ keys.emplace_back(pair.key_);
}
if (Exists(keys, &exists).ok() && exists > 0) {
return rocksdb::Status::OK();
@@ -406,16 +406,16 @@ rocksdb::Status String::MSetNX(const std::vector<StringPair> &pairs, uint64_t tt
std::string ns_key;
for (StringPair pair : pairs) {
- AppendNamespacePrefix(pair.key, &ns_key);
+ AppendNamespacePrefix(pair.key_, &ns_key);
LockGuard guard(storage_->GetLockManager(), ns_key);
- if (Exists({pair.key}, &exists).ok() && exists == 1) {
+ if (Exists({pair.key_}, &exists).ok() && exists == 1) {
return rocksdb::Status::OK();
}
std::string bytes;
Metadata metadata(kRedisString, false);
- metadata.expire = expire;
+ metadata.expire_ = expire;
metadata.Encode(&bytes);
- bytes.append(pair.value.data(), pair.value.size());
+ bytes.append(pair.value_.data(), pair.value_.size());
auto batch = storage_->GetWriteBatchBase();
WriteBatchLogData log_data(kRedisString);
batch->PutLogData(log_data.Encode());
@@ -459,7 +459,7 @@ rocksdb::Status String::CAS(const std::string &user_key, const std::string &old_
uint64_t now = Util::GetTimeStampMS();
expire = now + ttl;
}
- metadata.expire = expire;
+ metadata.expire_ = expire;
metadata.Encode(&raw_value);
raw_value.append(new_value);
auto write_status = updateRawValue(ns_key, raw_value);
diff --git a/src/types/redis_string.h b/src/types/redis_string.h
index dcbeda83..663332eb 100644
--- a/src/types/redis_string.h
+++ b/src/types/redis_string.h
@@ -28,8 +28,8 @@
#include "storage/redis_metadata.h"
struct StringPair {
- Slice key;
- Slice value;
+ Slice key_;
+ Slice value_;
};
namespace Redis {
diff --git a/src/types/redis_zset.cc b/src/types/redis_zset.cc
index 5f03150f..15842751 100644
--- a/src/types/redis_zset.cc
+++ b/src/types/redis_zset.cc
@@ -53,7 +53,7 @@ rocksdb::Status ZSet::Add(const Slice &user_key, ZAddFlags flags, std::vector<Me
std::string member_key;
std::set<std::string> added_member_keys;
for (int i = static_cast<int>(mscores->size() - 1); i >= 0; i--) {
- InternalKey(ns_key, (*mscores)[i].member, metadata.version, storage_->IsSlotIdEncoded()).Encode(&member_key);
+ InternalKey(ns_key, (*mscores)[i].member_, metadata.version_, storage_->IsSlotIdEncoded()).Encode(&member_key);
// Fix the corner case that adds the same member which may add the score
// column family many times and cause problems in the ZRANGE command.
@@ -69,7 +69,7 @@ rocksdb::Status ZSet::Add(const Slice &user_key, ZAddFlags flags, std::vector<Me
}
added_member_keys.insert(member_key);
- if (metadata.size > 0) {
+ if (metadata.size_ > 0) {
std::string old_score_bytes;
s = storage_->Get(rocksdb::ReadOptions(), member_key, &old_score_bytes);
if (!s.ok() && !s.IsNotFound()) return s;
@@ -79,28 +79,28 @@ rocksdb::Status ZSet::Add(const Slice &user_key, ZAddFlags flags, std::vector<Me
}
double old_score = DecodeDouble(old_score_bytes.data());
if (flags.HasIncr()) {
- if ((flags.HasLT() && (*mscores)[i].score >= 0) || (flags.HasGT() && (*mscores)[i].score <= 0)) {
+ if ((flags.HasLT() && (*mscores)[i].score_ >= 0) || (flags.HasGT() && (*mscores)[i].score_ <= 0)) {
continue;
}
- (*mscores)[i].score += old_score;
- if (std::isnan((*mscores)[i].score)) {
+ (*mscores)[i].score_ += old_score;
+ if (std::isnan((*mscores)[i].score_)) {
return rocksdb::Status::InvalidArgument("resulting score is not a number (NaN)");
}
}
- if ((*mscores)[i].score != old_score) {
- if ((flags.HasLT() && (*mscores)[i].score >= old_score) ||
- (flags.HasGT() && (*mscores)[i].score <= old_score)) {
+ if ((*mscores)[i].score_ != old_score) {
+ if ((flags.HasLT() && (*mscores)[i].score_ >= old_score) ||
+ (flags.HasGT() && (*mscores)[i].score_ <= old_score)) {
continue;
}
- old_score_bytes.append((*mscores)[i].member);
+ old_score_bytes.append((*mscores)[i].member_);
std::string old_score_key;
- InternalKey(ns_key, old_score_bytes, metadata.version, storage_->IsSlotIdEncoded()).Encode(&old_score_key);
+ InternalKey(ns_key, old_score_bytes, metadata.version_, storage_->IsSlotIdEncoded()).Encode(&old_score_key);
batch->Delete(score_cf_handle_, old_score_key);
std::string new_score_bytes, new_score_key;
- PutDouble(&new_score_bytes, (*mscores)[i].score);
+ PutDouble(&new_score_bytes, (*mscores)[i].score_);
batch->Put(member_key, new_score_bytes);
- new_score_bytes.append((*mscores)[i].member);
- InternalKey(ns_key, new_score_bytes, metadata.version, storage_->IsSlotIdEncoded()).Encode(&new_score_key);
+ new_score_bytes.append((*mscores)[i].member_);
+ InternalKey(ns_key, new_score_bytes, metadata.version_, storage_->IsSlotIdEncoded()).Encode(&new_score_key);
batch->Put(score_cf_handle_, new_score_key, Slice());
changed++;
}
@@ -111,16 +111,16 @@ rocksdb::Status ZSet::Add(const Slice &user_key, ZAddFlags flags, std::vector<Me
continue;
}
std::string score_bytes, score_key;
- PutDouble(&score_bytes, (*mscores)[i].score);
+ PutDouble(&score_bytes, (*mscores)[i].score_);
batch->Put(member_key, score_bytes);
- score_bytes.append((*mscores)[i].member);
- InternalKey(ns_key, score_bytes, metadata.version, storage_->IsSlotIdEncoded()).Encode(&score_key);
+ score_bytes.append((*mscores)[i].member_);
+ InternalKey(ns_key, score_bytes, metadata.version_, storage_->IsSlotIdEncoded()).Encode(&score_key);
batch->Put(score_cf_handle_, score_key, Slice());
added++;
}
if (added > 0) {
*ret = added;
- metadata.size += added;
+ metadata.size_ += added;
std::string bytes;
metadata.Encode(&bytes);
batch->Put(metadata_cf_handle_, ns_key, bytes);
@@ -140,7 +140,7 @@ rocksdb::Status ZSet::Card(const Slice &user_key, int *ret) {
ZSetMetadata metadata(false);
rocksdb::Status s = GetMetadata(ns_key, &metadata);
if (!s.ok()) return s.IsNotFound() ? rocksdb::Status::OK() : s;
- *ret = static_cast<int>(metadata.size);
+ *ret = static_cast<int>(metadata.size_);
return rocksdb::Status::OK();
}
@@ -155,7 +155,7 @@ rocksdb::Status ZSet::IncrBy(const Slice &user_key, const Slice &member, double
mscores.emplace_back(MemberScore{member.ToString(), increment});
rocksdb::Status s = Add(user_key, ZAddFlags::Incr(), &mscores, &ret);
if (!s.ok()) return s;
- *score = mscores[0].score;
+ *score = mscores[0].score_;
return rocksdb::Status::OK();
}
@@ -170,15 +170,15 @@ rocksdb::Status ZSet::Pop(const Slice &user_key, int count, bool min, std::vecto
rocksdb::Status s = GetMetadata(ns_key, &metadata);
if (!s.ok()) return s.IsNotFound() ? rocksdb::Status::OK() : s;
if (count <= 0) return rocksdb::Status::OK();
- if (count > static_cast<int>(metadata.size)) count = static_cast<int>(metadata.size);
+ if (count > static_cast<int>(metadata.size_)) count = static_cast<int>(metadata.size_);
std::string score_bytes;
double score = min ? kMinScore : kMaxScore;
PutDouble(&score_bytes, score);
std::string start_key, prefix_key, next_verison_prefix_key;
- InternalKey(ns_key, score_bytes, metadata.version, storage_->IsSlotIdEncoded()).Encode(&start_key);
- InternalKey(ns_key, "", metadata.version, storage_->IsSlotIdEncoded()).Encode(&prefix_key);
- InternalKey(ns_key, "", metadata.version + 1, storage_->IsSlotIdEncoded()).Encode(&next_verison_prefix_key);
+ InternalKey(ns_key, score_bytes, metadata.version_, storage_->IsSlotIdEncoded()).Encode(&start_key);
+ InternalKey(ns_key, "", metadata.version_, storage_->IsSlotIdEncoded()).Encode(&prefix_key);
+ InternalKey(ns_key, "", metadata.version_ + 1, storage_->IsSlotIdEncoded()).Encode(&next_verison_prefix_key);
auto batch = storage_->GetWriteBatchBase();
WriteBatchLogData log_data(kRedisZSet);
@@ -205,14 +205,14 @@ rocksdb::Status ZSet::Pop(const Slice &user_key, int count, bool min, std::vecto
GetDouble(&score_key, &score);
mscores->emplace_back(MemberScore{score_key.ToString(), score});
std::string default_cf_key;
- InternalKey(ns_key, score_key, metadata.version, storage_->IsSlotIdEncoded()).Encode(&default_cf_key);
+ InternalKey(ns_key, score_key, metadata.version_, storage_->IsSlotIdEncoded()).Encode(&default_cf_key);
batch->Delete(default_cf_key);
batch->Delete(score_cf_handle_, iter->key());
if (mscores->size() >= static_cast<unsigned>(count)) break;
}
if (!mscores->empty()) {
- metadata.size -= mscores->size();
+ metadata.size_ -= mscores->size();
std::string bytes;
metadata.Encode(&bytes);
batch->Put(metadata_cf_handle_, ns_key, bytes);
@@ -235,8 +235,8 @@ rocksdb::Status ZSet::Range(const Slice &user_key, int start, int stop, uint8_t
ZSetMetadata metadata(false);
rocksdb::Status s = GetMetadata(ns_key, &metadata);
if (!s.ok()) return s.IsNotFound() ? rocksdb::Status::OK() : s;
- if (start < 0) start += static_cast<int>(metadata.size);
- if (stop < 0) stop += static_cast<int>(metadata.size);
+ if (start < 0) start += static_cast<int>(metadata.size_);
+ if (stop < 0) stop += static_cast<int>(metadata.size_);
if (start < 0) start = 0;
if (stop < 0 || start > stop) {
return rocksdb::Status::OK();
@@ -246,9 +246,9 @@ rocksdb::Status ZSet::Range(const Slice &user_key, int start, int stop, uint8_t
double score = !reversed ? kMinScore : kMaxScore;
PutDouble(&score_bytes, score);
std::string start_key, prefix_key, next_verison_prefix_key;
- InternalKey(ns_key, score_bytes, metadata.version, storage_->IsSlotIdEncoded()).Encode(&start_key);
- InternalKey(ns_key, "", metadata.version, storage_->IsSlotIdEncoded()).Encode(&prefix_key);
- InternalKey(ns_key, "", metadata.version + 1, storage_->IsSlotIdEncoded()).Encode(&next_verison_prefix_key);
+ InternalKey(ns_key, score_bytes, metadata.version_, storage_->IsSlotIdEncoded()).Encode(&start_key);
+ InternalKey(ns_key, "", metadata.version_, storage_->IsSlotIdEncoded()).Encode(&prefix_key);
+ InternalKey(ns_key, "", metadata.version_ + 1, storage_->IsSlotIdEncoded()).Encode(&next_verison_prefix_key);
int count = 0;
int removed_subkey = 0;
@@ -276,7 +276,7 @@ rocksdb::Status ZSet::Range(const Slice &user_key, int start, int stop, uint8_t
if (count >= start) {
if (removed) {
std::string sub_key;
- InternalKey(ns_key, score_key, metadata.version, storage_->IsSlotIdEncoded()).Encode(&sub_key);
+ InternalKey(ns_key, score_key, metadata.version_, storage_->IsSlotIdEncoded()).Encode(&sub_key);
batch->Delete(sub_key);
batch->Delete(score_cf_handle_, iter->key());
removed_subkey++;
@@ -287,7 +287,7 @@ rocksdb::Status ZSet::Range(const Slice &user_key, int start, int stop, uint8_t
}
if (removed_subkey) {
- metadata.size -= removed_subkey;
+ metadata.size_ -= removed_subkey;
std::string bytes;
metadata.Encode(&bytes);
batch->Put(metadata_cf_handle_, ns_key, bytes);
@@ -305,7 +305,7 @@ rocksdb::Status ZSet::RangeByScore(const Slice &user_key, ZRangeSpec spec, std::
AppendNamespacePrefix(user_key, &ns_key);
std::unique_ptr<LockGuard> lock_guard;
- if (spec.removed) lock_guard = std::make_unique<LockGuard>(storage_->GetLockManager(), ns_key);
+ if (spec.removed_) lock_guard = std::make_unique<LockGuard>(storage_->GetLockManager(), ns_key);
ZSetMetadata metadata(false);
rocksdb::Status s = GetMetadata(ns_key, &metadata);
if (!s.ok()) return s.IsNotFound() ? rocksdb::Status::OK() : s;
@@ -341,18 +341,18 @@ rocksdb::Status ZSet::RangeByScore(const Slice &user_key, ZRangeSpec spec, std::
// generate next possible score of max
int64_t i64 = 0;
double max_next_score = 0;
- if (spec.reversed && !spec.maxex) {
- memcpy(&i64, &spec.max, sizeof(spec.max));
+ if (spec.reversed_ && !spec.maxex_) {
+ memcpy(&i64, &spec.max_, sizeof(spec.max_));
i64 = i64 >= 0 ? i64 + 1 : i64 - 1;
memcpy(&max_next_score, &i64, sizeof(i64));
}
std::string start_score_bytes;
- PutDouble(&start_score_bytes, spec.reversed ? (spec.maxex ? spec.max : max_next_score) : spec.min);
+ PutDouble(&start_score_bytes, spec.reversed_ ? (spec.maxex_ ? spec.max_ : max_next_score) : spec.min_);
std::string start_key, prefix_key, next_verison_prefix_key;
- InternalKey(ns_key, start_score_bytes, metadata.version, storage_->IsSlotIdEncoded()).Encode(&start_key);
- InternalKey(ns_key, "", metadata.version, storage_->IsSlotIdEncoded()).Encode(&prefix_key);
- InternalKey(ns_key, "", metadata.version + 1, storage_->IsSlotIdEncoded()).Encode(&next_verison_prefix_key);
+ InternalKey(ns_key, start_score_bytes, metadata.version_, storage_->IsSlotIdEncoded()).Encode(&start_key);
+ InternalKey(ns_key, "", metadata.version_, storage_->IsSlotIdEncoded()).Encode(&prefix_key);
+ InternalKey(ns_key, "", metadata.version_ + 1, storage_->IsSlotIdEncoded()).Encode(&next_verison_prefix_key);
rocksdb::ReadOptions read_options;
LatestSnapShot ss(storage_);
@@ -368,7 +368,7 @@ rocksdb::Status ZSet::RangeByScore(const Slice &user_key, ZRangeSpec spec, std::
auto batch = storage_->GetWriteBatchBase();
WriteBatchLogData log_data(kRedisZSet);
batch->PutLogData(log_data.Encode());
- if (!spec.reversed) {
+ if (!spec.reversed_) {
iter->Seek(start_key);
} else {
iter->SeekForPrev(start_key);
@@ -377,33 +377,33 @@ rocksdb::Status ZSet::RangeByScore(const Slice &user_key, ZRangeSpec spec, std::
}
}
- for (; iter->Valid() && iter->key().starts_with(prefix_key); !spec.reversed ? iter->Next() : iter->Prev()) {
+ for (; iter->Valid() && iter->key().starts_with(prefix_key); !spec.reversed_ ? iter->Next() : iter->Prev()) {
InternalKey ikey(iter->key(), storage_->IsSlotIdEncoded());
Slice score_key = ikey.GetSubKey();
double score = NAN;
GetDouble(&score_key, &score);
- if (spec.reversed) {
- if ((spec.minex && score == spec.min) || score < spec.min) break;
- if ((spec.maxex && score == spec.max) || score > spec.max) continue;
+ if (spec.reversed_) {
+ if ((spec.minex_ && score == spec.min_) || score < spec.min_) break;
+ if ((spec.maxex_ && score == spec.max_) || score > spec.max_) continue;
} else {
- if ((spec.minex && score == spec.min) || score < spec.min) continue;
- if ((spec.maxex && score == spec.max) || score > spec.max) break;
+ if ((spec.minex_ && score == spec.min_) || score < spec.min_) continue;
+ if ((spec.maxex_ && score == spec.max_) || score > spec.max_) break;
}
- if (spec.offset >= 0 && pos++ < spec.offset) continue;
- if (spec.removed) {
+ if (spec.offset_ >= 0 && pos++ < spec.offset_) continue;
+ if (spec.removed_) {
std::string sub_key;
- InternalKey(ns_key, score_key, metadata.version, storage_->IsSlotIdEncoded()).Encode(&sub_key);
+ InternalKey(ns_key, score_key, metadata.version_, storage_->IsSlotIdEncoded()).Encode(&sub_key);
batch->Delete(sub_key);
batch->Delete(score_cf_handle_, iter->key());
} else {
if (mscores) mscores->emplace_back(MemberScore{score_key.ToString(), score});
}
if (size) *size += 1;
- if (spec.count > 0 && mscores && mscores->size() >= static_cast<unsigned>(spec.count)) break;
+ if (spec.count_ > 0 && mscores && mscores->size() >= static_cast<unsigned>(spec.count_)) break;
}
- if (spec.removed && *size > 0) {
- metadata.size -= *size;
+ if (spec.removed_ && *size > 0) {
+ metadata.size_ -= *size;
std::string bytes;
metadata.Encode(&bytes);
batch->Put(metadata_cf_handle_, ns_key, bytes);
@@ -416,7 +416,7 @@ rocksdb::Status ZSet::RangeByLex(const Slice &user_key, const CommonRangeLexSpec
std::vector<std::string> *members, int *size) {
if (size) *size = 0;
if (members) members->clear();
- if (spec.offset > -1 && spec.count == 0) {
+ if (spec.offset_ > -1 && spec.count_ == 0) {
return rocksdb::Status::OK();
}
@@ -424,18 +424,18 @@ rocksdb::Status ZSet::RangeByLex(const Slice &user_key, const CommonRangeLexSpec
AppendNamespacePrefix(user_key, &ns_key);
std::unique_ptr<LockGuard> lock_guard;
- if (spec.removed) {
+ if (spec.removed_) {
lock_guard = std::make_unique<LockGuard>(storage_->GetLockManager(), ns_key);
}
ZSetMetadata metadata(false);
rocksdb::Status s = GetMetadata(ns_key, &metadata);
if (!s.ok()) return s.IsNotFound() ? rocksdb::Status::OK() : s;
- std::string start_member = spec.reversed ? spec.max : spec.min;
+ std::string start_member = spec.reversed_ ? spec.max_ : spec.min_;
std::string start_key, prefix_key, next_version_prefix_key;
- InternalKey(ns_key, start_member, metadata.version, storage_->IsSlotIdEncoded()).Encode(&start_key);
- InternalKey(ns_key, "", metadata.version, storage_->IsSlotIdEncoded()).Encode(&prefix_key);
- InternalKey(ns_key, "", metadata.version + 1, storage_->IsSlotIdEncoded()).Encode(&next_version_prefix_key);
+ InternalKey(ns_key, start_member, metadata.version_, storage_->IsSlotIdEncoded()).Encode(&start_key);
+ InternalKey(ns_key, "", metadata.version_, storage_->IsSlotIdEncoded()).Encode(&prefix_key);
+ InternalKey(ns_key, "", metadata.version_ + 1, storage_->IsSlotIdEncoded()).Encode(&next_version_prefix_key);
rocksdb::ReadOptions read_options;
LatestSnapShot ss(storage_);
@@ -452,47 +452,47 @@ rocksdb::Status ZSet::RangeByLex(const Slice &user_key, const CommonRangeLexSpec
WriteBatchLogData log_data(kRedisZSet);
batch->PutLogData(log_data.Encode());
- if (!spec.reversed) {
+ if (!spec.reversed_) {
iter->Seek(start_key);
} else {
- if (spec.max_infinite) {
+ if (spec.max_infinite_) {
iter->SeekToLast();
} else {
iter->SeekForPrev(start_key);
}
}
- for (; iter->Valid() && iter->key().starts_with(prefix_key); (!spec.reversed ? iter->Next() : iter->Prev())) {
+ for (; iter->Valid() && iter->key().starts_with(prefix_key); (!spec.reversed_ ? iter->Next() : iter->Prev())) {
InternalKey ikey(iter->key(), storage_->IsSlotIdEncoded());
Slice member = ikey.GetSubKey();
- if (spec.reversed) {
- if (member.ToString() < spec.min || (spec.minex && member == spec.min)) {
+ if (spec.reversed_) {
+ if (member.ToString() < spec.min_ || (spec.minex_ && member == spec.min_)) {
break;
}
- if ((spec.maxex && member == spec.max) || (!spec.max_infinite && member.ToString() > spec.max)) {
+ if ((spec.maxex_ && member == spec.max_) || (!spec.max_infinite_ && member.ToString() > spec.max_)) {
continue;
}
} else {
- if (spec.minex && member == spec.min) continue; // the min member was exclusive
- if ((spec.maxex && member == spec.max) || (!spec.max_infinite && member.ToString() > spec.max)) break;
+ if (spec.minex_ && member == spec.min_) continue; // the min member was exclusive
+ if ((spec.maxex_ && member == spec.max_) || (!spec.max_infinite_ && member.ToString() > spec.max_)) break;
}
- if (spec.offset >= 0 && pos++ < spec.offset) continue;
- if (spec.removed) {
+ if (spec.offset_ >= 0 && pos++ < spec.offset_) continue;
+ if (spec.removed_) {
std::string score_bytes = iter->value().ToString();
score_bytes.append(member.data(), member.size());
std::string score_key;
- InternalKey(ns_key, score_bytes, metadata.version, storage_->IsSlotIdEncoded()).Encode(&score_key);
+ InternalKey(ns_key, score_bytes, metadata.version_, storage_->IsSlotIdEncoded()).Encode(&score_key);
batch->Delete(score_cf_handle_, score_key);
batch->Delete(iter->key());
} else {
if (members) members->emplace_back(member.ToString());
}
if (size) *size += 1;
- if (spec.count > 0 && members && members->size() >= static_cast<unsigned>(spec.count)) break;
+ if (spec.count_ > 0 && members && members->size() >= static_cast<unsigned>(spec.count_)) break;
}
- if (spec.removed && size && *size > 0) {
- metadata.size -= *size;
+ if (spec.removed_ && size && *size > 0) {
+ metadata.size_ -= *size;
std::string bytes;
metadata.Encode(&bytes);
batch->Put(metadata_cf_handle_, ns_key, bytes);
@@ -513,7 +513,7 @@ rocksdb::Status ZSet::Score(const Slice &user_key, const Slice &member, double *
read_options.snapshot = ss.GetSnapShot();
std::string member_key, score_bytes;
- InternalKey(ns_key, member, metadata.version, storage_->IsSlotIdEncoded()).Encode(&member_key);
+ InternalKey(ns_key, member, metadata.version_, storage_->IsSlotIdEncoded()).Encode(&member_key);
s = storage_->Get(read_options, member_key, &score_bytes);
if (!s.ok()) return s;
*score = DecodeDouble(score_bytes.data());
@@ -536,12 +536,12 @@ rocksdb::Status ZSet::Remove(const Slice &user_key, const std::vector<Slice> &me
int removed = 0;
std::string member_key, score_key;
for (const auto &member : members) {
- InternalKey(ns_key, member, metadata.version, storage_->IsSlotIdEncoded()).Encode(&member_key);
+ InternalKey(ns_key, member, metadata.version_, storage_->IsSlotIdEncoded()).Encode(&member_key);
std::string score_bytes;
s = storage_->Get(rocksdb::ReadOptions(), member_key, &score_bytes);
if (s.ok()) {
score_bytes.append(member.data(), member.size());
- InternalKey(ns_key, score_bytes, metadata.version, storage_->IsSlotIdEncoded()).Encode(&score_key);
+ InternalKey(ns_key, score_bytes, metadata.version_, storage_->IsSlotIdEncoded()).Encode(&score_key);
batch->Delete(member_key);
batch->Delete(score_cf_handle_, score_key);
removed++;
@@ -549,7 +549,7 @@ rocksdb::Status ZSet::Remove(const Slice &user_key, const std::vector<Slice> &me
}
if (removed > 0) {
*ret = removed;
- metadata.size -= removed;
+ metadata.size_ -= removed;
std::string bytes;
metadata.Encode(&bytes);
batch->Put(metadata_cf_handle_, ns_key, bytes);
@@ -558,12 +558,12 @@ rocksdb::Status ZSet::Remove(const Slice &user_key, const std::vector<Slice> &me
}
rocksdb::Status ZSet::RemoveRangeByScore(const Slice &user_key, ZRangeSpec spec, int *ret) {
- spec.removed = true;
+ spec.removed_ = true;
return RangeByScore(user_key, spec, nullptr, ret);
}
rocksdb::Status ZSet::RemoveRangeByLex(const Slice &user_key, CommonRangeLexSpec spec, int *ret) {
- spec.removed = true;
+ spec.removed_ = true;
return RangeByLex(user_key, spec, nullptr, ret);
}
@@ -588,7 +588,7 @@ rocksdb::Status ZSet::Rank(const Slice &user_key, const Slice &member, bool reve
LatestSnapShot ss(storage_);
read_options.snapshot = ss.GetSnapShot();
std::string score_bytes, member_key;
- InternalKey(ns_key, member, metadata.version, storage_->IsSlotIdEncoded()).Encode(&member_key);
+ InternalKey(ns_key, member, metadata.version_, storage_->IsSlotIdEncoded()).Encode(&member_key);
s = storage_->Get(read_options, member_key, &score_bytes);
if (!s.ok()) return s.IsNotFound() ? rocksdb::Status::OK() : s;
@@ -596,9 +596,9 @@ rocksdb::Status ZSet::Rank(const Slice &user_key, const Slice &member, bool reve
std::string start_score_bytes, start_key, prefix_key, next_verison_prefix_key;
double start_score = !reversed ? kMinScore : kMaxScore;
PutDouble(&start_score_bytes, start_score);
- InternalKey(ns_key, start_score_bytes, metadata.version, storage_->IsSlotIdEncoded()).Encode(&start_key);
- InternalKey(ns_key, "", metadata.version, storage_->IsSlotIdEncoded()).Encode(&prefix_key);
- InternalKey(ns_key, "", metadata.version + 1, storage_->IsSlotIdEncoded()).Encode(&next_verison_prefix_key);
+ InternalKey(ns_key, start_score_bytes, metadata.version_, storage_->IsSlotIdEncoded()).Encode(&start_key);
+ InternalKey(ns_key, "", metadata.version_, storage_->IsSlotIdEncoded()).Encode(&prefix_key);
+ InternalKey(ns_key, "", metadata.version_ + 1, storage_->IsSlotIdEncoded()).Encode(&next_verison_prefix_key);
int rank = 0;
rocksdb::Slice upper_bound(next_verison_prefix_key);
@@ -637,14 +637,14 @@ rocksdb::Status ZSet::Overwrite(const Slice &user_key, const std::vector<MemberS
batch->PutLogData(log_data.Encode());
for (const auto &ms : mscores) {
std::string member_key, score_bytes, score_key;
- InternalKey(ns_key, ms.member, metadata.version, storage_->IsSlotIdEncoded()).Encode(&member_key);
- PutDouble(&score_bytes, ms.score);
+ InternalKey(ns_key, ms.member_, metadata.version_, storage_->IsSlotIdEncoded()).Encode(&member_key);
+ PutDouble(&score_bytes, ms.score_);
batch->Put(member_key, score_bytes);
- score_bytes.append(ms.member);
- InternalKey(ns_key, score_bytes, metadata.version, storage_->IsSlotIdEncoded()).Encode(&score_key);
+ score_bytes.append(ms.member_);
+ InternalKey(ns_key, score_bytes, metadata.version_, storage_->IsSlotIdEncoded()).Encode(&score_key);
batch->Put(score_cf_handle_, score_key, Slice());
}
- metadata.size = static_cast<uint32_t>(mscores.size());
+ metadata.size_ = static_cast<uint32_t>(mscores.size());
std::string bytes;
metadata.Encode(&bytes);
batch->Put(metadata_cf_handle_, ns_key, bytes);
@@ -660,40 +660,40 @@ rocksdb::Status ZSet::InterStore(const Slice &dst, const std::vector<KeyWeight>
std::vector<MemberScore> target_mscores;
int target_size = 0;
ZRangeSpec spec;
- auto s = RangeByScore(keys_weights[0].key, spec, &target_mscores, &target_size);
+ auto s = RangeByScore(keys_weights[0].key_, spec, &target_mscores, &target_size);
if (!s.ok() || target_mscores.empty()) return s;
for (const auto &ms : target_mscores) {
- double score = ms.score * keys_weights[0].weight;
+ double score = ms.score_ * keys_weights[0].weight_;
if (std::isnan(score)) score = 0;
- dst_zset[ms.member] = score;
- member_counters[ms.member] = 1;
+ dst_zset[ms.member_] = score;
+ member_counters[ms.member_] = 1;
}
for (size_t i = 1; i < keys_weights.size(); i++) {
- s = RangeByScore(keys_weights[i].key, spec, &target_mscores, &target_size);
+ s = RangeByScore(keys_weights[i].key_, spec, &target_mscores, &target_size);
if (!s.ok() || target_mscores.empty()) return s;
for (const auto &ms : target_mscores) {
- if (dst_zset.find(ms.member) == dst_zset.end()) continue;
- member_counters[ms.member]++;
- double score = ms.score * keys_weights[i].weight;
+ if (dst_zset.find(ms.member_) == dst_zset.end()) continue;
+ member_counters[ms.member_]++;
+ double score = ms.score_ * keys_weights[i].weight_;
if (std::isnan(score)) score = 0;
switch (aggregate_method) {
case kAggregateSum:
- dst_zset[ms.member] += score;
- if (std::isnan(dst_zset[ms.member])) {
- dst_zset[ms.member] = 0;
+ dst_zset[ms.member_] += score;
+ if (std::isnan(dst_zset[ms.member_])) {
+ dst_zset[ms.member_] = 0;
}
break;
case kAggregateMin:
- if (dst_zset[ms.member] > score) {
- dst_zset[ms.member] = score;
+ if (dst_zset[ms.member_] > score) {
+ dst_zset[ms.member_] = score;
}
break;
case kAggregateMax:
- if (dst_zset[ms.member] < score) {
- dst_zset[ms.member] = score;
+ if (dst_zset[ms.member_] < score) {
+ dst_zset[ms.member_] = score;
}
break;
}
@@ -722,27 +722,27 @@ rocksdb::Status ZSet::UnionStore(const Slice &dst, const std::vector<KeyWeight>
ZRangeSpec spec;
for (const auto &key_weight : keys_weights) {
// get all member
- auto s = RangeByScore(key_weight.key, spec, &target_mscores, &target_size);
+ auto s = RangeByScore(key_weight.key_, spec, &target_mscores, &target_size);
if (!s.ok() && !s.IsNotFound()) return s;
for (const auto &ms : target_mscores) {
- double score = ms.score * key_weight.weight;
+ double score = ms.score_ * key_weight.weight_;
if (std::isnan(score)) score = 0;
- if (dst_zset.find(ms.member) == dst_zset.end()) {
- dst_zset[ms.member] = score;
+ if (dst_zset.find(ms.member_) == dst_zset.end()) {
+ dst_zset[ms.member_] = score;
} else {
switch (aggregate_method) {
case kAggregateSum:
- dst_zset[ms.member] += score;
- if (std::isnan(dst_zset[ms.member])) dst_zset[ms.member] = 0;
+ dst_zset[ms.member_] += score;
+ if (std::isnan(dst_zset[ms.member_])) dst_zset[ms.member_] = 0;
break;
case kAggregateMin:
- if (dst_zset[ms.member] > score) {
- dst_zset[ms.member] = score;
+ if (dst_zset[ms.member_] > score) {
+ dst_zset[ms.member_] = score;
}
break;
case kAggregateMax:
- if (dst_zset[ms.member] < score) {
- dst_zset[ms.member] = score;
+ if (dst_zset[ms.member_] < score) {
+ dst_zset[ms.member_] = score;
}
break;
}
@@ -770,29 +770,29 @@ Status ZSet::ParseRangeSpec(const std::string &min, const std::string &max, ZRan
}
if (min == "-inf") {
- spec->min = kMinScore;
+ spec->min_ = kMinScore;
} else {
const char *sptr = min.data();
if (!min.empty() && min[0] == '(') {
- spec->minex = true;
+ spec->minex_ = true;
sptr++;
}
- spec->min = strtod(sptr, &eptr);
- if ((eptr && eptr[0] != '\0') || std::isnan(spec->min)) {
+ spec->min_ = strtod(sptr, &eptr);
+ if ((eptr && eptr[0] != '\0') || std::isnan(spec->min_)) {
return {Status::NotOK, "the min isn't double"};
}
}
if (max == "+inf") {
- spec->max = kMaxScore;
+ spec->max_ = kMaxScore;
} else {
const char *sptr = max.data();
if (!max.empty() && max[0] == '(') {
- spec->maxex = true;
+ spec->maxex_ = true;
sptr++;
}
- spec->max = strtod(sptr, &eptr);
- if ((eptr && eptr[0] != '\0') || std::isnan(spec->max)) {
+ spec->max_ = strtod(sptr, &eptr);
+ if ((eptr && eptr[0] != '\0') || std::isnan(spec->max_)) {
return {Status::NotOK, "the max isn't double"};
}
}
@@ -831,7 +831,7 @@ rocksdb::Status ZSet::MGet(const Slice &user_key, const std::vector<Slice> &memb
read_options.snapshot = ss.GetSnapShot();
std::string score_bytes, member_key;
for (const auto &member : members) {
- InternalKey(ns_key, member, metadata.version, storage_->IsSlotIdEncoded()).Encode(&member_key);
+ InternalKey(ns_key, member, metadata.version_, storage_->IsSlotIdEncoded()).Encode(&member_key);
score_bytes.clear();
s = storage_->Get(read_options, member_key, &score_bytes);
if (!s.ok() && !s.IsNotFound()) return s;
diff --git a/src/types/redis_zset.h b/src/types/redis_zset.h
index c536aeee..288d94c2 100644
--- a/src/types/redis_zset.h
+++ b/src/types/redis_zset.h
@@ -37,21 +37,21 @@ const double kMaxScore = (std::numeric_limits<float>::is_iec559 ? std::numeric_l
: std::numeric_limits<double>::max());
struct ZRangeSpec {
- double min = kMinScore, max = kMaxScore;
- bool minex = false, maxex = false; /* are min or max exclusive */
- int offset = -1, count = -1;
- bool removed = false, reversed = false;
+ double min_ = kMinScore, max_ = kMaxScore;
+ bool minex_ = false, maxex_ = false; /* are min or max exclusive */
+ int offset_ = -1, count_ = -1;
+ bool removed_ = false, reversed_ = false;
ZRangeSpec() = default;
};
struct KeyWeight {
- std::string key;
- double weight;
+ std::string key_;
+ double weight_;
};
struct MemberScore {
- std::string member;
- double score;
+ std::string member_;
+ double score_;
};
enum ZSetFlags {
@@ -67,24 +67,24 @@ enum ZSetFlags {
class ZAddFlags {
public:
- explicit ZAddFlags(uint8_t flags = 0) : flags(flags) {}
+ explicit ZAddFlags(uint8_t flags = 0) : flags_(flags) {}
- bool HasNX() const { return (flags & kZSetNX) != 0; }
- bool HasXX() const { return (flags & kZSetXX) != 0; }
- bool HasLT() const { return (flags & kZSetLT) != 0; }
- bool HasGT() const { return (flags & kZSetGT) != 0; }
- bool HasCH() const { return (flags & kZSetCH) != 0; }
- bool HasIncr() const { return (flags & kZSetIncr) != 0; }
- bool HasAnyFlags() const { return flags != 0; }
+ bool HasNX() const { return (flags_ & kZSetNX) != 0; }
+ bool HasXX() const { return (flags_ & kZSetXX) != 0; }
+ bool HasLT() const { return (flags_ & kZSetLT) != 0; }
+ bool HasGT() const { return (flags_ & kZSetGT) != 0; }
+ bool HasCH() const { return (flags_ & kZSetCH) != 0; }
+ bool HasIncr() const { return (flags_ & kZSetIncr) != 0; }
+ bool HasAnyFlags() const { return flags_ != 0; }
- void SetFlag(ZSetFlags set_flags) { flags |= set_flags; }
+ void SetFlag(ZSetFlags set_flags) { flags_ |= set_flags; }
static ZAddFlags Incr() { return ZAddFlags{kZSetIncr}; }
static ZAddFlags Default() { return ZAddFlags{0}; }
private:
- uint8_t flags = 0;
+ uint8_t flags_ = 0;
};
namespace Redis {
diff --git a/tests/cppunit/cluster_test.cc b/tests/cppunit/cluster_test.cc
index d23014e0..818eaf76 100644
--- a/tests/cppunit/cluster_test.cc
+++ b/tests/cppunit/cluster_test.cc
@@ -150,11 +150,11 @@ TEST(Cluster, CluseterGetSlotInfo) {
ASSERT_TRUE(s.IsOK());
ASSERT_TRUE(slots_infos.size() == 1);
SlotInfo info = slots_infos[0];
- ASSERT_TRUE(info.start == 5461);
- ASSERT_TRUE(info.end == 10922);
- ASSERT_TRUE(info.nodes.size() == 2);
- ASSERT_TRUE(info.nodes[0].port == 30002);
- ASSERT_TRUE(info.nodes[1].id == "07c37dfeb235213a872192d90877d0cd55635b91");
+ ASSERT_TRUE(info.start_ == 5461);
+ ASSERT_TRUE(info.end_ == 10922);
+ ASSERT_TRUE(info.nodes_.size() == 2);
+ ASSERT_TRUE(info.nodes_[0].port_ == 30002);
+ ASSERT_TRUE(info.nodes_[1].id_ == "07c37dfeb235213a872192d90877d0cd55635b91");
}
TEST(Cluster, TestDumpAndLoadClusterNodesInfo) {
@@ -181,17 +181,17 @@ TEST(Cluster, TestDumpAndLoadClusterNodesInfo) {
ASSERT_TRUE(s.IsOK());
ASSERT_EQ(2, slots_infos.size());
SlotInfo slot0_info = slots_infos[0];
- ASSERT_EQ(5461, slot0_info.start);
- ASSERT_EQ(10922, slot0_info.end);
- ASSERT_EQ(2, slot0_info.nodes.size());
- ASSERT_EQ(30002, slot0_info.nodes[0].port);
- ASSERT_EQ("07c37dfeb235213a872192d90877d0cd55635b91", slot0_info.nodes[1].id);
+ ASSERT_EQ(5461, slot0_info.start_);
+ ASSERT_EQ(10922, slot0_info.end_);
+ ASSERT_EQ(2, slot0_info.nodes_.size());
+ ASSERT_EQ(30002, slot0_info.nodes_[0].port_);
+ ASSERT_EQ("07c37dfeb235213a872192d90877d0cd55635b91", slot0_info.nodes_[1].id_);
SlotInfo slot1_info = slots_infos[1];
- ASSERT_EQ(10923, slot1_info.start);
- ASSERT_EQ(16383, slot1_info.end);
- ASSERT_EQ(1, slot1_info.nodes.size());
- ASSERT_EQ(30003, slot1_info.nodes[0].port);
- ASSERT_EQ("17ed2db8d677e59ec4a4cefb06858cf2a1a89fa1", slot1_info.nodes[0].id);
+ ASSERT_EQ(10923, slot1_info.start_);
+ ASSERT_EQ(16383, slot1_info.end_);
+ ASSERT_EQ(1, slot1_info.nodes_.size());
+ ASSERT_EQ(30003, slot1_info.nodes_[0].port_);
+ ASSERT_EQ("17ed2db8d677e59ec4a4cefb06858cf2a1a89fa1", slot1_info.nodes_[0].id_);
unlink(nodes_filename.c_str());
}
diff --git a/tests/cppunit/compact_test.cc b/tests/cppunit/compact_test.cc
index 39d74251..3dbc25c3 100644
--- a/tests/cppunit/compact_test.cc
+++ b/tests/cppunit/compact_test.cc
@@ -29,9 +29,9 @@
TEST(Compact, Filter) {
Config config;
- config.db_dir = "compactdb";
- config.backup_dir = "compactdb/backup";
- config.slot_id_encoded = false;
+ config.db_dir_ = "compactdb";
+ config.backup_dir_ = "compactdb/backup";
+ config.slot_id_encoded_ = false;
auto storage = std::make_unique<Engine::Storage>(&config);
Status s = storage->Open();
@@ -118,7 +118,7 @@ TEST(Compact, Filter) {
db->ReleaseSnapshot(read_options.snapshot);
std::error_code ec;
- std::filesystem::remove_all(config.db_dir, ec);
+ std::filesystem::remove_all(config.db_dir_, ec);
if (ec) {
std::cout << "Encounter filesystem error: " << ec << std::endl;
}
diff --git a/tests/cppunit/config_test.cc b/tests/cppunit/config_test.cc
index 4dc3e832..47df85b8 100644
--- a/tests/cppunit/config_test.cc
+++ b/tests/cppunit/config_test.cc
@@ -187,9 +187,9 @@ TEST(Namespace, Add) {
Config config;
auto s = config.Load(CLIOptions(path));
EXPECT_FALSE(s.IsOK());
- config.slot_id_encoded = false;
+ config.slot_id_encoded_ = false;
EXPECT_TRUE(!config.AddNamespace("ns", "t0").IsOK());
- config.requirepass = "foobared";
+ config.requirepass_ = "foobared";
std::vector<std::string> namespaces = {"n1", "n2", "n3", "n4"};
std::vector<std::string> tokens = {"t1", "t2", "t3", "t4"};
@@ -224,8 +224,8 @@ TEST(Namespace, Set) {
Config config;
auto s = config.Load(CLIOptions(path));
EXPECT_FALSE(s.IsOK());
- config.slot_id_encoded = false;
- config.requirepass = "foobared";
+ config.slot_id_encoded_ = false;
+ config.requirepass_ = "foobared";
std::vector<std::string> namespaces = {"n1", "n2", "n3", "n4"};
std::vector<std::string> tokens = {"t1", "t2", "t3", "t4"};
std::vector<std::string> new_tokens = {"nt1", "nt2'", "nt3", "nt4"};
@@ -262,8 +262,8 @@ TEST(Namespace, Delete) {
Config config;
auto s = config.Load(CLIOptions(path));
EXPECT_FALSE(s.IsOK());
- config.slot_id_encoded = false;
- config.requirepass = "foobared";
+ config.slot_id_encoded_ = false;
+ config.requirepass_ = "foobared";
std::vector<std::string> namespaces = {"n1", "n2", "n3", "n4"};
std::vector<std::string> tokens = {"t1", "t2", "t3", "t4"};
for (size_t i = 0; i < namespaces.size(); i++) {
@@ -292,9 +292,9 @@ TEST(Namespace, RewriteNamespaces) {
Config config;
auto s = config.Load(CLIOptions(path));
EXPECT_FALSE(s.IsOK());
- config.requirepass = "test";
- config.backup_dir = "test";
- config.slot_id_encoded = false;
+ config.requirepass_ = "test";
+ config.backup_dir_ = "test";
+ config.slot_id_encoded_ = false;
std::vector<std::string> namespaces = {"n1", "n2", "n3", "n4"};
std::vector<std::string> tokens = {"t1", "t2", "t3", "t4"};
for (size_t i = 0; i < namespaces.size(); i++) {
diff --git a/tests/cppunit/cron_test.cc b/tests/cppunit/cron_test.cc
index 612ee7ec..9322050c 100644
--- a/tests/cppunit/cron_test.cc
+++ b/tests/cppunit/cron_test.cc
@@ -27,26 +27,26 @@
class CronTest : public testing::Test {
protected:
explicit CronTest() {
- cron = std::make_unique<Cron>();
+ cron_ = std::make_unique<Cron>();
std::vector<std::string> schedule{"*", "3", "*", "*", "*"};
- auto s = cron->SetScheduleTime(schedule);
+ auto s = cron_->SetScheduleTime(schedule);
EXPECT_TRUE(s.IsOK());
}
~CronTest() override = default;
- std::unique_ptr<Cron> cron;
+ std::unique_ptr<Cron> cron_;
};
TEST_F(CronTest, IsTimeMatch) {
std::time_t t = std::time(nullptr);
std::tm *now = std::localtime(&t);
now->tm_hour = 3;
- ASSERT_TRUE(cron->IsTimeMatch(now));
+ ASSERT_TRUE(cron_->IsTimeMatch(now));
now->tm_hour = 4;
- ASSERT_FALSE(cron->IsTimeMatch(now));
+ ASSERT_FALSE(cron_->IsTimeMatch(now));
}
TEST_F(CronTest, ToString) {
- std::string got = cron->ToString();
+ std::string got = cron_->ToString();
ASSERT_EQ("* 3 * * *", got);
}
diff --git a/tests/cppunit/disk_test.cc b/tests/cppunit/disk_test.cc
index a46f9aa4..cd466709 100644
--- a/tests/cppunit/disk_test.cc
+++ b/tests/cppunit/disk_test.cc
@@ -138,9 +138,9 @@ TEST_F(RedisDiskTest, ZsetDisk) {
std::vector<MemberScore> mscores(5);
std::vector<int> value_size{1024, 1024, 1024, 1024, 1024};
for (int i = 0; i < int(value_size.size()); i++) {
- mscores[i].member = std::string(value_size[i], static_cast<char>('a' + i));
- mscores[i].score = 1.0;
- approximate_size += (key_.size() + 8 + mscores[i].member.size() + 8) * 2;
+ mscores[i].member_ = std::string(value_size[i], static_cast<char>('a' + i));
+ mscores[i].score_ = 1.0;
+ approximate_size += (key_.size() + 8 + mscores[i].member_.size() + 8) * 2;
}
rocksdb::Status s = zset->Add(key_, ZAddFlags::Default(), &mscores, &ret);
EXPECT_TRUE(s.ok() && ret == 5);
@@ -190,7 +190,7 @@ TEST_F(RedisDiskTest, StreamDisk) {
std::unique_ptr<Redis::Disk> disk = std::make_unique<Redis::Disk>(storage_, "disk_ns_stream");
key_ = "streamdisk_key";
Redis::StreamAddOptions options;
- options.with_entry_id = false;
+ options.with_entry_id_ = false;
Redis::StreamEntryID id;
uint64_t approximate_size = 0;
for (int i = 0; i < 100000; i++) {
diff --git a/tests/cppunit/status_test.cc b/tests/cppunit/status_test.cc
index 56e440c3..f6d49cc9 100644
--- a/tests/cppunit/status_test.cc
+++ b/tests/cppunit/status_test.cc
@@ -120,10 +120,10 @@ TEST(StatusOr, String) {
TEST(StatusOr, SharedPtr) {
struct A { // NOLINT
- explicit A(int *x) : x(x) { *x = 233; }
- ~A() { *x = 0; }
+ explicit A(int *x) : x_(x) { *x = 233; }
+ ~A() { *x_ = 0; }
- int *x;
+ int *x_;
};
int val = 0;
@@ -168,7 +168,7 @@ TEST(StatusOr, ValueOr) {
TEST(StatusOr, Size) {
struct A {
- std::string a, b;
+ std::string a_, b_;
};
static_assert(!StatusOr<char>::error_type::inplace);
@@ -177,16 +177,16 @@ TEST(StatusOr, Size) {
static_assert(StatusOr<A>::error_type::inplace);
struct B1 {
- char a;
- void *b;
+ char a_;
+ void *b_;
};
struct B2 {
- char a;
- std::string b;
+ char a_;
+ std::string b_;
};
struct B3 {
- char a;
- A b;
+ char a_;
+ A b_;
};
static_assert(sizeof(StatusOr<char>) == sizeof(B1));
static_assert(sizeof(StatusOr<int>) == sizeof(B1));
diff --git a/tests/cppunit/test_base.h b/tests/cppunit/test_base.h
index 612b0380..74668d77 100644
--- a/tests/cppunit/test_base.h
+++ b/tests/cppunit/test_base.h
@@ -30,11 +30,11 @@
class TestBase : public testing::Test { // NOLINT
protected:
explicit TestBase() : config_(new Config()) {
- config_->db_dir = "testdb";
- config_->backup_dir = "testdb/backup";
- config_->RocksDB.compression = rocksdb::CompressionType::kNoCompression;
- config_->RocksDB.write_buffer_size = 1;
- config_->RocksDB.block_size = 100;
+ config_->db_dir_ = "testdb";
+ config_->backup_dir_ = "testdb/backup";
+ config_->rocks_db_.compression_ = rocksdb::CompressionType::kNoCompression;
+ config_->rocks_db_.write_buffer_size_ = 1;
+ config_->rocks_db_.block_size_ = 100;
storage_ = new Engine::Storage(config_);
Status s = storage_->Open();
if (!s.IsOK()) {
@@ -43,7 +43,7 @@ class TestBase : public testing::Test { // NOLINT
}
}
~TestBase() override {
- auto db_dir = config_->db_dir;
+ auto db_dir = config_->db_dir_;
delete storage_;
delete config_;
diff --git a/tests/cppunit/types/bitmap_test.cc b/tests/cppunit/types/bitmap_test.cc
index e3b37a7a..2bc564e5 100644
--- a/tests/cppunit/types/bitmap_test.cc
+++ b/tests/cppunit/types/bitmap_test.cc
@@ -27,65 +27,65 @@
class RedisBitmapTest : public TestBase {
protected:
- explicit RedisBitmapTest() { bitmap = std::make_unique<Redis::Bitmap>(storage_, "bitmap_ns"); }
+ explicit RedisBitmapTest() { bitmap_ = std::make_unique<Redis::Bitmap>(storage_, "bitmap_ns"); }
~RedisBitmapTest() override = default;
void SetUp() override { key_ = "test_bitmap_key"; }
void TearDown() override {}
- std::unique_ptr<Redis::Bitmap> bitmap;
+ std::unique_ptr<Redis::Bitmap> bitmap_;
};
TEST_F(RedisBitmapTest, GetAndSetBit) {
uint32_t offsets[] = {0, 123, 1024 * 8, 1024 * 8 + 1, 3 * 1024 * 8, 3 * 1024 * 8 + 1};
for (const auto &offset : offsets) {
bool bit = false;
- bitmap->GetBit(key_, offset, &bit);
+ bitmap_->GetBit(key_, offset, &bit);
EXPECT_FALSE(bit);
- bitmap->SetBit(key_, offset, true, &bit);
- bitmap->GetBit(key_, offset, &bit);
+ bitmap_->SetBit(key_, offset, true, &bit);
+ bitmap_->GetBit(key_, offset, &bit);
EXPECT_TRUE(bit);
}
- bitmap->Del(key_);
+ bitmap_->Del(key_);
}
TEST_F(RedisBitmapTest, BitCount) {
uint32_t offsets[] = {0, 123, 1024 * 8, 1024 * 8 + 1, 3 * 1024 * 8, 3 * 1024 * 8 + 1};
for (const auto &offset : offsets) {
bool bit = false;
- bitmap->SetBit(key_, offset, true, &bit);
+ bitmap_->SetBit(key_, offset, true, &bit);
}
uint32_t cnt = 0;
- bitmap->BitCount(key_, 0, 4 * 1024, &cnt);
+ bitmap_->BitCount(key_, 0, 4 * 1024, &cnt);
EXPECT_EQ(cnt, 6);
- bitmap->BitCount(key_, 0, -1, &cnt);
+ bitmap_->BitCount(key_, 0, -1, &cnt);
EXPECT_EQ(cnt, 6);
- bitmap->Del(key_);
+ bitmap_->Del(key_);
}
TEST_F(RedisBitmapTest, BitPosClearBit) {
int64_t pos = 0;
bool old_bit = false;
for (int i = 0; i < 1024 + 16; i++) {
- bitmap->BitPos(key_, false, 0, -1, true, &pos);
+ bitmap_->BitPos(key_, false, 0, -1, true, &pos);
EXPECT_EQ(pos, i);
- bitmap->SetBit(key_, i, true, &old_bit);
+ bitmap_->SetBit(key_, i, true, &old_bit);
EXPECT_FALSE(old_bit);
}
- bitmap->Del(key_);
+ bitmap_->Del(key_);
}
TEST_F(RedisBitmapTest, BitPosSetBit) {
uint32_t offsets[] = {0, 123, 1024 * 8, 1024 * 8 + 16, 3 * 1024 * 8, 3 * 1024 * 8 + 16};
for (const auto &offset : offsets) {
bool bit = false;
- bitmap->SetBit(key_, offset, true, &bit);
+ bitmap_->SetBit(key_, offset, true, &bit);
}
int64_t pos = 0;
int start_indexes[] = {0, 1, 124, 1025, 1027, 3 * 1024 + 1};
for (size_t i = 0; i < sizeof(start_indexes) / sizeof(start_indexes[0]); i++) {
- bitmap->BitPos(key_, true, start_indexes[i], -1, true, &pos);
+ bitmap_->BitPos(key_, true, start_indexes[i], -1, true, &pos);
EXPECT_EQ(pos, offsets[i]);
}
- bitmap->Del(key_);
+ bitmap_->Del(key_);
}
diff --git a/tests/cppunit/types/geo_test.cc b/tests/cppunit/types/geo_test.cc
index 6f91d3c6..5636af9f 100644
--- a/tests/cppunit/types/geo_test.cc
+++ b/tests/cppunit/types/geo_test.cc
@@ -28,7 +28,7 @@
class RedisGeoTest : public TestBase {
protected:
- RedisGeoTest() { geo = std::make_unique<Redis::Geo>(storage_, "geo_ns"); }
+ RedisGeoTest() { geo_ = std::make_unique<Redis::Geo>(storage_, "geo_ns"); }
~RedisGeoTest() override = default;
void SetUp() override {
@@ -37,14 +37,14 @@ class RedisGeoTest : public TestBase {
"geo_test_key-5", "geo_test_key-6", "geo_test_key-7"};
longitudes_ = {-180, -1.23402, -1.23402, 0, 1.23402, 1.23402, 179.12345};
latitudes_ = {-85.05112878, -1.23402, -1.23402, 0, 1.23402, 1.23402, 85.0511};
- geoHashes_ = {"00bh0hbj200", "7zz0gzm7m10", "7zz0gzm7m10", "s0000000000",
- "s00zh0dsdy0", "s00zh0dsdy0", "zzp7u51dwf0"};
+ geo_hashes_ = {"00bh0hbj200", "7zz0gzm7m10", "7zz0gzm7m10", "s0000000000",
+ "s00zh0dsdy0", "s00zh0dsdy0", "zzp7u51dwf0"};
}
std::vector<double> longitudes_;
std::vector<double> latitudes_;
- std::vector<std::string> geoHashes_;
- std::unique_ptr<Redis::Geo> geo;
+ std::vector<std::string> geo_hashes_;
+ std::unique_ptr<Redis::Geo> geo_;
};
TEST_F(RedisGeoTest, Add) {
@@ -53,16 +53,16 @@ TEST_F(RedisGeoTest, Add) {
for (size_t i = 0; i < fields_.size(); i++) {
geo_points.emplace_back(GeoPoint{longitudes_[i], latitudes_[i], fields_[i].ToString()});
}
- geo->Add(key_, &geo_points, &ret);
+ geo_->Add(key_, &geo_points, &ret);
EXPECT_EQ(static_cast<int>(fields_.size()), ret);
std::vector<std::string> geo_hashes;
- geo->Hash(key_, fields_, &geo_hashes);
+ geo_->Hash(key_, fields_, &geo_hashes);
for (size_t i = 0; i < fields_.size(); i++) {
- EXPECT_EQ(geo_hashes[i], geoHashes_[i]);
+ EXPECT_EQ(geo_hashes[i], geo_hashes_[i]);
}
- geo->Add(key_, &geo_points, &ret);
+ geo_->Add(key_, &geo_points, &ret);
EXPECT_EQ(ret, 0);
- geo->Del(key_);
+ geo_->Del(key_);
}
TEST_F(RedisGeoTest, Dist) {
@@ -71,12 +71,12 @@ TEST_F(RedisGeoTest, Dist) {
for (size_t i = 0; i < fields_.size(); i++) {
geo_points.emplace_back(GeoPoint{longitudes_[i], latitudes_[i], fields_[i].ToString()});
}
- geo->Add(key_, &geo_points, &ret);
+ geo_->Add(key_, &geo_points, &ret);
EXPECT_EQ(fields_.size(), ret);
double dist = 0.0;
- geo->Dist(key_, fields_[2], fields_[3], &dist);
+ geo_->Dist(key_, fields_[2], fields_[3], &dist);
EXPECT_EQ(ceilf(dist), 194102);
- geo->Del(key_);
+ geo_->Del(key_);
}
TEST_F(RedisGeoTest, Hash) {
@@ -85,14 +85,14 @@ TEST_F(RedisGeoTest, Hash) {
for (size_t i = 0; i < fields_.size(); i++) {
geo_points.emplace_back(GeoPoint{longitudes_[i], latitudes_[i], fields_[i].ToString()});
}
- geo->Add(key_, &geo_points, &ret);
+ geo_->Add(key_, &geo_points, &ret);
EXPECT_EQ(static_cast<int>(fields_.size()), ret);
std::vector<std::string> geo_hashes;
- geo->Hash(key_, fields_, &geo_hashes);
+ geo_->Hash(key_, fields_, &geo_hashes);
for (size_t i = 0; i < fields_.size(); i++) {
- EXPECT_EQ(geo_hashes[i], geoHashes_[i]);
+ EXPECT_EQ(geo_hashes[i], geo_hashes_[i]);
}
- geo->Del(key_);
+ geo_->Del(key_);
}
TEST_F(RedisGeoTest, Pos) {
@@ -101,16 +101,16 @@ TEST_F(RedisGeoTest, Pos) {
for (size_t i = 0; i < fields_.size(); i++) {
geo_points.emplace_back(GeoPoint{longitudes_[i], latitudes_[i], fields_[i].ToString()});
}
- geo->Add(key_, &geo_points, &ret);
+ geo_->Add(key_, &geo_points, &ret);
EXPECT_EQ(static_cast<int>(fields_.size()), ret);
std::map<std::string, GeoPoint> gps;
- geo->Pos(key_, fields_, &gps);
+ geo_->Pos(key_, fields_, &gps);
for (size_t i = 0; i < fields_.size(); i++) {
- EXPECT_EQ(gps[fields_[i].ToString()].member, fields_[i].ToString());
- EXPECT_EQ(geo->EncodeGeoHash(gps[fields_[i].ToString()].longitude, gps[fields_[i].ToString()].latitude),
- geoHashes_[i]);
+ EXPECT_EQ(gps[fields_[i].ToString()].member_, fields_[i].ToString());
+ EXPECT_EQ(geo_->EncodeGeoHash(gps[fields_[i].ToString()].longitude_, gps[fields_[i].ToString()].latitude_),
+ geo_hashes_[i]);
}
- geo->Del(key_);
+ geo_->Del(key_);
}
TEST_F(RedisGeoTest, Radius) {
@@ -119,16 +119,16 @@ TEST_F(RedisGeoTest, Radius) {
for (size_t i = 0; i < fields_.size(); i++) {
geo_points.emplace_back(GeoPoint{longitudes_[i], latitudes_[i], fields_[i].ToString()});
}
- geo->Add(key_, &geo_points, &ret);
+ geo_->Add(key_, &geo_points, &ret);
EXPECT_EQ(static_cast<int>(fields_.size()), ret);
std::vector<GeoPoint> gps;
- geo->Radius(key_, longitudes_[0], latitudes_[0], 100000000, 100, kSortASC, std::string(), false, 1, &gps);
+ geo_->Radius(key_, longitudes_[0], latitudes_[0], 100000000, 100, kSortASC, std::string(), false, 1, &gps);
EXPECT_EQ(gps.size(), fields_.size());
for (size_t i = 0; i < gps.size(); i++) {
- EXPECT_EQ(gps[i].member, fields_[i].ToString());
- EXPECT_EQ(geo->EncodeGeoHash(gps[i].longitude, gps[i].latitude), geoHashes_[i]);
+ EXPECT_EQ(gps[i].member_, fields_[i].ToString());
+ EXPECT_EQ(geo_->EncodeGeoHash(gps[i].longitude_, gps[i].latitude_), geo_hashes_[i]);
}
- geo->Del(key_);
+ geo_->Del(key_);
}
TEST_F(RedisGeoTest, RadiusByMember) {
@@ -137,14 +137,14 @@ TEST_F(RedisGeoTest, RadiusByMember) {
for (size_t i = 0; i < fields_.size(); i++) {
geo_points.emplace_back(GeoPoint{longitudes_[i], latitudes_[i], fields_[i].ToString()});
}
- geo->Add(key_, &geo_points, &ret);
+ geo_->Add(key_, &geo_points, &ret);
EXPECT_EQ(static_cast<int>(fields_.size()), ret);
std::vector<GeoPoint> gps;
- geo->RadiusByMember(key_, fields_[0], 100000000, 100, kSortASC, std::string(), false, 1, &gps);
+ geo_->RadiusByMember(key_, fields_[0], 100000000, 100, kSortASC, std::string(), false, 1, &gps);
EXPECT_EQ(gps.size(), fields_.size());
for (size_t i = 0; i < gps.size(); i++) {
- EXPECT_EQ(gps[i].member, fields_[i].ToString());
- EXPECT_EQ(geo->EncodeGeoHash(gps[i].longitude, gps[i].latitude), geoHashes_[i]);
+ EXPECT_EQ(gps[i].member_, fields_[i].ToString());
+ EXPECT_EQ(geo_->EncodeGeoHash(gps[i].longitude_, gps[i].latitude_), geo_hashes_[i]);
}
- geo->Del(key_);
+ geo_->Del(key_);
}
diff --git a/tests/cppunit/types/hash_test.cc b/tests/cppunit/types/hash_test.cc
index f66a3250..b8c509ae 100644
--- a/tests/cppunit/types/hash_test.cc
+++ b/tests/cppunit/types/hash_test.cc
@@ -32,7 +32,7 @@
class RedisHashTest : public TestBase {
protected:
- explicit RedisHashTest() { hash = std::make_unique<Redis::Hash>(storage_, "hash_ns"); }
+ explicit RedisHashTest() { hash_ = std::make_unique<Redis::Hash>(storage_, "hash_ns"); }
~RedisHashTest() override = default;
void SetUp() override {
@@ -42,24 +42,24 @@ class RedisHashTest : public TestBase {
}
void TearDown() override {}
- std::unique_ptr<Redis::Hash> hash;
+ std::unique_ptr<Redis::Hash> hash_;
};
TEST_F(RedisHashTest, GetAndSet) {
int ret = 0;
for (size_t i = 0; i < fields_.size(); i++) {
- auto s = hash->Set(key_, fields_[i], values_[i], &ret);
+ auto s = hash_->Set(key_, fields_[i], values_[i], &ret);
EXPECT_TRUE(s.ok() && ret == 1);
}
for (size_t i = 0; i < fields_.size(); i++) {
std::string got;
- auto s = hash->Get(key_, fields_[i], &got);
+ auto s = hash_->Get(key_, fields_[i], &got);
EXPECT_EQ(s.ToString(), "OK");
EXPECT_EQ(values_[i], got);
}
- auto s = hash->Delete(key_, fields_, &ret);
+ auto s = hash_->Delete(key_, fields_, &ret);
EXPECT_TRUE(s.ok() && static_cast<int>(fields_.size()) == ret);
- hash->Del(key_);
+ hash_->Del(key_);
}
TEST_F(RedisHashTest, MGetAndMSet) {
@@ -68,136 +68,136 @@ TEST_F(RedisHashTest, MGetAndMSet) {
for (size_t i = 0; i < fields_.size(); i++) {
fvs.emplace_back(fields_[i].ToString(), values_[i].ToString());
}
- auto s = hash->MSet(key_, fvs, false, &ret);
+ auto s = hash_->MSet(key_, fvs, false, &ret);
EXPECT_TRUE(s.ok() && static_cast<int>(fvs.size()) == ret);
- s = hash->MSet(key_, fvs, false, &ret);
+ s = hash_->MSet(key_, fvs, false, &ret);
EXPECT_TRUE(s.ok());
EXPECT_EQ(ret, 0);
std::vector<std::string> values;
std::vector<rocksdb::Status> statuses;
- s = hash->MGet(key_, fields_, &values, &statuses);
+ s = hash_->MGet(key_, fields_, &values, &statuses);
EXPECT_TRUE(s.ok());
for (size_t i = 0; i < fields_.size(); i++) {
EXPECT_EQ(values[i], values_[i].ToString());
}
- s = hash->Delete(key_, fields_, &ret);
+ s = hash_->Delete(key_, fields_, &ret);
EXPECT_TRUE(s.ok());
EXPECT_EQ(static_cast<int>(fields_.size()), ret);
- hash->Del(key_);
+ hash_->Del(key_);
}
TEST_F(RedisHashTest, MSetSingleFieldAndNX) {
int ret = 0;
std::vector<FieldValue> values = {{"field-one", "value-one"}};
- auto s = hash->MSet(key_, values, true, &ret);
+ auto s = hash_->MSet(key_, values, true, &ret);
EXPECT_TRUE(s.ok() && ret == 1);
std::string field2 = "field-two";
std::string initial_value = "value-two";
- s = hash->Set(key_, field2, initial_value, &ret);
+ s = hash_->Set(key_, field2, initial_value, &ret);
EXPECT_TRUE(s.ok() && ret == 1);
values = {{field2, "value-two-changed"}};
- s = hash->MSet(key_, values, true, &ret);
+ s = hash_->MSet(key_, values, true, &ret);
EXPECT_TRUE(s.ok() && ret == 0);
std::string final_value;
- s = hash->Get(key_, field2, &final_value);
+ s = hash_->Get(key_, field2, &final_value);
EXPECT_TRUE(s.ok());
EXPECT_EQ(initial_value, final_value);
- hash->Del(key_);
+ hash_->Del(key_);
}
TEST_F(RedisHashTest, MSetMultipleFieldsAndNX) {
int ret = 0;
std::vector<FieldValue> values = {{"field-one", "value-one"}, {"field-two", "value-two"}};
- auto s = hash->MSet(key_, values, true, &ret);
+ auto s = hash_->MSet(key_, values, true, &ret);
EXPECT_TRUE(s.ok() && ret == 2);
values = {{"field-one", "value-one"}, {"field-two", "value-two-changed"}, {"field-three", "value-three"}};
- s = hash->MSet(key_, values, true, &ret);
+ s = hash_->MSet(key_, values, true, &ret);
EXPECT_TRUE(s.ok());
EXPECT_EQ(ret, 1);
std::string value;
- s = hash->Get(key_, "field-one", &value);
+ s = hash_->Get(key_, "field-one", &value);
EXPECT_TRUE(s.ok() && value == "value-one");
- s = hash->Get(key_, "field-two", &value);
+ s = hash_->Get(key_, "field-two", &value);
EXPECT_TRUE(s.ok() && value == "value-two");
- s = hash->Get(key_, "field-three", &value);
+ s = hash_->Get(key_, "field-three", &value);
EXPECT_TRUE(s.ok() && value == "value-three");
- hash->Del(key_);
+ hash_->Del(key_);
}
TEST_F(RedisHashTest, HGetAll) {
int ret = 0;
for (size_t i = 0; i < fields_.size(); i++) {
- auto s = hash->Set(key_, fields_[i], values_[i], &ret);
+ auto s = hash_->Set(key_, fields_[i], values_[i], &ret);
EXPECT_TRUE(s.ok() && ret == 1);
}
std::vector<FieldValue> fvs;
- auto s = hash->GetAll(key_, &fvs);
+ auto s = hash_->GetAll(key_, &fvs);
EXPECT_TRUE(s.ok() && fvs.size() == fields_.size());
- s = hash->Delete(key_, fields_, &ret);
+ s = hash_->Delete(key_, fields_, &ret);
EXPECT_TRUE(s.ok() && static_cast<int>(fields_.size()) == ret);
- hash->Del(key_);
+ hash_->Del(key_);
}
TEST_F(RedisHashTest, HIncr) {
int64_t value = 0;
Slice field("hash-incrby-invalid-field");
for (int i = 0; i < 32; i++) {
- auto s = hash->IncrBy(key_, field, 1, &value);
+ auto s = hash_->IncrBy(key_, field, 1, &value);
EXPECT_TRUE(s.ok());
}
std::string bytes;
- hash->Get(key_, field, &bytes);
+ hash_->Get(key_, field, &bytes);
auto parse_result = ParseInt<int64_t>(bytes, 10);
if (!parse_result) {
FAIL();
}
EXPECT_EQ(32, *parse_result);
- hash->Del(key_);
+ hash_->Del(key_);
}
TEST_F(RedisHashTest, HIncrInvalid) {
int ret = 0;
int64_t value = 0;
Slice field("hash-incrby-invalid-field");
- auto s = hash->IncrBy(key_, field, 1, &value);
+ auto s = hash_->IncrBy(key_, field, 1, &value);
EXPECT_TRUE(s.ok() && value == 1);
- s = hash->IncrBy(key_, field, LLONG_MAX, &value);
+ s = hash_->IncrBy(key_, field, LLONG_MAX, &value);
EXPECT_TRUE(s.IsInvalidArgument());
- hash->Set(key_, field, "abc", &ret);
- s = hash->IncrBy(key_, field, 1, &value);
+ hash_->Set(key_, field, "abc", &ret);
+ s = hash_->IncrBy(key_, field, 1, &value);
EXPECT_TRUE(s.IsInvalidArgument());
- hash->Set(key_, field, "-1", &ret);
- s = hash->IncrBy(key_, field, -1, &value);
+ hash_->Set(key_, field, "-1", &ret);
+ s = hash_->IncrBy(key_, field, -1, &value);
EXPECT_TRUE(s.ok());
- s = hash->IncrBy(key_, field, LLONG_MIN, &value);
+ s = hash_->IncrBy(key_, field, LLONG_MIN, &value);
EXPECT_TRUE(s.IsInvalidArgument());
- hash->Del(key_);
+ hash_->Del(key_);
}
TEST_F(RedisHashTest, HIncrByFloat) {
double value = 0.0;
Slice field("hash-incrbyfloat-invalid-field");
for (int i = 0; i < 32; i++) {
- auto s = hash->IncrByFloat(key_, field, 1.2, &value);
+ auto s = hash_->IncrByFloat(key_, field, 1.2, &value);
EXPECT_TRUE(s.ok());
}
std::string bytes;
- hash->Get(key_, field, &bytes);
+ hash_->Get(key_, field, &bytes);
value = std::stof(bytes);
EXPECT_FLOAT_EQ(32 * 1.2, value);
- hash->Del(key_);
+ hash_->Del(key_);
}
TEST_F(RedisHashTest, HRangeByLex) {
@@ -215,119 +215,119 @@ TEST_F(RedisHashTest, HRangeByLex) {
std::vector<FieldValue> tmp(fvs);
for (size_t i = 0; i < 100; i++) {
std::shuffle(tmp.begin(), tmp.end(), g);
- auto s = hash->MSet(key_, tmp, false, &ret);
+ auto s = hash_->MSet(key_, tmp, false, &ret);
EXPECT_TRUE(s.ok() && static_cast<int>(tmp.size()) == ret);
- s = hash->MSet(key_, fvs, false, &ret);
+ s = hash_->MSet(key_, fvs, false, &ret);
EXPECT_TRUE(s.ok());
EXPECT_EQ(ret, 0);
std::vector<FieldValue> result;
CommonRangeLexSpec spec;
- spec.offset = 0;
- spec.count = INT_MAX;
- spec.min = "key0";
- spec.max = "key3";
- s = hash->RangeByLex(key_, spec, &result);
+ spec.offset_ = 0;
+ spec.count_ = INT_MAX;
+ spec.min_ = "key0";
+ spec.max_ = "key3";
+ s = hash_->RangeByLex(key_, spec, &result);
EXPECT_TRUE(s.ok());
EXPECT_EQ(4, result.size());
- EXPECT_EQ("key0", result[0].field);
- EXPECT_EQ("key1", result[1].field);
- EXPECT_EQ("key2", result[2].field);
- EXPECT_EQ("key3", result[3].field);
- hash->Del(key_);
+ EXPECT_EQ("key0", result[0].field_);
+ EXPECT_EQ("key1", result[1].field_);
+ EXPECT_EQ("key2", result[2].field_);
+ EXPECT_EQ("key3", result[3].field_);
+ hash_->Del(key_);
}
- auto s = hash->MSet(key_, tmp, false, &ret);
+ auto s = hash_->MSet(key_, tmp, false, &ret);
EXPECT_TRUE(s.ok() && static_cast<int>(tmp.size()) == ret);
// use offset and count
std::vector<FieldValue> result;
CommonRangeLexSpec spec;
- spec.offset = 0;
- spec.count = INT_MAX;
- spec.min = "key0";
- spec.max = "key3";
- spec.offset = 1;
- s = hash->RangeByLex(key_, spec, &result);
+ spec.offset_ = 0;
+ spec.count_ = INT_MAX;
+ spec.min_ = "key0";
+ spec.max_ = "key3";
+ spec.offset_ = 1;
+ s = hash_->RangeByLex(key_, spec, &result);
EXPECT_TRUE(s.ok());
EXPECT_EQ(3, result.size());
- EXPECT_EQ("key1", result[0].field);
- EXPECT_EQ("key2", result[1].field);
- EXPECT_EQ("key3", result[2].field);
+ EXPECT_EQ("key1", result[0].field_);
+ EXPECT_EQ("key2", result[1].field_);
+ EXPECT_EQ("key3", result[2].field_);
- spec.offset = 1;
- spec.count = 1;
- s = hash->RangeByLex(key_, spec, &result);
+ spec.offset_ = 1;
+ spec.count_ = 1;
+ s = hash_->RangeByLex(key_, spec, &result);
EXPECT_TRUE(s.ok());
EXPECT_EQ(1, result.size());
- EXPECT_EQ("key1", result[0].field);
+ EXPECT_EQ("key1", result[0].field_);
- spec.offset = 0;
- spec.count = 0;
- s = hash->RangeByLex(key_, spec, &result);
+ spec.offset_ = 0;
+ spec.count_ = 0;
+ s = hash_->RangeByLex(key_, spec, &result);
EXPECT_TRUE(s.ok());
EXPECT_EQ(0, result.size());
- spec.offset = 1000;
- spec.count = 1000;
- s = hash->RangeByLex(key_, spec, &result);
+ spec.offset_ = 1000;
+ spec.count_ = 1000;
+ s = hash_->RangeByLex(key_, spec, &result);
EXPECT_TRUE(s.ok());
EXPECT_EQ(0, result.size());
// exclusive range
- spec.offset = 0;
- spec.count = -1;
- spec.minex = true;
- s = hash->RangeByLex(key_, spec, &result);
+ spec.offset_ = 0;
+ spec.count_ = -1;
+ spec.minex_ = true;
+ s = hash_->RangeByLex(key_, spec, &result);
EXPECT_TRUE(s.ok());
EXPECT_EQ(3, result.size());
- EXPECT_EQ("key1", result[0].field);
- EXPECT_EQ("key2", result[1].field);
- EXPECT_EQ("key3", result[2].field);
-
- spec.offset = 0;
- spec.count = -1;
- spec.maxex = true;
- spec.minex = false;
- s = hash->RangeByLex(key_, spec, &result);
+ EXPECT_EQ("key1", result[0].field_);
+ EXPECT_EQ("key2", result[1].field_);
+ EXPECT_EQ("key3", result[2].field_);
+
+ spec.offset_ = 0;
+ spec.count_ = -1;
+ spec.maxex_ = true;
+ spec.minex_ = false;
+ s = hash_->RangeByLex(key_, spec, &result);
EXPECT_TRUE(s.ok());
EXPECT_EQ(3, result.size());
- EXPECT_EQ("key0", result[0].field);
- EXPECT_EQ("key1", result[1].field);
- EXPECT_EQ("key2", result[2].field);
-
- spec.offset = 0;
- spec.count = -1;
- spec.maxex = true;
- spec.minex = true;
- s = hash->RangeByLex(key_, spec, &result);
+ EXPECT_EQ("key0", result[0].field_);
+ EXPECT_EQ("key1", result[1].field_);
+ EXPECT_EQ("key2", result[2].field_);
+
+ spec.offset_ = 0;
+ spec.count_ = -1;
+ spec.maxex_ = true;
+ spec.minex_ = true;
+ s = hash_->RangeByLex(key_, spec, &result);
EXPECT_TRUE(s.ok());
EXPECT_EQ(2, result.size());
- EXPECT_EQ("key1", result[0].field);
- EXPECT_EQ("key2", result[1].field);
+ EXPECT_EQ("key1", result[0].field_);
+ EXPECT_EQ("key2", result[1].field_);
// inf and revered
- spec.minex = false;
- spec.maxex = false;
- spec.min = "-";
- spec.max = "+";
- spec.max_infinite = true;
- spec.reversed = true;
- s = hash->RangeByLex(key_, spec, &result);
+ spec.minex_ = false;
+ spec.maxex_ = false;
+ spec.min_ = "-";
+ spec.max_ = "+";
+ spec.max_infinite_ = true;
+ spec.reversed_ = true;
+ s = hash_->RangeByLex(key_, spec, &result);
EXPECT_TRUE(s.ok());
EXPECT_EQ(4 + 26, result.size());
- EXPECT_EQ("key3", result[0].field);
- EXPECT_EQ("key2", result[1].field);
- EXPECT_EQ("key1", result[2].field);
- EXPECT_EQ("key0", result[3].field);
- hash->Del(key_);
+ EXPECT_EQ("key3", result[0].field_);
+ EXPECT_EQ("key2", result[1].field_);
+ EXPECT_EQ("key1", result[2].field_);
+ EXPECT_EQ("key0", result[3].field_);
+ hash_->Del(key_);
}
TEST_F(RedisHashTest, HRangeByLexNonExistingKey) {
std::vector<FieldValue> result;
CommonRangeLexSpec spec;
- spec.offset = 0;
- spec.count = INT_MAX;
- spec.min = "any-start-key";
- spec.max = "any-end-key";
- auto s = hash->RangeByLex("non-existing-key", spec, &result);
+ spec.offset_ = 0;
+ spec.count_ = INT_MAX;
+ spec.min_ = "any-start-key";
+ spec.max_ = "any-end-key";
+ auto s = hash_->RangeByLex("non-existing-key", spec, &result);
EXPECT_TRUE(s.ok());
EXPECT_EQ(result.size(), 0);
}
diff --git a/tests/cppunit/types/list_test.cc b/tests/cppunit/types/list_test.cc
index 432cfda7..04b83496 100644
--- a/tests/cppunit/types/list_test.cc
+++ b/tests/cppunit/types/list_test.cc
@@ -27,7 +27,7 @@
class RedisListTest : public TestBase {
protected:
- explicit RedisListTest() { list = std::make_unique<Redis::List>(storage_, "list_ns"); }
+ explicit RedisListTest() { list_ = std::make_unique<Redis::List>(storage_, "list_ns"); }
~RedisListTest() override = default;
void SetUp() override {
@@ -38,7 +38,7 @@ class RedisListTest : public TestBase {
"list-test-key-1", "list-test-key-2", "list-test-key-3", "list-test-key-4", "list-test-key-5"};
... 5644 lines suppressed ...