protected override void UnsubscribeFromEventBus()
 {
     eventBus?.TryUnsubscribe(newBlockDiscoveredSubscription);
     newBlockDiscoveredSubscription = null;
     eventBus?.TryUnsubscribe(newBlockAvailableInDBSubscription);
     newBlockAvailableInDBSubscription = null;
 }
 protected override void UnsubscribeFromEventBus()
 {
     eventBus?.TryUnsubscribe(nodeAddedSubscription);
     nodeAddedSubscription = null;
     eventBus?.TryUnsubscribe(nodeDeletedSubscription);
     nodeDeletedSubscription = null;
 }
Beispiel #3
0
        public async Task WaitForEventBusEventAsync <T>(EventBusSubscription <T> subscription, string description, Func <T, bool> predicate) where T : IntegrationEvent
        {
            try
            {
                do
                {
                    var evt = await subscription.ReadAsync(new CancellationTokenSource(5_000).Token);

                    if (predicate(evt))
                    {
                        break;
                    }

                    loggerTest.LogInformation($"Got notification event {evt}, but is not the one that we are looking for");
                } while (true);
            }
            catch (OperationCanceledException)
            {
                string msg = $"Timeout out while waiting for integration event {typeof(T).Name}. {description}";
                loggerTest.LogInformation(msg);
                throw new Exception(msg);
            }

            loggerTest.LogInformation($"The following wait for event completed successfully: {description}");
        }
Beispiel #4
0
        public async Task DoesntSendDataWhenNoSubscriptionMatchesTheFilter()
        {
            await this.eventBus.Subscribe(EventBusSubscription.Create <Message>(
                                              "testChannel",
                                              "someClientId",
                                              0,
                                              null,
                                              new { },
                                              e => e.Author == "Sam",
                                              operation));

            OnMessageReceivedEventArgs eventArgs = null;

            this.eventBus.OnMessageReceived += async(OnMessageReceivedEventArgs args) =>
            {
                await Task.Yield();

                eventArgs = args;
            };

            await this.eventBus.Publish(new Message()
            {
                Author = "Bob", Content = "stuff"
            }, "testChannel");


            Assert.IsNull(eventArgs);
        }
Beispiel #5
0
        public async Task ShouldReceiveDataDefinedBySubscription()
        {
            await this.eventBus.Subscribe(EventBusSubscription.Create <Message>(
                                              "testChannel",
                                              "someClientId",
                                              0,
                                              null,
                                              new { },
                                              e => e.Author == "Bob",
                                              operation));

            OnMessageReceivedEventArgs eventArgs = null;

            this.eventBus.OnMessageReceived += async(OnMessageReceivedEventArgs args) =>
            {
                await Task.Yield();

                eventArgs = args;
            };

            await this.eventBus.Publish(new Message()
            {
                Author = "Bob", Content = "stuff"
            }, "testChannel");


            Assert.AreEqual("testChannel", eventArgs.Channel);
        }
Beispiel #6
0
        private async Task RegisterSubscription(
            GraphQLFieldSelection fieldSelection,
            GraphQLSubscriptionType type,
            GraphQLDocument document,
            FieldScope scope)
        {
            var fieldInfo = type.GetFieldInfo(fieldSelection.Name.Value) as GraphQLSubscriptionTypeFieldInfo;

            Expression <Func <object, bool> > filter = null;

            if (fieldInfo.Filter != null)
            {
                filter = entity => (bool)scope.InvokeWithArgumentsSync(
                    fieldSelection.Arguments.ToList(), fieldInfo.Filter, entity);
            }

            await type.EventBus.Subscribe(EventBusSubscription.Create(
                                              fieldInfo.Channel,
                                              this.clientId,
                                              this.subscriptionId.Value,
                                              this.Operation?.Name?.Value ?? "Anonymous",
                                              this.variables,
                                              filter,
                                              this.ast));
        }
