Пример #1
0
        public void IsEquivalentToDetectsEqualOptionSets()
        {
            var customPolicy = Mock.Of <EventHubRetryPolicy>();
            var first        = new RetryOptions {
                CustomRetryPolicy = customPolicy
            };
            var second = new RetryOptions {
                CustomRetryPolicy = customPolicy
            };

            Assert.That(first.IsEquivalentTo(second), Is.True);
        }
Пример #2
0
        public void Receive_Retry_BufferFull_Ignore()
        {
            SetupTestReceiveThrows((timer, mockConsumer, retryConsumer) =>
            {
                int[] intArray = { 1, 2, 3, 4 };
                retryConsumer.Receive(intArray);

                mockConsumer.Verify(c => c.Receive(intArray), Times.Once);
                timer.Call();
                mockConsumer.Verify(c => c.Receive(intArray), Times.Once);
            }, RetryOptions.Retry(bufferSizeBytes: 1));
        }
Пример #3
0
        public void Receive_Retry_BufferFull_Throw()
        {
            SetupTestReceiveThrows((timer, mockConsumer, retryConsumer) =>
            {
                int[] intArray = { 1, 2, 3, 4 };
                Assert.Throws <InvalidOperationException>(() => { retryConsumer.Receive(intArray); });

                mockConsumer.Verify(c => c.Receive(intArray), Times.Once);
                timer.Call();
                mockConsumer.Verify(c => c.Receive(intArray), Times.Once);
            }, RetryOptions.Retry(bufferSizeBytes: 1, bufferOverflow: BufferOverflow.ThrowException));
        }
Пример #4
0
        public void Receive_NoRetry_Ignore()
        {
            SetupTestReceiveThrows((timer, mockConsumer, retryConsumer) =>
            {
                int[] intArray = { 1, 2, 3, 4 };
                retryConsumer.Receive(intArray);

                mockConsumer.Verify(c => c.Receive(intArray), Times.Once);
                timer.Call();
                mockConsumer.Verify(c => c.Receive(intArray), Times.Once);
            }, RetryOptions.NoRetry());
        }
Пример #5
0
        public SqlServerConnectionFactoryWithRetry(RetryOptions retryOptions, string connectionString = null)
        {
            if (retryOptions == null)
            {
                throw new ArgumentNullException(nameof(retryOptions));
            }

            _proxy = RetryProxy.Create <IConnectionFactory>(
                String.IsNullOrEmpty(connectionString) ? new SqlServerConnectionFactory() : new SqlServerConnectionFactory(connectionString),
                retryOptions,
                new SqlServerTransientErrorTester());
        }
