<commit_before>﻿// Copyright 2015-2018 The NATS Authors
// Licensed 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;

// disable XML comment warnings
#pragma warning disable 1591

namespace NATS.Client
{
    /// <summary>
    /// <see cref="AsyncSubscription"/> asynchronously delivers messages to listeners of the <see cref="MessageHandler"/>
    /// event. This class should not be used directly.
    /// </summary>
    /// <remarks>
    /// If the <see cref="AsyncSubscription"/> is created without listening to the <see cref="MessageHandler"/>
    /// event, no messages will be received until <see cref="Start()"/> has been called.
    /// </remarks>
    public sealed class AsyncSubscription : Subscription, IAsyncSubscription, ISubscription
    {
        /// <summary>
        /// Occurs when the <see cref="AsyncSubscription"/> receives a message from the
        /// underlying <see cref="Subscription"/>.
        /// </summary>
        public event EventHandler<MsgHandlerEventArgs> MessageHandler;

        private MsgHandlerEventArgs msgHandlerArgs = new MsgHandlerEventArgs();
        private Task                msgFeeder = null;

        private bool started = false;

        internal AsyncSubscription(Connection conn, string subject, string queue)
            : base(conn, subject, queue)
        {
            mch = conn.getMessageChannel();
            if ((ownsChannel = (mch == null)))
            {
                mch = new Channel<Msg>()
                {
                    Name = subject + (String.IsNullOrWhiteSpace(queue) ? "" : " (queue: " + queue + ")"),
                };
            }
        }

        internal override bool processMsg(Msg msg)
        {
            Connection localConn;
            EventHandler<MsgHandlerEventArgs> localHandler;
            long localMax;
            long d;

            lock (mu)
            {
                if (closed)
                    return false;

                // the message handler has not been setup yet, drop the 
                // message.
                if (MessageHandler == null)
                    return true;

                if (conn == null)
                    return false;

                d = tallyDeliveredMessage(msg);

                localConn = conn;
                localHandler = MessageHandler;
                localMax = max;
            }

            if (localMax <= 0 || d <= localMax)
            {
                msgHandlerArgs.msg = msg;
                try
                {
                    localHandler(this, msgHandlerArgs);
                }
                catch (Exception) { }

                if (d == max)
                {
                    unsubscribe(false);<commit_msg>Fix for #210 - race condition in case of concurrent requests<commit_after>﻿// Copyright 2015-2018 The NATS Authors
// Licensed 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;

// disable XML comment warnings
#pragma warning disable 1591

namespace NATS.Client
{
    /// <summary>
    /// <see cref="AsyncSubscription"/> asynchronously delivers messages to listeners of the <see cref="MessageHandler"/>
    /// event. This class should not be used directly.
    /// </summary>
    /// <remarks>
    /// If the <see cref="AsyncSubscription"/> is created without listening to the <see cref="MessageHandler"/>
    /// event, no messages will be received until <see cref="Start()"/> has been called.
    /// </remarks>
    public sealed class AsyncSubscription : Subscription, IAsyncSubscription, ISubscription
    {
        /// <summary>
        /// Occurs when the <see cref="AsyncSubscription"/> receives a message from the
        /// underlying <see cref="Subscription"/>.
        /// </summary>
        public event EventHandler<MsgHandlerEventArgs> MessageHandler;

        private Task                msgFeeder = null;

        private bool started = false;

        internal AsyncSubscription(Connection conn, string subject, string queue)
            : base(conn, subject, queue)
        {
            mch = conn.getMessageChannel();
            if ((ownsChannel = (mch == null)))
            {
                mch = new Channel<Msg>()
                {
                    Name = subject + (String.IsNullOrWhiteSpace(queue) ? "" : " (queue: " + queue + ")"),
                };
            }
        }

        internal override bool processMsg(Msg msg)
        {
            Connection localConn;
            EventHandler<MsgHandlerEventArgs> localHandler;
            long localMax;
            long d;

            lock (mu)
            {
                if (closed)
                    return false;

                // the message handler has not been setup yet, drop the 
                // message.
                if (MessageHandler == null)
                    return true;

                if (conn == null)
                    return false;

                d = tallyDeliveredMessage(msg);

                localConn = conn;
                localHandler = MessageHandler;
                localMax = max;
            }

            if (localMax <= 0 || d <= localMax)
            {
                try
                {
                    if (localHandler != null)
                    {
                        var msgHandlerEventArgs = new MsgHandlerEventArgs();
                        msgHandlerEventArgs.msg = msg;

                        localHandler(this, msgHandlerEventArgs);
                    }
                }
                catch (Exception) { }

                if (d == max)
                {
                    unsubscribe(false);
{'fraction_non_alphanumeric': 0.09291835814163284, 'fraction_numerical': 0.005563073222071869, 'mean_word_length': 1.6334125098970704, 'pattern_counts': {'":': 0, '<': 39, '<?xml version=': 0, '>': 35, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6851048', 'n_tokens_mistral': 1597, 'n_tokens_neox': 1506, 'n_words': 554}