refactor(backend): standardize errors and simplify configuration and test setup
This commit is contained in:
1 parent
1535c19b8c
commit
138666a7bb
92 files changed
+3994
-210
No files matched your search
@@ -111,6 +111,11 @@ linters:
|
||||
- comments
|
||||
- common-false-positives
|
||||
rules:
|
||||
# Error locations use actual Go identifiers, including exported type names.
|
||||
- linters:
|
||||
- staticcheck
|
||||
text: 'ST1005: error strings should not be capitalized'
|
||||
source: '(fmt\.Errorf|errors\.New)\("[A-Z][A-Za-z0-9]*\.[A-Za-z0-9]+ - '
|
||||
- path: _test\.go
|
||||
linters:
|
||||
- gocyclo
|
||||
|
||||
+11
-4
@@ -125,7 +125,7 @@ $(QUALITY_STAMP): $(QUALITY_REQUIREMENTS)
|
||||
.PHONY: install-quality-python-deps
|
||||
install-quality-python-deps: $(QUALITY_STAMP) ## Install pinned SQL quality tools locally
|
||||
|
||||
.PHONY: test test-fast test-race test-int test-int-compile
|
||||
.PHONY: test test-fast test-race test-int test-int-list test-int-compile test-scripts
|
||||
test: ## Run backend unit tests with the race detector
|
||||
$(GO) test -race -count=1 ./...
|
||||
|
||||
@@ -134,10 +134,16 @@ test-fast: ## Run backend unit tests without race instrumentation
|
||||
|
||||
test-race: test ## Alias for the race-enabled unit suite
|
||||
|
||||
test-int: ## Run PostgreSQL integration tests with Testcontainers
|
||||
$(GO) test -tags=integration -count=1 ./integration_test/...
|
||||
test-int: ## Run integration tests, optionally selected by TEST_SHARD_INDEX and TEST_SHARD_TOTAL
|
||||
$(BOOTSTRAP_PYTHON) scripts/run-integration-suite.py --go "$(GO)"
|
||||
|
||||
test-int-compile: ## Compile PostgreSQL integration tests without starting containers
|
||||
test-int-list: ## Discover and list the selected integration tests without starting containers
|
||||
$(BOOTSTRAP_PYTHON) scripts/run-integration-suite.py --go "$(GO)" --list
|
||||
|
||||
test-scripts: ## Check integration shard coverage, selection, and failure propagation
|
||||
$(BOOTSTRAP_PYTHON) -B -m unittest discover -s scripts -p 'test_*.py'
|
||||
|
||||
test-int-compile: ## Compile infrastructure integration tests without starting containers
|
||||
$(GO) test -tags=integration -run '^$$' ./integration_test/...
|
||||
|
||||
.PHONY: verify check
|
||||
@@ -145,6 +151,7 @@ check: ## Run local formatting, build, unit, and lint checks in order
|
||||
$(MAKE) --no-print-directory fmt-check
|
||||
$(MAKE) --no-print-directory build
|
||||
$(MAKE) --no-print-directory test-fast
|
||||
$(MAKE) --no-print-directory test-scripts
|
||||
$(MAKE) --no-print-directory lint
|
||||
|
||||
verify: ## Run code, test, tooling, and generated-drift checks in order
|
||||
|
||||
+118
-31
@@ -1,6 +1,7 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"os"
|
||||
@@ -9,13 +10,34 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultHTTPAddr = ":8080"
|
||||
defaultMetricsAddr = ":9090"
|
||||
defaultRedisAddr = "localhost:6379"
|
||||
defaultLogLevel = "info"
|
||||
defaultRedisTimeout = time.Second
|
||||
defaultReadinessTimeout = time.Second
|
||||
defaultShutdownTimeout = 10 * time.Second
|
||||
maxPortNumber = 65535
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
HTTPAddr string
|
||||
MetricsAddr string
|
||||
DatabaseURL string
|
||||
LogLevel string
|
||||
ReadinessTimeout time.Duration
|
||||
ShutdownTimeout time.Duration
|
||||
HTTPAddr string
|
||||
MetricsAddr string
|
||||
DatabaseURL string
|
||||
RedisAddr string
|
||||
RedisPassword string
|
||||
RedisDB int
|
||||
RedisTimeout time.Duration
|
||||
SeaweedFSEndpoint string
|
||||
SeaweedFSAccessKey string
|
||||
SeaweedFSSecretKey string
|
||||
SeaweedFSBucket string
|
||||
SeaweedFSRegion string
|
||||
SeaweedFSTimeout time.Duration
|
||||
LogLevel string
|
||||
ReadinessTimeout time.Duration
|
||||
ShutdownTimeout time.Duration
|
||||
}
|
||||
|
||||
type LookupEnv func(string) (string, bool)
|
||||
@@ -26,27 +48,41 @@ func Load() (Config, error) {
|
||||
|
||||
func LoadFromEnv(lookup LookupEnv) (Config, error) {
|
||||
config := Config{
|
||||
HTTPAddr: valueOrDefault(lookup, "HTTP_ADDR", ":8080"),
|
||||
MetricsAddr: valueOrDefault(lookup, "METRICS_ADDR", ":9090"),
|
||||
DatabaseURL: strings.TrimSpace(valueOrDefault(lookup, "DATABASE_URL", "")),
|
||||
LogLevel: strings.ToLower(strings.TrimSpace(valueOrDefault(lookup, "LOG_LEVEL", "info"))),
|
||||
ReadinessTimeout: time.Second,
|
||||
ShutdownTimeout: 10 * time.Second,
|
||||
HTTPAddr: valueOrDefault(lookup, "HTTP_ADDR", defaultHTTPAddr),
|
||||
MetricsAddr: valueOrDefault(lookup, "METRICS_ADDR", defaultMetricsAddr),
|
||||
DatabaseURL: strings.TrimSpace(valueOrDefault(lookup, "DATABASE_URL", "")),
|
||||
RedisAddr: strings.TrimSpace(valueOrDefault(lookup, "REDIS_ADDR", defaultRedisAddr)),
|
||||
RedisPassword: valueOrDefault(lookup, "REDIS_PASSWORD", ""),
|
||||
RedisTimeout: defaultRedisTimeout,
|
||||
SeaweedFSEndpoint: strings.TrimSpace(valueOrDefault(lookup, "SEAWEEDFS_ENDPOINT", defaultSeaweedFSEndpoint)),
|
||||
SeaweedFSAccessKey: valueOrDefault(lookup, "SEAWEEDFS_ACCESS_KEY", ""),
|
||||
SeaweedFSSecretKey: valueOrDefault(lookup, "SEAWEEDFS_SECRET_KEY", ""),
|
||||
SeaweedFSBucket: strings.TrimSpace(valueOrDefault(lookup, "SEAWEEDFS_BUCKET", defaultSeaweedFSBucket)),
|
||||
SeaweedFSRegion: strings.TrimSpace(valueOrDefault(lookup, "SEAWEEDFS_REGION", defaultSeaweedFSRegion)),
|
||||
SeaweedFSTimeout: defaultSeaweedFSTimeout,
|
||||
LogLevel: strings.ToLower(strings.TrimSpace(valueOrDefault(lookup, "LOG_LEVEL", defaultLogLevel))),
|
||||
ReadinessTimeout: defaultReadinessTimeout,
|
||||
ShutdownTimeout: defaultShutdownTimeout,
|
||||
}
|
||||
|
||||
if value, ok := lookup("READINESS_TIMEOUT"); ok {
|
||||
duration, err := time.ParseDuration(value)
|
||||
if err != nil {
|
||||
return Config{}, fmt.Errorf("parse READINESS_TIMEOUT: %w", err)
|
||||
}
|
||||
config.ReadinessTimeout = duration
|
||||
if err := config.loadRedis(lookup); err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
if value, ok := lookup("SHUTDOWN_TIMEOUT"); ok {
|
||||
duration, err := time.ParseDuration(value)
|
||||
if err != nil {
|
||||
return Config{}, fmt.Errorf("parse SHUTDOWN_TIMEOUT: %w", err)
|
||||
}
|
||||
config.ShutdownTimeout = duration
|
||||
|
||||
var err error
|
||||
config.SeaweedFSTimeout, err = durationOrDefault(lookup, "SEAWEEDFS_TIMEOUT", config.SeaweedFSTimeout)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
|
||||
config.ReadinessTimeout, err = durationOrDefault(lookup, "READINESS_TIMEOUT", config.ReadinessTimeout)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
|
||||
config.ShutdownTimeout, err = durationOrDefault(lookup, "SHUTDOWN_TIMEOUT", config.ShutdownTimeout)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
|
||||
if err := config.Validate(); err != nil {
|
||||
@@ -56,6 +92,12 @@ func LoadFromEnv(lookup LookupEnv) (Config, error) {
|
||||
}
|
||||
|
||||
func (config Config) Validate() error {
|
||||
if err := config.ValidateSeaweedFS(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := config.ValidateRedis(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := validateAddress("HTTP_ADDR", config.HTTPAddr); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -63,15 +105,15 @@ func (config Config) Validate() error {
|
||||
return err
|
||||
}
|
||||
if config.ReadinessTimeout <= 0 {
|
||||
return fmt.Errorf("READINESS_TIMEOUT must be positive")
|
||||
return errors.New("Config.Validate - READINESS_TIMEOUT must be positive")
|
||||
}
|
||||
if config.ShutdownTimeout <= 0 {
|
||||
return fmt.Errorf("SHUTDOWN_TIMEOUT must be positive")
|
||||
return errors.New("Config.Validate - SHUTDOWN_TIMEOUT must be positive")
|
||||
}
|
||||
switch config.LogLevel {
|
||||
case "debug", "info", "warn", "error":
|
||||
default:
|
||||
return fmt.Errorf("LOG_LEVEL must be one of debug, info, warn, or error")
|
||||
return errors.New("Config.Validate - LOG_LEVEL must be one of debug, info, warn, or error")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -83,17 +125,62 @@ func valueOrDefault(lookup LookupEnv, key, fallback string) string {
|
||||
return fallback
|
||||
}
|
||||
|
||||
func durationOrDefault(lookup LookupEnv, key string, fallback time.Duration) (time.Duration, error) {
|
||||
value, ok := lookup(key)
|
||||
if !ok {
|
||||
return fallback, nil
|
||||
}
|
||||
duration, err := time.ParseDuration(value)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("config.durationOrDefault - parse %s: %w", key, err)
|
||||
}
|
||||
return duration, nil
|
||||
}
|
||||
|
||||
func validateAddress(name, address string) error {
|
||||
if address == "" {
|
||||
return fmt.Errorf("%s must not be empty", name)
|
||||
return fmt.Errorf("config.validateAddress - %s must not be empty", name)
|
||||
}
|
||||
_, port, err := net.SplitHostPort(address)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s must be a host:port address: %w", name, err)
|
||||
return fmt.Errorf("config.validateAddress - %s must be a host:port address: %w", name, err)
|
||||
}
|
||||
number, err := strconv.Atoi(port)
|
||||
if err != nil || number < 0 || number > 65535 {
|
||||
return fmt.Errorf("%s port must be between 0 and 65535", name)
|
||||
if err != nil || number < 0 || number > maxPortNumber {
|
||||
return fmt.Errorf("config.validateAddress - %s port must be between 0 and %d", name, maxPortNumber)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (config *Config) loadRedis(lookup LookupEnv) error {
|
||||
if value, ok := lookup("REDIS_DB"); ok {
|
||||
database, err := strconv.Atoi(value)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Config.loadRedis - parse REDIS_DB: %w", err)
|
||||
}
|
||||
config.RedisDB = database
|
||||
}
|
||||
|
||||
var err error
|
||||
config.RedisTimeout, err = durationOrDefault(lookup, "REDIS_TIMEOUT", config.RedisTimeout)
|
||||
return err
|
||||
}
|
||||
|
||||
func (config Config) ValidateRedis() error {
|
||||
if err := validateAddress("REDIS_ADDR", config.RedisAddr); err != nil {
|
||||
return err
|
||||
}
|
||||
// validateAddress already checked both parsing operations above.
|
||||
host, port, _ := net.SplitHostPort(config.RedisAddr)
|
||||
number, _ := strconv.Atoi(port)
|
||||
if host == "" || number == 0 {
|
||||
return errors.New("Config.ValidateRedis - REDIS_ADDR must contain a host and a nonzero port")
|
||||
}
|
||||
if config.RedisDB < 0 {
|
||||
return errors.New("Config.ValidateRedis - REDIS_DB must not be negative")
|
||||
}
|
||||
if config.RedisTimeout <= 0 {
|
||||
return errors.New("Config.ValidateRedis - REDIS_TIMEOUT must be positive")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
+105
-15
@@ -7,7 +7,7 @@ import (
|
||||
)
|
||||
|
||||
func TestLoadFromEnvUsesOperationalDefaults(t *testing.T) {
|
||||
config, err := LoadFromEnv(func(string) (string, bool) { return "", false })
|
||||
config, err := LoadFromEnv(testEnvironment(nil))
|
||||
if err != nil {
|
||||
t.Fatalf("LoadFromEnv() error = %v", err)
|
||||
}
|
||||
@@ -20,6 +20,9 @@ func TestLoadFromEnvUsesOperationalDefaults(t *testing.T) {
|
||||
if config.DatabaseURL != "" {
|
||||
t.Fatalf("DatabaseURL = %q, want empty", config.DatabaseURL)
|
||||
}
|
||||
if config.RedisAddr != "localhost:6379" || config.RedisDB != 0 || config.RedisTimeout != time.Second || config.RedisPassword != "" {
|
||||
t.Fatalf("unexpected Redis defaults")
|
||||
}
|
||||
if config.LogLevel != "info" {
|
||||
t.Fatalf("LogLevel = %q, want info", config.LogLevel)
|
||||
}
|
||||
@@ -28,22 +31,26 @@ func TestLoadFromEnvUsesOperationalDefaults(t *testing.T) {
|
||||
func TestLoadFromEnvReadsAddressesAndTimeouts(t *testing.T) {
|
||||
values := map[string]string{
|
||||
"HTTP_ADDR": "127.0.0.1:18080",
|
||||
"REDIS_ADDR": "cache:6379",
|
||||
"REDIS_PASSWORD": " local-secret ",
|
||||
"REDIS_DB": "2",
|
||||
"REDIS_TIMEOUT": "500ms",
|
||||
"METRICS_ADDR": "127.0.0.1:19090",
|
||||
"DATABASE_URL": " postgres://app:secret@db/app ",
|
||||
"LOG_LEVEL": " DEBUG ",
|
||||
"READINESS_TIMEOUT": "2s",
|
||||
"SHUTDOWN_TIMEOUT": "15s",
|
||||
}
|
||||
config, err := LoadFromEnv(func(key string) (string, bool) {
|
||||
value, ok := values[key]
|
||||
return value, ok
|
||||
})
|
||||
config, err := LoadFromEnv(testEnvironment(values))
|
||||
if err != nil {
|
||||
t.Fatalf("LoadFromEnv() error = %v", err)
|
||||
}
|
||||
if config.HTTPAddr != values["HTTP_ADDR"] || config.MetricsAddr != values["METRICS_ADDR"] {
|
||||
t.Fatalf("unexpected listener values: %+v", config)
|
||||
}
|
||||
if config.RedisAddr != "cache:6379" || config.RedisPassword != " local-secret " || config.RedisDB != 2 || config.RedisTimeout != 500*time.Millisecond {
|
||||
t.Fatalf("Redis settings were not preserved")
|
||||
}
|
||||
if config.DatabaseURL != "postgres://app:secret@db/app" {
|
||||
t.Fatalf("DatabaseURL was not trimmed: %q", config.DatabaseURL)
|
||||
}
|
||||
@@ -61,21 +68,104 @@ func TestLoadFromEnvRejectsInvalidSettings(t *testing.T) {
|
||||
values map[string]string
|
||||
want string
|
||||
}{
|
||||
{name: "invalid HTTP address", values: map[string]string{"HTTP_ADDR": "bad"}, want: "HTTP_ADDR"},
|
||||
{name: "invalid metrics port", values: map[string]string{"METRICS_ADDR": ":70000"}, want: "METRICS_ADDR"},
|
||||
{name: "invalid readiness timeout", values: map[string]string{"READINESS_TIMEOUT": "soon"}, want: "READINESS_TIMEOUT"},
|
||||
{name: "zero shutdown timeout", values: map[string]string{"SHUTDOWN_TIMEOUT": "0s"}, want: "SHUTDOWN_TIMEOUT"},
|
||||
{name: "invalid log level", values: map[string]string{"LOG_LEVEL": "trace"}, want: "LOG_LEVEL"},
|
||||
{name: "invalid HTTP address", values: map[string]string{"HTTP_ADDR": "bad"}, want: "config.validateAddress - HTTP_ADDR"},
|
||||
{name: "invalid metrics port", values: map[string]string{"METRICS_ADDR": ":70000"}, want: "config.validateAddress - METRICS_ADDR"},
|
||||
{name: "invalid readiness timeout", values: map[string]string{"READINESS_TIMEOUT": "soon"}, want: "config.durationOrDefault - parse READINESS_TIMEOUT"},
|
||||
{name: "empty readiness timeout", values: map[string]string{"READINESS_TIMEOUT": ""}, want: "config.durationOrDefault - parse READINESS_TIMEOUT"},
|
||||
{name: "zero shutdown timeout", values: map[string]string{"SHUTDOWN_TIMEOUT": "0s"}, want: "Config.Validate - SHUTDOWN_TIMEOUT"},
|
||||
{name: "invalid Redis address", values: map[string]string{"REDIS_ADDR": "bad"}, want: "config.validateAddress - REDIS_ADDR"},
|
||||
{name: "empty Redis host", values: map[string]string{"REDIS_ADDR": ":6379"}, want: "Config.ValidateRedis - REDIS_ADDR"},
|
||||
{name: "zero Redis port", values: map[string]string{"REDIS_ADDR": "localhost:0"}, want: "Config.ValidateRedis - REDIS_ADDR"},
|
||||
{name: "invalid Redis database", values: map[string]string{"REDIS_DB": "abc"}, want: "Config.loadRedis - parse REDIS_DB"},
|
||||
{name: "negative Redis database", values: map[string]string{"REDIS_DB": "-1"}, want: "Config.ValidateRedis - REDIS_DB"},
|
||||
{name: "invalid Redis timeout", values: map[string]string{"REDIS_TIMEOUT": "soon"}, want: "config.durationOrDefault - parse REDIS_TIMEOUT"},
|
||||
{name: "zero Redis timeout", values: map[string]string{"REDIS_TIMEOUT": "0s"}, want: "Config.ValidateRedis - REDIS_TIMEOUT"},
|
||||
{name: "invalid log level", values: map[string]string{"LOG_LEVEL": "trace"}, want: "Config.Validate - LOG_LEVEL"},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
_, err := LoadFromEnv(func(key string) (string, bool) {
|
||||
value, ok := test.values[key]
|
||||
return value, ok
|
||||
})
|
||||
if err == nil || !strings.Contains(err.Error(), test.want) {
|
||||
_, err := LoadFromEnv(testEnvironment(test.values))
|
||||
if err == nil || !strings.HasPrefix(err.Error(), test.want) {
|
||||
t.Fatalf("LoadFromEnv() error = %v, want an error mentioning %q", err, test.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func testEnvironment(values map[string]string) LookupEnv {
|
||||
return func(key string) (string, bool) {
|
||||
if value, ok := values[key]; ok {
|
||||
return value, true
|
||||
}
|
||||
if key == "SEAWEEDFS_ACCESS_KEY" {
|
||||
return "test-access", true
|
||||
}
|
||||
if key == "SEAWEEDFS_SECRET_KEY" {
|
||||
return "test-secret", true
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadFromEnvSeaweedFS(t *testing.T) {
|
||||
settings, err := LoadFromEnv(testEnvironment(nil))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if settings.SeaweedFSEndpoint != "http://localhost:8333" || settings.SeaweedFSBucket != "lincodex" || settings.SeaweedFSRegion != "us-east-1" || settings.SeaweedFSTimeout != 10*time.Second {
|
||||
t.Fatal("unexpected SeaweedFS defaults")
|
||||
}
|
||||
settings, err = LoadFromEnv(testEnvironment(map[string]string{
|
||||
"SEAWEEDFS_ENDPOINT": " https://storage.example:8333/ ",
|
||||
"SEAWEEDFS_BUCKET": " private-files ",
|
||||
"SEAWEEDFS_REGION": " eu-central-1 ",
|
||||
"SEAWEEDFS_TIMEOUT": "2s",
|
||||
"SEAWEEDFS_SECRET_KEY": " preserve-spaces ",
|
||||
}))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if settings.SeaweedFSEndpoint != "https://storage.example:8333/" || settings.SeaweedFSBucket != "private-files" || settings.SeaweedFSRegion != "eu-central-1" || settings.SeaweedFSTimeout != 2*time.Second || settings.SeaweedFSSecretKey != " preserve-spaces " {
|
||||
t.Fatal("SeaweedFS environment was not loaded")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadFromEnvRejectsSeaweedFSSettings(t *testing.T) {
|
||||
for _, test := range []struct{ key, value string }{
|
||||
{"SEAWEEDFS_ENDPOINT", ""},
|
||||
{"SEAWEEDFS_ENDPOINT", "ftp://storage"},
|
||||
{"SEAWEEDFS_ENDPOINT", "http://secret@storage"},
|
||||
{"SEAWEEDFS_ENDPOINT", "http://storage/path"},
|
||||
{"SEAWEEDFS_ENDPOINT", "http://storage?token=secret"},
|
||||
{"SEAWEEDFS_ENDPOINT", "http://storage?"},
|
||||
{"SEAWEEDFS_ENDPOINT", "http://storage/%secret"},
|
||||
{"SEAWEEDFS_ENDPOINT", "http://storage/#secret"},
|
||||
{"SEAWEEDFS_ENDPOINT", "http://storage:0"},
|
||||
{"SEAWEEDFS_ENDPOINT", "http://storage:00"},
|
||||
{"SEAWEEDFS_ENDPOINT", "http://storage:000"},
|
||||
{"SEAWEEDFS_ENDPOINT", "http://storage:"},
|
||||
{"SEAWEEDFS_ENDPOINT", "http://storage:99999"},
|
||||
{"SEAWEEDFS_ENDPOINT", "http://storage:invalid"},
|
||||
{"SEAWEEDFS_ACCESS_KEY", ""},
|
||||
{"SEAWEEDFS_SECRET_KEY", " "},
|
||||
{"SEAWEEDFS_BUCKET", ""},
|
||||
{"SEAWEEDFS_BUCKET", "../files"},
|
||||
{"SEAWEEDFS_BUCKET", "a..b"},
|
||||
{"SEAWEEDFS_BUCKET", "192.168.1.1"},
|
||||
{"SEAWEEDFS_BUCKET", "-files"},
|
||||
{"SEAWEEDFS_BUCKET", "Files"},
|
||||
{"SEAWEEDFS_REGION", " "},
|
||||
{"SEAWEEDFS_TIMEOUT", "0s"},
|
||||
{"SEAWEEDFS_TIMEOUT", "soon"},
|
||||
} {
|
||||
t.Run(test.key+"/"+test.value, func(t *testing.T) {
|
||||
_, err := LoadFromEnv(testEnvironment(map[string]string{test.key: test.value}))
|
||||
if err == nil || !strings.Contains(err.Error(), test.key) {
|
||||
t.Fatalf("invalid configuration accepted: %v", err)
|
||||
}
|
||||
if strings.Contains(err.Error(), "secret") {
|
||||
t.Fatal("configuration error disclosed credentials")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultSeaweedFSEndpoint = "http://localhost:8333"
|
||||
defaultSeaweedFSBucket = "lincodex"
|
||||
defaultSeaweedFSRegion = "us-east-1"
|
||||
defaultSeaweedFSTimeout = 10 * time.Second
|
||||
minBucketNameLength = 3
|
||||
maxBucketNameLength = 63
|
||||
)
|
||||
|
||||
func (config Config) ValidateSeaweedFS() error {
|
||||
if err := validateStorageEndpoint(config.SeaweedFSEndpoint); err != nil {
|
||||
return err
|
||||
}
|
||||
if strings.TrimSpace(config.SeaweedFSAccessKey) == "" {
|
||||
return errors.New("Config.ValidateSeaweedFS - SEAWEEDFS_ACCESS_KEY must not be empty")
|
||||
}
|
||||
if strings.TrimSpace(config.SeaweedFSSecretKey) == "" {
|
||||
return errors.New("Config.ValidateSeaweedFS - SEAWEEDFS_SECRET_KEY must not be empty")
|
||||
}
|
||||
if !validBucket(config.SeaweedFSBucket) {
|
||||
return errors.New("Config.ValidateSeaweedFS - SEAWEEDFS_BUCKET must be a valid S3 bucket name")
|
||||
}
|
||||
if strings.TrimSpace(config.SeaweedFSRegion) == "" {
|
||||
return errors.New("Config.ValidateSeaweedFS - SEAWEEDFS_REGION must not be empty")
|
||||
}
|
||||
if config.SeaweedFSTimeout <= 0 {
|
||||
return errors.New("Config.ValidateSeaweedFS - SEAWEEDFS_TIMEOUT must be positive")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateStorageEndpoint(raw string) error {
|
||||
endpoint, err := url.Parse(raw)
|
||||
if err != nil {
|
||||
return errors.New("config.validateStorageEndpoint - SEAWEEDFS_ENDPOINT must be an absolute HTTP or HTTPS URL")
|
||||
}
|
||||
|
||||
hasHost := endpoint.Hostname() != ""
|
||||
hasHTTPScheme := endpoint.Scheme == "http" || endpoint.Scheme == "https"
|
||||
if !hasHost || !hasHTTPScheme {
|
||||
return errors.New("config.validateStorageEndpoint - SEAWEEDFS_ENDPOINT must be an absolute HTTP or HTTPS URL")
|
||||
}
|
||||
|
||||
hasCredentials := endpoint.User != nil
|
||||
hasQuery := endpoint.RawQuery != "" || endpoint.ForceQuery
|
||||
hasFragment := endpoint.Fragment != ""
|
||||
hasPath := endpoint.Path != "" && endpoint.Path != "/"
|
||||
if hasCredentials || hasQuery || hasFragment || hasPath {
|
||||
return errors.New("config.validateStorageEndpoint - SEAWEEDFS_ENDPOINT must not contain credentials, a path, query, or fragment")
|
||||
}
|
||||
if !validEndpointPort(endpoint) {
|
||||
return errors.New("config.validateStorageEndpoint - SEAWEEDFS_ENDPOINT must have a valid nonzero port")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validEndpointPort(endpoint *url.URL) bool {
|
||||
port := endpoint.Port()
|
||||
if port == "" && !strings.HasSuffix(endpoint.Host, ":") {
|
||||
return true
|
||||
}
|
||||
number, err := strconv.Atoi(port)
|
||||
return err == nil && number >= 1 && number <= maxPortNumber
|
||||
}
|
||||
|
||||
func validBucket(bucket string) bool {
|
||||
validLength := len(bucket) >= minBucketNameLength && len(bucket) <= maxBucketNameLength
|
||||
if !validLength || net.ParseIP(bucket) != nil {
|
||||
return false
|
||||
}
|
||||
for _, label := range strings.Split(bucket, ".") {
|
||||
if label == "" || label[0] == '-' || label[len(label)-1] == '-' {
|
||||
return false
|
||||
}
|
||||
for _, char := range label {
|
||||
if char != '-' && (char < 'a' || char > 'z') && (char < '0' || char > '9') {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
+16
-2
@@ -3,6 +3,10 @@ module lincodex/backend
|
||||
go 1.26.8
|
||||
|
||||
require (
|
||||
github.com/aws/aws-sdk-go-v2 v1.47.1
|
||||
github.com/aws/aws-sdk-go-v2/credentials v1.20.6
|
||||
github.com/aws/aws-sdk-go-v2/service/s3 v1.114.0
|
||||
github.com/aws/smithy-go v1.28.2
|
||||
github.com/felixge/httpsnoop v1.1.0
|
||||
github.com/go-chi/chi/v5 v5.3.2
|
||||
github.com/go-faster/errors v0.8.0
|
||||
@@ -11,8 +15,10 @@ require (
|
||||
github.com/jackc/pgx/v5 v5.11.0
|
||||
github.com/ogen-go/ogen v1.24.0
|
||||
github.com/prometheus/client_golang v1.24.1
|
||||
github.com/redis/go-redis/v9 v9.22.0
|
||||
github.com/testcontainers/testcontainers-go v0.44.0
|
||||
github.com/testcontainers/testcontainers-go/modules/postgres v0.44.0
|
||||
github.com/wahrwelt-kit/go-cachekit v0.7.0
|
||||
github.com/wahrwelt-kit/go-httpkit v0.7.0
|
||||
github.com/wahrwelt-kit/go-logkit v0.6.0
|
||||
go.opentelemetry.io/otel v1.47.0
|
||||
@@ -66,6 +72,14 @@ require (
|
||||
github.com/antlr4-go/antlr/v4 v4.13.1 // indirect
|
||||
github.com/ashanbrown/forbidigo/v2 v2.3.1 // indirect
|
||||
github.com/ashanbrown/makezero/v2 v2.2.1 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.20 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.4 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.4 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.4 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.19 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.5 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.4 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.4 // indirect
|
||||
github.com/bahlo/generic-list-go v0.2.0 // indirect
|
||||
github.com/beorn7/perks v1.0.1 // indirect
|
||||
github.com/bkielbasa/cyclop v1.2.3 // indirect
|
||||
@@ -296,7 +310,7 @@ require (
|
||||
github.com/segmentio/asm v1.2.1 // indirect
|
||||
github.com/sethvargo/go-retry v0.4.0 // indirect
|
||||
github.com/shirou/gopsutil/v4 v4.26.8 // indirect
|
||||
github.com/shopspring/decimal v1.4.0 // indirect
|
||||
github.com/shopspring/decimal v1.5.0 // indirect
|
||||
github.com/sirupsen/logrus v1.10.2 // indirect
|
||||
github.com/sivchari/containedctx v1.0.3 // indirect
|
||||
github.com/sonatard/noctx v0.5.1 // indirect
|
||||
@@ -357,7 +371,7 @@ require (
|
||||
go.opentelemetry.io/auto/sdk v1.2.1 // indirect
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.71.0 // indirect
|
||||
go.opentelemetry.io/otel/log v1.47.0 // indirect
|
||||
go.uber.org/atomic v1.11.0 // indirect
|
||||
go.uber.org/atomic v1.12.0 // indirect
|
||||
go.uber.org/multierr v1.11.0 // indirect
|
||||
go.uber.org/zap v1.28.0 // indirect
|
||||
go.yaml.in/yaml/v3 v3.0.5 // indirect
|
||||
|
||||
+40
-4
@@ -106,6 +106,30 @@ github.com/ashanbrown/forbidigo/v2 v2.3.1 h1:KAZijvQ7zeIBKbhikT4jCm0TLYXC4u78bTi
|
||||
github.com/ashanbrown/forbidigo/v2 v2.3.1/go.mod h1:2QDkLTzU6TV937eFROamXrW92M3paehdae4HCDCOZCM=
|
||||
github.com/ashanbrown/makezero/v2 v2.2.1 h1:A7uU8dgB1PA9aelTxHMfHIQ8Qev8AB3JLxJUBUsejqM=
|
||||
github.com/ashanbrown/makezero/v2 v2.2.1/go.mod h1:aEGT/9q3S8DHeE57C88z2a6xydvgx8J5hgXIGWgo0MY=
|
||||
github.com/aws/aws-sdk-go-v2 v1.47.1 h1:uOIZnp4PK3ZhKI0dNrJrhTEsLxbpXHTAJlwoS1pvAtw=
|
||||
github.com/aws/aws-sdk-go-v2 v1.47.1/go.mod h1:bttEH6JqnUL8LepvDVfdrds/fZ5bCIxzpe3abyUrhDU=
|
||||
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.20 h1:GPRlPwz40I2B2VrBEASOA3Bi77NyeqejNLkifosX0rs=
|
||||
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.20/go.mod h1:g7PNzKcsOKWb4fkSRBA7BZVAS6Y8IcxzN+nRohhQ1Q8=
|
||||
github.com/aws/aws-sdk-go-v2/credentials v1.20.6 h1:NpAFXCU7NzXNkdGK3zQTtsRJ+3v9tZQV0xcdRw8uBdw=
|
||||
github.com/aws/aws-sdk-go-v2/credentials v1.20.6/go.mod h1:mcZCoiPnyMvP8VMNbygNX5lLqSlkYJIMPODylQMurOk=
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.4 h1:CLq4+8UHCI+ZZYl/EuJxXovaIVN2xeeT8JV+dsApQ5E=
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.4/go.mod h1:Wv4q5sAM04xAMkoOedxLx2inVf6K5FdxYp+A61L+q/0=
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.4 h1:dD4MR81I7YkpEBRk6UP9rocC2QnT3qVuXwzlYTtfGEs=
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.4/go.mod h1:EcXV1kAFd5XwSkDHlj94gnF3q5CkJyYiIJfH8N0VmrE=
|
||||
github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.4 h1:7Wo47d/xn/7KttCSBd8EGYeZ7ULRFRkUHr6vkZPBzVQ=
|
||||
github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.4/go.mod h1:tDB2IVC1xC3vX8o+6uRlzhTxP3g1b77CZXFX/oD2FnQ=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.19 h1:bAdDl/HkGCcGPoe25ToSHEw23VIxt6CT5fLcg111BKg=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.19/go.mod h1:KaUzbLxv4CeSxh6ZCl9B4m7CuFenS8kUEaDs+f/DQr4=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.5 h1:/TYsZXdA8UTa+WCtCYSAJIr1vwl0+eho6TUgJGwFFO8=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.5/go.mod h1:qPqp1Uwd/BqdhPufv6oem9j5J7HNsgc2V22dUiDPn+s=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.4 h1:29SvnfGhXjTl8ONxFwbj2rs6lbhiFXD2CgFQmbT/bXY=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.4/go.mod h1:wm04I5DMuNVvZHFe/dHnUxincvNbbK7AiNBbYsQivek=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.4 h1:pPiWfgeNxqluKEph7hvU88kuGKBPOWzO+Dk9t2zqqNs=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.4/go.mod h1:YlwGoIUDG/3kBQbdNOVs/xKZ9J01G8e/6D1mRBj9uTk=
|
||||
github.com/aws/aws-sdk-go-v2/service/s3 v1.114.0 h1:VMAdYqr4Jn/8ATs9BHC5riwrs0d6m1Z2ohFriSwZwm0=
|
||||
github.com/aws/aws-sdk-go-v2/service/s3 v1.114.0/go.mod h1:9APRWGLFITKD+xzWSIyT9V7QV4bNlEuIieWlzXgGFlI=
|
||||
github.com/aws/smithy-go v1.28.2 h1:myhcykQcatTul2B/zITjDk203G7t0awUAs1hVry5Bvg=
|
||||
github.com/aws/smithy-go v1.28.2/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc=
|
||||
github.com/bahlo/generic-list-go v0.2.0 h1:5sz/EEAK+ls5wF+NeqDpk5+iNdMDXrh3z3nPnH1Wvgk=
|
||||
github.com/bahlo/generic-list-go v0.2.0/go.mod h1:2KvAjgMlE5NNynlg/5iLrrCCZ2+5xWbdbCW3pNTGyYg=
|
||||
github.com/benbjohnson/clock v1.1.0/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA=
|
||||
@@ -125,6 +149,10 @@ github.com/breml/errchkjson v0.4.1 h1:keFSS8D7A2T0haP9kzZTi7o26r7kE3vymjZNeNDRDw
|
||||
github.com/breml/errchkjson v0.4.1/go.mod h1:a23OvR6Qvcl7DG/Z4o0el6BRAjKnaReoPQFciAl9U3s=
|
||||
github.com/brunoga/deep v1.3.1 h1:bSrL6FhAZa6JlVv4vsi7Hg8SLwroDb1kgDERRVipBCo=
|
||||
github.com/brunoga/deep v1.3.1/go.mod h1:GDV6dnXqn80ezsLSZ5Wlv1PdKAWAO4L5PnKYtv2dgaI=
|
||||
github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=
|
||||
github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c=
|
||||
github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA=
|
||||
github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0=
|
||||
github.com/buger/jsonparser v1.6.1 h1:I0phFv0PlbLHnM7TZAVjZ2MJ2/eWRTDyuO7GLR98IEs=
|
||||
github.com/buger/jsonparser v1.6.1/go.mod h1:6RYKKt7H4d4+iWqouImQ9R2FZql3VbhNgx27UK13J/0=
|
||||
github.com/butuzov/ireturn v0.4.1 h1:vWb3NO4t77iku/sjCQ/2pHTQeOmxEhjIriJqRLg1Y+I=
|
||||
@@ -457,6 +485,8 @@ github.com/kkHAIKE/contextcheck v1.1.6 h1:7HIyRcnyzxL9Lz06NGhiKvenXq7Zw6Q0UQu/tt
|
||||
github.com/kkHAIKE/contextcheck v1.1.6/go.mod h1:3dDbMRNBFaq8HFXWC1JyvDSPm43CmE6IuHam8Wr0rkg=
|
||||
github.com/klauspost/compress v1.19.2 h1:hMRETovs/pu/dVWN7zIT1PGG8t509MwT6bO7XSi26R8=
|
||||
github.com/klauspost/compress v1.19.2/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ=
|
||||
github.com/klauspost/cpuid/v2 v2.2.10 h1:tBs3QSyvjDyFTq3uoc/9xFpCuOsJQFNPiAhYdw2skhE=
|
||||
github.com/klauspost/cpuid/v2 v2.2.10/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=
|
||||
github.com/knadh/koanf/maps v0.1.2 h1:RBfmAW5CnZT+PJ1CVc1QSJKf4Xu9kxfQgYVQSu8hpbo=
|
||||
github.com/knadh/koanf/maps v0.1.2/go.mod h1:npD/QZY3V6ghQDdcQzl1W4ICNVTkohC8E73eI2xW4yI=
|
||||
github.com/knadh/koanf/parsers/yaml v1.1.0 h1:3ltfm9ljprAHt4jxgeYLlFPmUaunuCgu1yILuTXRdM4=
|
||||
@@ -657,6 +687,8 @@ github.com/quasilyte/stdinfo v0.0.0-20220114132959-f7386bf02567 h1:M8mH9eK4OUR4l
|
||||
github.com/quasilyte/stdinfo v0.0.0-20220114132959-f7386bf02567/go.mod h1:DWNGW8A4Y+GyBgPuaQJuWiy0XYftx4Xm/y5Jqk9I6VQ=
|
||||
github.com/raeperd/recvcheck v0.3.1 h1:p7nZMxiCWkdUtY2i3o+pv1h4fJCR5gpvqAXr9326hEY=
|
||||
github.com/raeperd/recvcheck v0.3.1/go.mod h1:CbE7iRocQ4uc71JwpW/CPSh4BShnkre4A9Gb508RypU=
|
||||
github.com/redis/go-redis/v9 v9.22.0 h1:laDvpYXTJtZLloinw1fA5Kqd6HAEH2XKxOkG/PDq2F0=
|
||||
github.com/redis/go-redis/v9 v9.22.0/go.mod h1:y2g0Wj8rQvuK0ELM+oxSudcLtC09JScs98I/X9gRWY4=
|
||||
github.com/rekby/fixenv v0.6.1 h1:jUFiSPpajT4WY2cYuc++7Y1zWrnCxnovGCIX72PZniM=
|
||||
github.com/rekby/fixenv v0.6.1/go.mod h1:/b5LRc06BYJtslRtHKxsPWFT/ySpHV+rWvzTg+XWk4c=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
|
||||
@@ -697,8 +729,8 @@ github.com/sethvargo/go-retry v0.4.0 h1:9qy1OoIAxBL+gBYnkTnTnWle5wlfsXQlwRzIbbpd
|
||||
github.com/sethvargo/go-retry v0.4.0/go.mod h1:tvsjdKG6xfiCx4LSiUZ06kcv38xvdVQwv8R6/VnnVWg=
|
||||
github.com/shirou/gopsutil/v4 v4.26.8 h1:YQMTF/1J50B5+Y0vlo1eDRf5DoR7Gk69hY+8wjYkQeo=
|
||||
github.com/shirou/gopsutil/v4 v4.26.8/go.mod h1:5O9FjBiXoTDFatIWjZZosqj4pV0DRtLx598xGbBehzM=
|
||||
github.com/shopspring/decimal v1.4.0 h1:bxl37RwXBklmTi0C79JfXCEBD1cqqHt0bbgBAGFp81k=
|
||||
github.com/shopspring/decimal v1.4.0/go.mod h1:gawqmDU56v4yIKSwfBSFip1HdCCXN8/+DMd9qYNcwME=
|
||||
github.com/shopspring/decimal v1.5.0 h1:HxSWk31RmJv0EyY4oLiGQB9u7WPludUwPBdvQZnYFPc=
|
||||
github.com/shopspring/decimal v1.5.0/go.mod h1:gawqmDU56v4yIKSwfBSFip1HdCCXN8/+DMd9qYNcwME=
|
||||
github.com/sirupsen/logrus v1.10.2 h1:G2SED73/qrAu6YwbdxOD6peLkCBI3z7L+ykJFTXJBBo=
|
||||
github.com/sirupsen/logrus v1.10.2/go.mod h1:SLEg8TqYulVKKfIGHldVp2K2aYz2DKSVBq4g/H5bR7Q=
|
||||
github.com/sivchari/containedctx v1.0.3 h1:x+etemjbsh2fB5ewm5FeLNi5bUjK0V8n0RB+Wwfd0XE=
|
||||
@@ -789,6 +821,8 @@ github.com/vertica/vertica-sql-go v1.3.8 h1:FomjkM3cam9yE6zSic31flNWPLdsZbYGK9ih
|
||||
github.com/vertica/vertica-sql-go v1.3.8/go.mod h1:c4OZ8lq1Ztc18w8a0nG+dzQh69BzJRcKN2LZOnYbERI=
|
||||
github.com/wI2L/jsondiff v0.7.1 h1:Fg9+yj+1/x3UtPBJhR91TKEzRkrEEWcAcLbg9dzEaNM=
|
||||
github.com/wI2L/jsondiff v0.7.1/go.mod h1:yAt2W7U6Jd4HK0RA8DGSGk0zDtfEtOUUJVnH/xICpjo=
|
||||
github.com/wahrwelt-kit/go-cachekit v0.7.0 h1:xy6teSjg+4Ho+1eMpwOzVsCuiCEthMpEXaXTUp+JZqY=
|
||||
github.com/wahrwelt-kit/go-cachekit v0.7.0/go.mod h1:fkA0ZWm48nlgZfKdOuGDGdGWabhrPtqat+n8eDKgAjE=
|
||||
github.com/wahrwelt-kit/go-httpkit v0.7.0 h1:Se84sP2sf1aS24JRDDuNMluk1JuwrUpxShACTqJWNW0=
|
||||
github.com/wahrwelt-kit/go-httpkit v0.7.0/go.mod h1:3IP4Eg6gHcTZtQGu3Bized0pYzdOXAf7AYW9JNpqi2g=
|
||||
github.com/wahrwelt-kit/go-logkit v0.6.0 h1:3ZOBjXEKAdtJG99VJaKULCghMeWhE9UvZ6qbUnes+Fg=
|
||||
@@ -831,6 +865,8 @@ github.com/yuin/goldmark v1.8.6 h1:d0VcaP1sx9GkFVkoW+KtggpGi2KZ965i14b0+bDQST4=
|
||||
github.com/yuin/goldmark v1.8.6/go.mod h1:ip/1k0VRfGynBgxOz0yCqHrbZXhcjxyuS66Brc7iBKg=
|
||||
github.com/yusufpapurcu/wmi v1.2.4 h1:zFUKzehAFReQwLys1b/iSMl+JQGSCSjtVqQn9bBrPo0=
|
||||
github.com/yusufpapurcu/wmi v1.2.4/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0=
|
||||
github.com/zeebo/xxh3 v1.1.0 h1:s7DLGDK45Dyfg7++yxI0khrfwq9661w9EN78eP/UZVs=
|
||||
github.com/zeebo/xxh3 v1.1.0/go.mod h1:IisAie1LELR4xhVinxWS5+zf1lA4p0MW4T+w+W07F5s=
|
||||
github.com/ziutek/mymysql v1.5.4 h1:GB0qdRGsTwQSBVYuVShFBKaXSnSnYYC2d9knnE1LHFs=
|
||||
github.com/ziutek/mymysql v1.5.4/go.mod h1:LMSpPZ6DbqWFxNCHW77HeMg9I646SAhApZ/wKdgO/C0=
|
||||
gitlab.com/bosi/decorder v0.4.2 h1:qbQaV3zgwnBZ4zPMhGLW4KZe7A7NwxEhJx39R3shffo=
|
||||
@@ -865,8 +901,8 @@ go.opentelemetry.io/proto/otlp v0.7.0/go.mod h1:PqfVotwruBrMGOCsRd/89rSnXhoiJIqe
|
||||
go.uber.org/atomic v1.6.0/go.mod h1:sABNBOSYdrvTF6hTgEIbc7YasKWGhgEQZyfxyTvoXHQ=
|
||||
go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc=
|
||||
go.uber.org/atomic v1.9.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc=
|
||||
go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE=
|
||||
go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0=
|
||||
go.uber.org/atomic v1.12.0 h1:BvcXdFKuviU4fTL/f+SxdQ5qJX/Jix8pAkgdUcb3XOE=
|
||||
go.uber.org/atomic v1.12.0/go.mod h1:I6c4cg+6HCxRjfjSsYtApoFILnpc0CGUdGkXVqbYVNk=
|
||||
go.uber.org/goleak v1.1.10/go.mod h1:8a7PlsEVH3e/a/GLqe5IIrQx6GzcnRmZEufDUTk4A7A=
|
||||
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
|
||||
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
|
||||
|
||||
@@ -0,0 +1,316 @@
|
||||
//go:build integration
|
||||
|
||||
package integration_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"log/slog"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/testcontainers/testcontainers-go"
|
||||
"github.com/testcontainers/testcontainers-go/modules/postgres"
|
||||
"github.com/testcontainers/testcontainers-go/wait"
|
||||
|
||||
"lincodex/backend/config"
|
||||
postgresadapter "lincodex/backend/internal/adapter/secondary/postgres"
|
||||
redisadapter "lincodex/backend/internal/adapter/secondary/redis"
|
||||
"lincodex/backend/internal/adapter/secondary/seaweedfs"
|
||||
"lincodex/backend/internal/usecase/health"
|
||||
)
|
||||
|
||||
const (
|
||||
postgresImage = "postgres:alpine"
|
||||
redisImage = "redis:alpine"
|
||||
seaweedfsImage = "chrislusf/seaweedfs:latest"
|
||||
|
||||
postgresDatabase = "health"
|
||||
postgresUser = "health"
|
||||
postgresPassword = "health"
|
||||
redisPassword = "integration-cache-password"
|
||||
seaweedfsAccessKey = "integration-access"
|
||||
seaweedfsSecretKey = "integration-secret"
|
||||
seaweedfsBucket = "test-files"
|
||||
|
||||
startupTimeout = 90 * time.Second
|
||||
cleanupTimeout = 30 * time.Second
|
||||
stopTimeout = 15 * time.Second
|
||||
shutdownTimeout = 5 * time.Second
|
||||
seaweedfsStartupTimeout = time.Minute
|
||||
storageReadyTimeout = 30 * time.Second
|
||||
readinessInterval = 100 * time.Millisecond
|
||||
readinessTimeout = 5 * time.Second
|
||||
redisTimeout = 300 * time.Millisecond
|
||||
storageTimeout = 2 * time.Second
|
||||
)
|
||||
|
||||
type service uint8
|
||||
|
||||
const (
|
||||
postgresService service = iota
|
||||
redisService
|
||||
seaweedfsService
|
||||
)
|
||||
|
||||
type testEnvironment struct {
|
||||
Config config.Config
|
||||
Postgres *postgresadapter.HealthChecker
|
||||
Redis *redisadapter.Cache
|
||||
SeaweedFS *seaweedfs.Storage
|
||||
|
||||
owner *testing.T
|
||||
redisContainer testcontainers.Container
|
||||
seaweedfsContainer testcontainers.Container
|
||||
seaweedfsVolume string
|
||||
}
|
||||
|
||||
// bootstrap creates an isolated environment owned by t. Child tests may reuse it.
|
||||
func bootstrap(t *testing.T, services ...service) *testEnvironment {
|
||||
t.Helper()
|
||||
if len(services) == 0 {
|
||||
services = []service{postgresService, redisService, seaweedfsService}
|
||||
}
|
||||
for _, selected := range services {
|
||||
switch selected {
|
||||
case postgresService, redisService, seaweedfsService:
|
||||
default:
|
||||
t.Fatalf("unknown integration service: %d", selected)
|
||||
}
|
||||
}
|
||||
fixtures := map[string]string{
|
||||
"REDIS_PASSWORD": redisPassword,
|
||||
"REDIS_TIMEOUT": redisTimeout.String(),
|
||||
"SEAWEEDFS_ACCESS_KEY": seaweedfsAccessKey,
|
||||
"SEAWEEDFS_SECRET_KEY": seaweedfsSecretKey,
|
||||
"SEAWEEDFS_BUCKET": seaweedfsBucket,
|
||||
"SEAWEEDFS_TIMEOUT": storageTimeout.String(),
|
||||
}
|
||||
settings, err := config.LoadFromEnv(func(key string) (string, bool) {
|
||||
value, ok := fixtures[key]
|
||||
return value, ok
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("load integration configuration: %v", err)
|
||||
}
|
||||
env := &testEnvironment{Config: settings, owner: t}
|
||||
ctx, cancel := context.WithTimeout(t.Context(), startupTimeout)
|
||||
defer cancel()
|
||||
started := make(map[service]bool, len(services))
|
||||
for _, selected := range services {
|
||||
if started[selected] {
|
||||
continue
|
||||
}
|
||||
switch selected {
|
||||
case postgresService:
|
||||
env.startPostgres(ctx, t)
|
||||
case redisService:
|
||||
env.startRedis(ctx, t)
|
||||
case seaweedfsService:
|
||||
env.prepareStorageVolume()
|
||||
env.startSeaweedFS(ctx, t)
|
||||
}
|
||||
started[selected] = true
|
||||
}
|
||||
return env
|
||||
}
|
||||
|
||||
func (env *testEnvironment) cleanupContainer(ctx context.Context, container testcontainers.Container, name string) {
|
||||
env.owner.Cleanup(func() {
|
||||
ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), cleanupTimeout)
|
||||
defer cancel()
|
||||
if err := testcontainers.TerminateContainer(container, testcontainers.StopContext(ctx), testcontainers.StopTimeout(shutdownTimeout)); err != nil {
|
||||
env.owner.Errorf("terminate %s container: %v", name, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func (env *testEnvironment) startPostgres(ctx context.Context, t *testing.T) {
|
||||
t.Helper()
|
||||
container, err := postgres.Run(ctx, postgresImage,
|
||||
postgres.WithDatabase(postgresDatabase),
|
||||
postgres.WithUsername(postgresUser),
|
||||
postgres.WithPassword(postgresPassword),
|
||||
postgres.BasicWaitStrategies(),
|
||||
)
|
||||
env.cleanupContainer(ctx, container, "PostgreSQL")
|
||||
if err != nil {
|
||||
t.Fatalf("start PostgreSQL container: %v", err)
|
||||
}
|
||||
databaseURL, err := container.ConnectionString(ctx, "sslmode=disable")
|
||||
if err != nil {
|
||||
t.Fatalf("get PostgreSQL connection string: %v", err)
|
||||
}
|
||||
env.Config.DatabaseURL = databaseURL
|
||||
checker, cleanup, err := postgresadapter.NewHealthChecker(ctx, env.Config)
|
||||
if err != nil {
|
||||
t.Fatalf("create PostgreSQL health checker: %v", err)
|
||||
}
|
||||
env.owner.Cleanup(cleanup)
|
||||
env.Postgres = checker
|
||||
if err := env.Postgres.Check(ctx); err != nil {
|
||||
t.Fatalf("PostgreSQL readiness: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func (env *testEnvironment) startRedis(ctx context.Context, t *testing.T) {
|
||||
t.Helper()
|
||||
container, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{
|
||||
ContainerRequest: testcontainers.ContainerRequest{
|
||||
Image: redisImage,
|
||||
ExposedPorts: []string{"6379/tcp"},
|
||||
Cmd: []string{"redis-server", "--requirepass", env.Config.RedisPassword, "--save", "", "--appendonly", "no"},
|
||||
WaitingFor: wait.ForLog("Ready to accept connections"),
|
||||
},
|
||||
Started: true,
|
||||
})
|
||||
env.cleanupContainer(ctx, container, "Redis")
|
||||
if err != nil {
|
||||
t.Fatalf("start Redis container: %v", err)
|
||||
}
|
||||
env.redisContainer = container
|
||||
address, err := container.PortEndpoint(ctx, "6379/tcp", "")
|
||||
if err != nil {
|
||||
t.Fatalf("get Redis address: %v", err)
|
||||
}
|
||||
env.Config.RedisAddr = address
|
||||
env.Redis = env.newRedis(t, env.Config)
|
||||
if err := env.Redis.Check(ctx); err != nil {
|
||||
t.Fatalf("Redis readiness: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func (env *testEnvironment) newRedis(t *testing.T, settings config.Config) *redisadapter.Cache {
|
||||
t.Helper()
|
||||
cache, cleanup, err := redisadapter.NewCache(settings, slog.New(slog.DiscardHandler))
|
||||
if err != nil {
|
||||
t.Fatalf("create Redis cache: %v", err)
|
||||
}
|
||||
env.owner.Cleanup(cleanup)
|
||||
return cache
|
||||
}
|
||||
|
||||
func (env *testEnvironment) stopRedis(ctx context.Context, t *testing.T) {
|
||||
t.Helper()
|
||||
if env.redisContainer == nil {
|
||||
t.Fatal("Redis was not selected in bootstrap")
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(ctx, stopTimeout)
|
||||
defer cancel()
|
||||
timeout := shutdownTimeout
|
||||
if err := env.redisContainer.Stop(ctx, &timeout); err != nil {
|
||||
t.Fatalf("stop Redis: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func (env *testEnvironment) prepareStorageVolume() {
|
||||
env.seaweedfsVolume = "seaweedfs-test-" + strings.ToLower(rand.Text())
|
||||
// Register volume cleanup before startup so partially started containers do
|
||||
// not leave their volume behind. Container cleanup runs first in LIFO order.
|
||||
env.owner.Cleanup(func() {
|
||||
ctx, cancel := context.WithTimeout(context.WithoutCancel(env.owner.Context()), cleanupTimeout)
|
||||
defer cancel()
|
||||
if err := testcontainers.NewTerminateOptions(ctx, testcontainers.RemoveVolumes(env.seaweedfsVolume)).Cleanup(); err != nil {
|
||||
env.owner.Errorf("remove SeaweedFS test volume: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func (env *testEnvironment) startSeaweedFS(ctx context.Context, t *testing.T) {
|
||||
t.Helper()
|
||||
container, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{
|
||||
ContainerRequest: testcontainers.ContainerRequest{
|
||||
Image: seaweedfsImage,
|
||||
ExposedPorts: []string{"8333/tcp"},
|
||||
Env: map[string]string{
|
||||
"AWS_ACCESS_KEY_ID": env.Config.SeaweedFSAccessKey,
|
||||
"AWS_SECRET_ACCESS_KEY": env.Config.SeaweedFSSecretKey,
|
||||
"S3_BUCKET": env.Config.SeaweedFSBucket,
|
||||
},
|
||||
Cmd: []string{
|
||||
"mini", "-dir=/data", "-ip=127.0.0.1", "-ip.bind=0.0.0.0",
|
||||
"-webdav=false", "-admin.ui=false", "-s3.iam=false",
|
||||
"-s3.port.iceberg=0", "-s3.port.lance=0", "-s3.autoCreateBucket=false",
|
||||
"-s3.allowDeleteBucketNotEmpty=false", "-master.telemetry=false",
|
||||
},
|
||||
Mounts: testcontainers.ContainerMounts{testcontainers.VolumeMount(env.seaweedfsVolume, "/data")},
|
||||
WaitingFor: wait.ForHTTP("/healthz").WithPort("8333/tcp").WithStartupTimeout(seaweedfsStartupTimeout),
|
||||
},
|
||||
Started: true,
|
||||
})
|
||||
env.cleanupContainer(ctx, container, "SeaweedFS")
|
||||
if err != nil {
|
||||
t.Fatalf("start SeaweedFS container: %v", err)
|
||||
}
|
||||
env.seaweedfsContainer = container
|
||||
endpoint, err := container.PortEndpoint(ctx, "8333/tcp", "http")
|
||||
if err != nil {
|
||||
t.Fatalf("get SeaweedFS endpoint: %v", err)
|
||||
}
|
||||
env.Config.SeaweedFSEndpoint = endpoint
|
||||
env.SeaweedFS = env.newStorage(t, env.Config)
|
||||
waitForStorage(ctx, t, env.SeaweedFS)
|
||||
}
|
||||
|
||||
func (env *testEnvironment) newStorage(t *testing.T, settings config.Config) *seaweedfs.Storage {
|
||||
t.Helper()
|
||||
storage, cleanup, err := seaweedfs.NewStorage(settings)
|
||||
if err != nil {
|
||||
t.Fatalf("create SeaweedFS storage: %v", err)
|
||||
}
|
||||
env.owner.Cleanup(cleanup)
|
||||
return storage
|
||||
}
|
||||
|
||||
func (env *testEnvironment) recreateSeaweedFS(ctx context.Context, t *testing.T) {
|
||||
t.Helper()
|
||||
if env.seaweedfsContainer == nil {
|
||||
t.Fatal("SeaweedFS was not selected in bootstrap")
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(ctx, startupTimeout)
|
||||
defer cancel()
|
||||
if err := testcontainers.TerminateContainer(env.seaweedfsContainer, testcontainers.StopContext(ctx), testcontainers.StopTimeout(shutdownTimeout)); err != nil {
|
||||
t.Fatalf("remove first SeaweedFS container: %v", err)
|
||||
}
|
||||
env.startSeaweedFS(ctx, t)
|
||||
}
|
||||
|
||||
func waitForStorage(ctx context.Context, t *testing.T, storage *seaweedfs.Storage) {
|
||||
t.Helper()
|
||||
// The S3 listener starts before mini finishes provisioning configured buckets.
|
||||
ctx, cancel := context.WithTimeout(ctx, storageReadyTimeout)
|
||||
defer cancel()
|
||||
ticker := time.NewTicker(readinessInterval)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
err := storage.Check(ctx)
|
||||
if err == nil {
|
||||
return
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
t.Fatalf("wait for configured SeaweedFS bucket: %v", err)
|
||||
case <-ticker.C:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestBootstrapReadiness(t *testing.T) {
|
||||
env := bootstrap(t)
|
||||
if err := env.Config.Validate(); err != nil {
|
||||
t.Fatalf("invalid full bootstrap configuration: %v", err)
|
||||
}
|
||||
readiness := health.NewReadiness(env.Postgres, env.Redis, env.SeaweedFS)
|
||||
ctx, cancel := context.WithTimeout(t.Context(), readinessTimeout)
|
||||
defer cancel()
|
||||
if err := readiness.Check(ctx); err != nil {
|
||||
t.Fatalf("full environment is not ready: %v", err)
|
||||
}
|
||||
env.stopRedis(t.Context(), t)
|
||||
outageCtx, outageCancel := context.WithTimeout(t.Context(), readinessTimeout)
|
||||
defer outageCancel()
|
||||
if err := readiness.Check(outageCtx); err == nil {
|
||||
t.Fatal("full environment stayed ready after Redis stopped")
|
||||
}
|
||||
}
|
||||
@@ -5,46 +5,13 @@ package integration_test
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/testcontainers/testcontainers-go"
|
||||
"github.com/testcontainers/testcontainers-go/modules/postgres"
|
||||
|
||||
"lincodex/backend/config"
|
||||
postgresadapter "lincodex/backend/internal/adapter/secondary/postgres"
|
||||
)
|
||||
|
||||
func TestPostgresHealthQueryAgainstContainer(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second)
|
||||
env := bootstrap(t, postgresService)
|
||||
ctx, cancel := context.WithTimeout(t.Context(), readinessTimeout)
|
||||
defer cancel()
|
||||
container, err := postgres.Run(ctx, "postgres:alpine",
|
||||
postgres.WithDatabase("health"),
|
||||
postgres.WithUsername("health"),
|
||||
postgres.WithPassword("health"),
|
||||
postgres.BasicWaitStrategies(),
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("start PostgreSQL container: %v", err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
if err := testcontainers.TerminateContainer(container); err != nil {
|
||||
t.Errorf("terminate PostgreSQL container: %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
databaseURL, err := container.ConnectionString(ctx, "sslmode=disable")
|
||||
if err != nil {
|
||||
t.Fatalf("get PostgreSQL connection string: %v", err)
|
||||
}
|
||||
checker, closePool, err := postgresadapter.NewHealthChecker(ctx, config.Config{DatabaseURL: databaseURL})
|
||||
if err != nil {
|
||||
t.Fatalf("create PostgreSQL health checker: %v", err)
|
||||
}
|
||||
defer closePool()
|
||||
|
||||
checkContext, checkCancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
defer checkCancel()
|
||||
if err := checker.Check(checkContext); err != nil {
|
||||
if err := env.Postgres.Check(ctx); err != nil {
|
||||
t.Fatalf("PostgreSQL health query failed: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
//go:build integration
|
||||
|
||||
package integration_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
func TestRedisCacheAgainstContainer(t *testing.T) {
|
||||
env := bootstrap(t, redisService)
|
||||
ctx := t.Context()
|
||||
settings, cache := env.Config, env.Redis
|
||||
|
||||
t.Run("values misses and deletion", func(t *testing.T) {
|
||||
if _, err := cache.Get(ctx, "absent"); !errors.Is(err, outbound.ErrCacheMiss) {
|
||||
t.Fatalf("missing key: %v", err)
|
||||
}
|
||||
if err := cache.Set(ctx, "value", []byte{0, 1, 255}, time.Minute); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
value, err := cache.Get(ctx, "value")
|
||||
if err != nil || string(value) != string([]byte{0, 1, 255}) {
|
||||
t.Fatalf("Get returned %v, %v", value, err)
|
||||
}
|
||||
if err := cache.Del(ctx, "value", "absent"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := cache.Get(ctx, "value"); !errors.Is(err, outbound.ErrCacheMiss) {
|
||||
t.Fatalf("deleted key: %v", err)
|
||||
}
|
||||
if err := cache.Del(ctx); err != nil {
|
||||
t.Fatalf("empty deletion: %v", err)
|
||||
}
|
||||
if err := cache.Set(ctx, "empty", []byte{}, time.Minute); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if value, err := cache.Get(ctx, "empty"); err != nil || len(value) != 0 {
|
||||
t.Fatalf("empty value: %v, %v", value, err)
|
||||
}
|
||||
})
|
||||
t.Run("expiration and rejected writes", func(t *testing.T) {
|
||||
if err := cache.Set(ctx, "expires", []byte("value"), 50*time.Millisecond); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
deadline := time.Now().Add(3 * time.Second)
|
||||
for {
|
||||
_, err := cache.Get(ctx, "expires")
|
||||
if errors.Is(err, outbound.ErrCacheMiss) {
|
||||
break
|
||||
}
|
||||
if err != nil || time.Now().After(deadline) {
|
||||
t.Fatalf("TTL did not expire: %v", err)
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
for _, ttl := range []time.Duration{0, -time.Second} {
|
||||
if err := cache.Set(ctx, "invalid", []byte("value"), ttl); !errors.Is(err, outbound.ErrInvalidCacheTTL) {
|
||||
t.Fatalf("invalid TTL: %v", err)
|
||||
}
|
||||
}
|
||||
if _, err := cache.Get(ctx, "invalid"); !errors.Is(err, outbound.ErrCacheMiss) {
|
||||
t.Fatalf("invalid write persisted: %v", err)
|
||||
}
|
||||
if err := cache.Set(ctx, "", []byte("value"), time.Minute); !errors.Is(err, outbound.ErrInvalidCacheKey) {
|
||||
t.Fatalf("empty key: %v", err)
|
||||
}
|
||||
})
|
||||
t.Run("database isolation", func(t *testing.T) {
|
||||
other := settings
|
||||
other.RedisDB = 1
|
||||
cache := env.newRedis(t, other)
|
||||
if _, err := cache.Get(ctx, "empty"); !errors.Is(err, outbound.ErrCacheMiss) {
|
||||
t.Fatalf("database isolation: %v", err)
|
||||
}
|
||||
})
|
||||
t.Run("authentication failure is not a miss", func(t *testing.T) {
|
||||
other := settings
|
||||
other.RedisPassword = "wrong-password"
|
||||
cache := env.newRedis(t, other)
|
||||
if err := cache.Check(ctx); err == nil {
|
||||
t.Fatal("wrong password passed readiness")
|
||||
}
|
||||
if _, err := cache.Get(ctx, "absent"); err == nil || errors.Is(err, outbound.ErrCacheMiss) {
|
||||
t.Fatalf("auth error classified as cache miss: %v", err)
|
||||
}
|
||||
})
|
||||
t.Run("caller cancellation", func(t *testing.T) {
|
||||
canceled, cancel := context.WithCancel(ctx)
|
||||
cancel()
|
||||
if _, err := cache.Get(canceled, "empty"); !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("Get ignored cancellation: %v", err)
|
||||
}
|
||||
if err := cache.Set(canceled, "canceled", []byte("value"), time.Minute); !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("Set ignored cancellation: %v", err)
|
||||
}
|
||||
if err := cache.Del(canceled, "empty"); !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("Del ignored cancellation: %v", err)
|
||||
}
|
||||
if err := cache.Check(canceled); !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("Ping ignored cancellation: %v", err)
|
||||
}
|
||||
})
|
||||
t.Run("outage is not a miss", func(t *testing.T) {
|
||||
env.stopRedis(ctx, t)
|
||||
start := time.Now()
|
||||
if _, err := cache.Get(ctx, "empty"); err == nil || errors.Is(err, outbound.ErrCacheMiss) {
|
||||
t.Fatalf("outage classified as cache miss: %v", err)
|
||||
}
|
||||
if elapsed := time.Since(start); elapsed > 2*time.Second {
|
||||
t.Fatalf("outage exceeded timeout budget: %s", elapsed)
|
||||
}
|
||||
if err := cache.Check(ctx); err == nil {
|
||||
t.Fatal("outage passed readiness")
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
//go:build integration
|
||||
|
||||
package integration_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"lincodex/backend/internal/adapter/secondary/seaweedfs"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
func TestSeaweedFSStorageAgainstContainer(t *testing.T) {
|
||||
env := bootstrap(t, seaweedfsService)
|
||||
ctx := t.Context()
|
||||
settings, storage := env.Config, env.SeaweedFS
|
||||
payload := []byte{0, 1, 255, 2, 0, 3}
|
||||
const key = "private/documents/test.pdf"
|
||||
|
||||
t.Run("objects metadata and deletion", func(t *testing.T) {
|
||||
if err := storage.Check(ctx); err != nil {
|
||||
t.Fatalf("bucket readiness: %v", err)
|
||||
}
|
||||
if _, err := storage.Get(ctx, "absent"); !errors.Is(err, outbound.ErrObjectNotFound) {
|
||||
t.Fatalf("missing object: %v", err)
|
||||
}
|
||||
if err := storage.Put(ctx, key, struct{ io.Reader }{bytes.NewReader(payload)}, int64(len(payload)), "application/pdf"); err != nil {
|
||||
t.Fatalf("upload: %v", err)
|
||||
}
|
||||
assertStoredObject(ctx, t, storage, key, payload, "application/pdf")
|
||||
if err := storage.Delete(ctx, key); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := storage.Delete(ctx, key); err != nil {
|
||||
t.Fatalf("repeated deletion: %v", err)
|
||||
}
|
||||
if _, err := storage.Get(ctx, key); !errors.Is(err, outbound.ErrObjectNotFound) {
|
||||
t.Fatalf("deleted object: %v", err)
|
||||
}
|
||||
if err := storage.Put(ctx, "empty", bytes.NewReader(nil), 0, "application/octet-stream"); err != nil {
|
||||
t.Fatalf("empty object: %v", err)
|
||||
}
|
||||
assertStoredObject(ctx, t, storage, "empty", nil, "application/octet-stream")
|
||||
})
|
||||
t.Run("authentication failure is not absence", func(t *testing.T) {
|
||||
other := settings
|
||||
other.SeaweedFSSecretKey = "wrong-secret"
|
||||
unauthorized := env.newStorage(t, other)
|
||||
if err := unauthorized.Check(ctx); err == nil {
|
||||
t.Fatal("invalid credentials passed readiness")
|
||||
}
|
||||
if _, err := unauthorized.Get(ctx, "empty"); err == nil || errors.Is(err, outbound.ErrObjectNotFound) {
|
||||
t.Fatalf("invalid credentials classified as absence: %v", err)
|
||||
}
|
||||
if err := unauthorized.Put(ctx, "unauthorized", strings.NewReader("no"), 2, "text/plain"); err == nil {
|
||||
t.Fatal("invalid credentials uploaded an object")
|
||||
}
|
||||
if err := unauthorized.Delete(ctx, "empty"); err == nil {
|
||||
t.Fatal("invalid credentials deleted an object")
|
||||
}
|
||||
assertStoredObject(ctx, t, storage, "empty", nil, "application/octet-stream")
|
||||
})
|
||||
t.Run("missing bucket is not created by readiness", func(t *testing.T) {
|
||||
other := settings
|
||||
other.SeaweedFSBucket = "absent-bucket"
|
||||
missingBucket := env.newStorage(t, other)
|
||||
if err := missingBucket.Check(ctx); err == nil {
|
||||
t.Fatal("missing bucket passed readiness")
|
||||
}
|
||||
if _, err := missingBucket.Get(ctx, "empty"); err == nil || errors.Is(err, outbound.ErrObjectNotFound) {
|
||||
t.Fatalf("missing bucket classified as missing object: %v", err)
|
||||
}
|
||||
if err := missingBucket.Put(ctx, "object", strings.NewReader("no"), 2, "text/plain"); err == nil {
|
||||
t.Fatal("upload silently created missing bucket")
|
||||
}
|
||||
})
|
||||
t.Run("caller cancellation", func(t *testing.T) {
|
||||
canceled, cancel := context.WithCancel(ctx)
|
||||
cancel()
|
||||
if _, err := storage.Get(canceled, "empty"); !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("Get ignored cancellation: %v", err)
|
||||
}
|
||||
if err := storage.Put(canceled, "canceled", strings.NewReader("data"), 4, "text/plain"); !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("Put ignored cancellation: %v", err)
|
||||
}
|
||||
if err := storage.Delete(canceled, "empty"); !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("Delete ignored cancellation: %v", err)
|
||||
}
|
||||
if err := storage.Check(canceled); !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("HeadBucket ignored cancellation: %v", err)
|
||||
}
|
||||
})
|
||||
t.Run("objects survive container recreation", func(t *testing.T) {
|
||||
if err := storage.Put(ctx, key, bytes.NewReader(payload), int64(len(payload)), "application/pdf"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
env.recreateSeaweedFS(ctx, t)
|
||||
assertStoredObject(ctx, t, env.SeaweedFS, key, payload, "application/pdf")
|
||||
})
|
||||
}
|
||||
|
||||
func assertStoredObject(ctx context.Context, t *testing.T, storage *seaweedfs.Storage, key string, want []byte, contentType string) {
|
||||
t.Helper()
|
||||
object, err := storage.Get(ctx, key)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer object.Body.Close()
|
||||
data, err := io.ReadAll(object.Body)
|
||||
if err != nil || !bytes.Equal(data, want) || object.Size != int64(len(want)) || object.ContentType != contentType {
|
||||
t.Fatalf("stored object or metadata differs: size=%d type=%q error=%v", object.Size, object.ContentType, err)
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package httpadapter
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
|
||||
@@ -12,19 +13,28 @@ import (
|
||||
v1 "lincodex/backend/internal/adapter/primary/http/v1"
|
||||
)
|
||||
|
||||
func NewRouter(health *v1.HealthHandler, collector httpmiddleware.RequestMetrics, logger *slog.Logger) (http.Handler, error) {
|
||||
const (
|
||||
healthPath = "/healthz"
|
||||
readinessPath = "/readyz"
|
||||
)
|
||||
|
||||
func NewRouter(
|
||||
health *v1.HealthHandler,
|
||||
collector httpmiddleware.RequestMetrics,
|
||||
logger *slog.Logger,
|
||||
) (http.Handler, error) {
|
||||
apiServer, err := apiadapter.NewServer(health)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, fmt.Errorf("httpadapter.NewRouter - create API server: %w", err)
|
||||
}
|
||||
|
||||
router := chi.NewRouter()
|
||||
router.Use(kitmiddleware.RequestID())
|
||||
router.Use(kitmiddleware.Recoverer(logger))
|
||||
router.Use(kitmiddleware.Logger(logger, nil, kitmiddleware.WithSkipPaths("/healthz", "/readyz")))
|
||||
router.Use(kitmiddleware.Logger(logger, nil, kitmiddleware.WithSkipPaths(healthPath, readinessPath)))
|
||||
router.Use(httpmiddleware.CollectMetrics(collector))
|
||||
router.Get("/healthz", health.Healthz)
|
||||
router.Get("/readyz", health.Readyz)
|
||||
router.Get(healthPath, health.Healthz)
|
||||
router.Get(readinessPath, health.Readyz)
|
||||
router.Handle("/api/v1/*", apiServer)
|
||||
return router, nil
|
||||
}
|
||||
@@ -40,6 +40,7 @@ func (handler *HealthHandler) Readyz(w http.ResponseWriter, r *http.Request) {
|
||||
func writeStatus(w http.ResponseWriter, status int, value string) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
// The status is already committed; a failed write cannot be retried here.
|
||||
_ = json.NewEncoder(w).Encode(struct {
|
||||
Status string `json:"status"`
|
||||
}{Status: value})
|
||||
|
||||
@@ -23,11 +23,11 @@ func NewHealthChecker(ctx context.Context, config config.Config) (*HealthChecker
|
||||
|
||||
poolConfig, err := pgxpool.ParseConfig(config.DatabaseURL)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("parse DATABASE_URL: %w", err)
|
||||
return nil, nil, fmt.Errorf("postgres.NewHealthChecker - parse DATABASE_URL: %w", err)
|
||||
}
|
||||
pool, err := pgxpool.NewWithConfig(ctx, poolConfig)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("create PostgreSQL pool: %w", err)
|
||||
return nil, nil, fmt.Errorf("postgres.NewHealthChecker - create PostgreSQL pool: %w", err)
|
||||
}
|
||||
|
||||
return &HealthChecker{pool: pool, queries: sqlc.New(pool)}, pool.Close, nil
|
||||
@@ -35,10 +35,10 @@ func NewHealthChecker(ctx context.Context, config config.Config) (*HealthChecker
|
||||
|
||||
func (checker *HealthChecker) Check(ctx context.Context) error {
|
||||
if checker.pool == nil || checker.queries == nil {
|
||||
return outbound.ErrNotReady
|
||||
return fmt.Errorf("HealthChecker.Check - check configured database: %w", outbound.ErrNotReady)
|
||||
}
|
||||
if _, err := checker.queries.Ping(ctx); err != nil {
|
||||
return fmt.Errorf("PostgreSQL health query: %w", err)
|
||||
return fmt.Errorf("HealthChecker.Check - query PostgreSQL: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package redis
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
cachekit "github.com/wahrwelt-kit/go-cachekit"
|
||||
|
||||
"lincodex/backend/config"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
const (
|
||||
connectionLimit = 10
|
||||
disabledRetries = -1
|
||||
)
|
||||
|
||||
type Cache struct {
|
||||
client *redis.Client
|
||||
store *cachekit.RedisKeyValueStore
|
||||
timeout time.Duration
|
||||
}
|
||||
|
||||
var (
|
||||
_ outbound.Cache = (*Cache)(nil)
|
||||
_ outbound.ReadinessChecker = (*Cache)(nil)
|
||||
)
|
||||
|
||||
// NewCache creates a lazy connection pool. Readiness checks verify connectivity.
|
||||
func NewCache(settings config.Config, logger *slog.Logger) (*Cache, func(), error) {
|
||||
if err := settings.ValidateRedis(); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
client := redis.NewClient(&redis.Options{
|
||||
Addr: settings.RedisAddr,
|
||||
Password: settings.RedisPassword,
|
||||
DB: settings.RedisDB,
|
||||
DialTimeout: settings.RedisTimeout,
|
||||
ReadTimeout: settings.RedisTimeout,
|
||||
WriteTimeout: settings.RedisTimeout,
|
||||
PoolTimeout: settings.RedisTimeout,
|
||||
ContextTimeoutEnabled: true,
|
||||
MaxRetries: disabledRetries,
|
||||
PoolSize: connectionLimit,
|
||||
MaxActiveConns: connectionLimit,
|
||||
})
|
||||
cache := &Cache{
|
||||
client: client,
|
||||
store: &cachekit.RedisKeyValueStore{Client: client},
|
||||
timeout: settings.RedisTimeout,
|
||||
}
|
||||
return cache, func() {
|
||||
if err := client.Close(); err != nil {
|
||||
logger.Error("redis.NewCache - close client", "error", err)
|
||||
}
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (cache *Cache) Get(ctx context.Context, key string) ([]byte, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, cache.timeout)
|
||||
defer cancel()
|
||||
value, err := cache.store.Get(ctx, key)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("Cache.Get - get value: %w", cacheError(err))
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
|
||||
func (cache *Cache) Set(ctx context.Context, key string, value []byte, ttl time.Duration) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, cache.timeout)
|
||||
defer cancel()
|
||||
if err := cache.store.Set(ctx, key, value, ttl); err != nil {
|
||||
return fmt.Errorf("Cache.Set - set value: %w", cacheError(err))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (cache *Cache) Del(ctx context.Context, keys ...string) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, cache.timeout)
|
||||
defer cancel()
|
||||
if err := cache.store.Del(ctx, keys...); err != nil {
|
||||
return fmt.Errorf("Cache.Del - delete values: %w", cacheError(err))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (cache *Cache) Check(ctx context.Context) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, cache.timeout)
|
||||
defer cancel()
|
||||
if err := cache.client.Ping(ctx).Err(); err != nil {
|
||||
return fmt.Errorf("Cache.Check - ping Redis: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func cacheError(err error) error {
|
||||
switch {
|
||||
case errors.Is(err, cachekit.ErrNotFound):
|
||||
return outbound.ErrCacheMiss
|
||||
case errors.Is(err, cachekit.ErrEmptyKey):
|
||||
return outbound.ErrInvalidCacheKey
|
||||
case errors.Is(err, cachekit.ErrInvalidTTL):
|
||||
return outbound.ErrInvalidCacheTTL
|
||||
default:
|
||||
return err
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package redis
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"lincodex/backend/config"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
func TestColdConnectionHonorsTimeout(t *testing.T) {
|
||||
for _, callerDeadline := range []bool{false, true} {
|
||||
name := "configured timeout"
|
||||
if callerDeadline {
|
||||
name = "shorter caller deadline"
|
||||
}
|
||||
t.Run(name, func(t *testing.T) {
|
||||
listener, err := (&net.ListenConfig{}).Listen(t.Context(), "tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
release := make(chan struct{})
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
defer close(done)
|
||||
connection, err := listener.Accept()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer connection.Close()
|
||||
<-release
|
||||
}()
|
||||
t.Cleanup(func() {
|
||||
close(release)
|
||||
_ = listener.Close()
|
||||
<-done
|
||||
})
|
||||
timeout := 100 * time.Millisecond
|
||||
if callerDeadline {
|
||||
timeout = time.Second
|
||||
}
|
||||
cache, cleanup, err := NewCache(config.Config{RedisAddr: listener.Addr().String(), RedisTimeout: timeout}, slog.New(slog.DiscardHandler))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(cleanup)
|
||||
ctx := t.Context()
|
||||
if callerDeadline {
|
||||
var cancel context.CancelFunc
|
||||
ctx, cancel = context.WithTimeout(ctx, 100*time.Millisecond)
|
||||
defer cancel()
|
||||
}
|
||||
started := time.Now()
|
||||
_, err = cache.Get(ctx, "absent")
|
||||
elapsed := time.Since(started)
|
||||
if err == nil || errors.Is(err, outbound.ErrCacheMiss) {
|
||||
t.Fatalf("unresponsive server: %v", err)
|
||||
}
|
||||
if elapsed > 500*time.Millisecond {
|
||||
t.Fatalf("cold connection ignored timeout: elapsed=%s error=%v", elapsed, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
package seaweedfs
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/aws/aws-sdk-go-v2/aws"
|
||||
v4 "github.com/aws/aws-sdk-go-v2/aws/signer/v4"
|
||||
"github.com/aws/aws-sdk-go-v2/credentials"
|
||||
"github.com/aws/aws-sdk-go-v2/service/s3"
|
||||
"github.com/aws/aws-sdk-go-v2/service/s3/types"
|
||||
smithyhttp "github.com/aws/smithy-go/transport/http"
|
||||
|
||||
"lincodex/backend/config"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
const (
|
||||
connectionKeepAlive = 30 * time.Second
|
||||
maxIdleConnections = 10
|
||||
maxConnectionsPerHost = 20
|
||||
idleConnectionTimeout = 90 * time.Second
|
||||
expectContinueTimeout = time.Second
|
||||
)
|
||||
|
||||
type Storage struct {
|
||||
client *s3.Client
|
||||
bucket string
|
||||
timeout time.Duration
|
||||
}
|
||||
|
||||
var (
|
||||
_ outbound.ObjectStorage = (*Storage)(nil)
|
||||
_ outbound.ReadinessChecker = (*Storage)(nil)
|
||||
)
|
||||
|
||||
// NewStorage creates a lazy S3 client. Deployment owns bucket provisioning.
|
||||
func NewStorage(settings config.Config) (*Storage, func(), error) {
|
||||
if err := settings.ValidateSeaweedFS(); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
transport := &http.Transport{
|
||||
DialContext: (&net.Dialer{Timeout: settings.SeaweedFSTimeout, KeepAlive: connectionKeepAlive}).DialContext,
|
||||
ForceAttemptHTTP2: true,
|
||||
MaxIdleConns: maxIdleConnections,
|
||||
MaxIdleConnsPerHost: maxIdleConnections,
|
||||
MaxConnsPerHost: maxConnectionsPerHost,
|
||||
IdleConnTimeout: idleConnectionTimeout,
|
||||
TLSHandshakeTimeout: settings.SeaweedFSTimeout,
|
||||
ResponseHeaderTimeout: settings.SeaweedFSTimeout,
|
||||
ExpectContinueTimeout: expectContinueTimeout,
|
||||
}
|
||||
client := s3.New(s3.Options{
|
||||
Region: settings.SeaweedFSRegion,
|
||||
BaseEndpoint: aws.String(settings.SeaweedFSEndpoint),
|
||||
UsePathStyle: true,
|
||||
Credentials: credentials.NewStaticCredentialsProvider(settings.SeaweedFSAccessKey, settings.SeaweedFSSecretKey, ""),
|
||||
HTTPClient: &http.Client{
|
||||
Transport: transport,
|
||||
Timeout: settings.SeaweedFSTimeout,
|
||||
CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse },
|
||||
},
|
||||
// A non-seekable upload cannot be replayed safely.
|
||||
Retryer: aws.NopRetryer{},
|
||||
RequestChecksumCalculation: aws.RequestChecksumCalculationWhenRequired,
|
||||
ResponseChecksumValidation: aws.ResponseChecksumValidationWhenRequired,
|
||||
DisableLogOutputChecksumValidationSkipped: true,
|
||||
})
|
||||
return &Storage{client: client, bucket: settings.SeaweedFSBucket, timeout: settings.SeaweedFSTimeout}, transport.CloseIdleConnections, nil
|
||||
}
|
||||
|
||||
func (storage *Storage) Put(ctx context.Context, key string, body io.Reader, size int64, contentType string) error {
|
||||
if key == "" || body == nil || size < 0 {
|
||||
return fmt.Errorf("Storage.Put - validate input: %w", outbound.ErrInvalidObject)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(ctx, storage.timeout)
|
||||
defer cancel()
|
||||
_, err := storage.client.PutObject(ctx, &s3.PutObjectInput{
|
||||
Bucket: aws.String(storage.bucket),
|
||||
Key: aws.String(key),
|
||||
Body: body,
|
||||
ContentLength: aws.Int64(size),
|
||||
ContentType: aws.String(contentType),
|
||||
}, s3.WithAPIOptions(v4.SwapComputePayloadSHA256ForUnsignedPayloadMiddleware))
|
||||
if err != nil {
|
||||
return fmt.Errorf("Storage.Put - put object: %w", safeError(err))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (storage *Storage) Get(ctx context.Context, key string) (outbound.Object, error) {
|
||||
if key == "" {
|
||||
return outbound.Object{}, fmt.Errorf("Storage.Get - validate key: %w", outbound.ErrInvalidObject)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(ctx, storage.timeout)
|
||||
result, err := storage.client.GetObject(ctx, &s3.GetObjectInput{Bucket: aws.String(storage.bucket), Key: aws.String(key)})
|
||||
if err != nil {
|
||||
cancel()
|
||||
var missing *types.NoSuchKey
|
||||
if errors.As(err, &missing) {
|
||||
return outbound.Object{}, fmt.Errorf("Storage.Get - get object: %w", outbound.ErrObjectNotFound)
|
||||
}
|
||||
return outbound.Object{}, fmt.Errorf("Storage.Get - get object: %w", safeError(err))
|
||||
}
|
||||
return outbound.Object{
|
||||
Body: &objectBody{body: result.Body, cancel: cancel},
|
||||
Size: aws.ToInt64(result.ContentLength),
|
||||
ContentType: aws.ToString(result.ContentType),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (storage *Storage) Delete(ctx context.Context, key string) error {
|
||||
if key == "" {
|
||||
return fmt.Errorf("Storage.Delete - validate key: %w", outbound.ErrInvalidObject)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(ctx, storage.timeout)
|
||||
defer cancel()
|
||||
_, err := storage.client.DeleteObject(ctx, &s3.DeleteObjectInput{Bucket: aws.String(storage.bucket), Key: aws.String(key)})
|
||||
if err != nil {
|
||||
return fmt.Errorf("Storage.Delete - delete object: %w", safeError(err))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (storage *Storage) Check(ctx context.Context) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, storage.timeout)
|
||||
defer cancel()
|
||||
_, err := storage.client.HeadBucket(ctx, &s3.HeadBucketInput{Bucket: aws.String(storage.bucket)})
|
||||
if err != nil {
|
||||
return fmt.Errorf("Storage.Check - check bucket: %w", safeError(err))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// safeError keeps cancellation identifiable without exposing SDK URLs, keys,
|
||||
// credentials, or server-controlled messages in application errors and logs.
|
||||
func safeError(err error) error {
|
||||
switch {
|
||||
case errors.Is(err, context.Canceled):
|
||||
return context.Canceled
|
||||
case errors.Is(err, context.DeadlineExceeded):
|
||||
return context.DeadlineExceeded
|
||||
default:
|
||||
var response *smithyhttp.ResponseError
|
||||
if errors.As(err, &response) {
|
||||
return fmt.Errorf("seaweedfs.safeError - HTTP %d: %w", response.HTTPStatusCode(), outbound.ErrObjectStorage)
|
||||
}
|
||||
return outbound.ErrObjectStorage
|
||||
}
|
||||
}
|
||||
|
||||
type objectBody struct {
|
||||
body io.ReadCloser
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
func (body *objectBody) Read(buffer []byte) (int, error) {
|
||||
n, err := body.body.Read(buffer)
|
||||
if err != nil {
|
||||
body.cancel()
|
||||
if !errors.Is(err, io.EOF) {
|
||||
return n, fmt.Errorf("objectBody.Read - read object body: %w", safeError(err))
|
||||
}
|
||||
}
|
||||
return n, err
|
||||
}
|
||||
|
||||
func (body *objectBody) Close() error {
|
||||
defer body.cancel()
|
||||
if err := body.body.Close(); err != nil {
|
||||
return fmt.Errorf("objectBody.Close - close object body: %w", safeError(err))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,240 @@
|
||||
package seaweedfs
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"lincodex/backend/config"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
func TestStorageStreamsUploadWithExplicitCredentials(t *testing.T) {
|
||||
t.Setenv("AWS_ENDPOINT_URL_S3", "http://unused.invalid")
|
||||
t.Setenv("AWS_ACCESS_KEY_ID", "wrong-access")
|
||||
t.Setenv("AWS_SECRET_ACCESS_KEY", "wrong-secret")
|
||||
payload := bytes.Repeat([]byte("stream-data"), 1024)
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPut || r.URL.Path != "/test-files/private/file" {
|
||||
t.Errorf("unexpected upload route: %s %s", r.Method, r.URL.Path)
|
||||
}
|
||||
if !strings.Contains(r.Header.Get("Authorization"), "Credential=test-access/") {
|
||||
t.Error("configured credentials were not used")
|
||||
}
|
||||
if r.ContentLength != int64(len(payload)) || r.Header.Get("Content-Type") != "application/pdf" {
|
||||
t.Error("upload metadata differs")
|
||||
}
|
||||
body, err := io.ReadAll(r.Body)
|
||||
if err != nil || !bytes.Equal(body, payload) {
|
||||
t.Errorf("upload body differs: %v", err)
|
||||
}
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
defer server.Close()
|
||||
storage := newTestStorage(t, server.URL, time.Second)
|
||||
// Hide Seek to exercise streaming inputs such as request bodies.
|
||||
body := struct{ io.Reader }{bytes.NewReader(payload)}
|
||||
if err := storage.Put(t.Context(), "private/file", body, int64(len(payload)), "application/pdf"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStorageGetKeepsBodyAliveUntilClose(t *testing.T) {
|
||||
release := make(chan struct{})
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Length", "6")
|
||||
w.Header().Set("Content-Type", "text/plain")
|
||||
_, _ = io.WriteString(w, "abc")
|
||||
w.(http.Flusher).Flush()
|
||||
select {
|
||||
case <-release:
|
||||
_, _ = io.WriteString(w, "def")
|
||||
case <-r.Context().Done():
|
||||
}
|
||||
}))
|
||||
defer server.Close()
|
||||
storage := newTestStorage(t, server.URL, time.Second)
|
||||
object, err := storage.Get(t.Context(), "private/file")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer object.Body.Close()
|
||||
if object.Size != 6 || object.ContentType != "text/plain" {
|
||||
t.Fatal("download metadata differs")
|
||||
}
|
||||
first := make([]byte, 3)
|
||||
if _, err := io.ReadFull(object.Body, first); err != nil || string(first) != "abc" {
|
||||
t.Fatalf("Get returned a closed or buffered body: %q, %v", first, err)
|
||||
}
|
||||
close(release)
|
||||
remaining, err := io.ReadAll(object.Body)
|
||||
if err != nil || string(remaining) != "def" {
|
||||
t.Fatalf("remaining body: %q, %v", remaining, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStorageGetBodyHonorsCancellationAndTimeout(t *testing.T) {
|
||||
for _, mode := range []string{"caller", "timeout", "close"} {
|
||||
t.Run(mode, func(t *testing.T) {
|
||||
disconnected := make(chan struct{})
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Length", "100")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.(http.Flusher).Flush()
|
||||
<-r.Context().Done()
|
||||
close(disconnected)
|
||||
}))
|
||||
defer server.Close()
|
||||
timeout := time.Second
|
||||
if mode == "timeout" {
|
||||
timeout = 100 * time.Millisecond
|
||||
}
|
||||
storage := newTestStorage(t, server.URL, timeout)
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
defer cancel()
|
||||
object, err := storage.Get(ctx, "private/file")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer object.Body.Close()
|
||||
switch mode {
|
||||
case "close":
|
||||
if err := object.Body.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
case "caller", "timeout":
|
||||
want := context.DeadlineExceeded
|
||||
if mode == "caller" {
|
||||
cancel()
|
||||
want = context.Canceled
|
||||
}
|
||||
if _, err := object.Body.Read(make([]byte, 1)); !errors.Is(err, want) {
|
||||
t.Fatalf("body cancellation: %v, want %v", err, want)
|
||||
}
|
||||
}
|
||||
select {
|
||||
case <-disconnected:
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("response body left the server connection open")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestStorageClassifiesOnlyMissingObjectsAsNotFound(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
name, code string
|
||||
status int
|
||||
missing bool
|
||||
}{
|
||||
{name: "object", code: "NoSuchKey", status: http.StatusNotFound, missing: true},
|
||||
{name: "bucket", code: "NoSuchBucket", status: http.StatusNotFound},
|
||||
{name: "generic 404", code: "NotFound", status: http.StatusNotFound},
|
||||
{name: "credentials", code: "InvalidAccessKeyId", status: http.StatusForbidden},
|
||||
{name: "permission", code: "AccessDenied", status: http.StatusForbidden},
|
||||
{name: "server", code: "InternalError", status: http.StatusInternalServerError},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
var requests atomic.Int32
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
requests.Add(1)
|
||||
w.Header().Set("Content-Type", "application/xml")
|
||||
w.WriteHeader(test.status)
|
||||
_, _ = fmt.Fprintf(w, "<Error><Code>%s</Code><Message>private-file test-secret</Message><Key>private-file</Key></Error>", test.code)
|
||||
}))
|
||||
defer server.Close()
|
||||
storage := newTestStorage(t, server.URL, time.Second)
|
||||
_, err := storage.Get(t.Context(), "private-file")
|
||||
if err == nil || errors.Is(err, outbound.ErrObjectNotFound) != test.missing {
|
||||
t.Fatalf("wrong object error classification: %v", err)
|
||||
}
|
||||
if !strings.HasPrefix(err.Error(), "Storage.Get - get object: ") {
|
||||
t.Fatalf("storage error lacks method context: %v", err)
|
||||
}
|
||||
if requests.Load() != 1 {
|
||||
t.Fatal("request unexpectedly retried")
|
||||
}
|
||||
for _, sensitive := range []string{"private-file", "test-secret", server.URL} {
|
||||
if strings.Contains(err.Error(), sensitive) {
|
||||
t.Fatal("storage error disclosed sensitive request data")
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestStorageReadinessDoesNotProvisionBucket(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodHead || r.URL.Path != "/test-files/" {
|
||||
t.Errorf("readiness attempted a mutation or wrong bucket: %s %s", r.Method, r.URL.Path)
|
||||
}
|
||||
w.WriteHeader(http.StatusForbidden)
|
||||
}))
|
||||
defer server.Close()
|
||||
storage := newTestStorage(t, server.URL, time.Second)
|
||||
if err := storage.Check(t.Context()); !errors.Is(err, outbound.ErrObjectStorage) {
|
||||
t.Fatalf("unavailable bucket passed readiness: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStorageDoesNotFollowRedirects(t *testing.T) {
|
||||
var redirected atomic.Bool
|
||||
other := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
redirected.Store(true)
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
defer other.Close()
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
http.Redirect(w, r, other.URL, http.StatusTemporaryRedirect)
|
||||
}))
|
||||
defer server.Close()
|
||||
storage := newTestStorage(t, server.URL, time.Second)
|
||||
if _, err := storage.Get(t.Context(), "private-file"); err == nil || redirected.Load() {
|
||||
t.Fatal("storage followed a redirect away from the configured endpoint")
|
||||
}
|
||||
}
|
||||
|
||||
func TestStorageRequestCancellation(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) { t.Error("canceled request reached server") }))
|
||||
defer server.Close()
|
||||
storage := newTestStorage(t, server.URL, time.Second)
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
cancel()
|
||||
for name, call := range map[string]func() error{
|
||||
"get": func() error { _, err := storage.Get(ctx, "file"); return err },
|
||||
"put": func() error { return storage.Put(ctx, "file", strings.NewReader("data"), 4, "text/plain") },
|
||||
"delete": func() error { return storage.Delete(ctx, "file") },
|
||||
"readiness": func() error { return storage.Check(ctx) },
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
if err := call(); !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("cancellation lost: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func newTestStorage(t *testing.T, endpoint string, timeout time.Duration) *Storage {
|
||||
t.Helper()
|
||||
storage, cleanup, err := NewStorage(config.Config{
|
||||
SeaweedFSEndpoint: endpoint,
|
||||
SeaweedFSAccessKey: "test-access",
|
||||
SeaweedFSSecretKey: "test-secret",
|
||||
SeaweedFSBucket: "test-files",
|
||||
SeaweedFSRegion: "us-east-1",
|
||||
SeaweedFSTimeout: timeout,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(cleanup)
|
||||
return storage
|
||||
}
|
||||
Whitespace-only changes.
@@ -18,6 +18,11 @@ import (
|
||||
"lincodex/backend/internal/adapter/secondary/prometheus"
|
||||
)
|
||||
|
||||
const (
|
||||
readHeaderTimeout = 5 * time.Second
|
||||
idleTimeout = time.Minute
|
||||
)
|
||||
|
||||
type Application struct {
|
||||
config config.Config
|
||||
apiHandler http.Handler
|
||||
@@ -25,14 +30,19 @@ type Application struct {
|
||||
logger *slog.Logger
|
||||
}
|
||||
|
||||
func NewApplication(config config.Config, apiHandler http.Handler, metrics *prometheus.Metrics, logger *slog.Logger) *Application {
|
||||
func NewApplication(
|
||||
config config.Config,
|
||||
apiHandler http.Handler,
|
||||
metrics *prometheus.Metrics,
|
||||
logger *slog.Logger,
|
||||
) *Application {
|
||||
return &Application{config: config, apiHandler: apiHandler, metrics: metrics, logger: logger}
|
||||
}
|
||||
|
||||
func Run() (runErr error) {
|
||||
settings, err := config.Load()
|
||||
if err != nil {
|
||||
return fmt.Errorf("load configuration: %w", err)
|
||||
return fmt.Errorf("bootstrap.Run - load configuration: %w", err)
|
||||
}
|
||||
|
||||
log, err := logkit.New(
|
||||
@@ -40,17 +50,18 @@ func Run() (runErr error) {
|
||||
logkit.WithServiceName("lincodex-backend"),
|
||||
)
|
||||
if err != nil {
|
||||
return fmt.Errorf("create logger: %w", err)
|
||||
return fmt.Errorf("bootstrap.Run - create logger: %w", err)
|
||||
}
|
||||
defer func() {
|
||||
runErr = errors.Join(runErr, log.Close())
|
||||
if err := log.Close(); err != nil {
|
||||
runErr = errors.Join(runErr, fmt.Errorf("bootstrap.Run - close logger: %w", err))
|
||||
}
|
||||
}()
|
||||
logger := slog.New(logkit.SlogHandler(log))
|
||||
|
||||
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||
defer stop()
|
||||
if err := run(ctx, settings, logger); err != nil {
|
||||
logger.ErrorContext(ctx, "application stopped", slog.Any("error", err))
|
||||
return err
|
||||
}
|
||||
logger.Info("application stopped")
|
||||
@@ -59,11 +70,11 @@ func Run() (runErr error) {
|
||||
|
||||
func run(ctx context.Context, config config.Config, logger *slog.Logger) error {
|
||||
if err := config.Validate(); err != nil {
|
||||
return fmt.Errorf("validate configuration: %w", err)
|
||||
return fmt.Errorf("bootstrap.run - validate configuration: %w", err)
|
||||
}
|
||||
application, cleanup, err := initialize(ctx, config, logger)
|
||||
if err != nil {
|
||||
return fmt.Errorf("initialize application: %w", err)
|
||||
return fmt.Errorf("bootstrap.run - initialize application: %w", err)
|
||||
}
|
||||
defer cleanup()
|
||||
return application.run(ctx)
|
||||
@@ -86,60 +97,84 @@ func (application *Application) run(ctx context.Context) error {
|
||||
var listenerConfig net.ListenConfig
|
||||
apiListener, err := listenerConfig.Listen(ctx, "tcp", application.config.HTTPAddr)
|
||||
if err != nil {
|
||||
return fmt.Errorf("listen on HTTP_ADDR: %w", err)
|
||||
return fmt.Errorf("Application.run - listen on HTTP_ADDR: %w", err)
|
||||
}
|
||||
metricsListener, err := listenerConfig.Listen(ctx, "tcp", application.config.MetricsAddr)
|
||||
if err != nil {
|
||||
// Preserve the listen failure while releasing the first socket.
|
||||
_ = apiListener.Close()
|
||||
return fmt.Errorf("listen on METRICS_ADDR: %w", err)
|
||||
return fmt.Errorf("Application.run - listen on METRICS_ADDR: %w", err)
|
||||
}
|
||||
application.logger.Info("servers started",
|
||||
slog.String("http_addr", application.config.HTTPAddr),
|
||||
slog.String("metrics_addr", application.config.MetricsAddr),
|
||||
)
|
||||
|
||||
apiServer := &http.Server{
|
||||
Handler: application.apiHandler,
|
||||
ReadHeaderTimeout: 5 * time.Second,
|
||||
IdleTimeout: 60 * time.Second,
|
||||
}
|
||||
metricsServer := &http.Server{
|
||||
Handler: application.metrics.Handler(),
|
||||
ReadHeaderTimeout: 5 * time.Second,
|
||||
IdleTimeout: 60 * time.Second,
|
||||
}
|
||||
err = serveServers(ctx, apiListener, apiServer, metricsListener, metricsServer, application.config.ShutdownTimeout)
|
||||
apiServer := newHTTPServer(application.apiHandler)
|
||||
metricsServer := newHTTPServer(application.metrics.Handler())
|
||||
err = serveServers(
|
||||
ctx,
|
||||
apiListener,
|
||||
apiServer,
|
||||
metricsListener,
|
||||
metricsServer,
|
||||
application.config.ShutdownTimeout,
|
||||
)
|
||||
application.logger.Info("servers stopped")
|
||||
return err
|
||||
}
|
||||
|
||||
func serveServers(ctx context.Context, apiListener net.Listener, apiServer *http.Server, metricsListener net.Listener, metricsServer *http.Server, shutdownTimeout time.Duration) error {
|
||||
func newHTTPServer(handler http.Handler) *http.Server {
|
||||
return &http.Server{
|
||||
Handler: handler,
|
||||
ReadHeaderTimeout: readHeaderTimeout,
|
||||
IdleTimeout: idleTimeout,
|
||||
}
|
||||
}
|
||||
|
||||
func serveServers(
|
||||
ctx context.Context,
|
||||
apiListener net.Listener,
|
||||
apiServer *http.Server,
|
||||
metricsListener net.Listener,
|
||||
metricsServer *http.Server,
|
||||
shutdownTimeout time.Duration,
|
||||
) error {
|
||||
type serveResult struct {
|
||||
name string
|
||||
err error
|
||||
}
|
||||
results := make(chan serveResult, 2)
|
||||
go func() { results <- serveResult{name: "API", err: apiServer.Serve(apiListener)} }()
|
||||
go func() { results <- serveResult{name: "metrics", err: metricsServer.Serve(metricsListener)} }()
|
||||
servers := []struct {
|
||||
name string
|
||||
server *http.Server
|
||||
listener net.Listener
|
||||
}{
|
||||
{name: "API", server: apiServer, listener: apiListener},
|
||||
{name: "metrics", server: metricsServer, listener: metricsListener},
|
||||
}
|
||||
results := make(chan serveResult, len(servers))
|
||||
for _, entry := range servers {
|
||||
go func() { results <- serveResult{name: entry.name, err: entry.server.Serve(entry.listener)} }()
|
||||
}
|
||||
|
||||
serving := 2
|
||||
serving := len(servers)
|
||||
var runErr error
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
case result := <-results:
|
||||
serving--
|
||||
if result.err != nil && !errors.Is(result.err, http.ErrServerClosed) {
|
||||
runErr = fmt.Errorf("%s server stopped: %w", result.name, result.err)
|
||||
runErr = fmt.Errorf("bootstrap.serveServers - %s server stopped: %w", result.name, result.err)
|
||||
}
|
||||
}
|
||||
|
||||
shutdownContext, cancel := context.WithTimeout(context.WithoutCancel(ctx), shutdownTimeout)
|
||||
defer cancel()
|
||||
var shutdownErr error
|
||||
for _, server := range []*http.Server{apiServer, metricsServer} {
|
||||
if err := server.Shutdown(shutdownContext); err != nil {
|
||||
for _, entry := range servers {
|
||||
if err := entry.server.Shutdown(shutdownContext); err != nil {
|
||||
shutdownErr = errors.Join(shutdownErr, err)
|
||||
if closeErr := server.Close(); closeErr != nil {
|
||||
if closeErr := entry.server.Close(); closeErr != nil {
|
||||
shutdownErr = errors.Join(shutdownErr, closeErr)
|
||||
}
|
||||
}
|
||||
@@ -148,11 +183,11 @@ func serveServers(ctx context.Context, apiListener net.Listener, apiServer *http
|
||||
result := <-results
|
||||
serving--
|
||||
if result.err != nil && !errors.Is(result.err, http.ErrServerClosed) {
|
||||
runErr = errors.Join(runErr, fmt.Errorf("%s server stopped: %w", result.name, result.err))
|
||||
runErr = errors.Join(runErr, fmt.Errorf("bootstrap.serveServers - %s server stopped: %w", result.name, result.err))
|
||||
}
|
||||
}
|
||||
if shutdownErr != nil {
|
||||
return errors.Join(runErr, fmt.Errorf("shut down servers: %w", shutdownErr))
|
||||
return errors.Join(runErr, fmt.Errorf("bootstrap.serveServers - shut down servers: %w", shutdownErr))
|
||||
}
|
||||
return runErr
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package bootstrap
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net"
|
||||
"net/http"
|
||||
"strings"
|
||||
@@ -44,9 +45,12 @@ func TestServeServersStopsBothListenersWhenOneFails(t *testing.T) {
|
||||
&http.Server{Handler: http.NotFoundHandler()},
|
||||
time.Second,
|
||||
)
|
||||
if err == nil || !strings.Contains(err.Error(), "API server stopped") {
|
||||
if err == nil || !strings.HasPrefix(err.Error(), "bootstrap.serveServers - API server stopped: ") {
|
||||
t.Fatalf("serveServers() error = %v, want API server failure", err)
|
||||
}
|
||||
if !errors.Is(err, net.ErrClosed) {
|
||||
t.Fatalf("serveServers() lost the listener error: %v", err)
|
||||
}
|
||||
dialContext, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
|
||||
defer cancel()
|
||||
if _, err := (&net.Dialer{}).DialContext(dialContext, "tcp", metricsAddress); err == nil {
|
||||
|
||||
@@ -14,8 +14,9 @@ import (
|
||||
v1 "lincodex/backend/internal/adapter/primary/http/v1"
|
||||
"lincodex/backend/internal/adapter/secondary/postgres"
|
||||
metrics "lincodex/backend/internal/adapter/secondary/prometheus"
|
||||
redisadapter "lincodex/backend/internal/adapter/secondary/redis"
|
||||
"lincodex/backend/internal/adapter/secondary/seaweedfs"
|
||||
"lincodex/backend/internal/port/inbound"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
"lincodex/backend/internal/usecase/health"
|
||||
)
|
||||
|
||||
@@ -23,10 +24,11 @@ func initialize(ctx context.Context, config config.Config, logger *slog.Logger)
|
||||
wire.Build(
|
||||
wire.NewSet(
|
||||
postgres.NewHealthChecker,
|
||||
wire.Bind(new(outbound.ReadinessChecker), new(*postgres.HealthChecker)),
|
||||
redisadapter.NewCache,
|
||||
seaweedfs.NewStorage,
|
||||
wire.Bind(new(inbound.Readiness), new(*health.Readiness)),
|
||||
wire.Bind(new(httpmiddleware.RequestMetrics), new(*metrics.Metrics)),
|
||||
health.NewReadiness,
|
||||
newReadiness,
|
||||
metrics.New,
|
||||
newHealthHandler,
|
||||
httpadapter.NewRouter,
|
||||
@@ -39,3 +41,7 @@ func initialize(ctx context.Context, config config.Config, logger *slog.Logger)
|
||||
func newHealthHandler(readiness inbound.Readiness, config config.Config) *v1.HealthHandler {
|
||||
return v1.NewHealthHandler(readiness, config.ReadinessTimeout)
|
||||
}
|
||||
|
||||
func newReadiness(postgres *postgres.HealthChecker, cache *redisadapter.Cache, storage *seaweedfs.Storage) *health.Readiness {
|
||||
return health.NewReadiness(postgres, cache, storage)
|
||||
}
|
||||
@@ -13,6 +13,8 @@ import (
|
||||
"lincodex/backend/internal/adapter/primary/http/v1"
|
||||
"lincodex/backend/internal/adapter/secondary/postgres"
|
||||
"lincodex/backend/internal/adapter/secondary/prometheus"
|
||||
"lincodex/backend/internal/adapter/secondary/redis"
|
||||
"lincodex/backend/internal/adapter/secondary/seaweedfs"
|
||||
"lincodex/backend/internal/port/inbound"
|
||||
"lincodex/backend/internal/usecase/health"
|
||||
"log/slog"
|
||||
@@ -25,16 +27,31 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
readiness := health.NewReadiness(healthChecker)
|
||||
cache, cleanup2, err := redis.NewCache(config2, logger)
|
||||
if err != nil {
|
||||
cleanup()
|
||||
return nil, nil, err
|
||||
}
|
||||
storage, cleanup3, err := seaweedfs.NewStorage(config2)
|
||||
if err != nil {
|
||||
cleanup2()
|
||||
cleanup()
|
||||
return nil, nil, err
|
||||
}
|
||||
readiness := newReadiness(healthChecker, cache, storage)
|
||||
healthHandler := newHealthHandler(readiness, config2)
|
||||
metrics := prometheus.New()
|
||||
handler, err := httpadapter.NewRouter(healthHandler, metrics, logger)
|
||||
if err != nil {
|
||||
cleanup3()
|
||||
cleanup2()
|
||||
cleanup()
|
||||
return nil, nil, err
|
||||
}
|
||||
application := NewApplication(config2, handler, metrics, logger)
|
||||
return application, func() {
|
||||
cleanup3()
|
||||
cleanup2()
|
||||
cleanup()
|
||||
}, nil
|
||||
}
|
||||
@@ -44,3 +61,7 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger)
|
||||
func newHealthHandler(readiness inbound.Readiness, config2 config.Config) *v1.HealthHandler {
|
||||
return v1.NewHealthHandler(readiness, config2.ReadinessTimeout)
|
||||
}
|
||||
|
||||
func newReadiness(postgres2 *postgres.HealthChecker, cache *redis.Cache, storage *seaweedfs.Storage) *health.Readiness {
|
||||
return health.NewReadiness(postgres2, cache, storage)
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package outbound
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrCacheMiss = errors.New("cache key not found")
|
||||
ErrInvalidCacheKey = errors.New("cache key must not be empty")
|
||||
ErrInvalidCacheTTL = errors.New("cache TTL must be positive")
|
||||
)
|
||||
|
||||
// Cache stores serialized values with a mandatory expiration.
|
||||
type Cache interface {
|
||||
// Get returns ErrCacheMiss only when a key is absent, never on a service failure.
|
||||
Get(ctx context.Context, key string) ([]byte, error)
|
||||
Set(ctx context.Context, key string, value []byte, ttl time.Duration) error
|
||||
// Del succeeds when a key is already absent or no keys are supplied.
|
||||
Del(ctx context.Context, keys ...string) error
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package outbound
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrObjectNotFound = errors.New("object not found")
|
||||
ErrInvalidObject = errors.New("invalid object input")
|
||||
ErrObjectStorage = errors.New("object storage request failed")
|
||||
)
|
||||
|
||||
// Object contains a streaming response. The caller must close Body and keep the
|
||||
// request context alive until reading is complete.
|
||||
type Object struct {
|
||||
Body io.ReadCloser
|
||||
Size int64
|
||||
ContentType string
|
||||
}
|
||||
|
||||
type ObjectStorage interface {
|
||||
// Put streams exactly size bytes. The caller owns the source reader and must
|
||||
// ensure a blocking source can be canceled. An error may leave a completed
|
||||
// object when the server accepted the write before the response was lost.
|
||||
Put(ctx context.Context, key string, body io.Reader, size int64, contentType string) error
|
||||
Get(ctx context.Context, key string) (Object, error)
|
||||
// Delete succeeds when the object is already absent.
|
||||
Delete(ctx context.Context, key string) error
|
||||
}
|
||||
@@ -8,16 +8,21 @@ import (
|
||||
)
|
||||
|
||||
type Readiness struct {
|
||||
checker outbound.ReadinessChecker
|
||||
checkers []outbound.ReadinessChecker
|
||||
}
|
||||
|
||||
func NewReadiness(checker outbound.ReadinessChecker) *Readiness {
|
||||
return &Readiness{checker: checker}
|
||||
func NewReadiness(checkers ...outbound.ReadinessChecker) *Readiness {
|
||||
return &Readiness{checkers: checkers}
|
||||
}
|
||||
|
||||
func (readiness *Readiness) Check(ctx context.Context) error {
|
||||
if err := readiness.checker.Check(ctx); err != nil {
|
||||
return fmt.Errorf("readiness check failed: %w", err)
|
||||
if len(readiness.checkers) == 0 {
|
||||
return fmt.Errorf("Readiness.Check - no readiness checkers: %w", outbound.ErrNotReady)
|
||||
}
|
||||
for _, checker := range readiness.checkers {
|
||||
if err := checker.Check(ctx); err != nil {
|
||||
return fmt.Errorf("Readiness.Check - check dependency: %w", err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package health
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
type checkFunc func(context.Context) error
|
||||
|
||||
func (check checkFunc) Check(ctx context.Context) error { return check(ctx) }
|
||||
|
||||
func TestReadinessRequiresEveryDependency(t *testing.T) {
|
||||
failure := errors.New("dependency unavailable")
|
||||
for _, failed := range []int{-1, 0, 1} {
|
||||
calls := 0
|
||||
checkers := make([]outbound.ReadinessChecker, 0, 2)
|
||||
for index := range 2 {
|
||||
checkers = append(checkers, checkFunc(func(ctx context.Context) error {
|
||||
calls++
|
||||
if ctx != t.Context() {
|
||||
t.Error("readiness replaced the caller context")
|
||||
}
|
||||
if index == failed {
|
||||
return failure
|
||||
}
|
||||
return nil
|
||||
}))
|
||||
}
|
||||
err := NewReadiness(checkers...).Check(t.Context())
|
||||
if failed < 0 {
|
||||
if err != nil || calls != 2 {
|
||||
t.Fatalf("healthy dependencies: calls=%d error=%v", calls, err)
|
||||
}
|
||||
continue
|
||||
}
|
||||
if !errors.Is(err, failure) {
|
||||
t.Fatalf("failed dependency %d: error=%v", failed, err)
|
||||
}
|
||||
}
|
||||
if err := NewReadiness().Check(t.Context()); !errors.Is(err, outbound.ErrNotReady) {
|
||||
t.Fatalf("no dependencies: error=%v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
__pycache__/
|
||||
@@ -0,0 +1,89 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Discover and run whole integration tests in deterministic, isolated CI shards."""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shlex
|
||||
import subprocess
|
||||
import sys
|
||||
from collections import defaultdict
|
||||
|
||||
|
||||
def shard_settings():
|
||||
index = os.environ.get("TEST_SHARD_INDEX")
|
||||
total = os.environ.get("TEST_SHARD_TOTAL")
|
||||
if index is None and total is None:
|
||||
return 1, 1
|
||||
if not all(value and re.fullmatch(r"[1-9][0-9]*", value) for value in (index, total)):
|
||||
raise ValueError("TEST_SHARD_INDEX and TEST_SHARD_TOTAL must both be positive integers")
|
||||
index, total = int(index), int(total)
|
||||
if index > total:
|
||||
raise ValueError("TEST_SHARD_INDEX must not exceed TEST_SHARD_TOTAL")
|
||||
return index, total
|
||||
|
||||
|
||||
def capture(command):
|
||||
result = subprocess.run(command, text=True, stdout=subprocess.PIPE, check=False)
|
||||
if result.returncode:
|
||||
print(result.stdout, file=sys.stderr, end="")
|
||||
raise subprocess.CalledProcessError(result.returncode, command)
|
||||
return result.stdout
|
||||
|
||||
|
||||
def discover(go):
|
||||
packages = capture([*go, "list", "-tags=integration", "./integration_test/..."])
|
||||
tests = set()
|
||||
for package in sorted({line.strip() for line in packages.splitlines() if line.strip()}):
|
||||
output = capture([
|
||||
*go, "test", "-tags=integration", "-count=1", "-json", "-list=^Test", package,
|
||||
])
|
||||
for line in output.splitlines():
|
||||
event = json.loads(line)
|
||||
name = event.get("Output", "").strip()
|
||||
if event.get("Action") == "output" and re.fullmatch(r"Test\w*", name):
|
||||
tests.add((package, name))
|
||||
if not tests:
|
||||
raise ValueError("no top-level integration tests were discovered")
|
||||
return sorted(tests)
|
||||
|
||||
|
||||
def run():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--go", default=os.environ.get("GO", "go"))
|
||||
parser.add_argument("--list", action="store_true", help="list the selected tests without running them")
|
||||
args = parser.parse_args()
|
||||
go = shlex.split(args.go)
|
||||
if not go:
|
||||
raise ValueError("Go command must not be empty")
|
||||
index, total = shard_settings()
|
||||
tests = discover(go)
|
||||
if total > len(tests):
|
||||
raise ValueError(f"{total} shards would leave empty shards for {len(tests)} tests")
|
||||
selected = tests[index - 1::total]
|
||||
print(f"Integration shard {index}/{total}: {len(selected)} of {len(tests)} tests", flush=True)
|
||||
packages = defaultdict(list)
|
||||
for package, name in selected:
|
||||
print(f" {package}: {name}", flush=True)
|
||||
packages[package].append(name)
|
||||
if args.list:
|
||||
return
|
||||
for package, names in packages.items():
|
||||
# Go splits -run at slashes. Anchoring only the parent keeps all its subtests.
|
||||
pattern = "^(" + "|".join(re.escape(name) for name in names) + ")$"
|
||||
subprocess.run([
|
||||
*go, "test", "-tags=integration", "-count=1", "-timeout=10m",
|
||||
"-run=" + pattern, package,
|
||||
], check=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
run()
|
||||
except subprocess.CalledProcessError as error:
|
||||
print(f"Integration runner - command failed with status {error.returncode}", file=sys.stderr)
|
||||
sys.exit(error.returncode if error.returncode > 0 else 1)
|
||||
except (ValueError, OSError) as error:
|
||||
print(f"Integration runner - {error}", file=sys.stderr)
|
||||
sys.exit(2)
|
||||
@@ -0,0 +1,154 @@
|
||||
"""Exercise discovery, shard selection, and failures through the Go boundary."""
|
||||
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shlex
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
|
||||
RUNNER = Path(__file__).with_name("run-integration-suite.py")
|
||||
FIXTURE = {
|
||||
"example/integration_test": ["TestZulu", "TestAlpha", "TestAlphaLong"],
|
||||
"example/integration_test/nested": ["TestSecond", "TestFirst"],
|
||||
"example/integration_test/helpers": [],
|
||||
}
|
||||
FAKE_GO = r'''
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
args = sys.argv[1:]
|
||||
with Path(os.environ["RUN_LOG"]).open("a") as log:
|
||||
log.write(json.dumps(args) + "\n")
|
||||
tests = json.loads(os.environ["TEST_FIXTURE"])
|
||||
stage = "packages" if args[0] == "list" else "discovery" if "-list=^Test" in args else "tests"
|
||||
if os.environ.get("FAIL_STAGE") == stage:
|
||||
print("deliberate " + stage + " failure")
|
||||
sys.exit(23)
|
||||
if stage == "packages":
|
||||
print("\n".join(reversed(tests)))
|
||||
elif stage == "discovery":
|
||||
for name in tests[args[-1]]:
|
||||
print(json.dumps({"Action": "output", "Output": name + "\n"}))
|
||||
print(json.dumps({"Action": "output", "Output": "ok " + args[-1] + "\n"}))
|
||||
'''
|
||||
|
||||
|
||||
class IntegrationSuiteTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
directory = tempfile.TemporaryDirectory(prefix="integration-runner-")
|
||||
self.addCleanup(directory.cleanup)
|
||||
self.directory = Path(directory.name)
|
||||
self.fake_go = self.directory / "go.py"
|
||||
self.fake_go.write_text(FAKE_GO)
|
||||
self.log = self.directory / "runs.jsonl"
|
||||
|
||||
def run_suite(self, settings=None, fixture=None, list_only=False):
|
||||
environment = {
|
||||
key: value for key, value in os.environ.items()
|
||||
if key not in ("TEST_SHARD_INDEX", "TEST_SHARD_TOTAL", "FAIL_STAGE")
|
||||
}
|
||||
environment.update({
|
||||
"RUN_LOG": str(self.log),
|
||||
"TEST_FIXTURE": json.dumps(FIXTURE if fixture is None else fixture),
|
||||
})
|
||||
environment.update(settings or {})
|
||||
self.log.write_text("")
|
||||
command = [sys.executable, str(RUNNER), "--go", shlex.join([sys.executable, str(self.fake_go)])]
|
||||
if list_only:
|
||||
command.append("--list")
|
||||
result = subprocess.run(command, env=environment, text=True, capture_output=True, check=False)
|
||||
calls = [json.loads(line) for line in self.log.read_text().splitlines()]
|
||||
return result, calls
|
||||
|
||||
def selected(self, calls):
|
||||
selected = []
|
||||
for args in calls:
|
||||
patterns = [arg.removeprefix("-run=") for arg in args if arg.startswith("-run=")]
|
||||
if not patterns:
|
||||
continue
|
||||
pattern = patterns[0]
|
||||
self.assertTrue(pattern.startswith("^(") and pattern.endswith(")$"))
|
||||
self.assertNotIn("/", pattern, "subtests must remain with their parent test")
|
||||
for name in FIXTURE[args[-1]]:
|
||||
if re.search(pattern, name):
|
||||
selected.append((args[-1], name))
|
||||
self.assertFalse(re.search(pattern, "TestAlphaLonger"))
|
||||
self.assertIn("-count=1", args)
|
||||
return selected
|
||||
|
||||
def test_shards_are_disjoint_and_cover_every_package(self):
|
||||
selected = []
|
||||
for index in (1, 2, 3):
|
||||
result, calls = self.run_suite({"TEST_SHARD_INDEX": str(index), "TEST_SHARD_TOTAL": "3"})
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
shard = self.selected(calls)
|
||||
self.assertTrue(shard)
|
||||
selected.extend(shard)
|
||||
expected = [(package, name) for package, names in FIXTURE.items() for name in names]
|
||||
self.assertCountEqual(selected, expected)
|
||||
|
||||
def test_default_runs_full_suite(self):
|
||||
result, calls = self.run_suite()
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertEqual(len(self.selected(calls)), 5)
|
||||
|
||||
def test_discovery_order_does_not_change_selection(self):
|
||||
settings = {"TEST_SHARD_INDEX": "1", "TEST_SHARD_TOTAL": "2"}
|
||||
result, calls = self.run_suite(settings)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
expected = self.selected(calls)
|
||||
fixture = {package: list(reversed(names)) for package, names in reversed(FIXTURE.items())}
|
||||
result, calls = self.run_suite(settings, fixture)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertEqual(self.selected(calls), expected)
|
||||
|
||||
def test_list_only_never_runs_tests(self):
|
||||
result, calls = self.run_suite(list_only=True)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertIn("5 of 5 tests", result.stdout)
|
||||
self.assertEqual(self.selected(calls), [])
|
||||
|
||||
def test_invalid_shard_settings_fail_before_discovery(self):
|
||||
settings = [
|
||||
{"TEST_SHARD_INDEX": "1"}, {"TEST_SHARD_TOTAL": "2"},
|
||||
{"TEST_SHARD_INDEX": "0", "TEST_SHARD_TOTAL": "2"},
|
||||
{"TEST_SHARD_INDEX": "3", "TEST_SHARD_TOTAL": "2"},
|
||||
{"TEST_SHARD_INDEX": "one", "TEST_SHARD_TOTAL": "2"},
|
||||
{"TEST_SHARD_INDEX": "1", "TEST_SHARD_TOTAL": "-2"},
|
||||
{"TEST_SHARD_INDEX": "", "TEST_SHARD_TOTAL": ""},
|
||||
]
|
||||
for setting in settings:
|
||||
with self.subTest(setting=setting):
|
||||
result, calls = self.run_suite(setting)
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertEqual(calls, [])
|
||||
|
||||
def test_empty_suite_and_empty_shards_fail(self):
|
||||
for fixture in ({}, {"example/integration_test": []}):
|
||||
with self.subTest(fixture=fixture):
|
||||
result, calls = self.run_suite(fixture=fixture)
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("no top-level integration tests", result.stderr)
|
||||
self.assertEqual(self.selected(calls), [])
|
||||
result, calls = self.run_suite({"TEST_SHARD_INDEX": "1", "TEST_SHARD_TOTAL": "6"})
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("empty shards", result.stderr)
|
||||
self.assertEqual(self.selected(calls), [])
|
||||
|
||||
def test_discovery_and_test_failures_are_propagated(self):
|
||||
for stage in ("packages", "discovery", "tests"):
|
||||
with self.subTest(stage=stage):
|
||||
result, _ = self.run_suite({"FAIL_STAGE": stage})
|
||||
self.assertEqual(result.returncode, 23)
|
||||
self.assertIn("deliberate " + stage + " failure", result.stdout + result.stderr)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user