44 lines
934 B
Go
44 lines
934 B
Go
package limiter
|
|
|
|
import (
|
|
"alfred/config"
|
|
"context"
|
|
"golang.org/x/sync/semaphore"
|
|
"time"
|
|
)
|
|
|
|
var (
|
|
VideoSem = initVideoSemaphore()
|
|
DefaultTimeout = initDefaultTimeout()
|
|
)
|
|
|
|
func TryAcquire(ctx context.Context, sem *semaphore.Weighted, timeout time.Duration) bool {
|
|
ctxWithTimeout, cancel := context.WithTimeout(ctx, timeout)
|
|
defer cancel()
|
|
|
|
err := sem.Acquire(ctxWithTimeout, 1)
|
|
return err == nil
|
|
}
|
|
|
|
func Release(sem *semaphore.Weighted) {
|
|
if sem != nil {
|
|
sem.Release(1)
|
|
}
|
|
}
|
|
|
|
func initVideoSemaphore() *semaphore.Weighted {
|
|
maxJobs := config.GetCoreConfig().VideoProcessingConfig.MaxConcurrentJobs
|
|
if maxJobs <= 0 {
|
|
maxJobs = 3
|
|
}
|
|
return semaphore.NewWeighted(int64(maxJobs))
|
|
}
|
|
|
|
func initDefaultTimeout() time.Duration {
|
|
timeoutSeconds := config.GetCoreConfig().VideoProcessingConfig.DefaultTimeoutSeconds
|
|
if timeoutSeconds <= 0 {
|
|
timeoutSeconds = 5
|
|
}
|
|
return time.Duration(timeoutSeconds) * time.Second
|
|
}
|