git-hulk commented on code in PR #2142: URL: https://github.com/apache/kvrocks/pull/2142#discussion_r1562550081
########## src/types/redis_hyperloglog.cc: ########## @@ -0,0 +1,347 @@ +/* + * 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. + * + */ + +/* Redis HyperLogLog probabilistic cardinality approximation. + * This file implements the algorithm and the exported Redis commands. + * + * Copyright (c) 2014, Salvatore Sanfilippo <antirez at gmail dot com> + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of Redis nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +#include "redis_hyperloglog.h" + +#include <math.h> +#include <stdint.h> + +#include "db_util.h" +#include "murmurhash2.h" + +namespace redis { + +/* Store the value of the register at position 'index' into variable 'val'. + * 'registers' is an array of unsigned bytes. */ +void HllDenseGetRegister(uint8_t *val, uint8_t *registers, uint32_t index) { + uint32_t byte = index * kHyperLogLogBits / 8; + uint8_t fb = index * kHyperLogLogBits & 7; + uint8_t fb8 = 8 - fb; + uint8_t b0 = registers[byte]; + uint8_t b1 = registers[byte + 1]; + *val = ((b0 >> fb) | (b1 << fb8)) & kHyperLogLogRegisterMax; +} + +/* Set the value of the register at position 'index' to 'val'. + * 'registers' is an array of unsigned bytes. */ +void HllDenseSetRegister(uint8_t *registers, uint32_t index, uint8_t val) { + uint32_t byte = index * kHyperLogLogBits / 8; + uint8_t fb = index * kHyperLogLogBits & 7; + uint8_t fb8 = 8 - fb; + uint8_t v = val; + registers[byte] &= ~(kHyperLogLogRegisterMax << fb); + registers[byte] |= v << fb; + registers[byte + 1] &= ~(kHyperLogLogRegisterMax >> fb8); + registers[byte + 1] |= v >> fb8; +} + +rocksdb::Status HyperLogLog::GetMetadata(Database::GetOptions get_options, const Slice &ns_key, + HyperloglogMetadata *metadata) { + return Database::GetMetadata(get_options, {kRedisHyperLogLog}, ns_key, metadata); +} + +/* the max 0 pattern counter of the subset the element belongs to is incremented if needed */ +rocksdb::Status HyperLogLog::Add(const Slice &user_key, const std::vector<Slice> &elements, uint64_t *ret) { + *ret = 0; + std::string ns_key = AppendNamespacePrefix(user_key); + + LockGuard guard(storage_->GetLockManager(), ns_key); + HyperloglogMetadata metadata; + rocksdb::Status s = GetMetadata(GetOptions(), ns_key, &metadata); + if (!s.ok() && !s.IsNotFound()) return s; + + auto batch = storage_->GetWriteBatchBase(); + WriteBatchLogData log_data(kRedisHyperLogLog); + batch->PutLogData(log_data.Encode()); + if (s.IsNotFound()) { + std::string bytes; + metadata.Encode(&bytes); + batch->Put(metadata_cf_handle_, ns_key, bytes); + } + + Bitmap::SegmentCacheStore cache(storage_, metadata_cf_handle_, ns_key, metadata); + for (const auto &element : elements) { + uint32_t register_index = 0; + auto ele_str = element.ToString(); + std::vector<uint8_t> ele(ele_str.begin(), ele_str.end()); + uint8_t count = HllPatLen(ele, ®ister_index); + uint32_t segment_index = register_index / kHyperLogLogRegisterCountPerSegment; + uint32_t register_index_in_segment = register_index % kHyperLogLogRegisterCountPerSegment; + + std::string *segment = nullptr; + auto s = cache.GetMut(segment_index, &segment); + if (!s.ok()) return s; + if (segment->size() == 0) { + segment->resize(kHyperLogLogRegisterBytesPerSegment, 0); + } + + uint8_t old_count = 0; + HllDenseGetRegister(&old_count, reinterpret_cast<uint8_t *>(segment->data()), register_index_in_segment); + if (count > old_count) { + HllDenseSetRegister(reinterpret_cast<uint8_t *>(segment->data()), register_index_in_segment, count); + *ret = 1; + } + } + cache.BatchForFlush(batch); + return storage_->Write(storage_->DefaultWriteOptions(), batch->GetWriteBatch()); +} + +rocksdb::Status HyperLogLog::Count(const Slice &user_key, uint64_t *ret) { + *ret = 0; + std::vector<uint8_t> registers(kHyperLogLogRegisterBytes); + auto s = getRegisters(user_key, ®isters); + if (!s.ok()) return s; + *ret = HllCount(registers); + return rocksdb::Status::OK(); +} + +rocksdb::Status HyperLogLog::Merge(const std::vector<Slice> &user_keys) { + std::vector<uint8_t> max(kHyperLogLogRegisterBytes); + for (const auto &user_key : user_keys) { + std::vector<uint8_t> registers(kHyperLogLogRegisterBytes); + auto s = getRegisters(user_key, ®isters); + if (!s.ok()) return s; + HllMerge(&max, registers); + } + + std::string ns_key = AppendNamespacePrefix(user_keys[0]); + + LockGuard guard(storage_->GetLockManager(), ns_key); + HyperloglogMetadata metadata; + rocksdb::Status s = GetMetadata(GetOptions(), ns_key, &metadata); + if (!s.ok() && !s.IsNotFound()) return s; + + auto batch = storage_->GetWriteBatchBase(); + WriteBatchLogData log_data(kRedisHyperLogLog); + batch->PutLogData(log_data.Encode()); + if (s.IsNotFound()) { + std::string bytes; + metadata.Encode(&bytes); + batch->Put(metadata_cf_handle_, ns_key, bytes); + } + + Bitmap::SegmentCacheStore cache(storage_, metadata_cf_handle_, ns_key, metadata); + for (uint32_t segment_index = 0; segment_index < kHyperLogLogSegmentCount; segment_index++) { + std::string registers(max.begin() + segment_index * kHyperLogLogRegisterBytesPerSegment, + max.begin() + (segment_index + 1) * kHyperLogLogRegisterBytesPerSegment); + std::string *segment = nullptr; + s = cache.GetMut(segment_index, &segment); + if (!s.ok()) return s; + if (segment->size() == 0) { + *segment = registers; + } + } + cache.BatchForFlush(batch); + return storage_->Write(storage_->DefaultWriteOptions(), batch->GetWriteBatch()); +} + +/* ========================= HyperLogLog algorithm ========================= */ Review Comment: We can add a comment line to notice if those codes are generally modified from other repository like: https://github.com/apache/kvrocks/blob/unstable/src/common/rocksdb_crc32c.h#L10 -- 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]
