HavretGC commented on a change in pull request #4: AMQNET-589: Failover 
implementation
URL: https://github.com/apache/activemq-nms-amqp/pull/4#discussion_r303253206
 
 

 ##########
 File path: src/NMS.AMQP/NmsMessageConsumer.cs
 ##########
 @@ -0,0 +1,466 @@
+/*
+ * 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.
+ */
+
+using System;
+using System.Threading.Tasks;
+using Apache.NMS.AMQP.Message;
+using Apache.NMS.AMQP.Meta;
+using Apache.NMS.AMQP.Provider;
+using Apache.NMS.AMQP.Util;
+using Apache.NMS.Util;
+
+namespace Apache.NMS.AMQP
+{
+    public class NmsMessageConsumer : IMessageConsumer
+    {
+        private static readonly object SyncRoot = new object();
+        private readonly AcknowledgementMode acknowledgementMode;
+        private readonly AtomicBool closed = new AtomicBool();
+        private readonly MessageDeliveryTask deliveryTask;
+        private readonly PriorityMessageQueue messageQueue = new 
PriorityMessageQueue();
+        private readonly AtomicBool started = new AtomicBool();
+
+        private Exception failureCause;
+
+        public NmsMessageConsumer(Id consumerId, NmsSession session, 
IDestination destination, string selector, bool noLocal) : this(consumerId, 
session, destination, null, selector, noLocal)
+        {
+        }
+
+        public NmsMessageConsumer(Id consumerId, NmsSession session, 
IDestination destination, string name, string selector, bool noLocal)
+        {
+            Session = session;
+            acknowledgementMode = session.AcknowledgementMode;
+
+            if (destination.IsTemporary)
+            {
+                
session.Connection.CheckConsumeFromTemporaryDestination((NmsTemporaryDestination)
 destination);
+            }
+            
+            Info = new ConsumerInfo(consumerId, Session.SessionInfo.Id)
+            {
+                Destination = destination,
+                Selector = selector,
+                NoLocal = noLocal,
+                SubscriptionName = name
+            };
+            deliveryTask = new MessageDeliveryTask(this);
+
+            if (Session.IsStarted)
+                Start();
+        }
+
+        public NmsSession Session { get; }
+        public ConsumerInfo Info { get; }
+        public IDestination Destination => Info.Destination;
+
+        public void Dispose()
+        {
+            try
+            {
+                Close();
+            }
+            catch (Exception ex)
+            {
+                Tracer.DebugFormat("Caught exception while disposing {0} {1}. 
Exception {2}", GetType().Name, Info, ex);
+            }
+        }
+
+        public void Close()
+        {
+            if (closed.Value)
+                return;
+
+            lock (SyncRoot)
+            {
+                Shutdown(null);
+                
Session.Connection.DestroyResource(Info).ConfigureAwait(false).GetAwaiter().GetResult();
+            }
+        }
+
+        public ConsumerTransformerDelegate ConsumerTransformer { get; set; }
+
+        event MessageListener IMessageConsumer.Listener
+        {
+            add
+            {
+                CheckClosed();
+                lock (SyncRoot)
+                {
+                    Listener += value;
+                    DrainMessageQueueToListener();
+                }
+            }
+            remove
+            {
+                lock (SyncRoot)
+                {
+                    Listener -= value;                    
+                }
+            }
+        }
+
+        public IMessage Receive()
+        {
+            CheckClosed();
+            CheckMessageListener();
+
+            while (true)
+            {
+                if (started)
+                {
+                    return ReceiveInternal(-1);
+                }
+            }
+        }
+
+        public IMessage ReceiveNoWait()
+        {
+            CheckClosed();
+            CheckMessageListener();
+
+            return started ? ReceiveInternal(0) : null;
+        }
+
+        public IMessage Receive(TimeSpan timeout)
+        {
+            CheckClosed();
+            CheckMessageListener();
+
+            int timeoutInMilliseconds = (int) timeout.TotalMilliseconds;
+
+            if (started)
+            {
+                return ReceiveInternal(timeoutInMilliseconds);
+            }
+
+            long deadline = GetDeadline(timeoutInMilliseconds);
+
+            while (true)
+            {
+                timeoutInMilliseconds = (int) (deadline - 
DateTime.UtcNow.Ticks / 10_000L);
+                if (timeoutInMilliseconds < 0)
+                {
+                    return null;
+                }
+
+                if (started)
+                {
+                    return ReceiveInternal(timeoutInMilliseconds);
+                }
+            }
+        }
+
+        private void CheckMessageListener()
+        {
+            if (HasMessageListener())
+            {
+                throw new IllegalStateException("Cannot synchronously receive 
a message when a MessageListener is set");
+            }
+        }
+
+        private void CheckClosed()
+        {
+            if (closed)
+            {
+                throw new IllegalStateException("The MessageConsumer is 
closed");
+            }
+        }
+
+        private event MessageListener Listener;
+
+        public async Task Init()
+        {
+            await Session.Connection.CreateResource(Info);
+            await Session.Connection.StartResource(Info);
+        }
+
+        public void OnInboundMessage(InboundMessageDispatch envelope)
+        {
+            SetAcknowledgeCallback(envelope);
+
+            if (envelope.EnqueueFirst)
+                messageQueue.EnqueueFirst(envelope);
+            else
+                messageQueue.Enqueue(envelope);
+
+            if (Session.IsStarted && Listener != null)
+            {
+                Session.EnqueueForDispatch(deliveryTask);
+            }
+        }
+
+        private void DeliverNextPending()
+        {
+            if (Session.IsStarted && started && Listener != null)
+            {
+                var envelope = messageQueue.DequeueNoWait();
+                if (envelope == null)
+                    return;
+
+                lock (SyncRoot)
 
 Review comment:
   Not sure if we really want to maintain messageQueue state as this 
information is already represented by consumer's ```started``` field. The 
reason why this race condition might happen is lack of double check inside the 
lock statement. This is what Qpid jms is doing under the hood when you try to 
dequeue next element. In fact, as I'm looking at this implementation, there is 
still a risk of having null pointer exception on message listener there. As 
dequeueNoWait do not check if message listener is a null, sb may clear 
messageListener field between the check on top of the method and taking the 
lock. 
   
   The suggested change is to add the double check and this should solve the 
problem. 
   
   ```
   private void DeliverNextPending()
   {
       if (Session.IsStarted && started && Listener != null)
       {
           lock (SyncRoot)
           {
               if (started && Listener != null)
               {
                   var envelope = messageQueue.DequeueNoWait();
                   if (envelope == null)
                       return;                                  
                                        
                // the rest of the method
               }
           }
       }
   }
   ```

----------------------------------------------------------------
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.
 
For queries about this service, please contact Infrastructure at:
[email protected]


With regards,
Apache Git Services

Reply via email to