Beispiel #7
0
        public virtual void TestInitialize()
        {
            Initialize(mockedServices: false);

            var bitcoindConfigKey = "BitcoindFullPath";

            bitcoindFullPath = Configuration[bitcoindConfigKey];
            if (string.IsNullOrEmpty(bitcoindFullPath))
            {
                throw new Exception($"Required parameter {bitcoindConfigKey} is missing from configuration");
            }

            var alternativeIp = Configuration["HostIp"];

            if (!string.IsNullOrEmpty(alternativeIp))
            {
                hostIp = alternativeIp;
            }

            bool skipNodeStart = GetType().GetMethod(TestContext.TestName).GetCustomAttributes(true).Any(a => a.GetType() == typeof(SkipNodeStartAttribute));

            if (!skipNodeStart)
            {
                zmqSubscribedEventSubscription = eventBus.Subscribe <ZMQSubscribedEvent>();
                node0      = CreateAndStartNode(0);
                _          = zmqSubscribedEventSubscription.ReadAsync(CancellationToken.None).Result;
                rpcClient0 = node0.RpcClient;
                SetupChain(rpcClient0);
            }
        }
        protected override void SubscribeToEventBus(CancellationToken stoppingToken)
        {
            newBlockDiscoveredSubscription    = eventBus.Subscribe <NewBlockDiscoveredEvent>();
            newBlockAvailableInDBSubscription = eventBus.Subscribe <NewBlockAvailableInDB>();

            _ = newBlockDiscoveredSubscription.ProcessEventsAsync(stoppingToken, logger, NewBlockDiscoveredAsync);
            _ = newBlockAvailableInDBSubscription.ProcessEventsAsync(stoppingToken, logger, ParseBlockForTransactionsAsync);
        }
 protected override void SubscribeToEventBus(CancellationToken stoppingToken)
 {
     // subscribe to node events
     nodeAddedSubscription   = eventBus.Subscribe <NodeAddedEvent>();
     nodeDeletedSubscription = eventBus.Subscribe <NodeDeletedEvent>();
     _ = nodeAddedSubscription.ProcessEventsAsync(stoppingToken, logger, NodeRepositoryNodeAddedAsync);
     _ = nodeDeletedSubscription.ProcessEventsAsync(stoppingToken, logger, NodeRepositoryDeletedEventAsync);
 }
        protected override void UnsubscribeFromEventBus()
        {
            eventBus?.TryUnsubscribe(invalidTxDetectedSubscription);
            invalidTxDetectedSubscription = null;

            eventBus?.TryUnsubscribe(removedFromMempoolSubscription);
            removedFromMempoolSubscription = null;
        }
        protected override void SubscribeToEventBus(CancellationToken stoppingToken)
        {
            invalidTxDetectedSubscription  = eventBus.Subscribe <InvalidTxDetectedEvent>();
            removedFromMempoolSubscription = eventBus.Subscribe <RemovedFromMempoolEvent>();

            _ = invalidTxDetectedSubscription.ProcessEventsAsync(stoppingToken, logger, InvalidTxDetectedAsync);
            _ = removedFromMempoolSubscription.ProcessEventsAsync(stoppingToken, logger, RemovedFromMempoolEventAsync);
        }
        public void Subscribe(EventBusSubscription eventBusSubscription)
        {
            if (eventBusSubscription != null)
            {
                _logger.LogInformation($"Subscribing event {eventBusSubscription.SubscriptionEventName}");

                StartBasicConsume();
                DoInternalSubscription(eventBusSubscription);
            }
        }
        private void DoInternalSubscription(EventBusSubscription subscription)
        {
            _eventBusConnection.EnsureConnection();

            using (var channel = _eventBusConnection.CreateModel())
            {
                var args = new Dictionary <string, object>();

                channel.QueueBind(
                    queue: _queueName,
                    exchange: _exchangeName,
                    routingKey: subscription.SubscriptionEventName,
                    args);
            }
        }
Beispiel #14
0
 private void HandleMessage(
     EventBusSubscription eventBusSubscription,
     ReplyEventBusRequest <int, int> busRequest,
     int messageCount)
 {
     Assertions.AssertTrue(!busRequest.IsError(), "not error message");
     if (messageCount > 5)
     {
         busRequest.ErrorReply("test error", 2);
         eventBusSubscription.Stop();
     }
     else
     {
         busRequest.Reply(busRequest.Content + 1);
     }
 }
 internal async Task DisableSubscriptionAsync(EventBusSubscription subscription)
 {
     _logger.LogDebug("Disabling subscription: {0}", subscription.Name);
     if (_subscriptions.Remove(subscription.Name) && IsConnectionOpen)
     {
         try {
             await SendMessageAsync(new UnsubscribeAction {
                 Rule = subscription.Name
             });
         } catch (InvalidOperationException) {
             // websocket is not connected; ignore error
         } catch (Exception e) {
             // nothing to do
             _logger.LogDebug("Deactivating subscription FAILED: {0}\n{1}", subscription.Name, e);
         }
     }
 }
