public void RetryForeverActionTrue()
        {
            // Arrange.
            int i          = 0;
            int zero       = 0;
            int iterations = 10;

            Action func = () =>
            {
                i += 1;
                if (i != iterations)
                {
                    int x = i / zero;
                }
            };

            // Act.
            var result = Retrier.Init()
                         .WithMsWaitOf(0)
                         .RetryUntilSuccessful()
                         .Invoke(func);

            // Assert.
            Assert.Equal(iterations, result.RetryInfo.Executions);
            Assert.IsType <DivideByZeroException>(result.RetryInfo.Exceptions.FirstOrDefault());
            Assert.Equal(iterations - 1, result.RetryInfo.Exceptions.Count());
            Assert.False(result.Successful);
        }
        public void RetryForeverFunctionTrue()
        {
            // Arrange.
            int i              = 0;
            int zero           = 0;
            int expectedReturn = 1101;
            int iterations     = 10;

            Func <int> func = () =>
            {
                i += 1;
                if (i == iterations)
                {
                    return(expectedReturn);
                }

                return(i / zero);
            };

            // Act.
            var result = Retrier.Init()
                         .WithMsWaitOf(0)
                         .RetryUntilSuccessful()
                         .Invoke(func);

            // Assert.
            Assert.Equal(expectedReturn, result.Result);
            Assert.Equal(iterations, result.RetryInfo.Executions);
            Assert.IsType <DivideByZeroException>(result.RetryInfo.Exceptions.FirstOrDefault());
            Assert.Equal(iterations - 1, result.RetryInfo.Exceptions.Count());
            Assert.False(result.Successful);
        }
示例#3
0
        private void ValidateSequencePage(IWebElement table, WebDriverWait wait)
        {
            Retrier.RetryAsync(() =>
            {
                table    = wait.Until(ExpectedConditions.ElementIsVisible(By.Id(Strings.Id.ViewUsageTable)));
                var elms = table.FindElements(By.TagName("tr"));
                IntegrationTestBase.Log($"View usage table row count: {elms.Count}");
                Assert.IsTrue(elms.Count > 1, "View usage table does not have at least one row");
            }, TimeSpan.FromMilliseconds(1000), 30).GetAwaiter().GetResult();

            var rows = table.FindElements(By.TagName("tr"));

            if (rows.Count > 1)
            {
                var cells = rows[1].FindElements(By.TagName("td"));

                var link = cells[1].FindElement(By.TagName("a"));

                link.ClickWrapper(this.Driver);

                Retrier.RetryAsync(() =>
                {
                    var sequenceTable = wait.Until(ExpectedConditions.ElementIsVisible(By.Id(Strings.Id.SequenceHistoryTable)));
                    var sequenceRows  = sequenceTable.FindElements(By.TagName("tr"));
                    Assert.IsTrue(sequenceRows.Count > 1, $"Sequence table does not contain sequence elements. [{sequenceTable.Text}]"); //includes header
                }, TimeSpan.FromMilliseconds(1000), 30).GetAwaiter().GetResult();
            }
        }
        /// <summary>
        /// Returns a (paginated) list of logs for a given work request.
        ///
        /// </summary>
        /// <param name="request">The request object containing the details to send. Required.</param>
        /// <param name="retryConfiguration">The retry configuration that will be used by to send this request. Optional.</param>
        /// <param name="cancellationToken">The cancellation token to cancel this operation. Optional.</param>
        /// <returns>A response object containing details about the completed operation</returns>
        public async Task <ListWorkRequestLogsResponse> ListWorkRequestLogs(ListWorkRequestLogsRequest request, RetryConfiguration retryConfiguration = null, CancellationToken cancellationToken = default)
        {
            logger.Trace("Called listWorkRequestLogs");
            Uri                uri            = new Uri(this.restClient.GetEndpoint(), System.IO.Path.Combine(basePathWithoutHost, "/workRequests/{workRequestId}/logs".Trim('/')));
            HttpMethod         method         = new HttpMethod("Get");
            HttpRequestMessage requestMessage = Converter.ToHttpRequestMessage(uri, method, request);

            requestMessage.Headers.Add("Accept", "application/json");
            GenericRetrier      retryingClient = Retrier.GetPreferredRetrier(retryConfiguration, this.retryConfiguration);
            HttpResponseMessage responseMessage;

            try
            {
                if (retryingClient != null)
                {
                    responseMessage = await retryingClient.MakeRetryingCall(this.restClient.HttpSend, requestMessage, cancellationToken);
                }
                else
                {
                    responseMessage = await this.restClient.HttpSend(requestMessage);
                }

                return(Converter.FromHttpResponseMessage <ListWorkRequestLogsResponse>(responseMessage));
            }
            catch (Exception e)
            {
                logger.Error($"ListWorkRequestLogs failed with error: {e.Message}");
                throw;
            }
        }