Пример #6
0
        public void ConfigureServices(IServiceCollection services)
        {
            var cosmosDbConnectionContentPages = configuration.GetSection(CosmosDbContentPagesConfigAppSettings).Get <CosmosDbConnection>();
            var cosmosRetryOptions             = new RetryOptions {
                MaxRetryAttemptsOnThrottledRequests = 20, MaxRetryWaitTimeInSeconds = 60
            };

            services.AddContentPageServices <ContentPageModel>(cosmosDbConnectionContentPages, env.IsDevelopment(), cosmosRetryOptions);

            services.AddApplicationInsightsTelemetry();
            services.AddHttpContextAccessor();
            services.AddTransient <IPagesControlerHelpers, PagesControlerHelpers>();
            services.AddTransient <IEventMessageService <ContentPageModel>, EventMessageService <ContentPageModel> >();
            services.AddTransient <ICacheReloadService, CacheReloadService>();
            services.AddTransient <IWebhooksService, WebhooksService>();
            services.AddTransient <IWebhookContentProcessor, WebhookContentProcessor>();
            services.AddTransient <IPageLocatonUpdater, PageLocatonUpdater>();
            services.AddTransient <IContentItemUpdater, ContentItemUpdater>();
            services.AddTransient <IMarkupContentItemUpdater <CmsApiHtmlModel>, MarkupContentItemUpdater <CmsApiHtmlModel> >();
            services.AddTransient <IMarkupContentItemUpdater <CmsApiHtmlSharedModel>, MarkupContentItemUpdater <CmsApiHtmlSharedModel> >();
            services.AddTransient <IMarkupContentItemUpdater <CmsApiSharedContentModel>, MarkupContentItemUpdater <CmsApiSharedContentModel> >();
            services.AddTransient <IMarkupContentItemUpdater <CmsApiFormModel>, MarkupContentItemUpdater <CmsApiFormModel> >();
            services.AddTransient <IEventGridService, EventGridService>();
            services.AddTransient <IEventGridClientService, EventGridClientService>();
            services.AddAutoMapper(typeof(Startup).Assembly);
            services.AddSingleton(configuration.GetSection(nameof(CmsApiClientOptions)).Get <CmsApiClientOptions>() ?? new CmsApiClientOptions());
            services.AddSingleton(configuration.GetSection(nameof(EventGridPublishClientOptions)).Get <EventGridPublishClientOptions>() ?? new EventGridPublishClientOptions());
            services.AddSingleton(configuration.GetSection(nameof(AppRegistryClientOptions)).Get <AppRegistryClientOptions>() ?? new AppRegistryClientOptions());
            services.AddSingleton(configuration.GetSection(nameof(CacheReloadTimerOptions)).Get <CacheReloadTimerOptions>() ?? new CacheReloadTimerOptions());
            services.AddHostedServiceTelemetryWrapper();
            services.AddSubscriptionBackgroundService(configuration);
            services.AddHostedService <CacheReloadBackgroundService>();
            services.AddHostedService <CacheReloadTimedHostedService>();

            const string AppSettingsPolicies = "Policies";
            var          policyOptions       = configuration.GetSection(AppSettingsPolicies).Get <PolicyOptions>() ?? new PolicyOptions();
            var          policyRegistry      = services.AddPolicyRegistry();

            services.AddApiServices(configuration, policyRegistry);

            services
            .AddPolicies(policyRegistry, nameof(AppRegistryClientOptions), policyOptions)
            .AddHttpClient <IAppRegistryApiService, AppRegistryApiService, AppRegistryClientOptions>(configuration, nameof(AppRegistryClientOptions), nameof(PolicyOptions.HttpRetry), nameof(PolicyOptions.HttpCircuitBreaker));

            services.AddMvc(config =>
            {
                config.RespectBrowserAcceptHeader = true;
                config.ReturnHttpNotAcceptable    = true;
            })
            .AddNewtonsoftJson()
            .SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
        }
        public void ConfigureServices(IServiceCollection services)
        {
            var cosmosDbConnectionJobGroup      = configuration.GetSection(CosmosDbJobGroupConfigAppSettings).Get <CosmosDbConnection>();
            var cosmosDbConnectionSharedContent = configuration.GetSection(CosmosDbSharedContentConfigAppSettings).Get <CosmosDbConnection>();
            var cosmosRetryOptions = new RetryOptions {
                MaxRetryAttemptsOnThrottledRequests = 20, MaxRetryWaitTimeInSeconds = 60
            };

            services.AddDocumentServices <JobGroupModel>(cosmosDbConnectionJobGroup, env.IsDevelopment(), cosmosRetryOptions);
            services.AddDocumentServices <ContentItemModel>(cosmosDbConnectionSharedContent, env.IsDevelopment(), cosmosRetryOptions);

            services.AddApplicationInsightsTelemetry();
            services.AddHttpContextAccessor();
            services.AddHostedServiceTelemetryWrapper();
            services.AddAutoMapper(typeof(Startup).Assembly);
            services.AddHostedService <SharedContentCacheReloadBackgroundService>();
            services.AddSubscriptionBackgroundService(configuration);
            services.AddTransient <IJobGroupCacheRefreshService, JobGroupCacheRefreshService>();
            services.AddTransient <IJobGroupPublishedRefreshService, JobGroupPublishedRefreshService>();
            services.AddTransient <IWebhooksService, WebhooksService>();
            services.AddTransient <IWebhooksContentService, WebhooksContentService>();
            services.AddTransient <IWebhooksDeleteService, WebhooksDeleteService>();
            services.AddTransient <ISharedContentCacheReloadService, SharedContentCacheReloadService>();
            services.AddTransient <IApiConnector, ApiConnector>();
            services.AddTransient <IApiDataConnector, ApiDataConnector>();
            services.AddSingleton(configuration.GetSection(nameof(EventGridClientOptions)).Get <EventGridClientOptions>() ?? new EventGridClientOptions());
            services.AddTransient <IEventGridService, EventGridService>();
            services.AddTransient <IEventGridClientService, EventGridClientService>();

            var policyOptions  = configuration.GetSection(AppSettingsPolicies).Get <PolicyOptions>() ?? new PolicyOptions();
            var policyRegistry = services.AddPolicyRegistry();

            services.AddSingleton(configuration.GetSection(nameof(LmiTransformationApiClientOptions)).Get <LmiTransformationApiClientOptions>() ?? new LmiTransformationApiClientOptions());
            services.AddSingleton(configuration.GetSection(nameof(JobGroupDraftApiClientOptions)).Get <JobGroupDraftApiClientOptions>() ?? new JobGroupDraftApiClientOptions());
            services.AddApiServices(configuration, policyRegistry);

            services
            .AddPolicies(policyRegistry, nameof(LmiTransformationApiClientOptions), policyOptions)
            .AddHttpClient <ILmiTransformationApiConnector, LmiTransformationApiConnector, LmiTransformationApiClientOptions>(nameof(LmiTransformationApiClientOptions), nameof(PolicyOptions.HttpRetry), nameof(PolicyOptions.HttpCircuitBreaker));

            services
            .AddPolicies(policyRegistry, nameof(JobGroupDraftApiClientOptions), policyOptions)
            .AddHttpClient <IJobGroupApiConnector, JobGroupApiConnector, JobGroupDraftApiClientOptions>(nameof(JobGroupDraftApiClientOptions), nameof(PolicyOptions.HttpRetry), nameof(PolicyOptions.HttpCircuitBreaker));

            services.AddMvc(config =>
            {
                config.RespectBrowserAcceptHeader = true;
                config.ReturnHttpNotAcceptable    = true;
            })
            .AddNewtonsoftJson()
            .SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
        }
