config.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. package workers
  2. import (
  3. "errors"
  4. "runtime"
  5. "github.com/imgproxy/imgproxy/v3/ensure"
  6. "github.com/imgproxy/imgproxy/v3/env"
  7. )
  8. var (
  9. IMGPROXY_REQUESTS_QUEUE_SIZE = env.Describe("IMGPROXY_REQUESTS_QUEUE_SIZE", "number > 0")
  10. IMGPROXY_WORKERS_NUMBER = env.Describe("IMGPROXY_WORKERS_NUMBER", "number > 0")
  11. )
  12. // Config represents [Workers] config
  13. type Config struct {
  14. RequestsQueueSize int // Maximum request queue size
  15. WorkersNumber int // Number of allowed workers
  16. }
  17. // NewDefaultConfig creates a new configuration with defaults
  18. func NewDefaultConfig() Config {
  19. return Config{
  20. RequestsQueueSize: 0,
  21. WorkersNumber: runtime.GOMAXPROCS(0) * 2,
  22. }
  23. }
  24. // LoadConfigFromEnv loads config from environment variables
  25. func LoadConfigFromEnv(c *Config) (*Config, error) {
  26. c = ensure.Ensure(c, NewDefaultConfig)
  27. err := errors.Join(
  28. env.Int(&c.RequestsQueueSize, IMGPROXY_REQUESTS_QUEUE_SIZE),
  29. env.Int(&c.WorkersNumber, IMGPROXY_WORKERS_NUMBER),
  30. )
  31. return c, err
  32. }
  33. // Validate checks configuration values
  34. func (c *Config) Validate() error {
  35. if c.RequestsQueueSize < 0 {
  36. return IMGPROXY_REQUESTS_QUEUE_SIZE.ErrorNegative()
  37. }
  38. if c.WorkersNumber <= 0 {
  39. return IMGPROXY_WORKERS_NUMBER.ErrorZeroOrNegative()
  40. }
  41. return nil
  42. }