Code Monkey home page Code Monkey logo

trybot's Introduction

Trybot

Appveyor build status Travis CI build status Tests coverage Sourcelink

Trybot is a transient fault handling framework including such resiliency solutions as Retry, Timeout, Fallback, Rate limit, and Circuit Breaker. The framework is extendable with custom, user-defined bots.

Github (stable) NuGet (stable) Fuget (stable) NuGet (pre-release)
Github release NuGet Version Trybot on fuget.org Nuget pre-release

Bots

  • Retry - Allows configuring auto re-execution of an operation based on exceptions it throws or on its return value.

  • Timeout - Ensures that the caller won't have to wait indefinitely for an operation to finish by setting a maximum time range within the given operation should be executed.

  • Fallback - Handles faults by executing an alternative operation when the original one is failing, also provides the ability to produce an alternative result value when the actual operation is not able to do it.

  • Circuit breaker - When the number of failures exceeds a given threshold, this bot prevents the continuous re-execution of the failing operation by blocking the traffic for a configured amount of time. This usually could give some break to the remote resource to heal itself properly.

  • Rate limit - Controls the rate of the operations by specifying a maximum amount of executions within a given time window.

Supported Platforms

  • .NET 4.5 and above
  • .NET Core
  • Mono
  • Universal Windows Platform
  • Xamarin (Android/iOS/Mac)
  • Unity

Usage

During the configuration of a bot policy, you can chain different bots to each other.

policy.Configure(policyConfig => policyConfig
    .CircuitBreaker(circuitBreakerConfig => circuitBreakerConfig
        .DurationOfOpen(TimeSpan.FromSeconds(10))
        .BrakeWhenExceptionOccurs(exception => exception is HttpRequestException),
            strategyConfig => strategyConfig
                .FailureThresholdBeforeOpen(5)
                .SuccessThresholdInHalfOpen(2))

    .Retry(retryConfig => retryConfig
        .WithMaxAttemptCount(5)
        .WhenExceptionOccurs(exception => exception is HttpRequestException)
        .WaitBetweenAttempts((attempt, exception) => 
        {
            if(exception is CircuitOpenException cbException)
                return TimeSpan.FromSeconds(cbException.OpenDuration);

            return TimeSpan.FromSeconds(Math.Pow(2, attempt);
        })))

    .Timeout(timeoutConfig => timeoutConfig
        .After(TimeSpan.FromSeconds(120))));

The handling order of the given operation would be the same as the configuration order from top to bottom. That means in the example above that the circuit breaker will try to execute the given operation first, then if it fails, the retry bot will start to re-execute it until the timeout bot is not signaling a cancellation.

Then you can execute the configured policy:

  • With cancellation:

    var tokenSource = new CancellationTokenSource();
    policy.Execute((context, cancellationToken) => DoSomeCancellableOperation(cancellationToken), tokenSource.Token);
  • With a custom correlation id:

    var correlationId = Guid.NewGuid();
    policy.Execute((context, cancellationToken) => DoSomeOperationWithCorrelationId(context.CorrelationId), correlationId);

    Without setting a custom correlation id, the framework will always generate a unique one for every policy execution.

  • Synchronously:

    // Without lambda parameters
    policy.Execute(() => DoSomeOperation());
    
    // Or with lambda parameters
    policy.Execute((context, cancellationToken) => DoSomeOperation());
  • Asynchronously:

    // Without lambda parameters
    await policy.ExecuteAsync(() => DoSomeAsyncOperation());
    
    // Or with lambda parameters
    await policy.ExecuteAsync((context, cancellationToken) => DoSomeAsyncOperation());

You can also create your custom bots as described here.

Contact & Support

  • Join the chat at https://gitter.im/z4kn4fein/trybot
  • Create an issue for bug reports, feature requests, or questions.
  • Add a ⭐️ to support the project!

Extensions

Documentation

trybot's People

Contributors

configcat-developer avatar z4kn4fein avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

trybot's Issues

Feature Request: OnRetryLimitReached

Could we have an OnRetyLimitExceeded() method? That is called after a retry is completed successfully?

I am using TryBot Retry together with Stateless (A StateMachine Library) and I need to be able to signal to the state machine that an all of the retries failed.

I can use a FallBack and catch Trybot.Retry.Exceptions.MaxRetryAttemptsReachedException but it seems a little messy for my purpose.

Sample usage.

var policyForCommands = new BotPolicy();

policyForCommands.Configure(config => config
	.Retry(retryconfig => retryconfig
		.WhenExceptionOccurs(exception => exception is Exception)
		.WithMaxAttemptCount(5)
		.OnRetry((exception, context) =>
		{
			Console.WriteLine("Retrying ");
			//** StateMachine Change State To "ErrorOccured"
		})
		.OnRetryLimitExceeded((Context) => 
		{
			Console.WriteLine("All Retries Failed");
			//** StateMachine Change State To "TryingToReconnect"
		})
		)
);

Feature Request: OnRetrySuccess

Could we have an OnRetrySuccess() method? That is called after a retry is completed successfully?

I am using TryBot Retry together with Stateless (A StateMachine Library) and I need to beable to signal to the statemachine that a retry succeeded.

Sample usage.

var policyForCommands = new BotPolicy();

policyForCommands.Configure(config => config
	.Retry(retryconfig => retryconfig
		.WhenExceptionOccurs(exception => exception is Exception)
		.WithMaxAttemptCount(5)
		.OnRetry((exception, context) =>
		{
			Console.WriteLine("Retrying ");
			//** StateMachine Change State To "ErrorOccured"
		})
		.OnRetrySuccess((Context) => 
		{
			Console.WriteLine("Retry Succeeded");
			//** StateMachine Change State To "Connected"
		})
		)
	.Fallback(fallbackConfig => fallbackConfig
		.WhenExceptionOccurs((exception) => exception is Trybot.Retry.Exceptions.MaxRetryAttemptsReachedException)
		.OnFallback((exception, context) =>
		{
			Console.WriteLine("Retries Failed");
			//** StateMachine Change State To "TryingToReconnect"
		})
		)
);

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.