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                            onDispatch(node, node.getMessage());
178                        }
179                        return;
180                    }
181                }
182            } finally {
183                pending.release();
184            }
185        }
186        throw new JMSException(
187                "Slave broker out of sync with master: Dispatched message ("
188                        + mdn.getMessageId() + ") was not in the pending list for "
189                        + mdn.getConsumerId() + " on " + mdn.getDestination().getPhysicalName());
190    }
191
192    @Override
193    public final void acknowledge(final ConnectionContext context,final MessageAck ack) throws Exception {
194        // Handle the standard acknowledgment case.
195        boolean callDispatchMatched = false;
196        Destination destination = null;
197
198        if (!okForAckAsDispatchDone.await(0l, TimeUnit.MILLISECONDS)) {
199            // suppress unexpected ack exception in this expected case
200            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);
201            return;
202        }
203
204        LOG.trace("ack: {}", ack);
205
206        synchronized(dispatchLock) {
207            if (ack.isStandardAck()) {
208                // First check if the ack matches the dispatched. When using failover this might
209                // not be the case. We don't ever want to ack the wrong messages.
210                assertAckMatchesDispatched(ack);
211
212                // Acknowledge all dispatched messages up till the message id of
213                // the acknowledgment.
214                boolean inAckRange = false;
215                List<MessageReference> removeList = new ArrayList<MessageReference>();
216                for (final MessageReference node : dispatched) {
217                    MessageId messageId = node.getMessageId();
218                    if (ack.getFirstMessageId() == null
219                            || ack.getFirstMessageId().equals(messageId)) {
220                        inAckRange = true;
221                    }
222                    if (inAckRange) {
223                        // Don't remove the nodes until we are committed.
224                        if (!context.isInTransaction()) {
225                            getSubscriptionStatistics().getDequeues().increment();
226                            removeList.add(node);
227                            contractPrefetchExtension(1);
228                        } else {
229                            registerRemoveSync(context, node);
230                        }
231                        acknowledge(context, ack, node);
232                        if (ack.getLastMessageId().equals(messageId)) {
233                            destination = (Destination) node.getRegionDestination();
234                            callDispatchMatched = true;
235                            break;
236                        }
237                    }
238                }
239                for (final MessageReference node : removeList) {
240                    dispatched.remove(node);
241                    decrementPrefetchCounter(node);
242                }
243                // this only happens after a reconnect - get an ack which is not
244                // valid
245                if (!callDispatchMatched) {
246                    LOG.warn("Could not correlate acknowledgment with dispatched message: {}", ack);
247                }
248            } else if (ack.isIndividualAck()) {
249                // Message was delivered and acknowledge - but only delete the
250                // individual message
251                for (final MessageReference node : dispatched) {
252                    MessageId messageId = node.getMessageId();
253                    if (ack.getLastMessageId().equals(messageId)) {
254                        // Don't remove the nodes until we are committed - immediateAck option
255                        if (!context.isInTransaction()) {
256                            getSubscriptionStatistics().getDequeues().increment();
257                            dispatched.remove(node);
258                            decrementPrefetchCounter(node);
259                            contractPrefetchExtension(1);
260                        } else {
261                            registerRemoveSync(context, node);
262                            expandPrefetchExtension(1);
263                        }
264                        acknowledge(context, ack, node);
265                        destination = (Destination) node.getRegionDestination();
266                        callDispatchMatched = true;
267                        break;
268                    }
269                }
270            } else if (ack.isDeliveredAck()) {
271                // Message was delivered but not acknowledged: update pre-fetch
272                // counters.
273                int index = 0;
274                for (Iterator<MessageReference> iter = dispatched.iterator(); iter.hasNext(); index++) {
275                    final MessageReference node = iter.next();
276                    Destination nodeDest = (Destination) node.getRegionDestination();
277                    if (ack.getLastMessageId().equals(node.getMessageId())) {
278                        expandPrefetchExtension(ack.getMessageCount());
279                        destination = nodeDest;
280                        callDispatchMatched = true;
281                        break;
282                    }
283                }
284                if (!callDispatchMatched) {
285                    throw new JMSException(
286                            "Could not correlate acknowledgment with dispatched message: "
287                                    + ack);
288                }
289            } else if (ack.isExpiredAck()) {
290                // Message was expired
291                int index = 0;
292                boolean inAckRange = false;
293                for (Iterator<MessageReference> iter = dispatched.iterator(); iter.hasNext(); index++) {
294                    final MessageReference node = iter.next();
295                    Destination nodeDest = (Destination) node.getRegionDestination();
296                    MessageId messageId = node.getMessageId();
297                    if (ack.getFirstMessageId() == null || ack.getFirstMessageId().equals(messageId)) {
298                        inAckRange = true;
299                    }
300                    if (inAckRange) {
301                        Destination regionDestination = nodeDest;
302                        if (broker.isExpired(node)) {
303                            regionDestination.messageExpired(context, this, node);
304                        }
305                        iter.remove();
306                        decrementPrefetchCounter(node);
307
308                        if (ack.getLastMessageId().equals(messageId)) {
309                            contractPrefetchExtension(1);
310                            destination = (Destination) node.getRegionDestination();
311                            callDispatchMatched = true;
312                            break;
313                        }
314                    }
315                }
316                if (!callDispatchMatched) {
317                    throw new JMSException(
318                            "Could not correlate expiration acknowledgment with dispatched message: "
319                                    + ack);
320                }
321            } else if (ack.isRedeliveredAck()) {
322                // Message was re-delivered but it was not yet considered to be
323                // a DLQ message.
324                boolean inAckRange = false;
325                for (final MessageReference node : dispatched) {
326                    MessageId messageId = node.getMessageId();
327                    if (ack.getFirstMessageId() == null
328                            || ack.getFirstMessageId().equals(messageId)) {
329                        inAckRange = true;
330                    }
331                    if (inAckRange) {
332                        if (ack.getLastMessageId().equals(messageId)) {
333                            destination = (Destination) node.getRegionDestination();
334                            callDispatchMatched = true;
335                            break;
336                        }
337                    }
338                }
339                if (!callDispatchMatched) {
340                    throw new JMSException(
341                            "Could not correlate acknowledgment with dispatched message: "
342                                    + ack);
343                }
344            } else if (ack.isPoisonAck()) {
345                // TODO: what if the message is already in a DLQ???
346                // Handle the poison ACK case: we need to send the message to a
347                // DLQ
348                if (ack.isInTransaction()) {
349                    throw new JMSException("Poison ack cannot be transacted: "
350                            + ack);
351                }
352                int index = 0;
353                boolean inAckRange = false;
354                List<MessageReference> removeList = new ArrayList<MessageReference>();
355                for (final MessageReference node : dispatched) {
356                    MessageId messageId = node.getMessageId();
357                    if (ack.getFirstMessageId() == null
358                            || ack.getFirstMessageId().equals(messageId)) {
359                        inAckRange = true;
360                    }
361                    if (inAckRange) {
362                        sendToDLQ(context, node, ack.getPoisonCause());
363                        Destination nodeDest = (Destination) node.getRegionDestination();
364                        removeList.add(node);
365                        getSubscriptionStatistics().getDequeues().increment();
366                        index++;
367                        acknowledge(context, ack, node);
368                        if (ack.getLastMessageId().equals(messageId)) {
369                            contractPrefetchExtension(1);
370                            destination = nodeDest;
371                            callDispatchMatched = true;
372                            break;
373                        }
374                    }
375                }
376                for (final MessageReference node : removeList) {
377                    dispatched.remove(node);
378                    decrementPrefetchCounter(node);
379                }
380                if (!callDispatchMatched) {
381                    throw new JMSException(
382                            "Could not correlate acknowledgment with dispatched message: "
383                                    + ack);
384                }
385            }
386        }
387        if (callDispatchMatched && destination != null) {
388            destination.wakeup();
389            dispatchPending();
390
391            if (pending.isEmpty()) {
392                wakeupDestinationsForDispatch();
393            }
394        } else {
395            LOG.debug("Acknowledgment out of sync (Normally occurs when failover connection reconnects): {}", ack);
396        }
397    }
398
399    private void registerRemoveSync(ConnectionContext context, final MessageReference node) {
400        // setup a Synchronization to remove nodes from the
401        // dispatched list.
402        context.getTransaction().addSynchronization(
403                new Synchronization() {
404
405                    @Override
406                    public void afterCommit()
407                            throws Exception {
408                        Destination nodeDest = (Destination) node.getRegionDestination();
409                        synchronized (dispatchLock) {
410                            getSubscriptionStatistics().getDequeues().increment();
411                            dispatched.remove(node);
412                            decrementPrefetchCounter(node);
413                        }
414                        contractPrefetchExtension(1);
415                        nodeDest.wakeup();
416                        dispatchPending();
417                    }
418
419                    @Override
420                    public void afterRollback() throws Exception {
421                        contractPrefetchExtension(1);
422                    }
423                });
424    }
425
426    /**
427     * Checks an ack versus the contents of the dispatched list.
428     *  called with dispatchLock held
429     * @param ack
430     * @throws JMSException if it does not match
431     */
432    protected void assertAckMatchesDispatched(MessageAck ack) throws JMSException {
433        MessageId firstAckedMsg = ack.getFirstMessageId();
434        MessageId lastAckedMsg = ack.getLastMessageId();
435        int checkCount = 0;
436        boolean checkFoundStart = false;
437        boolean checkFoundEnd = false;
438        for (MessageReference node : dispatched) {
439
440            if (firstAckedMsg == null) {
441                checkFoundStart = true;
442            } else if (!checkFoundStart && firstAckedMsg.equals(node.getMessageId())) {
443                checkFoundStart = true;
444            }
445
446            if (checkFoundStart) {
447                checkCount++;
448            }
449
450            if (lastAckedMsg != null && lastAckedMsg.equals(node.getMessageId())) {
451                checkFoundEnd = true;
452                break;
453            }
454        }
455        if (!checkFoundStart && firstAckedMsg != null)
456            throw new JMSException("Unmatched acknowledge: " + ack
457                    + "; Could not find Message-ID " + firstAckedMsg
458                    + " in dispatched-list (start of ack)");
459        if (!checkFoundEnd && lastAckedMsg != null)
460            throw new JMSException("Unmatched acknowledge: " + ack
461                    + "; Could not find Message-ID " + lastAckedMsg
462                    + " in dispatched-list (end of ack)");
463        if (ack.getMessageCount() != checkCount && !ack.isInTransaction()) {
464            throw new JMSException("Unmatched acknowledge: " + ack
465                    + "; Expected message count (" + ack.getMessageCount()
466                    + ") differs from count in dispatched-list (" + checkCount
467                    + ")");
468        }
469    }
470
471    /**
472     *
473     * @param context
474     * @param node
475     * @param poisonCause
476     * @throws IOException
477     * @throws Exception
478     */
479    protected void sendToDLQ(final ConnectionContext context, final MessageReference node, Throwable poisonCause) throws IOException, Exception {
480        broker.getRoot().sendToDeadLetterQueue(context, node, this, poisonCause);
481    }
482
483    @Override
484    public int getInFlightSize() {
485        return dispatched.size();
486    }
487
488    /**
489     * Used to determine if the broker can dispatch to the consumer.
490     *
491     * @return true if the subscription is full
492     */
493    @Override
494    public boolean isFull() {
495        return getPrefetchSize() == 0 ? prefetchExtension.get() == 0 : dispatched.size() - prefetchExtension.get() >= info.getPrefetchSize();
496    }
497
498    /**
499     * @return true when 60% or more room is left for dispatching messages
500     */
501    @Override
502    public boolean isLowWaterMark() {
503        return (dispatched.size() - prefetchExtension.get()) <= (info.getPrefetchSize() * .4);
504    }
505
506    /**
507     * @return true when 10% or less room is left for dispatching messages
508     */
509    @Override
510    public boolean isHighWaterMark() {
511        return (dispatched.size() - prefetchExtension.get()) >= (info.getPrefetchSize() * .9);
512    }
513
514    @Override
515    public int countBeforeFull() {
516        return getPrefetchSize() == 0 ? prefetchExtension.get() : info.getPrefetchSize() + prefetchExtension.get() - dispatched.size();
517    }
518
519    @Override
520    public int getPendingQueueSize() {
521        return pending.size();
522    }
523
524    @Override
525    public long getPendingMessageSize() {
526        return pending.messageSize();
527    }
528
529    @Override
530    public int getDispatchedQueueSize() {
531        return dispatched.size();
532    }
533
534    @Override
535    public long getDequeueCounter() {
536        return getSubscriptionStatistics().getDequeues().getCount();
537    }
538
539    @Override
540    public long getDispatchedCounter() {
541        return getSubscriptionStatistics().getDispatched().getCount();
542    }
543
544    @Override
545    public long getEnqueueCounter() {
546        return getSubscriptionStatistics().getEnqueues().getCount();
547    }
548
549    @Override
550    public boolean isRecoveryRequired() {
551        return pending.isRecoveryRequired();
552    }
553
554    public PendingMessageCursor getPending() {
555        return this.pending;
556    }
557
558    public void setPending(PendingMessageCursor pending) {
559        this.pending = pending;
560        if (this.pending!=null) {
561            this.pending.setSystemUsage(usageManager);
562            this.pending.setMemoryUsageHighWaterMark(getCursorMemoryHighWaterMark());
563        }
564    }
565
566    @Override
567    public void add(ConnectionContext context, Destination destination) throws Exception {
568        synchronized(pendingLock) {
569            super.add(context, destination);
570            pending.add(context, destination);
571        }
572    }
573
574    @Override
575    public List<MessageReference> remove(ConnectionContext context, Destination destination) throws Exception {
576        return remove(context, destination, dispatched);
577    }
578
579    public List<MessageReference> remove(ConnectionContext context, Destination destination, List<MessageReference> dispatched) throws Exception {
580        LinkedList<MessageReference> redispatch = new LinkedList<MessageReference>();
581        synchronized(pendingLock) {
582            super.remove(context, destination);
583            // Here is a potential problem concerning Inflight stat:
584            // Messages not already committed or rolled back may not be removed from dispatched list at the moment
585            // Except if each commit or rollback callback action comes before remove of subscriber.
586            redispatch.addAll(pending.remove(context, destination));
587
588            if (dispatched == null) {
589                return redispatch;
590            }
591
592            // Synchronized to DispatchLock if necessary
593            if (dispatched == this.dispatched) {
594                synchronized(dispatchLock) {
595                    addReferencesAndUpdateRedispatch(redispatch, destination, dispatched);
596                }
597            } else {
598                addReferencesAndUpdateRedispatch(redispatch, destination, dispatched);
599            }
600        }
601
602        return redispatch;
603    }
604
605    private void addReferencesAndUpdateRedispatch(LinkedList<MessageReference> redispatch, Destination destination, List<MessageReference> dispatched) {
606        ArrayList<MessageReference> references = new ArrayList<MessageReference>();
607        for (MessageReference r : dispatched) {
608            if (r.getRegionDestination() == destination) {
609                references.add(r);
610                getSubscriptionStatistics().getInflightMessageSize().addSize(-r.getSize());
611            }
612        }
613        redispatch.addAll(0, references);
614        destination.getDestinationStatistics().getInflight().subtract(references.size());
615        dispatched.removeAll(references);
616    }
617
618    // made public so it can be used in MQTTProtocolConverter
619    public void dispatchPending() throws IOException {
620        List<Destination> slowConsumerTargets = null;
621
622        synchronized(pendingLock) {
623            try {
624                int numberToDispatch = countBeforeFull();
625                if (numberToDispatch > 0) {
626                    setSlowConsumer(false);
627                    setPendingBatchSize(pending, numberToDispatch);
628                    int count = 0;
629                    pending.reset();
630                    while (count < numberToDispatch && !isFull() && pending.hasNext()) {
631                        MessageReference node = pending.next();
632                        if (node == null) {
633                            break;
634                        }
635
636                        // Synchronize between dispatched list and remove of message from pending list
637                        // related to remove subscription action
638                        synchronized(dispatchLock) {
639                            pending.remove();
640                            if (!isDropped(node) && canDispatch(node)) {
641
642                                // Message may have been sitting in the pending
643                                // list a while waiting for the consumer to ak the message.
644                                if (node != QueueMessageReference.NULL_MESSAGE && node.isExpired()) {
645                                    //increment number to dispatch
646                                    numberToDispatch++;
647                                    if (broker.isExpired(node)) {
648                                        ((Destination)node.getRegionDestination()).messageExpired(context, this, node);
649                                    }
650
651                                    if (!isBrowser()) {
652                                        node.decrementReferenceCount();
653                                        continue;
654                                    }
655                                }
656                                dispatch(node);
657                                count++;
658                            }
659                        }
660                        // decrement after dispatch has taken ownership to avoid usage jitter
661                        node.decrementReferenceCount();
662                    }
663                } else if (!isSlowConsumer()) {
664                    setSlowConsumer(true);
665                    slowConsumerTargets = destinations;
666                }
667            } finally {
668                pending.release();
669            }
670        }
671
672        if (slowConsumerTargets != null) {
673            for (Destination dest : slowConsumerTargets) {
674                dest.slowConsumer(context, this);
675            }
676        }
677    }
678
679    protected void setPendingBatchSize(PendingMessageCursor pending, int numberToDispatch) {
680        pending.setMaxBatchSize(numberToDispatch);
681    }
682
683    // called with dispatchLock held
684    protected boolean dispatch(final MessageReference node) throws IOException {
685        final Message message = node.getMessage();
686        if (message == null) {
687            return false;
688        }
689
690        okForAckAsDispatchDone.countDown();
691
692        MessageDispatch md = createMessageDispatch(node, message);
693        if (node != QueueMessageReference.NULL_MESSAGE) {
694            dispatched.add(node);
695            getSubscriptionStatistics().getDispatched().increment();
696        }
697        if (getPrefetchSize() == 0) {
698            while (true) {
699                int currentExtension = prefetchExtension.get();
700                int newExtension = Math.max(0, currentExtension - 1);
701                if (prefetchExtension.compareAndSet(currentExtension, newExtension)) {
702                    break;
703                }
704            }
705        }
706        if (info.isDispatchAsync()) {
707            md.setTransmitCallback(new TransmitCallback() {
708
709                @Override
710                public void onSuccess() {
711                    // Since the message gets queued up in async dispatch, we don't want to
712                    // decrease the reference count until it gets put on the wire.
713                    onDispatch(node, message);
714                }
715
716                @Override
717                public void onFailure() {
718                    Destination nodeDest = (Destination) node.getRegionDestination();
719                    if (nodeDest != null) {
720                        if (node != QueueMessageReference.NULL_MESSAGE) {
721                            nodeDest.getDestinationStatistics().getDispatched().increment();
722                            incrementPrefetchCounter(node);
723                            LOG.trace("{} failed to dispatch: {} - {}, dispatched: {}, inflight: {}",
724                                    info.getConsumerId(), message.getMessageId(), message.getDestination(),
725                                    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                incrementPrefetchCounter(node);
747                LOG.trace("{} dispatched: {} - {}, dispatched: {}, inflight: {}",
748                        info.getConsumerId(), message.getMessageId(), message.getDestination(),
749                        getSubscriptionStatistics().getDispatched().getCount(), dispatched.size());
750            }
751        }
752
753        if (info.isDispatchAsync()) {
754            try {
755                dispatchPending();
756            } catch (IOException e) {
757                context.getConnection().serviceExceptionAsync(e);
758            }
759        }
760    }
761
762    /**
763     * inform the MessageConsumer on the client to change it's prefetch
764     *
765     * @param newPrefetch
766     */
767    @Override
768    public void updateConsumerPrefetch(int newPrefetch) {
769        if (context != null && context.getConnection() != null && context.getConnection().isManageable()) {
770            ConsumerControl cc = new ConsumerControl();
771            cc.setConsumerId(info.getConsumerId());
772            cc.setPrefetch(newPrefetch);
773            context.getConnection().dispatchAsync(cc);
774        }
775    }
776
777    /**
778     * @param node
779     * @param message
780     * @return MessageDispatch
781     */
782    protected MessageDispatch createMessageDispatch(MessageReference node, Message message) {
783        MessageDispatch md = new MessageDispatch();
784        md.setConsumerId(info.getConsumerId());
785
786        if (node == QueueMessageReference.NULL_MESSAGE) {
787            md.setMessage(null);
788            md.setDestination(null);
789        } else {
790            Destination regionDestination = (Destination) node.getRegionDestination();
791            md.setDestination(regionDestination.getActiveMQDestination());
792            md.setMessage(message);
793            md.setRedeliveryCounter(node.getRedeliveryCounter());
794        }
795
796        return md;
797    }
798
799    /**
800     * Use when a matched message is about to be dispatched to the client.
801     *
802     * @param node
803     * @return false if the message should not be dispatched to the client
804     *         (another sub may have already dispatched it for example).
805     * @throws IOException
806     */
807    protected abstract boolean canDispatch(MessageReference node) throws IOException;
808
809    protected abstract boolean isDropped(MessageReference node);
810
811    /**
812     * Used during acknowledgment to remove the message.
813     *
814     * @throws IOException
815     */
816    protected abstract void acknowledge(ConnectionContext context, final MessageAck ack, final MessageReference node) throws IOException;
817
818
819    public int getMaxProducersToAudit() {
820        return maxProducersToAudit;
821    }
822
823    public void setMaxProducersToAudit(int maxProducersToAudit) {
824        this.maxProducersToAudit = maxProducersToAudit;
825        if (this.pending != null) {
826            this.pending.setMaxProducersToAudit(maxProducersToAudit);
827        }
828    }
829
830    public int getMaxAuditDepth() {
831        return maxAuditDepth;
832    }
833
834    public void setMaxAuditDepth(int maxAuditDepth) {
835        this.maxAuditDepth = maxAuditDepth;
836        if (this.pending != null) {
837            this.pending.setMaxAuditDepth(maxAuditDepth);
838        }
839    }
840
841    @Override
842    public void setPrefetchSize(int prefetchSize) {
843        this.info.setPrefetchSize(prefetchSize);
844        try {
845            this.dispatchPending();
846        } catch (Exception e) {
847            LOG.trace("Caught exception during dispatch after prefetch change.", e);
848        }
849    }
850
851    private void incrementPrefetchCounter(final MessageReference node) {
852        ((Destination)node.getRegionDestination()).getDestinationStatistics().getInflight().increment();
853        getSubscriptionStatistics().getInflightMessageSize().addSize(node.getSize());
854    }
855
856    private void decrementPrefetchCounter(final MessageReference node) {
857        ((Destination)node.getRegionDestination()).getDestinationStatistics().getInflight().decrement();
858        getSubscriptionStatistics().getInflightMessageSize().addSize(-node.getSize());
859    }
860}