Пример #8
0
        public void IsEquivalentToDetectsNullArgument()
        {
            var first = new RetryOptions
            {
                Mode           = RetryMode.Fixed,
                MaximumRetries = 99,
                MaximumDelay   = TimeSpan.FromMinutes(3),
                Delay          = TimeSpan.FromSeconds(4),
                TryTimeout     = TimeSpan.Zero
            };

            Assert.That(first.IsEquivalentTo((RetryOptions)null), Is.False);
        }
        public static async Task <bool> SimpleActivityRetrySuccceds([OrchestrationTrigger] IDurableOrchestrationContext ctx)
        {
            (TimeSpan firstRetry, TimeSpan maxRetry) = ctx.GetInput <(TimeSpan, TimeSpan)>();

            RetryOptions retry = new RetryOptions(firstRetry, 5)
            {
                MaxRetryInterval = maxRetry,
            };

            await ctx.CallActivityWithRetryAsync <Guid>(nameof(TestActivities.NewGuid), retry, null);

            return(true);
        }
Пример #10
0
        public void IsEquivalentToDetectsSameInstance()
        {
            var first = new RetryOptions
            {
                Mode           = RetryMode.Fixed,
                MaximumRetries = 99,
                MaximumDelay   = TimeSpan.FromMinutes(3),
                Delay          = TimeSpan.FromSeconds(4),
                TryTimeout     = TimeSpan.Zero
            };

            Assert.That(first.IsEquivalentTo(first), Is.True);
        }
        public static async Task <object> NewWorker(
            [OrchestrationTrigger] DurableOrchestrationContext ctx,
            TraceWriter log
            )
        {
            int retryattempts = 1;
            var query         = ctx.GetInput <string>();

            var retryOptions = new RetryOptions(
                firstRetryInterval: TimeSpan.FromSeconds(5),
                maxNumberOfAttempts: retryattempts);

            var getcookietask = ctx.CallActivityWithRetryAsync <string>("Authenticate", retryOptions, "credentials");

            getcookietask.ContinueWith(t =>
            {
                return("Failed");
            }, TaskContinuationOptions.OnlyOnFaulted);
            await getcookietask;
            var   cookiesjsonb64 = getcookietask.Result;
            var   cookies        = CookieConverter.DecodeCookie(cookiesjsonb64);

            if (!ctx.IsReplaying)
            {
                log.Warning($"Successfully retrieved {cookies.Length} cookies.");
            }

            var querygurutask = ctx.CallActivityWithRetryAsync <int>("QueryGuru", retryOptions, new Tuple <string, string>(query, cookiesjsonb64));

            querygurutask.ContinueWith(t =>
            {
                return("Failed");
            }, TaskContinuationOptions.OnlyOnFaulted);
            var pages = await querygurutask;

            if (!ctx.IsReplaying)
            {
                log.Warning($"Query successfully returned {pages}.");
            }

            var workload = await ctx.CallActivityAsync <List <int> >("CreateWorkload", pages);

            //log.Warning(ctx.InstanceId);
            var worker = ctx.CallSubOrchestratorAsync("WorkerWork", new WorkerWorkArgs {
                query = query, cookiestext = cookiesjsonb64, workload = workload, total = workload.Count
            });

            string result = await ctx.WaitForExternalEvent <string>("Finished");

            return(result);
        }
