Ejemplo n.º 1
0
        /// <summary>
        /// Subscribes a message handler to the bus, which is disconnected after the message
        /// is received.
        /// </summary>
        /// <typeparam name="T">The message type</typeparam>
        /// <param name="filter">A filter that only completes the task if filter is true</param>
        /// <returns>An awaitable task completed when the message is received</returns>
        public Task <ConsumeContext <T> > SubscribeHandler <T>(Func <ConsumeContext <T>, bool> filter)
            where T : class
        {
            TaskCompletionSource <ConsumeContext <T> > source = TaskUtil.GetTask <ConsumeContext <T> >();

            ConnectHandle handler = null;

            handler = Bus.ConnectHandler <T>(async context =>
            {
                if (filter(context))
                {
                    handler.Disconnect();

                    source.SetResult(context);
                }
            });

            TestCancelledTask.ContinueWith(x =>
            {
                handler.Disconnect();

                source.TrySetCanceled();
            }, TaskContinuationOptions.OnlyOnCanceled);

            return(source.Task);
        }
        public AsyncInactivityObserver(TimeSpan timeout, CancellationToken cancellationToken)
        {
            _inactivityTaskSource = TaskUtil.GetTask();
            _inactivityTask       = new Lazy <Task>(() => _inactivityTaskSource.Task.OrTimeout(timeout, cancellationToken));

            _inactivityTokenSource = new CancellationTokenSource();
        }
        public MultipleResultRequestContext(TRequest request, IPipe <ResultContext> resultPipe)
        {
            _resultPipe = resultPipe;
            Request     = request;

            _resultTask = TaskUtil.GetTask <Task <ResultContext> >();
        }
                public Observer(IReceiveEndpoint endpoint, CancellationToken cancellationToken)
                {
                    _cancellationToken = cancellationToken;
                    _ready             = TaskUtil.GetTask <ReceiveEndpointReady>();

                    _handle = endpoint.ConnectReceiveEndpointObserver(this);
                }
Ejemplo n.º 5
0
            public async Task Should_support_the_new_syntax()
            {
                ServiceBusTokenProviderSettings settings = new TestAzureServiceBusAccountSettings();
                var serviceBusNamespace = Configuration.ServiceNamespace;

                var serviceUri = AzureServiceBusEndpointUriCreator.Create(
                    serviceBusNamespace,
                    "MassTransit.Azure.ServiceBus.Core.Tests"
                    );

                TaskCompletionSource <A> completed = TaskUtil.GetTask <A>();

                var bus = Bus.Factory.CreateUsingAzureServiceBus(x =>
                {
                    BusTestFixture.ConfigureBusDiagnostics(x);

                    x.Host(serviceUri, h =>
                    {
                        h.SharedAccessSignature(s =>
                        {
                            s.KeyName         = settings.KeyName;
                            s.SharedAccessKey = settings.SharedAccessKey;
                            s.TokenTimeToLive = settings.TokenTimeToLive;
                            s.TokenScope      = settings.TokenScope;
                        });
                    });

                    x.ReceiveEndpoint("input_queue", e =>
                    {
                        e.PrefetchCount = 16;

                        e.Handler <A>(async context => completed.TrySetResult(context.Message));

                        // Add a message handler and configure the pipeline to retry the handler
                        // if an exception is thrown
                        e.Handler <A>(Handle, h =>
                        {
                            h.UseRetry(r => r.Interval(5, 100));
                        });
                    });
                });

                var busHandle = await bus.StartAsync(TestCancellationToken);

                try
                {
                }
                finally
                {
                    await busHandle.StopAsync();
                }

                //                }))
                //                {
                //                    var queueAddress = new Uri(hostAddress, "input_queue");
                //                    ISendEndpoint endpoint = bus.GetSendEndpoint(queueAddress);
                //
                //                    await endpoint.Send(new A());
                //                }
            }
Ejemplo n.º 6
0
        /// <summary>
        /// Creates the Agent
        /// </summary>
        public Agent()
        {
            _ready     = TaskUtil.GetTask();
            _completed = TaskUtil.GetTask();

            _stopped = new Lazy <CancellationTokenSource>(() =>
            {
                var source = new CancellationTokenSource();
                if (_isStopped)
                {
                    source.Cancel();
                }

                return(source);
            });
            _stopping = new Lazy <CancellationTokenSource>(() =>
            {
                var source = new CancellationTokenSource();
                if (_isStopping)
                {
                    source.Cancel();
                }

                return(source);
            });
        }
