git-hulk commented on code in PR #1699:
URL: https://github.com/apache/kvrocks/pull/1699#discussion_r1306588711


##########
src/commands/cmd_bloom_filter.cc:
##########
@@ -0,0 +1,117 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ */
+
+#include "command_parser.h"
+#include "commander.h"
+#include "error_constants.h"
+#include "server/server.h"
+#include "types/redis_bloom_chain.h"
+
+namespace redis {
+
+class CommandBFReserve : public Commander {
+ public:
+  Status Parse(const std::vector<std::string> &args) override {
+    auto parse_error_rate = ParseFloat<double>(args[2]);
+    if (!parse_error_rate) {
+      return {Status::RedisParseErr, errValueIsNotFloat};
+    }
+    error_rate_ = *parse_error_rate;
+    if (error_rate_ >= 1 || error_rate_ <= 0) {
+      return {Status::RedisParseErr, "0 < error rate range < 1"};
+    }
+
+    auto parse_capacity = ParseInt<uint32_t>(args[3], 10);
+    if (!parse_capacity) {
+      return {Status::RedisParseErr, errValueNotInteger};
+    }
+    capacity_ = *parse_capacity;
+    if (capacity_ <= 0) {
+      return {Status::RedisParseErr, "capacity should be larger than 0"};
+    }
+
+    CommandParser parser(args, 4);
+    bool nonscaling = false;
+    while (parser.Good()) {
+      if (parser.EatEqICase("nonscaling")) {
+        nonscaling = true;
+      } else if (parser.EatEqICase("expansion")) {
+        expansion_ = GET_OR_RET(parser.TakeInt<uint16_t>());
+        if (expansion_ < 1) {
+          return {Status::RedisParseErr, "expansion should be greater or equal 
to 1"};
+        }
+      } else {
+        return {Status::RedisParseErr, errInvalidSyntax};
+      }
+    }
+
+    // if nonscaling is true, expansion should be 0
+    if (nonscaling && expansion_ != 0) {
+      return {Status::RedisParseErr, "nonscaling filters cannot expand"};
+    }
+
+    return Commander::Parse(args);
+  }
+
+  Status Execute(Server *svr, Connection *conn, std::string *output) override {
+    redis::BloomChain bloomfilter_db(svr->storage, conn->GetNamespace());
+    auto s = bloomfilter_db.Reserve(args_[1], capacity_, error_rate_, 
expansion_);
+    if (!s.ok()) return {Status::RedisExecErr, s.ToString()};
+
+    *output = redis::SimpleString("OK");
+    return Status::OK();
+  }
+
+ private:
+  double error_rate_;
+  uint32_t capacity_;
+  uint16_t expansion_ = 0;
+};
+
+class CommandBFAdd : public Commander {
+ public:
+  Status Execute(Server *svr, Connection *conn, std::string *output) override {
+    redis::BloomChain bloom_db(svr->storage, conn->GetNamespace());
+    int ret = 0;
+    auto s = bloom_db.Add(args_[1], args_[2], &ret);
+    if (!s.ok()) return {Status::RedisExecErr, s.ToString()};
+
+    *output = redis::Integer(ret);
+    return Status::OK();
+  }
+};
+
+class CommandBFExist : public Commander {
+ public:
+  Status Execute(Server *svr, Connection *conn, std::string *output) override {
+    redis::BloomChain bloom_db(svr->storage, conn->GetNamespace());
+    int ret = 0;
+    auto s = bloom_db.Exist(args_[1], args_[2], &ret);
+    if (!s.ok()) return {Status::RedisExecErr, s.ToString()};
+
+    *output = redis::Integer(ret);
+    return Status::OK();
+  }
+};
+
+REDIS_REGISTER_COMMANDS(MakeCmdAttr<CommandBFReserve>("bf.reserve", -4, 
"write", 1, 1, 1),
+                        MakeCmdAttr<CommandBFAdd>("bf.add", 3, "write", 1, 1, 
1),
+                        MakeCmdAttr<CommandBFExist>("bf.exist", 3, 
"read-only", 1, 1, 1), )
+}  // namespace redis

Review Comment:
   ```suggestion
   }  // namespace redis
   
   ```



##########
src/commands/cmd_bloom_filter.cc:
##########
@@ -0,0 +1,117 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ */
+
+#include "command_parser.h"
+#include "commander.h"
+#include "error_constants.h"
+#include "server/server.h"
+#include "types/redis_bloom_chain.h"
+
+namespace redis {
+
+class CommandBFReserve : public Commander {
+ public:
+  Status Parse(const std::vector<std::string> &args) override {
+    auto parse_error_rate = ParseFloat<double>(args[2]);
+    if (!parse_error_rate) {
+      return {Status::RedisParseErr, errValueIsNotFloat};
+    }
+    error_rate_ = *parse_error_rate;
+    if (error_rate_ >= 1 || error_rate_ <= 0) {
+      return {Status::RedisParseErr, "0 < error rate range < 1"};

Review Comment:
   ```suggestion
         return {Status::RedisParseErr, "error rate should be between 0 and 1"};
   ```



##########
src/types/redis_bloom_chain.cc:
##########
@@ -0,0 +1,184 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ */
+
+#include "redis_bloom_chain.h"
+
+namespace redis {
+
+std::string BloomChain::getBFKey(const Slice &ns_key, const BloomChainMetadata 
&metadata, uint16_t filters_index) {
+  std::string sub_key;
+  sub_key.append(kBloomFilterSeparator);
+  PutFixed16(&sub_key, filters_index);
+
+  std::string bf_key = InternalKey(ns_key, sub_key, metadata.version, 
storage_->IsSlotIdEncoded()).Encode();
+  return bf_key;
+}
+
+void BloomChain::getBFKeyList(const Slice &ns_key, const BloomChainMetadata 
&metadata,
+                              std::vector<std::string> *bf_key_list) {
+  bf_key_list->reserve(metadata.n_filters);
+  for (uint16_t i = 0; i < metadata.n_filters; ++i) {
+    std::string bf_key = getBFKey(ns_key, metadata, i);
+    bf_key_list->push_back(std::move(bf_key));
+  }
+}
+
+rocksdb::Status BloomChain::getBloomChainMetadata(const Slice &ns_key, 
BloomChainMetadata *metadata) {
+  return Database::GetMetadata(kRedisBloomFilter, ns_key, metadata);
+}
+
+rocksdb::Status BloomChain::createBloomChain(const Slice &ns_key, double 
error_rate, uint32_t capacity,
+                                             uint16_t expansion, 
BloomChainMetadata *metadata) {
+  metadata->n_filters = 1;
+  metadata->expansion = expansion;
+  metadata->size = 0;
+
+  metadata->error_rate = error_rate;
+  metadata->base_capacity = capacity;
+  metadata->bloom_bytes = BlockSplitBloomFilter::OptimalNumOfBytes(capacity, 
error_rate);
+
+  BlockSplitBloomFilter block_split_bloom_filter;
+  block_split_bloom_filter.Init(metadata->bloom_bytes);
+
+  auto batch = storage_->GetWriteBatchBase();
+  WriteBatchLogData log_data(kRedisBloomFilter, {"createSBChain"});
+  batch->PutLogData(log_data.Encode());
+
+  std::string sb_chain_meta_bytes;
+  metadata->Encode(&sb_chain_meta_bytes);
+  batch->Put(metadata_cf_handle_, ns_key, sb_chain_meta_bytes);
+
+  std::string bf_key = getBFKey(ns_key, *metadata, metadata->n_filters - 1);
+  batch->Put(bf_key, block_split_bloom_filter.GetData());
+
+  return storage_->Write(storage_->DefaultWriteOptions(), 
batch->GetWriteBatch());
+}
+
+rocksdb::Status BloomChain::bloomCheckAdd(const Slice &bf_key, const 
std::string &item, ReadWriteMode mode, int *ret) {
+  std::string bf_data;
+  rocksdb::Status s = storage_->Get(rocksdb::ReadOptions(), bf_key, &bf_data);
+  BlockSplitBloomFilter block_split_bloom_filter;
+  block_split_bloom_filter.Init(std::move(bf_data));
+
+  uint64_t h = BlockSplitBloomFilter::Hash(item.data(), item.size());
+  bool found = block_split_bloom_filter.FindHash(h);
+
+  *ret = 0;
+  if (found && mode == ReadWriteMode::READ) {
+    *ret = 1;
+  } else if (!found && mode == ReadWriteMode::WRITE) {
+    auto batch = storage_->GetWriteBatchBase();
+    *ret = 1;
+    block_split_bloom_filter.InsertHash(h);
+    batch->Put(bf_key, block_split_bloom_filter.GetData());
+    return storage_->Write(storage_->DefaultWriteOptions(), 
batch->GetWriteBatch());
+  }
+
+  return rocksdb::Status::OK();
+}
+
+rocksdb::Status BloomChain::Reserve(const Slice &user_key, uint32_t capacity, 
double error_rate, uint16_t expansion) {
+  std::string ns_key = AppendNamespacePrefix(user_key);
+
+  LockGuard guard(storage_->GetLockManager(), ns_key);
+  BloomChainMetadata bloom_chain_metadata;
+  rocksdb::Status s = getBloomChainMetadata(ns_key, &bloom_chain_metadata);
+  if (!s.ok() && !s.IsNotFound()) return s;
+  if (!s.IsNotFound()) {
+    return rocksdb::Status::InvalidArgument("the key already exists");
+  }
+
+  return createBloomChain(ns_key, error_rate, capacity, expansion, 
&bloom_chain_metadata);
+}
+
+rocksdb::Status BloomChain::Add(const Slice &user_key, const Slice &item, int 
*ret) {
+  std::string ns_key = AppendNamespacePrefix(user_key);
+  LockGuard guard(storage_->GetLockManager(), ns_key);
+
+  BloomChainMetadata metadata;
+  rocksdb::Status s = getBloomChainMetadata(ns_key, &metadata);
+
+  if (s.IsNotFound()) {
+    rocksdb::Status create_s =
+        createBloomChain(ns_key, kBFDefaultErrorRate, kBFDefaultInitCapacity, 
kBFDefaultExpansion, &metadata);
+    if (!create_s.ok()) return create_s;
+  } else if (!s.ok()) {
+    return s;
+  }
+
+  std::vector<std::string> bf_key_list;
+  getBFKeyList(ns_key, metadata, &bf_key_list);
+
+  auto batch = storage_->GetWriteBatchBase();
+  WriteBatchLogData log_data(kRedisBloomFilter, {"insert"});
+  batch->PutLogData(log_data.Encode());
+
+  bool item_exist = false;

Review Comment:
   Looks like we can check the add status by the index 'i'



##########
src/types/redis_bloom_chain.cc:
##########
@@ -0,0 +1,184 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ */
+
+#include "redis_bloom_chain.h"
+
+namespace redis {
+
+std::string BloomChain::getBFKey(const Slice &ns_key, const BloomChainMetadata 
&metadata, uint16_t filters_index) {
+  std::string sub_key;
+  sub_key.append(kBloomFilterSeparator);
+  PutFixed16(&sub_key, filters_index);
+
+  std::string bf_key = InternalKey(ns_key, sub_key, metadata.version, 
storage_->IsSlotIdEncoded()).Encode();
+  return bf_key;
+}
+
+void BloomChain::getBFKeyList(const Slice &ns_key, const BloomChainMetadata 
&metadata,
+                              std::vector<std::string> *bf_key_list) {
+  bf_key_list->reserve(metadata.n_filters);
+  for (uint16_t i = 0; i < metadata.n_filters; ++i) {
+    std::string bf_key = getBFKey(ns_key, metadata, i);
+    bf_key_list->push_back(std::move(bf_key));
+  }
+}
+
+rocksdb::Status BloomChain::getBloomChainMetadata(const Slice &ns_key, 
BloomChainMetadata *metadata) {
+  return Database::GetMetadata(kRedisBloomFilter, ns_key, metadata);
+}
+
+rocksdb::Status BloomChain::createBloomChain(const Slice &ns_key, double 
error_rate, uint32_t capacity,
+                                             uint16_t expansion, 
BloomChainMetadata *metadata) {
+  metadata->n_filters = 1;
+  metadata->expansion = expansion;
+  metadata->size = 0;
+
+  metadata->error_rate = error_rate;
+  metadata->base_capacity = capacity;
+  metadata->bloom_bytes = BlockSplitBloomFilter::OptimalNumOfBytes(capacity, 
error_rate);
+
+  BlockSplitBloomFilter block_split_bloom_filter;
+  block_split_bloom_filter.Init(metadata->bloom_bytes);
+
+  auto batch = storage_->GetWriteBatchBase();
+  WriteBatchLogData log_data(kRedisBloomFilter, {"createSBChain"});
+  batch->PutLogData(log_data.Encode());
+
+  std::string sb_chain_meta_bytes;
+  metadata->Encode(&sb_chain_meta_bytes);
+  batch->Put(metadata_cf_handle_, ns_key, sb_chain_meta_bytes);
+
+  std::string bf_key = getBFKey(ns_key, *metadata, metadata->n_filters - 1);
+  batch->Put(bf_key, block_split_bloom_filter.GetData());
+
+  return storage_->Write(storage_->DefaultWriteOptions(), 
batch->GetWriteBatch());
+}
+
+rocksdb::Status BloomChain::bloomCheckAdd(const Slice &bf_key, const 
std::string &item, ReadWriteMode mode, int *ret) {
+  std::string bf_data;
+  rocksdb::Status s = storage_->Get(rocksdb::ReadOptions(), bf_key, &bf_data);

Review Comment:
   We should check the get result?



##########
src/types/redis_bloom_chain.cc:
##########
@@ -0,0 +1,184 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ */
+
+#include "redis_bloom_chain.h"
+
+namespace redis {
+
+std::string BloomChain::getBFKey(const Slice &ns_key, const BloomChainMetadata 
&metadata, uint16_t filters_index) {
+  std::string sub_key;
+  sub_key.append(kBloomFilterSeparator);
+  PutFixed16(&sub_key, filters_index);
+
+  std::string bf_key = InternalKey(ns_key, sub_key, metadata.version, 
storage_->IsSlotIdEncoded()).Encode();
+  return bf_key;
+}
+
+void BloomChain::getBFKeyList(const Slice &ns_key, const BloomChainMetadata 
&metadata,
+                              std::vector<std::string> *bf_key_list) {
+  bf_key_list->reserve(metadata.n_filters);
+  for (uint16_t i = 0; i < metadata.n_filters; ++i) {
+    std::string bf_key = getBFKey(ns_key, metadata, i);
+    bf_key_list->push_back(std::move(bf_key));
+  }
+}
+
+rocksdb::Status BloomChain::getBloomChainMetadata(const Slice &ns_key, 
BloomChainMetadata *metadata) {
+  return Database::GetMetadata(kRedisBloomFilter, ns_key, metadata);
+}
+
+rocksdb::Status BloomChain::createBloomChain(const Slice &ns_key, double 
error_rate, uint32_t capacity,
+                                             uint16_t expansion, 
BloomChainMetadata *metadata) {
+  metadata->n_filters = 1;
+  metadata->expansion = expansion;
+  metadata->size = 0;
+
+  metadata->error_rate = error_rate;
+  metadata->base_capacity = capacity;
+  metadata->bloom_bytes = BlockSplitBloomFilter::OptimalNumOfBytes(capacity, 
error_rate);
+
+  BlockSplitBloomFilter block_split_bloom_filter;
+  block_split_bloom_filter.Init(metadata->bloom_bytes);
+
+  auto batch = storage_->GetWriteBatchBase();
+  WriteBatchLogData log_data(kRedisBloomFilter, {"createSBChain"});
+  batch->PutLogData(log_data.Encode());
+
+  std::string sb_chain_meta_bytes;
+  metadata->Encode(&sb_chain_meta_bytes);
+  batch->Put(metadata_cf_handle_, ns_key, sb_chain_meta_bytes);
+
+  std::string bf_key = getBFKey(ns_key, *metadata, metadata->n_filters - 1);
+  batch->Put(bf_key, block_split_bloom_filter.GetData());
+
+  return storage_->Write(storage_->DefaultWriteOptions(), 
batch->GetWriteBatch());
+}
+
+rocksdb::Status BloomChain::bloomCheckAdd(const Slice &bf_key, const 
std::string &item, ReadWriteMode mode, int *ret) {
+  std::string bf_data;
+  rocksdb::Status s = storage_->Get(rocksdb::ReadOptions(), bf_key, &bf_data);
+  BlockSplitBloomFilter block_split_bloom_filter;
+  block_split_bloom_filter.Init(std::move(bf_data));
+
+  uint64_t h = BlockSplitBloomFilter::Hash(item.data(), item.size());
+  bool found = block_split_bloom_filter.FindHash(h);
+
+  *ret = 0;
+  if (found && mode == ReadWriteMode::READ) {
+    *ret = 1;
+  } else if (!found && mode == ReadWriteMode::WRITE) {
+    auto batch = storage_->GetWriteBatchBase();
+    *ret = 1;
+    block_split_bloom_filter.InsertHash(h);
+    batch->Put(bf_key, block_split_bloom_filter.GetData());
+    return storage_->Write(storage_->DefaultWriteOptions(), 
batch->GetWriteBatch());
+  }
+
+  return rocksdb::Status::OK();
+}
+
+rocksdb::Status BloomChain::Reserve(const Slice &user_key, uint32_t capacity, 
double error_rate, uint16_t expansion) {
+  std::string ns_key = AppendNamespacePrefix(user_key);
+
+  LockGuard guard(storage_->GetLockManager(), ns_key);
+  BloomChainMetadata bloom_chain_metadata;
+  rocksdb::Status s = getBloomChainMetadata(ns_key, &bloom_chain_metadata);
+  if (!s.ok() && !s.IsNotFound()) return s;
+  if (!s.IsNotFound()) {
+    return rocksdb::Status::InvalidArgument("the key already exists");
+  }
+
+  return createBloomChain(ns_key, error_rate, capacity, expansion, 
&bloom_chain_metadata);
+}
+
+rocksdb::Status BloomChain::Add(const Slice &user_key, const Slice &item, int 
*ret) {
+  std::string ns_key = AppendNamespacePrefix(user_key);
+  LockGuard guard(storage_->GetLockManager(), ns_key);
+
+  BloomChainMetadata metadata;
+  rocksdb::Status s = getBloomChainMetadata(ns_key, &metadata);
+
+  if (s.IsNotFound()) {
+    rocksdb::Status create_s =
+        createBloomChain(ns_key, kBFDefaultErrorRate, kBFDefaultInitCapacity, 
kBFDefaultExpansion, &metadata);
+    if (!create_s.ok()) return create_s;
+  } else if (!s.ok()) {
+    return s;
+  }
+
+  std::vector<std::string> bf_key_list;
+  getBFKeyList(ns_key, metadata, &bf_key_list);
+
+  auto batch = storage_->GetWriteBatchBase();
+  WriteBatchLogData log_data(kRedisBloomFilter, {"insert"});
+  batch->PutLogData(log_data.Encode());
+
+  bool item_exist = false;
+  std::string item_string = item.ToString();
+
+  // check
+  for (int i = metadata.n_filters - 1; i >= 0; --i) {  // TODO: to test which 
direction for searching is better
+    s = bloomCheckAdd(bf_key_list[i], item_string, ReadWriteMode::READ, ret);
+    if (*ret == 1) {
+      item_exist = true;
+      break;
+    }
+  }
+
+  // insert
+  if (!item_exist) {
+    if (metadata.size + 1 > metadata.GetCapacity()) {  // TODO: scaling would 
be supported later
+      return rocksdb::Status::Aborted("filter is full");
+    }
+    s = bloomCheckAdd(bf_key_list.back(), item_string, ReadWriteMode::WRITE, 
ret);
+    metadata.size += *ret;
+  }
+
+  std::string sb_chain_metadata_bytes;
+  metadata.Encode(&sb_chain_metadata_bytes);
+  batch->Put(metadata_cf_handle_, ns_key, sb_chain_metadata_bytes);
+
+  return storage_->Write(storage_->DefaultWriteOptions(), 
batch->GetWriteBatch());
+}
+
+rocksdb::Status BloomChain::Exist(const Slice &user_key, const Slice &item, 
int *ret) {
+  std::string ns_key = AppendNamespacePrefix(user_key);
+  LockGuard guard(storage_->GetLockManager(), ns_key);

Review Comment:
   I think we can split the check and add logic. For the existing operation, 
it's unnecessary to lock for adding the missing bloom filter, because the 
BloomFilter read operations would be much larger than the write operations in 
most of scenarios. So it'd be better to non-lock for that. 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to