Files
ARTEX/third_party/norma/llm/retry.go
T
wangdefa f782b612ec build: 内置 norma 模块,构建不再依赖上游仓库
把 github.com/Autumn-27/norma v0.4.3(commit 320ae32)的源码复制到
third_party/norma,并用 go.mod 的 replace 指向本地副本。上游删除仓库或
改写 tag 都不再影响本仓库构建。

- 已验证 GOPROXY=off 下可完整编译并打出发行包
- go.sum 中该模块的两条校验记录随之删除(本地 replace 不需要哈希)
- 升级方法与授权注意事项见 third_party/README.md
2026-10-20 21:10:41 -07:00

102 lines
3.0 KiB
Go

package llm
import (
"bytes"
"context"
"fmt"
"io"
"net/http"
"strings"
"time"
)
// doStream sends the streaming request with retries on transient failures and
// returns a 200 response (caller reads + closes the body). Only the request
// establishment phase is retried — connection reset / timeout / 429 / 5xx before
// any stream data is consumed — so retrying is safe (it can't duplicate
// partially-streamed assistant output). A mid-stream drop is the caller's to
// surface. Context cancellation is never retried and interrupts the backoff.
// Count comes from cfg.retries(), the wait between attempts from
// cfg.retryDelay() (exponential by default, fixed when Config.RetryInterval is set).
func doStream(ctx context.Context, cfg Config, url string, body []byte, setHeaders func(*http.Request), errPrefix string) (*http.Response, error) {
// Rate limit once per logical request (outside the retry loop, so retries do
// not consume additional tokens). Shared across all callers of this provider.
if err := cfg.limiter.Wait(ctx); err != nil {
return nil, err
}
retries := cfg.retries()
for attempt := 0; ; attempt++ {
req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(body))
if err != nil {
return nil, err
}
setHeaders(req)
resp, err := cfg.HTTPClient.Do(req)
if err == nil && resp.StatusCode == http.StatusOK {
return resp, nil
}
retryable := false
switch {
case err != nil:
retryable = ctx.Err() == nil // transient network error (not cancellation)
case isRetryableStatus(resp.StatusCode):
retryable = true
}
if attempt >= retries || !retryable {
if err != nil {
return nil, err
}
data, _ := io.ReadAll(resp.Body)
resp.Body.Close()
return nil, fmt.Errorf("%s: status %d: %s", errPrefix, resp.StatusCode, strings.TrimSpace(string(data)))
}
if resp != nil {
resp.Body.Close()
}
if !backoffSleep(ctx, cfg.retryDelay(attempt)) {
return nil, ctx.Err() // context cancelled during backoff
}
}
}
func isRetryableStatus(code int) bool {
switch code {
case http.StatusRequestTimeout, // 408
http.StatusTooManyRequests, // 429
http.StatusInternalServerError, // 500
http.StatusBadGateway, // 502
http.StatusServiceUnavailable, // 503
http.StatusGatewayTimeout: // 504
return true
}
return false
}
// expBackoff is the default retry ladder: 0.5s, 1s, 2s, … capped at 8s. Used
// whenever the caller did not pin a fixed interval on the Config.
func expBackoff(attempt int) time.Duration {
d := 500 * time.Millisecond * (1 << attempt)
if d > 8*time.Second {
d = 8 * time.Second
}
return d
}
// backoffSleep waits d, interruptible by ctx. Returns false if the context was
// cancelled (or d is non-positive, which never happens for a real wait).
func backoffSleep(ctx context.Context, d time.Duration) bool {
if d <= 0 {
return ctx.Err() == nil
}
t := time.NewTimer(d)
defer t.Stop()
select {
case <-ctx.Done():
return false
case <-t.C:
return true
}
}