示例#5
0
        public Installer Import(Assembly assembly, string packageName, string targetPath = null)
        {
            var unpackTarget = Path.Combine(WorkingDirectory ?? string.Empty, "import");

            // prepare package: extract it to the file system
            var packageFolder = UnpackEmbeddedPackage(assembly, packageName, unpackTarget);

            Import(packageFolder, targetPath);

            // cleanup, but do not wait for the result
            Task.Run(() =>
                     Retrier.RetryAsync(5, 3000, () =>
            {
                Directory.Delete(packageFolder, true);
                return(Task.CompletedTask);
            }, (i, exception) =>
            {
                if (exception == null)
                {
                    SnTrace.System.Write($"Package {packageFolder} has been deleted successfully.");
                    return(true);
                }

                // last iteration
                if (i == 1)
                {
                    SnTrace.System.WriteError($"Package {packageFolder} could not be deleted after several retries.");
                }

                return(false);
            }));

            return(this);
        }
示例#6
0
        /// <summary>
        /// Gets the content of an artifact with a specified &#x60;artifactPath&#x60; and &#x60;version&#x60;.
        /// </summary>
        /// <param name="request">The request object containing the details to send. Required.</param>
        /// <param name="retryConfiguration">The retry configuration that will be used by to send this request. Optional.</param>
        /// <param name="cancellationToken">The cancellation token to cancel this operation. Optional.</param>
        /// <returns>A response object containing details about the completed operation</returns>
        /// <example>Click <a href="https://docs.cloud.oracle.com/en-us/iaas/tools/dot-net-examples/latest/genericartifactscontent/GetGenericArtifactContentByPath.cs.html">here</a> to see an example of how to use GetGenericArtifactContentByPath API.</example>
        public async Task <GetGenericArtifactContentByPathResponse> GetGenericArtifactContentByPath(GetGenericArtifactContentByPathRequest request, RetryConfiguration retryConfiguration = null, CancellationToken cancellationToken = default)
        {
            logger.Trace("Called getGenericArtifactContentByPath");
            Uri                uri            = new Uri(this.restClient.GetEndpoint(), System.IO.Path.Combine(basePathWithoutHost, "/generic/repositories/{repositoryId}/artifactPaths/{artifactPath}/versions/{version}/content".Trim('/')));
            HttpMethod         method         = new HttpMethod("GET");
            HttpRequestMessage requestMessage = Converter.ToHttpRequestMessage(uri, method, request);

            requestMessage.Headers.Add("Accept", "application/octet-stream");
            GenericRetrier      retryingClient = Retrier.GetPreferredRetrier(retryConfiguration, this.retryConfiguration);
            HttpResponseMessage responseMessage;

            try
            {
                if (retryingClient != null)
                {
                    responseMessage = await retryingClient.MakeRetryingCall(this.restClient.HttpSend, requestMessage, cancellationToken).ConfigureAwait(false);
                }
                else
                {
                    responseMessage = await this.restClient.HttpSend(requestMessage).ConfigureAwait(false);
                }
                this.restClient.CheckHttpResponseMessage(requestMessage, responseMessage);

                return(Converter.FromHttpResponseMessage <GetGenericArtifactContentByPathResponse>(responseMessage));
            }
            catch (Exception e)
            {
                logger.Error($"GetGenericArtifactContentByPath failed with error: {e.Message}");
                throw;
            }
        }
        public void InMemDb_Core_TextPropertyWrite()
        {
            Test(() =>
            {
                // ARRANGE
                var propertyName = "Education";
                var testValue    = "High school 46";

                Retrier.Retry(3, 200, typeof(NodeIsOutOfDateException), () =>
                {
                    var admin = Node.Load <User>(Identifiers.AdministratorUserId);

                    Assert.AreEqual(DataType.Text, PropertyType.GetByName(propertyName).DataType);
                    Assert.AreNotEqual(testValue, admin.GetProperty <string>(propertyName));

                    // ACTION
                    admin.SetProperty(propertyName, testValue);
                    admin.Save();

                    // ASSERT
                    admin = Node.Load <User>(Identifiers.AdministratorUserId);
                    Assert.AreEqual(testValue, admin.GetProperty <string>(propertyName));
                });
            });
        }
