* fix(httpclient): bound response-header waits and retry stalled reads on a new connection The maintainer-city shadow run saw 22 requests sit out the full 60s client timeout, each on one silent HTTP/1.1 connection while other connections to the same serve kept answering. wire.Client now bounds an idempotent request's wait for response headers (15s default; BEADS_HTTP_RESPONSE_HEADER_TIMEOUT or DialOptions.ResponseHeaderTimeout; "off" disables), separately from the 60s overall timeout, and stops the timer once headers arrive so a streaming body is never cut. A read (GET/HEAD/OPTIONS, or a Request marked Idempotent: the POST batch get) that stalls or has its connection reset is retried once: the stalled attempt's cancellation closes its connection and idle connections are dropped, so the retry dials fresh. Every retry is counted (wire.StallRetryCount) and reported (OnStallRetry; the dialer's default logs one stderr line with the count). Writes are never retried and get no header timer, because bd serve answers a write only after it commits (a large batch apply can legitimately take tens of seconds). A write whose overall timeout fires before its headers fails with a typed *wire.ResponseHeaderTimeoutError (inside *ConnectError) naming the host and saying the outcome is unknown. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(httpclient): retry a stalled read within the overall timeout (bd-p1wzpi) Adoption review of #7553 found three defects in the header timer and its retry. This maintainer fixup sits on top of the contributor commit and supersedes three of its claims: that the timer bounds a read's every attempt, that idle connections are dropped before the retry, and that any write whose overall timeout fires before its headers is typed. A slow but healthy read is no longer cut short. The 15s timer cannot tell a silent connection from a serve still working on the read (serve writes a read's headers only after waiting up to 10s for a database slot and running the query), and the retry ran under a fresh 15s timer, so a read slower than 15s failed at about 30s after sending two requests where it used to succeed within 60s. The timer now bounds only the first attempt. The retry has no header timer and runs under a deadline of when the first attempt was sent plus the client's overall Timeout, the moment that Timeout itself counts from, so it finishes such a read and no read waits longer than the 60s it could before. The request is built and stamped once and each attempt sends a copy of it, so the credential source is consulted once, before any clock starts, and a cold token command costs the retry none of its budget. What is left: a read whose headers take longer than the timer, and whose retry then needs more than what remains of the 60s (about 45s) for its headers and body together, now fails at 60s where it used to succeed, and the server also gets the abandoned first request. A read whose first attempt already spent the whole Timeout (the timer off) is not retried at all and keeps its typed timeout. A request is typed *ResponseHeaderTimeoutError only once it was written. Any Timeout() error on a write used to be typed, including the baseline transport's dial and TLS handshake timeouts where nothing reached the server, and the message then said the write "may or may not have been applied", gave the overall timeout as the wait, dropped the transport's error, and Temporary() was true. The timer is now armed from httptrace's WroteRequest (where http.Transport.ResponseHeaderTimeout starts its own clock), which also records that the request went out. A timeout is typed only for a written request whose caller's context is still alive; a dial or TLS timeout stays a plain *ConnectError. After is the measured wait, Err is printed, Temporary() reports Replayable (false for a write), and a retried read says why its first attempt was abandoned (Reason). Arming at the write also stops a slow credential source (BEADS_HTTP_TOKEN_COMMAND may take 30s) from being reported, counted and retried as a server stall. No idle-connection flush. CloseIdleConnections ran on a transport shared by every no-CA dial in the process (baselineTransport), so one stalled read dropped idle keep-alives to every host. Canceling the stalled attempt already closes its connection (net/http never pools a canceled HTTP/1.1 connection), so the retry rides another one. Also: - wire.Request.Replayable (GET/HEAD/OPTIONS, or Idempotent) is now the one predicate behind both the wire's stall retry and dispatch's bounded 503 retry, so the batch get, a read on POST, is retried on a 503 too. dispatch's doc comment no longer says the wire never resends. - The docs, the error and the stall line say the retry goes out on "another connection", not a "new" one: the idle pool may hand it one already open. dialStream's doc says the events:watch connect gets neither the timer nor the retry. - BEADS_HTTP_RESPONSE_HEADER_TIMEOUT takes bare seconds ("30") as BEADS_GATE_WAIT_TIMEOUT does, and "off" in any case. "off" or 0 turns off only the timer: a reset connection is still retried and a written request that times out is still typed. - README says "each read" and spells out the above, bounding the retry by its headers and body together; it no longer says a streaming body is never cut off (the header timer never does, the 60s bound still does). The CHANGELOG entry moves from Added to Fixed and states the same bound. - CredentialProvider's doc, in wire and on the public bdhttp alias, says Authorize runs once per request, not once per attempt: the stall retry resends the stamped headers up to the overall timeout later, so a single-use or short-lived credential may draw a 401 there, which reaches Refresh like any other. Tests: a read queued behind a LimitListener backlog finishes once a slot frees; a read slower than the timer on every connection finishes on its retry; a slow credential source is not a stall, and one that takes the whole Timeout to resolve still leaves the retry its budget (starting the deadline before the stamp, or re-stamping the retry, fails it); a write whose dial times out is a plain *ConnectError; a stall leaves another server's idle connection on a shared transport alone; a retry after a reset names the reset; the stall-twice case is bounded by the overall timeout and pins After, Reason and the message; dispatch retries a read on POST on a 503, and GetMany's batch get is sent as one (dropping its Idempotent fails that); the env knob takes "30", " 1.5 " and "OFF" and refuses "-3". A read whose first attempt spent the whole Timeout is not retried and keeps its typed error (dropping the spent-budget check fails it; no other test did). A stall retry that draws a 401 refreshes once and authorizes only the re-issued request, so Authorize runs twice, not three times (re-stamping the retry fails it). Not covered, as before, and now said in README and the CHANGELOG: the events:watch stream's connect (dialStream) has no header timer or retry. Nor is a reset on Windows: stallReason matches syscall.ECONNRESET, which a Windows reset (WSAECONNRESET) is not, so there a reset connection is retried only when it surfaces as EOF. Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Julian Knutsen Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Eddie the Engineer <adopt-pr@gascity.com>
178 lines
7.3 KiB
Go
178 lines
7.3 KiB
Go
// Contributed by gascity from bd-enterprise (internal/enterprise/httpstore/batchgetter.go@49d1df2f6)
|
|
// to OSS beads under the MIT license.
|
|
package httpclient
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"net/http"
|
|
|
|
"github.com/steveyegge/beads/internal/httpapi/apigen"
|
|
"github.com/steveyegge/beads/internal/httpclient/wire"
|
|
"github.com/steveyegge/beads/issueops"
|
|
)
|
|
|
|
// httpBatchGetter serves batchGetIssues (POST /v0/beads/issues:batchGet) —
|
|
// the role behind gc's ready veto and the CLI's own id-resolution passes,
|
|
// once they move off one Get per id.
|
|
//
|
|
// IT IS A READ, DIALED AS A POST: the request carries an `ids` array no GET
|
|
// query string can hold cleanly at the operation's own cap (MaxGetManyIDs),
|
|
// the same reason queryIssues dials POST rather than GET. Nothing about that
|
|
// changes the role's nature — it writes nothing, takes no actor and no
|
|
// version guard — so this goes through dispatch directly, the way Counter
|
|
// and Querier do, rather than through roleWire: there is no write envelope
|
|
// here for a WriteWire method to carry.
|
|
//
|
|
// THE CAP AND THE BLANK-ID CHECK ARE DONE HERE, BEFORE THE DIAL, and that is
|
|
// a deliberate divergence from how every other validation on this surface
|
|
// works: everywhere else, the role's own ErrValidation reaches the wire
|
|
// through the server's failure translation and this client decodes it back.
|
|
// batch_get.go's failBatchGetErr does not do that — it collapses EVERY
|
|
// validation failure, the cap included, into one generic
|
|
// InvalidArgument/invalid_value problem with no distinguishing code, so a
|
|
// server round trip can never hand this client the exact
|
|
// *issueops.TooManyIDsError{Requested, Cap} the role's own contract and the
|
|
// conformance suite's errors.As checks require. checkGetManyIDs reproduces
|
|
// internal/storage/issueops.ValidateGetManyRequest's exact two checks, in
|
|
// its exact order (the cap, counted before deduplication; then the first
|
|
// blank entry) — not by importing that package, which is the storage
|
|
// engine's shared body and does not belong in a transport client, but by
|
|
// restating its two rules against the same public issueops types the role
|
|
// itself is spelled in.
|
|
type httpBatchGetter struct{ store *Store }
|
|
|
|
var _ issueops.BatchGetter = (*httpBatchGetter)(nil)
|
|
|
|
// GetMany dials POST /v0/beads/issues:batchGet.
|
|
//
|
|
// The ids are sent VERBATIM — not trimmed, not deduplicated, not reordered —
|
|
// checkDeleteIDs' sibling reason: the wire's own `ids` member document says
|
|
// duplicates collapse and the answer comes back in first-mention order,
|
|
// which is exactly the normalization ValidateGetManyRequest's callers
|
|
// (ExecuteGetMany, via DedupeGetManyIDs and FinishGetMany) apply server-side.
|
|
// Redoing it here would be a second implementation of a rule that already
|
|
// has one, on the operation where a disagreement about which id was "first"
|
|
// would reorder the answer rather than merely duplicate work.
|
|
func (g *httpBatchGetter) GetMany(ctx context.Context, req issueops.GetManyRequest) (issueops.GetManyResult, error) {
|
|
if err := checkGetManyIDs(req.IDs); err != nil {
|
|
return issueops.GetManyResult{}, err
|
|
}
|
|
if len(req.IDs) == 0 {
|
|
// Answered locally rather than dialed: an empty request is legal and
|
|
// the role promises an empty, non-nil answer, so there is nothing a
|
|
// round trip could add — the same early return ExecuteGetMany itself
|
|
// takes after deduplication.
|
|
return issueops.GetManyResult{Issues: []*issueops.Issue{}, Missing: []string{}}, nil
|
|
}
|
|
|
|
token, _ := wire.CapabilityFor(wire.OpBatchGetIssues)
|
|
served, err := g.store.servesCapability(ctx, token)
|
|
if err != nil {
|
|
return issueops.GetManyResult{}, err
|
|
}
|
|
if !served {
|
|
return g.getOneAtATime(ctx, req.IDs)
|
|
}
|
|
|
|
var body apigen.BatchGetIssuesResult
|
|
if err := g.store.dispatch(ctx, wire.Request{
|
|
Op: wire.OpBatchGetIssues,
|
|
Method: http.MethodPost,
|
|
Path: wire.PathIssuesBatchGet,
|
|
Body: apigen.BatchGetIssuesRequest{
|
|
Ids: append([]string(nil), req.IDs...),
|
|
},
|
|
// A read on POST: safe to replay after a stall or a 503, as a GET is.
|
|
Idempotent: true,
|
|
}, &body); err != nil {
|
|
return issueops.GetManyResult{}, err
|
|
}
|
|
|
|
issues := make([]*issueops.Issue, 0, len(body.Issues))
|
|
for i := range body.Issues {
|
|
entry := body.Issues[i]
|
|
// BatchGetIssue.Revision is this operation's only wire spelling of the
|
|
// row's token — Issue.RowVersion is json:"-", the same stitch
|
|
// getIssuesByExactID and role_reader.go's getIssue make for their own
|
|
// responses. Without it, every resolved issue would carry a RowVersion
|
|
// of 0, and a caller that fed one into a guarded write would get a
|
|
// spurious precondition_failed instead of none.
|
|
version, err := parseRevision("BatchGetter.GetMany", entry.Revision)
|
|
if err != nil {
|
|
return issueops.GetManyResult{}, err
|
|
}
|
|
issue := entry.Issue
|
|
issue.RowVersion = version
|
|
issues = append(issues, &issue)
|
|
}
|
|
|
|
missing := make([]string, len(body.Missing))
|
|
copy(missing, body.Missing)
|
|
|
|
return issueops.GetManyResult{
|
|
Issues: issues,
|
|
Missing: missing,
|
|
}, nil
|
|
}
|
|
|
|
// checkGetManyIDs applies the request-intrinsic refusals before the dial,
|
|
// in the SAME ORDER internal/storage/issueops.ValidateGetManyRequest applies
|
|
// them server-side (batch_get.go's batchGetRequest comment says so
|
|
// explicitly): the cap first, counted on the request as sent, before any
|
|
// deduplication; then the first blank entry.
|
|
//
|
|
// The blank check is a LITERAL id == "", not a trimmed one: GetManyRequest.IDs
|
|
// are exact ids, and DedupeGetManyIDs' own doc says this role does not trim
|
|
// whitespace the way DeleteRequest.IDs does, because a caller that padded an
|
|
// id is naming a genuinely different, unresolvable id rather than making a
|
|
// typo this role should forgive. checkDeleteIDs' TrimSpace check does not
|
|
// apply here for that reason.
|
|
func checkGetManyIDs(ids []string) error {
|
|
if len(ids) > issueops.MaxGetManyIDs {
|
|
return &issueops.TooManyIDsError{Requested: len(ids), Cap: issueops.MaxGetManyIDs}
|
|
}
|
|
for i, id := range ids {
|
|
if id == "" {
|
|
return fmt.Errorf("%w: get many id at position %d is empty", issueops.ErrValidation, i)
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// getOneAtATime answers a GetMany against a server that does not advertise
|
|
// issues.batchGet with one getIssue per distinct id, in first-mention order —
|
|
// the same rows and the same Missing a batch would answer, without its single
|
|
// snapshot. It is a transport fallback for a capability, kept here so no
|
|
// caller of the role has to know which servers publish the batch.
|
|
func (g *httpBatchGetter) getOneAtATime(ctx context.Context, ids []string) (issueops.GetManyResult, error) {
|
|
reader, err := g.store.IssueReader()
|
|
if err != nil {
|
|
return issueops.GetManyResult{}, err
|
|
}
|
|
out := issueops.GetManyResult{Issues: []*issueops.Issue{}, Missing: []string{}}
|
|
seen := make(map[string]bool, len(ids))
|
|
for _, id := range ids {
|
|
if seen[id] {
|
|
continue
|
|
}
|
|
seen[id] = true
|
|
details, err := reader.Get(ctx, issueops.GetRequest{ID: id})
|
|
if errors.Is(err, issueops.ErrNotFound) {
|
|
out.Missing = append(out.Missing, id)
|
|
continue
|
|
}
|
|
if err != nil {
|
|
return issueops.GetManyResult{}, err
|
|
}
|
|
issue := details.Issue
|
|
if len(issue.Labels) == 0 && len(details.Labels) > 0 {
|
|
issue.Labels = append([]string(nil), details.Labels...)
|
|
}
|
|
// Hydration is labels only, as the batch's is.
|
|
issue.Dependencies, issue.Comments = nil, nil
|
|
out.Issues = append(out.Issues, &issue)
|
|
}
|
|
return out, nil
|
|
}
|