package config import ( "fmt" "os" "strconv" "strings" "time" ) type Attachment struct { Endpoint, Region, Bucket, AccessKey, SecretKey string MaxBytes, MaxPixels int64 Timeout, Grace time.Duration Uploads, Decoders int } func LoadAttachment() (*Attachment, error) { c := &Attachment{Endpoint: env("S3_ENDPOINT", "http://s3:9000"), Region: env("S3_REGION", "us-east-1"), Bucket: env("S3_BUCKET", "messenger-attachments"), MaxBytes: 10485760, MaxPixels: 40000000, Timeout: 120 * time.Second, Grace: time.Hour, Uploads: 4, Decoders: 1} var err error for key, dst := range map[string]*string{"S3_ACCESS_KEY_ID_FILE": &c.AccessKey, "S3_SECRET_ACCESS_KEY_FILE": &c.SecretKey} { b, e := os.ReadFile(os.Getenv(key)) if e != nil { return nil, fmt.Errorf("read %s: %w", key, e) } *dst = strings.TrimSpace(string(b)) if *dst == "" { return nil, fmt.Errorf("empty %s", key) } } for key, dst := range map[string]*int64{"MAX_UPLOAD_BYTES": &c.MaxBytes, "MAX_IMAGE_PIXELS": &c.MaxPixels} { if v := os.Getenv(key); v != "" { *dst, err = strconv.ParseInt(v, 10, 64) if err != nil { return nil, fmt.Errorf("invalid %s", key) } } } for key, dst := range map[string]*time.Duration{"UPLOAD_TIMEOUT": &c.Timeout, "RECONCILE_GRACE_PERIOD": &c.Grace} { if v := os.Getenv(key); v != "" { *dst, err = time.ParseDuration(v) if err != nil { return nil, fmt.Errorf("invalid %s", key) } } } if c.MaxBytes < 1 || c.MaxBytes > 10485760 || c.MaxPixels < 1 || c.MaxPixels > 40000000 || c.Timeout < time.Second || c.Timeout > 120*time.Second || c.Grace <= 2*c.Timeout { return nil, fmt.Errorf("invalid attachment limits or grace period") } return c, nil } func env(k, d string) string { if v := os.Getenv(k); v != "" { return v } return d }