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


##########
lib/TableViewImpl.h:
##########
@@ -0,0 +1,74 @@
+/**
+ * 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.
+ */
+
+#ifndef PULSAR_CPP_TABLEVIEW_IMPL_H
+#define PULSAR_CPP_TABLEVIEW_IMPL_H
+
+#include <map>
+
+#include "ClientImpl.h"

Review Comment:
   It's better not to include "ClientImpl.h" directly. Use forward declaration. 
See `ProducerImpl.h` for example.



##########
lib/TableViewImpl.h:
##########
@@ -0,0 +1,74 @@
+/**
+ * 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.
+ */
+
+#ifndef PULSAR_CPP_TABLEVIEW_IMPL_H
+#define PULSAR_CPP_TABLEVIEW_IMPL_H
+
+#include <map>
+
+#include "ClientImpl.h"
+#include "SynchronizedHashMap.h"
+
+namespace pulsar {
+
+class TableViewImpl : public std::enable_shared_from_this<TableViewImpl> {
+   public:
+    TableViewImpl(const ClientImplPtr client, const std::string& topic, const 
TableViewConfiguration& conf);

Review Comment:
   Don't add `const` to a value type. (tips. a `std::shared_ptr` is also a 
value type because it's just a class)
   
   ```suggestion
       TableViewImpl(ClientImplPtr client, const std::string& topic, const 
TableViewConfiguration& conf);
   ```



##########
lib/ClientImpl.cc:
##########
@@ -244,6 +245,34 @@ void ClientImpl::createReaderAsync(const std::string& 
topic, const MessageId& st
                   std::placeholders::_2, topicName, msgId, conf, callback));
 }
 
+void ClientImpl::createTableViewAsync(const std::string& topic, const 
TableViewConfiguration& conf,
+                                      TableViewCallback callback) {
+    TopicNamePtr topicName;
+    {
+        Lock lock(mutex_);
+        if (state_ != Open) {
+            lock.unlock();
+            callback(ResultAlreadyClosed, TableView());
+            return;
+        } else if (!(topicName = TopicName::get(topic))) {
+            lock.unlock();
+            callback(ResultInvalidTopicName, TableView());
+            return;
+        }
+    }
+
+    TableViewImplPtr tableViewPtr =
+        std::make_shared<TableViewImpl>(shared_from_this(), 
topicName->toString(), conf);
+    auto self = shared_from_this();
+    tableViewPtr->start().addListener([callback, self](Result result, 
TableViewImplPtr tableViewImplPtr) {

Review Comment:
   ```suggestion
       tableViewPtr->start().addListener([callback](Result result, 
TableViewImplPtr tableViewImplPtr) {
   ```
   
   We don't need to capture `self` because there is no field like `producers_` 
and `consumers_` in `ClientImpl`



##########
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());
+            } catch (const std::exception& exc) {
+                LOG_ERROR("Table view listener raised an exception: " << 
exc.what());
+            }
+        }
+    }
+}
+
+void TableViewImpl::readAllExistingMessages(Promise<Result, TableViewImplPtr> 
promise, long startTime,
+                                            long messagesRead) {
+    std::weak_ptr<TableViewImpl> weakSelf{shared_from_this()};
+    reader_->hasMessageAvailableAsync(
+        [weakSelf, promise, startTime, messagesRead](Result result, bool 
hasMessage) {
+            auto self = weakSelf.lock();
+            if (!self || result != ResultOk) {
+                promise.setFailed(result);
+                return;
+            }
+            if (hasMessage) {
+                Message msg;
+                self->reader_->readNextAsync(
+                    [weakSelf, promise, startTime, messagesRead](Result res, 
const Message& msg) {
+                        auto self = weakSelf.lock();
+                        if (!self || res != ResultOk) {
+                            promise.setFailed(res);

Review Comment:
   Maybe we should add an error log if `res != ResultOk`?



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