예제 #1
0
        //ILogger _logger;

        public ReturnItem SendMail(Request req)
        {
            var validationErrors = InputValidator.ValidateInputs(req);

            if (validationErrors.Count == 0)
            {
                var retCode = PrimaryClient.SendMail(req);

                if (retCode.RetCode == 1)
                {
                    return(retCode);
                }
                else
                {
                    return(RetryHandler.Retry(req, ScondaryClientList, retCode.Message));
                }
            }
            else
            {
                return(new ReturnItem
                {
                    Message = string.Join(";", validationErrors.ToArray()),
                    RetCode = 3
                });
            }
        }
예제 #2
0
        public async Task DisconnectAsync(CancellationToken cancellationToken)
        {
            var cancelToken       = cancellationToken != null ? cancellationToken : CancellationToken.None;
            var disconnectOptions = new MqttClientDisconnectOptions {
                ReasonString = "Bridge disconnect"
            };
            await PrimaryClient.DisconnectAsync(disconnectOptions, cancelToken);

            await SecondaryClient.DisconnectAsync(disconnectOptions, cancelToken);
        }
예제 #3
0
        /// <summary>
        /// Configures circuit breaker.
        /// </summary>
        private void ConfigureCircuitBreaker()
        {
            void OnBreak(Exception exception, TimeSpan timespan)
            {
                //recreate secondary sender
                if (SecondaryClient == null)
                {
                    SecondaryClient = CreateClient(_secondaryServiceBusConnectionString);
                }

                //kill primary sender
                PrimaryClient.CloseAsync().ConfigureAwait(false).GetAwaiter().GetResult();
                PrimaryClient = null;

                _logger?.LogWarning(exception, "Switched from primary to secondary service bus sender");
            }

            void OnHalfOpen()
            {
                //recreate primary sender
                if (PrimaryClient == null)
                {
                    PrimaryClient = CreateClient(_primaryServiceBusConnectionString);
                }

                //kill secondary
                SecondaryClient.CloseAsync().ConfigureAwait(false).GetAwaiter().GetResult();
                SecondaryClient = null;

                _logger?.LogWarning("Switched back from secondary to primary service bus sender");
            }

            void OnReset()
            {
                _logger?.LogInformation("Circuit breaker was reset.");
            }

            _circuitBreaker = Policy
                              .Handle <Exception>()
                              .CircuitBreakerAsync(ExceptionsAllowedBeforeBreaking, TimeSpan.FromMilliseconds(TimeOutIfBreaksInMilliseconds), OnBreak, OnReset, OnHalfOpen);
        }