示例#8
0
        /// <summary>
        /// Create the Kubeconfig YAML for a cluster.
        /// </summary>
        /// <param name="request">The request object containing the details to send. Required.</param>
        /// <param name="retryConfiguration">The retry configuration that will be used by to send this request. Optional.</param>
        /// <param name="cancellationToken">The cancellation token to cancel this operation. Optional.</param>
        /// <returns>A response object containing details about the completed operation</returns>
        public async Task <CreateKubeconfigResponse> CreateKubeconfig(CreateKubeconfigRequest request, RetryConfiguration retryConfiguration = null, CancellationToken cancellationToken = default)
        {
            logger.Trace("Called createKubeconfig");
            Uri                uri            = new Uri(this.restClient.GetEndpoint(), System.IO.Path.Combine(basePathWithoutHost, "/clusters/{clusterId}/kubeconfig/content".Trim('/')));
            HttpMethod         method         = new HttpMethod("Post");
            HttpRequestMessage requestMessage = Converter.ToHttpRequestMessage(uri, method, request);

            requestMessage.Headers.Add("Accept", "application/x-yaml");
            GenericRetrier      retryingClient = Retrier.GetPreferredRetrier(retryConfiguration, this.retryConfiguration);
            HttpResponseMessage responseMessage;

            try
            {
                if (retryingClient != null)
                {
                    responseMessage = await retryingClient.MakeRetryingCall(this.restClient.HttpSend, requestMessage, cancellationToken);
                }
                else
                {
                    responseMessage = await this.restClient.HttpSend(requestMessage);
                }

                return(Converter.FromHttpResponseMessage <CreateKubeconfigResponse>(responseMessage));
            }
            catch (Exception e)
            {
                logger.Error($"CreateKubeconfig failed with error: {e.Message}");
                throw;
            }
        }
示例#9
0
        internal static WopiDiscovery GetInstance(string officeOnlineUrl)
        {
            return(Instances.GetOrAdd(officeOnlineUrl.TrimEnd('/'), oosUrl => new Lazy <WopiDiscovery>(() =>
            {
                var discoveryXml = new XmlDocument();

                Retrier.Retry(3, 500, () =>
                {
                    using (var client = new HttpClient())
                    {
                        using (var discoveryStream = client.GetAsync($"{oosUrl}/hosting/discovery")
                                                     .Result.Content.ReadAsStreamAsync().Result)
                        {
                            discoveryXml.Load(discoveryStream);
                        }
                    }
                }, (i, ex) => ex == null || i > 3);

                if (discoveryXml.DocumentElement == null)
                {
                    SnLog.WriteWarning($"Could not connect to Office Online Server {oosUrl} for available actions.");
                }
                else
                {
                    SnLog.WriteInformation($"Connected to Office Online Server {oosUrl} for available actions.");
                }


                return FromXmlDocument(discoveryXml);
            })).Value);
        }
