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

 ##########
 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:
   There is a race condition here when the envelope is taken from the message 
and either the consumer is stopped or closed. That lets the messages listener 
be invoked after the consumer is closed or the connection is stopped. I was 
able to see this by modifying TestConsumerCloseWaitsForAsyncDeliveryToComplete 
test to send another message after the 
"latch.WaitOne(TimeSpan.FromMilliseconds(30000)" line and setting some break 
points (with freezing threads).
   The qpid design that this is based off of avoids this by having the 
messageQueue maintain stop/start state and synchronizing the message delivery 
dispatch and the message queue start/stop state.
   

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