Пример #12
0
        public async Task <List <WorkflowStepResult> > StartProvisionUserWithMultipleGroupsOrchestrator(
            [OrchestrationTrigger] IDurableOrchestrationContext context,
            ILogger logger)
        {
            var input = context.GetInput <ProvisionNewUserMultipleGroups>();

            if (!context.IsReplaying)
            {
                logger.LogInformation($"Executing User provisioning workflow with InstanceId: {input.CorrelationId.ToString()}");
            }

            var retryOptions = new RetryOptions(TimeSpan.FromSeconds(5), 3);

            var outputs = new List <WorkflowStepResult>();

            var createUserResult = await context.CallActivityWithRetryAsync <WorkflowStepResult>(Constants.FunctionNames.Activity.CreateUser, retryOptions, (input.OperatorEmail, input.User, input.GroupIds));

            outputs.Add(createUserResult);

            if (createUserResult.Successfull)
            {
                var assignUserToGroupTasks = new Task <WorkflowStepResult> [input.GroupIds.Count];
                for (int i = 0; i < input.GroupIds.Count; i++)
                {
                    assignUserToGroupTasks[i] = context.CallActivityWithRetryAsync <WorkflowStepResult>(Constants.FunctionNames.Activity.AssignUserToGroup, retryOptions, new AssignUserToGroupModel(input.GroupIds[i], createUserResult.OutputId));
                }

                var paralellOutputs = await Task.WhenAll(assignUserToGroupTasks);

                outputs.AddRange(paralellOutputs);


                var unassignedGroups = paralellOutputs.Where(x => !x.Successfull).ToList();
                if (unassignedGroups.Any())
                {
                    var unassignGroupFromUserTasks = new Task <WorkflowStepResult> [unassignedGroups.Count];
                    for (int i = 0; i < unassignedGroups.Count; i++)
                    {
                        unassignGroupFromUserTasks[i] = context.CallActivityWithRetryAsync <WorkflowStepResult>(Constants.FunctionNames.Activity.UnassignGroupFromUser, retryOptions, (createUserResult.OutputId, unassignedGroups[i].OutputId.ToString()));
                    }
                }
            }

            await context.CallActivityWithRetryAsync <WorkflowStepResult>(Constants.FunctionNames.Activity.SendEmail, retryOptions, new MailItemModel(
                                                                              from : string.Empty,
                                                                              to : input.OperatorEmail,
                                                                              subject : $"Provisioning User {input.User.FirstName} {input.User.FirstName} with Groups {string.Join(',', input.GroupIds)}",
                                                                              htmlBody : outputs.ToProvisioningUserMailBody(input.User)));

            return(outputs);
        }
