package main import ( "bytes" "context" "errors" "fmt" "io" "net" "net/http" "os" "strings" "time" ) // doAICallWithRetry menangani request ke endpoint AI dengan Exponential Backoff. // Hanya melakukan retry pada 429, 503, Timeout, dan Transient Network Error. func doAICallWithRetry(ctx context.Context, urlAPI string, requestBody []byte, modelName string) ([]byte, error) { var lastErr error delay := AIRetryInitialDelay for attempt := 1; attempt <= AIRetryMaxAttempts; attempt++ { // Timeout request dibatasi 60 detik per attempt agar cukup waktu untuk model pro reqCtx, cancel := context.WithTimeout(ctx, 60*time.Second) req, err := http.NewRequestWithContext(reqCtx, "POST", urlAPI, bytes.NewBuffer(requestBody)) if err != nil { cancel() return nil, fmt.Errorf("gagal buat request: %w", err) } req.Header.Set("Content-Type", "application/json") req.Header.Set("Authorization", "Bearer "+geminiAPIKey()) resp, err := httpClientGemini.Do(req) isRetryable := false reason := "" if err != nil { var netErr net.Error if errors.As(err, &netErr) && netErr.Timeout() { isRetryable = true reason = "net/http timeout" } else if errors.Is(err, context.DeadlineExceeded) || os.IsTimeout(err) { isRetryable = true reason = "context deadline exceeded" } else if strings.Contains(strings.ToLower(err.Error()), "connection reset") || strings.Contains(strings.ToLower(err.Error()), "eof") || strings.Contains(strings.ToLower(err.Error()), "no such host") { isRetryable = true reason = "transient network error" } else if errors.As(err, &netErr) && netErr.Temporary() { isRetryable = true reason = "net.Error temporary" } } else { if resp.StatusCode == 429 || resp.StatusCode == 503 || resp.StatusCode == 502 || resp.StatusCode == 504 { isRetryable = true reason = fmt.Sprintf("HTTP %d", resp.StatusCode) } else if resp.StatusCode >= 400 && resp.StatusCode < 500 { isRetryable = false // Permanent client error (400, 401, 403, 404) } } // Jika request sukses ATAU ada error permanent yang tidak bisa di-retry if !isRetryable { if err == nil { defer resp.Body.Close() body, readErr := io.ReadAll(io.LimitReader(resp.Body, 5*1024*1024)) // limit 5MB cancel() if readErr != nil { return nil, fmt.Errorf("gagal baca body: %w", readErr) } if resp.StatusCode >= 300 { return nil, fmt.Errorf("HTTP %d: %s", resp.StatusCode, string(body)) } if attempt > 1 { fmt.Printf("[AI RETRY SUCCESS]\nattempt=%d\nmodel=%s\n", attempt, modelName) } return body, nil } cancel() return nil, err } // Jika error retryable tapi ini attempt terakhir if attempt == AIRetryMaxAttempts { cancel() if err != nil { lastErr = err } else { lastErr = fmt.Errorf("HTTP %d", resp.StatusCode) resp.Body.Close() } break } // Print LOG AI RETRY sesuai instruksi fmt.Printf("[AI RETRY]\nattempt=%d\nmodel=%s\nreason=%s\n", attempt, modelName, reason) if resp != nil && resp.Body != nil { resp.Body.Close() } cancel() // Jeda sebelum retry berikutnya (Exponential Backoff) select { case <-ctx.Done(): // Jika bot sedang shutdown return nil, ctx.Err() case <-time.After(delay): } // Set delay eksponensial (2s -> 4s -> 8s) delay *= 2 if delay > AIRetryMaxDelay { delay = AIRetryMaxDelay } } return nil, fmt.Errorf("max retry reached (%d attempts), last error: %w", AIRetryMaxAttempts, lastErr) }