示例#10
0
        /// <summary>
        /// Moves an SDDC into a different compartment within the same tenancy. For information
        /// about moving resources between compartments, see
        /// [Moving Resources to a Different Compartment](https://docs.cloud.oracle.com/iaas/Content/Identity/Tasks/managingcompartments.htm#moveRes).
        ///
        /// </summary>
        /// <param name="request">The request object containing the details to send. Required.</param>
        /// <param name="retryConfiguration">The retry configuration that will be used by to send this request. Optional.</param>
        /// <param name="cancellationToken">The cancellation token to cancel this operation. Optional.</param>
        /// <returns>A response object containing details about the completed operation</returns>
        /// <example>Click <a href="https://docs.cloud.oracle.com/en-us/iaas/tools/dot-net-examples/latest/ocvp/ChangeSddcCompartment.cs.html">here</a> to see an example of how to use ChangeSddcCompartment API.</example>
        public async Task <ChangeSddcCompartmentResponse> ChangeSddcCompartment(ChangeSddcCompartmentRequest request, RetryConfiguration retryConfiguration = null, CancellationToken cancellationToken = default)
        {
            logger.Trace("Called changeSddcCompartment");
            Uri                uri            = new Uri(this.restClient.GetEndpoint(), System.IO.Path.Combine(basePathWithoutHost, "/sddcs/{sddcId}/actions/changeCompartment".Trim('/')));
            HttpMethod         method         = new HttpMethod("POST");
            HttpRequestMessage requestMessage = Converter.ToHttpRequestMessage(uri, method, request);

            requestMessage.Headers.Add("Accept", "application/json");
            GenericRetrier      retryingClient = Retrier.GetPreferredRetrier(retryConfiguration, this.retryConfiguration);
            HttpResponseMessage responseMessage;

            try
            {
                if (retryingClient != null)
                {
                    responseMessage = await retryingClient.MakeRetryingCall(this.restClient.HttpSend, requestMessage, cancellationToken).ConfigureAwait(false);
                }
                else
                {
                    responseMessage = await this.restClient.HttpSend(requestMessage).ConfigureAwait(false);
                }
                this.restClient.CheckHttpResponseMessage(requestMessage, responseMessage);

                return(Converter.FromHttpResponseMessage <ChangeSddcCompartmentResponse>(responseMessage));
            }
            catch (Exception e)
            {
                logger.Error($"ChangeSddcCompartment failed with error: {e.Message}");
                throw;
            }
        }
示例#11
0
        public async Task SetSystemTimeAsync(CancellationToken ct)
        {
            DateTime now = DateTime.UtcNow;

            try
            {
                await Retrier.RetryAsync(() =>
                {
                    now = ntpService.GetNetworkTime();
                    logger.LogInfo().WithCategory(LogCategory.Manager).WithMessage($"NTP time: {now} UTC: {now.ToUniversalTime()}").Commit();
                    now = now.ToUniversalTime();
                }, logger, 10, "Read NTP", true, ct);

                SetSystemTime(now);
                await Retrier.RetryAsync(() =>
                {
                    logger.LogInfo().WithCategory(LogCategory.Manager).WithMessage("Writing to RTC").Commit();
                    wittyPiService.RtcDateTime = now;
                }, logger, int.MaxValue, "Read RTC", true, ct);
            }
            catch (Exception ex)
            {
                now = DateTime.UtcNow;
                logger.LogWarn().WithCategory(LogCategory.Manager).WithMessage($"Failed to read NTP or set it, will use local {now}")
                .WithException(ex).Commit();
            }
            referenceNow = now.AddMinutes(-settings.InitialDelay);
            logger.LogInfo().WithCategory(LogCategory.Manager).WithMessage($"RTC (referenceNow) reset to : {referenceNow.ToLocalTime()}").Commit();
        }
