Files
magpie/internal/gateway/notapi.go
T
yetone 4ed6b42f6b provider: an upstream refusal with an empty body or a web page says what it was
maralica's custom Responses relay answered 403, and Codex was told only
"<provider>: 403 Forbidden": apiError dropped any body starting with "<"
and said nothing of an empty one, so a Cloudflare block page, a proxy's
nginx page and a firewall's empty refusal all read the same.

apiError now says a web page by its <title> (provider.WebPage: markup
and entities taken out, whitespace folded, 120 runes at most), and an
empty body, when the fallback is an HTTP status ("403 Forbidden" or
"Forbidden", statusLine), as refused with no details, often a firewall
or proxy in front of the API (NoDetails). An empty body under any other
fallback stays bare: sniff's response.failed with no error still reads
"upstream stream failed" (TestNativeStreamFailureAccounting). Every
caller of APIError (passthrough, translated tries, routing, search,
decide, the built-in clients) says the same. edgeBlocked now also knows
Cloudflare's block pages ("Sorry, you have been blocked", "used
Cloudflare to restrict access", plain "error code: 1005-1012/1020"), and
APIError puts the page's title before BlockedHint. JSON errors read as
their message, as before; other markup (XML) still says nothing.

Siblings: planquota's vendorSaid and the gateway's HTTP error sites for
drawing, embeddings, video and WorkBuddy's config said a bare status or
dumped raw HTML; they use provider.Unsaid (empty or page) now, through
errorSaid in draw.go, and vendorMessage names a page by its title.
notAnAPIReply's webPage and codexSaidNothing kept their own title regex;
both read provider.PageTitle now.

Routing effect: a 4xx Cloudflare block page now counts as EdgeBlocked,
so retryable() lets a 400/405 one fail over as Alibaba's does (a 403 was
retryable already).

Tests: TestAPIErrorUnsaid (Cloudflare WAF page, plain-text 1020, nginx
page with markup and an entity in its title, a 200-rune title cut,
empty and whitespace bodies under "403 Forbidden", "Forbidden" and
"502", nil under a non-status fallback left bare, JSON unchanged,
vendorSaid);
TestRelayRefusalSaysWhatItWas (a custom Responses provider answering 403
with each through /v1/responses; message has no markup);
TestAPIErrorShapes updated for the page case.

Broken by hand: the page branch and the NoDetails line in apiError off:
TestAPIErrorShapes and TestAPIErrorUnsaid red ("403 Forbidden"), and
TestRelayRefusalSaysWhatItWas red in cloudflare, page and empty
("Relay: 403 Forbidden"). Restored, green.

Earlier, the Cloudflare words out of edgeBlocked turned TestAPIErrorUnsaid
red too.

