trpc.group/trpc-go/trpc-go@v1.0.3/naming/circuitbreaker/circuitbreaker.go (about) 1 // 2 // 3 // Tencent is pleased to support the open source community by making tRPC available. 4 // 5 // Copyright (C) 2023 THL A29 Limited, a Tencent company. 6 // All rights reserved. 7 // 8 // If you have downloaded a copy of the tRPC source code from Tencent, 9 // please note that tRPC source code is licensed under the Apache 2.0 License, 10 // A copy of the Apache 2.0 License is included in this file. 11 // 12 // 13 14 // Package circuitbreaker is a pluggable circuit breaker module. 15 package circuitbreaker 16 17 import ( 18 "sync" 19 "time" 20 21 "trpc.group/trpc-go/trpc-go/naming/registry" 22 ) 23 24 // DefaultCircuitBreaker is the default circuit breaker. 25 var DefaultCircuitBreaker CircuitBreaker = &NoopCircuitBreaker{} 26 27 // SetDefaultCircuitBreaker sets the default circuit breaker. 28 func SetDefaultCircuitBreaker(cb CircuitBreaker) { 29 DefaultCircuitBreaker = cb 30 } 31 32 // CircuitBreaker is the interface that defines the circuit breaker which determines whether a node 33 // is available and report the result of an RPC on the node. 34 type CircuitBreaker interface { 35 Available(node *registry.Node) bool 36 Report(node *registry.Node, cost time.Duration, err error) error 37 } 38 39 var ( 40 circuitbreakers = make(map[string]CircuitBreaker) 41 lock = sync.RWMutex{} 42 ) 43 44 // Register registers a named circuit breaker. 45 func Register(name string, s CircuitBreaker) { 46 lock.Lock() 47 circuitbreakers[name] = s 48 lock.Unlock() 49 } 50 51 // Get gets a named circuit breaker. 52 func Get(name string) CircuitBreaker { 53 lock.RLock() 54 c := circuitbreakers[name] 55 lock.RUnlock() 56 return c 57 } 58 59 func unregisterForTesting(name string) { 60 lock.Lock() 61 delete(circuitbreakers, name) 62 lock.Unlock() 63 } 64 65 // NoopCircuitBreaker is a noop circuit breaker. 66 type NoopCircuitBreaker struct{} 67 68 // Available always returns true. 69 func (*NoopCircuitBreaker) Available(*registry.Node) bool { 70 return true 71 } 72 73 // Report does nothing. 74 func (*NoopCircuitBreaker) Report(*registry.Node, time.Duration, error) error { 75 return nil 76 }