示例#12
0
        /// <summary>
        /// Uploads an artifact. Provide &#x60;artifactPath&#x60;, &#x60;version&#x60; and content. Avoid entering confidential information when you define the path and version.
        /// </summary>
        /// <param name="request">The request object containing the details to send. Required.</param>
        /// <param name="retryConfiguration">The retry configuration that will be used by to send this request. Optional.</param>
        /// <param name="cancellationToken">The cancellation token to cancel this operation. Optional.</param>
        /// <returns>A response object containing details about the completed operation</returns>
        /// <example>Click <a href="https://docs.cloud.oracle.com/en-us/iaas/tools/dot-net-examples/latest/genericartifactscontent/PutGenericArtifactContentByPath.cs.html">here</a> to see an example of how to use PutGenericArtifactContentByPath API.</example>
        public async Task <PutGenericArtifactContentByPathResponse> PutGenericArtifactContentByPath(PutGenericArtifactContentByPathRequest request, RetryConfiguration retryConfiguration = null, CancellationToken cancellationToken = default)
        {
            logger.Trace("Called putGenericArtifactContentByPath");
            Uri                uri            = new Uri(this.restClient.GetEndpoint(), System.IO.Path.Combine(basePathWithoutHost, "/generic/repositories/{repositoryId}/artifactPaths/{artifactPath}/versions/{version}/content".Trim('/')));
            HttpMethod         method         = new HttpMethod("PUT");
            HttpRequestMessage requestMessage = Converter.ToHttpRequestMessage(uri, method, request);

            requestMessage.Headers.Add("Accept", "application/json");
            requestMessage.Properties.Add(Oci.Common.Http.Signing.SigningStrategy.SIGNING_STRATEGY_PROPERTY_NAME_KEY, Oci.Common.Http.Signing.SigningStrategy.EXCLUDE_BODY);
            GenericRetrier      retryingClient = Retrier.GetPreferredRetrier(retryConfiguration, this.retryConfiguration);
            HttpResponseMessage responseMessage;

            try
            {
                if (retryingClient != null)
                {
                    responseMessage = await retryingClient.MakeRetryingCall(this.restClient.HttpSend, requestMessage, cancellationToken).ConfigureAwait(false);
                }
                else
                {
                    responseMessage = await this.restClient.HttpSend(requestMessage).ConfigureAwait(false);
                }
                this.restClient.CheckHttpResponseMessage(requestMessage, responseMessage);

                return(Converter.FromHttpResponseMessage <PutGenericArtifactContentByPathResponse>(responseMessage));
            }
            catch (Exception e)
            {
                logger.Error($"PutGenericArtifactContentByPath failed with error: {e.Message}");
                throw;
            }
        }
        /// <summary>
        /// Deletes an autoscaling policy for the specified autoscaling configuration.
        /// </summary>
        /// <param name="request">The request object containing the details to send. Required.</param>
        /// <param name="retryConfiguration">The retry configuration that will be used by to send this request. Optional.</param>
        /// <param name="cancellationToken">The cancellation token to cancel this operation. Optional.</param>
        /// <returns>A response object containing details about the completed operation</returns>
        /// <example>Click <a href="https://docs.cloud.oracle.com/en-us/iaas/tools/dot-net-examples/latest/autoscaling/DeleteAutoScalingPolicy.cs.html">here</a> to see an example of how to use DeleteAutoScalingPolicy API.</example>
        public async Task <DeleteAutoScalingPolicyResponse> DeleteAutoScalingPolicy(DeleteAutoScalingPolicyRequest request, RetryConfiguration retryConfiguration = null, CancellationToken cancellationToken = default)
        {
            logger.Trace("Called deleteAutoScalingPolicy");
            Uri                uri            = new Uri(this.restClient.GetEndpoint(), System.IO.Path.Combine(basePathWithoutHost, "/autoScalingConfigurations/{autoScalingConfigurationId}/policies/{autoScalingPolicyId}".Trim('/')));
            HttpMethod         method         = new HttpMethod("DELETE");
            HttpRequestMessage requestMessage = Converter.ToHttpRequestMessage(uri, method, request);

            requestMessage.Headers.Add("Accept", "application/json");
            GenericRetrier      retryingClient = Retrier.GetPreferredRetrier(retryConfiguration, this.retryConfiguration);
            HttpResponseMessage responseMessage;

            try
            {
                if (retryingClient != null)
                {
                    responseMessage = await retryingClient.MakeRetryingCall(this.restClient.HttpSend, requestMessage, cancellationToken).ConfigureAwait(false);
                }
                else
                {
                    responseMessage = await this.restClient.HttpSend(requestMessage).ConfigureAwait(false);
                }
                this.restClient.CheckHttpResponseMessage(requestMessage, responseMessage);

                return(Converter.FromHttpResponseMessage <DeleteAutoScalingPolicyResponse>(responseMessage));
            }
            catch (Exception e)
            {
                logger.Error($"DeleteAutoScalingPolicy failed with error: {e.Message}");
                throw;
            }
        }
