func (b *Breaker) Reserve(_ context.Context) (func(), bool) {
	if !b.tryAcquirePending() {
		return nil, false
	}
	if !b.sem.tryAcquire() {
		b.releasePending()
		return nil, false
	}
	return b.release, true
}
Reserve reserves an execution slot in the breaker, to permit
richer semantics in the caller.
The caller on success must execute the callback when done with work.
package proxy
import (
	"context"
	"errors"
	"fmt"
	"go.uber.org/atomic"
)
var (
	ErrRequestQueueFull = errors.New("pending request queue full")
)
type BreakerParams struct {
	QueueDepth      int
	MaxConcurrency  int
	InitialCapacity int
}
type Breaker struct {
	inFlight   atomic.Int64
	totalSlots int64
	sem        *semaphore
	release func()
}
func NewBreaker(params BreakerParams) *Breaker {
	if params.QueueDepth <= 0 {
		panic(fmt.Sprintf("Queue depth must be greater than 0. Got %v.", params.QueueDepth))
	}
	if params.MaxConcurrency < 0 {
		panic(fmt.Sprintf("Max concurrency must be 0 or greater. Got %v.", params.MaxConcurrency))
	}
	if params.InitialCapacity < 0 || params.InitialCapacity > params.MaxConcurrency {
		panic(fmt.Sprintf("Initial capacity must be between 0 and max concurrency. Got %v.", params.InitialCapacity))
	}
	b := &Breaker{
		totalSlots: int64(params.QueueDepth + params.MaxConcurrency),
		sem:        newSemaphore(params.MaxConcurrency, params.InitialCapacity),
	}
	b.release = func() {
		b.sem.release()
		b.releasePending()
	}
	return b
}
func (b *Breaker) tryAcquirePending() bool {
	for {
		cur := b.inFlight.Load()
		if cur == b.totalSlots {
			return false
		}
		if b.inFlight.CAS(cur, cur+1) {
			return true
		}
	}
}
func (b *Breaker) releasePending() {
	b.inFlight.Dec()
}