Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
YoshiyukiMineo committed Jun 1, 2015
0 parents commit 0b26ff4
Show file tree
Hide file tree
Showing 6 changed files with 753 additions and 0 deletions.
8 changes: 8 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
language: go
go:
- 1.4
- tip
sudo: false
script:
- go test -v .
- cd example && go build -o http_breaker && ./http_breaker
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright 2015 Sony Corporation

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
121 changes: 121 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
gobreaker
=========

gobreaker implements the [Circuit Breaker pattern](https://msdn.microsoft.com/en-us/library/dn589784.aspx) in Go.

Installation
------------

```
go get github.com/sony/gobreaker
```

Usage
-----

The struct CircuitBreaker is a state machine to prevent sending requests that are likely to fail.
The function NewCircuitBreaker creates a new CircuitBreaker.

```go
func NewCircuitBreaker(st Settings) *CircuitBreaker
```

You can configure CircuitBreaker by the struct Settings:

```go
type Settings struct {
Name string
MaxRequests uint32
Interval time.Duration
Timeout time.Duration
ReadyToTrip func(counts Counts) bool
OnStateChange func(name string, from State, to State)
}
```

- Name is the name of the CircuitBreaker.

- MaxRequests is the maximum number of requests allowed to pass through
when the CircuitBreaker is half-open.
If MaxRequests is 0, the CircuitBreaker allows only 1 request.

- Interval is the cyclic period of the closed state
for the CircuitBreaker to clear the internal Counts, described later in this section.
If Interval is 0, the CircuitBreaker doesn't clear the internal Counts during the closed state.

- Timeout is the period of the open state,
after which the state of the CircuitBreaker becomes half-open.
If Timeout is 0, the timeout value of the CircuitBreaker is set to 60 seconds.

- ReadyToTrip is called with a copy of Counts whenever a request fails in the closed state.
If ReadyToTrip returns true, the CircuitBreaker will be placed into the open state.
If ReadyToTrip is nil, default ReadyToTrip is used.
Default ReadyToTrip returns true when the number of consecutive failures is more than 5.

- OnStateChange is called whenever the state of the CircuitBreaker changes.

The struct Counts holds the numbers of requests and their successes/failures:

```go
type Counts struct {
Requests uint32
TotalSuccesses uint32
TotalFailures uint32
ConsecutiveSuccesses uint32
ConsecutiveFailures uint32
}
```

CircuitBreaker clears the internal Counts either
on the change of the state or at the closed-state intervals.
Counts ignores the results of the requests sent before clearing.

CircuitBreaker can wrap any function to send a request:

```go
func (cb *CircuitBreaker) Execute(req func() (interface{}, error)) (interface{}, error)
```

The method Execute runs the given request if the CircuitBreaker accepts it.
Execute returns an error instantly if the CircuitBreaker rejects the request.
Otherwise, Execute returns the result of the request.
If a panic occurs in the request, the CircuitBreaker handles it as an error
and causes the same panic again.

Example
-------

```go
var cb *breaker.CircuitBreaker

func Get(url string) ([]byte, error) {
body, err := cb.Execute(func() (interface{}, error) {
resp, err := http.Get(url)
if err != nil {
return nil, err
}

defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}

return body, nil
})
if err != nil {
return nil, err
}

return body.([]byte), nil
}
```

See [example](https://github.com/sony/gobreaker/blob/master/example) for details.

License
-------

The MIT License (MIT)

See [LICENSE](https://github.com/sony/gobreaker/blob/master/LICENSE) for details.
55 changes: 55 additions & 0 deletions example/http_breaker.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
package main

import (
"fmt"
"io/ioutil"
"log"
"net/http"

"github.com/sony/gobreaker"
)

var cb *gobreaker.CircuitBreaker

func init() {
var st gobreaker.Settings
st.Name = "HTTP GET"
st.ReadyToTrip = func(counts gobreaker.Counts) bool {
failureRatio := float64(counts.TotalFailures) / float64(counts.Requests)
return counts.Requests >= 3 && failureRatio >= 0.6
}

cb = gobreaker.NewCircuitBreaker(st)
}

// Get wraps http.Get in CircuitBreaker.
func Get(url string) ([]byte, error) {
body, err := cb.Execute(func() (interface{}, error) {
resp, err := http.Get(url)
if err != nil {
return nil, err
}

defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}

return body, nil
})
if err != nil {
return nil, err
}

return body.([]byte), nil
}

func main() {
body, err := Get("http://www.google.com/robots.txt")
if err != nil {
log.Fatal(err)
}

fmt.Println("%s", string(body))
}
Loading

0 comments on commit 0b26ff4

Please sign in to comment.