示例#14
0
        /// <summary>
        /// For a given compartmentId, resource limit name, and scope, returns the following:
        ///   * The number of available resources associated with the given limit.
        ///   * The usage in the selected compartment for the given limit.
        ///   Note that not all resource limits support this API. If the value is not available, the API returns a 404 response.
        ///
        /// </summary>
        /// <param name="request">The request object containing the details to send. Required.</param>
        /// <param name="retryConfiguration">The retry configuration that will be used by to send this request. Optional.</param>
        /// <param name="cancellationToken">The cancellation token to cancel this operation. Optional.</param>
        /// <returns>A response object containing details about the completed operation</returns>
        /// <example>Click <a href="https://docs.cloud.oracle.com/en-us/iaas/tools/dot-net-examples/latest/limits/GetResourceAvailability.cs.html">here</a> to see an example of how to use GetResourceAvailability API.</example>
        public async Task <GetResourceAvailabilityResponse> GetResourceAvailability(GetResourceAvailabilityRequest request, RetryConfiguration retryConfiguration = null, CancellationToken cancellationToken = default)
        {
            logger.Trace("Called getResourceAvailability");
            Uri                uri            = new Uri(this.restClient.GetEndpoint(), System.IO.Path.Combine(basePathWithoutHost, "/20190729/services/{serviceName}/limits/{limitName}/resourceAvailability".Trim('/')));
            HttpMethod         method         = new HttpMethod("GET");
            HttpRequestMessage requestMessage = Converter.ToHttpRequestMessage(uri, method, request);

            requestMessage.Headers.Add("Accept", "application/json");
            GenericRetrier      retryingClient = Retrier.GetPreferredRetrier(retryConfiguration, this.retryConfiguration);
            HttpResponseMessage responseMessage;

            try
            {
                if (retryingClient != null)
                {
                    responseMessage = await retryingClient.MakeRetryingCall(this.restClient.HttpSend, requestMessage, cancellationToken).ConfigureAwait(false);
                }
                else
                {
                    responseMessage = await this.restClient.HttpSend(requestMessage).ConfigureAwait(false);
                }
                this.restClient.CheckHttpResponseMessage(requestMessage, responseMessage);

                return(Converter.FromHttpResponseMessage <GetResourceAvailabilityResponse>(responseMessage));
            }
            catch (Exception e)
            {
                logger.Error($"GetResourceAvailability failed with error: {e.Message}");
                throw;
            }
        }
        protected void ClickOnProgramMenuButton(string appName, string buttonSuffix)
        {
            try
            {
                Retrier.RetryAsync(() =>
                {
                    WebDriverWait wait  = new WebDriverWait(this.Driver, TimeSpan.FromSeconds(15));
                    IWebElement element = this.Driver.TryFind(By.Id($"{appName}_menu"));

                    IntegrationTestBase.Log($"Found { appName}_menu button");

                    var prgMenu = wait.Until(ExpectedConditions.ElementToBeClickable(element));
                    prgMenu.ClickWrapper(this.Driver);
                    IntegrationTestBase.Log($"Clicked { appName}_menu button");


                    IWebElement link = this.Driver.TryFind(By.Id(appName + buttonSuffix));
                    IntegrationTestBase.Log($"Found { appName}{buttonSuffix} button");

                    link = wait.Until(ExpectedConditions.ElementToBeClickable(link));

                    link.ClickWrapper(this.Driver);
                }, TimeSpan.FromMilliseconds(500), 3).GetAwaiter().GetResult();
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException($"Failed to click on button {buttonSuffix} for app {appName}.", ex);
            }
        }
示例#16
0
 public static void MainMethod()
 {
     Retrier.Retry(() => RetrierDemoWithoutReturnFunction());
     //string retrierResult1 = Retrier.Retry<string>(() => RetrierDemoWithReturnFunction());
     //string retrierResult2 = Retrier.Retry<string, Exception>(() => RetrierDemoWithReturnFunction());
     //Console.WriteLine(retrierResult1);
     //Console.WriteLine(retrierResult2);
 }
示例#17
0
        public void RetryForeverConfigFalse()
        {
            // Arrange & Act.
            var config = Retrier.Init();

            // Assert.
            Assert.False(config.RetryForever);
        }
示例#18
0
 public async Task <IEnumerable <DailyStockData> > GetDailyStockData(string symbol)
 {
     return(await Retrier.Retry(
                async() => await TryGetDailyStockData(symbol),
                message => _logger.LogInformation(message),
                _apiConfig.MaxRetries,
                _apiConfig.InitialDelay
                ));
 }
示例#19
0
        public void InitRetryConfig()
        {
            // Arrange && Act.
            var config = Retrier.Init(TimeSpan.FromMilliseconds(200), 10);

            // Assert.
            Assert.Equal(200, config.WaitBetweenRetries.Milliseconds);
            Assert.Equal(10, config.MaxRetries);
        }
