You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@pulsar.apache.org by gi...@git.apache.org on 2017/08/14 20:55:02 UTC

[GitHub] rdhabalia commented on a change in pull request #620: added new entrypoint for reader to websocket proxy

rdhabalia commented on a change in pull request #620: added new entrypoint for reader to websocket proxy
URL: https://github.com/apache/incubator-pulsar/pull/620#discussion_r133058980
 
 

 ##########
 File path: pulsar-websocket/src/main/java/org/apache/pulsar/websocket/ReaderHandler.java
 ##########
 @@ -0,0 +1,247 @@
+/**
+ * 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.
+ */
+package org.apache.pulsar.websocket;
+
+import static com.google.common.base.Preconditions.checkArgument;
+
+import java.io.IOException;
+import java.time.Instant;
+import java.time.ZoneId;
+import java.time.format.DateTimeFormatter;
+import java.util.Base64;
+import java.util.List;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicLongFieldUpdater;
+import java.util.concurrent.atomic.LongAdder;
+
+import javax.servlet.http.HttpServletRequest;
+
+import static org.apache.commons.lang3.StringUtils.isNotBlank;
+
+import org.apache.pulsar.client.api.ReaderConfiguration;
+import org.apache.pulsar.client.api.SubscriptionType;
+import org.apache.pulsar.client.impl.MessageIdImpl;
+import org.apache.pulsar.client.impl.ReaderImpl;
+import org.apache.pulsar.client.api.Consumer;
+import org.apache.pulsar.client.api.MessageId;
+import org.apache.pulsar.client.api.Reader;
+import org.apache.pulsar.common.naming.DestinationName;
+import org.apache.pulsar.common.util.ObjectMapperFactory;
+import org.apache.pulsar.websocket.data.ConsumerMessage;
+import org.eclipse.jetty.websocket.api.Session;
+import org.eclipse.jetty.websocket.api.WriteCallback;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.google.common.base.Splitter;
+
+/**
+ *
+ * WebSocket end-point url handler to handle incoming receive.
+ * <p>
+ * <b>receive:</b> socket-proxy keeps pushing messages to client by writing into session.<br/>
+ * </P>
+ *
+ */
+public class ReaderHandler extends AbstractWebSocketHandler {
+    private String subscription;
+    private final ReaderConfiguration conf;
+    private Reader reader;
+
+    private final int maxPendingMessages;
+    private final AtomicInteger pendingMessages = new AtomicInteger();
+    
+    private final LongAdder numMsgsDelivered;
+    private final LongAdder numBytesDelivered;
+    private volatile long msgDeliveredCounter = 0;
+    private static final AtomicLongFieldUpdater<ReaderHandler> MSG_DELIVERED_COUNTER_UPDATER =
+            AtomicLongFieldUpdater.newUpdater(ReaderHandler.class, "msgDeliveredCounter");
+
+    public ReaderHandler(WebSocketService service, HttpServletRequest request) {
+        super(service, request);
+        this.subscription = "";
+        this.conf = getReaderConfiguration();
+        this.maxPendingMessages = (conf.getReceiverQueueSize() == 0) ? 1 : conf.getReceiverQueueSize();
+        this.numMsgsDelivered = new LongAdder();
+        this.numBytesDelivered = new LongAdder();        
+    }
+
+    @Override
+    protected void createClient(Session session) {
+
+        try {
+            this.reader = service.getPulsarClient().createReader(topic, getMessageId(), conf);
+            this.subscription = ((ReaderImpl)this.reader).getConsumer().getSubscription(); 
+            this.service.addReader(this);
+            receiveMessage();
+        } catch (Exception e) {
+            log.warn("[{}] Failed in creating subscription {} on topic {}", session.getRemoteAddress(), subscription,
+                    topic, e);
+            close(WebSocketError.FailedToSubscribe, e.getMessage());
+        }
+    }
+
+	private void receiveMessage() {
+        if (log.isDebugEnabled()) {
+            log.debug("[{}] [{}] [{}] Receive next message", getSession().getRemoteAddress(), topic, subscription);
+        }
+
+        reader.readNextAsync().thenAccept(msg -> {
+            if (log.isDebugEnabled()) {
+                log.debug("[{}] [{}] [{}] Got message {}", getSession().getRemoteAddress(), topic, subscription,
+                        msg.getMessageId());
+            }
+
+            ConsumerMessage dm = new ConsumerMessage();
+            dm.messageId = Base64.getEncoder().encodeToString(msg.getMessageId().toByteArray());
+            dm.payload = Base64.getEncoder().encodeToString(msg.getData());
+            dm.properties = msg.getProperties();
+            dm.publishTime = DATE_FORMAT.format(Instant.ofEpochMilli(msg.getPublishTime()));
+            if (msg.hasKey()) {
+                dm.key = msg.getKey();
+            }
+            final long msgSize = msg.getData().length;
+
+            try {
+                getSession().getRemote()
+                        .sendString(ObjectMapperFactory.getThreadLocal().writeValueAsString(dm), new WriteCallback() {
+                            @Override
+                            public void writeFailed(Throwable th) {
+                                log.warn("[{}/{}] Failed to deliver msg to {} {}", reader.getTopic(), subscription,
+                                        getRemote().getInetSocketAddress().toString(), th.getMessage());
+                                pendingMessages.decrementAndGet();
+                                // schedule receive as one of the delivery failed
+                                service.getExecutor().execute(() -> receiveMessage());
+                            }
+
+                            @Override
+                            public void writeSuccess() {
+                                if (log.isDebugEnabled()) {
+                                    log.debug("[{}/{}] message is delivered successfully to {} ", reader.getTopic(),
+                                            subscription, getRemote().getInetSocketAddress().toString());
+                                }
+                                updateDeliverMsgStat(msgSize);
+                                pendingMessages.getAndDecrement();
+                            }
+                        });
+            } catch (JsonProcessingException e) {
+                close(WebSocketError.FailedToSerializeToJSON);
+            }
+
+            int pending = pendingMessages.incrementAndGet();
+            if (pending < maxPendingMessages) {
+                // Start next read in a separate thread to avoid recursion
+                service.getExecutor().execute(() -> receiveMessage());
+            } else {
+                // Resume delivery
+                receiveMessage();
 
 Review comment:
   Should't we stop delivery if `pending` reached to `maxPendingMessages` else it will keep sending messages to the client ? 
   Should we do the similar like [ConsumerHandler](https://github.com/apache/incubator-pulsar/blob/master/pulsar-websocket/src/main/java/org/apache/pulsar/websocket/ConsumerHandler.java#L166), after reaching `maxPendingMessages`, proxy-reader will send more message when it receives a new `readNext` request from client, same way consumer receives `ack-request`.? If that seems feasible solution then we can document the semantic into websocket-reader-doc as well.
   
   
   
 
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services