// Copyright 2022 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// See the License for the specific language governing permissions and
// limitations under the License.

package quota

import (
	"context"

	"github.com/pingcap/tiflow/pkg/errors"
	"golang.org/x/sync/semaphore"
)

// ConcurrencyQuota abstracts an interface that supports acquire and release
// quota concurrently
type ConcurrencyQuota interface {
	Consume(ctx context.Context) error
	TryConsume() bool
	Release()
}

// NewConcurrencyQuota creates a new concurrencyQuotaImpl instance that
// implements ConcurrencyQuota interface
func NewConcurrencyQuota(total int64) ConcurrencyQuota {
	return &concurrencyQuotaImpl{sem: semaphore.NewWeighted(total)}
}

type concurrencyQuotaImpl struct {
	sem *semaphore.Weighted
}

func (c *concurrencyQuotaImpl) Consume(ctx context.Context) error {
	return errors.Trace(c.sem.Acquire(ctx, 1))
}

func (c *concurrencyQuotaImpl) TryConsume() bool {
	return c.sem.TryAcquire(1)
}

func (c *concurrencyQuotaImpl) Release() {
	c.sem.Release(1)
}
