summaryrefslogtreecommitdiff
path: root/services/worker/internal/configuration/configuration.go
blob: 4d0819659c9e46c8e90e1455373aa3bf7f8df314 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package configuration

import (
	"fmt"
	"os"
	"strconv"
	"time"
)

type Configuration struct {
	DatabaseURL       string
	WorkerConcurrency int
	PollInterval      time.Duration
	FetchTimeout      time.Duration
	QueuePollInterval time.Duration
	BatchSize         int
	HealthPort        int
	LogLevel          string
	LogJSON           bool
}

func Load() (Configuration, error) {
	databaseURL := os.Getenv("DATABASE_URL")

	if databaseURL == "" {
		return Configuration{}, fmt.Errorf("DATABASE_URL is required")
	}

	workerConcurrency := getEnvironmentInteger("WORKER_CONCURRENCY", 10)
	pollInterval := getEnvironmentDuration("POLL_INTERVAL", 30*time.Second)
	fetchTimeout := getEnvironmentDuration("FETCH_TIMEOUT", 30*time.Second)
	queuePollInterval := getEnvironmentDuration("QUEUE_POLL_INTERVAL", 5*time.Second)
	batchSize := getEnvironmentInteger("BATCH_SIZE", 50)
	healthPort := getEnvironmentInteger("HEALTH_PORT", 8080)
	logLevel := getEnvironmentString("LOG_LEVEL", "info")
	logJSON := getEnvironmentBoolean("LOG_JSON", false)

	return Configuration{
		DatabaseURL:       databaseURL,
		WorkerConcurrency: workerConcurrency,
		PollInterval:      pollInterval,
		FetchTimeout:      fetchTimeout,
		QueuePollInterval: queuePollInterval,
		BatchSize:         batchSize,
		HealthPort:        healthPort,
		LogLevel:          logLevel,
		LogJSON:           logJSON,
	}, nil
}

func getEnvironmentString(key string, defaultValue string) string {
	value := os.Getenv(key)

	if value == "" {
		return defaultValue
	}

	return value
}

func getEnvironmentInteger(key string, defaultValue int) int {
	raw := os.Getenv(key)

	if raw == "" {
		return defaultValue
	}

	parsed, parseError := strconv.Atoi(raw)

	if parseError != nil {
		return defaultValue
	}

	return parsed
}

func getEnvironmentDuration(key string, defaultValue time.Duration) time.Duration {
	raw := os.Getenv(key)

	if raw == "" {
		return defaultValue
	}

	parsed, parseError := time.ParseDuration(raw)

	if parseError != nil {
		return defaultValue
	}

	return parsed
}

func getEnvironmentBoolean(key string, defaultValue bool) bool {
	raw := os.Getenv(key)

	if raw == "" {
		return defaultValue
	}

	parsed, parseError := strconv.ParseBool(raw)

	if parseError != nil {
		return defaultValue
	}

	return parsed
}