|
1
|
|
|
package decorators |
|
2
|
|
|
|
|
3
|
|
|
import ( |
|
4
|
|
|
"context" |
|
5
|
|
|
"errors" |
|
6
|
|
|
|
|
7
|
|
|
"github.com/afex/hystrix-go/hystrix" |
|
8
|
|
|
|
|
9
|
|
|
"github.com/Permify/permify/internal/storage" |
|
10
|
|
|
base "github.com/Permify/permify/pkg/pb/base/v1" |
|
11
|
|
|
) |
|
12
|
|
|
|
|
13
|
|
|
// BundleReaderWithCircuitBreaker - Add circuit breaker behaviour to bundle reader |
|
14
|
|
|
type BundleReaderWithCircuitBreaker struct { |
|
15
|
|
|
delegate storage.BundleReader |
|
16
|
|
|
timeout int |
|
17
|
|
|
} |
|
18
|
|
|
|
|
19
|
|
|
// NewBundleReaderWithCircuitBreaker - Add circuit breaker behaviour to new bundle reader |
|
20
|
|
|
func NewBundleReaderWithCircuitBreaker(delegate storage.BundleReader, timeout int) *BundleReaderWithCircuitBreaker { |
|
21
|
|
|
return &BundleReaderWithCircuitBreaker{delegate: delegate, timeout: timeout} |
|
22
|
|
|
} |
|
23
|
|
|
|
|
24
|
|
|
// Read - Reads bundles from the repository |
|
25
|
|
|
func (r *BundleReaderWithCircuitBreaker) Read(ctx context.Context, tenantID, name string) (bundle *base.DataBundle, err error) { |
|
26
|
|
|
type circuitBreakerResponse struct { |
|
27
|
|
|
Bundle *base.DataBundle |
|
28
|
|
|
Error error |
|
29
|
|
|
} |
|
30
|
|
|
|
|
31
|
|
|
output := make(chan circuitBreakerResponse, 1) |
|
32
|
|
|
hystrix.ConfigureCommand("bundleReader.read", hystrix.CommandConfig{Timeout: r.timeout}) |
|
33
|
|
|
bErrors := hystrix.Go("bundleReader.read", func() error { |
|
34
|
|
|
bundle, err := r.delegate.Read(ctx, tenantID, name) |
|
35
|
|
|
output <- circuitBreakerResponse{Bundle: bundle, Error: err} |
|
36
|
|
|
return nil |
|
37
|
|
|
}, func(err error) error { |
|
38
|
|
|
return nil |
|
39
|
|
|
}) |
|
40
|
|
|
|
|
41
|
|
|
select { |
|
42
|
|
|
case out := <-output: |
|
43
|
|
|
return out.Bundle, out.Error |
|
44
|
|
|
case <-bErrors: |
|
45
|
|
|
return nil, errors.New(base.ErrorCode_ERROR_CODE_CIRCUIT_BREAKER.String()) |
|
46
|
|
|
} |
|
47
|
|
|
} |
|
48
|
|
|
|