示例#20
0
        public void RetrierUnitTest_Success()
        {
            int      num_ur_per_kr = 10;
            int      num_kr        = 2;
            DateTime start         = DateTime.Now;

            Amazon.Kinesis.Model.PutRecordsResponse response = new Amazon.Kinesis.Model.PutRecordsResponse();
            response.HttpStatusCode    = System.Net.HttpStatusCode.OK;
            response.FailedRecordCount = 0;
            response.Records           = new System.Collections.Generic.List <Amazon.Kinesis.Model.PutRecordsResultEntry>();
            response.Records.Add(new Amazon.Kinesis.Model.PutRecordsResultEntry()
            {
                SequenceNumber = "1234", ShardId = "shardId-000000000000"
            });
            response.Records.Add(new Amazon.Kinesis.Model.PutRecordsResultEntry()
            {
                SequenceNumber = "4567", ShardId = "shardId-000000000001"
            });
            AwsKinesisResult result = make_prr_ctx(num_kr, num_ur_per_kr, null, response, start, start.AddMilliseconds(5));


            int     count   = 0;
            Retrier retrier = new Retrier(
                new KPLNETInterface.KPLNETConfiguration(),
                (ur) =>
            {
                var attempts = ur.Attempts();
                Assert.AreEqual(attempts.Count, 1);
                Assert.IsTrue(attempts[0].Start() == start);
                Assert.IsTrue(attempts[0].End() == start.AddMilliseconds(5));
                Assert.IsTrue(attempts[0].Success());

                if (count++ / num_ur_per_kr == 0)
                {
                    Assert.AreEqual(attempts[0].Sequence_number(), "1234");
                    Assert.AreEqual(attempts[0].Shard_id(), "shardId-000000000000");
                }
                else
                {
                    Assert.AreEqual(attempts[0].Sequence_number(), "4567");
                    Assert.AreEqual(attempts[0].Shard_id(), "shardId-000000000001");
                }
            },
                (ur) =>
            {
                Assert.Fail("Retry should not be called");
            },
                (dt) =>
            {
                Assert.Fail("Shard map invalidate should not be called");
            });

            retrier.put(result);

            Assert.AreEqual(count, num_kr * num_ur_per_kr);
        }
示例#21
0
        public void RetryAsyncAction()
        {
            // Arrange && Act.
            var result = Retrier.Init()
                         .Invoke(async() => await FakeService.DoFakeCalculationsAsync());

            // Assert.
            Assert.Equal(1, result.RetryInfo.Executions);
            Assert.True(result.Successful);
        }
示例#22
0
        public void InitDefaultRetryConfig()
        {
            // Arrange
            // Act.
            var config = Retrier.Init();

            // Assert.
            Assert.Equal(0, config.WaitBetweenRetries.Milliseconds);
            Assert.Equal(3, config.MaxRetries);
        }
示例#23
0
        public void RetryForeverConfigTrue()
        {
            // Arrange & Act.
            var config = Retrier.Init()
                         .WithMsWaitOf(0)
                         .RetryUntilSuccessful();

            // Assert.
            Assert.True(config.RetryForever);
        }
        private void ExecuteCommand(
            string storedProcedureName,
            DbParameter[] parameters,
            Action <DbCommand> action,
            bool closeConnection)
        {
            void InternalAction()
            {
                DbCommand command = CreateCommand(storedProcedureName, parameters);

                try
                {
                    if (_connection.State != ConnectionState.Open)
                    {
                        _connection.Open();
                    }

                    DateTime startUtc = DateTime.UtcNow;
                    action.Invoke(command);
                    var executionTimeSeconds = (int)DateTime.UtcNow.Subtract(startUtc).TotalSeconds;

                    if (executionTimeSeconds >= Settings.Instance.DBContextSetting.LongRunningStoredProcedureTimeSeconds)
                    {
                        OnLongRunningStoredProcedure?.Invoke(
                            this,
                            new LongRunningStoredProcedureEventArgs(storedProcedureName, executionTimeSeconds));
                    }
                }
                catch (Exception exception)
                {
                    //DbConnection.ClearPool(_connection);
                    ExceptionDispatchInfo.Capture(exception).Throw();
                }
                finally
                {
                    if (!InTransaction() && closeConnection)
                    {
                        DisposeConnection();
                    }
                }
            }

            if (InTransaction())
            {
                InternalAction();
            }
            else
            {
                Retrier.InvokeAction(
                    InternalAction,
                    Settings.Instance.DBContextSetting.RetriesNumber,
                    Settings.Instance.DBContextSetting.SleepBetweenRetriesMilliSeconds,
                    RetrierHelper.IsRetriableError);
            }
        }
