Passed
Push — master ( 4e9e72...8e2c0a )
by Tolga
03:36 queued 16s
created

decorators.NewTenantReaderWithCircuitBreaker   A

Complexity

Conditions 1

Size

Total Lines 2
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nop 2
dl 0
loc 2
rs 10
c 0
b 0
f 0
1
package decorators
2
3
import (
4
	"context"
5
6
	"github.com/afex/hystrix-go/hystrix"
7
	"github.com/pkg/errors"
8
9
	"github.com/Permify/permify/internal/storage"
10
	"github.com/Permify/permify/pkg/database"
11
	base "github.com/Permify/permify/pkg/pb/base/v1"
12
)
13
14
// TenantReaderWithCircuitBreaker - Add circuit breaker behaviour to tenant reader
15
type TenantReaderWithCircuitBreaker struct {
16
	delegate storage.TenantReader
17
	timeout  int
18
}
19
20
// NewTenantReaderWithCircuitBreaker - Add circuit breaker behaviour to new tenant reader
21
func NewTenantReaderWithCircuitBreaker(delegate storage.TenantReader, timeout int) *TenantReaderWithCircuitBreaker {
22
	return &TenantReaderWithCircuitBreaker{delegate: delegate, timeout: timeout}
23
}
24
25
// ListTenants - List tenants from the repository
26
func (r *TenantReaderWithCircuitBreaker) ListTenants(ctx context.Context, pagination database.Pagination) (tenants []*base.Tenant, ct database.EncodedContinuousToken, err error) {
27
	type circuitBreakerResponse struct {
28
		Tenants []*base.Tenant
29
		Ct      database.EncodedContinuousToken
30
		Error   error
31
	}
32
33
	output := make(chan circuitBreakerResponse, 1)
34
	hystrix.ConfigureCommand("tenantReader.listTenants", hystrix.CommandConfig{Timeout: r.timeout})
35
	bErrors := hystrix.Go("tenantReader.listTenants", func() error {
36
		tenants, ct, err := r.delegate.ListTenants(ctx, pagination)
37
		output <- circuitBreakerResponse{Tenants: tenants, Ct: ct, Error: err}
38
		return nil
39
	}, func(err error) error {
40
		return nil
41
	})
42
43
	select {
44
	case out := <-output:
45
		return out.Tenants, out.Ct, out.Error
46
	case <-bErrors:
47
		return nil, nil, errors.New(base.ErrorCode_ERROR_CODE_CIRCUIT_BREAKER.String())
48
	}
49
}
50