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_r303183156
 
 

 ##########
 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)
+                {
+                    if (IsMessageExpired(envelope))
+                    {
+                        if (Tracer.IsDebugEnabled)
+                            Tracer.Debug($"{Info.Id} filtered expired message: 
{envelope.Message.NMSMessageId}");
+
+                        DoAckExpired(envelope);
+                    }
+                    else if (IsRedeliveryExceeded(envelope))
+                    {
+                        if (Tracer.IsDebugEnabled)
+                            Tracer.Debug($"{Info.Id} filtered message with 
excessive redelivery count: {envelope.RedeliveryCount}");
+
+                        // TODO: Apply redelivery policy
+                        DoAckExpired(envelope);
+                    }
+                    else
+                    {
+                        bool deliveryFailed = false;
+                        bool autoAckOrDupsOk = acknowledgementMode == 
AcknowledgementMode.AutoAcknowledge || acknowledgementMode == 
AcknowledgementMode.DupsOkAcknowledge;
+
+                        if (autoAckOrDupsOk)
+                            DoAckDelivered(envelope);
+                        else
+                            AckFromReceive(envelope);
+
+                        try
+                        {
+                            Listener.Invoke(envelope.Message);
 
 Review comment:
   Its a copy in the qpid implementation, see the JmsMessageConsumer 
[deliveryNextPending](https://github.com/apache/qpid-jms/blob/45e6ca37b156c34fa25b56b1a10b28234f53842a/qpid-jms-client/src/main/java/org/apache/qpid/jms/JmsMessageConsumer.java#L720)
 method. Qpid also copies the message in the send case, right before handing 
the message off to the provider, as well however I believe this is because qpid 
jms support async send paths so application that reuse messages for sending 
won't modify the message before it gets written to the wire. 
   
   I'm not sure that's the case with the nms amqp provider as the send 
operation are either presettled (non-persistent) or synchronous (persistent). 
   
   However, it might be worth looking into the amqpnetlite code to understand 
how the given Message object is stored and used and make sure the Message 
reference can not be modified before amqpnetlite encodes and writes out to the 
socket. Also another pointer where a message copy might be useful is on 
failover where the send is wrapped in a failover request that I think could be 
re-executed after failover (I'm still coming up to speed with that part of the 
code).

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