Exemplo n.º 1
0
        public async Task SubscribeAsync(Func <PunchyMessage, Task> onMessageAsync, string groupId, CancellationToken cancellationToken, params string[] topics)
        {
            if (onMessageAsync == null)
            {
                throw new ArgumentNullException(nameof(onMessageAsync));
            }

            if (groupId == null)
            {
                throw new ArgumentNullException(nameof(groupId));
            }

            if (!TopicNameHelpers.IsValid(groupId))
            {
                throw new ArgumentException(
                          $"The groupId must match regex pattern: '{TopicNameHelpers.TopicOrGroupIdValidationRegexPattern}'", nameof(groupId));
            }

            var messageHandler = new MessageHandler(onMessageAsync, pubSub, logger, configuration, groupId);
            var retryerTopics  = new List <string>();

            foreach (var topic in topics)
            {
                if (!TopicNameHelpers.IsValid(topic))
                {
                    throw new ArgumentException(
                              $"The topic name must match regex pattern: '{TopicNameHelpers.TopicOrGroupIdValidationRegexPattern}'. " +
                              $"Validation failed for '{topic}'.", nameof(topics));
                }

                if (!TopicNameHelpers.IsBadMessageTopic(topic))
                {
                    for (int i = 0; i < configuration.LevelDelaysInSeconds.Length; i++)
                    {
                        retryerTopics.Add(TopicNameHelpers.BuildBadMessageTopicName(topic, i, groupId));
                    }
                }
            }

            var subscription = pubSub.Subscribe(messageHandler, groupId, topics.Union(retryerTopics).ToArray());

            messageHandler.Subscription = subscription;
            await subscription.StartAsync(cancellationToken);
        }