fix: standardize startup database retries
This commit is contained in:
1 parent
668e9dd310
commit
d9e2d64535
6 files changed
+230
-44
No files matched your search
+5
-20
@@ -19,6 +19,7 @@ import (
|
||||
sharedauth "repos.gfranz.ch/Gabriel20xx/shared/backend/auth"
|
||||
"repos.gfranz.ch/Gabriel20xx/shared/backend/carriernodeclient"
|
||||
"repos.gfranz.ch/Gabriel20xx/shared/backend/coreconfig"
|
||||
sharedpostgres "repos.gfranz.ch/Gabriel20xx/shared/backend/postgres"
|
||||
)
|
||||
|
||||
// The SvelteKit build is copied here by the Docker builder before go build.
|
||||
@@ -132,11 +133,7 @@ func main() {
|
||||
}
|
||||
|
||||
func connectWithRetry(ctx context.Context, connectionString string) (*DB, error) {
|
||||
interval := time.Duration(envInt64("DB_INIT_RETRY_INTERVAL_MS", 5000)) * time.Millisecond
|
||||
if interval < 250*time.Millisecond {
|
||||
interval = 250 * time.Millisecond
|
||||
}
|
||||
maxAttempts := envInt64("DB_INIT_RETRY_MAX_ATTEMPTS", 0)
|
||||
retryOptions := sharedpostgres.StartupRetryOptionsFromEnv()
|
||||
|
||||
for attempt := int64(1); ; attempt++ {
|
||||
database, err := connectDB(ctx, connectionString)
|
||||
@@ -153,14 +150,14 @@ func connectWithRetry(ctx context.Context, connectionString string) (*DB, error)
|
||||
}
|
||||
|
||||
fmt.Fprintf(os.Stderr, "[DB] Initialization attempt %d failed: %v\n", attempt, err)
|
||||
if maxAttempts > 0 && attempt >= maxAttempts {
|
||||
if retryOptions.MaxAttempts > 0 && attempt >= retryOptions.MaxAttempts {
|
||||
return nil, err
|
||||
}
|
||||
fmt.Printf("[DB] Retrying in %s...\n", interval)
|
||||
fmt.Printf("[DB] Retrying in %s...\n", retryOptions.Interval)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
case <-time.After(interval):
|
||||
case <-time.After(retryOptions.Interval):
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -254,18 +251,6 @@ func envOrDefault(name, fallback string) string {
|
||||
return fallback
|
||||
}
|
||||
|
||||
func envInt64(name string, fallback int64) int64 {
|
||||
value := strings.TrimSpace(os.Getenv(name))
|
||||
if value == "" {
|
||||
return fallback
|
||||
}
|
||||
var parsed int64
|
||||
if _, err := fmt.Sscan(value, &parsed); err != nil {
|
||||
return fallback
|
||||
}
|
||||
return parsed
|
||||
}
|
||||
|
||||
func decodeJSON(r *http.Request, target any) error {
|
||||
decoder := json.NewDecoder(io.LimitReader(r.Body, 50*1024*1024))
|
||||
if err := decoder.Decode(target); err != nil {
|
||||
|
||||
Reference in new issue
Block a user