Пример #13
0
        public static void RetryOptions_Default()
        {
            // Arrange
            var optionsString = string.Empty;

            // Act
            var options = new RetryOptions(optionsString);

            // Assert
            Assert.Equal(0, options.MaxRetryCount);
            Assert.Equal(0, options.RetryDelay);
            Assert.Equal(false, options.RetryFails);
            Assert.Equal(0, options.RetryTimeout);
        }
Пример #14
0
        public static void RetryOptions_OptionsString_WithPrefix()
        {
            // Arrange
            var optionsString = "Transfer Max Retry Count = 10;Transfer Retry Delay = 5;Transfer Retry Fails = true;Transfer Retry Timeout = 250";

            // Act
            var options = new RetryOptions(optionsString, "Transfer");

            // Assert
            Assert.Equal(10, options.MaxRetryCount);
            Assert.Equal(5, options.RetryDelay);
            Assert.Equal(true, options.RetryFails);
            Assert.Equal(250, options.RetryTimeout);
        }
Пример #15
0
 /// <summary>
 /// Initializes a new instance of the <see cref="InstanceIdClient"/> class.
 /// </summary>
 /// <param name="clientFactory">A default implentation of the HTTP client factory.</param>
 /// <param name="credential">An instance of the <see cref="GoogleCredential"/> class.</param>
 /// <param name="retryOptions">An instance of the <see cref="RetryOptions"/> class.</param>
 internal InstanceIdClient(
     HttpClientFactory clientFactory, GoogleCredential credential, RetryOptions retryOptions = null)
 {
     this.httpClient = new ErrorHandlingHttpClient <FirebaseMessagingException>(
         new ErrorHandlingHttpClientArgs <FirebaseMessagingException>()
     {
         HttpClientFactory           = clientFactory.ThrowIfNull(nameof(clientFactory)),
         Credential                  = credential.ThrowIfNull(nameof(credential)),
         RequestExceptionHandler     = MessagingErrorHandler.Instance,
         ErrorResponseHandler        = InstanceIdErrorHandler.Instance,
         DeserializeExceptionHandler = MessagingErrorHandler.Instance,
         RetryOptions                = retryOptions,
     });
 }
Пример #16
0
        public static void RetryOptions_OptionsString()
        {
            // Arrange
            var optionsString = "Max Retry Count = 10;Retry Delay = 5;Retry Fails = true;Retry Timeout = 250";

            // Act
            var options = new RetryOptions(optionsString);

            // Assert
            Assert.Equal(10, options.MaxRetryCount);
            Assert.Equal(5, options.RetryDelay);
            Assert.Equal(true, options.RetryFails);
            Assert.Equal(250, options.RetryTimeout);
        }
Пример #17
0
        private GoogleLogger GetLogger(
            IConsumer <LogEntry> consumer      = null, LogLevel logLevel = LogLevel.Information,
            Dictionary <string, string> labels = null, IServiceProvider serviceProvider = null,
            string logName = null,
            MonitoredResource monitoredResource = null, LogTarget logTarget = null,
            RetryOptions retryOptions           = null)
        {
            consumer          = consumer ?? new Mock <IConsumer <LogEntry> >(MockBehavior.Strict).Object;
            monitoredResource = monitoredResource ?? MonitoredResourceBuilder.GlobalResource;
            logTarget         = logTarget ?? s_defaultLogTarget;
            LoggerOptions options = LoggerOptions.Create(logLevel, logName, labels, monitoredResource, retryOptions: retryOptions);

            return(new GoogleLogger(consumer, logTarget, options, LogName, s_clock, serviceProvider));
        }
        public static async Task ProcessOrderOrchestrator(
            [OrchestrationTrigger] DurableOrchestrationContext context,
            ILogger log)
        {
            var policy = context.GetInput <WhatIfDemoDbDataContext.Policy>();

            // Configuring retries for SavePolicyToDb activity
            var retryOptions = new RetryOptions(TimeSpan.FromSeconds(5), 3);

            policy = await context.CallActivityWithRetryAsync <WhatIfDemoDbDataContext.Policy>(nameof(SavePolicyToDb), retryOptions, policy);

            // Now let's start charging the customer via a sub-orchestration
            await context.CallSubOrchestratorAsync(nameof(ProcessOrderSubOrchestrator), policy);
        }
