BewareMyPower commented on code in PR #196:
URL: https://github.com/apache/pulsar-client-cpp/pull/196#discussion_r1124646522


##########
lib/TableViewImpl.cc:
##########
@@ -0,0 +1,165 @@
+/**
+ * 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 "TableViewImpl.h"
+
+#include "LogUtils.h"
+#include "ReaderImpl.h"
+#include "TimeUtils.h"
+
+namespace pulsar {
+
+DECLARE_LOG_OBJECT()
+
+TableViewImpl::TableViewImpl(const ClientImplPtr client, const std::string& 
topic,
+                             const TableViewConfiguration& conf)
+    : client_(client), topic_(topic), conf_(conf) {}
+
+Future<Result, TableViewImplPtr> TableViewImpl::start() {
+    Promise<Result, TableViewImplPtr> promise;
+    ReaderConfiguration readerConfiguration;
+    readerConfiguration.setSchema(conf_.schemaInfo);
+    readerConfiguration.setReadCompacted(true);
+    readerConfiguration.setInternalSubscriptionName(conf_.subscriptionName);
+
+    TableViewImplPtr self = shared_from_this();
+    ReaderCallback readerCallback = [self, promise](Result res, Reader reader) 
{
+        if (res == ResultOk) {
+            self->reader_ = reader.impl_;
+            self->readAllExistingMessages(promise, 
TimeUtils::currentTimeMillis(), 0);
+        } else {
+            promise.setFailed(res);
+        }
+    };
+    client_->createReaderAsync(topic_, MessageId::earliest(), 
readerConfiguration, readerCallback);
+    return promise.getFuture();
+}
+
+bool TableViewImpl::retrieveValue(const std::string& key, std::string& value) {
+    auto optValue = data_.remove(key);
+    if (optValue) {
+        value = optValue.value();
+        return true;
+    }
+    return false;
+}
+
+bool TableViewImpl::getValue(const std::string& key, std::string& value) const 
{
+    auto optValue = data_.find(key);
+    if (optValue) {
+        value = optValue.value();
+        return true;
+    }
+    return false;
+}
+
+bool TableViewImpl::containsKey(const std::string& key) const { return 
data_.find(key) != boost::none; }
+
+std::unordered_map<std::string, std::string> TableViewImpl::snapshot() { 
return data_.move(); }
+
+std::size_t TableViewImpl::size() const { return data_.size(); }
+
+void TableViewImpl::forEach(TableViewAction action) { data_.forEach(action); }
+
+void TableViewImpl::forEachAndListen(TableViewAction action) {
+    Lock lock(listenersMutex_);
+    data_.forEach(action);
+    listeners_.emplace_back(action);
+}
+
+void TableViewImpl::closeAsync(ResultCallback callback) {
+    if (reader_) {
+        reader_->closeAsync([callback, this](Result result) {
+            reader_.reset();
+            callback(result);
+        });
+    } else {
+        callback(ResultConsumerNotInitialized);
+    }
+}
+
+void TableViewImpl::handleMessage(const Message& msg) {
+    if (msg.hasPartitionKey()) {
+        LOG_DEBUG("Applying message from " << topic_ << " key=" << 
msg.getPartitionKey()
+                                           << " value=" << 
msg.getDataAsString())
+
+        if (msg.getDataAsString().empty()) {

Review Comment:
   You should use `msg.getLength() == 0` because the bytes copy happens in 
`getDataAsString()`.



##########
lib/TableViewImpl.cc:
##########
@@ -0,0 +1,165 @@
+/**
+ * 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 "TableViewImpl.h"
+
+#include "LogUtils.h"
+#include "ReaderImpl.h"
+#include "TimeUtils.h"
+
+namespace pulsar {
+
+DECLARE_LOG_OBJECT()
+
+TableViewImpl::TableViewImpl(const ClientImplPtr client, const std::string& 
topic,
+                             const TableViewConfiguration& conf)
+    : client_(client), topic_(topic), conf_(conf) {}
+
+Future<Result, TableViewImplPtr> TableViewImpl::start() {
+    Promise<Result, TableViewImplPtr> promise;
+    ReaderConfiguration readerConfiguration;
+    readerConfiguration.setSchema(conf_.schemaInfo);
+    readerConfiguration.setReadCompacted(true);
+    readerConfiguration.setInternalSubscriptionName(conf_.subscriptionName);
+
+    TableViewImplPtr self = shared_from_this();
+    ReaderCallback readerCallback = [self, promise](Result res, Reader reader) 
{
+        if (res == ResultOk) {
+            self->reader_ = reader.impl_;
+            self->readAllExistingMessages(promise, 
TimeUtils::currentTimeMillis(), 0);
+        } else {
+            promise.setFailed(res);
+        }
+    };
+    client_->createReaderAsync(topic_, MessageId::earliest(), 
readerConfiguration, readerCallback);
+    return promise.getFuture();
+}
+
+bool TableViewImpl::retrieveValue(const std::string& key, std::string& value) {
+    auto optValue = data_.remove(key);
+    if (optValue) {
+        value = optValue.value();
+        return true;
+    }
+    return false;
+}
+
+bool TableViewImpl::getValue(const std::string& key, std::string& value) const 
{
+    auto optValue = data_.find(key);
+    if (optValue) {
+        value = optValue.value();
+        return true;
+    }
+    return false;
+}
+
+bool TableViewImpl::containsKey(const std::string& key) const { return 
data_.find(key) != boost::none; }
+
+std::unordered_map<std::string, std::string> TableViewImpl::snapshot() { 
return data_.move(); }
+
+std::size_t TableViewImpl::size() const { return data_.size(); }
+
+void TableViewImpl::forEach(TableViewAction action) { data_.forEach(action); }
+
+void TableViewImpl::forEachAndListen(TableViewAction action) {
+    Lock lock(listenersMutex_);
+    data_.forEach(action);
+    listeners_.emplace_back(action);
+}
+
+void TableViewImpl::closeAsync(ResultCallback callback) {
+    if (reader_) {
+        reader_->closeAsync([callback, this](Result result) {
+            reader_.reset();
+            callback(result);
+        });
+    } else {
+        callback(ResultConsumerNotInitialized);
+    }
+}
+
+void TableViewImpl::handleMessage(const Message& msg) {
+    if (msg.hasPartitionKey()) {
+        LOG_DEBUG("Applying message from " << topic_ << " key=" << 
msg.getPartitionKey()
+                                           << " value=" << 
msg.getDataAsString())
+
+        if (msg.getDataAsString().empty()) {
+            data_.remove(msg.getPartitionKey());
+        } else {
+            data_.emplace(msg.getPartitionKey(), msg.getDataAsString());
+        }
+
+        Lock lock(listenersMutex_);
+        for (const auto& listener : listeners_) {
+            try {
+                listener(msg.getPartitionKey(), msg.getDataAsString());

Review Comment:
   For the same reason, we should avoid calling `getDataAsString()` repeatedly. 
It's better to introduce a local variable here:
   
   ```c++
   auto value = msg.getDataAsString();
   ```



##########
lib/TableView.cc:
##########
@@ -0,0 +1,92 @@
+/**
+ * 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 <pulsar/TableView.h>
+
+#include "TableViewImpl.h"
+#include "Utils.h"
+
+namespace pulsar {
+
+TableView::TableView() {}
+
+TableView::TableView(TableViewImplPtr impl) : impl_(impl) {}
+
+bool TableView::retrieveValue(const std::string& key, std::string& value) {
+    if (impl_) {
+        return impl_->retrieveValue(key, value);
+    }
+    return false;
+}
+
+bool TableView::getValue(const std::string& key, std::string& value) const {
+    if (impl_) {
+        return impl_->getValue(key, value);
+    }
+    return false;
+}
+
+bool TableView::containsKey(const std::string& key) const {
+    if (impl_) {
+        return impl_->containsKey(key);
+    }
+    return false;
+}
+
+std::unordered_map<std::string, std::string> TableView::snapshot() {
+    if (impl_) {
+        return impl_->snapshot();
+    }
+    return {};
+}
+
+std::size_t TableView::size() const { return impl_->size(); }

Review Comment:
   You should check `impl_` is not null here. I think we can return 0 if it's 
null.



##########
tests/TableViewTest.cc:
##########
@@ -0,0 +1,224 @@
+/**
+ * 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 <gtest/gtest.h>
+#include <pulsar/Client.h>
+
+#include <chrono>
+#include <future>
+
+#include "HttpHelper.h"
+#include "PulsarFriend.h"
+#include "WaitUtils.h"
+
+using namespace pulsar;
+
+static std::string lookupUrl = "pulsar://localhost:6650";
+static std::string adminUrl = "http://localhost:8080/";;
+
+DECLARE_LOG_OBJECT()
+
+TEST(TableViewTest, testCreateTableView) {
+    const std::string topic = "testCreateTableView" + 
std::to_string(time(nullptr));
+    Client client(lookupUrl);
+
+    static const std::string jsonSchema =
+        
R"({"type":"record","name":"cpx","fields":[{"name":"re","type":"double"},{"name":"im","type":"double"}]})";
+    SchemaInfo schemaInfo(JSON, "test-json", jsonSchema);
+    ProducerConfiguration producerConfiguration;
+    producerConfiguration.setSchema(schemaInfo);
+    Producer producer;
+    ASSERT_EQ(ResultOk, client.createProducer(topic, producerConfiguration, 
producer));
+
+    // Create table view failed, The schema is not compatible
+    TableViewConfiguration tableViewConfiguration{.schemaInfo = 
SchemaInfo(AVRO, "", "")};
+    TableView tableView;
+    ASSERT_EQ(ResultIncompatibleSchema, client.createTableView(topic, 
tableViewConfiguration, tableView));
+    ASSERT_EQ(ResultConsumerNotInitialized, tableView.close());
+
+    // Create table view success.
+    ASSERT_EQ(ResultOk, client.createTableView(topic, {.schemaInfo = 
schemaInfo}, tableView));
+    ASSERT_EQ(ResultOk, tableView.close());
+
+    // Test async create and close the client during the process.
+    Latch latch(1);
+    client.createTableViewAsync(
+        topic, tableViewConfiguration, [&latch](Result result, const 
TableView& tableView) {
+            latch.countdown();
+            ASSERT_TRUE(result == ResultDisconnected || result == 
ResultAlreadyClosed);
+        });
+    client.close();
+    latch.wait();
+}
+
+TEST(TableViewTest, testSimpleTableView) {
+    const std::string topic = "testTableView" + std::to_string(time(nullptr));
+    Client client(lookupUrl);
+
+    ProducerConfiguration producerConfiguration;
+    Producer producer;
+    ASSERT_EQ(ResultOk, client.createProducer(topic, producerConfiguration, 
producer));
+
+    auto count = 20;
+    for (int i = 0; i < count; ++i) {
+        auto msg = MessageBuilder()
+                       .setPartitionKey("key" + std::to_string(i))
+                       .setContent("value" + std::to_string(i))
+                       .build();
+        ASSERT_EQ(ResultOk, producer.send(msg));
+    }
+
+    // Create table view and assert size.
+    TableView tableView;
+    ASSERT_EQ(ResultOk, client.createTableView(topic, {}, tableView));
+    ASSERT_EQ(tableView.size(), count);
+
+    // Send some more messages, The 0 ~ count message key/value is duplicated 
send.
+    for (int i = 0; i < count * 2; ++i) {
+        auto msg = MessageBuilder()
+                       .setPartitionKey("key" + std::to_string(i))
+                       .setContent("value" + std::to_string(i))
+                       .build();
+        ASSERT_EQ(ResultOk, producer.send(msg));
+    }
+    waitUntil(
+        std::chrono::seconds(2), [&] { return tableView.size() == count * 2; 
}, 1000);
+    ASSERT_EQ(tableView.size(), count * 2);
+
+    // assert interfaces.
+    std::string value;
+    ASSERT_TRUE(tableView.getValue("key1", value));
+    ASSERT_EQ(value, "value1");
+    ASSERT_TRUE(tableView.retrieveValue("key1", value));
+    ASSERT_EQ(value, "value1");
+    ASSERT_FALSE(tableView.containsKey("key1"));
+    ASSERT_EQ(tableView.snapshot().size(), count * 2 - 1);
+    ASSERT_EQ(tableView.size(), 0);
+
+    client.close();
+}
+
+TEST(TableViewTest, testPublishNullValue) {

Review Comment:
   ```suggestion
   TEST(TableViewTest, testPublishEmptyValue) {
   ```
   
   Actually the C++ client does not support sending a "null" value.



##########
lib/TableViewImpl.cc:
##########
@@ -0,0 +1,165 @@
+/**
+ * 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 "TableViewImpl.h"
+
+#include "LogUtils.h"
+#include "ReaderImpl.h"
+#include "TimeUtils.h"
+
+namespace pulsar {
+
+DECLARE_LOG_OBJECT()
+
+TableViewImpl::TableViewImpl(const ClientImplPtr client, const std::string& 
topic,
+                             const TableViewConfiguration& conf)
+    : client_(client), topic_(topic), conf_(conf) {}
+
+Future<Result, TableViewImplPtr> TableViewImpl::start() {
+    Promise<Result, TableViewImplPtr> promise;
+    ReaderConfiguration readerConfiguration;
+    readerConfiguration.setSchema(conf_.schemaInfo);
+    readerConfiguration.setReadCompacted(true);
+    readerConfiguration.setInternalSubscriptionName(conf_.subscriptionName);
+
+    TableViewImplPtr self = shared_from_this();
+    ReaderCallback readerCallback = [self, promise](Result res, Reader reader) 
{
+        if (res == ResultOk) {
+            self->reader_ = reader.impl_;
+            self->readAllExistingMessages(promise, 
TimeUtils::currentTimeMillis(), 0);
+        } else {
+            promise.setFailed(res);
+        }
+    };
+    client_->createReaderAsync(topic_, MessageId::earliest(), 
readerConfiguration, readerCallback);
+    return promise.getFuture();
+}
+
+bool TableViewImpl::retrieveValue(const std::string& key, std::string& value) {
+    auto optValue = data_.remove(key);
+    if (optValue) {
+        value = optValue.value();
+        return true;
+    }
+    return false;
+}
+
+bool TableViewImpl::getValue(const std::string& key, std::string& value) const 
{
+    auto optValue = data_.find(key);
+    if (optValue) {
+        value = optValue.value();
+        return true;
+    }
+    return false;
+}
+
+bool TableViewImpl::containsKey(const std::string& key) const { return 
data_.find(key) != boost::none; }
+
+std::unordered_map<std::string, std::string> TableViewImpl::snapshot() { 
return data_.move(); }
+
+std::size_t TableViewImpl::size() const { return data_.size(); }
+
+void TableViewImpl::forEach(TableViewAction action) { data_.forEach(action); }
+
+void TableViewImpl::forEachAndListen(TableViewAction action) {
+    Lock lock(listenersMutex_);
+    data_.forEach(action);

Review Comment:
   Switch the order because `data_` does not need `listenersMutex_` to protect.
   
   ```suggestion
       data_.forEach(action);
       Lock lock(listenersMutex_);
   ```



-- 
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