001/**
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.activemq.broker.region;
018
019import java.io.IOException;
020import java.util.ArrayList;
021import java.util.Iterator;
022import java.util.LinkedList;
023import java.util.List;
024import java.util.concurrent.CountDownLatch;
025import java.util.concurrent.TimeUnit;
026
027import javax.jms.JMSException;
028
029import org.apache.activemq.broker.Broker;
030import org.apache.activemq.broker.ConnectionContext;
031import org.apache.activemq.broker.region.cursors.PendingMessageCursor;
032import org.apache.activemq.broker.region.cursors.VMPendingMessageCursor;
033import org.apache.activemq.command.ConsumerControl;
034import org.apache.activemq.command.ConsumerInfo;
035import org.apache.activemq.command.Message;
036import org.apache.activemq.command.MessageAck;
037import org.apache.activemq.command.MessageDispatch;
038import org.apache.activemq.command.MessageDispatchNotification;
039import org.apache.activemq.command.MessageId;
040import org.apache.activemq.command.MessagePull;
041import org.apache.activemq.command.Response;
042import org.apache.activemq.thread.Scheduler;
043import org.apache.activemq.transaction.Synchronization;
044import org.apache.activemq.transport.TransmitCallback;
045import org.apache.activemq.usage.SystemUsage;
046import org.slf4j.Logger;
047import org.slf4j.LoggerFactory;
048
049/**
050 * A subscription that honors the pre-fetch option of the ConsumerInfo.
051 */
052public abstract class PrefetchSubscription extends AbstractSubscription {
053
054    private static final Logger LOG = LoggerFactory.getLogger(PrefetchSubscription.class);
055    protected final Scheduler scheduler;
056
057    protected PendingMessageCursor pending;
058    protected final List<MessageReference> dispatched = new ArrayList<MessageReference>();
059    private int maxProducersToAudit=32;
060    private int maxAuditDepth=2048;
061    protected final SystemUsage usageManager;
062    protected final Object pendingLock = new Object();
063    protected final Object dispatchLock = new Object();
064    private final CountDownLatch okForAckAsDispatchDone = new CountDownLatch(1);
065
066    public PrefetchSubscription(Broker broker, SystemUsage usageManager, ConnectionContext context, ConsumerInfo info, PendingMessageCursor cursor) throws JMSException {
067        super(broker,context, info);
068        this.usageManager=usageManager;
069        pending = cursor;
070        try {
071            pending.start();
072        } catch (Exception e) {
073            throw new JMSException(e.getMessage());
074        }
075        this.scheduler = broker.getScheduler();
076    }
077
078    public PrefetchSubscription(Broker broker,SystemUsage usageManager, ConnectionContext context, ConsumerInfo info) throws JMSException {
079        this(broker,usageManager,context, info, new VMPendingMessageCursor(false));
080    }
081
082    /**
083     * Allows a message to be pulled on demand by a client
084     */
085    @Override
086    public Response pullMessage(ConnectionContext context, final MessagePull pull) throws Exception {
087        // The slave should not deliver pull messages.
088        // TODO: when the slave becomes a master, He should send a NULL message to all the
089        // consumers to 'wake them up' in case they were waiting for a message.
090        if (getPrefetchSize() == 0) {
091            prefetchExtension.set(pull.getQuantity());
092            final long dispatchCounterBeforePull = getSubscriptionStatistics().getDispatched().getCount();
093
094            // Have the destination push us some messages.
095            for (Destination dest : destinations) {
096                dest.iterate();
097            }
098            dispatchPending();
099
100            synchronized(this) {
101                // If there was nothing dispatched.. we may need to setup a timeout.
102                if (dispatchCounterBeforePull == getSubscriptionStatistics().getDispatched().getCount() || pull.isAlwaysSignalDone()) {
103                    // immediate timeout used by receiveNoWait()
104                    if (pull.getTimeout() == -1) {
105                        // Null message indicates the pull is done or did not have pending.
106                        prefetchExtension.set(1);
107                        add(QueueMessageReference.NULL_MESSAGE);
108                        dispatchPending();
109                    }
110                    if (pull.getTimeout() > 0) {
111                        scheduler.executeAfterDelay(new Runnable() {
112                            @Override
113                            public void run() {
114                                pullTimeout(dispatchCounterBeforePull, pull.isAlwaysSignalDone());
115                            }
116                        }, pull.getTimeout());
117                    }
118                }
119            }
120        }
121        return null;
122    }
123
124    /**
125     * Occurs when a pull times out. If nothing has been dispatched since the
126     * timeout was setup, then send the NULL message.
127     */
128    final void pullTimeout(long dispatchCounterBeforePull, boolean alwaysSignalDone) {
129        synchronized (pendingLock) {
130            if (dispatchCounterBeforePull == getSubscriptionStatistics().getDispatched().getCount() || alwaysSignalDone) {
131                try {
132                    prefetchExtension.set(1);
133                    add(QueueMessageReference.NULL_MESSAGE);
134                    dispatchPending();
135                } catch (Exception e) {
136                    context.getConnection().serviceException(e);
137                } finally {
138                    prefetchExtension.set(0);
139                }
140            }
141        }
142    }
143
144    @Override
145    public void add(MessageReference node) throws Exception {
146        synchronized (pendingLock) {
147            // The destination may have just been removed...
148            if (!destinations.contains(node.getRegionDestination()) && node != QueueMessageReference.NULL_MESSAGE) {
149                // perhaps we should inform the caller that we are no longer valid to dispatch to?
150                return;
151            }
152
153            // Don't increment for the pullTimeout control message.
154            if (!node.equals(QueueMessageReference.NULL_MESSAGE)) {
155                getSubscriptionStatistics().getEnqueues().increment();
156            }
157            pending.addMessageLast(node);
158        }
159        dispatchPending();
160    }
161
162    @Override
163    public void processMessageDispatchNotification(MessageDispatchNotification mdn) throws Exception {
164        synchronized(pendingLock) {
165            try {
166                pending.reset();
167                while (pending.hasNext()) {
168                    MessageReference node = pending.next();
169                    node.decrementReferenceCount();
170                    if (node.getMessageId().equals(mdn.getMessageId())) {
171                        // Synchronize between dispatched list and removal of messages from pending list
172                        // related to remove subscription action
173                        synchronized(dispatchLock) {
174                            pending.remove();
175                            createMessageDispatch(node, node.getMessage());
176                            dispatched.add(node);
177                            getSubscriptionStatistics().getInflightMessageSize().addSize(node.getSize());
178                            onDispatch(node, node.getMessage());
179                        }
180                        return;
181                    }
182                }
183            } finally {
184                pending.release();
185            }
186        }
187        throw new JMSException(
188                "Slave broker out of sync with master: Dispatched message ("
189                        + mdn.getMessageId() + ") was not in the pending list for "
190                        + mdn.getConsumerId() + " on " + mdn.getDestination().getPhysicalName());
191    }
192
193    @Override
194    public final void acknowledge(final ConnectionContext context,final MessageAck ack) throws Exception {
195        // Handle the standard acknowledgment case.
196        boolean callDispatchMatched = false;
197        Destination destination = null;
198
199        if (!okForAckAsDispatchDone.await(0l, TimeUnit.MILLISECONDS)) {
200            // suppress unexpected ack exception in this expected case
201            LOG.warn("Ignoring ack received before dispatch; result of failover with an outstanding ack. Acked messages will be replayed if present on this broker. Ignored ack: {}", ack);
202            return;
203        }
204
205        LOG.trace("ack: {}", ack);
206
207        synchronized(dispatchLock) {
208            if (ack.isStandardAck()) {
209                // First check if the ack matches the dispatched. When using failover this might
210                // not be the case. We don't ever want to ack the wrong messages.
211                assertAckMatchesDispatched(ack);
212
213                // Acknowledge all dispatched messages up till the message id of
214                // the acknowledgment.
215                boolean inAckRange = false;
216                List<MessageReference> removeList = new ArrayList<MessageReference>();
217                for (final MessageReference node : dispatched) {
218                    MessageId messageId = node.getMessageId();
219                    if (ack.getFirstMessageId() == null
220                            || ack.getFirstMessageId().equals(messageId)) {
221                        inAckRange = true;
222                    }
223                    if (inAckRange) {
224                        // Don't remove the nodes until we are committed.
225                        if (!context.isInTransaction()) {
226                            getSubscriptionStatistics().getDequeues().increment();
227                            ((Destination)node.getRegionDestination()).getDestinationStatistics().getInflight().decrement();
228                            removeList.add(node);
229                            contractPrefetchExtension(1);
230                        } else {
231                            registerRemoveSync(context, node);
232                        }
233                        acknowledge(context, ack, node);
234                        if (ack.getLastMessageId().equals(messageId)) {
235                            destination = (Destination) node.getRegionDestination();
236                            callDispatchMatched = true;
237                            break;
238                        }
239                    }
240                }
241                for (final MessageReference node : removeList) {
242                    dispatched.remove(node);
243                    getSubscriptionStatistics().getInflightMessageSize().addSize(-node.getSize());
244                }
245                // this only happens after a reconnect - get an ack which is not
246                // valid
247                if (!callDispatchMatched) {
248                    LOG.warn("Could not correlate acknowledgment with dispatched message: {}", ack);
249                }
250            } else if (ack.isIndividualAck()) {
251                // Message was delivered and acknowledge - but only delete the
252                // individual message
253                for (final MessageReference node : dispatched) {
254                    MessageId messageId = node.getMessageId();
255                    if (ack.getLastMessageId().equals(messageId)) {
256                        // Don't remove the nodes until we are committed - immediateAck option
257                        if (!context.isInTransaction()) {
258                            getSubscriptionStatistics().getDequeues().increment();
259                            ((Destination)node.getRegionDestination()).getDestinationStatistics().getInflight().decrement();
260                            dispatched.remove(node);
261                            getSubscriptionStatistics().getInflightMessageSize().addSize(-node.getSize());
262                            contractPrefetchExtension(1);
263                        } else {
264                            registerRemoveSync(context, node);
265                            expandPrefetchExtension(1);
266                        }
267                        acknowledge(context, ack, node);
268                        destination = (Destination) node.getRegionDestination();
269                        callDispatchMatched = true;
270                        break;
271                    }
272                }
273            } else if (ack.isDeliveredAck()) {
274                // Message was delivered but not acknowledged: update pre-fetch
275                // counters.
276                int index = 0;
277                for (Iterator<MessageReference> iter = dispatched.iterator(); iter.hasNext(); index++) {
278                    final MessageReference node = iter.next();
279                    Destination nodeDest = (Destination) node.getRegionDestination();
280                    if (ack.getLastMessageId().equals(node.getMessageId())) {
281                        expandPrefetchExtension(ack.getMessageCount());
282                        destination = nodeDest;
283                        callDispatchMatched = true;
284                        break;
285                    }
286                }
287                if (!callDispatchMatched) {
288                    throw new JMSException(
289                            "Could not correlate acknowledgment with dispatched message: "
290                                    + ack);
291                }
292            } else if (ack.isExpiredAck()) {
293                // Message was expired
294                int index = 0;
295                boolean inAckRange = false;
296                for (Iterator<MessageReference> iter = dispatched.iterator(); iter.hasNext(); index++) {
297                    final MessageReference node = iter.next();
298                    Destination nodeDest = (Destination) node.getRegionDestination();
299                    MessageId messageId = node.getMessageId();
300                    if (ack.getFirstMessageId() == null || ack.getFirstMessageId().equals(messageId)) {
301                        inAckRange = true;
302                    }
303                    if (inAckRange) {
304                        Destination regionDestination = nodeDest;
305                        if (broker.isExpired(node)) {
306                            regionDestination.messageExpired(context, this, node);
307                        }
308                        iter.remove();
309                        nodeDest.getDestinationStatistics().getInflight().decrement();
310
311                        if (ack.getLastMessageId().equals(messageId)) {
312                            contractPrefetchExtension(1);
313                            destination = (Destination) node.getRegionDestination();
314                            callDispatchMatched = true;
315                            break;
316                        }
317                    }
318                }
319                if (!callDispatchMatched) {
320                    throw new JMSException(
321                            "Could not correlate expiration acknowledgment with dispatched message: "
322                                    + ack);
323                }
324            } else if (ack.isRedeliveredAck()) {
325                // Message was re-delivered but it was not yet considered to be
326                // a DLQ message.
327                boolean inAckRange = false;
328                for (final MessageReference node : dispatched) {
329                    MessageId messageId = node.getMessageId();
330                    if (ack.getFirstMessageId() == null
331                            || ack.getFirstMessageId().equals(messageId)) {
332                        inAckRange = true;
333                    }
334                    if (inAckRange) {
335                        if (ack.getLastMessageId().equals(messageId)) {
336                            destination = (Destination) node.getRegionDestination();
337                            callDispatchMatched = true;
338                            break;
339                        }
340                    }
341                }
342                if (!callDispatchMatched) {
343                    throw new JMSException(
344                            "Could not correlate acknowledgment with dispatched message: "
345                                    + ack);
346                }
347            } else if (ack.isPoisonAck()) {
348                // TODO: what if the message is already in a DLQ???
349                // Handle the poison ACK case: we need to send the message to a
350                // DLQ
351                if (ack.isInTransaction()) {
352                    throw new JMSException("Poison ack cannot be transacted: "
353                            + ack);
354                }
355                int index = 0;
356                boolean inAckRange = false;
357                List<MessageReference> removeList = new ArrayList<MessageReference>();
358                for (final MessageReference node : dispatched) {
359                    MessageId messageId = node.getMessageId();
360                    if (ack.getFirstMessageId() == null
361                            || ack.getFirstMessageId().equals(messageId)) {
362                        inAckRange = true;
363                    }
364                    if (inAckRange) {
365                        sendToDLQ(context, node, ack.getPoisonCause());
366                        Destination nodeDest = (Destination) node.getRegionDestination();
367                        nodeDest.getDestinationStatistics()
368                        .getInflight().decrement();
369                        removeList.add(node);
370                        getSubscriptionStatistics().getDequeues().increment();
371                        index++;
372                        acknowledge(context, ack, node);
373                        if (ack.getLastMessageId().equals(messageId)) {
374                            contractPrefetchExtension(1);
375                            destination = nodeDest;
376                            callDispatchMatched = true;
377                            break;
378                        }
379                    }
380                }
381                for (final MessageReference node : removeList) {
382                    dispatched.remove(node);
383                    getSubscriptionStatistics().getInflightMessageSize().addSize(-node.getSize());
384                }
385                if (!callDispatchMatched) {
386                    throw new JMSException(
387                            "Could not correlate acknowledgment with dispatched message: "
388                                    + ack);
389                }
390            }
391        }
392        if (callDispatchMatched && destination != null) {
393            destination.wakeup();
394            dispatchPending();
395
396            if (pending.isEmpty()) {
397                wakeupDestinationsForDispatch();
398            }
399        } else {
400            LOG.debug("Acknowledgment out of sync (Normally occurs when failover connection reconnects): {}", ack);
401        }
402    }
403
404    private void registerRemoveSync(ConnectionContext context, final MessageReference node) {
405        // setup a Synchronization to remove nodes from the
406        // dispatched list.
407        context.getTransaction().addSynchronization(
408                new Synchronization() {
409
410                    @Override
411                    public void afterCommit()
412                            throws Exception {
413                        Destination nodeDest = (Destination) node.getRegionDestination();
414                        synchronized (dispatchLock) {
415                            getSubscriptionStatistics().getDequeues().increment();
416                            dispatched.remove(node);
417                            getSubscriptionStatistics().getInflightMessageSize().addSize(-node.getSize());
418                            nodeDest.getDestinationStatistics().getInflight().decrement();
419                        }
420                        contractPrefetchExtension(1);
421                        nodeDest.wakeup();
422                        dispatchPending();
423                    }
424
425                    @Override
426                    public void afterRollback() throws Exception {
427                        contractPrefetchExtension(1);
428                    }
429                });
430    }
431
432    /**
433     * Checks an ack versus the contents of the dispatched list.
434     *  called with dispatchLock held
435     * @param ack
436     * @throws JMSException if it does not match
437     */
438    protected void assertAckMatchesDispatched(MessageAck ack) throws JMSException {
439        MessageId firstAckedMsg = ack.getFirstMessageId();
440        MessageId lastAckedMsg = ack.getLastMessageId();
441        int checkCount = 0;
442        boolean checkFoundStart = false;
443        boolean checkFoundEnd = false;
444        for (MessageReference node : dispatched) {
445
446            if (firstAckedMsg == null) {
447                checkFoundStart = true;
448            } else if (!checkFoundStart && firstAckedMsg.equals(node.getMessageId())) {
449                checkFoundStart = true;
450            }
451
452            if (checkFoundStart) {
453                checkCount++;
454            }
455
456            if (lastAckedMsg != null && lastAckedMsg.equals(node.getMessageId())) {
457                checkFoundEnd = true;
458                break;
459            }
460        }
461        if (!checkFoundStart && firstAckedMsg != null)
462            throw new JMSException("Unmatched acknowledge: " + ack
463                    + "; Could not find Message-ID " + firstAckedMsg
464                    + " in dispatched-list (start of ack)");
465        if (!checkFoundEnd && lastAckedMsg != null)
466            throw new JMSException("Unmatched acknowledge: " + ack
467                    + "; Could not find Message-ID " + lastAckedMsg
468                    + " in dispatched-list (end of ack)");
469        if (ack.getMessageCount() != checkCount && !ack.isInTransaction()) {
470            throw new JMSException("Unmatched acknowledge: " + ack
471                    + "; Expected message count (" + ack.getMessageCount()
472                    + ") differs from count in dispatched-list (" + checkCount
473                    + ")");
474        }
475    }
476
477    /**
478     *
479     * @param context
480     * @param node
481     * @param poisonCause
482     * @throws IOException
483     * @throws Exception
484     */
485    protected void sendToDLQ(final ConnectionContext context, final MessageReference node, Throwable poisonCause) throws IOException, Exception {
486        broker.getRoot().sendToDeadLetterQueue(context, node, this, poisonCause);
487    }
488
489    @Override
490    public int getInFlightSize() {
491        return dispatched.size();
492    }
493
494    /**
495     * Used to determine if the broker can dispatch to the consumer.
496     *
497     * @return
498     */
499    @Override
500    public boolean isFull() {
501        return getPrefetchSize() == 0 ? prefetchExtension.get() == 0 : dispatched.size() - prefetchExtension.get() >= info.getPrefetchSize();
502    }
503
504    /**
505     * @return true when 60% or more room is left for dispatching messages
506     */
507    @Override
508    public boolean isLowWaterMark() {
509        return (dispatched.size() - prefetchExtension.get()) <= (info.getPrefetchSize() * .4);
510    }
511
512    /**
513     * @return true when 10% or less room is left for dispatching messages
514     */
515    @Override
516    public boolean isHighWaterMark() {
517        return (dispatched.size() - prefetchExtension.get()) >= (info.getPrefetchSize() * .9);
518    }
519
520    @Override
521    public int countBeforeFull() {
522        return getPrefetchSize() == 0 ? prefetchExtension.get() : info.getPrefetchSize() + prefetchExtension.get() - dispatched.size();
523    }
524
525    @Override
526    public int getPendingQueueSize() {
527        return pending.size();
528    }
529
530    @Override
531    public int getDispatchedQueueSize() {
532        return dispatched.size();
533    }
534
535    @Override
536    public long getDequeueCounter() {
537        return getSubscriptionStatistics().getDequeues().getCount();
538    }
539
540    @Override
541    public long getDispatchedCounter() {
542        return getSubscriptionStatistics().getDispatched().getCount();
543    }
544
545    @Override
546    public long getEnqueueCounter() {
547        return getSubscriptionStatistics().getEnqueues().getCount();
548    }
549
550    @Override
551    public boolean isRecoveryRequired() {
552        return pending.isRecoveryRequired();
553    }
554
555    public PendingMessageCursor getPending() {
556        return this.pending;
557    }
558
559    public void setPending(PendingMessageCursor pending) {
560        this.pending = pending;
561        if (this.pending!=null) {
562            this.pending.setSystemUsage(usageManager);
563            this.pending.setMemoryUsageHighWaterMark(getCursorMemoryHighWaterMark());
564        }
565    }
566
567    @Override
568    public void add(ConnectionContext context, Destination destination) throws Exception {
569        synchronized(pendingLock) {
570            super.add(context, destination);
571            pending.add(context, destination);
572        }
573    }
574
575    @Override
576    public List<MessageReference> remove(ConnectionContext context, Destination destination) throws Exception {
577        return remove(context, destination, dispatched);
578    }
579
580    public List<MessageReference> remove(ConnectionContext context, Destination destination, List<MessageReference> dispatched) throws Exception {
581        LinkedList<MessageReference> redispatch = new LinkedList<MessageReference>();
582        synchronized(pendingLock) {
583            super.remove(context, destination);
584            // Here is a potential problem concerning Inflight stat:
585            // Messages not already committed or rolled back may not be removed from dispatched list at the moment
586            // Except if each commit or rollback callback action comes before remove of subscriber.
587            redispatch.addAll(pending.remove(context, destination));
588
589            if (dispatched == null) {
590                return redispatch;
591            }
592
593            // Synchronized to DispatchLock if necessary
594            if (dispatched == this.dispatched) {
595                synchronized(dispatchLock) {
596                    addReferencesAndUpdateRedispatch(redispatch, destination, dispatched);
597                }
598            } else {
599                addReferencesAndUpdateRedispatch(redispatch, destination, dispatched);
600            }
601        }
602
603        return redispatch;
604    }
605
606    private void addReferencesAndUpdateRedispatch(LinkedList<MessageReference> redispatch, Destination destination, List<MessageReference> dispatched) {
607        ArrayList<MessageReference> references = new ArrayList<MessageReference>();
608        for (MessageReference r : dispatched) {
609            if (r.getRegionDestination() == destination) {
610                references.add(r);
611                getSubscriptionStatistics().getInflightMessageSize().addSize(-r.getSize());
612            }
613        }
614        redispatch.addAll(0, references);
615        destination.getDestinationStatistics().getInflight().subtract(references.size());
616        dispatched.removeAll(references);
617    }
618
619    // made public so it can be used in MQTTProtocolConverter
620    public void dispatchPending() throws IOException {
621        List<Destination> slowConsumerTargets = null;
622
623        synchronized(pendingLock) {
624            try {
625                int numberToDispatch = countBeforeFull();
626                if (numberToDispatch > 0) {
627                    setSlowConsumer(false);
628                    setPendingBatchSize(pending, numberToDispatch);
629                    int count = 0;
630                    pending.reset();
631                    while (count < numberToDispatch && !isFull() && pending.hasNext()) {
632                        MessageReference node = pending.next();
633                        if (node == null) {
634                            break;
635                        }
636
637                        // Synchronize between dispatched list and remove of message from pending list
638                        // related to remove subscription action
639                        synchronized(dispatchLock) {
640                            pending.remove();
641                            if (!isDropped(node) && canDispatch(node)) {
642
643                                // Message may have been sitting in the pending
644                                // list a while waiting for the consumer to ak the message.
645                                if (node != QueueMessageReference.NULL_MESSAGE && node.isExpired()) {
646                                    //increment number to dispatch
647                                    numberToDispatch++;
648                                    if (broker.isExpired(node)) {
649                                        ((Destination)node.getRegionDestination()).messageExpired(context, this, node);
650                                    }
651
652                                    if (!isBrowser()) {
653                                        node.decrementReferenceCount();
654                                        continue;
655                                    }
656                                }
657                                dispatch(node);
658                                count++;
659                            }
660                        }
661                        // decrement after dispatch has taken ownership to avoid usage jitter
662                        node.decrementReferenceCount();
663                    }
664                } else if (!isSlowConsumer()) {
665                    setSlowConsumer(true);
666                    slowConsumerTargets = destinations;
667                }
668            } finally {
669                pending.release();
670            }
671        }
672
673        if (slowConsumerTargets != null) {
674            for (Destination dest : slowConsumerTargets) {
675                dest.slowConsumer(context, this);
676            }
677        }
678    }
679
680    protected void setPendingBatchSize(PendingMessageCursor pending, int numberToDispatch) {
681        pending.setMaxBatchSize(numberToDispatch);
682    }
683
684    // called with dispatchLock held
685    protected boolean dispatch(final MessageReference node) throws IOException {
686        final Message message = node.getMessage();
687        if (message == null) {
688            return false;
689        }
690
691        okForAckAsDispatchDone.countDown();
692
693        MessageDispatch md = createMessageDispatch(node, message);
694        if (node != QueueMessageReference.NULL_MESSAGE) {
695            getSubscriptionStatistics().getDispatched().increment();
696            dispatched.add(node);
697            getSubscriptionStatistics().getInflightMessageSize().addSize(node.getSize());
698        }
699        if (getPrefetchSize() == 0) {
700            while (true) {
701                int currentExtension = prefetchExtension.get();
702                int newExtension = Math.max(0, currentExtension - 1);
703                if (prefetchExtension.compareAndSet(currentExtension, newExtension)) {
704                    break;
705                }
706            }
707        }
708        if (info.isDispatchAsync()) {
709            md.setTransmitCallback(new TransmitCallback() {
710
711                @Override
712                public void onSuccess() {
713                    // Since the message gets queued up in async dispatch, we don't want to
714                    // decrease the reference count until it gets put on the wire.
715                    onDispatch(node, message);
716                }
717
718                @Override
719                public void onFailure() {
720                    Destination nodeDest = (Destination) node.getRegionDestination();
721                    if (nodeDest != null) {
722                        if (node != QueueMessageReference.NULL_MESSAGE) {
723                            nodeDest.getDestinationStatistics().getDispatched().increment();
724                            nodeDest.getDestinationStatistics().getInflight().increment();
725                            LOG.trace("{} failed to dispatch: {} - {}, dispatched: {}, inflight: {}", new Object[]{ info.getConsumerId(), message.getMessageId(), message.getDestination(), getSubscriptionStatistics().getDispatched().getCount(), dispatched.size() });
726                        }
727                    }
728                    if (node instanceof QueueMessageReference) {
729                        ((QueueMessageReference) node).unlock();
730                    }
731                }
732            });
733            context.getConnection().dispatchAsync(md);
734        } else {
735            context.getConnection().dispatchSync(md);
736            onDispatch(node, message);
737        }
738        return true;
739    }
740
741    protected void onDispatch(final MessageReference node, final Message message) {
742        Destination nodeDest = (Destination) node.getRegionDestination();
743        if (nodeDest != null) {
744            if (node != QueueMessageReference.NULL_MESSAGE) {
745                nodeDest.getDestinationStatistics().getDispatched().increment();
746                nodeDest.getDestinationStatistics().getInflight().increment();
747                LOG.trace("{} dispatched: {} - {}, dispatched: {}, inflight: {}", new Object[]{ info.getConsumerId(), message.getMessageId(), message.getDestination(), getSubscriptionStatistics().getDispatched().getCount(), dispatched.size() });
748            }
749        }
750
751        if (info.isDispatchAsync()) {
752            try {
753                dispatchPending();
754            } catch (IOException e) {
755                context.getConnection().serviceExceptionAsync(e);
756            }
757        }
758    }
759
760    /**
761     * inform the MessageConsumer on the client to change it's prefetch
762     *
763     * @param newPrefetch
764     */
765    @Override
766    public void updateConsumerPrefetch(int newPrefetch) {
767        if (context != null && context.getConnection() != null && context.getConnection().isManageable()) {
768            ConsumerControl cc = new ConsumerControl();
769            cc.setConsumerId(info.getConsumerId());
770            cc.setPrefetch(newPrefetch);
771            context.getConnection().dispatchAsync(cc);
772        }
773    }
774
775    /**
776     * @param node
777     * @param message
778     * @return MessageDispatch
779     */
780    protected MessageDispatch createMessageDispatch(MessageReference node, Message message) {
781        MessageDispatch md = new MessageDispatch();
782        md.setConsumerId(info.getConsumerId());
783
784        if (node == QueueMessageReference.NULL_MESSAGE) {
785            md.setMessage(null);
786            md.setDestination(null);
787        } else {
788            Destination regionDestination = (Destination) node.getRegionDestination();
789            md.setDestination(regionDestination.getActiveMQDestination());
790            md.setMessage(message);
791            md.setRedeliveryCounter(node.getRedeliveryCounter());
792        }
793
794        return md;
795    }
796
797    /**
798     * Use when a matched message is about to be dispatched to the client.
799     *
800     * @param node
801     * @return false if the message should not be dispatched to the client
802     *         (another sub may have already dispatched it for example).
803     * @throws IOException
804     */
805    protected abstract boolean canDispatch(MessageReference node) throws IOException;
806
807    protected abstract boolean isDropped(MessageReference node);
808
809    /**
810     * Used during acknowledgment to remove the message.
811     *
812     * @throws IOException
813     */
814    protected abstract void acknowledge(ConnectionContext context, final MessageAck ack, final MessageReference node) throws IOException;
815
816
817    public int getMaxProducersToAudit() {
818        return maxProducersToAudit;
819    }
820
821    public void setMaxProducersToAudit(int maxProducersToAudit) {
822        this.maxProducersToAudit = maxProducersToAudit;
823        if (this.pending != null) {
824            this.pending.setMaxProducersToAudit(maxProducersToAudit);
825        }
826    }
827
828    public int getMaxAuditDepth() {
829        return maxAuditDepth;
830    }
831
832    public void setMaxAuditDepth(int maxAuditDepth) {
833        this.maxAuditDepth = maxAuditDepth;
834        if (this.pending != null) {
835            this.pending.setMaxAuditDepth(maxAuditDepth);
836        }
837    }
838
839    @Override
840    public void setPrefetchSize(int prefetchSize) {
841        this.info.setPrefetchSize(prefetchSize);
842        try {
843            this.dispatchPending();
844        } catch (Exception e) {
845            LOG.trace("Caught exception during dispatch after prefetch change.", e);
846        }
847    }
848}