Coder Social home page Coder Social logo

autobreaker's Introduction

autobreaker

autobreaker is a Scala library that wraps your objects and intercepts all methods returning Futures with a circuit breaker.

It is based on atmos and Akka's Circuit Breaker, using Java's Proxy to intercept method calls.

Usage

import com.unstablebuild.autobreaker._

trait MyService {
  def add(a: Int, b: Int): Future[Int]
}

class FailingService extends MyService {
  override def add(a: Int, b: Int): Future[Int] = Future.failed(new Exception("error"))
}

val realService: MyService = new FailingService
val serviceWithCircuitBreaker = AutoBreaker.proxy(realService)

// Make it fail a few times
(1 to 10).foreach { _ => serviceWithCircuitBreaker.add(11, 23) }

// Try again and see that the service isn't called
serviceWithCircuitBreaker.add(11, 23)
// [warn] e.c.CircuitBreakerProxy - Attempt 1 of operation interrupted: akka.pattern.CircuitBreakerOpenException: Circuit Breaker is open; calls are failing fast
// akka.pattern.CircuitBreakerOpenException: Circuit Breaker is open; calls are failing fast

Please check the unit tests for more examples.

Skipping a specific method

You can prevent a method from being intercept with the NoCircuitBreaker annotation. For example:

class AnotherImplementation extends MyService {
  @NoCircuitBreaker
  override def add(a: Int, b: Int): Future[Int] = Future.failed(new Exception("error"))
}

Install

To use it with SBT, add the following to your build.sbt file:

resolvers += Resolver.sonatypeRepo("public")

libraryDependencies += "com.unstablebuild" %% "autobreaker" % "0.5.6"

Configuration

The following settings (and their default values) are available:

case class CircuitBreakerSettings(
  totalAttempts: TerminationPolicy = 3.attempts,
  backoffPolicy: BackoffPolicy = LimitedExponentialBackoffPolicy(2.minutes, 1.second),
  maxFailures: Int = 5,
  callTimeout: FiniteDuration = 10.seconds,
  resetTimeout: FiniteDuration = 1.minute,
  knownError: Throwable => Boolean = _ => false
)

Please see atmos and akka documentations for further reference.

knownError is used to decide if, given an exception type returned by the method, it should be retried or not, or counted as a failure on the circuit breaker. This allows the usage of custom exceptions to communicate the users about errors that don't affect the used method. For instance, you can decide that an exception communicating validation issues should not be considered as bad as a failure when communicating with a downstream system.

Guice Integration

autobreaker-guice allows you to annotate your implementations with @WithCircuitBreaker and modify your Guice module to automatically wrap the generated objects.

In order to use it, you need to add the following to your dependencies:

libraryDependencies += "com.unstablebuild" %% "autobreaker-guice" % "0.5.6"

Afterwards, it can be used like this:

@WithCircuitBreaker
class DownstreamService extends MyService {
  override def add(a: Int, b: Int): Future[Int] = ???
}

class TestModule extends AbstractModule {
  override def configure(): Unit = bind(classOf[MyService]).to(classOf[DownstreamService])
}

val module = new TestModule()
val injector = Guice.createInjector(AutoBreakerGuice.prepare(module))
val service = injector.getInstance(classOf[MyService])

An ExecutionContext and Scheduler should be available on your bindings.

You can also use a AutoBreakerModule instead of AbstractModule, and that will call AutoBreakerGuice.prepare for you.

Settings

You can inject settings in two ways:

  1. Bind a CircuitBreakerSettings;
  2. Bind a named CircuitBreakerSettings.

For example:

bind(classOf[CircuitBreakerSettings])
          .toInstance(mySettings)

bind(classOf[CircuitBreakerSettings])
  .annotatedWith(Names.named("custom-conf"))
  .toInstance(mySettings)

To use named Settings, you can add the use named to the WithCircuitBreaker annotation:

@WithCircuitBreaker(name = "custom-conf")
class CustomNamedFailureTestService(error: Throwable) extends MyService { ... }

If a Settings instance with the given name is not found, the library will try to use an unnamed one. If it also can't fidn one, it will fall back to AutoBreaker.defaultSettings.

Release

./sbt test guice/test
./sbt publishSigned guice/publishSigned
./sbt sonatypeReleaseAll

autobreaker's People

Contributors

lucastorri avatar

Watchers

 avatar

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.