Пример #19
0
        internal UnitOfWork(
            IDbConnection connection,
            bool transactional            = false,
            IsolationLevel isolationLevel = IsolationLevel.ReadCommitted,
            RetryOptions retryOptions     = null)
        {
            _connection   = connection;
            _retryOptions = retryOptions;

            if (transactional)
            {
                _transaction = connection.BeginTransaction(isolationLevel);
            }
        }
Пример #20
0
        public void Receive_Retry_MaxRetries_Ignore()
        {
            SetupTestReceiveThrows((timer, mockConsumer, retryConsumer) =>
            {
                int[] intArray = { 1, 2, 3, 4 };
                retryConsumer.Receive(intArray);

                timer.Call();
                timer.Call();
                // Extra call to ensure buffer is emptied.
                timer.Call();
                mockConsumer.Verify(c => c.Receive(intArray), Times.Exactly(3));
            }, RetryOptions.Retry(retryAttempts: 2));
        }
Пример #21
0
        public static void Execute_RetryFails()
        {
            // Arrange
            var options = new RetryOptions()
            {
                MaxRetryCount = 1,
                RetryFails    = true
            };

            // Act
            Assert.Throws <TimeoutException>(() => RetryHelper.Execute(options, () => false));

            // Assert
        }
Пример #22
0
        public static Schema ReadSchema(string connectionString)
        {
            Schema result = new Schema();

            var retryOptions = new RetryOptions(30, TimeSpan.FromSeconds(60));
            IConnectionFactory connectionFactory = new SqlServerConnectionFactoryWithRetry(retryOptions);

            using (var connection = connectionFactory.Open(connectionString))
                using (var reader = new SqlReader(connection, new SqlServerParameterFactory(), new SqlServerDataAdapterFactory()))
                {
                    using (var schemas = reader.Read(Resources.GetSchemasSql))
                    {
                        if (schemas.Tables.Count != 1)
                        {
                            throw new ApplicationException("no schemas found");
                        }
                        result.Schemas = schemas.Tables[0].Rows.ToArray <IItemName, ItemName>();
                    }
                    using (var tables = reader.Read(Resources.GetTablesSql))
                    {
                        if (tables.Tables.Count != 1)
                        {
                            throw new ApplicationException("no tables found");
                        }
                        result.Tables = tables.Tables[0].Rows.ToArray <IEntityName, EntityName>();
                    }
                    using (var procedures = reader.Read(Resources.GetProceduresSql))
                    {
                        if (procedures.Tables.Count != 1)
                        {
                            throw new ApplicationException("no procedures found");
                        }
                        result.Procedures = procedures.Tables[0].Rows.ToArray <Procedure>().ToDictionary(p => p.ToString());
                    }
                    using (var procedureParams = reader.Read(Resources.GetProcedureParametersSql))
                    {
                        if (procedureParams.Tables.Count != 1)
                        {
                            throw new ApplicationException("no parameters found");
                        }
                        var parameters = procedureParams.Tables[0].Rows.ToArray <ProcedureParameter>();
                        foreach (var procedure in result.Procedures)
                        {
                            procedure.Value.ProcedureParameters = (from p in parameters where p.Schema == procedure.Value.Schema && p.Procedure == procedure.Value.Name orderby p.Order select p).ToArray();
                        }
                    }
                }

            return(result);
        }
Пример #23
0
        public static void RetryOptions_OptionsString_WithPrefix_NoMatch()
        {
            // Arrange
            var optionsString = "Max Retry Count = 10;Retry Delay = 5;Retry Fails = true;Retry Timeout = 250";

            // Act
            var options = new RetryOptions(optionsString, "Transfer");

            // Assert
            Assert.Equal(0, options.MaxRetryCount);
            Assert.Equal(0, options.RetryDelay);
            Assert.Equal(false, options.RetryFails);
            Assert.Equal(0, options.RetryTimeout);
        }