示例#25
0
        public void RetryAsyncFunction()
        {
            // Arrange && Act.
            var result = Retrier.Init()
                         .Invoke(async() => await FakeService.GetHelloWorldAsync());

            // Assert.
            Assert.Equal("Hello world", result.Result.Result);
            Assert.Equal(1, result.RetryInfo.Executions);
            Assert.True(result.Successful);
        }
示例#26
0
        public void InitRetryConfigFluent()
        {
            // Arrange && Act.
            var config = Retrier.Init()
                         .WithNumberOfRetries(10)
                         .WithMsWaitOf(1000);

            // Assert.
            Assert.Equal(10, config.MaxRetries);
            Assert.Equal(1, config.WaitBetweenRetries.Seconds);
        }
示例#27
0
        private async STT.Task PutToCacheAsync(DatabaseUsage databaseUsage, File cached, CancellationToken cancel)
        {
            var resultBuilder = new StringBuilder();

            using (var writer = new StringWriter(resultBuilder))
                JsonSerializer.Create(SerializerSettings).Serialize(writer, databaseUsage);

            using (new SystemAccount())
            {
                cached ??= await CreateCacheFileAsync(cancel);

                if (cached == null)
                {
                    return;
                }

                var iteration = 0;

                try
                {
                    var serialized   = resultBuilder.ToString();
                    var cachedStream = !cached.IsNew ? cached.Binary?.GetStream() : null;
                    var cachedData   = cachedStream != null?RepositoryTools.GetStreamString(cachedStream) : string.Empty;

                    // save the content only if there was a change
                    if (string.Equals(serialized, cachedData))
                    {
                        return;
                    }

                    Retrier.Retry(5, 500, typeof(NodeIsOutOfDateException), () =>
                    {
                        iteration++;

                        // reload to have a fresh instance
                        if (!cached.IsNew && iteration > 1)
                        {
                            cached = Node.Load <File>(cached.Id);
                        }

                        cached.SetCachedData(CacheKey, databaseUsage);
                        cached.Binary.SetStream(RepositoryTools.GetStreamFromString(serialized));
                        cached.Save(SavingMode.KeepVersion);

                        _logger.LogTrace($"DatabaseUsage.cache has been saved. Iteration: {iteration}");
                    });
                }
                catch (Exception e)
                {
                    _logger.LogWarning(e, $"An error occurred during saving DatabaseUsage.cache in iteration {iteration}.");
                    // do nothing
                }
            }
        }
示例#28
0
 /// <summary>
 /// Creates the data storage
 /// </summary>
 public FileSystemDataBusStorage(string directoryPath, IRebusLoggerFactory rebusLoggerFactory, IRebusTime rebusTime)
 {
     if (rebusLoggerFactory == null)
     {
         throw new ArgumentNullException(nameof(rebusLoggerFactory));
     }
     _directoryPath = directoryPath ?? throw new ArgumentNullException(nameof(directoryPath));
     _rebusTime     = rebusTime ?? throw new ArgumentNullException(nameof(rebusTime));
     _log           = rebusLoggerFactory.GetLogger <FileSystemDataBusStorage>();
     _retrier       = new Retrier(rebusLoggerFactory);
 }
示例#29
0
        public void Retrier_Success_NoRetry()
        {
            RetryCallCounter = 0;

            Retrier.Retry(3, 10, typeof(InvalidOperationException), () =>
            {
                // run once without error
                Interlocked.Increment(ref RetryCallCounter);
            });

            Assert.AreEqual(1, RetryCallCounter, $"#1 Callback called {RetryCallCounter} times.");
        }
示例#30
0
        public void RetrierWithCondition_Fail_TooManyRetries()
        {
            RetryCallCounter = 0;

            var result = Retrier.Retry <int>(3, 10, () =>
            {
                Interlocked.Increment(ref RetryCallCounter);
                throw new InvalidOperationException();
            },
                                             (r, i, e) => e == null);

            Assert.AreEqual(default, result, "Wrong result: " + result);