Ejemplo n.º 7
0
 public PendingConfirmation(ConnectionContext connectionContext, string exchange, ulong publishTag)
 {
     _connectionContext = connectionContext;
     _exchange          = exchange;
     PublishTag         = publishTag;
     _source            = TaskUtil.GetTask <ulong>();
 }
        public SingleResultRequestContext(TRequest request, IPipe <ResultContext <TRequest, TResult> > resultPipe)
        {
            _resultPipe = resultPipe;
            Request     = request;

            _resultTask = TaskUtil.GetTask <Task <ResultContext <TResult> > >();
        }
        public TopologyHandle Connect(IMessageReceiver receiver)
        {
            if (receiver == null)
            {
                throw new ArgumentNullException(nameof(receiver));
            }

            lock (_receivers)
            {
                var id = ++_nextId;

                _receivers.Add(id, receiver);

                IMessageReceiver[] connected = _receivers.Values.ToArray();

                var balancer = connected.Length == 1
                    ? new SingleReceiverLoadBalancer(connected[0])
                    : _balancerFactory(connected);

                if (!_balancer.TrySetResult(balancer))
                {
                    _balancer = TaskUtil.GetTask <IReceiverLoadBalancer>();
                    _balancer.SetResult(balancer);
                }

                return(new Handle(id, this));
            }
        }
        public MessageReceiverCollection(LoadBalancerFactory balancerFactory)
        {
            _balancerFactory = balancerFactory;

            _balancer  = TaskUtil.GetTask <IReceiverLoadBalancer>();
            _receivers = new Dictionary <long, IMessageReceiver>();
        }
Ejemplo n.º 11
0
        /// <summary>
        /// </summary>
        /// <param name="context"></param>
        public PipeContextAgent(Task <TContext> context)
        {
            _context  = context;
            _inactive = TaskUtil.GetTask <DateTime>();

            SetReady(_context);
        }
Ejemplo n.º 12
0
            static Cached()
            {
                var source = TaskUtil.GetTask <TValue>();

                source.TrySetException(new InvalidOperationException("The cached value has been removed"));

                Removed = source.Task;
            }
Ejemplo n.º 13
0
            public ProducingConsumer(TaskCompletionSource <ProducingConsumer> consumerCreated, MyId myId)
            {
                MyId = myId;

                _received = TaskUtil.GetTask <ConsumeContext <SimpleMessageInterface> >();

                consumerCreated.TrySetResult(this);
            }
Ejemplo n.º 14
0
        public ReceiveEndpoint(IReceiveTransport receiveTransport, ReceiveEndpointContext context)
        {
            _context          = context;
            _receiveTransport = receiveTransport;

            _started = TaskUtil.GetTask <ReceiveEndpointReady>();
            _handle  = receiveTransport.ConnectReceiveTransportObserver(new Observer(this, context.EndpointObservers));
        }