Пример #24
0
        public void Receive_Retry_MaxRetries_Throw()
        {
            SetupTestReceiveThrows((timer, mockConsumer, retryConsumer) =>
            {
                int[] intArray = { 1, 2, 3, 4 };
                retryConsumer.Receive(intArray);

                timer.Call();
                Assert.Throws <InvalidOperationException>(() => { timer.Call(); });
                // Extra call to ensure buffer is emptied.
                timer.Call();
                mockConsumer.Verify(c => c.Receive(intArray), Times.Exactly(3));
            }, RetryOptions.Retry(exceptionHandling: ExceptionHandling.Propagate, retryAttempts: 2));
        }
        private static Dictionary <string, object> ToDictionary(RetryOptions retryOptions)
        {
            var result = new Dictionary <string, object>()
            {
                { "firstRetryIntervalInMilliseconds", ToIntMilliseconds(retryOptions.FirstRetryInterval) },
                { "maxNumberOfAttempts", retryOptions.MaxNumberOfAttempts }
            };

            AddOptionalValue(result, "backoffCoefficient", retryOptions.BackoffCoefficient, x => x);
            AddOptionalValue(result, "maxRetryIntervalInMilliseconds", retryOptions.MaxRetryInterval, ToIntMilliseconds);
            AddOptionalValue(result, "retryTimeoutInMilliseconds", retryOptions.RetryTimeout, ToIntMilliseconds);

            return(result);
        }
        public static async Task OrchestrateConsumersFunc([OrchestrationTrigger] DurableOrchestrationContext ctx)
        {
            var changedProducts = ctx.GetInput <IEnumerable <string> >();

            var retryOptions = new RetryOptions(firstRetryInterval: TimeSpan.FromSeconds(5),
                                                maxNumberOfAttempts: 3);

            var consumers = Environment.GetEnvironmentVariable("CONSUMERS", EnvironmentVariableTarget.Process)
                            ?.Split('|');

            var parallelTasks = consumers.Select(x => CallSendToConsumerActivityAsync(ctx, retryOptions, x, changedProducts));

            await Task.WhenAll(parallelTasks);
        }
Пример #27
0
        public async Task CallActivityWithRetryAsync_is_calling_extension_method()
        {
            var retryOptions = new RetryOptions(TimeSpan.FromSeconds(10), 5);
            var durableOrchestrationContextBaseMock = new Mock <IDurableOrchestrationContext> {
            };

            durableOrchestrationContextBaseMock
            .Setup(x => x.CallActivityWithRetryAsync <object>(FunctionName, retryOptions, this.inputObject))
            .Returns(this.taskFromTen);
            var result      = durableOrchestrationContextBaseMock.Object.CallActivityWithRetryAsync(FunctionName, retryOptions, this.inputObject);
            var resultValue = await(Task <object>) result;

            resultValue.Should().Be(this.stateValueTen);
        }
        public async Task <List <WorkflowStepResult> > StartProvisionUserWithSingleGroupOrchestrator(
            [OrchestrationTrigger] IDurableOrchestrationContext context,
            ILogger logger)
        {
            var input = context.GetInput <ProvisionNewUserSingleGroup>();

            if (!context.IsReplaying)
            {
                logger.LogInformation($"Started User provisioning workflow with InstanceId: {input.CorrelationId.ToString()}");
            }

            var retryOptions = new RetryOptions(TimeSpan.FromSeconds(5), 3);

            var outputs = new List <WorkflowStepResult>();

            var createUserResult = await context.CallActivityWithRetryAsync <WorkflowStepResult>(Constants.FunctionNames.Activity.CreateUser, retryOptions, (input.OperatorEmail, input.User, new List <Guid> {
                input.GroupId
            }));

            outputs.Add(createUserResult);

            if (createUserResult.Successfull)
            {
                var assignUserToGroupResult = await context.CallActivityWithRetryAsync <WorkflowStepResult>(
                    Constants.FunctionNames.Activity.AssignUserToGroup,
                    retryOptions,
                    new AssignUserToGroupModel(input.GroupId, createUserResult.OutputId));

                outputs.Add(assignUserToGroupResult);

                if (!assignUserToGroupResult.Successfull)
                {
                    var unassignGroupFromUserResult = await context.CallActivityWithRetryAsync <WorkflowStepResult>(
                        Constants.FunctionNames.Activity.UnassignGroupFromUser,
                        retryOptions,
                        (createUserResult.OutputId, assignUserToGroupResult.OutputId));

                    outputs.Add(unassignGroupFromUserResult);
                }
            }

            await context.CallActivityWithRetryAsync <WorkflowStepResult>(Constants.FunctionNames.Activity.SendEmail, retryOptions, new MailItemModel(
                                                                              from : string.Empty,
                                                                              to : input.OperatorEmail,
                                                                              subject : $"Provisioning User {input.User.FirstName} {input.User.LastName} with Group {input.GroupId}",
                                                                              htmlBody : outputs.ToProvisioningUserMailBody(input.User)));

            return(outputs);
        }