Beispiel #16
0
        public async Task Test()
        {
            var messageCount1 = 0;

            _subscription1 = this.MessageEndpoint <int, int>(EventBusMessageTest.ConsumerAddress1, message =>
            {
                messageCount1++;
                HandleMessage(_subscription1, message, messageCount1);
            });
            var messageCount2 = 0;

            _subscription2 = this.MessageEndpoint <int, int>(EventBusMessageTest.ConsumerAddress2, message =>
            {
                messageCount2++;
                HandleMessage(_subscription2, message, messageCount2);
            });
        }
        internal async Task EnableSubscriptionAsync(EventBusSubscription subscription)
        {
            _logger.LogDebug("Enabling subscription: {0}", subscription.Name);
            if (IsConnectionOpen)
            {
                try {
                    await SendMessageAndWaitForAcknowledgeAsync(new SubscribeAction {
                        Rule    = subscription.Name,
                        Pattern = subscription.Pattern
                    });
                } catch (InvalidOperationException) {
                    // websocket is not connected; ignore error
                } catch (Exception e) {
                    _logger.LogDebug("Activating subscription FAILED: {0}\n{1}", subscription.Name, e);
                    subscription.Status = EventBusSubscriptionStatus.Error;

                    // subscription failed
                    SubscriptionError?.Invoke(this, new EventBusSubscriptErrorEventArgs(subscription, e));
                }
            }
        }
Beispiel #18
0
        public async Task IgnoresMultipleSameSubscriptions()
        {
            await this.eventBus.Subscribe(EventBusSubscription.Create <Message>(
                                              "testChannel",
                                              "someClientId",
                                              0,
                                              null,
                                              new { },
                                              e => e.Author == "Sam",
                                              operation));

            await this.eventBus.Subscribe(EventBusSubscription.Create <Message>(
                                              "testChannel",
                                              "someClientId",
                                              0,
                                              null,
                                              new { },
                                              e => e.Author == "Sam",
                                              operation));

            List <string> clientIds = new List <string>();

            this.eventBus.OnMessageReceived += async(OnMessageReceivedEventArgs args) =>
            {
                await Task.Yield();

                clientIds.Add(args.ClientId);
            };

            await this.eventBus.Publish(new Message()
            {
                Author = "Sam", Content = "stuff"
            }, "testChannel");


            Assert.AreEqual(1, clientIds.Count);
        }
        /// <summary>
        /// The <see cref="SubscribeTo{T}(string,LambdaSharp.App.EventBus.EventBusPattern,Action{IEventBusSubscription,CloudWatchEvent{T}})"/> method creates a subscription for the specified source and type.
        /// </summary>
        /// <param name="name">The name of the LambdaSharp App EventBus subscription.</param>
        /// <param name="eventPattern"></param>
        /// <param name="callback">The callback to invoke when a matching event is received.</param>
        /// <typeparam name="T">The event payload type.</typeparam>
        /// <returns>The subscription instance.</returns>
        public IEventBusSubscription SubscribeTo <T>(string name, EventBusPattern eventPattern, Action <IEventBusSubscription, CloudWatchEvent <T> > callback)
        {
            if (name is null)
            {
                throw new ArgumentNullException(nameof(name));
            }
            if (eventPattern is null)
            {
                throw new ArgumentNullException(nameof(eventPattern));
            }
            if (callback is null)
            {
                throw new ArgumentNullException(nameof(callback));
            }

            // register subscription
            var subscription = new EventBusSubscription(
                name,
                JsonSerializer.Serialize(eventPattern),
                (callbackSubscription, cloudWatchEventJson) => {
                try {
                    // deserialize received event
                    callback?.Invoke(callbackSubscription, JsonSerializer.Deserialize <CloudWatchEvent <T> >(cloudWatchEventJson));
                } catch (Exception e) {
                    _logger.LogError(e, "Callback for rule '{0}' failed", name);
                }
            },
                this
                );

            _subscriptions[name] = subscription;

            // kick off subscription, but don't wait for response
            _ = subscription.EnableSubscriptionAsync();
            return(subscription);
        }
 protected override void SubscribeToEventBus(CancellationToken stoppingToken)
 {
     newNotificationEventSubscription = eventBus.Subscribe <NewNotificationEvent>();
     _ = newNotificationEventSubscription.ProcessEventsAsync(stoppingToken, logger, ProcessNotificationAsync);
 }
 protected override void UnsubscribeFromEventBus()
 {
     eventBus?.TryUnsubscribe(newNotificationEventSubscription);
     newNotificationEventSubscription = null;
 }
        protected override void SubscribeToEventBus(CancellationToken stoppingToken)
        {
            newBlockDiscoveredSubscription = eventBus.Subscribe <NewBlockDiscoveredEvent>();

            _ = newBlockDiscoveredSubscription.ProcessEventsAsync(stoppingToken, logger, NewBlockDiscoveredAsync);
        }