Ejemplo n.º 15
0
        public Receiver(ClientContext context, IBrokeredMessageReceiver messageReceiver)
        {
            _context         = context;
            _messageReceiver = messageReceiver;

            Tracker           = new DeliveryTracker(HandleDeliveryComplete);
            _deliveryComplete = TaskUtil.GetTask <bool>();
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Returns a task completion that is automatically canceled when the test is canceled
        /// </summary>
        /// <typeparam name="T">The task type</typeparam>
        /// <returns></returns>
        public TaskCompletionSource <T> GetTask <T>()
        {
            TaskCompletionSource <T> source = TaskUtil.GetTask <T>();

            TestCancelledTask.ContinueWith(x => source.TrySetCanceled(), TaskContinuationOptions.OnlyOnCanceled);

            return(source);
        }
Ejemplo n.º 17
0
        public async Task Should_be_able_to_consume_messages_polymorphically_if_the_receiving_bus_support_the_binary_serializer()
        {
            var consumed = TaskUtil.GetTask <Base>();

            var bus = Bus.Factory.CreateUsingInMemory(x =>
            {
                x.SupportBinaryMessageDeserializer();
                x.UseBinarySerializer();
                x.ReceiveEndpoint("input_queue", configurator =>
                {
                #pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously
                    configurator.Handler <Base>(async ctx =>
                    {
                        consumed.TrySetResult(ctx.Message);
                    });
                #pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously
                });
            });

            await bus.StartAsync();

            try
            {
                // Create a recursive list
                var head = new ListNode {
                    Value = 100
                };
                var tail = new ListNode {
                    Next = head, Value = 200
                };
                head.Next = tail;

                var messageToSend = new Derived()
                {
                    PropBase    = 10,
                    PropDerived = 20,
                    Head        = head
                };

                await bus.Publish(messageToSend);

                var completedTask = await Task.WhenAny(consumed.Task, Task.Delay(250));

                Assert.AreEqual(consumed.Task, completedTask,
                                "Timeout while waiting to receive the message sent on the source bus.");

                var message = await consumed.Task;
                Assert.NotNull(message);
                Assert.AreEqual(messageToSend.PropBase, message.PropBase);
                Assert.AreEqual(head.Value, message.Head.Value);
                Assert.AreEqual(tail.Value, message.Head.Next.Value);
                Assert.AreEqual(head.Value, message.Head.Next.Next.Value);
            }
            finally
            {
                await bus.StopAsync();
            }
        }
Ejemplo n.º 18
0
            public async Task Should_support_the_new_syntax()
            {
                ServiceBusTokenProviderSettings settings = new TestAzureServiceBusAccountSettings();

                Uri serviceUri = ServiceBusEnvironment.CreateServiceUri("sb", Configuration.ServiceNamespace,
                                                                        "MassTransit.AzureServiceBusTransport.Tests");

                var completed = TaskUtil.GetTask <A>();

                IBusControl bus = Bus.Factory.CreateUsingAzureServiceBus(x =>
                {
                    IServiceBusHost host = x.Host(serviceUri, h =>
                    {
                        h.SharedAccessSignature(s =>
                        {
                            s.KeyName         = settings.KeyName;
                            s.SharedAccessKey = settings.SharedAccessKey;
                            s.TokenTimeToLive = settings.TokenTimeToLive;
                            s.TokenScope      = settings.TokenScope;
                        });
                    });

                    x.ReceiveEndpoint(host, "input_queue", e =>
                    {
                        e.PrefetchCount = 16;

                        e.UseExecute(context => Console.WriteLine(
                                         $"Received (input_queue): {context.ReceiveContext.TransportHeaders.Get("MessageId", "N/A")}, Types = ({string.Join(",", context.SupportedMessageTypes)})"));

                        e.Handler <A>(async context => completed.TrySetResult(context.Message));

                        // Add a message handler and configure the pipeline to retry the handler
                        // if an exception is thrown
                        e.Handler <A>(Handle, h =>
                        {
                            h.UseRetry(r => r.Interval(5, 100));
                        });
                    });
                });

                BusHandle busHandle = await bus.StartAsync();

                try
                {
                }
                finally
                {
                    await busHandle.StopAsync();
                }

                //                }))
                //                {
                //                    var queueAddress = new Uri(hostAddress, "input_queue");
                //                    ISendEndpoint endpoint = bus.GetSendEndpoint(queueAddress);
                //
                //                    await endpoint.Send(new A());
                //                }
            }
Ejemplo n.º 19
0
        public HttpConsumer(HttpReceiveEndpointContext context)
        {
            _context = context;

            _tracker          = new DeliveryTracker(OnDeliveryComplete);
            _deliveryComplete = TaskUtil.GetTask <bool>();

            SetReady();
        }
Ejemplo n.º 20
0
        public Receiver(ClientContext context, IBrokeredMessageReceiver messageReceiver)
        {
            _context         = context;
            _messageReceiver = messageReceiver;

            messageReceiver.ZeroActivity += HandleDeliveryComplete;

            _deliveryComplete = TaskUtil.GetTask <bool>();
        }
Ejemplo n.º 21
0
        public SimpleConsumer(ISimpleConsumerDependency dependency)
        {
            _dependency = dependency;
            Console.WriteLine("SimpleConsumer()");

            _received = TaskUtil.GetTask <SimpleMessageInterface>();

            _consumerCreated.TrySetResult(this);
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Creates a node value factory, with the inital pending value
        /// </summary>
        /// <param name="initialPendingValue">The value that brought the node to the cache</param>
        /// <param name="timeoutInMilliseconds">The timeout to wait for additional factories before faulting</param>
        public NodeValueFactory(IPendingValue <TValue> initialPendingValue, int timeoutInMilliseconds)
        {
            _timeout = timeoutInMilliseconds;

            _pendingCollection = new BlockingCollection <IPendingValue <TValue> >();

            _value = TaskUtil.GetTask <TValue>();

            _pendingCollection.Add(initialPendingValue);
        }
Ejemplo n.º 23
0
        public EventHubReceiveEndpoint(EventProcessorClient processor, int prefetch, int concurrencyLimit, BlobContainerClient blobContainerClient,
                                       IEventHubDataReceiver transport, ReceiveEndpointContext context)
        {
            _processor           = processor;
            _blobContainerClient = blobContainerClient;
            _transport           = transport;
            _context             = context;

            _started  = TaskUtil.GetTask <ReceiveEndpointReady>();
            _executor = new ChannelExecutor(prefetch, concurrencyLimit);
        }
Ejemplo n.º 24
0
        public KafkaReceiveEndpoint(string topic, int prefetch, int concurrencyLimit, IConsumer <TKey, TValue> consumer,
                                    IKafkaMessageReceiver <TKey, TValue> transport, ReceiveEndpointContext context)
        {
            _topic     = topic;
            _consumer  = consumer;
            _transport = transport;
            _context   = context;

            _started  = TaskUtil.GetTask <ReceiveEndpointReady>();
            _executor = new ChannelExecutor(prefetch, concurrencyLimit);
        }
Ejemplo n.º 25
0
        public static async Task WithCancellation(this Task task, CancellationToken cancellationToken)
        {
            var tcs = TaskUtil.GetTask <bool>();

            using (cancellationToken.Register(s => ((TaskCompletionSource <bool>)s).TrySetResult(true), tcs))
                if (task != await Task.WhenAny(task, tcs.Task).ConfigureAwait(false))
                {
                    throw new OperationCanceledException(cancellationToken);
                }

            await task.ConfigureAwait(false);
        }
Ejemplo n.º 26
0
        public ConsumePipe(IDynamicFilter <ConsumeContext, Guid> dynamicFilter, IPipe <ConsumeContext> pipe, bool autoStart)
        {
            _dynamicFilter = dynamicFilter ?? throw new ArgumentNullException(nameof(dynamicFilter));
            _pipe          = pipe ?? throw new ArgumentNullException(nameof(pipe));

            _connected = TaskUtil.GetTask <bool>();

            if (autoStart)
            {
                _connected.TrySetResult(true);
            }
        }
Ejemplo n.º 27
0
            public RenewLockScope(BrokeredMessageContext context, TimeSpan delay)
            {
                _context   = context;
                _delay     = delay;
                _source    = new CancellationTokenSource();
                _completed = TaskUtil.GetTask <bool>();

                if (context != null)
                {
                    Task.Factory.StartNew(LockRenewal, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default);
                }
            }
Ejemplo n.º 28
0
        public BatchConsumer(int messageLimit, TimeSpan timeLimit, ChannelExecutor executor, ChannelExecutor dispatcher, IPipe <ConsumeContext <Batch <TMessage> > > consumerPipe)
        {
            _messageLimit = messageLimit;
            _executor     = executor;
            _consumerPipe = consumerPipe;
            _dispatcher   = dispatcher;
            _messages     = new SortedDictionary <Guid, ConsumeContext <TMessage> >();
            _completed    = TaskUtil.GetTask <DateTime>();
            _firstMessage = DateTime.UtcNow;

            _timer = new Timer(TimeLimitExpired, null, timeLimit, TimeSpan.FromMilliseconds(-1));
        }
Ejemplo n.º 29
0
        /// <summary>
        /// The basic consumer receives messages pushed from the broker.
        /// </summary>
        /// <param name="model">The model context for the consumer</param>
        /// <param name="context">The topology</param>
        public RabbitMqBasicConsumer(ModelContext model, RabbitMqReceiveEndpointContext context)
        {
            _model   = model;
            _context = context;

            _tracker = new DeliveryTracker(HandleDeliveryComplete);

            _receiveSettings = model.GetPayload <ReceiveSettings>();

            _pending = new ConcurrentDictionary <ulong, RabbitMqReceiveContext>();

            _deliveryComplete = TaskUtil.GetTask <bool>();
        }
        public AsyncInactivityObserver(TimeSpan timeout, CancellationToken cancellationToken)
        {
            _inactivityTaskSource = TaskUtil.GetTask();
            _inactivityTask       = new Lazy <Task>(() =>
            {
                SetupTimeout(timeout, cancellationToken);

                return(_inactivityTaskSource.Task);
            });

            _sources = new HashSet <IInactivityObservationSource>();
            _inactivityTokenSource = new CancellationTokenSource();
        }