Пример #29
0
        public void ReceiveAsyncRespectsTheRetryPolicy(RetryOptions retryOptions)
        {
            var eventHub           = "eventHubName";
            var consumerGroup      = "$DEFAULT";
            var partition          = "3";
            var eventPosition      = EventPosition.FromOffset(123);
            var trackLastEnqueued  = false;
            var ownerLevel         = 123L;
            var tokenValue         = "123ABC";
            var retryPolicy        = new BasicRetryPolicy(retryOptions);
            var retriableException = new EventHubsException(true, "Test");
            var mockConverter      = new Mock <AmqpMessageConverter>();
            var mockCredential     = new Mock <TokenCredential>();
            var mockScope          = new Mock <AmqpConnectionScope>();

            using var cancellationSource = new CancellationTokenSource();

            mockCredential
            .Setup(credential => credential.GetTokenAsync(It.IsAny <TokenRequestContext>(), It.Is <CancellationToken>(value => value == cancellationSource.Token)))
            .Returns(new ValueTask <AccessToken>(new AccessToken(tokenValue, DateTimeOffset.MaxValue)));

            mockScope
            .Setup(scope => scope.OpenConsumerLinkAsync(
                       It.IsAny <string>(),
                       It.IsAny <string>(),
                       It.IsAny <EventPosition>(),
                       It.IsAny <TimeSpan>(),
                       It.IsAny <uint>(),
                       It.IsAny <long?>(),
                       It.IsAny <bool>(),
                       It.IsAny <CancellationToken>()))
            .Throws(retriableException);

            var consumer = new AmqpConsumer(eventHub, consumerGroup, partition, eventPosition, trackLastEnqueued, ownerLevel, null, mockScope.Object, Mock.Of <AmqpMessageConverter>(), retryPolicy);

            Assert.That(async() => await consumer.ReceiveAsync(100, null, cancellationSource.Token), Throws.InstanceOf(retriableException.GetType()));

            mockScope
            .Verify(scope => scope.OpenConsumerLinkAsync(
                        It.Is <string>(value => value == consumerGroup),
                        It.Is <string>(value => value == partition),
                        It.Is <EventPosition>(value => value == eventPosition),
                        It.IsAny <TimeSpan>(),
                        It.IsAny <uint>(),
                        It.Is <long?>(value => value == ownerLevel),
                        It.Is <bool>(value => value == trackLastEnqueued),
                        It.IsAny <CancellationToken>()),
                    Times.Exactly(1 + retryOptions.MaximumRetries));
        }
Пример #30
0
        public static async Task ActivityWithRetry_NullRetryOptions([OrchestrationTrigger] DurableOrchestrationContext ctx)
        {
            string message = ctx.GetInput <string>();

            if (string.IsNullOrEmpty(message))
            {
                // This throw happens directly in the orchestration.
                throw new ArgumentNullException(nameof(message));
            }

            RetryOptions options = null;

            // This throw happens in the implementation of an activity.
            await ctx.CallActivityWithRetryAsync(nameof(TestActivities.ThrowActivity), options, message);
        }