예제 #4
0
        public async Task <MQTTnet.Client.Connecting.MqttClientAuthenticateResult> ConnectAsync(CancellationToken cancellationToken)
        {
            var cancelToken = cancellationToken != null ? cancellationToken : CancellationToken.None;
            MqttClientAuthenticateResult connectPrimary = null;

            if (!PrimaryClient.IsConnected)
            {
                PrimaryClient.UseConnectedHandler(async e =>
                {
                    var primaryFilters = Options.PrimaryFilters != null && Options.PrimaryFilters.Any()
                        ? Options.PrimaryFilters
                        : new TopicFilter[] { new TopicFilterBuilder().WithTopic("#").Build() };
                    await PrimaryClient.SubscribeAsync(primaryFilters);
                });

                connectPrimary = await PrimaryClient.ConnectAsync(Options.PrimaryOptions, cancelToken);

                if (connectPrimary.ResultCode != MqttClientConnectResultCode.Success)
                {
                    throw new ArgumentException("PrimaryOptions, could not connect to primary server.");
                }
            }

            if (!SecondaryClient.IsConnected)
            {
                var connectSecondary = await SecondaryClient.ConnectAsync(Options.SecondaryOptions, cancelToken);

                if (connectSecondary.ResultCode != MqttClientConnectResultCode.Success)
                {
                    throw new ArgumentException("SecondaryOptions, could not connect to secondary server.");
                }
            }


            PrimaryClient.UseDisconnectedHandler(async e =>
            {
                var connectRetry = Policy
                                   .Handle <Exception>()
                                   .WaitAndRetryForeverAsync(
                    retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)),
                    (exception, timespan) =>
                {
                    Console.WriteLine("### DISCONNECTED FROM SERVER ###");
                });
                await connectRetry.ExecuteAsync(async() => {
                    var response = await PrimaryClient.ConnectAsync(Options.PrimaryOptions, cancelToken);
                    Console.Write($"{response.ResultCode} {response.ReasonString}");
                });
            });

            SecondaryClient.UseDisconnectedHandler(async e =>
            {
                var connectRetry = Policy
                                   .Handle <Exception>()
                                   .WaitAndRetryForeverAsync(
                    retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)),
                    (exception, timespan) =>
                {
                    Console.WriteLine("### DISCONNECTED FROM SERVER ###");
                });
                await connectRetry.ExecuteAsync(async() => {
                    var response = await SecondaryClient.ConnectAsync(Options.SecondaryOptions, cancelToken);
                    Console.Write($"{response.ResultCode} {response.ReasonString}");
                });
            });

            PrimaryClient.UseApplicationMessageReceivedHandler(e =>
            {
                var message = new MqttApplicationMessageBuilder()
                              .WithTopic(e.ApplicationMessage.Topic)
                              .WithPayload(e.ApplicationMessage.Payload);
                if (e.ApplicationMessage.Retain)
                {
                    message = message.WithRetainFlag();
                }
                switch (e.ApplicationMessage.QualityOfServiceLevel)
                {
                case MqttQualityOfServiceLevel.ExactlyOnce:
                    message = message.WithExactlyOnceQoS();
                    break;

                case MqttQualityOfServiceLevel.AtLeastOnce:
                    message = message.WithAtLeastOnceQoS();
                    break;

                case MqttQualityOfServiceLevel.AtMostOnce:
                    message = message.WithAtMostOnceQoS();
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }

                Task.Run(() => SecondaryClient.PublishAsync(message.Build(), cancelToken), cancelToken);
            });

            if (Options.SyncMode)
            {
                SecondaryClient.UseConnectedHandler(async e =>
                {
                    var secondaryFilters = Options.SecondaryFilters != null && Options.SecondaryFilters.Any()
                        ? Options.SecondaryFilters
                        : new TopicFilter[] { new TopicFilterBuilder().WithTopic("#").Build() };
                    await SecondaryClient.SubscribeAsync(secondaryFilters);
                });

                SecondaryClient.UseApplicationMessageReceivedHandler(e =>
                {
                    var message = new MqttApplicationMessageBuilder()
                                  .WithTopic(e.ApplicationMessage.Topic)
                                  .WithPayload(e.ApplicationMessage.Payload);
                    if (e.ApplicationMessage.Retain)
                    {
                        message = message.WithRetainFlag();
                    }
                    switch (e.ApplicationMessage.QualityOfServiceLevel)
                    {
                    case MqttQualityOfServiceLevel.ExactlyOnce:
                        message = message.WithExactlyOnceQoS();
                        break;

                    case MqttQualityOfServiceLevel.AtLeastOnce:
                        message = message.WithAtLeastOnceQoS();
                        break;

                    case MqttQualityOfServiceLevel.AtMostOnce:
                        message = message.WithAtMostOnceQoS();
                        break;

                    default:
                        throw new ArgumentOutOfRangeException();
                    }

                    Task.Run(() => PrimaryClient.PublishAsync(message.Build(), cancelToken), cancelToken);
                });
            }
            return(connectPrimary);
        }
예제 #5
0
 /// <summary>
 /// Cleans up (un)managed resources.
 /// </summary>
 /// <param name="disposing"></param>
 protected virtual void Dispose(bool disposing)
 {
     PrimaryClient?.CloseAsync().ConfigureAwait(false).GetAwaiter().GetResult();
     SecondaryClient?.CloseAsync().ConfigureAwait(false).GetAwaiter().GetResult();
 }