Run (worktree, go1.26.8, rebased on origin/main 6afbe3f30): at this
commit, TestAPIError*, TestRelayRefusalSaysWhatItWas,
TestNativeStreamFailureAccounting, TestEdgeBlocked* and the draw,
embeddings and video tests ok; at the pushed head (this plus the
as-sent commit, which touches neither file nor test) go test
internal/gateway, whole package, -timeout 45m: ok (464s); internal/provider whole package
crashes in TestUnreadLoginsWriteErrorsKeepCredentials ("close of synctest
channel from outside bubble"), alone too, the open red on main #3632, not
touched here; the rest with it skipped: ok (99s). gofmt -l clean; go vet
gateway+provider darwin/linux/windows clean; go build . darwin and
GOOS=windows, GOOS=windows ./internal/..., GOOS=linux gateway+provider
(GOOS=linux of the app stops in wails' cgo files, as on main).
Not run: the full ./... suite (machine load ~30-60, other sessions'
suites). Not tried: maralica's real relay.
2026-10-27 03:30:57 +08:00

110 lines
4.1 KiB
Go

package gateway
import (
"bufio"
"bytes"
"encoding/json"
"io"
"net/http"
"regexp"
"strings"
"github.com/yetone/magpie/internal/provider"
)
// notAnAPIReply turns a 2xx reply that can't be a model API's answer into
// the 502 it stands for: a web page (a sign-in page, Cloudflare's
// challenge, a relay's own error page, served 200 text/html), a body that
// is empty, or one sent as JSON that doesn't begin as JSON. Each was taken
// for an answer: relayed to the agent as it came, logged as served with
// nothing in or out, the group's next member never asked — Codex was
// handed a text/html page from a relay and failed with "stream closed
// before response.completed" (#1012). Read as a 502, it is a failure like
// any other before the reply begins: the next key, account or member is
// asked, the try rests as a 502 does, and the log says why. Only the
// reply's first bytes are looked at, which a stream waits for anyway; a
// read that fails is left to the reader, as it was. name prefixes the
// reason, for a caller that doesn't put the provider's name before it.
func notAnAPIReply(res *http.Response, name string) *http.Response {
if res == nil || res.StatusCode < 200 || res.StatusCode >= 300 || res.StatusCode == http.StatusNoContent || res.Body == nil {
return res
}
ct := strings.ToLower(res.Header.Get("Content-Type"))
if strings.HasPrefix(ct, "text/html") {
return asBadGateway(res, name, webPage(res, ct))
}
br := bufio.NewReaderSize(res.Body, 4<<10)
res.Body = readCloser{br, res.Body}
if _, err := br.Peek(1); err == io.EOF {
return asBadGateway(res, name, "answered "+res.Status+" with nothing in it, not an API reply")
} else if err != nil {
return res
}
if ce := res.Header.Get("Content-Encoding"); ce != "" && ce != "identity" {
return res // compressed: its first bytes say nothing of what it is
}
head, _ := br.Peek(br.Buffered())
head = bytes.TrimLeft(head, " \t\r\n\ufeff")
switch {
case htmlStart.Match(head) && !strings.Contains(ct, "xml"):
return asBadGateway(res, name, webPage(res, ct))
case strings.Contains(ct, "json") && len(head) > 0 && head[0] != '{' && head[0] != '[':
b, _ := io.ReadAll(io.LimitReader(res.Body, 1<<10))
return asBadGateway(res, name, "answered "+res.Status+" with a reply that isn't JSON, not an API reply: "+clipRunes(string(bytes.TrimSpace(b)), 200))
}
return res
}
// htmlStart is how a web page begins.
var htmlStart = regexp.MustCompile(`(?i)^<(!doctype\s+html|html[\s>]|head[\s>]|body[\s>])`)
// webPage says what a page served in place of a reply was, by its title,
// and for a firewall's block page what to do about it.
func webPage(res *http.Response, ct string) string {
b, _ := io.ReadAll(io.LimitReader(res.Body, 64<<10))
if ct == "" {
ct = "no Content-Type"
}
why := "answered " + res.Status + " with a web page (" + strings.TrimSpace(strings.SplitN(ct, ";", 2)[0]) + "), not an API reply"
if t := provider.PageTitle(b); t != "" {
why += ": “" + t + "”"
}
if provider.EdgeBlocked(b) {
why += " — " + provider.BlockedHint
}
return why
}
// asBadGateway is res as the 502 it stands for, saying why in an error
// body every reader of one finds its message in.
func asBadGateway(res *http.Response, name, why string) *http.Response {
io.Copy(io.Discard, io.LimitReader(res.Body, 1<<20))
res.Body.Close()
msg := name + why
b, _ := json.Marshal(map[string]any{"error": map[string]any{"message": msg, "type": "bad_gateway"}, "message": msg})
h := res.Header.Clone()
for _, k := range []string{"Content-Type", "Content-Length", "Content-Encoding", "Transfer-Encoding"} {
h.Del(k)
}
h.Set("Content-Type", "application/json")
out := *res
out.StatusCode, out.Status = http.StatusBadGateway, "502 Bad Gateway"
out.Header, out.Body, out.ContentLength = h, io.NopCloser(bytes.NewReader(b)), int64(len(b))
return &out
}
// readCloser reads through a buffer in front of a body, and closes the
// body.
type readCloser struct {
io.Reader
io.Closer
}
// clipRunes is s cut to at most n runes.
func clipRunes(s string, n int) string {
if r := []rune(s); len(r) > n {
return string(r[:n]) + "…"
}
return s
}